text
string | meta
dict |
|---|---|
Q: FaucetPay Script Coin List Not Working Problem In Admin Setting Coin List not showing Problem in Faucetpay Script, How i Solve this issue.
AnyOne Help me to Solve this Issue
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How can include a info.plist file in the application bundle when debugging Python in VS code? In order to have my Pyside6 bluetooth application work successfully, I've had to include the NSBluetoothAlwaysUsageDescription key to the application's info.plist file (macOS Ventura 13.2).
However, the only way I've found to include this when running the program is to use PyInstaller, with the following in the .spec file:
app = BUNDLE(
exe,
name='run.app',
icon=None,
bundle_identifier=None,
info_plist={
'NSBluetoothAlwaysUsageDescription': 'This application uses a bluetooth sensor'
},
)
However, this requires building a packaged app to allow the necessary bluetooth permission.
My question is: How can I include this info.plist information when running and debugging within VScode?
I expected there would be a configuration to include this and have tried the following configuration in the launch.json
"osx": {
"name": "Launch",
"type": "python",
"request": "launch",
"infoPlist": "${workspaceFolder}/Info.plist"
}
I've also tried editing the settings.json with the following:
"python.pythonPath": "${workspaceFolder}/Info.plist"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can anyone tell me why my redirect helper does not work the way I'd expect it to? I'm trying to redirect to the other method in same controller, but it takes me http://localhost/ajaxTutorial/welcome/localhost/ajaxTutorial/welcome/index means it merge the both links. Does this make sense to anyone?
this is my controller code
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Welcome extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('form_validation');
$this->load->model('welcome_model', 'model');
}
public function index()
{
$this->load->view('login');
}
public function login()
{
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run()) {
$email = $_POST['email'];
$pass = $_POST['password'];
$modelData = $this->model->login($email , $pass);
if (!isset($modelData)) {
$_SESSION['logged_in'] = TRUE;
$_SESSION['id'] = $modelData['id'];
$_SESSION['username'] = $modelData['username'];
echo json_encode($modelData);
}else{
echo json_encode($modelData);
}
}else {
$modelData = array('Emailerr' => form_error('email'), 'Passerr'=>form_error('password'));
echo json_encode($modelData);
}
}
public function dashboard()
{
if (!isset($_SESSION['username'])) {
redirect('welcome/index');
} else {
echo "welcome";
}
}
Does anyone have advice on how to fix this issue?
A: It looks like you may be using a relative URL for your redirect, which is causing the URL to merge incorrectly. To fix this issue, you can try using an absolute URL instead.
Instead of using:
redirect('welcome/index');
Try using:
redirect(base_url('welcome/index'));
This should ensure that the redirect URL is constructed correctly and navigates to the correct controller method.
Note that base_url() is a CodeIgniter helper function that returns the base URL of your application. You can find more information about this function in the CodeIgniter documentation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: In Python: Replacing multiple characters in a string Given random string: x= "afffbeeec"
I want to apply the following changes:
*
*Replace x[0] with x[len(x)//2] # bfffbeeec
*Replace x[len(x)//2] with original x[-1] # bfffceeec
*Replace x[-1] with original x[0] # bfffceeea
Is there a more elegnt way than doing it like this:
x = "afffbeeec"
new_x = x[len (x)//2] + x[1:len(x)//2] + \
x[-1] + x[len(x)//2 + 1:-1] + x[0]
print(new_x)
I've tried ".replace", "list" + "join" and "index" methods.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to find average age in sql? I am trying to get the average age of each team I have in my team table and display the one that has an average age under 30. I am having issues getting the average age of each team. I am still new to SQL so I apologize in advance if my code does not make any sense.
At the moment the code will not work. I need to get the age from the date of birth and then get the average of all the players age on each team and display the one that is under 30.
Here is my code:
SELECT
teamName,
teamCity,
(
DATEDIFF( YY, athleteDateOfBirth, GETDATE() )
-
CASE WHEN DATEADD( YY,DATEDIFF( YY, athleteDateOfBirth, GETDATE() ), athleteDateOfBirth ) > GETDATE() THEN 1 ELSE 0 END
) AS [Age]
FROM
team
FULL JOIN athlete ON athlete.teamId = team.teamId
WHERE
athleteDateOfBirth =
(
SELECT
AVG(athleteDateOfBirth) AS 'Avg Age'
FROM
athlete
)
GROUP BY
teamName,
teamCity,
athleteDateOfBirth
HAVING
COUNT( athleteDateOfBirth ) < 30;
A: To calculate the team average you only want to group by team information. With that in mind you don't need a full join either because if someone isn't on a team they won't affect the team averages, so use an inner join.
SELECT
teamName
, teamCity
, AVG(DATEDIFF(YY, athleteDateOfBirth, GETDATE()) - CASE
WHEN DATEADD(YY, DATEDIFF(YY, athleteDateOfBirth, GETDATE()), athleteDateOfBirth) > GETDATE()
THEN 1
ELSE 0
END
) AS [AvAge]
FROM team
INNER JOIN athlete ON athlete.teamId = team.teamId
GROUP BY
teamName
, teamCity
HAVING AVG(DATEDIFF(YY, athleteDateOfBirth, GETDATE()) - CASE
WHEN DATEADD(YY, DATEDIFF(YY, athleteDateOfBirth, GETDATE()), athleteDateOfBirth) > GETDATE()
THEN 1
ELSE 0
END
) < 30;
NB: You really don't need a where clause if you are after an unbiased team average. If you were to, say, only choose players under 30, then you have biased your over result (and every team average would be below 30).
an alternative syntax:
with cte as (
SELECT
teamName
, teamCity
, AVG(DATEDIFF(YY, athleteDateOfBirth, GETDATE()) - CASE
WHEN DATEADD(YY, DATEDIFF(YY, athleteDateOfBirth, GETDATE()), athleteDateOfBirth) > GETDATE()
THEN 1
ELSE 0
END
) AS [AvAge]
FROM team
INNER JOIN athlete ON athlete.teamId = team.teamId
GROUP BY
teamName
, teamCity
)
select
*
from CTE
where AvAge < 30
Here the calculated column AvAge can be used in the second query and final where clause, hence you don't use a having clause due to this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: cGAN - how to train on multi labels with different classes? I would like to train a cGAN on 3 different labels, each having different classes (e.g. Label A has classes 0 to 4, Label B has classes 0 to 10, Label C has classes 0 to 20.
All code examples I've seen online only ever have 1 label with a certain number of classes, and they just concatenate this label vector with the latent vector. How would this work when you have multiple labels? A reference example would be great. Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unable to run github cli in interactive mode I am trying to create a repo using GitHub cli the command that I've used is gh repo create <repo name> but I am getting the following error
--public`, `--private`, or `--internal` required when not running interactively
Usage: gh repo create [<name>] [flags]
I can use flags and make it work but I want to use interactive mode it should work interactively out of the box but not working
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: seeking Alamofire response as string, but response is always nil I'm trying to download some HTML from a website, parse it,
and display it in a grid. The HTML isn't formatted very well,
so I've already written an init() method that parses that
HTML as a String.
My init() works fine in my unit tests.
What I'm having trouble with, is, getting the HTML as a
string via Alamofire. All the examples I can find seem to
imply that I need to do something close to this...
import SwiftUI
import Alamofire
func getHtml()-> String
{
let x = AF.request("https://httpbin.org/get")
.validate()
.response
if let y = x {
debugPrint(y)
return y.something()
}
return "<!-- the html could not be retrieved -->"
}
struct ContentView: View {
var body: some View {
Text(getHtml())
.padding()
}
}
My challenge is that AF.request().response seems to always
be nil. Which I find strange because all the Alamofire examples
I've seen online do not seem to even check for that. It's
as if older of Alamofire returned an HTTPResponse, not
an HTTPResponse?
Is there a simple way I can retrieve the (non-JSON) output
of the website I'm looking at, and hand it to my
constructor? With or without Alamofire?
Thanks!
This is with Alamofire 5.6.3 if it matters
Things I've tried:
*
*I've tried with / without the validate()
*On the theory response is asyrchonous, I tried adding a braindead while loop:
while(response != null) {
sleep(1)
}
A: You cannot return after you call an asynchronous function to get to the results.
You need to wait for the results, then use them. There are many ways to do this,
including completion handlers. You will have to look up how to use
asynchronous functions in Swift.
Here is some code that shows an additional alternative to Alamofire, using Swift async/await framework,
to get the html string from the asynchronous function getHtml().
Note that, you get some JSON data from the url you show, which could easily be decoded into a
model if needed.
struct ContentView: View {
@State var htmlString = "no data"
var body: some View {
Text(htmlString)
// .task {
// await getHtml()
// }
// Alamofire
.onAppear {
getHtml() { html, error in
if error == nil && html != nil {
print("\n---> html: \n \(html) \n")
htmlString = html!
}
}
}
}
func getHtml() async {
if let url = URL(string: "https://httpbin.org/get") {
do {
let (data, _) = try await URLSession.shared.data(from: url)
htmlString = String(data: data, encoding: .utf8)!
print("\n---> htmlString: \n \(htmlString) \n")
} catch {
print(error)
}
}
}
// using Alamofire
func getHtml(completion: @escaping (String?, Error?) -> Void) {
AF.request("https://httpbin.org/get").response { response in
switch response.result {
case .success(_):
let theString = String(data: response.data!, encoding: .utf8)!
completion(theString, nil)
case .failure(let AFError):
let error = AFError
print(error)
completion(nil, error)
}
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I serialize / deserialize private fields in pydantic models I'm using pydantic to model objects which are then being serialized to json and persisted in mongodb
For better encapsulation, I want to some fields to be private
but I still want them to be serialized to json when saving to mongodb, and then deserialized back from json when I fetch the object from the db
how can this be done?
Example Model:
class MyModel(BaseModel):
public_field: str
_creation_time: str
def __init__(self, public_field: str):
super().__init__(public_field=public_field,
_creation_time=str(datetime.now()))
model = MyModel(public_field='foo')
json_str = model.json()
print(json_str)
The output of this code is:
{"public_field": "foo"}
I would like it to be something like this:
{"public_field": "foo", "_creation_time": "2023-03-03 09:43:47.796720"}
and then also to be able to deserialize the above json back with the private field populated
A: Pydantic doesn't really like this having these private fields. By default it will just ignore the value and is very strict about what fields get set.
One way around this is to allow the field to be added as an Extra (although this will allow more than just this one field to be added).
The following works as you might expect:
class MyModel(BaseModel, extra=Extra.allow):
public_field: str
_creation_time: str
def __init__(self, **kwargs):
kwargs.setdefault("_creation_time", str(datetime.now()))
super().__init__(**kwargs)
model = MyModel(public_field='foo')
print(model)
json_str = model.json()
print(json_str)
print(MyModel.parse_obj({"public_field": "foo", "_creation_time": "2023-03-05 00:08:21.722193"}))
public_field='foo' _creation_time='2023-03-05 00:12:35.554712'
{"public_field": "foo", "_creation_time": "2023-03-05 00:12:35.554712"}
public_field='foo' _creation_time='2023-03-05 00:08:21.722193'
Note that because the field itself is being ignored, setting Field(default_factory=...) will not work, so you're stuck with the more awkward __init__ method,
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Pull out data from invoice and fess table based on ranges mysql I have 3 tables members fees and tblinvoice All they have a memberid
So if someone pays data goes to fees and tblinvoice and invoiceid is created in a fees table and tblinvoice plus memberid is inserted in these two tables two know which member paid.
now when the invoice is created only the tblinvoice recieves data but still with the memberid.
Now I want to pull out data from the 3 tables but the two tables fees and tblinvoice data will be based on the date range from tblinvoice which is invoicedate and also from tblinvoice date from fees fees.paiddate.
Now if there was data in table fees put it and if there is nothing pull out from tblinvoice or if both pull out from both.
The objective here is to pull out a statement for payments and invoiced amount. I wonder if I explained well this is what I have tried below am using mysql.
select
members.memberid,
fees.feesid,
members.usercode,
members.title,
members.name,
members.surname,
members.address,
members.city,
members.cell,
fees.recieved_by,
fees.paidfor,
fees.fromdate,
fees.amountpaid AS amountpaidMe,
fees.feestype,
fees.qty,
fees.paiddate,
fees.unitPrice,
fees.todate,
fees.invoiceid,
tblinvoice.amount AS invoicedAmount,
tblinvoice.invoicedate
FROM members
INNER JOIN fees ON fees.memberid = members.memberid
LEFT OUTER JOIN tblinvoice ON tblinvoice.memberid = fees.memberid
WHERE members.memberid ='62396'
&& tblinvoice.invoicedate BETWEEN '2023-01-01' AND '2023-03-05' OR fees.paiddate BETWEEN '2023-01-01' AND '2023-03-05'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unity is loading an empty gameobject into list even though the prefab exists UNITY C# Trying to do a code where a gameobject is added to a list when the code runs. No errors however the code just adds an empty gameobject even though a specific one has been identified.
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class HomeScreen : MonoBehaviour
{
public List<GameObject> myCollection;
public int money = 1000;
[SerializeField] public TMPro.TextMeshProUGUI currentMoney;
// Start is called before the first frame update
void Start()
{
myCollection.Add(Resources.Load<GameObject>("Assets/Resources/dogPrize.prefab"));
}
void Update()
{
currentMoney.text = "Money: $" + money.ToString();
}
public void buyScreen()
{
SceneManager.LoadScene (sceneName:"Buy Screen");
}
}
Actual Output:
Where the game object is located:
Expected result:
A: As explained in to the documentation, the path you pass to Resources.Load is relative to the Resources directory, and must not contain the extension, so it should be this:
myCollection.Add(Resources.Load<GameObject("dogPrize"));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why is the training loss constantly increasing? The following text is the result of translation by the translator, I am sorry if there are grammatical errors. Please bear with me, and please also ignore the Chinese comments in the code.
I am new to deep learning. I have just finished learning multi-layer perceptrons, and I have just started learning CNN, and I haven't finished it yet. In the past two days, I found a third-party image classification dataset (I searched it in advance because I will use it later in the paper), and implemented a simple CNN network. Although the code can run through, there is a serious problem, that is, the loss has increased since the beginning of the training, and the accuracy of the final test is relatively low but not ridiculously low. The specific data sets and codes are as follows:
The data set is a Lung Nodule Malignancy recognition data set, a binary classification data set, containing 6691 pieces of data, and the size is [1, 64, 64]. I divide it into a training set and a test set according to 8:2.
The code show as below:
# 导入所需的库
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import h5py
from torch.utils.data import Dataset, DataLoader, random_split
# 定义超参数
num_epochs = 5
batch_size = 100
learning_rate = 0.0001
# 使用GPU
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# 加载MNIST数据集并进行预处理
# 定义Dataset类
class HDF5Dataset(Dataset):
def __init__(self, file_path, transform=None):
# file_path: hdf5文件的路径
# transform: 可选的图像变换操作
self.file_path = file_path
self.transform = transform
# 打开hdf5文件(只读模式)
self.hdf5_file = h5py.File(file_path, "r")
# 获取图像和标签的数据集对象(注意修改为实际名称)
self.images = self.hdf5_file["ct_slices"]
self.labels = self.hdf5_file["new_slice_class"]
def __len__(self):
# 返回数据集的大小
return len(self.images)
def __getitem__(self, index):
# 根据索引返回一张图片及其标签
image = self.images[index] # 从hdf5文件中读取图像数据
label = self.labels[index] # 从hdf5文件中读取标签数据
if self.transform:
image = self.transform(image)
return image, label
# 定义图像变换操作
transform = transforms.Compose([
transforms.ToTensor(), # 将图片转换为张量格式
])
# 创建数据集对象
dataset = HDF5Dataset(file_path="all_patches.hdf5", transform=transform)
# 定义训练集和测试集的大小(8:2)
train_size = int(0.8 * len(dataset))
test_size = len(dataset) - train_size
# 随机分割数据集为训练集和测试集
train_dataset, test_dataset = random_split(dataset, [train_size, test_size])
# 创建训练集和测试集的数据加载器对象
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True, drop_last=True)
test_loader = DataLoader(test_dataset, batch_size=32, drop_last=True)
# 使用for循环遍历训练集和测试集
print("Training set:")
print(f"Train dataset size: {len(train_dataset)}")
for images, labels in train_loader:
print(images.shape)
print(labels.shape)
# print(images)
# print(labels)
break
print("------------------------------------------------")
print("Test set:")
print(f"Test dataset size: {len(test_dataset)}")
for images, labels in test_loader:
print(images.shape)
print(labels.shape)
# print(images)
# print(labels)
break
print("------------------------------------------------")
# 定义网络
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
# 定义卷积层,输入通道为1,输出通道为16,卷积核大小为5,步长为1,填充为1
self.conv1 = nn.Conv2d(1, 16, 3, 1, 1)
# 定义激活函数,使用ReLU函数
self.relu1 = nn.ReLU()
# 定义池化层,使用最大池化,池化核大小为2,步长为2
self.pool1 = nn.MaxPool2d(2, 2)
# 定义卷积层,输入通道为16,输出通道为32,卷积核大小为5,步长为1,填充为1
self.conv2 = nn.Conv2d(16, 32, 3, 1, 1)
# 定义激活函数,使用ReLU函数
self.relu2 = nn.ReLU()
# 定义池化层,使用最大池化,池化核大小为2,步长为2
self.pool2 = nn.MaxPool2d(2, 2)
# 定义全连接层,输入特征数为32*16*16
self.fc1 = nn.Linear(32*16*16, 1024)
# 定义激活函数,使用ReLU函数
self.relu3 = nn.ReLU()
# 定义全连接层,输入特征数为1024,输出为128
self.fc2 = nn.Linear(1024, 128)
# 定义激活函数,使用ReLU函数
self.relu4 = nn.ReLU()
# 定义全连接层,128,输出为128,输出特征数为2
self.fc3 = nn.Linear(128, 2)
# 定义softmax操作
self.softmax = nn.Softmax(dim=1)
def forward(self, x):
# 前向传播过程
#包括
x = self.conv1(x)
x = self.relu1(x)
x = self.pool1(x)
x = self.conv2(x)
x = self.relu2(x)
x = self.pool2(x)
x = x.view(-1, 32 * 16 * 16)
x = self.fc1(x)
x = self.relu3(x)
x = self.fc2(x)
x = self.relu4(x)
x = self.fc3(x)
x = self.softmax(x)
return x
# 创建一个CNN对象,并将其移动到GPU上
net = CNN().to(device)
# 创建损失函数和优化器,并指定要优化的参数和学习率
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters(), lr=learning_rate)
# 训练CNN网络
for epoch in range(num_epochs):
running_loss = 0.0
for i, (data, label) in enumerate(train_loader, 0):
# 将数据和标签移动到GPU上
data, label = data.to(device), label.to(device, dtype=torch.int64)
# 梯度清零
optimizer.zero_grad()
# 前向传播、计算损失、反向传播和优化
output = net(data)
loss = criterion(output, label)
loss.backward()
optimizer.step()
# 计算损失和准确率
running_loss += loss.item()
if (i+1) % 10 == 0: # 每10个batch输出一次
current_running_loss = running_loss / 10
print(f"Epoch {epoch + 1} Batch {i+1}, Loss: {current_running_loss:.4f}")
print('Finished Training')
# 在测试集上评估CNN网络的性能
correct = 0
total = 0
with torch.no_grad():
for data, label in test_loader:
# 将输入和标签移到GPU上
data, label = data.to(device), label.to(device)
# 前向传播、计算预测结果和准确率
outputs = net(data)
_, predicted = torch.max(outputs.data, 1)
total += label.size(0)
correct += (predicted == label).sum().item()
print('Accuracy of the network on the 10000 test images: {} %'.format(100 * correct / total))
The output of the model training part is as follows:
Epoch 1 Batch 10, Loss: 0.6785
Epoch 1 Batch 20, Loss: 1.3699
Epoch 1 Batch 30, Loss: 2.0675
Epoch 1 Batch 40, Loss: 2.7401
Epoch 1 Batch 50, Loss: 3.4534
Epoch 1 Batch 60, Loss: 4.1604
Epoch 1 Batch 70, Loss: 4.8768
Epoch 1 Batch 80, Loss: 5.5619
Epoch 1 Batch 90, Loss: 6.2502
Epoch 1 Batch 100, Loss: 6.9353
Epoch 1 Batch 110, Loss: 7.6517
Epoch 1 Batch 120, Loss: 8.3900
Epoch 1 Batch 130, Loss: 9.0907
Epoch 1 Batch 140, Loss: 9.7634
Epoch 1 Batch 150, Loss: 10.4548
Epoch 1 Batch 160, Loss: 11.1305
Epoch 2 Batch 10, Loss: 0.6695
Epoch 2 Batch 20, Loss: 1.3921
Epoch 2 Batch 30, Loss: 2.0835
Epoch 2 Batch 40, Loss: 2.8093
Epoch 2 Batch 50, Loss: 3.5194
Epoch 2 Batch 60, Loss: 4.2608
Epoch 2 Batch 70, Loss: 4.9428
Epoch 2 Batch 80, Loss: 5.6123
Epoch 2 Batch 90, Loss: 6.3225
Epoch 2 Batch 100, Loss: 6.9889
Epoch 2 Batch 110, Loss: 7.6459
Epoch 2 Batch 120, Loss: 8.3060
Epoch 2 Batch 130, Loss: 8.9630
Epoch 2 Batch 140, Loss: 9.6919
Epoch 2 Batch 150, Loss: 10.3833
Epoch 2 Batch 160, Loss: 11.0528
Epoch 3 Batch 10, Loss: 0.6851
Epoch 3 Batch 20, Loss: 1.3828
Epoch 3 Batch 30, Loss: 2.0960
Epoch 3 Batch 40, Loss: 2.8062
Epoch 3 Batch 50, Loss: 3.5101
Epoch 3 Batch 60, Loss: 4.1358
Epoch 3 Batch 70, Loss: 4.8366
Epoch 3 Batch 80, Loss: 5.5280
Epoch 3 Batch 90, Loss: 6.1600
Epoch 3 Batch 100, Loss: 6.8732
Epoch 3 Batch 110, Loss: 7.6021
Epoch 3 Batch 120, Loss: 8.2810
Epoch 3 Batch 130, Loss: 8.9693
Epoch 3 Batch 140, Loss: 9.6669
Epoch 3 Batch 150, Loss: 10.3552
Epoch 3 Batch 160, Loss: 11.0528
Epoch 4 Batch 10, Loss: 0.6633
Epoch 4 Batch 20, Loss: 1.3921
Epoch 4 Batch 30, Loss: 2.1117
Epoch 4 Batch 40, Loss: 2.8155
Epoch 4 Batch 50, Loss: 3.5226
Epoch 4 Batch 60, Loss: 4.1858
Epoch 4 Batch 70, Loss: 4.8803
Epoch 4 Batch 80, Loss: 5.6092
Epoch 4 Batch 90, Loss: 6.2850
Epoch 4 Batch 100, Loss: 6.9732
Epoch 4 Batch 110, Loss: 7.7209
Epoch 4 Batch 120, Loss: 8.3904
Epoch 4 Batch 130, Loss: 9.0505
Epoch 4 Batch 140, Loss: 9.7357
Epoch 4 Batch 150, Loss: 10.4271
Epoch 4 Batch 160, Loss: 11.0809
Epoch 5 Batch 10, Loss: 0.6758
Epoch 5 Batch 20, Loss: 1.3546
Epoch 5 Batch 30, Loss: 2.0179
Epoch 5 Batch 40, Loss: 2.7468
Epoch 5 Batch 50, Loss: 3.4819
Epoch 5 Batch 60, Loss: 4.1858
Epoch 5 Batch 70, Loss: 4.8866
Epoch 5 Batch 80, Loss: 5.5967
Epoch 5 Batch 90, Loss: 6.2319
Epoch 5 Batch 100, Loss: 6.9045
Epoch 5 Batch 110, Loss: 7.6021
Epoch 5 Batch 120, Loss: 8.2841
Epoch 5 Batch 130, Loss: 8.9474
Epoch 5 Batch 140, Loss: 9.6763
Epoch 5 Batch 150, Loss: 10.3677
Epoch 5 Batch 160, Loss: 11.0528
Finished Training
One way I know of to address this problem is to turn down the learning rate, but it doesn't improve. I would like to know if the seniors can advise me how to optimize and solve this problem in this case.
Because I am a pure novice, I will definitely make some mistakes that may be very stupid. Just do not hesitate to enlighten me, and please don't blame me too much, thank you very much for your guidance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: High metrics value for linear regression model I'm working with a dataset of cars, containing 10k rows and 5 columns:
id mileage_per_year model_year price sold
There are two negative values in the price column, I didn't know if I should 0 it or just leave it, and so, I left it untouched. I don't know if it can affect the training too much.
id 4200 price -270.77 mileage_per_year 17000 model_year 1998
id 4796 price -840.36 mileage_per_year 13277 model_year 1998
The max price in the dataset is 118,929.72 and the mean price is 64,842.
The challenge was to perform an exploratory analysis, change the dataset from imperial to metric system, translate from english to portuguese and create a model to predict the price of a car from 2005 and 172.095,3 total kilometers.
KM por ano = mileage_per_year
Ano do modelo = model_year
Vendido = sold
df['KM total'] = 1
novo = ['Indice', 'KM por ano', 'Ano do modelo', 'Preço', 'Vendido']
df = df.rename(columns={list(df.columns.values)[i] : novo[i] for i in range(len(novo))})
for i in range(len(df)):
df['KM por ano'][i] = int(float(df["KM por ano"][i] * 1.60934))
if df['Vendido'][i] == 'yes':
df['Vendido'][i] = 'Sim'
else:
df['Vendido'][i] = 'Nao'
df['KM total'][i] = int(df['KM por ano'][i] * (2023 - df['Ano do modelo'][i]))
I created a new column containing the total KM the car has so it would be, in my mind, easier to train the model.
X = df[['KM por ano','KM total','Ano do modelo']]
y = df[['Preço']]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)
lr = LinearRegression()
lr.fit(X_train, y_train)
km_ano = 172095.3 / (2023-2005)
preds = lr.predict([[km_ano, 172095.3, 2005]])
The model predicts the price of 66,347 USD.
My problem is with the evaluation of the model.
MAE = 20,849.715
MSE(squared=False) = 24,571.520
RMSE(squared=False) = 156.753
At this point I thought the model was bogus, something was wrong. However the coefficient of determination score was encouraging (at least it seems so)
r2 = 0.04946931214392558
Am I doing something wrong? It felt pretty obvious to use multiple linear regression for this but with these metrics it feels like it's wrong.
Sorry if the question isn't clear, I tried my best to explain.
The main task here was to predict the price of a car with 172095.3 total km and model year from 2005. I think I did everything right but the metrics, as far as I know, should be around 0-1 however they are off the charts. Only r2 seems to corroborate the prediction, but is it enough to trust the model?
A: None of your average metrics will be between 0 and 1 if you're trying to predict the price of a car. However, if you are trying to predict the size of an ant, you might say "I have a problem" with such values :-)
The price you predict has an average absolute error of +/-$20k. So you can consider the confidence interval of your prediction between [151245.585, 192945.02]. The smaller your spread, the more confidence you can have in your prediction. The best is to use the MAPE (Mean Absolute Percentage Error) to get a percentage error. Probably here you will have an error of +/- 12%.
So with MAPE, you can compare the accuracy of two models: one for car price and other for ant size.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: tensorflow is outdated to my current python version currently my python version is 3.11.x but my TensorFlow is outdated, is it possible to make outdated TensorFlow to work with the latest python
is it possible to get outdated TensorFlow to work with latest python
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Axum Query Extractor - Allow for struct with optional fields to be parsed? Rust newbie here (and first time SO poster)! I am attempting to add pagination to my axum API, and am trying to use an optional Query extractor on a Pagination struct in my request, to allow for users to skip specifying Pagination and allow the default values if they are sufficient for what the user needs. I was able to accomplish this pretty easily by wrapping my query param in an Option and using unwrap_or_default when grabbing it in the code. The problem I have now, is I think it would be useful to allow the user to specify just one value of pagination, i.e. limit or offset, instead of them both in the case that a user only needs to change one value and the default for the other works fine.
I have an impl Default set up to specify a default value for pagination if it is not supplied by the user, but the issue I'm running into now is that the user must specify both the limit and offset to have pagination work - if only one is specified, the axum Query extractor fails to parse the struct and uses the default Pagination instead, disregarding what the user specified for the query params completely.
I thought I could try making the inner fields of the structs Options, but then my default trait would only cover a None case, and I'd have to set up some handling function like Pagination::fill(pagination: Pagination) -> Pagination or something similar that would parse through all fields and set the None values to their default values, which I would have to specify somewhere and would ultimately defeat the whole point of the default function and does not feel like best practice.
Is there some better way to handle the simple Default for a struct with optional fields, or perhaps some axum extractor specific way to allow for a query struct that can have any permutations of it's fields set (i.e. I am considering implementing a custom extractor for pagination specifically, but feel like there has to be some easier way to handle this behavior).
Example
use axum::{
routing::get,
Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
pub struct Pagination {
pub offset: i64,
pub limit: i64,
}
impl Default for Pagination {
fn default() -> Self {
offset: 0,
limit: 10,
}
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/get_many_items", get(get_many_items));
axum::Server::bind(&"0.0.0.0:7878".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
// route handler that will return a lot of items
// =============================================
// if the user calls without any query param set or ?offset=<offset>&limit=<limit>
// expected behavior - pagination is set to default or user specified resp.
//
// if the user calls ?offset=<offset> or ?limit=<limit>
// unexpected behavior, query extractor fails and default pagination is used instead
async fn get_many_items(pagination: Option<Pagination>) -> String {
let Query(pagination) = pagination.unwrap_or_default();
let message = format!("offset={} & limit={}", pagination.offset, pagination.limit);
println!("{}", &message);
message
}
Actions attempted
I attempted making both fields Options, but if the query param is not specified the default query extractor fails to recognize the partial fields as the struct still. I am also considering setting explicitly declared constant default values in my pagination struct and using those instead of the Default trait, but adding const values to structs does not seem to be a very "rust" solution to the problem. Additionally, I could change the fields into their own structs, like
pub struct PaginationLimit {
limit: i64,
}
impl Default for PaginationLimit {
fn default() -> Self {
Self {
limit: 10,
}
}
}
pub struct PaginationOffset {
offset: i64,
}
impl Default for PaginationOffset {
fn default() -> Self {
Self {
offset: 0,
}
}
}
or I could just parse the values themselves without using the struct encapsulaiton e.g.
fn get_many(Query(limit): Option<i64>, Query(offset): Option<i64>) { ...
but that feels wrong, and like it would open up paths to a bunch of issues later as you would have to manually specify all fields of pagination in the params of any handler you want pagination in (not to mention the refactoring required if pagination's fields were to change ever in the future).
Finally, I am considering adding in a custom extractor for this use case, but as I would expect this to be a somewhat common use case I would at least like to confirm with the community there is not an easier/better way to handle this behavior before going forwards with that approach.
Relevant links found while researching the topic:
Axum extract documentation:
*
*https://docs.rs/axum/latest/axum/extract/index.html#applying-multiple-extractors
Specifies how to set an optional query struct, but not how to handle optional values inside the struct
Top Google Results:
*
*How to use both axum::extract::Query and axum::extract::State with Axum?
Just about using multiple extractors combined in request
*https://www.reddit.com/r/learnrust/comments/yk0wib/axum_optional_path_extractor/
About optional path extractors, not query extractor or multiple optional values
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: why is my multiple dropdowns menus not working? i am trying to make two dropdown menus using those codes:
html code:
//menu 1
<li>
<p onclick="myFunction()" class="dropbtn">
Categories
<i class="fa fa-caret-down icon" aria-hidden="true"> </i>
</p>
<div id="myDropdown" class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</li>
//menu 2
<div class="account-logo">
<p onclick="my()" class="dropbtn">
<i class="fa fa-user" aria-hidden="true"></i
><i class="fa fa-caret-down" aria-hidden="true"></i>
</p>
<div id="myaccountDropdown" class="dropdown-accountsetting">
<a href="#">Linked 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
css code :
/* Dropdown Button */
.dropbtn {
color: whitesmoke;
width: 100%;
height: 100%;
display: flex;
align-content: stretch;
justify-content: center;
align-items: center;
flex-wrap: inherit;
cursor: pointer;
}
.dropbtn:hover {
color: blueviolet;
}
/* The container <div> - needed to position the dropdown content */
.dropdown {
position: relative;
top: 8px;
}
/* Dropdown Content (Hidden by Default) */
.dropdown-content {
display: none;
position: absolute;
background-color: #242222;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
z-index: 1;
}
/* Links inside the dropdown */
.dropdown-content a {
color: rgb(255, 255, 255);
padding: 12px 16px;
text-decoration: none;
display: block;
}
/* Change color of dropdown links on hover */
.dropdown-content a:hover {
background-color: #ddd;
}
/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
.show {
display: block;
}
.dropbtn .fa {
position: relative;
right: -3px;
}
/* account logo setting */
.clicked {
color: whitesmoke;
width: 100%;
height: 100%;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
cursor: pointer;
}
.clicked:hover {
color: blueviolet;
}
.account-logo {
position: relative;
display: inline-block;
}
.dropdown-accountsetting {
display: none;
position: absolute;
background-color: #242222;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
z-index: 1;
}
.dropdown-accountsetting a {
color: rgb(255, 255, 255);
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-accountsetting a:hover {
background-color: #ddd;
}
.showed {
display: block;
}
js code :
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function my() {
document.getElementById("myaccountDropdown").classList.toggle("showed");
}
// Function to handle clicks on the window
function handleClick(event) {
// Check if the click target is NOT the "dropbtn" element
if (!event.target.matches(".dropbtn")) {
// Get references to all the dropdown-content elements
var dropdowns = document.getElementsByClassName("dropdown-content");
// Loop through the dropdown-content elements
for (var i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
// Check if the current dropdown-content element has the "show" class
if (openDropdown.classList.contains("show")) {
// If it does, remove the "show" class to close the dropdown
openDropdown.classList.remove("show");
}
}
}
// Check if the click target is the "clicked" element
if (event.target.matches(".clicked")) {
// Get references to all the dropdown-accountsettings elements
var dropdowns = document.getElementsByClassName("dropdown-accountsetting");
// Loop through the dropdown-accountsettings elements
for (var i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
// Check if the current dropdown-accountsettings element has the "showed" class
if (openDropdown.classList.contains("showed")) {
// If it does, remove the "showed" class to close the dropdown
openDropdown.classList.remove("showed");
}
}
}
}
// Add the event listener to the window
window.addEventListener("click", handleClick);
the first buttom with myFunction() work fine but the 2nd my() only work when i click on the button i want to make it response whenever click at any place at the window
i try to make handle with eventlistener to make the window.onclick work with the two button
A: It seems like the issue with your second dropdown menu is that it only toggles when you click on the button itself, and not when you click anywhere else on the window.
To fix this issue, you can modify your event listener to check for both dropdown menus, and remove the corresponding classes accordingly. Here's the modified code for your event listener function:
function handleClick(event) {
// Check if the click target is NOT the "dropbtn" element or the "clicked" element
if (!event.target.matches(".dropbtn") && !event.target.matches(".clicked")) {
// Get references to all the dropdown-content and dropdown-accountsetting elements
var dropdowns = document.getElementsByClassName("dropdown-content");
var accountDropdowns = document.getElementsByClassName("dropdown-accountsetting");
// Loop through the dropdown-content elements
for (var i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
// Check if the current dropdown-content element has the "show" class
if (openDropdown.classList.contains("show")) {
// If it does, remove the "show" class to close the dropdown
openDropdown.classList.remove("show");
}
}
// Loop through the dropdown-accountsetting elements
for (var j = 0; j < accountDropdowns.length; j++) {
var openAccountDropdown = accountDropdowns[j];
// Check if the current dropdown-accountsetting element has the "showed" class
if (openAccountDropdown.classList.contains("showed")) {
// If it does, remove the "showed" class to close the dropdown
openAccountDropdown.classList.remove("showed");
}
}
}
// Check if the click target is the "dropbtn" element
if (event.target.matches(".dropbtn")) {
document.getElementById("myDropdown").classList.toggle("show");
}
// Check if the click target is the "clicked" element
if (event.target.matches(".clicked")) {
document.getElementById("myaccountDropdown").classList.toggle("showed");
}
}
// Add the event listener to the window
window.addEventListener("click", handleClick);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a way to pass a function (to be called) with arguments to another swift function without placing it in a closure? For the fun of it, I'm writing code for an operator to do optional chaining to a function. The operator will call the function on the right of the operator if the element on the left is not nil. I want to take the code below and simplify it to not have the "if" test. Optional chaining can get rid of "if" tests in other types of code so why not here:
let derp: Connector? = nil
if derp != nil {
selectConnector( connector: derp! )
}
I want optional chaining to work for calling a function that is not a member of Connector sort of like this:
let derp: Connector? = nil
derp?.selectConnector( connector: derp! )// No good because selectConnector is not a member of Connector.
So I implemented this:
infix operator ???
func ??? ( test: Any?, function: ()->Void ) {
if test != nil { function() }
}
And call it like this:
let derp: Connector? = nil
derp ??? { selectConnector( connector: derp! ) }
This works. The only thing I want to change is to not have a closure and to somehow pass the selectConnector() function with its parameters to the operator. Here's what I've tried but it doesn't work:
infix operator ???
func ??? ( test: Any?, function: ( _ args: Any... )->Void ) {
if test != nil { function( args ) } // Error is "args" isn't in scope.
}
...
let derp: Connector? = nil
derp ??? selectConnector( connector: derp! )
I also tried this way of calling the function which gets rid of the "args" isn't in scope error:
infix operator ???
func ??? ( test: Any?, function: ( _ args: Any... )->Void ) {
if test != nil { function() } // No error here.
}
...
let derp: Connector? = nil
derp ??? selectConnector( connector: derp! ) // The error (mentioned below) shows here instead.
The one-line change above shows no error in the operator code but when I try to use the operator later, I get this error:
Cannot convert value of type '()' to expected argument type '(Any...) -> Void'
The error seems weird since I'm trying to pass a function that has parameter values and it sort of suggests that I'm not.
Is it possible to pass a function with specific parameter values to another function and call it, without using a closure?
And interestingly, the ? operator for optional chaining, when used with a function call, sort of implies "call the function after the operator if the variable IS NOT nil" and yet the ?? operator implies "use the value after the operator if the variable IS nil. So I'm torn on if this should be a ??? operator or maybe a !! operator. But that's a different question that I don't really need answered right now.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: spring Framwork learning path and documentation helo to everyone!
i'm begginer and i want to learn java spring. please help me where from should i start. if anyone has documentation of spring framework then send.
spring Framework path for beginners & easy documentations
spring Framework path for beginners & easy documentations
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Entity Framework Core: how to programmatically choose DbSet? I am trying to specify the table I would like _context to work with based on the request parameters.
I have 2 tables e.g. Chair, Table in my _context all of which implement interface
IProduct.
I would like to create a function, that would return either DbSet<Chair> or DbSet<Table>
After 2 hours of searching I cannot understand how to do it.
One of my attempts was:
public DbSet<IProduct> GetDbSet(bool condition)
{
if (condition)
{
return _context.Set<Chair>();
}
else
{
return _context.Set<Table>();
}
}
It generates "Cannot implicitly convert Chair to IProduct etc.
I am new to C# and I believe there must be a simple way to do this, but almost giving up on finding it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ref value showing undefined inside an event handler function in react js I am new to react and I am tring to access the amount value using amountInputRef.current.value for my food app inside submitHandler function but it shows as undefined when I try to add the items in the cart.
Below is the snippet of code React JS
const submitHandler = (event) => {
event.preventDefault();
// this line gives error
const enteredAmount = amountInputRef.current.value;
const enteredAmountNumber = +enteredAmount;
if (
enteredAmount.trim().length === 0 ||
enteredAmountNumber < 1 ||
enteredAmountNumber > 5
) {
setAmountIsValid(false);
return;
}
props.onAddToCart(enteredAmountNumber);
};
The error I get is -
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
Check the render method of `MealItemForm`.
at Input (http://localhost:3000/static/js/bundle.js:1261:22)
at form
at MealItemForm (http://localhost:3000/static/js/bundle.js:917:92)
at div
at li
at MealItem (http://localhost:3000/static/js/bundle.js:804:27)
at ul
at div
at Card (http://localhost:3000/static/js/bundle.js:1193:21)
at section
at AvailableMeals
at Meals
at main
at CartProvider (http://localhost:3000/static/js/bundle.js:1533:92)
at App (http://localhost:3000/static/js/bundle.js:35:88)
MealItemForm.js:14
Uncaught TypeError: Cannot read properties of undefined (reading 'value')
at submitHandler (MealItemForm.js:14:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:1)
at executeDispatch (react-dom.development.js:9041:1)
at processDispatchQueueItemsInOrder (react-dom.development.js:9073:1)
at processDispatchQueue (react-dom.development.js:9086:1)
at dispatchEventsForPlugins (react-dom.development.js:9097:1)
at react-dom.development.js:9288:1
MealItemForm.js
import { useRef, useState } from 'react';
import Input from '../../UI/Input';
import classes from './MealItemForm.module.css';
const MealItemForm = (props) => {
const [amountIsValid, setAmountIsValid] = useState(true);
const amountInputRef = useRef();
const submitHandler = (event) => {
event.preventDefault();
// below line gives error
const enteredAmount = amountInputRef.current.value;
const enteredAmountNumber = +enteredAmount;
if (
enteredAmount.trim().length === 0 ||
enteredAmountNumber < 1 ||
enteredAmountNumber > 5
) {
setAmountIsValid(false);
return;
}
props.onAddToCart(enteredAmountNumber);
};
return (
<form className={classes.form} onSubmit={submitHandler}>
<Input
ref={amountInputRef}
label='Amount'
input={{
id: 'amount_' + props.id,
type: 'number',
min: '1',
max: '5',
step: '1',
defaultValue: '1',
}}
/>
<button>+ Add</button>
{!amountIsValid && <p>Please enter a valid amount (1-5).</p>}
</form>
);
};
export default MealItemForm;
<Input /> is my custom component where I am passing ref using React.forwardRef.
Here is the full code of <Input /> component.
Input.js
import React from 'react';
import classes from './Input.module.css';
const Input = React.forwardRef((props, ref) => {
return (
<div className={classes.input}>
<label htmlFor={props.input.id}>{props.label}</label>
<input ref={ref} {...props.input} />
</div>
);
});
export default Input;
image of error
Here is the package.json
{
"name": "react-complete-guide",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.6",
"@testing-library/react": "^11.2.2",
"@testing-library/user-event": "^12.5.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-scripts": "5.0.1",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
I have deployed the app on netlify and I am not getting error there but gives error when running app on local server.
Live App Link - https://inquisitive-travesseiro-e08d8c.netlify.app/
GitHub Repo - https://github.com/themukuldharashivkar/Food-Order-App_ReactJS
Any help regarding this will be appreciated, thanks in advance.
The submitHandler() function should take the amount added and add it to the cart but nothing gets added.
A: The error you are getting is because you are trying to use a ref on a functional component. To approaching this, you can wrap your component with React.forwardRef() and pass the ref as a prop. By wrapping your component with forwardRef you can pass the ref down to the Input component. I
import {
useRef,
useState,
forwardRef
} from 'react';
import Input from '../../UI/Input';
import classes from './MealItemForm.module.css';
const MealItemForm = forwardRef((props, ref) => {
const [amountIsValid, setAmountIsValid] = useState(true);
const amountInputRef = useRef();
const submitHandler = (event) => {
event.preventDefault();
const enteredAmount = amountInputRef.current.value;
const enteredAmountNumber = +enteredAmount;
if (
enteredAmount.trim().length === 0 ||
enteredAmountNumber < 1 ||
enteredAmountNumber > 5
) {
setAmountIsValid(false);
return;
}
props.onAddToCart(enteredAmountNumber);
};
return ( <
form className = {
classes.form
}
onSubmit = {
submitHandler
} >
<
Input ref = {
ref
}
label = 'Amount'
input = {
{
id: 'amount_' + props.id,
type: 'number',
min: '1',
max: '5',
step: '1',
defaultValue: '1',
}
}
/> <
button > +Add < /button> {
!amountIsValid && < p > Please enter a valid amount(1 - 5). < /p>} <
/form>
);
});
export default MealItemForm;
hope this fixes your issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ¿Cómo puedo hacer una transicion se pagina? qué tal, colegas. Tengo una interrogante, y es que estoy intentando hacer una transición de página con html, css y Javascript, pero quisiera quitar el evento que hace que recargue la página, y se haga de una forma más fluida. Lo hago con e.preventDefault, pero pues, no me lleva a la otra sección. ¿Cómo puedo quitar el evento del ancla por defecto, pero que me permita ir a la otra sección? (estoy haciendo transiciones de página con gsap)
Grachas desde ya, por sus respuestas, ojalá me puedan ayudar.
Básicamente es cómo puedo hacer una transición de páginas, quitando el evento ee recarga de página del ancla que me va a llevar a la otra sección.
Y
|
{
"language": "es",
"url": "https://stackoverflow.com/questions/75640277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: why pyscript doesn't show output to when I run it? Can someone help me with this? Um... When I use pyscript with html and then run the program, it doesn't show the output.
It just shows the python code. Like it will just display print ("hello world") instead of hello world. If someone can help me fix this that would be great. I'm on windows.
I tried downloading the pyscript extension.
picture of my output
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make a solid, high-resolution 3D line with gradient coloring in THREE.js? I want to create a line that smoothly curves into space and is colored by gradient, but also has 3d properties (something I do not get 100% from the MeshLine library, and closely approximates the fat-lines example - https://threejs.org/examples/webgl_lines_fat.html)
Issues I'm facing:
*
*Creating gradient or shading on line
*Making line "solid"
*Line "resolution" (seems jagged) when using MeshLine
*I would like to get advantage of MeshLine's easy-to-animate properties in the long term
Do you have any suggestions on how I could achieve that?
It is my first time experimenting with THREE.js so I'm a bit of a novice when it comes to its limitations
My code so far:
function makeLine(geometry, color, width) {
var newLine = new MeshLineGeometry()
newLine.setPoints(geometry)
var material = new MeshLineMaterial({
//map - a THREE.Texture to paint along the line (requires useMap set to true)
useMap: false, //tells the material to use map (0 - solid color, 1 use texture)
//alphaMap - a THREE.Texture to paint along the line (requires useAlphaMap set to true)
//useAlphaMap - tells the material to use alphaMap (0 - no alpha, 1 modulate alpha)
//repeat - THREE.Vector2 to define the texture tiling (applies to map and alphaMap - MIGHT CHANGE IN THE FUTURE)
color: new THREE.Color(color), //THREE.Color to paint the line width, or tint the texture with
opacity: 1, //alpha value from 0 to 1 (requires transparent set to true)
//alphaTest - cutoff value from 0 to 1
//dashArray - the length and space between dashes. (0 - no dash)
//dashOffset - defines the location where the dash will begin. Ideal to animate the line.
//dashRatio - defines the ratio between that is visible or not (0 - more visible, 1 - more invisible).
resolution: resolution, //THREE.Vector2 specifying the canvas size (REQUIRED)
sizeAttenuation: false, //makes the line width constant regardless distance (1 unit is 1px on screen) (0 - attenuate, 1 - don't attenuate)
lineWidth: width, //float defining width (if sizeAttenuation is true, it's world units; else is screen pixels)
//near: camera.near,
//far: camera.far
})
// Create a new Mesh and set its geometry and material, then add it to the graph
var mesh = new MeshLine(newLine, material)
graph.add(mesh)
}
// Define the init function to create the lines
function init() {
createLines();
createAxes();
createCurve();
createSpline()
}
function createSpline() {
// create a curve using CatmullRomCurve3, which is a type of curve that smoothly interpolates points in 3D space
var spline = new THREE.CatmullRomCurve3(
[
new THREE.Vector3(-30, 2, 0), // starting point of the curve
new THREE.Vector3(10, 10, 0),
new THREE.Vector3(30, 1, 0),
new THREE.Vector3(-30, 12, 20) // ending point of the curve
]
);
var divisions = Math.round(12 * spline.points.length);
console.log(spline.points.length);
var positions = [];
var colors = [];
var color = new THREE.Color();
for (var i = 0, l = divisions; i < l; i++) {
var point = spline.getPoint(i / l);
positions.push(point.x, point.y, point.z);
color.setHSL(i / l, 1.0, 0.5);
colors.push(color.r, color.g, color.b);
}
makeLine(positions, 'red', 40);
}
function createCurve() {
// create a curve using CatmullRomCurve3, which is a type of curve that smoothly interpolates points in 3D space
var curve = new THREE.CatmullRomCurve3(
[
new THREE.Vector3(-30, 2, 0), // starting point of the curve
new THREE.Vector3(10, 10, 0),
new THREE.Vector3(30, 1, 0),
new THREE.Vector3(-30, 12, 20) // ending point of the curve
]
);
// define the number of points that will be used to create the ribbon
var pointsCount = 100;
// increase the number of points to create a more detailed ribbon
var pointsCount1 = pointsCount + 1;
// create a new array of points by offsetting the original points along the z-axis
var points = curve.getPoints(pointsCount);
var width = 5; // the width of the ribbon
var widthSteps = 1; // the number of steps to use when creating the ribbon width
let ptsZ = curve.getPoints(pointsCount);
ptsZ.forEach(p => {
p.z += width; // move each point in pts2 along the z-axis by the width of the ribbon
});
points = points.concat(ptsZ); // concatenate the two arrays of points to create the final array of points for the ribbon
// create a BufferGeometry from the array of points
var ribbonGeom = new THREE.BufferGeometry().setFromPoints(points);
// create the faces of the ribbon using the indices of the points in the array
var indices = [];
for (var iy = 0; iy < widthSteps; iy++) { // iterate over the number of steps in the width of the ribbon
for (var ix = 0; ix < pointsCount; ix++) { // iterate over the number of points along the curve
var a = ix + pointsCount1 * iy;
var b = ix + pointsCount1 * (iy + 1);
var c = (ix + 1) + pointsCount1 * (iy + 1);
var d = (ix + 1) + pointsCount1 * iy;
// create two faces for each "quad" of points, which will create the shape of the ribbon
indices.push(a, b, d);
indices.push(b, c, d);
}
}
ribbonGeom.setIndex(indices); // set the indices for the BufferGeometry to define the faces of the ribbon
ribbonGeom.computeVertexNormals(); // compute the vertex normals for the ribbon, which will be used for shading
// create a new Mesh using the BufferGeometry and a Material, and add it to the scene
var ribbon = new THREE.Mesh(
ribbonGeom,
new THREE.MeshNormalMaterial({
side: THREE.DoubleSide // make the ribbon double-sided to ensure it's visible from all angles
})
);
scene.add(ribbon);
}
function createAxes() {
var axesColor = 0x5ca4a9 //color of graph
var axesWidth = 10 //width of graph
//x-axis
var line = [];
line.push(new THREE.Vector3(-30, -30, -30)); //Point 1 x, z, y
line.push(new THREE.Vector3(30, -30, -30));//Point 2 x, z, y
//line connects points 1 and 2
//more points can be added to create more complex lines
makeLine(line, axesColor, axesWidth);
//z-axis (vertical)
var line = [];
line.push(new THREE.Vector3(-30, -30, -30));
line.push(new THREE.Vector3(-30, 30, -30));
makeLine(line, axesColor, axesWidth);
//y-axis
var line = [];
line.push(new THREE.Vector3(-30, -30, -30));
line.push(new THREE.Vector3(-30, -30, 30));
makeLine(line, axesColor, axesWidth);
}
function createLines() {
// Creates a Float32Array for line data with 600 positions
var line = new Float32Array(600);
// For loop that increments by 3
for (var j = 0; j < 200 * 3; j += 3) {
// Assigns x, y, and z coordinates to line array
line[j] = -30 + .1 * j;
line[j + 1] = 5 * Math.sin(.01 * j);
line[j + 2] = -20;
}
// Calls makeLine function and passes in the line array and color index 0
makeLine(line, colors[0], 10);
}
}
Code is based on:
http://spite.github.io/THREE.MeshLine/demo/graph.html
How Can I Convert a THREE.CatmullRomCurve3 to a Mesh?
Tried using MeshLine and fat-lines, no progress
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get constant literal type inferred from an javascript object imported from another file I have a javascript constant map defined in another file (I don't own this file) like this:
const obj = {
prop1: 'val1',
prop2: 'val2',
}
I want to use the literal types from this object while defining one of my types. For example, I want to define a function overload based on these values like this
function func(key: typeof obj.prop1): string;
function func(key: typeof obj.prop2): number;
when i import this object in my ts file, the default types are the wider types:
obj.prop1 is type string
obj.prop2 is type string
while i would want obj.prop1 to be type val1 and obj.prop2 to be val2
is there a way to do that?
*
*I can modify the original file to add a jsdoc annotation so that this obj is expored as const (I don't own the file)
*I can redefine the obj as enum in my typescript file and use that for getting the constant values (values can get out of sync over time)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: In powerbi how to show single report to user based on thier dataset using third party application Hello I am creating one applicarion where I want to integrate powerbi report as dashboard where user is login in our system and based on usreid dataset of poerbi repot should be changed for that user only. At a same time anyone using this report that also visual based on his data.
Anyone know there is better solution for this problem?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error "File too small" When using spm_slice_vol, Fieldtrip MATLAB When I was trying to convert a CT scan file's coordinate system into an approximation of the ACPC coordinate system on Fieldtrip MATLAB for a tutorial, there was error prompting that:
Warning: Cant get default Analyze orientation - assuming flipped
Smoothing by 0 & 8mm..
Error using spm_slice_vol
File too small.
Error in spm_smoothto8bit>smoothto8bit (line 51)
img = spm_slice_vol(V,spm_matrix([0 0 i]),V.dim(1:2),0);
Error in spm_smoothto8bit (line 14)
VO = smoothto8bit(V,fwhm);
Error in spm_normalise (line 151)
VF1 = spm_smoothto8bit(VF,flags.smosrc);
Error in ft_convert_coordsys (line 285)
params = spm_normalise(V2,V1,[],[],[],flags);
I have been trying to realign the anatomical CT scan, but the errors are still there.
By the way, the .nii file of the CT scan seems to be incomplete in the anterior part of the brain, particularly around nasion. Is it possible to remove the partial data so that the file is correctly read by Fieldtrip?
Does anyone know how to solve this? Thank you so much in advance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Scrapy - only returns yield from 1 url of list I'm crawling a website which has many countries, ex: amazon.com, .mx, .fr, .de, .es,...
(the website is not actually amazon)
I've made a url list of each base url and call parse with each one:
def start_requests(self):
for url in self.start_urls:
yield scrapy.Request(url, callback=self.parse)
I also have a list of keywords that it will search ex: toshiba, apple, hp, ibm,...
In the parse function I loop through each keyword and create a build url
ex: amazon.de/search?={keyword} in the correct format, this in turn calls another callback function:
def parse(self, response):
for keyword in self.keywords:
...(make build url with keyword)...
yield scrapy.Request(build_url, meta={'current_page': 1}, callback=self.crawl)
The function crawl will get the href of each listing on the page and follow it with a callback:
def crawl:
...(finds the href of each listing)...
for listing in listings:
yield scrapy.Request(self.main_url + href, callback=self.followListing,meta={'data':data})
data is a scrapy item which I fill in followListing() with the data I'm interested in.
ex: name, description, price, image_urls, etc... This final callback ends with a yield data which I would like to save in an output file.
def followListing(self, response):
...(fills up data item)...
yield data
when I run my crawler:
scrapy crawl my_crawler -o output.json
The output.json file only contains the listings from one of the url's (ex: amazon.mx), each time I run it it can contain the listings of a different url but only from one of them.
I suppose that as soon as one finishes it saves to the output file so the first one finished is the only one saved. Is this the case? How can I get the output with the yield from all of them or is there something else I'm missing?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to Check if a Restored Purchase is Pending with Flutter in_app_purchase package Problem
I have been working on a small app which has an option to purchase a premium version. It works perfectly fine for the test cards which automatically accept or decline. However, the slow cards pose a problem. The app will say the purchase is pending (desired behavior), but after the purchase is restored, it will act as if the purchase is charged even if it is still pending, giving access to the premium version until the purchase becomes declined or before they should have access (undesired behavior). The other problem that comes from this is that I locally save if they have premium, so even if they get it for a few minutes, the app will treat as if they have it for life. I have thought of checking for the restore purchase every time the app opens, so it revokes premium privilege to people who didn't yet pay for it, but it comes with the problems of it being avoided through being offline and not preventing anyone from using the a slow, declining card to continually get premium. I mainly just want to know if my code has a problem or if restored purchases are supposed to act like this even if they are payment pending.
What I Have Tried
I have tried seeing if the purchaseDetailsList contained more than one restored purchase (did not). I also had the _iap.completePurchase(purchaseDetails) outside of the two if statements, waiting to see if the purchase was pending completion, but this changed nothing. Finally, I tried a hail mary by getting rid of the restore functionality all together to see if all I needed was purchaseDetails.status == PurchaseStatus.purchased. It was not.
Relevant Code
InAppPurchase _iap = InAppPurchase.instance;
bool _available = true;
List<ProductDetails> _products = [];
List <PurchaseDetails> _purchases = [];
StreamSubscription? _subscription;
BuildContext? contextReference;
void _initialize() async {
_available = await _iap.isAvailable();
if(_available){
_subscription = _iap.purchaseStream.listen((data) => setState(() {
HandlePurchases(data);
}));
List<Future> futures = [_getProducts(), _getPastPurchases()];
await Future.wait(futures);
}
}
Future<void> _getProducts() async {
ProductDetailsResponse response = await _iap.queryProductDetails(Set.from([premiumEditionID]));
if (response.notFoundIDs.isNotEmpty) {
print("Can't Find ID");
}
setState(() {
_products = response.productDetails;
});
}
Future<void> _getPastPurchases() async {
//await Future.delayed(const Duration(milliseconds: 1500));
await _iap.restorePurchases(applicationUserName: null);
}
void HandlePurchases(List<PurchaseDetails> purchaseDetailsList){
purchaseDetailsList.forEach((PurchaseDetails purchaseDetails) async {
if (purchaseDetails.status == PurchaseStatus.error) {
PopUp("Error with Purchase");
}
else if (purchaseDetails.status == PurchaseStatus.pending) {
PopUp("Purchase is Pending");
}
else if (purchaseDetails.status == PurchaseStatus.purchased) {
PurchasePremium(true);
if (purchaseDetails.pendingCompletePurchase) {
await _iap.completePurchase(purchaseDetails);
}
}
else if(purchaseDetails.status == PurchaseStatus.restored) {
PurchasePremium(false);
if (purchaseDetails.pendingCompletePurchase){
await _iap.completePurchase(purchaseDetails);
}
}
else if (purchaseDetails.status == PurchaseStatus.canceled) {
PopUp("Purchase was Cancelled");
}
});
}
void PurchasePremium(bool firstPurchase){
setState(() {
if(contextReference != null || firstPurchase == false) {
if(firstPurchase){
Navigator.pop(contextReference!);
}
hasPremium = true;
prefs?.put('premium', true);
if(firstPurchase) {
ScaffoldMessenger.of(contextReference!).showSnackBar(
SnackBar(
content: Text(
"Thank you for your purchase! You now have premium!",
style: GoogleFonts.raleway(
),
),
),
);
}
}
});
}
void PopUp(String text){
setState(() {
if(contextReference != null) {
Navigator.pop(contextReference!);
ScaffoldMessenger.of(contextReference!).showSnackBar(
SnackBar(
content: Text(
text,
style: GoogleFonts.raleway(
),
),
),
);
}
});
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Usage of implode in OOP (cognitive framework) we have a code like below:
`$arrayUstKat = array();
if(isset($_POST["ust_id"]))
{
foreach ($_POST["ust_id"] as $UstKat)
$arrayUstKat[] =$UstKat;
}
$stringSTR = implode(",", $arrayUstKat);`
So, we have to implement this code to OOP framework (cognitive framework)
`$insert = $this->urun_kategori_model->add(
array(
"title" => $this->input->post("title"),
"ust_id" => $this->input->post("ust_id"),
"isActive" => 1,
"createdAt" => date("Y-m-d H:i:s")
)
);`
`public function post($index = NULL, $xss_clean = NULL)
{
return $this->_fetch_from_array($_POST, $index, $xss_clean);
}`
This OOP function takes only one value from the form, but we want to take all values from select multiple object with our implode code above. Can anyone help us about this?
Hello,
we have a code like below:
`$arrayUstKat = array();
if(isset($_POST["ust_id"]))
{
foreach ($_POST["ust_id"] as $UstKat)
$arrayUstKat[] =$UstKat;
}
$stringSTR = implode(",", $arrayUstKat);`
So, we have to implement this code to OOP framework (cognitive framework)
`$insert = $this->urun_kategori_model->add(
array(
"title" => $this->input->post("title"),
"ust_id" => $this->input->post("ust_id"),
"isActive" => 1,
"createdAt" => date("Y-m-d H:i:s")
)
);`
`public function post($index = NULL, $xss_clean = NULL)
{
return $this->_fetch_from_array($_POST, $index, $xss_clean);
}`
This OOP function takes only one value from the form, but we want to take all values from select multiple object with our implode code above. Can anyone help us about this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Update unlisted iOS App with same version number I have publsihed an unlisted app to the App Store (v1.0.0, build number: 2), and the status is "Ready for Sale". Then, I want to update the app since previous version has some major bugs. But Apple did not allow me to publish a same version with different build number.
So I published a new version (v1.0.1, build number: 1) and the status is "Ready for Sale". However, users with previous version (v1.0.0) installed does not get any notifications when there's an update. So, I had to notify them personally for them to update the app.
Right now, all users already updated this app to v1.0.1. But, I want to add popup notifications that will notify the user if there is an update. And I want this modification applies to current version (v1.0.1). But, I'm not sure how to do this since previously when I tried to publish the app with same version, it didn't work out as the error shows as "This version cannot receive any update. You need to publish to a new version".
Can anyone help? Tried to search for any answers, but I don't think any of the solution worked. Apple also didn't provide any detailed documentation on this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does my pthread_cond_signal not immediately wake a blocked thread? I'm writing a multithreaded program where an auxiliary thread runs after a condition is met, i.e., a certain number of elements existing in a data structure.
void*
gc_thread_handler(void *arg) {
while (!done) {
pthread_mutex_lock(&(gc.mutex));
while (!gc.collect && !done) {
pthread_cond_wait(&(gc.cond), &(gc.mutex));
}
pthread_mutex_unlock(&(gc.mutex));
rcgc_activate();
}
return NULL;
}
I block on the waiting thread until it receives a signal sent by the following function.
void *
gc_alloc(size_t sz) {
pthread_mutex_lock(&(gc.mutex));
// ...
gc.num_chunks++;
if (gc.num_chunks > MAX_CHUNKS) {
gc.collect = true;
pthread_cond_signal(&(gc.cond));
}
pthread_mutex_unlock(&(gc.mutex));
return ptr;
}
For some reason, however, it seems as if the signal does not immediately wake up the sleeping thread; the signals are repeatedly issued (because gc_alloc is repeatedly called). Eventually, the waiting thread does wake up and call gc_activate, but I don't really understand why it does not wake immediately.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640292",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I disable refresh mode in scrollview? In Android Studio, when we drag the scroll view to the end, a shadow is displayed at the bottom, how can I disable it?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Connect Python/Django App to a Free Tier Oracle cloud Database Im having some issues getting my app to connect to Oracles Free Tier Autonomous Database.
I keep getting the following error when attempting to start up the server.
(venv) me@computer app % python3 manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
Exception in thread django-main-thread:
Traceback (most recent call last):
File c/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 244, in ensure_connection
self.connect()
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "/Users/me/Projects/blah/app//Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 225, in connect
self.connection = self.get_new_connection(conn_params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/db/backends/oracle/base.py", line 250, in get_new_connection
return Database.connect(
^^^^^^^^^^^^^^^^^
cx_Oracle.DatabaseError: DPI-1047: Cannot locate a 64-bit Oracle Client library: "dlopen(libclntsh.dylib, 0x0001): tried: 'libclntsh.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OSlibclntsh.dylib' (no such file), '/usr/lib/libclntsh.dylib' (no such file, not in dyld cache), 'libclntsh.dylib' (no such file), '/usr/lib/libclntsh.dylib' (no such file, not in dyld cache)". See https://cx-oracle.readthedocs.io/en/latest/user_guide/installation.html for help
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 1038, in _bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 975, in run
self._target(*self._args, **self._kwargs)
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 137, in inner_run
self.check_migrations()
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/core/management/base.py", line 576, in check_migrations
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/db/migrations/executor.py", line 18, in __init__
self.loader = MigrationLoader(self.connection)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/db/migrations/loader.py", line 58, in __init__
self.build_graph()
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/db/migrations/loader.py", line 235, in build_graph
self.applied_migrations = recorder.applied_migrations()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/db/migrations/recorder.py", line 81, in applied_migrations
if self.has_table():
^^^^^^^^^^^^^^^^
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/db/migrations/recorder.py", line 57, in has_table
with self.connection.cursor() as cursor:
^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 284, in cursor
return self._cursor()
^^^^^^^^^^^^^^
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 260, in _cursor
self.ensure_connection()
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 243, in ensure_connection
with self.wrap_database_errors:
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/db/utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 244, in ensure_connection
self.connect()
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 225, in connect
self.connection = self.get_new_connection(conn_params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "/Users/me/Projects/blah/app/venv/lib/python3.11/site-packages/django/db/backends/oracle/base.py", line 250, in get_new_connection
return Database.connect(
^^^^^^^^^^^^^^^^^
django.db.utils.DatabaseError: DPI-1047: Cannot locate a 64-bit Oracle Client library: "dlopen(libclntsh.dylib, 0x0001): tried: 'libclntsh.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OSlibclntsh.dylib' (no such file), '/usr/lib/libclntsh.dylib' (no such file, not in dyld cache), 'libclntsh.dylib' (no such file), '/usr/lib/libclntsh.dylib' (no such file, not in dyld cache)". See https://cx-oracle.readthedocs.io/en/latest/user_guide/installation.html for help
I added the following to my settings.py file as per the Django documentation update the fields with the information I got from my tnsnames.ora file and I am still unable to connect via the app. But I am able to connect through VS Code and run queries/create tables etc.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'Database_Name', #AS SEEN FROM THE ORACLE CLOUD INTERFACE
'USER': 'user',
'PASSWORD': 'password',
'HOST': 'HOST', #AS SEEN IN THE TNSNAMES.ORA FILE
'PORT': '1522',
}
}
I have tried installing cx_oracle 8 & oracledb as well an neither of those resolved the issue.
Thanks for any assistance in resolving this issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Spring Boot version versus Spring Framework version? Given that you know the Spring Boot version used by an application, how do you find the underlying Spring (Framework) version?
Suppose you're the user of a Spring Boot application. The application log shows the Spring Boot version.
The application uses some Spring features that depend on the underlying Spring version. For example, Spring Expression Language (SpEL). To view the relevant version-specific docs for SpEL, you need to know the Spring version. Here's the URL for the SpEL docs for Spring 5.3.18:
https://docs.spring.io/spring-framework/docs/5.3.18/reference/html/core.html#expressions
How does the user of a Spring Boot application know which version of the Spring (Framework) docs to look at?
One person has told me that, as far as they know, "SpEL is stable", and so, the specific Spring version is not that significant. Still, the fact remains: the SpEL docs are Spring-version-specific. I'd like to view the docs that match the Spring version of the app. But perhaps I should have picked a different example Spring feature.
Am I missing something?
Examples of content that occurs to me might exist, and that I've looked for, but not found:
*
*In the Spring Boot docs, is there a formatted HTML table that maps Spring Boot versions to Spring Framework versions?
*In the docs for each version of Spring Boot, is there a link to the docs for the corresponding version of Spring? That is, do the Spring Boot 2.6.6 docs contain a link to the Spring 5.3.18 docs?
A: Find the reference to Spring Framework in the build.gradle file in the source for that Spring Boot version in GitHub.
For example, from the build.gradle for Spring Boot 2.6.6:
library("Spring Framework", "5.3.18")
But, is this the best answer?
The most user-friendly way for an application user, who might not typically look at build.gradle files, to "map" Spring Boot version 2.6.6 to Spring Framework version 5.3.18, so they can find the relevant Spring Framework docs?
A: The Spring Boot docs already link to the correct Spring version docs.
For example, in the Spring Boot 2.6.6 docs:
SpEL Expression Conditions
The @ConditionalOnExpression annotation lets configuration be included based on the result of a SpEL expression.
The text "SpEL expression" links to the corresponding Spring 5.3.18 docs.
Also from the Spring Boot 2.6.6 docs:
4.2. System Requirements
Spring Boot 2.6.6 requires Java 8 and is compatible up to and including Java 17. Spring Framework 5.3.18 or above is also required.
I'm out of excuses. It's right there under "Getting Started", in plain sight; not "hidden" behind a link URL.
I'm embarrassed to admit that I just hadn't noticed this before. Writing this question reinforced the feeling that I was missing something. I was. Perhaps I just should delete this entire question. I'm open to that. Then again, perhaps, by leaving this question, I might save someone else the same embarrassment.
Bottom line: RTFM!
A: (1) use https://start.spring.io/ create your first spring boot application and download zip , Project option select Maven
(2) unzip
(3) run this command:
mvn dependency:tree
if you select spring boot version is 3.0.3, you can get
[INFO] --- dependency:3.3.0:tree (default-cli) @ demo ---
[INFO] com.example:demo:jar:0.0.1-SNAPSHOT
[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:3.0.3:compile
[INFO] | +- org.springframework.boot:spring-boot-starter:jar:3.0.3:compile
[INFO] | | +- org.springframework.boot:spring-boot:jar:3.0.3:compile
[INFO] | | +- org.springframework.boot:spring-boot-autoconfigure:jar:3.0.3:compile
[INFO] | | +- org.springframework.boot:spring-boot-starter-logging:jar:3.0.3:compile
[INFO] | | | +- ch.qos.logback:logback-classic:jar:1.4.5:compile
[INFO] | | | | \- ch.qos.logback:logback-core:jar:1.4.5:compile
[INFO] | | | +- org.apache.logging.log4j:log4j-to-slf4j:jar:2.19.0:compile
[INFO] | | | | \- org.apache.logging.log4j:log4j-api:jar:2.19.0:compile
[INFO] | | | \- org.slf4j:jul-to-slf4j:jar:2.0.6:compile
[INFO] | | +- jakarta.annotation:jakarta.annotation-api:jar:2.1.1:compile
[INFO] | | \- org.yaml:snakeyaml:jar:1.33:compile
[INFO] | +- org.springframework.boot:spring-boot-starter-json:jar:3.0.3:compile
[INFO] | | +- com.fasterxml.jackson.core:jackson-databind:jar:2.14.2:compile
[INFO] | | | +- com.fasterxml.jackson.core:jackson-annotations:jar:2.14.2:compile
[INFO] | | | \- com.fasterxml.jackson.core:jackson-core:jar:2.14.2:compile
[INFO] | | +- com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar:2.14.2:compile
[INFO] | | +- com.fasterxml.jackson.datatype:jackson-datatype-jsr310:jar:2.14.2:compile
[INFO] | | \- com.fasterxml.jackson.module:jackson-module-parameter-names:jar:2.14.2:compile
[INFO] | +- org.springframework.boot:spring-boot-starter-tomcat:jar:3.0.3:compile
[INFO] | | +- org.apache.tomcat.embed:tomcat-embed-core:jar:10.1.5:compile
[INFO] | | +- org.apache.tomcat.embed:tomcat-embed-el:jar:10.1.5:compile
[INFO] | | \- org.apache.tomcat.embed:tomcat-embed-websocket:jar:10.1.5:compile
[INFO] | +- org.springframework:spring-web:jar:6.0.5:compile
[INFO] | | +- org.springframework:spring-beans:jar:6.0.5:compile
[INFO] | | \- io.micrometer:micrometer-observation:jar:1.10.4:compile
[INFO] | | \- io.micrometer:micrometer-commons:jar:1.10.4:compile
[INFO] | \- org.springframework:spring-webmvc:jar:6.0.5:compile
[INFO] | +- org.springframework:spring-aop:jar:6.0.5:compile
[INFO] | +- org.springframework:spring-context:jar:6.0.5:compile
[INFO] | \- org.springframework:spring-expression:jar:6.0.5:compile
[INFO] \- org.springframework.boot:spring-boot-starter-test:jar:3.0.3:test
[INFO] +- org.springframework.boot:spring-boot-test:jar:3.0.3:test
[INFO] +- org.springframework.boot:spring-boot-test-autoconfigure:jar:3.0.3:test
[INFO] +- com.jayway.jsonpath:json-path:jar:2.7.0:test
[INFO] | +- net.minidev:json-smart:jar:2.4.8:test
[INFO] | | \- net.minidev:accessors-smart:jar:2.4.8:test
[INFO] | | \- org.ow2.asm:asm:jar:9.1:test
[INFO] | \- org.slf4j:slf4j-api:jar:2.0.6:compile
[INFO] +- jakarta.xml.bind:jakarta.xml.bind-api:jar:4.0.0:test
[INFO] | \- jakarta.activation:jakarta.activation-api:jar:2.1.1:test
[INFO] +- org.assertj:assertj-core:jar:3.23.1:test
[INFO] | \- net.bytebuddy:byte-buddy:jar:1.12.23:test
[INFO] +- org.hamcrest:hamcrest:jar:2.2:test
[INFO] +- org.junit.jupiter:junit-jupiter:jar:5.9.2:test
[INFO] | +- org.junit.jupiter:junit-jupiter-api:jar:5.9.2:test
[INFO] | | +- org.opentest4j:opentest4j:jar:1.2.0:test
[INFO] | | +- org.junit.platform:junit-platform-commons:jar:1.9.2:test
[INFO] | | \- org.apiguardian:apiguardian-api:jar:1.1.2:test
[INFO] | +- org.junit.jupiter:junit-jupiter-params:jar:5.9.2:test
[INFO] | \- org.junit.jupiter:junit-jupiter-engine:jar:5.9.2:test
[INFO] | \- org.junit.platform:junit-platform-engine:jar:1.9.2:test
[INFO] +- org.mockito:mockito-core:jar:4.8.1:test
[INFO] | +- net.bytebuddy:byte-buddy-agent:jar:1.12.23:test
[INFO] | \- org.objenesis:objenesis:jar:3.2:test
[INFO] +- org.mockito:mockito-junit-jupiter:jar:4.8.1:test
[INFO] +- org.skyscreamer:jsonassert:jar:1.5.1:test
[INFO] | \- com.vaadin.external.google:android-json:jar:0.0.20131108.vaadin1:test
[INFO] +- org.springframework:spring-core:jar:6.0.5:compile
[INFO] | \- org.springframework:spring-jcl:jar:6.0.5:compile
[INFO] +- org.springframework:spring-test:jar:6.0.5:test
[INFO] \- org.xmlunit:xmlunit-core:jar:2.9.1:test
you can find the version and library.
my example pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
re sorting result:
Spring Boot 3.0.3 use:
Spring Framework:
*
*org.springframework:spring-aop:jar:6.0.5:compile
*org.springframework:spring-beans:jar:6.0.5:compile
*org.springframework:spring-context:jar:6.0.5:compile
*org.springframework:spring-core:jar:6.0.5:compile
*org.springframework:spring-expression:jar:6.0.5:compile
*org.springframework:spring-jcl:jar:6.0.5:compile
*org.springframework:spring-test:jar:6.0.5:test
*org.springframework:spring-web:jar:6.0.5:compile
*org.springframework:spring-webmvc:jar:6.0.5:compile
Logging:
*
*org.slf4j:jul-to-slf4j:jar:2.0.6:compile
*org.slf4j:slf4j-api:jar:2.0.6:compile
*org.apache.logging.log4j:log4j-api:jar:2.19.0:compile
*org.apache.logging.log4j:log4j-to-slf4j:jar:2.19.0:compile
*ch.qos.logback:logback-classic:jar:1.4.5:compile
*ch.qos.logback:logback-core:jar:1.4.5:compile
....
or you can change pom.xml, spring boot version from 3.0.3 to 2.7.8,
then re-run command:
mvn dependency:tree
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Comparing multidimensional lists in Python I have two multidimensional lists J,Cond. For every True element of Cond[0], I want the corresponding element in J[0] to be zero. I present the current and expected output.
J=[[0, 2, 0, 6, 7, 9, 10]]
Cond=[[False, True, False, True, True, True, True]]
for i in range(0,len(J[0])):
if(Cond[0][i]==True):
J[0][i]==0
print(J)
The current output is
[[0, 2, 0, 6, 7, 9, 10]]
The expected output is
[[0, 0, 0, 0, 0, 0, 0]]
A: Use J[0][i] = 0 instead of J[0][i] == 0.
Assignment is done by a single equal sign, while checking for equality is done by double equal sign.
A: You have an operator error in the if condition. Here is the code for the same
J=[[0, 2, 0, 6, 7, 9, 10]]
Cond=[[False, True, False, True, True, True, True]]
for i in range(0,len(J[0])):
if(Cond[0][i] == True):
J[0][i] = 0
print(J)
A: Your code :
*
*J=[[0, 2, 0, 6, 7, 9, 10]]
*Cond=[[False, True, False, True, True, True, True]]
*
*for i in range(0,len(J[0])):
*
if(Cond[0][i]==True):
*
J[0][i]==0
*print(J)
In line no.6 your statement : J[0][i]==0, here, the == operator is used for checking equality of the statement and returns a boolean value. So, your J[0][i] is only being compared with integer 0 and is not being assigned any value.
Assignment operator is =.
The correct statement for assignment would be : J[0][i]=0. After this, the J[0][i] would be assigned value as integer 0.
You only need to replace this line and you will get the required output.
So the corrected code would look like this :
*
*J=[[0, 2, 0, 6, 7, 9, 10]]
*Cond=[[False, True, False, True, True, True, True]]
*
*for i in range(0,len(J[0])):
*
if(Cond[0][i]==True):
*
J[0][i]=0
*print(J)
A: Você pode usar um loop for para iterar sobre os elementos em J[0] e Cond[0]. Se o elemento correspondente em Cond[0] for True, você pode definir o elemento em J[0] como 0. Aqui está um exemplo de como fazer isso:
J = [[0, 2, 0, 6, 7, 9, 10]] Cond = [[False, True, False, True, True, True, True]] for i in range(len(J[0])): if Cond[0][i]: J[0][i] = 0 print(J)
Isso produzirá [[0, 0, 0, 0, 0, 0, 0]], que é a saída esperada
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: execute a yolov5 model that looks like detect.py script when executed I have a yolov5 model (best.pt), i can load it using torch.hub.load and webcam as an input. However, it not looks the same when i execute detect.py script when it becomes from detection process. Also, I try to modify the detect.py script in another file to directly execute it without cmd but it so difficult.
How can I execute a file that looks like detect.py script but only uses a webcam as an input?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: In used firebase in Flutter web app : Error: Method not found: 'utilpromiseToFuture'. Error I chose firebase as database to make a web application in Flutter. At first everything was fine, but then an error occurred. I have no idea why it came out. Please help.
Error Below
Launching lib/main.dart on Chrome in debug mode...
main.dart:1
: Error: Method not found: 'utilpromiseToFuture'.
utils.dart:116
return utilpromiseToFuture(thenable);
^^^^^^^^^^^^^^^^^^^ Failed to compile application. Exited
As far as I could find on the internet, in dart flutter and it was said to update the packages. Even though I did these, the error did not change.
flutter doctor -v
[✓] Flutter (Channel stable, 3.7.6, on macOS 13.2.1 22D68 darwin-arm64, locale tr-TR)
• Flutter version 3.7.6 on channel stable at /Users/MSK/development/flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision 12cb4eb7a0 (3 days ago), 2023-03-01 10:29:26 -0800
• Engine revision ada363ee93
• Dart version 2.19.3
• DevTools version 2.20.1
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.2)
• Android SDK at /Users/MSK/Library/Android/sdk
• Platform android-33, build-tools 33.0.2
• Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 11.0.15+0-b2043.56-8887301)
• All Android licenses accepted.
[!] Xcode - develop for iOS and macOS (Xcode 14.2)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Build 14C18
✗ CocoaPods not installed.
CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
Without CocoaPods, plugins will not work on iOS or macOS.
For more info, see https://flutter.dev/platform-plugins
To install see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.
[✓] Chrome - develop for the web
• Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
[✓] Android Studio (version 2022.1)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin can be installed from:
https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 11.0.15+0-b2043.56-8887301)
[✓] VS Code (version 1.76.0)
• VS Code at /Applications/Visual Studio Code.app/Contents
• Flutter extension version 3.60.0
[✓] Connected device (2 available)
• macOS (desktop) • macos • darwin-arm64 • macOS 13.2.1 22D68 darwin-arm64
• Chrome (web) • chrome • web-javascript • Google Chrome 110.0.5481.177
[✓] HTTP Host Availability
• All required HTTP hosts are available
! Doctor found issues in 1 category.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: problem settinfg column span (setSpan) in QTableWidget with Python I have my header information in HeaderCol objects (below) that hold the text, the actual row the text is to appear on (it is one of the first two rows) the start column, and the span (number of columns)
I have the following code:
import sys
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem, QApplication, QDialog, QVBoxLayout, QHBoxLayout
class TenantEvent:
TENANT_EVENTS = []
def __init__(self, text):
self.text = text
TenantEvent.TENANT_EVENTS.append(self.text)
class HeaderCol:
MAX_COL = 0
HEADERS = [[]]
def __init__(self, text, row, col, span=1, header_row=0):
if row == 0:
HeaderCol.MAX_COL += col
self.text = text
self.row = row
self.col = col
self.span = span
if len(HeaderCol.HEADERS) <= header_row:
HeaderCol.HEADERS.append([])
HeaderCol.HEADERS[header_row].append(self)
class TransactionsTable(QTableWidget):
HEADER_TOP_ROW = 0
HEADER_SECOND_ROW = 1
col = 0
row = HEADER_TOP_ROW
ENTRY_COL = HeaderCol('Entry', row, col, 2)
col += ENTRY_COL.span
DUE_COL = HeaderCol('Due', row, col, 4)
col += DUE_COL.span
PAID_COL = HeaderCol('Paid', row, col, 7)
col += PAID_COL.span
MANAGEMENT_COL = HeaderCol('Management', row, col, 2)
col += MANAGEMENT_COL.span
col = 0
row = HEADER_SECOND_ROW
DATE_COL = HeaderCol('Date', row, col, 1, 1)
col += DATE_COL.span
EVENT_COL = HeaderCol('Event', row, col, 1, 1)
col += EVENT_COL.span
FEES_AND_CHARGES_COL = HeaderCol('Fees & Charges', row, col, 1, 1)
col += FEES_AND_CHARGES_COL.span
RENT_COL = HeaderCol('Rent', row, col, 1, 1)
col += RENT_COL.span
TAX_DUE_COL = HeaderCol('Tax', row, col, 1, 1)
col += TAX_DUE_COL.span
TOTAL_DUE_COL = HeaderCol('Total Due', row, col, 1, 1)
col += TOTAL_DUE_COL.span
PAID_COL = HeaderCol('Paid', row, col, 1, 1)
col += PAID_COL.span
PAYMENT_METHOD_COL = HeaderCol('Payment Method', row, col, 1, 1)
col += PAYMENT_METHOD_COL.span
CHECK_NUMBER_COL = HeaderCol('Check Number', row, col, 1, 1)
col += CHECK_NUMBER_COL.span
DATE_BANKED_COL = HeaderCol('Date Banked', row, col, 1, 1)
col += DATE_BANKED_COL.span
RENT_COL = HeaderCol('Rent', row, col, 1, 1)
col += RENT_COL.span
TAX_PAID_COL = HeaderCol('Tax', row, col, 1, 1)
col += TAX_PAID_COL.span
TOTAL_PAID_COL = HeaderCol('Total Paid', row, col, 1, 1)
col += TOTAL_PAID_COL.span
TENANT_STATUS_COL = HeaderCol('Tenant Status', row, col, 1, 1)
col += TENANT_STATUS_COL.span
EXPENSE_COL = HeaderCol('Expense', row, col)
col += EXPENSE_COL.span
MANAGEMENT_FEE_COL = HeaderCol('Management Fee', row, col)
HeaderCol.MAX_COL = col + MANAGEMENT_FEE_COL.span
NET_COL = HeaderCol('Net', row, col)
col += NET_COL.span
NOTES_COL = HeaderCol('Notes', row, col)
col += NOTES_COL.span
FEE_DUE_EVENT = TenantEvent('Fee Due')
MANAGEMENT_EXPENSE_EVENT = TenantEvent('Management Expense')
RENT_DUE_EVENT = TenantEvent('Rent Due')
LATE_FEE_EVENT = TenantEvent('Late Fee')
RENT_PAID_EVENT = TenantEvent('Rent Paid')
FEE_PAID_EVENT = TenantEvent('Fee Paid')
BOUNCED_RENT_CHECK_EVENT = TenantEvent('Bounced Rent Check')
BOUNCED_CHECK_FEE_EVENT = TenantEvent('Bounced Check Fee Due')
REPAIRS_AND_MAINTENANCE_EVENT = TenantEvent('Repairs & Maintenance')
def __init__(self, data, *args):
QTableWidget.__init__(self, *args)
self.verticalHeader().setVisible(False)
self.horizontalHeader().setVisible(False)
self.data = data
# self.set_data()
self.setRowCount(20)
self.setColumnCount(HeaderCol.MAX_COL+30)
self.resizeColumnsToContents()
self.resizeRowsToContents()
def add_headers(self):
print(f'{"text":>15}\trow\tcol\tr_s\tc_s')
for header_row in range(2):
for header in HeaderCol.HEADERS[header_row]:
row = header_row
col = header.col
row_span = 1
col_span = header.span
print(f'{header.text:>15}\t{row}\t{col}\t{row_span}\t{col_span}')
self.setSpan(row, col, row_span, col_span)
new_item = QTableWidgetItem(header.text)
self.setItem(header_row, header.col, new_item)
class TransactionsDialog(QDialog):
def __init__(self, data, *args):
super().__init__()
top_layout = QVBoxLayout()
layout = QHBoxLayout()
self.table = TransactionsTable(data, *args)
layout.addWidget(self.table)
top_layout.addLayout(layout)
self.setLayout(top_layout)
self.resize(2400, 600)
def main():
app = QApplication(sys.argv)
data = {'col1': ['1', '2', '3', '4'],
'col2': ['1', '2', '1', '3'],
'col3': ['1', '1', '2', '1']}
dialog = TransactionsDialog(data, 4, 3)
dialog.show()
dialog.exec()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The print output is this (which looks correct to me):
text row col r_s c_s
Entry 0 0 1 2
Due 0 2 1 4
Paid 0 6 1 7
Management 0 13 1 2
Expense 0 14 1 1
Management Fee 0 15 1 1
Net 0 15 1 1
Notes 0 16 1 1
Date 1 0 1 1
Event 1 1 1 1
Fees & Charges 1 2 1 1
Rent 1 3 1 1
Tax 1 4 1 1
Total Due 1 5 1 1
Paid 1 6 1 1
Payment Method 1 7 1 1
Check Number 1 8 1 1
Date Banked 1 9 1 1
Rent 1 10 1 1
Tax 1 11 1 1
Total Paid 1 12 1 1
Tenant Status 1 13 1 1
The problem is that the cells are not laid out correctly and don't get the correct text:
The first column and row are correct (Entry 0 0 1 2)
The first two cells on the first row are spanned together.
The problem is that the next entry (Due 0 2 1 4) on the first row merges all of the rest of the cells on the first row and I assume because there are no more cells on the first row, the rest is distrubuted down the table. I have tried stopping after the second entry, but the problem of taking up all the rest of the cells on first row is still there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get the Confusion matrix, Precision, Recall, F1 score, ROC curve, and AUC graph? I built and trained the CNN Model but didn't know how to get the Confusion matrix, Precision, Recall, F1 score, ROC curve, and AUC graph.
I'm not splitting the dataset by sklearn. Manually Split dataset into train, test and validation.
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras import layers
from tensorflow.keras import models
from tensorflow.keras import optimizers
from tensorflow.keras.preprocessing.image import load_img
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True,
validation_split=0.2)
training_set = train_datagen.flow_from_directory(
'/mnt/batch/tasks/shared/LS_root/mounts/clusters/saba19ec117/code/Users/saba19ec117/Project/train',
target_size = (250, 250),
batch_size = 32,
class_mode = 'binary')
validation_generator = train_datagen.flow_from_directory(
'/mnt/batch/tasks/shared/LS_root/mounts/clusters/saba19ec117/code/Users/saba19ec117/Project/test',
target_size = (250, 250),
batch_size = 32,
class_mode = 'binary')
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), padding = 'valid', activation = 'relu', input_shape=(250, 250, 3)))
model.add(layers.MaxPooling2D(pool_size=(2, 2)))
model.add(layers.Conv2D(64, (3, 3), padding = 'valid', activation = 'relu'))
model.add(layers.MaxPooling2D(pool_size=(2, 2)))
model.add(layers.Dense(310, activation = 'relu'))
model.add(layers.Dropout(0.45))
model.add(layers.Dense(270, activation = 'relu'))
model.add(layers.Dense(1, activation = 'sigmoid'))
model.compile(loss = 'binary_crossentropy',
optimizer = optimizers.Adam(learning_rate = 1e-4),
metrics = ['accuracy'])
model.fit(training_set,
steps_per_epoch = 30,
epochs = 25,
validation_data = validation_generator,
validation_steps = 9)
plt.plot(model.history.history['accuracy'])
plt.plot(model.history.history['val_accuracy'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
# Plot training & validation loss values
plt.plot(model.history.history['loss'])
plt.plot(model.history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
Can you tell, me how to get the Confusion matrix, Precision, Recall, F1 score, ROC curve, and AUC graph to my code?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to change usb keyboard layout language using InputMethodService? I have a smart TV on kitkat android, I want to connect a usb keyboard and set up keyboard shortcuts like in Windows, so as not to feel discomfort from non-convenient (standard) keyboard shortcuts, and I also want to add my own implementations of functionality that are not available in applications available in Google Play.
I tried to set keyboard shortcuts through the following programs:
1.External Keyboard Helper Pro
In this application, language switching is done as I need, but the application does not know how much, I managed to implement all the other functions, but there is no language switching.
2.Button Mapper: Remap your keys the application requires accessibility to be enabled, but smart TV firmware is cut down and there is no way to enable accessibility.
Therefore, I am writing my application, as there is a need and a desire to move in this direction.
Decided to make my own app but faced the problem of switching keyboard layout
public class ServiceIME1
extends InputMethodService{
private static final String TAG = ServiceIME.class.getSimpleName();
private static int pair[] = new int[2];
@Override
public boolean onKeyDown(int keyCode, KeyEvent keyEvent){
switch (keyCode){
case KeyEvent.KEYCODE_ALT_LEFT:
case KeyEvent.KEYCODE_CTRL_LEFT:
case KeyEvent.KEYCODE_META_LEFT:
pair[0] = keyCode;
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
if (pair[0] == KeyEvent.KEYCODE_CTRL_LEFT){ //"ctrl+shift" InputMethodManager inputMethodManager = (InputMethodManager) getApplicationContext().getSystemService(getApplicationContext().INPUT_METHOD_SERVICE);
inputMethodManager.showInputMethodPicker(); }
if (pair[0] == KeyEvent.KEYCODE_ALT_LEFT){ // alt+shift // switch lang
Locale locale1 = new Locale("en", "US");
Locale locale2 = new Locale("ru", "RU");
Locale l1 = Locale.getDefault();
Log.d(TAG, "" + l1.toString().equals(locale2.toString()));
if (l1.toString().equals(locale2.toString())){
l1.setDefault(locale1);
}
if (l1.toString().equals(locale1.toString())){
l1.setDefault(locale2);
}
Toast.makeText(getApplicationContext(), l1.getDisplayLanguage(), Toast.LENGTH_SHORT).show();
return true;
}
return true;
default:
return super.onKeyDown(keyCode, keyEvent);
}
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event){
switch (keyCode)
{
case KeyEvent.KEYCODE_ALT_LEFT:
case KeyEvent.KEYCODE_CTRL_LEFT:
case KeyEvent.KEYCODE_META_LEFT:
pair[0] = 0;
return true;
default:
return super.onKeyUp(keyCode, event);
}
}
}
Tried the solutions found on this forum:
//1
try{
String keyCommand = "input keyevent " + KeyEvent.KEYCODE_LANGUAGE_SWITCH;
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(keyCommand);
}
catch (IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
//2
new KeyEvent(KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_LANGUAGE_SWITCH);
//3
InputConnection inputConnection = this.getCurrentInputConnection();
if (inputConnection != null) {
inputConnection.sendKeyEvent(new KeyEvent(
keyEvent.getDownTime(),
keyEvent.getEventTime(),
keyEvent.getAction(),
KeyEvent.KEYCODE_LANGUAGE_SWITCH, keyEvent.getRepeatCount(), 0, keyEvent.getDeviceId(), keyEvent.getScanCode(), keyEvent.getFlags()
));}
//4
Locale locale = new Locale("ru");
Locale.setDefault(locale);
Configuration config = getBaseContext().getResources().getConfiguration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(
config,getBaseContext().getResources().getDisplayMetrics());
//5
Locale locale1 = new Locale("en", "US");
Locale locale2 = new Locale("ru", "RU");
Locale l1 = Locale.getDefault();
if (l1.toString().equals(locale2.toString())){
l1.setDefault(locale1);
Resources resources = getResources();
Configuration configuration = resources.getConfiguration();
DisplayMetrics displayMetrics = resources.getDisplayMetrics();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){ configuration.setLocale(locale1);
}else{
configuration.locale = locale1;}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N){
getApplicationContext().createConfigurationContext(configuration);}else{ resources.updateConfiguration(configuration, displayMetrics);}
}
if (l1.toString().equals(locale1.toString())){
l1.setDefault(locale2);
Resources resources = getResources();
Configuration configuration = resources.getConfiguration();
DisplayMetrics displayMetrics = resources.getDisplayMetrics();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
configuration.setLocale(locale2);}else{
configuration.locale = locale2;}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N){
getApplicationContext().createConfigurationContext(configuration);}else{
resources.updateConfiguration(configuration, displayMetrics);
}
}
Log.d(TAG, l1.getDisplayLanguage().toString());
Log.d(TAG, l1.toString());
Toast.makeText(getApplicationContext(), "current lang= " + l1.getDisplayLanguage().toString(), Toast.LENGTH_SHORT).show();
I am hope for your help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: GCP Custom Slack notification alert I need a way to customize slack alert notifications in GCP alert policy based on logs matching a given query like showing log details in the notification message, how can I do that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to setup the size and position of the cmd console as the output of the application form windows c# how to setup the size and position of the cmd console as the output of the application form windows,
I made an application that also brings up the CLI console but I can't adjust the size and position, I ask for your help
I want to determine the size and position of the CLI console in the windows application form
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting internal server error in UI and nullpointerexception in log while bringing up a new weblogic instance Getting nullpointerexception while trying to bring up a new weblogic instance in <[ServletContext@189093650[app:TBMS-APP module:tbms path:null spec-version:3.1]] Problem occurred while serving the error page. java.lang.NullPointerException at TbmsWebCache.getLabel(TbmsWebCache.java:294) at jsp_servlet._admin.__tbms_error._jspService(__tbms_error.java:773) at weblogic.servlet.jsp.JspBase.service(JspBase.java:35) at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:295) at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:260)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make my form write out to an excel sheet while automatically breaking to a new empty row I am trying to get text boxes from my Windows Form to write to an excel sheet, but breaking to the next empty row and doing the same thing. I just need Column A-D in each row filled in. with A = tbname.Text, B = tbphone.Text, C = ddisue.Text, D = lbdate.Text. Then breaking to row 2 A-D for the next customers info. The form is a kiosk that lets customers input this info and it resets for the next person. My only problem now is getting this data into excel. The excel sheet is saved to C:\Users\Willi\OneDrive\Desktop\log\form.xlsx
I can write to static cells however it overwrites once I click submit on the form again.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I have a function that takes two arguements and i need to pass thru two columns of a dataframe one by one This is a function i am using. I have two variables that i need to enter to get an output as you see below. I need to pass thru 10,000 columns as seems in image 2, which is just two of the columns. But essentially i need this to run 10k lines of a dataframe and save each output back in the dataframe ideally.
Here is my table. i need to pass thru these columns. they are passed as lists to the function.
| dx_full_list | poa
------|---------------------------------------|--------------------
12345 | [I255, I5023, R570, I4901] | [R570]
44444 | [I255, D62, D689, T86298, N390, I495] | [T86298, N390, I495]
from hcuppy.elixhauser import ElixhauserEngine
ee = ElixhauserEngine()
dx_full_lst = df.iat[0,0]
dx_poa_lst = df.iat[0,1]
out = ee.get_elixhauser(dx_full_lst,dx_poa_lst)
print(out)
{'cmrbdt_lst': ['HF'], 'rdmsn_scr': 0, 'mrtlt_scr': 0}`
image2
I can't get anything close to a result.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: React how to position a component next to another one So I have a component that I would like to display next to some text fields, but it isn't being displayed properly. This is how it is currently displaying (Sorry can't attatch images yet). The PieChart still has to render the blue section, but I believe it is overlapping with the bottom of the form. It should be able to render all 3 parts.
This is all under one functional component by the way. The PieChart is down towards the bottom and all of the code is under one div.
return(
<>
<div>
<h1 style = {{textAlign : "center", backgroundColor : 'grey'}}>Calorie Counter</h1>
<h1 style = {{textAlign : 'center', fontSize : '22px'}}>DAILY INTAKE: {currentCals} / {calorieIntake} |
PROTEIN : {currentProtein} / {maxProtein} | FATS: {currentFats} / {maxFats} | CARBS : {currentCarbs} / {maxCarbs} </h1>
<form style = {{display : 'flex', flexDirection : 'column', borderTop : '1px solid black' , borderRight : '1px solid black',
borderBottom : '1px solid black', width : '230px', marginTop : '30px'}}
onSubmit = {(event) => calculateCaloricIntake(event)}>
<h1 style = {{fontSize : '15px'}}>CALCULATE CALORIC INTAKE</h1>
<FormControl required>
<InputLabel>Sex</InputLabel>
<Select value = {sex} id = 'selectSex' onChange={(event) => setSex(event.target.value)} sx = {{width : 150} }>
<MenuItem value = 'Male'>Male</MenuItem>
<MenuItem value = 'Female'>Female</MenuItem>
</Select>
</FormControl>
<FormControl>
<TextField required placeholder = "Age" onChange = {(event) => setAge(event.target.value)} inputProps = {{maxLength : 2}} sx ={{width : 150}} ></TextField>
<TextField required placeholder = "Weight" onChange = {(event) => setUserWeight(event.target.value)} inputProps = {{maxLength : 3}} sx ={{width : 150}} ></TextField>
</FormControl>
<FormControl>
<InputLabel>Height in Feet</InputLabel>
<Select value = {heightFeet} onChange = {(event) => setHeightFeet(event.target.value)} sx = {{width : 150}} required>
<MenuItem value = {5}>5</MenuItem>
<MenuItem value = {6}>6</MenuItem>
</Select>
</FormControl>
<FormControl>
<InputLabel>Height in Inches</InputLabel>
<Select value = {heightInches} onChange = {(event) => setHeightInches(event.target.value)} sx = {{width : 150 }} required>
<MenuItem value = {1}>1</MenuItem>
<MenuItem value = {2}>2</MenuItem>
<MenuItem value = {3}>3</MenuItem>
<MenuItem value = {4}>4</MenuItem>
<MenuItem value = {5}>5</MenuItem>
<MenuItem value = {6}>6</MenuItem>
<MenuItem value = {7}>7</MenuItem>
<MenuItem value = {8}>8</MenuItem>
<MenuItem value = {9}>9</MenuItem>
<MenuItem value = {10}>10</MenuItem>
<MenuItem value = {11}>11</MenuItem>
</Select>
</FormControl>
<FormControl>
<InputLabel>Activity Level</InputLabel>
<Select required value = {activityLevel} onChange = {(event) => setActivityLevel(event.target.value)} sx = {{width : 150}}>
<MenuItem value = {1.2}>Sedentary</MenuItem>
<MenuItem value = {1.375}>Slightly Active</MenuItem>
<MenuItem value = {1.55} >Moderately Active</MenuItem>
<MenuItem value = {1.725}>Very Active</MenuItem>
<MenuItem value = {1.9}>Extremely Active</MenuItem>
</Select>
</FormControl>
<Button sx = {{justifyContent : 'left'}} type = "submit">Submit</Button>
</form>
<FormControl sx = {{ display : 'left', flexDirection : 'column', alignItems : 'right', borderTop : '1px solid black', borderRight: '1px solid black', borderBottom: '1px solid black', width : '230px', height : '300px', marginTop : '30px'}}>
<form onSubmit = {(e) => submitForm(e)} required>
<h1 style = {{fontSize : '15px'}}>ADD FOOD</h1>
<TextField placeholder='Calories' sx = {{width : '200px'}} id = "calories" required ></TextField>
<TextField placeholder='Protein' sx = {{width : '200px'}} id = "protein" required ></TextField>
<TextField placeholder='Fats' sx = {{width : '200px'}} id = "fats" required></TextField>
<TextField placeholder='Carbs' sx = {{width : '200px'}} id = "carbs" required></TextField>
<Button type = "submit" > Add Food</Button>
</form>
</FormControl>
<PieChart data = {pieData} radius = '10' center={[50, 1]} ></PieChart>
</div>
</>
)
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to run app on Api 24 emulator in Android Studio I have an App Source Code That's working Fine in Android Studio Emulator Above API 24 Devices But When I want to run it on API 24 or Below AVD Devices it says This Device not Supported . I want to know Can I run my App on Real Devices that come with API 24. this is code below
public class SplashActivity extends AppCompatActivity {
static String generic = "generic";
String email;
String name;
String profile;
FirebaseAuth mAuth;
public static boolean isEmulator() {
return Build.FINGERPRINT.startsWith(generic)
|| Build.FINGERPRINT.startsWith("unknown")
|| Build.MODEL.contains("google_sdk")
// || Build.MODEL.contains("Emulator")
|| Build.MODEL.contains("Android SDK built for x86")
|| Build.MANUFACTURER.contains("Genymotion")
|| (Build.BRAND.startsWith(generic) && Build.DEVICE.startsWith(generic))
|| "google_sdk".equals(Build.PRODUCT);
}
// printHashKey();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_activity);
mAuth = FirebaseAuth.getInstance();
if (!isEmulator()) {
FirebaseUser user = mAuth.getCurrentUser();
if (!AppController.getInstance().getEmail().equalsIgnoreCase("0")) {
email = AppController.getInstance().getEmail();
name = "user";
profile = "profile";
login();
} else {
AppController.getInstance().setCoins("0");
AppController.getInstance().setId("0");
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
} else {
Toast.makeText(getApplicationContext(), "This Device Not Supported", Toast.LENGTH_LONG).show();
finish();
}}
private void printHashKey() {
try {
PackageInfo info = getPackageManager().getPackageInfo("com.player.pro", PackageManager.GET_SIGNATURES);
for (android.content.pm.Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.e("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public void login() {
class Login extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... voids) {
RequestHandler requestHandler = new RequestHandler();
HashMap<String, String> params = new HashMap<>();
params.put("register_or_login", "1");
params.put("email", email);
params.put(PROFILE, profile);
params.put(NAME, name);
params.put(REFER, "0");
Log.e("Constants.TAG", params.toString());
return requestHandler.sendPostRequest(BASEURL, params);
}
I want to run my App on All AVD Devices but it is not Running on API 24 Emulator how to solve this Errors .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SwiperJS virtual slider displays blank slides for renderExternal with vueJS Trying to get virtual slides working with swiper element and vueJS.
But i am facing an issue, slides are not visible after initial few swipes.
I find no documentation example of how renderExternal is supposed to be used.
Here's my sample : https://codesandbox.io/p/sandbox/frosty-rgb-cgkc94
<template>
<div class="screen">
<swiper-container init="false" ref="swiperEl">
<swiper-slide v-for="(q, i) in virtualSlides.slides" :key="q.id">
<div class="card">
{{ q.content }}
</div>
</swiper-slide>
</swiper-container>
</div>
</template>
<script setup>
import { ref, onMounted } from "vue";
const slides = ref([]);
//cerate 50 slides
for (let i = 0; i < 50; i += 1) {
slides.value.push({ id: i, content: `Slide ${i}` });
}
console.log("Slides", slides.value);
const virtualSlides = ref({ slides: [] });
const swiperOpts = {
slidesPerView: 1,
speed: 40,
height: "100%",
spaceBetween: 16,
virtual: {
slides: slides.value,
addSlidesAfter: 0,
addSlidesBefore: 0,
initialSlide: 3,
renderExternal: (data) => {
console.log("Virtual data", data.slides);
virtualSlides.value.slides = data.slides.map((s) => {
return slides.value[s.id];
});
console.log("virtualSlide", virtualSlides.value.slides);
},
},
};
const swiperEl = ref();
onMounted(() => {
Object.assign(swiperEl.value, swiperOpts);
swiperEl.value.initialize();
});
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting a filename from a http web request/response I'm currently working on a web scraping project and working on how to determine the "best" file name for saving a file locally. I see a few options in determining what to name the file - scrape it from the url request (assuming a valid file name can be extracted), grab it from the response header, content-disposition filename if it's set, some custom header data that the web server returns, etc. Every site seems to return data slightly differently and it makes it very difficult to determine how to name file locally.
I've done some searching and I haven't seen any code that handles the situation of requests/responses data in determining a "best" filename. Hoping someone may have a more robust algorithm to help deal with this issue so I don't have to code it from scratch.
I've scraped the websites and got the responses. However, I'm looking for an efficient method of naming the files received from a web server.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Difficulty calculating blood oxygen saturation I'm sorry if this is not an appropriate question for the programming exchange.
I am having trouble with a function that is intended to calculate the saturation of oxygen in blood. I'm trying to use well known functions and science, but the result is coming back as a negative value who's absolute value is a few percent off the correct value.
private float _calculate_blood_oxygen_saturation(
float inspiredPartialPressure_kPa,
float arterialPartialPressure_kPa,
float temperature_C
)
{
// Constants for the oxygen-hemoglobin dissociation curve coefficients
const float _A = -173.4292f;
const float _B = 248.3763f;
const float _C = 0.7102f;
const float _D = -0.9959f;
const float _E = -0.2337f;
// Calculate the oxygen saturation curve coefficient
float temperature_K = temperature_C + 273.15f;
float oxygenSaturationCurveCoefficient =
_A +
( _B / temperature_K ) +
( _C * Mathf.Log( temperature_K ) ) +
( _D * Mathf.Pow( 10.0f, _E * ( temperature_K - 50 ) ) );
// Calculate the oxygen saturation percentage
float saturationPercentage = ( inspiredPartialPressure_kPa / arterialPartialPressure_kPa ) * 100.0f;
float saturation = ( saturationPercentage / oxygenSaturationCurveCoefficient ) * 100.0f;
return saturation;
}
The value should be a positive value between 0 and 100, but is returning as a negative value. I feel like something wrong with either my calculation of the oxygen coefficient, or the constants I'm using.
Edit:
The inputs are:
*
*arterialPartialPressure is a constant (95 mmHg * 0.133322f)
*temperatures will be near 20C
*inspiredPartialPressure will always be around 20
Edit 2: By request, I've added a link to the same question on the Biology Exchange, in the hopes that someone there can help me debug my formula:
https://biology.stackexchange.com/questions/111648/difficulty-calculating-blood-oxygen-saturation
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to assign agents to different nodes? I have a road-based transit center facility which has inbound and outbound docks. It is not on a GIS map, but a custom-designed layout.
I have a separate populations of inbound and outbound dock agents (7 and 8 respectively).
For each dock, there is a node.
How can I allocate each agent to separate node?
I have tried programmatically, by entering code in the 'On Start Up' field of the agent type.
Code for inbound docks given below.
//Define list with node names of inbound docks
List node_names = Arrays.asList("receivingDock1", "receivingDock2", "receivingDock3", "receivingDock4", "receivingDock5", "receivingDock6", "receivingDock7");
//Iterate over the inboundDocks agent population and assign to respective node
for (int i = 0; i < inboundDocks.size(); i++) {
inboundDocks.getAgent(i).setNode(getNodeByName(node_names.get(i)))};
However, I get errors:
`Error during model startup:
Unresolved compilation problems:
inboundDocks cannot be resolved
inboundDocks cannot be resolved
The method getNodeByName(String) is undefined for the type inboundDock
Syntax error, insert ";" to complete BlockStatements'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Python Question regarding ipaddress.IPv4Network I was wondering if there was a way to optimize the following that i'm probably missing.
ip_list = []
ipv4_list = ipaddress.IPv4Network('1.0.0.0/8')
for i in ipv4_list:
ip_list.append(str(i)) <-- This takes ~30 seconds
ip_list.append(i) <-- This takes ~13 seconds
I wasn't sure if there was a way to speed this process up.
The only other way i was thinking was break out the /8 into multiple /24s and process those in parallel and do whatever i needed to with them.
Essentially i'm just storing a list of all the ips in a block to do whatever with them. This essentially kills fastapi without increasing the timeout so i just wanted to speed it up.
A: It's probably just a mild speed-up, but using IPNetwork's built-in function hosts() will return the same list:
ip_list = list(ipaddress.IPv4Network('1.0.0.0/8').hosts())
The fact of the matter is, this is over 16 million addresses and it makes sense it'll perform badly. If you have an alternative way of doing whatever calculation you need that doesn't require iterating over all the subnets it's probably better.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I order the x-axis by date in R using ggplot2? I'm learning data visualization using R and as a personal project I decided to track and plot all of my workouts. My csv file has three columns: "Date", "Activity", and "Duration". I'm having trouble getting the dates to appear in the right order on the graph.
Here is my code:
log <- read_csv("Training Log.csv")
ggplot(log, aes(Date,Duration))+
geom_col(aes(fill=Activity))+
ylab("Duration (min)")
Details about my tibble using dput(log):
structure(list(Date = c("2/6", "2/9", "2/11", "2/13", "2/15",
"2/16", "2/17", "2/18", "2/19", "2/19", "2/21", "2/24", "2/25",
"2/26", "2/27", "2/28", "3/1", "3/2", "3/3", "3/3"), Activity = c("BJJ (Gi)",
"BJJ (Nogi)", "Lifting", "BJJ (Gi)", "BJJ (Gi)", "Lifting", "Lifting",
"BJJ (Gi)", "Tennis", "Lifting", "BJJ (Gi)", "BJJ (Gi)", "BJJ (Gi)",
"Lifting", "BJJ (Gi)", "BJJ (Gi)", "BJJ (Gi)", "BJJ (Nogi)",
"BJJ (Gi)", "Lifting"), Duration = c(90, 90, 40, 60, 60, 40,
40, 120, 30, 30, 75, 90, 90, 45, 140, 70, 120, 60, 60, 30)), row.names = c(NA,
-20L), class = c("tbl_df", "tbl", "data.frame"))
The result looks like the plot below, where it mostly goes in chronological order but puts dates like 2/6 and 2/9 after the rest of February's. I am hoping to make the x-axis fully chronological.
A bonus feature would be showing dates I didn't exercise with values of 0 for duration, but that might be too complicated for right now.
A: log = structure(list(Date = c("2/6", "2/9", "2/11", "2/13", "2/15",
"2/16", "2/17", "2/18", "2/19", "2/19", "2/21", "2/24", "2/25",
"2/26", "2/27", "2/28", "3/1", "3/2", "3/3", "3/3"), Activity = c("BJJ (Gi)",
"BJJ (Nogi)", "Lifting", "BJJ (Gi)", "BJJ (Gi)", "Lifting", "Lifting",
"BJJ (Gi)", "Tennis", "Lifting", "BJJ (Gi)", "BJJ (Gi)", "BJJ (Gi)",
"Lifting", "BJJ (Gi)", "BJJ (Gi)", "BJJ (Gi)", "BJJ (Nogi)",
"BJJ (Gi)", "Lifting"), Duration = c(90, 90, 40, 60, 60, 40,
40, 120, 30, 30, 75, 90, 90, 45, 140, 70, 120, 60, 60, 30)), row.names = c(NA,
-20L), class = c("tbl_df", "tbl", "data.frame"))
Sys.setlocale("LC_TIME", "English")
log$Date = as.Date(paste("2023/",log$Date,sep = ""))
ggplot(log, aes(Date,Duration))+
geom_col(aes(fill=Activity))+
ylab("Duration (min)")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Discord Bot prefix command not working as needed So I am working on a discord bot that uses the "!" prefix to then prompt the user to fill in different fields. However, the code runs fine, and the bot is running but the ! has no effect what so ever. I can use it to do other things within the bot. Like using !Percent 10 100, works fine.
But I want the bot to show field options once the ! is used.
Below is parts of the code that are related to my issue.
from datetime import datetime
import discord
import time
from discord.ext import commands
# Define intents
intents = discord.Intents.default()
intents.members = True
# create bot object
bot = commands.Bot(command_prefix='Wiz ', intents=intents)
# create dictionary to keep track of amounts added by each user
amounts = {}
# command to add ticket amount
@bot.command()
async def add_ticket(ctx):
# ask user to enter the amount charged and ticket name
await ctx.send('Enter the amount charged for the ticket:')
amount = await bot.wait_for('message', check=lambda message: message.author == ctx.author)
await ctx.send('Enter the ticket name:')
ticket_name = await bot.wait_for('message', check=lambda message: message.author == ctx.author)
# calculate 10% of amount
tip = float(amount.content) * 0.1
total = float(amount.content) + tip
# create embed with information
embed = discord.Embed(title="Ticket Information",
description="Here is the information for the ticket you added.", color=0x00ff00)
embed.add_field(name="Tutor Name", value=ctx.author.name, inline=False)
embed.add_field(name="Ticket Name", value=ticket_name.content, inline=False)
embed.add_field(name="Ticket Amount", value=amount.content, inline=False)
embed.add_field(name="Tip Amount", value="{:.2f}".format(tip), inline=False)
embed.add_field(name="Total Amount", value="{:.2f}".format(total), inline=False)
embed.add_field(name="Date", value=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), inline=False)
# send embed to channel
await ctx.send(embed=embed)
# add amount to dictionary
if ctx.author.id in amounts:
amounts[ctx.author.id] += total
else:
amounts[ctx.author.id] = total
# command to show total amount for user
@bot.command()
async def total(ctx):
# check if user has added any amounts
if ctx.author.id in amounts:
# create embed with total amount
embed = discord.Embed(title="Total Amount", description="Here is the total amount you have added.",
color=0x00ff00)
embed.add_field(name="Tutor Name", value=ctx.author.name, inline=False)
embed.add_field(name="Total Amount", value="{:.2f}".format(amounts[ctx.author.id]), inline=False)
# send embed to channel
await ctx.send(embed=embed)
else:
await ctx.send("You haven't added any amounts yet.")
I tried using different prefixes like / and the word Wiz but still none of them worked. I even tried adding a space after the ! to make it like this "! " but that didn't work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Make a command that's only available for the owner of the bot to use, but the bot will send the message said by the user to every guild.bot is in I'm trying to do this from scratch. I am also doing python for this.
Current code:
import discord
import os
from keep_alive import keep_alive
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
prefix = os.environ['PREFIX']
@client.event
async def on_ready():
print(f'Logged in as {client.user}')
await client.change_presence(activity=discord. Activity(type=discord.ActivityType.watching, name='Nothing <3'))
@client.event
async def on_message(message):
if message.author == client.user:
return
keep_alive()
client.run(os.getenv('TOKEN'))
Trying to do the owner command, but it failed and said, something close to object is not in the arguement.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: Expected an int but was 68203991471 at line 1 column 25 path $.series_id I am calling an api, it told me to use id as the endpoint path and the api will encode it to base36.
//const val id: Long = 68203991471
const val base36: String = "vbyw8mn"
interface ApiService {
@GET("v1/series/{id}")
suspend fun getWebtoonApi(@Path("id") id: Long = 68203991471): Response<WebtoonJson>
}
object RetrofitApi {
private val retrofit = Retrofit.Builder()
.baseUrl("https://api.mangaupdates.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val retrofitApi: ApiService = retrofit.create(ApiService::class.java)
}
I tried to change the id to long and string, but it doesn't work.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.webtoon_gacha, PID: 27282
com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: Expected an int but was 68203991471 at line 1 column 25 path $.series_id
at com.google.gson.internal.bind.TypeAdapters$7.read(TypeAdapters.java:228)
at com.google.gson.internal.bind.TypeAdapters$7.read(TypeAdapters.java:218)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:131)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:222)
at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:40)
at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:27)
at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:243)
at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:153)
at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:519)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Suppressed: kotlinx.coroutines.DiagnosticCoroutineContextException: [StandaloneCoroutine{Cancelling}@c36cdc, Dispatchers.Main.immediate]
Caused by: java.lang.NumberFormatException: Expected an int but was 68203991471 at line 1 column 25 path $.series_id
at com.google.gson.stream.JsonReader.nextInt(JsonReader.java:1172)
at com.google.gson.internal.bind.TypeAdapters$7.read(TypeAdapters.java:226)
... 11 more
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Save tensorflow model with TextVectorization layer in h5 format The tensorflow model includes preprocessing layer, TextVectorization that is adapted before the model is build. When trying to save the model in '.h5' format, it shows an error: *NotImplementedError: Save or restore weights that is not an instance of tf.Variable is not supported in h5, use save_format='tf' instead. Received a model or layer TextVectorization with weights.
I'm using tensorflow 2.11.0, the whole code:
import os
import re
import shutil
import string
import tensorflow as tf
import numpy as np
import pandas as pd
url = "https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz"
dataset = tf.keras.utils.get_file("aclImdb_v1.tar.gz", url,
untar=True, cache_dir='.',
cache_subdir='')
dataset_dir = os.path.join(os.path.dirname(dataset), 'aclImdb')
train_dir = os.path.join(dataset_dir, "train")
os.listdir(train_dir)
r = os.path.join(train_dir, "unsup")
shutil.rmtree(r)
test_dir = os.path.join(dataset_dir, "test")
# Train and test datasets
train_ds = tf.keras.utils.text_dataset_from_directory(train_dir,
batch_size=1024)
test_ds = tf.keras.utils.text_dataset_from_directory(test_dir,
batch_size=1024)
# vectorize
MAXTOKEN = 10000
OUTLENGTH = 100
vectorizer = tf.keras.layers.TextVectorization(max_tokens=MAXTOKEN, output_sequence_length=OUTLENGTH)
text_ds = train_ds.map(lambda x, y : x )
vectorizer.adapt(text_ds)
# functional API model
inputs = tf.keras.layers.Input(shape=(1,), dtype=tf.string)
x = vectorizer(inputs)
x = tf.keras.layers.Embedding(input_dim = MAXTOKEN, output_dim = OUTLENGTH)(x)
x = tf.keras.layers.LSTM(32)(x)
output = tf.keras.layers.Dense(1, activation='sigmoid')(x)
nlpmod = tf.keras.Model(inputs, output, name='nlp')
# compile
nlpmod.compile(loss=tf.keras.losses.BinaryCrossentropy(),
optimizer=tf.keras.optimizers.Adam(),
metrics=['accuracy'], run_eagerly=True)
# fit
hist = nlpmod.fit(train_ds, validation_data=test_ds, epochs=2)
# Trying to save - shows the error
nlpmod.save("nlpmod.h5")
I tried to save using downgraded tensorflow version - 2.0, but it doesn't work. Including tf.keras.layers.TextVectorization as a layer in the model didn't worked for me also.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640355",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: (C) How do I include a directory path after a getenv()? I have been trying to figure out how to (in C) put "getenv()" and "/filetest" into one char.
I've thought that you could do it by putting:
char *file = getenv("HOME") + "/filetest";
But, I can't seem to figure it out.
I tried after that to do:
char *file = getenv("HOME") && "/filetest";
But that didn't work either..
Then, I tried:
char *file1 = getenv("HOME");
char *file = file1 + "/filetest";
Could someone please tell me what I am doing wrong?
A: In C, string copy / concatenation is performed by strcpy / strcat:
https://www.tutorialspoint.com/c_standard_library/c_function_strcpy.htm
https://www.tutorialspoint.com/c_standard_library/c_function_strcat.htm
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char file[200];
strcpy(file, getenv("HOME"));
strcat(file, "/filetest");
printf("%s", file);
printf("\n\n");
return 0;
}
A: Allocate a buffer big enough to hold the two strings, and then use strcat() to concatenate string2 to string1:
char buffer[BUFSIZ];
strcat (strcpy (buffer, getenv ("HOME"), "/filetest");
/* OR */
unsigned offset = 0;
strcpy (buffer + offset, tmp);
offset += strlen (tmp);
strcpy (buffer + offset, "/filetest");
Note that getenv() indicates failure by returning a NULL pointer constant, code should check its result before the call to strcpy().
char *tmp = getenv ("HOME");
if (!tmp) {
complain ();
}
/* Now copy. */
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to enable GIT to PostgreSQL in DataGrip? I am making the integration between the database and the **GIT **system. As a database I use postgreSQL and IDE DataGrip. Initially, I made it from **DataGrip **to export all the entities to the .SQL file and it turns out DUMP tables, triggers, functions, etc. Then I apply **Git **to the exported files.
Now the question itself. I don’t like the step with the fact that each time changes in the database should be exported to the .SQL file, can it be somehow bypassed using DataGrip and its plugins? In order to undertake changes to the DBMS itself, and so that everything else understands what changes I have introduced and automatically understands what COMMIT needed.
A number of questions of interest:
*
*Is it possible to realize my idea at all? Because I have not seen before people do the integration between the DBMS itself and the GIT system itself.
*Could it be worth using other versions control tools?
*other approaches to solving my problem
Thank you all in advance for the answers)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: 'vsce' is not recognized as an internal or external command, operable program or batch file." after npm i -g @vscode/vsce" i have just installed vsce using npm install -g @vscode/vsce but after successfully installing cmd is showing this error :
'vsce' is not recognized as an internal or external command,
operable program or batch file.
i have run cmd with administrator because when i try to install without administrator it's showing this error:
npm ERR! code EPERM
npm ERR! syscall mkdir
npm ERR! path C:\Users\User\AppData\Roaming\npm\node_modules\@vscode\.vsce-q9bFjg86
npm ERR! errno -4048
npm ERR! Error: EPERM: operation not permitted, mkdir 'C:\Users\User\AppData\Roaming\npm\node_modules\@vscode\.vsce-q9bFjg86'
npm ERR! [Error: EPERM: operation not permitted, mkdir 'C:\Users\User\AppData\Roaming\npm\node_modules\@vscode\.vsce-q9bFjg86'] {
npm ERR! errno: -4048,
npm ERR! code: 'EPERM',
npm ERR! syscall: 'mkdir',
npm ERR! path: 'C:\\Users\\User\\AppData\\Roaming\\npm\\node_modules\\@vscode\\.vsce-q9bFjg86'
npm ERR! }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It's possible that the file was already in use (by a text editor or antivirus),
npm ERR! or that you lack permissions to access it.
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\ChetanKK\AppData\Local\npm-cache\_logs\2023-03-05T05_06_01_324Z-debug-0.log
i want to publish my vscode theme on marketplace
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python, plot data versus month & year Say I have a simple df, with columns 'month', 'year', and 'value'. with matplotlib, I want to plot 'value' versus BOTH 'month' and 'year' simultaneously (unsure if this is the right way to phrase this) to achieve a plot that looks like something akin to this
Notice how the x-axis only reads 'year', but in reality each 'value' corresponds to both a month and a year.
The way I thought to solve this would be to simply convert the month and year to a datetime, but I cannot do this since I have no "day" field to fill in in the datetime. Help would be appreciated as I feel this should be quite simple and I'm missing something obvious
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I am trying to load a bean of class simpleurlhandlermapping, But i couldn't find any logs from that class. How to check if the handlers are mapped? I am trying to load a bean of class simpleurlhandlermapping, But i couldn't find any logs from simpleurlhandlermapping class. How to check if the handlers are mapped?
I tried loading the same bean without declaring any property(mappings,urlmap), I don't find any logs from simpleurlhandlermapping class even in this case. I think, i should be receiving the below warning in this case.
WARNING: Neither 'urlMap' nor 'mappings' set on SimpleUrlHandlerMapping.
can someone help me in understanding why i can't find any logs.
Thanks in advance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: My macros work fine except when I click an item in a ListBox. Then the same code won't work I'm reconciling a database with pay period reports with 3 different depts on 3 different sheets. I autofilter the pay period reports so I can compare the pay details with the database information on one sheet. There are 3 departments 2593,2591, and 2590. My macros autofilter the employees pay cheque details when I click the "Next" and "Previous" Button on Sheet1. It all works fine. I also have userform with a ListBox, so that I can manually select a particular employee rather than clicking "Next" through the list. But the macros won't work and nothing is autofiltered.
In particular I get the Error Message 1004 Unable to get the CurrentRegion property of the Range Class.
I have tried qualifying the workbooks/worksheets but it still doesn't work.
Sub ClearForNextRecord()
Dim rng As Range
'set the range on the REVIEW sheet to display the employee records and clean up range before the next record
Set rng = Sheet1.Range("A15")
rng.CurrentRegion.Clear '--ERROR APPEARS AT THIS LINE
Application.CutCopyMode = False
'Start the extraction of records from the dept sheet onto the REVIEW sheet
Call Copy_AutoFiltered_VisibleRows_NewSheet
End Sub
I was expecting the macros to work the same way as when I click on the "Next" and "Previous" Buttons on the Userform. The ListBox is not working. I am fairly new to VBA and I'm sure I'm missing something quite simple Any help will be greatly appreciated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Undefined array key error in php Warning. Please let me know where I'm going wrong in the code Warning: Undefined array key "submit" in C:\xampp\htdocs\crud\input_info.php on line 564
Connection is established but I'm getting the above warning as an error due to which I'm uable to store data in the database.
<div class="container">
<form action="" method="POST">
<h3>Enter the following details :</h3>
<form autocomplete="off" action="">
<div class="autocomplete" style="width:300px;">
<label for="school">School :</label> <br>
<input id="school" type="text" name="School" placeholder="Enter School" required>
</div>
</form>
<br>
<form autocomplete="off" action="">
<div class="autocomplete" style="width:300px;">
<label for="school_ID">School ID :</label> <br>
<input id="school_ID" type="text" name="School_ID" placeholder="Enter School ID" required>
</div>
</form>
<br>
<label for="class">Class :</label>
<select name="Class" id="class">
<option value="I">I</option>
<option value="II">II</option>
<option value="III">III</option>
<option value="IV">IV</option>
<option value="V">V</option>
</select>
<label for="sec">Sec : </label>
<select name="sec" id="sec">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<br><br>
<label for="Film_1">Film 1 :</label> <br>
<input id = "Film_1" type= "text" placeholder="Enter film 1" name="Film_1" required>
<br>
<br>
<label for="Film_2">Film 2 (if applicable) :</label><br>
<input id = "Film_2" type="text" placeholder="Enter film 2" name="Film_2">
<br>
<br>
<label for="Film_3">Film 3 (if applicable) :</label><br>
<input id = "Film_3" type="text" placeholder="Enter film 3" name="Film_3">
<br>
<br>
<input type="file" onchange="readURL(this)" accept="image/*" name="Picture">
<button id="submit_btn" type="submit" value="submit" name="submit">Submit</button>
</form>
</div>
</body>
<?php
if($_POST['submit']){
$School = $_POST['School'];
$School_ID = $_POST['School_ID'];
$Class = $_POST['Class'];
$sec = $_POST['sec'];
$Film_1 = $_POST['Film_1'];
$Film_2 = $_POST['Film_2'];
$Film_3 = $_POST['Film_3'];
$Picture = $_POST['Picture'];
$query = "INSERT INTO test_kant VALUES('$School','$School_ID','$Class','$sec','$Film_1','$Film_2','$Film_3','$Picture')";
$data = mysqli_query($conn, query);
if($data){
echo "Data Inserted Succesfully!";
}
else{
echo"Data Insertion Failed!";
}
}
?>
Why am I getting undefined array key "submit" error?
Please help me with the code, I'm unable to detect the error. Connection is established but I'm getting this warning.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Converting the fetched data using fetch() to JavaScript array of maps I want to fetch the contributors of a GitHub repository using GitHub API and JavaScript. I am able to fetch the data but I need that data as JS valid data type so that I can manipulate it according to my needs. The fetched data is basically array of objects so I am not able to use it as an array of Maps.
async function fetchData() {
const token = '<GitHub Token>';
fetch('https://api.github.com/repos/Bitwarden/mobile/contributors', {
headers: {
'Authorization': `${token}`
}
})
.then(response => response.json())
.then(data => {
console.log(data);
return data;
})
.catch(error => console.error(error));
}
//let data = new Map(Object.entries(fetchData()))
const data = fetchData()
let map1 = new Map()
for(let i=0;i<30;i++) {
map1.set(data[i], data[i].contributions)
}
console.log(map1)
It is giving the error as
Uncaught TypeError: fetchData(...).values is not a function
at script.js:19:26
Can anyone help me convert the fetched array of objects to an array of maps so that I can use it throughout the program?
A: One-liner:
const data = (await fetchData()).map(obj => new Map(Object.entries(obj)));
About fetchData, it needs to be modified a bit:
async function fetchData() {
const token = '<GitHub Token>';
const response = await fetch('https://api.github.com/repos/Bitwarden/mobile/contributors', {
headers: {
Authorization: `${token}`
}
});
const data = await response.json();
return data;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When using version 3.0.3 of the Spring Boot starter web, the version of Spring Core is 5.3.24 instead of the expected 6.0.5 I'm using Spring Boot 3.0.3 and I've noticed that while the spring-boot-starter-parent dependency has version 3.0.3, the spring-core and spring-web dependencies have version 5.3.24 instead of 6.0.5. I'm using modules where the parent of the parent pom is spring-boot-starter-parent 3.0.3 and the parent of the child poms is the BOM pom file. Why is this happening and how can I ensure that all dependencies use the latest version of Spring Core?
How can I auto-configure the spring-core dependency version to 6.0.5 in my Spring Boot project without manually adding it to the pom.xml file
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: For some reason my code just display one time, when I refresh the page i am starting to get errors
import React from "react";
import { useParams } from "react-router-dom";
import { useState, useEffect } from "react";
const SingleUser = () => {
const [user, setUser] = useState([]);
const { username } = useParams();
useEffect(() => {
const getSingleUser = async () => {
try {
const res = await fetch(
`https://api.chess.com/pub/player/${username}/stats`
);
const data = await res.json();
const heroesArray = Object.values(data);
setUser(heroesArray);
console.log(heroesArray[0].last);
} catch (error) {
console.error(error);
}
};
getSingleUser();
}, []);
return (
<section>
<div>
<h1>Rapid Chess</h1>
<p>Current Rating: {user[0].last.rating}</p>
<p>Best Rating: {user[0].best.rating} </p>
<div>
<p>Wins: {user[0].record.win} </p>
<p>Losses: {user[0].record.loss} </p>
<p>Draws: {user[0].record.draw} </p>
</div>
</div>
</section>
);
};
export default SingleUser;
For some reason my code just display one time, when I refresh the page i am starting to get errors. I think it is something about useEffect but I don't know
TypeError: Cannot read properties of undefined (reading 'last') . I get these error.
A: The error message "TypeError: Cannot read properties of undefined (reading 'last')" is indicating that you are trying to access the property 'last' of an undefined object. This is likely because the user state is initially an empty array, and the API request has not completed yet, so user[0] is undefined. You can add a conditional rendering to handle this scenario and wait for the API response to complete before displaying the user data.
Here's an updated version of your code that adds conditional rendering:
import React from "react";
import { useParams } from "react-router-dom";
import { useState, useEffect } from "react";
const SingleUser = () => {
const [user, setUser] = useState([]);
const { username } = useParams();
useEffect(() => {
const getSingleUser = async () => {
try {
const res = await fetch(
`https://api.chess.com/pub/player/${username}/stats`
);
const data = await res.json();
const heroesArray = Object.values(data);
setUser(heroesArray);
console.log(heroesArray[0].last);
} catch (error) {
console.error(error);
}
};
getSingleUser();
}, [username]);
if (user.length === 0) {
return <p>Loading...</p>;
}
return (
<section>
<div>
<h1>Rapid Chess</h1>
<p>Current Rating: {user[0].last.rating}</p>
<p>Best Rating: {user[0].best.rating} </p>
<div>
<p>Wins: {user[0].record.win} </p>
<p>Losses: {user[0].record.loss} </p>
<p>Draws: {user[0].record.draw} </p>
</div>
</div>
</section>
);
};
export default SingleUser;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can't type on input field in React after close then open it again I have created a search box using a form input tag in react, I use Tailwindcss and Motion Framer for handling the animation. The search box will not appear until I click a button search and it will be closed after I click the Xmark button. I still can type on the input when the first try I open the search box, but after I close and open it again I can't type anymore.
enter image description here
{/* Login and Search Button Start */}
<div className="hidden md:block">
{!isSearchOpen && (
<AnimatePresence>
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="md:flex md:items-center md:gap-3"
>
<button
onClick={() => setIsSearchOpen(!isSearchOpen)}
className="cursor-pointer flex items-center justify-between gap-2 w-32 px-3 h-8 bg-gray-200 hover:bg-gray-300 border border-solid border-gray-200 rounded-lg"
>
<span className="text-green-900 font-medium">Search</span>
<MagnifyingGlassIcon className="h-5 w-5 text-green-900" />
</button>
<LoginButton />
</motion.div>
</AnimatePresence>
)}
{isSearchOpen && (
<AnimatePresence>
<motion.div
initial={{
width: 0,
opacity: 0,
}}
animate={{
width: "auto",
opacity: 1,
}}
exit={{
width: 0,
opacity: 0,
}}
className="md:flex"
>
<form>
<input
placeholder="Search for workshops, articles, and videos"
type="text"
className="md:w-96 md:px-3 md:mr-3 md:h-7 md:bg-gray-300 md:border-solid md:border-gray-200 md:rounded-lg md:text-sm"
/>
</form>
<button onClick={() => setIsSearchOpen(!isSearchOpen)}>
<XMarkIcon
onClick={() => setIsMobOpen(!isMobOpen)}
className="md:h-7 md:w-7 md:text-green-900 md:cursor-pointer"
/>
</button>
</motion.div>
</AnimatePresence>
)}
</div>
{/* Login and Search Button End */}
I expected that I still can't type when the search box closed and opened again.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Visual Studio Added Captions in wrong places My Visual Studio has started adding these strange captions in places where they don't belong. Is this an add-on that I have? How do I stop this? Maybe if I knew what these things were called I could research it but I don't even know where to start without a name.
On this page it appears to be working correctly, but if I can just turn it off for all pages that would be best as the places where it gets it wrong is quite annoying.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Angular - Search filter does not correspond with pagination in ngx-pagination I am implementing ngx-pagination with server side pagination in ASP.NET Core-6 Web API. Precisely, I have a search text input. I have this code:
JSON Response:
{
"data": {
"pageItems": [
{
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"auditType": "string",
"actionPerformed": "string",
"actionPerformedTime": "2022-10-28T05:54:12.830Z"
}
],
"currentPage": 1,
"pageSize": 10,
"numberOfPages": 3,
"totalRecord": 33
},
"successful": true,
"message": "string",
"statusCode": 0
}
model:
export interface IPageItem {
id: string;
auditType: string;
actionPerformed: string;
actionPerformedTime: Date;
}
export interface IData {
pageItems: IPageItem[];
pageSize: number;
currentPage: number;
numberOfPages: number;
totalRecord: number;
}
export interface IAuditList {
data: IData;
successful: boolean;
message: string;
statusCode: number;
}
service:
getAllAuditsPagination(pageNumber?: number,pageSize?: number): Observable<IAuditList[]> {
return this.http.get<IAuditList[]>(this.baseUrl + '/users/all-audits?pagenumber='+ pageNumber+'&pageSize='+pageSize);
}
component.ts:
allAuditList: any[] = [];
dataBk: IPageItem[] = this.allAuditList;
pageSize: number = 10;
currentPage: number = 1;
numberOfPages!: number;
totalRecords: number = 0;
pageSizes = [10, 20, 50, 100];
selectedName: string = '';
handlePageChange(event: number): void {
this.currentPage = event;
this.loadAllAudits();
}
handlePageSizeChange(event: any): void {
this.pageSize = event.target.value;
this.currentPage = 1;
this.loadAllAudits();
}
onAuditSearch() {
this.allAuditList = this.dataBk.filter(
(row) =>
row.auditType
?.toLowerCase()
.includes(this.selectedName?.toLowerCase())
);
}
loadAllAudits() {
this.auditService.getAllAuditsPagination(this.currentPage, this.pageSize).subscribe({
next: (res: any) => {
this.allAuditList = res.data.pageItems;
this.totalRecords = res.data.totalRecord;
this.currentPage = res.data.currentPage;
this.pageSize = res.data.pageSize;
this.dataBk = res.data.pageItems;
this.isLoading = false;
}
})
}
component.html:
<div class="row">
<div class="col-sm-6 col-xs-6 col-6">
<div class="form-group">
<label for="auditType">Audit Type:</label>
<input
type="text"
autocomplete="off"
class="form-control"
id="auditType"
[(ngModel)]="selectedName"
(input)="onAuditSearch()"
placeholder="auditType"
/>
</div>
</div>
</div>
<tr
*ngFor="
let row of allAuditList
| paginate
: {
itemsPerPage: pageSize,
currentPage: currentPage,
totalItems: totalRecords
}
| orderBy : order : reverse : caseInsensitive;
let i = index
"
>
<div class="row">
<div class="col-md-6">
<pagination-controls
previousLabel="Prev"
nextLabel="Next"
[responsive]="true"
(pageChange)="handlePageChange($event)"
>
</pagination-controls>
</div>
<div class="col-md-4">
Items Per Page:
<select (change)="handlePageSizeChange($event)">
<option *ngFor="let size of pageSizes" [ngValue]="size">
{{ size }}
</option>
</select>
</div>
</div>
In the component.html, when user types in the text input field for search in auditType ([(ngModel)]="selectedName"), the the items in the page changes (this is working), but the pagination (1,2,3,...6) remains the same.
How do I correct this?
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Module 'networkx.algorithms.community' has no attribute 'greedy_modularity_communities' A few months ago I used the module
networkx.algorithms.community.greedy_modularity_communities(G)
to detect communities within a graph G in python3.8. I had used networkx version 1.8.1 or 2.1 (I cannot remember clearly). I tried running the same code again but got the error "module 'networkx.algorithms.community' has no attribute 'greedy_modularity_communities'". I made the mistake of uninstalling networkx and trying different versions without checking my old networkx version and thus cannot remember the exact version. However, I get this error in networkx versions 1.8 and 2.1.
What could be causing this and how can I fix it?
Thank you in advance!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SoundPlayer.Play makes no sound in a Visual Studio debugger thread I am trying to play a sound (wav file) in a thread in a test method in Visual Studio. The code below in the test method tries to play the sound file three times. The first play works fine and demonstrates the code that is in the PlaySound method. The second play of the sound also works fine and demonstrates that the PlaySound(path) method works okay.
But the third attempt to play the sound by calling the helper method in a Task fails to play any sound. The code appears to work fine and call the player, etc. But there is no sound. I am wondering if the task thread has access to the speakers or something.
Is it possible to play a sound on a thread in the VS debugger? Thank you.
// play the sound the first time and it works fine async with Play()
// this is the same code as in the PlaySound(path) helper method.
using (var simpleSound = new SoundPlayer(path)) {
try {
simpleSound.Load();
simpleSound.Play(); // async play is okay, PlaySync works too
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
// wait 4 seconds and play it again - works fine
Thread.Sleep(4000);
PlaySound(path);
// call it in a task in Visual Studio and there is no sound heard.
// Neither Play() nor PlaySync() works in the thread.
// Do threads in the VS debugger have access to the speaker?
// What can I do to make this example work?
var t1 = new Task(() => PlaySound(path));
t1.Start();
Task.WaitAll();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NEMO network mobility in omnet++ Can anyone please give me some ideas about NEMO network mobility implementation or is it an outdated protocol?
Hope, I will get your response.
Regards
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does the dependency declared in libs.versions.toml not work in subprojects? I'm writing a build script for a multi-module project using gradle 8.0.2, declaring some dependencies in the libs.versions.toml file, and my build script is as follows
buildscript {
repositories {
gradlePluginPortal()
maven {
url = uri("https://plugins.gradle.org/m2/")
}
}
dependencies {
classpath("gradle.plugin.com.github.johnrengelman:shadow:7.1.2")
}
}
plugins{
`kotlin-dsl`
}
group = "xxx"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_19
subprojects {
apply(plugin = "java")
apply(plugin = "checkstyle")
apply(plugin = "maven-publish")
apply(plugin = "com.github.johnrengelman.shadow")
// common deps + repos
repositories {
mavenCentral()
}
dependencies {
api(libs.jsr305)
testImplementation(libs.bundles.junit)
compileOnly(libs.lombok)
annotationProcessor(libs.lombok)
testCompileOnly(libs.lombok)
testAnnotationProcessor(libs.lombok)
}
java {
withSourcesJar()
}
tasks.named<Test>("test") {
useJUnitPlatform()
}
tasks.withType<JavaCompile>() {
options.encoding = "UTF-8"
}
tasks.withType<Javadoc>() {
options.encoding = "UTF-8"
}
}
I want to apply these common dependencies in each subproject, which are defined in libs.versions.toml, and I can guarantee that libs.versions.toml is written without problems, but I can't get it to work in subprojects
Error:
Extension with name 'libs' does not exist. Currently registered extension names: [ext, base, defaultArtifacts, sourceSets, reporting, javaToolchains, java, testing, checkstyle, publishing, shadow]
* Try:
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
* Exception is:
org.gradle.api.UnknownDomainObjectException: Extension with name 'libs' does not exist. Currently registered extension names: [ext, base, defaultArtifacts, sourceSets, reporting, javaToolchains, java, testing, checkstyle, publishing, shadow]
A: Sorry this is a duplicate issue, I've found a solution for it
How can I use gradle versions file for multimodule gradle app?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cannot import in vsc So I just started coding (Python) recently and I downloaded VSC for the first time. But as I was trying to import (as in for example 'import numpy', the numpy (all of them in my case) are colored a bit grayish and I cannot use them.
I tried re downloading to no avail, It's working perfectly fine in Jupyter and/or Spyder, just not on VSC. I hope I can start using them
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: recursion method that returns a string after changing every other letter from uppercase or lowercase Change a strings character from every other letter from uppercase to lowercase using recursion and return that string. im trying to expand on my knowledge of recursion i know i could do this without it, but im wondering how you do it this way, this is what i have so far
public static String camelCaseRecursive(String w){
if(w.length()==0) {
return "";
}
char sec = 0;
String returned_str = "";
char ch = w.charAt(0);
if (w.length() > 1) {
sec = w.charAt(1);
}
;
String remaining_str = w.substring(1);
returned_str = camelCaseRecursive(remaining_str);
if(ch >= 'A' && ch <='Z' && sec >= 'a' && sec <='z' ) {
ch = Character.toLowerCase(w.charAt(0));
returned_str = ch+returned_str;
}
else if((ch >= 'A' && ch <='Z') && (sec >= 'A' && sec <='Z') ){
ch = Character.toLowerCase(w.charAt(0));
returned_str = ch+returned_str;
}
else if((ch >= 'a' && ch <='z') && returned_str.length() %2 !=0){
ch = Character.toUpperCase(w.charAt(0));
returned_str = ch+returned_str;
}
else{
returned_str = ch+returned_str;
}
return returned_str;
}
what i expect is
input:(Hello World) output:(hElLo wOrLd)
input:(Even) output:(eVeN)
what i get is
input:(Hello World) output:(hElLo wOrLd)
input:(Even) output:(evEn)
i know that the reason i get what i get is because of returned_str.length() %2 !=0 giving odd numbers and if use == it does it for even strings. is there a way to do both or know when to use the appropriate one base on the first call? the thing is i don't know how you would go about alternating between uppercase and lowercase in recursion without having some sort of counter to keep track. Is is possible to set a method that can alternate between upper and lower case, or set a condition that knows when to do so using the length of the string or maybe reading it like a subscript or compare or something?
A: One way to do it is to use a private helper method passing additional arguments.
We pass the index of the string to process and to avoid string concatenation, we build the resultant string using a StringBuilder.
public static String camelCaseRecursive(String s) {
return camelCaseRecursiveHelper(s, 0, new StringBuilder());
}
private static String camelCaseRecursiveHelper(String s, int i,
StringBuilder stringBuilder) {
if (i == s.length()) {
return stringBuilder.toString();
} else {
Character curr = s.charAt(i);
if (Character.isLetter(curr)) {
curr = i % 2 == 0
? Character.toLowerCase(curr)
: Character.toUpperCase(curr);
}
stringBuilder.append(curr);
return camelCaseRecursiveHelper(s, i + 1, stringBuilder);
}
}
We check if the current index is even or odd and based on that, we do the case-conversion.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to export matlab data to excel sheets I have a data file with 9 x 1 cell array
fn =
9×1 cell array
{'speed' }
{'duration' }
{'exercise' }
{'gender' }
{'angles'}
{'region' }
{'space' }
{'subject' }
{'cost' }
When I use the code below, only one of the data is written to the first worksheet of the excel workbook. For instance the code below will write only the gender into the first sheet.
data=load('S9_E3_A1.mat');
fn=fieldnames(data) %get all variable names
%firstdiff=data.(fn{4}); %get the first variable
%xlswrite('hand_data_2.xlsx', firstdiff); %write it
Can anyone please help me, I will like to write all the varaibles into the differente sheets of an excel workbook.
Thank you
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: android app with voice command that shows current location and locate destinations I am completely new to programming and just started last month and my professor decided to suddenly gave us a project to do an individual android app that needs to do the following, but I don't know where to start.
PS I already have android studio and the following misc installed.
Tried online tutorial but I lag learning when I watch and would rather read.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Change custom Ajax Add to Cart button after add to cart in WooCommerce I use code that changes the text and its color after adding an item to cart - Change custom Ajax Add to Cart button text after add to cart in WooCommerce
/* Changing the Add to cart button text for catalogs and categories */
add_filter( 'woocommerce_product_add_to_cart_text', 'new_products_button_text', 20, 2 );
function new_products_button_text( $text, $product ) {
if ( is_admin() && is_null( WC()->cart ) ) {
wc_load_cart();
}
if(
$product->is_type( 'simple' )
&& $product->is_purchasable()
&& $product->is_in_stock()
&& WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( $product->get_id() ) )
) {
$text = 'Already in cart';
}
return $text;
}
/* Change the Add to cart button text for the product page */
add_filter( 'woocommerce_product_single_add_to_cart_text', 'new_single_product_button_text' );
function new_single_product_button_text( $text ) {
if( WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( get_the_ID() ) ) ) {
$text = 'Already in cart';
}
return $text;
}
add_action( 'wp_footer', 'action_wp_footer' );
function action_wp_footer() {
?>
<script>
jQuery(document).ready(function($) {
var selector = '.add_to_cart_text:contains("Already in cart")';
// Selector contains specific text
if ( $( selector ).length > 0 ) {
$( selector ).addClass( 'product-is-added' );
} else {
$( selector ).removeClass( 'product-is-added' );
}
});
</script>
<?php
}
add_action( 'wp_footer', 'ajax_button_text_js_script' );
function ajax_button_text_js_script() {
$text = __('Already in cart', 'woocommerce');
?>
<script>
jQuery(function($) {
var text = '<?php echo $text; ?>', $this;
// If the button on the product list page
$('.ajax_add_to_cart').click(function() {
$(document.body).on('click', '.ajax_add_to_cart', function(event){
$this = $(this); // Get button jQuery Object and set it in a variable
});
$(document.body).on('added_to_cart', function(event,b,data){
var archiveButtonText = '<span class="add_to_cart_text product-is-added">'+text+'</span>';
// change inner button html (with text) and Change "data-tip" attribute value
$this.html(archiveButtonText).attr('data-tip',text);
});
});
// If the button on the single product page
$('.single_add_to_cart_button').click(function() {
$(document.body).on('click', '.single_add_to_cart_button', function(event){
$this = $(this); // Get button jQuery Object and set it in a variable
});
$(document.body).on('added_to_cart', function(event,b,data){
var detailButtonText = '<span class="add_to_cart_text product-is-added">'+text+'</span>';
// change inner button html (with text) and Change "data-tip" attribute value
$this.html(detailButtonText).attr('data-tip',text);
});
});
});
</script>
<?php
}
Unfortunately, I can't do the same for the add to cart button. I need to change the color not of the text, but of the whole button.
Here is the html code of my button:
<a href="?add-to-cart=542" data-quantity="1" class="button wp-element-button product_type_simple add_to_cart_button ajax_add_to_cart add-to-cart-grid btn-link" data-product_id="542" data-product_sku="TB20/320 IN" rel="nofollow">
<span class="add_to_cart_text">Add to cart</span>
</a>
I tried to replace .add_to_cart_text with .add_to_cart_button in the code, but the color of the button changes only when the page reloads.
I would be glad to have your help!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Hello, Kindly help me what to do? I am so confused!! What should I do ??
Devops or Data Science or Machine learning ?
I am ready to do any but which would be easy to do?
I am not getting which one has more advantages by putting future aspects to considered!
A: Demand: All three of these career paths are in high demand, but the level of demand may vary depending on your location and industry. You may want to research job openings in your area to get a better idea of the demand for each of these roles.
Salary: Salaries for DevOps, Data Science, and Machine Learning can vary depending on your experience, location, and industry. You may want to research average salaries for each of these roles in your area to help you make a decision.
Future growth: All three of these fields are expected to continue growing in the future, but the rate of growth may vary. You may want to research industry trends and predictions to get a better idea of the future growth potential of each field.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WAMP + Windows 11 (64bit) + PHP 8.1.0. + SQL Server + Laravel : PDOException - could not find driver I am using WAMP (64 Bit) on Windows 11 (64bit) , and PHP 8.1.0.
I downloaded the zip file from Microsoft website
I copied php_sqlsrv_81_ts_x64.dll and php_pdo_sqlsrv_81_ts_x64.dll to extension_dir.
I added these lines
extension=php_sqlsrv_81_ts_x64.dll
extension=php_pdo_sqlsrv_81_ts_x64.dll
to php.ini files at
1. wamp64\bin\php\php8.1.0
2. wamp64\bin\apache\apache2.4.51\bin
I checked phpinfo, and it shows:
I added proper information to .env, but still dd(DB::connection()->getPdo()); throws exception:
PDOException
could not find driver
and if I call dd(DB::availableDrivers());, it shows:
What am I missing?
I tried restarting the services, and even restarting the computer, still no luck.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: duckdb getting 'Error: IO Error: Frame requires too much memory for decoding' error when reading very large files I'm trying to read a month's worth of Reddit data from Pushshift. These files are around 30gigs, compressed (zst format) of json data. I am trying to convert these files to parquet.
Here is the code:
time ~/prog/duckdb -c "copy (select created_utc, body, author, subreddit, parent_id, id from read_ndjson_auto('RC_2022-01.zst')) to 'RC_2022-01.parquet' (format 'PARQUET', CODEC 'ZSTD')"
The weird thing is, I can process the most recent file just fine. This file also happens to be the biggest. Perhaps something changed in the zst parameters they used to compress the file. This also implies that this isn't a bug in duckdb.
However, I do need to know how to change framesize or increase memory available to the zst module. Not sure how to control that in duckdb.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: systems analysts need to be able to distinguish between laws, policies, and procedures. Why is this important? In identifying and documenting business requirements, systems analysts need to be able to distinguish between laws, policies, and procedures. Why is this important?
In identifying and documenting business requirements, systems analysts need to be able to distinguish between laws, policies, and procedures. Why is this important?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Trying to upload a vite project to git hub pages, but command line says You need to run this command from the toplevel of the working tree this error occurred after I ran git subtree push --prefix dist origin gh-pages, i was following along with this article. below is a photo of my files as well as the command line. not sure how to properly deploy
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I write good codes about making function that counts vowels in a word? I want to create a function named countVowels that takes string as a parameter named word and returns the number of vowels in the word.
I came up with two solutions but I don't know if they are good solutions or not.
I guess I don't even know how to judge what 'good' code is.
My question is ...
*
*What could be the problems of the solutions I came up with?
*If they are not ideal, what are ideal codes in this case and why?
These solutions are what I came up with, but I don't know if they are good solutions or not.
I guess I don't even know how to judge what 'good' code is.
Can I get some code reviews on these ones? What could be the problems of the solutions I came up with?
First solution
function countVowels(word){
let vowels = ["a","e","i","o","u"];
let index = 0;
for (let i = 0; i < word.length; i++){
for (let j = 0; j < vowels.length; j++){
if (word[i] == vowels[j]){
index += 1;
}
}
}
return index;
};
Second solution
function countVowels(word){
let vowels = ["a","e","i","o","u"];
let index = 0;
for (let i = 0; i < word.length; i++) {
if (vowels.includes(word[i])) {
index += 1;
}
}
return index;
};
A: I prefer a regex replacement approach here:
function countVowels(word) {
return word.length - word.replace(/[aeiou]/gi, "").length;
}
var input = "peninsula";
var numVowels = countVowels(input);
console.log(input + " has " + numVowels + " vowels.");
Here we define the number of vowels in an input string as being the original length minus the length of the same input with all vowels removed.
A: Your second solution is much easier to read and understand.
Here's another solution I can come up with, similar to your second solution but without the for loop:
function countVowels(word) {
const vowels = ["a", "e", "i", "o", "u"];
const foundVowels = [...word].filter((char) => vowels.includes(char))
return foundVowels.length
};
console.log(countVowels("peninsula"))
A:
function countVowels(word){
return word.split("").filter(e=>(new RegExp(/[aeiou]/)).test(e)).length;
}
console.log(countVowels("peninsula"));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Hadoop streaming Python Mapper and reducer error message print. Is that possible? Hello everyone and thank you for your time first.
I am working on a Hadoop streaming job with a python mapper and reducer.
Therefore my command looks like
yarn jar /where/hadoop-version/blahblah/hadoop-streaming.jar. -files mapper.py,reducer.py -mapper mapper.py -reducer reducer.py -input input.txt -output output
However, Hadoop streaming doesn't give me a helpful error message when my python code has a problem. For example, if I have any typo in my mapper.py or if my for loop is out of the range of the list. Hadoop just gives me back a java error that I cannot understand.
Is there any technique that shows a python error message?
Thank you!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Having issue displaying the information of a form in Android Studio I have written the following code in Android Studio to print the information of a register form:
package com.example.session8_project1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class RegisterButtonActivity extends AppCompatActivity {
Button btn;
EditText Name, LastName, Email, Password;
RadioGroup genderRadioGroup;
RadioButton genderRadioButton;
CheckBox chk;
int genderId;
Boolean Conditions;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_button);
btn = findViewById(R.id.reg_button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
chk = findViewById(R.id.CheckBoxConditions);
// Find Ids
Name = findViewById(R.id.NameText);
LastName = findViewById(R.id.LastNameText);
Email = findViewById(R.id.EmailText);
Password = findViewById(R.id.PasswordText);
// Convert to String
String name = Name.getText().toString();
String lastname = LastName.getText().toString();
String email = Email.getText().toString();
String password = Password.getText().toString();
genderRadioGroup = findViewById(R.id.RadGrp);
genderId = genderRadioGroup.getCheckedRadioButtonId();
genderRadioButton = findViewById(genderId);
String gender = genderRadioButton.getText().toString();
// Check whether the Checkboxes are selected or not.
// Conditions = chk.isChecked();
Conditions = chk.isSelected();
Intent in = new Intent(RegisterButtonActivity.this, ResultActivity.class);
in.putExtra("name ", name);
in.putExtra("lastname ", lastname);
in.putExtra("email ", email);
in.putExtra("password ", password);
in.putExtra("gender ", gender);
in.putExtra("Conditions ", Conditions);
startActivity(in);
}
});
}
}
And the activity to which this code is applying is as follows:
package com.example.session8_project1;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class ResultActivity extends AppCompatActivity {
TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
Bundle extras = getIntent().getExtras();
result = findViewById(R.id.ResultText);
if (extras != null){
result.setText(extras.getString("name") + "\n" +
extras.getString("lastname" )+ "\n" +
extras.getString("email") + "\n" +
extras.getString("password") + "\n" +
extras.getString("gender") + "\n" +
extras.getBoolean("Conditions"));
}
}
}
When I fill the information of the form, it will give me the null result. I do not know why? is there something wrong?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Batch file to conditionally rename files inside folders using folder name and if multiples append a text string and numbering I have a folder containing thousands of folders.
In each of those folders, there is a single .nfo file as well as one or multiple files of extension .t64
The .nfo should always be renamed to the folder name.
If there is only one .t64 file in the folder, I need it to be renamed to the exact folder name as well.
However if (and only if) there are 2 or more .t64 files in that folder, they need to have as a name the folder name followed by " (Disk A of B)" where A starts at 1 and gets incremented up to the total number of .t64 files in that folder and B is the number of .t64 files in that folder. (so for example, Disk 1 of 3, then Disk 2 of 3 and finally Disk 3 of 3).
Would anyone be so kind as to give me a batch code that could accomplish this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: strtok_r() in c is apparently skipping tokens? I have a program meant to take in a file (WarandPeace.txt), read it into a given number of threads, and process it into a list of words and a count of each word. I open the file separately in each thread, read a chunk of it into a string with pread(), then break the string into tokens with strtkn_r(). I add the tokens to the list, incrementing where I find the same token repeated, and then finally combine the lists from each thread into a single list.
My problem is that as far as I can tell strtok_r is failing to count various words accurately for some reason. As an example, I know the word "princess" occurs 937 times in the file, but in my code strtok_r only appears to pick it up about 300 times. The error persists irrespective of how many threads I run the program with. It doesn't seem to be a problem with adding tokens to the list because when I do a printf("%s,%i",token, count) as I process the string I get the same reduced count.
My code follows below. The use of strtok_r() is early in readFile()
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
// You may find this Useful
char * delim = "\"\'.“”‘’?:;-,—*($%)! \t\n\x0A\r";
// This struct holds a word from the file and its count, as well as a pointer
// to another word, in order to create a singly-linked list of words
struct Word {
char * word;
int count;
struct Word * next;
};
typedef struct Word Word;
// This struct holds the information passed to each thread as well as a pointer
// to the final shared list to be created, one of these will be created
// for each thread
struct ThreadRecord {
int totalThreads;
int thisThread;
Word ** listHead;
char * fileName;
};
typedef struct ThreadRecord ThreadRecord;
// This is the function passed into each thread that does the main work of
// the program
void * readFile( void * threadRecordVoid );
// this function runs after the threads have returned and sorts the completed
// list by size of count
void sortListBySize( Word ** listHead );
// This function runs as part of readFile and combines the multiple thread's
// list of words into a single combined list of words
void combineList (Word ** combinedList, Word ** transferList);
int main (int argc, char *argv[])
{
//***TO DO*** Look at arguments, open file, divide by threads
// Allocate and Initialize and storage structures
char * fileName = argv[1];
char * ptr;
int threadCount = (int)strtol(argv[2], &ptr, 10);
// The list pointer we pass to every thread to make our combined list
Word * listHead = NULL;
// A threadRecord created for every thread passing in that thread's number
// the total number of threads and the filename, which will allow each
// thread to access the file at the appropriate place.
ThreadRecord * threadRecords[threadCount];
for(int i = 0; i < threadCount; i++){
threadRecords[i] = malloc(sizeof(ThreadRecord));
threadRecords[i]->totalThreads = threadCount;
threadRecords[i]->thisThread = i;
threadRecords[i]->fileName = fileName;
threadRecords[i]->listHead = &listHead;
}
//**************************************************************
// DO NOT CHANGE THIS BLOCK
//Time stamp start
struct timespec startTime;
struct timespec endTime;
clock_gettime(CLOCK_REALTIME, &startTime);
//**************************************************************
// *** TO DO *** start your thread processing
// wait for the threads to finish
pthread_t threads[threadCount];
int threadReturn[threadCount];
// We run our threads, calling readFile
for (int i = 0; i < threadCount; i++){
threadReturn[i] = pthread_create( &threads[i], NULL, readFile, (void*) threadRecords[i]);
}
// we wait on our threads
for (int i = 0; i < threadCount; i++){
pthread_join(threads[i], NULL);
}
// If a thread returns an error, we say so and exit
for (int i = 0; i < threadCount; i++){
if (threadReturn[i] > 0) {
printf("Thread %d returned an error, quitting", i);
return 2;
}
}
// ***TO DO *** Process TOP 10 and display
// we sort the master list of threads
sortListBySize(threadRecords[0]->listHead);
// We print the top 10 threads
printf("\nThe top 10 words - %d threads\n", threadCount);
Word * printList = *threadRecords[0]->listHead;
for (int i = 0; i < 10 && printList != NULL; i++){
printf("\nWord - %s, count - %d\n", printList->word, printList->count);
printList = printList->next;
}
//**************************************************************
// DO NOT CHANGE THIS BLOCK
//Clock output
clock_gettime(CLOCK_REALTIME, &endTime);
time_t sec = endTime.tv_sec - startTime.tv_sec;
long n_sec = endTime.tv_nsec - startTime.tv_nsec;
if (endTime.tv_nsec < startTime.tv_nsec)
{
--sec;
n_sec = n_sec + 1000000000L;
}
printf("Total Time was %ld.%09ld seconds\n", sec, n_sec);
//**************************************************************
// ***TO DO *** cleanup
// here we free the list memory
Word * deleteList = *threadRecords[0]->listHead;
while(deleteList){
Word * tempWord = deleteList;
deleteList = deleteList->next;
free(tempWord->word);
tempWord->word = NULL;
free(tempWord);
tempWord = NULL;
}
// here we free the threadRecord memory
for (int i = 0; i < threadCount; i++){
free(threadRecords[i]);
threadRecords[i] = NULL;
}
}
// This is the function that runs for every thread, it divides up the file into a chunk for each
// thread, sorts that chunk of the file into words and totals of occurrences (sorting the words
// alphabetically), then it merges every thread's list into a combined list using mutex locks
// to ensure data safety. The merged list is also sorted, this way the sort step in which the
// threads can run independently is bumped from n to nlogn but the merge step in which the
// threads are limited by the lock is reduced from n^2 to nlogn, resulting in code that gets
// more efficient with more threads
void * readFile (void * threadRecordVoid){
// we recover the voided threadRecord that contains our passthrough data
ThreadRecord * threadRecord = (ThreadRecord *)threadRecordVoid;
// we open the file
int fileID = open(threadRecord->fileName, O_RDONLY);
// we get the filesize
off_t fileSize = lseek(fileID, 0, SEEK_END);
printf("\nfilesize: %ld\n", fileSize);
// we calculate how big each thread's chunk of the filesize will be
long fileChunkSize = fileSize / threadRecord->totalThreads;
printf("\nchunk size: %ld\n", fileChunkSize);
// we create the array we'll use to read from the file and end it
// with a null terminator
char readFromFile[fileChunkSize + 1];
readFromFile[fileChunkSize] = '\0';
// we read from the file
ssize_t readResult = pread(fileID,
readFromFile,
fileChunkSize,
fileChunkSize * threadRecord->thisThread);
/*
char sample[1000];
sample[999] = '\0';
strncpy(sample, readFromFile, 999);
printf("\nSample Text of War and Peace:\n%s\n", sample);
*/
// Here we begin breaking up the file and storing it as individual words
// with counts. We use strtok_r (because it's threadsafe) to read a word
// from the string we created from our thread's chunk of the file. We
// handle that word in various ways depending on how it sorts into the list.
// We move on to the next word until we're out of words. Then we're done and we
// move on ot the merge step.
// We start will a null node.
Word * threadListHead = NULL;
char* token;
char* rest = readFromFile;
// We get a token from strtok_r and check if it's null
int counter = 0;
while ((token = strtok_r(rest, delim, &rest)) ){
// We only do something with the token if it's at least six chars
if (strcmp(token, "princess") == 0) {
counter++;
printf("\ntoken - %s, count - %i\n", token, counter);
}
if (strlen(token) >= 6){
// This handles the very first node created in the list
if (threadListHead == NULL){
threadListHead = malloc(sizeof(Word));
threadListHead->word = malloc(sizeof(token));
strcpy(threadListHead->word,token);
threadListHead->count = 1;
threadListHead->next = NULL;
}
// This handles count increases at the head node
else if (strcmp(threadListHead->word, token) == 0) {
threadListHead->count++;
}
// This handles the case of whether a word is lower in the
// list than the head, in which case we create a new head
else if (strcmp(threadListHead->word, token) > 0) {
Word * newWord = malloc(sizeof(Word));
newWord->word = malloc(sizeof(token));
strcpy(newWord->word, token);
newWord->count = 1;
newWord->next = threadListHead;
threadListHead = newWord;
}
// here we handle traversing the list after the head
else {
Word * currWord = threadListHead;
// We traverse the list while the next word is not null and the next word
// is smaller than the current token
while(currWord->next != NULL && strcmp(currWord->next->word, token) < 0) {
currWord = currWord->next;
}
// If we get to null, we add a new node on the end of the list
if (currWord->next == NULL){
currWord->next = malloc(sizeof(Word));
currWord = currWord->next;
currWord->next = NULL;
currWord->word = malloc(sizeof(token));
strcpy(currWord->word, token);
currWord->count = 1;
if(strcmp(currWord->word, "princess") == 0){
printf("\nAdding at end\n%s - count %d",
currWord->word, currWord->count);
}
}
// if we have a matching word, we increase the count
else if (strcmp(currWord->next->word, token) == 0) {
currWord->next->count++;
/*
if(strcmp(currWord->next->word, "princess") == 0){
printf("\nincrementing count\n%s - count %d",
currWord->next->word, currWord->next->count);
}
*/
}
// if we have a node that matches a particular position in the list, we
// insert a new node into that position
else if (strcmp(currWord->next->word, token) > 0) {
Word * newWord = malloc(sizeof(Word));
newWord->word = malloc(sizeof(token));
strcpy(newWord->word, token);
newWord->count = 1;
newWord->next = currWord->next;
currWord->next = newWord;
if(strcmp(currWord->next->word, "princess") == 0){
printf("\ninserting into list\n%s - count %d",
currWord->next->word, currWord->next->count);
}
}
else {
printf("\nerror storing token - %s\n", token);
}
}
}
}
// Here we call the function that combines the sorted lists into a single list
combineList(threadRecord->listHead, &threadListHead);
/*
Word * transferHead = threadListHead;
while(transferHead) {
pthread_mutex_lock( &mutex1 );
if ((*threadRecord->listHead) == NULL){
Word * tempWord = transferHead;
transferHead = transferHead->next;
tempWord->next = NULL;
*threadRecord->listHead = tempWord;
}
else if (strcmp((*threadRecord->listHead)->word, transferHead->word) == 0){
Word * tempWord = transferHead;
transferHead = transferHead->next;
(*threadRecord->listHead)->count += tempWord->count;
free(tempWord->word);
tempWord->word = NULL;
free(tempWord);
tempWord = NULL;
}
else if (strcmp((*threadRecord->listHead)->word, transferHead->word) > 0){
Word * tempWord = transferHead;
transferHead = transferHead->next;
tempWord->next = *threadRecord->listHead;
*threadRecord->listHead = tempWord;
}
else {
Word * currWord = *threadRecord->listHead;
while(currWord->next != NULL && strcmp(currWord->next->word, transferHead->word) < 0){
currWord = currWord->next;
}
if (currWord->next == NULL){
//printf("segfault? currWord->next == NULL");
Word * tempWord = transferHead;
transferHead = transferHead->next;
tempWord->next = NULL;
currWord->next = tempWord;
}
else if (strcmp(currWord->next->word, transferHead->word) == 0){
//printf("segfault? strcmp(currWord->next->word, transferHead->word) == 0");
Word * tempWord = transferHead;
transferHead = transferHead->next;
currWord->next->count = currWord->next->count + tempWord->count;
free(tempWord->word);
tempWord->word = NULL;
free(tempWord);
tempWord = NULL;
}
else if (strcmp(currWord->next->word, transferHead->word) > 0)
{
//printf("segfault? strcmp(currWord->next->word, transferHead->word) > 0");
Word * tempWord = transferHead;
transferHead = transferHead->next;
tempWord->next = currWord->next;
currWord->next = tempWord;
}
else{
printf("\nError transferring word - %s\n", transferHead->word);
}
}
pthread_mutex_unlock( &mutex1 );
}
*/
/*
printf("\nThread %d - first 10 of threadRecord\n", threadRecord->thisThread);
printList = *threadRecord->listHead;
for(int i = 0; i < 10 && printList != NULL; i++){
printf("\nword - %s - count - %d\n", printList->word, printList->count);
printList = printList->next;
}
*/
/*
while(threadListHead){
Word * toDelete = threadListHead;
threadListHead = threadListHead->next;
free(toDelete);
toDelete = NULL;
}
*/
}
// This is the function that readFile runs to combine the sorted lists from each
// thread into a single combined list. It pulls nodes directly out of the
// existing lists and enters them into the new list, deleting duplicate entries
// after adding their counts to the existing entry's count
void combineList (Word ** combinedList, Word ** transferList){
Word * transferHead = *transferList;
while(transferHead) {
// We use a mutex lock here to control access to the combined list since
// writes to it need to be thread safe
pthread_mutex_lock( &mutex1 );
// Here we handle creating the first node in the previously empty list
if ((*combinedList) == NULL){
Word * tempWord = transferHead;
transferHead = transferHead->next;
tempWord->next = NULL;
*combinedList = tempWord;
}
// next we handle nodes that match the head, deleting the nodes after we've
// added in the count
else if (strcmp((*combinedList)->word, transferHead->word) == 0){
Word * tempWord = transferHead;
transferHead = transferHead->next;
(*combinedList)->count += tempWord->count;
free(tempWord->word);
tempWord->word = NULL;
free(tempWord);
tempWord = NULL;
}
// Next we handle words that go before the head by creating a new head and
// tagging the rest of the list onto it
else if (strcmp((*combinedList)->word, transferHead->word) > 0){
Word * tempWord = transferHead;
transferHead = transferHead->next;
tempWord->next = *combinedList;
*combinedList = tempWord;
}
// Next we handle traversal of the list beyond the head
else {
Word * currWord = *combinedList;
// We search the list while the next pointer is not null and is smaller than the
// current search term
while(currWord->next != NULL
&& strcmp(
currWord->next->word,
transferHead->word) < 0){
currWord = currWord->next;
}
// if we reach null, we insert the node at the end and make its next pointer the new
// NULL
if (currWord->next == NULL){
Word * tempWord = transferHead;
transferHead = transferHead->next;
tempWord->next = NULL;
currWord->next = tempWord;
if(strcmp("princess", tempWord->word) == 0){
printf("\ninserting at end of list\n%s - count %d",
tempWord->word,
tempWord->count);
}
}
// if the word is a match, we add the count to the list and delete the transfer node
else if (strcmp(currWord->next->word, transferHead->word) == 0){
Word * tempWord = transferHead;
transferHead = transferHead->next;
currWord->next->count = currWord->next->count + tempWord->count;
if(strcmp("princess", tempWord->word) == 0){
printf("\nadding to existing node\n%s - count %d",
currWord->next->word,
currWord->next->count);
}
free(tempWord->word);
tempWord->word = NULL;
free(tempWord);
tempWord = NULL;
}
// if the word slots in earlier in the list, we add the node in that location
else if (strcmp(currWord->next->word, transferHead->word) > 0)
{
Word * tempWord = transferHead;
transferHead = transferHead->next;
tempWord->next = currWord->next;
currWord->next = tempWord;
if(strcmp("princess", tempWord->word) == 0){
printf("\ninserting into list\n%s - count %d",
tempWord->word,
tempWord->count);
}
}
else{
printf("\nError transferring word - %s\n", transferHead->word);
}
}
pthread_mutex_unlock( &mutex1 );
}
}
// This function sorts the completed list by the size of the count using an insertion
// sort. Note: May come back to this later to sort by something with better time
// complexity to improve program performance
void sortListBySize ( Word ** listHead ){
Word * sortedList = NULL;
Word * currListHead = *listHead;
while ( currListHead) {
// Here we handle the first node in the sorted list, taking it from the
// unsorted list
if (sortedList == NULL){
sortedList = currListHead;
currListHead = currListHead->next;
sortedList->next = NULL;
}
// Here we handle nodes that sort before the list head, making them
// the new list head and tacking the list on after them
else if (sortedList->count <= currListHead->count){
Word * tempWord = currListHead;
currListHead = currListHead -> next;
tempWord->next = sortedList;
sortedList = tempWord;
}
// Here we handle sorted list traversal beyond the head
else {
Word * currWord = sortedList;
// We advance in the sorted list while the next pointer doesn't equal null
// and its count is greater than the unsorted list node's count
while(currWord->next != NULL && currWord->next->count > currListHead->count){
currWord = currWord->next;
}
// If we reach null, we insert the pointer at the end and set its next
// pointer to null
if (currWord->next == NULL) {
Word * tempWord = currListHead;
currListHead = currListHead->next;
tempWord->next = NULL;
currWord->next = tempWord;
}
// If we reach a position in the list earlier than null, we insert the node
// at that position
else if (currWord->next->count <= currListHead->count){
Word * tempWord = currListHead;
currListHead = currListHead->next;
tempWord->next = currWord->next;
currWord->next = tempWord;
}
}
}
// We set the listHead to the sortedList pointer, setting the list to the
// sorted list
*listHead = sortedList;
}
The correct results for the top 10 threads should be as follows:
Number 1 is Pierre with a count of 1963
Number 2 is Prince with a count of 1928
Number 3 is Natásha with a count of 1212
Number 4 is Andrew with a count of 1143
Number 5 is himself with a count of 1020
Number 6 is princess with a count of 916
Number 7 is French with a count of 881
Number 8 is before with a count of 833
Number 9 is Rostóv with a count of 776
Number 10 is thought with a count of 767
My results are as follows:
Word - Pierre, count - 1963
Word - Prince, count - 1577
Word - Natásha, count - 1213
Word - Andrew, count - 1143
Word - himself, count - 1017
Word - French, count - 881
Word - before, count - 779
Word - Rostóv, count - 776
Word - thought, count - 766
Word - CHAPTER, count - 730
Does anyone know what the source of the error could be?
A: ssize_t readResult = pread(fileID,
readFromFile,
fileChunkSize,
fileChunkSize * threadRecord->thisThread);
man: pread() reads "up to" count bytes from file descriptor fd
Check your return. You probably have a short read.
It looks like you tried to debug with "princess" and short circuited your logic and found that the problem is in strtok_r. Normally I'd be complaining about reduce your code to a much smaller example but I'm pretty sure you manually verified counter has the wrong value even though the code that looks at is missing right now. This doesn't leave much left to find but the short read.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: File upload issue with Iphone - capturing image We have form with 3 input fields all the inputs have type of file.
When we are uploading from library it's uploading no issue. when a user is giving input from camera iphone is sending the last captured image.
we have tried capture attribute and accept attribute no changes.
we are using #php, #js and #ajax.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Bootstrap Collapse Sidebar Issue I have a sidebar for my navigation on my webpage. I want this sidebar to be collapsible. Im using bootstrap 5, and am facing issues with this.
Before adding the around my , my page looks like this: Image. However after adding the , it turns to this: Image. The sidebar covers the page.
I tried adding position-relative to the collapse, however this did not do anything. Could someone help me with this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640436",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: c# Regex not working but the Regular Expression works online I'm using the regex expression below in c# code. The expression works on online editor sites but won't work with .Net Regex in .NET 4.8 framework.
Regex rxrp = new Regex(@"([[:upper:]]\.|^\d+\.)");
var matchResults = rxrp.Matches(dataStore);
Here's a sample sentence:
That same year, J.J. Thomson conducted an experiment in which he channeled a stream of neon ions through magnetic and electric fields, striking a photographic plate at the other end.
The abbreviations J.J. should both match but the MatchCollections is empty, no results. Any ideas?
I applied the regular expression and expected matches to occur but none were detected.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to make a submit button using react that submits text entries using react native We don't know where to start...
https://snack.expo.dev/@hansuja-yalavarthi/hwits
^^^ code for our project, can someone help please
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What are the permissions that Kinesis delivery Role needs to enable server-side encryption? And some additional questions on Kinesis and KMS For my current use case, I'm using Kinesis delivery streams/firehose to stream Firewall Manager logs. So currently the set up is the Kinesis is in Account A(same account as Firewall Manager), and streaming the logs into a S3 bucket in Account B. So below is the current IAM policy attached to the Kinesis Role(Able to successfully send data to S3). Have also added a bucket policy to the destination bucket to allow the below actions to be performed on the S3 bucket by the Kinesis Role:
data "aws_iam_policy_document" "firehose_policy" {
statement {
actions = ["logs:PutLogEvents"]
resources = ["arn:aws:logs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:log-group:/aws/kinesisfirehose/aws-waf-logs-*"]
}
statement {
actions = [
"s3:AbortMultipartUpload",
"s3:GetBucketLocation",
"s3:GetObject",
"s3:ListBucket",
"s3:ListBucketMultipartUploads",
"s3:PutObject",
"s3:PutObjectAcl"
]
resources = [
"arn:aws:s3:::<name of destination bucket>",
"arn:aws:s3:::<name of destination bucket>/*"
]
}
}
However now there's an additional requirement to enable server-side encryption on the Kinesis firehose using CMK. Came across this docs on AWS, however I do not fully understand it and have the following questions stated below: https://docs.aws.amazon.com/streams/latest/dev/permissions-user-key-KMS.html
My questions are:
*
*In my use case, is my consumer the S3 destination bucket?
*Since I have to create a KMS key(i guess in Account A), what are the KMS key policies I have to attach to the KMS key? Is the KMS key policy to specify permissions to allow the kinesis firehose role to use the key?
*Do I have to attach any KMS permissions to the IAM policy of the Kinesis firehose?
*Since Kinesis is eventually going to encrypt using KMS and store it in S3, does the S3 bucket need any bucket policies to specify something regarding the KMS key?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: leetcode 332. Reconstruct Itinerary AddressSanitizer: stack-overflow error I am trying to solve this problem by using a private method applyHierholzerAlgorithm, but it always happened a AddressSanitizer: stack-overflow error.
Could anyone give some hint about what's wrong about this code?
class Solution {
public:
vector findItinerary(vector<vector>& tickets) {
//build the graph, and make it sorted
for (auto entry : tickets) {
std::string origin = entry[0];
std::string dest = entry[1];
if (flights.find(origin) != flights.end()) {
flights[origin].push_back(dest);
//sort here
std::sort(flights[origin].begin(), flights[origin].end());
} else {
std::vector<std::string> destList = std::vector<std::string>();
destList.push_back(dest);
flights[origin] = destList;
}
}
applyHierholzerAlgorithm("JFK");
return result;
}
private:
std::unordered_map<std::string, std::vector<std::string>> flights;
std::vector<std::string> result;
void applyHierholzerAlgorithm(std::string origin) {
if (flights.find(origin) != flights.end()) {
std::vector<std::string> dests = flights[origin];
while(!dests.empty()) {
std::string nextTo = dests[0];
dests.erase(dests.begin());
applyHierholzerAlgorithm(nextTo);
}
}
result.insert(result.begin(), origin);
}
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to add record in datatable flet python? I want the user to enter the values and press the plus button to display all the values in the TextField in the data table and in my code to access these records through a list.
In the picture below, the data table is created again from the beginning, if I want it to be added as a record in the data table every time the value is entered in the TextField and the add option is pressed by the user.
The point is that I want these records to be in the list in the source
def main(page: ft.Page):
def add_clicked(e):
page.add(
ft.DataTable(
columns=[
ft.DataColumn(ft.Text("First name")),
ft.DataColumn(ft.Text("Last name")),
ft.DataColumn(ft.Text("Age")),
],
rows=[
ft.DataRow(
cells=[
ft.DataCell(ft.Text(new_task.value)),
ft.DataCell(ft.Text(new_task1.value)),
ft.DataCell(ft.Text(new_task2.value)),
],
),
]
)
)
# page.add(ft.DataCell(ft.Text(new_task.value)))
# page.add(ft.DataCell(ft.Text(new_task1.value)))
# page.add(ft.DataCell(ft.Text(new_task2.value)))
# page.add(ft.Checkbox(label=new_task.value))
# page.add(ft.Checkbox(label=new_task1.value))
# page.add(ft.Checkbox(label=new_task2.value))
new_task.value = ""
new_task1.value = ""
new_task2.value = ""
page.update()
new_task = ft.TextField(hint_text="Whats needs to be done?")
new_task1 = ft.TextField(hint_text="Whats needs to be done?")
new_task2 = ft.TextField(hint_text="Whats needs to be done?")
page.add(new_task,new_task1,new_task2, ft.FloatingActionButton(icon=ft.icons.ADD, on_click=add_clicked),
)
ft.app(target=main)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error : To connecting mongoDB with node js const mongoose = require('mongoose');
const app = express();
const mongoDB = "mongodb://localhost:27017/ecomm";
mongoose.connect(mongoDB,{ useNewUrlParser: true })
.then(()=>console.log('connection successfully'))
app.listen(5000,()=>{
console.log('Server is running on port : 5000');
}) `
i am gettting this error :
Server is running on port : 5000
F:\Node js\mongo db\node_modules\mongoose\lib\connection.js:755
err = new ServerSelectionError();
^
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at _handleConnectionErrors (F:\Node js\mongo db\node_modules\mongoose\lib\connection.js:755:11)
at NativeConnection.openUri (F:\Node js\mongo db\node_modules\mongoose\lib\connection.js:730:11)
at runNextTicks (node:internal/process/task_queues:60:5)
at listOnTimeout (node:internal/timers:538:9)
at process.processTimers (node:internal/timers:512:7) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 4708510,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (F:\Node js\mongo db\node_modules\mongodb\lib\cmap\connect.js:383:20)
at Socket. (F:\Node js\mongo db\node_modules\mongodb\lib\cmap\connect.js:307:22)
at Object.onceWrapper (node:events:628:26)
at Socket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
cause: Error: connect ECONNREFUSED ::1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 27017
},
[Symbol(errorLabels)]: Set(1) { 'ResetPool' }
},
topologyVersion: null,
setName: null,
setVersion: null,
electionId: null,
logicalSessionTimeoutMinutes: null,
primary: null,
me: null,
'$clusterTime': null
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: null,
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined
}
Node.js v18.14.0
[nodemon] app crashed - waiting for file changes before starting...
help me
#node #mongodb
help to solve this error i am getting this error during connecting mongodb with node js
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What happens if you use hibernate 4 and java 11 Considering the announcement of hibernate 4 as "end of life", and java 11 being listed in hibernate 5.x,
*
*what happens if you use 4 with java 11? What problems may occur?
In general, what does it mean when no one says "the two are compatible"?
*Even if it's officially announced "the two are not compatible", what's the result? Does it mean it's not supported officially or (maybe or definitely?)problems occur if you use them?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: how to create new zod schema with infering its type I want to reasign value of my object
i have interface like this
interface Root {
userId: number;
id: number;
title: string;
completed: boolean;
}
and i know how to create zod schema from that interface
const zRoot: z.ZodType<Root> = z.object({
userId: z.number(),
id: z.number(),
title: z.string(),
completed: z.boolean(),
});
but, how to make schema that type like this?
type RootObjectArray = {
[F in keyof Root]: Root[F][];
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android app: Google Fit Vs Samsung Health | Pros and Cons? Question:
I need a detailed overview from every Android user, that which is a better app, Google Fit Vs Samsung Health?
Key points:
Battery draining, tracking activity wise, features, sync data, auto track, accuracy, intelligence (If I start tracking running, and then I forgot to stop and I was walking towards home, then how it will make separation?), helpful widgets, graphs, Can I set a new goal and track daily data?, smart watches support, other Android app supports, etc.
Support:
Request everyone to participate on this discussion.
Rating:
Could you add your own rating from 1 to 10?
How to answer?
Give a detailed overview, then separate pros and cons section and highlight with bullet points. And, at very last give rating, for ex. Google Fit 6.8, Samsung health 7.2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75640451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|