Skip to main content

Posts

Showing posts from March, 2022

How do I time python code, similar to unix time command? [duplicate]

I want something in python that is similar to the unix time command. The time command gives user time, real time, and system time... all of which are useful in different contexts.. I can get real time via the time.time() methods, but the others I'm not sure about... Also, I'm using this to instrument large blocks of code, so timeit doesn't look particularly useful. source https://stackoverflow.com/questions/71698802/how-do-i-time-python-code-similar-to-unix-time-command

How to avoid duplicate items in a drop down list to display?

I would like to create a drop-down list and retrieve the elements from a webService. My problem is that I would like to avoid displaying duplicate items because I have 9999 items. Here is the JSON file. enter image description here Do you think it is possible to do this? Because, I have no idea how to program this? The display method is this: private getDropDownList(): void { this.service.getDropDownList().pipe( takeUntil(this.unsubscribe$) ).subscribe(res => { if (res.RETURNCODE === ApiResponseCodeEnum.Ok) { this.corporateLines = res.TITRE.map( corporateLine => { return { placelabel: corporateLine.PLACELABEL, } } ); } }); } corporate.component.ts export class CorporateComponent implements OnInit, OnDestroy { private unsubscribe$ = new Subject<void>(); corporateLines: Corporate[] = []; constructor(private service: CorporateService, private router: Rou...

How to use Regex (in Pandas) to find hyphenated words in strings, then select only hyphenated words with 2 characters?

This is the code I have so far to select the hyphenated words: df_hyph = df[df["Sentence"].str.contains(r'\b(?:-)')] Now I want to select the words with 2 or more characters: df_2 = df_hyph[df_hyph["Sentence"].str.contains(r'a-z')] This line isn't working, what am I doing wrong? source https://stackoverflow.com/questions/71697993/how-to-use-regex-in-pandas-to-find-hyphenated-words-in-strings-then-select-on

How to prevent receiving the same random data from the list in python

I want to check that the random cards from the list are not the same card. How can I do that? Can you help me? Thanks. import random vals = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] suits = ['C', 'D', 'H', 'S'] name = [] playercount=int(input("Please Enter Number of Player = ")) if 2 <= playercount <= 5: for i in range(playercount): username=str(input("Please Enter Player Name: ")) if not username: name.append("Player {}".format(i+1)) name.append(random.choices(vals)) name.append(random.choices(suits)) else: name.append(username) name.append(random.choices(vals)) name.append(random.choices(suits)) print("Players, Vals and Suits on the Desk ") for x in range(len(name)...

Data of redux store getting empty on reload

I am new to react and redux. I have 3 screens in my react js application. On First Screen, user input the id and that id get stored in redux store. On submit of first screen button API is called which take id as a parameter and bring the data. I Store that data in redux store. On Second Screen, I show that data after fetching it from store. Problem arises when I reload the page, the data of redux store get initilized to initial state i.e. empty. I want when I reload the page, request should again go to server and fetch the data. NOTE - I dont have access to id on second screen after reload so I cant call API again inside useEffect Hook. Secondly I dont want to store data in any storage. Kindly assist. Thank You Via Active questions tagged javascript - Stack Overflow https://ift.tt/dP1g9bT

React Multiple Button Filter

I have been able to map JSON wine data to a table and filter the table of wine data by color. When I click Red , the table filters to red wines, and the same for the White button. Goal: Filter JSON data with multiple buttons. I would like to add taste buttons (Sweet, Dry, Semi-Sweet) that filter by taste and a body button that will filter wines by body How can I accomplish this? Here, I created an object that defines wines and their properties: var wineData = { redWines : [ {name: "Pinot Noir", body: "Light", taste:"Dry"}, {name: "Cabernet Sauvignon", body: "Full", taste:"Dry"}, {name: "Malbec", body: "Full", taste:"Dry"}, {name:"Zinfadel",body:"Medium",taste:""}, {name: "Montepulciano", body: "Medium", taste:"Dry"}, {name: "Merlot", body: "Medium", ...

Problem in running Dash DatePickerRange with Graph

I am new to Python programming. I am trying to add a date range to my graph using DatePickerRange in Dash but it doesn't seem to work. The following message is displayed every time I click on the link: My data frame is in the following format: Date (index, YYYY-MM-DD), Machine, Start Time (YYYY-MM-DD HH-MM-SS), Parameter 1, Parameter 2 My inputs are: start date, end date, parameter (from drop down). Output: line graph for the specified date range with "Parameter" on the y-axis, "Start Time" on the x-axis, legend="Machine" datatypes: Start Time: datetime64[ns] Parameter: int64 Machine: object I have tried plotting without DatePickerRange and it seems to work fine. Somehow, with DatePickerRange my inputs are not being read. I am not sure what I am doing wrong. I've provided part of the code below. Any help will be greatly appreciated! app = dash.Dash(__name__) app.layout = html.Div([ dcc.DatePickerRange( id='my-date-picker-range'...

Python Oracle_cx How to check what is being inserted

sql_insert=""" Insert into DIRECTOR (name,secondName) values (:1,:2) """ name='Tom' second_name='Musk' data=[name,second_name] try: cur.execute(sql_insert,data) except Exception as err: print('Error DIRECTOR',err) else: conn.commit() I want to print what is inserting to my database. Like in this case i want to see: Insert into DIRECTOR (name,secondName) values ('Tom','Musk') I tried to print it like this print(cur.fetchall()) and any different metods but no one is working. source https://stackoverflow.com/questions/71683570/python-oracle-cx-how-to-check-what-is-being-inserted

getElementbyId is returning null when window location is switched but an element with that Id definitely exists

So I have this code: window.location.href = "orderConfirmation.html"; document.onload = orderConfirmation(); // I have tried to use window.onload as well function orderConfirmation () { document.getElementById("test").innerText = "test" // This should make the p element have a body of "test" } In my orderConfirmation.html I have a paragraph element with an id of "test" I know its not a spelling error or anything like that. Any advice would be much appreciated. Via Active questions tagged javascript - Stack Overflow https://ift.tt/lVqoKZS

Copy text range and pate in web element using selenium python

I have excel which I need to copy range of rows and paste in web element. I tried following code by it's not working. I am not seeing data pasted in website. excel = client.Dispatch('Excel.Application') wb = excel.Workbooks.Open(file) sheet = wb.Sheets['Sheet1'] excel.Visible = 1 lastrow = sheet.UsedRange.Rows.Count row = str(lastrow) sheet.Range('A1:C' + row + '').Copy driver.find_element(By.XPATH, "//textarea[@id='activity-stream- textarea']").send_keys(Keys.CONTROL,"v") source https://stackoverflow.com/questions/71683022/copy-text-range-and-pate-in-web-element-using-selenium-python

Unable to rename/replace categories in a dataframe after removing unicode u

I am trying to rename the categories in a dataframe after removing the unicode u with a .replace('u','',regex) method due to the method removing the other 'u's in the text as well. I have tried using the replace, and the rename_categories method to change the categories into desired format using a dictionary to map but it remains unchanged after removing the unicode u. Does anyone know a better way I can approach this? I have attached a link to the CSV I am working with. '''uploaded = files.upload() yelpdf = pd.read_csv(io.BytesIO(uploaded['yelp_reviews.csv'])) print(yelpdf['NoiseLevel'].value_counts()) yelpdf['NoiseLevel'] = yelpdf['NoiseLevel'].astype(str) update_NoiseLevel = {'average': 'Average', 'lod': 'Loud', 'qiet': 'Quiet', 'very_lod': 'Very Loud'} yelpdf['NoiseLevel'] = yelpdf['NoiseLevel'].replace('u','',regex=Tr...

Add dots to truncate multiline overflow CSS

i need to add 3 dots '...' to truncate long text multinine. We can Not use -webkit-line-clamp: X; Since we do not know the number of rows or owr text. The phader item has fixed height and the text can be changed, so, its long will be different. I have tested several ways, the most ideal is this one: overflow: hidden; display: inline-block; max-height: 96% It works but I need to add 3 dots at the end of truncate text. Any help? thank you in advance Via Active questions tagged javascript - Stack Overflow https://ift.tt/lVqoKZS

Equal Table Columns Based On Content. Different Logic for First Column

kinda stuck on a styling problem for a table I am working on. Here are the requirements: First Column : Width is determined by the longest text in the column. Having a max width of 200px. Columns 2-n : Width is determined by the column (2-n) with longest text. Having a max width of 150px Table scrolls horizontally if it exceeds 100% Example: Header 1 Header 2 Header 3 short content short content Really Really long content Really Really long content short content short content So column 1 would have a width based on row 2 since is the longest. Column 2 & 3 would have a width based on column 3 row 1. Via Active questions tagged javascript - Stack Overflow https://ift.tt/Wiv3CQa

Is it possible to write a .csv file from a xarray.Dataset in python?

I have been using the python package xgrads to parse and read a descriptor file with a suffix .ctl which describes a raw binary 3D dataset, provided by GrADS (Grid Analysis and Display System), a widely used software for easy access, manipulation, and visualization of earth science data. I have been using the following code to read the binary data into a xarray.Dataset . from xgrads import open_CtlDataset dset = open_CtlDataset('./ur2m_eta40km_2001011312.ctl') # print all the info in ctl file print(dset) <xarray.Dataset> Dimensions: (time: 553, lat: 36, lon: 30) Coordinates: * time (time) datetime64[ns] 2001-01-13T12:00:00 ... 2001-05-31T12:00:00 * lat (lat) float32 -21.2 -20.8 -20.4 -20.0 -19.6 ... -8.4 -8.0 -7.6 -7.2 * lon (lon) float32 -47.8 -47.4 -47.0 -46.6 ... -37.4 -37.0 -36.6 -36.2 Data variables: ur2m (time, lat, lon) float32 dask.array<chunksize=(1, 36, 30), meta=np.ndarray> Attributes: comment: Relative Humidity 2m ...

Webscraping with RStudio

I'm trying to webscrap a website (actually I'm downloading a .xlsx file) with R, but I got stuck since I don't know too much about both R and HTML. I found the code below here , but it is not doing all the job. On the website I need to select (on a dropdown menu) the department and the checklist type, and then click on a download button (which opens the "download url" from the code bellow). The problem is the website allows me to download data from one department at a time. So I would like to find a way to do this with R, and download the files from all the departments just changing the ID (from both department and checklist). install.packages("rvest") library(rvest) url <- "https://website.com/auth/login?redirectUrl=" download_url <- "https://website.com/departments/file.xlsx" session <- html_session(url) form <- html_form(session)[[1]] filled_form <- set_values(form, email = "myuser...

pandas bar plot not taking list of colours

I'm trying to colour a bar chart with different colours, but when I pass a list of colours to the color argument, it still colors all bars the same. combi_df = pd.DataFrame(columns=['Labels', 'Number']) label_list = ['one','two','three','four','five','six','seven','eight'] int_list = [302,11,73,10,68,36,42,30] combi_df['Labels'] = label_list combi_df['Number'] = int_list fig = plt.figure() ax = plt.subplot(111) box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) c = ['#1b9e77', '#a9f971', '#fdaa48','#6890F0','#A890F0','#fdaa48','#6890F0','#A890F0'] combi_df[['Number']].plot(kind='bar',color=c ,legend=True, fontsize=10,ax=ax) ax.legend(ax.patches, combi_df['Labels'], loc='upper center',bbox_to_anchor=(0.75, 1)) ax.set_xlabel("...

Creating HTML table with multiple arrays using Javascript

Budget table I'm trying to recreate this budget table (see link above). Right now, I can't figure out how to get the table to generate everything when the page loads. I'm also confused as to how to write a loop that'll get each row to show with their header along with the cell value showing as 0. I've only been able to get the array tableHeader to show. Below is what I've done so far: window.addEventListener('load', function() { let tableHeader = ["Allocated", "July", "August", "September", "October", "November", "December", "January", "Feburary", "March", "April", "May", "June", "Expense", "Balance", "Percent Spent" ]; let tableRow = ["Salaries:", "Fringe: ", "Booking: ", "Legal Fees:", "Rent:", "Utilities:", "Te...

Loop through dropdown menu items to add class to next sibling in vanilla JS

I am learning JavaScript and am trying to wrap my head around creating a nav megamenu. Basically, each button has a div after it that contains the megamenu content. Hovering OR clicking on the button adds a class to the dropdown (I could also use a show/hide within the JS, not sure which is better). The class adds opacity and visibility to the div. I've created a "container" variable so it's only listening within the navbar, and then looping through the buttons to add the listener with nextElementSibling, but I can't seem to get it working. Markup: <nav id="main-nav"> <div class="nav-content"> <div class="nav-item"> <button class="nav-dropdown">Services</button> <div class="nav-submenu"> (Links) </div> </div> <div class="nav-item"> <button class=...

pyTelegrambotAPI user_id, message_id

I wrote a bot that measures the area of ​​a rectangle using the pygrambotapi library. If only one user uses the bot, the bot returns the correct answer, but if many users use the bot at the same time, the bot mixes up the answers and results in incorrect answers. How do I know which user wrote which message? a = '' b = '' float_pattern = r'^\d{1,7}\.\d{1,2}$' ... ... def firstside(message): global a if message.text.isdigit() or re.match(float_pattern, message.text): a = float(message.text) print('a:', a, type(a)) bot.send_message(message.chat.id, "good!") bot.register_next_step_handler(msg, secondside) else: msg = bot.send_message(message.chat.id, "Only number!") bot.register_next_step_handler(msg, firstside) def secondside(message): global b if message.text.isdigit() or re.match(float_pattern, message.text): a = float(message.text) print('b:...

Vuetify search in v-autocomplete with property item-text or another property?

I've a Todo list which is an array of objects with properities ( id, title, description ) Also I want to display title in v-autocomplete but when I do search for word it's fine, but what I want is Doing search for description or title . For Example: if I type programming , it will display to me Read books . Template <v-autocomplete v-model="idTodo" :items="todos" label="search todo..." item-value="id" item-text="title" /> Script visitCategories: [], todos: [ { id: 1, title: "Read books", description: "read books related to programming" }, { id: 2, title: "watch tutorials", description: "watch tutorials in many platforms like Youtube, Udemy...", }, ], idTodo: -1, Via Active questions tagged javascript - Stack Overflow https://ift.tt/NuzpWm1

Matplotlib not showing quiver to [0,0,0

I am trying to build a plot in 3d with matplotlib which has a dot at [0,0,0] and a quiver (vector) "looking" to it from [10, 10, 10]. But when I run the code I only get the dot. Why is that and how can I fix it? Code: import matplotlib.pyplot as plt fig = plt.figure() ax = plt.axes(projection="3d") ax.set_xlim3d(0, 20) ax.set_ylim3d(0, 20) ax.set_zlim3d(0, 20) ax.quiver(10, 10, 10, 0, 0, 0, length=2) ax.scatter(0,0,0) plt.show() source https://stackoverflow.com/questions/71653186/matplotlib-not-showing-quiver-to-0-0-0

onclick vs. event attributes of Button component

I am very new to React and Front End development. I recently came across something that confused me. Why would the following code fragment work properly: import React, { useState } from "react"; import "./styles.css"; import Button from "./Button"; export default function App() { const [buttonsOnCanvas, setButtonsOnCanvas] = useState([]); return ( <div className="App"> <Button event={() => { setButtonsOnCanvas([...buttonsOnCanvas, <Button />]); }} /> <div className="canvas">{buttonsOnCanvas}</div> </div> ); } but not this: import React, { useState } from "react"; import "./styles.css"; import Button from "./Button"; export default function App() { const [buttonsOnCanvas, setButtonsOnCanvas] = useState([]); function handleAddButtonClick() { setButtonsOnCanvas([...buttonsOnCanvas, <Button />]...

React Router v6 - re-rerenders

I am trying to use react router v6 for my application. Whenever I try to navigate from a component programmatically using useNavigate() hook, the entire component gets re-rendered when I navigate. I am trying to build a header which navigates between different pages. I want to avoid unwanted re-renders of the header component as the routing is taking place only on the children. However if I move the Button component to a separate component and use the useNavigate hook within that child component, the header component is restricted from re-renders. How ever the button component gets re-rendered. I would like to understand how this useNavigate() hook is designed and how should we properly use it to avoid these situations. Thanks in advance! export default function Header() { console.log("header rendering...") const navigate = useNavigate() return ( <> { MENUS.map((menu, index) => { return <Button ...

Printing out the entire Table Row of one or more found elements

This is my code so far: from bs4 import BeautifulSoup import requests import re day = input("Für welchen tag willst du den vertretungsplan sehen? \n Heute = 1, Morgen = 2, Übermorgen = 3 \n") if day == 1 or 2 or 3: pass else: print("Bitte gebe eine zahl von 1-3 ein!") url = f"https://jenaplan-weimar.de/vplan/Vertretungsplaene/SchuelerInnen/subst_00{day}.htm" result = requests.get(url) doc = BeautifulSoup(result.text, "html.parser") wunschklasse = input("Für welche Klasse möchtest du den Vertretungsplan sehen? (Achtung, bitte beachte die Abkürzungen!) ") klasse = doc.find_all(text=re.compile(f"{wunschklasse}.*")) # parent = klasse[0].parent # parent2 = parent.parent # parent3 = parent2.parent if klasse == []: print("Sry aber deine gewählte Klasse hat keine Vertertung bzw keinen Ausfall") else: print(f"Für {wunschklasse} wurde folgendes gefunden: {klasse}") As you can see, I let the user ...

ten un pequeño error, para ver si me pueden ayudar [closed]

me gustaria recibir una acespria referente a este error codigo: <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> el error que me sale asi y la verdad no se que hacer, soy nuevo en andorid studio AGPBI: {"kind":"error","text":"Android resource linking failed","sources":[{}],"original":"ERROR:AAPT: error: resource style/AppTheme (aka com.example.domiciliosblader:style/AppTheme) not found.\nerror: failed linking references.\n\n ","tool":"AAPT"} ERROR:AAPT: error: resource style/AppTheme (aka com.example.domiciliosblader:style/AppTheme) not found. error: failed linking references. Via Active questions tagged javascript - Stack Overflow https://ift.tt/JTFRdio

UnKnown unable to find smtp.gmail.com: No response from server

I tried setting up nodemailer Initially I set it up with my gmail account. I have disabled two-factor authentication on it, and enabled IMAP. Here is the function that is supposed to send emails: import { sendMailType } from '../../types/sendMail.d'; import nodemailer from 'nodemailer'; export const sendMail: sendMailType = async (to, link) => { const transporter = nodemailer.createTransport({ host: 'smtp.gmail.email', port: 587, secure: false, auth: { user: process.env.USER, // exampleFrom@gmail.com pass: process.env.PASS, // password }, }); let info = await transporter.sendMail({ from: `Mikita <${process.env.SMTP_USER}>`, to, subject: 'Follow the link to confirm your email address', text: '', html: ` <div> <h1>Follow the link to confirm your email address</h1> <a href="${link}" target="_blank...

How to posititon text in a slick slider and ensure it does not move around

I'm currently trying to overlay text over the image in my slick slider, however even though I have overlaid the text when I resize the window the text seems to move around in the image. How do I fix this? Is there a different way to overlay text over an image in an image carousel? please do advise, my code pen is also linked below This is my codepen https://codepen.io/rahil8533/pen/OJzpzxo HTML code <html> <head> <title>Slick Playground</title> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css"/> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.7.1/slick-theme.css"> </head> <body> <section class="regular slider"> <div> <img src="https://s26.postimg.cc/7ayxq3q5l/cg5.jpg"> ...

"TypeError: ___ object is not subscriptable" in Python and how can I fix it?

I have been tasked on building a code using queues and a class in which you get three options: Generates a new number Calls on the first number of the queue and takes it out of the main queue(there is an auxiliary queue for that) Shows the already called numbers This is the class created: class Fila: def __init__(self): self._vet = [] def enqueue(self, item): # enfileirar self._vet.append([-1]) def dequeue(self): # desenfileirar self._vet.pop(0) def front(self): # mostrar o 1o da fila, sem remover! return(self._vet[1]) def is_empty(self): # retorna se a fila esta vazia if len(self._vet) == 0: return True return False def __len__(self): return len(self._vet) def __str__(self): # representacao da fila como string return str(self._vet) And this is the code I came up with: from classeFila import * if __name__ == "__main__": ...

user existence check not working - discord.js

I'm trying to write a discord bot. Now there is one command in which another user is selected. So far, all commands work except for one, checking for the existence of a user. That's how I do it if (!userToMarry) { return message.channel.send('Please try again with a valid user.')} If there is no such user, then a corresponding message should be displayed. But instead I get this message: You provided an invalid userToMarry. Please try again. Respond with cancel to cancel the command. The command will automatically be cancelled in 30 seconds. How can this be fixed? The second part of the error bothers me more, because of it the first one occurs, as far as I understand, this is a built-in command from discord.js-commando Can it be turned off somehow? Please try again. Respond with cancel to cancel the command. The command will automatically be cancelled in 30 seconds. const { Command } = require('discord.js-commando'); const db = require("...

Multiply row with upper row in a column of DataFrame (Python)

I have a dataframe below and I want to add another column called "CUMULATIVE". To get the value of that column you need to just multiply [DAILY]row(x) * [DAILY]row(x-1). In excel it is pretty simple, because you only need to paste formula "=A2*A1" in the the second row and just drag it down. But it is getting hard for me to repeat it in python. Do you have any ideas how to do it ? I used the below line but it is not correct, because because it multiplicates with each above rows, instead of with just 2 rows nearby. df['cumprod'] = df.groupby('TICKER')['MNOZNIK_DZIENNY'].cumprod() source https://stackoverflow.com/questions/71627582/multiply-row-with-upper-row-in-a-column-of-dataframe-python

Selenium / Use pagination on site?

i want to trigger the pagination on this site: https://www.kicker.de/bundesliga/topspieler/2008-09 I found the element with this XPATH in the chrome-inspector: driver.find_element(By.XPATH,"//a[@class='kick__pagination__button kick__icon-Pfeil04 kick__pagination--icon']").click() Now i want to click this element to go one page further - but i get an error. This is my code: import time from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from sys import platform import os, sys from datetime import datetime, timedelta from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from webdriver_manager.chrome import ChromeDriverManager from fake_useragent import UserAgent if __name__ == '__main__...

Typescript not bundling modules

I have a node application that compiles typescript files to a dist folder and then serves these files as lambda resolvers via aws cdk. Here is an example of my setup: The code register.ts import ValidateUserFields from '../utils/forms'; exports.main = async function (event: any, context: any) { return { statusCode: 200, }; } register-lambda-config.ts import { Construct } from 'constructs'; import * as apigateway from 'aws-cdk-lib/aws-apigateway'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as s3 from 'aws-cdk-lib/aws-s3'; export class FrontendService extends Construct { constructor(scope: Construct, id: string) { super(scope, id); const api = new apigateway.RestApi(this, 'frontend-api', { restApiName: 'Frontend Service', description: 'This service serves the frontend.', }); const functionName = 'register'; const handler = new lambda.Function(...

Paypal Smart Buttons sales tax by state

Have to charge sales tax if the order is in Texas, but do not know the address until after customer has entered it. The only event that seemed reasonable was onShippingChange, but after the customer clicks continue, PayPal sends back an error page saying this are not working as expected. I can not be the only person that needs to charge sales tax with these new "Smart" buttons. <script> const baseOrderAmount = 20.00; function initPayPalButton() { paypal.Buttons({ style: { shape: 'pill', color: 'blue', layout: 'vertical', label: 'paypal', }, createOrder: function(data, actions) { return actions.order.create({ purchase_units: [ { "description": "Add product to buy", "custom_id": ...

Tic tac toe move shows up in other slot in array then on the board. javascript

I'am creating a tik tak toe game with javascript. So right now i'am making it that you can play vs the computer. And i got it to work but right now it does fill in a field on the board, and i also have a array with the gameState to track which fields on the board are already filled in. But what it does right now is that in that array the move of the computer gets in a wrong position SOMETIMES. Not always but like 50/50 and sometimes it doesn't even showup in the array. Ill put my code for the computer down below. The fields variable is just a querySelectorAll for the fiels of the board. function handleComputerMove() { const emptyFields = []; let randomField; if (!gameActive || !gameState.includes("")) { return; } fields.forEach(function(cell){ if (cell.textContent == '') { emptyFields.push(cell); } }); randomField = Math.ceil(Math.random() * emptyFields.length -1); emptyFields[randomFiel...

Using Shopify Product AJAX API on Checkout.Liquid

Goal: To create a product upsell section within checkout.liquid in a Shopify Plus store by checking the cart's products metafields for the appropriate upsell product. Issue: The main issue I am running into is retrieving any response from the Product AJAX API. I retrieve the handles which are stored in the metafields using this liquid code: var recommendation_handle = []; I then try to get the product data from the Shopify Product API, but I just receive a 404 error. var storeURL = "https://www.examplestore.com"; jQuery.getJSON(storeURL + "/products/"+ recommendation_handle[0], function( product ){ productTitle = product.title; console.log(productTitle); }); It looks to be that the url redirects to a unique checkout url. Is there a different way I can call the Product AJAX API within checkout.liquid? Via Active questions tagged javascript - Stack Overflow https://ift.tt/Coqgp5D

Which expected.conditions For Select?

I have a dropdown menu where I can select hotmail.com with Selenium. The following code is working: Select(driver.find_element(By.XPATH, '//*[@id="MemberName"]')).select_by_value('hotmail.com') But now I want to add WebDriverWait and expected.conditions to it to make it more dynamic. But which expected.conditions should I use? I guess elementToBeSelected makes less sense... I am searching for something like: Select(WebDriverWait(driver, 15).until(EC.element_to ??? ((By.XPATH, '//\*\[@id="MemberName"\]'))).select_by_value('hotmail.com') source https://stackoverflow.com/questions/71622659/which-expected-conditions-for-select

Unable to redirect user to login page after authentication check in Express.js

I have been attempting to redirect users to a login page after submitting a request to the home page if they are not logged in, but they keep getting redirected to the home page regardless. I have a method that is used to verify if they are logged in and returns a boolean with their status, then I have written another helper function using this method to redirect the user: const verifySession = (req, res, next) => { if (req.session) { models.Sessions.get({hash: req.session.hash}) .then(sessionInfo => { return models.Sessions.isLoggedIn(sessionInfo); }) .then (status => { if (!status) { console.log(‘status’, status); res.redirect('/login'); } else { next(); } }); } }; The console.log for status is returning false as expected, but still no redirect is occurring. I have tried using this helper function in several different ways in my express request handler: app.get('/', (...

React-flow & dare: reactFlowInstance.fitView() fits the instance in the screen after 2nd button click. (1st only changes the direction of the graph)

I have tried different ways of implementing this beauty, but it doesn't seem to work. My problem is that when I hit the button, I want to change the layout of the graph, which happens and I am glad for it, but I also want my graph to be centered (fit) on the screen. The first button click changes the direction, but doesn't fit the instance. To fit the instance I need to hit the button for a second time. I guess it has to do with asynchronous JS or? This is my code: const onChangeTreeLayout = useCallback( (treeLayoutDirection) => { const layoutedElements = getLayoutedGraphElements( elements, treeLayoutDirection, setTreeLayoutDirection ); setElements(layoutedElements); }, [elements] ); Then how I get the instance and trigger it follows: Note: I can't use useReactFlow() hook as we decided not to migrate to a newer version. But useZoomPanHelper does its work anyway. const reactFlowInstance = useZoomPanHelper(); ...

Why is the the text "help" not visible, blue border of div(class=main) not visible and red border of div(class=head) not visible?

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lost and Found</title> <link rel="stylesheet" href="style.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="<link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Anton&display=swap" rel="stylesheet"> </head> <body> <div class="nav" > <i...

fastest way to stack ndarrays

Gist Basically I want to perform an increase in dimension of two axes on a n-dimensonal tensor. For some reason this operation seems very slow on bigger tensors. If someone can give me a reason or better method I'd be very happy. Goal Going from (4, 8, 8, 4, 4, 4, 4, 4, 16, 8, 4, 4, 1) to (4, 32, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 1) takes roughly 170 second . I'd like to improve on that. Below is an example, finding the correct indices is not necessary here. Example Code Increase dimension (0,2) of tensor tensor = np.arange(16).reshape(2,2,4,1) I = np.identity(4) I tried 3 different methods: np.kron indices = [1,3,0,2] result = np.kron( I, tensor.transpose(indices) ).transpose(np.argsort(indices)) print(result.shape) # should be (8,2,16,1) manual stacking col = [] for i in range(4): row = [np.zeros_like(tensor)]*4 row[i]=tensor col.append(a) result = np.array(col).transpose(0,2,3,1,4,5).reshape(8,2,16,1) print(result.shape) # should b...

python equal strings are not equal with new line character in it

I have a password. It contains newline (lets for now omit why) character and is: "h2sdf\ndfGd" This password is in dict my_dict . When I just print values of dict I get "\" instead of "" - "h2sdf\ndfGd" ! Don't understand why. When I get it and use it to authenticate to web server, it says that Authentication fails. When I try to compare: my_dict["password"] == "h2sdf\ndfGd" it returns False . But when I try just print(my_dict["password"]) I get h2sdf\ndfGd which is identical, but for python it is not. Why? I am lost. source https://stackoverflow.com/questions/71608042/python-equal-strings-are-not-equal-with-new-line-character-in-it

Apostrophe CMS: filtering apostrophe-events based on a field from the (extended) widget definition

We have locations (and location-pages) as the primary page type on our site. We use the apostrophe-events module to contain basic event (day, time, location, etc.) information which is then presented via widgets within the associated location page. Our events/event-pages definitions have a required 'location' field to associate a location, and work as expected. We have a 'featured-event-widgets' defined that presents a single, selected, event. I am trying to implement the events modules standard 'events-widgets', which presents multiple events, however I want to filter the returned events by associated location and am running into a problem. The default implementation works as expected - it finds x upcoming events (i.e. events that haven't happened/finished yet), where x is an arbitrary number specified in the widget, and passes the collection of events to the widget.html template for expression. My issue is that the default widget provides the next even...

Click all google AdSense block buttons at once?

Hello guys can anyone help with a script or trick to click all AdSense Block buttons at once I used this one but it took to much time setInterval(function(){ toggl=document.querySelector('.all-networks-table div.material-toggle[aria-pressed=false]'); if (toggl==null){document.querySelector('.all-networks-table material-button.next').click()}else{toggl.click()} }, 1000); Via Active questions tagged javascript - Stack Overflow https://ift.tt/jC63uEl

NodeJS: UnhandledPromiseRejection when promise is rejected before await

I have two promises without catch blocks in the beginning and I'm doing await on both of them later with catch blocks. Second promise reject s before first promise resolve s. So, while I'm still await ing on the first promise, second promise is reject ed and since I have not attached the catch yet, it crashes the server with UnhandledPromiseRejection . Is there a way to make p2's reject propagate to await p2 , like it does in case when p2 resolve s? PS: I cannot attach the catch in the beginning itself. Adding the code below for reference. In stackoverflow it works fine for some reason, but when run from local, the server crashes. async function main() { console.log("starting"); let p1 = new Promise((resolve, reject) => { console.log('p1 sleeping'); setTimeout(function() { console.log('p1 awake'); resolve('p1 resolved'); }, 5000); }); let p2 = new Promise((resolve, reject) => { console.log...

Input onchange not firing at all in React App

I am currently working on an app using React and I've encountered a strange problem. I have an input whose type = "file" and an onChange event handler. I am using this to have the user select a photo and upload it to a library. The problem is that when selecting this input button, the file picker window is not opening at all. This same exact function was working in this app previously and then suddenly stopped working. It also works when I move it into another React app and try running it there. Does anybody know what could cause an onchange to stop firing in one React app, while working in another app that is running the same exact code? Again, the code works when I open it with another React App. I click on the 'Choose a file' button, and my file picker opens up to allow me to choose one as you might expect. However, when I click on this button in the app that I am working on, nothing happens (can't even log to the console). Via Active questions tagged jav...

How to find best route to reach from source to destination [closed]

const first_line = [a,b,c,h,e,f,g] const second_line = [h,i,j,k,m] const third_line = [o,n,m,p,q] const fourth_line = [aa,bb,cc,p,dd,ee,ff] Above is the kind of metro rail arrays with some stations. So I want to know how can I calculate the shortest distance and choose best line to reach there. How i find the shortest route and get all the stations in the array that i need to pass or change trains. Like a to p or a to ff Please let me know if anybody can provide me good login of it in javascript Via Active questions tagged javascript - Stack Overflow https://ift.tt/jC63uEl

How can I make function public?

I want to make an API that takes HTTP Requests body and sends that body with the TCP server. I'm using Express and Net library for Node.JS. So I have a file was named MakeAnnounce.js. Inside that file, code takes the "announce" value from the body of the request and write it to the database. Then it needs to write that value to the TCP server. TCP Server is in another file. But I don't know how can I call it. Because "socket.write" needs to be in something, like "server.on('connection', function (socket)". How can make it public? Like where ever I want to use the "socket.write" function. I tried to "module.export" but it didn't work. Also, I tried to declare the "socket" function outside of the "server" but I'm unable to do that. const db = require('quick.db'); module.exports = (req, res) => { const duyuru = req.body; const sinif = req.get("sinif"); if(db....

Is it possible to hide the getpass() warning?

Is it possible to hide the message that gets displayed if getpass() cannot hide the message? GetPassWarning: Can not control echo on the terminal. Warning: Password input may be echoed. Is it possible to replace this message with something else more user friendly? If it is, how? source https://stackoverflow.com/questions/71543613/is-it-possible-to-hide-the-getpass-warning

Below is my List I need to get just the numbers and currency out of this. Any solutions? [closed]

[' 6.99 €\n ', ' 7.99 €\n ', ' 9.99 €\n ', ' 9.99 €\n ', ' 9.99 €\n ', ' 4.99 €\n ', ' 6.99 €\n ', ' 4.99 €\n ', ' 4.99 €\n ', ' 14.99 €\n ', ' 12.99 €\n ', ' 4.99 €\n ', ' 14.99 €\n ', ' 9.99 €\n \n\n 1.99 €\n ', ' 9.99 €\n \n\n 1.99 €\n ', ' 12.99 €\n \n\n 4.99 €\n ', ' 9.99 €\n \n\n 2.99 €\n ', ' 14.99 €\n \n\n 12.99 €\n ', ' 9.99 €\n \n\n 3.99 €\n ', ' 9.99 €\n \n\n 2.99 €\n ', ' 9.99 €\n \n\n 2.99 €\n ', ' 12.99 €\n \n\n 9.99 €\n ', ' 12.99 €\n \n\n 9.99 €\n ', ' 12.99 €\n \n\n 9.99 €\n '] source https://stackoverflow.com/questions/71593302/below-is-my-list-i-need-to-get-just-the-numbers-and-currency-out-of-this-any-so

Python: How to transform JSON file into an XML file and modify its keys

I have an XML file like this: <XML> <Report> <ReportNumber>178414417</ReportNumber> <ReportDatetime>2022-03-23T21:10:04</ReportDatetime> <Sender>Alexandra Bell</Sender> <Receiver>Tamara Watson</Receiver> <MessageToReceiver>Miss Watson, come here, I want to see you.</MessageToReceiver> </Report> </XML> and I would like to transform it into a JSON file which looks like this: { "report": { "report_number": 178414417, "report_datetime": "2022-03-23T21:10:04", "sender": "Alexandra Bell", "receiver": "Tamara Watson", "message_to_receiver": "Miss Watson, come here, I want to see you" } } I am able to carry out JSON to XML transformation using json and xmlschema (simple outline below) but what I'm not sure how to properly add that underscore to...

How to be sure if the files are uploaded in client side and show a message that files are successfully uploaded?

I've built an express application which people can upload images to server (files are parsing by multer module). I want to send an alert that says "Files are successfully uploaded" when the files are uploaded. I don't want to redirect user and then show the alert. I couldn't find any solution for that. var express = require("express"); var bodyParser = require("body-parser"); var multer = require('multer'); var app = express(); app.use(bodyParser.json()); var storage = multer.diskStorage({ destination: function (req, file, callback) { callback(null, './images'); }, filename: function (req, file, callback) { callback(null, file.fieldname + '-' + Date.now() + ".jpg"); } }); var upload = multer({ storage: storage }).array('userPhoto', 5); app.get('/', function (req, res) { res.sendFile(__dirn...

Iterating a list to apply a function to each element from current position

Let's say I have a list with the following values: values=['foo','bar','lorem','ipsum'] I want that for every element of the list, iterates the entire list adding up the length of the current item + all the other lengths. This is done by a function that does the following: def sum_length(first_string,second_string): return len(first_string)+len(second_string) My code looks like this for i,_ in enumerate(values): counter=i while counter < len(values): print(sum_length(values[i],values[counter])) counter+=1 So the first iteration would be 1. len('foo') + len('bar') 2. len('foo') + len('lorem') 3. len('foo') + len('ipsum') Second: 1. len('bar') + len('lorem') 2. len('bar') + len('ipsum') This is not very effective with very big lists or more complex functions, how could I improve my running time? source https://stackoverflow.com/q...

What is a virtual for an URL in Mongoose?

I am currently following a tutorial on implementing a database (Mongoose) in a simple website created using Express-framework. I do not have any problem understanding the concept of models, but I fail to make sense of the lines following the comment " Virtual for book's URL " in the code attached. How do these lines operate, and what role does having a virtual property have in this context? var mongoose = require('mongoose'); var Schema = mongoose.Schema; var BookSchema = new Schema( { title: {type: String, required: true}, author: {type: Schema.Types.ObjectId, ref: 'Author', required: true}, summary: {type: String, required: true}, isbn: {type: String, required: true}, genre: [{type: Schema.Types.ObjectId, ref: 'Genre'}] } ); // Virtual for book's URL BookSchema .virtual('url') .get(function () { return '/catalog/book/' + this._id; }); //Export model module.exports = mongoose.model('Book',...

Python - Push forward weekend values to Monday

I have a dataframe (called df) that looks like this: I'm trying to take all weekend 'Volume' values (the ones where column 'WEEKDAY'=5 (saturday) or 6(sunday)) and sum them to the subsequent monday(WEEKDAY=0). I tried a few things but nothing really worked, taking an example from the last three rows: What I'm expecting is this: To reproduce the problem: !wget https://raw.githubusercontent.com/brunodifranco/TCC/main/volume_por_dia.csv df = pd.read_csv('volume_por_dia.csv').sort_values('Datas',ascending=True) df['Datas'] = pd.to_datetime(df['Datas']) df = df_volume_noticias.set_index('Datas') df['WEEKDAY'] = df.index.dayofweek df source https://stackoverflow.com/questions/71576071/python-push-forward-weekend-values-to-monday

How to play a tween animation on key press multiple times

I am trying to make a robot that can perform certain animations when keys are pressed. When I press the "J" key I would like the robot to jump up and down. I am using Three.js and Tween.js to accomplish this. So far I have a scene made with light and a camera. I am creating the different parts of the robot through functions. I have an example of one of these functions below. function createHead() { const head = new THREE.Mesh( new THREE.BoxGeometry(30, 30, 30), new THREE.MeshLambertMaterial({ color: 0x669999 })); head.position.y = 30; head.position.z = -250; head.rotation.y = 5; scene.add(head); var jumpTween = new TWEEN.Tween(head.position).to({y: head.position.y+20}, 1000).repeat(1).yoyo(true).start(); } Here is my function for updating function update (event) { if (String.fromCharCode(event.keyCode) == "J" || isJumping) { isJumping = true; TWEEN.update(); } // Draw! ...

Can i send the letter ț to the keyboard?

Can anyone help me? I've been trying to fix it but i don't think i can import win32com.client as comclt wsh= comclt.Dispatch("WScript.Shell") wsh.SendKeys("ț") i dont know how to actually do it source https://stackoverflow.com/questions/71577774/can-i-send-the-letter-%c8%9b-to-the-keyboard

How to debug click event is not trigger on mobile phone?

I have this code here where it works perfectly on my local Macbook pro, simulated test as mobile phone in Google Chrome. But when I deploy it, and clicked on the mobile phone itself, no event seems to be detected, it's like it ignore click event completely. //show age diff var showAgeDiff = false; var oldText = $( "#age").text(); var sdt = new Date(''); var difdt = new Date(new Date() - sdt); var babyAgeToCurrentDate = (difdt.toISOString().slice(0, 4) - 1970) + "Y " + (difdt.getMonth()+1) + "M " + difdt.getDate() + "D"; $("#age, #babyNameMobile").click(function() { showAgeDiff = !showAgeDiff if(showAgeDiff){ $( "#age" ).text(babyAgeToCurrentDate); } else { $( "#age" ).text(oldText); } }); Live View https://mybabies.app/baby/a4b7efe4-9c2f-4c48-b5b1-cc516a8f027f?code=krR4Mn Desktop No issue, works as expected. It change from "~8 weeks" --> 0Y 3M 1D Mo...