qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,167,436 | <p>Hope you're well. I'm studying Javascript after a few years without studying programming. The first thing I learned was Java and object-oriented programming. I remember the important parts like classes and methods. Studying Javascript on the Mozilla website with explanations, they say that a function is a different kind of object.</p>
<p>To me this doesn't make sense because an object is like something, like a cat. A function is more like a verb, an action that something or someone does, like the cat's leap. Wouldn't it be better to explain to people that functions are not objects, but actions, rather than seeing that it's an object too?</p>
<p>Object for me is like the subject of a sentence. Like: You work". The object/subject of the sentence is "You" and the action/verb/function is "work". We can't say, for example, "Run dances" because "Run" is a function, not an object Does that make sense, or am I just crazy? haha</p>
<p>Thank you friends.</p>
| [
{
"answer_id": 74167444,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": -1,
"selected": false,
"text": "// create a function\nfunction run() {\n console.log('run')\n}\n\n// calls a function\nrun()\n\n// adds a property ... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20311076/"
] |
74,167,470 | <p>Here I am counting each character in a string and return that character with it's number of occurences in the string. e.g.: <code>ab("aabbc")</code> and return a string: <code>a2b2c1</code></p>
<p>However I have a list here where instead of returning <code>a2b2c1</code>, it returns <code>['a',2,'b',2,'c',1]</code>. I want it to return it in the form of a string, and not a list.</p>
<p>Here's what I did:</p>
<pre><code>def ab(n):
char = []
for i in n:
if i not in char:
char.append(i)
count = n.count(i)
char.append(count)
return(char)
</code></pre>
| [
{
"answer_id": 74167526,
"author": "Sash Sinha",
"author_id": 6328256,
"author_profile": "https://Stackoverflow.com/users/6328256",
"pm_score": 1,
"selected": false,
"text": "def ab(n):\n char = []\n i = 0\n while i < len(n):\n run_length = 1\n while i + 1 < len(n)... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20214604/"
] |
74,167,479 | <p>Here is my SQL Server table</p>
<pre><code>ID Job ParentID MyTeam
1 CEO NULL
2 CFO 1
3 CTO 1
4 CMO 1
5 Accounting Manager 2
6 Payroll Manager 2
7 Data Manager 3
8 Software Manager 3
9 Data Analyst 7
10 Data Engineer 7
</code></pre>
<p>I need to fill the MyTeam field this way</p>
<p>each job will have all people that job managing</p>
<p><strong>CEO's</strong> team will be <code>CEO, CFO, CTO, CMO, Accounting Manager, Payroll Manager, Data Manager, Software Manager, Data Analyst, Data Engineer</code></p>
<p><strong>CFO's</strong> team will be <code>CFO, Accounting Manager, Payroll Manager</code></p>
<p><strong>CTO's</strong> team will be <code>CTO, Data Manager, Software Manager, Data Analyst, Data Engineer</code></p>
<p>I built a loop on this data and contacted each job to its parent and so on</p>
<p>but this is too slow</p>
<p>Is there a faster one update statement to do that fast</p>
| [
{
"answer_id": 74168533,
"author": "seanb",
"author_id": 14267425,
"author_profile": "https://Stackoverflow.com/users/14267425",
"pm_score": 1,
"selected": false,
"text": "/* Initial data setup */\n\nCREATE TABLE #Emps (ID int PRIMARY KEY, Job nvarchar(30), ParentID int);\nINSERT INTO ... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1492229/"
] |
74,167,483 | <p>I'm creating my first little project and I'm having a button toggle a class on an element. When I use the toggle I can see in the browser that chrome shows as if it changed but it changes to the same thing that's on it right now. I've even tried toggling a different random class onto it and cannot get it to toggle that on or off. Not quite sure what I'm doing wrong.</p>
<p>Heres my javascript:</p>
<pre><code>document.querySelectorAll(".open").forEach((item) => {
item.addEventListener("click", (event) => {
event.target
.parentElement
.parentElement
.parentElement
.parentElement
.children[1]
.classList.toggle("hidden");
});
});
</code></pre>
<p>And my HTML code</p>
<pre class="lang-html prettyprint-override"><code><div class="search-container">
<ul class="blade-list">
<li class="blade">
<div class="title">
<h1 class="blade-material">27574-10</h1>
<div class="buttons">
<button class="open" id="open1">
<img
class="open"
id="open1"
src="img/svg/plus-empty.svg"
alt="Expand specs"
/>
</button>
<button class="print" id="print1">
<img
class="print"
id="print1"
src="img/svg/printer-empty.svg"
alt="Print"
/>
</button>
</div>
</div>
<div
class="specs-container hidden"
id="specs-container-1"
></div>
</li>
</ul>
</div>
</code></pre>
| [
{
"answer_id": 74167549,
"author": "SollyBunny",
"author_id": 7483019,
"author_profile": "https://Stackoverflow.com/users/7483019",
"pm_score": 2,
"selected": false,
"text": "querySelectorAll(\".open\")"
},
{
"answer_id": 74167572,
"author": "Mister Jojo",
"author_id": 10... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9579662/"
] |
74,167,502 | <p>I'm on Windows 11, using Python Python 3.10.8 and pip 22.3.</p>
<p>I'm trying to create a new selenium project using webdriver-manager for the webdriver.</p>
<p>When I create a new project, I pip install webdriver-manager.</p>
<p>I have tried in venvs, as well as resinstalling python but get the same result.</p>
<p>Then I try to import webdriver-manager and it fails.</p>
<pre><code>from webdriver_manager.chrome import ChromeDriverManager
</code></pre>
<p>I get the error:</p>
<pre><code>ModuleNotFoundError: No module named 'packaging'
</code></pre>
<p>Full stack trace:</p>
<pre><code>Traceback (most recent call last):
File "z:\Social Research\TikTok\selenium\learning\whyWontUInstall\main.py", line 1, in <module>
from webdriver_manager.chrome import ChromeDriverManager
File "C:\Users\noahp\AppData\Local\Programs\Python\Python310\lib\site-packages\webdriver_manager\chrome.py", line 7, in <module>
from webdriver_manager.drivers.chrome import ChromeDriver
File "C:\Users\noahp\AppData\Local\Programs\Python\Python310\lib\site-packages\webdriver_manager\drivers\chrome.py", line 1, in <module>
from packaging import version
ModuleNotFoundError: No module named 'packaging'
</code></pre>
| [
{
"answer_id": 74168372,
"author": "relent95",
"author_id": 1186624,
"author_profile": "https://Stackoverflow.com/users/1186624",
"pm_score": 3,
"selected": false,
"text": "> pip install packaging\n"
},
{
"answer_id": 74258521,
"author": "lam vu Nguyen",
"author_id": 1194... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17231651/"
] |
74,167,514 | <p>I'm using the Arduino IDE and langauge (C) to program a Raspberry Pi Pico. I have a project that uses a 16x2 LCD and a button to control it's backlight. The button and everything other works correctly, my problem is that every time i press the switch, the backlight flickers, and need to press it random times to stay on or off i suggest due to bouncing.
I want to clear the 22 bit in the ICSR register of the RP2040 to clear any pending stuff in the interrupt buffer before return from the interrupt.
<a href="https://datasheets.raspberrypi.com/rp2040/rp2040-datasheet.pdf#tab-registerlist_m0plus" rel="nofollow noreferrer">https://datasheets.raspberrypi.com/rp2040/rp2040-datasheet.pdf#tab-registerlist_m0plus</a>
(page 87, or 86 on the bottom of the page)</p>
<p>My code so far:</p>
<pre><code>#include <Adafruit_BMP280.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
#include <hd44780.h>
#include <hd44780ioClass/hd44780_I2Cexp.h>
#include "hardware/regs/m0plus.h"
//#include <pico/stdlib.h>
//#include <hardware/pwm.h>
Adafruit_BMP280 bmp; //I2C
hd44780_I2Cexp lcd(0x27, 16, 2);
const uint16_t AirValue = 1023;
const uint16_t WaterValue = 660; //measured fully submerged in water
const uint16_t DarkValue = 0;
const uint16_t LightValue = 1023;
uint16_t soilMoisture;
uint16_t soilMoisturePercent;
uint16_t lightIntensity;
uint16_t lightIntensityPercent;
volatile bool lcdBacklightStatus = false;
byte pressureChar[] = { 0b01000, 0b11110, 0b11100, 0b01000, 0b00011, 0b01111, 0b00000, 0b11110
};
byte moistureChar[] = { 0b00000, 0b00100, 0b01110, 0b11111, 0b11111, 0b11111, 0b01110, 0b00000
};
byte lightIntensityChar[] = { 0b00000, 0b01110, 0b10001, 0b11011, 0b10101, 0b01110, 0b01110, 0b00100
};
byte temperatureChar[] = { 0b01000, 0b10111, 0b10100, 0b11111, 0b11100, 0b11100, 0b11100, 0b01000
};
byte separatorWall[] = { 0b10101, 0b01010, 0b10101, 0b01010, 0b10101, 0b01010, 0b10101, 0b01010
};
byte degreeChar[] = { 0b00111, 0b00101, 0b00111, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000
};
void backlight();
void setup() {
lcd.begin(0x27, 16, 2);
lcd.createChar(0, pressureChar);
lcd.createChar(1, moistureChar);
lcd.createChar(2, lightIntensityChar);
lcd.createChar(3, temperatureChar);
lcd.createChar(4, separatorWall);
lcd.createChar(5, degreeChar);
lcd.home();
pinMode(26, INPUT); //soilMoisture
pinMode(27, INPUT); //lightIntensity
pinMode(17, INPUT); //button
attachInterrupt(digitalPinToInterrupt(17), backlight, RISING);
//Serial.begin(9600);
bmp.begin(0x76);
bmp.setSampling(Adafruit_BMP280::MODE_NORMAL, /* Operating Mode. */
Adafruit_BMP280::SAMPLING_X2, /* Temp. oversampling */
Adafruit_BMP280::SAMPLING_X16, /* Pressure oversampling */
Adafruit_BMP280::FILTER_X16, /* Filtering. */
Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */
lcd.clear();
lcd.backlight(); //lcd.noBacklight();
lcd.setCursor(1,0);
lcd.print("Plant Station");
lcd.setCursor(6,1);
lcd.print("V0.8");
delay(2000);
lcd.noBacklight();
lcd.clear();
lcd.setCursor(0,0);
lcd.write(byte(3));
lcd.setCursor(10,0);
lcd.write(byte(2));
lcd.setCursor(0,1);
lcd.write(byte(0));
lcd.setCursor(10,1);
lcd.write(byte(1));
lcd.setCursor(7,0);
lcd.write(byte(5));
lcd.setCursor(8,0);
lcd.print("C");
lcd.setCursor(15,0);
lcd.print("%");
lcd.setCursor(6,1);
lcd.print("hPa");
lcd.setCursor(15,1);
lcd.print("%");
}
void loop() {
soilMoisture = analogRead(26);
soilMoisturePercent = map(soilMoisture, AirValue, WaterValue, 0, 100);
lightIntensity = analogRead(27);
lightIntensityPercent = map(lightIntensity, DarkValue, LightValue, 0, 100);
if(soilMoisturePercent >= 100) soilMoisturePercent = 100;
else if(soilMoisturePercent <= 0) soilMoisturePercent = 0;
if(lightIntensityPercent >= 100) lightIntensityPercent = 100;
else if(lightIntensityPercent <= 0) lightIntensityPercent = 0;
//Serial.print("Moisture: ");
//Serial.println(soilMoisture);
//Serial.print("Percentage: ");
//Serial.println(soilMoisturePercent);
//Serial.print("LightIntensity: ");
//Serial.println(lightIntensity);
//Serial.print(soilMoisture);
//Serial.println(soilMoisturePercent);
//BANNED CURSOR POSITIONS: 0,0 9,0 0,1 9,1 6,0 14,0 7,0 15,0 5,1 15,1
lcd.setCursor(3,0);
lcd.print(bmp.readTemperature(),1);
lcd.setCursor(2,1);
lcd.print(((bmp.readPressure()/100)),0);
if(soilMoisturePercent < 10) {
lcd.setCursor(13,1);
lcd.print(" ");
lcd.print(soilMoisturePercent);
} else if(soilMoisturePercent < 100) {
lcd.setCursor(13,1);
lcd.print(soilMoisturePercent);
} else {
lcd.setCursor(12,1);
lcd.print(soilMoisturePercent);
}
if(lightIntensityPercent < 10) {
lcd.setCursor(13,0);
lcd.print(" ");
lcd.print(lightIntensityPercent);
} else if(lightIntensityPercent < 100) {
lcd.setCursor(13,0);
lcd.print(lightIntensityPercent);
} else {
lcd.setCursor(12,0);
lcd.print(lightIntensityPercent);
}
delay(60000);
}
void backlight() {
//noInterrupts();
detachInterrupt(digitalPinToInterrupt(17));
if(lcdBacklightStatus == true) {
lcd.noBacklight();
} else if(lcdBacklightStatus == false) {
lcd.backlight();
}
delayMicroseconds(500000);
//interrupts();
attachInterrupt(digitalPinToInterrupt(17), backlight, RISING);
lcdBacklightStatus = !lcdBacklightStatus;
//want to clear ICSR register here i guess
}
</code></pre>
<p>I may be not clear enough, sorry if that's the case, English isn't my main langauge.</p>
| [
{
"answer_id": 74168372,
"author": "relent95",
"author_id": 1186624,
"author_profile": "https://Stackoverflow.com/users/1186624",
"pm_score": 3,
"selected": false,
"text": "> pip install packaging\n"
},
{
"answer_id": 74258521,
"author": "lam vu Nguyen",
"author_id": 1194... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17019379/"
] |
74,167,552 | <p>I'm creating a snippet file for my project. However, I only want to defined the scope for some snippets for <strong>Vue Files</strong> only. Of course I know I can omit the scope property to apply it in all kinds of files, but I don't want that.</p>
<p>I tried different options (<code>vue, html, vuejs</code>) like this:</p>
<p><a href="https://i.stack.imgur.com/2JRDz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2JRDz.png" alt="enter image description here" /></a></p>
<p>However this snippet is not being displayed.</p>
<p><a href="https://i.stack.imgur.com/DZZmr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DZZmr.png" alt="enter image description here" /></a></p>
<p>If I removed the scope, the snippet is displayed.</p>
<p><a href="https://i.stack.imgur.com/IfzGm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IfzGm.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/1KJEs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1KJEs.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/Ss7Bs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ss7Bs.png" alt="enter image description here" /></a></p>
<p>But I don't want this, because it shows up in all kinds of files where I don't need it.</p>
<p>I searched in the official documentation in: <a href="https://code.visualstudio.com/docs/editor/userdefinedsnippets#_snippet-scope" rel="nofollow noreferrer">https://code.visualstudio.com/docs/editor/userdefinedsnippets#_snippet-scope</a>
but they don't show the list of different possibilities, including of course VueJS.</p>
<p><a href="https://i.stack.imgur.com/w233T.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w233T.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74168372,
"author": "relent95",
"author_id": 1186624,
"author_profile": "https://Stackoverflow.com/users/1186624",
"pm_score": 3,
"selected": false,
"text": "> pip install packaging\n"
},
{
"answer_id": 74258521,
"author": "lam vu Nguyen",
"author_id": 1194... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2506701/"
] |
74,167,557 | <p>The signature I'm looking for is <code>(Maybe a, b) -> (a, b)</code>, which hoogle returns <a href="https://hoogle.haskell.org/?hoogle=(Maybe%20a%2C%20b)%20-%3E%20(a%2C%20b)" rel="nofollow noreferrer">no results</a> for. I can easily write my own as</p>
<pre class="lang-hs prettyprint-override"><code>import Data.Maybe (fromJust)
fromJustTuple :: (Maybe a, b) -> (a, b)
fromJustTuple (a, b) = (fromJust a, b)
</code></pre>
<p>The context is that I'm using <a href="https://hackage.haskell.org/package/containers-0.6.6/docs/Data-Map-Strict.html#v:updateLookupWithKey" rel="nofollow noreferrer">updateLookupWithKey</a> on a <code>Map</code> where I can guarantee that the keys I'm querying exist. I could say</p>
<pre class="lang-hs prettyprint-override"><code>let (Just x, myMap') = updateLookupWithKey f k myMap
</code></pre>
<p>, but then I'd have to disable <code>incomplete-uni-patterns</code>, which I don't want to do.</p>
<p>Backing up a bit, this may be an <a href="https://xyproblem.info/" rel="nofollow noreferrer">XY problem</a>. I'm happy to hear so and learn about a different, more idiomatic approach.</p>
| [
{
"answer_id": 74168372,
"author": "relent95",
"author_id": 1186624,
"author_profile": "https://Stackoverflow.com/users/1186624",
"pm_score": 3,
"selected": false,
"text": "> pip install packaging\n"
},
{
"answer_id": 74258521,
"author": "lam vu Nguyen",
"author_id": 1194... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12162258/"
] |
74,167,567 | <p>I am making an app in android studio using an API that returns the following:</p>
<pre><code>[{"domains": ["upes.ac.in"], "country": "India", "state-province": "Dehradun", "web_pages": ["https://www.upes.ac.in/"], "name": "University of Petroleum and Energy Studies", "alpha_two_code": "IN"}]
</code></pre>
<p>I run it as follows:</p>
<pre><code>public void onResponse(String response) {
listaUniversidades = new ArrayList<>();
JSONArray jsonArray = new JSONArray(response);
String nombreUni, pais, url;
for (int i = 0; i < jsonArray.length(); i++) {
nombreUni = jsonArray.getJSONObject(i).getString("name");
pais = jsonArray.getJSONObject(i).getString("country");
url = jsonArray.getJSONObject(i).getString("web_pages"));
texto.setText(url);
listaUniversidades.add(new Universidad(nombreUni, pais, url));
}}
</code></pre>
<p>The thing is that the web_pages returns the following: ["http://.www.upes.ac.in/"]</p>
<p>How could I make it return the correct url? Since that way I can not access the university website.</p>
<p>Thank you!</p>
| [
{
"answer_id": 74167700,
"author": "Gayuh Hikmawan",
"author_id": 6046077,
"author_profile": "https://Stackoverflow.com/users/6046077",
"pm_score": 0,
"selected": false,
"text": "String nombreUni, pais, url;\n"
},
{
"answer_id": 74167787,
"author": "Aleph Santos",
"author... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18386055/"
] |
74,167,578 | <p>So I have to write a short Java program which will input of the height a ball is dropped from. Assuming that on each bounce the height reached reduces by 5%, output the number of bounces that occur before
the ball stops bouncing.</p>
<p>I understand the logic of how to work this out but I cannot grasp how to put this into code.</p>
<p>I have some unfinished code, but just hit a brick wall. Any suggestions would be greatly appreciated.</p>
<pre class="lang-java prettyprint-override"><code>package doWhileLoops;
import java.util.Scanner;
public class Ex3 {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int height = 0, noBounces = 0, fivePer = 0;
fivePer = height /100 * 5;
System.out.print("\n\tEnter the height in feet that the ball will be dropped from: ");
height = key.nextInt();
do {
System.out.print("\n\tIt took " + (height - fivePer));
fivePer--;
} while (height > 0);
}
}
</code></pre>
| [
{
"answer_id": 74167700,
"author": "Gayuh Hikmawan",
"author_id": 6046077,
"author_profile": "https://Stackoverflow.com/users/6046077",
"pm_score": 0,
"selected": false,
"text": "String nombreUni, pais, url;\n"
},
{
"answer_id": 74167787,
"author": "Aleph Santos",
"author... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17854360/"
] |
74,167,585 | <p>Hello I have a database of football matches for prediction.</p>
<pre><code>Team<-rep("A",10)
Match<-1:10
Outcome<-c("W","W","W","L","L","W","L","W","L","L")
mymatch<-data.frame(Team,Match,Outcome)
</code></pre>
<p>I would like to create a column with the number of successive wins but also successive losses. When the team loses the win sequence starts again at zero. Similarly when it wins the sequence of defeat resumes at zero. I also need a column for the end of a sequence, whether it is a win or a loss.</p>
<pre><code> Team Match Outcome win_seq win_end loss_seq loss_end
1 A 1 W 1 0 0 0
2 A 2 W 2 0 0 0
3 A 3 W 3 1 0 0
4 A 4 L 0 0 1 0
5 A 5 L 0 0 2 1
6 A 6 W 1 1 0 0
7 A 7 L 0 0 1 1
8 A 8 W 1 1 0 0
9 A 9 L 0 0 1 0
10 A 10 L 0 0 2 1
</code></pre>
| [
{
"answer_id": 74167641,
"author": "Ben Bolker",
"author_id": 190277,
"author_profile": "https://Stackoverflow.com/users/190277",
"pm_score": 1,
"selected": false,
"text": "W, W, W, L, L"
},
{
"answer_id": 74167712,
"author": "Andre Wildberg",
"author_id": 9462095,
"a... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11652655/"
] |
74,167,611 | <br />
Hello,<br />
For educational purposes, I am building a django app with multiple models and relationships. <br />
According to the official tutorial and many implementations I found online, the database models and serializers as well as views are all defined in single files: "models.py", "serializers.py", and "views.py". <br />
So, the project directory looks as follows:
<pre><code>> my_app
> migrations
> __init__.py
> admin.py
> models.py
> apps.py
> serializers.py
> tests.py
> urls.py
> views.py
</code></pre>
<p>Depending on how many models are included in the app, those files may grow to hundreds or even thousands lines of code.
As a result, developing and maintaining the application becomes extremely challenging.
I would like to split these files so that every model (and coresponding serializer and view) will be defined in a separate per-model file. <br /> As follows:</p>
<pre><code>> my_app
> migrations
> models
> __init__.py
> model1.py
> model2.py
> model3.py
> model4.py
> serializers
> __init__.py
> model1_serializers.py
> model2_serializers.py
> model3_serializers.py
> model4_serializers.py
> views
> __init__.py
> model1_views.py
> model2_views.py
> model3_views.py
> model4_views.py
> __init__.py
> admin.py
> apps.py
> tests.py
> urls.py
</code></pre>
<p>I encountered some difficulties in splitting these files and have not yet found an optimal solution. <br /> <br />
<strong>The Problem</strong></p>
<p>In order to define a serializer -> corresponding model should be imported. <br />
And in order to define a view -> corresponding model and serializers should be imported. <br /></p>
<p>There are some difficulties importing objects from models/files located in the same level as the parent directoriey.
For example: Importing model to serializers/model1_serializers.py results an error</p>
<blockquote>
<p>from models.model1 import Model1 # error: Unresolved reference 'models' <br />
from my_app.models.model1 import Model1 # error: Unresolved reference 'my_app'</p>
</blockquote>
<p><strong>What I have tried</strong></p>
<ol>
<li>Mark project directory as source in pycharm - After marking "my_app" folder as source the following import works. But running the code outside of pycharm (cmd for example) results import errors.</li>
</ol>
<blockquote>
<pre><code>from models.model1 import Model1
</code></pre>
</blockquote>
<ol start="2">
<li>Adding the project direcrtory to sys.path - sys.path contains a list of directories that the interpreter will search in for the required module. So adding the following lines should make import possible (in file my_app/views/model1_views.py), but it doesnt work, pycharm still marks the import lines as errors. Do you know where is my mistake?</li>
</ol>
<blockquote>
<pre><code>import os
from sys import path
path.append(os.path.dirname(os.path.dirname(__file__)))
from my_app.models.model1 import Model1
</code></pre>
</blockquote>
<p>I would very appreciate if you could explain my mistake and propose a solution for spliting those files, thank you!</p>
| [
{
"answer_id": 74167641,
"author": "Ben Bolker",
"author_id": 190277,
"author_profile": "https://Stackoverflow.com/users/190277",
"pm_score": 1,
"selected": false,
"text": "W, W, W, L, L"
},
{
"answer_id": 74167712,
"author": "Andre Wildberg",
"author_id": 9462095,
"a... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7052374/"
] |
74,167,614 | <p>I'm trying some mapping and calculation between dataframes.</p>
<p>Is there any examples or anyone can help how to use python code to do this?</p>
<p>I've 2 dataframes:</p>
<pre><code>products components
c1 c2 c3 c4
p1 1 0 1 0
p2 0 1 1 0
p3 1 0 0 1
p4 0 1 0 1
</code></pre>
<pre><code> items cost
components i1 i2 i3 i4
c1 0 10 30 0
c2 20 10 0 0
c3 0 0 10 15
c4 20 0 0 30
</code></pre>
<p>The end results should be a dictionary contains the sum of the cost for each components and find the maximum:</p>
<pre><code>{p1: [c1,c3] } -> {p1: [i2+i3,i3+i4] } -> {p1: [40,25] } -> {p1: 40 }
{p2: [c2,c3] } -> {p2: [i1+i2,i3+i4] } -> {p2: [30,25] } -> {p2: 30 }
{p3: [c1,c4] } -> {p3: [i2+i3,i1+i4] } -> {p3: [40,50] } -> {p3: 50 }
{p4: [c2,c4] } -> {p4: [i1+i2,i1+i4] } -> {p4: [30,50] } -> {p4: 50 }
</code></pre>
| [
{
"answer_id": 74167641,
"author": "Ben Bolker",
"author_id": 190277,
"author_profile": "https://Stackoverflow.com/users/190277",
"pm_score": 1,
"selected": false,
"text": "W, W, W, L, L"
},
{
"answer_id": 74167712,
"author": "Andre Wildberg",
"author_id": 9462095,
"a... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15350235/"
] |
74,167,639 | <p>My output differs from what my professor wants, below is my code, my output, and the desired output. The white space between the number and the 's' and the ':' is the issue, it shouldn't be there. I've tried the leading whitespace strip function, the trailing one, the join function. I keep getting errors. Something simple that I can just add in is best. Please help!!!</p>
<pre><code> import random
roll_list = [] #empty list for appending rolls
num_rolls = 100 #number of times the program will run
def init_list(): #defines initial list for possible outcomes
for x in range(0,13):
roll_list.append(0)
def roll_dice(): #rolls the dice and sums the outcomes
dice1 = random.randint(1,6)#random operator to make all rolls random 1-6
dice2 = random.randint(1,6)
roll = dice1 + dice2 #sum of each roll
return roll #keeps the program in this loop
def update_list(roll): #defines updated list of possible outcomes
previousvalue = roll_list.pop(roll)
roll_list.insert(roll,previousvalue + 1)
def print_histogram(): #defines the for loop below, printing the desired outcome
for numbers in range(2, 13):
print((numbers), 's', ':', '*' * roll_list[numbers])
# main program
init_list() #executeds first def, list of values 2-12
for y in range(0,num_rolls): #excecutes second def, roll dice, 100 times
update_list(roll_dice())#executes third def, updated list 100 values long
print_histogram() #excecutes fourth def, printing desired outcome
</code></pre>
<p>My output:</p>
<pre><code>2 s : ****
3 s : ***
4 s : ************
5 s : ***********
6 s : ******************
7 s : ************
8 s : ************
9 s : **********
10 s : **********
11 s : ****
12 s : ****
</code></pre>
<p>Desired output:</p>
<pre><code>2s: *****
3s: *********
4s: *******
5s: ****
6s: ************
7s: *****
8s: **********
9s: **
10s: ********
11s: ****
12s: *************
</code></pre>
| [
{
"answer_id": 74167652,
"author": "slitvinov",
"author_id": 1534218,
"author_profile": "https://Stackoverflow.com/users/1534218",
"pm_score": 0,
"selected": false,
"text": "print(\"%ds:\" % numbers, '*' * roll_list[numbers])\n"
},
{
"answer_id": 74167671,
"author": "Federico... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20257924/"
] |
74,167,662 | <p>I want to create a list of string serial numbers such that knowing a few, a casual user cannot guess others.</p>
<p>eg if I run the following, serial1 should look nothing like serial2 and thus could not guess serial3</p>
<pre><code>def scramble(txt):
# encoding happens here
return str(out)
serial1 = scramble('123456')
serial2 = scramble('123457')
</code></pre>
<p>Any alphanumeric output is fine as long as it will have a direct relationship to the input.
Hashlib would work but all output types are way too long and truncation introduces possible collisions
Perhaps some kind of simple symmetrical encryption?</p>
<p>Any ideas?</p>
| [
{
"answer_id": 74169554,
"author": "John M.",
"author_id": 18950910,
"author_profile": "https://Stackoverflow.com/users/18950910",
"pm_score": 1,
"selected": false,
"text": "random"
}
] | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7654773/"
] |
74,167,673 | <p>The question says:</p>
<p>Given an array of integers.</p>
<p>Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers. 0 is neither positive nor negative.</p>
<p>If the input is an empty array or is null, return an empty array.</p>
<pre><code> def count_positives_sum_negatives(last)
pos = []
neg = []
x = lst.each
if x % 2 == 0
pos.push x
else neg.push x
end
y = pos.count
z = neg.sum
puts "[#{y},#{z}]"
end
</code></pre>
<p>I tested with</p>
<pre><code> count_positives_sum_negatives([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15])
#should return [10, -65]
</code></pre>
<p>I am unsure why my one only gives an error message:</p>
<pre class="lang-none prettyprint-override"><code>An error occurred while loading spec_helper.
Failure/Error: if (x % 2) == 0
NoMethodError:
undefined method `%' for #<Enumerator: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]:each>
# ./lib/solution.rb:7:in `count_positives_sum_negatives'
# ./lib/solution.rb:18:in `<top (required)>'
# ./spec/spec_helper.rb:1:in `require'
# ./spec/spec_helper.rb:1:in `<top (required)>'
No examples found.
No examples found.
</code></pre>
| [
{
"answer_id": 74168019,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "lst.each do |x|"
},
{
"answer_id": 74168263,
"author": "Cary Swoveland",
"author_id": 256970,
"au... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20308905/"
] |
74,167,697 | <p>Im trying to make a method that checks if the object will be of a faculty type based from the faculty class. This is the code but im getting a syntax error?</p>
<pre><code>def addFaculty(self, f_obj):
if f_obj isinstance(f_obj, Faculty):
return True
else:
self.directory.append(f_obj)
</code></pre>
| [
{
"answer_id": 74167716,
"author": "Fares_Hassen",
"author_id": 20310974,
"author_profile": "https://Stackoverflow.com/users/20310974",
"pm_score": 0,
"selected": false,
"text": "def addFaculty(self, f_obj): \n return isinstance(f_obj, Faculty)\n"
},
{
"answer_id": 74167720,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20151553/"
] |
74,167,722 | <p>i recently change pubspec.yaml file but flutter can't display my font</p>
<pre><code> fonts:
- family: Amatic
fonts:
- asset: assets/fonts/Amatic-Bold.ttf
- asset: assets/fonts/Amatic-Regular.ttf
</code></pre>
| [
{
"answer_id": 74167716,
"author": "Fares_Hassen",
"author_id": 20310974,
"author_profile": "https://Stackoverflow.com/users/20310974",
"pm_score": 0,
"selected": false,
"text": "def addFaculty(self, f_obj): \n return isinstance(f_obj, Faculty)\n"
},
{
"answer_id": 74167720,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15440015/"
] |
74,167,723 | <p>I want to make a module script like module.py and I want to call these modules in other script files. How can I do that?</p>
<p><strong>module.py</strong></p>
<pre><code> import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import os
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
opt=Options()
opt.add_experimental_option("excludeSwitches", ["enable-automation"])
driver = webdriver.Chrome(options=opt)
insta = 'https://www.instagram.com/'
driver.get(insta)
delay = 3
</code></pre>
<p>and <strong>main.py</strong></p>
<pre><code>import module
........ my code
</code></pre>
| [
{
"answer_id": 74167716,
"author": "Fares_Hassen",
"author_id": 20310974,
"author_profile": "https://Stackoverflow.com/users/20310974",
"pm_score": 0,
"selected": false,
"text": "def addFaculty(self, f_obj): \n return isinstance(f_obj, Faculty)\n"
},
{
"answer_id": 74167720,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20311286/"
] |
74,167,734 | <p>I want to periodically fetch data (using asynchronous <code>reqwest</code>), which is then served at an http endpoint using <code>actix-web</code> as a server.
(I have a data source that has a fixed format, that I want to have read by a service that require a different format, so I need to transform the data.)
I've tried to combine actix concepts with the thread sharing state example from the Rust book, but I don't understand the error or how to solve it.
This is the code minified as much as I was able:</p>
<pre><code>use actix_web::{get, http, web, App, HttpResponse, HttpServer, Responder};
use std::sync::{Arc, Mutex};
use tokio::time::{sleep, Duration};
struct AppState {
status: String,
}
#[get("/")]
async fn index(data: web::Data<Mutex<AppState>>) -> impl Responder {
let state = data.lock().unwrap();
HttpResponse::Ok()
.insert_header(http::header::ContentType::plaintext())
.body(state.status.to_owned())
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let status_string = get_state().await.unwrap();
let app_data = Arc::new(Mutex::new(web::Data::new(AppState {
status: status_string,
})));
let app_data1 = Arc::clone(&app_data);
actix_web::rt::spawn(async move {
loop {
println!("I get executed every 2-ish seconds!");
sleep(Duration::from_millis(2000)).await;
let res = get_state().await;
let mut app_data = app_data1.lock().unwrap();
// Edit 2: this line is not accepted by the compiler
// Edit 2: *app_data.status = res.unwrap();
// Edit 2: but this line is accepted
*app_data = web::Data::new(AppState { status: res });
}
});
let app_data2 = Arc::clone(&app_data);
// Edit 2: but I get an error here now
HttpServer::new(move || App::new().app_data(app_data2).service(index))
.bind(("127.0.0.1", 9090))?
.run()
.await
}
async fn get_state() -> Result<String, Box<dyn std::error::Error>> {
let client = reqwest::Client::new().get("http://ipecho.net/plain".to_string());
let status = client.send().await?.text().await?;
println!("got status: {status}");
Ok(status)
}
</code></pre>
<p>But I get the following error:</p>
<pre class="lang-none prettyprint-override"><code>error[E0308]: mismatched types
--> src/main.rs:33:32
|
33 | *app_data.status = res.unwrap();
| ---------------- ^^^^^^^^^^^^ expected `str`, found struct `String`
| |
| expected due to the type of this binding
error[E0277]: the size for values of type `str` cannot be known at compilation time
--> src/main.rs:33:13
|
33 | *app_data.status = res.unwrap();
| ^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `str`
= note: the left-hand-side of an assignment must have a statically known size
Some errors have detailed explanations: E0277, E0308.
For more information about an error, try `rustc --explain E0277`.
</code></pre>
<p>Why do I suddenly get a <code>str</code>? Is there an easy fix or is my approach to solving this wrong?
<code>Edit:</code> Maybe removing the <code>*</code> is the right way to go, as <em>Peter Hall</em> suggests, but that gives me the following error instead:</p>
<pre><code>error[E0594]: cannot assign to data in an `Arc`
--> src/main.rs:33:13
|
33 | app_data.status = res.unwrap();
| ^^^^^^^^^^^^^^^ cannot assign
|
= help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Arc<AppState>`
error[E0507]: cannot move out of `app_data2`, a captured variable in an `Fn` closure
--> src/main.rs:38:49
|
37 | let app_data2 = Arc::clone(&app_data);
| --------- captured outer variable
38 | HttpServer::new(move || App::new().app_data(app_data2).service(index))
| ------- ^^^^^^^^^ move occurs because `app_data2` has type `Arc<std::sync::Mutex<Data<AppState>>>`, which does not implement the `Copy` trait
| |
| captured by this `Fn` closure
Some errors have detailed explanations: E0507, E0594.
For more information about an error, try `rustc --explain E0507`.
</code></pre>
<p><code>Edit 2:</code> I now get the following error (code changes commented with 'Edit 2' above):</p>
<pre><code>error[E0507]: cannot move out of `app_data2`, a captured variable in an `Fn` closure
--> src/main.rs:46:49
|
45 | let app_data2 = app_data.clone();
| --------- captured outer variable
46 | HttpServer::new(move || App::new().app_data(app_data2).service(index))
| ------- ^^^^^^^^^ move occurs because `app_data2` has type `Arc<Mutex<Data<AppState>>>`, which does not implement the `Copy` trait
| |
| captured by this `Fn` closure
For more information about this error, try `rustc --explain E0507`.
</code></pre>
<p>My <code>Cargo.toml</code> dependencies:</p>
<pre><code>[dependencies]
actix-web = "4.2.1"
reqwest = "0.11.12"
tokio = "1.21.2"
</code></pre>
| [
{
"answer_id": 74167716,
"author": "Fares_Hassen",
"author_id": 20310974,
"author_profile": "https://Stackoverflow.com/users/20310974",
"pm_score": 0,
"selected": false,
"text": "def addFaculty(self, f_obj): \n return isinstance(f_obj, Faculty)\n"
},
{
"answer_id": 74167720,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/97874/"
] |
74,167,739 | <p>I have an issue to write a RestControler Junit in Spring Boot. I have a problem in listBook in when option.</p>
<p>How can I fix the issue?</p>
<p>Here is the method of restController shown below.</p>
<pre><code>@GetMapping("/search")
public ResponseEntity<List<BookResponse>> listBook(@RequestParam(name = "size") int size, @RequestParam(name = "page") int page) {
final Long userID = userService.findInContextUser().getId();
return ResponseEntity.ok(bookListService.listBooks(size, page, userID));
}
</code></pre>
<p>Here is the test method shown below</p>
<pre><code>@Test
void itShouldGetBooks_WhenSearch() throws Exception {
// given - precondition or setup
BookResponse response1 = BookResponse.builder()
.title("Book 1")
.authorName("authorName")
.build();
BookResponse response2 = BookResponse.builder()
.title("Book 1")
.authorName("authorName2")
.build();
List<BookResponse> response = List.of(response1, response2);
UserDto userDto = UserDto.builder()
.id(1L)
.username("username")
.build();
// when - action or the behaviour that we are going test
when(userService.findInContextUser()).thenReturn(userDto);
when(bookListService.listBooks(anyInt(), anyInt(), eq(userDto.getId()))).thenReturn(response);
// then - verify the output
mockMvc.perform(get("/api/v1/book/search?size=" + anyInt() + "&page=" + anyInt()) // HERE IS THE ERROR LINE
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(jsonPath("$", hasSize(2))) // ERROR IS HERE
.andExpect(status().isOk());
}
</code></pre>
<p>Here is the error message shown below.</p>
<pre><code> java.lang.AssertionError: JSON path "$"
Expected: a collection with size <2>
but: was LinkedHashMap <{error=Request processing failed; nested exception is org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
0 matchers expected, 2 recorded:
</code></pre>
| [
{
"answer_id": 74167716,
"author": "Fares_Hassen",
"author_id": 20310974,
"author_profile": "https://Stackoverflow.com/users/20310974",
"pm_score": 0,
"selected": false,
"text": "def addFaculty(self, f_obj): \n return isinstance(f_obj, Faculty)\n"
},
{
"answer_id": 74167720,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5719229/"
] |
74,167,747 | <p>I am struggling to understand classes/objects and using a csv with them.</p>
<p>I have a CSV with 26 rows, 1 being the header, the other containing rows of info. Small example below</p>
<pre class="lang-none prettyprint-override"><code>id,food,food_print,cal1,cal2,expi1999,expi2000,expi2001
1,bun,bun_bun,45.3434,199.32323,23.3333,45.4444,33.33333
2,burger,burger_bun,45.342343,200.34243,34.3333,0,9
3,pickle,pickle_seed,67.345454,34.3434,34,56,33
4,chicken,chicken_egg,44.34343,43.343343,43,434,34343
</code></pre>
<p>I have my class as follows:</p>
<pre><code>class City(object):
def __init__(self, food = 'n/a', foodprint = 'n/a', cal1 = -999, cal2 = -999,
expi1999 = -999, expi2000 = -999, expi2001 = -999)
self.food = food
self.foodprint = foodprint
self.cal1 = cal1
self.cal2 = cal2
self.expi1999 = expi1999
self.expi2000 = expi2000
self.expi2001 = expi2001
meals = []
foodfile = open('Food.csv', 'rt')
headers = foodfile.readline().strip().split(',')
headers = headers.split(',')
for line in foodfile:
foodfields = foodfile.readline().strip().split(',')
</code></pre>
<p>How do I write in the rows from my food csv into an object to be referenced in the class?</p>
| [
{
"answer_id": 74167716,
"author": "Fares_Hassen",
"author_id": 20310974,
"author_profile": "https://Stackoverflow.com/users/20310974",
"pm_score": 0,
"selected": false,
"text": "def addFaculty(self, f_obj): \n return isinstance(f_obj, Faculty)\n"
},
{
"answer_id": 74167720,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20125787/"
] |
74,167,749 | <p>Working on learning Ruby and RoR over here. Got Ruby, Brew, Bundle and Rails installed. Created a local Rails project on my Mac and was ready to start the local rails server.</p>
<p>But I get an error and I'm just too new to figure out what I should do. Unfortunately the tutorial (which has been easy to follow up to this point) doesn't address what to do next.</p>
<p>Any suggestions would be extremely appreciated.</p>
<p>Here's the error:</p>
<pre><code>... hello_world_ % rails server
Ignoring racc-1.6.0 because its extensions are not built. Try: gem pristine racc --version 1.6.0
bin/rails:3:in `require_relative': cannot load such file -- /Users/.../Dropbox/Mac/Documents/RailsProjects/hello_world_/config/boot (LoadError)
from bin/rails:3:in `<main>'
</code></pre>
| [
{
"answer_id": 74167716,
"author": "Fares_Hassen",
"author_id": 20310974,
"author_profile": "https://Stackoverflow.com/users/20310974",
"pm_score": 0,
"selected": false,
"text": "def addFaculty(self, f_obj): \n return isinstance(f_obj, Faculty)\n"
},
{
"answer_id": 74167720,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6916199/"
] |
74,167,755 | <p>I'm trying to make the search function work on this simple react app. I can see that it is getting the new data properly when I log it to the console, but it doesn't seem like the child component that builds the "page" to display the data with pagination is ever being called after the initial rendering. Codepen & code below:</p>
<p><a href="https://codepen.io/eacres/pen/LYmwmmZ" rel="nofollow noreferrer">https://codepen.io/eacres/pen/LYmwmmZ</a></p>
<pre><code>const propTypes = {
books: React.PropTypes.array.isRequired,
onChangePage: React.PropTypes.func.isRequired,
initialPage: React.PropTypes.number
}
const defaultProps = {
initialPage: 1
}
class Pagination extends React.Component {
constructor(props) {
super(props);
this.state = { pager: {} };
}
componentWillMount() {
// set page if books array isn't empty
if (this.props.books && this.props.books.length) {
this.setPage(this.props.initialPage);
}
}
componentDidUpdate(prevProps, prevState) {
// reset page if books array has changed
if (this.props.books !== prevProps.books) {
this.setPage(this.props.initialPage);
}
}
setPage(page) {
var books = this.props.books;
var pager = this.state.pager;
if (page < 1 || page > pager.totalPages) {
return;
}
// get new pager object for specified page
pager = this.getPager(books.length, page);
// get new page of books from books array
var pageofBooks = books.slice(pager.startIndex, pager.endIndex + 1);
// update state
this.setState({ pager: pager });
// call change page function in parent component
this.props.onChangePage(pageofBooks);
}
getPager(totalbooks, currentPage, pageSize) {
// default to first page
currentPage = currentPage || 1;
// default page size is 8
pageSize = pageSize || 8;
// calculate total pages
var totalPages = Math.ceil(totalbooks / pageSize);
var startPage, endPage;
if (totalPages <= 10) {
// less than 10 total pages so show all
startPage = 1;
endPage = totalPages;
} else {
// more than 10 total pages so calculate start and end pages
if (currentPage <= 6) {
startPage = 1;
endPage = 10;
} else if (currentPage + 4 >= totalPages) {
startPage = totalPages - 9;
endPage = totalPages;
} else {
startPage = currentPage - 5;
endPage = currentPage + 4;
}
}
// calculate start and end item indexes
var startIndex = (currentPage - 1) * pageSize;
var endIndex = Math.min(startIndex + pageSize - 1, totalbooks - 1);
// create an array of pages to ng-repeat in the pager control
var pages = [...Array((endPage + 1) - startPage).keys()].map(i => startPage + i);
// return object with all pager properties required by the view
return {
totalbooks: totalbooks,
currentPage: currentPage,
pageSize: pageSize,
totalPages: totalPages,
startPage: startPage,
endPage: endPage,
startIndex: startIndex,
endIndex: endIndex,
pages: pages
};
}
render() {
var pager = this.state.pager;
if (!pager.pages || pager.pages.length <= 1) {
// don't display pager if there is only 1 page
return null;
}
return (
<ul className="pagination">
<li className={pager.currentPage === 1 ? 'disabled' : ''}>
<a onClick={() => this.setPage(1)}>First</a>
</li>
<li className={pager.currentPage === 1 ? 'disabled' : ''}>
<a onClick={() => this.setPage(pager.currentPage - 1)}>Previous</a>
</li>
{pager.pages.map((page, index) =>
<li key={index} className={pager.currentPage === page ? 'active' : ''}>
<a onClick={() => this.setPage(page)}>{page}</a>
</li>
)}
<li className={pager.currentPage === pager.totalPages ? 'disabled' : ''}>
<a onClick={() => this.setPage(pager.currentPage + 1)}>Next</a>
</li>
<li className={pager.currentPage === pager.totalPages ? 'disabled' : ''}>
<a onClick={() => this.setPage(pager.totalPages)}>Last</a>
</li>
</ul>
);
}
}
Pagination.propTypes = propTypes;
Pagination.defaultProps = defaultProps;
/* App Component
-------------------------------------------------*/
class App extends React.Component {
constructor() {
super();
// an example array of books to be paged
axios.get(`https://goodreads-server-express--dotdash.repl.co/search/name`)
.then(response => {
this.setState({bookList: response.data.list}) ;
})
.catch(error => {
// edge case
// alert("Yikes! Looks like we don't have anything for that search. Please edit your search and try again.");
console.log(error);
});
this.state = {
bookList: [],
pageofBooks: []
};
this.onChangePage = this.onChangePage.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
onChangePage(pageofBooks) {
// update state with new page of books
this.setState({ pageofBooks: pageofBooks }, () => {
//console.log(this.state.pageofBooks)
});
}
handleChange (e) {
e.preventDefault();
this.setState({searchString: e.target.value})
}
handleSubmit (e) {
e.preventDefault();
this.setState({ bookList : [] });
// edge case
if (!this.state.searchString) {
alert('Oops! Please enter your search in the box below.')
} else {
axios.get(`https://goodreads-server-express--dotdash.repl.co/search/${this.state.searchString}`)
.then(response => {
this.setState({ bookList: response.data.list });
})
.catch(error => {
// edge case
alert("Yikes! Looks like we don't have anything for that search. Please edit your search and try again.");
console.log(error);
});
}
}
render() {
return (
<div>
<div className="container">
<div className="text-center">
<form className="search-bar">
<label htmlFor="search">Find me a book</label>
<input id="search" onChange={this.handleChange} />
<button onClick={this.handleSubmit}>Search</button>
</form>
<div className="search-results">
{this.state.pageofBooks.map( (item, i) =>
<BookCard book={item} key={item.title} />
)}
</div>
<Pagination books={this.state.bookList} onChangePage={this.onChangePage} />
</div>
</div>
<hr />
</div>
);
}
}
class BookCard extends React.Component {
constructor(props) {
super(props);
this.state = {
author: props.book.authorName,
title: props.book.title,
image: props.book.imageUrl
}
}
render() {
return (
<div className="book-card">
<div className="image__container">
<img src={this.state.image} />
</div>
<div className="book-card__header">
<h3>{this.state.author}</h3>
<h2>{this.state.title.length > 40 ? this.state.title.slice(0, 40) + '...' : this.state.title}</h2>
</div>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
</code></pre>
<p>Thanks in advance!</p>
| [
{
"answer_id": 74167899,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 0,
"selected": false,
"text": "class BookCard extends React.Component {\n constructor(props) {\n super(props);\n }\n\n render() {\n return ... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8566127/"
] |
74,167,766 | <p>I want to display the image of a product when it is clicked on in another form because on the first form the image size is small so I want it to show on a bigger form when its clicked on</p>
<p>code that shows the product image when the product is clicked on</p>
<pre><code>Private Sub ListBox1_Click()
Dim strFile As String
Me.cmb_Product.Value = Me.ListBox1.List(Me.ListBox1.ListIndex, 0)
iPath = ThisWorkbook.Path & "\Item Images\" & Me.cmb_Product.Value & ".JPG"
iPathNA = ThisWorkbook.Path & "\Item Images\NA.jpg"
strFile = iPath
If Len(Dir(strFile)) <> 0 Then
ItemImage.Picture = LoadPicture(strFile)
Else
ItemImage.Picture = LoadPicture(iPathNA)
End If
End Sub
</code></pre>
<p>code on image click event</p>
<pre><code>Private Sub ItemImage_Click()
productImage.Show False
End Sub
</code></pre>
<p>code in 2nd form</p>
<pre><code>Private Sub productImage_BeforeDragOver(ByVal Cancel As MSForms.ReturnBoolean, ByVal Data As MSForms.DataObject, ByVal X As Single, ByVal Y As Single, ByVal DragState As MSForms.fmDragState, ByVal Effect As MSForms.ReturnEffect, ByVal Shift As Integer)
productImage.Picture = LoadPicture(frm_Inventory_Management.iPathNA)
End Sub
</code></pre>
| [
{
"answer_id": 74170446,
"author": "FaneDuru",
"author_id": 2233308,
"author_profile": "https://Stackoverflow.com/users/2233308",
"pm_score": 1,
"selected": false,
"text": "Public"
},
{
"answer_id": 74212529,
"author": "Khola",
"author_id": 6889393,
"author_profile": ... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6889393/"
] |
74,167,774 | <p>I have created code with a MLX90640 Thermal Camera with a Raspberry Pi.</p>
<p>The code is shown below:</p>
<pre><code>import time,board,busio
import numpy as np
import adafruit_mlx90640
import matplotlib.pyplot as plt
print("Initializing MLX90640")
i2c = busio.I2C(board.SCL, board.SDA, frequency=800000) # setup I2C
mlx = adafruit_mlx90640.MLX90640(i2c) # begin MLX90640 with I2C comm
mlx.refresh_rate = adafruit_mlx90640.RefreshRate.REFRESH_2_HZ # set refresh rate
mlx_shape = (24,32)
print("Initialized")
# setup the figure for plotting
plt.ion() # enables interactive plotting
fig,ax = plt.subplots(figsize=(12,7))
therm1 = ax.imshow(np.zeros(mlx_shape),vmin=0,vmax=60) #start plot with zeros
cbar = fig.colorbar(therm1) # setup colorbar for temps
cbar.set_label('Temperature [$^{\circ}$C]',fontsize=14) # colorbar label
frame = np.zeros((24*32,)) # setup array for storing all 768 temperatures
t_array = []
print("Starting loop")
while True:
t1 = time.monotonic()
try:
mlx.getFrame(frame) # read MLX temperatures into frame var
data_array = (np.reshape(frame,mlx_shape)) # reshape to 24x32
therm1.set_data(np.fliplr(data_array)) # flip left to right
therm1.set_clim(vmin=np.min(data_array),vmax=np.max(data_array)) # set bounds
cbar.update_normal(therm1) # update colorbar range
plt.title(f"Max Temp: {np.max(data_array):.1f}C")
plt.pause(0.001) # required
#fig.savefig('mlx90640_test_fliplr.png',dpi=300,facecolor='#FCFCFC', bbox_inches='tight') # comment out to speed up
t_array.append(time.monotonic()-t1)
print('Sample Rate: {0:2.1f}fps'.format(len(t_array)/np.sum(t_array)))
except ValueError:
continue # if error, just read again
</code></pre>
<p>It showcases this output:</p>
<p><a href="https://i.stack.imgur.com/NjWAY.jpg" rel="nofollow noreferrer">Output of video</a></p>
<p>In the top right corner, you can see the x and y coordinates of the highest heat that was detected.</p>
<p>What I'm having trouble with is orienting the coordinates based on the middle of image instead of the bottom left.</p>
<p><a href="https://i.stack.imgur.com/5DZgr.gif" rel="nofollow noreferrer">Here is an example of what I'm trying to get</a></p>
<p>I'm trying to orient the x and y points from (0,0) in the very middle of the output and also print the x and y coordinates separately from the graph.</p>
<p>I'm sure there is a line of code I can input or change, but I'm having the worst trouble.</p>
| [
{
"answer_id": 74170446,
"author": "FaneDuru",
"author_id": 2233308,
"author_profile": "https://Stackoverflow.com/users/2233308",
"pm_score": 1,
"selected": false,
"text": "Public"
},
{
"answer_id": 74212529,
"author": "Khola",
"author_id": 6889393,
"author_profile": ... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19563976/"
] |
74,167,785 | <p>I have the following define:</p>
<pre><code>#define MY_CLASS MyClass
</code></pre>
<p>I'm trying to make a macro that will use MY_CLASS to expand to:</p>
<pre><code>#include "MyClass.h"
</code></pre>
<p>Something like (according to <a href="https://stackoverflow.com/questions/14396139/how-do-i-concatenate-two-macros-with-a-dot-between-them-without-inserting-spaces">this</a> answer):</p>
<pre><code>#define MY_CLASS MyClass
#define FILE_EXT h
#define M_CONC(A, B) M_CONC_(A, B)
#define M_CONC_(A, B) A##B
#define APP_BUILD M_CONC(MY_CLASS, M_CONC(.,FILE_EXT))
#include APP_BUILD
</code></pre>
<p>That one doesn't work though... I get these 3 errors:</p>
<pre><code>Expected "FILENAME" or <FILENAME>
Pasting formed '.h', an invalid preprocessing token
Pasting formed 'MyClass.', an invalid preprocessing token
</code></pre>
<p>Is it possible to do it somehow?</p>
| [
{
"answer_id": 74168522,
"author": "traveh",
"author_id": 2375105,
"author_profile": "https://Stackoverflow.com/users/2375105",
"pm_score": 0,
"selected": false,
"text": "#define MY_CLASS MyClass\n#define EMPTY\n#define MACRO1(x) #x\n#define MACRO2(x, y) MACRO1(x##y.h)\n#define MACRO3(x,... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2375105/"
] |
74,167,815 | <p><code>dput (Data)</code> is, as follows:</p>
<pre><code>structure(list(Year = c(1986, 1987, 1988, 1989, 1990, 1991, 1992,
1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001), RwandaGDP = c(266296395453522,
266232388162044, 278209717380819, 278108075482628, 271435453185924,
264610535380715, 280150385073342, 257433853555685, 128078318071279,
173019272512077, 195267342948145, 222311386633263, 242005217615319,
252537014428159, 273676681432581, 296896832706772), ChadGDP = c(221078469390513,
215510570376333, 248876690715831, 261033657789193, 250126438514823,
271475073131674, 293196997307684, 247136226809204, 272188148422562,
275553889112468, 282165595568286, 297579071872462, 318265518859647,
316009224207253, 313311638596115, 349837931311225), RwandaLifeExpectancy = c(50.233,
47.409, 43.361, 38.439, 33.413, 29.248, 26.691, 26.172, 27.738,
31.037, 35.38, 39.838, 43.686, 46.639, 48.649, 49.936), ChadLifeExpectancy = c(46.397,
46.601, 46.772, 46.91, 47.019, 47.108, 47.187, 47.265, 47.345,
47.426, 47.498, 47.559, 47.61, 47.657, 47.713, 47.789)), row.names = c(NA,
-16L), spec = structure(list(cols = list(Year = structure(list(), class = c("collector_double",
"collector")), RwandaGDP = structure(list(), class = c("collector_double",
"collector")), ChadGDP = structure(list(), class = c("collector_double",
"collector")), RwandaLifeExpectancy = structure(list(), class = c("collector_double",
"collector")), ChadLifeExpectancy = structure(list(), class = c("collector_double",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), delim = ";"), class = "col_spec"), problems = <pointer: 0x000001f0ef568410>, class = c("spec_tbl_df",
"tbl_df", "tbl", "data.frame"))
</code></pre>
<p>I come from performing a Difference in Differences regression in R, with the following code:</p>
<pre><code>GDP <- as.numeric(Data$RwandaGDP, Data$ChadGDP)
MyDataTime <- ifelse(Data$Year >= "1994", 1, 0)
MyDataTreated <- Data$RwandaLifeExpectancy
MyDataDiD <- MyDataTime * MyDataTreated
DidReg = lm(GDP ~ MyDataTime + MyDataTreated + MyDataDiD, data = Data)
summary(DidReg)
</code></pre>
<p>Now, there is only one thing left to do, which is to plot the results.</p>
<p>I am looking for something akin to what can be seen in point 3.4 (line plot) on this website:</p>
<p><a href="https://rpubs.com/phle/r_tutorial_difference_in_differences" rel="nofollow noreferrer">https://rpubs.com/phle/r_tutorial_difference_in_differences</a></p>
<p>However, when I try to adapt my code to the one that is facilitated on the aforementioned website, I keep getting the error "Discrete value supplied to continuous scale".</p>
<p>I've been stuck with this issue for hours, and I really don't know what I am doing wrong in my code.</p>
<p>Any help would be enormously appreciated!</p>
<p>Many thanks in advance!</p>
<p><strong>EDIT</strong></p>
<p>My adapted code is, as follows:</p>
<pre><code>Data %>%
mutate(label = if_else(Year == "1994", as.character(GDP), NA_character_)) %>%
ggplot(aes(x=Data$Year,y=Data$RwandaGDP, group=GDP)) +
geom_line(aes(color=GDP), size=1.2) +
geom_vline(xintercept = "Rwandan Genocide", linetype="dotted",
color = "black", size=1.1) +
scale_color_brewer(palette = "Accent") +
scale_y_continuous(limits = c(17,24)) +
ggrepel::geom_label_repel(aes(label = label),
nudge_x = 0.5, nudge_y = -0.5,
na.rm = TRUE) +
guides(scale="none") +
labs(x="", y="GDP") +
annotate(
"text",
x = "1994",
y = "",
label = "{Difference-in-Differences}",
angle = 90,
size = 3
)
</code></pre>
| [
{
"answer_id": 74168522,
"author": "traveh",
"author_id": 2375105,
"author_profile": "https://Stackoverflow.com/users/2375105",
"pm_score": 0,
"selected": false,
"text": "#define MY_CLASS MyClass\n#define EMPTY\n#define MACRO1(x) #x\n#define MACRO2(x, y) MACRO1(x##y.h)\n#define MACRO3(x,... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16567173/"
] |
74,167,845 | <p>I'm enjoying using react-admin and how promising this frontend seems to be for some dashboard development,</p>
<p>I followed a tutorial react-admin + loopback 4 and trying to filter a long list using a ReferenceInput + Autosuggestion as mentioned here <a href="https://marmelab.com/react-admin/AutocompleteInput.html#properties" rel="nofollow noreferrer"></a></p>
<p>the list of department show properly in the dropdown list and if I select an item the list gets filtered as it should, however if I type in, the results is an empty dropdown with "No Option" as a result.</p>
<p>Do I have to populate the list somewhere before passing it? or am I missing something? Below is an example of a machine list that I try to filter by department.</p>
<p>Thanks a lot</p>
<p><a href="https://i.stack.imgur.com/XQANF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XQANF.png" alt="the dropdown list show MOD4, the filter works if I click on it" /></a></p>
<p><a href="https://i.stack.imgur.com/cFhz3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cFhz3.png" alt="the dropdown list becomes empty if I type in the word MOD" /></a></p>
<pre><code>const machineFilters = [
<ReferenceInput
source='department_id'
reference='departments'
alwaysOn={true}
>
<AutocompleteInput />
</ReferenceInput>,
];
</code></pre>
<p>If I manually enter some choices (I tried with one only) the typing in seems to work, although I thought I wouldn't need to provide the choice according to the doc of RA</p>
<blockquote>
<p>Tip: If you want to populate the choices attribute with a list of
related records, you should decorate with
, and leave the choices empty</p>
</blockquote>
<p>EDIT:</p>
<p>i'm using loopback4, in postman i query this address</p>
<p><code>http://localhost:3000/categories?filter={"where": {"description": { "like": "marking","options": "i"}}}</code></p>
<p>in my RA I used</p>
<pre><code>const filterToQuery = (searchText) => ({
where: { description: `${searchText}` },
});
const machineFilters = [
<ReferenceInput
source='category_id'
reference='categories'
alwaysOn={true}
sort={{ field: 'code', order: 'ASC' }}
>
<AutocompleteInput
style={{ width: '300px' }}
source='categories'
filterToQuery={filterToQuery}
/>
</ReferenceInput>,
];
</code></pre>
<p>but still no luck so far, I'm continuing investigating the doc of RA and LB4, any help is appreciated, thank you</p>
| [
{
"answer_id": 74198931,
"author": "François Zaninotto",
"author_id": 1333479,
"author_profile": "https://Stackoverflow.com/users/1333479",
"pm_score": 2,
"selected": false,
"text": "<AutocompleteInput filterToQuery>"
},
{
"answer_id": 74324112,
"author": "Zovitch",
"auth... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11673293/"
] |
74,167,877 | <p>I'm trying to get something I thought should be relatively simple (it works in Oracle and MySQL). The PostgreSQL fiddle for the code below is available <a href="https://dbfiddle.uk/iHNFJrVW" rel="nofollow noreferrer">here</a> - just change the server to check out the others.</p>
<p>Very simple test case:</p>
<pre><code>CREATE TABLE x
(
y CHAR(1)
);
</code></pre>
<p>populate:</p>
<pre><code>INSERT INTO x VALUES ('x');
</code></pre>
<p>and</p>
<pre><code>INSERT INTO x VALUES('y');
</code></pre>
<p>then (works - as one would expect):</p>
<pre><code>SELECT
y AS the_char
FROM
x
ORDER BY the_char;
</code></pre>
<p>Result:</p>
<pre><code>the_char
x
y
</code></pre>
<p>But then, if I try the following:</p>
<pre><code>SELECT
y AS the_char
FROM
x
ORDER BY ASCII(the_char);
</code></pre>
<p>I receive an error:</p>
<pre><code>ERROR: column "the_char" does not exist
LINE 5: ORDER BY ASCII(the_char);
</code></pre>
<p>As mentioned, this works with Oracle and MySQL, but not on PostgreSQL, Firebird and SQL Server.</p>
<p>Can anyone explain why? What is it about a simple function of the column that causes the <code>ORDER BY</code> to fail? This seems to conflict with the manual <a href="https://www.postgresql.org/docs/current/queries-order.html" rel="nofollow noreferrer">here</a> which says:</p>
<blockquote>
<p>The sort expression(s) can be any expression that would be valid in
the query's select list. An example is:</p>
<p>SELECT a, b FROM table1 ORDER BY a + b, c;</p>
</blockquote>
| [
{
"answer_id": 74167940,
"author": "Rajat",
"author_id": 9947159,
"author_profile": "https://Stackoverflow.com/users/9947159",
"pm_score": 2,
"selected": false,
"text": "SELECT\n y AS the_char\nFROM \n x\nORDER BY ASCII(y);\n"
},
{
"answer_id": 74168247,
"author": "The Impa... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/470530/"
] |
74,167,893 | <p>I'm trying to align a div like a gallery through a loop,
is there a way to do this efficiently with bootstrap? they just stay one above another. I tried to make more divs, but they repeat the results of first too. I'm using Laravel 9.0 and Bootstrap 5.0</p>
<p><a href="https://i.stack.imgur.com/h61pZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h61pZ.png" alt="divs above another on running loop to show result" /></a></p>
<pre><code>@extends('master')
<body class="bg-light"></body>
<div class="container-fluid">
<div class="px-lg-5">
<?php
if (!empty($sql)) {
foreach ($sql as $value) {
?>
<div class="row">
<!-- Gallery item -->
<div class="col-xl-3 col-lg-4 col-md-6 mb-4 float-left">
<div class="bg-white rounded shadow-sm"><img src="https://bootstrapious.com/i/snippets/sn-gallery/img-1.jpg" alt="" class="img-fluid card-img-top">
<div class="p-4">
<h5> <a href="#" class="text-dark"><?php echo $value->name; ?></a></h5>
<p class="small text-muted mb-0">Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>
<p class="small text-muted mb-0">Avaliable: <?php echo $value->quantity ?></p>
<div class="d-flex align-items-center justify-content-between rounded-pill bg-light px-3 py-2 mt-4">
<p class="small mb-0"><span class="font-weight-bold">R$<?php echo $value->price ?></span></p>
<div class="badge badge-danger px-3 rounded-pill font-weight-normal">
<span class="text-dark"><?php echo substr($value->category, 0, 7); ?></span>
</div>
<div>
<a href="" class="btn btn-primary my-1">GET</a>
</div>
<div>
<a href="" class="btn btn-primary mx-2">GET</a>
</div>
</div>
</div>
</div>
</div>
<!-- End -->
<?php } ?>
<!-- End -->
<?php } ?>
</div>
<div class="py-5 text-right"><a href="#" class="btn btn-dark px-5 py-3 text-uppercase">Show me more</a></div>
</div>
</div>
</body>
</code></pre>
| [
{
"answer_id": 74168097,
"author": "Onur Uslu",
"author_id": 6106487,
"author_profile": "https://Stackoverflow.com/users/6106487",
"pm_score": 0,
"selected": false,
"text": "<div class=\"row\">"
},
{
"answer_id": 74168119,
"author": "Yunus Kocabay",
"author_id": 2472870,
... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74167893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15890066/"
] |
74,167,903 | <p>I am trying to create a chat like app using tailwind, and I can't seem to get overflow to function properly.</p>
<p>Instead of overflowing, it just stretches the box to fit all the contents.
Please see the code snippet or link below, at line 25 is where the container begins, the top container should span over 5/6 grid rows, and only overflow if the contents exceed the container!</p>
<pre><code><div class="grid h-screen w-screen grid-rows-6 gap-2 bg-neutral-900 p-1">
<div class="row-span-1 bg-neutral-800">
<div class="h-full w-full p-1">
<div class="mt-5">
<div class="flex flex-wrap justify-between px-5 w-full text-white">
<div>Com</div>
<div>3dub</div>
<div>Prof</div>
</div>
</div>
</div>
</div>
<div class="row-span-5 bg-neutral-800 p-1">
<div class="grid grid-cols-6 w-full h-full gap-1 p-1">
<div class="col-span-1 h-full">
<div class="h-full w-full p-1 bg-neutral-700">
<div class="text-white">Nodes</div>
</div>
</div>
<div class="col-span-5 h-full">
<div class="h-full w-full p-1 bg-neutral-700">
<div class="h-full w-full rounded-lg bg-neutral-600 p-4">
<div class="h-full w-full">
<div class="grid grid-rows-6 h-full w-full gap-y-1">
<div class="row-span-5 w-full rounded-lg bg-neutral-500">
<div class="h-full w-full min-h-0 rounded-lg bg-neutral-500 p-4">
<div class="flex flex-col h-full w-full overflow-y-scroll gap-y-2">
<div class="w-1/2 rounded-lg bg-neutral-400 p-4">Chat Msg</div>
<div class="w-1/2 rounded-lg bg-neutral-400 p-4">Chat Msg</div>
<div class="w-1/2 rounded-lg bg-neutral-400 p-4">Chat Msg</div>
<div class="w-1/2 rounded-lg bg-neutral-400 p-4">Chat Msg</div>
<div class="w-1/2 rounded-lg bg-neutral-400 p-4">Chat Msg</div>
<div class="w-1/2 rounded-lg bg-neutral-400 p-4">Chat Msg</div>
<div class="w-1/2 rounded-lg bg-neutral-400 p-4">Chat Msg</div>
<div class="w-1/2 rounded-lg bg-neutral-400 p-4">Chat Msg</div>
<div class="w-1/2 rounded-lg bg-neutral-400 p-4">Chat Msg</div>
</div>
</div>
</div>
<div class="row-span-1 w-full rounded-lg bg-neutral-500">
<div>Message</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</code></pre>
<p><a href="https://play.tailwindcss.com/2G6f2owRqQ" rel="nofollow noreferrer">https://play.tailwindcss.com/2G6f2owRqQ</a></p>
<p>Edit: Included the wrong play.tailwindcss link</p>
| [
{
"answer_id": 74168097,
"author": "Onur Uslu",
"author_id": 6106487,
"author_profile": "https://Stackoverflow.com/users/6106487",
"pm_score": 0,
"selected": false,
"text": "<div class=\"row\">"
},
{
"answer_id": 74168119,
"author": "Yunus Kocabay",
"author_id": 2472870,
... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74167903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8600197/"
] |
74,167,909 | <p>Dear Stackflow Community,</p>
<p>I'm trying to install the R "curl" package from source using a specialized R CMD INSTALL script on Debian 11 x86_64 machine. The source package downloads and build fine but when the linker tries to link libcurl to the source package, the linker can't seem to find my libcurl package and the build fails. I've read others have had similar issues with not being able to local the libcurl package and have followed all prior suggested solutions (including ensuring I have the appropriate libcurl developement files downloaded from Debian distribution as noted in the resultant error message). R itself is installed and runs fine and can install packages from CRAN, but I need a source build for a special project.</p>
<p>Any suggestions? Thanks!</p>
<p>Here is the output of my attempt to build libcurl from source:</p>
<p><a href="https://i.stack.imgur.com/ixW4b.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ixW4b.jpg" alt="Screenshot
" /></a></p>
| [
{
"answer_id": 74168097,
"author": "Onur Uslu",
"author_id": 6106487,
"author_profile": "https://Stackoverflow.com/users/6106487",
"pm_score": 0,
"selected": false,
"text": "<div class=\"row\">"
},
{
"answer_id": 74168119,
"author": "Yunus Kocabay",
"author_id": 2472870,
... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74167909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15179212/"
] |
74,167,933 | <p>I have a file with each line containing a name and some numbers for instance
John, 55 , 77, 89
Sarah, 78, 45, 67
Joe, 40, 99, 63, 89,60
I was able to convert this to a list using split(). But I can’t figure out how to turn it to a dictionary from there. I have something like [‘John’, ‘55,’ ‘77,’… etc. How do I covert this list to a dictionary and am I on the right path?</p>
| [
{
"answer_id": 74167985,
"author": "Peter Wood",
"author_id": 1084416,
"author_profile": "https://Stackoverflow.com/users/1084416",
"pm_score": 0,
"selected": false,
"text": "csv"
},
{
"answer_id": 74167987,
"author": "bn_ln",
"author_id": 10535824,
"author_profile": ... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74167933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20251409/"
] |
74,167,959 | <p>I made a form in order to create events. First, the user has to create a profile and be connected. He has a list of his own addresses. Currently, in the form he can select any addresses, even those created by other users. I would like to allow him to see only addresses he has created in drop selection.</p>
<ul>
<li><p>In <strong>EventType</strong> file, I used <code>EntityType::class</code> for Location entity, knowing that thanks to it addresses are created.</p>
</li>
<li><p>In Entity file for Location, the column 'organizer' is created in order to know who created the address. It's connected with a ManyToOne to User class.</p>
</li>
</ul>
<p>Where do I have to specify that user must select only his own address in the form ?</p>
<p><strong>EventType.php</strong></p>
<pre><code><?php
namespace App\Form;
use App\Entity\Event;
use App\Entity\Language;
use App\Entity\Location;
use App\Entity\Category;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TimeType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
class EventType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('title')
->add('description', TextareaType::class)
->add('spokenlanguage', EntityType::class, [
'class' => Language::class,
'choice_label' => 'name',
'placeholder' => 'Je sélectionne une langue étrangère',
])
->add('category', EntityType::class, [
'class' => Category::class,
'choice_label' => 'title',
'placeholder' => 'Je sélectionne un type de sortie ou d\'activité',
])
->add('start', DateTimeType::class, [
'widget' => 'choice'
])
->add('end', TimeType::class, [
'input' => 'datetime',
'widget' => 'choice',
])
->add('address', EntityType::class, [
'class' => Location::class,
'choice_label' => 'address',
'placeholder' => 'Je sélectionne une adresse',
])
->add('save', SubmitType::class, [
'attr' => ['class' => 'save'],
])
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Event::class,
'translation_domain' => 'forms'
]);
}
}
</code></pre>
<p><strong>Location.php</strong></p>
<pre><code><?php
namespace App\Entity;
use App\Repository\LocationRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: LocationRepository::class)]
class Location
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $name = null;
#[ORM\Column(length: 255)]
private ?string $number = null;
#[ORM\Column(length: 255)]
private ?string $street = null;
#[ORM\Column(length: 255)]
private ?string $zipcode = null;
#[ORM\Column(length: 255)]
private ?string $city = null;
#[ORM\ManyToOne(inversedBy: 'locations')]
private ?BigCity $bigcity = null;
#[ORM\OneToMany(mappedBy: 'address', targetEntity: Event::class)]
private Collection $events;
#[ORM\Column(type: Types::DECIMAL, precision: 10, scale: 7, nullable: true)]
private ?string $lat = null;
#[ORM\Column(type: Types::DECIMAL, precision: 10, scale: 7, nullable: true)]
private ?string $lon = null;
#[ORM\ManyToOne(inversedBy: 'locations')]
private ?User $organizer = null;
public function __construct()
{
$this->events = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getNameAndId(): ?string
{
$nameandid =$this->getName() . ' (Id : ' . $this->getId() . ')';
return $nameandid;
}
public function getNumber(): ?string
{
return $this->number;
}
public function setNumber(string $number): self
{
$this->number = $number;
return $this;
}
public function getStreet(): ?string
{
return $this->street;
}
public function setStreet(string $street): self
{
$this->street = $street;
return $this;
}
public function getZipcode(): ?string
{
return $this->zipcode;
}
public function setZipcode(string $zipcode): self
{
$this->zipcode = $zipcode;
return $this;
}
public function getCity(): ?string
{
return $this->city;
}
public function setCity(string $city): self
{
$this->city = $city;
return $this;
}
public function getAddress(): ?string
{
$address =$this->getName() . ', ' . $this->getNumber() . ' ' . $this->getStreet() . ', ' . $this->getCity();
return $address;
}
public function getBigcity(): ?BigCity
{
return $this->bigcity;
}
public function setBigcity(?BigCity $bigcity): self
{
$this->bigcity = $bigcity;
return $this;
}
/**
* @return Collection<int, Event>
*/
public function getEvents(): Collection
{
return $this->events;
}
public function addEvent(Event $event): self
{
if (!$this->events->contains($event)) {
$this->events->add($event);
$event->setAddress($this);
}
return $this;
}
public function removeEvent(Event $event): self
{
if ($this->events->removeElement($event)) {
// set the owning side to null (unless already changed)
if ($event->getAddress() === $this) {
$event->setAddress(null);
}
}
return $this;
}
public function getLat(): ?string
{
return $this->lat;
}
public function setLat(?string $lat): self
{
$this->lat = $lat;
return $this;
}
public function getLon(): ?string
{
return $this->lon;
}
public function setLon(?string $lon): self
{
$this->lon = $lon;
return $this;
}
public function getOrganizer(): ?User
{
return $this->organizer;
}
public function setOrganizer(?User $organizer): self
{
$this->organizer = $organizer;
return $this;
}
}
</code></pre>
| [
{
"answer_id": 74169908,
"author": "Fatal Error",
"author_id": 20307285,
"author_profile": "https://Stackoverflow.com/users/20307285",
"pm_score": -1,
"selected": true,
"text": "$form = $this->createForm(EventType::class, $event, [\n 'addresses' => $locationRepository->findBy(['organi... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74167959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10592891/"
] |
74,167,976 | <p>I'm trying to find middlepoint on the circle between 2 points, <a href="https://i.stack.imgur.com/sgfEX.png" rel="nofollow noreferrer">pictorial drawing</a></p>
<p>There are given radius, p1, p2 and middle of the circle.</p>
<p>Distance betweeen p1 and p2 is an diameter, and I'm trying to make up python formula that returns point on the circle between those 2 points. I know this is rather silly question but I'm trying to make this for 3 hours now and all I can find on web is distance between those 2 points.</p>
<p>I'm trying to find formula for p3 (like in the picture)</p>
<p>That's what I ended up making so far:</p>
<pre><code>import math
points = [[100, 200], [250, 350]]
midpoint = (int(((points[0][0] + points[1][0]) / 2)), int(((points[0][1] + points[1][1]) / 2)))
radius = int(math.sqrt(((points[1][0] - points[0][0])**2) + ((points[1][1] - points[0][1])**2))) // 2
# This below is wrong
print(int(midpoint[0] - math.sqrt((points[0][1] - midpoint[1]) ** 2)),
int(midpoint[1] - math.sqrt((points[0][0] - midpoint[1]) ** 2)))
</code></pre>
| [
{
"answer_id": 74168093,
"author": "mlokos",
"author_id": 19570235,
"author_profile": "https://Stackoverflow.com/users/19570235",
"pm_score": 0,
"selected": false,
"text": "import math\nimport random\n\npoints = [[100, 200], [250, 350]]\nmidpoint = (int(((points[0][0] + points[1][0]) / 2... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74167976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16221264/"
] |
74,167,988 | <p>One more question that is easy, but for me is hard, because I can't understand JS.
<br>
I need to put 2 variables in the post request, when I am trying to do it, it give me an error: http error 400(bad request) <br><br> Here is the code</p>
<pre><code>document.getElementById("reg-btn").addEventListener("click", myFunction);
function myFunction() {
let l_i;
document.querySelector("#user-input").addEventListener("click", () => {
l_i = document.querySelector("#user_input").value;
});
let p_i;
document.querySelector("#passwordCopy").addEventListener("click", () => {
p_i = document.querySelector("#passwordCopy").value;
});
$.ajax({
url: "http://localhost:8000/api/api-token-auth/",
type: "POST",
headers: {
"X-CSRFToken": Cookies.get('csrftoken') // Extract the csrftoken from the cookie
},
data:{ username: l_i, password: p_i},
dataType:"json"
}).done(function(data) {
Cookies.set(data)
})}
</code></pre>
<p>Here in l_i and p_i, I am storing the username and password that I want to send to an api url, in order to take token that I will store in cookie after.</p>
| [
{
"answer_id": 74168093,
"author": "mlokos",
"author_id": 19570235,
"author_profile": "https://Stackoverflow.com/users/19570235",
"pm_score": 0,
"selected": false,
"text": "import math\nimport random\n\npoints = [[100, 200], [250, 350]]\nmidpoint = (int(((points[0][0] + points[1][0]) / 2... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74167988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19548737/"
] |
74,168,051 | <p>So I have this array:</p>
<pre><code>TEST = np.array([[1,2,3,4,5], [0,0,1,1,1], [0,1,2,4,5]])
</code></pre>
<p>And I want to replace a single random number from the array with 6.</p>
<p>With an exact value I would replace him with:</p>
<pre><code>TEST[0,0] = 6
</code></pre>
<p>But since it's a random number that alternates I cannot do that (or maybe I can and just don't know how)</p>
<p>We also have repeated values, so I cannot just pick a value 0 and replace it for 6 since it would replace all the zeros (I think).</p>
<p>So does anyone know how to replace a random number in this specific array? (as an example).</p>
| [
{
"answer_id": 74168076,
"author": "CryptoFool",
"author_id": 7631480,
"author_profile": "https://Stackoverflow.com/users/7631480",
"pm_score": 2,
"selected": true,
"text": "import numpy as np\nimport random\n\ntest = np.array([[1,2,3,4,5], [0,0,1,1,1], [0,1,2,4,5]])\n\nn1 = random.randr... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20311468/"
] |
74,168,054 | <p>My problem is a very complex and confusing one, I haven't been able to find the answer anywhere.
I basically have 2 dataframes, one is price history of certain products and the other is invoice dataframe that contains transaction data.</p>
<p>Sample Data:</p>
<p>Price History:</p>
<pre><code> product_id updated price
id
1 1 2022-01-01 5.0
2 2 2022-01-01 5.5
3 3 2022-01-01 5.7
4 1 2022-01-15 6.0
5 2 2022-01-15 6.5
6 3 2022-01-15 6.7
7 1 2022-02-01 7.0
8 2 2022-02-01 7.5
9 3 2022-02-01 7.7
</code></pre>
<p>Invoice:</p>
<pre><code> transaction_date product_id quantity
id
1 2022-01-02 1 2
2 2022-01-02 2 3
3 2022-01-02 3 4
4 2022-01-14 1 1
5 2022-01-14 2 4
6 2022-01-14 3 2
7 2022-01-15 1 3
8 2022-01-15 2 6
9 2022-01-15 3 5
10 2022-01-16 1 3
11 2022-01-16 2 2
12 2022-01-16 3 3
13 2022-02-05 1 1
14 2022-02-05 2 4
15 2022-02-05 3 7
16 2022-05-10 1 4
17 2022-05-10 2 2
18 2022-05-10 3 1
</code></pre>
<p>What I am looking to achieve is to add the price column in the Invoice dataframe, based on:</p>
<ol>
<li>The product id</li>
<li>Comparing the Updated and Transaction Date in a way that updated date <= transaction date for that particular record, basically finding the closest date after the price was updated. (The MAX date that is <= transaction date)</li>
</ol>
<p>I managed to do this:</p>
<pre><code>invoice['price'] = invoice['product_id'].map(price_history.set_index('id')['price'])
</code></pre>
<p>but need to incorporate the date condition now.</p>
<p>Expected result for sample data:</p>
<p><a href="https://i.stack.imgur.com/SOwgO.png" rel="nofollow noreferrer">Expected Result</a></p>
<p>Any guidance in the correct direction is appreciated, thanks</p>
| [
{
"answer_id": 74168302,
"author": "Code Different",
"author_id": 2538939,
"author_profile": "https://Stackoverflow.com/users/2538939",
"pm_score": 1,
"selected": false,
"text": "merge_asof"
},
{
"answer_id": 74168401,
"author": "Jason Baker",
"author_id": 3249641,
"a... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18705823/"
] |
74,168,058 | <p>I'm trying to get my divs to change color on mousedown using the value of my type="color". Currently, the divs change color successfully if I specify the value straight up like <code>element.style.background = 'black'</code> but I would like to give the user the option to choose the color via <code>type='color'</code>. Would someone be able to identify what is causing my <code>element.style.background</code> from using the value from <code>type='color'</code>?</p>
<p>html:</p>
<pre><code><div id="selectColor">
Select a Color <input onchange="selectColor()" type='color'>
</div>
</code></pre>
<p>javascript:</p>
<pre><code>function colorPixel() {
document.querySelectorAll('.contentDivs').forEach(function(element) {
element.addEventListener('mousedown', () => {
element.style.background = selectColor();
})
})
document.querySelectorAll('.horizontalDivs').forEach(function(element) {
element.addEventListener('mousedown', () => {
element.style.background = selectColor();
})
})
}
function selectColor() {
let colorSelected = document.getElementById('selectColor').value;
element.style.background = colorSelected;
}
</code></pre>
<p>I can provide the rest of the code if that is helpful. Thanks in advance!</p>
| [
{
"answer_id": 74168061,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 1,
"selected": false,
"text": "<div>\n Select a Color <input onchange=\"selectColor()\" id=\"selectColor\" type='color'>\n</div>\n"
},
{
"a... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16916067/"
] |
74,168,070 | <p>I’m struggling with JavaScript’s <a href="https://tc39.es/proposal-temporal/docs/" rel="nofollow noreferrer">proposed new Temporal API</a>. What I am trying to do should be straight-forward, yet I fail to find a convincing solution. I must be missing something.</p>
<p>The task is as follows: <strong>instantiate an object representation of an UTC datetime from variables for year, month, day, hour and minute</strong>.</p>
<p>My thinking is as follows:</p>
<ul>
<li>we are talking UTC so I need a <code>Temporal.Instant</code>;</li>
<li><code>new Temporal.Instant()</code> requires the timestamp in nanoseconds so that doesn’t work;</li>
<li><code>Temporal.Instant.from()</code> requires a ISO datetime string, which would require me to generate a properly formatted piece of text from the five variables I have — this is possible but a bit of a hack and kinda defeating the purpose of using a datetime library;</li>
<li><code>Temporal.PlainDateTime.from()</code> has the right design, as it accepts an object like <code>{ year, month, day, hour, minute }</code>;</li>
<li>so then all we need to do is creating an <code>Instant</code> from this <code>PlainDateTime</code>. This does not seem to be possible though? Other than through — once again — a datetime string or a timestamp in ns…?</li>
</ul>
<p>This is silly! The use case here is super basic, and yet it’s not obvious (to me) at all how to address it.</p>
<p>I was expecting to be able to simply do something like: <code> Temporal.Instant.from({ year, month, day, hour, minute });</code></p>
<p>Now the best I can come up with is: <code>Temporal.Instant.from(year + '-' + String(month).padStart(2, '0') + '-' + String(day).padStart(2, '0') + 'T' + String(hour).padStart(2, '0') + ':' + String(minute).padStart(2, '0') + 'Z'); // </code></p>
<p>Please tell me I’m bigtime overlooking something.</p>
| [
{
"answer_id": 74172168,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 3,
"selected": true,
"text": "PlainDateTime"
},
{
"answer_id": 74179443,
"author": "RobG",
"author_id": 257182,
"author_profile":... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146438/"
] |
74,168,118 | <p>There is this Project i am dealing with, you can check it's Git Repository here :
<a href="https://github.com/google-ar/arcore-android-sdk/tree/master/samples/augmented_faces_java" rel="nofollow noreferrer">Arcore repo</a></p>
<ul>
<li>The Project builds successfully and runs on emulator or physical device while using <strong>android Studio</strong> .</li>
</ul>
<p><em><strong>Problem:</strong></em> I cloned this project and opened it with <em><strong>vscode</strong></em>, and run <code>./gradlew clean build</code>; this goes as expected!!</p>
<ul>
<li>But it seems to always get stack at :</li>
</ul>
<blockquote>
<p>./gradlew run</p>
</blockquote>
<p>with "error" <em><strong>run task is not found in the root project</strong></em></p>
| [
{
"answer_id": 74168173,
"author": "Pexers",
"author_id": 9213148,
"author_profile": "https://Stackoverflow.com/users/9213148",
"pm_score": 1,
"selected": false,
"text": "build.gradle"
},
{
"answer_id": 74274056,
"author": "Archiee",
"author_id": 11756439,
"author_pro... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11756439/"
] |
74,168,120 | <p>I'm trying to get specific values from an array object returned by my node.js api</p>
<p>Here's the array of object returned by my node.js api</p>
<pre><code>[
{
"name": "device1",
"serial": "WMD105222022",
"status": "online"
},
{
"name": "device2q",
"serial": "sdfsdf",
"status": "online"
},
{
"name": "ducs",
"serial": "WMD105222022",
"status": "online"
}
]
</code></pre>
<p>Here's my react.js code</p>
<pre><code>import React, {useState, useEffect} from "react";
import './Module.css';
import {SDH} from '../../components';
import {temp, water, humidity, nutrient} from '../../assets';
import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal';
import Form from 'react-bootstrap/Form';
import {Link} from 'react-router-dom';
import Axios from "axios";
const Module = () => {
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
const email = sessionStorage.getItem("email");
const [device, setDevice] = useState({});
Axios.defaults.withCredentials = true;
useEffect(() => {
Axios.get("http://localhost:3020/getdevice", {
params: {
email: email
}
})
.then((response) => {
setDevice(response.data);
})
// .then((response) => {},
// (err) => {
// alert("No Data To Show");
// }
// )
.catch((err) => {
return false;
});
},[]);
const DisplayData = () => {
return (
<div>
<td>{device.name}</td>
<td>{device.serial}</td>
<td>{device.status}</td>
</div>
);
};
return (
<div className="MainBodyM">
<SDH/>
<h3 className="deviceStatus"></h3>
{/* <Button onClick={getDevices} variant="primary" type="submit">Refresh List</Button> */}
<div className="tempHeader">
<table>
<tr>
<td>Name</td>
<td>Serial Number</td>
<td>Status</td>
</tr>
<tr>
{DisplayData}
</tr>
</table>
</div>
<Link to="/registerdevice">
<Button>Add Control Module</Button>
</Link>
</div>
);
};
export default Module;
</code></pre>
<p>I needed to get the <code>name, serial, and status</code> to be displayed in a table. up until now i'm still getting nowhere, please help, i'm only using <code>{JSON.stringify(device, null, 3)}</code> to display the returned array of object that's why i know i'm getting an array of object. I'm open to suggestions and correction. Thank you.</p>
<p>I need the output to be like this, regardless how many devices/data i add in array of object.</p>
<pre><code>Device Serial Status
Device1 121 online
device2 234135 offline
balcony ash3 online
bathroom dsgfkahaskj23 online
so on... tj2l5 offline
</code></pre>
| [
{
"answer_id": 74168193,
"author": "Enfield li",
"author_id": 16648127,
"author_profile": "https://Stackoverflow.com/users/16648127",
"pm_score": 0,
"selected": false,
"text": "\"Device\", \"Serial\", \"Status\""
},
{
"answer_id": 74168969,
"author": "Daniel",
"author_id"... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12093475/"
] |
74,168,162 | <p>I have two dataframes that I'd like to conditionally merge.</p>
<p>df1:</p>
<pre><code> Location `Sub Location` Date n
<chr> <chr> <chr> <int>
1 AREA 1 Bore Drain 2014-04-21 15
2 AREA 1 Bore Drain 2014-04-23 2
3 AREA 1 Bore Drain 2014-04-24 6
4 AREA 1 Bore Drain 2015-04-04 6
5 AREA 1 Bore Drain 2015-04-08 8
6 AREA 1 Bore Drain 2015-04-09 9
7 AREA 1 Bore Drain 2016-03-25 31
8 AREA 1 Large Dam 2016-03-26 7
9 AREA 1 Bore Drain 2016-04-01 2
10 AREA 1 Bore Drain 2016-04-02 6
</code></pre>
<p>and df2:</p>
<pre><code> Location `Sub Location` StartDate EndDate Totals
<chr> <chr> <chr> <chr> <dbl>
1 AREA 1 Homestead 2013-03-29 2013-03-30 0
2 AREA 1 Bore Drain 2014-04-21 2014-04-21 0
3 AREA 1 Homestead 2014-04-17 2014-04-18 0
4 AREA 1 Cottage 2014-04-21 2014-04-22 0
5 AREA 1 Bore Drain 2014-04-23 2014-04-24 0
6 AREA 1 Bore Drain 2015-04-03 2015-04-04 0
7 AREA 1 Homestead 2015-04-03 2015-04-04 0
8 AREA 1 Bore Drain 2015-04-08 2015-04-09 0
9 AREA 1 Cottage 2015-04-08 2015-04-09 0
10 AREA 1 Homestead 2016-03-25 2016-03-25 0
</code></pre>
<p>What I'd like to do is check for each entry in df1, if <code>Date</code> matches either <code>StartDate</code> OR <code>EndDate</code>, AND the <code>location</code> and <code>Sub Location</code> are the same. If this is the case, I'd like <code>n</code> in df1 to be added to <code>Totals</code> in df2</p>
<p>I've tried using <code>ifelse()</code> or going through every entry in a for loop, but I haven't been able to get it working. Any suggestions are appreciated :)</p>
| [
{
"answer_id": 74168346,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 0,
"selected": false,
"text": "df2$Totals <- rowSums(t(apply(df2, 1, function(x) \n ifelse(x[\"Location\"] == df1$Location & ... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20311615/"
] |
74,168,182 | <p>First time asking a question so please forgive me. Dealing with two different dataframes, one containing state level data and another containing individual level data (within states)</p>
<p>Surveyframe:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>Location</th>
<th>Year</th>
<th>Age</th>
<th>Smokes</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>NY</td>
<td>2000</td>
<td>15</td>
<td>False</td>
</tr>
<tr>
<td>2</td>
<td>NY</td>
<td>2000</td>
<td>17</td>
<td>True</td>
</tr>
<tr>
<td>3</td>
<td>NY</td>
<td>2001</td>
<td>13</td>
<td>True</td>
</tr>
<tr>
<td>4</td>
<td>NY</td>
<td>2001</td>
<td>16</td>
<td>False</td>
</tr>
<tr>
<td>5</td>
<td>SD</td>
<td>2000</td>
<td>15</td>
<td>False</td>
</tr>
<tr>
<td>6</td>
<td>SD</td>
<td>2000</td>
<td>17</td>
<td>True</td>
</tr>
<tr>
<td>7</td>
<td>SD</td>
<td>2001</td>
<td>13</td>
<td>True</td>
</tr>
<tr>
<td>8</td>
<td>SD</td>
<td>2001</td>
<td>16</td>
<td>False</td>
</tr>
</tbody>
</table>
</div>
<p>etc...</p>
<p>taxframe:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>Location</th>
<th>Year</th>
<th>SubMeasure</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>NY</td>
<td>2000</td>
<td>Total Tax/Pack</td>
<td>0.50</td>
</tr>
<tr>
<td>2</td>
<td>NY</td>
<td>2000</td>
<td>Avg Cost/Pack</td>
<td>5.50</td>
</tr>
<tr>
<td>3</td>
<td>NY</td>
<td>2001</td>
<td>Total Tax/Pack</td>
<td>0.75</td>
</tr>
<tr>
<td>4</td>
<td>NY</td>
<td>2001</td>
<td>Avg Cost/Pack</td>
<td>5.75</td>
</tr>
<tr>
<td>5</td>
<td>SD</td>
<td>2000</td>
<td>Total Tax/Pack</td>
<td>0.10</td>
</tr>
<tr>
<td>6</td>
<td>SD</td>
<td>2000</td>
<td>Avg Cost/Pack</td>
<td>3.25</td>
</tr>
<tr>
<td>7</td>
<td>SD</td>
<td>2001</td>
<td>Total Tax/Pack</td>
<td>0.10</td>
</tr>
<tr>
<td>8</td>
<td>SD</td>
<td>2001</td>
<td>Avg Cost/Pack</td>
<td>3.25</td>
</tr>
</tbody>
</table>
</div>
<p>etc...</p>
<p>Desire:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>Location</th>
<th>Year</th>
<th>Age</th>
<th>Smokes</th>
<th>Total Tax/Pack</th>
<th>Avg Cost/Pack</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>NY</td>
<td>2000</td>
<td>15</td>
<td>False</td>
<td>0.50</td>
<td>5.50</td>
</tr>
<tr>
<td>2</td>
<td>NY</td>
<td>2000</td>
<td>17</td>
<td>True</td>
<td>0.50</td>
<td>5.50</td>
</tr>
<tr>
<td>3</td>
<td>NY</td>
<td>2001</td>
<td>13</td>
<td>True</td>
<td>0.75</td>
<td>5.75</td>
</tr>
<tr>
<td>4</td>
<td>NY</td>
<td>2001</td>
<td>16</td>
<td>False</td>
<td>0.75</td>
<td>5.75</td>
</tr>
<tr>
<td>5</td>
<td>SD</td>
<td>2000</td>
<td>15</td>
<td>False</td>
<td>0.10</td>
<td>3.25</td>
</tr>
<tr>
<td>6</td>
<td>SD</td>
<td>2000</td>
<td>17</td>
<td>True</td>
<td>0.10</td>
<td>3.25</td>
</tr>
<tr>
<td>7</td>
<td>SD</td>
<td>2001</td>
<td>13</td>
<td>True</td>
<td>0.10</td>
<td>3.25</td>
</tr>
<tr>
<td>8</td>
<td>SD</td>
<td>2001</td>
<td>16</td>
<td>False</td>
<td>0.10</td>
<td>3.25</td>
</tr>
</tbody>
</table>
</div>
<p>Using data for around 10 states with multiple sub-measures and over 200k individuals.</p>
<p>My first idea was to loop through each column appending to the surveyrfame, filling in value from the taxframe where the location and year match the location and year of the current indes, but that seems inefficient. Is there a better way to get this done with pandas?</p>
<p>Thanks</p>
| [
{
"answer_id": 74168346,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 0,
"selected": false,
"text": "df2$Totals <- rowSums(t(apply(df2, 1, function(x) \n ifelse(x[\"Location\"] == df1$Location & ... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20304820/"
] |
74,168,184 | <p>I want to calculate the square root of a numpy array of negative numbers.</p>
<p>I tried with <code>np.sqrt()</code> but it gives error beacuse the domain.</p>
<p>Then, I found that for complex numbers you can use <code>cmath.sqrt(x)</code> but it also gives me an error.</p>
<p>Here's my code</p>
<pre><code>import numpy as np
import cmath
from cmath import sqrt
x = np.arange(-10, 10, 0.01)
E = 1
p1 = cmath.sqrt(E - x**2)
</code></pre>
<p>And got this error</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\os.py", line 49, in <module>
p1 = cmath.sqrt(E - x**2)
TypeError: only length-1 arrays can be converted to Python scalars
</code></pre>
<p>Later I tried to use a for loop and it's not possible either.
Here's the code:</p>
<pre><code>import numpy as np
import cmath
from cmath import sqrt
x = np.arange(-10, 10, 0.01)
E = 1
for i in range(0, len(x)):
p1 = cmath.sqrt(E - x(i)**2)
</code></pre>
<p>and the message error</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\os.py", line 48, in <module>
p1 = cmath.sqrt(E - x(i)**2)
TypeError: 'numpy.ndarray' object is not callable
</code></pre>
<p>I don't know what am I dpoing wrong, can anyone help me?, please.
I need to calculate the square root of an numpy array of negative numbers, does anyone know how to do this?</p>
| [
{
"answer_id": 74168346,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 0,
"selected": false,
"text": "df2$Totals <- rowSums(t(apply(df2, 1, function(x) \n ifelse(x[\"Location\"] == df1$Location & ... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20186251/"
] |
74,168,185 | <p>I have a table with integer ID as primary key--auto increment.
Because of frequent delete/insert, the ID values are like <code>1 1000 2340 5420 ...</code>.</p>
<p>I want it always to be <code>1 2 3 4 ...</code>.</p>
<p>So is there a way--while inserting a new row--to insert a first missing ID value automatically--instead of constantly increment values?</p>
<p>Example: If current values are <code>1 3 4 5</code>, the next insert should be <code>1 2 3 4 5</code> and not <code>1 3 4 5 6</code>.</p>
| [
{
"answer_id": 74168319,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": true,
"text": "INT"
},
{
"answer_id": 74168337,
"author": "Tịnh Trần Thanh",
"author_id": 10725858,
"author_prof... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10983537/"
] |
74,168,192 | <p>I'm looking for a faster algorithm that solves the following problem:</p>
<ul>
<li>Input: Two arrays of integers <code>A</code> and <code>B</code> in the range <code>[0, N)</code>, both of fixed length <code>d</code>, assumed to be given in sorted order with no repeated elements.</li>
<li>Output: Whether the largest possible intersection (i.e. number of elements in common) between <code>A</code> and a cyclic shift of <code>B</code> is greater than some specified threshold <code>t</code>. By a cyclic shift of <code>B</code>, I mean the array <code>[(b + s) % N for b in B]</code> for some integer <code>s</code>.</li>
</ul>
<p>If it matters, I'm implementing this in Rust (though I'm more interested in general algorithmic improvements than language-specific optimizations), and in practice, <code>t</code> will be less than 10, <code>d</code> will typically be in the range of 15 to 150, and <code>N</code> will be roughly on the order of <code>2*d*d</code>.</p>
<p>My current algorithm is essentially as follows (note, <code>d</code> and <code>N</code> are constants defined at compile-time):</p>
<pre class="lang-rust prettyprint-override"><code>fn max_shifted_overlap_geq(A: [u32; d], B: [u32; d], threshold: u32) -> bool {
for i in 0..d {
for j in 0..d {
let s = N + A[i] - B[j];
let mut B_s = [0; d];
for k in 0..d {
B_s[k] = (B[k] + s) % N;
}
B_s.sort();
// Actually, I do an insertion-sort in place as I construct B_s,
// but I'm writing it this way here for simplicity.
if sorted_intersection_count(&A, &B_s) >= threshold {
return true;
}
}
}
false
}
</code></pre>
<p>So I'm only choosing shifts from the possible values of <code>A[i] - B[j]</code> (since a shift not of this form gives zero intersection), and then I just construct the cyclic shift of <code>B</code> and count the number of elements in common in a fairly naive way.</p>
<p>Is there a more efficient algorithm for this, keeping in mind the fairly small size of the arrays? In particular, is there a better way of finding shifts that are more likely to yield large overlaps?</p>
<p>Edit: To provide additional context (as requested below), this arises in the study of QC-MDPC codes: The arrays represent the supports of binary vectors that generate the circulant blocks of the parity-check matrix, and this condition on the intersection with cyclic shifts defines a class of "weak keys" with some cryptographic implications. (I initially didn't mention this because the problem seems interesting in isolation and doesn't require any knowledge of coding theory or cryptography.)</p>
<p>Edit 2: Fixed some typos in the code and switched to a better method of counting intersections of sorted lists. (Weirdly, I actually had used that improved algorithm in an earlier version and the code ran slower, but that might've been due to an implementation bug or now-fixed problems elsewhere in the code.)</p>
<p>Edit 3: For future reference of anyone who runs into a similar problem, here's my current implementation, using the key idea from virchau13's answer below plus some small additional optimizations. This seems quite efficient in practice. (I've renamed some variables for clarity—<code>arr1</code> and <code>arr2</code> for the input arrays, and <code>LEN</code> instead of <code>d</code> for the array length.)</p>
<pre class="lang-rust prettyprint-override"><code>fn relative_shifts(arr1: &[u32; LEN], arr2: &[u32; LEN]) -> [[u32; LEN]; LEN] {
let n = N as u32;
let mut shifts = [[0; LEN]; LEN];
for i in 0..LEN {
for j in 0..LEN {
shifts[i][j] = if arr1[i] < arr2[j] {
n + arr1[i] - arr2[j]
} else {
arr1[i] - arr2[j]
}; // this equals (arr1[i] - arr2[j]) % n
}
}
shifts
}
fn max_shifted_overlap_geq(arr1: &[u32; LEN], arr2: &[u32; LEN], threshold: u8) -> bool {
let shifts = relative_shifts(arr1, arr2);
let mut shift_counts = [0; N];
for i in 0..LEN {
for j in 0..LEN {
let count = &mut shift_counts[shifts[i][j] as usize];
*count += 1;
if *count >= threshold {
return true;
}
}
}
false
}
</code></pre>
<p>A couple implementation notes:</p>
<ol>
<li>This could easily be modified to produce the largest possible intersection as a value (by taking a maximum instead of short-circuiting when the threshold is exceeded) or a set of index pairs (by also appending the index pairs <code>(i, j)</code> to a list associated to each shift <code>s</code> as it's computed).</li>
<li>We do not need to assume the arrays are sorted for this to work. For that matter, I don't think we need to assume the arrays are of the same length, either, though I haven't tested this for arrays of different lengths.</li>
</ol>
| [
{
"answer_id": 74168319,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": true,
"text": "INT"
},
{
"answer_id": 74168337,
"author": "Tịnh Trần Thanh",
"author_id": 10725858,
"author_prof... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20285682/"
] |
74,168,206 | <p>I currently created this condition that only works for the listed <strong>userName</strong> from the <strong>data.uniqueId</strong>. Without the condition, it works to all names from the <strong>data.uniqueId</strong>. My purpose is so I could trigger the <strong>addContent</strong> to some names of my choice only, those that I will put the list.</p>
<pre><code>let userName = data.uniqueId;
if(userName == "name1"){
addContent(
`<img src="${userAvatar}" style="width:25px;height:25px;border-radius: 50%;"/>&nbsp;<span class="hostMessage">Host</span>
<span style="font-weight: bold;">${userName}</span>: ${message}`
);
}
</code></pre>
<p>The code I have now is working but only for <strong>name1</strong>, I don't know how to do the code if I want to have more than 1 <strong>userName</strong> in the list.</p>
<p>Could anyone help me with this? I would appreciate it if you could come up with a way that's easier for me to add more names to the list in the future, maybe a different .js file just for the name list and then call to a different .js file where I currently have the code above.</p>
<p>Otherwise, any method that works should be fine enough. Thank you in advance!</p>
| [
{
"answer_id": 74168319,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": true,
"text": "INT"
},
{
"answer_id": 74168337,
"author": "Tịnh Trần Thanh",
"author_id": 10725858,
"author_prof... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7676733/"
] |
74,168,244 | <p>In an SQL query, I have a column, in which I want to convert numeric value type to text, that way I can replace only one numeric value which is -1 for the word Unknown, and leave the rest of the other values as it is.</p>
<p>How can I achieve this?</p>
<p>Thanks.</p>
| [
{
"answer_id": 74168306,
"author": "DannySlor",
"author_id": 19174570,
"author_profile": "https://Stackoverflow.com/users/19174570",
"pm_score": 0,
"selected": false,
"text": "select col1 \n ,case when col1 = -1 then 'unknown' else cast(col1 as varchar(20)) end as new_col1\nfrom ... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18480436/"
] |
74,168,266 | <p>How to fix (stdC++20 mode VS2022)</p>
<pre><code>#include <format>
#include <string>
auto dump(int *p)
{
std::string resultstring = std::format(" p points to address {:p}", p);
</code></pre>
<p>resulting in:</p>
<pre><code>error C3615: consteval function 'std::_Compile_time_parse_format_specs' cannot result in a constant expression
</code></pre>
| [
{
"answer_id": 74168267,
"author": "GeePokey",
"author_id": 333046,
"author_profile": "https://Stackoverflow.com/users/333046",
"pm_score": 3,
"selected": true,
"text": "std::string resultstring = std::format(\"{:p}\", (void *)p);\n"
},
{
"answer_id": 74183892,
"author": "vit... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/333046/"
] |
74,168,281 | <p>Ok so I have a group of numbers say for example (12, 28,14). I also have a column of numbers in Column A up to the 150th row. Each cell in column A can take numbers between 0 and 36. I would like a formular that would highlight to me anytime this pattern (12,28 14) occurs in the list of numbers. The number group could be arranged in any order say for eg 28,12,14 or 28,14,12 etc. i have tried but I would like this to be more dynamic. Thanks for any assistance.</p>
| [
{
"answer_id": 74168267,
"author": "GeePokey",
"author_id": 333046,
"author_profile": "https://Stackoverflow.com/users/333046",
"pm_score": 3,
"selected": true,
"text": "std::string resultstring = std::format(\"{:p}\", (void *)p);\n"
},
{
"answer_id": 74183892,
"author": "vit... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20311764/"
] |
74,168,308 | <p>I just finished cleaning my data and I noticed that there are columns that have duplicate values in the rows that are separated by a space. I was wondering what is the best way to remove the space after the first value and then all values after it.</p>
<p>There are some columns that have multiple duplicates such as 42.35 42.25 23.12 in the same cell.</p>
<p>The data is large with 1500 columns and around 4000 rows so there is no way I could manually fix the issue.</p>
<p>Thanks!</p>
<p>Here is an example</p>
<pre><code> PAG
0 54.36
1 50.3
2 46.81
3 47.71
4 42.35 42.35 <------ This is one of the many rows (cell) that have this duplicate.
5 43.91
6 43.54
</code></pre>
<p>Here is what the data looks like and the dtypes
Dtype</p>
<pre><code>MthCalDt int64
A float64
AA float64
AAL float64
AAON float64
...
ZD float64
ZEN float64
ZION float64
ZTS float64
ZWS float64
Length: 1583, dtype: object
</code></pre>
<pre><code>cleaned_data = pd.read_csv("Wrds_Data\wrds_data_clean.csv")
cleaned_data.head()
MthCalDt A AA AAL AAON AAP AAPL AAT AAWW AB ... YUMC YY Z ZBH ZBRA ZD ZEN ZION ZTS ZWS
0 20170131 48.97 36.45 44.25 33.95 164.24 121.35 42.93 52.75 23.35 ... 27.48 41.08 35.38 118.33 83.67 83.81 23.93 42.19 54.94 22.09
1 20170228 51.30 34.59 46.36 33.65 156.61 136.99 44.00 56.85 23.70 ... 26.59 44.29 33.94 117.08 90.71 81.42 27.23 44.90 53.31 22.17
2 20170331 52.87 34.40 42.30 35.35 148.26 143.66 41.84 55.45 22.85 ... 27.20 46.11 33.67 122.11 91.25 83.91 28.04 42.00 53.37 23.08
3 20170428 55.05 33.73 42.62 36.65 142.14 143.65 42.83 58.00 22.90 ... 34.12 48.97 39.00 119.65 94.27 90.24 28.75 40.03 56.11 24.40
4 20170531 60.34 32.94 48.41 36.18 133.63 152.76 39.05 48.70 22.55 ... 38.41 58.34 43.52 119.21 104.34 84.62 25.98 40.07 62.28 22.80
</code></pre>
<p>What I tried So Far Comes up with the error could not convert a string into float. The error is caused by the duplicate with a space in one of the rows (Cell)</p>
<pre><code>cleaned_data = pd.read_csv("Wrds_Data\wrds_data_clean.csv")
cleaned_data.astype(float)
cleaned_data.applymap(lambda x: x.split(" ")[0])
error:
could not convert string to float: '126.49 126.49' <--- This is referencing a duplicate cell that is considered a string since there is a space.
</code></pre>
<p>Here is the newer code with regex that tries to replace cells with spaces but there are still cells with duplicates.</p>
<pre><code>cleaned_data = pd.read_csv("Wrds_Data\wrds_data_clean.csv")
columns = cleaned_data.columns.copy().drop('MthCalDt')
cleaned_data[columns] = cleaned_data[columns].replace(r"^(\d+\.\d+) .*", r"\1", regex=True).astype(float)
cleaned_data
Error:
Cell In [114], line 3
1 cleaned_data = pd.read_csv("Wrds_Data\wrds_data_clean.csv")
2 columns = cleaned_data.columns.copy().drop('MthCalDt')
----> 3 cleaned_data[columns] = cleaned_data[columns].replace(r"^(\d+\.\d+) .*", r"\1", regex=True).astype(float)
4 cleaned_data
169 # Explicit copy, or required since NumPy can't view from / to object.
--> 170 return arr.astype(dtype, copy=True)
172 return arr.astype(dtype, copy=copy)
ValueError: could not convert string to float: '60 55.66'
</code></pre>
<p><strong>Here is the Step By Step Guide for what I did when cleaning the data to show if I made a mistake when cleaning the data.</strong></p>
<p>Step 1. Showing what the original Data looked like.</p>
<pre><code>df1 = pd.read_csv("Wrds_Data\wrds_data_raw.csv")
output:
Ticker MthCalDt MthPrc
0 JJSF 20170131 127.57
1 JJSF 20170228 133.8
2 JJSF 20170331 135.56
3 JJSF 20170428 134.58
4 JJSF 20170531 130.1
</code></pre>
<p>Step 2: Making the Tickers into columns and MthPrc as the Values indexed in MthCalDt</p>
<pre><code>df1 = pd.read_csv("Wrds_Data\wrds_data_raw.csv")
df2 = df1.pivot_table(index='MthCalDt', columns="Ticker", values="MthPrc", aggfunc=lambda x: ' '.join(x.dropna()))
df2.to_csv("Wrds_Data\wrds_data_clean.csv")
Output:
</code></pre>
<p><a href="https://i.stack.imgur.com/nkZ06.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nkZ06.png" alt="Data Output" /></a></p>
| [
{
"answer_id": 74168409,
"author": "Lowin Li",
"author_id": 19560513,
"author_profile": "https://Stackoverflow.com/users/19560513",
"pm_score": 2,
"selected": false,
"text": "applymap"
},
{
"answer_id": 74168424,
"author": "tdelaney",
"author_id": 642070,
"author_prof... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15534784/"
] |
74,168,347 | <p>I'm a newbie in java. I'm trying to find minimum maximum element in array and then delete the minimum and maximum. This is the code I wrote, it's only working for maximum not for minimum.</p>
<pre class="lang-java prettyprint-override"><code>public class delminmax {
public static void main(String[] args) {
int [] nums = {10,50,20,90,22};
int max = 0;
int min = 0;
for (int i=0; i<nums.length; i++) {
if (nums[i]> max)
max = nums[i];
}
System.out.println("The max number is "+ max);
for (int i=0;i<nums.length;i++)
if (max==nums[i]) {
for (int j=i; j<nums.length-1;j++)
nums[j]= nums[j+1];
}
for (int i=0;i<nums.length-1;i++)
System.out.print(nums[i]+ " " + "\n");
for (int i=0; i<nums.length; i++) {
if (nums[i]< min)
min = nums[i];
}
System.out.println("The min number is "+ min);
for (int i=0;i<nums.length;i++)
if (min==nums[i]) {
for (int j=i; j<nums.length-1;j++)
nums[j]= nums[j+1];
}
for (int i=0;i<nums.length-1;i++)
System.out.println(nums[i] + " ");
}
}
</code></pre>
| [
{
"answer_id": 74168409,
"author": "Lowin Li",
"author_id": 19560513,
"author_profile": "https://Stackoverflow.com/users/19560513",
"pm_score": 2,
"selected": false,
"text": "applymap"
},
{
"answer_id": 74168424,
"author": "tdelaney",
"author_id": 642070,
"author_prof... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19146556/"
] |
74,168,364 | <p>I have this entry</p>
<pre><code>id value reps
1 333 1
1 332 4
1 335 1
4 555 3
4 225 1
444 2 5
</code></pre>
<p>I want this, organizing the values by the column reps from less to more</p>
<pre><code>id col1 col2 col3 col4
1 333 335 332 nan
4 225 555 nan nan
444 2 nan nan nan
</code></pre>
<p>I have tried to use pivot table and got this</p>
<pre><code>dataframe = dataframe.pivot_table(index='id', columns='reps', values='value')
dataframe = dataframe.rename_axis(columns=None).reset_index()
id 1 3 4 5
1 334 nan 332 nan
4 225.5 555.5 nan nan
444 nan nan nan 2
</code></pre>
| [
{
"answer_id": 74168523,
"author": "rurgel",
"author_id": 20296262,
"author_profile": "https://Stackoverflow.com/users/20296262",
"pm_score": 2,
"selected": false,
"text": "reps"
},
{
"answer_id": 74169005,
"author": "Azhar Khan",
"author_id": 2847330,
"author_profile... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19787051/"
] |
74,168,387 | <p>my code in python is supposed to sum the two variables and return a value, but it keeps returning the two numbers together:</p>
<pre><code>A = input("insert a value: ")
B = input("insert another value: ")
if A >= B:
R == A + B
print ("this is the result", R)
else:
R == A - B
print ("this is the result", R)
input 1: A=1 and B=1
output 1: R=11
input 2: A=2 and B=1
output 2: R=21
</code></pre>
| [
{
"answer_id": 74168416,
"author": "Darryl Johnson",
"author_id": 6477796,
"author_profile": "https://Stackoverflow.com/users/6477796",
"pm_score": -1,
"selected": false,
"text": "A_INPUT = input(\"insert a value: \")\nB_INPUT = input(\"insert another value: \")\n\nA = int(A_INPUT)\nB = ... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20293469/"
] |
74,168,389 | <p>I'm looking to somehow figure out a way to insert a geographic graph of British Columbia which is a part of Canada in my data analysis.</p>
<p>I have made this image here explaining what tree is being planted the most in Vancouver<br />
<img src="https://i.stack.imgur.com/2FwdP.png" alt="I have made this image here explaining what tree is being planted the most in Vancouver" /></p>
<p>Now I want to make a geograph kind of like this <a href="https://altair-viz.github.io/gallery/airports_count.html" rel="nofollow noreferrer">https://altair-viz.github.io/gallery/airports_count.html</a></p>
<p>to answer: how the density/distribution of species planted different in different neighbourhoods look like.</p>
<p>This is what I'm having trouble with.</p>
<p>Thus</p>
<pre><code>from vega_datasets import data
world_map = alt.topo_feature(data.world_110m.url, 'countries')
alt.Chart(world_map).mark_geoshape().project()
</code></pre>
<p>and it's giving me a world map! Great! I tried zooming into just British Columbia but it's not really working out.</p>
<p>Can anyone give me any direction on where to go and how I should go about answering my question? I really wanted to use geoshape</p>
<p>I also found this if it's helpful</p>
<p><a href="https://global.mapit.mysociety.org/area/960958.html" rel="nofollow noreferrer">https://global.mapit.mysociety.org/area/960958.html</a></p>
<p>Thank you and I appreciate everyones advice!</p>
| [
{
"answer_id": 74173205,
"author": "joelostblom",
"author_id": 2166823,
"author_profile": "https://Stackoverflow.com/users/2166823",
"pm_score": 1,
"selected": false,
"text": "world_110m"
},
{
"answer_id": 74175582,
"author": "amance",
"author_id": 17142551,
"author_p... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19279798/"
] |
74,168,449 | <p>I have a df containing minute bars of different symbols like so:</p>
<pre><code> timestamp open high low close volume trade_count vwap symbol
0 2021-10-13 08:00:00+00:00 140.20 140.40 140.000 140.40 6084 65 140.205417 AAPL
1 2021-10-13 08:01:00+00:00 140.35 140.40 140.200 140.40 3052 58 140.308182 AAPL
2 2021-10-13 08:02:00+00:00 140.35 140.35 140.350 140.35 632 30 140.320934 AAPL
3 2021-10-13 08:03:00+00:00 140.28 140.30 140.200 140.20 2867 36 140.279473 AAPL
4 2021-10-13 08:04:00+00:00 140.20 140.20 140.200 140.20 435 36 140.199195 AAPL
... ... ... ... ... ... ... ... ... ...
58250 2021-10-27 19:58:00+00:00 209.31 209.33 209.215 209.26 26440 348 209.251852 ZTS
58251 2021-10-27 19:59:00+00:00 209.28 209.59 209.010 209.56 109758 1060 209.384672 ZTS
58252 2021-10-27 20:03:00+00:00 209.58 209.58 209.580 209.58 537786 49 209.580000 ZTS
58253 2021-10-27 20:05:00+00:00 209.58 209.58 209.580 209.58 4170 1 209.580000 ZTS
58254 2021-10-27 20:12:00+00:00 209.58 209.58 209.580 209.58 144 1 209.580000 ZTS
[58255 rows x 9 columns]
</code></pre>
<p>I want to be able to use <code>df.groupby</code> so I can loop over each of the days of each ticker. Something like:</p>
<pre><code> timestamp open high low close volume trade_count vwap symbol
0 2021-10-13 08:00:00+00:00 140.20 140.40 140.000 140.40 6084 65 140.205417 AAPL
1 2021-10-13 08:01:00+00:00 140.35 140.40 140.200 140.40 3052 58 140.308182 AAPL
2 2021-10-13 08:02:00+00:00 140.35 140.35 140.350 140.35 632 30 140.320934 AAPL
3 2021-10-13 08:03:00+00:00 140.28 140.30 140.200 140.20 2867 36 140.279473 AAPL
4 2021-10-13 08:04:00+00:00 140.20 140.20 140.200 140.20 435 36 140.199195 AAPL
timestamp open high low close volume trade_count vwap symbol
0 2021-10-14 08:00:00+00:00 140.20 140.40 140.000 140.40 6084 65 140.205417 AAPL
1 2021-10-14 08:01:00+00:00 140.35 140.40 140.200 140.40 3052 58 140.308182 AAPL
2 2021-10-14 08:02:00+00:00 140.35 140.35 140.350 140.35 632 30 140.320934 AAPL
3 2021-10-14 08:03:00+00:00 140.28 140.30 140.200 140.20 2867 36 140.279473 AAPL
4 2021-10-14 08:04:00+00:00 140.20 140.20 140.200 140.20 435 36 140.199195 AAPL
</code></pre>
<p>How can I do this?</p>
<p>Someone suggested I look at another <a href="https://stackoverflow.com/questions/74168222/how-to-use-groupby-to-take-minute-data-and-group-by-day">question</a>:</p>
<pre><code>table = df.groupby(pd.Grouper(key='timestamp', axis=0, freq='D')).sum()
</code></pre>
<p>But this takes the minute data and returns daily:</p>
<pre><code>Name: 2022-04-04 00:00:00+00:00, dtype: float64)
(Timestamp('2022-04-05 00:00:00+0000', tz='UTC', freq='D'), open 0.0
high 0.0
low 0.0
close 0.0
volume 0.0
trade_count 0.0
vwap 0.0
Name: 2022-04-05 00:00:00+00:00, dtype: float64)
(Timestamp('2022-04-06 00:00:00+0000', tz='UTC', freq='D'), open 2000.818300
high 2001.724000
low 2000.563300
close 2001.462900
volume 59717.000000
trade_count 487.000000
vwap 2001.073115
Name: 2022-04-06 00:00:00+00:00, dtype: float64)
</code></pre>
<p><strong>I need to take my minute data and split the minutes into separate days. I don't need to upscale to daily bars like was suggested <a href="https://stackoverflow.com/questions/74168222/how-to-use-groupby-to-take-minute-data-and-group-by-day">here</a>.</strong></p>
| [
{
"answer_id": 74168491,
"author": "Raibek",
"author_id": 11040577,
"author_profile": "https://Stackoverflow.com/users/11040577",
"pm_score": 1,
"selected": false,
"text": "df = df.sort_values(by=[\"timestamp\", \"symbol\"])\n"
},
{
"answer_id": 74168802,
"author": "mozway",
... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7317408/"
] |
74,168,459 | <p>Tried making gravity that would make the character go down, instead the character is going up and I have no idea why. My code - `</p>
<pre><code>import pygame, sys
from pygame.locals import QUIT
background_colour = (255, 255, 255)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
(width, height) = (800, 400)
window = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *background.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
[pygame.draw.rect(background, color, rect) for rect, color in tiles]
rect = pygame.Rect(0, 0, 20, 20)
rect.center = window.get_rect().center
speed = 3.4
speed2 = 5
</code></pre>
<p>The gravity is implemented here and I cannot find out why the gravity is going up instead of down like it should.</p>
<pre><code>#main application loop
run = True
while run:
gravity = -2
# limit frames per second
clock.tick(100)
# event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# update the game states and positions of objects dependent on the input
keys = pygame.key.get_pressed()
rect.x += (keys[pygame.K_d] - keys[pygame.K_a]) * speed
rect.y += (keys[pygame.K_s] - keys[pygame.K_w]) * speed2
rect.y = rect.y + gravity
border_rect = window.get_rect()
rect.clamp_ip(border_rect)
# clear the display and draw background
window.blit(background, (0, 0))
# draw the scene
pygame.draw.rect(window, (255, 0, 0), rect)
# update the display
pygame.display.flip()
dt = 0
x = 30
y = 30
w = 30
h = 30
a = 30
e = 30
l = 30
k = 30
def draw():
square = pygame.draw.rect(window, RED, pygame.Rect(30, 30, 60, 60), 2)
pygame.display.flip()
def screen_bound():
global x
global y
global w
global h
global a
global e
global l
global k
# hit right wall
if ((x+w) > width):
x = width - w
# hit floor
if ((y+h) > height):
y = height - h
# hit left wall
if (x < 0):
x = 0
# hit roof
if (y < 0):
y = 0
def handle_events():
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
pass
def start():
draw()
screen_bound()
handle_events()
pygame.quit()
exit()`
</code></pre>
<p>I've tried to google and find out the problem, but I am new to coding and can't understand much of what people are saying.</p>
| [
{
"answer_id": 74168500,
"author": "Thiroshan Suthakar",
"author_id": 14687311,
"author_profile": "https://Stackoverflow.com/users/14687311",
"pm_score": 0,
"selected": false,
"text": "gravity = -2\n"
},
{
"answer_id": 74169557,
"author": "Rabbid76",
"author_id": 5577765,... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20306096/"
] |
74,168,466 | <p>I'm trying to make a nestjs project with Mikro Orm refrencing <a href="https://docs.nestjs.com/recipes/mikroorm#load-entities-automatically" rel="nofollow noreferrer">load-entities-automatically</a>. But Mikro Orm does not create tables automatically... The following codes are my settings</p>
<p><strong>AppModule.ts</strong></p>
<pre class="lang-js prettyprint-override"><code>@Module({
imports: [
MikroOrmModule.forRoot({
type: 'postgresql',
host: 'localhost',
user: 'test',
password: 'test',
dbName: 'test',
port: 5440,
autoLoadEntities: true,
entities: ['../entity/domain'],
entitiesTs: ['../entity/domain'],
allowGlobalContext: true,
schemaGenerator: {
createForeignKeyConstraints: false,
},
}),
UserModule,
],
controllers: [],
providers: [],
})
export class AppModule {}
</code></pre>
<p><strong>UserModule</strong></p>
<pre class="lang-js prettyprint-override"><code>@Module({
imports: [UserEntityModule],
controllers: [UserController],
providers: [UserService, UserRepository],
})
export class UserModule {}
</code></pre>
<p><strong>UserRepository</strong></p>
<pre class="lang-js prettyprint-override"><code>import { InjectRepository } from '@mikro-orm/nestjs';
import { EntityRepository } from '@mikro-orm/postgresql';
import { Injectable } from '@nestjs/common';
@Injectable()
export class UserRepository {
constructor(
@InjectRepository(User)
private readonly userRepository: EntityRepository<User>,
) {}
async save(req: UserSaveRequest) {
const response = await this.userRepository
.createQueryBuilder()
.insert(req)
.execute();
return response;
}
}
</code></pre>
<p><strong>UserEntityModule</strong></p>
<pre class="lang-js prettyprint-override"><code>import { MikroOrmModule } from '@mikro-orm/nestjs';
@Module({
imports: [MikroOrmModule.forFeature([User])],
exports: [MikroOrmModule],
})
export class UserEntityModule {}
</code></pre>
<p><strong>User</strong></p>
<pre class="lang-js prettyprint-override"><code>import { Entity, Property } from '@mikro-orm/core';
@Entity({ tableName: 'users' })
export class User extends BaseEntity {
@Property({ comment: "user's nickname" })
nickname: string;
}
</code></pre>
<p><strong>BaseEntity</strong></p>
<pre class="lang-js prettyprint-override"><code>export abstract class BaseEntity {
@PrimaryKey()
id: number;
}
</code></pre>
<p>Code is simple but too long... How can I solve it?</p>
| [
{
"answer_id": 74168500,
"author": "Thiroshan Suthakar",
"author_id": 14687311,
"author_profile": "https://Stackoverflow.com/users/14687311",
"pm_score": 0,
"selected": false,
"text": "gravity = -2\n"
},
{
"answer_id": 74169557,
"author": "Rabbid76",
"author_id": 5577765,... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7029796/"
] |
74,168,475 | <p>I have a challenge when applying multiple conditions in columns, never did it before and would be appreciated some help,from teh database it is required:</p>
<pre><code> ID user reception_date end_date Status
0 42872 luaquint@a.com.co 2022-03-30 2022-03-30 Accepted
1 42872 andres@a.com.co 2022-03-01 2022-03-04 Returned
2 42872 luaquint@a.com.co 2022-03-07 2022-03-30 In Study
3 9999 luaquint@a.com.co 2022-03-07 2022-03-30 Rejected
</code></pre>
<p>if the ID is the same, check if in the Status column has the status of "Accepted", once verified this first requirement, check if the "end_date" of "Accepted" is greater or equal to the date of the status "In Study", if this condition is true change the status from "In Study" to "Accepted".</p>
<p>The expected output would be as follows:</p>
<pre><code> ID user reception_date end_date Status
0 42872 luaquint@a.com.co 2022-03-30 2022-03-30 Accepted
1 42872 andres@a.com.co 2022-03-01 2022-03-04 Returned
2 42872 luaquint@a.com.co 2022-03-07 2022-03-30 Accepted
3 9999 luaquint@a.com.co 2022-03-07 2022-03-30 Rejected
</code></pre>
<p>I have tried several methods to make comparisons such as <code>np.where</code>, <code>df.loc</code> and tried using <code>apply()</code>, however the results weren't good as I expected, I don't have much knowledge about Pandas and I am still learning, thank you very much!</p>
| [
{
"answer_id": 74168500,
"author": "Thiroshan Suthakar",
"author_id": 14687311,
"author_profile": "https://Stackoverflow.com/users/14687311",
"pm_score": 0,
"selected": false,
"text": "gravity = -2\n"
},
{
"answer_id": 74169557,
"author": "Rabbid76",
"author_id": 5577765,... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11263455/"
] |
74,168,477 | <p>The class myDataFrame inherits a pandas DataFrame. When I make modifications to the DataFrame using "self =", the operation completes successfully but in fact the DataFrame object is not modified. Why is this the case and what is the correct way to modify the DataFrame?</p>
<pre><code>import pandas
class myDataFrame(pandas.DataFrame):
def __init__(self, adict):
super().__init__(adict)
def df_reorder_columns(self):
self = self[["Name", "Number"]] # this assignment doesn't work
my_data = {'Number': [1, 2],
'Name': ['Adam', 'Abel']}
test_myDataFrame = myDataFrame(my_data)
print(test_myDataFrame)
test_myDataFrame.df_reorder_columns()
print(test_myDataFrame)
</code></pre>
<pre><code> Number Name
0 1 Adam
1 2 Abel
Number Name
0 1 Adam
1 2 Abel
</code></pre>
| [
{
"answer_id": 74168520,
"author": "Raibek",
"author_id": 11040577,
"author_profile": "https://Stackoverflow.com/users/11040577",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd \n\nclass myDataFrame(pandas.DataFrame):\n\n def __init__(self, adict):\n super()... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4490632/"
] |
74,168,490 | <p>I tried to implement producer consumer problem in C++, but I found that my implementation has a problem that it will produce until the size reaches the capacity and then start the consume process. I wonder what's the problem with my implementation.</p>
<pre><code>#include <iostream>
#include <mutex>
#include <thread>
#include <queue>
#include <chrono>
using namespace std;
std::mutex mtx;
condition_variable cv;
queue<int> q;
int n=2;
int produceData() {
int res=rand()%1000;
cout<<"produce data:"<<res<<endl;
return res;
}
void consumeData() {
cout<<"consume data:"<<q.front()<<endl;
}
void producer(){
while(true) {
unique_lock<mutex> lk(mtx);
cv.wait(lk,[&](){return q.size()<n;});
q.push(produceData());
cv.notify_one();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
void consumer() {
while(true) {
unique_lock<mutex> lk(mtx);
cv.wait(lk,[&](){return q.size()>0;});
consumeData();
q.pop();
cv.notify_one();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main() {
std::thread t1(producer);
std::thread t2(consumer);
t1.join();
t2.join();
return 0;
}
</code></pre>
| [
{
"answer_id": 74168563,
"author": "selbie",
"author_id": 104458,
"author_profile": "https://Stackoverflow.com/users/104458",
"pm_score": 3,
"selected": true,
"text": "unique_lock"
},
{
"answer_id": 74171569,
"author": "Solomon Slow",
"author_id": 801894,
"author_prof... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20079379/"
] |
74,168,512 | <p>Is there any way to make this code work with a column on a data frame that contains 1 word only? I just need all POS that a single word can have. Enclosed is an example of pack which can be a NN or VB.</p>
<pre><code>import nltk
from nltk.corpus import brown
from collections import Counter, defaultdict
x = defaultdict(list)
for word, pos in brown.tagged_words()[1:1000000000]:
if pos not in x[word]:
x[word].append(pos)
print(x["pack"])
</code></pre>
<p>Out put: ['NN', 'VB']</p>
| [
{
"answer_id": 74168563,
"author": "selbie",
"author_id": 104458,
"author_profile": "https://Stackoverflow.com/users/104458",
"pm_score": 3,
"selected": true,
"text": "unique_lock"
},
{
"answer_id": 74171569,
"author": "Solomon Slow",
"author_id": 801894,
"author_prof... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20195029/"
] |
74,168,552 | <p>I am getting this error in my code: There is no argument given corresponds to the required formal pattern 'y' of Math.Pow(double, double).</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.ComponentModel.DataAnnotations;
namespace AssignmentTwo.Models
{
public class FutureValueCalculator
{
[Required(ErrorMessage = "Please enter a Principal value.")]
[Range(50000, 1000000, ErrorMessage =
"Principle value must be between 50,000 to 10,00,000.")]
public decimal? PrincipleValue { get; set; }
[Required(ErrorMessage = "Please enter a yearly interest rate.")]
[Range(0.1, 10.0, ErrorMessage =
"Yearly interest rate must be between 0.1 and 10.0.")]
public decimal? YearlyInterestRate { get; set; }
[Required(ErrorMessage = "Please enter Compounding periods per year.")]
[Range(1, 24, ErrorMessage =
"Compounding period must be between 1 to 24 according to months")]
public decimal? CompoundingPeriod { get; set; }
[Required(ErrorMessage = "Please enter a number of years.")]
[Range(1, 50, ErrorMessage =
"Number of years must be between 1 and 50.")]
public int? Years { get; set; }
public decimal? CalculateFutureValue()
{
int? months = Years * 12;
decimal? monthlyInterestRate = YearlyInterestRate / 12 / 100;
decimal? futureValue = 0;
for (int i = 0; i < months; i++)
{
futureValue = Decimal.ToDouble(Math.Pow((PrincipleValue * (1 + (YearlyInterestRate / CompoundingPeriod)), CompoundingPeriod * Years)));
}
return futureValue;
}
}
}
</code></pre>
| [
{
"answer_id": 74168565,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 0,
"selected": false,
"text": "Math.Pow((PrincipleValue * (1 + (YearlyInterestRate / CompoundingPeriod)), CompoundingPeriod * Years))"
},
{
... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20312122/"
] |
74,168,558 | <p>if I have this:</p>
<pre><code>{
"restaurant": {
"categories": [
{
"name": "Italia"
},
{
"name": "Modern"
}
],
}
}
</code></pre>
<p>I've tried to get the value with <em>restaurant.categories</em>,
it return [object, object],[object, object]</p>
<p>expected result: Italia, Modern</p>
| [
{
"answer_id": 74168566,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 2,
"selected": true,
"text": "map()"
},
{
"answer_id": 74168720,
"author": "SUMIT KUMAR SINGH",
"author_id": 11687831,
"autho... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20312117/"
] |
74,168,560 | <p>I'm writing a C project for school assignments with pthreads and for some reason my program throws <code>SEGFAULT (exact error is "[1] 2446 segmentation fault ./time")</code> if I try to run it when I compile it without <code>fsanitize=address</code>. However if I compile the same program with <code>fsanitize=address</code>, the program throws</p>
<pre><code>time(2544,0x10b1d1600) malloc: nano zone abandoned due to inability to preallocate reserved vm space.
</code></pre>
<p>but still runs. I compile using the make file I've made:</p>
<pre><code>CC = /usr/bin/gcc
CPPFLAGS =-g -Wall -fsanitize=address -std=c11
HDRS = gui2.h display.h
OBJS = gui2.o display.o
main: $(OBJS) $(HDRS)
$(CC) $(CPPFLAGS) -lpthread -o time time.c $(OBJS)
%.o: %.c %.h
.PHONY: clean
clean:
rm -r time.dSYM && rm $(OBJS) time
</code></pre>
<p>As this is incorrect behaviour, how can I fix this?</p>
<pre><code>I'm on macOS 12.6
$ gcc --version
Apple clang version 14.0.0 (clang-1400.0.29.102)
Target: x86_64-apple-darwin21.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
</code></pre>
<p>My code is here:</p>
<p>time.c</p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <unistd.h>
#include "gui2.h"
typedef struct data {
int tid;
pthread_mutex_t *mutex;
pthread_cond_t *cond;
} data;
typedef struct gui_data {
int bin;
int *done;
pthread_mutex_t *mutex;
pthread_cond_t *cond;
} gui_data;
void *thread_function(void *args)
{
struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 100000000;
pthread_t t;
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, NULL);
pthread_cond_t cond;
pthread_cond_init(&cond, NULL);
data *thread_data = (data*)args;
gui_data *threadData = (gui_data*)malloc(sizeof(gui_data));
threadData->bin = thread_data->tid;
threadData->done = (int*)malloc(sizeof(int));
*(threadData->done) = 0;
threadData->mutex = &mutex;
threadData->cond = &cond;
//instead of tracking the counter for the iteration with a variable, we implemented a simpler counting mechanism in the thread itself with a explicit var
for (int i = 0; i < 2; ++i)
{
*(threadData->done) = 0;
pthread_mutex_lock(&mutex);
pthread_create(&t, NULL, gui, threadData);
if (threadData->done == 0)
{
pthread_cond_wait(threadData->cond, threadData->mutex);
}
nanosleep(&ts, NULL);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
pthread_join(t,NULL);
free(threadData->done);
free(threadData);
pthread_exit(NULL);
}
int main()
{
int n = 100;
pthread_t tid[n];
data args[n];
for (int i = 0; i < n; i++)
{
args[i].tid = i;
}
struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 100000000;
for (int i = 0; i < n; ++i)
{
nanosleep(&ts, NULL);
pthread_create(&tid[i], NULL, thread_function, &args[i]);
}
return EXIT_SUCCESS;
}
</code></pre>
<p>gui2.c</p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <pthread.h>
#include "display.h"
#define PI2 6.28318530717
typedef struct gui_data {
int bin;
int *done;
pthread_mutex_t *mutex;
pthread_cond_t *cond;
} gui_data;
void *gui(void *count)
{
gui_data *guiData = (gui_data*)count;
pthread_mutex_lock(guiData->mutex);
int x, y;
char panel[HEIGHT][WIDTH];
fill(panel);
x = ((guiData->bin / 10) % 10);
y = (guiData->bin % 10);
set(panel, x, y, 'X');
system("clear");
display(panel);
printf("\n");
*(guiData->done) = 1;
pthread_mutex_unlock(guiData->mutex);
pthread_exit(NULL);
}
</code></pre>
<p>gui2.h</p>
<pre><code>#ifndef GUI_H
#define GUI_H
void *gui(void *count);
#endif
</code></pre>
<p>display.c</p>
<pre><code>#include <stdio.h>
#include <string.h>
#include "display.h"
void set(char buf[HEIGHT][WIDTH], int i, int j, char c)
{
buf[j][i] = c;
}
void fill(char buf[HEIGHT][WIDTH])
{
for (int j = 0; j < HEIGHT; j++)
{
for (int i = 0; i < WIDTH; i++)
{
buf[j][i] = '`';
}
}
}
void display(char buf[HEIGHT][WIDTH])
{
char frame[HEIGHT*(WIDTH+1)+1];
copy_frame(frame, buf);
printf("%s", frame);
}
void copy_frame(char f[], char b[HEIGHT][WIDTH])
{
for (int i = 0; i < HEIGHT; i++)
{
strncpy(
&(f[i*(WIDTH+1)]),
b[i],
WIDTH
);
f[i*(WIDTH+1) + WIDTH] = '\n';
}
f[HEIGHT*(WIDTH+1)] = '\0';
}
</code></pre>
<p>and finally this is display.h</p>
<pre><code>#ifndef HEADER_DISPLAY
#define HEADER_DISPLAY
#define WIDTH 10
#define HEIGHT 10
void set(char buf[HEIGHT][WIDTH], int, int, char);
void fill(char buf[HEIGHT][WIDTH]);
void display(char buf[HEIGHT][WIDTH]);
void copy_frame(char[], char buf[HEIGHT][WIDTH]);
#endif
</code></pre>
| [
{
"answer_id": 74168806,
"author": "Vladislav Tsisyk",
"author_id": 11628610,
"author_profile": "https://Stackoverflow.com/users/11628610",
"pm_score": 0,
"selected": false,
"text": "done"
},
{
"answer_id": 74169062,
"author": "n. m.",
"author_id": 775806,
"author_pro... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5984665/"
] |
74,168,583 | <p>I have a datatable with 4 columns but only 3 are currently showing when the screen is rotated i am able to see all 4 columns it is not even scrollable.</p>
<p>I am try to see the 4 columns in a single view ut I am getting this error:</p>
<pre><code>lib/screens/home_screen.dart:79:29: Error: Cannot invoke a non-'const' constructor where a const expression is expected.
Try using a constructor or factory that is 'const'.
DataTable(
^^^^^^^^^
lib/screens/home_screen.dart:78:54: Error: Too many positional arguments: 0 allowed, but 1 found.
Try removing the extra positional arguments.
const SingleChildScrollView(
^
/C:/src/flutter/flutter/packages/flutter/lib/src/widgets/single_child_scroll_view.dart:140:9: Context: Found this candidate, but the arguments don't match.
const SingleChildScrollView({
^^^^^^^^^^^^^^^^^^^^^
Restarted application in 274ms.
</code></pre>
<p>Here is th e code for the table:</p>
<pre><code> ExpansionTile(
title: const Text("Click Here to See table Name"),
children: [
const SingleChildScrollView(
DataTable(
columns: const <DataColumn>[
DataColumn(
label: Text(
'Sr.No',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
),
DataColumn(
label: Text(
'Website',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
),
DataColumn(
label: Text(
'Tutorial',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
),
DataColumn(
label: Text(
'Review',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
),
],
rows: const <DataRow>[
DataRow(
cells: <DataCell>[
DataCell(
Text('1'),
),
DataCell(
Text('https://flutter.dev/'),
),
DataCell(
Text('Flutter'),
),
DataCell(
Text('5*'),
),
],
),
DataRow(
cells: <DataCell>[
DataCell(
Text('2'),
),
DataCell(
Text('https://dart.dev/'),
),
DataCell(
Text('Dart'),
),
DataCell(
Text('5*'),
),
],
),
DataRow(
cells: <DataCell>[
DataCell(
Text('3'),
),
DataCell(
Text('https://pub.dev/'),
),
DataCell(
Text('Flutter Packages'),
),
DataCell(
Text('5*'),
),
],
),
],
),
),
],
),
</code></pre>
<p>My question: How can make the table view in one screen so that it can be wrapped or the columns shrink to be view in a singleview?</p>
| [
{
"answer_id": 74168886,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": true,
"text": "DataTable"
},
{
"answer_id": 74169006,
"author": "Umut Kaya",
"author_id": 20142195,
"autho... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13176726/"
] |
74,168,590 | <p>Question: How do I create a wallet guard that will allow for an arbitrary number of people to withdraw from it, if they meet specific conditions?</p>
<p>I am trying to make a wallet with a guard that lets a user withdraw a specific amount from it depending on how long they've owned an NFT, among other factors. Right now I'm doing the most basic check: seeing if the "recipient" address passed into the claim function is the owner of a specific NFT. If they own that NFT, they can withdraw as much as they want.</p>
<pre><code> (defcap WITHDRAW (recipient:string nft-id:string)
(with-read mledger nft-id
{'owner-address := owner-address }
(enforce (= recipient owner-address) "not the owner of this NFT")
)
(compose-capability (BANK_DEBIT))
)
(defun require-WITHDRAW (recipient:string nft-id:string)
(require-capability (WITHDRAW recipient nft-id))
)
(defun create-WITHDRAW-guard (recipient:string nft-id:string)
(create-user-guard (require-WITHDRAW recipient nft-id))
)
(defun create-simple-user-guard (funder:string nft-id:string BANK_KDA_ACCT:string amount:decimal recipient:string)
(coin.transfer-create funder BANK_KDA_ACCT
(create-WITHDRAW-guard recipient nft-id) amount)
)
</code></pre>
<p>With my current code, only the very first inputs that I pass into (create-simple-user-guard) impact who can withdraw, but I do not know how to allow the guard to accept many different recipients and NFT-ids. Any advice would be appreciated.</p>
<p>I'm following this "tutorial" <a href="https://medium.com/kadena-io/deprecation-notice-for-module-guards-and-pact-guards-2efbf64f488f" rel="nofollow noreferrer">https://medium.com/kadena-io/deprecation-notice-for-module-guards-and-pact-guards-2efbf64f488f</a> but it loses any amount of detail after it gets to making more robust debit capabilities</p>
| [
{
"answer_id": 74168887,
"author": "Luzzotica",
"author_id": 19692450,
"author_profile": "https://Stackoverflow.com/users/19692450",
"pm_score": 2,
"selected": false,
"text": "(defcap WITHDRAW (nft-id:string)\n (with-read mledger nft-id\n {'owner-address := owner-address }\n (... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19151953/"
] |
74,168,609 | <p>I am writing an embedded C code.
Which if condition would be faster/optimized:</p>
<pre><code>if (a == false)
{
Some code
}
</code></pre>
<p>OR</p>
<pre><code>if (a != true)
{
Some code
}
</code></pre>
| [
{
"answer_id": 74168620,
"author": "jgpixel",
"author_id": 18584468,
"author_profile": "https://Stackoverflow.com/users/18584468",
"pm_score": 1,
"selected": false,
"text": "if (!a) { /* code */ }"
},
{
"answer_id": 74168691,
"author": "Jonathan Leffler",
"author_id": 151... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3220717/"
] |
74,168,611 | <pre><code> <tbody>
{nums.map(index => {
return (
<tr >
<td>A</td>
{reservedSeat.map((obj, index) => {
return (
<>
<td><Button >{obj.seatno}</Button></td>
</>
)
})}
</tr>
)
})}
</tbody>
</code></pre>
<p>Here the reservedSeat is array of objects. Each object contains id and name</p>
<p>output i got :
A001 A002 A003 A004 A005 B001 B002 B003 B004 B005 C001 C002 C003 C004 C005 \n
A001 A002 A003 A004 A005 B001 B002 B003 B004 B005 C001 C002 C003 C004 C005 \n
A001 A002 A003 A004 A005 B001 B002 B003 B004 B005 C001 C002 C003 C004 C005</p>
<p>pattern:</p>
<pre><code>A001 A002 A003 A004 A005 \n
B001 B002 B003 B004 B005 \n
C001 C002 C003 C004 C005 \n
</code></pre>
| [
{
"answer_id": 74168620,
"author": "jgpixel",
"author_id": 18584468,
"author_profile": "https://Stackoverflow.com/users/18584468",
"pm_score": 1,
"selected": false,
"text": "if (!a) { /* code */ }"
},
{
"answer_id": 74168691,
"author": "Jonathan Leffler",
"author_id": 151... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19809652/"
] |
74,168,645 | <p>I want the code to execute the average marks of all students simultaneously and also determine the grade of the student after printing each average marks.</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
int main()
{
int stud_rlno[8], phy_marks[8], chem_marks[8],
bio_marks[8], CS_marks[8], average;
int i;
for(int i = 0; i < 1; ++i)
{
printf("Enter the roll number of student %d: ", i);
scanf("%d", &stud_rlno[i]);
printf("Enter the physics marks of student %d: ", i);
scanf("%d", &phy_marks[i]);
printf("Enter the chemistry marks of student %d: ", i);
scanf("%d", &chem_marks[i]);
printf("Enter the biology marks of student %d: ", i);
scanf("%d", &bio_marks[i]);
printf("Enter the CS marks of student %d: ", i);
scanf("%d", &CS_marks[I]);
}
for(int i = 0; i <= 1; i++)
{
average = phy_marks[i] + chem_marks[i] + bio_marks[i] + CS_marks[i];
printf("The average of student is %d \n", average / 4);
if(average > 90)
{
printf("Grade A \n");
}
else if(average <= 90 && average > 82)
{
printf("Grade B \n");
}
else if(average <= 82 && average > 75)
{
printf("Grade C \n");
}
else if(average <= 75 && average > 65)
{
printf("Grade D \n");
}
else if(average <= 65)
{
printf("Grade E \n");
}
else
{
printf("Fail");
}
}
}
</code></pre>
<p>The if statements inside the for loop don't work, Why are the If statements inside the for loop not working except for the first condition whichever it satisfies? I tried with many variations but it still doesn't work.</p>
| [
{
"answer_id": 74168620,
"author": "jgpixel",
"author_id": 18584468,
"author_profile": "https://Stackoverflow.com/users/18584468",
"pm_score": 1,
"selected": false,
"text": "if (!a) { /* code */ }"
},
{
"answer_id": 74168691,
"author": "Jonathan Leffler",
"author_id": 151... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19528900/"
] |
74,168,662 | <p>I am trying to make a program that shifts the characters of a message to the right of its position in the alphabet. For example: the input is "abc" and the output would be "bcd".</p>
<p>Currently this is the code:</p>
<pre><code>import string
alphabet = list(string.ascii_lowercase)
codelist = []
code = input("input text message: ")
for char in code:
codelist.append(char)
for x in codelist:
for y in alphabet:
if y == x and x != " ":
x = alphabet[alphabet.index(y) + 1]
</code></pre>
<p>Traceback:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\pythonProject1\file.py", line 12, in <module>
x = alphabet[alphabet.index(y) + 1]
IndexError: list index out of range
</code></pre>
| [
{
"answer_id": 74168721,
"author": "assume_irrational_is_rational",
"author_id": 11622508,
"author_profile": "https://Stackoverflow.com/users/11622508",
"pm_score": -1,
"selected": false,
"text": "ord"
},
{
"answer_id": 74168793,
"author": "Huzaifa Azhar",
"author_id": 17... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20312125/"
] |
74,168,673 | <p>I have this Object on get:</p>
<pre><code> [
{
"id": {
"M49": 20,
"ISO-3166-1-ALPHA-2": "AD",
"ISO-3166-1-ALPHA-3": "AND"
},
"nome": {
"abreviado": "Andorra",
"abreviado-EN": "Andorra",
"abreviado-ES": "Andorra"
},
"area": {
"total": "468",
"unidade": {
"nome": "quilômetros quadrados",
"símbolo": "km2",
"multiplicador": 1
}
},
"localizacao": {
"regiao": {
"id": {
"M49": 150
},
"nome": "Europa"
},
"sub-regiao": {
"id": {
"M49": 39
},
"nome": "Europa meridional (Sul da Europa)"
},
"regiao-intermediaria": null
},
"linguas": [
{
"id": {
"ISO-639-1": "ca",
"ISO-639-2": "cat"
},
"nome": "catalão"
}
],
"governo": {
"capital": {
"nome": "Andorra-a-Velha"
}
},
"unidades-monetarias": [
{
"id": {
"ISO-4217-ALPHA": "EUR",
"ISO-4217-NUMERICO": "978"
},
"nome": "Euro"
}
],
"historico": "O Principado de Andorra é um dos menores Estados da Europa, situado no alto dos Pireneus, entre as... "
}
]
</code></pre>
<p>I can't return every "nome": {"abreviado":"Andorra"}</p>
<pre><code>import styles from "../styles/Home.module.css";
import { useEffect, useState } from "react";
let url = "https://servicodados.ibge.gov.br/api/v1/paises";
export default function Home() {
let [countryfact, setCountryfact] = useState([null]);
useEffect(() => {
fetch(url)
.then((response) => response.json())
.then((result) => setCountryfact(result));
}, []);
console.log(countryfact)
return (
<div style={{ color: "blue" }}>
<ul>
{countryfact.map((country, name) => (
<li key={country.name}>
<span>name: {countryfact.name}</span> <span>age: {countryfact.id}</span>
</li>
))}
</ul>
</div>
);
}
</code></pre>
<p>I want to return the object inside another object but i can't do it with my code</p>
<p>My return on screen, is empty, but there a lot empty lines returning.
Maybe this is a simple, but i try with another ways without results</p>
<p><a href="https://i.stack.imgur.com/wAWDl.png" rel="nofollow noreferrer">Return on screen</a></p>
| [
{
"answer_id": 74168697,
"author": "Pedro Demeu",
"author_id": 16696305,
"author_profile": "https://Stackoverflow.com/users/16696305",
"pm_score": 0,
"selected": false,
"text": "li"
},
{
"answer_id": 74168851,
"author": "user11877521",
"author_id": 11877521,
"author_p... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20074108/"
] |
74,168,681 | <p>right now my div looks like this:</p>
<pre><code> .codeText{
background-color: #2C3E50 ;
color: white;
display:inline-block;
border-radius: 25px;
}
</code></pre>
<p>when I use it on a <code><p></code> like this:</p>
<pre><code><div class="codeText">
<p> <code>&lt;p&gt;This is a paragraph &lt;/p&gt;</code></p>
</div>
</code></pre>
<p>The output looks like this:</p>
<p><a href="https://i.stack.imgur.com/jBlN5.png" rel="nofollow noreferrer">Code output screenshot</a></p>
<p>What I want is for there to be a little gap between the text and the background. (gaps on the red arrows shown on the screenshot)</p>
<p><strong>edit:</strong> I want to implement this into the <code>.codeText{}</code> and not inline so I can use in multiple areas</p>
| [
{
"answer_id": 74168737,
"author": "Huda Addelson",
"author_id": 19123792,
"author_profile": "https://Stackoverflow.com/users/19123792",
"pm_score": 0,
"selected": false,
"text": "padding-left"
},
{
"answer_id": 74168739,
"author": "Haim Abeles",
"author_id": 15298697,
... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19866356/"
] |
74,168,698 | <p>i have a button variable and is keeps crashing</p>
<p>here's MainActivity.java:</p>
<pre><code>package com.example.datasaving;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
Button button = this.findViewById(R.id.SAVE);
TextView InputID = findViewById(R.id.textView);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String msg = InputID.getText().toString();
Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
}
});
}
}
</code></pre>
<p>and Here's activity_main.xml:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/SAVE"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/save"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/enter_your_gmail"
android:textColorHint="#757575"
app:layout_constraintBottom_toTopOf="@+id/SAVE"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code></pre>
<p>now it gives me an error saying :</p>
<pre><code>FATAL EXCEPTION: main
Process: com.example.datasaving, PID: 6961
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.datasaving/com.example.datasaving.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3921)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4078)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2423)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:233)
at android.os.Looper.loop(Looper.java:334)
at android.app.ActivityThread.main(ActivityThread.java:8348)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:582)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1065)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.datasaving.MainActivity.onCreate(MainActivity.java:20)
at android.app.Activity.performCreate(Activity.java:8363)
at android.app.Activity.performCreate(Activity.java:8341)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3894)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4078)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2423)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:233)
at android.os.Looper.loop(Looper.java:334)
at android.app.ActivityThread.main(ActivityThread.java:8348)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:582)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1065)
</code></pre>
<p>so this says that i have a null object but when i ctrl click that object it sends me back to The button what could be wrong am I doing something wrong or is it just the android studio??? </p>
| [
{
"answer_id": 74168709,
"author": "z.y",
"author_id": 19023745,
"author_profile": "https://Stackoverflow.com/users/19023745",
"pm_score": 2,
"selected": true,
"text": "Button button = this.findViewById(R.id.SAVE);\nTextView InputID = findViewById(R.id.textView);\nsuper.onCreate(savedIns... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20312274/"
] |
74,168,705 | <p>I have a string which contains repeated substrings like</p>
<pre><code>The big black dog big black dog is a friendly friendly dog who who lives nearby nearby
</code></pre>
<p>How can I remove these in BQ so that the result looks like this</p>
<pre><code>The big black dog is a friendly dog who lives nearby
</code></pre>
<p>I tried with regex capturing groups like in this <a href="https://stackoverflow.com/a/38683695/165130">question</a> but no luck so far, it just returns the original phrase</p>
<pre><code>with text as (
select "The big black dog big black dog is a friendly
friendly dog who who lives nearby nearby" as phrase
)
select REGEXP_REPLACE(phrase,r'([ \\w]+)\\1',r'$1') from text
</code></pre>
<p>Edit: assuming the repeated word or phrase <strong>follows right after</strong> the first instance of a word or phrase</p>
<p>i.e. <code>dog dog</code> is considered a repetition of <code>dog</code>,
but <code>dog good dog</code> is not</p>
<p>similarly for phrases:</p>
<p><code>good dog good dog</code> is repetition of <code>good dog</code></p>
<p>but <code>good dog catch ball good dog</code> is not considered a repetition</p>
| [
{
"answer_id": 74168709,
"author": "z.y",
"author_id": 19023745,
"author_profile": "https://Stackoverflow.com/users/19023745",
"pm_score": 2,
"selected": true,
"text": "Button button = this.findViewById(R.id.SAVE);\nTextView InputID = findViewById(R.id.textView);\nsuper.onCreate(savedIns... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165130/"
] |
74,168,711 | <p>How do I change a bash array into a string with this pattern? Let's say I have <code>arr=(a b c d)</code> and I want to change to this pattern
<code>'a' + 'b' + 'c' + 'd'</code> with the white space in between.</p>
<p>PS-I figured out this pattern <code>'a'+'b'+'c'+'d'</code> but not sure how to put <code>" + "</code> instead of just <code>"+"</code> in between.</p>
| [
{
"answer_id": 74168763,
"author": "Gilles Quenot",
"author_id": 465183,
"author_profile": "https://Stackoverflow.com/users/465183",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\n\narr=(a b c d)\nstr=\"${arr[@]}\"\nstr=${str// / + } # Parameter Expansion\nsed \"s/[a-z]/'&'/g\" ... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16666341/"
] |
74,168,742 | <p>From my understanding:</p>
<ol>
<li><Route loader...> "<a href="https://reactrouter.com/en/main/route/loader" rel="nofollow noreferrer">only works if using a data router</a>"</li>
<li>data routers (like createBrowserRouter) don't allow for wrapping 'all' of the routes in jsx containing <Link> components. See examples</li>
</ol>
<p>Example: Non data routers</p>
<pre class="lang-js prettyprint-override"><code><Router>
<header>
<Link to="/">Home</Link>
</header>
<Routes>
<Route...>
<Route...>
</Routes>
</Router>
</code></pre>
<p>Example: data routers (throws error) <a href="https://playcode.io/992668" rel="nofollow noreferrer">full example</a></p>
<pre class="lang-js prettyprint-override"><code>const router = createBrowserRouter([....]);
<div>
<header>
<Link to="/">Home</Link>
</header>
<RouterProvider router={router} />
</div>
</code></pre>
<p>My question is this: How can we create a template that wraps the RouterProvider (and all the content it imports) with a template that makes use of <Link> functionality?</p>
| [
{
"answer_id": 74168838,
"author": "Drew Reese",
"author_id": 8690857,
"author_profile": "https://Stackoverflow.com/users/8690857",
"pm_score": 3,
"selected": true,
"text": "header"
},
{
"answer_id": 74247910,
"author": "MadaShindeInai",
"author_id": 13221036,
"author... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/697576/"
] |
74,168,749 | <p>when I execute below cmd:</p>
<pre><code>go get k8s.io/client-go@v12.0.0
</code></pre>
<p>it tells me: "<strong>go: k8s.io/client-go@v12.0.0: invalid version: module contains a go.mod file, so module path must match major version ("k8s.io/client-go/v12")</strong>"</p>
<p>ok, then I changed the cmd to this:</p>
<pre><code>go get k8s.io/client-go@v12.0.0+incompatible
</code></pre>
<p>then again, it still tells me the same error: <strong>go: k8s.io/client-go@v12.0.0+incompatible: invalid version: module contains a go.mod file, so module path must match major version ("k8s.io/client-go/v12")</strong></p>
<p>one interesting thing puzzles me that if I add <strong>require k8s.io/client-go v12.0.0+incompatible</strong> to go.mod and then execute <strong>go mod tidy</strong>, then client-go v12.0.0 will be downloaded correctly.</p>
<p>My question is: <strong>how can I download this specific version of client-go via go get</strong>??</p>
<p>Go Version: v1.18</p>
| [
{
"answer_id": 74168838,
"author": "Drew Reese",
"author_id": 8690857,
"author_profile": "https://Stackoverflow.com/users/8690857",
"pm_score": 3,
"selected": true,
"text": "header"
},
{
"answer_id": 74247910,
"author": "MadaShindeInai",
"author_id": 13221036,
"author... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1773471/"
] |
74,168,832 | <p>I have a web url <code>https://www.blibli.com/backend/content/promotions/blm-ranch-market</code>
where when I opened it on chrome returns a json.</p>
<p>However when I tried using requests in python and tried using headers including the cookie from headers it does not work. What is missing?
How do we know what's needed for the request?I check in sources there's no payload only headers, I assumed by this code it will work. However using the same headers does not work.</p>
<pre class="lang-py prettyprint-override"><code>import requests
resp = requests.get('https://www.blibli.com/backend/content/promotions/blm-ranch-market')
if resp == 200:
print(resp.json())
</code></pre>
| [
{
"answer_id": 74168874,
"author": "ankitgupta5294",
"author_id": 5584763,
"author_profile": "https://Stackoverflow.com/users/5584763",
"pm_score": 0,
"selected": false,
"text": "resp.content"
},
{
"answer_id": 74168987,
"author": "relent95",
"author_id": 1186624,
"au... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20296808/"
] |
74,168,842 | <p>So, just like the title says, I've written code to load the info from a json and show it on a <em>SUPER</em> simple HTML page. All I want is for it to show the image, title and have a button to load a new image. The problem is that only the button shows up.</p>
<p>What am I missing here?</p>
<p><strong>Javascript</strong></p>
<pre><code>// function to output the image to the page with the title and description
function output(comic_info) {
let article = document.createElement("article");
let h3 = document.createElement("h3");
h3.innerHTML = comic_info.title;
let img = document.createElement("img");
img.src = comic_info.img;
img.alt = comic_info.alt;
article.appendChild(h3);
article.appendChild(img);
document.getElementById("comics").appendChild(article);
}
// fetch the info from the url about the comic
async function getComic(comic_url) {
const response = await fetch(comic_url);
// check that fetch is successful
if (response.ok) {
comic_info = await response.json();
output(comic_info);
}
}
// get a different comic's info
function getNewComic() {
let random_number = Math.floor(Math.random() * 1000);
let comic_url = "https://xkcd.com/" + random_number + "/info.0.json";
getComic(comic_url);
}
// when a button is clicked, get a new comic
document.getElementById("new_comic").addEventListener("click", getNewComic);
</code></pre>
<p><strong>HTML</strong></p>
<pre><code><body>
<main>
<section>
<!-- div to add comic image and info to the page -->
<div id="comics">
</div>
<!-- button to choose new comic -->
<button id="new_comic">New Comic</button>
</section>
</main>
<footer>
&copy;<span id="year"></span> | Project | Lesson 06
</footer>
<script src="/week06/student_files/scripts/main.js"></script>
<script src="/week06/w06_project.js"></script>
</body>
</code></pre>
| [
{
"answer_id": 74169066,
"author": "Stephen R. Smith",
"author_id": 5596484,
"author_profile": "https://Stackoverflow.com/users/5596484",
"pm_score": 0,
"selected": false,
"text": "async function getComic(comic_url) {\n console.log('In getComic', comic_url);\n"
},
{
"answer_id":... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15293389/"
] |
74,168,861 | <p>I am trying to scrape api data from this link (<a href="https://api.prizepicks.com/projections" rel="nofollow noreferrer">https://api.prizepicks.com/projections</a>). However, I seem to be running into a 403 error. Is there a way around it?</p>
<p>Here is my code:</p>
<p>'''</p>
<pre><code>import pandas as pd
import requests
from pandas.io.json import json_normalize
params = (
('league_id', '7'),
('per_page', '250'),
('projection_type_id', '1'),
('single_stat', 'true'),
)
session = requests.Session()
response = session.get('https://api.prizepicks.com/projections', data=params)
print(response.status_code)
#df1 = json_normalize(response.json()['included'])
#df1 = df1[df1['type'] == 'new_player']
#df2 = json_normalize(response.json()['data'])
#df = pd.DataFrame(zip(df1['attributes.name'], df2['attributes.line_score']), columns=['name', 'points'])
</code></pre>
<p>'''</p>
| [
{
"answer_id": 74168942,
"author": "Barry the Platipus",
"author_id": 19475185,
"author_profile": "https://Stackoverflow.com/users/19475185",
"pm_score": 2,
"selected": false,
"text": "import requests\nfrom bs4 import BeautifulSoup as bs\nimport pandas as pd\n\npd.set_option('display.max... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20312481/"
] |
74,168,878 | <p>When the Supervisor code below is invoked I expect the GenServer to start.
The GenServer does not start and I want to know why and how to fix it.</p>
<pre><code>defmodule App.Service do
use GenServer
def start_link(state) do
GenServer.start_link(__MODULE__, state)
end
def init(state) do
{:ok, state}
end
def get_state(pid) do
GenServer.call(pid, :get_state)
end
def set_state(pid,state) do
GenServer.call(pid, {:set_state, state})
end
def handle_call(:get_state, _from, state) do
{:reply, state, state}
end
def handle_call({:set_state, new_state}, _from, state)do
{:reply,state,[new_state | state]}
end
end
defmodule App.Supervisor do
use Supervisor
def start do
Supervisor.start_link(__MODULE__, [])
end
def init(_) do
children = [
App.Service
]
Supervisor.init(children, strategy: :one_for_one)
end
end
x = App.Supervisor.start()
IO.inspect x
pid = Process.whereis(App.Service)
# The following is nil. I expect a PID
IO.inspect pid
</code></pre>
| [
{
"answer_id": 74168942,
"author": "Barry the Platipus",
"author_id": 19475185,
"author_profile": "https://Stackoverflow.com/users/19475185",
"pm_score": 2,
"selected": false,
"text": "import requests\nfrom bs4 import BeautifulSoup as bs\nimport pandas as pd\n\npd.set_option('display.max... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1152980/"
] |
74,168,913 | <p>I have a Java program running as jar. When it's running, I want to detect download of a file from browser to Downloads folder. I can detect using Java nio package WatchService but the problem is with this I can detect only the addition of new file to Downloads folder. I can't detect when download or copy finishes.</p>
<p>Is there a way I can detect the download (or addition) of a file to a directory (e.g. Downloads) when it finishes?</p>
| [
{
"answer_id": 74168942,
"author": "Barry the Platipus",
"author_id": 19475185,
"author_profile": "https://Stackoverflow.com/users/19475185",
"pm_score": 2,
"selected": false,
"text": "import requests\nfrom bs4 import BeautifulSoup as bs\nimport pandas as pd\n\npd.set_option('display.max... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4472664/"
] |
74,168,927 | <p>I facing problem on cmd Process i can't execute command on cmd and retrieve the result and print it. anyone can help me ?</p>
<pre><code>public class rev {
public static void main(String args[]) throws InterruptedException, IOException {
String host="127.0.0.1";
int port=4444;
String cmd="cmd.exe",readLine;
BufferedWriter writer;
BufferedReader read;
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();
Socket s=new Socket(host,port);
System.out.print(p.getInputStream().read());
writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
writer.write("dir");
read = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((readLine = read.readLine()) != null) {
System.out.print(read.readLine());
}
}
}
</code></pre>
| [
{
"answer_id": 74168942,
"author": "Barry the Platipus",
"author_id": 19475185,
"author_profile": "https://Stackoverflow.com/users/19475185",
"pm_score": 2,
"selected": false,
"text": "import requests\nfrom bs4 import BeautifulSoup as bs\nimport pandas as pd\n\npd.set_option('display.max... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15661834/"
] |
74,168,930 | <p>I want to load my page faster in my Django project, so I know there has the "Bulk" option.</p>
<p>views.py:</p>
<pre><code>class HRListView(Budgetlevel2Mixin, BudgetMixin, LoginRequiredMixin, ListView):
model = HR
template_name = "budget/hr_list.html"
</code></pre>
<p>models.py:</p>
<pre><code>class HR(models.Model):
year_scenario_version = models.ForeignKey(
measure_name = models.ForeignKey(
employee_type = models.ForeignKey(
employee_level = models.ForeignKey(
subsidiary = models.ForeignKey(
department = models.ForeignKey(
currency = models.ForeignKey(
</code></pre>
<p>hr_list.html:</p>
<pre><code>{% block thead %}
<tr>
<th>ID</th>
<th>HR Year Scenario</th>
<th>Measure Name</th>
<th>Employee Type</th>
<th>Employee Level</th>
<th>Subsidiary</th>
<th>Department</th>
</tr>
{% endblock %}
{% block tbody %}
{% for q in object_list %}
<tr>
<td>{{ q.id }}</td>
<td>{{ q.year_scenario_version }}</td>
<td>{{ q.measure_name }}</td>
<td>{{ q.employee_type }}</td>
<td>{{ q.employee_level }}</td>
<td>{{ q.subsidiary }}</td>
<td>{{ q.department }}</td>
</tr>
{% endfor %}
{% endblock %}
</code></pre>
<p>How can I improve the page loading time?
It takes almost 10 sec for full loading, something around 1200 records.</p>
<p>Thanks a lot!</p>
| [
{
"answer_id": 74169070,
"author": "Alombaros",
"author_id": 20263044,
"author_profile": "https://Stackoverflow.com/users/20263044",
"pm_score": 2,
"selected": true,
"text": "def get_queryset():\n return HR.objects.select_related(\"year_scenario_version\", \"measure_name\", \"employee... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13719970/"
] |
74,168,937 | <p>I know how to get all of the sheets from a spreadsheet. The spreadsheet will eventually get more and more sheets.</p>
<pre><code> const thisDoc = SpreadsheetApp.getActive()
const allSheets = thisDoc.getSheets()
</code></pre>
<p>I have a list of string names of the two sheets in the spreadsheet that I never want to use:</p>
<pre><code> excludeList = ["template", "instructions"]
</code></pre>
<p>In Python I would do the following using the NOT IN keywords:</p>
<pre class="lang-py prettyprint-override"><code> listInclSheets = []
for thisSheet in allSheets:
if sheet.getName() not in excludeList:
listInclSheets.append(thisSheet)
</code></pre>
<p>My Question is: How do I get a Subset of an Array excluding members based on a list of String Names of Sheets in Google Apps Script using the array.map() or array.filter() or some other cool method that is not doing it the long way?</p>
<p>I also know how to do it the long way using nested for loops and a boolean flag:</p>
<pre><code> const thisDoc = SpreadsheetApp.getActive()
const arInclSheets = []
const allSheets = thisDoc.getSheets();
excludeList = ["template", "instructions"];
for (thisSheet of allSheets)
{
var booInclude = true;
for (anExcludeName of excludeList)
{
Logger.log("is "+ thisSheet.getName() + "equal to " + anExcludeName +"?");
if (thisSheet.getName() == anExcludeName);
{
booInclude = false;
}
}
if ( booInclude)
{
arInclSheets.push(thisSheet);
}
}
Logger.log(arInclSheets);
for (thisSheet of arInclSheets)
{
Logger.log(thisSheet.getName());
}
}
</code></pre>
<p>P.S. map functions with fancy one line coding always confuse me, so please explain them so I can get unconfused by them.</p>
| [
{
"answer_id": 74169158,
"author": "TheMaster",
"author_id": 8404453,
"author_profile": "https://Stackoverflow.com/users/8404453",
"pm_score": 2,
"selected": true,
"text": "Set"
},
{
"answer_id": 74172243,
"author": "Cooper",
"author_id": 7215091,
"author_profile": "h... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16156431/"
] |
74,168,940 | <p>How can I remove the search button in Mobile Design? As far as I know display: none code this should work but unfortunately I am not able to. I would be very happy if someone can help. Is it a typo error or is there something I've overlooked? I spent about two hours but couldn't figure it out. My codes are like this:</p>
<p>My React codes are like this:</p>
<pre><code> import React from 'react'
import styles from './Hero.module.css'
import {AiOutlineSearch} from 'react-icons/ai'
function Hero() {
return (
<div className={styles.hero}>
<form>
<div className={styles.text}>
<label>Where</label>
<input type="text" placeholder='Search Location' />
</div>
<div className={styles.from}>
<span className={styles.border}></span>
<label>From</label>
<input type="date" />
</div>
<div className={styles.until}>
<span className={styles.border}></span>
<label>Until</label>
<input type="date" />
</div>
<div className={styles.search_btn}>
<AiOutlineSearch />
<button className={styles.btn}>Search for cars</button>
</div>
</form>
</div>
)
}
export default Hero
</code></pre>
<pre><code>My CSS Modules Codes like this:
</code></pre>
<pre class="lang-css prettyprint-override"><code>
.hero {
background: url('https://images.unsplash.com/photo-1519641471654-76ce0107ad1b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2342&q=80')
no-repeat center/cover;
width: 100%;
height: 500px;
display: flex;
}
form {
display: flex;
justify-content: space-between;
align-items: center;
max-width: 700px;
width: 100%;
margin: auto;
margin-top: 10%;
padding: 6px 15px;
border-radius: 25px;
box-shadow: rgba(0, 0, 0, 0.9) 0px 8px 24px;
background-color: rgba(247, 247, 247, 0.9);
}
form label {
font-size: 0.78rem;
padding-bottom: 2px;
}
.text, .from, .until {
display: flex;
flex-direction: column;
}
form input {
background-color: transparent;
border: none;
font-family: 'Epilogue', sans-serif;
}
form .text_input {
width: 300px;
font-size: 1rem;
}
form input:focus {
outline: none;
}
.from, .until {
border-left: 1px solid #333;
padding-left: 6px;
}
form .search_btn {
display: flex;
align-items: center;
}
.search_btn button {
display: none;
}
@media screen and (max-width: 720px) {
form {
display: flex;
flex-direction: column;
max-width: 100%;
margin: auto 1rem;
}
.text, .from, .until {
width: 100%;
padding: .2rem;
}
.from, .until {
border-left: none;
}
.text_input {
font-size: 0.8rem;
}
.text_input{
font-size: 0.8rem;
}
form label {
padding: 0.4rem 0;
}
.border {
border-top: 1px solid #333;
padding: 8px;
}
.search_btn {
width: 100%;
border-top: 1px solid #333;
padding: 8px 0;
}
.search_btn .btn {
display: block;
background-color: #593cfb;
color: #fff;
font-weight: 600;
font-size: 1rem;
border: none;
width: 100%;
padding: 12px 18px;
margin: .5rem 0;
cursor: pointer;
}
.search_btn .btn:hover {
background-color: #4733b7;
transition: background-color 1s;
}
.icon {
display: none;
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/Xxpoo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xxpoo.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74169158,
"author": "TheMaster",
"author_id": 8404453,
"author_profile": "https://Stackoverflow.com/users/8404453",
"pm_score": 2,
"selected": true,
"text": "Set"
},
{
"answer_id": 74172243,
"author": "Cooper",
"author_id": 7215091,
"author_profile": "h... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18950029/"
] |
74,168,989 | <p>I'm trying to call an async function in a callback in useEffect like this.</p>
<pre><code>import {useState, useEffect} from 'react';
import Navbar from 'react-bootstrap/Navbar';
interface EnBoards {
id: number
name: string
uri: string
}
const RedichanNav = (): JSX.Element => {
const [enBoards, setEnBoards] = useState({});
useEffect(() => {
const fetchEnBoards = async () => {
const response = await fetch('/api/en-boards');
const enBoardsJson = await response.json() as EnBoards;
setEnBoards(enBoardsJson);
};
fetchEnBoards(); // Here
});
return (
<Navbar ></Navbar>);
};
export default RedichanNav;
</code></pre>
<p>Then I got an error.</p>
<pre><code> 20:5 error Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the `void` operator
@typescript-eslint/no-floating-promises
</code></pre>
<p>Then I changed the code like this.</p>
<pre><code> useEffect(async () => {
const fetchEnBoards = async () => {
const response = await fetch('/api/en-boards');
const enBoardsJson = await response.json() as EnBoards;
setEnBoards(enBoardsJson);
};
await fetchEnBoards();
});
</code></pre>
<p>Then I got another error.</p>
<pre><code> 14:13 error Effect callbacks are synchronous to prevent race conditions. Put the async function inside:
useEffect(() => {
async function fetchData() {
// You can await here
const response = await MyAPI.getData(someId);
// ...
}
fetchData();
}, [someId]); // Or [] if effect doesn't need props or state
Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching react-hooks/exhaustive-deps
</code></pre>
<p>My code is almost the same as <a href="https://en.reactjs.org/docs/hooks-faq.html#performance-optimizations" rel="nofollow noreferrer">FAQ</a> and <a href="https://codesandbox.io/s/jvvkoo8pq3" rel="nofollow noreferrer">small demo</a> and <a href="https://www.robinwieruch.de/react-hooks-fetch-data/" rel="nofollow noreferrer">this article</a>.</p>
<p>My .eslintrc.js</p>
<pre><code>module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
'plugin:react/recommended',
'airbnb',
'airbnb/hooks',
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/recommended-requiring-type-checking',
'prettier',
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 12,
sourceType: 'module',
tsconfigRootDir: __dirname,
project: ['./tsconfig.json'],
},
plugins: [
'react',
'@typescript-eslint',
],
"ignorePatterns": [
".eslintrc.js"
],
rules: {
'semi': ['error', 'always'],
'no-use-before-define': "off",
"@typescript-eslint/no-use-before-define": "off",
'import/prefer-default-export': "off",
'import/extensions': [
'error',
{
js: 'never',
jsx: 'never',
ts: 'never',
tsx: 'never',
},
],
'react/jsx-filename-extension': [
'error',
{
extensions: ['.jsx', '.tsx'],
},
],
'react/react-in-jsx-scope': 'off',
'no-void': [
'error',
{
allowAsStatement: true,
},
],
"react/function-component-definition": [
2,
{
"namedComponents": "arrow-function"
}
]
},
settings: {
'import/resolver': {
node: {
paths: ['src'],
extensions: ['.js', '.jsx', '.ts', '.tsx']
},
},
},
};
</code></pre>
<h2>Enmironment</h2>
<ul>
<li>MacOS 12.5</li>
<li>Node.js 18.7.0</li>
<li>TypeScript 4.8.4</li>
<li>React 18.2.0</li>
<li>React-Bootstrap 2.5.0</li>
<li>ESLint 8.25.0</li>
<li>@typescript-eslint/eslint-plugin 5.39.0</li>
<li>eslint-plugin-react-hooks 4.6.0</li>
</ul>
<p>Thank you to read. Can anyone solve this?</p>
| [
{
"answer_id": 74169072,
"author": "Davi Oliveira",
"author_id": 19464177,
"author_profile": "https://Stackoverflow.com/users/19464177",
"pm_score": 0,
"selected": false,
"text": " useEffect(() => {\n const fetchEnBoards = async () => {\n try { //This\n const ... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8707371/"
] |
74,168,993 | <p>I have an old app that generates something like:</p>
<pre><code>USERLIST (
"jasonr"
"jameso"
"tommyx"
)
ROLELIST (
"op"
"admin"
"ro"
)
</code></pre>
<p>I need some form of regex that changes ONLY the <code>USERLIST</code> section to <code>USERLIST("jasonr", "jameso", "tommyx")</code> and the rest of the text remain intact:</p>
<pre><code>USERLIST("jasonr", "jameso", "tommyx")
ROLELIST (
"op"
"admin"
"ro"
)
</code></pre>
<p>In addition to the multiline issue, I don't know how to handle the replacement in only part of the string. I've tried perl (<code>-0pe</code>) and sed, can't find a solution. I don't want to write an app to do this, surely there is a way...</p>
| [
{
"answer_id": 74169275,
"author": "zdim",
"author_id": 4653379,
"author_profile": "https://Stackoverflow.com/users/4653379",
"pm_score": 4,
"selected": true,
"text": "perl -0777 -wpe'\n s{USERLIST\\s*\\(\\K ([^)]+) }{ join \", \", $1 =~ /(\"[^\"]+\")/g }ex' file\n"
},
{
"answ... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9911256/"
] |
74,168,995 | <p>I was trying to create a multi-control marquee built with vanilla JavaScript - for my website, so I made this marquee-like slider which is in its early stages.</p>
<p>It is basically a marquee which I made to be controlled using the <strong>mousewheel.</strong></p>
<p>Now the issue is that, while it seems to work as intended, I wanted it to be infinite, that is, allowing the user to continue scrolling instead of stopping at the left side or the right side.</p>
<p>How do I convert this to an infinite scroll effect?</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 categories = document.querySelector('div.categories')
const inner_categories = document.querySelector('div.inner_categories')
categories.addEventListener("mousewheel", function(e) {
if (e.deltaY > 0) {
this.scrollLeft += 100;
} else {
this.scrollLeft -= 100;
}
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Yu Gothic UI';
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100vh;
background-color: #8a5bcb;
}
div.categories {
border: 1px solid #000;
display: flex;
align-items: center;
background-color: #30b090;
overflow: hidden;
height: 40px;
width: 50vw;
position: relative;
}
div.inner_categories {
display: flex;
white-space: nowrap;
grid-column-gap: 10px;
position: absolute;
top: 50%;
transform: translateY(-50%);
left: 0;
right: 0;
width: 100%;
}
div.category {
font-size: 12px;
background-color: #E0E0E0;
padding-top: 2px;
padding-bottom: 2px;
padding-left: 5px;
padding-right: 5px;
border-radius: 5px;
}
div.category:hover {
cursor: pointer;
}
a {
text-decoration: none;
color: #111;
font-weight: 600;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- ========== begin ========== MARQUEE TABS ========== begin ========== -->
<div class="categories">
<div class="inner_categories">
<!-- ========== begin ========== CATEGORY TABS ========== begin ========== -->
<div class="category">
<a href="https://google.com">Google</a>
</div>
<div class="category">
<a href="https://yahoo.com">Yahoo</a>
</div>
<div class="category">
<a href="https://bing.com">Bing</a>
</div>
<div class="category">
<a href="https://facebook.com">Facebook</a>
</div>
<div class="category">
<a href="https://instagram.com">Instagram</a>
</div>
<div class="category">
<a href="https://twitter.com">Twitter</a>
</div>
<div class="category">
<a href="https://tiktok.com">TikTok</a>
</div>
<div class="category">
<a href="https://linkedin.com">Linkedin</a>
</div>
<div class="category">
<a href="https://behance.net">Bēhance</a>
</div>
<div class="category">
<a href="https://indeed.com">Indeed</a>
</div>
<div class="category">
<a href="https://slot.ng">SLOT</a>
</div>
<div class="category">
<a href="https://pointekonline.com">Pointek online</a>
</div>
<div class="category">
<a href="https://gsmarena.com">GSM Arena</a>
</div>
<div class="category">
<a href="https://stackoverflow.com">StackOverflow</a>
</div>
<div class="category">
<a href="https://youtube.com">YouTube</a>
</div>
<div class="category">
<a href="https://dailymotion.com">Daily Motion</a>
</div>
<div class="category">
<a href="https://vimeo.com">Vimeo</a>
</div>
<div class="category">
<a href="https://tumblr.com">Tumblr</a>
</div>
<div class="category">
<a href="https://naijaterra.com">NaijaTerra</a>
</div>
<div class="category">
<a href="https://gtbank.com">GT bank</a>
</div>
<div class="category">
<a href="https://outlook.com">Outlook</a>
</div>
<!-- ========== end ========== CATEGORY TABS ========== end ========== -->
</div>
</div>
<!-- ========== end ========== MARQUEE TABS ========== end ========== --></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74169088,
"author": "NNL993",
"author_id": 17799125,
"author_profile": "https://Stackoverflow.com/users/17799125",
"pm_score": 0,
"selected": false,
"text": "mousewheel"
},
{
"answer_id": 74169204,
"author": "Arleigh Hix",
"author_id": 6127393,
"author_... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19258933/"
] |
74,168,999 | <p>I have a problem, I can't insert an icon in front of the text
this is how it should be:<a href="https://i.stack.imgur.com/9RjHM.png" rel="nofollow noreferrer">enter image description here</a>
(I add code on snippet) I am a beginner coder, so there may be mistakes and I just want to add a trading basket icon in front of the logo with text of the same color as the logo itself, I searched for a long time on the Internet and on other forums, but everything that was there did not help me or did not work</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>body {
margin: 0;
font-family: Helvetica, sans-serif;
background-color: #f4f4f4;
}
a {
color: #000;
}
/* header */
.header {
background-color: #fff;
box-shadow: 1px 1px 4px 0 rgba(0,0,0,.1);
position: fixed;
width: 100%;
z-index: 3;
}
.header ul {
margin: 0;
padding: 0;
list-style: none;
overflow: hidden;
background-color: #fff;
}
.header li a {
display: block;
padding: 20px 20px;
border-right: 1px solid #f4f4f4;
text-decoration: none;
}
.header li a:hover,
.header .menu-btn:hover {
color:green;
}
/* Big coder moment, да я гений просто зеленим залив без хекса */
.header .logo {
display: block;
float: left;
font-size: 2em;
padding: 10px 20px;
text-decoration: none;
color:green;
}
/* menu */
.header .menu {
clear: both;
max-height: 0;
transition: max-height .2s ease-out;
}
/* menu icon */
.header .menu-icon {
cursor: pointer;
display: inline-block;
float: right;
padding: 28px 20px;
position: relative;
user-select: none;
}
.header .menu-icon .navicon {
background: #333;
display: block;
height: 2px;
position: relative;
transition: background .2s ease-out;
width: 18px;
}
.header .menu-icon .navicon:before,
.header .menu-icon .navicon:after {
background: #333;
content: '';
display: block;
height: 100%;
position: absolute;
transition: all .2s ease-out;
width: 100%;
}
.header .menu-icon .navicon:before {
top: 5px;
}
.header .menu-icon .navicon:after {
top: -5px;
}
/* menu btn */
.header .menu-btn {
display: none;
}
.header .menu-btn:checked ~ .menu {
max-height: 240px;
}
.header .menu-btn:checked ~ .menu-icon .navicon {
background: transparent;
}
.header .menu-btn:checked ~ .menu-icon .navicon:before {
transform: rotate(-45deg);
}
.header .menu-btn:checked ~ .menu-icon .navicon:after {
transform: rotate(45deg);
}
.header .menu-btn:checked ~ .menu-icon:not(.steps) .navicon:before,
.header .menu-btn:checked ~ .menu-icon:not(.steps) .navicon:after {
top: 0;
}
/* 48em = 768px */
@media (min-width: 48em) {
.header li {
float: left;
}
.header li a {
padding: 20px 30px;
}
.header .menu {
clear: none;
float: center;
max-height: none;
}
.header .menu-icon {
display: none;
}
}
logo:before {
content:url(images/quotemarks.png);
}
</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<header class="header">
<a href="" class="logo">Fresh market</a>
<input class="menu-btn" type="checkbox" id="menu-btn" />
<link rel="stylesheet" href="style.css">
<label class="menu-icon" for="menu-btn"><span class="navicon"></span></label>
<ul class="menu">
<li><a href="#work">Home</a></li>
<li><a href="#about">Shop</a></li>
<li><a href="#careers">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</header>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shop</title>
</head>
<body>
</body>
</html></code></pre>
</div>
</div>
thanks in advance :)
<a href="https://i.stack.imgur.com/BFfv5.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>some wrong :(</p>
| [
{
"answer_id": 74169088,
"author": "NNL993",
"author_id": 17799125,
"author_profile": "https://Stackoverflow.com/users/17799125",
"pm_score": 0,
"selected": false,
"text": "mousewheel"
},
{
"answer_id": 74169204,
"author": "Arleigh Hix",
"author_id": 6127393,
"author_... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74168999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19214467/"
] |
74,169,003 | <p>I created a sample program for 3 data points however, I have many data points and need more efficient code to run. The logic is I am comparing every Pi with its next P(i+1) and post comparing all the differences, I am selecting the max value and taking its relevant BSPi & SSPi.
additional condition is if P[i] is greater than p[i+1]; it should be greater than 50.</p>
<pre><code>sp1=100
sp2=150
sp3=200
sp4=250
p1=90
p2=40
p3=120
p4=150
if p1-p2>=0:
d1=p1-p2-50
bsp1=sp2
ssp1=sp1
else:
d1=p2-p1
bsp1=sp1
ssp1=sp2
if p2-p3>=0:
d2=p2-p3-50
bsp2=sp3
ssp2=sp2
else:
d2=p3-p2
bsp2=sp2
ssp2=sp3
if p3-p4>=0:
d3=p3-p4-50
bsp3=sp4
ssp3=sp3
else:
d3=p4-p3
bsp3=sp3
ssp3=sp3
data = {'d1': d1,'d2': d2, 'd3': d3,}
max_data=max(data, key=data.get)
if max_data=='d1':
bsp=bsp1
ssp=ssp1
elif max_data=='d2':
bsp=bsp2
ssp=ssp2
else:
bsp=bsp3
ssp=ssp3
print(bsp)
print(ssp)
</code></pre>
| [
{
"answer_id": 74169064,
"author": "Khoi Nguyen",
"author_id": 18489845,
"author_profile": "https://Stackoverflow.com/users/18489845",
"pm_score": 2,
"selected": true,
"text": "sp = [sp1, ... , spn]"
},
{
"answer_id": 74169604,
"author": "Cobra",
"author_id": 17580381,
... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74169003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20195125/"
] |
74,169,044 | <p>I have this shell code which is suppose to open a MessageBox. It works when testing it with <a href="https://github.com/NytroRST/ShellcodeCompiler" rel="nofollow noreferrer">https://github.com/NytroRST/ShellcodeCompiler</a>, however when I create a new console application using c and try to compile this</p>
<pre><code>#include <stdio.h>
#include <Windows.h>
unsigned char rc[] = "\x31\xC3\x89\x64\xE2\x80\xB9\x41\x30\xE2\x80\xB9\x40\x0C\xE2\x80\xB9\x70\x14\xC2\xAD\xE2\x80\x93\xC2\xAD\xE2\x80\xB9\x58\x10\xE2\x80\xB9\x53\x3C\x01\xC3\x9A\xE2\x80\xB9\x52\x78\x01\xC3\x9A\xE2\x80\xB9\x72\x20\x01\xC3\x9E\x31\xC3\x89\x41\xC2\xAD\x01\xC3\x98\xC2\x81\x38\x47\x65\x74\x50\x75\xC3\xB4\xC2\x81\x78\x04\x72\x6F\x63\x41\x75\xC3\xAB\xC2\x81\x78\x08\x64\x64\x72\x65\x75\xC3\xA2\xE2\x80\xB9\x72\x24\x01\xC3\x9E\x66\xE2\x80\xB9\x0C\x4E\x49\xE2\x80\xB9\x72\x1C\x01\xC3\x9E\xE2\x80\xB9\x14\xC5\xBD\x01\xC3\x9A\x31\xC3\x89\x53\x52\x51\x68\x61\x72\x79\x41\x68\x4C\x69\x62\x72\x68\x4C\x6F\x61\x64\x54\x53\xC3\xBF\xC3\x92\x92\xC3\x84\x0C\x59\x50\x31\xC3\x80\x66\xC2\xB8\x6C\x6C\x50\x68\x33\x32\x2E\x64\x68\x75\x73\x65\x72\x54\xC3\xBF\x54\x24\x10\xC6\x92\xC3\x84\x0C\x50\x31\xC3\x80\xC2\xB8\x6F\x78\x41\x23\x50\xC6\x92\x6C\x24\x03\x23\x68\x61\x67\x65\x42\x68\x4D\x65\x73\x73\x54\xC3\xBF\x74\x24\x10\xC3\xBF\x54\x24\x1C\xC6\x92\xC3\x84\x0C\x50\x31\xC3\x80\xC2\xB8\x65\x73\x73\x23\x50\xC6\x92\x6C\x24\x03\x23\x68\x50\x72\x6F\x63\x68\x45\x78\x69\x74\x54\xC3\xBF\x74\x24\x20\xC3\xBF\x54\x24\x20\xC6\x92\xC3\x84\x0C\x50\x31\xC3\x80\xC2\xB8\x59\x6F\x75\x23\x50\xC6\x92\x6C\x24\x03\x23\x68\x41\x72\x65\x20\x68\x48\x6F\x77\x20\x68\x48\x65\x79\x20\x54\x31\xC3\x80\x50\x68\x54\x65\x73\x74\x54\x31\xC3\x80\x50\xC3\xBF\x74\x24\x04\xC3\xBF\x74\x24\x14\x31\xC3\x80\x50\xC3\xBF\x54\x24\x34\x92\xC3\x84\x20\x31\xC3\x80\x50\xC3\xBF\x54\x24\x04\x6e";
int main() {
(*(void(*)()) rc)();
}
</code></pre>
<p>It always throws an Access Violation Exception after running it, I can get rid of this exception if I change the memory protections at the location of the shell codes injection. But yet it still does not display the MessageBox. I am certain the shell code works because the link above has a program that tests the shellcode and it works flawlessly. Only difference between their exploitation approach is that they are using c++ to do it and im using c.</p>
| [
{
"answer_id": 74169074,
"author": "thedemons",
"author_id": 13253010,
"author_profile": "https://Stackoverflow.com/users/13253010",
"pm_score": 2,
"selected": false,
"text": "rc"
},
{
"answer_id": 74170790,
"author": "JohnySiuu",
"author_id": 20096208,
"author_profil... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74169044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20297009/"
] |
74,169,059 | <p>I have a nested dictionary with the structure <code>{ "1" : [{"a" : ["p", "q"]}, "b", "c", {"d" : ["h", "w"]}] }</code>. Here is the <a href="https://github.com/santoshlinkha/prob_and_stat/blob/main/breakdown.js" rel="nofollow noreferrer">link to the exact data</a>. The depth can go up to any length, but the dept is finite. I am trying to create a nested list (of checkboxes) with the following code.</p>
<pre><code>
import React from "react";
class TagTree extends React.Component{
render(){
return(
<React.Fragment>
<ul>
{
this.props.tag.map( (t) =>
<li>
{ (typeof(t) === "object")? Object.keys(t) : t }
</li>
)
}
</ul>
</React.Fragment>
)
}
}
class TagApp extends React.Component{
render(){
return(
<div>
<TagTree tag={this.props.tagList} />
</div>
)
}
}
export default TagApp;
</code></pre>
<p>Here, the input dictionary is passed as <code>this.props.tagList</code>. I have two problems.</p>
<ol>
<li>If I recursively create <code>TagTree</code> at the following line</li>
</ol>
<pre><code>
<li>
{ (typeof(t) === "object")? <TagTree tag={t} /> : t }
</li>
</code></pre>
<p>I get an error</p>
<ol start="2">
<li>I need to display the key before displaying it's contents.</li>
</ol>
<p>My thanks for your help. The error is as follows.</p>
<pre><code>Unchecked runtime.lastError: The message port closed before a response was received.
localhost/:1 Unchecked runtime.lastError: The message port closed before a response was received.
localhost/:1 Unchecked runtime.lastError: The message port closed before a response was received.
localhost/:1 Unchecked runtime.lastError: The message port closed before a response was received.
react-jsx-dev-runtime.development.js:87 Warning: Each child in a list should have a unique "key" prop.
Check the render method of `TagTree`. See https://reactjs.org/link/warning-keys for more information.
at li
at TagTree (http://localhost:3000/static/js/bundle.js:1301:1)
at div
at TagApp (http://localhost:3000/static/js/bundle.js:1330:1)
at div
at div
at McqApp (http://localhost:3000/static/js/bundle.js:952:5)
at App (http://localhost:3000/static/js/bundle.js:32:1)
printWarning @ react-jsx-dev-runtime.development.js:87
error @ react-jsx-dev-runtime.development.js:61
validateExplicitKey @ react-jsx-dev-runtime.development.js:1078
validateChildKeys @ react-jsx-dev-runtime.development.js:1105
jsxWithValidation @ react-jsx-dev-runtime.development.js:1276
render @ tag.jsx:7
finishClassComponent @ react-dom.development.js:19752
updateClassComponent @ react-dom.development.js:19698
beginWork @ react-dom.development.js:21611
beginWork$1 @ react-dom.development.js:27426
performUnitOfWork @ react-dom.development.js:26557
workLoopSync @ react-dom.development.js:26466
renderRootSync @ react-dom.development.js:26434
performConcurrentWorkOnRoot @ react-dom.development.js:25738
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
6tag.jsx:8 Uncaught TypeError: this.props.tag.map is not a function
at TagTree.render (tag.jsx:8:1)
at finishClassComponent (react-dom.development.js:19752:1)
at updateClassComponent (react-dom.development.js:19698:1)
at beginWork (react-dom.development.js:21611:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at beginWork$1 (react-dom.development.js:27451:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)
render @ tag.jsx:8
finishClassComponent @ react-dom.development.js:19752
updateClassComponent @ react-dom.development.js:19698
beginWork @ react-dom.development.js:21611
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
beginWork$1 @ react-dom.development.js:27451
performUnitOfWork @ react-dom.development.js:26557
workLoopSync @ react-dom.development.js:26466
renderRootSync @ react-dom.development.js:26434
performConcurrentWorkOnRoot @ react-dom.development.js:25738
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
6tag.jsx:8 Uncaught TypeError: this.props.tag.map is not a function
at TagTree.render (tag.jsx:8:1)
at finishClassComponent (react-dom.development.js:19752:1)
at updateClassComponent (react-dom.development.js:19698:1)
at beginWork (react-dom.development.js:21611:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at beginWork$1 (react-dom.development.js:27451:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)
render @ tag.jsx:8
finishClassComponent @ react-dom.development.js:19752
updateClassComponent @ react-dom.development.js:19698
beginWork @ react-dom.development.js:21611
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
beginWork$1 @ react-dom.development.js:27451
performUnitOfWork @ react-dom.development.js:26557
workLoopSync @ react-dom.development.js:26466
renderRootSync @ react-dom.development.js:26434
recoverFromConcurrentError @ react-dom.development.js:25850
performConcurrentWorkOnRoot @ react-dom.development.js:25750
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
6react-dom.development.js:18687 The above error occurred in the <TagTree> component:
at TagTree (http://localhost:3000/static/js/bundle.js:1301:1)
at li
at ul
at TagTree (http://localhost:3000/static/js/bundle.js:1301:1)
at div
at TagApp (http://localhost:3000/static/js/bundle.js:1330:1)
at div
at div
at McqApp (http://localhost:3000/static/js/bundle.js:952:5)
at App (http://localhost:3000/static/js/bundle.js:32:1)
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
logCapturedError @ react-dom.development.js:18687
update.callback @ react-dom.development.js:18720
callCallback @ react-dom.development.js:13923
commitUpdateQueue @ react-dom.development.js:13944
commitLayoutEffectOnFiber @ react-dom.development.js:23391
commitLayoutMountEffects_complete @ react-dom.development.js:24688
commitLayoutEffects_begin @ react-dom.development.js:24674
commitLayoutEffects @ react-dom.development.js:24612
commitRootImpl @ react-dom.development.js:26823
commitRoot @ react-dom.development.js:26682
finishConcurrentRender @ react-dom.development.js:25892
performConcurrentWorkOnRoot @ react-dom.development.js:25809
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
tag.jsx:8 Uncaught TypeError: this.props.tag.map is not a function
at TagTree.render (tag.jsx:8:1)
at finishClassComponent (react-dom.development.js:19752:1)
at updateClassComponent (react-dom.development.js:19698:1)
at beginWork (react-dom.development.js:21611:1)
at beginWork$1 (react-dom.development.js:27426:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)
at renderRootSync (react-dom.development.js:26434:1)
at recoverFromConcurrentError (react-dom.development.js:25850:1)
at performConcurrentWorkOnRoot (react-dom.development.js:25750:1)
</code></pre>
| [
{
"answer_id": 74169074,
"author": "thedemons",
"author_id": 13253010,
"author_profile": "https://Stackoverflow.com/users/13253010",
"pm_score": 2,
"selected": false,
"text": "rc"
},
{
"answer_id": 74170790,
"author": "JohnySiuu",
"author_id": 20096208,
"author_profil... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74169059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/447023/"
] |
74,169,075 | <p>Current Code:</p>
<pre class="lang-py prettyprint-override"><code>weight_lbs=float(input("How much do you weigh(lbs)? : " ))
weight_kg=float(input("My weight is " + weight_lbs/2.205 + "kg"))
print(weight_kg)
</code></pre>
<p>Error Message:</p>
<pre><code>Traceback (most recent call last):
File "<string>", line 9, in <module>
TypeError: can only concatenate str (not "float") to str
</code></pre>
| [
{
"answer_id": 74169108,
"author": "sourin",
"author_id": 14912756,
"author_profile": "https://Stackoverflow.com/users/14912756",
"pm_score": 1,
"selected": false,
"text": "weight_lbs=float(input(\"How much do you weigh(lbs)? : \" ))\nweight_kg=float(input(\"My weight is \" + str(weight_... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74169075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20312644/"
] |
74,169,093 | <p>My project structure:</p>
<pre><code>MyProj
app
benchmarks
Investigate.hs
src
test
Example1.hs -- defines module Example1
</code></pre>
<p>My current <code>package.yaml</code> (simplified):</p>
<pre><code>name: proj
dependencies:
- base >= 4.7 && < 5
library:
source-dirs: src
executables:
proj-exe:
main: Main.hs
source-dirs: app
dependencies: proj
tests:
proj-test:
main: Spec.hs
source-dirs: test
dependencies: proj
benchmarks:
investigate:
main: benchmarks/Investigate.hs
dependencies: proj
</code></pre>
<p>I want to import a module (say <code>Example1</code> that lives under <em>test</em>, and use it in <code>Investigate.hs</code> under <em>benchmarks</em>. I am using <code>stack</code>, so how exactly do I configure my <code>package.yaml</code>?</p>
| [
{
"answer_id": 74175735,
"author": "Ben",
"author_id": 450128,
"author_profile": "https://Stackoverflow.com/users/450128",
"pm_score": 1,
"selected": false,
"text": "dependencies"
},
{
"answer_id": 74179623,
"author": "lsmor",
"author_id": 9271266,
"author_profile": "... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74169093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16838330/"
] |
74,169,121 | <p>I am using CKEditor to enter text and saving into database. When I retrieve it description, it also shows the html p tags which i dont want. How can I save it into database such that the p tags don't show but tags like are still applied. Essentially I want to save it as html itself and not text. Is there a way I can do that? Currently I am using TextField to store the description.</p>
| [
{
"answer_id": 74169161,
"author": "saharsh solanki",
"author_id": 13712372,
"author_profile": "https://Stackoverflow.com/users/13712372",
"pm_score": 0,
"selected": false,
"text": "def save(instance):\n\n instance.html = instance.html.replace(\"<p>\",\"<div>\").replace(\"</p>\",\"</d... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74169121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20197985/"
] |
74,169,127 | <p><strong>Question:</strong> <em>Given a string 's', generate all subsequences of the string using recursion. The output should be in a certain manner (all the subsequences of 'a' should be printed first, then subsequences of 'b' and so on and so forth).</em></p>
<p>The sample output for a given string 's' = abcd</p>
<pre><code>a
ab
abc
abcd
abd
ac
acd
ad
b
bc
bcd
bd
c
cd
d
</code></pre>
<p>I wasn't able to solve the problem in the first go but I took some help and then was able to solve it. Below is the code for it but what I am not able to get is that why we are passing <strong>i+1</strong> in the recursion call and why not <strong>index+1</strong>? I tried doing it and obviously it was giving wrong output. I thought it is same as passing <strong>i+1</strong> to it because either way the we are incrementing the <strong>index</strong>, right?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function allSubseq(new_str, str, index) {
if (new_str.length !== 0) {
console.log(new_str.join(""));
}
if (index === str.length) {
return;
}
for (let i = index; i < str.length; i++) {
new_str.push(str[i]);
allSubseq(new_str, str, i + 1);
new_str.pop(); // Backtracking step
}
}
let str = "abcd";
new_str = [];
allSubseq(new_str, str, 0);</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74169161,
"author": "saharsh solanki",
"author_id": 13712372,
"author_profile": "https://Stackoverflow.com/users/13712372",
"pm_score": 0,
"selected": false,
"text": "def save(instance):\n\n instance.html = instance.html.replace(\"<p>\",\"<div>\").replace(\"</p>\",\"</d... | 2022/10/23 | [
"https://Stackoverflow.com/questions/74169127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9600505/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.