问:
Somthing wrong with my python implementation of phong shading with only numpy and PIL
Recently, I tried to implement Phong shading with only NumPy and PIL using python. But there is some black-and-white noise in the rendered image. Can you point out what I should do to improve my code to fix the issue?

The resulting image is as follows:

The mesh model could be downloaded from https://github.com/google/nerfactor/blob/main/third_party/xiuminglib/data/models/teapot.obj.

You could try the code below by yourself.

```<code>import random

import numpy as np
import trimesh
from meshio import load_obj
from PIL import Image

def phong_shading(light_direction, view_direction, normal, material):
    # Calculate the ambient color
    ambient_color = material.ambient_color

    # Calculate the diffuse color
    diffuse_coefficient = max(np.dot(normal, light_direction), 0)
    diffuse_color = diffuse_coefficient * material.diffuse_color

    # Calculate the specular color
    halfway_direction = normalize(light_direction + view_direction)
    specular_coefficient = max(np.dot(normal, halfway_direction), 0)
    specular_coefficient = specular_coefficient ** material.shininess
    specular_color = specular_coefficient * material.specular_color

    # Combine the ambient, diffuse and specular colors
    final_color = specular_color + diffuse_color + ambient_color
    return final_color

def normalize(v, axis=-1, epsilon=1e-12):
    square_sum = np.sum(np.square(v), axis, keepdims=True)
    v_inv_norm = 1. / np.sqrt(np.maximum(square_sum, epsilon))
    return v * v_inv_norm

def rasterize_triangle(vertices):
    # calculate the bounding box of the triangle
    min_x = int(min(vertices[:, 0]))
    max_x = int(max(vertices[:, 0])) + 1
    min_y = int(min(vertices[:, 1]))
    max_y = int(max(vertices[:, 1])) + 1

    for x in range(min_x, max_x):
        for y in range(min_y, max_y):
            if point_in_triangle(vertices, x, y):
                yield (x, y)

def is_point_in_triangle(vertices, x, y):
    v0, v1, v2 = vertices
    A = 1/2 * (-v1[1]*v2[0] + v0[1]*(-v1[0] + v2[0]) +
               v0[0]*(v1[1] - v2[1]) + v1[0]*v2[1])
    s = v0[1]*v2[0] - v0[0]*v2[1] + (v2[1] - v0[1])*x + (v0[0] - v2[0])*y
    t = v0[0]*v1[1] - v0[1]*v1[0] + (v0[1] - v1[1])*x + (v1[0] - v0[0])*y
    return 0 <= s and s <= A and 0 <= t and t <= A and (s + t) <= A

def point_in_triangle(vertices, x, y):
    # x, y = point
    v0, v1, v2 = vertices
    x1, y1, x2, y2, x3, y3 = v0[0], v0[1], v1[0], v1[1], v2[0], v2[1]

    # Compute barycentric coordinates
    denom = (y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3)
    l1 = ((y2 - y3) * (x - x3) + (x3 - x2) * (y - y3)) / denom
    l2 = ((y3 - y1) * (x - x3) + (x1 - x3) * (y - y3)) / denom
    l3 = 1 - l1 - l2

    # Check if point is inside the triangle
    return 0 <= l1 <= 1 and 0 <= l2 <= 1 and 0 <= l3 <= 1

def world_to_camera_coordinates(vertices, camera_position):
    ''' convert from world coordinate to camera_coordinate.

    this function has the assumption that the camera is looking at the origin.
    and the y axis of the camera is pointing down to the ground.

    Args:
        vertices (np.array): the vertices of the mesh in world coordinate.

    Returns:
        the vertices in camera coordinate.
    '''
    camera_z_axis = -normalize(camera_position)  # (3,)
    world_z_axis = np.array([0, 0, 1])
    project_y_on_z = -(-world_z_axis @ camera_z_axis.T) * camera_z_axis
    camera_y_axis = project_y_on_z - world_z_axis  # (3,)
    camera_x_axis = np.cross(camera_y_axis, camera_z_axis)  # (3,)
    camera_matrix = np.stack([camera_x_axis, camera_y_axis, camera_z_axis])
    return (camera_matrix @ (vertices - camera_position).T).T

def camera_to_screen_coordinates(vertices, width, height, fov, near_clip, far_clip):
    aspect_ratio = width / height
    # Create the perspective projection matrix
    projection_matrix = perspective(fov, aspect_ratio, near_clip, far_clip)

    # create a matrix to store the transformed vertices
    transformed_vertices = np.ones((len(vertices), 4))
    transformed_vertices[:, :3] = vertices

    # multiply each vertex by the projection matrix
    transformed_vertices = np.matmul(transformed_vertices, projection_matrix.T)

    # Convert from homogeneous coordinates to screen coordinates
    transformed_vertices[:, 0] = (
        transformed_vertices[:, 0] / transformed_vertices[:, 3]) * (width / 2) + (width / 2)
    transformed_vertices[:, 1] = (
        transformed_vertices[:, 1] / transformed_vertices[:, 3]) * (height / 2) + (height / 2)

    return transformed_vertices[:, :2]

def perspective(fov, aspect_ratio, near_clip, far_clip):
    fov = np.radians(fov)
    t = np.tan(fov / 2) * near_clip
    b = -t
    r = t * aspect_ratio
    l = -r

    projection_matrix = np.array(
        [
            [(2 * near_clip) / (r - l), 0, (r + l) / (r - l), 0],
            [0, (2 * near_clip) / (t - b), (t + b) / (t - b), 0],
            [0, 0, -(far_clip + near_clip) / (far_clip - near_clip),
             -(2 * far_clip * near_clip) / (far_clip - near_clip)],
            [0, 0, -1, 0]
        ]
    )
    return projection_matrix

def transform_to_screen_space(vertices, camera_position, img_width, img_height):
    assert img_width == img_height, 'The image must be square'

    # Transform the vertices to camera space
    camera_vertices = world_to_camera_coordinates(vertices, camera_position)

    # Transform the vertices to perspective space
    fov = 45
    focal = img_width / (2 * np.tan(np.radians(fov / 2)))
    screen_vertices = camera_vertices / camera_vertices[:, 2].reshape(-1, 1)
    screen_vertices[:, :2] = screen_vertices[:, :2] * focal + img_height / 2

    return screen_vertices, camera_vertices

def area_triangle(v1, v2, v3):
    ''' compute the area of a triangle.
    '''
    return 0.5 * np.linalg.norm(np.cross(v2 - v1, v3 - v1))

def compute_vertices_normals(vertices, faces):
    ''' compute the normal vector for each vertex.

    Args:
        vertices (np.array): the vertices of the mesh in world coordinate.
        faces

    '''
    # method with trimesh
    # '''
    mesh = trimesh.Trimesh(vertices=vertices, faces=faces, processed=False)
    vertices_normals = normalize(mesh.vertex_normals, epsilon=1e-160)
    # '''

    # method with numpy
    '''
    vertices_normals = np.zeros_like(vertices).astype(np.float128)

    v1 = vertices[faces][:, 0]
    v2 = vertices[faces][:, 1]
    v3 = vertices[faces][:, 2]

    normal_before_normalization = np.cross(v2 - v1, v3 - v1)
    per_face_area = 0.5 * np.linalg.norm(
        normal_before_normalization, axis=-1, keepdims=True
    )
    per_face_area_enlarged = per_face_area * \
        per_face_area.shape[0] / per_face_area.sum()
    per_face_normal = normalize(normal_before_normalization, epsilon=1e-160)

    weighted_normal = per_face_normal * per_face_area_enlarged
    weighted_normal_boardcast = np.reshape(
        np.repeat(np.expand_dims(weighted_normal, 1), 3, axis=1), (-1, 3)
    )
    np.add.at(vertices_normals, faces.ravel(), weighted_normal_boardcast)
    vertices_normals = normalize(vertices_normals, epsilon=1e-160)
    '''

    return vertices_normals

def barycentric_coords(triangle_vertices, x, y):
    x1, y1, z1 = triangle_vertices[0]
    x2, y2, z2 = triangle_vertices[1]
    x3, y3, z3 = triangle_vertices[2]
    # calculate barycentric coordinates
    lambda1 = ((y2 - y3)*(x - x3) + (x3 - x2)*(y - y3)) / \
        ((y2 - y3)*(x1 - x3) + (x3 - x2)*(y1 - y3))
    lambda2 = ((y3 - y1)*(x - x3) + (x1 - x3)*(y - y3)) / \
        ((y2 - y3)*(x1 - x3) + (x3 - x2)*(y1 - y3))
    lambda3 = 1 - lambda1 - lambda2
    return np.array([lambda1, lambda2, lambda3]).reshape(-1, 1)

def render_phong(vertices, faces, camera_position, light_position, width, height, material):
    # compute the normal vector for each vertex
    vertices_normals = compute_vertices_normals(vertices, faces)

    # Transform the vertices to screen space
    transformed_vertices, camera_vertices = transform_to_screen_space(
        vertices, camera_position, width, height)

    # Create an empty image
    img = Image.new('RGB', (width, height), (0, 0, 0))
    pixels = img.load()
    pixel_depth = np.ones((width, height)) * np.inf

    for face in faces:
        v1 = transformed_vertices[face[0]]
        v2 = transformed_vertices[face[1]]
        v3 = transformed_vertices[face[2]]
        if area_triangle(v1, v2, v3) == 0:
            continue
        # calculate the normal vector for the face
        normal = vertices_normals[face]

        # calculate the light and view direction vectors for each vertex
        light_direction = normalize(light_position - vertices[face])
        view_direction = normalize(camera_position - vertices[face])

        # Rasterize the triangle
        for x, y in rasterize_triangle(transformed_vertices[face]):
            for i in range(20):
                tubx = random.uniform(0, 1.0) + x
                tuby = random.uniform(0, 1.0) + y
                # calculate the barycentric coordinates of the pixel
                barycentric = barycentric_coords(
                    transformed_vertices[face], tubx, tuby)
                if np.min(barycentric) < 0:  # Check if pixel is outside of the triangle
                    continue

                # Interpolate the vertex attributes to get per-pixel attributes
                interpolated_normal = (barycentric * normal).sum(axis=0)
                interpolated_light_direction = (
                    barycentric * light_direction
                ).sum(axis=0)
                interpolated_view_direction = (
                    barycentric * view_direction
                ).sum(axis=0)
                interpolated_camera_vertices = (
                    barycentric * camera_vertices[face]).sum(axis=0)

                # Calculate the color of the pixel
                color = phong_shading(interpolated_light_direction,
                                      interpolated_view_direction, interpolated_normal, material)
                if x >= 0 and x < width and y >= 0 and y < height:
                    oldr, oldg, oldb = pixels[x, y]
                    newr, newg, newb = (np.clip(color, 0, 1)
                                        * 255).astype(np.uint8)
                    # newr = newr if newr > oldr else oldr
                    # newg = newg if newg > oldg else oldg
                    # newb = newb if newb > oldb else oldb
                    depth = interpolated_camera_vertices[2]
                    if depth < pixel_depth[x, y]:
                        # print(depth, pixel_depth[x, y])
                        pixel_depth[x, y] = depth
                        pixels[x, y] = (newr, newg, newb)
                        # if x < 453 and x > 415 and y > 255 and y < 265:
                        #     img.save(f"debug/f_{face}_x_{x}_y_{y}_d_{depth}.jpg")

    return img

class PhongShader():
    def __init__(self, light_position, camera_position, image_width=512, image_height=512):
        # assert the camera position is not along z axis.

        self.light_position = light_position
        self.camera_position = camera_position
        self.image_width = image_width
        self.image_height = image_height

    def render(self, vertices, faces, material):
        return render_phong(vertices, faces, self.camera_position, self.light_position, self.image_width, self.image_height, material)

class Material():
    def __init__(self) -> None:
        self.ambient_color = np.array([0.1, 0.1, 0.1])
        self.diffuse_color = np.array([1., 0.0, 0.5])
        self.specular_color = np.array([0.5, 0.5, 0.5])
        self.shininess = 50

def main():
    # load the mesh
    mesh = trimesh.load('teapot.obj')
    vertices, faces = mesh.vertices, mesh.faces

    # create a shader
    shader = PhongShader(light_position=np.array(
        [8, 0, 0]), camera_position=np.array([8, 0, 0]))

    # render the image
    material = Material()
    img = shader.render(vertices, faces, material)
    img.save("output.jpg")

if __name__ == '__main__':
    main()
</code>```

