问:
How can I get the time at which the audio from the microphone is received by the computer using sounddevice callback?
SO I want to get the following times:-

t_0 = the time at which the microphone is triggered by the python code

t_1 = the time at which the microphone starts recording

t_2 = the time at which the system/computer recieves the audio from the microphone

I am doing all of this to get the exact latency.

Till now I have the following-

sounddevice to get the triggered time t_0

```<code>record_voice = sounddevice.rec(int( durations * samp ) , samplerate = samp , channels = 2 )
</code>```

Thinking of using usbrply for t_1 but have no clue on how to.

I want to use the callback function from

```<code>https://python-sounddevice.readthedocs.io/en/0.4.5/usage.html#recording
</code>```

to get the time t_2 but I don't know how to get the time from it.

Can anyone help me with this?

Body:
SO I want to get the following times:-

t_0 = the time at which the microphone is triggered by the python code

t_1 = the time at which the microphone starts recording

t_2 = the time at which the system/computer recieves the audio from the microphone

I am doing all of this to get the exact latency.

Till now I have the following-

sounddevice to get the triggered time t_0

record_voice = sounddevice.rec(int( durations * samp ) , samplerate = samp , channels = 2 )

Thinking of using usbrply for t_1 but have no clue on how to.

I want to use the callback function from

https://python-sounddevice.readthedocs.io/en/0.4.5/usage.html#recording

to get the time t_2 but I don't know how to get the time from it.

Can anyone help me with this?


来源: stackexchange

问:
Appcenter build failure org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction

What went wrong:
Execution failed for task ':app:kaptReleaseKotlin'.

A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction
java.lang.reflect.InvocationTargetException (no error message)

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 13m 33s

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.7.1/userguide/command_line_interface.html#sec:command_line_warnings
181 actionable tasks: 171 executed, 10 up-to-date
Error: /Users/runner/work/1/s/android/gradlew failed with return code: 1
at ChildProcess. (/Users/runner/work/_tasks/Gradle_8d8eebd8-2b94-4c97-85af-839254cc6da4/1.128.0/node_modules/vsts-task-lib/toolrunner.js:569:30)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:920:16)
at Socket. (internal/child_process.js:351:11)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at Pipe._handle.close [as _onclose] (net.js:509:12)

ContentLicense: CC BY-SA 4.0


问:
I can't launch the application in unicorn
2022-12-29 16:30:10,287 - uvicorn.error - INFO - Uvicorn running on http://localhost:8080 (Press CTRL+C to quit)
2022-12-29 16:30:10,287 - uvicorn.error - INFO - Started reloader process [12316] using StatReload
2022-12-29 16:30:11,767 - uvicorn.error - ERROR - Error loading ASGI app. Could not import module "app.main".
2022-12-29 16:30:11,767 - uvicorn.error - ERROR - Error loading ASGI app. Could not import module "app.main".
2022-12-29 16:30:11,767 - uvicorn.error - ERROR - Error loading ASGI app. Could not import module "app.main".

i want see all error or run my apps


问:
How to add a button on taskbar using python?
How can add a button on taskbar where there it shows battery, connection status as in the picture?(https://i.stack.imgur.com/yqbs8.png)

I wanted a play button there on the taskbar through which I could control something on my python app.


问:
Loss is Inf, while fine-tuning gpt-neo-125M on wikisql dataset
I'm trying to fine-tune GPT 125M params on WikiSql dataset, I'm sharing the code here as well.

I declared the batch size to be 32, and number of epochs is 10.

Unfortunately, I'm getting loss value is Inf, kindly help me to figure out what am I doing wrong?

And do I fine-tune the model properly?

The shape of each target_tensor and logits are :
Logits shape: torch.Size([32, 147, 50257])
Target shape: torch.Size([32, 147])

PSB the code that I ran to fine-tune GPT 125M:

```<code>import torch
from transformers import GPTNeoForCausalLM, GPT2Tokenizer
import pandas as pd
import transformers

# Check if MPS is available and built
print(torch.backends.mps.is_available())
print(torch.backends.mps.is_built())

# Set the device to MPS MacBook pro GPU
device = torch.device("mps")

# Load the dataset with pandas
dataset = pd.read_csv("wikisql/train.csv")

# Tokenize the text using the GPT-NeoX tokenizer
tokenizer = GPT2Tokenizer.from_pretrained("EleutherAI/gpt-neo-125M")
tokenizer.pad_token_id = 50256
# Get the text and sql columns from the dataset
print(tokenizer.pad_token_id)
text_list = dataset['question']
sql_list = dataset['sql']

# Convert the sql to a list of tokens
sql_tokens_list = [tokenizer.encode(sql, add_special_tokens=True) for sql in sql_list if sql is not None]

# Find the maximum length of the sql sequences
max_sql_length = max(len(sql) for sql in sql_tokens_list)
# Pad the sql sequences as needed
padded_sql_tokens = [
    sql + [tokenizer.pad_token_id] * (max_sql_length - len(sql)) if sql is not None else [tokenizer.pad_token_id] * max_sql_length
    for sql in sql_tokens_list
]
# print the sql sequences that are the maximum length
[print(sql) for sql in sql_tokens_list if len(sql) == max_sql_length]

# Convert the sql sequences to PyTorch tensors
sql_tokens = torch.tensor(padded_sql_tokens)

# Create a list of input sequences by tokenizing the text and adding special tokens
input_sequences = [tokenizer.encode(text, add_special_tokens=True) for text in text_list if text is not None]

# Filter out any None values from the input_sequences list
input_sequences = [[token for token in seq if token is not None] for seq in input_sequences]

# Pad the input sequences as needed
max_length = max(len(seq) for seq in input_sequences)
input_sequences = [
    seq + [tokenizer.pad_token_id] * (max_length - len(seq)) if seq is not None else [tokenizer.pad_token_id] * max_length
    for seq in input_sequences
]

# Convert the input sequences to PyTorch tensors
inputs = torch.tensor(input_sequences)

# Compute the sequence length for each input sequence
sequence_length = max_sql_length

# Load the dataset into PyTorch DataLoaders
batch_size = 32

# Split the data into training, validation, and test sets
train_size = int(0.8 * len(dataset))
val_size = int(0.1 * len(dataset))
test_size = len(dataset) - train_size - val_size

def collate_fn(data):
    input_data, target_data = zip(*data)
    input_batch = torch.stack(input_data, dim=0)
    target_batch = torch.stack(target_data, dim=0)
    return input_batch, target_batch

def pad_tensor(tensor, desired_length, padding_token=50256):
    current_length = tensor.shape[1]
    if current_length >= desired_length:
        return tensor
    padding = torch.full((tensor.shape[0], desired_length - current_length), padding_token, dtype=tensor.dtype)
    # move the padding to the same device as the tensor
    padding = padding.to(tensor.device)
    return torch.cat((tensor, padding), dim=1)

train_dataset = torch.utils.data.TensorDataset(inputs[:train_size], sql_tokens[:train_size])
val_dataset = torch.utils.data.TensorDataset(inputs[train_size:train_size+val_size], sql_tokens[train_size:train_size+val_size])
test_dataset = torch.utils.data.TensorDataset(inputs[train_size+val_size:], sql_tokens[train_size+val_size:])

train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True, collate_fn=collate_fn)
val_dataloader = torch.utils.data.DataLoader(val_dataset, batch_size=batch_size, shuffle=False)
test_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False)

# Define the model architecture and initialize the weights
model = GPTNeoForCausalLM.from_pretrained("EleutherAI/gpt-neo-125M")
# Add a linear layer on top of the model to generate logits for the sql tokens
print(model)
logits_layer = torch.nn.Linear(model.config.hidden_size, model.config.vocab_size)
model.add_module("logits", logits_layer)

# Transfer the model to the MPS device
model = model.to(device)

# Define the loss function and the optimizer
loss_fn = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters())

# Train the model
num_epochs = 10
for epoch in range(num_epochs):
  # Train the model for one epoch
  model.train()
  loss_val = 0
  # Epoch number started
  print(f"Epoch {epoch + 1} started")
  for input_tensor, target_tensor in train_dataloader:
    # Transfer the input and target tensors to the MPS device
    input_tensor = input_tensor.to(device)
    target_tensor = target_tensor.to(device)
    max_length = max(input_tensor.shape[1], target_tensor.shape[1])
    input_tensor = pad_tensor(input_tensor, max_length)
    target_tensor = pad_tensor(target_tensor, max_length)
    # Compute the logits and the loss
    logits = model(input_tensor, labels=target_tensor).logits
    # Get the shape of the logits tensor
    logits = logits.transpose(1, 2)
    # Calculate the loss
    loss = loss_fn(logits, target_tensor)    # Backpropagate the error and update
    loss_val += loss.item()
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    print(f"Loss: {loss_val / len(train_dataloader)}")
  # Validate the model
  model.eval()
  with torch.no_grad():
    val_loss = 0
    for input_tensor, target_tensor in val_dataloader:
      # Transfer the input and target tensors to the MPS device
      input_tensor = input_tensor.to(device)
      target_tensor = target_tensor.to(device)
      max_length = max(input_tensor.shape[1], target_tensor.shape[1])
      input_tensor = pad_tensor(input_tensor, max_length)
      target_tensor = pad_tensor(target_tensor, max_length)
      # Compute the logits and the loss
      logits = model(input_tensor, labels=target_tensor).logits
      logits = logits.transpose(1, 2)
      loss = loss_fn(logits, target_tensor)
      val_loss += loss.item()

    # Print the validation loss
    print(f"Validation loss: {val_loss / len(val_dataloader)}")

# Test the model
model.eval()
with torch.no_grad():
  test_loss = 0
  for input_tensor, target_tensor in test_dataloader:
   input_tensor = input_tensor.to(device)
   target_tensor = target_tensor.to(device)
   max_length = max(input_tensor.shape[1], target_tensor.shape[1])
   input_tensor = pad_tensor(input_tensor, max_length)
   target_tensor = pad_tensor(target_tensor, max_length)
    # Compute the logits and the loss
   logits = model(input_tensor, labels=target_tensor)
   logits.transpose(1, 2)
   loss = loss_fn(logits, target_tensor)
   test_loss += loss.item()

  # Print the test loss
  print(f"Test loss: {test_loss / len(test_dataloader)}")

</code>```

Body:
I'm trying to fine-tune GPT 125M params on WikiSql dataset, I'm sharing the code here as well.

I declared the batch size to be 32, and number of epochs is 10.

Unfortunately, I'm getting loss value is Inf, kindly help me to figure out what am I doing wrong?

And do I fine-tune the model properly?

The shape of each target_tensor and logits are :
Logits shape: torch.Size([32, 147, 50257])
Target shape: torch.Size([32, 147])

PSB the code that I ran to fine-tune GPT 125M:

import torch
from transformers import GPTNeoForCausalLM, GPT2Tokenizer
import pandas as pd
import transformers

# Check if MPS is available and built
print(torch.backends.mps.is_available())
print(torch.backends.mps.is_built())

# Set the device to MPS MacBook pro GPU
device = torch.device("mps")

# Load the dataset with pandas
dataset = pd.read_csv("wikisql/train.csv")

# Tokenize the text using the GPT-NeoX tokenizer
tokenizer = GPT2Tokenizer.from_pretrained("EleutherAI/gpt-neo-125M")
tokenizer.pad_token_id = 50256
# Get the text and sql columns from the dataset
print(tokenizer.pad_token_id)
text_list = dataset['question']
sql_list = dataset['sql']

# Convert the sql to a list of tokens
sql_tokens_list = [tokenizer.encode(sql, add_special_tokens=True) for sql in sql_list if sql is not None]

# Find the maximum length of the sql sequences
max_sql_length = max(len(sql) for sql in sql_tokens_list)
# Pad the sql sequences as needed
padded_sql_tokens = [
    sql + [tokenizer.pad_token_id] * (max_sql_length - len(sql)) if sql is not None else [tokenizer.pad_token_id] * max_sql_length
    for sql in sql_tokens_list
]
# print the sql sequences that are the maximum length
[print(sql) for sql in sql_tokens_list if len(sql) == max_sql_length]

# Convert the sql sequences to PyTorch tensors
sql_tokens = torch.tensor(padded_sql_tokens)

# Create a list of input sequences by tokenizing the text and adding special tokens
input_sequences = [tokenizer.encode(text, add_special_tokens=True) for text in text_list if text is not None]

# Filter out any None values from the input_sequences list
input_sequences = [[token for token in seq if token is not None] for seq in input_sequences]

# Pad the input sequences as needed
max_length = max(len(seq) for seq in input_sequences)
input_sequences = [
    seq + [tokenizer.pad_token_id] * (max_length - len(seq)) if seq is not None else [tokenizer.pad_token_id] * max_length
    for seq in input_sequences
]

# Convert the input sequences to PyTorch tensors
inputs = torch.tensor(input_sequences)

# Compute the sequence length for each input sequence
sequence_length = max_sql_length

# Load the dataset into PyTorch DataLoaders
batch_size = 32

# Split the data into training, validation, and test sets
train_size = int(0.8 * len(dataset))
val_size = int(0.1 * len(dataset))
test_size = len(dataset) - train_size - val_size

def collate_fn(data):
    input_data, target_data = zip(*data)
    input_batch = torch.stack(input_data, dim=0)
    target_batch = torch.stack(target_data, dim=0)
    return input_batch, target_batch

def pad_tensor(tensor, desired_length, padding_token=50256):
    current_length = tensor.shape[1]
    if current_length >= desired_length:
        return tensor
    padding = torch.full((tensor.shape[0], desired_length - current_length), padding_token, dtype=tensor.dtype)
    # move the padding to the same device as the tensor
    padding = padding.to(tensor.device)
    return torch.cat((tensor, padding), dim=1)

train_dataset = torch.utils.data.TensorDataset(inputs[:train_size], sql_tokens[:train_size])
val_dataset = torch.utils.data.TensorDataset(inputs[train_size:train_size+val_size], sql_tokens[train_size:train_size+val_size])
test_dataset = torch.utils.data.TensorDataset(inputs[train_size+val_size:], sql_tokens[train_size+val_size:])

train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True, collate_fn=collate_fn)
val_dataloader = torch.utils.data.DataLoader(val_dataset, batch_size=batch_size, shuffle=False)
test_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False)

