instruction stringlengths 0 30k β |
|---|
|sql-server|django|sql-server-2022|mssql-django| |
`math.gcd()` is certainly a Python shim over a library function that is running as machine code (i.e. compiled from "C" code), not a function being run by the Python interpreter. See also: [Where are math.py and sys.py?](https://stackoverflow.com/questions/18857355/where-are-math-py-and-sys-py)
**This should be it (for CPython):**
`math_gcd(PyObject *module, PyObject * const *args, Py_ssize_t nargs)`
in [`mathmodule.c`](https://github.com/python/cpython/blob/main/Modules/mathmodule.c)
and it calls
`_PyLong_GCD(PyObject *aarg, PyObject *barg)`
in [`longobject.c`](https://github.com/python/cpython/blob/main/Objects/longobject.c)
which apparently uses [Lehmer's GCD algorithm](https://en.wikipedia.org/wiki/Lehmer's_GCD_algorithm)
The code is smothered in housekeeping operations and handling of special case though, increasing the complexity considerably. Still, quite clean.
~~~ lang-C
PyObject *
_PyLong_GCD(PyObject *aarg, PyObject *barg)
{
PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
stwodigits x, y, q, s, t, c_carry, d_carry;
stwodigits A, B, C, D, T;
int nbits, k;
digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
a = (PyLongObject *)aarg;
b = (PyLongObject *)barg;
if (_PyLong_DigitCount(a) <= 2 && _PyLong_DigitCount(b) <= 2) {
Py_INCREF(a);
Py_INCREF(b);
goto simple;
}
/* Initial reduction: make sure that 0 <= b <= a. */
a = (PyLongObject *)long_abs(a);
if (a == NULL)
return NULL;
b = (PyLongObject *)long_abs(b);
if (b == NULL) {
Py_DECREF(a);
return NULL;
}
if (long_compare(a, b) < 0) {
r = a;
a = b;
b = r;
}
/* We now own references to a and b */
Py_ssize_t size_a, size_b, alloc_a, alloc_b;
alloc_a = _PyLong_DigitCount(a);
alloc_b = _PyLong_DigitCount(b);
/* reduce until a fits into 2 digits */
while ((size_a = _PyLong_DigitCount(a)) > 2) {
nbits = bit_length_digit(a->long_value.ob_digit[size_a-1]);
/* extract top 2*PyLong_SHIFT bits of a into x, along with
corresponding bits of b into y */
size_b = _PyLong_DigitCount(b);
assert(size_b <= size_a);
if (size_b == 0) {
if (size_a < alloc_a) {
r = (PyLongObject *)_PyLong_Copy(a);
Py_DECREF(a);
}
else
r = a;
Py_DECREF(b);
Py_XDECREF(c);
Py_XDECREF(d);
return (PyObject *)r;
}
x = (((twodigits)a->long_value.ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
((twodigits)a->long_value.ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
(a->long_value.ob_digit[size_a-3] >> nbits));
y = ((size_b >= size_a - 2 ? b->long_value.ob_digit[size_a-3] >> nbits : 0) |
(size_b >= size_a - 1 ? (twodigits)b->long_value.ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
(size_b >= size_a ? (twodigits)b->long_value.ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
/* inner loop of Lehmer's algorithm; A, B, C, D never grow
larger than PyLong_MASK during the algorithm. */
A = 1; B = 0; C = 0; D = 1;
for (k=0;; k++) {
if (y-C == 0)
break;
q = (x+(A-1))/(y-C);
s = B+q*D;
t = x-q*y;
if (s > t)
break;
x = y; y = t;
t = A+q*C; A = D; B = C; C = s; D = t;
}
if (k == 0) {
/* no progress; do a Euclidean step */
if (l_mod(a, b, &r) < 0)
goto error;
Py_SETREF(a, b);
b = r;
alloc_a = alloc_b;
alloc_b = _PyLong_DigitCount(b);
continue;
}
/*
a, b = A*b-B*a, D*a-C*b if k is odd
a, b = A*a-B*b, D*b-C*a if k is even
*/
if (k&1) {
T = -A; A = -B; B = T;
T = -C; C = -D; D = T;
}
if (c != NULL) {
assert(size_a >= 0);
_PyLong_SetSignAndDigitCount(c, 1, size_a);
}
else if (Py_REFCNT(a) == 1) {
c = (PyLongObject*)Py_NewRef(a);
}
else {
alloc_a = size_a;
c = _PyLong_New(size_a);
if (c == NULL)
goto error;
}
if (d != NULL) {
assert(size_a >= 0);
_PyLong_SetSignAndDigitCount(d, 1, size_a);
}
else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
d = (PyLongObject*)Py_NewRef(b);
assert(size_a >= 0);
_PyLong_SetSignAndDigitCount(d, 1, size_a);
}
else {
alloc_b = size_a;
d = _PyLong_New(size_a);
if (d == NULL)
goto error;
}
a_end = a->long_value.ob_digit + size_a;
b_end = b->long_value.ob_digit + size_b;
/* compute new a and new b in parallel */
a_digit = a->long_value.ob_digit;
b_digit = b->long_value.ob_digit;
c_digit = c->long_value.ob_digit;
d_digit = d->long_value.ob_digit;
c_carry = 0;
d_carry = 0;
while (b_digit < b_end) {
c_carry += (A * *a_digit) - (B * *b_digit);
d_carry += (D * *b_digit++) - (C * *a_digit++);
*c_digit++ = (digit)(c_carry & PyLong_MASK);
*d_digit++ = (digit)(d_carry & PyLong_MASK);
c_carry >>= PyLong_SHIFT;
d_carry >>= PyLong_SHIFT;
}
while (a_digit < a_end) {
c_carry += A * *a_digit;
d_carry -= C * *a_digit++;
*c_digit++ = (digit)(c_carry & PyLong_MASK);
*d_digit++ = (digit)(d_carry & PyLong_MASK);
c_carry >>= PyLong_SHIFT;
d_carry >>= PyLong_SHIFT;
}
assert(c_carry == 0);
assert(d_carry == 0);
Py_INCREF(c);
Py_INCREF(d);
Py_DECREF(a);
Py_DECREF(b);
a = long_normalize(c);
b = long_normalize(d);
}
Py_XDECREF(c);
Py_XDECREF(d);
simple:
assert(Py_REFCNT(a) > 0);
assert(Py_REFCNT(b) > 0);
/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
undefined behaviour when LONG_MAX type is smaller than 60 bits */
#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
/* a fits into a long, so b must too */
x = PyLong_AsLong((PyObject *)a);
y = PyLong_AsLong((PyObject *)b);
#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
x = PyLong_AsLongLong((PyObject *)a);
y = PyLong_AsLongLong((PyObject *)b);
#else
# error "_PyLong_GCD"
#endif
x = Py_ABS(x);
y = Py_ABS(y);
Py_DECREF(a);
Py_DECREF(b);
/* usual Euclidean algorithm for longs */
while (y != 0) {
t = y;
y = x % y;
x = t;
}
#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
return PyLong_FromLong(x);
#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
return PyLong_FromLongLong(x);
#else
# error "_PyLong_GCD"
#endif
error:
Py_DECREF(a);
Py_DECREF(b);
Py_XDECREF(c);
Py_XDECREF(d);
return NULL;
}
~~~ |
I have a task and I need to copy data from one SQLite table to almost identical postgreSQL table. I wrote a code that doesn't work and I can't figure out what's the problem. It prints that connection was established successfull, shows to errors, but when I go to the terminal to check `content.film_work` table with commands `SELECT * FROM content.film_work;` I don't see the data. It shows:
movies_database=# SELECT * FROM content.film_work;
created | modified | id | title | description | creation_date | rating | type | file_path
---------+----------+----+-------+-------------+---------------+--------+------+-----------
(0 rows)
1. Connect to the SQLite database and copy data from film_work table to dataclass.
2. Pass list of dataclasses instances with table rows to another function whee I connect to the postgreSQL.
3. Connect to the postgreSQL and get postgreSQL table (content.film_work) column names to pass it to the INSERT SQL query.
4. Before all this I change the order of columns to correctly pass data from SQLite to postgreSQL.
**SQLite table (film_work):**
0|id|TEXT|0||1
1|title|TEXT|1||0
2|description|TEXT|0||0
3|creation_date|DATE|0||0
4|file_path|TEXT|0||0
5|rating|FLOAT|0||0
6|type|TEXT|1||0
7|created_at|timestamp with time zone|0||0
8|updated_at|timestamp with time zone|0||0
**postgreSQL table (content.film_work):**
created | modified | id | title | description | creation_date | rating | type | file_path
**Code snippet:**
psycopg2.extras.register_uuid()
db_path = 'db.sqlite'
@contextmanager
def conn_context(db_path: str):
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
try:
yield conn
finally:
conn.close()
@dataclass
class FilmWork:
created_at: date = None
updated_at: date = None
id: uuid.UUID = field(default_factory=uuid.uuid4)
title: str = ''
description: str = ''
creation_date: date = None
rating: float = 0.0
type: str = ''
file_path: str = ''
def __post_init__(self):
if self.creation_date is None:
self.creation_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
if self.created_at is None:
self.created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
if self.updated_at is None:
self.updated_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
if self.description is None:
self.description = 'ΠΠ΅Ρ ΠΎΠΏΠΈΡΠ°Π½ΠΈΡ'
if self.rating is None:
self.rating = 0.0
def copy_from_sqlite():
with conn_context(db_path) as connection:
cursor = connection.cursor()
cursor.execute("SELECT * FROM film_work;")
result = cursor.fetchall()
films = [FilmWork(**dict(film)) for film in result]
save_film_work_to_postgres(films)
def save_film_work_to_postgres(films: list):
psycopg2.extras.register_uuid()
dsn = {
'dbname': 'movies_database',
'user': 'app',
'password': '123qwe',
'host': 'localhost',
'port': 5432,
'options': '-c search_path=content',
}
try:
conn = psycopg2.connect(**dsn)
print("Successfull connection!")
with conn.cursor() as cursor:
cursor.execute(f"SELECT column_name FROM information_schema.columns WHERE table_name = 'film_work' ORDER BY ordinal_position;")
column_names_list = [row[0] for row in cursor.fetchall()]
column_names_str = ','.join(column_names_list)
col_count = ', '.join(['%s'] * len(column_names_list))
bind_values = ','.join(cursor.mogrify(f"({col_count})", astuple(film)).decode('utf-8') for film in films)
cursor.execute(f"""INSERT INTO content.film_work ({column_names_str}) VALUES {bind_values} """)
except psycopg2.Error as _e:
print("ΠΡΠΈΠ±ΠΊΠ°:", _e)
finally:
if conn is not None:
conn.close()
copy_from_sqlite() |
How to copy data from SQLite to postgreSQL? |
|python|postgresql|sqlite| |
For some reason, the navbar is displayed below other content and I'm not sure where I've messed up...
This applies to all other pages with the same navbar. Other content overlaps the navbar when scrolling. I'm not able to view the dropdown on .resources. I really can't find where the issue is as the same navbar has worked on other sites.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
scroll-behavior: smooth;
height: 100%;
}
body {
overflow-x: hidden;
position: relative;
display: flex;
scroll-behavior: smooth;
padding: 0;
margin: 0;
height: 100%;
}
a {
text-decoration: none;
margin: 0;
}
ul {
padding: 0;
margin: 0;
}
nav {
display: flex;
justify-content: center;
align-items: center;
font-family: 'Bebas Neue', sans-serif;
height: max-content;
position: sticky;
}
.navbar-nav {
display: flex;
list-style: none;
height: max-content;
width: max-content;
padding: 0;
}
.cta-nav {
position: absolute;
right: 0;
display: flex;
list-style: none;
height: max-content;
width: max-content;
padding: 0;
margin-right: 2em;
}
.cta-item:first-child {
padding-left: 1.5rem;
}
.cta-item {
background-color: #557571;
margin-top: 1em;
scroll-behavior: smooth;
}
.cta-item:not(:last-child) {
padding-right: 1.5rem;
}
.cta-opts {
padding: 6px 0;
margin-top: 0.2rem;
margin-bottom: 0.2rem;
font-weight: 400;
text-decoration: none;
display: inline-block;
font-size: 1.6rem;
transition: all 0.5s ease-in-out;
position: relative;
color: white;
}
.main-nav {
transition: all 0.5s;
position: fixed;
margin: auto;
height: 100px;
margin-top: 10vh;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
background-color: #fafafa;
}
.main-nav-scroll {
transition: all 0.5s;
opacity: 0;
}
.main-nav-scroll:hover {
opacity: 1;
background-color: #EEEEEE;
}
.nav-item:first-child {
padding-left: 3rem;
}
.nav-item:last-child {
padding-right: 1rem;
}
.nav-item {
margin-top: 1em;
scroll-behavior: smooth;
}
.nav-item:not(:last-child) {
padding-right: 1rem;
}
.nav-opts {
position: fixed;
padding-top: 2px;
padding-bottom: 2px;
padding-left: 10px;
padding-right: 10px;
margin-top: 0.2rem;
margin-bottom: 0.2rem;
font-weight: 400;
text-decoration: none;
display: inline-block;
font-size: 2rem;
transition: all 0.5s ease-in-out;
position: relative;
color: #557571;
}
.nav-opts:hover {
cursor: pointer;
transition: all 0.2s ease-in-out;
color: white;
background: linear-gradient(90deg, #fff 0%, #fff 50%, #557571 50%, #557571 100%);
background-size: 200% 100%;
background-position: 100% 0;
}
.drop-item {
margin: 0;
left: 0;
text-align: left;
display: block;
width: 148px;
font-size: 1.5rem;
padding: 7.5px 0px;
padding-left: 15px;
background-color: #EEEEEE;
margin-bottom: 3px;
}
.drop-item a {
color: #D49A89;
}
.drop-item:hover {
background-color: #557571;
}
.dropdown {
width: 100%;
position: fixed;
display: none;
}
ul li:hover ul.dropdown {
display: block;
}
ul li {
position: relative; /* Ensure parent is positioned */
}
header {
background-color: transparent;
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 999;
}
.main-nav img {
margin-top: 12.5px;
margin-left: 30px;
position: absolute;
left: 0;
width: 110px;
}
.hero {
height: 90vh;
margin-top: 50px;
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
position: relative;
}
.hero-bg {
object-fit: cover;
width: 100%;
height: 600px;
position: absolute;
}
.hero-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
flex-direction: column;
text-align: center;
}
.hero-title {
width: 370px;
}
.hero a {
display: inline-block;
width: 80px;
margin: auto;
margin-top: 40px;
padding: 7.5px 30px;
background-color: #557571;
color: white;
text-decoration: none;
font-size: 30px;
font-family: 'Bebas Neue', sans-serif;
transition: all 0.3s ease;
}
.hero a:hover {
background-color: white;
color: #557571;
}
.container {
width: 100%;
}
.about {
margin-top: 200px;
width: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
position: relative;
font-family: "Libre Baskerville", serif;
margin-bottom: 100px;
}
.about h2 {
color: #394240;
font-size: 2.75rem;
margin-bottom: 15px;
letter-spacing: -1px;
}
.about p {
letter-spacing: -1px;
color: #557571;
margin: auto;
width: 900px;
font-size: 1.2rem;
margin-bottom: 50px;
}
.hg {
color: #D49A89;
}
.stats {
margin: auto;
display: flex;
flex-direction: row;
width: 75%;
}
.line {
height: 70px;
margin-bottom: 50px;
}
.vision {
margin-top: 150px;
text-align: left;
}
.vision h3 {
margin-left: 225px;
font-size: 1.5rem;
color: #394240;
}
.vision p {
font-size: 1.25rem;
margin-left: 225px;
width: 900px;
}
.teach {
margin-top: 75px;
text-align: right;
}
.teach h3 {
margin-right: 225px;
font-size: 1.5rem;
color: #394240;
}
.teach p {
font-size: 1.25rem;
margin-right: 225px;
width: 900px;
}
.partners {
margin-top: 200px;
}
.partners h2 {
margin-bottom: 40px;
}
.partners img {
width: 85%;
}
<!-- language: lang-html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-wi
dth, initial-scale=1.0">
<link rel="stylesheet" href="css/index.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Libre+Baskerville:ital,wght@0,400;0,700;1,400&family=Lora:ital,wght@0,400..700;1,400..700&family=Playfair+Display:ital,wght@0,400..900;1,400..900&display=swap"
rel="stylesheet">
<link
href="https://fonts.googleapis.com/css2?family=Lora:ital,wght@0,400..700;1,400..700&family=Playfair+Display:ital,wght@0,400..900;1,400..900&display=swap"
rel="stylesheet">
<title>Meraki</title>
</head>
<body>
<header>
<nav>
<div class="main-nav" id="navbar">
<img src="images/logo.png" alt="Logo">
<ul class="navbar-nav">
<li class="nav-item"><a href="index.html" class="nav-opts">HOME</a></li>
<li class="nav-item"><a href="#about" class="nav-opts">ABOUT</a></li>
<li class="nav-item"><a href="#contact" class="nav-opts">CONTACT</a></li>
<li class="nav-item">
<a href="#resources" class="nav-opts">RESOURCES βΎ</a>
<ul class="dropdown">
<li class="drop-item"><a href="">Events</a></li>
<li class="drop-item"><a href="">Gallery</a></li>
<li class="drop-item"><a href="">Newsletter</a></li>
<li class="drop-item"><a href="blog.html">Blog</a></li>
</ul>
</li>
<li class="nav-item"></li>
</ul>
<ul class="cta-nav">
<li class="cta-item"><a href="#join" class="cta-opts">JOIN</a></li>
<li class="cta-item"><a href="#donate" class="cta-opts">DONATE</a></li>
<li class="cta-item"><a href="#partner" class="cta-opts">PARTNER</a></li>
<li class="cta-item"></li>
</ul>
</div>
</nav>
</header>
<main>
<div class="container">
<div class="hero">
<img class="hero-bg" src="images/hero-bg.png" alt="Bg">
<div class="hero-content">
<img class="hero-title" src="images/hero-title.png" alt="Meraki">
<a href="#">Join Us</a>
</div>
</div>
<div class="about">
<img class="line" src="images/line.png" alt="">
<h2>About Us</h2>
<p> <span class="hg">Meraki</span> is an organization that aims to improve education by promoting the
importance of arts in academics
for
a more wholesome learning. We do this by teaching students different arts.</p>
<img class="stats" src="images/stats.png" alt="">
<div class="info">
<div class="vision">
<h3>Our Vision</h3>
<p>Meraki wants to see students from all different age groups and backgrounds discover their own
talents, passions and hobbies. <span class="hg">Every student should have the opportunity to
learn whatever
subject they wish to.</span></p>
</div>
<div class="teach">
<h3>What Do We Teach?</h3>
<p>Meraki empowers students through the arts, offering vibrant lessons <span class="hg">in
music, dance, and art.</span> Our
goal is to cultivate a love for creativity, providing a space where each student can
discover
and express their unique artistic flair.</p>
</div>
</div>
<div class="partners">
<h2>Our Partners</h2>
<img class="partners-img" src="images/partners.png" alt="Partners">
</div>
</div>
</div>
</main>
<script>
var prevScrollpos = window.pageYOffset;
window.onscroll = function () {
var currentScrollPos = window.pageYOffset;
var navbar = document.getElementById("navbar");
if (prevScrollpos > 200) {
navbar.classList.add("main-nav-scroll");
} else {
navbar.classList.remove("main-nav-scroll");
}
prevScrollpos = currentScrollPos;
}
</script>
</body>
</html>
<!-- end snippet -->
I tried setting z-index of main-nav to 999 but it still doesnt work. I cant set the z-index of other content to -1 as their hover animations then don't work. |
null |
For some reason, the navbar is displayed below other content and I'm not sure where I've messed up...
This applies to all other pages with the same navbar. Other content overlaps the navbar when scrolling. I'm not able to view the dropdown on .resources. I really can't find where the issue is as the same navbar has worked on other sites.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
scroll-behavior: smooth;
height: 100%;
}
body {
overflow-x: hidden;
position: relative;
display: flex;
scroll-behavior: smooth;
padding: 0;
margin: 0;
height: 100%;
}
a {
text-decoration: none;
margin: 0;
}
ul {
padding: 0;
margin: 0;
}
nav {
display: flex;
justify-content: center;
align-items: center;
font-family: 'Bebas Neue', sans-serif;
height: max-content;
position: sticky;
}
.navbar-nav {
display: flex;
list-style: none;
height: max-content;
width: max-content;
padding: 0;
}
.cta-nav {
position: absolute;
right: 0;
display: flex;
list-style: none;
height: max-content;
width: max-content;
padding: 0;
margin-right: 2em;
}
.cta-item:first-child {
padding-left: 1.5rem;
}
.cta-item {
background-color: #557571;
margin-top: 1em;
scroll-behavior: smooth;
}
.cta-item:not(:last-child) {
padding-right: 1.5rem;
}
.cta-opts {
padding: 6px 0;
margin-top: 0.2rem;
margin-bottom: 0.2rem;
font-weight: 400;
text-decoration: none;
display: inline-block;
font-size: 1.6rem;
transition: all 0.5s ease-in-out;
position: relative;
color: white;
}
.main-nav {
transition: all 0.5s;
position: fixed;
margin: auto;
height: 100px;
margin-top: 10vh;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
background-color: #fafafa;
}
.main-nav-scroll {
transition: all 0.5s;
opacity: 0;
}
.main-nav-scroll:hover {
opacity: 1;
background-color: #EEEEEE;
}
.nav-item:first-child {
padding-left: 3rem;
}
.nav-item:last-child {
padding-right: 1rem;
}
.nav-item {
margin-top: 1em;
scroll-behavior: smooth;
}
.nav-item:not(:last-child) {
padding-right: 1rem;
}
.nav-opts {
position: fixed;
padding-top: 2px;
padding-bottom: 2px;
padding-left: 10px;
padding-right: 10px;
margin-top: 0.2rem;
margin-bottom: 0.2rem;
font-weight: 400;
text-decoration: none;
display: inline-block;
font-size: 2rem;
transition: all 0.5s ease-in-out;
position: relative;
color: #557571;
}
.nav-opts:hover {
cursor: pointer;
transition: all 0.2s ease-in-out;
color: white;
background: linear-gradient(90deg, #fff 0%, #fff 50%, #557571 50%, #557571 100%);
background-size: 200% 100%;
background-position: 100% 0;
}
.drop-item {
margin: 0;
left: 0;
text-align: left;
display: block;
width: 148px;
font-size: 1.5rem;
padding: 7.5px 0px;
padding-left: 15px;
background-color: #EEEEEE;
margin-bottom: 3px;
}
.drop-item a {
color: #D49A89;
}
.drop-item:hover {
background-color: #557571;
}
.dropdown {
width: 100%;
position: fixed;
display: none;
}
ul li:hover ul.dropdown {
display: block;
}
ul li {
position: relative; /* Ensure parent is positioned */
}
header {
background-color: transparent;
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 999;
}
.main-nav img {
margin-top: 12.5px;
margin-left: 30px;
position: absolute;
left: 0;
width: 110px;
}
.hero {
height: 90vh;
margin-top: 50px;
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
position: relative;
}
.hero-bg {
object-fit: cover;
width: 100%;
height: 600px;
position: absolute;
}
.hero-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
flex-direction: column;
text-align: center;
}
.hero-title {
width: 370px;
}
.hero a {
display: inline-block;
width: 80px;
margin: auto;
margin-top: 40px;
padding: 7.5px 30px;
background-color: #557571;
color: white;
text-decoration: none;
font-size: 30px;
font-family: 'Bebas Neue', sans-serif;
transition: all 0.3s ease;
}
.hero a:hover {
background-color: white;
color: #557571;
}
.container {
width: 100%;
}
.about {
margin-top: 200px;
width: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
position: relative;
font-family: "Libre Baskerville", serif;
margin-bottom: 100px;
}
.about h2 {
color: #394240;
font-size: 2.75rem;
margin-bottom: 15px;
letter-spacing: -1px;
}
.about p {
letter-spacing: -1px;
color: #557571;
margin: auto;
width: 900px;
font-size: 1.2rem;
margin-bottom: 50px;
}
.hg {
color: #D49A89;
}
.stats {
margin: auto;
display: flex;
flex-direction: row;
width: 75%;
}
.line {
height: 70px;
margin-bottom: 50px;
}
.vision {
margin-top: 150px;
text-align: left;
}
.vision h3 {
margin-left: 225px;
font-size: 1.5rem;
color: #394240;
}
.vision p {
font-size: 1.25rem;
margin-left: 225px;
width: 900px;
}
.teach {
margin-top: 75px;
text-align: right;
}
.teach h3 {
margin-right: 225px;
font-size: 1.5rem;
color: #394240;
}
.teach p {
font-size: 1.25rem;
margin-right: 225px;
width: 900px;
}
.partners {
margin-top: 200px;
}
.partners h2 {
margin-bottom: 40px;
}
.partners img {
width: 85%;
}
<!-- language: lang-html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-wi
dth, initial-scale=1.0">
<link rel="stylesheet" href="css/index.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Libre+Baskerville:ital,wght@0,400;0,700;1,400&family=Lora:ital,wght@0,400..700;1,400..700&family=Playfair+Display:ital,wght@0,400..900;1,400..900&display=swap"
rel="stylesheet">
<link
href="https://fonts.googleapis.com/css2?family=Lora:ital,wght@0,400..700;1,400..700&family=Playfair+Display:ital,wght@0,400..900;1,400..900&display=swap"
rel="stylesheet">
<title>Meraki</title>
</head>
<body>
<header>
<nav>
<div class="main-nav" id="navbar">
<img src="images/logo.png" alt="Logo">
<ul class="navbar-nav">
<li class="nav-item"><a href="index.html" class="nav-opts">HOME</a></li>
<li class="nav-item"><a href="#about" class="nav-opts">ABOUT</a></li>
<li class="nav-item"><a href="#contact" class="nav-opts">CONTACT</a></li>
<li class="nav-item">
<a href="#resources" class="nav-opts">RESOURCES βΎ</a>
<ul class="dropdown">
<li class="drop-item"><a href="">Events</a></li>
<li class="drop-item"><a href="">Gallery</a></li>
<li class="drop-item"><a href="">Newsletter</a></li>
<li class="drop-item"><a href="blog.html">Blog</a></li>
</ul>
</li>
<li class="nav-item"></li>
</ul>
<ul class="cta-nav">
<li class="cta-item"><a href="#join" class="cta-opts">JOIN</a></li>
<li class="cta-item"><a href="#donate" class="cta-opts">DONATE</a></li>
<li class="cta-item"><a href="#partner" class="cta-opts">PARTNER</a></li>
<li class="cta-item"></li>
</ul>
</div>
</nav>
</header>
<main>
<div class="container">
<div class="hero">
<img class="hero-bg" src="images/hero-bg.png" alt="Bg">
<div class="hero-content">
<img class="hero-title" src="images/hero-title.png" alt="Meraki">
<a href="#">Join Us</a>
</div>
</div>
<div class="about">
<img class="line" src="images/line.png" alt="">
<h2>About Us</h2>
<p> <span class="hg">Meraki</span> is an organization that aims to improve education by promoting the
importance of arts in academics
for
a more wholesome learning. We do this by teaching students different arts.</p>
<img class="stats" src="images/stats.png" alt="">
<div class="info">
<div class="vision">
<h3>Our Vision</h3>
<p>Meraki wants to see students from all different age groups and backgrounds discover their own
talents, passions and hobbies. <span class="hg">Every student should have the opportunity to
learn whatever
subject they wish to.</span></p>
</div>
<div class="teach">
<h3>What Do We Teach?</h3>
<p>Meraki empowers students through the arts, offering vibrant lessons <span class="hg">in
music, dance, and art.</span> Our
goal is to cultivate a love for creativity, providing a space where each student can
discover
and express their unique artistic flair.</p>
</div>
</div>
<div class="partners">
<h2>Our Partners</h2>
<img class="partners-img" src="images/partners.png" alt="Partners">
</div>
</div>
</div>
</main>
<script>
var prevScrollpos = window.pageYOffset;
window.onscroll = function () {
var currentScrollPos = window.pageYOffset;
var navbar = document.getElementById("navbar");
if (prevScrollpos > 200) {
navbar.classList.add("main-nav-scroll");
} else {
navbar.classList.remove("main-nav-scroll");
}
prevScrollpos = currentScrollPos;
}
</script>
</body>
</html>
<!-- end snippet -->
I tried setting the `z-index` of main-nav to 999 but it still doesn't work. I cant set the `z-index` of other content to -1 as their hover animations then don't work. |
You need to send the message to the `HWND` that `CreateWindow()` creates. You can get that from the return value of `CreateWindow()`, or from `GetDlgItem()` after `CreateWindow()` is finished.
The `LPARAM` needs to be a pointer to the 1st character of a null-terminated C-style string, eg:
```
char myline[size];
//fill myline as needed...
HWND hwndLB = CreateWindowA(WC_LISTBOXA, ... hwnd, reinterpret_cast<HMENU>(LST_LISTBOX), ...);
// or:
// CreateWindowA(...);
// HWND hwndLB = GetDlgItem(hwnd, LST_LISTBOX);
SendMessage(hwndLB, LB_ADDSTRING, 0, reinterpret_cast<LPARAM>(myline));
```
Alternatively:
```
std::string myline;
//fill myline as needed...
HWND hwndLB = ...;
SendMessage(hwndLB, LB_ADDSTRING, 0, reinterpret_cast<LPARAM>(myline.c_str()));
``` |
I'm new to both android and java, now im trying to update a textview with the state of the call, but the view model doesn't get the value from the telephony callback class.
Im using post value since app goes background when it rings.
The permissions for read_phone_state and call_phone are given on mainActivity.
CallstateListener class
```
public class CallStateListener extends TelephonyCallback implements TelephonyCallback.CallStateListener {
private MutableLiveData<String> callState = new MutableLiveData<>();
//Construtor com ref ao viewmodel
public CallStateListener() {
}
@Override
public void onCallStateChanged(int state) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
callState.postValue("IDLE");
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
callState.postValue("OFFHOOK");
break;
case TelephonyManager.CALL_STATE_RINGING:
callState.postValue("RINGING");
break;
default:
callState.postValue("NULL");
break;
}
}
public MutableLiveData<String> getCallState() {
return callState;
}
```
viewmodel
```
public class LteViewModel extends ViewModel {
private CallStateListener callState = new CallStateListener();
private MutableLiveData<String> state;
public LteViewModel() {
state = new MutableLiveData<>();
state = callState.getCallState();
}
public LiveData<String> getCallState(){ return state;}
}
```
fragment with registerTelephonyCallback and method to update the textview which is named mIntraHOLte
```
public class LteFragment extends Fragment {
private FragmentLteBinding binding;
private LteViewModel lteViewModel;
public TelephonyManager telephonyManager;
public CallStateListener callStateListener;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
callStateListener = new CallStateListener();
telephonyManager = (TelephonyManager) requireActivity().getSystemService(TELEPHONY_SERVICE);
lteViewModel =
new ViewModelProvider(this).get(LteViewModel.class);
binding = FragmentLteBinding.inflate(inflater, container, false);
View root = binding.getRoot();
TextView mIntraHOLte = binding.titleLteIntraho;
telephonyManager.registerTelephonyCallback(Runnable::run, callStateListener);
lteViewModel.getCallState().observe(getViewLifecycleOwner(), mIntraHOLte::setText);
return root;
}
@Override
public void onDestroyView() {
super.onDestroyView();
telephonyManager.unregisterTelephonyCallback(callStateListener);
}
}
```
|
Flatlist Sometimes Capped at 10 Items Bug |
|react-native| |
null |
I'm trying to create a plugin which hooks into Invision Community Suite's 'saved actions' functionality. Essentially, when a saved action is run against a topic, I want to ask for more information.
This is for the latest version of IPS, no third-party applications/plugins installed.
I have tried 'echo'ing the JavaScript out onto the page, with no avail - it just refreshed and didn't show anything.
I have tried utilising the '\IPS\Output' class to run some custom JavaScript:
```js
\IPS\Output::i()->jsVariables['arr_showConfirmationModal'] = 'ara_ShowDialog()';
```
where the 'ara_ShowDialog' method is as simple as:
```js
function ara_ShowDialog() {
dialog.show();
}
```
I have the hook working which hooks into the 'SavedAction' class, but I can't for the life of me figure out how to stop the page redirecting and display a popup modal - any help will be greatly appreciated! |
Invision Community Suite - Display popup modal in PHP hook via plugin? |
|php|invision| |
null |
I'm trying to create a thumbnail sheet (a grid of thumbnails) using ImageMagick with filenames beneath each image. The filenames are long UUID style strings, and using the -title option they overflow into each other to create an unreadable mess. So I thought I'd truncate the names to only show the first n characters. My Bash script is below (running via Git Bash on Windows 11.) I'm not sure whether this is an error in my Bash code, or my use of ImageMagick.
```
magick montage -verbose -label "$(echo '%t' | cut -c -8)" -font Arial -pointsize 16 \
-background '#000000' -fill 'gray' \
-define jpeg:size=200x200 \
-geometry 200x200+2+2 -tile 8x0 \
-auto-orient \
$(ls -rt *.jpg) \
out.jpg
```
As far as I can tell the issue I have is with the `$(echo '%t'` ... part of the script in the first line; it doesn't seem to be piped into the cut command following it. If I use a literal string, eg. `echo 'Hello world!'`, each thumbnail is labeled with what I'd expect, 'Hello wo'. But if I instead use %t (which is ImageMagick's format variable for exposing the base filename of the image) I get the full untruncated filename as if the cut command isn't being applied.
When I use a naked format variable (I've tried %f, the full filename, and %t, the base filename), without echo'ing it into cut, I get the expected untruncated filename. As mentioned, if I echo a literal string (Hello world!) piped into cut, I get the expected truncated output. It is only when I combine the two to echo %f or %t into cut that the truncation fails and I get the full filename. I've also tried piping the echo into sed instead of cut, but yet again the second command is ignored and I get the full filename.
EDIT: An extra little detail I forgot: if I do something funky with the %t, like `$(echo 'xxx%t')`, I get the filename preceded by xxx -- so it seems the echo is working as expected. But when I try to pipe it into cut, it doesn't truncate.
Any help gratefully received. |
I want to prepare a site to automatically compare prices with ready-made codes. I found a dashboard with ready-made codes on Bootstrap. Hosting was purchased for me to start the process. Now how can I continue the process? Are there sites for videos or other information?
Code to try: I have 1 year of knowledge. |
JSON file of 7000 meetings in multiple timezones and Flatlist |
|react-native|datetime|react-native-flatlist| |
null |
InnoSetup error 193 after install Mysql Connector |
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
``` |
Alternatively to what @kadina has posted, you could pass a pointer to a character to your `Get` function.
You also need to eliminate the trailing newline character from your format string.
void Get(char *ch) {
scanf("%c", ch);
}
And in main, we declare a variable `ch` of type `char`, since there is no need for global variables, then pass a pointer to that to `Get`.
int main(void) {
char ch;
Get(&ch);
}
Hopefully this helps point you in the right direction.
**Note:** calling `scanf` in this way discards any opportunity to test the return value, and thus to know whether the I/O was successful. |
I am trying to make predictions with Bert, where the prediction of subsequent words in the first input of each paragraph may be aided, so can Bert make use of previous predictions in subsequent predictions like an autoregressive language model? |
Give Bert an input and ask him to predict. In this input, can Bert apply the first word prediction result to all subsequent predictions? |
|machine-learning|nlp|bert-language-model| |
null |
Within your working repo , Create a folder named templates and copy your html files to it . |
When i tryied to light the LED from python with this code:
```
import serial
arduino_port = 'COM5'
arduino_baudrate = 9600
arduino = serial.Serial(arduino_port, arduino_baudrate)
def send_command_to_arduino(command):
arduino.write(command.encode())
send_command_to_arduino('2,1')
```
i have this error in arduino Output:
`> avrdude: stk500_recv():
> programmer is not responding avrdude: stk500_getsync() attempt 1 of 10:
> not in sync: resp=0x93 arduino.
(
in arduino i have this code to parse serial monitor:
```
#include "Parser.h"
void setup() {
Serial.begin(9600);
pinMode(10, OUTPUT);
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(3, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
}
void loop() {
if (Serial.available() > 1) {
char str[30];
int amount = Serial.readBytesUntil(';', str, 30);
str[amount] = NULL;
Parser data(str, ',');
int ints[5];
int am = data.parseInts(ints);
switch (ints[0]) {
case 0: digitalWrite(10, ints[1]); break;
case 1: digitalWrite(12, ints[1]); break;
case 2: digitalWrite(11, ints[1]); break;
case 3:
analogWrite(3, ints[1]);
analogWrite(5, ints[2]);
analogWrite(6, ints[3]);
break;
}
}
}
```
i have arduino UNO
It firs time i get this error, so i don`t know what i should try. |
How to fix python serial monitor parsing error? |
|python|arduino|pyserial|arduino-uno|serial-monitor| |
null |
Intent Environment = new Intent().setAction(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
.setData(Uri.parse("package:" + getPackageName()));
if (Environment.resolveActivity(getPackageManager())!=null) {
startActivity(Environment);
} |
I'm using `py setup.py bdist_msi` to generate windows single executable file for my python application. this works fine on my computer, but it does not work when it is executed in GitLab pipeline. does anyone know how to solve this issue? i'm using Python 3.11.8 on my local machine and on the pipeline. here is the error:
[![enter image description here][1]][1]
here is my setup.py file:
```
from cx_Freeze import setup, Executable
import sys
directory_table = [("ProgramMenuFolder", "TARGETDIR", "."),
("MyProgramMenu", "ProgramMenuFolder", "MYPROG~1|My Program")]
msi_data = {"Directory": directory_table,
"ProgId": [("Prog.Id", None, None, "This is a description", "IconId", None)],
"Icon": [("IconId", "matplotlib.ico")]}
files = ['param_list.py', 'mca_ioconfig_parser.py', 'mca_package_manifest_parser.py', 'mca_rti_log_parser.py',
'ui_interface.py', 'resources_rc.py']
bdist_msi_options = {"add_to_path": False,
"data": msi_data,
'initial_target_dir': r'[ProgramFilesFolder]%s' % 'yammiX',
"upgrade_code": "{96a85bac-52af-4019-9e94-3afcc9e1ad0c}"}
build_exe_options = {"excludes": [], "includes": []}
executables = Executable(script="toolName.py",
base="Win32GUI" if sys.platform == "win32" else None,
icon="matplotlib.ico",
shortcut_name="toolName",
shortcut_dir="DesktopFolder")
setup(name="toolName",
version="0.1.5",
author="toolName",
description="",
executables=[executables],
options={"build_exe": build_exe_options,
"bdist_msi": bdist_msi_options})
```
here is my yml file:
```
image: python:3.11.8
stages:
- build
- test
- deploy
build-job:
stage: build
# Update stuff before building versions
before_script:
- apt-get update -q -y
- apt install -y python3-pip
- apt install -y python3-venv
- python3 -m venv .venv
- source .venv/bin/activate
- python3 --version
- python3 -m pip install -r requirements.txt
script:
- python3 setup.py -q bdist_msi
artifacts:
paths:
- build/
unit-test-job:
stage: test
script:
- echo "Running unit tests... This will take about few seconds."
- echo "Code coverage is 100%"
deploy-job:
stage: deploy
script:
- echo "Deploying application..."
- echo "Application successfully deployed."
```
[1]: https://i.stack.imgur.com/QkIW7.png |
I am a beginner trying to build very simple inventory system using PHP + SQL
I have 2 warehouse. I added 2 tables, 1 for each warehouse contains (item id)-(in)- (out) like shown below
table1
| item id | in | out |
| -------- | -- |-----|
| item1 | 10 | 0 |
| item1 | 5 | 0 |
| item2 | 0 | 3 |
| item2 | 0 | 2 |
table2
| item id | in | out |
| -------- | -- |-----|
| item1 | 12 | 0 |
| item1 | 50 | 0 |
| item2 | 0 | 10 |
| item2 | 0 | 30 |
I have report show balance for each warehouse separately by using query below
Select item_id, sum(in-out) as balance from table1 group by item_id
My question is how show each warehouse balance in one table like below
| item id | warehouse1 | warehouse2|
| -------- | ---------- |-----------|
| item1 | 7 | 2 |
| item2 | 3 | 20 |
I tired with this query but I get wrong results
SELECT table1.item_id, sum(table1.in)-sum(table1.out) as tb1, sum(table2.in)-sum(table2.out) as tb2 FROM table1 , table2 WHERE table1.item_id=table2.item_id GROUP by item_id |
I'm using this key
```
final GlobalKey<DropdownSearchState<ProductModel>> _productKey = GlobalKey();
```
Using this key in the following dropdown_search
```
Widget loadProducts() {
return DropdownSearch<ProductModel>(
key: _productKey,
asyncItems: (String filter) async {
var response = await APIServices.getProducts();
var models = response.data;
return models ?? [];
},
itemAsString: (ProductModel item) =>
'${item.productId} - ${item.productName!}',
onChanged: (item) async {
if (item != null) {
_productModel = item;
fetchProductData(_productModel!.productId!);
}
},
selectedItem: _productModel,
);
}
```
And I'm using Layout Builder to make my app responsive on both desktop and mobile. And here is the basic structure of my screen. I'm calling the editRow() from DataCell in datatable and edit button on ListView.
```
@override
Widget build(BuildContext context) {
return Scaffold(
body: ResponsiveWidget(
largeScreen: SingleChildScrollView(
child: Column(
children: [
loadProducts(),
DataTable(columns: [], rows: [])
]
),
),
smallScreen: Column(
children: [
TabBar(
controller: _tabbarController,
tabs: [
Tab(text: 'Order',),
Tab(text: 'Products'),
Tab(text: 'Detail')
],
),
TabBarView(
controlerr: _tabbarController,
children: [
TabBar1Content(),
Column(
children: [
TabBar(
controller: _tabbarController2,
tabs: [
Tab(text: 'Product'),
Tab(text: 'List')
]
),
TabBarView(
controller: _tabbarController2
children: [
Column(
children: [
loadProducts(),
ListView.builder(itemBuilder: (context, index) => ProductCard(onEditClick: (){
editRow()
}))
],
)
])
],
)
TabBar3Content()
])
]
),
),
);
}
```
I'm having this error only in smallScreen while accessing the currentState of \_productKey. I'm confused here what I'm doing wrong.
```
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value #0 _AddSaleOrderScreenState.editRow (package:ultra_erp/screens/sale/add_screen/add_sale_order_screen.dart:708:29) #1 _AddSaleOrderScreenState.build.<anonymous closure>.<anonymous closure> (package:ultra_erp/screens/sale/add_screen/add_sale_order_screen.dart:2542:45) #2 CustomSlidableAction._handleTap (package:flutter_slidable/src/actions.dart:116:16) #3 CustomSlidableAction.build.<anonymous closure> (package:flutter_slidable/src/actions.dart:98:28) #4 _InkResponseState.handleTap (package:flutter/src/material/ink_well.dart:1183:21) #5 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:315:24) #6 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:652:11) #7 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:309:5)
```
I tried to debug the problem using `print(_productKey.currentState!.mounted);` at different stages. But as long as I navigate to list tab and call the editRow function it throws the above null check error. |
TelephonyCallback.CallStateListener with LiveData and ViewModel |
|java|android|mvvm|callback|mutablelivedata| |
null |
I'm working on a react-three-fiber website and can't get SSR (screen spaced reflections) working at the same time as Bloom. I'm using [@react-three/postprocessing](https://www.npmjs.com/package/@react-three/postprocessing) which I understand uses Effects rather than Passes, however I believe my real issue lies in library versions and peer-dependency conflicts.
Here is what it looks like with Screen Spaced Reflections working and the dependencies I used (note the nice reflections on the floor):
[](https://i.stack.imgur.com/Tgkdl.gif)
```
"@react-three/drei": "9.17.1",
"@react-three/fiber": "8.2.0",
"@react-three/postprocessing": "2.6.1",
"three": "0.142.0",
```
And here is what it looks like with Bloom working and the dependencies I used (note the nice glow around some of the neon bulbs):
[](https://i.stack.imgur.com/BDcss.gif)
```
"@react-three/drei": "^9.84.2"
"@react-three/fiber": "^8.15.15"
"@react-three/postprocessing": "^2.16.0"
"three": "^0.161.0"
```
I've read in a few places that SSR has been deprecated in more recent version so maybe I need to implement Drei's Reflector or MeshReflectionMaterial.
Here is a link to the public github repo: https://github.com/DaveSeidman/jen-stark and the [relevant code block](https://github.com/DaveSeidman/jen-stark/blob/main/src/components/scene/index.jsx#L81-L86)
Hopefully there's an easy way to resolve it and implement both effects. Thanks in advance for any help or guidance!
I've bounced through a lot of codeandsandbox examples, read all the relevant docs for all the libraries, and experimented heavily with upgrading / downgrading npm versions of each of the relevant libraries. |
Threejs Postprocessing Screen Spaced Reflections with Bloom |
|three.js|react-three-fiber|post-processing|react-three-drei|bloom| |
null |
No, unfortunately, all IDE have limitations to display datasets.
However, you can print row by row until you reach the end of your dataframe. |
**The problem**
In my Flutter app, there is a custom drawer that is accessed through a button. In this drawer, there is a widget (InfoCard) which displays some of the user's information. However, in this widget, there is a FutureBuilder, so every time the drawer is displayed it shows a CircularProgressIndicator until it gets all the pieces of information from the Firestore server. My question is: can I avoid the FutureBuilder so that, when the app is fully loaded, it gets all the data needed for the widget?
Another problem related to this is that I need to wait until the SQFLite database is loaded before returning the InfoCard widget (I don't know why because all the data is uploaded on the Firestore server). So the thing is: I have to avoid calling the database or I call it somehow before building the widget so that I don't need to use the FutureBuilder.
**The code**
Here is the widget drawer:
class SideDrawer extends ConsumerStatefulWidget {
SideDrawer({
super.key,
required this.setIndex,
});
Function(int index) setIndex;
@override
ConsumerState<SideDrawer> createState() => _SideDrawerState();
}
class _SideDrawerState extends ConsumerState<SideDrawer> {
@override
Widget build(BuildContext context) {
final userP = ref.watch(userStateNotifier);
return Scaffold(
body: Container(
width: MediaQuery.sizeOf(context).width * 3 / 4,
height: double.infinity,
color: Theme.of(context).colorScheme.secondary,
child: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
FutureBuilder<Widget>(
future: Datas().infocard(userP),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return Text('Errore: ${snapshot.error}');
}
return snapshot.data!;
} else {
return CircularProgressIndicator();
}
},
),
ColDrawer(setIndex: (index) {
widget.setIndex(index);
},),
],
),
),
),
);
}
}
the infoCard method:
Future<Widget> infocard(AppUser userP) async {
var db = FirebaseFirestore.instance;
QuerySnapshot qn =
await db.collection('users').where('id', isEqualTo: userP.id).get();
return InfoCard(
username: userP.username,
age: userP.age,
weight: userP.measurements
.firstWhere((measure) => measure.title == 'Weight')
.datas
.last
.values
.first,
);
}
If I don't wait for the database to be loaded or if I substitute the FutureBuilder with the InfoCard widget, it throws this error ONLY for the userP.measurements... line:
StateError (Bad state: No element)
Lastly, why do I need to call the database even though all the data is stored on the Firestore database (and gotten when the app is launched)? |
Iβm making an in app purchase for my game on Steam. On my server I use python 3. Iβm trying to make an https request as follows:
conn = http.client.HTTPSConnection("partner.steam-api.com")
orderid = uuid.uuid4().int & (1<<64)-1
print("orderid = ", orderid)
key = "xxxxxxxxxxxxxxxxxxx" # omitted for security reason
steamid = "xxxxxxxxxxxxxxxxxxx" # omitted for security reason
pid = "testItem1"
appid = "480"
itemcount = 1
currency = 'CNY'
amount = 350
description = 'testing_description'
urlSandbox = "/ISteamMicroTxnSandbox/"
s = f'{urlSandbox}InitTxn/v3/?key={key}&orderid={orderid}&appid={appid}&steamid={steamid}&itemcount={itemcount}¤cy={currency}&itemid[0]={pid}&qty[0]={1}&amount[0]={amount}&description[0]={description}'
print("s = ", s)
conn.request('POST', s)
r = conn.getresponse()
print("InitTxn result = ", r.read())
I checked the s in console, which is:
```
s = /ISteamMicroTxnSandbox/InitTxn/v3/?key=xxxxxxx&orderid=11506775749761176415&appid=480&steamid=xxxxxxxxxxxx&itemcount=1¤cy=CNY&itemid[0]=testItem1&qty[0]=1&amount[0]=350&description[0]=testing_description
```
However I got a bad request response:
```
InitTxn result = b"<html><head><title>Bad Request</title></head><body><h1>Bad Request</h1>Required parameter 'orderid' is missing</body></html>"
````
How to solve this? Thank you!
BTW I use almost the same way to call GetUserInfo, except changing parameters and replace POST with GET request, and it works well.
Just read that I should put parameters in post. So I changed the codes to as follows, but still get the same error of "Required parameter 'orderid' is missing"
params = {
'key': key,
'orderid': orderid,
'appid': appid,
'steamid': steamid,
'itemcount': itemcount,
'currency': currency,
'pid': pid,
'qty[0]': 1,
'amount[0]': amount,
'description[0]': description
}
s = urllib.parse.urlencode(params)
# In console: s = key=xxxxx&orderid=9231307508782239594&appid=480&steamid=xxx&itemcount=1¤cy=CNY&pid=testItem1&qty%5B0%5D=1&amount%5B0%5D=350&description%5B0%5D=testing_description
print("s = ", s)
conn.request('POST', url=f'{urlSandbox}InitTxn/v3/', body=s) |
{"Voters":[{"Id":7582247,"DisplayName":"Ted Lyngmo"},{"Id":18519921,"DisplayName":"wohlstad"},{"Id":11294831,"DisplayName":"the busybee"}],"SiteSpecificCloseReasonIds":[13]} |
If the packageManger field in package.json is not specified, Corepack will download the **global** version of the package manager that Corepack is configured with (Corepack also calls these 'Known Good Releases'). To update the Known Good Release, you can either:
- Set the packageManger field in your project's package.json to your preferred version (e.g. `"packageManger": "yarn@4.1.1"`), then run `yarn` to install the dependencies using that package manager version.
- Upgrade Corepack's global yarn version using `corepack up -g yarn@4.1.1`.
----------
## Links
- Useful issue on the Corepack Github discussing upgrading globally installed package managers: https://github.com/nodejs/corepack/issues/395
- Known Good Releases Corepack documentation: https://github.com/nodejs/corepack?tab=readme-ov-file#known-good-releases |
THIS IS MY TRUFFLE-CONFIG.JS
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
require("babel-register");
const HDWalletProvider = require("truffle-hdwallet-provider");
require("dotenv").config();
module.exports = {
networks: {
Sepolia: {
provider: function() {
return new HDWalletProvider(
process.env.MNEMONIC,
process.env.PROJECT_ENDPOINT,
address_index=0,
num_addresses=2
);
},
network_id: 11155111 ,
gas: 4500000,
gasPrice: 10000000000,
},
development: {
host: process.env.LOCAL_ENDPOINT.split(":")[1].slice(2),
port: process.env.LOCAL_ENDPOINT.split(":")[2],
network_id: "*",
},
compilers: {
solc: {
version: "^0.4.24",
},
},
},
};
<!-- end snippet -->
I AM UNABLE TO GET THE NETWORK ID FOR SEPOLIA TEST NETWORK
BELOW IS THE LINK OF THE ERROR COMING-
[1]: https://i.stack.imgur.com/HPl09.png |
automatically compare prices with ready-made codes |
|css|bootstrap-5| |
null |
I am looking for example to JUnit test KStream related scenarios with spring-cloud-stream kafka streams binder. Any example available with KStream, KTable? For example i want to test following function
@Bean
public Function<KStream<String, String>, KTable<String, String>> func() {
return stringKStream -> {
stringKStream .print(Printed.<String, String>toSysOut().withLabel("String-Stream-
Print"));
return stringKStream.toTable();
};
}
I tried above example by referring https://docs.spring.io/spring-cloud-stream/reference/spring-cloud-stream/spring_integration_test_binder.html#test-binder-configuration but am getting following error
java.lang.NullPointerException: Cannot invoke
"org.springframework.messaging.SubscribableChannel.send(org.springframework.messaging.Message)"
because the return value of "org.springframework.cloud.stream.binder.test.InputDestination.getChannelByName(String)" is null
at org.springframework.cloud.stream.binder.test.InputDestination.send(InputDestination.java:89)
at net.apmoller.crb.apmt.microservices.tiaim.state.handler.integration.AnotherConfigTest.lambda$test2107$0(AnotherConfigTest.java:87)
at java.base/java.lang.Iterable.forEach(Iterable.java:75)
at net.apmoller.crb.apmt.microservices.tiaim.state.handler.integration.AnotherConfigTest.test2107(AnotherConfigTest.java:86)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) |
How to JUnit test KStream related scenarios with spring-cloud-stream kafka streams binder? Any example available with KStream, KTable? |
|spring-cloud-stream-binder-kafka| |
null |
I'm trying to create a plugin which hooks into Invision Community Suite's 'saved actions' functionality. Essentially, when a saved action is run against a topic, I want to ask for more information.
This is for the latest version of IPS, no third-party applications/plugins installed.
I have tried 'echo'ing the JavaScript out onto the page, with no avail - it just refreshed and didn't show anything.
I have tried utilising the '\IPS\Output' class to run some custom JavaScript:
```php
\IPS\Output::i()->jsVariables['arr_showConfirmationModal'] = 'ara_ShowDialog()';
```
where the 'ara_ShowDialog' method is as simple as:
```js
function ara_ShowDialog() {
dialog.show();
}
```
I have the hook working which hooks into the 'SavedAction' class, but I can't for the life of me figure out how to stop the page redirecting and display a popup modal - any help will be greatly appreciated! |
grep -o 'CN=[^,]*' data | sed 's/^CN=//'
The grep command extracts CN=*blahblahblah* by finding 'CN=' followed by anything that is not a comma. Then the sed command deletes 'CN=', leaving just the *blahblahblah*. Another way of doing it is
grep -o 'CN=[^,]*' data | tail -c +4
where the tail commands excludes the first 3 characters, which would be 'CN='
Here it is via a Lua script invoked at the shell:
<data lua -e 'for s in io.lines() do m = string.match(s, "CN=([^,]*)"); if m then print(m) end end'
Being restricted to one line, it is less clear, of course, than if it were on multiple lines.
Note that the input redirection from the file named "data" is written **before** the command rather than after, which is uncommon but it works, and I think makes more sense conceptually. This has nothing to do with Lua, it is shell syntax.
The Lua match pattern "CN=([^,]*)" is very similar to an extended regex--the parentheses denote a capture pattern in order to exclude the "CN=".
Lua does not use regular expressions, but a similar system. See https://www.lua.org/manual/5.4/manual.html#6.4.1 |
How to maintain the current state of global key in flutter |
|flutter|dart|global-key| |
null |
I've just installed Wordpress 6.4.3 & MAMP and managed to edit functions.php and saved my changes.
When I tried to make more changes to the file, Wordpress started displaying the following error message:
> Something went wrong. Your change may not have been saved. Please try again. There is also a chance that you may need to manually fix and upload the file over FTP.
What I have done:
- I've checked permissions of the file and gave read and write access to everyone on my localhost.
- Restarted the server
|
I have created an ASP.NET Core 6 Web API using C#.
When I changed `app.Run();` in `program.cs` file to this:
```
app.Run(async context =>
{
await context.Response.WriteAsync("I'm upgrading!\nTRY AGAIN LATER");
});
```
The application does not show me the message and does not open either!
Does anybody know the reason?
I tried to change the pipeline but it didn't work.
My `program.cs` file is now like this:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run(async context =>
{
await context.Response.WriteAsync("I'm upgrading!\nTRY AGAIN LATER");
}); |
ASP.NET Core Web API pipeline Does Not Work As expected |
|c#|asp.net-core-webapi|asp.net-core-6.0| |
I'm working on a program that processes arrays of coordinate points, with the goal of determining whether these points form geometric shapes such as circles, ellipses, arcs, straight lines, or polylines. If the points form a circle or an ellipse, the program needs to return the parameters of these shapes.
I've looked into two potential methods for this problem:
1. Hough Transform: I understand that it's a feature extraction technique used to detect shapes, but I'm concerned about its computational complexity, especially for detecting ellipses due to the high dimensionality of the parameter space.
2. Direct Least Squares Fitting of Ellipses: This seems to be a straightforward approach for ellipse detection , but I'm concerned that it has the potential to detect polylines as ellipses.
I am looking for advice on:
- Which method would be more suitable for accurately and efficiently detecting circles and ellipses in my scenario?
- How can these methods be adapted to handle the detection of straight lines or polylines, or to differentiate between these and circular/elliptical shapes?
- Are there any reference implementations or libraries in Java that could simplify this process?
I appreciate any guidance or suggestions on how to approach this problem. Thank you in advance! |
Here is the scenario / task:
The user is browsing online and as soon as he/she runs into a website that uses CDN (for example CloudFlare or any other reverse proxy) the browser the user is using has to do the following:
Either
1. Warn the user that the site is on CDN / reverse proxy.
or
2. Block the site by saying it's on CDN / reverse proxy.
Are there any extensions / plug in / scripts to achieve this? Would appreciate any comments / suggestions / insights. Many thanks in advance!
|
Here is the scenario / task:
The user is browsing online and as soon as he/she runs into a website that uses CDN (for example CloudFlare or any other reverse proxy) the browser the user is using has to do the following:
Either
1. Warn the user that the site is on CDN / reverse proxy.
or
2. Block the site by saying it's on CDN / reverse proxy.
Are there any extensions / plug in / scripts to achieve this? Would appreciate any comments / suggestions / insights. Many thanks in advance!
|
{"Voters":[{"Id":10008173,"DisplayName":"David Maze"},{"Id":2395282,"DisplayName":"vimuth"},{"Id":213269,"DisplayName":"Jonas"}],"SiteSpecificCloseReasonIds":[13]} |
**Explaination**
I have visual studio to 17.9.5
when i publish an existing project or create a new one and publish it.
It shows me only the http:5000 port.
It does not run neither on cloud.
**Question**
Why is the https port disabled on publish?
How can it be enabled?
**The code i get when i run the app, after publish**
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
|
Why https is disabled on publish in .net core 7.0 |
|.net|asp.net-core| |
|python|setuptools|setup.py|python-packaging|pipenv| |
|node.js|database|jsx| |
Since it was obvious nobody knew the answers I was looking for, I decided to experiment and discovered/remembered the following: for vertical spacing the first two keys are Alt+O V, and for horizontal spacing Alt+O Z. After this, you type E (to equalise), I (to increase) or D (to decrease). I'm using Access 2010 and the main problem I have with it is that when editing a form it is essential to close the properties list before exiting design mode, otherwise you may have to wait 10 minutes while "Access is not responding".
I hope those of you who like to design their forms themselves (rather than relying on a wizard) find these commands as useful as I have done over the years.
|
I have developed a social platform where users can upload text posts, each time a user opens the app text posts pubished on the database are showed, we also have a page including posts under top hashtags, in app notifications, personal page with our posts showing and the ability to search for hashtags. I have to admit I didn't really take the download problem in consideration. I just tought that, since all the information is in string the download size would have been very low. Instead in the 5 days of the launch, with just 20 users our download size increased drastically reaching a value of 100MB a day. That's pretty high.
What are the best practicises to reduce download size in this situation? I woulf like to create a caching system: I want users to be able to see new posts without having to re-download all of them. |
As @Paulie_D say, you can avoid this overflow issue by changing `height` to `min-height`
<!-- begin snippet: js hide: false console: false babel: false -->
<!-- language: lang-js -->
document.body.addEventListener('click', function() {
const elem = document.getElementById("aid");
if( elem.innerHTML == "" ) {
elem.innerHTML = "Some long content. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec molestie metus ac nunc hendrerit suscipit. Aenean convallis accumsan gravida. Ut lobortis turpis ut orci efficitur, at eleifend arcu ultricies. Ut tempus eget neque efficitur auctor. Donec sagittis, augue et rhoncus vulputate, purus sem malesuada elit, id rhoncus dolor nulla placerat velit. Suspendisse purus quam, consequat quis turpis ut, tempor elementum nulla. Pellentesque nibh risus, aliquet sit amet felis placerat, lobortis vehicula nisl. Sed convallis turpis sodales ligula egestas, a ultrices libero ultrices. Sed in ipsum urna. Suspendisse aliquet mollis enim. Aliquam mollis est vitae dignissim finibus. Sed nulla tortor, ultricies eget aliquet a, consectetur at enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam sodales ligula eget lacus maximus, ut suscipit augue tristique. Phasellus ac tortor dolor. Etiam ornare tempor semper. Fusce rutrum arcu a est iaculis varius. Curabitur libero augue, bibendum non leo sit amet, malesuada blandsse purus quam, consequat quis turpis ut, tempor elementum nulla. Pellentesque nibh risus, aliquet sit amet felis placerat, lobortis vehicula nisl. Sed convallis turpis sbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam sodales ligula eget lacus maximus, ut suscipit augue tristique. Phasellus ac tortor dolor. Etiam ornare tempor semper. Fusce rutrum arcu a est iaculis varius. Curabitur libero augue, bibendum non leo sit amet, malesuada blandsse purus quam, consequat quis turpis ut, tempor elementum nulla. Pellentesque nibh risus, aliquet sit amet felis placerat, lobortis vehicula nisl. Sed convallis turpis sodales ligula egestas, a ultrices libero ultrices. Sed in ipsum urna. Suspendisse aliquet mollis enim. Aliquam mollis est vitae dignissim finibus. Sed nulla tortor, ultricies eget aliquet a, consectetur at enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam sodales ligula eget lacus maximus, ut suscipit augue tristique. Phasellus ac tortor dolor. Etiam ornare tempor semper. Fusce rutrum arcu a est iaculis varius. Curabitur libero augue, bibendum non leo sit amet, malesuada blandit nunc. Maecenas pulvinar ligula et arcu feugiat egestas. Nunc quis viverra ante. Donec purus augue, iaculis a dui ut, ullamcorper viverra massa. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam elementum ipsum nunc, quis dictum massa convallis quis. Morbi neque risus, mattis sodales lobortis eu, iaculis a sapien. Suspendisse aliquet mollis enim. Aliquam mollis est vitae dignissim finibus. Sed nulla tortor, ultricies eget aliquet a, consectetur at enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam sodales ligula eget lacus maximus, ut suscipit augue tristique. Phasellus ac tortor dolor. Etiam ornare tempor semper. Fusce rutrum arcu a est iaculis varius. Curabitur libero augue, bibendum non leo sit amet, malesuada blandit nunc. Maecenas pulvinar ligula et arcu feugiat egestas. Nunc quis viverra ante. Donec purus augue, iaculis a dui ut, ullamcorper viverra massa. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam elementum ipsum nunc, quis dictum massa convallis quis. Morbi neque risus, mattis sodales lobortis eu, iaculis a sapien.";
}
else {
elem.innerHTML = "";
}
}, true);
<!-- language: lang-css -->
body {
margin: 0;
min-height: 100dvh;
padding: 2dvh 0;
box-sizing: border-box;
display: flex;
flex-direction: column;
}
.fill {
background-color: green;
flex-grow: 1;
}
.header, .footer {
background-color: red;
color: white;
padding: 1rem;
}
<!-- language: lang-html -->
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="header">Header</div>
<div id=aid></div>
<div class="fill"></div>
<div class="footer">Footer</div>
</body>
<!-- end snippet -->
|
Currently, I'm trying to get down basics of jetpack compose, and I'd like to ask you about the view model. Let's say we have an app which will make a few different api calls. As far as I know, before jetpack compose, we could have a few fragments for each api call (because they will serve completely different data). So we had to make separated ViewModel for each fragment, right? But how should I approach ViewModels in jetpack compose, when we can have a single activity, that display many composables? Should I stay with one ViewModel then? |
Your question is definitely incomplete, and it's going to be hard to find a legit answer.
How do you experience the cached file? I'm assuming that it is downloaded via https:// on the website? That's really the only time WordPress and cache is involved...
So the answer is to rewrite the URL code inside to do this:
$filePath = "/location/on/fs/of/sellers.json";
$fileURI = "/location/on/uri/sellers.json";
$timestamp = filemtime($filePath);
echo "<a href=\"$fileURI?$timestamp\">My Sellers</a>";
The trick is to pass a timestamp of the file with the URL. Then, you'll never need to hit the clear-cache button. |
Windows 11
I would like to filter double values.
[![enter image description here][1]][1]
[![enter image description here][2]][2]
[1]: https://i.stack.imgur.com/ZckkI.png
[2]: https://i.stack.imgur.com/ICCrr.png
1. testo = text
2. numerico = numeric
3. valuta = currency
I can filter Strings
Dim srchStr As String = Me.TextBox1.text
Dim strFilter As String = "MyCol1 LIKE '*" & srchStr.Replace("'", "''") & "*'"
dv.RowFilter = strFilter
I can filter Integers
Dim srchStr As String = Me.TextBox1.Text
Dim id As Integer
If Integer.TryParse(srchStr, id) Then
dv.RowFilter = "code = " & id
Else
MessageBox.Show("Error: ........")
End If
Dim strFilter As String = "code = " & id
dv.RowFilter = strFilter
but I can not filter a double value.
I actually use this code to filter strings in my DataGridView
Private Sub MyTabDataGridView_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyTabDataGridView.DoubleClick
Try
'MyRow
Dim row As Integer = MyTabDataGridView.CurrentRow.Index
'MyColumn
Dim column As Integer = MyTabDataGridView.CurrentCell.ColumnIndex
'MyColumn and MyRow
Dim ColumnRow As String = MyTabDataGridView(column, row).FormattedValue.ToString
'Header Text
Dim HeaderText As String = MyTabDataGridView.Columns(column).HeaderText
'I exclude the errors
If HeaderText = "id" Or HeaderText = "MyCol3" Or HeaderText = "MyCol4" Or HeaderText = "MyCol5" Then
Exit Sub
End If
'Ready to filter
Dim strFilter As String = HeaderText & " Like '*" & ColomnRow.Replace("'", "''") & "*'"
dv.RowFilter = strFilter
Catch ex As Exception
End Try
Any suggestion will be highly appreciated.
Solution:
Private Sub MyTabDataGridView_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyTabDataGridView.DoubleClick
Try
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US")
'MyRow
Dim row As Integer = MyTabDataGridView.CurrentRow.Index
'MyColumn
Dim column As Integer = MyTabDataGridView.CurrentCell.ColumnIndex
'MyColumn and MyRow
Dim ColumnRow As String = MyTabDataGridView(column, row).FormattedValue.ToString
'Header Text
Dim HeaderText As String = MyTabDataGridView.Columns(column).HeaderText
'I exclude the errors
If HeaderText = "id" Then
Exit Sub
End If
If HeaderText = "MyCol1" Or HeaderText = "MyCol2" Then
'Si filtra
Dim strFilter As String = HeaderText & " Like '*" & ColumnRow & "*'"
dv.RowFilter = strFilter
ElseIf HeaderText = "MyCol3" Or HeaderText = "MyCol4" Or HeaderText = "MyCol5" Then
Dim strFilter2 As String = HeaderText & "= " & ColumnRow.Replace(",", ".")
dv.RowFilter = strFilter2
End If
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("it-IT")
'Refresh il DataGridView
Me.MyTabDataGridView.Refresh()
Catch ex As Exception
Dim lNewVariable2 As String = "mailto:m_larosamdvm@libero.it?subject=Invio Dati " & "&body= {0}{1}{2}"
System.Diagnostics.Process.Start(String.Format(lNewVariable2, ex.Message, Environment.NewLine, ex.StackTrace))
End Try
End Sub
|
|sql|mysql|select|left-join| |
Considering the following example:
```rust
pub trait Fusion: Send + Sync {
...
}
let ff2: Arc<RefCell<(Box<dyn Fusion>, bool)>> = ...;
```
all Impls of Fusion already has atomic, lock-free algorithm built-in, they are safe to be shared in multiple threads. It should be noted that both RwLock and Mutex cannot be used here as they are too inefficient.
However, ff2 (mutable reference counting) cannot be used in another thread, the compiler will complain:
```lang-none
error[E0277]: `RefCell<(Box<dyn Fusion>, bool)>` cannot be shared between threads safely
--> src/lib.rs:188:36
|
188 | let handle = thread::spawn(move || loop {
| ______________________-------------_^
| | ...
196 | | });
| |_________^ `RefCell<(Box<dyn Fusion>, bool)>` cannot be shared between threads safely
```
I need to find an alternative smart pointer that supports both reference counting and lock-free mutability. To my knowledge, this feature doesn't exist in vanilla Rust. What should be done in this case? |
I don't know how to correctly calculate the accuracy of the relationship between how many tries I needed and how probable it was to find the number within this amount of tries. E.g. if I needed 1 try it should be 100% accuracy-score but if it took more tries, the accuracy-score gets decreased.
My attempt was to divide the amount of tries by the highest possible option and multiply this by 100 to get an accuracy-score of 1 to 100.
```
import random
input("You have to guess a number between two others you define! To play, press enter")
play = "yes"
lowest = 1
while play == "yes":
numIsSet = False
while not numIsSet:
highest = int(input("What should the highest number be? "))
if highest <= lowest:
print("Highest number should be greater than 1!")
else:
numIsSet = True
numSearch = random.randint(lowest, highest)
chance = lowest / highest * 100
numGuess = None
triesCount = 0
while numGuess != numSearch:
numGuess = int(input("Guess a number between " + str(lowest) + " and " + str(highest) + "! "))
triesCount += 1
if numGuess == numSearch:
accuracy = (triesCount / highest) * 100
print("Cool! You found the correct number with " + str(triesCount) + " tries!")
print("There was a chance of " + str(chance) + "% to find the correct number at the first try.")
print("Your accuracy score is:", accuracy)
if accuracy > 89:
print("β
β
β
β
β
Your score is VERY good!")
elif accuracy > 70:
print("β
β
β
β
β Your score is good!")
elif accuracy > 50:
print("β
β
β
ββ Your score is ok!")
elif accuracy > 30:
print("β
β
βββ Your score isn't that good. You can do it better!")
else:
print("β
ββββ Your score is bad. You can do it a lot better!")
triesCount = 0
play = input("Do you want to play again? If yes, type 'yes', if not press enter to close the program! ")
print()
elif numGuess < lowest or numGuess > highest:
print("Please use numbers in the given range!")
elif numGuess < numSearch:
print("β The searched number is HIGHER than yours!")
else:
print("β The searched number is LOWER than yours!")
```
----------
Edit
----
I got a solution close to what I wanted.
I first define the `average` amount of tries with `math.log2(highest - lowest + 1) + 1`. When the number is right, I calculate the relationship between the average and the actual amount of tries with `accuracy = round(average / triesCount, 3)` (rounded to 3 decimals). 1 is the average score and the higher it is, the better you are.
```
import random
import math
print("You have to guess a number between two others you define! To play, press enter")
play = "yes"
lowest = 1
while play == "yes":
numIsSet = False
while not numIsSet:
highest = int(input("What should the highest number be? "))
if highest <= lowest:
print("Highest number should be greater than 1!")
else:
numIsSet = True
numSearch = random.randint(lowest, highest)
chance = round(lowest / highest * 100, 3)
average = math.log2(highest - lowest + 1) + 1
print(average)
numGuess = None
triesCount = 0
while numGuess != numSearch:
numGuess = int(input("Guess a number between " + str(lowest) + " and " + str(highest) + "! "))
triesCount += 1
if numGuess == numSearch:
accuracy = round(average / triesCount, 3)
print()
print("Cool! You found the correct number with " + str(triesCount) + " tries!")
print("There was a chance of " + str(chance) + "% to find the correct number at the first try.")
print(f"Your accuracy score is {accuracy} (The average score is 1. The higher your score, the better it is!)")
if accuracy > 1:
print("β
β
β
β
β
Your score is VERY good!")
elif accuracy >= 0.9:
print("β
β
β
β
β Your score is good!")
elif accuracy >= 0.7:
print("β
β
β
ββ Your score is ok!")
elif accuracy >= 0.5:
print("β
β
βββ Your score isn't that good. You can do it better!")
else:
print("β
ββββ Your score is bad. You can do it a lot better!")
triesCount = 0
print()
play = input("Do you want to play again? If yes, type 'yes', if not press enter to close the program! ")
print()
elif numGuess < lowest or numGuess > highest:
print("Please use numbers in the given range!")
elif numGuess < numSearch:
print("β The searched number is HIGHER than yours!")
lowest = numGuess
else:
print("β The searched number is LOWER than yours!")
highest = numGuess
``` |
I am a beginner trying to build very simple inventory system using PHP + SQL
I have 2 warehouse. I added 2 tables, 1 for each warehouse contains (item id)-(in)- (out) like shown below
table1
| item id | in | out |
| -------- | -- |-----|
| item1 | 10 | 0 |
| item1 | 5 | 0 |
| item2 | 0 | 3 |
| item2 | 0 | 2 |
table2
| item id | in | out |
| -------- | -- |-----|
| item1 | 12 | 0 |
| item1 | 50 | 0 |
| item2 | 0 | 10 |
| item2 | 0 | 30 |
I have report show balance for each warehouse separately by using query below
Select item_id, sum(in-out) as balance from table1 group by item_id
My question is how show each warehouse balance in one table like below
| item id | warehouse1 | warehouse2|
| -------- | ---------- |-----------|
| item1 | 7 | 2 |
| item2 | 3 | 20 |
I tired with this query but I get wrong results
SELECT table1.item_id, sum(table1.in)-sum(table1.out) as tb1, sum(table2.in)-sum(table2.out) as tb2 FROM table1 , table2 WHERE table1.item_id=table2.item_id GROUP by item_id
the query above have 2 problems
1. results are not correct
2. only items in both tables are shown , while any item exist in table and not exists in the second one is not shown |
Why do I need to wait for SQFLite when data is stored in Firestore server |
|flutter|google-cloud-firestore|sqflite| |
In the index.html, does the <base href="/xxxxxxx/"> match the folder in IIS? Typically \inetpub\wwwroot\someapp but in your case d:\myapp
If you have a pluralsight subscribtion, there are videos by Shawn Wildermuth specifically on using .net and angular together.
Also, I am used to seeing Cors setup in two parts.
Setting up in services:
> services.AddCors(options =>
> {
> options.AddPolicy("MyAllowedOrigins",
> policy =>
> {
> policy
> .AllowAnyOrigin()
> .AllowAnyHeader()
> .AllowAnyMethod();
> });
> });
Calling in app:
app.UseCors("MyAllowedOrigins");
UPDATE #1
The OP mentioned 404 on refresh. There are many ways to setup IIS, Angular, etc. This sounds like a redirect issue.
Using the hash in the Angular route will should address this issue.
RouterModule.forRoot(routes,
{
useHash: true
}
If this fixes it, please mark this as the answer.
|
The Logtalk distribution includes a [state-space searching](https://github.com/LogtalkDotOrg/logtalk3/tree/master/examples/searching) programming example implementing a framework for solving state-space search problems. It includes abstractions of heuristic and non-heuristic state spaces plus several search methods allowing applying multiple search methods to a state space and applying a search method to multiple state spaces. A corrected definition of the "locked doors" state space using this framework could be:
:- object(doors,
instantiates(state_space)).
initial_state(start, s(Room, no_key, no_key)) :-
initial(Room).
goal_state(end, s(Room, _, _)) :-
treasure(Room).
% moving without picking up a key or using a key
next_state(s(A, Red, Blue), s(B, Red, Blue)) :-
door(A, B).
next_state(s(A, Red, Blue), s(B, Red, Blue)) :-
door(B, A).
% picking up a red key
next_state(s(A, no_key, Blue), s(B, red, Blue)) :-
door(A, B),
key(B, red).
% picking up a blue key
next_state(s(A, Red, no_key), s(B, Red, blue)) :-
door(A, B),
key(B, blue).
% open locked doors
next_state(s(A, Red, blue), s(B, Red, blue)) :-
locked_door(A, B, blue).
next_state(s(A, Red, blue), s(B, Red, blue)) :-
locked_door(B, A, blue).
next_state(s(A, red, Blue), s(B, red, Blue)) :-
locked_door(A, B, red).
next_state(s(A, red, Blue), s(B, red, Blue)) :-
locked_door(B, A, red).
print_state(State) :-
write(State),
nl.
initial(0).
door(0, 1).
door(0, 2).
door(1, 2).
door(1, 3).
door(2, 4).
locked_door(2, 5, red).
locked_door(5, 6, blue).
key(3, red).
key(4, blue).
treasure(6).
:- end_object.
Note that grabbing a key is independent of holding or not holding the other key, something that's incorrect in your code (unless your description of the problem is incomplete). Other changes are for either making the code more compact, simpler, or coding guidelines.
To get the shortest solution, we can use the provided breadth-first search method. Assuming the object above saved in a `doors.lgt` file in the current directory and using Logtalk with the Trealla Prolog backend:
$ tplgt -q
?- {searching(loader), doors}.
true.
?- doors::initial_state(Initial), breadth_first(20)::solve(doors, Initial, Path), doors::print_path(Path).
s(0,no_key,no_key)
s(1,no_key,no_key)
s(3,red,no_key)
s(1,red,no_key)
s(2,red,no_key)
s(4,red,blue)
s(2,red,blue)
s(5,red,blue)
s(6,red,blue)
Initial = s(0,no_key,no_key), Path = [s(0,no_key,no_key),s(1,no_key,no_key),s(3,red,no_key),s(1,red,no_key),s(2,red,no_key),s(4,red,blue),s(2,red,blue),s(5,red,blue),s(6,red,blue)]
;
Backtracking will give you solutions of increasing length. |
There are two frontend websites in question. Upon user authentication on one website, a JWT token is generated. Subsequently, when the user accesses the second frontend, they should seamlessly retrieve their information without the need for reauthentication. How can I effectively implement this feature? I would appreciate any suggestions or guidance on this matter. |
How to share JWT through 2 React.js Frontend |
|javascript|reactjs|node.js|jwt| |
# Material-UI Data-Grid v7
import { styled } from '@mui/system';
import { DataGridPro } from '@mui/x-data-grid-pro';
function DataGridGeneric(props) {
return (
<CustomDataGridPro
disableColumnMenu
{...props}
/>
);
}
export default DataGridGeneric;
const CustomDataGridPro = styled(DataGridPro)(({ theme }) => ({
'& .MuiDataGrid-columnSeparator': {
display: 'none'
}
}));
p.s. in v7 works for me, hope it helps |
Another solution:
```cpp
=LET(s,SEQUENCE(INT(LEN(A2)/2)),FILTER(LEFT(A2,s),LEFT(A2,s)=MID(A2,s+1,s)))
```
[![enter image description here][1]][1]
The idea is the same as the other user. Generate all the potentially matching strings of length at most `INT(LEN(str)/2)` and only keep the ones that match, if there are any.
For example, for `johnjohnsajoalsas` we check the following strings:
[![enter image description here][2]][2]
We see there is a match at row 4 so we keep that value and remove everything else.
We could also do this with a single formula in <kbd>C2</kbd> that doesn't require to be dragged using the [`MAP`](https://support.google.com/docs/answer/12568985?hl=en) function.
```cpp
=MAP(A2:A,LAMBDA(str,IF(str="",,LET(s,SEQUENCE(INT(LEN(str)/2)),
FILTER(LEFT(str,s),LEFT(str,s)=MID(str,s+1,s))))))
```
[![enter image description here][3]][3]
[1]: https://i.stack.imgur.com/k1Hfq.png
[2]: https://i.stack.imgur.com/sytfH.png
[3]: https://i.stack.imgur.com/K390K.png |
I'd like to create a speech bubble using pure CSS.
There's a few requirements I have:
- It must scale with either the content + some padding or a preffered size.
- It's background color should be semi-transparent.
- You should be able to set a border, with it's own level of transparency.
- You should be able to set a border-radius, which both the border and background adheres to.
Here's an example of what I would imagine two of such a speech bubble would look like, the first has a preffered with and height and centers the content, the second fits the height and width of the content with some padding. I think the crucial bit here is that in both cases, the little pointy triangle remains the same size and is centered.
[![enter image description here][1]][1]
I've tried looking for different speech bubble approaches, and attempted to adapt examples, such as #34 on the list [here](https://css-generators.com/tooltip-speech-bubble/):
```css
/* HTML: <div class="tooltip">This is a Tooltip with a border and a border radius. Border can have a solid or gradient coloration and the background is transparent</div> */
.tooltip {
color: #fff;
font-size: 18px;
max-width: 28ch;
text-align: center;
background-color: #ff000055;
border-radius: 25px;
}
.tooltip {
/* triangle dimension */
--a: 90deg; /* angle */
--h: 1em; /* height */
--p: 50%; /* triangle position (0%:left 100%:right) */
--b: 7px; /* border width */
--r: 1.2em; /* the radius */
padding: 1em;
color: #415462;
position: relative;
z-index: 0;
}
.tooltip:before,
.tooltip:after {
content: '';
position: absolute;
z-index: -1;
inset: 0;
background: conic-gradient(#4ecdc4 33%, #fa2a00 0 66%, #cf9d38 0); /* your coloration */
--_p: clamp(
var(--h) * tan(var(--a) / 2) + var(--b),
var(--p),
100% - var(--h) * tan(var(--a) / 2) - var(--b)
);
}
.tooltip:before {
padding: var(--b);
border-radius: var(--r) var(--r) min(var(--r), 100% - var(--p) - var(--h) * tan(var(--a) / 2))
min(var(--r), var(--p) - var(--h) * tan(var(--a) / 2)) / var(--r);
background-size: 100% calc(100% + var(--h));
clip-path: polygon(
0 100%,
0 0,
100% 0,
100% 100%,
calc(var(--_p) + var(--h) * tan(var(--a) / 2) - var(--b) * tan(45deg - var(--a) / 4)) 100%,
calc(var(--_p) + var(--h) * tan(var(--a) / 2) - var(--b) * tan(45deg - var(--a) / 4))
calc(100% - var(--b)),
calc(var(--_p) - var(--h) * tan(var(--a) / 2) + var(--b) * tan(45deg - var(--a) / 4))
calc(100% - var(--b)),
calc(var(--_p) - var(--h) * tan(var(--a) / 2) + var(--b) * tan(45deg - var(--a) / 4)) 100%
);
-webkit-mask:
linear-gradient(#000 0 0) content-box,
linear-gradient(#000 0 0);
-webkit-mask-composite: xor;
mask-composite: exclude;
}
.tooltip:after {
bottom: calc(-1 * var(--h));
clip-path: polygon(
calc(var(--_p) + var(--h) * tan(var(--a) / 2)) calc(100% - var(--h)),
var(--_p) 100%,
calc(var(--_p) - var(--h) * tan(var(--a) / 2)) calc(100% - var(--h)),
calc(var(--_p) - var(--h) * tan(var(--a) / 2) + var(--b) * tan(45deg - var(--a) / 4))
calc(100% - var(--h) - var(--b)),
var(--_p) calc(100% - var(--b) / sin(var(--a) / 2)),
calc(var(--_p) + var(--h) * tan(var(--a) / 2) - var(--b) * tan(45deg - var(--a) / 4))
calc(100% - var(--h) - var(--b))
);
}
```
But setting a semi-transparent background color (and a border-radius to hide the overflow behind the border) doesn't fill in the little triangle at the bottom. Nor could I find a way to do so.
I also found a related question [here](https://stackoverflow.com/questions/69144960/speech-bubble-with-triangle-translucent-background) which suggests an approach which I adapted to the code below
```html
<div class="background">
<div class="bubble">
<p>
Hello world! I am some content. Who's got time for lorems?
</p>
</div>
</div>
```
```css
.background {
background: pink;
display: flex;
width: 100%;
height: 100vh;
}
.bubble {
height: fit-content;
color: red;
max-width: 75%;
min-width: 200px;
padding: 8px 12px 0 12px;
position: relative;
border-radius: 0 0 4px 4px;
margin-top:40px;
border: 1px solid red;
border-top:0;
margin-right: 16px;
background: #0000bb55;
}
.bubble::before,
.bubble::after{
content: '';
position: absolute;
width: 70%;
height: 20px;
top: -21px;
border:1px solid;
background: #0000bb55;
}
.bubble::before {
right:-1px;
border:1px solid;
border-width:1px 1px 0 0;
transform-origin:bottom;
transform:skew(-45deg);
}
.bubble::after{
left:-1px;
border-width:1px 0 0 1px;
border-radius:4px 0 0 0;
}
p {
margin-top:0;
}
```
But as soon as you start introducing semi-transparent colors, those skewed transforms start overlapping and introducing color discrepancies.
[![enter image description here][2]][2]
Finally, the answers in [this](https://stackoverflow.com/questions/16356438/opacity-in-a-speech-bubble-in-css) post also seems to have different opacity levels for the triangle and the background:
```html
<div class="wrapper">
<p class="infoBubble">aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</p>
</div>
```
```css
.wrapper {
background: pink;
height: 500px;
width: 100vw;
}
.infoBubble {
font-family:arial;
font-size:12px;
color:#FFFFFF;
display: inline-block;
position: absolute;
padding:6px;
background-color: rgba(0, 0, 0, 0.7);
-webkit-border-radius:7px;
-moz-border-radius:7px;
border-radius:7px;
}
.infoBubble:after {
content:"";
position:absolute;
bottom:-6px;
left:20px;
opacity:0.7;
border-width:6px 6px 0;
border-style:solid;
border-color: rgba(0, 0, 0, 0.7) transparent;
display:block;
width:0;
}
```
[![enter image description here][3]][3]
[![enter image description here][4]][4]
So, I am wondering.. what is the right approach here?
[1]: https://i.stack.imgur.com/363Zq.jpg
[2]: https://i.stack.imgur.com/PQzom.png
[3]: https://i.stack.imgur.com/HkmbM.png
[4]: https://i.stack.imgur.com/dL8JT.png |
Pure CSS speech bubble with semi-transparent background and a border |
|html|css| |
I have a page similar to this:
File: `[pid].tsx`
type ProblemPageProps = {
problem: Problem
};
const ProblemPage:React.FC<ProblemPageProps> = ({problem}) => {
...
return (
<div>
<Workspace problem={problem} />
</div>
);
}
export default ProblemPage;
export async function getStaticPaths() {
const paths = Object.keys(problems).map((key) => ({
params: {pid:key}
}))
return {
paths,
fallback: false
}
}
export async function getStaticProps({params}: {params: {pid: string}}) {
const {pid} = params;
const problem = problems[pid];
if (!problem) {
return {
notFound: true
}
}
return {
props: {
problem
}
}
}
In `Workspace` I have something like this - gets triggered on a click of a button:
const handleCodeReset = () => {
setUserCode(problem.starterCode);
};
And I have one function to push to the **same** `[pid].tsx` page but with a different PID:
const handlePreviousProblemChange = () => {
router.push(`/problems/my_second_problem`);
}
Being triggered by:
<div onClick={() => handlePreviousProblemChange()}>
BLA BLA BLA
</div>
When that happens, `problem` is pointing to `my_second_problem` which is exactly what I need but during `onClick` event, `problem.starterCode` still points to the previous `pid`. What can I do to make sure `problem.startedCode` gets referenced in the right way?
This is an example of `problem`:
interface ProblemMap {
[key: string]: Problem;
}
export const problems: ProblemMap = {
"key": value,
...
} |
Detecting Circles and Ellipses from Point Arrays in Java |