问:
Golang socks5 proxy client
I'm trying to make a proxy:

I need to listen to port 1080 (socks 5), and complete a request to a destination using an external ip:port socks 5, I managed to open this connection with the external ip, but I don't know how I could complete the request to the target destination using that external ip.

could someone help me with this?

```<code>package main

import (
    "bufio"
    "errors"
    "fmt"
    "io"
    "log"
    "net"
)

const (
    ConnectCommand   = uint8(1)
    BindCommand      = uint8(2)
    AssociateCommand = uint8(3)
    ipv4Address      = uint8(1)
    fqdnAddress      = uint8(3)
    ipv6Address      = uint8(4)
)

type AddrSpec struct {
    FQDN string
    IP   net.IP
    Port int
}

func main() {
    l, err := net.Listen("tcp", "127.0.0.1:1080")
    if err != nil {
        fmt.Print(err)
    }
    defer l.Close()

    for {
        conn, err := l.Accept()
        if err != nil {
            fmt.Print(err)
        }

        go handle(conn)
    }
}

func handle(conn net.Conn) {
    defer func() {
        _ = conn.Close()
    }()

    bufConn := bufio.NewReader(conn)
    version := []byte{0}
    if _, err := bufConn.Read(version); err != nil {
        log.Fatalf("cannot read version: %s", err.Error())
    }

    if version[0] != uint8(5) {
        log.Fatalf("unsupported SOCKS version: %v", version)
    }

    socks5ExternalConn, err := net.Dial("tcp", externalSOCKS5Proxy())
    if err != nil {
        log.Printf("Connection error: %s", err.Error())
    }

    dest, err := readAddrSpec(bufConn)
    if err != nil {
    }

    // how i can send request to server with external conn?
}

func externalSOCKS5Proxy() string {
    return "externalip:externalport"
}

func readAddrSpec(r io.Reader) (*AddrSpec, error) {
    d := &AddrSpec{}

    // Get the address type
    addrType := []byte{0}
    if _, err := r.Read(addrType); err != nil {
        return nil, err
    }

    // Handle on a per type basis
    switch addrType[0] {
    case ipv4Address:
        addr := make([]byte, 4)
        if _, err := io.ReadAtLeast(r, addr, len(addr)); err != nil {
            return nil, err
        }
        d.IP = net.IP(addr)

    case ipv6Address:
        addr := make([]byte, 16)
        if _, err := io.ReadAtLeast(r, addr, len(addr)); err != nil {
            return nil, err
        }
        d.IP = net.IP(addr)

    case fqdnAddress:
        if _, err := r.Read(addrType); err != nil {
            return nil, err
        }
        addrLen := int(addrType[0])
        fqdn := make([]byte, addrLen)
        if _, err := io.ReadAtLeast(r, fqdn, addrLen); err != nil {
            return nil, err
        }
        d.FQDN = string(fqdn)

    default:
        return nil, errors.New("unrecognizedAddrType")
    }

    // Read the port
    port := []byte{0, 0}
    if _, err := io.ReadAtLeast(r, port, 2); err != nil {
        return nil, err
    }
    d.Port = (int(port[0]) << 8) | int(port[1])

    return d, nil
}
</code>```

Title: Golang socks5 proxy client

Body:
I'm trying to make a proxy:

I need to listen to port 1080 (socks 5), and complete a request to a destination using an external ip:port socks 5, I managed to open this connection with the external ip, but I don't know how I could complete the request to the target destination using that external ip.

could someone help me with this?

package main

import (
    "bufio"
    "errors"
    "fmt"
    "io"
    "log"
    "net"
)

const (
    ConnectCommand   = uint8(1)
    BindCommand      = uint8(2)
    AssociateCommand = uint8(3)
    ipv4Address      = uint8(1)
    fqdnAddress      = uint8(3)
    ipv6Address      = uint8(4)
)

type AddrSpec struct {
    FQDN string
    IP   net.IP
    Port int
}

func main() {
    l, err := net.Listen("tcp", "127.0.0.1:1080")
    if err != nil {
        fmt.Print(err)
    }
    defer l.Close()

    for {
        conn, err := l.Accept()
        if err != nil {
            fmt.Print(err)
        }

        go handle(conn)
    }
}

func handle(conn net.Conn) {
    defer func() {
        _ = conn.Close()
    }()

    bufConn := bufio.NewReader(conn)
    version := []byte{0}
    if _, err := bufConn.Read(version); err != nil {
        log.Fatalf("cannot read version: %s", err.Error())
    }

    if version[0] != uint8(5) {
        log.Fatalf("unsupported SOCKS version: %v", version)
    }

    socks5ExternalConn, err := net.Dial("tcp", externalSOCKS5Proxy())
    if err != nil {
        log.Printf("Connection error: %s", err.Error())
    }

    dest, err := readAddrSpec(bufConn)
    if err != nil {
    }

    // how i can send request to server with external conn?
}

func externalSOCKS5Proxy() string {
    return "externalip:externalport"
}

func readAddrSpec(r io.Reader) (*AddrSpec, error) {
    d := &AddrSpec{}

    // Get the address type
    addrType := []byte{0}
    if _, err := r.Read(addrType); err != nil {
        return nil, err
    }

    // Handle on a per type basis
    switch addrType[0] {
    case ipv4Address:
        addr := make([]byte, 4)
        if _, err := io.ReadAtLeast(r, addr, len(addr)); err != nil {
            return nil, err
        }
        d.IP = net.IP(addr)

    case ipv6Address:
        addr := make([]byte, 16)
        if _, err := io.ReadAtLeast(r, addr, len(addr)); err != nil {
            return nil, err
        }
        d.IP = net.IP(addr)

    case fqdnAddress:
        if _, err := r.Read(addrType); err != nil {
            return nil, err
        }
        addrLen := int(addrType[0])
        fqdn := make([]byte, addrLen)
        if _, err := io.ReadAtLeast(r, fqdn, addrLen); err != nil {
            return nil, err
        }
        d.FQDN = string(fqdn)

    default:
        return nil, errors.New("unrecognizedAddrType")
    }

    // Read the port
    port := []byte{0, 0}
    if _, err := io.ReadAtLeast(r, port, 2); err != nil {
        return nil, err
    }
    d.Port = (int(port[0]) << 8) | int(port[1])

    return d, nil
}


来源: stackexchange

问:
What are the requirements for video in an image tag to work in Safari?
Apple recommends using mp4 video files in image tags instead of gifs

Use MP4 Video Instead of Animated GIFs

GIFs can be up to 12 times as expensive in bandwidth and twice as expensive in energy use when compared to a modern video codec. Instead, use H.264-encoded MP4 files for animations; for example:

```<code><img src="explosion.mp4" alt="An explosion of colors.">
</code>```

From: https://developer.apple.com/documentation/webkit/delivering_video_content_for_safari

But I tried it and it failed on iOS 16.2 Safari (worked on MacOS Safari)

```

The instructions say h.264 but the file is h.264

Stream #0:0(und): Video: h264 (Main) (avc1 / 0x31637661), yuv420p(tv, smpte170m/bt709/bt709), 230x130, 490 kb/s, 30 fps, 30 tbr, 12k tbn, 60 tbc (default)

note: yes of course it doesn't work in Chrome/Edge/Firefox. The Apple article lists a workaround.

ContentLicense: CC BY-SA 4.0

Body:
Apple recommends using mp4 video files in image tags instead of gifs

Use MP4 Video Instead of Animated GIFs

GIFs can be up to 12 times as expensive in bandwidth and twice as expensive in energy use when compared to a modern video codec. Instead, use H.264-encoded MP4 files for animations; for example:

From: https://developer.apple.com/documentation/webkit/delivering_video_content_for_safari

But I tried it and it failed on iOS 16.2 Safari (worked on MacOS Safari)

The instructions say h.264 but the file is h.264

Stream #0:0(und): Video: h264 (Main) (avc1 / 0x31637661), yuv420p(tv, smpte170m/bt709/bt709), 230x130, 490 kb/s, 30 fps, 30 tbr, 12k tbn, 60 tbc (default)

note: yes of course it doesn't work in Chrome/Edge/Firefox. The Apple article lists a workaround.


问:
how to transform Unicode characters to a different font?
I was able to transform sinhala Unicode characters to symbols by just copying those characters into MS word and changing the font to TIMES NEW ROMAN, The letters are in the link image;

sequence of symbols and letters  =  fnda, rduqj - .Kl rduqj

But now I can't changed those Unicode characters into sequence of symbols and letters. Every time I paste those characters it doesn't allow me to change to another font type. How can I make it changeable or is there a better way of getting that sequence of letters?

ContentLicense: CC BY-SA 3.0


问:
Getting VCP codes from external monitor in C#
I need to get various VCP codes from an DDC/CI enabled external monitor in a C# application running on a Windows machine.

I have been able to find the WIN32 API which can does exactly this, but uses unmanaged code, specifically C++. Additionally, I have searched for native C# ways to do this and only 1 solution came up, namely the Nuget package MonitorControl. However, this Nuget package only support the highlevel, not lowlevel API, plus when I downloaded the package I wasn't able to use it due to missing files.

So from this website (Using the Low-Level Monitor Configuration Functions) I have been able to come up with some C++ code(largely copy/pasted from the example on the website), which I have implemented successfully.

#include "Windows.h"
#include "PhysicalMonitorEnumerationAPI.h"
#include "lowlevelmonitorconfigurationapi.h"

#pragma comment(lib, "Dxva2.lib")

void readVCPFromMonitor(BYTE vcpCode)
{
    HMONITOR hMonitor = NULL;
    DWORD cPhysicalMonitors;
    LPPHYSICAL_MONITOR pPhysicalMonitors = NULL;

    HWND hWnd = ::GetDesktopWindow();

    // Get the monitor handle.
    hMonitor = MonitorFromWindow(hWnd, MONITOR_DEFAULTTOPRIMARY);

    // Get the number of physical monitors.
    BOOL bSuccess = GetNumberOfPhysicalMonitorsFromHMONITOR(hMonitor, &cPhysicalMonitors);

    if (bSuccess)
    {
        // Allocate the array of PHYSICAL_MONITOR structures.
        pPhysicalMonitors = (LPPHYSICAL_MONITOR)malloc(cPhysicalMonitors * sizeof(PHYSICAL_MONITOR));

        if (pPhysicalMonitors != NULL)
        {
            // Get the array.
            bSuccess = GetPhysicalMonitorsFromHMONITOR(hMonitor, cPhysicalMonitors, pPhysicalMonitors);

            // Get physical monitor handle.
            HANDLE hPhysicalMonitor = pPhysicalMonitors[0].hPhysicalMonitor;

            MC_VCP_CODE_TYPE pvct = MC_SET_PARAMETER;
            DWORD pdwCurrentValue = 0;
            DWORD pdwMaximvumValue = 0;

            bSuccess = GetVCPFeatureAndVCPFeatureReply(hPhysicalMonitor, vcpCode, &pvct, &pdwCurrentValue, &pdwMaximvumValue);

            if (bSuccess == FALSE)
            {
                std::cout << "Error getting VCP Code" << std::endl;
            }

            else
            {
                std::cout << "VCP Code Value : " << std::dec << pdwCurrentValue << std::endl;
                if (pvct != 0)
                {
                    std::cout << "VCP Code Type: " << std::dec << pvct << std::endl;
                }
                if (pdwMaximvumValue != 0)
                {
                    std::cout << "VCP Code Max value: " << std::dec << pdwMaximvumValue << std::endl;
                }
            }

            // Close the monitor handles.
            bSuccess = DestroyPhysicalMonitors(cPhysicalMonitors, pPhysicalMonitors);

            // Free the array.
            free(pPhysicalMonitors);
        }
    }
}
```

