问:
How to build a model to diagnose chest conditions from Chexpert dataset
I am using the Chexpert dataset (found here on kaggle) to build a CNN model that can predict disease conditions (e.g. cardiomegaly, pleural effusion, atelectasis, etc) from chest x-ray image. I am using PyTorch lightning and my code is attached to this question. I have tried several architectures and I don’t seem to get the models to perform well. I performed the overfit test (in which I try to overfit a model on one batch of data) and the models were able to overfit the single batch - showing that they are capable of fitting the data. However, regardless of the architecture I use, there is quite a difference between training loss (which can get as low as 0.2) and validation (which can get as low as 0.49). On sensitivity and precision (the metrics I am interested in), the models perform terribly during validation. After leaving the models for longer epochs, I also observed that the loss values start to increase. I will appreciate any help or suggestion to help me solve this problem. Thank you.

This is my code:

```<code>import torch
import torch.nn as nn
import torchvision
import torchvision.models as models
import torchvision.transforms as transforms
import torch.nn.functional as F
import matplotlib.pyplot as plt
import pytorch_lightning as pl
from pytorch_lightning import Trainer
from pytorch_lightning.loggers import TensorBoardLogger
from sklearn.metrics import roc_auc_score
from pytorch_lightning.trainer.states import RunningStage, TrainerFn, TrainerState, TrainerStatus
import numpy as np
import time

import pandas as pd
import gc
import random

from chexpertloader import ChestXrayDataset
# from ipykernel import kernelapp as app

from torch.utils.tensorboard import SummaryWriter
import torchmetrics
from torchmetrics import AUROC
from pytorch_lightning.callbacks import LearningRateMonitor
from pytorch_lightning.callbacks import ModelCheckpoint
from torch.optim.lr_scheduler import ReduceLROnPlateau
from sklearn.metrics import confusion_matrix

seed = 123
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True

backbones = {
    'efficientnetb0': models.efficientnet_b0(weights='IMAGENET1K_V1'),
    'efficientnetb1': models.efficientnet_b1(weights='IMAGENET1K_V1'),
    'efficientnetb2': models.efficientnet_b2(weights='IMAGENET1K_V1'),
    'efficientnetb3': models.efficientnet_b3(weights='IMAGENET1K_V1'),
    'efficientnetb4': models.efficientnet_b4(weights='IMAGENET1K_V1'),
    'efficientnetb5': models.efficientnet_b5(weights='IMAGENET1K_V1'),
    'efficientnetb6': models.efficientnet_b6(weights='IMAGENET1K_V1'),
    'efficientnetb7': models.efficientnet_b7(weights='IMAGENET1K_V1'),
    'densenet121': models.densenet121(weights='IMAGENET1K_V1'),
    'densenet161': models.densenet161(weights='IMAGENET1K_V1'),
    'densenet169': models.densenet169(weights='IMAGENET1K_V1'),
    'densenet201': models.densenet201(weights='IMAGENET1K_V1'),
    'resnet50': models.resnet50(weights='IMAGENET1K_V1'),
    'efficientnetV2_m': models.efficientnet_v2_m(weights='IMAGENET1K_V1')
        }

class LitEfficientNet(pl.LightningModule):
    def __init__(self, arch, num_classes, lr):
        super(LitEfficientNet, self).__init__()

        self.arch = arch
        self.lr = lr

        self.sizes = {
            'efficientnetb0': (256, 224), 'efficientnetb1': (256, 240), 'efficientnetb2': (288, 288), 'efficientnetb3': (320, 300),
            'efficientnetb4': (384, 380), 'efficientnetb5': (489, 456), 'efficientnetb6': (561, 528), 'efficientnetb7': (633, 600),
            'densenet121':(256,256), 'densenet161':(256,256), 'densenet169':(256,256), 'densenet201':(256,256),
            'resnet50':(224,224), 'efficientnetV2_m':(384,384)
        }

        self.batch_sizes = {
                'efficientnetb0': 64, 'efficientnetb1': 64, 'efficientnetb2': 64, 'efficientnetb3': 32,
                'efficientnetb4': 20, 'efficientnetb5': 7, 'efficientnetb6': 5, 'efficientnetb7': 2,
                'densenet121':64, 'densenet161':32, 'densenet169':32, 'densenet201':32, 'resnet50':32,
                'efficientnetV2_m':16
        }

        self.model = backbones[arch]

        if 'densenet' in arch:

            self.model.classifier = nn.Sequential(
                nn.Linear(self.model.classifier.in_features, 2048),
                nn.ReLU(),
                nn.Dropout(p=0.6),

                nn.Linear(2048, 512),
                nn.ReLU(),
                nn.Dropout(p=0.2),

                nn.Linear(512, num_classes),
            )

        elif 'resnet' in arch:
             self.model.fc = nn.Linear(self.model.fc.in_features, num_classes)

        elif 'efficientnet' in arch:
              self.model.classifier = nn.Sequential(
                  nn.Dropout(p=self.model.classifier[0].p, inplace=True),
                  nn.Linear(self.model.classifier[1].in_features, num_classes),
              )

    def forward(self, x):

        y_pred = self.model(x)

        return y_pred

    def training_step(self, batch, batch_idx):
        images, labels = batch

        # Forward pass
        m = nn.Sigmoid()
        outputs = self.model(images)

        classes = {0:'Cardiomegaly', 1:'Edema', 2:'Atelectasis',
                   3:'Pleural Effuion', 4:'Lung Opacity'
                  }

        Loss = nn.BCEWithLogitsLoss()
        loss = Loss(outputs, labels)

        self.log('train_loss', loss, sync_dist=True)

        return loss

    def train_dataloader(self):

        train_csv = pd.read_csv('CheXpert-v1.0-small/train.csv')
        train_csv.fillna(0, inplace=True)

        train_dataset = ChestXrayDataset("CheXpert-v1.0-small/train", train_csv, self.sizes[self.arch], True)

        # Data loader
        train_loader = torch.utils.data.DataLoader(
            dataset=train_dataset, batch_size=self.batch_sizes[self.arch], num_workers=8, shuffle=False
        )

        return train_loader

    def validation_step(self, batch, batch_idx):
        images, labels = batch
        images = images

        m = nn.Sigmoid()
        outputs = self.model(images)

        classes = {0:'Cardiomegaly', 1:'Edema', 2:'Atelectasis',
                   3:'Pleural Effuion', 4:'Lung Opacity'
                  }

        Loss = nn.BCEWithLogitsLoss()
        loss = Loss(outputs, labels)

        self.log('val_loss', loss, sync_dist=True)

        tensorboard_logs = {'val_loss': loss}
        return loss

    def val_dataloader(self):
      validation_csv = pd.read_csv('CheXpert-v1.0-small/valid.csv')
      validation_csv.fillna(0, inplace=True)

      validation_csv = validation_csv.sample(frac=1)

      validation_dataset = ChestXrayDataset("CheXpert-v1.0-small/valid", validation_csv, self.sizes[self.arch], True)

      # Data loader
      validation_loader = torch.utils.data.DataLoader(
          dataset=validation_dataset, batch_size=self.batch_sizes[self.arch], num_workers=8, shuffle=False
      )

      return validation_loader

    def configure_optimizers(self):
        optimizer = optimizer = torch.optim.Adam(self.parameters(), lr=self.lr)
        return optimizer

if __name__ == '__main__':
    archs = ['efficientnetV2_m']
    learning_rates = [0.001]
    num_classes = 5

    for i in range(len(learning_rates)):

        arch = archs[0]
        learning_rate = learning_rates[i]

        logger = TensorBoardLogger(f"tb_logs_binary/{arch}",name=f"{arch}_{learning_rate}_ppv_npv_sensitive")
        model = LitEfficientNet(arch,num_classes, learning_rate)
        trainer = Trainer(
                                log_every_n_steps=1411,
                                logger=logger,
                                accelerator='gpu',
                                devices=-1,
                                # devices=1,
                                # overfit_batches=10,
                                max_epochs=50,
                                val_check_interval=0.1,
                                deterministic=True,
                                fast_dev_run=False)

        trainer.fit(model)

        del model, trainer
        gc.collect()
</code>```

Body:
I am using the Chexpert dataset (found here on kaggle) to build a CNN model that can predict disease conditions (e.g. cardiomegaly, pleural effusion, atelectasis, etc) from chest x-ray image. I am using PyTorch lightning and my code is attached to this question. I have tried several architectures and I don’t seem to get the models to perform well. I performed the overfit test (in which I try to overfit a model on one batch of data) and the models were able to overfit the single batch - showing that they are capable of fitting the data. However, regardless of the architecture I use, there is quite a difference between training loss (which can get as low as 0.2) and validation (which can get as low as 0.49). On sensitivity and precision (the metrics I am interested in), the models perform terribly during validation. After leaving the models for longer epochs, I also observed that the loss values start to increase. I will appreciate any help or suggestion to help me solve this problem. Thank you.

This is my code:

import torch
import torch.nn as nn
import torchvision
import torchvision.models as models
import torchvision.transforms as transforms
import torch.nn.functional as F
import matplotlib.pyplot as plt
import pytorch_lightning as pl
from pytorch_lightning import Trainer
from pytorch_lightning.loggers import TensorBoardLogger
from sklearn.metrics import roc_auc_score
from pytorch_lightning.trainer.states import RunningStage, TrainerFn, TrainerState, TrainerStatus
import numpy as np
import time

import pandas as pd
import gc
import random

from chexpertloader import ChestXrayDataset
# from ipykernel import kernelapp as app

from torch.utils.tensorboard import SummaryWriter
import torchmetrics
from torchmetrics import AUROC
from pytorch_lightning.callbacks import LearningRateMonitor
from pytorch_lightning.callbacks import ModelCheckpoint
from torch.optim.lr_scheduler import ReduceLROnPlateau
from sklearn.metrics import confusion_matrix

seed = 123
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True

backbones = {
    'efficientnetb0': models.efficientnet_b0(weights='IMAGENET1K_V1'),
    'efficientnetb1': models.efficientnet_b1(weights='IMAGENET1K_V1'),
    'efficientnetb2': models.efficientnet_b2(weights='IMAGENET1K_V1'),
    'efficientnetb3': models.efficientnet_b3(weights='IMAGENET1K_V1'),
    'efficientnetb4': models.efficientnet_b4(weights='IMAGENET1K_V1'),
    'efficientnetb5': models.efficientnet_b5(weights='IMAGENET1K_V1'),
    'efficientnetb6': models.efficientnet_b6(weights='IMAGENET1K_V1'),
    'efficientnetb7': models.efficientnet_b7(weights='IMAGENET1K_V1'),
    'densenet121': models.densenet121(weights='IMAGENET1K_V1'),
    'densenet161': models.densenet161(weights='IMAGENET1K_V1'),
    'densenet169': models.densenet169(weights='IMAGENET1K_V1'),
    'densenet201': models.densenet201(weights='IMAGENET1K_V1'),
    'resnet50': models.resnet50(weights='IMAGENET1K_V1'),
    'efficientnetV2_m': models.efficientnet_v2_m(weights='IMAGENET1K_V1')
        }