# Define the model architecture and initialize the weights
model = GPTNeoForCausalLM.from_pretrained("EleutherAI/gpt-neo-125M")
# Add a linear layer on top of the model to generate logits for the sql tokens
print(model)
logits_layer = torch.nn.Linear(model.config.hidden_size, model.config.vocab_size)
model.add_module("logits", logits_layer)

# Transfer the model to the MPS device
model = model.to(device)

# Define the loss function and the optimizer
loss_fn = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters())

# Train the model
num_epochs = 10
for epoch in range(num_epochs):
  # Train the model for one epoch
  model.train()
  loss_val = 0
  # Epoch number started
  print(f"Epoch {epoch + 1} started")
  for input_tensor, target_tensor in train_dataloader:
    # Transfer the input and target tensors to the MPS device
    input_tensor = input_tensor.to(device)
    target_tensor = target_tensor.to(device)
    max_length = max(input_tensor.shape[1], target_tensor.shape[1])
    input_tensor = pad_tensor(input_tensor, max_length)
    target_tensor = pad_tensor(target_tensor, max_length)
    # Compute the logits and the loss
    logits = model(input_tensor, labels=target_tensor).logits
    # Get the shape of the logits tensor
    logits = logits.transpose(1, 2)
    # Calculate the loss
    loss = loss_fn(logits, target_tensor)    # Backpropagate the error and update
    loss_val += loss.item()
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    print(f"Loss: {loss_val / len(train_dataloader)}")
  # Validate the model
  model.eval()
  with torch.no_grad():
    val_loss = 0
    for input_tensor, target_tensor in val_dataloader:
      # Transfer the input and target tensors to the MPS device
      input_tensor = input_tensor.to(device)
      target_tensor = target_tensor.to(device)
      max_length = max(input_tensor.shape[1], target_tensor.shape[1])
      input_tensor = pad_tensor(input_tensor, max_length)
      target_tensor = pad_tensor(target_tensor, max_length)
      # Compute the logits and the loss
      logits = model(input_tensor, labels=target_tensor).logits
      logits = logits.transpose(1, 2)
      loss = loss_fn(logits, target_tensor)
      val_loss += loss.item()

    # Print the validation loss
    print(f"Validation loss: {val_loss / len(val_dataloader)}")

# Test the model
model.eval()
with torch.no_grad():
  test_loss = 0
  for input_tensor, target_tensor in test_dataloader:
   input_tensor = input_tensor.to(device)
   target_tensor = target_tensor.to(device)
   max_length = max(input_tensor.shape[1], target_tensor.shape[1])
   input_tensor = pad_tensor(input_tensor, max_length)
   target_tensor = pad_tensor(target_tensor, max_length)
    # Compute the logits and the loss
   logits = model(input_tensor, labels=target_tensor)
   logits.transpose(1, 2)
   loss = loss_fn(logits, target_tensor)
   test_loss += loss.item()

  # Print the test loss
  print(f"Test loss: {test_loss / len(test_dataloader)}")


问:
How to save plotly graph (python) and send by email?
I have a dataframe and I made a graph with the variables I need
I need the graphic to be in the email (html) I'm developing (not in a file)

```<code>a = fig.plot(df['example_1'], df['example_2'])
plt.xticks(rotation=45)
</code>```

Given the graph, I need to save it and put it in the email, and also use rotation to better visualize the data.

Save the graph and use rotation=45, get it sent by email.
I can't save the image. When I get it, the image in the email (html) is in error or blank.

Body:
I have a dataframe and I made a graph with the variables I need
I need the graphic to be in the email (html) I'm developing (not in a file)

a = fig.plot(df['example_1'], df['example_2'])
plt.xticks(rotation=45)

Given the graph, I need to save it and put it in the email, and also use rotation to better visualize the data.

Save the graph and use rotation=45, get it sent by email.
I can't save the image. When I get it, the image in the email (html) is in error or blank.


问:
Exception of type 'System.Exception' was thrown while creating 'winui' new project in visual studio
I open visual studio 2022 and click on create a new project. And then choose Blank page, Packaged(WinUI 3 in Desktop) and click next. I Enter the project name and set location for the project. When I click next, I got error "Exception of type 'System.Exception' was thrown."

System.Exception Error image


问:
How to use pgcrypto `crypt` function with Go's (*sql.Tx).Exec function?
I would like to be able to use the encryption provided by the PostgreSQL extension pgcrypto from within my go program. Consider this code snippet:

_, err = tx.Exec("INSERT INTO users (username, email, password) VALUES (?, ?, crypt(?, gen_salt('bf', 8)))", u.Username, u.Email, u.Password)
    if err != nil {
        fmt.Println("Could not create user in database:", err.Error())
        return err
    }
```
<p>I receive the following log message: <code>Could not create user in database: pq: syntax error at or near ","</code>.</p>
<p>When I manually execute this statement</p>
<pre class="lang-sql prettyprint-override"><code>INSERT INTO users(username, email, password) VALUES ('test', 'test@test.org', crypt('12345', gen_salt('bf', 8)));
</code>```

it successfully creates a row in the database.
How can I make the crypt function work from within Go?

Body:
I would like to be able to use the encryption provided by the PostgreSQL extension pgcrypto from within my go program. Consider this code snippet:

_, err = tx.Exec("INSERT INTO users (username, email, password) VALUES (?, ?, crypt(?, gen_salt('bf', 8)))", u.Username, u.Email, u.Password)
    if err != nil {
        fmt.Println("Could not create user in database:", err.Error())
        return err
    }

I receive the following log message: Could not create user in database: pq: syntax error at or near ",".

When I manually execute this statement

INSERT INTO users(username, email, password) VALUES ('test', 'test@test.org', crypt('12345', gen_salt('bf', 8)));

it successfully creates a row in the database.
How can I make the crypt function work from within Go?


问:
What is a clean way to write a localized FtpReply to an FtpSession in a Ftplet?
I would like to avoid hardcoding reply messages in a Ftplet, how can I call LocalizedFtpReply org.apache.ftpserver.impl.LocalizedFtpReply.translate(FtpIoSession session, FtpRequest request, FtpServerContext context, int code, String subId, String basicMsg) or equivalent, in a clean way?

