Skip to main content

Posts

Showing posts from October, 2022

Plotly Dash, center multiple cards within dbc.Row

How can I center the cards below? I have passed justify='center' & align='center' It does not make a diffrence and aligned to the left? code below def meta_card(values: dict, label: str = None, cls_name: str = None) -> list[dbc.CardHeader, dbc.CardBody]: card_meta = [ dbc.CardHeader(label, style={"textAlign": "center"}), dbc.CardBody( dbc.ListGroup( [dbc.ListGroupItem([f"{k}: {v} ", meta_pill(v, '1000')]) for k, v in values.items()], flush=True, ) ), ] return card_meta dash_cards = html.Div( dbc.Row( [ dbc.Col( dbc.Card( meta_card(standing_card_meta, label="Standing", cls_name="total_standing_card"), color="primary", outline=True, style={'width': '25rem'} ...

I need to optimaze my code that containt two loops. The code is for calculating a sum of numbers

I was traying to write a code that calculate the sum of 2*j+i+1 where 0<=j<=i<=n but I wasn't very optimazed there are my code : def get_sum(n): s=0 for j in range(n+1): ss=0 ss=sum(2*j+i+1 for i in range(j,n+1)) s+=ss return s Write to calculate a a sum of 2*j+i+1 where 0<=j<=i<=n but it wasn't optimazed source https://stackoverflow.com/questions/74267736/i-need-to-optimaze-my-code-that-containt-two-loops-the-code-is-for-calculating

Return a CSV File from Flask to Angular Client

I have an app which runs an Angular Frontend and Flask Backend. I have created a button that trigger a API call to Flask that queries my database and returns a dataframe (df) in a CSV format. I believe I have coded the Flask part correctly as I can't see any errors in the logs. However, I do get an error appearing on the client side which is: SyntaxError: Unexpected token '', ""... is not valid JSON I suspect its because my subscribing of the data is done incorrect, but I am unsure of what needs to happen Angular (When the Download Button is clicked, this is triggered) fullDownload() { let responseData: any; const date = this.selectedDate; const id= this.selectedId; this.seriveFile.getFullData(date, id).subscribe( data => { responseData = new Blob([data], {type: 'text/csv'}) const url = window.URL.createObjectURL(responseData); window.open(url); ...

How can I extract all possible errors in Mongoose?

I was studying Mongoose schemas and there is a thing I can not get it or maybe is not possible. var schemaClient = new mongoose.Schema({ Name:{ type:String, required:[true,'The name is obligatory'], maxLength:[10,'Max 10 characters'], match:[new RegExp('^[a-zA-Z]+$'),'only letters without white space.'] } }) The attribute name have three validators [required,maxLength,match] if for example I create a Client like that: var client={Name:'asdasd asdas asdasd asdd'} here there are two errors: [maxLength,match] However mongoose always stop validate when throw the first error, in this case is the maxLength validator error. var modelClient = mongoose.model('Client',schemaClient); try{ modelClient.validate(Client) }catch(error){ console.log(error.errors); } But I am interested to throw all possible errors for the attribute Name. I mean.... the attribute name have the error [maxLength,match]....and I want to catch the erro...

Postman: How to dynamically validate JSON value without using a switch statement

I want to dynamically validate the value of JSON request parameters without the use of switch statement I tried the code below which works fine but it is not optimized as I have to create a case for each field I am validating. If there a way to achieve the same result without using switch statement if(responsecode == 200){ const cfields = ["author", "title", "genre", "price"]; cfields.forEach(myFunction); function myFunction(item) { var reqprop = item; pm.test("Verify that "+reqprop+" is not empty", function () { switch(reqprop) { case'author': pm.expect(requestObjectprop.author, "Request is successful with a null '"+reqprop+"' ").and.not.be.empty; //pm.expect(contentValue).to.be.a('string').and.not.be.empty break; case 'title': pm.expect(requestObjectprop.title, "Request is successful with a null '"+reqprop+"' ").an...

Im getting this error trying to use the clarifai api, how can i fix it?

im using the clarifai face recognition Api and getting an error on my console saying: "TypeError: axios.post is not a function". anyone knows how do I solve it? i dont use Axios in my code, but i think the API uses it. thanks I tried installing Axios and clarifai again and it did nothing Via Active questions tagged javascript - Stack Overflow https://ift.tt/TvU56LY

How to merge audio and video in bytes using ffmpeg?

I'm trying to merge a video with its seperate audio file in Python. I have both the video and the audio as bytes in memory and I would like to know how to allow ffmpeg-python to merge them. I have seen it done through ffmpeg.concat and by reading the files from disk using ffmpeg.input, but when my program downloads the files, it saves them in memory as bytes objects. I tried passing the byte objects into ffmpeg.concat but it threw an error as it is expecting stream objects: TypeError: Expected incoming stream(s) to be of one of the following types: ffmpeg.nodes.FilterableStream; got <class 'bytes'> How should I approach the problem when my files are in bytes format? source https://stackoverflow.com/questions/74256808/how-to-merge-audio-and-video-in-bytes-using-ffmpeg

How do I create a cookie in svelte and access it?

I am trying to create a cookie in svelte (and I am also using svelte kit) and access it. I am want to use the cookie for authentication purposes, more specifically, to store a JWT Token. I am tried implementing pure JS code, such as getCookie() and setCookie() as shown here W3Schools - JavaScript Cookies . But I can't get access to the document. I have also tried serialize from the cookie npm package, as shown below, and I have also tried using browser as shown below. import { serialize } from "cookie"; import { browser } from '$app/environment'; Via Active questions tagged javascript - Stack Overflow https://ift.tt/5z1NAW2

How to see output on VS Code with Typescript?

I am doing some code challenges using Typescript in VS code. When I try to run the code and see the output, I get "Code Language is not supported or defined". The language mode is set to Typescript React (I also tried just Typescript). And the file has a .tsx ending. Finally, I also did compile the file and make a duplicate .js version. Is there something I am forgetting? Via Active questions tagged javascript - Stack Overflow https://ift.tt/5z1NAW2

Why do I receive null for the value of player.sprite?

the error: Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLCanvasElement or HTMLImageElement or HTMLVideoElement or ImageBitmap or OffscreenCanvas or SVGImageElement or VideoFrame)'. here is the player value in the editor: let player = { x: 100, y: 100, h: 0, vh: 0, v: 0, hp: 100, controls: { turnLeft: false, turnRight: false, accelerate: false, deccelerate: false, }, sprite: document.getElementById("fighter3"), } here is the player value in the console: controls: {turnLeft: false, turnRight: false, accelerate: false, deccelerate: false} h: 0 hp: 100 sprite: null v: 0 vh: 0 x: 100 y: 100 and here is the draw command: ctx.drawImage(player.sprite, player.x, player.y); I am trying to draw a sprite to canvas and when I use context.drawImage I get an error, I narrowed it down to the fact that ...

Projectile doesnt spawn and stops main playable character from moving Javascript

When I click the right green button it stops the middle circle's movement and doesn't visually show a bullet. I set the the x-axis the same for the green player and for the bullet but it only stops it's movement. I wanted for it to spawn a rectangle no matter where I am on the x-axis. Via Active questions tagged javascript - Stack Overflow https://ift.tt/5z1NAW2

How can I access the highest and lowest price from the price scale on TradingView?

I'm trying to access the highest and lowest values of the price scale on TradingView. I don't think it's possible but perhaps there is someone more clever than myself who has a solution. I have looked through the Pine Script v5 reference and cannot see any available methods to access price scale data. If you dig deep into enough into the page's javascript then I think some functions might reveal the data, however I think the functions are not useable outside of their file. Via Active questions tagged javascript - Stack Overflow https://ift.tt/mzEuqFG

How do i connect my authenticated service account Google People API to read contacts on my personal user account?

I have my service account JSON credentials in my environment. I am able to use the Google People API while connected to a service account. But I can't make requests to impersonate my personal user account which owns the platform. I throws error when i add my user Gmail as subject account. require("dotenv").config(); const { google } = require("googleapis"); let scopes = ["https://www.googleapis.com/auth/contacts"]; const init = async () => { console.log("Auth Started"); let auth = await google.auth.getClient({ scopes, }); // auth.subject = "username@gmail.com"; const { people } = google.people({ version: "v1", auth, }); let res = await people.connections.list({ resourceName: "people/me", personFields: "names", }); console.log(res); }; init(); Via Active questions tagged javascript - Stack Overflow https:/...

How to make image disappear or how to hide image from the screen? [duplicate]

I'm making my first pygame game, Plane Delivery game. I'm stuck at the menu. I created menu with my custom background image. Also, I created START button which is used to start the game. When player clicks the START button, I want to hide main menu background, and show the game's background image, world map. Thank you for help! There's code: import pygame pygame.init() window = pygame.display.set_mode((1920, 1080)) pygame.display.set_caption('Plane Delivery') POZADINA = (254, 0, 60) # BOJA POZADINE window.fill(POZADINA) clock = pygame.time.Clock() menu_img = pygame.image.load('Plane_Delivery2.jpg') menu_img = pygame.transform.scale(menu_img, (1920, 1080)) bg_img = pygame.image.load('background.jpg') bg_img = pygame.transform.scale(bg_img,(1920, 1080)) plane_sprite = pygame.image.load('avion3.png') x2 = 960 y2 = 540 # -- Main Menu -- #button class class Button(): def __init__(self, x, y, image, scale): width = image.ge...

it gives me syntax error on the line which i think is correct

#Task 4 a=274 n=3 while int(input("Enter your code: "))!=a: print("Wrong") if int(input("Enter your code: "))!=a and n==0: print("Phone blocked") else: print("Welcome, {your name and surname}" .format(your name and surname="Aqshin Hasanov")) at the end, it says invalid syntax error I tried using formatting, it gave error. source https://stackoverflow.com/questions/74248094/it-gives-me-syntax-error-on-the-line-which-i-think-is-correct

Javascript in bad body

function checkIsResetAvailable() { if(istimerStarted === false) { lapResetBtn.innerHTML = "Reset"; } else { lapResetBtn.innerHTML = "Lap"; } } There is an error on lines 74 and 77 please help me I tried to make a stopwatch and got an error Via Active questions tagged javascript - Stack Overflow https://ift.tt/mzEuqFG

Using different queries in the same component

is it possible to use different queries using react-query conditionally? I have the the same component with quite complex logic in two different places in my app. The only difference is in the endpoint I want to hit with my infiniteQuery based on prop received by the component. What is the best way of achieving this? I've went through documentation and different posts but have not found anything similar. Via Active questions tagged javascript - Stack Overflow https://ift.tt/mzEuqFG

How to template jsx with createBrowserRouter

From my understanding: <Route loader...> " only works if using a data router " data routers (like createBrowserRouter) don't allow for wrapping 'all' of the routes in jsx containing <Link> components. See examples Example: Non data routers <Router> <header> <Link to="/">Home</Link> </header> <Routes> <Route...> <Route...> </Routes> </Router> Example: data routers (throws error) full example const router = createBrowserRouter([....]); <div> <header> <Link to="/">Home</Link> </header> <RouterProvider router={router} /> </div> My question is this: How can we create a template that wraps the RouterProvider (and all the content it imports) with a template that makes use of <Link> functionality? Via Active questions tagged javascript - Stack Overflow https://ift.tt/mzEuqFG

I can't import data from gtm's data layer into my own database

I created a data layer in gtm and wrote a script to import the information reflected in this part into my own data store, but something seems wrong. I have a trigger called addToCard, and with this event, my script fires as it pulls the data. but my data block looks empty as seen in the image Please help, I can explain more details you want. at least give me advice.. ` <script> var SvstData={}; var a = window['dataLayer'] var x =[] var b a.forEach(item=>{ if(item.event=="addToCart"){ b=item } }) if(a){ b.ecommerce.add.products.forEach((item) = function() { x.push({ pId: item.id, pQty: item.quantity, pPrice: item.price, pName: item.name, url: '0', pimg: '0', image_url: '0', category_name: item.category, category_id: '0', brand: item.brand, brand_id: '0', product_code: '0', ...

Django installation failed

My pc recently started giving error in installing Django.... Look at the error message, what could be the cause please? I tried installing Django for my project, and it just throw an unexpected error message. I have the right Venv activation code so I expected it to work. source https://stackoverflow.com/questions/74240239/django-installation-failed

A random JS alert is appearing only in production - how to debug in browser?

I'm looking for any way to try and debug where a javascript alert is coming from. The alert itself isn't helpful, it's just the number 2 It doesn't appear in the code at first glance (and globally searching is ~4k+ entries to look through), and is only showing up in a specific region in production. It does not show up on our development servers. I've seen suggestions of adding a stack trace to every alert() call, but considering we cannot replicate it in our development environments and only in production, this isn't a viable option. HELP! Is there a way to stack trace it directly in browser without pushing code to production? I'm almost wondering if it's somehow coming from the JQuery library etc. Via Active questions tagged javascript - Stack Overflow https://ift.tt/H8QdEn7

Nuxt3 Dynamic Asset Import

I'm using Nuxt v3.0.0-rc.12 . I have a component that needs to show an image, but the image path changes based on the image prop: <template> <img alt="" :src="resolvedImage"> </template> <script setup> import { computed } from 'vue' const props = defineProps({ image: { default: '', type: String } }) const resolvedImage = computed(() => { return props.image ? new URL(props.image, import.meta.url).href : '' }) </script> And I use this component like that: <my-component image="../assets/somefolder/filename.png" /> I've read in the Vite docs that the correct way to do that is with new URL(url, import.meta.url) . It works, but not in the first page load (because SSR). I get this warning and the image is not displayed. What am I doing wrong? Via Active questions tagged javascript - Stack Overflow https://ift.tt/H8QdEn7

Vuetify not showing when i use jQuery append

I'm having trouble using jquery append with vuetify. I can't write any vuetify code in my javascript. It wouldn't show me the vuetify code, but it should work. I think it has something to do with vuetify having to be restarted when you want to insert a new vuetify code. new Vue({ el: '#app', vuetify: new Vuetify(), methods: { createList() { if (this.$refs.form.validate()) { $('#lists').append(` <v-card width="374" class="mx-10 my-12" elevation="5"> <v-system-bar color="${this.color.hexa}" dark><b>${this.name}</b></v-system-bar> <v-form ref="form" lazy-validation> <v-card-actions> <v-text-field v-model="name" ref="name" class="mx-5" :rules="jobsTitleRules" ...

how I can find out the position of two moving objects running in a track with respect of each other?

I have latitudes and longitudes of two moving objects. I need to find out and analyze the situation of these two. I know how to calculate the distance between given two lang/lat, but I am not sure how I can compare them. for example, how I can figure out when one of them is further than the other one. These two moving objects are running in a track. And I want to see which one is further in some point of the time. is there any way? let me know if you need me to provide some data. The image shows the track. the starting point is the right and finishing pint is the left. the following is longitude and latitude of two runners: 1-- 40.712841 -73.721023 2--40.712805 -73.720860 which one is further on the track? source https://stackoverflow.com/questions/74228243/how-i-can-find-out-the-position-of-two-moving-objects-running-in-a-track-with-re

What is list slicing when it has 2 colons? [duplicate]

In codecademy, the instructions say not to use [::-1] The program I am trying to accomplish is to print a string in reverse without using the reversed() function or using [::-1] Can somebody please let me know what it means in general? I know I'm not supposed to be using it, but I want to know. Thanks! source https://stackoverflow.com/questions/74228481/what-is-list-slicing-when-it-has-2-colons

Uploading a tar.gz file to S3 seems to corrupt it and makes it unreadable [closed]

I have a lambda function to generate presigned URL, using that URL via PUT request I am uploading a file to S3, on each S3 bucket it triggers a lambda function which processes the uploaded files, but when the lambda tries to open the file it says, uncompressed file My lambda functions are on Python Just a note when I upload file directly to S3 and when it triggers the lambda, everything works fine but when uploading file via generate_presigned_url, it starts giving compression error What am I doing wronh here? This is my lambda function to generate presigned url source https://stackoverflow.com/questions/74220785/uploading-a-tar-gz-file-to-s3-seems-to-corrupt-it-and-makes-it-unreadable

youtube fullscreen error on mobile in swiper js

I have a swiper carousel, when I click on the youtube fullscreen icon on mobile, it makes the page fullscreen, as if I pressed F11 <div style="--swiper-navigation-color: #0059b3; --swiper-pagination-color: #0059b3" class="swiper mySwiperPhone d-md-none d-block"> <div class="swiper-wrapper"> @if($imovel->videoYoutube) <div class="swiper-slide"> <iframe src="" style="width: 100%; height: 350px; object-fit: contain;" title="Vídeo do imóvel" frameborder="0" allow="fullscreen"></iframe> </div> @endif @foreach($fotos as $foto) <div class="swiper-slide"> <img src="" style="height: 350px; object-fit: contain;...

How to pass a ref to a child input component with Vue?

I'm currently trying to pass a ref to get the value of the input (base-input component) on submit. You will find below the two components. With the console.log in handleSubmit, email is always undefined. Thanks in advance for your help. Parent component <template> <form @submit.prevent="handleSubmit"> <div class="flex flex-col mt-10"> <form-label forInput="email" label="Email Address" /> <base-input type="email" name="email" ref="email" /> </div> </form> </template> <script> import BaseInput from "../UI/BaseInput.vue"; export default { components: { BaseInput, }, methods: { handleSubmit() { const email = this.$refs.email.value; console.log(email); }, }, }; </script> Child Input component <template> <input :type="type" :name="name" :ref=...

Does QGIS provide a code listener or script logger?

My Photoshop CS6 has a wonderful add-on known as ScriptLogger, where upon finishing selections/operations you have made you can see that in script form as a Javascript or Visual Basic Script. Does QGIS offer anything like that... preferably for Python? If not, why not? That would make an excellent learning tool/plug-in for QGIS. source https://stackoverflow.com/questions/74227264/does-qgis-provide-a-code-listener-or-script-logger

How to change the Redirect URI from HTTP to HTTPS within a FastAPI web app using fastapi_msal?

I am trying to setup Azure AD authentication for a web application using FastAPI. I am using the fastapi_msal python package to do this. The problem I am having is that when I go to the web app, I am able to login, but once i am authenticated, it says the redirect URI that the application is using begins with HTTP. However, Azure requires the redirect uri begin with HTTPS unless running the app locally. Does anyone know how I can change the redirect uri to begin with https instead? The code for my project pretty much exactly resembles the code from this example project here . However, I have found a similar project using Flask instead of FastAPI. And there is a specific portion of the code that addresses this redirect uri problem: # This section is needed for url_for("foo", _external=True) to automatically # generate http scheme when this sample is running on localhost, # and to generate https scheme when it is deployed behind reversed proxy. # See also https://flask.pallet...

Portugol Studio [closed]

Consider the following vector: [-5, 10, -3, 12, -9, 5, 90, 0, 1]; Implement an algorithm that analyzes the vector above and automatically creates a second vector containing only the positive numbers. Show this new vector on the screen. programa { funcao inicio() { inteiro vetor[] = {-5, 10, -3, 12, -9, 5, 90, 0, 1} para (inteiro posicao = 0; posicao < 9; posicao++) { se (vetor[posicao]>0) { escreva (vetor[posicao],"\n") } } } } Via Active questions tagged javascript - Stack Overflow https://ift.tt/XIp7yGY

How to post data from js client to golang server

I want to create a simple rest api authorization service where js/html is client, golang is server and postgres is db. I had success posting body from postman and I received expected answer and data were added to db. But when I am trying to do the same from my js/html client the answer is null - {"message":"Invalid request","status":false} . Here is my golang example code: var CreateAccount = func(w http.ResponseWriter, r *http.Request) { account := &models.Account{} err := json.NewDecoder(r.Body).Decode(account) //decode the request body into struct and failed if any error occur if err != nil { utils.Respond(w, utils.Message(false, "Invalid request")) return } resp := account.Create() //Create account utils.Respond(w, resp) } Client: 'use strict' const form = document.getElementById('form'); const url = "http://localhost:8080/api/user/login"; const myHeaders = new He...

Record CSV data being streamed over a UDP port from a smart phone in Python

So I am starting to learn robotics and how to work with sensors. As one of my first lines of effort, I am attempting to learn about calibrating Inertial Measurement Units (IMUs) and working with their data. To do so, I want to collect some data from the IMU on my iPhone. After some research, I found an app called "IMU Utility" which can collect this data and stream it over a network. When I start the stream and select CSV as the data format, I am presented with an IP address and a UDP port number (let's say IP: 555.555.5.555, port: 32000, these are fake just used for illustration). I want to collect this data on my computer and aggregate it into a single CSV file that I can play around with later for educational purposes. How would I go about doing this? I would like to do so in python however, this is not strictly necessary if there is a better language/toolkit for the task. Note: The app can also stream the data in JSON and Protobuf format. I'm grateful for any a...

How can I make a nav scrolling horizontally with buttons when media queries kick in? html css, javascript and boostrap 5.2

I'm trying to make a nav scrollable but horizontally and with buttons when media queries kicks in. I can't find any solution and it's becoming overwhelming. My team used bootstrap 5.2 and then used scss for styling the project. I think it was the worst mistake we did. We have to replicate EA site and it is starting to look pretty complicated. I am trying to replicate the same behavior of the "lastest updates" nav when resized. If you scroll down to "latest updates" in this link you can see it: https://www.ea.com/ What I've tried so far: my HTML with script at the end of the body: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Bootstrap demo</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" ...

Difference between data[0:4] and data.iloc[0:4]

Can anyone explain me whats the Difference between data[0:4] and data.iloc[0:4] when i run these 2 commands iam reciving same output Here is my code:- import pandas as pd data= pd.read_csv("C:/Users/Admin/PycharmProjects/pythonProject1/venv\Lib/site-packages/pandas/test.csv") print(data[0:4]) print(data.iloc[0:4]) output:- source https://stackoverflow.com/questions/74212248/difference-between-data04-and-data-iloc04

Un-Ending Loop?

Whenever I run this snippet: let longString = 0; let fact = 6; const lettersLeft = ["abcde"] const select = lettersLeft; let j = 1 while (j <= fact, j=j+1) { longString += select; } console.log(longString); it crashes my app. I'm thinking it is trying to run indefinately, or it cannot read something. How do I fix this because this is very important to my code. Via Active questions tagged javascript - Stack Overflow https://ift.tt/E9hzFAM

"Invalid URL" error when passing URL to .openByUrl Apps Script

I receive the error message "invalid url" with the instruction openByUrl(url) when I try to assign the url a value from an array passed from another workbook. let url = array[20]. The logged result of array[20] is the working url I want. I tried passing it without quotes, with single and double quotes, but no luck. If I hardcode the url in the script as let agentcrmUrl = "https://ift.tt/jQhsYD4......", all works fine. Thanks for any help! profile.forEach(function(agent,index,array) { //arrary from another workbook Logger.log(agent[4]); Logger.log(agent[20]); //pasted logged result in browser works fine let agentcrmUrl = agent[20]; //passed with/without single and double quotes let responses16Sheet = SpreadsheetApp.openByUrl(agentcrmUrl).getSheetByName("Form Responses 16"); let responses16 = responses16Sheet.getDataRange().getValues(); Searched solutions online. Via Active questions tagged javascript - Stack Overfl...

Data are overwrite in pandas how to solve that

Data are overwritten in pandas how to resolve these problem...... How I get out of for loop to solve these problem kindly recommend any solution for that However, with every iteration through the loop, the previously extracted data is overwritten. How can I solve this problem? from selenium import webdriver import time from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support.select import Select from selenium.webdriver.support import expected_conditions as EC import pandas as pd # url='https://www.amazon.com/dp/B00M0DWQYI?th=1' # url='https://www.amazon.com/dp/B010RWD4GM?th=1' PATH="C:\Program Files (x86)\chromedriver.exe" driver =webdriver.Chrome(PATH) df_urls = pd.read_csv('D:/selenium/inputs/amazone-asin.csv',encoding='utf-8') list_dicts_urls =df_urls.to_dict('records') item=dict() product=[] for url in list_dicts_urls: product_url = 'https...

Seaborn Swarmplot "hue" not coloring correctly / as expected

When I graph my data with Seaborn swarmplot, it orders the overlapping points "middle out". Meaning, the larger levels are in the middle and the smaller are on the edges (like 1,1,2,2,1,1 or 2,2,3,4,2,2 ). This messes up the hue coloration as confirmed by getting the index of the point that I am hovering over and labeling it (see below images for proof). What I am unsure about is, is it my labeling method that is incorrect or is it Seaborn's hue that is messing up? I've tried reordering the dataframe used for the plot and also setting the hue_order but nothing has worked correctly. Here is a snippet of the data: import pandas as pd from io import StringIO rejectionDF = StringIO(''' ID,Level,Days_After 472,3,3 678,2,3 491,3,10 621,3,10 314,4,11 575,3,11 654,3,11 356,3,12 403,3,12 301,2,12 557,2,12 405,3,13 694,3,13 770,3,13 361,2,13 452,2,13 484,2,13 750,2,13 371,3,14 458,3,14 474,3,14 483,3,14 705,3,14 418,2,14 481,2,14 583,2,14 729,2,14 797,2,14 818,2...

Adding count information to mapreduce output

I have data that came from sys.stdout mapper.py program as follows: input from stdout of previous mapper.py chevy, {mod: spark | col: brown} chevy, {mod: equinox | col: red} honda, {mod:civic | col:black} honda, {mod:accord | col:white} honda, {mod:crv | col:pink} honda, {mod:hrv | col:gray} toyota, {mod:corola | col:white} I would like to write a reducer.py or maybe even another mapper that takes this information and produces an output such as: Expected output chevy, {mod: spark | col: brown | total:2} chevy, {mod: equinox | col: red | total:2} honda, {mod:civic | col:black | total:4} honda, {mod:accord | col:white | total:4} honda, {mod:crv | col:pink | total:4} honda, {mod:hrv | col:gray | total:4} toyota, {mod:corola | col:white | total:1} the total is only for the keys (car brand), so chevy appears twice, honda appears 4 times, and toyota 1. I have tried a reducer.py program and it did not work. The program I wrote looks like this: curr_k = None curr_v = None k =...

Implementing TCP Server with Python-How to?

I have searched a lot on the forums for implementing TCP server using Python. All that I could find is a multi-threaded approach to TCP Server Implementation on a single port for interacting with clients. I am looking for Server sample code for creating sockets using different ports.I have clients with distinct port numbers.For example, One socket binding IP and portNo-2000 and second one binding IP and another port No. 3000 and so on. Could anybody provide pointers? source https://stackoverflow.com/questions/74194181/implementing-tcp-server-with-python-how-to

Google Maps API using Node.js and Express

i have an idea for a website that takes in ufo information from a certain API. i have been able to display information such as the location of the encounter. the API also returns coordinates of the encounters and i want to display a map with a marker of said location. the only way I'm able to obtain the specific data i want is by using the "<%=%>". the information is random each time so i hope there is a method similar that that above that will help me access the coordinates of each random case tracker.ejs <form method="GET" action="/tracker"> <section class = "theHeader"> <h1> Type in a location </h1> <h6>to track something</h6> <input type="text" name="location" placeholder="type in a location"> <input type="submit"> </form> </section> <section class="theInfo"> <div id="googleMap"><...

How to display runes in pycharm?

I want to write this in pycharm elder = 'ᚠᚢᚦᚨᚱᚲᚷᚹᚺᚾᛁᛃᛈᛇᛉᛊᛏᛒᛖᛗᛚᛜᛞᛟ' But it displays only empty squares elder = '□□□□□□□□□□□□□□□□□□□□□□□□' source https://stackoverflow.com/questions/74185627/how-to-display-runes-in-pycharm

Inherit a custom user models fields from parent class to a child class between two different applications

Hello kings and queens! I'm working on a project and got stuck on a (for me) complicated issue. I have one model (generalpage.models) where all the common info about the users is stored. In a different app (profilesettings), I have an app where all profile page related functions will be coded. I tried to inherit the model fields from the User class in generalpage.models into profilesettings.models by simply writing UserProfile(User). When I did this, a empty forms was created in the admin panel. So basically, the information that was already stored generalpage.models were not inherited into the profilesettings.models, I created an entire new table in the database. my questions are: Is it possible to create an abstract class for a custom user model? Is there a proper way to handle classes and create a method in profilesettings.models that fills the UserProfile form with the data already stored in database created by the User class? Can someone please explain how the informat...

How to set the default model to a variable if None was passed?

Can I make a default model in Pydantic if None is passed in the field? I am new to pydantic and searched for relevant answers but could not find any. I have the following code, from typing import Optional,List from pydantic import BaseModel class FieldInfo(BaseModel): value: Optional[str] = "" confidence: Optional[float] = -1.0 class UserInfo(BaseModel): first_name: Optional[FieldInfo] last_name: Optional[FieldInfo] user_info = {"user":{"first_name":["john",0.98], "last_name":["doe",0.98]}} user = UserInfo(**{k:{"value":v[0],"confidence":v[1]} for k,v in user_info["user"].items()}) print(user) gives me first_name=FieldInfo(value='john', confidence=0.98) last_name=FieldInfo(value='doe', confidence=0.98) but if last_name is None i.e. user_info = {"user":{"first_name":["john",0.98]}} user = UserInfo(**{k:{"value":v[0],...

using create_date Automatic fields in odoo

I am follow odoo document and in chapter 9 I want to use Automatic field ( create_date) to compute value of another field this is my model. _name = "estate.offer" _description = "this is work as a offer offered to our real estate model" _log_access = True price = fields.Float() status = fields.Selection(selection=[('accepted', 'Accepted'), ('refused', 'Refused')], copy=False) partner_id = fields.Many2one("res.partner", string="Partner", required=True) property_id = fields.Many2one("estate.model", 'offer_id', required=True) validity = fields.Integer(compute="_inverse_date_deadline", inverse="_compute_date_deadline") date_deadline = fields.Date(string="Date Deadline", compute="_compute_date_deadline", inverse="_inverse_date_deadline") api.depends('create_date', 'validity') def _compute_date_deadline(self...

python match : confusion about match testing

I know there are other ways to do this, but I am want to use match here. In this snip, the break piece matches for all integers > 0, but I want it to match only n ' I'm using the cast because it wasn't working without it. Not working with it either but... #times is a simple list of python datetimes n=len(times) for i,time in enumerate(times) : print(f'{i} {time}') match int(i): case 0 : print('continuing') continue case int(n) : print(f'breaking for {i}') #break case __ : period = times[i+1] - time print(period) source https://stackoverflow.com/questions/74182057/python-match-confusion-about-match-testing

Webpack "Cannot find module 'fs' "

I've been banging my head over my table trying to figure out whats wrong here, and I need some help pls :') I'm trying to convert a CSV file to JSON, and all of the packages seem to use something called "fs". I've searched the web and tried all of the following fixes, but nothing seems to work. I'm using webpack 5.74 btw. Node cannot find module "fs" when using webpack https://github.com/webpack-contrib/css-loader/issues/447 https://jasonwatmore.com/post/2021/07/30/next-js-webpack-fix-for-modulenotfounderror-module-not-found-error-cant-resolve No matter what I try, I always get the "Cannot find module 'fs'" error. Does anyone have an idea of what this could be, since I've tried all of the possible solutions in the links above? Any help would be much appreciated! Thank you! ------ UPDATE-------- const csvtojson = require("csvtojson"); const fs = require('fs'); const handleParse = () => { if ...

How can I best compare the frequency of categorical values from two datasets with Pandas?

I am trying to compare two sets of data, each with a long list of categorical variables using Pandas and Matplotlib. I want to get and somehow store the frequency of values for each variable using the value_counts() method for each data set so that I can later compare the two for statistically significant differences in those frequencies. As of now I just have a function to display the values and counts for each column in a data frame as pie charts, given a list of columns (cat_columns) which is defined outside of the function: def getCat(data): for column in cat_columns: plt.figure() df[column].value_counts().plot(kind='pie', autopct='%1.1f%%') plt.title(f"Distribution of {column} Patients in {dataname}") plt.ylabel('') getCat(df) Is it possible to append/store the returned values of value_counts() into a new DataFrame object corresponding to the each original data set so I can access and operat...

Build an array of dates with cumulative sum

I am building a dashboard to compare the cumulative spending of the current month against the cumulative spending of the last month. This looks like this: As you can see below, my code is very naive and I am pretty sure it can be improved. Right now I loop many times over the arrays to fill each date of currentMonthSpend with the appropriate sum of transactions that happened on this date, cumulated with the previous values ... Would you be able to guide me with a smarter way of doing it? The current logic is the following: Create the array date objects (with x = date and y = cumulative sum) I already have my list of transactions (with date and amount for each entry which can obviously happen at the same date of another entry) First, I iterate through currentMonthTransactions , I find the corresponding date in currentMonthSpend and I increment the y property Then I iterate through currentMonthSpend and I apply a cumulative sum Thanks for your help! const startOfCurrent...

First graph is erased when using clear() but second graph is still usable. Graphs plotted using Matplotlib and Tkinter for GUI

So here is my code. from tkinter import * from numpy import pi from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg as FC import matplotlib.pyplot as plt global r global t r = 90 t = 90 main_window = Tk() main_window.title("GUI test") plt.rc('grid', color='#316931', linewidth=1, linestyle='-') plt.rc('xtick', labelsize=15) plt.rc('ytick', labelsize=15) # initializig figure 1 fig1 = plt.figure(figsize=(2, 1),facecolor='#4a5859') fig1.tight_layout() ax1 = fig1.add_axes([0.1, 0.1, 0.7, 0.7], polar=True) ax1.set_thetamin(0) ax1.set_thetamax(180) ax1.set_rticks([]) arr1 = plt.arrow(r/180.*pi, 0, 0, 1, width = 0.015, edgecolor = 'black', lw = 2, zorder = 5) canvas1 = FC(fig1, master = main_window) canvas1.get_tk_widget().grid(row = 0, column = 1) # initializing figure 2 fig2 = plt.figure(figsize=(2, 1),facecolor='#4a5859') fig2.tight_layout() ax2 = fig2.add_axes([0.1, 0.1, 0.7, 0.7], polar=True) ax2.se...

How to login in PRAW?

Im trying to learn PRAW . Doing everything according to official documentations but start getting login error (output below) What do I wrong? How can I fix that? All creds are correct. import json import praw import requests subr = 'test' credentials = 'client_secrets.json' with open(credentials) as f: creds = json.load(f) reddit = praw.Reddit(client_id=creds['client_id'], client_secret=creds['client_secret'], user_agent=creds['user_agent'], redirect_uri=creds['redirect_uri'], pasword=creds['password'], username=creds['username']) title = "PRAW documentation" url = "https://praw.readthedocs.io" reddit.subreddit("test").submit(title, url=url) Output: RedditAPIException: USER_REQUIRED: 'Please log in to do that.' source https://stackoverflow.com/questions/74174099/h...

use a function at the result of pandas .loc

Hy peeps, I wold like to know if have some possibility to use a function at the result of pandas .loc or if exist some better way to do it. So what I'm trying to do is: If the value in this series is =!0, then get the values of other rows and use as parameters for one function (in this case, get_working_days_delta), after this put the result in the same series. df.loc[(df["SERIES"] != 0), 'SERIES'] = df.apply(cal.get_working_days_delta(df["DATE_1"],df["DATE_2"])) The output is: datetime64[ns] is of unsupported type (<class 'pandas.core.series.Series'>) In this case, the parameters used (df["DATE_1"] df["DATE_2"]) are recognized as the entire series rather than cell values I don't wanna use .apply or .at because this df has over 4 milion rows source https://stackoverflow.com/questions/74166376/use-a-function-at-the-result-of-pandas-loc

Node crypto error when decrypting file - 'Unsupported state or unable to authenticate data'

Iam using node crypto to encrypt files but it gives me error - "Unsupported state or unable to authenticate data" Iam using AuthTag or else it just decrypts to random text. I have not used encoding cause i wanted to encrypt all types of files txt,png,md,etc const app = { encrypt(data, password) { const salt = crypto.randomBytes(16); const key = crypto.scryptSync(password, salt, 32, { N: 16384 }); const cipher = crypto.createCipheriv('aes-256-gcm', key, salt) const encryptedData = Buffer.concat([cipher.update(data), cipher.final()]); const authTag = cipher.getAuthTag(); return salt+authTag+encryptedData; }, decrypt(data, password) { const salt = data.slice(0,16); const authTag = data.slice(16,32); const encData = data.slice(32,data.length); const key = crypto.scryptSync(password, salt, 32, { N: 16384 }); const decipher = crypto.createDecipheriv('aes-256-gcm', ...

How do I make an interval happen whenever I put a cursor on a button, and when your mouse gets out of the button, it clears the interval in JS / HTML?

Here is my code: <!DOCTYPE html> <html> <head> <script type="text/javascript"> function mouseOn() { function int() { document.getElementById("hover").click(); } var interval = setInterval(int, 0); } function mouseOff() { clearInterval(interval); } </script> </head> <body> <button id="hover" onmouseenter="mouseOn();" onmouseleave="mouseOff();"> Hover and Autoclick </button> </body> </html> It doesn't autoclick when my mouse hovers on it. Do you guys know how to fix this? Via Active questions tagged javascript - Stack Overflow https://ift.tt/KFMx9E7

The term 'ts-node' is not recognized

I am following a tutorial and the guy uses ts-node, so I did the same and installed it through yarn but it showed this error ts-node : The term 'ts-node' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + ts-node .\deploy.ts + ~~~~~~~ + CategoryInfo : ObjectNotFound: (ts-node:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException so I searched a bit and tried to add it globally but it still shows the same error, can you guys help me find out what the issue is, as I want to learn the basics of TypeScript for a quiz tomorrow. Via Active questions tagged javascript - Stack Overflow https://ift.tt/KFMx9E7

"You need to enable JavaScript to run this app" on browser at Axios Call Despite 200 response

I have seen this similar issue everywhere else however my specific issue is that my create react app but it only ever happens on my Fetch/Axios call (which btw is returning a 200 just fine). If I don't do an axios call my app runs perfectly fine. Everywhere else I've looked also has it on the API call but my API call is still returning a 200. Did everything under this link right here => https://www.upbeatcode.com/react/solved-you-need-to-enable-javascript-to-run-this-app/ And also made sure to add cors to my backend express.js server (which runs on a different port to my react app) Would love to get some insight as to why this is happening and how I can resolve it! And would be willing to provide stuff like pseudocode and my package.json files and such when needed. react js package.json { "name": "vorboss-airtable", "version": "0.1.0", "private": true, "proxy": "http://localhost:3001", ...

JQuery submit form on keyup

I have a problem with JQuery. I have 2 forms with the same ids. I want when you type a key in the text area with id=ingevuldNotitie then javascript will submit the form. Is there a way to do this and so how? <div id="response"> <div id="child_response"> <form action="test.php" method="post" id="notitieForm" onsubmit="return notitieOpslaan();"> <input type="text" id="clientNotitieDatum" value="2022-10-17" name="clientNotitieDatum" hidden=""> <textarea rows="4" cols="50" id="ingevuldNotitie" name="ingevuldNotitie"></textarea> <input type="submit" name="clientNotitie" value="Notitie opslaan"> </form> <form action="test.php" method="post" id="notitieForm" onsu...

Javascript Maximum call stack size exceeded when I try to push more than 1 number into an array of factorials numbers [closed]

trying to solve this problem that asks to return an array of factorials numbers. now I came up with this code that is working Only if I use 1 number in the array, when I try to insert an array of 2+ numbers it says: Maximum call stack size exceeded. this is my code: function getFactorials(nums) { const bucket = []; if (nums === 0 || nums === 1) { return 1; } else { bucket.push(nums * getFactorials(nums - 1)); } return bucket; } console.log(getFactorials([5])); console.log(getFactorials([5, 10])); // maximum call stack size exceeded basically, I want this function that takes an array of positive integers and returns an array of factorials of these numbers. E.g. [5, 10, 2] => [120, 3628800, 2]. If for example, I pass only [5] the return is correct =>[120] but if I pass [5, 10, 2] => maximum call stack size exceeded. How can I solve that? Via Active questions tagged javascript - Stack Overflow https://ift.tt/KFMx9E7

python requests for load more data

i want to scrap product images from https://society6.com/art/i-already-want-to-take-a-nap-tomorrow-pink of each product > step=1 first i go in div', class_='card_card__l44w (which is having each product link) step=2 then parse the href of each product > but its getting back only first 15 product link inspite of all 44 ============================== second thing is when i parse each product link and then grab json from there ['product']['response']['product']['data']['attributes']['media_map'] after media_map key there are many other keys like b , c , d , e , f , g (all having src: in it with the image link i only want to parse .jpg image from every key) below is my code import requests import json from bs4 import BeautifulSoup import pandas as pd baseurl = 'https://society6.com/' headers = { "User-Agent": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko...

How can I make an interactive histogram using plotly

I want to make a histogram in which we could set width for bins and has an overflow bin for value greater than certain number. source https://stackoverflow.com/questions/74158783/how-can-i-make-an-interactive-histogram-using-plotly

I can't save to localstorage first input with save button. Trying to save multiple inputs to localStorage

I am new at this and I'm trying to save multiple inputs to localStorage with one save button. Its saved second one but not the first one and I can't quite get it to work. Can you please tell me what is the reason? Why doesn't it save the first one? My inputs and save button: <body onload="init()"> <input type="text" id="myTxt1" placeholder="Type here ..." ></br></br></br> <input type="text" id="myTxt2" placeholder="Type here ..."></br></br> <button onclick="onSavePressed()">Save</button> </body> My script: function init(){ if (localStorage.first1Box){ document.getElementById("myTxt1").value = localStorage.first1Box; } } function onSavePressed(){ localStorage.first1Box = document.getElementById("myTxt1").value; alert("Saved Successfully!!!"); ...

Copy and Rename files in destination folder?

I was trying to copy my files to a new destination using fs and then rename them to like 1.png , 1.txt and so on but i always get an error here is my code : const fs = require('fs'); const path = require('path') const dir = 'files/newFiles' const fileNames = fs.readdirSync('files') for(let i = 0 ; i < fileNames.length ; i++) { if (!fs.existsSync(dir)){ fs.mkdirSync(dir); if(!fs.existsSync(dir+'/image')) fs.mkdirSync(dir+'/image'); if(!fs.existsSync(dir+'/txt')) fs.mkdirSync(dir+'/txt'); } const ext = path.extname(fileNames[i]) if(ext === '.png') return fs.copyFileSync(fileNames[i], dir+'/image/'+i+ext) if(ext === '.txt') return fs.copyFileSync(fileNames[i], dir+'/txt/'+i+ext) } here is the error message : Error: ENOENT: no such file or directory, copyfile 'file1.png' -> 'files/newFiles/image/' Via Active questions tagg...

why is document.getElementById() not working in VS Code?

why is document.getElementById() not working in VS Code?? I keep getting this error: "Uncaught ReferenceError ReferenceError: document is not defined". I'm new to VS Code but I'm assuming the reason It's not working is that I need to install some extension to make it work. The same code is working on Replit but not VS code. I installed JS(ES6) Snippets, Open-in browser, Live Preview and Live Server. It's very simple 2-line code just to experiment but it's not working. It's driving me crazy! let head = document.getElementById('change') head.innerText = 'hello' Via Active questions tagged javascript - Stack Overflow https://ift.tt/WKON2ns

What is making this Python code so slow? How can I modify it to run faster?

I am writing a program in Python for a data analytics project involving advertisement performance data matched to advertisement characteristics aimed at identifying high performing groups of ads that share n similar characteristics. The dataset I am using has individual ads as rows, and characteristic, summary, and performance data as columns. Below is my current code - the actual dataset I am using has 51 columns, 4 are excluded, so it is running with 47 C 4, or 178365 iterations in the outer loop. Currently, this code takes ~2 hours to execute. I know that nested for loops can be the source of such a problem, but I do not know why it is taking so long to run, and am not sure how I can modify the inner/outer for loops to improve performance. Any feedback on either of these topics would be greatly appreciated. import itertools import pandas as pd import numpy as np # Identify Clusters of Rows (Ads) that have a KPI value above a certain threshold def set_groups(df, n): "...