问:
Jest testing with props
React, typescript, and jest are all new to me.  I have a component, 'myContacts,' displaying tabs and tab panels with contacts; an address book.

Here is a portion of myContacts.

```<code>import ... as needed ...

export default function myContacts( props ){

const { data, link } = props;

const [limit, setLimit] = useState<number>(data.limit);

(handleTabsChange and various other logic)

useEffect(() => {
    const offset = (page - 1) * limit;
    setContactsPerPage(
      entries[currentTab?.activeKey]?.slice(offset, offset + limit)
    );
    setLimit(viewData.limit);
  }, [entries, currentTab?.activeKey, page, limit, data.limit]);

  if (currentTab?.activeKey == null) {
    return null;
  }

return (
 <div>
    <Tabs
            index={tabIndex}
            onChange={handleTabsChange}
          >
            <TabList>
              {tabs.map((item: string) => (
                <Tab key={item}>{item}</Tab>
              ))}
            </TabList>
            <TabPanels>
              {tabs.map((item: string) => (
                <TabPanel key={item}>
                     ...  do some stuff ...
                    />
                  ))}
                </TabPanel>
              ))}
            </TabPanels>
          </Tabs>
          <Container>
            <div className="w-full md:w-8/12">
              <Pagination
                totalEntries={entries[currentTab?.activeKey]?.length}
                limit={data.limit}
                page={page}
                setPage={setPage}
              />
            </div>
          </Container>
    </div>

 );
}
</code>```

Here is the test I am working on. Very simple. Check that myContacts has rendered.

```<code>import { render, screen } from "@testing-library/react";

import myContacts from "../myContacts";

test("render contacts", () => {
  render(<myContacts />);
  expect(screen.getByText(/component myContacts/i)).toBeInTheDocument();
});

</code>```

However, I am getting the following error.

TypeError: Cannot read properties of undefined (reading 'limit')

```<code>  23 |   const { link, route, viewData } = props;
  24 |
> 25 |   const [limit, setLimit] = useState<number>(viewData.limit);
</code>```

My initial thought was to do the following:

```<code>
test("render contacts", () => {
const limit = 5;

  render(<myContacts limit={limit} />);
  expect(screen.getByText(/component myContacts/i)).toBeInTheDocument();
});

</code>```

but this resulted in the same error.

I know this error is because 'limit' is not defined in the test, but I am at a loss on how to define and pass it in the test.

Title: Jest testing with props

Body:
React, typescript, and jest are all new to me.  I have a component, 'myContacts,' displaying tabs and tab panels with contacts; an address book.

Here is a portion of myContacts.

import ... as needed ...

export default function myContacts( props ){

const { data, link } = props;

const [limit, setLimit] = useState<number>(data.limit);

(handleTabsChange and various other logic)

useEffect(() => {
    const offset = (page - 1) * limit;
    setContactsPerPage(
      entries[currentTab?.activeKey]?.slice(offset, offset + limit)
    );
    setLimit(viewData.limit);
  }, [entries, currentTab?.activeKey, page, limit, data.limit]);

  if (currentTab?.activeKey == null) {
    return null;
  }

return (

    <Tabs
            index={tabIndex}
            onChange={handleTabsChange}
          >
            <TabList>
              {tabs.map((item: string) => (
                <Tab key={item}>{item}</Tab>
              ))}
            </TabList>
            <TabPanels>
              {tabs.map((item: string) => (
                <TabPanel key={item}>
                     ...  do some stuff ...
                    />
                  ))}
                </TabPanel>
              ))}
            </TabPanels>
          </Tabs>
          <Container>

              <Pagination
                totalEntries={entries[currentTab?.activeKey]?.length}
                limit={data.limit}
                page={page}
                setPage={setPage}
              />

          </Container>

 );
}

Here is the test I am working on. Very simple. Check that myContacts has rendered.

import { render, screen } from "@testing-library/react";

import myContacts from "../myContacts";

test("render contacts", () => {
  render(<myContacts />);
  expect(screen.getByText(/component myContacts/i)).toBeInTheDocument();
});

However, I am getting the following error.

TypeError: Cannot read properties of undefined (reading 'limit')

  23 |   const { link, route, viewData } = props;
  24 |
> 25 |   const [limit, setLimit] = useState<number>(viewData.limit);

My initial thought was to do the following:

test("render contacts", () => {
const limit = 5;

  render(<myContacts limit={limit} />);
  expect(screen.getByText(/component myContacts/i)).toBeInTheDocument();
});

but this resulted in the same error.

I know this error is because 'limit' is not defined in the test, but I am at a loss on how to define and pass it in the test.


来源: stackexchange

问:
Error when loading json spritesheet in react-pixi
I am using Pixi 6.5.8 and react-pixi, i am trying to load sprite sheet from json file. I am using method i found on codepen examples posted on react-pixi documentation(https://codepen.io/inlet/pen/VwLLYme).

Json was generated from TexturePacker, with output specified for PIXI, so i guess this is not a problem, the same sprite sheet worked perfectly when i used it in Pixi v7 and Assets.load method, however i am forced to work with react now).

Thats the code

```<code>export default function JetFighter() {
const [frames, setFrames] = React.useState([]);
const app = useApp();

const spritesheet = "./assets/Sprites/ship_2_idle-0.json";

React.useEffect(() => {

app.loader.add(spritesheet).load((_, resource) => {
  setFrames(
    Object.keys(resource[spritesheet].data.frames).map((frame) =>
      PIXI.Texture.from(frame)
    )
  );
});
}, []);

if (frames.length === 0) {
return null;
}

return (
<Container x={250} y={250}>
  <AnimatedSprite
    animationSpeed={0.5}
    isPlaying={true}
    textures={frames}
    anchor={0.5}
  />
</Container>
);
}
</code>```

Error

I've tried to use Assets.load from  "@pixi/assets":^6.5.8", but with this method i am getting such error:

Error from Assets.load method

Do you have any idea how to solve this issue?

ContentLicense: CC BY-SA 4.0

Body:
I am using Pixi 6.5.8 and react-pixi, i am trying to load sprite sheet from json file. I am using method i found on codepen examples posted on react-pixi documentation(https://codepen.io/inlet/pen/VwLLYme).

Json was generated from TexturePacker, with output specified for PIXI, so i guess this is not a problem, the same sprite sheet worked perfectly when i used it in Pixi v7 and Assets.load method, however i am forced to work with react now).

Thats the code

export default function JetFighter() {
const [frames, setFrames] = React.useState([]);
const app = useApp();

const spritesheet = "./assets/Sprites/ship_2_idle-0.json";

React.useEffect(() => {

app.loader.add(spritesheet).load((_, resource) => {
  setFrames(
    Object.keys(resource[spritesheet].data.frames).map((frame) =>
      PIXI.Texture.from(frame)
    )
  );
});
}, []);

if (frames.length === 0) {
return null;
}

return (
<Container x={250} y={250}>
  <AnimatedSprite
    animationSpeed={0.5}
    isPlaying={true}
    textures={frames}
    anchor={0.5}
  />
</Container>
);
}

Error

I've tried to use Assets.load from  "@pixi/assets":^6.5.8", but with this method i am getting such error:

Error from Assets.load method

Do you have any idea how to solve this issue?


问:
unable to display in image view the image received from socket programming at the client side
well i wrote code in python for server and i am applying simple aruco detection on the video from my webcam and i want to display the result in my android app . But i unable to do so.

After runnig the app  it shows these errors
Throwing OutOfMemoryError "Failed to allocate a 268435468 byte allocation with 25165824 free bytes and 380MB until OOM, target footprint 163122328, growth limit 536870912" (VmSize 6267440 kB)

i tried to change the bytes i am allocating to the array, i also tried solution present here --

Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

but still i am getting same error

here is my code for

mainactivity.java

```<code>

package com.example.drone3;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.ContactsContract;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import android.widget.VideoView;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {
    Button Land,up,forward,rotate;
    EditText editTextAddress, editTextPort;
    Button buttonConnect;
    Switch am;
    ImageView imageV;
    private ImageView screen;
    public void abort(View view){
        up.setEnabled(false);
        forward.setEnabled(false);
        rotate.setEnabled(false);
        am.setEnabled(false);

    }
    public void onclick(View view){
        Button b=(Button) view;
        String s=b.getText().toString();
        Log.i("command is:",s);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(getSupportActionBar()!=null)
            this.getSupportActionBar().hide();
        editTextAddress = (EditText)findViewById(R.id.address);
        editTextPort = (EditText)findViewById(R.id.port);
        buttonConnect = (Button)findViewById(R.id.connect);
        buttonConnect.setOnClickListener(buttonConnectOnClickListener);
        am=(Switch) findViewById(R.id.switch1);
        Land=(Button) findViewById(R.id.landbutton);
        up=(Button) findViewById(R.id.upbutton);
        forward=(Button) findViewById(R.id.forwardbutton);
        Log.i("this shit is working:","57");
        rotate=(Button) findViewById(R.id.rotatebutton);
        am.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(am.isChecked()){
                    Land.setEnabled(false);
                    up.setEnabled(false);
                    forward.setEnabled(false);
                    rotate.setEnabled(false);

                }
                else{
                    Land.setEnabled(true);
                    up.setEnabled(true);
                    forward.setEnabled(true);
                    rotate.setEnabled(true);
                }
            }
        });
        if(Build.VERSION.SDK_INT>9){
            StrictMode.ThreadPolicy BackgroundTask=
                    new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(BackgroundTask);
        }
    }

    View.OnClickListener buttonConnectOnClickListener =
            new View.OnClickListener(){

                @Override
                public void onClick(View arg0) {
                    MyClientTask myClientTask = new MyClientTask(
                            editTextAddress.getText().toString(),
                            Integer.parseInt(editTextPort.getText().toString()));
                    myClientTask.execute();
                }};

    public class MyClientTask extends AsyncTask<Void, Void, Void> {

        String dstAddress;
        int dstPort;
        MyClientTask(String addr, int port){
            dstAddress = addr;
            dstPort = port;
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            InputStream inputStream;

                try {
                    Socket socket = new Socket(dstAddress, dstPort);
                    inputStream = socket.getInputStream();
                    ByteArrayOutputStream byteArrayOutputStream =
                            new ByteArrayOutputStream(4*1024);
                    byte[] buffer = new byte[4*1024 ];

                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        byteArrayOutputStream.write(buffer, 0, bytesRead);
                    }
                    Log.i("this shit is working:",""+buffer.length);
                    Bitmap bm = BitmapFactory.decodeByteArray(buffer, 0,buffer.length);

                    imageV.setImageBitmap(bm);
                    Log.i("this packet",buffer.toString());

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

        }

    }

}

</code>```