```<code>public class NotifyFtplet extends DefaultFtplet {

    @Override
    public FtpletResult onUploadStart(FtpSession session, FtpRequest request) throws FtpException, IOException {
        session.write(new DefaultFtpReply(FtpReply.REPLY_150_FILE_STATUS_OKAY, "File status okay; about to open data connection."));
        return FtpletResult.SKIP;
    }

}
</code>```

Body:
I would like to avoid hardcoding reply messages in a Ftplet, how can I call LocalizedFtpReply org.apache.ftpserver.impl.LocalizedFtpReply.translate(FtpIoSession session, FtpRequest request, FtpServerContext context, int code, String subId, String basicMsg) or equivalent, in a clean way?

public class NotifyFtplet extends DefaultFtplet {

    @Override
    public FtpletResult onUploadStart(FtpSession session, FtpRequest request) throws FtpException, IOException {
        session.write(new DefaultFtpReply(FtpReply.REPLY_150_FILE_STATUS_OKAY, "File status okay; about to open data connection."));
        return FtpletResult.SKIP;
    }

}


问:
Generating and serving a PDF file with twisted
I would like to realize the following with twisted web:

The user clicks on a link on a page

This is bring the user to a temporary page where the user is informed that the PDF is generated

When the PDF generation is finished, the download starts automatically.

This is my example code:

from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.internet import reactor
from twisted.web.server import NOT_DONE_YET

class DownloadResource(Resource):
    isLeaf = True

    def render_GET(self, request: Resource):
        # Start generating the PDF file in the background
        reactor.callInThread(generate_pdf, request)
        request.write(b"Please wait while the PDF file is generated and download will start soon...")
        return NOT_DONE_YET

def generate_pdf(request: Resource):
    # Generate the PDF data
    # for the time being, just open it from the disk.
    # the real application will generate it.
    filename = r'/path/to/pdf'
    with open(filename, 'rb') as f:
        pdf_data = f.read()

    # Serve the PDF data
    request.setHeader(b"content-type", b"application/pdf")
    request.setHeader(b"content-length", str(len(pdf_data)).encode('utf-8'))
    request.write(pdf_data)
    request.finish()

resource = DownloadResource()
```

This works almost ok, the point is that the pdf data are written as bytes next to the text message. Something like this:
Please wait while the PDF file is generated and download will start soon...%PDF-1.4 %ª«¬ 1 0 obj << /Title....

Instead I would like the pdf file to be downloaded. Ideally I would need a kind of send_file. Does it exist?

Can you help me in solving this issue?

Body:
I would like to realize the following with twisted web:

The user clicks on a link on a page

This is bring the user to a temporary page where the user is informed that the PDF is generated

When the PDF generation is finished, the download starts automatically.

This is my example code:

from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.internet import reactor
from twisted.web.server import NOT_DONE_YET

class DownloadResource(Resource):
    isLeaf = True

    def render_GET(self, request: Resource):
        # Start generating the PDF file in the background
        reactor.callInThread(generate_pdf, request)
        request.write(b"Please wait while the PDF file is generated and download will start soon...")
        return NOT_DONE_YET

def generate_pdf(request: Resource):
    # Generate the PDF data
    # for the time being, just open it from the disk.
    # the real application will generate it.
    filename = r'/path/to/pdf'
    with open(filename, 'rb') as f:
        pdf_data = f.read()

    # Serve the PDF data
    request.setHeader(b"content-type", b"application/pdf")
    request.setHeader(b"content-length", str(len(pdf_data)).encode('utf-8'))
    request.write(pdf_data)
    request.finish()

resource = DownloadResource()

This works almost ok, the point is that the pdf data are written as bytes next to the text message. Something like this:
Please wait while the PDF file is generated and download will start soon...%PDF-1.4 %ª«¬ 1 0 obj << /Title....

Instead I would like the pdf file to be downloaded. Ideally I would need a kind of send_file. Does it exist?

Can you help me in solving this issue?


问:
Uncaught TypeError: Cannot access offset of type string on. When adding seconds to date variable
I have produced some code that requests a bearer token from an endpoint and adds a new key with a datetime value with seconds that get added to it. This code also produces a fatal error as in the title of this question on line 66:

```<code>function requestBearerToken()
{
    global $username, $password;
    $base_url = 'https://example-url.com/endpoint';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, ($base_url));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, 1);

    $headers = array(
        'Content-Type: application/json',
        'Authorization: Basic ' . base64_encode("$username:$password"),
    );
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    //$data = curl_exec($ch);
    curl_close($ch);
    $data['expires_on'][0] = date("d-m-Y H:i:s", (time() + 580));
    file_put_contents("bearer.json", $data);
    $pre_result = json_decode($data, true);
    $token = $pre_result;
    print_r($token);
}
</code>```

The reponse body, $data, is as follow:

```<code>{
  "access_token": "<access_token>",
  "token_type": "Bearer",
  "expires_in": 299,
  "scope": "<scopes>"
}
</code>```

Body:
I have produced some code that requests a bearer token from an endpoint and adds a new key with a datetime value with seconds that get added to it. This code also produces a fatal error as in the title of this question on line 66:

function requestBearerToken()
{
    global $username, $password;
    $base_url = 'https://example-url.com/endpoint';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, ($base_url));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, 1);

    $headers = array(
        'Content-Type: application/json',
        'Authorization: Basic ' . base64_encode("$username:$password"),
    );
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    //$data = curl_exec($ch);
    curl_close($ch);
    $data['expires_on'][0] = date("d-m-Y H:i:s", (time() + 580));
    file_put_contents("bearer.json", $data);
    $pre_result = json_decode($data, true);
    $token = $pre_result;
    print_r($token);
}

The reponse body, $data, is as follow:

{
  "access_token": "<access_token>",
  "token_type": "Bearer",
  "expires_in": 299,
  "scope": "<scopes>"
}


问:
unity network variabe occasional writing permission error
I am new to unity netcode and I am trying to implement a grabbing/dropping mechanism for a 3rd person game.

But my network variable occasionally throws a confusing error out at the host side when client side "drop" something:

[Netcode] Client wrote to NetworkVariable`1 without permission. No more variables can be read. This is critical. => NetworkObjectId: 5 - GetNetworkBehaviourOrderIndex(): 1 - VariableIndex: 0

Sometimes it throws 1 of this error, sometimes it throws 2 and in rare case it doesn't throw error at all.

What is the possible reason for this?

Basically my approach is:
(below using clientNetworkTransform)
Grab:

calling grabServerRpc( callerClientId ) in the Grabbable object by the local player

passing the ownership of the Grabbable setting the network variable grabbedClientId to callerClientId in grabServerRpc()

in the OnValueChange delegate for every player, check if LocalPlayerId == grabbedClientId

if equal, set the local targetTransform to the grabbing point of the player and serval more properties to complete the grab
(the OnValueChange also check if grabbedClientId == Default value before doing anything to prevent execution due to dropServerRpc())

Drop:

unset the properties to drop it.

call the dropServerRpc() in the Grabbable

removeOwnership() in the dropServerRpc()

restore the grabbedClientId to default value to complete the drop

    public void grab(ulong grabbedClientId){
        this.grabServerRpc(grabbedClientId);
    }
    [ServerRpc(RequireOwnership = false)]
    private void grabServerRpc(ulong grabClientId){
        if (this.grabbedClientId != TPNetworkGrabbable.GRABBED_CLIENT_DEFAULT) return;

        this.networkObject.ChangeOwnership(grabClientId);
        this.grabbedClientId = grabClientId;
        print("grabbed");
        return;
    }
    private void OnGrab(ulong previous, ulong current){ // OnValueChange for grabbedClientId
        if (this.grabbedClientId == TPNetworkGrabbable.GRABBED_CLIENT_DEFAULT) return; // prevent calling due to changes in drop()
        if (this.grabbedClientId != NetworkManager.LocalClientId) return;

        TPNetworkGrabbingControl grabbingControl = NetworkManager.LocalClient.PlayerObject.GetComponent<TPNetworkGrabbingControl>();
       this._targetTransform = grabbingControl.grabPosition;
        this.rigidbody.useGravity = false;
        this.transform.rotation = Quaternion.Euler(0, 0, 0);
        this.rigidbody.freezeRotation = true;
    }

    public void drop(){
        if (this.grabbedClientId != NetworkManager.LocalClientId) return;
        if (this.grabbedClientId == TPNetworkGrabbable.GRABBED_CLIENT_DEFAULT) return;

        this._targetTransform = null;
        this.rigidbody.useGravity = true;
        this.rigidbody.freezeRotation = false;
        this.dropServerRpc();
    }
    [ServerRpc(RequireOwnership = false)]
    private void dropServerRpc(){
        this.networkObject.RemoveOwnership();
        this.grabbedClientId = TPNetworkGrabbable.GRABBED_CLIENT_DEFAULT;
        print("dropped");
    }
```

what I have done:

global searched my project and every single modification to any network variable are already done in [ServerRpc] and they are server write authoritive by default.

Googled and found basically nothing related to this specific error, except this:
though the solution seems to not apply to my case and the example does not exist anymore.

Body:
I am new to unity netcode and I am trying to implement a grabbing/dropping mechanism for a 3rd person game.

But my network variable occasionally throws a confusing error out at the host side when client side "drop" something:

[Netcode] Client wrote to NetworkVariable`1 without permission. No more variables can be read. This is critical. => NetworkObjectId: 5 - GetNetworkBehaviourOrderIndex(): 1 - VariableIndex: 0

Sometimes it throws 1 of this error, sometimes it throws 2 and in rare case it doesn't throw error at all.

What is the possible reason for this?

Basically my approach is:
(below using clientNetworkTransform)
Grab:

calling grabServerRpc( callerClientId ) in the Grabbable object by the local player

passing the ownership of the Grabbable setting the network variable grabbedClientId to callerClientId in grabServerRpc()

in the OnValueChange delegate for every player, check if LocalPlayerId == grabbedClientId

if equal, set the local targetTransform to the grabbing point of the player and serval more properties to complete the grab
(the OnValueChange also check if grabbedClientId == Default value before doing anything to prevent execution due to dropServerRpc())

Drop:

unset the properties to drop it.

call the dropServerRpc() in the Grabbable

removeOwnership() in the dropServerRpc()