class LitEfficientNet(pl.LightningModule):
    def __init__(self, arch, num_classes, lr):
        super(LitEfficientNet, self).__init__()

        self.arch = arch
        self.lr = lr

        self.sizes = {
            'efficientnetb0': (256, 224), 'efficientnetb1': (256, 240), 'efficientnetb2': (288, 288), 'efficientnetb3': (320, 300),
            'efficientnetb4': (384, 380), 'efficientnetb5': (489, 456), 'efficientnetb6': (561, 528), 'efficientnetb7': (633, 600),
            'densenet121':(256,256), 'densenet161':(256,256), 'densenet169':(256,256), 'densenet201':(256,256),
            'resnet50':(224,224), 'efficientnetV2_m':(384,384)
        }

        self.batch_sizes = {
                'efficientnetb0': 64, 'efficientnetb1': 64, 'efficientnetb2': 64, 'efficientnetb3': 32,
                'efficientnetb4': 20, 'efficientnetb5': 7, 'efficientnetb6': 5, 'efficientnetb7': 2,
                'densenet121':64, 'densenet161':32, 'densenet169':32, 'densenet201':32, 'resnet50':32,
                'efficientnetV2_m':16
        }

        self.model = backbones[arch]

        if 'densenet' in arch:

            self.model.classifier = nn.Sequential(
                nn.Linear(self.model.classifier.in_features, 2048),
                nn.ReLU(),
                nn.Dropout(p=0.6),

                nn.Linear(2048, 512),
                nn.ReLU(),
                nn.Dropout(p=0.2),

                nn.Linear(512, num_classes),
            )

        elif 'resnet' in arch:
             self.model.fc = nn.Linear(self.model.fc.in_features, num_classes)

        elif 'efficientnet' in arch:
              self.model.classifier = nn.Sequential(
                  nn.Dropout(p=self.model.classifier[0].p, inplace=True),
                  nn.Linear(self.model.classifier[1].in_features, num_classes),
              )

    def forward(self, x):

        y_pred = self.model(x)

        return y_pred

    def training_step(self, batch, batch_idx):
        images, labels = batch

        # Forward pass
        m = nn.Sigmoid()
        outputs = self.model(images)

        classes = {0:'Cardiomegaly', 1:'Edema', 2:'Atelectasis',
                   3:'Pleural Effuion', 4:'Lung Opacity'
                  }

        Loss = nn.BCEWithLogitsLoss()
        loss = Loss(outputs, labels)

        self.log('train_loss', loss, sync_dist=True)

        return loss

    def train_dataloader(self):

        train_csv = pd.read_csv('CheXpert-v1.0-small/train.csv')
        train_csv.fillna(0, inplace=True)

        train_dataset = ChestXrayDataset("CheXpert-v1.0-small/train", train_csv, self.sizes[self.arch], True)

        # Data loader
        train_loader = torch.utils.data.DataLoader(
            dataset=train_dataset, batch_size=self.batch_sizes[self.arch], num_workers=8, shuffle=False
        )

        return train_loader

    def validation_step(self, batch, batch_idx):
        images, labels = batch
        images = images

        m = nn.Sigmoid()
        outputs = self.model(images)

        classes = {0:'Cardiomegaly', 1:'Edema', 2:'Atelectasis',
                   3:'Pleural Effuion', 4:'Lung Opacity'
                  }

        Loss = nn.BCEWithLogitsLoss()
        loss = Loss(outputs, labels)

        self.log('val_loss', loss, sync_dist=True)

        tensorboard_logs = {'val_loss': loss}
        return loss

    def val_dataloader(self):
      validation_csv = pd.read_csv('CheXpert-v1.0-small/valid.csv')
      validation_csv.fillna(0, inplace=True)

      validation_csv = validation_csv.sample(frac=1)

      validation_dataset = ChestXrayDataset("CheXpert-v1.0-small/valid", validation_csv, self.sizes[self.arch], True)

      # Data loader
      validation_loader = torch.utils.data.DataLoader(
          dataset=validation_dataset, batch_size=self.batch_sizes[self.arch], num_workers=8, shuffle=False
      )

      return validation_loader

    def configure_optimizers(self):
        optimizer = optimizer = torch.optim.Adam(self.parameters(), lr=self.lr)
        return optimizer

if __name__ == '__main__':
    archs = ['efficientnetV2_m']
    learning_rates = [0.001]
    num_classes = 5

    for i in range(len(learning_rates)):

        arch = archs[0]
        learning_rate = learning_rates[i]

        logger = TensorBoardLogger(f"tb_logs_binary/{arch}",name=f"{arch}_{learning_rate}_ppv_npv_sensitive")
        model = LitEfficientNet(arch,num_classes, learning_rate)
        trainer = Trainer(
                                log_every_n_steps=1411,
                                logger=logger,
                                accelerator='gpu',
                                devices=-1,
                                # devices=1,
                                # overfit_batches=10,
                                max_epochs=50,
                                val_check_interval=0.1,
                                deterministic=True,
                                fast_dev_run=False)

        trainer.fit(model)

        del model, trainer
        gc.collect()


来源: stackexchange

问:
Multiple statement on alpine.js x-effect make the test case fail but work normal with manual testing
I try to use alpine to finish the front-end mentor challenge on the interactive pricing component.
the objective is to reactively change the value when the slider change. when I test it manually it works normal, but when I do the test case it fail with Node is either not clickable or not an HTMLElement. to combat this I remove the this.yearlyPrice=... and this.price=... and the test case is able to detect again but because I 've removed this.yearlyPrice=... and this.price=... from x-effect code, the program won't work as expected like before. super confused about this cause x-effect is the only way to achieve this. of course I could use the @change in input range and put in the this.yearlyPrice=... and this.price=... on it, the app will work if I do manual testing, but will not satisfy the test because like we know the on change event could not hear it if we change the input range value programmatically (the test is changing the value programmatically using webdriver and compare the result)

```<code><div  x-data="app" x-effect="slideEffect" >
  <section>
    <h2 class="my-10 mt-14 text-sm font-bold text-gray-500"  x-text="pageviews + ' PAGEVIEWS'"></h2>
    <input
      type="range"
      name="price"
      min="1"
      max="5"
      id="price-slider"
      x-model="data"
    />
    <h1 x-text="price"></h1>
    <h1 x-text="yearlyPrice"></h1>
  </section>
</div>
</code>```

the the logic is below

```<code><script>
  document.addEventListener('alpine:init', () => {
    Alpine.data('app', () => ({
      data: '3',
      yearly: false,
      pageviews: 100,
      price: '$16.00',
      yearlyPrice: '$12.00',

      slideEffect() {
        this.pageviews =
          this.data === '1'
            ? '10K'
            : this.data === '2'
            ? '50K'
            : this.data === '3'
            ? '100K'
            : this.data === '4'
            ? '500K'
            : '1M'
        this.price =
          this.data === '1'
            ? '$8.00'
            : this.data === '2'
            ? '$12.00'
            : this.data === '3'
            ? '$16.00'
            : this.data === '4'
            ? '$24.00'
            : '$36.00'
        this.yearlyPrice =
          this.data === '1'
            ? '$6.00'
            : this.data === '2'
            ? '$9.00'
            : this.data === '3'
            ? '$12.00'
            : this.data === '4'
            ? '$18.00'
            : '$27.00'
      },
    }))
  })
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I try to use alpine to finish the front-end mentor challenge on the interactive pricing component.
the objective is to reactively change the value when the slider change. when I test it manually it works normal, but when I do the test case it fail with Node is either not clickable or not an HTMLElement. to combat this I remove the this.yearlyPrice=... and this.price=... and the test case is able to detect again but because I 've removed this.yearlyPrice=... and this.price=... from x-effect code, the program won't work as expected like before. super confused about this cause x-effect is the only way to achieve this. of course I could use the @change in input range and put in the this.yearlyPrice=... and this.price=... on it, the app will work if I do manual testing, but will not satisfy the test because like we know the on change event could not hear it if we change the input range value programmatically (the test is changing the value programmatically using webdriver and compare the result)

    <input
      type="range"
      name="price"
      min="1"
      max="5"
      id="price-slider"
      x-model="data"
    />

the the logic is below


问:
create a program that takes the length of the password as input and generates a random password . some time it give true output and some give error
```<code>import random

letters=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
              'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
numbers=['1','2','3','4','5','6','7','8','9','0']
symbols=['!','@','#','$','%','^','&','*','(',')','-','+','=','?',':','~']
print("welcome to the passward genrator!")
no_of_letters=int(input(f"how many letters would you like in your password: \n"))
no_of_symbols=int(input(f"how many symbols would you like: \n"))
no_of_numbers=int(input(f"how many numbers would you like :\n"))

if (no_of_numbers+no_of_symbols+no_of_numbers)<=12:
    print("your passward must be 12 characater")

else:
    i = 0
    letters_char = ""
    while i < no_of_letters:
        letters_index = random.randint(0, len(letters) - 1)
        i += 1
        a = letters[letters_index]
        letters_char += a
    p = (letters_char)
    s = (p[0].upper()) + p[1:]

    j = 0
    number_char = ""
    while j < no_of_numbers:
        number_index = random.randint(0, len(numbers) - 1)
        j += 1
        b = numbers[number_index]
        number_char += b
    q = (number_char)

    k = 0
    symbol_char = ""
    while k < no_of_symbols:
        symbol_index = random.randint(0, len(symbols))
        k += 1
        c = symbols[symbol_index]
        symbol_char += c
    r = (symbol_char)
    print(f"Your password is: {s+q+r}")

