qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,254,073 | <p>I try to install metaploit, but every time I get errors and I can't get it to work.</p>
<p>During installation I get the following error code:</p>
<pre><code>pip install --upgrade streamlit
(Deleted a lot of irrelevant information)
Building wheels for collected packages: pyarrow
Building wheel for pyarrow (pyproject.toml) ... error
error: subprocess-exited-with-error
× Building wheel for pyarrow (pyproject.toml) did not run successfully.
│ exit code: 1
╰─> [291 lines of output]
ModuleNotFoundError: No module named 'cmake'
error: command 'D:\\Eind Project Programming Final\\venv\\Scripts\\cmake.exe' failed with exit code 1
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for pyarrow
Failed to build pyarrow
ERROR: Could not build wheels for pyarrow, which is required to install pyproject.toml-based projects
</code></pre>
<p><strong>I have already tried the following:</strong></p>
<ul>
<li>Re-install Pycharm and Python and install the 64 bit version. (Running no other python or program)</li>
<li>Tried different versions of the packages.</li>
<li>Deleted & Re-installed packages.</li>
<li>Finding a solution on google.</li>
<li>(Latest python, pycharm version and all the packages I updated to the lastest versions.)</li>
</ul>
<p><strong>Tried these commands:</strong></p>
<pre><code>pip uninstall streamlit
pip uninstall wheel
pip uninstall setuptools
pip uninstall pip
pip install --upgrade streamlit
pip install --upgrade matplotlib
pip install --upgrade setuptools
pip install --upgrade wheel
pip install --upgrade pyarrow
pip install --upgrade cmake
</code></pre>
| [
{
"answer_id": 74254185,
"author": "Kutay Kılıç",
"author_id": 19274851,
"author_profile": "https://Stackoverflow.com/users/19274851",
"pm_score": 0,
"selected": false,
"text": "No module named 'cmake'\n"
},
{
"answer_id": 74295851,
"author": "M.O.",
"author_id": 11612918... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20205827/"
] |
74,254,074 | <p>I have the following test code:</p>
<pre class="lang-py prettyprint-override"><code>from os import path
from PySide6.QtCore import QObject, QMetaObject
from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QApplication
class MyWin(QObject):
def __init__(self, parent=None):
super().__init__(parent)
self.ui = QUiLoader().load(path.join(path.dirname(__file__), "MainWindow.ui"))
self.ui.pushButton.clicked.connect(self.on_pushButton_clicked)
def show(self):
self.ui.show()
def on_pushButton_clicked(self):
print("button pushed!")
app = QApplication([])
win = MyWin()
win.show()
app.exec()
</code></pre>
<p>with its associated <code>MainWindow.ui</code>:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QPushButton" name="pushButton">
<property name="text">
<string>PushButton</string>
</property>
</widget>
</item>
<item>
<widget class="QTableView" name="tableView"/>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>19</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
</code></pre>
<p>... which works as expected.</p>
<p>Question is: how do I replace the line:</p>
<pre><code> self.ui.pushButton.clicked.connect(self.on_pushButton_clicked)
</code></pre>
<p>with an equivalent using <code>QMetaObject.connectSlotsByName(???)</code> ?</p>
<p>Problem here is PySide6 <code>QUiLoader</code> is incapable to add widgets as children of <code>self</code> (as PyQt6 <code>uic.loadUi(filename, self)</code> can do) and thus I'm forced to put UI in a separate variable (<code>self.ui</code>) while slots are defined in "parent" <code>MyWin</code>.</p>
<p>How can I circumvent limitation?</p>
<p>Reason why I ask is my real program has zillions of signals/slots and <code>connect()</code>'ing them manually is a real PITA (and error-prone)</p>
<p><strong>UPDATE:</strong>
Following advice I modified <code>MyWin</code> to inherit from <code>QWidget</code>, but enabling <code>self.ui.setParent(self)</code> is enough to prevent display of UI.</p>
<pre class="lang-py prettyprint-override"><code>from os import path
from PySide6.QtCore import QMetaObject
from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QApplication, QWidget
class MyWin(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.ui = QUiLoader().load(path.join(path.dirname(__file__), "MainWindow.ui"))
self.ui.pushButton.clicked.connect(self.on_pushButton_clicked)
self.ui.setParent(self)
# QMetaObject.connectSlotsByName(self)
def myshow(self):
self.ui.show()
def on_pushButton_clicked(self):
print("button pushed!")
app = QApplication([])
win = MyWin()
win.myshow()
app.exec()
</code></pre>
<p>I also see some strange errors:</p>
<pre><code>mcon@ikea:~/projects/pyside6-test$ venv/bin/python t.py
qt.pysideplugin: Environment variable PYSIDE_DESIGNER_PLUGINS is not set, bailing out.
qt.pysideplugin: No instance of QPyDesignerCustomWidgetCollection was found.
Qt WebEngine seems to be initialized from a plugin. Please set Qt::AA_ShareOpenGLContexts using QCoreApplication::setAttribute and QSGRendererInterface::OpenGLRhi using QQuickWindow::setGraphicsApi before constructing QGuiApplication.
^C^C^C^C
Terminated
</code></pre>
<p>I need to kill process from another terminal, normal Ctrl-C is ignored.</p>
<p><strong>UPDATE2</strong>:
I further updated code following @ekhumoro advice:</p>
<pre class="lang-py prettyprint-override"><code>from os import path
from PySide6.QtCore import QMetaObject
from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QApplication, QWidget, QMainWindow
class UiLoader(QUiLoader):
_baseinstance = None
def createWidget(self, classname, parent=None, name=''):
if parent is None and self._baseinstance is not None:
widget = self._baseinstance
else:
widget = super(UiLoader, self).createWidget(classname, parent, name)
if self._baseinstance is not None:
setattr(self._baseinstance, name, widget)
return widget
def loadUi(self, uifile, baseinstance=None):
self._baseinstance = baseinstance
widget = self.load(uifile)
QMetaObject.connectSlotsByName(widget)
return widget
class MyWin(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
UiLoader().loadUi(path.join(path.dirname(__file__), "MainWindow.ui"), self)
# self.pushButton.clicked.connect(self.on_pushButton_clicked)
QMetaObject.connectSlotsByName(self)
def on_pushButton_clicked(self):
print("button pushed!")
app = QApplication([])
win = MyWin()
win.show()
app.exec()
</code></pre>
<p>This doesn't work either: it shows GUI, but button click is not connected (unless I explicitly do it uncommenting the line).</p>
<p>What am I doing wrong?</p>
| [
{
"answer_id": 74254185,
"author": "Kutay Kılıç",
"author_id": 19274851,
"author_profile": "https://Stackoverflow.com/users/19274851",
"pm_score": 0,
"selected": false,
"text": "No module named 'cmake'\n"
},
{
"answer_id": 74295851,
"author": "M.O.",
"author_id": 11612918... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1714490/"
] |
74,254,081 | <p>So I have a table that has stats for workouts in that table there two fields Feet and Inches. I work out the longest jump by going to linq like this.</p>
<pre><code>var playerBroadJumpHistory = await api.GetAllWorkOutsByPlayerId(playerId);
var maxBroadJumpFeet = (from u in playerBroadJumpHistory
where u.PlayerId == playerId
orderby u.BroadJumpFeet descending
select u).Take(1);
</code></pre>
<p>But I also want to get the value of inches which is u.BroadJumpInches how would I do that in the above example but retain both elements?. I am obviously doing this to get the max distance the person jumped over there scores but I need both columns of data so can display them.</p>
<p>Could I just create a new object using the select ?</p>
| [
{
"answer_id": 74254108,
"author": "c-sharp-and-swiftui-devni",
"author_id": 651887,
"author_profile": "https://Stackoverflow.com/users/651887",
"pm_score": 0,
"selected": false,
"text": "var maxBroadJumpFeet = (from u in playerBroadJumpHistory\n where u.PlayerId =... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/651887/"
] |
74,254,091 | <p>The app, I am building with nodeJS expressJS is for connecting to a sqlserver database and retrieving data. Am trying to make the code as modular and
reusable as posssible. So different files for routing and controller. The error I am now facing is-</p>
<pre><code>throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a Object
</code></pre>
<p>For ease of understanding of the imports, my project structure is as such:</p>
<pre><code>controller
|-- controller.js
db
|-- db.js
query
|-- queries.json
routes
|-- route.js
package.json
server.js
</code></pre>
<p>My main server.js file is</p>
<pre><code>const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const fs = require('fs')
const path = require('path')
const morgan = require('morgan')
const router=require('./routes/route');
const app = express()
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
app.use(morgan('dev'));
const port = 3200
app.listen(process.env.PORT || port , (err) => {
if(err)
{
console.log('Unable to start the server!');
}
else
console.log('NodeExpress Data API started running on : ' + port);
})
</code></pre>
<p>the controller file is</p>
<pre><code>const express=require('express')
const { sql, poolPromise } = require('../db/db')
const fs = require('fs');
class MainController
{
async getAllData(req, resp)
{
try
{
const pool = await poolPromise
const result = await pool.request()
.query("select * from players");
resp.json(result.recordset)
}
catch (error)
{
resp.status(500)
resp.send(error.message)
}
}
}
const controller=new MainController();
module.exports=controller;
</code></pre>
<p>and the route file is</p>
<pre><code>const express = require('express');
const controller = require('../controller/controller')
const router = express.Router();
router.get('/getAllData', controller.getAllData);
</code></pre>
<p>So when I insert this line
app.use('api/', router) in the server.js to wire all the modules together and make calls to api endpoint to get all data, I am getting that error mentioned.</p>
<p>What is it about, can anyone explain me in simple terms? Is the error being thrown from the controller file, since I am initializing a new instance of the controller type? Which line from which file is throwing this error? What is the code correction needed to remove this error?</p>
| [
{
"answer_id": 74263603,
"author": "Nabhag Motivaras",
"author_id": 15820509,
"author_profile": "https://Stackoverflow.com/users/15820509",
"pm_score": 1,
"selected": false,
"text": "router.get('/getAllData', controller.getAllData());"
},
{
"answer_id": 74457543,
"author": "A... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9193561/"
] |
74,254,104 | <pre><code>public class TimeAList {
public static void timeAListConstruction() {
private void AListDataReturnation(int numbers) {
</code></pre>
<p>Returns a <code>java: illegal start of expression</code> error within the bottommost method.</p>
| [
{
"answer_id": 74263603,
"author": "Nabhag Motivaras",
"author_id": 15820509,
"author_profile": "https://Stackoverflow.com/users/15820509",
"pm_score": 1,
"selected": false,
"text": "router.get('/getAllData', controller.getAllData());"
},
{
"answer_id": 74457543,
"author": "A... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19564905/"
] |
74,254,123 | <p>I know that using Python's <strong>random.choices</strong> I can do this:</p>
<pre><code>import random
array_probabilities = [0.5 for _ in range(4)]
print(array_probabilities) # [0.5, 0.5, 0.5, 0.5]
a = [random.choices([0, 1], weights=[1 - probability, probability])[0] for probability in array_probabilities]
print(a) # [1, 1, 1, 0]
</code></pre>
<p><strong>How to make an numpy array of 0 and 1 based on a probability array?</strong></p>
<p>Using random.choices is fast, but I know numpy is even faster. I would like to know how to write the same code but using numpy. I'm just getting started with numpy and would appreciate your feedback.</p>
| [
{
"answer_id": 74254401,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "out = (np.random.random(size=len(array_probabilities)) > array_probabilities).astype(int)\n"
},
{
"answer_id... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15264145/"
] |
74,254,127 | <p>I Have a workbook that I am using to track inventory and purchasing. The initial sheet contains the "List" which identifies if something is in inventory or if it needs purchasing, there is a data validation for "Inventory" or "Purchase" in Column E. I want to populate another sheet within the same workbook, only rows that end with the "Purchase" value in column E.</p>
<p>For example:
In the sheet "List", if E2 is "Purchase", I want the sheet "Shopping" to populate with the values in List!A2:D2, I've tried a few combinations of If formulas and Arrayformula but haven't returned anything but Errors</p>
<p>I have tried in the shopping sheet, cell A2</p>
<pre><code>=IF(List!E2"Purchase",List!A2:D2,blank)
=IF(List!E2"Purchase",Arrayformula(List!A2:d2),blank)
</code></pre>
<p>I've done a few other variations that I can't remember the exact order on but you get the gist of the ways I've tried it.</p>
| [
{
"answer_id": 74254401,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "out = (np.random.random(size=len(array_probabilities)) > array_probabilities).astype(int)\n"
},
{
"answer_id... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20372379/"
] |
74,254,131 | <p>I have a dataframe (concerning prostate cancer survival) and one of the factor variables "stage" only has 4 observations for stage 3. I want to combine stage 3 with stage 2 before doing regression. Is there a function that will search through the stage data and if stage = 3, change this value to 2?</p>
<p>Many thanks!</p>
<p>I have tried:</p>
<pre><code>pro$stage[pro$stage==3] <- 2
</code></pre>
<p>but this doesnt seem to do the trick</p>
| [
{
"answer_id": 74254401,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "out = (np.random.random(size=len(array_probabilities)) > array_probabilities).astype(int)\n"
},
{
"answer_id... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20372423/"
] |
74,254,144 | <p>Good morning, currently I am stuck on trying to figure out how to detect a cycle in a undirected graph where the keys are strings.</p>
<p>my code so far:</p>
<pre><code>public boolean hascycle() {
DSHashMap<String> parent = new DSHashMap<>();
DSHashMap<String> visted = new DSHashMap<>();
LinkedList<String> q = new LinkedList<>();
for (String start : graph) {
q.add(start);
visted.put(start, "");
;
while (!q.isEmpty()) {
String v = q.poll();
for (String x : graph.get(v)) {
if (!visted.containsKey(x)) {
visted.put(x, "");
;
q.add(v);
parent.put(x, v);
} else if (!parent.get(x).equals(v))
return true;
}
}
}
return false;
}
</code></pre>
<p>My logic so far: if the key of parent does not equal to v, it must be a new neighbor and we should return true.</p>
<p>When I tried checking my code with this checker:</p>
<pre><code>private static void gradehascycles() {
System.out.println("\nGrading the cycles function");
DSGraph g = new DSGraph();
g.addEdge("a", "b");
g.addEdge("a", "e");
g.addEdge("c", "b");
g.addEdge("c", "d");
checkExpect(g.hascycle(), false, "Square graph", 1);
}
</code></pre>
<p>My code returned true even though it was supposed to be false. What is the logic behind checking if a graph has a cycle or not?</p>
| [
{
"answer_id": 74255561,
"author": "Vitaly Chura",
"author_id": 8587732,
"author_profile": "https://Stackoverflow.com/users/8587732",
"pm_score": 0,
"selected": false,
"text": "else if (!parent.get(v).equals(x))\n return true;\n }\n"
}
] | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20095770/"
] |
74,254,160 | <p>I’m trying to write a program that has while true: at the start and then at the end asks the user if they want to repeat.</p>
<pre><code>While True:
print(“I will list the prime numbers between 0 and N”)
N=input(“up to what number will I list the prime numbers?”)
print (“prime numbers between 0 and”,N,” are:”)
for no in range (2,N)
if no>1:
prime=True
for i in range (2, no):
if (no % i) == 0:
prime=False
break
if prime:
print(no)
print(“would you like to enter a new range?”)
response= input(“Enter yes or press enter key to exit”)
if response == yes:
True
</code></pre>
<p>But no matter what is entered it keeps repeating</p>
<p>I tried adding an
else:
break</p>
<p>But it would say break away out of the loop of
I’m not sure what to do</p>
| [
{
"answer_id": 74254188,
"author": "Anonymous User",
"author_id": 20372397,
"author_profile": "https://Stackoverflow.com/users/20372397",
"pm_score": -1,
"selected": false,
"text": "while run\n"
},
{
"answer_id": 74254354,
"author": "Samwise",
"author_id": 3799759,
"a... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20372383/"
] |
74,254,255 | <p>I have this type:</p>
<pre><code>type DropdownProps<T> = {
data: T[],
id: keyof T,
};
</code></pre>
<p>The problem is that if I now try to use <code>id</code> it will have the <code>any</code>. I need to make sure that <code>id</code> is either type <code>number</code> or <code>string</code>.</p>
<p>Basically, I want to pass an array of objects and one of the object's keys. That key should return a value of the type <code>string</code> or <code>number</code>.</p>
<p>I don't want to require the key to be called <code>id</code>, but if that's necessary to make it work it would be fine.</p>
| [
{
"answer_id": 74254277,
"author": "caTS",
"author_id": 18244921,
"author_profile": "https://Stackoverflow.com/users/18244921",
"pm_score": 2,
"selected": true,
"text": "type DropdownProps<T> = {\n data: T[],\n id: keyof T & (string | number),\n};\n"
},
{
"answer_id": 74254288,... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11177575/"
] |
74,254,260 | <p>I'm getting <code>AttributeError: 'list' object has no attribute 'sort_values'</code> in below code,</p>
<p>task.py:</p>
<pre><code>from __future__ import absolute_import,unicode_literals
from celery import shared_task
from time import sleep
import eda
import os
@shared_task
def aync_task(amz_columns_dict, download_path, file_name, data):
sleep(10)
eda_object = eda.eda(col_dict=amz_columns_dict)
save_path = download_path
name_of_file = file_name
file_path = os.path.join(save_path, name_of_file+".html")
eda_object.create_report(data=data, filename=file_path)
return 'task complete'
</code></pre>
<p>views.py :</p>
<pre><code>def eda_flow(request):
path = '/Unilever/satyajit/us_amz.csv'
mode = 'rb'
df = pd.read_csv("/home/satyajit/Desktop/opensource/data/us_amz.csv", low_memory=False)
df = df.head(100)
json_records = df.reset_index().to_json(orient ='records')
data = []
data = json.loads(json_records)
context = {'data': data, 'message': 'data loaded successfully.'}
if request.method == 'POST':
id_col = request.POST.get('id_col')
file_name = request.POST.get('file_name')
download_path = request.POST.get('download_path')
amz_columns_dict = {'id_col': id_col}
try:
if os.path.exists(download_path):
status = aync_task.delay(amz_columns_dict, download_path, file_name, data)
return render(request,'home/index.html', {'message': 'Save Complete'})
else:
return render(request,'home/index.html', {'message': 'download path is not exist'})
except Exception as e:
print('error is---->', e)
return render(request,'home/index.html', {'message': 'Error while generating EDA'})
return render(request, "home/tables-simple.html", context)
</code></pre>
<p>The error of this code on below as screenshot:</p>
<p><a href="https://i.stack.imgur.com/jtne0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jtne0.png" alt="enter image description here" /></a></p>
<p>I've also tried to search similar question here (<a href="https://stackoverflow.com/questions/57220128/attributeerror-list-object-has-no-attribute-sort-values">similar question</a>) but that does not helpful to me.</p>
<p>Any help would be much appreciated. thanks in advance.</p>
| [
{
"answer_id": 74254277,
"author": "caTS",
"author_id": 18244921,
"author_profile": "https://Stackoverflow.com/users/18244921",
"pm_score": 2,
"selected": true,
"text": "type DropdownProps<T> = {\n data: T[],\n id: keyof T & (string | number),\n};\n"
},
{
"answer_id": 74254288,... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19808286/"
] |
74,254,298 | <p>I have this web scraper program in python, but it prints both tennis players Felix and Alexander. I would like to only print the first available tennis player as a separate item and exclude all the ones after it, so what do I need change in the code to do this?</p>
<p>To note, I did this through Visual Studio 2022 and applied the program to use Microsoft Edge web browser.</p>
<pre><code>import requests
from bs4 import BeautifulSoup
response = requests.get("https://www.betexplorer.com/tennis/atp-singles/basel/auger-aliassime-felix-bublik-alexander/U5HIueTc/")
webpage = response.content
soup = BeautifulSoup(webpage, "html.parser")
for h2 in soup.find_all('h2'):
values = [data for data in h2.find_all('a')]
for value in values:
print(value.text.replace(" ","_"))
print()
</code></pre>
| [
{
"answer_id": 74254277,
"author": "caTS",
"author_id": 18244921,
"author_profile": "https://Stackoverflow.com/users/18244921",
"pm_score": 2,
"selected": true,
"text": "type DropdownProps<T> = {\n data: T[],\n id: keyof T & (string | number),\n};\n"
},
{
"answer_id": 74254288,... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14745788/"
] |
74,254,386 | <p><a href="https://i.stack.imgur.com/3jn5l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3jn5l.png" alt="list of text fields" /></a>.</p>
<p>I want my code to remove elements from list of text fields properly.
Each element has an X button to remove it's text field.
If I start removing elements from the bottom it works but <strong>it doesn't work for removing random elements</strong>
<strong>I want to use forEachIndexed for displaing the list</strong>
Please help me with solving this problem. I've been trying to do this for some time but every trial is unsuccessful.</p>
<p>This is a piece of code that I've managed to write but removing elements doesn't work properly</p>
<pre><code>val listOfWords = mutableStateListOf<String>()
@Composable
fun Main() {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "Words",
modifier = Modifier.padding(0.dp, 0.dp, 0.dp, 4.dp),
style = MaterialTheme.typography.h6
)
listOfWords.forEachIndexed { index, word ->
Input(word, 30, "Word", 1,
{newWord ->
listOfWords[index] = newWord
Log.d("text ",word)
},
{
listOfWords.removeAt(index)
}
)
}
IconButton(
onClick = {
listOfWords.add("")
}
) {
Icon(
imageVector = Icons.Filled.Add,
contentDescription = "Add"
)
}
}
}
@Composable
fun Input(
word: String,
maxChar: Int,
label: String,
maxLines: Int,
onEdit: (word: String) -> (Unit),
onRemove: () -> (Unit)
) {
var text by remember { mutableStateOf(word) }
Column(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp, 0.dp, 8.dp, 0.dp)
) {
OutlinedTextField(
value = text,
onValueChange = {
if (it.length <= maxChar) text = it
onEdit(text)
},
modifier = Modifier.fillMaxWidth(),
label = { Text(label) },
leadingIcon = {
Icon(Icons.Default.Edit, null)
},
trailingIcon = {
IconButton(onClick = {
onRemove()
}) {
Icon(
imageVector = Icons.Default.Clear,
contentDescription = "Back"
)
}
},
maxLines = maxLines
)
Text(
text = "${text.length} / $maxChar",
textAlign = TextAlign.End,
style = MaterialTheme.typography.caption,
modifier = Modifier
.fillMaxWidth()
.padding(end = 16.dp)
)
}
}
</code></pre>
| [
{
"answer_id": 74264882,
"author": "Arthur Kasparian",
"author_id": 19454251,
"author_profile": "https://Stackoverflow.com/users/19454251",
"pm_score": 1,
"selected": false,
"text": "listOfWords.forEachIndexed { index, word ->\n ... // rest of code\n {\n listOfWords.removeAt... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15600837/"
] |
74,254,389 | <p>I am trying to create a function which will take a number n as its parameter and returns the first n elements of a fibonacci sequence in a list.</p>
<p>But, I also want to include an optimal parameter 'start' (a pair of numbers, which specifies the first two elements of a generalised Fibonacci sequence.</p>
<p>Any ideas how to include the optional parameter in the code?</p>
<p>Thanks for help in an advance.</p>
<pre><code>def fibonacci(n: int, start: tuple[int, int] = (0, 1)) -> list[int]:
sequence = [0,1]
for i in range(3,n+1):
next_num = sequence[-1] + sequence[-2]
sequence.append(next_num)
return sequence
print(fibonacci(8))
</code></pre>
<p>Current output
<code>[0, 1, 1, 2, 3, 5, 8, 13]</code></p>
<hr />
<p>Desired input <code>fibonacci(6, start=(2, 2))</code></p>
<p>Desired output <code> [2, 2, 4, 6, 10, 16]</code></p>
<p>Curent output <code>[0, 1, 1, 2, 3, 5]</code></p>
| [
{
"answer_id": 74264882,
"author": "Arthur Kasparian",
"author_id": 19454251,
"author_profile": "https://Stackoverflow.com/users/19454251",
"pm_score": 1,
"selected": false,
"text": "listOfWords.forEachIndexed { index, word ->\n ... // rest of code\n {\n listOfWords.removeAt... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20243069/"
] |
74,254,449 | <p>I have large data file with some data as :</p>
<pre><code>01 01 00 2c 00 82 03 00 02 00 00 00 07 08 07 08
07 08 07 08 07 08 07 08 07 08 07 08 07 08 07 08
07 08 07 08 07 08 07 08 07 08 07 08 07 08 07 08
07 08 07 08 07 08 07 08 07 08 07 08 07 08 07 08
0f 08 08 08 0a 08 07 08 0f 08 08 08 08 08 08 08
08 08 08 08 08 07 08 07 0a 07 07 07 0f 07 08 07
08 07 08 07 08 07 08 07 08 07 08 07 0a 07 07 07
..
.....
</code></pre>
<p>I would like to delete every first n characters from every 6th row</p>
<p>I have found a command :</p>
<pre><code>sed 's/^.\{,n\}//' file
</code></pre>
<p>But this command deletes first n chars from each row, which I do not want to happen.</p>
<p>Could someone suggest the right command?</p>
| [
{
"answer_id": 74254509,
"author": "tripleee",
"author_id": 874188,
"author_profile": "https://Stackoverflow.com/users/874188",
"pm_score": 3,
"selected": true,
"text": "awk -v n=17 '(NR%6)==1 { print substr($0, n+1); next } 1' file\n"
},
{
"answer_id": 74255656,
"author": "D... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14726199/"
] |
74,254,483 | <p>I have a simple script that automates the command "Export Library" in Music. It does the following:</p>
<pre><code>tell application "System Events"
tell process "Music"
set libmenu to menu item "Library" of menu "File" of menu bar 1
click menu item "Export Library…" of menu of libmenu
tell window 1
click button "Save"
tell sheet 1 to click button "Replace"
end tell
end tell
end tell
</code></pre>
<p>(So basically it opens the menu and clicks the obvious buttons, saving me a few clicks). However, after upgrading to Ventura (macOS 13.0), this stopped working. The command <code>click button "Save"</code> is failing with:</p>
<pre><code>Can’t get button \"Save\" of window 1 of process \"Music\"."
</code></pre>
<p>I tried to say <code>click button 1</code> or <code>click button 2</code> instead, but that doesn't work. I then said <code>name of every button</code> and it printed</p>
<pre><code>{missing value, missing value, missing value}
</code></pre>
<p>I couldn't find a good manual for AppleScript, but it does look like something changed in Ventura. Any hints will be appreciated!</p>
<p>Thanks,</p>
| [
{
"answer_id": 74254509,
"author": "tripleee",
"author_id": 874188,
"author_profile": "https://Stackoverflow.com/users/874188",
"pm_score": 3,
"selected": true,
"text": "awk -v n=17 '(NR%6)==1 { print substr($0, n+1); next } 1' file\n"
},
{
"answer_id": 74255656,
"author": "D... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5008520/"
] |
74,254,511 | <p>I need to make a http request at application startup and save the value in the widget, to use it in the child widgets, but I can't make it work. I am using InitState() to make the request, but I can't save and use the value.</p>
<p>This is my code for now. The error I'm getting is that WeatherObject as a parameter to MainWeatherCardWidget can't be null, and I agree, but if I understood things correctly, shouldn't the await keyboard inside fetchData() waits until the http request is completed? Or I misunderstood something?</p>
<p>The variable being optional may be the key, but I need to make it as I need to save the value in it after its initialization, and I can't return something from InitState().</p>
<p>I think it might work with Provider package, but I didn't want to use it in this project, as I don't think a global state is required. Anyway, how to achieve it?</p>
<pre><code>class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
CurrentWeatherInterface? weatherObject;
Future<void> fetchData() async {
weatherObject = await fetchCurrentWeather(dotenv.env['API_KEY']);
}
@override
void initState() {
super.initState();
// fetch weather data
fetchData();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize:
Size.fromHeight(MediaQuery.of(context).size.height * 0.075),
child: AppBar(
backgroundColor: Colors.transparent,
elevation: 0.0,
),
),
drawer: const Drawer(),
backgroundColor: const Color.fromRGBO(62, 149, 250, 1),
body: SingleChildScrollView(
child: Center(
child: SizedBox(
width: MediaQuery.of(context).size.width * 0.85,
child: Column(
children: [
MainWeatherCardWidget(
weatherObject: weatherObject!,
),
const HourlyWeatherCardListWidget(),
const DailyWeatherListCardWidget(),
],
),
),
),
),
);
}
}
</code></pre>
<pre><code>import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:weather_app/interfaces/current_weather_interface.dart';
Future<CurrentWeatherInterface> fetchCurrentWeather(String? APIKey) async {
const url =
'http://api.weatherapi.com/v1/current.json?key=729fc1d266eb46589bf122819222505&q=Ararangua&qi=no';
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
return CurrentWeatherInterface.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to fetch data');
}
}
</code></pre>
| [
{
"answer_id": 74254509,
"author": "tripleee",
"author_id": 874188,
"author_profile": "https://Stackoverflow.com/users/874188",
"pm_score": 3,
"selected": true,
"text": "awk -v n=17 '(NR%6)==1 { print substr($0, n+1); next } 1' file\n"
},
{
"answer_id": 74255656,
"author": "D... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17109557/"
] |
74,254,526 | <p>I want to compute cumulative sum within 5 days for each group.</p>
<pre><code>df <- data.frame(
date = ymd( c( "2022-01-02","2022-01-03","2022-01-05","2022-01-07","2022-01-11","2022-01-14","2022-01-17","2022-01-18","2022-01-24","2022-01-27","2022-01-01","2022-01-04","2022-01-04","2022-01-08","2022-01-12","2022-01-14","2022-01-19","2022-01-24","2022-01-25","2022-01-28")),
group = c("A","A","A","A","A","A","A","A","A","A","B","B","B","B","B","B","B","B","B","B"),
number = c(10,30,20,50,30,50,40,50,30,50,55,10,30,20,50,30,40,30,40,30))
</code></pre>
<p>A small sample of my data frame is below including what the cumulative sum column should return.
Any help would be appreciated. Thanks.</p>
<pre><code>date group number cumsum(s)
2022-01-02 A 10 10
2022-01-03 A 30 40
2022-01-05 A 20 60
2022-01-07 A 50 110
2022-01-11 A 30 80
2022-01-14 A 50 80
2022-01-17 A 40 90
2022-01-18 A 50 140
2022-01-24 A 30 30
2022-01-27 A 50 80
2022-01-01 B 55 55
2022-01-04 B 10 65
2022-01-04 B 30 95
2022-01-08 B 20 60
2022-01-12 B 50 70
2022-01-14 B 30 80
2022-01-19 B 40 70
2022-01-24 B 30 70
2022-01-25 B 40 70
2022-01-28 B 30 100
</code></pre>
<p>I tried to use map() and cumsum() but failed.</p>
| [
{
"answer_id": 74254597,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "diff"
},
{
"answer_id": 74254698,
"author": "langtang",
"author_id": 4447540,
"author_profile": "h... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20372411/"
] |
74,254,534 | <pre><code><Input
label="Retail price"
editMode
name="retail_price"
rules={[{ required: true, message: validationRequiredText('retail price') }]}
type="number"
min={1}
/>
</code></pre>
<p>In this how can I update and Set the form values using the name="retail_price"?</p>
<p>I tried on other answers on google but didn't get the expected output.</p>
| [
{
"answer_id": 74254829,
"author": "Ravi kishore",
"author_id": 20366659,
"author_profile": "https://Stackoverflow.com/users/20366659",
"pm_score": 0,
"selected": false,
"text": "import React from \"react\";\nimport { useForm } from \"react-hook-form\";\n\nexport default function FormVal... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20372760/"
] |
74,254,540 | <p>I have an extension that needs to detect when a new Chrome session has started. I found a post here that suggested the following:</p>
<pre><code>chrome.runtime.onStartup.addListener(async function() {
console.log("new startup detected");
await chrome.storage.local.set({"status":false});
});
</code></pre>
<p>However, it seems that the listener does not work. It is also not clear what startup it refers to. Start up of Chrome or startup of the extension. Can someone clarify how to detect when a new chrome has started? TIA.</p>
<p><strong>Updated Code</strong></p>
<pre><code>chrome.windows.onCreated.addListener(async function() {
console.log("new startup detected");
await chrome.storage.local.set({"status":false});
});
</code></pre>
<p><strong>Updated withj Manifest</strong></p>
<pre><code>{
"manifest_version": 3,
"name": "Auto_Select",
"description": "This extension auto selects Mturk HITs",
"version": "1.0.12",
"action": {
"default_icon": "auto_select.png",
"type": "module",
"default_popup": "auto_select.html"
},
"permissions": [
"tabs",
"activeTab",
"storage",
"contextMenus",
"tts"
],
"host_permissions": [
"<all_urls>"
],
"background": {
"service_worker": "auto_select.js"
},
"content_security_policy": {
"extension_pages": "script-src 'self'; object-src 'self'; script-src-elem 'self'"
}
}
</code></pre>
| [
{
"answer_id": 74255576,
"author": "Norio Yamamoto",
"author_id": 20074043,
"author_profile": "https://Stackoverflow.com/users/20074043",
"pm_score": 0,
"selected": false,
"text": "{\n \"name\": \"hoge\",\n \"version\": \"1.0\",\n \"manifest_version\": 3,\n \"permissions\": [\"storag... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3998664/"
] |
74,254,569 | <p>I want to have a border such that it is shown only at the bottom and appears in center only and hidden around the corners:
This is what I have implemented till now :</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> .bd{
border-bottom:1px solid black;
position: relative;
}
.bd:after{
content: "";
width:25%;
height:1.1px;
background-color:white;
position: absolute;
right:0;
bottom:-1px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bd">Example</div>
</code></pre>
</div>
</div>
</p>
<p>What I have been able to achieve with this is I have a border which does not appear at right corner but does appear around left corner and I want to hide it from there as well.
I am not able to achieve that</p>
| [
{
"answer_id": 74254685,
"author": "Azu",
"author_id": 12806767,
"author_profile": "https://Stackoverflow.com/users/12806767",
"pm_score": 1,
"selected": false,
"text": "h3 {\n text-align: center;\n }\n .line {\n height: 2px;\n background-image: linear-gradient(... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13796424/"
] |
74,254,570 | <p>I want to create a bar chart such that the x-axis contains the different <code>engine_type</code> and the y-axis contains the <code>count</code>. Data frame (DEU_2001_df) below:</p>
<pre><code> Year engine_type count
1 2001 petrol_number 2185247
2 2001 diesel_gas_number 1155300
3 2001 full_mild_hybrid_number 606.
4 2001 plugin_hybrid_number 0
5 2001 battery_electric_number 56
</code></pre>
<p>When using the following line:</p>
<pre><code>ggplot(DEU_2001_df, mapping = aes(x = 'engine_type', y = 'count')) +
geom_bar(stat = "identity")
</code></pre>
<p>I get this plot:
<a href="https://i.stack.imgur.com/ITRcT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ITRcT.png" alt="enter image description here" /></a></p>
<p>Steps taken as above.</p>
| [
{
"answer_id": 74254723,
"author": "Nowfel Ahmed",
"author_id": 20370986,
"author_profile": "https://Stackoverflow.com/users/20370986",
"pm_score": 0,
"selected": false,
"text": "engine %>% ggplot(aes(x = engine_type, y = count)) + geom_bar(stat = 'identity')"
},
{
"answer_id": 7... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18408564/"
] |
74,254,581 | <p>how to combine numbers from different ranges into one variable</p>
<p>I have 3 ranges from which I recognize the value and set them to a variable, and then I try to add the values of these variables into functions. Why it doesn't work</p>
<pre><code><form action="range">
<label>Рассчитай свои <br> накопления и доход</label>
<div class="first__range">
<div class="name">
<label>Сумма вклада</label>
</div>
<input id="rangeOne" type="range" min="0" max="1000000" value="0">
</div>
<div class="two__range">
<div class="name">
<label>Срок инвестирования</label>
</div>
<input id="rangeTwo" type="range" min="0" max="24" value="0">
</div>
<div class="three__range">
<div class="name">
<label>Пополнение вклада</label>
</div>
<input id="rangeThree" type="range" min="0" max="30000" value="0">
</div>
</form>
<div class="final_count">
Сюда
</div>
</code></pre>
<pre><code>const rangeOne = document.querySelector('#rangeOne');
const rangeTwo = document.querySelector('#rangeTwo');
const rangeThree = document.querySelector('#rangeThree');
const finalCount = document.querySelector('.final_count')
rangeOne.addEventListener('input', () => {
let a = rangeOne.value
});
rangeTwo.addEventListener('input', () => {
let b = rangeTwo.value
});
rangeThree.addEventListener('input', () => {
let c = rangeThree.value
});
function score() {
let final = a + b + c;
console.log(final)
}
score()
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>document.querySelector('#btnCount').addEventListener('click', () => {
document.querySelector('#finalCountVal').innerHTML = (
+document.querySelector('#rangeOne').value +
+document.querySelector('#rangeTwo').value +
+document.querySelector('#rangeThree').value
);
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<label>Рассчитай свои <br> накопления и доход</label>
<div class="first__range">
<div class="name">
<label>Сумма вклада</label>
</div>
<input id="rangeOne" type="range" min="0" max="1000000" value="0">
</div>
<div class="two__range">
<div class="name">
<label>Срок инвестирования</label>
</div>
<input id="rangeTwo" type="range" min="0" max="24" value="0">
</div>
<div class="three__range">
<div class="name">
<label>Пополнение вклада</label>
</div>
<input id="rangeThree" type="range" min="0" max="30000" value="0">
</div>
</form>
<div class="final_count">
Сюда
</div>
<br/>
<button id="btnCount">Count</button>
<br/>
<div id="finalCountVal"></div>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74254753,
"author": "Johna",
"author_id": 20056500,
"author_profile": "https://Stackoverflow.com/users/20056500",
"pm_score": 0,
"selected": false,
"text": "const rangeOne = document.querySelector('#rangeOne');\nconst rangeTwo = document.querySelector('#rangeTwo');\nconst ... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20324239/"
] |
74,254,615 | <p>I have a folder of numerous .xslx files on my desktop and I am trying to iterate through them one by one to collect the respective sheet names automatically from each workbook.</p>
<pre><code>import openpyxl
import glob
# specifying the path to csv files
path = "C:/Users/X/Desktop/Test"
# csv files in the path
files = glob.glob(path + "/*.xlsx")
sheet_names = []
for x in files:
openpyxl.load_workbook(files)
sheet_names.append(files.sheetnames)
</code></pre>
<p>I am getting an error code:</p>
<pre><code>TypeError: expected str, bytes or os.PathLike object, not list
</code></pre>
<p>Is there any way to do this iteratively versus one by one if I have all of the workbook names in a list?</p>
<p>Thank you.</p>
<p>I am looking for the sheet names in each respective Excel workbook file.</p>
| [
{
"answer_id": 74254684,
"author": "ouroboros1",
"author_id": 18470692,
"author_profile": "https://Stackoverflow.com/users/18470692",
"pm_score": 3,
"selected": true,
"text": "sheet_names = []\n\nfor x in files:\n sheet_names.append(openpyxl.load_workbook(x).sheetnames)\n"
},
{
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20360218/"
] |
74,254,618 | <p>I'm a new one at the world of Python programming. I've just, unfortunately, stuck on this, I think, simple exercise.</p>
<p>So what I should do is to modify the stars(n) function to print n stars, with each group of five stars separated by a vertical line.
I have code like this, but I really don't know what to do with it.</p>
<pre><code>def stars(n):
for i in range(n):
print("*", end='')
if i == 4:
print("|", end="")
print()
stars(7)
stars(15)
</code></pre>
<p>The output should be like that:</p>
<pre><code>*****|**
*****|*****|*****|
</code></pre>
| [
{
"answer_id": 74254796,
"author": "Anters Bear",
"author_id": 6158471,
"author_profile": "https://Stackoverflow.com/users/6158471",
"pm_score": 1,
"selected": false,
"text": "def stars(n):\n solution = ''\n for i in range(n):\n if i % 5 == 0 and i != 0:\n solutio... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20372783/"
] |
74,254,627 | <p>OnCollisionEnter I am calculating the magnitude to determine whether or not to play a sound clip. Which works fine for most of the collisions, but it is triggering with my ball that is rolling on a plane. Since the ball is moving at a relatively fast speed and the magnitude doesn't take direction into account, every time it rolls it plays the clip. Sometimes 15 times a second. I only want the clip to play when the ball is dropped on the plane. Does anybody have some suggestions or solutions to calculate the impact velocity?</p>
| [
{
"answer_id": 74254796,
"author": "Anters Bear",
"author_id": 6158471,
"author_profile": "https://Stackoverflow.com/users/6158471",
"pm_score": 1,
"selected": false,
"text": "def stars(n):\n solution = ''\n for i in range(n):\n if i % 5 == 0 and i != 0:\n solutio... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19815272/"
] |
74,254,633 | <p>How would I update the stock number of a car with a given index using an increment function? I'm assuming I need to use setState but I'm not sure how to implement that. If I use setState inside the increment function will my react component re-render?</p>
<pre><code>class App extends React.Component {
constructor(props) {
super(props);
this.state = {
cars: [
{
"manufacturer": "Toyota",
"model": "Rav4",
"year": 2008,
"stock": 3,
"price": 8500
},
{
"manufacturer": "Toyota",
"model": "Camry",
"year": 2009,
"stock": 2,
"price": 6500
},
]
};
}
increment(index)
{
//Need to increment the stock number by 1 here
}
render() {
return (
<table>
<tr>
<th>manufacturer</th>
<th>model</th>
<th>year</th>
<th>stock</th>
<th>price</th>
<th>option</th>
</tr>
<tr>
<td>{this.state.cars[0].manufacturer}</td>
<td>{this.state.cars[0].model}</td>
<td>{this.state.cars[0].year}</td>
<td>{this.state.cars[0].stock}</td>
<td>${this.state.cars[0].price}.00</td>
<td>
<button onClick={this.increment(0)}>Increment</button>
</td>
<td>
<button>Decrement</button>
</td>
</tr>
<tr>
<td>{this.state.cars[1].manufacturer}|</td>
<td>{this.state.cars[1].model}</td>
<td>{this.state.cars[1].year}</td>
<td>{this.state.cars[1].stock}</td>
<td>${this.state.cars[1].price}.00</td>
<td>
<button onClick={this.increment(1)}>Increment</button>
</td>
<td>
<button>Decrement</button>
</td>
</tr>`your text`
</table>
);
};
}
ReactDOM.render(<App />, document.getElementById("app"))
</code></pre>
<p>I'm assuming I need to use setState in my increment function but how would I do that?</p>
| [
{
"answer_id": 74254796,
"author": "Anters Bear",
"author_id": 6158471,
"author_profile": "https://Stackoverflow.com/users/6158471",
"pm_score": 1,
"selected": false,
"text": "def stars(n):\n solution = ''\n for i in range(n):\n if i % 5 == 0 and i != 0:\n solutio... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15343871/"
] |
74,254,639 | <p>How can I use a negated or a "not" type in Typescript?</p>
<p>example(just an example), I tried to use <code>is not</code> in a type predicate:</p>
<pre><code>function notUndef(obj: any): obj is not undefined {
// -------------------------------> ~~~ error!
// cannot find name 'not'.
return obj !== void(0);
}
</code></pre>
<p>and</p>
<pre><code>function notUndef(obj: any): (typeof obj !== undefined) {
// ')' expected -----> ~~~ -----> ~
// ';' expected
return obj !== void(0);
}
</code></pre>
<p>but I received errors.</p>
<p>Neither of these work, what can I do?</p>
| [
{
"answer_id": 74254764,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 2,
"selected": false,
"text": "function notUndef<T>(obj: T): obj is Exclude<T, undefined> {\n return obj !== void(0);\n}\n"
},
{
"answer_i... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18248235/"
] |
74,254,641 | <p>I'm trying to generate a map, from a map within a list.</p>
<pre><code>locals {
account_assignments_test = [
{
principal_name = "CORP_SYSTEM_RO@hq.vw.ad",
account = "123456789012",
permission_set_name = "system-audit"
},
{
principal_name = "CORP_SYSTEM_RW@hq.vw.ad",
account = [ "234567890123", "345678901234" ]
permission_set_name = "system-admin"
}
]
account_assignment_map_test = {
for pn in local.account_assignments_test : format("%v-%v-%v", pn.account, pn.principal_name, pn.permission_set_name) => pn
}
}
</code></pre>
<pre><code>output "account_assignment_map_test" {
value = local.account_assignment_map_test
}
</code></pre>
<p>The outputs is clean:</p>
<pre><code>Outputs:
account_assignment_map_test = {
"123456789012-CORP_SYSTEM_RO@hq.vw.ad-system-audit" = {
"account" = "123456789012"
"permission_set_name" = "system-audit"
"principal_name" = "CORP_SYSTEM_RO@hq.vw.ad"
}
"[\"234567890123\",\"345678901234\"]-CORP_SYSTEM_RW@hq.vw.ad-system-admin" = {
"account" = [
"234567890123",
"345678901234",
]
"permission_set_name" = "system-admin"
"principal_name" = "CORP_SYSTEM_RW@hq.vw.ad"
}
}
</code></pre>
<p>I do not feel comfortable with flatten, but I try it out, the idea is to loop on <code>account</code> first, then on <code>principal_name</code> (not sure if it's good idea). I've try lot of thing but without success.</p>
<pre><code> account_assignment_map_test = flatten([
for principal_name_key, principal_name in local.account_assignments_test: [
for account_key, account in principal_name.account : {
principal_name_key = principal_name
account_key = account
# permission_set_name_key = permission_set_name
}
]
])
</code></pre>
<p>But it doesn't work, i got the following message :</p>
<pre><code>│ Error: Iteration over non-iterable value
│
│ on variables_locals.tf line 66, in locals:
│ 65: for principal_name_key, principal_name in local.account_assignments_test: [
│ 66: for account_key, account in principal_name.account : {
│ 67: principal_name_key = principal_name
│ 68: account_key = account
│ 69: # permission_set_name_key = permission_set_name
│ 70: }
│ 71: ]
│ ├────────────────
│ │ principal_name.account is "123456789012"
│
│ A value of type string cannot be used as the collection in a 'for' expression.
</code></pre>
<p>I would like to iterate on account list to get something like this</p>
<pre><code>Outputs:
association_list = {
"123456789012-CORP_SYSTEM_RO@hq.vw.ad-system-audit" = {
"account" = "123456789012"
"permission_set_name" = "system-audit"
"principal_name" = "CORP_SYSTEM_RO@hq.vw.ad"
}
"234567890123-CORP_SYSTEM_RW@hq.vw.ad-system-admin" = {
"account" = "234567890123"
"permission_set_name" = "system-admin"
"principal_name" = "CORP_SYSTEM_RW@hq.vw.ad"
}
"345678901234-CORP_SYSTEM_RW@hq.vw.ad-system-admin" = {
"account" = "345678901234"
"permission_set_name" = "system-admin"
"principal_name" = "CORP_SYSTEM_RW@hq.vw.ad"
}
}
</code></pre>
<p>To run a <code>for_each</code> from a ressource:</p>
<pre><code>resource "aws_ssoadmin_account_assignment" "test" {
for_each = local.account_assignment_map_test
instance_arn = local.sso_instance_arn
permission_set_arn = aws_ssoadmin_permission_set.test[each.value.permission_set_name].arn
principal_id = data.aws_identitystore_group.test[each.value.principal_name].id
principal_type = "GROUP"
target_id = each.value.account
target_type = "AWS_ACCOUNT"
}
</code></pre>
<p>I think that I need a nested loop to solve it, but i don't know how.</p>
<p>And i would like to know if it's permit to go further with a new iteration but on <code>permission_set_name</code>:</p>
<pre><code>{
principal_name = "CORP_SYSTEM_RW@hq.vw.ad",
account = [ "234567890123", "345678901234" ]
permission_set_name = ["system-admin", "system-admin"]
}
</code></pre>
<p>But, I'm note sure that we can iterate infinitely ?</p>
| [
{
"answer_id": 74254970,
"author": "Chris Doyle",
"author_id": 1212401,
"author_profile": "https://Stackoverflow.com/users/1212401",
"pm_score": 2,
"selected": true,
"text": "terraform {\n\n}\n\n\nlocals {\n account_assignments_test = [\n {\n principal_name = \"CORP_SYST... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10653829/"
] |
74,254,660 | <p>I am trying to take an object containing other objects and filter them first. Then if any objects contain the same two key/value pairs, I want to merge them to add any new data.</p>
<p>I know how to use the spread operator to merge the two, but I can not for the life of figure out the filter method.</p>
<p>Here is a sample object structure:</p>
<pre><code>let timesheet = {
'job1': {
day_of_week: 1,
wo_number: '486322',
reg_hours: 4.5
}
'job2': {
day_of_week: 1,
wo_number: '486322',
ot_hours: 2.0
}
'job3': {
day_of_week: 1,
wo_number: '486922',
reg_hours: 3.5
}
}
</code></pre>
<p>What I am doing is that I take the info from a db call, turn it into JSON and then re-create the object with meaningful keys I can use. Then I delete all the keys I don't need. I am left with an object similar to the above sample, except with many other keys.</p>
<p>What I need to do is filter through these. Any job# that matches both wo_number and day_of_week numbers are to be considered the same job. Those will then be merged and the properties reg_hours and ot_hours will be then on the same job# and the other job# will not be returned.</p>
<p>Any help is appreciated.</p>
| [
{
"answer_id": 74254970,
"author": "Chris Doyle",
"author_id": 1212401,
"author_profile": "https://Stackoverflow.com/users/1212401",
"pm_score": 2,
"selected": true,
"text": "terraform {\n\n}\n\n\nlocals {\n account_assignments_test = [\n {\n principal_name = \"CORP_SYST... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20277940/"
] |
74,254,661 | <p>I have an array that has objects, within which is an array of objects as shown below.</p>
<pre><code>const property = [
{
houses: {
"id": "HT-00001",
"features": [{ "id": "FT-0001", "name": "balcony"}, { "id": "FT-0002", "name": "wifi"}],
"opts": [{
"desc": "House description",
"bed": 3,
"bath": 1,
"location": "Location of property",
"name": "Name of Property Listing",
"isDefault": false,
"listPrice": [{"amount": 123, "currency": "EUR"}]
}]
},
currency: {
"currency": "EUR"
}
},
{
houses: {
"id": "HT-00002",
"features": [{ "id": "FT-0003", "name": "tiled floor"}, { "id": "FT-0002", "name": "wifi"}],
"opts": [{
"desc": "House description",
"bed": 3,
"bath": 1,
"location": "Location of property",
"name": "Name of Property Listing",
"isDefault": false,
"listPrice": [{"amount": 123, "currency": "EUR"}]
}]
},
currency: {
"currency": "EUR"
}
},
{
houses: {
"id": "HT-00003",
"features": [{ "id": "FT-0004", "name": "refrigerator"}, { "id": "FT-0005", "name": "microwave"}],
"opts": [{
"desc": "House description",
"bed": 3,
"bath": 1,
"location": "Location of property",
"name": "Name of Property Listing",
"isDefault": false,
"listPrice": [{"amount": 123, "currency": "EUR"}]
}]
},
currency: {
"currency": "EUR"
}
},
];
</code></pre>
<p>Now, I am getting a challenge extracting a unique list of features name as an array. Take note that the features has objects and it is within houses object which is an object of object of the array that I am dealing with. What I want is just an array of all unique feature names that are within the provided property array. This is what I have tried, even though it is so much confusing and I need your help.</p>
<pre><code> const allFeatures = property?.map((propertyItem) => {
let features = Array.from(new Set(propertyItem?.houses?.features?.map(({ name }) => name)));
return features;
});
</code></pre>
<p>The expected array will be something like:
<code>allFeatures = ['balcony', 'wifi', 'tiled floor', 'refrigerator', 'microwave']</code></p>
| [
{
"answer_id": 74254721,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 3,
"selected": true,
"text": "map"
},
{
"answer_id": 74255687,
"author": "PeterKA",
"author_id": 3558931,
"author_profile": "https... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2978051/"
] |
74,254,665 | <p>I have a <code>class</code> that conforms to <code>ObservableObject</code>, which takes some arguments. When I then use <code>@ObservedObject var someName = className()</code> in my view to access all the functions and data in the class, I get an error saying:</p>
<blockquote>
<p>Missing arguments for parameters 'pickedVideo', 'pickedImage', 'retrievedImages', 'retrievedVideos' in call</p>
</blockquote>
<p>I am aware that I somehow have to pass the arguments from my view to the class.</p>
<p><strong>But how do I pass variables from my view to my class?</strong></p>
<p><strong>Class:</strong></p>
<pre><code>class DBFunctions : ObservableObject {
init(pickedVideo: [String], pickedImage: [UIImage], retrievedImages: [UIImage], retrievedVideos: [AVPlayer]) {
self.pickedVideo = pickedVideo
self.pickedImage = pickedImage
self.retrievedImages = retrievedImages
self.retrievedVideos = retrievedVideos
}
var pickedVideo : [String]
var pickedImage : [UIImage]
var retrievedImages : [UIImage]
var retrievedVideos : [AVPlayer]
func somefunc() {
}
}
</code></pre>
<p><strong>View:</strong></p>
<pre><code>struct ContentView: View {
@ObservedObject var helpFuncs = DBFunctions()
@State var showPicker: Bool = false
@State var pickedImage: [UIImage] = []
@State var retrievedImages = [UIImage]()
@State var player : AVPlayer?
@State var width : CGFloat = 0
@State var retrievedVideos = [AVPlayer]()
@State var pickedVideo: [String] = []
@State var isPaused = false
var body: some View {
VStack{
Button(action: {
helpFuncs.uploadImage()
}) {
Text("Upload Image")
}
}
}
</code></pre>
| [
{
"answer_id": 74254721,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 3,
"selected": true,
"text": "map"
},
{
"answer_id": 74255687,
"author": "PeterKA",
"author_id": 3558931,
"author_profile": "https... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13708093/"
] |
74,254,748 | <p>I am making a quiz. I would like to iterate over the different buttons to bring up different questions once I press the buttons. However, since each button has a different id, I am finding it difficult to find a way of changing the id names in the loop. See below for code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let mybtn1 = document.getElementById("myBtn1")
let questions = [
{
question : "What is an Epidemics?",
choiceA : "CorrectA",
choiceB : "WrongB",
choiceC : "WrongC",
choiceD: "Hello",
correct : "Hello"
},{
question : "What does CSS stand for?",
choiceA : "Wrong",
choiceB : "Correct",
choiceC : "Wrong",
correct : "B"
},{
question : "What does JS stand for?",
choiceA : "Wrong",
choiceB : "Wrong",
choiceC : "Correct",
correct : "C"
}
];
mybtn1.addEventListener("click", pressbtn);
function pressbtn(){
modal.style.display = "block";
questionText.innerHTML = questions[0].question;
answerA.innerHTML = questions[0].choiceA;
answerB.innerHTML = questions[0].choiceB;
answerC.innerHTML = questions[0].choiceC;
answerD.innerHTML = questions[0].choiceD;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="path-one-row">
<li class="grid blue" id="myBtn1"></li>
<li class="grid blue" id="myBtn2"></li>
<li class="grid blue" id="myBtn3"></li>
<li class="grid blue" id="myBtn4"></li>
</ul></code></pre>
</div>
</div>
</p>
<p>For example, when I click the button with id='mybtn1', it should iterate to give me access to questions[0] and so then I can manipulate the innerHTML. For id='mybtn2', questions[1] and so on. How could I write a loop to help me iterate this?</p>
| [
{
"answer_id": 74254721,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 3,
"selected": true,
"text": "map"
},
{
"answer_id": 74255687,
"author": "PeterKA",
"author_id": 3558931,
"author_profile": "https... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14458269/"
] |
74,254,772 | <p>I have a timer, I want to do something when textContent of div element === 0;</p>
<p>JS:</p>
<pre><code>function createTimer() {
const display = document.createElement('div');
display.classList.add('display');
display.id = 'display';
display.textContent = '5';
return display;
};
let intervalID;
function startTimer() {
resetTimer();
intervalID = setInterval(() => {
let displayTimer = document.getElementById('display');
let displayNumber = parseInt(displayTimer.textContent);
if (displayTimer.textContent !== '0') displayTimer.textContent = displayNumber - 1;
}, 1000);
};
function resetTimer() {
clearInterval(intervalID);
};
function someFunc() {
// here is a lot of code stuff and timer is working correctly
const timer = createTimer();
};
</code></pre>
<p><strong>This is what i tried:</strong></p>
<pre><code>function someFunc() {
const timer = createTimer();
timer.addEventListener('input', () => {
if (timer.textContent === '0') {
console.log(true);
};
});
};
</code></pre>
<p>As far as I understood correctly, by creating <em>input</em> event on timer, I always get timer.textContent when it changes, right? I keep track of all the changes thats happening in this div element.</p>
<p>nothing happens.. am i dumb?</p>
| [
{
"answer_id": 74254721,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 3,
"selected": true,
"text": "map"
},
{
"answer_id": 74255687,
"author": "PeterKA",
"author_id": 3558931,
"author_profile": "https... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19463106/"
] |
74,254,800 | <p>Let's say I have the LinkedHashMap with some unknown data inside.</p>
<pre><code>//==================
Map< Integer, String > map = new LinkedHashMap<>();
map.put(10, "C");
map.put(20, "C++");
map.put(50, "JAVA");
map.put(40, "PHP");
map.put(30, "Kotlin");
//=============
</code></pre>
<p>And I know just the key = 50;</p>
<p>I am wondering what is the best way to get the next element to the element that I have by this key (50)? This is not a multi-threaded application. I don't worry about thread-safety.</p>
<p>I don't like the way to iterate all keys through entrySet from the beginning.</p>
<p>It would be great to somehow get access to the <code>next()</code> of <code>LinkedHashMap</code>s Entry.</p>
| [
{
"answer_id": 74254894,
"author": "oleg.cherednik",
"author_id": 3461397,
"author_profile": "https://Stackoverflow.com/users/3461397",
"pm_score": 1,
"selected": false,
"text": "LinkedHashMap"
},
{
"answer_id": 74254936,
"author": "Alexander Ivanchenko",
"author_id": 179... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20301714/"
] |
74,254,819 | <p>We have to create a code that will shuffle the deck of cards after showing the first 13 cards.</p>
<p>so far this is the portion of my code:</p>
<pre class="lang-py prettyprint-override"><code>deck_of_cards = [ "A-C", "2-C" ,"3-C" ,"4-C" ,"5-C" ,"6-C" ,"7-C" ,"8-C" ,"9-C" ,"10-C" ,"J-C" ,"Q-C" ,"K-C" ,
"A-D" ,"2-D" ,"3-D" ,"4-D" ,"5-D" ,"6-D" ,"7-D" ,"8-D" ,"9-D" ,"10-D" ,"J-D" ,"Q-D" ,"K-D" ,
"A-H" ,"2-H" ,"3-H" ,"4-H" ,"5-H" ,"6-H" ,"7-H" ,"8-H" ,"9-H" ,"10-H" ,"J-H" ,"Q-H" ,"K-H" ,
"A-S" ,"2-S" ,"3-S" ,"4-S" ,"5-S" ,"6-S" ,"7-S" ,"8-S" ,"9-S" ,"10-S" ,"J-S" ,"Q-S" ,"K-S"]
if choose == '1'
new_deck = []
d1 = deck_of_cards[:len(deck_of_cards)//2]
d2 = deck_of_cards[len(deck_of_cards)//2::]
for i in range(len(deck_of_cards)//2):
new_deck.append(d2[i])
new_deck.append(d1[i])
if len(deck_of_cards) % 2 == 1:
new_deck.append(deck_of_cards[-1])
shuffle = new_deck[0:13:]
print(','.join(map(str,shuffle)))
</code></pre>
<p>I got the shuffled deck of cards (13 cards) but if I shuffle it twice, its still the same set of cards:</p>
<pre><code>A-H,A-C,2-H,2-C,3-H,3-C,4-H,4-C,5-H,5-C,6-H,6-C,7-H
</code></pre>
<p>How can I shuffle the deck of cards repeatedly without getting the same set of shuffled cards just like the above result???</p>
<p>We were also asked not to import module functions.</p>
<p>I am just a beginner coder.</p>
| [
{
"answer_id": 74255331,
"author": "Javad",
"author_id": 11833435,
"author_profile": "https://Stackoverflow.com/users/11833435",
"pm_score": 1,
"selected": false,
"text": "itertools"
},
{
"answer_id": 74264408,
"author": "wwii",
"author_id": 2823755,
"author_profile":... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20370477/"
] |
74,254,828 | <p>im trying to be a junior android developer and im trying to make a fake product list from an api. I'm using a recyclerview with gridlayout. I created an asynclist in my adapter and gathering values from viewmodel and observing and submitting in the fragment. And i would add the sort and filter options on my fragment. I would do that like real apps. I created 2 alertdialogs for my buttons. I can sort and filter respectively. But sorting after filter does not work for second time. For first time i can filter and sort. But if i changed filter i cant sort the items. List comes empty from filter alertdialog...</p>
<p>Here is my codeblock;</p>
<pre><code>@AndroidEntryPoint
</code></pre>
<p>class ProductFragment : Fragment(R.layout.fragment_product) {</p>
<pre><code>private var fragmentBinding : FragmentProductBinding? = null
@Inject
lateinit var viewModel: HomeViewModel
@Inject
lateinit var adapter: ProductsAdapter
lateinit var list : MutableList<Product>
private var filteredList = mutableListOf<Product>()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = FragmentProductBinding.bind(view)
fragmentBinding = binding
viewModel.getAllProducts()
viewModel.products.observe(viewLifecycleOwner){
adapter.recyclerListDiffer.submitList(it.data)
list = adapter.recyclerListDiffer.currentList
}
filteredList.addAll(adapter.recyclerListDiffer.currentList)
binding.productsRecycler.adapter = adapter
binding.productsRecycler.layoutManager = StaggeredGridLayoutManager(2,RecyclerView.VERTICAL)
adapter.setOnItemClickListener {
val action = ProductFragmentDirections.actionProductFragmentToDetailScreenFragment(it)
findNavController().navigate(action)
}
//**BACK BUTTON
binding.productsBackbutton.setOnClickListener {
findNavController().popBackStack()
}
//** SORT ***///
val sortArray = arrayOf("Best Match","Price Asc","Price Desc")
var adbIndex = 0
var selectedItem = ""
binding.productsSortbutton.setOnClickListener {
MaterialAlertDialogBuilder(requireContext())
.setSingleChoiceItems(sortArray,adbIndex){ dialog,which->
adbIndex = which
selectedItem = sortArray[which]
}
.setPositiveButton("Sort"){dialog,which->
when(selectedItem){
sortArray.get(0) ->{
adapter.recyclerListDiffer.submitList(filteredList)
}
else {
adapter.recyclerListDiffer.submitList(list)
}
binding.productsRecycler.smoothScrollToPosition(0)
}
sortArray.get(1) ->{
if (filteredList.isNotEmpty()){
adapter.recyclerListDiffer.submitList(filteredList.sortedBy { it.price.toDouble() })
}
else {
adapter.recyclerListDiffer.submitList(list.sortedBy { it.price.toDouble() })
}
binding.productsRecycler.smoothScrollToPosition(0)
}
sortArray.get(2) -> {
if (filteredList.isNotEmpty()){
adapter.recyclerListDiffer.submitList(filteredList.sortedByDescending { it.price.toDouble() })
}
else{
adapter.recyclerListDiffer.submitList(list.sortedByDescending { it.price.toDouble() })
}
binding.productsRecycler.smoothScrollToPosition(0)
}
}
}
.show()
}
//FILTER
val filterArray = arrayOf("Electronics","Jewelery","Men's Clothing","Women's Clothing")
var filterArrayBool : BooleanArray = booleanArrayOf(false,false,false,false)
val currentItemList = Arrays.asList(*filterArray)
val selectedItemList = ArrayList<String>()
binding.productsFilterbutton.setOnClickListener {
MaterialAlertDialogBuilder(requireContext())
.setCancelable(false)
.setMultiChoiceItems(filterArray,filterArrayBool) {dialog,which,isChecked ->
filterArrayBool[which] = isChecked
}
.setPositiveButton("FILTER"){dialog,which->
for (i in filterArrayBool.indices){
val checked = filterArrayBool[i]
if (checked){
selectedItemList.add(currentItemList[i].lowercase())
}
when(selectedItemList.size){
1 -> {
filteredList.clear()
viewModel.products.observe(viewLifecycleOwner){
adapter.recyclerListDiffer.submitList(it.data?.filter { it.category== selectedItemList.get(0) })
}
filteredList.addAll(adapter.recyclerListDiffer.currentList.filter { it.category == selectedItemList.get(0) })
}
2 -> {
viewModel.products.observe(viewLifecycleOwner){
adapter.recyclerListDiffer.submitList(it.data?.filter { it.category== selectedItemList.get(0) || it.category == selectedItemList.get(1) })
filteredList.clear().also { filteredList.addAll(adapter.recyclerListDiffer.currentList.filter { it.category== selectedItemList.get(0) || it.category == selectedItemList.get(1) }) }
}
}
3 -> {
viewModel.products.observe(viewLifecycleOwner){
adapter.recyclerListDiffer.submitList(it.data?.filter { it.category== selectedItemList.get(0) || it.category == selectedItemList.get(1) || it.category == selectedItemList.get(2) })
filteredList.clear().also { filteredList.addAll(adapter.recyclerListDiffer.currentList.filter { it.category== selectedItemList.get(0) || it.category == selectedItemList.get(2) }) }
}
}
4 -> {
viewModel.products.observe(viewLifecycleOwner){
adapter.recyclerListDiffer.submitList(it.data?.filter { it.category== selectedItemList.get(0) || it.category == selectedItemList.get(2) || it.category == selectedItemList.get(3) })
filteredList.clear().also { filteredList.addAll(adapter.recyclerListDiffer.currentList.filter { it.category== selectedItemList.get(0) || it.category == selectedItemList.get(2) || it.category == selectedItemList.get(3) }) }
}
} else ->
viewModel.products.observe(viewLifecycleOwner){
adapter.recyclerListDiffer.submitList(it.data)
filteredList.clear().also { filteredList.addAll(adapter.recyclerListDiffer.currentList) }
}
}
}
binding.productsRecycler.smoothScrollToPosition(0)
selectedItemList.clear()
} .setNeutralButton("Show All"){dialog,which ->
viewModel.products.observe(viewLifecycleOwner){
adapter.recyclerListDiffer.submitList(it.data) }
filterArrayBool.forEach { it==false }
binding.productsRecycler.smoothScrollToPosition(0)
}.show()
}
}
}
</code></pre>
<p>How can i update the list everytime when i select the positive button?</p>
| [
{
"answer_id": 74256485,
"author": "Mert",
"author_id": 4058604,
"author_profile": "https://Stackoverflow.com/users/4058604",
"pm_score": 1,
"selected": false,
"text": " viewModel.products.observe(viewLifecycleOwner){\n adapter.recyclerListDiffer.submitList(it.data)\n li... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3155444/"
] |
74,254,836 | <p>How can I make a design like the image with Jetpack Compose? I searched a lot, but I couldn't get any answer similar to the structure I wanted.</p>
<p><a href="https://i.stack.imgur.com/2qzOj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2qzOj.jpg" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74256485,
"author": "Mert",
"author_id": 4058604,
"author_profile": "https://Stackoverflow.com/users/4058604",
"pm_score": 1,
"selected": false,
"text": " viewModel.products.observe(viewLifecycleOwner){\n adapter.recyclerListDiffer.submitList(it.data)\n li... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18201304/"
] |
74,254,876 | <pre><code>Function Find-Compliance { param ( [Parameter(Mandatory)] $StatusID )
$category_list = Import-Excel "C:\pATCHING\pATCHES.xlsx"
foreach ($category in $category_list) {
if ($category.status -eq $StatusID) {
Write-Host "$($category.Parameter), whose status is $($Category.status)." } else { Write-Host "System is fully compliant in all parameter" -ForegroundColor Green } } } Find-Compliance -StatusID 'Non-Compliant'
</code></pre>
<p>Tried above code but it's giving multiple output.</p>
| [
{
"answer_id": 74256485,
"author": "Mert",
"author_id": 4058604,
"author_profile": "https://Stackoverflow.com/users/4058604",
"pm_score": 1,
"selected": false,
"text": " viewModel.products.observe(viewLifecycleOwner){\n adapter.recyclerListDiffer.submitList(it.data)\n li... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20241109/"
] |
74,254,882 | <p>I have a table of URL hosts with a varying number of dots, e.g. "sub.domain.co.uk", "domain.co.uk" and "domain.com" in one column, and the parts of each host (split up at dots) in the second column. Example of data:</p>
<pre><code>CREATE TABLE dt AS
SELECT * FROM
(WITH temp AS (
SELECT * FROM (VALUES ('sub.domain.co.uk', 'domain', 1), ('sub.domain.co.uk', 'co', 2), ('sub.domain.co.uk', 'uk', 3), ('domain.co.uk', 'co', 1), ('domain.co.uk', 'uk', 2), ('domain.com', 'com', 1)) AS account (host, part, n)
)
SELECT host, part, n from temp)
</code></pre>
<p><a href="https://i.stack.imgur.com/MLmFv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MLmFv.png" alt="enter image description here" /></a></p>
<p>Ultimately, I want to create a column that creates subsets of the <code>host</code> field, the first combining the second to <code>n</code>th part until the last containing just the <code>n</code>th part. Desired output with example data:</p>
<pre><code>WITH dt AS (
SELECT * FROM (VALUES ('sub.domain.co.uk', 'domain', 1, 'domain.co.uk'), ('sub.domain.co.uk', 'co', 2, 'co.uk'), ('sub.domain.co.uk', 'uk', 3, 'uk'), ('domain.co.uk', 'co', 1, 'co.uk'), ('domain.co.uk', 'uk', 2, 'uk'), ('domain.com', 'com', 1, 'com')) AS account (host, part, number, subset)
)
SELECT host, part, number, subset from dt;
</code></pre>
<p><a href="https://i.stack.imgur.com/jJdD2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jJdD2.png" alt="enter image description here" /></a></p>
<p>I have found a solution with window function. The only problem is that since the number of parts for each <code>host</code> varies in my real data, I have to first find the maximum number of parts, and then create the according number of window-function columns, and then concatenate the columns. So with maximum number of 4 parts:</p>
<pre><code>SELECT *,
CASE
WHEN part_2 IS NULL THEN part
WHEN part_2 IS NOT NULL AND part_3 IS NULL THEN concat(part, '.', part_2)
WHEN part_3 IS NOT NULL THEN concat(part, '.', part_2, '.', part_3)
END AS pattern
FROM
(SELECT
host, part,
LEAD(part) OVER (PARTITION BY host ORDER BY n_row) AS part_2,
LEAD(part, 2) OVER (PARTITION BY host ORDER BY n_row) AS part_3
FROM
(SELECT host, part, row_number() OVER (PARTITION BY host) n_row
FROM dt))
</code></pre>
<p>However, this gets annoying when the maximum number of parts gets higher. Is there any way to take care of this more elegantly?</p>
| [
{
"answer_id": 74256887,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 1,
"selected": false,
"text": "part"
},
{
"answer_id": 74265144,
"author": "Rajat",
"author_id": 9947159,
"author_profile": ... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10483692/"
] |
74,254,890 | <p>Basically in my program, I am using a for loop, it assigns values to each element of the array and stores them in it and then writes them out and it gives good results. However, when I exit the loop and want to write out the elements of this array I get wrong results all equal to 0.0000. How do I overcome this and keep the results outside of the for loop ?</p>
<pre><code> // declares arrays of the given size
double array[50];
// I calculate the length of the array using sizeof
double array_lenght = sizeof(array) / sizeof(array[0]);
printf("%lf \n", array_lenght);
//declares two variables of type double one for the area over which it will generate x the other for incrementing the deltaX difference
double length;
double deltaX;
// I count the differences of the domains and the value of one sample for x and display it
length = Dmax - Dmin;
deltaX = length / 50;
printf("Delta x = %lf \n", deltaX);
double i;
for(i = Dmin; i < Dmax; i+=deltaX)
{
// assigns to each element in the array the value of x increased by delta x and stores them in my array.
int k = 0;
array[k] = i;
double y = A * cos(i/B) + C * sin(i) + D;
printf("For a sample of %lf, the assigned function is %lf \n", array[k], y);
k++;
}
printf("Elements of original array: \n");
for (int i = 0; i < array_length; i++) {
printf("%lf ", array[i]);
}
</code></pre>
| [
{
"answer_id": 74256887,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 1,
"selected": false,
"text": "part"
},
{
"answer_id": 74265144,
"author": "Rajat",
"author_id": 9947159,
"author_profile": ... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17403129/"
] |
74,254,914 | <p>I am making a program for calculating a determinant of a matrix in C++ and I want to do so by using vectors, after this I will make a program that inverts a matrix, but I will do that afterwards. I don't have much experience using vectors, so I assume that I'm making a stupid mistake, here is my function:</p>
<pre><code>#include<iostream>
#include<vector>
#include<cmath>
#include<cstdlib>
int determinant(std::vector<std::vector<int>>& matrix, int x, int y) {
std::vector<std::vector<int>> minor;
int det, position;
if(x != y)
{
return 0;
}
switch (x)
{
case 2:
return (matrix[0][0]*matrix[1][1])-(matrix[1][0]*matrix[0][1]);
break;
case 1:
return matrix[0][0];
break;
}
for(postion= 0; position< x; position++)
{
int temp;
for(uint8_t i = 1; i < x; i++)
for(uint8_t j = 0; j < y; j++)
if(j != position)
minor[i-1][j] = matrix[i][j];
det += pow((-1), position+ 2) * matrix[0][position]*determinant(minor, x-1, y-1);
}
return det;
main()
{
srand(time(0));
int input;
int row, col;
std::cin >> row >> col;
std::vector<std::vector<int>> matrix;
for(uint8_t i = 0; i < row; i++)
{
std::vector<int> temp;
for(uint8_t j = 0; j < col; j++)
{
std::cin >> input;
temp.push_back(input);
}
matrix.push_back(temp);
}
std::cout << std::endl << "Determinant: " << determinant(matricx, row, col);
</code></pre>
<p>I tried making it work by using minor.pushback(matrix[i][j]), but I get an error message saying that argument types are (int) and I also get an error message saying "no instance of overload function"
Also if the name of a variable doesnt match somewhere, I was changing it manually, so maybe I forgot to change somewhere, because I named them in my native language, just so You don't think that that is an issue.</p>
| [
{
"answer_id": 74255842,
"author": "Dan ",
"author_id": 20370689,
"author_profile": "https://Stackoverflow.com/users/20370689",
"pm_score": 1,
"selected": false,
"text": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <cstdlib>\n\nint determinant(std::vector<std::vect... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74254914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14708164/"
] |
74,255,051 | <p>I am trying to use <strong>Chaquopy Plugin</strong> in my android project generated with flutter. I mean that when a flutter project is created it generates an android project app folder with it. As Chaquopy does not provide direct support for flutter so I have decided to use this in that flutter generated android app. I went through the line-by-line of Chaquopy's documentation and tried to follow all the instructions given there. But I think I missed something and it is showing errors now and not downloading the Chaquopy Plugin. I am giving my settings.gradle and other gradle files below. Please help me. I am very new to programming and that's why I don't understand these stuff much
<a href="https://chaquo.com/chaquopy/doc/current/android.html" rel="nofollow noreferrer">Here is the Chaquopy Documentation</a></p>
<h2>Here is my Settings.gradle</h2>
<pre><code>include ':app'
def localPropertiesFile = new File(rootProject.projectDir, "local.properties")
def properties = new Properties()
assert localPropertiesFile.exists()
localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) }
def flutterSdkPath = properties.getProperty("flutter.sdk")
assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle"
</code></pre>
<h2>Here is my Project level Build.gradle</h2>
<pre><code>buildscript {
ext.kotlin_version = '1.6.10'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.2.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
plugins {
id 'com.chaquo.python' version '12.0.1' apply false
}
allprojects {
repositories {
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code></pre>
<h2>Here is my App level Build.gradle</h2>
<pre><code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
plugins {
id 'com.chaquo.python'
}
android {
compileSdkVersion flutter.compileSdkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.pyflut"
minSdkVersion flutter.minSdkVersion
targetSdkVersion flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
python {
buildPython "C:/Users/super/AppData/Local/Programs/Python/Python310/python.exe"
buildPython "C:/Users/super/AppData/Local/Programs/Python/Python310/python.exe", "-3.10"
}
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
}
flutter {
source '../..'
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
</code></pre>
<h2>Finally here are my errors</h2>
<pre><code>Build file 'F:\Pyflut\android\build.gradle' line: 14
Error resolving plugin [id: 'com.chaquo.python', version: '12.0.1', apply: false]
> Could not resolve all dependencies for configuration 'detachedConfiguration1'.
> Could not determine artifacts for com.chaquo.python:com.chaquo.python.gradle.plugin:12.0.1
> Could not get resource 'https://plugins.gradle.org/m2/com/chaquo/python/com.chaquo.python.gradle.plugin/12.0.1/com.chaquo.python.gradle.plugin-12.0.1.jar'.
> Could not HEAD 'https://jcenter.bintray.com/com/chaquo/python/com.chaquo.python.gradle.plugin/12.0.1/com.chaquo.python.gradle.plugin-12.0.1.jar'.
> Read timed out
* Try:
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
* Exception is:
org.gradle.api.GradleException: Error resolving plugin [id: 'com.chaquo.python', version: '12.0.1', apply: false]
at org.gradle.plugin.use.internal.DefaultPluginRequestApplicator.resolveToFoundResult(DefaultPluginRequestApplicator.java:215)...... [Can not copy full error because of character limitaions sorry for that but if it needs then I will provide you that
</code></pre>
| [
{
"answer_id": 74255842,
"author": "Dan ",
"author_id": 20370689,
"author_profile": "https://Stackoverflow.com/users/20370689",
"pm_score": 1,
"selected": false,
"text": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <cstdlib>\n\nint determinant(std::vector<std::vect... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17143678/"
] |
74,255,055 | <p>My code show this error. I didn't use "flutter_secure_storage" dependency but it shows this error. But the app is working well, What is the reason for this and how to fix this also if didn't fix this, the effect of this error?
<a href="https://i.stack.imgur.com/r07za.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r07za.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74255842,
"author": "Dan ",
"author_id": 20370689,
"author_profile": "https://Stackoverflow.com/users/20370689",
"pm_score": 1,
"selected": false,
"text": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <cstdlib>\n\nint determinant(std::vector<std::vect... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20000775/"
] |
74,255,098 | <p>I have a <code>hash</code>, where each key has a value (an integer). What I want to do is to create a method, where I write as an argument an <code>array</code>, this <code>array</code> will have written inside the name of the different keys.</p>
<p>So once I give the <code>array</code> to the method, it will sum all the values from each element. But I am not sure how to go through my <code>array</code>, and put all the elements inside the <code>hash</code>, and then sum it, and get the total value.</p>
<p><strong>Here is my code:</strong></p>
<pre><code>DISHES_CALORIES = {
"Hamburger" => 250,
"Cheese Burger" => 300,
"Veggie Burger" => 540,
"Vegan Burger" => 350,
"Sweet Potatoes" => 230,
"Salad" => 15,
"Iced Tea" => 70,
"Lemonade" => 90
}
def poor_calories_counter(burger, side, beverage)
DISHES_CALORIES[burger] + DISHES_CALORIES[side] + DISHES_CALORIES[beverage]
end
def calories_counter(orders)
# TODO: return number of calories for a less constrained order
sum = 0
orders.each { |element| sum = sum + DISHES_CALORIES[":#{element}"] }
end
</code></pre>
| [
{
"answer_id": 74255172,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "orders.each"
},
{
"answer_id": 74259998,
"author": "Ritesh Choudhary",
"author_id": 386540,
"auth... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20211830/"
] |
74,255,114 | <p>Consider this sample. Let's say we have this structure and we want to check some state value in the <code>onChange</code> handler of an input. In this case I've used the input value to do the <code>if</code> check, and if the condition doesn't pass, we set up an error. However, when I type in 10 characters, the input doesn't trigger the if block right away, but on the next typing. I know that state changes are asynchronous, which is why we'd mostly use <code>useEffect</code>, but in this case, I cannot use it for an event handler.</p>
<p>So I am wondering what is the best way to handle this type of situations, when you need to check some state value inside an event handler and perform some actions based on that.</p>
<pre><code>import { useState } from "react";
export default function App() {
const [value, setValue] = useState("");
const [error, setError] = useState(false);
function onSubmit(event) {
event.preventDefault();
}
function onChange(event) {
if (value.length < 10) {
setValue(event.target.value);
} else {
setError(true);
}
}
return (
<form onSubmit={onSubmit}>
<input type="text" value={value} onChange={onChange} />
{error && <h2>Error triggered</h2>}
</form>
);
}
</code></pre>
| [
{
"answer_id": 74255172,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "orders.each"
},
{
"answer_id": 74259998,
"author": "Ritesh Choudhary",
"author_id": 386540,
"auth... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20373179/"
] |
74,255,141 | <p>I have a GAM with country now added as a factor, to model the relationship within countries (i think this has been done correctly, let me know if not), and now wish to plot my new model how ever my issue is an aesthetics error (seen below), if anyone knows how to correctly plot this that would be great</p>
<pre><code>! Aesthetics must be either length 1 or the same as the data (480): y
</code></pre>
<p>This is the code i have used and a snipet of my data (let me know if you need my whole dataset and i can attach it), hopefully someone is able to plot this, i think the error is coming as im not plotting the model correctly now i have added countries as a factor</p>
<p>model code;</p>
<pre><code>mod = gam(gdp_per_capita ~ s(fisheries_production_pc, k = 25, bs = 'cs') + as.factor(Country_Name),
data = economy_df,
family = gaussian(link = "log"))
#predictions
preds = predict(mod, type = 'response', se.fit = TRUE)
#plot model
plot = ggplot(economy_df, aes(y = gdp_per_capita, x = fisheries_production_pc)) +
geom_point() +
geom_line(aes(fisheries_production_pc, preds$fit), colour = 'red') +
scale_x_log10()
</code></pre>
<p>data;</p>
<pre><code>economy_df
Country_Name year gdp_per_capita fisheries_production
Albania 1997 717.3800 1110.80
Albania 1998 813.7894 2807.50
Albania 1999 1033.2425 3057.90
Albania 2000 1126.6833 3635.00
Albania 2001 1281.6598 3597.20
Albania 2002 1425.1242 4516.80
Bosnia 1997 982.8018 253.00
Bosnia 1998 1102.3907 254.00
Bosnia 1999 1251.7476 255.00
Bosnia 2000 1484.1761 255.00
Bosnia 2001 1544.6021 255.00
Croatia 1997 5312.3695 20551.49
Croatia 1998 5691.1095 27935.08
Croatia 1999 5246.9360 25222.19
Croatia 2000 4887.7137 27944.24
Croatia 2001 5412.9251 29019.12
Cyprus 1997 14234.2441 25788.00
Cyprus 1998 15092.8262 20482.00
Cyprus 1999 15287.9189 41060.00
Cyprus 2000 14388.3477 70223.00
</code></pre>
| [
{
"answer_id": 74255172,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "orders.each"
},
{
"answer_id": 74259998,
"author": "Ritesh Choudhary",
"author_id": 386540,
"auth... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18338223/"
] |
74,255,151 | <p>I am trying to unfreeze my player rotation and then freeze it again. It unfreezes but due to some reason I cannot freeze the rotation again.</p>
<p>GameManager script -</p>
<pre><code> public void enableRotation()
{
if (CompareTag("Player"))
{
rb.freezeRotation = true;
}
}
</code></pre>
<p>flyer_Off script -</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class flyer_Off : MonoBehaviour
{
void OnTriggerEnter(Collider other)
{
FindObjectOfType<GameManager>().enableRotation();
}
}
</code></pre>
<p>I was able to unfreeze rotation the same way but for some reason it's not working when I try to freeze it again.</p>
<p>I tried adding the GameManager script to Player and flyer_Off to cube with box collider on trigger and player as well.</p>
<p>I can add if anymore info is needed.</p>
<p>Thank you</p>
| [
{
"answer_id": 74255172,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "orders.each"
},
{
"answer_id": 74259998,
"author": "Ritesh Choudhary",
"author_id": 386540,
"auth... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20266306/"
] |
74,255,173 | <p>I want to generate data using random numbers and then generate random samples with replacement using the generated data. The problem is that using <code>random.seed(10)</code> only fixes the initial random numbers for the generated data but it does not fix the random samples generated inside the loop, everytime I run the code I get the same generated data but different random samples and I would like to get the same random samples in order to get reproducible results. The code is the following:</p>
<pre><code>import numpy as np
import random
np.random.seed(10)
data = list(np.random.binomial(size = 215 , n=1, p= 0.3))
sample_mean = []
for i in range(1000):
sample = random.choices(data, k=215)
mean = np.mean(sample)
sample_mean.append(mean)
print(np.mean(sample_mean))
</code></pre>
<p><code>np.mean(sample_mean)</code> should retrieve the same value every time the code is ran but it does not happen.</p>
<p>I tried typing random.seed(i) inside the loop but it didn't work.</p>
| [
{
"answer_id": 74255307,
"author": "Ahmed AEK",
"author_id": 15649230,
"author_profile": "https://Stackoverflow.com/users/15649230",
"pm_score": 2,
"selected": false,
"text": "random.choices(data, k=215)"
},
{
"answer_id": 74255309,
"author": "ShlomiF",
"author_id": 50245... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20372685/"
] |
74,255,201 | <p>I have a top down game and I need the player to be rendered below the bottom walls, and above the top walls, and my solution would be to set the depth of individual tiles in the tilemap by the tile ID. I can't use anything involving tiled, because my game will be procedurally generated. Maybe something similar to this:</p>
<pre><code>this.wallLayer.forEachTile((tile)=>{
if(tile.id === 1){
tile.setDepth(1)
}
if(tile.id === 2){
tile.setDepth(3)
}
})
</code></pre>
<p>if there is a similar method I could use, it would be great if someone could point me in the right direction. Thanks!</p>
| [
{
"answer_id": 74256267,
"author": "winner_joiner",
"author_id": 1679286,
"author_profile": "https://Stackoverflow.com/users/1679286",
"pm_score": 2,
"selected": true,
"text": "replaceByIndex"
},
{
"answer_id": 74256302,
"author": "caTS",
"author_id": 18244921,
"autho... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16773979/"
] |
74,255,207 | <p>I used ch unit for my width. I was just wondering why does the second p does not automatically line break after 10ch. The 0 is maximizing the width of my screen instead of breaking just like the first p with the lorem text.</p>
<p>Here is the HTML and CSS Code:</p>
<pre class="lang-html prettyprint-override"><code><html>
<head>
<title>Practice</title>
<style>
.ch-unit {
background-color: red;
width: 10ch;
}
</style>
</head>
<body>
<div class="ch-unit">
<p>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Deleniti,
saepe ad? Iure corrupti laborum pariatur, eos amet officia deserunt sit
quasi quam provident facere eum commodi! Vel soluta eum fugiat.
</p>
<p>
0000000000000000000000000000000000000000000000000000000000000000000000
</p>
</div>
</body>
</html>
</code></pre>
<p><a href="https://i.stack.imgur.com/nkaCU.png" rel="nofollow noreferrer">Here is the screenshot</a></p>
| [
{
"answer_id": 74255240,
"author": "NeNaD",
"author_id": 14389830,
"author_profile": "https://Stackoverflow.com/users/14389830",
"pm_score": 2,
"selected": true,
"text": "word-break: break-word;"
},
{
"answer_id": 74255243,
"author": "A Haworth",
"author_id": 10867454,
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20120341/"
] |
74,255,230 | <p>I'm desperately trying to adhere to the MVVM design pattern in my App. So I'm trying to use the <code>EventToCommandBehavior</code> behavior from the MCT. (I'm also using the CommunityToolkit.Mvvm for <code>[RelayCommand]</code>) I've attached it to an <code>Entry</code> and am trying to forward the TextChanged event to my command. However, my command doesn't execute.</p>
<p>XAML:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
x:Class="MyApp.View.Accounts.AddAccountPage"
xmlns:viewmodel="clr-namespace:MyApp.ViewModel.AccountsViewModel"
Title="Add Account">
<VerticalStackLayout>
<Entry x:Name="entryAccountName"
Placeholder="Account Name"
PlaceholderColor="Black"
TextColor="{StaticResource Tertiary}"
BackgroundColor="{StaticResource Primary}"
WidthRequest="125"
HorizontalOptions="Center"
Keyboard="Text"
ClearButtonVisibility="WhileEditing"
ReturnType="Next">
<Entry.Behaviors>
<toolkit:EventToCommandBehavior
EventName="TextChanged"
Command="{Binding AccountTextChangedCommand}" />
</Entry.Behaviors>
</Entry>
....More XAML....
</code></pre>
<p>AccountsViewModel code:</p>
<pre><code> [RelayCommand]
public void AccountTextChanged()
{
Application.Current.MainPage.DisplayAlert("Text changed", "Account Text Changed", "OK");
}
</code></pre>
<p>I've got a breakpoint set to the Method and it just never gets called. Any ideas as to what am I doing wrong?</p>
| [
{
"answer_id": 74255810,
"author": "XJonOneX",
"author_id": 1277304,
"author_profile": "https://Stackoverflow.com/users/1277304",
"pm_score": 0,
"selected": false,
"text": "using MyApp.Services;\nusing MyApp.ViewModel.AccountsViewModel;\n\nnamespace MyApp.View.Accounts;\n\npublic partial... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1277304/"
] |
74,255,249 | <p>I'm having trouble showing an image using <code>div</code> in react js. the path is correct because I can display it using an <code>img</code> tag.</p>
<p><strong>I can't use the <code>import</code> method because the filename is going to be taken from a database table.</strong></p>
<p>this is my code: (<a href="https://codesandbox.io/s/infallible-frost-jd1f9c?file=/src/components/Test.js:0-623" rel="nofollow noreferrer">Sandbox</a>)</p>
<p><strong>App.js</strong></p>
<pre><code>import "./styles.css";
import Test from "./components/Test";
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<Test />
</div>
);
}
</code></pre>
<p><strong>./components/Test.js</strong></p>
<pre><code>import img1 from "../assets/images/sandwich.jpg";
const Test = () => {
return (
<div>
<p>This uses the img tag</p>
<img
src={img1}
style={{ width: "100px", height: "100px" }}
alt="an img tag"
/>
<p>And this uses a div with backgroundImage</p>
<div
style={{
backgroundImage: `url("../assets/images/sandwich.jpg")`,
backgroundSize: "cover",
backgroundPosition: "center",
width: "200px",
height: "200px",
border: "1px solid black"
}}
></div>
</div>
);
};
export default Test;
</code></pre>
| [
{
"answer_id": 74255379,
"author": "MegaMindTheCoder",
"author_id": 19312990,
"author_profile": "https://Stackoverflow.com/users/19312990",
"pm_score": 1,
"selected": false,
"text": "import img1 from \"../assets/images/sandwich.jpg\";\n\nconst Test = () => {\n return (\n <div>\n ... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1235167/"
] |
74,255,270 | <p>The PDF content below renders with the correct vertical positions, but how?</p>
<pre><code>1 0 0 -1 0 792 cm
q
.75 0 0 .75 72 192.75 cm
BT
/F4 14.666667 Tf
1 0 0 -1 0 .80265617 Tm
0 -13.2773438 Td <0030> Tj
12.2087708 0 Td <0024> Tj
8.6870575 0 Td <003C> Tj
9.7756042 0 Td <0032> Tj
11.4001007 0 Td <0035> Tj
ET
Q
q
.75 0 0 .75 72 222.75 cm
BT
/F4 14.666667 Tf
1 0 0 -1 4.0719757 .80265617 Tm
0 -13.2773438 Td <002C> Tj
4.0719757 0 Td <0003> Tj
4.0719757 0 Td <0057> Tj
4.0719757 0 Td <004B> Tj
8.1511078 0 Td <004C> Tj
3.2561493 0 Td <0051> Tj
8.1511078 0 Td <004E> Tj
ET
Q
</code></pre>
<p>Renders correctly:</p>
<pre><code>MAJOR
I think
</code></pre>
<p>However I can't understand how the y positions are calculated to do this (x is fine). The Text Rendering Matrix (TRM) is given by Text Matrix (TM) multiplied by Current Transformation Matrix (CTM) <em>PDF1.7 Reference section 9.4.4</em>. CTM is the identity matrix multiplied by each "cm" operation.</p>
<p>So for the first snippet,</p>
<pre><code>CTM = [1 0 0 -1 0 792] x [0.75 0 0 0.75 72 192.75] = [0.75 0 0 -0.75 72 786.75]
</code></pre>
<p>TRM is TM x CTM:</p>
<pre><code>TRM = [1 0 0 -1 0 0.8026] x [0.75 0 0 -0.75 72 786.75] = [0.75 0 0 0.75 72 786.1]
</code></pre>
<p>So, ignoring small details, the text will be rendered around y = 786 (actually 776 I reckon)</p>
<p>For the second snippet,</p>
<pre><code>CTM = [1 0 0 -1 0 792] x [0.75 0 0 0.75 72 222.75] = [0.75 0 0 -0.75 72 816.75]
TRM = [1 0 0 -1 4.072 0.802] x [0.75 0 0 -0.75 72 816.75] = [0.75 0 0 0.75 75.05 816.4]
</code></pre>
<p>Again, ignoring small details, the text will be rendered around y = 816 (actually 806 I reckon)</p>
<p>But the y origin is the bottom of the page, and 816 is greater than 786. So how come the second snippet of text renders correctly below the first? I'm clearly missing something in the calculations, but I can't see what. Any ideas?</p>
| [
{
"answer_id": 74256737,
"author": "K J",
"author_id": 10802527,
"author_profile": "https://Stackoverflow.com/users/10802527",
"pm_score": 0,
"selected": false,
"text": "0 792 cm"
},
{
"answer_id": 74257212,
"author": "mkl",
"author_id": 1729265,
"author_profile": "ht... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9855230/"
] |
74,255,282 | <p>I set the following rule in my .htaccess file to redirect example.com/index.php to example.com</p>
<pre><code>RewriteCond %{THE_REQUEST} ^.*/index\.php
RewriteRule ^(.*)index.php$ /$1 [R=301,L]
</code></pre>
<p>Then I set my canonical as following in the header.php for all pages:</p>
<pre><code><link rel="canonical" href="https://www.example.com<?php echo $_SERVER['PHP_SELF']; ?>" />
</code></pre>
<p>However I noticed the canonical url sets to index.php instead of the root.</p>
| [
{
"answer_id": 74300039,
"author": "Tural Rzaxanov",
"author_id": 9922647,
"author_profile": "https://Stackoverflow.com/users/9922647",
"pm_score": 3,
"selected": true,
"text": " <link rel=\"canonical\" href=\"https://www.example.com<?=$_SERVER['REQUEST_URI']?>\" />\n"
}
] | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4779281/"
] |
74,255,315 | <p>I was able to build and publish my flutter app on <code>October 6th</code>, I returned today on <code>Octuber 30th</code> and I am getting this build error:</p>
<ul>
<li><code>Could not resolve io.grpc:grpc-core:[1.28.0].</code></li>
<li><code>Could not HEAD 'https://jcenter.bintray.com/io/grpc/grpc-core/maven-metadata.xml'.</code></li>
<li><code>Read timed out</code></li>
</ul>
<p>It seems there is an issue with <code>cloud_firestore</code> somehow it's still trying to read from jcenter which I am informed that it's down and not supporting new repositories, but the issue is that I have not changed a single line nor updated any packages since my last publish and build, what caused this issue?</p>
<p>I remember I had a similar issue a few months ago but everything was fixed after I replaced jcenter with mavenCentral, but this time it's back again.</p>
<pre><code>Launching lib\main.dart on Android SDK built for x86 in debug mode...
FAILURE: Build failed with an exception.
* What went wrong:
Could not determine the dependencies of task ':app:processDebugResources'.
> Could not resolve all task dependencies for configuration ':app:debugRuntimeClasspath'.
> Could not resolve io.grpc:grpc-core:[1.28.0].
Required by:
project :app > project :cloud_firestore > com.google.firebase:firebase-firestore:21.7.1 > io.grpc:grpc-android:1.28.0
project :app > project :cloud_firestore > com.google.firebase:firebase-firestore:21.7.1 > io.grpc:grpc-okhttp:1.28.0
> Failed to list versions for io.grpc:grpc-core.
> Unable to load Maven meta-data from https://jcenter.bintray.com/io/grpc/grpc-core/maven-metadata.xml.
> Could not HEAD 'https://jcenter.bintray.com/io/grpc/grpc-core/maven-metadata.xml'.
> Read timed out
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 1m 37s
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)
</code></pre>
<p>This is my <code>build.gradle</code>:</p>
<pre><code>buildscript {
ext.kotlin_version = '1.3.50'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.2'
classpath 'com.google.gms:google-services:4.3.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code></pre>
<p>Yes, my app is pretty old, since I have yet to update to null-safety.</p>
<p>Any tips to avoid this issue in the future?</p>
<p>How do I solve this current issue?</p>
| [
{
"answer_id": 74256311,
"author": "Florian Knoll",
"author_id": 17716042,
"author_profile": "https://Stackoverflow.com/users/17716042",
"pm_score": 1,
"selected": false,
"text": " Could not HEAD 'https://jcenter.bintray.com/com/stripe/stripe-android/maven-metadata.xml'.\n > R... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12950588/"
] |
74,255,336 | <p>I want to stop the model at a specific model time.</p>
<p>Do I have to work with a counter variable per time and then throw <code>stopSimulation()</code> or is there another possibility? My simulation will run for one week in model time. I want to stop the simulation 5min before it will end, so 5min before one week of model time is over.</p>
| [
{
"answer_id": 74255496,
"author": "Yossi Benagou",
"author_id": 18366972,
"author_profile": "https://Stackoverflow.com/users/18366972",
"pm_score": 2,
"selected": false,
"text": "Simulation:main"
}
] | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20346372/"
] |
74,255,351 | <p>I have a dataset with statistics by region. I would like to build several other city datasets based on this dataset. At the same time, when creating in each such set, I would like to add a column with the name of the city.</p>
<p>That is, from one data set, I would like to receive three.</p>
<p>I'll give you an example. Initial dataset:</p>
<pre><code>df
date name_region
2022-01-01 California
2022-01-02 California
2022-01-03 California
</code></pre>
<p>Next, I have a list with cities: <code> city_list = ['Los Angeles', 'San Diego', 'San Jose']</code></p>
<p>As an output, I want to have 3 datasets (or more, depending on the number of items in the list):</p>
<pre><code>df_city_1
date name_region city
2022-01-01 California Los Angeles
2022-01-02 California Los Angeles
2022-01-03 California Los Angeles
</code></pre>
<pre><code>df_city_2
date name_region city
2022-01-01 California San Diego
2022-01-02 California San Diego
2022-01-03 California San Diego
</code></pre>
<pre><code>df_city_3
date name_region city
2022-01-01 California San Jose
2022-01-02 California San Jose
2022-01-03 California San Jose
</code></pre>
<p>It would be ideal if, at the same time, the data set could be accessed by a key determined by an element in the list:</p>
<pre><code>df_city['Los Angeles']
date name_region city
2022-01-01 California Los Angeles
2022-01-02 California Los Angeles
2022-01-02 California Los Angeles
</code></pre>
<p>How can I do that? I found only a way of this division into several data sets, when the original set already has information on the unique values of the column (in this case, the same cities), , but this does not suit me very well.</p>
| [
{
"answer_id": 74255371,
"author": "ouroboros1",
"author_id": 18470692,
"author_profile": "https://Stackoverflow.com/users/18470692",
"pm_score": 3,
"selected": true,
"text": "dictionary comprehension"
},
{
"answer_id": 74255428,
"author": "PaulS",
"author_id": 11564487,
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14744714/"
] |
74,255,355 | <p>So my book is explaining me pointers to an array using ts example</p>
<pre><code>#include <stdio.h>
int main()
{
int s[4][2] = {
{1234,56},{1212,33},{1434,80},{1312,78}
};
int(*p)[2];
int i, j, * pint;
for (i = 0; i <= 3; i++)
{
p = &s[i];
pint = (int*)p;
printf("\n");
for (j = 0; j<= 1; j++)
{
printf("%d ", *(pint + j));
}
}
return 0;
}
</code></pre>
<p>The output is Given as</p>
<pre><code>1234 56
1212 33
1434 80
1312 78
</code></pre>
<p>No issue I am getting the same output.<br />
My question is <strong>what was the need of using another pointer <em>pint</em> ?</strong>
Why can't we directly use <em><strong>P</strong></em>?</p>
<p>So When I tried to do it using <em><strong>P</strong></em> directly it <em>didn't work</em></p>
<pre><code>printf("%d ", *(p + j));
</code></pre>
<p>I got garbage values in output, <em>Why is this happening?</em><br />
I also tried printing <em><strong>p</strong></em> and <em><strong>pint</strong></em> they are the same.</p>
| [
{
"answer_id": 74255371,
"author": "ouroboros1",
"author_id": 18470692,
"author_profile": "https://Stackoverflow.com/users/18470692",
"pm_score": 3,
"selected": true,
"text": "dictionary comprehension"
},
{
"answer_id": 74255428,
"author": "PaulS",
"author_id": 11564487,
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18246254/"
] |
74,255,356 | <p>I am now trying to create a form on NextJs 13 (Typescript) with Formik. The form that I created doesn't work then I tried adding the example code snippets from <code>Formik</code> as you could see below. Both the form I created and Formik's examples are only returning <code>TypeError: React.createContext is not a function</code> in console. I could see this <code>(sc_server)/./node_modules/formik/dist/formik.cjs.development.js</code> in another line of console error.</p>
<pre><code>import * as React from 'react';
import {
Formik,
FormikHelpers,
FormikProps,
Form,
Field,
FieldProps,
} from 'formik';
interface MyFormValues {
firstName: string;
}
export const MyApp: React.FC<{}> = () => {
const initialValues: MyFormValues = { firstName: '' };
return (
<div>
<h1>My Example</h1>
<Formik
initialValues={initialValues}
onSubmit={(values, actions) => {
console.log({ values, actions });
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}}
>
<Form>
<label htmlFor="firstName">First Name</label>
<Field id="firstName" name="firstName" placeholder="First Name" />
<button type="submit">Submit</button>
</Form>
</Formik>
</div>
);
};
</code></pre>
<p>I imported above component in /app/page.tsx as the following.</p>
<pre><code>import { MyApp } from '../components/form/MyApp';
export default function Home() {
return (
<div>
<MyApp />
</div>
);
}
</code></pre>
| [
{
"answer_id": 74314103,
"author": "ARDIANSYAH PUTRA - A2RJ",
"author_id": 14898711,
"author_profile": "https://Stackoverflow.com/users/14898711",
"pm_score": 2,
"selected": false,
"text": "use client"
},
{
"answer_id": 74442490,
"author": "Mirado Andria",
"author_id": 10... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20262524/"
] |
74,255,365 | <p>My instructions are:
You are going to write a tip-calculating program that does the following:</p>
<ul>
<li>Asks the user to enter the subtotal of a restaurant bill</li>
<li>Asks the user if they wish to enter a tip and if they do, let them choose to enter the tip by a specific amount, or by percentage of the subtotal.</li>
<li>Display the receipt: Subtotal, Taxed Owed (13%), Tip, Final Total</li>
</ul>
<p>I feel like I have too many print statements. How can I make it so there is one that works for all of them?</p>
<pre class="lang-py prettyprint-override"><code>subtotal= float(input("Please enter the subtotal of your bill:"))
print("\nPlease select an option:")
print("1. Enter tip percentage (%)")
print("2. Enter tip amount ($)")
print("3. No tip")
choice= float(input("How would you like to tip?"))
tax= subtotal*0.13
if choice == 1:
tip_percentage= float(input("Please enter the percentage you would like to tip (%):"))
if tip_percentage > 0:
percent_decimal= tip_percentage/100
tip_1= subtotal*percent_decimal
finaltotal_1= subtotal + tax + tip_1
if subtotal > 0:
print("\nSubtotal:", (round(subtotal,2)))
print("Tax Owed:", (round(tax,2)))
print("Tip:", (round(tip_1,2)))
print("Final total:", (round(finaltotal_1,2)))
else:
print("Please try again.")
if choice == 2:
tip_2= float(input("Please enter the tip amount:"))
if tip_2 > 0:
finaltotal_2= subtotal + tax + tip_2
if subtotal>0 and tip_2>0:
print("\nSubtotal:", (round(subtotal,2)))
print("Tax Owed:", (round(tax,2)))
print("Tip:", (round(tip_2,2)))
print("Final total:", (round(finaltotal_2,2)))
else:
print("Please try again.")
if choice == 3:
tip_3= 0
finaltotal_3= subtotal + tax + tip_3
if subtotal>0:
print("\nSubtotal:", (round(subtotal,2)))
print("Tax Owed:", (round(tax,2)))
print("Tip:", (round(tip_3,2)))
print("Final total:", (round(finaltotal_3,2)))
else:
print("Please try again.")
</code></pre>
| [
{
"answer_id": 74314103,
"author": "ARDIANSYAH PUTRA - A2RJ",
"author_id": 14898711,
"author_profile": "https://Stackoverflow.com/users/14898711",
"pm_score": 2,
"selected": false,
"text": "use client"
},
{
"answer_id": 74442490,
"author": "Mirado Andria",
"author_id": 10... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20277384/"
] |
74,255,384 | <p>For example, if I had this list of invalid characters:</p>
<pre><code>invalid_char_list = [',', '.', '!']
</code></pre>
<p>And this list of strings:</p>
<pre><code>string_list = ['Hello,', 'world.', 'I', 'am', 'a', 'programmer!!']
</code></pre>
<p>I would want to get this new list:</p>
<pre><code>new_string_list = ['Hello', 'world', 'I', 'am', 'a', 'programmer']
</code></pre>
<p>withouth <code>,</code> or <code>.</code> or <code>!</code> in any of the strings in the list because those are the characters that are in my list of invalid characters.</p>
| [
{
"answer_id": 74255432,
"author": "E Joseph",
"author_id": 18011737,
"author_profile": "https://Stackoverflow.com/users/18011737",
"pm_score": 1,
"selected": true,
"text": "invalid_char_list = [',', '.', '!']\nstring_list = ['Hello,', 'world.', 'I', 'am', 'a', 'programmer!!']\n\nfor inv... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19810733/"
] |
74,255,406 | <p>I have a custom user model and a form that allows admins to add users without having to go to the admin section. I want hide the password fields and set the password to a random generated string. Then send an email to the new user with a link to reset their password.</p>
<p>So far I haven't been able to figure out the first part - hiding the password fields.</p>
<p>The form.py:</p>
<pre><code>from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class AddCompanyEmployeeForm(UserCreationForm):
class Meta:
model = CustomUser
fields = UserCreationForm.Meta.fields + ('email', 'full_name', 'age')
</code></pre>
<p>the view:</p>
<pre><code>from django.views.generic import CreateView, ListView
from django.urls.base import reverse
from .forms import CustomUserCreationForm, AddCompanyEmployeeForm
from .models import CustomUser
class SignUpView(CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy('login')
template_name = 'registration/signup.html'
class AddCompanyEmployee(CreateView):
model = CustomUser
template_name = 'manage/add_employee.html'
form_class = AddCompanyEmployeeForm
#success_url = reverse_lazy('directory')
def get_success_url(self):
return reverse('userprofile_detail', kwargs={'pk': self.object.userprofile.pk})
</code></pre>
<p>The custom user model:</p>
<pre><code>from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import Group
from django.contrib import admin
from django.db.models import Count
from django.db.models.signals import post_save
class CustomUser(AbstractUser):
full_name = models.CharField(max_length=250, null=True)
age = models.PositiveIntegerField(null=True, blank=True)
employee_type = models.ForeignKey(Group, null=True, on_delete=models.SET_NULL, default=1)
employee_start_date = models.DateField(null=True, blank=True)
is_active = models.BooleanField(null=False, default=True)
</code></pre>
<p>I have tried a number of approaches including changing the form to</p>
<pre><code>class AddCompanyEmployeeForm(UserCreationForm):
class Meta:
model = CustomUser
fields = ('email', 'full_name', 'age')
</code></pre>
<p>So far the password fields continue to be visible regardless of what I try. Any suggestions?</p>
| [
{
"answer_id": 74255432,
"author": "E Joseph",
"author_id": 18011737,
"author_profile": "https://Stackoverflow.com/users/18011737",
"pm_score": 1,
"selected": true,
"text": "invalid_char_list = [',', '.', '!']\nstring_list = ['Hello,', 'world.', 'I', 'am', 'a', 'programmer!!']\n\nfor inv... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16063250/"
] |
74,255,491 | <p>I'm working with the System.Text.Json serializer, and need to provide custom serialization logic for one property of my overall object. That's not the issue, it's working, but I don't understand how. This is the sample provided in the MS docs.</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/converters-how-to?pivots=dotnet-6-0#registration-sample---converters-collection" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/converters-how-to?pivots=dotnet-6-0#registration-sample---converters-collection</a></p>
<pre class="lang-cs prettyprint-override"><code>var serializeOptions = new JsonSerializerOptions
{
WriteIndented = true,
Converters =
{
new DateTimeOffsetJsonConverter()
}
};
jsonString = JsonSerializer.Serialize(weatherForecast, serializeOptions);
</code></pre>
<p>Best I can tell, the Converters property only implements a getter.</p>
<p><a href="https://i.stack.imgur.com/QfPei.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QfPei.png" alt="Hover description in VSCode" /></a></p>
<p>Here's the decompiled code I get with a Go To Definition.</p>
<pre class="lang-cs prettyprint-override"><code> // Summary:
// Gets the list of user-defined converters that were registered.
//
// Returns:
// The list of custom converters.
public IList<Serialization.JsonConverter> Converters { get; }
</code></pre>
<p>And, what I think is the original code.</p>
<p><a href="https://github.com/dotnet/runtime/blob/main/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Converters.cs#L23" rel="nofollow noreferrer">https://github.com/dotnet/runtime/blob/main/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Converters.cs#L23</a></p>
<p>What magick explains this?</p>
| [
{
"answer_id": 74255681,
"author": "Etienne de Martel",
"author_id": 71141,
"author_profile": "https://Stackoverflow.com/users/71141",
"pm_score": 3,
"selected": true,
"text": "Converters"
},
{
"answer_id": 74255728,
"author": "Oliver",
"author_id": 1838048,
"author_p... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237012/"
] |
74,255,520 | <p>I have a table <code>source</code>:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>data</th>
</tr>
</thead>
<tbody>
<tr>
<td>{ "results": { "rows": [ { "title": "A", "count": 61 }, { "title": "B", "count": 9 } ] }}</td>
</tr>
<tr>
<td>{ "results": { "rows": [ { "title": "C", "count": 43 } ] }}</td>
</tr>
</tbody>
</table>
</div>
<p>And I want a table <code>dest</code>:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>title</th>
<th>count</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>61</td>
</tr>
<tr>
<td>B</td>
<td>9</td>
</tr>
<tr>
<td>C</td>
<td>43</td>
</tr>
</tbody>
</table>
</div>
<p>I found there is <a href="https://docs.singlestore.com/managed-service/en/reference/sql-reference/json-functions/json_to_array.html" rel="nofollow noreferrer">JSON_TO_ARRAY</a> function that might be helpful, but got stuck how to apply it.</p>
<p>How to correctly flatten the json array from the table?</p>
| [
{
"answer_id": 74257126,
"author": "user19416376",
"author_id": 19416376,
"author_profile": "https://Stackoverflow.com/users/19416376",
"pm_score": 1,
"selected": false,
"text": " With t as (\nselect table_col AS title FROM json_tab join TABLE(JSON_TO_ARRAY(jsondata::results::rows)))\... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8189903/"
] |
74,255,536 | <p>I cant seem to get the nav bar items to align to the center even if I set the align-items value to center, I cant seem to find any part of code which commands the nav bar items to stick to the right either!</p>
<p>I need a solution to this</p>
<pre><code>@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}
nav {
display: flex;
height: 80px;
width: 100%;
background: #1b1b1b;
align-items: center;
justify-content: space-between;
padding: 0 50px 0 100px;
flex-wrap: wrap;
}
nav .logo {
color: #fff;
font-size: 35px;
font-weight: 600;
}
nav ul {
display: flex;
align-items: center;
flex-wrap: wrap;
list-style: none;
}
nav ul li {
margin: 0 5px;
}
nav ul li a {
color: #f2f2f2;
text-decoration: none;
font-size: 18px;
font-weight: 500;
padding: 8px 15px;
border-radius: 5px;
letter-spacing: 1px;
transition: all 0.3s ease;
}
nav ul li a:hover {
color: #111;
background: #fff;
}
nav .menu-btn i{
color: #fff;
font-size: 22px;
cursor: pointer;
display: none;
}
input[type="checkbox"] {
display: none;
}
@media (max-width: 1000px) {
nav{
padding: 0 40px 0 50px;
}
}
@media (max-width: 920px) {
nav .menu-btn i{
display: block;
}
#click:checked ~ .menu-btn i:before {
content: "\f00d";
}
nav ul {
position: fixed;
top: 80px;
left: -100%;
background: #111;
height: 100vh;
width: 100%;
text-align: center;
display: block;
transition: all 0.3s ease;
}
#click:checked ~ ul {
left: 0;
}
nav ul li {
width: 100%;
margin: 40px 0;
}
nav ul li a {
width: 100%;
margin-left: -100%;
display: block;
font-size: 20px;
transition: 0.6s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}
#click:checked ~ ul li a {
margin-left: 0px;
}
nav ul li a:hover {
background: none;
color: cyan;
}
}
.content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
z-index: -1;
width: 100%;
padding: 0 30px;
color: #1b1b1b;
}
.content div {
font-size: 40px;
font-weight: 700;
}
</code></pre>
<p>That's my CSS code, I tried to do what I could but I cant fix the problem</p>
| [
{
"answer_id": 74255619,
"author": "Shreyansh Gupta",
"author_id": 18046485,
"author_profile": "https://Stackoverflow.com/users/18046485",
"pm_score": -1,
"selected": false,
"text": "nav{\n/*...*/\njustify-content:center;\n/*...*/\n}\n"
},
{
"answer_id": 74256420,
"author": "... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20369381/"
] |
74,255,549 | <p>When I'm using</p>
<pre><code>ticker = "MSFT"
stock = yf.Ticker('MSFT').history('5y')
stock
</code></pre>
<p>I get a dataframe in response</p>
<p>When I use</p>
<pre><code>ticker = "MSFT"
stock_info = yf.Ticker(ticker).info
stock_info
</code></pre>
<p>I'm receiving a list from Yahoo finance API. How can I transform this list to a Dataframe in Pandas?
So I could use</p>
<pre><code>stock.to_csv(folder + ticker + ".csv") => Working with 'history' data
stock_info.to_csv(folder + ticker + ".csv") => Not working with 'info' data because it's a list not a dataframe.
</code></pre>
<p>How can I save yf.Ticker(ticker).info data to a csv?</p>
<p><a href="https://i.stack.imgur.com/24NW0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/24NW0.png" alt="enter image description here" /></a></p>
<pre><code>ticker = "MSFT"
stock_info = yf.Ticker(ticker).info
stock_info
stock_info.to_csv(folder + ticker + ".csv")
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In [158], line 4
2 stock_info = yf.Ticker(ticker).info
3 stock_info
----> 4 stock_info.to_csv(folder + ticker + ".csv")
AttributeError: 'dict' object has no attribute 'to_csv'
ticker = "MSFT"
stock_info = yf.Ticker(ticker).info
stock_info
{'zip': '98052-6399',
'sector': 'Technology',
'fullTimeEmployees': 221000,
'longBusinessSummary': 'Microsoft Corporation develops, licenses, and supports software, services, devices, and solutions worldwide. The company operates in three segments: Productivity and Business Processes, Intelligent Cloud, and More Personal Computing. The Productivity and Business Processes segment offers Office, Exchange, SharePoint, Microsoft Teams, Office 365 Security and Compliance, Microsoft Viva, and Skype for Business; Skype, Outlook.com, OneDrive, and LinkedIn; and Dynamics 365, a set of cloud-based and on-premises business solutions for organizations and enterprise divisions. The Intelligent Cloud segment licenses SQL, Windows Servers, Visual Studio, System Center, and related Client Access Licenses; GitHub that provides a collaboration platform and code hosting service for developers; Nuance provides healthcare and enterprise AI solutions; and Azure, a cloud platform. It also offers enterprise support, Microsoft consulting, and nuance professional services to assist customers in developing, deploying, and managing Microsoft server and desktop solutions; and training and certification on Microsoft products. The More Personal Computing segment provides Windows original equipment manufacturer (OEM) licensing and other non-volume licensing of the Windows operating system; Windows Commercial, such as volume licensing of the Windows operating system, Windows cloud services, and other Windows commercial offerings; patent licensing; and Windows Internet of Things. It also offers Surface, PC accessories, PCs, tablets, gaming and entertainment consoles, and other devices; Gaming, including Xbox hardware, and Xbox content and services; video games and third-party video game royalties; and Search, including Bing and Microsoft advertising. The company sells its products through OEMs, distributors, and resellers; and directly through digital marketplaces, online stores, and retail stores. Microsoft Corporation was founded in 1975 and is headquartered in Redmond, Washington.',
'city': 'Redmond',
'phone': '425 882 8080',
'state': 'WA',
'country': 'United States',
'companyOfficers': [],
'website': 'https://www.microsoft.com',
'maxAge': 1,
'address1': 'One Microsoft Way',
'fax': '425 706 7329',
'industry': 'Software—Infrastructure',
'ebitdaMargins': 0.48672,
'profitMargins': 0.34366,
'grossMargins': 0.6826,
'operatingCashflow': 87693000704,
'revenueGrowth': 0.106,
'operatingMargins': 0.41691002,
'ebitda': 98841001984,
'targetLowPrice': 255,
'recommendationKey': 'buy',
'grossProfits': 135620000000,
'freeCashflow': 46155874304,
...
'dayHigh': 236.6,
'coinMarketCapLink': None,
'regularMarketPrice': 235.87,
'preMarketPrice': None,
'logo_url': 'https://logo.clearbit.com/microsoft.com'}
</code></pre>
<p>I don't understand how I can change this list into something I can write to CSV</p>
<pre><code>{'zip': '98052-6399',
'sector': 'Technology',
'fullTimeEmployees': 221000,
'longBusinessSummary': 'Microsoft Corporation develops, licenses, and supports software, services, devices, and solutions worldwide. The company operates in three segments: Productivity and Business Processes, Intelligent Cloud, and More Personal Computing. The Productivity and Business Processes segment offers Office, Exchange, SharePoint, Microsoft Teams, Office 365 Security and Compliance, Microsoft Viva, and Skype for Business; Skype, Outlook.com, OneDrive, and LinkedIn; and Dynamics 365, a set of cloud-based and on-premises business solutions for organizations and enterprise divisions. The Intelligent Cloud segment licenses SQL, Windows Servers, Visual Studio, System Center, and related Client Access Licenses; GitHub that provides a collaboration platform and code hosting service for developers; Nuance provides healthcare and enterprise AI solutions; and Azure, a cloud platform. It also offers enterprise support, Microsoft consulting, and nuance professional services to assist customers in developing, deploying, and managing Microsoft server and desktop solutions; and training and certification on Microsoft products. The More Personal Computing segment provides Windows original equipment manufacturer (OEM) licensing and other non-volume licensing of the Windows operating system; Windows Commercial, such as volume licensing of the Windows operating system, Windows cloud services, and other Windows commercial offerings; patent licensing; and Windows Internet of Things. It also offers Surface, PC accessories, PCs, tablets, gaming and entertainment consoles, and other devices; Gaming, including Xbox hardware, and Xbox content and services; video games and third-party video game royalties; and Search, including Bing and Microsoft advertising. The company sells its products through OEMs, distributors, and resellers; and directly through digital marketplaces, online stores, and retail stores. Microsoft Corporation was founded in 1975 and is headquartered in Redmond, Washington.',
'city': 'Redmond',
'phone': '425 882 8080',
'state': 'WA',
'country': 'United States',
'companyOfficers': [],
'website': 'https://www.microsoft.com',
'maxAge': 1,
'address1': 'One Microsoft Way',
'fax': '425 706 7329',
'industry': 'Software—Infrastructure',
'ebitdaMargins': 0.48672,
'profitMargins': 0.34366,
'grossMargins': 0.6826,
'operatingCashflow': 87693000704,
'revenueGrowth': 0.106,
'operatingMargins': 0.41691002,
'ebitda': 98841001984,
'targetLowPrice': 255,
'recommendationKey': 'buy',
'grossProfits': 135620000000,
'freeCashflow': 46155874304,
'targetMedianPrice': 296,
'currentPrice': 235.87,
'earningsGrowth': -0.133,
'currentRatio': 1.84,
'returnOnAssets': 0.15223,
'numberOfAnalystOpinions': 45,
'targetMeanPrice': 307.58,
'debtToEquity': 44.442,
'returnOnEquity': 0.42875,
'targetHighPrice': 411,
'totalCash': 107244003328,
'totalDebt': 77136003072,
'totalRevenue': 203074994176,
'totalCashPerShare': 14.387,
'financialCurrency': 'USD',
'revenuePerShare': 27.142,
'quickRatio': 1.585,
'recommendationMean': 1.7,
'exchange': 'NMS',
'shortName': 'Microsoft Corporation',
'longName': 'Microsoft Corporation',
'exchangeTimezoneName': 'America/New_York',
'exchangeTimezoneShortName': 'EDT',
'isEsgPopulated': False,
'gmtOffSetMilliseconds': '-14400000',
'quoteType': 'EQUITY',
'symbol': 'MSFT',
'messageBoardId': 'finmb_21835',
'market': 'us_market',
'annualHoldingsTurnover': None,
'enterpriseToRevenue': 8.51,
'beta3Year': None,
'enterpriseToEbitda': 17.484,
'52WeekChange': -0.2838753,
'morningStarRiskRating': None,
'forwardEps': 11.35,
'revenueQuarterlyGrowth': None,
'sharesOutstanding': 7454470144,
'fundInceptionDate': None,
'annualReportExpenseRatio': None,
'totalAssets': None,
'bookValue': 23.276,
'sharesShort': 38213792,
'sharesPercentSharesOut': 0.0050999997,
'fundFamily': None,
'lastFiscalYearEnd': 1656547200,
'heldPercentInstitutions': 0.71777,
'netIncomeToCommon': 69788999680,
'trailingEps': 9.29,
'lastDividendValue': 0.62,
'SandP52WeekChange': -0.1544562,
'priceToBook': 10.133615,
'heldPercentInsiders': 0.00071000005,
'nextFiscalYearEnd': 1719705600,
'yield': None,
'mostRecentQuarter': 1664496000,
'shortRatio': 1.28,
'sharesShortPreviousMonthDate': 1663200000,
'floatShares': 7399682766,
'beta': 0.960206,
'enterpriseValue': 1728178552832,
'priceHint': 2,
'threeYearAverageReturn': None,
'lastSplitDate': 1045526400,
'lastSplitFactor': '2:1',
'legalType': None,
'lastDividendDate': 1660694400,
'morningStarOverallRating': None,
'earningsQuarterlyGrowth': -0.144,
'priceToSalesTrailing12Months': 8.658308,
'dateShortInterest': 1665705600,
'pegRatio': 1.8,
'ytdReturn': None,
'forwardPE': 20.781496,
'lastCapGain': None,
'shortPercentOfFloat': 0.0050999997,
'sharesShortPriorMonth': 42967330,
'impliedSharesOutstanding': 0,
'category': None,
'fiveYearAverageReturn': None,
'previousClose': 226.75,
'regularMarketOpen': 226.24,
'twoHundredDayAverage': 272.84604,
'trailingAnnualDividendYield': 0.0112017635,
'payoutRatio': 0.26700002,
'volume24Hr': None,
'regularMarketDayHigh': 236.6,
'navPrice': None,
'averageDailyVolume10Day': 34581880,
'regularMarketPreviousClose': 226.75,
'fiftyDayAverage': 248.0068,
'trailingAnnualDividendRate': 2.54,
'open': 226.24,
'toCurrency': None,
'averageVolume10days': 34581880,
'expireDate': None,
'algorithm': None,
'dividendRate': 2.72,
'exDividendDate': 1668556800,
'circulatingSupply': None,
'startDate': None,
'regularMarketDayLow': 226.06,
'currency': 'USD',
'trailingPE': 25.389666,
'regularMarketVolume': 40593443,
'lastMarket': None,
'maxSupply': None,
'openInterest': None,
'marketCap': 1758285791232,
'volumeAllCurrencies': None,
'strikePrice': None,
'averageVolume': 26490917,
'dayLow': 226.06,
'ask': 235.7,
'askSize': 1200,
'volume': 40593443,
'fiftyTwoWeekHigh': 349.67,
'fromCurrency': None,
'fiveYearAvgDividendYield': 1.2,
'fiftyTwoWeekLow': 219.13,
'bid': 235.5,
'tradeable': False,
'dividendYield': 0.0115,
'bidSize': 900,
'dayHigh': 236.6,
'coinMarketCapLink': None,
'regularMarketPrice': 235.87,
'preMarketPrice': None,
'logo_url': 'https://logo.clearbit.com/microsoft.com'}
</code></pre>
<p>This is the full response from Yahoo Finance API from which I only need 'freeCashflow', 'industry', 'debtToEquity, 'returnOnEquity', 'sharesOutstanding' to CSV</p>
<pre><code>ticker = "MSFT"
stock_info = yf.Ticker(ticker).info
stock_info
df = pd.DataFrame(stock_info)
df
</code></pre>
<p>This code returns an empty df but I can see the columns. 154 columns but 0 rows??? I should have 1 row of data.</p>
<p><a href="https://i.stack.imgur.com/Wu9By.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Wu9By.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74255619,
"author": "Shreyansh Gupta",
"author_id": 18046485,
"author_profile": "https://Stackoverflow.com/users/18046485",
"pm_score": -1,
"selected": false,
"text": "nav{\n/*...*/\njustify-content:center;\n/*...*/\n}\n"
},
{
"answer_id": 74256420,
"author": "... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5645152/"
] |
74,255,560 | <p>I have a time series with daily values. I have extracted the month values in column L. I want to add a column (M) with date format. The first value of column ‘M’ is year 2000. I want the value 2000 is repeated if the month is the same, and when we go to the next month the value 2000 becomes 2001 and so on.
<a href="https://i.stack.imgur.com/dFQlD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dFQlD.jpg" alt="Dataset" /></a></p>
<p>This can be done easily in excel by this conditional code:</p>
<pre><code>=IF(L3=L2,M2,M2+366)
</code></pre>
<p>But I don’t know how to do that in python.</p>
| [
{
"answer_id": 74255781,
"author": "Devam Sanghvi",
"author_id": 16921041,
"author_profile": "https://Stackoverflow.com/users/16921041",
"pm_score": 2,
"selected": true,
"text": "from openpyxl import load_workbook\nimport datetime\n#initial date\nm2 = datetime.date(2000, 1, 1)\n#get the ... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20087535/"
] |
74,255,565 | <p>I'm trying to setup a React Component library with Rollup, but every time I try to build the app with <code>rollup -c</code>, I get the following error: `</p>
<pre><code>[!] TypeError: dts is not a function
TypeError: dts is not a function
at Object.<anonymous> (D:\xyz\rollup.config.js:32:15)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Function.Module._load (node:internal/modules/cjs/loader:878:12)
at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:169:29)
at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
at async Promise.all (index 0)
at ESMLoader.import (node:internal/modules/esm/loader:530:24)
at importModuleDynamicallyWrapper (node:internal/vm/module:438:15)
</code></pre>
<p>Here are my files:</p>
<p><strong>rollup.config.js</strong></p>
<pre><code>const resolve = require('@rollup/plugin-node-resolve')
const commonjs = require('@rollup/plugin-commonjs')
const typescript = require('@rollup/plugin-typescript')
const dts = require('rollup-plugin-dts')
const packageJson = require('./package.json')
module.exports = [
{
input: 'src/index.ts',
output: [
{
file: packageJson.main,
format: 'cjs',
sourcemap: true,
},
{
file: packageJson.module,
format: 'esm',
sourcemap: true,
},
],
plugins: [
resolve(),
commonjs(),
typescript({ tsconfig: './tsconfig.json' }),
],
},
{
input: 'dist/esm/index.d.ts',
output: [{ file: 'dist/index.d.ts', format: 'esm' }],
plugins: [dts()],
},
]
</code></pre>
<p><strong>tsconfig.json</strong></p>
<pre><code>{
"exclude": [
"dist",
"node_modules",
"src/**/*.test.tsx",
"src/**/*.stories.tsx"
],
"rootDir": "./src",
"compilerOptions": {
// Default
"target": "es5",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
// Added
"jsx": "react",
"module": "ESNext",
"declaration": true,
"declarationDir": "types",
"sourceMap": true,
"outDir": "dist",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"emitDeclarationOnly": true
}
}
</code></pre>
<p>and <strong>package.json</strong></p>
<pre><code> "main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
"files": [
"dist"
],
"types": "dist/index.d.ts",
"devDependencies": {
"@chakra-ui/react": "^2.3.6",
"@commitlint/cli": "^17.1.2",
"@commitlint/config-conventional": "^17.1.0",
"@emotion/react": "^11.10.4",
"@emotion/styled": "^11.10.4",
"@rollup/plugin-commonjs": "^23.0.2",
"@rollup/plugin-node-resolve": "^15.0.1",
"@rollup/plugin-typescript": "^9.0.2",
"@testing-library/react": "^13.4.0",
"@types/react": "^18.0.21",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"commitizen": "^4.2.5",
"cz-conventional-changelog": "^3.3.0",
"eslint": "8.2.0",
"eslint-config-airbnb": "19.0.4",
"eslint-config-standard-with-typescript": "^23.0.0",
"eslint-plugin-import": "2.25.3",
"eslint-plugin-jest": "^27.1.3",
"eslint-plugin-jsx-a11y": "6.5.1",
"eslint-plugin-n": "^15.0.0",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-promise": "^6.0.0",
"eslint-plugin-react": "^7.31.10",
"eslint-plugin-react-hooks": "4.3.0",
"framer-motion": "^7.6.1",
"husky": "^8.0.1",
"jest": "^29.2.2",
"lint-staged": "^13.0.3",
"prettier": "^2.7.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-test-renderer": "^18.2.0",
"rimraf": "^3.0.2",
"rollup": "^3.2.3",
"rollup-plugin-dts": "^5.0.0",
"typescript": "^4.8.4"
},
"peerDependencies": {
"@types/react": "^18.0.21",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"typescript": "^4.8.4"
}
</code></pre>
<p>Any idea what I might be doing wrong? Thanks in advance.</p>
<p>Initially, I tried putting in all imports in ES6 way: <code>import xyz from 'xyz'</code>, but that gave me rollup error:</p>
<p><code>RollupError: Node tried to load your configuration file as CommonJS even though it is likely an ES module. To resolve this, change the extension of your configuration to ".mjs", set "type": "module" in your package.json file or pass the "--bundleConfigAsCjs" flag.</code></p>
<p>I also tried passing <code>dts</code> as <code>plugins: [dts]</code> instead of <code>plugins: [dts()]</code></p>
<p>But that obviously broke when building the app</p>
| [
{
"answer_id": 74272447,
"author": "Dementevms",
"author_id": 20385422,
"author_profile": "https://Stackoverflow.com/users/20385422",
"pm_score": 1,
"selected": false,
"text": "const packageJson = require('./package.json')\n"
},
{
"answer_id": 74300031,
"author": "Chinmay",
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20373517/"
] |
74,255,567 | <p>I'm using serverless@3.23.0 to deploy my services, and I'm looking at setting up an HTTP API Proxy to an SQS Service.</p>
<p>I've handled this previously through this <a href="https://github.com/serverless-operations/serverless-apigateway-service-proxy" rel="nofollow noreferrer">plugin - serverless-apigateway-service-proxy</a>. Unfortunately this sets up the proxy through a REST API. I don't need all the features from a REST API, so I'm looking at setting up a HTTP API Proxy to SQS.</p>
<p>I've used these resources to help me set up:</p>
<ul>
<li><a href="https://blog.deleu.dev/receiving-sqs-messages-via-api-gateway/" rel="nofollow noreferrer">https://blog.deleu.dev/receiving-sqs-messages-via-api-gateway/</a></li>
<li><a href="https://awsteele.com/blog/2021/09/06/api-gateway-http-apis-and-sqs-messageattributes.html" rel="nofollow noreferrer">https://awsteele.com/blog/2021/09/06/api-gateway-http-apis-and-sqs-messageattributes.html</a></li>
</ul>
<p>But I'm consistently getting a 400 error</p>
<pre class="lang-bash prettyprint-override"><code>Operation: SQS-SendMessage is not supported. (Service: AmazonApiGatewayV2; Status Code: 400;
</code></pre>
<p>Here's the snippet for the Integration.</p>
<pre class="lang-yaml prettyprint-override"><code> Integration:
Type: AWS::ApiGatewayV2::Integration
Properties:
ApiId: ${param:HttpAPIRef}
IntegrationSubtype: SQS-SendMessage
IntegrationType: AWS_PROXY
ConnectionType: INTERNET
PayloadFormatVersion: 1.0
CredentialsArn: !GetAtt HttpApiRole.Arn
RequestParameters:
QueueUrl: !Ref Queue
MessageBody: random+text
</code></pre>
<p>I successfully created an Integration through the AWS Console and the aws cli. This is the only workaround. But it's a pain to maintain as you might see</p>
<ol>
<li>Create the integration on the Console or CLI</li>
<li>Reference the integration id through custom parameters</li>
</ol>
<p>A pain when referencing across different environments
Any idea why I would get this error through Cloudfromation?</p>
<p>Also, any way I can debug this further? I'm fairly new to AWS, so I'm learning as I'm going :)</p>
<p>Here's a screenshot of the error on AWS Console:</p>
<p><a href="https://i.stack.imgur.com/49gVf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/49gVf.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74272447,
"author": "Dementevms",
"author_id": 20385422,
"author_profile": "https://Stackoverflow.com/users/20385422",
"pm_score": 1,
"selected": false,
"text": "const packageJson = require('./package.json')\n"
},
{
"answer_id": 74300031,
"author": "Chinmay",
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2986350/"
] |
74,255,580 | <p>I have this below function in which i am calling another function <code>"uploadContentVersion"</code> which is a request POST. This also includes a callback which i am capturing in the below function .</p>
<p>The issue which i am facing is this line <code>"console.log(data)"</code> is giving me result like this</p>
<pre><code>{"id":"11111111111111","success":true,"errors":[]}
</code></pre>
<p>But when i am trying to print <code>console.log(data.id)</code> i am getting undefined.Not sure where i am doing wrong.</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 createFileFromJSON = async() => {
if (fs.existsSync('./templates/officetemplate.docx')) {
const templateFile = fs.readFileSync('./templates/officetemplate.docx');
//console.log(templateFile.toString('utf8'))
var doc = await handler.process(templateFile, data);
// 3. save output
fs.writeFileSync('./templates/' + data.accPlanId + '.docx', doc);
uploadContentVersion(sfdc_token.access_token, sfdc_token.instance_url, data.accPlanId, function(data) {
var conn = new sf.Connection({});
conn.initialize({
instanceUrl: sfdc_token.instance_url,
accessToken: sfdc_token.access_token
});
console.log(data) -- > {
"id": "11111111111111",
"success": true,
"errors": []
}
console.log(data.id) -- > undefined
attachFileToRecord(conn, data)
})
// console.log(contentversionres)
} else {
console.log('Template is not present..')
}
var uploadContentVersion = function(token, instUrl, fname, callback) {
var options = {
'method': 'POST',
'url': some url,
'headers': {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json',
},
body: JSON.stringify({
"VersionData": fs.readFileSync(`./templates/${fname}.docx`).toString('base64')
})
};
request(options, function(error, response) {
if (response.statusCode === 201) {
callback(response.body);
}
if (error) throw new Error(error);
});
}</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74272447,
"author": "Dementevms",
"author_id": 20385422,
"author_profile": "https://Stackoverflow.com/users/20385422",
"pm_score": 1,
"selected": false,
"text": "const packageJson = require('./package.json')\n"
},
{
"answer_id": 74300031,
"author": "Chinmay",
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6938609/"
] |
74,255,602 | <p>How to iterate over JSON using python with children nodes?</p>
| [
{
"answer_id": 74272447,
"author": "Dementevms",
"author_id": 20385422,
"author_profile": "https://Stackoverflow.com/users/20385422",
"pm_score": 1,
"selected": false,
"text": "const packageJson = require('./package.json')\n"
},
{
"answer_id": 74300031,
"author": "Chinmay",
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20373570/"
] |
74,255,634 | <p>I am trying to show the buttons in parallelly view like showing the below image. How to align buttons in parallelly in flutter for android application. But I do not know how to align it. I have attached images for more info. If anyone knows the answer please help to find the solution.</p>
<pre><code> child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: [
const SizedBox(
height: 510,
),
SizedBox(
width: 300, // <-- Your width
height: 50, // <-- Your height
child: ElevatedButton(
onPressed: () {
//validateForm();
Navigator.push(context,
MaterialPageRoute(builder: (c) => const PhoneLoginScreen()));
},
style: ElevatedButton.styleFrom(
primary: Color(0xff557de3),
shape: StadiumBorder()
),
child: const Text(
"SIGN IN WITH",
style: TextStyle(
color: Colors.white,
fontSize: 13,
fontWeight: FontWeight.bold
),
),
),
),
const SizedBox(
height: 20,
),
SizedBox(
width: 300, // <-- Your width
height: 50, // <-- Your height
child: ElevatedButton(
onPressed: () {
onGoogleSignIn(context);
},
style: ElevatedButton.styleFrom(
primary: Color(0xFF557de3),
shape: CircleBorder(),
padding: EdgeInsets.all(24),
//primary: Color(0xFFF5F1F1),
),
child: const Text(
"GMAIL",
style: TextStyle(
color: Colors.white,
fontSize: 13,
fontWeight: FontWeight.bold
),
),
),
),
SizedBox(
width: 300, // <-- Your width
height: 50, // <-- Your height
child: ElevatedButton(
onPressed: () {
onGoogleSignIn(context);
},
style: ElevatedButton.styleFrom(
primary: Color(0xFF557de3),
shape: CircleBorder(),
padding: EdgeInsets.all(24),
//primary: Color(0xFFF5F1F1),
),
child: const Text(
"PHONE",
style: TextStyle(
color: Colors.white,
fontSize: 13,
fontWeight: FontWeight.bold
),
),
),
),
],
),
),
)
</code></pre>
<p>From my code:</p>
<p><a href="https://i.stack.imgur.com/04oce.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/04oce.png" alt="enter image description here" /></a></p>
<p>Expecting like this:</p>
<p><a href="https://i.stack.imgur.com/XIUEw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XIUEw.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74255669,
"author": "Tirth Patel",
"author_id": 4593315,
"author_profile": "https://Stackoverflow.com/users/4593315",
"pm_score": 0,
"selected": false,
"text": "Row"
},
{
"answer_id": 74255870,
"author": "MajorShepard",
"author_id": 3472838,
"author_pro... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19099386/"
] |
74,255,647 | <p>I want to merge two dataframe rows with one column value different. For example,</p>
<p>DataframeA:</p>
<pre><code>firstName lastName age
Alex Smith 19
Rick Mart 18
</code></pre>
<p>DataframeB:</p>
<pre><code>firstName lastName age
Alex Smith 21
</code></pre>
<p>Result when I use merge DataframeA with DataframeB using <code>union</code>:</p>
<pre><code>firstName lastName age
Alex Smith 19
Rick Mart 18
Alex Smith 21
</code></pre>
<p>What I want is that the rows with all column values same but different age should get combined as well, in a way that the age column has the max value. So, this is what I expect -</p>
<pre><code>firstName lastName age
Alex Smith 21
Rick Mart 18
</code></pre>
<p>Anyway I can achieve this in PySpark?</p>
<p>Thanks</p>
| [
{
"answer_id": 74255669,
"author": "Tirth Patel",
"author_id": 4593315,
"author_profile": "https://Stackoverflow.com/users/4593315",
"pm_score": 0,
"selected": false,
"text": "Row"
},
{
"answer_id": 74255870,
"author": "MajorShepard",
"author_id": 3472838,
"author_pro... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13396419/"
] |
74,255,667 | <p>It has been a month now since I work with the following issue but not succeed. I have three svg images with less difference in size and trying to fit them into one row adding them to different columns.</p>
<p>But unfortunately, the top text and those images are not fit equally. some get high padding top some bottom. I know the reason SVG width. I need help please.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="section-top-homepage">
<div class="row circular-wrap text-center">
<div class="col-md-4 col-sm-4 top15"><img alt="" data-entity-type="file" height="67" src="/sites/default/files/inline-images/vision.svg" width="71" />
<h3 class="whitecolor top15">Vision</h3>
</div>
<div class="col-md-4 col-sm-4 top15"><img alt="" data-entity-type="file" height="72" src="/sites/default/files/inline-images/objectives.svg" width="73" />
<h3 class="whitecolor top15">Objectives</h3>
</div>
<p>&nbsp;</p>
<div class="col-md-4 col-sm-4 top15"><img alt="" data-entity-type="file" height="59" src="/sites/default/files/inline-images/mission.svg" width="72" />
<h3 class="whitecolor top15">Mission</h3>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p><a href="https://i.stack.imgur.com/jA7bm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jA7bm.jpg" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74255669,
"author": "Tirth Patel",
"author_id": 4593315,
"author_profile": "https://Stackoverflow.com/users/4593315",
"pm_score": 0,
"selected": false,
"text": "Row"
},
{
"answer_id": 74255870,
"author": "MajorShepard",
"author_id": 3472838,
"author_pro... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13022311/"
] |
74,255,668 | <p>I'm really new to Delphi and have not yet worked with SQL (I'm a complete beginner).</p>
<p>I use code to connect my database and tables to my program, but as soon as I run my program, I get a <code>Syntax error in FROM clause</code> message.</p>
<p>When I select break, it highlights <code>end;</code> of a part of the code.</p>
<pre><code>function TADOCommand.Execute(var RecordsAffected: Integer;
const Parameters: OleVariant): _Recordset;
var
VarRecsAffected: OleVariant;
begin
SetConnectionFlag(cfExecute, True);
try
Initialize;
Result := CommandObject.Execute(VarRecsAffected, Parameters,
Integer(CommandObject.CommandType) + ExecuteOptionsToOrd
(FExecuteOptions));
RecordsAffected := VarRecsAffected;
finally
SetConnectionFlag(cfExecute, False);
end;
end;
</code></pre>
<p>I have three tables, of which two display on their grids, but one is not displaying on the grid, and also gives me the <code>Syntax error in FROM clause</code> when I want to do anything with it.</p>
<p>This is the code that I used to connect my database in the datamodule:</p>
<pre><code>unit dmChamps_u;
interface
uses
System.SysUtils, System.Classes, ADODB, DB; // add Ado and DB
type
TdmChamps = class(TDataModule)
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
conArchers: TADOConnection;
tblArchers: TADOTable;
tblJT: TADOTable;
tblMatches: TADOTable;
dscArchers: TDataSource;
dscMatches: TDataSource;
dscJT: TDataSource;
end;
var
dmChamps: TdmChamps;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
procedure TdmChamps.DataModuleCreate(Sender: TObject);
begin
// create objects
conArchers := TADOConnection.Create(dmChamps);
tblArchers := TADOTable.Create(dmChamps);
tblMatches := TADOTable.Create(dmChamps);
tblJT := TADOTable.Create(dmChamps);
dscArchers := TDataSource.Create(dmChamps);
dscMatches := TDataSource.Create(dmChamps);
dscJT := TDataSource.Create(dmChamps);
// setup connection
conArchers.ConnectionString :=
'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=ArchChampsDB.mdb;Mode=ReadWrite;Persist Security Info=False';
conArchers.LoginPrompt := false;
conArchers.Open;
// setup table archers
tblArchers.Connection := conArchers;
tblArchers.TableName := 'Archers';
// setup data source
dscArchers.DataSet := tblArchers;
tblArchers.Open;
// setup table matches
tblMatches.Connection := conArchers;
tblMatches.TableName := 'Matches';
// setup data source
dscMatches.DataSet := tblMatches;
tblMatches.Open;
// setup table JT
tblJT.Connection := conArchers;
tblJT.TableName := 'Judges/Timekeepers';
// setup data source
dscJT.DataSet := tblJT;
tblJT.Open;
end;
end.
</code></pre>
<p>I've looked through all of the questions on the <code>From clause</code> error already on the site, but none of the scenarios quite match my problem. I also went to Embarcadero's site and read about TableDirect, which I thought might be a possible solution, but it was already in the code.</p>
| [
{
"answer_id": 74274644,
"author": "Kees de Kraker",
"author_id": 6690513,
"author_profile": "https://Stackoverflow.com/users/6690513",
"pm_score": -1,
"selected": false,
"text": "DataModuleCreate"
},
{
"answer_id": 74361554,
"author": "Joao Bosco dos Reis Becker",
"autho... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20373588/"
] |
74,255,678 | <p>In previous versions of symfony, you could fetch objects like this
`</p>
<pre><code>
public function someMethod()
{
$method = $this->getDoctrine()->getRepository(Method::class)->findOneBy(array('id' => 1));
return $method;
}
</code></pre>
<p>`
This was easy because it meant that you could easily make global variables in the twig.yaml file and have dynamic content all around your page.</p>
<p>Now in symfony as far as i know, an argument of ManagerRegistry has to be passed as a argument all the time. Am I being too close minded or is there a work around for this problem?</p>
<p>I tried extending classes and have it pass down that way but it gave me the same workaround errors.</p>
| [
{
"answer_id": 74274644,
"author": "Kees de Kraker",
"author_id": 6690513,
"author_profile": "https://Stackoverflow.com/users/6690513",
"pm_score": -1,
"selected": false,
"text": "DataModuleCreate"
},
{
"answer_id": 74361554,
"author": "Joao Bosco dos Reis Becker",
"autho... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13841694/"
] |
74,255,755 | <p><strong>I would like to customize the <code>pin_write</code> function from <code>pins</code> package:</strong></p>
<p>The original works this way:</p>
<pre><code>library(pins)
# create board:
board_versioned <- board_folder("your path", versioned = TRUE)
board_versioned %>%
pin_write(iris, "iris")
# gives:
# Guessing `type = 'rds'`
# Creating new version '20221030T182552Z-f2bf1'
# Writing to pin 'iris'
</code></pre>
<p>Now I want to create a custom function:</p>
<pre><code>library(pins)
my_pin_write <- function(board, df) {
board %>%
pin_write(df, deparse(substitute(df)))
}
my_pin_write(board_versioned, iris)
#gives:
# Guessing `type = 'rds'`
# Replacing version '20221030T182736Z-f2bf1' with '20221030T182750Z-f2bf1'
# Writing to pin 'df'
</code></pre>
<p>The problem is <strong>Wrting to pin 'df'</strong> .
I would expect:
<strong>Writing to pin 'iris'</strong></p>
<p>I can't manage how to pass the dataframe as name as string in this situation. Many thanks!</p>
| [
{
"answer_id": 74256994,
"author": "onyambu",
"author_id": 8380272,
"author_profile": "https://Stackoverflow.com/users/8380272",
"pm_score": 3,
"selected": true,
"text": " pin_write(board, df, deparse(substitute(df)))\n"
},
{
"answer_id": 74257900,
"author": "akrun",
"aut... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13321647/"
] |
74,255,760 | <p>I would like to copy a Cell from all worksheet but "Data" Worksheet on column C of "Data Worksheet". The following code is not working properly, always blank value. The value I would like to copy is placed on E16 Cell.</p>
<pre><code>For Each ws In ActiveWorkbook.Worksheets
If ws.Name <> "Data" Then
x = x + 1
Sheets("Data").Range("B1").Offset(x) = Worksheets(ws.Name).Cells(4, 16).Value
End If
Next ws
</code></pre>
| [
{
"answer_id": 74256994,
"author": "onyambu",
"author_id": 8380272,
"author_profile": "https://Stackoverflow.com/users/8380272",
"pm_score": 3,
"selected": true,
"text": " pin_write(board, df, deparse(substitute(df)))\n"
},
{
"answer_id": 74257900,
"author": "akrun",
"aut... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10770539/"
] |
74,255,779 | <p>I'm using bootstrap inside of my app on which I have a readonly input where I need to add checkmark inside of it. I tried to add simple <code><input readonly type="text" id="kyc_status" class="form-control" value="Success"></code> but this won't work. Below is my HTML structure:</p>
<pre><code><div class="card">
<div class="card-body">
<form>
<div class="row mb-3">
<div class="col">
<label for="kyc_status" class="form-label">
KYC Status
</label>
<input readonly type="text" id="kyc_status" class="form-control" value="Success">
<i class="bi bi-check"></i>
</div>
</div>
</form>
</div>
</div>
</code></pre>
<p>So now it produces me:</p>
<p><a href="https://i.stack.imgur.com/SgmkI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SgmkI.png" alt="enter image description here" /></a></p>
<p>How to put this checkmark inside of the input on the left ?</p>
| [
{
"answer_id": 74255862,
"author": "mehdi eybak abadi",
"author_id": 12828793,
"author_profile": "https://Stackoverflow.com/users/12828793",
"pm_score": 0,
"selected": false,
"text": "position"
},
{
"answer_id": 74256298,
"author": "Arleigh Hix",
"author_id": 6127393,
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10443890/"
] |
74,255,783 | <p>I have built a chat app in firebase android everything is working fine the only problem is that when users are chatting with each other the messages are not showing in order or sequence they are just showing randomly. Image should be shown in proper sequence but it is not working please check it guide me why this is happning? thank you in adnvace</p>
<p><strong>image here</strong></p>
<p><a href="https://i.stack.imgur.com/qi8bH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qi8bH.jpg" alt="enter image description here" /></a>
I have no idea why is this happening</p>
<p><strong>this is Adapter</strong></p>
<pre><code>public class MessageAdapter extends RecyclerView.Adapter {
Context context;
ArrayList<Message> messageArrayList;
int ITEM_SENT = 1;
int ITEM_RECEIVE = 2;
String senderRoom;
String receiverRoom;
public MessageAdapter()
{
}
public MessageAdapter(Context context, ArrayList<Message> messageArrayList, String senderRoom, String receiverRoom) {
this.context = context;
this.messageArrayList = messageArrayList;
this.senderRoom = senderRoom;
this.receiverRoom = receiverRoom;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if (viewType==ITEM_SENT)
{
View view = LayoutInflater.from(context).inflate(R.layout.senderchatlayout, parent, false);
return new SenderViewHolder(view);
}else
{
View view = LayoutInflater.from(context).inflate(R.layout.receiverchatlayout, parent, false);
return new RecieverViewHolder(view);
}
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
Message message = messageArrayList.get(position);
if (holder.getClass() == SenderViewHolder.class)
{
SenderViewHolder viewHolder = (SenderViewHolder) holder;
viewHolder.textViewMessage.setText(message.getMessage());
viewHolder.timeofmessage.setText(message.getCurrenttime());
}else
{
RecieverViewHolder viewHolder = (RecieverViewHolder) holder;
viewHolder.textViewMessage.setText(message.getMessage());
viewHolder.timeofmessage.setText(message.getCurrenttime());
}
}
@Override
public int getItemViewType(int position) {
Message message = messageArrayList.get(position);
if (FirebaseAuth.getInstance().getCurrentUser().getUid().equals(message.getSenderId()))
{
return ITEM_SENT;
}else
{
return ITEM_RECEIVE;
}
}
@Override
public int getItemCount() {
return messageArrayList.size();
}
public class SenderViewHolder extends RecyclerView.ViewHolder
{
TextView textViewMessage;
TextView timeofmessage;
public SenderViewHolder(@NonNull View itemView) {
super(itemView);
textViewMessage = itemView.findViewById(R.id.senderMessage);
timeofmessage = itemView.findViewById(R.id.senderTime);
}
}
public class RecieverViewHolder extends RecyclerView.ViewHolder
{
TextView textViewMessage;
TextView timeofmessage;
public RecieverViewHolder(@NonNull View itemView) {
super(itemView);
textViewMessage = itemView.findViewById(R.id.receiverMessage);
timeofmessage = itemView.findViewById(R.id.receiverTime);
}
}
</code></pre>
<p>}</p>
<p><strong>CODE TO GET MESSAGES IN ChatActivity</strong></p>
<pre><code>public class SpecificChatActivity extends AppCompatActivity {
ActivitySpecificChatBinding binding;
private FirebaseAuth auth;
FirebaseFirestore firebaseFirestore;
private String enteredMessage;
String mreceiveruid, msenderuid;
String senderroom, receiverroom;
String currenttime;
Calendar calendar;
String conversionId;
ArrayList<Message> messageArrayList;
MessageAdapter adapter;
SimpleDateFormat simpleDateFormat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivitySpecificChatBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
auth = FirebaseAuth.getInstance();
firebaseFirestore = FirebaseFirestore.getInstance();
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("hh:mm a");
setSupportActionBar(binding.specificToolbar);
messageArrayList = new ArrayList<>();
String id = UUID.randomUUID().toString();
Intent intent = getIntent();
String name = intent.getStringExtra("name");
String image = intent.getStringExtra("profileImage");
msenderuid = auth.getUid();
mreceiveruid = intent.getStringExtra("receiverUid");
senderroom = msenderuid+mreceiveruid;
receiverroom = mreceiveruid+msenderuid;
binding.specificUserName.setText(name);
if (!image.isEmpty())
{
Glide.with(getApplicationContext())
.load(image)
.placeholder(R.drawable.userchaticon)
.into(binding.specificUserImage);
}
binding.sendBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
enteredMessage = binding.messageBox.getText().toString();
if (enteredMessage.isEmpty())
{
Toast.makeText(SpecificChatActivity.this, "Entered some message", Toast.LENGTH_SHORT).show();
}else
{
Date date = new Date();
currenttime = simpleDateFormat.format(calendar.getTime());
Message message = new Message(enteredMessage, auth.getUid(), mreceiveruid, date.getTime(), currenttime, name, image);
firebaseFirestore.collection("Chats")
.document(senderroom)
.collection("Messages")
.document()
.set(message).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
firebaseFirestore.collection("Chats")
.document(receiverroom)
.collection("Messages")
.document()
.set(message).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
}
});
}
});
binding.messageBox.setText(null);
}
}
});
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
binding.specificUserRecycler.setLayoutManager(linearLayoutManager);
adapter = new MessageAdapter(SpecificChatActivity.this, messageArrayList, senderroom, receiverroom);
binding.specificUserRecycler.setAdapter(adapter);
CollectionReference collectionReference = firebaseFirestore.collection("Chats").document(senderroom)
.collection("Messages");
collectionReference.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
messageArrayList.clear();
for (DocumentSnapshot snapshots : value.getDocuments())
{
Message message = snapshots.toObject(Message.class);
messageArrayList.add(message);
}
adapter.notifyDataSetChanged();
}
});
}
}
</code></pre>
| [
{
"answer_id": 74256081,
"author": "Roman Meromerow",
"author_id": 13743964,
"author_profile": "https://Stackoverflow.com/users/13743964",
"pm_score": 0,
"selected": false,
"text": "firebaseFirestore.collection(\"Chats\").document(senderroom)\n .collection(\"Messages\")\n .... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11915666/"
] |
74,255,797 | <p>I cannot install <code>@material-ui/core</code> or <code>@mui/styles</code> My React and MUI versions are</p>
<pre><code>"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"@mui/icons-material": "^5.10.9",
"@mui/material": "^5.10.10",
"@emotion/react": "^11.10.4",
"@emotion/styled": "^11.10.4",
</code></pre>
<p>When I try to use <code>makeStyles</code> it says I need to install <code>@mui/styles</code> but when I try to install it it gives the following error</p>
<pre><code>npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: my-app@0.1.0
npm ERR! Found: react@18.2.0
npm ERR! node_modules/react
npm ERR! react@"^18.2.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.8.0 || ^17.0.0" from @material-ui/core@4.12.4
npm ERR! node_modules/@material-ui/core
npm ERR! @material-ui/core@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
</code></pre>
<p>Where am I missing out? I cannot find out the problem.</p>
| [
{
"answer_id": 74255968,
"author": "Jacob K",
"author_id": 14077491,
"author_profile": "https://Stackoverflow.com/users/14077491",
"pm_score": -1,
"selected": false,
"text": "@material-ui/core"
},
{
"answer_id": 74334625,
"author": "AndreFeijo",
"author_id": 2946773,
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16797471/"
] |
74,255,805 | <p>I'd like to remove hyphen from string values using SQL.</p>
<p>I have a column that contains data like:</p>
<pre><code>middle-to high-income parents
Assets -
business – 1 year in their Certified program
explain your assets
10-12-15 years -
</code></pre>
<p>and this is what I need from those string:</p>
<pre><code>middle-to high-income parents
Assets
business – 1 year in their Certified program
explain your assets
10-12-15 years
</code></pre>
<p>I tried</p>
<pre><code>rtrim(ltrim(replace(bal_sheet_item, '-', ' ')))
</code></pre>
<p>but it removed all hyphens not just the ones at the end of the string.</p>
| [
{
"answer_id": 74256248,
"author": "Stuck at 1337",
"author_id": 20091109,
"author_profile": "https://Stackoverflow.com/users/20091109",
"pm_score": 2,
"selected": false,
"text": "SELECT bal_sheet_item = LEFT(bal_sheet_item, LEN(bal_sheet_item) \n - CASE WHEN RIGHT(bal_sheet_item,1) = ... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20113103/"
] |
74,255,855 | <p>I have a pure function that takes 18 arguments process them and returns an answer.
Inside this function I call many other pure functions and those functions call other pure functions within them as deep as 6 levels.</p>
<p>This way of composition is cumbersome to test as the top level functions,in addition to their logic,have to gather parameters for inner functions.</p>
<pre><code># Minimal conceptual example
main_function(a, b, c, d, e) = begin
x = pure_function_1(a, b, d)
y = pure_function_2(a, c, e, x)
z = pure_function_3(b, c, y, x)
answer = pure_function_4(x,y,z)
return answer
end
</code></pre>
<pre><code># real example
calculate_time_dependant_losses(
Ap,
u,
Ac,
e,
Ic,
Ep,
Ecm_t,
fck,
RH,
T,
cementClass::Char,
ρ_1000,
σ_p_start,
f_pk,
t0,
ts,
t_start,
t_end,
) = begin
μ = σ_p_start / f_pk
fcm = fck + 8
Fr = σ_p_start * Ap
_σ_pb = σ_pb(Fr, Ac, e, Ic)
_ϵ_cs_t_start_t_end = ϵ_cs_ti_tj(ts, t_start, t_end, Ac, u, fck, RH, cementClass)
_ϕ_t0_t_start_t_end = ϕ_t0_ti_tj(RH, fcm, Ac, u, T, cementClass, t0, t_start, t_end)
_Δσ_pr_t_start_t_end =
Δσ_pr(σ_p_start, ρ_1000, t_end, μ) - Δσ_pr(σ_p_start, ρ_1000, t_start, μ)
denominator =
1 +
(1 + 0.8 * _ϕ_t0_t_start_t_end) * (1 + (Ac * e^2) / Ic) * ((Ep * Ap) / (Ecm_t * Ac))
shrinkageLoss = (_ϵ_cs_t_start_t_end * Ep) / denominator
relaxationLoss = (0.8 * _Δσ_pr_t_start_t_end) / denominator
creepLoss = (Ep * _ϕ_t0_t_start_t_end * _σ_pb) / Ecm_t / denominator
return shrinkageLoss + relaxationLoss + creepLoss
end
</code></pre>
<p>I see examples of functional composition (dot chaining,pipe operator etc) with single argument functions.</p>
<p>Is it practical to compose the above function using functional programming?If yes, how?</p>
| [
{
"answer_id": 74256356,
"author": "Noughtmare",
"author_id": 15207568,
"author_profile": "https://Stackoverflow.com/users/15207568",
"pm_score": 2,
"selected": false,
"text": "sum $ map (/ denominator)\n [ _ϵ_cs_t_start_t_end * Ep\n , 0.8 * _Δσ_pr_t_start_t_end\n , (Ep * _ϕ_t0_t_star... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13631440/"
] |
74,255,859 | <p>I am trying to run docker inside a shell script. This is what my script looks like :-</p>
<pre><code>#!/bin/bash
aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin <account-id>.dkr.ecr.us-east-1.amazonaws.com
IMAGE=$(aws ecr describe-images --repository-name repo --query 'sort_by(imageDetails,& imagePushedAt)[-1].imageTags[0]')
echo $IMAGE
docker pull https://<account-id>.dkr.ecr.us-east-1.amazonaws.com/repo:$IMAGE
docker run -d -p 8080:8080 https://<account-id>.dkr.ecr.us-east-1.amazonaws.com/repo:$IMAGE
</code></pre>
<p>But when i run the script, i keep running into</p>
<pre><code>docker: invalid reference format.
See 'docker run --help'.
</code></pre>
<p>and i'm not sure what i'm doing wrong. Any help will be appreciated.</p>
| [
{
"answer_id": 74255920,
"author": "Paolo",
"author_id": 3390419,
"author_profile": "https://Stackoverflow.com/users/3390419",
"pm_score": 3,
"selected": true,
"text": "$ docker pull <account-id>.dkr.ecr.us-east-1.amazonaws.com/repo:$IMAGE\n"
},
{
"answer_id": 74256136,
"auth... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11505813/"
] |
74,255,873 | <p>The Problem occurs while sending <strong>GET</strong> or any request with parameters in the URL.</p>
<p>for example my<br />
<code>index.js</code></p>
<pre><code>const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/:name", function (req, res) {
let name = req.params.name;
console.log("Hello " + name + " from /:name");
res.send("Hello " + name + " from /:name");
});
app.get("/", function (req, res) {
console.log("Hello world from /");
res.send("Hello world from /");
});
app.listen(3000, () => {
console.log("Server is running on port " + 3000)
});
</code></pre>
<p>For <code>http://localhost:3000/</code> it's working perfectly fine.
<a href="https://i.stack.imgur.com/Kxusn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Kxusn.png" alt="Home route "http://localhost:3000/"" /></a></p>
<hr />
<p>the Problem is occurring when we try to hit <code>/:name</code> route
when we use URL <code>http://localhost:3000/?name=NODE</code> it is going to the same route as above. in <code>/</code></p>
<p><a href="https://i.stack.imgur.com/zhs26.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zhs26.png" alt="Home route "http://localhost:3000/?"" /></a></p>
<hr />
<p>But the <strong>crazy</strong> part is when we put <code>http://localhost:3000/NODE</code> which is simply a new different route that is not implemented.<br />
It is getting the response from <code>:/name</code> which doesn't make any sense.
<a href="https://i.stack.imgur.com/Tniyt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tniyt.png" alt="enter image description here" /></a></p>
<hr />
<p><strong>is it a BUG or I am doing something wrong or is it something new I am not aware of?</strong></p>
<p>I am currently using Windows11,
this problem also occurs in my friend's PC who uses Ubuntu</p>
| [
{
"answer_id": 74255920,
"author": "Paolo",
"author_id": 3390419,
"author_profile": "https://Stackoverflow.com/users/3390419",
"pm_score": 3,
"selected": true,
"text": "$ docker pull <account-id>.dkr.ecr.us-east-1.amazonaws.com/repo:$IMAGE\n"
},
{
"answer_id": 74256136,
"auth... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13502870/"
] |
74,255,890 | <p>Getting row count I managed to get, but why the other approach doesn't work? I am using SQLite with Microsoft's SQLite extension for Entity Framework Core.</p>
<p>This works :</p>
<pre><code>using (var db = new DBConnection())
{
foreach (var table in db.Model.GetEntityTypes())
{
await using var cmd = db.Database.GetDbConnection().CreateCommand();
cmd.CommandText = $"SELECT COUNT(*) FROM {table.Name.Split(".").Last()}";
await db.Database.OpenConnectionAsync();
var count = await cmd.ExecuteScalarAsync();
Console.WriteLine(count);
}
}
</code></pre>
<p>This doesn't :</p>
<pre><code>using (var db = new DBConnection())
{
foreach (var table in db.Model.GetEntityTypes())
{
var query = db.Database.SqlQueryRaw<int>("SELECT COUNT(*) FROM {0}", $"SELECT COUNT(*) FROM {0}",{table.Name.Split(".").Last()});
var count = query.Single();
Console.WriteLine(count);
}
}
</code></pre>
<p>What did I do wrong?</p>
| [
{
"answer_id": 74255920,
"author": "Paolo",
"author_id": 3390419,
"author_profile": "https://Stackoverflow.com/users/3390419",
"pm_score": 3,
"selected": true,
"text": "$ docker pull <account-id>.dkr.ecr.us-east-1.amazonaws.com/repo:$IMAGE\n"
},
{
"answer_id": 74256136,
"auth... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13604738/"
] |
74,255,907 | <p><a href="https://i.stack.imgur.com/ONyKy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ONyKy.png" alt="enter image description here" /></a></p>
<p>I am trying to make an Android application first time using the Firebase Realtime Database.</p>
| [
{
"answer_id": 74255920,
"author": "Paolo",
"author_id": 3390419,
"author_profile": "https://Stackoverflow.com/users/3390419",
"pm_score": 3,
"selected": true,
"text": "$ docker pull <account-id>.dkr.ecr.us-east-1.amazonaws.com/repo:$IMAGE\n"
},
{
"answer_id": 74256136,
"auth... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20373760/"
] |
74,255,949 | <p>In the df_input['Visit' ] column, there are three different timepoints that I would like to extract and have print into a new dataframe (df_output). The time points are Pre, Post, and Screening.</p>
<p><a href="https://i.stack.imgur.com/qd5oJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qd5oJ.png" alt="data_input" /></a></p>
<p><a href="https://i.stack.imgur.com/6U2lB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6U2lB.png" alt="data_output" /></a></p>
<p>I essentially would like to make a for loop (or just a single code strand) stating:</p>
<p>if data_input['Visit '] contains the word "Pre", print "Pre" in df_output['VISIT']
elif data_input['Visit '] contains the word "Post", print "Post" in df_output['VISIT']
else data_input['Visit '] contains the word "Screening", print "Screening" in df_output['VISIT']</p>
<p>I am just not sure of the proper way to do that.</p>
<p>So far, the only thing I have is this line of code:</p>
<p><em>df_output['VISIT'] = df_input[df_input['Visit '].str.contains('Pr|Po|Sc'))</em></p>
<p>that gives the error message "Columns must be the same length as key"</p>
<p>I've also tried: <em>df_output['VISIT'] = df_input['Visit '].str.contains('Pr|Po|Sc')</em>, which prints True or False into my output dataframe.</p>
| [
{
"answer_id": 74255920,
"author": "Paolo",
"author_id": 3390419,
"author_profile": "https://Stackoverflow.com/users/3390419",
"pm_score": 3,
"selected": true,
"text": "$ docker pull <account-id>.dkr.ecr.us-east-1.amazonaws.com/repo:$IMAGE\n"
},
{
"answer_id": 74256136,
"auth... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20373732/"
] |
74,255,960 | <p>I'm new to react and I'm trying to figure out how to make redirect after check if email is available or not. I've tried to do it with only React.useState, but states are not updated immediately, so I've been redirected in all cases.</p>
<p>I've read somewhere here that to change state I have to use React.useEffect, but after this my code doesn't redirect or output error message at all.</p>
<p>Here is my code with both useState and useEffect. How can I set state, so that the code can analyze the changes after?</p>
<pre><code>import React from 'react';
import { ToMainNavPanel } from "./ToMainNavPanel";
import { Link, Navigate } from 'react-router-dom';
import axios from 'axios';
import '../css_components/sign-inup-form.css';
export function SignUpAccount() {
const [passCoincidence, setPassCoincidence] = React.useState(false);
const [emailExistance, setEmailExistance] = React.useState(false);
const [canRedirect, setCanRedirect] = React.useState(false);
let isEmailInvalid: boolean = false;
let isRedirectAvailable: boolean = false;
React.useEffect(() => {
const tmpMail = isEmailInvalid;
console.log(tmpMail);
setEmailExistance(tmpMail);
}, [isEmailInvalid]);
React.useEffect(() => {
const tmpRedirect = isRedirectAvailable;
console.log(tmpRedirect);
setCanRedirect(tmpRedirect);
}, [isRedirectAvailable]);
async function checkEmail(email: string) {
await axios.post('https://api.escuelajs.co/api/v1/users/is-available',
{
email: `${email}`
})
.then((response) => {
if (!response.data.isAvailable) {
isEmailInvalid = true;
}
})
.catch((error) => {
console.log(error);
});
}
async function registerUser(name: string, email: string, pass: string) {
await axios.post('https://api.escuelajs.co/api/v1/users/',
{
name: `${name}`,
email: `${email}`,
password: `${pass}`,
avatar: ""
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
}
async function checkEntered() {
isEmailInvalid = false;
isRedirectAvailable = false;
let pass: string = (document.getElementById("newPass") as HTMLInputElement).value;
let rPass: string = (document.getElementById("newPassRepeat") as HTMLInputElement).value;
if (pass !== rPass) {
setPassCoincidence(true);
return;
}
else setPassCoincidence(false);
let email: string = (document.getElementById("email") as HTMLInputElement).value;
await checkEmail(email)
.then(() => {
if (!isEmailInvalid) {
let name: string = (document.getElementById("user") as HTMLInputElement).value;
registerUser(name, email, pass)
.then(() => {
isRedirectAvailable = true;
})
}
})
}
return (
<div className='sign-up-page'>
<ToMainNavPanel></ToMainNavPanel>
<div className='entrance-window'>
<div id="wrapper">
<form className='before:top-22' id="signin" method="" action="" onSubmit={(e) => e.preventDefault()}>
<input type="text" id="email" name="email" placeholder="Электронная почта" />
<input type="text" id="user" name="user" placeholder="Имя пользователя" />
<input type="password" id="newPass" name="newPass" placeholder="Придумайте пароль" />
<input type="password" id="newPassRepeat" name="newPassRepeat" placeholder="Повторите пароль" />
{passCoincidence && <p className='sign-error'>Entered passwords doesn't match!</p>}
{emailExistance && <p className='sign-error'>The email is already busy!</p>}
<p className='sign-text'><Link className='sign-link' to="/account">У меня уже есть аккаунт</Link></p>
<button className='top-15' type="submit" onClick={() => {checkEntered();}}>&#9998;</button>
{canRedirect && <Navigate replace to="/account"/>}
</form>
</div>
</div>
</div>
)
}
</code></pre>
| [
{
"answer_id": 74255920,
"author": "Paolo",
"author_id": 3390419,
"author_profile": "https://Stackoverflow.com/users/3390419",
"pm_score": 3,
"selected": true,
"text": "$ docker pull <account-id>.dkr.ecr.us-east-1.amazonaws.com/repo:$IMAGE\n"
},
{
"answer_id": 74256136,
"auth... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20373809/"
] |
74,255,963 | <p><a href="https://i.stack.imgur.com/HGETc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HGETc.png" alt="enter image description here" /></a></p>
<p>How to convert RequireDate(String) to DateTime ?</p>
| [
{
"answer_id": 74256048,
"author": "pythonGo",
"author_id": 12986987,
"author_profile": "https://Stackoverflow.com/users/12986987",
"pm_score": 0,
"selected": false,
"text": "RequireDate: DateTime.parse(RequireDate),\n"
},
{
"answer_id": 74256057,
"author": "Tirth Patel",
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15237097/"
] |
74,255,988 | <p>when I click on an element in the flatlist, I just want to change its style. but whichever button I click, only the style of the last element changes. codes below. what do i need to do to fix it?</p>
<pre><code>import { Text, View, FlatList, TouchableOpacity } from 'react-native'
import React, { useRef } from 'react'
const App = () => {
const ref = useRef()
const click = () => {
ref.current.setNativeProps({ style: { backgroundColor: 'blue' } })
}
return (
<View>
<FlatList
data={[1, 2, 3, 4, 5]}
renderItem={({ item }) =>
<TouchableOpacity onPress={() => click()} >
<View ref={ref} style={{ backgroundColor: '#eee', margin: 5, padding: 20, alignItems: 'center', borderRadius: 10 }}>
<Text>{item}</Text>
</View>
</TouchableOpacity>}
keyExtractor={(item, index) => index.toString()}
/>
</View>
)
}
export default App
</code></pre>
| [
{
"answer_id": 74256048,
"author": "pythonGo",
"author_id": 12986987,
"author_profile": "https://Stackoverflow.com/users/12986987",
"pm_score": 0,
"selected": false,
"text": "RequireDate: DateTime.parse(RequireDate),\n"
},
{
"answer_id": 74256057,
"author": "Tirth Patel",
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4180861/"
] |
74,255,993 | <p>I'm trying to group an array by one property (year) and then create a nested array inside each year, listing the weeks with their total Total Distance and Max Avg Speed.</p>
<p>i.e.</p>
<pre><code>[
{
"year": 2015,
"weeks": [
{week: 45, totalDistance: nnn, maxAvgSpeed: nnn},
{week: 46, totalDistance: nnn, maxAvgSpeed: nnn},
{week: 47, totalDistance: nnn, maxAvgSpeed: nnn}
...
</code></pre>
<p>This is what I have so far, but it says "<em>activitiesByYear.forEach is not a function</em>" even though activitiesByYear is an array as expected.</p>
<pre><code>const activities = [
{
"id": 1,
"actvityYear": 2015,
"actvityWeek": 45,
"name": "One",
"avgSpeed": 1200,
"distance": 2
},
{
"id": 2,
"actvityYear": 2015,
"actvityWeek": 45,
"name": "Two",
"avgSpeed": 1403,
"distance": 6
},
{
"id": 3,
"actvityYear": 2015,
"actvityWeek": 46,
"name": "Three",
"avgSpeed": 1700,
"distance": 7
},
{
"id": 4,
"actvityYear": 2015,
"actvityWeek": 47,
"name": "Four",
"avgSpeed": 600,
"distance": 12
},
{
"id": 5,
"actvityYear": 2015,
"actvityWeek": 47,
"name": "Five",
"avgSpeed": 300,
"distance": 4
},
{
"id": 6,
"actvityYear": 2016,
"actvityWeek": 2,
"name": "Six",
"avgSpeed": 1800,
"distance": 15
}
]
function groupBy(objectArray, property) {
return objectArray.reduce((acc, obj) => {
const key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
// Add object to list for given key's value
acc[key].push(obj);
return acc;
}, {});
}
const activitiesByYear = groupBy(activities, 'actvityYear');
let years = [];
activitiesByYear.forEach(year => {
let weeks = [];
year.reduce(function(result, value) {
const week = moment(value.actvityDate).week();
if (!result[week]) {
result[week] = { week: week, totalDistance: 0, maxAvgSpeed: value.avgSpeed };
weeks.push(result[week])
}
result[week].totalDistance += value.distance;
if (value.average_speed > result[week].maxAvgSpeed) result[week].maxAvgSpeed = value.average_speed;
return result;
}, {});
years.push({"year": year, "weeks": weeks})
})
console.log(years)
</code></pre>
| [
{
"answer_id": 74256058,
"author": "Franco Agustín Torres",
"author_id": 20318366,
"author_profile": "https://Stackoverflow.com/users/20318366",
"pm_score": 0,
"selected": false,
"text": "TypeError: activitiesByYear.forEach is not a function"
},
{
"answer_id": 74256089,
"auth... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74255993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/443425/"
] |
74,256,005 | <p>I have an 18 byte struct in C++. I want to read 18 bytes of data from a file straight into this struct. However, my C++ compiler pads the struct to be 20 bytes (4 byte aligned). This is relatively easy to get around for just my compiler alone but I would prefer to use a method that is more reliable cross-platform/cross-compiler.</p>
<p>This is the struct:</p>
<pre><code>struct Test {
uint8_t a;
uint8_t b;
uint8_t c;
uint16_t d;
uint16_t e;
uint8_t f;
uint16_t g;
uint16_t h;
uint16_t i;
uint16_t j;
uint8_t k;
uint8_t l;
};
</code></pre>
<p>I could add bytes to the front of the struct to guarantee it to be 32 bytes which would be a valid alignment on most systems, however I don't know if that would actually work with how structs need their elements to be naturally aligned.</p>
<p>Any help on this would be great but I could always end up copying the bytes manually into the attributes .</p>
| [
{
"answer_id": 74256058,
"author": "Franco Agustín Torres",
"author_id": 20318366,
"author_profile": "https://Stackoverflow.com/users/20318366",
"pm_score": 0,
"selected": false,
"text": "TypeError: activitiesByYear.forEach is not a function"
},
{
"answer_id": 74256089,
"auth... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,256,014 | <p>I have already got the data from firestore into recyclerView.</p>
<p>Now i want to order those documents by the numbers which is in each documents.</p>
<p>The document which has the highest number must be in top ,
And document which has the lowest number must be in below of the recyclerView.</p>
<p>my code which i used to retrieve data from firestore
`</p>
<pre><code>private fun eventChangeListener() {
db = FirebaseFirestore.getInstance()
db.collection("posts").orderBy("hike",Query.Direction.ASCENDING)
.addSnapshotListener(object : EventListener<QuerySnapshot>{
override fun onEvent(value: QuerySnapshot?, error: FirebaseFirestoreException?) {
if (error != null){
Log.e("Firestore Error",error.message.toString())
return
}
for (dc: DocumentChange in value?.documentChanges!!){
if (dc.type == DocumentChange.Type.ADDED){
userArrayList.add(dc.document.toObject(User::class.java))
}
}
adapter.notifyDataSetChanged()
}
})
}
</code></pre>
<p>`</p>
<p>numbers of the documents are given in the field "hike".</p>
| [
{
"answer_id": 74256058,
"author": "Franco Agustín Torres",
"author_id": 20318366,
"author_profile": "https://Stackoverflow.com/users/20318366",
"pm_score": 0,
"selected": false,
"text": "TypeError: activitiesByYear.forEach is not a function"
},
{
"answer_id": 74256089,
"auth... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16200474/"
] |
74,256,019 | <p>I try to change the node version on mac m1 pro macOs 13,
I do the following commands:</p>
<ol>
<li>sudo npm cache clean -f</li>
<li>sudo npm install -g n</li>
<li>sudo n stable</li>
</ol>
<p>but it is not change, the result is:</p>
<pre><code>copying : node/18.12.0
installed : v18.12.0 to /usr/local/bin/node
active : v17.8.0 at /opt/homebrew/bin/node
</code></pre>
<p>How can I activate the installed version?</p>
| [
{
"answer_id": 74256058,
"author": "Franco Agustín Torres",
"author_id": 20318366,
"author_profile": "https://Stackoverflow.com/users/20318366",
"pm_score": 0,
"selected": false,
"text": "TypeError: activitiesByYear.forEach is not a function"
},
{
"answer_id": 74256089,
"auth... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11451886/"
] |
74,256,038 | <p>When I was trying to make some commit in Github repository, I am unable to click on the commit button.</p>
<p><a href="https://i.stack.imgur.com/SGsqz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SGsqz.png" alt="unable to click on the commit button" /></a></p>
<p>I tried other ways like making commit through terminal and tried to push. But it wasn't working.</p>
| [
{
"answer_id": 74256058,
"author": "Franco Agustín Torres",
"author_id": 20318366,
"author_profile": "https://Stackoverflow.com/users/20318366",
"pm_score": 0,
"selected": false,
"text": "TypeError: activitiesByYear.forEach is not a function"
},
{
"answer_id": 74256089,
"auth... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16404249/"
] |
74,256,046 | <p>I am creating phone app in .Net Maui and I have problem with data binding/properties.</p>
<p>Link to git : <a href="https://github.com/wojblaz/Clicer-Game---final" rel="nofollow noreferrer">https://github.com/wojblaz/Clicer-Game---final</a></p>
<p>This part of my app is for choosing level you will play on. On swich you choose time or points. If you choose time timer will be set on some value and you will have to click as many buttons as you can(points startion from 0) and if you choose points you have to click given amount of times as fast as posible. The value of time/points you will choose from slider - values 5,10,15.</p>
<p>Problems
When I am debbuging method OnSliderValueChanged is never used.</p>
<p>I have also no idea how to make transition - the closer you are to number 5 the bigger the font of lable 5 and lower of 10.</p>
<p>There is also second problem with swich. I want lables to change text based on what is turned on on swich. For example it is time - I want lable time to be set on based of what is set in slider and lable points to 0 and vice versa points 15 and time 0.</p>
<p>This is code in xaml.</p>
<pre><code> <Switch
x:Name="ModeSelector"
IsEnabled="{Binding BindingContext.SwichTimeCommmand, Source={x:Reference ModeSelector}}"
IsToggled="{Binding BindingContext.SwichPointsCommmand, Source={x:Reference ModeSelector}}"
OnColor="LightBlue"
ThumbColor="Blue"
Grid.Row="1"
Grid.Column="0"
HorizontalOptions="Center"/>
<Label Text="{Binding lTime}"
Grid.Row="1"
Grid.Column="1"
HorizontalOptions="Center"
FontSize="25"/>
<Label Text="{Binding lPoints}"
Grid.Row="1"
Grid.Column="2"
HorizontalOptions="Center"/>
<Slider x:Name="ValueSelector"
Grid.Row="3"
Grid.ColumnSpan="3"
Minimum="5"
Maximum="15"
Value="{Binding BindingContext.OnSliderValueChangedCommmand, Source={x:Reference ValueSelector}}"/>
</code></pre>
<p>ViewModel</p>
<pre><code>
[RelayCommand]
public void SwichTime()
{
time = SelectedGameValue;
lTime = SelectedGameValue.ToString();
lPoints = "0";
points = 0;
}
[RelayCommand]
public void SwichPoints()
{
points = SelectedGameValue;
lPoints = SelectedGameValue.ToString();
lTime = "0";
time = 0;
}
[RelayCommand]
public void OnSliderValueChanged(ValueChangedEventArgs args)
{
double value = args.NewValue;
if (value <=7.5)
{
SelectedGameValue = 5;
}
else if(7.5 <= value && value <= 12.5)
{
SelectedGameValue = 10;
}
else if(12.5 <= value)
{
SelectedGameValue = 15;
}
}
</code></pre>
<p><strong>Code after answer. Still there is no text displayed on lables and methods are not executed</strong></p>
<p>Is there way to do all methods in View Model instead of in cs? And why
there is no references to methods?</p>
<p>As always I updated git.</p>
<p>Xaml</p>
<pre><code> <Switch
x:Name="ModeSelector"
IsToggled="False"
Toggled="ModeSelector_Toggled"
OnColor="LightBlue"
ThumbColor="Blue"
Grid.Row="1"
Grid.Column="0"
HorizontalOptions="Center"/>
<Label Text="{Binding timeLabel}"
Grid.Row="1"
Grid.Column="1"
HorizontalOptions="Center"
FontSize="25"
FontFamily="FAR"/>
<Label Text="{Binding pointsLabel}"
Grid.Row="1"
Grid.Column="2"
HorizontalOptions="Center"
FontSize="25"/>
<Slider x:Name="ValueSelector"
Grid.Row="3"
Grid.ColumnSpan="3"
Minimum="5"
Maximum="15"
ValueChanged="OnSliderValueChanged"/>
</code></pre>
<p>Xaml.cs</p>
<pre><code>using Clicer_Game.ViewModels;
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace Clicer_Game.Views;
public partial class ClassicMode : ContentPage
{
ClassicModelViewModel vm;
public ClassicMode()
{
InitializeComponent();
vm = new ClassicModelViewModel();
this.BindingContext = vm;
}
private void OnSliderValueChanged(object sender, ValueChangedEventArgs e) // this methods will be triggered when the value of slider changes, for example, drag the slider
{
double value = e.NewValue;
if (value <= 7.5)
{
vm.SelectedGameValue = 5;
}
else if (7.5 <= value && value <= 12.5)
{
vm.SelectedGameValue = 10;
}
else if (12.5 <= value)
{
vm.SelectedGameValue = 15;
}
//And here you can set the text of your timeLabel and your pointLabel based on the switcher ( if IsTime is true which means OnTime, else means OnPoint), 'IsTime' property will be mentioned later
if (vm.IsTime)
{
vm.timeLabel = vm.SelectedGameValue.ToString();
vm.pointsLabel = "0";
}
else
{
vm.pointsLabel = vm.SelectedGameValue.ToString();
vm.timeLabel = "0";
}
}
private void ModeSelector_Toggled(object sender, ToggledEventArgs e)
{
if (ModeSelector.IsToggled)
{
vm.IsTime = false;
}
else
{
vm.IsTime = true;
}
}
}
</code></pre>
<p>ViewModel</p>
<pre><code> public partial class ClassicModelViewModel : ObservableObject
{
[ObservableProperty]
public string timeLabel;
[ObservableProperty]
public string pointsLabel;
private int _selectedGameValue;
private bool _isTime;
public int SelectedGameValue
{
get { return _selectedGameValue; }
set { _selectedGameValue = value; }
}
public bool IsTime
{
get
{
return _isTime;
}
set
{
_isTime = value;
}
}
}
}
</code></pre>
| [
{
"answer_id": 74258419,
"author": "Liqun Shen-MSFT",
"author_id": 20118901,
"author_profile": "https://Stackoverflow.com/users/20118901",
"pm_score": 0,
"selected": false,
"text": "//INotifyPropertyChanged is notification mechanism that allows the binding infrastructure to be notified w... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20308422/"
] |
74,256,072 | <p>I'm building a tool that allows user grab data from a generic source (with generic structure) and remap the properties to match my API.</p>
<ol>
<li>User will input a source URL (a REST API or a JSON);</li>
<li>User will input a JSON-based DTO instruction</li>
</ol>
<p>DTO will be a JSON like this:</p>
<pre class="lang-json prettyprint-override"><code>{
"data.collection.name": "section.title",
"just.an.example": "data.foo",
}
</code></pre>
<p>and when the source provides a data with this structure:</p>
<pre class="lang-json prettyprint-override"><code>{
"data": {
"foo": "bar",
"collection": {
"totalCount": 123,
"title": "Best sellers",
}
}
}
</code></pre>
<p>the functionality will remap the value to:</p>
<pre class="lang-json prettyprint-override"><code>{
"section": {
"title": "Best sellers"
},
"just": {
"an": {
"example": "bar"
}
}
}
</code></pre>
<p>I could achieve this using lodash <code>get</code> and <code>set</code> methods, with the following algorithm:</p>
<pre><code>const data = {
foo: "bar",
collection: {
title: "BestSellers",
},
just: {
an: {
example: "bar",
},
},
nodes: {
edges: [
{
title: "Orange juice",
slug: "orange-juice",
},
{
title: "Apple juice",
slug: "apple-juice",
},
],
},
};
let transformed = {};
const transformer = {
"collection.title": "section.title",
"just.an.example": "foo",
};
Object.keys(transformer).forEach((key) => {
const value = _.get(data, key);
const path = transformer[key];
_.set(transformed, path, value);
});
console.log(transformed);
</code></pre>
<p>Now I need to achieve the same results, but with array properties (like <code>nodes.edges</code>).</p>
<p>User DTO JSON looking like this (not a requirement, but ideal):</p>
<pre class="lang-json prettyprint-override"><code>{
"data.collection.name": "section.title",
"nodes.edges.title": "products.title",
"nodes.edges.slug": "products.seo.slug",
}
</code></pre>
<p>will generate this output:</p>
<pre class="lang-json prettyprint-override"><code>{
"section": {
"title": "BestSellers"
},
"products": [
{
"title": "Orange Juice",
"seo": {
"slug": "orange-juice"
}
},
{
"title": "Apple Juice",
"seo": {
"slug": "apple-juice"
}
}
]
}
</code></pre>
| [
{
"answer_id": 74256502,
"author": "Icepickle",
"author_id": 3231537,
"author_profile": "https://Stackoverflow.com/users/3231537",
"pm_score": 1,
"selected": false,
"text": "const transformer = {\n \"collection.title\": \"section.title\",\n \"nodes.edges.length\": \"products.count\",\n... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10878843/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.