restore the grabbedClientId to default value to complete the drop

    public void grab(ulong grabbedClientId){
        this.grabServerRpc(grabbedClientId);
    }
    [ServerRpc(RequireOwnership = false)]
    private void grabServerRpc(ulong grabClientId){
        if (this.grabbedClientId != TPNetworkGrabbable.GRABBED_CLIENT_DEFAULT) return;

        this.networkObject.ChangeOwnership(grabClientId);
        this.grabbedClientId = grabClientId;
        print("grabbed");
        return;
    }
    private void OnGrab(ulong previous, ulong current){ // OnValueChange for grabbedClientId
        if (this.grabbedClientId == TPNetworkGrabbable.GRABBED_CLIENT_DEFAULT) return; // prevent calling due to changes in drop()
        if (this.grabbedClientId != NetworkManager.LocalClientId) return;

        TPNetworkGrabbingControl grabbingControl = NetworkManager.LocalClient.PlayerObject.GetComponent<TPNetworkGrabbingControl>();
       this._targetTransform = grabbingControl.grabPosition;
        this.rigidbody.useGravity = false;
        this.transform.rotation = Quaternion.Euler(0, 0, 0);
        this.rigidbody.freezeRotation = true;
    }

    public void drop(){
        if (this.grabbedClientId != NetworkManager.LocalClientId) return;
        if (this.grabbedClientId == TPNetworkGrabbable.GRABBED_CLIENT_DEFAULT) return;

        this._targetTransform = null;
        this.rigidbody.useGravity = true;
        this.rigidbody.freezeRotation = false;
        this.dropServerRpc();
    }
    [ServerRpc(RequireOwnership = false)]
    private void dropServerRpc(){
        this.networkObject.RemoveOwnership();
        this.grabbedClientId = TPNetworkGrabbable.GRABBED_CLIENT_DEFAULT;
        print("dropped");
    }

what I have done:

global searched my project and every single modification to any network variable are already done in [ServerRpc] and they are server write authoritive by default.

Googled and found basically nothing related to this specific error, except this:
though the solution seems to not apply to my case and the example does not exist anymore.


问:
Querying OpenAI Gym Simulator
How can I use OpenAI's Gym environments "step" function or something equivalent without actually "stepping" the environment?

I just want to know what is the next state given current state and action but not to actually do the "step".

Title: Querying OpenAI Gym Simulator


问:
What is "delta" in R function power.t.test() and how i can get it?
I need to get the minimum amount of data in each group needed for some power and significance levels. I have two samples(quantitative,continuous) of different sizes.

I find function power.t.test() in R, but i don't understand what is "delta" parameter. In documentation:

delta: true difference in means

But what does this mean? abs(mean(sample_1) - mean(sample_2))?


问:
How get number of numeric strings and sum of numbers from list
How do I get number of numeric strings and sum of numbers from list TEXTS.
Outputs are:
There are 3 numeric strings.
The sum of all the numbers 8510

TEXTS = [Situated about 10 miles west of Kemmerer, Fossil Butte is a ruggedly impressive topographic feature that rises sharply some 1000 feet above Twin Creek Valley to an elevation of more than 7500 feet above sea level. The butte is located just north of US and the Union Pacific Railroad, which traverse the valley.]

Thank you

```<code>count = 0
for cisla in TEXTS.split():
    if cisla.isdigit():
        count += 1
        print("There are", count, "numeric strings.")
There are 1 numeric strings.
There are 2 numeric strings.
There are 3 numeric strings.
</code>```

I need only last loop with number 3, or if there is better way? No idea with sum of numbers.

Body:
How do I get number of numeric strings and sum of numbers from list TEXTS.
Outputs are:
There are 3 numeric strings.
The sum of all the numbers 8510

TEXTS = [Situated about 10 miles west of Kemmerer, Fossil Butte is a ruggedly impressive topographic feature that rises sharply some 1000 feet above Twin Creek Valley to an elevation of more than 7500 feet above sea level. The butte is located just north of US and the Union Pacific Railroad, which traverse the valley.]

Thank you

count = 0
for cisla in TEXTS.split():
    if cisla.isdigit():
        count += 1
        print("There are", count, "numeric strings.")
There are 1 numeric strings.
There are 2 numeric strings.
There are 3 numeric strings.

I need only last loop with number 3, or if there is better way? No idea with sum of numbers.


问:
How to include a struct with a named lifetime inside a struct without a named lifetime?
I'm trying to include apache_avro::Writer inside a struct I define. My struct implements multiple traits, and those methods mutate the struct. You can think of the traits as event handlers and my struct is intended to log the events to avro.

Ideally, I'd like the lifetime of the Writer contained in my struct to match the lifetime of my struct, but I can't use '_ in the definition. I also tried adding a named lifetime to MyStruct, but run into issues because then I think I need to add that to all the traits MyStruct implements to ensure that all the &mut self references have the same right lifetime.

Here's a minimal playground example

```<code>pub struct Writer<'a, W> {
    bar: &'a u64,
}

use std::fs::File;

trait TraitMyStructNeedsToImplement {
    fn foo(&mut self);
}

struct MyStruct {
    writer: Writer<'_, File>,
}

impl TraitMyStructNeedsToImplement for MyStruct {
    fn foo(&mut self) {
        todo!();
    }
}
</code>```

Body:
I'm trying to include apache_avro::Writer inside a struct I define. My struct implements multiple traits, and those methods mutate the struct. You can think of the traits as event handlers and my struct is intended to log the events to avro.

Ideally, I'd like the lifetime of the Writer contained in my struct to match the lifetime of my struct, but I can't use '_ in the definition. I also tried adding a named lifetime to MyStruct, but run into issues because then I think I need to add that to all the traits MyStruct implements to ensure that all the &mut self references have the same right lifetime.

Here's a minimal playground example

pub struct Writer<'a, W> {
    bar: &'a u64,
}

use std::fs::File;

trait TraitMyStructNeedsToImplement {
    fn foo(&mut self);
}

struct MyStruct {
    writer: Writer<'_, File>,
}

impl TraitMyStructNeedsToImplement for MyStruct {
    fn foo(&mut self) {
        todo!();
    }
}


问:
Group a dataset based on values in two columns and create a new dynamic DataFrame columns by that groups
I have taken the Years and Crime Type columns out of a huge dataset, and I want to group that dataset in a specific manner.

It has 6 different Crime Types and years from 2017 to 2021

I need to group those years, and the count of each crime type for that year should be in the stack as follows:

All available types:

Current dataset:

I tried the following code:

```<code>initialMainCrimes = crimeDataWithoutNotCrimes[["year", "Crime Name2"]]
mainCrimes = initialMainCrimes.rename(columns={'Crime Name2':'Crime Type'})

yearsSet = mainCrimes.groupby('year').size()

#Create columns
cType = mainCrimes.groupby('Crime Type').size().sort_values(ascending = False)
cType = cType.iloc[1:][:6]
columns = np.array(cType.index)
columns = np.insert(columns, 0, "Year")
columns = list(map(str, columns))

dfa = mainCrimes.groupby(['year', 'Crime Type']).size()

dfn = pnd.DataFrame([["2018", 55, 90, 90, 50, 65, 33]],
                  columns=columns)

dfn.plot(x="Year",
        kind='bar',
        stacked=False,
        title='Grouped Bar Graph with dataframe')
</code>```

My final desired output will be a plot based on the count of types by year:

Body:
I have taken the Years and Crime Type columns out of a huge dataset, and I want to group that dataset in a specific manner.

It has 6 different Crime Types and years from 2017 to 2021

I need to group those years, and the count of each crime type for that year should be in the stack as follows:

All available types:

Current dataset:

I tried the following code:

initialMainCrimes = crimeDataWithoutNotCrimes[["year", "Crime Name2"]]
mainCrimes = initialMainCrimes.rename(columns={'Crime Name2':'Crime Type'})

yearsSet = mainCrimes.groupby('year').size()

#Create columns
cType = mainCrimes.groupby('Crime Type').size().sort_values(ascending = False)
cType = cType.iloc[1:][:6]
columns = np.array(cType.index)
columns = np.insert(columns, 0, "Year")
columns = list(map(str, columns))

dfa = mainCrimes.groupby(['year', 'Crime Type']).size()

dfn = pnd.DataFrame([["2018", 55, 90, 90, 50, 65, 33]],
                  columns=columns)

dfn.plot(x="Year",
        kind='bar',
        stacked=False,
        title='Grouped Bar Graph with dataframe')

My final desired output will be a plot based on the count of types by year:


问:
How to show an error message inside JDesktop pane on top of internalframe
i want to display error massages inside the jdesktop pane in java
i have not done anything yet and am a beginner sorry for the broken English

i tried using JDialog but comes up on top of everything thisnthe code am using to call the JDialog

```<code>private  boolean showAdmin_T() {
        admin_priv obj = new admin_priv(fram, true);
        fram.getRootPane().getGlassPane().setVisible(true);
        obj.showMessage();
        return obj.isOk();
    }
</code>```

i created a separate JDialog but it only opens outside the JDesktop pane
here is the code for the Jdialog