This code can be called with a specific VCP code as a parameter and spits out the result to the console, just for testing purposes. But now I need to "translate" this code to C#, and I dont know how to do the proper marshalling.

Any pointers, example code or other help would be greatly appreciated!

Final note: I have also found the Nuget package CsWin32 which should automate much of the marshalling, but I have not yet succeded.

If anyone know of a library or anything else that I can use, I am also very open to that.

Body:
I need to get various VCP codes from an DDC/CI enabled external monitor in a C# application running on a Windows machine.

I have been able to find the WIN32 API which can does exactly this, but uses unmanaged code, specifically C++. Additionally, I have searched for native C# ways to do this and only 1 solution came up, namely the Nuget package MonitorControl. However, this Nuget package only support the highlevel, not lowlevel API, plus when I downloaded the package I wasn't able to use it due to missing files.

So from this website (Using the Low-Level Monitor Configuration Functions) I have been able to come up with some C++ code(largely copy/pasted from the example on the website), which I have implemented successfully.

#include "Windows.h"
#include "PhysicalMonitorEnumerationAPI.h"
#include "lowlevelmonitorconfigurationapi.h"

#pragma comment(lib, "Dxva2.lib")

void readVCPFromMonitor(BYTE vcpCode)
{
    HMONITOR hMonitor = NULL;
    DWORD cPhysicalMonitors;
    LPPHYSICAL_MONITOR pPhysicalMonitors = NULL;

    HWND hWnd = ::GetDesktopWindow();

    // Get the monitor handle.
    hMonitor = MonitorFromWindow(hWnd, MONITOR_DEFAULTTOPRIMARY);

    // Get the number of physical monitors.
    BOOL bSuccess = GetNumberOfPhysicalMonitorsFromHMONITOR(hMonitor, &cPhysicalMonitors);

    if (bSuccess)
    {
        // Allocate the array of PHYSICAL_MONITOR structures.
        pPhysicalMonitors = (LPPHYSICAL_MONITOR)malloc(cPhysicalMonitors * sizeof(PHYSICAL_MONITOR));

        if (pPhysicalMonitors != NULL)
        {
            // Get the array.
            bSuccess = GetPhysicalMonitorsFromHMONITOR(hMonitor, cPhysicalMonitors, pPhysicalMonitors);

            // Get physical monitor handle.
            HANDLE hPhysicalMonitor = pPhysicalMonitors[0].hPhysicalMonitor;

            MC_VCP_CODE_TYPE pvct = MC_SET_PARAMETER;
            DWORD pdwCurrentValue = 0;
            DWORD pdwMaximvumValue = 0;

            bSuccess = GetVCPFeatureAndVCPFeatureReply(hPhysicalMonitor, vcpCode, &pvct, &pdwCurrentValue, &pdwMaximvumValue);

            if (bSuccess == FALSE)
            {
                std::cout << "Error getting VCP Code" << std::endl;
            }

            else
            {
                std::cout << "VCP Code Value : " << std::dec << pdwCurrentValue << std::endl;
                if (pvct != 0)
                {
                    std::cout << "VCP Code Type: " << std::dec << pvct << std::endl;
                }
                if (pdwMaximvumValue != 0)
                {
                    std::cout << "VCP Code Max value: " << std::dec << pdwMaximvumValue << std::endl;
                }
            }

            // Close the monitor handles.
            bSuccess = DestroyPhysicalMonitors(cPhysicalMonitors, pPhysicalMonitors);

            // Free the array.
            free(pPhysicalMonitors);
        }
    }
}

This code can be called with a specific VCP code as a parameter and spits out the result to the console, just for testing purposes. But now I need to "translate" this code to C#, and I dont know how to do the proper marshalling.

Any pointers, example code or other help would be greatly appreciated!

Final note: I have also found the Nuget package CsWin32 which should automate much of the marshalling, but I have not yet succeded.

If anyone know of a library or anything else that I can use, I am also very open to that.


问:
Why does makefile pattern rule fail with spaces in name. How do I fix it?
For a Makefile containing...

```<code>File\ space.o: %.o : %.c
        echo hello
</code>```

make returns

```<code>make: *** No rule to make target 'File.c space.c', needed by 'File space.o'.  Stop.
</code>```

Why does it not return...

```<code>make: *** No rule to make target 'File space.c', needed by 'File space.o'.  Stop.
</code>```

?

Body:
For a Makefile containing...

File\ space.o: %.o : %.c
        echo hello

make returns

make: *** No rule to make target 'File.c space.c', needed by 'File space.o'.  Stop.

Why does it not return...

make: *** No rule to make target 'File space.c', needed by 'File space.o'.  Stop.

?


问:
How to show JProgressBar for InputStream while reading data from a SerialPort?
I'm trying to show a JProgressBar in a Swing application used for communicating with a device using a SerialPort connection.

Sometimes the data that the device sends is large so it can take some time(5-10 seconds) to receive the data. Because of that, I want to show the user a progress bar so he knows that something is happening.

I tried doing this with JProgressBar and also with ProgressMonitor, but I just managed to show the progress window, but it just stayed at 0%.

Here is a method that I use to read the serialPort.

```<code>public static void readingDataSB9(SerialPort comPort) {

    comPort.addDataListener(new SerialPortDataListener() {
        @Override
        public int getListeningEvents() {
            return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
        }

        @Override
        public void serialEvent(SerialPortEvent serialPortEvent) {
            try {

                if (serialPortEvent.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE) {
                    return;
                }

                //here I save the count data in the string array
                List<String> countData = new ArrayList<>();
                //here I save the text that is OCRed from the images
                List<String> ocrText = new ArrayList<>();
                //here I save the images from the machine
                List<ImageIcon> serialImage = new ArrayList<>();

                //trying to decode non UTF-8 strings from an array of Strings, only for TEST purposes
                CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
                decoder.onMalformedInput(CodingErrorAction.IGNORE);

                //Strings that represent the start of the serial number and new lines on each serial number
                String startSn = "110000010011010001101100100011011000100011010000111000010001010";
                String newLine = "01100000110110010001101100010001101000011100001000101";

                int x = 0;
                String s1 = "";

                //getting InputStream from serial port and then converting it to BufferedStream, so it can be reset
                //and read two times
                InputStream in = comPort.getInputStream();
                InputStream bufferdInputStream = new BufferedInputStream(in);
                bufferdInputStream.mark(1000000000);

                //I try to show progress of receiving data from InputStream
                showProgress(bufferdInputStream, MainWindow.frame);

                //first reading the input stream with scanner to get count data as Strings
                Scanner sc = new Scanner(bufferdInputStream);

                while (sc.hasNextLine()) {

                    countData.add(sc.next());
                    //this is the last string in the InputStream, so I use it to break from the while loop
                    if (countData.contains("\u001Bm\u001B3")) {
                        break;
                    }
                }

                System.out.println(countData);

                //here I reset the InputStream, so it can be read again to receive the bytes needed to get the image
                //of serial number
                bufferdInputStream.reset();

                while (((x = bufferdInputStream.read()) != 109)) {
                    //bytes are converted to binaryStrings, so I can get the binary image with Java Graphics library
                    s1 += String.format("%8s", Integer.toBinaryString(x & 0xFF)).replace(' ', '0');
                }

                //bytes are stored in the String array, they are split by String for the start of serial number
                String[] binarySerialNumberArr = s1.split(startSn);

                //here I immediately write the binaryString to the gui of MainWindow, so it can be saved to the database
                MainWindow.jt_serialBinary.setText(String.join(", ", binarySerialNumberArr));

                //here we take each element of String array and convert it from BinaryString to image
                for (int i = 1; i < binarySerialNumberArr.length; i++) {

                    //first we create a empty image
                    BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
                    Graphics2D g2d = img.createGraphics();
                    Font font = new Font("Arial", Font.PLAIN, 2);
                    g2d.setFont(font);
                    int height = g2d.getFontMetrics().getHeight();
                    g2d.dispose();

                    //here we start to create the actual image of the serial number
                    img = new BufferedImage(384, 40, BufferedImage.TYPE_INT_RGB);
                    g2d = img.createGraphics();

                    g2d.setFont(font);
                    g2d.setColor(Color.WHITE);
                    int fontSize = 1;

                    for (String s : binarySerialNumberArr[i].split(newLine)) {
                        //we draw each string and use the newLine String to split the array element
                        //each 0 is represented as white, and 1 as black
                        g2d.drawString(s, 0, height);
                        height += fontSize;
                    }
                    //creating the image file
                    File file = new File("images\\Text" + i + ".png");
                    //saving the image to file
                    ImageIO.write(img, "png", file);
                    g2d.dispose();

                    //here we use the Tesseracts OCR library to get OCR text from image file
                    String ocrString = SerialOcr(file);
                    //here we fix some mistakes that OCR library does when doing OCR on images and add the data to
                    //OCR string array
                    ocrText.add(trainOcr(ocrString));
                    //we convert to image to ImageIcon and add it to ImageIcon array
                    serialImage.add(makeIcon(img));

                    System.out.println(ocrString);
                }

                //here we add ocrText to gui MainWindow
                for (int i = 0; i < ocrText.size(); i++) {
                    MainWindow.model_ocrText.add(i, ocrText.get(i));
                }
                //here we add images to gui MainWindow
                for (int i = 0; i < serialImage.size(); i++) {
                    MainWindow.model_serialImage.add(i, serialImage.get(i));
                }

                //here I try to ignore non UTF-8 string so I can get the OCR values from the machine also
                //this is a TEST
                ArrayList<String> validData = new ArrayList<>();

                for (int i = 0; i < countData.size(); i++) {
                    decoder.decode(java.nio.ByteBuffer.wrap(countData.get(i).getBytes()));
                    validData.add(countData.get(i));
                }

                System.out.println(validData);

                //checking to see what currency is the data from the machine, and building the gui table accordingly
                for (int i = 0; i < countData.size(); i++) {
                    switch (countData.get(i)) {
                        case "RSD" -> insertRSD(countData, MainWindow.jt_denom);
                        case "USD" -> insertUSD(countData, MainWindow.jt_denom);
                        case "EUR" -> insertEUR(countData, MainWindow.jt_denom);
                        default ->
                            //in case none of the above currencies is chosen, we show the error message on JOptionPane
                                JOptionPane.showMessageDialog(null, "Odabrana valuta nije podržana", "Greška!", JOptionPane.ERROR_MESSAGE);
                    }
                }

                //after getting all the data to the gui table in MainWindow, we calculate the total count data
                ButtonListeners.tableTotalAmountRows(MainWindow.jt_denom);
                ButtonListeners.tableTotalAmountColumns(MainWindow.jt_denom);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

}
</code>```