androidmanifest.xml

```<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"/>

    <application
        android:usesCleartextTraffic="true"
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:hardwareAccelerated="false"
        android:largeHeap="true"
        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.Drone3"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <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>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/imageview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/landbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="40dp"
        android:layout_marginStart="16dp"
        android:onClick="abort"
        android:text="Land"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/rotatebutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="40dp"
        android:layout_marginStart="36dp"
        android:onClick="onclick"
        android:text="rotate"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/landbutton" />

    <Button
        android:id="@+id/upbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="40dp"
        android:layout_marginStart="40dp"
        android:onClick="onclick"
        android:text="Up"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/rotatebutton" />

    <Button
        android:id="@+id/forwardbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="40dp"
        android:layout_marginStart="28dp"
        android:onClick="onclick"
        android:text="Forward"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/upbutton" />

    <Switch
        android:id="@+id/switch1"
        android:layout_width="132dp"
        android:layout_height="48dp"
        android:layout_marginBottom="40dp"
        android:layout_marginEnd="40dp"
        android:text="M/A"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="162dp"
        android:layout_height="66dp"
        android:gravity="center"
        android:text="OmProduction"
        android:textAlignment="center"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.595" />

    <ImageView
        android:id="@+id/display"
        android:layout_width="705dp"
        android:layout_height="288dp"
        android:layout_marginEnd="16dp"
        android:layout_marginTop="4dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/ic_launcher_foreground" />

    <EditText
        android:id="@+id/address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:hint="dstAddress"
        android:minHeight="48dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <EditText
        android:id="@+id/port"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:hint="dstPort"
        android:minHeight="48dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/address" />

    <Button
        android:id="@+id/connect"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Connect..."
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/port" />

</androidx.constraintlayout.widget.ConstraintLayout>

</code>```

here is my python code for server

```<code>import socket
import cv2
import pickle
import struct
from cv2 import aruco
import numpy as np
import jpysocket
marker_dict = aruco.Dictionary_get(aruco.DICT_4X4_50)
param_markers = aruco.DetectorParameters_create()
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host_name = socket.gethostname()
print("host name", host_name)
host_ip = socket.gethostbyname(host_name)
print('HOST IP:', host_ip)
port = 9999
socket_address = (host_ip, port)
server_socket.bind(socket_address)
server_socket.listen(5)
print("LISTENING AT:", socket_address)

while True:
    client_socket, addr = server_socket.accept()
    print('GOT CONNECTION FROM:', addr)
    if client_socket:
        vid = cv2.VideoCapture(0)
        while(vid.isOpened()):
            ret, frame = vid.read()
            gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            marker_corners, marker_IDs, reject = aruco.detectMarkers(
            gray_frame, marker_dict, parameters=param_markers
            )
            if marker_corners:
                for ids, corners in zip(marker_IDs, marker_corners):
                    cv2.polylines(
                        frame, [corners.astype(np.int32)], True, (0, 255, 255), 4, cv2.LINE_AA
                    )
                    corners = corners.reshape(4, 2)
                    corners = corners.astype(int)
                    top_right = corners[0].ravel()
                    top_left = corners[1].ravel()
                    bottom_right = corners[2].ravel()
                    bottom_left = corners[3].ravel()
                    cv2.putText(
                        frame,
                        f"id: {ids[0]}",
                        top_right,
                        cv2.FONT_HERSHEY_PLAIN,
                        1.3,
                        (200, 100, 0),
                        2,
                        cv2.LINE_AA,
                    )
            a = pickle.dumps(frame)
            message = a
            print(len(message))
            client_socket.send(message)
            cv2.imshow('TRANSMITTING VIDEO', frame)
            key = cv2.waitKey(1) & 0xFF
            if key == 27:
                client_socket.close()
</code>```

Body:
well i wrote code in python for server and i am applying simple aruco detection on the video from my webcam and i want to display the result in my android app . But i unable to do so.

After runnig the app  it shows these errors
Throwing OutOfMemoryError "Failed to allocate a 268435468 byte allocation with 25165824 free bytes and 380MB until OOM, target footprint 163122328, growth limit 536870912" (VmSize 6267440 kB)

i tried to change the bytes i am allocating to the array, i also tried solution present here --

Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

but still i am getting same error

here is my code for

mainactivity.java

package com.example.drone3;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.ContactsContract;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import android.widget.VideoView;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {
    Button Land,up,forward,rotate;
    EditText editTextAddress, editTextPort;
    Button buttonConnect;
    Switch am;
    ImageView imageV;
    private ImageView screen;
    public void abort(View view){
        up.setEnabled(false);
        forward.setEnabled(false);
        rotate.setEnabled(false);
        am.setEnabled(false);

    }
    public void onclick(View view){
        Button b=(Button) view;
        String s=b.getText().toString();
        Log.i("command is:",s);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(getSupportActionBar()!=null)
            this.getSupportActionBar().hide();
        editTextAddress = (EditText)findViewById(R.id.address);
        editTextPort = (EditText)findViewById(R.id.port);
        buttonConnect = (Button)findViewById(R.id.connect);
        buttonConnect.setOnClickListener(buttonConnectOnClickListener);
        am=(Switch) findViewById(R.id.switch1);
        Land=(Button) findViewById(R.id.landbutton);
        up=(Button) findViewById(R.id.upbutton);
        forward=(Button) findViewById(R.id.forwardbutton);
        Log.i("this shit is working:","57");
        rotate=(Button) findViewById(R.id.rotatebutton);
        am.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(am.isChecked()){
                    Land.setEnabled(false);
                    up.setEnabled(false);
                    forward.setEnabled(false);
                    rotate.setEnabled(false);

                }
                else{
                    Land.setEnabled(true);
                    up.setEnabled(true);
                    forward.setEnabled(true);
                    rotate.setEnabled(true);
                }
            }
        });
        if(Build.VERSION.SDK_INT>9){
            StrictMode.ThreadPolicy BackgroundTask=
                    new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(BackgroundTask);
        }
    }

    View.OnClickListener buttonConnectOnClickListener =
            new View.OnClickListener(){

                @Override
                public void onClick(View arg0) {
                    MyClientTask myClientTask = new MyClientTask(
                            editTextAddress.getText().toString(),
                            Integer.parseInt(editTextPort.getText().toString()));
                    myClientTask.execute();
                }};

    public class MyClientTask extends AsyncTask<Void, Void, Void> {

        String dstAddress;
        int dstPort;
        MyClientTask(String addr, int port){
            dstAddress = addr;
            dstPort = port;
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            InputStream inputStream;

                try {
                    Socket socket = new Socket(dstAddress, dstPort);
                    inputStream = socket.getInputStream();
                    ByteArrayOutputStream byteArrayOutputStream =
                            new ByteArrayOutputStream(4*1024);
                    byte[] buffer = new byte[4*1024 ];

                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        byteArrayOutputStream.write(buffer, 0, bytesRead);
                    }
                    Log.i("this shit is working:",""+buffer.length);
                    Bitmap bm = BitmapFactory.decodeByteArray(buffer, 0,buffer.length);

                    imageV.setImageBitmap(bm);
                    Log.i("this packet",buffer.toString());

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

        }

    }

}

androidmanifest.xml

<?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"/>

    <application
        android:usesCleartextTraffic="true"
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:hardwareAccelerated="false"
        android:largeHeap="true"
        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.Drone3"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <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>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/imageview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/landbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="40dp"
        android:layout_marginStart="16dp"
        android:onClick="abort"
        android:text="Land"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/rotatebutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="40dp"
        android:layout_marginStart="36dp"
        android:onClick="onclick"
        android:text="rotate"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/landbutton" />

    <Button
        android:id="@+id/upbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="40dp"
        android:layout_marginStart="40dp"
        android:onClick="onclick"
        android:text="Up"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/rotatebutton" />

    <Button
        android:id="@+id/forwardbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="40dp"
        android:layout_marginStart="28dp"
        android:onClick="onclick"
        android:text="Forward"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/upbutton" />

    <Switch
        android:id="@+id/switch1"
        android:layout_width="132dp"
        android:layout_height="48dp"
        android:layout_marginBottom="40dp"
        android:layout_marginEnd="40dp"
        android:text="M/A"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="162dp"
        android:layout_height="66dp"
        android:gravity="center"
        android:text="OmProduction"
        android:textAlignment="center"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.595" />

    <ImageView
        android:id="@+id/display"
        android:layout_width="705dp"
        android:layout_height="288dp"
        android:layout_marginEnd="16dp"
        android:layout_marginTop="4dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/ic_launcher_foreground" />

    <EditText
        android:id="@+id/address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:hint="dstAddress"
        android:minHeight="48dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <EditText
        android:id="@+id/port"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:hint="dstPort"
        android:minHeight="48dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/address" />

    <Button
        android:id="@+id/connect"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Connect..."
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/port" />

