Skip to main content

Posts

Showing posts from February, 2023

How can I iterate through a doc2vec model?

I have built a Doc2Vec model and am trying to get the vectors of all my testing set (176 points). The code below I can only see one vector at a time. I want to be able to do "clean_corpus[404:]" to get the entire data set but when I try that it still outputs one vector. model.save(r'F:\LLNL\d2v.model') print("Model Saved") from gensim.models.doc2vec import Doc2Vec model= Doc2Vec.load(r'F:\LLNL\d2v.model') #to find the vector of a document which is not in training data test_data = clean_corpus[404] v1 = model.infer_vector(test_data) print("V1_infer", v1) Is there a way to easily iterate over the model to get and save all 176 vectors? source https://stackoverflow.com/questions/75596881/how-can-i-iterate-through-a-doc2vec-model

Django: Model attribute looks for field works in view, but not in template

Say I have a model: from django.db import models class Foo(models.Model) fav_color = models.CharField(max_length=250, help_text="What's your fav color?") print(Foo.fav_color.field.help_text) # prints: What's your fav color? Say I have a view with context: { 'Foo': Foo } And in a template , the result will be blank. However will print the string representation of the model, so I know the models is getting passed into the template. Why are the attributes look ups to get the help_text failing in the template, why is the help_text empty in the template? source https://stackoverflow.com/questions/75592945/django-model-attribute-looks-for-field-works-in-view-but-not-in-template

react-fuse - how to perform specific search with fuse

I am having trouble performing an aggressive search with fuse, where my search result will only return the one item with matching title, or role from either Buffed or Nerfed genre. I have a json file where I am pulling data from using Firebase. This is my json file: //Buffed firebase.firestore().collection('Buffed').add({ id: getUUID(), title: 'Cyclops', description: 'A mysterious celestial traveler' role: 'Mage', genre: 'Buffed', }); firebase.firestore().collection('Buffed').add({ id: getUUID(), title: 'Esmeralda', description: 'Family Member of Agelta' role: 'Mage', genre: 'Buffed', }); firebase.firestore().collection('Buffed').add({ id: getUUID(), title: 'Paquito', description: 'Nobody' role: 'Fighter', genre: 'Buffed', ...

can't insert a row into my table with pymysql