Here is the showProgress method.

```<code>public static void showProgress(InputStream bufferedInputStream, JFrame frame) throws IOException {
    JOptionPane pane = new JOptionPane();
    pane.setMessage("Receiving data...");
    JProgressBar jProgressBar = new JProgressBar(1, bufferedInputStream.available());
    jProgressBar.setValue(bufferedInputStream.read());
    pane.add(jProgressBar,1);
    JDialog dialog = pane.createDialog(frame, "Information message");
    dialog.setVisible(true);
    dialog.dispose();
}
</code>```

If someone has a better idea of how to show the progress, or just to keep the message on the screen while the data is being received, please feel free to suggest it.

Thanks in advance

Body:
I'm trying to show a JProgressBar in a Swing application used for communicating with a device using a SerialPort connection.

Sometimes the data that the device sends is large so it can take some time(5-10 seconds) to receive the data. Because of that, I want to show the user a progress bar so he knows that something is happening.

I tried doing this with JProgressBar and also with ProgressMonitor, but I just managed to show the progress window, but it just stayed at 0%.

Here is a method that I use to read the serialPort.

public static void readingDataSB9(SerialPort comPort) {

    comPort.addDataListener(new SerialPortDataListener() {
        @Override
        public int getListeningEvents() {
            return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
        }

        @Override
        public void serialEvent(SerialPortEvent serialPortEvent) {
            try {

                if (serialPortEvent.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE) {
                    return;
                }

                //here I save the count data in the string array
                List<String> countData = new ArrayList<>();
                //here I save the text that is OCRed from the images
                List<String> ocrText = new ArrayList<>();
                //here I save the images from the machine
                List<ImageIcon> serialImage = new ArrayList<>();

                //trying to decode non UTF-8 strings from an array of Strings, only for TEST purposes
                CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
                decoder.onMalformedInput(CodingErrorAction.IGNORE);

                //Strings that represent the start of the serial number and new lines on each serial number
                String startSn = "110000010011010001101100100011011000100011010000111000010001010";
                String newLine = "01100000110110010001101100010001101000011100001000101";

                int x = 0;
                String s1 = "";

                //getting InputStream from serial port and then converting it to BufferedStream, so it can be reset
                //and read two times
                InputStream in = comPort.getInputStream();
                InputStream bufferdInputStream = new BufferedInputStream(in);
                bufferdInputStream.mark(1000000000);

                //I try to show progress of receiving data from InputStream
                showProgress(bufferdInputStream, MainWindow.frame);

                //first reading the input stream with scanner to get count data as Strings
                Scanner sc = new Scanner(bufferdInputStream);

                while (sc.hasNextLine()) {

                    countData.add(sc.next());
                    //this is the last string in the InputStream, so I use it to break from the while loop
                    if (countData.contains("\u001Bm\u001B3")) {
                        break;
                    }
                }

                System.out.println(countData);

                //here I reset the InputStream, so it can be read again to receive the bytes needed to get the image
                //of serial number
                bufferdInputStream.reset();

                while (((x = bufferdInputStream.read()) != 109)) {
                    //bytes are converted to binaryStrings, so I can get the binary image with Java Graphics library
                    s1 += String.format("%8s", Integer.toBinaryString(x & 0xFF)).replace(' ', '0');
                }

                //bytes are stored in the String array, they are split by String for the start of serial number
                String[] binarySerialNumberArr = s1.split(startSn);

                //here I immediately write the binaryString to the gui of MainWindow, so it can be saved to the database
                MainWindow.jt_serialBinary.setText(String.join(", ", binarySerialNumberArr));

                //here we take each element of String array and convert it from BinaryString to image
                for (int i = 1; i < binarySerialNumberArr.length; i++) {

                    //first we create a empty image
                    BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
                    Graphics2D g2d = img.createGraphics();
                    Font font = new Font("Arial", Font.PLAIN, 2);
                    g2d.setFont(font);
                    int height = g2d.getFontMetrics().getHeight();
                    g2d.dispose();

                    //here we start to create the actual image of the serial number
                    img = new BufferedImage(384, 40, BufferedImage.TYPE_INT_RGB);
                    g2d = img.createGraphics();

                    g2d.setFont(font);
                    g2d.setColor(Color.WHITE);
                    int fontSize = 1;

                    for (String s : binarySerialNumberArr[i].split(newLine)) {
                        //we draw each string and use the newLine String to split the array element
                        //each 0 is represented as white, and 1 as black
                        g2d.drawString(s, 0, height);
                        height += fontSize;
                    }
                    //creating the image file
                    File file = new File("images\\Text" + i + ".png");
                    //saving the image to file
                    ImageIO.write(img, "png", file);
                    g2d.dispose();

                    //here we use the Tesseracts OCR library to get OCR text from image file
                    String ocrString = SerialOcr(file);
                    //here we fix some mistakes that OCR library does when doing OCR on images and add the data to
                    //OCR string array
                    ocrText.add(trainOcr(ocrString));
                    //we convert to image to ImageIcon and add it to ImageIcon array
                    serialImage.add(makeIcon(img));

                    System.out.println(ocrString);
                }

                //here we add ocrText to gui MainWindow
                for (int i = 0; i < ocrText.size(); i++) {
                    MainWindow.model_ocrText.add(i, ocrText.get(i));
                }
                //here we add images to gui MainWindow
                for (int i = 0; i < serialImage.size(); i++) {
                    MainWindow.model_serialImage.add(i, serialImage.get(i));
                }

                //here I try to ignore non UTF-8 string so I can get the OCR values from the machine also
                //this is a TEST
                ArrayList<String> validData = new ArrayList<>();

                for (int i = 0; i < countData.size(); i++) {
                    decoder.decode(java.nio.ByteBuffer.wrap(countData.get(i).getBytes()));
                    validData.add(countData.get(i));
                }

                System.out.println(validData);

                //checking to see what currency is the data from the machine, and building the gui table accordingly
                for (int i = 0; i < countData.size(); i++) {
                    switch (countData.get(i)) {
                        case "RSD" -> insertRSD(countData, MainWindow.jt_denom);
                        case "USD" -> insertUSD(countData, MainWindow.jt_denom);
                        case "EUR" -> insertEUR(countData, MainWindow.jt_denom);
                        default ->
                            //in case none of the above currencies is chosen, we show the error message on JOptionPane
                                JOptionPane.showMessageDialog(null, "Odabrana valuta nije podržana", "Greška!", JOptionPane.ERROR_MESSAGE);
                    }
                }

                //after getting all the data to the gui table in MainWindow, we calculate the total count data
                ButtonListeners.tableTotalAmountRows(MainWindow.jt_denom);
                ButtonListeners.tableTotalAmountColumns(MainWindow.jt_denom);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

}

Here is the showProgress method.

public static void showProgress(InputStream bufferedInputStream, JFrame frame) throws IOException {
    JOptionPane pane = new JOptionPane();
    pane.setMessage("Receiving data...");
    JProgressBar jProgressBar = new JProgressBar(1, bufferedInputStream.available());
    jProgressBar.setValue(bufferedInputStream.read());
    pane.add(jProgressBar,1);
    JDialog dialog = pane.createDialog(frame, "Information message");
    dialog.setVisible(true);
    dialog.dispose();
}

If someone has a better idea of how to show the progress, or just to keep the message on the screen while the data is being received, please feel free to suggest it.

Thanks in advance


问:
android greendao plugin config confusing
In latest androidstudio, the project build.gradle format changed as below:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.3.1' apply false
    id 'com.android.library' version '7.3.1' apply false
    id 'org.greenrobot-gradle-plugin' version '3.2.1' apply false
}
</code>```

The 3rd line report error:
P

```<code>lugin [id: 'org.greenrobot-gradle-plugin', version: '3.2.1', apply: false] was not found in any of the following sources:
</code>```

I know the old androidstudio use below format:

```<code>buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
    }
}
</code>```

How should I convert old build.gradle config to new format?

Body:
In latest androidstudio, the project build.gradle format changed as below:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.3.1' apply false
    id 'com.android.library' version '7.3.1' apply false
    id 'org.greenrobot-gradle-plugin' version '3.2.1' apply false
}

The 3rd line report error:
P

lugin [id: 'org.greenrobot-gradle-plugin', version: '3.2.1', apply: false] was not found in any of the following sources:

I know the old androidstudio use below format:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
    }
}

How should I convert old build.gradle config to new format?


问:
move duplicates to the end of array in c while preserving order - nlogn
I am stuck in this question for long time.
the question is - to move duplicates to the end of the array while preserving the order(time complexity must be O(nlogn)).
limitation:

order must be preserved.

can use only 1 helper array

the range of values in the array are not known and can be really large from n(which is the size fo the array).

values are positives.

time complexity - nlogn

example:
arr = {7, 3, 1, 2, 7, 9, 3, 2, 5, 9, 6, 2}, n = 12
result:
arr = {7, 3, 1, 2, 9, 5, 6, 2, 9, 2, 3, 7}

this what i did right now but i am stuck from thier:

copied original array to temp array

sort the temp array using quick sort

move duplicate to the end in temp array

i know that i need to do some comparison with the original array but this the part that i am stuck.

code:

```<code>int findDulpilcatesV2(int* arr, int n) {
    int i, * tempArr, j = 0, countNonRepeatEl = 0, searchKeyIndex, elIndex;

    tempArr = (int*)calloc(n, sizeof(int));
    assert(tempArr);

    // Saving original array in temp array
    for (i = 0; i < n; i++)
    {
        tempArr[i] = arr[i];
    }

    // Sorting temp array
    quickSort(tempArr, 0, n - 1);

    // Move duplicates to the end
    for (i = 0; i < n; i++)
    {
        if (tempArr[i] != tempArr[i+1])
        {
            swap(&tempArr[j], &tempArr[i]);
            countNonRepeatEl++;
            j++;
        }
    }

    free(tempArr);
    tempArr = NULL;
    return countNonRepeatEl;
}
</code>```

Body:
I am stuck in this question for long time.
the question is - to move duplicates to the end of the array while preserving the order(time complexity must be O(nlogn)).
limitation:

order must be preserved.

can use only 1 helper array

the range of values in the array are not known and can be really large from n(which is the size fo the array).

values are positives.

time complexity - nlogn

example:
arr = {7, 3, 1, 2, 7, 9, 3, 2, 5, 9, 6, 2}, n = 12
result:
arr = {7, 3, 1, 2, 9, 5, 6, 2, 9, 2, 3, 7}

this what i did right now but i am stuck from thier:

copied original array to temp array

sort the temp array using quick sort

move duplicate to the end in temp array

i know that i need to do some comparison with the original array but this the part that i am stuck.

code:

int findDulpilcatesV2(int* arr, int n) {
    int i, * tempArr, j = 0, countNonRepeatEl = 0, searchKeyIndex, elIndex;

    tempArr = (int*)calloc(n, sizeof(int));
    assert(tempArr);

    // Saving original array in temp array
    for (i = 0; i < n; i++)
    {
        tempArr[i] = arr[i];
    }

    // Sorting temp array
    quickSort(tempArr, 0, n - 1);

    // Move duplicates to the end
    for (i = 0; i < n; i++)
    {
        if (tempArr[i] != tempArr[i+1])
        {
            swap(&tempArr[j], &tempArr[i]);
            countNonRepeatEl++;
            j++;
        }
    }

    free(tempArr);
    tempArr = NULL;
    return countNonRepeatEl;
}


问:
How to rewrite this lambda so it circumvents latebinding

Problem

As far as I'm aware, this undesired behaviour (by my standards) happens, because of late-binding in contrast to early binding in the loop. That is, when the lambda function is called, the iterator variables all have the same values, namely the ones after all loops are finnished.

```<code>for color in range(N_COLORS):
    for hsv in range(N_HSV):
        for mm in range(N_MINMAX):
            cv2.createTrackbar(STR_COLORS[color] + STR_HSV[hsv] + STR_MINMAX[mm], window_title, 0, 255, lambda x: change(color, hsv, mm, x))
</code>```

Question

How can I rewrite this code, so that each Trackbar that is created, has distinct values for color, hsv and mm instead of all of them having the same value.

Minimal Working Example:

```<code>import numpy as np

N_COLORS = 3
N_HSV = 3
N_MINMAX = 2

list = []

for color in range(N_COLORS):
    for hsv in range(N_HSV):
        for mm in range(N_MINMAX):
            list.append(lambda: print(color, hsv, mm))

list[0]()
list[1]()
list[2]()
</code>```

expected output:

[0, 0, 0]

[0, 0, 1]

[0, 1, 0]

actual output:

[2, 2, 1]

[2, 2, 1]

[2, 2, 1]

Answer

As per the duplicate, this solves it

```<code>cv2.createTrackbar(STR_COLORS[color] + STR_HSV[hsv] + STR_MINMAX[mm], window_title, 0, 255, lambda x, color=color, hsv=hsv, mm=mm: change(color, hsv, mm, x))
</code>```

Body:
Problem

As far as I'm aware, this undesired behaviour (by my standards) happens, because of late-binding in contrast to early binding in the loop. That is, when the lambda function is called, the iterator variables all have the same values, namely the ones after all loops are finnished.

for color in range(N_COLORS):
    for hsv in range(N_HSV):
        for mm in range(N_MINMAX):
            cv2.createTrackbar(STR_COLORS[color] + STR_HSV[hsv] + STR_MINMAX[mm], window_title, 0, 255, lambda x: change(color, hsv, mm, x))

Question

How can I rewrite this code, so that each Trackbar that is created, has distinct values for color, hsv and mm instead of all of them having the same value.

Minimal Working Example:

import numpy as np

N_COLORS = 3
N_HSV = 3
N_MINMAX = 2

list = []

for color in range(N_COLORS):
    for hsv in range(N_HSV):
        for mm in range(N_MINMAX):
            list.append(lambda: print(color, hsv, mm))

list[0]()
list[1]()
list[2]()

expected output:

[0, 0, 0]

[0, 0, 1]

[0, 1, 0]

actual output:

[2, 2, 1]

[2, 2, 1]

[2, 2, 1]

Answer

As per the duplicate, this solves it

cv2.createTrackbar(STR_COLORS[color] + STR_HSV[hsv] + STR_MINMAX[mm], window_title, 0, 255, lambda x, color=color, hsv=hsv, mm=mm: change(color, hsv, mm, x))


问:
Removing error of looping through columns in a Latex Tabular Environment
Hi I am using the following code to try and dynamically set the number of columns in a Latex tabular environment:

```<code>\documentclass{article}

\usepackage{array}

\newcounter{numcols}
\setcounter{numcols}{4}

\begin{document}

\begin{tabular}{
$\loop
\stepcounter{col}
\ifnum \value{col} < \value{numcols}
    c &
\else
    c
\fi
\ifnum \value{col} = \value{numcols}
    \setcounter{col}{0}
\repeat$
}
\hline
\loop
\stepcounter{col}
\ifnum \value{col} < \value{numcols}
    \textbf{Column \thecol} &
\else
    \textbf{Column \thecol} \\
\fi
\ifnum \value{col} = \value{numcols}
    \setcounter{col}{0}
\repeat
\hline
\loop
\stepcounter{row}
\ifnum \value{row} < 10
    \loop
    \stepcounter{col}
    \ifnum \value{col} < \value{numcols}
        Cell \therow,\thecol &
    \else
        Cell \therow,\thecol \\
    \fi
    \ifnum \value{col} = \value{numcols}
        \setcounter{col}{0}
    \repeat
\repeat
\hline
\end{tabular}

\end{document}
</code>```

However, it throws an error that Illegal pream-token ($): c' used if I remove the $ I receive the same error but it says Illegal pream-token (\loop): c' used.

Any help on solving this error would be much appreciated.

I need to create a table with a dynamic number of columns in Latex

Body:
Hi I am using the following code to try and dynamically set the number of columns in a Latex tabular environment:

\documentclass{article}

\usepackage{array}

\newcounter{numcols}
\setcounter{numcols}{4}

\begin{document}

\begin{tabular}{
$\loop
\stepcounter{col}
\ifnum \value{col} < \value{numcols}
    c &
\else
    c
\fi
\ifnum \value{col} = \value{numcols}
    \setcounter{col}{0}
\repeat$
}
\hline
\loop
\stepcounter{col}
\ifnum \value{col} < \value{numcols}
    \textbf{Column \thecol} &
\else
    \textbf{Column \thecol} \\
\fi
\ifnum \value{col} = \value{numcols}
    \setcounter{col}{0}
\repeat
\hline
\loop
\stepcounter{row}
\ifnum \value{row} < 10
    \loop
    \stepcounter{col}
    \ifnum \value{col} < \value{numcols}
        Cell \therow,\thecol &
    \else
        Cell \therow,\thecol \\
    \fi
    \ifnum \value{col} = \value{numcols}
        \setcounter{col}{0}
    \repeat
\repeat
\hline
\end{tabular}

\end{document}

However, it throws an error that Illegal pream-token ($): c' used if I remove the $ I receive the same error but it says Illegal pream-token (\loop): c' used.

Any help on solving this error would be much appreciated.

I need to create a table with a dynamic number of columns in Latex


问:
How to diagnose ownership errors and fix them?
I just wanted to read file contents from a user picked file and save them to a var.
Unfortunately I am getting Ownership Errors, but I dont know how to pass a mutable Reference to the function I'm calling in the following code:

use tauri::api::dialog::FileDialogBuilder;

#[tauri::command]
fn import_file() -> String {

    let mut file_contents = String::new();
    let mut file_name = String::new();

    FileDialogBuilder::new()
        .set_title("Select a file to import")
        .pick_file(|file_path| {
            // do something with the optional file path here
            // the file path is `None` if the user closed the dialog
            if let Some(file_path) = file_path {
                println!("{}", file_path.to_string_lossy().into_owned());
                let contents = std::fs::read_to_string(file_path).unwrap();
                file_contents = contents;
            }
        });

    println!("{}", file_contents);

    return String::from("yoo");
}
```

I tried wrapping the expression in a block and assigned it to the var like
file_contents = { FileDialogBuilder::new()...
but got errors again.

I tried to cargo-expand the main.rs but got unreadable binary code. Seems to come from tauri.

Body:
I just wanted to read file contents from a user picked file and save them to a var.
Unfortunately I am getting Ownership Errors, but I dont know how to pass a mutable Reference to the function I'm calling in the following code:

use tauri::api::dialog::FileDialogBuilder;

#[tauri::command]
fn import_file() -> String {

    let mut file_contents = String::new();
    let mut file_name = String::new();

    FileDialogBuilder::new()
        .set_title("Select a file to import")
        .pick_file(|file_path| {
            // do something with the optional file path here
            // the file path is `None` if the user closed the dialog
            if let Some(file_path) = file_path {
                println!("{}", file_path.to_string_lossy().into_owned());
                let contents = std::fs::read_to_string(file_path).unwrap();
                file_contents = contents;
            }
        });

    println!("{}", file_contents);

    return String::from("yoo");
}

I tried wrapping the expression in a block and assigned it to the var like
file_contents = { FileDialogBuilder::new()...
but got errors again.

I tried to cargo-expand the main.rs but got unreadable binary code. Seems to come from tauri.


问:
Dynamic site content based on previous hovers, clicks, scrolls
I am looking for easy-to-build website development platforms that allows me to also manage and deliver dynamic web content based on prior user events such as clicks, hovers, scrolls. For example, if one engaged more with cat-themed content and assets than dog-themed, I want to dynamically load similarly themed content and assets going forward.

Did not find anything on Wix, SquareSpace, Wordpress, Hubspot CMS. Perhaps I am also searching using the wrong terminologies.

Looking for webdev services. And/or terminologies  that I should be researching (if commercial recommendations are off-topic).


问:
Is there a way to programmatically open a NEW built-in terminal in VSCode from the terminal/bash?
Specifically I'd like to run a terminal command from vscode's built in terminal and have that command open another new vscode built-in terminal. Is this possible?

This is related to my question here - https://github.com/mklement0/ttab/issues/51#issuecomment-1372825316

Say I have the following command in my package.json scripts:

```<code>"sayHello": "ttab echo hello",
</code>```

And I run npm run sayHello from the vscode integrated terminal. Is
there a way to have it so that the new terminal that is created is
created within the integrated terminal instead of from (in my case)
the default mac terminal application?

Body:
Specifically I'd like to run a terminal command from vscode's built in terminal and have that command open another new vscode built-in terminal. Is this possible?

This is related to my question here - https://github.com/mklement0/ttab/issues/51#issuecomment-1372825316

Say I have the following command in my package.json scripts:

"sayHello": "ttab echo hello",

And I run npm run sayHello from the vscode integrated terminal. Is
there a way to have it so that the new terminal that is created is
created within the integrated terminal instead of from (in my case)
the default mac terminal application?


问:
Strange issue when no breakpoint is set when calling SslStream.AuthenticateAsServer
I am adding some code to a legacy application running .net 4.5.2. I copied some code from .net 4.8 solution for decrypting the Ssl Stream. My Code works fine when I have a breakpoint right on or right after  SslStream.AuthenticateAsServer. if I statement "return sslStream"

```<code>        public SslStream DecrtyptStream(TcpClient client)
        {

            bool clientCertificateRequired = false;
            SslStream sslStream = null;
            if (gTLS_CertEnable == "Yes")
            {
                clientCertificateRequired = true;

                sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(_validateServerCertificate));
            }
            else
            {
                sslStream = new SslStream(client.GetStream(), false);
            }
            sslStream.ReadTimeout = 60000;
            sslStream.WriteTimeout = 5000;
            if (gTLS_Ver == "TLS1.0")
            {
                sslStream.AuthenticateAsServer(_serverCertificate, clientCertificateRequired, SslProtocols.Tls, true);

            }
            else if (gTLS_Ver == "TLS1.1")
            {
                sslStream.AuthenticateAsServer(_serverCertificate, clientCertificateRequired, SslProtocols.Tls11, true);

            }
            else
            {
                //https://stackoverflow.com/questions/38236302/the-client-and-server-cannot-communicate-because-they-do-not-possess-a-common-a
                sslStream.AuthenticateAsServer(_serverCertificate, clientCertificateRequired, SslProtocols.Tls12, true);
            }
            return sslStream;
        }
</code>```

When I remove the breakpoint I get this error:

The client and server cannot communicate, because they do not possess
a common algorithm.

So as shown in a stackoverflow post I changed it to

```<code>sslStream.AuthenticateAsServer(_serverCertificate, clientCertificateRequired, SslProtocols.Tls11 | SslProtocols.Tls | SslProtocols.Tls12, true);
</code>```

I get this error message:

The supplied message is incomplete. The signature was not verified

But still if I add a breakpoint, this error does not happen.

Body:
I am adding some code to a legacy application running .net 4.5.2. I copied some code from .net 4.8 solution for decrypting the Ssl Stream. My Code works fine when I have a breakpoint right on or right after  SslStream.AuthenticateAsServer. if I statement "return sslStream"

        public SslStream DecrtyptStream(TcpClient client)
        {

            bool clientCertificateRequired = false;
            SslStream sslStream = null;
            if (gTLS_CertEnable == "Yes")
            {
                clientCertificateRequired = true;

                sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(_validateServerCertificate));
            }
            else
            {
                sslStream = new SslStream(client.GetStream(), false);
            }
            sslStream.ReadTimeout = 60000;
            sslStream.WriteTimeout = 5000;
            if (gTLS_Ver == "TLS1.0")
            {
                sslStream.AuthenticateAsServer(_serverCertificate, clientCertificateRequired, SslProtocols.Tls, true);

            }
            else if (gTLS_Ver == "TLS1.1")
            {
                sslStream.AuthenticateAsServer(_serverCertificate, clientCertificateRequired, SslProtocols.Tls11, true);

            }
            else
            {
                //https://stackoverflow.com/questions/38236302/the-client-and-server-cannot-communicate-because-they-do-not-possess-a-common-a
                sslStream.AuthenticateAsServer(_serverCertificate, clientCertificateRequired, SslProtocols.Tls12, true);
            }
            return sslStream;
        }

When I remove the breakpoint I get this error:

The client and server cannot communicate, because they do not possess
a common algorithm.

So as shown in a stackoverflow post I changed it to

sslStream.AuthenticateAsServer(_serverCertificate, clientCertificateRequired, SslProtocols.Tls11 | SslProtocols.Tls | SslProtocols.Tls12, true);

I get this error message:

The supplied message is incomplete. The signature was not verified

But still if I add a breakpoint, this error does not happen.


问:
What's the point of an Impl block without struct fields in rust?
I don't really understand why there is the case where one would create an empty struct like this:

pub struct Foo;

and then subsequently have this:

```<code>impl Foo {
...
}
</code>```

It just doesn't make sense to me, why not just create a mod within the crate with a file that has the functions within the impl block above?

Body:
I don't really understand why there is the case where one would create an empty struct like this:

pub struct Foo;

and then subsequently have this:

impl Foo {
...
}

It just doesn't make sense to me, why not just create a mod within the crate with a file that has the functions within the impl block above?


问:
How can I prevent Excel from modifying the format of the values that I export from the table?
Im using xlsx.full.min.js and tableexport.min.js.
My problem is that when I create an Excel file with the data I export from a table I receive some modifications. This is because the id codes of some documents are very similar to a date format.

So, How can I prevent Excel from doing that?.

```<code>const $btnExportar = document.querySelector("#btnExportar"),
        $tabla = document.querySelector("#tabla");

$btnExportar.addEventListener("click", function() {
        let tableExport = new TableExport($tabla, {
            exportButtons: false, // No queremos botones
            filename: "requisiciones_reportes", //Nombre del archivo de Excel
            sheetname: "Reporte de prueba", //Título de la hoja
        });
        let datos = tableExport.getExportData();
        let preferenciasDocumento = datos.tabla.xlsx;
        tableExport.export2file(preferenciasDocumento.data, preferenciasDocumento.mimeType,   preferenciasDocumento.filename, preferenciasDocumento.fileExtension, preferenciasDocumento.merges, preferenciasDocumento.RTL, preferenciasDocumento.sheetname);
});
</code>```

How can I prevent Excel from doing that?.

Body:
Im using xlsx.full.min.js and tableexport.min.js.
My problem is that when I create an Excel file with the data I export from a table I receive some modifications. This is because the id codes of some documents are very similar to a date format.

So, How can I prevent Excel from doing that?.

const $btnExportar = document.querySelector("#btnExportar"),
        $tabla = document.querySelector("#tabla");

$btnExportar.addEventListener("click", function() {
        let tableExport = new TableExport($tabla, {
            exportButtons: false, // No queremos botones
            filename: "requisiciones_reportes", //Nombre del archivo de Excel
            sheetname: "Reporte de prueba", //Título de la hoja
        });
        let datos = tableExport.getExportData();
        let preferenciasDocumento = datos.tabla.xlsx;
        tableExport.export2file(preferenciasDocumento.data, preferenciasDocumento.mimeType,   preferenciasDocumento.filename, preferenciasDocumento.fileExtension, preferenciasDocumento.merges, preferenciasDocumento.RTL, preferenciasDocumento.sheetname);
});

How can I prevent Excel from doing that?.


问:
How to make normal subtitles in MoviePy
Writing this makes me feel stupid... So, currently I am trying to make a simple subtitles for a video - I have ready phrases and their durations. But I am really struggling with making a caption on the video. Is there any method to make subtitles without saving a bunch of files for moviepy?

I tried TextClip - it returned some strange error messages (tride to fix them, haven't succeed). Then I tried to make image via PIL and convert in to numpy.array - this didn't work either.

UPD

The code I tried write for ImageClip + PIL

```<code>def get_image(text: str) -> numpy.array:

    image = Image.new('RGB', (600, 400), color = (255, 255, 255))
    draw = ImageDraw.Draw(image)
    draw.text((10, 10), text.encode('utf-8'), fill=(255, 255, 0))
    image.show()

    return numpy.array(image)

audio_with_subtitles = [(str, int), ...]
textclips = [
    ImageClip(
        get_image(phrase),
    ).set_duration(duration)
    for phrase, duration in audio_with_subtitles
]
videoclip = CompositeVideoClip(
    [
        videoclip,
        *textclips,
    ]
)
</code>```

The tries with TextClip

```<code>audio_with_subtitles = [(str, int), ...]
textclips = [
    TextClip(
        phrase,
        fontsize=30,
        color='black',
    ).set_duration(duration)
    for phrase, duration in audio_with_subtitles
]
videoclip = CompositeVideoClip(
    [
        videoclip,
        *textclips,
    ]
)
</code>```

The error I got while using TextClip

```<code>OSError: convert-im6.q16: attempt to perform an operation not allowed by the security policy `@/tmp/tmp7wugzgq3.txt' @ error/property.c/InterpretImageProperties/3706.
convert-im6.q16: no images defined `PNG32:/tmp/tmpk3q2l74h.png' @ error/convert.c/ConvertImageCommand/3229.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/bifle/Desktop/tiktok_test.py", line 67, in <module>
    TextClip(
  File "/home/bifle/.local/lib/python3.10/site-packages/moviepy/video/VideoClip.py", line 1146, in __init__
    raise IOError(error)
OSError: MoviePy Error: creation of None failed because of the following error:

convert-im6.q16: attempt to perform an operation not allowed by the security policy `@/tmp/tmp7wugzgq3.txt' @ error/property.c/InterpretImageProperties/3706.
convert-im6.q16: no images defined `PNG32:/tmp/tmpk3q2l74h.png' @ error/convert.c/ConvertImageCommand/3229.
.

.This error can be due to the fact that ImageMagick is not installed on your computer, or (for Windows users) that you didn't specify the path to the ImageMagick binary in file conf.py, or that the path you specified is incorrect
</code>```

I tried installing ImageMagick and all *-dev things, nothing helped(

Title: How to make normal subtitles in MoviePy

Body:
Writing this makes me feel stupid... So, currently I am trying to make a simple subtitles for a video - I have ready phrases and their durations. But I am really struggling with making a caption on the video. Is there any method to make subtitles without saving a bunch of files for moviepy?

I tried TextClip - it returned some strange error messages (tride to fix them, haven't succeed). Then I tried to make image via PIL and convert in to numpy.array - this didn't work either.

UPD

The code I tried write for ImageClip + PIL

def get_image(text: str) -> numpy.array:

    image = Image.new('RGB', (600, 400), color = (255, 255, 255))
    draw = ImageDraw.Draw(image)
    draw.text((10, 10), text.encode('utf-8'), fill=(255, 255, 0))
    image.show()

    return numpy.array(image)

audio_with_subtitles = [(str, int), ...]
textclips = [
    ImageClip(
        get_image(phrase),
    ).set_duration(duration)
    for phrase, duration in audio_with_subtitles
]
videoclip = CompositeVideoClip(
    [
        videoclip,
        *textclips,
    ]
)

The tries with TextClip

audio_with_subtitles = [(str, int), ...]
textclips = [
    TextClip(
        phrase,
        fontsize=30,
        color='black',
    ).set_duration(duration)
    for phrase, duration in audio_with_subtitles
]
videoclip = CompositeVideoClip(
    [
        videoclip,
        *textclips,
    ]
)

The error I got while using TextClip

OSError: convert-im6.q16: attempt to perform an operation not allowed by the security policy `@/tmp/tmp7wugzgq3.txt' @ error/property.c/InterpretImageProperties/3706.
convert-im6.q16: no images defined `PNG32:/tmp/tmpk3q2l74h.png' @ error/convert.c/ConvertImageCommand/3229.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/bifle/Desktop/tiktok_test.py", line 67, in <module>
    TextClip(
  File "/home/bifle/.local/lib/python3.10/site-packages/moviepy/video/VideoClip.py", line 1146, in __init__
    raise IOError(error)
OSError: MoviePy Error: creation of None failed because of the following error:

convert-im6.q16: attempt to perform an operation not allowed by the security policy `@/tmp/tmp7wugzgq3.txt' @ error/property.c/InterpretImageProperties/3706.
convert-im6.q16: no images defined `PNG32:/tmp/tmpk3q2l74h.png' @ error/convert.c/ConvertImageCommand/3229.
.

.This error can be due to the fact that ImageMagick is not installed on your computer, or (for Windows users) that you didn't specify the path to the ImageMagick binary in file conf.py, or that the path you specified is incorrect

I tried installing ImageMagick and all *-dev things, nothing helped(


问:
fabletools models do not combine to give correct response, how to debug?

Summary

I have a tsibble that I have transformed into a mixed hierarchical (and grouped) time series. For the large majority of specified time series, I can obtain forecasts via the following:

```<code>fit <- hg_ts %>%
  fabletools::model(
    stl = fabletools::decomposition_model(
      feasts::STL(log(y), robust = TRUE),
      fable::ETS(season_adjust)))

fit %>%
  fabletools::forecast(h = 4)
</code>```

For many of the remaining time series, this produces no forecast. In particular, some time series return

```<code>Warning: Non-integer lag orders for random walk models are not supported. Rounding to the nearest integer.
...
Warning: 29 errors (1 unique) encountered for stl
[29] The models specified do not combine to give the correct response.
Please check that you have specified the decomposition models appropriately.
</code>```

Debugging difficulties

If I try debugonce(fabletools::decomposition_model), I see calls to fabletools::new_model_class() and fabletools::new_model_definition(). I took a look at https://fabletools.tidyverts.org/articles/extension_models.html (as well as https://r6.r-lib.org/articles/Debugging.html) but a lot is currently over my head.

How can I reach a "debugging" point (where I can examine all the objects the real code execution knows about) in model_decomposition.R's code where it says

```<code>  if(!isTRUE(all.equal(response(model)[[".response"]], .data[[measured_vars(.data)]]))){
    abort(
"The models specified do not combine to give the correct response.
Please check that you have specified the decomposition models appropriately.")
  }
</code>```

if this were my decomposition model:

library(magrittr)

tsibble::tourism %>%
    fabletools::aggregate_key((State/Region) * Purpose, Trips = sum(Trips)) %>%
    dplyr::filter(Purpose == "Business", State == "New South Wales") %>%
    fabletools::model(
        stl = fabletools::decomposition_model(
            feasts::STL(log(Trips), robust = TRUE),
            fable::ETS(season_adjust)))
#> Warning: 1 error encountered for dcmp
#> [1] promise already under evaluation: recursive default argument reference or earlier problems?
#> Warning: 1 error encountered for stl
#> [1] Problem while computing `cmp = map(.fit, components)`.
#> Loading required namespace: crayon
#> # A mable: 14 x 4
#> # Key:     State, Purpose, Region [14]
#>    State           Purpose  Region                                       stl
#>    <chr*>          <chr*>   <chr*>                                   <model>
#>  1 New South Wales Business Blue Mountains         <STL decomposition model>
#>  2 New South Wales Business Capital Country        <STL decomposition model>
#>  3 New South Wales Business Central Coast                       <NULL model>
#>  4 New South Wales Business Central NSW            <STL decomposition model>
#>  5 New South Wales Business Hunter                 <STL decomposition model>
#>  6 New South Wales Business New England North West <STL decomposition model>
#>  7 New South Wales Business North Coast NSW        <STL decomposition model>
#>  8 New South Wales Business Outback NSW            <STL decomposition model>
#>  9 New South Wales Business Riverina               <STL decomposition model>
#> 10 New South Wales Business Snowy Mountains        <STL decomposition model>
#> 11 New South Wales Business South Coast            <STL decomposition model>
#> 12 New South Wales Business Sydney                 <STL decomposition model>
#> 13 New South Wales Business The Murray             <STL decomposition model>
#> 14 New South Wales Business <aggregated>           <STL decomposition model>
```

Created on 2023-01-05 with reprex v2.0.2

For example, I might want to step through code to examine the "error"/"Warning"s, or see why "Central Coast" has a NULL model, etc. Thanks.

Body:
Summary

I have a tsibble that I have transformed into a mixed hierarchical (and grouped) time series. For the large majority of specified time series, I can obtain forecasts via the following:

fit <- hg_ts %>%
  fabletools::model(
    stl = fabletools::decomposition_model(
      feasts::STL(log(y), robust = TRUE),
      fable::ETS(season_adjust)))

fit %>%
  fabletools::forecast(h = 4)

For many of the remaining time series, this produces no forecast. In particular, some time series return

Warning: Non-integer lag orders for random walk models are not supported. Rounding to the nearest integer.
...
Warning: 29 errors (1 unique) encountered for stl
[29] The models specified do not combine to give the correct response.
Please check that you have specified the decomposition models appropriately.

Debugging difficulties

If I try debugonce(fabletools::decomposition_model), I see calls to fabletools::new_model_class() and fabletools::new_model_definition(). I took a look at https://fabletools.tidyverts.org/articles/extension_models.html (as well as https://r6.r-lib.org/articles/Debugging.html) but a lot is currently over my head.

How can I reach a "debugging" point (where I can examine all the objects the real code execution knows about) in model_decomposition.R's code where it says

  if(!isTRUE(all.equal(response(model)[[".response"]], .data[[measured_vars(.data)]]))){
    abort(
"The models specified do not combine to give the correct response.
Please check that you have specified the decomposition models appropriately.")
  }

if this were my decomposition model:

library(magrittr)

tsibble::tourism %>%
    fabletools::aggregate_key((State/Region) * Purpose, Trips = sum(Trips)) %>%
    dplyr::filter(Purpose == "Business", State == "New South Wales") %>%
    fabletools::model(
        stl = fabletools::decomposition_model(
            feasts::STL(log(Trips), robust = TRUE),
            fable::ETS(season_adjust)))
#> Warning: 1 error encountered for dcmp
#> [1] promise already under evaluation: recursive default argument reference or earlier problems?
#> Warning: 1 error encountered for stl
#> [1] Problem while computing `cmp = map(.fit, components)`.
#> Loading required namespace: crayon
#> # A mable: 14 x 4
#> # Key:     State, Purpose, Region [14]
#>    State           Purpose  Region                                       stl
#>    <chr*>          <chr*>   <chr*>                                   <model>
#>  1 New South Wales Business Blue Mountains         <STL decomposition model>
#>  2 New South Wales Business Capital Country        <STL decomposition model>
#>  3 New South Wales Business Central Coast                       <NULL model>
#>  4 New South Wales Business Central NSW            <STL decomposition model>
#>  5 New South Wales Business Hunter                 <STL decomposition model>
#>  6 New South Wales Business New England North West <STL decomposition model>
#>  7 New South Wales Business North Coast NSW        <STL decomposition model>
#>  8 New South Wales Business Outback NSW            <STL decomposition model>
#>  9 New South Wales Business Riverina               <STL decomposition model>
#> 10 New South Wales Business Snowy Mountains        <STL decomposition model>
#> 11 New South Wales Business South Coast            <STL decomposition model>
#> 12 New South Wales Business Sydney                 <STL decomposition model>
#> 13 New South Wales Business The Murray             <STL decomposition model>
#> 14 New South Wales Business <aggregated>           <STL decomposition model>

Created on 2023-01-05 with reprex v2.0.2

For example, I might want to step through code to examine the "error"/"Warning"s, or see why "Central Coast" has a NULL model, etc. Thanks.


问:
How to create and use many to many relationships with FastAPI and SQLModel and avoid circular references?
I've got a Python 3.10.8 FastAPI application using SQLModel and having trouble with many-to-many relationships. I can define them okay using strings to refer to the class on the other side of the many. Here is a simplified sample of one side of the many-to-many schema/model:

schedule.py file

class Schedule(ScheduleBase, table=True):
    __tablename__ = "schedules"
    id: Optional[int] = Field(default=None, primary_key=True)
    plans: List["Plan"] = Relationship(back_populates="schedules", link_model=SchedulePlanLink)
```
<p>Here's the other side of the many-to-many schema/model:</p>
<pre class="lang-py prettyprint-override"><code>class Plan(PlanBase, table=True):
    __tablename__ = "plans"
    id: Optional[int] = Field(default=None, primary_key=True)
    schedules: List["Schedule"] = Relationship(back_populates="plans", link_model=SchedulePlanLink)
</code>```

And here's the association table between them:

class SchedulePlanLink(SchedulePlanLinkBase, table=True):
    __tablename__ = "schedule_plan_links"
    schedule_id: Optional[int] = Field(
        default=None, primary_key=True, foreign_key="schedules.id"
    )
    plan_id: Optional[int] = Field(
        default=None, primary_key=True, foreign_key="plans.id"
    )
```
<p>This works and creates the expected tables and FK's, etc. The problem arises when I try to access the data. I have a SQLModel class that looks like this:</p>
<pre class="lang-py prettyprint-override"><code>class ScheduleReadWithPlans(ScheduleRead):

    plans: Optional[List["PlanRead"]] = []
</code>```

And I have to have this in order to read the data and return it via a route:

ScheduleReadWithPlans.update_forward_refs()
```

And I can get the schedule data with the list of plans. But if I try the same thing with plan data trying to get a list of schedules (with the appropriate classes define), I end up getting circular references.

Any ideas about how to define/configure this kind of thing to to work?

Body:
I've got a Python 3.10.8 FastAPI application using SQLModel and having trouble with many-to-many relationships. I can define them okay using strings to refer to the class on the other side of the many. Here is a simplified sample of one side of the many-to-many schema/model:

schedule.py file

class Schedule(ScheduleBase, table=True):
    __tablename__ = "schedules"
    id: Optional[int] = Field(default=None, primary_key=True)
    plans: List["Plan"] = Relationship(back_populates="schedules", link_model=SchedulePlanLink)

Here's the other side of the many-to-many schema/model:

class Plan(PlanBase, table=True):
    __tablename__ = "plans"
    id: Optional[int] = Field(default=None, primary_key=True)
    schedules: List["Schedule"] = Relationship(back_populates="plans", link_model=SchedulePlanLink)

And here's the association table between them:

class SchedulePlanLink(SchedulePlanLinkBase, table=True):
    __tablename__ = "schedule_plan_links"
    schedule_id: Optional[int] = Field(
        default=None, primary_key=True, foreign_key="schedules.id"
    )
    plan_id: Optional[int] = Field(
        default=None, primary_key=True, foreign_key="plans.id"
    )

This works and creates the expected tables and FK's, etc. The problem arises when I try to access the data. I have a SQLModel class that looks like this:

class ScheduleReadWithPlans(ScheduleRead):

    plans: Optional[List["PlanRead"]] = []

And I have to have this in order to read the data and return it via a route:

ScheduleReadWithPlans.update_forward_refs()

And I can get the schedule data with the list of plans. But if I try the same thing with plan data trying to get a list of schedules (with the appropriate classes define), I end up getting circular references.

Any ideas about how to define/configure this kind of thing to to work?


问:
How do you use Redux Toolkit and React-Redux for User Registration & Authentication?
I've been working on the user registration of my React-Redux project (I'm really new to Redux), and I'm having trouble with registering Users with error handling...

My curriculum teaches nothing on using Redux with React (which is what my project does) to send data to an backend database.

I have been using useState for setting both the current user (currentUser, onLogin) and any errors (errors, setErrors) inside of UserInput.jsx, and I'm trying to move that functionality over to usersSlice.js.

Right now, I am trying to set my User object to be the action.payload. I also need to deal with how to pass the new User's info from my form, to my Slice.

Any solutions?

My code:

usersSlice.js

import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";

export const signup = createAsyncThunk("users/signup", async ({username, password}, thunkAPI) => {
    await fetch("/signup", {
        method: "POST",
        headers: headers,
        body: JSON.stringify({user: {username, password}})
    }).then((data) => {
        data.json().then((data) => {
            if(data.errors){
                return thunkAPI.rejectWithValue(data.errors);
            } else{
                // Find a way to set the current user!!!
                return data;
            }
        })
    })
});

const usersSlice = createSlice({
    name: "users",
    initialState: {
        user: [],  // This should be an SINGLE User Object!!!
        errorMessage: null,
        status: 'idle',
    },
    reducers: {
        userLogin(state, action){
            state.user.push(action.payload);
        },
        userLogout(state){
            state.user = [];
        },
    },
    extraReducers(builder){
        // Omit extraReduxers logic
    }
});
```
<p><strong>UserInput.jsx:</strong></p>
<pre class="lang-js prettyprint-override"><code>function UserInput({onLogin, username, setUsername, password, setPassword, errors, setErrors}){
  const dispatch = useDispatch();

  function handleSubmit(e){
    e.preventDefault();

    const user ={
      username: username,
      password: password
    }

    dispatch(signup(user));
    if(user.errors) { // Returns null due to the user object above...
      setErrors(user.errors);
        }
    else{
      setErrors(null);
      onLogin(user); // setCurrentUser(user);
    }
  }
  // Omit the signup form
}

export default UserInput;
</code>```

Body:
I've been working on the user registration of my React-Redux project (I'm really new to Redux), and I'm having trouble with registering Users with error handling...

My curriculum teaches nothing on using Redux with React (which is what my project does) to send data to an backend database.

I have been using useState for setting both the current user (currentUser, onLogin) and any errors (errors, setErrors) inside of UserInput.jsx, and I'm trying to move that functionality over to usersSlice.js.

Right now, I am trying to set my User object to be the action.payload. I also need to deal with how to pass the new User's info from my form, to my Slice.

Any solutions?

My code:

usersSlice.js

import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";

export const signup = createAsyncThunk("users/signup", async ({username, password}, thunkAPI) => {
    await fetch("/signup", {
        method: "POST",
        headers: headers,
        body: JSON.stringify({user: {username, password}})
    }).then((data) => {
        data.json().then((data) => {
            if(data.errors){
                return thunkAPI.rejectWithValue(data.errors);
            } else{
                // Find a way to set the current user!!!
                return data;
            }
        })
    })
});

const usersSlice = createSlice({
    name: "users",
    initialState: {
        user: [],  // This should be an SINGLE User Object!!!
        errorMessage: null,
        status: 'idle',
    },
    reducers: {
        userLogin(state, action){
            state.user.push(action.payload);
        },
        userLogout(state){
            state.user = [];
        },
    },
    extraReducers(builder){
        // Omit extraReduxers logic
    }
});

UserInput.jsx:

function UserInput({onLogin, username, setUsername, password, setPassword, errors, setErrors}){
  const dispatch = useDispatch();

  function handleSubmit(e){
    e.preventDefault();

    const user ={
      username: username,
      password: password
    }

    dispatch(signup(user));
    if(user.errors) { // Returns null due to the user object above...
      setErrors(user.errors);
        }
    else{
      setErrors(null);
      onLogin(user); // setCurrentUser(user);
    }
  }
  // Omit the signup form
}

export default UserInput;


问:
Error in Dart function: 'QuerySnapshot<Map<String, dynamic>>' can't be returned from an async function
Goal:
I want to search for a Firestore record (there should be only one) where the value of the List field contains two elements that are input as parameters: Document References to the User collection.

However, I don't understand how to fix the error given my approach to searching for a given document.

This is my code:

```<code>import 'package:cloud_firestore/cloud_firestore.dart';

Future<ChatsRecord> getChatDoc(
  DocumentReference chatUserRef,
  DocumentReference authUserRef,
) async {
  // Add your function code here!

  final firestore =
      FirebaseFirestore.instance; // Get a reference to the Firestore database
  final collectionRef =
      firestore.collection('chats'); // Get a reference to the collection
  final filteredDocuments = collectionRef.where('fieldName', isEqualTo: [
    authUserRef,
    chatUserRef
  ]); // Use the `where` method to filter the list of documents

  final documents = await filteredDocuments
      .get(); // You can then use the get method on this Query object to retrieve the list of documents.

  return documents;
}
</code>```

This is my error:

```<code>Error: Command failed: flutter build web  --web-renderer html --no-pub --no-version-check
Target dart2js failed: Exception:
lib/custom_code/actions/get_chat_doc.dart:31:10:
Error: A value of type 'QuerySnapshot<Map<String, dynamic>>' can't be returned from an async function with return type 'Future<ChatsRecord>'.
 - 'QuerySnapshot' is from 'package:cloud_firestore/cloud_firestore.dart' ('/root/.pub-cache/hosted/pub.dartlang.org/cloud_firestore-4.2.0/lib/cloud_firestore.dart').
 - 'Map' is from 'dart:core'.
 - 'Future' is from 'dart:async'.
 - 'ChatsRecord' is from 'package:counter_party/backend/schema/chats_record.dart' ('lib/backend/schema/chats_record.dart').
  return documents;
         ^
Error: Compilation failed.

Exception: Failed to compile application for the Web.
</code>```

Body:
Goal:
I want to search for a Firestore record (there should be only one) where the value of the List field contains two elements that are input as parameters: Document References to the User collection.

However, I don't understand how to fix the error given my approach to searching for a given document.

This is my code:

import 'package:cloud_firestore/cloud_firestore.dart';

Future<ChatsRecord> getChatDoc(
  DocumentReference chatUserRef,
  DocumentReference authUserRef,
) async {
  // Add your function code here!

  final firestore =
      FirebaseFirestore.instance; // Get a reference to the Firestore database
  final collectionRef =
      firestore.collection('chats'); // Get a reference to the collection
  final filteredDocuments = collectionRef.where('fieldName', isEqualTo: [
    authUserRef,
    chatUserRef
  ]); // Use the `where` method to filter the list of documents

  final documents = await filteredDocuments
      .get(); // You can then use the get method on this Query object to retrieve the list of documents.

  return documents;
}

This is my error:

Error: Command failed: flutter build web  --web-renderer html --no-pub --no-version-check
Target dart2js failed: Exception:
lib/custom_code/actions/get_chat_doc.dart:31:10:
Error: A value of type 'QuerySnapshot<Map<String, dynamic>>' can't be returned from an async function with return type 'Future<ChatsRecord>'.
 - 'QuerySnapshot' is from 'package:cloud_firestore/cloud_firestore.dart' ('/root/.pub-cache/hosted/pub.dartlang.org/cloud_firestore-4.2.0/lib/cloud_firestore.dart').
 - 'Map' is from 'dart:core'.
 - 'Future' is from 'dart:async'.
 - 'ChatsRecord' is from 'package:counter_party/backend/schema/chats_record.dart' ('lib/backend/schema/chats_record.dart').
  return documents;
         ^
Error: Compilation failed.

Exception: Failed to compile application for the Web.


问:
How do I resolve git error because of a large file, even after reset and removing file?
I had committed a large file (15Mb) locally. It fails when I do "git push" because a remote server blocks it. So I've tried many times to remove it but keep getting this error:

```<code>error: remote unpack failed: error The blob object aa6526b297e0c54b8a7e865e441fb7e4f6122c1f was rejected: The object is 15668057 bytes, which is greater than the 10485760 byte limit for objects in this repository.
</code>```

I did a "git log" to find the commit (it was two commits ago), and then:

```<code>git reset --hard 1b8c876a9ca8eab6569876e9b16086ca75690c0e

git rm [file name]

git add .

git commit -m "removing large file"
</code>```

And when I do git push again, I get the same error. So I can't push to the remote.

How do I resolve this??

Body:
I had committed a large file (15Mb) locally. It fails when I do "git push" because a remote server blocks it. So I've tried many times to remove it but keep getting this error:

error: remote unpack failed: error The blob object aa6526b297e0c54b8a7e865e441fb7e4f6122c1f was rejected: The object is 15668057 bytes, which is greater than the 10485760 byte limit for objects in this repository.

I did a "git log" to find the commit (it was two commits ago), and then:

git reset --hard 1b8c876a9ca8eab6569876e9b16086ca75690c0e

git rm [file name]

git add .

git commit -m "removing large file"

And when I do git push again, I get the same error. So I can't push to the remote.

How do I resolve this??


问:
Alarm sound excel macro is not generating any sound
I have an excel macro that is written to repeat the alarm function every 5 minutes. But, the code is not generating any alarm. Can you please fix the issue which I am not able to find out. Following is the excel macro.

Sub SoundAlarm()

'Declare variables
Dim alarmTime As Date
Dim currentTime As Date

'Set the time that the alarm should start
alarmTime = TimeValue("12:00:00")

'Loop until the current time is after the alarm time
Do Until currentTime > alarmTime + TimeValue("6:00:00")
    'Get the current time
    currentTime = Time
    'If the current time is equal to or after the alarm time
    If currentTime >= alarmTime Then
        'Play the sound alarm
        Application.Sound.Play "C:\Users\HP\Downloads\alarm-clock.mp3"
        'Set the next time for the alarm to go off
        alarmTime = alarmTime + TimeValue("0:05:00")
    End If
    'Wait for 1 second
    Application.Wait Now + TimeValue("0:00:01")
Loop

End Sub
```

I expected the code to sound the alarm every 5 minutes, but even after 5 minutes, the alarm is not sounding. I have checked the .mp3 path and it is find.

Body:
I have an excel macro that is written to repeat the alarm function every 5 minutes. But, the code is not generating any alarm. Can you please fix the issue which I am not able to find out. Following is the excel macro.

Sub SoundAlarm()

'Declare variables
Dim alarmTime As Date
Dim currentTime As Date

'Set the time that the alarm should start
alarmTime = TimeValue("12:00:00")

'Loop until the current time is after the alarm time
Do Until currentTime > alarmTime + TimeValue("6:00:00")
    'Get the current time
    currentTime = Time
    'If the current time is equal to or after the alarm time
    If currentTime >= alarmTime Then
        'Play the sound alarm
        Application.Sound.Play "C:\Users\HP\Downloads\alarm-clock.mp3"
        'Set the next time for the alarm to go off
        alarmTime = alarmTime + TimeValue("0:05:00")
    End If
    'Wait for 1 second
    Application.Wait Now + TimeValue("0:00:01")
Loop

End Sub

I expected the code to sound the alarm every 5 minutes, but even after 5 minutes, the alarm is not sounding. I have checked the .mp3 path and it is find.


问:
Strimzi Kafka on GKE - automating distribution of TLS certs to external Kafka clients on certs expiry
We have a Strimzi kafka cluster on GKE with TLS implemented, the TLS certs have a default expiry of 1 year i.e. the certs get renewed every year

Currently, on expiry - we have to provide the external Kafka clients with new certs, the objective is to automate this process
i.e. One should not have to distribute the certs manually to the multiple clients, instead - this should be automated

What is the best way to achieve this ?
I was checking CMPv2 as an option - however, the documentation is not very clear on this.

Any pointers on this is appreciated !

tia!


问:
Is it possible to change Ghost CMS comment styles?
I've been trying for days now, the problem that I see is that Ghost CMS does not appear to utilise any of the custom themes styles for comments. This is because it loads the comments in an iframe (why, WHY!?), and uses its own CSS stylesheet.

Does anyone have any ideas how to improve this and ensure your comment section looks like the rest of your site? Currently on my site it's completely unusable.


问:
Youtube Player Flutter infinity loading after release
I’m using youtube_player_flutter package it works on emulator
But when release the video goes in infinity load

I tried to add permissions on Android file directly “didn’t ask user”
but that wasn’t helpful

If there any thing you can help
Or specific permission or way
I will be grateful

Adding permissions to android file
Edit minSdkVersion
Change package version


问:
Javascript Fetch Type error when trying to fetch data from php file
I'm trying to fetch json data from a own hosted php file into my shopify theme. But getting this error:"Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Invalid name".

This is my JS function loaded into my shopify:

```<code>async function getAppointments() {
    const response = await fetch('https://*******.be/test.php', {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin' : '*',
            'Access-Control-Allow-Credentials ': true

        }
    });

    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log(data);

    // alert(data);
    const appointmentsContainer = document.querySelector('.appointments-container');
    appointmentsContainer.innerHTML = '';
    for (const appointment of data.appointments) {
        appointmentsContainer.innerHTML += `
        <div class="appointment">
          <h2>${appointment.title}</h2>
          <p>${appointment.start_time}</p>
        </div>
      `;
    }
}

  getAppointments();
</code>```

And this is the php file (https://*******.be/test.php)I'm trying to fetch the data from:

```<code><?php
$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://acuityscheduling.com/api/v1/appointments?max=100&canceled=false&email=******%40hotmail.com&excludeForms=false&direction=DESC",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => [
    "accept: application/json",
    "authorization: Basic ****************API********************"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
    $appointments = json_decode($response, true);
                return response()->json([
                'appointments' => $appointments
            ]);
}

</code>```

And this php file outputs the data when I open it in my browser:

enter image description here

I have tried to debugging by trowing an error if the response insn't OK:

```<code>    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
</code>```

I want to display the data from Acuity in a Shopify website. By sending a server side API request in my php file to Acuity(because I cannot use php in my shopify theme and tried using JS but ran into a Cors error) So I wanted to do the request through my server and alow Access-Control-Allow-Origin for the Shopify domain to retrieve the data through a fetch.

Body:
I'm trying to fetch json data from a own hosted php file into my shopify theme. But getting this error:"Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Invalid name".

This is my JS function loaded into my shopify:

async function getAppointments() {
    const response = await fetch('https://*******.be/test.php', {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin' : '*',
            'Access-Control-Allow-Credentials ': true

        }
    });

    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log(data);

    // alert(data);
    const appointmentsContainer = document.querySelector('.appointments-container');
    appointmentsContainer.innerHTML = '';
    for (const appointment of data.appointments) {
        appointmentsContainer.innerHTML += `

${appointment.title}

${appointment.start_time}

      `;
    }
}

  getAppointments();

And this is the php file (https://*******.be/test.php)I'm trying to fetch the data from:

<?php
$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://acuityscheduling.com/api/v1/appointments?max=100&canceled=false&email=******%40hotmail.com&excludeForms=false&direction=DESC",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => [
    "accept: application/json",
    "authorization: Basic ****************API********************"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
    $appointments = json_decode($response, true);
                return response()->json([
                'appointments' => $appointments
            ]);
}

And this php file outputs the data when I open it in my browser:

enter image description here

I have tried to debugging by trowing an error if the response insn't OK:

    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }

I want to display the data from Acuity in a Shopify website. By sending a server side API request in my php file to Acuity(because I cannot use php in my shopify theme and tried using JS but ran into a Cors error) So I wanted to do the request through my server and alow Access-Control-Allow-Origin for the Shopify domain to retrieve the data through a fetch.


问:
CvInvoke Get MeanStdDev While Ignoring Black Areas
I am trying to find fluness in an image using Emgu CV. Original solution was making it grey and getting standard deviation.
But when the image has a black masked area I am unable find fluness because standard deviation changes.

I tried a way, to go all pixels and find out which pixels are black and put them in a list, and afterwards calculate standard deviation by going through all pixels again. But this is too slow.

Is there a way in Emgu CV, that lets me remove 0 (or less than 10) pixels from std deviation calculation of a gray colored image?


问:
How can I access the Eclipse path of the file so that I can write over the txt file?
I have txt files for 2-D game development, so that I can pull the information and write the maps.
The txt files are located under maps source folder.

However, when I write this code, it gives me error as
java.io.FileNotFoundException:\maps\studentcenter.txt (System cant find the path)//
I translated it, my IDE isnt English.

Here is the code I tried;

```<code>        FileWriter map = new FileWriter("/maps/studentcenter.txt");
        BufferedWriter writer =  new BufferedWriter(map) ;

        for (int i = 0; i < 14; i++) {
            for (int j = 0; j < 24; j++ ) {
                if (j != 23) writer.write(0 + " ");
                else writer.write(0);

            }
            System.getProperty("line.seperator");
        }

        writer.close();

</code>```

Eventually what I want is that, the txt file in the Eclipse is changed as desired: 14 rows and 24 columns of 0

Body:
I have txt files for 2-D game development, so that I can pull the information and write the maps.
The txt files are located under maps source folder.

However, when I write this code, it gives me error as
java.io.FileNotFoundException:\maps\studentcenter.txt (System cant find the path)//
I translated it, my IDE isnt English.

Here is the code I tried;

        FileWriter map = new FileWriter("/maps/studentcenter.txt");
        BufferedWriter writer =  new BufferedWriter(map) ;

        for (int i = 0; i < 14; i++) {
            for (int j = 0; j < 24; j++ ) {
                if (j != 23) writer.write(0 + " ");
                else writer.write(0);

            }
            System.getProperty("line.seperator");
        }

        writer.close();

Eventually what I want is that, the txt file in the Eclipse is changed as desired: 14 rows and 24 columns of 0


问:
Hide certain commands for non admins (pytelegrambotapi)
I've a bot with a list of commands, some are for all users, and some are for admins.

I've coded it so the commands won't run if not an admin but the set_my_command only lets me set one scope making it one or the other.

Does anyone know a way I can hide the admin commands but leave the non admins visible?

```<code>`bot.set_my_commands(
commands=[
    telebot.types.BotCommand("command1", "available to all"),
    telebot.types.BotCommand("command2", "admins only"),
    telebot.types.BotCommand("command3", "admins only")
],

scope=telebot.types.BotCommandScopeAllChatAdministrators()
</code>```

)
`

I'd like to so command 1 is visible to all (members and admins), while command2/command3 is only.

Body:
I've a bot with a list of commands, some are for all users, and some are for admins.

I've coded it so the commands won't run if not an admin but the set_my_command only lets me set one scope making it one or the other.

Does anyone know a way I can hide the admin commands but leave the non admins visible?

`bot.set_my_commands(
commands=[
    telebot.types.BotCommand("command1", "available to all"),
    telebot.types.BotCommand("command2", "admins only"),
    telebot.types.BotCommand("command3", "admins only")
],

scope=telebot.types.BotCommandScopeAllChatAdministrators()

)
`

I'd like to so command 1 is visible to all (members and admins), while command2/command3 is only.


问:
How do i update a matplotlib plot legend/label dynamically?
I want to update the "label"/legend parameter dynamically. It will be an integer variable coming from a function. I want the label to change every time that value in the function changes.

so i want it to say alpha = some int variable

```<code>    plt.plot(vals, smpl_sz, 'b', marker = 'o', label='alpha='**some value that updates**)
    plt.plot(val2, smpl_sz2, 'g', marker = 'o', label = 'alpha='**some value that updates** )
    plt.title('Power vs Sample Size')
    plt.xlabel('Power')
    plt.ylabel('Sample Size')
    plt.legend(loc = "lower right")
</code>```

Body:
I want to update the "label"/legend parameter dynamically. It will be an integer variable coming from a function. I want the label to change every time that value in the function changes.

so i want it to say alpha = some int variable

    plt.plot(vals, smpl_sz, 'b', marker = 'o', label='alpha='**some value that updates**)
    plt.plot(val2, smpl_sz2, 'g', marker = 'o', label = 'alpha='**some value that updates** )
    plt.title('Power vs Sample Size')
    plt.xlabel('Power')
    plt.ylabel('Sample Size')
    plt.legend(loc = "lower right")