</androidx.constraintlayout.widget.ConstraintLayout>

here is my python code for server

import socket
import cv2
import pickle
import struct
from cv2 import aruco
import numpy as np
import jpysocket
marker_dict = aruco.Dictionary_get(aruco.DICT_4X4_50)
param_markers = aruco.DetectorParameters_create()
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host_name = socket.gethostname()
print("host name", host_name)
host_ip = socket.gethostbyname(host_name)
print('HOST IP:', host_ip)
port = 9999
socket_address = (host_ip, port)
server_socket.bind(socket_address)
server_socket.listen(5)
print("LISTENING AT:", socket_address)

while True:
    client_socket, addr = server_socket.accept()
    print('GOT CONNECTION FROM:', addr)
    if client_socket:
        vid = cv2.VideoCapture(0)
        while(vid.isOpened()):
            ret, frame = vid.read()
            gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            marker_corners, marker_IDs, reject = aruco.detectMarkers(
            gray_frame, marker_dict, parameters=param_markers
            )
            if marker_corners:
                for ids, corners in zip(marker_IDs, marker_corners):
                    cv2.polylines(
                        frame, [corners.astype(np.int32)], True, (0, 255, 255), 4, cv2.LINE_AA
                    )
                    corners = corners.reshape(4, 2)
                    corners = corners.astype(int)
                    top_right = corners[0].ravel()
                    top_left = corners[1].ravel()
                    bottom_right = corners[2].ravel()
                    bottom_left = corners[3].ravel()
                    cv2.putText(
                        frame,
                        f"id: {ids[0]}",
                        top_right,
                        cv2.FONT_HERSHEY_PLAIN,
                        1.3,
                        (200, 100, 0),
                        2,
                        cv2.LINE_AA,
                    )
            a = pickle.dumps(frame)
            message = a
            print(len(message))
            client_socket.send(message)
            cv2.imshow('TRANSMITTING VIDEO', frame)
            key = cv2.waitKey(1) & 0xFF
            if key == 27:
                client_socket.close()


问:
Video Loop issues in Lua Android App not working?
There is an app on our device, the app contains a place to hold a video which should loop. however when we put our video into the app it doesnt loop smoothly. We have tried using GIFF and MP4 formats.
GIFF Freezes and doesnt move any further, mp4 has a jump where the screen turns blue for around 0.5 - 1 second.

the app is an android device
the app is not public its just an app designed for a game
the app doesnt have any video settings to change features of any video

The app is written in lua

Using a GIFF i thought would loop automatically however it froze.

creating a smooth MP4 i thought would work however there was a jump when the file was uploaded.


问:
Problems with mounting .aws credentials directory inside a docker image
I have the following docker compose:

```<code>services:
  run_program:
    image: image:1
    entrypoint: python main.py
    environment:
      - HOME=/home
    volumes:
      - $HOME/.aws:/home/.aws:ro
</code>```

This should allow me to access host ~/.aws/credentials inside docker. However boto3 is spitting this error:

```<code>botocore.exceptions.ProfileNotFound: The config profile (default) could not be found
</code>```

When I open an interactive docker session on that image like so:

```<code>docker run -e "HOME=/home" -v $HOME/.aws:/home/.aws -it --entrypoint bash image:1
</code>```

And I check what is inside /home/.aws I see a credentials file there. But when I try to do cat /home/.aws/credentials to check the contents I get:

```<code>cat: /home/.aws/credentials: Is a directory
</code>```

And the directory is empty.
According to all tutorials and documentations this should work. All files inside host ~/.aws have read permissions and ~/.aws/credentials on host have the default profile set up.

If it makes any difference my host machine is a Mac, and docker daemon is provided by minikube.

UPDATE:

After some more digging I see I should first mount the host directory in minikube VMlike this:

```<code>minikube mount ~/.aws/:/host/.aws
</code>```

but trying this gives the following error:

```<code>Exiting due to GUEST_MOUNT: mount with cmd /bin/bash -c "sudo mount -t 9p -o dfltgid=$(grep ^docker: /etc/group | cut -d: -f3),dfltuid=$(id -u docker),msize=262144,port=55424,trans=tcp,version=9p2000.L 192.168.64.1 /host/.aws" : /bin/bash -c "sudo mount -t 9p -o dfltgid=$(grep ^docker: /etc/group | cut -d: -f3),dfltuid=$(id -u docker),msize=262144,port=55424,trans=tcp,version=9p2000.L 192.168.64.1 /host/.aws": Process exited with status 32
stdout:

stderr:
mount: /host/.aws: mount(2) system call failed: Connection refused.
</code>```

And this seems to be related to this issue however I haven't figured it out how to solve this on a Mac yet.

Body:
I have the following docker compose:

services:
  run_program:
    image: image:1
    entrypoint: python main.py
    environment:
      - HOME=/home
    volumes:
      - $HOME/.aws:/home/.aws:ro

This should allow me to access host ~/.aws/credentials inside docker. However boto3 is spitting this error:

botocore.exceptions.ProfileNotFound: The config profile (default) could not be found

When I open an interactive docker session on that image like so:

docker run -e "HOME=/home" -v $HOME/.aws:/home/.aws -it --entrypoint bash image:1

And I check what is inside /home/.aws I see a credentials file there. But when I try to do cat /home/.aws/credentials to check the contents I get:

cat: /home/.aws/credentials: Is a directory

And the directory is empty.
According to all tutorials and documentations this should work. All files inside host ~/.aws have read permissions and ~/.aws/credentials on host have the default profile set up.

If it makes any difference my host machine is a Mac, and docker daemon is provided by minikube.

UPDATE:

After some more digging I see I should first mount the host directory in minikube VMlike this:

minikube mount ~/.aws/:/host/.aws

but trying this gives the following error:

Exiting due to GUEST_MOUNT: mount with cmd /bin/bash -c "sudo mount -t 9p -o dfltgid=$(grep ^docker: /etc/group | cut -d: -f3),dfltuid=$(id -u docker),msize=262144,port=55424,trans=tcp,version=9p2000.L 192.168.64.1 /host/.aws" : /bin/bash -c "sudo mount -t 9p -o dfltgid=$(grep ^docker: /etc/group | cut -d: -f3),dfltuid=$(id -u docker),msize=262144,port=55424,trans=tcp,version=9p2000.L 192.168.64.1 /host/.aws": Process exited with status 32
stdout:

stderr:
mount: /host/.aws: mount(2) system call failed: Connection refused.

And this seems to be related to this issue however I haven't figured it out how to solve this on a Mac yet.


问:
Object moving between random positions, how to put speed limitation with CSS or Javascript?
I have a keyframe animation in css like this:

```<code>@keyframes anim-target1 {
    0% {
    scale: 0.24;
        transform: translateX(0) translateY(0);
    }

    100% {
        scale: 0.24;
        transform: translateX(-650px) translateY(-25px);
    }
}
</code>```

Now I want to make the object go forth and back randomly in between these two points, stopping at random positions not having to go to the start or end before going the other way. And having it be random every time it is run, otherwise I would obviously just make the keyframes for it. The keyframes being like a path it can not deviate from. Is there a way to do this simple with css and javascript? Taking scale into consideration, should it be two points between different scales also (I only have for X and Y). Anyone up for the task to solve?

I have tried making a script that creates random keyframes in between 0 and 100, and it works, but the speed is not consistent but fluxate. Somehow to make a speed limit on how fast the object can move no matter how far or short it travels.

Here is the javascript I have so far to make the random positions:

```<code>// Generate a random number of intermediate positions
    var numPositions = Math.floor(Math.random() * 10) + 1;

    // Generate the keyframes string
    var keyframes = "@keyframes anim-target1 {\n";
    keyframes += "  0% { scale: 0.24; transform: translateX(0) translateY(0); }\n";
    for (var i = 1; i <= numPositions; i++) {
        // Generate random values for the translateX and translateY properties
        var translateX = Math.floor(Math.random() * 651);
        var translateY = Math.floor(Math.random() * 26);
        keyframes += "  " + (i * 10) + "% { scale: 0.24; transform: translateX(" + translateX + "px) translateY(" + translateY + "px); }\n";
    }
    keyframes += "  100% { scale: 0.24; transform: translateX(-650px) translateY(-25px); }\n";
    keyframes += "}";

    // Inject the keyframes string into the page
    var style = document.createElement("style");
    style.innerHTML = keyframes;
    document.head.appendChild(style);
</code>```

I figure it would be better maybe to make all the animation points in javascript somehow might be better, if anyone has any suggestions?

I was expecting this solution I have could be somehow easily controled to have a speed limit and not determin by the animation time. But yet to figure it out.

Body:
I have a keyframe animation in css like this:

@keyframes anim-target1 {
    0% {
    scale: 0.24;
        transform: translateX(0) translateY(0);
    }

    100% {
        scale: 0.24;
        transform: translateX(-650px) translateY(-25px);
    }
}

Now I want to make the object go forth and back randomly in between these two points, stopping at random positions not having to go to the start or end before going the other way. And having it be random every time it is run, otherwise I would obviously just make the keyframes for it. The keyframes being like a path it can not deviate from. Is there a way to do this simple with css and javascript? Taking scale into consideration, should it be two points between different scales also (I only have for X and Y). Anyone up for the task to solve?

