Skip to main content

Posts

Showing posts from April, 2023

Python jira packapge - Atlassian's bug JRA-41559

I get this "Atlassian's but" error after running below code. This same section of code previously worked. Why this is happening? Is this related to JIRA website? Is there a way to overcome? Thanks for helping! 2023-04-23 12:42:42 Atlassian's bug https://jira.atlassian.com/browse/JRA-41559 KeyError: "'issues' : {}" code jira_client = JIRA(options={"server": "https://jira.mycompanyname.com/"}, basic_auth=(email, password)) project_name='XXXX' issues = [] i = 0 chunk_size = 100 while True: chunk = jira_client.search_issues(f'project = {project_name}', startAt=i, maxResults=chunk_size, fields=["id", "fixVersion"]) i += chunk_size issues += chunk.iterable if i >= chunk.total: break Restarted Kernel. Didn't solve. source https://stackoverflow.com/questions/76143434/python-jira-packapge-atlassians-bug-jra-41559

How to create websites automatically and assign a subdomain in a website builder? [closed]

I decided to create a website builder where users can sign up, create their shop, put their products. The issue is I can’t understand how website builders automatically generate the website and assign the subdomain to the website so that the user can access it instantly and, on top of that, they can use their own domain. I just can’t figure out a solution that can automate this stuff. I have no idea how to do this. Via Active questions tagged javascript - Stack Overflow https://ift.tt/JTPrv78

Firebase and Google Chart , timestamp not accurate

