qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,390,753 | <p>I'm referring to the snippet in useEffect in the for loop at the last line. After I ran the code once and I console.logged the grids state with the button I rendered I'd get an array with only the number 196.</p>
<pre><code>import { useState, useEffect } from "react";
const Gameboard = () => {
const [grids, setGrids] = useState([]);
useEffect(() => {
setGrids([]);
for (let i = 0; i < 196; i++) {
const grid = i + 1;
setGrids([...grids, grid]);
}
}, [])
return (
<div className="game-board">
<button onClick={() => console.log(grids)}>click</button>
{grids.map(grid => (
<div key={ grid }></div>
))}
</div>
);
}
export default Gameboard;
</code></pre>
<p>Now I know how to fix that:</p>
<pre><code>import { useState, useEffect } from "react";
const Gameboard = () => {
const [grids, setGrids] = useState([]);
useEffect(() => {
setGrids([]);
for (let i = 0; i < 196; i++) {
const grid = i + 1;
setGrids(grids => [...grids, grid]);
}
}, [])
return (
<div className="game-board">
{grids.map(grid => (
<div key={ grid }></div>
))}
</div>
);
}
export default Gameboard;
</code></pre>
<p>So the latter one works. That's clear. But why is it? Can someone explain me how this:</p>
<p>setGrids([...grids, grid]);</p>
<p>and this:</p>
<p>setGrids(grids => [...grids, grid]);</p>
<p>works? And why do we get good results with the last one unlike with the other. Thanks in advance!</p>
| [
{
"answer_id": 74390824,
"author": "Rono",
"author_id": 2292457,
"author_profile": "https://Stackoverflow.com/users/2292457",
"pm_score": 3,
"selected": true,
"text": "if (yourArray.Any(a => example1.StartsWith(a))\n"
},
{
"answer_id": 74392129,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 0,
"selected": false,
"text": "foreach"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74390753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20306342/"
] |
74,390,767 | <pre><code>{"reels":{"6592252783":{"id":"6592252783","latest_reel_media":1668086478,"expiring_at":1668172878,"seen"....
</code></pre>
<p>How can we do 6592252783 is changing every time.</p>
<pre><code>Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class _16278726
{
public string id { get; set; }
public int latest_reel_media { get; set; }
public int expiring_at { get; set; }
public int seen { get; set; }
public bool can_reply { get; set; }
public bool can_gif_quick_reply { get; set; }
public bool can_reshare { get; set; }
public bool can_react_with_avatar { get; set; }
public string reel_type { get; set; }
public object ad_expiry_timestamp_in_millis { get; set; }
public object is_cta_sticker_available { get; set; }
public User user { get; set; }
public List<Item> items { get; set; }
public int prefetch_count { get; set; }
public int media_count { get; set; }
public List<string> media_ids { get; set; }
}
</code></pre>
<p>ı use online json to c# converter .How should it be?</p>
| [
{
"answer_id": 74390824,
"author": "Rono",
"author_id": 2292457,
"author_profile": "https://Stackoverflow.com/users/2292457",
"pm_score": 3,
"selected": true,
"text": "if (yourArray.Any(a => example1.StartsWith(a))\n"
},
{
"answer_id": 74392129,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 0,
"selected": false,
"text": "foreach"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74390767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5695903/"
] |
74,390,792 | <p><strong>EDIT</strong>:</p>
<p>It seems that there is a something unsupported by valgrind with alpine ditrib.
With a simple main like this :</p>
<pre><code>#include <iostream>
int main() {return 0;}
</code></pre>
<p>valgrind return a leak :</p>
<pre><code>==8== Memcheck, a memory error detector
==8== Copyright (C) 2002-2022, and GNU GPL'd, by Julian Seward et al.
==8== Using Valgrind-3.19.0-8d3c8034b8-20220411 and LibVEX; rerun with -h for copyright info
==8== Command: ./toto
==8== Parent PID: 1
==8==
--8--
--8-- Valgrind options:
--8-- --track-origins=yes
--8-- --keep-debuginfo=yes
--8-- --read-inline-info=yes
--8-- --error-exitcode=1
--8-- --leak-check=full
--8-- --errors-for-leak-kinds=all
--8-- --show-leak-kinds=all
--8-- --verbose
--8-- --sigill-diagnostics=no
--8-- --log-file=valgrind-out.txt
--8-- Contents of /proc/version:
--8-- Linux version 5.10.16.3-microsoft-standard-WSL2 (oe-user@oe-host) (x86_64-msft-linux-gcc (GCC) 9.3.0, GNU ld (GNU Binutils) 2.34.0.20200220) #1 SMP Fri Apr 2 22:23:49 UTC 2021
--8--
--8-- Arch and hwcaps: AMD64, LittleEndian, amd64-cx16-lzcnt-rdtscp-sse3-ssse3-avx-avx2-bmi-f16c-rdrand-rdseed
--8-- Page sizes: currently 4096, max supported 4096
--8-- Valgrind library directory: /usr/libexec/valgrind
--8-- Reading syms from /src/toto
--8-- Reading syms from /lib/ld-musl-x86_64.so.1
--8-- object doesn't have a symbol table
--8-- Reading syms from /usr/libexec/valgrind/memcheck-amd64-linux
--8-- object doesn't have a dynamic symbol table
--8-- Scheduler: using generic scheduler lock implementation.
--8-- Reading suppressions file: /usr/libexec/valgrind/default.supp
==8== embedded gdbserver: reading from /tmp/vgdb-pipe-from-vgdb-to-8-by-???-on-0d65120c6746
==8== embedded gdbserver: writing to /tmp/vgdb-pipe-to-vgdb-from-8-by-???-on-0d65120c6746
==8== embedded gdbserver: shared mem /tmp/vgdb-pipe-shared-mem-vgdb-8-by-???-on-0d65120c6746
==8==
==8== TO CONTROL THIS PROCESS USING vgdb (which you probably
==8== don't want to do, unless you know exactly what you're doing,
==8== or are doing some strange experiment):
==8== /usr/libexec/valgrind/../../bin/vgdb --pid=8 ...command...
==8==
==8== TO DEBUG THIS PROCESS USING GDB: start GDB like this
==8== /path/to/gdb ./toto
==8== and then give GDB the following command
==8== target remote | /usr/libexec/valgrind/../../bin/vgdb --pid=8
==8== --pid is optional if only one valgrind process is running
==8==
--8-- Reading syms from /usr/libexec/valgrind/vgpreload_core-amd64-linux.so
--8-- object doesn't have a symbol table
--8-- Reading syms from /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so
--8-- object doesn't have a symbol table
--8-- REDIR: 0x405082f (libc.musl-x86_64.so.1:strlen) redirected to 0x48a7b10 (strlen)
--8-- REDIR: 0x40505f1 (libc.musl-x86_64.so.1:strcpy) redirected to 0x48a7b72 (strcpy)
--8-- REDIR: 0x4050534 (libc.musl-x86_64.so.1:strchr) redirected to 0x48a787c (strchr)
--8-- REDIR: 0x4050935 (libc.musl-x86_64.so.1:strncmp) redirected to 0x48a7f6a (strncmp)
--8-- REDIR: 0x40509bd (libc.musl-x86_64.so.1:strnlen) redirected to 0x48a7aea (strnlen)
--8-- REDIR: 0x4050a80 (libc.musl-x86_64.so.1:strspn) redirected to 0x48ab61a (strspn)
--8-- REDIR: 0x4050601 (libc.musl-x86_64.so.1:strcspn) redirected to 0x48ab5ba (strcspn)
--8-- Reading syms from /usr/lib/libstdc++.so.6.0.29
--8-- object doesn't have a symbol table
--8-- REDIR: 0x40509f9 (libc.musl-x86_64.so.1:strrchr) redirected to 0x48a77e9 (strrchr)
--8-- Reading syms from /usr/lib/libgcc_s.so.1
--8-- object doesn't have a symbol table
--8-- REDIR: 0x4023529 (libc.musl-x86_64.so.1:malloc) redirected to 0x48a2650 (malloc)
--8-- REDIR: 0x40505d9 (libc.musl-x86_64.so.1:strcmp) redirected to 0x48a847c (strcmp)
==8==
==8== HEAP SUMMARY:
==8== in use at exit: 72,704 bytes in 1 blocks
==8== total heap usage: 1 allocs, 0 frees, 72,704 bytes allocated
==8==
==8== Searching for pointers to 1 not-freed blocks
==8== Checked 51,200 bytes
==8==
==8== 72,704 bytes in 1 blocks are still reachable in loss record 1 of 1
==8== at 0x48A26D5: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==8== by 0x4974557: ??? (in /usr/lib/libstdc++.so.6.0.29)
==8== by 0x4059482: ??? (in /lib/ld-musl-x86_64.so.1)
==8== by 0x409693F: ???
==8== by 0x4A7651F: ??? (in /usr/lib/libstdc++.so.6.0.29)
==8== by 0x1FFF000CFF: ???
==8== by 0xB907FED: ???
==8== by 0x5C1A2: ???
==8== by 0xCE9F: ???
==8== by 0x1CEAEF: ???
==8==
==8== LEAK SUMMARY:
==8== definitely lost: 0 bytes in 0 blocks
==8== indirectly lost: 0 bytes in 0 blocks
==8== possibly lost: 0 bytes in 0 blocks
==8== still reachable: 72,704 bytes in 1 blocks
==8== suppressed: 0 bytes in 0 blocks
==8==
==8== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
</code></pre>
<p>for easy reproduction, you could use a docker file like this :</p>
<pre><code>FROM alpine
RUN apk update && apk add libstdc++ g++ make linux-headers valgrind
WORKDIR /src
CMD ["make"]
</code></pre>
<p>with this makefile</p>
<pre><code>MAKEFLAGS += --no-print-directory
CC=g++
CFLAGS=-W -Wall -Wunused -Wshadow -Wpointer-arith -Wcast-qual -Wno-missing-braces -ansi -pedantic -std=c++20 -I/usr/local/include
LDFLAGS=-L /usr/lib/openssl/lib -L /usr/lib
EXEC_DEBUG=toto
DEBOBJDIR=./obj/debug
SRCDIR=.
SRC_FILES=$(wildcard $(SRCDIR)/*/*/*.cpp $(SRCDIR)/*/*.cpp $(SRCDIR)/*.cpp)
DEBOBJ= $(SRC_FILES:%.cpp=$(DEBOBJDIR)/%.o)
DEPS= $(DEBOBJ:.o=.d)
MEMORYCHECKER=valgrind
MEMORY_RESULT_FILE=valgrind-out.txt
VALGRIND_FLAGS=--error-exitcode=1 --leak-check=full --errors-for-leak-kinds=all --show-leak-kinds=all --verbose --sigill-diagnostics=no --log-file=$(MEMORY_RESULT_FILE)
VALGRIND_FULL_FLAGS=--track-origins=yes --keep-debuginfo=yes --read-inline-info=yes
.PHONY: all clear
all: $(EXEC_DEBUG) fullMemoryCheck
-include $(DEPS)
$(EXEC_DEBUG): $(DEBOBJ)
$(CC) -o $@ $^ $(LDFLAGS)
$(DEBOBJDIR)/%.o : %.cpp makefile
@mkdir -p $(dir $@)
$(CC) -o $@ -MP -MMD -c $< $(CFLAGS) -g
clean:
find $(DEBOBJDIR) -name "*.o" -type f -delete
find $(DEBOBJDIR) -name "*.d" -type f -delete
clear: clean
rm -rf $(EXEC) $(EXEC_DEBUG)
fullMemoryCheck: $(EXEC_DEBUG)
@export GLIBCXX_FORCE_NEW
$(MEMORYCHECKER) $(VALGRIND_FULL_FLAGS) $(VALGRIND_FLAGS) ./$(EXEC_DEBUG)
</code></pre>
<p>As @Paul Floyd mention it, there is an existing bug declare here : <a href="https://bugs.kde.org/show_bug.cgi?id=426751" rel="nofollow noreferrer">https://bugs.kde.org/show_bug.cgi?id=426751</a> but without known issue. So I had my exemple to help finding what is unsupported in alpine (lib musl libc).</p>
<p>PS : the problem come from iostream, because it disapear if I comment the include.</p>
<p><strong>OLD VERSION</strong>:</p>
<p>after lot of searches I can't find a way to see the stack strace for a "leak" (still reachable) in my code.
As I can read in the documentation I add some option to valgrind "--track-origins=yes --keep-debuginfo=yes --read-inline-info=yes" but it doesn't help me.</p>
<p>My compilation lines looks like this (with -g3) :</p>
<pre class="lang-none prettyprint-override"><code>g++ -o obj/debug/./src/file1.o -MP -MMD -c src/file1.cpp -W -Wall -Wunused -Wshadow -Wpointer-arith -Wcast-qual -Wno-missing-braces -ansi -pedantic -std=c++20 -I/usr/local/include -DRAPIDJSON_HAS_STDSTRING -g3
g++ -o obj/debug/./src/file2.o -MP -MMD -c src/file2.cpp -W -Wall -Wunused -Wshadow -Wpointer-arith -Wcast-qual -Wno-missing-braces -ansi -pedantic -std=c++20 -I/usr/local/include -DRAPIDJSON_HAS_STDSTRING -g3
g++ -o obj/debug/./src/file3.o -MP -MMD -c src/file3.cpp -W -Wall -Wunused -Wshadow -Wpointer-arith -Wcast-qual -Wno-missing-braces -ansi -pedantic -std=c++20 -I/usr/local/include -DRAPIDJSON_HAS_STDSTRING -g3
...
g++ -o obj/debug/./src/fileX.o -MP -MMD -c src/fileX.cpp -W -Wall -Wunused -Wshadow -Wpointer-arith -Wcast-qual -Wno-missing-braces -ansi -pedantic -std=c++20 -I/usr/local/include -DRAPIDJSON_HAS_STDSTRING -g3
g++ -o obj/debug/./src/main.o -MP -MMD -c src/main.cpp -W -Wall -Wunused -Wshadow -Wpointer-arith -Wcast-qual -Wno-missing-braces -ansi -pedantic -std=c++20 -I/usr/local/include -DRAPIDJSON_HAS_STDSTRING -g3
g++ -o botsd obj/debug/./src/file1.o obj/debug/./src/file2.o obj/debug/./src/file3.o obj/debug/./src/fileX.o obj/debug/./src/main.o -L /usr/lib/openssl/lib -L /usr/lib -llog4cplus -lpthread -lssl -lcrypto -lcurl
g++ -c -g3 -I. -I.. -std=c++20 -I/usr/include -I./cxxtest-4.4/ -DCXXTEST_RUNNING -DRAPIDJSON_HAS_STDSTRING -o output/OutputTrace.o ../src/cmdLine/OutputTrace.cpp
python3 cxxtest-4.4/bin/cxxtestgen -o output/testMemory.cpp --error-printer testFile1.h testFile2.h testFile3.h ... testFileX.h
g++ -c -g3 -I. -I.. -std=c++20 -I/usr/include -I./cxxtest-4.4/ -DCXXTEST_RUNNING -DRAPIDJSON_HAS_STDSTRING output/testMemory.cpp -o output/testMemory.o
g++ -Wall -g3 -I. -I.. output/testMemory.o ../obj/debug/src/file1.o ../obj/debug/src/file2.o ../obj/debug/src/file3.o ... ../obj/debug/src/fileX.o -L /usr/lib/openssl/lib -L /usr/lib -llog4cplus -lpthread -lssl -lcrypto -lcurl -o output/testMemory
</code></pre>
<p>Extract from my primary makefile :</p>
<pre><code>MAKEFLAGS += --no-print-directory
CC=g++
CPPCHECK=cppcheck
CFLAGS=-W -Wall -Wunused -Wshadow -Wpointer-arith -Wcast-qual -Wno-missing-braces -ansi -pedantic -std=c++20 -I/usr/local/include -DRAPIDJSON_HAS_STDSTRING
LDFLAGS=-L /usr/lib/openssl/lib -L /usr/lib -llog4cplus -lpthread -lssl -lcrypto -lcurl
EXEC_DEBUG=test
DEBOBJDIR=./obj/debug
SRCDIR=./src
TESTDIR=./tests
SRC=$(wildcard $(SRCDIR)/*/*/*.cpp $(SRCDIR)/*/*.cpp $(SRCDIR)/*.cpp)
DEBOBJ= $(SRC:%.cpp=$(DEBOBJDIR)/%.o)
DEPS= $(DEBOBJ:.o=.d)
.PHONY: all clean clear
all: $(EXEC_DEBUG) run-tests
-include $(DEPS)
$(EXEC_DEBUG): $(DEBOBJ)
$(CC) -o $@ $^ $(LDFLAGS)
$(DEBOBJDIR)/%.o : %.cpp makefile
@mkdir -p $(dir $@)
$(CC) -o $@ -MP -MMD -c $< $(CFLAGS) -g3
test-clean:
+@cd $(TESTDIR) && make clean
clean: test-clean
find $(DEBOBJDIR) -name "*.o" -type f -delete
find $(DEBOBJDIR) -name "*.d" -type f -delete
clear: clean
rm -rf $(EXEC_DEBUG)
run-tests: $(EXEC_DEBUG)
+@cd $(TESTDIR) && make
fullMemoryCheck: $(EXEC_DEBUG)
+@cd $(TESTDIR) && make fullMemoryCheck
</code></pre>
<p>And then I launch Valgrind like this (I think GLIBCXX_FORCE_NEW is useless but I try a lot of things :) )</p>
<pre class="lang-none prettyprint-override"><code>export GLIBCXX_FORCE_NEW
valgrind --track-origins=yes --keep-debuginfo=yes --read-inline-info=yes --error-exitcode=1 --leak-check=full --errors-for-leak-kinds=all --show-leak-kinds=all --verbose --sigill-diagnostics=no --log-file=valgrind-out.txt ./output/testMemory
</code></pre>
<p>see from my secondary (test) makefile :</p>
<pre><code>CXXC = g++ -Wall -g3 -I. -I..
CC = g++ -c -g3 -I. -I.. -std=c++20 -I/usr/include -I./cxxtest-4.4/ -DCXXTEST_RUNNING -DRAPIDJSON_HAS_STDSTRING
LDFLAGS=-L /usr/lib/openssl/lib -L /usr/lib -llog4cplus -lpthread -lssl -lcrypto -lcurl
TESTGEN=cxxtest-4.4/bin/cxxtestgen
MEMORYCHECKER=valgrind
MEMORY_RESULT_FILE=valgrind-out.txt
VALGRIND_FLAGS=--error-exitcode=1 --leak-check=full --errors-for-leak-kinds=all --show-leak-kinds=all --verbose --sigill-diagnostics=no --log-file=$(MEMORY_RESULT_FILE)
VALGRIND_FULL_FLAGS=--track-origins=yes --keep-debuginfo=yes --read-inline-info=yes
TARGETS=error_printer
VALGRIND_TARGET=testMemory
OUTDIR=output
OBJDIR=../obj/debug/src
TST_FILES=$(wildcard */*/*.h */*.h)
TSTFILES= $(filter-out $(wildcard cxxtest*/*/*), $(TST_FILES))
NOPERFFILES= $(filter-out $(wildcard */Perf*.h), $(TSTFILES))
NO_PERF_FILES= $(filter-out $(wildcard */*/Perf*.h), $(NOPERFFILES))
OBJ_FILES=$(wildcard $(OBJDIR)/*/*/*.o $(OBJDIR)/*/*.o)
ADDITIONNAL_SRC=../src/cmdLine/OutputTrace.cpp
EXCLUDE_OBJ=$(subst ../,../obj/debug/,$(ADDITIONNAL_SRC:%.cpp=%.o))
ADDITIONNAL_OBJ=$(OUTDIR)/$(addsuffix .o,$(basename $(notdir $(ADDITIONNAL_SRC))))
FINAL_OBJ=$(filter-out $(EXCLUDE_OBJ), $(OBJ_FILES))
.PHONY: all clean distclean fullMemoryCheck
all: run memoryCheck
clean:
rm -f $(OUTDIR)/*
distclean: clean
rm -f Makefile
memoryCheck: $(VALGRIND_TARGET)
@export GLIBCXX_FORCE_NEW
@if $(MEMORYCHECKER) $(VALGRIND_FLAGS) ./$(OUTDIR)/$(VALGRIND_TARGET); then \
echo " Memory is clear!"; \
else \
cat $(MEMORY_RESULT_FILE); \
exit "Memory problems found"; \
fi
fullMemoryCheck: $(VALGRIND_TARGET)
@export GLIBCXX_FORCE_NEW
$(MEMORYCHECKER) $(VALGRIND_FULL_FLAGS) $(VALGRIND_FLAGS) ./$(OUTDIR)/$(VALGRIND_TARGET)
run: $(TARGETS)
@./$(OUTDIR)/$(TARGETS)
$(ADDITIONNAL_OBJ): $(ADDITIONNAL_SRC)
@mkdir -p $(dir $@)
$(CC) -o $@ $<
$(TARGETS).cpp: $(TSTFILES)
python3 $(TESTGEN) -o $(OUTDIR)/$@ --error-printer $(TSTFILES)
$(TARGETS).o: $(TARGETS).cpp
$(CC) $(OUTDIR)/$(TARGETS).cpp -o $(OUTDIR)/$(TARGETS).o
$(TARGETS): $(ADDITIONNAL_OBJ) $(TARGETS).o
$(CXXC) $(OUTDIR)/$(TARGETS).o $(ADDITIONNAL_OBJ) $(FINAL_OBJ) $(LDFLAGS) -o $(OUTDIR)/$(TARGETS)
$(VALGRIND_TARGET).cpp: $(NO_PERF_FILES)
python3 $(TESTGEN) -o $(OUTDIR)/$@ --error-printer $(NO_PERF_FILES)
$(VALGRIND_TARGET).o: $(VALGRIND_TARGET).cpp
$(CC) $(OUTDIR)/$(VALGRIND_TARGET).cpp -o $(OUTDIR)/$(VALGRIND_TARGET).o
$(VALGRIND_TARGET): $(ADDITIONNAL_OBJ) $(VALGRIND_TARGET).o
$(CXXC) $(OUTDIR)/$(VALGRIND_TARGET).o $(ADDITIONNAL_OBJ) $(FINAL_OBJ) $(LDFLAGS) -o $(OUTDIR)/$(VALGRIND_TARGET)
</code></pre>
<p>I had to add --sigill-diagnostics=no to avoid an error with openSSL which use SIGKILL (cf <a href="https://bugzilla.redhat.com/show_bug.cgi?id=1495320" rel="nofollow noreferrer">https://bugzilla.redhat.com/show_bug.cgi?id=1495320</a>)</p>
<p>and the output is now just one "leak" :</p>
<pre class="lang-none prettyprint-override"><code>==255== Memcheck, a memory error detector
==255== Copyright (C) 2002-2022, and GNU GPL'd, by Julian Seward et al.
==255== Using Valgrind-3.19.0-8d3c8034b8-20220411 and LibVEX; rerun with -h for copyright info
==255== Command: ./output/testMemory
==255== Parent PID: 246
==255==
--255--
--255-- Valgrind options:
--255-- --track-origins=yes
--255-- --keep-debuginfo=yes
--255-- --read-inline-info=yes
--255-- --error-exitcode=1
--255-- --leak-check=full
--255-- --errors-for-leak-kinds=all
--255-- --show-leak-kinds=all
--255-- --verbose
--255-- --sigill-diagnostics=no
--255-- --log-file=valgrind-out.txt
--255-- Contents of /proc/version:
--255-- Linux version 5.10.16.3-microsoft-standard-WSL2 (oe-user@oe-host) (x86_64-msft-linux-gcc (GCC) 9.3.0, GNU ld (GNU Binutils) 2.34.0.20200220) #1 SMP Fri Apr 2 22:23:49 UTC 2021
--255--
--255-- Arch and hwcaps: AMD64, LittleEndian, amd64-cx16-lzcnt-rdtscp-sse3-ssse3-avx-avx2-bmi-f16c-rdrand-rdseed
--255-- Page sizes: currently 4096, max supported 4096
--255-- Valgrind library directory: /usr/libexec/valgrind
--255-- Reading syms from /src/tests/output/testMemory
--255-- Reading syms from /lib/ld-musl-x86_64.so.1
--255-- object doesn't have a symbol table
--255-- Reading syms from /usr/libexec/valgrind/memcheck-amd64-linux
--255-- object doesn't have a dynamic symbol table
--255-- Scheduler: using generic scheduler lock implementation.
--255-- Reading suppressions file: /usr/libexec/valgrind/default.supp
==255== embedded gdbserver: reading from /tmp/vgdb-pipe-from-vgdb-to-255-by-???-on-91ae10bb5054
==255== embedded gdbserver: writing to /tmp/vgdb-pipe-to-vgdb-from-255-by-???-on-91ae10bb5054
==255== embedded gdbserver: shared mem /tmp/vgdb-pipe-shared-mem-vgdb-255-by-???-on-91ae10bb5054
==255==
==255== TO CONTROL THIS PROCESS USING vgdb (which you probably
==255== don't want to do, unless you know exactly what you're doing,
==255== or are doing some strange experiment):
==255== /usr/libexec/valgrind/../../bin/vgdb --pid=255 ...command...
==255==
==255== TO DEBUG THIS PROCESS USING GDB: start GDB like this
==255== /path/to/gdb ./output/testMemory
==255== and then give GDB the following command
==255== target remote | /usr/libexec/valgrind/../../bin/vgdb --pid=255
==255== --pid is optional if only one valgrind process is running
==255==
--255-- Reading syms from /usr/libexec/valgrind/vgpreload_core-amd64-linux.so
--255-- object doesn't have a symbol table
--255-- Reading syms from /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so
--255-- object doesn't have a symbol table
--255-- REDIR: 0x405082f (libc.musl-x86_64.so.1:strlen) redirected to 0x48a7b10 (strlen)
--255-- REDIR: 0x40505f1 (libc.musl-x86_64.so.1:strcpy) redirected to 0x48a7b72 (strcpy)
--255-- REDIR: 0x4050534 (libc.musl-x86_64.so.1:strchr) redirected to 0x48a787c (strchr)
--255-- REDIR: 0x4050935 (libc.musl-x86_64.so.1:strncmp) redirected to 0x48a7f6a (strncmp)
--255-- REDIR: 0x4050a80 (libc.musl-x86_64.so.1:strspn) redirected to 0x48ab61a (strspn)
--255-- REDIR: 0x4050601 (libc.musl-x86_64.so.1:strcspn) redirected to 0x48ab5ba (strcspn)
--255-- REDIR: 0x40509bd (libc.musl-x86_64.so.1:strnlen) redirected to 0x48a7aea (strnlen)
--255-- Reading syms from /usr/lib/liblog4cplus-2.0.so.3.4.6
--255-- object doesn't have a symbol table
--255-- REDIR: 0x40509f9 (libc.musl-x86_64.so.1:strrchr) redirected to 0x48a77e9 (strrchr)
--255-- Reading syms from /usr/lib/openssl/lib/libcrypto.so.3
--255-- Reading syms from /usr/local/lib/librestclient-cpp.so.1.1.1
--255-- Reading syms from /usr/lib/libstdc++.so.6.0.29
--255-- object doesn't have a symbol table
--255-- Reading syms from /usr/lib/libgcc_s.so.1
--255-- object doesn't have a symbol table
--255-- Reading syms from /usr/local/lib/libcurl.so.4.8.0
--255-- Reading syms from /usr/lib/openssl/lib/libssl.so.3
--255-- REDIR: 0x4023529 (libc.musl-x86_64.so.1:malloc) redirected to 0x48a2650 (malloc)
--255-- REDIR: 0x4e5c68e (libstdc++.so.6:operator new(unsigned long)) redirected to 0x48a2de0 (operator new(unsigned long))
--255-- REDIR: 0x40505d9 (libc.musl-x86_64.so.1:strcmp) redirected to 0x48a847c (strcmp)
--255-- REDIR: 0x404ff8d (libc.musl-x86_64.so.1:memcmp) redirected to 0x48a9ff3 (memcmp)
--255-- REDIR: 0x4050544 (libc.musl-x86_64.so.1:strchrnul) redirected to 0x48aaf8d (strchrnul)
--255-- REDIR: 0x4e5ae18 (libstdc++.so.6:operator delete(void*, unsigned long)) redirected to 0x48a51f4 (operator delete(void*, unsigned long))
--255-- REDIR: 0x4e5c70e (libstdc++.so.6:operator new[](unsigned long)) redirected to 0x48a3dc4 (operator new[](unsigned long))
--255-- REDIR: 0x404fefe (libc.musl-x86_64.so.1:memchr) redirected to 0x48a8542 (memchr)
--255-- REDIR: 0x4e5ae2a (libstdc++.so.6:operator delete[](void*)) redirected to 0x48a5e80 (operator delete[](void*))
--255-- REDIR: 0x4023460 (libc.musl-x86_64.so.1:free) redirected to 0x48a4a8a (free)
--255-- REDIR: 0x402519f (libc.musl-x86_64.so.1:realloc) redirected to 0x48a6e29 (realloc)
--255-- REDIR: 0x40233a1 (libc.musl-x86_64.so.1:calloc) redirected to 0x48a6b5a (calloc)
--255-- REDIR: 0x4e5ae0f (libstdc++.so.6:operator delete(void*)) redirected to 0x48a4fac (operator delete(void*))
--255-- REDIR: 0x4050d40 (libc.musl-x86_64.so.1:strstr) redirected to 0x48ab4a4 (strstr)
--255-- REDIR: 0x4050972 (libc.musl-x86_64.so.1:strncpy) redirected to 0x48a7cae (strncpy)
--255-- memcheck GC: 1000 nodes, 315 survivors (31.5%)
--255-- memcheck GC: 1014 new table size (driftup)
==255==
==255== HEAP SUMMARY:
==255== in use at exit: 72,704 bytes in 1 blocks
==255== total heap usage: 9,136,810 allocs, 9,136,809 frees, 369,272,065 bytes allocated
==255==
==255== Searching for pointers to 1 not-freed blocks
==255== Checked 134,080 bytes
==255==
==255== 72,704 bytes in 1 blocks are still reachable in loss record 1 of 1
==255== at 0x48A26D5: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==255== by 0x4E59557: ??? (in /usr/lib/libstdc++.so.6.0.29)
==255== by 0x4059D8A: ??? (in /lib/ld-musl-x86_64.so.1)
==255== by 0x409693F: ???
==255== by 0x4F5B51F: ??? (in /usr/lib/libstdc++.so.6.0.29)
==255== by 0xB907FED: ???
==255== by 0x5C1A2: ???
==255== by 0xCE9F: ???
==255== by 0x1CEAEF: ??? (in /src/tests/output/testMemory)
==255==
==255== LEAK SUMMARY:
==255== definitely lost: 0 bytes in 0 blocks
==255== indirectly lost: 0 bytes in 0 blocks
==255== possibly lost: 0 bytes in 0 blocks
==255== still reachable: 72,704 bytes in 1 blocks
==255== suppressed: 0 bytes in 0 blocks
==255==
==255== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
</code></pre>
<p>I can add that I run this in a docker container based on alpine 3.16.2 (with valgrind, g++, etc...)</p>
<p>For people who knew it, it's a program ran with cxxtest (v4.4). But it shouldn't impact because all sources files are compiled like mine and are in my program folders. So valgrind should found symbols (there are part of lotOfFiles.h and lotOfFiles.cpp)</p>
<p>So my question is : what I can add to help valgrind finding symbols ? (obviously I don't want details from libstdc++, but just a clue in my code)</p>
| [
{
"answer_id": 74393766,
"author": "Paul Floyd",
"author_id": 6594576,
"author_profile": "https://Stackoverflow.com/users/6594576",
"pm_score": 1,
"selected": false,
"text": "--track-origins=yes"
},
{
"answer_id": 74416788,
"author": "zzDiego",
"author_id": 17457691,
"author_profile": "https://Stackoverflow.com/users/17457691",
"pm_score": 1,
"selected": true,
"text": "{\n default_iostream\n Memcheck:Leak\n match-leak-kinds: reachable\n fun:malloc\n obj:/usr/lib/libstdc++.so.6.0.29\n obj:/lib/ld-musl-x86_64.so.1\n obj:*\n obj:/usr/lib/libstdc++.so.6.0.29\n obj:*\n obj:*\n ...\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74390792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17457691/"
] |
74,390,817 | <p>I am trying to call an api base on scroll View current position but not sure how to I achieve that.</p>
<p>This is my code</p>
<pre><code> <ScrollView
ref={scrollViewRef}
scrollEventThrottle={0}
onScroll={({nativeEvent}) => {
console.log(
nativeEvent.contentSize.height -
nativeEvent.layoutMeasurement.height,
);
console.log(nativeEvent.contentOffset);
}}>
</code></pre>
<p>I tried to call the api inside onScroll but that didnt work well.</p>
| [
{
"answer_id": 74391291,
"author": "Yusuf Dimari",
"author_id": 15664914,
"author_profile": "https://Stackoverflow.com/users/15664914",
"pm_score": 1,
"selected": false,
"text": "useEffect(() => {\n Window.addEventListener(‘scroll’_.debounce(setScroll,1000));},[]);\n"
},
{
"answer_id": 74464799,
"author": "Abdullah Al Mamun",
"author_id": 7588807,
"author_profile": "https://Stackoverflow.com/users/7588807",
"pm_score": 0,
"selected": false,
"text": "const [apiData, setApiData] = useState();\n\nonScroll={({nativeEvent}) => {\n if (!apiData) {\n if (\n nativeEvent.contentSize.height -\n nativeEvent.layoutMeasurement.height -\n nativeEvent.contentOffset.y <\n 250\n ) {\n getApiDataHandler();\n }\n }\n }}"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74390817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7588807/"
] |
74,390,879 | <p>I try to make a code more compact by coding a helper method, because the code is very repetitive.</p>
<p>The code consists of:</p>
<ol>
<li>call a command (remote ssh, or local command, this part is not interesting for my question)</li>
<li>check if it was a success</li>
<li>if not, stop here and return the return code to the calling method (i.e. <code>return cr;</code>)</li>
<li>if success, continue with another command</li>
</ol>
<p>I tried to create a helper method that do all that. If the command execution is a failure, it will return an <code>Optional<Integer></code> of the return code. If it works as expected, it returns a <code>Optional.empty()</code>.</p>
<p>My question is how to do something like that:</p>
<pre><code>public void topMethod()
{
int cr = execCmds();
... do stuff with cr ...
}
private int execCmds()
{
executeCmd("my command").ifPresent(cr -> return cr);
executeCmd("my next command").ifPresent(cr -> return cr);
....
return 0;
}
</code></pre>
<p>As you can see, I want to stop the flow if the return code is meaningful. If not it must continue. Is there a way to do that? (Something concise.)</p>
<p>For information, the <code>return cr</code> is invalid in the <code>ifPresent</code> lambda method.</p>
| [
{
"answer_id": 74391291,
"author": "Yusuf Dimari",
"author_id": 15664914,
"author_profile": "https://Stackoverflow.com/users/15664914",
"pm_score": 1,
"selected": false,
"text": "useEffect(() => {\n Window.addEventListener(‘scroll’_.debounce(setScroll,1000));},[]);\n"
},
{
"answer_id": 74464799,
"author": "Abdullah Al Mamun",
"author_id": 7588807,
"author_profile": "https://Stackoverflow.com/users/7588807",
"pm_score": 0,
"selected": false,
"text": "const [apiData, setApiData] = useState();\n\nonScroll={({nativeEvent}) => {\n if (!apiData) {\n if (\n nativeEvent.contentSize.height -\n nativeEvent.layoutMeasurement.height -\n nativeEvent.contentOffset.y <\n 250\n ) {\n getApiDataHandler();\n }\n }\n }}"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74390879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/937028/"
] |
74,390,909 | <p>I am Trying to serialise an ojekt to json but it givs me alway an emty json obiject bak I am usning the default build in serialiser.</p>
<p>My Object to seriaclise:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json.Serialization;
[Serializable]
public class Order
{
[JsonPropertyName("contractornumber")]
public readonly uint contractorNumber;
[JsonPropertyName("contractorname")]
public readonly string contractorName;
[JsonPropertyName("durationofcontract")]
public readonly TimeSpan durationOfContract;
[JsonPropertyName("ordernumber")]
public readonly uint orderNumber;
[JsonPropertyName("iban")]
public readonly string IBAN;
public Order( uint contractorNumber, string contractorName,TimeSpan durationOfContract, uint orderNumber,string IBAN)
{
this.contractorNumber = contractorNumber;
this.contractorName = contractorName;
//this.durationOfContract = durationOfContract;
this.orderNumber = orderNumber;
this.IBAN = IBAN;
}
public Order() { }
}
</code></pre>
<p>And I try to serialise it So:</p>
<pre><code>var order = new Order(89745, "F", DateTime.Now.TimeOfDay, 84537, "FU");
var k = JsonSerializer.Serialize(order);
Console.WriteLine(k);
</code></pre>
<p>And It gives me an output : "{}"</p>
<p>I am using .net 6 C# on winodws 10.</p>
| [
{
"answer_id": 74391469,
"author": "n-azad",
"author_id": 5997281,
"author_profile": "https://Stackoverflow.com/users/5997281",
"pm_score": 0,
"selected": false,
"text": "var order = new Order(89745, \"F\", DateTime.Now.TimeOfDay, 84537, \"FU\");\nvar options = new JsonSerializerOptions { IncludeFields = true };\nvar k = JsonSerializer.Serialize<Order>(order, options);\n"
},
{
"answer_id": 74391578,
"author": "Poul Bak",
"author_id": 5741643,
"author_profile": "https://Stackoverflow.com/users/5741643",
"pm_score": 2,
"selected": false,
"text": "field"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74390909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12343364/"
] |
74,390,953 | <p>Most time I use a jQuery event handler to do CSS styling. And this is the first time I try to accomplish this by using the HTML event attribute. Here's my code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('.navBtn').on('click', function() {
var length = $(this).closest('.videoList').find('.slider').length;
alert(`length A = ${length}`);
});
function btnClick() {
var length = $(this).closest('.videoList').find('.slider').length;
alert(`length B = ${length}`);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="videoList">
<div class="navBtn" onclick="btnClick()">Button</div>
<div class="slider">
<ul>
<li>items</li>
</ul>
</div>
</section></code></pre>
</div>
</div>
The result of length A is 1 and length B is 0.
I think it's probably that I mixed use jQuery with other stuff. But I want to know more details. Please explain to me or show me the information. Thanks!</p>
| [
{
"answer_id": 74391044,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 2,
"selected": true,
"text": "this"
},
{
"answer_id": 74391090,
"author": "Michael M.",
"author_id": 13376511,
"author_profile": "https://Stackoverflow.com/users/13376511",
"pm_score": 0,
"selected": false,
"text": "onclick="
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74390953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4416562/"
] |
74,390,997 | <p>I need to get only the latest input from my text widget, and then append that character to a list.
I am using
<code>Text.get(1.0,'end-1c')</code>
, and it does not work because the loop constantly gets all the input, instead of only getting the latest input when there is a new latest input.</p>
<pre><code>def main_screen():
start_time=time.time()
tk=Tk()
tk.title('Typing Test')
tk.geometry('800x500')
main_title=Label(tk,text='1 Minute Test',font=('Times New Roman',36))
main_title.pack(pady=5)
directions=Label(tk,text='Start Typing',font=('Times New Roman',14))
directions.pack()
base_text=Label(tk,text=randomizer(),bg='#E0E0EE',font=('Arial',14),wraplength=700,justify=LEFT)
base_text.pack(pady=10)
text_area=Text(tk,font=('Arial',14),width=63,height=7,wrap='word')
text_area.pack()
tk.update()
#WPM Calculation
target_text=randomizer()
typed_text=[]
wpm=0
errors=0
while True:
tk.update()
time_elapsed=max(time.time()-start_time,1)
wpm=round((len(typed_text)/60)/5)
if time_elapsed>=60:
break
#Problem Section
key=text_area.get(1.0,'end-1c')
typed_text.append(key)
for x in typed_text:
if x != target_text:
errors += 1
</code></pre>
<p>Alternatively, I tried using a variable in place of the 1.0 in .get, that would increase by one with each iteration of the loop. Next, I tried a try/except command, and put the #Problem Section into a function. I tried calling that function by binding the text area to</p>
<pre><code>'<Key>'
'<KeyPress>'
'<KeyRelease>'
</code></pre>
<p>None of these attempts work. I used a print statement to see what those variables are with each iteration of the loop, and using the first method, it just keeps making a longer and longer string that repeats constantly, instead of updating with each new character. Trying the other ways I just got nothing, no output, but no error either. I am completely stuck, and don't know what else to try.</p>
| [
{
"answer_id": 74391208,
"author": "DonPre",
"author_id": 7022759,
"author_profile": "https://Stackoverflow.com/users/7022759",
"pm_score": 2,
"selected": true,
"text": "text_area"
},
{
"answer_id": 74392145,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 0,
"selected": false,
"text": "import tkinter as tk\n\ndef get_new_text():\n data = text.get(\"last\", \"end-1c\")\n print(f\"new data: >>>{data}<<<\")\n text.mark_set(\"last\", \"end-1c\")\n root.after(5000, get_new_text)\n\nroot = tk.Tk()\ntext = tk.Text(root, wrap=\"word\")\ntext.pack(fill=\"both\", expand=True)\ntext.mark_set(\"last\", \"1.0\")\ntext.mark_gravity(\"last\", \"left\")\n\nroot.after(5000, get_new_text)\n\nroot.mainloop()\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74390997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20170478/"
] |
74,391,012 | <p>I have to implement a relatively simple communication protocol on top of RS-232.
It's an ASCII based text protocol with a couple of frame types.</p>
<p>Each frame looks something like this:</p>
<pre><code> * ___________________________________
* | | | | |
* | SOH | Data | CRC-16 | EOT |
* |_____|_________|_________|________|
* 1B nBytes 2B 1B
</code></pre>
<ol>
<li>Start Of Header (1 Byte)</li>
<li>Data (n-Bytes)</li>
<li>CRC-16 (2 Bytes)</li>
<li>EOT (End Of Transmission)</li>
</ol>
<p>Each data-field needs to be separated by semicolon ";":
for example, for HEADER type data (contains code,ver,time,date,src,id1,id2 values):</p>
<p>{code};{ver};{time};{date};{src};{id1};{id2}</p>
<p>what is the most elegant way of implementing this in C is my question?</p>
<p>I have tried defining multiple structs for each type of frame, for example:</p>
<pre><code>
typedef struct {
uint8_t soh;
char code;
char ver;
Time_t time;
Date_t date;
char src; // Unsigned char
char id1[20]; // STRING_20
char id2[20]; // STRING_20
char crlf;
uint16_t crc;
uint8_t eot;
} stdHeader_t;
</code></pre>
<p>I have declared a global buffer:</p>
<pre><code>uint8_t DATA_BUFF[BUFF_SIZE];
</code></pre>
<p>I then have a function sendHeader() in which I want to use RS-232 send function to send everything byte by byte by casting the dataBuffer to header struct and filling out the struct:</p>
<pre><code>static enum_status sendHeader(handle_t *handle)
{
uint16_t len;
enum_RETURN_VALUE rs232_err = OK;
enum_status err = STATUS_OK;
stdHeader_t *header = (stdHeader_t *)DATA_BUFF;
memset(DATA_BUFF, 0, size);
header ->soh= SOH,
header ->code= HEADER,
header ->ver= 10, // TODO
header ->time= handle->time,
header ->date= handle->date,
header ->src= handle->config->source,
memset(header ->id1,handle->config->id1, strlen(handle->config->id1));
memset(header ->id2,handle->config->id2, strlen(handle->config->id1));
header ->crlf = '\r\n',
header ->crc = calcCRC();
header ->eot = EOT;
len = sizeof(stdHeader_t );
do
{
for (uint16_t i = 0; i < len; i++)
{
rs232_err= rs232_tx_send(DATA_BUFF[i], 1); // Send one byte
if (rs232_err!= OK)
{
err = STATUS_ERR;
break;
}
}
// Break do-while loop if there is an error
if (err == STATUS_ERR)
{
break;
}
} while (conditions);
return err;
}
</code></pre>
<p>My problem is that I do not know how to approach the problem of handling ascii text based protocol,
the above principle would work very well for byte based protocols.</p>
<p>Also, I do not know how to implement semicolon ";" seperation of data in the above snippet, as everything is sent byte by byte, I would need aditional logic to know when it is needed to send ";" and with current implementation, that would not look very good.</p>
<p>For fields id1 and id2, I am receiveing string values as a part of handle->config, they can be of any lenght, but max is 20. Because of that, with current implementation, I would be sending more than needed in case actual lenght is less than 20, but I cannot use pointers to char inside the struct, because in that case, only the pointer value would get sent.</p>
<p>So to sumarize, the main question is:</p>
<p>How to implement the above described text based protocol for rs-232 in a nice and proper way?</p>
| [
{
"answer_id": 74391319,
"author": "Lundin",
"author_id": 584518,
"author_profile": "https://Stackoverflow.com/users/584518",
"pm_score": 2,
"selected": false,
"text": "uint8_t"
},
{
"answer_id": 74393363,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 2,
"selected": false,
"text": "char"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20469410/"
] |
74,391,013 | <p>I am pulling data from a table that changes often using Python - and the method I am using is not ideal. What I would like to have is a method to pull all strings that contain only one letter and leave out anything that is 2 or more.</p>
<p>An example of data I might get:</p>
<pre><code>115
19A6
HYS8
568
</code></pre>
<p>In this example, I would like to pull 115, 19A6, and 568.</p>
<p>Currently I am using the <code>isdigit()</code> method to determine if it is a digit and this filters out all numbers with one letter, which works for some purposes, but is less than ideal.</p>
| [
{
"answer_id": 74391319,
"author": "Lundin",
"author_id": 584518,
"author_profile": "https://Stackoverflow.com/users/584518",
"pm_score": 2,
"selected": false,
"text": "uint8_t"
},
{
"answer_id": 74393363,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 2,
"selected": false,
"text": "char"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20469665/"
] |
74,391,025 | <p>I have an array called responseData, it serves for me to show the available card options on the screen</p>
<pre><code>public responseData = [
{
id: 1399,
pessoa_id: 75898,
created_at: '2022-11-08T16:59:59.000000Z',
holder: 'LEONARDO ',
validade: '2029-05-01',
},
{
id: 13932,
pessoa_id: 75898,
created_at: '2022-11-08T16:59:59.000000Z',
holder: 'LEONARDO L',
validade: '2029-05-01',
},
{
id: 139429,
pessoa_id: 75898,
created_at: '2022-11-08T16:59:59.000000Z',
holder: 'LEONARDO SILVA DE L',
validade: '2029-05-01',
},
];
</code></pre>
<p>In this case the user will click on a card, when he clicks I put the object of the card he clicked on in another variable called</p>
<pre><code> this.cardDelete = card;
</code></pre>
<p>So it has the option to delete this card, I would like to know a way that I could map the id of the <code>cardDelete</code> and set to null the responseData with the corresponding id</p>
<p>Here's an example I did on stackblitz</p>
<p>I put some instructions in the html</p>
<p><a href="https://stackblitz.com/edit/angular-wzxnpe?file=src/app/app.component.html" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-wzxnpe?file=src/app/app.component.html</a></p>
| [
{
"answer_id": 74391103,
"author": "Luca Angrisani",
"author_id": 13240452,
"author_profile": "https://Stackoverflow.com/users/13240452",
"pm_score": 3,
"selected": true,
"text": " this.responseData = this.responseData.filter(\n (card) => card.id != this.cardDelete.id\n );\n"
},
{
"answer_id": 74391236,
"author": "Francesco Scassillo",
"author_id": 10021963,
"author_profile": "https://Stackoverflow.com/users/10021963",
"pm_score": 0,
"selected": false,
"text": "this.responseData.map((data) => {\n if (data.id == this.cardDelete.id) return null;\n return data;\n});\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19574035/"
] |
74,391,026 | <p>How do you convert a float32 pointer <code>*float32</code> to a float64 pointer <code>*float64</code>.</p>
<pre class="lang-golang prettyprint-override"><code>package main
import "fmt"
func main() {
var value *float32
v := float64(*value)
vp := &v
fmt.Println(vp)
}
</code></pre>
<p>The following code returns</p>
<blockquote>
<p>runtime error: invalid memory address or nil pointer dereference</p>
</blockquote>
| [
{
"answer_id": 74391103,
"author": "Luca Angrisani",
"author_id": 13240452,
"author_profile": "https://Stackoverflow.com/users/13240452",
"pm_score": 3,
"selected": true,
"text": " this.responseData = this.responseData.filter(\n (card) => card.id != this.cardDelete.id\n );\n"
},
{
"answer_id": 74391236,
"author": "Francesco Scassillo",
"author_id": 10021963,
"author_profile": "https://Stackoverflow.com/users/10021963",
"pm_score": 0,
"selected": false,
"text": "this.responseData.map((data) => {\n if (data.id == this.cardDelete.id) return null;\n return data;\n});\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236687/"
] |
74,391,030 | <p>I'm decoding a base64 image with the following code:</p>
<pre class="lang-py prettyprint-override"><code>def string_to_image(base64_string):
decoded = base64.b64decode(base64_string)
np_data = np.frombuffer(decoded, np.uint8)
img = cv2.imdecode(np_data, cv2.IMREAD_UNCHANGED)
return img
</code></pre>
<p>The goal is to receive an image from the request body, decode it, resize it with tensorflow, predict it with a model, and return a response saying what is that image:</p>
<pre class="lang-py prettyprint-override"><code>image_base64 = request.json['image']
decoded_image = string_to_image(image_base64)
image_resized = tf.image.resize(decoded_image, (256, 256))
model = load_model('src/models/mymodel.h5')
result = model.predict(np.expand_dims(image_resized/255, 0))
</code></pre>
<p>However, I'm getting the error <code>ValueError: Input 0 of layer "sequential_2" is incompatible with the layer: expected shape=(None, 256, 256, 3), found shape=(None, 256, 256, 4)</code>.</p>
<p>I don't know how to change the Shape value from '4' to '3'.</p>
<p>I tried the following:</p>
<pre class="lang-py prettyprint-override"><code>image_resized = tf.image.resize(decoded_image, (256, 256, 3))
</code></pre>
<p>But I get <code>'size' must be a 1-D Tensor of 2 elements: new_height, new_width</code>.</p>
<p>I also tried:</p>
<pre class="lang-py prettyprint-override"><code>image_resized = cv2.resize(decoded_image, (256,256,3))
</code></pre>
<p>But I get <code>OpenCV(4.6.0) :-1: error: (-5:Bad argument) in function 'resize'</code></p>
<p><code>Overload resolution failed:</code></p>
<p><code>- Can't parse 'dsize'. Expected sequence length 2, got 3</code></p>
<p><code>- Can't parse 'dsize'. Expected sequence length 2, got 3</code></p>
<p>Please help :(</p>
| [
{
"answer_id": 74391120,
"author": "AndreaYolo",
"author_id": 15982708,
"author_profile": "https://Stackoverflow.com/users/15982708",
"pm_score": 2,
"selected": false,
"text": "tf.squeeze"
},
{
"answer_id": 74413473,
"author": "Samuel A. Souza",
"author_id": 16524788,
"author_profile": "https://Stackoverflow.com/users/16524788",
"pm_score": 1,
"selected": true,
"text": "decoded_image = string_to_image(image_base64)\ndecoded_image = decoded_image[:,:,:3]\nimage_resized = tf.image.resize(decoded_image, (256, 256))\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16524788/"
] |
74,391,038 | <pre><code>string small = "12";
string big = "123456789";
</code></pre>
<p><strong>I need to get exactly 8 characters (addition and removal respectively)</strong><br />
The result be like this:</p>
<pre><code>small = "12 ";
big = "12345678";
</code></pre>
| [
{
"answer_id": 74391091,
"author": "Tim Schmelter",
"author_id": 284240,
"author_profile": "https://Stackoverflow.com/users/284240",
"pm_score": 3,
"selected": true,
"text": "String.PadRight"
},
{
"answer_id": 74391501,
"author": "Dmitry Bychenko",
"author_id": 2319407,
"author_profile": "https://Stackoverflow.com/users/2319407",
"pm_score": 1,
"selected": false,
"text": "8"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19401967/"
] |
74,391,073 | <p>I want to be able to write a size for a input and after that enter each number seperated by space which is less or equal than the size.</p>
<p>Like this:</p>
<p>First input (length): 3</p>
<p>inputs: 1 2 3</p>
<p>This should also be converted as an integer and stored in a list</p>
<p>I have tried this:</p>
<pre><code>import sys
inputs = sys.stdin.readline()
print(len(inputs))
mynumbers = inputs.strip().split(' ')
newlist = [int(x) for x in mynumbers]
print(newlist)
#print(input.rstrip(''))
</code></pre>
| [
{
"answer_id": 74391091,
"author": "Tim Schmelter",
"author_id": 284240,
"author_profile": "https://Stackoverflow.com/users/284240",
"pm_score": 3,
"selected": true,
"text": "String.PadRight"
},
{
"answer_id": 74391501,
"author": "Dmitry Bychenko",
"author_id": 2319407,
"author_profile": "https://Stackoverflow.com/users/2319407",
"pm_score": 1,
"selected": false,
"text": "8"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1020623/"
] |
74,391,089 | <p>I have a filter macro that will filter a table for items and delete rows with that item. This is done by looping through an array which referenced a finite range on reference worksheet.</p>
<p>I am trying to change this array to be dynamic so that I can add or remove items to be deleted without having to open the code.</p>
<p>Before:</p>
<pre><code> Dim ArrCategory As Variant
ArrCategory = Worksheets("Sheet1").Range("B8:B12")
For i = 2 To LastRowA
For Each item In ArrCategory
If Range("E" & i).Value = item Then
lo1710.Range.autofilter Field:=5, Criteria1:=item
Application.DisplayAlerts = False
lo1710.DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
lo1710.autofilter.ShowAllData
Else
End If
Next item
Next i
</code></pre>
<p>After:</p>
<pre><code> Dim ArrCategory As Variant
ArrCategory = Worksheets("Sheet1").Range("B8:B" & Cells(Rows.Count, "B").End(xlUp).row)
For i = 2 To LastRowA
For Each item In ArrCategory
If Range("E" & i).Value = item Then
lo1710.Range.autofilter Field:=5, Criteria1:=item
Application.DisplayAlerts = False
lo1710.DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
lo1710.autofilter.ShowAllData
Else
End If
Next item
Next i
</code></pre>
<p>After making this change I started getting the "No cells were found" error. When I look in the locals window to see what is in that array, I see the values that are supposed to be in there, but then also hundreds of "empties".</p>
<p><a href="https://i.stack.imgur.com/VROh7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VROh7.jpg" alt="enter image description here" /></a></p>
<p>The code does work to eliminate the rows containing the items in the array.</p>
| [
{
"answer_id": 74391202,
"author": "BigBen",
"author_id": 9245853,
"author_profile": "https://Stackoverflow.com/users/9245853",
"pm_score": 2,
"selected": false,
"text": "ActiveSheet"
},
{
"answer_id": 74396348,
"author": "VBasic2008",
"author_id": 9814069,
"author_profile": "https://Stackoverflow.com/users/9814069",
"pm_score": 0,
"selected": false,
"text": "Function SetNonBlankColumn( _\n FirstCell As Range) _\nAs Range\n Dim rg As Range\n With FirstCell.Cells(1)\n Dim lCell As Range\n Set lCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _\n .Find(\"*\", , xlValues, , , xlPrevious)\n If lCell Is Nothing Then Exit Function\n Set rg = .Resize(lCell.Row - .Row + 1)\n End With\n Set SetNonBlankColumn = rg\nEnd Function\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12351932/"
] |
74,391,139 | <p>I want to check if the subdomain <code>demo</code> exists in my URL.</p>
<p>So if my URL is either <code>https://demo.stackoverflow.com/</code> or <code>https://demo.stacks.com/</code> or <code>https://demo.hello.com/</code>, the function should return true.</p>
<p>If the URL is just <code>https://stackoverflow.com/</code>, without the word <code>demo</code>, the function should return false.</p>
<p>So how can I do that?</p>
<p><strong>Current Code</strong></p>
<pre class="lang-html prettyprint-override"><code><script>
if (window.location.hostname === 'https://demo.stackoverflow.com/') {
document.write('<script src="./script.min.js"></' + 'script>');
}
</script>
</code></pre>
| [
{
"answer_id": 74391202,
"author": "BigBen",
"author_id": 9245853,
"author_profile": "https://Stackoverflow.com/users/9245853",
"pm_score": 2,
"selected": false,
"text": "ActiveSheet"
},
{
"answer_id": 74396348,
"author": "VBasic2008",
"author_id": 9814069,
"author_profile": "https://Stackoverflow.com/users/9814069",
"pm_score": 0,
"selected": false,
"text": "Function SetNonBlankColumn( _\n FirstCell As Range) _\nAs Range\n Dim rg As Range\n With FirstCell.Cells(1)\n Dim lCell As Range\n Set lCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _\n .Find(\"*\", , xlValues, , , xlPrevious)\n If lCell Is Nothing Then Exit Function\n Set rg = .Resize(lCell.Row - .Row + 1)\n End With\n Set SetNonBlankColumn = rg\nEnd Function\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8305219/"
] |
74,391,144 | <p>I need to read data from the database, send them to <code>Kafka</code>, and then delete those data (which were successfully sent) from the database. I would think to do it straitforward:</p>
<pre><code>public void syncData() {
List<T> data = repository.findAll();
data.forEach(value -> kafkaTemplate.send(topicName, value));
repository.deleteAll(data);
}
</code></pre>
<p>But I have never worked with Kafka before and I have a confusion with <code>kafkaTemplate.send</code> operation. As the method returns <code>ListenableFuture</code>that means that the iteration <code>data.forEach</code> might be finished before all the messages are really sent to a broker. Thus, I might delete the data before they are really sent. What if, for some reason, some messages are not sent. Say I have 10 data, and starting from 7th the broker gets down.</p>
<ul>
<li>Will <code>Kafka</code> throw an exception if a message is not sent?</li>
<li>Should I introduce an extra logic to ensure that all messages are sent before going to the next stage of deleting the data?</li>
</ul>
<hr />
<p>P.S. I use <code>Kafka</code> with <code>Spring-boot</code></p>
| [
{
"answer_id": 74391202,
"author": "BigBen",
"author_id": 9245853,
"author_profile": "https://Stackoverflow.com/users/9245853",
"pm_score": 2,
"selected": false,
"text": "ActiveSheet"
},
{
"answer_id": 74396348,
"author": "VBasic2008",
"author_id": 9814069,
"author_profile": "https://Stackoverflow.com/users/9814069",
"pm_score": 0,
"selected": false,
"text": "Function SetNonBlankColumn( _\n FirstCell As Range) _\nAs Range\n Dim rg As Range\n With FirstCell.Cells(1)\n Dim lCell As Range\n Set lCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _\n .Find(\"*\", , xlValues, , , xlPrevious)\n If lCell Is Nothing Then Exit Function\n Set rg = .Resize(lCell.Row - .Row + 1)\n End With\n Set SetNonBlankColumn = rg\nEnd Function\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4003272/"
] |
74,391,145 | <p>I have several widgets that I'd like to toggle on click/blur/submit.</p>
<p>Let's take a simple example with an input (Vue 2 style)</p>
<p><strong>Input.vue</strong></p>
<pre class="lang-html prettyprint-override"><code><template>
<input
ref="input"
:value="value"
@input="input"
@blur="input"
@keyup.escape="close"
@keyup.enter="input"
/>
</template>
<script>
export default {
props: ['value'],
methods: {
input() {
this.$emit("input", this.$refs.text.value);
this.close();
},
close() {
this.$emit("close");
},
}
}
</script>
</code></pre>
<p><strong>ToggleWrapper.vue</strong></p>
<pre class="lang-html prettyprint-override"><code><template>
<div @click="open = true">
<div v-if="open">
<slot @close="open = false"></slot> <!-- Attempt to intercept the close event -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
open: false,
}
},
}
</script>
</code></pre>
<p>Final usage:</p>
<pre class="lang-html prettyprint-override"><code><ToggleWrapper>
<Input v-model="myText" @submit="updateMyText" />
</ToggleWrapper>
</code></pre>
<p>So when I click on <code>ToggleWrapper</code> it appears, but if I close it, it doesn't disappear because it's not getting the close event.</p>
<p>Should I use scoped events ?<br />
How can I intercept the close event by adding the less possible markup on the final usage ?</p>
| [
{
"answer_id": 74391202,
"author": "BigBen",
"author_id": 9245853,
"author_profile": "https://Stackoverflow.com/users/9245853",
"pm_score": 2,
"selected": false,
"text": "ActiveSheet"
},
{
"answer_id": 74396348,
"author": "VBasic2008",
"author_id": 9814069,
"author_profile": "https://Stackoverflow.com/users/9814069",
"pm_score": 0,
"selected": false,
"text": "Function SetNonBlankColumn( _\n FirstCell As Range) _\nAs Range\n Dim rg As Range\n With FirstCell.Cells(1)\n Dim lCell As Range\n Set lCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _\n .Find(\"*\", , xlValues, , , xlPrevious)\n If lCell Is Nothing Then Exit Function\n Set rg = .Resize(lCell.Row - .Row + 1)\n End With\n Set SetNonBlankColumn = rg\nEnd Function\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305189/"
] |
74,391,203 | <p>I'm creating a SPM project and I need to check if the data I get from an API is correct.
How can I print out this data?</p>
<p>I tried to create a view inside the SPM and adding it to an App project and it works, but it doesn't exist an easier alternative?</p>
<p>Console doesn't show anything, no print no logs...</p>
<p><a href="https://i.stack.imgur.com/LLIzH.png" rel="nofollow noreferrer">image with code</a></p>
| [
{
"answer_id": 74391202,
"author": "BigBen",
"author_id": 9245853,
"author_profile": "https://Stackoverflow.com/users/9245853",
"pm_score": 2,
"selected": false,
"text": "ActiveSheet"
},
{
"answer_id": 74396348,
"author": "VBasic2008",
"author_id": 9814069,
"author_profile": "https://Stackoverflow.com/users/9814069",
"pm_score": 0,
"selected": false,
"text": "Function SetNonBlankColumn( _\n FirstCell As Range) _\nAs Range\n Dim rg As Range\n With FirstCell.Cells(1)\n Dim lCell As Range\n Set lCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _\n .Find(\"*\", , xlValues, , , xlPrevious)\n If lCell Is Nothing Then Exit Function\n Set rg = .Resize(lCell.Row - .Row + 1)\n End With\n Set SetNonBlankColumn = rg\nEnd Function\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20469775/"
] |
74,391,269 | <p>Language used : js with react</p>
<p>I need to count how much "theme" I have but not if he's already count/exist</p>
<p>data example :</p>
<pre><code> movies = [{"id" : 1, "name": "Ps: i love you", "theme": { "id": 1, "name": "love"} },
{"id" : 2, "name": "Holiday", "theme": { "id": 1, "name": "love"} },
{"id" :3, "name": "Scary Movie", "theme": { "id": 2, "name": "horror"} }]
</code></pre>
<p>Here, i have two theme : love and horror.</p>
<p>I know how to get the number of theme but i don't want to count the duplicate, so here i only want to get "2" and no "3" .</p>
<p>what i am actually trying :</p>
<pre><code>const movieTheme= movies.filter((item) => item.theme.name);
const movieThemeCount = movieTheme.length;
console.log(movieThemeCount ); // of course i'm here getting 3 instead of 2
</code></pre>
| [
{
"answer_id": 74391407,
"author": "Besufkad Menji",
"author_id": 10239185,
"author_profile": "https://Stackoverflow.com/users/10239185",
"pm_score": 0,
"selected": false,
"text": "movies = [{\"id\": 1, \"name\": \"Ps: i love you\", \"theme\": {\"id\": 1, \"name\": \"love\"}},\n{\"id\": 2, \"name\": \"Holiday\", \"theme\": {\"id\": 1, \"name\": \"love\"}},\n{\"id\": 3, \"name\": \"Scary Movie\", \"theme\": {\"id\": 2, \"name\": \"horror\"}}]\n\n\nconst movieTheme = []\n\nmovies.forEach((item) => {\n let exists = false\n for (let i = 0; i < movieTheme.length; i++) {\n if (movieTheme[i] === item.theme.name) {\n exists = true;\n }\n}\nif (exists) {\n return false\n} else {\n movieTheme.push(item.theme.name)\n return item.theme.name;\n\n}\n});\nconst movieThemeCount = movieTheme.length;\n\nconsole.log(movieTheme); \nconsole.log(movieThemeCount); \n"
},
{
"answer_id": 74391424,
"author": "RenokK",
"author_id": 2377357,
"author_profile": "https://Stackoverflow.com/users/2377357",
"pm_score": 3,
"selected": true,
"text": "map"
},
{
"answer_id": 74391535,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 0,
"selected": false,
"text": "handleCountTheme"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19389219/"
] |
74,391,333 | <p>I would like this ForEach to return h3 to me only once, instead of three which is the length of the array. How can I do? Thanks to those who will answer</p>
<pre><code> @foreach (var winelistObj in Model.winetype.Where(s => s.name == Request.Query["wine"]))
{
<h3 class="text-uppercase font-logo text-regular letter-spacing-200">@winelistObj.name</h3>
}
</code></pre>
| [
{
"answer_id": 74391407,
"author": "Besufkad Menji",
"author_id": 10239185,
"author_profile": "https://Stackoverflow.com/users/10239185",
"pm_score": 0,
"selected": false,
"text": "movies = [{\"id\": 1, \"name\": \"Ps: i love you\", \"theme\": {\"id\": 1, \"name\": \"love\"}},\n{\"id\": 2, \"name\": \"Holiday\", \"theme\": {\"id\": 1, \"name\": \"love\"}},\n{\"id\": 3, \"name\": \"Scary Movie\", \"theme\": {\"id\": 2, \"name\": \"horror\"}}]\n\n\nconst movieTheme = []\n\nmovies.forEach((item) => {\n let exists = false\n for (let i = 0; i < movieTheme.length; i++) {\n if (movieTheme[i] === item.theme.name) {\n exists = true;\n }\n}\nif (exists) {\n return false\n} else {\n movieTheme.push(item.theme.name)\n return item.theme.name;\n\n}\n});\nconst movieThemeCount = movieTheme.length;\n\nconsole.log(movieTheme); \nconsole.log(movieThemeCount); \n"
},
{
"answer_id": 74391424,
"author": "RenokK",
"author_id": 2377357,
"author_profile": "https://Stackoverflow.com/users/2377357",
"pm_score": 3,
"selected": true,
"text": "map"
},
{
"answer_id": 74391535,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 0,
"selected": false,
"text": "handleCountTheme"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19761134/"
] |
74,391,344 | <p>I have two fragments that share information with each other, in the first one I have an edit text and button widget. The second fragment is just a listview. When the user clicks the button, it displays whatever is in the edit text widget in the second fragment.
So if the user enters the text study and clicks the button the second fragment will display</p>
<p>Study</p>
<p>If the user then enters the text eat and clicks the button, the second fragment will display
Study
Eat</p>
<p>I am having so issues with displaying the texts</p>
<p>So far this is what I have done</p>
<pre><code>class FirstFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
viewModel = activity?.run { ViewModelProvider(this)[MyViewModel::class.java]
} ?: throw Exception("Invalid Activity")
val view = inflater.inflate(R.layout.one_fragment, container, false)
val button = view.findViewById<Button>(R.id.vbutton)
val value = view.findViewById<EditText>(R.id.textView)
button.setOnClickListener {
}
return view;
}
}
</code></pre>
<pre><code>class SecondFragment : Fragment() {
lateinit var viewModel: MyViewModel
@SuppressLint("MissingInflatedId")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
viewModel = activity?.run { ViewModelProvider(this)[MyViewModel::class.java]
} ?: throw Exception("Invalid Activity")
val view = inflater.inflate(R.layout.page3_fragment, container, false)
val valueView = v.findViewById<TextView>(R.id.textView)
return view
</code></pre>
<p>The problem I am having is how to display the texts</p>
| [
{
"answer_id": 74391407,
"author": "Besufkad Menji",
"author_id": 10239185,
"author_profile": "https://Stackoverflow.com/users/10239185",
"pm_score": 0,
"selected": false,
"text": "movies = [{\"id\": 1, \"name\": \"Ps: i love you\", \"theme\": {\"id\": 1, \"name\": \"love\"}},\n{\"id\": 2, \"name\": \"Holiday\", \"theme\": {\"id\": 1, \"name\": \"love\"}},\n{\"id\": 3, \"name\": \"Scary Movie\", \"theme\": {\"id\": 2, \"name\": \"horror\"}}]\n\n\nconst movieTheme = []\n\nmovies.forEach((item) => {\n let exists = false\n for (let i = 0; i < movieTheme.length; i++) {\n if (movieTheme[i] === item.theme.name) {\n exists = true;\n }\n}\nif (exists) {\n return false\n} else {\n movieTheme.push(item.theme.name)\n return item.theme.name;\n\n}\n});\nconst movieThemeCount = movieTheme.length;\n\nconsole.log(movieTheme); \nconsole.log(movieThemeCount); \n"
},
{
"answer_id": 74391424,
"author": "RenokK",
"author_id": 2377357,
"author_profile": "https://Stackoverflow.com/users/2377357",
"pm_score": 3,
"selected": true,
"text": "map"
},
{
"answer_id": 74391535,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 0,
"selected": false,
"text": "handleCountTheme"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20283835/"
] |
74,391,375 | <p>Given an integer in Java, is there an easy way you could represent this in binary as an array of <code>boolean</code>?</p>
<pre><code>int input = 12;
return {True, True, False, False};
</code></pre>
<p>And what about, for example, if you already had a set list length? How would you make it return a list with the set length?</p>
<pre><code>int input = 15;
return {False, False, True, True, True, True};
</code></pre>
<p>I tried to make a pointer that would reset every two times, but I know that there has to be an easier solution involving just using the <code>%</code> operator.</p>
<p>This resulted in a very long time delay, ending up in a timing out.</p>
| [
{
"answer_id": 74391456,
"author": "Rob Spoor",
"author_id": 1180351,
"author_profile": "https://Stackoverflow.com/users/1180351",
"pm_score": 3,
"selected": true,
"text": "BitSet bitSet = BitSet.valueOf(new long[] { 12});\n"
},
{
"answer_id": 74391626,
"author": "R-Rothrock",
"author_id": 19124377,
"author_profile": "https://Stackoverflow.com/users/19124377",
"pm_score": 0,
"selected": false,
"text": "import java.util.*;\nimport java.math.*;\nclass GFG {\n\n public static BigInteger binaryConv(BigInteger n)\n {\n if (n.compareTo(BigInteger.valueOf(1)) == 0) {\n\n return BigInteger.valueOf(1);\n }\n return ((binaryConv(n.divide(BigInteger.valueOf(2))).multiply(BigInteger.valueOf(10))).add(n.mod(BigInteger.valueOf(2))));\n }\n public static void main(String[] args)\n {\n BigInteger N = new BigInteger(\"9876543210987543210\");\n System.out.println(binaryConv(N));\n }\n}\n"
},
{
"answer_id": 74396706,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 0,
"selected": false,
"text": "Interger"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18345621/"
] |
74,391,376 | <p>I have a Blazor Maui application where I'd like to have the option to receive push notifications on.
I'd like to send the push notifications from a server project inside the same solution where I have my Blazor Maui project. For example : the server should contain a Gui with a textbox for the title and messagebody. This should then sent to all the users who downloaded the app.</p>
<p>Any tutorials,links, examples, tips or recommendations on how to start this?</p>
<p>I followed <a href="https://www.youtube.com/watch?v=gBbbctEvbOk" rel="nofollow noreferrer">this</a> guide before but this is all configured inside the app itself.</p>
<p>Thank you in advance.</p>
| [
{
"answer_id": 74391456,
"author": "Rob Spoor",
"author_id": 1180351,
"author_profile": "https://Stackoverflow.com/users/1180351",
"pm_score": 3,
"selected": true,
"text": "BitSet bitSet = BitSet.valueOf(new long[] { 12});\n"
},
{
"answer_id": 74391626,
"author": "R-Rothrock",
"author_id": 19124377,
"author_profile": "https://Stackoverflow.com/users/19124377",
"pm_score": 0,
"selected": false,
"text": "import java.util.*;\nimport java.math.*;\nclass GFG {\n\n public static BigInteger binaryConv(BigInteger n)\n {\n if (n.compareTo(BigInteger.valueOf(1)) == 0) {\n\n return BigInteger.valueOf(1);\n }\n return ((binaryConv(n.divide(BigInteger.valueOf(2))).multiply(BigInteger.valueOf(10))).add(n.mod(BigInteger.valueOf(2))));\n }\n public static void main(String[] args)\n {\n BigInteger N = new BigInteger(\"9876543210987543210\");\n System.out.println(binaryConv(N));\n }\n}\n"
},
{
"answer_id": 74396706,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 0,
"selected": false,
"text": "Interger"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20281236/"
] |
74,391,457 | <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class MyElement extends HTMLElement {
constructor() {
super();
// Props
this._color = this.getAttribute("color");
this._myArray = this.getAttribute("myArray");
// data
// Shadow DOM
this._shadowRoot = this.attachShadow({ mode: "open" });
this.render();
}
template() {
const template = document.createElement("template");
template.innerHTML = `
<style>
:host {
display: block;
}
span {color: ${this.color}}
</style>
<p>Notice the console displays three renders: the original, when color changes to blue after 2 secs, and when the array gets values</p>
<p>The color is: <span>${this.color}</span></p>
<p>The array is: ${this.myArray}</p>
`;
return template;
}
get color() {
return this._color;
}
set color(value) {
this._color = value;
this.render();
}
get myArray() {
return this._myArray;
}
set myArray(value) {
this._myArray = value;
this.render();
}
render() {
// Debug only
const props = Object.getOwnPropertyNames(this).map(prop => {
return this[prop]
})
console.log('Parent render; ', JSON.stringify(props));
// end debug
this._shadowRoot.innerHTML = '';
this._shadowRoot.appendChild(this.template().content.cloneNode(true));
}
}
window.customElements.define('my-element', MyElement);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<head>
<script type="module" src="./src/my-element.js" type="module"></script>
<!-- <script type="module" src="./src/child-element.js" type="module"></script> -->
</head>
<body>
<p><span>Outside component</span> </p>
<my-element color="green"></my-element>
<script>
setTimeout(() => {
document.querySelector('my-element').color = 'blue';
document.querySelector('my-element').myArray = [1, 2, 3];
}, 2000);
</script>
</body></code></pre>
</div>
</div>
</p>
<p>I have a native web component whose attributes and properties may change (using getters/setters). When they do, the whole component rerenders, including all children they may have.</p>
<p>I need to rerender only the elements in the template that are affected.</p>
<pre class="lang-js prettyprint-override"><code>import {ChildElement} from './child-element.js';
class MyElement extends HTMLElement {
constructor() {
super();
// Props
this._color = this.getAttribute("color");
this._myArray = this.getAttribute("myArray");
// Shadow DOM
this._shadowRoot = this.attachShadow({ mode: "open" });
this.render();
}
template() {
const template = document.createElement("template");
template.innerHTML = `
<style>
span {color: ${this.color}}
</style>
<p>The color is: <span>${this.color}</span></p>
<p>The array is: ${this.myArray}</p>
<child-element></child-element>
`;
return template;
}
get color() {
return this._color;
}
set color(value) {
this._color = value;
this.render(); // It rerenders the whole component
}
get myArray() {
return this._myArray;
}
set myArray(value) {
this._myArray = value;
this.render();
}
render() {
this._shadowRoot.innerHTML = '';
this._shadowRoot.appendChild(this.template().content.cloneNode(true));
}
}
window.customElements.define('my-element', MyElement);
window.customElements.define('child-element', ChildElement);
</code></pre>
<p>Because each setter calls <code>render()</code>, the whole component, including children unaffected by the updated property, rerenders.</p>
| [
{
"answer_id": 74391456,
"author": "Rob Spoor",
"author_id": 1180351,
"author_profile": "https://Stackoverflow.com/users/1180351",
"pm_score": 3,
"selected": true,
"text": "BitSet bitSet = BitSet.valueOf(new long[] { 12});\n"
},
{
"answer_id": 74391626,
"author": "R-Rothrock",
"author_id": 19124377,
"author_profile": "https://Stackoverflow.com/users/19124377",
"pm_score": 0,
"selected": false,
"text": "import java.util.*;\nimport java.math.*;\nclass GFG {\n\n public static BigInteger binaryConv(BigInteger n)\n {\n if (n.compareTo(BigInteger.valueOf(1)) == 0) {\n\n return BigInteger.valueOf(1);\n }\n return ((binaryConv(n.divide(BigInteger.valueOf(2))).multiply(BigInteger.valueOf(10))).add(n.mod(BigInteger.valueOf(2))));\n }\n public static void main(String[] args)\n {\n BigInteger N = new BigInteger(\"9876543210987543210\");\n System.out.println(binaryConv(N));\n }\n}\n"
},
{
"answer_id": 74396706,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 0,
"selected": false,
"text": "Interger"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5276057/"
] |
74,391,480 | <p>Please help me to solve this error. If click Save button display the following error. I am using ASP.NET Core 3.1 with Entity Framework Core.</p>
<blockquote>
<p>An unhandled exception occurred while processing the request.
InvalidOperationException: The view 'Save' was not found. The following locations were searched:</p>
<p>/Views/Home/Save.cshtml<br />
/Views/Shared/Save.cshtml</p>
<p>InvalidOperationException: The view 'Save' was not found. The following locations were searched: /Views/Home/Save.cshtml /Views/Shared/Save.cshtml</p>
</blockquote>
<p>Controller: HomeController</p>
<pre><code>public IActionResult Index()
{
CascadingModel model = new CascadingModel();
model.Countries = (from customer in this.Context.Countries
select new SelectListItem
{
Value = customer.CountryId.ToString(),
Text = customer.CountryName
}).ToList();
return View(model);
}
[HttpPost]
public ActionResult Index(int countryId, int stateId, int cityId)
{
CascadingModel model = new CascadingModel();
model.Countries = (from customer in this.Context.Countries
select new SelectListItem
{
Value = customer.CountryId.ToString(),
Text = customer.CountryName
}).ToList();
model.States = (from customer in this.Context.States
where customer.CountryId == countryId
select new SelectListItem
{
Value = customer.StateId.ToString(),
Text = customer.StateName
}).ToList();
model.Cities = (from customer in this.Context.Cities
where customer.StateId == stateId
select new SelectListItem
{
Value = customer.CityId.ToString(),
Text = customer.CityName
}).ToList();
return View(model);
}
[HttpPost]
[ActionName("Save")]
[ValidateAntiForgeryToken]
public IActionResult Save(CascadingModel model)
{
if (ModelState.IsValid)
{
var newstaffrecords = new StaffDetailVM()
{
StaffId = model.StaffId,
StaffName = model.StaffName,
CountryName = model.CountryName,
StateName = model.StateName,
CityName = model.CityName,
};
this.Context.Stafftbl.Add(newstaffrecords);
this.Context.SaveChanges();
}
return View(model);
}
</code></pre>
<p>View: Index.cshtml</p>
<pre><code><form asp-controller="Home" method="post">
<div class="row">
<div class="col-md-4">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="StaffId" class="control-label"></label>
<input asp-for="StaffId" class="form-control" />
<span asp-validation-for="StaffId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="StaffName" class="control-label"></label>
<input asp-for="StaffName" class="form-control" />
<span asp-validation-for="StaffName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="CountryId" class="control-label"></label>
<select id="ddlCountries" name="CountryName" asp-for="CountryId" asp-items="Model.Countries" class="form-control">
<option value="">--Please select--</option>
</select>
<span asp-validation-for="CountryId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="StateId" class="control-label"></label>
<select id="ddlStates" name="StateName" asp-for="StateId" asp-items="Model.States" class="form-control">
<option value="">--Please select--</option>
</select>
<span asp-validation-for="StateId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="CityId" class="control-label"></label>
<select id="ddlCities" name="CityName" asp-for="CityId" asp-items="Model.Cities" class="form-control">
<option value="">--Please select--</option>
</select>
<span asp-validation-for="CityId" class="text-danger"></span>
</div>
<div class="form-group">
<button type="submit" asp-action="Save" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</form>
</code></pre>
| [
{
"answer_id": 74394804,
"author": "Facundo Gallardo",
"author_id": 20375146,
"author_profile": "https://Stackoverflow.com/users/20375146",
"pm_score": 1,
"selected": false,
"text": "[HttpPost]\n[ActionName(\"Save\")]\n[ValidateAntiForgeryToken]\npublic IActionResult Save(CascadingModel model)\n{\n if (ModelState.IsValid)\n {\n var newstaffrecords = new StaffDetailVM()\n {\n StaffId = model.StaffId,\n StaffName = model.StaffName,\n CountryName = model.CountryName,\n StateName = model.StateName,\n CityName = model.CityName,\n\n };\n this.Context.Stafftbl.Add(newstaffrecords);\n this.Context.SaveChanges();\n }\n\n return View(\"Index\", model);\n}\n"
},
{
"answer_id": 74399564,
"author": "Md Farid Uddin Kiron",
"author_id": 9663070,
"author_profile": "https://Stackoverflow.com/users/9663070",
"pm_score": 0,
"selected": false,
"text": "controller public IActionResult Save(CascadingModel model)"
},
{
"answer_id": 74399761,
"author": "Yanga",
"author_id": 3173214,
"author_profile": "https://Stackoverflow.com/users/3173214",
"pm_score": 0,
"selected": false,
"text": "Index.cshtml"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16437954/"
] |
74,391,481 | <p>I've a file with a line that looks like this "Room,home,You are in your home"</p>
<p>I wanna read the file and then create an object (I have created a class called Room), what I wanna do now is like read the line and creat something like this.</p>
<p>Room home = new Room (You are in your home)</p>
<p>I have used bufferedreader and split my words and put them in an ArrayList but it just doesn't look right. I need help cuz I don't know how to continue.</p>
<pre><code>BufferedReader myfile = new BufferedReader(new FileReader(thefile));
String line = thefile.readLine();
while (line != null) {
String[] array = line.split(",");
line = file.readLine();}
</code></pre>
| [
{
"answer_id": 74394804,
"author": "Facundo Gallardo",
"author_id": 20375146,
"author_profile": "https://Stackoverflow.com/users/20375146",
"pm_score": 1,
"selected": false,
"text": "[HttpPost]\n[ActionName(\"Save\")]\n[ValidateAntiForgeryToken]\npublic IActionResult Save(CascadingModel model)\n{\n if (ModelState.IsValid)\n {\n var newstaffrecords = new StaffDetailVM()\n {\n StaffId = model.StaffId,\n StaffName = model.StaffName,\n CountryName = model.CountryName,\n StateName = model.StateName,\n CityName = model.CityName,\n\n };\n this.Context.Stafftbl.Add(newstaffrecords);\n this.Context.SaveChanges();\n }\n\n return View(\"Index\", model);\n}\n"
},
{
"answer_id": 74399564,
"author": "Md Farid Uddin Kiron",
"author_id": 9663070,
"author_profile": "https://Stackoverflow.com/users/9663070",
"pm_score": 0,
"selected": false,
"text": "controller public IActionResult Save(CascadingModel model)"
},
{
"answer_id": 74399761,
"author": "Yanga",
"author_id": 3173214,
"author_profile": "https://Stackoverflow.com/users/3173214",
"pm_score": 0,
"selected": false,
"text": "Index.cshtml"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16086533/"
] |
74,391,486 | <pre><code><label>Gender<span class="note">*</span>:</label>
<select name="gender">
<option value="1" selected <?= ($_POST['gender'] == "1")? "selected":"";?>>Select</option>
<option value="male" <?= ($_POST['gender'] == "2")? "selected":"";?>>Male</option>
<option value="female" <?= ($_POST['gender'] == "3")? "selected":"";?>>Female</option>
</select>
<?php echo "<p class='note'>".$msg_gender."</p>";?>
</code></pre>
<pre><code>if (isset($_POST['submit'])) {
$gender = $_POST['gender'];
if($gender != "2" || $gender != "3"){
$msg_gender = "Gender not valid";
}
}
</code></pre>
<p>If the $msg_gender="" the form will be valid, else it'll say gender invalid. But it says gender invalid at every stage no matter which option i select</p>
| [
{
"answer_id": 74394804,
"author": "Facundo Gallardo",
"author_id": 20375146,
"author_profile": "https://Stackoverflow.com/users/20375146",
"pm_score": 1,
"selected": false,
"text": "[HttpPost]\n[ActionName(\"Save\")]\n[ValidateAntiForgeryToken]\npublic IActionResult Save(CascadingModel model)\n{\n if (ModelState.IsValid)\n {\n var newstaffrecords = new StaffDetailVM()\n {\n StaffId = model.StaffId,\n StaffName = model.StaffName,\n CountryName = model.CountryName,\n StateName = model.StateName,\n CityName = model.CityName,\n\n };\n this.Context.Stafftbl.Add(newstaffrecords);\n this.Context.SaveChanges();\n }\n\n return View(\"Index\", model);\n}\n"
},
{
"answer_id": 74399564,
"author": "Md Farid Uddin Kiron",
"author_id": 9663070,
"author_profile": "https://Stackoverflow.com/users/9663070",
"pm_score": 0,
"selected": false,
"text": "controller public IActionResult Save(CascadingModel model)"
},
{
"answer_id": 74399761,
"author": "Yanga",
"author_id": 3173214,
"author_profile": "https://Stackoverflow.com/users/3173214",
"pm_score": 0,
"selected": false,
"text": "Index.cshtml"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18224896/"
] |
74,391,520 | <p>Let's say I have a model called <code>Research</code>. Each research belongsToMany <code>Location</code> models. And each <code>Location</code> model BelongsToMany <code>Contact</code> models. BUT, each <code>Contact</code> is also related to <code>Research</code>.</p>
<pre><code>class Research extends Model {
protected $table = 'researches';
public function locations()
{
return BelongsToMany( Location::class, 'research_locations_list', 'research_id', 'location_id' );
}
}
class Location extends Model {
protected $table = 'locations';
public function researches()
{
return BelongsToMany( Research::class, 'research_locations_list', 'research_id', 'location_id' );
}
public function contacts()
{
return BelongsToMany( Contact::class, 'location_contacts_list', 'location_id', 'contact_id' );
}
}
class Contact extends Model {
protected $table = 'contacts';
public function locations()
{
return BelongsToMany( Location::class, 'location_contacts_list', 'location_id', 'contact_id' );
}
}
</code></pre>
<p><code>researches</code> table:</p>
<pre><code>+----+------------+
| id | research |
+----+------------+
| 1 | Research 1 |
| 2 | Research 2 |
+----+------------+
</code></pre>
<p><code>locations</code> table:</p>
<pre><code>+----+---------------+
| id | location |
+----+---------------+
| 1 | United States |
| 2 | Great Britain |
| 3 | Germany |
+----+---------------+
</code></pre>
<p><code>contacts</code> table:</p>
<pre><code>+----+---------+
| id | contact |
+----+---------+
| 1 | Jack |
| 2 | John |
| 3 | Hanz |
+----+---------+
</code></pre>
<p><code>research_locations_list</code> table:</p>
<pre><code>+----+-------------+-------------+
| id | research_id | location_id |
+----+-------------+-------------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 2 |
| 4 | 2 | 3 |
+----+-------------+-------------+
</code></pre>
<p>So Research 1 is being conducted in United States and Great Britain, Research 2 in Great Britain and Germany</p>
<p><code>location_contacts_list</code> table:</p>
<pre><code>+----+-------------+------------+-------------+
| id | location_id | contact_id | research_id |
+----+-------------+------------+-------------+
| 1 | 1 | 1 | 1 |
| 2 | 1 | 2 | 1 |
| 3 | 2 | 1 | 2 |
| 4 | 3 | 3 | 2 |
+----+-------------+------------+-------------+
</code></pre>
<p>Research 1 should have Jack and John as contacts in United States and no contacts elsewhere;</p>
<p>Research 2 should have John as contact in Great Britain and Hanz in Germany;</p>
<p>Now, with lazy load I can achieve that:</p>
<pre><code>$researches = Research::all();
foreach( $researches as $research )
{
foreach( $research->locations as $location )
{
$contacts = $location->contacts()->wherePivot( 'research_id', $research->id )->get();
// Will return John and Jack in United States for Research 1 and John in Great Britain and Hanz in Germany for Research 2
}
}
</code></pre>
<p>Now, the question is: how do I achieve this with eager loading?</p>
<pre><code>$researches = Research::with( 'locations.contacts' )->all();
foreach( $researches as $research )
{
foreach( $research->locations as $location )
{
$contacts = $location->contacts;
// Will return John and Jack in United States, John in Great Britain ( which is not supposed to happen ) for Research 1 and John in Great Britain and Hanz in Germany for Research 2
}
}
</code></pre>
<p>Perhaps I can instruct somehow for contacts to respect ancestor id? Like:</p>
<pre><code>$research = Research::with( 'locations.contacts' )->where( 'researches.id = location_contacts_list.research_id' )->all();
</code></pre>
<p><strong>UPDATE</strong></p>
<p>The closest I came up to solving this is modifying the <code>Location</code> model like this:</p>
<pre><code>class Location extends Model {
protected $table = 'locations';
public function researches()
{
return BelongsToMany( Research::class, 'research_locations_list', 'research_id', 'location_id' );
}
public function contacts()
{
return BelongsToMany( Contact::class, 'location_contacts_list', 'location_id', 'contact_id' );
}
// Modify contacts attribute getter
public function getContactsAttribute()
{
$contacts = $this->contacts();
if( !empty( $this->pivot->research_id ) )
{
$contacts = $contacts->wherePivot( 'research_id', $this->pivot->research_id );
}
return $contacts->get();
}
}
</code></pre>
<p>But it looks kind of dirty...</p>
| [
{
"answer_id": 74391880,
"author": "gkouem",
"author_id": 18035371,
"author_profile": "https://Stackoverflow.com/users/18035371",
"pm_score": 0,
"selected": false,
"text": "with"
},
{
"answer_id": 74425658,
"author": "Vlad",
"author_id": 20382571,
"author_profile": "https://Stackoverflow.com/users/20382571",
"pm_score": 1,
"selected": false,
"text": "class Research extends Model\n{\n protected $table = 'researches';\n\n public function locations(): BelongsToMany\n {\n return $this->belongsToMany(Location::class, 'research_locations_list');\n }\n\n public function contacts(): BelongsToMany\n {\n return $this->belongsToMany(Contact::class, 'location_contacts_list')\n ->withPivot('location_id');\n }\n\n public function contactsByLocationAttribute(int $locationId): Collection\n {\n return $this->contacts\n ->filter(static function ($contact) use ($locationId) {\n return $contact->pivot->location_id === $locationId;\n });\n }\n}\n\n\n$researches = Research::with(['locations', 'contacts'])->get();\nforeach ($researches as $research) {\n foreach ($research->locations as $location) {\n $contacts = $research->contactsByLocation($location->id);\n }\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1263987/"
] |
74,391,527 | <p>I have a dataset where the data is reported by week and year like: YYWW. I have split it into to columns: Year and Week.</p>
<p>I need to get a date from the week: Week_start_date. My weeks start at mondays, so I would like to get the monday and sunday date from each week.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>YYWW</th>
<th>year</th>
<th>week</th>
<th>Week_start_date</th>
<th>Week_end_date</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1504</td>
<td>2015</td>
<td>04</td>
<td>?</td>
<td>?</td>
</tr>
<tr>
<td>2</td>
<td>1651</td>
<td>2016</td>
<td>51</td>
<td>?</td>
<td>?</td>
</tr>
<tr>
<td>3</td>
<td>1251</td>
<td>2012</td>
<td>51</td>
<td>?</td>
<td>?</td>
</tr>
<tr>
<td>4</td>
<td>1447</td>
<td>2014</td>
<td>47</td>
<td>?</td>
<td>?</td>
</tr>
</tbody>
</table>
</div>
<p>How do I extract the week start date from just a week number and year?
I've looked at several threads at SO, but haven't found a solution yet.</p>
<p>I have tried looking at different threads, but encounters problems using their solutions. Most seaches for "convert week number and year to date" on google and SO returns the opposite: Getting a weeknumber from a date. This guy answered by Vince, have maybe some similar issues, but I can't get the code to do the job: <a href="https://communities.sas.com/t5/SAS-Programming/Converting-week-number-to-start-date/td-p/106456" rel="nofollow noreferrer">https://communities.sas.com/t5/SAS-Programming/Converting-week-number-to-start-date/td-p/106456</a></p>
| [
{
"answer_id": 74391692,
"author": "Reeza",
"author_id": 1919583,
"author_profile": "https://Stackoverflow.com/users/1919583",
"pm_score": 1,
"selected": false,
"text": "data have;\ninfile cards dlm='09'x;\ninput ID $ YYWW year week ;\nformat year 8. week z2.;\ncards; \n1 1504 2015 04 \n2 1651 2016 51 \n3 1251 2012 51 \n4 1447 2014 47\n;;;;\n\ndata want;\nset have;\n week_start = intnx('week', mdy(1, 1, year), week, 'b')+1;\n week_end = intnx('week', mdy(1, 1, year), week, 'e')+1;\n format week_: date9.;\nrun;\n"
},
{
"answer_id": 74392932,
"author": "Tom",
"author_id": 4965549,
"author_profile": "https://Stackoverflow.com/users/4965549",
"pm_score": 0,
"selected": false,
"text": "data have;\n input ID $ YYWW year week ;\ncards; \n1 1504 2015 04\n2 1651 2016 51\n3 1251 2012 51\n4 1447 2014 47\n;;;;\n\ndata want;\n set have;\n week_start=input(cats(year,'W',put(week,Z2.)),weekv.);\n week_end=week_start+6;\n format week_: yymmdd10.;\nrun;\n\nResults\n\nObs ID YYWW year week week_start week_end\n\n 1 1 1504 2015 4 2015-01-19 2015-01-25\n 2 2 1651 2016 51 2016-12-19 2016-12-25\n 3 3 1251 2012 51 2012-12-17 2012-12-23\n 4 4 1447 2014 47 2014-11-17 2014-11-23\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20469428/"
] |
74,391,592 | <p>I need a little help removing unique characters in a doubly linked list in C. So here's the logic I tried implementing: I counted the occurrence of each character in the doubly linked list. If it's occurrence is 1 time, then it is unique element and needs to be deleted. I'll be repeating the process for all elements. But my code in remove_unique_dll() function isn't working properly, please help me fix it. Here's my code-</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
char data;
struct node *next;
struct node *prev;
};
struct node *head, *tail = NULL; //Represent the head and tail of the doubly linked list
int len;
void addNode(char data)
{
struct node *newNode = (struct node*) malloc(sizeof(struct node)); //Create new node
newNode->data = data;
if (head == NULL)
{ //If dll is empty
head = tail = newNode; //Both head and tail will point to newNode
head->prev = NULL; //head's previous will point to NULL
tail->next = NULL; //tail's next will point to NULL, as it is the last node of the list
}
else
{
tail->next = newNode; //newNode will be added after tail such that tail's next points to newNode
newNode->prev = tail; //newNode's previous will point to tail
tail = newNode; //newNode will become new tail
tail->next = NULL; //As it is last node, tail's next will point to NULL
}
}
void remove_unique_dll()
{
struct node *current = head;
struct node *next;
struct node *prev;
int cnt;
while (current != NULL)
{
next = current->next;
cnt = 1;
//printf("!%c ",next->data);
while (next != NULL)
{
if (next->data == current->data)
{
cnt += 1;
next = next->next;
}
else
next = next->next;
//printf("@%c %d %c\n",next->data,cnt,current->data);
}
if (cnt == 1)
{
prev = current->prev;
//printf("@%c %d",prev->data,cnt);
if (prev == NULL)
{
head = next;
}
else
{
prev->next = next;
}
if (next == NULL)
{
tail = prev;
}
else
{
next->prev = prev;
}
}
current = current->next;
//printf("#%c ",current->data);
}
head = current;
}
void display()
{
struct node *current = head; //head the global one
while (current != NULL)
{
printf("%c<->", current->data); //Prints each node by incrementing pointer.
current = current->next;
}
printf("NULL\n");
}
int main()
{
char s[100];
int i;
printf("Enter string: ");
scanf("%s", s);
len = strlen(s);
for (i = 0; i < len; i++)
{
addNode(s[i]);
}
printf("Doubly linked list: \n");
display();
remove_unique_dll();
printf("Doubly linked list after removing unique elements: \n");
display();
return 0;
}
</code></pre>
<p>The output is like this-
<a href="https://i.stack.imgur.com/svz10.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/svz10.png" alt="enter image description here" /></a></p>
<p>If you uncomment the printf() statements inside remove_unique_dll() you'll notice that no code below inner while loop is being executed after inner while loop ends. What's the issue here and what's the solution?</p>
<p>Sample input- aacb</p>
<p>Expected output- a<->a<->NULL</p>
| [
{
"answer_id": 74391692,
"author": "Reeza",
"author_id": 1919583,
"author_profile": "https://Stackoverflow.com/users/1919583",
"pm_score": 1,
"selected": false,
"text": "data have;\ninfile cards dlm='09'x;\ninput ID $ YYWW year week ;\nformat year 8. week z2.;\ncards; \n1 1504 2015 04 \n2 1651 2016 51 \n3 1251 2012 51 \n4 1447 2014 47\n;;;;\n\ndata want;\nset have;\n week_start = intnx('week', mdy(1, 1, year), week, 'b')+1;\n week_end = intnx('week', mdy(1, 1, year), week, 'e')+1;\n format week_: date9.;\nrun;\n"
},
{
"answer_id": 74392932,
"author": "Tom",
"author_id": 4965549,
"author_profile": "https://Stackoverflow.com/users/4965549",
"pm_score": 0,
"selected": false,
"text": "data have;\n input ID $ YYWW year week ;\ncards; \n1 1504 2015 04\n2 1651 2016 51\n3 1251 2012 51\n4 1447 2014 47\n;;;;\n\ndata want;\n set have;\n week_start=input(cats(year,'W',put(week,Z2.)),weekv.);\n week_end=week_start+6;\n format week_: yymmdd10.;\nrun;\n\nResults\n\nObs ID YYWW year week week_start week_end\n\n 1 1 1504 2015 4 2015-01-19 2015-01-25\n 2 2 1651 2016 51 2016-12-19 2016-12-25\n 3 3 1251 2012 51 2012-12-17 2012-12-23\n 4 4 1447 2014 47 2014-11-17 2014-11-23\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19611563/"
] |
74,391,598 | <p>I've recently started working on a frontend project that uses Next.js, and I'm trying to figure out how to best take advantage of the SSR it provides. I want to use some client-side fetching as well, and while the <a href="https://nextjs.org/learn/foundations/how-nextjs-works/rendering" rel="nofollow noreferrer">documentation</a> explains that using React hooks in a component will make it render client-side, it seems quite sparse about how this affects the other components up/down the DOM tree.</p>
<p>I tried to test the SSR/CSR behaviour by creating a site with some components with/without React hooks in them, and opening it in Chrome first with JavaScript enabled, then disabled. So far I've found out a couple of things and I was wondering if my assumptions are right:</p>
<ul>
<li>it seems that components that use hooks work like typical React components - their children re-render when effect/state hooks in the parent render, so they don't seem to benefit from SSR and should instead be optimised using React features like <code>React.memo</code>.</li>
<li>when I open the site with JS disabled, it seems that all components come pre-rendered - components that use state and display it, even show the initial state set in the hook. For example, the below component:</li>
</ul>
<pre><code>export const TestComponent = () => {
const [num, setNum] = useState(13)
return (
<div>
<button onClick={() => setNum(num+1)}>CLICK</button>
<h2>Number: {num}</h2>
</div>
)
}
</code></pre>
<p>actually contains the text "<strong>Number: 13</strong>" (the button obviously doesn't work without JS though)</p>
<p>What I'm also wondering is how much using global context providers is going to diminish performance improvement from SSR. Let's say my <code>_app.jsx</code> wraps each page in a provider that periodically queries an API. Does it completely void the advantage presented by SSR, seeing as it will probably cause the entire page to re-render?</p>
| [
{
"answer_id": 74470693,
"author": "Sparko Sol",
"author_id": 20407048,
"author_profile": "https://Stackoverflow.com/users/20407048",
"pm_score": 0,
"selected": false,
"text": "import React from 'react';\n\nimport { useRouter } from 'next/router';\n\n\nconst Page = () => {\n\n const router = useRouter();\n\n const { id } = router.query;\n\n return <p>Post: {id}</p>;\n\n};\n\nexport default Page;\n"
},
{
"answer_id": 74498290,
"author": "Badal Saibo",
"author_id": 7679903,
"author_profile": "https://Stackoverflow.com/users/7679903",
"pm_score": 3,
"selected": true,
"text": "getServerSideProps"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20460574/"
] |
74,391,605 | <p>I am learning python as a novice and I was asked to solve the total of seconds in the problem. I was given the format but it still seems that I can not get a hand of it. it keeps telling me that I didn't get the minute and seconds part</p>
<p>I tried this:</p>
<pre><code>def get_seconds(hours, minutes, seconds):
return 3600*hours + 60*minutes + seconds
amount_a = get_seconds(3600*2 + 60*30 + 0*0)
amount_b = get_seconds(0 + 60*45 + 15)
result = amount_a + amount_b
print(result)
</code></pre>
<p>expecting to get it right as i think i imputed everything correctly but instead i was getting this:</p>
<pre><code>Error on line 4:
amount_a = get_seconds(3600*2 + 60*30 + 0*0)
TypeError: get_seconds() missing 2 required positional arguments: 'minutes' and 'seconds'
</code></pre>
| [
{
"answer_id": 74391652,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 1,
"selected": false,
"text": "amount_a = get_seconds(2, 30, 0) # 2 hours and 30 minutes\namount_b = get_seconds(0, 45, 15) # 45 minutes and 15 seconds\nresult = amount_a + amount_b # total seconds\nprint(result) # 11715\n"
},
{
"answer_id": 74391671,
"author": "0x0fba",
"author_id": 20339407,
"author_profile": "https://Stackoverflow.com/users/20339407",
"pm_score": 0,
"selected": false,
"text": "def get_seconds(hours, minutes, seconds):\n return 3600*hours + 60*minutes + seconds\n\namount_a = get_seconds(2, 30, 0)\namount_b = get_seconds(0, 45, 5)\nresult = amount_a + amount_b \nprint(result)\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20441278/"
] |
74,391,607 | <p>I need to persist my domain objects into two different databases. This use case is purely write-only. I don't need to read back from the databases.</p>
<p>Following <code>Domain Driven Design</code>, I typically create a repository for each aggregate root.</p>
<p>I see two alternatives. I can create one single repository for my <code>AG</code>, and implement it so that it persists the domain object into the two databases.</p>
<p>The second alternative is to create two repositories, one each for each database.</p>
<p>From a <code>domain driven design</code> perspective, which alternative is correct?</p>
| [
{
"answer_id": 74391652,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 1,
"selected": false,
"text": "amount_a = get_seconds(2, 30, 0) # 2 hours and 30 minutes\namount_b = get_seconds(0, 45, 15) # 45 minutes and 15 seconds\nresult = amount_a + amount_b # total seconds\nprint(result) # 11715\n"
},
{
"answer_id": 74391671,
"author": "0x0fba",
"author_id": 20339407,
"author_profile": "https://Stackoverflow.com/users/20339407",
"pm_score": 0,
"selected": false,
"text": "def get_seconds(hours, minutes, seconds):\n return 3600*hours + 60*minutes + seconds\n\namount_a = get_seconds(2, 30, 0)\namount_b = get_seconds(0, 45, 5)\nresult = amount_a + amount_b \nprint(result)\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4811392/"
] |
74,391,674 | <p>I have a string as this, and I want to convert it into dictionary.</p>
<pre><code>test=
'{"age":59.0,"bp":70.0,"sg":1.01,"al":3.0,"su":0.0,"rbc":1.0,"ba":0.0,"bgr":76.0,"bu":186.0,"sc":15.0,"sod":135.0,"pot":7.6,"hemo":7.1,"pcv":22.0,"wbcc":3800.0,"rbcc":2.1,"htn":1.0,"dm":0.0,"cad":0.0,"appet":0.0,"pe":1.0,"ane":1.0}'
</code></pre>
<p>I tried <code>dict(test)</code> but it retuned an error as:</p>
<pre><code>ValueError: dictionary update sequence element #0 has length 1; 2 is required
</code></pre>
<p>How can I convert this string to a dict?</p>
| [
{
"answer_id": 74391699,
"author": "It_is_Chris",
"author_id": 9177877,
"author_profile": "https://Stackoverflow.com/users/9177877",
"pm_score": 3,
"selected": true,
"text": "import ast\n\nnew_dict = ast.literal_eval(test)\n"
},
{
"answer_id": 74391772,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 2,
"selected": false,
"text": "json"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11589463/"
] |
74,391,744 | <p>I am learning to use SQL in R. I want to query a database about the mountains whose height is less than 100 meter difference from the average height of all mountains.</p>
<p>My code so far looks like this:</p>
<pre class="lang-r prettyprint-override"><code>sql6 = "SELECT Name, Height, AVG(Height) FROM mountain WHERE AVG(Height) > 100 AND AVG(Height) < 100"
result6 = dbSendQuery(con, sql6)
df6 = dbFetch(result6)
head(df6)
</code></pre>
<p>But I get an error saying</p>
<blockquote>
<p>Error: Invalid use of group function [1111]</p>
</blockquote>
<p>I have tried substituting the <code>AVG(Height) > 100</code> with <code>Height > 100</code> and the problem seems to be somewhere around there. Any ideas how to solve this?</p>
| [
{
"answer_id": 74391699,
"author": "It_is_Chris",
"author_id": 9177877,
"author_profile": "https://Stackoverflow.com/users/9177877",
"pm_score": 3,
"selected": true,
"text": "import ast\n\nnew_dict = ast.literal_eval(test)\n"
},
{
"answer_id": 74391772,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 2,
"selected": false,
"text": "json"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4636470/"
] |
74,391,760 | <pre><code>def get_student_list():
iStr = ""
stdlist = []
x = 1
while not iStr == "quit":
iStr = input(f'Please enter a new student name, ("quit" if no more student)')
if not iStr == "quit":
stdlist.append(iStr)
elif iStr == "":
print("Empty student name is not allowed.")
x += 1
print(f'The whole class list is {sum(stdList)}')
</code></pre>
<p>What's wrong and how do I fix it?</p>
<p>I'm expecting the user input student into list and end when they type quit. Or when it's empty, print empty student name is not allowed</p>
| [
{
"answer_id": 74391821,
"author": "Hai Vu",
"author_id": 459745,
"author_profile": "https://Stackoverflow.com/users/459745",
"pm_score": 0,
"selected": false,
"text": "stdlist"
},
{
"answer_id": 74391938,
"author": "Sembei Norimaki",
"author_id": 20396240,
"author_profile": "https://Stackoverflow.com/users/20396240",
"pm_score": 1,
"selected": true,
"text": "def get_student_list():\n stdlist = []\n\n while True:\n iStr = input('Please enter a new student name, (\"quit\" if no more student)')\n if iStr == \"quit\":\n return stdlist \n elif iStr == \"\":\n print(\"Empty student name is not allowed.\")\n else: \n stdlist.append(iStr)\n\nstdList = get_student_list()\nprint(f\"You have a total of {len(stdList)} students:\")\nfor i, name in enumerate(stdList):\n print(f\" {i+1}) {name}\")\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20470075/"
] |
74,391,782 | <p>So the this dictionary is basically from a txt file and I formatted in order to have the same format as its supposed to have in order for my other definitions to work. The problem I'm having is that the for the loadInventory function, dictionary works inside the function but outside even though I've returned the dictionary the value doesn't return. The other definitions had no problem returning the dictionary or its values.</p>
<pre><code>def addProduct(dictionary):
prod_id = input("Enter prod ID: ")
prod_name = input("Enter prod name: ")
prod_input = input("Enter prod desc: ")
prod_quantity = int(input("Enter prod quality: "))
dictionary[prod_id] = [prod_name,prod_input,prod_quantity]
return dictionary
def saveInventory(dictionary):
save = open('inventory.dat', 'w')
for key, value in dictionary.items():
save.write(key + '\n')
save.write(value[0] + '\n')
save.write(value[1] + '\n')
save.write(str(value[2]) + '\n')
save.close()
return dictionary
def loadInventory(dictionary):
dicty = {}
n = 4
with open('inventory.dat','r') as file:
your_list = [line.strip() for line in file.readlines()]
final = [your_list[i * n:(i + 1) * n] for i in range((len(your_list) + n - 1) // n )]
dictionary= dict((value[0], value[1:]) for value in final)
print(dictionary)
return dictionary
dictionary= {}
prodID = ""
#the actual code for the main menu
loop = True
while loop:
menu()
menuoption = int(input("Enter Choice: "))
if menuoption == 1:
addProduct(dictionary)
elif menuoption == 7:
loadInventory(dictionary)
elif menuoption == 8:
saveInventory(dictionary)
</code></pre>
<p>Again I tried everything to get the dicitonary in that function to output but I'm at my wits end. Any help will be much appreciated!</p>
| [
{
"answer_id": 74391868,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 2,
"selected": true,
"text": " # this looks like it never gets used for anything\n dicty = {} \n"
},
{
"answer_id": 74391930,
"author": "Code-Apprentice",
"author_id": 1440565,
"author_profile": "https://Stackoverflow.com/users/1440565",
"pm_score": 0,
"selected": false,
"text": "return"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20470030/"
] |
74,391,797 | <p>I have this:</p>
<pre><code>let time = store.time;
const run = setInterval(() => {
const delay = store.delay;
setTimeout(() => {
console.log("Execute event....");
}, delay * 1000);
time--;
if (time === 0) {
clearInterval(run);
}
}, 1000);
</code></pre>
<p>I just want to run a process indicating a time and delaying the time at the same time, for example:</p>
<p>time=10 ; delay=2, then the process will be executed when the time is equal to: 2, 4, 6, 8 and 10</p>
<p>time=10 ; delay=3, then the process will be executed when the time is equal to: 3, 6 and 9</p>
<p>time=10 ; delay=4, then the process will be executed when the time is equal to: 4 and 8</p>
<p>time=10 ; delay=5, then the process will be executed when the time is equal to: 5 and 10</p>
<p>It's not currently working that way, it's only running 10 times, why??</p>
| [
{
"answer_id": 74391868,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 2,
"selected": true,
"text": " # this looks like it never gets used for anything\n dicty = {} \n"
},
{
"answer_id": 74391930,
"author": "Code-Apprentice",
"author_id": 1440565,
"author_profile": "https://Stackoverflow.com/users/1440565",
"pm_score": 0,
"selected": false,
"text": "return"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19950248/"
] |
74,391,842 | <p>I have a list of numbers of varying lengths stored in a file, like this...</p>
<pre><code>98
132145
132324848
4435012341
1254545221
2314565447
</code></pre>
<p>I need a function that looks through the list and counts every number that is 10 digits in length and begins with the number 1. I have stored the list in both a .txt and a .csv with no luck. I think a big part of the problem is that the numbers are integers, not strings.</p>
<pre><code>
`import regex
with open(r"C:\Desktop\file.csv") as file:
data = file.read()
x = regex.findall('\d+', data)
def filterNumberOne(n):
if(len(n)==10:
for i in n:
if(i.startswith(1)):
return True
else:
return False
one = list(filter(filterNumberOne, x))
print(len(one))`
</code></pre>
| [
{
"answer_id": 74392334,
"author": "romain gal",
"author_id": 9612932,
"author_profile": "https://Stackoverflow.com/users/9612932",
"pm_score": 0,
"selected": false,
"text": "# Get your file content as a string.\nwith open(r\"C:\\Desktop\\file.csv\") as f:\n s = \" \".join([l.rstrip(\"\\n\").strip() for l in f])\n\n# Look for the 10 digits number starting with a one.\nnb = [n for n in s.split(' ') if len(n)==10 and n[0]=='1']\n"
},
{
"answer_id": 74439857,
"author": "kyblueraider",
"author_id": 20469699,
"author_profile": "https://Stackoverflow.com/users/20469699",
"pm_score": -1,
"selected": false,
"text": "def filterNumberOne(n):\n if (len(n)==10:\n if str(n)[0] == '1':\n return True\n else:\n return False\none = list(filter(filterNumberOne, x ))\nprint(len(one))\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20469699/"
] |
74,391,854 | <p>We created several views postgresql 12 (not materialized views) which include nested queries and multiple joins.
we are facing a strange behavior, are noticing that some views are disappearing from the view list and others are remaining. is this related to Database configuration.</p>
<p>Are we missing some configuration?</p>
| [
{
"answer_id": 74398317,
"author": "Laurenz Albe",
"author_id": 6464308,
"author_profile": "https://Stackoverflow.com/users/6464308",
"pm_score": 2,
"selected": true,
"text": "DROP"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/523008/"
] |
74,391,865 | <p>I am just getting started with OOP, so I apologise in advance if my question is as obvious as 2+2. :)</p>
<p>Basically I created a class that adds attributes and methods to a panda data frame. That's because I am sometimes looking to do complex but repetitive tasks like merging with a bunch of other tables, dropping duplicates, etc. So it's pleasant to be able to do that in just one go with a predefined method. For example, I can create an object like this:</p>
<pre><code>mysupertable = MySupperTable(original_dataframe)
</code></pre>
<p>And then do:</p>
<pre><code>mysupertable.complex_operation()
</code></pre>
<p>Where original_dataframe is the original panda data frame (or object) that is defined as an attribute to the class. Now, this is all good and well, but if I want to print (or just access) that original data frame I have to do something like</p>
<pre><code>print(mysupertable.original_dataframe)
</code></pre>
<p>Is there a way to have that happening "by default" so if I just do:</p>
<pre><code>print(mysupertable)
</code></pre>
<p>it will print the original data frame, rather than the memory location?</p>
<p>I know there are the <em>str</em> and <em>rep</em> methods that can be implemented in a class which return default string representations for an object. I was just wondering if there was a similar magic method (or else) to just default showing a particular attribute. I tried looking this up but I think I am somehow not finding the right words to describe what I want to do, because I can't seem to be able to find an answer.</p>
<p>Thank you!
Cheers</p>
| [
{
"answer_id": 74391907,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 4,
"selected": true,
"text": "MySupperTable"
},
{
"answer_id": 74391931,
"author": "Dakeyras",
"author_id": 1857909,
"author_profile": "https://Stackoverflow.com/users/1857909",
"pm_score": 1,
"selected": false,
"text": "print()"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12159955/"
] |
74,391,887 | <p>I want to change the color of all elements with <li> tags to red.</p>
<p>I'm doing:-</p>
<pre><code>document.getElementsByTagName("li").style.color = "red"
</code></pre>
<p>This isn't working. But it's working with querySelectorAll method and getElementsByClassName method.</p>
<p>Does it mean that I can't use this technique with getElementsByTagName or am I doing it wrong?</p>
| [
{
"answer_id": 74391907,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 4,
"selected": true,
"text": "MySupperTable"
},
{
"answer_id": 74391931,
"author": "Dakeyras",
"author_id": 1857909,
"author_profile": "https://Stackoverflow.com/users/1857909",
"pm_score": 1,
"selected": false,
"text": "print()"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19464505/"
] |
74,391,916 | <p>I've got 2 arrays:</p>
<p>$array1 = ('1','2','7','9')
$array2 = ('7','9','1','2')</p>
<p>These collections are dynamically changed and I need to add the values from the first array to second. I need to create a condition if.... and check... if these arrays are equals - do nothing.</p>
<p>But, if the first array has new value for example it becomes $array1 = ('1','2','7','9', '6') and second array doesn't have such value</p>
<p>then I need to add this '6' new value to the second array...so the second array will become $array2 = ('7','9','1','2', '6')... please help to achieve it.</p>
<p>Please note that values in 2 arrays could be in different order it doesn't matter, the goal is to have the same values inside 2 arrays.</p>
| [
{
"answer_id": 74392003,
"author": "Mathias R. Jessen",
"author_id": 712649,
"author_profile": "https://Stackoverflow.com/users/712649",
"pm_score": 2,
"selected": false,
"text": "$array2 = @($array1;$array2) |Sort-Object -Unique\n"
},
{
"answer_id": 74392016,
"author": "mklement0",
"author_id": 45375,
"author_profile": "https://Stackoverflow.com/users/45375",
"pm_score": 2,
"selected": false,
"text": "$array2"
},
{
"answer_id": 74392042,
"author": "Santiago Squarzon",
"author_id": 15339544,
"author_profile": "https://Stackoverflow.com/users/15339544",
"pm_score": 1,
"selected": false,
"text": "IsSupersetOf"
},
{
"answer_id": 74392118,
"author": "jmhpecds",
"author_id": 20338838,
"author_profile": "https://Stackoverflow.com/users/20338838",
"pm_score": 0,
"selected": false,
"text": "-notcontains"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18644650/"
] |
74,391,929 | <p>Maybe somebody could help me. I don't understand what is wrong with my code.</p>
<p>I want loop through the ArrayList, get the index value of each element (index number itself) and add these index values to another array. Don't ask me why =))</p>
<p>Here's my code:</p>
<pre><code>List<Integer> a = new ArrayList<>();
a.add(2);
a.add(5);
a.add(1);
List<Integer> b = new ArrayList<>();
for (int i = 0; i < a.size(); i++) {
b.add(a.indexOf(i));
}
System.out.println("array b: " + b);
</code></pre>
<p>Output: array b: [-1, 2, 0]</p>
<p>But my expected output is: [0, 1, 2]</p>
<p>Maybe it's a very simple question but I'm really stuck and don't understand why the output is so strange.</p>
| [
{
"answer_id": 74392003,
"author": "Mathias R. Jessen",
"author_id": 712649,
"author_profile": "https://Stackoverflow.com/users/712649",
"pm_score": 2,
"selected": false,
"text": "$array2 = @($array1;$array2) |Sort-Object -Unique\n"
},
{
"answer_id": 74392016,
"author": "mklement0",
"author_id": 45375,
"author_profile": "https://Stackoverflow.com/users/45375",
"pm_score": 2,
"selected": false,
"text": "$array2"
},
{
"answer_id": 74392042,
"author": "Santiago Squarzon",
"author_id": 15339544,
"author_profile": "https://Stackoverflow.com/users/15339544",
"pm_score": 1,
"selected": false,
"text": "IsSupersetOf"
},
{
"answer_id": 74392118,
"author": "jmhpecds",
"author_id": 20338838,
"author_profile": "https://Stackoverflow.com/users/20338838",
"pm_score": 0,
"selected": false,
"text": "-notcontains"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16730985/"
] |
74,391,970 | <p>React Native List with Map Method</p>
<p>What I want to achieve,
I want when click item then a new Item (I preferer add a new custom View) is added below the Selected item.</p>
<blockquote>
<p>Expo Snack code>
<a href="https://snack.expo.dev/@stefanosalexandrou/tenacious-french-fries" rel="nofollow noreferrer">https://snack.expo.dev/@stefanosalexandrou/tenacious-french-fries</a></p>
</blockquote>
<p><a href="https://i.stack.imgur.com/KjL2N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KjL2N.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74392003,
"author": "Mathias R. Jessen",
"author_id": 712649,
"author_profile": "https://Stackoverflow.com/users/712649",
"pm_score": 2,
"selected": false,
"text": "$array2 = @($array1;$array2) |Sort-Object -Unique\n"
},
{
"answer_id": 74392016,
"author": "mklement0",
"author_id": 45375,
"author_profile": "https://Stackoverflow.com/users/45375",
"pm_score": 2,
"selected": false,
"text": "$array2"
},
{
"answer_id": 74392042,
"author": "Santiago Squarzon",
"author_id": 15339544,
"author_profile": "https://Stackoverflow.com/users/15339544",
"pm_score": 1,
"selected": false,
"text": "IsSupersetOf"
},
{
"answer_id": 74392118,
"author": "jmhpecds",
"author_id": 20338838,
"author_profile": "https://Stackoverflow.com/users/20338838",
"pm_score": 0,
"selected": false,
"text": "-notcontains"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20379858/"
] |
74,391,992 | <p>As mentioned I have a vector of 1D matrice, such as:</p>
<pre><code>P_predefined = [[.3 .4 .2 .1], [.2 .3 .5 0.], [.1 0. .8 .1], [.4 0. 0. .6]]
</code></pre>
<p>I would like to turn it into a matrix of 2D, I tried to use vcat, for which I expected to behave like vstack in Python, but it doesn't work.</p>
<pre><code>vcat(algorithm.predefinedP)
</code></pre>
<p>It still returns a vector</p>
<pre><code>[[0.3 0.4 0.2 0.1], [0.2 0.3 0.5 0.0], [0.1 0.0 0.8 0.1], [0.4 0.0 0.0 0.6]] #Vector{Matrix{Float64}}
</code></pre>
<p>How should I do it in the right way?</p>
| [
{
"answer_id": 74392069,
"author": "phipsgabler",
"author_id": 1346276,
"author_profile": "https://Stackoverflow.com/users/1346276",
"pm_score": 2,
"selected": false,
"text": "vcat(A...)"
},
{
"answer_id": 74393162,
"author": "Eric Hanson",
"author_id": 20471121,
"author_profile": "https://Stackoverflow.com/users/20471121",
"pm_score": 4,
"selected": true,
"text": "stack"
},
{
"answer_id": 74394120,
"author": "AboAmmar",
"author_id": 3943170,
"author_profile": "https://Stackoverflow.com/users/3943170",
"pm_score": 1,
"selected": false,
"text": "vcat"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74391992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13241995/"
] |
74,392,036 | <p>I'm trying to make a website for a fake company and im struggling with putting an image and a dropdown on the same line</p>
<p>This is what I tried :</p>
<pre><code><body>
<img src="Kharabora Coding-1 (1).png" height="150px" class="img">
<form style="background-color: #ffffff">
<div class="dropdown" style="padding-left: 1300px;">
<button class="dropbtn"><a href="#" class="a-a">LATEST WORK</a></button>
<div class="dropdown-content">
</div>
</div>
<div class="dropdown3" style="padding-left: 75px;">
<button class="dropbtn3"><a href="#" class="a-2">WHAT WE DO</a></button>
<div class="dropdown-content3">
</div>
</div>
<div class="dropdown2" style="padding-left: 75px;">
<button class="dropbtn2"><a href="#" class="a-1">ABOUT</a></button>
<div class="dropdown-content2">
</div>
</div>
</form>
</div>
</div>
</body>
</code></pre>
<p>and it ended up looking like this : <a href="https://i.stack.imgur.com/kUtvN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kUtvN.png" alt="enter image description here" /></a></p>
<p>Please help</p>
| [
{
"answer_id": 74392069,
"author": "phipsgabler",
"author_id": 1346276,
"author_profile": "https://Stackoverflow.com/users/1346276",
"pm_score": 2,
"selected": false,
"text": "vcat(A...)"
},
{
"answer_id": 74393162,
"author": "Eric Hanson",
"author_id": 20471121,
"author_profile": "https://Stackoverflow.com/users/20471121",
"pm_score": 4,
"selected": true,
"text": "stack"
},
{
"answer_id": 74394120,
"author": "AboAmmar",
"author_id": 3943170,
"author_profile": "https://Stackoverflow.com/users/3943170",
"pm_score": 1,
"selected": false,
"text": "vcat"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20470296/"
] |
74,392,040 | <p>I have a function which takes a array of GitHub repository names and then I want to send a request with every repository, to get the data about used languages in this repository and add it to an array. It looks like this:</p>
<pre><code>function getRepositoryLanguages(owner, repos) {
var stats = [];
repos.forEach(async (repoName) => {
try {
repoLang = await axios.get(
`https://api.github.com/repos/${owner}/${repoName}/languages`,
{
headers: {
Authorization: "token ${token}",
},
}
);
stats.push(repoLang.data, repoName);
} catch (error) {
console.log(error);
}
});
return stats;
}
</code></pre>
<p>I want to get language statistic for every reposository and then store it in array called <code>stats</code>.
The thing is that this function return an empty array, when I am doing something like this:</p>
<pre><code>getRepositoryNames(username).then((repos) => {
console.log(getRepositoryLanguages(username, repos));
});
</code></pre>
<p>I just get an <code>[]</code>.</p>
<p>Does anyone knows how to write this function properly with keeping in mind that those functions will be used in the <code>app.get(/stats)</code> route?</p>
| [
{
"answer_id": 74392216,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 2,
"selected": false,
"text": ".forEach"
},
{
"answer_id": 74392281,
"author": "ezhupa99",
"author_id": 8665500,
"author_profile": "https://Stackoverflow.com/users/8665500",
"pm_score": 1,
"selected": false,
"text": "/**\n * \n * @param owner Owner of repository\n * @param repos All his public repos\n * @returns Language statistics\n */\nasync function getRepositoryLanguages(owner, repos) {\n\n /**\n * language statistics\n */\n let stats = [];\n\n for (let index = 0; index < repos.length; index++) {\n const repoName = repos[index];\n\n const response = await axios.get(\n `https://api.github.com/repos/${owner}/${repoName}/languages`, {\n headers: {\n Authorization: \"token ${token}\",\n },\n }\n )\n\n stats.push({\n name: repoName,\n languages: response.data\n });\n };\n\n return stats;\n}\n\ngetRepositoryNames(username).then(async(repos) => {\n console.log(await getRepositoryLanguages(username, repos));\n});\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17885211/"
] |
74,392,043 | <pre><code>banword = ["/","\n",'"',"'","Badword","*","badword","badword","badword"]
okword = ["","","","","f","","Badword","badword","badword"]
for c in range (1,len(commentaries) + 1):
azpeo = commentaries[c]
print(azpeo)
for c in range(len(banword)):
azpeo.replace(banword[c],okword[c])
commentaries[c] = azpeo
</code></pre>
<p>So here, i am trying to delete bad word from sentences that are contained in a dictionnary, the dictionnary look like that :</p>
<pre><code>commentaries = {1 : "sentences", 2 : "sentences"}```
But nothing is changing at all and i can't understand why ?
</code></pre>
<p>I tried removing characters with <code>.replace</code> method by stocking each value in a variable and then using <code>.replace</code> but this does not seems to work ?</p>
| [
{
"answer_id": 74392119,
"author": "assume_irrational_is_rational",
"author_id": 11622508,
"author_profile": "https://Stackoverflow.com/users/11622508",
"pm_score": 2,
"selected": true,
"text": "replace"
},
{
"answer_id": 74392269,
"author": "Iulian St",
"author_id": 19333216,
"author_profile": "https://Stackoverflow.com/users/19333216",
"pm_score": 0,
"selected": false,
"text": "azpeo = azpeo.replace(banword[c],okword[c])\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20457318/"
] |
74,392,046 | <p>We have a few controllers that were written in a way that allows the <code>Error [ERR_HTTP_HEADERS_SENT]</code> error to be sent.</p>
<p>For context this happens in code similar to...
<em>This is a <strong>very</strong> contrived example</em></p>
<pre><code>try{
if(someCheck) { res.status(400).send({someStatus}); }
/* other code */
}catch(e){ res.status(500).send({error}); }
</code></pre>
<p>In the example above if the <code>someCheck</code> causes the 400 to be sent and then the "other code" triggers an exception we would receive the headers sent error as mentioned.</p>
<p>My question to help mitigate this...
Is there an eslint rule or could a custom rule be created that would require either...</p>
<pre><code>return res.status(400).send({someStatus});
/* or */
res.status(400).send({someStatus});
return;
</code></pre>
<p>I'd prefer the later, but really the goal is to warn/error if <code>send()</code> is called and doesn't have a correlated return statement.</p>
| [
{
"answer_id": 74392119,
"author": "assume_irrational_is_rational",
"author_id": 11622508,
"author_profile": "https://Stackoverflow.com/users/11622508",
"pm_score": 2,
"selected": true,
"text": "replace"
},
{
"answer_id": 74392269,
"author": "Iulian St",
"author_id": 19333216,
"author_profile": "https://Stackoverflow.com/users/19333216",
"pm_score": 0,
"selected": false,
"text": "azpeo = azpeo.replace(banword[c],okword[c])\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/718003/"
] |
74,392,077 | <p>I have a variable with a lot of categories, individuals were asked to choose their first 3 choices. So the choices are <code>A</code>, <code>B</code>, <code>C</code> and <code>D</code> here (It's true that in my database there are more than 4 possible choices)</p>
<pre><code>`var1:choice1`<-c("A","B","C")
`var1:choice2`<-c("B","C","A")
`var1:choice3`<-c("C","D","B")
id=1:3
mydata<-data.frame(id,`var1:choice1`,`var1:choice2`,`var1:choice3`)
</code></pre>
<p>Now I want to change the choices into an dummy variables, so that I can have the number of occurrences of each choice.
I should have this table below:</p>
<pre><code> var1.A var1.B var1.C var1.D
1 1 1 1 0
2 0 1 1 1
3 1 1 1 0
</code></pre>
| [
{
"answer_id": 74392148,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 2,
"selected": false,
"text": "mydata %>% \n pivot_longer(-id) %>% \n mutate(var = paste0(substr(name, 1, 5), value)) %>% \n select(id, var, value) %>% \n pivot_wider(names_from = var, values_from = value, values_fn = length, values_fill = 0)\n\n# A tibble: 3 × 5\n id var1.A var1.B var1.C var1.D\n <int> <int> <int> <int> <int>\n1 1 1 1 1 0\n2 2 0 1 1 1\n3 3 1 1 1 0\n"
},
{
"answer_id": 74392154,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 1,
"selected": false,
"text": "pivot_wider"
},
{
"answer_id": 74392156,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": false,
"text": "table(rep(mydata[[1]], 3), paste0('var1.', unlist(mydata[-1])))\n \n var1.A var1.B var1.C var1.D\n 1 1 1 1 0\n 2 0 1 1 1\n 3 1 1 1 0\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11652655/"
] |
74,392,105 | <p>I'm trying to insert text into Entry and when I try to run this code I get an error message:</p>
<p><code>"System.ArgumentException: 'Parameter "parameter" (object) cannot be of type Pension.ViewsModels.MainViewModel, as the command type requires an argument of type Pension.Models.Order. (Parameter 'parameter')'"</code></p>
<p>but I in the VerticalStackLayout say x:DataType="model:Order" and send in CommandParameter="{Binding .}" to send the Order Object. So i not understand the problem</p>
<p>Thanks !</p>
<p>and I get the error here</p>
<pre><code>{
using Pension.ViewsModels;
namespace Pension.View;
public partial class MainPage : ContentPage
{
public MainPage(MainViewModel vm)
{
InitializeComponent();
BindingContext = vm;//here the error
}
}
}
</code></pre>
<p>the function i want to send the object</p>
<pre><code>{
[RelayCommand]
async Task Continue(Order order)
{
//Order order = new Order()
//{
// DateStart = dateStart,
// DateEnd = dateEnd,
// DogName = dogName
//};
await Shell.Current.GoToAsync(nameof(ShowOrderPage), true, new Dictionary<string, object>
{
{"Order", order}
});
}
}
</code></pre>
<pre><code>{<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:model="clr-namespace:Pension.Models"
xmlns:viewmodel="clr-namespace:Pension.ViewsModels"
x:DataType="viewmodel:MainViewModel"
x:Class="Pension.Views.MainPage"
BackgroundColor="#F2F2F2">
<VerticalStackLayout Margin="0,20,0,0" Spacing="10" FlowDirection="RightToLeft">
<Label Text="הזמנת פנסיון לכלב" FontSize="40" HorizontalOptions="Center" Margin="5"/>
<Label Text="לפני שנתחיל נשמח לדעת מה התאריך בו תרצו להתארח אצלנו" HorizontalOptions="Center" FontSize="20" FontFamily="op-light"/>
<Grid Padding="20" Background="#FFFFFF" Margin="54">
<Grid.Shadow>
<Shadow Brush="#000"
Offset="5,0"
Opacity="0.26"/>
</Grid.Shadow>
<VerticalStackLayout Spacing="10" x:DataType="model:Order">
<Label Text="בחירת תאריך" FontSize="30" HorizontalOptions="Center" Margin="0,0,0,15"/>
<Frame x:Name="DateStart" CornerRadius="0" Padding="10,0">
<DatePicker MinimumDate="01/01/2022"
MaximumDate="12/31/2025"
Date="{Binding DateStart}"/>
</Frame>
<Frame CornerRadius="0" Padding="10,0">
<DatePicker x:Name="DateEnd" MinimumDate="01/01/2022"
MaximumDate="12/31/2025"
Date="{Binding DateEnd}" />
</Frame>
<Frame CornerRadius="0" Padding="10,0">
<Entry x:Name="dogName" Placeholder="שם הכלב/ה" Text="{Binding DogName}"/>
</Frame>
<Button Text="המשך" BackgroundColor="#EEBF3E"
TextColor="Black" CornerRadius="0"
Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:MainViewModel}},Path=ContinueCommand}"
CommandParameter="{Binding .}">
<Button.Shadow>
<Shadow Brush="#ccccd0"
Offset="3,6"
Opacity="1"/>
</Button.Shadow>
</Button>
</VerticalStackLayout>
</Grid>
</VerticalStackLayout>
</ContentPage>}
</code></pre>
| [
{
"answer_id": 74392148,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 2,
"selected": false,
"text": "mydata %>% \n pivot_longer(-id) %>% \n mutate(var = paste0(substr(name, 1, 5), value)) %>% \n select(id, var, value) %>% \n pivot_wider(names_from = var, values_from = value, values_fn = length, values_fill = 0)\n\n# A tibble: 3 × 5\n id var1.A var1.B var1.C var1.D\n <int> <int> <int> <int> <int>\n1 1 1 1 1 0\n2 2 0 1 1 1\n3 3 1 1 1 0\n"
},
{
"answer_id": 74392154,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 1,
"selected": false,
"text": "pivot_wider"
},
{
"answer_id": 74392156,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": false,
"text": "table(rep(mydata[[1]], 3), paste0('var1.', unlist(mydata[-1])))\n \n var1.A var1.B var1.C var1.D\n 1 1 1 1 0\n 2 0 1 1 1\n 3 1 1 1 0\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13622774/"
] |
74,392,110 | <p>I want to do something like this:</p>
<pre><code>=MYFUNC(my_number, limit_down, limit_up)
</code></pre>
<p>If the number goes out of limits, bring it to the closest limit and some examples, what I want:</p>
<pre><code>=MYFUNC(1, 4, 8) ==> 4
=MYFUNC(5, 4, 8) ==> 5
=MYFUNC(6, 4, 8) ==> 6
=MYFUNC(8, 4, 8) ==> 8
=MYFUNC(9, 4, 8) ==> 8
=MYFUNC(0, 4, 8) ==> 4
</code></pre>
<p>I can use <code>MAX</code> and <code>MIN</code> for this task, but maybe there is a more elegant way?</p>
| [
{
"answer_id": 74392672,
"author": "Ping",
"author_id": 20288037,
"author_profile": "https://Stackoverflow.com/users/20288037",
"pm_score": 1,
"selected": false,
"text": "=LAMBDA(INT,MIN,MAX,\n IF(INT <= MIN, MIN, IF(INT>= MAX, MAX, INT))\n)(my_number, limit_down, limit_up)\n"
},
{
"answer_id": 74393034,
"author": "The God of Biscuits",
"author_id": 18645332,
"author_profile": "https://Stackoverflow.com/users/18645332",
"pm_score": 3,
"selected": true,
"text": "=min(max(number,lower_limit),upper_limit)\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19540382/"
] |
74,392,142 | <p>My application uses OpenID to authenticate the user.</p>
<p>The first page is more of a splash screen that hands the user to a webpage to authorise if needed or just perform a background refresh of the token the navigate to the main screen.</p>
<p>I'm unsure of how to start the authentication flow without a button click</p>
<pre><code>@Composable
fun LoginScreen(viewModel: LoginViewModel) {
val ctx = LocalContext.current
AppTheme {
Screen()
}
viewModel.performLogin(ctx)
}
</code></pre>
<p>Doing the above works, but it then gets called again when the app navigates to the main screen.</p>
<pre><code>fun loginComplete(navController: NavHostController) {
navController.navigate("main")
}
@Composable
fun MyApp(viewModel: LoginViewModel) {
val navController = rememberNavController()
viewModel.setOnLoginCompete(navController, ::loginComplete)
NavHost(navController, startDestination = "login") {
composable(route = "login") {
LoginScreen(viewModel)
}
composable(route = "main") {
MainScreen()
}
}
}
</code></pre>
<p>I don't think I'm supposed to call the performLogin function like I am in a Composable function, but I can't see another way. What am I missing?</p>
| [
{
"answer_id": 74392453,
"author": "Steyrix",
"author_id": 7221362,
"author_profile": "https://Stackoverflow.com/users/7221362",
"pm_score": 3,
"selected": true,
"text": "@Composable\nfun OnLifecycleEvent(onEvent: (owner: LifecycleOwner, event:Lifecycle.Event) -> Unit) {\n val eventHandler = rememberUpdatedState(onEvent)\n val lifecycleOwner = rememberUpdatedState(LocalLifecycleOwner.current)\n\n DisposableEffect(lifecycleOwner.value) {\n val lifecycle = lifecycleOwner.value.lifecycle\n val observer = LifecycleEventObserver { owner, event ->\n eventHandler.value(owner, event)\n }\n\n lifecycle.addObserver(observer)\n onDispose {\n lifecycle.removeObserver(observer)\n }\n }\n}\n"
},
{
"answer_id": 74400936,
"author": "Vahid Garousi",
"author_id": 5909910,
"author_profile": "https://Stackoverflow.com/users/5909910",
"pm_score": 0,
"selected": false,
"text": "@HiltViewModel\nclass LoginViewModel @Inject constructor(\n private val savedStateHandle: SavedStateHandle\n) : ViewModel(), DefaultLifecycleObserver {\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/655703/"
] |
74,392,143 | <p>Can i showDialog inside a function without passing context?</p>
<pre><code>void test(){
showDialog(context: context, builder: (_) => AlertDialog(
content: Column(
children: [
Row(
children: const [
Icon(Icons.check_circle, color: Colors.green,),
Text("Hi"),
],
)
],
),
));
}
</code></pre>
<p>Sorry i didn't explain very well, without passing context to function, not to showDialog</p>
| [
{
"answer_id": 74392453,
"author": "Steyrix",
"author_id": 7221362,
"author_profile": "https://Stackoverflow.com/users/7221362",
"pm_score": 3,
"selected": true,
"text": "@Composable\nfun OnLifecycleEvent(onEvent: (owner: LifecycleOwner, event:Lifecycle.Event) -> Unit) {\n val eventHandler = rememberUpdatedState(onEvent)\n val lifecycleOwner = rememberUpdatedState(LocalLifecycleOwner.current)\n\n DisposableEffect(lifecycleOwner.value) {\n val lifecycle = lifecycleOwner.value.lifecycle\n val observer = LifecycleEventObserver { owner, event ->\n eventHandler.value(owner, event)\n }\n\n lifecycle.addObserver(observer)\n onDispose {\n lifecycle.removeObserver(observer)\n }\n }\n}\n"
},
{
"answer_id": 74400936,
"author": "Vahid Garousi",
"author_id": 5909910,
"author_profile": "https://Stackoverflow.com/users/5909910",
"pm_score": 0,
"selected": false,
"text": "@HiltViewModel\nclass LoginViewModel @Inject constructor(\n private val savedStateHandle: SavedStateHandle\n) : ViewModel(), DefaultLifecycleObserver {\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7385152/"
] |
74,392,152 | <p>we're developping an app that will run as a service. One of the feature would be to download file at given URL (ex PDF) and save it into the download folder so user can load it from a specific application (Avenza Maps).</p>
<p>All the download process should be without any user interaction since it's by a service that run in the background.</p>
<p>i've added the following permission:</p>
<p><strong>AndroidManifest.xml</strong></p>
<pre><code><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
<application
android:requestLegacyExternalStorage="true"
</code></pre>
<p>whatever i'll try i got the following error</p>
<pre><code>java.io.FileNotFoundException: /storage/emulated/0/Download/name.pdf (Permission denied)
</code></pre>
<p>how can i get the permission to write on Download folder (this is system Download folder)
without having to open an activity to save the file?</p>
<p>i'll try multiple solution yet(2 day of google) without success</p>
<p>for now as stated we target API 28 (android 9)
we will later target other API since we provide the device to the client so we develop only for the API our device have.</p>
| [
{
"answer_id": 74392453,
"author": "Steyrix",
"author_id": 7221362,
"author_profile": "https://Stackoverflow.com/users/7221362",
"pm_score": 3,
"selected": true,
"text": "@Composable\nfun OnLifecycleEvent(onEvent: (owner: LifecycleOwner, event:Lifecycle.Event) -> Unit) {\n val eventHandler = rememberUpdatedState(onEvent)\n val lifecycleOwner = rememberUpdatedState(LocalLifecycleOwner.current)\n\n DisposableEffect(lifecycleOwner.value) {\n val lifecycle = lifecycleOwner.value.lifecycle\n val observer = LifecycleEventObserver { owner, event ->\n eventHandler.value(owner, event)\n }\n\n lifecycle.addObserver(observer)\n onDispose {\n lifecycle.removeObserver(observer)\n }\n }\n}\n"
},
{
"answer_id": 74400936,
"author": "Vahid Garousi",
"author_id": 5909910,
"author_profile": "https://Stackoverflow.com/users/5909910",
"pm_score": 0,
"selected": false,
"text": "@HiltViewModel\nclass LoginViewModel @Inject constructor(\n private val savedStateHandle: SavedStateHandle\n) : ViewModel(), DefaultLifecycleObserver {\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19411871/"
] |
74,392,160 | <p>Im trying to flatten 2 columns from a table loaded into a dataframe as below:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">u_group</th>
<th style="text-align: left;">t_group</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">{"link": "https://hi.com/api/now/table/system/2696f18b376bca0", "value": "2696f18b376bca0"}</td>
<td style="text-align: left;">{"link": "https://hi.com/api/now/table/system/2696f18b376bca0", "value": "2696f18b376bca0"}</td>
</tr>
<tr>
<td style="text-align: left;">{"link": "https://hi.com/api/now/table/system/99b27bc1db761f4", "value": "99b27bc1db761f4"}</td>
<td style="text-align: left;">{"link": "https://hi.com/api/now/table/system/99b27bc1db761f4", "value": "99b27bc1db761f4"}</td>
</tr>
</tbody>
</table>
</div>
<p>I want to separate them and get them as:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">u_group.link</th>
<th style="text-align: left;">u_group.value</th>
<th style="text-align: left;">t_group.link</th>
<th style="text-align: left;">t_group.value</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">https://hi.com/api/now/table/system/2696f18b376bca0</td>
<td style="text-align: left;">2696f18b376bca0</td>
<td style="text-align: left;">https://hi.com/api/now/table/system/2696f18b376bca0</td>
<td style="text-align: left;">2696f18b376bca0</td>
</tr>
<tr>
<td style="text-align: left;">https://hi.com/api/now/table/system/99b27bc1db761f4</td>
<td style="text-align: left;">99b27bc1db761f4</td>
<td style="text-align: left;">https://hi.com/api/now/table/system/99b27bc1db761f4</td>
<td style="text-align: left;">99b27bc1db761f4</td>
</tr>
</tbody>
</table>
</div>
<p>I used the below code, but wasnt successful.</p>
<pre><code>import ast
from pandas.io.json import json_normalize
df12 = spark.sql("""select u_group,t_group from tbl""")
def only_dict(d):
'''
Convert json string representation of dictionary to a python dict
'''
return ast.literal_eval(d)
def list_of_dicts(ld):
'''
Create a mapping of the tuples formed after
converting json strings of list to a python list
'''
return dict([(list(d.values())[1], list(d.values())[0]) for d in ast.literal_eval(ld)])
A = json_normalize(df12['u_group'].apply(only_dict).tolist()).add_prefix('link.')
B = json_normalize(df['u_group'].apply(list_of_dicts).tolist()).add_prefix('value.')
</code></pre>
<p>TypeError: 'Column' object is not callable</p>
<p>Kindly help or suggest if any other code would work better.</p>
| [
{
"answer_id": 74392453,
"author": "Steyrix",
"author_id": 7221362,
"author_profile": "https://Stackoverflow.com/users/7221362",
"pm_score": 3,
"selected": true,
"text": "@Composable\nfun OnLifecycleEvent(onEvent: (owner: LifecycleOwner, event:Lifecycle.Event) -> Unit) {\n val eventHandler = rememberUpdatedState(onEvent)\n val lifecycleOwner = rememberUpdatedState(LocalLifecycleOwner.current)\n\n DisposableEffect(lifecycleOwner.value) {\n val lifecycle = lifecycleOwner.value.lifecycle\n val observer = LifecycleEventObserver { owner, event ->\n eventHandler.value(owner, event)\n }\n\n lifecycle.addObserver(observer)\n onDispose {\n lifecycle.removeObserver(observer)\n }\n }\n}\n"
},
{
"answer_id": 74400936,
"author": "Vahid Garousi",
"author_id": 5909910,
"author_profile": "https://Stackoverflow.com/users/5909910",
"pm_score": 0,
"selected": false,
"text": "@HiltViewModel\nclass LoginViewModel @Inject constructor(\n private val savedStateHandle: SavedStateHandle\n) : ViewModel(), DefaultLifecycleObserver {\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8259636/"
] |
74,392,162 | <p>The update for Visual Studio 17.4 has changed the font in the text editor, so that it is very thin and a bit of a strain on the eyes to the read. How can you change this back, short of rolling back the update?</p>
<p>Please note that I've searched a little bit for this, and I see the following setting:</p>
<p><a href="https://i.stack.imgur.com/Oe5sDl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Oe5sDl.png" alt="enter image description here" /></a></p>
<p>But I have no idea what to set this to. People have mentioned the Consolas font on one or more other posts, but that doesn't seem to match what was there before. I've tried checking <code>Bold</code>. Etc.</p>
<p>I just need it back to the "normal Visual Studio font" that was there before the update to 17.4, which has enough thickness in the letters that it's not uncomfortable to read.</p>
| [
{
"answer_id": 74395442,
"author": "Tyler",
"author_id": 6804626,
"author_profile": "https://Stackoverflow.com/users/6804626",
"pm_score": 2,
"selected": false,
"text": "Cascadia Mono SemiBold"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/279112/"
] |
74,392,179 | <p>In the matrix of my report where there is a blank I would like to display a zero.</p>
<p>This is my expression</p>
<pre><code> =Sum(IIF(Fields!CondSubstantive.Value = True , 1, 0))
</code></pre>
<p>I've been trying similar things to the below but not having much success</p>
<pre><code>=Sum(IIF(isnothing(Fields!CondSubstantive.Value = True , 1, 0)) , 0, Sum(IIF(Fields!CondSubstantive.Value = True , 1, 0))
</code></pre>
| [
{
"answer_id": 74392555,
"author": "Alan Schofield",
"author_id": 1775389,
"author_profile": "https://Stackoverflow.com/users/1775389",
"pm_score": 2,
"selected": true,
"text": "=VAL(Sum(IIF(Fields!CondSubstantive.Value = True , 1, 0)))\n"
},
{
"answer_id": 74397784,
"author": "Cedrick Clemente",
"author_id": 6269652,
"author_profile": "https://Stackoverflow.com/users/6269652",
"pm_score": 0,
"selected": false,
"text": "=Sum(IIF (IsNothing(Fields!CondSubstantive.Value) = True, 0, 1))\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10021463/"
] |
74,392,207 | <p>I wanted to use BigQuery's array aggregate function, array_concat_agg over a window function. It doesn't look like this is possible - and actually, I might have a second issue regarding the accessibility of my window function to an inner query.</p>
<p>Here is my current SQL:</p>
<pre class="lang-sql prettyprint-override"><code>WITH data AS (
SELECT 1 AS id, 1 AS iteration_recency, DATE("2022-07-09") AS start_date, DATE("2022-07-31") AS end_date
UNION ALL
SELECT 1 AS id, 2 AS iteration_recency, DATE("2022-08-01") AS start_date, DATE("2022-08-15") AS end_date
UNION ALL
SELECT 1 AS id, 3 AS iteration_recency, DATE("2022-07-01") AS start_date, DATE("2022-07-04") AS end_date
UNION ALL
SELECT 1 AS id, 4 AS iteration_recency, DATE("2022-07-25") AS start_date, DATE("2022-08-04") AS end_date
UNION ALL
SELECT 1 AS id, 5 AS iteration_recency, DATE("2022-07-01") AS start_date, DATE("2022-07-31") AS end_date
UNION ALL
SELECT 2 AS id, 1 AS iteration_recency, DATE("2022-08-01") AS start_date, DATE("2022-10-30") AS end_date
UNION ALL
SELECT 2 AS id, 2 AS iteration_recency, DATE("2022-07-05") AS start_date, DATE("2022-07-22") AS end_date
UNION ALL
SELECT 2 AS id, 3 AS iteration_recency, DATE("2022-08-06") AS start_date, DATE("2022-08-24") AS end_date
)
SELECT
id,
iteration_recency,
(
SELECT MIN(`dates` IN UNNEST(
ARRAY_CONCAT_AGG(GENERATE_DATE_ARRAY(`start_date`, `end_date`)) OVER `newer_iterations`
)
)
FROM UNNEST(GENERATE_DATE_ARRAY(`start_date`, `end_date`)) AS `dates`
) AS date_range_contained_in_more_recent_iterations
FROM data
WINDOW `newer_iterations` AS (
PARTITION BY id
ORDER BY iteration ASC
ROWS BETWEEN 1 PRECEDING AND UNBOUNDED PRECEDING
)
</code></pre>
<p>The purpose of this query is to determine whether a date range is fully represented by more recent iterations of the same id. Regarding the use case, you can imagine this would be used in some monitoring whereby when iteration 3 fails for some date range but that date range is covered by more recent iteration(s), it's not a problem. I can't do something clever with min/max because more recent iterations may have overlapped the failed date range but perhaps not completely covered it between them.</p>
<p>The slightly crazy <code>MIN in UNEST()</code> stuff draws inspiration from <a href="https://stackoverflow.com/a/60391888/17277930">this answer</a> which provides a neat way for working out if all items from arrayA are in arrayB.</p>
<p>Currently, I get the error, <strong>Unrecognized window alias newer_iterations at [24:76]</strong>
I was actually expecting to get the error (paraphrased), "the OVER clause is not supported for ARRAY_CONCAT_AGG" because according to the docs, it is not - but it looks like I'm misunderstanding the availability of the outer window function in the inner function.</p>
<p>Maybe there's a way of doing this with a join but I think the logical requirement of ARRAY_CONCAT_AGG operating over a frame clause of <code>1 ROW PRECEDING AND UNBOUNDED PRECEDING</code> seems unavoidable to me.</p>
<p>The result I was expecting was:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>iteration_recency</th>
<th>date_range_contained_in_more_recent_iterations</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>false</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>false</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
<td>false</td>
</tr>
<tr>
<td>1</td>
<td>4</td>
<td>true</td>
</tr>
<tr>
<td>1</td>
<td>5</td>
<td>false</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>false</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>false</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>true</td>
</tr>
</tbody>
</table>
</div>
<p><strong>P.s. this table renders fine in the edit question window - no idea what is wrong with it so if someone can edit my text to fix, I'd be grateful.</strong></p>
<p>Grateful for any pointers, thanks!</p>
| [
{
"answer_id": 74392555,
"author": "Alan Schofield",
"author_id": 1775389,
"author_profile": "https://Stackoverflow.com/users/1775389",
"pm_score": 2,
"selected": true,
"text": "=VAL(Sum(IIF(Fields!CondSubstantive.Value = True , 1, 0)))\n"
},
{
"answer_id": 74397784,
"author": "Cedrick Clemente",
"author_id": 6269652,
"author_profile": "https://Stackoverflow.com/users/6269652",
"pm_score": 0,
"selected": false,
"text": "=Sum(IIF (IsNothing(Fields!CondSubstantive.Value) = True, 0, 1))\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17277930/"
] |
74,392,212 | <p>I have a day name such as Monday. and the current day is Wednesday. Now i want to get the date of next coming Monday. How can i do it with a best practice in a very short way. right now i am trying to do this with bunch of if conditions and it made things messy and very difficult.</p>
<p>here is my code :</p>
<pre><code>day_time = timezone.now()
current_day = day_time.strftime("%A")
coming_day = "monday"
if coming_day == current_day:
day_time = day_time
if coming_day=="sunday" and coming_day == "monday":
day_time = day_time + timedelta(days=6)
if coming_day=="sunday" and coming_day == "tuesday":
day_time = day_time + timedelta(days=5)
if coming_day=="sunday" and coming_day == "wednesday":
day_time = day_time + timedelta(days=4)
if coming_day=="sunday" and coming_day == "thursday":
day_time = day_time + timedelta(days=3)
.........so on
</code></pre>
| [
{
"answer_id": 74392509,
"author": "Jay",
"author_id": 8677071,
"author_profile": "https://Stackoverflow.com/users/8677071",
"pm_score": 3,
"selected": true,
"text": "day_time"
},
{
"answer_id": 74392588,
"author": "The Lazy Graybeard",
"author_id": 9608497,
"author_profile": "https://Stackoverflow.com/users/9608497",
"pm_score": 0,
"selected": false,
"text": "dateutils"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20286415/"
] |
74,392,218 | <p>I need to filter array of objects with the existing filter, for example</p>
<pre><code>const students= [
{
id: 1,
name: "Alan",
subjects: [
{
name: "math",
mark: 5
},
{
name: "poetry",
mark: 4
},
{
name: "physics",
mark: 3
}
]
},
{
id: 2,
name: "Joe",
subjects: [
{
name: "geography",
mark: 5
},
{
name: "music",
mark: 5
},
{
name: "literature",
mark: 3
}
]
},
{
id: 3,
name: "Megan",
subjects: [
{
name: "math",
mark: 4
},
{
name: "physics",
mark: 3
}
]
}
];
</code></pre>
<pre><code>const filters = [
{
name: "math",
mark: 5
},
{
name: "physics",
mark: 3
}
];
</code></pre>
<p>From <strong>students</strong> array I need to get <strong>Alan</strong> and <strong>Megan</strong> according to existing <strong>filters</strong>. So if at least one subject from filters with mark exists in students, I need to get that student.</p>
<p>I tried this</p>
<pre><code>const common: any = students.filter((x: any) => {
return filters.indexOf(x.skills) !== -1;
});
console.log(common);
</code></pre>
<p>But the common array is empty so it didn't work</p>
| [
{
"answer_id": 74392509,
"author": "Jay",
"author_id": 8677071,
"author_profile": "https://Stackoverflow.com/users/8677071",
"pm_score": 3,
"selected": true,
"text": "day_time"
},
{
"answer_id": 74392588,
"author": "The Lazy Graybeard",
"author_id": 9608497,
"author_profile": "https://Stackoverflow.com/users/9608497",
"pm_score": 0,
"selected": false,
"text": "dateutils"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6356416/"
] |
74,392,230 | <p>I manage an array of Objects like this</p>
<p><a href="https://i.stack.imgur.com/41HKp.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/41HKp.jpg" alt="enter image description here" /></a></p>
<p>I see that this is the same</p>
<p><a href="https://i.stack.imgur.com/Gsgny.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gsgny.jpg" alt="enter image description here" /></a></p>
<p>But when I try this</p>
<p><a href="https://i.stack.imgur.com/18JZu.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/18JZu.jpg" alt="enter image description here" /></a></p>
<p>Any idea, please?</p>
<p>Thanks</p>
| [
{
"answer_id": 74392509,
"author": "Jay",
"author_id": 8677071,
"author_profile": "https://Stackoverflow.com/users/8677071",
"pm_score": 3,
"selected": true,
"text": "day_time"
},
{
"answer_id": 74392588,
"author": "The Lazy Graybeard",
"author_id": 9608497,
"author_profile": "https://Stackoverflow.com/users/9608497",
"pm_score": 0,
"selected": false,
"text": "dateutils"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3367720/"
] |
74,392,253 | <p>I have 2 classes. AlchemicalStorage class is used to store the AlchemicalElement objects.</p>
<pre><code>class AlchemicalElement:
def __init__(self, name: str):
self.name = name
def __repr__(self):
return f'<AE: {self.name}>'
class AlchemicalStorage:
def __init__(self):
self.storage_list = []
</code></pre>
<p>I already have a function that adds elements to AlchemicalStorage. What I need is a function that removes and returns previously added element from the storage by its name.</p>
<p>What I have so far:</p>
<pre><code>def add(self, element: AlchemicalElement):
if isinstance(element, AlchemicalElement):
self.storage_list.append(element)
else:
raise TypeError()
def pop(self, element_name: str) -> AlchemicalElement or None:
"""
Remove and return previously added element from storage by its name.
If there are multiple elements with the same name, remove only the one that was added most recently to the
storage. If there are no elements with the given name, do not remove anything and return None.
:param element_name: Name of the element to remove.
:return: The removed AlchemicalElement object or None.
"""
self.storage_list.append(element_name)
return self.storage_list.pop()
</code></pre>
<p>Obviously pop() function is incorrect. I can't figure out what the logic is here.</p>
<p>An example of what I want to achieve:</p>
<pre><code>storage.add(AlchemicalElement('Fire'))
storage.add(AlchemicalElement('Water'))
storage.add(AlchemicalElement('Water'))
print(storage.pop('Water') == element_three) # True
print(storage.pop('Water') == element_two) # True
</code></pre>
| [
{
"answer_id": 74392399,
"author": "jprebys",
"author_id": 3268228,
"author_profile": "https://Stackoverflow.com/users/3268228",
"pm_score": 2,
"selected": true,
"text": "def pop(self, element_name: str) -> AlchemicalElement | None:\n for element in reversed(self.storage_list):\n if element.name == element_name:\n self.storage_list.remove(element)\n return element\n return None\n"
},
{
"answer_id": 74394863,
"author": "agtoever",
"author_id": 3056710,
"author_profile": "https://Stackoverflow.com/users/3056710",
"pm_score": 0,
"selected": false,
"text": "__eq__"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20421646/"
] |
74,392,277 | <p>I'm just about finished with a project but I'm getting these two errors. Does anyone know how I can fix this?</p>
<p>src\App.js Line 118:4: React Hook useEffect has a missing dependency: 'getMoviesData'. Either include it or remove the dependency array react-hooks/exhaustive-deps</p>
<p>src\components\MusicPlayer.jsx Line 48:9: React Hook useEffect has a missing dependency: 'togglePlay'. Either include it or remove the dependency array react-hooks/exhaustive-deps</p>
<p>Any help is greatly appreciated!</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function App() {
//State
const [movies, setMovies] = useState([])
const [topMovies, setTopMovies] = useState([])
const [kidsMovies, setKidsMovies] = useState([])
const [setKidsTv] = useState([])
//KidsTv
const [setTvShows] = useState([])
//TvShows
const [kidsTvSeries, setKidsTvSeries] = useState([])
//API URL
const url = 'https://api.themoviedb.org/3/discover/movie?api_key=&with_genres=28/';
const tvUrl = 'https://api.themoviedb.org/3/tv/popular?api_key=&language=en-US&page=1';
const kidsMovieURL = 'https://api.themoviedb.org/3/discover/movie?api_key=&certification_country=US&certification.lte=G&with_genres=16&include_adult=false&sort_by=popularity.desc';
const kidsTvURL = 'https://api.themoviedb.org/3/tv/popular?api_key=8&language=en-US&page=1&with_genres=16&include_adult=false&sort_by=popularity.desc';
const topPicks = 'https://api.themoviedb.org/3/movie/top_rated?api_key=&language=en-US&page=1';
// const kidsAnimatedMovies = 'https://api.themoviedb.org/3/discover/movie?api_key=1f7c961ae4f02a23e0968d449c15bc98&with_genres=16';
const kidsSeries = 'https://api.themoviedb.org/3/discover/tv?api_key=&with_genres=10762'
//Async function to fetch API
async function getMoviesData (url, tvUrl, topPicks, kidsMovieURL, kidsTvUrl, kidsSeries) {
await fetch(url).then(res => res.json()).then(data => setMovies(data.results))
await fetch(topPicks).then(res => res.json()).then(data => setTopMovies(data.results))
await fetch(tvUrl).then(res => res.json()).then(data => setTvShows(data.results))
await fetch(kidsMovieURL).then(res => res.json()).then(data => setKidsMovies(data.results))
await fetch(kidsTvUrl).then(res => res.json()).then(data => setKidsTv(data.results))
await fetch(kidsSeries).then(res => res.json()).then(data => setKidsTvSeries(data.results))
}
//Use Effect
useEffect(() => {
getMoviesData(url, tvUrl, topPicks, kidsMovieURL, kidsTvURL, kidsSeries);
}, [])
const [songClicked, setSongClicked] = useState({})</code></pre>
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React, { useState, useEffect, useRef } from 'react'
function MusicPlayer({songs}) {
//Test
const songFiles = songs.map(song => song.songFile)
//Hooks
const audioPlayer = useRef()
//State
const [index, setIndex] = useState(0);
const { songClicked} = useContext(songContext)
// setSongClicked
const [currentSong, setCurrentSong] = useState(songClicked);
const [isPlaying, setisPlaying] = useState(false);
const [volume, setVolume] = useState(30);
const [mute, setMute] = useState(false);
useEffect(() => {
setCurrentSong(songClicked)
if (songClicked) {
audioPlayer.current.play()
}
if (songClicked) {
togglePlay()
}
}, [songClicked])
useEffect(() => {
if(audioPlayer) {
audioPlayer.current.volume = volume / 100;
}
}, [volume]);
function togglePlay() {
if(!isPlaying) {
audioPlayer.current.play()
} else {
audioPlayer.current.pause()
}
// setisPlaying(prev => !prev)
setisPlaying(isPlaying => !isPlaying)
}
function toggleSkipForward() {
if(index >= songFiles.length - 1) {
setIndex(0);
audioPlayer.current.src = songFiles[0];
audioPlayer.current.play();
} else {
setIndex(prev => prev + 1);
audioPlayer.current.src = songFiles[index + 1];
audioPlayer.current.play();
}
}
function toggleSkipBackward() {
if(index > 0) {
setIndex(prev => prev -1);
audioPlayer.current.src = songFiles[index -1];
audioPlayer.current.play();
}
}
function VolumeBtns() {
return mute
? <VolumeOffIcon sx={{color: 'lime', '&:hover': {color: 'white'}}} onClick={() => setMute(!mute)} />
: volume <= 20 ? <VolumeMuteIcon sx={{color: 'lime', '&:hover': {color: 'white'}}} onClick={() => setMute(!mute)} />
: volume <= 75 ? <VolumeDownIcon sx={{color: 'lime', '&:hover': {color: 'white'}}} onClick={() => setMute(!mute)} />
: <VolumeUpIcon sx={{color: 'lime', '&:hover': {color: 'white'}}} onClick={() => setMute(!mute)} />
}
return (
<div className='music-player-container'>
<audio src={currentSong} ref={audioPlayer} muted={mute} webkit-playsinline="true" playsInline="true" autoplay="" />
<div className="controls">
<div className="volume">
<IconButton>
<VolumeBtns />
</IconButton>
<Slider min={0} max={100} value={volume} onChange={(e,v) => setVolume(v)}
defaultValue={50}
sx={{
width: 100,
color: 'success.main',
margin: '20px',
}} />
</div>
<div className="control-panel">
<IconButton onClick={toggleSkipBackward}>
<SkipPreviousIcon
sx={{
margin: '10px',
cursor: 'pointer',
color: 'silver', '&:hover': {color: 'blue'}
}} />
</IconButton>
{/* Play/Pause */}
{!isPlaying
? <IconButton onClick={togglePlay}>
<PlayArrowIcon sx={{ margin: '10px', cursor: 'pointer', color: 'silver', '&:hover': {color: 'blue'} }} />
</IconButton>
: <IconButton onClick={togglePlay}>
<PauseIcon sx={{ margin: '10px', cursor: 'pointer', color: 'silver', '&:hover': {color: 'blue'} }} />
</IconButton>
}
{/* Play/Pause */}
<IconButton onClick={toggleSkipForward}>
<SkipNextIcon
sx={{
margin: '10px',
cursor: 'pointer',
color: 'silver', '&:hover': {color: 'blue'}
}} />
</IconButton>
</div>
</div>
</div>
)
}
export default MusicPlayer</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74392504,
"author": "Jack Ecuyer",
"author_id": 14559762,
"author_profile": "https://Stackoverflow.com/users/14559762",
"pm_score": 2,
"selected": true,
"text": "getMoviesData()"
},
{
"answer_id": 74392547,
"author": "arp",
"author_id": 10841628,
"author_profile": "https://Stackoverflow.com/users/10841628",
"pm_score": 0,
"selected": false,
"text": "const getMoviesData = useCallback(async (url, tvUrl, topPicks, kidsMovieURL, kidsTvUrl, kidsSeries) => {\n await fetch(url).then(res => res.json()).then(data => setMovies(data.results))\n await fetch(topPicks).then(res => res.json()).then(data => setTopMovies(data.results))\n await fetch(tvUrl).then(res => res.json()).then(data => setTvShows(data.results))\n await fetch(kidsMovieURL).then(res => res.json()).then(data => setKidsMovies(data.results))\n await fetch(kidsTvUrl).then(res => res.json()).then(data => setKidsTv(data.results))\n await fetch(kidsSeries).then(res => res.json()).then(data => setKidsTvSeries(data.results))\n},[])\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20165435/"
] |
74,392,306 | <p>First of all this is my first question here...</p>
<p>Ok, and now my problem:
I created a formula that generates a dynamic Query if you are searching for data in multiple sheets. I just write the names of the sheets in green field and it changes the Query.
<a href="https://i.stack.imgur.com/3RUTa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3RUTa.png" alt="screenshot" /></a>
The text for the Query is correct, but now I want this to by the actual formula in a cell to display the data.</p>
<p>If I use the = and add the cell with the Query text, it copy the text. I tried the INDIRECT formula, but it does the same.
How can I use a this dynamic text to be my Query to dispaly the data depending on the amount of names in the green field?</p>
<p>EDIT: As advised by user doubleunary (as mentioned, this is my first time), I'm going to rephrase the problem.
In an spreadsheet a manager imputs for every task the amount a worker has made. He creates an new sheet for each date and imputs the data for that day. Each day can have different rows of data. The boss wants a spreadsheet that display in one sheet all that has been done in the current month. I used Query because you can easy join data from multiple sheets and ignor the empty rows.
But the problem is, that every day a new sheet is added with a new "name" (date). And the easyest way I found tho make a dynamic Query, without the Boss to manualy edit the Query, was to create a text with TEXTJOIN formula, in witch he ony needs to enter the new "name" (date).
If there is a better was, please share, but it should not be in App Script if possible.</p>
<p>Thank you.</p>
| [
{
"answer_id": 74392504,
"author": "Jack Ecuyer",
"author_id": 14559762,
"author_profile": "https://Stackoverflow.com/users/14559762",
"pm_score": 2,
"selected": true,
"text": "getMoviesData()"
},
{
"answer_id": 74392547,
"author": "arp",
"author_id": 10841628,
"author_profile": "https://Stackoverflow.com/users/10841628",
"pm_score": 0,
"selected": false,
"text": "const getMoviesData = useCallback(async (url, tvUrl, topPicks, kidsMovieURL, kidsTvUrl, kidsSeries) => {\n await fetch(url).then(res => res.json()).then(data => setMovies(data.results))\n await fetch(topPicks).then(res => res.json()).then(data => setTopMovies(data.results))\n await fetch(tvUrl).then(res => res.json()).then(data => setTvShows(data.results))\n await fetch(kidsMovieURL).then(res => res.json()).then(data => setKidsMovies(data.results))\n await fetch(kidsTvUrl).then(res => res.json()).then(data => setKidsTv(data.results))\n await fetch(kidsSeries).then(res => res.json()).then(data => setKidsTvSeries(data.results))\n},[])\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20470447/"
] |
74,392,339 | <p>I'm a beginner with Django 4.1. I'm using the model to edit a form and render it on a webpage. This runs correctly. When I click on submit, my function recognizes the <em>POST</em> method but never validates the form. I'm sure that I have to fix a bug in my models or my form but I don't know where.</p>
<p>in <em><strong>models.py</strong></em>:</p>
<pre class="lang-py prettyprint-override"><code>class Auction(models.Model):
HOUSE = "HOU"
MOTORS = "MOT"
PROPERTY = "PPT"
HOBBIES = "HOB"
INFORMATION_TECHNOLOGY = "IT"
MUSIC = "MUS"
BOOK = "BOK"
CATEGORY_CHOICES = [
(HOUSE, "All for your House"),
(MOTORS, "Car, Moto, Boat"),
(PROPERTY, "Houses, flats, manors"),
(HOBBIES, "Hobbies"),
(INFORMATION_TECHNOLOGY, "Laptop, Desktop, Mobile Phone"),
(MUSIC, "CD, Musical Intrusments"),
(BOOK, "Books, Comics,...")
]
ONE = 1
THREE = 3
SEVEN = 7
FOURTEEN = 14
DURATION_CHOICES = [
(ONE, "1 day"),
(THREE, "3 days"),
(SEVEN, "7 days"),
(FOURTEEN, "14 days")
]
title = models.CharField(max_length=64)
description = models.TextField(max_length=500, blank=True)
creation_date = models.DateTimeField(auto_now_add=True)
image = models.URLField(null=True, blank=True, default="")
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="seller")
duration = models.CharField(max_length=7, choices=DURATION_CHOICES, default=SEVEN)
category = models.CharField(max_length=3, choices=CATEGORY_CHOICES, default=INFORMATION_TECHNOLOGY)
price = models.DecimalField(max_digits=12, decimal_places=2, default=0.0)
def __str__(self):
return f"{self.id}: {self.title}"
</code></pre>
<p>in <em><strong>forms.py</strong></em>:</p>
<pre class="lang-py prettyprint-override"><code>class CreateListingsForm(forms.ModelForm):
class Meta:
model = Auction
fields = ["title", "description", "image", "category", "duration", "price"]
</code></pre>
<p>and in <em><strong>views.py</strong></em>:</p>
<pre class="lang-py prettyprint-override"><code>def create(request):
if request.method == "POST":
form = CreateListingsForm(request.POST)
form.instance.user = request.user
form.instance.creation_date = datetime.now()
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "auctions/listings.html", {
"form": form
})
else:
form = CreateListingsForm()
return render(request, "auctions/listings.html", {
"form": form
})
</code></pre>
<p>I've tried to handle instances like below. I've tried to override <code>__init__</code> in my form too.</p>
<p>Edit:
I do <code>print(form.error)</code> and the result is:</p>
<pre><code><ul class="errorlist"><li>duration<ul class="errorlist"><li>Select a valid choice. 7 is not one of the available choices.</li></ul></li></ul>
</code></pre>
<p>May the problem be my default value?</p>
<p>Edit2:</p>
<p>The error was the type of the field so it works when I changed it to <code>IntegerField</code>.</p>
| [
{
"answer_id": 74392504,
"author": "Jack Ecuyer",
"author_id": 14559762,
"author_profile": "https://Stackoverflow.com/users/14559762",
"pm_score": 2,
"selected": true,
"text": "getMoviesData()"
},
{
"answer_id": 74392547,
"author": "arp",
"author_id": 10841628,
"author_profile": "https://Stackoverflow.com/users/10841628",
"pm_score": 0,
"selected": false,
"text": "const getMoviesData = useCallback(async (url, tvUrl, topPicks, kidsMovieURL, kidsTvUrl, kidsSeries) => {\n await fetch(url).then(res => res.json()).then(data => setMovies(data.results))\n await fetch(topPicks).then(res => res.json()).then(data => setTopMovies(data.results))\n await fetch(tvUrl).then(res => res.json()).then(data => setTvShows(data.results))\n await fetch(kidsMovieURL).then(res => res.json()).then(data => setKidsMovies(data.results))\n await fetch(kidsTvUrl).then(res => res.json()).then(data => setKidsTv(data.results))\n await fetch(kidsSeries).then(res => res.json()).then(data => setKidsTvSeries(data.results))\n},[])\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19836827/"
] |
74,392,376 | <p>I have the following form in an angular component:</p>
<pre><code>this.signUpForm = this.fb.group({
agencyName: ['', [Validators.required],
taxId: ['', [Validators.required],
address: ['', Validators.required],
city: ['', Validators.required],
state: ['', Validators.required],
zip: ['', Validators.required],
county: ['', Validators.required],
firstName: ['', Validators.required],
lastName: ['', Validators.required],
mobile: ['', Validators.required],
phone: [''],
});
</code></pre>
<p>What is the correct way to assign a control in this form to a variable?</p>
<pre><code>this.control = this.signUpForm.controls.state;
</code></pre>
<p>or</p>
<pre><code>this.control = this.signUpForm.controls.['state'];
</code></pre>
<p>In Angular 14 I am getting syntax error highlighting for the first annotation, while in previous versions it has worked.</p>
| [
{
"answer_id": 74393001,
"author": "Chady BAGHDADI",
"author_id": 16227834,
"author_profile": "https://Stackoverflow.com/users/16227834",
"pm_score": 2,
"selected": true,
"text": "this.control = this.signUpForm..get('state')\n"
},
{
"answer_id": 74393988,
"author": "Dinuka Silva",
"author_id": 20457576,
"author_profile": "https://Stackoverflow.com/users/20457576",
"pm_score": 0,
"selected": false,
"text": "get agencyName(){\n return this.signUpForm.get('agencyName');\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1819315/"
] |
74,392,398 | <p>I don't get the RedemptionLoader work with Visual Basic .Net (Visual Studio 2019) at all.</p>
<p>I'm trying to avoid registering Redemption.dll (Redemption64.dll) on users machines.
I tried to following instructions from <a href="https://www.dimastr.com/redemption/security.htm#redemptionloader" rel="nofollow noreferrer">https://www.dimastr.com/redemption/security.htm#redemptionloader</a>
to switch my application to the unregistered version with the RedemptionLoader.
But I just can't get the version with the RedemptionLoader to work at all.</p>
<p>I'm using Visual Studio 2019, Visual Basic.
I added RedemptionLoader.vb to the project. Among the references is reference to the Interop.Redemption.</p>
<p>In the project folder are</p>
<ul>
<li>Interop.Redemption.dll</li>
<li>Redemption.dll</li>
<li>Redemption64.dll</li>
</ul>
<p>The two Redemption DLLs have been deregistered.</p>
<p>In the program I try the following:</p>
<pre><code>Dim RDOSession As Redemption.session
RDOSession = RedemptionLoader.new_RDOSession()
</code></pre>
<p>But already:</p>
<pre><code>Dim RDOSession As Redemption.session
</code></pre>
<p>-> it does not work (Redemption is underlined).</p>
<p>This would be possible:</p>
<pre><code>Dim RDOSession As Redemption.RedemptionLoader
</code></pre>
<p>-> but it is of no use for me.</p>
<p>I'm desperate and very thankful when I get the basics up and running.</p>
<p>Regards</p>
<p>Albert</p>
| [
{
"answer_id": 74393001,
"author": "Chady BAGHDADI",
"author_id": 16227834,
"author_profile": "https://Stackoverflow.com/users/16227834",
"pm_score": 2,
"selected": true,
"text": "this.control = this.signUpForm..get('state')\n"
},
{
"answer_id": 74393988,
"author": "Dinuka Silva",
"author_id": 20457576,
"author_profile": "https://Stackoverflow.com/users/20457576",
"pm_score": 0,
"selected": false,
"text": "get agencyName(){\n return this.signUpForm.get('agencyName');\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20470372/"
] |
74,392,402 | <p>I am looking to try and create a small image converter that would convert HEIC files that are uploaded to a php web document to .JPG (or any other generic file format).</p>
<p>I am running PHP off a unix server and have ImageMagick installed on the server. The following command line code works from the server:</p>
<pre><code>mogrify -format jpg *.HEIC
</code></pre>
<p>I'd like to convert this command line code to PHP.</p>
<p>As mentioned I like to convert the command line formatting code to PHP. I currently have the following code set up in a basic HTML + PHP form. The file being converted is newly uploaded and not located on the server. If necessary I can upload to the server first then read form the server file.</p>
<pre><code>if($_SERVER["REQUEST_METHOD"] == "POST")
{
if(empty($_FILES['image_url']['name']))
{
echo "No File uploaded";
}
else{
$uploadedImage = fopen($_FILES['image_url']['tmp_name'], 'rb');
$image_to_convert = new Imagick();
$image_to_convert->readImageFile($uploadedImage);
$image_to_convert->setFormat("jpg");
$image_to_convert->setFileName('test.jpg');
header('Content-Type: image/jpg');
header('Content-disposition: attachment; filename='.$image_to_convert->getFileName());
header("Content-Description: File Transfer");
readfile($image_to_convert);
}
}
</code></pre>
<p>This code downloads a "test.jpg" file, but when I try to open it in Windows image viewer it displays a "It looks like we don't support this file format" message. I'm relatively new to PHP so I don't know all the tricks for output/input streams so if my code is horrible let me know.</p>
<p>Any and all help is welcome. Thanks!</p>
| [
{
"answer_id": 74393001,
"author": "Chady BAGHDADI",
"author_id": 16227834,
"author_profile": "https://Stackoverflow.com/users/16227834",
"pm_score": 2,
"selected": true,
"text": "this.control = this.signUpForm..get('state')\n"
},
{
"answer_id": 74393988,
"author": "Dinuka Silva",
"author_id": 20457576,
"author_profile": "https://Stackoverflow.com/users/20457576",
"pm_score": 0,
"selected": false,
"text": "get agencyName(){\n return this.signUpForm.get('agencyName');\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14122581/"
] |
74,392,428 | <p><strong>TL;DR</strong></p>
<p>If my <code>Content-Type "application/x-ourformat"</code> bound custom <code>TextInputFormatter</code> cannot parse the input, I want to return HTTP <code>400</code> (possibly <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/415" rel="nofollow noreferrer"><code>415</code></a>) back to the client.</p>
<p>What is the correct way to return from the implementation of <code>ReadRequestBodyAsync</code> to get the framework to return a <code>4xx</code> HTTP response?</p>
<hr />
<p>We have a custom formatter for <code>application/x-ourformat</code> built upon the <a href="https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/custom-formatters?view=aspnetcore-7.0&viewFallbackFrom=aspnetcore-2.2" rel="nofollow noreferrer"><code>TextInputFormatter</code></a> as explained in the link.</p>
<p>The example from the MS docs above does error handling as follows:</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.formatters.inputformatter.readrequestbodyasync?view=aspnetcore-7.0" rel="nofollow noreferrer">ReadRequestBodyAsync</a>:</p>
<pre><code>public override async Task<InputFormatterResult> ReadRequestBodyAsync(
InputFormatterContext context, Encoding effectiveEncoding)
{
...
return await InputFormatterResult.SuccessAsync(contact);
}
catch
{
logger.LogError("Read failed: nameLine = {nameLine}", nameLine);
return await InputFormatterResult.FailureAsync();
}
}
</code></pre>
<p>That is, if the processing of the input fails with an exception, it will return <code>FailureAsync()</code>.</p>
<p><strong>However</strong>, this will NOT result in a HTTP 400 response, instead the input object bound to the Api will simply be <code>null</code>.</p>
<p>What <em>does</em> result in a 400 response is:</p>
<ul>
<li>Throwing an exception out of <code>ReadRequestBodyAsync</code></li>
<li>Setting <code>context.ModelState.AddModelError("My Key", "Couldn't really understand you.");</code> prior to returning <code>FailureAsync</code>.</li>
</ul>
<p>But I do neither understand which one is "correct" nor do I really understand what the ModelError is supposed to represent.</p>
| [
{
"answer_id": 74393617,
"author": "jdweng",
"author_id": 5015238,
"author_profile": "https://Stackoverflow.com/users/5015238",
"pm_score": -1,
"selected": false,
"text": "HTTP/1.1 200 OK\nDate: Mon, 27 Jul 2009 12:28:53 GMT\nServer: Apache\nLast-Modified: Wed, 22 Jul 2009 19:15:56 GMT\nETag: \"34aa387-d-1568eb00\"\nAccept-Ranges: bytes\nContent-Length: 51\nVary: Accept-Encoding\nContent-Type: text/plain\nHello World! My content includes a trailing CRLF.\n"
},
{
"answer_id": 74399326,
"author": "Martin Ba",
"author_id": 321013,
"author_profile": "https://Stackoverflow.com/users/321013",
"pm_score": 0,
"selected": false,
"text": "ReadRequestBodyAsync"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/321013/"
] |
74,392,432 | <p>I would like to discover the version number of docker-compose. The format differs per version.</p>
<p>Ex: Running docker-compose --version</p>
<pre><code>docker-compose version 1.29.2, build someId
Docker Compose version v2.12.2
</code></pre>
<p>I have separate sed statements that grab the version number, but if possible I'd like to combine them.</p>
<pre><code>echo `docker-compose --version` | sed -nr 's|^docker-compose version (.*)(,.*)|\1|p'
echo `docker-compose --version` | sed -nr 's|^Docker compose version v(.*)|\1|p'
</code></pre>
<p>If I or the two regexes together using a pipe, the reference needs to change to either \1 or \3 depending where it's caught.</p>
<p>Is there a better way using sed?</p>
| [
{
"answer_id": 74392491,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 3,
"selected": true,
"text": "sed"
},
{
"answer_id": 74392494,
"author": "Charles Duffy",
"author_id": 14122,
"author_profile": "https://Stackoverflow.com/users/14122",
"pm_score": 2,
"selected": false,
"text": "[[ $string =~ $regex ]]"
},
{
"answer_id": 74392496,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 2,
"selected": false,
"text": "echo `docker-compose --version` | sed -nr 's|^[dD]ocker[ -][cC]ompose version v?([^, ]*).*|\\1|p'\n"
},
{
"answer_id": 74409943,
"author": "RavinderSingh13",
"author_id": 5866580,
"author_profile": "https://Stackoverflow.com/users/5866580",
"pm_score": 2,
"selected": false,
"text": "awk"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4726822/"
] |
74,392,439 | <p>i am triying to pull a branch in my local but i didn't have the same data like in github repository, in the terminal, says: <code>Already up to date</code>.</p>
<p>For examples in my github repository, i have a file named <code>data.json</code>, the content of this this is not the same as the <code>data.json</code> i have in my local repository.</p>
<p>Here is the github link : <a href="https://github.com/Meriemu/TestCaseLvmh/blob/feature/slider/public/data.json" rel="nofollow noreferrer">https://github.com/Meriemu/TestCaseLvmh/blob/feature/slider/public/data.json</a></p>
<p>And here is a screnshot of my local data :
<a href="https://i.stack.imgur.com/dgRN3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dgRN3.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74392491,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 3,
"selected": true,
"text": "sed"
},
{
"answer_id": 74392494,
"author": "Charles Duffy",
"author_id": 14122,
"author_profile": "https://Stackoverflow.com/users/14122",
"pm_score": 2,
"selected": false,
"text": "[[ $string =~ $regex ]]"
},
{
"answer_id": 74392496,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 2,
"selected": false,
"text": "echo `docker-compose --version` | sed -nr 's|^[dD]ocker[ -][cC]ompose version v?([^, ]*).*|\\1|p'\n"
},
{
"answer_id": 74409943,
"author": "RavinderSingh13",
"author_id": 5866580,
"author_profile": "https://Stackoverflow.com/users/5866580",
"pm_score": 2,
"selected": false,
"text": "awk"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18631280/"
] |
74,392,457 | <p>I was wondering is there a way to automate (e.g., loop) the subtraction of (<code>X2-X1</code>), (<code>X3-X1</code>), (<code>X3-X2</code>) in my <code>data</code> below and add them as three new columns to the <code>data</code>?</p>
<pre><code>m="
id X1 X2 X3
A 1 0 4
B 2 2 2
C 3 4 1"
data <- read.table(text = m, h = T)
</code></pre>
| [
{
"answer_id": 74392491,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 3,
"selected": true,
"text": "sed"
},
{
"answer_id": 74392494,
"author": "Charles Duffy",
"author_id": 14122,
"author_profile": "https://Stackoverflow.com/users/14122",
"pm_score": 2,
"selected": false,
"text": "[[ $string =~ $regex ]]"
},
{
"answer_id": 74392496,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 2,
"selected": false,
"text": "echo `docker-compose --version` | sed -nr 's|^[dD]ocker[ -][cC]ompose version v?([^, ]*).*|\\1|p'\n"
},
{
"answer_id": 74409943,
"author": "RavinderSingh13",
"author_id": 5866580,
"author_profile": "https://Stackoverflow.com/users/5866580",
"pm_score": 2,
"selected": false,
"text": "awk"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16760971/"
] |
74,392,468 | <p>This is my code:</p>
<pre><code>$arr = [
[step_1] => Array
(
[method] => getLastRealisesData
[description] => Get last realises data
[error] => null
[done] => 0
)
[step_2] => Array
(
[method] => downloadFile
[description] => Download file
[error] => null
[done] => 0
)
];
foreach($arr as $item){
$result = 0;
if($result == 0){
$item['done'] = 0;
$item['error'] = 'Error message';
break;
}
$result = 1;
}
</code></pre>
<p>My value did not update, why?
I need to update my value if I my result == 0
Mayby I need to use object or somethink else...</p>
| [
{
"answer_id": 74392564,
"author": "RiggsFolly",
"author_id": 2310830,
"author_profile": "https://Stackoverflow.com/users/2310830",
"pm_score": 2,
"selected": false,
"text": "\nforeach($arr as &$item){\n// note ^ reference\n $result = 0;\n if($result == 0){\n $item['done'] = 0;\n $item['error'] = 'Error message';\n break;\n }\n $result = 1;\n}\nunset($item); // unset the reference\n\n"
},
{
"answer_id": 74392884,
"author": "callmebob",
"author_id": 3759368,
"author_profile": "https://Stackoverflow.com/users/3759368",
"pm_score": 0,
"selected": false,
"text": "<?php\n$arr = array(1, 2, 3, 4);\nforeach ($arr as &$value) {\n $value = $value * 2;\n}\n// $arr is now array(2, 4, 6, 8)\nunset($value); // break the reference with the last element\n?>\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20166453/"
] |
74,392,477 | <p>The user input represents half of the rows in the diamonds (top triangles). If I enter the input as 9, I should have 9 rows including the center/longest line. But, underneath I only have 8 lines (I need to have 9 on the bottom too, including a copy of the line above so it’s even). I need to make it so that both of my bottom triangles also have that repeated line so there are two lines at the center having same number of asterisks. I think I insert it below my last printed line but it doesn’t work.</p>
<p>My question is: How can I have two center lines that are the same?</p>
<pre><code>rows = int(input("Please enter the amount of rows in half of the diamond:"))
#Upper triangles 1 and 2
for i in range(rows):
#spaces for triangle 1
for s in range(rows - i) :
print(" ", end="")
#stars
for stars in range((i * 2) - 1):
print("*", end="")
#space to separate triangle 1 and 2
for s in range(rows-i+1) :
print(" ", end="")
#spaces for triangle 2
for s in range (i,rows) :
print(end=" ")
#stars
for stars in range((i * 2) - 1):
print("*", end="")
print()
#new for loop under middle line: stars, how many spaces?
#Lower triangles 3 and 4
for i in range(rows,0,-1):
#spaces for triangle 3
for s in range(rows - i) :
print(" ", end="")
#stars
for stars in range((i * 2) - 1):
print("*", end="")
#space to separate triangle 3 and 4
for s in range(rows-i+1) :
print(" ", end="")
#spaces for triangle 4
for s in range(rows - i) :
print(" ", end="")
#stars
for stars in range((i * 2) - 1):
print("*", end="")
print()
if rows<=0:
print("Invalid.")
</code></pre>
| [
{
"answer_id": 74392564,
"author": "RiggsFolly",
"author_id": 2310830,
"author_profile": "https://Stackoverflow.com/users/2310830",
"pm_score": 2,
"selected": false,
"text": "\nforeach($arr as &$item){\n// note ^ reference\n $result = 0;\n if($result == 0){\n $item['done'] = 0;\n $item['error'] = 'Error message';\n break;\n }\n $result = 1;\n}\nunset($item); // unset the reference\n\n"
},
{
"answer_id": 74392884,
"author": "callmebob",
"author_id": 3759368,
"author_profile": "https://Stackoverflow.com/users/3759368",
"pm_score": 0,
"selected": false,
"text": "<?php\n$arr = array(1, 2, 3, 4);\nforeach ($arr as &$value) {\n $value = $value * 2;\n}\n// $arr is now array(2, 4, 6, 8)\nunset($value); // break the reference with the last element\n?>\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20277384/"
] |
74,392,598 | <p>I am building an angular application. A list of child controls will be dynamicly built based on the conditions in the parent control.</p>
<p>The dynamic control is embedded in the parent form:</p>
<pre><code><app-dynamic-form [searchItem]="searchItemValue"></app-dynamic-form>
</code></pre>
<p>Here is the code for the form setup:</p>
<pre><code> //form group setup
this.searchForm = this.fb.group({
category: this.fb.control('', [Validators.required]),
searchItem: this.fb.control({ value: '', disabled: true }, [Validators.required]),
dynamicFormArray: this.fb.array([])
});
</code></pre>
<p>A BehaviorSubject and JSON are used for the communication between the parent and the child dynamic component.</p>
<pre><code>private subjectFormFields = new BehaviorSubject({} as DynamicFormFieldModel[]);
currentFormFields = this.subjectFormFields.asObservable();
dynamicFormFields!: DynamicFormFieldModel[] =
[
{
id: 'firstName',
label: 'First Name',
type: 'text',
value: ''
},
...
]
updateFormFieldList(formFieldList: DynamicFormFieldModel[]) {
this.subjectFormFields.next(formFieldList);
}
</code></pre>
<p>In the dynamic form component, the dynamic contorls are built like this:</p>
<pre><code>updateDynamicForm() {
this.dynamicFormArray.clear();
//Dynamicly create form field controls and add it to the parent form
this.dynamicFormFields.forEach(formItem => {
const form = this.fb.group([]);
const formControl = this.fb.control('', formItem.validators);
form.addControl(formItem.id, formControl);
this.dynamicFormArray.push(form);
})
}
</code></pre>
<p>In the dynamic component, I have everything setup with reqired <strong>formGroupName</strong> and <strong>formControlName</strong> (which seems a source to have the same error acoording to the web research):</p>
<pre><code> <ng-container formArrayName="dynamicFormArray" *ngIf="(dynamicFormFields && dynamicFormFields.length)">
<ng-container *ngFor="let formItem of dynamicFormFields; let i = index;">
<div class="form-field">
<label>{{formItem.label}}</label>
<ng-container [ngSwitch]="formItem.type">
<!-- Input Text-->
<ng-container [formGroupName]="i" *ngSwitchCase="'text'">
<input type="text" class="form-control"
[formControlName]="formItem.id" [id]="formItem.id">
</ng-container>
...
</ng-container>
</div>
</ng-container>
</ng-container>
</code></pre>
<p>However, I still get "Cannot find control with path" error from time to time but not always. Why?</p>
<p>I googled searched "Cannot find control with path" and made sure that the formArrayName, formGroupName and formControlName are all correctly in place. and check the form building process ..</p>
| [
{
"answer_id": 74393015,
"author": "Eliseo",
"author_id": 8558186,
"author_profile": "https://Stackoverflow.com/users/8558186",
"pm_score": -1,
"selected": false,
"text": "<ng-container formArrayName=\"dynamicFormArray\" *ngIf=\"(dynamicFormFields && dynamicFormFields.length)\">\n <!--see iterate over dynamicFormArray.controls-->\n <ng-container *ngFor=\"let group of dynamicFormArray.controls; let i = index;\">\n <!--then use dynamicFormFields[i] instead of formItem-->\n <div class=\"form-field\">\n <label>{{dynamicFormFields[i].label}}</label>\n <ng-container [ngSwitch]=\"dynamicFormFields[i].type\">\n <!-- Input Text-->\n <ng-container [formGroupName]=\"i\" *ngSwitchCase=\"'text'\">\n <input type=\"text\" class=\"form-control\" \n [formControlName]=\"dynamicFormFields[i].id\" [id]=\"dynamicFormFields[i].id\">\n </ng-container>\n...\n </ng-container>\n </div>\n </ng-container>\n </ng-container>\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18246660/"
] |
74,392,603 | <p>I ran into this problem and don't know how to solve it. I need to drag and drop a point inside the map and save its new coordinates relative to the map.</p>
<p>Let's say I have a layout like in the picture I've attached. How can I get information about exactly where x or y in relation to this map I moved the element? I really need help!</p>
<p>I'm using HTML Drag And Drop, but I don't understand how to use the data that the event gives me to calculate this<a href="https://i.stack.imgur.com/9gxLT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9gxLT.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74392756,
"author": "Little_Dev",
"author_id": 19524489,
"author_profile": "https://Stackoverflow.com/users/19524489",
"pm_score": 1,
"selected": false,
"text": "function dodrop(event) {\n var dt = event.dataTransfer;\n var files = dt.files;\n\n var count = files.length;\n output(\"File Count: \" + count + \"\\n\");\n\n for (var i = 0; i < files.length; i++) {\n console.log(event);\n output(\" File \" + i + \":\\n(\" + (typeof files[i]) + \") : <\" + files[i] + \" > \" +\n files[i].name + \" \" + files[i].size + \"\\n\");\n }\n}\n\nfunction output(text) {\n document.getElementById(\"output\").textContent += text;\n //dump(text);\n}"
},
{
"answer_id": 74412761,
"author": "Vyacheslav Morozov",
"author_id": 15028649,
"author_profile": "https://Stackoverflow.com/users/15028649",
"pm_score": 1,
"selected": true,
"text": "<div class=\"map\">\n <div>\n <img :src=\"props.currentItem.map_image\" alt=\"Map\" />\n </div>\n <div\n @drop.prevent=\"onDrop($event)\"\n @dragenter.prevent\n @dragover.prevent\n class=\"map__container map__dropzone\"\n >\n <map-item\n v-for=\"item in itemsData\"\n :class=\"[`item-${item.id}`, { editable: props.isEditMapMode }]\"\n :key=\"item.id\"\n draggable\n @dragstart=\"startDrag($event, sensor)\"\n />\n </div>\n</div>\n\nconst offsetX = ref(0);\nconst offsetY = ref(0);\n\nconst startDrag = (event: DragEvent, item: IItemInterface) => {\n const rect = (event.target as HTMLElement).getBoundingClientRect();\n\n offsetX.value = event.clientX - rect.x;\n offsetY.value = event.clientY - rect.y;\n\n if (event.dataTransfer) {\n event.dataTransfer.dropEffect = 'move';\n event.dataTransfer.effectAllowed = 'move';\n event.dataTransfer.setData('itemId', item.id.toString());\n }\n};\n\nconst onDrop = (event: DragEvent) => {\n const dropZoneRect = (event.target as HTMLElement).getBoundingClientRect();\n const left = dropZoneRect.left;\n const top = dropZoneRect.top;\n\n const itemId = event.dataTransfer?.getData('itemId');\n const item = document.querySelector(`.item-${itemId}`);\n\n (sensor as HTMLElement).style.left =\n event.clientX - left - offsetX.value + 'px';\n\n (sensor as HTMLElement).style.top =\n event.clientY - top - offsetY.value + 'px';\n};\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15028649/"
] |
74,392,615 | <p>I am trying to pull data from a folder containing 300 Workbooks, each named 001, 002 etc.
I am only interested in pulling the data from column G of each file and copying it into a separate folder (each file does not have the same amount if data in row G)</p>
<p>I have been able to copy the data across, but I can't seem to get it to move past column 2 and instead writes over the previous column.</p>
<p>The output needed is:
data from column G workbook"001" pasted into "new sheet" column A
data from column G workbook"002" pasted into "new sheet" column B
and so on</p>
<p>Each file in the folder of 300 only has 1 worksheet each, each labelled: 001,002,...,300</p>
<p>This is the code I already had which results in 2 columns of data where 1 gets replaced by each new sheet instead.</p>
<p>Any help to solve this issue would be greatly appreciated.</p>
<pre><code>Sub Copy()
Dim MyFile As String
Dim Filepath As String
Dim q As Long
Dim ThisCol As Integer
Dim ThisRow As Long
Dim CurS As Worksheet
Dim CurRg As Range
Dim InfCol As Integer
Set CurS = ActiveSheet
ThisRow = ActiveCell.Row
ThisCol = ActiveCell.Column
InfCol = 1
Filepath = "C:..."
MyFile = Dir(Filepath)
Do While Len(MyFile) > 0
If MyFile = "Text to column.xlsm" Then
Exit Sub
End If
Workbooks.Open (Filepath & MyFile)
LastRow = Range("G1").CurrentRegion.Rows.Count
Range("G1", Range("G" & LastRow)).Copy ThisWorkbook.Sheets("Sheet1").Range(CurS.Cells(ThisRow, ThisCol + 1), CurS.Cells(ThisRow, ThisCol + CurS.Cells(ThisRow, InfCol).Value))
ActiveWorkbook.Save
ActiveWorkbook.Close
MyFile = Dir
Loop
End Sub
</code></pre>
| [
{
"answer_id": 74392756,
"author": "Little_Dev",
"author_id": 19524489,
"author_profile": "https://Stackoverflow.com/users/19524489",
"pm_score": 1,
"selected": false,
"text": "function dodrop(event) {\n var dt = event.dataTransfer;\n var files = dt.files;\n\n var count = files.length;\n output(\"File Count: \" + count + \"\\n\");\n\n for (var i = 0; i < files.length; i++) {\n console.log(event);\n output(\" File \" + i + \":\\n(\" + (typeof files[i]) + \") : <\" + files[i] + \" > \" +\n files[i].name + \" \" + files[i].size + \"\\n\");\n }\n}\n\nfunction output(text) {\n document.getElementById(\"output\").textContent += text;\n //dump(text);\n}"
},
{
"answer_id": 74412761,
"author": "Vyacheslav Morozov",
"author_id": 15028649,
"author_profile": "https://Stackoverflow.com/users/15028649",
"pm_score": 1,
"selected": true,
"text": "<div class=\"map\">\n <div>\n <img :src=\"props.currentItem.map_image\" alt=\"Map\" />\n </div>\n <div\n @drop.prevent=\"onDrop($event)\"\n @dragenter.prevent\n @dragover.prevent\n class=\"map__container map__dropzone\"\n >\n <map-item\n v-for=\"item in itemsData\"\n :class=\"[`item-${item.id}`, { editable: props.isEditMapMode }]\"\n :key=\"item.id\"\n draggable\n @dragstart=\"startDrag($event, sensor)\"\n />\n </div>\n</div>\n\nconst offsetX = ref(0);\nconst offsetY = ref(0);\n\nconst startDrag = (event: DragEvent, item: IItemInterface) => {\n const rect = (event.target as HTMLElement).getBoundingClientRect();\n\n offsetX.value = event.clientX - rect.x;\n offsetY.value = event.clientY - rect.y;\n\n if (event.dataTransfer) {\n event.dataTransfer.dropEffect = 'move';\n event.dataTransfer.effectAllowed = 'move';\n event.dataTransfer.setData('itemId', item.id.toString());\n }\n};\n\nconst onDrop = (event: DragEvent) => {\n const dropZoneRect = (event.target as HTMLElement).getBoundingClientRect();\n const left = dropZoneRect.left;\n const top = dropZoneRect.top;\n\n const itemId = event.dataTransfer?.getData('itemId');\n const item = document.querySelector(`.item-${itemId}`);\n\n (sensor as HTMLElement).style.left =\n event.clientX - left - offsetX.value + 'px';\n\n (sensor as HTMLElement).style.top =\n event.clientY - top - offsetY.value + 'px';\n};\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20470612/"
] |
74,392,634 | <p>In python I'm trying to write nested loops in one line. I've seen a lot of examples, but in all of them the inner iterable variable is different compared to the outer one. So in my case, it won't work. Here's my try:</p>
<pre><code>my_list = [for ip in subnet for subnet in subnets]
</code></pre>
<p>where I'm getting:</p>
<pre><code>Unresolved reference 'subnet'
</code></pre>
| [
{
"answer_id": 74392724,
"author": "cmauck10",
"author_id": 19935366,
"author_profile": "https://Stackoverflow.com/users/19935366",
"pm_score": 2,
"selected": true,
"text": "my_list = [ip for subnet in subnets for ip in subnet]\n"
},
{
"answer_id": 74392737,
"author": "Ljg",
"author_id": 13603339,
"author_profile": "https://Stackoverflow.com/users/13603339",
"pm_score": -1,
"selected": false,
"text": "my_list = [[ip for ip in subnet] for subnet in subnets]\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20470733/"
] |
74,392,651 | <p>I'm trying to use the append (<code>+=</code>) operator for a JSX expression:</p>
<pre><code>let j = "";
for (let i in [1,2,3]) {
j += <span>{i}</span>;
}
</code></pre>
<p>But it unexpectedly renders as three strings, instead of HTML:</p>
<p><code>[object Object][object Object][object Object]</code></p>
| [
{
"answer_id": 74392652,
"author": "emallove",
"author_id": 712035,
"author_profile": "https://Stackoverflow.com/users/712035",
"pm_score": 2,
"selected": false,
"text": "[1,2,3].map((i) =>\n <span>{i}</span>\n);\n"
},
{
"answer_id": 74394679,
"author": "codinn.dev",
"author_id": 15755662,
"author_profile": "https://Stackoverflow.com/users/15755662",
"pm_score": 1,
"selected": false,
"text": "let j = \"\";\nfor (let i in [1,2,3]) {\n j += `<span>${i}</span>`;\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/712035/"
] |
74,392,666 | <p>I am implemented 5mins alarm app, where we can set alarm at increment of 5mins. Ex, If I open app at 01:00PM and press button three time the alarm is set for 01:05PM, 01:10PM and 01:15PM. I used AlarmManager to set the pending intent for future broadcast and in broadcast receiver I used Notification to show notification at the same time app default ringtone using MediaPlayer. While using MediaPlayer I faced issue to stop the last alarm because when first alarm starts it is okay but if first alarm rings continuously and second alarm start then multiple alarm rings at same time. How to get the same MediaPlayer Instance in all Broadcast or is any better way to handel it?</p>
<p>Unable to stop the last alarm ring because of different instances of MediaPlayer Class. So if i wanted to stop the last alarm ring and start another ring then what should i do?</p>
| [
{
"answer_id": 74392652,
"author": "emallove",
"author_id": 712035,
"author_profile": "https://Stackoverflow.com/users/712035",
"pm_score": 2,
"selected": false,
"text": "[1,2,3].map((i) =>\n <span>{i}</span>\n);\n"
},
{
"answer_id": 74394679,
"author": "codinn.dev",
"author_id": 15755662,
"author_profile": "https://Stackoverflow.com/users/15755662",
"pm_score": 1,
"selected": false,
"text": "let j = \"\";\nfor (let i in [1,2,3]) {\n j += `<span>${i}</span>`;\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16373444/"
] |
74,392,699 | <p>I am struggling with vertically aligning the text that is shown in the navbar below. I have one div that extends over the entire navbar as a container, and two child divs two cover each the right and left part of the navbar side by side. Centering it horizontally is no problem.</p>
<p>It's worth noticing that the two divs cover the navbar 50% each, so they have equal sizes.</p>
<p><a href="https://i.stack.imgur.com/Y6Jpu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y6Jpu.png" alt="This is the navbar with its icons and one part of the text i want to display, as you can see neither the text nor the icons get displayed centered vertically. The red line in the center indicates where the navbar is splitted, since the line is drawn by hand ther could be slight inaccuracys" /></a></p>
<p>I tried:</p>
<ol>
<li>Working with <code>margin: 0 auto</code> this doesn't work because I need a margin of <code>-10</code> at the left to compensate the css elements of my browser (I tried working with a normalizing script but since that didn't work as expected I left it out),</li>
<li>setting <code>box-sizing</code> to <code>border box</code>,</li>
<li>translating y to <code>-50%</code>,</li>
<li>changing the positions to <code>relative</code> on the child and <code>absolute</code> on the parent,</li>
<li>Setting <code>top</code> to <code>50%</code> (doesn't work since it displaces the navbar child containers),</li>
<li>anything with <code>display: flex</code> doesn't work, because I need the two child elements to be inline blocks to fit next to each other.</li>
</ol>
<p>Here's my code:</p>
<pre class="lang-css prettyprint-override"><code>.wrapper {
width: 100vw;
height: 2.5cm;
margin-top: -10px;
align-items: baseline;
position: relative;
}
.topnav-left {
margin-left: -10px;
background-color: #18191C;
height: 2cm;
width: 50vw;
display: inline-block;
vertical-align: top;
position: relative;
}
.topnav-right {
background-color: #18191C;
height: 2cm;
width: 50vw;
display: inline-block;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<div className="wrapper">
<div className="topnav-left">
<Link to="/About"><u>Über</u></Link>
</div>
<div className="topnav-right">
<Link to="/settings"><i class="material-icons">settings</i></Link> <!-- uses gooogle font incons -->
<Link to="/profile"><i class="material-icons">person</i></Link> <!-- uses gooogle font incons -->
</div>
</div>
</code></pre>
<p>Is there something I am missing, or perhaps a completely different idea?</p>
<p>Any help is appreciated</p>
<p>PS: there are other questions that needs help by vertically aligning text, but most of those aren't as specific on the situation;
I looked at those questions and followed little steps provided in other examples but none of these worked for me.</p>
<p><strong>Edits:</strong>
I have added my html file for clarification of my problem so the code can be understand in a better way</p>
<pre><code>
<!DOCTYPE html>
<html lang="en">
<head>
<style>
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@100&display=swap');
</style>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="icon" href="Images/logo.png" />
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <!-- Use of google font icons -->
<title>GFOS Award</title>
</head>
<body style="overflow: hidden;">
<div id="root" style="height: 100vh;" ></div>
</body>
</html>
</code></pre>
<p><a href="https://i.stack.imgur.com/eWh6s.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eWh6s.png" alt="This is what happens if i use the configuration given as an answer, since i am pretty new to react and css i have not found the source of this issue" /></a></p>
<p>This is what happens if i use the configuration given as an answer, since i am pretty new to react and css i have not found the source of this issue</p>
| [
{
"answer_id": 74392791,
"author": "goga iosebashvili",
"author_id": 20121566,
"author_profile": "https://Stackoverflow.com/users/20121566",
"pm_score": 2,
"selected": true,
"text": "\n\n.topnav-left{\nfloat: left;\nwidth: 50%;\ndisplay:flex;\nalign-items:center;\n}\n\n.topnav-right{\nfloat: right;\nwidth: 50%;\ndisplay:flex;\nalign-items:center;\n}\n"
},
{
"answer_id": 74393845,
"author": "Damian Fraustro",
"author_id": 6067627,
"author_profile": "https://Stackoverflow.com/users/6067627",
"pm_score": 0,
"selected": false,
"text": ".wrapper {\n width:100vw;\n height:2.5cm;\n display:flex;\n}\n\n.topnav-left {\n background-color:#18191C;\n width:50%;\n display:flex;\n align-items:center\n}\n\n.topnav-right {\n background-color:#18191C;\n width:50%;\n display:flex;\n align-items:center;\n justify-content:end;\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20412483/"
] |
74,392,708 | <p>I have a list like the following:</p>
<pre><code>T = [10.749957462142994, 10.90579301143351, 10.981580990083001]
</code></pre>
<p>That contains <code>timestamp</code> in a decimal format</p>
<pre><code>hours = [ int(x) for x in T ]
minutes =[ (x*60) % 60 for x in T]
print("%d:%02d"%(hours[0], minutes[0]), "%d:%02d"%(hours[1], minutes[1]), "%d:%02d"%(hours[2], minutes[2]))
['10:44', '10:54', '10:58']
</code></pre>
<p>I would like to create a list of datetime without years-month-day but just hours and minutes.</p>
<p>I tried this</p>
<pre><code>from datetime import datetime
DT = []
for i,t in enumerate(T):
string = str("%d:%02d"%(hours[i], minutes[i]))
datetime_object = datetime. strptime(string, '%H:%M')
DT.append(datetime_object)
</code></pre>
<p>However <code>DT</code> looks like the following</p>
<pre><code>DT
[datetime.datetime(1900, 1, 1, 10, 44),
datetime.datetime(1900, 1, 1, 10, 54),
datetime.datetime(1900, 1, 1, 10, 58)]
</code></pre>
<p>How can I remove the information of year, day and month and have something like:</p>
<pre><code>DT
[datetime.datetime( 10, 44),
datetime.datetime( 10, 54),
datetime.datetime( 10, 58)]
</code></pre>
| [
{
"answer_id": 74393061,
"author": "dan04",
"author_id": 287586,
"author_profile": "https://Stackoverflow.com/users/287586",
"pm_score": 2,
"selected": true,
"text": "import datetime\n\nDUMMY_DATETIME = datetime.datetime(2000, 1, 1, 0, 0)\nHOUR = datetime.timedelta(hours=1)\n\nT = [10.749957462142994, 10.90579301143351, 10.981580990083001]\nDT = [(DUMMY_DATETIME + hours * HOUR).time() for hours in T]\n"
},
{
"answer_id": 74393105,
"author": "Bharel",
"author_id": 1658617,
"author_profile": "https://Stackoverflow.com/users/1658617",
"pm_score": 1,
"selected": false,
"text": "from datetime import time, datetime, timedelta\nT = [10.749957462142994, 10.90579301143351, 10.981580990083001]\nvalues = [(datetime.min + timedelta(hours=t)).time() for t in T]\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3590067/"
] |
74,392,749 | <p>Hello I am having some trouble with removing items from selectedTags state array onClick. Please see the below react component:</p>
<p>TagPosts.tsx</p>
<pre class="lang-js prettyprint-override"><code>interface Tag {
id: string;
name: string;
}
const TagPosts: React.FC= () => {
let [tags, setTags] = useState<Tag[]>([]);
let [selectedTags, setSelectedTags] = useState<Tag[]>([]);
// STATE IS BEING UPDATED FINE WITH THE BELOW addToSelected FUNCTION
const addToSelected = (tag: Tag) => {
setSelectedTags([...selectedTags, tag]);
};
// HAVING ISSUE WITH REMOVING ITEMS FROM SELECTED ARRAY. STATE IS NOT BEING UPDATED WITH THE BELOW FUNCTION
const removeFromSelected = (tag: Tag) => {
const index = selectedTags.indexOf(tag);
const newSelectedTags = selectedTags;
newSelectedTags.splice(index, 1);
setSelectedTags(newSelectedTags);
};
const renderTags = tags.map((tag) => {
if (!selectedTags.includes(tag)) {
return (
<StyledTagBox key={tag.id} onClick={() => addToSelected(tag)}>
<Typography variant="displayTags">{tag.name}</Typography>
</StyledTagBox>
);
} else if (selectedTags.includes(tag)) {
return (
<SelectedTagBox key={tag.id} onClick={() => removeFromSelected(tag)}>
<Typography variant="displayTags" color="#fff">
{tag.name}
</Typography>
</SelectedTagBox>
);
}
});
export default TagPosts;
</code></pre>
<p>Can anyone spot the bug? The weird thing is that when i console.log the newSelectedTags variable it is showing the desired array but the setSelectedTags function in the line right after is not executing?</p>
<p>Any help would be greatly appreciated. Thanks!</p>
| [
{
"answer_id": 74392842,
"author": "SnNeposis",
"author_id": 20347565,
"author_profile": "https://Stackoverflow.com/users/20347565",
"pm_score": 1,
"selected": false,
"text": "selectedTags"
},
{
"answer_id": 74392956,
"author": "Nick Vu",
"author_id": 9201587,
"author_profile": "https://Stackoverflow.com/users/9201587",
"pm_score": 2,
"selected": false,
"text": "splice"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17481492/"
] |
74,392,773 | <p>I need to count the avg number of messages sent by distinct users_id. I have the messages under the table "comments" , and the distinct users_id under the table "user". They join under the use of another table "tickets" this way:</p>
<pre class="lang-sql prettyprint-override"><code>left outer join tickets t on c.ticket_id = t.ticket_id
left outer join "users" u on u.user_id = t.requester
</code></pre>
<p>I'm not too sure where to start from either.</p>
<pre class="lang-sql prettyprint-override"><code>select user_id,
count avg (distinct c.ticket_id)
from "comments" c
group by ticket_id
left outer join tickets t on c.ticket_id = t.ticket_id
left outer join "users" u on u.user_id = t.requester
where t.created_at between '2022-10-01' and '2022-10-31'
</code></pre>
| [
{
"answer_id": 74392842,
"author": "SnNeposis",
"author_id": 20347565,
"author_profile": "https://Stackoverflow.com/users/20347565",
"pm_score": 1,
"selected": false,
"text": "selectedTags"
},
{
"answer_id": 74392956,
"author": "Nick Vu",
"author_id": 9201587,
"author_profile": "https://Stackoverflow.com/users/9201587",
"pm_score": 2,
"selected": false,
"text": "splice"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20470674/"
] |
74,392,814 | <p>I have two lists and I need to print matching characters to string in order of characters in list 2. If there is no match, i need to print "-" instead of that character. Final string should have same length of chars as list 2</p>
<p>Example 1 :</p>
<pre><code>list 1 = ["r", "w", "d"]
list 2 = ["w", "o", "r", "d"]
</code></pre>
<p>Expected output = W - R D</p>
<p>Example 2:</p>
<pre><code>list 1 = ["r"]
list 2 = ["w", "o", "r", "d"]
</code></pre>
<p>Expected output = - - R -</p>
| [
{
"answer_id": 74392946,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 1,
"selected": false,
"text": "list_1 = [\"r\", \"w\", \"d\"]\nlist_2 = [\"w\", \"o\", \"r\", \"d\"]\nprint(*[e.upper() if e in list_1 else '-' for e in list_2])\n"
},
{
"answer_id": 74392954,
"author": "Jay",
"author_id": 8677071,
"author_profile": "https://Stackoverflow.com/users/8677071",
"pm_score": 3,
"selected": true,
"text": "list2"
},
{
"answer_id": 74393019,
"author": "Iulian St",
"author_id": 19333216,
"author_profile": "https://Stackoverflow.com/users/19333216",
"pm_score": 0,
"selected": false,
"text": "list1 = [\"r\"]\nlist2 = [\"w\", \"o\", \"r\", \"d\"]\n\nfor c in list2:\n if c in list1: print(c.upper(), end=' ')\n else: print('-', end=' ')\n\n\n> Output:\n> - - R -\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16806651/"
] |
74,392,817 | <p>Is there a way to import rotated text from a PDF table such as with tabula-py in python?</p>
<p>I realize I can just rename the column headers in this case, but I was wondering if there is a way to set a parameter for importing rotated text. I don't see any mention of rotation in the readthedocs for tabula-py and haven't found other packages that would do this yet either (although I did see a mention of rotating an entire page- which doesn't fit this use case exactly as renaming the columns would be easier).</p>
<p>Example:</p>
<pre><code>import tabula
list_df = tabula.read_pdf(
'https://sos.oregon.gov/elections/Documents/statistics/G22-Daily-Ballot-Returns.pdf',
pages=3
)
list_df[0]
</code></pre>
<p><a href="https://i.stack.imgur.com/LraFt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LraFt.png" alt="Screen Capture of Result and PDF" /></a></p>
| [
{
"answer_id": 74392946,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 1,
"selected": false,
"text": "list_1 = [\"r\", \"w\", \"d\"]\nlist_2 = [\"w\", \"o\", \"r\", \"d\"]\nprint(*[e.upper() if e in list_1 else '-' for e in list_2])\n"
},
{
"answer_id": 74392954,
"author": "Jay",
"author_id": 8677071,
"author_profile": "https://Stackoverflow.com/users/8677071",
"pm_score": 3,
"selected": true,
"text": "list2"
},
{
"answer_id": 74393019,
"author": "Iulian St",
"author_id": 19333216,
"author_profile": "https://Stackoverflow.com/users/19333216",
"pm_score": 0,
"selected": false,
"text": "list1 = [\"r\"]\nlist2 = [\"w\", \"o\", \"r\", \"d\"]\n\nfor c in list2:\n if c in list1: print(c.upper(), end=' ')\n else: print('-', end=' ')\n\n\n> Output:\n> - - R -\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3621575/"
] |
74,392,837 | <p>I have a netCDF file for temperature going back the last 22 thousand years at a decadal average (TraCE dataset). I want to calculate 100 or 1000 year averages.</p>
<p>I am really stuck, if anyone could help then that would be great. I am mostly using <code>R</code>, but if it is simple in <code>cdo</code> then I can try this too.</p>
<p>I don't have any code to show as I really don't know where to start. Most examples I have seen have been on daily or yearly data... not decadal</p>
| [
{
"answer_id": 74392946,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 1,
"selected": false,
"text": "list_1 = [\"r\", \"w\", \"d\"]\nlist_2 = [\"w\", \"o\", \"r\", \"d\"]\nprint(*[e.upper() if e in list_1 else '-' for e in list_2])\n"
},
{
"answer_id": 74392954,
"author": "Jay",
"author_id": 8677071,
"author_profile": "https://Stackoverflow.com/users/8677071",
"pm_score": 3,
"selected": true,
"text": "list2"
},
{
"answer_id": 74393019,
"author": "Iulian St",
"author_id": 19333216,
"author_profile": "https://Stackoverflow.com/users/19333216",
"pm_score": 0,
"selected": false,
"text": "list1 = [\"r\"]\nlist2 = [\"w\", \"o\", \"r\", \"d\"]\n\nfor c in list2:\n if c in list1: print(c.upper(), end=' ')\n else: print('-', end=' ')\n\n\n> Output:\n> - - R -\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20470859/"
] |
74,392,851 | <p>I need to create functions to perform the calculation of the triangle area that include error handling using exceptions.</p>
<p>Def 1: Function named checkTriangleEdges(a, b, c) that verifies:</p>
<ol>
<li>That the three parameters are greater than 0, and</li>
<li>if the three parameters can form a triangle.
Raise a ValueError exception with the error message “All triangle edges must be > 0” if condition 1 is
violated, and with the error message “a, b and c can not form a triangle” if condition 2 is violated.</li>
</ol>
<p>Def 2: Function named requestTriangleEdges() that uses the input() function to obtain 3
numbers from the user and checks them with the checkTriangleEdges(a, b, c) function. If an exception
occurs, the function must print the error message and repeat until valid triangle edges are obtained.
Return the obtained valid triangle edges as a tuple.</p>
<p>Def 3: Function named calculateTriangleArea() that uses requestTriangleEdges() to obtain valid
triangle edges from the user and to calculate and return the triangle area.</p>
<pre><code>import math
def checkTriangleEdges(a, b, c):
if a<=0 or b<=0 or c<=0:
raise ValueError("All triangle edges must be > 0")
if a+b<c or b+c<a or c+a<b:
raise ValueError("a, b and c can not form a triangle")
def requestTriangleEdges():
try:
a = float(input("Length of edge a: "))
b = float(input("Length of edge b: "))
c = float(input("Length of edge c: "))
checkTriangleEdges(a, b, c)
return (a, b, c)
except ValueError as e:
print(e)
requestTriangleEdges()
def calculateTriangleArea():
a, b, c = requestTriangleEdges()
p = (a + b + c) / 2
s = p * (p - a) * (p - b) * (p - c)
result = math.sqrt(s)
return print(result)
calculateTriangleArea()
</code></pre>
<p>The problem is that when I check the program and immediately enter data that does not imply an error, everything works, but when I enter such data that imply an error, everything works until the moment when I enter the correct value and the program gives an error</p>
<p>Output example:</p>
<p>In case when all data is correct:</p>
<pre class="lang-none prettyprint-override"><code>Length of edge a: 3
Length of edge b: 3
Length of edge c: 3
3.897114317029974
</code></pre>
<p>After handling an error</p>
<pre class="lang-none prettyprint-override"><code>Length of edge a: x
could not convert string to float: 'x'
Length of edge a: 3
Length of edge b: 10
Length of edge c: 1
a, b and c can not form a triangle
Length of edge a: 0
Length of edge b: 1
Length of edge c: 3
All triangle edges must be > 0
Length of edge a: 4
Length of edge b: 4
Length of edge c: 4
Traceback (most recent call last):
File "C:\Users\Alex\Documents\HTML5\Fundamentals-S1\tp7.py", line 42, in <module>
calculateTriangleArea()
File "C:\Users\Alex\Documents\HTML5\Fundamentals-S1\tp7.py", line 32, in calculateTriangleArea
a, b, c = requestTriangleEdges()
TypeError: cannot unpack non-iterable NoneType object
</code></pre>
<p>I completely don't understand where I did a mistake and why program is not working.</p>
| [
{
"answer_id": 74393110,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 1,
"selected": false,
"text": "def checkTriangleEdges(a, b, c):\n if a <= 0 or b <= 0 or c <= 0:\n raise ValueError(\"All triangle edges must be > 0\")\n if a+b < c or b+c < a or c+a < b:\n raise ValueError(\"a, b and c can not form a triangle\")\n return a, b, c\n\ndef requestTriangleEdges():\n while True:\n try:\n a = float(input(\"Length of edge a: \"))\n b = float(input(\"Length of edge b: \"))\n c = float(input(\"Length of edge c: \"))\n return checkTriangleEdges(a, b, c)\n except ValueError as e:\n print(e)\n\ndef calculateTriangleArea():\n a, b, c = requestTriangleEdges()\n p = (a + b + c) / 2\n s = p * (p - a) * (p - b) * (p - c)\n return s**0.5\n\narea = calculateTriangleArea()\nprint(area)\n"
},
{
"answer_id": 74393316,
"author": "Dmitriy Neledva",
"author_id": 16786350,
"author_profile": "https://Stackoverflow.com/users/16786350",
"pm_score": 0,
"selected": false,
"text": "def requestTriangleEdges():\n\n try:\n a = float(input(\"Length of edge a: \"))\n b = float(input(\"Length of edge b: \"))\n c = float(input(\"Length of edge c: \"))\n checkTriangleEdges(a, b, c)\n return (a, b, c)\n\n except ValueError as e:\n\n print(e)\n requestTriangleEdges()\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20470589/"
] |
74,392,870 | <p>In the past hour I was searching here and couldn't find a very simple thing I need to do, duplicate a single row at <code>index</code> x, and just put in on <code>index x+1</code>.</p>
<p>df</p>
<pre><code> a b
0 3 8
1 2 4
2 9 0
3 5 1
</code></pre>
<p>copy index 2 and insert it as is in the next row:</p>
<pre><code> a b
0 3 8
1 2 4
2 9 0
3 9 0 # new row
4 5 1
</code></pre>
<p>What I tried is concat(with my own columns names) which make a mess.</p>
<pre><code>line = pd.DataFrame({"date": date, "event": None}, index=[index+1])
return pd.concat([df.iloc[:index], line, df.iloc[index:]]).reset_index(drop=True)
</code></pre>
<p>How to simply duplicate a full row at a given index ?</p>
| [
{
"answer_id": 74393282,
"author": "gotiredofcoding",
"author_id": 18813761,
"author_profile": "https://Stackoverflow.com/users/18813761",
"pm_score": 0,
"selected": false,
"text": "df.loc[index+0.5] = df.loc[index].values\nreturn df.sort_index().reset_index(drop = True)\n"
},
{
"answer_id": 74393760,
"author": "rhug123",
"author_id": 13802115,
"author_profile": "https://Stackoverflow.com/users/13802115",
"pm_score": 1,
"selected": false,
"text": "repeat()"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18813761/"
] |
74,392,911 | <p>Given I have a svg as follows:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#a)">
<path d="M0 0h20v20H0V0z" fill="#0D4AF9" />
<path fill-rule="evenodd" clip-rule="evenodd"
d="M2 14.666a1.334 1.334 0 1 1 2.669.001A1.334 1.334 0 0 1 2 14.666zm4.667.667a.668.668 0 0 1 0-1.334h10.667a.667.667 0 1 1 0 1.334H6.667zM2 9.998a1.333 1.333 0 1 1 2.666 0 1.333 1.333 0 0 1-2.666 0zm4.667.667a.667.667 0 1 1 0-1.333h10.667a.666.666 0 1 1 0 1.333H6.667zM2 5.333a1.333 1.333 0 1 1 2.666.001A1.333 1.333 0 0 1 2 5.332v.001zm4.667.666a.667.667 0 1 1 0-1.333h10.667a.666.666 0 1 1 0 1.333H6.667z"
fill="#fff"/>
</g>
<defs>
<clipPath id="a">
<rect width="20" height="20" rx="2"/>
</clipPath>
</defs>
</svg></code></pre>
</div>
</div>
</p>
<p>which renders like:</p>
<p><a href="https://i.stack.imgur.com/ybM4U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ybM4U.png" alt="enter image description here" /></a></p>
<p>How can one make those white lines and circles transparent? I tried creating masks but a total noob.</p>
| [
{
"answer_id": 74394478,
"author": "enxaneta",
"author_id": 7897395,
"author_profile": "https://Stackoverflow.com/users/7897395",
"pm_score": 3,
"selected": true,
"text": "d"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3475930/"
] |
74,392,912 | <p>I have a spreadsheet (Google Sheets) with several non-contiguous Cost columns. When I try to user ArrayFormula to sum each row "Grand Total", it's returning some interesting (incorrect) numbers.</p>
<p>Here's a sample, stripped down the number of cost columns for brevity.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Venue Cost</th>
<th>Moving</th>
<th>Moving Details</th>
<th>AV Support</th>
<th>Grand Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>1500</td>
<td>500</td>
<td></td>
<td>500</td>
<td>2500</td>
</tr>
<tr>
<td>2500</td>
<td>500</td>
<td></td>
<td>750</td>
<td>3750</td>
</tr>
<tr>
<td>1500</td>
<td>500</td>
<td></td>
<td>500</td>
<td>2500</td>
</tr>
</tbody>
</table>
</div>
<p>My Array Formula for the Grand Total Column is</p>
<p><code>=ARRAYFORMULA(filter(G2:G, G2:G<>"") + SUM(H2:H,J2:J))</code></p>
<p>where G is the Venue Cost and H and J are additional costs.</p>
<p>This is the resulting Grand Total:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Venue Cost</th>
<th>Moving</th>
<th>Moving Details</th>
<th>AV Support</th>
<th>Grand Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>1500</td>
<td>500</td>
<td></td>
<td>500</td>
<td>4750</td>
</tr>
<tr>
<td>2500</td>
<td>500</td>
<td></td>
<td>750</td>
<td>5750</td>
</tr>
<tr>
<td>1500</td>
<td>500</td>
<td></td>
<td>500</td>
<td>4750</td>
</tr>
</tbody>
</table>
</div>
<p>I tried moving away from SUM, to just manually adding the additional costs together.</p>
<p><code>=ARRAYFORMULA(filter(G2:G, G2:G<>"") + (J2:J + H2:H ))</code></p>
<p>but received the #N/A error, which expanded to "Error: Array arguments to ADD are of different size." We have a document generating tool that sees those N/A's as additional jobs to process, so any extra spillover is not good:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Venue Cost</th>
<th>Moving</th>
<th>Moving Details</th>
<th>AV Support</th>
<th>Grand Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>1500</td>
<td>500</td>
<td></td>
<td>500</td>
<td>2500</td>
</tr>
<tr>
<td>2500</td>
<td>500</td>
<td></td>
<td>750</td>
<td>3750</td>
</tr>
<tr>
<td>1500</td>
<td>500</td>
<td></td>
<td>500</td>
<td>2500</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>#N/A</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>#N/A</td>
</tr>
</tbody>
</table>
</div>
<p>I'm pretty sure that the SUM and the ADD versions are including more than one row, do I need to filter the 'Additional Costs' Columns as well as the Venue Costs? Or, are the non-contiguous columns an issue?</p>
<p>Thank you!</p>
| [
{
"answer_id": 74394478,
"author": "enxaneta",
"author_id": 7897395,
"author_profile": "https://Stackoverflow.com/users/7897395",
"pm_score": 3,
"selected": true,
"text": "d"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20334775/"
] |
74,392,916 | <p>i have the following codes,</p>
<pre class="lang-dart prettyprint-override"><code>class mWidget extends StatefulWidget {
mWidget({super.key, required this.text});
String text;
@override
State<mWidget> createState() => _mWidgetState();
}
class _mWidgetState extends State<mWidget> {
@override
Widget build(BuildContext context) {
return Center(
child: Text(widget.text),
);
}
}
</code></pre>
<p>This is my custom widget,</p>
<pre class="lang-dart prettyprint-override"><code>class _MainState extends State<Main> {
var n = mWidget(text: "Hi");
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
n,
ElevatedButton(
onPressed: () {
setState(() {
n.text = "Hello";
});
},
child: Text("Click me"),
),
],
),
);
}
}
</code></pre>
<p>And this is the code in the main.dart file.</p>
<p>The problem is that pressing the button doesn't change the output on the screen unless a hot reload even though I am calling the setState function.</p>
<p>I wonder why is that.</p>
<p>Thanks in advance!</p>
| [
{
"answer_id": 74394478,
"author": "enxaneta",
"author_id": 7897395,
"author_profile": "https://Stackoverflow.com/users/7897395",
"pm_score": 3,
"selected": true,
"text": "d"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14229865/"
] |
74,392,937 | <p>when I run this code below I am getting IndexError: list index out of range.</p>
<p>I am trying to go through the list "years" and compare the value found in the list to the list of lists "data". I am unsure why I am getting the error below. Any thoughts on why this is the case?</p>
<p>PS. I am new to writing code... so pls excuse my ignorance lol..</p>
<pre><code>attempts_per_year = []
n = 0
y = 0
count = 0
for element in years:
if y <= len(data) and years[n] == data[y][0]:
count += 1
y += 1
elif years[n] != data[y][0]:
y += 1
else:
attempts_per_year.append (years[n], count)
count = 0
n += 1
</code></pre>
<pre><code>IndexError Traceback (most recent call last)
<ipython-input-145-07e49ab31e13> in <module>
5
6 for element in years:
----> 7 if y <= len(data) and years[n] == data[y][0]:
8 count += 1
9 y += 1
IndexError: list index out of range
</code></pre>
| [
{
"answer_id": 74394478,
"author": "enxaneta",
"author_id": 7897395,
"author_profile": "https://Stackoverflow.com/users/7897395",
"pm_score": 3,
"selected": true,
"text": "d"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20470671/"
] |
74,392,957 | <p>I am working on an angular app. I am making a progress bar in it. My code is as follows:</p>
<p>CSS:</p>
<pre><code>.progressbar {
position: relative; /* for position absolute of pseudo element work */
height: 56px;
margin: 5px;
background:
linear-gradient(to right, red 0%, yellow 50%, green 34%)
left/var(--p, 100%) fixed,
lightgray;
box-shadow: inset 0px -2px 5px rgba(0, 0, 0, 0.5);
animation: change 1s linear infinite;
}
.progressbar:after {
content: '';
position: absolute;
right: 0;
width: 0;
height: 0;
border-top: 28px solid white; /* Your background color*/
border-bottom: 28px solid white; /* Your background color*/
border-left: 28px solid transparent;
}
.progressbar:before {
content: '';
position: absolute;
left: 0;
width: 0;
height: 0;
border-top: 28px solid transparent;
border-bottom: 28px solid transparent;
border-left: 28px solid white; /* Your background color*/
}
.bar {
display:flex;
gap:10px;
}
</code></pre>
<p>HTML:</p>
<pre><code><div class="bar">
<div class="progressbar" style="width:100%;"></div>
<div class="progressbar" style="width:100%;"></div>
<div class="progressbar" style="width:100%;"></div>
</div>
</code></pre>
<p>My Fiddle is as follows:</p>
<p><a href="http://jsfiddle.net/9hL0nb4a/9/" rel="nofollow noreferrer">http://jsfiddle.net/9hL0nb4a/9/</a></p>
<p>Problem in my code is this I am making a progress bar combining multiple gradient bar. Because of which there is a gap between them and alignment is not proper.</p>
<p>I want to make bars of this progress bar equally spaced and close to each other as shown in below image <a href="https://i.stack.imgur.com/LIA7l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LIA7l.png" alt="progress_bar" /></a></p>
<p>How can I do that?</p>
| [
{
"answer_id": 74394478,
"author": "enxaneta",
"author_id": 7897395,
"author_profile": "https://Stackoverflow.com/users/7897395",
"pm_score": 3,
"selected": true,
"text": "d"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17800542/"
] |
74,392,966 | <p>I get a runtime error when i try to remove a fox object from a dictionary when it has starved in my simulation program, how can i fix this?</p>
<p>I tried to use other methods i discovered online, but i kept getting the same error.</p>
<pre><code>import random
class Simulation:
def __init__(self):
self.Foxes = {}
for i in range(100): # Creates 100 foxes
self.Foxes[i] = Fox()
def Main(self):
for i in range(100): # Forages for each fox and checks for starvation
for i in self.Foxes.keys():
self.Foxes[i].Forage()
if self.Foxes[i].Hunger >= self.Foxes[i].HungerMaximum:
self.Foxes.pop(i)
print("There are " + str(len(self.Foxes)) + " foxes remaining.")
class Animal:
def __init__(self):
self.Age = 0
self.HungerMaximum = 50
self.Hunger = 0
self.ForagingChance = 20
def Forage(self):
if random.randint(1,self.ForagingChance) == self.ForagingChance:
if self.Hunger > 10:
self.Hunger = self.Hunger - 10
else:
self.Hunger = self.Hunger + 10
class Fox(Animal):
def __init__(self):
Animal.__init__(self)
</code></pre>
| [
{
"answer_id": 74394478,
"author": "enxaneta",
"author_id": 7897395,
"author_profile": "https://Stackoverflow.com/users/7897395",
"pm_score": 3,
"selected": true,
"text": "d"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12363234/"
] |
74,392,986 | <p>I encounter strange behaviour.</p>
<p>Produce: <a href="https://stackblitz.com/edit/angular-nk45eb?file=src%2Fapp%2Fapp.module.ts,src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fstore%2Fdeployment.effects.ts,src%2Fapp%2Fstore%2Fdeployment.slice.ts" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-nk45eb?file=src%2Fapp%2Fapp.module.ts,src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fstore%2Fdeployment.effects.ts,src%2Fapp%2Fstore%2Fdeployment.slice.ts</a></p>
<p>Issue:
When calling action creator which calls effect, to get data from http, it return first response to action creator, updates the slice (with undefined), and then http is resolved and returned data. (we need to await http before continue and get data)</p>
<p>I have tried few different approaches:</p>
<pre><code>getPipelineLogs$ = createEffect(() =>
this.actions$.pipe(
ofType(DeploymentActions.getPipelineLogs),
switchMap((currentValue) => {
return this.http.get<any>(
`${this.apiBase}/pipelines/${currentValue.pipelineId}/logs`,
this.bufferHttpOptions
)
}),
map((result) => {
return DeploymentActions.setPipelineLogs({ name: result.logName, data: result.logData });
}),
catchError((e) => of(DeploymentActions.error(e)))
)
);
</code></pre>
<p>I have tried also to add .pipe() on the request itself:</p>
<pre><code>getPipelineLogs$ = createEffect(() =>
this.actions$.pipe(
ofType(DeploymentActions.getPipelineLogs),
switchMap((currentValue) => {
return this.http.get<any>(
`${this.apiBase}/pipelines/${currentValue.pipelineId}/logs`,
this.bufferHttpOptions
)
.pipe(
map((result) => {
return DeploymentActions.setPipelineLogs({ name: result.logName, data: result.logData });
}),
catchError((e) => of(DeploymentActions.error(e)))
)
})
)
);
</code></pre>
<p>but it aways first return response to action creator(updating slice with undefined) and then go back and resolve the http.get.</p>
<p>I also tried to change switchMap to exhaustMap, and different operator in the equation, but didn't make it work to await http and then continue with next operator.</p>
<p>Can you help on this, thanks so much!</p>
<p>Please provide a link to a minimal reproduction of the bug
No response</p>
<p>Please provide the exception or error you saw
No errors. Http request must be done in order to proceed.
Please provide the environment you discovered this bug in (run ng version)</p>
<ul>
<li>Angular CLI: 14.2.2</li>
<li>Node: v18.4.0</li>
<li>yarn: 1.22.19</li>
</ul>
| [
{
"answer_id": 74394478,
"author": "enxaneta",
"author_id": 7897395,
"author_profile": "https://Stackoverflow.com/users/7897395",
"pm_score": 3,
"selected": true,
"text": "d"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74392986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3701812/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.