I have tried making a script that creates random keyframes in between 0 and 100, and it works, but the speed is not consistent but fluxate. Somehow to make a speed limit on how fast the object can move no matter how far or short it travels.

Here is the javascript I have so far to make the random positions:

// Generate a random number of intermediate positions
    var numPositions = Math.floor(Math.random() * 10) + 1;

    // Generate the keyframes string
    var keyframes = "@keyframes anim-target1 {\n";
    keyframes += "  0% { scale: 0.24; transform: translateX(0) translateY(0); }\n";
    for (var i = 1; i <= numPositions; i++) {
        // Generate random values for the translateX and translateY properties
        var translateX = Math.floor(Math.random() * 651);
        var translateY = Math.floor(Math.random() * 26);
        keyframes += "  " + (i * 10) + "% { scale: 0.24; transform: translateX(" + translateX + "px) translateY(" + translateY + "px); }\n";
    }
    keyframes += "  100% { scale: 0.24; transform: translateX(-650px) translateY(-25px); }\n";
    keyframes += "}";

    // Inject the keyframes string into the page
    var style = document.createElement("style");
    style.innerHTML = keyframes;
    document.head.appendChild(style);

I figure it would be better maybe to make all the animation points in javascript somehow might be better, if anyone has any suggestions?

I was expecting this solution I have could be somehow easily controled to have a speed limit and not determin by the animation time. But yet to figure it out.


问:
Client-side issue collection
I would like to use a service that allows a user to record a video of an issue. For instance if they want to show me how a website is crashing they should be able to record the video and walk through the steps in the browser.

Ideally this service would send the user a link they can just click and run.

Also it would be great if the service can collect diagnostic information such as hardware and software profiles.

I'm looking for all possible options available so I can find the right one for me. If you know of anything like that please post, thanks!

Title: Client-side issue collection


问:
How to scroll on infinite scrolling or lazy loading elements on the follower list from Instagram?
I want to get username from Instagram followers. However, Instagram uses lazy loading elements to get all the data

this is the code that I made, but it doesn't scroll in the element list of the follower

```<code>
driver.get("http://www.instagram.com")

# target username
username = WebDriverWait(
    driver, 10).until(EC.element_to_be_clickable(
        (By.CSS_SELECTOR, "input[name='username']")))

# target Password
password = WebDriverWait(
    driver, 10).until(EC.element_to_be_clickable(
        (By.CSS_SELECTOR, "input[name='password']")))

# enter username and password
username.clear()
username.send_keys("username")
password.clear()
password.send_keys("password")

# target the login button and click it
button = WebDriverWait(
    driver, 2).until(EC.element_to_be_clickable(
        (By.CSS_SELECTOR, "button[type='submit']"))).click()

driver.get("https://www.instagram.com/username/followers/")

for i in range(1,100):
   driver.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight")
   time.sleep(1)
</code>```

how to do scrolling inside the element? so that you can get username data from followers

Body:
I want to get username from Instagram followers. However, Instagram uses lazy loading elements to get all the data

this is the code that I made, but it doesn't scroll in the element list of the follower

driver.get("http://www.instagram.com")

# target username
username = WebDriverWait(
    driver, 10).until(EC.element_to_be_clickable(
        (By.CSS_SELECTOR, "input[name='username']")))

# target Password
password = WebDriverWait(
    driver, 10).until(EC.element_to_be_clickable(
        (By.CSS_SELECTOR, "input[name='password']")))

# enter username and password
username.clear()
username.send_keys("username")
password.clear()
password.send_keys("password")

# target the login button and click it
button = WebDriverWait(
    driver, 2).until(EC.element_to_be_clickable(
        (By.CSS_SELECTOR, "button[type='submit']"))).click()

driver.get("https://www.instagram.com/username/followers/")

for i in range(1,100):
   driver.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight")
   time.sleep(1)

how to do scrolling inside the element? so that you can get username data from followers


问:
s3 write speed is too slow - is there a way to speed it up?
We are moving from NFS to S3 but I am not happy with the write performance.

How can I speed it up ? Are there any configurations to use while moving large files?

Now it's around ~10MB/s vs our regular NFS filesystem 200MB/s ie 20 times slower.

I am curious about the general write performance you guys see on your system.

My observations using s3cmd version 2.1.0:

Put a 4gb tar file on s3 storage shows 8.45 MB/s

upload: '' -> 's3://yetest/backups/si106-251/si106-251.20221219202432.tgz' [part 299, 15MB]
15728640 of 15728640 100% in 1s 8.45 MB/s done

upload: '' -> 's3://yetest/backups/si106-251/si106-251.20221219202432.tgz' [part 299, 15MB]
15728640 of 15728640 100% in 1s 8.45 MB/s done <------ 8.45MB/s


问:
There is a way to track who use a git submodule?
I am using a self hosted git platform (gitea) and working with submodules. My aim is to know which repo use a submodule, in order to track them reversely. For example, I want to know every repository that contains the submodule "display" to update them every time that the "display" repo has a bug fix.

Anyone know a way to do that? Thanks.

I've tried some package managements, but no one that I know give me this traceback.


问:
What is an efficient way to manage an array of Javascript references (IJSObjectReference) in Blazor?
Consider a Javascript function like queryLocalFonts (not mine so "don't use this, use Blazor" is not an option) that returns an array of objects, each could have a few properties as well as methods, making keeping a reference of them (IJSObjectReference) neccessary:

class Foo {
    id = 1;
    name = "foo";

    doSomething1() { return "a"; }
    doSomething2() { return 1; }
}

function getAllFoos() {} // Return a Foo[]
```
<p>From Blazor .NET code, I need to get all <code>Foo</code> instances, most of the time I only care about <code>id</code> and <code>name</code>. However sometimes I need a specific <code>Foo</code> instance and call their functions:</p>
<pre class="lang-cs prettyprint-override"><code>@inject IJSRuntime Js;
// ...
var foos = await Js.InvokeAsync<IJSObjectReference>();
</code>```

I cannot keep it as IJSObjectReference[] or IEnumerable<IJSObjectReference>. Now iterating over foos is not simple. I have to write an interop method for each item. For example:

getFooRef(arr, index) { return arr[index]; }
getFooName(arr, index) { return arr[index].name }
doSomething1ForFoo(arr, index) { return arr[index].doSomething1(); }
doSomething1ForFoos(arr) { /* ... */ }
```
<p>And I am not the end user, I am writing a class library. To "safeguard" the reference, I could create classes like this:</p>
<pre class="lang-cs prettyprint-override"><code>    class FooCollection
    {
        readonly IJSObjectReference jsRef;
        readonly IJSRuntime js;
        internal FooCollection(IJSObjectReference jsRef, IJSRuntime js)
        {
            this.jsRef = jsRef;
            this.js = js;
        }

        public async Task<Foo> GetItem(int index)
        {
            var fooRef = await js.InvokeAsync<IJSObjectReference>("getFooItem", this.jsRef, index);
            return new Foo(fooRef, js);
        }
    }

// I have to code Foo class similarly
</code>```

IMO, this is not very nice as iterating the collection is not easy (not without one "round-trip" call for each item unless I write an interop JS method), a lot of code has to be written for Foo and FooCollection.

Is there a more clever way to manage this?

Body:
Consider a Javascript function like queryLocalFonts (not mine so "don't use this, use Blazor" is not an option) that returns an array of objects, each could have a few properties as well as methods, making keeping a reference of them (IJSObjectReference) neccessary:

class Foo {
    id = 1;
    name = "foo";

    doSomething1() { return "a"; }
    doSomething2() { return 1; }
}

function getAllFoos() {} // Return a Foo[]

From Blazor .NET code, I need to get all Foo instances, most of the time I only care about id and name. However sometimes I need a specific Foo instance and call their functions:

@inject IJSRuntime Js;
// ...
var foos = await Js.InvokeAsync<IJSObjectReference>();

I cannot keep it as IJSObjectReference[] or IEnumerable<IJSObjectReference>. Now iterating over foos is not simple. I have to write an interop method for each item. For example:

getFooRef(arr, index) { return arr[index]; }
getFooName(arr, index) { return arr[index].name }
doSomething1ForFoo(arr, index) { return arr[index].doSomething1(); }
doSomething1ForFoos(arr) { /* ... */ }

And I am not the end user, I am writing a class library. To "safeguard" the reference, I could create classes like this:

    class FooCollection
    {
        readonly IJSObjectReference jsRef;
        readonly IJSRuntime js;
        internal FooCollection(IJSObjectReference jsRef, IJSRuntime js)
        {
            this.jsRef = jsRef;
            this.js = js;
        }

        public async Task<Foo> GetItem(int index)
        {
            var fooRef = await js.InvokeAsync<IJSObjectReference>("getFooItem", this.jsRef, index);
            return new Foo(fooRef, js);
        }
    }

// I have to code Foo class similarly

IMO, this is not very nice as iterating the collection is not easy (not without one "round-trip" call for each item unless I write an interop JS method), a lot of code has to be written for Foo and FooCollection.

Is there a more clever way to manage this?


问:
About steam-user module on csgo
I am logging in to steam by entering username and password and logging into csgo. And I want to login to a community server by sending a message to the console or by direct command, but I guess the "steam-user" module does not support this. Can you suggest another module code that is compatible with this module?

```<code>steam.gamesPlayed([730]);

steam.on('appLaunched', (appid) => {
    console.log("Game is started: ", appid);
</code>```

I tried to use sendtoGC command but I still do not know how it is working. I am waiting for your reply.

I am trying to join steam by username and password. Then starting csgo and connect a community server by ip and port. But I couldn't send a connect command to console or directly connect server.

Title: About steam-user module on csgo

