qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,666,167
|
<p>I'm trying to associate in a dataframe the values of a list of numbers with the respective strings. Here's the problem:</p>
<pre><code>import pandas as pd
categories = {"key1":["string1", "string2", "string3"], "key2": ["string1", "str1", "str2"]}
strings= ["string1", "string2", "string3", "string1", "str1", "str2"]
numbers = [1,2,3,4,5,6]
array = []
expected_fields = []
#Creation of the dataframe with double rows, where the first is the key of categories
#and the second is the elements of the list present in the values of categories
for key, value in categories.items():
array.extend([key]* len(value))
expected_fields.extend(value)
arrays = [array ,expected_fields]
#Creation of the dataframe
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples)
df = pd.Series(dtype='float', index=index)
for key, values in categories.items():
for value in values:
for i in range(len(strings)):
if strings[i] == value:
df[key, value] = numbers[i]
print(df)
</code></pre>
<p>Output:</p>
<pre><code>key1 string1 4.0 <---------
string2 2.0
string3 3.0
key2 string1 4.0
str1 5.0
str2 6.0
</code></pre>
<p>Expected output:</p>
<pre><code>key1 string1 1.0 <---------
string2 2.0
string3 3.0
key2 string1 4.0
str1 5.0
str2 6.0
</code></pre>
<p>The association is always going for the last element of the list due to the repeated string in strings. However I want the first element of numbers for the first repeated string and the following number for the second repeated string.</p>
<p>I could count the number of elements of the values of the dictionary categories for each key and perform an increment in the for loop correspondent to the strings and based on the lower and upper limit add an if inside that for loop, however I can't go for this approach due to technical limitations.</p>
|
[
{
"answer_id": 74666208,
"author": "a5zima",
"author_id": 14034634,
"author_profile": "https://Stackoverflow.com/users/14034634",
"pm_score": 0,
"selected": false,
"text": "# Convert the list of lists to a set\ndata_set = set(tuple(x) for x in data)\n\n# Convert the set back to a list\ndata_unique = [list(x) for x in data_set]\n"
},
{
"answer_id": 74666257,
"author": "Punit Choudhary",
"author_id": 13527252,
"author_profile": "https://Stackoverflow.com/users/13527252",
"pm_score": 0,
"selected": false,
"text": "def get_unique(lst):\n if not lst:\n return []\n if lst[0] in lst[1:]:\n return get_unique(lst[1:])\n else:\n return [lst[0]] + get_unique(lst[1:])\n\ndata = [\n[\"629-2, text1, 12\"],\n[\"629-2, text2, 12\"],\n[\"407-3, text9, 6\"],\n[\"407-3, text4, 6\"],\n[\"000-5, text7, 0\"],\n[\"000-5, text6, 0\"],\n]\nprint(get_unique(data))\n"
},
{
"answer_id": 74666343,
"author": "DarrylG",
"author_id": 3066077,
"author_profile": "https://Stackoverflow.com/users/3066077",
"pm_score": 3,
"selected": true,
"text": "from itertools import groupby\n\ndef get_unique(data):\n def designated_version(item):\n return item[0].split(',')[0]\n\n return [list(v)[0] \n for _, v in groupby(sorted(data, \n key = designated_version),\n designated_version)\n ]\n\n \n print(get_unique(data))\n# Output\n[['629-2, text1, 12'], ['407-3, text9, 6'], ['000-5, text7, 0']]\n lambda item: item[0].split(',')[0] list(v)[0]"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11945594/"
] |
74,666,170
|
<p><a href="https://i.stack.imgur.com/zek7C.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zek7C.jpg" alt="from web page HTML" /></a></p>
<p>I am doing a county property survey. The mailing address is included on each record/webpage as a non-displayed comment <!-- p> with a p tag I am trying to extract those non non-displayed comments which contain the mailing and physical address of the property (see attached jpeg)</p>
<p>I have tried various forms of comment and attribute schemes to add on to the CSS and xPath Selectors for the h2 header above the comments - but no go so far</p>
<p>Set Mailing = MyBrowser.FindElementsByCss("#lxT413 > table > tbody > tr:nth-child(2) > td > h2)
Set Mailing = MyBrowser.FindElementByXPath("//*[@id="lxT413"]/table/tbody/tr[2]/td/h2")</p>
|
[
{
"answer_id": 74667786,
"author": "Shatas",
"author_id": 4054411,
"author_profile": "https://Stackoverflow.com/users/4054411",
"pm_score": 1,
"selected": true,
"text": "h2 td"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14858801/"
] |
74,666,184
|
<p>I am unable to decipher the error here. Can any one help ?</p>
<pre><code>from jinja2 import Template
prefixes = {
"10.0.0.0/24" : {
"description": "Corporate NAS",
"region": "Europe",
"site": "Telehouse-West"
}
}
template = """
Details for 10.0.0.0/24 prefix:
Description: {{ prefixes['10.0.0.0/24'].description }}
Region: {{ prefixes['10.0.0.0/24'].region }}
Site: {{ prefixes['10.0.0.0/24'].site }}
"""
j2 = Template(template)
print(j2.render(prefixes))
</code></pre>
<p>Error:</p>
<pre><code> File "c:\Users\verma\Documents\Python\jinja\jinja1.py", line 19, in <module>
print(j2.render(prefixes))
File "C:\Users\verma\AppData\Roaming\Python\Python310\site-packages\jinja2\environment.py", line 1301, in render
self.environment.handle_exception()
File "C:\Users\verma\AppData\Roaming\Python\Python310\site-packages\jinja2\environment.py", line 936, in handle_exception
raise rewrite_traceback_stack(source=source)
File "<template>", line 3, in top-level template code
File "C:\Users\verma\AppData\Roaming\Python\Python310\site-packages\jinja2\environment.py", line 466, in getitem
return obj[argument]
jinja2.exceptions.UndefinedError: 'prefixes' is undefined
</code></pre>
<p>I was expecting the jinja2 rendering to work.</p>
|
[
{
"answer_id": 74666243,
"author": "Mohamed Yasser",
"author_id": 16516114,
"author_profile": "https://Stackoverflow.com/users/16516114",
"pm_score": 1,
"selected": false,
"text": "render print(j2.render(prefixes)) print(j2.render(prefixes=prefixes))"
},
{
"answer_id": 74666285,
"author": "Gabio",
"author_id": 12400214,
"author_profile": "https://Stackoverflow.com/users/12400214",
"pm_score": 0,
"selected": false,
"text": "prefixes prefixes prefixes = {\n \"prefixes\": {\n \"10.0.0.0/24\": {\n \"description\": \"Corporate NAS\",\n \"region\": \"Europe\",\n \"site\": \"Telehouse-West\"\n }\n }\n}\n"
},
{
"answer_id": 74666296,
"author": "Sahaj Raj Malla",
"author_id": 11773575,
"author_profile": "https://Stackoverflow.com/users/11773575",
"pm_score": 0,
"selected": false,
"text": "prefixes prefixes render() render() \nprint(j2.render(prefixes=prefixes))\n\n prefixes"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20020613/"
] |
74,666,185
|
<p>populate each hand with two cards. Take a card from the deck
and put it in the player_hand list. Then, take a card from the deck and
put it in the dealer_hand list. Do that one more time in that order so that the dealer and player have each two cards. Make sure the dealer's first card is face down. I keep receiving this error from my 2 tests.</p>
<p>My code:</p>
<pre><code> while len(dealer_hand) != 2 and len(player_hand) != 2:
player_card = random.choice(deck)
player_hand.append(player_card)
deck.remove(player_card)
if len(player_hand) == 2:
player_hand[0].face_up()
player_hand[1].face_up()
dealer_card = random.choice(deck)
dealer_hand.append(dealer_card)
deck.remove(dealer_card)
if len(dealer_hand) == 2:
dealer_hand[0].face_down()
dealer_hand[1].face_up()
return player_hand and dealer_hand
False != True
Expected :True
Actual :False
def test_deal_cards():
deck = []
for suit in cards.SUITS:
for rank in cards.RANKS:
deck.append(cards.Card(suit, rank))
dealer_hand = []
player_hand = []
blackjack.deal_cards(deck, dealer_hand, player_hand)
assert len(dealer_hand) == 2
assert len(player_hand) == 2
> assert dealer_hand[0].is_face_up() is True
E assert False is True
E + where False = <bound method Card.is_face_up of [10 of Hearts]>()
E + where <bound method Card.is_face_up of [10 of Hearts]> = [10 of Hearts].is_face_up
test_deal_cards.py:19: AssertionError
(test_deal_cards_alternates_between_player_and_dealer)
[7 of Hearts] != [6 of Spades]
Expected :[6 of Spades]
Actual :[7 of Hearts]
def test_deal_cards_alternates_between_player_and_dealer():
card1 = cards.Card(cards.SPADES, cards.SIX)
card2 = cards.Card(cards.HEARTS, cards.SEVEN)
card3 = cards.Card(cards.CLUBS, cards.EIGHT)
card4 = cards.Card(cards.DIAMONDS, cards.NINE)
deck = [card4, card3, card2, card1]
dealer_hand = []
player_hand = []
blackjack.deal_cards(deck, dealer_hand, player_hand)
assert len(dealer_hand) == 2
assert len(player_hand) == 2
> assert player_hand[0] is card1, 'Player 1st card should be Six of Spades'
E AssertionError: Player 1st card should be Six of Spades
E assert [7 of Hearts] is [6 of Spades]
test_deal_cards.py:39: AssertionError
</code></pre>
|
[
{
"answer_id": 74666243,
"author": "Mohamed Yasser",
"author_id": 16516114,
"author_profile": "https://Stackoverflow.com/users/16516114",
"pm_score": 1,
"selected": false,
"text": "render print(j2.render(prefixes)) print(j2.render(prefixes=prefixes))"
},
{
"answer_id": 74666285,
"author": "Gabio",
"author_id": 12400214,
"author_profile": "https://Stackoverflow.com/users/12400214",
"pm_score": 0,
"selected": false,
"text": "prefixes prefixes prefixes = {\n \"prefixes\": {\n \"10.0.0.0/24\": {\n \"description\": \"Corporate NAS\",\n \"region\": \"Europe\",\n \"site\": \"Telehouse-West\"\n }\n }\n}\n"
},
{
"answer_id": 74666296,
"author": "Sahaj Raj Malla",
"author_id": 11773575,
"author_profile": "https://Stackoverflow.com/users/11773575",
"pm_score": 0,
"selected": false,
"text": "prefixes prefixes render() render() \nprint(j2.render(prefixes=prefixes))\n\n prefixes"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20326002/"
] |
74,666,206
|
<p>I am trying to grab data from JSON file based on what quarter the dates represent. My goal is to assign the data to a variable so I should have Q1, Q2, Q3, Q4 variables holding the data inside. Below is the JSON:</p>
<pre><code>{
"lastDate":{
"0":"2022Q4",
"1":"2022Q4",
"2":"2022Q4",
"7":"2022Q4",
"8":"2022Q4",
"9":"2022Q4",
"18":"2022Q3",
"19":"2022Q3",
"22":"2022Q3",
"24":"2022Q2"
},
"transactionType":{
"0":"Sell",
"1":"Automatic Sell",
"2":"Automatic Sell",
"7":"Automatic Sell",
"8":"Sell",
"9":"Automatic Sell",
"18":"Automatic Sell",
"19":"Automatic Sell",
"22":"Automatic Sell",
"24":"Automatic Sell"
},
"sharesTraded":{
"0":"20,200",
"1":"176,299",
"2":"8,053",
"7":"167,889",
"8":"13,250",
"9":"176,299",
"18":"96,735",
"19":"15,366",
"22":"25,000",
"24":"25,000"
}
}
</code></pre>
<p>Now if i try to use the following code:</p>
<pre><code>import json
data = json.load(open("AAPL22data.json"))
Q2data = [item for item in data if '2022Q2' in data['lastDate']]
print(Q2data)
</code></pre>
<p>My ideal output should be:</p>
<pre><code>{
"lastDate":{
"24":"2022Q2"
},
"transactionType":{
"24":"Automatic Sell"
},
"sharesTraded":{
"24":"25,000"
}
}
</code></pre>
<p>And then repeat the same structure for the other quarters. However, my current output gives me "[ ]"</p>
|
[
{
"answer_id": 74666502,
"author": "Franco Milanese",
"author_id": 13991234,
"author_profile": "https://Stackoverflow.com/users/13991234",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd \n\nsample_dict = {\n \"lastDate\":{\n \"0\":\"2022Q4\",\n \"1\":\"2022Q4\",\n \"2\":\"2022Q4\",\n \"7\":\"2022Q4\",\n \"8\":\"2022Q4\",\n \"9\":\"2022Q4\",\n \"18\":\"2022Q3\",\n \"19\":\"2022Q3\",\n \"22\":\"2022Q3\",\n \"24\":\"2022Q2\"\n },\n \"transactionType\":{\n \"0\":\"Sell\",\n \"1\":\"Automatic Sell\",\n \"2\":\"Automatic Sell\",\n \"7\":\"Automatic Sell\",\n \"8\":\"Sell\",\n \"9\":\"Automatic Sell\",\n \"18\":\"Automatic Sell\",\n \"19\":\"Automatic Sell\",\n \"22\":\"Automatic Sell\",\n \"24\":\"Automatic Sell\"\n },\n \"sharesTraded\":{\n \"0\":\"20,200\",\n \"1\":\"176,299\",\n \"2\":\"8,053\",\n \"7\":\"167,889\",\n \"8\":\"13,250\",\n \"9\":\"176,299\",\n \"18\":\"96,735\",\n \"19\":\"15,366\",\n \"22\":\"25,000\",\n \"24\":\"25,000\"\n }\n}\n\nprint(pd.DataFrame.from_dict(sample_dict))\n Output:\n\n lastDate transactionType sharesTraded\n0 2022Q4 Sell 20,200\n1 2022Q4 Automatic Sell 176,299\n2 2022Q4 Automatic Sell 8,053\n7 2022Q4 Automatic Sell 167,889\n8 2022Q4 Sell 13,250\n9 2022Q4 Automatic Sell 176,299\n18 2022Q3 Automatic Sell 96,735\n19 2022Q3 Automatic Sell 15,366\n22 2022Q3 Automatic Sell 25,000\n24 2022Q2 Automatic Sell 25,000\n"
},
{
"answer_id": 74667303,
"author": "Marty_C137",
"author_id": 15417368,
"author_profile": "https://Stackoverflow.com/users/15417368",
"pm_score": 1,
"selected": false,
"text": "import json\n\nmy_json = \"\"\"{\n \"lastDate\":{\n \"0\":\"2022Q4\",\n \"1\":\"2022Q4\",\n \"2\":\"2022Q4\",\n \"7\":\"2022Q4\",\n \"8\":\"2022Q4\",\n \"9\":\"2022Q4\",\n \"18\":\"2022Q3\",\n \"19\":\"2022Q3\",\n \"22\":\"2022Q3\",\n \"24\":\"2022Q2\"\n },\n \"transactionType\":{\n \"0\":\"Sell\",\n \"1\":\"Automatic Sell\",\n \"2\":\"Automatic Sell\",\n \"7\":\"Automatic Sell\",\n \"8\":\"Sell\",\n \"9\":\"Automatic Sell\",\n \"18\":\"Automatic Sell\",\n \"19\":\"Automatic Sell\",\n \"22\":\"Automatic Sell\",\n \"24\":\"Automatic Sell\"\n },\n \"sharesTraded\":{\n \"0\":\"20,200\",\n \"1\":\"176,299\",\n \"2\":\"8,053\",\n \"7\":\"167,889\",\n \"8\":\"13,250\",\n \"9\":\"176,299\",\n \"18\":\"96,735\",\n \"19\":\"15,366\",\n \"22\":\"25,000\",\n \"24\":\"25,000\"\n }\n}\"\"\"\n data = json.loads(my_json)\n\nvar = \"24\" #This corresponds to 2022 Q2 in your example\n\ndata = {k:{var: v[var]} for k, v in data.items()}\ndata = json.dumps(data, indent = 2)\n\nprint(data)\n {\n \"lastDate\": {\n \"24\": \"2022Q2\"\n },\n \"transactionType\": {\n \"24\": \"Automatic Sell\"\n },\n \"sharesTraded\": {\n \"24\": \"25,000\"\n }\n}\n"
},
{
"answer_id": 74669207,
"author": "kiestuthridge23",
"author_id": 18823431,
"author_profile": "https://Stackoverflow.com/users/18823431",
"pm_score": 0,
"selected": false,
"text": "group_by import json\nimport pandas as pd \n\ndata = json.load(open(\"AAPL22data.json\"))\n\ndf = pd.DataFrame.from_dict(data)\n\nq2df = df.groupby('lastDate')\n\nq2df.get_group('2022Q2') #change '2022q2' for others & assign to a different variable\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18823431/"
] |
74,666,210
|
<p>world!
I'm currently stuck on this problem where i want to join two columns and run the select statement of the two, but i'm getting errors; these are the columns i want to join:</p>
<pre><code>SELECT DISTINCT column_name FROM owner_name.table_name ORDER BY column_name;
</code></pre>
<p>and</p>
<pre><code>SELECT DISTINCT * FROM (SELECT count(column_name) OVER (partition by column_name) Amount from owner_name.table_name order by column_name);
</code></pre>
<p>where in the second, for every row, i count how many equal rows i have for each value.</p>
<p>the two columns values:
<a href="https://i.stack.imgur.com/FMe2M.png" rel="nofollow noreferrer">first column</a>
<a href="https://i.stack.imgur.com/BbZC1.png" rel="nofollow noreferrer">second column</a></p>
<p>i dont know how to have both of them next to each other as a normal select statement:
SELECT column_1, column_2 FROM table;</p>
|
[
{
"answer_id": 74666502,
"author": "Franco Milanese",
"author_id": 13991234,
"author_profile": "https://Stackoverflow.com/users/13991234",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd \n\nsample_dict = {\n \"lastDate\":{\n \"0\":\"2022Q4\",\n \"1\":\"2022Q4\",\n \"2\":\"2022Q4\",\n \"7\":\"2022Q4\",\n \"8\":\"2022Q4\",\n \"9\":\"2022Q4\",\n \"18\":\"2022Q3\",\n \"19\":\"2022Q3\",\n \"22\":\"2022Q3\",\n \"24\":\"2022Q2\"\n },\n \"transactionType\":{\n \"0\":\"Sell\",\n \"1\":\"Automatic Sell\",\n \"2\":\"Automatic Sell\",\n \"7\":\"Automatic Sell\",\n \"8\":\"Sell\",\n \"9\":\"Automatic Sell\",\n \"18\":\"Automatic Sell\",\n \"19\":\"Automatic Sell\",\n \"22\":\"Automatic Sell\",\n \"24\":\"Automatic Sell\"\n },\n \"sharesTraded\":{\n \"0\":\"20,200\",\n \"1\":\"176,299\",\n \"2\":\"8,053\",\n \"7\":\"167,889\",\n \"8\":\"13,250\",\n \"9\":\"176,299\",\n \"18\":\"96,735\",\n \"19\":\"15,366\",\n \"22\":\"25,000\",\n \"24\":\"25,000\"\n }\n}\n\nprint(pd.DataFrame.from_dict(sample_dict))\n Output:\n\n lastDate transactionType sharesTraded\n0 2022Q4 Sell 20,200\n1 2022Q4 Automatic Sell 176,299\n2 2022Q4 Automatic Sell 8,053\n7 2022Q4 Automatic Sell 167,889\n8 2022Q4 Sell 13,250\n9 2022Q4 Automatic Sell 176,299\n18 2022Q3 Automatic Sell 96,735\n19 2022Q3 Automatic Sell 15,366\n22 2022Q3 Automatic Sell 25,000\n24 2022Q2 Automatic Sell 25,000\n"
},
{
"answer_id": 74667303,
"author": "Marty_C137",
"author_id": 15417368,
"author_profile": "https://Stackoverflow.com/users/15417368",
"pm_score": 1,
"selected": false,
"text": "import json\n\nmy_json = \"\"\"{\n \"lastDate\":{\n \"0\":\"2022Q4\",\n \"1\":\"2022Q4\",\n \"2\":\"2022Q4\",\n \"7\":\"2022Q4\",\n \"8\":\"2022Q4\",\n \"9\":\"2022Q4\",\n \"18\":\"2022Q3\",\n \"19\":\"2022Q3\",\n \"22\":\"2022Q3\",\n \"24\":\"2022Q2\"\n },\n \"transactionType\":{\n \"0\":\"Sell\",\n \"1\":\"Automatic Sell\",\n \"2\":\"Automatic Sell\",\n \"7\":\"Automatic Sell\",\n \"8\":\"Sell\",\n \"9\":\"Automatic Sell\",\n \"18\":\"Automatic Sell\",\n \"19\":\"Automatic Sell\",\n \"22\":\"Automatic Sell\",\n \"24\":\"Automatic Sell\"\n },\n \"sharesTraded\":{\n \"0\":\"20,200\",\n \"1\":\"176,299\",\n \"2\":\"8,053\",\n \"7\":\"167,889\",\n \"8\":\"13,250\",\n \"9\":\"176,299\",\n \"18\":\"96,735\",\n \"19\":\"15,366\",\n \"22\":\"25,000\",\n \"24\":\"25,000\"\n }\n}\"\"\"\n data = json.loads(my_json)\n\nvar = \"24\" #This corresponds to 2022 Q2 in your example\n\ndata = {k:{var: v[var]} for k, v in data.items()}\ndata = json.dumps(data, indent = 2)\n\nprint(data)\n {\n \"lastDate\": {\n \"24\": \"2022Q2\"\n },\n \"transactionType\": {\n \"24\": \"Automatic Sell\"\n },\n \"sharesTraded\": {\n \"24\": \"25,000\"\n }\n}\n"
},
{
"answer_id": 74669207,
"author": "kiestuthridge23",
"author_id": 18823431,
"author_profile": "https://Stackoverflow.com/users/18823431",
"pm_score": 0,
"selected": false,
"text": "group_by import json\nimport pandas as pd \n\ndata = json.load(open(\"AAPL22data.json\"))\n\ndf = pd.DataFrame.from_dict(data)\n\nq2df = df.groupby('lastDate')\n\nq2df.get_group('2022Q2') #change '2022q2' for others & assign to a different variable\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20673907/"
] |
74,666,238
|
<pre><code>def n(a):
a = str(a)
if "0" in a:
b = str((a).replace("0", ''))
a = b[::-1]
a = a[::-1]
a = int(a)
return a
else:
a = a[::-1]
a = a[::-1]
a = int(a)
return a
N = int(input())
des = 10**9 + 7
summa = 0
for a in range():
print(n(a))
b = n(a)
summa = summa + b
summa = summa % des
print(summa)
</code></pre>
<p>gives such an error : <code>'invalid literal for int() with base 10: '' '</code></p>
<p>If I pass the value to the variable a without the for i in loop, then everything works</p>
<p>I just need to understand what is wrong with the code. I'm new to programming and can't figure it out right away</p>
|
[
{
"answer_id": 74666270,
"author": "Mitchell van Zuylen",
"author_id": 7052826,
"author_profile": "https://Stackoverflow.com/users/7052826",
"pm_score": 2,
"selected": false,
"text": "input '' '' int('')` # returns `ValueError: invalid literal for int() with base 10: ''\n '' int() input N = int(input())\n range range(N) def n(a):\n a = str(a)\n if \"0\" in a: # this also happen when a == '0'\n b = str((a).replace(\"0\", '')) \n a = b[::-1]\n a = a[::-1]\n a = int(a) # and if a == '0', this resolved to int('')\n ....\n def n(a):\n if not a: # ifa is anything beside 0\n return 0 # then there is no sense in flipping it around \n a = str(a)\n ....\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20673956/"
] |
74,666,244
|
<h2><strong>Problem</strong></h2>
<p>I created a counter using HTML, CSS and JS (such as satisfied customer numbers, branch numbers, etc.)
The counter is also animated but since it's down the page, I'd like to animate it only when it gets to that point on the page. How do I do with the js?</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 counters = document.querySelectorAll('.value');
const speed = 400;
counters.forEach( counter => {
const animate = () => {
const value = +counter.getAttribute('akhi');
const data = +counter.innerText;
const time = value / speed;
if(data < value) {
counter.innerText = Math.ceil(data + time);
setTimeout(animate, 1);
}else{
counter.innerText = value;
}
}
animate();
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.counter-box {
display: block;
background: #f6f6f6;
padding: 40px 20px 37px;
text-align: center
}
.counter-box p {
margin: 5px 0 0;
padding: 0;
color: #909090;
font-size: 18px;
font-weight: 500
}
.counter {
display: block;
font-size: 32px;
font-weight: 700;
color: #666;
line-height: 28px
}
.counter-box.colored {
background: #eab736;
}
.counter-box.colored p,
.counter-box.colored .counter {
color: #fff;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="container">
<div class="row contatore">
<div class="col-md-4">
<div class="counter-box colored">
<span class="counter value" akhi="560">0</span>
<p>Countries visited</p>
</div>
</div>
<div class="col-md-4">
<div class="counter-box">
<span class="counter value" akhi="3275">0</span>
<p>Registered travellers</p>
</div>
</div>
<div class="col-md-4">
<div class="counter-box">
<span class="counter value" id="conta" akhi="289">0</span>
<p>Partners</p>
</div>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<h2><strong>What I have tried</strong></h2>
<p>i had tried with</p>
<pre><code>const target = document.querySelector('.counter');
observer.observe(target);
</code></pre>
<p>but it doesn't seem to work. Many thanks to whoever can help me.</p>
|
[
{
"answer_id": 74666895,
"author": "ths",
"author_id": 6388552,
"author_profile": "https://Stackoverflow.com/users/6388552",
"pm_score": 1,
"selected": false,
"text": "observer counters animate counter IntersectionObserver counters const counters = document.querySelectorAll('.value'),\n speed = 400,\n /**\n * create an IntersectionObserver with the specified callback that will be executed for each intersection change for every counter we have. \n * You may customize the options (2nd argument) per you requirement\n */\n observer = new IntersectionObserver(\n entries => entries.forEach(entry => entry.isIntersecting && animate(entry.target)), \n {\n threshold: 1 // tells the browser that we only need to execute the callback only when an element (counter) is fully visible in the viewport\n }\n ),\n // the animate function now accepts a counter (HTML element)\n animate = counter => {\n const value = +counter.dataset.akhi,\n data = +counter.innerText,\n time = value / speed;\n if (data < value) {\n counter.innerText = Math.ceil(data + time);\n setTimeout(() => animate(counter), 1);\n } else {\n counter.innerText = value;\n }\n };\n\n// attach the counters to the observer\ncounters.forEach(c => observer.observe(c)); .counter-box {\n display: block;\n background: #f6f6f6;\n padding: 40px 20px 37px;\n text-align: center\n}\n\n.counter-box p {\n margin: 5px 0 0;\n padding: 0;\n color: #909090;\n font-size: 18px;\n font-weight: 500\n}\n\n.counter {\n display: block;\n font-size: 32px;\n font-weight: 700;\n color: #666;\n line-height: 28px\n}\n\n.counter-box.colored {\n background: #eab736;\n}\n\n.counter-box.colored p,\n.counter-box.colored .counter {\n color: #fff;\n} <div class=\"container\">\n <div class=\"row contatore\">\n <div class=\"col-md-4\">\n <div class=\"counter-box colored\">\n <!-- it is recommended to use \"data-*\" attributes to cache data that we might use later. The \"data-akhi\" contains the number to animate -->\n <span class=\"counter value\" data-akhi=\"560\">0</span>\n <p>Countries visited</p>\n </div>\n </div>\n <div class=\"col-md-4\">\n <div class=\"counter-box\">\n <span class=\"counter value\" data-akhi=\"3275\">0</span>\n <p>Registered travellers</p>\n </div>\n </div>\n <div class=\"col-md-4\">\n <div class=\"counter-box\">\n <span class=\"counter value\" id=\"conta\" data-akhi=\"289\">0</span>\n <p>Partners</p>\n </div>\n </div>\n </div>\n</div>"
},
{
"answer_id": 74666949,
"author": "gugateider",
"author_id": 5168782,
"author_profile": "https://Stackoverflow.com/users/5168782",
"pm_score": 0,
"selected": false,
"text": "const counters = document.querySelectorAll('.value');\nconst speed = 400;\n\nconst observer = new IntersectionObserver( items => {\n \n if(items[0].isIntersecting) { \n const target = items[0].target;\n const animate = () => {\n const value = + target.getAttribute('akhi');\n const data = + target.innerText;\n \n const time = value / speed;\n if(data < value) {\n target.innerText = Math.ceil(data + time);\n setTimeout(animate, 1);\n }else{\n target.innerText = value;\n } \n } \n animate(); \n observer.unobserve(target);\n }\n})\n\ncounters.forEach( counter => observer.observe(counter)); .counter-box {\n\n display: block;\n background: #f6f6f6;\n padding: 40px 20px 37px;\n text-align: center\n\n}\n.counter-box p {\n\n margin: 5px 0 0;\n padding: 0;\n color: #909090;\n font-size: 18px;\n font-weight: 500\n\n}\n\n.counter { \n\n display: block;\n font-size: 32px;\n font-weight: 700;\n color: #666;\n line-height: 28px\n\n}\n.counter-box.colored {\n\n background: #eab736;\n\n}\n.counter-box.colored p,\n.counter-box.colored .counter {\n\n color: #fff;\n\n} <div style=\"height: 600px;\">\n\n</div>\n\n\n<div class=\"container\">\n <div class=\"row contatore\">\n <div class=\"col-md-4\">\n <div class=\"counter-box colored\">\n <span class=\"counter value\" akhi=\"560\">0</span>\n <p>Countries visited</p>\n </div>\n </div>\n\n <div class=\"col-md-4\">\n <div class=\"counter-box\">\n <span class=\"counter value\" akhi=\"3275\">0</span>\n <p>Registered travellers</p>\n </div>\n </div>\n\n <div class=\"col-md-4\">\n <div class=\"counter-box\">\n <span class=\"counter value\" id=\"conta\" akhi=\"289\">0</span>\n <p>Partners</p>\n </div>\n </div>\n </div> \n </div>"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15910389/"
] |
74,666,280
|
<p>I have two dataframes:</p>
<pre><code>df1 =
C0 C1. C2.
4 AB. 1. 2
5 AC. 7 8
6 AD. 9. 9
7 AE. 2. 6
8 AG 8. 9
df2 =
C0 C1. C2
8 AB 0. 1
9 AE. 6. 3
10 AD. 1. 2
</code></pre>
<p>I want to apply a subtraction between these two dataframes, such that when the value of the columns C0 is the same - I will get the subsraction, and when is not - a bool column will have the value False. notice that current indeics are not aligned.
So new df1 should be:</p>
<pre><code>df1 =
C0 C1. C2. diff_C1 match
4 AB. 1. 2. 1. True
5 AC. 7 8. 0. False
6 AD. 9. 9. 8. True
7 AE. 2. 6. -4. True
8 AG 8. 9. 0 False
</code></pre>
<p>What is the best way to do it?</p>
|
[
{
"answer_id": 74666447,
"author": "Tron",
"author_id": 9917285,
"author_profile": "https://Stackoverflow.com/users/9917285",
"pm_score": 1,
"selected": true,
"text": "df1.merge(df2, how='left', on='C0')\n .assign(match=lambda x: x['C1_y'].notna())\n .fillna(0)\n df['C1_diff'] = df['C1_x'] - df['C1_y']\n"
},
{
"answer_id": 74666495,
"author": "PaulS",
"author_id": 11564487,
"author_profile": "https://Stackoverflow.com/users/11564487",
"pm_score": 1,
"selected": false,
"text": "pandas.DataFrame.merge (df1.merge(df2.iloc[:,:-1], on='C0', suffixes=['', 'y'], how='left')\n .rename({'C1.y': 'diff_C1'}, axis=1)\n .assign(diff_C1 = lambda x: x['C1.'].sub(x['diff_C1']))\n .assign(match = lambda x: x['diff_C1'].notna())\n .fillna(0))\n C0 C1. C2. diff_C1 match\n0 AB. 1.0 2 1.0 True\n1 AC. 7.0 8 0.0 False\n2 AD. 9.0 9 8.0 True\n3 AE. 2.0 6 -4.0 True\n4 AG. 8.0 9 0.0 False\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6057371/"
] |
74,666,329
|
<p>I have in a component this piece of code</p>
<p><a href="https://i.stack.imgur.com/RAwmk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RAwmk.png" alt="enter image description here" /></a></p>
<p>TagCanvas is defined in the _app.tsx file within a legacy JS script. I need to do like that because if I include it in the component using it doesn't work when the component is rendered again.</p>
<p><a href="https://i.stack.imgur.com/m83xv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m83xv.png" alt="enter image description here" /></a></p>
<p>I want to test this component, so I have started rendering the component like this:</p>
<pre><code>import {render, screen} from '@testing-library/react';
import {MusasCloud} from '../../../components/MusasCloud.tsx';
const TagCanvas = jest.fn();
describe('MusasCloud component', () => {
test('Should render the MusasCloud component', () => {
render(<MusasCloud musas={[]} />);
screen.debug();
});
});
</code></pre>
<p>I get the html rendered as I expect but I am getting the Canvas error which I would like to avoid.</p>
<p><a href="https://i.stack.imgur.com/t4Udw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t4Udw.png" alt="enter image description here" /></a></p>
<p>As you can see I have tried to mock the TagCanvas function using <code>jest.fn()</code> but this is not ding the job I'd expect.</p>
<p><strong>Question</strong>: How can I avoid this exception when running the test?</p>
|
[
{
"answer_id": 74671333,
"author": "Marek Rozmus",
"author_id": 6738911,
"author_profile": "https://Stackoverflow.com/users/6738911",
"pm_score": 2,
"selected": true,
"text": "global setupTest.js global.TagCanvas = {\n Start: () => \"this is the mocked implementation\"\n}\n"
},
{
"answer_id": 74675071,
"author": "manou",
"author_id": 967216,
"author_profile": "https://Stackoverflow.com/users/967216",
"pm_score": 0,
"selected": false,
"text": "beforeAll setupTest.js //jest.config.js\nconst nextJest = require('next/jest');\n\nconst createJestConfig = nextJest({\n dir: './',\n});\n\n// Add any custom config to be passed to Jest\nconst customJestConfig = {\n moduleDirectories: ['node_modules', '<rootDir>/'],\n testEnvironment: 'jest-environment-jsdom',\n // Define setupTest file here\n setupFiles: ['<rootDir>/setupTest.js'],\n};\n\nmodule.exports = createJestConfig(customJestConfig);\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/967216/"
] |
74,666,330
|
<p>I have code to generate series of keys as in below:</p>
<pre><code>def Keygen (x,r,size):
key=[]
for i in range(size):
x= r*x*(1-x)
key.append(int((x*pow(10,16))%256))
return key
if __name__=="__main__":
key=Keygen(0.45,0.685,92)#Intial Parameters
print('nx key:', key, "\n")
</code></pre>
<p>The output keys are:</p>
<pre><code>nx key: [0, 11, 53, 42, 111, 38, 55, 102, 252, 155, 54, 219, 149, 220, 235, 177, 140, 46, 209, 249, 46, 241, 218, 243, 6, 166, 247, 106, 33, 24, 220, 185, 129, 182, 214, 210, 180, 28, 84, 117, 228, 213, 205, 240, 125, 37, 181, 234, 246, 54, 22, 195, 38, 174, 212, 166, 9, 237, 25, 225, 81, 23, 244, 235, 171, 196, 111, 182, 227, 26, 22, 246, 35, 52, 225, 249, 90, 237, 162, 111, 76, 52, 35, 24, 16, 11, 7, 5, 3, 2, 1, 1]
</code></pre>
<p>I try to convert all key values to hex by used the following code:</p>
<pre><code>K=hex(key)
print('nx key:', key, "\n")
</code></pre>
<p>But when run I got the error "TypeError: 'list' object cannot be interpreted as an integer" </p>
<p>Then try to use "K= hex(ord(key))" but also got another error "TypeError: ord() expected string of length 1, but list found"</p>
<p>What I need is to convert all keys to hex, then select just 4 keys to be like this </p>
<pre><code>K = (0x3412, 0x7856, 0xBC9A, 0xF0DE)
</code></pre>
|
[
{
"answer_id": 74671333,
"author": "Marek Rozmus",
"author_id": 6738911,
"author_profile": "https://Stackoverflow.com/users/6738911",
"pm_score": 2,
"selected": true,
"text": "global setupTest.js global.TagCanvas = {\n Start: () => \"this is the mocked implementation\"\n}\n"
},
{
"answer_id": 74675071,
"author": "manou",
"author_id": 967216,
"author_profile": "https://Stackoverflow.com/users/967216",
"pm_score": 0,
"selected": false,
"text": "beforeAll setupTest.js //jest.config.js\nconst nextJest = require('next/jest');\n\nconst createJestConfig = nextJest({\n dir: './',\n});\n\n// Add any custom config to be passed to Jest\nconst customJestConfig = {\n moduleDirectories: ['node_modules', '<rootDir>/'],\n testEnvironment: 'jest-environment-jsdom',\n // Define setupTest file here\n setupFiles: ['<rootDir>/setupTest.js'],\n};\n\nmodule.exports = createJestConfig(customJestConfig);\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14111838/"
] |
74,666,357
|
<pre><code>struct Node
{
int data;
Node *next;
};
void myLinkedList( Node* navigatePtr )
{
if(navigatePtr == NULL)
return;
myLinkedList(navigatePtr -> next);
cout << navigatePtr -> data << " ";
}
int main()
{
// Assuming that head is a pointer pointing to
// a linked list 1 -> 2 -> 3 -> 4 -> 5
myLinkedList(head);
return 0;
}
</code></pre>
<p>This is a question from a past year paper. It asks for the output which is 5,4,3,2,1. But, i do not understand what makes it print the linked list in reverse.</p>
|
[
{
"answer_id": 74671333,
"author": "Marek Rozmus",
"author_id": 6738911,
"author_profile": "https://Stackoverflow.com/users/6738911",
"pm_score": 2,
"selected": true,
"text": "global setupTest.js global.TagCanvas = {\n Start: () => \"this is the mocked implementation\"\n}\n"
},
{
"answer_id": 74675071,
"author": "manou",
"author_id": 967216,
"author_profile": "https://Stackoverflow.com/users/967216",
"pm_score": 0,
"selected": false,
"text": "beforeAll setupTest.js //jest.config.js\nconst nextJest = require('next/jest');\n\nconst createJestConfig = nextJest({\n dir: './',\n});\n\n// Add any custom config to be passed to Jest\nconst customJestConfig = {\n moduleDirectories: ['node_modules', '<rootDir>/'],\n testEnvironment: 'jest-environment-jsdom',\n // Define setupTest file here\n setupFiles: ['<rootDir>/setupTest.js'],\n};\n\nmodule.exports = createJestConfig(customJestConfig);\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20674067/"
] |
74,666,361
|
<p>I have setup a wagtail website. It works great for postings like a blog and simply add new pages.
But what if I want to add some extra functions to a page. Like showing values from my own database in a table.
Normally i use a models.py, views.py and template.py. But now I don’t see any views.py to add functions or a urls.py to redirect to an url?</p>
<p>Don’t know where to start!
Or is this not the meaning of a wagtail site, to customize it that way?</p>
<p>Thnx in advanced.</p>
|
[
{
"answer_id": 74671333,
"author": "Marek Rozmus",
"author_id": 6738911,
"author_profile": "https://Stackoverflow.com/users/6738911",
"pm_score": 2,
"selected": true,
"text": "global setupTest.js global.TagCanvas = {\n Start: () => \"this is the mocked implementation\"\n}\n"
},
{
"answer_id": 74675071,
"author": "manou",
"author_id": 967216,
"author_profile": "https://Stackoverflow.com/users/967216",
"pm_score": 0,
"selected": false,
"text": "beforeAll setupTest.js //jest.config.js\nconst nextJest = require('next/jest');\n\nconst createJestConfig = nextJest({\n dir: './',\n});\n\n// Add any custom config to be passed to Jest\nconst customJestConfig = {\n moduleDirectories: ['node_modules', '<rootDir>/'],\n testEnvironment: 'jest-environment-jsdom',\n // Define setupTest file here\n setupFiles: ['<rootDir>/setupTest.js'],\n};\n\nmodule.exports = createJestConfig(customJestConfig);\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12263783/"
] |
74,666,362
|
<p>How do I wait in using oc command for an operator package manifest to be available?</p>
<p>I am trying this</p>
<pre><code>❯ oc wait --for=condition=ready packagemanifest/example-manifest -n openshift-marketplace
Error from server (MethodNotAllowed): the server does not allow this method on the requested resource
</code></pre>
<p>This is failing because there is no ready state under spec field of package manifest</p>
|
[
{
"answer_id": 74671333,
"author": "Marek Rozmus",
"author_id": 6738911,
"author_profile": "https://Stackoverflow.com/users/6738911",
"pm_score": 2,
"selected": true,
"text": "global setupTest.js global.TagCanvas = {\n Start: () => \"this is the mocked implementation\"\n}\n"
},
{
"answer_id": 74675071,
"author": "manou",
"author_id": 967216,
"author_profile": "https://Stackoverflow.com/users/967216",
"pm_score": 0,
"selected": false,
"text": "beforeAll setupTest.js //jest.config.js\nconst nextJest = require('next/jest');\n\nconst createJestConfig = nextJest({\n dir: './',\n});\n\n// Add any custom config to be passed to Jest\nconst customJestConfig = {\n moduleDirectories: ['node_modules', '<rootDir>/'],\n testEnvironment: 'jest-environment-jsdom',\n // Define setupTest file here\n setupFiles: ['<rootDir>/setupTest.js'],\n};\n\nmodule.exports = createJestConfig(customJestConfig);\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9286924/"
] |
74,666,392
|
<p>New to C here, I am creating an insert function that will insert any value to an array provided I give the position of the array.</p>
<p>For example, here is what I have tried:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
int insert(int A[], int N, int P, int KEY){
int i = N - 1;
while(i >= P){
A[i+1] = A[i];
i += 1;
}
A[P] = KEY;
N = N+1;
return *A;
}
int main(void){
int arr[5] = { 1, 2, 3, 4, 5 };
size_t n = sizeof(arr)/sizeof(arr[0]);
int p = 3;
int K = 2;
int result;
result = insert(arr, n, p, K);
printf("Insert values: %d", result);
return 0;
}
</code></pre>
<p>However, I get the following error:</p>
<blockquote>
<p>zsh: segmentation fault ./insert</p>
</blockquote>
|
[
{
"answer_id": 74671333,
"author": "Marek Rozmus",
"author_id": 6738911,
"author_profile": "https://Stackoverflow.com/users/6738911",
"pm_score": 2,
"selected": true,
"text": "global setupTest.js global.TagCanvas = {\n Start: () => \"this is the mocked implementation\"\n}\n"
},
{
"answer_id": 74675071,
"author": "manou",
"author_id": 967216,
"author_profile": "https://Stackoverflow.com/users/967216",
"pm_score": 0,
"selected": false,
"text": "beforeAll setupTest.js //jest.config.js\nconst nextJest = require('next/jest');\n\nconst createJestConfig = nextJest({\n dir: './',\n});\n\n// Add any custom config to be passed to Jest\nconst customJestConfig = {\n moduleDirectories: ['node_modules', '<rootDir>/'],\n testEnvironment: 'jest-environment-jsdom',\n // Define setupTest file here\n setupFiles: ['<rootDir>/setupTest.js'],\n};\n\nmodule.exports = createJestConfig(customJestConfig);\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19136165/"
] |
74,666,402
|
<p>I am trying to concatenate data in QUERY formula from cell as shown in image
(<a href="https://i.stack.imgur.com/3EdUX.jpg" rel="nofollow noreferrer">https://i.stack.imgur.com/3EdUX.jpg</a>)
Formula is :=QUERY(CONCATENATE(A9,"!A2:D5"),"Select A,B")
picking data_range from another cell
how can I get it?</p>
<p>picking "data_range" from another cell
I want to "data_range" in query changeable</p>
|
[
{
"answer_id": 74671333,
"author": "Marek Rozmus",
"author_id": 6738911,
"author_profile": "https://Stackoverflow.com/users/6738911",
"pm_score": 2,
"selected": true,
"text": "global setupTest.js global.TagCanvas = {\n Start: () => \"this is the mocked implementation\"\n}\n"
},
{
"answer_id": 74675071,
"author": "manou",
"author_id": 967216,
"author_profile": "https://Stackoverflow.com/users/967216",
"pm_score": 0,
"selected": false,
"text": "beforeAll setupTest.js //jest.config.js\nconst nextJest = require('next/jest');\n\nconst createJestConfig = nextJest({\n dir: './',\n});\n\n// Add any custom config to be passed to Jest\nconst customJestConfig = {\n moduleDirectories: ['node_modules', '<rootDir>/'],\n testEnvironment: 'jest-environment-jsdom',\n // Define setupTest file here\n setupFiles: ['<rootDir>/setupTest.js'],\n};\n\nmodule.exports = createJestConfig(customJestConfig);\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17089511/"
] |
74,666,415
|
<p>I would like to use <code>@store.Name</code> in the <code>src="../Pandora.jpg"</code>.</p>
<p>At the moment my code is:</p>
<pre><code><img src="../Pandora.jpg" class="card-img-top" alt="@store.Name Logo">
</code></pre>
<p>but I want something like:</p>
<pre><code><img src="../@store.Name.jpg" class="card-img-top" alt="@store.Name Logo">
</code></pre>
|
[
{
"answer_id": 74666443,
"author": "odnualam",
"author_id": 10875688,
"author_profile": "https://Stackoverflow.com/users/10875688",
"pm_score": 0,
"selected": false,
"text": "<img src=\"../' + @store.Name + '.jpg\" class=\"card-img-top\" alt=\"@store.Name Logo\">\n <img src=\"../${@store.Name}.jpg\" class=\"card-img-top\" alt=\"@store.Name Logo\">\n"
},
{
"answer_id": 74666616,
"author": "Yong Shun",
"author_id": 8017690,
"author_profile": "https://Stackoverflow.com/users/8017690",
"pm_score": 3,
"selected": true,
"text": "@() .jpg <img src=\"../@(store.Name).jpg\" class=\"card-img-top\" alt=\"@store.Name Logo\">\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4049591/"
] |
74,666,424
|
<h1>Problem</h1>
<p>First off, I am going to clarify that this question is not a duplicate of <a href="https://stackoverflow.com/questions/2536379/difference-in-months-between-two-dates-in-javascript">Difference in months between two dates in javascript</a> or <a href="https://stackoverflow.com/questions/4312825/javascript-month-difference?noredirect=1&lq=1">javascript month difference</a></p>
<p>My question is specifically about getting the <em>months</em> in between two dates, not the <em>number</em> of months.</p>
<h1>Expected Results</h1>
<p>So If <code>date1</code> is 11/01/2022 (mm/dd/yyyy) and <code>date2</code> is 02/20/2023, it should output an array of months including the month of <code>date1</code> and <code>date2</code> like <code>["November", "December", "January", "February"]</code>. I need to know how to return the actual months between two dates, not the number of months. Can somebody explain what would be the way to do that?</p>
|
[
{
"answer_id": 74666443,
"author": "odnualam",
"author_id": 10875688,
"author_profile": "https://Stackoverflow.com/users/10875688",
"pm_score": 0,
"selected": false,
"text": "<img src=\"../' + @store.Name + '.jpg\" class=\"card-img-top\" alt=\"@store.Name Logo\">\n <img src=\"../${@store.Name}.jpg\" class=\"card-img-top\" alt=\"@store.Name Logo\">\n"
},
{
"answer_id": 74666616,
"author": "Yong Shun",
"author_id": 8017690,
"author_profile": "https://Stackoverflow.com/users/8017690",
"pm_score": 3,
"selected": true,
"text": "@() .jpg <img src=\"../@(store.Name).jpg\" class=\"card-img-top\" alt=\"@store.Name Logo\">\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13944742/"
] |
74,666,426
|
<p>Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_').</p>
<p>Examples:</p>
<ul>
<li>'abc' => ['ab', 'c_']</li>
<li>'abcdef' => ['ab', 'cd', 'ef']</li>
</ul>
<p><a href="https://prnt.sc/E2sdtceLtkmF" rel="nofollow noreferrer">https://prnt.sc/E2sdtceLtkmF</a></p>
<pre><code>
# **My Code:**
</code></pre>
<pre><code>def solution(s):
```n = 2
```sp = [s[index : index + n] for index in range(0, len(s), n)]
```if len(sp[-1]) == 1:
sp[-1] = sp[-1] + "_"
```return sp
```else:
```return sp
</code></pre>
<h1><strong>and i geting this error:</strong></h1>
<pre><code>Traceback (most recent call last):
File "/workspace/default/tests.py", line 13, in <module>
test.assert_equals(solution(inp), exp)
File "/workspace/default/solution.py", line 5, in solution
if len(sp[-1]) == 1:
IndexError: list index out of range
</code></pre>
<p><strong># pls someone help</strong></p>
<pre><code></code></pre>
|
[
{
"answer_id": 74666443,
"author": "odnualam",
"author_id": 10875688,
"author_profile": "https://Stackoverflow.com/users/10875688",
"pm_score": 0,
"selected": false,
"text": "<img src=\"../' + @store.Name + '.jpg\" class=\"card-img-top\" alt=\"@store.Name Logo\">\n <img src=\"../${@store.Name}.jpg\" class=\"card-img-top\" alt=\"@store.Name Logo\">\n"
},
{
"answer_id": 74666616,
"author": "Yong Shun",
"author_id": 8017690,
"author_profile": "https://Stackoverflow.com/users/8017690",
"pm_score": 3,
"selected": true,
"text": "@() .jpg <img src=\"../@(store.Name).jpg\" class=\"card-img-top\" alt=\"@store.Name Logo\">\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20367266/"
] |
74,666,428
|
<p>Is this sample in a correct format based on JSON API specifications? In another word can we have in <strong>attributes</strong> an array?</p>
<pre><code>{
"meta": {
},
"links": {
"self": ""
},
"jsonapi": {
"version": "",
"meta": {
}
},
"data": {
"type": "typeof(class)",
"id": "string",
"attributes": [
{
"item1": "Value1",
"item2": "Value2",
"item3": "Value3"
}
],
"links": {
"self": ""
}
}
}
</code></pre>
<p>I am not sure even after reading that (<a href="https://jsonapi.org/format/#document-resource-object-attributes" rel="nofollow noreferrer">link</a>) If correct how can I Deserialize it I am using JSONAPISerializer package in C#</p>
|
[
{
"answer_id": 74666443,
"author": "odnualam",
"author_id": 10875688,
"author_profile": "https://Stackoverflow.com/users/10875688",
"pm_score": 0,
"selected": false,
"text": "<img src=\"../' + @store.Name + '.jpg\" class=\"card-img-top\" alt=\"@store.Name Logo\">\n <img src=\"../${@store.Name}.jpg\" class=\"card-img-top\" alt=\"@store.Name Logo\">\n"
},
{
"answer_id": 74666616,
"author": "Yong Shun",
"author_id": 8017690,
"author_profile": "https://Stackoverflow.com/users/8017690",
"pm_score": 3,
"selected": true,
"text": "@() .jpg <img src=\"../@(store.Name).jpg\" class=\"card-img-top\" alt=\"@store.Name Logo\">\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4502841/"
] |
74,666,435
|
<p>I am making a discord bot in which an auction could take place.So I want someone to bid only once unless someone bids after him/her.</p>
<pre><code>`async def bid(ctx):
embed1=discord.Embed(description= f'Bid has been placed by {ctx.author}', title='bid placed')
await ctx.send(embed=embed1)
`
</code></pre>
<p>That's what I have so far made.</p>
|
[
{
"answer_id": 74666765,
"author": "Raymus",
"author_id": 20487456,
"author_profile": "https://Stackoverflow.com/users/20487456",
"pm_score": 2,
"selected": true,
"text": "bidderid = 0 #this will reset whenever your bot restarts\n@client.command()\nasync def bid(ctx):\n global bidderid\n if ctx.author.id != bidderid: #if it is not the same bidder\n bidderid = ctx.author.id\n embed1=discord.Embed(description= f'Bid has been placed by {ctx.author}', title='bid placed')\n await ctx.send(embed=embed1)\n else: #if it is the same bidder\n await ctx.send('You cannot bid twice in a row!') #replace with whatever message\n ctx.author"
},
{
"answer_id": 74666773,
"author": "Begging",
"author_id": 16606223,
"author_profile": "https://Stackoverflow.com/users/16606223",
"pm_score": 2,
"selected": false,
"text": "# create an empty list to store user IDs\nuser_ids = []\n\nasync def bid(ctx):\n # check if the user's ID is in the list of user IDs\n if ctx.author.id in user_ids:\n # if the user has already placed a bid, send a message to let them know\n embed1 = discord.Embed(description= f'{ctx.author}, you have already placed a bid', title='bid not placed')\n await ctx.send(embed=embed1)\n else:\n # if the user has not placed a bid, add their ID to the list of user IDs and send a message to confirm their bid\n user_ids.append(ctx.author.id)\n embed1 = discord.Embed(description= f'Bid has been placed by {ctx.author}', title='bid placed')\n await ctx.send(embed=embed1)\n\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20674140/"
] |
74,666,460
|
<p>I am trying to use the <code>@Valid</code> and <code>@NotBlank</code> annotations in my spring boot project within IntelliJ IDEA 2022.2.3 (Community Edition)
Build #IC-222.4345.14, built on October 5, 2022</p>
<p>I have added dependency like below in my project pom.xml</p>
<pre><code><dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<scope>test</scope>
</dependency>
</code></pre>
<p>In my entity class i have added <code>@NotBlank</code> annotation as below</p>
<pre><code>@NotBlank(message = "Please add the department name")
private String departmentName;
</code></pre>
<p>In my controller class i have added <code>@Valid</code> annotation as well</p>
<pre><code>@PostMapping("/departments")
public Department saveDepartment(@Valid @RequestBody Department department)
{
return departmentService.saveDepartment(department);
}
</code></pre>
<p>Even with all this i don't think the validation APIs are working.</p>
<p>My spring boot version is</p>
<pre><code><parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
</code></pre>
<p>Ideally i should be getting validation error if i don't pass the department name in my POST request BUT i never get any error with blank department name where my annotations are present.</p>
<p>I have tried various suggested solutions like closing and restarting IntelliJ Idea, Rebuilt the project. Also, I have tried invalidating the cache. NOTHING IS WORKING !!! The dependencies also seem to be all GOOD.</p>
<p>What else I could try?</p>
|
[
{
"answer_id": 74667661,
"author": "vanOekel",
"author_id": 3080094,
"author_profile": "https://Stackoverflow.com/users/3080094",
"pm_score": 2,
"selected": false,
"text": "test spring-boot-starter-validation mvn clean test"
},
{
"answer_id": 74668186,
"author": "Helena",
"author_id": 18105313,
"author_profile": "https://Stackoverflow.com/users/18105313",
"pm_score": 0,
"selected": false,
"text": "IntelliJ IDEA 2022.2.4 (Community Edition)\nBuild #IC-222.4459.24, built on November 22, 2022\nRuntime version: 17.0.5+7-b469.71 amd64\nVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o.\nWindows 11 10.0\nGC: G1 Young Generation, G1 Old Generation\nMemory: 1004M\nCores: 8\n\nKotlin: 222-1.7.10-release-334-IJ4459.24\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18105313/"
] |
74,666,461
|
<p>So I am working on an online shop as a practice
I have imported products data and wanna make pagination. On a page it will be 12 products like so
<a href="https://i.stack.imgur.com/hxxmw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hxxmw.png" alt="enter image description here" /></a></p>
<p>I have this kind of code, but I don't understand why there is an infinite loop in useEffect and how to fix this
The error is: "Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render."
I can rid of products in dependancy, but not sure it's the way</p>
<pre><code>import React, {useState, useEffect} from "react";
import data from './products.json'
import Product from "./components/Product/Product";
const PRODUCTS_PER_PAGE = 12
export const Shop = () => {
const [products, setProducts] = useState(data.products)
const [currentPage, setCurrentPage] = useState(1)
const firstIndex = (currentPage - 1) * PRODUCTS_PER_PAGE
const lastIndex = firstIndex + PRODUCTS_PER_PAGE
const totalPages = products.length / PRODUCTS_PER_PAGE
useEffect(() => {
const slicedProducts = products.slice(firstIndex,lastIndex)
setProducts(slicedProducts)
console.log(slicedProducts)
}, [currentPage, products])
return (
<div className="products">
{
products.map((product) => (
<Product product={product}/>))
}
</div>
)
}
</code></pre>
|
[
{
"answer_id": 74666475,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 1,
"selected": false,
"text": "products useEffect(() => {\n setProducts(prods => prods.slice(firstIndex,lastIndex))\n}, [currentPage])\n useEffect import React, {useState, useEffect} from \"react\";\nimport data from './products.json'\nimport Product from \"./components/Product/Product\";\n\nconst PRODUCTS_PER_PAGE = 12\n\nexport const Shop = () => {\n const [products, setProducts] = useState(data.products)\n const [currentPage, setCurrentPage] = useState(1)\n\n const firstIndex = (currentPage - 1) * PRODUCTS_PER_PAGE\n const lastIndex = firstIndex + PRODUCTS_PER_PAGE\n const totalPages = products.length / PRODUCTS_PER_PAGE\n\n return (\n <div className=\"products\">\n {\n products.slice(firstIndex,lastIndex).map((product) => (\n <Product product={product}/>))\n }\n </div>\n )\n}\n"
},
{
"answer_id": 74666668,
"author": "Azzy",
"author_id": 2122822,
"author_profile": "https://Stackoverflow.com/users/2122822",
"pm_score": 0,
"selected": false,
"text": "// if you dont want to inlcude currentPage as a dependency and trigger another calculation\n// const currentPageRef = useRef(currentPage);\n// currentPageRef.current = currentPage;\nconst mappedProducts = useMemo(() => {\n\n const firstIndex = (currentPage - 1) * PRODUCTS_PER_PAGE\n const lastIndex = firstIndex + PRODUCTS_PER_PAGE\n\n const slicedProducts = products.slice(firstIndex, lastIndex)\n return slicedProducts\n\n}, [products, currentPage])\n\nreturn (\n <div className=\"products\">\n {\n // should this be mappedProducts?.map(product => \n mappedProducts.slice(firstIndex,lastIndex).map((product) => (\n <Product product={product}/>))\n }\n </div>\n)\n"
},
{
"answer_id": 74666679,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 0,
"selected": false,
"text": "import React, {useState, useEffect, useRef} from \"react\";\nimport data from './products.json'\nimport Product from \"./components/Product/Product\";\n\nconst PRODUCTS_PER_PAGE = 12\n\nexport const Shop = () => {\n const [products, setProducts] = useState(data.products);\n const [currentPage, setCurrentPage] = useState(1);\n\n const previousProductsRef = useRef(data.products);\n const previousPageRef = useRef(1);\n\n const firstIndex = (currentPage - 1) * PRODUCTS_PER_PAGE\n const lastIndex = firstIndex + PRODUCTS_PER_PAGE\n const totalPages = products.length / PRODUCTS_PER_PAGE\n\n\n useEffect(() => {\n if(JSON.stringify(previousProductsRef.current) !== JSON.stringify(products) || previousPageRef.current !== currentPage) {\n const slicedProducts = products.slice(firstIndex,lastIndex);\n previousProductsRef.current = slicedProducts;\n previousPageRef.current = currentPage;\n setProducts(slicedProducts);\n console.log(slicedProducts);\n }\n }, [currentPage, products])\n\n return (\n <div className=\"products\">\n {\n products.map((product) => (\n <Product product={product}/>))\n }\n </div>\n )\n}\n const productsArray = useMemo(() => {\n const firstIndex = (currentPage - 1) * PRODUCTS_PER_PAGE;\n const lastIndex = firstIndex + PRODUCTS_PER_PAGE;\n\n const slicedProducts = products.slice(firstIndex, lastIndex);\n return slicedProducts;\n\n}, [currentPage, products]);\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19501234/"
] |
74,666,511
|
<p>I have a script that uses ts-node:</p>
<pre><code>#!/usr/binenv ts-node
const top: number[] = [];
</code></pre>
<p>but <code>tsc</code> complains:</p>
<pre><code>top3.ts(3,7): error TS2451: Cannot redeclare block-scoped variable 'top'.
</code></pre>
<p>because apparently <code>top</code> is a global variable in browsers.</p>
<p>I've installed <code>@types/node</code> and my <code>tsconfig.json</code> reads:</p>
<pre><code>{
"compilerOptions": {
"noImplicitAny": true,
"target": "es6",
"types": ["node"],
}
}
</code></pre>
<p>so I can refer to node builtins like <code>process</code>.</p>
<p>How do I configure <code>tsc</code> so that it does not include browser builtins, but only pure ECMAScript + node.js builtins?</p>
|
[
{
"answer_id": 74666475,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 1,
"selected": false,
"text": "products useEffect(() => {\n setProducts(prods => prods.slice(firstIndex,lastIndex))\n}, [currentPage])\n useEffect import React, {useState, useEffect} from \"react\";\nimport data from './products.json'\nimport Product from \"./components/Product/Product\";\n\nconst PRODUCTS_PER_PAGE = 12\n\nexport const Shop = () => {\n const [products, setProducts] = useState(data.products)\n const [currentPage, setCurrentPage] = useState(1)\n\n const firstIndex = (currentPage - 1) * PRODUCTS_PER_PAGE\n const lastIndex = firstIndex + PRODUCTS_PER_PAGE\n const totalPages = products.length / PRODUCTS_PER_PAGE\n\n return (\n <div className=\"products\">\n {\n products.slice(firstIndex,lastIndex).map((product) => (\n <Product product={product}/>))\n }\n </div>\n )\n}\n"
},
{
"answer_id": 74666668,
"author": "Azzy",
"author_id": 2122822,
"author_profile": "https://Stackoverflow.com/users/2122822",
"pm_score": 0,
"selected": false,
"text": "// if you dont want to inlcude currentPage as a dependency and trigger another calculation\n// const currentPageRef = useRef(currentPage);\n// currentPageRef.current = currentPage;\nconst mappedProducts = useMemo(() => {\n\n const firstIndex = (currentPage - 1) * PRODUCTS_PER_PAGE\n const lastIndex = firstIndex + PRODUCTS_PER_PAGE\n\n const slicedProducts = products.slice(firstIndex, lastIndex)\n return slicedProducts\n\n}, [products, currentPage])\n\nreturn (\n <div className=\"products\">\n {\n // should this be mappedProducts?.map(product => \n mappedProducts.slice(firstIndex,lastIndex).map((product) => (\n <Product product={product}/>))\n }\n </div>\n)\n"
},
{
"answer_id": 74666679,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 0,
"selected": false,
"text": "import React, {useState, useEffect, useRef} from \"react\";\nimport data from './products.json'\nimport Product from \"./components/Product/Product\";\n\nconst PRODUCTS_PER_PAGE = 12\n\nexport const Shop = () => {\n const [products, setProducts] = useState(data.products);\n const [currentPage, setCurrentPage] = useState(1);\n\n const previousProductsRef = useRef(data.products);\n const previousPageRef = useRef(1);\n\n const firstIndex = (currentPage - 1) * PRODUCTS_PER_PAGE\n const lastIndex = firstIndex + PRODUCTS_PER_PAGE\n const totalPages = products.length / PRODUCTS_PER_PAGE\n\n\n useEffect(() => {\n if(JSON.stringify(previousProductsRef.current) !== JSON.stringify(products) || previousPageRef.current !== currentPage) {\n const slicedProducts = products.slice(firstIndex,lastIndex);\n previousProductsRef.current = slicedProducts;\n previousPageRef.current = currentPage;\n setProducts(slicedProducts);\n console.log(slicedProducts);\n }\n }, [currentPage, products])\n\n return (\n <div className=\"products\">\n {\n products.map((product) => (\n <Product product={product}/>))\n }\n </div>\n )\n}\n const productsArray = useMemo(() => {\n const firstIndex = (currentPage - 1) * PRODUCTS_PER_PAGE;\n const lastIndex = firstIndex + PRODUCTS_PER_PAGE;\n\n const slicedProducts = products.slice(firstIndex, lastIndex);\n return slicedProducts;\n\n}, [currentPage, products]);\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4969945/"
] |
74,666,546
|
<p>I have recently explored handling JSON data with the org.json library and all went well.
Now I started a bigger Maven project, for which I intend to use the Jackson libraries in stead.
Sadly, it does not seem to work for me. I wanted to try out the ObjectMapper class, that VScode autocompleted for me, which also automatically adds the required import:</p>
<pre><code>import com.fasterxml.jackson.databind.ObjectMapper;
</code></pre>
<p>However, I also immediately get an error on that line:
"<strong>The type com.fasterxml.jackson.databind.ObjectMapper is not accessible Java (16778666)</strong>"</p>
<p>I have added the necessary dependencies to my pom.xml file like so:</p>
<pre><code><dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>13</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.14.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.14.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.14.0</version>
</dependency>
</dependencies>
</code></pre>
<p>Am I missing something? Are there any other steps that I should have taken?</p>
|
[
{
"answer_id": 74666475,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 1,
"selected": false,
"text": "products useEffect(() => {\n setProducts(prods => prods.slice(firstIndex,lastIndex))\n}, [currentPage])\n useEffect import React, {useState, useEffect} from \"react\";\nimport data from './products.json'\nimport Product from \"./components/Product/Product\";\n\nconst PRODUCTS_PER_PAGE = 12\n\nexport const Shop = () => {\n const [products, setProducts] = useState(data.products)\n const [currentPage, setCurrentPage] = useState(1)\n\n const firstIndex = (currentPage - 1) * PRODUCTS_PER_PAGE\n const lastIndex = firstIndex + PRODUCTS_PER_PAGE\n const totalPages = products.length / PRODUCTS_PER_PAGE\n\n return (\n <div className=\"products\">\n {\n products.slice(firstIndex,lastIndex).map((product) => (\n <Product product={product}/>))\n }\n </div>\n )\n}\n"
},
{
"answer_id": 74666668,
"author": "Azzy",
"author_id": 2122822,
"author_profile": "https://Stackoverflow.com/users/2122822",
"pm_score": 0,
"selected": false,
"text": "// if you dont want to inlcude currentPage as a dependency and trigger another calculation\n// const currentPageRef = useRef(currentPage);\n// currentPageRef.current = currentPage;\nconst mappedProducts = useMemo(() => {\n\n const firstIndex = (currentPage - 1) * PRODUCTS_PER_PAGE\n const lastIndex = firstIndex + PRODUCTS_PER_PAGE\n\n const slicedProducts = products.slice(firstIndex, lastIndex)\n return slicedProducts\n\n}, [products, currentPage])\n\nreturn (\n <div className=\"products\">\n {\n // should this be mappedProducts?.map(product => \n mappedProducts.slice(firstIndex,lastIndex).map((product) => (\n <Product product={product}/>))\n }\n </div>\n)\n"
},
{
"answer_id": 74666679,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 0,
"selected": false,
"text": "import React, {useState, useEffect, useRef} from \"react\";\nimport data from './products.json'\nimport Product from \"./components/Product/Product\";\n\nconst PRODUCTS_PER_PAGE = 12\n\nexport const Shop = () => {\n const [products, setProducts] = useState(data.products);\n const [currentPage, setCurrentPage] = useState(1);\n\n const previousProductsRef = useRef(data.products);\n const previousPageRef = useRef(1);\n\n const firstIndex = (currentPage - 1) * PRODUCTS_PER_PAGE\n const lastIndex = firstIndex + PRODUCTS_PER_PAGE\n const totalPages = products.length / PRODUCTS_PER_PAGE\n\n\n useEffect(() => {\n if(JSON.stringify(previousProductsRef.current) !== JSON.stringify(products) || previousPageRef.current !== currentPage) {\n const slicedProducts = products.slice(firstIndex,lastIndex);\n previousProductsRef.current = slicedProducts;\n previousPageRef.current = currentPage;\n setProducts(slicedProducts);\n console.log(slicedProducts);\n }\n }, [currentPage, products])\n\n return (\n <div className=\"products\">\n {\n products.map((product) => (\n <Product product={product}/>))\n }\n </div>\n )\n}\n const productsArray = useMemo(() => {\n const firstIndex = (currentPage - 1) * PRODUCTS_PER_PAGE;\n const lastIndex = firstIndex + PRODUCTS_PER_PAGE;\n\n const slicedProducts = products.slice(firstIndex, lastIndex);\n return slicedProducts;\n\n}, [currentPage, products]);\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20138458/"
] |
74,666,548
|
<p>I would like to know if there is a faster way to print all the not empty elements of a string list in Java.</p>
<p>Currently, this is my code and it works, but I would like to know if there is another, shorter way to do it. That means without creating a "cloned list" from which we removed all the empty element (as we must not edit the original list "strings")</p>
<pre><code>List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
//get count of empty string
int countEmptyStr = (int) strings.stream().filter(string -> string.isEmpty()).count();
System.out.println("Number of empty strings:" + countEmptyStr );
//get count of no empty string
int countNoEmptyStr = (int) strings.stream().filter(string -> !string.isEmpty()).count();
System.out.println("Number of no-empty strings:" + countNoEmptyStr );
//print only no empty string from the list
List<String> stringsRmvd = new ArrayList<String>(strings);
stringsRmvd.removeAll(Arrays.asList("", null));
System.out.println("Print only no empty string from the list:" + stringsRmvd);
</code></pre>
<p>And we get in the output (as expected):</p>
<pre><code>Number of empty strings:2
Number of no-empty strings:5
Print only no empty string from the list:[abc, bc, efg, abcd, jkl]
</code></pre>
|
[
{
"answer_id": 74666586,
"author": "markspace",
"author_id": 2338547,
"author_profile": "https://Stackoverflow.com/users/2338547",
"pm_score": 2,
"selected": false,
"text": "filter filter(string -> !string.isEmpty()).toList()\n System.out.println( \"Print only non-empty string from the list:\" \n + strings.stream()\n .filter(string -> !string.isEmpty())\n .toList() );\n"
},
{
"answer_id": 74666595,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 2,
"selected": true,
"text": "List<String> strings = Arrays.asList(\"abc\", \"\", \"bc\", \"efg\", \"abcd\", \"\", \"jkl\");\n \nstrings.stream()\n .filter(str -> !str.isEmpty()) // retain the string that matches the predicate (i.e. not empty)\n .forEach(System.out::println);\n abc\nbc\nefg\nabcd\njkl\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19175002/"
] |
74,666,555
|
<p>I am using Joomla version 3.10 and after upgrading the php version from 7.4 to 8.0, I received this error.</p>
<p><code>Fatal error: Unparenthesized </code>a ? b : c ? d : e<code>is not supported. Use either</code>(a ? b : c) ? d : e<code>or</code>a ? b : (c ? d : e)<code> in /home/public_html/language/fa-IR/fa-IR.localise.php on line 115</code></p>
<p><strong>I put the source code of fa-IR.localise.php on line 115 below:</strong></p>
<pre><code>`if (strpos($return, self::MONTH_LENGTH) !== false) {
$return = str_replace(self::MONTH_LENGTH, $m < 7 ? 31 : $m < 12 ? 30 : self::leap_persian($y) ? 30 : 29 , $return);`
</code></pre>
<p>Thank you for helping me.</p>
<p>When I go back to php version 7.4, the problem is solved</p>
|
[
{
"answer_id": 74666602,
"author": "MaZzIMo24",
"author_id": 15222409,
"author_profile": "https://Stackoverflow.com/users/15222409",
"pm_score": 1,
"selected": true,
"text": "$return = str_replace(self::MONTH_LENGTH, ($m < 7 ? 31 : ($m < 12 ? 30 : (self::leap_persian($y) ? 30 : 29) ) ) , $return);\n"
},
{
"answer_id": 74666676,
"author": "Begging",
"author_id": 16606223,
"author_profile": "https://Stackoverflow.com/users/16606223",
"pm_score": 1,
"selected": false,
"text": "if (strpos($return, self::MONTH_LENGTH) !== false) {\n $return = str_replace(\n self::MONTH_LENGTH,\n ($m < 7 ? 31 : $m < 12 ? 30 : self::leap_persian($y) ? 30 : 29),\n $return\n );\n}\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15774314/"
] |
74,666,568
|
<p>The result should have square brackets enclosing the elements of list which are numbers , these numbers should not be enclosed into quotes.</p>
<p>i tried to do so with split function and for loop but was not able to get my desired result. i am expecting the answer.</p>
|
[
{
"answer_id": 74666602,
"author": "MaZzIMo24",
"author_id": 15222409,
"author_profile": "https://Stackoverflow.com/users/15222409",
"pm_score": 1,
"selected": true,
"text": "$return = str_replace(self::MONTH_LENGTH, ($m < 7 ? 31 : ($m < 12 ? 30 : (self::leap_persian($y) ? 30 : 29) ) ) , $return);\n"
},
{
"answer_id": 74666676,
"author": "Begging",
"author_id": 16606223,
"author_profile": "https://Stackoverflow.com/users/16606223",
"pm_score": 1,
"selected": false,
"text": "if (strpos($return, self::MONTH_LENGTH) !== false) {\n $return = str_replace(\n self::MONTH_LENGTH,\n ($m < 7 ? 31 : $m < 12 ? 30 : self::leap_persian($y) ? 30 : 29),\n $return\n );\n}\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20674167/"
] |
74,666,590
|
<p>I found the problem is It cannot close this window. But it can open the MainWindow.
pls help
<a href="https://i.stack.imgur.com/xZ6qc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xZ6qc.png" alt="enter image description here" /></a>
Code in button</p>
<pre><code> private void LoginBtn_Click(object sender, RoutedEventArgs e)
{
MainWindow MainView = new MainWindow();
MainView.Show();
AuthWindow AuthView = new AuthWindow();
AuthView.Close();
}
</code></pre>
<p>I want to press the button inside the page and close that window and open another window.</p>
|
[
{
"answer_id": 74666602,
"author": "MaZzIMo24",
"author_id": 15222409,
"author_profile": "https://Stackoverflow.com/users/15222409",
"pm_score": 1,
"selected": true,
"text": "$return = str_replace(self::MONTH_LENGTH, ($m < 7 ? 31 : ($m < 12 ? 30 : (self::leap_persian($y) ? 30 : 29) ) ) , $return);\n"
},
{
"answer_id": 74666676,
"author": "Begging",
"author_id": 16606223,
"author_profile": "https://Stackoverflow.com/users/16606223",
"pm_score": 1,
"selected": false,
"text": "if (strpos($return, self::MONTH_LENGTH) !== false) {\n $return = str_replace(\n self::MONTH_LENGTH,\n ($m < 7 ? 31 : $m < 12 ? 30 : self::leap_persian($y) ? 30 : 29),\n $return\n );\n}\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17217152/"
] |
74,666,644
|
<p>I am new to programming. Trying to open Gmail using this code snippet. But problem is putExtra(Intent.EXTRA_EMAIL, strTo) does not give any result. putExtra(Intent.EXTRA_SUBJECT, strSubject) works fine. I tried to pass array also but result is same. Could someone please give suggestions for this email sender using kotlin.</p>
<pre><code>val etTo = findViewById<EditText>(R.id.etTo)
val etSubject = findViewById<EditText>(R.id.etSubject)
val emailBtn = findViewById<Button>(R.id.emailBtn)
emailBtn.setOnClickListener {
val strTo = etTo.text.toString()
val strSubject = etSubject.text.toString()
val intent = Intent(Intent.ACTION_SENDTO).apply {
data = Uri.parse("mailto")
putExtra(Intent.EXTRA_EMAIL, strTo)
putExtra(Intent.EXTRA_SUBJECT, strSubject)
startActivity(intent,)
composeEmail("$strTo", "$strSubject")
}
</code></pre>
<p>}</p>
<pre><code> fun composeEmail(addresses: String, subject: String) {
val intent = Intent(Intent.ACTION_SENDTO).apply {
data = Uri.parse("mailto:")
putExtra(Intent.EXTRA_EMAIL, addresses)
putExtra(Intent.EXTRA_SUBJECT, subject)
}
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent)
}
}
</code></pre>
<p>I tried using array.</p>
<p>fun composeEmail(addresses: Array, subject: String)</p>
|
[
{
"answer_id": 74666661,
"author": "Begging",
"author_id": 16606223,
"author_profile": "https://Stackoverflow.com/users/16606223",
"pm_score": 2,
"selected": false,
"text": "val intent = Intent(Intent.ACTION_SEND).apply {\n type = \"message/rfc822\"\n putExtra(Intent.EXTRA_EMAIL, arrayOf(strTo))\n putExtra(Intent.EXTRA_SUBJECT, strSubject)\n}\nstartActivity(intent)\n"
},
{
"answer_id": 74666665,
"author": "chivalrous-nerd",
"author_id": 7347835,
"author_profile": "https://Stackoverflow.com/users/7347835",
"pm_score": 0,
"selected": false,
"text": "putExtra(Intent.EXTRA_EMAIL, strTo) Intent.EXTRA_EMAIL val emailBtn = findViewById<Button>(R.id.emailBtn)\n\nemailBtn.setOnClickListener {\n\n val strTo = etTo.text.toString()\n val strSubject = etSubject.text.toString()\n\n // Create an array of strings with the email address entered in the etTo EditText\n val emailAddresses = arrayOf(strTo)\n\n // Use the array of email addresses to pass to putExtra()\n val intent = Intent(Intent.ACTION_SENDTO).apply {\n data = Uri.parse(\"mailto\")\n putExtra(Intent.EXTRA_EMAIL, emailAddresses)\n putExtra(Intent.EXTRA_SUBJECT, strSubject)\n startActivity(intent,)\n }\n composeEmail(emailAddresses, \"$strSubject\")\n}\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5117918/"
] |
74,666,674
|
<p>I can use an unconstrained type paramter:</p>
<pre><code>interface State<V>
</code></pre>
<p>or I can use a constrained type parameter:</p>
<pre><code>interface State<V: Any>
</code></pre>
<p>This seems to be the same, because <a href="https://kotlinlang.org/docs/basic-types.html" rel="nofollow noreferrer">"In Kotlin, everything is an object [...]"</a>. But this may be deceptive. What consequences does it have, if I favor the second instead of the first?</p>
|
[
{
"answer_id": 74667104,
"author": "hassan bazai",
"author_id": 14279755,
"author_profile": "https://Stackoverflow.com/users/14279755",
"pm_score": 0,
"selected": false,
"text": "Any Any"
},
{
"answer_id": 74668459,
"author": "broot",
"author_id": 448875,
"author_profile": "https://Stackoverflow.com/users/448875",
"pm_score": 1,
"selected": false,
"text": "Any Any? interface State<V> interface State<V : Any?> interface State<V : Any> T interface State<V : Any>\n\nclass StringState : State<String> // ok\nclass NullableStringState : State<String?> // compile error\n Any?"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402322/"
] |
74,666,678
|
<p>how to convert json file data to string in bash shell script?
i have below petstore swagger file (<a href="https://petstore.swagger.io/v2/swagger.json" rel="nofollow noreferrer">https://petstore.swagger.io/v2/swagger.json</a>)
in json format.</p>
<p>i have converted this json file into string with backspaces characters \ needed for one operation using this site <a href="https://jsontostring.com/" rel="nofollow noreferrer">https://jsontostring.com/</a> .</p>
<p>i have tried jq tool to achieve this, didn't got the result and perhaps it will not come using jq tool.</p>
<p>How can we convert this same petstore swagger json file into string with below expected output in linux or bash shell script ?</p>
<pre><code>{"swagger":"2.0","info":{"description":"This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.","version":"1.0.6","title":"Swagger Petstore","termsOfService":"http://swagger.io/terms/","contact":{"email":"apiteam@swagger.io"},"license":{"name":"Apache 2.0","url":"http://www.apache.org/licenses/LICENSE-2.0.html"}},"host":"petstore.swagger.io","basePath":"/v2","tags":[{"name":"pet","description":"Everything about your Pets","externalDocs":{"description":"Find out more","url":"http://swagger.io"}},{"name":"store","description":"Access to Petstore orders"},{"name":"user","description":"Operations about user","externalDocs":{"description":"Find out more about our store","url":"http://swagger.io"}}],"schemes":["https","http"],"paths":{"/pet/{petId}/uploadImage":{"post":{"tags":["pet"],"summary":"uploads an image","description":"","operationId":"uploadFile","consumes":["multipart/form-data"],"produces":["application/json"],"parameters":[{"name":"petId","in":"path","description":"ID of pet to update","required":true,"type":"integer","format":"int64"},{"name":"additionalMetadata","in":"formData","description":"Additional data to pass to server","required":false,"type":"string"},{"name":"file","in":"formData","description":"file to upload","required":false,"type":"file"}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/ApiResponse"}}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/pet":{"post":{"tags":["pet"],"summary":"Add a new pet to the store","description":"","operationId":"addPet","consumes":["application/json","application/xml"],"produces":["application/json","application/xml"],"parameters":[{"in":"body","name":"body","description":"Pet object that needs to be added to the store","required":true,"schema":{"$ref":"#/definitions/Pet"}}],"responses":{"405":{"description":"Invalid input"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]},"put":{"tags":["pet"],"summary":"Update an existing pet","description":"","operationId":"updatePet","consumes":["application/json","application/xml"],"produces":["application/json","application/xml"],"parameters":[{"in":"body","name":"body","description":"Pet object that needs to be added to the store","required":true,"schema":{"$ref":"#/definitions/Pet"}}],"responses":{"400":{"description":"Invalid ID supplied"},"404":{"description":"Pet not found"},"405":{"description":"Validation exception"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/pet/findByStatus":{"get":{"tags":["pet"],"summary":"Finds Pets by status","description":"Multiple status values can be provided with comma separated strings","operationId":"findPetsByStatus","produces":["application/json","application/xml"],"parameters":[{"name":"status","in":"query","description":"Status values that need to be considered for filter","required":true,"type":"array","items":{"type":"string","enum":["available","pending","sold"],"default":"available"},"collectionFormat":"multi"}],"responses":{"200":{"description":"successful operation","schema":{"type":"array","items":{"$ref":"#/definitions/Pet"}}},"400":{"description":"Invalid status value"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/pet/findByTags":{"get":{"tags":["pet"],"summary":"Finds Pets by tags","description":"Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.","operationId":"findPetsByTags","produces":["application/json","application/xml"],"parameters":[{"name":"tags","in":"query","description":"Tags to filter by","required":true,"type":"array","items":{"type":"string"},"collectionFormat":"multi"}],"responses":{"200":{"description":"successful operation","schema":{"type":"array","items":{"$ref":"#/definitions/Pet"}}},"400":{"description":"Invalid tag value"}},"security":[{"petstore_auth":["write:pets","read:pets"]}],"deprecated":true}},"/pet/{petId}":{"get":{"tags":["pet"],"summary":"Find pet by ID","description":"Returns a single pet","operationId":"getPetById","produces":["application/json","application/xml"],"parameters":[{"name":"petId","in":"path","description":"ID of pet to return","required":true,"type":"integer","format":"int64"}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/Pet"}},"400":{"description":"Invalid ID supplied"},"404":{"description":"Pet not found"}},"security":[{"api_key":[]}]},"post":{"tags":["pet"],"summary":"Updates a pet in the store with form data","description":"","operationId":"updatePetWithForm","consumes":["application/x-www-form-urlencoded"],"produces":["application/json","application/xml"],"parameters":[{"name":"petId","in":"path","description":"ID of pet that needs to be updated","required":true,"type":"integer","format":"int64"},{"name":"name","in":"formData","description":"Updated name of the pet","required":false,"type":"string"},{"name":"status","in":"formData","description":"Updated status of the pet","required":false,"type":"string"}],"responses":{"405":{"description":"Invalid input"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]},"delete":{"tags":["pet"],"summary":"Deletes a pet","description":"","operationId":"deletePet","produces":["application/json","application/xml"],"parameters":[{"name":"api_key","in":"header","required":false,"type":"string"},{"name":"petId","in":"path","description":"Pet id to delete","required":true,"type":"integer","format":"int64"}],"responses":{"400":{"description":"Invalid ID supplied"},"404":{"description":"Pet not found"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/store/order":{"post":{"tags":["store"],"summary":"Place an order for a pet","description":"","operationId":"placeOrder","consumes":["application/json"],"produces":["application/json","application/xml"],"parameters":[{"in":"body","name":"body","description":"order placed for purchasing the pet","required":true,"schema":{"$ref":"#/definitions/Order"}}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/Order"}},"400":{"description":"Invalid Order"}}}},"/store/order/{orderId}":{"get":{"tags":["store"],"summary":"Find purchase order by ID","description":"For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions","operationId":"getOrderById","produces":["application/json","application/xml"],"parameters":[{"name":"orderId","in":"path","description":"ID of pet that needs to be fetched","required":true,"type":"integer","maximum":10,"minimum":1,"format":"int64"}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/Order"}},"400":{"description":"Invalid ID supplied"},"404":{"description":"Order not found"}}},"delete":{"tags":["store"],"summary":"Delete purchase order by ID","description":"For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors","operationId":"deleteOrder","produces":["application/json","application/xml"],"parameters":[{"name":"orderId","in":"path","description":"ID of the order that needs to be deleted","required":true,"type":"integer","minimum":1,"format":"int64"}],"responses":{"400":{"description":"Invalid ID supplied"},"404":{"description":"Order not found"}}}},"/store/inventory":{"get":{"tags":["store"],"summary":"Returns pet inventories by status","description":"Returns a map of status codes to quantities","operationId":"getInventory","produces":["application/json"],"parameters":[],"responses":{"200":{"description":"successful operation","schema":{"type":"object","additionalProperties":{"type":"integer","format":"int32"}}}},"security":[{"api_key":[]}]}},"/user/createWithArray":{"post":{"tags":["user"],"summary":"Creates list of users with given input array","description":"","operationId":"createUsersWithArrayInput","consumes":["application/json"],"produces":["application/json","application/xml"],"parameters":[{"in":"body","name":"body","description":"List of user object","required":true,"schema":{"type":"array","items":{"$ref":"#/definitions/User"}}}],"responses":{"default":{"description":"successful operation"}}}},"/user/createWithList":{"post":{"tags":["user"],"summary":"Creates list of users with given input array","description":"","operationId":"createUsersWithListInput","consumes":["application/json"],"produces":["application/json","application/xml"],"parameters":[{"in":"body","name":"body","description":"List of user object","required":true,"schema":{"type":"array","items":{"$ref":"#/definitions/User"}}}],"responses":{"default":{"description":"successful operation"}}}},"/user/{username}":{"get":{"tags":["user"],"summary":"Get user by user name","description":"","operationId":"getUserByName","produces":["application/json","application/xml"],"parameters":[{"name":"username","in":"path","description":"The name that needs to be fetched. Use user1 for testing. ","required":true,"type":"string"}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/User"}},"400":{"description":"Invalid username supplied"},"404":{"description":"User not found"}}},"put":{"tags":["user"],"summary":"Updated user","description":"This can only be done by the logged in user.","operationId":"updateUser","consumes":["application/json"],"produces":["application/json","application/xml"],"parameters":[{"name":"username","in":"path","description":"name that need to be updated","required":true,"type":"string"},{"in":"body","name":"body","description":"Updated user object","required":true,"schema":{"$ref":"#/definitions/User"}}],"responses":{"400":{"description":"Invalid user supplied"},"404":{"description":"User not found"}}},"delete":{"tags":["user"],"summary":"Delete user","description":"This can only be done by the logged in user.","operationId":"deleteUser","produces":["application/json","application/xml"],"parameters":[{"name":"username","in":"path","description":"The name that needs to be deleted","required":true,"type":"string"}],"responses":{"400":{"description":"Invalid username supplied"},"404":{"description":"User not found"}}}},"/user/login":{"get":{"tags":["user"],"summary":"Logs user into the system","description":"","operationId":"loginUser","produces":["application/json","application/xml"],"parameters":[{"name":"username","in":"query","description":"The user name for login","required":true,"type":"string"},{"name":"password","in":"query","description":"The password for login in clear text","required":true,"type":"string"}],"responses":{"200":{"description":"successful operation","headers":{"X-Expires-After":{"type":"string","format":"date-time","description":"date in UTC when token expires"},"X-Rate-Limit":{"type":"integer","format":"int32","description":"calls per hour allowed by the user"}},"schema":{"type":"string"}},"400":{"description":"Invalid username/password supplied"}}}},"/user/logout":{"get":{"tags":["user"],"summary":"Logs out current logged in user session","description":"","operationId":"logoutUser","produces":["application/json","application/xml"],"parameters":[],"responses":{"default":{"description":"successful operation"}}}},"/user":{"post":{"tags":["user"],"summary":"Create user","description":"This can only be done by the logged in user.","operationId":"createUser","consumes":["application/json"],"produces":["application/json","application/xml"],"parameters":[{"in":"body","name":"body","description":"Created user object","required":true,"schema":{"$ref":"#/definitions/User"}}],"responses":{"default":{"description":"successful operation"}}}}},"securityDefinitions":{"api_key":{"type":"apiKey","name":"api_key","in":"header"},"petstore_auth":{"type":"oauth2","authorizationUrl":"https://petstore.swagger.io/oauth/authorize","flow":"implicit","scopes":{"read:pets":"read your pets","write:pets":"modify pets in your account"}}},"definitions":{"ApiResponse":{"type":"object","properties":{"code":{"type":"integer","format":"int32"},"type":{"type":"string"},"message":{"type":"string"}}},"Category":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"}},"xml":{"name":"Category"}},"Pet":{"type":"object","required":["name","photoUrls"],"properties":{"id":{"type":"integer","format":"int64"},"category":{"$ref":"#/definitions/Category"},"name":{"type":"string","example":"doggie"},"photoUrls":{"type":"array","xml":{"wrapped":true},"items":{"type":"string","xml":{"name":"photoUrl"}}},"tags":{"type":"array","xml":{"wrapped":true},"items":{"xml":{"name":"tag"},"$ref":"#/definitions/Tag"}},"status":{"type":"string","description":"pet status in the store","enum":["available","pending","sold"]}},"xml":{"name":"Pet"}},"Tag":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"}},"xml":{"name":"Tag"}},"Order":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"petId":{"type":"integer","format":"int64"},"quantity":{"type":"integer","format":"int32"},"shipDate":{"type":"string","format":"date-time"},"status":{"type":"string","description":"Order Status","enum":["placed","approved","delivered"]},"complete":{"type":"boolean"}},"xml":{"name":"Order"}},"User":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"username":{"type":"string"},"firstName":{"type":"string"},"lastName":{"type":"string"},"email":{"type":"string"},"password":{"type":"string"},"phone":{"type":"string"},"userStatus":{"type":"integer","format":"int32","description":"User Status"}},"xml":{"name":"User"}}},"externalDocs":{"description":"Find out more about Swagger","url":"http://swagger.io"}}
</code></pre>
<p>expected output;</p>
<pre><code>"{\"swagger\":\"2.0\",\"info\":{\"description\":\"ThisisasampleserverPetstoreserver.YoucanfindoutmoreaboutSwaggerat[http://swagger.io](http://swagger.io)oron[irc.freenode.net,#swagger](http://swagger.io/irc/).Forthissample,youcanusetheapikey`special-key`totesttheauthorizationfilters.\",\"version\":\"1.0.6\",\"title\":\"SwaggerPetstore\",\"termsOfService\":\"http://swagger.io/terms/\",\"contact\":{\"email\":\"apiteam@swagger.io\"},\"license\":{\"name\":\"Apache2.0\",\"url\":\"http://www.apache.org/licenses/LICENSE-2.0.html\"}},\"host\":\"petstore.swagger.io\",\"basePath\":\"/v2\",\"tags\":[{\"name\":\"pet\",\"description\":\"EverythingaboutyourPets\",\"externalDocs\":{\"description\":\"Findoutmore\",\"url\":\"http://swagger.io\"}},{\"name\":\"store\",\"description\":\"AccesstoPetstoreorders\"},{\"name\":\"user\",\"description\":\"Operationsaboutuser\",\"externalDocs\":{\"description\":\"Findoutmoreaboutourstore\",\"url\":\"http://swagger.io\"}}],\"schemes\":[\"https\",\"http\"],\"paths\":{\"/pet/{petId}/uploadImage\":{\"post\":{\"tags\":[\"pet\"],\"summary\":\"uploadsanimage\",\"description\":\"\",\"operationId\":\"uploadFile\",\"consumes\":[\"multipart/form-data\"],\"produces\":[\"application/json\"],\"parameters\":[{\"name\":\"petId\",\"in\":\"path\",\"description\":\"IDofpettoupdate\",\"required\":true,\"type\":\"integer\",\"format\":\"int64\"},{\"name\":\"additionalMetadata\",\"in\":\"formData\",\"description\":\"Additionaldatatopasstoserver\",\"required\":false,\"type\":\"string\"},{\"name\":\"file\",\"in\":\"formData\",\"description\":\"filetoupload\",\"required\":false,\"type\":\"file\"}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"$ref\":\"#/definitions/ApiResponse\"}}},\"security\":[{\"petstore_auth\":[\"write:pets\",\"read:pets\"]}]}},\"/pet\":{\"post\":{\"tags\":[\"pet\"],\"summary\":\"Addanewpettothestore\",\"description\":\"\",\"operationId\":\"addPet\",\"consumes\":[\"application/json\",\"application/xml\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"in\":\"body\",\"name\":\"body\",\"description\":\"Petobjectthatneedstobeaddedtothestore\",\"required\":true,\"schema\":{\"$ref\":\"#/definitions/Pet\"}}],\"responses\":{\"405\":{\"description\":\"Invalidinput\"}},\"security\":[{\"petstore_auth\":[\"write:pets\",\"read:pets\"]}]},\"put\":{\"tags\":[\"pet\"],\"summary\":\"Updateanexistingpet\",\"description\":\"\",\"operationId\":\"updatePet\",\"consumes\":[\"application/json\",\"application/xml\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"in\":\"body\",\"name\":\"body\",\"description\":\"Petobjectthatneedstobeaddedtothestore\",\"required\":true,\"schema\":{\"$ref\":\"#/definitions/Pet\"}}],\"responses\":{\"400\":{\"description\":\"InvalidIDsupplied\"},\"404\":{\"description\":\"Petnotfound\"},\"405\":{\"description\":\"Validationexception\"}},\"security\":[{\"petstore_auth\":[\"write:pets\",\"read:pets\"]}]}},\"/pet/findByStatus\":{\"get\":{\"tags\":[\"pet\"],\"summary\":\"FindsPetsbystatus\",\"description\":\"Multiplestatusvaluescanbeprovidedwithcommaseparatedstrings\",\"operationId\":\"findPetsByStatus\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"status\",\"in\":\"query\",\"description\":\"Statusvaluesthatneedtobeconsideredforfilter\",\"required\":true,\"type\":\"array\",\"items\":{\"type\":\"string\",\"enum\":[\"available\",\"pending\",\"sold\"],\"default\":\"available\"},\"collectionFormat\":\"multi\"}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/Pet\"}}},\"400\":{\"description\":\"Invalidstatusvalue\"}},\"security\":[{\"petstore_auth\":[\"write:pets\",\"read:pets\"]}]}},\"/pet/findByTags\":{\"get\":{\"tags\":[\"pet\"],\"summary\":\"FindsPetsbytags\",\"description\":\"Multipletagscanbeprovidedwithcommaseparatedstrings.Usetag1,tag2,tag3fortesting.\",\"operationId\":\"findPetsByTags\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"tags\",\"in\":\"query\",\"description\":\"Tagstofilterby\",\"required\":true,\"type\":\"array\",\"items\":{\"type\":\"string\"},\"collectionFormat\":\"multi\"}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/Pet\"}}},\"400\":{\"description\":\"Invalidtagvalue\"}},\"security\":[{\"petstore_auth\":[\"write:pets\",\"read:pets\"]}],\"deprecated\":true}},\"/pet/{petId}\":{\"get\":{\"tags\":[\"pet\"],\"summary\":\"FindpetbyID\",\"description\":\"Returnsasinglepet\",\"operationId\":\"getPetById\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"petId\",\"in\":\"path\",\"description\":\"IDofpettoreturn\",\"required\":true,\"type\":\"integer\",\"format\":\"int64\"}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"$ref\":\"#/definitions/Pet\"}},\"400\":{\"description\":\"InvalidIDsupplied\"},\"404\":{\"description\":\"Petnotfound\"}},\"security\":[{\"api_key\":[]}]},\"post\":{\"tags\":[\"pet\"],\"summary\":\"Updatesapetinthestorewithformdata\",\"description\":\"\",\"operationId\":\"updatePetWithForm\",\"consumes\":[\"application/x-www-form-urlencoded\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"petId\",\"in\":\"path\",\"description\":\"IDofpetthatneedstobeupdated\",\"required\":true,\"type\":\"integer\",\"format\":\"int64\"},{\"name\":\"name\",\"in\":\"formData\",\"description\":\"Updatednameofthepet\",\"required\":false,\"type\":\"string\"},{\"name\":\"status\",\"in\":\"formData\",\"description\":\"Updatedstatusofthepet\",\"required\":false,\"type\":\"string\"}],\"responses\":{\"405\":{\"description\":\"Invalidinput\"}},\"security\":[{\"petstore_auth\":[\"write:pets\",\"read:pets\"]}]},\"delete\":{\"tags\":[\"pet\"],\"summary\":\"Deletesapet\",\"description\":\"\",\"operationId\":\"deletePet\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"api_key\",\"in\":\"header\",\"required\":false,\"type\":\"string\"},{\"name\":\"petId\",\"in\":\"path\",\"description\":\"Petidtodelete\",\"required\":true,\"type\":\"integer\",\"format\":\"int64\"}],\"responses\":{\"400\":{\"description\":\"InvalidIDsupplied\"},\"404\":{\"description\":\"Petnotfound\"}},\"security\":[{\"petstore_auth\":[\"write:pets\",\"read:pets\"]}]}},\"/store/order\":{\"post\":{\"tags\":[\"store\"],\"summary\":\"Placeanorderforapet\",\"description\":\"\",\"operationId\":\"placeOrder\",\"consumes\":[\"application/json\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"in\":\"body\",\"name\":\"body\",\"description\":\"orderplacedforpurchasingthepet\",\"required\":true,\"schema\":{\"$ref\":\"#/definitions/Order\"}}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"$ref\":\"#/definitions/Order\"}},\"400\":{\"description\":\"InvalidOrder\"}}}},\"/store/order/{orderId}\":{\"get\":{\"tags\":[\"store\"],\"summary\":\"FindpurchaseorderbyID\",\"description\":\"ForvalidresponsetryintegerIDswithvalue>=1and<=10.Othervalueswillgeneratedexceptions\",\"operationId\":\"getOrderById\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"orderId\",\"in\":\"path\",\"description\":\"IDofpetthatneedstobefetched\",\"required\":true,\"type\":\"integer\",\"maximum\":10,\"minimum\":1,\"format\":\"int64\"}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"$ref\":\"#/definitions/Order\"}},\"400\":{\"description\":\"InvalidIDsupplied\"},\"404\":{\"description\":\"Ordernotfound\"}}},\"delete\":{\"tags\":[\"store\"],\"summary\":\"DeletepurchaseorderbyID\",\"description\":\"ForvalidresponsetryintegerIDswithpositiveintegervalue.Negativeornon-integervalueswillgenerateAPIerrors\",\"operationId\":\"deleteOrder\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"orderId\",\"in\":\"path\",\"description\":\"IDoftheorderthatneedstobedeleted\",\"required\":true,\"type\":\"integer\",\"minimum\":1,\"format\":\"int64\"}],\"responses\":{\"400\":{\"description\":\"InvalidIDsupplied\"},\"404\":{\"description\":\"Ordernotfound\"}}}},\"/store/inventory\":{\"get\":{\"tags\":[\"store\"],\"summary\":\"Returnspetinventoriesbystatus\",\"description\":\"Returnsamapofstatuscodestoquantities\",\"operationId\":\"getInventory\",\"produces\":[\"application/json\"],\"parameters\":[],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"type\":\"object\",\"additionalProperties\":{\"type\":\"integer\",\"format\":\"int32\"}}}},\"security\":[{\"api_key\":[]}]}},\"/user/createWithArray\":{\"post\":{\"tags\":[\"user\"],\"summary\":\"Createslistofuserswithgiveninputarray\",\"description\":\"\",\"operationId\":\"createUsersWithArrayInput\",\"consumes\":[\"application/json\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"in\":\"body\",\"name\":\"body\",\"description\":\"Listofuserobject\",\"required\":true,\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/User\"}}}],\"responses\":{\"default\":{\"description\":\"successfuloperation\"}}}},\"/user/createWithList\":{\"post\":{\"tags\":[\"user\"],\"summary\":\"Createslistofuserswithgiveninputarray\",\"description\":\"\",\"operationId\":\"createUsersWithListInput\",\"consumes\":[\"application/json\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"in\":\"body\",\"name\":\"body\",\"description\":\"Listofuserobject\",\"required\":true,\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/User\"}}}],\"responses\":{\"default\":{\"description\":\"successfuloperation\"}}}},\"/user/{username}\":{\"get\":{\"tags\":[\"user\"],\"summary\":\"Getuserbyusername\",\"description\":\"\",\"operationId\":\"getUserByName\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"username\",\"in\":\"path\",\"description\":\"Thenamethatneedstobefetched.Useuser1fortesting.\",\"required\":true,\"type\":\"string\"}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"$ref\":\"#/definitions/User\"}},\"400\":{\"description\":\"Invalidusernamesupplied\"},\"404\":{\"description\":\"Usernotfound\"}}},\"put\":{\"tags\":[\"user\"],\"summary\":\"Updateduser\",\"description\":\"Thiscanonlybedonebytheloggedinuser.\",\"operationId\":\"updateUser\",\"consumes\":[\"application/json\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"username\",\"in\":\"path\",\"description\":\"namethatneedtobeupdated\",\"required\":true,\"type\":\"string\"},{\"in\":\"body\",\"name\":\"body\",\"description\":\"Updateduserobject\",\"required\":true,\"schema\":{\"$ref\":\"#/definitions/User\"}}],\"responses\":{\"400\":{\"description\":\"Invalidusersupplied\"},\"404\":{\"description\":\"Usernotfound\"}}},\"delete\":{\"tags\":[\"user\"],\"summary\":\"Deleteuser\",\"description\":\"Thiscanonlybedonebytheloggedinuser.\",\"operationId\":\"deleteUser\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"username\",\"in\":\"path\",\"description\":\"Thenamethatneedstobedeleted\",\"required\":true,\"type\":\"string\"}],\"responses\":{\"400\":{\"description\":\"Invalidusernamesupplied\"},\"404\":{\"description\":\"Usernotfound\"}}}},\"/user/login\":{\"get\":{\"tags\":[\"user\"],\"summary\":\"Logsuserintothesystem\",\"description\":\"\",\"operationId\":\"loginUser\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"username\",\"in\":\"query\",\"description\":\"Theusernameforlogin\",\"required\":true,\"type\":\"string\"},{\"name\":\"password\",\"in\":\"query\",\"description\":\"Thepasswordforloginincleartext\",\"required\":true,\"type\":\"string\"}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"headers\":{\"X-Expires-After\":{\"type\":\"string\",\"format\":\"date-time\",\"description\":\"dateinUTCwhentokenexpires\"},\"X-Rate-Limit\":{\"type\":\"integer\",\"format\":\"int32\",\"description\":\"callsperhourallowedbytheuser\"}},\"schema\":{\"type\":\"string\"}},\"400\":{\"description\":\"Invalidusername/passwordsupplied\"}}}},\"/user/logout\":{\"get\":{\"tags\":[\"user\"],\"summary\":\"Logsoutcurrentloggedinusersession\",\"description\":\"\",\"operationId\":\"logoutUser\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[],\"responses\":{\"default\":{\"description\":\"successfuloperation\"}}}},\"/user\":{\"post\":{\"tags\":[\"user\"],\"summary\":\"Createuser\",\"description\":\"Thiscanonlybedonebytheloggedinuser.\",\"operationId\":\"createUser\",\"consumes\":[\"application/json\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"in\":\"body\",\"name\":\"body\",\"description\":\"Createduserobject\",\"required\":true,\"schema\":{\"$ref\":\"#/definitions/User\"}}],\"responses\":{\"default\":{\"description\":\"successfuloperation\"}}}}},\"securityDefinitions\":{\"api_key\":{\"type\":\"apiKey\",\"name\":\"api_key\",\"in\":\"header\"},\"petstore_auth\":{\"type\":\"oauth2\",\"authorizationUrl\":\"https://petstore.swagger.io/oauth/authorize\",\"flow\":\"implicit\",\"scopes\":{\"read:pets\":\"readyourpets\",\"write:pets\":\"modifypetsinyouraccount\"}}},\"definitions\":{\"ApiResponse\":{\"type\":\"object\",\"properties\":{\"code\":{\"type\":\"integer\",\"format\":\"int32\"},\"type\":{\"type\":\"string\"},\"message\":{\"type\":\"string\"}}},\"Category\":{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\",\"format\":\"int64\"},\"name\":{\"type\":\"string\"}},\"xml\":{\"name\":\"Category\"}},\"Pet\":{\"type\":\"object\",\"required\":[\"name\",\"photoUrls\"],\"properties\":{\"id\":{\"type\":\"integer\",\"format\":\"int64\"},\"category\":{\"$ref\":\"#/definitions/Category\"},\"name\":{\"type\":\"string\",\"example\":\"doggie\"},\"photoUrls\":{\"type\":\"array\",\"xml\":{\"wrapped\":true},\"items\":{\"type\":\"string\",\"xml\":{\"name\":\"photoUrl\"}}},\"tags\":{\"type\":\"array\",\"xml\":{\"wrapped\":true},\"items\":{\"xml\":{\"name\":\"tag\"},\"$ref\":\"#/definitions/Tag\"}},\"status\":{\"type\":\"string\",\"description\":\"petstatusinthestore\",\"enum\":[\"available\",\"pending\",\"sold\"]}},\"xml\":{\"name\":\"Pet\"}},\"Tag\":{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\",\"format\":\"int64\"},\"name\":{\"type\":\"string\"}},\"xml\":{\"name\":\"Tag\"}},\"Order\":{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\",\"format\":\"int64\"},\"petId\":{\"type\":\"integer\",\"format\":\"int64\"},\"quantity\":{\"type\":\"integer\",\"format\":\"int32\"},\"shipDate\":{\"type\":\"string\",\"format\":\"date-time\"},\"status\":{\"type\":\"string\",\"description\":\"OrderStatus\",\"enum\":[\"placed\",\"approved\",\"delivered\"]},\"complete\":{\"type\":\"boolean\"}},\"xml\":{\"name\":\"Order\"}},\"User\":{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\",\"format\":\"int64\"},\"username\":{\"type\":\"string\"},\"firstName\":{\"type\":\"string\"},\"lastName\":{\"type\":\"string\"},\"email\":{\"type\":\"string\"},\"password\":{\"type\":\"string\"},\"phone\":{\"type\":\"string\"},\"userStatus\":{\"type\":\"integer\",\"format\":\"int32\",\"description\":\"UserStatus\"}},\"xml\":{\"name\":\"User\"}}},\"externalDocs\":{\"description\":\"FindoutmoreaboutSwagger\",\"url\":\"http://swagger.io\"}}"
</code></pre>
|
[
{
"answer_id": 74667104,
"author": "hassan bazai",
"author_id": 14279755,
"author_profile": "https://Stackoverflow.com/users/14279755",
"pm_score": 0,
"selected": false,
"text": "Any Any"
},
{
"answer_id": 74668459,
"author": "broot",
"author_id": 448875,
"author_profile": "https://Stackoverflow.com/users/448875",
"pm_score": 1,
"selected": false,
"text": "Any Any? interface State<V> interface State<V : Any?> interface State<V : Any> T interface State<V : Any>\n\nclass StringState : State<String> // ok\nclass NullableStringState : State<String?> // compile error\n Any?"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14004008/"
] |
74,666,681
|
<p>In a SpringBoot Controller class, my APIs usually return a ResponseEntity with a body and a status code. But I can apparently dispense with the ResponseEntity by annotating my controller method with <code>@ResponseBody</code>, like this:</p>
<pre><code>@Controller
public class DemoController
{
@Autowired
StudentService studentService;
@GetMapping("/student")
@ResponseBody
Student getStudent(@RequestParam id) {
return studentService.getStudent(id);
}
}
</code></pre>
<p>If my service throws an exception, I can return a custom HTTP status by throwing a <code>ResponseStatusException</code>, but it's not clear how to specify the HTTP status for a valid response. How would I specify this? Or how does it decide what to use?</p>
|
[
{
"answer_id": 74667104,
"author": "hassan bazai",
"author_id": 14279755,
"author_profile": "https://Stackoverflow.com/users/14279755",
"pm_score": 0,
"selected": false,
"text": "Any Any"
},
{
"answer_id": 74668459,
"author": "broot",
"author_id": 448875,
"author_profile": "https://Stackoverflow.com/users/448875",
"pm_score": 1,
"selected": false,
"text": "Any Any? interface State<V> interface State<V : Any?> interface State<V : Any> T interface State<V : Any>\n\nclass StringState : State<String> // ok\nclass NullableStringState : State<String?> // compile error\n Any?"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2028066/"
] |
74,666,692
|
<pre><code>def result(player1, player2):
if player1 == 'A' and player2 == 'X' or player1 == 'B' and player2 == 'Y' or player1 == 'C' and player2 == 'Z':
state = 'draw'
return state, VALUE[player2]
if player1 == 'A' and player2 == 'Y' or player1 == 'B' and player2 == 'Z' or player1 == 'C' and player2 == 'X':
state = 'win'
return state, VALUE[player2]
if player1 == 'A' and player2 == 'Z' or player1 == 'B' and player2 == 'X' or player1 == 'C' and player2 == 'Y':
state = 'loss'
return state, VALUE[player2]
for i in range(len(new_data)):
points = 0
player1 = new_data[i][0]
player2 = new_data[i][1]
results = result(player1, player2)
if results[0] == 'draw':
points += 1 + result[1]
if results[0] == 'win':
points += 6 + result[1]
if results[0] == 'loss':
points += 1 + result[1]
</code></pre>
<p>I thought my function result is returning two values that are stored in the variable <code>results</code> as a tuple, and that I can then access with <code>results[0], results[1]</code>.
But apparently I'm wrong.</p>
<pre><code>`i = 0
result = result(new_data[i][0], new_data[i][1])
print(result)
`
</code></pre>
<p>Returns my desired output
<code>('loss', 2)</code></p>
<p>This I tried and it returned the values I expected. But these values don't seem to get put into the function.</p>
|
[
{
"answer_id": 74667104,
"author": "hassan bazai",
"author_id": 14279755,
"author_profile": "https://Stackoverflow.com/users/14279755",
"pm_score": 0,
"selected": false,
"text": "Any Any"
},
{
"answer_id": 74668459,
"author": "broot",
"author_id": 448875,
"author_profile": "https://Stackoverflow.com/users/448875",
"pm_score": 1,
"selected": false,
"text": "Any Any? interface State<V> interface State<V : Any?> interface State<V : Any> T interface State<V : Any>\n\nclass StringState : State<String> // ok\nclass NullableStringState : State<String?> // compile error\n Any?"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20674289/"
] |
74,666,762
|
<p>Here is my code</p>
<pre><code> print(data['a'][0]['aa'])
print(data['a'][0].keys())
</code></pre>
<p>This is input-></p>
<pre><code> data={
'a':[{
'aa':{'aax':5,'aay':6,'aaz':7},
'ab':{'abx':8,'aby':9,'abz':10}
},
{
'aaa':{'aaax':11,'aaay':12,'aaaz':13},
'aab':{'aabx':14,'aaby':15,'aabz':16}
}]
}
</code></pre>
<p>How can i print the dictionary like this output</p>
<pre><code> Output:
Key:aax Value: 5
Key:aay Value: 6
Key:aaz Value: 7
Key:abx Value: 8
Key:aby Value: 9
Key:abz Value: 10
Key:aaax Value: 11
</code></pre>
<p>How can i loop through in this type of data.How can i loop through and print all the data I can access the single data but how can print all data.</p>
|
[
{
"answer_id": 74666810,
"author": "JayPeerachai",
"author_id": 12135518,
"author_profile": "https://Stackoverflow.com/users/12135518",
"pm_score": 2,
"selected": true,
"text": "for loop for outer_list in data['a']:\n for outer_key, outer_value in outer_list.items():\n for key, value in outer_value.items():\n print(\"Key: {}, Value: {}\".format(key, value))\n Key: aax, Value: 5\nKey: aay, Value: 6\nKey: aaz, Value: 7\nKey: abx, Value: 8\nKey: aby, Value: 9\nKey: abz, Value: 10\nKey: aaax, Value: 11\nKey: aaay, Value: 12\nKey: aaaz, Value: 13\nKey: aabx, Value: 14\nKey: aaby, Value: 15\nKey: aabz, Value: 16\n"
},
{
"answer_id": 74666874,
"author": "chivalrous-nerd",
"author_id": 7347835,
"author_profile": "https://Stackoverflow.com/users/7347835",
"pm_score": 0,
"selected": false,
"text": "for outer_dict in data['a']:\n for inner_dict in outer_dict.values():\n for key, value in inner_dict.items():\n print(f\"Key: {key} Value: {value}\")\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12633191/"
] |
74,666,769
|
<p>I am trying to overwrite specific rows and columns from one dataframe with a second dataframe rows and columns. I can't give the actual data but I will use a proxy here.</p>
<p>Here is an example and what I have tried:</p>
<pre><code>df1
UID B C D
0 X14 cat red One
1 X26 cat blue Two
2 X99 cat pink One
3 X54 cat pink One
df2
UID B C EX2
0 X14 dog blue coat
1 X88 rat green jacket
2 X99 bat red glasses
3 X29 bat red shoes
</code></pre>
<p>What I want to do here is overwrite column <code>B</code> and <code>C</code> in <code>df1</code> with the values in <code>df2</code> based upon <code>UID</code>. Therefore in this example <code>X88</code> and <code>X29</code> from <code>df2</code> would not appear in <code>df2</code>. Also column <code>D</code> would not be affected and <code>EX2</code> not</p>
<p>The outcome would looks as such:</p>
<pre><code>df1
UID B C D
0 X14 dog blue One
1 X26 cat blue Two
2 X99 bat red One
3 X54 cat pink One
</code></pre>
<p>I looked at this solution : <a href="https://stackoverflow.com/questions/58226481/pandas-merge-two-dataframe-and-overwrite-rows">Pandas merge two dataframe and overwrite rows</a>
However this appears to only update null values whereas I want an overwrite.</p>
<p>My attempt looked this like:</p>
<pre><code>df = df1.merge(df2.filter(['B', 'C']), on=['B', 'C'], how='left')
</code></pre>
<p>For my data this actually doesn't seem to overwrite anything. Please could someone explain why this would not work?</p>
<p>Thanks</p>
|
[
{
"answer_id": 74666841,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 1,
"selected": false,
"text": "reindex_like combine_first out = (\n df2.set_index(\"UID\")\n .reindex_like(df1.set_index(\"UID\"))\n .combine_first(df1.set_index(\"UID\"))\n .reset_index()\n )\n print(out)\n\n UID B C D\n0 X14 dog blue One\n1 X26 cat blue Two\n2 X99 bat red One\n3 X54 cat pink One\n"
},
{
"answer_id": 74666936,
"author": "ouroboros1",
"author_id": 18470692,
"author_profile": "https://Stackoverflow.com/users/18470692",
"pm_score": 2,
"selected": true,
"text": "df.set_index UID inplace df.update overwrite True set_index df2 B C UID df.reset_index df1.set_index('UID', inplace=True)\ndf1.update(df2.set_index('UID'), overwrite=True)\ndf1.reset_index(inplace=True)\nprint(df1)\n\n UID B C D\n0 X14 dog blue One\n1 X26 cat blue Two\n2 X99 bat red One\n3 X54 cat pink One\n"
},
{
"answer_id": 74666946,
"author": "Vinay",
"author_id": 16523586,
"author_profile": "https://Stackoverflow.com/users/16523586",
"pm_score": 0,
"selected": false,
"text": "df1.set_index('UID', inplace=True)\ndf2.set_index('UID', inplace=True)\n\ndf1.update(df2)\ndf1.reset_index(inplace=True)\nprint(df1)\n UID B C D\n0 X14 dog blue One\n1 X26 cat blue Two\n2 X99 bat red One\n3 X54 cat pink One\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10574250/"
] |
74,666,795
|
<p>I am trying to sort datas which are fetched from firebase realtime database according to the value of a child using MVVM architecture the daabase reference is created in a repository</p>
<p><strong>GroupNoticeRepository</strong></p>
<pre><code>class GroupNoticeRepository(private var groupSelected: String) {
val auth = Firebase.auth
val user = auth.currentUser!!.uid
private val scheduleReference: DatabaseReference =
FirebaseDatabase.getInstance().getReference("group-notice").child(groupSelected)
@Volatile
private var INSTANCE: GroupNoticeRepository? = null
fun getInstance(): GroupNoticeRepository {
return INSTANCE ?: synchronized(this) {
val instance = GroupNoticeRepository(groupSelected)
INSTANCE = instance
instance
}
}
fun loadSchedules(allSchedules: MutableLiveData<List<GroupNoticeData>>) {
scheduleReference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
try {
val scheduleList: List<GroupNoticeData> =
snapshot.children.map { dataSnapshot ->
dataSnapshot.getValue(GroupNoticeData::class.java)!!
}
allSchedules.postValue(scheduleList)
} catch (_: Exception) {
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
}
</code></pre>
<p><strong>GroupNoticeFragment</strong></p>
<pre><code>override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recycler = binding.taskList
recycler.layoutManager = LinearLayoutManager(context)
recycler.setHasFixedSize(true)
adapter = GroupNoticeAdapter(_inflater)
recycler.adapter = adapter
viewModel = ViewModelProvider(this)[GroupNoticeViewModel::class.java]
viewModel.initialize(groupId)
viewModel.allSchedules.observe(viewLifecycleOwner) {
adapter!!.updateUserList(it)
}
}
</code></pre>
<p><strong>GroupNoticeViewModel</strong></p>
<pre><code>
class GroupNoticeViewModel : ViewModel() {
private lateinit var repository: GroupNoticeRepository
private val _allSchedules = MutableLiveData<List<GroupNoticeData>>()
val allSchedules: LiveData<List<GroupNoticeData>> = _allSchedules
fun initialize(groupSelected: String) {
repository = GroupNoticeRepository(groupSelected).getInstance()
repository.loadSchedules(_allSchedules)
}
}
</code></pre>
<p>`<a href="https://i.stack.imgur.com/d1tPF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/d1tPF.jpg" alt="enter image description here" /></a></p>
<p>As you can see the current structure
group-notice
-groupId(groups)
-noticeId (notices)
- taskDate</p>
<p>Here under group notice there are some groups and in each group there are some notices(noticeId) .
Each notice has a task date . Now I am trying to sort the notices according to the taskdate meaning the taskDate which will is closer to todays date will view first in the recycler view. Or the notice with latest taskdate given will appear first in the recycler view .</p>
|
[
{
"answer_id": 74667410,
"author": "hassan bazai",
"author_id": 14279755,
"author_profile": "https://Stackoverflow.com/users/14279755",
"pm_score": 2,
"selected": true,
"text": "public class FirebaseDataComparator implements Comparator<FirebaseData> {\n @Override\n public int compare(FirebaseData o1, FirebaseData o2) {\n return o1.getName().compareTo(o2.getName());\n }\n}\n"
},
{
"answer_id": 74668421,
"author": "Parvez Ahammed",
"author_id": 13925224,
"author_profile": "https://Stackoverflow.com/users/13925224",
"pm_score": 0,
"selected": false,
"text": "class FirebaseDataComparator : Comparator<GroupNoticeData?> {\n override fun compare(p0: GroupNoticeData?, p1: GroupNoticeData?): Int {\n\n val dateFormat = SimpleDateFormat(\"dd/MM/yyyy\")\n\n val firstDate: Date = dateFormat.parse(p0?.taskdate!!) as Date\n val secondDate: Date = dateFormat.parse(p1?.taskdate!!) as Date\n\n return firstDate.compareTo(secondDate)\n }\n}\n fun updateNoticeList(notices: List<GroupNoticeData>) {\n Collections.sort(notices, FirebaseDataComparator())\n this.tasks.clear()\n this.tasks.addAll(notices)\n\n notifyDataSetChanged()\n\n }\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13925224/"
] |
74,666,805
|
<p><a href="https://i.stack.imgur.com/PF0Dy.png" rel="nofollow noreferrer">Object</a> Im have Object , but how can get keys + value in this (main : , weather : , clouds: , cors : , ... )
Im try use map but can't go next entry
<a href="https://i.stack.imgur.com/RZdnp.png" rel="nofollow noreferrer">My demo</a>
Sorry im bad english . thanks alot</p>
|
[
{
"answer_id": 74666845,
"author": "sheepiiHD",
"author_id": 3081794,
"author_profile": "https://Stackoverflow.com/users/3081794",
"pm_score": 1,
"selected": false,
"text": "const foobar = {main: \"hello\", clouds = \"world\", cors: 1}\nconst keypairs = Object.entries(foobar);\n\n//looping\nkeypairs.map(([key, value]) => { // do something });\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20673525/"
] |
74,666,821
|
<p>if the user enters a char it should show the wrong input and continue asking for input until it reaches the range of 10 elements. how to solve this? output</p>
<pre><code>list = []
even = 0
for x in range(10):
number = int(input("Enter a number: "))
list.append(number)
for y in list:
if y % 2 == 0:
even +=1
print("Number of even numbers: " ,even)
for y in list:
if y % 2 == 0:
count = list.index(y)
print("Index [",count,"]: ",y)
</code></pre>
|
[
{
"answer_id": 74666845,
"author": "sheepiiHD",
"author_id": 3081794,
"author_profile": "https://Stackoverflow.com/users/3081794",
"pm_score": 1,
"selected": false,
"text": "const foobar = {main: \"hello\", clouds = \"world\", cors: 1}\nconst keypairs = Object.entries(foobar);\n\n//looping\nkeypairs.map(([key, value]) => { // do something });\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18929055/"
] |
74,666,827
|
<p>I am new to react, so if I am doing anything outside of the problem wrong please tell me also.</p>
<p>I'm trying to map my json response into a table, I can collect the data into an object array, but I am receiving this error :
<a href="https://i.stack.imgur.com/BvwfF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BvwfF.png" alt="enter image description here" /></a></p>
<p>Here is the components code:</p>
<pre><code>import axios from "axios";
function FilmTableRows(props) {
const dataFormat = props.dataFormat;
const [data, setData] = useState([]);
const baseURL = "http://localhost:8080/FilmRestful/filmapi";
const getJson = () => {
let config = {
headers: {
"data-type": "json",
"Content-type": "application/json",
},
};
axios
.get(baseURL, config)
.then((res) => {
const resData = res.data;
setData(resData);
})
.catch((err) => {});
};
switch (dataFormat.value) {
case "json":
getJson();
console.log(data);
break;
case "xml":
getXML();
console.log(data);
break;
default:
getString();
console.log(data);
}
const child = data.map((el) => {
return (
<tr key={el.id}>
<td>{el.title}</td>
<td>{el.year}</td>
<td>{el.director}</td>
<td>{el.stars}</td>
<td>{el.review}</td>
</tr>
);
});
return <>{data && data.length > 0 && { child }}</>;
}
export default FilmTableRows;
</code></pre>
|
[
{
"answer_id": 74666909,
"author": "Yahli Gi",
"author_id": 17089291,
"author_profile": "https://Stackoverflow.com/users/17089291",
"pm_score": 2,
"selected": true,
"text": "return <>{data && data.length > 0 && child }</>;\n"
},
{
"answer_id": 74667153,
"author": "Amirpasha Bagheri",
"author_id": 14877576,
"author_profile": "https://Stackoverflow.com/users/14877576",
"pm_score": 0,
"selected": false,
"text": "child {} data.length render return <>{data && child}</>\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19213617/"
] |
74,666,835
|
<p>I have a table with 8,000 rows of data and a small sample of it here:</p>
<pre><code>Customer ItemDescription Invoice PurchaseDate
1064 Produce 55514 22-01
1064 Snack 55514 22-01
1080 Drink 56511 23-01
1080 Snack 56511 23-01
1230 Drink 55551 26-03
1230 Snack 55551 26-03
1128 Meat 55003 04-03
1128 Snack 55003 04-03
1229 Drink 55100 06-03
1229 Snack 55100 06-03
1230 Meat 55102 07-03
1230 Snack 55102 07-03
</code></pre>
<p>I am trying to find the top 3 items that customers have bought along with "Snack".</p>
<p>So the printed result should look like this:</p>
<pre><code>0 Drink
1 Meat
2 Produce
</code></pre>
<p>I have tried df.groupby but it doesn't sort them based on what was purchased along with "snacks".</p>
|
[
{
"answer_id": 74666909,
"author": "Yahli Gi",
"author_id": 17089291,
"author_profile": "https://Stackoverflow.com/users/17089291",
"pm_score": 2,
"selected": true,
"text": "return <>{data && data.length > 0 && child }</>;\n"
},
{
"answer_id": 74667153,
"author": "Amirpasha Bagheri",
"author_id": 14877576,
"author_profile": "https://Stackoverflow.com/users/14877576",
"pm_score": 0,
"selected": false,
"text": "child {} data.length render return <>{data && child}</>\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20413330/"
] |
74,666,866
|
<p>I built a knn model for classification. Unfortunately, my model has accuracy > 80%, and I would like to get a better result. Can I ask for some tips? Maybe I used too many predictors?</p>
<p>My data = <a href="https://www.openml.org/search?type=data&sort=runs&id=53&status=active" rel="nofollow noreferrer">https://www.openml.org/search?type=data&sort=runs&id=53&status=active</a></p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix, accuracy_score, f1_score
from sklearn.model_selection import GridSearchCV
heart_disease = pd.read_csv('heart_disease.csv', sep=';', decimal=',')
y = heart_disease['heart_disease']
X = heart_disease.drop(["heart_disease"], axis=1)
correlation_matrix = heart_disease.corr()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=123)
scaler = MinMaxScaler(feature_range=(-1,1))
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
knn_3 = KNeighborsClassifier(3, n_jobs = -1)
knn_3.fit(X_train, y_train)
y_train_pred = knn_3.predict(X_train)
labels = ['0', '1']
print('Training set')
print(pd.DataFrame(confusion_matrix(y_train, y_train_pred), index = labels, columns = labels))
print(accuracy_score(y_train, y_train_pred))
print(f1_score(y_train, y_train_pred))
y_test_pred = knn_3.predict(X_test)
print('Test set')
print(pd.DataFrame(confusion_matrix(y_test, y_test_pred), index = labels, columns = labels))
print(accuracy_score(y_test, y_test_pred))
print(f1_score(y_test, y_test_pred))
hyperparameters = {'n_neighbors' : range(1, 15), 'weights': ['uniform','distance']}
knn_best = GridSearchCV(KNeighborsClassifier(), hyperparameters, n_jobs = -1, error_score = 'raise')
knn_best.fit(X_train,y_train)
knn_best.best_params_
y_train_pred_best = knn_best.predict(X_train)
y_test_pred_best = knn_best.predict(X_test)
print('Training set')
print(pd.DataFrame(confusion_matrix(y_train, y_train_pred_best), index = labels, columns = labels))
print(accuracy_score(y_train, y_train_pred_best))
print(f1_score(y_train, y_train_pred_best))
print('Test set')
print(pd.DataFrame(confusion_matrix(y_test, y_test_pred_best), index = labels, columns = labels))
print(accuracy_score(y_test, y_test_pred_best))
print(f1_score(y_test, y_test_pred_best))
</code></pre>
|
[
{
"answer_id": 74667057,
"author": "solac34",
"author_id": 20554831,
"author_profile": "https://Stackoverflow.com/users/20554831",
"pm_score": 1,
"selected": false,
"text": "errlist = [] #an error list to append\nfor i in range(1,40): #from 0-40 numbers to use in k_neighbors\n knn_i = KNeighborsClassifier(k_neighbors=i)\n knn_i.fit(X_train,y_train)\n errlist.append(np.mean(knn_i.predict(X_test)!=y_test)) # append the mean of failed-predict numbers\n plt.plot(range(1,40),errlist)\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19753240/"
] |
74,666,870
|
<p>I have a CartController with the following function:</p>
<pre><code> public function getTotalCartPrice()
{
$totalCartPrice = 1;
return $totalCartPrice;
}
</code></pre>
<p>Cart.blade.php</p>
<pre><code><h3 class="cartTotal">Cart total: {{ Cart::getTotalCartPrice }} </h3>
</code></pre>
<p>Routes</p>
<pre><code>Route::resource('/cart', CartController::class);
</code></pre>
<p>Using this does not seem to display the total cart price and I get an error saying class "Cart" not found. I have attempted to change my route to this:</p>
<pre><code>Route::get('/cartPrice', [CartController::class, 'getTotalCartPrice'])->name('getTotalCartPrice');
</code></pre>
<p>and then inside my blade view:</p>
<pre><code><h3 class="cartTotal">Cart total: {{ route('getTotalCartPrice') }} </h3>
</code></pre>
<p>But I just get an output on the website:</p>
<pre><code>Cart total: http://localhost/cartPrice
</code></pre>
|
[
{
"answer_id": 74667057,
"author": "solac34",
"author_id": 20554831,
"author_profile": "https://Stackoverflow.com/users/20554831",
"pm_score": 1,
"selected": false,
"text": "errlist = [] #an error list to append\nfor i in range(1,40): #from 0-40 numbers to use in k_neighbors\n knn_i = KNeighborsClassifier(k_neighbors=i)\n knn_i.fit(X_train,y_train)\n errlist.append(np.mean(knn_i.predict(X_test)!=y_test)) # append the mean of failed-predict numbers\n plt.plot(range(1,40),errlist)\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12071277/"
] |
74,666,901
|
<p>Left side there is a menu, right side the content.</p>
<p>A flex box is used. Why menu scroll, if I scroll in right side? Why it is not keep fixed? How can I fix it?</p>
<p><a href="https://i.stack.imgur.com/OSK0y.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OSK0y.gif" alt="" /></a></p>
<p>CSS is inline in React.js.</p>
<pre class="lang-js prettyprint-override"><code>const DashboardLayout = ({ children }: Props) => {
const isDesktop = useMediaQuery('(min-width: 575px)')
return (
<Layout isNavbarTransparent={false}>
<section className={`section-base`}>
<div style={{ display: 'flex' }}>
{isDesktop ? (
<>
<div style={{ flexBasis: '350px' }}>
<DashboardSidebar embeddedIn={'dashboard'} />
</div>
<div>{children}</div>
</>
) : (
<div>{children}</div>
)}
</div>
</section>
</Layout>
)
}
</code></pre>
<p>I tried to set this for right content:</p>
<pre class="lang-css prettyprint-override"><code>overflow: hidden;
height: 100px;
</code></pre>
<p>Did not help.</p>
|
[
{
"answer_id": 74667179,
"author": "Franco Gabriel",
"author_id": 19499461,
"author_profile": "https://Stackoverflow.com/users/19499461",
"pm_score": 1,
"selected": false,
"text": "position: sticky; .top-bar {\n width: 100%;\n height: 40px;\n background-color: black;\n}\n\n.dashboard {\n display: flex;\n width: 100%;\n}\n\n.menu {\n width: 30%;\n margin: 20px;\n}\n\n.sticky-container {\n position: sticky;\n top: 0; /* set top for sticky to work */\n padding-top: 10px;\n}\n\n.content {\n width: 70%;\n} <div>\n <div class=\"top-bar\"></div>\n <div class=\"dashboard\">\n <div class=\"menu\">\n <div class=\"sticky-container\">\n <li>Options</li>\n <li>Options</li>\n <li>Options</li>\n <li>Options</li>\n </div>\n </div>\n <div class=\"content\">\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia laborum ab ducimus, consequatur itaque modi dolores dolorem optio assumenda ad doloribus eveniet voluptas, asperiores maiores deleniti, cupiditate dolor necessitatibus aliquam. Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad maxime beatae quod ea excepturi libero reprehenderit. Animi, voluptates? Obcaecati illum quis asperiores molestias, autem dolorum. Sapiente quis voluptate voluptatibus ipsa?</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia laborum ab ducimus, consequatur itaque modi dolores dolorem optio assumenda ad doloribus eveniet voluptas, asperiores maiores deleniti, cupiditate dolor necessitatibus aliquam. Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad maxime beatae quod ea excepturi libero reprehenderit. Animi, voluptates? Obcaecati illum quis asperiores molestias, autem dolorum. Sapiente quis voluptate voluptatibus ipsa?</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia laborum ab ducimus, consequatur itaque modi dolores dolorem optio assumenda ad doloribus eveniet voluptas, asperiores maiores deleniti, cupiditate dolor necessitatibus aliquam. Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad maxime beatae quod ea excepturi libero reprehenderit. Animi, voluptates? Obcaecati illum quis asperiores molestias, autem dolorum. Sapiente quis voluptate voluptatibus ipsa?</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia laborum ab ducimus, consequatur itaque modi dolores dolorem optio assumenda ad doloribus eveniet voluptas, asperiores maiores deleniti, cupiditate dolor necessitatibus aliquam. Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad maxime beatae quod ea excepturi libero reprehenderit. Animi, voluptates? Obcaecati illum quis asperiores molestias, autem dolorum. Sapiente quis voluptate voluptatibus ipsa?</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia laborum ab ducimus, consequatur itaque modi dolores dolorem optio assumenda ad doloribus eveniet voluptas, asperiores maiores deleniti, cupiditate dolor necessitatibus aliquam. Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad maxime beatae quod ea excepturi libero reprehenderit. Animi, voluptates? Obcaecati illum quis asperiores molestias, autem dolorum. Sapiente quis voluptate voluptatibus ipsa?</p>\n </div>\n </div>\n</div>"
},
{
"answer_id": 74667354,
"author": "János",
"author_id": 239219,
"author_profile": "https://Stackoverflow.com/users/239219",
"pm_score": 0,
"selected": false,
"text": "overflow: scroll;\nheight: calc(100vh - 64px);\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239219/"
] |
74,666,910
|
<p>on my Project I have a banner on top of my site with 2 buttons. when I click the button profile I want it to change the css style of a div in another component.
this is my code for the banner:</p>
<pre><code>import Profile from "./Profile";
function Banner() {
const invis=false;
return (
<div className="banner">
<span className="bannerbtnsettings">
<button className="btnbannersettings">Settings</button>
</span>
<span className="bannerbtnprofile">
<button className="btnbannerprofile" onClick={Profile.changeStyle}>Profile</button>
</span>
</div>
);
}
export default Banner;
</code></pre>
<p>this is my code for the div in the other component:</p>
<pre><code>import "../index.css";
import React, { useState } from "react";
const Profile = () => {
const [style, setStyle] = useState("profile-hidden");
const changeStyle = () => {
console.log("you just clicked");
setStyle("profile-displayed");
};
return (
<div>
<div className={style}> hellllo</div>
</div>
);
};
export default Profile;
</code></pre>
<p>I can only find information about this with parent-child components.
They said I should use a usestate import but I can't seem to get it working. what's the proper way to do this?</p>
|
[
{
"answer_id": 74667179,
"author": "Franco Gabriel",
"author_id": 19499461,
"author_profile": "https://Stackoverflow.com/users/19499461",
"pm_score": 1,
"selected": false,
"text": "position: sticky; .top-bar {\n width: 100%;\n height: 40px;\n background-color: black;\n}\n\n.dashboard {\n display: flex;\n width: 100%;\n}\n\n.menu {\n width: 30%;\n margin: 20px;\n}\n\n.sticky-container {\n position: sticky;\n top: 0; /* set top for sticky to work */\n padding-top: 10px;\n}\n\n.content {\n width: 70%;\n} <div>\n <div class=\"top-bar\"></div>\n <div class=\"dashboard\">\n <div class=\"menu\">\n <div class=\"sticky-container\">\n <li>Options</li>\n <li>Options</li>\n <li>Options</li>\n <li>Options</li>\n </div>\n </div>\n <div class=\"content\">\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia laborum ab ducimus, consequatur itaque modi dolores dolorem optio assumenda ad doloribus eveniet voluptas, asperiores maiores deleniti, cupiditate dolor necessitatibus aliquam. Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad maxime beatae quod ea excepturi libero reprehenderit. Animi, voluptates? Obcaecati illum quis asperiores molestias, autem dolorum. Sapiente quis voluptate voluptatibus ipsa?</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia laborum ab ducimus, consequatur itaque modi dolores dolorem optio assumenda ad doloribus eveniet voluptas, asperiores maiores deleniti, cupiditate dolor necessitatibus aliquam. Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad maxime beatae quod ea excepturi libero reprehenderit. Animi, voluptates? Obcaecati illum quis asperiores molestias, autem dolorum. Sapiente quis voluptate voluptatibus ipsa?</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia laborum ab ducimus, consequatur itaque modi dolores dolorem optio assumenda ad doloribus eveniet voluptas, asperiores maiores deleniti, cupiditate dolor necessitatibus aliquam. Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad maxime beatae quod ea excepturi libero reprehenderit. Animi, voluptates? Obcaecati illum quis asperiores molestias, autem dolorum. Sapiente quis voluptate voluptatibus ipsa?</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia laborum ab ducimus, consequatur itaque modi dolores dolorem optio assumenda ad doloribus eveniet voluptas, asperiores maiores deleniti, cupiditate dolor necessitatibus aliquam. Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad maxime beatae quod ea excepturi libero reprehenderit. Animi, voluptates? Obcaecati illum quis asperiores molestias, autem dolorum. Sapiente quis voluptate voluptatibus ipsa?</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia laborum ab ducimus, consequatur itaque modi dolores dolorem optio assumenda ad doloribus eveniet voluptas, asperiores maiores deleniti, cupiditate dolor necessitatibus aliquam. Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad maxime beatae quod ea excepturi libero reprehenderit. Animi, voluptates? Obcaecati illum quis asperiores molestias, autem dolorum. Sapiente quis voluptate voluptatibus ipsa?</p>\n </div>\n </div>\n</div>"
},
{
"answer_id": 74667354,
"author": "János",
"author_id": 239219,
"author_profile": "https://Stackoverflow.com/users/239219",
"pm_score": 0,
"selected": false,
"text": "overflow: scroll;\nheight: calc(100vh - 64px);\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19870243/"
] |
74,666,923
|
<p>Disabled users who cannot control a mouse use the keyboard to navigate the page. How do you allow them to select the various styles (like bold etc) in ckeditor5? These elements are NOT in the tabindex of the page by default.</p>
<p>Tabbing through a form, I expect to be able to interact with every interactable element on a page</p>
|
[
{
"answer_id": 74667179,
"author": "Franco Gabriel",
"author_id": 19499461,
"author_profile": "https://Stackoverflow.com/users/19499461",
"pm_score": 1,
"selected": false,
"text": "position: sticky; .top-bar {\n width: 100%;\n height: 40px;\n background-color: black;\n}\n\n.dashboard {\n display: flex;\n width: 100%;\n}\n\n.menu {\n width: 30%;\n margin: 20px;\n}\n\n.sticky-container {\n position: sticky;\n top: 0; /* set top for sticky to work */\n padding-top: 10px;\n}\n\n.content {\n width: 70%;\n} <div>\n <div class=\"top-bar\"></div>\n <div class=\"dashboard\">\n <div class=\"menu\">\n <div class=\"sticky-container\">\n <li>Options</li>\n <li>Options</li>\n <li>Options</li>\n <li>Options</li>\n </div>\n </div>\n <div class=\"content\">\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia laborum ab ducimus, consequatur itaque modi dolores dolorem optio assumenda ad doloribus eveniet voluptas, asperiores maiores deleniti, cupiditate dolor necessitatibus aliquam. Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad maxime beatae quod ea excepturi libero reprehenderit. Animi, voluptates? Obcaecati illum quis asperiores molestias, autem dolorum. Sapiente quis voluptate voluptatibus ipsa?</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia laborum ab ducimus, consequatur itaque modi dolores dolorem optio assumenda ad doloribus eveniet voluptas, asperiores maiores deleniti, cupiditate dolor necessitatibus aliquam. Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad maxime beatae quod ea excepturi libero reprehenderit. Animi, voluptates? Obcaecati illum quis asperiores molestias, autem dolorum. Sapiente quis voluptate voluptatibus ipsa?</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia laborum ab ducimus, consequatur itaque modi dolores dolorem optio assumenda ad doloribus eveniet voluptas, asperiores maiores deleniti, cupiditate dolor necessitatibus aliquam. Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad maxime beatae quod ea excepturi libero reprehenderit. Animi, voluptates? Obcaecati illum quis asperiores molestias, autem dolorum. Sapiente quis voluptate voluptatibus ipsa?</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia laborum ab ducimus, consequatur itaque modi dolores dolorem optio assumenda ad doloribus eveniet voluptas, asperiores maiores deleniti, cupiditate dolor necessitatibus aliquam. Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad maxime beatae quod ea excepturi libero reprehenderit. Animi, voluptates? Obcaecati illum quis asperiores molestias, autem dolorum. Sapiente quis voluptate voluptatibus ipsa?</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia laborum ab ducimus, consequatur itaque modi dolores dolorem optio assumenda ad doloribus eveniet voluptas, asperiores maiores deleniti, cupiditate dolor necessitatibus aliquam. Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad maxime beatae quod ea excepturi libero reprehenderit. Animi, voluptates? Obcaecati illum quis asperiores molestias, autem dolorum. Sapiente quis voluptate voluptatibus ipsa?</p>\n </div>\n </div>\n</div>"
},
{
"answer_id": 74667354,
"author": "János",
"author_id": 239219,
"author_profile": "https://Stackoverflow.com/users/239219",
"pm_score": 0,
"selected": false,
"text": "overflow: scroll;\nheight: calc(100vh - 64px);\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74666923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16008060/"
] |
74,667,001
|
<p>Hi all I am a newby and I am trying to create a function that when I press a button for example the 'b' key focus will move from one button on the page to the next. I am able to set the focus on the first button of the page but when I press the 'b' key again focus stays on the first button.</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 btn = document.querySelector("button");
document.body.addEventListener("keypress", (e) => {
if (e.key == "b") {
e.preventDefault();
document.querySelector("button").focus();
}
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>Button 1</button><br>
<button>Button 2</button><br>
<button>Button 3</button><br>
<button>Button 4</button><br>
<button>Button 5</button><br></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74667190,
"author": "raykay",
"author_id": 18357803,
"author_profile": "https://Stackoverflow.com/users/18357803",
"pm_score": 0,
"selected": false,
"text": "let buttons = document.querySelectorAll('button');\nlet currentButton = 0;\n\ndocument.body.addEventListener('keypress', e => {\n if (e.key == 'b') {\n e.preventDefault();\n currentButton++; // move to the next button in the list\n if (currentButton >= buttons.length) {\n currentButton = 0; // loop back to the first button if we reach the end of the list\n }\n buttons[currentButton].focus();\n }\n});\n"
},
{
"answer_id": 74667288,
"author": "ths",
"author_id": 6388552,
"author_profile": "https://Stackoverflow.com/users/6388552",
"pm_score": 2,
"selected": true,
"text": "data-* data-is-focused 1 0 data-is-focused JavaScript 0 1 data-is-focused 0 \"b\" data-is-focused 1 0 0 const btns = Array.from(document.querySelectorAll(\"button\")),\n /**\n * guess the index of the buitton to be focused based on the index of the currently focused button and whether we want to walk forwards or backwards.\n */\n guessNextButtonIndex = (focusedBtnIndex, inReverseOrder) => {\n return inReverseOrder\n ? (focusedBtnIndex <= 0 ? btns.length - 1 : focusedBtnIndex - 1) \n : (focusedBtnIndex === -1 || focusedBtnIndex === btns.length - 1 ? 0 : focusedBtnIndex + 1);\n };\n\ndocument.body.addEventListener(\"keydown\", e => {\n // because we accept shift key, when you press shift + \"b\" the output will be \"B\" (uppercased) so we need to transform that to lower case.\n if (e.key.toLowerCase() === \"b\") {\n // get the index of the currently focused button based on the data-is-focused attribute. If no button is focused, -1 is returned.\n const idx = btns.findIndex(btn => btn.dataset.isFocused == 1),\n btnToFocus = btns[guessNextButtonIndex(idx, e.shiftKey)];\n // set the data-is-focused of the last focused button to \"0\"\n idx !== -1 && (btns[idx].dataset.isFocused = 0);\n // set the data-is-focused of the button to be focused to \"1\"\n btnToFocus.dataset.isFocused = 1;\n // focus the button to be focused\n btnToFocus.focus();\n }\n}); <button>Button 1</button><br>\n<button>Button 2</button><br>\n<button>Button 3</button><br>\n<button>Button 4</button><br>\n<button>Button 5</button><br>"
},
{
"answer_id": 74667616,
"author": "Jagdish Ahir",
"author_id": 20674763,
"author_profile": "https://Stackoverflow.com/users/20674763",
"pm_score": 0,
"selected": false,
"text": " const boxes = document.querySelectorAll('button');\n var boxesLength = boxes.length;\n for (var i = 0; i < boxesLength; i++) {\n boxes[i].addEventListener('click', function (i) {\n var findnextbtn;\n if ((boxesLength - 1) == i) {\n removeStyle();\n findnextbtn = boxes[0];\n } else {\n removeStyle();\n findnextbtn = boxes[i + 1];\n }\n findnextbtn.setAttribute('style', 'background-color: yellow;');\n }.bind(null, i));\n }\n function removeStyle() {\n boxes.forEach(box => {\n box.setAttribute('style', 'background-color: none;');\n });\n } <button>Button 1</button><br>\n<button>Button 2</button><br>\n<button>Button 3</button><br>\n<button>Button 4</button><br>\n<button>Button 5</button><br>"
},
{
"answer_id": 74667828,
"author": "Muhammad Salman",
"author_id": 15715337,
"author_profile": "https://Stackoverflow.com/users/15715337",
"pm_score": 0,
"selected": false,
"text": "let btn = document.querySelector(\"button\");\ndocument.body.addEventListener(\"keypress\", (e) => {\n if (e.key == \"b\") {\n e.preventDefault();\n // Get a list of all buttons on the page\n const buttons = document.querySelectorAll(\"button\");\n // Find the next button in the list\n const nextButton = buttons.find((button) => button.tabIndex > btn.tabIndex);\n if (nextButton) {\n // Set focus on the next button\n nextButton.focus();\n }\n }\n});\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20674542/"
] |
74,667,022
|
<p>here is a code for multiselect which is working fine for multiselect but i need this code to be work in single select , in this Code #Country list is simply getting list from option as you can see in code and when we select #country in dropdown the #state data is fetching from data base according to country selection</p>
<pre><code>( Multi select is Working fine but i need this in Single select )
<script src="js/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<label for="country">Country</label> ( Simple Drop Down for Country )
<?php include "fetch_country.php"; ?>
<select id="country" name="country[]" multiple class="form-control" >
<option value="India" label="India">India</option>
<option value="USA" label="USA">USA</option>
<option value="UK" label="UK">UK</option>
<option value="Canada" label="Canada">Canada</option>
<option value="China" label="China">China</option>
</select>
<div class="col-sm-6">
<label for="state">State</label> ( Fetching State data from Database )
<select id="state" name="state[]" multiple class="form-control" >
<option disabled>Select Country First</option>
</select>
<button class="myButnsbmt" type="submit" name="update" value="Update">Submit</button>
</form>
<script>
$(document).ready(function(){
$('#country').multiselect({
nonSelectedText:'?',
buttonWidth:'250px',
maxHeight: 400,
onChange:function(option, checked){
var selected = this.$select.val();
if(selected.length > 0)
{
$.ajax({
url:"fetch_country.php",
method:"POST",
data:{selected:selected},
success:function(data)
{
$('#state').html(data);
$('#state').multiselect('rebuild');
}
})
}
}
});
$('#state').multiselect({
nonSelectedText: '?',
allSelectedText: 'All',
buttonWidth:'250px',
includeSelectAllOption: true,
maxHeight: 400,
enableFiltering:true
});
});
</script>
</code></pre>
|
[
{
"answer_id": 74667190,
"author": "raykay",
"author_id": 18357803,
"author_profile": "https://Stackoverflow.com/users/18357803",
"pm_score": 0,
"selected": false,
"text": "let buttons = document.querySelectorAll('button');\nlet currentButton = 0;\n\ndocument.body.addEventListener('keypress', e => {\n if (e.key == 'b') {\n e.preventDefault();\n currentButton++; // move to the next button in the list\n if (currentButton >= buttons.length) {\n currentButton = 0; // loop back to the first button if we reach the end of the list\n }\n buttons[currentButton].focus();\n }\n});\n"
},
{
"answer_id": 74667288,
"author": "ths",
"author_id": 6388552,
"author_profile": "https://Stackoverflow.com/users/6388552",
"pm_score": 2,
"selected": true,
"text": "data-* data-is-focused 1 0 data-is-focused JavaScript 0 1 data-is-focused 0 \"b\" data-is-focused 1 0 0 const btns = Array.from(document.querySelectorAll(\"button\")),\n /**\n * guess the index of the buitton to be focused based on the index of the currently focused button and whether we want to walk forwards or backwards.\n */\n guessNextButtonIndex = (focusedBtnIndex, inReverseOrder) => {\n return inReverseOrder\n ? (focusedBtnIndex <= 0 ? btns.length - 1 : focusedBtnIndex - 1) \n : (focusedBtnIndex === -1 || focusedBtnIndex === btns.length - 1 ? 0 : focusedBtnIndex + 1);\n };\n\ndocument.body.addEventListener(\"keydown\", e => {\n // because we accept shift key, when you press shift + \"b\" the output will be \"B\" (uppercased) so we need to transform that to lower case.\n if (e.key.toLowerCase() === \"b\") {\n // get the index of the currently focused button based on the data-is-focused attribute. If no button is focused, -1 is returned.\n const idx = btns.findIndex(btn => btn.dataset.isFocused == 1),\n btnToFocus = btns[guessNextButtonIndex(idx, e.shiftKey)];\n // set the data-is-focused of the last focused button to \"0\"\n idx !== -1 && (btns[idx].dataset.isFocused = 0);\n // set the data-is-focused of the button to be focused to \"1\"\n btnToFocus.dataset.isFocused = 1;\n // focus the button to be focused\n btnToFocus.focus();\n }\n}); <button>Button 1</button><br>\n<button>Button 2</button><br>\n<button>Button 3</button><br>\n<button>Button 4</button><br>\n<button>Button 5</button><br>"
},
{
"answer_id": 74667616,
"author": "Jagdish Ahir",
"author_id": 20674763,
"author_profile": "https://Stackoverflow.com/users/20674763",
"pm_score": 0,
"selected": false,
"text": " const boxes = document.querySelectorAll('button');\n var boxesLength = boxes.length;\n for (var i = 0; i < boxesLength; i++) {\n boxes[i].addEventListener('click', function (i) {\n var findnextbtn;\n if ((boxesLength - 1) == i) {\n removeStyle();\n findnextbtn = boxes[0];\n } else {\n removeStyle();\n findnextbtn = boxes[i + 1];\n }\n findnextbtn.setAttribute('style', 'background-color: yellow;');\n }.bind(null, i));\n }\n function removeStyle() {\n boxes.forEach(box => {\n box.setAttribute('style', 'background-color: none;');\n });\n } <button>Button 1</button><br>\n<button>Button 2</button><br>\n<button>Button 3</button><br>\n<button>Button 4</button><br>\n<button>Button 5</button><br>"
},
{
"answer_id": 74667828,
"author": "Muhammad Salman",
"author_id": 15715337,
"author_profile": "https://Stackoverflow.com/users/15715337",
"pm_score": 0,
"selected": false,
"text": "let btn = document.querySelector(\"button\");\ndocument.body.addEventListener(\"keypress\", (e) => {\n if (e.key == \"b\") {\n e.preventDefault();\n // Get a list of all buttons on the page\n const buttons = document.querySelectorAll(\"button\");\n // Find the next button in the list\n const nextButton = buttons.find((button) => button.tabIndex > btn.tabIndex);\n if (nextButton) {\n // Set focus on the next button\n nextButton.focus();\n }\n }\n});\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20667291/"
] |
74,667,069
|
<p>May I ask on how to add photo background on my website using VS Code?</p>
<p>I tried checking in yt but its not background, it just add up to my website as photo alone.</p>
|
[
{
"answer_id": 74667190,
"author": "raykay",
"author_id": 18357803,
"author_profile": "https://Stackoverflow.com/users/18357803",
"pm_score": 0,
"selected": false,
"text": "let buttons = document.querySelectorAll('button');\nlet currentButton = 0;\n\ndocument.body.addEventListener('keypress', e => {\n if (e.key == 'b') {\n e.preventDefault();\n currentButton++; // move to the next button in the list\n if (currentButton >= buttons.length) {\n currentButton = 0; // loop back to the first button if we reach the end of the list\n }\n buttons[currentButton].focus();\n }\n});\n"
},
{
"answer_id": 74667288,
"author": "ths",
"author_id": 6388552,
"author_profile": "https://Stackoverflow.com/users/6388552",
"pm_score": 2,
"selected": true,
"text": "data-* data-is-focused 1 0 data-is-focused JavaScript 0 1 data-is-focused 0 \"b\" data-is-focused 1 0 0 const btns = Array.from(document.querySelectorAll(\"button\")),\n /**\n * guess the index of the buitton to be focused based on the index of the currently focused button and whether we want to walk forwards or backwards.\n */\n guessNextButtonIndex = (focusedBtnIndex, inReverseOrder) => {\n return inReverseOrder\n ? (focusedBtnIndex <= 0 ? btns.length - 1 : focusedBtnIndex - 1) \n : (focusedBtnIndex === -1 || focusedBtnIndex === btns.length - 1 ? 0 : focusedBtnIndex + 1);\n };\n\ndocument.body.addEventListener(\"keydown\", e => {\n // because we accept shift key, when you press shift + \"b\" the output will be \"B\" (uppercased) so we need to transform that to lower case.\n if (e.key.toLowerCase() === \"b\") {\n // get the index of the currently focused button based on the data-is-focused attribute. If no button is focused, -1 is returned.\n const idx = btns.findIndex(btn => btn.dataset.isFocused == 1),\n btnToFocus = btns[guessNextButtonIndex(idx, e.shiftKey)];\n // set the data-is-focused of the last focused button to \"0\"\n idx !== -1 && (btns[idx].dataset.isFocused = 0);\n // set the data-is-focused of the button to be focused to \"1\"\n btnToFocus.dataset.isFocused = 1;\n // focus the button to be focused\n btnToFocus.focus();\n }\n}); <button>Button 1</button><br>\n<button>Button 2</button><br>\n<button>Button 3</button><br>\n<button>Button 4</button><br>\n<button>Button 5</button><br>"
},
{
"answer_id": 74667616,
"author": "Jagdish Ahir",
"author_id": 20674763,
"author_profile": "https://Stackoverflow.com/users/20674763",
"pm_score": 0,
"selected": false,
"text": " const boxes = document.querySelectorAll('button');\n var boxesLength = boxes.length;\n for (var i = 0; i < boxesLength; i++) {\n boxes[i].addEventListener('click', function (i) {\n var findnextbtn;\n if ((boxesLength - 1) == i) {\n removeStyle();\n findnextbtn = boxes[0];\n } else {\n removeStyle();\n findnextbtn = boxes[i + 1];\n }\n findnextbtn.setAttribute('style', 'background-color: yellow;');\n }.bind(null, i));\n }\n function removeStyle() {\n boxes.forEach(box => {\n box.setAttribute('style', 'background-color: none;');\n });\n } <button>Button 1</button><br>\n<button>Button 2</button><br>\n<button>Button 3</button><br>\n<button>Button 4</button><br>\n<button>Button 5</button><br>"
},
{
"answer_id": 74667828,
"author": "Muhammad Salman",
"author_id": 15715337,
"author_profile": "https://Stackoverflow.com/users/15715337",
"pm_score": 0,
"selected": false,
"text": "let btn = document.querySelector(\"button\");\ndocument.body.addEventListener(\"keypress\", (e) => {\n if (e.key == \"b\") {\n e.preventDefault();\n // Get a list of all buttons on the page\n const buttons = document.querySelectorAll(\"button\");\n // Find the next button in the list\n const nextButton = buttons.find((button) => button.tabIndex > btn.tabIndex);\n if (nextButton) {\n // Set focus on the next button\n nextButton.focus();\n }\n }\n});\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20674647/"
] |
74,667,078
|
<p>i tried to install dependencies of my program and I get a error when execute yarn install on linux os</p>
<p>i execute "yarn install or sudo yarn install" a i get the next error:</p>
<pre><code>An unexpected error occurred: "https://registry.yarnpkg.com/eslint/-/eslint-7.32.0.tgz: connect EACCES 2606:4700::6810:1523:443"
</code></pre>
<p>any ideas?</p>
|
[
{
"answer_id": 74667190,
"author": "raykay",
"author_id": 18357803,
"author_profile": "https://Stackoverflow.com/users/18357803",
"pm_score": 0,
"selected": false,
"text": "let buttons = document.querySelectorAll('button');\nlet currentButton = 0;\n\ndocument.body.addEventListener('keypress', e => {\n if (e.key == 'b') {\n e.preventDefault();\n currentButton++; // move to the next button in the list\n if (currentButton >= buttons.length) {\n currentButton = 0; // loop back to the first button if we reach the end of the list\n }\n buttons[currentButton].focus();\n }\n});\n"
},
{
"answer_id": 74667288,
"author": "ths",
"author_id": 6388552,
"author_profile": "https://Stackoverflow.com/users/6388552",
"pm_score": 2,
"selected": true,
"text": "data-* data-is-focused 1 0 data-is-focused JavaScript 0 1 data-is-focused 0 \"b\" data-is-focused 1 0 0 const btns = Array.from(document.querySelectorAll(\"button\")),\n /**\n * guess the index of the buitton to be focused based on the index of the currently focused button and whether we want to walk forwards or backwards.\n */\n guessNextButtonIndex = (focusedBtnIndex, inReverseOrder) => {\n return inReverseOrder\n ? (focusedBtnIndex <= 0 ? btns.length - 1 : focusedBtnIndex - 1) \n : (focusedBtnIndex === -1 || focusedBtnIndex === btns.length - 1 ? 0 : focusedBtnIndex + 1);\n };\n\ndocument.body.addEventListener(\"keydown\", e => {\n // because we accept shift key, when you press shift + \"b\" the output will be \"B\" (uppercased) so we need to transform that to lower case.\n if (e.key.toLowerCase() === \"b\") {\n // get the index of the currently focused button based on the data-is-focused attribute. If no button is focused, -1 is returned.\n const idx = btns.findIndex(btn => btn.dataset.isFocused == 1),\n btnToFocus = btns[guessNextButtonIndex(idx, e.shiftKey)];\n // set the data-is-focused of the last focused button to \"0\"\n idx !== -1 && (btns[idx].dataset.isFocused = 0);\n // set the data-is-focused of the button to be focused to \"1\"\n btnToFocus.dataset.isFocused = 1;\n // focus the button to be focused\n btnToFocus.focus();\n }\n}); <button>Button 1</button><br>\n<button>Button 2</button><br>\n<button>Button 3</button><br>\n<button>Button 4</button><br>\n<button>Button 5</button><br>"
},
{
"answer_id": 74667616,
"author": "Jagdish Ahir",
"author_id": 20674763,
"author_profile": "https://Stackoverflow.com/users/20674763",
"pm_score": 0,
"selected": false,
"text": " const boxes = document.querySelectorAll('button');\n var boxesLength = boxes.length;\n for (var i = 0; i < boxesLength; i++) {\n boxes[i].addEventListener('click', function (i) {\n var findnextbtn;\n if ((boxesLength - 1) == i) {\n removeStyle();\n findnextbtn = boxes[0];\n } else {\n removeStyle();\n findnextbtn = boxes[i + 1];\n }\n findnextbtn.setAttribute('style', 'background-color: yellow;');\n }.bind(null, i));\n }\n function removeStyle() {\n boxes.forEach(box => {\n box.setAttribute('style', 'background-color: none;');\n });\n } <button>Button 1</button><br>\n<button>Button 2</button><br>\n<button>Button 3</button><br>\n<button>Button 4</button><br>\n<button>Button 5</button><br>"
},
{
"answer_id": 74667828,
"author": "Muhammad Salman",
"author_id": 15715337,
"author_profile": "https://Stackoverflow.com/users/15715337",
"pm_score": 0,
"selected": false,
"text": "let btn = document.querySelector(\"button\");\ndocument.body.addEventListener(\"keypress\", (e) => {\n if (e.key == \"b\") {\n e.preventDefault();\n // Get a list of all buttons on the page\n const buttons = document.querySelectorAll(\"button\");\n // Find the next button in the list\n const nextButton = buttons.find((button) => button.tabIndex > btn.tabIndex);\n if (nextButton) {\n // Set focus on the next button\n nextButton.focus();\n }\n }\n});\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10300298/"
] |
74,667,121
|
<p>So for my to-do list, im trying to show in my view the difference in number of days between the current date and the date that the task is suppose to be completed by. But i cant seem to do that because im using date_diff() function and it only accepts objects and not strings for the data types.</p>
<p>This is the error message</p>
<pre><code>date_diff(): Argument #1 ($baseObject) must be of type DateTimeInterface, string given
</code></pre>
<p>This is my controller</p>
<pre><code>public function saveItem(Request $request) {
$newTask = new task;
if ($request->task == null) {
abort(404);
}
$newTask->tasks = $request->task;
$newTask->is_complete = 0;
$newTask->task_date = date("Y-m-d");
if($request->day === "tomorrow") {
$date = date_create(date("Y-m-d"));
date_add($date, date_interval_create_from_date_string("1 day"));
$newTask->date_of_completion = date_format($date, "Y-m-d");
} elseif($request->day === "today") {
$newTask->date_of_completion = date("Y-m-d");
}
$newTask->save();
return redirect('/');
}
</code></pre>
<p>This is my view</p>
<pre><code><p class="flex items-center px-4 py-1 rounded-lg text-[#555]">{{ date_diff(date("Y-m-d"), date_create($task->date_of_completion)) }}</p>
</code></pre>
<p>If i can find out how to change or use something else to get the current date as an object so that it can be used in my date_diff(), it will really help but if you have a better solution that is much easier, im open it to it as well.</p>
|
[
{
"answer_id": 74667190,
"author": "raykay",
"author_id": 18357803,
"author_profile": "https://Stackoverflow.com/users/18357803",
"pm_score": 0,
"selected": false,
"text": "let buttons = document.querySelectorAll('button');\nlet currentButton = 0;\n\ndocument.body.addEventListener('keypress', e => {\n if (e.key == 'b') {\n e.preventDefault();\n currentButton++; // move to the next button in the list\n if (currentButton >= buttons.length) {\n currentButton = 0; // loop back to the first button if we reach the end of the list\n }\n buttons[currentButton].focus();\n }\n});\n"
},
{
"answer_id": 74667288,
"author": "ths",
"author_id": 6388552,
"author_profile": "https://Stackoverflow.com/users/6388552",
"pm_score": 2,
"selected": true,
"text": "data-* data-is-focused 1 0 data-is-focused JavaScript 0 1 data-is-focused 0 \"b\" data-is-focused 1 0 0 const btns = Array.from(document.querySelectorAll(\"button\")),\n /**\n * guess the index of the buitton to be focused based on the index of the currently focused button and whether we want to walk forwards or backwards.\n */\n guessNextButtonIndex = (focusedBtnIndex, inReverseOrder) => {\n return inReverseOrder\n ? (focusedBtnIndex <= 0 ? btns.length - 1 : focusedBtnIndex - 1) \n : (focusedBtnIndex === -1 || focusedBtnIndex === btns.length - 1 ? 0 : focusedBtnIndex + 1);\n };\n\ndocument.body.addEventListener(\"keydown\", e => {\n // because we accept shift key, when you press shift + \"b\" the output will be \"B\" (uppercased) so we need to transform that to lower case.\n if (e.key.toLowerCase() === \"b\") {\n // get the index of the currently focused button based on the data-is-focused attribute. If no button is focused, -1 is returned.\n const idx = btns.findIndex(btn => btn.dataset.isFocused == 1),\n btnToFocus = btns[guessNextButtonIndex(idx, e.shiftKey)];\n // set the data-is-focused of the last focused button to \"0\"\n idx !== -1 && (btns[idx].dataset.isFocused = 0);\n // set the data-is-focused of the button to be focused to \"1\"\n btnToFocus.dataset.isFocused = 1;\n // focus the button to be focused\n btnToFocus.focus();\n }\n}); <button>Button 1</button><br>\n<button>Button 2</button><br>\n<button>Button 3</button><br>\n<button>Button 4</button><br>\n<button>Button 5</button><br>"
},
{
"answer_id": 74667616,
"author": "Jagdish Ahir",
"author_id": 20674763,
"author_profile": "https://Stackoverflow.com/users/20674763",
"pm_score": 0,
"selected": false,
"text": " const boxes = document.querySelectorAll('button');\n var boxesLength = boxes.length;\n for (var i = 0; i < boxesLength; i++) {\n boxes[i].addEventListener('click', function (i) {\n var findnextbtn;\n if ((boxesLength - 1) == i) {\n removeStyle();\n findnextbtn = boxes[0];\n } else {\n removeStyle();\n findnextbtn = boxes[i + 1];\n }\n findnextbtn.setAttribute('style', 'background-color: yellow;');\n }.bind(null, i));\n }\n function removeStyle() {\n boxes.forEach(box => {\n box.setAttribute('style', 'background-color: none;');\n });\n } <button>Button 1</button><br>\n<button>Button 2</button><br>\n<button>Button 3</button><br>\n<button>Button 4</button><br>\n<button>Button 5</button><br>"
},
{
"answer_id": 74667828,
"author": "Muhammad Salman",
"author_id": 15715337,
"author_profile": "https://Stackoverflow.com/users/15715337",
"pm_score": 0,
"selected": false,
"text": "let btn = document.querySelector(\"button\");\ndocument.body.addEventListener(\"keypress\", (e) => {\n if (e.key == \"b\") {\n e.preventDefault();\n // Get a list of all buttons on the page\n const buttons = document.querySelectorAll(\"button\");\n // Find the next button in the list\n const nextButton = buttons.find((button) => button.tabIndex > btn.tabIndex);\n if (nextButton) {\n // Set focus on the next button\n nextButton.focus();\n }\n }\n});\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19012424/"
] |
74,667,137
|
<p>our electricity provider think it could be very fun to make difficult to read csv files they provide.</p>
<p>This is precise electric consumption, every 30 min but in the SAME column you have hours, and date, example :</p>
<p>[EDIT : here the raw version of the csv file, my bad]</p>
<pre><code>;
"Récapitulatif de mes puissances atteintes en W";
;
"Date et heure de relève par le distributeur";"Puissance atteinte (W)"
;
"19/11/2022";
"00:00:00";4494
"23:30:00";1174
"23:00:00";1130
[...]
"01:30:00";216
"01:00:00";2672
"00:30:00";2816
;
"18/11/2022";
"00:00:00";4494
"23:30:00";1174
"23:00:00";1130
[...]
"01:30:00";216
"01:00:00";2672
"00:30:00";2816
</code></pre>
<p>How damn can I obtain this kind of lovely formated file :</p>
<pre><code>2022-11-19 00:00:00 2098
2022-11-19 23:30:00 218
2022-11-19 23:00:00 606
</code></pre>
<p>etc.</p>
|
[
{
"answer_id": 74667242,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\n\ncurrent_date = None\nall_data = []\nwith open(\"your_file.txt\", \"r\") as f_in:\n # skip first 5 rows (header)\n for _ in range(5):\n next(f_in)\n\n for row in map(str.strip, f_in):\n row = row.replace('\"', \"\")\n if row == \"\":\n continue\n if \"/\" in row:\n current_date = row\n else:\n all_data.append([current_date, *row.split(\";\")])\n\ndf = pd.DataFrame(all_data, columns=[\"Date\", \"Time\", \"Value\"])\nprint(df)\n Date Time Value\n0 19/11/2022; 00:00:00 4494\n1 19/11/2022; 23:30:00 1174\n2 19/11/2022; 23:00:00 1130\n3 19/11/2022; 01:30:00 216\n4 19/11/2022; 01:00:00 2672\n5 19/11/2022; 00:30:00 2816\n6 18/11/2022; 00:00:00 4494\n7 18/11/2022; 23:30:00 1174\n8 18/11/2022; 23:00:00 1130\n9 18/11/2022; 01:30:00 216\n10 18/11/2022; 01:00:00 2672\n11 18/11/2022; 00:30:00 2816\n"
},
{
"answer_id": 74667252,
"author": "wallbloggerbeing",
"author_id": 16581025,
"author_profile": "https://Stackoverflow.com/users/16581025",
"pm_score": 0,
"selected": false,
"text": "import itertools\ndList = [f\"{f}/{s}/2022\" for f, s in itertools.product(range(1, 32), range(1, 13))]\n file = 'yourfilename.txt'\n#make sure youre running the program in the same directory as the .txt file\nwith open(file, \"r\") as f:\n global lines\n lines = f.readlines()\nlines = [word.replace('\\n','') for word in lines]\nfor i in lines:\n if i in dList:\n curD = i\n else:\n with open('output.txt', 'w') as g:\n g.write(f'{i} {(i.split())[0]} {(i.split())[1]}')\n"
},
{
"answer_id": 74667367,
"author": "meti",
"author_id": 8704180,
"author_profile": "https://Stackoverflow.com/users/8704180",
"pm_score": 0,
"selected": false,
"text": "data.csv 19/11/2022 \n00:00:00 2098\n23:30:00 218\n23:00:00 606\n01:30:00 216\n01:00:00 2672\n00:30:00 2816\n18/11/2022 \n00:00:00 1994\n23:30:00 260\n23:00:00 732\n01:30:00 200\n01:00:00 1378\n00:30:00 2520\n17/11/2022 \n00:00:00 1830\n23:30:00 96\n23:00:00 122\n01:30:00 694\n01:00:00 2950\n00:30:00 3062\n16/11/2022 \n00:00:00 2420\n23:30:00 678\n23:00:00 644\n Implementation import pandas as pd\ndf = pd.read_csv('data.csv', header=None)\ndf['amount'] = df[0].apply(lambda item:item.split(' ')[-1] if item.find(':')>0 else None)\ndf['time'] = df[0].apply(lambda item:item.split(' ')[0] if item.find(':')>0 else None)\ndf['date'] = df[0].apply(lambda item:item if item.find('/')>0 else None)\ndf['date'] = df['date'].fillna(method='ffill')\ndf = df.dropna(subset=['amount'], how='any')\ndf = df.drop(0, axis=1)\nprint(df)\n output amount time date\n1 2098 00:00:00 19/11/2022 \n2 218 23:30:00 19/11/2022 \n3 606 23:00:00 19/11/2022 \n4 216 01:30:00 19/11/2022 \n5 2672 01:00:00 19/11/2022 \n6 2816 00:30:00 19/11/2022 \n8 1994 00:00:00 18/11/2022 \n9 260 23:30:00 18/11/2022 \n10 732 23:00:00 18/11/2022 \n11 200 01:30:00 18/11/2022 \n12 1378 01:00:00 18/11/2022 \n13 2520 00:30:00 18/11/2022 \n15 1830 00:00:00 17/11/2022 \n16 96 23:30:00 17/11/2022 \n17 122 23:00:00 17/11/2022 \n18 694 01:30:00 17/11/2022 \n19 2950 01:00:00 17/11/2022 \n20 3062 00:30:00 17/11/2022 \n22 2420 00:00:00 16/11/2022 \n23 678 23:30:00 16/11/2022 \n24 644 23:00:00 16/11/2022 \n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18618577/"
] |
74,667,141
|
<p>I have an object that looks like this :</p>
<pre><code>{
"mark": [
{
"id":1,
"name": "mark",
"age":26
},
{
"id":2,
"name": "mark",
"age":25
}
],
"jack": [
{
"id":1,
"name": "jack",
"age":26
},
{
"id":2,
"name": "jack",
"age": 24,
}
]
}
</code></pre>
<p>WHAT I GOT AS OUTPUT IF A NEW USER IS ADDED IT IS NOT APPENDED, BUT IT IS OVERWRITTEN OR CREATED AS A NEW OBJECT</p>
<pre><code>{
"mark": [
{
"id":1,
"name": "mark",
"age":26
},
{
"id":2,
"name": "mark",
"age":25
}
],
"jack": [
{
"id":1,
"name": "jack",
"age":26
},
{
"id":2,
"name": "jack",
"age": 24,
}
],
} "Josh": [
{
"id":1,
"name": "Josh",
"age":26
},
{
"id":2,
"name": "Josh",
"age": 24,
}
]
</code></pre>
<p><em><strong>Expected</strong></em></p>
<p>if new person data arrives in my JSON File, that should be appended to the next array with key values of array of Objects,</p>
<p>like</p>
<pre><code> {
"mark": [
{
"id":1,
"name": "mark",
"age":26
},
{
"id":2,
"name": "mark",
"age":25
}
],
"jack": [
{
"id":1,
"name": "jack",
"age":26
},
{
"id":2,
"name": "jack",
"age": 24,
}
],
"Josh": [
{
"id":1,
"name": "Josh",
"age":26
},
{
"id":2,
"name": "Josh",
"age": 24,
}
]
}
</code></pre>
<p>I've tried this method after reading the JSON file</p>
<pre><code>var newObject = array.reduce(function (obj, value) {
var key = `${value.name}`;
if (obj[key] == null) obj[key] = [];
obj[key].push(value);
return obj;
}, {});
console.log(newObject);
fs.appendFile("users.json", newObject, (err) => {
res.send(JSON.stringify(newObject));
});
</code></pre>
|
[
{
"answer_id": 74667262,
"author": "Dan Philip Bejoy",
"author_id": 6412847,
"author_profile": "https://Stackoverflow.com/users/6412847",
"pm_score": 0,
"selected": false,
"text": "const data = fs.readFileSync('users.json');\n.\n.\nfs.writeFileSync('users.json', {...data, ...newObject});\n"
},
{
"answer_id": 74667673,
"author": "danh",
"author_id": 294949,
"author_profile": "https://Stackoverflow.com/users/294949",
"pm_score": 2,
"selected": false,
"text": "import { promises as fs } from 'fs'; // or require('fs').promises\n\n// inside the OP's route\n const filename = 'users.json';\n try {\n const array = await fs.readFile(filename);\n\n // OP's code here\n // const newObject = array.reduce(...\n\n await fs.writeFile(filename, newObject);\n return res.send(JSON.stringify(newObject));\n\n } catch (error) {\n return res.status(500).send({ message: 'error' });\n }\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20117097/"
] |
74,667,144
|
<p><a href="https://i.stack.imgur.com/9rTcj.png" rel="nofollow noreferrer">ValueError: could not broadcast input array from shape (200,200,3) into shape (200,200)</a></p>
<pre><code>img_000= np.array(img_00)
</code></pre>
|
[
{
"answer_id": 74667178,
"author": "solac34",
"author_id": 20554831,
"author_profile": "https://Stackoverflow.com/users/20554831",
"pm_score": 1,
"selected": false,
"text": "np.asarray(img_00)\n"
},
{
"answer_id": 74669010,
"author": "hpaulj",
"author_id": 901925,
"author_profile": "https://Stackoverflow.com/users/901925",
"pm_score": 0,
"selected": false,
"text": "In [72]: alist = [np.ones((3,3,3)), np.zeros((3,3))]\n\nIn [73]: np.array(alist)\nC:\\Users\\paul\\AppData\\Local\\Temp\\ipykernel_7196\\2629805649.py:1: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.\n np.array(alist)\n---------------------------------------------------------------------------\nValueError Traceback (most recent call last)\nInput In [73], in <cell line: 1>()\n----> 1 np.array(alist)\n\nValueError: could not broadcast input array from shape (3,3,3) into shape (3,3)\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19535251/"
] |
74,667,168
|
<p>I have 2 inputs: i (the integer), length (how many bytes the integer should be encoded).</p>
<p>how can I convert integer to bytes only with bitwise operations.</p>
<pre><code>def int_to_bytes(i, length):
for _ in range(length):
pass
</code></pre>
|
[
{
"answer_id": 74667175,
"author": "AKX",
"author_id": 51685,
"author_profile": "https://Stackoverflow.com/users/51685",
"pm_score": 2,
"selected": false,
"text": "int.to_bytes >>> (1234).to_bytes(16, \"little\")\nb'\\xd2\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n def int_to_bytes(i, length):\n return i.to_bytes(length, \"little\")\n big def int_to_bytes(i, length):\n buf = bytearray(length)\n for j in range(length):\n buf[j] = i & 0xFF\n i >>= 8\n return bytes(buf)\n\nprint(int_to_bytes(1234, 4))\n"
},
{
"answer_id": 74667332,
"author": "Cyzanfar",
"author_id": 3307520,
"author_profile": "https://Stackoverflow.com/users/3307520",
"pm_score": 2,
"selected": true,
"text": "def int_to_bytes(i, length):\n result = bytearray(length)\n for index in range(length):\n result[index] = i & 0xff\n i >>= 8\n return result\n int_to_bytes(0x12345678, 4)\n# returns bytearray(b'\\x78\\x56\\x34\\x12')\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12251690/"
] |
74,667,170
|
<p>I'm running my website on localhost , when I upload files the uploaded file stored in htdocs (local host file) so i want to change the location to my project assets file which is in other location than localhost files
this is my code :</p>
<pre><code><?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
$image = $_POST['file'];
$name = $_POST['name'];
$file = base64_decode($image);
file_put_contents($name , $file);
echo 'upload is finished';
?>
</code></pre>
|
[
{
"answer_id": 74667175,
"author": "AKX",
"author_id": 51685,
"author_profile": "https://Stackoverflow.com/users/51685",
"pm_score": 2,
"selected": false,
"text": "int.to_bytes >>> (1234).to_bytes(16, \"little\")\nb'\\xd2\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n def int_to_bytes(i, length):\n return i.to_bytes(length, \"little\")\n big def int_to_bytes(i, length):\n buf = bytearray(length)\n for j in range(length):\n buf[j] = i & 0xFF\n i >>= 8\n return bytes(buf)\n\nprint(int_to_bytes(1234, 4))\n"
},
{
"answer_id": 74667332,
"author": "Cyzanfar",
"author_id": 3307520,
"author_profile": "https://Stackoverflow.com/users/3307520",
"pm_score": 2,
"selected": true,
"text": "def int_to_bytes(i, length):\n result = bytearray(length)\n for index in range(length):\n result[index] = i & 0xff\n i >>= 8\n return result\n int_to_bytes(0x12345678, 4)\n# returns bytearray(b'\\x78\\x56\\x34\\x12')\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17563478/"
] |
74,667,173
|
<p>I'm practicing format fuction and when I use this code with \t in it, the first 9 output did not have any big space
`</p>
<pre><code>import random
lst = [random.randint(1,100) for i in range(51)]
for index, val in enumerate(lst):
print(f'{index=}\t{val=}')
</code></pre>
<p>`</p>
<p>It works with \n but not \t, I don't know why. Can anyone explain it?</p>
|
[
{
"answer_id": 74667175,
"author": "AKX",
"author_id": 51685,
"author_profile": "https://Stackoverflow.com/users/51685",
"pm_score": 2,
"selected": false,
"text": "int.to_bytes >>> (1234).to_bytes(16, \"little\")\nb'\\xd2\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n def int_to_bytes(i, length):\n return i.to_bytes(length, \"little\")\n big def int_to_bytes(i, length):\n buf = bytearray(length)\n for j in range(length):\n buf[j] = i & 0xFF\n i >>= 8\n return bytes(buf)\n\nprint(int_to_bytes(1234, 4))\n"
},
{
"answer_id": 74667332,
"author": "Cyzanfar",
"author_id": 3307520,
"author_profile": "https://Stackoverflow.com/users/3307520",
"pm_score": 2,
"selected": true,
"text": "def int_to_bytes(i, length):\n result = bytearray(length)\n for index in range(length):\n result[index] = i & 0xff\n i >>= 8\n return result\n int_to_bytes(0x12345678, 4)\n# returns bytearray(b'\\x78\\x56\\x34\\x12')\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14420872/"
] |
74,667,174
|
<p>I tried to implement a logout test method through selenium in Spring Boot but I cannot detect dropdown menu located top right hand side.</p>
<p>How can I fix it?</p>
<p>Here is the test method shown below.</p>
<pre><code>@Test
@Order(4)
public void logout() throws InterruptedException {
login();
driver.get("https://github.com");
Thread.sleep(1000);
// Header-item position-relative mr-0 d-none d-md-flex
WebElement profileDropdown = driver.findElement(By.cssSelector(".Header-item.position-relative.mr-0.d-none.d-md-flex")); // cannot work
// dropdown-item dropdown-signout
WebElement signOutButton = driver.findElement(By.cssSelector(".dropdown-item.dropdown-signout")); // cannot work
profileDropdown.click();
Thread.sleep(1000);
signOutButton.click();
}
</code></pre>
<p>Here is the error part shown below</p>
<pre><code>java.net.SocketException: Connection reset
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":".dropdown-item.dropdown-signout"}
</code></pre>
<p>1st Edited</p>
<pre><code>String xpathProfile = "//*[@aria-label='View profile and more']";
WebElement profileDropdown = driver.findElement(By.xpath(xpathProfile));
String xpathSignOut = "//button[contains(@class,'dropdown-signout')]";
WebElement signOutButton = driver.findElement(By.xpath(xpathSignOut));
</code></pre>
<p>I got this issue shown below.</p>
<pre><code>org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//button[contains(@class,'dropdown-signout')]"}
</code></pre>
|
[
{
"answer_id": 74667679,
"author": "Shatas",
"author_id": 4054411,
"author_profile": "https://Stackoverflow.com/users/4054411",
"pm_score": 0,
"selected": false,
"text": "String xpathProfile = \"//*[@aria-label='View profile and more']\"; \nString xpathSignOut = \"//button[contains(@class,'dropdown-signout')]\";\n ChromeOptions options = new ChromeOptions();\noptions.addArgument(\"--window-size=1920,1080\");\nChromeDriver driver = new ChromeDriver(options);\n"
},
{
"answer_id": 74668322,
"author": "S.N",
"author_id": 5719229,
"author_profile": "https://Stackoverflow.com/users/5719229",
"pm_score": 1,
"selected": false,
"text": "public void logout() throws InterruptedException {\n\n login();\n\n driver.get(\"https://github.com\");\n Thread.sleep(1000);\n\n // Header-item position-relative mr-0 d-none d-md-flex\n WebElement profileDropdown = driver.findElement(By.cssSelector(\".Header-item.position-relative.mr-0.d-none.d-md-flex\"));\n profileDropdown.click();\n\n Thread.sleep(1000);\n\n // dropdown-item dropdown-signout\n WebElement signOutButton = driver.findElement(By.cssSelector(\".dropdown-item.dropdown-signout\"));\n signOutButton.click();\n\n Thread.sleep(2000);\n \n }\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5719229/"
] |
74,667,211
|
<p>i am a web developer (php, js, css and ...).
i order a python script for remove image background. it worked in cmd very well but when running it from php script, it dosnt work.
i look at the script for find problem and i realized that the script stops at this line:</p>
<pre><code>net.load_state_dict(self.torch.load(os.path.join("../library/removeBG/models/", name, name + '.pth'), map_location="cpu"))
</code></pre>
<p>I guess the problem with the script is that it can't find the file, and probably the problem is caused by the path that os.path points to.
Is it possible to print the path that os .path points to?
If not, do you have a solution to this problem?</p>
|
[
{
"answer_id": 74667679,
"author": "Shatas",
"author_id": 4054411,
"author_profile": "https://Stackoverflow.com/users/4054411",
"pm_score": 0,
"selected": false,
"text": "String xpathProfile = \"//*[@aria-label='View profile and more']\"; \nString xpathSignOut = \"//button[contains(@class,'dropdown-signout')]\";\n ChromeOptions options = new ChromeOptions();\noptions.addArgument(\"--window-size=1920,1080\");\nChromeDriver driver = new ChromeDriver(options);\n"
},
{
"answer_id": 74668322,
"author": "S.N",
"author_id": 5719229,
"author_profile": "https://Stackoverflow.com/users/5719229",
"pm_score": 1,
"selected": false,
"text": "public void logout() throws InterruptedException {\n\n login();\n\n driver.get(\"https://github.com\");\n Thread.sleep(1000);\n\n // Header-item position-relative mr-0 d-none d-md-flex\n WebElement profileDropdown = driver.findElement(By.cssSelector(\".Header-item.position-relative.mr-0.d-none.d-md-flex\"));\n profileDropdown.click();\n\n Thread.sleep(1000);\n\n // dropdown-item dropdown-signout\n WebElement signOutButton = driver.findElement(By.cssSelector(\".dropdown-item.dropdown-signout\"));\n signOutButton.click();\n\n Thread.sleep(2000);\n \n }\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5511768/"
] |
74,667,223
|
<p>(<a href="https://i.stack.imgur.com/2zm2w.png" rel="nofollow noreferrer">https://i.stack.imgur.com/2zm2w.png</a>)</p>
<pre><code>collectionData(queryRef).subscribe((data) => {
for (const each of data) {
this.getCourse(each.courseId)
.pipe(take(1))
.subscribe((courseData) => {
const course = courseData[0];
console.log(course);
this.getLecturer(course.lecturerId).pipe(take(1)).subscribe((res: any)=>{
const lecturer = res[0];
course.lecturerName = lecturer.lecturerName;
course.lecturerImageUrl = lecturer.lecturerImageUrl;
});
recentVisit.push(course);
});
}
});
</code></pre>
<p>Hi I am still new to the rxjs of Angular.
I am building an Ionic app using Angular Fire.
I'm currently facing some problems here, I'm using Firebase as my backend, and I would have to query through different collections to fetch my data. For example, the first subscription only fetch user course enroll data like courseId, progress..., the second subscription would fetch the course details, and the third will fetch lecturer details. Can anyone give some suggestion on how to avoid using nested subscription because many people said it is not recommended to do so.
I would be very appreciated if you can provide some detailed explainations because I really only know the basics of rxjs.</p>
<p>I have tried concatMap but it shows firebase error(<a href="https://i.stack.imgur.com/6SOS0.png" rel="nofollow noreferrer">https://i.stack.imgur.com/6SOS0.png</a>)]</p>
<p><img src="https://i.stack.imgur.com/jgMwV.png" alt="" /></p>
<pre><code>collectionData(queryRef)
.pipe(
concatMap((res: any) => this.getCourse(res.courseId))
//concatMap((result2: any) => this.getLecturer(result2.lecturerId))
)
.subscribe((res) => {
console.log(res);
});
</code></pre>
<p>But actually I also not sure did I did it right because I really cannot understand how concatMap works.</p>
|
[
{
"answer_id": 74667795,
"author": "DaumannM",
"author_id": 11896081,
"author_profile": "https://Stackoverflow.com/users/11896081",
"pm_score": -1,
"selected": false,
"text": "forkJoin(\n {\n a: this.http.call1()..\n b: this.http.call2()..\n c: this.http.call3()..\n }).subscribe()\n\n"
},
{
"answer_id": 74671028,
"author": "kellermat",
"author_id": 20035486,
"author_profile": "https://Stackoverflow.com/users/20035486",
"pm_score": 1,
"selected": false,
"text": "switchMap forkJoin getMergedCourseDetails() /* Initialize all information about the courses */\n\nngOnInit(): void {\n this.collectionData(this.queryRef).pipe(\n switchMap(data => {\n if (data.length) {\n\n // Create an observable (backend-request) for each course-id:\n const courseObs = data.map(c => this.getCourse(c.courseId));\n\n // Execute the array of backend-requests via forkJoin():\n return courseObs.length ? forkJoin(courseObs) : of([]);\n }\n return of([]);\n }),\n switchMap((courseDataList: Course[][]) => { \n if (courseDataList.length) {\n\n // Get the first course from each course array (as defined in SO question):\n const courses = courseDataList.filter(c => c.length).map(c => c[0]);\n\n // Create observables to retrieve additional details for each of the courses:\n const detailInfoObs = courses.map(c => this.getMergedCourseDetails(c));\n\n // Execute the created observables via forkJoin():\n return detailInfoObs.length ? forkJoin(detailInfoObs) : of([]);\n }\n return of([]);\n }),\n tap((courseList: Course[]) => {\n courseList.forEach(d => {\n console.log('Lecturer Id:', d.lecturerId);\n console.log('Lecturer Name:', d.lecturerName);\n console.log('Lecturer ImageUrl:', d.lecturerImageUrl);\n });\n }) \n )\n .subscribe();\n}\n\n/* Enrich existing course-data with lecturer-details */\n\nprivate getMergedCourseDetails(course: Course): Observable<Course> {\n return this.getLecturer(course.lecturerId).pipe( \n map(lecturers => \n // Merge existing course-data with newly retrieved lecturer-details: \n ({...course,\n lecturerName: lecturers[0]?.lecturerName ?? '', \n lecturerImageUrl: lecturers[0]?.lecturerImageUrl ?? '' } as Course))\n );\n}\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20674766/"
] |
74,667,250
|
<p>I have a struct defined like the following (other fields removed for brevity):</p>
<pre><code>use chrono::{
DateTime,
Utc
};
use serde::{
Deserialize,
Serialize
};
#[derive(
Clone, Debug, PartialEq, Eq, Serialize, Deserialize
)]
pub struct Test {
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")]
pub time_period: Option<Vec<DateTime<Utc>>>
}
</code></pre>
<p>And I'm using the following dependencies:</p>
<pre><code>bson = { version = "^2.4", default-features = false, features = [ "chrono-0_4" ] }
chrono = "^0.4"
serde = { version = "^1.0", default-features = false, features = [ "derive" ] }
</code></pre>
<p>But <code>serde</code> derivations throw error, because there is type mismatch. It expects a <code>DateTime</code> object, but we have an optional vector here. Any ideas how to serialize optional vector of <code>DateTime</code> objects?</p>
|
[
{
"answer_id": 74667795,
"author": "DaumannM",
"author_id": 11896081,
"author_profile": "https://Stackoverflow.com/users/11896081",
"pm_score": -1,
"selected": false,
"text": "forkJoin(\n {\n a: this.http.call1()..\n b: this.http.call2()..\n c: this.http.call3()..\n }).subscribe()\n\n"
},
{
"answer_id": 74671028,
"author": "kellermat",
"author_id": 20035486,
"author_profile": "https://Stackoverflow.com/users/20035486",
"pm_score": 1,
"selected": false,
"text": "switchMap forkJoin getMergedCourseDetails() /* Initialize all information about the courses */\n\nngOnInit(): void {\n this.collectionData(this.queryRef).pipe(\n switchMap(data => {\n if (data.length) {\n\n // Create an observable (backend-request) for each course-id:\n const courseObs = data.map(c => this.getCourse(c.courseId));\n\n // Execute the array of backend-requests via forkJoin():\n return courseObs.length ? forkJoin(courseObs) : of([]);\n }\n return of([]);\n }),\n switchMap((courseDataList: Course[][]) => { \n if (courseDataList.length) {\n\n // Get the first course from each course array (as defined in SO question):\n const courses = courseDataList.filter(c => c.length).map(c => c[0]);\n\n // Create observables to retrieve additional details for each of the courses:\n const detailInfoObs = courses.map(c => this.getMergedCourseDetails(c));\n\n // Execute the created observables via forkJoin():\n return detailInfoObs.length ? forkJoin(detailInfoObs) : of([]);\n }\n return of([]);\n }),\n tap((courseList: Course[]) => {\n courseList.forEach(d => {\n console.log('Lecturer Id:', d.lecturerId);\n console.log('Lecturer Name:', d.lecturerName);\n console.log('Lecturer ImageUrl:', d.lecturerImageUrl);\n });\n }) \n )\n .subscribe();\n}\n\n/* Enrich existing course-data with lecturer-details */\n\nprivate getMergedCourseDetails(course: Course): Observable<Course> {\n return this.getLecturer(course.lecturerId).pipe( \n map(lecturers => \n // Merge existing course-data with newly retrieved lecturer-details: \n ({...course,\n lecturerName: lecturers[0]?.lecturerName ?? '', \n lecturerImageUrl: lecturers[0]?.lecturerImageUrl ?? '' } as Course))\n );\n}\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12103188/"
] |
74,667,255
|
<pre><code>import React from "react";
import "./App.css"
import Navbar from "./components/Navbar/Navbar";
import Home from "./components/Home/Home"
import About from "./components/About/About";
import { BrowserRouter,Route,Routes,Router } from "react-router-dom";
export default function App()
{
return(
<div>
<Navbar />
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path='about' element={<About/>} />
</Routes>
</BrowserRouter>
</div>
)
</code></pre>
<p>}</p>
<p>this is my app component</p>
<pre><code>import React from "react";
import {Link} from "react-router-dom";
export default function Navbar()
{
return(
<nav>
<Link to='/'> Home</Link>
<Link to='/about'>About</Link>
</nav>
)
</code></pre>
<p>}</p>
<p>this is my nav component
The issue whenever i try to load from the URL without adding a navbar my component works perfectly fine but after i add navbar it doesn't works</p>
|
[
{
"answer_id": 74667795,
"author": "DaumannM",
"author_id": 11896081,
"author_profile": "https://Stackoverflow.com/users/11896081",
"pm_score": -1,
"selected": false,
"text": "forkJoin(\n {\n a: this.http.call1()..\n b: this.http.call2()..\n c: this.http.call3()..\n }).subscribe()\n\n"
},
{
"answer_id": 74671028,
"author": "kellermat",
"author_id": 20035486,
"author_profile": "https://Stackoverflow.com/users/20035486",
"pm_score": 1,
"selected": false,
"text": "switchMap forkJoin getMergedCourseDetails() /* Initialize all information about the courses */\n\nngOnInit(): void {\n this.collectionData(this.queryRef).pipe(\n switchMap(data => {\n if (data.length) {\n\n // Create an observable (backend-request) for each course-id:\n const courseObs = data.map(c => this.getCourse(c.courseId));\n\n // Execute the array of backend-requests via forkJoin():\n return courseObs.length ? forkJoin(courseObs) : of([]);\n }\n return of([]);\n }),\n switchMap((courseDataList: Course[][]) => { \n if (courseDataList.length) {\n\n // Get the first course from each course array (as defined in SO question):\n const courses = courseDataList.filter(c => c.length).map(c => c[0]);\n\n // Create observables to retrieve additional details for each of the courses:\n const detailInfoObs = courses.map(c => this.getMergedCourseDetails(c));\n\n // Execute the created observables via forkJoin():\n return detailInfoObs.length ? forkJoin(detailInfoObs) : of([]);\n }\n return of([]);\n }),\n tap((courseList: Course[]) => {\n courseList.forEach(d => {\n console.log('Lecturer Id:', d.lecturerId);\n console.log('Lecturer Name:', d.lecturerName);\n console.log('Lecturer ImageUrl:', d.lecturerImageUrl);\n });\n }) \n )\n .subscribe();\n}\n\n/* Enrich existing course-data with lecturer-details */\n\nprivate getMergedCourseDetails(course: Course): Observable<Course> {\n return this.getLecturer(course.lecturerId).pipe( \n map(lecturers => \n // Merge existing course-data with newly retrieved lecturer-details: \n ({...course,\n lecturerName: lecturers[0]?.lecturerName ?? '', \n lecturerImageUrl: lecturers[0]?.lecturerImageUrl ?? '' } as Course))\n );\n}\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17582110/"
] |
74,667,264
|
<p>i need to count longest 01 from list
ex:</p>
<pre><code>[1,1,1,0,0,1,1,1,0,1,0,1,0,1,0]
</code></pre>
<p>suppose to print 4 (sequence could also start with 10):</p>
<pre><code>1,0,1,0 = 2
</code></pre>
<pre><code>import itertools
with open("file.txt", 'r+') as file:
file_context = file.read()
print(file_context)
def func1(arg):
global key
key = list(arg)
print(key)
func1(file_context)
A = [0,1,0,1]
key2 = [ int(x) for x in key ]
c=0
k = max(len(list(lent)) for (A[c],lent) in itertools.groupby(A) if A[c]==0 and A[c+1]==1)
print(k)
</code></pre>
|
[
{
"answer_id": 74667795,
"author": "DaumannM",
"author_id": 11896081,
"author_profile": "https://Stackoverflow.com/users/11896081",
"pm_score": -1,
"selected": false,
"text": "forkJoin(\n {\n a: this.http.call1()..\n b: this.http.call2()..\n c: this.http.call3()..\n }).subscribe()\n\n"
},
{
"answer_id": 74671028,
"author": "kellermat",
"author_id": 20035486,
"author_profile": "https://Stackoverflow.com/users/20035486",
"pm_score": 1,
"selected": false,
"text": "switchMap forkJoin getMergedCourseDetails() /* Initialize all information about the courses */\n\nngOnInit(): void {\n this.collectionData(this.queryRef).pipe(\n switchMap(data => {\n if (data.length) {\n\n // Create an observable (backend-request) for each course-id:\n const courseObs = data.map(c => this.getCourse(c.courseId));\n\n // Execute the array of backend-requests via forkJoin():\n return courseObs.length ? forkJoin(courseObs) : of([]);\n }\n return of([]);\n }),\n switchMap((courseDataList: Course[][]) => { \n if (courseDataList.length) {\n\n // Get the first course from each course array (as defined in SO question):\n const courses = courseDataList.filter(c => c.length).map(c => c[0]);\n\n // Create observables to retrieve additional details for each of the courses:\n const detailInfoObs = courses.map(c => this.getMergedCourseDetails(c));\n\n // Execute the created observables via forkJoin():\n return detailInfoObs.length ? forkJoin(detailInfoObs) : of([]);\n }\n return of([]);\n }),\n tap((courseList: Course[]) => {\n courseList.forEach(d => {\n console.log('Lecturer Id:', d.lecturerId);\n console.log('Lecturer Name:', d.lecturerName);\n console.log('Lecturer ImageUrl:', d.lecturerImageUrl);\n });\n }) \n )\n .subscribe();\n}\n\n/* Enrich existing course-data with lecturer-details */\n\nprivate getMergedCourseDetails(course: Course): Observable<Course> {\n return this.getLecturer(course.lecturerId).pipe( \n map(lecturers => \n // Merge existing course-data with newly retrieved lecturer-details: \n ({...course,\n lecturerName: lecturers[0]?.lecturerName ?? '', \n lecturerImageUrl: lecturers[0]?.lecturerImageUrl ?? '' } as Course))\n );\n}\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20674825/"
] |
74,667,269
|
<p>I am doing cohort analysis and the dataset I'm using has 15 months as the name as columns with revenue and around 7k user_id rows.
I need to get a new column with the month when the user was last time active.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>2021-01-01</th>
<th>2021-02-01</th>
</tr>
</thead>
<tbody>
<tr>
<td>3456.</td>
<td>Nan</td>
</tr>
<tr>
<td>Nan.</td>
<td>8679</td>
</tr>
</tbody>
</table>
</div>
<p>Result should be like this</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>2021-01-01</th>
<th>2021-02-01</th>
<th>Last_month</th>
</tr>
</thead>
<tbody>
<tr>
<td>3456.</td>
<td>Nan</td>
<td>2021-01-01</td>
</tr>
<tr>
<td>Nan.</td>
<td>8679</td>
<td>2021-02-01</td>
</tr>
</tbody>
</table>
</div>
<p>I have tried few options but it didnt work</p>
<p>users.apply(pd.Series.last_valid_index)</p>
|
[
{
"answer_id": 74667352,
"author": "Umar.H",
"author_id": 9375102,
"author_profile": "https://Stackoverflow.com/users/9375102",
"pm_score": 1,
"selected": false,
"text": "idxmax() df['last_month'] = (~df.isna()).idxmax(axis=1)\n\n\nprint(df)\n\n\n 2021-01-01 2021-02-01 last_month\n0 3456 NaN 2021-01-01\n1 NaN 8679 2021-02-01\n"
},
{
"answer_id": 74667387,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 1,
"selected": true,
"text": "data = {'2021-01-01': {0: 3456, 1: None}, '2021-02-01': {0: None, 1: 8679}}\ndf = pd.DataFrame(data)\n df 2021-01-01 2021-02-01\n0 3456.0 NaN\n1 NaN 8679.0\n df.apply(lambda x: x.last_valid_index(), axis=1)\n 0 2021-01-01\n1 2021-02-01\ndtype: object\n Last_month df.assign(Last_month=df.apply(lambda x: x.last_valid_index(), axis=1))\n 2021-01-01 2021-02-01 Last_month\n0 3456.0 NaN 2021-01-01\n1 NaN 8679.0 2021-02-01\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20674781/"
] |
74,667,319
|
<p>I am trying to get a backwards typing effect with my code. So the <code><P></code> will say "Coming Soon" then type backwards. Then type forwards into "SeaDogs.com.eu.as"</p>
<p>This is what I have so far, for some reason it type coming soon backwards twice??? Which is my first hurtle I'm trying to overcome. And trying to delay it so it shows the word "Coming soon" for a few seconds.</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>var str = 'Coming Soon';
var remove = false;
var i = str.length;
var isTag;
var text;
(function type() {
if (!remove) {
text = str.slice(0, --i);
if (text === str) return;
}
if (!isTag) {
document.getElementById("demo").innerHTML = text;
}
setTimeout(type, 520);
}());</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="demo"></p></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74667405,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 1,
"selected": false,
"text": "const demo = document.querySelector('#demo')\n\nconst initial = \"Coming Soon\"\nconst later = \"SeaDogs.com.eu.as\"\n\nremove(initial).then(() => add(later))\n\nfunction remove(text) {\n let i = text.length\n return new Promise(r => {\n removeCharacter()\n\n function removeCharacter() {\n if (i < 0) {\n r()\n return\n }\n const copy = text.slice(0, i)\n demo.textContent = copy\n\n setTimeout(removeCharacter, 100)\n i -= 1\n }\n })\n}\n\nfunction add(text) {\n let i = 0\n return new Promise(r => {\n removeCharacter()\n\n function removeCharacter() {\n if (i > text.length) {\n r()\n return\n }\n const copy = text.slice(0, i)\n demo.textContent = copy\n\n setTimeout(removeCharacter, 100)\n i += 1\n }\n })\n} <p id=\"demo\"></p>"
},
{
"answer_id": 74667469,
"author": "freedomn-m",
"author_id": 2181514,
"author_profile": "https://Stackoverflow.com/users/2181514",
"pm_score": 1,
"selected": false,
"text": ".slice .slice(0, 8) .slice(0, -2) if (text === str) return if (text === \"\") return;\n if (i === 0) return;\n if (i<0) return;\n var str = 'Coming Soon';\nvar remove = false;\nvar i = str.length;\nvar isTag;\nvar text;\n\n(function type() {\n if (!remove) {\n text = str.slice(0, --i);\n //console.log(i, text)\n if (i < 0) return;\n }\n\n if (!isTag) {\n document.getElementById(\"demo\").innerHTML = text;\n }\n\n setTimeout(type, 150);\n\n}()); <p id=\"demo\"></p> remove !remove"
},
{
"answer_id": 74667493,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 3,
"selected": true,
"text": "function delay(time) {\n return new Promise(r =>\n setTimeout(r, time))\n}\n\nasync function typeAnimation(div, rtl, text, time) {\n for (let i = 1; i <= text.length; i++) {\n div.innerText = text.slice(0, rtl ? -i : +i)\n await delay(time)\n }\n}\n\nasync function main() {\n let div = document.querySelector('h1')\n await typeAnimation(div, true, 'Coming soon...', 100)\n await typeAnimation(div, false, 'and here it comes!', 100)\n}\n\nmain() <h1></h1>"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20674899/"
] |
74,667,324
|
<p>I have a table that shows the date and time whenever an issuer has called the service. I want to write a query to show in a specific day the requests of an specific issuer has not covered the 24 hours. I will be appreciated if someone can guide me. I am beginner at SQL.
<img src="https://i.stack.imgur.com/JkLsJ.png" alt="mht_issuer_revoked_call" /></p>
<p>i tried to partition by issuerid and order by startdate and use the lag to compare startdate and enddate with previous record and add a new start and end date but i think i cant get the answer this way.</p>
<pre><code>select r.*,
case
when r.startdate > lag(r.enddate) over(partition by r.issuerid order by r.startdate) then r.startdate
else min(r.startdate) over(partition by r.issuerid order by r.startdate)
end startdate_new,
case
when lag(r.enddate) over(partition by r.issuerid order by r.startdate) is null then r.enddate
when r.enddate <= lag(r.enddate) over(partition by r.issuerid order by r.startdate) then lag(r.enddate) over(partition by r.issuerid order by r.startdate)
when r.enddate > lag(r.enddate) over(partition by r.issuerid order by r.startdate) then r.enddate
end enddate_new
from mht_issuer_revoked_call r
</code></pre>
|
[
{
"answer_id": 74667405,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 1,
"selected": false,
"text": "const demo = document.querySelector('#demo')\n\nconst initial = \"Coming Soon\"\nconst later = \"SeaDogs.com.eu.as\"\n\nremove(initial).then(() => add(later))\n\nfunction remove(text) {\n let i = text.length\n return new Promise(r => {\n removeCharacter()\n\n function removeCharacter() {\n if (i < 0) {\n r()\n return\n }\n const copy = text.slice(0, i)\n demo.textContent = copy\n\n setTimeout(removeCharacter, 100)\n i -= 1\n }\n })\n}\n\nfunction add(text) {\n let i = 0\n return new Promise(r => {\n removeCharacter()\n\n function removeCharacter() {\n if (i > text.length) {\n r()\n return\n }\n const copy = text.slice(0, i)\n demo.textContent = copy\n\n setTimeout(removeCharacter, 100)\n i += 1\n }\n })\n} <p id=\"demo\"></p>"
},
{
"answer_id": 74667469,
"author": "freedomn-m",
"author_id": 2181514,
"author_profile": "https://Stackoverflow.com/users/2181514",
"pm_score": 1,
"selected": false,
"text": ".slice .slice(0, 8) .slice(0, -2) if (text === str) return if (text === \"\") return;\n if (i === 0) return;\n if (i<0) return;\n var str = 'Coming Soon';\nvar remove = false;\nvar i = str.length;\nvar isTag;\nvar text;\n\n(function type() {\n if (!remove) {\n text = str.slice(0, --i);\n //console.log(i, text)\n if (i < 0) return;\n }\n\n if (!isTag) {\n document.getElementById(\"demo\").innerHTML = text;\n }\n\n setTimeout(type, 150);\n\n}()); <p id=\"demo\"></p> remove !remove"
},
{
"answer_id": 74667493,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 3,
"selected": true,
"text": "function delay(time) {\n return new Promise(r =>\n setTimeout(r, time))\n}\n\nasync function typeAnimation(div, rtl, text, time) {\n for (let i = 1; i <= text.length; i++) {\n div.innerText = text.slice(0, rtl ? -i : +i)\n await delay(time)\n }\n}\n\nasync function main() {\n let div = document.querySelector('h1')\n await typeAnimation(div, true, 'Coming soon...', 100)\n await typeAnimation(div, false, 'and here it comes!', 100)\n}\n\nmain() <h1></h1>"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17070100/"
] |
74,667,350
|
<p>the below is my main_call.py file</p>
<pre><code>from flask import Flask, jsonify, request
from test_invoke.invoke import end_invoke
from config import config
app = Flask(__name__)
@app.route("/get/posts", methods=["GET"])
def load_data():
res = "True"
# setting a Host url
host_url = config()["url"]
# getting request parameter and validating it
generate_schedule= end_invoke(host_url)
if generate_schedule == 200:
return jsonify({"status_code": 200, "message": "success"})
elif generate_schedule == 400:
return jsonify(
{"error": "Invalid ", "status_code": 400}
)
if __name__ == "__main__":
app.run(debug=True)
</code></pre>
<p>invoke.py</p>
<pre><code>import requests
import json
import urllib
from urllib import request, parse
from config import config
from flask import request
def end_invoke(schedule_url):
headers = {
"Content-Type":"application/json",
}
schedule_data = requests.get(schedule_url, headers=headers)
if not schedule_data.status_code // 100 == 2:
error = schedule_data.json()["error"]
print(error)
return 400
else:
success = schedule_data.json()
return 200
</code></pre>
<p>tree structure</p>
<pre><code>test_invoke
├── __init__.py
├── __pycache__
│ ├── config.cpython-38.pyc
│ └── invoke.cpython-38.pyc
├── config.py
├── env.yaml
├── invoke.py
└── main_call.py
</code></pre>
<p>However when i run, i get the no module found error</p>
<pre><code> python3 main_call.py
Traceback (most recent call last):
File "main_call.py", line 3, in <module>
from test_invoke.invoke import end_invoke
ModuleNotFoundError: No module named 'test_invoke'
</code></pre>
|
[
{
"answer_id": 74667398,
"author": "Saurabh Verma",
"author_id": 12817895,
"author_profile": "https://Stackoverflow.com/users/12817895",
"pm_score": 1,
"selected": true,
"text": "from test_invoke.invoke import end_invoke from invoke import end_invoke"
},
{
"answer_id": 74667502,
"author": "Serge Ballesta",
"author_id": 3545273,
"author_profile": "https://Stackoverflow.com/users/3545273",
"pm_score": 2,
"selected": false,
"text": "PYTHONPATH test_invoke main_call.py __main__.py from .invoke import end_invoke python -m test_invoke test_invoke PYTHONPATH"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1004770/"
] |
74,667,361
|
<p>I want to delete some records after sort and skip items but this query always delete all records after find.as if sort and skip don't do anything':</p>
<pre><code>await Book.find(Book.owner.id == user.id).sort("-created_at").skip(2).delete()
</code></pre>
|
[
{
"answer_id": 74667398,
"author": "Saurabh Verma",
"author_id": 12817895,
"author_profile": "https://Stackoverflow.com/users/12817895",
"pm_score": 1,
"selected": true,
"text": "from test_invoke.invoke import end_invoke from invoke import end_invoke"
},
{
"answer_id": 74667502,
"author": "Serge Ballesta",
"author_id": 3545273,
"author_profile": "https://Stackoverflow.com/users/3545273",
"pm_score": 2,
"selected": false,
"text": "PYTHONPATH test_invoke main_call.py __main__.py from .invoke import end_invoke python -m test_invoke test_invoke PYTHONPATH"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11976483/"
] |
74,667,366
|
<p>I am new to react-router-dom I was passing data from <strong>ParentPage</strong> to the <strong>ChildPage</strong> page using <code><Link/></code> and it was a success, but if I'm going to refresh the child page it returns an error <code>TypeError: Cannot read properties of undefined</code>. I have also tried storing the data on the <code>localStorage</code> but it is still returning the same error</p>
<p>Here is my code snippet, I hope anyone can help me.
<a href="https://i.stack.imgur.com/rAnPk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rAnPk.png" alt="enter image description here" /></a></p>
<p>And here is the <code>Error</code>
<a href="https://i.stack.imgur.com/D6ZXT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D6ZXT.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74667398,
"author": "Saurabh Verma",
"author_id": 12817895,
"author_profile": "https://Stackoverflow.com/users/12817895",
"pm_score": 1,
"selected": true,
"text": "from test_invoke.invoke import end_invoke from invoke import end_invoke"
},
{
"answer_id": 74667502,
"author": "Serge Ballesta",
"author_id": 3545273,
"author_profile": "https://Stackoverflow.com/users/3545273",
"pm_score": 2,
"selected": false,
"text": "PYTHONPATH test_invoke main_call.py __main__.py from .invoke import end_invoke python -m test_invoke test_invoke PYTHONPATH"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13084897/"
] |
74,667,386
|
<p>I have two SVG icons, and all I want to do is apply a background, add some padding, and make the <strong>padding</strong> appear round (border-radius). When adding the padding all is fine and appears as expected, it's only when trying to make it round.</p>
<p>No matter what the amount of padding is, the SVG's are cut off.</p>
<p>SVG with <code>10px padding</code> and <code>50% border-radius</code>:</p>
<p><a href="https://i.stack.imgur.com/WsglA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WsglA.png" alt="enter image description here" /></a></p>
<p>For reference, this is what the SVG normally looks like:</p>
<p><a href="https://i.stack.imgur.com/831mz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/831mz.png" alt="enter image description here" /></a></p>
<p>As I explained above, I tried many different padding sizes, but all result in a part of the SVG being cutoff. I've searched on the topic, but the only things I could find were:</p>
<p><a href="https://stackoverflow.com/questions/9409632/border-radius-and-padding-not-playing-nice">Link 1</a> - It was about another topic not related to mine.</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/border-block-start" rel="nofollow noreferrer">Link 2</a> - I tried <code>border-block-start</code>, but unfortunately nothing happened.</p>
<p>Can anyone help me?</p>
|
[
{
"answer_id": 74667398,
"author": "Saurabh Verma",
"author_id": 12817895,
"author_profile": "https://Stackoverflow.com/users/12817895",
"pm_score": 1,
"selected": true,
"text": "from test_invoke.invoke import end_invoke from invoke import end_invoke"
},
{
"answer_id": 74667502,
"author": "Serge Ballesta",
"author_id": 3545273,
"author_profile": "https://Stackoverflow.com/users/3545273",
"pm_score": 2,
"selected": false,
"text": "PYTHONPATH test_invoke main_call.py __main__.py from .invoke import end_invoke python -m test_invoke test_invoke PYTHONPATH"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16415800/"
] |
74,667,397
|
<p>My expo application works normally on Expo go, even using the command bellow it still works.</p>
<blockquote>
<p>npx expo start --no-dev --minify</p>
</blockquote>
<p>But when building with different methods it don't work at all, with different crashes.</p>
<blockquote>
<p>eas build -p android --profile preview</p>
</blockquote>
<p>It generates the APK, when i drag to the emulator (android 11) it gets the "successful install", so I open and the splash screen shows, after that it crashes and the app disappear from the device. Looks like it was automatically uninstalled, because I can't find it anywhere in the files.</p>
<blockquote>
<p>expo build:android -t apk</p>
</blockquote>
<p>With the deprecated method above i still get a "successful install", but it never gets to the splash screen, just get a white screen and it never crashes or disappear from device.</p>
<p>I tried on multiple devices and android versions and i have the same problem with each build in all of them. So i guess the problem is the build. I couldn't find anyone else with the solution or a hint for it.</p>
<p>I tried uninstalling multiple npm packages to see if was the problem with no successes.</p>
<p>Its my first time working with React Native and Expo, so I can be missing something.</p>
<pre><code> //app.json
{
"expo": {
"name": "tv_box",
"slug": "tv_box",
"version": "1.0.0",
"orientation": "landscape",
"icon": "./assets/icon.png",
"userInterfaceStyle": "light",
"splash": {
"image": "./assets/splash.png",
"resizeMode": "contain",
"backgroundColor": "#ffffff"
},
"updates": {
"fallbackToCacheTimeout": 0
},
"assetBundlePatterns": [
"**/*"
],
"ios": {
"supportsTablet": true
},
"android": {
"adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#FFFFFF"
},
"package": "com.test.tv_box"
},
"web": {
"favicon": "./assets/favicon.png"
},
"extra": {
"eas": {
"projectId": "4b9e5710-cdd0-4e3a-846d-3faed6c56510"
}
}
}
}
//eas.json
{
"cli": {
"version": ">= 2.8.0"
},
"build": {
"development": {
"developmentClient": true,
"distribution": "internal"
},
"preview": {
"distribution": "internal"
},
"production": {}
},
"submit": {
"production": {}
}
}
//package.json
{
"name": "tv_box",
"version": "1.0.0",
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web"
},
"dependencies": {
"@react-native-async-storage/async-storage": "^1.17.10",
"@react-navigation/stack": "^6.3.2",
"expo": "~46.0.7",
"expo-status-bar": "~1.4.0",
"expo-system-ui": "~1.3.0",
"expo-updates": "~0.14.7",
"pocketbase": "^0.7.4",
"react": "18.0.0",
"react-native": "0.69.6",
"react-native-gesture-handler": "~2.5.0",
"react-native-restart": "^0.0.24",
"react-native-vector-icons": "^9.2.0",
"expo-av": "~12.0.4"
},
"devDependencies": {
"@babel/core": "^7.12.9"
},
"private": true
}
</code></pre>
|
[
{
"answer_id": 74668275,
"author": "mirik999",
"author_id": 13907400,
"author_profile": "https://Stackoverflow.com/users/13907400",
"pm_score": 1,
"selected": false,
"text": "\"developmentClient\": true\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13253577/"
] |
74,667,407
|
<p>TrackPoint tp
Type: TrackPoint</p>
<p>The argument type 'TrackPoint
(where TrackPoint is defined in ...lib\trackpoint.dart)'
can't be assigned to
the parameter type 'TrackPoint (where TrackPoint is defined in ...lib\trackPoint.dart)'.dart
<strong>(argument_type_not_assignable)</strong>
trackpoint.dart(8, 7): TrackPoint is defined in ...lib\trackpoint.dart
trackPoint.dart(8, 7): TrackPoint is defined in ...lib\trackPoint.dart</p>
<p>Here is where the error is:</p>
<pre><code>import 'trackpoint.dart' show TrackPoint;
class TrackingStatus {
// ...
static void _triggerEvent(TrackPoint tp) {
// ...
TrackingStatusChangedEvent.trigger(tp); // <-- error on tp, see above
}
</code></pre>
<p>Here is what causes the error:</p>
<pre><code>class TrackingStatusChangedEvent {
static void trigger(TrackPoint tp) { // <-- causes error
// ...
}
static void trigger(tp) { // <-- works but tp should not be dynamic
// ...
}
</code></pre>
<p>Here is where TrackPoint comes from:</p>
<pre><code>
class TrackPoint {
static final List<TrackPoint> _trackPoints = [];
void _addTrackPoint() {
_trackPoints.add(this);
</code></pre>
<p>argument_type_not_assignable is not reasonable for me. Especially because the error message points to the same class in the same file as if they are something different</p>
|
[
{
"answer_id": 74668275,
"author": "mirik999",
"author_id": 13907400,
"author_profile": "https://Stackoverflow.com/users/13907400",
"pm_score": 1,
"selected": false,
"text": "\"developmentClient\": true\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4823385/"
] |
74,667,424
|
<p>I'm trying to use regex to match: a word that's at least 5 characters long and ends with an 's', but the 's' is included in the 5 characters. Say for example, I have the following words:</p>
<pre><code>hexes pixies major prairies caveman zipfiles oxes
</code></pre>
<p>I tried doing <code>([a-z]s?){5,}</code></p>
|
[
{
"answer_id": 74667543,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 3,
"selected": true,
"text": "([a-z]s?){5,} s \\b s \\b[a-z]{4,}s\\b\n"
},
{
"answer_id": 74667875,
"author": "Oskar Asplin",
"author_id": 14166396,
"author_profile": "https://Stackoverflow.com/users/14166396",
"pm_score": 0,
"selected": false,
"text": "\\b[A-Za-z]{4,}s\\b\n \\b[A-Za-zÀ-ȕ]{4,}s\\b\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15748497/"
] |
74,667,427
|
<p>I read <a href="https://tkdodo.eu/blog/react-query-as-a-state-manager" rel="nofollow noreferrer">an article on using react-query as a state manager</a> and I am now trying to replace a context in my app with react-query (version 4).</p>
<p>Previously, I created a context with <code>useContext()</code> that stored a <strong>user account</strong> object for the logged-in user. I used react-query to fetch this data, and then <code>useReducer()</code> to modify the account object. However, I realized this is a mess and the relevant data is in react-query anyway, so I should get rid of the context and reducer and just use react-query directly (I am generating the user account object in the query that I make with react-query).</p>
<p>I generate the user account object in a custom hook:</p>
<pre><code>function useUser(): UseQueryResult<User, Error> {
const query = getInitialUserUrl;
const platform = usePlatformContext();
return useQuery<User, Error>(
queryKeyUseUser,
async () => {
const data = await fetchAuth(query);
if (didQueryReturnData(data)) {
return new User(platform, data[0]);
}
return new User(platform);
},
{
refetchOnReconnect: 'always',
refetchInterval: false,
},
);
}
export default useUser;
</code></pre>
<p>Now I have a mutation where I verify the user's email address (old way using context):</p>
<pre><code>const useMutationVerifyEmail = (): UseMutationResult<RpcResponseEmailVerify, Error, FormEmailVerifyInput> => {
const { userObject } = useUserContext();
return useMutation(
(data: FormEmailVerifyInput) => verifyEmail(userObject.id, data.validation_code),
},
);
};
</code></pre>
<p>I tried to replace the call to context with a direct call to <code>useUser()</code>:</p>
<pre><code>const useMutationVerifyEmail = (): UseMutationResult<RpcResponseEmailVerify, Error, FormEmailVerifyInput> => {
const { data: userObject } = useUser();
return useMutation(
(data: FormEmailVerifyInput) => verifyEmail(userObject.id, data.validation_code),
},
);
};
</code></pre>
<p>However, TypeScript complains that <code>Object is possibly 'undefined'</code> for <code>userObject</code>. I'm not sure why, because as far as I understand, <code>useUser()</code> always returns a <code>User</code> object.</p>
<p>How can I update my custom hook to return a <code>User</code> object so that I can use it instead of context?</p>
<p><strong>UPDATE</strong></p>
<p>I can wrap my <code>useUser()</code> hook in another hook:</p>
<pre><code>function useUserObject() {
const { data: userObject } = useUser();
if (userObject instanceof User) {
return userObject;
}
throw new Error('Failed to get account info!');
}
</code></pre>
<p>And then I can do <code>const userObject = useUserObject()</code> to get the user account object... but is this really the optimal way? Do I need to create a custom hook for a custom hook just to use my user objects like I do with <code>useContext()?</code></p>
|
[
{
"answer_id": 74673284,
"author": "Jakub Kotrs",
"author_id": 2188587,
"author_profile": "https://Stackoverflow.com/users/2188587",
"pm_score": 2,
"selected": false,
"text": "undefined export type QueryStatus = 'loading' | 'error' | 'success'\n data undefined type QueryObserverResult = {\n status: 'success',\n data: TData\n} | {\n status: 'error',\n data: undefined\n} | {\n status: 'loading',\n data: undefined\n}\n user useUser function useUser(): DefinedUseQueryResult<User, Error> {\n ...\n ...\n return useQuery(...) as DefinedUseQueryResult<User, Error>\n}\n"
},
{
"answer_id": 74674946,
"author": "TkDodo",
"author_id": 8405310,
"author_profile": "https://Stackoverflow.com/users/8405310",
"pm_score": 4,
"selected": true,
"text": "useQuery useMutationVerifyEmail const useMutationVerifyEmail = (): UseMutationResult<RpcResponseEmailVerify, Error, FormEmailVerifyInput> => {\n const { data: userObject } = useUser();\n\n return useMutation(\n (data: FormEmailVerifyInput) => verifyEmail(userObject!.id, data.validation_code),\n );\n};\n const useMutationVerifyEmail = (): UseMutationResult<RpcResponseEmailVerify, Error, FormEmailVerifyInput> => {\n const { data: userObject } = useUser();\n\n return useMutation(\n async (data: FormEmailVerifyInput) => {\n if (!userObject) {\n throw new Error(\"no user available\")\n }\n return verifyEmail(userObject.id, data.validation_code)\n },\n );\n};\n useUser const useMutationVerifyEmail = (): UseMutationResult<RpcResponseEmailVerify, Error, FormEmailVerifyInput> => {\n return useMutation(\n ({ id, ...data} : FormEmailVerifyInput & { id: number }) => verifyEmail(id, data.validation_code),\n );\n};\n useQuery null useQuery const UserProvider = ({ children }) => {\n const { data } = useUser()\n\n if (data.isLoading) return \"loading ...\"\n if (data.isError) return \"error\"\n\n return <UserContext.Provider value={data}>{children}</UserContext.Provider>\n}\n data useContext() useQuery value select children EssentialDataProvider"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1209486/"
] |
74,667,428
|
<p>I want to display the data of the authenticated user and also produce a status code and a status message when the user is not authenticated. I am using Laravel API and Sanctum and this is what I have tried:</p>
<pre><code>public function me(Request $request){
$user = $request->user();
if($user)
{
return response()->json([
'status'=>200,
'user'=>$user
]);
} else {
return response()->json([
'status'=>401,
'message'=>'No access'
]);
}
}
</code></pre>
<p>Problem is, it displays the status 200 when authenticated and does not display the status 401 code when not. It only displays the default Sanctum</p>
<pre><code>{
"message": "Unauthenticated."
}
</code></pre>
<p>There is also a bearer token involved in the authentication.
Kindly help</p>
|
[
{
"answer_id": 74673284,
"author": "Jakub Kotrs",
"author_id": 2188587,
"author_profile": "https://Stackoverflow.com/users/2188587",
"pm_score": 2,
"selected": false,
"text": "undefined export type QueryStatus = 'loading' | 'error' | 'success'\n data undefined type QueryObserverResult = {\n status: 'success',\n data: TData\n} | {\n status: 'error',\n data: undefined\n} | {\n status: 'loading',\n data: undefined\n}\n user useUser function useUser(): DefinedUseQueryResult<User, Error> {\n ...\n ...\n return useQuery(...) as DefinedUseQueryResult<User, Error>\n}\n"
},
{
"answer_id": 74674946,
"author": "TkDodo",
"author_id": 8405310,
"author_profile": "https://Stackoverflow.com/users/8405310",
"pm_score": 4,
"selected": true,
"text": "useQuery useMutationVerifyEmail const useMutationVerifyEmail = (): UseMutationResult<RpcResponseEmailVerify, Error, FormEmailVerifyInput> => {\n const { data: userObject } = useUser();\n\n return useMutation(\n (data: FormEmailVerifyInput) => verifyEmail(userObject!.id, data.validation_code),\n );\n};\n const useMutationVerifyEmail = (): UseMutationResult<RpcResponseEmailVerify, Error, FormEmailVerifyInput> => {\n const { data: userObject } = useUser();\n\n return useMutation(\n async (data: FormEmailVerifyInput) => {\n if (!userObject) {\n throw new Error(\"no user available\")\n }\n return verifyEmail(userObject.id, data.validation_code)\n },\n );\n};\n useUser const useMutationVerifyEmail = (): UseMutationResult<RpcResponseEmailVerify, Error, FormEmailVerifyInput> => {\n return useMutation(\n ({ id, ...data} : FormEmailVerifyInput & { id: number }) => verifyEmail(id, data.validation_code),\n );\n};\n useQuery null useQuery const UserProvider = ({ children }) => {\n const { data } = useUser()\n\n if (data.isLoading) return \"loading ...\"\n if (data.isError) return \"error\"\n\n return <UserContext.Provider value={data}>{children}</UserContext.Provider>\n}\n data useContext() useQuery value select children EssentialDataProvider"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20490773/"
] |
74,667,431
|
<p>I want to make a set of floating point numbers, but with a twist:</p>
<p>When testing if some float x is a member of the set s, I want the test to return true if s contains some float f such that</p>
<pre><code>abs(x - f) < tol
</code></pre>
<p>In other words, if the set contains a number that is close to x, return true. Otherwise return false.</p>
<p>One way I thought of doing this is to store numbers in a heap rather than a hash set, and use an approximate equality rule to decide whether the heap contains a close number.</p>
<p>However, that would take log(N) time, which is not bad, but it would be nice to get O(1) if such an algorithm exists.</p>
<p>Does anyone have any ideas how this might be possible?</p>
|
[
{
"answer_id": 74669412,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 0,
"selected": false,
"text": "float float MAX_FLOAT N -MAX_FLOAT -N float float"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9985445/"
] |
74,667,477
|
<p>Could you please help me figure out why is this not working i.e. refering to the comment in the code <code>//I need to do this but I can't. I thought this the goal!</code>? I have no idea why this is not working, it's inspired by examples I have seen online.</p>
<pre><code>#include <variant>
#include <iostream>
template<typename... args>
class Visitor //: public boost_base_visitor<double>...
{
public:
virtual ~Visitor() = default;
virtual double visit(typename std::variant<args...> visitable)
{
auto op = [this](typename std::variant<args...> visitable) -> double { return this->apply(visitable); };
return std::visit(std::ref(op), visitable);
}
virtual double apply(typename std::variant<args...> visitable) = 0;
Visitor() = default;
};
class SubVisitor : public Visitor<std::string, double>
{
public:
virtual ~SubVisitor() = default;
SubVisitor() : Visitor<std::string, double>() {};
virtual double apply(std::variant<std::string, double> visitable) override
{
//return process(visitable); //I need to do this but I can't. I thought this the goal!
return process(std::get<std::string>(visitable)); //I DON'T KNOW IF THIS IS REALLY A STRING??
};
virtual double process(std::string visitable)
{
std::cout << "STRING HANDLED" << std::endl;
return 0.0;
}
virtual double process(double visitable)
{
std::cout << "DOUBLE HANDLED" << std::endl;
return 1.0;
}
};
int main(int argc, char* argv[])
{
SubVisitor v;
v.apply("dd");
//v.apply(1.0); //This will fail as we only handle string?? What is the purpose of variant then?
return 1;
}
</code></pre>
<p>I am getting error when uncommenting the <code>process</code> function above:</p>
<blockquote>
<p>Error C2664: 'double SubVisitor::process(std::string)': cannot convert
argument 1 from 'std::variantstd::string,double' to 'std::string'</p>
</blockquote>
|
[
{
"answer_id": 74667677,
"author": "apple apple",
"author_id": 5980430,
"author_profile": "https://Stackoverflow.com/users/5980430",
"pm_score": 2,
"selected": false,
"text": "std:visit class SubVisitor{\n virtual double apply(std::variant<std::string, double> visitable) override\n {\n // std::visit expect `operator()`, not `process`\n // so wrap `this` inside a lambda here\n return std::visit( \n [this](auto&& v){return process(v);},\n visitable\n );\n };\n}\n class SubVisitor{\n virtual double apply(std::variant<std::string, double> visitable) override\n {\n if(auto* s = std::get_if<std::string>(&visitable))\n return process(*s);\n \n else if(auto* d = std::get_if<double>(&visitable))\n return process(*d);\n\n throw std::bad_variant_access();\n }\n};\n"
},
{
"answer_id": 74667868,
"author": "apple apple",
"author_id": 5980430,
"author_profile": "https://Stackoverflow.com/users/5980430",
"pm_score": 1,
"selected": false,
"text": "template<typename... args>\nclass Visitor{\npublic:\n Visitor() = default;\n virtual ~Visitor() = default;\n\n // this should be non-virtual\n double visit(std::variant<args...> visitable)\n {\n // dispatch via the customization point `this->apply`\n return this->apply(visitable);\n }\n virtual double apply(std::variant<args...> visitable) = 0;\n};\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18718251/"
] |
74,667,505
|
<p>With <code>strict</code> enabled in <code>tsconfig.json</code>, why does <code>tsc</code> not issue an error when indexing an object of type <code>never</code>?</p>
<pre><code>const mystery = ({ foo: 1 } as never)
console.log(mystery['foo']) // no error
console.log(mystery.foo) // Property 'foo' does not exist on type 'never'.
export {}
</code></pre>
<p><a href="https://www.typescriptlang.org/play?#code/MYewdgzgLgBAtgT2gUwE4JgXhgCgN4wBmIIAXDAIwwC+MAhhDGMgG5oCUAUJ6JCADbIAdPxABzHIhToA2gHJiIOQF12MGAHoNTEDDSoQqHuAgDhoiVKhoEQxWs3aACgYAOaKBgUk5MACYgyIxgILDIAB4AltAw4DCe7jByzGyockLcEa6GsHjUnEA" rel="nofollow noreferrer">Playground example</a></p>
|
[
{
"answer_id": 74667539,
"author": "chivalrous-nerd",
"author_id": 7347835,
"author_profile": "https://Stackoverflow.com/users/7347835",
"pm_score": -1,
"selected": false,
"text": "type never mystery never { foo: number } as never mystery never console.log console.log never never"
},
{
"answer_id": 74667557,
"author": "T.J. Crowder",
"author_id": 157247,
"author_profile": "https://Stackoverflow.com/users/157247",
"pm_score": 2,
"selected": true,
"text": "let x = [1, 2, 3, 4].forEach(x => { console.log(x));\nx[\"hello\"] = 123;\n never declare let mystery: never;\n\nconsole.log(mystery[\"foo\"]); // No error\nconsole.log(mystery.foo); // Property 'foo' does not exist on type 'never'.\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/720877/"
] |
74,667,509
|
<p>I'm making a simple to-do app with add and delete functionality and I want to implement an undo-delete option.</p>
<p>So far, I've tried using context but I have a problem with context state logic: undo function uses not-yet updated state values, which leads to errors.</p>
<p>The problem is better documented in the demo:</p>
<p><a href="https://codesandbox.io/s/damp-frost-x48zh6?file=/src/TaskProvider.js&autoresize=1&fontsize=14&hidenavigation=1&theme=dark" rel="nofollow noreferrer"><img src="https://codesandbox.io/static/img/play-codesandbox.svg" alt="Edit damp-frost-x48zh6" /></a></p>
|
[
{
"answer_id": 74667539,
"author": "chivalrous-nerd",
"author_id": 7347835,
"author_profile": "https://Stackoverflow.com/users/7347835",
"pm_score": -1,
"selected": false,
"text": "type never mystery never { foo: number } as never mystery never console.log console.log never never"
},
{
"answer_id": 74667557,
"author": "T.J. Crowder",
"author_id": 157247,
"author_profile": "https://Stackoverflow.com/users/157247",
"pm_score": 2,
"selected": true,
"text": "let x = [1, 2, 3, 4].forEach(x => { console.log(x));\nx[\"hello\"] = 123;\n never declare let mystery: never;\n\nconsole.log(mystery[\"foo\"]); // No error\nconsole.log(mystery.foo); // Property 'foo' does not exist on type 'never'.\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13457557/"
] |
74,667,518
|
<pre><code>import qrcode
import time
import tkinter as tk
import os
import shutil
from sys import exit
# GUI with tkinter
root = tk.Tk()
root.title('Window')
root.geometry("400x400+50+50")
root.iconbitmap('QRCODE-GENERATOR.ico')
root.configure(bg="grey")
lbl_1 = tk.Label(root, text="Qrcode generator", font="1")
entry_1 = tk.Entry(root)
lbl_1.pack()
entry_1.pack(side=tk.RIGHT)
tk.mainloop()
# GUI end
if not entry_1:
exit()
data = entry_1
# Qr code setup
qr = qrcode.QRCode(
version=1,
box_size=5,
border=5
)
# Adding the data to the system
qr.add_data(data)
# qr customizing
qr.make(fit=True)
img = qr.make_image(
fill_color= 'black',
back_color= 'white'
)
time.sleep(2)
# saving qr
img.save('output.png')
# absolute path
src_path = r"D:\Python\QRcode generator\output.png"
dst_path = r"D:\Users"
shutil.move(src_path, dst_path)
</code></pre>
<p>you see I'm getting the error file already exists, so what I want it to add a number to the QR code every time someone saves it. So it doesn't throw the error, you see python and shutils just gets confused when saving a file with the same name 2 times. If you don't really get what I'm saying then just tell me to make some edits, ill make it simpler.</p>
<p>Note: I might not be able to respond when you answer</p>
|
[
{
"answer_id": 74667539,
"author": "chivalrous-nerd",
"author_id": 7347835,
"author_profile": "https://Stackoverflow.com/users/7347835",
"pm_score": -1,
"selected": false,
"text": "type never mystery never { foo: number } as never mystery never console.log console.log never never"
},
{
"answer_id": 74667557,
"author": "T.J. Crowder",
"author_id": 157247,
"author_profile": "https://Stackoverflow.com/users/157247",
"pm_score": 2,
"selected": true,
"text": "let x = [1, 2, 3, 4].forEach(x => { console.log(x));\nx[\"hello\"] = 123;\n never declare let mystery: never;\n\nconsole.log(mystery[\"foo\"]); // No error\nconsole.log(mystery.foo); // Property 'foo' does not exist on type 'never'.\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20484607/"
] |
74,667,546
|
<p>I try to fetch 4 categories from my DB.</p>
<p>I get the category, everything is ok but when I submit my form, I get this data :</p>
<pre><code>[object%20Object],[object%20Object],[object%20Object],[object%20Object]
</code></pre>
<p>Here the code :</p>
<pre><code>//State
const [cates, setCates] = useState([]);
// Fetch 4 categories
useEffect(() => {
const getCates = async () => {
const res = await axios.get("http://localhost:8080/api/categories");
setCates(res.data);
};
getCates();
}, [])
//Map the categories from the State : cates
const Categorie = cates.map((c) => (
<option value={c.name}>{c.name}</option>
))
</code></pre>
<p>My component :</p>
<pre><code><Select>
<option value="" hidden>Choisissez une catégorie</option>
{Categorie}
</Select>
</code></pre>
<p>The console.log(Categorie) return an Array of object :</p>
<pre><code>(4) [{…}, {…}, {…}, {…}]
0
:
{$$typeof: Symbol(react.element), type: 'option', key: null, ref: null, props: {…}, …}
1
:
{$$typeof: Symbol(react.element), type: 'option', key: null, ref: null, props: {…}, …}
2
:
{$$typeof: Symbol(react.element), type: 'option', key: null, ref: null, props: {…}, …}
3
:
{$$typeof: Symbol(react.element), type: 'option', key: null, ref: null, props: {…}, …}
length
:
4
[[Prototype]]
:
Array(0)
</code></pre>
<p>And the console.log(cates[0].name) give me the result I'm looking for.</p>
<p>But even when I try to put manually the categories like that : cates[0].name, cates[1].names etc... I get a blank page when I save my code and reload the page.</p>
<p>I just want to get my the categorie selected.</p>
|
[
{
"answer_id": 74667539,
"author": "chivalrous-nerd",
"author_id": 7347835,
"author_profile": "https://Stackoverflow.com/users/7347835",
"pm_score": -1,
"selected": false,
"text": "type never mystery never { foo: number } as never mystery never console.log console.log never never"
},
{
"answer_id": 74667557,
"author": "T.J. Crowder",
"author_id": 157247,
"author_profile": "https://Stackoverflow.com/users/157247",
"pm_score": 2,
"selected": true,
"text": "let x = [1, 2, 3, 4].forEach(x => { console.log(x));\nx[\"hello\"] = 123;\n never declare let mystery: never;\n\nconsole.log(mystery[\"foo\"]); // No error\nconsole.log(mystery.foo); // Property 'foo' does not exist on type 'never'.\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17026389/"
] |
74,667,561
|
<p>I am using amazon service and created rabbitmq broker now from the DOT NET code i am trying to connect to this broker.</p>
<pre><code> var factory = new ConnectionFactory
{
Uri = new Uri("amqps://it:Password@hostname:5671")
};
var connection = factory.CreateConnection();
</code></pre>
<p>I am struggle here to get connection getting below error :</p>
<pre><code> None of the specified endpoints were reachable
at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, String clientProvidedName)
</code></pre>
|
[
{
"answer_id": 74667539,
"author": "chivalrous-nerd",
"author_id": 7347835,
"author_profile": "https://Stackoverflow.com/users/7347835",
"pm_score": -1,
"selected": false,
"text": "type never mystery never { foo: number } as never mystery never console.log console.log never never"
},
{
"answer_id": 74667557,
"author": "T.J. Crowder",
"author_id": 157247,
"author_profile": "https://Stackoverflow.com/users/157247",
"pm_score": 2,
"selected": true,
"text": "let x = [1, 2, 3, 4].forEach(x => { console.log(x));\nx[\"hello\"] = 123;\n never declare let mystery: never;\n\nconsole.log(mystery[\"foo\"]); // No error\nconsole.log(mystery.foo); // Property 'foo' does not exist on type 'never'.\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2746693/"
] |
74,667,577
|
<p>Here's my sample code:</p>
<pre><code>public class MyList<T extends Number> {
private List<T> items;
public void func() {
items.add(Integer.valueOf(1));
}
}
</code></pre>
<p>I think I should be able to add integer to items, but compilation fails:</p>
<pre><code>Required type: T
Provided: Integer
</code></pre>
<p>Anyone knows what's wrong here?</p>
|
[
{
"answer_id": 74667902,
"author": "Stephen C",
"author_id": 139985,
"author_profile": "https://Stackoverflow.com/users/139985",
"pm_score": 1,
"selected": false,
"text": "public class MyList<T extends Number> {\n\n private List<T> items = new ArrayList<>();\n\n public void func() {\n items.add(Integer.valueOf(1));\n }\n}\n func MyList<Double> myDoubles = new MyList<>();\nmyDoubles.func();\n MyList T Double Double Number items List<Double> ArrayList Double func Integer List<Double> Required type: T Provided: Integer T Integer Integer Number T item Number private List<T> items = new ArrayList<>();\n private List<Number> items = new ArrayList<>();\n items.add(Integer.valueOf(1)) 1 items T MyList T 1 func Class<T> func 1 Integer T"
},
{
"answer_id": 74667973,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 0,
"selected": false,
"text": "<T extends Number> T Number Number BigDecimal AtomicLong List<T> List<AtomicLong> AtomicLong String Integer Integer List<T> T Number Number"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/243755/"
] |
74,667,598
|
<p>I'm currently working on a website and I it's putting line breaks where I don't believe it should.</p>
<p>For example if I'd do:</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>a</p><p>b</p></code></pre>
</div>
</div>
</p>
<p>it'd put a line break between them. Has it always been this way?</p>
|
[
{
"answer_id": 74667619,
"author": "Tohirul Islam",
"author_id": 16414128,
"author_profile": "https://Stackoverflow.com/users/16414128",
"pm_score": 0,
"selected": false,
"text": "<br/> \\n <p></p> <p></p> <span>a</span><span>b</span> <span></span>"
},
{
"answer_id": 74667662,
"author": "Yahli Gi",
"author_id": 17089291,
"author_profile": "https://Stackoverflow.com/users/17089291",
"pm_score": 1,
"selected": false,
"text": "<p> p {\n margin: 0\n}\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18374054/"
] |
74,667,612
|
<p>I want to generate a random binary matrix, so I'm using <code> W=np.random.binomial(1, p, (n,n))</code>.
It works fine, but I want a constraint that no row is just of 0s.</p>
<p>I create the following function:</p>
<pre class="lang-py prettyprint-override"><code>def random_matrix(p,n):
m=0
while m==0:
W = np.random.binomial(1, p, (n,n))
m=min(W.sum(axis=1))
return W
</code></pre>
<p>It also works fine, but it seems to me too inefficient. Is there a faster way to create this constraint?</p>
|
[
{
"answer_id": 74667619,
"author": "Tohirul Islam",
"author_id": 16414128,
"author_profile": "https://Stackoverflow.com/users/16414128",
"pm_score": 0,
"selected": false,
"text": "<br/> \\n <p></p> <p></p> <span>a</span><span>b</span> <span></span>"
},
{
"answer_id": 74667662,
"author": "Yahli Gi",
"author_id": 17089291,
"author_profile": "https://Stackoverflow.com/users/17089291",
"pm_score": 1,
"selected": false,
"text": "<p> p {\n margin: 0\n}\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9975452/"
] |
74,667,621
|
<p>I'm trying to get full article in Google Sheet using Openai API. In column A I just mention the topic and want to get full article in column B.</p>
<p>Here is what I'm trying</p>
<pre><code> /**
* Use GPT-3 to generate an article
*
* @param {string} topic - the topic for the article
* @return {string} the generated article
* @customfunction
*/
function getArticle(topic) {
// specify the API endpoint and API key
const api_endpoint = 'https://api.openai.com/v1/completions';
const api_key = 'YOUR_API_KEY';
// specify the API parameters
const api_params = {
prompt: topic,
max_tokens: 1024,
temperature: 0.7,
model: 'text-davinci-003',
};
// make the API request using UrlFetchApp
const response = UrlFetchApp.fetch(api_endpoint, {
method: 'post',
headers: {
Authorization: 'Bearer ' + api_key,
'Content-Type': 'application/json',
},
payload: JSON.stringify(api_params),
});
// retrieve the article from the API response
const json = JSON.parse(response.getContentText());
if (json.data && json.data.length > 0) {
const article = json.data[0].text;
return article;
} else {
return 'No article found for the given topic.';
}
}
</code></pre>
<p>How can I get the article?</p>
|
[
{
"answer_id": 74668192,
"author": "doubleunary",
"author_id": 13045193,
"author_profile": "https://Stackoverflow.com/users/13045193",
"pm_score": 0,
"selected": false,
"text": "console.log(response.getContentText()) { \"title\": \"OpenAI API Example Article\", \"author\": \"John Doe\", \"content\": \"This is an example of an article retrieved using the OpenAI API. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco est laborum.\", \"source\": \"www.example.com\" } title content const json = JSON.parse(response.getContentText());\n const { title, content } = json;\n console.log(title);\n console.log(content);\n console.log(response.getContentText()) [{ \"title\": ... }, { \"title\": ... }] const { title, content } = json[0];\n json JSON.parse() articleObject"
},
{
"answer_id": 74672449,
"author": "Tanaike",
"author_id": 7108653,
"author_profile": "https://Stackoverflow.com/users/7108653",
"pm_score": 2,
"selected": true,
"text": "https://api.openai.com/v1/completions {\n \"id\": \"cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7\",\n \"object\": \"text_completion\",\n \"created\": 1589478378,\n \"model\": \"text-davinci-003\",\n \"choices\": [\n {\n \"text\": \"\\n\\nThis is indeed a test\",\n \"index\": 0,\n \"logprobs\": null,\n \"finish_reason\": \"length\"\n }\n ],\n \"usage\": {\n \"prompt_tokens\": 5,\n \"completion_tokens\": 7,\n \"total_tokens\": 12\n }\n }\n json.data https://api.openai.com/v1/models json.data[0].text text https://api.openai.com/v1/completions if (json.data && json.data.length > 0) {\n const article = json.data[0].text;\n return article;\n} else {\n return 'No article found for the given topic.';\n}\n if (json.choices && json.choices.length > 0) {\n const article = json.choices[0].text;\n return article;\n} else {\n return 'No article found for the given topic.';\n}\n response.getContentText()"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7954236/"
] |
74,667,623
|
<pre><code>user_input = int(input('Enter input: '))
if type(user_input) == "<class 'int'>":
print('This is a integer.')
</code></pre>
<p>The code above outputs nothing to the console. I am just confused because it is very simple and looks like it should work.</p>
<p>I've tried removing the int() in the input line which output nothing, I understand this because user_input turns into a string but I do not understand why it outputs nothing when user_input is defined as an integer.</p>
|
[
{
"answer_id": 74668192,
"author": "doubleunary",
"author_id": 13045193,
"author_profile": "https://Stackoverflow.com/users/13045193",
"pm_score": 0,
"selected": false,
"text": "console.log(response.getContentText()) { \"title\": \"OpenAI API Example Article\", \"author\": \"John Doe\", \"content\": \"This is an example of an article retrieved using the OpenAI API. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco est laborum.\", \"source\": \"www.example.com\" } title content const json = JSON.parse(response.getContentText());\n const { title, content } = json;\n console.log(title);\n console.log(content);\n console.log(response.getContentText()) [{ \"title\": ... }, { \"title\": ... }] const { title, content } = json[0];\n json JSON.parse() articleObject"
},
{
"answer_id": 74672449,
"author": "Tanaike",
"author_id": 7108653,
"author_profile": "https://Stackoverflow.com/users/7108653",
"pm_score": 2,
"selected": true,
"text": "https://api.openai.com/v1/completions {\n \"id\": \"cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7\",\n \"object\": \"text_completion\",\n \"created\": 1589478378,\n \"model\": \"text-davinci-003\",\n \"choices\": [\n {\n \"text\": \"\\n\\nThis is indeed a test\",\n \"index\": 0,\n \"logprobs\": null,\n \"finish_reason\": \"length\"\n }\n ],\n \"usage\": {\n \"prompt_tokens\": 5,\n \"completion_tokens\": 7,\n \"total_tokens\": 12\n }\n }\n json.data https://api.openai.com/v1/models json.data[0].text text https://api.openai.com/v1/completions if (json.data && json.data.length > 0) {\n const article = json.data[0].text;\n return article;\n} else {\n return 'No article found for the given topic.';\n}\n if (json.choices && json.choices.length > 0) {\n const article = json.choices[0].text;\n return article;\n} else {\n return 'No article found for the given topic.';\n}\n response.getContentText()"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20309887/"
] |
74,667,658
|
<p>I try to make a simple file upload server. I wonder if it stores the uploaded file in a ram or hard disk since the container itself run as a virtual-machine in ram so it should not be able to have access to the disk right? unless I specify the bind-mounted volume option. So if the user upload a lot of files to the server at some points it's going to crash since it doesn't have ram space to store the files.</p>
|
[
{
"answer_id": 74668192,
"author": "doubleunary",
"author_id": 13045193,
"author_profile": "https://Stackoverflow.com/users/13045193",
"pm_score": 0,
"selected": false,
"text": "console.log(response.getContentText()) { \"title\": \"OpenAI API Example Article\", \"author\": \"John Doe\", \"content\": \"This is an example of an article retrieved using the OpenAI API. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco est laborum.\", \"source\": \"www.example.com\" } title content const json = JSON.parse(response.getContentText());\n const { title, content } = json;\n console.log(title);\n console.log(content);\n console.log(response.getContentText()) [{ \"title\": ... }, { \"title\": ... }] const { title, content } = json[0];\n json JSON.parse() articleObject"
},
{
"answer_id": 74672449,
"author": "Tanaike",
"author_id": 7108653,
"author_profile": "https://Stackoverflow.com/users/7108653",
"pm_score": 2,
"selected": true,
"text": "https://api.openai.com/v1/completions {\n \"id\": \"cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7\",\n \"object\": \"text_completion\",\n \"created\": 1589478378,\n \"model\": \"text-davinci-003\",\n \"choices\": [\n {\n \"text\": \"\\n\\nThis is indeed a test\",\n \"index\": 0,\n \"logprobs\": null,\n \"finish_reason\": \"length\"\n }\n ],\n \"usage\": {\n \"prompt_tokens\": 5,\n \"completion_tokens\": 7,\n \"total_tokens\": 12\n }\n }\n json.data https://api.openai.com/v1/models json.data[0].text text https://api.openai.com/v1/completions if (json.data && json.data.length > 0) {\n const article = json.data[0].text;\n return article;\n} else {\n return 'No article found for the given topic.';\n}\n if (json.choices && json.choices.length > 0) {\n const article = json.choices[0].text;\n return article;\n} else {\n return 'No article found for the given topic.';\n}\n response.getContentText()"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9740664/"
] |
74,667,749
|
<p>Im just curious why the linethrough worked on everything even the textbox placeholders but not with the text inside all the buttons, with css or not.
``</p>
<pre><code>function strike(){
document.getElementById("root").style.textDecoration= "line-through";
}
function unstrike(){
document.getElementById("root").style.textDecoration= null;
}
function App() {
return (
<div className="container">
<Form state={userIsRegistered} />
<button onClick={strike}>strike</button>
<button onClick={unstrike}>unstrike</button>
</div>
);
}
</code></pre>
<p>``</p>
<p>Even if i targeted the root. What should I do to include it when i click on the strike button?</p>
|
[
{
"answer_id": 74668192,
"author": "doubleunary",
"author_id": 13045193,
"author_profile": "https://Stackoverflow.com/users/13045193",
"pm_score": 0,
"selected": false,
"text": "console.log(response.getContentText()) { \"title\": \"OpenAI API Example Article\", \"author\": \"John Doe\", \"content\": \"This is an example of an article retrieved using the OpenAI API. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco est laborum.\", \"source\": \"www.example.com\" } title content const json = JSON.parse(response.getContentText());\n const { title, content } = json;\n console.log(title);\n console.log(content);\n console.log(response.getContentText()) [{ \"title\": ... }, { \"title\": ... }] const { title, content } = json[0];\n json JSON.parse() articleObject"
},
{
"answer_id": 74672449,
"author": "Tanaike",
"author_id": 7108653,
"author_profile": "https://Stackoverflow.com/users/7108653",
"pm_score": 2,
"selected": true,
"text": "https://api.openai.com/v1/completions {\n \"id\": \"cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7\",\n \"object\": \"text_completion\",\n \"created\": 1589478378,\n \"model\": \"text-davinci-003\",\n \"choices\": [\n {\n \"text\": \"\\n\\nThis is indeed a test\",\n \"index\": 0,\n \"logprobs\": null,\n \"finish_reason\": \"length\"\n }\n ],\n \"usage\": {\n \"prompt_tokens\": 5,\n \"completion_tokens\": 7,\n \"total_tokens\": 12\n }\n }\n json.data https://api.openai.com/v1/models json.data[0].text text https://api.openai.com/v1/completions if (json.data && json.data.length > 0) {\n const article = json.data[0].text;\n return article;\n} else {\n return 'No article found for the given topic.';\n}\n if (json.choices && json.choices.length > 0) {\n const article = json.choices[0].text;\n return article;\n} else {\n return 'No article found for the given topic.';\n}\n response.getContentText()"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20675197/"
] |
74,667,758
|
<p>This will raise an <code>Error: Hydration failed because the initial UI does not match what was rendered on the server.</code> error:</p>
<pre class="lang-js prettyprint-override"><code>const [selectedOrganizationShortId, setSelectedOrganizationShortId] =
useLocalStorage<string>('teamId', undefined)
</code></pre>
<p>This will not:</p>
<pre class="lang-js prettyprint-override"><code>const [selectedOrganizationShortId, setSelectedOrganizationShortId] =
useState<string>(undefined)
const [selectedProgramId, saveSelectedProgramId] = useState<
string | undefined
>(undefined)
</code></pre>
<p>though both does the same. I would use <code>useLocalStorage</code> as it is handy convenience solution, but seems it is not compatible with Next.js.</p>
<p><code>useLocalStorage</code> is used from here: <a href="https://usehooks-ts.com/react-hook/use-local-storage" rel="nofollow noreferrer">https://usehooks-ts.com/react-hook/use-local-storage</a></p>
|
[
{
"answer_id": 74668192,
"author": "doubleunary",
"author_id": 13045193,
"author_profile": "https://Stackoverflow.com/users/13045193",
"pm_score": 0,
"selected": false,
"text": "console.log(response.getContentText()) { \"title\": \"OpenAI API Example Article\", \"author\": \"John Doe\", \"content\": \"This is an example of an article retrieved using the OpenAI API. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco est laborum.\", \"source\": \"www.example.com\" } title content const json = JSON.parse(response.getContentText());\n const { title, content } = json;\n console.log(title);\n console.log(content);\n console.log(response.getContentText()) [{ \"title\": ... }, { \"title\": ... }] const { title, content } = json[0];\n json JSON.parse() articleObject"
},
{
"answer_id": 74672449,
"author": "Tanaike",
"author_id": 7108653,
"author_profile": "https://Stackoverflow.com/users/7108653",
"pm_score": 2,
"selected": true,
"text": "https://api.openai.com/v1/completions {\n \"id\": \"cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7\",\n \"object\": \"text_completion\",\n \"created\": 1589478378,\n \"model\": \"text-davinci-003\",\n \"choices\": [\n {\n \"text\": \"\\n\\nThis is indeed a test\",\n \"index\": 0,\n \"logprobs\": null,\n \"finish_reason\": \"length\"\n }\n ],\n \"usage\": {\n \"prompt_tokens\": 5,\n \"completion_tokens\": 7,\n \"total_tokens\": 12\n }\n }\n json.data https://api.openai.com/v1/models json.data[0].text text https://api.openai.com/v1/completions if (json.data && json.data.length > 0) {\n const article = json.data[0].text;\n return article;\n} else {\n return 'No article found for the given topic.';\n}\n if (json.choices && json.choices.length > 0) {\n const article = json.choices[0].text;\n return article;\n} else {\n return 'No article found for the given topic.';\n}\n response.getContentText()"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239219/"
] |
74,667,776
|
<p>i'm currently trying to solve a problem by counting the repeated sequences of character
for example:- input:"aaabbcc" output should be printed as 3; input:"aabbcde" output:2. even if a repeated sequencce occurs two or more time it should be considered as 1?</p>
<pre><code>private int stringocc1(String m) {
int count=0;
for (int i = 0; i < m.length(); i++) {
for (int j = 0; j < m.length(); j++) {
if(m.charAt(i)==m.charAt(j)) {
count++;
}
}
}
return count;
}
</code></pre>
|
[
{
"answer_id": 74668192,
"author": "doubleunary",
"author_id": 13045193,
"author_profile": "https://Stackoverflow.com/users/13045193",
"pm_score": 0,
"selected": false,
"text": "console.log(response.getContentText()) { \"title\": \"OpenAI API Example Article\", \"author\": \"John Doe\", \"content\": \"This is an example of an article retrieved using the OpenAI API. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco est laborum.\", \"source\": \"www.example.com\" } title content const json = JSON.parse(response.getContentText());\n const { title, content } = json;\n console.log(title);\n console.log(content);\n console.log(response.getContentText()) [{ \"title\": ... }, { \"title\": ... }] const { title, content } = json[0];\n json JSON.parse() articleObject"
},
{
"answer_id": 74672449,
"author": "Tanaike",
"author_id": 7108653,
"author_profile": "https://Stackoverflow.com/users/7108653",
"pm_score": 2,
"selected": true,
"text": "https://api.openai.com/v1/completions {\n \"id\": \"cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7\",\n \"object\": \"text_completion\",\n \"created\": 1589478378,\n \"model\": \"text-davinci-003\",\n \"choices\": [\n {\n \"text\": \"\\n\\nThis is indeed a test\",\n \"index\": 0,\n \"logprobs\": null,\n \"finish_reason\": \"length\"\n }\n ],\n \"usage\": {\n \"prompt_tokens\": 5,\n \"completion_tokens\": 7,\n \"total_tokens\": 12\n }\n }\n json.data https://api.openai.com/v1/models json.data[0].text text https://api.openai.com/v1/completions if (json.data && json.data.length > 0) {\n const article = json.data[0].text;\n return article;\n} else {\n return 'No article found for the given topic.';\n}\n if (json.choices && json.choices.length > 0) {\n const article = json.choices[0].text;\n return article;\n} else {\n return 'No article found for the given topic.';\n}\n response.getContentText()"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20663066/"
] |
74,667,777
|
<p>I have a hitbox with a script called "accept", I then have 2 prefabs that have a public bool of "isPoor". One of the prefabs = true, the other = false.</p>
<p>When the prefabs with isPoor = true goes into the "accept" hitbox I want the game to fail, and when isPoor = false goes into "accept" hitbox I want the player to win.</p>
<p>The problem with the code I have is that it only ever fails the game, even when an NPC with isPoor = false goes into the "accept" hitbox.</p>
<p>This is the code for the accept hitbox.</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class accept : MonoBehaviour
{
public LayerMask grabbable;
public GameObject Spawner;
bool isPoor;
public GameManager gameManager;
public void OnTriggerEnter2D(Collider2D other)
{
isPoor = other.gameObject.GetComponent<Poor>().isPoor;
if (isPoor = true)
{
gameManager.GameOver();
}
if (isPoor = false)
{
gameManager.GameWon();
}
Destroy(other.gameObject);
Spawner.GetComponent<Spawner>().Spawn();
}
}
</code></pre>
<p>It's my first time using Unity so I'm a bit stumped. But it seems that the script just treats both prefabs as if they had isPoor = true.</p>
|
[
{
"answer_id": 74667832,
"author": "Olivier Jacot-Descombes",
"author_id": 880990,
"author_profile": "https://Stackoverflow.com/users/880990",
"pm_score": 2,
"selected": true,
"text": "isPoor class accept OnTriggerEnter2D = = == // bool isPoor; drop this declaration!\n\npublic void OnTriggerEnter2D(Collider2D other)\n{\n bool isPoor = other.gameObject.GetComponent<Poor>().isPoor;\n if (isPoor) {\n // isPoor == true here\n gameManager.GameOver();\n } else {\n // isPoor == false here\n gameManager.GameWon();\n }\n\n Destroy(other.gameObject);\n Spawner.GetComponent<Spawner>().Spawn();\n}\n true if false if"
},
{
"answer_id": 74668542,
"author": "Kanhaya Tyagi",
"author_id": 14945515,
"author_profile": "https://Stackoverflow.com/users/14945515",
"pm_score": 0,
"selected": false,
"text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class accept : MonoBehaviour\n{\n public LayerMask grabbable;\n public GameObject Spawner;\n bool isPoor;\n public GameManager gameManager;\n\n public void OnTriggerEnter2D(Collider2D other)\n {\n\n if (other.gameObject.GetComponent<Poor>().isPoor)\n gameManager.GameOver();\n else\n gameManager.GameWon();\n\n Destroy(other.gameObject);\n\n Spawner.GetComponent<Spawner>().Spawn();\n\n }\n\n}\n\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20675073/"
] |
74,667,793
|
<p>I don't understand what the difference between</p>
<pre class="lang-c prettyprint-override"><code>int main(int argc, char* argv[]){;}
</code></pre>
<p>and</p>
<pre class="lang-c prettyprint-override"><code>int main(int argc, const char* argv[]){;}
</code></pre>
<p>is.</p>
<p>I'm aware of the difference between a <code>char*[]</code> and <code>const char*[]</code> but I wonder why one would like to use the latter.</p>
<p>Are there use cases where one would want to change command line arguments? What's the best practice about adding <code>const</code>?</p>
|
[
{
"answer_id": 74667874,
"author": "Eric Postpischil",
"author_id": 298225,
"author_profile": "https://Stackoverflow.com/users/298225",
"pm_score": 4,
"selected": true,
"text": "int main(int argc, char *argv[]) main int main(int argc, const char *argv[]) const char *[] const char *[] main const char *argv[] char *argv[] const char *argv[]"
},
{
"answer_id": 74668031,
"author": "human bean",
"author_id": 17186475,
"author_profile": "https://Stackoverflow.com/users/17186475",
"pm_score": 2,
"selected": false,
"text": "char** argv int main(void) { /* ... */ }\n argc argv int main(int argc, char *argv[]) { /* ... */ }`\n int typedef int argv char ** argv const char char argc argv argv const main char **argv const const char **argv const"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20675205/"
] |
74,667,805
|
<p>I tried to add a directory path to <code>sys.path</code>, but it gives me an error:</p>
<pre class="lang-py prettyprint-override"><code>import sys
sys.path.append("C:\Users\tamer\Desktop\code\python\modules")
</code></pre>
<pre class="lang-py prettyprint-override"><code>SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
</code></pre>
|
[
{
"answer_id": 74667874,
"author": "Eric Postpischil",
"author_id": 298225,
"author_profile": "https://Stackoverflow.com/users/298225",
"pm_score": 4,
"selected": true,
"text": "int main(int argc, char *argv[]) main int main(int argc, const char *argv[]) const char *[] const char *[] main const char *argv[] char *argv[] const char *argv[]"
},
{
"answer_id": 74668031,
"author": "human bean",
"author_id": 17186475,
"author_profile": "https://Stackoverflow.com/users/17186475",
"pm_score": 2,
"selected": false,
"text": "char** argv int main(void) { /* ... */ }\n argc argv int main(int argc, char *argv[]) { /* ... */ }`\n int typedef int argv char ** argv const char char argc argv argv const main char **argv const const char **argv const"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20675252/"
] |
74,667,819
|
<p>Center the numeric input box vertically in the content area<br />
<img src="https://i.stack.imgur.com/3NdSx.png" alt="image" /></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-css lang-css prettyprint-override"><code>input {
vertical-align:middle
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
<span>
<input type="number" id="number" value="8" min="1" max="20">
密码位数
</span>
</p>
</code></pre>
</div>
</div>
</p>
<pre><code>To no avail
</code></pre>
|
[
{
"answer_id": 74667874,
"author": "Eric Postpischil",
"author_id": 298225,
"author_profile": "https://Stackoverflow.com/users/298225",
"pm_score": 4,
"selected": true,
"text": "int main(int argc, char *argv[]) main int main(int argc, const char *argv[]) const char *[] const char *[] main const char *argv[] char *argv[] const char *argv[]"
},
{
"answer_id": 74668031,
"author": "human bean",
"author_id": 17186475,
"author_profile": "https://Stackoverflow.com/users/17186475",
"pm_score": 2,
"selected": false,
"text": "char** argv int main(void) { /* ... */ }\n argc argv int main(int argc, char *argv[]) { /* ... */ }`\n int typedef int argv char ** argv const char char argc argv argv const main char **argv const const char **argv const"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20675230/"
] |
74,667,821
|
<p>My input.txt is as below</p>
<pre><code> \n\n \n \n\n \n\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n \r\n\r\n\r\n \r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n hello boys\r\n boys\r\n boys\r\n\r\n Download PDF\r\n PDF\r\n X\r\n Close Window\r\n\r\n\r\n\r\n
This boys text has undergone conversion so that it is mobile and web-friendly. This may have created formatting or alignment issues. Please refer to the PDF copy for a print-friendly version.
\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n
BOYS CLUB AUSTRALIA
\r\n
26 July 2019
\r\n
hello boys
\r\n
\r\nhello boys
\r\n
--------------------------------------------------------------------------------------------------------------------------------------
\r\n
Introduction
\r\n\r\n
1. \r\n
This letter to let you know that your application has been successful with our school
\r\n
</code></pre>
<p>I am trying to remove unnecessary patterns like "\n\n", "\r\r", "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
While parsing, I want to remove all the special patterns and want to have only text and numbers.</p>
<p>I have tried as below.</p>
<pre><code>with open (data, "r", encoding='utf-8') as myfile:
for line in myfile:
line.rstrip()
line = re.sub(r'\r\n', '', line)
with open("out.txt", "a", encoding='utf-8') as output:
output.write(line)
</code></pre>
<p>But even '\r\n' is not getting removed in output file. Thanks.</p>
|
[
{
"answer_id": 74667874,
"author": "Eric Postpischil",
"author_id": 298225,
"author_profile": "https://Stackoverflow.com/users/298225",
"pm_score": 4,
"selected": true,
"text": "int main(int argc, char *argv[]) main int main(int argc, const char *argv[]) const char *[] const char *[] main const char *argv[] char *argv[] const char *argv[]"
},
{
"answer_id": 74668031,
"author": "human bean",
"author_id": 17186475,
"author_profile": "https://Stackoverflow.com/users/17186475",
"pm_score": 2,
"selected": false,
"text": "char** argv int main(void) { /* ... */ }\n argc argv int main(int argc, char *argv[]) { /* ... */ }`\n int typedef int argv char ** argv const char char argc argv argv const main char **argv const const char **argv const"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11930479/"
] |
74,667,822
|
<p>this my html code</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<title>pyscript demo</title>
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
</head>
<body>
<py-script src="pythonfile.py"></py-script>
</body>
</html>
</code></pre>
<p>and this my python program code</p>
<pre><code>lst = [["a", 45], ["b", 40], ["c", 18], ["d", 17]]
name = input("Enter your name:")
print("Searching in list")
for item in lst:
if item[0] == name:
print("name:", item[0], "age:", item[1])
</code></pre>
<p>I have tried to run python program in html webpage the html web page is working and the python code is not running is html webpage</p>
|
[
{
"answer_id": 74667874,
"author": "Eric Postpischil",
"author_id": 298225,
"author_profile": "https://Stackoverflow.com/users/298225",
"pm_score": 4,
"selected": true,
"text": "int main(int argc, char *argv[]) main int main(int argc, const char *argv[]) const char *[] const char *[] main const char *argv[] char *argv[] const char *argv[]"
},
{
"answer_id": 74668031,
"author": "human bean",
"author_id": 17186475,
"author_profile": "https://Stackoverflow.com/users/17186475",
"pm_score": 2,
"selected": false,
"text": "char** argv int main(void) { /* ... */ }\n argc argv int main(int argc, char *argv[]) { /* ... */ }`\n int typedef int argv char ** argv const char char argc argv argv const main char **argv const const char **argv const"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20167592/"
] |
74,667,823
|
<p>I am currently working on a program that should create a list out of your own inputs. It should list your inputs under each other but if I try to press the "Hinzufügen" button (Enter button), nothing happens and my inputs aren't listed. This is for a school project and I am stuck with this for some time.</p>
<p>I already tried to look if I made some spelling mistakes and I corrected them. I really don't know what makes my programme not working. I would appreciate any help.</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>var enterButton = document.getElementById("enter");
var input = document.getElementById("benutzerInput");
var ul = document.querySelector("ul");
var item = document.getElementsByTagName("li");
function erstellenEintrag() {
var li = document.createElement("li");
ul.appendChild(li);
}
enterButton.addEventListener("click", erstellenEintrag);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
background: #1d1e22;
text-align: center;
font-family: "Arial", sans-serif;
color: #ffffff;
}
h1 {
text-transform: uppercase;
font-weight: 800;
}
input {
border-radius: 5px;
min-width: 80%;
padding: 20px;
margin-top: 10px;
}
#enter {
border: none;
padding: 20px;
border-radius: 5px;
color: #ffffff;
background-color: #4eb9cd;
transition: all 0.75s ease;
font-weight: normal;
}
ul {
padding-left: 15px;
padding-right: 15px;
}
li {
text-align: left;
margin-top: 20px;
list-style: none;
padding: 20px;
color: #ffffff;
text-transform: capitalize;
font-weight: 600;
border-radius: 5px;
margin-bottom: 10;
background: #4eb9cd;
transition: all 0.75s ease;
}
li:hover {
background: none;
border: none;
float: right;
color: #ffffff;
font-weight: 800;
}
.done {
background: #51df51 !important;
color: #00891f;
text-decoration: line-through;
}
.delete {
display: none;
}
body {
background: #1d1e22;
color: rgb(255, 0, 153)
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Kühlflex</h1>
<div>
<input id="benutzerInput" type="text" placeholder="Neuer Eintrag..." />
<button id="enter">Hinzufügen</button>
</div>
</ul></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74667879,
"author": "N.braha",
"author_id": 6121138,
"author_profile": "https://Stackoverflow.com/users/6121138",
"pm_score": 0,
"selected": false,
"text": "function erstellenEintrag() {\n var li = document.createElement(\"li\");\n // Set the content of the <li> element to the value of the input element\n li.innerHTML = input.value;\n ul.appendChild(li);\n // Reset the value of the input element\n input.value = \"\";\n}\n"
},
{
"answer_id": 74668009,
"author": "gautam thakur",
"author_id": 20633741,
"author_profile": "https://Stackoverflow.com/users/20633741",
"pm_score": -1,
"selected": false,
"text": " window.onload = function() {\n var enterButton = document.getElementById(\"enter\");\n \n function erstellenEintrag() {\n var ul = document.querySelector(\"ul\");\n var input = document.getElementById(\"benutzerInput\").value;\n var li = document.createElement(\"li\");\n li.append(input);\n ul.appendChild(li);\n }\n } \n\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20219637/"
] |
74,667,871
|
<p>I need to have an async consumer method to consume messages from RabbitMq. My problem is that the rabbitmq client for .net rely on an event handler.
I tried to implement a blocking system with a Semaphore, which is working with a low volume. When I'm getting more volume, some messages are lost.</p>
<p>Here is my implementation :</p>
<pre><code> private long _lock;
private string _message;
private object _tag;
private readonly SemaphoreSlim _signal;
public void Configure()
{
Interlocked.Exchange(ref _lock, 0);
var consumer = new EventingBasicConsumer(_channel);
consumer.Received += (sender, ea) =>
{
_message = Encoding.UTF8.GetString(ea.Body.ToArray());
_tag = ea.DeliveryTag;
Interlocked.Exchange(ref _lock, 1);
_signal.Release();
};
_channel.BasicConsume(queue: _rabbitConfig.Queue, autoAck: true, consumer: consumer);
}
public async Task<string> Consume(CancellationToken cancellationToken)
{
while (0 == Interlocked.Read(ref _lock))
{
await _signal.WaitAsync();
}
Interlocked.Exchange(ref _lock, 0);
return _message;
}
</code></pre>
<p>I alse tried using BufferBlock but some messages are still lost.
Is there any other way to implement a system keeping my Consume() method ?</p>
|
[
{
"answer_id": 74667879,
"author": "N.braha",
"author_id": 6121138,
"author_profile": "https://Stackoverflow.com/users/6121138",
"pm_score": 0,
"selected": false,
"text": "function erstellenEintrag() {\n var li = document.createElement(\"li\");\n // Set the content of the <li> element to the value of the input element\n li.innerHTML = input.value;\n ul.appendChild(li);\n // Reset the value of the input element\n input.value = \"\";\n}\n"
},
{
"answer_id": 74668009,
"author": "gautam thakur",
"author_id": 20633741,
"author_profile": "https://Stackoverflow.com/users/20633741",
"pm_score": -1,
"selected": false,
"text": " window.onload = function() {\n var enterButton = document.getElementById(\"enter\");\n \n function erstellenEintrag() {\n var ul = document.querySelector(\"ul\");\n var input = document.getElementById(\"benutzerInput\").value;\n var li = document.createElement(\"li\");\n li.append(input);\n ul.appendChild(li);\n }\n } \n\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2884046/"
] |
74,667,881
|
<p>im using <a href="https://pub.dev/packages/flutter_svg" rel="nofollow noreferrer">flutter_svg</a> package for svg. and now i want to use a svg inside a container as decoration like this,</p>
<pre class="lang-dart prettyprint-override"><code>
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: SvgPicture.string(
'''<svg viewBox="...">...</svg>'''
),
),
),
)
</code></pre>
<p>but the problem is DecorationImage peram expecting 'ImageProvider'. how can i do this ?</p>
<p>i tried <a href="https://pub.dev/packages/flutter_svg_provider" rel="nofollow noreferrer">flutter_svg_provider</a> but its also not working. i found <a href="https://stackoverflow.com/questions/59217425/svgpicture-cant-be-assigned-to-imageprovider">this</a> solution, but dont know how to use.</p>
|
[
{
"answer_id": 74667879,
"author": "N.braha",
"author_id": 6121138,
"author_profile": "https://Stackoverflow.com/users/6121138",
"pm_score": 0,
"selected": false,
"text": "function erstellenEintrag() {\n var li = document.createElement(\"li\");\n // Set the content of the <li> element to the value of the input element\n li.innerHTML = input.value;\n ul.appendChild(li);\n // Reset the value of the input element\n input.value = \"\";\n}\n"
},
{
"answer_id": 74668009,
"author": "gautam thakur",
"author_id": 20633741,
"author_profile": "https://Stackoverflow.com/users/20633741",
"pm_score": -1,
"selected": false,
"text": " window.onload = function() {\n var enterButton = document.getElementById(\"enter\");\n \n function erstellenEintrag() {\n var ul = document.querySelector(\"ul\");\n var input = document.getElementById(\"benutzerInput\").value;\n var li = document.createElement(\"li\");\n li.append(input);\n ul.appendChild(li);\n }\n } \n\n"
}
] |
2022/12/03
|
[
"https://Stackoverflow.com/questions/74667881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10016592/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.