when i try to run this code i get error ((1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''music' ('Number', 'Song', 'Band', 'Link', 'Sad depressing', 'Dreamy', 'Anxious ' at line 1")) and i don't know why. everything seems right to me import pymysql def mysqladd(Number, Song, Band, Link, Sad_depressing, Dreamy, Anxious_tense, Scary_fearful, Annoying, Indignant_defiant, Energizing_pump_up, Amusing, Joyful_cheerful, Erotic_Desirous, Calm_relaxing, Beatyful): connection = pymysql.connect(host='localhost', user='cd63913_neurohac', password='1234', database='cd63913_neurohac') cur = connection.cursor() #cur.execute("select @@version") mySql_insert_query = "INSERT INTO 'music' ('Number', 'Song', 'Band', 'Link', ...

When is it necessary to define __getattr__() and __setattr()__ methods for a class?

The official Python Programming FAQ advises the programmer to define the methods object.__getattr__(self, name) and object.__setattr__(self, name, value) under certain circumstances when implementing the OOP concept of delegation . However, I can't find good general advice on when defining these two methods is necessary, customary, or useful . The Python Programming FAQ's example is the following code class UpperOut: def __init__(self, outfile): self._outfile = outfile def write(self, s): self._outfile.write(s.upper()) def __getattr__(self, name): return getattr(self._outfile, name) "to implement[] a class that behaves like a file but converts all written data to uppercase". The accompanying text also contains a vague note telling the programmer to define __setattr__ in a careful way whenever attributes need to be set/modified (as opposed to just being read). One question about this code is why their example doesn't ...

rails 7 and bootstrap 5.2.3 with importmaps javascript won't work

I'm not sure what I am doing wrong, I checked also most other similar questions on Stack Overflow, but nothing seem to work for me. I'm trying to get bootstrap 5.2.3 javascript to work to get a dropdown menu. I'm trying to do this with using importmaps, which looks like the easiest way (I tried also with esbuild with no success). here's my import maps (bootstrap comes from jsdelivr as I understand the version on yarn has troubles with popper): pin 'application', preload: true pin '@hotwired/turbo-rails', to: 'turbo.min.js', preload: true pin '@hotwired/stimulus', to: 'stimulus.min.js', preload: true pin '@hotwired/stimulus-loading', to: 'stimulus-loading.js', preload: true pin_all_from 'app/javascript/controllers', under: 'controllers' pin "bootstrap", to: "https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.esm.js" pin "@popperjs/core", to: "https://...

Saving class instances to a file and reading from it (OOP) [duplicate]

So i am fairly new to OOP in Python, and as an excercise, I wrote a simple "Bank" program, and it works. The obstacle is when I create an instance to the Account class, i want to save it in some text file, and be able to read existing instances from it. For example : *I create 10 accounts, and when I kill the program, I want for them to save the instance data to a file, and when I open it again, I want to be able to import it and use it as previously * Here is the code I wrote : class Account: def __init__(self,name,password,amount): self.name = name self.password = password self.amount = amount def display(self): print(self.name, self.amount) def withdraw(self, new_amount): if new_amount < self.amount and new_amount > 0: self.amount -=new_amount else: raise ValueError('Amount must be greater than 0 and less than current amount') def deposit(self,new_amount): if new_...

Should I worry about conflicts with possible future ECMAScript changes if I want to add a generically named property to a Function object?

I am trying to create a function which can be invoked through the following ways: log() log.error() Based on my understanding, we can creating such a function by writing on the function itself: function log(){ } log.error = () => {} Is it not recommended writing on the function this way? Because JavaScript might release an update in the future which might hold the "error" property, then my "error" property will be overriding that JavaScript feature. Here's an example of where people might be using this pattern and why it's useful. For example, Jquery: $( "#button-container button" ).on( "click", function( event ) {} ) and $.ajax({ url: "/api/getWeather" }); you see this pattern in many popular libraries. the $ is an object, it's callable, so you can invoke it $('css query selector here') and it's chainable, so you can call other methods on it $().on() , and it has methods on it $.ajax() Via ...

How do I turn an unformatted text file list into a python list in another file?

I've created a text file that just has an unformatted list of emails, all on a new line. Ex: This is the unformatted list called emailListTest.txt a@a.org b@b.org c@c.org d@d.org e@e.org f@f.org g@g.org h@h.org I have another app that opens and reads the unformatted email list file. Then it creates a new python file and tries to put the unformatted list of emails all in a python list. This all started because I wanted to learn how to send emails with code. I've made another app that does this, but I wanted one that sends emails to multiple people at the same time. This is my writer app emailListFile = open("emailListTest.txt", "r") emailListFileList = open("emailListTestList.py","w") print(emailListFileList.write("emailAsList = ")) print(emailListFileList.write("[")) def emailAddressList(): #try: for i in emailListFile: print(emailListFileList.write( "\n'" + i + "'" ...

How to search and delete specific lines from a parquet file in pyspark? (data purge)

I'm starting a project to adjust the data lake for the specific purge of data, to comply with data privacy legislation. Basically the owner of the data opens a call requesting the deletion of records for a specific user, and I need to sweep all AWS S3 bucktes by checking all parquet files and delete this specific record from all parquet files in my data lake. Has anyone developed a similar project in python or pyspark? Can you suggest what would be the good market practice for this case? Today what I'm doing is reading all the parquet files, throwing it to a dataframe , filtering that dataframe excluding the current record, and rewriting the partition where that record was. This solution even works, but to purge where I need to look at a 5-year history, the processing is very heavy. Can anyone suggest me a more practical solution? remembering that my parquet files are in AWS S3, there are Athena tables, and my script will run in EMR (Pyspark) Thanks source https://sta...

Trying to add a background image to breakout game

I am trying to add a background image and my teacher was trying to explain what to do but it still wouldn't work. <!DOCTYPE html> <html> <head> <style> background-image: url("https://imgur.com/sJTAxQG"); </style> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>group project</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <audio id="myAudio"> <source src="8d82b5_Star_Wars_Main_Theme_Song.mp3" type="audio/mpeg"> </audio> <canvas id="myCanvas" width="480" height="320"></canvas> <script> var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); var background = new Image(); background...

Disable dates + weekday numbers with flatpickr

I would like to be able to deactivate days + weekday numbers 1 to 7. calendar.flatpickr({ disable: dateUnvailableCalendar, minDate: "today", onChange: function (selectedDates, dateStr) { calendarHandleChange(dateStr); } }); This is what I have already done. this disable days i send in an array. now i wish i could disable day number 5 and 7 of every week of the whole year. Do you know how I can do this please? Thank you for help. Via Active questions tagged javascript - Stack Overflow https://ift.tt/pnYMaFs

Sorting Visualizer - Why won't my highlights update when one of my swapped out bars is the next in line to get swapped in?

I'm creating a sorting visualizer, and it's implemented by using synchronous sorting algorithms that push animations to a queue to be handled in the async function animateArrayUpdate . The purpose of the highlights is to indicate the bar which is next up to get sorted. In the case of selection sort, this would be the bar at minIndex which will be swapped with the bar at the current index or i on the next iteration of the loop. The sorting/swapping works perfectly, and the highlighting mostly works, except when the following scenario occurs: The bar at i gets swapped out for a bar at minIndex and then is next up to get swapped in for the next i . In these cases, the bar that got swapped in the last iteration retains its highlight for that iteration so the newly swapped-in bar never gets highlighted. I'll show a trivial example with a mostly sorted array, but the extent to which the rest of the array is sorted is irrelevant, and this wonky highlighting behavior will happe...

Passport Local.js with email instead of username

I am using passport-local to authenticate users. However, I am using email and password to login instead of the default username. How do I change my configuration to change username to email in passport.authenticate? Here is my LocalStrategy code: const strategy = new LocalStrategy(userSchema.authenticate() ) passport.use(strategy); Here is my signup code: app.post('/signup', async function (req, res) { const email = req.body.email; const password = req.body.password; const passwordretype = req.body.passwordretype const name = req.body.name if (password.length < 5) { return res.render('signup', { error: "Your Password must be at least 5 characters in length" }) } if (password !== passwordretype) { return res.render('signup', { error: "Your Passwords must match" }) } if (password.length > 40) { return res.render('signup', { error: "Your Password must be under 40 characters in length...

pyo3 Troubles with `inspect.signature` method

I have a rust struct with which I had implemented python's magic methods __iter__ , __next__ , and __call__ . #[pyclass(name = "PyNRICContainer")] #[derive(Debug)] #[pyo3(text_signature = "(cls, value, values)")] pub struct PyNRICContainer { #[pyo3(get, set)] boolean: bool, } Here are the implementations: #[pymethods] impl PyNRICContainer { #[new] #[pyo3(signature = "(cls, value, values)")] fn new() -> PyResult<PyNRICContainer> { Ok(PyNRICContainer { boolean: true }) } fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> { slf } fn __next__(mut slf: PyRefMut<'_, Self>) -> IterNextOutput<PyRefMut<'_, Self>, &'static str> { if slf.boolean { slf.boolean = false; IterNextOutput::Yield(slf) } else { IterNextOutput::Return("No Longer Iterable.") } } #[cla...

VSCode attach do Python process ran with `-m pdb`

I'm running my Python program with -m pdb to stop it execution at the start. In VSCode, I attach to that process using the following launch.json: { "name": "Python: Attach using Process Id", "type": "python", "request": "attach", "processId": "${command:pickProcess}", "logToFile": true, } but after attaching, I can't resume execution of the code, can't really do anything. I've read that VSCode uses pydevd . Does that mean there is no way to use pdb in such case? source https://stackoverflow.com/questions/75574385/vscode-attach-do-python-process-ran-with-m-pdb

How to solve async setState poblem?

I've code below. console.log from useEffect shows current "files" value, but console.log from handleInputChange function always show previous value. I understand this is because of async setState behavour, but I don't understand how to make it work. import React, { useState, useEffect } from 'react'; import Button from '../Button/Button'; function Card({ accept }) { let [uploadDisabled, setUploadDisabled] = useState(true); let [multiple, setMultiple] = useState(true); let [files, setFiles] = useState([]); function handleOpenClick() { const inputEl = document.getElementById('file'); inputEl.click(); } useEffect(() => { console.log(files); }); function handleInputChange(event) { event.preventDefault(); if (!event.target.files) return; setUploadDisabled(false); setFiles(Array.from(event.target.files))...

Run-Time Error for Chanukah Problem on Kattis

I solved the Chanukah problem from kattis in my IDE and it works perfectly, but when I'm submitting it on kattis, I get a runtime error. This is the code I'm trying to submit, which works perfectly fine in my local IDE and also on replit. def chanukah(): sets = int(input()) dict = {} for k in range(sets): days = int(input()) total = (days * (days + 1) // 2) + days dict[k + 1] = total for key, value in dict.items(): print(key, value) chanukah() I encountered a similar issue on a previous problem, and what I did to fix it was adding extra variables assigning the inputs as int after getting the input from the user, instead of converting the input into int right in the input line, like you can see below, but this time it doesn't make the trick and kattis doesn't like my solution. def chanukah(): sets = input() dict = {} sts = int(sets) for k in range(sts): days = input() dys = int(d...

filter polars DataFrame based on when rows whose specific columns contain pairs from a list of pairs

In this example, on columns ["foo", "ham"] , I want rows 1 and 4 to be removed since they match a pair in the list df = pl.DataFrame( { "foo": [1, 1, 2, 2, 3, 3, 4], "bar": [6, 7, 8, 9, 10, 11, 12], "ham": ["a", "b", "c", "d", "e", "f", "b"] } ) pairs = [(1,"b"),(3,"e"),(4,"g")] The following worked for me but I think this will be problematic when the dataframe and list of pairs are large. for a, b in pairs: df = df.filter(~(pl.col('foo') == a) | ~(pl.col('ham') == b)) I think this is the pandas implementation for this problem Pandas: How to remove rows from a dataframe based on a list of tuples representing values in TWO columns? I am not sure what the Polars implementation of it is. (I think this problem can be generalized to any number of selected columns and any number of eleme...

Error on Seaborn lmplot when passing dataframe data due to dtype('O') error, except I've replaced all object dtypes [duplicate]

Background I have a dataframe imported from an excel doc. Each column is an experiment variable and every row is an entry. The dataframe is 242x18. I am attempting to plot 1x3 lmplot, plotting two Float64 dtypes against one another. Data shown below for context: Data in question dtypes of data Here are the dtypes of the full dataframe: dtypes of full dataframe Note that it was read in as: dtypes of full dataframe prior to conversion Where I then used: df = df_forging.convert_dtypes() The Error The function I'm using is exactly: g = sns.lmplot(data = df,y='Peak Tensile Force (N)',x='Elliptical Area (mm^2)') Which returns the following: --------------------------------------------------------------------------- UFuncTypeError Traceback (most recent call last) >! \~\\AppData\\Local\\Temp\\ipykernel_27312\\4132946937.py in \<module\> 1 # Isolate to one weld population 2 g = sns.lmplot(data=df_forging, 3 y...

onscroll not being fired on CodePen

I made a website with(I think) a pretty cool and simple navigation menu a while back, so I decided to try and put it on CodePen. The onscroll event listener just seems to not be called? The codepen URL is here It works on locally or when hosted on my hosting service window.onscroll = function() { console.log("test") /*code*/ } If you have any idea, please tell me. Thanks in advance. I tried adding eventlistener, doesn't work, tried adding onscroll directly in the html, doesn't work as well. Via Active questions tagged javascript - Stack Overflow https://ift.tt/bGF9N6T

Vite.js error: `Could not resolve "rc-util/es/hooks/useMobile"`

I have created a react.js app using vite.js. When I try to run the app in development mode it returns the following error: X [ERROR] Could not resolve "rc-util/es/hooks/useMobile" node_modules/rc-input-number/es/StepHandler.js:6:22: 6 │ import useMobile from "rc-util/es/hooks/useMobile"; ╵ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You can mark the path "rc-util/es/hooks/useMobile" as external to exclude it from the bundle, which will remove this error. E:\Web Development\Projects\talk-motion-react\node_modules\esbuild\lib\main.js:1566 let error = new Error(`${text}${summary}`); ^ Error: Build failed with 1 error: node_modules/rc-input-number/es/StepHandler.js:6:22: ERROR: Could not resolve "rc-util/es/hooks/useMobile" at failureErrorWithLog (E:\Web Development\Projects\talk-motion-react\node_modules\esbuild\lib\main.js:1566:15) at E:\Web Development\Projects\talk-motion-react\node_module...

How can I scroll inside a popup using Selenium webdriver?

I need to scroll a popup. I know only driver.execute_script("window.scrollTo(0, 2080)") - doesn't work. i've tryed driver.execute_script("window.scrollTo(0, 2080)") , but this command scrolls all window, not a popup. source https://stackoverflow.com/questions/75557224/how-can-i-scroll-inside-a-popup-using-selenium-webdriver

WooCommerce AJAX add to cart don't work for variable products

var data = { action: 'woocommerce_ajax_add_to_cart', product_id: "23716", product_sku: 'MUV–SMO6-50ML-EM', variation_id: "23718", variation: { 'attribute_pa_volume': '50ml', }, quantity: '1', }; $.ajax({ type: 'post', url: '/?wc-ajax=add_to_cart', data: data, beforeSend: function (response) { console.log('1') $(".btn-primary").removeClass('added').addClass('loading'); }, complete: function (response) { $(".btn-primary").addClass('added').removeClass('loading'); }, success: function (response) { $(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash]); }, }); Hello, here's the code I'm using to add a product to the cart with woocommerce_ajax_add_to_cart, this works perfectly for a product without variati...

Using the NetSuite 'N/ui/dialog' Module in Client Functions that Return a Boolean

So, the 'N/ui/dialog' module in SuiteScript 2.x gives nicer looking versions of the native JavaScript alert() and confirm() functions that match the UI theme. However, when using them in the client functions like validateField() and onSave() they don't pause the script execution, so if you need to return a false to do something like preventing the record from saving, it doesn't work. In fact, I believe that if you try to return false from the dialog's promise object, the function won't even see it anyway. Now, I've seen some ways to make it work in onSave() , but those methods don't appear to work in a scripted form due to some NS-provided values not existing in a scripted form. Also, none of these methods account for trying to use a dialog in something like the validateField() function. When using dialog.alert() , this isn't really an issue as a false can be returned after creating the alert regardless of the alert's promise. For example: ...

libtorch Conv1D doesn't operate over signal length dimension

I have a torch model, that simply contains a conv1d (intended to be used to implement a STFT fourier transform). The model works fine in torch, and traced using torch.jit.load in Python. When I attempt to use the model on iOS with libtorch via this react native library ( https://www.npmjs.com/package/react-native-pytorch-core ), I do not get the intended output. The first output channel is correct (i.e. in this case it equals the first 2048 samples dot product with the convolution), but the remainder output channels, which should correspond with the kernel sliding along the signal (in time) are the same as the first one!) In Python / torch... import torch class Model(torch.nn.Module): def __init__(self): n_fft = 2048 hop_length = 512 self.conv = torch.nn.Conv1d(in_channels=1, out_channels=n_fft // 2 + 1, kernel_size=n_fft, stride=hop_length, padding=0, dilation=1, groups=1, bias=False) def forward(self, x): retu...

Puppeteer in headless mode not allowing to see saved cookies to site?

I got problem with my script where I am logging in to site. I am using puppeteer-extra-plugin-stealth to prevent headless detection. The code works fine when running with headless: false . But in headless: true is page acting like it does not see the cookies and I am not logged in. When I checked the cookies in both scenarios they are the same so there should be no problem. The cookies are in browser memory. I could find any solution so far. My code: const puppeteer = require('puppeteer-extra') const {executablePath} = require('puppeteer') const StealthPlugin = require('puppeteer-extra-plugin-stealth') puppeteer.use(StealthPlugin()) const browser = await puppeteer.launch({ "headless": true, "ignoreHTTPSErrors": true, "executablePath" = executablePath() }); const page = await browser.newPage(); await page.goto(url, { waitUntil: "networkidle0", }); await page.waitForSelecto...

Standard JavaScript regular expressions to match from tag

I am trying to pull below 3 values from tag of dynatrace with regex and tried : } else { //Regex to find CFU, Environment & Snowappid from tags var add_info_parser = JSON.parse(requestBody); var regex_match = new RegExp(/^(?=.*Environment:\s*(\w+))(?=.*CFU:\s*(\w+))(?=.*SnowAppID:\s*(\w+)).*/igm); var tags = add_info_parser.Tags; gs.info("Dynatarce before regex match" + tags); regex_match = regex_match.exec(tags); gs.info("Dynatrace regex value" + regex_match); appIdTag = regex_match[3].toString(); environmentTag = regex_match[1].toString(); var CFU_value = regex_match[2].toString().toLowerCase(); if (cfuOverride.indexOf(CFU_value) > -1) { overrideBinding = true; } unfortunately not worked. Can a...

correct path not being displayed while reading a file using s3.glob

I am reading multiple csv files from a folder using the following code import pandas as pd import s3fs s3 = s3fs.S3FileSystem(anon=False) bucket='<my_s3_bucket_name>' object = '<my-file-path>/*.csv' path= s3.glob('s3://{}/{}'.format(bucket, object)) path When I display the list of csv files, I get all the csv files in the folder but the path comes without the s3 prefix and when I try to read the csv file, it gives me FileNotFoundError: [Errno 2] No such file or directory: Any help will be really appreciated source https://stackoverflow.com/questions/75538393/correct-path-not-being-displayed-while-reading-a-file-using-s3-glob

Getting Value outside tag with web scraper JavaScript

I'm attempting to create a scraper broken into two classes. One being a backend that will scrap a value from a website & return it to the front end, where for now it'll be printed. My problem is I'm stuck when it comes to getting a value defined outside a tag. I.e. <div class="temp">13</div> Here is my backend so far, it takes a url in the get function in the event I want to add more classes that use it in the future const PORT = 8000 const axios = require('axios') const cheerio = require('cheerio') const express = require('express') const app = express() const cors = require('cors') const url = require("url"); app.use(cors()) app.get('/temp/:url1', (req, res) => { axios(url1) .then(response => { const html = response.data const $ = cheerio.load(html) const value = [] *stuck here* }).catch(err => ...

How to make discord role command case insensitive for inputs

I have this discord bot code that gives users roles: @client.command(aliases=['r'], case_insensitive=True) async def role(ctx, *, role: discord.Role): if role in ctx.author.roles: await ctx.author.remove_roles(role) else: await ctx.author.add_roles(role) However, when a user inputs a role it is not case sensitive. For example, if you wanted the role "Coder" and did the command !role coder, it would not give you the role as it is lowercase when the role is uppercase. I tried experimenting with the capitalize() Method but I have not figured anything out. source https://stackoverflow.com/questions/75539218/how-to-make-discord-role-command-case-insensitive-for-inputs

Why is my function refuse to store or update inputs

I am unable to Create an event listener to save the entry when it changes. I tried everything I could, from swapping var between different lines of code to add .value at end of some of my var to see if he'd work. Sorry, I am not really good on describing the issue or even coding, but normally this function should Create an event listener to save the entry when it changes. When this change is complete, we should see items change in the ‘Application’ or ‘Storage’ tab of your browser developer tools after you type text on the page, and move the focus away from the text input (e.g. by pressing the Tab key on your keyboard or clicking elsewhere on the page). When you reload the page these entries will reappear on the page. /** * Make diary data item * @param type Type of item to create, either "text" or "image" * @param data Item data, either text or data URL * @returns JSON string to store in local storage */ function makeItem(type,...

How to write the following Python code in C++? [closed]

I would like to translate the following Python code to C++. def puzzle(i): ps = set() def sp(i, p=2): if i==1: return '' d = ps.add(p) or 0 while i % p == 0: d,i = d+1,i//p while any(p % q == 0 for q in ps): p+=1 return puzzle(d) + sp(i,p) return f'({sp(si)})' if i else '.' I made a couple of tries but got stuck with recursive lambda/function<> (I tried to implement a nested function with it). So the main problem for me is to implement the sp() inside puzzle(). However, I don't necessary want it to be nested, just so the code works. I am beginner in C++, so I'm sorry if it'd be too trivial. Thanks in advance. source https://stackoverflow.com/questions/75538678/how-to-write-the-following-python-code-in-c

Fetch fails when exceeding a certain execution time even-though using proper CORS headers

I have been stuck with a weird issue with CORS for quite some time now. To explain the setup I have a frontend JS snippet (including fetch API call to my own server) which I want to use as an embed code snippet other web applications can use. (ex: kind of like google analytics) // JS snippet to copy to an unknown website <script> // extract data and add to the body const extracted_data = {} fetch("https://api.xxxx.com/xxxxxx/create", { method: "POST", mode: 'cors', body: JSON.stringify(extracted_data), referrer: "origin", headers: { 'Content-Type': 'application/json', }, }) .then(function (response) { // The API call was successful! if (response.ok) { return response.json(); } else { return Promise.reject(response); } }) .then(function (data) { /...

Better way to identify chunks where data is available in zarr

I have a zarr store of weather data with 1 hr time interval for the year 2022. So 8760 chunks. But there are data only for random days. How do i check which are the hours in 0 to 8760, the data is available? Also the store is defined with "fill_value": "NaN", I am iterating over each hour and checking for all nan as below (using xarray ) to identify if there is data or not. But its a very time consuming process. hours = 8760 for hour in range(hours): if not np.isnan(np.array(xarrds['temperature'][hour])).all(): print(f"data available in hour: {i}") is there a better way to check the data availablity? source https://stackoverflow.com/questions/75521500/better-way-to-identify-chunks-where-data-is-available-in-zarr

RuntimeError: A 'SQLAlchemy' instance has already been registered on this Flask app

I am writing a test for my Flask app that uses Flask-SQLAlchemy. In models.py , I used db = SQLAlchemy() , and wrote a function to configure it with the app. But when I run my test, I get the error "RuntimeError: A 'SQLAlchemy' instance has already been registered on this Flask app". I'm not sure where the test file is creating a new instance of SQLAlchemy. # flaskr.py from flask import Flask from models import setup_db def create_app(test_config=None): app = Flask(__name__) setup_db(app) return app # models.py from flask_sqlalchemy import SQLAlchemy database_path = "postgresql://student:student@localhost/bookshelf" db = SQLAlchemy() def setup_db(app, database_path=database_path): app.config["SQLALCHEMY_DATABASE_URI"] = database_path db.init_app(app) with app.app_context(): db.create_all() # test_flaskr.py import unittest from flaskr import create_app from models import setup_db class BookTestCase(unitt...

Issues with CSS and JavaScript for creating a carousel with multiple images

I am trying to create a carousel with multiple images using HTML, CSS, and JavaScript, but I am having trouble getting it to work properly. The first image displays correctly, but the second image only shows up partially or not at all. I have tried adjusting the CSS, but it doesn't seem to be solving the issue. Here is my current code: document.addEventListener('DOMContentLoaded', () => { const track = document.querySelector('.carousel_track'); const slides = Array.from(track.children); const nextButton = document.querySelector('button.button-carousel.next'); const prevButton = document.querySelector('button.button-carousel.prev'); const trackWidth = track.getBoundingClientRect().width; const slideWidth = trackWidth / slides.length; // const setSlide = (slide, index) => { // slide.style.left = slideWidth * index + 'px'; // }; const setSlide = (slide, index) => { const offset = (t...

Three.js ReactJS integration

import THREE from 'https://threejs.org/build/three.js'; function Thbox(props) { const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 ); const renderer = new THREE.WebGLRenderer(); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement ); const geometry = new THREE.BoxGeometry( 1, 1, 1 ); const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } ); const cube = new THREE.Mesh( geometry, material ); scene.add( cube ); camera.position.z = 5; function animate() { requestAnimationFrame( animate ); cube.rotation.x += 0.01; cube.rotation.y += 0.01; renderer.render( scene, camera ); }; return ; } export default Thbox; I am getting 'cannot read properties of undefined' on: const scene = new THREE.Scene(); What is the issue and How to fix this ?...

How can I assert that the number 12 can be fulfilled? [closed]

x = 22 print (f"Sector {float(x)}: ",sum(([3]+[5,4,3,3,6,2,4,2,6,1]*(x//1))[:x-2])) #sector3 (5) 39 #sector4 (4) 44 #sector5 (3) 48 #sector6 (3) 51 #sector7 (6) 54 #sector8 (2) 60 #sector9 (4) 62 #sector10 (2) 66 #sector11 (6) 68 #sector12 (1) 69 The number 12 does not comply because it gives me the result 74 which should be 69 The #12 that should add 1 does not do so source https://stackoverflow.com/questions/75513739/how-can-i-assert-that-the-number-12-can-be-fulfilled

Function to validate strings and arrays in object JavaScript [closed]

I have an object, as example: { commands: [ 'element1', 'element2', 'element3' ], 'audit-log': { channel: 'string', 'message-events': { enabled: [ 'element1', 'element2', 'element3' ], ignored: [ 'element1', 'element2', 'element3' ] }, 'moderation-events': [ 'element1', 'element2', 'element3' ] }, enabled: [ 'element1', 'element2', 'element3' ] } All the strings and array elements have to be checked if a certain array includes those. This array is different for every object element. So if the function checks enabled in message-events , it takes another array then when it checks the standard enabled or ignored in message-events . Example array for ignored : [ 'element1', 'element3', 'element4' ] . This will return false when checked, because element2 is not in the ignored array. Examp...

Merge/attach/join/put together fibonacci output lines into a single line

def fib(n): a = 0 b = 1 if n == 1: print(a) else: print(a) print(b) for i in range(2,n): c = a + b a = b b = c print(c) fib(int(input())) how do i make it so the output comes in a single line attached one result to another instead of receiving one sum below the other simple append/join commands that didn't work, most likely i don't know how to properly use them in this instance your text source https://stackoverflow.com/questions/75513181/merge-attach-join-put-together-fibonacci-output-lines-into-a-single-line

pythonic way to decorate an iterator at run-time?

I have the following code: def assertfilter(iterator, predicate): # TODO support send() for result in iterator: if not predicate(result): raise AssertionError("predicate failed in assertfilter()") yield result Any attempt I could come up with to refactor it to support send() seems to look horrifically convoluted, unreadable, and non-obvious: def assertfilter(iterator, predicate): result = None while True: try: sent = yield result if sent is not None: result = iterator.send(sent) else: result = next(iterator) if not predicate(result): raise AssertionError("predicate failed in assertfilter()") except StopIteration as e: if e.value is not None: return e.value return Is there a recognized, common, readable way to inject/wrap logic onto an existing iterator? Or is the abov...

CSS3: Have a block display with 2 text lines top-right and buttom-right with a link-text in the middle

CSS: Mix block display with html/css text ansd styles. Extending dropdown menu with update date and site count in block style. Cool menu. Hi guys, I found a cool menue display with CSS, JS and Html that look like this: drop about settings Test 1 Test 2 Test 3 Test 4 help more deeper deep 1 deep 2 deep 3 test no drop var count = 1 setTimeout(demo, 500) setTimeout(demo, 700) setTimeout(demo, 900) setTimeout(reset, 2000) setTimeout(demo, 2500) setTimeout(demo, 2750) setTimeout(demo, 3050) var mousein = false function demo() { if(mousein) return document.getElementById('demo' + count++) .classList.toggle('hover') } function demo2() { if(mousein) return document.getElementById('demo2') .classList.toggle('hover') } function reset() { count = 1 var hovers = document.querySelectorAll('.hover') for(var i = 0; i < hovers.length; i++ ) { hovers[i].classList.remove('hover') } } document.addEv...

github action pytest exit code 134

So I am running pytest via github actions and a test that passes on my machine (both through direct command line and vscode testing) is erroring out and aborting in the container and idk why. ============================= test session starts ============================== platform linux -- Python 3.10.10, pytest-7.2.1, pluggy-1.0.0 -- /opt/hostedtoolcache/Python/3.10.10/x64/bin/python cachedir: .pytest_cache rootdir: /home/runner/work/jbuielCubesProject/jbuielCubesProject collecting ... collected 4 items tests/test_data.py::test_api_data_amount PASSED [ 25%] tests/test_data.py::test_entry_in_database PASSED [ 50%] tests/test_data.py::test_data_in_table PASSED [ 75%] Fatal Python error: Aborted Current thread 0x00007f6d807b6c40 (most recent call first): File "/home/runner/work/jbuielCubesProject/jbuielCubesProject/tests/test_data.py", line 55 in test_gui_info File "/opt/hostedtoolcache/Pytho...