Body:
I am logging in to steam by entering username and password and logging into csgo. And I want to login to a community server by sending a message to the console or by direct command, but I guess the "steam-user" module does not support this. Can you suggest another module code that is compatible with this module?

steam.gamesPlayed([730]);

steam.on('appLaunched', (appid) => {
    console.log("Game is started: ", appid);

I tried to use sendtoGC command but I still do not know how it is working. I am waiting for your reply.

I am trying to join steam by username and password. Then starting csgo and connect a community server by ip and port. But I couldn't send a connect command to console or directly connect server.


问:
How to write promises and connections while executing multiple Mysql queries in Nodejs?
How can I use multiple queries while constructing promises.
Below is the example code of context.

```<code>const mysql = require('mysql');

const pool = mysql.createPool({
    connectionLimit: 10,
    password: “yourDBpassword”,
    user: “yourusername”,
    database: “yourDBname”,
    host: “locahost”,
    port: “yourDBport”

});
SelectAllElements = () =>{
    return new Promise((resolve, reject)=>{
        pool.query('SELECT * FROM DB_table ',  (error, elements)=>{
            if(error){
                return reject(error);
            }
            return resolve(elements);
        });
    });
};
</code>```

Also, do I need to write db.getconnection everytime I write query functions?  Is it possible to end connection without using constructor as it's done below?

```<code>const mysql = require( 'mysql' );
class Database {
    constructor( config ) {
        this.connection = mysql.createConnection( config );
    }
    query( sql, args ) {
        return new Promise( ( resolve, reject ) => {
            this.connection.query( sql, args, ( err, rows ) => {
                if ( err )
                    return reject( err );
                resolve( rows );
            } );
        } );
    }
    close() {
        return new Promise( ( resolve, reject ) => {
            this.connection.end( err => {
                if ( err )
                    return reject( err );
                resolve();
            } );
        } );
    }
}
</code>```

Body:
How can I use multiple queries while constructing promises.
Below is the example code of context.

const mysql = require('mysql');

const pool = mysql.createPool({
    connectionLimit: 10,
    password: “yourDBpassword”,
    user: “yourusername”,
    database: “yourDBname”,
    host: “locahost”,
    port: “yourDBport”

});
SelectAllElements = () =>{
    return new Promise((resolve, reject)=>{
        pool.query('SELECT * FROM DB_table ',  (error, elements)=>{
            if(error){
                return reject(error);
            }
            return resolve(elements);
        });
    });
};

Also, do I need to write db.getconnection everytime I write query functions?  Is it possible to end connection without using constructor as it's done below?

const mysql = require( 'mysql' );
class Database {
    constructor( config ) {
        this.connection = mysql.createConnection( config );
    }
    query( sql, args ) {
        return new Promise( ( resolve, reject ) => {
            this.connection.query( sql, args, ( err, rows ) => {
                if ( err )
                    return reject( err );
                resolve( rows );
            } );
        } );
    }
    close() {
        return new Promise( ( resolve, reject ) => {
            this.connection.end( err => {
                if ( err )
                    return reject( err );
                resolve();
            } );
        } );
    }
}


问:
C# selenium how to filter web resource like cefsharp
when I use CEFSharp I can using ResourceRequestHandler class to filter web resource

and I can chooce use or not.

for example

```<code>        protected override IResponseFilter GetResourceResponseFilter(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response)
        {
            var url = request.Url.ToLower();

            if (url.Contains("https://aaaa.com/demo.js"))
            {
                return null;
            }
        }
</code>```

the demo.js will don't load in the page

so I want to know Selenium have same method to do this

if no, have any solution can do this?

Body:
when I use CEFSharp I can using ResourceRequestHandler class to filter web resource

and I can chooce use or not.

for example

        protected override IResponseFilter GetResourceResponseFilter(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response)
        {
            var url = request.Url.ToLower();

            if (url.Contains("https://aaaa.com/demo.js"))
            {
                return null;
            }
        }

the demo.js will don't load in the page

so I want to know Selenium have same method to do this

if no, have any solution can do this?


问:
not-null property references a null or transient value : com.hellion.writeup.models.Comment.parentComment
I'm trying to implement comment/reply feature in my blog application. I did all the work, but when I try to add comment I get the exception in the title: parentComment is null but it shouldn't be because it has nullable = false. Now I've tried to remove the nullable = false and add @Basic annotation to my Comment entity but then I get another exception and it says:

NULL not allowed for column "PARENT_ID"; SQL statement: insert into
comment (id, author, created_at, parent_id, post_id, text) values
(default, ?, ?, ?, ?, ?)

I've tried inserting parent_comment as such:

```<code>public void addComment(Long postId, String commentText){
        Post post = postRepository.findById(postId).get();
        Comment comment = new Comment(commentText, post);
        /*
        comment.setParentComment(comment);
         */
        comment.setCreatedAt(LocalDateTime.now());
        commentRepository.save(comment);
    }
</code>```

but that didn't work. I also tried goign to the database and unselecting the "NOT_NULL" in the alter table, but I dunno how to do that in h2-database. Also, I've had an idea where I would create a blank comment which would be the parent comment to every comment and try branching the replies to it, but it sounds stupid. Please help :)

Here are all the files:

Comment.java

```<code>@Entity
@Table(name="COMMENT")
@NoArgsConstructor
@Getter
@Setter
@AllArgsConstructor
public class Comment {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String text;

    @Column(nullable = false)
    private LocalDateTime createdAt;

    private String author;

    @ManyToOne
    @JoinColumn(name="parent_id")
    private Comment parentComment;

    @ManyToOne
    @JoinColumn(name="post_id", nullable = false)
    private Post post;

    public Comment(String text, Post post) {
        this.text = text;
        this.post = post;
    }

    public Comment(String text, Post post, Comment parentComment) {
        this.text = text;
        this.post = post;
        this.parentComment = parentComment;
    }

}
</code>```

CommentController.java

```<code>import com.hellion.writeup.models.Comment;
import com.hellion.writeup.models.Post;
import com.hellion.writeup.repository.CommentRepository;
import com.hellion.writeup.repository.PostRepository;
import com.hellion.writeup.service.AccountService;
import com.hellion.writeup.service.CommentService;
import com.hellion.writeup.service.PostService;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Optional;

@Controller
public class CommentController{

    @Autowired
    private CommentService commentService;

    @Autowired
    private PostRepository postRepository;

    @Autowired
    private CommentRepository commentRepository;

    @PostMapping("/post/{postId}/comment")
    public String addComment(@PathVariable("postId") Long postId, @RequestParam String commentText, Model model){
        commentService.addComment(postId, commentText);
        Post post = postRepository.findById(postId).get();
        model.addAttribute("post", post);
        return "post";
    }

    @PostMapping("/comment/{commentId}/reply")
    public String addReply(@PathVariable("commentId")Long commentId, @RequestParam String replyText, Model model){
        commentService.addReply(commentId, replyText);
        Comment comment = commentRepository.findById(commentId).get();
        model.addAttribute("post", comment.getPost());
        return "post";
    }

}
</code>```

CommentService.java

```<code>import com.hellion.writeup.models.Comment;
import com.hellion.writeup.models.Post;
import com.hellion.writeup.repository.CommentRepository;
import com.hellion.writeup.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class CommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private PostRepository postRepository;

    public void addComment(Long postId, String commentText){
        Post post = postRepository.findById(postId).get();
        Comment comment = new Comment(commentText, post);
        /*
        comment.setParentComment(comment);
         */
        comment.setCreatedAt(LocalDateTime.now());
        commentRepository.save(comment);
    }

    public void addReply(Long commentId, String replyText){
        Comment comment = commentRepository.findById(commentId).get();
        Comment reply = new Comment(replyText, comment.getPost(), comment);
        reply.setCreatedAt(LocalDateTime.now());
        commentRepository.save(reply);
    }

}
</code>```

and commentRepository is just extends JpaRepository<>{} without any methods.

Body:
I'm trying to implement comment/reply feature in my blog application. I did all the work, but when I try to add comment I get the exception in the title: parentComment is null but it shouldn't be because it has nullable = false. Now I've tried to remove the nullable = false and add @Basic annotation to my Comment entity but then I get another exception and it says:

NULL not allowed for column "PARENT_ID"; SQL statement: insert into
comment (id, author, created_at, parent_id, post_id, text) values
(default, ?, ?, ?, ?, ?)

I've tried inserting parent_comment as such:

public void addComment(Long postId, String commentText){
        Post post = postRepository.findById(postId).get();
        Comment comment = new Comment(commentText, post);
        /*
        comment.setParentComment(comment);
         */
        comment.setCreatedAt(LocalDateTime.now());
        commentRepository.save(comment);
    }

but that didn't work. I also tried goign to the database and unselecting the "NOT_NULL" in the alter table, but I dunno how to do that in h2-database. Also, I've had an idea where I would create a blank comment which would be the parent comment to every comment and try branching the replies to it, but it sounds stupid. Please help :)

Here are all the files:

Comment.java

@Entity
@Table(name="COMMENT")
@NoArgsConstructor
@Getter
@Setter
@AllArgsConstructor
public class Comment {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String text;

    @Column(nullable = false)
    private LocalDateTime createdAt;

    private String author;

    @ManyToOne
    @JoinColumn(name="parent_id")
    private Comment parentComment;

    @ManyToOne
    @JoinColumn(name="post_id", nullable = false)
    private Post post;

    public Comment(String text, Post post) {
        this.text = text;
        this.post = post;
    }

    public Comment(String text, Post post, Comment parentComment) {
        this.text = text;
        this.post = post;
        this.parentComment = parentComment;
    }

}

CommentController.java