This code is to show the temperature on the specific are and record it to the firebase database. This code is supposedly to record current date into the database then temperature and at last , timestamp, but it instead record a different time (ex. My current data and time is May 1 , 3:11am but it instead recorded April 30 , 6pm) which result onto not showing anything into chart since the chart is set to show only the data on the same day ( if it's may 1 , the chart only shows may 1, data's ) <!DOCTYPE html> <html> <head> <title>Temperature Chart</title> <!-- Load Google Charts API --> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['line']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { // G...

How to sort list of classes, as if they were integers in python [duplicate]

Hi so I have a list of class objects list = [x, y, z] but I want to sort them like integers ( they have a integer variable defined in them that I want to sort by(i access it by doing list[x].score)), but i don't know how to could anyone show me how to sort this? (the list has variable length) idealy something like this: list = [x, y, z] # x.score = 2, y.score = 3, z.score = 1 list.sort() # or something # list = [z, x, y] source https://stackoverflow.com/questions/76142965/how-to-sort-list-of-classes-as-if-they-were-integers-in-python

Setting a column in a dataframe to new values

from sklearn import preprocessing def labelencoder(dataframe) : label_encoder = preprocessing.LabelEncoder() dataframe= label_encoder.fit_transform(dataframe) return dataframe new_df['label'] = labelencoder(new_df['label']) I am getting the following warning for the above code: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy new_df['label'] = labelencoder(new_df['label']) The code is working fine, it just shows this warning each time. Is there a solution? I tried something like: new_df.loc[:, 'label'] = labelencoder(new_df['label']) But it didn't work, It still shows the warning source https://stackoverflow.com/questions/76134989/setting-a-column-in-a-dataframe-to-new-values ...

Object as a checkbox value

I have an array of objects and I map through them. {alltasks.map((task) => ( <div key={task.task}> <input type="checkbox" name="task" id={task.task} value={task} className="hidden peer check" /> <label for={task.task} className="inline-flex items-center justify-between w-full p-5 text-white bg-transparent border-2 border-slate-600 rounded-lg cursor-pointer peer-checked:border-emerald-500 hover:border-emerald-700"> <div> <img src={task.img} alt="" /> <div className="w-full text-sm mt-2">ID: {task.task}</div> </div> </label> </div> ))} Each object will now have its own checkbox. I set the checbox's value as the object, so I can use it later. On submit I want to get all checked checbox's values, so I can st...

Javascript is not being implemented

I am trying to build a background animation for the menu items of my website. It mostly works as I want but I'm not able to get the javascript to work. The folders are all in the same directory and the code is as follows: const menu = document.getElementById("menu"); Array.from(document.getElementsByClassName("menu-item")) .forEach((item, index) => { item.onmouseover = () => { menu.dataset.activeIndex = index; } }); body { background-color: rgb(20, 20, 20); margin: 0px; } #menu { height: 100vh; display: flex; align-items: center; } .menu-item { color: aliceblue; font-size: clamp(3rem, 8vw, 8rem); font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; display: block; text-decoration: none; padding: clamp(0.25rem, 0.5vw, 1rem) 0rem; transition: opacity 400ms ease-in; } #menu-items { margin-left: clamp(4rem, 20vw, 48rem); position: relative; z-index: 2; } #menu-items:hover>.menu-item {...

add a new dimension and repeat values for a numpy array

I have a very basic question. I think this can be done elegantly in a single line with numpy, but I don't know how. Let's say I have a 2D numpy array with shape (Nx,Ny) , and I want to add a third dimension with shape Nz . For every fixed index_x,index_y I want to repeat the value of the array for all indices across the new z axis. I can easily do this with basic instructions like # array_1 has shape (Nx,Ny) array_2 = np.zeros((Nx,Ny,Nz)) for idx_x in range(Nx): for idx_y in range(Ny): array_2[idx_x,idx_y,:] = array_1[idx_x,idx_y] but I was wondering what is the exact numpy function to do this in a single line source https://stackoverflow.com/questions/76137156/add-a-new-dimension-and-repeat-values-for-a-numpy-array

Planet not following orbit in Solar System Simulation

I'm trying to simulate a solar system, but the planets don't seem to follow the orbit, instead, the distance between a planet and the sun increases. I can't figure out what's wrong with this code. Here is an MRE. import numpy as np import matplotlib.pyplot as plt GRAVITATIONAL_CONSTANT = 6.674e-11 EARTH_MASS = 5.972 * (10**24) SUN_MASS = 332954.355179 * EARTH_MASS MERCURY_MASS = 0.06 * EARTH_MASS AU2M = 1.495979e11 AUD2MS = AU2M / 86400 class SolarSystemBody: def __init__(self, name, mass, position, velocity): self.name = name self.mass = mass self.position = np.array(position, dtype=float) * AU2M self.velocity = np.array(velocity, dtype=float) * AUD2MS self.acceleration = np.zeros(3, dtype=float) def update_position(self, dt): self.position += self.velocity * dt + 0.5 * self.acceleration * dt**2 def update_velocity(self, dt): self.velocity += self.acceleration * dt def gravitational_force(s...

ENS contract "register" function failing

I wanted to ask a question about my ENS domain register flow that im doing in node.js It goes as follows : I check and verify that the domain is available by calling available I call makeCommitment I pass the output from makeCommitment to the commit Function and send it as a transaction I wait for 90 seconds I call register (passing in the same arguments I passed into make commit ) and send it as a transaction with the value being the rentPrice of the domain The last step is where it fails. Here is the output of makeCommitment when manually passing in the same data my coded uses (check image): The commitment my code generated matches the one in the image commitment : 0x3f39cd6bbf253c6cc72e623a619b69dad1edee34889a7f95e7a67f5e621243de Here is my transaction to the commit call Here is the Failing transaction to register call The code is attached. it uses ethers.js version 5.7.2 This is the Controller contract address I'm using : 0xCc5e7dB10E65EED1BBD105359e726...

Error when starting dev server, Vite with React.js

I closed the project to sleep, and in the other day, I've tried to "npm run dev", and this log came to me: failed to load config from F:\Projetos\Atividades_e_Outros\PokedexReact\PokedexReact\vite.config.js error when starting dev server: Error: The service was stopped at F:\Projetos\Atividades_e_Outros\PokedexReact\PokedexReact\node_modules\esbuild\lib\main.js:1073:25 at responseCallbacks.<computed> (F:\Projetos\Atividades_e_Outros\PokedexReact\PokedexReact\node_modules\esbuild\lib\main.js:697:9) at Socket.afterClose (F:\Projetos\Atividades_e_Outros\PokedexReact\PokedexReact\node_modules\esbuild\lib\main.js:687:28) at Socket.emit (node:events:525:35) at endReadableNT (node:internal/streams/readable:1359:12) at process.processTicksAndRejections (node:internal/process/task_queues:82:21) My vite.config.js: import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' // https://vitejs.dev/config/ export defaul...

Fullcalendar: How to keep just one event per line horizontally?

I have this calendar, with plugin fullcalendar 6.1.5: Calendar I want to show one event per line, horizontally. Example: If event A starts on the 26th and event B starts on the 27th, event B should be on the bottom row, and so on. Here is an example of how it should be: enter image description here One event per line, regardless of its start and end, only one per line, is it possible? Here is what i tried: I tried changing the CSS properties of the events to shift to the bottom, using margin-top: 30px and margin-bottom I tried to use eventDidMount, eventPositioned, eventRender (some were not supported by the version I use. I tried to create "invisible" events to try to scroll down I tried changing the event width to shift all events on the same line down But nothing worked... Here is the code: CDN: <link href="bower_components/fullcalendar/dist/fullcalendar.min.css" rel="stylesheet"> <script src="bower_components/mom...

Jupyter is not starting with my environemnt

So for the first problem in my life I have this problem. I activate my venv through: source venv/bin/activate I then install jupyter with pip install jupyter Now when in a notebook and I do sys.executable I get ./bin/python3 But this is not my environemnt! When I enter python through terminal and do the same I get: /home/user/.../venv/bin/python3' Additionally, I'm missing all my libraries and stuff... source https://stackoverflow.com/questions/76133513/jupyter-is-not-starting-with-my-environemnt

How to keep dropdown visible Vue.js Tailwind

I'm trying to make a dropdown menu with Vue.js and Tailwind css, when I hover over the Genres link the dropdown appears but when I put my mouse off it disappears, how to make it remain visible while mouse is over the dropdown? <template> <nav class="navbar"> <div class="navigation flex justify-between"> <ul class="flex gap-2.5"> <li v-for="item in navLinks" :key="item.name"> <NuxtLink :to="item.link" class="hover:text-blue-500"></NuxtLink> <div v-if="item.name === 'Genres'" class="dropdown absolute w-48 bg-white shadow-lg rounded-lg py-2"> <ul> <li v-for="genre in genres" :key="genre._id"> <NuxtLink :to="genre.name" class="bloc...

Stored Prcedure for Create another Table and column from existing database source

Good afternoon I want to make a stored procedure that generate auditories tables. Flow: If the table exists that add new columns else create the new table same origianl without restrictions also create another control columns such as User, date and mmore, which is detailed in the next sql code: USE Based; DROP PROCEDURE IF EXISTS TEST; DELIMITER // CREATE PROCEDURE TEST( IN DbName VARCHAR(255), IN Tablename VARCHAR(255), IN AuditDb varchar(255) ) BEGIN SET @AuditTableName = CONCAT("Aud_",Tablename); set @TrimAuditTableName =concat("'",@AuditTableName,"'"); set @TrimDbName = concat("'",DbName,"'"); set @TrimTablename =concat("'",Tablename,"'"); set @TrimAuditDb =concat("'",AuditDb,"'"); set @TrimAuditTableName =concat("'",@AuditTableName,"'"); IF NOT EXISTS( SELECT NULL FROM INFORMATION_SCHEMA.COLUMNS ...

How to set filled color in react-chartjs-2 with gradient color

I am trying to fill the background color with the gradient color just like below image. I have tried multiple methods to achieve the gradient but failed in most of them. This is what I have tried till now: import React from "react"; import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, Filler, } from "chart.js"; import { Line } from "react-chartjs-2"; import { colors, hexToRGB } from "@/constant/data"; import useDarkMode from "@/hooks/useDarkMode"; ChartJS.register( CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, Filler ); const LineChart = () => { const [isDark] = useDarkMode(); //using the variable to add gradient color const gradientColor = { type: "linear", x0: 0, y0: 0, x1: 0, y1: 1, colorStops: [ { offset: 0, color: "rgba(126, 234, 184, 1)" }, { off...

(SOLVED) Python subtraction operator not functioning properly

I'm creating a GUI implementation of roulette in python using PyQT6. However, when I was creating a function to stack similar bets, I began encountering an error with the subtraction The first time I place a $10 bet on 36, it subtracts $10 from my wallet, as expected. However, I go to place another $10 bet on 36, and it subtracts no money. The next time, it adds $10. After that, it adds $20, $30, $40 and so on. Upon debugging, the amount fed into the function is correct, but the function to subtract money is not working self.t.players[0].subtract_money( self.BetAmountBox.value() ) # Remove money self.BetAmountBox is just a spinbox (single), where the users enter their bet amount. The subtract_money() function is contained within a separate player class, defined as: def subtract_money(self, amount: int) -> None: self.balance -= amount # Subtract the money This problem only appears when stacking bets, and does not occur when just placing regular bets I tried ...

why is creating multiple databases when I interact with socket.server?

I've created socket server in one .py file I've created socket client into an another .py file I've created a demo database into an another .py file I want that client verify a social number from database thru server and now the party begins.. 1st issue: When I introduce another social number to be verified if exists, the previous one appears and when I introduce another social number, the social number that I've asked for to be verified before appears double times :-) 2nd issue: Now I have the same database twice in two different folders. It's driving me crazy :-) Please give me a hint what I'm doing wrong Here are my sheets: database from sqlalchemy import create_engine, Column, Integer, String, select from sqlalchemy.orm import sessionmaker, declarative_base class Personas(): personas = create_engine('sqlite:///personas.db') Session = sessionmaker(bind=personas) sessionDB = Session() Base = declarative_base() class TablePers...

Unable to get timezone for unix timestamp

I'm trying to get the timezone for Autralia and print a unix timestamp however the timestamp just read UTC opposed to Australia time. Here is what I'm working with: //Get todays date var d = new Date() //convert to timezone d.toLocaleString("en-US", {timeZone: "Australia/Sydney"}); const insevendays = Math.floor(new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0,30,0) / 1000 + 604800) d.toLocaleString("en-US", {timeZone: "Australia/Sydney"}); Is not outputing the correct timezone. Via Active questions tagged javascript - Stack Overflow https://ift.tt/2OenTcw

Regionprops in skimage does not return intensity_mean

Regionprops in skimage does not return intensity_mean and returns an error. A minimal example is here: from skimage import data, util from skimage.measure import label, regionprops img = util.img_as_ubyte(data.coins()) > 110 label_img = label(img, connectivity=img.ndim) regions = regionprops(label_img) for region in regions: print(region.area) So the above example works, but the example below doesn't work: from skimage import data, util from skimage.measure import label, regionprops img = util.img_as_ubyte(data.coins()) > 110 label_img = label(img, connectivity=img.ndim) regions = regionprops(label_img) for region in regions: print(region.intensity_mean) Honestly, I don't know what to try! source https://stackoverflow.com/questions/76118536/regionprops-in-skimage-does-not-return-intensity-mean

React-redux, nextauth, next.js error depreciation error

So I am trying to add React-redux to my next.js app that also uses Next Auth. And seem to be unable to figure out how to get rid of the depreciation error. my _app.tsx : import 'bootstrap/dist/css/bootstrap.min.css' // Import bootstrap CSS import { SessionProvider, useSession } from 'next-auth/react' import NavBar from '../components/NavBar' import dynamic from 'next/dynamic' import React from 'react' import { wrapper } from "../store/store"; import { PersistGate } from "redux-persist/integration/react"; import { useStore } from "react-redux"; // eslint-disable-next-line @next/next/no-document-import-in-page import { Head } from 'next/document' const BackgroundImage = dynamic( () => { return import('../components/BackgroundImage') }, { ssr: false, loading: () => <p>...</p>, } ) function MyApp({ Component, pageProps: { session, pageProps } ...

Why does grouping by one column return a list of strings instead of a list of dictionaries in SQLModel?

Explanation: The provided code uses the SQLModel library in Python to create a SQLite database and store records in it. The Model class represents the schema of the database table and inherits from the SQLModel class. Two functions, select_groupby_one_col() and select_groupby_more_col(), execute SQL queries using the Session class and the select() method of the sqlmodel library. The select_groupby_one_col() function should return a list of dictionaries with two keys, 'userId' and 'compl', but it returns a list of strings with only the 'userId' values. In contrast, the select_groupby_more_col() function returns a list of tuples with three values, 'userId', 'year', and 'compl'. My concern is that, given the implementation of the Model class and the use of the SQLModel library, why does select_groupby_one_col() return a list of strings instead of a list of dictionaries? from sqlmodel import SQLModel, create_engine, Field, Session, select,...

Displaying red square with JS [closed]

I'm trying to display this red square on the screen with JS. Any idea where I'm going wrong? Here is my code : const canvas = document.querySelector('canvas') const c = canvas.getContext('2d') canvas.width = innerWidth canvas.height = innerHeight class Player { constructor() { this.position = { x: 200, y: 200 } this.velocity = { x: 0, y: 0 } // this.image = this.width = 100 this.height = 100 } draw() { c.fillStyle = 'red' c.fillRect(this.position.x, this.position.y, this.position.width, this.position.height) } } const player = new Player() player.draw() No idea where I'm going wrong here. I should be seeing a red square Via Active questions tagged javascript - Stack Overflow https://ift.tt/fDqtxLw

Hyperlinks in Cells using Python Tabulator

I am using Tabulator in Python to generate dynamic Quarto reports. I would like to embed a hyperlink in each cell to navigate to another page when clicked. I wasn't able to find how to do this from the documentation here: https://panel.holoviz.org/reference/widgets/Tabulator.html . source https://stackoverflow.com/questions/76114292/hyperlinks-in-cells-using-python-tabulator

File System Access API on Safari iOS - createSyncAccessHandle() UnknownError: 'invalid platform file handle'

I'm currently refactoring an app to use the OPFS to save images on an iPad for a use-case where a user needs to take pictures in a location that doesn't have wi-fi but storing all of the images in RAM will cause the iPad to crash. I've managed to create a working OPFS Worker that works on my local Windows machine on Chrome and Firefox, but I can't get it working on the test iPad. [EDIT] What it does is sends the base64 text to the worker and saves it as a text file, that I can retrieve later. The iPad I'm using to test is iOS version 16.3.1. The iPad I'm trying to develop for is iOS version 15.7.3. As far as I can tell, Safari iOS has had OPFS compatibility since 15.2. I was able to narrow down the problem to one specific error (via Web Inspector): Unhandled Promise Rejection: UnknownError: invalid platform file handle It references back to the following code (within a Web Worker): const root = await navigator.storage.getDirectory(); const saveHa...

How to assign image url dynamically using $.map in jquery

How to assign image tag attributes data dynamically using $.map loop below is my html and jquery code. html:- <div class="justify-content-center"> <div class="icons"> <i class='chart-icon'> <img src="" alt=""> </i> </div> <span></span> </div> <div class="justify-content-center"> <div class="icons"> <i class='chart-icon'> <img src="" alt=""> </i> </div> <span></span> </div> <div class="justify-content-center"> <div class="icons"> <i class='chart-icon'> <img src="" alt=""> </i> </div> <span></span> </div> jquery code:- ($.map(algoimg, function (item) { $(".justify-content-center").find("img").a...

How can I ignore missing values when plotting using subplot?

I am trying to plot my data using plt.subplots. I have three main variables, as follow: x = DF["Time"] y = DF["recording1"] n = DF ["recording2"] I am trying to plot y over x, while label y (as a text) with n. The problem is that n has some missing values which I do not want them to appear in the figure. So how can I plot the figure while ignoring the nan values? How can I draw multiple lines corresponding with each raw based on the value of recording1 fig, ax = plt.subplots(figsize=(15, 8)) ax.scatter(x, y) plt.title("test") plt.xlabel("Time") plt.ylabel("recording1") texts = [] for i, txt in enumerate(n): texts.append(ax.annotate(txt, (x[i], y[i]), xytext=(x[i],y[i]-.03), ha='center', fontsize=8)) adjust_text(texts) groups = DF.groupby("recording2") for name, group in groups: plt.plot(group.Time, group.recording1, marker='o', linestyle=...

How to load onclick functions on Google Maps correctly?

I've made a Google map from documentation exmaples. I want to make onclick functions for showing alerts or getting data from clicked objects. <!DOCTYPE html> <html> <head> <title>Simple Map</title> <meta name="viewport" content="initial-scale=1.0"> <meta charset="utf-8"> <style> #map { height: 90%; } html, body { height: 90%; margin: 0; padding: 0; } </style> </head> <body> <div id="map"></div> <script> let map; function initMap() { map = new google.maps.Map ( document.getElementById( 'map' ), { center: { lat: 51.513329, lng: -0.088950 }, zoom: 14 }); } google.maps.event.addDomListener(window, 'load', initialize); google.maps.event.addListener(map, 'click', function(event) {alert('Hi');}); </script> <script src=" https://maps.googleapis.com/maps/api/js?key=key&callback=initMap" async defer><...

Why will only one of two almost identical toggle functions actually change the state of a property?

I wrote ToggleDisplayMenu first and it works perfectly. I tried writing ToggleMelkesjef and ToggleOrdenselev the exact same way but they do not work. They do get called on their respective button clicks, just the values of isMelkesjef and isOrdenselev do not seem to change. //Function to toggle displaymenu function ToggleDisplayMenu(name) { setStudents( students.map((student) => student.name === name ? { ...student, isDisplayMenu: !student.isDisplayMenu } : student ) ); } //Function to toggle ordenselev function ToggleOrdenselev(name) { setStudents( students.map((student) => student.name === name ? { ...student, isOrdenselev: !student.isOrdenselev } : student ) ); } //Function to toggle melkesjef function ToggleMelkesjef(name) { setStudents( students.map((student) => student.name === name ? { ...student, isMelkesjef: !student.isMelkesjef ...

Best way to exclude unset fields from nested FastAPI model response

Assuming I have Pydantic-based FastAPI models similar to: class Filter(BaseModel, extra=Extra.forbid): expression: str | None kind: str | None ... class Configuration(BaseModel): filter: Filter | None = {} .... By default a model that is sent nothing for the filter will end up exporting like this: { "filter": { "expression": None, "kind": None, ... }, ... } What I want instead is this: { "filter": {}, ... } What is the best way to have the nested model always have the exclude_unset behavior when exporting? Sometimes in a complicated model I want some nested models to exclude unset fields but other ones to include them. I'm aware of exclude_unset and response_model_exclude_unset , but both affect the entire model. It feels like there should be a way to specify behavior for a nested model and have the be consistently respected, but I can't find how to do this. Is there a be...

Three.JS - Additional canvases only displaying black screen

So I’m basically trying to create different objects on different canvases. The initial canvas (background) is working properly, but the additional canvases that I created would only display a black screen. Not sure what is wrong as I believe I have put in the necessary elements (lights, renderers, etc) inside already. Background Canvas Works, other canvas only Black Screen If these small canvases could render properly, I am planning to include my custom 3D models, as well as orbit controls. How my site is set up: Background: A Fullscreen Three.JS scene containing various shapes with scroll animations - rendered into a fixed position (CSS) canvas that acts as a background. Rows: A 50-50 grid layout where the left side contains texts, and the right side is a Three.JS scene resized using (window.ClientWidth and Height) and CSS Width and Height. This will be duplicated several times as the idea is to display numerous products. This is where the problem lies. The web was built using vani...

Python Fastest (minimum execution time) approach

I am looking for the fastest , minimum execution time approach to get all the numbers below a "n" number given by the user that are multi-perfect. A number "X" is said to be multi-perfect if the sum of divisors is equal to "X" or "X" multiplied by a int between 2 to 11. Something like this: sum_div = X --> Multi-perfect number sum_div = X * k (int between 2 to 11) --> Multi-perfect number The algorithm that i have currently is this: def multiperfect(n): list=[1] for X in range(2, n + 1): div = [] for i in range(1, X): if X % i == 0: div.append(i) sum_div = sum(div) if sum_div == X: list.append(X) else: for k in range(2, 11): if (k * X == sum_div): list.append(X) return list As you can see this algorithm has 2 iterative structures that make it very very slow O(n^2), i am looking to improv...

Using Mammoth style_map to apply inline styles and custom attributes

I'd like to use Mammoth's style map to apply inline styles, like color:red and custom tags/attributes, though I cannot seem to find anything in the docs that suggest I can. Does mammoth have the capability to do inline styling? Simple tags and classes works fine, e.g. p[style-name='Heading 3'] => div.foo:fresh However I'd like to do something like this: p[style-name='Heading 3'] => div(color:red):fresh or p[style-name='Heading 3'] => div, cust_tag:val:fresh source https://stackoverflow.com/questions/76096026/using-mammoth-style-map-to-apply-inline-styles-and-custom-attributes

Print a list of One Hot Encoder values

I`m using sklearn library to encode one column with categorical data to One Hot Encoder values. from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder ct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [3])], remainder='passthrough') X = np.array(ct.fit_transform(X)) Is there a method in sklearn library to print a list of categorical values with assigned One Hot Encoder code? For example, if I have categorical data "A", "B", "C", I want it to print something like "A" 0 0 1, "B" 0 1 0,"C" 1 0 0, so I can track back which code to which value was assigned. I tried to use .get_feature_names() method, but it gives me error. source https://stackoverflow.com/questions/76095583/print-a-list-of-one-hot-encoder-values

How can I remove the "\n" character in a large file with Python?

I have a large .txt file containing numerous email addresses, but it also contains many unnecessary "\n" characters. I want to extract only the email addresses and remove any other characters. To accomplish this, I have written a small script in Python. import re filename = "input.txt" output_filename = "output.txt" email_regex = r'\s*([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,})\s*' with open(filename, "r") as f, open(output_filename, "w") as out: for line in f: emails = re.findall(email_regex, line) for email in emails: out.write(email + "\n") While the script successfully extracted regular email addresses, it encountered some difficulties with certain formats. As an example, suppose I have a line of data that reads "CC\nexample@example.com\n". When I run my code, the resulting output is "nexample@example.com", which is not what I intended. Rather, I woul...

How to center SVG in nextJs with viewbox

I am building a preloader using nextjs, it's a timed benzene animation that plays out entirely before the homepage appears. The issue that I am dealing with comes from both ways that I try to implement this preloader. First, when I set the viewbox attributes in the component as shown below, I receive an error. "use client"; import React, { useEffect, useState } from 'react'; import './Preloader.module.css'; const Preloader = () => { const viewBox = `${-window.innerWidth / 2} ${-window.innerHeight / 2} ${window.innerWidth} ${window.innerHeight}`; return ( <div className='preloader-div'> <svg viewBox={viewBox} width="100%" height="100%"> ... </svg> </div> ); }; export default Preloader; This is the error I receive... error - ReferenceError: window is not defined at Preloader (./src/app/preloader/preloader.tsx:13:21) 6 | const Preloader = () => { 7 ...

How do I link to specific tabs from another page?

I've set up my first tab to open by default on page load, but on some occasions, I want display the second or third tab when linked to from another page. How can I accomplish this? I tried linking to the tab's ID, but the defaultOpen tab is the one that remains visible. I was thinking I could call the openTab function, passing the ID of the tab I wanted to view, but I don't know how to code that when going from one page to another. Any guidance you can offer would be much appreciated. Here's the basic HTML tab skeleton. <div class="new-tab-section"> <div class="tabs"> <button class="tablinks" onclick="openTab(event, 'InstallationTab')" id="defaultOpen">Installation</button> <button class="tablinks" onclick="openTab(event, 'TrainingTab')">Training</button> <button class="tablinks" onclick="openTab(event, 'Trouble...

With Inline script working, How can I make my external .js file work properly with my HTML file?

I'm currently working on a website utilizing ipfs & pinning services like Pinata. My last build works flawlessly when delivered locally or through a public gateway. When trying to pin my last build to Pinata, I was informed I can't use inline JS. So my next build includes an external JS file called app.js. I'm storing this file within the same folder as my HTML file (index.html) and uploading to IPFS for testing purposes before pinning on Pinata. I cannot for the life of me get this new build to work properly. No matter how I try to call the .js filepath, I either get 400s or 500s every single time. <script type="text/javascript" src="app.js"></script> This is the line im using to call the file. I'm learning as I go so I don't know enough about permissions or other issues that may be causing this .js file to be unretreivable. At this point the code base is still pretty simple and I'm sure I'm missing something very o...

How to combine columns in dask horizontally?

I'm trying to combine multiple columns into 1 column with python Dask. However I don't seem to find an (elegant) way to combine columns into a list. I only need to combine column "b - e" into 1 column. Column "a" needs to stay exactly as it is now. I've tried using apply to achieve this. Despite the fact that this isn't working it's also slow and must likely not the best way to do this. Polars has this command concat_list which works beautifully using: df.select('a', value=pl.concat_list(pl.exclude('a'))) . What is the Dask alternative for this? Anyone who can help me out with how I can achieve this result? The dataframe I have: ┌─────┬─────┬─────┬─────┬─────┐ │ a ┆ b ┆ c ┆ d ┆ e │ ╞═════╪═════╪═════╪═════╪═════╡ │ 0.1 ┆ 1.1 ┆ 2.1 ┆ 3.1 ┆ 4.1 │ │ 0.2 ┆ 1.2 ┆ 2.2 ┆ 3.2 ┆ 4.2 │ │ 0.3 ┆ 1.3 ┆ 2.3 ┆ 3.3 ┆ 4.3 │ └─────┴─────┴─────┴─────┴─────┘ The result I need: ┌─────┬───────────────────┐ │ a ┆ value │ ...

How to start a flask server on android/iOS in backend

I am making an app with flutter frontend and python backend. The problem is that I need to create a flask server running offline locally on an Android or iOS device. I don't know how to start the server simultaneously with the app to push some http requests to the server. The server is basically: from flask import Flask, request, jsonify import socket import threading import paramiko app = Flask(__name__) @app.route('/function_name', methods=['POST']) def function(): .... if __name__ == '__main__': app.run(host='0.0.0.0', port=5000) source https://stackoverflow.com/questions/76086999/how-to-start-a-flask-server-on-android-ios-in-backend

Audio file only plays first few seconds before restarting on website

I am trying to create a small sound dashboard app (similar in functionality to Noisli ). For every "sound" I am using a for loop in Svelte to generate its HTML: {#each songList as {id, name}} <button id="{name}Container" on:click={() => handleSong(name)} class="sound"> <p class="soundCaption">{name}</p> <audio id="{name}" src="/audio/{name}.mp3" loop></audio> </button> {/each} When the container is clicked it is then handled with this function: function handleSound(soundName){ const audio = document.getElementById(soundName); const temp = soundName + "Container"; var audioContainer = document.getElementById(temp); if (audio.paused) { audio.play(); audioContainer.style.backgroundColor = "rgba(0, 0, 0, 0.3)"; } else { audio.pause(); ...

NPM install behaves differently in different situation, unable to understand if it's correct or not?

npm init to initialize the project I am using axios: "~1.2.4" in the package.json file when I run npm install package 1.2.6 will be installed which is correct as the latest patch will be installed now if I use ^1.2.4 in package.json and run npm install the node modules or package-lock.json won’t get updated to 1.3.6 which is the intended behaviour based on the usage of ^ ( why is this happening here? ) now if I use ^1.3.4 in package.json and run npm install the node modules and package-lock.json both will get updated to use 1.3.6 which is the intended behaviour (and I suppose this is correct) now if I use 1.2.4 or 1.3.4 the packages with the version will be installed Also, what is the actual use of the .package-lock.json file? Via Active questions tagged javascript - Stack Overflow https://ift.tt/nfDTGYI

IpcMain communication issue

I'm trying to change the src="" of a webview. My program are two html pages, in the page1 I have an Input that when you press enter or a button, go to next page (page2). So in Page2 I put a webview to make appear the result of the search of the text put in the input. To do that I used ipcRender and ipcMain, but the communication its not working. I have the 2 html files and 4 js files: In the htmls I have the input and a button, and in the other html the webview To send the text of the input I have the input.js: const searchBtn = document.getElementById('searchBtn'); const textInput = document.getElementById('text-input'); textInput.addEventListener('keydown', (event) => { if (event.key === 'Enter') { search(); } }); searchBtn.addEventListener('click', () => { search(); }); function search() { const query = textInput.value; ipcRenderer.send('search', query); // Send to index.js the query, I checked...