</code>```

genrally it take error with when i give input 7(no of letters),8(no of symbol),9[enter image description here](https://i.stack.imgur.com/XB8B0.png)(no of numbers)

sometime it give true output in same input

Body:
import random

letters=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
              'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
numbers=['1','2','3','4','5','6','7','8','9','0']
symbols=['!','@','#','$','%','^','&','*','(',')','-','+','=','?',':','~']
print("welcome to the passward genrator!")
no_of_letters=int(input(f"how many letters would you like in your password: \n"))
no_of_symbols=int(input(f"how many symbols would you like: \n"))
no_of_numbers=int(input(f"how many numbers would you like :\n"))

if (no_of_numbers+no_of_symbols+no_of_numbers)<=12:
    print("your passward must be 12 characater")

else:
    i = 0
    letters_char = ""
    while i < no_of_letters:
        letters_index = random.randint(0, len(letters) - 1)
        i += 1
        a = letters[letters_index]
        letters_char += a
    p = (letters_char)
    s = (p[0].upper()) + p[1:]

    j = 0
    number_char = ""
    while j < no_of_numbers:
        number_index = random.randint(0, len(numbers) - 1)
        j += 1
        b = numbers[number_index]
        number_char += b
    q = (number_char)

    k = 0
    symbol_char = ""
    while k < no_of_symbols:
        symbol_index = random.randint(0, len(symbols))
        k += 1
        c = symbols[symbol_index]
        symbol_char += c
    r = (symbol_char)
    print(f"Your password is: {s+q+r}")

genrally it take error with when i give input 7(no of letters),8(no of symbol),9[enter image description here](https://i.stack.imgur.com/XB8B0.png)(no of numbers)

sometime it give true output in same input


问:
Calling dll function in Python works on local build but crashes on executable build
I have a python application that uses a dll file to call a few functions. I am currently using the Win32COM library to do this. I am using a publicly available mini-circuits dll for a power meter connected using a USB port.

```<code>self.mini_circuits_dll = win32com.client.Dispatch("mcl_pm.USB_PM")
</code>```

The actual dll file is named "mcl_pm.dll" and the USB_PM is the class where the functions are being held.

This works well on my local build, but once I create an executable version of this using pyinstaller it no longer works. The dll file is located in the correct folders still and the dll also gets added to the build like so

```<code>--add-binary="mcl_pm.dll;."
</code>```

I have tried to use the ctypes library but have not had any luck. It can find and open the dll file, but I have not been able to instantiate the class correctly once it is opened.

```<code>self.mini_circuits_dll_instance = ctypes.WinDLL("mcl_pm.dll")
self.mini_circuits_dll = self.mini_circuits_dll_instance.USB_PM()
</code>```

Body:
I have a python application that uses a dll file to call a few functions. I am currently using the Win32COM library to do this. I am using a publicly available mini-circuits dll for a power meter connected using a USB port.

self.mini_circuits_dll = win32com.client.Dispatch("mcl_pm.USB_PM")

The actual dll file is named "mcl_pm.dll" and the USB_PM is the class where the functions are being held.

This works well on my local build, but once I create an executable version of this using pyinstaller it no longer works. The dll file is located in the correct folders still and the dll also gets added to the build like so

--add-binary="mcl_pm.dll;."

I have tried to use the ctypes library but have not had any luck. It can find and open the dll file, but I have not been able to instantiate the class correctly once it is opened.

self.mini_circuits_dll_instance = ctypes.WinDLL("mcl_pm.dll")
self.mini_circuits_dll = self.mini_circuits_dll_instance.USB_PM()


问:
dialog-flow showing empty response
As shown in image I'm getting this error by adding custom load in Dialog flow any suggestions!

It must be like this!!!

Title: dialog-flow showing empty response


问:
How to redirect network traffic to a tcp/udp connection in golang
So I've seen projects like trojan-go,v2ray-go
They are making their own proxy protocols in user space level. I am trying to do the same thing but I don't know how to redirect network traffic from clients to proxy server.

Basically I don't understand how those tools (or any tool) can redirect internet traffic of the device to a certain server, so when the packets are going to the internet they go to the proxy server first instead of their destination ip address.

How can I do it in golang without dealing with netlink and Iptables?
I know apps like wireguard do this by dealing with layer 3-4 stuff using netlink API but I need to know how apps do it without adding a new network interface.


问:
How to translate objects with different parent together wpf Canvas and Grid
I'm trying to do a Rotate/Translate/Scale of objects using a canvas for the actual figure and I use a Grid for "thumbs" container (Thumbs are some small ellipses)

I have some trouble understanding the logic behind this example.

```<code><Window x:Class="RotateMe.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:RotateMe"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Button x:Name="AddRectangle" Width="50" Grid.Row="0" HorizontalAlignment="Left" Click="AddRectangle_Click"/>
        <Canvas x:Name="DrawingCanvas" Grid.Row="1" Background="Gray">
            <Ellipse x:Name="Thumb3" Fill="Azure"  Height="10" Width="10" >
                <Ellipse.RenderTransform>
                    <TranslateTransform X="-50" Y="-50"/>
                </Ellipse.RenderTransform>
            </Ellipse>
            <Ellipse x:Name="Thumb4" Fill="Beige"  Height="10" Width="10"  >
                <Ellipse.RenderTransform>
                    <TranslateTransform X="50" Y="50"/>
                </Ellipse.RenderTransform>
            </Ellipse>
        </Canvas>
        <Grid x:Name="ThumbsParent" Grid.Row="1" RenderTransformOrigin="1,1">
            <Ellipse x:Name="Thumb" Fill="Red"  Height="10" Width="10"  RenderTransformOrigin="1,1">
                <Ellipse.RenderTransform>
                    <TranslateTransform X="-50" Y="-50"/>
                </Ellipse.RenderTransform>
            </Ellipse>
            <Ellipse x:Name="Thumb2"  Height="10" Width="10"  Fill="Green">
                <Ellipse.RenderTransform>
                    <TranslateTransform X="50" Y="50"/>
                </Ellipse.RenderTransform>
            </Ellipse>
        </Grid>
    </Grid>
</Window>
</code>```

So here I have

A Grid over an Canvas (same size)

Each of them contain a 10/10 ellipse that one is render transform -50/-50 and one is 50/50.

I would have expected the same behavior (overlap of the ellipses on both -50/-50 and 50/50)

Instead it looks like this.

So from what I understand from this.

Grid renders from CenterX/CenterY
Canvas renders from 0/0.

Is there a particular reason this is happening?

Why I am asking this, because I wanted to use a TranslateTransform for all my object and if one moves, all should move, but because one translate from 0/0 and one from CenterX/CenterY the same translate won't work on these elements.

Body:
I'm trying to do a Rotate/Translate/Scale of objects using a canvas for the actual figure and I use a Grid for "thumbs" container (Thumbs are some small ellipses)

I have some trouble understanding the logic behind this example.

<Window x:Class="RotateMe.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:RotateMe"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Button x:Name="AddRectangle" Width="50" Grid.Row="0" HorizontalAlignment="Left" Click="AddRectangle_Click"/>
        <Canvas x:Name="DrawingCanvas" Grid.Row="1" Background="Gray">
            <Ellipse x:Name="Thumb3" Fill="Azure"  Height="10" Width="10" >
                <Ellipse.RenderTransform>
                    <TranslateTransform X="-50" Y="-50"/>
                </Ellipse.RenderTransform>
            </Ellipse>
            <Ellipse x:Name="Thumb4" Fill="Beige"  Height="10" Width="10"  >
                <Ellipse.RenderTransform>
                    <TranslateTransform X="50" Y="50"/>
                </Ellipse.RenderTransform>
            </Ellipse>
        </Canvas>
        <Grid x:Name="ThumbsParent" Grid.Row="1" RenderTransformOrigin="1,1">
            <Ellipse x:Name="Thumb" Fill="Red"  Height="10" Width="10"  RenderTransformOrigin="1,1">
                <Ellipse.RenderTransform>
                    <TranslateTransform X="-50" Y="-50"/>
                </Ellipse.RenderTransform>
            </Ellipse>
            <Ellipse x:Name="Thumb2"  Height="10" Width="10"  Fill="Green">
                <Ellipse.RenderTransform>
                    <TranslateTransform X="50" Y="50"/>
                </Ellipse.RenderTransform>
            </Ellipse>
        </Grid>
    </Grid>
</Window>

So here I have

A Grid over an Canvas (same size)

Each of them contain a 10/10 ellipse that one is render transform -50/-50 and one is 50/50.

I would have expected the same behavior (overlap of the ellipses on both -50/-50 and 50/50)

Instead it looks like this.

So from what I understand from this.

Grid renders from CenterX/CenterY
Canvas renders from 0/0.

Is there a particular reason this is happening?

Why I am asking this, because I wanted to use a TranslateTransform for all my object and if one moves, all should move, but because one translate from 0/0 and one from CenterX/CenterY the same translate won't work on these elements.


问:
Any way to tell which direction focus is off in image
I'm trying to make an autofocuser for a microscopic USB Cam.

using the standard

```<code>return cv2.Laplacian(image, cv2.CV_64F).var()
</code>```

to calculate the overall blurriness of a 64x64 pixel "focus cursor" which works fine.

What I'd like to be able to determine is which direction I need to move the focus knob to achieve ideal focus. I initially tried simply sampling a small movement each direction to determine better/worse score but I find for badly out of focus images the score is so low the Laplacian score becomes based on image noise rather than true blur.

Is there a way to detect the direction the focus needs to go in based on image data?

Also if anyone has a link to the the vocabulary used when speaking of focusing in vs out it would be appreciated as I know the way I'm describing it is not the correct terminology.

Thanks!

Body:
I'm trying to make an autofocuser for a microscopic USB Cam.

using the standard

return cv2.Laplacian(image, cv2.CV_64F).var()

to calculate the overall blurriness of a 64x64 pixel "focus cursor" which works fine.

What I'd like to be able to determine is which direction I need to move the focus knob to achieve ideal focus. I initially tried simply sampling a small movement each direction to determine better/worse score but I find for badly out of focus images the score is so low the Laplacian score becomes based on image noise rather than true blur.

Is there a way to detect the direction the focus needs to go in based on image data?

Also if anyone has a link to the the vocabulary used when speaking of focusing in vs out it would be appreciated as I know the way I'm describing it is not the correct terminology.

Thanks!


问:
How to run a background loop with other code running
```<code>def snow():
  turtle_list  = []
  wn.bgcolor("light blue")
  while True:
    snowball = turtle.Turtle()
    snowball.hideturtle()
    snowball.speed(0)
    snowball.penup()
    x = random.randint(-10,10) * 30
    snowball.shape("circle")
    snowball.color("white")
    snowball.goto(x,400)
    snowball.showturtle()
    snowball.speed(3)
    snowball.goto(x,-400)
#This will make the snow function run in background
snow_thread = threading.Thread(target = snow)
snow_thread.start()
</code>```

I'm still a beginner but I have a snow function that does a simple job of moving turtles to top of screen then dropping them one by one. The problem that I am having is with attempting to run this function to be running at all times with another game running for a snowfall since the while loop doesn't let my other code run. I attempted threading but it doesn't run the snow function and only the game.

I tried multiprocessing with this and still couldn't get the snow function to run, only the game.

Body:
def snow():
  turtle_list  = []
  wn.bgcolor("light blue")
  while True:
    snowball = turtle.Turtle()
    snowball.hideturtle()
    snowball.speed(0)
    snowball.penup()
    x = random.randint(-10,10) * 30
    snowball.shape("circle")
    snowball.color("white")
    snowball.goto(x,400)
    snowball.showturtle()
    snowball.speed(3)
    snowball.goto(x,-400)
#This will make the snow function run in background
snow_thread = threading.Thread(target = snow)
snow_thread.start()

I'm still a beginner but I have a snow function that does a simple job of moving turtles to top of screen then dropping them one by one. The problem that I am having is with attempting to run this function to be running at all times with another game running for a snowfall since the while loop doesn't let my other code run. I attempted threading but it doesn't run the snow function and only the game.

I tried multiprocessing with this and still couldn't get the snow function to run, only the game.


问:
convert C# System.Unit16[,] to Python list
I receive data from a .dll written in C# which generates a 2D array of type System.Uint16[,]
I need to convert this data in python to a list as quick as possible, to publish it on Ros2. That is the only format supported by Ros python.

I have tried a few things:

```<code>Data_RawADC = list(Res)
Data_RawADC = np.reshape(Data_RawADC, (4, int(len(Data_RawADC)/4)))
</code>```

This works but takes very long time.
I also tried this:

```<code>Res_iter = list(np.fromiter(Res, np.int16).reshape(4, -1))
</code>```

Also works, but only 12% faster. Still super slow.
Does anybody know a (much) faster way ?
Thanks in advance

Body:
I receive data from a .dll written in C# which generates a 2D array of type System.Uint16[,]
I need to convert this data in python to a list as quick as possible, to publish it on Ros2. That is the only format supported by Ros python.

I have tried a few things:

Data_RawADC = list(Res)
Data_RawADC = np.reshape(Data_RawADC, (4, int(len(Data_RawADC)/4)))

This works but takes very long time.
I also tried this:

Res_iter = list(np.fromiter(Res, np.int16).reshape(4, -1))

Also works, but only 12% faster. Still super slow.
Does anybody know a (much) faster way ?
Thanks in advance


问:
bulk or batch update in knex.js
I'm working with on nodejs with knex.js and sql as a database I have a record of 4000 data in array of object I have to update it into a table, which is currently taking more than 10 minutes. I wanted to reduce the time taken.

this is the records

```<code>      const records = [
        { ID: "45159", UnitCost: "1", country: "GB" },
        { ID: "45209", UnitCost: "2", country: "GB" },
      ];