import com.hellion.writeup.models.Comment;
import com.hellion.writeup.models.Post;
import com.hellion.writeup.repository.CommentRepository;
import com.hellion.writeup.repository.PostRepository;
import com.hellion.writeup.service.AccountService;
import com.hellion.writeup.service.CommentService;
import com.hellion.writeup.service.PostService;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Optional;

@Controller
public class CommentController{

    @Autowired
    private CommentService commentService;

    @Autowired
    private PostRepository postRepository;

    @Autowired
    private CommentRepository commentRepository;

    @PostMapping("/post/{postId}/comment")
    public String addComment(@PathVariable("postId") Long postId, @RequestParam String commentText, Model model){
        commentService.addComment(postId, commentText);
        Post post = postRepository.findById(postId).get();
        model.addAttribute("post", post);
        return "post";
    }

    @PostMapping("/comment/{commentId}/reply")
    public String addReply(@PathVariable("commentId")Long commentId, @RequestParam String replyText, Model model){
        commentService.addReply(commentId, replyText);
        Comment comment = commentRepository.findById(commentId).get();
        model.addAttribute("post", comment.getPost());
        return "post";
    }

}

CommentService.java

import com.hellion.writeup.models.Comment;
import com.hellion.writeup.models.Post;
import com.hellion.writeup.repository.CommentRepository;
import com.hellion.writeup.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class CommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private PostRepository postRepository;

    public void addComment(Long postId, String commentText){
        Post post = postRepository.findById(postId).get();
        Comment comment = new Comment(commentText, post);
        /*
        comment.setParentComment(comment);
         */
        comment.setCreatedAt(LocalDateTime.now());
        commentRepository.save(comment);
    }

    public void addReply(Long commentId, String replyText){
        Comment comment = commentRepository.findById(commentId).get();
        Comment reply = new Comment(replyText, comment.getPost(), comment);
        reply.setCreatedAt(LocalDateTime.now());
        commentRepository.save(reply);
    }

}

and commentRepository is just extends JpaRepository<>{} without any methods.


问:
Accidentally removed libglib2.0-0 and Ubuntu shows black screen after boot
In short I didn’t know that this package is so important so I just did:

sudo apt remove libglib2.0-0

I wanted to delete it as moments before this I installed newer version manually (2.7 didn’t appear in apt).

I was able to enter recovery mode and installed same package but graphics interface is still not back.
Please help.


问:
In android navigation menu, menu item is not clickable
I'm working on a menu navigation drawer , in that I'm not able to click items when I'm adding a constraint layout inside the drawer layout. But after removing that click, the menu item works fine. So please tell me how can I fix this issue.

here below is my activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
    tools:context=".MainActivity"
    android:id="@+id/drawerlayout"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include layout="@layout/appbar">
    </include>

    <com.google.android.material.navigation.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        app:menu="@menu/navigationitem"
        android:id="@+id/navigationview"
        app:headerLayout="@layout/header_layout"
        android:layout_gravity="start">
    </com.google.android.material.navigation.NavigationView>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Test"
            android:textColor="@color/white">
        </TextView>
    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.drawerlayout.widget.DrawerLayout>
