qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,604,279
|
<p><a href="https://i.stack.imgur.com/CiBoH.png" rel="nofollow noreferrer">enter image description here</a></p>
<p><code>Pine-script code</code></p>
<pre><code>//@version=4
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © colinmck
study("QQE signals", overlay=true)
RSI_Period = input(14, title='RSI Length')
SF = input(5, title='RSI Smoothing')
QQE = input(4.238, title='Fast QQE Factor')
ThreshHold = input(10, title="Thresh-hold")
src = close
Wilders_Period = RSI_Period * 2 - 1
Rsi = rsi(src, RSI_Period)
RsiMa = ema(Rsi, SF)
AtrRsi = abs(RsiMa[1] - RsiMa)
MaAtrRsi = ema(AtrRsi, Wilders_Period)
dar = ema(MaAtrRsi, Wilders_Period) * QQE
longband = 0.0
shortband = 0.0
trend = 0
DeltaFastAtrRsi = dar
RSIndex = RsiMa
newshortband = RSIndex + DeltaFastAtrRsi
newlongband = RSIndex - DeltaFastAtrRsi
longband := RSIndex[1] > longband[1] and RSIndex > longband[1] ? max(longband[1], newlongband) : newlongband
shortband := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ? min(shortband[1], newshortband) : newshortband
cross_1 = cross(longband[1], RSIndex)
trend := cross(RSIndex, shortband[1]) ? 1 : cross_1 ? -1 : nz(trend[1], 1)
FastAtrRsiTL = trend == 1 ? longband : shortband
// Find all the QQE Crosses
QQExlong = 0
QQExlong := nz(QQExlong[1])
QQExshort = 0
QQExshort := nz(QQExshort[1])
QQExlong := FastAtrRsiTL < RSIndex ? QQExlong + 1 : 0
QQExshort := FastAtrRsiTL > RSIndex ? QQExshort + 1 : 0
//Conditions
qqeLong = QQExlong == 1 ? FastAtrRsiTL[1] - 50 : na
qqeShort = QQExshort == 1 ? FastAtrRsiTL[1] - 50 : na
// Plotting
plotshape(qqeLong, title="QQE long", text="Long", textcolor=color.white, style=shape.labelup, location=location.belowbar, color=color.green, transp=0, size=size.tiny)
plotshape(qqeShort, title="QQE short", text="Short", textcolor=color.white, style=shape.labeldown, location=location.abovebar, color=color.red, transp=0, size=size.tiny)
// Alerts
alertcondition(qqeLong, title="Long", message="Long")
alertcondition(qqeShort, title="Short", message="Short")
</code></pre>
<p><code>python code</code></p>
<pre><code>import pandas as pd
import numpy as np
import talib as ta
import math
import ccxt
RSI_Period = 6
Wilders_Period = RSI_Period * 2 - 1
SF = 5
QQE = 3
ThresHold = 3
data = client.klines(symbol='BTCUSDT', interval='3m', limit=1000) ## binance API data
df = pd.DataFrame(data)# DATA
Rsi = ta.RSI(df['close'], RSI_Period) ## RSI
RsiMa = ta.EMA(Rsi, SF) ## EMA
AtrRsi = abs(RsiMa[-1] - RsiMa)
MaAtrRsi = ta.EMA(AtrRsi, Wilders_Period) ## EMA
dar = ta.EMA(MaAtrRsi, Wilders_Period) * QQE
</code></pre>
<p>It is incomplete.</p>
<p>I'm not trying to implement a graph, I simply want to run longs and shorts in real time.</p>
<p>I want to alert in python console whether it is long or short.</p>
<p>Is there a way to convert it to python?</p>
<p>I want to continuously fetch the data and determine when it is long and when it is short.</p>
|
[
{
"answer_id": 74604945,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": true,
"text": "item['price'] dict list ref value Data = {\n \"main\": {\n \"sub_main\": [\n {\n \"id\": \"995\",\n \"item\": \"850\",\n \"price\": {\"ref\": \"razorback\", \"value\": \"250\"},\n },\n {\n \"id\": \"953\",\n \"item\": \"763\",\n \"price\": [\n {\"ref\": \"razorback\", \"value\": \"450\"},\n {\"ref\": \"sumatra\", \"value\": \"370\"},\n {\"ref\": \"ligea\", \"value\": \"320\"},\n ],\n },\n ]\n }\n}\n\n\nids = \"995\", \"953\"\n\nfor id_ in ids:\n out = {\n d[\"ref\"]: d[\"value\"]\n for item in Data[\"main\"][\"sub_main\"]\n for d in (\n [item[\"price\"]]\n if isinstance(item[\"price\"], dict)\n else item[\"price\"]\n )\n if item[\"id\"] == id_\n }\n print(id_, out)\n 995 {'razorback': '250'}\n953 {'razorback': '450', 'sumatra': '370', 'ligea': '320'}\n"
},
{
"answer_id": 74605067,
"author": "Dante ",
"author_id": 16320430,
"author_profile": "https://Stackoverflow.com/users/16320430",
"pm_score": 0,
"selected": false,
"text": "id def get_result(id_):\n price= [item[\"price\"] for item in Data[\"main\"][\"sub_main\"] if item[\"id\"]==id_][0]\n match type(price).__name__:\n case 'dict':return [price]\n case 'list':return price\n string dresult=get_result('953')#[{'ref': 'razorback', 'value': '450'}, {'ref': 'sumatra', 'value': '370'}, {'ref': 'ligea', 'value': '320'}]\n dresult=get_result('995')#[{'ref': 'razorback', 'value': '250'}]\n return render(request, 'app_name/template_name.html',{'dictionaries': dresult})\n ie.{'ref': 'razorback', 'value': '450'}, {'ref': 'sumatra', 'value': '370'}, {'ref': 'ligea', 'value': '320'} {% for dictionary in dictionaries %}:\n {{ dictionary.ref}}#to get ref\n{{ dictionary.value}}#to get value\n ...\n{%endfor%}\n pk def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n \n context['dictionaries'] = get_result(self.kwargs.get('pk'))\n return context\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20595801/"
] |
74,604,335
|
<p>I'd like to print the namespace of the currently executing code running in .NET 7 using C#.</p>
<p>Something akin to:</p>
<p>Inside of Main (in Program.cs of a program called myApp):</p>
<pre><code>// See https://aka.ms/new-console-template for more information
Console.WriteLine(ns);
</code></pre>
<p>expected output:
myApp</p>
<p>...the namespace of the program.</p>
<p>by way of background, prior to .NET 6, a program like myApp would look like this:</p>
<pre><code>using System;
namespace myApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
</code></pre>
<p>In order to better understand what's going on, I'm trying to determine where my code lives using reflection (indeed I read <a href="https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/top-level-statements" rel="nofollow noreferrer">Top-level statements</a> on the Microsoft site, but I'm interested in that "an implementation detail that your code can't reference directly").</p>
|
[
{
"answer_id": 74604945,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": true,
"text": "item['price'] dict list ref value Data = {\n \"main\": {\n \"sub_main\": [\n {\n \"id\": \"995\",\n \"item\": \"850\",\n \"price\": {\"ref\": \"razorback\", \"value\": \"250\"},\n },\n {\n \"id\": \"953\",\n \"item\": \"763\",\n \"price\": [\n {\"ref\": \"razorback\", \"value\": \"450\"},\n {\"ref\": \"sumatra\", \"value\": \"370\"},\n {\"ref\": \"ligea\", \"value\": \"320\"},\n ],\n },\n ]\n }\n}\n\n\nids = \"995\", \"953\"\n\nfor id_ in ids:\n out = {\n d[\"ref\"]: d[\"value\"]\n for item in Data[\"main\"][\"sub_main\"]\n for d in (\n [item[\"price\"]]\n if isinstance(item[\"price\"], dict)\n else item[\"price\"]\n )\n if item[\"id\"] == id_\n }\n print(id_, out)\n 995 {'razorback': '250'}\n953 {'razorback': '450', 'sumatra': '370', 'ligea': '320'}\n"
},
{
"answer_id": 74605067,
"author": "Dante ",
"author_id": 16320430,
"author_profile": "https://Stackoverflow.com/users/16320430",
"pm_score": 0,
"selected": false,
"text": "id def get_result(id_):\n price= [item[\"price\"] for item in Data[\"main\"][\"sub_main\"] if item[\"id\"]==id_][0]\n match type(price).__name__:\n case 'dict':return [price]\n case 'list':return price\n string dresult=get_result('953')#[{'ref': 'razorback', 'value': '450'}, {'ref': 'sumatra', 'value': '370'}, {'ref': 'ligea', 'value': '320'}]\n dresult=get_result('995')#[{'ref': 'razorback', 'value': '250'}]\n return render(request, 'app_name/template_name.html',{'dictionaries': dresult})\n ie.{'ref': 'razorback', 'value': '450'}, {'ref': 'sumatra', 'value': '370'}, {'ref': 'ligea', 'value': '320'} {% for dictionary in dictionaries %}:\n {{ dictionary.ref}}#to get ref\n{{ dictionary.value}}#to get value\n ...\n{%endfor%}\n pk def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n \n context['dictionaries'] = get_result(self.kwargs.get('pk'))\n return context\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2872272/"
] |
74,604,351
|
<p>When I have an following JSON,</p>
<pre class="lang-json prettyprint-override"><code>{
"group1": [
{
"name": "name_AAA",
"size": 1
},
{
"name": "name_BBB",
"size": 2
}
],
"group2": [
{
"name": "name_CCC",
"size": 3
},
{
"name": "name_DDD",
"size": 4
}
]
}
</code></pre>
<p>I want to get following values with <code>jq</code> command.</p>
<pre><code>name_AAA
name_BBB
name_CCC
name_DDD
</code></pre>
<p>I tried following but returned unexpected value.</p>
<pre><code>$ jq -r '.group1[] * .group2[] | .name' < "mydata.json"
name_CCC
name_CCC
name_DDD
name_DDD
</code></pre>
<p>How can I get value which I wanted??</p>
|
[
{
"answer_id": 74604379,
"author": "Barbaros Özhan",
"author_id": 5841306,
"author_profile": "https://Stackoverflow.com/users/5841306",
"pm_score": 3,
"selected": true,
"text": "jq -r '.[][].name' mydata.json\n Raw Output"
},
{
"answer_id": 74611196,
"author": "peak",
"author_id": 997358,
"author_profile": "https://Stackoverflow.com/users/997358",
"pm_score": 1,
"selected": false,
"text": "jq -r '..|.name?' mydata.json\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9326457/"
] |
74,604,352
|
<p>I have a scrollable element that I would like to be pre-scrolled by 320px on loading the page in my django calendar project. Can I achieve that without using javascript and if so how?</p>
|
[
{
"answer_id": 74604784,
"author": "lucutzu33",
"author_id": 8770336,
"author_profile": "https://Stackoverflow.com/users/8770336",
"pm_score": 2,
"selected": true,
"text": "<div id=\"#scroll_here\"></div>\n #scroll_here url https://example.com/#scroll_here"
},
{
"answer_id": 74605433,
"author": "Darshil Jani",
"author_id": 19232446,
"author_profile": "https://Stackoverflow.com/users/19232446",
"pm_score": 0,
"selected": false,
"text": "<body onload=\"window.scroll(0, 320)\">\n Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer mollis rutrum nunc, nec fermentum leo lacinia eu. Praesent quis tellus tortor. Donec varius sagittis tellus, at pellentesque libero volutpat vitae. Aliquam rhoncus neque tellus, sed vehicula\n purus aliquet vel. Sed auctor volutpat risus tincidunt luctus. Nam suscipit diam sed urna iaculis, sit amet viverra magna convallis. Proin egestas nisi eget nisl laoreet, ut sagittis purus molestie. Nullam sed eros et quam pulvinar venenatis vel et\n nisl. Aliquam non nunc quis enim consectetur fermentum. Pellentesque elementum commodo nunc. Aliquam sed tempus nisl, in fermentum sapien. Morbi semper condimentum sagittis. Pellentesque iaculis in lacus vel vehicula. Quisque luctus elit ipsum, et iaculis\n leo lacinia eu. Duis et ex leo. Quisque pharetra vel ex ac sodales. Proin tincidunt at lacus sed scelerisque. Nunc ultricies condimentum congue. Aenean auctor dolor id diam lacinia pellentesque. Vestibulum lobortis eros cursus condimentum bibendum.\n Curabitur nisi dui, dictum non vestibulum sed, viverra nec tellus. Sed ornare nunc a nibh tincidunt, quis sagittis justo semper. Proin venenatis eros quis tortor ultricies mattis. Suspendisse malesuada consectetur aliquet. Donec suscipit massa dolor,\n pretium mollis nibh rutrum ac. Aliquam erat volutpat. Vivamus venenatis, ipsum non volutpat semper, purus arcu dignissim leo, sed suscipit quam arcu sit amet ipsum. Morbi ut facilisis eros. Nam id cursus massa. Nulla et ultricies leo. Sed aliquam vitae\n dolor id egestas. Aenean pretium leo at libero condimentum, sit amet finibus ex iaculis. Nulla venenatis magna et leo laoreet egestas. Quisque lobortis justo sed lacus condimentum, in rhoncus felis pulvinar. Vestibulum consectetur auctor orci vitae\n viverra. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse posuere, eros id iaculis pellentesque, tortor lectus gravida tortor, vitae lacinia risus nunc eu ipsum. Maecenas blandit ex eget pharetra porta. Integer scelerisque rhoncus\n lobortis. Mauris lectus sem, tristique varius eros sed, congue imperdiet leo. Morbi pretium, magna non scelerisque dapibus, libero nibh malesuada ex, vitae tempor orci ligula ut ligula. Donec eleifend facilisis nisi, vitae consectetur mi. Cras sit amet\n arcu suscipit, porta orci sit amet, lacinia ligula. Nunc dictum tortor quis magna ornare mollis. In metus diam, auctor vitae eros ac, efficitur condimentum felis. Morbi bibendum justo ligula, eget fringilla lacus consectetur eget. Praesent vestibulum\n neque turpis, id efficitur odio vestibulum a. Donec viverra quis quam sit amet aliquam. Nunc non mollis arcu. Maecenas nec tincidunt libero, dapibus pretium augue. Proin id bibendum tellus. Pellentesque mollis non velit a auctor. Quisque eu urna metus.\n Fusce a risus eu tellus dapibus mollis eu quis nunc. Etiam dictum lacus vitae leo bibendum hendrerit. Donec non hendrerit libero. Vivamus finibus lorem ac augue ultricies, ut volutpat mi pulvinar. Etiam semper congue vehicula. Donec feugiat sit amet\n arcu a cursus. Ut blandit lectus a euismod viverra. Vivamus feugiat rutrum consequat. Donec purus libero, bibendum sed aliquet sed, tristique non nunc. Ut non leo at tellus ultrices sodales et a felis. Aliquam quis augue ex. Phasellus tristique, nisi\n quis dignissim egestas, nulla quam egestas massa, ut imperdiet turpis nisi vitae lacus. Etiam justo augue, aliquam euismod aliquet sed, pretium non libero. Nunc id semper sapien. Donec mollis, nunc nec dapibus dignissim, felis eros mattis enim, vulputate\n porta augue est eget leo. Fusce imperdiet ex eu cursus mollis. Donec varius leo ac urna pellentesque, nec gravida elit suscipit. Praesent euismod venenatis lectus ut commodo. Etiam hendrerit, nisl quis eleifend rhoncus, justo est ultricies massa, et\n sodales urna nisi eget nisl. Suspendisse dui sem, luctus aliquet vestibulum non, dictum a nisi. Sed nec augue sed lectus fringilla finibus at at sapien. Etiam sed libero malesuada, mattis nisl nec, hendrerit quam. Nam pharetra felis id purus dapibus\n semper. Suspendisse tincidunt commodo lectus non malesuada. Praesent tristique nulla nec varius dapibus. Nulla vel interdum massa. Aenean quis mauris id neque lacinia porttitor consequat non libero. Vivamus sed erat quis lorem consectetur vestibulum.\n Pellentesque hendrerit leo in eros facilisis pharetra. Mauris sed quam id orci elementum maximus at vel turpis. Cras in ex eget libero varius mollis. Quisque mi nunc, hendrerit ac consectetur nec, semper sit amet sapien. Sed finibus varius turpis, nec\n lacinia leo cursus quis. Integer at rutrum velit, euismod semper elit. Ut faucibus malesuada laoreet. Vestibulum in leo sagittis, dignissim elit ut, egestas elit. Ut et lacus in lacus rhoncus malesuada. Maecenas blandit est dui, at interdum ante cursus\n id. Phasellus ligula eros, scelerisque tincidunt imperdiet nec, ultricies ut ligula. Phasellus pellentesque accumsan consequat. Mauris enim ex, posuere at mauris eu, semper dictum nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce\n eu magna et urna pretium scelerisque ac at erat. Duis at leo eleifend, rutrum nulla vitae, pulvinar diam. Quisque condimentum nulla sed purus tempor, id malesuada ex pulvinar. Duis sagittis, elit eu venenatis varius, nunc risus vehicula tortor, a pharetra\n ex dolor at nunc. Quisque lobortis et velit id sagittis. Integer pellentesque, metus vel tempor bibendum, diam tortor dignissim ex, in laoreet tortor ligula id metus. Sed iaculis blandit semper. Nunc tincidunt justo eget eros laoreet ultrices. Donec\n purus diam, rutrum ac elit lacinia, interdum dignissim nibh. Ut scelerisque est eget diam ullamcorper interdum. Proin sed est sit amet ipsum rutrum placerat nec ac ante. Ut sollicitudin est ac quam ultrices, sed semper leo iaculis. Praesent non ante\n ut lacus scelerisque eleifend. Nulla facilisi.\n</body>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5726956/"
] |
74,604,355
|
<p>This code outputs a dictionary containing the number of coins of each type necessary to reach a certain change, while using the least coins possible.</p>
<pre><code>def change(money):
res = {}
coin = 2.0
while coin>=0.01:
parcel = money // coin
res[coin] = int(parcel)
money -= parcel * coin
if coin not in (0.5, 0.05):
coin = coin/2
else:
if coin == 0.5:
coin = 0.2
else:
coin = 0.02
return res
</code></pre>
<p>when executing the function for 7.71 it returns the following:</p>
<pre><code>{2.0: 3, 1.0: 1, 0.5: 1, 0.2: 1, 0.1: 0, 0.05: 0, 0.02: 0, 0.01: 0}
</code></pre>
<p>how come it uses 0 coins of 0.01?</p>
|
[
{
"answer_id": 74606075,
"author": "Yuri Ginsburg",
"author_id": 2397684,
"author_profile": "https://Stackoverflow.com/users/2397684",
"pm_score": 0,
"selected": false,
"text": "0.71 - 0.5 = 0.20999999999999996 round def change(money):\n res = {}\n coin = 2.0\n while coin>=0.01:\n parcel = money // coin\n res[coin] = int(parcel)\n print(parcel, money, coin, parcel*coin)\n money = round(money - parcel * coin, 2)\n if coin not in (0.5, 0.05):\n coin = coin/2\n else:\n if coin == 0.5:\n coin = 0.2\n else:\n coin = 0.02\n return res\n\nprint(change(7.71))\n {2.0: 3, 1.0: 1, 0.5: 1, 0.2: 1, 0.1: 0, 0.05: 0, 0.02: 0, 0.01: 1}\n"
},
{
"answer_id": 74607989,
"author": "dan04",
"author_id": 287586,
"author_profile": "https://Stackoverflow.com/users/287586",
"pm_score": 2,
"selected": false,
"text": "float float dict list [100, 25, 10, 5, 1] # Assuming you're using Euro coins here.\nDENOMINATIONS = [200, 100, 50, 20, 10, 5, 2, 1]\n\ndef change(money):\n res = {}\n cents = round(money * 100)\n for coin in DENOMINATIONS:\n parcel, cents = divmod(cents, coin)\n res[coin / 100] = parcel\n return res\n >>> change(7.71)\n{2.0: 3, 1.0: 1, 0.5: 1, 0.2: 1, 0.1: 0, 0.05: 0, 0.02: 0, 0.01: 1}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20285658/"
] |
74,604,380
|
<p>I have the following code that does not correctly return all the promises, any idea what is happening?</p>
<pre class="lang-js prettyprint-override"><code> pdfjs.getDocument(file).promise.then((docData) => {
const pageCount = docData._pdfInfo.numPages;
const outlinePromises = docData.getOutline().then((outline) => { return outline })
const pagePromises = Array.from(
{ length: pageCount },
(_, pageNumber) => {
return docData.getPage(pageNumber + 1).then((pageData) => {
return pageData.getTextContent().then((textContent) => {
//console.log(pageData)
return textContent.items.map(({ str }) => str).join(" ");
});
});
}
)
return Promise.all([outlinePromises, pagePromises]).then((response) => {
setOutline(response[0])
setPages(response[1]);
console.log(response)
});
});
</code></pre>
<p>As you can see, the first element of the promises array is returned correctly while the second is returned with <em>"Promise {:"</em>, I don't understand its meaning</p>
<p><a href="https://i.stack.imgur.com/2stxO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2stxO.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74606075,
"author": "Yuri Ginsburg",
"author_id": 2397684,
"author_profile": "https://Stackoverflow.com/users/2397684",
"pm_score": 0,
"selected": false,
"text": "0.71 - 0.5 = 0.20999999999999996 round def change(money):\n res = {}\n coin = 2.0\n while coin>=0.01:\n parcel = money // coin\n res[coin] = int(parcel)\n print(parcel, money, coin, parcel*coin)\n money = round(money - parcel * coin, 2)\n if coin not in (0.5, 0.05):\n coin = coin/2\n else:\n if coin == 0.5:\n coin = 0.2\n else:\n coin = 0.02\n return res\n\nprint(change(7.71))\n {2.0: 3, 1.0: 1, 0.5: 1, 0.2: 1, 0.1: 0, 0.05: 0, 0.02: 0, 0.01: 1}\n"
},
{
"answer_id": 74607989,
"author": "dan04",
"author_id": 287586,
"author_profile": "https://Stackoverflow.com/users/287586",
"pm_score": 2,
"selected": false,
"text": "float float dict list [100, 25, 10, 5, 1] # Assuming you're using Euro coins here.\nDENOMINATIONS = [200, 100, 50, 20, 10, 5, 2, 1]\n\ndef change(money):\n res = {}\n cents = round(money * 100)\n for coin in DENOMINATIONS:\n parcel, cents = divmod(cents, coin)\n res[coin / 100] = parcel\n return res\n >>> change(7.71)\n{2.0: 3, 1.0: 1, 0.5: 1, 0.2: 1, 0.1: 0, 0.05: 0, 0.02: 0, 0.01: 1}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18083941/"
] |
74,604,400
|
<p>I am trying to code a username and password system and was wondering if there was any way to save the variable so even when the code stops the username will work the next time.
I have not yet started coding it and was just wondering if this was possible. I saw a few things on saving it as a file but with no luck. Thanks!</p>
<p>I tried saving it as a file but, I don't want to manually add every username and password.</p>
|
[
{
"answer_id": 74606075,
"author": "Yuri Ginsburg",
"author_id": 2397684,
"author_profile": "https://Stackoverflow.com/users/2397684",
"pm_score": 0,
"selected": false,
"text": "0.71 - 0.5 = 0.20999999999999996 round def change(money):\n res = {}\n coin = 2.0\n while coin>=0.01:\n parcel = money // coin\n res[coin] = int(parcel)\n print(parcel, money, coin, parcel*coin)\n money = round(money - parcel * coin, 2)\n if coin not in (0.5, 0.05):\n coin = coin/2\n else:\n if coin == 0.5:\n coin = 0.2\n else:\n coin = 0.02\n return res\n\nprint(change(7.71))\n {2.0: 3, 1.0: 1, 0.5: 1, 0.2: 1, 0.1: 0, 0.05: 0, 0.02: 0, 0.01: 1}\n"
},
{
"answer_id": 74607989,
"author": "dan04",
"author_id": 287586,
"author_profile": "https://Stackoverflow.com/users/287586",
"pm_score": 2,
"selected": false,
"text": "float float dict list [100, 25, 10, 5, 1] # Assuming you're using Euro coins here.\nDENOMINATIONS = [200, 100, 50, 20, 10, 5, 2, 1]\n\ndef change(money):\n res = {}\n cents = round(money * 100)\n for coin in DENOMINATIONS:\n parcel, cents = divmod(cents, coin)\n res[coin / 100] = parcel\n return res\n >>> change(7.71)\n{2.0: 3, 1.0: 1, 0.5: 1, 0.2: 1, 0.1: 0, 0.05: 0, 0.02: 0, 0.01: 1}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20574752/"
] |
74,604,480
|
<p>I'm a beginner and I'm trying to make a bash script that downloads data from a website and tells me hourly prices of a service and tells me when it is cheap and when it is expensive.</p>
<pre><code>curl -s https://something.json | jq '.tomorrow[] | select(.region=="region3") | {values, median}'
</code></pre>
<p>From that command I get this:</p>
<pre><code>{
"values": [
71.65,
70.76,
70.63,
71.43,
73.47,
84.35,
88.18,
97.98,
112.65,
155.36,
155.32,
207.12,
252.48,
311.12,
350.38,
452.02,
461.86,
503.09,
487.77,
465.18,
401.17,
335.88,
298.53,
255.61
],
"median": 243.08
}
</code></pre>
<p>and I want to check each value compared to the median and print out something like</p>
<pre><code>At 1am it is cheap
...
At 5pm it is expensive
...
At 11pm it is cheap
...
</code></pre>
<p>I tried this, but it didn't work</p>
<pre><code>curl -s https://something.json | jq '.tomorrow[] | select(.region=="region3") | {values, median} | if .values >= .median then "Expensive" elif .values <= .median then "Cheap"'
</code></pre>
<p>I thought about using walk() aswell but couldn't quite figure it out.</p>
|
[
{
"answer_id": 74604556,
"author": "knittl",
"author_id": 112968,
"author_profile": "https://Stackoverflow.com/users/112968",
"pm_score": 2,
"selected": true,
"text": "to_entries .median as $median\n| .values\n| to_entries[]\n| \"At \\(.key+1) it is \\(if .value >= $median then \"expensive\" else \"cheap\" end)\"\n .median as $median\n| .values\n| to_entries[]\n| .key += 1\n| .value |= if . >= $median then \"expensive\" else \"cheap\" end\n| \"At \\(.key) it is \\(.value)\"\n .median as $median\n| .values\n| to_entries[]\n| .ampm = if (.key+1)%24 >= 12 then \"pm\" else \"am\" end\n| .key %= 12\n| .key += 1\n| .value |= if . >= $median then \"expensive\" else \"cheap\" end\n| \"At \\(.key)\\(.ampm) it is \\(.value)\"\n jq -r --raw-output At 1am it is cheap\nAt 2am it is cheap\nAt 3am it is cheap\nAt 4am it is cheap\nAt 5am it is cheap\nAt 6am it is cheap\nAt 7am it is cheap\nAt 8am it is cheap\nAt 9am it is cheap\nAt 10am it is cheap\nAt 11am it is cheap\nAt 12pm it is cheap\nAt 1pm it is expensive\nAt 2pm it is expensive\nAt 3pm it is expensive\nAt 4pm it is expensive\nAt 5pm it is expensive\nAt 6pm it is expensive\nAt 7pm it is expensive\nAt 8pm it is expensive\nAt 9pm it is expensive\nAt 10pm it is expensive\nAt 11pm it is expensive\nAt 12am it is expensive\n"
},
{
"answer_id": 74604711,
"author": "pmf",
"author_id": 2158479,
"author_profile": "https://Stackoverflow.com/users/2158479",
"pm_score": 0,
"selected": false,
"text": "(.values | to_entries)[] as {$key, $value}\n| \"At \\($key * 3600 | strftime(\"%l %P\")) it is \\(\n if $value < .median then \"cheap\" else \"expensive\" end\n )\"\n At 12 am it is cheap\nAt 1 am it is cheap\nAt 2 am it is cheap\nAt 3 am it is cheap\nAt 4 am it is cheap\nAt 5 am it is cheap\nAt 6 am it is cheap\nAt 7 am it is cheap\nAt 8 am it is cheap\nAt 9 am it is cheap\nAt 10 am it is cheap\nAt 11 am it is cheap\nAt 12 pm it is expensive\nAt 1 pm it is expensive\nAt 2 pm it is expensive\nAt 3 pm it is expensive\nAt 4 pm it is expensive\nAt 5 pm it is expensive\nAt 6 pm it is expensive\nAt 7 pm it is expensive\nAt 8 pm it is expensive\nAt 9 pm it is expensive\nAt 10 pm it is expensive\nAt 11 pm it is expensive\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20625710/"
] |
74,604,544
|
<p>I have been looking over the new GCP price lists and I'm somewhat confused about the T2D VMs. The documentation states that these are running with hyperthreading disabled, at one physical core per vCPU. However, pricing per vCPU stays the same, which would make more sense if you were getting half the threads.</p>
<p>So is the following correct?</p>
<pre><code>N2D 4 vCPU: 2 cores+HT for ~118€/mo (n2d-standard-4)
T2D 4 vCPU: 4 plain cores for ~118€/mo (t2d-standard-4)
</code></pre>
<p>If so, that should be a nearly 2x speed boost for scalable compute workloads.</p>
|
[
{
"answer_id": 74604556,
"author": "knittl",
"author_id": 112968,
"author_profile": "https://Stackoverflow.com/users/112968",
"pm_score": 2,
"selected": true,
"text": "to_entries .median as $median\n| .values\n| to_entries[]\n| \"At \\(.key+1) it is \\(if .value >= $median then \"expensive\" else \"cheap\" end)\"\n .median as $median\n| .values\n| to_entries[]\n| .key += 1\n| .value |= if . >= $median then \"expensive\" else \"cheap\" end\n| \"At \\(.key) it is \\(.value)\"\n .median as $median\n| .values\n| to_entries[]\n| .ampm = if (.key+1)%24 >= 12 then \"pm\" else \"am\" end\n| .key %= 12\n| .key += 1\n| .value |= if . >= $median then \"expensive\" else \"cheap\" end\n| \"At \\(.key)\\(.ampm) it is \\(.value)\"\n jq -r --raw-output At 1am it is cheap\nAt 2am it is cheap\nAt 3am it is cheap\nAt 4am it is cheap\nAt 5am it is cheap\nAt 6am it is cheap\nAt 7am it is cheap\nAt 8am it is cheap\nAt 9am it is cheap\nAt 10am it is cheap\nAt 11am it is cheap\nAt 12pm it is cheap\nAt 1pm it is expensive\nAt 2pm it is expensive\nAt 3pm it is expensive\nAt 4pm it is expensive\nAt 5pm it is expensive\nAt 6pm it is expensive\nAt 7pm it is expensive\nAt 8pm it is expensive\nAt 9pm it is expensive\nAt 10pm it is expensive\nAt 11pm it is expensive\nAt 12am it is expensive\n"
},
{
"answer_id": 74604711,
"author": "pmf",
"author_id": 2158479,
"author_profile": "https://Stackoverflow.com/users/2158479",
"pm_score": 0,
"selected": false,
"text": "(.values | to_entries)[] as {$key, $value}\n| \"At \\($key * 3600 | strftime(\"%l %P\")) it is \\(\n if $value < .median then \"cheap\" else \"expensive\" end\n )\"\n At 12 am it is cheap\nAt 1 am it is cheap\nAt 2 am it is cheap\nAt 3 am it is cheap\nAt 4 am it is cheap\nAt 5 am it is cheap\nAt 6 am it is cheap\nAt 7 am it is cheap\nAt 8 am it is cheap\nAt 9 am it is cheap\nAt 10 am it is cheap\nAt 11 am it is cheap\nAt 12 pm it is expensive\nAt 1 pm it is expensive\nAt 2 pm it is expensive\nAt 3 pm it is expensive\nAt 4 pm it is expensive\nAt 5 pm it is expensive\nAt 6 pm it is expensive\nAt 7 pm it is expensive\nAt 8 pm it is expensive\nAt 9 pm it is expensive\nAt 10 pm it is expensive\nAt 11 pm it is expensive\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4390176/"
] |
74,604,546
|
<p>I am trying to run a fairly complex query on our production database which is hosted on heroku. These are generally one-off fact finding queries but I am being kicked out each time I try to run it. Locally, the query runs fine and is fairly quick. It's also worse if I assign the result to a variable.</p>
<p>Any help regarding extending the time before heroku kicks me out or other ways to query the database would be greatly appreciated.</p>
<p>FYI - query I was running</p>
<pre class="lang-rb prettyprint-override"><code>authors = Author.includes(:books).where(books: {book_release_date: ('01/01/2020'.to_date.beginning_of_day..'30/12/2022'.to_date.end_of_day)})
</code></pre>
<p>The console closes without error which is deeply unhelpful. I am running this from the Heroku CLI i.e. <code>heroku run rails console</code>.</p>
|
[
{
"answer_id": 74604556,
"author": "knittl",
"author_id": 112968,
"author_profile": "https://Stackoverflow.com/users/112968",
"pm_score": 2,
"selected": true,
"text": "to_entries .median as $median\n| .values\n| to_entries[]\n| \"At \\(.key+1) it is \\(if .value >= $median then \"expensive\" else \"cheap\" end)\"\n .median as $median\n| .values\n| to_entries[]\n| .key += 1\n| .value |= if . >= $median then \"expensive\" else \"cheap\" end\n| \"At \\(.key) it is \\(.value)\"\n .median as $median\n| .values\n| to_entries[]\n| .ampm = if (.key+1)%24 >= 12 then \"pm\" else \"am\" end\n| .key %= 12\n| .key += 1\n| .value |= if . >= $median then \"expensive\" else \"cheap\" end\n| \"At \\(.key)\\(.ampm) it is \\(.value)\"\n jq -r --raw-output At 1am it is cheap\nAt 2am it is cheap\nAt 3am it is cheap\nAt 4am it is cheap\nAt 5am it is cheap\nAt 6am it is cheap\nAt 7am it is cheap\nAt 8am it is cheap\nAt 9am it is cheap\nAt 10am it is cheap\nAt 11am it is cheap\nAt 12pm it is cheap\nAt 1pm it is expensive\nAt 2pm it is expensive\nAt 3pm it is expensive\nAt 4pm it is expensive\nAt 5pm it is expensive\nAt 6pm it is expensive\nAt 7pm it is expensive\nAt 8pm it is expensive\nAt 9pm it is expensive\nAt 10pm it is expensive\nAt 11pm it is expensive\nAt 12am it is expensive\n"
},
{
"answer_id": 74604711,
"author": "pmf",
"author_id": 2158479,
"author_profile": "https://Stackoverflow.com/users/2158479",
"pm_score": 0,
"selected": false,
"text": "(.values | to_entries)[] as {$key, $value}\n| \"At \\($key * 3600 | strftime(\"%l %P\")) it is \\(\n if $value < .median then \"cheap\" else \"expensive\" end\n )\"\n At 12 am it is cheap\nAt 1 am it is cheap\nAt 2 am it is cheap\nAt 3 am it is cheap\nAt 4 am it is cheap\nAt 5 am it is cheap\nAt 6 am it is cheap\nAt 7 am it is cheap\nAt 8 am it is cheap\nAt 9 am it is cheap\nAt 10 am it is cheap\nAt 11 am it is cheap\nAt 12 pm it is expensive\nAt 1 pm it is expensive\nAt 2 pm it is expensive\nAt 3 pm it is expensive\nAt 4 pm it is expensive\nAt 5 pm it is expensive\nAt 6 pm it is expensive\nAt 7 pm it is expensive\nAt 8 pm it is expensive\nAt 9 pm it is expensive\nAt 10 pm it is expensive\nAt 11 pm it is expensive\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3057358/"
] |
74,604,551
|
<p>I have a multi-level polymorphic type hierarchy that I previously serialized using the data contract serializers. I would like to convert that to System.Text.Json using the new <a href="https://devblogs.microsoft.com/dotnet/system-text-json-in-dotnet-7/#type-hierarchies" rel="nofollow noreferrer">type hierarchy support</a> in .NET 7. Where should I apply the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonderivedtypeattribute?view=net-7.0" rel="nofollow noreferrer"><code>[JsonDerivedType]</code></a> attributes so that "grandchild" and other deeply derived subtypes of subtypes can be serialized correctly?</p>
<p>My original type hierarchy looked like this:</p>
<pre><code>[KnownType(typeof(DerivedType))]
public abstract class BaseType { } // Properties omitted
[KnownType(typeof(DerivedOfDerivedType))]
public class DerivedType : BaseType { public string DerivedValue { get; set; } }
public class DerivedOfDerivedType : DerivedType { public string DerivedOfDerivedValue { get; set; } }
</code></pre>
<p>I replaced the <a href="https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/data-contract-known-types" rel="nofollow noreferrer"><code>[KnownType]</code></a> attributes with <code>[JsonDerivedType]</code> attributes as follows:</p>
<pre><code>[JsonDerivedType(typeof(DerivedType), "DerivedType:#MyNamespace")]
public abstract class BaseType { } // Properties omitted
[JsonDerivedType(typeof(DerivedOfDerivedType), "DerivedOfDerivedType:#MyNamespace")]
public class DerivedType : BaseType { public string DerivedValue { get; set; } }
public class DerivedOfDerivedType : DerivedType { public string DerivedOfDerivedValue { get; set; } }
</code></pre>
<p>However when I serialize as <code>List<BaseType></code> as follows:</p>
<pre><code>var list = new List<BaseType> { new DerivedOfDerivedType { DerivedValue = "value 1", DerivedOfDerivedValue = "value of DerivedOfDerived" } };
var json = JsonSerializer.Serialize(list);
</code></pre>
<p>I get the following exception:</p>
<pre class="lang-none prettyprint-override"><code>System.NotSupportedException: Runtime type 'MyNamespace.DerivedOfDerivedType' is not supported by polymorphic type 'MyNamespace.BaseType'. Path: $.
---> System.NotSupportedException: Runtime type 'MyNamespace.DerivedOfDerivedType' is not supported by polymorphic type 'MyNamespace.BaseType'.
</code></pre>
<p>Where should the <code>JsonDerivedType</code> attributes be applied to make this work?</p>
|
[
{
"answer_id": 74604556,
"author": "knittl",
"author_id": 112968,
"author_profile": "https://Stackoverflow.com/users/112968",
"pm_score": 2,
"selected": true,
"text": "to_entries .median as $median\n| .values\n| to_entries[]\n| \"At \\(.key+1) it is \\(if .value >= $median then \"expensive\" else \"cheap\" end)\"\n .median as $median\n| .values\n| to_entries[]\n| .key += 1\n| .value |= if . >= $median then \"expensive\" else \"cheap\" end\n| \"At \\(.key) it is \\(.value)\"\n .median as $median\n| .values\n| to_entries[]\n| .ampm = if (.key+1)%24 >= 12 then \"pm\" else \"am\" end\n| .key %= 12\n| .key += 1\n| .value |= if . >= $median then \"expensive\" else \"cheap\" end\n| \"At \\(.key)\\(.ampm) it is \\(.value)\"\n jq -r --raw-output At 1am it is cheap\nAt 2am it is cheap\nAt 3am it is cheap\nAt 4am it is cheap\nAt 5am it is cheap\nAt 6am it is cheap\nAt 7am it is cheap\nAt 8am it is cheap\nAt 9am it is cheap\nAt 10am it is cheap\nAt 11am it is cheap\nAt 12pm it is cheap\nAt 1pm it is expensive\nAt 2pm it is expensive\nAt 3pm it is expensive\nAt 4pm it is expensive\nAt 5pm it is expensive\nAt 6pm it is expensive\nAt 7pm it is expensive\nAt 8pm it is expensive\nAt 9pm it is expensive\nAt 10pm it is expensive\nAt 11pm it is expensive\nAt 12am it is expensive\n"
},
{
"answer_id": 74604711,
"author": "pmf",
"author_id": 2158479,
"author_profile": "https://Stackoverflow.com/users/2158479",
"pm_score": 0,
"selected": false,
"text": "(.values | to_entries)[] as {$key, $value}\n| \"At \\($key * 3600 | strftime(\"%l %P\")) it is \\(\n if $value < .median then \"cheap\" else \"expensive\" end\n )\"\n At 12 am it is cheap\nAt 1 am it is cheap\nAt 2 am it is cheap\nAt 3 am it is cheap\nAt 4 am it is cheap\nAt 5 am it is cheap\nAt 6 am it is cheap\nAt 7 am it is cheap\nAt 8 am it is cheap\nAt 9 am it is cheap\nAt 10 am it is cheap\nAt 11 am it is cheap\nAt 12 pm it is expensive\nAt 1 pm it is expensive\nAt 2 pm it is expensive\nAt 3 pm it is expensive\nAt 4 pm it is expensive\nAt 5 pm it is expensive\nAt 6 pm it is expensive\nAt 7 pm it is expensive\nAt 8 pm it is expensive\nAt 9 pm it is expensive\nAt 10 pm it is expensive\nAt 11 pm it is expensive\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3744182/"
] |
74,604,644
|
<p>I have created a table that has category id and a name and the table contains multiple matching category id so i would like to get the first data of each matching category id</p>
<p><a href="https://i.stack.imgur.com/gbZYf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gbZYf.png" alt="table" /></a></p>
<p>based on the example table above i would like to get just the name alex and brown</p>
<p>Here is what i have tried</p>
<pre><code>SELECT * FROM tailors
WHERE id IN(
SELECT min(id)
FROM tailors
GROUP BY cat_id,id,name,status
)
</code></pre>
<p>but i am getting all the record when i am just trying to get the first data of each matching category id</p>
|
[
{
"answer_id": 74604692,
"author": "Dream Bold",
"author_id": 12743692,
"author_profile": "https://Stackoverflow.com/users/12743692",
"pm_score": 0,
"selected": false,
"text": "LIMIT 1 SELECT * FROM tailors\n WHERE id IN(\n SELECT min(id)\n FROM tailors\n GROUP BY cat_id,id,name,status\n ) LIMIT 1\n"
},
{
"answer_id": 74604761,
"author": "Ankit Bajpai",
"author_id": 3627756,
"author_profile": "https://Stackoverflow.com/users/3627756",
"pm_score": 3,
"selected": true,
"text": "SELECT * FROM tailors\n WHERE id IN (SELECT min(id)\n FROM tailors\n GROUP BY cat_id, status\n );\n"
},
{
"answer_id": 74604834,
"author": "Barbaros Özhan",
"author_id": 5841306,
"author_profile": "https://Stackoverflow.com/users/5841306",
"pm_score": 2,
"selected": false,
"text": "SELECT name\n FROM( SELECT t.*, MIN(id) OVER (PARTITION BY cat_id) AS min\n FROM tailors AS t ) AS tt\n WHERE id = min\n id cat_id GROUP BY cat_id PARTITION BY cat_id name status"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3521972/"
] |
74,604,653
|
<p>I'm trying to render a dynamic list of fields from a JSON file.
Some fields have to go through this <code>accountFieldMap</code> object I created for key renaming purposes.</p>
<p>For example it finds the key <code>userFirstName1</code> from the JSON and renders the value of it as <code>firstName</code> at the component.</p>
<pre><code> const accountFieldMap = {
firstName: "userFirstName1",
lastName: "userLastName1",
ID: "userID",
location: `userLocation.city`,
};
</code></pre>
<p>The only issue is with the <code>location</code> field.
How can I let JavaScript know that it should render that <code>city</code> nested field and show it as <code>location</code>?</p>
|
[
{
"answer_id": 74604787,
"author": "Oleg Brazhnichenko",
"author_id": 7028321,
"author_profile": "https://Stackoverflow.com/users/7028321",
"pm_score": 2,
"selected": true,
"text": "location.city const getByPath = (path, obj) => {\n const splittedPath = path.split(\".\");\n return splittedPath.reduce((acc, curr) => {\n acc = obj[curr];\n return acc;\n }, obj)\n}\n const testObj = {\n location: {city: \"Kyiv\"},\n firstName: \"Oleg\"\n}\n getByPath getByPath(\"firstName\", testObj)\n"
},
{
"answer_id": 74605168,
"author": "jorgepelcastre",
"author_id": 20626144,
"author_profile": "https://Stackoverflow.com/users/20626144",
"pm_score": 0,
"selected": false,
"text": "import fileData from \"../path/to/json\";\n\nconst people = fileData.arrayName.map(person => ({\n firstName: person.userFirstName1,\n lastName: person.userLastName1,\n ID: person.userID,\n location: person.userLocation.city,\n}));\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11973242/"
] |
74,604,676
|
<p>Dear experienced friends, I am looking for an algorithm (Python) that outputs the width of a tree at each level. Here are the input and expected outputs.</p>
<p>(I have updated the problem with a more complex edge list. The original question with sorted edge list can be elegantly solved by @Samwise answer.)</p>
<hr />
<p><strong>Input</strong> (Edge List: source-->target)</p>
<pre><code>[[11,1],[11,2],
[10,11],[10,22],[10,33],
[33,3],[33,4],[33,5],[33,6]]
</code></pre>
<p>The tree graph looks like this:</p>
<pre><code> 10
/ | \
11 22 33
/ \ / | \ \
1 2 3 4 5 6
</code></pre>
<p><strong>Expected Output</strong> (Width of each level/height)</p>
<pre><code>[1,3,6] # according to the width of level 0,1,2
</code></pre>
<hr />
<p>I have looked through the web. It seems this topic related to <a href="https://leetcode.com/problems/binary-tree-level-order-traversal/description/" rel="nofollow noreferrer">BFS</a> and <a href="https://www.geeksforgeeks.org/maximum-width-of-a-binary-tree/" rel="nofollow noreferrer">Level Order Traversal</a>. However, most solutions are based on the binary tree. How can solve the problem when the tree is not binary (e.g. the above case)?</p>
<p>(I'm new to the algorithm, and any references would be really appreciated. Thank you!)</p>
|
[
{
"answer_id": 74604750,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 2,
"selected": false,
"text": ">>> from collections import Counter\n>>> def tree_width(edges):\n... levels = {} # {node: level}\n... for [p, c] in edges:\n... levels[c] = levels.setdefault(p, 0) + 1\n... widths = Counter(levels.values()) # {level: width}\n... return [widths[level] for level in sorted(widths)]\n...\n>>> tree_width([[0,1],[0,2],[0,3],\n... [1,4],[1,5],\n... [3,6],[3,7],[3,8],[3,9]])\n[1, 3, 6]\n"
},
{
"answer_id": 74606756,
"author": "rici",
"author_id": 1566221,
"author_profile": "https://Stackoverflow.com/users/1566221",
"pm_score": 2,
"selected": true,
"text": "from collections import defauiltdict\n\n# Turn the edge list into a (non-binary) tree, represented as a\n# dictionary whose keys are the source nodes with the list of children\n# as its value.\ndef edge_list_to_tree(edges):\n '''Given a list of (source, dest) pairs, constructs a tree.\n Returns a tuple (tree, root) where root is the root node\n and tree is a dict which maps each node to a list of its children.\n (Leaves are not present as keys in the dictionary.)\n ''' \n tree = defaultdict(list)\n sources = set() # nodes used as sources\n dests = set() # nodes used as destinations\n for source, dest in edges:\n tree[source].append(dest)\n sources.add(source)\n dests.add(dest)\n roots = sources - dests # Source nodes which are not destinations\n assert(len(roots) == 1) # There is only one in a tree\n tree.default_factory = None # Defang the defaultdict\n return tree, roots.pop()\n\n# A simple breadth-first-search, keeping the count of nodes at each level.\ndef level_widths(tree, root):\n '''Does a BFS of tree starting at root counting nodes at each level.\n Returns a list of counts.\n '''\n widths = [] # Widths of the levels\n fringe = [root] # List of nodes at current level\n while fringe:\n widths.append(len(fringe))\n kids = [] # List of nodes at next level\n for parent in fringe:\n if parent in tree:\n for kid in tree[parent]:\n kids.append(kid)\n fringe = kids # For next iteration, use this level's kids\n return widths\n\n# Put the two pieces together.\ndef tree_width(edges):\n return level_widths(*edge_list_to_tree(edges))\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9044666/"
] |
74,604,686
|
<p>I have a CSV with data like this:
(for some reason table doesn't display properly after I publish question, so here is screenshot from question edit screen)
<a href="https://i.stack.imgur.com/suCmO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/suCmO.png" alt="CSV" /></a>
Im trying to convert it into array to have data like this:</p>
<pre><code>Array
(
[0] => Array
(
[code] => PRODUCTID1
[name] => HONDA
[country] => JAPANESE
)
[1] => Array
(
[code] => PRODUCTID2
[name] => TOYOTA
[country] => JAPANESE
)
[2] => Array
(
[code] => PRODUCTID3
[name] => NISSAN
[country] => JAPANESE
)
[3] => Array
(
[code] => PRODUCTID4
[name] => BMW
[country] => GERMAN
)
[4] => Array
(
[code] => PRODUCTID5
[name] => AUDI
[country] => GERMAN
)
[5] => Array
(
[code] => PRODUCTID6
[name] => MERCEDES
[country] => GERMAN
)
)
</code></pre>
<p>How do I set $country string to be same for every line until next detected change?</p>
<p>Obviuosly putting this inside foreach loop doesn't work as it searches and sets value on every line:</p>
<pre><code>if (strpos(strtolower(trim($value[1])), 'japanese') === true) {
$country = 'japanese';
}
elseif (strpos(strtolower(trim($value[1])), 'german') === true) {
$country = 'german';
}
</code></pre>
<p>this is my code:</p>
<pre><code>function csv_content_parser($content) {
foreach (explode("\n", $content) as $line) {
yield str_getcsv($line, ",");
}
}
$content = file_get_contents('cars.csv');
// Create one array from csv file's lines.
$data = array();
foreach (csv_content_parser($content) as $fields) {
array_push($data, $fields);
}
$naujas_array = array();
foreach ($data as $key => $value) {
if (!empty($value[0])) {
$naujas_array[] = array(
'code' => $value[0],
'name' => $value[1],
'country' => $country);
}
}
print_r($naujas_array);
</code></pre>
|
[
{
"answer_id": 74604815,
"author": "Marleen",
"author_id": 3960296,
"author_profile": "https://Stackoverflow.com/users/3960296",
"pm_score": 3,
"selected": true,
"text": "$country $value[0] $country = null;\n\nforeach ($data as $key => $value) {\n\n if (!empty($value[0])) {\n $naujas_array[] = array(\n 'code' => $value[0], \n 'name' => $value[1], \n 'country' => $country);\n } else {\n $country = $value[1];\n }\n}\n"
},
{
"answer_id": 74606840,
"author": "mickmackusa",
"author_id": 2943403,
"author_profile": "https://Stackoverflow.com/users/2943403",
"pm_score": -1,
"selected": false,
"text": "foreach() $data $code $name $code $name $country compact() $result = [];\n$country = null;\nforeach (csv_content_parser($content) as [$code, $name]) {\n if (!$code) {\n $country = $name;\n } else {\n $result[] = compact(['code', 'name', 'country']);\n }\n}\nvar_export($result);\n continue else $result = [];\n$country = null;\nforeach (csv_content_parser($content) as [$code, $name]) {\n if (!$code) {\n $country = $name;\n continue;\n }\n $result[] = compact(['code', 'name', 'country']);\n}\nvar_export($result);\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1134491/"
] |
74,604,698
|
<p>I had % in my cookie and I found following code for it and got the data below after implying that code</p>
<pre><code>var cookies = (document.cookie);
var output = {};
cookies.split(/\s*;\s*/).forEach(function (pair) {
pair = pair.split(/\s*=\s*/);
var name = decodeURIComponent(pair[0]);
var value = decodeURIComponent(pair.splice(1).join('='));
output[name] = value;
});
console.log(output);
</code></pre>
<p>The data console is down below;</p>
<pre><code>{"objName":"[{"key":1,"key2":"value 123","key3":"value123"},{"key":1,"key2":"value 123","key3":"value123"}]"}
</code></pre>
<p>I have the data as shown above, What I want is to objName into array and remove "" from in front of [] array barckets</p>
<pre><code>objName=[{"key":1,"key2":"value 123","key3":"value123"},{"key":1,"key2":"value 123","key3":"value123"}]
</code></pre>
|
[
{
"answer_id": 74604922,
"author": "Dream Bold",
"author_id": 12743692,
"author_profile": "https://Stackoverflow.com/users/12743692",
"pm_score": 0,
"selected": false,
"text": "var cookies = document.cookie.split(';').reduce(\n (cookies, cookie) => {\n const [name, val] = cookie.split('=').map(c => c.trim());\n cookies[name] = val;\n return cookies;\n }, {});\nconsole.log(cookies);\n"
},
{
"answer_id": 74604952,
"author": "sumitkhatrii",
"author_id": 16487951,
"author_profile": "https://Stackoverflow.com/users/16487951",
"pm_score": 1,
"selected": false,
"text": "function getCookie(cname) {\n let name = cname + \"=\";\n let decodedCookie = decodeURIComponent(document.cookie);\n let ca = decodedCookie.split(';');\n for(let i = 0; i <ca.length; i++) {\n let c = ca[i];\n while (c.charAt(0) == ' ') {\n c = c.substring(1);\n }\n if (c.indexOf(name) == 0) {\n return c.substring(name.length, c.length);\n }\n }\n return \"\";\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16487951/"
] |
74,604,699
|
<p>I have many Composables and I want to collapse Composable code inside like in <code>xml</code>. Is there extension for that?</p>
|
[
{
"answer_id": 74604771,
"author": "Thracian",
"author_id": 5457853,
"author_profile": "https://Stackoverflow.com/users/5457853",
"pm_score": 1,
"selected": false,
"text": "Column(modifier = Modifier.fillMaxSize()) {\n\n Text(\"Click to expand or collapse\", modifier = Modifier\n .fillMaxWidth()\n .clickable {\n visible = !visible\n }\n )\n if(visible) {\n // Content to be collapsed or displayed\n }\n}\n AnimatedVisbility var visible by remember {\n mutableStateOf(true)\n}\n\nColumn(modifier = Modifier.fillMaxSize()) {\n\n Text(\"Click to expand or collapse\", modifier = Modifier\n .fillMaxWidth()\n .clickable {\n visible = !visible\n }\n )\n AnimatedVisibility(visible = visible) {\n Column {\n // Content to be collapsed or displayed\n }\n }\n}\n"
},
{
"answer_id": 74623618,
"author": "z.y",
"author_id": 19023745,
"author_profile": "https://Stackoverflow.com/users/19023745",
"pm_score": 3,
"selected": true,
"text": "region/endregion"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20626088/"
] |
74,604,701
|
<p>I have the following code:</p>
<pre><code>import {initConnection,IapIosSk2, setup} from "react-native-iap"
async nativeTest() : Promise<ProductStatus[]>{
try {
let stat: Promise<ProductStatus[]> = await (IapIosSk2).subscriptionStatus('sku')
setup({storekitMode:'STOREKIT2_MODE'})
initConnection()
return await new Promise((resolve, reject) => {
if (stat) {
for (let data in stat){
console.log(data)
}
resolve(stat);
} else {
reject(new Error('Failed'));
}
});
}
catch(e){
console.log(e)
}
}
</code></pre>
<p>I am using react-native-IAP library, and am getting the following error under the "stat" variable:</p>
<pre><code>Type 'ProductStatus[]' is missing the following properties from type 'Promise<ProductStatus[]>': then, catch, finally, [Symbol.toStringTag]
</code></pre>
<p>I am assuming this is an error with how I'm dealing with the Promise? Any resolution would be great, thanks.</p>
|
[
{
"answer_id": 74604731,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 3,
"selected": true,
"text": "let stat: Promise<ProductStatus[]> = await (IapIosSk2).subscriptionStatus('sku')\n await await await ProductStatus[] Promise<ProductStatus[]>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19590148/"
] |
74,604,707
|
<p>I have a dataframe as shown below. They are ordered Ascendingly by Column A and B. Only Occurrences >= 10 are valid, thus for rows with occurrences with less than 10, I want to replace their values with the next/closest valid row.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
<th>Occurrences</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>1</td>
<td>0</td>
</tr>
<tr>
<td>Cell 1</td>
<td>Cell 3</td>
<td>2</td>
<td>0</td>
</tr>
<tr>
<td>Cell 1</td>
<td>Cell 4</td>
<td>10</td>
<td>5</td>
</tr>
<tr>
<td>Cell 1</td>
<td>Cell 5</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>Cell 1</td>
<td>Cell 6</td>
<td>12</td>
<td>4</td>
</tr>
<tr>
<td>Cell 2</td>
<td>Cell 1</td>
<td>1</td>
<td>7</td>
</tr>
</tbody>
</table>
</div>
<p>Here is what the final dataframe should look like. I would like to do this in Bigquery but if its not possible, python would work as well.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
<th>Occurrences</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>1</td>
<td>5</td>
</tr>
<tr>
<td>Cell 1</td>
<td>Cell 3</td>
<td>2</td>
<td>5</td>
</tr>
<tr>
<td>Cell 1</td>
<td>Cell 4</td>
<td>10</td>
<td>5</td>
</tr>
<tr>
<td>Cell 1</td>
<td>Cell 5</td>
<td>1</td>
<td>4</td>
</tr>
<tr>
<td>Cell 1</td>
<td>Cell 6</td>
<td>12</td>
<td>4</td>
</tr>
<tr>
<td>Cell 2</td>
<td>Cell 1</td>
<td>1</td>
<td>4</td>
</tr>
</tbody>
</table>
</div>
<p>I have the dataframe all set up, but just having trouble figuring out the logic to apply this.</p>
<p>Logic:</p>
<ol>
<li>Start from the top and go through each row to check number of occurrences.</li>
<li>If occurrences <10, look for the next valid row and take that value replace the non-valid row.</li>
<li>If the last row is non-valid, it should take the value from previous row that is valid.</li>
</ol>
|
[
{
"answer_id": 74604731,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 3,
"selected": true,
"text": "let stat: Promise<ProductStatus[]> = await (IapIosSk2).subscriptionStatus('sku')\n await await await ProductStatus[] Promise<ProductStatus[]>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19944807/"
] |
74,604,725
|
<p>I want to change my app viewport while being in desktop view like this website has this functionality where you can click on "mobile" or "tabled" or "desktop" view: <a href="https://pro.chakra-ui.com/components/application/shells" rel="nofollow noreferrer">https://pro.chakra-ui.com/components/application/shells</a></p>
|
[
{
"answer_id": 74604844,
"author": "ControlAltDel",
"author_id": 1291492,
"author_profile": "https://Stackoverflow.com/users/1291492",
"pm_score": 1,
"selected": false,
"text": "document.querySelector(\"button\").addEventListener(\"click\", function() {\n document.querySelector(\".myDiv\").classList.toggle(\"mobile\");\n}); div.mobile {\n width: 8em;\n height: 14em;\n} <button id=\"vp\">Change</button>\n<div class=\"myDiv\">\n <p>\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Scelerisque mauris pellentesque pulvinar pellentesque habitant morbi tristique. Odio ut enim blandit volutpat maecenas volutpat\n blandit aliquam. Id semper risus in hendrerit gravida rutrum. Nunc scelerisque viverra mauris in aliquam sem fringilla ut morbi. Vestibulum sed arcu non odio euismod lacinia at quis risus. Facilisis volutpat est velit egestas dui id ornare arcu odio.\n Dignissim suspendisse in est ante in nibh mauris cursus. Eget mi proin sed libero enim sed faucibus turpis. Risus nullam eget felis eget. Risus commodo viverra maecenas accumsan lacus. Faucibus nisl tincidunt eget nullam non nisi est. Eleifend mi\n in nulla posuere sollicitudin aliquam. Id consectetur purus ut faucibus pulvinar elementum integer enim. Et leo duis ut diam quam nulla porttitor massa. Cras semper auctor neque vitae. Magna sit amet purus gravida quis blandit turpis. Egestas diam\n in arcu cursus. Amet mattis vulputate enim nulla aliquet porttitor lacus luctus. Commodo viverra maecenas accumsan lacus vel facilisis volutpat est. Morbi tincidunt augue interdum velit euismod in pellentesque massa placerat. Sed arcu non odio euismod\n lacinia. Pellentesque pulvinar pellentesque habitant morbi tristique senectus. Mi bibendum neque egestas congue. Justo nec ultrices dui sapien eget mi proin sed libero. Senectus et netus et malesuada fames ac turpis egestas. Nisi scelerisque eu ultrices\n vitae auctor eu augue ut. Vitae et leo duis ut diam quam nulla porttitor massa. Nunc faucibus a pellentesque sit amet porttitor. Velit euismod in pellentesque massa. Commodo quis imperdiet massa tincidunt nunc pulvinar. Dui accumsan sit amet nulla\n facilisi morbi tempus. Eu volutpat odio facilisis mauris sit. At risus viverra adipiscing at in tellus integer. Pharetra sit amet aliquam id diam maecenas. Malesuada nunc vel risus commodo viverra maecenas accumsan lacus vel. Pharetra et ultrices\n neque ornare aenean euismod elementum nisi quis. Ut porttitor leo a diam sollicitudin. Est ultricies integer quis auctor. Natoque penatibus et magnis dis parturient. Sapien nec sagittis aliquam malesuada bibendum arcu vitae elementum curabitur. Elit\n eget gravida cum sociis. Placerat duis ultricies lacus sed turpis tincidunt id. Sit amet mattis vulputate enim nulla. In hac habitasse platea dictumst. Vulputate dignissim suspendisse in est. Est ultricies integer quis auctor elit sed vulputate mi\n sit. Ultricies tristique nulla aliquet enim tortor. Id neque aliquam vestibulum morbi blandit cursus. Volutpat blandit aliquam etiam erat. Erat pellentesque adipiscing commodo elit at imperdiet dui accumsan. Sed viverra tellus in hac habitasse. Elementum\n curabitur vitae nunc sed velit dignissim sodales. Eu turpis egestas pretium aenean pharetra magna. Arcu odio ut sem nulla pharetra diam sit amet. Aliquam sem et tortor consequat id porta nibh venenatis. Dictum non consectetur a erat nam at lectus\n urna duis. Tempus imperdiet nulla malesuada pellentesque elit eget gravida. Aliquet nec ullamcorper sit amet risus nullam eget felis. Posuere lorem ipsum dolor sit amet. Vel elit scelerisque mauris pellentesque pulvinar pellentesque habitant morbi\n tristique. Mauris a diam maecenas sed enim.\n </p>\n <p>\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Scelerisque mauris pellentesque pulvinar pellentesque habitant morbi tristique. Odio ut enim blandit volutpat maecenas volutpat\n blandit aliquam. Id semper risus in hendrerit gravida rutrum. Nunc scelerisque viverra mauris in aliquam sem fringilla ut morbi. Vestibulum sed arcu non odio euismod lacinia at quis risus. Facilisis volutpat est velit egestas dui id ornare arcu odio.\n Dignissim suspendisse in est ante in nibh mauris cursus. Eget mi proin sed libero enim sed faucibus turpis. Risus nullam eget felis eget. Risus commodo viverra maecenas accumsan lacus. Faucibus nisl tincidunt eget nullam non nisi est. Eleifend mi\n in nulla posuere sollicitudin aliquam. Id consectetur purus ut faucibus pulvinar elementum integer enim. Et leo duis ut diam quam nulla porttitor massa. Cras semper auctor neque vitae. Magna sit amet purus gravida quis blandit turpis. Egestas diam\n in arcu cursus. Amet mattis vulputate enim nulla aliquet porttitor lacus luctus. Commodo viverra maecenas accumsan lacus vel facilisis volutpat est. Morbi tincidunt augue interdum velit euismod in pellentesque massa placerat. Sed arcu non odio euismod\n lacinia. Pellentesque pulvinar pellentesque habitant morbi tristique senectus. Mi bibendum neque egestas congue. Justo nec ultrices dui sapien eget mi proin sed libero. Senectus et netus et malesuada fames ac turpis egestas. Nisi scelerisque eu ultrices\n vitae auctor eu augue ut. Vitae et leo duis ut diam quam nulla porttitor massa. Nunc faucibus a pellentesque sit amet porttitor. Velit euismod in pellentesque massa. Commodo quis imperdiet massa tincidunt nunc pulvinar. Dui accumsan sit amet nulla\n facilisi morbi tempus. Eu volutpat odio facilisis mauris sit. At risus viverra adipiscing at in tellus integer. Pharetra sit amet aliquam id diam maecenas. Malesuada nunc vel risus commodo viverra maecenas accumsan lacus vel. Pharetra et ultrices\n neque ornare aenean euismod elementum nisi quis. Ut porttitor leo a diam sollicitudin. Est ultricies integer quis auctor. Natoque penatibus et magnis dis parturient. Sapien nec sagittis aliquam malesuada bibendum arcu vitae elementum curabitur. Elit\n eget gravida cum sociis. Placerat duis ultricies lacus sed turpis tincidunt id. Sit amet mattis vulputate enim nulla. In hac habitasse platea dictumst. Vulputate dignissim suspendisse in est. Est ultricies integer quis auctor elit sed vulputate mi\n sit. Ultricies tristique nulla aliquet enim tortor. Id neque aliquam vestibulum morbi blandit cursus. Volutpat blandit aliquam etiam erat. Erat pellentesque adipiscing commodo elit at imperdiet dui accumsan. Sed viverra tellus in hac habitasse. Elementum\n curabitur vitae nunc sed velit dignissim sodales. Eu turpis egestas pretium aenean pharetra magna. Arcu odio ut sem nulla pharetra diam sit amet. Aliquam sem et tortor consequat id porta nibh venenatis. Dictum non consectetur a erat nam at lectus\n urna duis. Tempus imperdiet nulla malesuada pellentesque elit eget gravida. Aliquet nec ullamcorper sit amet risus nullam eget felis. Posuere lorem ipsum dolor sit amet. Vel elit scelerisque mauris pellentesque pulvinar pellentesque habitant morbi\n tristique. Mauris a diam maecenas sed enim.\n </p>\n</div>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6425639/"
] |
74,604,770
|
<p>Suppose I have this Matrix:</p>
<pre><code>julia> mat = [
1 2 3 4
5 6 7 8
9 8 7 6
];
</code></pre>
<p>Then I want to put slices of this Matrix into a 3D <code>Array</code> with types of <code>SMatrix{Int64}</code>, like below:</p>
<pre><code>julia> using StaticArrays
julia> arr = Array{SMatrix{Int64}, 3}(undef, 3, 2, 3);
julia> col_idx = [1, 2, 3];
julia> foreach(x->arr[:, :, x] = mat[:, x:x+1], col_idx)
ERROR: MethodError: Cannot `convert` an object of type
Int64 to an object of type
SMatrix{Int64}
Closest candidates are:
convert(::Type{T}, ::LinearAlgebra.Factorization) where T<:AbstractArray at C:\Users\JUL\.julia\juliaup\julia-1.8.3+0.x64\share\julia\stdlib\v1.8\LinearAlgebra\src\factorization.jl:58
convert(::Type{SA}, ::Tuple) where SA<:StaticArray at C:\Users\JUL\.julia\packages\StaticArrays\x7lS0\src\convert.jl:179
convert(::Type{SA}, ::SA) where SA<:StaticArray at C:\Users\JUL\.julia\packages\StaticArrays\x7lS0\src\convert.jl:178
...
Stacktrace:
[1] setindex!
@ .\array.jl:968 [inlined]
[2] macro expansion
@ .\multidimensional.jl:946 [inlined]
[3] macro expansion
@ .\cartesian.jl:64 [inlined]
[4] macro expansion
@ .\multidimensional.jl:941 [inlined]
[5] _unsafe_setindex!(::IndexLinear, ::Array{SMatrix{Int64}, 3}, ::Matrix{Int64}, ::Base.Slice{Base.OneTo{Int64}}, ::Base.Slice{Base.OneTo{Int64}}, ::Int64)
@ Base .\multidimensional.jl:953
[6] _setindex!
@ .\multidimensional.jl:930 [inlined]
[7] setindex!(::Array{SMatrix{Int64}, 3}, ::Matrix{Int64}, ::Function, ::Function, ::Int64)
@ Base .\abstractarray.jl:1344
[8] (::var"#5#6")(x::Int64)
@ Main .\REPL[20]:1
[9] foreach(f::var"#5#6", itr::Vector{Int64})
@ Base .\abstractarray.jl:2774
[10] top-level scope
@ REPL[20]:1
</code></pre>
<p>How can I achieve it?</p>
<p>P.S.:<br />
This is just a minimal and reproducible example. In the practical sense, I have a size of <code>(10, 10, 2000)</code> for <code>arr</code> and a big size for <code>mat</code> as well (<code>10x2000</code>, I guess)!</p>
|
[
{
"answer_id": 74605145,
"author": "AboAmmar",
"author_id": 3943170,
"author_profile": "https://Stackoverflow.com/users/3943170",
"pm_score": 2,
"selected": false,
"text": "mat = [ 1 2 3 4\n 5 6 7 8\n 9 8 7 6 ];\n\nusing StaticArrays\n\ncol_idx = [1, 2, 3];\n\narr = [SMatrix{3,2}(mat[:, x:x+1]) for x in col_idx]\n3-element Vector{SMatrix{3, 2, Int64, 6}}:\n [1 2; 5 6; 9 8]\n [2 3; 6 7; 8 7]\n [3 4; 7 8; 7 6]\n"
},
{
"answer_id": 74605405,
"author": "Shayan",
"author_id": 11747148,
"author_profile": "https://Stackoverflow.com/users/11747148",
"pm_score": 2,
"selected": false,
"text": "julia> using StaticArrays\n\njulia> mat = [\n 1 2 3 4\n 5 6 7 8\n 9 8 7 6\n ];\n\njulia> arr = Array{Int64, 3}(undef, 3, 2, 3);\n\njulia> foreach(x->arr[:, :, x] = mat[:, x:x+1], [1, 2, 3]);\n\njulia> sarr = SArray{Tuple{3, 2, 3}}(arr)\n3×2×3 SArray{Tuple{3, 2, 3}, Int64, 3, 18} with indices SOneTo(3)×SOneTo(2)×SOneTo(3):\n[:, :, 1] =\n 1 2\n 5 6\n 9 8\n\n[:, :, 2] =\n 2 3\n 6 7\n 8 7\n\n[:, :, 3] =\n 3 4\n 7 8\n 7 6\n\njulia> typeof(sarr[:, :, 1])\nSMatrix{3, 2, Int64, 6} (alias for SArray{Tuple{3, 2}, Int64, 2, 6})\n Array SArray julia> mat = rand(10, 2000);\n\njulia> arr = Array{Float64, 3}(undef, 10, 2, 1999);\n\njulia> foreach(x->arr[:, :, x] = mat[:, x:x+1], 1:1999);\n\njulia> sarr = SArray{Tuple{10, 2, 1999}}(arr);\n"
},
{
"answer_id": 74615527,
"author": "Dan Getz",
"author_id": 3580870,
"author_profile": "https://Stackoverflow.com/users/3580870",
"pm_score": 0,
"selected": false,
"text": "BlockArrays.jl BlockArrays using StaticArrays, BlockArrays\n\nmat = rand(10,2000) # random demo matrix\n\n# make all the slice SArrays\narr = [SArray{Tuple{10,2,1}, Float64, 3}(mat[:,i:i+1])\n for i=1:1999]\narr = reshape(arr,1,1,1999)\n\n# glue them into a BlockArray\nbricked = mortar(arr)\n julia> size(bricked)\n(10, 2, 1999)\n\njulia> bricked[:,:,25]\n1×1-blocked 10×2 BlockMatrix{Float64}:\n 0.265972 0.258414 \n 0.396142 0.863366 \n 0.41708 0.648276 \n 0.960283 0.773064 \n 0.62513 0.268989 \n 0.132796 0.0493077\n 0.844674 0.791772 \n 0.59638 0.0769661\n 0.221536 0.388623 \n 0.595742 0.50732 \n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20407495/"
] |
74,604,782
|
<p>I have data like this my table</p>
<p>2020-01-01 H</p>
<p>2020-01-02 B</p>
<p>2020-01-03 B</p>
<p>2020-01-04 B</p>
<p>.</p>
<p>2020-01-29 B</p>
<p>2020-01-30 H</p>
<p>2020-01-31 H</p>
<p>2020-01-02 H</p>
<p>2020-02-02 H</p>
<p>2020-02-03 B</p>
<p>2020-02-04 B</p>
<p>2020-02-05 B</p>
<p>.</p>
<p>now my problem is in the current month i need to check third business day i.e in this case 2020-02-05 i need to get last business day of last month. i.e.2020-01-29</p>
|
[
{
"answer_id": 74605145,
"author": "AboAmmar",
"author_id": 3943170,
"author_profile": "https://Stackoverflow.com/users/3943170",
"pm_score": 2,
"selected": false,
"text": "mat = [ 1 2 3 4\n 5 6 7 8\n 9 8 7 6 ];\n\nusing StaticArrays\n\ncol_idx = [1, 2, 3];\n\narr = [SMatrix{3,2}(mat[:, x:x+1]) for x in col_idx]\n3-element Vector{SMatrix{3, 2, Int64, 6}}:\n [1 2; 5 6; 9 8]\n [2 3; 6 7; 8 7]\n [3 4; 7 8; 7 6]\n"
},
{
"answer_id": 74605405,
"author": "Shayan",
"author_id": 11747148,
"author_profile": "https://Stackoverflow.com/users/11747148",
"pm_score": 2,
"selected": false,
"text": "julia> using StaticArrays\n\njulia> mat = [\n 1 2 3 4\n 5 6 7 8\n 9 8 7 6\n ];\n\njulia> arr = Array{Int64, 3}(undef, 3, 2, 3);\n\njulia> foreach(x->arr[:, :, x] = mat[:, x:x+1], [1, 2, 3]);\n\njulia> sarr = SArray{Tuple{3, 2, 3}}(arr)\n3×2×3 SArray{Tuple{3, 2, 3}, Int64, 3, 18} with indices SOneTo(3)×SOneTo(2)×SOneTo(3):\n[:, :, 1] =\n 1 2\n 5 6\n 9 8\n\n[:, :, 2] =\n 2 3\n 6 7\n 8 7\n\n[:, :, 3] =\n 3 4\n 7 8\n 7 6\n\njulia> typeof(sarr[:, :, 1])\nSMatrix{3, 2, Int64, 6} (alias for SArray{Tuple{3, 2}, Int64, 2, 6})\n Array SArray julia> mat = rand(10, 2000);\n\njulia> arr = Array{Float64, 3}(undef, 10, 2, 1999);\n\njulia> foreach(x->arr[:, :, x] = mat[:, x:x+1], 1:1999);\n\njulia> sarr = SArray{Tuple{10, 2, 1999}}(arr);\n"
},
{
"answer_id": 74615527,
"author": "Dan Getz",
"author_id": 3580870,
"author_profile": "https://Stackoverflow.com/users/3580870",
"pm_score": 0,
"selected": false,
"text": "BlockArrays.jl BlockArrays using StaticArrays, BlockArrays\n\nmat = rand(10,2000) # random demo matrix\n\n# make all the slice SArrays\narr = [SArray{Tuple{10,2,1}, Float64, 3}(mat[:,i:i+1])\n for i=1:1999]\narr = reshape(arr,1,1,1999)\n\n# glue them into a BlockArray\nbricked = mortar(arr)\n julia> size(bricked)\n(10, 2, 1999)\n\njulia> bricked[:,:,25]\n1×1-blocked 10×2 BlockMatrix{Float64}:\n 0.265972 0.258414 \n 0.396142 0.863366 \n 0.41708 0.648276 \n 0.960283 0.773064 \n 0.62513 0.268989 \n 0.132796 0.0493077\n 0.844674 0.791772 \n 0.59638 0.0769661\n 0.221536 0.388623 \n 0.595742 0.50732 \n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12177405/"
] |
74,604,790
|
<p>I need some help optimising a function. I'm aware that an apply function could speed this up, but I've never learned to use that family of functions properly and can't find advice online that I can follow easily to convert this ...</p>
<p>I have two data frames. They look like this (but each has >1 million rows).</p>
<pre><code>df.DP:
CHR POS
12 463
12 5412
12 76123
431 276
431 200187
8521 23
8521 2001
df.mask:
CHR START END
10 67 876
12 4321 8724
12 8742 8910
277 10293 10599
8521 1068 3233
</code></pre>
<p>What I want do do is add a column to df.DP which indicates whether each row matching a CHR value from df.mask also has a POS value that is greater than df.mask START and lower than df.mask END. For example...</p>
<pre><code>result:
CHR POS mask
12 463 0
12 5412 1
12 76123 0
431 276 0
431 200187 0
8521 23 0
8521 2001 1
</code></pre>
<p>This is the function I've written:</p>
<pre><code>index.masked <- function(df.DP, df.mask){
#Create all 0s masked index column
df.DP$masked = 0
#Iterate over df
for(i in 1:nrow(df.DP)){
#Report progress
print(i)
#Check if df.DP$CHR[i] is in df.mask$CHR
if(df.DP$CHR[i] %in% df.mask$CHR){
#Check if ith SNP is within masked range
if(nrow(df.mask[which(df.mask$CHR == df.DP$CHR[i] &
df.mask$START < df.DP$POS[i] &
df.mask$END > df.DP$POS[i]),]) > 0){
#Report progress
print("Ding!")
#Set index column to 1
df.DP$masked[i] <- 1
}
}
}
#Return df.DP
return(df.DP)
}
</code></pre>
<p>Basically this is horribly slow. As I've said, each data frame has > 1 million rows. On top of that, I have multiple data frames on which I need to perform this operation.</p>
<p>If anyone could please show me how to make this faster I would be very grateful.</p>
<p>Here is some code to generate dummy data...</p>
<pre><code>test.DP <- data.frame(CHR = c("12", "12", "23", "23", "23"),
POS = c(245, 6542, 12, 564, 1874))
test.mask <- data.frame(CHR = c("12", "13", "23"),
START = c(150, 717, 550),
END = c(270, 871, 599))
</code></pre>
<p>When I run my function on this dummy data it works fine.</p>
<pre><code>test1 <- index.masked(test.DP, test.mask)
> test1
CHR POS masked
1 12 245 1
2 12 6542 0
3 23 12 0
4 23 564 1
5 23 1874 0
</code></pre>
<p>With > 1M rows in each data frame, this is too slow though.</p>
<p>I have searched extensively and while I can find plenty of posts here asking for help with similar problems, I'm so unfamiliar with the apply functions and other approaches to solving things that I just can't follow what's been done and apply (no pun intended) it to my own situation.</p>
<p>Any help would be deeply appreciated.</p>
|
[
{
"answer_id": 74605145,
"author": "AboAmmar",
"author_id": 3943170,
"author_profile": "https://Stackoverflow.com/users/3943170",
"pm_score": 2,
"selected": false,
"text": "mat = [ 1 2 3 4\n 5 6 7 8\n 9 8 7 6 ];\n\nusing StaticArrays\n\ncol_idx = [1, 2, 3];\n\narr = [SMatrix{3,2}(mat[:, x:x+1]) for x in col_idx]\n3-element Vector{SMatrix{3, 2, Int64, 6}}:\n [1 2; 5 6; 9 8]\n [2 3; 6 7; 8 7]\n [3 4; 7 8; 7 6]\n"
},
{
"answer_id": 74605405,
"author": "Shayan",
"author_id": 11747148,
"author_profile": "https://Stackoverflow.com/users/11747148",
"pm_score": 2,
"selected": false,
"text": "julia> using StaticArrays\n\njulia> mat = [\n 1 2 3 4\n 5 6 7 8\n 9 8 7 6\n ];\n\njulia> arr = Array{Int64, 3}(undef, 3, 2, 3);\n\njulia> foreach(x->arr[:, :, x] = mat[:, x:x+1], [1, 2, 3]);\n\njulia> sarr = SArray{Tuple{3, 2, 3}}(arr)\n3×2×3 SArray{Tuple{3, 2, 3}, Int64, 3, 18} with indices SOneTo(3)×SOneTo(2)×SOneTo(3):\n[:, :, 1] =\n 1 2\n 5 6\n 9 8\n\n[:, :, 2] =\n 2 3\n 6 7\n 8 7\n\n[:, :, 3] =\n 3 4\n 7 8\n 7 6\n\njulia> typeof(sarr[:, :, 1])\nSMatrix{3, 2, Int64, 6} (alias for SArray{Tuple{3, 2}, Int64, 2, 6})\n Array SArray julia> mat = rand(10, 2000);\n\njulia> arr = Array{Float64, 3}(undef, 10, 2, 1999);\n\njulia> foreach(x->arr[:, :, x] = mat[:, x:x+1], 1:1999);\n\njulia> sarr = SArray{Tuple{10, 2, 1999}}(arr);\n"
},
{
"answer_id": 74615527,
"author": "Dan Getz",
"author_id": 3580870,
"author_profile": "https://Stackoverflow.com/users/3580870",
"pm_score": 0,
"selected": false,
"text": "BlockArrays.jl BlockArrays using StaticArrays, BlockArrays\n\nmat = rand(10,2000) # random demo matrix\n\n# make all the slice SArrays\narr = [SArray{Tuple{10,2,1}, Float64, 3}(mat[:,i:i+1])\n for i=1:1999]\narr = reshape(arr,1,1,1999)\n\n# glue them into a BlockArray\nbricked = mortar(arr)\n julia> size(bricked)\n(10, 2, 1999)\n\njulia> bricked[:,:,25]\n1×1-blocked 10×2 BlockMatrix{Float64}:\n 0.265972 0.258414 \n 0.396142 0.863366 \n 0.41708 0.648276 \n 0.960283 0.773064 \n 0.62513 0.268989 \n 0.132796 0.0493077\n 0.844674 0.791772 \n 0.59638 0.0769661\n 0.221536 0.388623 \n 0.595742 0.50732 \n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20626103/"
] |
74,604,805
|
<p>I have a complicated code of several classes and functions. one of the functions is called n times and I need to do something specific in the last call of the function. It is too complicated to use the iteratble of the for loop.
I need something that knows that this is the last call of the function, then it does what I want
something like that</p>
<blockquote>
<p>def myfunc(y):
x = y*2</p>
</blockquote>
<blockquote>
<p>if last_call:
x = y*3</p>
</blockquote>
<p>is it possible?</p>
<p>I tried to use the items in the for loop that calls the function but because the code has several classes with several functions, it did not work as there are detailed requirements to call the functions and these requirements contradict what I tried to do.
Thanks</p>
|
[
{
"answer_id": 74604850,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 1,
"selected": false,
"text": "def myfunc(y, z=2):\n x = y * z\n ...\n for i in range(10):\n myfunc(i, 2 if range < 9 else 3)\n for i in range(9):\n myfunc(i)\nmyfunc(10, 3)\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20281708/"
] |
74,604,857
|
<p>I am using Postgresql 13 and I have a table that looks something like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>event_id</th>
<th>timestamp</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2022-11-28 00:00:00</td>
</tr>
<tr>
<td>1</td>
<td>2022-11-28 00:00:10</td>
</tr>
<tr>
<td>2</td>
<td>2022-11-28 00:00:20</td>
</tr>
<tr>
<td>2</td>
<td>2022-11-28 00:00:30</td>
</tr>
<tr>
<td>2</td>
<td>2022-11-28 00:00:40</td>
</tr>
<tr>
<td>3</td>
<td>2022-11-28 00:00:50</td>
</tr>
<tr>
<td>3</td>
<td>2022-11-28 00:01:10</td>
</tr>
<tr>
<td>1</td>
<td>2022-11-28 00:01:20</td>
</tr>
<tr>
<td>2</td>
<td>2022-11-28 00:01:30</td>
</tr>
<tr>
<td>2</td>
<td>2022-11-28 00:01:40</td>
</tr>
<tr>
<td>3</td>
<td>2022-11-28 00:01:50</td>
</tr>
<tr>
<td>3</td>
<td>2022-11-28 00:02:10</td>
</tr>
<tr>
<td>3</td>
<td>2022-11-28 00:02:20</td>
</tr>
<tr>
<td>4</td>
<td>2022-11-28 00:02:30</td>
</tr>
</tbody>
</table>
</div>
<p>I need to get monotonically increasing values for the event_id column based on the timestamp order. So the above table will become something like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>event_id</th>
<th>timestamp</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2022-11-28 00:00:00</td>
</tr>
<tr>
<td>1</td>
<td>2022-11-28 00:00:10</td>
</tr>
<tr>
<td>2</td>
<td>2022-11-28 00:00:20</td>
</tr>
<tr>
<td>2</td>
<td>2022-11-28 00:00:30</td>
</tr>
<tr>
<td>2</td>
<td>2022-11-28 00:00:40</td>
</tr>
<tr>
<td>3</td>
<td>2022-11-28 00:00:50</td>
</tr>
<tr>
<td>3</td>
<td>2022-11-28 00:01:10</td>
</tr>
<tr>
<td>4</td>
<td>2022-11-28 00:01:20</td>
</tr>
<tr>
<td>5</td>
<td>2022-11-28 00:01:30</td>
</tr>
<tr>
<td>5</td>
<td>2022-11-28 00:01:40</td>
</tr>
<tr>
<td>6</td>
<td>2022-11-28 00:01:50</td>
</tr>
<tr>
<td>6</td>
<td>2022-11-28 00:02:10</td>
</tr>
<tr>
<td>6</td>
<td>2022-11-28 00:02:20</td>
</tr>
<tr>
<td>7</td>
<td>2022-11-28 00:02:30</td>
</tr>
</tbody>
</table>
</div>
<p>Ideally I'd need this done in a single select statement, I tried a bunch of different approaches but nothing led me even close to what I need. Any suggestion? Thanks</p>
|
[
{
"answer_id": 74604850,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 1,
"selected": false,
"text": "def myfunc(y, z=2):\n x = y * z\n ...\n for i in range(10):\n myfunc(i, 2 if range < 9 else 3)\n for i in range(9):\n myfunc(i)\nmyfunc(10, 3)\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13765741/"
] |
74,604,897
|
<p>I have a column defined as TO_VARCHAR(START_TIME, 'yyyy-mm-dd hh')</p>
<p>I would like to use this column as an X-Axis in a Snowsight dashboard but it won't let me do that...
Any particular reason I am missing?</p>
|
[
{
"answer_id": 74609077,
"author": "Felipe Hoffa",
"author_id": 132438,
"author_profile": "https://Stackoverflow.com/users/132438",
"pm_score": 0,
"selected": false,
"text": "with data(t, d) as (\n select * from values('2020-10-10 03:03:01', 1), ('2020-10-11 05:03:01', 2), ('2020-10-13 08:03:01', 6)\n)\n\nselect TO_VARCHAR(t::timestamp, 'yyyy-mm-dd hh') ts, d\nfrom data\n with data(t, d) as (\n select * from values('2020-10-10 03:03:01', 1), ('2020-10-11 05:03:01', 2), ('2020-10-13 08:03:01', 6)\n)\n\nselect TO_VARCHAR(t::timestamp, 'yyyy-mm-dd hh:mi:ss') ts, d\nfrom data\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10331351/"
] |
74,604,906
|
<p>I have the following textfile from an LFT command.</p>
<pre><code>2 [14080] [100.0.0.0 - 100.255.255.255] 100.5.254.150 6.3ms
3 [14080] [100.0.0.0 - 100.255.255.255] 100.8.254.149 5.7ms
4 [15169] [GOOGLE] 142.250.164.139 17.5ms
5 [15169] [GOOGLE] 142.250.164.138 10.9ms
6 [15169] [GOOGLE] 72.14.233.63 12.8ms
7 [15169] [GOOGLE] 142.250.210.131 9.6ms
8 [15169] [GOOGLE] 142.250.78.78 11.9ms
</code></pre>
<p>Where each space could be understood like a field.
I tried convert this textfile in a JSON file but I have that:</p>
<pre><code>{
"emp1": {
"Jumps": "2",
"System": "[14080]",
"Adress": "[100.0.0.0",
"IP": "-",
"Delay": "100.255.255.255] 100.5.254.150 6.3ms"
},
"emp2": {
"Jumps": "3",
"System": "[14080]",
"Adress": "[100.0.0.0",
"IP": "-",
"Delay": "100.255.255.255] 100.5.254.150 5.7ms"
},
"emp3": {
"Jumps": "4",
"System": "[15169]",
"Adress": "[GOOGLE]",
"IP": "142.250.164.139",
"Delay": "17.5ms"
},
"emp4": {
"Jumps": "5",
"System": "[15169]",
"Adress": "[GOOGLE]",
"IP": "142.250.164.138",
"Delay": "10.9ms"
},
"emp5": {
"Jumps": "6",
"System": "[15169]",
"Adress": "[GOOGLE]",
"IP": "72.14.233.63",
"Delay": "12.8ms"
},
"emp6": {
"Jumps": "7",
"System": "[15169]",
"Adress": "[GOOGLE]",
"IP": "142.250.210.131",
"Delay": "9.6ms"
},
"emp7": {
"Jumps": "8",
"System": "[15169]",
"Adress": "[GOOGLE]",
"IP": "142.250.78.78",
"Delay": "11.9ms"
}
}
</code></pre>
<p>As you can see, the first two fields in the "Delay" section are worng.</p>
<p>How I can fix it?
What can I do for that?</p>
<p>I tried to use pandas too but what I get is the same answer:</p>
<p><code>data = pd.read_csv("file.txt", sep=r'\s+')</code>
<a href="https://i.stack.imgur.com/hfPC8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hfPC8.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74609077,
"author": "Felipe Hoffa",
"author_id": 132438,
"author_profile": "https://Stackoverflow.com/users/132438",
"pm_score": 0,
"selected": false,
"text": "with data(t, d) as (\n select * from values('2020-10-10 03:03:01', 1), ('2020-10-11 05:03:01', 2), ('2020-10-13 08:03:01', 6)\n)\n\nselect TO_VARCHAR(t::timestamp, 'yyyy-mm-dd hh') ts, d\nfrom data\n with data(t, d) as (\n select * from values('2020-10-10 03:03:01', 1), ('2020-10-11 05:03:01', 2), ('2020-10-13 08:03:01', 6)\n)\n\nselect TO_VARCHAR(t::timestamp, 'yyyy-mm-dd hh:mi:ss') ts, d\nfrom data\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16459368/"
] |
74,604,911
|
<p>I have the following wizard structure [ field name and data type ]</p>
<ul>
<li>Type :- Selection :- Type 1 and Type 2</li>
<li>Route :- One2many</li>
</ul>
<p>When Users select Type 1, I want to allow them to add records in the Route table. While on the Type 2, I want to make Route readonly and don't allow deletion. I will fill it with default route information.</p>
<p>I write following code in the .xml file:</p>
<pre><code><group attrs="{'invisible': [('type', '=', 'type_2')]}">
<field name="route_ids" string="Testing 1">
<tree>
<field name="x"/>
<field name="y"/>
</tree>
</field>
</group>
<group attrs="{'invisible': [('type', '=', 'type_1')]}">
<field name="route_ids" string="Testing 2">
<tree delete="false" create="false">
<field name="x"/>
<field name="y"/>
</tree>
</field>
</group>
</code></pre>
<p>I notice that based on Type selection, route field label is changing but tree attributes (readonly, delete) remain same / whatever set in the last.</p>
<p>Expectation:</p>
<p>One2many field attribute should be refreshed instead of keeping last.</p>
<p>I resolved it by adding a new field and onchange method but I'm looking for a better approach to resolve it.</p>
|
[
{
"answer_id": 74609077,
"author": "Felipe Hoffa",
"author_id": 132438,
"author_profile": "https://Stackoverflow.com/users/132438",
"pm_score": 0,
"selected": false,
"text": "with data(t, d) as (\n select * from values('2020-10-10 03:03:01', 1), ('2020-10-11 05:03:01', 2), ('2020-10-13 08:03:01', 6)\n)\n\nselect TO_VARCHAR(t::timestamp, 'yyyy-mm-dd hh') ts, d\nfrom data\n with data(t, d) as (\n select * from values('2020-10-10 03:03:01', 1), ('2020-10-11 05:03:01', 2), ('2020-10-13 08:03:01', 6)\n)\n\nselect TO_VARCHAR(t::timestamp, 'yyyy-mm-dd hh:mi:ss') ts, d\nfrom data\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2926754/"
] |
74,604,923
|
<p>How to write a function to the game where you can run from the fight and so it would return your position to the state before the battle, because with my current code it returns you to the beginning of the game.</p>
<p>This is my code</p>
<pre><code>def run():
runnum = random.randitn(1, 10)
if runnum <= 4:
print("Success!")
option = input(" ")
start1()
else runnum > 7:
print("You can't run!")
option = input(" ")
fight()
</code></pre>
|
[
{
"answer_id": 74609077,
"author": "Felipe Hoffa",
"author_id": 132438,
"author_profile": "https://Stackoverflow.com/users/132438",
"pm_score": 0,
"selected": false,
"text": "with data(t, d) as (\n select * from values('2020-10-10 03:03:01', 1), ('2020-10-11 05:03:01', 2), ('2020-10-13 08:03:01', 6)\n)\n\nselect TO_VARCHAR(t::timestamp, 'yyyy-mm-dd hh') ts, d\nfrom data\n with data(t, d) as (\n select * from values('2020-10-10 03:03:01', 1), ('2020-10-11 05:03:01', 2), ('2020-10-13 08:03:01', 6)\n)\n\nselect TO_VARCHAR(t::timestamp, 'yyyy-mm-dd hh:mi:ss') ts, d\nfrom data\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20522693/"
] |
74,604,941
|
<p>While going through Firebase's documentation for geohashing,
Im using modular SDK, and I tried converting the namespace code,
but I was encountering a <code>TypeError that q.get is not a function</code></p>
<pre><code>// Find cities within Dkm of [lat, lng]
const center = [Number(lat), Number(lng)];
const radiusInM = dist * 1000;
// Each item in 'bounds' represents a startAt/endAt pair. We have to issue
// a separate query for each pair. There can be up to 9 pairs of bounds
// depending on overlap, but in most cases there are 4.
const bounds = geohashQueryBounds(center, radiusInM);
const promises = [];
for (const b of bounds) {
const q = query(
collection(db, USERS_COL),
orderBy('geohash'),
startAt(b[0]),
endAt(b[1])
);
promises.push(q.get());
}
</code></pre>
<p><a href="https://firebase.google.com/docs/firestore/solutions/geoqueries#query_geohashes" rel="nofollow noreferrer">Documentation Link</a></p>
<p>Documentation code:</p>
<pre><code>st radiusInM = 50 * 1000;
// Each item in 'bounds' represents a startAt/endAt pair. We have to issue
// a separate query for each pair. There can be up to 9 pairs of bounds
// depending on overlap, but in most cases there are 4.
const bounds = geofire.geohashQueryBounds(center, radiusInM);
const promises = [];
for (const b of bounds) {
const q = db.collection('cities')
.orderBy('geohash')
.startAt(b[0])
.endAt(b[1]);
promises.push(q.get());
}
</code></pre>
|
[
{
"answer_id": 74605014,
"author": "Frank van Puffelen",
"author_id": 209103,
"author_profile": "https://Stackoverflow.com/users/209103",
"pm_score": 2,
"selected": true,
"text": "getDocs(q)\n"
},
{
"answer_id": 74605632,
"author": "Dipanshu",
"author_id": 16869352,
"author_profile": "https://Stackoverflow.com/users/16869352",
"pm_score": 0,
"selected": false,
"text": "// Find cities within dist km of [lat, lng]\n const center = [Number(lat), Number(lng)];\n const radiusInM = dist * 1000;\n // Each item in 'bounds' represents a startAt/endAt pair. We have to issue\n // a separate query for each pair. There can be up to 9 pairs of bounds\n // depending on overlap, but in most cases there are 4.\n const bounds = geohashQueryBounds(center, radiusInM);\n const promises = [];\n\n for (const b of bounds) {\n const q = query(\n collection(db, USERS_COL),\n orderBy('geohash'),\n startAt(b[0]),\n endAt(b[1])\n );\n const querySnapshot = await getDocs(q);\n querySnapshot.forEach((doc) => {\n // doc.data() is never undefined for query doc snapshots\n promises.push(doc.data());\n });\n }\n\n var finalResult = [];\n // Collect all the query results together into a single list\n await Promise.all(promises)\n .then((snapshots) => {\n const matchingDocs = [];\n\n for (const snap of snapshots) {\n // We have to filter out a few false positives due to GeoHash\n // accuracy, but most will match\n const lat = snap.lat;\n const lng = snap.lng;\n const distanceInKm = distanceBetween([lat, lng], center);\n const distanceInM = distanceInKm * 1000;\n if (distanceInM <= radiusInM) {\n matchingDocs.push(snap);\n }\n }\n console.log('val', matchingDocs);\n return matchingDocs;\n })\n .then((matchingDocs) => {\n finalResult = matchingDocs;\n // return matchingDocs;\n });\n return finalResult;\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16869352/"
] |
74,604,996
|
<p>I want to set a the text of a paragraph element via JS. The string contains <strong>line breaks</strong> (\n), but they are <strong>not visible in the paragraph</strong>.</p>
<p>This is the <strong>desired result</strong>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
Lorem ipsum dolor sit amet,<br>
consetetur sadipscing elitr,<br>
sed diam nonumy <br> eirmod tempor...
</p></code></pre>
</div>
</div>
</p>
<p>This it how it looks when I <strong>set the text via JS</strong>:</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>document.getElementById("text").textContent =
"Lorem ipsum dolor sit amet,\n" +
"consetetur sadipscing elitr,\n" +
"sed diam nonumy \n eirmod tempor...";</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="text"></p></code></pre>
</div>
</div>
</p>
<p>How can I <strong>achieve the behaviour of the first example with JS?</strong></p>
|
[
{
"answer_id": 74605014,
"author": "Frank van Puffelen",
"author_id": 209103,
"author_profile": "https://Stackoverflow.com/users/209103",
"pm_score": 2,
"selected": true,
"text": "getDocs(q)\n"
},
{
"answer_id": 74605632,
"author": "Dipanshu",
"author_id": 16869352,
"author_profile": "https://Stackoverflow.com/users/16869352",
"pm_score": 0,
"selected": false,
"text": "// Find cities within dist km of [lat, lng]\n const center = [Number(lat), Number(lng)];\n const radiusInM = dist * 1000;\n // Each item in 'bounds' represents a startAt/endAt pair. We have to issue\n // a separate query for each pair. There can be up to 9 pairs of bounds\n // depending on overlap, but in most cases there are 4.\n const bounds = geohashQueryBounds(center, radiusInM);\n const promises = [];\n\n for (const b of bounds) {\n const q = query(\n collection(db, USERS_COL),\n orderBy('geohash'),\n startAt(b[0]),\n endAt(b[1])\n );\n const querySnapshot = await getDocs(q);\n querySnapshot.forEach((doc) => {\n // doc.data() is never undefined for query doc snapshots\n promises.push(doc.data());\n });\n }\n\n var finalResult = [];\n // Collect all the query results together into a single list\n await Promise.all(promises)\n .then((snapshots) => {\n const matchingDocs = [];\n\n for (const snap of snapshots) {\n // We have to filter out a few false positives due to GeoHash\n // accuracy, but most will match\n const lat = snap.lat;\n const lng = snap.lng;\n const distanceInKm = distanceBetween([lat, lng], center);\n const distanceInM = distanceInKm * 1000;\n if (distanceInM <= radiusInM) {\n matchingDocs.push(snap);\n }\n }\n console.log('val', matchingDocs);\n return matchingDocs;\n })\n .then((matchingDocs) => {\n finalResult = matchingDocs;\n // return matchingDocs;\n });\n return finalResult;\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14974627/"
] |
74,605,008
|
<p><a href="https://i.stack.imgur.com/fiiiz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fiiiz.png" alt="enter image description here" /></a></p>
<p>just explanation in a nutshell would help about this chart
I am not able to understand the illustrations of this data value which is a number</p>
|
[
{
"answer_id": 74605014,
"author": "Frank van Puffelen",
"author_id": 209103,
"author_profile": "https://Stackoverflow.com/users/209103",
"pm_score": 2,
"selected": true,
"text": "getDocs(q)\n"
},
{
"answer_id": 74605632,
"author": "Dipanshu",
"author_id": 16869352,
"author_profile": "https://Stackoverflow.com/users/16869352",
"pm_score": 0,
"selected": false,
"text": "// Find cities within dist km of [lat, lng]\n const center = [Number(lat), Number(lng)];\n const radiusInM = dist * 1000;\n // Each item in 'bounds' represents a startAt/endAt pair. We have to issue\n // a separate query for each pair. There can be up to 9 pairs of bounds\n // depending on overlap, but in most cases there are 4.\n const bounds = geohashQueryBounds(center, radiusInM);\n const promises = [];\n\n for (const b of bounds) {\n const q = query(\n collection(db, USERS_COL),\n orderBy('geohash'),\n startAt(b[0]),\n endAt(b[1])\n );\n const querySnapshot = await getDocs(q);\n querySnapshot.forEach((doc) => {\n // doc.data() is never undefined for query doc snapshots\n promises.push(doc.data());\n });\n }\n\n var finalResult = [];\n // Collect all the query results together into a single list\n await Promise.all(promises)\n .then((snapshots) => {\n const matchingDocs = [];\n\n for (const snap of snapshots) {\n // We have to filter out a few false positives due to GeoHash\n // accuracy, but most will match\n const lat = snap.lat;\n const lng = snap.lng;\n const distanceInKm = distanceBetween([lat, lng], center);\n const distanceInM = distanceInKm * 1000;\n if (distanceInM <= radiusInM) {\n matchingDocs.push(snap);\n }\n }\n console.log('val', matchingDocs);\n return matchingDocs;\n })\n .then((matchingDocs) => {\n finalResult = matchingDocs;\n // return matchingDocs;\n });\n return finalResult;\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15989533/"
] |
74,605,010
|
<p>If you have this HTML:</p>
<pre><code><dl class="test">
<dt>key:</dt>
<dd>value</dd>
<dt>keyyy:</dt>
<dd>valueeeee</dd>
</dl>
</code></pre>
<p>how can you accomplish and structure up so the content looks like</p>
<pre><code>key: value
key: value
</code></pre>
<p>Tried #1:
With <strong>flex</strong> but it doesn't work because I'm only allowed to play with the HTML presented at the top, I can't add any divs or such if I don't do it through some css hack because the code is coming from another place.</p>
<p>Tried #2:
With <strong>grid</strong> but then the outcome looks like:
<a href="https://jsfiddle.net/fo6ckghd/2/" rel="nofollow noreferrer">https://jsfiddle.net/fo6ckghd/2/</a></p>
<p>its too much space between key and value and it doesnt get nice if the length is different on each key value pair.</p>
<p>Tried #3:</p>
<pre><code>dl
dt
display: inline-block;
dd
display: contents;
</code></pre>
<p>This did not work either because after first key:value
the second one would be the same line, I tried with ::before ::after
to add a new line but didnt succeed.</p>
|
[
{
"answer_id": 74605014,
"author": "Frank van Puffelen",
"author_id": 209103,
"author_profile": "https://Stackoverflow.com/users/209103",
"pm_score": 2,
"selected": true,
"text": "getDocs(q)\n"
},
{
"answer_id": 74605632,
"author": "Dipanshu",
"author_id": 16869352,
"author_profile": "https://Stackoverflow.com/users/16869352",
"pm_score": 0,
"selected": false,
"text": "// Find cities within dist km of [lat, lng]\n const center = [Number(lat), Number(lng)];\n const radiusInM = dist * 1000;\n // Each item in 'bounds' represents a startAt/endAt pair. We have to issue\n // a separate query for each pair. There can be up to 9 pairs of bounds\n // depending on overlap, but in most cases there are 4.\n const bounds = geohashQueryBounds(center, radiusInM);\n const promises = [];\n\n for (const b of bounds) {\n const q = query(\n collection(db, USERS_COL),\n orderBy('geohash'),\n startAt(b[0]),\n endAt(b[1])\n );\n const querySnapshot = await getDocs(q);\n querySnapshot.forEach((doc) => {\n // doc.data() is never undefined for query doc snapshots\n promises.push(doc.data());\n });\n }\n\n var finalResult = [];\n // Collect all the query results together into a single list\n await Promise.all(promises)\n .then((snapshots) => {\n const matchingDocs = [];\n\n for (const snap of snapshots) {\n // We have to filter out a few false positives due to GeoHash\n // accuracy, but most will match\n const lat = snap.lat;\n const lng = snap.lng;\n const distanceInKm = distanceBetween([lat, lng], center);\n const distanceInM = distanceInKm * 1000;\n if (distanceInM <= radiusInM) {\n matchingDocs.push(snap);\n }\n }\n console.log('val', matchingDocs);\n return matchingDocs;\n })\n .then((matchingDocs) => {\n finalResult = matchingDocs;\n // return matchingDocs;\n });\n return finalResult;\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9056339/"
] |
74,605,034
|
<blockquote>
<p>I am new in flutter, I am working on solving bugs in app. I want to print latitude and longitude of current user after 2 seconds, how can i do that?</p>
</blockquote>
<pre><code>void startTimer() {
const oneSec = const Duration(seconds: 2);
timer2 = new Timer.periodic(
oneSec,
(Timer timer) {
if (start == 0) {
timer.cancel();
setState(() {});
// });
} else {
// setState(() {
start--;
setState(() {
print("My current location ${homeMapCtrl!.userCurrentLatLng}");
});
// });
}
},
);
}
</code></pre>
<blockquote>
<p>I am using this method and i am calling it in Consumer but it always run upto 1 to 100 seconds.</p>
</blockquote>
|
[
{
"answer_id": 74605014,
"author": "Frank van Puffelen",
"author_id": 209103,
"author_profile": "https://Stackoverflow.com/users/209103",
"pm_score": 2,
"selected": true,
"text": "getDocs(q)\n"
},
{
"answer_id": 74605632,
"author": "Dipanshu",
"author_id": 16869352,
"author_profile": "https://Stackoverflow.com/users/16869352",
"pm_score": 0,
"selected": false,
"text": "// Find cities within dist km of [lat, lng]\n const center = [Number(lat), Number(lng)];\n const radiusInM = dist * 1000;\n // Each item in 'bounds' represents a startAt/endAt pair. We have to issue\n // a separate query for each pair. There can be up to 9 pairs of bounds\n // depending on overlap, but in most cases there are 4.\n const bounds = geohashQueryBounds(center, radiusInM);\n const promises = [];\n\n for (const b of bounds) {\n const q = query(\n collection(db, USERS_COL),\n orderBy('geohash'),\n startAt(b[0]),\n endAt(b[1])\n );\n const querySnapshot = await getDocs(q);\n querySnapshot.forEach((doc) => {\n // doc.data() is never undefined for query doc snapshots\n promises.push(doc.data());\n });\n }\n\n var finalResult = [];\n // Collect all the query results together into a single list\n await Promise.all(promises)\n .then((snapshots) => {\n const matchingDocs = [];\n\n for (const snap of snapshots) {\n // We have to filter out a few false positives due to GeoHash\n // accuracy, but most will match\n const lat = snap.lat;\n const lng = snap.lng;\n const distanceInKm = distanceBetween([lat, lng], center);\n const distanceInM = distanceInKm * 1000;\n if (distanceInM <= radiusInM) {\n matchingDocs.push(snap);\n }\n }\n console.log('val', matchingDocs);\n return matchingDocs;\n })\n .then((matchingDocs) => {\n finalResult = matchingDocs;\n // return matchingDocs;\n });\n return finalResult;\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17753629/"
] |
74,605,070
|
<p>I have the below class</p>
<pre><code>@Component
public class MyBean {
private int val1;
public MyBean(int val1) {
this.val1 = val1;
}
public int getVal1() {
return val1;
}
public void setVal1(int val1) {
this.val1 = val1;
}
}
</code></pre>
<p>I want to Autowire <code>Mybean</code> like below</p>
<pre><code>@Service
public class MyService
{
@Autowire
private MyBean myBean;
}
</code></pre>
<p>When i run i get the below error</p>
<blockquote>
<p>Parameter 0 of constructor MyBean required a bean of type 'int' that could not be found.</p>
</blockquote>
|
[
{
"answer_id": 74605014,
"author": "Frank van Puffelen",
"author_id": 209103,
"author_profile": "https://Stackoverflow.com/users/209103",
"pm_score": 2,
"selected": true,
"text": "getDocs(q)\n"
},
{
"answer_id": 74605632,
"author": "Dipanshu",
"author_id": 16869352,
"author_profile": "https://Stackoverflow.com/users/16869352",
"pm_score": 0,
"selected": false,
"text": "// Find cities within dist km of [lat, lng]\n const center = [Number(lat), Number(lng)];\n const radiusInM = dist * 1000;\n // Each item in 'bounds' represents a startAt/endAt pair. We have to issue\n // a separate query for each pair. There can be up to 9 pairs of bounds\n // depending on overlap, but in most cases there are 4.\n const bounds = geohashQueryBounds(center, radiusInM);\n const promises = [];\n\n for (const b of bounds) {\n const q = query(\n collection(db, USERS_COL),\n orderBy('geohash'),\n startAt(b[0]),\n endAt(b[1])\n );\n const querySnapshot = await getDocs(q);\n querySnapshot.forEach((doc) => {\n // doc.data() is never undefined for query doc snapshots\n promises.push(doc.data());\n });\n }\n\n var finalResult = [];\n // Collect all the query results together into a single list\n await Promise.all(promises)\n .then((snapshots) => {\n const matchingDocs = [];\n\n for (const snap of snapshots) {\n // We have to filter out a few false positives due to GeoHash\n // accuracy, but most will match\n const lat = snap.lat;\n const lng = snap.lng;\n const distanceInKm = distanceBetween([lat, lng], center);\n const distanceInM = distanceInKm * 1000;\n if (distanceInM <= radiusInM) {\n matchingDocs.push(snap);\n }\n }\n console.log('val', matchingDocs);\n return matchingDocs;\n })\n .then((matchingDocs) => {\n finalResult = matchingDocs;\n // return matchingDocs;\n });\n return finalResult;\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20626335/"
] |
74,605,111
|
<p>I have an WPF tooltip defined within a dictionary.xaml that I want to apply to all my items, labels, buttons, etc. I import this dictionary in my view.</p>
<pre><code><Style x:Key="{x:Type ToolTip}" TargetType="ToolTip">
<Setter Property="OverridesDefaultStyle" Value="true" />
<Setter Property="HorizontalOffset" Value="1" />
<Setter Property="VerticalOffset" Value="1" />
<Setter Property="Background" Value="White" />
<Setter Property="Foreground" Value="Black" />
<Setter Property="FontSize" Value="12" />
<Setter Property="FontFamily" Value="Segoe UI" />
<Setter Property="DataContext" Value="{Binding Path=PlacementTarget.DataContext, RelativeSource={x:Static RelativeSource.Self}}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ToolTip">
<Canvas Width="225" Height="131">
<Path x:Name="Container"
Canvas.Left="0"
Canvas.Top="0"
Margin="0"
Data="M8,7.41 L15.415,0 L22.83,7.41 L224,7.41 L224,130 L0,130 L0,7.41 L8,7.41"
Fill="{TemplateBinding Background}"
Stroke="Gray">
<Path.Effect>
<DropShadowEffect BlurRadius="10"
Opacity="0.5"
ShadowDepth="4" />
</Path.Effect>
</Path>
<TextBlock Canvas.Left="10"
Canvas.Top="10"
Width="100"
Height="65"
Text="{TemplateBinding Content}"
TextWrapping="WrapWithOverflow" />
</Canvas>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</code></pre>
<p>so I can use it as below:</p>
<pre><code> <Label x:Name="myLabel"
ToolTip="This is a custom tooltip for my label."
ToolTipClosing="tt_ToolTipClosing"/>
</code></pre>
<p>also I have other items:</p>
<pre><code> <Button x:Name="myBtn"
Tooltip="This is a custom tooltip for my button"
ToolTipClosing="tt_ToolTipClosing"/>
</code></pre>
<p>Tooltip is working fine, when I hover the mouse on it, the tooltip is shown.</p>
<p>Now I am trying to do below 2 things:</p>
<ol>
<li>Implement a tooltip closing event handler that works for all my items (labels, buttons, etc.)</li>
<li>Keep the tooltip always opened until user clicks on anywhere in the screen with the mouse if a property keepOpened is set to true. Otherwise, if keepOpened is set to false, it behaves as a normal tooltip, it closes automatically when mouse leaves item.</li>
</ol>
<p>In the code behind now I have below event handler (I have got this code from <a href="https://stackoverflow.com/a/28989388/1624552">here</a>):</p>
<pre><code> private void tt_ToolTipClosing(object sender, ToolTipEventArgs e)
{
if (keepOpened)
{
// TODO: Determine who is the sender, a label, a button, etc.
// We suppose in this example it is a label
Label myLabel = sender as Label;
ToolTip tt = myLabel.ToolTip as ToolTip;
if (tt.PlacementTarget == null)
{
tt.PlacementTarget = myLabel;
}
tt.IsOpen = true;
}
}
</code></pre>
<p>For first point, I guess I need to use a switch to determine if sender is a button, label, etc. and then get the tooltip by casting it. I do not know if there are any other better way to do it. If so, please tell me.</p>
<p>For second point, KeepOpened would be a property defined in the view model, so I guess I need to use a command instead and move the above event to the view model, right? I know that I can use a popup instead but i don't want to use it as it is always on top of all desktop objects - even if you switch to another program, the popup will be visible and obscure part of the other program.</p>
<p>Also, now I have a problem in above event handler when casting to a Tooltip, tt is getting null. Why? I have set the datacontext in the style that is defined in the dictionary.xaml.</p>
|
[
{
"answer_id": 74605014,
"author": "Frank van Puffelen",
"author_id": 209103,
"author_profile": "https://Stackoverflow.com/users/209103",
"pm_score": 2,
"selected": true,
"text": "getDocs(q)\n"
},
{
"answer_id": 74605632,
"author": "Dipanshu",
"author_id": 16869352,
"author_profile": "https://Stackoverflow.com/users/16869352",
"pm_score": 0,
"selected": false,
"text": "// Find cities within dist km of [lat, lng]\n const center = [Number(lat), Number(lng)];\n const radiusInM = dist * 1000;\n // Each item in 'bounds' represents a startAt/endAt pair. We have to issue\n // a separate query for each pair. There can be up to 9 pairs of bounds\n // depending on overlap, but in most cases there are 4.\n const bounds = geohashQueryBounds(center, radiusInM);\n const promises = [];\n\n for (const b of bounds) {\n const q = query(\n collection(db, USERS_COL),\n orderBy('geohash'),\n startAt(b[0]),\n endAt(b[1])\n );\n const querySnapshot = await getDocs(q);\n querySnapshot.forEach((doc) => {\n // doc.data() is never undefined for query doc snapshots\n promises.push(doc.data());\n });\n }\n\n var finalResult = [];\n // Collect all the query results together into a single list\n await Promise.all(promises)\n .then((snapshots) => {\n const matchingDocs = [];\n\n for (const snap of snapshots) {\n // We have to filter out a few false positives due to GeoHash\n // accuracy, but most will match\n const lat = snap.lat;\n const lng = snap.lng;\n const distanceInKm = distanceBetween([lat, lng], center);\n const distanceInM = distanceInKm * 1000;\n if (distanceInM <= radiusInM) {\n matchingDocs.push(snap);\n }\n }\n console.log('val', matchingDocs);\n return matchingDocs;\n })\n .then((matchingDocs) => {\n finalResult = matchingDocs;\n // return matchingDocs;\n });\n return finalResult;\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1624552/"
] |
74,605,136
|
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" ><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
<button type="button" id="butt">click here </button>
</form>
<script>
const lname=document.getElementById('lname').value;
const fname=document.getElementById('fname').value;
document.getElementById('butt').onclick= function() {submit();}
function submit(lname,fname){
alert(lname);
console.log(fname);
}
</script></code></pre>
</div>
</div>
</p>
<p>I know this is kiddish. I've been trying to get the value inside a html input box and alert it using js. Its returning as <code>undefined</code> error. Any help is appreciated</p>
|
[
{
"answer_id": 74605014,
"author": "Frank van Puffelen",
"author_id": 209103,
"author_profile": "https://Stackoverflow.com/users/209103",
"pm_score": 2,
"selected": true,
"text": "getDocs(q)\n"
},
{
"answer_id": 74605632,
"author": "Dipanshu",
"author_id": 16869352,
"author_profile": "https://Stackoverflow.com/users/16869352",
"pm_score": 0,
"selected": false,
"text": "// Find cities within dist km of [lat, lng]\n const center = [Number(lat), Number(lng)];\n const radiusInM = dist * 1000;\n // Each item in 'bounds' represents a startAt/endAt pair. We have to issue\n // a separate query for each pair. There can be up to 9 pairs of bounds\n // depending on overlap, but in most cases there are 4.\n const bounds = geohashQueryBounds(center, radiusInM);\n const promises = [];\n\n for (const b of bounds) {\n const q = query(\n collection(db, USERS_COL),\n orderBy('geohash'),\n startAt(b[0]),\n endAt(b[1])\n );\n const querySnapshot = await getDocs(q);\n querySnapshot.forEach((doc) => {\n // doc.data() is never undefined for query doc snapshots\n promises.push(doc.data());\n });\n }\n\n var finalResult = [];\n // Collect all the query results together into a single list\n await Promise.all(promises)\n .then((snapshots) => {\n const matchingDocs = [];\n\n for (const snap of snapshots) {\n // We have to filter out a few false positives due to GeoHash\n // accuracy, but most will match\n const lat = snap.lat;\n const lng = snap.lng;\n const distanceInKm = distanceBetween([lat, lng], center);\n const distanceInM = distanceInKm * 1000;\n if (distanceInM <= radiusInM) {\n matchingDocs.push(snap);\n }\n }\n console.log('val', matchingDocs);\n return matchingDocs;\n })\n .then((matchingDocs) => {\n finalResult = matchingDocs;\n // return matchingDocs;\n });\n return finalResult;\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19868394/"
] |
74,605,167
|
<p>Hi I'am totally new to programmering and i have just jumped into it.</p>
<p>The problem i am trying to solve is to make a function that standardized an adress as input.</p>
<p>example:</p>
<pre><code>def standardize_address(a):
numbers =[]
letters = []
a.replace('_', ' ')
for word in a.split():
if word. isdigit():
numbers. append(int(word))
elif word.isalpha():
letters.append(word)
s = f"{numbers} {letters}"
return s
</code></pre>
<p>Can someone help me explain my error and give me a "pro" programmers solution and "noob" (myself) solution?</p>
<p>This is what i should print:</p>
<pre><code>a = 'New_York 10001'
s = standardize_address(a)
print(s)
</code></pre>
<p>and the output should be:</p>
<pre><code>10001 New York
</code></pre>
<p>Right now my output is:</p>
<pre><code>[10001] ['New', 'York']
</code></pre>
|
[
{
"answer_id": 74605200,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 0,
"selected": false,
"text": "numbers letters [] '' s = f\"{numbers} {letters}\"\n \n \n return s\n return ' '.join(numbers + letters)\n numbers + letters ' '.join() ' '"
},
{
"answer_id": 74605222,
"author": "azro",
"author_id": 7212686,
"author_profile": "https://Stackoverflow.com/users/7212686",
"pm_score": 3,
"selected": true,
"text": "a = a.replace('_', ' ') numbers + letters \" \".join() int \" \".join def standardize_address(a):\n numbers = []\n letters = []\n for word in a.replace('_', ' ').split():\n if word.isdigit():\n numbers.append(word)\n elif word.isalpha():\n letters.append(word)\n return ' '.join(numbers + letters)\n isdigit def standardize_address(value):\n return ' '.join(sorted(value.replace('_', ' ').split(),\n key=str.isdigit, reverse=True))\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20231086/"
] |
74,605,189
|
<p>I am trying write an excel function that groups a long list of numbers.</p>
<p>Eg.</p>
<pre><code><165 "reject" ( less than 165 = reject)
>=165 <167 "F" (greater than or equal to 165 and less than 167 = group F)
>=167 <169 "D" (greater than or equal to 167 and less than 169 = group D)
>=169 <171 "B" (greater than or equal to 169 and less than 171 = group B)
>=171 <173 "A" (greater than or equal to 171 and less than 173 = group A)
>=173 <175 "C" (greater than or equal to 173 and less than 175 = group C)
>=175 <177 "E" (greater than or equal to 175 and less than 177 = group E)
>=177 "reject" ( greater than or equal to 177 = reject)
</code></pre>
<p>Any advice is greatly appreciated!</p>
<p>Thank you</p>
<p>I have tried the formula below but am getting the error "too many arguments in the function"</p>
<pre><code>{=IF(C4<165,"reject165",IF(C4>=165,C4<167,"F",IF(C4>=167,C4<169,"D",IF(C4>=169,C4<171,"B",IF(C4>=165,C4<167,"A",IF(C4>=165,C4<167,"C",IF(C4>=165,C4<167,"E",IF(C4>=177,"reject177","null"))))))))}
</code></pre>
|
[
{
"answer_id": 74605200,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 0,
"selected": false,
"text": "numbers letters [] '' s = f\"{numbers} {letters}\"\n \n \n return s\n return ' '.join(numbers + letters)\n numbers + letters ' '.join() ' '"
},
{
"answer_id": 74605222,
"author": "azro",
"author_id": 7212686,
"author_profile": "https://Stackoverflow.com/users/7212686",
"pm_score": 3,
"selected": true,
"text": "a = a.replace('_', ' ') numbers + letters \" \".join() int \" \".join def standardize_address(a):\n numbers = []\n letters = []\n for word in a.replace('_', ' ').split():\n if word.isdigit():\n numbers.append(word)\n elif word.isalpha():\n letters.append(word)\n return ' '.join(numbers + letters)\n isdigit def standardize_address(value):\n return ' '.join(sorted(value.replace('_', ' ').split(),\n key=str.isdigit, reverse=True))\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20626352/"
] |
74,605,191
|
<p>I'm trying to wrap hyphenated text on a button as if it were one word. I've tried using a few different variations of the <code>word-wrap</code> and <code>break-word</code> CSS properties but no luck.</p>
<p>In the snippet below, I'm trying to get <code>hello</code> on one line, and <code>this-is-a-test</code> on the next line</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>const btn = document.getElementById("btn");
btn.innerHTML = 'hello this-is-a-test'</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#btn {
width: 90px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="btn"></button></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74605200,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 0,
"selected": false,
"text": "numbers letters [] '' s = f\"{numbers} {letters}\"\n \n \n return s\n return ' '.join(numbers + letters)\n numbers + letters ' '.join() ' '"
},
{
"answer_id": 74605222,
"author": "azro",
"author_id": 7212686,
"author_profile": "https://Stackoverflow.com/users/7212686",
"pm_score": 3,
"selected": true,
"text": "a = a.replace('_', ' ') numbers + letters \" \".join() int \" \".join def standardize_address(a):\n numbers = []\n letters = []\n for word in a.replace('_', ' ').split():\n if word.isdigit():\n numbers.append(word)\n elif word.isalpha():\n letters.append(word)\n return ' '.join(numbers + letters)\n isdigit def standardize_address(value):\n return ' '.join(sorted(value.replace('_', ' ').split(),\n key=str.isdigit, reverse=True))\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7934389/"
] |
74,605,247
|
<p>Strangely enough I cant find any where on the internet if its possible to be done.</p>
<p>I have a datafrme of array column.</p>
<pre><code>arr_col
[1,3,4]
[4,3,5]
</code></pre>
<p>I want result</p>
<pre><code>Result
3
4
</code></pre>
<p>I want the median for each row.</p>
<p>I managed to do it with a pandas udf but it iterates the column and applies np.median to each row. .</p>
<p>I dont want it as it's slow and tow at a time. I want it to act at all rows the same time.</p>
<p>Either in pandas or pyspark</p>
|
[
{
"answer_id": 74605395,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "import numpy as np\ndf['Result'] = np.median(np.vstack(df['arr_col']), axis=1)\n explode groupby.median df['Result'] = (df['arr_col'].explode()\n .groupby(level=0).median()\n )\n arr_col Result\n0 [1, 3, 4] 3.0\n1 [4, 3, 5] 4.0\n df = pd.DataFrame({'arr_col': [[1,3,4], [4,3,5]]})\n"
},
{
"answer_id": 74608213,
"author": "wwnde",
"author_id": 8986975,
"author_profile": "https://Stackoverflow.com/users/8986975",
"pm_score": 0,
"selected": false,
"text": "m =udf(lambda x: int(np.median(x)),IntegerType())\ndf.withColumn('Result', m(col('arr_col'))).show()\n\n+---+---------+------+\n| Id| arr_col|Result|\n+---+---------+------+\n| 1|[1, 3, 4]| 3.0|\n| 1|[4, 3, 6]| 4.0|\n+---+---------+------+\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11531487/"
] |
74,605,248
|
<p>I'm trying to change the site name when I search it on google. the only thing that appear is "React App" and i dont know how change it</p>
<p><a href="https://i.stack.imgur.com/tMB5C.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>I tryed change the</p>
<p><code><title>Ton Redutores</title></code></p>
<p>in index.html but it just change the guide name</p>
|
[
{
"answer_id": 74605395,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "import numpy as np\ndf['Result'] = np.median(np.vstack(df['arr_col']), axis=1)\n explode groupby.median df['Result'] = (df['arr_col'].explode()\n .groupby(level=0).median()\n )\n arr_col Result\n0 [1, 3, 4] 3.0\n1 [4, 3, 5] 4.0\n df = pd.DataFrame({'arr_col': [[1,3,4], [4,3,5]]})\n"
},
{
"answer_id": 74608213,
"author": "wwnde",
"author_id": 8986975,
"author_profile": "https://Stackoverflow.com/users/8986975",
"pm_score": 0,
"selected": false,
"text": "m =udf(lambda x: int(np.median(x)),IntegerType())\ndf.withColumn('Result', m(col('arr_col'))).show()\n\n+---+---------+------+\n| Id| arr_col|Result|\n+---+---------+------+\n| 1|[1, 3, 4]| 3.0|\n| 1|[4, 3, 6]| 4.0|\n+---+---------+------+\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19346776/"
] |
74,605,250
|
<p>I have an WPF speech bubble tooltip which is working fine.</p>
<pre><code><Style x:Key="{x:Type ToolTip}" TargetType="ToolTip">
<Setter Property="OverridesDefaultStyle" Value="true" />
<Setter Property="HorizontalOffset" Value="1" />
<Setter Property="VerticalOffset" Value="1" />
<Setter Property="Background" Value="White" />
<Setter Property="Foreground" Value="Black" />
<Setter Property="FontSize" Value="12" />
<Setter Property="FontFamily" Value="Segoe UI" />
<Setter Property="DataContext" Value="{Binding Path=PlacementTarget.DataContext, RelativeSource={x:Static RelativeSource.Self}}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ToolTip">
<Canvas Width="225" Height="131">
<Path x:Name="Container"
Canvas.Left="0"
Canvas.Top="0"
Margin="0"
Data="M8,7.41 L15.415,0 L22.83,7.41 L224,7.41 L224,130 L0,130 L0,7.41 L8,7.41"
Fill="{TemplateBinding Background}"
Stroke="Gray">
<Path.Effect>
<DropShadowEffect BlurRadius="10"
Opacity="0.5"
ShadowDepth="4" />
</Path.Effect>
</Path>
<TextBlock Canvas.Left="10"
Canvas.Top="10"
Width="100"
Height="65"
Text="{TemplateBinding Content}"
TextWrapping="WrapWithOverflow" />
</Canvas>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</code></pre>
<p>The problem with above approach is that the arrow/pointer of the speech bubble tooltip (path) is always placed in the same position regardless the situation and I would like it to adapt to the situation and use one of the following (above style implements the arrow placed at the top left, first tooltip in the screenshot below):</p>
<p><a href="https://i.stack.imgur.com/T2MdB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T2MdB.png" alt="enter image description here" /></a></p>
<p>How can I do this? Is it possible?</p>
|
[
{
"answer_id": 74610783,
"author": "bazsisz",
"author_id": 17900036,
"author_profile": "https://Stackoverflow.com/users/17900036",
"pm_score": -1,
"selected": false,
"text": "internal class ArrowBorderDecorator : Decorator\n ArrowTipToArrowTriangleBaseDistance public static readonly DependencyProperty ArrowTipToArrowTriangleBaseDistanceProperty = DependencyProperty.Register(\"ArrowTipToArrowTriangleBaseDistance\", typeof(double), typeof(ArrowBorderDecorator), new FrameworkPropertyMetadata(0.0, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender));\n\n public double ArrowTipToArrowTriangleBaseDistance\n {\n get { return (double)GetValue(ArrowTipToArrowTriangleBaseDistanceProperty); }\n set { SetValue(ArrowTipToArrowTriangleBaseDistanceProperty, value); }\n }\n ArrangeOverride MeasureOverride OnRender OnRender <localdecorators:ArrowBorderDecorator ArrowBaseHalfSegment=\"0\"\n FillColor=\"{DynamicResource MahApps.Brushes.Accent3}\"\n StrokeColor=\"{DynamicResource MahApps.Brushes.ThemeForeground}\"\n ArrowBorderThickness=\"1\"\n ArrowTipToArrowTriangleBaseDistance=\"10\">\n<TextBlock Text=\"{Binding Path=Title}\"\n Foreground=\"{DynamicResource MahApps.Brushes.IdealForeground}\"\n Padding=\"10 1 10 1\"\n VerticalAlignment=\"Center\"\n FontWeight=\"Bold\">\n</TextBlock></localdecorators:ArrowBorderDecorator>\n"
},
{
"answer_id": 74617368,
"author": "bazsisz",
"author_id": 17900036,
"author_profile": "https://Stackoverflow.com/users/17900036",
"pm_score": 0,
"selected": false,
"text": "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media;\n\nnamespace Decorators\n{\npublic enum Position \n{\n None,\n Top,\n Bottom,\n RightSide,\n LeftSide,\n}\n\npublic enum SpecificPosition\n{\n None,\n LeftOrTop = 25,\n Center = 50,\n RightOrBottom = 75,\n}\n\ninternal class BubbleTextDecorator : Decorator\n{\n\n\n #region DependencyProperties\n public static readonly DependencyProperty VerticalMarginProperty = DependencyProperty.Register(\"VerticalMargin\", \n typeof(double), \n typeof(BubbleTextDecorator), \n new FrameworkPropertyMetadata(0.0, \n FrameworkPropertyMetadataOptions.AffectsMeasure | \n FrameworkPropertyMetadataOptions.AffectsRender));\n\n public double VerticalMargin\n {\n get { return (double)GetValue(VerticalMarginProperty); }\n set { SetValue(VerticalMarginProperty, value); }\n }\n\n public static readonly DependencyProperty HorizontalMarginProperty = DependencyProperty.Register(\"HorizontalMargin\", \n typeof(double),\n typeof(BubbleTextDecorator),\n new FrameworkPropertyMetadata(0.0,\n FrameworkPropertyMetadataOptions.AffectsMeasure |\n FrameworkPropertyMetadataOptions.AffectsRender));\n\n public double HorizontalMargin\n {\n get { return (double)GetValue(HorizontalMarginProperty); }\n set { SetValue(HorizontalMarginProperty, value); }\n }\n\n\n\n public static readonly DependencyProperty PointerPositionProperty = DependencyProperty.Register(\"PointerPosition\", \n typeof(Position), \n typeof(BubbleTextDecorator), \n new FrameworkPropertyMetadata(Position.None, \n FrameworkPropertyMetadataOptions.AffectsRender |\n FrameworkPropertyMetadataOptions.AffectsMeasure));\n\n public Position PointerPosition\n {\n get { return (Position)GetValue(PointerPositionProperty); }\n set { SetValue(PointerPositionProperty, value); }\n }\n\n public static readonly DependencyProperty AlignmentPositionProperty = DependencyProperty.Register(\"AlignmentPosition\",\n typeof(SpecificPosition),\n typeof(BubbleTextDecorator),\n new FrameworkPropertyMetadata(SpecificPosition.None,\n FrameworkPropertyMetadataOptions.AffectsRender |\n FrameworkPropertyMetadataOptions.AffectsMeasure));\n\n public SpecificPosition AlignmentPosition\n {\n get { return (SpecificPosition)GetValue(AlignmentPositionProperty); }\n set { SetValue(AlignmentPositionProperty, value); }\n }\n\n\n public static readonly DependencyProperty PointerHeightProperty = DependencyProperty.Register(\"PointerHeight\", \n typeof(double), \n typeof(BubbleTextDecorator), \n new FrameworkPropertyMetadata(0.0, \n FrameworkPropertyMetadataOptions.AffectsMeasure |\n FrameworkPropertyMetadataOptions.AffectsRender));\n\n public double PointerHeight\n {\n get { return (double)GetValue(PointerHeightProperty); }\n set { SetValue(PointerHeightProperty, value); }\n }\n\n public static readonly DependencyProperty PointerWidthProperty = DependencyProperty.Register(\"PointerWidth\", \n typeof(double), \n typeof(BubbleTextDecorator), \n new FrameworkPropertyMetadata(0.0,\n FrameworkPropertyMetadataOptions.AffectsMeasure |\n FrameworkPropertyMetadataOptions.AffectsArrange |\n FrameworkPropertyMetadataOptions.AffectsRender));\n\n public double PointerWidth\n {\n get { return (double)GetValue(PointerWidthProperty); }\n set { SetValue(PointerWidthProperty, value); }\n }\n\n #endregion\n\n protected override Size ArrangeOverride(Size arrangeSize)\n {\n Size desiredSize = base.ArrangeOverride(arrangeSize);\n if (Child != null) \n {\n\n switch (PointerPosition)\n {\n case Position.Top:\n Child.Arrange(new Rect(new Point(0.0, PointerHeight), new Point(desiredSize.Width, desiredSize.Height)));\n break;\n case Position.Bottom:\n Child.Arrange(new Rect(new Point(0.0, 0.0), new Point(desiredSize.Width, desiredSize.Height - PointerHeight)));\n break;\n case Position.LeftSide:\n Child.Arrange(new Rect(new Point(PointerHeight, 0.0), new Point(desiredSize.Width, desiredSize.Height)));\n break;\n case Position.RightSide:\n Child.Arrange(new Rect(new Point(0.0, 0.0), new Point(desiredSize.Width - PointerHeight, desiredSize.Height)));\n break;\n }\n }\n return arrangeSize;\n }\n\n protected override Size MeasureOverride(Size constraint)\n {\n Size desiredSize = base.MeasureOverride(constraint);\n Size size = (PointerPosition == Position.Top || PointerPosition == Position.Bottom)\n ? new Size(desiredSize.Width + (HorizontalMargin * 2), desiredSize.Height + (VerticalMargin * 2) + PointerHeight)\n : new Size(desiredSize.Width + (HorizontalMargin * 2) + PointerHeight, desiredSize.Height + (VerticalMargin * 2));\n\n return size;\n }\n\n protected override void OnRender(DrawingContext drawingContext)\n {\n Brush renderBrush = Brushes.Transparent;\n Pen renderPen = new Pen(Brushes.Black, 1);\n StreamGeometry geom = new StreamGeometry();\n\n switch (PointerPosition) \n {\n case Position.Top:\n DrawTop(geom);\n break;\n case Position.Bottom:\n DrawBottom(geom);\n break;\n case Position.RightSide:\n DrawRight(geom);\n break;\n case Position.LeftSide:\n DrawLeft(geom);\n break;\n\n }\n // Some arbitrary drawing implements.\n drawingContext.DrawGeometry(renderBrush, renderPen, geom);\n }\n\n private void DrawLeft(StreamGeometry geom)\n {\n using (StreamGeometryContext ctx = geom.Open())\n {\n ctx.BeginFigure(\n new Point(PointerHeight, 0.0),\n true,\n true);\n ctx.LineTo(\n new Point(ActualWidth, 0.0),\n true,\n false);\n ctx.LineTo(\n new Point(ActualWidth, ActualHeight),\n true,\n false);\n ctx.LineTo(\n new Point(PointerHeight, ActualHeight),\n true,\n false);\n ctx.LineTo(\n new Point(PointerHeight, (ActualHeight * (double)AlignmentPosition / 100) + (PointerWidth / 2)),\n true,\n false);\n ctx.LineTo(\n new Point(0.0, ActualHeight * (double)AlignmentPosition / 100),\n true,\n false);\n ctx.LineTo(\n new Point(PointerHeight, (ActualHeight * (double)AlignmentPosition / 100) - (PointerWidth / 2)),\n true,\n false);\n ctx.LineTo(\n new Point(PointerHeight, 0.0),\n true,\n false);\n }\n }\n\n private void DrawRight(StreamGeometry geom)\n {\n using (StreamGeometryContext ctx = geom.Open())\n {\n ctx.BeginFigure(\n new Point(0.0, 0.0),\n true,\n true);\n ctx.LineTo(\n new Point(ActualWidth - PointerHeight, 0.0),\n true,\n false);\n ctx.LineTo(\n new Point(ActualWidth - PointerHeight, (ActualHeight * (double)AlignmentPosition / 100) - (PointerWidth / 2)),\n true,\n false);\n ctx.LineTo(\n new Point(ActualWidth, ActualHeight * (double)AlignmentPosition / 100),\n true,\n false);\n ctx.LineTo(\n new Point(ActualWidth - PointerHeight, (ActualHeight * (double)AlignmentPosition / 100) + (PointerWidth / 2)),\n true,\n false);\n ctx.LineTo(\n new Point(ActualWidth - PointerHeight, ActualHeight),\n true,\n false);\n ctx.LineTo(\n new Point(0.0, ActualHeight),\n true,\n false);\n ctx.LineTo(\n new Point(0.0, 0.0),\n true,\n false);\n }\n }\n\n private void DrawBottom(StreamGeometry geom)\n {\n using (StreamGeometryContext ctx = geom.Open())\n {\n ctx.BeginFigure(\n new Point(0.0, 0.0),\n true,\n true);\n ctx.LineTo(\n new Point(ActualWidth, 0.0),\n true,\n false);\n ctx.LineTo(\n new Point(ActualWidth, ActualHeight - PointerHeight),\n true,\n false);\n ctx.LineTo(\n new Point((ActualWidth * (double)AlignmentPosition / 100) + (PointerWidth / 2), ActualHeight - PointerHeight),\n true,\n false);\n ctx.LineTo(\n new Point(ActualWidth * (double)AlignmentPosition / 100, ActualHeight),\n true,\n false);\n ctx.LineTo(\n new Point((ActualWidth * (double)AlignmentPosition / 100) - (PointerWidth / 2), ActualHeight - PointerHeight),\n true,\n false);\n ctx.LineTo(\n new Point(0.0, ActualHeight - PointerHeight),\n true,\n false);\n ctx.LineTo(\n new Point(0.0, 0.0),\n true,\n false);\n }\n }\n\n private void DrawTop(StreamGeometry geom)\n {\n using (StreamGeometryContext ctx = geom.Open())\n {\n ctx.BeginFigure(\n new Point(0.0, PointerHeight),\n true,\n true);\n ctx.LineTo(\n new Point((ActualWidth * (double)AlignmentPosition / 100) - (PointerWidth / 2), PointerHeight),\n true,\n false);\n ctx.LineTo(\n new Point(ActualWidth * (double)AlignmentPosition / 100, 0.0),\n true,\n false);\n ctx.LineTo(\n new Point((ActualWidth * (double)AlignmentPosition / 100) + (PointerWidth / 2), PointerHeight),\n true,\n false);\n ctx.LineTo(\n new Point(ActualWidth, PointerHeight),\n true,\n false);\n ctx.LineTo(\n new Point(ActualWidth, ActualHeight),\n true,\n false);\n ctx.LineTo(\n new Point(0.0, ActualHeight),\n true,\n false);\n ctx.LineTo(\n new Point(0.0, PointerHeight),\n true,\n false);\n }\n }\n}\n}\n <localdecorators:BubbleTextDecorator PointerHeight=\"10\"\n PointerWidth=\"20\"\n PointerPosition=\"LeftSide\"\n AlignmentPosition=\"Center\"\n VerticalMargin=\"30\"\n HorizontalMargin=\"30\"\n HorizontalAlignment=\"Left\">\n<TextBlock Text=\"this\"\n HorizontalAlignment=\"Center\"\n VerticalAlignment=\"Center\"/>\n</localdecorators:BubbleTextDecorator>\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1624552/"
] |
74,605,337
|
<p>I'm making a telegram bot that will send SMS through a parser and I need to loop until about 20 SMS are sent.
I am using the <code>telebot</code> library to create a bot and for the parser I have <code>requests</code> and <code>BeautifulSoup</code>.</p>
<pre class="lang-py prettyprint-override"><code>import telebot
import requests
from bs4 import BeautifulSoup
from telebot import types
bot = telebot.TeleBot('my token')
@bot.message_handler(commands=['start'])
def start(message):
mess = f'Привет, сегодня у меня для тебя 100 Анг слов! Удачи <b>{message.from_user.first_name}</b>'
bot.send_message(message.chat.id, mess, parse_mode='html')
@bot.message_handler(commands=['words'])
def website(message):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1)
word = types.KeyboardButton('100 Слов')
markup.add(word)#создание самой кнопки.
bot.send_message(message.chat.id, 'Подевиться слова', reply_markup=markup)
@bot.message_handler(content_types=['text'])
def get_user_commands(message):
if message.text == '100 Слов':
url = 'https://www.kreekly.com/lists/100-samyh-populyarnyh-angliyskih-slov/'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'lxml')
data = soup.find_all("div", class_="dict-word")
for i in data:
ENG = i.find("span", class_="eng").text
rU = i.find("span", class_="rus").text
bot.send_message(message.chat.id, ENG, parse_mode='html')
bot.send_message(message.chat.id, rU, parse_mode='html')
bot.polling(none_stop=True)
</code></pre>
<p>I tried to do it this way:</p>
<pre class="lang-py prettyprint-override"><code>if i >= 20:
break
</code></pre>
<p>but this does not work. I also tried to do it like this:</p>
<pre class="lang-py prettyprint-override"><code>if data.index(i) >= 20
break
</code></pre>
|
[
{
"answer_id": 74605392,
"author": "0stone0",
"author_id": 5625547,
"author_profile": "https://Stackoverflow.com/users/5625547",
"pm_score": 2,
"selected": true,
"text": "data = soup.find_all(\"div\", class_=\"dict-word\", limit=20)\n"
},
{
"answer_id": 74605512,
"author": "solac34",
"author_id": 20554831,
"author_profile": "https://Stackoverflow.com/users/20554831",
"pm_score": 0,
"selected": false,
"text": "for indx,i in enumerate(data):\n if index == 19: # including zero, 20th will be the 19th.\n break\n -code here-\n enumerate indx = 0 indx=1 for indx,i in enumerate(data):\n if index < 20: # apply the code if it's under the 20th itereation.\n -code here-\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20626316/"
] |
74,605,367
|
<p>In my production function:</p>
<pre><code>def myfunction():
try:
do_stuff()
(...)
raise MyException("...")
except MyException as exception:
do_clean_up(exception)
</code></pre>
<p>My test fails, because the exception is caught in the try/except block</p>
<pre><code>def test_raise(self):
with self.assertRaises(MyException):
myfunction()
</code></pre>
<p>self.assertRaises is never called.</p>
<p>How to guarantee that the exception is caught during testing?</p>
<p>The exception is never asserted
<code>AssertionError: MyException not raised</code></p>
|
[
{
"answer_id": 74605526,
"author": "prz.raf",
"author_id": 6435488,
"author_profile": "https://Stackoverflow.com/users/6435488",
"pm_score": 1,
"selected": false,
"text": "MyException myFunction() try-except assertRaises"
},
{
"answer_id": 74619982,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 0,
"selected": false,
"text": "MyException do_clean_up # Make sure the names you are patching are correct\nwith unittest.mock.patch('MyException', wraps=MyException) as mock_exc, \\\n unittest.mock.patch('do_clean_up', wraps=do_clean_up) as mock_cleanup:\n myfunction()\n if mock_exc.called:\n mock_cleanup.assert_called()\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20626472/"
] |
74,605,414
|
<p>As the topic indicates...</p>
<p>I have try two ways and none of them work:</p>
<p><strong>First:</strong></p>
<p>I want to programmatically talk to GCS in Python. such as reading gs://{bucketname}/{blobname} as a path or a file. The only thing I can find is a gsutil module, however it seems used in a commend line instead of a python application.</p>
<p>i find a code here <a href="https://stackoverflow.com/questions/41460802/accessing-data-in-google-cloud-bucket-for-a-python-tensorflow-learning-program">Accessing data in google cloud bucket</a>, but still confused on how to retrieve it to a type i need. there is a jpg file in the bucket, and want to download it for a text detection, this will be deploy on google funtion.</p>
<p><strong>Second:</strong></p>
<p><code>download_as_bytes()</code>method, <a href="https://github.com/googleapis/python-storage/blob/main/google/cloud/storage/blob.py" rel="nofollow noreferrer">Link to the blob document</a> I import the <code>googe.cloud.storage</code> module and provide the GCP key, however the error rise saying the Blob has no attribute of download_as_bytes().</p>
<p>is there anything else i haven't try? Thank you!</p>
<p>for the reference:</p>
<pre><code>def text_detected(user_id):
bucket=storage_client.bucket(
'img_platecapture')
blob=bucket.blob({user_id})
content= blob.download_as_bytes()
image = vision.Image(content=content) #insert a content
response = vision_client.text_detection(image=image)
if response.error.message:
raise Exception(
'{}\nFor more info on error messages, check: '
'https://cloud.google.com/apis/design/errors'.format(
response.error.message))
img = Image.open(input_file) #insert a path
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("simsun.ttc", 18)
for text in response.text_annotations[1::]:
ocr = text.description
draw.text((bound.vertices[0].x-25, bound.vertices[0].y-25),ocr,fill=(255,0,0),font=font)
draw.polygon(
[
bound.vertices[0].x,
bound.vertices[0].y,
bound.vertices[1].x,
bound.vertices[1].y,
bound.vertices[2].x,
bound.vertices[2].y,
bound.vertices[3].x,
bound.vertices[3].y,
],
None,
'yellow',
)
texts=response.text_annotations
a=str(texts[0].description.split())
b=re.sub(u"([^\u4e00-\u9fa5\u0030-u0039])","",a)
b1="".join(b)
print("偵測到的地址為:",b1)
return b1
@handler.add(MessageEvent, message=ImageMessage)
def handle_content_message(event):
message_content = line_bot_api.get_message_content(event.message.id)
user = line_bot_api.get_profile(event.source.user_id)
data=b''
for chunk in message_content.iter_content():
data+= chunk
global bucket_name
bucket_name = 'img_platecapture'
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(f'{user.user_id}.jpg')
blob.upload_from_string(data)
text_detected1=text_detected(user.user_id) ####Here's the problem
line_bot_api.reply_message(
event.reply_token,
messages=TextSendMessage(
text=text_detected1
))
</code></pre>
<p>reference code(gcsfs/fsspec):</p>
<pre><code>gcs = gcsfs.GCSFileSystem()
bucket=storage_client.bucket('img_platecapture')
blob=bucket.blob({user_id})
f =fsspec.open("gs://img_platecapture/{user_id}")
with f.open({user_id}, "rb") as fp:
content = fp.read()
image = vision.Image(content=content)
response = vision_client.text_detection(image=image)
</code></pre>
|
[
{
"answer_id": 74605526,
"author": "prz.raf",
"author_id": 6435488,
"author_profile": "https://Stackoverflow.com/users/6435488",
"pm_score": 1,
"selected": false,
"text": "MyException myFunction() try-except assertRaises"
},
{
"answer_id": 74619982,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 0,
"selected": false,
"text": "MyException do_clean_up # Make sure the names you are patching are correct\nwith unittest.mock.patch('MyException', wraps=MyException) as mock_exc, \\\n unittest.mock.patch('do_clean_up', wraps=do_clean_up) as mock_cleanup:\n myfunction()\n if mock_exc.called:\n mock_cleanup.assert_called()\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20452149/"
] |
74,605,420
|
<p>I am trying to find the sum of each order then group by the order ID. I had to use items.ItemID to join the 2 tables but I cannot get the sum of each order if I place ItemID in the group by statement.</p>
<p>This is what I tried:</p>
<pre><code>SELECT Orders.OrderID, Items.ItemID, Sum(Items.Price) AS SumPrice, Format(SumPrice*1.06,"Currency") AS TotalPrice
FROM Orders, Items
WHERE Items.ItemID=Orders.ItemID
GROUP BY OrderID;
</code></pre>
<p>I got the error "Your query does not include "ItemID" as part of an aggregate function."</p>
|
[
{
"answer_id": 74605526,
"author": "prz.raf",
"author_id": 6435488,
"author_profile": "https://Stackoverflow.com/users/6435488",
"pm_score": 1,
"selected": false,
"text": "MyException myFunction() try-except assertRaises"
},
{
"answer_id": 74619982,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 0,
"selected": false,
"text": "MyException do_clean_up # Make sure the names you are patching are correct\nwith unittest.mock.patch('MyException', wraps=MyException) as mock_exc, \\\n unittest.mock.patch('do_clean_up', wraps=do_clean_up) as mock_cleanup:\n myfunction()\n if mock_exc.called:\n mock_cleanup.assert_called()\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20626569/"
] |
74,605,463
|
<p>I have read many posts about dictionaries and serialization etc. and they all have different ways of doing things.
Being new to coding (to an extent) I am having trouble figuring out how to get my dictionary to a list or serialized to get it saved then reloaded on play. This is Unity BTW.
So here is what I am using.
I have an application manager that is mainly just a set of BOOL values that tells my mission system if something has been completed or not. Something like "GetWeapon FALSE" (then when they pick it up it changes to TRUE which tells the mission system to move to the next objective or complete)
So I have a starting list of keys,values...these then get placed into a dictionary and the values are changed within that.
I need to be able to save those values and reload them on LOAD (default PLAY mode is newgame--as you see below it resets the dictionary and copies in the starting states). I know it can't be as difficult as I am making it, just not understanding the whole serialize thing.
Most sites are showing a dictionary like {key,value} so I am getting lost on iterating through the dictionary and capturing the pairs and saving them.</p>
<p>Here is partial code for the appmanager (it is a singleton):</p>
<pre><code>// This holds any states you wish set at game startup
[SerializeField] private List<GameState> _startingGameStates = new List<GameState>();
</code></pre>
<pre><code>// Used to store the key/values pairs in the above list in a more efficient dictionary
private Dictionary<string, string> _gameStateDictionary = new Dictionary<string, string>();
</code></pre>
<pre><code>void Awake()
{
// This object must live for the entire application
DontDestroyOnLoad(gameObject);
ResetGameStates();
}
</code></pre>
<pre><code>void ResetGameStates()
{
_gameStateDictionary.Clear();
// Copy starting game states into game state dictionary
for (int i = 0; i < _startingGameStates.Count; i++)
{
GameState gs = _startingGameStates[i];
_gameStateDictionary[gs.Key] = gs.Value;
}
OnStateChanged.Invoke();
}
</code></pre>
<pre><code>public GameState GetStartingGameState(string key)
{
for (int i = 0; i < _startingGameStates.Count; i++)
{
if (_startingGameStates[i] != null && _startingGameStates[i].Key.Equals(key))
return _startingGameStates[i];
}
return null;
}
</code></pre>
<pre><code>// Name : SetGameState
// Desc : Sets a Game State
public bool SetGameState(string key, string value)
{
if (key == null || value == null) return false;
_gameStateDictionary[key] = value;
OnStateChanged.Invoke();
return true;
}
</code></pre>
<p>Tried something similar to this:</p>
<pre><code>Dictionary<string, string> _gameStateDictionary = new Dictionary<string, string>
{
for (int i = 0; i < _gameStateDictionary.Count; i++)
string json = JsonConvert.SerializeObject(_gameStateDictionary, Formatting.Indented);
Debug.Log(json);
{
}
</code></pre>
<p>However all I got was the first item in the list. (I did modify the above in a for loop) I know the above is wrong, I did other iterations to just to get the dictionary to print out in the console.
Anyway, just asking for a little code help to save and load a dictionary.</p>
|
[
{
"answer_id": 74605526,
"author": "prz.raf",
"author_id": 6435488,
"author_profile": "https://Stackoverflow.com/users/6435488",
"pm_score": 1,
"selected": false,
"text": "MyException myFunction() try-except assertRaises"
},
{
"answer_id": 74619982,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 0,
"selected": false,
"text": "MyException do_clean_up # Make sure the names you are patching are correct\nwith unittest.mock.patch('MyException', wraps=MyException) as mock_exc, \\\n unittest.mock.patch('do_clean_up', wraps=do_clean_up) as mock_cleanup:\n myfunction()\n if mock_exc.called:\n mock_cleanup.assert_called()\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20626427/"
] |
74,605,467
|
<p>I have my angular application running in AWS ECS (EC2 Instance) behind a load balancer. When i trigger the application using direct IP address of my EC2 instance the application loads fine without any issues. But when i trigger the application through the application load balancer, I see error on my browser console mentioning <strong>'text/plain' is not a valid JavaScript MIME type.</strong> I am not sure why i am able to trigger the application without any issues while i trigger using the direct IP, but face this error only when i use the load balancer URL. Please find below the nginx configuration.</p>
<pre><code>server {
include /etc/nginx/mime.types;
listen 443;
listen [::]:443;
server_name sampleweb.com www.sampleweb.com;
ssl_certificate /keys/cert.pem;
ssl_certificate_key /keys/key.pem;
ssl on;
ssl_session_cache builtin:1000 shared:SSL:10m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
ssl_prefer_server_ciphers on;
location ~ \.css {
add_header Content-Type text/css;
}
location ~ \.js {
add_header Content-Type application/x-javascript;
}
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri /index.html;
add_header 'Access-Control-Allow-Origin' '*';
}
# redirect server error pages to the static page /50x.html
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
</code></pre>
<p>Can anyone help with this issue?</p>
|
[
{
"answer_id": 74605526,
"author": "prz.raf",
"author_id": 6435488,
"author_profile": "https://Stackoverflow.com/users/6435488",
"pm_score": 1,
"selected": false,
"text": "MyException myFunction() try-except assertRaises"
},
{
"answer_id": 74619982,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 0,
"selected": false,
"text": "MyException do_clean_up # Make sure the names you are patching are correct\nwith unittest.mock.patch('MyException', wraps=MyException) as mock_exc, \\\n unittest.mock.patch('do_clean_up', wraps=do_clean_up) as mock_cleanup:\n myfunction()\n if mock_exc.called:\n mock_cleanup.assert_called()\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13722866/"
] |
74,605,492
|
<p>my code:-</p>
<pre><code>$host = "https://example.org/get.php?";
$newurl = file_get_contents($url);
$newurl = substr($newurl,stripos($newurl,"who"));
$newurl = substr($newurl,0,stripos($newurl,"</"));
// newurl string starts with "who" and ends with "</"
//var_dump($host.$newurl)."<br>"; //shows correct request string
header("Location: " . $host.$newurl);
exit();
</code></pre>
<p>new window displays the correct url request in the address bar but isn't redrawn
page source is blank except a single "1" char.
on pressing the resubmit button the page is drawn correctly.
Any help greatly appreciated.</p>
<p>Stve</p>
|
[
{
"answer_id": 74605526,
"author": "prz.raf",
"author_id": 6435488,
"author_profile": "https://Stackoverflow.com/users/6435488",
"pm_score": 1,
"selected": false,
"text": "MyException myFunction() try-except assertRaises"
},
{
"answer_id": 74619982,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 0,
"selected": false,
"text": "MyException do_clean_up # Make sure the names you are patching are correct\nwith unittest.mock.patch('MyException', wraps=MyException) as mock_exc, \\\n unittest.mock.patch('do_clean_up', wraps=do_clean_up) as mock_cleanup:\n myfunction()\n if mock_exc.called:\n mock_cleanup.assert_called()\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420415/"
] |
74,605,547
|
<p>i want to stop loading a video when the website is being displayed on a phone but it should load on desktop screen sizes.</p>
<p>P.s. - i am talking about loading/not-loading an element or component. please don't give answers by telling to change the css property (display: none, visibility: hidden).</p>
<p>i am using an Iphone and with display: none, the video is not showing. However, the video is autoplayed while scrolling and plays randomly in the video player of safari.</p>
|
[
{
"answer_id": 74606037,
"author": "Rohit Khandelwal",
"author_id": 15220748,
"author_profile": "https://Stackoverflow.com/users/15220748",
"pm_score": 1,
"selected": false,
"text": "CSS HTML @media @media screen and (max-width: 480px) {\n body {\n background-color: red;\n }\n} innerWidth window"
},
{
"answer_id": 74606056,
"author": "Beatriz Infante",
"author_id": 7773975,
"author_profile": "https://Stackoverflow.com/users/7773975",
"pm_score": 0,
"selected": false,
"text": "display: none visibility: hidden const renderVideo = () => { \n const {innerWidth} = window;\n return (innerWidth > 940 && <video ..../>\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20626648/"
] |
74,605,561
|
<p>Got this code, it does what I need it to do, but only the button cancel button doesn't work, I want it to remove the whole part of the list</p>
<p>I've been struggling, experimenting with whatever I could but nothing helped and I just don't know</p>
<p>My html:</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 myNodelist = document.getElementsByTagName("LI");
let i;
let close = document.getElementsByClassName("close");
function newTask() {
let li = document.createElement("li");
let value = document.getElementById("myinput").value;
let t = document.createTextNode(value);
li.appendChild(t);
if (value === '') {
alert("You must write something!");
} else {
document.getElementById("list").appendChild(li);
}
document.getElementById("myinput").value = "";
let button = document.createElement("button");
let text = document.createTextNode("\u00D7");
button.className = "close";
button.appendChild(text);
li.appendChild(button);
for (i = 0; i < close.length; i++) {
close[i].onclick = () => {
var div = parentElement;
div.style.display = "none";
}
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><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">
<title>Document</title>
<link rel="stylesheet" href="uloha.css">
<script src="app.js"></script>
</head>
<body>
<div class="task" id="task">
<h1>To-do list</h1>
<input type="text" , id="myinput" , placeholder="Task">
<button onclick="newTask()" type="button" , class="button" id="button"> Add</button>
</div>
<ul id="list">
</ul>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74606037,
"author": "Rohit Khandelwal",
"author_id": 15220748,
"author_profile": "https://Stackoverflow.com/users/15220748",
"pm_score": 1,
"selected": false,
"text": "CSS HTML @media @media screen and (max-width: 480px) {\n body {\n background-color: red;\n }\n} innerWidth window"
},
{
"answer_id": 74606056,
"author": "Beatriz Infante",
"author_id": 7773975,
"author_profile": "https://Stackoverflow.com/users/7773975",
"pm_score": 0,
"selected": false,
"text": "display: none visibility: hidden const renderVideo = () => { \n const {innerWidth} = window;\n return (innerWidth > 940 && <video ..../>\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20626325/"
] |
74,605,581
|
<p>I am having a little trouble with this assignment for school. I am using JavaScript to make a menu and give the total price of that order. I am doing 4 menus: Breakfast, Lunch, Dinner, each with sides (Trying to get a little extra credit). I am supposed to use prompt() for this assignment. I was able to get the numbers in an array but I can't get them to equal out anything. I have posted the code I have, but if there is a simpler version I will gladly be doing that too.</p>
<p>I have the menu in HTML and the code itself for the javascript is in the <code><script></code> tag.</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>const b1 = 4;
const b2 = 5;
const bs1 = 2;
const l1 = 10;
const l2 = 20;
const l3 = 5;
const d1 = 10;
const d2 = 20;
const s1 = 2;
const s2 = 3;
const s3 = 5
function orderHere() {
var i = 0;
var order;
sum = 0
for (i = 0; i < 2; i++) {
order = prompt("What would you like to eat today?", "Order Here" + (i + 1));
sum += order;
}
alert("Your price is $" + sum + ". Enjoy your meal!");
}
orderHere();</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74605669,
"author": "Static Spaghetti 13",
"author_id": 20455439,
"author_profile": "https://Stackoverflow.com/users/20455439",
"pm_score": 0,
"selected": false,
"text": "const prices = new Map();\n\nprices.set(\"dinner 1\", 10);\n//The first parameter is the food\n//the second is the price\n\nconsole.log(prices.get(\"dinner 1\")); //returns 10\n"
},
{
"answer_id": 74605674,
"author": "Stephen Gilboy",
"author_id": 621827,
"author_profile": "https://Stackoverflow.com/users/621827",
"pm_score": 1,
"selected": false,
"text": "const menu = { b1: 4, b2: 5, ... } sum += menu[order]"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20245955/"
] |
74,605,590
|
<p>I want to ask how can I run an external batch file while updating the variable before I run the process. The detail for my question is following:</p>
<p>I have a batch file right now, while it performs a simulation process. I want to write a module that I can update the variable first without manually updating the batch files, then run the simulation, and finally import the result, like:</p>
<pre><code># this will be the variable that I want to update
yyyy = 2022
mm = 11
dd = 28
Path1 = 'the path for first variable'
Path2 = 'the path for second variable'
# the batch file is like:
Batch_simulation.bat
Path 2/remote/noclear/Path 1/%yyyy%%mm%%dd%
# therefore, I want to update the variable in batch file first, then run the simulation, my code is looking like this right now:
import subprocess
yyyy = 2022
mm = 11
dd = 28
Path1 = 'the path for first variable'
Path2 = 'the path for second variable'
paramStr = str(yyyy)+','+str(mm)+','+str(dd)+','+Path1+','+Path2
bat_file = ['pathway for Batch_simulation.bat', paramStr]
process = subprocess.run([bat_file])
stdout, stderr = process.communicate()
</code></pre>
<p>Can someone give some advice, or any possible solution please? Thank you so much</p>
|
[
{
"answer_id": 74605669,
"author": "Static Spaghetti 13",
"author_id": 20455439,
"author_profile": "https://Stackoverflow.com/users/20455439",
"pm_score": 0,
"selected": false,
"text": "const prices = new Map();\n\nprices.set(\"dinner 1\", 10);\n//The first parameter is the food\n//the second is the price\n\nconsole.log(prices.get(\"dinner 1\")); //returns 10\n"
},
{
"answer_id": 74605674,
"author": "Stephen Gilboy",
"author_id": 621827,
"author_profile": "https://Stackoverflow.com/users/621827",
"pm_score": 1,
"selected": false,
"text": "const menu = { b1: 4, b2: 5, ... } sum += menu[order]"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20462756/"
] |
74,605,598
|
<p>My final data after parsing from a yaml file is like this in text file :</p>
<pre><code> - id: 200
addr: 10.242.57.129/27
- id: 210
addr: 10.242.57.161/25
- id: 300
addr: 10.244.26.1/24
</code></pre>
<p>I wanted to convert to this and save it as txt with shell scripting ( bash):</p>
<pre><code>200,10.242.57.125,27
210,10.242.57.162,25
300,10.244.26.11,24
</code></pre>
<p>Can anyone help for that?</p>
<p>Need to get the command shell for this (with awk, grep , sed , ...).</p>
<p>I used the following code but it doesn't work:</p>
<pre><code>grep -F -e "id:" | cut -c 14-16 -e "addr:" | cut -c 16-35 ip.txt | paste -d , - -
</code></pre>
|
[
{
"answer_id": 74606299,
"author": "HatLess",
"author_id": 16372109,
"author_profile": "https://Stackoverflow.com/users/16372109",
"pm_score": 1,
"selected": true,
"text": "sed $ sed -E '/-/{N;s~[^0-9]*([0-9]+)\\n[^0-9]*([0-9.]+)/([0-9]+)~\\1,\\2,\\3~}' input_file\n200,10.242.57.129,27\n210,10.242.57.161,25\n300,10.244.26.1,24\n"
},
{
"answer_id": 74606425,
"author": "mklement0",
"author_id": 45375,
"author_profile": "https://Stackoverflow.com/users/45375",
"pm_score": 1,
"selected": false,
"text": "powershell switch awk switch -Regex -File file.txt {\n '\\bid: (\\d+)' { $id = $Matches.1 }\n '\\baddr: ([\\d.]+)/(\\d+)' { '{0},{1},{2}' -f $id, $Matches.1, $Matches.2 }\n}\n $Matches -f"
},
{
"answer_id": 74607899,
"author": "potong",
"author_id": 967492,
"author_profile": "https://Stackoverflow.com/users/967492",
"pm_score": 0,
"selected": false,
"text": "sed 'N;s/[^0-9.\\n/]//g;y/\\n\\//,,/' file\n / ,"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20626676/"
] |
74,605,611
|
<p>I'm working on converting Stata code to R. There's a snippet of code that creates a new variable and adds the column value if it meets specific parameters. For example, if a cell is greater than 0 and less than or equal to 3, that value would be added to <code>newvar</code></p>
<pre><code>gen newvar=0
local list a b c
foreach x of local list{
qui replace newvar=newvar+`x' if `x'>0 & `x'<=3
}
</code></pre>
<pre><code>set.seed(5)
dat <- data.frame(a = rnorm(5), b = rnorm(5), c = rnorm(5))
</code></pre>
<p><a href="https://i.stack.imgur.com/iZusN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iZusN.png" alt="enter image description here" /></a></p>
<p><strong>Desired Output</strong></p>
<p><a href="https://i.stack.imgur.com/Ebf3n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ebf3n.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74605652,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 0,
"selected": false,
"text": "NA rowSums dat$newvar <- rowSums(NA^(dat <=0|dat >=3)*dat, na.rm = TRUE)\n > dat\n a b c newvar\n1 -0.84085548 -0.6029080 1.2276303 1.22763034\n2 1.38435934 -0.4721664 -0.8017795 1.38435934\n3 -1.25549186 -0.6353713 -1.0803926 0.00000000\n4 0.07014277 -0.2857736 -0.1575344 0.07014277\n5 1.71144087 0.1381082 -1.0717600 1.84954910\n"
},
{
"answer_id": 74605666,
"author": "Vinícius Félix",
"author_id": 9696037,
"author_profile": "https://Stackoverflow.com/users/9696037",
"pm_score": 1,
"selected": false,
"text": "tidyverse library(dplyr)\nset.seed(5)\ndat <- data.frame(a = rnorm(5), b = rnorm(5), c = rnorm(5))\n\nconditional_sum <- function(x,a = 0,b = 3){\n sum(x[x > a & x <= b],na.rm = TRUE)\n}\n\ndat %>% \n rowwise() %>% \n mutate(newvar = conditional_sum(c_across()))\n\n# A tibble: 5 x 4\n# Rowwise: \n a b c newvar\n <dbl> <dbl> <dbl> <dbl>\n1 -0.841 -0.603 1.23 1.23 \n2 1.38 -0.472 -0.802 1.38 \n3 -1.26 -0.635 -1.08 0 \n4 0.0701 -0.286 -0.158 0.0701\n5 1.71 0.138 -1.07 1.85 \n"
},
{
"answer_id": 74605672,
"author": "Axeman",
"author_id": 4341440,
"author_profile": "https://Stackoverflow.com/users/4341440",
"pm_score": 0,
"selected": false,
"text": "apply dat$newvar <- apply(dat, 1, \\(r) sum(r[r > 0 & r <= 3]))\n dat r r a b c newvar\n1 -0.84085548 -0.6029080 1.2276303 1.22763034\n2 1.38435934 -0.4721664 -0.8017795 1.38435934\n3 -1.25549186 -0.6353713 -1.0803926 0.00000000\n4 0.07014277 -0.2857736 -0.1575344 0.07014277\n5 1.71144087 0.1381082 -1.0717600 1.84954910\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18911130/"
] |
74,605,645
|
<p>I am trying to filter an array of objects, based on the elements within another array.</p>
<p>The array of objects I would like filtered is:</p>
<pre><code>const data = [
{id: 1, method: "bike"},
{id: 2, method: "walk"},
{id: 3, method: "bus"},
{id: 4, method: "bike"},
{id: 5, method: "walk"},
{id: 5, method: "bus"},
]
</code></pre>
<p>I have one of three arrays that have what <code>method</code> I would like to include</p>
<pre><code>const filter1 = ['bike'];
const filter2 = ['bike', 'walk'];
const filter3 = ['bike', 'walk', 'bus'];
</code></pre>
<p>I am able to <code>push</code> the filtered array to a new array, but I would like the filtered array to have the same structure as <code>data</code>, instead of an array of arrays.</p>
<p>This is my current method, and it gives me a 2D array:</p>
<pre><code>let output = [];
const filterArr = filter2.forEach(element => {
const filt = data.filter(el => el.method === element);
output.push(filt);
});
</code></pre>
<p>My desired output is:</p>
<pre><code>const want = [
{id: 1, method: "bike"},
{id: 2, method: "walk"},
{id: 4, method: "bike"},
{id: 5, method: "walk"},
]
</code></pre>
|
[
{
"answer_id": 74605696,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 0,
"selected": false,
"text": "methods = filter2, // one of your filters.\nresult = data.filter(({ method }) => methods.includes(method));\n"
},
{
"answer_id": 74605705,
"author": "Mr. Polywhirl",
"author_id": 1762224,
"author_profile": "https://Stackoverflow.com/users/1762224",
"pm_score": 2,
"selected": true,
"text": "Array Set Set.prototype.has method const filter2 = new Set(['bike', 'walk']);\n\nconst data = [\n { id: 1, method: \"bike\" },\n { id: 2, method: \"walk\" },\n { id: 3, method: \"bus\" },\n { id: 4, method: \"bike\" },\n { id: 5, method: \"walk\" },\n { id: 5, method: \"bus\" },\n];\n\nconst filtered = data.filter(({ method }) => filter2.has(method));\n\nconsole.log(filtered); .as-console-wrapper { top: 0; max-height: 100% !important; }"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6301517/"
] |
74,605,646
|
<p>The <strong>length <= 2 check</strong> is <strong>working</strong> ONLY if I'm manually erasing the text from the input.
However, My input has closing button which has reset(); on it, and when I'm pressing it, my input is empty, however jquery code doesnt care about that and doesnt recognise the input as empty, because as I know the reset(); function turns my input form to undefined.. so I have to check the input for undefined in my jQuery, however it doesn't work. any clues??</p>
<pre><code><script>
$('.regulator').keyup(function() {
if ($(this).val().length <= 2 || $(this).val().value == undefined) {
$('.quickSearchResults').hide();
} else {
$('.quickSearchResults').show();
}
}).keyup();
</script>
</code></pre>
|
[
{
"answer_id": 74605696,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 0,
"selected": false,
"text": "methods = filter2, // one of your filters.\nresult = data.filter(({ method }) => methods.includes(method));\n"
},
{
"answer_id": 74605705,
"author": "Mr. Polywhirl",
"author_id": 1762224,
"author_profile": "https://Stackoverflow.com/users/1762224",
"pm_score": 2,
"selected": true,
"text": "Array Set Set.prototype.has method const filter2 = new Set(['bike', 'walk']);\n\nconst data = [\n { id: 1, method: \"bike\" },\n { id: 2, method: \"walk\" },\n { id: 3, method: \"bus\" },\n { id: 4, method: \"bike\" },\n { id: 5, method: \"walk\" },\n { id: 5, method: \"bus\" },\n];\n\nconst filtered = data.filter(({ method }) => filter2.has(method));\n\nconsole.log(filtered); .as-console-wrapper { top: 0; max-height: 100% !important; }"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9062202/"
] |
74,605,684
|
<p>I am trying get difference between two timestamps and check if its greater than 30 mins</p>
<pre><code>timestamp1 = 1668027512
now = datetime.now(tz)
</code></pre>
<p>And this is what i am trying to do</p>
<pre><code>from datetime import datetime
import pytz as tz
tz = tz.timezone('UTC')
import time
timestamp1 = 1668027512
timestamp1 = datetime.utcfromtimestamp(int(timestamp1)).strftime("%Y-%m-%dT%H:%M:%S")
print(timestamp1)
now = datetime.now(tz).strftime("%Y-%m-%dT%H:%M:%S")
print(now)
print(timestamp1 - now)
</code></pre>
<p>This is giving me this error</p>
<pre><code>TypeError: unsupported operand type(s) for -: 'str' and 'str
</code></pre>
<p>so i tried to convert them to unix timestamp and then do the difference</p>
<pre><code>d1_ts = time.mktime(timestamp1.timetuple())
d2_ts = time.mktime(now.timetuple())
print(d1_ts - d2_ts)
</code></pre>
<p>But now the error is this</p>
<pre><code>'str' object has no attribute 'timetuple'
</code></pre>
<p>This <code>datetime</code> package is confusing,
What am i missing here ?</p>
|
[
{
"answer_id": 74605766,
"author": "John Gordon",
"author_id": 494134,
"author_profile": "https://Stackoverflow.com/users/494134",
"pm_score": 1,
"selected": false,
"text": "from datetime import datetime\n\n# 30 minutes times 60 seconds\nthirty_minutes = 30 * 60\n\npast_timestamp = 1668027512\nnow_timestamp = datetime.now().timestamp()\n\nif (now_timestamp - past_timestamp) > thirty_minutes:\n # do your thing\n"
},
{
"answer_id": 74605818,
"author": "João Vítor Rios Fuck",
"author_id": 19402498,
"author_profile": "https://Stackoverflow.com/users/19402498",
"pm_score": 0,
"selected": false,
"text": ".strftime(\"%Y-%m-%dT%H:%M:%S\") now = now.replace(tzinfo=None) from datetime import datetime\nimport pytz as tz\ntz = tz.timezone('UTC')\nimport time\n\ntimestamp1 = 1668027512\ntimestamp1 = datetime.utcfromtimestamp(int(timestamp1))\n\nprint(timestamp1.strftime(\"%Y-%m-%dT%H:%M:%S\"))\nnow = datetime.now(tz)\nprint(now.strftime(\"%Y-%m-%dT%H:%M:%S\"))\n\nnow = now.replace(tzinfo=None)\nprint(timestamp1 - now)\n"
},
{
"answer_id": 74606050,
"author": "0x0fba",
"author_id": 20339407,
"author_profile": "https://Stackoverflow.com/users/20339407",
"pm_score": 0,
"selected": false,
"text": "utcfromtimestamp() tzinfo fromtimestamp() pytz UTC timedelta() from datetime import datetime, timedelta\nfrom pytz import UTC\n\ndt1 = datetime.fromtimestamp(1668027512, UTC)\nnow = datetime.now(UTC)\nif now - dt1 > timedelta(minutes=30):\n print(\"period expired\")\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19671817/"
] |
74,605,704
|
<p>I have a dataset where names have been entered differently. Some names of been entered as first name space last name while others have been entered last name comma first name. I need all to read last name comma first name. I would like to keep the data within the dataframe but I can append back if there is no other way to do it. Here is an example of the dataframe:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Names</th>
<th>Other_Column</th>
</tr>
</thead>
<tbody>
<tr>
<td>Smith, John</td>
<td>...</td>
</tr>
<tr>
<td>Sam Miller</td>
<td>...</td>
</tr>
<tr>
<td>Anderson, Sam</td>
<td>...</td>
</tr>
<tr>
<td>Williams, Jacob</td>
<td>...</td>
</tr>
<tr>
<td>Susan Styles</td>
<td>...</td>
</tr>
<tr>
<td>Burke, David</td>
<td>...</td>
</tr>
</tbody>
</table>
</div>
<p>I have tried to do a case_when statement after piping in the dataframe but that didn't work. I have also tried grep1 and str_split.</p>
|
[
{
"answer_id": 74605770,
"author": "Vinícius Félix",
"author_id": 9696037,
"author_profile": "https://Stackoverflow.com/users/9696037",
"pm_score": 0,
"selected": false,
"text": "df <-\ntibble::tribble(\n ~Names, ~Other_Column,\n \"Smith, John\", \"...\",\n \"Sam Miller\", \"...\",\n \"Anderson, Sam\", \"...\",\n \"Williams, Jacob\", \"...\",\n \"Susan Styles\", \"...\",\n \"Burke, David\", \"...\"\n )\n\nlibrary(stringr)\nlibrary(dplyr)\n\nchange_name <- \n function(x){\n if(!str_detect(x,\",\")){\n aux <- str_split(x,pattern = \" \")[[1]]\n output <- str_c(aux[2],\", \",aux[1])\n }else{\n output <- x\n }\n return(output)\n }\n\ndf %>% \n rowwise() %>% \n mutate(new_name = change_name(Names))\n\n# A tibble: 6 x 3\n# Rowwise: \n Names Other_Column new_name \n <chr> <chr> <chr> \n1 Smith, John ... Smith, John \n2 Sam Miller ... Miller, Sam \n3 Anderson, Sam ... Anderson, Sam \n4 Williams, Jacob ... Williams, Jacob\n5 Susan Styles ... Styles, Susan \n6 Burke, David ... Burke, David \n"
},
{
"answer_id": 74605785,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 2,
"selected": true,
"text": "library(dplyr)\nquux %>%\n mutate(\n Names = if_else(grepl(\",\", Names),\n Names,\n sub(\"^(.+)\\\\s+(\\\\S+)$\", \"\\\\2, \\\\1\", Names))\n )\n# Names Other_Column\n# 1 Smith, John ...\n# 2 Miller, Sam ...\n# 3 Anderson, Sam ...\n# 4 Williams, Jacob ...\n# 5 Styles, Susan ...\n# 6 Burke, David ...\n ^(.+)\\\\s+(\\\\S+)$\n^ beginning-of-string\n (^^) group of anything (1-or-more)\n ^^^^ blank-space (1-or-more)\n (^^^^) group of non-blank-space characters (1-or-more)\n ^ end-of-string\n quux <- structure(list(Names = c(\"Smith, John\", \"Sam Miller\", \"Anderson, Sam\", \"Williams, Jacob\", \"Susan Styles\", \"Burke, David\"), Other_Column = c(\"...\", \"...\", \"...\", \"...\", \"...\", \"...\")), class = \"data.frame\", row.names = c(NA, -6L))\n"
},
{
"answer_id": 74606004,
"author": "rjen",
"author_id": 12820205,
"author_profile": "https://Stackoverflow.com/users/12820205",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\n\ndf %>%\n separate(Names, into = c(\"first\", \"second\"), remove = F) %>%\n transmute(Names = Names,\n new_names = case_when(str_detect(Names, \",\") ~ Names,\n T ~ str_c(second, first, sep = \", \")))\n\n# A tibble: 6 × 2\n# Names new_names \n# <chr> <chr> \n# 1 Smith, John Smith, John \n# 2 Sam Miller Miller, Sam \n# 3 Anderson, Sam Anderson, Sam \n# 4 Williams, Jacob Williams, Jacob\n# 5 Susan Styles Styles, Susan \n# 6 Burke, David Burke, David\n df <- tibble(Names = c(\"Smith, John\", \"Sam Miller\", \"Anderson, Sam\", \"Williams, Jacob\", \"Susan Styles\", \"Burke, David\"))\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19017141/"
] |
74,605,715
|
<p>Here I have 3 tables, CONTAINS, ORDER, and PRODUCT. The problem is that the total price of the order in the ORDER1 table must be calculated, it is the sum (product * price) for all the products in that order, so for example for Order1 ID = 1 in table ORDER1 we must go to the CONTAINS table to find the quanity of the product and barcode of the product (which we use to get the price of that product from the PRODUCT table). after that we multiply price by quantity for every product in that Order_ID to get the total price,</p>
<p>These are the tables:</p>
<p>Table: Order1</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Order_ID</th>
<th>Total Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>NULL</td>
</tr>
<tr>
<td>2</td>
<td>NULL</td>
</tr>
</tbody>
</table>
</div>
<p>Table: Contains</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Order_ID</th>
<th>Barcode</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>12</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>34</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>56</td>
<td>4</td>
</tr>
</tbody>
</table>
</div>
<p>Table: Product</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Barcode</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>12</td>
<td>5</td>
</tr>
<tr>
<td>34</td>
<td>1</td>
</tr>
<tr>
<td>56</td>
<td>6</td>
</tr>
</tbody>
</table>
</div>
<p>I know how to generate a table that contains the order_ID and the total price, but I do not know how to UPDATE the Order1 table using what I wrote, and I must use an UPDATE statement</p>
<p>This is how the select statement would generate the correct ouptput:</p>
<pre><code>SELECT ORDER1.ORDER_ID, SUM(Quantity*Selling_Price) AS "Total"
FROM PRODUCT, IS_PRESENT_IN, Order1
WHERE PRODUCT.BARCODE = IS_PRESENT_IN.BARCODE AND ORDER1.ORDER_ID = IS_PRESENT_IN.ORDER_ID
GROUP BY order1.ORDER_ID
ORDER BY SUM(Quantity*Selling_price) ;
</code></pre>
|
[
{
"answer_id": 74605792,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 1,
"selected": false,
"text": "merge SQL> merge into order1 o\n 2 using (select i.order_id,\n 3 sum(i.quantity * p.selling_price) as total_price\n 4 from is_present_in i join product p on p.barcode = i.barcode\n 5 group by i.order_id\n 6 ) x\n 7 on (x.order_id = o.order_id)\n 8 when matched then update set\n 9 o.total_price = x.total_price;\n\n2 rows merged.\n\nSQL> select * from order1;\n\n ORDER_ID TOTAL_PRICE\n---------- -----------\n 1 11\n 2 24\n\nSQL>\n"
},
{
"answer_id": 74605830,
"author": "tinazmu",
"author_id": 11695049,
"author_profile": "https://Stackoverflow.com/users/11695049",
"pm_score": 3,
"selected": true,
"text": "UPDATE Order1\nSET TotalPrice=\n (SELECT SUM(Quantity*Selling_Price)\n FROM PRODUCT P\n \n INNER JOIN \n IS_PRESENT_IN IPI\n ON P.BARCODE=IPI.BARCODE\n\n WHERE IPI.ORDER_ID=Order1.ORDER_ID\n )\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15851071/"
] |
74,605,735
|
<p>I have a lot of circles and I store their position in a list.
All circles have the same radius.</p>
<p>How can I detect if any circle collides with another circle?
What would be the fastest way?</p>
|
[
{
"answer_id": 74605792,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 1,
"selected": false,
"text": "merge SQL> merge into order1 o\n 2 using (select i.order_id,\n 3 sum(i.quantity * p.selling_price) as total_price\n 4 from is_present_in i join product p on p.barcode = i.barcode\n 5 group by i.order_id\n 6 ) x\n 7 on (x.order_id = o.order_id)\n 8 when matched then update set\n 9 o.total_price = x.total_price;\n\n2 rows merged.\n\nSQL> select * from order1;\n\n ORDER_ID TOTAL_PRICE\n---------- -----------\n 1 11\n 2 24\n\nSQL>\n"
},
{
"answer_id": 74605830,
"author": "tinazmu",
"author_id": 11695049,
"author_profile": "https://Stackoverflow.com/users/11695049",
"pm_score": 3,
"selected": true,
"text": "UPDATE Order1\nSET TotalPrice=\n (SELECT SUM(Quantity*Selling_Price)\n FROM PRODUCT P\n \n INNER JOIN \n IS_PRESENT_IN IPI\n ON P.BARCODE=IPI.BARCODE\n\n WHERE IPI.ORDER_ID=Order1.ORDER_ID\n )\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19771452/"
] |
74,605,763
|
<p>Is there a way to summarize occurrences of variable values by another variable?</p>
<p>It's similar to pivoting from long to wide, but pivoting is done into a vector rather than into multiple variables</p>
<p><strong>data have:</strong></p>
<pre><code>| var1 | var2 |
| :--: |:------:|
| 1 | 2 |
| 1 | 4 |
| 1 | 4 |
| 1 | 4 |
| 1 | 6 |
| 2 | 8 |
| 2 | 8 |
| 2 | 10 |
| 2 | 12 |
</code></pre>
<p><strong>data want:</strong></p>
<pre><code>| var1 | var2 |
| :--: |:---------:|
| 1 | (2, 4, 6) |
| 2 | (8,10,12) |
</code></pre>
|
[
{
"answer_id": 74605783,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "list unique library(dplyr)\ndf1 %>%\n distinct %>%\n group_by(var1) %>%\n summarise(var2 = list(var2))\n"
},
{
"answer_id": 74605814,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 2,
"selected": false,
"text": "aggregate aggregate(. ~ var1, df, function(x) list(unique(x)))\n var1 var2\n1 1 2, 4, 6\n2 2 8, 10, 12\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7956263/"
] |
74,605,786
|
<p>I need to use the <code>filter</code> function (or maybe some other alternatives) multiple times to calculate the average based on the conditions specified.</p>
<p>Here is the dataset:</p>
<pre><code>df <- data.frame(id = c(1,2,3,4,5,6,7),
cond = c("Y", "Y", "N", "Y", "N", "Y", "N"), score = c(3,4,5,2,1,2,9))
</code></pre>
<p>I need to calculate the average separately for <code>cond=Y</code> and <code>cond=N</code> and later append this average column to the original dataset like this:</p>
<pre><code> id cond score average
1 1 Y 3 2.75
2 2 Y 4 2.75
3 3 N 5 5
4 4 Y 2 2.75
5 5 N 1 5
6 6 Y 2 2.75
7 7 N 9 5
</code></pre>
|
[
{
"answer_id": 74605799,
"author": "Vinícius Félix",
"author_id": 9696037,
"author_profile": "https://Stackoverflow.com/users/9696037",
"pm_score": 2,
"selected": false,
"text": "dplyr library(dplyr)\n\ndf <- data.frame(cond = c(1,1,1,2,2,2,2), score = c(3,4,5,2,1,2,9))\n\ndf %>% \n group_by(cond) %>% \n mutate(average = mean(score, na.rm = TRUE))\n\n# A tibble: 7 x 3\n# Groups: cond [2]\n cond score average\n <dbl> <dbl> <dbl>\n1 1 3 4 \n2 1 4 4 \n3 1 5 4 \n4 2 2 3.5\n5 2 1 3.5\n6 2 2 3.5\n7 2 9 3.5\n"
},
{
"answer_id": 74605803,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "library(data.table)\nsetDT(df)[, average := mean(score), by = cond]\n > df\n id cond score average\n <num> <char> <num> <num>\n1: 1 Y 3 2.75\n2: 2 Y 4 2.75\n3: 3 N 5 5.00\n4: 4 Y 2 2.75\n5: 5 N 1 5.00\n6: 6 Y 2 2.75\n7: 7 N 9 5.00\n collapse library(collapse)\ndf$average <- fmean(df$score, df$cond, TRA = 1)\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7989204/"
] |
74,605,791
|
<p>Is there a way to have a dynamic array formula that gives the solution as per cells A11:B12 out of the Table A1:B6.
<a href="https://i.stack.imgur.com/Q4shs.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>meaning that if a customer C would be added with product V, it would dynamically add a line <a href="https://i.stack.imgur.com/qVxdt.png" rel="nofollow noreferrer">enter image description here</a>
I would imagine that in A11 there would be something like <strong>UNIQUE(Table1[Client])</strong>?? But how to get with a Dynamic Array formula the products in column B?</p>
<p>Thank you for your help</p>
<p>I tried the filter function couple with xmatch, but could not make it to run due to the dynamic nature of the lookup range</p>
|
[
{
"answer_id": 74605932,
"author": "Mayukh Bhattacharya",
"author_id": 8162520,
"author_profile": "https://Stackoverflow.com/users/8162520",
"pm_score": 3,
"selected": true,
"text": "A10 =HSTACK(UNIQUE(Table23[Client]),BYROW(UNIQUE(Table23[Client]),LAMBDA(x,TEXTJOIN(\",\",,REPT(Table23[Product],x=Table23[Client])))))\n LET() A10 =LET(_client,UNIQUE(Table23[Client]),\nHSTACK(_client,BYROW(_client,LAMBDA(x,TEXTJOIN(\",\",,REPT(Table23[Product],x=Table23[Client]))))))\n FILTER() REPT() A10 =LET(_client,UNIQUE(Table23[Client]),\nHSTACK(_client,BYROW(_client,LAMBDA(x,TEXTJOIN(\",\",,FILTER(Table23[Product],x=Table23[Client]))))))\n A9 =DROP(IFERROR(REDUCE(\"\",UNIQUE(Table23[Client]),LAMBDA(a,b,VSTACK(a,HSTACK(b,TEXTJOIN(\",\",1,FILTER(Table23[Product],Table23[Client]=b)))))),\"\"),1)\n"
},
{
"answer_id": 74611533,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 1,
"selected": false,
"text": "D1 =REDUCE(Table1[#Headers],UNIQUE(Table1[Client]),LAMBDA(a,b,VSTACK(a,HSTACK(b,TEXTJOIN(\",\",,FILTER(Table1[Product],Table1[Client]=b))))))\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20626730/"
] |
74,605,796
|
<p>I've been trying to install Create React App using NPM and it's giving me a permission denied error:</p>
<p><a href="https://i.stack.imgur.com/X0rWz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X0rWz.png" alt="terminal screenshot" /></a></p>
<p>I force cleaned NPM cache and it did not work.</p>
|
[
{
"answer_id": 74605932,
"author": "Mayukh Bhattacharya",
"author_id": 8162520,
"author_profile": "https://Stackoverflow.com/users/8162520",
"pm_score": 3,
"selected": true,
"text": "A10 =HSTACK(UNIQUE(Table23[Client]),BYROW(UNIQUE(Table23[Client]),LAMBDA(x,TEXTJOIN(\",\",,REPT(Table23[Product],x=Table23[Client])))))\n LET() A10 =LET(_client,UNIQUE(Table23[Client]),\nHSTACK(_client,BYROW(_client,LAMBDA(x,TEXTJOIN(\",\",,REPT(Table23[Product],x=Table23[Client]))))))\n FILTER() REPT() A10 =LET(_client,UNIQUE(Table23[Client]),\nHSTACK(_client,BYROW(_client,LAMBDA(x,TEXTJOIN(\",\",,FILTER(Table23[Product],x=Table23[Client]))))))\n A9 =DROP(IFERROR(REDUCE(\"\",UNIQUE(Table23[Client]),LAMBDA(a,b,VSTACK(a,HSTACK(b,TEXTJOIN(\",\",1,FILTER(Table23[Product],Table23[Client]=b)))))),\"\"),1)\n"
},
{
"answer_id": 74611533,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 1,
"selected": false,
"text": "D1 =REDUCE(Table1[#Headers],UNIQUE(Table1[Client]),LAMBDA(a,b,VSTACK(a,HSTACK(b,TEXTJOIN(\",\",,FILTER(Table1[Product],Table1[Client]=b))))))\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17177781/"
] |
74,605,815
|
<p>I'm working on a scheduling web application.</p>
<p>I am trying to implement a feature that detects the total hours between two times, startTime and endTime, which are selected on a form and stored via the useState hook:</p>
<pre><code> const [startTime, setStartTime] = useState("")
const [endTime, setEndTime] = useState("")
const [totalHours, setTotalHours] = useState(0)
</code></pre>
<p>The end goal is to calculate and print the total hours between both times next to "totalHours:" in the UI:
<a href="https://i.stack.imgur.com/lguYx.png" rel="nofollow noreferrer">Image of UI for selecting start, end times and total hours</a></p>
<p>My Issue: The onChange event is only updating startTime and endTime to the PREVIOUS state whenever I update their respective fields on the form.</p>
<p>For example, both start at "12:00AM". If I change the startTime to "1:00AM", when I read startTime using <code>console.log(startTime)</code>, it prints "NaN". If I then change startTime a second time, say to "2:00AM", <code>console.log(startTime)</code> prints "1:00AM"</p>
<p>I tried googling this and only found other threads referring the state as a component prop, nothing that uses the useState hook:</p>
<p><a href="https://stackoverflow.com/questions/58497548/react-usestate-hook-variable-value-dont-update-on-input-onchange-event">react useState hook variable value don't update on input onChange event</a></p>
<p><a href="https://stackoverflow.com/questions/38558200/react-setstate-not-updating-immediately?noredirect=1&lq=1">React setState not Updating Immediately</a></p>
<p>My understanding is that the setter functions for the useState hook, e.g. setStartTime() and setEndTime(), run asynchronously and cause this error.</p>
<p>I would appreciate any help.</p>
<p>my React/Typescript code:</p>
<p>The form HTML:</p>
<pre><code> return(
<form>
...
<label>
startTime:
{/* <input type="text" className={inputStyle} onChange={(e) => setStartTime(e.target.value)}/> */}
<div id="selectStartTime">
<select className={inputStyle} name="startTimeHour" id="startTimeHour"
onChange={(e) => handleStartTimeChange(e.target.value)}> {/*set the time AND calculate total hours*/}
<option value="12:00AM">12:00AM</option>
<option value="1:00AM">1:00AM</option>
<option value="2:00AM">2:00AM</option>
<option value="3:00AM">3:00AM</option>
<option value="4:00AM">4:00AM</option>
<option value="5:00AM">5:00AM</option>
<option value="6:00AM">6:00AM</option>
<option value="7:00AM">7:00AM</option>
<option value="8:00AM">8:00AM</option>
<option value="9:00AM">9:00AM</option>
<option value="10:00AM">10:00AM</option>
<option value="11:00AM">11:00AM</option>
<option value="12:00PM">12:00PM</option>
<option value="1:00PM">1:00PM</option>
<option value="2:00PM">2:00PM</option>
<option value="3:00PM">3:00PM</option>
<option value="4:00PM">4:00PM</option>
<option value="5:00PM">5:00PM</option>
<option value="6:00PM">6:00PM</option>
<option value="7:00PM">7:00PM</option>
<option value="8:00PM">8:00PM</option>
<option value="9:00PM">9:00PM</option>
<option value="10:00PM">10:00PM</option>
<option value="11:00PM">11:00PM</option>
</select>
</div>
</label>
<br/>
<label>
endTime:
{/* <input type="text" className={inputStyle} onChange={(e) => setEndTime(e.target.value)}/> */}
<div id="selectEndTime">
<select className={inputStyle} name="endTimeHour" id="endTimeHour"
onChange={(e) => handleEndTimeChange(e.target.value)}> {/*set the time AND calculate total hours*/}
<option value="12:00AM">12:00AM</option>
<option value="1:00AM">1:00AM</option>
<option value="2:00AM">2:00AM</option>
<option value="3:00AM">3:00AM</option>
<option value="4:00AM">4:00AM</option>
<option value="5:00AM">5:00AM</option>
<option value="6:00AM">6:00AM</option>
<option value="7:00AM">7:00AM</option>
<option value="8:00AM">8:00AM</option>
<option value="9:00AM">9:00AM</option>
<option value="10:00AM">10:00AM</option>
<option value="11:00AM">11:00AM</option>
<option value="12:00PM">12:00PM</option>
<option value="1:00PM">1:00PM</option>
<option value="2:00PM">2:00PM</option>
<option value="3:00PM">3:00PM</option>
<option value="4:00PM">4:00PM</option>
<option value="5:00PM">5:00PM</option>
<option value="6:00PM">6:00PM</option>
<option value="7:00PM">7:00PM</option>
<option value="8:00PM">8:00PM</option>
<option value="9:00PM">9:00PM</option>
<option value="10:00PM">10:00PM</option>
<option value="11:00PM">11:00PM</option>
</select>
</div>
</label>
<br/>
<label>
totalHours: {}
</label>
...
</form>
</code></pre>
<p>The handler functions for onChange:</p>
<pre><code> const handleStartTimeChange = (time: string) => {
setStartTime(time);
calculateTotalHours();
}
const handleEndTimeChange = (time: string) => {
setEndTime(time);
calculateTotalHours();
}
</code></pre>
<p>The function that calculates the total hours between startTime and endTime
(This is where I console.log to see that the error is happening)</p>
<pre><code> // calculate total hours based on start and end time
const calculateTotalHours = () => {
// convert strings as times to ints with values from 0 to 23 to represent 24 hour time
// where 0 = 12am and 23 = 11pm
// NOTE: This is where I see my error occuring
console.log(startTime, endTime)
// Get hours value
// All values before ":", split time by colon and get first value, convert to int
let startTimeValue = parseInt(startTime.split(":")[0]);
let endTimeValue = parseInt(endTime.split(":")[0]);
// if either time is 12, remove 12 hours
if (startTimeValue === 12) {
startTimeValue -= 12;
}
if (endTimeValue === 12) {
endTimeValue -= 12;
}
// if either time has PM, add 12 hours respectively
if (startTime.includes("PM")) {
startTimeValue += 12;
}
if (endTime.includes("PM")) {
endTimeValue += 12;
}
// calculate time between start and end times
const total = endTimeValue - startTimeValue;
// if that value is negative, return 0.
if (totalHours < 0) {
const total = 0;
setTotalHours(total);
}
// else, return the value
setTotalHours(total);
}
</code></pre>
|
[
{
"answer_id": 74605932,
"author": "Mayukh Bhattacharya",
"author_id": 8162520,
"author_profile": "https://Stackoverflow.com/users/8162520",
"pm_score": 3,
"selected": true,
"text": "A10 =HSTACK(UNIQUE(Table23[Client]),BYROW(UNIQUE(Table23[Client]),LAMBDA(x,TEXTJOIN(\",\",,REPT(Table23[Product],x=Table23[Client])))))\n LET() A10 =LET(_client,UNIQUE(Table23[Client]),\nHSTACK(_client,BYROW(_client,LAMBDA(x,TEXTJOIN(\",\",,REPT(Table23[Product],x=Table23[Client]))))))\n FILTER() REPT() A10 =LET(_client,UNIQUE(Table23[Client]),\nHSTACK(_client,BYROW(_client,LAMBDA(x,TEXTJOIN(\",\",,FILTER(Table23[Product],x=Table23[Client]))))))\n A9 =DROP(IFERROR(REDUCE(\"\",UNIQUE(Table23[Client]),LAMBDA(a,b,VSTACK(a,HSTACK(b,TEXTJOIN(\",\",1,FILTER(Table23[Product],Table23[Client]=b)))))),\"\"),1)\n"
},
{
"answer_id": 74611533,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 1,
"selected": false,
"text": "D1 =REDUCE(Table1[#Headers],UNIQUE(Table1[Client]),LAMBDA(a,b,VSTACK(a,HSTACK(b,TEXTJOIN(\",\",,FILTER(Table1[Product],Table1[Client]=b))))))\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20626729/"
] |
74,605,940
|
<p>For the last week I have been trying to get cx_oracle installed and working.
I started with an Oracle 19 appliance which is on Oracle Linux 7.
I used the official oracle site to install cx_oracle as listed below.
The install seems to have worked fine, but when I try to import the module, it is not found.
I checked all the env variables, the path, spend countless hours trying to get this work, what am I missing?
If anyone could please point me to my mistake, I would really appreciate it.
Here are all the steps I have taken so far:</p>
<p>Installing cx_Oracle for Python 3
To install cx_Oracle for Python 3 on Oracle Linux 7:</p>
<p>$ sudo yum -y install oraclelinux-developer-release-el7
$ sudo yum -y install oracle-instantclient-release-el7
$ sudo yum -y install python36-cx_Oracle
<a href="https://yum.oracle.com/oracle-linux-python.html#cx_OraclePython3FromLatest" rel="nofollow noreferrer">https://yum.oracle.com/oracle-linux-python.html#cx_OraclePython3FromLatest</a></p>
<pre><code>[oracle@localhost tmp]$ yum list installed |grep cx
python36-cx_Oracle.x86_64 8.3.0-1.el7 @ol7_developer
[oracle@localhost tmp]$ yum list installed |grep instant
oracle-instantclient-basic.x86_64 21.8.0.0.0-1 @ol7_oracle_instantclient21
oracle-instantclient-release-el7.x86_64
[oracle@localhost ~]$ yum search cx_oracle
Loaded plugins: langpacks, ulninfo
============================================================= N/S matched: cx_oracle ==============================================================cx_Oracle-12c-py27.x86_64 : Python interface to Oracle
cx_Oracle-py27.x86_64 : Python interface to Oracle
python-cx_Oracle.x86_64 : Python interface to Oracle
python-cx_Oracle-12c.x86_64 : Python interface to Oracle
python36-cx_Oracle.x86_64 : Python interface to Oracle
Name and summary matches only, use "search all" for everything.
[oracle@localhost ~]$ sudo yum install python36-cx_Oracle.x86_64
Loaded plugins: langpacks, ulninfo
Package python36-cx_Oracle-8.3.0-1.el7.x86_64 already installed and latest version
Nothing to do
[oracle@localhost ~]$ python3
Python 3.11.0 (main, Nov 26 2022, 17:15:54) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44.0.3)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import cx_oracle
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'cx_oracle'
>>> quit()
[oracle@localhost ~]$ python
Python 2.7.5 (default, Jul 1 2022, 08:35:16)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44.0.3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cx_oracle
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named cx_oracle
>>> quit()
[oracle@localhost ~]$ python --version
Python 2.7.5
[oracle@localhost ~]$ python3 --version
Python 3.11.0
[oracle@localhost ~]$ which python
/usr/bin/python
[oracle@localhost ~]$ which python3
/usr/local/bin/python3
[oracle@localhost ~]$ echo $PATH
/home/oracle/Desktop/Database_Track/coffeeshop:/home/oracle/java/jdk1.8.0_201/bin:/home/oracle/bin:/home/oracle/sqlcl/bin:/home/oracle/sqldeveloper:/home/oracle/datamodeler:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/oracle/sqlcl/bin:/home/oracle/sqldeveloper:/home/oracle/bin:/home/oracle/.local/bin:/home/oracle/bin
[oracle@localhost ~]$ echo $ORACLE_BASE
/u01/app/oracle
[oracle@localhost ~]$ echo $ORACLE_HOME
/u01/app/oracle/product/version/db_1
[oracle@localhost ~]$ echo $LD_LIBRARY_PATH
/usr/lib/oracle/21/client64/lib/
[oracle@localhost ~]$ echo $LD_LIBRARY_PATH64
/usr/lib/oracle/21/client64/lib/
[oracle@localhost ~]$ env
XDG_SESSION_ID=2
HOSTNAME=localhost.localdomain
SELINUX_ROLE_REQUESTED=
TERM=xterm-256color
SHELL=/bin/bash
HISTSIZE=1000
SSH_CLIENT=192.168.59.1 65195 22
SELINUX_USE_CURRENT_RANGE=
SSH_TTY=/dev/pts/2
USER=oracle
LD_LIBRARY_PATH=/usr/lib/oracle/21/client64/lib/
TWO_TASK=ORCL
LS_COLORS=rs=0:di=38;5;27:ln=38;5;51:mh=44;38;5;15:pi=40;38;5;11:so=38;5;13:do=38;5;5:bd=48;5;232;38;5;11:cd=48;5;232;38;5;3:or=48;5;232;38;5;9:mi=05;48;5;232;38;5;15:su=48;5;196;38;5;15:sg=48;5;11;38;5;16:ca=48;5;196;38;5;226:tw=48;5;10;38;5;16:ow=48;5;10;38;5;21:st=48;5;21;38;5;15:ex=38;5;34:*.tar=38;5;9:*.tgz=38;5;9:*.arc=38;5;9:*.arj=38;5;9:*.taz=38;5;9:*.lha=38;5;9:*.lz4=38;5;9:*.lzh=38;5;9:*.lzma=38;5;9:*.tlz=38;5;9:*.txz=38;5;9:*.tzo=38;5;9:*.t7z=38;5;9:*.zip=38;5;9:*.z=38;5;9:*.Z=38;5;9:*.dz=38;5;9:*.gz=38;5;9:*.lrz=38;5;9:*.lz=38;5;9:*.lzo=38;5;9:*.xz=38;5;9:*.bz2=38;5;9:*.bz=38;5;9:*.tbz=38;5;9:*.tbz2=38;5;9:*.tz=38;5;9:*.deb=38;5;9:*.rpm=38;5;9:*.jar=38;5;9:*.war=38;5;9:*.ear=38;5;9:*.sar=38;5;9:*.rar=38;5;9:*.alz=38;5;9:*.ace=38;5;9:*.zoo=38;5;9:*.cpio=38;5;9:*.7z=38;5;9:*.rz=38;5;9:*.cab=38;5;9:*.jpg=38;5;13:*.jpeg=38;5;13:*.gif=38;5;13:*.bmp=38;5;13:*.pbm=38;5;13:*.pgm=38;5;13:*.ppm=38;5;13:*.tga=38;5;13:*.xbm=38;5;13:*.xpm=38;5;13:*.tif=38;5;13:*.tiff=38;5;13:*.png=38;5;13:*.svg=38;5;13:*.svgz=38;5;13:*.mng=38;5;13:*.pcx=38;5;13:*.mov=38;5;13:*.mpg=38;5;13:*.mpeg=38;5;13:*.m2v=38;5;13:*.mkv=38;5;13:*.webm=38;5;13:*.ogm=38;5;13:*.mp4=38;5;13:*.m4v=38;5;13:*.mp4v=38;5;13:*.vob=38;5;13:*.qt=38;5;13:*.nuv=38;5;13:*.wmv=38;5;13:*.asf=38;5;13:*.rm=38;5;13:*.rmvb=38;5;13:*.flc=38;5;13:*.avi=38;5;13:*.fli=38;5;13:*.flv=38;5;13:*.gl=38;5;13:*.dl=38;5;13:*.xcf=38;5;13:*.xwd=38;5;13:*.yuv=38;5;13:*.cgm=38;5;13:*.emf=38;5;13:*.axv=38;5;13:*.anx=38;5;13:*.ogv=38;5;13:*.ogx=38;5;13:*.aac=38;5;45:*.au=38;5;45:*.flac=38;5;45:*.mid=38;5;45:*.midi=38;5;45:*.mka=38;5;45:*.mp3=38;5;45:*.mpc=38;5;45:*.ogg=38;5;45:*.ra=38;5;45:*.wav=38;5;45:*.axa=38;5;45:*.oga=38;5;45:*.spx=38;5;45:*.xspf=38;5;45:
LD_LIBRARY_PATH64=/usr/lib/oracle/21/client64/lib/
GNOME_CHECK=1
ORACLE_BASE=/u01/app/oracle
MAIL=/var/spool/mail/oracle
PATH=/home/oracle/Desktop/Database_Track/coffeeshop:/home/oracle/java/jdk1.8.0_201/bin:/home/oracle/bin:/home/oracle/sqlcl/bin:/home/oracle/sqldeveloper:/home/oracle/datamodeler:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/oracle/sqlcl/bin:/home/oracle/sqldeveloper:/home/oracle/bin:/home/oracle/.local/bin:/home/oracle/bin
PWD=/home/oracle
JAVA_HOME=/home/oracle/java/jdk1.8.0_201
LANG=en_US.UTF-8
SELINUX_LEVEL_REQUESTED=
HISTCONTROL=ignoredups
SHLVL=1
HOME=/home/oracle
LOGNAME=oracle
JAVAENV=true
XDG_DATA_DIRS=/home/oracle/.local/share/flatpak/exports/share:/var/lib/flatpak/exports/share:/usr/local/share:/usr/share
SSH_CONNECTION=192.168.59.1 65195 192.168.59.130 22
LESSOPEN=||/usr/bin/lesspipe.sh %s
TMZ=GMT
XDG_RUNTIME_DIR=/run/user/1000
ORACLE_HOME=/u01/app/oracle/product/version/db_1
_=/usr/bin/env
</code></pre>
|
[
{
"answer_id": 74606258,
"author": "Anthony Tuininga",
"author_id": 2510347,
"author_profile": "https://Stackoverflow.com/users/2510347",
"pm_score": 0,
"selected": false,
"text": "cx_Oracle cx_oracle"
},
{
"answer_id": 74606547,
"author": "Christopher Jones",
"author_id": 4799035,
"author_profile": "https://Stackoverflow.com/users/4799035",
"pm_score": 1,
"selected": false,
"text": "$ sudo yum -y install python3\n $ sudo yum -y install oraclelinux-developer-release-el7\n$ sudo yum -y install oracle-instantclient-release-el7\n$ sudo yum -y install python36-cx_Oracle\n cjones@localhost:~$ python3\nPython 3.6.8 (default, Nov 18 2021, 10:07:16) \n[GCC 4.8.5 20150623 (Red Hat 4.8.5-44.0.3)] on linux\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import cx_Oracle\n>>> cx_Oracle.version\n'8.3.0'\n import cx_Oracle sudo yum -y install python3\nsudo yum -y install oraclelinux-developer-release-el7\nsudo yum -y install python3-oracledb\n cjones@localhost:~$ python3\nPython 3.6.8 (default, Nov 18 2021, 10:07:16)\n[GCC 4.8.5 20150623 (Red Hat 4.8.5-44.0.3)] on linux\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import oracledb\n>>> oracledb.version\n'1.1.1'\n sudo yum -y install oracle-instantclient-release-el7\nsudo yum -y install oracle-instantclient-basic\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74605940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233309/"
] |
74,606,033
|
<p>As the title states, I am trying to use regex to split the trademark ™ symbol from a string. I am looking for two possible patterns:</p>
<ol>
<li>string™ --> expected result: string ™</li>
</ol>
<p>or</p>
<ol start="2">
<li>string™2 --> expected result: string ™ 2</li>
</ol>
<p>I came up with the below pattern to check whether a string contains either potential option:</p>
<pre><code>pattern = "[a-zA-Z0-9]+[™]([0-9])?$"
</code></pre>
<p>Is there any way to add some functionality to split it to end up with the expected results mentioned above?</p>
|
[
{
"answer_id": 74606705,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": "re.sub import re\n\ns = \"\"\"\\\nstring™\nstring™2\nstring©2\ntest test string™9 test test test\"\"\"\n\n\ns = re.sub(r\"([a-zA-Z0-9])([™©])\", r\"\\1 \\2\", s)\ns = re.sub(r\"([™©])([0-9])\", r\"\\1 \\2\", s)\n\nprint(s)\n string ™\nstring ™ 2\nstring © 2\ntest test string ™ 9 test test test\n"
},
{
"answer_id": 74606994,
"author": "colidyre",
"author_id": 2648551,
"author_profile": "https://Stackoverflow.com/users/2648551",
"pm_score": 0,
"selected": false,
"text": "™ import re\n\ntext = (\"string™\", \"string™2\", \"test test string™9 test test test\")\npattern = re.compile(r\"([^ ])(™)(.*)\")\n\nfor t in text:\n print(re.sub(pattern, r\"\\1 \\2 \\3\", t).rstrip())\n\n# Outputs:\n# --------\n# string ™\n# string ™ 2\n# test test string ™ 9 test test test\n [0-9] for t in text:\n print(t.replace(\"™\", \" ™ \").rstrip())\n"
},
{
"answer_id": 74607132,
"author": "Mark Tolonen",
"author_id": 235698,
"author_profile": "https://Stackoverflow.com/users/235698",
"pm_score": 0,
"selected": false,
"text": "re.split import re\n\ntrials = 'string™', 'string™2', 'test test string™9 test test test'\n\nfor trial in trials:\n result = [x for x in re.split(' |(™)', trial) if x]\n print(f'{result!r} {\" \".join(result)!r}')\n ['string', '™'] 'string ™'\n['string', '™', '2'] 'string ™ 2'\n['test', 'test', 'string', '™', '9', 'test', 'test', 'test'] 'test test string ™ 9 test test test'\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19293921/"
] |
74,606,065
|
<p>If I have code like <a href="https://play.rust-lang.org/?version=stable&mode=release&edition=2021&gist=06ec2b36ea946abbf46965f8316b2ef5" rel="nofollow noreferrer">this</a>:</p>
<pre><code>pub fn f(x: u16) -> impl Iterator<Item = u16> {
std::iter::once(0).chain((x >> 10)..x)
}
</code></pre>
<p>where I chain a constant in front of an iterator using <code>once</code>, do I pay an O(n) cost for it <em>when the iterator is consumed</em>? I can't tell from the assembly (other than that it definitely sets up an additional data structure in memory). How can I tell?</p>
|
[
{
"answer_id": 74606322,
"author": "Masklinn",
"author_id": 8182118,
"author_profile": "https://Stackoverflow.com/users/8182118",
"pm_score": 1,
"selected": false,
"text": "Once Option take take mem::replace(self, None)\n if at runtime once chain"
},
{
"answer_id": 74607448,
"author": "Kevin Reid",
"author_id": 99692,
"author_profile": "https://Stackoverflow.com/users/99692",
"pm_score": 3,
"selected": true,
"text": "once() chain() once() <Chain as Iterator>::next() next() for for_each() for_each() main2() pub fn f(x: u16) -> impl Iterator<Item = u16> {\n std::iter::once(0).chain((x >> 10)..x)\n}\n\npub fn main1() -> u16 {\n let mut sum = 0;\n for item in f(3) {\n sum += std::hint::black_box(item);\n }\n sum\n}\n\npub fn main2() -> u16 { \n let mut sum = 0;\n f(3).for_each(|item| {\n sum += std::hint::black_box(item);\n });\n sum\n}\n black_box() for_each() fold() Chain fold() fold() for_each() fold() sum() collect() chain() next() next() for item in iter {} continue await for"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1002430/"
] |
74,606,072
|
<p>I'm trying to draw partial or one-side open rect rounded border to achieve this effect:</p>
<p><a href="https://i.stack.imgur.com/GsMWy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GsMWy.png" alt="enter image description here" /></a></p>
<p>After playing around a bit I got this:</p>
<p><a href="https://i.stack.imgur.com/1Fk1P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1Fk1P.png" alt="enter image description here" /></a></p>
<p>This is done via:</p>
<pre class="lang-kotlin prettyprint-override"><code>RoundedCornerShape(topStartPercent = 50, bottomStartPercent = 50) // start
RoundedCornerShape(topEndPercent = 50, bottomEndPercent = 50) // end
RectangleShape // for middle
</code></pre>
<p>What I want is to remove the connecting vertical lines between the cells.</p>
|
[
{
"answer_id": 74606561,
"author": "Gabriele Mariotti",
"author_id": 2016562,
"author_profile": "https://Stackoverflow.com/users/2016562",
"pm_score": 2,
"selected": false,
"text": "offset val itemsList = (0..4).toList()\n\nRow() {\n itemsList.forEachIndexed { index, item ->\n OutlinedButton(\n onClick = { /** do something */},\n modifier = when (index) {\n 0 ->\n Modifier\n .offset(0.dp, 0.dp)\n else ->\n Modifier\n .offset((-1 * index).dp, 0.dp)\n },\n shape = when (index) {\n // left outer button\n 0 -> RoundedCornerShape(topStart = cornerRadius, topEnd = 0.dp, bottomStart = cornerRadius, bottomEnd = 0.dp)\n // right outer button\n itemsList.size - 1 -> RoundedCornerShape(topStart = 0.dp, topEnd = cornerRadius, bottomStart = 0.dp, bottomEnd = cornerRadius)\n // middle button\n else -> RoundedCornerShape(0.dp)\n },\n border = BorderStroke(1.dp, Blue500)\n ) {}\n }\n}\n"
},
{
"answer_id": 74609250,
"author": "Thracian",
"author_id": 5457853,
"author_profile": "https://Stackoverflow.com/users/5457853",
"pm_score": 3,
"selected": true,
"text": "enum class BorderOrder {\n Start, Center, End\n}\n\nfun Modifier.drawSegmentedBorder(\n strokeWidth: Dp,\n color: Color,\n cornerPercent: Int,\n borderOrder: BorderOrder,\n drawDivider: Boolean = false\n) = composed(\n factory = {\n\n val density = LocalDensity.current\n val strokeWidthPx = density.run { strokeWidth.toPx() }\n\n Modifier.drawBehind {\n val width = size.width\n val height = size.height\n val cornerRadius = height * cornerPercent / 100\n\n when (borderOrder) {\n BorderOrder.Start -> {\n\n drawLine(\n color = color,\n start = Offset(x = width, y = 0f),\n end = Offset(x = cornerRadius, y = 0f),\n strokeWidth = strokeWidthPx\n )\n\n // Top left arc\n drawArc(\n color = color,\n startAngle = 180f,\n sweepAngle = 90f,\n useCenter = false,\n topLeft = Offset.Zero,\n size = Size(cornerRadius * 2, cornerRadius * 2),\n style = Stroke(width = strokeWidthPx)\n )\n drawLine(\n color = color,\n start = Offset(x = 0f, y = cornerRadius),\n end = Offset(x = 0f, y = height - cornerRadius),\n strokeWidth = strokeWidthPx\n )\n // Bottom left arc\n drawArc(\n color = color,\n startAngle = 90f,\n sweepAngle = 90f,\n useCenter = false,\n topLeft = Offset(x = 0f, y = height - 2 * cornerRadius),\n size = Size(cornerRadius * 2, cornerRadius * 2),\n style = Stroke(width = strokeWidthPx)\n )\n drawLine(\n color = color,\n start = Offset(x = cornerRadius, y = height),\n end = Offset(x = width, y = height),\n strokeWidth = strokeWidthPx\n )\n }\n BorderOrder.Center -> {\n drawLine(\n color = color,\n start = Offset(x = 0f, y = 0f),\n end = Offset(x = width, y = 0f),\n strokeWidth = strokeWidthPx\n )\n drawLine(\n color = color,\n start = Offset(x = 0f, y = height),\n end = Offset(x = width, y = height),\n strokeWidth = strokeWidthPx\n )\n\n if (drawDivider) {\n drawLine(\n color = color,\n start = Offset(x = 0f, y = 0f),\n end = Offset(x = 0f, y = height),\n strokeWidth = strokeWidthPx\n )\n }\n }\n else -> {\n\n if (drawDivider) {\n drawLine(\n color = color,\n start = Offset(x = 0f, y = 0f),\n end = Offset(x = 0f, y = height),\n strokeWidth = strokeWidthPx\n )\n }\n\n drawLine(\n color = color,\n start = Offset(x = 0f, y = 0f),\n end = Offset(x = width - cornerRadius, y = 0f),\n strokeWidth = strokeWidthPx\n )\n\n // Top right arc\n drawArc(\n color = color,\n startAngle = 270f,\n sweepAngle = 90f,\n useCenter = false,\n topLeft = Offset(x = width - cornerRadius * 2, y = 0f),\n size = Size(cornerRadius * 2, cornerRadius * 2),\n style = Stroke(width = strokeWidthPx)\n )\n drawLine(\n color = color,\n start = Offset(x = width, y = cornerRadius),\n end = Offset(x = width, y = height - cornerRadius),\n strokeWidth = strokeWidthPx\n )\n // Bottom right arc\n drawArc(\n color = color,\n startAngle = 0f,\n sweepAngle = 90f,\n useCenter = false,\n topLeft = Offset(\n x = width - 2 * cornerRadius,\n y = height - 2 * cornerRadius\n ),\n size = Size(cornerRadius * 2, cornerRadius * 2),\n style = Stroke(width = strokeWidthPx)\n )\n drawLine(\n color = color,\n start = Offset(x = 0f, y = height),\n end = Offset(x = width -cornerRadius, y = height),\n strokeWidth = strokeWidthPx\n )\n }\n }\n }\n }\n)\n @Composable\nprivate fun SegmentedBorderSample() {\n Row {\n repeat(3) {\n\n val order = when (it) {\n 0 -> BorderOrder.Start\n 2 -> BorderOrder.End\n else -> BorderOrder.Center\n }\n\n Box(\n contentAlignment = Alignment.Center,\n modifier = Modifier\n .size(40.dp)\n .drawSegmentedBorder(\n strokeWidth = 2.dp,\n color = Color.Green,\n borderOrder = order,\n cornerPercent = 40,\n drawDivider = false\n )\n .padding(4.dp)\n ) {\n Text(text = \"$it\")\n }\n }\n }\n\n\n Row {\n repeat(4) {\n\n val order = when (it) {\n 0 -> BorderOrder.Start\n 3 -> BorderOrder.End\n else -> BorderOrder.Center\n }\n\n Box(\n contentAlignment = Alignment.Center,\n modifier = Modifier\n .size(40.dp)\n .drawSegmentedBorder(\n strokeWidth = 2.dp,\n color = Color.Cyan,\n borderOrder = order,\n cornerPercent = 50,\n drawDivider = true\n )\n .padding(4.dp)\n ) {\n Text(text = \"$it\")\n }\n }\n }\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1274974/"
] |
74,606,086
|
<p>I am trying to summarize rows in a data frame by adding numerical row values and keeping the character values from the second occurrence of the grouping variable.</p>
<p>I have the data frame listed below:</p>
<pre class="lang-r prettyprint-override"><code>df <- data.frame(
Season = c('Summer', 'Fall', 'Fall', 'Winter','Spring', 'Spring'),
Number = c(1,2,2,6,7,2),
Character = c('1s', '2s', 's', '1s', '3s', 'q')
)
</code></pre>
<p>df</p>
<pre><code> Season Number Character
1 Summer 1 1s
2 Fall 2 2s
3 Fall 2 s
4 Winter 6 1s
5 Spring 7 3s
6 Spring 2 q
</code></pre>
<p>I am trying to summarize the data into the format listed below but <code>dplyr</code>'s summarize functions don't work well with non-numeric columns.</p>
<p>Here is my expected output...</p>
<pre><code> Season Number Character
1 Summer 1 1s
2 Fall 4 s
4 Winter 6 1s
5 Spring 9 q
</code></pre>
|
[
{
"answer_id": 74606153,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 3,
"selected": true,
"text": "[[2]] summarize() library(dplyr)\n\ndf %>%\n group_by(Season) %>%\n summarize(\n Number = sum(Number),\n Character = ifelse(length(Character) > 1, Character[[2]], Character)\n ) %>%\n ungroup()\n # A tibble: 4 × 3\n Season Number Character\n <chr> <dbl> <chr> \n1 Fall 4 s \n2 Spring 9 q \n3 Summer 1 1s \n4 Winter 6 1s \n"
},
{
"answer_id": 74606225,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 1,
"selected": false,
"text": "last library(dplyr)\n\ndf %>% \n group_by(Season) %>% \n summarize(across(Number:Character, ~ ifelse(is.numeric(.x), sum(.x), last(.x))))\n# A tibble: 4 × 3\n Season Number Character\n <chr> <dbl> <chr>\n1 Fall 4 s\n2 Spring 9 q\n3 Summer 1 1s\n4 Winter 6 1s\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11537219/"
] |
74,606,106
|
<p>I need to filter rows if some of the variables have missing values. Here is an example dataset.</p>
<pre><code>df <- data.frame(id = c(1,2,3,4,5),
v1 = c(5,6,7,8,1),
v2 = c(5,9,34,2,1),
a1 = c(1,NA,NA,2,3),
a2 = c(NA,1,NA,8,9))
> df
id v1 v2 a1 a2
1 1 5 5 1 NA
2 2 6 9 NA 1
3 3 7 34 NA NA
4 4 8 2 2 8
5 5 1 1 3 9
</code></pre>
<p>From columns 4 and 5, if there is any missingness, I need to filter them. How can I code by specifying the column number (4th column) to the end of the columns? Because I have multiple and differentiating in the number of columns for different datasets.</p>
<p>How can I get this filtered dataset below?</p>
<pre><code>> df1
id v1 v2 a1 a2
1 1 5 5 1 NA
2 2 6 9 NA 1
3 3 7 34 NA NA
</code></pre>
|
[
{
"answer_id": 74606124,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "if_any filter : last_col() library(dplyr)\ndf %>% \n filter(if_any(4:last_col(), is.na))\n id v1 v2 a1 a2\n1 1 5 5 1 NA\n2 2 6 9 NA 1\n3 3 7 34 NA NA\n"
},
{
"answer_id": 74606165,
"author": "onyambu",
"author_id": 8380272,
"author_profile": "https://Stackoverflow.com/users/8380272",
"pm_score": 2,
"selected": false,
"text": "df[!complete.cases(df[4:ncol(df)]),]\n id v1 v2 a1 a2\n1 1 5 5 1 NA\n2 2 6 9 NA 1\n3 3 7 34 NA NA\n\nsubset(df, !complete.cases(df[4:ncol(df)]))\n id v1 v2 a1 a2\n1 1 5 5 1 NA\n2 2 6 9 NA 1\n3 3 7 34 NA NA\n"
},
{
"answer_id": 74606278,
"author": "Neeraj",
"author_id": 5047311,
"author_profile": "https://Stackoverflow.com/users/5047311",
"pm_score": 3,
"selected": true,
"text": "complete.cases df[!complete.cases(df[, 4:ncol(df)]),]\n apply df[apply(df[, 4:ncol(df)], 1, FUN = function(x) any(is.na(x))), ]\n data.table library(data.table)\nsetDT(df)\ndf[!complete.cases(df[, 4:ncol(df)])]\n df <- data.frame(id = c(1,2,3,4,5),\n v1 = c(5,6,7,8,1),\n v2 = c(5,9,34,2,1),\n a1 = c(1,NA,NA,2,3),\n a2 = c(NA,1,NA,8,9))\n"
},
{
"answer_id": 74606498,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 2,
"selected": false,
"text": "base df[rowSums(is.na(df[, 4:ncol(df)])) > 0, ]\n any(is.na(x)) df[apply(df[, 4:ncol(df)], 1, anyNA), ]\n id v1 v2 a1 a2\n1 1 5 5 1 NA\n2 2 6 9 NA 1\n3 3 7 34 NA NA\n"
},
{
"answer_id": 74606612,
"author": "Yomi.blaze93",
"author_id": 16087142,
"author_profile": "https://Stackoverflow.com/users/16087142",
"pm_score": 2,
"selected": false,
"text": "df <- data.frame(id = c(1,2,3,4,5),\n v1 = c(5,6,7,8,1),\n v2 = c(5,9,34,2,1),\n a1 = c(1,NA,NA,2,3),\n a2 = c(NA,1,NA,8,9))\n \n new_df <- df %>% \n filter_all(any_vars(is.na(.)))\n\nprint(new_df)\n\nid v1 v2 a1 a2\n1 1 5 5 1 NA\n2 2 6 9 NA 1\n3 3 7 34 NA NA\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5933306/"
] |
74,606,127
|
<p>Assume that N is the number of agents and M is the number of tasks. The number of tasks is greater than number of agents, i.e. M > N. Each agent must have at <strong>least one task</strong>. Given rectangular matrix of costs, find the optimal solution (i.e. assign each task to exactly one agent so each agent has at least one task and the cost is minimized).</p>
<p>What effective algorithm could solve this problem?</p>
<p>I've tried to implement naive recursive algorithm with memorization, but it is too slow for values of M over 1000. I know about Hungarian method, but I wasn't able to use the algorithm with my constraint (each agent must have at least one task).</p>
|
[
{
"answer_id": 74607426,
"author": "btilly",
"author_id": 585411,
"author_profile": "https://Stackoverflow.com/users/585411",
"pm_score": 2,
"selected": false,
"text": "M-N M-N M M N M-N"
},
{
"answer_id": 74608082,
"author": "Erwin Kalvelagen",
"author_id": 5625534,
"author_profile": "https://Stackoverflow.com/users/5625534",
"pm_score": 2,
"selected": false,
"text": "# sets\ni : tasks\nj : agents\n\n# model\nmin sum((i,j), c[i,j]*x[i,j])\nsum(j, x[i,j]) = 1 ∀i \"assign each task to an agent\"\nsum(i, x[i,j]) >= 1 ∀j \"each agent needs to do at least one task\"\nx[i,j] ∈ {0,1}\n import cvxpy as cp\nimport numpy as np\n\nNTASK = 1000\nNAGENT = 200\n\n# random data\nnp.random.seed(123)\nc = np.random.uniform(1,100,(NTASK,NAGENT))\n\n# model\nx = cp.Variable((NTASK,NAGENT),boolean=True)\nprob = cp.Problem(cp.Minimize(cp.sum(cp.multiply(c,x))),\n [cp.sum(x,axis=1) == 1, \n cp.sum(x,axis=0) >= 1])\n\n# solve and print results\nres = prob.solve(verbose=True)\nprint(prob.status)\nprint(prob.value)\n# print(x.value) \n x[i,j] ∈ [0,1]"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20627066/"
] |
74,606,200
|
<p>I have a pyspark dataframe with Quarterly data in that. The data is in the following format</p>
<pre><code>2022-03-01 abc
2022-06-01 xyz
2000-03-01 abcd
</code></pre>
<p>Starting from the very first date (somewhere around 1960's) I need to find if there are any quarters missing from the date. And for the current year, any quarters that have passed. For example for 2022 checking only first 3 quarters if the data exists for those.</p>
<p>the code i have written works fine for the previous years but takes a few lines to code for the whole scenario to cover.</p>
<p>I am looking for a one liner kind of code if possible.</p>
<p>i am looking for all quarters in all years except for 1965 as there is no full quarter data is available for that year (Just one year is an exception)</p>
<p>My code is something as under.</p>
<pre><code>qtrs = df.groupBy(year("mydate").alias("q_count")).count().filter(col("count")!= 4).filter(~col("qtr_count").isin(1965)).collect()
If len[qtrs] !=0:
return ("Error")
</code></pre>
<p>The above works for previous years but for the current year i have to write a separate logic. Is there a way I can incorporate the complete logic in the above one liner ? to check all the quarters.</p>
<p>Simply i want to make sure that no quarters are missing from the data starting from particular year Up until the last Quarter of the current year.</p>
<p>Any help please ?</p>
|
[
{
"answer_id": 74607426,
"author": "btilly",
"author_id": 585411,
"author_profile": "https://Stackoverflow.com/users/585411",
"pm_score": 2,
"selected": false,
"text": "M-N M-N M M N M-N"
},
{
"answer_id": 74608082,
"author": "Erwin Kalvelagen",
"author_id": 5625534,
"author_profile": "https://Stackoverflow.com/users/5625534",
"pm_score": 2,
"selected": false,
"text": "# sets\ni : tasks\nj : agents\n\n# model\nmin sum((i,j), c[i,j]*x[i,j])\nsum(j, x[i,j]) = 1 ∀i \"assign each task to an agent\"\nsum(i, x[i,j]) >= 1 ∀j \"each agent needs to do at least one task\"\nx[i,j] ∈ {0,1}\n import cvxpy as cp\nimport numpy as np\n\nNTASK = 1000\nNAGENT = 200\n\n# random data\nnp.random.seed(123)\nc = np.random.uniform(1,100,(NTASK,NAGENT))\n\n# model\nx = cp.Variable((NTASK,NAGENT),boolean=True)\nprob = cp.Problem(cp.Minimize(cp.sum(cp.multiply(c,x))),\n [cp.sum(x,axis=1) == 1, \n cp.sum(x,axis=0) >= 1])\n\n# solve and print results\nres = prob.solve(verbose=True)\nprint(prob.status)\nprint(prob.value)\n# print(x.value) \n x[i,j] ∈ [0,1]"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18627728/"
] |
74,606,204
|
<p>I have no problem with the following html tabs and java script in a normal rmarkdown. However, I have encounter a difficulty after adding <code>runtime: shiny</code> in yaml. The contents are not displayed.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>---
title: "Untitled"
author: "John Doe"
date: "2022-11-28"
output: html_document
#runtime: shiny
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
<!-- Tab links -->
<div class="tab">
<button class="tablinks active" onclick="tablabel(event, 'app_1')">Application 1</button>
<button class="tablinks" onclick="tablabel(event, 'app_2')">Application 2</button>
</div>
<!-- Tab content -->
<div id="app_1" class="tabcontent" style="display:block">
This is the content for application 1.
</div>
<div id="app_2" class="tabcontent">
This is the content for application 2.
</div>
<style type = "text/css">
.tab {
overflow: hidden;
/*border: 1px solid #ccc;*/
/*background-color: #f1f1f1;*/
}
/* Style the buttons that are used to open the tab content */
.tab button {
background-color: #f1e4ff;
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: 0.3s;
font-size: 17px;
margin-left:0.3em;
}
/* Change background color of buttons on hover */
.tab button:hover {
background-color: #e4e5ff;
}
/* Create an active/current tablink class */
.tab button.active {
background-color: #ffe4ff;
}
/* Style the tab content */
.tabcontent {
display: none;
padding: 6px 12px;
/*border: 1px solid #ccc;*/
border-top: none;
}
</style>
<script>
function tablabel(evt, tabName) {
// Declare all variables
var i, tabcontent, tablinks;
// Get all elements with class="tabcontent" and hide them
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Get all elements with class="tablinks" and remove the class "active"
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
// Show the current tab, and add an "active" class to the button that opened the tab
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
</script></code></pre>
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>My session info is:
R version 4.2.0 (2022-04-22 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19044)
Matrix products: default
locale:
[1] LC_COLLATE=English_Canada.utf8 LC_CTYPE=English_Canada.utf8
[3] LC_MONETARY=English_Canada.utf8 LC_NUMERIC=C
[5] LC_TIME=English_Canada.utf8
attached base packages:
[1] stats4 stats graphics grDevices utils datasets methods base
other attached packages:
[1] tibble_3.1.8 dplyr_1.0.10 ggplot2_3.4.0 Spectra_1.8.0
[5] ProtGenerics_1.29.1 BiocParallel_1.30.3 S4Vectors_0.34.0 BiocGenerics_0.42.0
loaded via a namespace (and not attached):
[1] Rcpp_1.0.9 assertthat_0.2.1 digest_0.6.30 utf8_1.2.2
[5] mime_0.12 R6_2.5.1 evaluate_0.18 pillar_1.8.1
[9] rlang_1.0.6 curl_4.3.3 rstudioapi_0.14 jquerylib_0.1.4
[13] rmarkdown_2.18 labeling_0.4.2 stringr_1.4.1 munsell_0.5.0
[17] shiny_1.7.3 compiler_4.2.0 httpuv_1.6.6 xfun_0.35
[21] pkgconfig_2.0.3 askpass_1.1 htmltools_0.5.3 openssl_2.0.4
[25] tidyselect_1.2.0 IRanges_2.30.0 codetools_0.2-18 fansi_1.0.3
[29] withr_2.5.0 later_1.3.0 MASS_7.3-56 grid_4.2.0
[33] jsonlite_1.8.3 xtable_1.8-4 gtable_0.3.1 lifecycle_1.0.3
[37] DBI_1.1.3 magrittr_2.0.3 MsCoreUtils_1.8.0 scales_1.2.1
[41] cli_3.4.1 stringi_1.7.8 cachem_1.0.6 farver_2.1.1
[45] fs_1.5.2 promises_1.2.0.1 bslib_0.4.1 ellipsis_0.3.2
[49] generics_0.1.3 vctrs_0.5.1 tools_4.2.0 glue_1.6.2
[53] rsconnect_0.8.28 parallel_4.2.0 fastmap_1.1.0 yaml_2.3.6
[57] clue_0.3-63 colorspace_2.0-3 cluster_2.1.3 memoise_2.0.1
[61] knitr_1.41 sass_0.4.3 </code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74607426,
"author": "btilly",
"author_id": 585411,
"author_profile": "https://Stackoverflow.com/users/585411",
"pm_score": 2,
"selected": false,
"text": "M-N M-N M M N M-N"
},
{
"answer_id": 74608082,
"author": "Erwin Kalvelagen",
"author_id": 5625534,
"author_profile": "https://Stackoverflow.com/users/5625534",
"pm_score": 2,
"selected": false,
"text": "# sets\ni : tasks\nj : agents\n\n# model\nmin sum((i,j), c[i,j]*x[i,j])\nsum(j, x[i,j]) = 1 ∀i \"assign each task to an agent\"\nsum(i, x[i,j]) >= 1 ∀j \"each agent needs to do at least one task\"\nx[i,j] ∈ {0,1}\n import cvxpy as cp\nimport numpy as np\n\nNTASK = 1000\nNAGENT = 200\n\n# random data\nnp.random.seed(123)\nc = np.random.uniform(1,100,(NTASK,NAGENT))\n\n# model\nx = cp.Variable((NTASK,NAGENT),boolean=True)\nprob = cp.Problem(cp.Minimize(cp.sum(cp.multiply(c,x))),\n [cp.sum(x,axis=1) == 1, \n cp.sum(x,axis=0) >= 1])\n\n# solve and print results\nres = prob.solve(verbose=True)\nprint(prob.status)\nprint(prob.value)\n# print(x.value) \n x[i,j] ∈ [0,1]"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13628691/"
] |
74,606,207
|
<p>I am trying to reduce some logging noise I am getting from PostgreSQL on my Heroku/Rails application. Specifically, I am trying to configure the <code>client_min_messages</code> setting to <code>warning</code> instead of the default <code>notice</code>.</p>
<p>I followed the steps in <a href="https://anti-pattern.com/suppressing-notice-messages-with-postgresql-on-rails" rel="nofollow noreferrer">this post</a> and specified <code>min_messages: warning</code> in my <code>database.yml</code> file but that doesn't seem to have any effect on my Heroku PostgreSQL instance. I'm still seeing NOTICE messages in my logs and when I run <code>SHOW client_min_messages</code> on the database it still returns <code>notice</code>.</p>
<p>Here is a redacted example of the logs I'm seeing in Papertrail:</p>
<pre><code>Nov 23 15:04:51 my-app-name-production app/postgres.123467 [COLOR] [1234-5] sql_error_code = 00000 log_line="5733" application_name="puma: cluster worker 0: 4 [app]" NOTICE: text-search query contains only stop words or doesn't contain lexemes, ignored
</code></pre>
<p>I can also confirm that the setting does seem to be in the Rails configuration - <code>Rails.application.config.database_configuration[Rails.env]</code> in a production console does show a hash containing <code>"min_messages"=>"warning"</code></p>
<p>I also tried manually updating that via the PostgreSQL console - so <code>SET client_min_messages TO WARNING;</code> - but that setting doesn't 'stick'. It seems to be reset on the next session.</p>
<p>How do I configure <code>client_min_messages</code> to be <code>warning</code> on Heroku/Rails?</p>
|
[
{
"answer_id": 74607773,
"author": "Chris",
"author_id": 354577,
"author_profile": "https://Stackoverflow.com/users/354577",
"pm_score": 0,
"selected": false,
"text": "ALTER DATABASE your_database\n SET client_min_messages TO 'warning';\n"
},
{
"answer_id": 74662063,
"author": "Jabbar",
"author_id": 16930239,
"author_profile": "https://Stackoverflow.com/users/16930239",
"pm_score": -1,
"selected": false,
"text": "psql -d rails_app_development\nALTER ROLE USER_NAME SET client_min_messages TO WARNING;\n USER_NAME"
},
{
"answer_id": 74664485,
"author": "regex",
"author_id": 9470979,
"author_profile": "https://Stackoverflow.com/users/9470979",
"pm_score": -1,
"selected": false,
"text": "client_min_messages notice notice client_min_messages heroku pg:psql SET client_min_messages warning heroku pg:psql -c \"SET client_min_messages TO warning;\"\n client_min_messages notice ALTER DATABASE client_min_messages heroku pg:psql -c \"ALTER DATABASE <database_name> SET client_min_messages TO warning;\"\n <database_name> client_min_messages warning"
},
{
"answer_id": 74666374,
"author": "Begging",
"author_id": 16606223,
"author_profile": "https://Stackoverflow.com/users/16606223",
"pm_score": -1,
"selected": false,
"text": "SHOW config_file; client_min_messages = warning postgresql.conf pg_ctl reload SHOW client_min_messages;"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121531/"
] |
74,606,218
|
<p>I have 4 images into a div, how to split them in 2 columns of 2 images in CSS?</p>
<pre><code> <div id="your-cards">
<img src="./cards/BACK5.jpeg" aria-valuetext="7-c" id="P0">
<img src="./cards/BACK5.jpeg" aria-valuetext="4-c" id="P1">
<img src="./cards/BACK5.jpeg" aria-valuetext="2-h" id="P2">
<img src="./cards/BACK5.jpeg" aria-valuetext="A-c" id="P3">
</div>
</code></pre>
<p>Thanks</p>
|
[
{
"answer_id": 74606273,
"author": "OliverRadini",
"author_id": 5011469,
"author_profile": "https://Stackoverflow.com/users/5011469",
"pm_score": 0,
"selected": false,
"text": "flex #your-cards {\n display: flex;\n flex-wrap: wrap;\n padding-left: 0;\n}\n\n#your-cards div {\n list-style: none;\n flex: 0 0 50%;\n} <div id=\"your-cards\">\n <div>1</div>\n <div>2</div>\n <div>3</div>\n <div>4</div>\n</div> flex flex-grow flex-shrink flex-basis"
},
{
"answer_id": 74606275,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 2,
"selected": false,
"text": "#your-cards { display: grid; grid-template-columns: repeat(2, 50px); gap: 0.5em; } <div id=\"your-cards\">\n <img src=\"https://dummyimage.com/50x50/555/f0f\" aria-valuetext=\"7-c\" id=\"P0\">\n <img src=\"https://dummyimage.com/50x50/6e6/fff\" aria-valuetext=\"4-c\" id=\"P1\">\n <img src=\"https://dummyimage.com/50x50/a33/fff\" aria-valuetext=\"2-h\" id=\"P2\">\n <img src=\"https://dummyimage.com/50x50/44d/fff\" aria-valuetext=\"A-c\" id=\"P3\">\n</div>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16019296/"
] |
74,606,235
|
<p><a href="https://github.com/SteveSandersonMS/BlazeOrbital/" rel="nofollow noreferrer">SteveSandersonMSBlazeOrbital</a></p>
<p>i am trying to launch the Steve's Sanderson Blazer Orbital project.
i added SQLitePCLRaw.Bundle_e_sqlite3 package via NuGet manager.
but project throws an exception :</p>
<pre><code>System.DllNotFoundException: e_sqlite3
at SQLitePCL.SQLite3Provider_e_sqlite3.SQLitePCL.ISQLite3Provider.sqlite3_libversion_number()
at SQLitePCL.raw.SetProvider(ISQLite3Provider imp)
</code></pre>
<p>any suggestion , how to solve the problem ?</p>
|
[
{
"answer_id": 74606273,
"author": "OliverRadini",
"author_id": 5011469,
"author_profile": "https://Stackoverflow.com/users/5011469",
"pm_score": 0,
"selected": false,
"text": "flex #your-cards {\n display: flex;\n flex-wrap: wrap;\n padding-left: 0;\n}\n\n#your-cards div {\n list-style: none;\n flex: 0 0 50%;\n} <div id=\"your-cards\">\n <div>1</div>\n <div>2</div>\n <div>3</div>\n <div>4</div>\n</div> flex flex-grow flex-shrink flex-basis"
},
{
"answer_id": 74606275,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 2,
"selected": false,
"text": "#your-cards { display: grid; grid-template-columns: repeat(2, 50px); gap: 0.5em; } <div id=\"your-cards\">\n <img src=\"https://dummyimage.com/50x50/555/f0f\" aria-valuetext=\"7-c\" id=\"P0\">\n <img src=\"https://dummyimage.com/50x50/6e6/fff\" aria-valuetext=\"4-c\" id=\"P1\">\n <img src=\"https://dummyimage.com/50x50/a33/fff\" aria-valuetext=\"2-h\" id=\"P2\">\n <img src=\"https://dummyimage.com/50x50/44d/fff\" aria-valuetext=\"A-c\" id=\"P3\">\n</div>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7060504/"
] |
74,606,293
|
<p>In the below code, I am repeating the same code twice except one change. If there is a way to write the same in single line then it would be great.</p>
<p>The only changes I made is <code>Obsc</code> and <code>zp</code> based on the <code>if..else</code> statement.</p>
<pre><code>var zp = __Services.GetValue("Z", Order.Code);
var St="";
if(sp.Label != null)
{
var Obsc = _Services.GetValue("Z", sp.Label);
St= string.Format(Obsc, .......,userProfile.DisplayName());
}
else
{
St = string.Format(zp, ......., userProfile.DisplayName());
}
</code></pre>
|
[
{
"answer_id": 74606325,
"author": "SilicDev",
"author_id": 20614914,
"author_profile": "https://Stackoverflow.com/users/20614914",
"pm_score": -1,
"selected": false,
"text": "result = condition ? trueValue : falseValue;\n if ... else ..."
},
{
"answer_id": 74606378,
"author": "Luca Q",
"author_id": 10819948,
"author_profile": "https://Stackoverflow.com/users/10819948",
"pm_score": 0,
"selected": false,
"text": "var code = sp.Label is null\n ? Order.Code\n : sp.Label;\n\nvar zpOrObsc = service.GetValue(\"Z\", code); // please use a valid variable name\nvar st = string.Format(zpOrObsc, ......, userProfile.DisplayName());\n"
},
{
"answer_id": 74606379,
"author": "gunr2171",
"author_id": 1043380,
"author_profile": "https://Stackoverflow.com/users/1043380",
"pm_score": 0,
"selected": false,
"text": "GetValue GetValue string.Format var whateverTheSecondParamForGetValueIs = Order.Code;\n\nif (sp.Label != null) {\n whateverTheSecondParamForGetValueIs = sp.Label;\n}\n\nvar zp = _Services.GetValue(\"Z\", Order.Code);\nvar St = string.Format(zp, ......., userProfile.DisplayName());\n"
},
{
"answer_id": 74606406,
"author": "Alex Broitman",
"author_id": 874702,
"author_profile": "https://Stackoverflow.com/users/874702",
"pm_score": 0,
"selected": false,
"text": "St = string.Format(_Services.GetValue(\"Z\", sp.Label ?? Order.Code), ......., userProfile.DisplayName());\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20505175/"
] |
74,606,320
|
<p>I am facing a very peculiar issue with slf4j log in my SpringBoot application. Code example -</p>
<pre><code>@RestControllerAdvice
@Slf4j
public class ControllerAdvice{
public ResponseEntity getErrors(String status, String source, String uid, String res) {
...
...
log.error("Error is {} source, uid, res: {} | {} | {}", status, source, uid, res);
...
...
}
}
</code></pre>
<p>Here whenever any of parameter(status, source, uid or res) is null the entire log is getting skipped. Is there any way we can print the value, even if it is null?</p>
<p>The dependencies I am using are below -</p>
<pre><code>//sfl4j
compile("org.slf4j:slf4j-api:1.7.32")
//lombok
compileOnly("org.projectlombok:lombok:1.18.2")
annotationProcessor("org.projectlombok:lombok:1.18.8")
</code></pre>
|
[
{
"answer_id": 74606325,
"author": "SilicDev",
"author_id": 20614914,
"author_profile": "https://Stackoverflow.com/users/20614914",
"pm_score": -1,
"selected": false,
"text": "result = condition ? trueValue : falseValue;\n if ... else ..."
},
{
"answer_id": 74606378,
"author": "Luca Q",
"author_id": 10819948,
"author_profile": "https://Stackoverflow.com/users/10819948",
"pm_score": 0,
"selected": false,
"text": "var code = sp.Label is null\n ? Order.Code\n : sp.Label;\n\nvar zpOrObsc = service.GetValue(\"Z\", code); // please use a valid variable name\nvar st = string.Format(zpOrObsc, ......, userProfile.DisplayName());\n"
},
{
"answer_id": 74606379,
"author": "gunr2171",
"author_id": 1043380,
"author_profile": "https://Stackoverflow.com/users/1043380",
"pm_score": 0,
"selected": false,
"text": "GetValue GetValue string.Format var whateverTheSecondParamForGetValueIs = Order.Code;\n\nif (sp.Label != null) {\n whateverTheSecondParamForGetValueIs = sp.Label;\n}\n\nvar zp = _Services.GetValue(\"Z\", Order.Code);\nvar St = string.Format(zp, ......., userProfile.DisplayName());\n"
},
{
"answer_id": 74606406,
"author": "Alex Broitman",
"author_id": 874702,
"author_profile": "https://Stackoverflow.com/users/874702",
"pm_score": 0,
"selected": false,
"text": "St = string.Format(_Services.GetValue(\"Z\", sp.Label ?? Order.Code), ......., userProfile.DisplayName());\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/678892/"
] |
74,606,335
|
<p>We are using Apache Flink to read a Kafka topic which contains an Id and a list of objects as follows:</p>
<pre><code>{
Id: "12345",
Objetcs: [
{
fatherId: "1a",
id: "111",
name: "aabc"
},
{
fatherId: "1b",
id: "222",
name: "abffc"
},
{
fatherId: "1a",
id: "333",
name: "gfds"
},
...
]
}
</code></pre>
<p>Then we convert it to a data stream of tuples containing the listId and the product. Finally we do a KeyBy and a TumblingProcessingTimeWindows of 10 seconds to group the data by the listId and fhaterId and convert the result of grouping the data to a string as follows:
“{ [ {fhaterId: “1a”, id: “222”, name: “aabc”}, {fhaterId: “1a”, id: “333”, name: “gfds”} ], [ {fhaterId: “1a ”, id: “222”, name: “aabc”} ] }”</p>
<p>The problem is that in some tests, we send 5 lists with 128,000 data each, where the expected result should be 5 string, but there are times when 6 arrive because one of the messages is divided.
In the example above it would be something like:
String 1: “{[{fhaterId: “1a”, id: “222”, name: “aabc”}], [{fhaterId: “1a”, id: “222”, name: “aabc”}]}”
String 2: “{[{fhaterId: “1a”, id: “333”, name: “gfds”}]}”</p>
<p>When the expected response is a single string.</p>
<p>what could be the reason?</p>
<p>The flow code is as follows:</p>
<pre><code>DataStream<Result> sourceNegotiation = listNegotiationProducts
.flatMap(new FlatMapFunction<ListNegotiationProduct, Tuple2<UUID, NegotiationProduct>>() {
@Override
public void flatMap(ListNegotiationProduct listNegotiationProduct, Collector<Tuple2<UUID, NegotiationProduct>> out) throws Exception {
listNegotiationProduct.getProducts().forEach(lnp -> {
Tuple2<UUID, NegotiationProduct> response = new Tuple2<>(listNegotiationProduct.getTransactionId(), lnp);
out.collect(response);
});
}
})
.keyBy(new KeySelector<Tuple2<UUID, NegotiationProduct>, Tuple2<UUID, Integer>>() {
@Override
public Tuple2<UUID, Integer> getKey(Tuple2<UUID, NegotiationProduct> value) throws Exception {
return Tuple2.of(value.f0, value.f1.getNegotiationId());
}
})
.window(TumblingProcessingTimeWindows.of(Time.seconds(10)))
.allowedLateness(Time.seconds(1))
.apply(new WindowFunction<Tuple2<UUID, NegotiationProduct>, Tuple2<UUID, Negotiation>, Tuple2<UUID, Integer>, TimeWindow>() {
@Override
public void apply(Tuple2<UUID, Integer> uuidIntegerTuple2, TimeWindow window, Iterable<Tuple2<UUID, NegotiationProduct>> iterable, Collector<Tuple2<UUID, Negotiation>> collector) throws Exception {
Negotiation negotiation = new Negotiation();
Tuple2<UUID, Negotiation> response = new Tuple2<>();
List<Product> productList = new ArrayList<>();
iterable.iterator().forEachRemaining(negotiationProduct -> {
negotiation.setNegotiationId(negotiationProduct.f1.getNegotiationId());
response.setField(negotiationProduct.f0, 0);
List<String> observationList = new ArrayList<>();
observationList.add(negotiationProduct.f1.getObservation());
productList.add(Product
.builder()
.productGtin(negotiationProduct.f1.getProductGtin())
.state(negotiationProduct.f1.getState())
.observation(observationList)
.retailerCode(negotiationProduct.f1.getRetailerCode()).build());
});
negotiation.setNegotiationProgressProducts(productList);
response.setField(negotiation, 1);
collector.collect(response);
}
})
.keyBy(t -> t.f0)
.window(TumblingProcessingTimeWindows.of(Time.seconds(10)))
.allowedLateness(Time.seconds(1))
.apply(new WindowFunction<Tuple2<UUID, Negotiation>, Result, UUID, TimeWindow>() {
@Override
public void apply(UUID uuid, TimeWindow window, Iterable<Tuple2<UUID, Negotiation>> iterable, Collector<Result> collector) throws Exception {
List<Negotiation> negotiations = new ArrayList<>();
iterable.iterator().forEachRemaining(n -> {
negotiations.add(n.f1);
});
collector.collect(BuildResult.build(new Payload(negotiations), uuid));
}
})
.returns(Result.class);
</code></pre>
|
[
{
"answer_id": 74612872,
"author": "David Anderson",
"author_id": 2000823,
"author_profile": "https://Stackoverflow.com/users/2000823",
"pm_score": 1,
"selected": false,
"text": "TumblingProcessingTimeWindows"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19017280/"
] |
74,606,380
|
<p>i have some rows on "MENU" table</p>
<pre><code>id, shop, size
1, 1 , 3
2, 1 , 8
3, 2 , 5
</code></pre>
<p>i need to show 1 row for each <strong>shop</strong> so if <strong>shop id</strong> is same then show the row with high value on column <strong>size</strong>
and results should be like this</p>
<pre><code>id, shop, size
2, 1 , 8
3, 2 , 5
</code></pre>
<p>also if size is 0 on both rows it will display just 1 row</p>
<p>i need something like this</p>
<blockquote>
<pre><code>SELECT * FROM menu GROUP by shop
</code></pre>
</blockquote>
<p>but to show the row with high value</p>
<p>i have tried this but if rows have <strong>0</strong> on <strong>column size</strong> then it shows both of them</p>
<pre><code>SELECT a.* FROM menu a
LEFT JOIN menu b
ON a.shop=b.shop AND a.size< b.size
WHERE b.size NULL
</code></pre>
|
[
{
"answer_id": 74606519,
"author": "Stu",
"author_id": 15332650,
"author_profile": "https://Stackoverflow.com/users/15332650",
"pm_score": 3,
"selected": true,
"text": "with t as (\n Select *, row_number() over(partition by Shop order by Size desc) rn\n from Menu\n)\nselect Id, Shop, size\nfrom t\nwhere rn = 1;\n"
},
{
"answer_id": 74606580,
"author": "Thorsten Kettner",
"author_id": 2270762,
"author_profile": "https://Stackoverflow.com/users/2270762",
"pm_score": 2,
"selected": false,
"text": "ROW_NUMBER RANK DENSE_RANK SELECT * \nFROM menu\nWHERE (shop, size) IN\n(\n SELECT shop, MAX(size)\n FROM menu\n GROUP by shop\n);\n SELECT * \nFROM menu\nWHERE NOT EXISTS\n(\n SELECT null\n FROM menu better\n WHERE better.shop = menu.shop\n AND better.size > menu.size\n);\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12293338/"
] |
74,606,385
|
<p>I am trying to scrape youtube videos from a channel by doing the following code below however, it seems that my element_titles don't have a href attribute. This worked about a year ago and I am unsure why it doesn't work now? Did youtube change the way we can get href?</p>
<pre><code>#Scrape for videos
# WARNING: Takes very long
HOME = "https://www.youtube.com/user/theneedledrop/videos"
driver = webdriver.Chrome("C:\webdriver\chromedriver.exe")
driver.get(HOME)
scroll()
element_titles = driver.find_elements(By.ID,"video-title")
</code></pre>
<p>The following attribtues are what is found in the WebDriver objects</p>
<pre><code>> element_titles[0].get_property('attributes')[0]
{'ATTRIBUTE_NODE': 2,
'CDATA_SECTION_NODE': 4,
'COMMENT_NODE': 8,
'DOCUMENT_FRAGMENT_NODE': 11,
'DOCUMENT_NODE': 9,
'DOCUMENT_POSITION_CONTAINED_BY': 16,
'DOCUMENT_POSITION_CONTAINS': 8,
'DOCUMENT_POSITION_DISCONNECTED': 1,
'DOCUMENT_POSITION_FOLLOWING': 4,
'DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC': 32,
'DOCUMENT_POSITION_PRECEDING': 2,
'DOCUMENT_TYPE_NODE': 10,
'ELEMENT_NODE': 1,
'ENTITY_NODE': 6,
'ENTITY_REFERENCE_NODE': 5,
'NOTATION_NODE': 12,
'PROCESSING_INSTRUCTION_NODE': 7,
'TEXT_NODE': 3,
'__shady_addEventListener': {},
'__shady_appendChild': {},
'__shady_childNodes': [],
'__shady_cloneNode': {},
'__shady_contains': {},
'__shady_dispatchEvent': {},
'__shady_firstChild': None,
'__shady_getRootNode': {},
'__shady_insertBefore': {},
'__shady_isConnected': False,
'__shady_lastChild': None,
'__shady_native_addEventListener': {},
'__shady_native_appendChild': {},
'__shady_native_childNodes': [],
'__shady_native_cloneNode': {},
'__shady_native_contains': {},
'__shady_native_dispatchEvent': {},
'__shady_native_firstChild': None,
'__shady_native_insertBefore': {},
'__shady_native_lastChild': None,
'__shady_native_nextSibling': None,
'__shady_native_parentElement': None,
'__shady_native_parentNode': None,
'__shady_native_previousSibling': None,
'__shady_native_removeChild': {},
'__shady_native_removeEventListener': {},
'__shady_native_replaceChild': {},
'__shady_native_textContent': 'video-title',
'__shady_nextSibling': None,
'__shady_parentElement': None,
'__shady_parentNode': None,
'__shady_previousSibling': None,
'__shady_removeChild': {},
'__shady_removeEventListener': {},
'__shady_replaceChild': {},
'__shady_textContent': 'video-title',
'addEventListener': {},
'appendChild': {},
'baseURI': 'https://www.youtube.com/user/theneedledrop/videos',
'childNodes': [],
'cloneNode': {},
'compareDocumentPosition': {},
'contains': {},
'dispatchEvent': {},
'firstChild': None,
'getRootNode': {},
'hasChildNodes': {},
'insertBefore': {},
'isConnected': False,
'isDefaultNamespace': {},
'isEqualNode': {},
'isSameNode': {},
'lastChild': None,
'localName': 'id',
'lookupNamespaceURI': {},
'lookupPrefix': {},
'name': 'id',
'namespaceURI': None,
'nextSibling': None,
'nodeName': 'id',
'nodeType': 2,
'nodeValue': 'video-title',
'normalize': {},
'ownerDocument': <selenium.webdriver.remote.webelement.WebElement (session="906f0b2a91a96de78811a8b48c702ce9", element="4105d26d-55b3-49a1-b657-10bbbbf43c84")>,
'ownerElement': <selenium.webdriver.remote.webelement.WebElement (session="906f0b2a91a96de78811a8b48c702ce9", element="c0d38452-435c-489a-8cb8-858adc4828b9")>,
'parentElement': None,
'parentNode': None,
'prefix': None,
'previousSibling': None,
'removeChild': {},
'removeEventListener': {},
'replaceChild': {},
'specified': True,
'textContent': 'video-title',
'value': 'video-title'}
</code></pre>
<p>I have tried exploring the web pages on youtube videos for the href however I am unable to find them</p>
|
[
{
"answer_id": 74606427,
"author": "BrownieInMotion",
"author_id": 14585634,
"author_profile": "https://Stackoverflow.com/users/14585634",
"pm_score": 0,
"selected": false,
"text": "video-title-link /watch video-title-link video-title"
},
{
"answer_id": 74606782,
"author": "Fazlul",
"author_id": 12848411,
"author_profile": "https://Stackoverflow.com/users/12848411",
"pm_score": 2,
"selected": true,
"text": "from selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nimport time\nimport pandas as pd\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\noptions = webdriver.ChromeOptions()\n#All are optional\n#options.add_experimental_option(\"detach\", True)\noptions.add_argument(\"--disable-extensions\")\noptions.add_argument(\"--disable-notifications\")\noptions.add_argument(\"--disable-Advertisement\")\noptions.add_argument(\"--disable-popup-blocking\")\noptions.add_argument(\"start-maximized\")\n\ns=Service('./chromedriver')\ndriver= webdriver.Chrome(service=s,options=options)\n\ndriver.get('https://www.youtube.com/user/theneedledrop/videos')\ntime.sleep(3)\n\nitem = []\nSCROLL_PAUSE_TIME = 1\nlast_height = driver.execute_script(\"return document.documentElement.scrollHeight\")\n\nitem_count = 100\n\nwhile item_count > len(item):\n driver.execute_script(\"window.scrollTo(0,document.documentElement.scrollHeight);\")\n time.sleep(SCROLL_PAUSE_TIME)\n new_height = driver.execute_script(\"return document.documentElement.scrollHeight\")\n\n if new_height == last_height:\n break\n last_height = new_height\n \n\ndata = []\ntry:\n for e in WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'div#details'))):\n vurl = e.find_element(By.CSS_SELECTOR,'a#video-title-link').get_attribute('href')\n data.append({\n 'video_url':vurl,\n \n })\nexcept:\n pass\n \nitem = data\n#print(item)\n#print(len(item))\ndf = pd.DataFrame(item).drop_duplicates()\nprint(df.to_markdown())\n | video_url |\n|----:|:--------------------------------------------|\n| 0 | https://www.youtube.com/watch?v=UZcSkasvj5c |\n| 1 | https://www.youtube.com/watch?v=9c8AXKAnp_E |\n| 2 | https://www.youtube.com/watch?v=KaLUHF7nQic |\n| 3 | https://www.youtube.com/watch?v=rxb2L0Bgp3U |\n| 4 | https://www.youtube.com/watch?v=z3L1wXvMN0Q |\n| 5 | https://www.youtube.com/watch?v=q7vqR74WVYc |\n| 6 | https://www.youtube.com/watch?v=Kb31OTOYYG8 |\n| 7 | https://www.youtube.com/watch?v=F-CaQbxwMZ0 |\n| 8 | https://www.youtube.com/watch?v=AWDWTyC0jls |\n| 9 | https://www.youtube.com/watch?v=LXWbnTgxeT4 |\n| 10 | https://www.youtube.com/watch?v=5KlHjDnefYQ |\n| 11 | https://www.youtube.com/watch?v=yfq8rdBcAMg |\n| 12 | https://www.youtube.com/watch?v=lATG1JBzVIU |\n| 13 | https://www.youtube.com/watch?v=SNmZfHDOHQw |\n| 14 | https://www.youtube.com/watch?v=IsQBbO_4EQI |\n| 15 | https://www.youtube.com/watch?v=wcSyXUOM63g |\n| 16 | https://www.youtube.com/watch?v=5hIaJZ9M8ZI |\n| 17 | https://www.youtube.com/watch?v=ikryWQEHsCE |\n| 18 | https://www.youtube.com/watch?v=5ARVgrao6E0 |\n| 19 | https://www.youtube.com/watch?v=_1q6-POT8sY |\n| 20 | https://www.youtube.com/watch?v=ycyxm3rgQG0 |\n| 21 | https://www.youtube.com/watch?v=InirkRGnC2w |\n| 22 | https://www.youtube.com/watch?v=nrvq5lY9oy0 |\n| 23 | https://www.youtube.com/watch?v=M1yGh3D_KI8 |\n| 24 | https://www.youtube.com/watch?v=Yn_4mtMYyXU |\n| 25 | https://www.youtube.com/watch?v=8vmm8x_Cq4s |\n| 26 | https://www.youtube.com/watch?v=Zfyojbr-cEQ |\n| 27 | https://www.youtube.com/watch?v=NqrVX-WOrc0 |\n| 28 | https://www.youtube.com/watch?v=Hx6k20LsAJ4 |\n| 29 | https://www.youtube.com/watch?v=OB6ZI5Bicww |\n| 30 | https://www.youtube.com/watch?v=uNMnIRKx0GE |\n| 31 | https://www.youtube.com/watch?v=U7w_MKl5_hE |\n| 32 | https://www.youtube.com/watch?v=KGi4Cpbh_Y0 |\n| 33 | https://www.youtube.com/watch?v=mQqRtaoyAdw |\n| 34 | https://www.youtube.com/watch?v=s3VzTy9oXXM |\n| 35 | https://www.youtube.com/watch?v=eCaojgO-ZWs |\n| 36 | https://www.youtube.com/watch?v=SeOLXwvu87E |\n| 37 | https://www.youtube.com/watch?v=IlZ6Y21rxTU |\n| 38 | https://www.youtube.com/watch?v=HxoRbEQFx3U |\n| 39 | https://www.youtube.com/watch?v=NDCAImW1o6o |\n| 40 | https://www.youtube.com/watch?v=gE778rR6-EM |\n| 41 | https://www.youtube.com/watch?v=cQ0eY9NJACQ |\n| 42 | https://www.youtube.com/watch?v=-x5Bx-leRWI |\n| 43 | https://www.youtube.com/watch?v=XQ0C_Dmf0hI |\n| 44 | https://www.youtube.com/watch?v=0eJ4JRNi4J8 |\n| 45 | https://www.youtube.com/watch?v=YczkDCv3GiM |\n| 46 | https://www.youtube.com/watch?v=GQmUsdUI20A |\n| 47 | https://www.youtube.com/watch?v=4CFnoywFia4 |\n| 48 | https://www.youtube.com/watch?v=A0Bzv8weX4s |\n| 49 | https://www.youtube.com/watch?v=YbxcaHn_d_o |\n| 50 | https://www.youtube.com/watch?v=GwUNT2k26mQ |\n| 51 | https://www.youtube.com/watch?v=zktcHftIhDs |\n| 52 | https://www.youtube.com/watch?v=_rY7Hvxe4x4 |\n| 53 | https://www.youtube.com/watch?v=rqB9gd4fbfE |\n| 54 | https://www.youtube.com/watch?v=oNPAhe7G3yg |\n| 55 | https://www.youtube.com/watch?v=37_aCQW98sU |\n| 56 | https://www.youtube.com/watch?v=GjA4fWIUv-A |\n| 57 | https://www.youtube.com/watch?v=8THBFF024ho |\n| 58 | https://www.youtube.com/watch?v=HLErXgsV3Nk |\n| 59 | https://www.youtube.com/watch?v=GsvdLIxY6Fg |\n| 60 | https://www.youtube.com/watch?v=iUU48DuTpl8 |\n| 61 | https://www.youtube.com/watch?v=5UluxcFJVx0 |\n| 62 | https://www.youtube.com/watch?v=5lOvAHg12uw |\n| 63 | https://www.youtube.com/watch?v=2UADjU66-4M |\n| 64 | https://www.youtube.com/watch?v=Qvr2labD_Es |\n| 65 | https://www.youtube.com/watch?v=qUWRnIn5oB0 |\n| 66 | https://www.youtube.com/watch?v=Qk7MPEyGhQ4 |\n| 67 | https://www.youtube.com/watch?v=bN7SDJFanS4 |\n| 68 | https://www.youtube.com/watch?v=6YoUjUGvHUk |\n| 69 | https://www.youtube.com/watch?v=NjiLz3HoWkM |\n| 70 | https://www.youtube.com/watch?v=rRdU7VhoWdI |\n| 71 | https://www.youtube.com/watch?v=zOm5n0OJLfc |\n| 72 | https://www.youtube.com/watch?v=z9jMFiSUe5Q |\n| 73 | https://www.youtube.com/watch?v=M6VLYjFnXMU |\n| 74 | https://www.youtube.com/watch?v=4iFEpKDQx-o |\n| 75 | https://www.youtube.com/watch?v=Zc1SE66DEYo |\n| 76 | https://www.youtube.com/watch?v=645qisC4slI |\n| 77 | https://www.youtube.com/watch?v=QeIRfgsVX5k |\n| 78 | https://www.youtube.com/watch?v=0jUr57dIMq4 |\n| 79 | https://www.youtube.com/watch?v=EjaTJGmoT_w |\n| 80 | https://www.youtube.com/watch?v=roXy5LA17fU |\n| 81 | https://www.youtube.com/watch?v=UeSwqepnAX0 |\n| 82 | https://www.youtube.com/watch?v=BDYSYypzhxE |\n| 83 | https://www.youtube.com/watch?v=iyBNxEnP7rk |\n| 84 | https://www.youtube.com/watch?v=YCUmI9f77qs |\n| 85 | https://www.youtube.com/watch?v=h21LYpHEfNU |\n| 86 | https://www.youtube.com/watch?v=LBQDuTn6T0c |\n| 87 | https://www.youtube.com/watch?v=le_0jyqCXFU |\n| 88 | https://www.youtube.com/watch?v=tGClvgTCrIY |\n| 89 | https://www.youtube.com/watch?v=969qt4RUx74 |\n| 90 | https://www.youtube.com/watch?v=XL8li__PnaA |\n| 91 | https://www.youtube.com/watch?v=RKf3ppfFUkg |\n| 92 | https://www.youtube.com/watch?v=xY5RyjaQJCE |\n| 93 | https://www.youtube.com/watch?v=6bjliN6hJTs |\n| 94 | https://www.youtube.com/watch?v=KcYBolH-j9c |\n| 95 | https://www.youtube.com/watch?v=nlsnpbRyvtU |\n| 96 | https://www.youtube.com/watch?v=AOWmL1eydWI |\n| 97 | https://www.youtube.com/watch?v=I8RPsF-hdXo |\n| 98 | https://www.youtube.com/watch?v=9NSOGd2p530 |\n| 99 | https://www.youtube.com/watch?v=8EdqpZu9lkM |\n| 100 | https://www.youtube.com/watch?v=a23wQEA4EAA |\n| 101 | https://www.youtube.com/watch?v=7g6TXGY-T6k |\n| 102 | https://www.youtube.com/watch?v=iXZNlGwOuWY |\n| 103 | https://www.youtube.com/watch?v=miR30bsSH4E |\n| 104 | https://www.youtube.com/watch?v=zb8-aHiTKL4 |\n| 105 | https://www.youtube.com/watch?v=rTEZmXq9K3k |\n| 106 | https://www.youtube.com/watch?v=OBeOJiolMug |\n| 107 | https://www.youtube.com/watch?v=fA0nxixnS-A |\n| 108 | https://www.youtube.com/watch?v=dMhpDlUTT_U |\n| 109 | https://www.youtube.com/watch?v=SgjDaPWjzuU |\n| 110 | https://www.youtube.com/watch?v=2lokqffmF2A |\n| 111 | https://www.youtube.com/watch?v=jmHZvGMe8pQ |\n| 112 | https://www.youtube.com/watch?v=KPYvMIMON9g |\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14805218/"
] |
74,606,397
|
<p>My idea is to show loader circle after clicking a form submit button, because it's take some time to redirect user to page which let you know that form is submitted successfully. But with my limited JavaScrip knowledge I can't figure it out how to start loader only if user have filed out all required fields. Is it possible using JavaScript?</p>
<p>Here is my HTML code:</p>
<pre><code> <form id="form">
<input type="text" required>
<button type="submit" class="button" onclick="this.classList.toggle('button--loading')">
<span class="button__text">Save</span>
</button>
</form>
</code></pre>
<p>and CSS code:</p>
<pre><code>.button {
position: relative;
padding: 8px 16px;
background: #009579;
border: none;
outline: none;
border-radius: 2px;
cursor: pointer;
}
.button:active {
background: #007a63;
}
.button__text {
font: bold 20px "Quicksand", san-serif;
color: #ffffff;
transition: all 0.2s;
}
.button--loading .button__text {
visibility: hidden;
opacity: 0;
}
.button--loading::after {
content: "";
position: absolute;
width: 16px;
height: 16px;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
border: 4px solid transparent;
border-top-color: #ffffff;
border-radius: 50%;
animation: button-loading-spinner 1s ease infinite;
}
@keyframes button-loading-spinner {
from {
transform: rotate(0turn);
}
to {
transform: rotate(1turn);
}
}
</code></pre>
|
[
{
"answer_id": 74606856,
"author": "jorgepelcastre",
"author_id": 20626144,
"author_profile": "https://Stackoverflow.com/users/20626144",
"pm_score": 0,
"selected": false,
"text": "const form = document.getElementById('form');\n\nconst handleSubmit = (event) => {\n event.preventDefault();\n const data = new FormData(form);\n const url = \"your url here\";\n const options = {\n method: \"POST\",\n body: data\n } \n // start animation\n fetch(url, options)\n .finally(() => {\n // end animation\n });\n}\n\nform.addEventListener('submit', handleSubmit);\n"
},
{
"answer_id": 74606920,
"author": "user3221512",
"author_id": 3221512,
"author_profile": "https://Stackoverflow.com/users/3221512",
"pm_score": 2,
"selected": true,
"text": "<form id=\"form\" onsubmit=\"return submitTheForm(this);\">\n <input type=\"text\" required>\n <button type=\"submit\" class=\"button\">\n <span class=\"button__text\">Save</span>\n </button>\n</form>\n\n<script>\n function submitTheForm(theForm){\n const eButton = theForm.querySelector('button[type=\"submit\"]');\n eButton.classList.toggle('button--loading');\n }\n</script>\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15083971/"
] |
74,606,401
|
<p>I have a dataframe <code>df</code> whose index is <code>[x[0], ..., x[N]]</code> and column is <code>[y[0], ..., y[M]]</code> and whose data is a 2D array of <code>z[i,j]</code>'s.</p>
<p>I have a python function <code>def f(x, y, z)</code> of 3 float variables and I would like to calculate the 2d array of <code>f(x[i], y[j], z[i,j])</code>'s in the fastest way using numpy and/or pandas but I don't see how to do it.</p>
<p>I see the <code>df.transform</code> method but it doesn't seem to allow for lambdas that are dependent on index and column of <code>df</code> -- or at least I don't know how to provide such lambdas.</p>
<p>Details on <code>df</code> and <code>f</code> :</p>
<ul>
<li><p>How was my <code>df</code> obtained ? I created it during a 45 minutes computation using an intensive numerical python vectorized function on a grid with N = 5000 and M = 5000 and I "<code>to_csv</code>'ed" it. Now when I want to use it, I use <code>read_csv</code>.</p>
</li>
<li><p>Now my function <code>f</code> is quite an involved numerical <code>C++</code> function that I exposed to python with pybind11 (I put the tag for sake of completness) and that I don't want to rewrite in a "numpy vectorizable fashion" for now as it is ultra-optimized and very fast unitarily. Given <code>x,y</code> the function <code>f</code> solves numerically (iterative root finder) an equation with parameters <code>x,y,z</code> and unknow <code>Z</code>, the root of the equation being <code>f(x,y,z)</code>.</p>
</li>
</ul>
|
[
{
"answer_id": 74606856,
"author": "jorgepelcastre",
"author_id": 20626144,
"author_profile": "https://Stackoverflow.com/users/20626144",
"pm_score": 0,
"selected": false,
"text": "const form = document.getElementById('form');\n\nconst handleSubmit = (event) => {\n event.preventDefault();\n const data = new FormData(form);\n const url = \"your url here\";\n const options = {\n method: \"POST\",\n body: data\n } \n // start animation\n fetch(url, options)\n .finally(() => {\n // end animation\n });\n}\n\nform.addEventListener('submit', handleSubmit);\n"
},
{
"answer_id": 74606920,
"author": "user3221512",
"author_id": 3221512,
"author_profile": "https://Stackoverflow.com/users/3221512",
"pm_score": 2,
"selected": true,
"text": "<form id=\"form\" onsubmit=\"return submitTheForm(this);\">\n <input type=\"text\" required>\n <button type=\"submit\" class=\"button\">\n <span class=\"button__text\">Save</span>\n </button>\n</form>\n\n<script>\n function submitTheForm(theForm){\n const eButton = theForm.querySelector('button[type=\"submit\"]');\n eButton.classList.toggle('button--loading');\n }\n</script>\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1581875/"
] |
74,606,422
|
<p>When the window is resized, I want the height to be set equal to the width so the windows always is a square. In the code below <code>print(event.width)</code> does print the new window width, but <code>canvas.configure(height=event.width)</code> doesn't change the canvas height. What am I doing wrong?</p>
<p>EDIT: I want the whole window to stay squared.</p>
<pre><code>import tkinter as tk
from timeit import default_timer as timer
start_timer = timer()
height = 600
width = 600
red = ("#ff7663")
root = tk.Tk()
canvas = tk.Canvas(root, height=height, width=width, background=red)
canvas.pack(expand=True,fill="both")
def resize(event):
end_timer = timer()
if end_timer - start_timer > 0.5:
print(event.width)
canvas.configure(height=event.width)
canvas.bind("<Configure>", resize)
root.mainloop()```
</code></pre>
|
[
{
"answer_id": 74606606,
"author": "JRiggles",
"author_id": 8512262,
"author_profile": "https://Stackoverflow.com/users/8512262",
"pm_score": 0,
"selected": false,
"text": "canvas import tkinter as tk\n\nroot = tk.Tk\nroot.geometry('600x600')\ncanvas = tk.Canvas(root, background=red)\ncanvas.pack()\n\n\ndef on_resize(event):\n w, h = event.width, event.height\n if w <= h:\n canvas.configure(width=w, height=w)\n\n\nif __name__ == '__main__':\n root.bind('<Configure>', on_resize)\n root.mainloop()\n"
},
{
"answer_id": 74606616,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 1,
"selected": false,
"text": "def resize(event):\n width = root.winfo_width()\n root.wm_geometry(f\"{width}x{width}\")\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9060784/"
] |
74,606,440
|
<p>Hi everyone hope you all doing good,</p>
<p>I am trying to add a plugin to sanity and the plugin is <a href="https://www.sanity.io/plugins/order-documents" rel="nofollow noreferrer">sanity-plugin-order-documents
</a>.<br>I have followed all the steps shown in the documentation step by step.<br></p>
<blockquote>
<p>I added <code>"plugins": [ "order-documents" ],</code> to <strong>sanity.json</strong> <br>
And add this field : <br>
<code>{ name: "order", title: "Order", type: "number", hidden: true, },</code><br>to <strong>sanity\schemas\projects.js</strong></p>
</blockquote>
<p>.<br>And this is how I used the plugin in my code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>useEffect(() => {
sanityClient.fetch(
`
*[_type == "projects"] | order(order asc){
...,
}
`
).then((data) => {
setProjectsData(data)
})
}, [])</code></pre>
</div>
</div>
</p>
<p>But whenever I try to do sanity start or sanity deploy I got this error :</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>Error: Errors while building:
./node_modules/@floating-ui/dom/dist/floating-ui.dom.esm.js
Module parse failed: Unexpected token (307:11)
You may need an appropriate loader to handle this file type.
| }
|
| return { ...rect,
| x: rect.x - scroll.scrollLeft + offsets.x,
| y: rect.y - scroll.scrollTop + offsets.y
@ ./node_modules/react-select/dist/react-select.esm.js 24:0-26
@ ./node_modules/sanity-plugin-order-documents/build/components/organisms/TypeSection.js
@ ./node_modules/sanity-plugin-order-documents/build/components/OrderDocuments.js
@ ./node_modules/sanity-plugin-order-documents/build/index.js
@ ./node_modules/sanity-plugin-order-documents/build?sanityPart=all%3Apart%3A%40sanity%2Fbase%2Ftool
@ ./node_modules/@sanity/default-layout/lib/util/getRegisteredTools.js
@ ./node_modules/@sanity/default-layout/lib/router.js
@ ./node_modules/@sanity/default-layout/lib/Root.js?sanityPart=part%3A%40sanity%2Fbase%2Froot
@ ./node_modules/@sanity/base/lib/components/SanityRoot.js?sanityPart=part%3A%40sanity%2Fbase%2Fsanity-root
@ ./node_modules/@sanity/server/lib/browser/entry.js
@ multi ./node_modules/@sanity/server/lib/browser/entry.js
at buildStaticAssets (C:/Users/Slima/Desktop/abdellah-slimani-portfolio/sanity/node_modules/@sanity/core/lib/actions/build/buildStaticAssets.js:103:13)
at async _default (C:/Users/Slima/Desktop/abdellah-slimani-portfolio/sanity/node_modules/@sanity/core/lib/actions/deploy/deployAction.js:78:9)</code></pre>
</div>
</div>
</p>
<p>I have done some research to solve this problem, and I see many people suggest to edit the webpack file but I have no idea about what to add to that file.</p>
<p>please send help, <strong>SOS</strong>.</p>
|
[
{
"answer_id": 74628538,
"author": "Aidan Marshall",
"author_id": 10193563,
"author_profile": "https://Stackoverflow.com/users/10193563",
"pm_score": 2,
"selected": true,
"text": "react-select@^5 react-select@^5 react-select yarn add npm install sanity-plugin-autocomplete-tags@1.0.0 sanity-plugin-media@1.4.13 sanity-plugin-order-documents@0.0.19"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16791905/"
] |
74,606,444
|
<p>i want to dynamically change the color of my text depending if it exceeds a certain range of numbers (between 0 and 360). i will share my code that is currently working but not changing colors.</p>
<pre><code>class _DurationContainers extends StatelessWidget {
const _DurationContainers({
Key? key,
required this.controller, required this.hint, required this.digits,
}) : super(key: key);
final String hint;
final TextEditingController controller;
final int digits;
@override
Widget build(BuildContext context) {
return Neumorphic(
style: marketplaceButtonsNeuStyle.copyWith(
boxShape: NeumorphicBoxShape.roundRect(BorderRadius.circular(15))
),
child: Container(
width: ScreenUtils.percentWidth(context, 3.2),
child: TextFormField(
controller: controller,
keyboardType: TextInputType.number,
textInputAction: TextInputAction.next,
onSaved: (precio) {},
textAlign: TextAlign.center,
cursorColor: Color.fromARGB(148, 66, 63, 63) ,
style: Theme.of(context).textTheme.headline1!.copyWith(fontSize: 20),
inputFormatters: [
LengthLimitingTextInputFormatter(digits),
FilteringTextInputFormatter.digitsOnly,
],
decoration: InputDecoration(
border: InputBorder.none,
hintStyle: Theme.of(context).textTheme.headline1!.copyWith(fontSize: 21),
contentPadding: EdgeInsets.symmetric(horizontal: ScreenUtils.percentHeight(context, .5)),
hintText: hint
),
),
),
);
}
}
</code></pre>
<p>I have tried parsing the data from my textfield to an int and setting a limit but i think im not doing it correctly since its giving me errors.</p>
<p>This is what im currently trying to do.</p>
<p><a href="https://i.stack.imgur.com/KVWok.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KVWok.jpg" alt="Text is normal since is between the range of 0 and 360" /></a></p>
<p><a href="https://i.stack.imgur.com/kxIO8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kxIO8.jpg" alt="Text should turn red once exceeding the max range of 360 turning red" /></a></p>
|
[
{
"answer_id": 74628538,
"author": "Aidan Marshall",
"author_id": 10193563,
"author_profile": "https://Stackoverflow.com/users/10193563",
"pm_score": 2,
"selected": true,
"text": "react-select@^5 react-select@^5 react-select yarn add npm install sanity-plugin-autocomplete-tags@1.0.0 sanity-plugin-media@1.4.13 sanity-plugin-order-documents@0.0.19"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19702304/"
] |
74,606,461
|
<p>I want to create a class in python that contains variables and a domain for each variable
to generate a list of dictionary containing all the possible solutions for variables assignments</p>
<pre><code>for exemple:
x='x'
y='y'
domainx=[1,2]
domainy=[3,4]
def solutions(elt,elt2,domainx,domainy):
for i in domainx:
for j in domainy:
liste.append({elt:i,elt2:j})
return liste
</code></pre>
<p>liste now is equal to [{'x':1,'y'=3},{'x':1,'y'=4},{'x':2,'y':3} etc..]</p>
<p>but this function it's not flexible and reutilizable because i must declare the variable one by one.
what i want is generate solutions from a liste like :
liste=[(x,[1,2]),(y,[3,4])or
liste=[(x,[324,3433]),(y,[43,34354,45]),(z,[5445,653,3,34,4,5])]</p>
<p>then i pass the liste to a function that will generate the solutions,i don't know how to do it especially that i should do as many as the length of liste is.</p>
<p>My purpose for this question is to create this class,</p>
<pre><code>class CST:
def __init__(self):
self.variables=[]
self.contraintes=[]
self.VarWithdomaines=[]
def addVarDom(self,variable,domain):
self.VarWithdomaines.append((variable,domain))
# def generate(self): it's not the correct way
# liste=[]
# for repitition in range(len(self.domaines)):
# solution={}
# for noeud in self.domaines:
# var=noeud[0]
# for x in noeud[1]:
# solution[var]=x
# liste.append(solution)
# return liste
Game=CST()
domain = [int(i) for i in range(2)]
domain2 = [int(i) for i in range(3)]
domain3 = [int(i) for i in range(21)]
# domain4 = [int(i) for i in range()]
Game.addVarDom("E1",domain)
Game.addVarDom("E2",domain2)
Game.addVarDom("C20",domain3)
listofsolutions=Game.generate())
#list should be for exemple list=[{E1:1,E2:0,C20:20},{E1:0,E2:2,C20:12}...]
</code></pre>
|
[
{
"answer_id": 74628538,
"author": "Aidan Marshall",
"author_id": 10193563,
"author_profile": "https://Stackoverflow.com/users/10193563",
"pm_score": 2,
"selected": true,
"text": "react-select@^5 react-select@^5 react-select yarn add npm install sanity-plugin-autocomplete-tags@1.0.0 sanity-plugin-media@1.4.13 sanity-plugin-order-documents@0.0.19"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20313832/"
] |
74,606,483
|
<p>So i want to make a list of these orders and implement a search function to it but i cant even figure the basics like now it just spams undefined on the html even though the "orderid" is a object on the json file. this is really hard to figure out and when i ask people, people give too straight forward messages to me that i cant figure it im not asking you guys to code for me but to point to right direction would helpful</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>const orderlist = document.getElementById('orderlist');
let orderid = [0];
const loadorders = async() => {
try {
const res = await fetch('https://www.cc.puv.fi/~asa/cgi-bin/fetchOrders.py');
orderid = await res.json();
displayorderid(orderid);
} catch (err) {
console.error(err);
console.log(res);
}
};
const displayorderid = (orderid) => {
const htmlString = orderid
.map((order) => {
return `
<li class="orderid">
<h2>${order.value}</h2>
</li>
`;
})
.join('');
orderlist.innerHTML = htmlString;
};
loadorders();</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
font-family: Georgia, serif;
background-color: rgb(59, 59, 243);
}
* {
box-sizing: border-box;
}
h1 {
color: azure margin-bottom:30px;
}
.container {
padding: 35px;
margin: 0 auto;
max-width: 1000px;
text-align: center center;
}
#customerslist {
padding-inline-start: 0;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
grid-gap: 15;
}
.Customer {
list-style-type: none;
background-color: aquamarine;
border-radius: 5px;
padding: 10px 25px;
grid-template-columns: 3fr 1fr;
grid-template-areas: ;
text-align: left;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<h1>tilaukset</h1>
<div id="search">
<input type="text" name="Hakupalkki" id="Hakupalkki" placeholder="Hae tilausta" />
</div>
<ul id="orderlist"></ul>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74606551,
"author": "damonholden",
"author_id": 17670742,
"author_profile": "https://Stackoverflow.com/users/17670742",
"pm_score": 0,
"selected": false,
"text": "const orderlist = document.getElementById('orderlist');\nlet orderid = [0];\n\nconst displayorderid = (orderid) => {\n const htmlString = orderid\n .map((orderid) => {\n return `\n <li class=\"orderid\">\n <h2>${orderid.customerid}</h2>\n </li>\n `; //<------- the customerid property exists\n })\n .join('');\n orderlist.innerHTML = htmlString;\n};\n\nconst loadorders = async () => {\n try {\n const res = await fetch(\n 'https://www.cc.puv.fi/~asa/cgi-bin/fetchOrders.py'\n );\n orderid = await res.json();\n console.log(orderid) //<------- use this to view the each object`s properties in the console\n displayorderid(orderid);\n } catch (err) {\n console.error(err);\n console.log(res);\n }\n};\n\nloadorders();\n"
},
{
"answer_id": 74606625,
"author": "Lissy93",
"author_id": 979052,
"author_profile": "https://Stackoverflow.com/users/979052",
"pm_score": 1,
"selected": false,
"text": "customerid const orderlist = document.getElementById('orderlist');\nlet orderid = [0];\n\nconst loadorders = async() => {\n try {\n const res = await fetch('https://www.cc.puv.fi/~asa/cgi-bin/fetchOrders.py');\n orderid = await res.json();\n displayorderid(orderid);\n } catch (err) {\n console.error(err);\n console.log(res);\n }\n};\nconst displayorderid = (orderObject) => {\n const htmlString = orderObject\n.map((orderObject) => {\n return `\n <li class=\"orderid\">\n <h2>${orderObject.customerid}</h2>\n </li>\n `; //<------- the customerid property exists\n})\n.join('');\n orderlist.innerHTML = htmlString;\n};\nloadorders(); body {\n font-family: Georgia, serif;\n background-color: rgb(59, 59, 243);\n}\n\n* {\n box-sizing: border-box;\n}\n\nh1 {\n color: azure margin-bottom:30px;\n}\n\n.container {\n padding: 35px;\n margin: 0 auto;\n max-width: 1000px;\n text-align: center center;\n}\n\n#customerslist {\n padding-inline-start: 0;\n display: grid;\n grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));\n grid-gap: 15;\n}\n\n.Customer {\n list-style-type: none;\n background-color: aquamarine;\n border-radius: 5px;\n padding: 10px 25px;\n grid-template-columns: 3fr 1fr;\n grid-template-areas: ;\n text-align: left;\n} <div class=\"container\">\n <h1>tilaukset</h1>\n <div id=\"search\">\n <input type=\"text\" name=\"Hakupalkki\" id=\"Hakupalkki\" placeholder=\"Hae tilausta\" />\n </div>\n <ul id=\"orderlist\"></ul>\n</div>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20583150/"
] |
74,606,511
|
<p>I am working on an Angular component that contains a function. In this function, I need to pass an Object as a function parameter and call this function with the function parameters. It´s been a while since I have been working with Angular and at the type, "any" was the return type to use with functions; nowadays it seems to be "undefined". However, I am not sure on how to write the function call with the corresponding parameters and would appreciate any help and hints. Thanks in advance!</p>
<p>Here´s the component:</p>
<pre><code>import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-root', // eslint-disable-line @angular-eslint/component-selector
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
public interactionID: number=0;
@Input()
public userdata!: Object;
constructor() {
// Called first time before the ngOnInit()
}
public ngOnInit(): void {
this.NewWorkItem(this.interactionID, this.userdata );
}
public NewWorkItem(interactionID: unknown, userData: { FirstName: unknown; LastName: unknown }): void {
console.log('NewWorkItem call',interactionID,userData);
const event: Event = new CustomEvent ('wde.newWorkItem', {
detail: {
FirstName: userData.FirstName,
LastName: userData.LastName,
InteractionID: interactionID
},
bubbles: true,
cancelable: true,
composed: false,
});
console.log('NewWorkItem event',event);
window.dispatchEvent(event);
}
}
</code></pre>
<p>This is the function that needs to be called in ngOnInit:</p>
<pre><code>public NewWorkItem(interactionID: unknown, userData: { FirstName: unknown; LastName: unknown }): void {
console.log('NewWorkItem call',interactionID,userData);
const event: Event = new CustomEvent ('wde.newWorkItem', {
detail: {
FirstName: userData.FirstName,
LastName: userData.LastName,
InteractionID: interactionID
},
bubbles: true,
cancelable: true,
composed: false,
});
console.log('NewWorkItem event',event);
window.dispatchEvent(event);
}
</code></pre>
<p>This is the function call in ngOnInit, where I am having the troubles in passing the paramters correctly:</p>
<pre><code> public ngOnInit(): void {
this.NewWorkItem(this.interactionID, this.userdata );
}
</code></pre>
<p>this.userdata cannot be passed as such as function parameter; the compiler error is:</p>
<pre><code>The argument of Typ "Object" cannot be assigned to the parameter of type "{ FirstName: unknown; LastName: unknown; }"
</code></pre>
<p>I was trying to call the function in the ngOnInit method with the corresponding parameters.
The error that I get is: The argument of Typ "Object" cannot be assigned to the parameter of type <code>"{ FirstName: unknown; LastName: unknown; }"</code>. I cannot tell on how to pass the object as a function parameter correctly.</p>
|
[
{
"answer_id": 74606662,
"author": "Bruno João",
"author_id": 2009212,
"author_profile": "https://Stackoverflow.com/users/2009212",
"pm_score": 0,
"selected": false,
"text": "type UserData = { FirstName: string; LastName: string };\n UserData @Input() public userdata!: UserData;\n public NewWorkItem(interactionID: unknown, userData: UserData): void {\n"
},
{
"answer_id": 74606688,
"author": "dbonev",
"author_id": 4200334,
"author_profile": "https://Stackoverflow.com/users/4200334",
"pm_score": 3,
"selected": true,
"text": "export interface IUserData { FirstName: unknown; LastName: unknown }\n @Input() public userdata!: IUserData;\n...\npublic NewWorkItem(interactionID: unknown, userData: IUserData);\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1120165/"
] |
74,606,523
|
<p>I am quite new to Django and followed a tutorial to create a website. I'm not able to log in to an account. When I log in with any details (correct or incorrect), my 'login' page just reloads and nothing else happens (The expected result is that I go into a different page when I log in correctly)</p>
<p>I am getting <strong>"POST /login/ HTTP/1.1" 200 3689</strong> in the terminal.</p>
<p>Here's part of the code:</p>
<p>(views.py)</p>
<pre><code>def loginpage(request):
error = ""
page = ""
if request.method == 'POST':
u = request.POST['email']
p = request.POST['password']
user = authenticate(request,username=u,password=p)
try:
if user is not None:
login(request,user)
error = "no"
g = request.user.groups.all()[0].name
if g == 'Doctor':
page = 'doctor'
d = {'error': error, 'page':page}
return render(request,'doctorhome.html',d)
elif g == 'Receptionist':
page = 'reception'
d = {'error': error, 'page':page}
return render(request,'receptionhome.html',d)
elif g == 'Patient':
page = 'patient'
d = {'error': error, 'page':page}
return render(request,'patienthome.html',d)
else:
error = "yes"
except Exception as e:
error = "yes"
#print(e)
#raise e
return render(request,'login.html')
</code></pre>
<p>Creating an account:</p>
<pre><code>def createaccountpage(request):
error = ""
user="none"
if request.method == 'POST':
name = request.POST['name']
email = request.POST['email']
password = request.POST['password']
repeatpassword = request.POST['repeatpassword']
gender = request.POST['gender']
phonenumber = request.POST['phonenumber']
address = request.POST['address']
birthdate = request.POST['dateofbirth']
bloodgroup = request.POST['bloodgroup']
try:
if password == repeatpassword:
Patient.objects.create(name=name,email=email,password=password,gender=gender,phonenumber=phonenumber,address=address,birthdate=birthdate,bloodgroup=bloodgroup)
user = User.objects.create_user(name=name,email=email,password=password,username=email)
pat_group = Group.objects.get(name='Patient')
pat_group.user.set.add(user)
user.save()
error = "no"
else:
error = "yes"
except Exception as e:
error = "yes"
print("Erorr:",e)
d = {'error' : error}
#print(error)
return render(request,'createaccount.html',d)
#return render(request,'createaccount.html')
</code></pre>
<p>I have an issue with creating an account as well. Whenever I create an account, the data isn't saved anywhere on the database for some reason. So instead, I manually added my details to the DB and tried logging in with those details but still it's not letting me log in.</p>
<p>I also thought the issue could be related to the DB itself (like certain data fields might be missing, I don't think the tutorial said all the data in the DB). Hence, I tried adding some data to it to see if permissions or something would affect anything and help me log in but it did not.</p>
<p>I'm now completely stuck and not sure how to proceed. I don't know if it will help but I have added a picture of the <a href="https://i.stack.imgur.com/Ko5ZZ.png" rel="nofollow noreferrer">Database here</a></p>
<p>I appreciate any kind of advice on how I can fix my issue of not being able to log in correctly.</p>
|
[
{
"answer_id": 74606662,
"author": "Bruno João",
"author_id": 2009212,
"author_profile": "https://Stackoverflow.com/users/2009212",
"pm_score": 0,
"selected": false,
"text": "type UserData = { FirstName: string; LastName: string };\n UserData @Input() public userdata!: UserData;\n public NewWorkItem(interactionID: unknown, userData: UserData): void {\n"
},
{
"answer_id": 74606688,
"author": "dbonev",
"author_id": 4200334,
"author_profile": "https://Stackoverflow.com/users/4200334",
"pm_score": 3,
"selected": true,
"text": "export interface IUserData { FirstName: unknown; LastName: unknown }\n @Input() public userdata!: IUserData;\n...\npublic NewWorkItem(interactionID: unknown, userData: IUserData);\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20627263/"
] |
74,606,541
|
<p>I have a vehicle class that gradually increases its speed to 10 and when it reaches 10 it maintains its value (remains 10), and when the speed is reduced, the speed must be reduced gradually. When it reaches 0, it maintains its value (remains 0).</p>
<p>I did not know how to reduce the vehicle speed and maintain the value (0), because the value becomes negative.</p>
<p>I know how to solve the problem through "if", but I want to solve it in a normal way as i did the speed increase to 10.</p>
<pre><code>public class vehicle {
private int speed;
public void speedUp() {
speed = (speed + 1) - speed / 10;
}
public void slowDown() {
}
public void show() {
System.out.println(speed);
}
}
</code></pre>
<p>I tried this but when the value becomes "0" I get an error because a number cannot be divided by 0.</p>
<pre><code>public void slowDown() {
speed = (speed - 1) % (speed / -1 );
}
</code></pre>
|
[
{
"answer_id": 74606565,
"author": "SilicDev",
"author_id": 20614914,
"author_profile": "https://Stackoverflow.com/users/20614914",
"pm_score": 0,
"selected": false,
"text": "speed = speed != 0 ? (speed - 1) % (speed / -1) : 0;\n"
},
{
"answer_id": 74606567,
"author": "David Schwartz",
"author_id": 721269,
"author_profile": "https://Stackoverflow.com/users/721269",
"pm_score": 3,
"selected": true,
"text": "speed speed = (speed - 1) speed speed speed speed (10 - speed) / 10 speed = (speed - 1) + (10 - speed) / 10;\n"
},
{
"answer_id": 74606577,
"author": "naghal",
"author_id": 5896405,
"author_profile": "https://Stackoverflow.com/users/5896405",
"pm_score": 2,
"selected": false,
"text": "speed = Math.max((speed - 1), 0)"
},
{
"answer_id": 74606623,
"author": "Gabe Sechan",
"author_id": 1631193,
"author_profile": "https://Stackoverflow.com/users/1631193",
"pm_score": 0,
"selected": false,
"text": "Math.min(10, speed+1) Math.max(0, speed - 1)"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20625659/"
] |
74,606,555
|
<p>How could I to show all years in a heat map label in R? Some years in "Y" label are missing.
Is it possible to put all the years with an angle or with alternate displacements?</p>
<pre><code>year = seq(from=1971,to=2020,by=1)
jan = runif(n = 50, min = -3, max = 3)
feb = runif(n = 50, min = -3, max = 3)
mar = runif(n = 50, min = -3, max = 3)
apr = runif(n = 50, min = -3, max = 3)
may = runif(n = 50, min = -3, max = 3)
jun= runif(n = 50, min = -3, max = 3)
jul= runif(n = 50, min = -3, max = 3)
aug= runif(n = 50, min = -3, max = 3)
sep= runif(n = 50, min = -3, max = 3)
oct= runif(n = 50, min = -3, max = 3)
nov= runif(n = 50, min = -3, max = 3)
dec= runif(n = 50, min = -3, max = 3)
df = data.frame(year,jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec)
head(df)
rownames(df) <- df$year
df=df[,-1]
df=as.matrix(df)
head(df)
my_palette <- colorRampPalette(c("red", "white", "blue"))(n = 9)
heatmap.2(df, scale = "none", col = my_palette,
trace = "none", density.info = "none", main = "Bohicon")
</code></pre>
<p>Thank you</p>
|
[
{
"answer_id": 74606700,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 0,
"selected": false,
"text": "gplots::heatmap.2(df, scale = \"none\", col = my_palette, \n trace = \"none\", density.info = \"none\", main = \"Bohicon\")\n"
},
{
"answer_id": 74606769,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 2,
"selected": false,
"text": "heatmap.2 cexRow heatmap.2(df, scale = \"none\", col = my_palette, trace = \"none\", \n density.info = \"none\", main = \"Bohicon\", cexRow=.5)\n 0.2 + 1/log10(nr)"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7817376/"
] |
74,606,557
|
<p>I want to query buttons present inside ng-content.</p>
<p><a href="https://stackblitz.com/edit/angular-ivy-tq6dzz?file=src%2Fapp%2Fselect%2Fselect.component.html,src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.module.ts,src%2Fapp%2Fselect%2Fselect.component.ts,src%2Fapp%2Fdirectives%2Fitem.directive.ts" rel="nofollow noreferrer">Slackblitz</a></p>
<p>html:</p>
<pre><code> <div appItem>
<ng-content></ng-content>
</div>
</code></pre>
<p>ts:</p>
<pre><code>ViewChildren(ItemDirective) buttons: QueryList<ItemDirective>;
constructor() {}
ngAfterContentInit(): void {
console.log(this.buttons);
}
ngAfterViewInit(): void {
console.log(this.buttons);
}
</code></pre>
<p>Directive:</p>
<pre><code>import { Directive } from '@angular/core';
@Directive({
selector: '[appItem]'
})
export class ItemDirective {
constructor() { }
}
</code></pre>
<p>Query list does not provide the list of buttons. Other things are present in it. How can I get the list of buttons in queryList?</p>
<p>I have tried ViewChildren and ContentChildren (both)</p>
|
[
{
"answer_id": 74606700,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 0,
"selected": false,
"text": "gplots::heatmap.2(df, scale = \"none\", col = my_palette, \n trace = \"none\", density.info = \"none\", main = \"Bohicon\")\n"
},
{
"answer_id": 74606769,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 2,
"selected": false,
"text": "heatmap.2 cexRow heatmap.2(df, scale = \"none\", col = my_palette, trace = \"none\", \n density.info = \"none\", main = \"Bohicon\", cexRow=.5)\n 0.2 + 1/log10(nr)"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11423881/"
] |
74,606,644
|
<p>My microservices project structure is like this:</p>
<pre><code>my-service-one/
- Dockerfile
- ...
my-service-two/
- Dockerfile
- ...
docker-compose.yml
</code></pre>
<p>As you can see, each service directory contains a Dockerfile. There is a <code>docker-compose.yml</code> in the root level.</p>
<p>The <code>docker-compose.yml</code> :</p>
<pre><code>version: "3"
services:
service-one:
container_name: service-one
build:
dockerfile: ./my-service-one/Dockerfile
ports:
- "8081:8081"
service-two:
container_name: service-two
build:
dockerfile: ./my-service-two/Dockerfile
ports:
- "8082:8082"
</code></pre>
<p>Now, I run <code>docker-compose up -d</code> from the root. I end up with error:</p>
<pre><code>$ docker-compose up -d
ERROR: The Compose file is invalid because:
Service service-one has neither an image nor a build context specified. At least one must be provided.
</code></pre>
<p>My question is <strong>why</strong> does docker-compose think my <code>service-one</code> doesn't have a build context specified? Didn't I specify it already with:</p>
<pre><code>build:
dockerfile: ./my-service-one/Dockerfile
</code></pre>
<p>Why this error?</p>
|
[
{
"answer_id": 74606949,
"author": "dbonev",
"author_id": 4200334,
"author_profile": "https://Stackoverflow.com/users/4200334",
"pm_score": 0,
"selected": false,
"text": "build:\n context: YOUR_DIRECTORY\n dockerfile: ./my-service-one/Dockerfile\n"
},
{
"answer_id": 74606959,
"author": "KamilCuk",
"author_id": 9072753,
"author_profile": "https://Stackoverflow.com/users/9072753",
"pm_score": 2,
"selected": true,
"text": "build:\n context: .\n dockerfile: ./my-service-two/Dockerfile\n my-service-two build:\n context: ./my-service-two\n dockerfile: ./Dockerfile\n build: ./my-service-two\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/842225/"
] |
74,606,652
|
<p>I am making my first commit using GIT in VS Code. I only have one main branch in Github and while I was using git push, I send it as:
git push origin/master accidentally.</p>
<p>Error:
error: src refspec main does not match any
error: failed to push some refs to 'https://github.com/<em>"repoName"</em>.git'</p>
<p>I tried git reset origin/main it shows me this message:
Unstaged changes after reset:
M README.md
D a.jpg</p>
<p>And when I tried again with git push origin main, it still throws the same error</p>
<p>I want to push it in my repo in main branch(there is no master branch in mine)</p>
|
[
{
"answer_id": 74606949,
"author": "dbonev",
"author_id": 4200334,
"author_profile": "https://Stackoverflow.com/users/4200334",
"pm_score": 0,
"selected": false,
"text": "build:\n context: YOUR_DIRECTORY\n dockerfile: ./my-service-one/Dockerfile\n"
},
{
"answer_id": 74606959,
"author": "KamilCuk",
"author_id": 9072753,
"author_profile": "https://Stackoverflow.com/users/9072753",
"pm_score": 2,
"selected": true,
"text": "build:\n context: .\n dockerfile: ./my-service-two/Dockerfile\n my-service-two build:\n context: ./my-service-two\n dockerfile: ./Dockerfile\n build: ./my-service-two\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20543349/"
] |
74,606,689
|
<p>I have a task to shift an array of real numbers to the right by n elements, what I have succesfully done, bu then I noticed that I was supposed to use only addresses and pointers.
I tried to rewrite code with addresses but it seems to not work, can someone please help me with it.</p>
<p>So here is the code which is working, but it uses indexes method, hope you can help me because i'm dumb and can't rewrite it properly(</p>
<pre><code>#include <stdio.h>
#include <math.h>
#define N 5
void main() {
double ar[N] = {1.2, 2.2, 3.3, 4.4, 5.5};
int n;
int save;
printf_s("Enter an n:");
scanf_s("%d", &n);
int length = sizeof(ar) / sizeof(ar[0]);
while (n) {
save = ar[N - 1];
for (int i = N - 1; i > 0; i--)
ar[i] = ar[i - 1];
ar[0] = save;
n--;
}
for (int i = 0; i < length; i++) {
printf("%f; ", ar[i]);
}
}
</code></pre>
|
[
{
"answer_id": 74606949,
"author": "dbonev",
"author_id": 4200334,
"author_profile": "https://Stackoverflow.com/users/4200334",
"pm_score": 0,
"selected": false,
"text": "build:\n context: YOUR_DIRECTORY\n dockerfile: ./my-service-one/Dockerfile\n"
},
{
"answer_id": 74606959,
"author": "KamilCuk",
"author_id": 9072753,
"author_profile": "https://Stackoverflow.com/users/9072753",
"pm_score": 2,
"selected": true,
"text": "build:\n context: .\n dockerfile: ./my-service-two/Dockerfile\n my-service-two build:\n context: ./my-service-two\n dockerfile: ./Dockerfile\n build: ./my-service-two\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20627290/"
] |
74,606,696
|
<p>I am trying to use TCLs builtin <code>exec</code> procedure to run the following <code>sed</code> shell command:</p>
<pre><code>sed -i 's/"VALUE.${name}">.*</"VALUE.${name}">${value}</' ${dir}/imp.xml
</code></pre>
<p>However when I pass it to exec tcl errors out with</p>
<pre><code>sed: -e expression #1, char 1: unknown command: `''
</code></pre>
<p>no idea how to interpret this.</p>
<p>I tried escaping the exec string:</p>
<pre><code>exec {sed -i 's/"VALUE.${name}">.*</"VALUE.${name}">${value}</' ${dir}/imp.xml}
</code></pre>
<p>However this prevents the tcl variables from being expanded inside of the string.</p>
<p>Does anyone know what I need to do to get tcl to exec this sed program?</p>
<p>(my shell is csh if that is relevant)</p>
|
[
{
"answer_id": 74606846,
"author": "Chris Heithoff",
"author_id": 16350882,
"author_profile": "https://Stackoverflow.com/users/16350882",
"pm_score": 1,
"selected": false,
"text": "exec exec sed -i 's/\\\"VALUE.\\${name}\\\">.*</\\\"VALUE.\\${name}\\\">\\${value}' \\${dir}/impl.xml\n"
},
{
"answer_id": 74606976,
"author": "Guilty",
"author_id": 11127623,
"author_profile": "https://Stackoverflow.com/users/11127623",
"pm_score": 3,
"selected": true,
"text": "exec sed -i \"s/\\\"VALUE.${name}\\\">.*</\\\"VALUE.${name}\\\">${alue}</\" ${dir}/impl.xml\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74606696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11127623/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.