</code>```

currently I'm mapping through each record and writing this condition

```<code>      const response = await baseQueryBuilder
        .clone()
        .where("country", countryCode)
        .where({ID:id})
        .update({UnitCost:UnitCost});

</code>```

is there any method that we can do batch or bulk upload so that the time can be reduced. Thanks.

Title: bulk or batch update in knex.js

Body:
I'm working with on nodejs with knex.js and sql as a database I have a record of 4000 data in array of object I have to update it into a table, which is currently taking more than 10 minutes. I wanted to reduce the time taken.

this is the records

      const records = [
        { ID: "45159", UnitCost: "1", country: "GB" },
        { ID: "45209", UnitCost: "2", country: "GB" },
      ];

currently I'm mapping through each record and writing this condition

      const response = await baseQueryBuilder
        .clone()
        .where("country", countryCode)
        .where({ID:id})
        .update({UnitCost:UnitCost});

is there any method that we can do batch or bulk upload so that the time can be reduced. Thanks.


问:
predict() function in R is not providing prediction in R console
My training data has 87620 rows and 5 columns. My test data has the same number of rows and columns. When I use a CART model to predict the "Defaults" (that is the target variable), my model works and provides me with predictions.

When I use a validation data set that has 6 columns and only 19561 rows, and does not have the Defaults variable, and then proceed to use the

```<code>View(validationsetpreds.CART3.3x)
</code>```

I get the attached picture

Validationsetpreds Picture

And when I perform the same command using the test data set I get the following Testsetpreds Picture

```<code>set.seed(123)

loans_training$Default <- as.factor(loans_training$Default)#Make the default variable categorical
loans_test$Default <- as.factor(loans_test$Default)#Make the default variable categorical

loans_training$term <- as.factor(loans_training$term)
loans_test$term <- as.factor(loans_test$term)

#Standardize datasets
library(psych)
library(caret)
preprocess.train.z <- preProcess(loans_training[1:5], method = c("center", "scale"))
preprocess.train.z
loans_train.z <- predict(preprocess.train.z,loans_training[1:5])

describe(loans_train.z)
View(loans_train.z)
summary(loans_train.z$Default)
preprocess.test.z <- preProcess(loans_test[1:5], method = c("center", "scale"))
preprocess.test.z
loans_test.z <- predict(preprocess.test.z,loans_test[1:5])

describe(loans_test.z)
View(loans_test.z)

summary(loans_train.z$Default)
(22417 * 2.3) + 22417

#Resampling subroutine
rare.record.indices <- which(loans_train.z$Default == "1")
rare.indices.resampled <- sample(x = rare.record.indices,size = 51559, replace = TRUE)
rare.records.resampled <- loans_train.z[rare.indices.resampled,]
loans_train.3.3x <- rbind(loans_train.z, rare.records.resampled)
table(loans_train.3.3x$Default)

#Develop 3.3x CART model
TC <- trainControl(method = "CV", number = 10)
fit.CART.3.3x <- train(Default ~ ., data = loans_train.3.3x, method = "rpart", trControl = TC)
fit.CART.3.3x$resample
testsetpreds.CART3.3x <- predict(fit.CART.3.3x,loans_test.z)
table(loans_test.z$Default, testsetpreds.CART3.3x)
testsetpreds.CART3.3x

#Predictions
set.seed(123)

loans_validation$grade <- as.character(loans_validation$grade)#Make the grade variable categorical

loans_validation$term <- as.factor(loans_validation$term)#Make the term variable categorical

loans_validation$Index <- as.factor(loans_validation$Index)#Make the Index variable categorical
#Standardize dataset
library(psych)
library(caret)
preprocess.validation.z <- preProcess(loans_validation[1:6], method = c("center", "scale"))
preprocess.validation.z
loans_validation.z <- predict(preprocess.validation.z,loans_validation[1:6])

#Predict Defaults using Cart
validationsetpreds.CART3.3x <- predict(fit.CART.3.3x,loans_validation.z)
View(validationsetpreds.CART3.3x)

</code>```

Any help would be greatly appreaciated :)

How would I apply this to the validation data set?

Body:
My training data has 87620 rows and 5 columns. My test data has the same number of rows and columns. When I use a CART model to predict the "Defaults" (that is the target variable), my model works and provides me with predictions.

When I use a validation data set that has 6 columns and only 19561 rows, and does not have the Defaults variable, and then proceed to use the

View(validationsetpreds.CART3.3x)

I get the attached picture

Validationsetpreds Picture

And when I perform the same command using the test data set I get the following Testsetpreds Picture

set.seed(123)

loans_training$Default <- as.factor(loans_training$Default)#Make the default variable categorical
loans_test$Default <- as.factor(loans_test$Default)#Make the default variable categorical

loans_training$term <- as.factor(loans_training$term)
loans_test$term <- as.factor(loans_test$term)

#Standardize datasets
library(psych)
library(caret)
preprocess.train.z <- preProcess(loans_training[1:5], method = c("center", "scale"))
preprocess.train.z
loans_train.z <- predict(preprocess.train.z,loans_training[1:5])

describe(loans_train.z)
View(loans_train.z)
summary(loans_train.z$Default)
preprocess.test.z <- preProcess(loans_test[1:5], method = c("center", "scale"))
preprocess.test.z
loans_test.z <- predict(preprocess.test.z,loans_test[1:5])

describe(loans_test.z)
View(loans_test.z)

summary(loans_train.z$Default)
(22417 * 2.3) + 22417

#Resampling subroutine
rare.record.indices <- which(loans_train.z$Default == "1")
rare.indices.resampled <- sample(x = rare.record.indices,size = 51559, replace = TRUE)
rare.records.resampled <- loans_train.z[rare.indices.resampled,]
loans_train.3.3x <- rbind(loans_train.z, rare.records.resampled)
table(loans_train.3.3x$Default)

#Develop 3.3x CART model
TC <- trainControl(method = "CV", number = 10)
fit.CART.3.3x <- train(Default ~ ., data = loans_train.3.3x, method = "rpart", trControl = TC)
fit.CART.3.3x$resample
testsetpreds.CART3.3x <- predict(fit.CART.3.3x,loans_test.z)
table(loans_test.z$Default, testsetpreds.CART3.3x)
testsetpreds.CART3.3x

#Predictions
set.seed(123)

loans_validation$grade <- as.character(loans_validation$grade)#Make the grade variable categorical

loans_validation$term <- as.factor(loans_validation$term)#Make the term variable categorical

loans_validation$Index <- as.factor(loans_validation$Index)#Make the Index variable categorical
#Standardize dataset
library(psych)
library(caret)
preprocess.validation.z <- preProcess(loans_validation[1:6], method = c("center", "scale"))
preprocess.validation.z
loans_validation.z <- predict(preprocess.validation.z,loans_validation[1:6])

#Predict Defaults using Cart
validationsetpreds.CART3.3x <- predict(fit.CART.3.3x,loans_validation.z)
View(validationsetpreds.CART3.3x)

Any help would be greatly appreaciated :)

How would I apply this to the validation data set?


问:
My Android Game Developed By OpenGL ES 2.0 Shows Textures In Low Quality
I'm new to developing Android games using OpenGL ES 2.0.

I recently made a simple game where players must touch hidden numbers respectively that appeared within 3 seconds to win a level.

Each level contains numbers as many as two more than level amounts (For example, level 5 has 5 + 2 numbers).

The game works fine but not enough fine as I expected in two issues:

1 - The textures shown in my game, compared with the image shown in my Image Viewer application, are low in quality.

This is the screenshot of my game:
image

And this is the screenshot of my Image Viewer application:
image

This is my Texture Class:

```<code>package com.theNumbers.openGLES;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLUtils;

public class OpenGLESTexture {

    private final Context mActivityContext;
    private final FloatBuffer mCubeTextureCoordinates;
    private int mTextureUniformHandle;
    private int mTextureCoordinateHandle;
    private final int mTextureCoordinateDataSize = 2;
    private int mTextureDataHandle;
    private final String vertexShaderCode =
            "attribute vec2 a_TexCoordinate;" +
            "varying vec2 v_TexCoordinate;" +
            "uniform mat4 uMVPMatrix;" +
            "attribute vec4 vPosition;" +
            "void main() {" +
            "   gl_Position = uMVPMatrix * vPosition;" +
            "   v_TexCoordinate = a_TexCoordinate;" +
            "}";
    private final String fragmentShaderCode =
            "precision mediump float;" +
            "uniform sampler2D u_Texture;" +
            "varying vec2 v_TexCoordinate;" +
            "void main() {" +
            "   gl_FragColor = texture2D(u_Texture, v_TexCoordinate);" +
            "}";
    private final int shaderProgram;
    private final FloatBuffer vertexBuffer;
    private final ShortBuffer drawListBuffer;
    private int mPositionHandle;
    private int mMVPMatrixHandle;
    static final int COORDS_PER_VERTEX = 2;
    private float[] spriteCoords = new float[8];
    private short drawOrder[] = { 0, 1, 2, 0, 2, 3 };
    private final int vertexStride = COORDS_PER_VERTEX * 4;
    private final float[] mTextureSize = new float[2];

