qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,486,815
|
<p>I want to use threading package to calculate the square of num and my code like,</p>
<pre><code>import threading
def my_squr(num): #if this function take long time to run
print(num*num)
return num*num
if __name__ == "__main__":
l1 = [1,3,5,7,11,13,15,17]
for i, item in enumerate(l1):
if i % 3 == 0:
t1 = threading.Thread(target=my_squr, args=(item,))
t1.start()
t1.join()
elif i % 3 == 1:
t2 = threading.Thread(target=my_squr, args=(item,))
t2.start()
t2.join()
else:
t3 = threading.Thread(target=my_squr, args=(item,))
t3.start()
t3.join()
# t1.join()
# t2.join()
# t3.join()
print("Done")
</code></pre>
<p>However, I am confused about where should I put the <code>join()</code> method.Although, they both get same answer, I guess there are some differeces between them.</p>
|
[
{
"answer_id": 74486917,
"author": "Mustafa KÜÇÜKDEMİRCİ",
"author_id": 15833253,
"author_profile": "https://Stackoverflow.com/users/15833253",
"pm_score": 3,
"selected": true,
"text": "->Create thread x and start\n->wait for finish of thread x\n->Create thread y and start\n->wait for finish of thread y\n... and so on.\n ->Create thread x and start\n->Create thread y and start\n->Create thread z and start\n... \n\nat the end\n->wait thread x to finish\n->wait thread y to finish\n...\n"
},
{
"answer_id": 74487106,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 1,
"selected": false,
"text": "import threading\ndef my_squr(num): #if this function take long time to run\n print(num*num)\n return num*num\n\nif __name__ == \"__main__\":\n threads = []\n l1 = [1,3,5,7,11,13,15,17]\n for i, item in enumerate(l1):\n if i % 3 == 0:\n t1 = threading.Thread(target=my_squr, args=(item,))\n t1.start()\n threads.append(t1)\n elif i % 3 == 1:\n t2 = threading.Thread(target=my_squr, args=(item,))\n t2.start()\n threads.append(t2)\n else:\n t3 = threading.Thread(target=my_squr, args=(item,))\n t3.start()\n threads.append(t3)\n\n for thread in threads:\n thread.join()\n\n print(\"Done\")\n"
},
{
"answer_id": 74487186,
"author": "eatmeimadanish",
"author_id": 3591014,
"author_profile": "https://Stackoverflow.com/users/3591014",
"pm_score": 1,
"selected": false,
"text": "import threading\ndef my_squr(num): #if this function take long time to run\n print(num*num)\n return num*num\n\nif __name__ == \"__main__\":\n threads = list()\n l1 = [1,3,5,7,11,13,15,17]\n for i, item in enumerate(l1):\n if i % 3 == 0:\n t1 = threading.Thread(target=my_squr, args=(item,))\n threads.append(t1)\n t1.start()\n elif i % 3 == 1:\n t2 = threading.Thread(target=my_squr, args=(item,))\n threads.append(t2)\n t2.start()\n else:\n t3 = threading.Thread(target=my_squr, args=(item,))\n threads.append(t3)\n t3.start()\n\n for t in threads:\n t,join()\n\n print(\"Done\")\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74486815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12931358/"
] |
74,486,825
|
<p>Is there any way I can store inside <code>header</code> base on <code>section.type</code> different titles like <code><p> {section.title1} </p></code> or <code><p> {section.title2} </p></code> ?</p>
<pre><code>return (
<Collapse
onToggle={onHandleClick}
header={
<p> {section.title1} </p>
}
</Collapse>
);
</code></pre>
|
[
{
"answer_id": 74486845,
"author": "S.Marx",
"author_id": 11095009,
"author_profile": "https://Stackoverflow.com/users/11095009",
"pm_score": 0,
"selected": false,
"text": "return (\n <Collapse\n onToggle={onHandleClick}\n header={\n section.type ? <p>{section.title1}</p> : <p>{section.title2}</p>\n }\n </Collapse>\n)\n"
},
{
"answer_id": 74486863,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 1,
"selected": false,
"text": " header={\n <p> {section.type ? section.title1 : section.title2} </p>\n }\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74486825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3522687/"
] |
74,486,841
|
<p>Firstly, I'm using Python 3.11.0 in Colab.</p>
<p>When I use <code>/</code> to make parameters positional-only, <code>SyntaxError</code> is raised.</p>
<p>However, when I use <code>*</code> for keyword-only parameters, any error hasn't been raised.</p>
<p>Is there anyone who knows why these things happen?</p>
<pre><code># SyntaxError is raised
def foo(x, y, /):
return x + y
</code></pre>
<pre><code> File "<ipython-input-28-57597574dc0a>", line 1
def foo(x, y, /):
^
SyntaxError: invalid syntax
</code></pre>
<pre><code># This was ok
def foo(*, x, y):
return x + y
</code></pre>
|
[
{
"answer_id": 74486845,
"author": "S.Marx",
"author_id": 11095009,
"author_profile": "https://Stackoverflow.com/users/11095009",
"pm_score": 0,
"selected": false,
"text": "return (\n <Collapse\n onToggle={onHandleClick}\n header={\n section.type ? <p>{section.title1}</p> : <p>{section.title2}</p>\n }\n </Collapse>\n)\n"
},
{
"answer_id": 74486863,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 1,
"selected": false,
"text": " header={\n <p> {section.type ? section.title1 : section.title2} </p>\n }\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74486841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20537542/"
] |
74,486,843
|
<p><code>x:Key</code> behaves like an attached property where it is available in the children of <code>ResourceDictionary</code>. However, I cannot find the implementation of <code>x:Key</code> in <code>ResourceDictionary</code> (<a href="https://github.com/dotnet/maui/blob/50d5bc9c2aed26276371740bd9d5e5beab52533c/src/Controls/src/Core/ResourceDictionary.cs#L18" rel="nofollow noreferrer">the repo</a>).</p>
<p><strong>Question</strong>: How and where is <code>x:Key</code> implemented in MAUI?</p>
|
[
{
"answer_id": 74487804,
"author": "mamift",
"author_id": 1376318,
"author_profile": "https://Stackoverflow.com/users/1376318",
"pm_score": 2,
"selected": true,
"text": "x:Key xmlns:x=\"http://schemas.microsoft.com/winfx/2009/xaml\" XmlName XmlName x:Key x:Arguments x:DataType x:FactoryMethod x:Name x:TypeArguments x:Class x:FieldModifier x: x: x:Static"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74486843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/835073/"
] |
74,486,859
|
<p>i'm going to learn flutter.
so i installed the latest version of flutter(Flutter 3.3.8) and make the path of that on windows.
then i installed the latest version of android studio(Android Studio Dolphin | 2021.3.1 Patch 1) and installed the flutter plugin and sdk and emulator of api 32 and 29 on it.</p>
<p>also i installed the java jdk and jre v8.</p>
<p>but when i try to run the defult app on emulator in recevied this error on terminal :</p>
<pre><code>FAILURE: Build failed with an exception.
* What went wrong:
A problem occurred configuring root project 'android'.
> Could not resolve all files for configuration ':classpath'.
> Could not find com.android.tools.build:gradle:7.1.2.
Searched in the following locations:
- https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/7.1.2/gradle-7.1.2.pom
- https://repo.maven.apache.org/maven2/com/android/tools/build/gradle/7.1.2/gradle-7.1.2.pom
Required by:
project :
and here it is the result of doctor command of flutter :
C:\Users\new>flutter doctor -v
[√] Flutter (Channel stable, 3.3.8, on Microsoft Windows [Version 10.0.18363.535], locale en-US)
• Flutter version 3.3.8 on channel stable at E:\src\flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision 52b3dc25f6 (9 days ago), 2022-11-09 12:09:26 +0800
• Engine revision 857bd6b74c
• Dart version 2.18.4
• DevTools version 2.15.0
[√] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
• Android SDK at C:\Users\new\AppData\Local\Android\sdk
• Platform android-33, build-tools 33.0.0
• Java binary at: E:\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
• All Android licenses accepted.
[√] Chrome - develop for the web
• Chrome at C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
[X] Visual Studio - develop for Windows
X Visual Studio not installed; this is necessary for Windows development.
Download at https://visualstudio.microsoft.com/downloads/.
Please install the "Desktop development with C++" workload, including all of its default components
[√] Android Studio (version 2021.3)
• Android Studio at E:\Android\Android Studio
• Flutter plugin can be installed from:
https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
[√] VS Code, 64-bit edition (version 1.71.2)
• VS Code at C:\Program Files\Microsoft VS Code
• Flutter extension can be installed from:
https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter
[√] Connected device (3 available)
• sdk gphone64 x86 64 (mobile) • emulator-5554 • android-x64 • Android 12 (API 32) (emulator)
• Windows (desktop) • windows • windows-x64 • Microsoft Windows [Version 10.0.18363.535]
• Chrome (web) • chrome • web-javascript • Google Chrome 107.0.5304.107
[√] HTTP Host Availability
• All required HTTP hosts are available
</code></pre>
<p>I would be grateful if you could guide me in solving this problem.
thx to all!</p>
<p><a href="https://i.stack.imgur.com/IPvUN.jpg" rel="nofollow noreferrer">build.gradle codes</a></p>
|
[
{
"answer_id": 74487804,
"author": "mamift",
"author_id": 1376318,
"author_profile": "https://Stackoverflow.com/users/1376318",
"pm_score": 2,
"selected": true,
"text": "x:Key xmlns:x=\"http://schemas.microsoft.com/winfx/2009/xaml\" XmlName XmlName x:Key x:Arguments x:DataType x:FactoryMethod x:Name x:TypeArguments x:Class x:FieldModifier x: x: x:Static"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74486859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20537641/"
] |
74,486,875
|
<p>I'm trying to change the number of items in array, over which a for loop is running, during the for loop, with the objective that this changes the number of loops. In a very simplified version, the code would look something like this:</p>
<pre><code>var loopArray: [Int] = []
loopArray.append(1)
loopArray.append(2)
loopArray.append(3)
loopArray.append(4)
loopArray.append(5)
for x in 0..<Int(loopArray.count) {
print(x)
if x == 4 {
loopArray.append(6)
}
}
</code></pre>
<p>When running this code, 5 numbers are printed, and while the number 6 is added to the Array, the <code>loopArray.count</code> does not seem to update. How can I make the <code>.count</code> dynamic?
This is a very simplified example, in the project I'm working on, appending numbers to the array depends on conditions that may or may not be met.</p>
<p>I have looked for examples online, but have not been able to find any similar cases. Any help or guidance is much appreciated.</p>
|
[
{
"answer_id": 74487804,
"author": "mamift",
"author_id": 1376318,
"author_profile": "https://Stackoverflow.com/users/1376318",
"pm_score": 2,
"selected": true,
"text": "x:Key xmlns:x=\"http://schemas.microsoft.com/winfx/2009/xaml\" XmlName XmlName x:Key x:Arguments x:DataType x:FactoryMethod x:Name x:TypeArguments x:Class x:FieldModifier x: x: x:Static"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74486875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16835035/"
] |
74,486,884
|
<p>I try to read data from application properties file in Spring Boot Application.</p>
<p>Following Code is my main class.</p>
<pre><code>@SpringBootApplication(scanBasePackages = "com.fsk.limitservice")
public class LimitServiceApplication {
public static void main(String[] args) {
SpringApplication.run(LimitServiceApplication.class, args);
}
}
</code></pre>
<p>Following Code is My Controller Class</p>
<pre><code>@RestController
public class LimitsConfigurationController {
@Autowired
LimitConfiguration limitConfiguration;
@GetMapping("/limits")
public LimitConfiguration retrieveLimitFromConfiguration() {
return new LimitConfiguration(limitConfiguration.getMinimum(), limitConfiguration.getMaximum());
}
}
</code></pre>
<p>Following Code is my component class</p>
<pre><code>@Component
@ConfigurationProperties("limits-service")
public class LimitConfiguration {
private int minimum;
private int maximum;
public LimitConfiguration(int minimum, int maximum) {
this.minimum = minimum;
this.maximum = maximum;
}
public int getMinimum() {
return minimum;
}
public void setMinimum(int minimum) {
this.minimum = minimum;
}
public int getMaximum() {
return maximum;
}
public void setMaximum(int maximum) {
this.maximum = maximum;
}
}
</code></pre>
<p>And Lastly this is my application properties file</p>
<pre><code>spring.application.name=limits-service
limits-service.minimum=17
limits-service.maximum=1124
</code></pre>
<p>When i click to run button, i get the following error.
How can i fix this.?</p>
<p><a href="https://i.stack.imgur.com/9GrWu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9GrWu.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74487120,
"author": "DingHao",
"author_id": 19546048,
"author_profile": "https://Stackoverflow.com/users/19546048",
"pm_score": 1,
"selected": false,
"text": "@ConfigurationPropertiesScan @ConstructorBinding"
},
{
"answer_id": 74487899,
"author": "birca123",
"author_id": 10231374,
"author_profile": "https://Stackoverflow.com/users/10231374",
"pm_score": 1,
"selected": false,
"text": "@ConfigurationProperties @EnableConfigurationProperties @Component @ConfigurationPropertiesScan"
},
{
"answer_id": 74488127,
"author": "Răzvan Puiu",
"author_id": 7156819,
"author_profile": "https://Stackoverflow.com/users/7156819",
"pm_score": 0,
"selected": false,
"text": "@Configuration\npublic class LimitConfiguration {\n\n @Value(\"${limits-service.minimum}\")\n private int minimum;\n\n @Value(\"${limits-service.maximum}\")\n private int maximum;\n\n...\n}\n return new LimitConfiguration(limitConfiguration.getMinimum(),limitConfiguration.getMaximum());"
},
{
"answer_id": 74488758,
"author": "ajesh",
"author_id": 12039826,
"author_profile": "https://Stackoverflow.com/users/12039826",
"pm_score": 0,
"selected": false,
"text": "@RestController\n@RequestMapping(\"/limits\")\npublic class LimitsConfigurationController {\n\n @Value(\"${limits-service.minimum}\")\n private int minimum;\n\n @Value(\"${limits-service.maximum}\")\n private int maximum;\n\n @GetMapping\n public LimitConfiguration retrieveLimitFromConfiguration() {\n return new LimitConfiguration(minimum, maximum);\n }\n}\n public class LimitConfiguration {\n\n private int minimum;\n\n private int maximum;\n\n // Getters, Setters, No args constructor and 2 args constructor\n\n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74486884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11863934/"
] |
74,486,886
|
<p>My docker-compose creates 3 containers - django, celery and rabbitmq. When i run the following commands -> docker-compose build and docker-compose up, the containers run successfully.</p>
<p>However I am having issues with deploying the image. The image generated has an image ID of 24d7638e2aff. For whatever reason however, if I just run the command below, nothing happens with an exit 0. Both the django and celery applications have the same image id.</p>
<pre><code>docker run 24d7638e2aff
</code></pre>
<p><a href="https://i.stack.imgur.com/W0yCJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/W0yCJ.png" alt="" /></a></p>
<p>This is not good, as I am unable to deploy this image on kubernetes. My only thought is that the dockerfile has been configured wrongly, but i cannot figure out what is the cause</p>
<p>docker-compose.yaml</p>
<pre><code>version: "3.9"
services:
django:
container_name: testapp_django
build:
context: .
args:
build_env: production
ports:
- "8000:8000"
command: >
sh -c "python manage.py migrate &&
python manage.py runserver 0.0.0.0:8000"
volumes:
- .:/code
links:
- rabbitmq
- celery
rabbitmq:
container_name: testapp_rabbitmq
restart: always
image: rabbitmq:3.10-management
ports:
- "5672:5672" # specifies port of queue
- "15672:15672" # specifies port of management plugin
celery:
container_name: testapp_celery
restart: always
build:
context: .
args:
build_env: production
command: celery -A testapp worker -l INFO -c 4
depends_on:
- rabbitmq
</code></pre>
<p>Dockerfile</p>
<pre><code>ARG PYTHON_VERSION=3.9-slim-buster
# define an alias for the specfic python version used in this file.
FROM python:${PYTHON_VERSION} as python
# Python build stage
FROM python as python-build-stage
ARG build_env
# Install apt packages
RUN apt-get update && apt-get install --no-install-recommends -y \
# dependencies for building Python packages
build-essential \
# psycopg2 dependencies
libpq-dev
# Requirements are installed here to ensure they will be cached.
COPY ./requirements .
# Create Python Dependency and Sub-Dependency Wheels.
RUN pip wheel --wheel-dir /usr/src/app/wheels \
-r ${build_env}.txt
# Python 'run' stage
FROM python as python-run-stage
ARG build_env
ARG APP_HOME=/app
ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1
ENV BUILD_ENV ${build_env}
WORKDIR ${APP_HOME}
RUN addgroup --system appuser \
&& adduser --system --ingroup appuser appuser
# Install required system dependencies
RUN apt-get update && apt-get install --no-install-recommends -y \
# psycopg2 dependencies
libpq-dev \
# Translations dependencies
gettext \
# git for GitPython commands
git-all \
# cleaning up unused files
&& apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \
&& rm -rf /var/lib/apt/lists/*
# All absolute dir copies ignore workdir instruction. All relative dir copies are wrt to the workdir instruction
# copy python dependency wheels from python-build-stage
COPY --from=python-build-stage /usr/src/app/wheels /wheels/
# use wheels to install python dependencies
RUN pip install --no-cache-dir --no-index --find-links=/wheels/ /wheels/* \
&& rm -rf /wheels/
COPY --chown=appuser:appuser ./docker_scripts/entrypoint /entrypoint
RUN sed -i 's/\r$//g' /entrypoint
RUN chmod +x /entrypoint
# copy application code to WORKDIR
COPY --chown=appuser:appuser . ${APP_HOME}
# make appuser owner of the WORKDIR directory as well.
RUN chown appuser:appuser ${APP_HOME}
USER appuser
EXPOSE 8000
ENTRYPOINT ["/entrypoint"]
</code></pre>
<p>entrypoint</p>
<pre><code>#!/bin/bash
set -o errexit
set -o pipefail
set -o nounset
exec "$@"
</code></pre>
<p>How do I build images of these containers so that I can deploy them to k8s?</p>
|
[
{
"answer_id": 74486987,
"author": "HoliSimo",
"author_id": 10419454,
"author_profile": "https://Stackoverflow.com/users/10419454",
"pm_score": 0,
"selected": false,
"text": "docker-compose.yml set -o errexit\nset -o pipefail\nset -o nounset\n\npython manage.py migrate && python manage.py runserver 0.0.0.0:8000\nexec \"$@\"\n python manage.py runserver 0.0.0.0:8000"
},
{
"answer_id": 74489257,
"author": "David Maze",
"author_id": 10008173,
"author_profile": "https://Stackoverflow.com/users/10008173",
"pm_score": 2,
"selected": true,
"text": "command: CMD docker run docker-compose.yml docker run CMD CMD CMD python manage.py migrate && python manage.py runserver 0.0.0.0:8000\n docker run docker run -d --net ... your-image \\\n celery -A testapp worker -l INFO -c 4\n args: command:"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74486886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15980387/"
] |
74,486,889
|
<p>I'm working on a Spring Boot project that uses Spring Cloud (<code>io.awspring.cloud:spring-cloud-aws-dependencies:2.4.2</code>) to produce and consume AWS SQS messages. I have several message producers and several message consumers, and all is working fine from that perspective.</p>
<p>I now have a cross cutting concern where I need to set a header on all messages being produced/sent; and to read that header on all messages being consumed (<code>correlationId</code>), and AOP seems like a good fit.</p>
<p>My aspect for handling (receiving) a message works fine:</p>
<pre><code> @Before("execution(* org.springframework.messaging.handler.invocation.AbstractMethodMessageHandler.handleMessage(..))")
fun beforeHandleMessage(joinPoint: JoinPoint) {
</code></pre>
<p>The class and method that it is targeting is:</p>
<pre><code>package org.springframework.messaging.handler.invocation;
...
public abstract class AbstractMethodMessageHandler<T>
implements MessageHandler, ApplicationContextAware, InitializingBean {
...
@Override
public void handleMessage(Message<?> message) throws MessagingException {
</code></pre>
<p>As mentioned, this works great.</p>
<p>However, I can't get my pointcut for sending a message working. This is my aspect:</p>
<pre><code> @Before("execution(* org.springframework.messaging.support.AbstractMessageChannel.send(..))")
// @Before("execution(* io.awspring.cloud.messaging.core.QueueMessageChannel.send(..))")
fun beforeSendMessage(joinPoint: JoinPoint) {
</code></pre>
<p>And the class and method that I'm trying to target is this:</p>
<pre><code>package org.springframework.messaging.support;
...
public abstract class AbstractMessageChannel implements MessageChannel, InterceptableChannel, BeanNameAware {
...
@Override
public final boolean send(Message<?> message) {
</code></pre>
<p>But it doesn't seem to work. I've also tried writing the pointcut to target the concrete implementation class (as commented out above), but that also does nothing.</p>
<p>I can't see what the difference is between my working pointcut for <code>beforeHandleMessage</code> and <code>beforeSendMethod</code>, other than the pointcut for <code>beforeSendMethod</code> is targeting a <code>final</code> method. Is that relevant?</p>
<p>Any pointers to get this working would be very much appreciated;<br />
Thanks</p>
|
[
{
"answer_id": 74500968,
"author": "kriegaex",
"author_id": 1082681,
"author_profile": "https://Stackoverflow.com/users/1082681",
"pm_score": 1,
"selected": false,
"text": "MessageChannel.send(Message) # This works, now we can create JDK interface proxies. The seemingly equivalent alternative\n# @EnableAspectJAutoProxy(proxyTargetClass = false)\n# where 'false' is even the default, does *not* work in Spring Boot.\nspring.aop.proxy-target-class=false\n"
},
{
"answer_id": 74524434,
"author": "Nathan Russell",
"author_id": 1378228,
"author_profile": "https://Stackoverflow.com/users/1378228",
"pm_score": 1,
"selected": true,
"text": "send"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74486889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1378228/"
] |
74,486,897
|
<p>I'm working on an Angular project and after I make a put request I want to be able to display on screen the message from console to inform the user.
I tried using <code>res.message</code> but i get <code>Property 'message' does not exist on type 'Object' </code>
the function code</p>
<pre><code>this.http.put('https://hjwnr2qluh-vpce-023bfa93fa33e8bbe.execute-api.eu-central-1.amazonaws.com/fabi/masterdata/v1/units/multiple',
data1).subscribe((res) => {
JSON.stringify(res)
console.log(res)
},(err:HttpErrorResponse)=>{console.log(err.error.detail)},
)
</code></pre>
<p>Data generated looks like this</p>
<p><a href="https://i.stack.imgur.com/rWRre.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rWRre.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74487070,
"author": "Luca Angrisani",
"author_id": 13240452,
"author_profile": "https://Stackoverflow.com/users/13240452",
"pm_score": 0,
"selected": false,
"text": "this.http.put('https://hjwnr2qluh-vpce-023bfa93fa33e8bbe.execute-api.eu-central-1.amazonaws.com/fabi/masterdata/v1/units/multiple',\n data1).subscribe(\n (res) => {\n console.log(res)\n alert(res.message)\n },\n (err: HttpErrorResponse) => {\n console.log(err.error.detail)\n alert(err.error.detail)\n }\n );\n"
},
{
"answer_id": 74487077,
"author": "Shifenis",
"author_id": 6393934,
"author_profile": "https://Stackoverflow.com/users/6393934",
"pm_score": 1,
"selected": false,
"text": "data binding public message: string;\n\n public retrieveInformation(): void {\n this.http.put('https://hjwnr2qluh-vpce-023bfa93fa33e8bbe.execute-api.eu-central-1.amazonaws.com/fabi/masterdata/v1/units/multiple',\n data1).subscribe((res) => {\n \n // JSON.stringify(res); this row is useless here :)\n console.log(res);\n this.message = res.message;\n \n },(err:HttpErrorResponse)=>{console.log(err.error.detail)},\n )\n } \n\n <span *ngIf=\"message\">\n {{message}} \n </span>\n"
},
{
"answer_id": 74487150,
"author": "Andriu1510",
"author_id": 17238007,
"author_profile": "https://Stackoverflow.com/users/17238007",
"pm_score": 1,
"selected": false,
"text": " this.http.put('https://hjwnr2qluh-vpce-023bfa93fa33e8bbe.execute-api.eu-central-1.amazonaws.com/fabi/masterdata/v1/units/multiple',\n data1).pipe(\n tap(rs => {\n JSON.stringify(res)\n console.log(res)\n }),\ncatchError((err:HttpErrorResponse => {console.log(err.error.detail)})\n ).subscribe()\n"
},
{
"answer_id": 74487198,
"author": "Hadi Masoumi",
"author_id": 11894228,
"author_profile": "https://Stackoverflow.com/users/11894228",
"pm_score": 0,
"selected": false,
"text": "import {Component, inject} from '@angular/core';\nimport {MatSnackBar, MatSnackBarRef} from '@angular/material/snack-bar';\n\n\n@Component({\n selector: '',\n templateUrl: '',\n styleUrls: [''],\n})\nexport class SnackBarAnnotatedComponentExample {\n\n constructor(private _snackBar: MatSnackBar) {\n this.http.put('..yourEndpoint', yourPayload ).subscribe((res) => {\n \n JSON.stringify(res);\n console.log(res);\n \n if (res?.message) {\n this.showMessage(res.message);\n }\n },(err:HttpErrorResponse)=>{console.log(err.error.detail)},\n )}\n\n showMessage(message) {\n this._snackBar.open(message, {\n duration: 5000,\n panelClass: ['white-color', 'success-back']\n });\n }\n}"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74486897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19938599/"
] |
74,486,902
|
<p>I added 5 buttons in js to html and I want them to be defined with a one second delay, and because of this js, when it reaches the addEventListener line, those buttons are not defined and gives an error.</p>
<p><a href="https://i.stack.imgur.com/PYq4N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PYq4N.png" alt="enter image description here" /></a></p>
<p>HTML:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style.css">
<title>Document</title>
</head>
<body>
<div id="btn-adder"></div>
<script src="./script.js"></script>
</body>
</html>
</code></pre>
<p>CSS:</p>
<pre><code>*{
padding: 0;
margin: 0;
box-sizing: border-box;
font-size: 20px;
}
body{
background: rgb(61, 61, 61);
}
#btn-adder{
margin-top: 40px;
text-align: center;
}
#btn-adder button{
padding: 5px;
margin: 5px;
}
</code></pre>
<p>JavaScript:</p>
<pre><code>const btnAdder = document.getElementById("btn-adder");
for (let i = 0; i < 5; i++) {
setTimeout(function () {
btnAdder.innerHTML += `<button id="btn${i}">Button ${i}</button>`;
}, 1000);
}
for (let i = 0; i < 5; i++) {
document.getElementById(`btn${i}`).addEventListener("click", function () {
console.log(`Button ${i} clicked`);
});
}
</code></pre>
<p>Is there a way to make the addEventListener recognize the new variables?</p>
|
[
{
"answer_id": 74487070,
"author": "Luca Angrisani",
"author_id": 13240452,
"author_profile": "https://Stackoverflow.com/users/13240452",
"pm_score": 0,
"selected": false,
"text": "this.http.put('https://hjwnr2qluh-vpce-023bfa93fa33e8bbe.execute-api.eu-central-1.amazonaws.com/fabi/masterdata/v1/units/multiple',\n data1).subscribe(\n (res) => {\n console.log(res)\n alert(res.message)\n },\n (err: HttpErrorResponse) => {\n console.log(err.error.detail)\n alert(err.error.detail)\n }\n );\n"
},
{
"answer_id": 74487077,
"author": "Shifenis",
"author_id": 6393934,
"author_profile": "https://Stackoverflow.com/users/6393934",
"pm_score": 1,
"selected": false,
"text": "data binding public message: string;\n\n public retrieveInformation(): void {\n this.http.put('https://hjwnr2qluh-vpce-023bfa93fa33e8bbe.execute-api.eu-central-1.amazonaws.com/fabi/masterdata/v1/units/multiple',\n data1).subscribe((res) => {\n \n // JSON.stringify(res); this row is useless here :)\n console.log(res);\n this.message = res.message;\n \n },(err:HttpErrorResponse)=>{console.log(err.error.detail)},\n )\n } \n\n <span *ngIf=\"message\">\n {{message}} \n </span>\n"
},
{
"answer_id": 74487150,
"author": "Andriu1510",
"author_id": 17238007,
"author_profile": "https://Stackoverflow.com/users/17238007",
"pm_score": 1,
"selected": false,
"text": " this.http.put('https://hjwnr2qluh-vpce-023bfa93fa33e8bbe.execute-api.eu-central-1.amazonaws.com/fabi/masterdata/v1/units/multiple',\n data1).pipe(\n tap(rs => {\n JSON.stringify(res)\n console.log(res)\n }),\ncatchError((err:HttpErrorResponse => {console.log(err.error.detail)})\n ).subscribe()\n"
},
{
"answer_id": 74487198,
"author": "Hadi Masoumi",
"author_id": 11894228,
"author_profile": "https://Stackoverflow.com/users/11894228",
"pm_score": 0,
"selected": false,
"text": "import {Component, inject} from '@angular/core';\nimport {MatSnackBar, MatSnackBarRef} from '@angular/material/snack-bar';\n\n\n@Component({\n selector: '',\n templateUrl: '',\n styleUrls: [''],\n})\nexport class SnackBarAnnotatedComponentExample {\n\n constructor(private _snackBar: MatSnackBar) {\n this.http.put('..yourEndpoint', yourPayload ).subscribe((res) => {\n \n JSON.stringify(res);\n console.log(res);\n \n if (res?.message) {\n this.showMessage(res.message);\n }\n },(err:HttpErrorResponse)=>{console.log(err.error.detail)},\n )}\n\n showMessage(message) {\n this._snackBar.open(message, {\n duration: 5000,\n panelClass: ['white-color', 'success-back']\n });\n }\n}"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74486902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19556273/"
] |
74,486,952
|
<p>I'm trying to optimize the loading of fonts on a website. I found this website <a href="https://beamtic.com/optimizing-font-load" rel="nofollow noreferrer">https://beamtic.com/optimizing-font-load</a> giving suggestions to improve the fonts loading.
I read the section "Avoid font swapping" which suggests to use font-display: optional but Chrome does not seem to recognize it.
In the documentation of Mozilla (<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display</a>) I understand that this descriptor is used in @font-face only.
So the first website is giving wrong advices? If I can use font-display: optional only in @font-face how it works?
If I use a custom font for example body {font-family: 'My font', Verdana, Tahoma, sans-serif;} and I declare</p>
<pre><code>@font-face {
font-family: 'My font';
...
font-display: optional;
</code></pre>
<p>the first font that will be loaded is Verdana?</p>
<p>I tried to declare font-display: optional in body but Chrome does not recognize it.</p>
|
[
{
"answer_id": 74487070,
"author": "Luca Angrisani",
"author_id": 13240452,
"author_profile": "https://Stackoverflow.com/users/13240452",
"pm_score": 0,
"selected": false,
"text": "this.http.put('https://hjwnr2qluh-vpce-023bfa93fa33e8bbe.execute-api.eu-central-1.amazonaws.com/fabi/masterdata/v1/units/multiple',\n data1).subscribe(\n (res) => {\n console.log(res)\n alert(res.message)\n },\n (err: HttpErrorResponse) => {\n console.log(err.error.detail)\n alert(err.error.detail)\n }\n );\n"
},
{
"answer_id": 74487077,
"author": "Shifenis",
"author_id": 6393934,
"author_profile": "https://Stackoverflow.com/users/6393934",
"pm_score": 1,
"selected": false,
"text": "data binding public message: string;\n\n public retrieveInformation(): void {\n this.http.put('https://hjwnr2qluh-vpce-023bfa93fa33e8bbe.execute-api.eu-central-1.amazonaws.com/fabi/masterdata/v1/units/multiple',\n data1).subscribe((res) => {\n \n // JSON.stringify(res); this row is useless here :)\n console.log(res);\n this.message = res.message;\n \n },(err:HttpErrorResponse)=>{console.log(err.error.detail)},\n )\n } \n\n <span *ngIf=\"message\">\n {{message}} \n </span>\n"
},
{
"answer_id": 74487150,
"author": "Andriu1510",
"author_id": 17238007,
"author_profile": "https://Stackoverflow.com/users/17238007",
"pm_score": 1,
"selected": false,
"text": " this.http.put('https://hjwnr2qluh-vpce-023bfa93fa33e8bbe.execute-api.eu-central-1.amazonaws.com/fabi/masterdata/v1/units/multiple',\n data1).pipe(\n tap(rs => {\n JSON.stringify(res)\n console.log(res)\n }),\ncatchError((err:HttpErrorResponse => {console.log(err.error.detail)})\n ).subscribe()\n"
},
{
"answer_id": 74487198,
"author": "Hadi Masoumi",
"author_id": 11894228,
"author_profile": "https://Stackoverflow.com/users/11894228",
"pm_score": 0,
"selected": false,
"text": "import {Component, inject} from '@angular/core';\nimport {MatSnackBar, MatSnackBarRef} from '@angular/material/snack-bar';\n\n\n@Component({\n selector: '',\n templateUrl: '',\n styleUrls: [''],\n})\nexport class SnackBarAnnotatedComponentExample {\n\n constructor(private _snackBar: MatSnackBar) {\n this.http.put('..yourEndpoint', yourPayload ).subscribe((res) => {\n \n JSON.stringify(res);\n console.log(res);\n \n if (res?.message) {\n this.showMessage(res.message);\n }\n },(err:HttpErrorResponse)=>{console.log(err.error.detail)},\n )}\n\n showMessage(message) {\n this._snackBar.open(message, {\n duration: 5000,\n panelClass: ['white-color', 'success-back']\n });\n }\n}"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74486952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18881168/"
] |
74,487,021
|
<p>for some reason this isn't working.</p>
<p>i may be making a silly mistake somewhere.
please help</p>
<pre><code># importing modules
import urllib.request
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
from PIL import Image
</code></pre>
<p>#dowload mona lisa image</p>
<pre><code>urllib.request.urlretrieve(
'https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/1024px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg',
"Mona_Lisa.png")
</code></pre>
<p>#open the file</p>
<pre><code>img = Image.open("/content/Mona_Lisa.png")
</code></pre>
<p>#convert to from rgba to rgb</p>
<pre><code>rgb_image = img.convert('RGB')
rgb_image_rgb = np.array(rgb_image)
</code></pre>
<p>#show image</p>
<pre><code>plt.imshow(rgb_image_rgb, cmap = cm.Greys_r)
</code></pre>
|
[
{
"answer_id": 74487066,
"author": "Chris",
"author_id": 14408656,
"author_profile": "https://Stackoverflow.com/users/14408656",
"pm_score": 2,
"selected": false,
"text": "from PIL import Image\nimg = Image.open('image.png').convert('L')\nimg.save('greyscale.png')\n"
},
{
"answer_id": 74487102,
"author": "Runinho",
"author_id": 18724786,
"author_profile": "https://Stackoverflow.com/users/18724786",
"pm_score": 1,
"selected": false,
"text": "img = Image.open(\"/content/Mona_Lisa.png\").convert(\"L\")\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7846884/"
] |
74,487,023
|
<p>I have two columns in a df and rows of dates. I'd like to see how well each column matches the other and moves in sync with the other column - ie. do they move in tandem and does one influence the movements in the other.</p>
<pre><code> Col1 Col2
Date
1991-01-01 00:00:00+00:00 6.945847 3.4222
1991-04-01 00:00:00+00:00 8.377481 6.7783
1991-07-01 00:00:00+00:00 7.869787 4.6666
... ...
</code></pre>
<p>Is there a way to do this in pandas?</p>
<p>I thought of dividing each row by the value in the first row to see the % increase, but wondered if there was a better statistical way of doing this.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 74487066,
"author": "Chris",
"author_id": 14408656,
"author_profile": "https://Stackoverflow.com/users/14408656",
"pm_score": 2,
"selected": false,
"text": "from PIL import Image\nimg = Image.open('image.png').convert('L')\nimg.save('greyscale.png')\n"
},
{
"answer_id": 74487102,
"author": "Runinho",
"author_id": 18724786,
"author_profile": "https://Stackoverflow.com/users/18724786",
"pm_score": 1,
"selected": false,
"text": "img = Image.open(\"/content/Mona_Lisa.png\").convert(\"L\")\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9437961/"
] |
74,487,025
|
<p><a href="https://i.stack.imgur.com/YzV9L.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YzV9L.png" alt="enter image description here" /></a></p>
<p>I need help with my program. I need it to calculate the 3x3 average and then go and and calculate the next. This is what i got so far, it‘s only to calculate the average of all and now I‘m stuck…</p>
<pre><code>#include <stdio.h>
#define ROWS 5
#define COLS 7
int main(void){
float in_sum = 0;
float *in_matrix[ROWS][COLS];
float in_avg;
float matr[ROWS][COLS]={{1.5, 5, 6, 12, 13, 7, 80},
{50, 6.5, 23, 77, 17, 8.5, 28},
{43.5, 78, 8, 9, 34.5, 10, 95},
{75, 44, 40, 29, 39, 5, 99.5},
{18, 86, 68, 92, 10.5, 11, 4}};
printf("Matrix Input:\n");
for(int i = 0; i < ROWS; i++){
for (int j = 0; j < COLS; j++){
printf("%.2f ", matr[i][j]);
if(j==6){
printf("\n");
}
}
}
printf("\nMatrix Output: \n");
int j = 0, nr = 3, nc = 3;
for (int i = 0; i < nr; i++){
for(j = 0; j < nc; j++){
in_sum = in_sum + matr[i][j];
}
}
in_avg = in_sum/(ROWS*COLS);
for (int i=0; i< ROWS; i++){
for (int j=0; j< COLS; j++){
printf("%.2f", in_avg);
}
printf("\n");
}
in_matrix[ROWS][COLS] = &in_sum;
return 0;
}
</code></pre>
|
[
{
"answer_id": 74487066,
"author": "Chris",
"author_id": 14408656,
"author_profile": "https://Stackoverflow.com/users/14408656",
"pm_score": 2,
"selected": false,
"text": "from PIL import Image\nimg = Image.open('image.png').convert('L')\nimg.save('greyscale.png')\n"
},
{
"answer_id": 74487102,
"author": "Runinho",
"author_id": 18724786,
"author_profile": "https://Stackoverflow.com/users/18724786",
"pm_score": 1,
"selected": false,
"text": "img = Image.open(\"/content/Mona_Lisa.png\").convert(\"L\")\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20528928/"
] |
74,487,051
|
<p>I have a large list of around 200 values</p>
<p>The list looks like this</p>
<pre><code>list_ids = [10148,
10149,
10150,
10151,
10152,
10153,
10154,
10155,
10156,
10157,
10158,
10159,
10160,
10161,
10163,
10164,
10165,
10167,
10168,
10169,
10170,
10171,
10172,
10173,
10174,
10175,
10177,
10178,
10179,
10180,
10181,
10182,
10183,
7137,
7138,
7139,
7142,
7143,
7148,
7150,
7151,
7152,
7153,
7155,
7156,
7157,
9086,
9087,
9088,
9089,
9090,
9091,
9094,
9095,
9096,
9097,
2164]
</code></pre>
<p>I would like to shuffle this list and create a sublist of 19 values for each sublist.</p>
<p>I tried :</p>
<pre><code>list_ids.sort(key=lambda list_ids, r={b: random.random() for a, b in list_ids}: r[list_ids[1]])
</code></pre>
<p>But it didnt work. Looks like I am missing something.</p>
<p>End result is a sublist with shuffled values containing 19 values each</p>
|
[
{
"answer_id": 74487144,
"author": "StephanT",
"author_id": 10895042,
"author_profile": "https://Stackoverflow.com/users/10895042",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n\nids = pd.Series(list_ids)\nids.sample(19).values\n import random\nrandom.shuffle(list_ids)\nresult = {}\nfor i in list_ids:\n result[i] = [random.random() for x in range(19)]\nresult\n import random\nrandom.shuffle(list_ids)\nresult = {}\nfor i in list_ids:\n result[i] = [ids.sample(19).values]\nresult\n"
},
{
"answer_id": 74487168,
"author": "Runinho",
"author_id": 18724786,
"author_profile": "https://Stackoverflow.com/users/18724786",
"pm_score": 3,
"selected": true,
"text": "import random\n\n# shuffles list in place\nrandom.shuffle(list_ids)\n\n#split into lists containg 19 elements\nsplits = list([list_ids[i:i+19] for i in range(0,len(list_ids),19)])\n"
},
{
"answer_id": 74487209,
"author": "DMcC",
"author_id": 9809542,
"author_profile": "https://Stackoverflow.com/users/9809542",
"pm_score": 1,
"selected": false,
"text": "import random\n\ns = 19\nrandom.shuffle(list_ids)\nsub_lists = [list_ids[s*i:s*(i+1)] for i in range(len(list_ids) // s)]\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11883900/"
] |
74,487,068
|
<p>I wanted to connect a MySQL database to my Laravel application.<br />
I created one using <a href="https://www.phpmyadmin.net/" rel="nofollow noreferrer">PHPMyAdmin</a> administration tool of MySQL, then I added it in the <code>.env</code> as whereas the <code>database.php</code> application files.</p>
<p>I ran the terminal command: <code>php artisan migrate</code> which gave me the following error:</p>
<pre><code>could not find driver (SQL: select * from information_schema.tables where table_schema = pl_project and table_name = migrations and table_type = 'BASE TABLE')
at C:\Users\u\Documents\pl_project_test\pl_project_test\vendor\laravel\framework\src\Illuminate\Database\Connection.php:760
756▕ // If an exception occurs when attempting to run a query, we'll format the error
757▕ // message to include the bindings with SQL, which will make this exception a
758▕ // lot more helpful to the developer instead of just the database's errors.
759▕ catch (Exception $e) {
➜ 760▕ throw new QueryException(
761▕ $query, $this->prepareBindings($bindings), $e
762▕ );
763▕ }
764▕ }
1 C:\Users\u\Documents\pl_project_test\pl_project_test\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
PDOException::("could not find driver")
2 C:\Users\u\Documents\pl_project_test\pl_project_test\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
PDO::__construct()
</code></pre>
<h5>Here is the <code>.env</code> excerpt that I edited:</h5>
<pre><code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=pl_project
DB_USERNAME=root
DB_PASSWORD=
</code></pre>
<h5>Here is the <code>database.php</code> excerpt that I edited:</h5>
<pre class="lang-php prettyprint-override"><code>'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'pl_project'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
]
</code></pre>
<h5>Here is the output of the command: <code>php -m</code></h5>
<pre class="lang-bash prettyprint-override"><code>[PHP Modules]
bcmath
calendar
Core
ctype
curl
date
dom
fileinfo
filter
hash
iconv
json
libxml
mbstring
mysqlnd
openssl
pcre
PDO
Phar
readline
Reflection
session
SimpleXML
SPL
standard
tokenizer
xml
xmlreader
xmlwriter
zip
zlib
[Zend Modules]
</code></pre>
<h5>A couple of notes:</h5>
<ol>
<li>I did add PHP to my <em>env</em> variables as well as MySQL.</li>
<li>I did uncomment <code>extension=pdo_mysql</code> in <code>php.ini</code>.</li>
</ol>
<p>But none of it changed anything and I still get the same error.</p>
|
[
{
"answer_id": 74487144,
"author": "StephanT",
"author_id": 10895042,
"author_profile": "https://Stackoverflow.com/users/10895042",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n\nids = pd.Series(list_ids)\nids.sample(19).values\n import random\nrandom.shuffle(list_ids)\nresult = {}\nfor i in list_ids:\n result[i] = [random.random() for x in range(19)]\nresult\n import random\nrandom.shuffle(list_ids)\nresult = {}\nfor i in list_ids:\n result[i] = [ids.sample(19).values]\nresult\n"
},
{
"answer_id": 74487168,
"author": "Runinho",
"author_id": 18724786,
"author_profile": "https://Stackoverflow.com/users/18724786",
"pm_score": 3,
"selected": true,
"text": "import random\n\n# shuffles list in place\nrandom.shuffle(list_ids)\n\n#split into lists containg 19 elements\nsplits = list([list_ids[i:i+19] for i in range(0,len(list_ids),19)])\n"
},
{
"answer_id": 74487209,
"author": "DMcC",
"author_id": 9809542,
"author_profile": "https://Stackoverflow.com/users/9809542",
"pm_score": 1,
"selected": false,
"text": "import random\n\ns = 19\nrandom.shuffle(list_ids)\nsub_lists = [list_ids[s*i:s*(i+1)] for i in range(len(list_ids) // s)]\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20537718/"
] |
74,487,130
|
<p>Edited for clarity and reproduciblity....</p>
<p>I have a list of dataframes that I want to export to a folder on my PC via a file path. Doing this one at a time, or writing multiple <code>'write.csv'</code> commands is possible, but repetitive. Is there a way that I could use a for loop to export my data frames from that list using a single command?</p>
<p>example data:</p>
<pre><code>m1 <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
75, 10, 36, 36, 23, 55, 56, 24, 22, 66,
-7.8, -5.6, -2, -4.1, -8.4, -3, -4.2, -4, 0.1, -3), nrow = 10)
df <- as.data.frame(m1)
split_n <- 5
dlist <- split(df, factor(sort(rank(row.names(df))%%split_n)))
names(dlist) <- paste0("site_data", 1980:1984)
dlist
</code></pre>
<p>I can do the following, one file at a time:</p>
<pre><code>write.csv(dataList$table_1,"C:/filepath/dataframe_name_1.csv", row.names = F)
</code></pre>
<p>But doing this for hundreds of files isn't exactly efficient.</p>
<p>What I want to do is send the five data frames (site_data1980 : site_data1984) along my filepath to the folder on my PC as a list of named csv files.</p>
|
[
{
"answer_id": 74487337,
"author": "Julien",
"author_id": 8806649,
"author_profile": "https://Stackoverflow.com/users/8806649",
"pm_score": 1,
"selected": false,
"text": "lapply(seq_along(dataList), \\(i) write.csv(dataList[[i]], paste0(\"C:/filepath/dataframe_name_\", i, \".csv\"), row.names = F))\n"
},
{
"answer_id": 74487363,
"author": "Julian",
"author_id": 14137004,
"author_profile": "https://Stackoverflow.com/users/14137004",
"pm_score": 1,
"selected": true,
"text": "filepath <- \"C:/filepath/dataframe_name_\"\n\npurrr::imap(dlist, ~write.csv(x = .x, file = paste0(filepath, \n readr::parse_number(.y), \".csv\"), \n row.names = FALSE))\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17438953/"
] |
74,487,165
|
<p>Imagining I have these two <code>INSERT</code> statements, the first one was yesterday and the second one is today:</p>
<pre><code>INSERT INTO table(id, field1, field2, field3)
VALUES (1, "John", "Doe", "12345")
INSERT INTO table(id, field1, field2, field3)
VALUES (1, "Mary", "May", "12345")
</code></pre>
<p>Is there a way to make these <code>INSERT</code> statements not insert rows if there is already an equal value in any row in <code>field3</code>? This means the second record wouldn't be inserted.</p>
<p>I have searched for this but only found cases where they use the primary key as comparison.</p>
|
[
{
"answer_id": 74487241,
"author": "Eric Kong",
"author_id": 15723533,
"author_profile": "https://Stackoverflow.com/users/15723533",
"pm_score": 1,
"selected": false,
"text": "ALTER TABLE table ADD UNIQUE (field3);\n"
},
{
"answer_id": 74487244,
"author": "Haresh Makwana",
"author_id": 6607787,
"author_profile": "https://Stackoverflow.com/users/6607787",
"pm_score": 0,
"selected": false,
"text": "INSERT INTO table (id, field1, field2, field3)\nSELECT * FROM (SELECT 1 as id, 'John' as field1, 'Doe' as field2, '12345' as field3) AS tmp\nWHERE NOT EXISTS (\n SELECT id FROM table WHERE field3 = '12345'\n);\n\nINSERT INTO table (id, field1, field2, field3)\nSELECT * FROM (SELECT 1 as id, 'Mary' as field1, 'May' as field2, '12345' as field3) AS tmp\nWHERE NOT EXISTS (\n SELECT id FROM table WHERE field3 = '12345'\n);\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11025822/"
] |
74,487,176
|
<p>How do I change the shape of this data so that the subject column becomes a top row header containing all unique values. Name and Surnames are listed in the 1st and 2nd column as unique values. Then in each cell I need a true or false of whether the person is in that subject class. I need to transpose or reshape the data but how on earth is this done in code?</p>
<pre><code>SUBJECT NAME SURNAME
Art person1 Surname1
Art person2 surname2
Art person3 Surname3
Art person4 Surname4
Art person5 Surname5
Art person6 Surname6
Art person7 Surname7
Art person8 Surname8
DT person1 Surname1
DT person3 Surname3
DT person5 Surname5
Photography person1 Surname1
Photography person2 surname2
Photography person3 Surname3
Photography person5 Surname5
Photography person8 Surname8
Games person4 Surname4
Games person5 Surname5
Games person6 Surname6
Games person7 Surname7
Games person8 Surname8
Games person9 Surname9
</code></pre>
<p>So that it looks like this:</p>
<pre><code> Name Surname Art DT Photography Games
person1 Surname1 True False True etc....
person2 surname2 False True False etc...
person3 Surname3
person4 Surname4
person5 Surname5
person6 Surname6
person7 Surname7
person8 Surname8
person9 Surname9
</code></pre>
|
[
{
"answer_id": 74487212,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "crosstab out = (pd\n .crosstab([df['NAME'], df['SURNAME']], df['SUBJECT'])\n .astype(bool)\n .reset_index().rename_axis(columns=None)\n)\n NAME SURNAME Art DT Games Photography\n0 person1 Surname1 True True False True\n1 person2 surname2 True False False True\n2 person3 Surname3 True True False True\n3 person4 Surname4 True False True False\n4 person5 Surname5 True True True True\n5 person6 Surname6 True False True False\n6 person7 Surname7 True False True False\n7 person8 Surname8 True False True True\n8 person9 Surname9 False False True False\n"
},
{
"answer_id": 74487312,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 2,
"selected": false,
"text": "(df.value_counts().unstack(0)\n .notnull()\n .reindex(columns=df['SUBJECT'].unique())\n .reset_index()\n .rename_axis(columns=None))\n NAME SURNAME Art DT Photography Games\n0 person1 Surname1 True True True False\n1 person2 surname2 True False True False\n2 person3 Surname3 True True True False\n3 person4 Surname4 True False False True\n4 person5 Surname5 True True True True\n5 person6 Surname6 True False False True\n6 person7 Surname7 True False False True\n7 person8 Surname8 True False True True\n8 person9 Surname9 False False False True\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11436736/"
] |
74,487,208
|
<p>I have following dataframe named df.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>letter</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>x,y</td>
</tr>
<tr>
<td>2</td>
<td>z</td>
</tr>
<tr>
<td>3</td>
<td>a</td>
</tr>
</tbody>
</table>
</div>
<p>The mapping condition is {'x' : 1, 'z' : 2, 'ELSE' : 0}</p>
<p>my desired output dataframe should look like,</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>letter</th>
<th>map</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>x,y</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>z</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>a</td>
<td>0</td>
</tr>
</tbody>
</table>
</div>
<p>Which means, even any of the letters in column <code>letter</code> is x, then the column <code>map</code> should be 1.</p>
<p>Without iterating through each row of the dataframe, is there any way to do that?</p>
|
[
{
"answer_id": 74487275,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "cond = {'x' : 1, 'z' : 2, 'ELSE' : 0}\n\ndf['map'] = (df['letter']\n .str.split(',').explode()\n .map(lambda x: cond.get(x, cond['ELSE']))\n .groupby(level=0).max()\n)\n df['map'] = (df['letter']\n .str.split(',').explode()\n .map(cond)\n .groupby(level=0).first()\n .fillna(cond['ELSE'], downcast='infer')\n)\n cond = {'x' : 1, 'z' : 2, 'ELSE' : 0}\n\ndf['map'] = [next((cond[x] for x in s.split(',') if x in cond),\n cond['ELSE']) for s in df['letter']]\n id letter map\n0 1 x,y 1\n1 2 z 2\n2 3 a 0\n"
},
{
"answer_id": 74487583,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 0,
"selected": false,
"text": "np.select import numpy as np\n\ncond1 = df['letter'].str.contains('x')\ncond2 = df['letter'].str.contains('z')\ndf.assign(map=np.select([cond1, cond2], [1, 2], 0))\n id letter map\n0 1 x,y 1\n1 2 z 2\n2 3 a 0\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10428889/"
] |
74,487,250
|
<p>Our automated scripts have been installing this package for sometime without any issues. We also had this problem last week with the azcopy package (same error) - it was failing for around 4 days and then miraculously started working again. Is anyone else experiencing this?</p>
<p>Installing the package using:
<code>choco install iiscrypto</code></p>
<p>It seems that installing the choco package iiscrypto-cli 3.1 package is currently failing with the error message:</p>
<p>"ERROR: The remote file either doesn't exist, is unauthorized, or is forbidden for url 'https://www.nartac.com/Downloads/IISCrypto/IISCrypto40.exe'. Exception calling "GetResponse" with "0" argument(s): "The remote server returned an error: (404) Not Found.""</p>
|
[
{
"answer_id": 74487275,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "cond = {'x' : 1, 'z' : 2, 'ELSE' : 0}\n\ndf['map'] = (df['letter']\n .str.split(',').explode()\n .map(lambda x: cond.get(x, cond['ELSE']))\n .groupby(level=0).max()\n)\n df['map'] = (df['letter']\n .str.split(',').explode()\n .map(cond)\n .groupby(level=0).first()\n .fillna(cond['ELSE'], downcast='infer')\n)\n cond = {'x' : 1, 'z' : 2, 'ELSE' : 0}\n\ndf['map'] = [next((cond[x] for x in s.split(',') if x in cond),\n cond['ELSE']) for s in df['letter']]\n id letter map\n0 1 x,y 1\n1 2 z 2\n2 3 a 0\n"
},
{
"answer_id": 74487583,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 0,
"selected": false,
"text": "np.select import numpy as np\n\ncond1 = df['letter'].str.contains('x')\ncond2 = df['letter'].str.contains('z')\ndf.assign(map=np.select([cond1, cond2], [1, 2], 0))\n id letter map\n0 1 x,y 1\n1 2 z 2\n2 3 a 0\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5515824/"
] |
74,487,262
|
<p>Let's say I have a file called <code>File1.txt</code> that has the string</p>
<pre><code>Hamburger
</code></pre>
<p>And I have another file called <code>File2.txt</code> that has the string:</p>
<pre><code>I love Pizza
</code></pre>
<p>I want to use the <code>sed</code> command to make changes such that it copies all the text from <code>File1.txt</code> i.e. <code>Hamburger</code> and replace it in <code>File2.txt</code> with the word <code>Pizza</code> so that the final output in <code>File2.txt</code> would be</p>
<pre><code>I love Hamburger
</code></pre>
<p>Is there a way to do this suing the sed command ?</p>
<p>Here's an example of code I am trying to use but it doesn't work:</p>
<pre><code>sed -e '/Hamburger/{r File1.txt' -e 'd}' File2.txt
</code></pre>
|
[
{
"answer_id": 74487865,
"author": "sorpigal",
"author_id": 180736,
"author_profile": "https://Stackoverflow.com/users/180736",
"pm_score": 1,
"selected": false,
"text": "github-actions envsubst File2.txt I love $Pizza\n export Pizza=$(<File1.txt)\nenvsubst '$Pizza' < File2.txt\n $Pizza"
},
{
"answer_id": 74488225,
"author": "HatLess",
"author_id": 16372109,
"author_profile": "https://Stackoverflow.com/users/16372109",
"pm_score": 2,
"selected": true,
"text": "sed $ sed \"s/Pizza/$(cat File1.txt)/\" File2.txt\nI love Hamburger\n"
},
{
"answer_id": 74500068,
"author": "potong",
"author_id": 967492,
"author_profile": "https://Stackoverflow.com/users/967492",
"pm_score": 0,
"selected": false,
"text": "sed 's/.*/s#pizza#&#/' file2 | sed -f - file1\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19979471/"
] |
74,487,302
|
<p>I'm trying to solve the Leetcode's Two Sum problem (<a href="https://leetcode.com/problems/two-sum/" rel="nofollow noreferrer">https://leetcode.com/problems/two-sum/</a>) and my code runs well on small lists,</p>
<p>but the website outputs me 'time limit exceeded' when trying this list and target (<a href="https://leetcode.com/submissions/detail/845707290/testcase/" rel="nofollow noreferrer">https://leetcode.com/submissions/detail/845707290/testcase/</a>) (19999), although my coding environment outputs [9998, 9999] (after some time though)</p>
<pre><code>x = 0
y = 1
while x < len(nums):
if x == y:
y += 1
if (nums[x] + nums[y]) == target:
L = [x, y]
print(L)
break
if y == len(nums) - 1:
x += 1
y = 0
if (nums[x] + nums[y]) == target:
L = [x, y]
print(L)
break
#if x == len(nums) - 1:
# y += 1
# x = 0
elif (nums[x] + nums[y]) == target:
L = [x, y]
print(L)
break
y += 1
</code></pre>
<p>(My code in Leetcode contains return instead of print as it's a part of function)
Thanks.</p>
<p>Here is the code on LeetCode</p>
<pre><code>class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
x = 0
y = 1
while x < len(nums):
if x == y:
y += 1
if (nums[x] + nums[y]) == target:
L = [x, y]
return L
break
if y == len(nums) - 1:
x += 1
y = 0
if (nums[x] + nums[y]) == target:
L = [x, y]
return L
break
#if x == len(nums) - 1:
# y += 1
# x = 0
if (nums[x] + nums[y]) == target:
L = [x, y]
return L
break
y += 1
</code></pre>
<p>UPDATE 1</p>
<pre><code>class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
x = 0
y = 1
while x < len(nums):
if (nums[x] + nums[y]) == target:
L = [x, y]
return L
if y == len(nums) - 1:
x += 1
y = x + 1
if (nums[x] + nums[y]) == target:
L = [x, y]
return L
y += 1
</code></pre>
|
[
{
"answer_id": 74487517,
"author": "Nineteendo",
"author_id": 13454049,
"author_profile": "https://Stackoverflow.com/users/13454049",
"pm_score": 0,
"selected": false,
"text": "from datetime import datetime\nstart = datetime.now()\nnums = list(range(1,10_000 + 1))\ntarget = 19_999\nx = 0\ny = 1\nwhile x < len(nums):\n if x == y:\n y += 1\n if (nums[x] + nums[y]) == target:\n print([x, y])\n break\n if y == len(nums) - 1:\n x += 1\n y = 0\n if (nums[x] + nums[y]) == target:\n print([x, y])\n break\n if (nums[x] + nums[y]) == target:\n print([x, y])\n break\n y += 1\nprint(\"Finished in:\", datetime.now() - start)\n [9998, 9999]\nFinished in: 0:04:43.237951\n from datetime import datetime\nfrom typing import List\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n x = 0\n y = 1\n while x < len(nums):\n if x == y:\n y += 1\n if (nums[x] + nums[y]) == target:\n return [x, y]\n if y == len(nums) - 1:\n x += 1\n y = 0\n if (nums[x] + nums[y]) == target:\n return [x, y] \n if (nums[x] + nums[y]) == target: \n return [x, y]\n y += 1\n\nstart = datetime.now()\nnums = list(range(1, 10_000 + 1))\ntarget = 19_999\nprint(Solution().twoSum(nums, target))\nprint(\"Finished in:\", datetime.now() - start)\n [9998, 9999]\nFinished in: 0:03:47.205079\n from datetime import datetime\nfrom typing import List\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n x = 0\n y = 1\n while x < len(nums):\n if (nums[x] + nums[y]) == target:\n return [x, y]\n if y == len(nums) - 1:\n x += 1\n y = x + 1\n if (nums[x] + nums[y]) == target:\n return [x, y]\n y += 1\n\nstart = datetime.now()\nnums = list(range(1, 10_000 + 1))\ntarget = 19_999\nprint(Solution().twoSum(nums, target))\nprint(\"Finished in:\", datetime.now() - start)\n [9998, 9999]\nFinished in: 0:01:25.186796\n from datetime import datetime\nstart = datetime.now()\nnums = list(range(1,10_000 + 1))\ntarget = 19_999\nfor i, x in enumerate(nums):\n for j, y in enumerate(nums[i + 1:]):\n if x + y == target:\n break\n if x + y == target:\n print([i, i + 1 + j])\n break\nprint(\"Finished in:\", datetime.now() - start)\n [9998, 9999]\nFinished in: 0:00:28.605655\n from datetime import datetime\ndef find_sum(nums, target):\n for i, x in enumerate(nums):\n for j, y in enumerate(nums[i + 1:]):\n if x + y == target:\n return [i, i + 1 + j]\n\nstart = datetime.now()\nnums = list(range(1, 10_000 + 1))\ntarget = 19_999\nprint(find_sum(nums, target))\nprint(\"Finished in:\", datetime.now() - start)\n [9998, 9999]\nFinished in: 0:00:18.117496\n from datetime import datetime\ndef sum_of_two_edit(nums, target):\n lookup = {}\n for i, a in enumerate(nums):\n b = target - a\n j = lookup.get(b, None)\n if j is not None:\n return [j, i]\n lookup[a] = i\n\nstart = datetime.now()\nnums = list(range(1, 10_000 + 1))\ntarget = 19_999\nprint(sum_of_two_edit(nums, target))\nprint(\"Finished in:\", datetime.now() - start)\n [9998, 9999]\nFinished in: 0:00:00.010349\n from datetime import datetime\ndef twoSum(nums, target):\n d = {}\n for i, n in enumerate(nums):\n if (j := d.get(target - n)) is not None:\n return [i, j]\n d[n] = i\nstart = datetime.now()\nnums = list(range(1, 10_000 + 1))\ntarget = 19_999\nprint(twoSum(nums, target))\nprint(\"Finished in:\", datetime.now() - start)\n [9999, 9998]\nFinished in: 0:00:00.009762\n"
},
{
"answer_id": 74487668,
"author": "Dan Nagle",
"author_id": 2202018,
"author_profile": "https://Stackoverflow.com/users/2202018",
"pm_score": 2,
"selected": false,
"text": "nums = [1,5,2,7,21]\ntarget = 23\n\nlookup = { k:v for (v,k) in enumerate(nums) }\n\nfor a in nums:\n b = target - a\n if lookup.get(b, None):\n print([lookup[a], lookup[b]])\n break\n [2, 4]\n lookup.get() b def sum_of_two(nums, target):\n lookup = { value:index for (index, value) in enumerate(nums) }\n for a in nums:\n b = lookup.get(target - a, None)\n if b is not None:\n return([lookup[a], b])\n def sum_of_two_edit(nums, target):\n lookup = {}\n for i, a in enumerate(nums):\n b = target - a\n j = lookup.get(b, None)\n if j is not None:\n return [j, i]\n lookup[a] = i\n nums = [1,2,3,3,6]\ntarget = 6\n\nsum_of_two_edit(nums, target)\n [2, 3]\n"
},
{
"answer_id": 74487689,
"author": "loki.dev",
"author_id": 18439584,
"author_profile": "https://Stackoverflow.com/users/18439584",
"pm_score": -1,
"selected": false,
"text": "sorted() [].sort() def twoSum(self, nums: List[int], target: int) -> List[int]:\n sorted_list = list(sorted(nums)) # the most expensive part\n left, right = 0, len(nums) - 1 # start at the ends\n result = -1 # any value which is not \"possible\" suffices\n while result != target:\n if result < target:\n left += 1\n elif result > targe:t\n right -= 1\n value_left, value_right = sorted_list[left], sorted_list[right]\n result = value_left + value_right\n\n return [nums.index(value_left), nums.index(value_right)]\n"
},
{
"answer_id": 74487882,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 0,
"selected": false,
"text": " def twoSum(nums, target):\n d = {}\n for i, n in enumerate(nums):\n if (b := target - n) in d:\n return [i, d[b]]\n d[n] = i \n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310521/"
] |
74,487,324
|
<p>I have a list of random objects generated from a Model (querySet).
I intend to create a separate list of objects using some but not all of the values of the objects from the original list.</p>
<p>For instance,</p>
<pre class="lang-py prettyprint-override"><code>people = [
{'name': 'John', 'age': 20, 'location': 'Lagos'},
{'name': 'Kate', 'age': 40, 'location': 'Athens'},
{'name': 'Mike', 'age': 30, 'location': 'Delhi'},
{'name': 'Ben', 'age': 48, 'location': 'New York'}
]
</code></pre>
<p>Here's what I've tried:</p>
<pre class="lang-py prettyprint-override"><code>my_own_list = []
my_obj = {}
for person in people:
my_obj['your_name'] = person['name']
my_obj['your_location'] = person['location']
my_own_list.append(my_obj)
</code></pre>
<p>However, my code created only one obj, repeatedly four times.</p>
|
[
{
"answer_id": 74487365,
"author": "Runinho",
"author_id": 18724786,
"author_profile": "https://Stackoverflow.com/users/18724786",
"pm_score": 1,
"selected": true,
"text": "my_own_list = []\n\nfor person in people:\n my_obj = {}\n my_obj['your_name'] = person['name']\n my_obj['your_location'] = person['location']\n my_own_list.append(my_obj)\n"
},
{
"answer_id": 74487402,
"author": "Chris",
"author_id": 14408656,
"author_profile": "https://Stackoverflow.com/users/14408656",
"pm_score": 0,
"selected": false,
"text": "my_own_list = [{\"a\": person[\"name\"], \"b\": person[\"location\"]} for person in people]\n"
},
{
"answer_id": 74487436,
"author": "Stefano Fiorucci - anakin87",
"author_id": 10883094,
"author_profile": "https://Stackoverflow.com/users/10883094",
"pm_score": 1,
"selected": false,
"text": "my_own_list = []\n\nfor person in people:\n # every time you create a new dictionary\n my_obj = {}\n my_obj['your_name'] = person['name']\n my_obj['your_location'] = person['location']\n my_own_list.append(my_obj)\n [{k:v for k,v in p.items() if k in ['name', 'location']} for p in people]\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18823056/"
] |
74,487,361
|
<p>Execution time of this code is too long.</p>
<pre><code>df.rolling(window=255).apply(myFunc)
</code></pre>
<p>My dataframes shape is (500, 10000).</p>
<pre><code> 0 1 ... 9999
2021-11-01 0.011111 0.054242
2021-11-04 0.025244 0.003653
2021-11-05 0.524521 0.099521
2021-11-06 0.054241 0.138321
...
</code></pre>
<p>I make the calculation for each date with the last 255 date values. myFunc looks like:</p>
<pre><code>def myFunc(x):
coefs = ...
return np.sqrt(np.sum(x ** 2 * coefs))
</code></pre>
<p>I tried to use swifter but performances are the same :</p>
<pre><code>import swifter
df.swifter.rolling(window=255).apply(myFunc)
</code></pre>
<p>I also tried with Dask, but I think I didn't understand it well because the performance are not much better:</p>
<pre><code>import dask.dataframe as dd
ddf = dd.from_pandas(df)
ddf = ddf.rolling(window=255).apply(myFunc, raw=False)
ddf.execute()
</code></pre>
<p>I didn't manage to parallelize the execution with partitions. How can I use dask to improve performance ? I'm on Windows.</p>
|
[
{
"answer_id": 74487365,
"author": "Runinho",
"author_id": 18724786,
"author_profile": "https://Stackoverflow.com/users/18724786",
"pm_score": 1,
"selected": true,
"text": "my_own_list = []\n\nfor person in people:\n my_obj = {}\n my_obj['your_name'] = person['name']\n my_obj['your_location'] = person['location']\n my_own_list.append(my_obj)\n"
},
{
"answer_id": 74487402,
"author": "Chris",
"author_id": 14408656,
"author_profile": "https://Stackoverflow.com/users/14408656",
"pm_score": 0,
"selected": false,
"text": "my_own_list = [{\"a\": person[\"name\"], \"b\": person[\"location\"]} for person in people]\n"
},
{
"answer_id": 74487436,
"author": "Stefano Fiorucci - anakin87",
"author_id": 10883094,
"author_profile": "https://Stackoverflow.com/users/10883094",
"pm_score": 1,
"selected": false,
"text": "my_own_list = []\n\nfor person in people:\n # every time you create a new dictionary\n my_obj = {}\n my_obj['your_name'] = person['name']\n my_obj['your_location'] = person['location']\n my_own_list.append(my_obj)\n [{k:v for k,v in p.items() if k in ['name', 'location']} for p in people]\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15453459/"
] |
74,487,384
|
<p>I have 5 inputs and 5 buttons. I have two problems</p>
<ol>
<li>First, I want only one input to appear when a button is clicked.But
with the code I wrote, all inputs appear together</li>
<li>The second thing is that, when each button is clicked, the value
inside the button, which is a number here, will be displayed inside
the input.</li>
</ol>
<p>But with the code I wrote, by clicking on each button, the number inside it does not appear in the inptut.</p>
<p>In fact, by clicking on the first button, the number 1 should be displayed inside input 1.
By clicking on the second button, the number 2 will be displayed inside input 2.
By clicking on the third button, the number 3 will be displayed inside the input 3. and ....</p>
<p>In your opinion, the problem is the way of writing JavaScript codes or html?
Can you guide me or show me an example of this?</p>
<p>I would be grateful if you could guide me.</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>let myButtons = document.querySelectorAll(".myButton");
let myInputs = document.querySelectorAll(".myInput");
let print = document.querySelectorAll(".myInput > input");
let close = document.querySelectorAll(".close");
myButtons.forEach(function (buttonSelected, id) {
buttonSelected.addEventListener("click", function() {
print.value = id + 1;
console.log(id + 1);
for(let j = 0; j < myInputs.length; j ++ ){
myInputs[j].classList.add("active");
}
})
})
for (let i = 0; i < close.length; i++) {
close[i].addEventListener("click", function(){
this.parentNode.classList.remove("active")
})
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.myInput{
display: none;
align-items: center;
justify-content: space-between;
padding: 0.5rem 0.75rem;
width: 10%;
border-radius: var(--borderRadius20);
background: rgba(221, 199, 0, 0.2);
-webkit-margin-end: 1rem;
margin-inline-end: 1rem;
margin-bottom: 3rem;
border-radius: 5px;
}
.myInput.active{
display: flex;
}
.myInput > input{
width:90%;
border: none;
margin-right: 0.5rem;
border-radius: 5px;
}
.myInput > .close{
border: 1px solid blue;
border-radius: 5px;
cursor: pointer;
}
ul{
display: flex;
align-items: center;
border: 1px solid red;
width: auto;
margin-top: 1.5rem;
list-style: none;
}
.myButton{
padding: 1rem;
background: yellow;
border-radius: 10px;
margin-right: 0.5rem;
cursor: pointer;
border: 2px solid green;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- //inputs -->
<div>
<div class="myInput">
<input type="text" value>
<button class="close">close</button>
</div>
<div class="myInput">
<input type="text" value>
<button class="close">close</button>
</div>
<div class="myInput">
<input type="text" value>
<button class="close">close</button>
</div>
<div class="myInput">
<input type="text" value>
<button class="close">close</button>
</div>
<div class="myInput">
<input type="text" value>
<button class="close">close</button>
</div>
</div>
<!-- //buttons -->
<ul>
<li>
<button class="myButton">1</button>
</li>
<li>
<button class="myButton">2</button>
</li>
<li>
<button class="myButton">3</button>
</li>
<li>
<button class="myButton">4</button>
</li>
<li>
<button class="myButton">5</button>
</li>
</ul></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74487581,
"author": "pier farrugia",
"author_id": 19996700,
"author_profile": "https://Stackoverflow.com/users/19996700",
"pm_score": 0,
"selected": false,
"text": "document.querySelectorAll(\".myButton\").forEach(function(buttonSelected, id) {\n buttonSelected.addEventListener(\"click\", function(e) {\n const nb = e.target.innerHTML;\n hideAll();\n const el = document.querySelector('.input' + nb);\n el.innerHTML = nb;\n el.classList.add('active');\n })\n})\n\n\nfunction hideAll() {\n document.querySelectorAll('.myInput').forEach(e => {\n e.classList.remove('active');\n e.innerHTML = '';\n })\n} .myInput {\n display: none;\n align-items: center;\n justify-content: space-between;\n padding: 0.5rem 0.75rem;\n width: 10%;\n border-radius: var(--borderRadius20);\n background: rgba(221, 199, 0, 0.2);\n -webkit-margin-end: 1rem;\n margin-inline-end: 1rem;\n margin-bottom: 3rem;\n border-radius: 5px;\n}\n\n.myInput.active {\n display: flex;\n}\n\n.myInput>input {\n width: 90%;\n border: none;\n margin-right: 0.5rem;\n border-radius: 5px;\n}\n\n.myInput>.close {\n border: 1px solid blue;\n border-radius: 5px;\n cursor: pointer;\n}\n\nul {\n display: flex;\n align-items: center;\n border: 1px solid red;\n width: auto;\n margin-top: 1.5rem;\n list-style: none;\n}\n\n.myButton {\n padding: 1rem;\n background: yellow;\n border-radius: 10px;\n margin-right: 0.5rem;\n cursor: pointer;\n border: 2px solid green;\n} <!-- //inputs -->\n<div>\n <div class=\"myInput input1\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput input2\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput input3\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput input4\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput input5\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n</div>\n\n<!-- //buttons -->\n<ul>\n <li>\n <button class=\"myButton\">1</button>\n </li>\n <li>\n <button class=\"myButton\">2</button>\n </li>\n <li>\n <button class=\"myButton\">3</button>\n </li>\n <li>\n <button class=\"myButton\">4</button>\n </li>\n <li>\n <button class=\"myButton\">5</button>\n </li>\n</ul>"
},
{
"answer_id": 74487623,
"author": "George Chond",
"author_id": 17730652,
"author_profile": "https://Stackoverflow.com/users/17730652",
"pm_score": 2,
"selected": false,
"text": "print prints id close closes forEach let myButtons = document.querySelectorAll(\".myButton\");\nlet myInputs = document.querySelectorAll(\".myInput\");\nlet prints = document.querySelectorAll(\".myInput > input\");\nlet closes = document.querySelectorAll(\".close\");\n\nmyButtons.forEach((buttonSelected, id) => {\n buttonSelected.addEventListener(\"click\", () => {\n prints[id].value = id + 1;\n myInputs[id].classList.add(\"active\");\n })\n})\n\ncloses.forEach(close => close.addEventListener('click', () => close.parentNode.classList.remove('active'))); .myInput {\n display: none;\n align-items: center;\n justify-content: space-between;\n padding: 0.5rem 0.75rem;\n width: 10%;\n border-radius: var(--borderRadius20);\n background: rgba(221, 199, 0, 0.2);\n -webkit-margin-end: 1rem;\n margin-inline-end: 1rem;\n margin-bottom: 3rem;\n border-radius: 5px;\n}\n\n.myInput.active {\n display: flex;\n}\n\n.myInput>input {\n width: 90%;\n border: none;\n margin-right: 0.5rem;\n border-radius: 5px;\n}\n\n.myInput>.close {\n border: 1px solid blue;\n border-radius: 5px;\n cursor: pointer;\n}\n\nul {\n display: flex;\n align-items: center;\n border: 1px solid red;\n width: auto;\n margin-top: 1.5rem;\n list-style: none;\n}\n\n.myButton {\n padding: 1rem;\n background: yellow;\n border-radius: 10px;\n margin-right: 0.5rem;\n cursor: pointer;\n border: 2px solid green;\n} <div>\n <div class=\"myInput\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n</div>\n\n<ul>\n <li>\n <button class=\"myButton\">1</button>\n </li>\n <li>\n <button class=\"myButton\">2</button>\n </li>\n <li>\n <button class=\"myButton\">3</button>\n </li>\n <li>\n <button class=\"myButton\">4</button>\n </li>\n <li>\n <button class=\"myButton\">5</button>\n </li>\n</ul>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15034898/"
] |
74,487,390
|
<pre><code>public class Inputs
{
public string firstname { get; set; }
public string lastname { get; set; }
}
public class Data
{
public class D1 : Inputs { }
public class D2 : Inputs { }
public class D3 : Inputs { }
}
Data.D1 d1 = new Data.D1();
d1.firstname = "first";
Data.D2 d2 = new Data.D2();
d2.firstname = "first";
Data.D3 d3 = new Data.D3();
d3.firstname = "first";
</code></pre>
<p>I have 100 classes in Data form D1 to D100 is there a way to skip writing the same code for all 100 classes</p>
|
[
{
"answer_id": 74487581,
"author": "pier farrugia",
"author_id": 19996700,
"author_profile": "https://Stackoverflow.com/users/19996700",
"pm_score": 0,
"selected": false,
"text": "document.querySelectorAll(\".myButton\").forEach(function(buttonSelected, id) {\n buttonSelected.addEventListener(\"click\", function(e) {\n const nb = e.target.innerHTML;\n hideAll();\n const el = document.querySelector('.input' + nb);\n el.innerHTML = nb;\n el.classList.add('active');\n })\n})\n\n\nfunction hideAll() {\n document.querySelectorAll('.myInput').forEach(e => {\n e.classList.remove('active');\n e.innerHTML = '';\n })\n} .myInput {\n display: none;\n align-items: center;\n justify-content: space-between;\n padding: 0.5rem 0.75rem;\n width: 10%;\n border-radius: var(--borderRadius20);\n background: rgba(221, 199, 0, 0.2);\n -webkit-margin-end: 1rem;\n margin-inline-end: 1rem;\n margin-bottom: 3rem;\n border-radius: 5px;\n}\n\n.myInput.active {\n display: flex;\n}\n\n.myInput>input {\n width: 90%;\n border: none;\n margin-right: 0.5rem;\n border-radius: 5px;\n}\n\n.myInput>.close {\n border: 1px solid blue;\n border-radius: 5px;\n cursor: pointer;\n}\n\nul {\n display: flex;\n align-items: center;\n border: 1px solid red;\n width: auto;\n margin-top: 1.5rem;\n list-style: none;\n}\n\n.myButton {\n padding: 1rem;\n background: yellow;\n border-radius: 10px;\n margin-right: 0.5rem;\n cursor: pointer;\n border: 2px solid green;\n} <!-- //inputs -->\n<div>\n <div class=\"myInput input1\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput input2\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput input3\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput input4\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput input5\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n</div>\n\n<!-- //buttons -->\n<ul>\n <li>\n <button class=\"myButton\">1</button>\n </li>\n <li>\n <button class=\"myButton\">2</button>\n </li>\n <li>\n <button class=\"myButton\">3</button>\n </li>\n <li>\n <button class=\"myButton\">4</button>\n </li>\n <li>\n <button class=\"myButton\">5</button>\n </li>\n</ul>"
},
{
"answer_id": 74487623,
"author": "George Chond",
"author_id": 17730652,
"author_profile": "https://Stackoverflow.com/users/17730652",
"pm_score": 2,
"selected": false,
"text": "print prints id close closes forEach let myButtons = document.querySelectorAll(\".myButton\");\nlet myInputs = document.querySelectorAll(\".myInput\");\nlet prints = document.querySelectorAll(\".myInput > input\");\nlet closes = document.querySelectorAll(\".close\");\n\nmyButtons.forEach((buttonSelected, id) => {\n buttonSelected.addEventListener(\"click\", () => {\n prints[id].value = id + 1;\n myInputs[id].classList.add(\"active\");\n })\n})\n\ncloses.forEach(close => close.addEventListener('click', () => close.parentNode.classList.remove('active'))); .myInput {\n display: none;\n align-items: center;\n justify-content: space-between;\n padding: 0.5rem 0.75rem;\n width: 10%;\n border-radius: var(--borderRadius20);\n background: rgba(221, 199, 0, 0.2);\n -webkit-margin-end: 1rem;\n margin-inline-end: 1rem;\n margin-bottom: 3rem;\n border-radius: 5px;\n}\n\n.myInput.active {\n display: flex;\n}\n\n.myInput>input {\n width: 90%;\n border: none;\n margin-right: 0.5rem;\n border-radius: 5px;\n}\n\n.myInput>.close {\n border: 1px solid blue;\n border-radius: 5px;\n cursor: pointer;\n}\n\nul {\n display: flex;\n align-items: center;\n border: 1px solid red;\n width: auto;\n margin-top: 1.5rem;\n list-style: none;\n}\n\n.myButton {\n padding: 1rem;\n background: yellow;\n border-radius: 10px;\n margin-right: 0.5rem;\n cursor: pointer;\n border: 2px solid green;\n} <div>\n <div class=\"myInput\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n</div>\n\n<ul>\n <li>\n <button class=\"myButton\">1</button>\n </li>\n <li>\n <button class=\"myButton\">2</button>\n </li>\n <li>\n <button class=\"myButton\">3</button>\n </li>\n <li>\n <button class=\"myButton\">4</button>\n </li>\n <li>\n <button class=\"myButton\">5</button>\n </li>\n</ul>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19867742/"
] |
74,487,395
|
<p>I have a json data and I wanted to know how I can access the values using fetch api so that I can print it on the screen.
the json data from jsonplaceholder <a href="https://i.stack.imgur.com/YrkEP.png" rel="nofollow noreferrer"></a>.
the page I want it to be displayed</p>
<p><a href="https://i.stack.imgur.com/CwdpE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CwdpE.png" alt="enter image description here" /></a></p>
<p>.
the code of that page.</p>
<pre><code>
import React, { useEffect, useState } from 'react';
function More() {
const [item, setItem] = useState();
const queryParams = new URLSearchParams(window.location.search);
const id = queryParams.get("id");
const fetchData = () => {
fetch(`https://jsonplaceholder.typicode.com/todos?userId=1&&id=${id}`)
.then((response) => response.json())
.then((json) => {
console.log(json)
setItem(json)
// console.log(item)
});
};
useEffect(() => {
fetchData();
}, [1])
//const id = new URLSearchParams(search).id;
//console.log(id);
return (
<div>
<h1>more information about list</h1>
<h3>Todo id: </h3>
</div>
)
}
export default More;
</code></pre>
|
[
{
"answer_id": 74487581,
"author": "pier farrugia",
"author_id": 19996700,
"author_profile": "https://Stackoverflow.com/users/19996700",
"pm_score": 0,
"selected": false,
"text": "document.querySelectorAll(\".myButton\").forEach(function(buttonSelected, id) {\n buttonSelected.addEventListener(\"click\", function(e) {\n const nb = e.target.innerHTML;\n hideAll();\n const el = document.querySelector('.input' + nb);\n el.innerHTML = nb;\n el.classList.add('active');\n })\n})\n\n\nfunction hideAll() {\n document.querySelectorAll('.myInput').forEach(e => {\n e.classList.remove('active');\n e.innerHTML = '';\n })\n} .myInput {\n display: none;\n align-items: center;\n justify-content: space-between;\n padding: 0.5rem 0.75rem;\n width: 10%;\n border-radius: var(--borderRadius20);\n background: rgba(221, 199, 0, 0.2);\n -webkit-margin-end: 1rem;\n margin-inline-end: 1rem;\n margin-bottom: 3rem;\n border-radius: 5px;\n}\n\n.myInput.active {\n display: flex;\n}\n\n.myInput>input {\n width: 90%;\n border: none;\n margin-right: 0.5rem;\n border-radius: 5px;\n}\n\n.myInput>.close {\n border: 1px solid blue;\n border-radius: 5px;\n cursor: pointer;\n}\n\nul {\n display: flex;\n align-items: center;\n border: 1px solid red;\n width: auto;\n margin-top: 1.5rem;\n list-style: none;\n}\n\n.myButton {\n padding: 1rem;\n background: yellow;\n border-radius: 10px;\n margin-right: 0.5rem;\n cursor: pointer;\n border: 2px solid green;\n} <!-- //inputs -->\n<div>\n <div class=\"myInput input1\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput input2\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput input3\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput input4\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput input5\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n</div>\n\n<!-- //buttons -->\n<ul>\n <li>\n <button class=\"myButton\">1</button>\n </li>\n <li>\n <button class=\"myButton\">2</button>\n </li>\n <li>\n <button class=\"myButton\">3</button>\n </li>\n <li>\n <button class=\"myButton\">4</button>\n </li>\n <li>\n <button class=\"myButton\">5</button>\n </li>\n</ul>"
},
{
"answer_id": 74487623,
"author": "George Chond",
"author_id": 17730652,
"author_profile": "https://Stackoverflow.com/users/17730652",
"pm_score": 2,
"selected": false,
"text": "print prints id close closes forEach let myButtons = document.querySelectorAll(\".myButton\");\nlet myInputs = document.querySelectorAll(\".myInput\");\nlet prints = document.querySelectorAll(\".myInput > input\");\nlet closes = document.querySelectorAll(\".close\");\n\nmyButtons.forEach((buttonSelected, id) => {\n buttonSelected.addEventListener(\"click\", () => {\n prints[id].value = id + 1;\n myInputs[id].classList.add(\"active\");\n })\n})\n\ncloses.forEach(close => close.addEventListener('click', () => close.parentNode.classList.remove('active'))); .myInput {\n display: none;\n align-items: center;\n justify-content: space-between;\n padding: 0.5rem 0.75rem;\n width: 10%;\n border-radius: var(--borderRadius20);\n background: rgba(221, 199, 0, 0.2);\n -webkit-margin-end: 1rem;\n margin-inline-end: 1rem;\n margin-bottom: 3rem;\n border-radius: 5px;\n}\n\n.myInput.active {\n display: flex;\n}\n\n.myInput>input {\n width: 90%;\n border: none;\n margin-right: 0.5rem;\n border-radius: 5px;\n}\n\n.myInput>.close {\n border: 1px solid blue;\n border-radius: 5px;\n cursor: pointer;\n}\n\nul {\n display: flex;\n align-items: center;\n border: 1px solid red;\n width: auto;\n margin-top: 1.5rem;\n list-style: none;\n}\n\n.myButton {\n padding: 1rem;\n background: yellow;\n border-radius: 10px;\n margin-right: 0.5rem;\n cursor: pointer;\n border: 2px solid green;\n} <div>\n <div class=\"myInput\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n <div class=\"myInput\">\n <input type=\"text\" value>\n <button class=\"close\">close</button>\n </div>\n</div>\n\n<ul>\n <li>\n <button class=\"myButton\">1</button>\n </li>\n <li>\n <button class=\"myButton\">2</button>\n </li>\n <li>\n <button class=\"myButton\">3</button>\n </li>\n <li>\n <button class=\"myButton\">4</button>\n </li>\n <li>\n <button class=\"myButton\">5</button>\n </li>\n</ul>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20526756/"
] |
74,487,404
|
<p>I'm trying to fill a column down with a specific value. I stupidly used the xlDown function, which crashed Excel. I want the cells of column B to be filled <em>only</em> as long as the cells in column A aren't empty.</p>
<p>My idea at the moment is to declare a variable and initialize it with the value of the length of any other column, then set that variable as the end of the range, but I think using a loop would be a better alternative?</p>
<pre><code>Sub fillColumn()
Dim myrange as Range
Set myrange = Columns(1)
For Each cell In myrange.Cells
Do While cell <> vbNullString
Cell.Offset(0,1).Value = "Yes"
Next
Loop
End Sub()
</code></pre>
<p>I can't figure out how to handle <code>do-while</code> loops in conjunction with <code>for</code> loops, though, so I would appreciate any tips.</p>
|
[
{
"answer_id": 74487530,
"author": "kasjer",
"author_id": 7910019,
"author_profile": "https://Stackoverflow.com/users/7910019",
"pm_score": 1,
"selected": false,
"text": "for i = firstrow to lastrow\n if cells(i, yourColumn).value2 <> vbnullstring then\n cells(i, yourColumn+1).value2=\"yes\"\n end if\nnext i\n"
},
{
"answer_id": 74487880,
"author": "FaneDuru",
"author_id": 2233308,
"author_profile": "https://Stackoverflow.com/users/2233308",
"pm_score": 3,
"selected": true,
"text": "Sub fillBforNotEmptyA()\n Dim sh As Worksheet, lastR As Long, rngA As Range\n \n Set sh = ActiveSheet 'use here the sheet you need\n lastR = sh.Range(\"A\" & sh.rows.count).End(xlUp).row 'last row in A:A\n Set rngA = sh.Range(\"A2:A\" & lastR) 'the reference range\n \n sh.Range(\"B2:B\" & lastR).Value2 = sh.Evaluate(\"IF(\" & _\n rngA.address & \"<>\"\"\"\",\"\"Yes\"\",\"\"\"\")\")\nEnd Sub\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20197062/"
] |
74,487,421
|
<p>I want to manipulate the data after receiving it from the server in Datatable. Data comes from the web server. But the response data from server is encoded. To decode the data I need to call another asynchronous function (here decodeData() ).
I tried to call async funtion in dataSrc section like following example but data is not displayed in the table.</p>
<pre><code>$(document).ready(function () {
$('#example').DataTable({
processing: true,
serverSide: true,
"ajax": {
"url": "http://localhost:3000",
"dataSrc": async function ( json ) { // I added async
// call async funtion here
json.data = await decodeData(json)
return json.data;
}
});
});
</code></pre>
<p>Then I tried to using the xhr event, but it didn't work properly.</p>
<pre><code>var table = $('#example')
.on('xhr.dt', async function ( e, settings, json, xhr ) { // added async
json = await decodeData(json);
} ).DataTable({
processing: true,
serverSide: true,
"ajax": {
"url": "http://localhost:3000",
},
});
</code></pre>
<p>As far as I understand Datatable event handlers don't expect async functions - so they don't wait for the Promise to complete. How can I call the asynchronous function before the table is drawn?</p>
|
[
{
"answer_id": 74487448,
"author": "Muhammed YILMAZ",
"author_id": 19262548,
"author_profile": "https://Stackoverflow.com/users/19262548",
"pm_score": 0,
"selected": false,
"text": "$(document).ready(function () {\n $('#example').DataTable({\n processing: true,\n serverSide: true,\n \"ajax\": {\n \"url\": \"http://localhost:3000\",\n \"dataSrc\": async function ( json ) { // I added async\n // call async funtion here\n json.data = await decodeData(json)\n return json.data;\n }\n });\n});\n http://localhost:3000/persons/getpersons $(document).ready(function () {\n $('#example').DataTable({\n processing: true,\n serverSide: true,\n \"ajax\": {\n \"url\": \"http://localhost:3000\",\n \"dataSrc\": async function ( json ) { // I added async\n // call async funtion here\n json.data = await decodeData(json)\n return json.data;\n },\n \"error\": function(xhr){ \n console.log(xhr); \n }\n });\n });\n"
},
{
"answer_id": 74489694,
"author": "vsam",
"author_id": 1261941,
"author_profile": "https://Stackoverflow.com/users/1261941",
"pm_score": -1,
"selected": true,
"text": " $('#example').DataTable({\n processing: true,\n serverSide: true,\n ajax: function (data, callback, settings) {\n$.ajax({\n url: 'http://localhost:3000/',\n data: data,\n success:async function(data){\n data = await decodeData(data);\n \n callback(data);\n \n }\n});\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5174791/"
] |
74,487,433
|
<p>I don't know why my back arrow on the toolbar does nothing, can anybody help me?</p>
<p>I leave here the onCreate of the activity, the adapter and the xml
Im using recyclerView with constraint layout</p>
<p>here is the code of the Activity "onCreate" class:</p>
<pre><code>@Override
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(com.owncloud.android.R.layout.accounts_layout)
tintedCheck = ContextCompat.getDrawable(this, com.owncloud.android.R.drawable.ic_current_white)!!
tintedCheck = DrawableCompat.wrap(tintedCheck)
val tint = ContextCompat.getColor(this, com.owncloud.android.R.color.actionbar_start_color)
DrawableCompat.setTint(tintedCheck, tint)
val recyclerView: RecyclerView = findViewById(com.owncloud.android.R.id.account_list_recycler_view)
recyclerView.run {
filterTouchesWhenObscured = PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(applicationContext)
adapter = accountListAdapter
layoutManager = LinearLayoutManager(this@AccountManagementActivity)
}
setupStandardToolbar(
getString(com.owncloud.android.R.string.prefs_manage_accounts),
displayHomeAsUpEnabled = true,
homeButtonEnabled = true,
displayShowTitleEnabled = true
)
val accountList = AccountManager.get(this).getAccountsByType(accountType)
originalAccounts = toAccountNameSet(accountList)
originalCurrentAccount = AccountUtils.getCurrentOwnCloudAccount(this).name
accountListAdapter.submitAccountList(accountList = getAccountListItems())
account = AccountUtils.getCurrentOwnCloudAccount(this)
onAccountSet(false)
/**
// added click listener to switch account
recyclerView.onItemClickListener = OnItemClickListener { parent, view, position, id ->
switchAccount(
position
)
}
*/
}
</code></pre>
<p>The code from the Adapter, implementing the recyclerView:</p>
<pre><code>class AccountManagementAdapter(private val accountListener: AccountManagementActivity) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var accountItemsList = listOf<AccountRecyclerItem>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val inflater = LayoutInflater.from(parent.context)
return if (viewType == AccountManagementRecyclerItemViewType.ITEM_VIEW_ACCOUNT.ordinal) {
val view = inflater.inflate(R.layout.account_item, parent, false)
view.filterTouchesWhenObscured = PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(parent.context)
AccountManagementViewHolder(view)
} else {
val view = inflater.inflate(R.layout.account_action, parent, false)
view.filterTouchesWhenObscured = PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(parent.context)
NewAccountViewHolder(view)
}
}
fun submitAccountList(accountList: List<AccountRecyclerItem>) {
accountItemsList = accountList
notifyDataSetChanged()
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is AccountManagementViewHolder -> {
val accountItem = getItem(position) as AccountRecyclerItem.AccountItem
val account: Account = accountItem.account
try {
val oca = OwnCloudAccount(account, holder.itemView.context)
holder.binding.name.text = oca.displayName
} catch (e: Exception) {
Timber.w(
"Account not found right after being read :\\ ; using account name instead of display " +
"name"
)
holder.binding.name.text = AccountUtils.getUsernameOfAccount(account.name)
}
holder.binding.name.tag = account.name
holder.binding.account.text = DisplayUtils.convertIdn(account.name, false)
try {
val avatarUtils = AvatarUtils()
avatarUtils.loadAvatarForAccount(
holder.binding.icon,
account,
true,
20f
)
} catch (e: java.lang.Exception) {
Timber.e(e, "Error calculating RGB value for account list item.")
// use user icon as a fallback
holder.binding.icon.setImageResource(R.drawable.ic_user)
}
if (AccountUtils.getCurrentOwnCloudAccount(holder.itemView.context).name == account.name) {
holder.binding.ticker.visibility = View.VISIBLE
} else {
holder.binding.ticker.visibility = View.INVISIBLE
}
/// bind listener to refresh account
holder.binding.refreshAccountButton.apply {
setImageResource(R.drawable.ic_action_refresh)
setOnClickListener { accountListener.refreshAccount(account) }
}
/// bind listener to change password
holder.binding.passwordButton.apply {
setImageResource(R.drawable.ic_baseline_lock_reset_grey)
setOnClickListener { accountListener.changePasswordOfAccount(account) }
}
/// bind listener to remove account
holder.binding.removeButton.apply {
setImageResource(R.drawable.ic_action_delete_grey)
setOnClickListener { accountListener.removeAccount(account) }
}
///bind listener to switchAccount
holder.binding.account.apply {
setOnClickListener { accountListener.switchAccount(position) }
}
}
is NewAccountViewHolder -> {
holder.binding.icon.setImageResource(R.drawable.ic_account_plus)
holder.binding.name.setText(R.string.prefs_add_account)
// bind action listener
holder.binding.linearLayout.setOnClickListener {
accountListener.createAccount()
}
}
}
}
override fun getItemCount(): Int = accountItemsList.size
fun getItem(position: Int) = accountItemsList[position]
sealed class AccountRecyclerItem {
data class AccountItem(val account: Account) : AccountRecyclerItem()
object NewAccount : AccountRecyclerItem()
}
class AccountManagementViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val binding = AccountItemBinding.bind(itemView)
}
class NewAccountViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val binding = AccountActionBinding.bind(itemView)
}
override fun getItemViewType(position: Int): Int {
return when (getItem(position)) {
is AccountRecyclerItem.AccountItem -> AccountManagementRecyclerItemViewType.ITEM_VIEW_ACCOUNT.ordinal
is AccountRecyclerItem.NewAccount -> AccountManagementRecyclerItemViewType.ITEM_VIEW_ADD.ordinal
}
}
enum class AccountManagementRecyclerItemViewType {
ITEM_VIEW_ACCOUNT, ITEM_VIEW_ADD
}
/**
* Listener interface for Activities using the [AccountListAdapter]
*/
interface AccountAdapterListener {
fun removeAccount(account: Account)
fun changePasswordOfAccount(account: Account)
fun refreshAccount(account: Account)
fun createAccount()
fun switchAccount(position: Int)
}
}
</code></pre>
<p>and finally i leave you two xml files, which are the one where all the items are declared and the one where the recyclerView is implemented:</p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/accounts_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
layout="@layout/owncloud_toolbar" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/account_list_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
</code></pre>
<pre><code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="?android:attr/selectableItemBackground"
>
<ImageView
android:id="@+id/icon"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginStart="@dimen/standard_margin"
android:src="@drawable/ic_account_plus"
android:background="?android:attr/selectableItemBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="@+id/ticker"
android:layout_width="16dp"
android:layout_height="16dp"
android:layout_marginTop="-8dp"
android:layout_marginEnd="-8dp"
android:src="@drawable/ic_current"
app:layout_constraintEnd_toEndOf="@id/icon"
app:layout_constraintTop_toTopOf="@id/icon" />
<!-- drawable will be replaced by ic_current_white + tint in runtime;
ic_current here as a placeholder -->
<TextView
android:id="@+id/name"
android:layout_width="210dp"
android:layout_height="28dp"
android:layout_marginStart="24dp"
android:layout_marginTop="4dp"
android:gravity="bottom"
android:maxLines="1"
android:text="@string/placeholder_filename"
android:textColor="@color/textColor"
android:textSize="16sp"
android:textStyle="bold"
android:background="?android:attr/selectableItemBackground"
app:layout_constraintEnd_toStartOf="@+id/refreshAccountButton"
app:layout_constraintStart_toEndOf="@id/ticker"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/account"
android:layout_width="210dp"
android:layout_height="44dp"
android:layout_marginStart="30dp"
android:layout_marginEnd="@dimen/standard_half_margin"
android:layout_marginBottom="4dp"
android:ellipsize="end"
android:text="@string/placeholder_sentence"
android:textColor="@color/textColor"
android:textSize="14sp"
android:background="?android:attr/selectableItemBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@id/refreshAccountButton"
app:layout_constraintStart_toEndOf="@id/ticker"
app:layout_constraintTop_toBottomOf="@id/name" />
<ImageView
android:id="@+id/refreshAccountButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:contentDescription="@string/actionbar_sync"
android:paddingLeft="@dimen/standard_half_padding"
android:paddingTop="@dimen/standard_padding"
android:paddingRight="@dimen/standard_half_padding"
android:paddingBottom="@dimen/standard_padding"
android:src="@drawable/ic_action_refresh"
android:background="?android:attr/selectableItemBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@id/passwordButton"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:tint="@color/black" />
<ImageView
android:id="@+id/passwordButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingLeft="@dimen/standard_half_padding"
android:paddingTop="@dimen/standard_padding"
android:paddingRight="@dimen/standard_half_padding"
android:paddingBottom="@dimen/standard_padding"
android:src="@drawable/ic_baseline_lock_reset_grey"
android:background="?android:attr/selectableItemBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@id/removeButton"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:tint="@color/black" />
<ImageView
android:id="@+id/removeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingStart="@dimen/standard_half_padding"
android:paddingTop="@dimen/standard_padding"
android:paddingEnd="@dimen/standard_padding"
android:paddingBottom="@dimen/standard_padding"
android:src="@drawable/ic_action_delete_grey"
android:background="?android:attr/selectableItemBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:tint="@color/black" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code></pre>
<p>if any more code is needed i can add it :)</p>
<p>i tried adding something like this:</p>
<pre><code>if(item.getItemId() ==android.R.id.home){
onBackPressed();
}
</code></pre>
<p>and something like this:</p>
<pre><code>binding.toolbar.setNavigationOnClickListener { navController.popBackStack() }
</code></pre>
<p>but nothing worked</p>
|
[
{
"answer_id": 74487448,
"author": "Muhammed YILMAZ",
"author_id": 19262548,
"author_profile": "https://Stackoverflow.com/users/19262548",
"pm_score": 0,
"selected": false,
"text": "$(document).ready(function () {\n $('#example').DataTable({\n processing: true,\n serverSide: true,\n \"ajax\": {\n \"url\": \"http://localhost:3000\",\n \"dataSrc\": async function ( json ) { // I added async\n // call async funtion here\n json.data = await decodeData(json)\n return json.data;\n }\n });\n});\n http://localhost:3000/persons/getpersons $(document).ready(function () {\n $('#example').DataTable({\n processing: true,\n serverSide: true,\n \"ajax\": {\n \"url\": \"http://localhost:3000\",\n \"dataSrc\": async function ( json ) { // I added async\n // call async funtion here\n json.data = await decodeData(json)\n return json.data;\n },\n \"error\": function(xhr){ \n console.log(xhr); \n }\n });\n });\n"
},
{
"answer_id": 74489694,
"author": "vsam",
"author_id": 1261941,
"author_profile": "https://Stackoverflow.com/users/1261941",
"pm_score": -1,
"selected": true,
"text": " $('#example').DataTable({\n processing: true,\n serverSide: true,\n ajax: function (data, callback, settings) {\n$.ajax({\n url: 'http://localhost:3000/',\n data: data,\n success:async function(data){\n data = await decodeData(data);\n \n callback(data);\n \n }\n});\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20289804/"
] |
74,487,480
|
<p>I'm fairly new to spring boot and Java, I've been working on a REST API using springboot for an ecommerce project but for some reason I can't get the products from the database, my products are getting saved to the database but whenever I fetch them the fields show up as null values.<a href="https://i.stack.imgur.com/gWlVn.png" rel="nofollow noreferrer">this is what I get when I use GET using Postman.</a></p>
<p>My controller and other files are as follows.</p>
<pre><code>package com.ecommerce.ecommerceappapi.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ecommerce.ecommerceappapi.model.Product;
import com.ecommerce.ecommerceappapi.services.ProductService;
@CrossOrigin(origins = "http://localhost:3000")
@RestController
@RequestMapping("api/v1/")
public class ProductController {
@Autowired
private final ProductService productService;
public ProductController(ProductService productService) {
this.productService = productService;
}
@PostMapping("/products")
public Product createProduct(@RequestBody Product product) {
return productService.createProduct(product);
}
@GetMapping("/products")
public List<Product> getAllProducts() {
return productService.getAllProducts();
}
}
</code></pre>
<p>Entity -></p>
<pre><code>package com.ecommerce.ecommerceappapi.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
@Entity
@Data
@Table(name="products")
public class ProductEntity {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private long prodId;
private String productName;
private int productPrice;
private String productDesc;
private String productData;
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getProductPrice() {
return productPrice;
}
public void setProductPrice(int productPrice) {
this.productPrice = productPrice;
}
public String getProductDesc() {
return productDesc;
}
public void setProductDesc(String productDesc) {
this.productDesc = productDesc;
}
public String getProductData() {
return productData;
}
public void setProductData(String productData) {
this.productData = productData;
}
public Long getProdId() {
// TODO Auto-generated method stub
return prodId;
}
}
</code></pre>
<p>Service Interface -></p>
<pre><code>package com.ecommerce.ecommerceappapi.services;
import java.util.List;
import com.ecommerce.ecommerceappapi.model.Product;
public interface ProductService {
Product createProduct(Product product);
List<Product> getAllProducts();
}
</code></pre>
<p>Service Implementation -></p>
<pre><code>package com.ecommerce.ecommerceappapi.services;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.BeanUtils;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import com.ecommerce.ecommerceappapi.entity.ProductEntity;
import com.ecommerce.ecommerceappapi.model.Product;
import com.ecommerce.ecommerceappapi.repository.ProductRepository;
@Service
public class ProductServiceImpl implements ProductService {
private ProductRepository productRepository;
public ProductServiceImpl(ProductRepository productRepository) {
super();
this.productRepository = productRepository;
}
@Override
public Product createProduct(Product product) {
// TODO Auto-generated method stub
ProductEntity productEntity = new ProductEntity();
BeanUtils.copyProperties(product, productEntity);
productRepository.save(productEntity);
return product;
}
@Override
public List<Product> getAllProducts(){
List<ProductEntity> productEntities = productRepository.findAll();
List<Product> products = productEntities.stream().map(product -> new Product(
product.getProdId(),
product.getProductName(),
product.getProductPrice(),
product.getProductDesc()))
.collect(Collectors.toList());
return products;
}
}
</code></pre>
<p>Repository -></p>
<pre><code>package com.ecommerce.ecommerceappapi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.ecommerce.ecommerceappapi.entity.ProductEntity;
@Repository
public interface ProductRepository extends JpaRepository<ProductEntity, Long> {
}
</code></pre>
<p>Product -></p>
<pre><code>package com.ecommerce.ecommerceappapi.model;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
//import java.util.List;
import lombok.Data;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Product {
private long prodId;
private String productName;
private int productPrice;
private String productDesc;
private String productData;
public Product(Long prodId2, String productName2, int productPrice2, String productDesc2) {
// TODO Auto-generated constructor stub;
return;
}
public long getProdId() {
return prodId;
}
public void setProdId(long prodId) {
this.prodId = prodId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getProductPrice() {
return productPrice;
}
public void setProductPrice(int productPrice) {
this.productPrice = productPrice;
}
public String getProductDesc() {
return productDesc;
}
public void setProductDesc(String productDesc) {
this.productDesc = productDesc;
}
public String getProductData() {
return productData;
}
public void setProductData(String productData) {
this.productData = productData;
}
}
</code></pre>
<p>I figure the Product class is causing the issue as the method</p>
<pre><code>public Product(Long prodId2, String productName2, int productPrice2, String productDesc2) {
// TODO Auto-generated constructor stub;
return;
}
</code></pre>
<p>does not return anything, otherwise I'm totally lost as to what might be the issue here.</p>
|
[
{
"answer_id": 74487448,
"author": "Muhammed YILMAZ",
"author_id": 19262548,
"author_profile": "https://Stackoverflow.com/users/19262548",
"pm_score": 0,
"selected": false,
"text": "$(document).ready(function () {\n $('#example').DataTable({\n processing: true,\n serverSide: true,\n \"ajax\": {\n \"url\": \"http://localhost:3000\",\n \"dataSrc\": async function ( json ) { // I added async\n // call async funtion here\n json.data = await decodeData(json)\n return json.data;\n }\n });\n});\n http://localhost:3000/persons/getpersons $(document).ready(function () {\n $('#example').DataTable({\n processing: true,\n serverSide: true,\n \"ajax\": {\n \"url\": \"http://localhost:3000\",\n \"dataSrc\": async function ( json ) { // I added async\n // call async funtion here\n json.data = await decodeData(json)\n return json.data;\n },\n \"error\": function(xhr){ \n console.log(xhr); \n }\n });\n });\n"
},
{
"answer_id": 74489694,
"author": "vsam",
"author_id": 1261941,
"author_profile": "https://Stackoverflow.com/users/1261941",
"pm_score": -1,
"selected": true,
"text": " $('#example').DataTable({\n processing: true,\n serverSide: true,\n ajax: function (data, callback, settings) {\n$.ajax({\n url: 'http://localhost:3000/',\n data: data,\n success:async function(data){\n data = await decodeData(data);\n \n callback(data);\n \n }\n});\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20537761/"
] |
74,487,485
|
<p>Here is a sample of the data</p>
<pre><code> df<-read.table (text=" A1.1 A1.2 A1.3 A1.4 A1.5
3 3 4 3 1
0 4 1 2 4
4 1 0 4 3
1 2 3 3 3
4 4 3 3 3
1 3 0 1 4
0 1 3 0 0
1 1 0 0 1
", header=TRUE)
</code></pre>
<p>The outcome is</p>
<pre><code> Score Freq Percent
0 8 20
1 10 25
2 2 5
3 12 30
4 8 20
Total 40 100
</code></pre>
<p>I want to get the frequency and percentage for each score.
For example, 0 appears 8 times, so frequency= 8 and percentage= 8/40*100= 20
Assume that I have a large matrix. Is there a simple code to get this outcome?</p>
|
[
{
"answer_id": 74487588,
"author": "user2974951",
"author_id": 2974951,
"author_profile": "https://Stackoverflow.com/users/2974951",
"pm_score": 2,
"selected": true,
"text": "df2=data.frame(table(unlist(df)))\ndf2$Percent=df2$Freq/sum(df2$Freq)*100\n\n Var1 Freq Percent\n1 0 8 20\n2 1 10 25\n3 2 2 5\n4 3 12 30\n5 4 8 20\n"
},
{
"answer_id": 74487685,
"author": "zx8754",
"author_id": 680068,
"author_profile": "https://Stackoverflow.com/users/680068",
"pm_score": 0,
"selected": false,
"text": "x <- table(unlist(df))\ndata.frame(x, prop.table(x) * 100)\n# Var1 Freq Var1.1 Freq.1\n# 1 0 8 0 20\n# 2 1 10 1 25\n# 3 2 2 2 5\n# 4 3 12 3 30\n# 5 4 8 4 20\n"
},
{
"answer_id": 74488156,
"author": "harre",
"author_id": 4786466,
"author_profile": "https://Stackoverflow.com/users/4786466",
"pm_score": 2,
"selected": false,
"text": "tabyl janitor library(janitor)\n\ndf |> \n unlist() |>\n tabyl() |>\n adorn_totals(\"row\") |>\n adorn_pct_formatting()\n unlist(df) n percent\n 0 8 20.0%\n 1 10 25.0%\n 2 2 5.0%\n 3 12 30.0%\n 4 8 20.0%\n Total 40 100.0%\n"
},
{
"answer_id": 74488284,
"author": "dufei",
"author_id": 10363163,
"author_profile": "https://Stackoverflow.com/users/10363163",
"pm_score": 0,
"selected": false,
"text": "df %>% \n unlist() %>% \n as_tibble() %>% \n count(value) %>% \n mutate(share = n / sum(n))\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13095591/"
] |
74,487,493
|
<p>I'm trying to rotate a texture inside vertex shader. I have a pointer to a texture that, for my purpose, is rotated counterclockwise by 90 degrees. I <strong>don't want</strong> to manually rotate the texture before calling <code>glTexImage2D()</code>.</p>
<p>I can use <code>#version 120</code> only.</p>
<p>This is my original vertex shader:</p>
<pre><code>#version 120
attribute vec4 a_position;
attribute vec2 a_texCoord;
varying vec2 v_texCoord;
void main()
{
gl_Position = a_position;
v_texCoord = a_texCoord;
}
</code></pre>
<p>For testing purpose only, I modified the vertex shader in this way but I get a black screen:</p>
<pre><code>#version 120
const float w = 0.76;
float mat3 A = ( 1, 0, 0,
0, 1, 0,
0, 0, 1 );
attribute vec3 a_position;
attribute vec2 a_texCoord;
varying vec2 v_texCoord;
void main()
{
A = ( cos(w), -sin(w), 0,
sin(w), cos(w), 0,
0, 0, 1 );
gl_Position = A * vec4(a_position, 1.0f);
v_texCoord = a_texCoord;
}
</code></pre>
|
[
{
"answer_id": 74487636,
"author": "Rabbid76",
"author_id": 5577765,
"author_profile": "https://Stackoverflow.com/users/5577765",
"pm_score": 3,
"selected": true,
"text": "A = (cos(w), -sin(w), 0,\n sin(w), cos(w), 0,\n 0, 0, 1 );\n mat3 A = mat3(cos(w), -sin(w), 0.0,\n sin(w), cos(w), 0.0,\n 0.0, 0.0, 1.0);\n vec4 mat3 vec3 mat3 gl_Position = vec4(A * a_position, 1.0f);\n float mat3 A = ( 1, 0, 0,\n 0, 1, 0,\n 0, 0, 1 );\n mat3 A = mat3(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0);\n mat3 A = mat3(1.0);\n #version 120\n\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\n\nvoid main()\n{\n const float w = 0.76;\n mat3 A = mat3(cos(w), -sin(w), 0.0,\n sin(w), cos(w), 0.0,\n 0.0, 0.0, 1.0);\n gl_Position = vec4(A * a_position, 1.0);\n v_texCoord = a_texCoord;\n}\n"
},
{
"answer_id": 74487718,
"author": "Summit",
"author_id": 12651320,
"author_profile": "https://Stackoverflow.com/users/12651320",
"pm_score": 0,
"selected": false,
"text": "layout (location = 0) in vec3 aPos;\nlayout (location = 1) in vec3 aNormal;\nlayout (location = 2) in vec2 aTexCoord;\n\n\n\nuniform mat4 textureMatrix;\n\nout vec2 TexCoord;\n\nvoid main()\n{\n vec4 mTex; \n mTex = textureMatrix * vec4( aTexCoord.x , aTexCoord.y , 0.0 , 1.0 );\nTexCoord = vec2(mTex.x , mTex.y );\n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7556145/"
] |
74,487,528
|
<p>I want to make the sidenavigation modul to close when i click the linkes inside the sidenav, the links works but it does not close the modul</p>
<p>index.html</p>
<pre><code> <!-- side navbar -->
<div class="sidenav" id="sidenav">
<span class="cancel-btn" id="cancel-btn">
<i class="fas fa-times"></i>
</span>
<ul class="navbar">
<li><a href="#header" id = "closemodal">home</a></li>
<li><a href="#services">services</a></li>
<li><a href="#rooms">rooms</a></li>
<li><a href="#customers">customers</a></li>
</ul>
</div>
<!-- end of side navbar -->
<!-- fullscreen modal -->
<div id="modal"></div>
<!-- end of fullscreen modal -->
</code></pre>
<p>script.js</p>
<pre><code>const navBtn = document.getElementById('nav-btn');
const cancelBtn = document.getElementById('cancel-btn');
const sideNav = document.getElementById('sidenav');
const modal = document.getElementById('modal');
navBtn.addEventListener("click", function(){
sideNav.classList.add('show');
modal.classList.add('showModal');
});
cancelBtn.addEventListener('click', function(){
sideNav.classList.remove('show');
modal.classList.remove('showModal');
});
window.addEventListener('click', function(event){
if(event.target === modal){
sideNav.classList.remove('show');
modal.classList.remove('showModal');
}
});
</code></pre>
<p>i have tried adding this code from research but its not working</p>
<pre><code>$(function(){
$('#closemodal').click(function() {
$('#sidenav').modal('hide');
});
})
</code></pre>
|
[
{
"answer_id": 74487636,
"author": "Rabbid76",
"author_id": 5577765,
"author_profile": "https://Stackoverflow.com/users/5577765",
"pm_score": 3,
"selected": true,
"text": "A = (cos(w), -sin(w), 0,\n sin(w), cos(w), 0,\n 0, 0, 1 );\n mat3 A = mat3(cos(w), -sin(w), 0.0,\n sin(w), cos(w), 0.0,\n 0.0, 0.0, 1.0);\n vec4 mat3 vec3 mat3 gl_Position = vec4(A * a_position, 1.0f);\n float mat3 A = ( 1, 0, 0,\n 0, 1, 0,\n 0, 0, 1 );\n mat3 A = mat3(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0);\n mat3 A = mat3(1.0);\n #version 120\n\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\n\nvoid main()\n{\n const float w = 0.76;\n mat3 A = mat3(cos(w), -sin(w), 0.0,\n sin(w), cos(w), 0.0,\n 0.0, 0.0, 1.0);\n gl_Position = vec4(A * a_position, 1.0);\n v_texCoord = a_texCoord;\n}\n"
},
{
"answer_id": 74487718,
"author": "Summit",
"author_id": 12651320,
"author_profile": "https://Stackoverflow.com/users/12651320",
"pm_score": 0,
"selected": false,
"text": "layout (location = 0) in vec3 aPos;\nlayout (location = 1) in vec3 aNormal;\nlayout (location = 2) in vec2 aTexCoord;\n\n\n\nuniform mat4 textureMatrix;\n\nout vec2 TexCoord;\n\nvoid main()\n{\n vec4 mTex; \n mTex = textureMatrix * vec4( aTexCoord.x , aTexCoord.y , 0.0 , 1.0 );\nTexCoord = vec2(mTex.x , mTex.y );\n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16449134/"
] |
74,487,534
|
<p>I want to create a procedure show if a given number prime</p>
<p>what i have tried so far :</p>
<pre class="lang-py prettyprint-override"><code>def premier(a):
isPrimary=False
for i in range(2,a//2):
if(a%i==0):
isPrimary=True
break
if(isPrimary==True):
print(a,'est un nbre premier')
else:
print(a,'non premier')
c = int(input("Donner un nbre"))
premier(c)
</code></pre>
<p>test failed :
<code>Donner un nbre8 8 est un nbre premier</code>
which is not prime</p>
|
[
{
"answer_id": 74487574,
"author": "Chris",
"author_id": 14408656,
"author_profile": "https://Stackoverflow.com/users/14408656",
"pm_score": 0,
"selected": false,
"text": "def is_prime(n):\n for i in range(2,n):\n if (n % i) == 0:\n return False\n return True\n"
},
{
"answer_id": 74488339,
"author": "motiur.ion",
"author_id": 4063963,
"author_profile": "https://Stackoverflow.com/users/4063963",
"pm_score": -1,
"selected": false,
"text": " def premier(a):\n isPrimary=False\n for i in range(2,a//2):\n if(a%i!=0):\n isPrimary=True\n break\n if(isPrimary==True):\n print(a,'est un nbre premier')\n else:\n print(a,'non premier')\n c = int(input(\"Donner un nbre\"))\n premier(c)\n def premier(a):\n isPrimary=False\n for i in range(2,a//2):\n if(a%i==0):\n isPrimary=False\n break\n if(isPrimary==True):\n print(a,'est un nbre premier')\n else:\n print(a,'non premier')\n c = int(input(\"Donner un nbre\"))\n premier(c)\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20522314/"
] |
74,487,544
|
<p>I'm receiving data from a server in the form of an array, which I'm storing in a variable; the data is arriving every 5 seconds, so I need to store every array that comes through the server into an array.</p>
<p>So the array looks like this:</p>
<p><a href="https://i.stack.imgur.com/zM1Fd.png" rel="nofollow noreferrer">array</a></p>
<p>It's saved in a variable, and I'm setting it to log every 5 seconds, so all the different data is getting logged.</p>
<p>So I need to get it stored in an array. This is the variable from which the array is coming; here is my code: </p>
<pre><code>setInterval(function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = this.responseText;
snifferOnServer(myObj);
}
};
xhr.open('GET', 'http://192.168.43.154/wifimac', true);
xhr.send();
}, 7000);
function snifferOnServer(x) {
let obj = x.split(']');
// console.log(obj);
for (let i = 0; i < obj.length; i++) {
mac = obj[i];
macIdData = mac.split(',');
console.log(macIdData);
}
}
</code></pre>
<p>The array I was seeing in the console was getting through macIdData. I need to store all of the data in a new array The macIdData is a 2 dimensional array.</p>
<p>Thank You.</p>
<p>Need to store a variable which consist of array into a new array.</p>
|
[
{
"answer_id": 74487678,
"author": "Ademir Šehić",
"author_id": 13893004,
"author_profile": "https://Stackoverflow.com/users/13893004",
"pm_score": 0,
"selected": false,
"text": "let array = [];\n\nfor (let i = 0; i < 5; i++) {\n array = [...array, [1,2,3,4,5]];\n}\nconsole.log(array);"
},
{
"answer_id": 74488319,
"author": "Fru Promise",
"author_id": 14746701,
"author_profile": "https://Stackoverflow.com/users/14746701",
"pm_score": 1,
"selected": false,
"text": "// Sample of API data\nlet rawData = JSON.stringify([\n [\"1234\", \"45678\", \"9\"],\n [\"abc\", \"def\", \"ghi\"],\n [\"ABC\", \"DEF\", \"GHI\"]\n])\n\nsnifferOnServer(rawData);\n\nfunction snifferOnServer(data) {\n let obj = JSON.parse(data);\n let macIdData = [];\n\n // Loop through the obj dataset\n obj.forEach((mac) => {\n // Loop through the mac dataset\n mac.forEach((items) => {\n // store each value in the mac Array\n macIdData.push(items);\n })\n });\n\n console.log(macIdData);\n};\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19844902/"
] |
74,487,557
|
<p>Hi im a programming student and im trying to build a login/register page. and ive written a custom hook to get data of the user/ post data to login or register.
and my problem is that react only accepts custom hooks inside react components or other custom hooks and i want to post the login/register on button click.
whats the best why to use custom hooks onClick?</p>
<p><code>Custom useFetch hook</code></p>
<pre><code>import React, { useState, useEffect } from "react";
import axios from "axios";
import { useHistory } from "react-router-dom";
import { toast } from "react-toastify";
const useFetch = () => {
const [data, setData] = useState([]);
const history = useHistory();
let initialBizCardArray = [];
useEffect(() => {
(async () => {
try {
let currLocation = history.location.pathname;
switch (currLocation) {
case (currLocation = "/my-cards"):
case (currLocation = "/cards"):
{
let { data } = await axios.get(`/cards${currLocation}`);
initialBizCardArray = data;
setData(initialBizCardArray);
}
break;
case (currLocation = "/login"):
case (currLocation = "/register"):
{
let { data } = await axios.post(`/users${currLocation}`);
initialBizCardArray = data;
setData(initialBizCardArray);
}
break;
}
} catch (error) {
toast.error(error, {
position: "top-right",
autoClose: 2000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
return { error };
}
})();
}, []);
return { data, setData, initialBizCardArray };
};
export default useFetch;
</code></pre>
<p><code>How i tried using the useFetch</code></p>
<pre><code>const handleSubmitLogIn = async (ev) => {
ev.preventDefault();
ValidateErr(
{
email: loginInput.email,
password: loginInput.password,
},
loginSchema
);
try {
let { data } = await useFetch(userLocation, {
email: loginInput.email,
password: loginInput.password,
});
console.log("Succuss");
localStorage.setItem("token", data.token);
autoLoginFunction(data.token);
setTimeout(() => {
let userInfo = jwt_decode(data.token);
userInfo && userInfo.biz
? history.push("/my-cards")
: history.push("/");
}, 100);
} catch (err) {
console.error("error", err.response.data);
toast.error(` Email or password are invalid.`, err, {
position: "top-right",
autoClose: 2000,
hideProgressBar: false,
progress: undefined,
});
history.push("/login");
}
</code></pre>
|
[
{
"answer_id": 74487678,
"author": "Ademir Šehić",
"author_id": 13893004,
"author_profile": "https://Stackoverflow.com/users/13893004",
"pm_score": 0,
"selected": false,
"text": "let array = [];\n\nfor (let i = 0; i < 5; i++) {\n array = [...array, [1,2,3,4,5]];\n}\nconsole.log(array);"
},
{
"answer_id": 74488319,
"author": "Fru Promise",
"author_id": 14746701,
"author_profile": "https://Stackoverflow.com/users/14746701",
"pm_score": 1,
"selected": false,
"text": "// Sample of API data\nlet rawData = JSON.stringify([\n [\"1234\", \"45678\", \"9\"],\n [\"abc\", \"def\", \"ghi\"],\n [\"ABC\", \"DEF\", \"GHI\"]\n])\n\nsnifferOnServer(rawData);\n\nfunction snifferOnServer(data) {\n let obj = JSON.parse(data);\n let macIdData = [];\n\n // Loop through the obj dataset\n obj.forEach((mac) => {\n // Loop through the mac dataset\n mac.forEach((items) => {\n // store each value in the mac Array\n macIdData.push(items);\n })\n });\n\n console.log(macIdData);\n};\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18678710/"
] |
74,487,572
|
<p>Say that I have the following lists</p>
<pre><code>L = [("a0","a1"),("b0",),("b1","a1","b0"),("a0","a1"),("b0",)]
M = ["u0", "u1", "u2", "u3", "u4", "u5", "u6", "u7" , "u8"]
</code></pre>
<p>and I want to group the elements of <code>M</code> into a list of tuples <code>N</code> such that <code>N</code> has the same structure of <code>L</code>, i.e.</p>
<pre><code>N = [("u0", "u1"), ("u2",), ("u3", "u4", "u5"), ("u6", "u7") , ("u8",)]
</code></pre>
<p>or, to be more precise, such that <code>[len(L[ii]) == len(N[ii]) for ii, t in enumerate(L)]</code> has all <code>True</code> elements and <code>M == Q</code>, where <code>Q = [item for t in N for item in t]</code></p>
<p>How to do that?</p>
|
[
{
"answer_id": 74487626,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 3,
"selected": false,
"text": "it = iter(M)\n res = [tuple(itertools.islice(it, len(t))) for t in L]\n"
},
{
"answer_id": 74487641,
"author": "sahasrara62",
"author_id": 5086255,
"author_profile": "https://Stackoverflow.com/users/5086255",
"pm_score": 1,
"selected": false,
"text": ">>> L = [(\"a0\",\"a1\"),(\"b0\",),(\"b1\",\"a1\",\"b0\"),(\"a0\",\"a1\"),(\"b0\",)]\n>>> M = [\"u0\", \"u1\", \"u2\", \"u3\", \"u4\", \"u5\", \"u6\", \"u7\" , \"u8\"]\n>>> R =[]\n>>> idx = 0\n>>> for i in [len(j) for j in L]:\n... R.append(tuple(M[idx:idx+i]))\n... idx+=i\n... \n>>> R\n[('u0', 'u1'), ('u2',), ('u3', 'u4', 'u5'), ('u6', 'u7'), ('u8',)]\n"
},
{
"answer_id": 74488253,
"author": "anonymous",
"author_id": 18113554,
"author_profile": "https://Stackoverflow.com/users/18113554",
"pm_score": 0,
"selected": false,
"text": "L = [(\"a0\",\"a1\"),(\"b0\",),(\"b1\",\"a1\",\"b0\"),(\"a0\",\"a1\"),(\"b0\",)]\nM = [\"u0\", \"u1\", \"u2\", \"u3\", \"u4\", \"u5\", \"u6\", \"u7\" , \"u8\"]\n\nlen_L_elements = []\n\nfor i in L:\n len_L_elements.append(len(i))\n \nprint(len_L_elements)\n\nres = []\nc = 0 # It will handle element of M\nd = 0 # It will handle element of len_L_elemenst\n\nwhile c <= len(M)-1 and d <= len(len_L_elements)-1:\n temp_lis = [] # this will convert int tuple on time of append\n cnt = 0 # Initialize with 0 on one tuple creation\n while cnt <= len_L_elements[d]-1:\n temp_lis.append(M[c])\n c+=1\n cnt+=1\n \n # Convert List into tuple\n temp_tuple = tuple(temp_lis)\n res.append(temp_tuple)\n d+=1\nprint(res)\n \n \n\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2562058/"
] |
74,487,599
|
<p>I want one of my several SELECT statements to not print the column headers, just the selected records. Is this possible in Cassandra 3.0?</p>
<p>I tried the below but it returns the column name:</p>
<pre><code>cqlsh -e "select count(1) from system_schema.keyspaces where keyspace_name='test'";
count
-------
1
</code></pre>
<p>MySQL has options like -s -N to suppress the same.</p>
|
[
{
"answer_id": 74487626,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 3,
"selected": false,
"text": "it = iter(M)\n res = [tuple(itertools.islice(it, len(t))) for t in L]\n"
},
{
"answer_id": 74487641,
"author": "sahasrara62",
"author_id": 5086255,
"author_profile": "https://Stackoverflow.com/users/5086255",
"pm_score": 1,
"selected": false,
"text": ">>> L = [(\"a0\",\"a1\"),(\"b0\",),(\"b1\",\"a1\",\"b0\"),(\"a0\",\"a1\"),(\"b0\",)]\n>>> M = [\"u0\", \"u1\", \"u2\", \"u3\", \"u4\", \"u5\", \"u6\", \"u7\" , \"u8\"]\n>>> R =[]\n>>> idx = 0\n>>> for i in [len(j) for j in L]:\n... R.append(tuple(M[idx:idx+i]))\n... idx+=i\n... \n>>> R\n[('u0', 'u1'), ('u2',), ('u3', 'u4', 'u5'), ('u6', 'u7'), ('u8',)]\n"
},
{
"answer_id": 74488253,
"author": "anonymous",
"author_id": 18113554,
"author_profile": "https://Stackoverflow.com/users/18113554",
"pm_score": 0,
"selected": false,
"text": "L = [(\"a0\",\"a1\"),(\"b0\",),(\"b1\",\"a1\",\"b0\"),(\"a0\",\"a1\"),(\"b0\",)]\nM = [\"u0\", \"u1\", \"u2\", \"u3\", \"u4\", \"u5\", \"u6\", \"u7\" , \"u8\"]\n\nlen_L_elements = []\n\nfor i in L:\n len_L_elements.append(len(i))\n \nprint(len_L_elements)\n\nres = []\nc = 0 # It will handle element of M\nd = 0 # It will handle element of len_L_elemenst\n\nwhile c <= len(M)-1 and d <= len(len_L_elements)-1:\n temp_lis = [] # this will convert int tuple on time of append\n cnt = 0 # Initialize with 0 on one tuple creation\n while cnt <= len_L_elements[d]-1:\n temp_lis.append(M[c])\n c+=1\n cnt+=1\n \n # Convert List into tuple\n temp_tuple = tuple(temp_lis)\n res.append(temp_tuple)\n d+=1\nprint(res)\n \n \n\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6868255/"
] |
74,487,627
|
<p>I have a dataframe like as shown below</p>
<pre><code>customer_id revenue_m7 revenue_m8 revenue_m9 revenue_m10
1 1234 1231 1256 1239
2 5678 3425 3255 2345
</code></pre>
<p>I would like to do the below</p>
<p>a) get average of revenue for each customer based on latest two columns (revenue_m9 and revenue_m10)</p>
<p>b) get average of revenue for each customer based on latest four columns (revenue_m7, revenue_m8, revenue_m9 and revenue_m10)</p>
<p>So, I tried the below</p>
<pre><code>df['revenue_mean_2m'] = (df['revenue_m10']+df['revenue_m9'])/2
df['revenue_mean_4m'] = (df['revenue_m10']+df['revenue_m9']+df['revenue_m8']+df['revenue_m7'])/4
df['revenue_mean_4m'] = df.mean(axis=1) # i also tried this but how to do for only two columns (and not all columns)
</code></pre>
<p>But if I wish to compute average for past 12 months, then it may not be elegant to write this way. Is there any other better or efficient way to write this? I can just key in number of columns to look back and it can compute the average based on keyed in input</p>
<p>I expect my output to be like as below</p>
<pre><code>customer_id revenue_m7 revenue_m8 revenue_m9 revenue_m10 revenue_mean_2m revenue_mean_4m
1 1234 1231 1256 1239 1867 1240
2 5678 3425 3255 2345 2800 3675.75
</code></pre>
|
[
{
"answer_id": 74487656,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "filter # keep only the \"revenue_\" columns\ndf2 = df.filter(like='revenue_')\n# or\n# df2 = df.filter(regex=r'revenue_m\\d+')\n\n# get last 2/4 columns and aggregate as mean\ndf['revenue_mean_2m'] = df2.iloc[:, -2:].mean(axis=1)\ndf['revenue_mean_4m'] = df2.iloc[:, -4:].mean(axis=1)\n customer_id revenue_m7 revenue_m8 revenue_m9 revenue_m10 \\\n0 1 1234 1231 1256 1239 \n1 2 5678 3425 3255 2345 \n\n revenue_mean_2m revenue_mean_4m \n0 1247.5 1240.00 \n1 2800.0 3675.75 \n # shuffle the DataFrame columns for demo\ndf = df.sample(frac=1, axis=1)\n\n# filter and reorder the needed columns\nfrom natsort import natsort_key\ndf2 = df.filter(regex=r'revenue_m\\d+').sort_index(key=natsort_key, axis=1)\n"
},
{
"answer_id": 74487736,
"author": "maxxel_",
"author_id": 17575465,
"author_profile": "https://Stackoverflow.com/users/17575465",
"pm_score": 1,
"selected": false,
"text": "n_months = 4 # you could also do this in a loop for all months range(1, 12)\n\ndf[f'revenue_mean_{n_months}m'] = df.iloc[:, -n_months:-1].mean(axis=1)\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10829044/"
] |
74,487,650
|
<pre><code>double S = 0;
double *pSum = &S;
double P = 0;
double *pAverage = &P;
printf("The average and sum of the variables: %lf %lf", &S, &P);
</code></pre>
<p>I'm working with pointers and functions but for some reason I can't understand why I'm getting 2 warning specifically</p>
<p>non-float passed as argument <code>3</code> when float is required in call to <code>printf</code> actual type: <code>double *</code>.
non-float passed as argument <code>2</code> when float is required in call to <code>printf</code> actual type: <code>double *</code>.</p>
<p>To be completely honest I don't know what to try to get rid of the warning.</p>
|
[
{
"answer_id": 74487688,
"author": "Some programmer dude",
"author_id": 440558,
"author_profile": "https://Stackoverflow.com/users/440558",
"pm_score": 2,
"selected": false,
"text": "scanf printf & printf(\"The average and sum of the variables: %lf %lf\", S, P);\n"
},
{
"answer_id": 74487876,
"author": "Almogbb",
"author_id": 17378664,
"author_profile": "https://Stackoverflow.com/users/17378664",
"pm_score": 0,
"selected": false,
"text": "printf(\"The average and sum of the variables: %lf %lf\", S, P); printf(\"The average and sum of the variables: %lf %lf\", *pSum, *pAverage); *"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20276643/"
] |
74,487,654
|
<p>I have a dialogue component in which I have created a ref, but I also want to pass the ref from the parent to it. How can I do this?</p>
<pre><code>import { forwardRef } from "react";
export const PopOver = ({
show = false,
...
}, ref) => {
const thisRef = useRef(null);
// dealing with UI changes with 'thisRef'
return (
<div
ref={thisRef}, // How can I add a `ref` here?
....
>
Hello world
</div>
);
};
export default forwardRef(PopOver);
</code></pre>
|
[
{
"answer_id": 74487693,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 0,
"selected": false,
"text": "useEffect const otherRef = useRef(null);\nconst thisRef = useRef(null);\n\nuseEffect(() => {\n otherRef.current = thisRef.current;\n}, [thisRef.current]);\n\nreturn <div ref={thisRef} />;\n"
},
{
"answer_id": 74487728,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 2,
"selected": true,
"text": " <div ref={ref}>\n <div\n ref={thisRef}\n ....\n >\n Hello world\n </div>\n </div>\n useEffect(()=>{\n if(ref.current){\n thisRef.current = ref.current\n }\n},[ref])\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12609736/"
] |
74,487,664
|
<p>I have some strange error in my SPM.</p>
<p><strong>Code example:</strong></p>
<pre class="lang-swift prettyprint-override"><code>import SwiftUI
struct ExampleView: View {
var body: some View {
Text("Stub")
}
}
</code></pre>
<p><strong>Error:</strong></p>
<blockquote>
<p>'some' return types are only available in macOS 10.15.0 or newer</p>
</blockquote>
<p>But I have <code>macOS Ventura 13.0.1</code>, & <code>XCode 14.1</code>. What could be the problem?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 74487693,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 0,
"selected": false,
"text": "useEffect const otherRef = useRef(null);\nconst thisRef = useRef(null);\n\nuseEffect(() => {\n otherRef.current = thisRef.current;\n}, [thisRef.current]);\n\nreturn <div ref={thisRef} />;\n"
},
{
"answer_id": 74487728,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 2,
"selected": true,
"text": " <div ref={ref}>\n <div\n ref={thisRef}\n ....\n >\n Hello world\n </div>\n </div>\n useEffect(()=>{\n if(ref.current){\n thisRef.current = ref.current\n }\n},[ref])\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6465611/"
] |
74,487,673
|
<p>I want to match a pattern that starts with $ and ends with either dot(.) or double quote(").
I tried with this</p>
<pre><code>re.findall(r"\$(.+?)\.",query1)
</code></pre>
<p>Above works for starting with $ and ending with .
How to add OR in ending characters so that it matches with pattern ending either with . or with "</p>
<p>Any suggestions ?</p>
|
[
{
"answer_id": 74487693,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 0,
"selected": false,
"text": "useEffect const otherRef = useRef(null);\nconst thisRef = useRef(null);\n\nuseEffect(() => {\n otherRef.current = thisRef.current;\n}, [thisRef.current]);\n\nreturn <div ref={thisRef} />;\n"
},
{
"answer_id": 74487728,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 2,
"selected": true,
"text": " <div ref={ref}>\n <div\n ref={thisRef}\n ....\n >\n Hello world\n </div>\n </div>\n useEffect(()=>{\n if(ref.current){\n thisRef.current = ref.current\n }\n},[ref])\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11577186/"
] |
74,487,691
|
<p>I'm looking for the right sql query to do the following operation:
I need to display all record for today and for each make sum of price field for the curent user and date < today</p>
<p>Table Commandes: (today = 11/18/2022)</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>username</th>
<th>date</th>
<th>price</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>user.1</td>
<td>11/21/2022</td>
<td>99.0</td>
</tr>
<tr>
<td>2</td>
<td>user.x</td>
<td>11/21/2022</td>
<td>99.0</td>
</tr>
<tr>
<td>3</td>
<td>user.1</td>
<td>11/18/2022</td>
<td>2.5</td>
</tr>
<tr>
<td>4</td>
<td>user.x</td>
<td>11/18/2022</td>
<td>10.0</td>
</tr>
<tr>
<td>5</td>
<td>user.1</td>
<td>11/17/2022</td>
<td>2.5</td>
</tr>
<tr>
<td>6</td>
<td>user.x</td>
<td>11/17/2022</td>
<td>20.0</td>
</tr>
<tr>
<td>7</td>
<td>user.1</td>
<td>11/16/2022</td>
<td>2.5</td>
</tr>
<tr>
<td>8</td>
<td>user.x</td>
<td>11/16/2022</td>
<td>30.0</td>
</tr>
</tbody>
</table>
</div>
<p>I want:</p>
<pre><code>| ID | username | date | price | solde
| -------- | -------- |------------|------- |------
| 1 | user.1 | 11/18/2022 | 2.5 | 5.0
| 2 | user.x | 11/18/2022 | 10.0 | 40.0
</code></pre>
<p>solde would be same as "backorder not yet payed". When Item is payed, field price is set to 0.</p>
<p>For now, i use this query:</p>
<p>SELECT * FROM Commandes WHERE (Date='11/18/2022')</p>
<p>And in each row I execute:</p>
<pre><code>SELECT sum(price) as solde
FROM Commandes
WHERE (username=currentselecteduser) and (STR_TO_DATE(date, '%m/%d/%Y') < CURDATE());
</code></pre>
<p>That's working but really uggly !</p>
|
[
{
"answer_id": 74488045,
"author": "Akina",
"author_id": 10138734,
"author_profile": "https://Stackoverflow.com/users/10138734",
"pm_score": -1,
"selected": false,
"text": "SELECT username, \n `date`,\n MAX(CASE WHEN `date` = CURRENT_DATE THEN price END) price,\n SUM(CASE WHEN `date` < CURRENT_DATE THEN price END) solde\nFROM Commandes \nWHERE `date` <= CURRENT_DATE\nGROUP BY 1, 2;\n (username, `date`) date"
},
{
"answer_id": 74488094,
"author": "Punit Gajjar",
"author_id": 5127330,
"author_profile": "https://Stackoverflow.com/users/5127330",
"pm_score": 1,
"selected": true,
"text": "SELECT t1.* , \n(select sum(price) from Commandes where username = t1.username and date < CURDATE()) solde \nFROM `Commandes` as t1 \nWHERE date = CURDATE()\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20476202/"
] |
74,487,694
|
<p>let's see I have an array like <code>let filterData= [[1,2,3],[x,y],[z,10]]</code> Have to make it in single line or in single array as an output: <code>this.filterData= [ 1,2,3,x,y,z,10];</code>how can I achieve this in Javascript or typescript language.</p>
<p>anyone have a solution of it..please suggest</p>
<pre><code>`if (this.data && this.data.length > 0) {
this.filteredData.push(this.data[index].value);
this.filteredData.push(this.filteredData);
console.log(this.filteredData)
}`
</code></pre>
|
[
{
"answer_id": 74487753,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 2,
"selected": false,
"text": "Array.flat() let filterData= [[1,2,3],['x','y'],['z',10]]\nfilterData = filterData.flat()\nconsole.log(filterData)"
},
{
"answer_id": 74487843,
"author": "Gowtham",
"author_id": 4082319,
"author_profile": "https://Stackoverflow.com/users/4082319",
"pm_score": 0,
"selected": false,
"text": "let filterData= [[1,2,3],[\"x\",\"y\"],[\"z\",10]];\nlet array=[];\nfilterData.map((x)=>{x.forEach((m)=>{array.push(m)});})\nconsole.log(array);\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15070647/"
] |
74,487,735
|
<p>I'm trying to create a Flexbox grid where the images have the same height and the margin(gutter) adjusts itself depending on the size of the image.</p>
<p>I have tried to set the images to a certain height, but when text is added, the text does not break according to the width of the image.</p>
<p><a href="https://www.o-p.se/work" rel="nofollow noreferrer">https://www.o-p.se/work</a></p>
<p>As seen in my examples below I found a way to set a masonry grid without text. But when I add text the text block creates a white space besides the image.</p>
<p>This is what I want it to look like:
<a href="https://i.stack.imgur.com/2vqFa.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2vqFa.jpg" alt="enter image description here" /></a></p>
<p>This is how it looks without text:
<a href="https://i.stack.imgur.com/uJkMs.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uJkMs.jpg" alt="enter image description here" /></a></p>
<p>And this is my issue:
<a href="https://i.stack.imgur.com/Mpqaa.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Mpqaa.jpg" alt="enter image description here" /></a></p>
<p>This is my set up.</p>
<pre><code><div class=”collection-list”>
<div class=”collection-item”>
<img src=”url” class=”image”>
<div class=”text-block”>Image text</div>
</div>
<div class=”collection-item”>
<img src=”url” class=”image”>
<div class=”text-block”>Image text</div>
</div>
<div class=”collection-item”>
<img src=”url” class=”image”>
<div class=”text-block”>Image text</div>
</div>
<div class=”collection-item”>
<img src=”url” class=”image”>
<div class=”text-block”>Image text</div>
</div>
</div>
.collection-list {
display: flex;
flex-direction: row;
justify-content: space-between;
flex-wrap: wrap;
align-items: flex-start;
}
.collection-item {
display: flex;
height: 10vw;
flex-direction: column;
align-items: flex-start;
}
.image {
height: 80%;
}
</code></pre>
|
[
{
"answer_id": 74487891,
"author": "George Chond",
"author_id": 17730652,
"author_profile": "https://Stackoverflow.com/users/17730652",
"pm_score": 0,
"selected": false,
"text": ".collection-item-28 {\n margin-bottom: 14px; /* Adjust this to your liking */\n}\n.text-block-19{\n position: absolute;\n top: 100%;\n transform: translateY(-100%);\n width: 100%;\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11480879/"
] |
74,487,746
|
<p>I deployed kubernetes cluster in <code>minikube</code> which has one master node and one worker node. When I tried to see the kube-proxy with:</p>
<pre><code>kubectl get pods -n kube-system
</code></pre>
<p>two kube-proxies apear</p>
<pre><code>kube-proxy-6jxgq
kube-proxy-sq58d
</code></pre>
<p>According to the refrence architecture <a href="https://www.stackoverflow.com/">https://kubernetes.io/docs/concepts/overview/components/</a> kube-proxy is the component of worker node. I expect to see one kube-proxy not two. what is the reason?</p>
|
[
{
"answer_id": 74487891,
"author": "George Chond",
"author_id": 17730652,
"author_profile": "https://Stackoverflow.com/users/17730652",
"pm_score": 0,
"selected": false,
"text": ".collection-item-28 {\n margin-bottom: 14px; /* Adjust this to your liking */\n}\n.text-block-19{\n position: absolute;\n top: 100%;\n transform: translateY(-100%);\n width: 100%;\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19664050/"
] |
74,487,748
|
<p>In TypeScript, I have arrays of objects like this</p>
<pre><code>const props1 = [
{ propName: 'id', propValue: 1 },
{ propName: 'name', propValue: 'John' },
{ propName: 'age', propValue: 30 }
];
const props2 = [
{ propName: 'id', propValue: 2 },
{ propName: 'role', propValue: 'admin' }
];
const props3 = [
{ propName: 'job', propValue: 'developer' },
{ propName: 'salary', propValue: 1000 }
];
</code></pre>
<p>I want to create a function <code>createObject</code> that I can pass an array of them to it, and it should return an object that its keys are <code>propName</code> with values <code>propValue</code></p>
<p>This is the desirable results type</p>
<pre><code>const obj1 = createObject(props1); // Returned type should be: { id: number; name: string; age: number }
const obj2 = createObject(props2); // Returned type should be: { id: number; role: string }
const obj3 = createObject(props3); // Returned type should be: { job: string; salary: number }
</code></pre>
<p>This is my try, but doesn't return the correct type</p>
<pre><code>function createObject<T extends { propName: string; propValue: any }[]>(propertiesObject: T) {
const obj: { [key: string]: any } = {};
for (const { propName, propValue } of propertiesObject) {
obj[propName] = propValue;
}
return obj;
}
</code></pre>
|
[
{
"answer_id": 74487891,
"author": "George Chond",
"author_id": 17730652,
"author_profile": "https://Stackoverflow.com/users/17730652",
"pm_score": 0,
"selected": false,
"text": ".collection-item-28 {\n margin-bottom: 14px; /* Adjust this to your liking */\n}\n.text-block-19{\n position: absolute;\n top: 100%;\n transform: translateY(-100%);\n width: 100%;\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1274894/"
] |
74,487,759
|
<p>I am trying to uppercase strings that match a regular expression.</p>
<p>I tried:</p>
<pre><code>SELECT
REGEXP_REPLACE(
'I am testing this string',
'(testing|string)',
UPPER('\\1')
);
</code></pre>
<p>which does not work, my guess is because the upper is applied to '\1' before it is actually turned into the first capturing group.</p>
<p>Second try:</p>
<pre><code>SELECT
REGEXP_REPLACE(
'I am testing this string',
'(testing|string)',
UPPER(REGEXP_EXTRACT('I am testing this string', '(testing|string)'))
);
</code></pre>
<p>But this time it only applies upper to the first match of REGEXP_EXTRACT.</p>
<p>Desired output: <em>I am TESTING this STRING</em></p>
|
[
{
"answer_id": 74488354,
"author": "Samuel",
"author_id": 16529576,
"author_profile": "https://Stackoverflow.com/users/16529576",
"pm_score": 0,
"selected": false,
"text": "replace(replace(\"word for text \",\"word\",\"WORD\"),\"text,\"TEXT) * REGEXP_REPLACE * * X offset X UPPER string_agg``concats all parts of the splitted string. The inside the main Select\n123 as id,\n((SELECT string_agg(if(mod(Offset,2)=1,Upper(x),x),\"\") from\nunnest(split(REGEXP_REPLACE(\n'I am testing this string as best as I can do!',\n '(testing|string)',\n '*\\\\1*'\n),\"*\")) X with offset))\n"
},
{
"answer_id": 74495283,
"author": "Mikhail Berlyant",
"author_id": 5221944,
"author_profile": "https://Stackoverflow.com/users/5221944",
"pm_score": 2,
"selected": true,
"text": "create temp function cap_matches(text string, match string) returns string language js as r\"\"\"\n return text.replace(RegExp(match, 'gi'), word => word.charAt(0).toUpperCase() + word.slice(1));\n\"\"\";\nselect 'I am testing this string' text, \n cap_matches('I am testing this string', 'testing|string') new_text \n create temp function cap_matches(text string, match string) \nreturns string language js as r\"\"\"\n return text.replace(RegExp(match, 'gi'), word => word.toUpperCase());\n\"\"\";\nselect 'I am testing this string' text, \n cap_matches('I am testing this string', 'testing|string') new_text\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8007872/"
] |
74,487,766
|
<p>I want to run an external script (demo_print.py) and print the output in real-time in a text widget.</p>
<p>I got error:</p>
<p>What's my mistake and how to reach my goal ? You can suggest more simple solution if you have.</p>
<pre class="lang-py prettyprint-override"><code>Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/bin/python3/3.7.4/lib/python3.7/threading.py", line 926, in _bootstrap_inner
self.run()
File "/usr/bin/python3/3.7.4/lib/python3.7/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "example_gui.py", line 37, in test
textbox.insert(tk.END, msg + "\n")
File "example_gui.py", line 20, in write
self.widget.insert('end', textbox)
File "/usr/bin/python3/3.7.4/lib/python3.7/tkinter/__init__.py", line 3272, in insert
self.tk.call((self._w, 'insert', index, chars) + args)
_tkinter.TclError: out of stack space (infinite loop?)
</code></pre>
<p>I want to run an external script (demo_print.py) and print the output in real-time in a text widget.</p>
<p><strong>example_gui.py</strong></p>
<pre class="lang-py prettyprint-override"><code>import tkinter as tk
import subprocess
import threading
import sys
from functools import partial
# ### classes ####
class Redirect:
def __init__(self, widget, autoscroll=True):
self.widget = widget
self.autoscroll = autoscroll
def write(self, textbox):
self.widget.insert('end', textbox)
if self.autoscroll:
self.widget.see('end') # autoscroll
def flush(self):
pass
def run(textbox=None):
threading.Thread(target=test, args=[textbox]).start()
def test(textbox=None):
p = subprocess.Popen("demo_print.py", stdout=subprocess.PIPE, bufsize=1, text=True)
while p.poll() is None:
msg = p.stdout.readline().strip() # read a line from the process output
if msg:
textbox.insert(tk.END, msg + "\n")
if __name__ == "__main__":
fenster = tk.Tk()
fenster.title("My Program")
textbox = tk.Text(fenster)
textbox.grid()
scrollbar = tk.Scrollbar(fenster, orient=tk.VERTICAL)
scrollbar.grid()
textbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=textbox.yview)
start_button = tk.Button(fenster, text="Start", command=partial(run, textbox))
start_button.grid()
old_stdout = sys.stdout
sys.stdout = Redirect(textbox)
fenster.mainloop()
sys.stdout = old_stdout
</code></pre>
<p><strong>demo_print.py</strong></p>
<pre class="lang-py prettyprint-override"><code>import time
for i in range(10):
print(f"print {i}")
time.sleep(1)
</code></pre>
|
[
{
"answer_id": 74488354,
"author": "Samuel",
"author_id": 16529576,
"author_profile": "https://Stackoverflow.com/users/16529576",
"pm_score": 0,
"selected": false,
"text": "replace(replace(\"word for text \",\"word\",\"WORD\"),\"text,\"TEXT) * REGEXP_REPLACE * * X offset X UPPER string_agg``concats all parts of the splitted string. The inside the main Select\n123 as id,\n((SELECT string_agg(if(mod(Offset,2)=1,Upper(x),x),\"\") from\nunnest(split(REGEXP_REPLACE(\n'I am testing this string as best as I can do!',\n '(testing|string)',\n '*\\\\1*'\n),\"*\")) X with offset))\n"
},
{
"answer_id": 74495283,
"author": "Mikhail Berlyant",
"author_id": 5221944,
"author_profile": "https://Stackoverflow.com/users/5221944",
"pm_score": 2,
"selected": true,
"text": "create temp function cap_matches(text string, match string) returns string language js as r\"\"\"\n return text.replace(RegExp(match, 'gi'), word => word.charAt(0).toUpperCase() + word.slice(1));\n\"\"\";\nselect 'I am testing this string' text, \n cap_matches('I am testing this string', 'testing|string') new_text \n create temp function cap_matches(text string, match string) \nreturns string language js as r\"\"\"\n return text.replace(RegExp(match, 'gi'), word => word.toUpperCase());\n\"\"\";\nselect 'I am testing this string' text, \n cap_matches('I am testing this string', 'testing|string') new_text\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20538203/"
] |
74,487,779
|
<p>script.sh</p>
<blockquote>
</blockquote>
<pre><code>#!/bin/sh
dbt run --select $model_tag --profiles-dir .
</code></pre>
<p>Want to run this shell script that takes the Variable model_tag from my .go file</p>
<p>invoke.go</p>
<blockquote>
</blockquote>
<pre><code>package main
import (
"fmt"
"log"
"net/http"
"os"
"os/exec"
)
func handler(w http.ResponseWriter, r *http.Request) {
log.Print("helloworld: received a request")
mt := r.Header.Get("Model-Tag")
cmd := exec.CommandContext(r.Context(), "/bin/sh","script.sh")
cmd.Stderr = os.Stderr
out, err := cmd.Output()
if err != nil {
w.WriteHeader(500)
}
w.Write(out)
}
func main() {
log.Print("helloworld: starting server...")
http.HandleFunc("/", handler)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
log.Printf("helloworld: listening on %s", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}
</code></pre>
<p>Here, mt is the header being received from a request, that i need to pass to the shell script before execution?
How do i set model_tag = mt before executing the shell script using the go file?</p>
<p>Tried setting model_tag = mt directly, throws a syntax error</p>
|
[
{
"answer_id": 74487842,
"author": "Matteo",
"author_id": 2270041,
"author_profile": "https://Stackoverflow.com/users/2270041",
"pm_score": 0,
"selected": false,
"text": " cmd := exec.CommandContext(r.Context(), \"/bin/sh\",fmt.Sprintf(\"model_tag=%s script.sh\",mt))\n\n"
},
{
"answer_id": 74488527,
"author": "user1934428",
"author_id": 1934428,
"author_profile": "https://Stackoverflow.com/users/1934428",
"pm_score": 2,
"selected": false,
"text": "script.sh os.Setenv(\"model_tag\", mt)\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19329929/"
] |
74,487,852
|
<p>A function takes one string argument and outputs a string.</p>
<p>It should remove all vowels from the supplied string if the string contains mostly vowels, otherwise return the supplied string without modification.</p>
<p>Specification:</p>
<ul>
<li>A string is considered to contain mostly vowels if it has more vowels (a, e, i, o, u) than consonants (b, c, d, f, g, h, j, k, l, m, n, p, q, r, s, t, v, w, x, y, z), ignoring all non-alphabetic characters from the count.</li>
<li>If a string contains mostly vowels, the result should have excess whitespace removed - there should be no leading or trailing whitespace, nor any double spaces within the returned string.</li>
<li>Strings may contain more than one word. Spaces between words must be preserved, except for when the entire word has been removed.</li>
</ul>
<p>For example, the string "hello" would remain hello.</p>
<p>However, the string "adieu" would become d.</p>
<p>This is what I have tried to no success so far:</p>
<pre><code> function removeVowel(input) {
//function that takes string as input
//function returns an object containing vowel count without case in account.
function vowelCount(input) {
//to get vowel count using string.match
let arrVowels =input.match(/[aeiouAEIOU]+?/g);
//acc=accumulator, curr=current value
let countVowCons= arrVowels.reduce(function (acc, curr) {
if (typeof acc[curr.toLowerCase()] == 'undefined') {
acc[curr.toLowerCase()] = 1;
}
else {
acc[curr.toLowerCase()] += 1;
}
return acc;
// the blank object below is default value of the acc (accumulator)
}, {});
countVowCons.NonVowels= input.match(/[^aeiouAEIOU]+?/g).length;
if(arrVowels > countVowCons.NoVowels) {
//remove vowels from string & return new string
const noVowels = input.replace(/[aeiou]/gi, '')
} else {
// return supplied string withoout modification
return input
}
}
}
</code></pre>
<p>I know I´m doing a lot of things wrong, could anyone point me in the right direction?</p>
<pre><code>Expected: "hello"
Received: undefined
</code></pre>
<pre><code>Expected: "hrd d"
Received: undefined
</code></pre>
|
[
{
"answer_id": 74488067,
"author": "Smytt",
"author_id": 8263781,
"author_profile": "https://Stackoverflow.com/users/8263781",
"pm_score": 3,
"selected": true,
"text": "const maybeDisemvowel = (originalString) => {\n const onlyConsonants = originalString.replace(/[^bcdfghjklmnpqrstvwxys]/gi, '')\n const onlyVowels = originalString.replace(/[^aeoiu]/gi, '')\n const withoutVowels = originalString.replace(/[aeoiu]/gi, '')\n const shouldReturnOriginal = onlyConsonants.length > onlyVowels.length\n return shouldReturnOriginal\n ? originalString\n : withoutVowels.trim().replace(/\\s+/g, ' ')\n}\n\nconsole.log(maybeDisemvowel(' abb b')) // no change\nconsole.log(maybeDisemvowel('aaaaaa bbb aaa bbb b')) // change\nconsole.log(maybeDisemvowel('aa ab bba ')) // change"
},
{
"answer_id": 74488080,
"author": "R4ncid",
"author_id": 14326899,
"author_profile": "https://Stackoverflow.com/users/14326899",
"pm_score": 1,
"selected": false,
"text": "const transform = string => {\n const letters = string.replace(/\\W/gi, '')\n const notVowels = letters.replace(/[aeiou]/gi, '')\n\n if(letters.length < notVowels.length * 2){\n return string\n }\n\n return string.replace(/[aeiou]/gi, '').split(' ').filter(word => word).join(' ').trim()\n} \n\nconsole.log(transform('hello'))\n\n\nconsole.log(transform('Adieu'))\n\nconsole.log(transform('Adieu hello aaaaaaaaaaaa b'))\n\nconsole.log(transform('I heard a ad'))"
},
{
"answer_id": 74488512,
"author": "Toffy_",
"author_id": 9553685,
"author_profile": "https://Stackoverflow.com/users/9553685",
"pm_score": 0,
"selected": false,
"text": "//pass input Pneumonia\nfunction vowelCount(input) {\n //to get vowel count using string.match\n let arrVowels = input.match(/[\\saeiouAEIOU]+?/g);\n //arrVowels = ['e', 'u', 'o', 'i', 'a']\n\n // now simply compare length of input minus all vowels\n // with vowels you found in word\n // inp 9 - arrVow 5 < 5\n // 4 < 5 => true\n\n //you tried compare with variable that was not defined before\n //that value was in if statement which is out of reach\n if (input.length - arrVowels.length < arrVowels.length) {\n //remove vowels from string & return new string\n\n //you forget return this value\n return input.replace(/[\\saeiouAEIOU]/gi, '');\n } else {\n // return supplied string withoout modification\n return input;\n }\n}"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,487,881
|
<p>I am using a batch file to rename all files in a folder into a numbered list. The code I use is as follow:</p>
<pre><code>set /a Index=1
setlocal enabledelayedexpansion
for /f "tokens=*" %%f in ('dir /b') do (
echo %%f
echo !Index!
rename "%%f" "!Index!.*"
set /a Index+=1
pause
)
</code></pre>
<p>The result of the batch file is</p>
<pre><code>G:\Directory A> (
echo
03.jpg
echo 1
rename "
03.jpg" "1.*"
set /a Index+=1
pause
)
03.jpg
1
The filename, directory name, or volume label syntax is incorrect.
Press any key to continue . . .
G:\Directory A> (
echo 04.jpg
echo 1
rename "04.jpg" "1.*"
set /a Index+=1
pause
)
04.jpg
1
</code></pre>
<p>The first result ALWAYS contains a line break at the beginning of the file name, which causes the RENAME command to fail. Can anyone tell me what is wrong with my code?</p>
<hr />
<h3>UPDATE</h3>
<p>There is the folloging auto-run code set up in the Windows registry:</p>
<pre><code>[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"Autorun"="@chcp 65001>nul & prompt $d$s$s$t$_$p$g & cls"
</code></pre>
|
[
{
"answer_id": 74488656,
"author": "faragona",
"author_id": 5694941,
"author_profile": "https://Stackoverflow.com/users/5694941",
"pm_score": 3,
"selected": true,
"text": "[HKEY_CURRENT_USER\\Software\\Microsoft\\Command Processor]\n\"Autorun\"=\"@chcp 65001>nul & prompt $d$s$s$t$_$p$g & cls\"\n"
},
{
"answer_id": 74567641,
"author": "aschipfl",
"author_id": 5047996,
"author_profile": "https://Stackoverflow.com/users/5047996",
"pm_score": 1,
"selected": false,
"text": "cls 0x0C cls > con cls for /F for /F %F in ('cls') do @echo/%F for /F cmd.exe cmd /C for /F /D cls for /F %F in ('rem') do @echo/%F rem echo/& for /F rem // Precede the desired command with `echo/` and skip the first line:\nfor /F \"skip=1 delims=\" %%I in ('echo/^& dir /B') do echo \"%%I\"\n eol for /F echo/& rem // Retrieve the form-feed character and ignore lines beginning with a form-feed:\nfor /F delims^=^ eol^= %%F in ('echo/^& cls') do set \"_FF=%%F\"\n\nrem // Precede the desired command with `echo/` and use form-feed as `eol` character:\nfor /F \"delims= eol=%_FF%\" %%I in ('echo/^& dir /B') do echo \"%%I\"\n rem /* Determine the number of lines that the `AutoRun` code regurgitates, including empty ones;\nrem the command line actually executed by `for /F` implicitly using `cmd /C` is as follows:\nrem `chcp 437 > nul & echo/& cmd /C echo/| find /C /V \"\"`\nrem this first returns a line-break, to have potential `AutoRun` text separated from the rest;\nrem then another `AutoRun` text again with a terminal line-break is generated, but this time\nrem piped into `find /C /V \"\"` in order to count the number of lines;\nrem `chcp 437 > nul` is necessary to set the code page for the implicit `cmd.exe` instance,\nrem because `find` (just like `more`) may have issues with some particulay Unicode code pages\nrem (like 65001, which may be set by the `AutoRun` code): */\nfor /F %%C in ('chcp 437 ^> nul ^& echo/^& cmd /C echo/^| find /C /V \"\"') do set /A \"SKIP=%%C\" 2> nul\nif %SKIP% gtr 0 (set \"SKIP=skip=%SKIP%\") else set \"SKIP=\"\n\nrem // Precede the desired command with `echo/` and skip as many lines as necessary:\nfor /F \"%SKIP% delims=\" %%I in ('echo/^& dir /B') do echo \"%%I\"\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5694941/"
] |
74,487,889
|
<p>Say I have a web application with <code>UserController</code>. Client sends a HTTP POST request that is about to be handled by the controller. That however first must parse the provided json to <code>UserDTO</code>. For this reason there exist a <code>UserDTOConverter</code> with a method <code>toDTO(json): User</code>.</p>
<p>Given I value functional programming practices for its benefits of referential transparency and pure function the question is. What is the best approach to deal with a possibly inparsable json? First option would be to throw an exception and have it handled in global error handler. Invalid json means that something went terrible wrong (eg hacker) and this error is unrecoverable, hence the exception is on point (even assuming FP). The second option would be to return <code>Maybe<User></code> instead of <code>User</code>. Then in the controller we can based on the return type return HTTP success response or failure response. Ultimately both approaches results in the same failure/success response, which one is preferable though?</p>
<p>Another example. Say I have a web application that needs to retrieve some data from remote repository <code>UserRepository</code>. From a <code>UserController</code> the repository is called <code>getUser(userId): User</code>. Again, what is the best way to handle the error of possible non existent user under provided id? Instead of returning <code>User</code> I can again return <code>Maybe<User></code>. Then in controller this result can be handled by eg returning "204 No Content". Or I could throw an exception. The code stays referentially transparent as again I am letting the exception to bubble all the way up to global error handler (no try catch blocks).</p>
<p>Whereas in the first example I would lean more towards throwing an exception in the latter one I would prefer returning a Maybe. Exceptions result in cleaner code as the codebase is not cluttered with ubiquitous <code>Either</code>s, <code>Maybe</code>s, empty collections, etc. However, returning these kinds of data structure ensure explicitness of the calls, and imo results in better discoverability of the error.</p>
<p>Is there a place for exceptions in functional programming? What is the biggest pitfall of using exceptions over returning <code>Maybe</code>s or <code>Either</code>s? Does it make sense to be throwing exceptions in FP based app? If so is there a rule of thumb for that?</p>
|
[
{
"answer_id": 74488656,
"author": "faragona",
"author_id": 5694941,
"author_profile": "https://Stackoverflow.com/users/5694941",
"pm_score": 3,
"selected": true,
"text": "[HKEY_CURRENT_USER\\Software\\Microsoft\\Command Processor]\n\"Autorun\"=\"@chcp 65001>nul & prompt $d$s$s$t$_$p$g & cls\"\n"
},
{
"answer_id": 74567641,
"author": "aschipfl",
"author_id": 5047996,
"author_profile": "https://Stackoverflow.com/users/5047996",
"pm_score": 1,
"selected": false,
"text": "cls 0x0C cls > con cls for /F for /F %F in ('cls') do @echo/%F for /F cmd.exe cmd /C for /F /D cls for /F %F in ('rem') do @echo/%F rem echo/& for /F rem // Precede the desired command with `echo/` and skip the first line:\nfor /F \"skip=1 delims=\" %%I in ('echo/^& dir /B') do echo \"%%I\"\n eol for /F echo/& rem // Retrieve the form-feed character and ignore lines beginning with a form-feed:\nfor /F delims^=^ eol^= %%F in ('echo/^& cls') do set \"_FF=%%F\"\n\nrem // Precede the desired command with `echo/` and use form-feed as `eol` character:\nfor /F \"delims= eol=%_FF%\" %%I in ('echo/^& dir /B') do echo \"%%I\"\n rem /* Determine the number of lines that the `AutoRun` code regurgitates, including empty ones;\nrem the command line actually executed by `for /F` implicitly using `cmd /C` is as follows:\nrem `chcp 437 > nul & echo/& cmd /C echo/| find /C /V \"\"`\nrem this first returns a line-break, to have potential `AutoRun` text separated from the rest;\nrem then another `AutoRun` text again with a terminal line-break is generated, but this time\nrem piped into `find /C /V \"\"` in order to count the number of lines;\nrem `chcp 437 > nul` is necessary to set the code page for the implicit `cmd.exe` instance,\nrem because `find` (just like `more`) may have issues with some particulay Unicode code pages\nrem (like 65001, which may be set by the `AutoRun` code): */\nfor /F %%C in ('chcp 437 ^> nul ^& echo/^& cmd /C echo/^| find /C /V \"\"') do set /A \"SKIP=%%C\" 2> nul\nif %SKIP% gtr 0 (set \"SKIP=skip=%SKIP%\") else set \"SKIP=\"\n\nrem // Precede the desired command with `echo/` and skip as many lines as necessary:\nfor /F \"%SKIP% delims=\" %%I in ('echo/^& dir /B') do echo \"%%I\"\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20002375/"
] |
74,487,910
|
<p>I am new to python, apologies if I do not explain well or provide partial solutions yet...</p>
<p>I have a dataframe as below: a key, some dates (distributed in rows), and many other columns (same key, same value)</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Key</th>
<th>Date 1</th>
<th>Date 2</th>
<th>Date 3</th>
<th>Column X</th>
<th>Column Y</th>
</tr>
</thead>
<tbody>
<tr>
<td>Key 1</td>
<td>2022-01-01</td>
<td></td>
<td></td>
<td>X11111111</td>
<td>Y11111111</td>
</tr>
<tr>
<td>Key 1</td>
<td></td>
<td>2022-01-02</td>
<td></td>
<td>X11111111</td>
<td>Y11111111</td>
</tr>
<tr>
<td>Key 1</td>
<td></td>
<td></td>
<td>2022-01-03</td>
<td>X11111111</td>
<td>Y11111111</td>
</tr>
<tr>
<td>Key 2</td>
<td>2022-12-01</td>
<td></td>
<td></td>
<td>X22222222</td>
<td>Y22222222</td>
</tr>
<tr>
<td>Key 2</td>
<td></td>
<td>2022-12-02</td>
<td></td>
<td>X22222222</td>
<td>Y22222222</td>
</tr>
<tr>
<td>Key 2</td>
<td></td>
<td></td>
<td>2022-12-03</td>
<td>X22222222</td>
<td>Y22222222</td>
</tr>
</tbody>
</table>
</div>
<p>And I want to aggregate them like below, where the dates are aggregate, other columns keep the same</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Key</th>
<th>Date 1</th>
<th>Date 2</th>
<th>Date 3</th>
<th>Column X</th>
<th>Column Y</th>
</tr>
</thead>
<tbody>
<tr>
<td>Key 1</td>
<td>2022-01-01</td>
<td>2022-01-02</td>
<td>2022-01-03</td>
<td>X11111111</td>
<td>Y11111111</td>
</tr>
<tr>
<td>Key 2</td>
<td>2022-12-01</td>
<td>2022-12-02</td>
<td>2022-12-03</td>
<td>X22222222</td>
<td>Y22222222</td>
</tr>
</tbody>
</table>
</div>
<p>What would be the most efficient way of doing it? Thank you.</p>
<p>I have tried normal pivot and aggregation but did not work as I want ...</p>
|
[
{
"answer_id": 74488656,
"author": "faragona",
"author_id": 5694941,
"author_profile": "https://Stackoverflow.com/users/5694941",
"pm_score": 3,
"selected": true,
"text": "[HKEY_CURRENT_USER\\Software\\Microsoft\\Command Processor]\n\"Autorun\"=\"@chcp 65001>nul & prompt $d$s$s$t$_$p$g & cls\"\n"
},
{
"answer_id": 74567641,
"author": "aschipfl",
"author_id": 5047996,
"author_profile": "https://Stackoverflow.com/users/5047996",
"pm_score": 1,
"selected": false,
"text": "cls 0x0C cls > con cls for /F for /F %F in ('cls') do @echo/%F for /F cmd.exe cmd /C for /F /D cls for /F %F in ('rem') do @echo/%F rem echo/& for /F rem // Precede the desired command with `echo/` and skip the first line:\nfor /F \"skip=1 delims=\" %%I in ('echo/^& dir /B') do echo \"%%I\"\n eol for /F echo/& rem // Retrieve the form-feed character and ignore lines beginning with a form-feed:\nfor /F delims^=^ eol^= %%F in ('echo/^& cls') do set \"_FF=%%F\"\n\nrem // Precede the desired command with `echo/` and use form-feed as `eol` character:\nfor /F \"delims= eol=%_FF%\" %%I in ('echo/^& dir /B') do echo \"%%I\"\n rem /* Determine the number of lines that the `AutoRun` code regurgitates, including empty ones;\nrem the command line actually executed by `for /F` implicitly using `cmd /C` is as follows:\nrem `chcp 437 > nul & echo/& cmd /C echo/| find /C /V \"\"`\nrem this first returns a line-break, to have potential `AutoRun` text separated from the rest;\nrem then another `AutoRun` text again with a terminal line-break is generated, but this time\nrem piped into `find /C /V \"\"` in order to count the number of lines;\nrem `chcp 437 > nul` is necessary to set the code page for the implicit `cmd.exe` instance,\nrem because `find` (just like `more`) may have issues with some particulay Unicode code pages\nrem (like 65001, which may be set by the `AutoRun` code): */\nfor /F %%C in ('chcp 437 ^> nul ^& echo/^& cmd /C echo/^| find /C /V \"\"') do set /A \"SKIP=%%C\" 2> nul\nif %SKIP% gtr 0 (set \"SKIP=skip=%SKIP%\") else set \"SKIP=\"\n\nrem // Precede the desired command with `echo/` and skip as many lines as necessary:\nfor /F \"%SKIP% delims=\" %%I in ('echo/^& dir /B') do echo \"%%I\"\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20538245/"
] |
74,487,943
|
<p>I have a project that I developed with EF Core and react. What I want is to be able to give the second person an "updated before" error if two different users open the screen at the same time and update the same data at different times. But when I apply it as in the pictures, it does not catch any errors and updates the db. A unique new rowversion is also assigned to the db.</p>
<p><a href="https://i.stack.imgur.com/OPEtW.png" rel="nofollow noreferrer">implementation of what I want in the console app</a></p>
<p><a href="https://i.stack.imgur.com/XHMyE.png" rel="nofollow noreferrer">dbcontext</a></p>
<p><a href="https://i.stack.imgur.com/Ug88g.png" rel="nofollow noreferrer">appservice screenshot</a></p>
<p><a href="https://i.stack.imgur.com/NbTsf.png" rel="nofollow noreferrer">entity screenshot</a></p>
<p><a href="https://i.stack.imgur.com/QUEXk.png" rel="nofollow noreferrer">rowversion column</a></p>
<p>The points I updated in my project while implementing.</p>
<p>on modelcreating:</p>
<pre><code>modelBuilder.Entity<User>().Property(e => e.RowVersion)
.IsRequired()
.IsRowVersion()
.IsConcurrencyToken();
</code></pre>
<p>entity:</p>
<pre><code> public class User : AbpUser<User>
{
[Timestamp]
public byte[] RowVersion { get; set; }
}
</code></pre>
<p>the code i expect to give an error:</p>
<pre><code> public override async Task<UserDto> UpdateAsync(UserDto input) {
CheckUpdatePermission();
//input.RowVersion = new byte[] { 0, 0, 0, 0, 0, 0, 7, 215 };
var user = await _userManager.GetUserByIdAsync(input.Id);
//MapToEntity(input, user);
//user.UserName = "hh";
//user.RowVersion = new byte[] { 1, 2, 0, 0, 0, 0, 9, 85};
user.RowVersion[1] =55;
try
{
CheckErrors(await _userManager.UpdateAsync(user));
}
catch (Exception e)
{
throw new UserFriendlyException(e.Message);
}
if (input.RoleNames != null)
{
CheckErrors(await _userManager.SetRolesAsync(user, input.RoleNames));
}
return await GetAsync(input);
}
</code></pre>
|
[
{
"answer_id": 74488656,
"author": "faragona",
"author_id": 5694941,
"author_profile": "https://Stackoverflow.com/users/5694941",
"pm_score": 3,
"selected": true,
"text": "[HKEY_CURRENT_USER\\Software\\Microsoft\\Command Processor]\n\"Autorun\"=\"@chcp 65001>nul & prompt $d$s$s$t$_$p$g & cls\"\n"
},
{
"answer_id": 74567641,
"author": "aschipfl",
"author_id": 5047996,
"author_profile": "https://Stackoverflow.com/users/5047996",
"pm_score": 1,
"selected": false,
"text": "cls 0x0C cls > con cls for /F for /F %F in ('cls') do @echo/%F for /F cmd.exe cmd /C for /F /D cls for /F %F in ('rem') do @echo/%F rem echo/& for /F rem // Precede the desired command with `echo/` and skip the first line:\nfor /F \"skip=1 delims=\" %%I in ('echo/^& dir /B') do echo \"%%I\"\n eol for /F echo/& rem // Retrieve the form-feed character and ignore lines beginning with a form-feed:\nfor /F delims^=^ eol^= %%F in ('echo/^& cls') do set \"_FF=%%F\"\n\nrem // Precede the desired command with `echo/` and use form-feed as `eol` character:\nfor /F \"delims= eol=%_FF%\" %%I in ('echo/^& dir /B') do echo \"%%I\"\n rem /* Determine the number of lines that the `AutoRun` code regurgitates, including empty ones;\nrem the command line actually executed by `for /F` implicitly using `cmd /C` is as follows:\nrem `chcp 437 > nul & echo/& cmd /C echo/| find /C /V \"\"`\nrem this first returns a line-break, to have potential `AutoRun` text separated from the rest;\nrem then another `AutoRun` text again with a terminal line-break is generated, but this time\nrem piped into `find /C /V \"\"` in order to count the number of lines;\nrem `chcp 437 > nul` is necessary to set the code page for the implicit `cmd.exe` instance,\nrem because `find` (just like `more`) may have issues with some particulay Unicode code pages\nrem (like 65001, which may be set by the `AutoRun` code): */\nfor /F %%C in ('chcp 437 ^> nul ^& echo/^& cmd /C echo/^| find /C /V \"\"') do set /A \"SKIP=%%C\" 2> nul\nif %SKIP% gtr 0 (set \"SKIP=skip=%SKIP%\") else set \"SKIP=\"\n\nrem // Precede the desired command with `echo/` and skip as many lines as necessary:\nfor /F \"%SKIP% delims=\" %%I in ('echo/^& dir /B') do echo \"%%I\"\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20538410/"
] |
74,487,970
|
<p>I am very new to C++ programming. I want to insert elements of type enum into a <code>vector<uint8_t></code> ? ie append all elements of <code>std::vector <ValType> call</code> to <code>std::vector<uint8_t> bravo</code> .Is there any way to do so?</p>
<pre><code>#include <stdio.h>
#include <vector>
#include <cstdint>
enum class ValType : uint8_t
{
Working = 1,
Failed = 0,
Freezed = 0
};
int main()
{
std::vector<uint8_t> bravo = {23, 23, 23, 22, 5};
std::vector<ValType> call;
bravo.insert(bravo.end(), call.begin(), call.end());
return 0;
}
</code></pre>
<p>Live <a href="https://onlinegdb.com/rhBWRuaysD" rel="nofollow noreferrer">Here</a></p>
<p>I am getting an error while compiling :</p>
<pre><code> In file included from c:\program files (x86)\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\include\c++\11.2.0\vector:66,
from custom.cpp:2:
c:\program files (x86)\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\include\c++\11.2.0\bits\stl_uninitialized.h: In instantiation of '_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<ValType*, std::vector<ValType> >; _ForwardIterator = unsigned char*]':
c:\program files (x86)\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\include\c++\11.2.0\bits\stl_uninitialized.h:333:37: required from '_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<ValType*, std::vector<ValType> >; _ForwardIterator = unsigned char*; _Tp = unsigned char]'
c:\program files (x86)\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\include\c++\11.2.0\bits\vector.tcc:751:34: required from 'void std::vector<_Tp, _Alloc>::_M_range_insert(std::vector<_Tp, _Alloc>::iterator, _ForwardIterator, _ForwardIterator, std::forward_iterator_tag) [with _ForwardIterator = __gnu_cxx::__normal_iterator<ValType*, std::vector<ValType> >; _Tp = unsigned char; _Alloc = std::allocator<unsigned char>; std::vector<_Tp, _Alloc>::iterator = std::vector<unsigned char>::iterator]'
c:\program files (x86)\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\include\c++\11.2.0\bits\stl_vector.h:1665:19: required from 'void std::vector<_Tp, _Alloc>::_M_insert_dispatch(std::vector<_Tp, _Alloc>::iterator, _InputIterator, _InputIterator, std::__false_type) [with _InputIterator = __gnu_cxx::__normal_iterator<ValType*, std::vector<ValType> >; _Tp = unsigned char; _Alloc = std::allocator<unsigned char>; std::vector<_Tp, _Alloc>::iterator = std::vector<unsigned char>::iterator]'
c:\program files (x86)\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\include\c++\11.2.0\bits\stl_vector.h:1383:22: required from 'std::vector<_Tp, _Alloc>::iterator std::vector<_Tp, _Alloc>::insert(std::vector<_Tp, _Alloc>::const_iterator, _InputIterator, _InputIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<ValType*, std::vector<ValType> >; <template-parameter-2-2> = void; _Tp = unsigned char; _Alloc = std::allocator<unsigned char>; std::vector<_Tp, _Alloc>::iterator = std::vector<unsigned char>::iterator; std::vector<_Tp, _Alloc>::const_iterator = std::vector<unsigned char>::const_iterator]'
custom.cpp:18:17: required from here
c:\program files (x86)\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\include\c++\11.2.0\bits\stl_uninitialized.h:138:72: error: static assertion failed: result type must be constructible from value type of input range
138 | static_assert(is_constructible<_ValueType2, decltype(*__first)>::value,
| ^~~~~
c:\program files (x86)\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\include\c++\11.2.0\bits\stl_uninitialized.h:138:72: note: 'std::integral_constant<bool, false>::value' evaluates to false
In file included from c:\program files (x86)\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\include\c++\11.2.0\vector:60,
from custom.cpp:2:
c:\program files (x86)\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\include\c++\11.2.0\bits\stl_algobase.h: In instantiation of 'static _OI std::__copy_move<false, false, std::random_access_iterator_tag>::__copy_m(_II, _II, _OI) [with _II = ValType*; _OI = unsigned char*]':
c:\program files (x86)\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\include\c++\11.2.0\bits\stl_algobase.h:495:30: required from '_OI std::__copy_move_a2(_II, _II, _OI) [with bool _IsMove = false; _II = ValType*; _OI = unsigned char*]'
c:\program files (x86)\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\include\c++\11.2.0\bits\stl_algobase.h:522:42: required from '_OI std::__copy_move_a1(_II, _II, _OI) [with bool _IsMove = false; _II = ValType*; _OI = unsigned char*]'
c:\program files (x86)\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\include\c++\11.2.0\bits\stl_algobase.h:530:31: required from '_OI std::__copy_move_a(_II, _II, _OI) [with bool _IsMove = false; _II = __gnu_cxx::__normal_iterator<ValType*, std::vector<ValType> >; _OI = __gnu_cxx::__normal_iterator<unsigned char*, std::vector<unsigned char> >]'
c:\program files (x86)\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\include\c++\11.2.0\bits\stl_algobase.h:620:7: required from '_OI std::copy(_II, _II, _OI) [with _II = __gnu_cxx::__normal_iterator<ValType*, std::vector<ValType> >; _OI = __gnu_cxx::__normal_iterator<unsigned char*, std::vector<unsigned char> >]'
c:\program files (x86)\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\include\c++\11.2.0\bits\vector.tcc:744:16: required from 'void std::vector<_Tp, _Alloc>::_M_range_insert(std::vector<_Tp, _Alloc>::iterator, _ForwardIterator, _ForwardIterator, std::forward_iterator_tag) [with _ForwardIterator = __gnu_cxx::__normal_iterator<ValType*, std::vector<ValType> >; _Tp = unsigned char; _Alloc = std::allocator<unsigned char>; std::vector<_Tp, _Alloc>::iterator = std::vector<unsigned char>::iterator]'
c:\program files (x86)\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\include\c++\11.2.0\bits\stl_vector.h:1665:19: required from 'void std::vector<_Tp, _Alloc>::_M_insert_dispatch(std::vector<_Tp, _Alloc>::iterator, _InputIterator, _InputIterator, std::__false_type) [with _InputIterator = __gnu_cxx::__normal_iterator<ValType*, std::vector<ValType> >; _Tp = unsigned char; _Alloc = std::allocator<unsigned char>; std::vector<_Tp, _Alloc>::iterator = std::vector<unsigned char>::iterator]'
c:\program files (x86)\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\include\c++\11.2.0\bits\stl_vector.h:1383:22: required from 'std::vector<_Tp, _Alloc>::iterator std::vector<_Tp, _Alloc>::insert(std::vector<_Tp, _Alloc>::const_iterator, _InputIterator, _InputIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<ValType*, std::vector<ValType> >; <template-parameter-2-2> = void; _Tp = unsigned char; _Alloc = std::allocator<unsigned char>; std::vector<_Tp, _Alloc>::iterator = std::vector<unsigned char>::iterator; std::vector<_Tp, _Alloc>::const_iterator = std::vector<unsigned char>::const_iterator]'
custom.cpp:18:17: required from here
c:\program files (x86)\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\include\c++\11.2.0\bits\stl_algobase.h:385:25: error: cannot convert 'ValType' to 'unsigned char' in assignment
385 | *__result = *__first;
| ~~~~~~~~~~^~~~~~~~~~
</code></pre>
<p>Can someone please show me the correct way of doing this?</p>
|
[
{
"answer_id": 74488123,
"author": "Some programmer dude",
"author_id": 440558,
"author_profile": "https://Stackoverflow.com/users/440558",
"pm_score": 1,
"selected": false,
"text": "static_cast ValType ValType uint8_t static_cast std::transform"
},
{
"answer_id": 74488224,
"author": "Özgür Murat Sağdıçoğlu",
"author_id": 5106317,
"author_profile": "https://Stackoverflow.com/users/5106317",
"pm_score": 4,
"selected": true,
"text": "std::transform std::vector<uint8_t> bravo = {23, 23, 23, 22, 5};\nstd::vector<ValType> call;\n\nstd::transform(bravo.cbegin(), bravo.cend(), std::back_inserter(call),\n [](uint8_t a) { return static_cast<ValType>(a); });\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20483318/"
] |
74,487,980
|
<p>in my code, i don't understand why zero doesn't print i did all possible solutions that I know but it doesn't print zero.</p>
<pre><code>#include <iostream>
using namespace std;
int main(){
int digits;
int numberOne = 0;
int integer;
cout<<"Enter the number: ";
cin>>digits;
while (digits != 0) {
numberOne = (numberOne * 10) + (digits % 10);
digits /= 10;
}
for (integer = numberOne; integer > 0; integer = integer / 10){
switch (integer % 10) {
case 0:
cout<<"Zero\n";
break;
case 1:
cout<<"One\n";
break;
case 2:
cout<<"Two\n";
break;
case 3:
cout<<"Three\n";
break;
case 4:
cout<<"Four\n";
break;
case 5:
cout<<"Five\n";
break;
case 6:
cout<<"Six\n";
break;
case 7:
cout<<"Seven\n";
break;
case 8:
cout<<"Eight\n";
break;
case 9:
cout<<"Nine\n";
break;
}
}
return 0;
}
</code></pre>
<p>zero doesn't print how do I fix it?
Expected output is 900 (nine zero zero) but zero doesn't print in my case. help thanks.</p>
|
[
{
"answer_id": 74488123,
"author": "Some programmer dude",
"author_id": 440558,
"author_profile": "https://Stackoverflow.com/users/440558",
"pm_score": 1,
"selected": false,
"text": "static_cast ValType ValType uint8_t static_cast std::transform"
},
{
"answer_id": 74488224,
"author": "Özgür Murat Sağdıçoğlu",
"author_id": 5106317,
"author_profile": "https://Stackoverflow.com/users/5106317",
"pm_score": 4,
"selected": true,
"text": "std::transform std::vector<uint8_t> bravo = {23, 23, 23, 22, 5};\nstd::vector<ValType> call;\n\nstd::transform(bravo.cbegin(), bravo.cend(), std::back_inserter(call),\n [](uint8_t a) { return static_cast<ValType>(a); });\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74487980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20538431/"
] |
74,488,013
|
<p>I'm Using Junit in Spring Boot, along with <a href="https://www.testcontainers.org/" rel="nofollow noreferrer">TestContainers</a> (Docker, MySQL 8.0.29) to develop integration tests.</p>
<p>When I execute my tests individually, they all succeed. However when I run them all at once (i.e. in CI/CD), they fail. This is because the tests are not executed in order, and an item might already be deleted before the test to find the item is executed.</p>
<p>To fix this I want to give the entities a unique ID. However, the ID is already automaticly set in my Hibernate entity:</p>
<pre><code>@Entity
public class Assignment {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
</code></pre>
<p>I've tried to delete all items before each test is executed, however this does not work:</p>
<pre><code> @Autowired
private JdbcTemplate jdbcTemplate;
@BeforeEach
void tearDown() {
JdbcTestUtils.deleteFromTables(jdbcTemplate, "assignment");
}
</code></pre>
<p>Example integration test:</p>
<pre><code> @Test
void When_getById_Verify_Fields() {
AssignmentDTO assignmentDTO = new AssignmentDTO();
assignmentDTO.setTitle("test");
assignmentDTO.setDescription("test");
assignmentDTO.setUserId("1");
assignmentDTO.setCreator("1");
assignmentService.addAssignment(assignmentDTO);
AssignmentDTO expectedAssignment = assignmentService.getById(1);
assertEquals(assignmentDTO.getTitle(), expectedAssignment.getTitle());
assertEquals(assignmentDTO.getDescription(), expectedAssignment.getDescription());
assertEquals(assignmentDTO.getUserId(), expectedAssignment.getUserId());
assertEquals(assignmentDTO.getCreator(), expectedAssignment.getCreator());
}
</code></pre>
|
[
{
"answer_id": 74488063,
"author": "Simon Martinelli",
"author_id": 1045142,
"author_profile": "https://Stackoverflow.com/users/1045142",
"pm_score": 2,
"selected": false,
"text": "@Transactional"
},
{
"answer_id": 74488237,
"author": "Nathan Mittelette",
"author_id": 14209474,
"author_profile": "https://Stackoverflow.com/users/14209474",
"pm_score": 2,
"selected": false,
"text": "org.springframework.test.context.jdbc @SqlGroup({\n @Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = {\n \"classpath:datasets/integration/integration_test_before.sql\"}),\n @Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, scripts = {\n \"classpath:datasets/integration/integration_test_after.sql\"})})\n src/test/resources/datasets/integration"
},
{
"answer_id": 74522365,
"author": "Eddú Meléndez",
"author_id": 2203890,
"author_profile": "https://Stackoverflow.com/users/2203890",
"pm_score": 0,
"selected": false,
"text": "addAssignment id AssignmentDTO assignment = assignmentService.addAssignment(assignmentDTO);\n\nAssignmentDTO expectedAssignment = assignmentService.getById(assignment.getId());\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10148986/"
] |
74,488,038
|
<p>I was writing some code and realized this might be a reasonably common operation. I also realized I don't know a clean way to do it.</p>
<p>The questions is: Get the top 5 entries in column1, sorted by column2, within groups given by column3.</p>
<p>If I had to intuit how this would be writen in Polars it'd be:</p>
<pre><code>df.select(pl.col('column1').top_k(n=5, by='column2').over('column3'))
</code></pre>
<p>But note that is made up code; it does not work.</p>
<p>Consider this sample data:</p>
<pre><code>import numpy as np
import pandas as pd
import polars as pl
data_size = 10_000_000
np.random.seed = 1
saleValue = np.random.randint(0, 100, data_size)
storeId = np.random.choice([f'Store: {i}' for i in range(200_000)], replace=True, size=data_size)
customerId = np.random.choice([f'Customer: {i}' for i in range(1_000)], replace=True, size=data_size)
df = pd.DataFrame(
dict(storeId=storeId, customerId=customerId, saleValue=saleValue)
).pipe(pl.from_pandas)
</code></pre>
<p>It generates a dataframe of the form:</p>
<pre><code>┌───────────────┬───────────────┬───────────┐
│ storeId ┆ customerId ┆ saleValue │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i32 │
╞═══════════════╪═══════════════╪═══════════╡
│ Store: 161472 ┆ Customer: 960 ┆ 29 │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ Store: 168620 ┆ Customer: 814 ┆ 21 │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ Store: 37904 ┆ Customer: 80 ┆ 61 │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ Store: 166077 ┆ Customer: 516 ┆ 23 │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ Store: 141748 ┆ Customer: 549 ┆ 58 │
└─///───────────┴─///───────────┴─///───────┘
</code></pre>
<p>I'm curious how one would get the top 5 customer per store, sorted by their total spend.</p>
<p>One solution is:</p>
<pre><code>(df
# This part is essential; we need to get the total spend (sales)
.groupby(['storeId','customerId'])
.agg(pl.col('saleValue').sum().alias('totalSales'))
# This is the part I think could be cleaner
.sort('totalSales', reverse=True)
.groupby('storeId')
.agg(pl.col('customerId').head(5).list().alias('customerIds'))
)
┌───────────────┬─────────────────────────────────────┐
│ storeId ┆ customerIds │
│ --- ┆ --- │
│ str ┆ list[str] │
╞═══════════════╪═════════════════════════════════════╡
│ Store: 78152 ┆ ["Customer: 753", "Customer: 170... │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ Store: 67676 ┆ ["Customer: 957", "Customer: 896... │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ Store: 45152 ┆ ["Customer: 118", "Customer: 127... │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ Store: 183339 ┆ ["Customer: 370", "Customer: 227... │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ Store: 144688 ┆ ["Customer: 328", "Customer: 294... │
└─///───────────┴─///─────────────────────────────────┘
</code></pre>
<p>But I wonder if there is something cleaner using <code>.top_k</code></p>
|
[
{
"answer_id": 74499120,
"author": "jvz",
"author_id": 5504925,
"author_profile": "https://Stackoverflow.com/users/5504925",
"pm_score": 2,
"selected": true,
"text": "df_agg df_agg = df.groupby(['storeId','customerId']).agg(pl.col('saleValue').sum().alias('totalSales'))\n df_agg.groupby('storeId').agg(pl.col('customerId').sort_by('totalSales', reverse=True).slice(0,5))\n sort_by slice head list top_k sort_by top_k by"
},
{
"answer_id": 74512043,
"author": "ΩΠΟΚΕΚΡΥΜΜΕΝΟΣ",
"author_id": 20557510,
"author_profile": "https://Stackoverflow.com/users/20557510",
"pm_score": 0,
"selected": false,
"text": "top_k (\n df.groupby([\"storeId\", \"customerId\"])\n .agg(pl.col(\"saleValue\").sum().alias(\"totalSales\"))\n .filter(\n pl.col(\"totalSales\")\n >= pl.col(\"totalSales\").top_k(k=5).list().over(\"storeId\").arr.last()\n )\n)\n shape: (1048652, 3)\n┌───────────────┬───────────────┬────────────┐\n│ storeId ┆ customerId ┆ totalSales │\n│ --- ┆ --- ┆ --- │\n│ str ┆ str ┆ i64 │\n╞═══════════════╪═══════════════╪════════════╡\n│ Store: 92626 ┆ Customer: 829 ┆ 98 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 56532 ┆ Customer: 840 ┆ 93 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 159073 ┆ Customer: 684 ┆ 88 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 131292 ┆ Customer: 836 ┆ 98 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 73245 ┆ Customer: 545 ┆ 93 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 31163 ┆ Customer: 554 ┆ 91 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 128047 ┆ Customer: 971 ┆ 89 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 41563 ┆ Customer: 85 ┆ 92 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 157951 ┆ Customer: 45 ┆ 97 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 7677 ┆ Customer: 390 ┆ 88 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ ... ┆ ... ┆ ... │\n (\n df.groupby([\"storeId\", \"customerId\"])\n .agg(pl.col(\"saleValue\").sum().alias(\"totalSales\"))\n .filter(\n pl.col(\"totalSales\")\n >= pl.col(\"totalSales\").top_k(k=5).list().over(\"storeId\").arr.last()\n )\n .sort([\"storeId\", \"totalSales\"], reverse=[False, True])\n)\n shape: (1048652, 3)\n┌──────────────┬───────────────┬────────────┐\n│ storeId ┆ customerId ┆ totalSales │\n│ --- ┆ --- ┆ --- │\n│ str ┆ str ┆ i64 │\n╞══════════════╪═══════════════╪════════════╡\n│ Store: 0 ┆ Customer: 46 ┆ 151 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 0 ┆ Customer: 267 ┆ 102 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 0 ┆ Customer: 354 ┆ 94 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 0 ┆ Customer: 416 ┆ 93 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 0 ┆ Customer: 729 ┆ 93 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 1 ┆ Customer: 459 ┆ 99 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 1 ┆ Customer: 417 ┆ 90 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 1 ┆ Customer: 982 ┆ 89 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 1 ┆ Customer: 337 ┆ 86 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 1 ┆ Customer: 202 ┆ 84 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ ... ┆ ... ┆ ... │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 99998 ┆ Customer: 536 ┆ 99 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 99998 ┆ Customer: 295 ┆ 99 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 99998 ┆ Customer: 841 ┆ 98 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 99998 ┆ Customer: 782 ┆ 94 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 99999 ┆ Customer: 29 ┆ 96 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 99999 ┆ Customer: 84 ┆ 96 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 99999 ┆ Customer: 557 ┆ 96 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 99999 ┆ Customer: 885 ┆ 91 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 99999 ┆ Customer: 866 ┆ 89 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ Store: 99999 ┆ Customer: 695 ┆ 89 │\n└──────────────┴───────────────┴────────────┘\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17194313/"
] |
74,488,046
|
<p>I am stumbling into an issue with a regex search in python</p>
<p>So I have:</p>
<pre class="lang-py prettyprint-override"><code>testVariable = re.findall(r'functest(.*?)1', 'functest exampleOne [2] functest exampleTwo [1] functest exampleOne throw [2] functest exampleThree [1]')
</code></pre>
<p>Current Output is:</p>
<pre><code>[' exampleOne [2] functest exampleTwo [', ' exampleOne throw [2] functest exampleThree [']
</code></pre>
<p>But what I want is to find all occurences between ‘functest’ & 1' <or 2, or 3 based on need> so output should be like:</p>
<pre><code>['exampleTwo [, exampleThree [']
</code></pre>
<p>this because both above are between functest & 1 as I need. Anyone have any idea?</p>
|
[
{
"answer_id": 74488191,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 2,
"selected": true,
"text": "\\bfunctest\\b\\s*(\\D*)[13]\\b\n \\bfunctest\\b\\s* (\\D*) [13] \\b \\bfunctest\\b\\s*([^][]*\\[)[13]]\n import re\n\npattern = r\"\\bfunctest\\b\\s*([^][]*\\[)239]\"\n\ns = \"functest exampleOne [2] functest exampleTwo [239] functest exampleOne throw [2] functest exampleThree [1] functest exampleFour [2] functest exampleFive [239]\"\n\nprint(re.findall(pattern, s))\n ['exampleTwo [', 'exampleFive [']\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13053168/"
] |
74,488,051
|
<p>Currently I load multiple parquet file with this code :</p>
<pre><code>df = spark.read.parquet("/mnt/dev/bronze/Voucher/*/*")
</code></pre>
<p>(Into the Voucher folder, there is one folder by date, and one parquet file inside it)</p>
<p>How can I add the creation date of each parquet file into my DataFrame ?</p>
<p>Thanks</p>
<p><strong>EDIT 1:</strong></p>
<p>Thanks <strong>rainingdistros</strong>, I wrote this:</p>
<pre><code>import os
from datetime import datetime, timedelta
Path = "/dbfs/mnt/dev/bronze/Voucher/2022-09-23/"
fileFull = Path +'/'+'XXXXXX.parquet'
statinfo = os.stat(fileFull)
create_date = datetime.fromtimestamp(statinfo.st_ctime)
display(create_date)
</code></pre>
<p>Now I must find a way to loop through all the files and add a column in the DataFrame.</p>
|
[
{
"answer_id": 74639432,
"author": "Saideep Arikontham",
"author_id": 18844585,
"author_profile": "https://Stackoverflow.com/users/18844585",
"pm_score": 2,
"selected": true,
"text": "os.stat st_mtime st_ctime os.stat from pyspark.sql.functions import lit\nimport pandas as pd\npath = \"/dbfs/mnt/repro/2022-12-01\"\nfileinfo = os.listdir(path)\nfor file in fileinfo:\n pdf = pd.read_csv(f\"{path}/{file}\")\n pdf.display()\n statinfo = os.stat(\"/dbfs/mnt/repro/2022-12-01/sample1.csv\")\n create_date = datetime.fromtimestamp(statinfo.st_ctime)\n pdf['creation_date'] = [create_date.date()] * len(pdf)\n pdf.to_csv(f\"{path}/{file}\", index=False)\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6565296/"
] |
74,488,079
|
<p>i am working on project which contains more than 200 input fields for list.is it possible to manage them with single state input</p>
<pre><code>import { useState } from "react";
import Item from "../Components/Item";
const initialState={
input:''
}
const List = () => {
const [values,setValues]=useState(initialState)
const handleChange=(e)=>{
setValues({
...values,[e.target.name]:e.target.value
})
}
return (
<div className="container">
<div className="listhead">
<h3 className="text-center">Price List-2022</h3>
<table className="table table-bordered border-dark table-hover text-center">
<thead className="bg-success text-white table-bordered border-dark">
<tr>
<th>S.No</th>
<th>Item</th>
<th>Price</th>
<th>Qty</th>
<th>Total</th>
</tr>
</thead>
<Item
product="bomb"
name="input"
price="50"
value={values.input}
handleChange={handleChange}
/>
<Item
product="chakkar"
name="input"
price="100"
value={values.input}
handleChange={handleChange}
/>
</table>
</div>
</div>
);
};
export default List;
</code></pre>
<p>child element</p>
<pre><code>
const Item = ({name,product,price,value,handleChange}) => {
return (
<tbody>
<tr>
<th>1</th>
<th>{product}</th>
<th>{price}</th>
<th className="w-25">
<input
name={name}
value={value}
onChange={handleChange}
type='number'
/>
</th>
<th> </th>
</tr>
</tbody>
);
};
export default Item;
</code></pre>
<p>with this code if i enter values in input fields all other input fields reads the same value. if i need to create 200 input field with data, what are the ways to do that?</p>
|
[
{
"answer_id": 74488190,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 2,
"selected": true,
"text": " <Item\n name=\"input\"\n price=\"50\"\n value={values}\n handleChange={handleChange}\n />\n <input\n name={name}\n value={values[name]}\n onChange={handleChange}\n type='number'\n />\n"
},
{
"answer_id": 74488325,
"author": "RubenSmn",
"author_id": 20088324,
"author_profile": "https://Stackoverflow.com/users/20088324",
"pm_score": -1,
"selected": false,
"text": "name e.target.name <Item\n product=\"Something\"\n name={\"unique identifier\"}\n price=\"50\"\n value={values[\"unique identifier\"]}\n handleChange={handleChange}\n/>\n setValues((prevValues) => {\n return {\n ...prevValues,\n [e.target.name]: e.target.value,\n };\n});\n``\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20507696/"
] |
74,488,096
|
<p>I'm trying to trigger an update when a <code>list</code> in my <code>map</code> changes. Type is <code>Map<String, List<int>></code>. Basically one of the integers is changing in the list but not triggering the blocbuilder. Although when I print the state the value is updated. I'm using freezed. From what I understand freezed only provides deep copies for nested @freezed objects but not for Iterables. I've seen a few solutions for this kind of problem. For example create a new Map with <code>Map.from</code> and emit that map. But that doesn't trigger a rebuild. Any suggestions!</p>
<p>My <code>freezed</code> state is</p>
<pre><code>onst factory RiskAttitudeState.loaded({
required int customerId,
required RiskAttitudeQuestionsInfo riskAttitude,
required Map<String, List<int>> answerIds,
@Default(FormzStatus.pure) FormzStatus status,
int? finalRisk,
}) = RiskAttitudeLoaded;
</code></pre>
<p>And I'm updating an integer in the list type <code>List<int></code> in the map <code>answerIds</code></p>
<p>Here is the <code>bloc</code>
Future _mapAnswerToState(</p>
<pre><code> String id, List<int> answerIds, Emitter<RiskAttitudeState> emit) async {
await state.maybeMap(
loaded: (RiskAttitudeLoaded loaded) async {
if (loaded.answerIds.containsKey(id)) {
loaded.answerIds.update(
id,
(_) => answerIds,
ifAbsent: () {
add(RiskAttitudeEvent.error(Exception('unknown Question ID: $id')));
return answerIds;
},
);
}
emit(loaded.copyWith(answerIds: loaded.answerIds));
},
orElse: () async {},
);
}
</code></pre>
<p>For contest if I pass an empty map like this <code>emit(loaded.copyWith(answerIds:{}));</code></p>
<p>the builder gets triggered.</p>
|
[
{
"answer_id": 74488190,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 2,
"selected": true,
"text": " <Item\n name=\"input\"\n price=\"50\"\n value={values}\n handleChange={handleChange}\n />\n <input\n name={name}\n value={values[name]}\n onChange={handleChange}\n type='number'\n />\n"
},
{
"answer_id": 74488325,
"author": "RubenSmn",
"author_id": 20088324,
"author_profile": "https://Stackoverflow.com/users/20088324",
"pm_score": -1,
"selected": false,
"text": "name e.target.name <Item\n product=\"Something\"\n name={\"unique identifier\"}\n price=\"50\"\n value={values[\"unique identifier\"]}\n handleChange={handleChange}\n/>\n setValues((prevValues) => {\n return {\n ...prevValues,\n [e.target.name]: e.target.value,\n };\n});\n``\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2387962/"
] |
74,488,142
|
<p>I m building a car simulator game using Unity. For the input I m using Logitheck steering wheel G29. Now I need to use Hand Controller to accelerate or break.
This is my Hand Controller
Hand Controller HC1
<a href="https://www.3drap.it/product/hand-controller-throttle-and-brake-gaming-is-possible/" rel="nofollow noreferrer">Link</a></p>
<p>Now I can I interpect his input ? This device is recognize by my windows 10 system, but if I try to start the game with this device I cannot accelerate or break the car.</p>
<p>I configured this in my InputController of Unity:
<a href="https://i.stack.imgur.com/3gdfG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3gdfG.png" alt="enter image description here" /></a></p>
<p>And in my IRDSPlayerControls.cs file I write these lines of code:</p>
<pre><code>if (Input.anyKey)
{
foreach (KeyCode kcode in Enum.GetValues(typeof(KeyCode)))
{
Debug.Log("Joystick pressed " + kcode);
}
}
Debug.Log("Input debug acc: " + Input.GetAxis("Vertical3"));
Debug.Log("Input debug frenata: " + Input.GetAxis("Vertical4"));
</code></pre>
<p>In Console of Unity, I can display this:</p>
<pre><code>Input debug acc: -1
Input debug frenata: -1
</code></pre>
|
[
{
"answer_id": 74528293,
"author": "Jabbar",
"author_id": 16930239,
"author_profile": "https://Stackoverflow.com/users/16930239",
"pm_score": 2,
"selected": false,
"text": "joystick 1 button 0, joystick 1 button 1, joystick 2 button 0… joystick button 0, joystick button 1, joystick button 2… using UnityEngine;\n\npublic class Example : MonoBehaviour\n{\n // Prints a joystick name if movement is detected.\n\n void Update()\n {\n // requires you to set up axes \"Joy0X\" - \"Joy3X\" and \"Joy0Y\" - \"Joy3Y\" in the Input Manager\n for (int i = 0; i < 4; i++)\n {\n if (Mathf.Abs(Input.GetAxis(\"Joy\" + i + \"X\")) > 0.2 ||\n Mathf.Abs(Input.GetAxis(\"Joy\" + i + \"Y\")) > 0.2)\n {\n Debug.Log(Input.GetJoystickNames()[i] + \" is moved\");\n }\n }\n }\n}\n"
},
{
"answer_id": 74556954,
"author": "Lotan",
"author_id": 7878320,
"author_profile": "https://Stackoverflow.com/users/7878320",
"pm_score": 0,
"selected": false,
"text": "if (Input.anyKey)\n {\n foreach(KeyCode kcode in Enum.GetValues(typeof(KeyCode)))\n {\n Debug.Log(kcode);\n }\n }\n"
},
{
"answer_id": 74594935,
"author": "Strom",
"author_id": 10316640,
"author_profile": "https://Stackoverflow.com/users/10316640",
"pm_score": -1,
"selected": false,
"text": " InputSystem.onDeviceChange +=\n (device, change) =>\n {\n switch (change)\n {\n case InputDeviceChange.Added:\n // New Device.\n Debug.Log(\"New device added.\");\n break;\n case InputDeviceChange.Disconnected:\n // Device got unplugged.\n break;\n case InputDeviceChange.Connected:\n // Plugged back in.\n break;\n case InputDeviceChange.Removed:\n // Remove from Input System entirely; by default, Devices stay in the system once discovered.\n break;\n default:\n // See InputDeviceChange reference for other event types.\n break;\n }\n }\n var trace = new InputEventTrace(); // Can also give device ID to only\n // trace events for a specific device.\n\n trace.Enable();\n\n //…run stuff\n\n var current = new InputEventPtr();\n while (trace.GetNextEvent(ref current))\n {\n Debug.Log(\"Got some event: \" + current);\n }\n\n // Trace consumes unmanaged resources. Make sure to dispose.\n trace.Dispose();\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2405663/"
] |
74,488,160
|
<p>I have a TEXT file with 4 fields and 3rd field is JSON string which I want to extract and create a separate column in dataframe.</p>
<pre><code>pk,line,json,date
DBG,CDL,{"line":"CDL","stn":"DBG","latitude":"12.298915","longitude":"143.846263","isInterchange":true,"isIncidentStn":false,"stnKpis":[{"code":"PCD_PCT","value":0.1,"valueCreatedTs":1667361600000,"confidence":"50.0",}]},20221102
</code></pre>
<p>Expected output format in dataframe:</p>
<p><a href="https://i.stack.imgur.com/evEtx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/evEtx.png" alt="enter image description here" /></a></p>
<p>I tried below command , but it didn't produce expected output</p>
<pre><code>df=spark.read.csv("/content/sample_data/file.txt",header=True,inferSchema=True,quote='"',escape='"')
</code></pre>
<p>spark version:2.4
python version:3.6</p>
|
[
{
"answer_id": 74528293,
"author": "Jabbar",
"author_id": 16930239,
"author_profile": "https://Stackoverflow.com/users/16930239",
"pm_score": 2,
"selected": false,
"text": "joystick 1 button 0, joystick 1 button 1, joystick 2 button 0… joystick button 0, joystick button 1, joystick button 2… using UnityEngine;\n\npublic class Example : MonoBehaviour\n{\n // Prints a joystick name if movement is detected.\n\n void Update()\n {\n // requires you to set up axes \"Joy0X\" - \"Joy3X\" and \"Joy0Y\" - \"Joy3Y\" in the Input Manager\n for (int i = 0; i < 4; i++)\n {\n if (Mathf.Abs(Input.GetAxis(\"Joy\" + i + \"X\")) > 0.2 ||\n Mathf.Abs(Input.GetAxis(\"Joy\" + i + \"Y\")) > 0.2)\n {\n Debug.Log(Input.GetJoystickNames()[i] + \" is moved\");\n }\n }\n }\n}\n"
},
{
"answer_id": 74556954,
"author": "Lotan",
"author_id": 7878320,
"author_profile": "https://Stackoverflow.com/users/7878320",
"pm_score": 0,
"selected": false,
"text": "if (Input.anyKey)\n {\n foreach(KeyCode kcode in Enum.GetValues(typeof(KeyCode)))\n {\n Debug.Log(kcode);\n }\n }\n"
},
{
"answer_id": 74594935,
"author": "Strom",
"author_id": 10316640,
"author_profile": "https://Stackoverflow.com/users/10316640",
"pm_score": -1,
"selected": false,
"text": " InputSystem.onDeviceChange +=\n (device, change) =>\n {\n switch (change)\n {\n case InputDeviceChange.Added:\n // New Device.\n Debug.Log(\"New device added.\");\n break;\n case InputDeviceChange.Disconnected:\n // Device got unplugged.\n break;\n case InputDeviceChange.Connected:\n // Plugged back in.\n break;\n case InputDeviceChange.Removed:\n // Remove from Input System entirely; by default, Devices stay in the system once discovered.\n break;\n default:\n // See InputDeviceChange reference for other event types.\n break;\n }\n }\n var trace = new InputEventTrace(); // Can also give device ID to only\n // trace events for a specific device.\n\n trace.Enable();\n\n //…run stuff\n\n var current = new InputEventPtr();\n while (trace.GetNextEvent(ref current))\n {\n Debug.Log(\"Got some event: \" + current);\n }\n\n // Trace consumes unmanaged resources. Make sure to dispose.\n trace.Dispose();\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4324123/"
] |
74,488,166
|
<p>hello all I have a small issue
I want to add a condition in the extension where it works like this:
If you are on the home page, go to the relevant section
But if we are on another page, such as the user page, then when I press any button in the navbar, it takes me to the home page.</p>
<pre><code> <nav id="nav-menu-container">
<ul className="nav-menu">
<li className="menu-active"> <Link className="navbar-brand" to='/'>Home</Link></li>
<li><a href="#about">About Us</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#team">Team</a></li>
{sessionStorage.getItem("username")!== null?<>
<li><Link className="navbar-brand" to='/Contract'>Contarcts</Link></li>
<li><Link className="navbar-brand" to='/Userprofile'>{sessionStorage.getItem('username')} </Link></li>
<li><button className="logout" onClick={logout} >LOGOUT</button></li></>:<>
{/* add if Condition to the Link that directs the extension */}
<li><Link className="navbar-brand" to='/Signup'>Signup</Link></li>
<li><Link className="navbar-brand" to='/Login'>Login</Link></li></>}
</ul>
</nav>
</code></pre>
<p>if I am on a home page go to the specific section if I am not go to the homepage as simple as that.</p>
|
[
{
"answer_id": 74528293,
"author": "Jabbar",
"author_id": 16930239,
"author_profile": "https://Stackoverflow.com/users/16930239",
"pm_score": 2,
"selected": false,
"text": "joystick 1 button 0, joystick 1 button 1, joystick 2 button 0… joystick button 0, joystick button 1, joystick button 2… using UnityEngine;\n\npublic class Example : MonoBehaviour\n{\n // Prints a joystick name if movement is detected.\n\n void Update()\n {\n // requires you to set up axes \"Joy0X\" - \"Joy3X\" and \"Joy0Y\" - \"Joy3Y\" in the Input Manager\n for (int i = 0; i < 4; i++)\n {\n if (Mathf.Abs(Input.GetAxis(\"Joy\" + i + \"X\")) > 0.2 ||\n Mathf.Abs(Input.GetAxis(\"Joy\" + i + \"Y\")) > 0.2)\n {\n Debug.Log(Input.GetJoystickNames()[i] + \" is moved\");\n }\n }\n }\n}\n"
},
{
"answer_id": 74556954,
"author": "Lotan",
"author_id": 7878320,
"author_profile": "https://Stackoverflow.com/users/7878320",
"pm_score": 0,
"selected": false,
"text": "if (Input.anyKey)\n {\n foreach(KeyCode kcode in Enum.GetValues(typeof(KeyCode)))\n {\n Debug.Log(kcode);\n }\n }\n"
},
{
"answer_id": 74594935,
"author": "Strom",
"author_id": 10316640,
"author_profile": "https://Stackoverflow.com/users/10316640",
"pm_score": -1,
"selected": false,
"text": " InputSystem.onDeviceChange +=\n (device, change) =>\n {\n switch (change)\n {\n case InputDeviceChange.Added:\n // New Device.\n Debug.Log(\"New device added.\");\n break;\n case InputDeviceChange.Disconnected:\n // Device got unplugged.\n break;\n case InputDeviceChange.Connected:\n // Plugged back in.\n break;\n case InputDeviceChange.Removed:\n // Remove from Input System entirely; by default, Devices stay in the system once discovered.\n break;\n default:\n // See InputDeviceChange reference for other event types.\n break;\n }\n }\n var trace = new InputEventTrace(); // Can also give device ID to only\n // trace events for a specific device.\n\n trace.Enable();\n\n //…run stuff\n\n var current = new InputEventPtr();\n while (trace.GetNextEvent(ref current))\n {\n Debug.Log(\"Got some event: \" + current);\n }\n\n // Trace consumes unmanaged resources. Make sure to dispose.\n trace.Dispose();\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19478880/"
] |
74,488,175
|
<p>I am starting to learn C# design SOLID principles and design patterns. I just want to ask what could be the best design pattern to be used to refactor this particular code.</p>
<pre><code>using InvoiceApp.Invoices;
namespace InvoiceApp
{
internal class InvoiceProcessor
{
internal void Process(int client)
{
Console.WriteLine("Processing invoice...");
Invoice invoice;
switch (client)
{
case 0:
invoice = new SimpleInvoice();
break;
case 1:
invoice = new InvoiceWithHeader();
break;
case 2:
invoice = new InvoiceWithFooter();
break;
case 3:
case 4:
invoice = new InvoiceWithHeaderFooter();
break;
default:
throw new ArgumentException("Invalid client");
}
invoice.CreateInvoice();
DisplayInvoice(client, invoice);
SaveInvoice(client, invoice);
}
private void DisplayInvoice(int client, Invoice invoice)
{
if (client == 4)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(invoice.Data);
} else
{
Console.WriteLine(invoice.Data);
}
}
private void SaveInvoice(int client, Invoice invoice)
{
string data = invoice.Data;
//cipher first
switch (client)
{
case 0:
case 1:
data = CaesarCipher(data);
break;
case 2:
case 3:
data = WeirdCipher(data);
break;
}
File.WriteAllText("Invoice.txt", data);
Console.WriteLine("Invoice data saved!");
}
private string CaesarCipher(string input)
{
const int key = 4;
string output = string.Empty;
foreach (char ch in input)
{
if (!char.IsLetter(ch))
{
output += ch;
}
char d = char.IsUpper(ch) ? 'A' : 'a';
output += (char)((((ch + key) - d) % 26) + d);
}
return output;
}
private string WeirdCipher(string input)
{
return input.Replace('A', '$').Replace('H', '#');
}
}
}
</code></pre>
<p>I know this class violates SRP and maybe Dependency Injection(not sure), but I am having a hard time what could be the best design pattern to use to make the the implementation dynamic and maintainable.</p>
|
[
{
"answer_id": 74492257,
"author": "StepUp",
"author_id": 1646240,
"author_profile": "https://Stackoverflow.com/users/1646240",
"pm_score": 1,
"selected": false,
"text": "switch Dictionary<TKey, TValue> new public enum InvoiceType\n{\n SimpleInvoice, InvoiceWithHeader, InvoiceWithFooter, InvoiceWithHeaderFooter\n}\n public class InvoiceFactory\n{\n private Dictionary<InvoiceType, Invoice> _invoiceByType = new()\n {\n { InvoiceType.SimpleInvoice, new SimpleInvoice() },\n { InvoiceType.InvoiceWithHeader, new InvoiceWithHeader() },\n { InvoiceType.InvoiceWithFooter, new InvoiceWithFooter() },\n { InvoiceType.InvoiceWithHeaderFooter, new InvoiceWithHeaderFooter() },\n };\n\n public Invoice GetInstanceByType(InvoiceType invoiceType) => \n _invoiceByType[invoiceType];\n}\n public abstract class Invoice\n{\n public void Create() { }\n}\n Invoice Invoice Create() Invoice invoice.CreateInvoice(); // can be improved to -> please, see the next row\ninvoice.Create(); // imho, it is nice\n Invoice public class SimpleInvoice : Invoice\n{\n}\n\npublic class InvoiceWithHeader : Invoice\n{\n}\n\npublic class InvoiceWithFooter : Invoice\n{\n}\n\npublic class InvoiceWithHeaderFooter : Invoice\n{\n}\n InvoiceProcessor public class InvoiceProcessor\n{\n internal void Process(InvoiceType invoiceType)\n {\n Console.WriteLine(\"Processing invoice...\");\n InvoiceFactory factory = new InvoiceFactory();\n Invoice invoice = factory.GetInstanceByType(invoiceType);\n\n invoice.Create();\n\n // other code is omitted for the brevity\n }\n} \n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20538516/"
] |
74,488,216
|
<p>I have a table that logs calls and I'm trying to map the called numbers to the users answering them. To do this I need to display a table that shows me two seperate questions.</p>
<p>I guess the relevant columns in the existing table are "phone_number" and "user_email". Lets say we have around 400 numbers and 450 users.</p>
<p>Example Original Table, name would be "callsoftware_calls":</p>
<pre><code>| User_Email | phone_number |
| -------- | -------- |
| John@gmail.com | 1800 400 |
| John@gmail.com | 1800 400 |
| John@gmail.com | 1800 700 |
| Mary@gmail.com | 1800 600 |
| Mary@gmail.com | 1800 400 |
| Mary@gmail.com | 1800 300 |
</code></pre>
<p>Ideal table outputs for the two queries would be:</p>
<pre><code>| User | Count of assigned Numbers |
| -------- | -------- |
| John@gmail.com | 8 |
| Mary@gmail.com | 3 |
</code></pre>
<p>and</p>
<pre><code>| PhoneNumber | Count of unique emails/users |
| -------- | -------- |
| 1800 400 | 10 |
| 1800 300 | 6 |
</code></pre>
<p>any ideas on how to generate these two tables?</p>
<p>Honestly I don't know where to start in generating such a query. I'm used to excel and just getting started with sql so trying to do basic analysis</p>
|
[
{
"answer_id": 74492257,
"author": "StepUp",
"author_id": 1646240,
"author_profile": "https://Stackoverflow.com/users/1646240",
"pm_score": 1,
"selected": false,
"text": "switch Dictionary<TKey, TValue> new public enum InvoiceType\n{\n SimpleInvoice, InvoiceWithHeader, InvoiceWithFooter, InvoiceWithHeaderFooter\n}\n public class InvoiceFactory\n{\n private Dictionary<InvoiceType, Invoice> _invoiceByType = new()\n {\n { InvoiceType.SimpleInvoice, new SimpleInvoice() },\n { InvoiceType.InvoiceWithHeader, new InvoiceWithHeader() },\n { InvoiceType.InvoiceWithFooter, new InvoiceWithFooter() },\n { InvoiceType.InvoiceWithHeaderFooter, new InvoiceWithHeaderFooter() },\n };\n\n public Invoice GetInstanceByType(InvoiceType invoiceType) => \n _invoiceByType[invoiceType];\n}\n public abstract class Invoice\n{\n public void Create() { }\n}\n Invoice Invoice Create() Invoice invoice.CreateInvoice(); // can be improved to -> please, see the next row\ninvoice.Create(); // imho, it is nice\n Invoice public class SimpleInvoice : Invoice\n{\n}\n\npublic class InvoiceWithHeader : Invoice\n{\n}\n\npublic class InvoiceWithFooter : Invoice\n{\n}\n\npublic class InvoiceWithHeaderFooter : Invoice\n{\n}\n InvoiceProcessor public class InvoiceProcessor\n{\n internal void Process(InvoiceType invoiceType)\n {\n Console.WriteLine(\"Processing invoice...\");\n InvoiceFactory factory = new InvoiceFactory();\n Invoice invoice = factory.GetInstanceByType(invoiceType);\n\n invoice.Create();\n\n // other code is omitted for the brevity\n }\n} \n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20104248/"
] |
74,488,246
|
<p>I have a project that is using <code>net6</code> as the target framework. I recently installed .net core 7 SDK on my PC. After that, when I use <code>dotnet watch run</code> I get a strange error:</p>
<pre><code>Unhandled exception.
System.IO.FileNotFoundException:
Could not load file or assembly 'System.Runtime, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
The system cannot find the file specified.
.....
</code></pre>
<p>As the error suggests it is looking for .net 7 dlls in my project, while my project is targeting .net 6!</p>
<p>For a quick hack, I added a <code>global.json</code> in the root of project to explicitly using .net 6 SDK to build my project. However, I want a proper solution, and to know the reason behind this error.</p>
<p>Please note that I only experience this issue with <code>dotnet watch run</code>. I.e., other cases like <code>dotnet build</code>, <code>dotnet run</code>, <code>dotnet publish</code> are all fine!</p>
|
[
{
"answer_id": 74488505,
"author": "Lajos Arpad",
"author_id": 436560,
"author_profile": "https://Stackoverflow.com/users/436560",
"pm_score": 0,
"selected": false,
"text": "web.config <assemblies> <assemblies System.Runtime"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1730846/"
] |
74,488,301
|
<p>I have found interesting behaviour of js extends, and do not understand the reasons of it<br />
in case of copy values right from another value, for some reasons value will be copied from parent</p>
<pre><code>class parent {
defaultValue = 1;
value = this.defaultValue;
}
new parent() // {defaultValue: 1, value: 1}
class child extends parent {
defaultValue = 2;
}
new child() // {defaultValue: 2, value: 1}
</code></pre>
<p>which is really not obvious and unclear for me<br />
but if i replace it by function or even getter the behaviour will be changed, and i get the value from child</p>
<pre><code>class parent {
get defaultValue() { return 1; }
value = this.defaultValue;
}
new parent() // {defaultValue: 1, value: 1}
class child extends parent {
get defaultValue() { return 2; }
}
new child() // {defaultValue: 2, value: 2}
</code></pre>
<p>the main question here, is why in the moment of child creation in first case JS looking on parrent class to take value, but in seccond case JS looking on child class to take value</p>
<p>can someone explain the reason of such behaviour</p>
<p><strong>EDIT</strong> See t.niese or Yury Tarabanko answers for details</p>
<p>the short answer seems in next way</p>
<p>getters(also function) and function will be ovverided in prototype which allow them to be called by parent with child changes (in real it is expected)</p>
<p>while first example with assignee simple values will be called only in the moment of class creation (constructor or super) and it will be appear only in scope of current class(which cannot be changed by child) and prototype(which can be changed by child)</p>
|
[
{
"answer_id": 74491646,
"author": "Yury Tarabanko",
"author_id": 351705,
"author_profile": "https://Stackoverflow.com/users/351705",
"pm_score": 1,
"selected": false,
"text": "Child1 Parent1 defaultValue = 1 Child2 Child2.prototype defaultValue class Parent1 {\n defaultValue = 1;\n value = this.defaultValue;\n}\n\nclass Child1 extends Parent1 {\n defaultValue = 2;\n}\n\n\n\n\nclass Parent2 {\n get defaultValue() { return 1; }\n value = this.defaultValue;\n}\n\n\nclass Child2 extends Parent2 {\n get defaultValue() { return 2; }\n}\n\n\nconsole.log(Object.hasOwn(new Child1(), 'defaultValue'))\nconsole.log(Object.hasOwn(new Child2(), 'defaultValue'))"
},
{
"answer_id": 74491839,
"author": "t.niese",
"author_id": 1960455,
"author_profile": "https://Stackoverflow.com/users/1960455",
"pm_score": 3,
"selected": true,
"text": "parent child class parent {\n value = this.test();\n constructor() {\n this.test()\n }\n}\n\nclass child extends parent {\n test() {\n console.log('test')\n }\n}\n\nnew child() class parent {\n defaultValue = (() => {\n console.log('parent:init defaultValue')\n return 1;\n })();\n\n value = (() => {\n console.log('parent:init value')\n return this.defaultValue;\n })();\n\n constructor() {\n console.log('parent constructor')\n }\n}\n\nclass child extends parent {\n defaultValue = (() => {\n console.log('child:init defaultValue')\n return 2;\n })();\n\n\n constructor() {\n console.log('child constructor before super()')\n super()\n console.log('child constructor after super()')\n }\n}\n\nnew child()"
},
{
"answer_id": 74492435,
"author": "Ben Aston",
"author_id": 38522,
"author_profile": "https://Stackoverflow.com/users/38522",
"pm_score": 2,
"selected": false,
"text": "defaultValue Child value Parent this value Parent Child defaultValue defaultValue Parent 1 defaultValue [[Prototype]] [[Prototype]] .prototype [[Prototype]] Object.create(class.prototype)) this.defaultValue Parent value [[Prototype]] Child 2"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17018048/"
] |
74,488,311
|
<p>bonjour / hello</p>
<p>First of all sorry for my very poor english, I'm french and I used google translator.</p>
<p>I'm using an ansible playbook to run a bash script. In my test environment it works, but not in my production environment and I don't understand why.</p>
<p>It's a script that allows to scan for violations, check the status of the services and at the end it generates a report.</p>
<p>In ansible the task is accomplished but the report is not generated, whereas when I run the script directly from the terminal of my vm (hosted by aws) the script works and generates the report for me.</p>
<p>Can you help me please ?</p>
<pre class="lang-yaml prettyprint-override"><code> - name: run the scan to generate deviation report
become: yes
command: sh /<path>
</code></pre>
<p>I tried several commands but I always have the same result. I tried the ansible script module and launched it in debug mode with <code>bash -x</code></p>
|
[
{
"answer_id": 74491646,
"author": "Yury Tarabanko",
"author_id": 351705,
"author_profile": "https://Stackoverflow.com/users/351705",
"pm_score": 1,
"selected": false,
"text": "Child1 Parent1 defaultValue = 1 Child2 Child2.prototype defaultValue class Parent1 {\n defaultValue = 1;\n value = this.defaultValue;\n}\n\nclass Child1 extends Parent1 {\n defaultValue = 2;\n}\n\n\n\n\nclass Parent2 {\n get defaultValue() { return 1; }\n value = this.defaultValue;\n}\n\n\nclass Child2 extends Parent2 {\n get defaultValue() { return 2; }\n}\n\n\nconsole.log(Object.hasOwn(new Child1(), 'defaultValue'))\nconsole.log(Object.hasOwn(new Child2(), 'defaultValue'))"
},
{
"answer_id": 74491839,
"author": "t.niese",
"author_id": 1960455,
"author_profile": "https://Stackoverflow.com/users/1960455",
"pm_score": 3,
"selected": true,
"text": "parent child class parent {\n value = this.test();\n constructor() {\n this.test()\n }\n}\n\nclass child extends parent {\n test() {\n console.log('test')\n }\n}\n\nnew child() class parent {\n defaultValue = (() => {\n console.log('parent:init defaultValue')\n return 1;\n })();\n\n value = (() => {\n console.log('parent:init value')\n return this.defaultValue;\n })();\n\n constructor() {\n console.log('parent constructor')\n }\n}\n\nclass child extends parent {\n defaultValue = (() => {\n console.log('child:init defaultValue')\n return 2;\n })();\n\n\n constructor() {\n console.log('child constructor before super()')\n super()\n console.log('child constructor after super()')\n }\n}\n\nnew child()"
},
{
"answer_id": 74492435,
"author": "Ben Aston",
"author_id": 38522,
"author_profile": "https://Stackoverflow.com/users/38522",
"pm_score": 2,
"selected": false,
"text": "defaultValue Child value Parent this value Parent Child defaultValue defaultValue Parent 1 defaultValue [[Prototype]] [[Prototype]] .prototype [[Prototype]] Object.create(class.prototype)) this.defaultValue Parent value [[Prototype]] Child 2"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19125838/"
] |
74,488,324
|
<p>I have some confusion about permission with using <code>PHPickerViewController</code> & <code>UIImagePickerController</code>.</p>
<p><strong>Do I have to request permission for using it ? (Currently, I open it without request permission but It's working.)</strong></p>
<p><strong>Is it acceptable for upload to app store ? and if it acceptable when I have to request permission for photo?</strong></p>
<p>Ps.
I use <code>PHPickerViewController</code> for iOS14+ and <code>UIImagePickerController</code> for <iOS13.
Thank you for every reply or answer.</p>
|
[
{
"answer_id": 74491646,
"author": "Yury Tarabanko",
"author_id": 351705,
"author_profile": "https://Stackoverflow.com/users/351705",
"pm_score": 1,
"selected": false,
"text": "Child1 Parent1 defaultValue = 1 Child2 Child2.prototype defaultValue class Parent1 {\n defaultValue = 1;\n value = this.defaultValue;\n}\n\nclass Child1 extends Parent1 {\n defaultValue = 2;\n}\n\n\n\n\nclass Parent2 {\n get defaultValue() { return 1; }\n value = this.defaultValue;\n}\n\n\nclass Child2 extends Parent2 {\n get defaultValue() { return 2; }\n}\n\n\nconsole.log(Object.hasOwn(new Child1(), 'defaultValue'))\nconsole.log(Object.hasOwn(new Child2(), 'defaultValue'))"
},
{
"answer_id": 74491839,
"author": "t.niese",
"author_id": 1960455,
"author_profile": "https://Stackoverflow.com/users/1960455",
"pm_score": 3,
"selected": true,
"text": "parent child class parent {\n value = this.test();\n constructor() {\n this.test()\n }\n}\n\nclass child extends parent {\n test() {\n console.log('test')\n }\n}\n\nnew child() class parent {\n defaultValue = (() => {\n console.log('parent:init defaultValue')\n return 1;\n })();\n\n value = (() => {\n console.log('parent:init value')\n return this.defaultValue;\n })();\n\n constructor() {\n console.log('parent constructor')\n }\n}\n\nclass child extends parent {\n defaultValue = (() => {\n console.log('child:init defaultValue')\n return 2;\n })();\n\n\n constructor() {\n console.log('child constructor before super()')\n super()\n console.log('child constructor after super()')\n }\n}\n\nnew child()"
},
{
"answer_id": 74492435,
"author": "Ben Aston",
"author_id": 38522,
"author_profile": "https://Stackoverflow.com/users/38522",
"pm_score": 2,
"selected": false,
"text": "defaultValue Child value Parent this value Parent Child defaultValue defaultValue Parent 1 defaultValue [[Prototype]] [[Prototype]] .prototype [[Prototype]] Object.create(class.prototype)) this.defaultValue Parent value [[Prototype]] Child 2"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14202114/"
] |
74,488,333
|
<p>I am currently trying to write a Blazor component library to be used across different Blazor applications and I would like the ability to toggle whether there is security or not.</p>
<p>So essentially to write a Blazor component that if you so choose, doesn't require authorization, but if you do require authorization you'll need to assign whatever roles the component requires to the ClaimsIdentity in the AuthenticationState.</p>
<pre><code><AuthorizeView Roles="SomeRole">
<Authorized>
...Authorized stuff
</Authorized>
<NotAuthorized>
...Not authorized stuff
</NotAuthorized>
</AuthorizeView>
</code></pre>
<p>So in essence, can I instruct the component to completely ignore the requirement to authorize the user for role <code>SomeRole</code> as above and treat the current session as authorized? Ideally this would be done from a config setting.</p>
<p>My thinking at the moment is this can only be achieved using an <code>@if</code> statement within the component itself to check for the setting and apply different front end code based on what it finds.</p>
|
[
{
"answer_id": 74492744,
"author": "MrC aka Shaun Curtis",
"author_id": 13065781,
"author_profile": "https://Stackoverflow.com/users/13065781",
"pm_score": 1,
"selected": false,
"text": "AuthorizeView AuthorizeView public class UIAuthorizeButton : UIButton\n{\n [CascadingParameter] public Task<AuthenticationState> AuthTask { get; set; \n [Parameter] public string Policy { get; set; } = String.Empty;\n [Parameter] public object? AuthFields { get; set; } = null;\n} = default!;\n [Inject] protected IAuthorizationService authorizationService { get; set; } =default!;\n\n protected async override Task OnParametersSetAsync()\n {\n if (AuthTask is null)\n throw new Exception($\"{this.GetType().FullName} must have access to cascading Paramater {nameof(AuthTask)}\");\n\n await this.CheckPolicy();\n }\n\n protected virtual async ValueTask CheckPolicy()\n {\n var state = await AuthTask!;\n var result = await this.authorizationService.AuthorizeAsync(state.User, AuthFields, Policy);\n // code to hide the component if fails\n }\n}\n IAuthorizationService OwnerId ClaimsPrincipal state.User"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/621059/"
] |
74,488,338
|
<p>I have some problem and maybe I can give an example of two views below what I want to achieve.</p>
<pre><code>class SomeViewOne(TemplateView):
model = None
template_name = 'app/template1.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# The downloads view contains a list of countries eg France, Poland, Germany
# This returns to context and lists these countries in template1
class ItemDetail(TemplateView):
model = None
template_name = 'app/template2.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
countries_name = kwargs.get('str')
The view should get the passed "x" with the name of the country where I described it
below.
</code></pre>
<p>Then on the page I have a list of these countries.
After clicking on the selected country, a new tab should open and show a list of cities in the selected country.</p>
<p>So I am using in loop template1.html as below</p>
<pre><code>{% for x in list_countries %}
<li>
<a href="{% url 'some-name-url' '{{x}}' %}" class="target='_blank'">{{ x }}</a><br>
</li>
{% endfor %}
</code></pre>
<p><strong>I can't pass "x" this way. Why?</strong></p>
<p>The url for the next view looks like this</p>
<pre><code>path('some/countries/<str:x>/',views.ItemDetail.as_view(), name='some-name-url'),
</code></pre>
<p>And I can't get that 'x' given in the template in the href</p>
|
[
{
"answer_id": 74488454,
"author": "Manoj Tolagekar",
"author_id": 17808039,
"author_profile": "https://Stackoverflow.com/users/17808039",
"pm_score": 0,
"selected": false,
"text": "<a href=\"{% url 'some-name-url' {{ x }} %}\" #Just removed single quotes from variable x.\n"
},
{
"answer_id": 74488709,
"author": "JimmyFl0",
"author_id": 17943583,
"author_profile": "https://Stackoverflow.com/users/17943583",
"pm_score": 2,
"selected": true,
"text": "{% for item in items %}\n\n <div class=\"item-title\">\n {{ item }}<br>\n </div>\n <a href=\"{% url 'core:edit_item' item.id %}\">Edit {{ item }}</a>\n{% endfor %}\n <a href=\"{% url 'some-name-url' x %}\" class=\"target='_blank'\">{{ x }}</a>\n"
},
{
"answer_id": 74489351,
"author": "Sunderam Dubey",
"author_id": 17562044,
"author_profile": "https://Stackoverflow.com/users/17562044",
"pm_score": 1,
"selected": false,
"text": "x {{x}} '{{x}}' x some/countries/<str:x>/ kwargs.get('str') kwargs.get('x') countries_name template1.html class ItemDetail(TemplateView):\n template_name = 'template2.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['countries_name'] = self.kwargs.get('x')\n return context\n {% for x in list_countries %}\n <li>\n <a onclick=\"window.open('{% url 'some-name-url' x %}', '_blank')\" style='cursor:pointer;'>{{ x }}</a><br>\n </li>\n{% endfor %}\n countries_name template1.html <p>The clicked country is {{countries_name}}</p>\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17356459/"
] |
74,488,345
|
<p>I'm trying to make an arduino UNO circuit that allows me to set the blinking duration of an LED with two pushbuttons, but I'm having trouble with the program. First of all, the default blinking duration is 0,5 s. And I want to program the first pushbutton to be able to extend the blinking duration by 0,1 seconds, whereas the second one is for speeding up the duration by 0,1 seconds.</p>
<p>So in my current code, I use if statements to check whether the two buttons are pressed or not. If the inc button is pressed, the program should increase the duration by 100 ms, whereas when dec button is pressed, the program should decrease the duration by 100 ms.</p>
<p>However when I run it on the arduino circuit, the duration is stuck in 600 and 500. So in every loop, the program adds 100 ms to the duration time and then decreases it again by 100, even when I do nothing to the buttons.</p>
<p>Here's my code so far:</p>
<pre><code>const int led = 7;
const int buttonUp = 6;
const int buttonDown = 5;
int duration = 500;
void setup(){
pinMode(led, OUTPUT);
pinMode(buttonUp, INPUT);
pinMode(buttonDown, INPUT);
Serial.begin(9600);
}
void loop(){
int inc = digitalRead(buttonUp);
int dec = digitalRead(buttonDown);
if(inc == HIGH){
duration += 100;
Serial.println(duration);
}
if(dec == HIGH){
duration -= 100;
if(duration < 0){
duration = 100;
}
Serial.println(duration);
}
digitalWrite(led, HIGH);
delay(duration);
digitalWrite(led, LOW);
delay(duration);
}
</code></pre>
<p><a href="https://i.stack.imgur.com/qmRXE.png" rel="nofollow noreferrer">the code and circuit</a>
<a href="https://i.stack.imgur.com/XXB96.png" rel="nofollow noreferrer">serial monitor</a></p>
<p>Will be extremely grateful if anyone can point out any mistakes!! Thank you!</p>
|
[
{
"answer_id": 74488454,
"author": "Manoj Tolagekar",
"author_id": 17808039,
"author_profile": "https://Stackoverflow.com/users/17808039",
"pm_score": 0,
"selected": false,
"text": "<a href=\"{% url 'some-name-url' {{ x }} %}\" #Just removed single quotes from variable x.\n"
},
{
"answer_id": 74488709,
"author": "JimmyFl0",
"author_id": 17943583,
"author_profile": "https://Stackoverflow.com/users/17943583",
"pm_score": 2,
"selected": true,
"text": "{% for item in items %}\n\n <div class=\"item-title\">\n {{ item }}<br>\n </div>\n <a href=\"{% url 'core:edit_item' item.id %}\">Edit {{ item }}</a>\n{% endfor %}\n <a href=\"{% url 'some-name-url' x %}\" class=\"target='_blank'\">{{ x }}</a>\n"
},
{
"answer_id": 74489351,
"author": "Sunderam Dubey",
"author_id": 17562044,
"author_profile": "https://Stackoverflow.com/users/17562044",
"pm_score": 1,
"selected": false,
"text": "x {{x}} '{{x}}' x some/countries/<str:x>/ kwargs.get('str') kwargs.get('x') countries_name template1.html class ItemDetail(TemplateView):\n template_name = 'template2.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['countries_name'] = self.kwargs.get('x')\n return context\n {% for x in list_countries %}\n <li>\n <a onclick=\"window.open('{% url 'some-name-url' x %}', '_blank')\" style='cursor:pointer;'>{{ x }}</a><br>\n </li>\n{% endfor %}\n countries_name template1.html <p>The clicked country is {{countries_name}}</p>\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20538442/"
] |
74,488,359
|
<p>I have a python script that sends emails with attachments using GMAIL's API. Each time(mostly after a day) I run the script, I get an error that the token's invalid.</p>
<p>The only solution I have identified so far is to download the json file each time I run the script but I was expecting this to be done only once as I intend to convert the script to a desktop application.</p>
|
[
{
"answer_id": 74488454,
"author": "Manoj Tolagekar",
"author_id": 17808039,
"author_profile": "https://Stackoverflow.com/users/17808039",
"pm_score": 0,
"selected": false,
"text": "<a href=\"{% url 'some-name-url' {{ x }} %}\" #Just removed single quotes from variable x.\n"
},
{
"answer_id": 74488709,
"author": "JimmyFl0",
"author_id": 17943583,
"author_profile": "https://Stackoverflow.com/users/17943583",
"pm_score": 2,
"selected": true,
"text": "{% for item in items %}\n\n <div class=\"item-title\">\n {{ item }}<br>\n </div>\n <a href=\"{% url 'core:edit_item' item.id %}\">Edit {{ item }}</a>\n{% endfor %}\n <a href=\"{% url 'some-name-url' x %}\" class=\"target='_blank'\">{{ x }}</a>\n"
},
{
"answer_id": 74489351,
"author": "Sunderam Dubey",
"author_id": 17562044,
"author_profile": "https://Stackoverflow.com/users/17562044",
"pm_score": 1,
"selected": false,
"text": "x {{x}} '{{x}}' x some/countries/<str:x>/ kwargs.get('str') kwargs.get('x') countries_name template1.html class ItemDetail(TemplateView):\n template_name = 'template2.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['countries_name'] = self.kwargs.get('x')\n return context\n {% for x in list_countries %}\n <li>\n <a onclick=\"window.open('{% url 'some-name-url' x %}', '_blank')\" style='cursor:pointer;'>{{ x }}</a><br>\n </li>\n{% endfor %}\n countries_name template1.html <p>The clicked country is {{countries_name}}</p>\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19971389/"
] |
74,488,361
|
<p>This is the function I need to plot:
<a href="https://i.stack.imgur.com/yRQHG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yRQHG.png" alt="function" /></a></p>
<p>This is my code:</p>
<pre class="lang-py prettyprint-override"><code>pi = np.pi
sin = np.sin
e = np.e
x1 = np.linspace(-10*pi, -pi)
y1 = (4*pi*(e**0.1*x1)) * sin(2*pi*x1)
plt.plot(x1, y1)
x2 = np.linspace(-pi, -pi/2)
y2 = 0
plt.plot(x2, y2)
x3 = np.linspace(-pi/2, pi/2)
y3 = 4/pi * x3**2 - pi
plt.plot(x3, y3)
x4 = np.linspace(pi/2, pi)
y4 = 0
plt.plot(x4, y4)
plt.show()
</code></pre>
<p>But every time I try to run it gives me a ValueError:</p>
<pre><code>ValueError: x and y must have same first dimension, but have shapes (50,) and (1,)
</code></pre>
<p>I have tried using <code>np.piecewise</code> but haven't gotten anywhere.</p>
|
[
{
"answer_id": 74488480,
"author": "Ahmed AEK",
"author_id": 15649230,
"author_profile": "https://Stackoverflow.com/users/15649230",
"pm_score": 0,
"selected": false,
"text": "y2 = np.zeros_like(x2) y4 = np.zeros_like(x4)"
},
{
"answer_id": 74488573,
"author": "Double_LA",
"author_id": 5801964,
"author_profile": "https://Stackoverflow.com/users/5801964",
"pm_score": 0,
"selected": false,
"text": "#...\ny2 = x2*0\nplt.plot(x2, y2)\n\n#...\n\ny4 = x4*0\nplt.plot(x4, y4)\n\n y2 = np.zeros(x2.shape)\ny4 = np.zeros(x4.shape)\n"
},
{
"answer_id": 74489117,
"author": "gboffi",
"author_id": 2749397,
"author_profile": "https://Stackoverflow.com/users/2749397",
"pm_score": 1,
"selected": false,
"text": "numpy.where where from numpy import exp,linspace, pi, sin, where\nfrom matplotlib.pyplot import grid, plot, show\n\nx = linspace(-10*pi, +10*pi, 4001)\ny = where(x < -pi, 4*pi*exp(+x/10)*sin(1*x),\n where(x <-pi/2, 0,\n where(x <+pi/2, 4*x*x/pi-pi,\n where(x < +pi, 0,\n 4*pi*exp(-x/10)*sin(1*x)))))\n \nplot(x, y) ; grid() ; show()\n numpy.where np.nan y"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20538617/"
] |
74,488,367
|
<p>On my website I've got a button which is clicked automatically by js with the loading of the website.</p>
<pre><code>window.onload=function(){
document.getElementById("myBtn").click();
};
</code></pre>
<p>The thing I don't know how to code is that I want the button only to be auto clicked at the first visit of the page or only once an hour...</p>
<p>Is there a way to do it without using jquery?</p>
|
[
{
"answer_id": 74488982,
"author": "George Chond",
"author_id": 17730652,
"author_profile": "https://Stackoverflow.com/users/17730652",
"pm_score": 1,
"selected": true,
"text": "// Initialize an object\nlet obj = {};\n\n// Trigger when DOM loads\nwindow.addEventListener('DOMContentLoaded', () => {\n // Get current Date in UNIX\n let currentDate = Date.now();\n // An hour in UNIX\n const hour = 3600000;\n // The date to reclick\n let reclickDate = currentDate + hour;\n\n // If already clicked\n if (localStorage.getItem('clickData')){\n // Parse the JSON object from localStorage\n let data = JSON.parse(localStorage.getItem('clickData'));\n // The Date to Reclick\n reclickDate = Date(parseInt(data.clickTime)+hour);\n }\n // Otherwise click now and set object JSON\n else {\n document.getElementById(\"myBtn\").click();\n obj.clickTime = Date.now();\n localStorage.setItem('clickData', JSON.stringify(obj));\n }\n\n // Recursive Function\n checkForClick(currentDate, reclickDate);\n});\n\nconst checkForClick = (currentDate, reclickDate) => {\n setTimeout(() => {\n\n // If 1 hour passed\n if (currentDate > reclickDate){\n // Reclick\n document.getElementById(\"myBtn\").click();\n // Set localStorage new data\n obj.clickTime = Date.now();\n localStorage.setItem('clickData', JSON.stringify(obj));\n // Break function\n return;\n }\n\n // Otherwise recall the function\n checkForClick(currentDate+1000, reclickDate);\n }, 1000);\n}\n"
},
{
"answer_id": 74489014,
"author": "AAKASH9820",
"author_id": 12124280,
"author_profile": "https://Stackoverflow.com/users/12124280",
"pm_score": -1,
"selected": false,
"text": "$(document).ready(function(){\n $(\"#myBtn\").trigger('click'); \n});\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20324342/"
] |
74,488,379
|
<p>So I created a task handler. I want to have it run for some predetermined guaranteed amount of time, then I want to do some of my stuff, and only then do I need the result of the handler to be awaited. Something like:</p>
<pre><code>var th = TaskCreator();
th.awaitFor(5000);
//do some work
var result = await th;
</code></pre>
<p>So how can an async task run for a given number of seconds?</p>
|
[
{
"answer_id": 74488418,
"author": "ProgrammingLlama",
"author_id": 3181933,
"author_profile": "https://Stackoverflow.com/users/3181933",
"pm_score": 4,
"selected": true,
"text": "WhenAny var th = TaskCreator();\nawait Task.WhenAny(Task.Delay(TimeSpan.FromSeconds(5)), th);\n//do some work\nvar result = await th;\n th TaskCreator await Task.Yield(); TaskCreator"
},
{
"answer_id": 74489118,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": false,
"text": "TaskCreator TaskCreator using var cs = new CancellationTokenSource();\ncs.CancelAfter(TimeSpan.FromSeconds(5));\nvar result = await TaskCreator(cs.Token);\n TaskCreator async Task<int> TaskCreator(CancellationToken cancellationToken)\n cancellationToken TaskCreator .ThrowIfCancellationRequested() .Register(...)"
},
{
"answer_id": 74492289,
"author": "Stephen Cleary",
"author_id": 263693,
"author_profile": "https://Stackoverflow.com/users/263693",
"pm_score": 2,
"selected": false,
"text": "WaitAsync var th = TaskCreator();\nvar result = await th.WaitAsync(TimeSpan.FromSeconds(5));\n WaitAsync WhenAny WaitAsync WhenAny"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1973207/"
] |
74,488,383
|
<p>I have a bash script <code>vault.sh</code></p>
<pre><code>az login
Source_Kv_Name="myKeyVault2020"
SECRETS+=($(az keyvault secret list --vault-name $Source_Kv_Name --query "[].id" -o tsv))
</code></pre>
<p>If I run it as <code>bash vault.sh</code> it fails to connect to vault (authenticate)</p>
<p>If I run the same commands from terminal, not the script, it works fine.
Why is happening, and how do I authenticate bash script to run the same?</p>
|
[
{
"answer_id": 74488418,
"author": "ProgrammingLlama",
"author_id": 3181933,
"author_profile": "https://Stackoverflow.com/users/3181933",
"pm_score": 4,
"selected": true,
"text": "WhenAny var th = TaskCreator();\nawait Task.WhenAny(Task.Delay(TimeSpan.FromSeconds(5)), th);\n//do some work\nvar result = await th;\n th TaskCreator await Task.Yield(); TaskCreator"
},
{
"answer_id": 74489118,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": false,
"text": "TaskCreator TaskCreator using var cs = new CancellationTokenSource();\ncs.CancelAfter(TimeSpan.FromSeconds(5));\nvar result = await TaskCreator(cs.Token);\n TaskCreator async Task<int> TaskCreator(CancellationToken cancellationToken)\n cancellationToken TaskCreator .ThrowIfCancellationRequested() .Register(...)"
},
{
"answer_id": 74492289,
"author": "Stephen Cleary",
"author_id": 263693,
"author_profile": "https://Stackoverflow.com/users/263693",
"pm_score": 2,
"selected": false,
"text": "WaitAsync var th = TaskCreator();\nvar result = await th.WaitAsync(TimeSpan.FromSeconds(5));\n WaitAsync WhenAny WaitAsync WhenAny"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6489386/"
] |
74,488,391
|
<p>I found a strange behavior when using the ROUND function with the third parameter to truncate a float number:</p>
<pre><code>declare @f2 float = 1.24;
select round(@f2, 2, 1)
</code></pre>
<p>Outputs:</p>
<pre><code>1.23
</code></pre>
<p>I am fully aware of the approximately nature of floating point types, but it doesn't seem correct for such a "simple" number.</p>
<p>Code run on:
Microsoft SQL Server 2019 (RTM-CU18) (KB5017593) - 15.0.4261.1 (X64) Sep 12 2022 15:07:06 Copyright (C) 2019 Microsoft Corporation Enterprise Edition: Core-based Licensing (64-bit) on Windows Server 2019 Standard 10.0 (Build 17763: )</p>
|
[
{
"answer_id": 74488645,
"author": "Ineffable21",
"author_id": 19733965,
"author_profile": "https://Stackoverflow.com/users/19733965",
"pm_score": 0,
"selected": false,
"text": "declare @f2 float = 1.24;\nselect round(@f2, 2)\n"
},
{
"answer_id": 74489619,
"author": "Eric Postpischil",
"author_id": 298225,
"author_profile": "https://Stackoverflow.com/users/298225",
"pm_score": 1,
"selected": false,
"text": "declare @f2 float = 1.24; 1.24 select round(@f2, 2, 1)"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9252578/"
] |
74,488,433
|
<p>I want to call a function inside Wrap content. My requirement is to call this function before the wrap content is loaded.</p>
<pre class="lang-dart prettyprint-override"><code> void checkFund(){}
Wrap(
children: entList
.map((element) => Padding(
padding: const EdgeInsets.only(left: 4.0, bottom: 5),
child: element['isAcq']
? Acquisition('${element['ele']}')
: element['isPartner']
? GestureDetector(
// onTap: () {
// print('partner');
// },
child: NewPartnerShip(
'${element['ele']}',
)
: element['isFunding']
?
Funding('${element['ele']??'NA'}',
))
.toList(),
)
</code></pre>
|
[
{
"answer_id": 74489005,
"author": "RobMac",
"author_id": 13091054,
"author_profile": "https://Stackoverflow.com/users/13091054",
"pm_score": 0,
"selected": false,
"text": "... \nchild: _myFancyWidget(),\n... \nWidget _myFancyWidget() {\n checkFund();\n return Wrap( ... );\n}\n...\nvoid checkFund(){}\n...\n"
},
{
"answer_id": 74515209,
"author": "laila nabil",
"author_id": 20449673,
"author_profile": "https://Stackoverflow.com/users/20449673",
"pm_score": 2,
"selected": true,
"text": "expression body => block body void checkFund(){}\n\n Wrap(\n children: entList\n .map((element) { \n checkFund();\n retrun Padding(\n \n padding: const EdgeInsets.only(left: 4.0, bottom: 5),\n \n child: element['isAcq']\n ? Acquisition('${element['ele']}')\n : element['isPartner']\n ? GestureDetector(\n // onTap: () {\n // print('partner');\n // },\n child: NewPartnerShip(\n '${element['ele']}',\n )\n : element['isFunding']\n ?\n Funding('${element['ele']??'NA'}',\n ))\n .toList(),\n );\n }\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11118094/"
] |
74,488,452
|
<p>been trying for a while something i want to do:</p>
<p>i have two different objects with same keyName and different values, i need to create a new array that will contain a new object with two entries, the values from the two objects with same key.</p>
<pre><code>enter code here
OBJ1{ keyNAME : 'lalala', toto: 'bbbb', tata: 'blablabla' }
OBJ2{ keyNAME : 18, toto: 7, tata: null }
// here something that i imagine could look similar to:
let newObjectKeys = ['title', 'value' ]
function createMyNewArray()=> {
let newArray = []
Use somehow OBJ1 and OBJ2, check the keys and create new array using
newObjectKeys
i think it might use Object.keys method but all i have tried i don't get to the
result i need so i'm defo missing something
}
return newArray;
console.log("new Array", newArray)
</code></pre>
<p>OUTPUT WOULD LOOK LIKE:</p>
<pre><code>const newArray =[
{
string: "lalala",
value: 18
},
{
string: 'bbbb',
value: 7,
},
{
string: 'blablabla'
value: null
},
....
];
</code></pre>
<p>and so then i can use it on my front side like this:</p>
<pre><code>
{newArray.map((item)=> return(
<div>
p {item.string}
p {item.value}
</div>
))}
</code></pre>
<p>thank you</p>
|
[
{
"answer_id": 74488603,
"author": "titouanbou",
"author_id": 9913759,
"author_profile": "https://Stackoverflow.com/users/9913759",
"pm_score": 0,
"selected": false,
"text": "OBJ3=[]\nObject.keys(OBJ1).forEach((key)=>OBJ3[OBJ1[key]]=OBJ2[key])\n"
},
{
"answer_id": 74488651,
"author": "Smytt",
"author_id": 8263781,
"author_profile": "https://Stackoverflow.com/users/8263781",
"pm_score": 2,
"selected": true,
"text": "OBJ1 = { key: 'lalala', toto: 'bbbb', tata: 'blablabla' }\n\nOBJ2 = { key: 18, toto: 7, tata: null }\n\nconst createArray = (obj1, obj2) =>\n Object.keys(obj1).map(key => ({\n string: obj1[key],\n value: obj2[key]\n }))\n\nconsole.log(createArray(OBJ1, OBJ2))"
},
{
"answer_id": 74488667,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 0,
"selected": false,
"text": " const [list] = React.useState({\n keyNAME: 'lalala',\n toto: 'bbbb',\n tata: 'blablabla',\n });\n const [list2] = React.useState({ keyNAME: 18, toto: 7, tata: null });\n\n const newList = React.useMemo(() => {\n return Object.keys(list).map((key, index) => {\n return {\n string: list[key],\n value: list2[key],\n };\n });\n }, [list, list2]);\n"
},
{
"answer_id": 74488701,
"author": "Azzy",
"author_id": 2122822,
"author_profile": "https://Stackoverflow.com/users/2122822",
"pm_score": 0,
"selected": false,
"text": "const OBJ1 = { keyNAME: \"lalala\", toto: \"bbbb\", tata: \"blablabla\" };\n\nconst OBJ2 = { keyNAME: 18, toto: 7, tata: null };\n\nconst createMyNewArray = (obj1, obj2) => {\n let newArray = [];\n\n for (const key in obj1) {\n if (key in obj2) {\n newArray.push({\n string: key,\n value: obj2[key]\n });\n }\n }\n return newArray;\n};\n\nconst transformed = createMyNewArray(OBJ1, OBJ2);\n\nconsole.log(transformed);\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15802715/"
] |
74,488,465
|
<p>'Missing Expression' for Select Distinct Query
<a href="https://i.stack.imgur.com/VtX6V.png" rel="nofollow noreferrer">the error sign</a></p>
<pre><code>CREATE OR REPLACE FORCE EDITIONABLE VIEW "KIR_V_KAS_MASUK_KET" ("...") as
SELECT
KMH.KODE_KAS,
KA.NIS,
KA.NAMA,
KA.KELAS,
KA.JURUSAN,
SELECT DISTINCT
(SELECT PERIODE FROM KIR_KAS_MASUK_HEAD WHERE KODE_KAS=:P16_KODE_KAS) PERIODE,
TO_CHAR((SELECT SUM(PEMBAYARAN) FROM KIR_KAS_MASUK_DETAIL WHERE KODE_KAS = :P16_KODE_KAS), '999,999,999') TOTAL_PEMBAYARAN,
TO_CHAR(WAJIB_BAYAR * (SELECT COUNT(*) FROM KIR_ANGGOTA WHERE STATUS != 'TIDAK AKTIF'), '999,999,999') TOTAL_WAJIB_BAYAR,
KMD.KETERANGAN
FROM
KIR_ANGGOTA KA,
KIR_KAS_MASUK_HEAD KMH,
KIR_KAS_MASUK_DETAIL KMD
WHERE
KMD.KODE_KAS=KMH.KODE_KAS
AND
KMD.NIS=KA.NIS
/
</code></pre>
<p>i wanted to make a view table with 9 column that 3 of those column are something that i think is the problem, because select distinct in a select query which is wrong but i really don't know the solution because i just add those 'select distinct' query without knowing anything that makes it wrong. I hope someone would correct me so that i can make <a href="https://i.stack.imgur.com/iHC7f.jpg" rel="nofollow noreferrer">the result i wanted to create using the view table query</a> in my app</p>
|
[
{
"answer_id": 74488571,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 2,
"selected": false,
"text": "create view ... as\nselect DISTINCT kmh.kode_kas, ... --> DISTINCT goes here\n (select periode from ... ) periode,\n (select to_char(sum(pembayaran, '999,999,999)) from ...) total_pembayaran\nfrom kir_anggota ka, ...\nwhere ...\n periode total_pembayaran where"
},
{
"answer_id": 74490882,
"author": "Koen Lostrie",
"author_id": 4189814,
"author_profile": "https://Stackoverflow.com/users/4189814",
"pm_score": 1,
"selected": true,
"text": "CREATE OR REPLACE FORCE EDITIONABLE VIEW \"KIR_V_KAS_MASUK_KET\" (\"...\") as\n SELECT\nKMH.KODE_KAS,\nKA.NIS,\nKA.NAMA,\nKA.KELAS,\nKA.JURUSAN,\n(SELECT DISTINCT PERIODE FROM KIR_KAS_MASUK_HEAD WHERE KODE_KAS=v('P16_KODE_KAS')) PERIODE,\n(SELECT DISTINCT TO_CHAR((SELECT SUM(PEMBAYARAN) FROM KIR_KAS_MASUK_DETAIL WHERE KODE_KAS = v('P16_KODE_KAS')), '999,999,999') TOTAL_PEMBAYARAN,\n(SELECT DISTINCT TO_CHAR(WAJIB_BAYAR * (SELECT COUNT(*) FROM KIR_ANGGOTA WHERE STATUS != 'TIDAK AKTIF'), '999,999,999') TOTAL_WAJIB_BAYAR,\nKMD.KETERANGAN\nFROM\nKIR_ANGGOTA KA\n JOIN KIR_KAS_MASUK_DETAIL KDM ON KMD.NIS=KA.NIS\n JOIN KIR_KAS_MASUK_HEAD KMH ON KMD.KODE_KAS=KMH.KODE_KAS\n/\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20429504/"
] |
74,488,479
|
<p>I would like to split a tensor into several tensors with torch on Python.
The tensor is the tokenization of a long text.</p>
<p>First here is what I had done:</p>
<pre><code>tensor = tensor([[ 3746, 3120, 1024, ..., 2655, 24051, 2015]]) #size 14714
result = tensor.split(510)
</code></pre>
<p>It works but now I would like to refine this, and make it so that it can't split in the middle of a sentence but at the <strong>end of a sentence</strong>, so recognizing the dot '.' (token 1012). Of course all the tensor will not be the same size but will have to respect a <strong>maximum size</strong> (510 for example).</p>
<p>Thanks for your help</p>
|
[
{
"answer_id": 74488571,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 2,
"selected": false,
"text": "create view ... as\nselect DISTINCT kmh.kode_kas, ... --> DISTINCT goes here\n (select periode from ... ) periode,\n (select to_char(sum(pembayaran, '999,999,999)) from ...) total_pembayaran\nfrom kir_anggota ka, ...\nwhere ...\n periode total_pembayaran where"
},
{
"answer_id": 74490882,
"author": "Koen Lostrie",
"author_id": 4189814,
"author_profile": "https://Stackoverflow.com/users/4189814",
"pm_score": 1,
"selected": true,
"text": "CREATE OR REPLACE FORCE EDITIONABLE VIEW \"KIR_V_KAS_MASUK_KET\" (\"...\") as\n SELECT\nKMH.KODE_KAS,\nKA.NIS,\nKA.NAMA,\nKA.KELAS,\nKA.JURUSAN,\n(SELECT DISTINCT PERIODE FROM KIR_KAS_MASUK_HEAD WHERE KODE_KAS=v('P16_KODE_KAS')) PERIODE,\n(SELECT DISTINCT TO_CHAR((SELECT SUM(PEMBAYARAN) FROM KIR_KAS_MASUK_DETAIL WHERE KODE_KAS = v('P16_KODE_KAS')), '999,999,999') TOTAL_PEMBAYARAN,\n(SELECT DISTINCT TO_CHAR(WAJIB_BAYAR * (SELECT COUNT(*) FROM KIR_ANGGOTA WHERE STATUS != 'TIDAK AKTIF'), '999,999,999') TOTAL_WAJIB_BAYAR,\nKMD.KETERANGAN\nFROM\nKIR_ANGGOTA KA\n JOIN KIR_KAS_MASUK_DETAIL KDM ON KMD.NIS=KA.NIS\n JOIN KIR_KAS_MASUK_HEAD KMH ON KMD.KODE_KAS=KMH.KODE_KAS\n/\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14022403/"
] |
74,488,521
|
<p>I have two unordered lists inside a div with a known class. I need to change the list items in the first list to spans with the class "time". Next I would like to change the second list items to spans with the class "frequency". Finally I would like to remove the <code><ul></code> tags leaving only the spans behind in the div. Just like:</p>
<pre><code><div id="training-labels">
<ul>
<li>30 mins</li>
</ul>
<ul>
<li>Annually</li>
<li>First 2 weeks</li>
</ul>
</div>
</code></pre>
<p>to this</p>
<pre><code><span class="time">30 mins</span>
<span class="frequency">Annually</span>
<span class="frequency">First 2 weeks</span>
</code></pre>
<p>I have managed to change the contents of each list into spans:</p>
<pre><code>$('#training-labels ul:nth-of-type(1) li').wrapInner('<span class="time" />').contents();
$('#training-labels ul:nth-of-type(2) li').wrapInner('<span class="frequency" />').contents();
</code></pre>
<p>But have not been successful stripping out the ul and li tags, leaving only the spans behind.</p>
<p>Is this the best approach or is there a better way to achieve this with JQuery?</p>
<p>I have set up a <a href="https://jsfiddle.net/t7ex2gj0/" rel="nofollow noreferrer">Fiddle here</a></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>$('#training-labels ul:nth-of-type(1) li').wrapInner('<span class="time" />').contents();
$('#training-labels ul:nth-of-type(2) li').wrapInner('<span class="frequency" />').contents();</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.time {
color: green;
}
.frequency {
color: red;
}</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>
<div id="training-labels">
<ul>
<li>30 mins</li>
</ul>
<ul>
<li>Annually</li>
<li>First 2 weeks</li>
</ul>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74488628,
"author": "S M Samnoon Abrar",
"author_id": 8188682,
"author_profile": "https://Stackoverflow.com/users/8188682",
"pm_score": 3,
"selected": true,
"text": "$('#training-labels ul:nth-of-type(1) li').wrap('<span class=\"time\"/>').contents().unwrap();\n\n$('#training-labels ul:nth-of-type(2) li').wrap('<span class=\"frequency\"/>').contents().unwrap();\n\n$('#training-labels ul:nth-of-type(1) span').unwrap();\n$('#training-labels ul:nth-of-type(1) span').unwrap();\n\n .time {\n color: green;\n}\n\n.frequency {\n color: red;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<div id=\"training-labels\">\n <ul>\n <li>30 mins</li>\n </ul>\n\n <ul>\n <li>Annually</li>\n <li>First 2 weeks</li>\n </ul>\n</div> wrap() unwrap() training-labels"
},
{
"answer_id": 74488844,
"author": "mplungjan",
"author_id": 295783,
"author_profile": "https://Stackoverflow.com/users/295783",
"pm_score": 2,
"selected": false,
"text": "const $div = $('#training-labels');\nconst $uls = $('ul', $div); // save\n$div.empty(); // clear\n$uls.each(function(i, ul) {\n $(\"li\", ul).each(function(j, li) {\n $(`<span class=\"${i===0 ? \"time\" : \"frequency\" }\">${li.textContent}</span><br/>`)\n .appendTo($div)\n });\n}); .time {\n color: green;\n}\n\n.frequency {\n color: red;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<div id=\"training-labels\">\n <ul>\n <li>30 mins</li>\n </ul>\n <ul>\n <li>Annually</li>\n <li>First 2 weeks</li>\n </ul>\n</div> const $div = $('#training-labels')\n$('ul:nth-of-type(1) li', $div).wrapInner('<span class=\"time\" />').contents();\n$('ul:nth-of-type(2) li', $div).wrapInner('<span class=\"frequency\" />').contents();\n$div.html(function() { \n return $div.find(\"span\")\n .map(function() { return this.outerHTML })\n .get()\n .join(\"<br/>\"); // or space or something else\n}); .time {\n color: green;\n}\n\n.frequency {\n color: red;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<div id=\"training-labels\">\n <ul>\n <li>30 mins</li>\n </ul>\n <ul>\n <li>Annually</li>\n <li>First 2 weeks</li>\n </ul>\n</div>"
},
{
"answer_id": 74489258,
"author": "sorpigal",
"author_id": 180736,
"author_profile": "https://Stackoverflow.com/users/180736",
"pm_score": 0,
"selected": false,
"text": "let $div = $('#training-labels');\nlet $time = $('ul:nth-of-type(1) li', $div).clone().wrapInner('<span class=\"time\" />').contents();\nlet $freq = $('ul:nth-of-type(2) li', $div).clone().wrapInner('<span class=\"frequency\" />').contents();\n$div.replaceWith($().add($time).add($freq));\n unwrap clone"
},
{
"answer_id": 74519859,
"author": "David Thomas",
"author_id": 82548,
"author_profile": "https://Stackoverflow.com/users/82548",
"pm_score": 0,
"selected": false,
"text": "/* a simple reset to remove default font-sizes, box-sizing, margins and padding: */\n*, ::before, ::after {\n box-sizing: border-box;\n font-family: system-ui;\n font-size: 16px;\n margin: 0;\n padding: 0;\n}\n\n/* removing default list-markers from the <li> elements: */\nul {\n list-style-type: none;\n}\n\n/* wrapping the outer <div> elements which wrap your <ul>\n elements in a <main> element in order to style and\n align the content; this is unnecessary for the demo\n functionality: */\nmain {\n /* taking advantage of grid display to position items on\n the vertical (block) axis: */\n display: grid;\n /* separating tracks with a 'gutter': */\n gap: 1em;\n /* defining the inline-size - the size of the element\n along the inline-axis (horizontal in most latin-\n derived languages, such as French, English...): */\n inline-size: clamp(15rem, 70vw, 1100px);\n /* a 1em margin before the start of the element on its\n block axis (perpendicular to the inline axis,\n vertical in most Latin-derived languages): */\n margin-block-start: 1em;\n /* using margins to centre the element: */\n margin-inline: auto;\n}\n\n/* default styles for the .content elements (the class-name\n given to the <div> elements which wrap the <ul> elements:*/\n.content {\n border: 2px solid var(--color, currentColor);\n padding: 0.5em;\n}\n\n/* styling the <li> elements as inline-block; which allows them\n to flow inline but take a specified size (inline or block),\n and margins: */\n#inlineBlock li {\n display: inline-block;\n}\n\n/* using flex layout on the <ul> elements, which positions the\n <li> children along the inline-axis (by default) while allowing\n them to be sized according to their content or declaration: */\n#flex ul {\n display: flex;\n}\n\n/* this was posted purely for the sake of completeness, and I don't\n recommend it since the track sizing looks more tabular than\n is possibly required: */\n#grid {\n display: grid;\n /* this defines two columns with each column sized to fit the\n content within: */\n grid-template-columns: repeat(2, fit-content);\n}\n\n#grid ul {\n /* we use this to effectively pretend the <ul> elements don't\n exist, to allow the <li> elements to be placed into the\n grid rather than the <ul> elements: */\n display: contents;\n}\n\n/* because each row/column track of a grid has an equal number of\n divisions/\"cells\", and because we're pretending (display: contents)\n that the <ul> elements don't exist, this is to ensure that\n the <li> contents of the second <ul> don't fill the first row track;\n this can be adjusted if you'd prefer that to happen, but I didn't\n expect that it's required: */\n#grid li:only-child {\n grid-column: span 2;\n}\n\n/* going back to the land before time, we use a simple floats to\n allow the <li> elements to run inline: */\n#float li {\n float: left;\n}\n\n/* to ensure the first <li> always starts on a new line: */\n#float li:first-child {\n clear: left;\n}\n\n/* selecting all <li> elements that are not the :first-child,\n contained within a <div> that does not have an id of \"grid\": */\n.content:is(:not(#grid)) li:not(:first-child)::before {\n /* placing a comma before those elelements: */\n content: \", \";\n}\n\n/* selecting the :last-child <li> descendant of .content elements\n (which do not have the id of \"grid\"), and styling their ::after\n pseudo-element: */\n.content:is(:not(#grid)) li:last-child::after {\n /* adding a full-stop/period: */\n content: '.';\n}\n\n/* styling the ::after pseudo-element of an <li> which is the :only-child\n of its parent, and within a .content element without the id of \"grid\": */\n.content:is(:not(#grid)) li:only-child::after {\n /* adding a colon after the text of the element: */\n content: ': ';\n} <main>\n <div id=\"inlineBlock\" class=\"content\" style=\"--color: hsl(120deg 80% 70% / 1)\">\n <ul>\n <li>30 mins</li>\n </ul>\n\n <ul>\n <li>Annually</li>\n <li>First 2 weeks</li>\n </ul>\n </div>\n \n <div id=\"flex\" class=\"content\" style=\"--color: hsl(160deg 80% 70% / 1)\">\n <ul>\n <li>30 mins</li>\n </ul>\n\n <ul>\n <li>Annually</li>\n <li>First 2 weeks</li>\n </ul>\n </div>\n \n <div id=\"grid\" class=\"content\" style=\"--color: hsl(200deg 80% 70% / 1)\">\n <ul>\n <li>30 mins</li>\n </ul>\n\n <ul>\n <li>Annually</li>\n <li>First 2 weeks</li>\n </ul>\n </div>\n \n <div id=\"float\" class=\"content\" style=\"--color: hsl(240deg 80% 70% / 1)\">\n <ul>\n <li>30 mins</li>\n </ul>\n\n <ul>\n <li>Annually</li>\n <li>First 2 weeks</li>\n </ul>\n </div>\n</main> ::after ::before block-size border clamp() content display font-family font-size gap grid-column grid-template-columns inline-size :is() :last-child list-style-type margin-block margin-inline :not() :only-child padding repeat() var() :where()"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5444988/"
] |
74,488,552
|
<p>in my project i am using cypress with plain javascript. i am facing the challenge of importing the modules (page objects) via aliases instead of spaghetti code like <code>../../../../folder/page.js</code>.
I <strong>don't</strong> use <code>typescript</code> or <code>react.js</code> and <strong>don't</strong> have a <code>src</code> folder/directory.</p>
<p>my tests run locally in the browser or via a docker image (pipeline).</p>
<p>I would like to transform from this:</p>
<p><code>import { LoginPage } from "../../pages/loginPage.js";</code></p>
<p>to something like this:</p>
<p><code>import { LoginPage } from "@Pages/loginPage.js";</code></p>
<p>but I always get an error:</p>
<pre><code>Error: Webpack Compilation Error
./cypress/e2e/accountOverview/accountOverviewPageTest.spec.js
Module not found: Error: Can't resolve 'Pages/loginPage.js' in 'C:\Users\User\automated_frontend_tests\automated_frontend_tests\cypress\e2e\accountOverview'
resolve 'Pages/loginPage.js' in 'C:\Users\User\automated_frontend_tests\automated_frontend_tests\cypress\e2e\accountOverview'
Parsed request is a module
using description file: C:\Users\User\automated_frontend_tests\automated_frontend_tests\package.json (relative path: ./cypress/e2e/accountOverview)
Field 'browser' doesn't contain a valid alias configuration
Looked for and couldn't find the file at the following paths:
[C:\Users\User\automated_frontend_tests\automated_frontend_tests\cypress\e2e\accountOverview\node_modules]
[C:\Users\User\automated_frontend_tests\automated_frontend_tests\cypress\e2e\node_modules]
[C:\Users\User\automated_frontend_tests\automated_frontend_tests\cypress\node_modules]
[C:\Users\node_modules]
[C:\node_modules]
[C:\Users\User\automated_frontend_tests\automated_frontend_tests\node_modules\Pages\loginPage.js]
[C:\Users\User\automated_frontend_tests\node_modules\Pages\loginPage.js]
[C:\Users\User\node_modules\Pages\loginPage.js]
[C:\Users\User\automated_frontend_tests\automated_frontend_tests\node_modules\Pages\loginPage.js.js]
[C:\Users\User\automated_frontend_tests\node_modules\Pages\loginPage.js.js]
[C:\Users\User\node_modules\Pages\loginPage.js.js]
[C:\Users\User\automated_frontend_tests\automated_frontend_tests\node_modules\Pages\loginPage.js.json]
[C:\Users\User\automated_frontend_tests\node_modules\Pages\loginPage.js.json]
[C:\Users\User\node_modules\Pages\loginPage.js.json]
[C:\Users\User\automated_frontend_tests\automated_frontend_tests\node_modules\Pages\loginPage.js.jsx]
[C:\Users\User\automated_frontend_tests\node_modules\Pages\loginPage.js.jsx]
[C:\Users\User\node_modules\Pages\loginPage.js.jsx]
[C:\Users\User\automated_frontend_tests\automated_frontend_tests\node_modules\Pages\loginPage.js.mjs]
[C:\Users\User\automated_frontend_tests\node_modules\Pages\loginPage.js.mjs]
[C:\Users\User\node_modules\Pages\loginPage.js.mjs]
[C:\Users\User\automated_frontend_tests\automated_frontend_tests\node_modules\Pages\loginPage.js.coffee]
[C:\Users\User\automated_frontend_tests\node_modules\Pages\loginPage.js.coffee]
[C:\Users\User\node_modules\Pages\loginPage.js.coffee]
@ ./cypress/e2e/accountOverview/accountOverviewPageTest.spec.js 5:17-46
</code></pre>
<p>I have tried several solutions, including:</p>
<pre><code>//webpack.config.js
module.exports = {
resolve: {
alias: {
"@pages": path.resolve(__dirname, "cypress/pages/*"),
},
},
};
//testspec file
import { LoginPage } from "@pages/loginPage.js";
const loginPage = new LoginPage();
</code></pre>
<p>@Uzair Khan:
I tried your solution, but it still didn't work. The error message remains the same. It seems that the IDE does not search in the correct folder, but only in <code>...\node_modules\@page\loginPage.js</code> which makes no sense.
If I enter <code>const loginPage = new LoginPage()</code>, the module <code>LoginPage()</code> cannot be found by the IDE either. Something is wrong with the solution. Do I still have to install any packages via <code>NPM</code>?</p>
|
[
{
"answer_id": 74491050,
"author": "Uzair Khan",
"author_id": 17601619,
"author_profile": "https://Stackoverflow.com/users/17601619",
"pm_score": 0,
"selected": false,
"text": "webpack.config.js resolve.alias resolve: {\n alias: {\n '@page': path.resolve(__dirname, '{path you want to make alias}')\n }\n}\n cypress.config.js cypress.config.js import { defineConfig } from 'cypress'\nimport webpack from '@cypress/webpack-preprocessor'\nimport preprocessor from '@badeball/cypress-cucumber-preprocessor'\nimport path from 'path'\n\nexport async function setupNodeEvents (on, config) {\n // This is required for the preprocessor to be able to generate JSON reports after each run, and more,\n await preprocessor.addCucumberPreprocessorPlugin(on, config)\n\n on(\n 'file:preprocessor',\n webpack({\n webpackOptions: {\n resolve: {\n extensions: ['.ts', '.js', '.mjs'],\n alias: {\n '@page': path.resolve('cypress/support/pages/')\n }\n },\n module: {\n rules: [\n {\n test: /\\.feature$/,\n use: [\n {\n loader: '@badeball/cypress-cucumber-preprocessor/webpack',\n options: config\n }\n ]\n }\n ]\n }\n }\n })\n )\n\n // Make sure to return the config object as it might have been modified by the plugin.\n return config\n}\n cypress.config.js import page from '@page/visit.js'\n\nconst visit = new page()\n\nWhen('I visit duckduckgo.com', () => {\n visit.page()\n})\n"
},
{
"answer_id": 74524346,
"author": "TesterDick",
"author_id": 18366749,
"author_profile": "https://Stackoverflow.com/users/18366749",
"pm_score": 1,
"selected": false,
"text": "src const webpack = require('@cypress/webpack-preprocessor')\n...\nmodule.exports = defineConfig({\n ...\n e2e: {\n setupNodeEvents(on, config) {\n ...\n // @src alias\n const options = {\n webpackOptions: { \n resolve: { \n alias: { \n '@src': path.resolve(__dirname, './src') \n }, \n }, \n }, \n watchOptions: {},\n }\n on('file:preprocessor', webpack(options))\n ...\n path.resolve() ./ ../ * module.exports = defineConfig({\n ...\n e2e: {\n setupNodeEvents(on, config) {\n const pagesFolder = path.resolve(__dirname, './cypress/pages')\n console.log('pagesFolder', pagesFolder)\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20206511/"
] |
74,488,560
|
<p>When I write a Mojo, how can I determine whether I am currently in Batch Mode (i.e. the <code>-B</code> parameter was given on command line)?</p>
|
[
{
"answer_id": 74488695,
"author": "Mark Bramnik",
"author_id": 605153,
"author_profile": "https://Stackoverflow.com/users/605153",
"pm_score": 1,
"selected": false,
"text": "generate /**\n * User settings used to check the interactiveMode.\n */\n @Parameter( property = \"interactiveMode\", defaultValue = \"${settings.interactiveMode}\", required = true )\n private Boolean interactiveMode;\n if ( interactiveMode.booleanValue() )\n {\n getLog().info( \"Generating project in Interactive mode\" );\n }\n else\n {\n getLog().info( \"Generating project in Batch mode\" );\n }\n"
},
{
"answer_id": 74489156,
"author": "khmarbaise",
"author_id": 296328,
"author_profile": "https://Stackoverflow.com/users/296328",
"pm_score": 3,
"selected": true,
"text": " @Parameter(defaultValue = \"${session}\", required = true, readonly = true)\n private MavenSession session;\n if (session.getRequest().isInteractiveMode()) {\n //..\n } else {\n //..\n }\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/927493/"
] |
74,488,562
|
<p>I want to check if items in array existed and add new values from another array without overwriting element after reloading. I created such code:</p>
<pre><code>//take from that array
List<int> list = [2, 3, 5];
// add to this array and check if this array already has the same element or not
List<int> newValueInt = [2, 6, 7];
list.forEach((item) {
if(!list.contains(item)){
newValueInt.add(item);
print(newValueInt);
}
});
</code></pre>
<p>and it shows me that print:</p>
<pre><code> [2, 6, 7, 3]
[2, 6, 7, 3, 5]
</code></pre>
|
[
{
"answer_id": 74488695,
"author": "Mark Bramnik",
"author_id": 605153,
"author_profile": "https://Stackoverflow.com/users/605153",
"pm_score": 1,
"selected": false,
"text": "generate /**\n * User settings used to check the interactiveMode.\n */\n @Parameter( property = \"interactiveMode\", defaultValue = \"${settings.interactiveMode}\", required = true )\n private Boolean interactiveMode;\n if ( interactiveMode.booleanValue() )\n {\n getLog().info( \"Generating project in Interactive mode\" );\n }\n else\n {\n getLog().info( \"Generating project in Batch mode\" );\n }\n"
},
{
"answer_id": 74489156,
"author": "khmarbaise",
"author_id": 296328,
"author_profile": "https://Stackoverflow.com/users/296328",
"pm_score": 3,
"selected": true,
"text": " @Parameter(defaultValue = \"${session}\", required = true, readonly = true)\n private MavenSession session;\n if (session.getRequest().isInteractiveMode()) {\n //..\n } else {\n //..\n }\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16357470/"
] |
74,488,581
|
<p>I have the following function :
`</p>
<pre><code>def file(DOCname,TABLEid):
directory = DOCname
parent_dir = "E:\\Tables\\Documents\\"+TABLEid
path = os.path.join(parent_dir, directory)
try:
os.makedirs(path, exist_ok = True)
print("Directory '%s' created successfully" % directory)
except OSError as error:
print("Directory '%s' can not be created" % directory)
</code></pre>
<p>`</p>
<p>Now I want to use a Flask API and call this function to run with two variables that I will provide via Postman, DOCname and TABLEid, but I'm not sure how to run this at the same time I make an API call ?</p>
<p>I tried to run the file under a post request but nothing seems to happen.</p>
|
[
{
"answer_id": 74488695,
"author": "Mark Bramnik",
"author_id": 605153,
"author_profile": "https://Stackoverflow.com/users/605153",
"pm_score": 1,
"selected": false,
"text": "generate /**\n * User settings used to check the interactiveMode.\n */\n @Parameter( property = \"interactiveMode\", defaultValue = \"${settings.interactiveMode}\", required = true )\n private Boolean interactiveMode;\n if ( interactiveMode.booleanValue() )\n {\n getLog().info( \"Generating project in Interactive mode\" );\n }\n else\n {\n getLog().info( \"Generating project in Batch mode\" );\n }\n"
},
{
"answer_id": 74489156,
"author": "khmarbaise",
"author_id": 296328,
"author_profile": "https://Stackoverflow.com/users/296328",
"pm_score": 3,
"selected": true,
"text": " @Parameter(defaultValue = \"${session}\", required = true, readonly = true)\n private MavenSession session;\n if (session.getRequest().isInteractiveMode()) {\n //..\n } else {\n //..\n }\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20538757/"
] |
74,488,587
|
<p>In latex, I need to start an item in an enumerate list with an align* environment, but this environment starts with a new line, leaving an ugly empty space.</p>
<p>What I'm trying to achieve:</p>
<ol>
<li><p>e^{ix}=cos x+i sin x</p>
<p>e^{i\pi} = -1</p>
<p>e^{i\pi}+1=0</p>
</li>
</ol>
<p>What I'm trying:</p>
<pre><code>\begin{enumerate}
\item \begin{align*}
e^{ix}&=\cos x+i\sin x\\
e^{i\pi}&=-1\\
e^{i\pi}+1&=0
\end{align*}
\end{enumerate}
</code></pre>
<p>Is there some other environment for this?</p>
<p>(I know that it is not recommended to start an item with a displayed math formula, but in this case I need to.)</p>
|
[
{
"answer_id": 74488695,
"author": "Mark Bramnik",
"author_id": 605153,
"author_profile": "https://Stackoverflow.com/users/605153",
"pm_score": 1,
"selected": false,
"text": "generate /**\n * User settings used to check the interactiveMode.\n */\n @Parameter( property = \"interactiveMode\", defaultValue = \"${settings.interactiveMode}\", required = true )\n private Boolean interactiveMode;\n if ( interactiveMode.booleanValue() )\n {\n getLog().info( \"Generating project in Interactive mode\" );\n }\n else\n {\n getLog().info( \"Generating project in Batch mode\" );\n }\n"
},
{
"answer_id": 74489156,
"author": "khmarbaise",
"author_id": 296328,
"author_profile": "https://Stackoverflow.com/users/296328",
"pm_score": 3,
"selected": true,
"text": " @Parameter(defaultValue = \"${session}\", required = true, readonly = true)\n private MavenSession session;\n if (session.getRequest().isInteractiveMode()) {\n //..\n } else {\n //..\n }\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4230918/"
] |
74,488,607
|
<p>How do I convert an Enum to a Constant Class like this, in Typescript? Currently using React Typescript, with functional components .
This question is slightly different: <a href="https://stackoverflow.com/questions/43100718/typescript-enum-to-object-array">TypeScript enum to object array</a></p>
<pre><code>export enum ProductStatus {
Draft = 1,
Review = 2,
Approved = 3,
Rejected = 4,
Billed = 5,
Collected = 6,
Unpayable = 7,
WorkInProgress = 8,
ReadyToReview = 9,
NeedsRevision = 10,
Failed = 11,
}
export const ProductStatus = {
Draft: 1,
Review: 2,
Approved: 3,
Rejected: 4,
Billed: 5,
Collected: 6,
Unpayable: 7,
WorkInProgress: 8,
ReadyToReview: 9,
NeedsRevision: 10,
Failed: 11,
};
</code></pre>
|
[
{
"answer_id": 74488695,
"author": "Mark Bramnik",
"author_id": 605153,
"author_profile": "https://Stackoverflow.com/users/605153",
"pm_score": 1,
"selected": false,
"text": "generate /**\n * User settings used to check the interactiveMode.\n */\n @Parameter( property = \"interactiveMode\", defaultValue = \"${settings.interactiveMode}\", required = true )\n private Boolean interactiveMode;\n if ( interactiveMode.booleanValue() )\n {\n getLog().info( \"Generating project in Interactive mode\" );\n }\n else\n {\n getLog().info( \"Generating project in Batch mode\" );\n }\n"
},
{
"answer_id": 74489156,
"author": "khmarbaise",
"author_id": 296328,
"author_profile": "https://Stackoverflow.com/users/296328",
"pm_score": 3,
"selected": true,
"text": " @Parameter(defaultValue = \"${session}\", required = true, readonly = true)\n private MavenSession session;\n if (session.getRequest().isInteractiveMode()) {\n //..\n } else {\n //..\n }\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15435022/"
] |
74,488,608
|
<p>As part of my build process I want to run a dotnet tool before the compile.</p>
<p>I can add this section to my sdk project file:</p>
<pre><code> <ItemGroup>
<PackageDownload Include="MyTool" Version="[1.0.1]" />
</ItemGroup>
</code></pre>
<p>Then the tool is downloaded and is available inside:</p>
<pre><code> \Users\me\.nuget\packages\MyTool\1.0.1\tools\netcoreapp3.1\any\
</code></pre>
<p>I can then add a prebuild target like this:</p>
<pre><code> <Target Name="PreBuild" BeforeTargets="CoreCompile">
<Exec Command="dotnet C:\Users\me\.nuget\packages\MyTool\1.0.1\tools\netcoreapp3.1\any\MyTool.dll <MyOptions> />
</Target>
</code></pre>
<p>This works, but obviously I do not want absolute references to my user profile (or version) in the path.</p>
<p>Is there a way to substitute path with an environment variable?</p>
<p>I have tried adding <code>GeneratePathProperty="true"</code> to the PackageDownload but $(PkgMyTool) is undefined.</p>
<p>I also tried referencing the tool with <code><PackageReference></code> but this fails due to SDK incompatibility. My Tool is netcore3.1 and this project is netstandard2.0.</p>
|
[
{
"answer_id": 74488695,
"author": "Mark Bramnik",
"author_id": 605153,
"author_profile": "https://Stackoverflow.com/users/605153",
"pm_score": 1,
"selected": false,
"text": "generate /**\n * User settings used to check the interactiveMode.\n */\n @Parameter( property = \"interactiveMode\", defaultValue = \"${settings.interactiveMode}\", required = true )\n private Boolean interactiveMode;\n if ( interactiveMode.booleanValue() )\n {\n getLog().info( \"Generating project in Interactive mode\" );\n }\n else\n {\n getLog().info( \"Generating project in Batch mode\" );\n }\n"
},
{
"answer_id": 74489156,
"author": "khmarbaise",
"author_id": 296328,
"author_profile": "https://Stackoverflow.com/users/296328",
"pm_score": 3,
"selected": true,
"text": " @Parameter(defaultValue = \"${session}\", required = true, readonly = true)\n private MavenSession session;\n if (session.getRequest().isInteractiveMode()) {\n //..\n } else {\n //..\n }\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/304820/"
] |
74,488,619
|
<p>I'm using <a href="https://tanstack.com/query/v4/" rel="nofollow noreferrer">react-query 4</a> to get some data from my server via JSON:API and create some objects:</p>
<pre><code>export type QueryReturnQueue = QueueObject[] | false;
const getQueryQueue = async (query: string): Promise<QueryReturnQueue> => {
const data = await fetchAuth(query);
const returnData = [] as QueueObject[];
if (data) {
data.map((queueItem) => returnData.push(new QueueObject(queueItem)));
return returnData;
}
return false;
};
function useMyQueue(
queueType: QueueType,
): UseQueryResult<QueryReturnQueue, Error> {
const queryKey = ['getQueue', queueType];
return useQuery<QueryReturnQueue, Error>(
queryKey,
async () => {
const query = getUrl(queueType);
return getQueryQueue(query);
},
);
}
</code></pre>
<p>Then I have a component that displays the objects one at a time and the user is asked to make a choice (for example, "swipe left" or "swipe right"). This queue only goes in one direction-- the user sees a queueObject, processes the object, and then goes to the next one. The user cannot go back to a previous object, and the user cannot skip ahead.</p>
<p>So far, I've been using <code>useContext()</code> to track the index in the queue as state. However, I've been running into several bugs with this when the queue gets refreshed, which happens a lot, so I thought it would be easier to directly manipulate the data returned by <code>useQuery()</code>.</p>
<p>How can I remove items as they are processed from the locally cached query results?</p>
<p>My current flow:</p>
<ul>
<li>Fetch the queue data and generation objects with <code>useQuery()</code>.</li>
<li>Display the queue objects one at a time using <code>useContext()</code>.</li>
<li>Mutate the displayed object with <code>useMutation()</code> to modify <code>useContext()</code> and then show the next object in the cached data from <code>useQuery()</code>.</li>
</ul>
<p>My desired flow:</p>
<ul>
<li>Fetch the queue data and generation objects with <code>useQuery()</code>.</li>
<li>Mutate the displayed object with <code>useMutation()</code>, somehow removing the mutated item from the cached data from <code>useQuery()</code> (like what <code>shift()</code> does for arrays).</li>
</ul>
<p>Sources I consulted</p>
<ul>
<li><a href="https://github.com/TanStack/query/discussions/530" rel="nofollow noreferrer">Best practices for editing data after useQuery call</a> (couldn't find an answer relevant to my case)</li>
<li><a href="https://tanstack.com/query/v4/docs/guides/optimistic-updates" rel="nofollow noreferrer">Optimistic updates</a> (don't know how to apply it to my case)</li>
</ul>
|
[
{
"answer_id": 74488695,
"author": "Mark Bramnik",
"author_id": 605153,
"author_profile": "https://Stackoverflow.com/users/605153",
"pm_score": 1,
"selected": false,
"text": "generate /**\n * User settings used to check the interactiveMode.\n */\n @Parameter( property = \"interactiveMode\", defaultValue = \"${settings.interactiveMode}\", required = true )\n private Boolean interactiveMode;\n if ( interactiveMode.booleanValue() )\n {\n getLog().info( \"Generating project in Interactive mode\" );\n }\n else\n {\n getLog().info( \"Generating project in Batch mode\" );\n }\n"
},
{
"answer_id": 74489156,
"author": "khmarbaise",
"author_id": 296328,
"author_profile": "https://Stackoverflow.com/users/296328",
"pm_score": 3,
"selected": true,
"text": " @Parameter(defaultValue = \"${session}\", required = true, readonly = true)\n private MavenSession session;\n if (session.getRequest().isInteractiveMode()) {\n //..\n } else {\n //..\n }\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1209486/"
] |
74,488,659
|
<p>I want to copy a video file from a remote server to my localhost , so I have:</p>
<pre><code>const ftp = require("basic-ftp");
const path = 'C:\inetpub\wwwroot\Server\views\admin\files\session\trimed\oblivin.mp4';
example()
async function example() {
const client = new ftp.Client()
client.ftp.verbose = true
try {
await client.access({
host: "****",
user: "****",
password: "****",
secure: false
});
await client.ensureDir("movies");
console.log(await client.list());
await client.downloadTo(path, "oblivin.mp4");
}
catch (err) {
console.log(err)
}
client.close()
}
</code></pre>
<p>But it just create a file with 0 mb of size in local!</p>
<p>How to fix this?</p>
|
[
{
"answer_id": 74488949,
"author": "AAKASH9820",
"author_id": 12124280,
"author_profile": "https://Stackoverflow.com/users/12124280",
"pm_score": -1,
"selected": false,
"text": "fetch('C:\\inetpub\\wwwroot\\Server\\views\\admin\\files\\session\\trimed\\oblivin.mp4').then(resp => resp.blob()).then(blob => {\nconst url = window.URL.createObjectURL(blob);\nconst a = document.createElement('a');\na.style.display = 'none';\na.href = url;\n// change the filename as you want to download\na.download = 'todo-1.json';\ndocument.body.appendChild(a);\na.click();\nwindow.URL.revokeObjectURL(url);\nalert('your file has downloaded!'); }).catch(() => alert('Error occurred!'));\n"
},
{
"answer_id": 74556174,
"author": "AAKASH9820",
"author_id": 12124280,
"author_profile": "https://Stackoverflow.com/users/12124280",
"pm_score": 1,
"selected": false,
"text": "<?php // define some variables \n $local_file = 'myfile.zip'; // local path\n $server_file = 'server.zip'; // Server file \n // set up basic connection \n $conn_id = ftp_connect($ftp_server); // ftp host\n // login with username and password \n $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); \n // try to download $server_file and save to $local_file \n if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) \n { \n echo \"Successfully written to $local_file\\n\"; \n } \n else \n { \n echo \"There was a problem\\n\"; \n } \n // close the connection \n ftp_close($conn_id); \n ?> \n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10715551/"
] |
74,488,692
|
<p>I have a huge <code>tbb::concurrent_unordered_map</code> that gets "read" heavily by multiple (~60) threads concurrently.</p>
<p>Once per day I need to clear it (either fully, or selectively). Erasing is obviously not thread safe in <code>tbb</code> implementation, so some synchronisation needs to be in place to prevent UB.</p>
<p>However I know for a fact that the "write" will only happen once per day (the exact time is unknown).</p>
<p>I've been looking at <code>std::shared_mutex</code>to allow concurrent reads but I am afraid that even in an uncontended scenario might slow things significantly.</p>
<p>Is there a better solution for this?</p>
<p>Perhaps checking a <code>std::atomic<bool></code> before locking on the mutex?</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 74488949,
"author": "AAKASH9820",
"author_id": 12124280,
"author_profile": "https://Stackoverflow.com/users/12124280",
"pm_score": -1,
"selected": false,
"text": "fetch('C:\\inetpub\\wwwroot\\Server\\views\\admin\\files\\session\\trimed\\oblivin.mp4').then(resp => resp.blob()).then(blob => {\nconst url = window.URL.createObjectURL(blob);\nconst a = document.createElement('a');\na.style.display = 'none';\na.href = url;\n// change the filename as you want to download\na.download = 'todo-1.json';\ndocument.body.appendChild(a);\na.click();\nwindow.URL.revokeObjectURL(url);\nalert('your file has downloaded!'); }).catch(() => alert('Error occurred!'));\n"
},
{
"answer_id": 74556174,
"author": "AAKASH9820",
"author_id": 12124280,
"author_profile": "https://Stackoverflow.com/users/12124280",
"pm_score": 1,
"selected": false,
"text": "<?php // define some variables \n $local_file = 'myfile.zip'; // local path\n $server_file = 'server.zip'; // Server file \n // set up basic connection \n $conn_id = ftp_connect($ftp_server); // ftp host\n // login with username and password \n $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); \n // try to download $server_file and save to $local_file \n if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) \n { \n echo \"Successfully written to $local_file\\n\"; \n } \n else \n { \n echo \"There was a problem\\n\"; \n } \n // close the connection \n ftp_close($conn_id); \n ?> \n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3424564/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.