instruction stringlengths 0 30k ⌀ |
|---|
[i am talking about this bulb which is in this image](https://i.stack.imgur.com/SJZub.png)
**i want to glow this bulb but unable to glow spent 4 hour but still now able to do. Please tell me how to do anyone !**
this is html code
```
div className="item image">
<img src={sidimage} alt="sid" height="400" />
<div className="light">
<img className="bulb" src={bulb2} alt="light bulb" />
</div>
</div>
```
this is the css
```
.bulb{
position: relative;
left: 26.5rem;
bottom: 32rem;
}
```
i want to glow the bulb which is in the image |
Is there any way to glow this bulb image like a real light bulb |
|html|css|reactjs| |
null |
It seems currently not being possible to control the volume of for example a playing movie from the iPhone screen. I always have to use the physical buttons.
I tried to control the volume of a movie playing on the iPhone with a slider, but there was no slider visible |
How to control the volume of an iPhone programmatically in objective-c |
|objective-c|controls|volume| |
null |
A "C" approach could use functions from `<time.h>`.
OP comments, but not in the question, "I cannot, this is a challenge for my software engineering degree , and I cannot use libraries any other than those I'm using". Well you can use those functions to check your work.
```
#include <stdbool.h>
#include <stdio.h>
#include <time.h>
// Return error flag
bool calculate_time_difference_ref(double *diff_min, //
const char date_in[], const char time_in[], //
const char date_out[], const char time_out[]) {
struct tm dt1 = { .tm_isdst = -1 };
struct tm dt2 = { .tm_isdst = -1 };
if (sscanf(date_in, "%d-%d-%d", &dt1.tm_mday, &dt1.tm_mon, &dt1.tm_year) != 3) return true;
if (sscanf(time_in, "%d:%d", &dt1.tm_hour, &dt1.tm_min) != 2) return true;
if (sscanf(date_out, "%d-%d-%d", &dt2.tm_mday, &dt2.tm_mon, &dt2.tm_year) != 3) return true;
if (sscanf(time_out, "%d:%d", &dt2.tm_hour, &dt2.tm_min) != 2) return true;
time_t t_in = mktime(&dt1);
time_t t_out = mktime(&dt2);
if (t_in == -1 || t_out == -1) return true;
*diff_min = difftime(t_in, t_out)/60.0; // Difference in minutes
return false;
}
```
Note the above takes into account _daylight savings time_.
Use `struct tm dt1 = { .tm_isdst = 0 };` to assume standard time.
|
null |
I am working on Java Spring Boot project which includes simple Telegram Bot. My problem: I don't want to push credentials such as bot username and bot token to my remote repository. To achieve this, I simply put ***.env*** file into ***.gitignore***, but without creds, Java CI can't build project. I get quite natural root exception: ```org.telegram.telegrambots.meta.exceptions.TelegramApiException: Bot token and username can't be empty```
Here is the code of my bot:
```package application.carsharingapp.service.notification.impl;
import application.carsharingapp.exception.NotificationSendingException;
import application.carsharingapp.service.notification.NotificationService;
import io.github.cdimascio.dotenv.Dotenv;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
@RequiredArgsConstructor
@Service
public class TelegramNotificationService extends TelegramLongPollingBot
implements NotificationService {
private static final Dotenv DOTENV = Dotenv.configure().ignoreIfMissing().load();
private static final String BOT_USERNAME = DOTENV.get("BOT_USERNAME");
private static final String BOT_TOKEN = DOTENV.get("BOT_TOKEN");
private static final String TARGET_CHAT_ID = DOTENV.get("TARGET_CHAT_ID");
@Override
public void sendNotification(String message) {
SendMessage sendMessage = new SendMessage();
sendMessage.setText(message);
sendMessage.setChatId(TARGET_CHAT_ID);
try {
execute(sendMessage);
} catch (TelegramApiException e) {
throw new NotificationSendingException("Can't send notification "
+ "to chat: " + sendMessage.getChatId(), e);
}
}
@Override
public void onUpdateReceived(Update update) {
}
@Override
public String getBotUsername() {
return BOT_USERNAME;
}
@Override
public String getBotToken() {
return BOT_TOKEN;
}
}
```
And here is code of my bot's config:
```package application.carsharingapp.config;
import application.carsharingapp.service.notification.impl.TelegramNotificationService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;
@Configuration
public class TelegramBotConfig {
@Bean
public TelegramBotsApi telegramBotsApi(TelegramNotificationService telegramNotificationService)
throws TelegramApiException {
TelegramBotsApi api = new TelegramBotsApi(DefaultBotSession.class);
api.registerBot(telegramNotificationService);
return api;
}
}
```
I would really like to hear some advice or tips on how to solve this problem and what are the possible solutions.
To solve this problem I tried to set some mock values for credentials, but that I got 404 Not found error |
I have a data point (a file, an image, an audio , a video, etc..)
1: I need to slit that data point in to n part and encrypt them
2: if some part of n let make it "a " is missing i can use n-a to recover and decrypt to get the data point from the beginning.
thank you all. |
File splitting and encryption |
|file|encryption|file-recovery|filesplitting| |
I had to flip the source texture because it was in the format of ARGB and instead I needed BGRA.
```csharp
public virtual void CompositeImage(byte[] buffer, int bufferWidth, int bufferHeight, byte[] image, int imageWidth, int imageHeight, int x, int y)
{
for (int i = 0; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth; j++)
{
if (j > bufferWidth)
{
continue;
}
if (i > bufferHeight)
{
continue;
}
int index = Math.Min((i * imageWidth + j) * 4, image.Length - 4);
int bufferIndex = ((y + i) * bufferWidth + (x + j)) * 4;
if (bufferIndex < 0 || bufferIndex >= buffer.Length - 4)
return;
Pixel back = new Pixel(
buffer[bufferIndex + 3],
buffer[bufferIndex + 2],
buffer[bufferIndex + 1],
buffer[bufferIndex]
);
Pixel fore = new Pixel(
image[index],
image[index + 1],
image[index + 2],
image[index + 3]
);
if (fore.A < 255)
{
Color blend = fore.color.Blend(back.color, 0.15d);
buffer[bufferIndex] = blend.B;
buffer[bufferIndex + 1] = blend.G;
buffer[bufferIndex + 2] = blend.R;
if (back.A == 255) buffer[bufferIndex + 3] = 255;
else buffer[bufferIndex + 3] = blend.A;
}
else
{
buffer[bufferIndex] = fore.color.B;
buffer[bufferIndex + 1] = fore.color.G;
buffer[bufferIndex + 2] = fore.color.R;
buffer[bufferIndex + 3] = 255;
}
//back = back.Composite(fore);
}
}
}
``` |
Try this:
``` css
#logo {
background: url(images/logo.png) no-repeat;
background-position: 0px 40px;
height: 144px;
width: 301px;
}
``` |
null |
Set Expiry Dates for Google Drive
step to open the way to solve this issue, i need step to step handle this issue
step to open the way to solve this issue, i need step to step handle this issue
step to open the way to solve this issue, i need step to step handle this issue
step to open the way to solve this issue, i need step to step handle this issue
step to open the way to solve this issue, i need step to step handle this issue
step to open the way to solve this issue, i need step to step handle this issue
step to open the way to solve this issue, i need step to step handle this issue
step to open the way to solve this issue, i need step to step handle this issue
step to open the way to solve this issue, i need step to step handle this issue
step to open the way to solve this issue, i need step to step handle this issue |
Accessing REST API Error Codes using Azure Data Factory Copy Activity (or similar)? |
|rest|azure-data-factory| |
null |
On Python 3.10, you can inherit from `str` and `Enum` to have a `StrEnum`:
```python
from enum import Enum
class MyEnum(str, Enum):
choice1 = "choice1"
choice2 = "choice2"
```
With this approach, you have string comparison:
```python
"choice1" == MyEnum.choice1
>> True
```
Be aware, however, that Python 3.11 makes a breaking change to classes which inherit from (str, Enum): https://github.com/python/cpython/issues/100458. You will have to change all instances of (str, Enum) to StrEnum when upgrading to maintain the same behavior.
**Or**:
you can execute `pip install StrEnum` and have this:
```python
from strenum import StrEnum
class MyEnum(StrEnum):
choice1 = "choice1"
choice2 = "choice2"
``` |
null |
My code is just a simple prime factorization calculator.
I'm not sure why it's infinitely looping. I'm pretty new to Python and not entirely sure on how the while loop works.
```
def print_prime_factors(number):
x = 2
while x < number:
if number % x == 0:
y = number/x
print(str(x)+",")
y = number
if x > y:
break
x = x + 1
print_prime_factors(100)
# Should print 2,2,5,5
# DO NOT DELETE THIS COMMENT``` |
My code is infinitely looping and I'm not sure why |
null |
|flutter|dart|dictionary|openstreetmap| |
`orientation` does not seem to work as desired.\
Working with `aspect-ratio` may be the better way.
```
@media only screen and (max-aspect-ratio: 1/1){
//portrait
}
@media only screen and (min-aspect-ratio: 1/1){
//horizontal
}
``` |
My loader receives part of the program from the server as `.pyc` files (the files themselves are NOT saving in client pc's filesystem, the byte sequence is stored in a variable).
I need to create a module from this byte sequence without creating a file.
I found a way to create a module from a string:
spec = importlib.util.spec_from_loader("modulename", loader=None) # creating spec
module = importlib.util.module_from_spec(spec) # creating module
exec(source, module.__dict__) # executing module
# so that we can import it in other program files
sys.modules[name] = module
globals()[name] = module
But it doesn't work for me in my case.
The module is initially created with `py_compile.compile("sorcefile.py", "destfile.pyc")`.
The answer to a similar question (https://stackoverflow.com/questions/1830727/how-to-load-compiled-python-modules-from-memory) suggests using `marshal.loads(bytes[8:])` and indeed, looking at the source code of `py_compile.compile` function (https://svn.python.org/projects/python/trunk/Lib/py_compile.py) I saw that it uses `marshal.dump()`. However, as far as I understand, this code is deprecated, because looking at the source code of this function in my Python instance (3.11) (https://github.com/python/cpython/blob/3.11/Lib/py_compile.py), I saw that it no longer uses marshall.
This explains why this error appears in the following situation:
import marshal
import py_compile
py_compile.compile("source.py", "compiled.pyc")
with open("compiled.pyc", "rb") as f:
module_bytes = f.read()
module = marshal.loads(module_bytes[8:])
Output:
Traceback (most recent call last):
File "C:\test.py", line 9, in <module>
module = marshal.loads(module_bytes[8:])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: bad marshal data (unknown type code)
(In this case, the pyc file is created only to emulate the data received from the server.)
So, is it possible to create a module from a sequence of bytes without creating a file in python 3.11 (as in the *"string"* method). |
I'm trying to connect to local postgresql server from my docker container.
I'm using Ubuntu 22.04.4.
This is my `docker-compose.yml`.
```
version: '3'
services:
...
backend:
build:
context: '.'
dockerfile: 'Dockerfile'
ports:
- '8000:80'
- '8001:8001'
env_file:
- .env-docker
image: backend-django:latest
...
```
This is my `.env-docker`.
```
DEBUG=True
SECRET_KEY=******
DATABASE_USER=postgres
DATABASE_NAME=postgres
DATABASE_PASSWORD=postgres
DATABASE_HOST=host.docker.internal
DATABASE_PORT=5432
```
This is my `Dockerfile`.
```
FROM python:3.11
ENV PYTHONBUFFERED 1
...
EXPOSE 8000
CMD ["gunicorn", "-b", "0.0.0.0", "config.wsgi"]
```
It was working in Windows but not in Ubuntu now.
Is it related to postgresql?
I'm using the same version of postgresql and I can connect to local postgresl using PgAdmin.
How can I connect to postgresql server from my docker container? |
Can't connect to local postgresql server from my docker container |
|python|django|postgresql|docker|ubuntu| |
null |
I have the below pandas DF
[](https://i.stack.imgur.com/RZ7aM.png)
steps to create the DF
```
data=[['1','0','0','0','0'],['2','1','1','0','0|0'],['3','1','1','1','0|1'],['4','2','2','0','0|0|0'],['5','2','2','1','0|0|1'],['6','2','2','2','0|0|2'],['7','3','2','0','0|1|0'],['8','3','2','1','0|1|1'],['9','3','2','2','0|1|2'],['10','3','2','3','0|1|3'],['11','4','3','0','0|0|0|0'],['12','4','3','1','0|0|0|1'],['13','10','3','0','0|1|3|0']]
df = pd.DataFrame(data, columns=['eid','m_eid','level','path_variable','complete_path'])
df=df.drop('complete_path',axis=1)
```
Here:
**eid** = employee id
**m_eid** = manager id
**level** = level in org(0 being top boss)
**path_variable** = incremental number assigned to an employee based on there level this number resets for each manager(for example: eid[4,5,6,7,8,9,10] belong to same level 2 but eid[4,5,6] has same manager(m_eid=2) so there path_variable is 0,1,2 whereas eid[7,8,9,10] has a different manager(m_eid=3) so the path_variable restarts from 0)
i want to create a new column which shows the complete path till level 0 for each eid. Like shown below:
[](https://i.stack.imgur.com/oKhkl.png)
Complete path is concatenations of path_variable till level 0(top boss).
Its like path from root node to the edge node. For ex. lets take eid 10
[![enter image description here][1]][1]
there can be level skips between immediate managers. I m trying to avoid iterrows() due to performance constraints.
[1]: https://i.stack.imgur.com/sU7Mh.png |
I'm encountering an issue with passing the "size" parameter from my JavaScript function to my Django backend. Here's the relevant code snippet from my Django view:
```python
def get_product(request, slug):
try:
product = Product.objects.get(slug=slug)
if request.GET.get('size'):
size = request.GET.get('size')
print(size)
return render(request, "core/product_detail.html")
except Exception as e:
print(e)
```
And here's the JavaScript function:
```javascript
function get_correct_price(size) {
console.log(size);
window.location.href = window.location.pathname + `?size=${size}`;
}
```
In my HTML template, I'm calling the JavaScript function with the size parameter:
```html
<button onclick="get_correct_price('{{ s.name }}')">{{ s.name }}</button>
```
However, when I click the button, the size parameter doesn't seem to be passed to the backend. I've verified that the JavaScript function is being called, and the size parameter is logged correctly in the console.
Could you please help me identify why the size parameter is not being received in the backend? Any insights or suggestions would be greatly appreciated. Thank you!
urls.py:
```python
path("products/",product_list_view,name="product_list"),
path("product/<pid>/",product_detail_view,name="product_detail"),
path("product/<slug>/",get_product,name="product_detail"),
```
In my models.py:
```python
class Size(models.Model):
name=models.CharField(max_length=100)
code= models.CharField(max_length=50,blank=True,null=True)
price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
def __str__(self):
return self.name
class Product(models.Model):
pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef")
user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True)
cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True,related_name="category")
vendor=models.ForeignKey(Vendor, on_delete=models.SET_NULL,null=True,related_name="product")
color=models.ManyToManyField(Color,blank=True)
size=models.ManyToManyField(Size,blank=True)
title=models.CharField(max_length=100,default="Apple")
image=models.ImageField(upload_to=user_directory_path,default="product.jpg")
description=RichTextUploadingField(null=True, blank=True,default="This is a product")
price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99)
old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99)
specifications=RichTextUploadingField(null=True, blank=True)
tags=TaggableManager(blank=True)
product_status=models.CharField(choices=STATUS, max_length=10,default="In_review")
status=models.BooleanField(default=True)
in_stock=models.BooleanField(default=True)
featured=models.BooleanField(default=False)
digital=models.BooleanField(default=False)
sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef")
date=models.DateTimeField(auto_now_add=True)
updated=models.DateTimeField(null=True,blank=True)
class Meta:
verbose_name_plural="Products"
def product_image(self):
return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url))
def __str__(self):
return self.title
def get_percentage(self):
new_price=((self.old_price-self.price)/self.old_price)*100
return new_price
```
In short:
I simply want that ```http://127.0.0.1:8000/product/prdeeffeafaec/?size=15inch``` from the url it should print ```("?size=15inch")``` this |
{"OriginalQuestionIds":[33182329],"Voters":[{"Id":476,"DisplayName":"deceze","BindingReason":{"GoldTagBadge":"mysql"}}]} |
Just in case, if required to use Docker provider:
### Static (i.e. `traefik.yaml`)
```yaml
experimental:
plugins:
rewriteHeaders:
modulename: 'github.com/bitrvmpd/traefik-plugin-rewrite-headers'
version: 'v0.0.1'
```
### Dynamic
```yaml
services:
app:
image: php
volumes:
- '/var/docker/data/app/config/:/etc/nginx/conf.d/:ro'
- '/var/docker/data/app/data/:/var/www/'
networks:
reverse-proxy:
labels:
- 'traefik.enable=true'
- 'traefik.http.services.app.loadbalancer.server.port=80'
# Replace 'Destination' request header: 'https://' -> 'http://'
- 'traefik.http.middlewares.rewriteHeadersMW.plugin.traefik-plugin-rewrite-headers.rewrites.request[0].header=Destination'
- 'traefik.http.middlewares.rewriteHeadersMW.plugin.traefik-plugin-rewrite-headers.rewrites.request[0].regex=^https://(.+)$'
- 'traefik.http.middlewares.rewriteHeadersMW.plugin.traefik-plugin-rewrite-headers.rewrites.request[0].replacement=http://$1'
- 'traefik.http.routers.app.rule=Host(`sub.example.com`)'
- 'traefik.http.routers.app.entrypoints=https'
- 'traefik.http.routers.app.priority=2'
- 'traefik.http.routers.app.middlewares=rewriteHeadersMW'
networks:
reverse-proxy:
name: 'reverse-proxy'
external: true
```
---
Related:
- [Traefik Plugin Page](https://plugins.traefik.io/plugins/63718c14c672f04dd500d1a0/rewrite-headers);
- [GitHub Plugin Page](https://github.com/bitrvmpd/traefik-plugin-rewrite-headers). |
I'm trying to show phylogenetic signaling of a trait and plot a tree with dots at the end such that the dots size is indicative of trait value. But my dotTree function is giving me the following error:
> dotTree(Main_tree, topt_main_matrix)
Error in x[tree$tip.label, ] : subscript out of bounds
For reference, Main_tree (phylo object) is generated from topt_main_matrix (matrix and array object), so I know it's not a mismatch between the tree and the dataset. topt_main_matrix has two columns: one is the species names (matching the phylogenetic tree) and the other column is trait values.
Any idea where I'm going wrong?
I've tried specifying that I want to graph the second column (trait values) by changing the above code to this:
dotTree(Main_tree, topt_main_matrix[,2])
But it then gives me a phylogeny and then a bunch of random colorful dots across the plot. (see image).
Any idea how I can fix this ?
|
R 'phytools' dotTree function does not seem to accept my dataset/tree? |
|r|phylogeny|ape-phylo| |
null |
No, you cannot transition a background. You can transition opacity though, so you could stack two hearts one on top of the other and transition the opacity of one of them on hover.
I think the simplest solution is to use an SVG. This is what SVG is good at: vector graphics.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.heart {
width: 200px;
aspect-ratio: 1;
transition: .5s;
fill: red;
}
.heart:hover {
fill: blue;
}
<!-- language: lang-html -->
<svg class="heart" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
<path d="M 200 60 C 200 75.138 194.394 88.967 185.144 99.523 L 100 200.009 L 14.856 99.523 C 5.606 88.967 0 75.138 0 60 C 0 26.863 26.863 0 60 0 C 75.367 0 89.385 5.777 100 15.278 C 110.615 5.777 124.633 0 140 0 C 173.137 0 200 26.863 200 60 Z"/>
</svg>
<!-- end snippet -->
|
org.telegram.telegrambots.meta.exceptions.TelegramApiException: Bot token and username can't be empty |
|java|spring|environment-variables|telegram| |
null |
I am trying to perform a network meta-analysis. The network contains 3 subnetworks. Therefore I decided to use netmeta::discomb to perform an additive analysis. This worked without error in another project, but not with the new studies.
My current dataset contains 9 studies over a total of 10 treatments (all two-armed, continuous outcome) . The data was transformed from the arm-based to the contrast-based design using netmeta::pairwise. When calling the method netmeta::discomb, the error appears that the dimensions of the edge-vertex incidence matrices B and C are non-conformable. I guess, the warning about the missing separator will later become a problem.
The help says: *By default, the matrix C is calculated internally from treatment names.* Passing a C-matrix myself was also unsuccessful. Since the object `m1.netmeta` is not created, I cannot call C.Matrix to recognize a structural error there.
I would like to be able to create a reasonable overview at the end, i.e. with
`summary(m1.netmeta)`, `netgraph(m1.netmeta)` and `forest(m1.netmeta,...)`.
If required, I can also provide the data and script from the previous project. Maybe it will help.
The minimal code used is below. This is session info:
R version 4.3.2 (2023-10-31 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19045)
Matrix products: default
I appreciate any help and will be happy to answer any questions.
```
library(netmeta)
df <- data.frame(study= c('study 1', 'study 1', 'study 2', 'study 2', 'study 3', 'study 3',
'study 4', 'study 4', 'study 5', 'study 5', 'study 6', 'study 6',
'study 7', 'study 7', 'study 8', 'study 8', 'study 9', 'study 9'),
stud_ind= c(1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2),
comparators= c(1, 2, 3, 2, 1, 2, 4, 2, 5, 0, 6, 2, 7, 2, 6, 2, 8, 9),
n_probands= c(14, 14, 15, 15, 9, 9, 19, 19, 21, 21, 27, 27, 15, 15, 18, 19, 14, 11),
mean= c(3.13, 3.47, 2.36, 3.61, 2.89, 2.78, 2.36, 2.36, 2.64, 5.00, 3.24,
3.28, 1.53, 1.53, 3.07, 2.89, 3.00, 3.30),
sd= c(2.06, 1.74, 1.99, 1.95, 1.97, 1.29, 1.32, 1.32, 1.68,
2.75, 1.21, 1.17, 1.20, 1.20, 2.23, 2.56, 1.53, 1.52))
# long to wide + contrast based
df_wide = df %>%
pivot_wider(names_from=c(stud_ind), values_from=c(comparators, n_probands, mean, sd))
p1 <- pairwise(list(comparators_1, comparators_2),
TE = list(mean_1, mean_2), seTE = list(sd_1, sd_2),
data = df_wide, sm = "MD", reference.group = "2")
# look at network
nc1 <- netconnection(
data=p1,
sep.trts = ":",
nchar.trts = 500,
title = "",
warn = FALSE,
)
print(nc1)
#################################
m1.netmeta <- discomb(TE = TE,
seTE = seTE,
treat1= treat1,
treat2= treat2,
studlab = study,
data = p1,
sm = "MD",
fixed = FALSE,
random = TRUE,
reference.group = "2",
details.chkmultiarm = FALSE,
sep.trts = " vs. ")
# results in error:
# Error in B.matrix %*% C.matrix : non-conformable arguments
# In addition: Warning message:
# No treatment contains the component separator '+'.
#################################
# try with 'own' C.matrix
C <- rbind(c(1, 0, 0, 0, 0, 0, 0, 0, 0), # 0
c(0, 1, 0, 0, 0, 0, 0, 0, 0), # 1
c(0, 0, 1, 0, 0, 0, 0, 0, 0), # 2
c(0, 0, 0, 1, 0, 0, 0, 0, 0), # 3
c(0, 0, 0, 0, 1, 0, 0, 0, 0), # 4
c(0, 0, 0, 0, 0, 1, 0, 0, 0), # 5
c(0, 0, 0, 0, 0, 0, 1, 0, 0), # 6
c(0, 0, 0, 0, 0, 0, 0, 1, 0), # 8
c(0, 0, 0, 0, 0, 0, 0, 0, 1)) # 9
colnames(C)<-c("0","1","2","3","4","5","6","8","9")
rownames(C)<-c("0","1","2","3","4","5","6","8","9")
m2.netmeta <- discomb(TE = TE,
seTE = seTE,
treat1= treat1,
treat2= treat2,
studlab = study,
data = p1,
sm = "MD",
fixed = FALSE,
random = TRUE,
reference.group = "2",
details.chkmultiarm = FALSE,
sep.trts = " vs. ",
C.matrix = C)
# results in error:
# Error in B.matrix %*% C.matrix : non-conformable arguments
# In addition: Warning message:
# No treatment contains the component separator '+'.
```
|
If this is a new EC2 instance, it might is under the default block on SMTP port 25. This is to avoid misuse of EC2 to send spam emails. Steps to get this opened are explained in the link [**link**][1] .
Along with this, you may also want to make sure that your EC2 instance is having a public IP (EIP) and security-groups/NACL/Routing is all good to support this communication
[1]: https://repost.aws/knowledge-center/ec2-port-25-throttle |
> Is there a vulnerability to this?
There should not be a vulnerability to this, as long as the fetched [HTTP-only cookie](https://en.wikipedia.org/wiki/HTTP_cookie#Http-only_cookie) is not exposed to client-side JavaScript. The use of HTTP-only cookies is a security measure to prevent client-side scripts from accessing the cookie data, which helps mitigate cross-site scripting (XSS) attacks.
> Basically can I have a button that when you click it, it will return the value of the HTTP-ONLY cookie, we attach it to the request headers?
I suppose, as long as everything is done on the server-side, through a [server action](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).
It does not matter if it is through:
- [SSR (Server-Side Rendering)](https://nextjs.org/docs/pages/building-your-application/rendering/server-side-rendering), which involves rendering components on the server and sending the HTML to the client. During SSR, HTTP-ONLY cookies can be accessed on the server to pre-render pages with data that may be user-specific.
- [RSC (React Server Components)](https://nextjs.org/docs/app/building-your-application/rendering/server-components), allowing you to build components that render exclusively on the server. These components can directly access server-side data sources, such as databases or the file system, and can work with HTTP-ONLY cookies on the server.
The button mentioned in your question is likely intended to trigger a server-side action. The button would be part of a client-side component, and when clicked, it would send a request to the server action.
The reason for the button would be to initiate an interaction that requires server-side processing involving HTTP-ONLY cookies, such as refreshing a session, fetching user-specific data, or performing an action that requires authentication. By using server-side logic to handle the cookie, you would keep the token secure by never exposing it to the client-side environment, thus reducing the risk of XSS and CSRF attacks.
A typical workflow would be:
```bash
Client-Side Next.js Server External API
| | |
| Click Button | |
|-------------------------> | |
| | Read HTTP-only cookie |
| | from request headers |
| | |
| | Attach cookie to |
| | Authorization header |
| | |
| |---------------------------> |
| | Make authenticated |
| | request to API |
| | |
| <------------------------- | |
Receive | Response (no sensitive | |
data | data exposed) | |
| | |
| | |
V V V
```
The user interacts with the client-side by clicking a button, and the click event triggers a request to a server-side endpoint in the Next.js application.
The server-side code reads the HTTP-only cookie from the request headers (cookies are automatically sent by the browser with the request). It then attaches this cookie to the Authorization header (as a bearer token) for an outgoing request to an external API. This action is performed server-side and the cookie value is never exposed to the client.
The Next.js server makes (for instance) the authenticated request to the external API. Once the external API responds, the Next.js server processes the response. It may return some data to the client-side, but the HTTP-only cookie value itself is not included in this response, ensuring that it's not exposed to client-side JavaScript.
----
As a good illustration of this issue, consider [`vercel/next.js` discussion 59303](https://github.com/vercel/next.js/discussions/59303):
> ## No way to (securely) access cookies/headers for client component SSR
The discussion touches on the need for a method to access cookies securely during SSR without exposing them to the client, which is precisely your concern regarding the secure handling of JWTs and other sensitive information stored in cookies.
> Passing the cookie as a prop to the client component will result in the cookie value being serialized in the page and thus accessible to JavaScript.
So this is an area where Next.js might need further development to make sure security best practices can be easily and reliably implemented. |
I am trying to perform a network meta-analysis. The network contains 3 subnetworks. Therefore I decided to use netmeta::discomb to perform an additive analysis. This worked without error in another project, but not with the new studies.
My current dataset contains 9 studies over a total of 10 treatments (all two-armed, continuous outcome) . The data was transformed from the arm-based to the contrast-based design using netmeta::pairwise. When calling the method netmeta::discomb, the error appears that the dimensions of the edge-vertex incidence matrices B and C are non-conformable. I guess, the warning about the missing separator will later become a problem.
The help says: *By default, the matrix C is calculated internally from treatment names.* Passing a C-matrix myself was also unsuccessful. Since the object `m1.netmeta` is not created, I cannot call `C.matrix` to recognize a structural error there.
I would like to be able to create a reasonable overview at the end, i.e. with
`summary(m1.netmeta)`, `netgraph(m1.netmeta)` and `forest(m1.netmeta,...)`.
If required, I can also provide the data and script from the previous project. Maybe it will help.
The minimal code used is below. This is session info:
R version 4.3.2 (2023-10-31 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19045)
Matrix products: default
I appreciate any help and will be happy to answer any questions.
```
library(netmeta)
df <- data.frame(study= c('study 1', 'study 1', 'study 2', 'study 2', 'study 3', 'study 3',
'study 4', 'study 4', 'study 5', 'study 5', 'study 6', 'study 6',
'study 7', 'study 7', 'study 8', 'study 8', 'study 9', 'study 9'),
stud_ind= c(1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2),
comparators= c(1, 2, 3, 2, 1, 2, 4, 2, 5, 0, 6, 2, 7, 2, 6, 2, 8, 9),
n_probands= c(14, 14, 15, 15, 9, 9, 19, 19, 21, 21, 27, 27, 15, 15, 18, 19, 14, 11),
mean= c(3.13, 3.47, 2.36, 3.61, 2.89, 2.78, 2.36, 2.36, 2.64, 5.00, 3.24,
3.28, 1.53, 1.53, 3.07, 2.89, 3.00, 3.30),
sd= c(2.06, 1.74, 1.99, 1.95, 1.97, 1.29, 1.32, 1.32, 1.68,
2.75, 1.21, 1.17, 1.20, 1.20, 2.23, 2.56, 1.53, 1.52))
# long to wide + contrast based
df_wide = df %>%
pivot_wider(names_from=c(stud_ind), values_from=c(comparators, n_probands, mean, sd))
p1 <- pairwise(list(comparators_1, comparators_2),
TE = list(mean_1, mean_2), seTE = list(sd_1, sd_2),
data = df_wide, sm = "MD", reference.group = "2")
# look at network
nc1 <- netconnection(
data=p1,
sep.trts = ":",
nchar.trts = 500,
title = "",
warn = FALSE,
)
print(nc1)
#################################
m1.netmeta <- discomb(TE = TE,
seTE = seTE,
treat1= treat1,
treat2= treat2,
studlab = study,
data = p1,
sm = "MD",
fixed = FALSE,
random = TRUE,
reference.group = "2",
details.chkmultiarm = FALSE,
sep.trts = " vs. ")
# results in error:
# Error in B.matrix %*% C.matrix : non-conformable arguments
# In addition: Warning message:
# No treatment contains the component separator '+'.
#################################
# try with 'own' C.matrix
C <- rbind(c(1, 0, 0, 0, 0, 0, 0, 0, 0), # 0
c(0, 1, 0, 0, 0, 0, 0, 0, 0), # 1
c(0, 0, 1, 0, 0, 0, 0, 0, 0), # 2
c(0, 0, 0, 1, 0, 0, 0, 0, 0), # 3
c(0, 0, 0, 0, 1, 0, 0, 0, 0), # 4
c(0, 0, 0, 0, 0, 1, 0, 0, 0), # 5
c(0, 0, 0, 0, 0, 0, 1, 0, 0), # 6
c(0, 0, 0, 0, 0, 0, 0, 1, 0), # 8
c(0, 0, 0, 0, 0, 0, 0, 0, 1)) # 9
colnames(C)<-c("0","1","2","3","4","5","6","8","9")
rownames(C)<-c("0","1","2","3","4","5","6","8","9")
m2.netmeta <- discomb(TE = TE,
seTE = seTE,
treat1= treat1,
treat2= treat2,
studlab = study,
data = p1,
sm = "MD",
fixed = FALSE,
random = TRUE,
reference.group = "2",
details.chkmultiarm = FALSE,
sep.trts = " vs. ",
C.matrix = C)
# results in error:
# Error in B.matrix %*% C.matrix : non-conformable arguments
# In addition: Warning message:
# No treatment contains the component separator '+'.
```
|
Don't make the row expand in the column: because it will allocate all of the available screen space.
you only need to let the large button that will take a very long text to expand within the row:
try
@override
Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(),
body: Column(
children: [
Padding(
padding: EdgeInsets.all(20),
child:Row(
children: [
Expanded(child:
GestureDetector(
onTap:(){},
child: Container(
color: Colors.amber,
child:Text('HI, button 1 long text here, long text herelong text herelong text herelong text herelong text herelong text herelong text herelong text herelong text here'),
),
),),
SizedBox(width: 20,),
GestureDetector(
onTap:(){},
child: Container(
color: Colors.green,
child:Text('button2'),
),
),
],
))
],
)
);
}
}
[![result: ][1]][1]
[1]: https://i.stack.imgur.com/AN6Jmm.png
and of course you can align both buttons using `mainAxisAlignment` property of the `Row` widget.
Hope it helps you. |
I'm using Inertia to build a Laravel Vue app with Laravel 11 and Vue 3. The issue I'm facing involves a controller called `ListingController` that is resourceful. I created it using the command `php artisan make:model Listing -mrc`, which automatically creates a controller, model, and migration. All the pages were loading fine until I added an `auth` middleware in my `web.php`.
```
use App\Http\Controllers\AuthController;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PagesController;
use App\Http\Controllers\ListingController;
Route::get('/', [PagesController::class, 'home'])->name('home');
Route::get('login', [AuthController::class, 'create'])->name('login');
Route::post('login', [AuthController::class, 'store'])->name('login.store');
Route::delete('logout', [AuthController::class, 'destroy'])->name('logout');
// Allow access to listings.index and listings.show without authentication
// Route::get('listings', [ListingController::class, 'index'])->name('listings.index');
// Route::get('listings/{id}', [ListingController::class, 'show'])->name('listings.show');
route::get('register', [UserController::class, 'create'])->name('register');
route::post('register', [UserController::class, 'store'])->name('register.store');
Route::resource("listings", ListingController::class)->only(['index', 'show']);
Route::middleware('auth')->group(function () {
Route::resource("listings", ListingController::class)->only(['destroy', 'edit', 'store', 'update', 'create']);
});
```
I can access `/listings/edit` and send requests via other methods such as `destroy`, `store`, and `update`. However, the page for `/listings/create` will not load, and the browser throws a 404 not found error. I have even run `php artisan route:list` to ensure it exists.
```
GET|HEAD / .................................................................. home › PagesController@home
POST _ignition/execute-solution ignition.executeSolution › Spatie\LaravelIgnition › ExecuteSolutionC…
GET|HEAD _ignition/health-check ... ignition.healthCheck › Spatie\LaravelIgnition › HealthCheckController
POST _ignition/update-config ignition.updateConfig › Spatie\LaravelIgnition › UpdateConfigController
GET|HEAD listings .............................................. listings.index › ListingController@index
POST listings .............................................. listings.store › ListingController@store
GET|HEAD listings/create ..................................... listings.create › ListingController@create
GET|HEAD listings/{listing} ...................................... listings.show › ListingController@show
PUT|PATCH listings/{listing} .................................. listings.update › ListingController@update
DELETE listings/{listing} ................................ listings.destroy › ListingController@destroy
GET|HEAD listings/{listing}/edit ................................. listings.edit › ListingController@edit
GET|HEAD login ............................................................ login › AuthController@create
POST login ....................................................... login.store › AuthController@store
DELETE logout ......................................................... logout › AuthController@destroy
GET|HEAD register ...................................................... register › UserController@create
POST register ................................................. register.store › UserController@store
GET|HEAD up ................................................................. generated::LiOjdZsBMrWYI3QG
```
This is the screen shot of my browser when i try to access /listings/create
[](https://i.stack.imgur.com/vX92m.png)
However, when I change the order in which the routes are defined in my `web.php`, I am able to access `/listings/create`. By changing the order, I mean like this:
```
use App\Http\Controllers\AuthController;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PagesController;
use App\Http\Controllers\ListingController;
Route::get('/', [PagesController::class, 'home'])->name('home');
Route::get('login', [AuthController::class, 'create'])->name('login');
Route::post('login', [AuthController::class, 'store'])->name('login.store');
Route::delete('logout', [AuthController::class, 'destroy'])->name('logout');
// Allow access to listings.index and listings.show without authentication
// Route::get('listings', [ListingController::class, 'index'])->name('listings.index');
// Route::get('listings/{id}', [ListingController::class, 'show'])->name('listings.show');
route::get('register', [UserController::class, 'create'])->name('register');
route::post('register', [UserController::class, 'store'])->name('register.store');
Route::middleware('auth')->group(function () {
Route::resource("listings", ListingController::class)->only(['destroy', 'edit', 'store', 'update', 'create']);
});
Route::resource("listings", ListingController::class)->only(['index', 'show']);
```
When I attempt to access in both scenarios, I am authenticated.
I will provide any other information required to debug this issue. I have read through the documentation and found no mention that the order of routes matters.
Other solutions I have tried include:
1. Creating another route to serve the same page via a different
method defined in the controller. This approach works.
```
Route::middleware('auth')->group(function () {
Route::get('listings.create', [ListingController::class, 'create2'])->name('listings.create2');
});
```
2. However if i were to use listings/make instead , the browser throws the same 404 error.
```
Route::middleware('auth')->group(function () {
Route::get('listings/create', [ListingController::class, 'create2'])->name('listings.create2');
});
```
3. I have also tried running php artisan route:clear and php artisan optimize, still got the same 404 error.
I'm currently using `php artisan serve` for my application. |
Ok I found the solution. I used wrong name for `images`. I have to use `images` instead of `images[]`:
[![enter image description here][1]][1]
This is a bit strange, because as you can see I have `categoryIds[]` it is an array, and it works as expected.
Now I see:
[![enter image description here][2]][2]
[1]: https://i.stack.imgur.com/NKvys.png
[2]: https://i.stack.imgur.com/H8eyB.png |
For RFC 9110, the current HTTP spec as of 2024-03-31, the following statuses MUST NOT generate content:
- [Informational 1xx](https://datatracker.ietf.org/doc/html/rfc9110#name-informational-1xx)
- [204 No Content](https://datatracker.ietf.org/doc/html/rfc9110#name-204-no-content)
- [205 Reset Content](https://datatracker.ietf.org/doc/html/rfc9110#name-205-reset-content)
- [304 Not Modified](https://datatracker.ietf.org/doc/html/rfc9110#name-304-not-modified) |
How to load a module from a byte sequence without saving it to a file in python version 3.11? |
|python|python-3.x|pyc| |
I am making an article in quarto, for which I need a word (docx) output file. The article should be in 2 column format. To achieve the 2 column output in word, I referred to the answer given in [this question](https://stackoverflow.com/q/76452715/21281335). Here the answer involved making sections within the .qmd file using office open XML. Since I know nothing about this, I blindly copied the answer and it works well. My practice document looks like this[practice document](https://i.stack.imgur.com/Don9x.png).
In the document, I inserted some figures(test figures) to see how it would look, and when I need the figures within a column, the above approach works well. The problem is when I have a bigger figure that I need to span across the 2 columns. I need the figure to span the 2 columns while the text part still keeps the 2 column format. Could anyone please help with this ?
Since I don't know anything about open office XML, I have no idea what to try. For one, I tried to close the 2 column section before the image to be spanned, and then opened a new 2 column section after the image. But this lead to the image being placed on a fresh page, and a lot of empty space in the page above,[as shown](https://i.stack.imgur.com/iZNEx.png).
I think maybe there is a way to make a full span section within the 2 column section, to put the image, but I don't really know how. Please help |
Span figure across columns in Quarto docx output |
|multiple-columns|docx|quarto| |
null |
For now the solution seemed to be to use an older release v3.0.1.
Running through the same steps stated above lead to a succesful installation.
I did do one thing slightly different - which is to load the OpenMP module, but I'm not sure if this makes any difference. For now I'm happily able to use ```python-flint``` after installing v3.0.1 |
You do not have rights to that file, and so you do not have rights to change the permissions of that file. A file in `Documents/` can only be accessed by the app that created the file, and only for the specific *installation* of that app. Apps that are uninstalled and reinstalled are considered to be independent installations.
(I doubt that technique would work anyway, as Android manages file permissions differently)
Ordinarily, I would steer you to the Storage Access Framework. However, that is designed to do what users want: give them control over the storage. You appear to be attempting to hide your activity from the user ("create hidden file"). Google, device manufacturers, and users are working very hard to prevent developers from doing this. |
null |
I'm trying to compare the user's input to the values in the database.
I want to then check if their input is in the database, if so it will print they have entered the valid details, if not it will print they have entered incorrect details.
```
def check_data_with_tbl(packet): # Takes the packets sent by the client and compares them to the fields in the database
sqlstring = """
SELECT * FROM tblUserDetails WHERE Username = ? AND PasswordHash = ?
"""
if sqlstring is not None:
print("Login Successful")
else:
print("Invalid Username or Password")
values = (packet['username'], packet['password'])
runsql(sqlstring, values)
```
At the moment it just prints login successful every time even if I enter incorrect details. |
I'm trying to build a work schedule tracker, starting with the header. A picture attachement shows how the design will look once completed [Schedule Header Cosmetics](https://i.stack.imgur.com/DtFf0.png)
I have three classes so far,
- InputWindow: A Toplevel window for a user to select a month and year from two comboboxes
- App: the main window, based on the user selections in InputWindow, App should load a header consisting of the elements in container TitleFrame
- TitleFrame: a frame consisting of the app title, the selected month and selected year on the left, and a grid consisting of weekdays for the month in the first row, day numbers of the month on the second row, and crew shifts as "D" or "N" on the third row.
Here is the code:
```
# PEP8 Compliant Guidance
# Standard Library Imports
import tkinter as tk
from tkinter import ttk
import datetime
# Third-Party Library Imports
# Local Application/Library Specific Imports
import functions
class InputWindow(tk.Toplevel):
def __init__(self, parent):
super().__init__(parent)
# Customize the top-level window as needed
self.title("Schedule Selection")
self.geometry("400x500")
# widgets, labels, and other elements for user selections
currentdate = datetime.datetime.now()
currentmonth = currentdate.strftime("%B")
currentyear = currentdate.strftime("%Y")
# Month Selection
self.select_schedule_month = ttk.Combobox(self, values=functions.months_list())
self.select_schedule_month.set(currentmonth)
self.select_schedule_month.pack()
# Year Selection
self.select_schedule_year = ttk.Combobox(self, values=functions.years_list())
self.select_schedule_year.set(currentyear)
self.select_schedule_year.pack()
# Button to confirm selections and open the main application window
sel_button = tk.Button(self, text="Confirm", command=self.confirm_selections)
sel_button.pack()
def confirm_selections(self):
# Perform validation and check if the proper selections are made
# If selections are valid, hide the top-level window and open the main application window
if self.selections_are_valid():
self.selected_month = self.select_schedule_month.get()
self.selected_year = self.select_schedule_year.get()
self.withdraw() # Hide the top-level window
self.master.deiconify() # Show the main application window
def selections_are_valid(self):
# Implement your logic to validate selections
# Return True if selections are valid, False otherwise
return True
# The Main App Window - 35 columns | 5 rows
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("Schedule Window")
self.geometry("1300x300")
self.open_input_window()
# title frame
self.title_frame = TitleFrame(self)
self.title_frame.grid(column=0, row=0, columnspan=35, padx=10, pady=10)
def open_input_window(self):
self.input_window = InputWindow(self)
# self.wait_window(self.input_window) # Wait for the top-level window to close
self.handle_input_window_selections()
def handle_input_window_selections(self):
if self.input_window is not None:
selected_month = self.input_window.selected_month
selected_year = self.input_window.selected_year
# Use the selected month and year to perform any necessary operations
print(selected_month, selected_year)
# title frame
self.title_frame = TitleFrame(self)
self.title_frame.grid(column=0, row=0, columnspan=35, padx=10, pady=10)
# Schedule Header: Includes - Title, Calendar, Shifts, Crew Name, and Crew ID
class TitleFrame(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
self.config(borderwidth=1, relief="raised", width=1300)
self.grid(column=0, row=0, columnspan=35, padx=10, pady=10)
self.title_label = tk.Label(self, text="Overtime Schedule", font=("Calibri", 22))
self.title_label.config(padx=462)
self.title_label.grid(column=0, row=0, columnspan=24, sticky="w")
self.ID_detection_label = tk.Label(self, text=f"Current User: {functions.get_user_id()}",
font=("Calibri", 12))
# self.ID_detection_label.config(bg="black", fg="white")
self.ID_detection_label.grid(column=34, row=0, sticky="e")
self.Calendar_Month_hdr = tk.Label(self, text="Schedule Calendar", font=("Calibri", 12))
self.Calendar_Month_hdr.grid(column=0, row=1)
# self.Calendar_Month_hdr.configure(bg="black", fg="white")
"""Need to add a calendar widget for this feature"""
self.Calendar_Month_label = tk.Label(self, text="Selected Month", font=("Calibri", 12))
self.Calendar_Month_label.grid(column=0, row=2)
self.Calendar_Year_label = tk.Label(self, text="Selected year", font=("Calibri", 12))
self.Calendar_Year_label.grid(column=0, row=3)
# Top Level Selector
class SelectorFrame(tk.Toplevel):
def __init__(self, parent):
super().__init__(parent)
pass
app = App()
app.withdraw() # Hide the main application window
app.mainloop()
```
initially the app ran fine until I attempted to create the variables from the combobox selections in InputWindow and use them in TitleFrame as labels. I'm very new at python and tkinter and wanted to experiment with calling the variables from another class before attempting to update class labels.
InputWindow Line 42 & 43 - initial assignment
```
self.selected_month = self.select_schedule_month.get()
self.selected_year = self.select_schedule_year.get()
```
Calling to App Line 71-75 to print the values selected in InputWindow
```
def handle_input_window_selections(self):
if self.input_window is not None:
selected_month = self.input_window.selected_month
selected_year = self.input_window.selected_year
# Use the selected month and year to perform any necessary operations
print(selected_month, selected_year)
```
All local import functions work as expected when tested
The error I'm seeing when trying to call the selected_month/selected_year variables is an AttributeError. I'm not sure how to call selections from outside of class so I need some education on this, but even removing these variables from the equasion, I still can't get the Toplevel window to appear.
```
Exception has occurred: AttributeError
'InputWindow' object has no attribute 'selected_month'
File "C:\Users\edit\OneDrive\Py Scripts\Tkinter GUI\Schedule App\Schedule_GUI.py", line 71, in handle_input_window_selections
selected_month = self.input_window.selected_month
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\edit\OneDrive\Py Scripts\Tkinter GUI\Schedule App\Schedule_GUI.py", line 67, in open_input_window
self.handle_input_window_selections()
File "C:\Users\edit\OneDrive\Py Scripts\Tkinter GUI\Schedule App\Schedule_GUI.py", line 58, in __init__
self.open_input_window()
File "C:\Users\edit\OneDrive\Py Scripts\Tkinter GUI\Schedule App\Schedule_GUI.py", line 116, in <module>
app = App()
^^^^^
AttributeError: 'InputWindow' object has no attribute 'selected_month'
```
Thank you for any help, I certainly have a lot to learn. |
Finally, I've found a solution to this problem without utilizing the redirect and refreshListenable properties of GoRouter.
The concept involves creating a custom redirection component. Essentially, authStateChanges are globbally listened, and upon any change in AuthenticationState, we navigate to our redirection component. In my implementation, this redirection component is a splash page. From there, you can proceed to redirect to the desired page.
Here is my code
Router Class
class AppRouter {
factory AppRouter() => _instance;
AppRouter._();
static final AppRouter _instance = AppRouter._();
final _config = GoRouter(
initialLocation: RoutePaths.splashPath,
routes: <RouteBase>[
GoRoute(
path: RoutePaths.splashPath,
builder: (context, state) => const SplashPage(),
),
GoRoute(
path: RoutePaths.loginPath,
builder: (context, state) => const LoginPage(),
),
GoRoute(
path: RoutePaths.registrationPath,
builder: (context, state) => const RegistrationPage(),
),
GoRoute(
path: RoutePaths.homePath,
builder: (context, state) => const HomePage(),
),
],
);
GoRouter get config => _config;
}
class RoutePaths {
static const String loginPath = '/login';
static const String registrationPath = '/register';
static const String homePath = '/home';
static const String splashPath = '/';
}
Authentication Bloc
AuthenticationBloc(
this.registerUseCase,
this.loginUseCase,
) : super(const AuthenticationInitial()) {
on<AuthenticationStatusCheck>((event, emit) async {
await emit.onEach(
FirebaseAuth.instance.authStateChanges(),
onData: (user) async {
this.user = user;
emit(const AuthenticationSplash());
await Future.delayed(const Duration(seconds: 1,
milliseconds: 500),
() {
if (user == null) {
emit(const AuthenticationInitial());
} else if (state is! AuthenticationSuccess) {
emit(AuthenticationSuccess(user));
}
});
},
);
});
Main
final router = AppRouter().config;
return MultiBlocProvider(
providers: [
BlocProvider<AuthenticationBloc>(
create: (context) =>
sl<AuthenticationBloc>()..add(const AuthenticationStatusCheck()),
),
],
child: BlocListener<AuthenticationBloc, AuthenticationState>(
listener: (context, state) {
if (state is AuthenticationSplash) {
router.go(RoutePaths.splashPath);
}
},
child: MaterialApp.router(
title: 'Hero Games Case Study',
theme: ThemeData.dark(
useMaterial3: true,
),
routerConfig: router,
),
),
);
splash_page
return BlocListener<AuthenticationBloc, AuthenticationState>(
listener: (context, state) {
if (state is AuthenticationSuccess) {
context.go(RoutePaths.homePath);
} else if (state is AuthenticationInitial) {
context.go(RoutePaths.loginPath);
}
},
child: Scaffold(
appBar: AppBar(
title: const Text('Splash Page'),
),
body: const Center(
child: CircularProgressIndicator(),
),
),
);
NOTE:
If you will use deeplinking, you can add the code below to your GoRouter
redirect: (context, state) {
if (context.read<AuthenticationBloc>().user == null &&
(state.fullPath != RoutePaths.loginPath &&
state.fullPath != RoutePaths.registrationPath &&
state.fullPath != RoutePaths.splashPath)) {
return RoutePaths.splashPath;
}
return null;
},
|
{"Voters":[{"Id":7733418,"DisplayName":"Yunnosch"}]} |
The image here is just an example of what it is I'm trying to do. I have containers (left, main, right) and I want a visualized border, which I assume I will do via image of some sort. I honestly have no idea what they used here, nor how to create my own version of it with new artwork.
[](https://i.stack.imgur.com/28742.png)
I created a border image and now my website looks like a potato chunk slicer
But then after messing with the settings, it now looks like this:
[](https://i.stack.imgur.com/x1KVS.jpg)
At first I had utilized a picture of a border and just added 'border, like this here:
[](https://i.stack.imgur.com/SaiaM.jpg)
That looked like this when implemented on the site:
[![enter image description here][1]][1]
That made it look like this, which I guess isn't too terrible and more in line with my goal. I added this line to my index.html to get the above image:
`border-image: url("{{ url_for('static', filename='border.png')}}") 16 round;`
That wasn't what I wanted so I went into photoshop and created a border_top, _bottom, _left, _right and then tried to slice it and boy did it go wonky.
Image of border image: [](https://i.stack.imgur.com/10Uyc.png)
I only list one, but the others are just like it and are separated by side.
Then I tried this:
```
.container {
position: relative;
display: grid;
grid-template-columns: 1fr 3fr 1fr; /*Adjust the fr units as per your design */
gap: 10px;
height: 100vh; /* Use the full height of the viewport */
}
.container::before,
.container::after {
content: '';
position: absolute;
pointer-events: none;
}
.container::before { /* Top and bottom border */
top: 0; right: 0; bottom: 0; left: 0;
height: 100%;
border: solid transparent;
border-width: 16px 0; /* Top and bottom borders */
background-repeat: round;
background-image: url('border_top.png'), url('border_bottom.png');
background-position: top, bottom;
background-size: 100% 16px; /* Scale to the container width */
}
.container::after { /* Left and right border */
top: 0; right: 0; bottom: 0; left: 0;
width: 100%;
border: solid transparent;
border-width: 0 16px; /* Left and right borders */
background-repeat: round;
background-image: url('border_left.png'), url('border_right.png');
background-position: left, right;
background-size: 16px 100%; /* Scale to the container height */
```
and I ended up with the above picture of the potato chunk slicer. lol
Fair warning - I do NOT know what is standard for creating borders. Is there a way to take just a high-resolution texture and turn it into a border or do I have to create a border in the exact dimensions of each .container? Or? I have scoured the interwebs and see that using images as borders is problematic, but it was done in the above image so I'd like to try to get something similar in mine.
All help is appreciated. For the record, I have played around with all px sizes within. Some of them change the waffle pattern slightly but nothing that appears to fix the problem.
This is my index.html:
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My RPG Game</title>
<link
rel="stylesheet"
href="{{ url_for('static', filename='style.css') }}"
/>
<style>
.main-content {
position: relative;
border: 16px solid transparent;
/*border-image: url("{{ url_for('static', filename='border.png')}}") 16
round;*/
}
.main-content::before {
content: "";
position: absolute;
top: -16px;
left: 0;
width: 100%;
height: 16px;
background: url("{{ url_for('static', filename='border_top.png') }}")
repeat-x;
}
/* Bottom border */
.main-content::after {
content: "";
position: absolute;
bottom: -16px;
left: 0;
width: 100%;
height: 16px;
background: url("{{ url_for('static', filename='border_bottom.png') }}")
repeat-x;
}
.sidebar-left {
border: 16px solid transparent;
border-image: url("{{ url_for('static', filename='border.png')}}") 16
round;
}
.sidebar-right {
border: 16px solid transparent;
border-image: url("{{ url_for('static', filename='border.png')}}") 16
round;
}
/* Left border */
.sidebar-left::before {
content: "";
position: absolute;
top: 0;
left: -16px;
width: 16px;
height: 100%;
background: url("{{ url_for('static', filename='border_left.png') }}")
repeat-y;
}
/* Right border */
.sidebar-right::after {
content: "";
position: absolute;
top: 0;
right: -16px;
width: 16px;
height: 100%;
background: url("{{ url_for('static', filename='border_right.png') }}")
repeat-y;
}
</style>
</head>
<body>
<div class="container">
<aside class="sidebar-left">
<!-- Character's location and stats go here -->
</aside>
<main class="main-content">
<!-- Main game content and chat area go here -->
<div class="chat">
<!-- Chat content goes here -->
</div>
<div class="inventory">
<!-- Inventory list goes here -->
</div>
<!-- Add additional sections as needed -->
</main>
<aside class="sidebar-right">
<!-- Additional information or ads could go here -->
</aside>
</div>
<script src="{{ url_for('static', filename='script.js') }}"></script>
</body>
</html>
```
This is my full style.css:
```
/* Reset margins and padding */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* Container for the entire layout */
.container {
position: relative;
display: grid;
grid-template-columns: 1fr 3fr 1fr; /*Adjust the fr units as per your design */
gap: 10px;
height: 100vh; /* Use the full height of the viewport */
}
.container::before,
.container::after {
content: '';
position: absolute;
pointer-events: none;
}
.container::before { /* Top and bottom border */
top: 0; right: 0; bottom: 0; left: 0;
height: 100%;
border: solid transparent;
border-width: 16px 0; /* Top and bottom borders */
background-repeat: round;
background-image: url('border_top.png'), url('border_bottom.png');
background-position: top, bottom;
background-size: 100% 16px; /* Scale to the container width */
}
.container::after { /* Left and right border */
top: 0; right: 0; bottom: 0; left: 0;
width: 100%;
border: solid transparent;
border-width: 0 16px; /* Left and right borders */
background-repeat: round;
background-image: url('border_left.png'), url('border_right.png');
background-position: left, right;
background-size: 16px 100%; /* Scale to the container height */
}
.sidebar-left,
.sidebar-right {
background-color: #806c50; /* Example color */
/* Add more styling */
}
.main-content {
border-top: 16px solid transparent;
border-right: 16px solid transparent;
border-bottom: 16px solid transparent;
border-left: 16px solid transparent;
border-image-source: url('/static/border_top.png') 16 round,
url('/static/border_right.png') 16 round,
url('/static/border_bottom.png') 16 round,
url('/static/border_left.png') 16 round;
border-image-slice: 200;
border-image-repeat: repeat;
display: grid;
grid-template-rows: 1fr auto; /* Adjust the row sizes as needed
gap: 10px;*/
}
.chat {
background-color: #5c4838; /* Example color */
overflow-y: auto; /* If you want the chat to be scrollable */
/* Add more styling */
}
.inventory {
overflow-y: auto; /* Scrollable list of items */
/* Add more styling */
}
/* Responsive design */
@media (max-width: 768px) {
.container {
grid-template-columns: 1fr; /* Stack sidebars and content on smaller screens */
}
.sidebar-left,
.sidebar-right {
display: none; /* Hide sidebars on smaller screens, or adjust as needed */
}
.main-content {
border-image: none; /* Remove the border image on smaller screens if needed */
grid-template-rows: auto; /* Adjust layout for mobile */
}
}
```
[1]: https://i.stack.imgur.com/44aK6.png |
How do I add visual border, from image, that is flexible and scalable? |
|html|css|border| |
null |
I'm using `Intellij Ultimate 2023.3.6` and LiveTemplate to add TODO with words "todo" not working anymore.
I tried to clear cache, restart, disable and re-enable live template but nothing seems working.
Can someone help me? Thanks.
I'm talking about this, in past versions of intellij works as expected:
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/g8wbz.png |
LiveTemplate for TODO shortcut seems not working |
|intellij-idea| |
the only other code used in this from anywhere else is Player::getPosition(), which is just returning playerSprite.getPosition() and
Game::update which passes Player::getPosition() to this function
`sf::Vector2f enemyLocation{0.f, 0.f};`
starting value of enemyLocation for debugging
```
///<summary>
/// gets the amount enemy should move
/// called from Game.update()
///</summary>
/// <param name="t_playerPos"> player window position </param>
/// <returns> enemy move amount per frame (normalised) </returns>
sf::Vector2f Enemy::attemptMove(sf::Vector2f t_playerPos)
{
sf::Vector2f movement = { 0.f, 0.f }; // movement towards player each frame
sf::Vector2f direction = t_playerPos - enemyLocation; // delta playerPos and enemyPos
float angle = atan2f(direction.y, direction.x); // angle to player (rad)
angle = angle * 180.f / M_PI; // convert angle to degrees
float hyp = 1.f; // length of line to player (used for normalisation of vector)
// check if enemy is horizontally in line with player
if (direction.x == 0.f) {
if (direction.y > 0.f) { movement.y = hyp; } // move straight down
else { movement = -hyp; } // move straight up
}
// check if enemy is vertically in line with player
else if (direction.y == 0.f) {
if (direction.x > 0.f) { movement.x = hyp; } // move right
else { movement.x = -hyp; } // move left
}
// if enemy is not in line with player
else {
// ratio of sides y:x = opp:adj
movement.y = sinf(angle);
movement.x = cosf(angle);
// normalising the vector
hyp = sqrtf(abs(movement.x * movement.x) + abs(movement.y * movement.y));
hyp = abs(1.f / hyp); // inverse of pythagoras theorem hypothenuse
movement.x = hyp * movement.x;
movement.y = hyp * movement.y; // sqrt(x^2 + y^2) should equal 1
move(movement);
}
return movement; // return to Game::update() (not currently assigned to anything there)
}
///<summary>
/// moves the enemy by the amount it should each frame
/// in final code will be called from Game.update()
/// for now only called from Enemy::attemptMove()
///</summary>
///<param name="t_movement"> amount to move each frame towards player </param>
void Enemy::move(sf::Vector2f t_movement)
{
enemyLocation += t_movement; // update enemy location
enemySprite.setPosition(enemyLocation); // set enemy position to updated location
}
```
my includes are
```
#include <SFML/Graphics.hpp>
#include <iostream>
#define _USE_MATH_DEFINES
#include <math.h>
```
I expect the enemy to move in a straight line to the player, which does happen if the player is stationary
If the player moves diagonally away from the enemy, this also works, but if the player moves any other direction, the enemy spins in a circle (sometimes spiral) until the player stops moving or starts moving diagonally away from the enemy, or sometimes moves in a straight line in a completely wrong direction.
I have tried:
- assigning attemptMove() to a variable in Game::update and passing that to Enemy::move()
- including an alpha and beta angle and calculating the ratios of the angle by Sine rule
- including breakpoints to verify the angle is correct (it always seems to be)
- removing the checks for "in line" with player and always running the calculation
- changing if (movement.x/y == 0.f) to if (abs(movement.x/y) < 0.01f) and < epsilon
- changing where the functions are called from and what args are passed to them
- a few other changes, none of which seemed to have any promise
- rewriting large sections of the code outside of the block shown, which naturally had no effect
- cleaning up my code, (this is actually even cleaner than the one in my actual project, though I did run it to make sure it definitely didn't work before posting it)
nothing seems to have any effect, and a lot of things make the problem worse or more severe, I really don't know what else there is to do |
I'm using PyQt6 connecting to MySql database.
I created a QSqlRelationalTableModel then a QDataWidgetMapper to map a record to some widgets.
I insert a new record to the model, then position the datawidgetmapper to that record.
I don't get the default values from the database in the widgets.
I tried to print the `model.record().field(0).defaultValue()`, I always get None for all fields.
My question now, should the model get the default values from the database, or I have to set it using `QSqlField.setDefaultValue()`.
Now I tried to set the default values manually `model.record().field(i).setDefaultValue("someValue")` then `print(model.record().field(i).defaultValue()` I get `None`.
Tried it with a record form the database `db.record(tableName)` and get `None` too. |
|mysql|pyqt6| |
Just use a functional component in the table to add slot props to the columns automatically:
[VUE SFC PLAYGROUND][1]
```
<script setup>
const rows = [{
name: "Row 1",
col2: "XX",
col3: "YY"
},
{
name: "Row 2",
col2: "XX",
col3: "YY"
},
{
name: "Row 3",
col2: "XX",
col3: "YY"
}];
import { useSlots } from 'vue';
const slots = useSlots();
const renderCols = props => {
const cols = slots.default();
cols.forEach(vnode => Object.assign(vnode.props ??= {}, props));
return cols;
};
</script>
<template>
<table>
<thead>
<render-cols renderAs="header"/>
</thead>
<tbody>
<tr v-for="(row, index) of rows" :key="index">
<render-cols renderAs="cell" :row="row"/>
</tr>
</tbody>
</table>
</template>
```
The usage:
```
<script setup>
import FSTable from './FSTable.vue';
import FSTableColumn from './FSTableColumn.vue';
import { ref } from 'vue'
const msg = ref('Hello World!')
</script>
<template>
<FSTable>
<FSTableColumn header="Column 1" property="name" v-slot="cellProps">
<!-- This column renders a custom cell -->
CustomCell: {{ cellProps.value }}
</FSTableColumn>
<FSTableColumn header="Column 2" property="col2">
<!-- This column renders the default cell -->
</FSTableColumn>
<FSTableColumn header="Column 3" property="col3">
<!-- This column renders a custom header -->
<template #header="headerProps">
CustomHeader: {{ headerProps.header }}
</template>
</FSTableColumn>
</FSTable>
</template>
```
[1]: https://play.vuejs.org/#eNqtVltvEz0Q/SvDfg9ppWb7lfIUklZQFQEPgGglQCwP210n2bKxV7Y3TRXtf+eMvdeQlotQpMSey/GZ8cw42+BFUYTrUgSTYGoSnRWWjLBlcRbJbFUobenV1XV8kwuaa7WiUXhc79lp9HzX6kLl5Uru2nrpjseWtJhTVduyLpKRTJQ0llZmQTPWH4xeizxX9EnpPH0yOozk9NjTBEFsrFgVeWwFdtP6MCyJmk3NZyniVOhZFNT7kyigQqtCaHsPqYxXApL12OTKYp/gzA9QmyhwaMB7Mh7T9TIzlHgELSQQDcWUlMYiAvah8bi2v3DCC8gmtN06pQMM13FeCqoqR3KYn98h/nRIHGQg+RVHuxSUinlc5nZA8y/OP/3pfEh+O0cerctSe330X3uQXwyz3+TztdO5jPbMwhrWJ5XD6lXFvihbiVv3jIOjwBpU4DxbhLdGSTTFliE40FWR5UK/L2yGCo0CkPCnRUGMAr1762RWl+KokSdLkXzfI781G5ZFwQctjNBrlF6rs7FeCOvVl1fvxAbrVrlSaZnD+hHlR2EQJXP0Zi9LmYJ2z86xfeNaMJOLa3O5sUKaJigmypaVs48CtOXFI6F3dE/DZ84vkhWy2JsRewYLoUC4y7W6M2jzrzUcdyFz/qjuuEFrxlziLP38uS86ZdGXL1HQkd2Dgt74Byio8D9A+YYJ15txpRFXGCpmMOicic8BTxxOQmN3cNhT+gZC3bIFtx1+z5hil0Ocz0oHE9ZN7jAcNRPOlb6Mk+XBWqpUsPf7m1uR2DA2JltILw499Pn5jLbVkT/o0GNoXJmWDsrxqvA9mMDDGcwt3c5g3nBrtk089fGMHWe/fmHalo+C48btuO83tTcqve9ArMagRlhwPEAFHVEGoM0hqbkrKAyoyXfBw8nJezPkYQI8FNkP/tjhu+Pi2OiOWMsF630jhD9dA3QPH7fBTqKWiCOb40CX8LDhQ7PZjEY+JyOwSnLcFVuNe6Oe79sVaS99NGmHqEdsFG0omJt9TW9iMl4T1rLml4KfyI14mCTn7XGKE/fete7N00HnfFdfh8JvNGHpPr6/9EPzBQ+Ew3W0c0WDgUR5LBdgaJv3xjdW3W78cGZSuIdmWg+HJgnnEzJWY4q6VqH6TdqVNjR35QgEoljeu3115rp2+O/G2Hv88cKLVAiOwqaOQBGnKWAmdPJ/sXHON0q7d/Gk2BDmf5bSQseMi4QAkVHOguoHQy5DTA== |
I added uielement textbox to ligtningchartjs. I want to delete uielement ligtningchartjs on scale.
`this.chart .addUIElement(UIElementBuilders.TextBox) .setDraggingMode(UIDraggingModes.notDraggable) .setText('ID: ' + label) .setPosition({ x: xPosition + 1.6, y: 88 })` |
How to delete added UıElement |
|javascript|lightningchart| |
null |
I would like to replace all `<span>` elements containing the attribute `font-weight:` with `<strong>` elements.
I am using the following regex
```
$text = preg_replace("@<span (.*?)style=(.*?)font-weight:(.*?)>(.*?)</span>@i", "<strong>$4</strong>", $text);
```
that is a little variation of the solution proposed by onatm here: https://stackoverflow.com/questions/7903813/how-do-i-replace-span-style-font-weightbold-span-with-strong-stro
Unfortunately this regex delete from the $text string all <span> element that do not contain the `font-weight:` attribute. This is something I do not want. My goal is to replace only the spans that contain font-weight: and leave without change any other element.
I have created a live example here: https://onlinephp.io/c/c0b92
How can the problem be solved ?
Thank you for your help :) |
replace <span> elements with strong |
|php|regex| |
null |
{"OriginalQuestionIds":[32648371],"Voters":[{"Id":285587,"DisplayName":"Your Common Sense","BindingReason":{"GoldTagBadge":"mysqli"}}]} |
**function.json**
`{
"scriptFile": "__init__.py",
"disabled": false,
"bindings": [
{
"name": "blob",
"type": "blobTrigger",
"direction": "in",
"path": "{CONTAINERNAME}",
"connectionStringSetting": "BLOB_CONNECTION_STRING"
}
]
}`
**app/__init__.py**
`CONTAINERNAME =os.environ.get("CONTAINERNAME")`
`def main(blob: func.InputStream):
logging.info(f"Python blob trigger function processed blob \n"
f"Name:{blob.name}\n"
f"Blob Size: {blob.length} bytes")`
My requirement is to pass dynamic containername to function.json as it may change/update in future so somehow if I can pass it through environment variable. I have tried different ways like
- %CONTAINERNAME%
- ${CONTAINERNAME}
- {CONTAINERNAME}
- "pathStringSetting": "{CONTAINERNAME}",
But I'm getting same error: The 'app' function is in error: Unable to configure binding 'blob' of type 'blobTrigger'. This may indicate invalid function.json properties. Can't figure out which ctor to call.
|
use environment variable for path binding in azure python |
|python|azure|azure-functions|azure-blob-trigger|azure-triggers| |
null |
|php|pdo| |
The [handle class](https://www.mathworks.com/help/matlab/handle-classes.html) and its copy-by-reference behavior is the natural way to implement linkage.
It is, however, possible to implement a linked list in Matlab without OOP. And an abstract list which does *not* splice an existing array in the middle to insert a new element -- as complained in [this comment](https://stackoverflow.com/questions/1413860/matlab-linked-list#comment23877880_1422443).
(Although I do have to use a Matlab data type somehow, and adding new element to an existing Matlab array always requires memory allocation somewhere.)
The reason of this availability is that we can model linkage in other ways than pointer/reference. The reason is *not* [closure](https://en.wikipedia.org/wiki/Closure_(computer_programming)) with [nested functions](https://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html).
I will nevertheless use closure to encapsulate a few *persistent* variables. At the end, I will include an example to show that closure alone confers no linkage. And so [this answer](https://stackoverflow.com/a/1421186/3181104) as written is incorrect.
At the end of the day though, linked list in Matlab is only an academic exercise. Matlab, aside from aforementioned handler class and classes inheriting from it (called subclasses in Matlab), is purely copy-by-value. Matlab will optimize and automate how copying works under the hood. It will avoid deep copy whenever it can. That is probably the better take-away for OP's question.
That is also why linked list is not obvious to make in Matlab.
-------------
##### Example Matlab linked list:
```lang-matlab
function headNode = makeLinkedList(value)
% value is the value of the initial node
% for simplicity, we will require initial node; and won't implement insert before head node
% for the purpose of this example, we accommodate only double as value
% we will also limit max list size to 2^31-1 as opposed to the usual 2^48 in Matlab vectors
m_id2ind=containers.Map('KeyType','int32','ValueType','int32'); % pre R2022b, faster to split than to array value
m_idNext=containers.Map('KeyType','int32','ValueType','int32');
%if exist('value','var') && ~isempty(value)
m_data=value; % stores value for all nodes
m_id2ind(1)=1;
m_idNext(1)=0; % 0 denotes no next node
m_id=1; % id of head node
m_endId=1;
%else
% m_data=double.empty;
% % not implemented
%end
headNode = struct('value',value,...
'next',@next,...
'head',struct.empty,...
'push_back',@addEnd,...
'addAfter',@addAfter,...
'deleteAt',@deleteAt,...
'nodeById',@makeNode,...
'id',m_id);
function nextNode=next(node)
if m_idNext(node.id)==0
warning('There is no next node.')
nextNode=struct.empty;
else
nextNode=makeNode(m_idNext(node.id));
end
end
function node=makeNode(id)
if isKey(m_id2ind,id)
node=struct('value',id2val(id),...
'next',@next,...
'head',headNode,...
'push_back',@addEnd,...
'addAfter',@addAfter,...
'deleteAt',@deleteAt,...
'nodeById',@makeNode,...
'id',id);
else
warning('No such node!')
node=struct.empty;
end
end
function temp=id2val(id)
temp=m_data(m_id2ind(id));
end
function addEnd(value)
addAfter(value,m_endId);
end
function addAfter(value,id)
m_data(end+1)=value;
temp=numel(m_data);% new id will be new list length
if (id==m_endId)
m_idNext(temp)=0;
else
m_idNext(temp)=temp+1;
end
m_id2ind(temp)=temp;
m_idNext(id)=temp;
m_endId=temp;
end
function deleteAt(id)
end
end
```
With the above .m file, the following runs:
```lang-matlab
>> clear all % remember to clear all before making new lists
>> headNode = makeLinkedList(1);
>> node2=headNode.next(headNode);
Warning: There is no next node.
> In makeLinkedList/next (line 33)
>> headNode.push_back(2);
>> headNode.push_back(3);
>> node2=headNode.next(headNode);
>> node3=node2.next(node2);
>> node3=node3.next(node3);
Warning: There is no next node.
> In makeLinkedList/next (line 33)
>> node0=node2.head;
>> node2=node0.next(node0);
>> node2.value
ans =
2
>> node3=node2.next(node2);
>> node3.value
ans =
3
```
`.next()` in the above can take any valid node `struct` -- not limited to itself. Similarly, `push_back()` etc can be done from any node. A node it cannot reference itself implicitly and automatically because non-OOP [`struct`](https://www.mathworks.com/help/matlab/ref/struct.html) in Matlab does not have a `this` pointer or `self` reference.
In the above example, nodes are given unique IDs, a dictionary is used to map ID to data (index) and to map ID to next ID. (With pre-R2022 `containers.Map()`, it's more efficient to have 2 dictionaries even though we have the same key and same value type across the two.) So when inserting new node, we simply need to update the relevant next ID. (Double) array was chosen to store the node values (which are doubles) and that is the data type Matlab is designed to work with and be efficient at. As long as no new allocation is required to append an element, insertion is constant time. Matlab automates the management of memory allocation. Since we are not doing array operations on the underlying array, Matlab is unlikely to take extra step to make copies of new contiguous arrays every time there is a resize. [Cell array](https://www.mathworks.com/help/matlab/ref/cell.html) may require even less re-allocation but with some trade-offs.
Since [dictionary](https://www.mathworks.com/help/matlab/ref/dictionary.html) is used, I am not sure if this solution qualifies as purely [functional](https://en.wikipedia.org/wiki/Functional_programming).
------------
##### re: closure vs linkage
In short, closure does not confer linkage. Matlab's nested functions have access to variables in parent functions directly -- as long as they are not shadowed by local variables of the same names. But there is no variable passing. And thus there is no pass-by-reference. And thus we can't model linkage with this non-existent referencing.
I did take advantage of closure above to make variables persistent, since scope (called [workspace](https://www.mathworks.com/help/matlab/matlab_prog/base-and-function-workspaces.html) in Matlab) being referred to means all variables in the scope will persist. That said, Matlab also has a [persistent](https://www.mathworks.com/help/matlab/ref/persistent.html) specifier. Closure is not the only way.
To showcase this distinction, the example below will not work because every time there is passing of `previousNode`, `nextNode`, they are passed-by-value. There is no way to access the original `struct` across function boundaries. And thus, even with nested function and closure, there is no linkage!
```lang-matlab
function newNode = SOtest01(value,previousNode,nextNode)
if ~exist('previousNode','var') || isempty(previousNode)
i_prev=m_prev();
else
i_prev=previousNode;
end
if ~exist('nextNode','var') || isempty(nextNode)
i_next=m_next();
else
i_next=nextNode;
end
newNode=struct('value',m_value(),...
'prev',i_prev,...
'next',i_next);
function out=m_value
out=value;
end
function out=m_prev
out=previousNode;
end
function out=m_next
out=nextNode;
end
end
``` |
I want to use the Flutter Custom Clipper to create a shape like the picture below, but it doesn't work. Is there anyone who can help?
[![enter image description here][1]][1]
```dart
class MyCustomClipper extends CustomClipper<Path> {
@override
Path getClip(Size size) {
List<Offset> polygon = [
Offset(0, 10),
Offset(size.width - 30, 10),
Offset(size.width - 25, 0),
Offset(size.width - 20, 10),
Offset(size.width, 10),
Offset(size.width, size.height),
Offset(0, size.height),
Offset(0, 10),
];
Path path = Path()
..addPolygon(polygon, false)
..close();
return path;
}
@override
bool shouldReclip(CustomClipper<Path> oldClipper) {
return true;
}
}
```
Actually, I used this path through polygon, but I couldn't give it a border, so I guess I don't know much.
[1]: https://i.stack.imgur.com/YXJ78.png |
null |
Accessing REST API Status Codes using Azure Data Factory Copy Activity (or similar)? |
I need RTC-Tools for a homework assignment. Tried to follow [this tutorial](https://rtc-tools.readthedocs.io/en/stable/getting-started.html) to get it:
As it needed pip for installation, I installed it according to [this guide](https://www.geeksforgeeks.org/how-to-install-pip-on-windows).
Then, in the Command Prompt, I wrote:
```shell
pip install rtc-tools
```
It started downloading, but at the end I got an error message.
```none
ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: 'C:\\Users\\admin\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python39\\site-packages\\rtctools_channel_flow\\modelica\\Deltares\\ChannelFlow\\SimpleRouting\\Branches\\Internal\\KLagNonlinearityParameterDenominator.mo'
```
[Full console screenshot](https://i.stack.imgur.com/ecSkw.png)
I don't know how to fix it.
I also tried:
```shell
git clone https://gitlab.com/deltares/rtc-tools.git
```
That gave the same error message.
I am using Python 3.9.
|
'No such file or directory' installing RTC-Tools through pip |
|python|installation|cmd|pip| |
**Edit** following the comment left, kindly, by [kritzikratzi](https://stackoverflow.com/users/347508/kritzikratzi):
> [Starting] with ios 5beta a new property `-webkit-overflow-scrolling: touch` can be added which should result in the expected behaviour.
Some, but very little, further reading:
* [Native momentum scrolling in iOS 5](http://www.johanbrook.com/writings/native-style-momentum-scrolling-to-arrive-in-ios-5/)
<a href="http://i.stack.imgur.com/gYiEv.png"><img src="http://i.stack.imgur.com/gYiEv.png" /></a>
<hr />
**Original answer**, left for posterity.
Unfortunately neither `overflow: auto`, or `scroll`, produces scrollbars on the iOS devices, apparently due to the screen-width that would be taken up such useful mechanisms.
Instead, as you've found, users are required to perform the two-finger swipe in order to scroll the `overflow`-ed content. The only reference, since I'm unable to find the manual for the phone itself, I could find is here: [tuaw.com: iPhone 101: Two-fingered scrolling](http://www.tuaw.com/2007/12/13/iphone-101-two-fingered-scrolling/).
The only work-around I can think of for this, is if you could possibly use some JavaScript, and maybe jQTouch, to create your own scroll-bars for `overflow` elements. Alternatively you could use [@media queries](http://www.alistapart.com/articles/return-of-the-mobile-stylesheet) to remove the `overflow` and show the content in full, as an iPhone user this gets my vote, if only for the sheer simplicity. For example:
<link rel="stylesheet" href="handheld.css" media="only screen and (max-device width:480px)" />
The preceding code comes from [A List Apart](http://www.alistapart.com/), from the same article linked-to above (I'm not sure why they left of the `type="text/css"`, but I assume there are reasons. |
SFML/C++ Why does my method to move the enemy towards the player stop working when the player is moving? |