    public OpenGLESTexture(final Context activityContext, final int resourceId, final short width, final short height) {
        mActivityContext = activityContext;
        mTextureSize[0] = width;
        mTextureSize[1] = height;
        spriteCoords[0] = width / 2f;
        spriteCoords[1] = height / 2f;
        spriteCoords[2] = -width / 2f;
        spriteCoords[3] = height / 2f;
        spriteCoords[4] = -width / 2f;
        spriteCoords[5] = -height / 2f;
        spriteCoords[6] = width / 2f;
        spriteCoords[7] = -height / 2f;
        ByteBuffer bb = ByteBuffer.allocateDirect(spriteCoords.length * 4);
        bb.order(ByteOrder.nativeOrder());
        vertexBuffer = bb.asFloatBuffer();
        vertexBuffer.put(spriteCoords);
        vertexBuffer.position(0);
        final float[] cubeTextureCoordinateData =
        {
                 0.0f,  0.0f,
                 1.0f,  0.0f,
                 1.0f,  1.0f,
                 0.0f,  1.0f
        };
        mCubeTextureCoordinates = ByteBuffer.allocateDirect(cubeTextureCoordinateData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
        mCubeTextureCoordinates.put(cubeTextureCoordinateData).position(0);
        ByteBuffer dlb = ByteBuffer.allocateDirect(spriteCoords.length * 2);
        dlb.order(ByteOrder.nativeOrder());
        drawListBuffer = dlb.asShortBuffer();
        drawListBuffer.put(drawOrder);
        drawListBuffer.position(0);
        int vertexShader = OpenGLESRenderer.loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
        int fragmentShader = OpenGLESRenderer.loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);
        shaderProgram = GLES20.glCreateProgram();
        GLES20.glAttachShader(shaderProgram, vertexShader);
        GLES20.glAttachShader(shaderProgram, fragmentShader);
        GLES20.glBindAttribLocation(shaderProgram, 0, "a_TexCoordinate");
        GLES20.glLinkProgram(shaderProgram);
        mTextureDataHandle = loadTexture(mActivityContext, resourceId);
    }

    public void draw(float[] mvpMatrix)
    {
        GLES20.glUseProgram(shaderProgram);
        mPositionHandle = GLES20.glGetAttribLocation(shaderProgram, "vPosition");
        GLES20.glEnableVertexAttribArray(mPositionHandle);
        GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, vertexStride, vertexBuffer);
        mTextureUniformHandle = GLES20.glGetAttribLocation(shaderProgram, "u_Texture");
        mTextureCoordinateHandle = GLES20.glGetAttribLocation(shaderProgram, "a_TexCoordinate");
        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureDataHandle);
        GLES20.glUniform1i(mTextureUniformHandle, 0);
        GLES20.glUniform2fv(GLES20.glGetUniformLocation(shaderProgram, "u_TextureSize"), 1, mTextureSize, 0);//
        mCubeTextureCoordinates.position(0);
        GLES20.glVertexAttribPointer(mTextureCoordinateHandle, mTextureCoordinateDataSize, GLES20.GL_FLOAT, false, 0, mCubeTextureCoordinates);
        GLES20.glEnableVertexAttribArray(mTextureCoordinateHandle);
        mMVPMatrixHandle = GLES20.glGetUniformLocation(shaderProgram, "uMVPMatrix");
        GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0);
        GLES20.glDrawElements(GLES20.GL_TRIANGLES, drawOrder.length, GLES20.GL_UNSIGNED_SHORT, drawListBuffer);
        GLES20.glDisableVertexAttribArray(mPositionHandle);
    }

    public static int loadTexture(final Context context, final int resourceId)
    {
        final int[] textureHandle = new int[1];
        GLES20.glGenTextures(1, textureHandle, 0);
        if (textureHandle[0] != 0)
        {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inScaled = false;
            final Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId, options);
            GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureHandle[0]);
            GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR_MIPMAP_LINEAR);
            GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
            GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
            bitmap.recycle();
            GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D);
            GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
        }
        if (textureHandle[0] == 0)
        {
            throw new RuntimeException("Error loading texture.");
        }
        return textureHandle[0];
    }

}
</code>```

And this is my Renderer Class:

```<code>package com.theNumbers.openGLES;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import com.theNumbers.game.AssetsManager;

import android.content.Context;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;

public class OpenGLESRenderer implements GLSurfaceView.Renderer {

    private final Context mActivityContext;
    private final float[] mMVPMatrix = new float[16];
    private final float[] mProjMatrix = new float[16];
    private final float[] mVMatrix = new float[16];
    private float[] mRotationMatrix = new float[16];
    private boolean onCreate = true;
    public static float[] mStaticMVPMatrix = new float[16];
    public volatile float mAngle;

    public OpenGLESRenderer(final Context context) {
        mActivityContext = context;
    }

    public void onSurfaceCreated(GL10 unused, EGLConfig config) {
        GLES20.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
        GLES20.glEnable(GLES20.GL_BLEND);
        GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_ALPHA);
        AssetsManager.loadAssets(mActivityContext);
    }

    public void onDrawFrame(GL10 unused) {
        GLES20.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
        Matrix.setLookAtM(mVMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
        Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mVMatrix, 0);
        Matrix.setRotateM(mRotationMatrix, 0, mAngle, 0, 0, -1.0f);
        Matrix.multiplyMM(mMVPMatrix, 0, mRotationMatrix, 0, mMVPMatrix, 0);
        AssetsManager.equalizeMatrices(mMVPMatrix);
        if (onCreate) {
            onCreate = false;
            AssetsManager.load(mActivityContext);
            AssetsManager.save(mActivityContext);
            AssetsManager.createGUI();
            AssetsManager.updateLines();
            AssetsManager.mDoesFileExist = false;
        }
        AssetsManager.updateTime();
        AssetsManager.drawGUI();
        AssetsManager.drawRooms(mActivityContext);
        AssetsManager.mIsTouched = false;
    }

    public void onSurfaceChanged(GL10 unused, int width, int height) {
        float aspectRatio = (float) width / height;
        GLES20.glViewport(0, 0, width, height);
        Matrix.frustumM(mProjMatrix, 0, -aspectRatio * 960, aspectRatio * 960, -960, 960, 3, 7);
        AssetsManager.updateLines();
    }

    public static int loadShader(int type, String shaderCode) {
        int shader = GLES20.glCreateShader(type);
        GLES20.glShaderSource(shader, shaderCode);
        GLES20.glCompileShader(shader);
        return shader;
    }

}
</code>```

You can get the complete source code and the APK file here.

2 - Others can easily copy the textures I used in my game.

Just change the APK suffix to the ZIP suffix and open it to see all of my textures.

How can I solve these two issues that I explained above?

Body:
I'm new to developing Android games using OpenGL ES 2.0.

I recently made a simple game where players must touch hidden numbers respectively that appeared within 3 seconds to win a level.

Each level contains numbers as many as two more than level amounts (For example, level 5 has 5 + 2 numbers).

The game works fine but not enough fine as I expected in two issues:

1 - The textures shown in my game, compared with the image shown in my Image Viewer application, are low in quality.

This is the screenshot of my game:
image

And this is the screenshot of my Image Viewer application:
image

This is my Texture Class:

package com.theNumbers.openGLES;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLUtils;

public class OpenGLESTexture {

    private final Context mActivityContext;
    private final FloatBuffer mCubeTextureCoordinates;
    private int mTextureUniformHandle;
    private int mTextureCoordinateHandle;
    private final int mTextureCoordinateDataSize = 2;
    private int mTextureDataHandle;
    private final String vertexShaderCode =
            "attribute vec2 a_TexCoordinate;" +
            "varying vec2 v_TexCoordinate;" +
            "uniform mat4 uMVPMatrix;" +
            "attribute vec4 vPosition;" +
            "void main() {" +
            "   gl_Position = uMVPMatrix * vPosition;" +
            "   v_TexCoordinate = a_TexCoordinate;" +
            "}";
    private final String fragmentShaderCode =
            "precision mediump float;" +
            "uniform sampler2D u_Texture;" +
            "varying vec2 v_TexCoordinate;" +
            "void main() {" +
            "   gl_FragColor = texture2D(u_Texture, v_TexCoordinate);" +
            "}";
    private final int shaderProgram;
    private final FloatBuffer vertexBuffer;
    private final ShortBuffer drawListBuffer;
    private int mPositionHandle;
    private int mMVPMatrixHandle;
    static final int COORDS_PER_VERTEX = 2;
    private float[] spriteCoords = new float[8];
    private short drawOrder[] = { 0, 1, 2, 0, 2, 3 };
    private final int vertexStride = COORDS_PER_VERTEX * 4;
    private final float[] mTextureSize = new float[2];

    public OpenGLESTexture(final Context activityContext, final int resourceId, final short width, final short height) {
        mActivityContext = activityContext;
        mTextureSize[0] = width;
        mTextureSize[1] = height;
        spriteCoords[0] = width / 2f;
        spriteCoords[1] = height / 2f;
        spriteCoords[2] = -width / 2f;
        spriteCoords[3] = height / 2f;
        spriteCoords[4] = -width / 2f;
        spriteCoords[5] = -height / 2f;
        spriteCoords[6] = width / 2f;
        spriteCoords[7] = -height / 2f;
        ByteBuffer bb = ByteBuffer.allocateDirect(spriteCoords.length * 4);
        bb.order(ByteOrder.nativeOrder());
        vertexBuffer = bb.asFloatBuffer();
        vertexBuffer.put(spriteCoords);
        vertexBuffer.position(0);
        final float[] cubeTextureCoordinateData =
        {
                 0.0f,  0.0f,
                 1.0f,  0.0f,
                 1.0f,  1.0f,
                 0.0f,  1.0f
        };
        mCubeTextureCoordinates = ByteBuffer.allocateDirect(cubeTextureCoordinateData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
        mCubeTextureCoordinates.put(cubeTextureCoordinateData).position(0);
        ByteBuffer dlb = ByteBuffer.allocateDirect(spriteCoords.length * 2);
        dlb.order(ByteOrder.nativeOrder());
        drawListBuffer = dlb.asShortBuffer();
        drawListBuffer.put(drawOrder);
        drawListBuffer.position(0);
        int vertexShader = OpenGLESRenderer.loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
        int fragmentShader = OpenGLESRenderer.loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);
        shaderProgram = GLES20.glCreateProgram();
        GLES20.glAttachShader(shaderProgram, vertexShader);
        GLES20.glAttachShader(shaderProgram, fragmentShader);
        GLES20.glBindAttribLocation(shaderProgram, 0, "a_TexCoordinate");
        GLES20.glLinkProgram(shaderProgram);
        mTextureDataHandle = loadTexture(mActivityContext, resourceId);
    }

    public void draw(float[] mvpMatrix)
    {
        GLES20.glUseProgram(shaderProgram);
        mPositionHandle = GLES20.glGetAttribLocation(shaderProgram, "vPosition");
        GLES20.glEnableVertexAttribArray(mPositionHandle);
        GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, vertexStride, vertexBuffer);
        mTextureUniformHandle = GLES20.glGetAttribLocation(shaderProgram, "u_Texture");
        mTextureCoordinateHandle = GLES20.glGetAttribLocation(shaderProgram, "a_TexCoordinate");
        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureDataHandle);
        GLES20.glUniform1i(mTextureUniformHandle, 0);
        GLES20.glUniform2fv(GLES20.glGetUniformLocation(shaderProgram, "u_TextureSize"), 1, mTextureSize, 0);//
        mCubeTextureCoordinates.position(0);
        GLES20.glVertexAttribPointer(mTextureCoordinateHandle, mTextureCoordinateDataSize, GLES20.GL_FLOAT, false, 0, mCubeTextureCoordinates);
        GLES20.glEnableVertexAttribArray(mTextureCoordinateHandle);
        mMVPMatrixHandle = GLES20.glGetUniformLocation(shaderProgram, "uMVPMatrix");
        GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0);
        GLES20.glDrawElements(GLES20.GL_TRIANGLES, drawOrder.length, GLES20.GL_UNSIGNED_SHORT, drawListBuffer);
        GLES20.glDisableVertexAttribArray(mPositionHandle);
    }

    public static int loadTexture(final Context context, final int resourceId)
    {
        final int[] textureHandle = new int[1];
        GLES20.glGenTextures(1, textureHandle, 0);
        if (textureHandle[0] != 0)
        {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inScaled = false;
            final Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId, options);
            GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureHandle[0]);
            GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR_MIPMAP_LINEAR);
            GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
            GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
            bitmap.recycle();
            GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D);
            GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
        }
        if (textureHandle[0] == 0)
        {
            throw new RuntimeException("Error loading texture.");
        }
        return textureHandle[0];
    }

}

And this is my Renderer Class:

package com.theNumbers.openGLES;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import com.theNumbers.game.AssetsManager;

import android.content.Context;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;

public class OpenGLESRenderer implements GLSurfaceView.Renderer {

    private final Context mActivityContext;
    private final float[] mMVPMatrix = new float[16];
    private final float[] mProjMatrix = new float[16];
    private final float[] mVMatrix = new float[16];
    private float[] mRotationMatrix = new float[16];
    private boolean onCreate = true;
    public static float[] mStaticMVPMatrix = new float[16];
    public volatile float mAngle;

    public OpenGLESRenderer(final Context context) {
        mActivityContext = context;
    }

    public void onSurfaceCreated(GL10 unused, EGLConfig config) {
        GLES20.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
        GLES20.glEnable(GLES20.GL_BLEND);
        GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_ALPHA);
        AssetsManager.loadAssets(mActivityContext);
    }

    public void onDrawFrame(GL10 unused) {
        GLES20.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
        Matrix.setLookAtM(mVMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
        Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mVMatrix, 0);
        Matrix.setRotateM(mRotationMatrix, 0, mAngle, 0, 0, -1.0f);
        Matrix.multiplyMM(mMVPMatrix, 0, mRotationMatrix, 0, mMVPMatrix, 0);
        AssetsManager.equalizeMatrices(mMVPMatrix);
        if (onCreate) {
            onCreate = false;
            AssetsManager.load(mActivityContext);
            AssetsManager.save(mActivityContext);
            AssetsManager.createGUI();
            AssetsManager.updateLines();
            AssetsManager.mDoesFileExist = false;
        }
        AssetsManager.updateTime();
        AssetsManager.drawGUI();
        AssetsManager.drawRooms(mActivityContext);
        AssetsManager.mIsTouched = false;
    }

    public void onSurfaceChanged(GL10 unused, int width, int height) {
        float aspectRatio = (float) width / height;
        GLES20.glViewport(0, 0, width, height);
        Matrix.frustumM(mProjMatrix, 0, -aspectRatio * 960, aspectRatio * 960, -960, 960, 3, 7);
        AssetsManager.updateLines();
    }

    public static int loadShader(int type, String shaderCode) {
        int shader = GLES20.glCreateShader(type);
        GLES20.glShaderSource(shader, shaderCode);
        GLES20.glCompileShader(shader);
        return shader;
    }

}

You can get the complete source code and the APK file here.

2 - Others can easily copy the textures I used in my game.

Just change the APK suffix to the ZIP suffix and open it to see all of my textures.

How can I solve these two issues that I explained above?


问:
Git is picking up changes but all branches are up to date
So I just recently pushed a branch up as follows featureBranch -> Dev -> Main -> MainProd. I made sure all the branches were up to date by pulling down the latest from orgin.

However, when I git diff Dev...Main for example its telling me there are multiple differences with 5 different files. If I look at those files using git checkout Dev and then checkout Main, all of those files are synced and exactly the same on both branches. Also, if I git diff between any two of Dev, Main, and Main-Prod it says the same thing for each one with the same 5 files. Any idea how to fix this? Thanks!

PS. were using pull requests to merge code and azure dev ops. Main and Main-Prod can only have code merged in via pull requests. I read somewhere this could be a result of a squash commit?


问:
Can I "print" a turtle window with a tkinter button to create a recursive shape?
I have a fairly simplistic GUI with two tabs and a popup button. I'd like to ad a fun piece of recursion, so I was wondering if I can create a button on my tkinter window and then use turtle to make a fractal in the window.

The button shows in the window, but it doesn't seem that the turtle screen is popping up.

```<code>from tkinter import *
from tkinter import ttk as ttk
import turtle as t