</code>```

And here below is my mainactivity

```<code>public class MainActivity extends AppCompatActivity {
    DrawerLayout drawerLayout;
    Toolbar toolbar1;
    NavigationView navigationView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        drawerLayout=findViewById(R.id.drawerlayout);
        toolbar1=findViewById(R.id.tbar);
        navigationView=findViewById(R.id.navigationview);

        toolbar1.inflateMenu(R.menu.navigationitem);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar1,R.string.nav_open,R.string.nav_close);

        drawerLayout.addDrawerListener(toggle);

        toggle.syncState();

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int id = item.getItemId();

                if (id==R.id.profile){
                    Toast.makeText(MainActivity.this, "Profile", Toast.LENGTH_SHORT).show();
                }
                else if(id==R.id.contact){
                    Toast.makeText(MainActivity.this, "Contact", Toast.LENGTH_SHORT).show();
                }
                else{
                    Toast.makeText(MainActivity.this, "Logoutact", Toast.LENGTH_SHORT).show();
                }
                drawerLayout.closeDrawer(GravityCompat.START);

                return true;
            }
        });
    }
}
</code>```

Now, How Can Solve This Problem?

Body:
I'm working on a menu navigation drawer , in that I'm not able to click items when I'm adding a constraint layout inside the drawer layout. But after removing that click, the menu item works fine. So please tell me how can I fix this issue.

here below is my activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
    tools:context=".MainActivity"
    android:id="@+id/drawerlayout"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include layout="@layout/appbar">
    </include>

    <com.google.android.material.navigation.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        app:menu="@menu/navigationitem"
        android:id="@+id/navigationview"
        app:headerLayout="@layout/header_layout"
        android:layout_gravity="start">
    </com.google.android.material.navigation.NavigationView>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Test"
            android:textColor="@color/white">
        </TextView>
    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.drawerlayout.widget.DrawerLayout>

And here below is my mainactivity

public class MainActivity extends AppCompatActivity {
    DrawerLayout drawerLayout;
    Toolbar toolbar1;
    NavigationView navigationView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        drawerLayout=findViewById(R.id.drawerlayout);
        toolbar1=findViewById(R.id.tbar);
        navigationView=findViewById(R.id.navigationview);

        toolbar1.inflateMenu(R.menu.navigationitem);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar1,R.string.nav_open,R.string.nav_close);

        drawerLayout.addDrawerListener(toggle);

        toggle.syncState();

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int id = item.getItemId();

                if (id==R.id.profile){
                    Toast.makeText(MainActivity.this, "Profile", Toast.LENGTH_SHORT).show();
                }
                else if(id==R.id.contact){
                    Toast.makeText(MainActivity.this, "Contact", Toast.LENGTH_SHORT).show();
                }
                else{
                    Toast.makeText(MainActivity.this, "Logoutact", Toast.LENGTH_SHORT).show();
                }
                drawerLayout.closeDrawer(GravityCompat.START);

                return true;
            }
        });
    }
}

Now, How Can Solve This Problem?


问:
Async Function Within Jquery $(Document).Ready Not Awaiting (JQuery 1.11.2)
When attempting to await an immediately executed async function inside $(Document).Ready, the result is not awaited:

```<code>$(document).ready(function () {
    var outcomeNameStrings = (async () => {
        let namesObj = await getOutcomeNameStrings();
        return namesObj;
    })();
    console.log(outcomeNameStrings);
    . . . //other code
    debugger; //value is a promise still
}
</code>```

getOutcomeNameStrings creates an HTTP Get call to the server to retrieve a JSON object. This is need before all elements are loaded into the page (i.e. I don't think I can use Window Load). Implementation below:

```<code>async function getOutcomeNameStrings() {
    return $.ajax({
        async: true,
        type: "GET",
        url: "/Outcomes/GetOutcomeNameStrings",
        dataType: "json"
    });
}
</code>```

The value logged into the Console and at debugger line is a Promise and not the JSON object. I've also tried .then callback functions but this doesn't seem to work either.

The Jquery version is 1.11.2 and is used within a .NET Framework 4.7.2 MVC project. getOutcomeNameStrings hits a GET endpoint method in a controller.

If any more details are required to solve this, I am happy to provide them, thanks for any help!

Body:
When attempting to await an immediately executed async function inside $(Document).Ready, the result is not awaited:

$(document).ready(function () {
    var outcomeNameStrings = (async () => {
        let namesObj = await getOutcomeNameStrings();
        return namesObj;
    })();
    console.log(outcomeNameStrings);
    . . . //other code
    debugger; //value is a promise still
}

getOutcomeNameStrings creates an HTTP Get call to the server to retrieve a JSON object. This is need before all elements are loaded into the page (i.e. I don't think I can use Window Load). Implementation below:

async function getOutcomeNameStrings() {
    return $.ajax({
        async: true,
        type: "GET",
        url: "/Outcomes/GetOutcomeNameStrings",
        dataType: "json"
    });
}

The value logged into the Console and at debugger line is a Promise and not the JSON object. I've also tried .then callback functions but this doesn't seem to work either.

The Jquery version is 1.11.2 and is used within a .NET Framework 4.7.2 MVC project. getOutcomeNameStrings hits a GET endpoint method in a controller.

If any more details are required to solve this, I am happy to provide them, thanks for any help!


问:
Callinga column but error not exists even though column exists in the df
I am trying to plot a line graph with respect to years . I am calling the column from the dataframe but it can't see it i dont know why even though you will find in the screenshot that the column exists in the dataframe

Here i printed the df columns and the column itslef but still got the error


问:
Javascript works on my Chrome and Safari. On Friends Chrome and Safari it doesnt work
Hi my HTML File doesn´t work right depending on the browser.
The Bottle Animation where the Bottle gets fuller depending on where you click works fine on my PC and Macbook.
But on a friends macbook it does not work. neither chrome nor safari. I discovered that the code isnt working on my Firefox but on my Chrome and Safari.

What did I do wrong?

```<code>var kh_global;
var eiweiß_global;

function draw_bottle(kh, eiweiß) {
  kh_global = kh;
  eiweiß_global = eiweiß;
  document.getElementById('Main').addEventListener("click", printMousePos);
}

function printMousePos(event) {
    //orange
    const juiceMask = document.getElementById('juiceMask');
    //grün
    const juiceMask2 = document.getElementById('juiceMask2');
    //blau
    const juiceMask3 = document.getElementById('juiceMask3');
    var pixeloffset = event.clientY * 2;

    const percent = 1 - ((pixeloffset / 1600));

   console.log((1 - percent) * 1000)

   document.getElementById('anzeige').innerHTML = "Hohes C<br>"
   + "(Standardnährwert)<br>"
   + "Menge: " + Math.round(hohesc.Menge * percent * 1000) + "ml<br>"
   + "Brennwert: " + Math.round(hohesc.Brennwert * percent * 100) + "kcal<br>"
   + "Kohlenhydrate: " + Math.round(hohesc.Kohlenhydrate * percent * 100) + "g<br>"
   + "Eiweiß: " + Math.round(hohesc.Eiweiss * percent * 100) + "g<br>"
   + "Vitamin C: " + Math.round(hohesc.VitaminC * percent * 100) + "mg";

   change(kh_global, eiweiß_global, pixeloffset);

  }

  function change(kh, eiweiß, pixeloffset) {
        //orange
        const juiceMask = document.getElementById('juiceMask');
        //grün
        const juiceMask2 = document.getElementById('juiceMask2');
        //blau
        const juiceMask3 = document.getElementById('juiceMask3');

        const width_kh = 450 * kh / 100;
        const width_eiweiß = 450 * eiweiß / 100;
        const starting_point_rest = width_eiweiß + width_kh;
        const width_rest = 450 - starting_point_rest;

        const rest_percentage = 100-kh-eiweiß;

        document.getElementById('anzeige2unten').innerHTML = "Verteilung Inhaltsstoffe<br><br>"
        + "Zucker: <br>"+kh+"%<br>"
        + "Fruchtsaft: <br>"+eiweiß+"%<br>"
        + "Rest: <br>"+rest_percentage+"%<br><br>"
        +  "Vitamin C:<br> < 0,05%<br></br>";

        juiceMask.style.width = width_kh;
        juiceMask.style.transform = "translateY(" + pixeloffset + "px)" ;

        juiceMask2.style.transform = "translateX(" + width_kh + "px) translateY(" + pixeloffset + "px)" ;
        juiceMask2.style.width = width_eiweiß;

        juiceMask3.style.transform = "translateX(" + starting_point_rest + "px) translateY(" + pixeloffset + "px)" ;
        juiceMask3.style.width = width_rest;
  }

  const hohesc = {
    Menge: 1,
    Brennwert: 4.3,
    Kohlenhydrate: 0.88,
    Eiweiss: 0.07,
    VitaminC: 3.2
  }

draw_bottle(20, 70);

</code>```

Is it the mask in the HTML?
I have no clue :(

Body:
Hi my HTML File doesn´t work right depending on the browser.
The Bottle Animation where the Bottle gets fuller depending on where you click works fine on my PC and Macbook.
But on a friends macbook it does not work. neither chrome nor safari. I discovered that the code isnt working on my Firefox but on my Chrome and Safari.

What did I do wrong?

var kh_global;
var eiweiß_global;

function draw_bottle(kh, eiweiß) {
  kh_global = kh;
  eiweiß_global = eiweiß;
  document.getElementById('Main').addEventListener("click", printMousePos);
}

function printMousePos(event) {
    //orange
    const juiceMask = document.getElementById('juiceMask');
    //grün
    const juiceMask2 = document.getElementById('juiceMask2');
    //blau
    const juiceMask3 = document.getElementById('juiceMask3');
    var pixeloffset = event.clientY * 2;

    const percent = 1 - ((pixeloffset / 1600));

   console.log((1 - percent) * 1000)

   document.getElementById('anzeige').innerHTML = "Hohes C
"
   + "(Standardnährwert)
"
   + "Menge: " + Math.round(hohesc.Menge * percent * 1000) + "ml
"
   + "Brennwert: " + Math.round(hohesc.Brennwert * percent * 100) + "kcal
"
   + "Kohlenhydrate: " + Math.round(hohesc.Kohlenhydrate * percent * 100) + "g
"
   + "Eiweiß: " + Math.round(hohesc.Eiweiss * percent * 100) + "g
"
   + "Vitamin C: " + Math.round(hohesc.VitaminC * percent * 100) + "mg";

   change(kh_global, eiweiß_global, pixeloffset);

  }

  function change(kh, eiweiß, pixeloffset) {
        //orange
        const juiceMask = document.getElementById('juiceMask');
        //grün
        const juiceMask2 = document.getElementById('juiceMask2');
        //blau
        const juiceMask3 = document.getElementById('juiceMask3');

        const width_kh = 450 * kh / 100;
        const width_eiweiß = 450 * eiweiß / 100;
        const starting_point_rest = width_eiweiß + width_kh;
        const width_rest = 450 - starting_point_rest;

        const rest_percentage = 100-kh-eiweiß;

        document.getElementById('anzeige2unten').innerHTML = "Verteilung Inhaltsstoffe

"
        + "Zucker:
"+kh+"%
"
        + "Fruchtsaft:
"+eiweiß+"%
"
        + "Rest:
"+rest_percentage+"%

"
        +  "Vitamin C:
 < 0,05%

";

        juiceMask.style.width = width_kh;
        juiceMask.style.transform = "translateY(" + pixeloffset + "px)" ;

        juiceMask2.style.transform = "translateX(" + width_kh + "px) translateY(" + pixeloffset + "px)" ;
        juiceMask2.style.width = width_eiweiß;

        juiceMask3.style.transform = "translateX(" + starting_point_rest + "px) translateY(" + pixeloffset + "px)" ;
        juiceMask3.style.width = width_rest;
  }

  const hohesc = {
    Menge: 1,
    Brennwert: 4.3,
    Kohlenhydrate: 0.88,
    Eiweiss: 0.07,
    VitaminC: 3.2
  }

draw_bottle(20, 70);

Is it the mask in the HTML?
I have no clue :(


问:
Catching error messages before server starts
I have a language server set up in an extension that delegates a few commands from the client to the server. They work perfectly when the extension is working but the server takes a second or so to start. If the user happens to press the shortcut that triggers such a command during this time, VSC automatically shows a command XXX not found error message, what is actually true, the command is not yet found. But I would like to catch this situation to provide my own, more appropriate error message. Where can I do so? I tried to add a try/catch to my middleware, eg:

```<code>executeCommand: async (command, args, next) => {
  try {
    return next(command, args);
  } catch (error) {
    vscode.window.showErrorMessage('Server communication error');
  }
}
</code>```

but this isn't called, either, during the starting period, only later.

Body:
I have a language server set up in an extension that delegates a few commands from the client to the server. They work perfectly when the extension is working but the server takes a second or so to start. If the user happens to press the shortcut that triggers such a command during this time, VSC automatically shows a command XXX not found error message, what is actually true, the command is not yet found. But I would like to catch this situation to provide my own, more appropriate error message. Where can I do so? I tried to add a try/catch to my middleware, eg:

executeCommand: async (command, args, next) => {
  try {
    return next(command, args);
  } catch (error) {
    vscode.window.showErrorMessage('Server communication error');
  }
}

but this isn't called, either, during the starting period, only later.


问:
Docker app does not read daily updated data
I have developed a docker app that reads data from a folder on my server (/myapp1/app/data). The data are updated daily in this folder. If I run the docker app on my domain, the app reads the data from the folder, but when these data are updated the app doesn't read the new data, it only reads the old data. If I down the container and run it again, then the app does read the new data.

My dockerfile is the following:

```<code># get shiny server and R from the rocker project
FROM rocker/shiny:4.0.5

RUN apt-get update && apt-get install -y \
    sudo \
    gdebi-core \
    pandoc \
    pandoc-citeproc \
    libcurl4-gnutls-dev \
    libxt-dev \
    libssl-dev \
    libxml2 \
    libxml2-dev \
    libsodium-dev

# install R packages required
RUN R -e "install.packages(c('shiny', 'shinythemes', 'dygraphs', 'shinyWidgets', 'manipulateWidget', 'DT', 'zoo', 'shinyjs','emayili', 'wordcloud2', 'rmarkdown', 'xts', 'shinyauthr', 'curl', 'jsonlite', 'httr', 'lubridate'), repos='http://cran.rstudio.com/')"

# copy the app directory into the image
WORKDIR /myapp1/app
COPY app .

# run app
EXPOSE 8090
CMD ["R", "-e", "shiny::runApp('/myapp1/app',  host = '0.0.0.0', port = 8090)"]

</code>```

My docker-compose.yml file is the following:

```<code>version: "3.7"

services:

 app1:
  image: myapp1image
  container_name: myapp1container
  expose:
   - "8090"
  environment:
   - VIRTUAL_PORT=8090
   - VIRTUAL_HOST=myapp1.net,www.myapp1.net
   - LETSENCRYPT_HOST=myapp1.net,www.myapp1.net
   - LETSENCRYPT_EMAIL=info@myapp1.net
  volumes:
   - /myapp1/app/data:/myapp1/app/data
  networks:
   - mynetwork

networks:
 mynetwork:
  external : true

</code>```

My app should read the updated data without having to down and run the container every time the data is updated, so I would appreciate a solution to the problem raised above.

Body:
I have developed a docker app that reads data from a folder on my server (/myapp1/app/data). The data are updated daily in this folder. If I run the docker app on my domain, the app reads the data from the folder, but when these data are updated the app doesn't read the new data, it only reads the old data. If I down the container and run it again, then the app does read the new data.

My dockerfile is the following:

# get shiny server and R from the rocker project
FROM rocker/shiny:4.0.5

RUN apt-get update && apt-get install -y \
    sudo \
    gdebi-core \
    pandoc \
    pandoc-citeproc \
    libcurl4-gnutls-dev \
    libxt-dev \
    libssl-dev \
    libxml2 \
    libxml2-dev \
    libsodium-dev

# install R packages required
RUN R -e "install.packages(c('shiny', 'shinythemes', 'dygraphs', 'shinyWidgets', 'manipulateWidget', 'DT', 'zoo', 'shinyjs','emayili', 'wordcloud2', 'rmarkdown', 'xts', 'shinyauthr', 'curl', 'jsonlite', 'httr', 'lubridate'), repos='http://cran.rstudio.com/')"

# copy the app directory into the image
WORKDIR /myapp1/app
COPY app .

# run app
EXPOSE 8090
CMD ["R", "-e", "shiny::runApp('/myapp1/app',  host = '0.0.0.0', port = 8090)"]

My docker-compose.yml file is the following:

version: "3.7"

services:

 app1:
  image: myapp1image
  container_name: myapp1container
  expose:
   - "8090"
  environment:
   - VIRTUAL_PORT=8090
   - VIRTUAL_HOST=myapp1.net,www.myapp1.net
   - LETSENCRYPT_HOST=myapp1.net,www.myapp1.net
   - LETSENCRYPT_EMAIL=info@myapp1.net
  volumes:
   - /myapp1/app/data:/myapp1/app/data
  networks:
   - mynetwork

networks:
 mynetwork:
  external : true

My app should read the updated data without having to down and run the container every time the data is updated, so I would appreciate a solution to the problem raised above.


问:
Actuator on different port not logging with akkinoc / logback-access-spring-boot-starter
I am using akkinoc/logback-access-spring-boot-starter to enabe logback-access in spring boot application. Access logs are generated fine but I have a different management port and I do not see my actuator logs in this file.

Eg:

"GET /actuator/health HTTP/1.1" 200 1285
"GET /actuator/info HTTP/1.1" 200 381

When I use tomcat configurations, these work as expected.

Help highly appreciated.


问:
How to create samaccountname with maximum 12 character?
I need to create users with max 12 characters.
The last name can contain the first 11 characters (max) + the first letter of the first name

I'm not sure what to add next to $LastName

Can you help me with this?

```<code>$OU = "OU=Users,DC=domain,DC=com"
$PW = "Welcome$(Get-Random -minimum 0001 -maximum 9999)!"

$FirstName = Read-Host "Please enter the Firstname for the new user"
$LastName  = Read-Host "Please enter the Lastname for the new user"

$AccountName = $LastName + $FirstName[0]  # Last name (11 caracter max) + first character of first name
# test if a user with that accountname already exists and if so, append a sequence number
$count = 1
while (Get-ADUser -Filter "SamAccountName -eq '$AccountName'") {
    $AccountName = '{0}{1}{2}' -f $LastName, $FirstName[0], $count++
}

$UPN = "$($FirstName).$($LastName)@domain.com" #if the upn exists, add a digit to the last name
# test if a user with that UserPrincipalName already exists and if so, append a sequence number
$count = 1
while (Get-ADUser -Filter "UserPrincipalName -eq '$UPN'") {
    $UPN = '{0}.{1}{2}@domain.com' -f $FirstName, $LastName, $count++
}

# create a Hashtable for splatting parameters
$userParams = @{
     Name                         = "$($LastName), $($FirstName)"
     DisplayName                  = "$($LastName), $($FirstName)"
     FirstName                    = $FirstName
     LastName                     = $LastName
     SamAccountName               = $AccountName
     OnPremisesOrganizationalUnit = $OU
     UserPrincipalName            = $UPN
     Password                     = $PW | ConvertTo-SecureString -AsPlainText -Force
     ResetPasswordOnNextLogon     = $true
     Archive                      = $true
}

# Create User On-Premise and move to the managers OU if possible
try {
    New-RemoteMailbox @userParams -ErrorAction Stop

}
catch {
    Write-Error $_.Exception.Message
}
</code>```

Body:
I need to create users with max 12 characters.
The last name can contain the first 11 characters (max) + the first letter of the first name

I'm not sure what to add next to $LastName

Can you help me with this?

$OU = "OU=Users,DC=domain,DC=com"
$PW = "Welcome$(Get-Random -minimum 0001 -maximum 9999)!"

$FirstName = Read-Host "Please enter the Firstname for the new user"
$LastName  = Read-Host "Please enter the Lastname for the new user"

$AccountName = $LastName + $FirstName[0]  # Last name (11 caracter max) + first character of first name
# test if a user with that accountname already exists and if so, append a sequence number
$count = 1
while (Get-ADUser -Filter "SamAccountName -eq '$AccountName'") {
    $AccountName = '{0}{1}{2}' -f $LastName, $FirstName[0], $count++
}

$UPN = "$($FirstName).$($LastName)@domain.com" #if the upn exists, add a digit to the last name
# test if a user with that UserPrincipalName already exists and if so, append a sequence number
$count = 1
while (Get-ADUser -Filter "UserPrincipalName -eq '$UPN'") {
    $UPN = '{0}.{1}{2}@domain.com' -f $FirstName, $LastName, $count++
}

# create a Hashtable for splatting parameters
$userParams = @{
     Name                         = "$($LastName), $($FirstName)"
     DisplayName                  = "$($LastName), $($FirstName)"
     FirstName                    = $FirstName
     LastName                     = $LastName
     SamAccountName               = $AccountName
     OnPremisesOrganizationalUnit = $OU
     UserPrincipalName            = $UPN
     Password                     = $PW | ConvertTo-SecureString -AsPlainText -Force
     ResetPasswordOnNextLogon     = $true
     Archive                      = $true
}

# Create User On-Premise and move to the managers OU if possible
try {
    New-RemoteMailbox @userParams -ErrorAction Stop

}
catch {
    Write-Error $_.Exception.Message
}


问:
How to track usage of this SKU on Google? BigQuery Storage API Network Internet Egress Intercontinental (Excl Oceania and China)(Excl Oceania & China)
I need help to understand more about 2 SKU on Google Cloud, I'm charging a big amount on these skus:
BigQuery Storage API Network Internet Egress Intercontinental (Excl Oceania and China)
BigQuery Storage API Network Internet Egress South America to South America

My BigQuery datasets are in US multi-region, I don't understand how I can investigate or get more information about this.


问:
API response Include milliseconds when serializing DateTime even if component is zero
DateTimeStamp : 2022-04-29 15:19:41.350 after serialization 2022-04-29T22:19:41.35Z instead of 2022-04-29T22:19:41.350Z

I have fixed this using below code :

```<code>public static void ServiceJsonSettings(HttpConfiguration config, IServiceMetadata serviceMetadata)
    {
        config.Formatters.Insert(0, new JsonNewtonsoftJilFallbackFormatter());
        IsoDateTimeConverter dateConverter = new IsoDateTimeConverter
        {
            DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff'Z'",
            DateTimeStyles = DateTimeStyles.AdjustToUniversal
        };
        config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(dateConverter);

    }
</code>```

Now for large object serialization i am using Jil Serializer configured as below:

```<code>public static readonly Options JilOptions = new Options(excludeNulls: true, includeInherited: true,
            serializationNameFormat: SerializationNameFormat.CamelCase, dateFormat: DateTimeFormat.ISO8601);
</code>```

Using both Serializer Newtonsoft and JIL the output I am getting expected result : 2022-04-29T22:19:41.350Z.

But after testing it i found JIL serializer Serializer is trimming the zeros in millisecond part if it ends with 00 for ex:  DateTimeStamp : 2022-04-29 15:19:41.300 serialized to 2022-04-29T22:19:41.3Z. On the other hand newtonsoft serializer produce expected result 2022-04-29T22:19:41.300Z.

Is there any way to provide dateFormat as "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff'Z'" in JilOptions ?

Body:
DateTimeStamp : 2022-04-29 15:19:41.350 after serialization 2022-04-29T22:19:41.35Z instead of 2022-04-29T22:19:41.350Z

I have fixed this using below code :

public static void ServiceJsonSettings(HttpConfiguration config, IServiceMetadata serviceMetadata)
    {
        config.Formatters.Insert(0, new JsonNewtonsoftJilFallbackFormatter());
        IsoDateTimeConverter dateConverter = new IsoDateTimeConverter
        {
            DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff'Z'",
            DateTimeStyles = DateTimeStyles.AdjustToUniversal
        };
        config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(dateConverter);

    }

Now for large object serialization i am using Jil Serializer configured as below:

public static readonly Options JilOptions = new Options(excludeNulls: true, includeInherited: true,
            serializationNameFormat: SerializationNameFormat.CamelCase, dateFormat: DateTimeFormat.ISO8601);

Using both Serializer Newtonsoft and JIL the output I am getting expected result : 2022-04-29T22:19:41.350Z.

But after testing it i found JIL serializer Serializer is trimming the zeros in millisecond part if it ends with 00 for ex:  DateTimeStamp : 2022-04-29 15:19:41.300 serialized to 2022-04-29T22:19:41.3Z. On the other hand newtonsoft serializer produce expected result 2022-04-29T22:19:41.300Z.

Is there any way to provide dateFormat as "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff'Z'" in JilOptions ?


问:
WTelegramClient - Can't get intellisense to work (vs2022 C#)
Visual Studio 2022 (fresh install). Using the latest WTelegramClient version: Builds just fine in both net5.0 / netstandard2.0 in debug and release mode. Tested the dll (great work!) and working very good.

Looking for hours why I don't get intellisense to work with the assembly. Intellisense is working perfectly for other assemblies, for system syntaxes, just not this one.

Imported the WTelegramClient.dll file in the project dependencies,

Added the Using TL declaration,

Even tried coding under TL and also WTelegram namespace.

Is there anything I'm missing? anything special to do when building the dll? I feel I'm coding naked without the developer's comments now that I would like to use it =( Thanks!