The possible reason could be discreazation in coding. But I am not sure how to fix it.

Body:
Recently, I tried to implement Phong shading with only NumPy and PIL using python. But there is some black-and-white noise in the rendered image. Can you point out what I should do to improve my code to fix the issue?

The resulting image is as follows:

The mesh model could be downloaded from https://github.com/google/nerfactor/blob/main/third_party/xiuminglib/data/models/teapot.obj.

You could try the code below by yourself.

import random

import numpy as np
import trimesh
from meshio import load_obj
from PIL import Image

def phong_shading(light_direction, view_direction, normal, material):
    # Calculate the ambient color
    ambient_color = material.ambient_color

    # Calculate the diffuse color
    diffuse_coefficient = max(np.dot(normal, light_direction), 0)
    diffuse_color = diffuse_coefficient * material.diffuse_color

    # Calculate the specular color
    halfway_direction = normalize(light_direction + view_direction)
    specular_coefficient = max(np.dot(normal, halfway_direction), 0)
    specular_coefficient = specular_coefficient ** material.shininess
    specular_color = specular_coefficient * material.specular_color

    # Combine the ambient, diffuse and specular colors
    final_color = specular_color + diffuse_color + ambient_color
    return final_color

def normalize(v, axis=-1, epsilon=1e-12):
    square_sum = np.sum(np.square(v), axis, keepdims=True)
    v_inv_norm = 1. / np.sqrt(np.maximum(square_sum, epsilon))
    return v * v_inv_norm

def rasterize_triangle(vertices):
    # calculate the bounding box of the triangle
    min_x = int(min(vertices[:, 0]))
    max_x = int(max(vertices[:, 0])) + 1
    min_y = int(min(vertices[:, 1]))
    max_y = int(max(vertices[:, 1])) + 1

    for x in range(min_x, max_x):
        for y in range(min_y, max_y):
            if point_in_triangle(vertices, x, y):
                yield (x, y)

def is_point_in_triangle(vertices, x, y):
    v0, v1, v2 = vertices
    A = 1/2 * (-v1[1]*v2[0] + v0[1]*(-v1[0] + v2[0]) +
               v0[0]*(v1[1] - v2[1]) + v1[0]*v2[1])
    s = v0[1]*v2[0] - v0[0]*v2[1] + (v2[1] - v0[1])*x + (v0[0] - v2[0])*y
    t = v0[0]*v1[1] - v0[1]*v1[0] + (v0[1] - v1[1])*x + (v1[0] - v0[0])*y
    return 0 <= s and s <= A and 0 <= t and t <= A and (s + t) <= A

def point_in_triangle(vertices, x, y):
    # x, y = point
    v0, v1, v2 = vertices
    x1, y1, x2, y2, x3, y3 = v0[0], v0[1], v1[0], v1[1], v2[0], v2[1]

    # Compute barycentric coordinates
    denom = (y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3)
    l1 = ((y2 - y3) * (x - x3) + (x3 - x2) * (y - y3)) / denom
    l2 = ((y3 - y1) * (x - x3) + (x1 - x3) * (y - y3)) / denom
    l3 = 1 - l1 - l2

    # Check if point is inside the triangle
    return 0 <= l1 <= 1 and 0 <= l2 <= 1 and 0 <= l3 <= 1

def world_to_camera_coordinates(vertices, camera_position):
    ''' convert from world coordinate to camera_coordinate.

    this function has the assumption that the camera is looking at the origin.
    and the y axis of the camera is pointing down to the ground.

    Args:
        vertices (np.array): the vertices of the mesh in world coordinate.

    Returns:
        the vertices in camera coordinate.
    '''
    camera_z_axis = -normalize(camera_position)  # (3,)
    world_z_axis = np.array([0, 0, 1])
    project_y_on_z = -(-world_z_axis @ camera_z_axis.T) * camera_z_axis
    camera_y_axis = project_y_on_z - world_z_axis  # (3,)
    camera_x_axis = np.cross(camera_y_axis, camera_z_axis)  # (3,)
    camera_matrix = np.stack([camera_x_axis, camera_y_axis, camera_z_axis])
    return (camera_matrix @ (vertices - camera_position).T).T

def camera_to_screen_coordinates(vertices, width, height, fov, near_clip, far_clip):
    aspect_ratio = width / height
    # Create the perspective projection matrix
    projection_matrix = perspective(fov, aspect_ratio, near_clip, far_clip)

    # create a matrix to store the transformed vertices
    transformed_vertices = np.ones((len(vertices), 4))
    transformed_vertices[:, :3] = vertices

    # multiply each vertex by the projection matrix
    transformed_vertices = np.matmul(transformed_vertices, projection_matrix.T)

    # Convert from homogeneous coordinates to screen coordinates
    transformed_vertices[:, 0] = (
        transformed_vertices[:, 0] / transformed_vertices[:, 3]) * (width / 2) + (width / 2)
    transformed_vertices[:, 1] = (
        transformed_vertices[:, 1] / transformed_vertices[:, 3]) * (height / 2) + (height / 2)

    return transformed_vertices[:, :2]

def perspective(fov, aspect_ratio, near_clip, far_clip):
    fov = np.radians(fov)
    t = np.tan(fov / 2) * near_clip
    b = -t
    r = t * aspect_ratio
    l = -r

    projection_matrix = np.array(
        [
            [(2 * near_clip) / (r - l), 0, (r + l) / (r - l), 0],
            [0, (2 * near_clip) / (t - b), (t + b) / (t - b), 0],
            [0, 0, -(far_clip + near_clip) / (far_clip - near_clip),
             -(2 * far_clip * near_clip) / (far_clip - near_clip)],
            [0, 0, -1, 0]
        ]
    )
    return projection_matrix

def transform_to_screen_space(vertices, camera_position, img_width, img_height):
    assert img_width == img_height, 'The image must be square'

    # Transform the vertices to camera space
    camera_vertices = world_to_camera_coordinates(vertices, camera_position)

    # Transform the vertices to perspective space
    fov = 45
    focal = img_width / (2 * np.tan(np.radians(fov / 2)))
    screen_vertices = camera_vertices / camera_vertices[:, 2].reshape(-1, 1)
    screen_vertices[:, :2] = screen_vertices[:, :2] * focal + img_height / 2

    return screen_vertices, camera_vertices

def area_triangle(v1, v2, v3):
    ''' compute the area of a triangle.
    '''
    return 0.5 * np.linalg.norm(np.cross(v2 - v1, v3 - v1))

def compute_vertices_normals(vertices, faces):
    ''' compute the normal vector for each vertex.

    Args:
        vertices (np.array): the vertices of the mesh in world coordinate.
        faces

    '''
    # method with trimesh
    # '''
    mesh = trimesh.Trimesh(vertices=vertices, faces=faces, processed=False)
    vertices_normals = normalize(mesh.vertex_normals, epsilon=1e-160)
    # '''

    # method with numpy
    '''
    vertices_normals = np.zeros_like(vertices).astype(np.float128)

    v1 = vertices[faces][:, 0]
    v2 = vertices[faces][:, 1]
    v3 = vertices[faces][:, 2]

    normal_before_normalization = np.cross(v2 - v1, v3 - v1)
    per_face_area = 0.5 * np.linalg.norm(
        normal_before_normalization, axis=-1, keepdims=True
    )
    per_face_area_enlarged = per_face_area * \
        per_face_area.shape[0] / per_face_area.sum()
    per_face_normal = normalize(normal_before_normalization, epsilon=1e-160)

    weighted_normal = per_face_normal * per_face_area_enlarged
    weighted_normal_boardcast = np.reshape(
        np.repeat(np.expand_dims(weighted_normal, 1), 3, axis=1), (-1, 3)
    )
    np.add.at(vertices_normals, faces.ravel(), weighted_normal_boardcast)
    vertices_normals = normalize(vertices_normals, epsilon=1e-160)
    '''

    return vertices_normals

def barycentric_coords(triangle_vertices, x, y):
    x1, y1, z1 = triangle_vertices[0]
    x2, y2, z2 = triangle_vertices[1]
    x3, y3, z3 = triangle_vertices[2]
    # calculate barycentric coordinates
    lambda1 = ((y2 - y3)*(x - x3) + (x3 - x2)*(y - y3)) / \
        ((y2 - y3)*(x1 - x3) + (x3 - x2)*(y1 - y3))
    lambda2 = ((y3 - y1)*(x - x3) + (x1 - x3)*(y - y3)) / \
        ((y2 - y3)*(x1 - x3) + (x3 - x2)*(y1 - y3))
    lambda3 = 1 - lambda1 - lambda2
    return np.array([lambda1, lambda2, lambda3]).reshape(-1, 1)