def fractal(color, size, x, y):
    tertiary_window = turtle.Screen() # Create the screen.
    tertiary_window.setup(320, 320)

    t.penup()
    t.color(color)
    t.fillcolor(color)
    t.goto(x,y)
    t.begin_fill()
    t.pendown()
    t.circle(size)
    t.penup()
    t.end_fill()
    t.pendown()

    draw_circle("blue", 50, 0, 0)
    draw_circle("yellow", 50, -25, 0)

def main():
    '''this is essentially main, kicks everything off and begins the *game* haha'''
    start_button.destroy()
    start_label.destroy()

    flashcard_entry=Entry(tab1,width=80,borderwidth=15)
    flashcard_entry.place(x=245,y=375)

    entry_label=Label(tab1, text="Enter .csv file name \n (put .csv at end) ",font=("fixedsys",30),wraplength=590,bg="#6e17bf",fg="White",justify="center")
    entry_label.place(x=280,y=280)

    entry_button=Button(tab1, text="use flashcard set",font=("fixedsys",30),command=lambda:get_flashcards(flashcard_entry,entry_label,entry_button),bg="#2a19e3",fg="white",padx=73)
    entry_button.place(x=245,y=450)

    ###the rest of our data is passed by using the button in Tkinter, which calls a function  or preset module as a command

window=Tk()
window.configure(bg="bisque3")
#window.resizable(False, False)
window.geometry("1001x601")
window.title("Flashcard-App")

tabControl = ttk.Notebook(window)
tab1 = Frame(tabControl)
tab2 = Frame(tabControl)

tabControl.add(tab1, text ='Instructions & File')
tabControl.add(tab2, text ='Flashcards')
tabControl.pack(expand = 1, fill ="both")

help_button= Button(window,text="Help",font=("fixedsys",30),command=open_help,bg="red")
help_button.place(x=0, y=25)