```<code>package com.mutale.posapplication.dialogs;

import com.mutale.posapplication.scroll.ScrollBarCustom;
import com.mutale.posapplication.swing.icons.GoogleMaterialDesignIcons;
import com.mutale.posapplication.swing.icons.IconFontSwing;
import java.awt.Color;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import org.jdesktop.animation.timing.Animator;
import org.jdesktop.animation.timing.TimingTarget;
import org.jdesktop.animation.timing.TimingTargetAdapter;
public class error_disply extends javax.swing.JDialog {
    private String icon;
    public boolean isOk() {
        return ok;
    }
    public void setOk(boolean ok) {
        this.ok = ok;
    }
    private boolean ok;
    private final Animator animator;
    private boolean show = true;
    public error_disply(java.awt.Frame parent, boolean modal,String icon1) {
        super(parent, modal);
        initComponents();
        icon = "1";
        panel(error_ScrollPane);
        lbMessage.setLineWrap(true);
        lbMessage.setWrapStyleWord(true);
        setOpacity(0f);
        if(icon.equals(icon1)){      lbIcon.setIcon(IconFontSwing.buildIcon(GoogleMaterialDesignIcons.STORAGE, 60, new Color(254, 86, 96), new Color(113, 74, 67)));
        }else{
            lbIcon.setIcon(IconFontSwing.buildIcon(GoogleMaterialDesignIcons.REPORT_PROBLEM, 40, new Color(254, 86, 96), new Color(113, 74, 67)));
        }
       getContentPane().setBackground(Color.WHITE);
       TimingTarget target = new TimingTargetAdapter() {
            @Override
            public void timingEvent(float fraction) {
                if (show) {
                    setOpacity(fraction);
                } else {
                    setOpacity(1f - fraction);
                }
            }
            @Override
            public void end() {
                if (show == false) {
                    setVisible(false);
                }
            }
        };
        animator = new Animator(200, target);
        animator.setResolution(0);
        animator.setAcceleration(0.5f);
    }
    public void showMessage(String message) {
        lbMessage.setText(message);
        animator.start();
        setVisible(true);
    }
    public final void panel(JScrollPane scroll) {
        scroll.getViewport().setBackground(Color.WHITE);
        scroll.setVerticalScrollBar(new ScrollBarCustom());
        JPanel p = new JPanel();
        p.setBackground(Color.WHITE);
        scroll.setCorner(JScrollPane.UPPER_RIGHT_CORNER, p);
        scroll.setBorder(new EmptyBorder(0, 0, 0, 0));
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        lbIcon = new javax.swing.JLabel();
        cancele = new com.mutale.posapplication.swings.Button();
        error_ScrollPane = new javax.swing.JScrollPane();
        lbMessage = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setUndecorated(true);
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 0, 0), 2));    lbIcon.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        cancele.setBackground(new java.awt.Color(202, 5, 5));
        cancele.setText("X");
        cancele.setToolTipText("close");
        cancele.setColorGradient(new java.awt.Color(202, 5, 5));
        cancele.setEnabled(false);
        cancele.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        cancele.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                canceleMousePressed(evt);
            }
        });
        lbMessage.setEditable(false);
        lbMessage.setColumns(3);
        lbMessage.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
        lbMessage.setRows(4);
        lbMessage.setAutoscrolls(false);
        lbMessage.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        error_ScrollPane.setViewportView(lbMessage);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(lbIcon, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(cancele, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addComponent(error_ScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 540, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(cancele, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lbIcon, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(1, 1, 1)
                .addComponent(error_ScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 331, Short.MAX_VALUE))
        );    cancele.getAccessibleContext().setAccessibleParent(cancele);
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(       layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>
    private void canceleMousePressed(java.awt.event.MouseEvent evt) {
        ok = true;
        closeMenu();
    }
    private void closeMenu() {
        if (animator.isRunning()) {
            animator.stop();
        }
        show = false;
        animator.start();
    }
    // Variables declaration - do not modify
    private com.mutale.posapplication.swings.Button cancele;
    private javax.swing.JScrollPane error_ScrollPane;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lbIcon;
    private javax.swing.JTextArea lbMessage;
    // End of variables declaration
}
</code>```

Body:
i want to display error massages inside the jdesktop pane in java
i have not done anything yet and am a beginner sorry for the broken English

i tried using JDialog but comes up on top of everything thisnthe code am using to call the JDialog

private  boolean showAdmin_T() {
        admin_priv obj = new admin_priv(fram, true);
        fram.getRootPane().getGlassPane().setVisible(true);
        obj.showMessage();
        return obj.isOk();
    }

i created a separate JDialog but it only opens outside the JDesktop pane
here is the code for the Jdialog

package com.mutale.posapplication.dialogs;