def render_phong(vertices, faces, camera_position, light_position, width, height, material):
    # compute the normal vector for each vertex
    vertices_normals = compute_vertices_normals(vertices, faces)

    # Transform the vertices to screen space
    transformed_vertices, camera_vertices = transform_to_screen_space(
        vertices, camera_position, width, height)

    # Create an empty image
    img = Image.new('RGB', (width, height), (0, 0, 0))
    pixels = img.load()
    pixel_depth = np.ones((width, height)) * np.inf

    for face in faces:
        v1 = transformed_vertices[face[0]]
        v2 = transformed_vertices[face[1]]
        v3 = transformed_vertices[face[2]]
        if area_triangle(v1, v2, v3) == 0:
            continue
        # calculate the normal vector for the face
        normal = vertices_normals[face]

        # calculate the light and view direction vectors for each vertex
        light_direction = normalize(light_position - vertices[face])
        view_direction = normalize(camera_position - vertices[face])

        # Rasterize the triangle
        for x, y in rasterize_triangle(transformed_vertices[face]):
            for i in range(20):
                tubx = random.uniform(0, 1.0) + x
                tuby = random.uniform(0, 1.0) + y
                # calculate the barycentric coordinates of the pixel
                barycentric = barycentric_coords(
                    transformed_vertices[face], tubx, tuby)
                if np.min(barycentric) < 0:  # Check if pixel is outside of the triangle
                    continue

                # Interpolate the vertex attributes to get per-pixel attributes
                interpolated_normal = (barycentric * normal).sum(axis=0)
                interpolated_light_direction = (
                    barycentric * light_direction
                ).sum(axis=0)
                interpolated_view_direction = (
                    barycentric * view_direction
                ).sum(axis=0)
                interpolated_camera_vertices = (
                    barycentric * camera_vertices[face]).sum(axis=0)

                # Calculate the color of the pixel
                color = phong_shading(interpolated_light_direction,
                                      interpolated_view_direction, interpolated_normal, material)
                if x >= 0 and x < width and y >= 0 and y < height:
                    oldr, oldg, oldb = pixels[x, y]
                    newr, newg, newb = (np.clip(color, 0, 1)
                                        * 255).astype(np.uint8)
                    # newr = newr if newr > oldr else oldr
                    # newg = newg if newg > oldg else oldg
                    # newb = newb if newb > oldb else oldb
                    depth = interpolated_camera_vertices[2]
                    if depth < pixel_depth[x, y]:
                        # print(depth, pixel_depth[x, y])
                        pixel_depth[x, y] = depth
                        pixels[x, y] = (newr, newg, newb)
                        # if x < 453 and x > 415 and y > 255 and y < 265:
                        #     img.save(f"debug/f_{face}_x_{x}_y_{y}_d_{depth}.jpg")

    return img

class PhongShader():
    def __init__(self, light_position, camera_position, image_width=512, image_height=512):
        # assert the camera position is not along z axis.

        self.light_position = light_position
        self.camera_position = camera_position
        self.image_width = image_width
        self.image_height = image_height

    def render(self, vertices, faces, material):
        return render_phong(vertices, faces, self.camera_position, self.light_position, self.image_width, self.image_height, material)

class Material():
    def __init__(self) -> None:
        self.ambient_color = np.array([0.1, 0.1, 0.1])
        self.diffuse_color = np.array([1., 0.0, 0.5])
        self.specular_color = np.array([0.5, 0.5, 0.5])
        self.shininess = 50

def main():
    # load the mesh
    mesh = trimesh.load('teapot.obj')
    vertices, faces = mesh.vertices, mesh.faces

    # create a shader
    shader = PhongShader(light_position=np.array(
        [8, 0, 0]), camera_position=np.array([8, 0, 0]))

    # render the image
    material = Material()
    img = shader.render(vertices, faces, material)
    img.save("output.jpg")

if __name__ == '__main__':
    main()

The possible reason could be discreazation in coding. But I am not sure how to fix it.


来源: stackexchange

问:
" 'git rev-parse HEAD ' is not recognized" error when flutter doctor, but still works normally?
I've been trying to setup flutter on my laptop with Android studios dolphin (using Windows 11), but I've been running into some troubles with using flutter doctor and agreeing to the android licenses. Running the flutter doctor command produces the below error message, however it still runs normally :

I ignored it and tried to run the --android-licenses command as it suggested, but the below was returned :

'git rev-parse HEAD' is not recognized as an internal or external command, operable program or batch file'

'DIR /B /O:D "C:\Users\jerry\Downloads\flutter_windows_3.3.10-stable\flutter\packages\flutter_tools\pubspec.yaml" "C:\Users\jerry\Downloads\flutter_windows_3.3.10-stable\flutter\packages\flutter_tools\pubspec.lock"' is not recognized as an internal or external command'

The error in red says 'Android sdkmanager tool was found, but failed to run
(C:\Users\jerry\AppData\Local\Android\Sdk\cmdline-tools\latest\bin\sdkmanager.bat): "ProcessException: Cannot find file specified'.
Apologies for the Japanese.

Any ideas on how this could be? I can still access git through the cmd, and have added the bin and cmd paths to the PATH variable in the Environmental variables already.

I have another question posted regarding details about the issue with agreeing to the android licenses here :

'Android sdkmanager tool found, but failed to run' for flutter doctor --android-licenses

and I would be beyond grateful if someone could help me with that as well.

Solutions I've attempted :

Renaming the ComSpec from "%SystemRoot%\system32\cmd.exe;" to "C:\Windows\system32\cmd.exe" as suggested by this forum https://github.com/flutter/flutter/issues/30638

However the opposite is proposed by this thread : Flutter doctor script throws errors and then crashes which is what my ComSpec is set to now at the time of capturing this screenshot.

Checking my jdk - My JAVA_HOME is set to C:\Program Files\Java\jdk1.8.0_351

Added a FLUTTER_HOME variable, set to C:\Users\jerry\Downloads\flutter_windows_3.3.10-stable\flutter

ContentLicense: CC BY-SA 4.0