start_label=Label(text="FLASHCARDS",font=("fixedsys",155),bg="bisque3",fg="burlywood4",pady=90)
start_label.place(x=245,y=100)
start_button=Button(text="START STUDYING",font=("fixedsys",30),command=main,bg="#2a19e3",fg="white",anchor=CENTER,padx=99)
start_button.place(x=246,y=450)
window.mainloop()
</code>```

Body:
I have a fairly simplistic GUI with two tabs and a popup button. I'd like to ad a fun piece of recursion, so I was wondering if I can create a button on my tkinter window and then use turtle to make a fractal in the window.

The button shows in the window, but it doesn't seem that the turtle screen is popping up.

from tkinter import *
from tkinter import ttk as ttk
import turtle as t

def fractal(color, size, x, y):
    tertiary_window = turtle.Screen() # Create the screen.
    tertiary_window.setup(320, 320)

    t.penup()
    t.color(color)
    t.fillcolor(color)
    t.goto(x,y)
    t.begin_fill()
    t.pendown()
    t.circle(size)
    t.penup()
    t.end_fill()
    t.pendown()

    draw_circle("blue", 50, 0, 0)
    draw_circle("yellow", 50, -25, 0)

def main():
    '''this is essentially main, kicks everything off and begins the *game* haha'''
    start_button.destroy()
    start_label.destroy()

    flashcard_entry=Entry(tab1,width=80,borderwidth=15)
    flashcard_entry.place(x=245,y=375)

    entry_label=Label(tab1, text="Enter .csv file name \n (put .csv at end) ",font=("fixedsys",30),wraplength=590,bg="#6e17bf",fg="White",justify="center")
    entry_label.place(x=280,y=280)

    entry_button=Button(tab1, text="use flashcard set",font=("fixedsys",30),command=lambda:get_flashcards(flashcard_entry,entry_label,entry_button),bg="#2a19e3",fg="white",padx=73)
    entry_button.place(x=245,y=450)

    ###the rest of our data is passed by using the button in Tkinter, which calls a function  or preset module as a command

window=Tk()
window.configure(bg="bisque3")
#window.resizable(False, False)
window.geometry("1001x601")
window.title("Flashcard-App")

tabControl = ttk.Notebook(window)
tab1 = Frame(tabControl)
tab2 = Frame(tabControl)

tabControl.add(tab1, text ='Instructions & File')
tabControl.add(tab2, text ='Flashcards')
tabControl.pack(expand = 1, fill ="both")

help_button= Button(window,text="Help",font=("fixedsys",30),command=open_help,bg="red")
help_button.place(x=0, y=25)

start_label=Label(text="FLASHCARDS",font=("fixedsys",155),bg="bisque3",fg="burlywood4",pady=90)
start_label.place(x=245,y=100)
start_button=Button(text="START STUDYING",font=("fixedsys",30),command=main,bg="#2a19e3",fg="white",anchor=CENTER,padx=99)
start_button.place(x=246,y=450)
window.mainloop()


问:
Amchart Geodata & Excel - track simulated flight
Please I would like to use Excel to simulate flight route live . And visualize live where all aircrafts are in they journey at any given time. Can you assist me ?.I appreciate and await your detailled instruction.

I have doawnloaded the amchart geo data but do not know how to set it up with my excel


问:
Whenever i try to mock the apex method in test case i am getting "Cannot read properties of undefined (reading 'then') " error
if i place the " isOptimizationV2Enabled.mockResolvedValue(false);" inside before each it works as expected, but i want to assign the different value for each test case.
I tried several methods but facing same error</p>


问:
Outbound Modal Redirect
I have a speedbump on my WordPress site to prompt visitors that they are about to go to a 3rd party site when they click on links in the footer that our outside of my domain. It automatically redirects the visitor after 5 seconds to the page even if they don't click 'Ok' to acknowledge. Any suggested edits to remove the timeout?</p>
```<code>  $("a[href^='http']").filter(domainFilter).on('click', function (e, element) {
    e.preventDefault();
    const tgt = $(this)
    const url = tgt.attr('href')
    let clicked = false;
    const redirect = setTimeout(function () {
      if (clicked === false) {
        $.modal.close();
        window.location = url;
      }
    }, delay);

    $("#outbound-modal").modal({
      fadeDuration: 250
    })

    $('#outbound-modal').one($.modal.BEFORE_CLOSE, function (event, modal) {
      clearTimeout(redirect)
    });

    $('#outbound-modal .outbound-modal_target-link').attr('href', url).one('click', () => {
      clicked = true;
      $.modal.close();
    });
</code>```

Title: Outbound Modal Redirect

Body:
I have a speedbump on my WordPress site to prompt visitors that they are about to go to a 3rd party site when they click on links in the footer that our outside of my domain. It automatically redirects the visitor after 5 seconds to the page even if they don't click 'Ok' to acknowledge. Any suggested edits to remove the timeout?

  $("a[href^='http']").filter(domainFilter).on('click', function (e, element) {
    e.preventDefault();
    const tgt = $(this)
    const url = tgt.attr('href')
    let clicked = false;
    const redirect = setTimeout(function () {
      if (clicked === false) {
        $.modal.close();
        window.location = url;
      }
    }, delay);

    $("#outbound-modal").modal({
      fadeDuration: 250
    })

    $('#outbound-modal').one($.modal.BEFORE_CLOSE, function (event, modal) {
      clearTimeout(redirect)
    });

    $('#outbound-modal .outbound-modal_target-link').attr('href', url).one('click', () => {
      clicked = true;
      $.modal.close();
    });


问:
impossible to connect to a websocket
I'm trying to connect as a client to my websocket, but yet every time I try this error comes up, I've tried literally everything but the result is always the same

(with other languages, for example NodeJS, I can connect without problems)

```<code>
The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/root/api/.venv/lib/python3.9/site-packages/websockets/legacy/client.py", line 138, in read_http_response
    status_code, reason, headers = await read_response(self.reader)
  File "/root/api/.venv/lib/python3.9/site-packages/websockets/legacy/http.py", line 122, in read_response
    raise EOFError("connection closed while reading HTTP status line") from exc
EOFError: connection closed while reading HTTP status line

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/root/api/.venv/lib/python3.9/site-packages/websockets/legacy/client.py", line 666, in __await_impl__
    await protocol.handshake(
  File "/root/api/.venv/lib/python3.9/site-packages/websockets/legacy/client.py", line 326, in handshake
    status_code, response_headers = await self.read_http_response()
  File "/root/api/.venv/lib/python3.9/site-packages/websockets/legacy/client.py", line 144, in read_http_response
    raise InvalidMessage("did not receive a valid HTTP response") from exc
websockets.exceptions.InvalidMessage: did not receive a valid HTTP response

</code>```

code:

import websockets
from websockets import client

async def receiver(ws):
    for message in ws:
        print(f"{message}")

async for websocket in client.connect('wss://localhost:8777/password/AAAAAA/1/175/'):
    try:
        print('connecting')
    except websockets.ConnectionClosed:
        print('error')
```

Title: impossible to connect to a websocket

Body:
I'm trying to connect as a client to my websocket, but yet every time I try this error comes up, I've tried literally everything but the result is always the same

(with other languages, for example NodeJS, I can connect without problems)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/root/api/.venv/lib/python3.9/site-packages/websockets/legacy/client.py", line 138, in read_http_response
    status_code, reason, headers = await read_response(self.reader)
  File "/root/api/.venv/lib/python3.9/site-packages/websockets/legacy/http.py", line 122, in read_response
    raise EOFError("connection closed while reading HTTP status line") from exc
EOFError: connection closed while reading HTTP status line

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/root/api/.venv/lib/python3.9/site-packages/websockets/legacy/client.py", line 666, in __await_impl__
    await protocol.handshake(
  File "/root/api/.venv/lib/python3.9/site-packages/websockets/legacy/client.py", line 326, in handshake
    status_code, response_headers = await self.read_http_response()
  File "/root/api/.venv/lib/python3.9/site-packages/websockets/legacy/client.py", line 144, in read_http_response
    raise InvalidMessage("did not receive a valid HTTP response") from exc
websockets.exceptions.InvalidMessage: did not receive a valid HTTP response

code:

import websockets
from websockets import client

async def receiver(ws):
    for message in ws:
        print(f"{message}")

async for websocket in client.connect('wss://localhost:8777/password/AAAAAA/1/175/'):
    try:
        print('connecting')
    except websockets.ConnectionClosed:
        print('error')


问:
why firebase not sending me spam message on my main E-mail account? here is my android studio kotlin code:
```<code>buttonSendEmail.setOnClickListener {

    val email = editTextEmail.text.toString()

    if(email.isNotEmpty()){
        FirebaseAuth.getInstance().sendPasswordResetEmail(email)
            .addOnCompleteListener { task ->
                if(task.isSuccessful){
                    Toast.makeText(this, "Check E-mail", Toast.LENGTH_SHORT).show()
                }else{
                    Toast.makeText(this, "Error!", Toast.LENGTH_SHORT).show()
                }
            }
    }else{
        Toast.makeText(this, "Empty!", Toast.LENGTH_SHORT).show()
    }
}
</code>```

everything is fine, I think, but actualy not working :/ If someone has any idea, please help me.

Body:
buttonSendEmail.setOnClickListener {

    val email = editTextEmail.text.toString()

    if(email.isNotEmpty()){
        FirebaseAuth.getInstance().sendPasswordResetEmail(email)
            .addOnCompleteListener { task ->
                if(task.isSuccessful){
                    Toast.makeText(this, "Check E-mail", Toast.LENGTH_SHORT).show()
                }else{
                    Toast.makeText(this, "Error!", Toast.LENGTH_SHORT).show()
                }
            }
    }else{
        Toast.makeText(this, "Empty!", Toast.LENGTH_SHORT).show()
    }
}

everything is fine, I think, but actualy not working :/ If someone has any idea, please help me.


问:
Loop trough nested folder structure and change a line in all files with node.js
I want to write a script that loops through a nested folder structure and changes for instance console.log('hello world') in each javascript file. I simplified the task and basically can't use the in-built VS search and replace tool. Folder structure looks like this:

My try:

```<code>function changeLine(folderPaths) {

  folderPaths.forEach(folderPath=> {
    const results = fs.readdirSync(folderPath)
    const folders = results.filter(res=> fs.lstatSync(path.resolve(folderPath, res)).isDirectory())

    const innerFolderPaths = folders.map(folder => path.resolve(folderPath, folder));
    if(innerFolderPaths.length ===0) {
      return
    }
    innerFolderPaths.forEach(
      inner=>{
      if(fs.lstatSync(inner).isDirectory()) {
       //go deeper and change individual file
      let individualFile = fs.readFileSync(<go to individual file>).toString()
      individualFile = fileString.replace(/console.log('hello world')/, 'line changed');
  }}
  )
})
}

changeLine([path.resolve(__dirname, 'src')] )
</code>```

I don't have much experience with node.js and that's what I came up with so far. The if condition inside the forEach Loop is not correct, hope someone can make sense of it. Thanks for reading!

Body:
I want to write a script that loops through a nested folder structure and changes for instance console.log('hello world') in each javascript file. I simplified the task and basically can't use the in-built VS search and replace tool. Folder structure looks like this:

My try:

function changeLine(folderPaths) {

  folderPaths.forEach(folderPath=> {
    const results = fs.readdirSync(folderPath)
    const folders = results.filter(res=> fs.lstatSync(path.resolve(folderPath, res)).isDirectory())

    const innerFolderPaths = folders.map(folder => path.resolve(folderPath, folder));
    if(innerFolderPaths.length ===0) {
      return
    }
    innerFolderPaths.forEach(
      inner=>{
      if(fs.lstatSync(inner).isDirectory()) {
       //go deeper and change individual file
      let individualFile = fs.readFileSync(<go to individual file>).toString()
      individualFile = fileString.replace(/console.log('hello world')/, 'line changed');
  }}
  )
})
}

changeLine([path.resolve(__dirname, 'src')] )

I don't have much experience with node.js and that's what I came up with so far. The if condition inside the forEach Loop is not correct, hope someone can make sense of it. Thanks for reading!


问:
Multithreading in c++ ending unexpectledly
I'm a newbie in multithread, so the problem is: I'm trying to make multiple threads send message to a server, ever thread represents a device. The server who I'm testing has 10k ports open so every socket has his exclusively port. The problem is the program subtly stops and don't send all messages from all devices. I'm using a vector of futures to simulate the devices, that way:

```<code>vector<future<void>> futures;
map<string,vector<string> >::iterator it = mapDevtoMessage.begin();
for(it = mapDevtoMessage.begin(); it != mapDevtoMessage.end(); it++){
  futures.push_back(async(launch::async,[&]{ send_messages(it->second, it->first);}));
  std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
for(auto &its : futures){
  its.wait();
}
</code>```

The code for send_messages is:

```<code>void send_messages (vector<string>& vec, string name){
  mtx.lock();
  PORT++;
  mtx.unlock();
  int sock = 0, client_fd;
  struct sockaddr_in serv_addr;
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
       printf("\n Socket creation error \n");
    }
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_port = htons(PORT);
  if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
        printf("\nInvalid address/ Address not supported \n");
    }
  if ((client_fd
        = connect(sock, (struct sockaddr*)&serv_addr,
                  sizeof(serv_addr)))
      < 0) {
      printf("\nConnection Failed \n");
  }
  for(auto &i : vec){
    string val = hexToASCII(i);
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    send(sock, val.c_str(), 100, 0);
    mtx.lock();
    printf("\nmessage %s from %s send\n", i.c_str() , name.c_str());
    mtx.unlock();
  }

    // closing the connected socket
  close(client_fd);
}
</code>```

I added the for loop with the wait() method because the program keep terminating unexpectledly without any error or anything. So I added, but the program continues to subtle terminate. I tried an endless loop also. I may have missed a simple thing (I'm a noob), please let me know.

Body:
I'm a newbie in multithread, so the problem is: I'm trying to make multiple threads send message to a server, ever thread represents a device. The server who I'm testing has 10k ports open so every socket has his exclusively port. The problem is the program subtly stops and don't send all messages from all devices. I'm using a vector of futures to simulate the devices, that way:

vector<future<void>> futures;
map<string,vector<string> >::iterator it = mapDevtoMessage.begin();
for(it = mapDevtoMessage.begin(); it != mapDevtoMessage.end(); it++){
  futures.push_back(async(launch::async,[&]{ send_messages(it->second, it->first);}));
  std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
for(auto &its : futures){
  its.wait();
}

The code for send_messages is:

void send_messages (vector<string>& vec, string name){
  mtx.lock();
  PORT++;
  mtx.unlock();
  int sock = 0, client_fd;
  struct sockaddr_in serv_addr;
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
       printf("\n Socket creation error \n");
    }
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_port = htons(PORT);
  if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
        printf("\nInvalid address/ Address not supported \n");
    }
  if ((client_fd
        = connect(sock, (struct sockaddr*)&serv_addr,
                  sizeof(serv_addr)))
      < 0) {
      printf("\nConnection Failed \n");
  }
  for(auto &i : vec){
    string val = hexToASCII(i);
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    send(sock, val.c_str(), 100, 0);
    mtx.lock();
    printf("\nmessage %s from %s send\n", i.c_str() , name.c_str());
    mtx.unlock();
  }

    // closing the connected socket
  close(client_fd);
}

I added the for loop with the wait() method because the program keep terminating unexpectledly without any error or anything. So I added, but the program continues to subtle terminate. I tried an endless loop also. I may have missed a simple thing (I'm a noob), please let me know.


问:
Stop UL text from dropping down a line when restoring down a webpage
I'm a very new to programming and would like some help with this web-build for my university website portfolio. Basically, I am trying to stop the list from dropping down when restoring down a webpage. Please feel free to recommend any changes as well as I would like this webpage to be as optimized as possible.

Many thanks!

Jack

```<code><!DOCTYPE html>
    <head>
        <link rel ="stylesheet" href ="style.css">
        <title>Jack Shaw | Dev and Design</title>
        <meta name = "viewport" content="width=device-width, initial-scale=1.0">
        <meta charset ="utf-8">
        <script src="https://kit.fontawesome.com/a33f9e206b.js" crossorigin="anonymous"></script>
    </head>

    <body>

    <div class ="container">
        <div class ="header">
            <nav class ="navigation">
                <ul>
                    <li>
                        <a href ="#">Home</a>
                    </li>
                    <li>
                        <a href = "#">Year 1</a>
                    </li>
                    <li>
                        <a href ="#">Year 2</a>
                    </li>
                    <li>
                        <a href ="#">Year 3</a>
                    </li>
                    <li>
                        <a href ="#">About</a>
                    </li>
                </ul>
            </nav>
        </div>

        <div class ="hero">
            <h1>Hero Project</h1>
        </div>

        <div class ="project-1">
            <h2>Project 1</h2>
        </div>

        <div class ="project-2">
            <h2>Project 2</h2>
        </div>

        <div class ="concept">
            Concept Art and Other Works
        </div>

        <div class ="about">
            About Me
        </div>

        <div class ="footer">
            Social Media and Info
        </div>

    </div>

    </body>
</html>
</code>```
```<code>``
/* Website Grid and Margins */
body {
    margin: 0;
    background-color: rgb(136, 165, 197)
}
/* Grid Container */
.container {
    width: 100vw;
    height: 100vh;
    font-family: 'Quicksand', sans-serif ;
    font-weight: bold;
    font-size: 20px;
    display: grid;
    grid-template-columns: repeat(10, 1fr);
    grid-template-rows: 70px repeat(8, 1fr) 100px;
    gap: 10px;
    padding: 10px;
    box-sizing: border-box;
}
/* Container Boxes */
.container div {
    border: 1px solid black;
    background-color: rgb(185, 205, 207);
}
/* Header */
.header {
    grid-column: 1 / 11;
    padding-top: 5px;
}
/* Header Tabs */
ul li {
    float: left;
    margin-right: 8%;
    margin-left: 8%;
    list-style: none;

}

.footer {
    grid-column: 1 / 11;
    grid-row: 10 / 11;
}

.hero {
    grid-column: 1 / 7;
    grid-row: 2 / 7;
}

.hero h1 {
    margin: 0;
    margin-top: 100px;
    margin-left: 50px;
}

.project-1 {
    grid-column: 7 / 9;
    grid-row: 2 / 7;
}

.project-2 {
    grid-column: 9 / 11;
    grid-row: 2 / 7;
}

.concept {
    grid-column: 1 / 6;
    grid-row: 7 / 10;
}

.about {
    grid-column: 6 / 11;
    grid-row: 7 / 10
}
``
</code>```

Tried to research how to stop this from happening but not sure why.

Body:
I'm a very new to programming and would like some help with this web-build for my university website portfolio. Basically, I am trying to stop the list from dropping down when restoring down a webpage. Please feel free to recommend any changes as well as I would like this webpage to be as optimized as possible.

Many thanks!

Jack

<!DOCTYPE html>

        <link rel ="stylesheet" href ="style.css">
        <title>Jack Shaw | Dev and Design</title>
        <meta name = "viewport" content="width=device-width, initial-scale=1.0">
        <meta charset ="utf-8">

                        Home

                        Year 1

                        Year 2

                        Year 3

                        About

Hero Project

Project 1

Project 2

            Concept Art and Other Works

            About Me

            Social Media and Info

``
/* Website Grid and Margins */
body {
    margin: 0;
    background-color: rgb(136, 165, 197)
}
/* Grid Container */
.container {
    width: 100vw;
    height: 100vh;
    font-family: 'Quicksand', sans-serif ;
    font-weight: bold;
    font-size: 20px;
    display: grid;
    grid-template-columns: repeat(10, 1fr);
    grid-template-rows: 70px repeat(8, 1fr) 100px;
    gap: 10px;
    padding: 10px;
    box-sizing: border-box;
}
/* Container Boxes */
.container div {
    border: 1px solid black;
    background-color: rgb(185, 205, 207);
}
/* Header */
.header {
    grid-column: 1 / 11;
    padding-top: 5px;
}
/* Header Tabs */
ul li {
    float: left;
    margin-right: 8%;
    margin-left: 8%;
    list-style: none;

}

.footer {
    grid-column: 1 / 11;
    grid-row: 10 / 11;
}

.hero {
    grid-column: 1 / 7;
    grid-row: 2 / 7;
}

.hero h1 {
    margin: 0;
    margin-top: 100px;
    margin-left: 50px;
}

.project-1 {
    grid-column: 7 / 9;
    grid-row: 2 / 7;
}

.project-2 {
    grid-column: 9 / 11;
    grid-row: 2 / 7;
}

.concept {
    grid-column: 1 / 6;
    grid-row: 7 / 10;
}

.about {
    grid-column: 6 / 11;
    grid-row: 7 / 10
}
``

Tried to research how to stop this from happening but not sure why.


问:
ViewPager in Android with XML and Compose
I'm working with Compose but have Fragments. I need to switch to second page when user click IconButton.

With only xml:

```<code>  _binding = FragmentFirstScreenBinding.inflate(inflater, container, false)

        val viewPager = activity?.findViewById<ViewPager2>(R.id.viewPager)

        binding.firstFragmentButton.setOnClickListener{
            viewPager?.currentItem = 1
        }
</code>```

In Compose:

```<code>  AndroidView(factory = { context ->
                        val viewPager = activity?.findViewById<ViewPager2>(R.id.viewPager)
                        val view = LayoutInflater.from(context)
                            .inflate(R.layout.fragment_view_pager, null, false)
                        viewPager?.currentItem = 1
                        view

                    })
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                    ) {
                        IconButton(
                            onClick = { },
                            modifier = Modifier
                                .height(90.dp)
                                .width(90.dp)
                                .align(Alignment.TopEnd)
                        ) {
                            Icon(
                                painter = painterResource(id = R.drawable.ic_baseline_keyboard_arrow_right_24),
                                contentDescription = "",
                            )
                        }
                    }
</code>```

Problem with this code is that automatically I switch to second page.
I tried to put viewPager in IconButton on click but I dont get view back and got null when user clicks icon. My question is how to get that viewPager into compose part.

EDIT:
Just put viewPager in onCreateView before

```<code>val viewPager = activity?.findViewById<ViewPager2>(R.id.viewPager)
return ComposeView(requireContext()).apply {
setContent {
</code>```

Body:
I'm working with Compose but have Fragments. I need to switch to second page when user click IconButton.

With only xml:

  _binding = FragmentFirstScreenBinding.inflate(inflater, container, false)

        val viewPager = activity?.findViewById<ViewPager2>(R.id.viewPager)

        binding.firstFragmentButton.setOnClickListener{
            viewPager?.currentItem = 1
        }

In Compose:

  AndroidView(factory = { context ->
                        val viewPager = activity?.findViewById<ViewPager2>(R.id.viewPager)
                        val view = LayoutInflater.from(context)
                            .inflate(R.layout.fragment_view_pager, null, false)
                        viewPager?.currentItem = 1
                        view

                    })
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                    ) {
                        IconButton(
                            onClick = { },
                            modifier = Modifier
                                .height(90.dp)
                                .width(90.dp)
                                .align(Alignment.TopEnd)
                        ) {
                            Icon(
                                painter = painterResource(id = R.drawable.ic_baseline_keyboard_arrow_right_24),
                                contentDescription = "",
                            )
                        }
                    }

Problem with this code is that automatically I switch to second page.
I tried to put viewPager in IconButton on click but I dont get view back and got null when user clicks icon. My question is how to get that viewPager into compose part.

EDIT:
Just put viewPager in onCreateView before

val viewPager = activity?.findViewById<ViewPager2>(R.id.viewPager)
return ComposeView(requireContext()).apply {
setContent {


问:
How to debug rails app with Tilt setup in Dev environment
I am new to tilt. I am struggling to debug a rails app with Tilt. I can provide more details on it if needed. Thanks!

I tried some rails gem like pry-remote, byebug and debug etc but non of them are working or i am doing it in wrong way.

Pls suggest a way of debugging rails app with tilt in dev environment.


问:
Python ignores my code and I don't know why
My stripped code:

```<code>board = [] # 2 dimensional matrix (not showed here)

def build_ships():
    if (
        small_ship(board) == 1
    ):
        # When small_ships returns 1 it doesn't do anything, just ignores my code below
        code_2 clearing board to default
        build_ships()
        return 0

def small_ship(board):
    try:
        code_1 with recursions
    except RecursionError:
        return 1

build_ships()
</code>```

What am I missing?? I'm blind or missing some important rule here.

Thanks for help

When there's recursion error, it should start over with a clear board, instead it just ignores the code to start over with a clear board and do Nothing at all.

Body:
My stripped code:

board = [] # 2 dimensional matrix (not showed here)

def build_ships():
    if (
        small_ship(board) == 1
    ):
        # When small_ships returns 1 it doesn't do anything, just ignores my code below
        code_2 clearing board to default
        build_ships()
        return 0

def small_ship(board):
    try:
        code_1 with recursions
    except RecursionError:
        return 1

build_ships()

What am I missing?? I'm blind or missing some important rule here.

Thanks for help

When there's recursion error, it should start over with a clear board, instead it just ignores the code to start over with a clear board and do Nothing at all.


问:
How do I automate searching information of a list and pasting it to a document
I'm new to programing. I decided to learn how to automate menial task for my school research project. I have a large list of animals that I need to collect information on and record it on a table; like a spreadsheet. I want to make a program that scans through the list, then searches for the animal and downloads a picture of that animal then searches of other information on the animal (like body length) and pastes it to the spreadsheet. Truthfuly I have no idea where to start, what language would be best for this or whether its possible so any help would be appreciated.

I know this isnt much but this is the test code I wrote for pasting the info into the spreadsheet in python
import openpyxl wb = openpyxl.load_workbook('spreadsheet.xlsx') sheet = wb.active sheet['A1'] = 'Hello World!' sheet['A2'] = 'Good Bye World' wb.save('spreadsheet.xlsx')

overrall I'm pretty lost so any help or direction would be great