import com.mutale.posapplication.scroll.ScrollBarCustom;
import com.mutale.posapplication.swing.icons.GoogleMaterialDesignIcons;
import com.mutale.posapplication.swing.icons.IconFontSwing;
import java.awt.Color;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import org.jdesktop.animation.timing.Animator;
import org.jdesktop.animation.timing.TimingTarget;
import org.jdesktop.animation.timing.TimingTargetAdapter;
public class error_disply extends javax.swing.JDialog {
    private String icon;
    public boolean isOk() {
        return ok;
    }
    public void setOk(boolean ok) {
        this.ok = ok;
    }
    private boolean ok;
    private final Animator animator;
    private boolean show = true;
    public error_disply(java.awt.Frame parent, boolean modal,String icon1) {
        super(parent, modal);
        initComponents();
        icon = "1";
        panel(error_ScrollPane);
        lbMessage.setLineWrap(true);
        lbMessage.setWrapStyleWord(true);
        setOpacity(0f);
        if(icon.equals(icon1)){      lbIcon.setIcon(IconFontSwing.buildIcon(GoogleMaterialDesignIcons.STORAGE, 60, new Color(254, 86, 96), new Color(113, 74, 67)));
        }else{
            lbIcon.setIcon(IconFontSwing.buildIcon(GoogleMaterialDesignIcons.REPORT_PROBLEM, 40, new Color(254, 86, 96), new Color(113, 74, 67)));
        }
       getContentPane().setBackground(Color.WHITE);
       TimingTarget target = new TimingTargetAdapter() {
            @Override
            public void timingEvent(float fraction) {
                if (show) {
                    setOpacity(fraction);
                } else {
                    setOpacity(1f - fraction);
                }
            }
            @Override
            public void end() {
                if (show == false) {
                    setVisible(false);
                }
            }
        };
        animator = new Animator(200, target);
        animator.setResolution(0);
        animator.setAcceleration(0.5f);
    }
    public void showMessage(String message) {
        lbMessage.setText(message);
        animator.start();
        setVisible(true);
    }
    public final void panel(JScrollPane scroll) {
        scroll.getViewport().setBackground(Color.WHITE);
        scroll.setVerticalScrollBar(new ScrollBarCustom());
        JPanel p = new JPanel();
        p.setBackground(Color.WHITE);
        scroll.setCorner(JScrollPane.UPPER_RIGHT_CORNER, p);
        scroll.setBorder(new EmptyBorder(0, 0, 0, 0));
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        lbIcon = new javax.swing.JLabel();
        cancele = new com.mutale.posapplication.swings.Button();
        error_ScrollPane = new javax.swing.JScrollPane();
        lbMessage = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setUndecorated(true);
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 0, 0), 2));    lbIcon.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        cancele.setBackground(new java.awt.Color(202, 5, 5));
        cancele.setText("X");
        cancele.setToolTipText("close");
        cancele.setColorGradient(new java.awt.Color(202, 5, 5));
        cancele.setEnabled(false);
        cancele.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        cancele.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                canceleMousePressed(evt);
            }
        });
        lbMessage.setEditable(false);
        lbMessage.setColumns(3);
        lbMessage.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
        lbMessage.setRows(4);
        lbMessage.setAutoscrolls(false);
        lbMessage.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        error_ScrollPane.setViewportView(lbMessage);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(lbIcon, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(cancele, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addComponent(error_ScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 540, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(cancele, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lbIcon, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(1, 1, 1)
                .addComponent(error_ScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 331, Short.MAX_VALUE))
        );    cancele.getAccessibleContext().setAccessibleParent(cancele);
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(       layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>
    private void canceleMousePressed(java.awt.event.MouseEvent evt) {
        ok = true;
        closeMenu();
    }
    private void closeMenu() {
        if (animator.isRunning()) {
            animator.stop();
        }
        show = false;
        animator.start();
    }
    // Variables declaration - do not modify
    private com.mutale.posapplication.swings.Button cancele;
    private javax.swing.JScrollPane error_ScrollPane;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lbIcon;
    private javax.swing.JTextArea lbMessage;
    // End of variables declaration
}


问:
What are the features that sklearn.decomposition.PCA identifies?
The code runs and finds 2 components, but how do those components map back to the original feature names in the dataset?

```<code>import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
irisDF = pd.read_csv(url, names=['sepal length','sepal width','petal length','petal width','target'])
features = ['sepal length', 'sepal width', 'petal length', 'petal width']

x = irisDF.loc[:, features].values
y = irisDF.loc[:,['target']].values
x = StandardScaler().fit_transform(x)
pca = PCA(n_components=2)
principalComponents = pca.fit_transform(x)
#print("principal components", principalComponents)  # Too much data
principalDF = pd.DataFrame(data = principalComponents, columns = ['principal component 1', 'principal component 2'])
print(pca.explained_variance_ratio_)
</code>```

Output:

```<code>[0.72770452 0.23030523]
</code>```

Body:
The code runs and finds 2 components, but how do those components map back to the original feature names in the dataset?

import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
irisDF = pd.read_csv(url, names=['sepal length','sepal width','petal length','petal width','target'])
features = ['sepal length', 'sepal width', 'petal length', 'petal width']

x = irisDF.loc[:, features].values
y = irisDF.loc[:,['target']].values
x = StandardScaler().fit_transform(x)
pca = PCA(n_components=2)
principalComponents = pca.fit_transform(x)
#print("principal components", principalComponents)  # Too much data
principalDF = pd.DataFrame(data = principalComponents, columns = ['principal component 1', 'principal component 2'])
print(pca.explained_variance_ratio_)

Output:

[0.72770452 0.23030523]


问:
How to put text based on y axis value (in stead of 0,0 to 1,1 co-ordinate system) in matplotlib
I want to put a text slightly above a horizontal line, the value of y where is variable, not a constant in a matplotlib figure. My current code is following:

```<code>fig, host = plt.subplots(figsize=(18,6))
plt.axhline(y = *a variable between 0-100*, color='r')
plt.text(*x-cord*, *y-cord* , '*Desired Text*', verticalalignment='bottom', horizontalalignment='right', transform=host.transAxes, color='red', fontsize=14)
</code>```

However, the position of the text depends on x-coord, y-coord. As my horizontal line is a variable, every time I have to manually adjust the text position, which is not optimal for me to automate the figure creation.

Body:
I want to put a text slightly above a horizontal line, the value of y where is variable, not a constant in a matplotlib figure. My current code is following:

fig, host = plt.subplots(figsize=(18,6))
plt.axhline(y = *a variable between 0-100*, color='r')
plt.text(*x-cord*, *y-cord* , '*Desired Text*', verticalalignment='bottom', horizontalalignment='right', transform=host.transAxes, color='red', fontsize=14)

However, the position of the text depends on x-coord, y-coord. As my horizontal line is a variable, every time I have to manually adjust the text position, which is not optimal for me to automate the figure creation.


问:
How to write {% url ' ' %} for 2 and more slug arguments?
I try to generate url for "go to next url" but when i use {% url tuman_url 'iib:mahalla' i.slug %} i get error:

Reverse for 'mahalla' with arguments '(<Tuman: Sharof Rashidov Tumani>, 'ulugbek')' not found. 1 pattern(s) tried: ['(?P<tuman_slug>[-a-zA-Z0-9_]+)/mahalla/(?P<mahalla_slug>[-a-zA-Z0-9_]+)\Z']

urls.py

```<code>path('statistika/<slug:tuman_slug>/', show_one_stata, name='tuman_stata'),
path('<slug:tuman_slug>/mahalla/<slug:mahalla_slug>', show_one_mahalla, name='mahalla'),

</code>```

views.py

```<code>def show_one_stata (request,tuman_slug:str):
    tuman_url = get_object_or_404(Tuman, slug=tuman_slug)
    tuman = Tuman.objects.all()
    citizen = Citizen.objects.all()
    category = Category.objects.all()
    mahalla = Mahalla.objects.

    context = {
        'citizen' : citizen,
        'category' : category,
        'mahalla' : mahalla,
        'tuman' : tuman,
        'tuman_url' : tuman_url,

    return render(request, 'main/one_stata.html',context)

def show_one_mahalla(request, mahalla_slug:str,tuman_slug:str) :
    citizen = Citizen.objects.all()
    nizo = Category.objects.all()
    mahalla_for = get_object_or_404(Mahalla, slug=mahalla_slug)
    tuman_url = get_object_or_404(Tuman, slug=mahalla_slug)

    context = {
        'citizen':citizen,
        'nizo':nizo,
        'mahalla_for':mahalla_for,
        'tuman_url':tuman_url,

        }
    return render(request, 'main/one_mahalla.html',context)

</code>```

my html

```<code>    {% for i in mahalla %}
    {% if i.tum == tuman_url %}
    <tr>
        <td style="font-weight: bold;"><a href="{% url tuman_url 'iib:mahalla' i.slug %}" style="text-decoration:none; color:black;">{{ i.name }}</a></td>
   <tr>
    {% endif %}
    {% endfor %}

</code>```

models.py

```<code>class Tuman(models.Model):
    name = models.CharField(max_length=100, db_index=True, verbose_name="Tuman")
    slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL")

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('iib:tuman', kwargs={'tuman_slug': self.pk})

    class Meta:
        verbose_name = 'Tumanlar'
        verbose_name_plural = 'Tumanlar'

class Mahalla(models.Model):
    name = models.CharField(max_length=100, db_index=True, verbose_name="Mahallaning nomi")
    slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL")
    tum = models.ForeignKey('Tuman',on_delete=models.PROTECT,null=True,blank=True, verbose_name= "Tuman")

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('iib:mahalla', kwargs={'mahalla_slug': self.pk})

    class Meta:
        verbose_name = 'Mahalla'
        verbose_name_plural = 'Mahallalar'
</code>```

Body:
I try to generate url for "go to next url" but when i use {% url tuman_url 'iib:mahalla' i.slug %} i get error:

Reverse for 'mahalla' with arguments '(<Tuman: Sharof Rashidov Tumani>, 'ulugbek')' not found. 1 pattern(s) tried: ['(?P<tuman_slug>[-a-zA-Z0-9_]+)/mahalla/(?P<mahalla_slug>[-a-zA-Z0-9_]+)\Z']

urls.py

path('statistika/<slug:tuman_slug>/', show_one_stata, name='tuman_stata'),
path('<slug:tuman_slug>/mahalla/<slug:mahalla_slug>', show_one_mahalla, name='mahalla'),

views.py

def show_one_stata (request,tuman_slug:str):
    tuman_url = get_object_or_404(Tuman, slug=tuman_slug)
    tuman = Tuman.objects.all()
    citizen = Citizen.objects.all()
    category = Category.objects.all()
    mahalla = Mahalla.objects.

    context = {
        'citizen' : citizen,
        'category' : category,
        'mahalla' : mahalla,
        'tuman' : tuman,
        'tuman_url' : tuman_url,

    return render(request, 'main/one_stata.html',context)

def show_one_mahalla(request, mahalla_slug:str,tuman_slug:str) :
    citizen = Citizen.objects.all()
    nizo = Category.objects.all()
    mahalla_for = get_object_or_404(Mahalla, slug=mahalla_slug)
    tuman_url = get_object_or_404(Tuman, slug=mahalla_slug)

    context = {
        'citizen':citizen,
        'nizo':nizo,
        'mahalla_for':mahalla_for,
        'tuman_url':tuman_url,

        }
    return render(request, 'main/one_mahalla.html',context)

my html

    {% for i in mahalla %}
    {% if i.tum == tuman_url %}

        {{ i.name }}

    {% endif %}
    {% endfor %}

models.py

class Tuman(models.Model):
    name = models.CharField(max_length=100, db_index=True, verbose_name="Tuman")
    slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL")

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('iib:tuman', kwargs={'tuman_slug': self.pk})

    class Meta:
        verbose_name = 'Tumanlar'
        verbose_name_plural = 'Tumanlar'

class Mahalla(models.Model):
    name = models.CharField(max_length=100, db_index=True, verbose_name="Mahallaning nomi")
    slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL")
    tum = models.ForeignKey('Tuman',on_delete=models.PROTECT,null=True,blank=True, verbose_name= "Tuman")

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('iib:mahalla', kwargs={'mahalla_slug': self.pk})

    class Meta:
        verbose_name = 'Mahalla'
        verbose_name_plural = 'Mahallalar'


问:
RemoveEventListener not working when queryselectorall is used to access an element in javascript
I'm making tic tac toe and all the 9 squares in the game have the same class 'box'.

```<code>const box = document.querySelectorAll(".box");

box.forEach((element) => {
  element.addEventListener('click', ()=>{
    insertMark(element);
  });
});

function insertMark(event) {
  if (player === 1) {
    event.innerHTML = "X";
    player = 2;
  } else if (player === 2) {
    event.innerHTML = "O";
    player = 1;
  }
  event.classList.add("boxInsert");
  event.removeEventListener("click", insertMark);
}
</code>```

The eventListener works fine to insert a mark on the box, but I can't seem to remove the eventListener. What am I doing wrong?

Body:
I'm making tic tac toe and all the 9 squares in the game have the same class 'box'.

const box = document.querySelectorAll(".box");

box.forEach((element) => {
  element.addEventListener('click', ()=>{
    insertMark(element);
  });
});

function insertMark(event) {
  if (player === 1) {
    event.innerHTML = "X";
    player = 2;
  } else if (player === 2) {
    event.innerHTML = "O";
    player = 1;
  }
  event.classList.add("boxInsert");
  event.removeEventListener("click", insertMark);
}

The eventListener works fine to insert a mark on the box, but I can't seem to remove the eventListener. What am I doing wrong?


问:
xcode build error on unity asset Expected identifier or '('
why i'm getting this error when i try build to device or simulator with xcode?

Classes/PluginBase/UnityViewControllerListener.h:44:8 Expected identifier or '('

Thank you.

asset link:
https://assetstore.unity.com/packages/tools/integration/device-map-25179#releases

i just imported package and build ios version,build successful but got error on xcode build step.


问:
Inject data by dynamic token
I have 2 components:

```<code>class ComponentView {
  @Input() key!: string;
  @Input() data!: string;
}
class ComponentSettings {
  @Input() key!: string;
}
</code>```

They are instanciated in different places using dynamic component creation technique.

ComponentView has data object which I want to share to ComponentSettings via DI. Important to use key prop to make sure that connected instances by the key uses proper shared value.

How I see this solution, but it wan't work:

```<code>class ComponentView {
  @Input() key!: string;
  @Input() data!: string;

  ngOnInit() {
    Injector.create({ providers: [{ provide: this.key, useValue: this.data }]})
  }
}
class ComponentSettings {
  @Input() key!: string;

  constructor(private injector: Injector) {}

  ngOnInit() {
    const data = this.injector.get(this.key);
  }
}
</code>```

Title: Inject data by dynamic token

Body:
I have 2 components:

class ComponentView {
  @Input() key!: string;
  @Input() data!: string;
}
class ComponentSettings {
  @Input() key!: string;
}

They are instanciated in different places using dynamic component creation technique.

ComponentView has data object which I want to share to ComponentSettings via DI. Important to use key prop to make sure that connected instances by the key uses proper shared value.

How I see this solution, but it wan't work:

class ComponentView {
  @Input() key!: string;
  @Input() data!: string;

  ngOnInit() {
    Injector.create({ providers: [{ provide: this.key, useValue: this.data }]})
  }
}
class ComponentSettings {
  @Input() key!: string;

  constructor(private injector: Injector) {}

  ngOnInit() {
    const data = this.injector.get(this.key);
  }
}


问:
Can you define custom observables in ipywidget components?
With default widgets, such as sliders, it is possible to observe the value or other traits so that any changes trigger a given function (see here):

w_slider = widgets.IntSlider()
w_output = widgets.Output()

def on_value_change(change_dict):
    with w_output:
        print(change_dict['new'])

w_slider.observe(on_value_change, names='value')

display(w_slider, w_output)
```
<p>(I couldn't find a comprehensive list of available observable traits for each widget type, but it is not relevant for my question I think)</p>
<p>Is it possible to define/trigger custom observables in subclassed widgets? (I thought of 2 options of how it might be done, but maybe there is another way)</p>
<pre class="lang-py prettyprint-override"><code># Define the component
#----------------------------------------------------------------#
class CustomComponent(widgets.VBox):

    def __init__(self):
        self._internal_value = None
        # initialization of sub-components

    # Option 1: trigger the observe event when making changes
    def change_internal_value(self, newval):
        self._trigger_event("internal_value", {'type': 'change'})
        self._internal_value = newval

    # Option 2: mark a property as an observable and ipywidgets takes care of triggering events
    @widgets.mark_as_observable
    @property
    def internal_value(self):
        return self._internal_value

# Instantiate and observe the component
#----------------------------------------------------------------#
custom_component = CustomComponent()

def dont_touch(change_dict):
    print('Careful, you are changing the value!')

custom_component.observe(dont_touch, "internal_value")
</code>```

EDIT: as a pre-emptive clarification, I know I could implement my own suscribe_observer and notify_observer methods to the subclass, I would just prefer to re-utilize ipywidget functionalities for this as much as possible to avoid adding extra boilerplate code.

Body:
With default widgets, such as sliders, it is possible to observe the value or other traits so that any changes trigger a given function (see here):

w_slider = widgets.IntSlider()
w_output = widgets.Output()

def on_value_change(change_dict):
    with w_output:
        print(change_dict['new'])

w_slider.observe(on_value_change, names='value')

display(w_slider, w_output)

(I couldn't find a comprehensive list of available observable traits for each widget type, but it is not relevant for my question I think)

Is it possible to define/trigger custom observables in subclassed widgets? (I thought of 2 options of how it might be done, but maybe there is another way)

# Define the component
#----------------------------------------------------------------#
class CustomComponent(widgets.VBox):

    def __init__(self):
        self._internal_value = None
        # initialization of sub-components

    # Option 1: trigger the observe event when making changes
    def change_internal_value(self, newval):
        self._trigger_event("internal_value", {'type': 'change'})
        self._internal_value = newval

    # Option 2: mark a property as an observable and ipywidgets takes care of triggering events
    @widgets.mark_as_observable
    @property
    def internal_value(self):
        return self._internal_value

# Instantiate and observe the component
#----------------------------------------------------------------#
custom_component = CustomComponent()

def dont_touch(change_dict):
    print('Careful, you are changing the value!')

custom_component.observe(dont_touch, "internal_value")

EDIT: as a pre-emptive clarification, I know I could implement my own suscribe_observer and notify_observer methods to the subclass, I would just prefer to re-utilize ipywidget functionalities for this as much as possible to avoid adding extra boilerplate code.


问:
Unresolved extern crate Rocket after adding it to patch.crates-io
I have added the rocket = { version = "0.5.0-rc.1", features = ["json"] } to the Cargo.toml under [dependencies] & I'm using the below in the main.rs file:

```<code>#[macro_use]
extern crate rocket;
</code>```

It compiles & works fine. But now I want to use a fork of rocket so I add to the Cargo.toml:

```<code>[patch.crates-io]
rocket = { git = "https://github.com/LIT-Protocol/Rocket", branch = "feature/port-reuse" }
</code>```

But now the rust-analyzer error "unresolved extern crate" for:

```<code>#[macro_use]
extern crate rocket;
</code>```

How can I resolve this? Is there something else that I have to add to the Cargo.toml apart from the rocket patch that I added?

Body:
I have added the rocket = { version = "0.5.0-rc.1", features = ["json"] } to the Cargo.toml under [dependencies] & I'm using the below in the main.rs file:

#[macro_use]
extern crate rocket;

It compiles & works fine. But now I want to use a fork of rocket so I add to the Cargo.toml:

[patch.crates-io]
rocket = { git = "https://github.com/LIT-Protocol/Rocket", branch = "feature/port-reuse" }

But now the rust-analyzer error "unresolved extern crate" for:

#[macro_use]
extern crate rocket;

How can I resolve this? Is there something else that I have to add to the Cargo.toml apart from the rocket patch that I added?


问:
Create a "managed role" in discord
Is it possible for a bot to create a "managed role" in discord?

Looking at the API docs it seems that it is not.

The RoleData used in the .create also does not contain the managed prop

```<code>export interface RoleData {
  name?: string;
  color?: ColorResolvable;
  hoist?: boolean;
  position?: number;
  permissions?: PermissionResolvable;
  mentionable?: boolean;
  icon?: BufferResolvable | Base64Resolvable | EmojiResolvable | null;
  unicodeEmoji?: string | null;
}
</code>```

Tried creating a managed role using the RoleManager's .create

Title: Create a "managed role" in discord

Body:
Is it possible for a bot to create a "managed role" in discord?

Looking at the API docs it seems that it is not.

The RoleData used in the .create also does not contain the managed prop

export interface RoleData {
  name?: string;
  color?: ColorResolvable;
  hoist?: boolean;
  position?: number;
  permissions?: PermissionResolvable;
  mentionable?: boolean;
  icon?: BufferResolvable | Base64Resolvable | EmojiResolvable | null;
  unicodeEmoji?: string | null;
}

Tried creating a managed role using the RoleManager's .create


问:
memory layout of c++ class member variables
Basically I want to load member variables values from a data file, so my idea is to align data according to on RAM memory layout in file and then read it to memory from file directly.
For example for following class

```<code>class A {
 int a;
 int array_size;
 int *array;
};
</code>```

In file, first 8 bytes I will write value of a and next 8 bytes to store array_size then for some next n bytes I will store *array.

While loading from will do something like this
Pseudo code

```<code>char buffer[1028]; //I will get 1028 from some kind of header it will be total memory size of class including array size;
read(fd,buffer,1028);
A *a = buffer; //Type cast to type class A
a->array = a + 16; //Set array base address.
</code>```

Will my above approach work across different compiler and machine. (Don't worry about endiness). Will compiler guarantee some kind of alignment? I want file to be also interpreted by executable generated by different compiler and different machine.

Body:
Basically I want to load member variables values from a data file, so my idea is to align data according to on RAM memory layout in file and then read it to memory from file directly.
For example for following class

class A {
 int a;
 int array_size;
 int *array;
};

In file, first 8 bytes I will write value of a and next 8 bytes to store array_size then for some next n bytes I will store *array.

While loading from will do something like this
Pseudo code

char buffer[1028]; //I will get 1028 from some kind of header it will be total memory size of class including array size;
read(fd,buffer,1028);
A *a = buffer; //Type cast to type class A
a->array = a + 16; //Set array base address.

Will my above approach work across different compiler and machine. (Don't worry about endiness). Will compiler guarantee some kind of alignment? I want file to be also interpreted by executable generated by different compiler and different machine.


问:
Keycloak - Redirect the logged-in user to login page if consent is declined
In keycloak, we have enabled the 'Consent Required' as 'ON'. So during login at very first time, if user agreed to the consent, the page will be re-directed to home page and if denied, the page will be redirected to login page. This is behaving correctly but we wanted to have the following functionality also.  In user profile page, if the user revokes/denies the consent, then the page needs to be re-directed to login page.  Which keycloak configuration we need to set to have this functionality?</p>


问:
setting command alias through python API in gdb
I have written a small python script that adds new commands to gdb and for others to use it, they can just source the python file in their ~/.gdbinit, but I would now like to add some useful aliases to those commands.

Right now I've added a README instruction to add those aliases manually in each user's ~/.gdbinit, but wanted to know if there's any better way to just add aliases to the new commands in python itself.


问:
How to use Stack Navigator while still showing Bottom Tab Navigator
I'm currently developing an app where there is a Bottom Tab Navigator with 4 pages in it, but there are also other pages outside the tab navigator that the user can access, how can I show these pages to the user while also having the Bottom Tab Navigator at the bottom for quick access to the main pages?

Note: None of the tab navigator pages should be selected while showing the other pages

I tried using the default approach of nesting a stack navigator inside the Bottom Tab Navigator but in this approach I have to duplicate some common pages used throughout the app in each nested stack navigator... Also when any of the pages that aren't in the tab navigator are being displayed none of the icons in the Tab Navigator have to be selected

Any help would be appreciated
Thanks


问:
Yocto - create mImage kernel format
Hardware platform: RaspberryPi 4B. I want to create mImage kernel format using Yocto. I see that only allowed values for variable KERNEL_IMAGETYPE are zImage and Image. So I tried to write custom function that will create mImage format. But I struggling with dependency erros.

This is recipe of my image:

```<code>require recipes-core/images/core-image-minimal.bb
IMAGE_NAME = "super-pi"
IMAGE_INSTALL:append = " kernel-modules"

IMAGE_FSTYPES:append = " wic.gz"
IMAGE_FSTYPES:append = " ${INITRAMFS_FSTYPES}"
IMAGE_INSTALL += "testm"

do_create_mimage[nostamp] = "1"
do_create_mimage[depends] += "virtual/kernel:do_deploy"

addtask do_create_mimage after do_deploy before do_build

do_create_mimage() {
    bbnote "<super-pi> Building mImage"
    bbnote "deploy dir: ${DEPLOY_DIR_IMAGE}"
    bbnote "uboot build dir: ${UBOOT_BUILD_DIR}"
    ${UBOOT_BUILD_DIR}/tools/mkimage -C none -A ${ARCH} -O linux -T multi -a 0x88000000 -e 0x88000000 \
    -d ${DEPLOY_DIR_IMAGE}/Image:${DEPLOY_DIR_IMAGE}/super-pi-
    initramfs.cpio:${DEPLOY_DIR_IMAGE}/bcm2711-rpi-4-b.dtb ${DEPLOY_DIR_IMAGE}/mImage
}
</code>```

I defined UBOOT_BUILD_DIR in local.conf and it points to U-Boot B directory.
The problem is when function do_create_mimage is executed there is mkimage can't find super-pi-initramfs.cpio image (I wrote recipe for this image). Error message:

```<code>ERROR: super-pi-1.0-r0 do_create_mimage:
ExecutionError('/home/kuba/Desktop/YOCTO/build/tmp/work/raspberrypi4-poky-linux-gnueabi/super-
pi/1.0-r0/temp/run.do_create_mimage.39881', 1, None, None)
ERROR: Logfile of failure stored in: /home/kuba/Desktop/YOCTO/build/tmp/work/raspberrypi4-
poky-linux-gnueabi/super-pi/1.0-r0/temp/log.do_create_mimage.39881
Log data follows:
| DEBUG: Executing shell function do_create_mimage
| NOTE: <super-pi> Building mImage
| NOTE: deploy dir: /home/kuba/Desktop/YOCTO/build/tmp/deploy/images/raspberrypi4
| NOTE: uboot build dir: /home/kuba/Desktop/YOCTO/build/tmp/work/raspberrypi4-poky-linux-
gnueabi/u-boot/1_2022.01-r0/build
| /home/kuba/Desktop/YOCTO/build/tmp/work/raspberrypi4-poky-linux-gnueabi/u-boot/1_2022.01-
r0/build/tools/mkimage: Can't stat
/home/kuba/Desktop/YOCTO/build/tmp/deploy/images/raspberrypi4/super-pi-initramfs.cpio: No such
file or directory
| WARNING: exit code 1 from a shell command
</code>```

Where should I place function do_create_mimage() so that all dependencies are met before this function call?

I checked log.task_order for super-pi image:

```<code>. . .
do_image_tar (39740): log.do_image_tar.39740
do_image_ext3 (39741): log.do_image_ext3.39741
do_rootfs_wicenv (39747): log.do_rootfs_wicenv.39747
do_image_cpio (39742): log.do_image_cpio.39742
do_create_mimage (39881): log.do_create_mimage.39881
do_image_wic (39884): log.do_image_wic.39884
</code>```

It looks like my task is executed after cpio image should be ready, but it sill can't find it.

Title: Yocto - create mImage kernel format

Body:
Hardware platform: RaspberryPi 4B. I want to create mImage kernel format using Yocto. I see that only allowed values for variable KERNEL_IMAGETYPE are zImage and Image. So I tried to write custom function that will create mImage format. But I struggling with dependency erros.

This is recipe of my image:

require recipes-core/images/core-image-minimal.bb
IMAGE_NAME = "super-pi"
IMAGE_INSTALL:append = " kernel-modules"

IMAGE_FSTYPES:append = " wic.gz"
IMAGE_FSTYPES:append = " ${INITRAMFS_FSTYPES}"
IMAGE_INSTALL += "testm"

do_create_mimage[nostamp] = "1"
do_create_mimage[depends] += "virtual/kernel:do_deploy"

addtask do_create_mimage after do_deploy before do_build

do_create_mimage() {
    bbnote "<super-pi> Building mImage"
    bbnote "deploy dir: ${DEPLOY_DIR_IMAGE}"
    bbnote "uboot build dir: ${UBOOT_BUILD_DIR}"
    ${UBOOT_BUILD_DIR}/tools/mkimage -C none -A ${ARCH} -O linux -T multi -a 0x88000000 -e 0x88000000 \
    -d ${DEPLOY_DIR_IMAGE}/Image:${DEPLOY_DIR_IMAGE}/super-pi-
    initramfs.cpio:${DEPLOY_DIR_IMAGE}/bcm2711-rpi-4-b.dtb ${DEPLOY_DIR_IMAGE}/mImage
}

I defined UBOOT_BUILD_DIR in local.conf and it points to U-Boot B directory.
The problem is when function do_create_mimage is executed there is mkimage can't find super-pi-initramfs.cpio image (I wrote recipe for this image). Error message:

ERROR: super-pi-1.0-r0 do_create_mimage:
ExecutionError('/home/kuba/Desktop/YOCTO/build/tmp/work/raspberrypi4-poky-linux-gnueabi/super-
pi/1.0-r0/temp/run.do_create_mimage.39881', 1, None, None)
ERROR: Logfile of failure stored in: /home/kuba/Desktop/YOCTO/build/tmp/work/raspberrypi4-
poky-linux-gnueabi/super-pi/1.0-r0/temp/log.do_create_mimage.39881
Log data follows:
| DEBUG: Executing shell function do_create_mimage
| NOTE: <super-pi> Building mImage
| NOTE: deploy dir: /home/kuba/Desktop/YOCTO/build/tmp/deploy/images/raspberrypi4
| NOTE: uboot build dir: /home/kuba/Desktop/YOCTO/build/tmp/work/raspberrypi4-poky-linux-
gnueabi/u-boot/1_2022.01-r0/build
| /home/kuba/Desktop/YOCTO/build/tmp/work/raspberrypi4-poky-linux-gnueabi/u-boot/1_2022.01-
r0/build/tools/mkimage: Can't stat
/home/kuba/Desktop/YOCTO/build/tmp/deploy/images/raspberrypi4/super-pi-initramfs.cpio: No such
file or directory
| WARNING: exit code 1 from a shell command

Where should I place function do_create_mimage() so that all dependencies are met before this function call?

I checked log.task_order for super-pi image:

. . .
do_image_tar (39740): log.do_image_tar.39740
do_image_ext3 (39741): log.do_image_ext3.39741
do_rootfs_wicenv (39747): log.do_rootfs_wicenv.39747
do_image_cpio (39742): log.do_image_cpio.39742
do_create_mimage (39881): log.do_create_mimage.39881
do_image_wic (39884): log.do_image_wic.39884

It looks like my task is executed after cpio image should be ready, but it sill can't find it.


问:
How to create an exe file with MySQL database using Qt?
I am doing a qt project with MySQL database. But I don't know how to create an exe file with the MySQL database. I want to know,

which extension I should use to export the database.

the way how I should give the path to the database.

please help me to solve this problem....

I tried some youtube tutorials and I was able to build an exe file but the database didn't work properly.


问:
send VISCA commands over onvif protocal
I have worked on camera over VISCA commands to control PTZ, but now I want to send VISCA commands through ONVIF.
Is there any way to do that.
I have tried working with ONVIF device manager to control PTZ controls, its working fine, but I need a c++ library through which I can send VISCA commands.
Thanks in advance...

I have tried with some GitHub libraries to compile and generate binary files. They worked fine,but can't be able to integrate VISCA on ONVIF.
Github link: https://github.com/derzu/ONVIF-PVR

Title: send VISCA commands over onvif protocal


问:
Focusnode stuck at the last node
I have 3 FocusNodes which I would like to navigate using Keyboard or RemoteControl.

I've managed to do it yet I have a problem with the last node. Once It has focus I can't go backward to the previous node using the left arrow. Going backward works for the second node but not for the last one.

Here is the code I've been trying to make work:

```<code>import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  FocusNode? f1, f2, f3;

  void _onFocusChanged1() {
    bool f1Focus;
    setState(() => f1Focus = f1?.hasFocus ?? false);
  }

  void _onFocusChanged2() {
    bool f2Focus;
    setState(() => f2Focus = f2?.hasFocus ?? false);
  }

  void _onFocusChanged3() {
    bool f3Focus;
    setState(() => f3Focus = f3?.hasFocus ?? false);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (f1 == null) {
      f1 = FocusNode();
      f2 = FocusNode();
      f3 = FocusNode();
      //Setting the 1st Focus to the appropriate widget
      //List<FocusNode> fnList= List.generate(3, (index) => FocusNode());
      f1?.addListener(_onFocusChanged1);
      f2?.addListener(_onFocusChanged2);
      f3?.addListener(_onFocusChanged3);
      f1?.requestFocus();
    }
  }

  @override
  void dispose() {
    f1!.dispose();
    f2!.dispose();
    f3!.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: RawKeyboardListener(
            focusNode: FocusNode(),
            onKey: (event) {
              if (event.runtimeType == RawKeyUpEvent) {
                if (event.logicalKey == LogicalKeyboardKey.arrowRight) {
                  _onFocusChanged1;
                  _onFocusChanged2;
                  _onFocusChanged3;
                } else if (event.logicalKey == LogicalKeyboardKey.arrowLeft) {
                  _onFocusChanged1;
                  _onFocusChanged2;
                  _onFocusChanged3;
                }
              }
            },
            child: Center(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Focus(
                      focusNode: f1,
                      child: Container(
                        padding: const EdgeInsets.all(16),
                        height: 100,
                        width: 100,
                        color: (f1?.hasPrimaryFocus ?? true)
                            ? Colors.red
                            : Colors.blue,
                      ),
                    ),
                    Focus(
                      focusNode: f2,
                      child: Container(
                        padding: const EdgeInsets.all(16),
                        height: 100,
                        width: 100,
                        color: (f2?.hasPrimaryFocus ?? true)
                            ? Colors.red
                            : Colors.blue,
                      ),
                    ),
                    Focus(
                      focusNode: f3,
                      child: Container(
                        padding: const EdgeInsets.all(16),
                        height: 100,
                        width: 100,
                        color: (f3?.hasPrimaryFocus ?? true)
                            ? Colors.red
                            : Colors.blue,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
</code>```

Title: Focusnode stuck at the last node

Body:
I have 3 FocusNodes which I would like to navigate using Keyboard or RemoteControl.

I've managed to do it yet I have a problem with the last node. Once It has focus I can't go backward to the previous node using the left arrow. Going backward works for the second node but not for the last one.

Here is the code I've been trying to make work:

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  FocusNode? f1, f2, f3;

  void _onFocusChanged1() {
    bool f1Focus;
    setState(() => f1Focus = f1?.hasFocus ?? false);
  }

  void _onFocusChanged2() {
    bool f2Focus;
    setState(() => f2Focus = f2?.hasFocus ?? false);
  }

  void _onFocusChanged3() {
    bool f3Focus;
    setState(() => f3Focus = f3?.hasFocus ?? false);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (f1 == null) {
      f1 = FocusNode();
      f2 = FocusNode();
      f3 = FocusNode();
      //Setting the 1st Focus to the appropriate widget
      //List<FocusNode> fnList= List.generate(3, (index) => FocusNode());
      f1?.addListener(_onFocusChanged1);
      f2?.addListener(_onFocusChanged2);
      f3?.addListener(_onFocusChanged3);
      f1?.requestFocus();
    }
  }

  @override
  void dispose() {
    f1!.dispose();
    f2!.dispose();
    f3!.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: RawKeyboardListener(
            focusNode: FocusNode(),
            onKey: (event) {
              if (event.runtimeType == RawKeyUpEvent) {
                if (event.logicalKey == LogicalKeyboardKey.arrowRight) {
                  _onFocusChanged1;
                  _onFocusChanged2;
                  _onFocusChanged3;
                } else if (event.logicalKey == LogicalKeyboardKey.arrowLeft) {
                  _onFocusChanged1;
                  _onFocusChanged2;
                  _onFocusChanged3;
                }
              }
            },
            child: Center(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Focus(
                      focusNode: f1,
                      child: Container(
                        padding: const EdgeInsets.all(16),
                        height: 100,
                        width: 100,
                        color: (f1?.hasPrimaryFocus ?? true)
                            ? Colors.red
                            : Colors.blue,
                      ),
                    ),
                    Focus(
                      focusNode: f2,
                      child: Container(
                        padding: const EdgeInsets.all(16),
                        height: 100,
                        width: 100,
                        color: (f2?.hasPrimaryFocus ?? true)
                            ? Colors.red
                            : Colors.blue,
                      ),
                    ),
                    Focus(
                      focusNode: f3,
                      child: Container(
                        padding: const EdgeInsets.all(16),
                        height: 100,
                        width: 100,
                        color: (f3?.hasPrimaryFocus ?? true)
                            ? Colors.red
                            : Colors.blue,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}