问:
R : does `predict` still center linear predictors of categorical variables?
Until then, to obtain the linear predictors of a Cox model via  predict, it was accepted that the linear predictors were centred.
When they were recalculated, the continuous and categorical variables were centered (see Linear predictor from predict.coxph from coefficients only and Coxph predictions don't match the coefficients).

But when I test this now it appears that only continuous variables are centered. To reuse the link example:

```<code>URL   <- "http://socserv.mcmaster.ca/jfox/Books/Companion/data/Rossi.txt"
Rossi <- read.table(URL, header=TRUE)
library(survival)

#for binary variable
fitCPH <- coxph(Surv(week, arrest) ~ fin, data=Rossi)    #Cox-PH model
(coefCPH <- coef(fitCPH))                              # estimated coefficients
head(predict(fitCPH,type="lp"))
head((as.numeric(as.factor((Rossi$fin))) - 1) - mean(as.numeric(as.factor(Rossi$fin)) - 1)    * coef(fitCPH)) #centered
head((as.numeric(as.factor((Rossi$fin))) - 1)    * coef(fitCPH)) #non-centered
</code>```

Can someone confirm the information and the reason for this change?

Body:
Until then, to obtain the linear predictors of a Cox model via  predict, it was accepted that the linear predictors were centred.
When they were recalculated, the continuous and categorical variables were centered (see Linear predictor from predict.coxph from coefficients only and Coxph predictions don't match the coefficients).

But when I test this now it appears that only continuous variables are centered. To reuse the link example:

URL   <- "http://socserv.mcmaster.ca/jfox/Books/Companion/data/Rossi.txt"
Rossi <- read.table(URL, header=TRUE)
library(survival)

#for binary variable
fitCPH <- coxph(Surv(week, arrest) ~ fin, data=Rossi)    #Cox-PH model
(coefCPH <- coef(fitCPH))                              # estimated coefficients
head(predict(fitCPH,type="lp"))
head((as.numeric(as.factor((Rossi$fin))) - 1) - mean(as.numeric(as.factor(Rossi$fin)) - 1)    * coef(fitCPH)) #centered
head((as.numeric(as.factor((Rossi$fin))) - 1)    * coef(fitCPH)) #non-centered

Can someone confirm the information and the reason for this change?


问:
How to filter a query on linkedFrom?
I have a collection of authors. Some authors have written blogs, others have not. I can reference the total amount of blogs they've written using:

```<code>query {
  authorCollection {
    linkedFrom {
       blogCollection {
         total
       }
    }
  }
}
</code>```

What I want, however, is a list of authors with more than 1 blog post.  Some have written blogs, others have not.  How can I filter the query to do so? Ive tried something like this but this is not possible:

```<code>query {
  authorCollection(where: {linkedFrom: //This is not an available option}) {
    linkedFrom {
       blogCollection {
         total
       }
    }
  }
}
</code>```

Title: How to filter a query on linkedFrom?

Body:
I have a collection of authors. Some authors have written blogs, others have not. I can reference the total amount of blogs they've written using:

query {
  authorCollection {
    linkedFrom {
       blogCollection {
         total
       }
    }
  }
}

What I want, however, is a list of authors with more than 1 blog post.  Some have written blogs, others have not.  How can I filter the query to do so? Ive tried something like this but this is not possible:

query {
  authorCollection(where: {linkedFrom: //This is not an available option}) {
    linkedFrom {
       blogCollection {
         total
       }
    }
  }
}


问:
stored procedure stops working after first update
I have a task related to MYSQL where I am required to gather a particular set of values from a horizontal table and insert it into another table. The values in the table are like Index_0, AngleValue_0, Index_1, AngleValue_1,.....Index_11, AngleValue_11. I have to identify a set by the Index value, grab all the values of that set (for example if the Index is identified as Index_0, then grab Index_0 and AngleValue_0), and insert it into another table.

I have created a stored procedure for this, but it works for the first time and then stops updating.

Here is how my stored procedure looks.

```<code>DELIMITER //
drop procedure if exists updaterearseattorquereapir//
create procedure updaterearseattorquereapir(in ind int, in kanbn varchar(50), in rp_bdg int, in tl_bdg int, in qc_bdg int)
BEGIN
set @cnt = 0;

WHILE @cnt <= 11 DO
    set @i = 0;
    DROP TEMPORARY TABLE IF EXISTS indexcheck_Temp;
    set @sql_check = CONCAT('CREATE TEMPORARY TABLE indexcheck_Temp
    Select ',concat('Index_',@cnt),' as a From rearseattorque where ',concat('Index_',@cnt),'=', ind,' and Kanban = ',"@kanbn");
    prepare stmt from @sql_check;
    Execute stmt;
    deallocate prepare stmt;
    select @i := a from indexcheck_Temp;

    if ind = @i
        then
            DROP TEMPORARY TABLE IF EXISTS rearseattorquerepair_Temp;
            set @sql1 = CONCAT('
                    CREATE TEMPORARY TABLE rearseattorquerepair_Temp
                    SELECT Kanban, ',rp_bdg,', ',tl_bdg,', ',qc_bdg,', DTRowUpdate, ',concat('AngleValue_',@cnt),', ',concat('AngleStatus_',@cnt),', ',
                   concat('Index_',@cnt),', ',concat('Name_', @cnt),', ',concat('Operator_',@cnt),', ',concat('PSETNumber_',@cnt),', ',
                   concat('TighteningID_',@cnt),', ',concat('TighteningStatus_',@cnt),', ',concat('TimeStamp_',@cnt),', ',
                   concat('TorqueValue_',@cnt),', ',concat('TorqueStatus_',@cnt),
                   ' FROM rearseattorque where ',concat('Index_',@cnt),'=', ind,' and Kanban = ',"@kanbn");
            prepare stmt from @sql1;
            EXECUTE stmt;
            deallocate prepare stmt;

            Insert into rearseattorquerepair(Kanban
                                             ,RepairOperatorBadge
                                                ,    TeamLeaderBadge
                                                ,    QCBadge
                                                ,    DTRowUpdate
                                                ,    Bolt_AngleValue
                                                ,    Bolt_AngleStatus
                                                ,    Bolt_Index
                                                ,    Bolt_Name
                                                ,    Bolt_Operator
                                                ,    Bolt_PSETNumber
                                                ,    Bolt_TighteningID
                                                ,    Bolt_TighteningStatus
                                                ,    Bolt_TimeStamp
                                                ,    Bolt_TorqueValue
                                                ,    Bolt_TorqueStatus
                                                )
            Select * from rearseattorquerepair_Temp;

        else
            select 'data not found';

    END if;
    SET @cnt = @cnt + 1;
END WHILE;

END//

DELIMITER ;
</code>```

Body:
I have a task related to MYSQL where I am required to gather a particular set of values from a horizontal table and insert it into another table. The values in the table are like Index_0, AngleValue_0, Index_1, AngleValue_1,.....Index_11, AngleValue_11. I have to identify a set by the Index value, grab all the values of that set (for example if the Index is identified as Index_0, then grab Index_0 and AngleValue_0), and insert it into another table.

I have created a stored procedure for this, but it works for the first time and then stops updating.

Here is how my stored procedure looks.

DELIMITER //
drop procedure if exists updaterearseattorquereapir//
create procedure updaterearseattorquereapir(in ind int, in kanbn varchar(50), in rp_bdg int, in tl_bdg int, in qc_bdg int)
BEGIN
set @cnt = 0;

WHILE @cnt <= 11 DO
    set @i = 0;
    DROP TEMPORARY TABLE IF EXISTS indexcheck_Temp;
    set @sql_check = CONCAT('CREATE TEMPORARY TABLE indexcheck_Temp
    Select ',concat('Index_',@cnt),' as a From rearseattorque where ',concat('Index_',@cnt),'=', ind,' and Kanban = ',"@kanbn");
    prepare stmt from @sql_check;
    Execute stmt;
    deallocate prepare stmt;
    select @i := a from indexcheck_Temp;

    if ind = @i
        then
            DROP TEMPORARY TABLE IF EXISTS rearseattorquerepair_Temp;
            set @sql1 = CONCAT('
                    CREATE TEMPORARY TABLE rearseattorquerepair_Temp
                    SELECT Kanban, ',rp_bdg,', ',tl_bdg,', ',qc_bdg,', DTRowUpdate, ',concat('AngleValue_',@cnt),', ',concat('AngleStatus_',@cnt),', ',
                   concat('Index_',@cnt),', ',concat('Name_', @cnt),', ',concat('Operator_',@cnt),', ',concat('PSETNumber_',@cnt),', ',
                   concat('TighteningID_',@cnt),', ',concat('TighteningStatus_',@cnt),', ',concat('TimeStamp_',@cnt),', ',
                   concat('TorqueValue_',@cnt),', ',concat('TorqueStatus_',@cnt),
                   ' FROM rearseattorque where ',concat('Index_',@cnt),'=', ind,' and Kanban = ',"@kanbn");
            prepare stmt from @sql1;
            EXECUTE stmt;
            deallocate prepare stmt;

            Insert into rearseattorquerepair(Kanban
                                             ,RepairOperatorBadge
                                                ,    TeamLeaderBadge
                                                ,    QCBadge
                                                ,    DTRowUpdate
                                                ,    Bolt_AngleValue
                                                ,    Bolt_AngleStatus
                                                ,    Bolt_Index
                                                ,    Bolt_Name
                                                ,    Bolt_Operator
                                                ,    Bolt_PSETNumber
                                                ,    Bolt_TighteningID
                                                ,    Bolt_TighteningStatus
                                                ,    Bolt_TimeStamp
                                                ,    Bolt_TorqueValue
                                                ,    Bolt_TorqueStatus
                                                )
            Select * from rearseattorquerepair_Temp;

        else
            select 'data not found';

    END if;
    SET @cnt = @cnt + 1;
END WHILE;

END//

DELIMITER ;


问:
Three.js lines disappear when partially outside of view in Chrome but not Firefox
I am using Three.js to display a grid using the GridHelper class. The grid lines disappear when the camera is zoomed in and the lines are partially outside of the view. The issue is only present in Chrome, while it works correctly in Firefox. I've tried disabling frustum culling for the grid by setting frustumCulled = false and traversing through the children of the grid and setting frustumCulled = false for each object, but it doesn't seem to help.

Here is a jsfiddle link to show the issue: https://jsfiddle.net/dc43n91a/

Here is a screenshot how it looks in Firefox (correctly):

and Chrome (incorrectly)

Here is the code causing the issue:

```<code>        const scene = new THREE.Scene();
        const camera = new THREE.PerspectiveCamera( 75, 1, 0.1, 1000 );

        scene.background = new THREE.Color( 0x333333 );

        camera.up.set( 0, 0, 1 );
        camera.position.set( - 10, - 25, 10 );
        camera.lookAt(0,0,0);
        scene.add( camera );

        const grid = new THREE.GridHelper(200, 12);
        grid.rotation.set(Math.PI / 2, Math.PI / 2, 0);
        grid.position.set(0, 0, 0);
        grid.frustumCulled = false;
        grid.traverse((object) => { object.frustumCulled = false; });
        grid.geometry.computeBoundingSphere();
        scene.add(grid);

        const renderer = new THREE.WebGLRenderer();
        renderer.setSize( 400, 400 );

        document.getElementById('viewer').appendChild( renderer.domElement );

        renderer.render(scene, camera);
</code>```

Could anyone please help me understand why this issue is happening only in some browsers and how to fix it?

Body:
I am using Three.js to display a grid using the GridHelper class. The grid lines disappear when the camera is zoomed in and the lines are partially outside of the view. The issue is only present in Chrome, while it works correctly in Firefox. I've tried disabling frustum culling for the grid by setting frustumCulled = false and traversing through the children of the grid and setting frustumCulled = false for each object, but it doesn't seem to help.

Here is a jsfiddle link to show the issue: https://jsfiddle.net/dc43n91a/

Here is a screenshot how it looks in Firefox (correctly):

and Chrome (incorrectly)

Here is the code causing the issue:

        const scene = new THREE.Scene();
        const camera = new THREE.PerspectiveCamera( 75, 1, 0.1, 1000 );

        scene.background = new THREE.Color( 0x333333 );

        camera.up.set( 0, 0, 1 );
        camera.position.set( - 10, - 25, 10 );
        camera.lookAt(0,0,0);
        scene.add( camera );

        const grid = new THREE.GridHelper(200, 12);
        grid.rotation.set(Math.PI / 2, Math.PI / 2, 0);
        grid.position.set(0, 0, 0);
        grid.frustumCulled = false;
        grid.traverse((object) => { object.frustumCulled = false; });
        grid.geometry.computeBoundingSphere();
        scene.add(grid);

        const renderer = new THREE.WebGLRenderer();
        renderer.setSize( 400, 400 );

        document.getElementById('viewer').appendChild( renderer.domElement );

        renderer.render(scene, camera);

Could anyone please help me understand why this issue is happening only in some browsers and how to fix it?


问:
Getting error 503 on connection to secure web socket
When I'm making the connection using WSS protocol, I'm getting 503 on my back-end deployed on Heroku.
I'm using Netlify so they make me use only WSS protocol.
This is the error I'm getting:
WebSocketTester.3f92180b.js:1

WebSocket connection to 'wss://my-app-site/' failed: Error during WebSocket handshake: Unexpected response code: 503

this is my server side, i provided the cert and key:

```<code>const options = {
  cert: readFileSync('./etc/ssl/certs/server.crt'),
  key: readFileSync('./etc/ssl/private/key.pem')
};
const server = https.createServer(options, app);

const WebSocket = require('ws');

const wss = new WebSocket.Server({ server });
</code>```

this is my client side:

```<code>    if (!wsRef.current) {
      wsRef.current = new WebSocket(`wss://my-site-url`);
      wsRef.current.onopen = () => {
        console.log('connection opened!');
      }
      wsRef.current.onmessage = ({ data }) => console.log(data);
      wsRef.current.onclose = () => {
        wsRef.current = null;
      }
    }
</code>```

I would appreciate your help.

Body:
When I'm making the connection using WSS protocol, I'm getting 503 on my back-end deployed on Heroku.
I'm using Netlify so they make me use only WSS protocol.
This is the error I'm getting:
WebSocketTester.3f92180b.js:1

WebSocket connection to 'wss://my-app-site/' failed: Error during WebSocket handshake: Unexpected response code: 503

this is my server side, i provided the cert and key:

const options = {
  cert: readFileSync('./etc/ssl/certs/server.crt'),
  key: readFileSync('./etc/ssl/private/key.pem')
};
const server = https.createServer(options, app);

const WebSocket = require('ws');

const wss = new WebSocket.Server({ server });

this is my client side:

    if (!wsRef.current) {
      wsRef.current = new WebSocket(`wss://my-site-url`);
      wsRef.current.onopen = () => {
        console.log('connection opened!');
      }
      wsRef.current.onmessage = ({ data }) => console.log(data);
      wsRef.current.onclose = () => {
        wsRef.current = null;
      }
    }

I would appreciate your help.


问:
Apigee X - Upgrade process?
From an architectural long term planning perspective, is there any information about updates / upgrades processes and/or timelines of ApigeeX around?

It is a SaaS, so I assume upgrades are seamless and backwards compatible applied automatically in the background, but without evidence that's obviously an assumption only. There seems to be no version / build number shown in the Apigee console either, but I am sure it is upgraded regularly, as there are release notes.

Title: Apigee X - Upgrade process?


问:
Is order guaranteed for initializing Javascript objects?
I'm sure this has been asked but I'm not sure what to search. Say I have the following code:

```<code>const foo = {
  apple: buffer.read(),
  banana: buffer.read(),
  carrot: buffer.read()
};
</code>```

Is it guaranteed that the apple key will be initialized first, followed by the banana key, and then lastly the carrot key? It matters because the buffer read function internally increments the byte offset for later reading.

If it is not guaranteed I assume I would have to do this instead:

```<code>const apple = buffer.read();
const banana = buffer.read();
const carrot = buffer.read();

return { apple, banana, carrot };
</code>```

But it would be nice if the first one always worked. I'm just not sure if it does.

Body:
I'm sure this has been asked but I'm not sure what to search. Say I have the following code:

const foo = {
  apple: buffer.read(),
  banana: buffer.read(),
  carrot: buffer.read()
};

Is it guaranteed that the apple key will be initialized first, followed by the banana key, and then lastly the carrot key? It matters because the buffer read function internally increments the byte offset for later reading.

If it is not guaranteed I assume I would have to do this instead:

const apple = buffer.read();
const banana = buffer.read();
const carrot = buffer.read();

return { apple, banana, carrot };

But it would be nice if the first one always worked. I'm just not sure if it does.


问:
ftplib -- deleting many files from ftp folder
I am pretty new to Python, but would like to use it to do some tasks on an FTP. Feel like it should be fairly easy but I am having some issues when trying to delete multiple files (hundreds) from an FTP folder. I have the file names I want to delete as strings from a SQL table I can copy and paste if needed.

My code so far:

```<code>import os
import ftplib

ftpHost = 'ftp.myhost.com'
ftpPort = 21
ftpUsername = 'myuser'
ftpPassword = 'mypassword'

ftp = ftplib.FTP(timeout=30)

ftp.connect(ftpHost, ftpPort)

ftp.login(ftpUsername, ftpPassword)

ftp.cwd("/myftpfolder/January2023")

ftp.delete("1234myfile.mp4")

ftp.quit()

print("Execution complete...")
</code>```

As above, I can delete the files one-off but is there a practical way for me to delete about 800 files from the folder above if I were able to paste them somewhere or put them in a text file and have Python read through it to execute the deletes? I suppose this isn't necessarily an FTP or ftplib specific question, but could help me get a better general understanding of lists, tuples, etc. Using Python3.10 btw.

Thanks!

Body:
I am pretty new to Python, but would like to use it to do some tasks on an FTP. Feel like it should be fairly easy but I am having some issues when trying to delete multiple files (hundreds) from an FTP folder. I have the file names I want to delete as strings from a SQL table I can copy and paste if needed.

My code so far:

import os
import ftplib

ftpHost = 'ftp.myhost.com'
ftpPort = 21
ftpUsername = 'myuser'
ftpPassword = 'mypassword'

ftp = ftplib.FTP(timeout=30)

ftp.connect(ftpHost, ftpPort)

ftp.login(ftpUsername, ftpPassword)

ftp.cwd("/myftpfolder/January2023")

ftp.delete("1234myfile.mp4")

ftp.quit()

print("Execution complete...")

As above, I can delete the files one-off but is there a practical way for me to delete about 800 files from the folder above if I were able to paste them somewhere or put them in a text file and have Python read through it to execute the deletes? I suppose this isn't necessarily an FTP or ftplib specific question, but could help me get a better general understanding of lists, tuples, etc. Using Python3.10 btw.

Thanks!


问:
Input type "file" not working in Android WebView
I'm trying to use Android WebView, but my app can't upload an image! Basically speaking, he manages to take a picture (asks for all the permissions normally), but when he clicks to send, the sending is not carried out and the field is "blank"! Below I will leave my code. Thanks in advance to anyone who can help me!

Java

package com.example.app_android_5;

import android.os.Bundle;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {
    WebView webView;
    private static final String TAG = MainActivity.class.getSimpleName();
    private String mCM;
    private ValueCallback<Uri> mUM;
    private ValueCallback<Uri[]> mUMA;
    private final static int FCR=1;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent){
        super.onActivityResult(requestCode, resultCode, intent);
        if(Build.VERSION.SDK_INT >= 21){
            Uri[] results = null;
            //Check if response is positive
            if(resultCode== Activity.RESULT_OK){
                if(requestCode == FCR){
                    if(null == mUMA){
                        return;
                    }
                    if(intent == null){
                        //Capture Photo if no image available
                        if(mCM != null){
                            results = new Uri[]{Uri.parse(mCM)};
                        }
                    }else{
                        String dataString = intent.getDataString();
                        if(dataString != null){
                            results = new Uri[]{Uri.parse(dataString)};
                        }
                    }
                }
            }
            mUMA.onReceiveValue(results);
            mUMA = null;
        }else{
            if(requestCode == FCR){
                if(null == mUM) return;
                Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
                mUM.onReceiveValue(result);
                mUM = null;
            }
        }
    }

    @SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(Build.VERSION.SDK_INT >=23 && (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
        }

        webView = (WebView) findViewById(R.id.webView);
        assert webView != null;
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);

        if(Build.VERSION.SDK_INT >= 21){
            webSettings.setMixedContentMode(0);
            webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }else if(Build.VERSION.SDK_INT >= 19){
            webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }else if(Build.VERSION.SDK_INT < 19){
            webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        webView.setWebViewClient(new Callback());
        webView.loadUrl("https://google.com/");
        webView.setWebChromeClient(new WebChromeClient(){

            //For Android 5.0+
            public boolean onShowFileChooser(
                    WebView webView, ValueCallback<Uri[]> filePathCallback,
                    WebChromeClient.FileChooserParams fileChooserParams){
                if(mUMA != null){
                    mUMA.onReceiveValue(null);
                }
                mUMA = filePathCallback;
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if(takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null){
                    File photoFile = null;
                    try{
                        photoFile = createImageFile();
                        takePictureIntent.putExtra("PhotoPath", mCM);
                    }catch(IOException ex){
                        Log.e(TAG, "Image file creation failed", ex);
                    }
                    if(photoFile != null){
                        mCM = "file:" + photoFile.getAbsolutePath();
                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                    }else{
                        takePictureIntent = null;
                    }
                }
                Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
                contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
                contentSelectionIntent.setType("*/*");
                Intent[] intentArray;
                if(takePictureIntent != null){
                    intentArray = new Intent[]{takePictureIntent};
                }else{
                    intentArray = new Intent[0];
                }

                Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
                startActivityForResult(chooserIntent, FCR);
                return true;
            }
        });
    }
    public class Callback extends WebViewClient{
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
            Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();
        }
    }
    // Create an image file
    private File createImageFile() throws IOException{
        @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "img_"+timeStamp+"_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(imageFileName,".jpg",storageDir);
    }
    @Override
    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event){
        if(event.getAction() == KeyEvent.ACTION_DOWN){
            switch(keyCode){
                case KeyEvent.KEYCODE_BACK:
                    if(webView.canGoBack()){
                        webView.goBack();
                    }else{
                        finish();
                    }
                    return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig){
        super.onConfigurationChanged(newConfig);
    }
}
```
<h1>AndroidManifest</h1>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.CAMERA"/>

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.App_android_5"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
    </application>

</manifest>
</code>```

I've already looked in different forums and publications, but, as I still don't know very well how development using Android works, I couldn't reach this answer. Currently I've tested it with Android 5.0, 5.1, 8, 11 and 12, but it still doesn't work!

Body:
I'm trying to use Android WebView, but my app can't upload an image! Basically speaking, he manages to take a picture (asks for all the permissions normally), but when he clicks to send, the sending is not carried out and the field is "blank"! Below I will leave my code. Thanks in advance to anyone who can help me!

Java

package com.example.app_android_5;

import android.os.Bundle;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {
    WebView webView;
    private static final String TAG = MainActivity.class.getSimpleName();
    private String mCM;
    private ValueCallback<Uri> mUM;
    private ValueCallback<Uri[]> mUMA;
    private final static int FCR=1;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent){
        super.onActivityResult(requestCode, resultCode, intent);
        if(Build.VERSION.SDK_INT >= 21){
            Uri[] results = null;
            //Check if response is positive
            if(resultCode== Activity.RESULT_OK){
                if(requestCode == FCR){
                    if(null == mUMA){
                        return;
                    }
                    if(intent == null){
                        //Capture Photo if no image available
                        if(mCM != null){
                            results = new Uri[]{Uri.parse(mCM)};
                        }
                    }else{
                        String dataString = intent.getDataString();
                        if(dataString != null){
                            results = new Uri[]{Uri.parse(dataString)};
                        }
                    }
                }
            }
            mUMA.onReceiveValue(results);
            mUMA = null;
        }else{
            if(requestCode == FCR){
                if(null == mUM) return;
                Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
                mUM.onReceiveValue(result);
                mUM = null;
            }
        }
    }

    @SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(Build.VERSION.SDK_INT >=23 && (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
        }

        webView = (WebView) findViewById(R.id.webView);
        assert webView != null;
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);

        if(Build.VERSION.SDK_INT >= 21){
            webSettings.setMixedContentMode(0);
            webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }else if(Build.VERSION.SDK_INT >= 19){
            webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }else if(Build.VERSION.SDK_INT < 19){
            webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        webView.setWebViewClient(new Callback());
        webView.loadUrl("https://google.com/");
        webView.setWebChromeClient(new WebChromeClient(){

            //For Android 5.0+
            public boolean onShowFileChooser(
                    WebView webView, ValueCallback<Uri[]> filePathCallback,
                    WebChromeClient.FileChooserParams fileChooserParams){
                if(mUMA != null){
                    mUMA.onReceiveValue(null);
                }
                mUMA = filePathCallback;
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if(takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null){
                    File photoFile = null;
                    try{
                        photoFile = createImageFile();
                        takePictureIntent.putExtra("PhotoPath", mCM);
                    }catch(IOException ex){
                        Log.e(TAG, "Image file creation failed", ex);
                    }
                    if(photoFile != null){
                        mCM = "file:" + photoFile.getAbsolutePath();
                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                    }else{
                        takePictureIntent = null;
                    }
                }
                Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
                contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
                contentSelectionIntent.setType("*/*");
                Intent[] intentArray;
                if(takePictureIntent != null){
                    intentArray = new Intent[]{takePictureIntent};
                }else{
                    intentArray = new Intent[0];
                }

                Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
                startActivityForResult(chooserIntent, FCR);
                return true;
            }
        });
    }
    public class Callback extends WebViewClient{
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
            Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();
        }
    }
    // Create an image file
    private File createImageFile() throws IOException{
        @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "img_"+timeStamp+"_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(imageFileName,".jpg",storageDir);
    }
    @Override
    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event){
        if(event.getAction() == KeyEvent.ACTION_DOWN){
            switch(keyCode){
                case KeyEvent.KEYCODE_BACK:
                    if(webView.canGoBack()){
                        webView.goBack();
                    }else{
                        finish();
                    }
                    return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig){
        super.onConfigurationChanged(newConfig);
    }
}

AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.CAMERA"/>

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.App_android_5"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
    </application>

</manifest>

I've already looked in different forums and publications, but, as I still don't know very well how development using Android works, I couldn't reach this answer. Currently I've tested it with Android 5.0, 5.1, 8, 11 and 12, but it still doesn't work!


问:
kivy app crashed when i import firebase- admin
when i import firebase-admin in source code , and compile the app
the app crashed .

but
if i remove import firebase-admin from source code and compile
the app run normaly

try add firebase-admin and google to requirements = python3,kivy,kivymd,python-bidi,arabic_reshaper,six,future,pandas,firebase-admin,google

error catch in logcat :

2023-01-13 00:40:37.982 29866-29866 pythonutil               org.test.com.mini_pocket_accountant  V  Library loading error: dlopen failed: library "libpython3.5m.so" not found 2023-01-13 00:40:37.982 29866-29866 pythonutil               org.test.com.mini_pocket_accountant  V  Library loading error: dlopen failed: library "libpython3.6m.so" not found 2023-01-13 00:40:37.983 29866-29866 pythonutil               org.test.com.mini_pocket_accountant  V  Library loading error: dlopen failed: library "libpython3.7m.so" not found 2023-01-13 00:40:37.983 29866-29866 pythonutil               org.test.com.mini_pocket_accountant  V  Library loading error: dlopen failed: library "libpython3.8.so" not found 2023-01-13 00:40:39.084 29866-29902 python                   org.test.com.mini_pocket_accountant  I   ModuleNotFoundError: No module named 'google' 2023-01-13 00:40:39.231  1849-2298  InputDispatcher     pid-1849                              W  channel '23ae735 org.test.com.mini_pocket_accountant/org.kivy.android.PythonActivity (server)' ~ Consumer closed input channel or an error occurred.  events=0x9


问:
how to scrumble the word if i click a button
How can I make a button that scrambles the letter every time I click it? When I try to make another button and then click it, it will scramble the letter. Then, when I got another word, when I clicked again on the scramble button, it was back to the first word I answered. (I'm just new. I'm sorry for my code).

```<code> public static String wordJumble(String word )
{
    Random random = new Random();
    char wordArray[] = word.toCharArray();
    for(int i=0; i< wordArray.length; i++ )
    {
        int j = random.nextInt(wordArray.length);
        char temp = wordArray[i];
        wordArray[i] = wordArray[j];
        wordArray[j] = temp;
    }
    if(wordArray.toString().equals(word)){
        wordJumble(word);
    }
    return new String(wordArray);
}

@Override
protected void onResume() {
    super.onResume();
    final String [] str=quesWord.toArray(new String[quesWord.size()]);
    attemptsLeft.setText("Attempts left: "+chances);
    points.setText("Score: "+score);
    jumbleWord.setText(wordJumble(str[0]));
    b.setOnClickListener(new OnClickListener() {
        int j=0;
        int len=str.length;
        @Override
        public void onClick(View v) {
            try{
                if(answerText.getText().toString().trim().equalsIgnoreCase(str[j])){
                    score++;
                    if(score==len){
                        dbHandler.addScore2("JL",score);
                        countDownTimer.cancel();

                        adb.setTitle("You Won!");
                        adb.setMessage("Score: "+score);
                        adb.setPositiveButton("Okay", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        });
                        adb.show();
                    }
                    j++;
                    points.setText("Score: "+score);
                    jumbleWord.setText((wordJumble(str[j])));
                }
</code>```

My shuffle Button

```<code>  shuffle.setOnClickListener(new View.OnClickListener() {
        int j=0;
        @Override
        public void onClick(View v) {
            j++;
            jumbleWord.setText((wordJumble(str[j])));
        }
});
</code>```

Body:
How can I make a button that scrambles the letter every time I click it? When I try to make another button and then click it, it will scramble the letter. Then, when I got another word, when I clicked again on the scramble button, it was back to the first word I answered. (I'm just new. I'm sorry for my code).

 public static String wordJumble(String word )
{
    Random random = new Random();
    char wordArray[] = word.toCharArray();
    for(int i=0; i< wordArray.length; i++ )
    {
        int j = random.nextInt(wordArray.length);
        char temp = wordArray[i];
        wordArray[i] = wordArray[j];
        wordArray[j] = temp;
    }
    if(wordArray.toString().equals(word)){
        wordJumble(word);
    }
    return new String(wordArray);
}

@Override
protected void onResume() {
    super.onResume();
    final String [] str=quesWord.toArray(new String[quesWord.size()]);
    attemptsLeft.setText("Attempts left: "+chances);
    points.setText("Score: "+score);
    jumbleWord.setText(wordJumble(str[0]));
    b.setOnClickListener(new OnClickListener() {
        int j=0;
        int len=str.length;
        @Override
        public void onClick(View v) {
            try{
                if(answerText.getText().toString().trim().equalsIgnoreCase(str[j])){
                    score++;
                    if(score==len){
                        dbHandler.addScore2("JL",score);
                        countDownTimer.cancel();

                        adb.setTitle("You Won!");
                        adb.setMessage("Score: "+score);
                        adb.setPositiveButton("Okay", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        });
                        adb.show();
                    }
                    j++;
                    points.setText("Score: "+score);
                    jumbleWord.setText((wordJumble(str[j])));
                }

My shuffle Button

  shuffle.setOnClickListener(new View.OnClickListener() {
        int j=0;
        @Override
        public void onClick(View v) {
            j++;
            jumbleWord.setText((wordJumble(str[j])));
        }
});


问:
Having trouble deploying a parse server to heroku. Using moralis parse server and MongoDB
This server runs fine locally using "yarn build yarn start" but when trying to deploy I am getting these errors. Cannot find anything on google so far that has worked. Any help would be much appreciated!!

```<code>remote: -----> Installing dependencies
remote:        Installing node modules (yarn.lock)
remote:        yarn install v1.22.19
remote:        [1/4] Resolving packages...
remote:        [2/4] Fetching packages...
remote:        warning Pattern ["debug@>= 2.6.9 < 3.0.0 || >= ^3.1.0"] is trying to unpack in the same destination "/tmp/yarncache.VrWcZ/v6/npm-debug-3.2.7-integrity/node_modules/debug" as pattern ["debug@^3.1.0","debug@^3.2.7","debug@^3.2.7"]. This could result in non-deterministic behavior, skipping.
remote:        error Command failed.
remote:        Exit code: 128
remote:        Command: git
remote:        Arguments: ls-remote --tags --heads ssh://git@github.com/mongodb-js/mongodb-tools.git
remote:        Directory: /tmp/build_fa7e0e92
remote:        Output:
remote:        Host key verification failed.
remote:        fatal: Could not read from remote repository.
remote:
remote:        Please make sure you have the correct access rights
remote:        and the repository exists.
remote:        info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
remote:
remote: -----> Build failed
remote:
remote:        We're sorry this build is failing! You can troubleshoot common issues here:
remote:        https://devcenter.heroku.com/articles/troubleshooting-node-deploys
remote:
remote:        Some possible problems:
</code>```

I tried to deploy to heroku. Build fails due to "Host key verification failed" It looks like I do not have access to ssh://git@github.com/mongodb-js/mongodb-tools.git, but i'm not quite sure what that means

Body:
This server runs fine locally using "yarn build yarn start" but when trying to deploy I am getting these errors. Cannot find anything on google so far that has worked. Any help would be much appreciated!!

remote: -----> Installing dependencies
remote:        Installing node modules (yarn.lock)
remote:        yarn install v1.22.19
remote:        [1/4] Resolving packages...
remote:        [2/4] Fetching packages...
remote:        warning Pattern ["debug@>= 2.6.9 < 3.0.0 || >= ^3.1.0"] is trying to unpack in the same destination "/tmp/yarncache.VrWcZ/v6/npm-debug-3.2.7-integrity/node_modules/debug" as pattern ["debug@^3.1.0","debug@^3.2.7","debug@^3.2.7"]. This could result in non-deterministic behavior, skipping.
remote:        error Command failed.
remote:        Exit code: 128
remote:        Command: git
remote:        Arguments: ls-remote --tags --heads ssh://git@github.com/mongodb-js/mongodb-tools.git
remote:        Directory: /tmp/build_fa7e0e92
remote:        Output:
remote:        Host key verification failed.
remote:        fatal: Could not read from remote repository.
remote:
remote:        Please make sure you have the correct access rights
remote:        and the repository exists.
remote:        info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
remote:
remote: -----> Build failed
remote:
remote:        We're sorry this build is failing! You can troubleshoot common issues here:
remote:        https://devcenter.heroku.com/articles/troubleshooting-node-deploys
remote:
remote:        Some possible problems:

I tried to deploy to heroku. Build fails due to "Host key verification failed" It looks like I do not have access to ssh://git@github.com/mongodb-js/mongodb-tools.git, but i'm not quite sure what that means


问:
How can I make GetAsyncKeyState in C#, or IsKeyDown to work with C# using .net 7
How can I get event based, or recognize async key presses in C# .Net 7?

This is for player controls in a console application, so obviously I cannot have the game loop wait around for a button press, but maybe I could buffer it?
I am trying to get key presses to then let the camera know that it needs to turn, pan, move etc. without having the console halt the game loop.

I was using the following code translated from C++ as a base, and I was trying to find a similar solution in C#.

```<code>int LeftTurn = (ushort)'A';
int RightTurn = (ushort)'D';

if (GetAsyncKeyState(LeftTurn) & 0x8000)
    fPlayerA -= (0.1f);
if (GetAsyncKeyState(RightTurn) & 0x8000)
    fPlayerA += (0.1f);
</code>```

It appears there is a way to get GetAsyncKeyState to work with C# by importing a DLL, but I could not get it to work as it kept throwing errors at the DLL placement and at the function. So I tried using the following instead

```<code>if (Keyboard.IsKeyDown(LeftTurn))
    fPlayerA -= (0.1f);
if (Keyboard.IsKeyDown(RightTurn))
    fPlayerA += (0.1f);

</code>```

However this seems to only be supported in Windows desktop 7 and is not supported by .Net 7. Errors were thrown every time I tried to evoke Keyboard.
Is there something simple I am missing in either of these two methods or is there a better way to go about this?

This has me stumped, thanks.

edit:
I've tried copying some code I found on reddit that went like:

```<code>if(Input.IsKeyPressed((int) KeyList.W))
    {
        direction.y -= Speed * delta;
    }
</code>```

but I keep getting the error that "Error CS0234 The type or namespace name 'IsKeyPressed' does not exist in the namespace 'System.Windows.Input' (are you missing an assembly reference?)"
I'm very confused since every potential solution gives me this error, despite making sure that I declare that I am referencing the required files.

My code looks a bit like this:

```<code>using System.ComponentModel;
using System.Numerics;
using System.Reflection.Metadata;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Windows.Input;

class GameApp
{
    //Main Funtion
    static void Main()
    {
        //frame settings
        //camera variables
        //Level data
        Console.SetWindowPosition(0, 0);
        Console.SetWindowSize(nFrameWidth, nFrameHeight);
        Console.CursorVisible = false;
    //game loop
        while (true)
        {
            //User input
            //Camera Controls
            //Handle Rotation
            int LeftTurn = (ushort)'A';
            int RightTurn = (ushort)'D';
            if (Keyboard.IsKeyDown(LeftTurn))
                fPlayerA -= (0.1f) * fElapsedTime;
            if (Keyboard.IsKeyDown(RightTurn))
                fPlayerA += (0.1f) * fElapsedTime;
        //Render Frame
        //lots of math here
        }
    }
}
</code>```

I cut out the sections that shouldn't be relevant to save space and left comments for what the sections are supposed to do.
Please help, thanks.

Body:
How can I get event based, or recognize async key presses in C# .Net 7?

This is for player controls in a console application, so obviously I cannot have the game loop wait around for a button press, but maybe I could buffer it?
I am trying to get key presses to then let the camera know that it needs to turn, pan, move etc. without having the console halt the game loop.

I was using the following code translated from C++ as a base, and I was trying to find a similar solution in C#.

int LeftTurn = (ushort)'A';
int RightTurn = (ushort)'D';

if (GetAsyncKeyState(LeftTurn) & 0x8000)
    fPlayerA -= (0.1f);
if (GetAsyncKeyState(RightTurn) & 0x8000)
    fPlayerA += (0.1f);

It appears there is a way to get GetAsyncKeyState to work with C# by importing a DLL, but I could not get it to work as it kept throwing errors at the DLL placement and at the function. So I tried using the following instead

if (Keyboard.IsKeyDown(LeftTurn))
    fPlayerA -= (0.1f);
if (Keyboard.IsKeyDown(RightTurn))
    fPlayerA += (0.1f);

However this seems to only be supported in Windows desktop 7 and is not supported by .Net 7. Errors were thrown every time I tried to evoke Keyboard.
Is there something simple I am missing in either of these two methods or is there a better way to go about this?

This has me stumped, thanks.

edit:
I've tried copying some code I found on reddit that went like:

if(Input.IsKeyPressed((int) KeyList.W))
    {
        direction.y -= Speed * delta;
    }

but I keep getting the error that "Error CS0234 The type or namespace name 'IsKeyPressed' does not exist in the namespace 'System.Windows.Input' (are you missing an assembly reference?)"
I'm very confused since every potential solution gives me this error, despite making sure that I declare that I am referencing the required files.

My code looks a bit like this:

using System.ComponentModel;
using System.Numerics;
using System.Reflection.Metadata;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Windows.Input;

class GameApp
{
    //Main Funtion
    static void Main()
    {
        //frame settings
        //camera variables
        //Level data
        Console.SetWindowPosition(0, 0);
        Console.SetWindowSize(nFrameWidth, nFrameHeight);
        Console.CursorVisible = false;
    //game loop
        while (true)
        {
            //User input
            //Camera Controls
            //Handle Rotation
            int LeftTurn = (ushort)'A';
            int RightTurn = (ushort)'D';
            if (Keyboard.IsKeyDown(LeftTurn))
                fPlayerA -= (0.1f) * fElapsedTime;
            if (Keyboard.IsKeyDown(RightTurn))
                fPlayerA += (0.1f) * fElapsedTime;
        //Render Frame
        //lots of math here
        }
    }
}

I cut out the sections that shouldn't be relevant to save space and left comments for what the sections are supposed to do.
Please help, thanks.


问:
How can I find the points of intersection between two vector shapefiles?
I have two vector shapefiles (polylines), and I want to find all the points where they intersect. I want to produce a set of points where the intersections occur.

If it helps, the context here is that I am trying to find locations where a satellite orbit crosses a river.

I know I can use v.select in GRASS GIS to do this, but it just selects the overlapping features - what I want is (x,y) coordinates of the exact overlapping locations.


问:
Why did my new AdMob account get limited in a new app and the eCPM increased a lot after that?
I had an app that was going very well. One day I received an email (after 2 years of publication) that was saying that my account was limited and after some days my account was terminated.

I created a new one and change the ids in my app. After it shown the first ads, it got limited and terminated. I repeated this progress a lot of times untill I decided to change ad network. Noone was as good as admob was.

So after a lot of thought I got back to admob but in an other way. I thought that they see the app package name that was the same with accounts that was terminated. So my last chance was to republish the app with a new package name. I did it, it started well the app published 2 days ago and yesterday got limited once again. It hasn't terminated yet but i see weird thinks happening.

First of all i got a lot of users through my previous app because i advertised the new one from the previous. At first i added a frequency capping of 1 ad every 3 minutes. The eCPM was around 1€. Yesterday i decided to change the limit to 1 ad per 2 minutes. After 5 minutes of this change I got the bad news that ads has been limited. Immediately I changed the frequency capping to 1 ad per hour for all devices and 1 ad per day for TVs (because I think there is the problem).

The weird thinks i said before was that after limited my eCPM was increased and it was happening and in the previous accounts. Example: In one country i got 2 views, 2 clicks and 2,66€ in android TV. I have an eCPM up to 10€ and when I reach 10€ it starts to display less ads. Please i need some help and I can't contact Admob.


问:
How can I efficiently perform serialization on arbitrary integral types for transmission and archival purposes
I have a lot of different types of data I want to serialize to a BYTE array in a custom format.  (I plan to convert everything into a some int based representation and then use this technique)  I then want to send this data over a network to other machines and I also intend to use it to store data to files which may also travel to other machines.  I have figured out how to do most of this for integral types... however I am still struggling to write a byte swapping algorithm that avoids undefined behavior.  A lot of the implementations I've seen are either needlessly slow, or they rely on tricks that invoke UB.  What is the correct, general way to write a fast byte swap algorithm in c++?  I'd prefer c++11.  Also, can I detect one's comp/sign-mag on older systems and handle that too?  I want a wide variety of machines to be able to run this code as I plan to use it for pretty much all my binary serialization from embedded systems to web socket data until I can come up with something better.

I've looked into a few existing library implementations for serialization like protobuf, but they seem bloated and slow or they seems to use casting tricks to function which may invoke UB.  So I am looking to handle this in a custom way as well... This is a rough idea of the interface I am thinking of implementing so far, but maybe there is a better way for this too.  Regardless, here's what I've got atm:

template<typename T>
T nativeToTwosCompLittleEndien(const T& input)
{
static_assert(std::is_integral<T>::value, "T must be an integral type");
// ...
}

template<typename T>
T nativeToTwosCompBigEndien(const T& input)
{
static_assert(std::is_integral<T>::value, "T must be an integral type");
// ...
}

template<typename T>
T twosCompLittleEndienToNative(const T& input)
{
static_assert(std::is_integral<T>::value, "T must be an integral type");
// ...
}

template<typename T>
T twosCompBigEndienToNative(const T& input)
{
static_assert(std::is_integral<T>::value, "T must be an integral type");
// ...
}
```


问:
How do I diagnose timeouts in Laravel 9?
I am writing an app in Laravel 9 that is mostly a series of CRUDs so far. I'm focusing on getting one running perfectly before I finish writing the others but I've hit a weird problem that I don't know how to diagnose: timeouts.

I am getting execution timeouts for exceeding 60 seconds fairly frequently. I'm baffled because I'm simply trying to display the index for a table that has maybe 20 rows and I'm only displaying one of its three columns or trying to display a create template to add a new row, again just providing a value for one column and letting the other two take defaults. I don't understand why this is sometimes taking over 60 seconds. (Even when it doesn't timeout, it takes longer than I would have expected but maybe the age of this computer is a factor.)

I'm assuming there are ways to see where the bottlenecks are in the execution time but I don't know anything about how to do that in Laravel. Could someone point me in the right direction?


问:
Requests_html render() function doesn't execute my JS script
I need to parse data from a site where the data is loaded as you scroll down. I wrote a JS script that scrolls page by page with pauses. I submitted this script with the render function from the requests_html library. I expected the page to load and scroll down, and then I would get the html text to parse. But I got an error:
"pyppeteer.errors.ElementHandleError: Evaluation failed: SyntaxError: Unexpected identifier"
Here is my code:

```<code>...
url = "https://kalektar.org"
user = fake_useragent.UserAgent().random

headers = {
    "Accept": ...,
    "User-Agent": ...,
    }

session = HTMLSession()
response = session.get(url, headers=headers)

js_script = """
function down() {
  let step = window.innerHeight;
  window.scrollTo(0, window.pageYOffset+step);
  window.scrollTo({ left: 0, top: window.pageYOffset+step, behavior: "smooth"});
  let scrollHeight, totalHeight;
  scrollHeight = document.body.scrollHeight;
  totalHeight = window.scrollY + window.innerHeight;
  if (totalHeight >= scrollHeight) {
    clearInterval(timerID);
  }
};
let timerID = setInterval(down, 3000);
"""

response.html.render(timeout=20, sleep=2, script=js_script)
page_html = response.html.html
print(page_html)
</code>```

Other simpler JS scripts work fine with response.html.render(). I tested my JS script in codepen.io and it works fine. Then I added my JS script to html with DevTool in the browser, it worked fine.
I tried a few slightly different JS scripts, but nothing worked. Of course, I cannot use the parameter scrolldown= because of the unknown number of scrolls.

At first I tried to get the information in other ways, like parsing ajax requests. But I found this to be a very difficult task. I didn't find any clues when researching the queries and responses.

Body:
I need to parse data from a site where the data is loaded as you scroll down. I wrote a JS script that scrolls page by page with pauses. I submitted this script with the render function from the requests_html library. I expected the page to load and scroll down, and then I would get the html text to parse. But I got an error:
"pyppeteer.errors.ElementHandleError: Evaluation failed: SyntaxError: Unexpected identifier"
Here is my code:

...
url = "https://kalektar.org"
user = fake_useragent.UserAgent().random

headers = {
    "Accept": ...,
    "User-Agent": ...,
    }

session = HTMLSession()
response = session.get(url, headers=headers)

js_script = """
function down() {
  let step = window.innerHeight;
  window.scrollTo(0, window.pageYOffset+step);
  window.scrollTo({ left: 0, top: window.pageYOffset+step, behavior: "smooth"});
  let scrollHeight, totalHeight;
  scrollHeight = document.body.scrollHeight;
  totalHeight = window.scrollY + window.innerHeight;
  if (totalHeight >= scrollHeight) {
    clearInterval(timerID);
  }
};
let timerID = setInterval(down, 3000);
"""

response.html.render(timeout=20, sleep=2, script=js_script)
page_html = response.html.html
print(page_html)

Other simpler JS scripts work fine with response.html.render(). I tested my JS script in codepen.io and it works fine. Then I added my JS script to html with DevTool in the browser, it worked fine.
I tried a few slightly different JS scripts, but nothing worked. Of course, I cannot use the parameter scrolldown= because of the unknown number of scrolls.

At first I tried to get the information in other ways, like parsing ajax requests. But I found this to be a very difficult task. I didn't find any clues when researching the queries and responses.


问:
Select HTML element on hover
I am trying to insert in a form a select tag similar to this:

https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select

The only thing thing that I would like to make different from the usual select element that I want the options to be displayed on hover instead on click event.

I was trying this at that particular select element

```<code>.p-type:hover option{
display: block;
}
</code>```

and I also was trying with a dropdown https://www.w3schools.com/howto/howto_css_dropdown.asp At this one my issue is that when I put a  to it the dropdown list justifies/aligns to the label and not to the dropdown box itself.

Title: Select HTML element on hover

Body:
I am trying to insert in a form a select tag similar to this:

https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select

The only thing thing that I would like to make different from the usual select element that I want the options to be displayed on hover instead on click event.

I was trying this at that particular select element

.p-type:hover option{
display: block;
}

and I also was trying with a dropdown https://www.w3schools.com/howto/howto_css_dropdown.asp At this one my issue is that when I put a  to it the dropdown list justifies/aligns to the label and not to the dropdown box itself.


问:
404 when trying to open a PR via pre-populated URL in the browser
Trying to open a BitBucket PR with just the URL, with the dest. and feature branches pre-populated:

```<code>https://bitbucket.org/<repo_name>/pull-requests/new?source=<source_branch>&dest=<destination_branch>
</code>```

This gives me 404:

What would be the proper format?

Body:
Trying to open a BitBucket PR with just the URL, with the dest. and feature branches pre-populated:

https://bitbucket.org/<repo_name>/pull-requests/new?source=<source_branch>&dest=<destination_branch>

This gives me 404:

What would be the proper format?


问:
how to change tomcat catalina log directory name
I try to change catalina directory name for managing logs as date
but This code makes dir likes logs/yyyy-mm-dd or "$(date +%Y-%m-%d)"
How to make dir with date??

this is my logging.properties

```<code>1catalina.org.apache.juli.AsyncFileHandler.level = FINE
1catalina.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs/yyyy-mm-dd
1catalina.org.apache.juli.AsyncFileHandler.prefix = catalina."$(date +%Y-%m-%d)"
1catalina.org.apache.juli.AsyncFileHandler.maxDays = 90
1catalina.org.apache.juli.AsyncFileHandler.encoding = UTF-8
</code>```

Body:
I try to change catalina directory name for managing logs as date
but This code makes dir likes logs/yyyy-mm-dd or "$(date +%Y-%m-%d)"
How to make dir with date??

this is my logging.properties

1catalina.org.apache.juli.AsyncFileHandler.level = FINE
1catalina.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs/yyyy-mm-dd
1catalina.org.apache.juli.AsyncFileHandler.prefix = catalina."$(date +%Y-%m-%d)"
1catalina.org.apache.juli.AsyncFileHandler.maxDays = 90
1catalina.org.apache.juli.AsyncFileHandler.encoding = UTF-8


问:
Upgrading Jenkins running in Kubernetes cluster
I am running Jenkins in Kubernetes, specifically using the jenkins/jenkins: docker image in the pod spec to run the Jenkins instance. Is there any documentation or steps on how to upgrade the Jenkins core version when running it in Kubernetes?
The automatic upgrade in the UI does not work, because when the Jenkins pod restarts, the image downloads the war file with the version in the image tag. So Jenkins never gets upgraded. I have to manually edit the K8s deployment, and change the image to jenkins/jenkins: to successfully upgrade.

Couple questions:

1. Is this the right way to upgrade? What happens when there are conflicts between the two versions (like changes to directory structure , for example), and how can I resolve that?

2. When we update the docker image tag, the current pod (pod A) will terminate and a new pod (pod B) gets spun up with the new image. I noticed that the pod A does not do any clean up before terminating.

When I try to upgrade the Jenkins instance with the upgrade button in the UI, the cleanUp() method ( is called before the pod restarts (I saw the logs). (Note that this upgrade does not work because the docker image tag still has the old core version, but I was just testing what the upgrade button does)

How can I safely clean up Jenkins running on pod A before it terminates?

I have tried safeExit API which does clean up, but then the K8s Jenkins master pod restarts, which I don't want to happen.


问:
webpack css bundling - does webpack reduce css size?
this is react project

app.js

```<code><div class="mt10 box1"></div>
</code>```

style.scss

```<code>.box1 {background: black}
.box2 {background: red}
@for $i from 1 to 10
{
.mt#{$i}{
    margin-top: #{$i}px;
  } // it will be .mt1 {margin-top:1px;} .mt2 {margin-top:2px;} ~  .mt100 {margin-top:100px;}
}
</code>```

and....
build!

bundle.css sample1

```<code>.box1 {background: black}.mt10 {margin-top: 10px}
</code>```

bundle.css sample2

```<code>.bo1 {background: black}.box2 {background: red} .mt1{margin-top:1px;}~ .mt100{margin-top:100px;}
</code>```

i heard that WEBPACK compile sass with its nessessary and minimize code.

(unnessessary class will be disappeared?)

so here is my question.

style.scss will be sample1

style.scss will be sample2

which is correct?

i don't have much knowledge about this.

Body:
this is react project

app.js

style.scss

.box1 {background: black}
.box2 {background: red}
@for $i from 1 to 10
{
.mt#{$i}{
    margin-top: #{$i}px;
  } // it will be .mt1 {margin-top:1px;} .mt2 {margin-top:2px;} ~  .mt100 {margin-top:100px;}
}

and....
build!

bundle.css sample1

.box1 {background: black}.mt10 {margin-top: 10px}

bundle.css sample2

.bo1 {background: black}.box2 {background: red} .mt1{margin-top:1px;}~ .mt100{margin-top:100px;}

i heard that WEBPACK compile sass with its nessessary and minimize code.

(unnessessary class will be disappeared?)

so here is my question.

style.scss will be sample1

style.scss will be sample2

which is correct?

i don't have much knowledge about this.


问:
How to implement password_credential flutter package for web
i want to store my credential to google password manager using this package  password_credential. i need complete example or tutorial for web.</p>


问:
Whatsapp js closed session after some time
I am using whatsapp-js. Everything works fine but after a week or 10 days the session closes. In the console you can see:

```<code>Error: Protocol error (Runtime.callFunctionOn): Session closed. Most likely the page has been closed.
    at CDPSession.send (C:\bots\8353\node_modules\puppeteer\lib\cjs\puppeteer\common\Connection.js:218:35)
    at ExecutionContext._evaluateInternal (C:\bots\8353\node_modules\puppeteer\lib\cjs\puppeteer\common\ExecutionContext.js:204:50)
    at ExecutionContext.evaluate (C:\bots\8353\node_modules\puppeteer\lib\cjs\puppeteer\common\ExecutionContext.js:110:27)
    at DOMWorld.evaluate (C:\bots\8353\node_modules\puppeteer\lib\cjs\puppeteer\common\DOMWorld.js:97:24)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
</code>```

Does anyone know why the session is closed? The cell phone that scanned the QR is no longer connected, could that have something to do with it?

I thought it could be due to inactivity and I scheduled automatic message delivery once a day but after 8 days the same thing happened again.

Body:
I am using whatsapp-js. Everything works fine but after a week or 10 days the session closes. In the console you can see:

Error: Protocol error (Runtime.callFunctionOn): Session closed. Most likely the page has been closed.
    at CDPSession.send (C:\bots\8353\node_modules\puppeteer\lib\cjs\puppeteer\common\Connection.js:218:35)
    at ExecutionContext._evaluateInternal (C:\bots\8353\node_modules\puppeteer\lib\cjs\puppeteer\common\ExecutionContext.js:204:50)
    at ExecutionContext.evaluate (C:\bots\8353\node_modules\puppeteer\lib\cjs\puppeteer\common\ExecutionContext.js:110:27)
    at DOMWorld.evaluate (C:\bots\8353\node_modules\puppeteer\lib\cjs\puppeteer\common\DOMWorld.js:97:24)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

Does anyone know why the session is closed? The cell phone that scanned the QR is no longer connected, could that have something to do with it?

I thought it could be due to inactivity and I scheduled automatic message delivery once a day but after 8 days the same thing happened again.