Skip to main content

Posts

Showing posts from February, 2022

Is there a way to modify the leader line items display total in addition to percentage in Google Apps Script generated pie chart?

Is there a way to adjust the leader line labels on a pie chart generated using Google Apps Script in Google Docs? Currently the lines show the label and the percentage of the slice. Ideally, I'd like it to either list the Total Value of the Slice & the percentage, but even if I can just get it to show the Total Value only would work. I've tried searching Google's documentation but can't seem to find anything other then putting the values on the slices themself (Which I think makes the charts look really poorly made when the value can even fit on the slice). I've included a code snippet showing how the chart is built, as well as an example chart with the item I'm looking to adjust circled. Hopefully I formated the code block correct on this, since it's my first post! Thank you so much for your help! Pie Chart Example var chart = Charts.newPieChart() .setTitle('Chart Title') .setDimensions(864,534) .setDataTable(d

Setting a variable to a parameter value inline when calling a function

In other languages, like Java, you can do something like this: String path; if (exists(path = "/some/path")) my_path = path; the point being that path is being set as part of specifying a parameter to a method call. I know that this doesn't work in Python. It is something that I've always wished Python had. Is there any way to accomplish this in Python? What I mean here by "accomplish" is to be able to write write both the call to exists and the assignment to path as a single statement with no prior supporting code being necessary. I'll be OK with it if a way of doing this requires the use of an additional call to a function or method, including anything I might write myself. I spent a little time trying to come up with such a module, but failed to come up with anything that was less ugly than just doing the assignment before calling the function. source https://stackoverflow.com/questions/71300465/setting-a-variable-to-a-parameter-value-in

im trying to make a mod menu with on click javascript , im trying to edit a bookmarklet and change the clickable links to onclick

i hope im asking this question right but here is the bookmarklet im trying to edit i want to change the clickable links to onclick javascript javascript:!function(){var c=0x1f4,d=0x12c,e='#AAA',f=0x1,g=0x20,h='#444',i='#FFF',j='Bookmarklet\x20Links',k=~~(document['documentElement']['clientWidth']/0x2-c/0x2),l=~~(document['documentElement']['clientHeight']/0x2-d/0x2),m=~~(0.8*g),n=document'createElement';Object'assign';var o=document'createElement';Object'assign';var p=document'createElement';Object'assign',p['textContent']=j;var q=document'createElement',r=~~((g-m)/0x2);Object'assign';var s=document'createElement';Object'assign';var t=document'createElement';t['textContent']='Click\x20the\x20links\x20to\x20open\x20a\x20new\x20tab!',s'appendChild';var u=document'createElement';[{'name':

Anaconda3 - Ignore PackagesNotFoundError

I work on a machine that has anaconda 4.10.3 pre-installed. I am unable to update it to a newer version. The problem with this version is that it interprets "Python 3.10.2" as "Python 3.1". It cuts of the version number after the first character behind the dot. When I try to install pytorch I get the following error: PackagesNotFoundError: The following packages are not available from current channels: - python=3.1 Is there a possibility to ignore this error and just continue with the installation? source https://stackoverflow.com/questions/71300065/anaconda3-ignore-packagesnotfounderror

Sorting the distances of stores from user on getCurrentPosition() mapbox

Im working with the MapBox API and I want to customize the 'UserLocate' button such that it not only gives the current location but also sorts locations from the user. Here's the current code of user locate. navigator.geolocation.getCurrentPosition(position => { user_lat = position.coords.latitude; user_long = position.coords.longitude; }); Currently I am only able to sort distance when I use the search box in MapBox. I am changing the longitude and latitude of the searched location of event object to current user's longitude and latitude. From there I just use the methods availible on the doc geocoder.on('result', (event) => { /* Get the coordinate of the search result */ const searchResult = event.result.geometry; userLoc = searchResult; userLoc["coordinates"][0] = user_long; userLoc["coordinates"][1] = user_lat; // use userLoc to sort distances

How is the return method used in iterators / async iterators?

MDN states that async iterators have a return method const asyncIterable = { [Symbol.asyncIterator]() { let i = 0; return { next() { const done = i === LIMIT; const value = done ? undefined : i++; return Promise.resolve({ value, done }); }, return() { // This will be reached if the consumer called 'break' or 'return' early in the loop. return { done: true }; } }; } }; However, the Typescript definitions of async iterators require the return method to accept an optional value return {value: someValue, done: true} , whereas MDN does not do this. Here's the TS definition: interface AsyncIterator<T, TReturn = any, TNext = undefined> { // NOTE: 'next' is defined using a tuple to ensure we report the correct assignability errors in all places. next(...args: [] | [TNext]): Promise<IteratorResult<T, TReturn>>; return?(value?: TReturn | PromiseLike&l

Python - Better way to compare 2 csv files and add 2 new columns if condition met?

Goal: Compare 2 CSV files (Pandas DataFrames) If user_id value matches in rows, add values of country and year_of_birth columns from one DataFrame into corresponding row/columns in second DataFrame Create new CSV file from resulting "full" (updated) DataFrame The below code works, but it takes a LONG time when the CSV files are large. I have to imagine there is a better way to do this, I just haven't been able to figure it out. Current code: #!/usr/bin/env python # Imports import pandas as pd # Variables / Arrays import_optin_file_name = "full_data.csv" import_extravars_file_name = "id-country-dob.csv" export_file_name = "new_list.csv" # Create DataFrames from 2 imported CSV files optin_infile = pd.read_csv(import_optin_file_name) extravars_infile = pd.read_csv(import_extravars_file_name) # Create/Insert new columns to "optin_infile" dataframe (country,year_of_birth) with initial value of NULL optin_infile.insert(loc=

Filter array of objects with min and max value along with null check

So I have the following data set const data = [ { id: '11se23-213', name: 'Data1', points: [ { x: 5, y: 1.1 }, { x: 6, y: 2.1 }, { x: 7, y: 3.1 }, { x: 8, y: 1.5 }, { x: 9, y: 2.9 }, { x: 10, y: 1.1 } ] }, { id: 'fdsf-213', name: 'Data2', points: [ { x: 5, y: 3.1 }, { x: 6, y: 4.1 }, { x: 7, y: 2.1 }, { x: 8, y: 0.5 }, { x: 9, y: 1.9 }, { x: 10, y: 1.4 } ] }, ] On this data set I am rendering the chart. I am trying to achieve the following things with data set. Filter points using min and max value (user gives it in the input field) User have the option to only give min value User have the option to only give max value User can give both min and max value Revert to original data if a user remove/clear both min and max value/input Looking at the above requirement its possible that max and min value can be null. Since I am working in

MySQL update with variable

I am encountering a problem while updating a table. The code is from telegram bot. We are receiving messages from user, and asking him for a name. This is the variable 'first_name'. We already know his user_id which is integer. Then I am trying to do def bd_set(body): cursor.execute(body) connect.commit() bd_set(f"INSERT INTO user_info (user_id,first_name) VALUES({user_id},{first_name})") and getting an error: no such column "John". But if I try without variable, the code works: bd_set(f"INSERT INTO user_info (user_id,first_name) VALUES({user_id},'John')") So, I cannot input varibale (first_name), while variable'user_id' inputs easily. what can solve the issue? source https://stackoverflow.com/questions/71287140/mysql-update-with-variable

Wait till sound is finished and then play another sound

I'm working on a morse code audio player. I play each sound with this function: function playSound(n: number): void{ if(n === 0){ let sound = new Audio("../audio/short.mp3"); sound.play(); } else if(n === 1){ let sound = new Audio("../audio/long.mp3"); sound.play(); } else{ let sound = new Audio("../audio/break.mp3"); sound.play(); } I call it here: for (let j = 0; j < nummers.length; j++){ playSound(nummers[j]); } But when I call this function multiple times the sound are playing in parallel. Who can I play one after another? Via Active questions tagged javascript - Stack Overflow https://ift.tt/8QwYeNS

How to increment index in Python loop

I am wanting to loop through a string and capture 2 items each time while also incrementing through the index of the iterable. So I want to slice 2 items but increase the index by 1 every time through the loop. How can I do this? my_string = 'teststring' desired output = te es st ts st tr ri in ng I have tried the following to slice the two items, but can't figure out the best way to iterate thought the index str1 = 'teststring' i=0 while i<10: i +=1 str2=str1[0:2] print(str2) source https://stackoverflow.com/questions/71279525/how-to-increment-index-in-python-loop

TypeError: options.getMember is not a function

so I have been coding the ban command, just finished it and I started getting this error. I have no idea how to fix it even though searching through the internet for a while now. Can someone help me with this one? This is the error I am getting: /Users/Aplex/Documents/Aplel/Commands/Moderation/ban.js:45 const Target = options.getMember("target"); ^ TypeError: options.getMember is not a function at Object.execute (/Users/Aplex/Documents/Aplel/Commands/Moderation/ban.js:45:32) at Object.execute (/Users/Aplex/Documents/Aplel/Events/Interaction/interactionCreate.js:21:21) at Client.<anonymous> (/Users/Aplex/Documents/Aplel/Structures/Handlers/Events.js:18:54) at Client.emit (node:events:538:35) at InteractionCreateAction.handle (/Users/Aplex/Documents/Aplel/node_modules/discord.js/src/client/actions/InteractionCreate.js:74:12) at Object.module.exports [as INTERACTION_CREATE] (/Users/Aplex/Documents/Aplel/node

How to fix KeyError in pymongo

class tradesReport(): def saveBuyٍSelltrade(collection, ticker, buy, sell): collection= db[collection] newBuyTrade= {'Symbol': ticker, 'Buy': buy} buytrade=collection.insert_one(newBuyTrade) newSelltrade={'Symbol':ticker ,'Sell':sell} selltrade=collection.insert_one(newSelltrade) def BUYtrade(collection,ticker,buy): collection= db[collection] newBuyTrade= {'Symbol': ticker, 'Buy': buy} buytrade=collection.insert_one(newBuyTrade) return buytrade def Selltrade(collection,ticker,sell): collection= db[collection] newSellTrade= {'Symbol': ticker, 'Sell': sell} selltrade=collection.insert_one(newSellTrade) return selltrade def findAllBuyTrades(collection): tickers= {} collection= db[collection] data= collection.find({}) for dt in data: t

React not loading, It also doesn't recognize document commands

Extremely simple HTML & JS set up for react not working, I followed exactly the instructions in the react website but it is not working. If anyone can see any errors I would appreciate it, I just followed exactly the instructions on the react website... Also, even the document.getElementById command is not even working as shown in the error message on the screenshot... Thanks in advance. HTML code (extremely simple): <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="root"></div> <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/r

How do I make a responsive grid consisting of square images?

On my website, I would like to add a grid consisting of square images (album covers). I also want to add this hover effect to said images: https://codepen.io/jarvis-ai/pen/GRJpQWO . How would I do this? I have already tried a couple of things I found while researching my question but I never got the result I wanted. I have always had issues with the sizing of the images and making the sizes responsive. Here is a visualization of what I want it to look like and what I to happen: Grid on a normal-sized monitor: Grid on a smaller monitor or window: Image on hover: Pretty much: If the page is viewed on a normal-sized monitor, there should be 4 images in one row. If the page is viewed on a phone or if the window is resized, the images split into more rows with one row containing less than 4 now. If the mouse is being hovered over an image, the image should do the effect thing. Notice: I should be able to do the hover effect by myself since there is already a working demo. I a

I want to add a old document to a new collection on a specific date

I am extracting a document from a collection called 'Users'. Then I want to push the document with some updations to a collection 'pending'. The Invoke a cloud function every day and get data from my users' collection. Every document has a timestamp. enter image description here I check every day if the date is equal to the date on the server. if yes, then it executes the function for adding the data to the new collection pending. How can I ensure if It will work correctly? Thanks in advance! Via Active questions tagged javascript - Stack Overflow https://ift.tt/WkL6GMg

Deploy a Python Flink application on AWS Kinesis

I am trying to deploy a Python Flink application on AWS Kinesis Data Analytics. I followed the official documentation on https://docs.aws.amazon.com/kinesisanalytics/latest/java/how-python-creating.html I want to create a source table using the TableAPI that read from Confluent Kafka and deserialize the messages using avro-confluent format. Following the connectors documentation https://nightlies.apache.org/flink/flink-docs-release-1.13/docs/connectors/table/kafka/ and https://nightlies.apache.org/flink/flink-docs-release-1.13/docs/connectors/table/formats/avro-confluent/ I will need to include two jar files as dependencies. But the property jarfile on "ApplicationConfiguration": { "EnvironmentProperties": { "PropertyGroups": [ { "PropertyGroupId": "kinesis.analytics.flink.run.options", "PropertyMap": { "python": "MyApplication/main.py", &q

FlaskForm had to reload select choices

I am new to Python and Flask. I am trying to use WTForm FlaskForm, and having problems with choices in SelectField. I am building my forms like this. class FightForm(FlaskForm): fight_id = StringField('fight_id', render_kw={'readonly': True}) fight_type_id = SelectField('fight_type_id', choices=[(t.fight_type_id, t.type_name) for t in fight_type.query.all()], validate_choice=False, validators=[DataRequired()]) These choices appear to only load 1 time. If I go add a new fight_type , I have to stop the application and restart if for it to refresh. Also, I found this answer, flask wtforms selectfield choices not update , but FlaskForm does not trigger the __init__ function this suggests. I changed it temporarily to Form anyway and got an error saying fight_type_id does not belong to form (paraphrasing). I would like for these to refresh every time I call the page. source https://stackoverflow.com/questions/71258629/flaskform-had-to-reload-

Apple Login Using ColdFusion and Javascript

I have problem with Apple login not properly handle call back function getting from Apple Website. Can any one help me how i handle the call back link Thanks Now i have this message.. Via Active questions tagged javascript - Stack Overflow https://ift.tt/WkL6GMg

Convert complex txt to csv with python

I want to convert text to csv. Input file contains 10000K lines. Sample of input file is as below:- Item=a Price=10 colour=pink Item=b Price=20 colour=blue Pattern=checks My output should look like this Item Price Colour Pattern a 10 pink b 20 blue checks I am getting output if there is only single '=' in 1 line, if there are more than 1 like 2/3 '=' then I am not sure how to apply for loop. Can someone check my for loop part? Am I going wrong somewhere? import csv import glob import os def dat_to_csv(filename, table_name): with open(filename, 'r') as reader: list_of_columns = [] table_values = [] master_table = [] counter = 0 for line in reader: #stripped_line = line.strip() if line == "\n": #copy all elements which have values else paste a null if (table_values): #master_table.append(table_values)

jupyter contrib nbextension install gives Jupyter command `jupyter-contrib` not found

Trying to (re)install Jupyter's nbextension via the following steps in terminal pip install jupyter_contrib_nbextensions jupyter contrib nbextension install --user jupyter nbextension enable varInspector/main Step 1 = runs and i am able to launch notebooks via "jupyter notebook" in terminal just fine. Step 2 = fails with usage: jupyter [-h] [--version] [--config-dir] [--data-dir] [--runtime-dir] [--paths] [--json] [--debug] [subcommand] Jupyter: Interactive Computing positional arguments: subcommand the subcommand to launch optional arguments: -h, --help show this help message and exit --version show the versions of core jupyter packages and exit --config-dir show Jupyter config dir --data-dir show Jupyter data dir --runtime-dir show Jupyter runtime dir --paths show all Jupyter paths. Add --json for machine-readable format. --json output paths as machine-readable j

How do I increase electron forge memory heap size?

I have a template app made with electron forge, and when I try to execute the following code const ARRAY_LENGTH = 1.1e8; const randomArray = []; for (let i = 0; i < ARRAY_LENGTH; i += 1) { randomArray.push(Math.random()); } I believe I run out of memory with the following error: <--- Last few GCs ---> [23850:0x7900000000] 16762 ms: Mark-sweep (reduce) 3622.1 (3706.7) -> 3478.0 (3562.6) MB, 1806.7 / 0.0 ms (+ 0.5 ms in 1 steps since start of marking, biggest step 0.5 ms, walltime since start of marking 2717 ms) (average mu = 0.589, current mu = 0.60[23850:0x7900000000] 20404 ms: Mark-sweep (reduce) 3478.0 (3562.6) -> 3286.0 (3370.6) MB, 3640.7 / 0.0 ms (average mu = 0.307, current mu = 0.000) last resort GC in old space requested <--- JS stacktrace ---> I'm wondering how I increase the memory available to the process? Note: tried adding preload script in forge.config.js as described here , using the following (to no avail, although the preload

Extracting HUE value from specific part of Image

I have one image with some structure (rectangle) That all of them are approximately green. I used this code to find a number of those objects in the image and make a contour around them. Their hue value will change over time. I need to add one code to extract the average of the new hue value in each counter that we detect in the previous step and save them in a new array. My mask, I want to find The average hue value inside the mask(or detected contour) after one hour import cv2 import numpy as np img = cv2.imread(r"Image.JPG") hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) lower_range = np.array([75, 50, 50]) upper_range = np.array([165, 200, 255]) mask = cv2.inRange(hsv, lower_range, upper_range) (cnt, hierarchy) = cv2.findContours(mask.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) print("Number of object in the image is : ", len(cnt)) rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) count=cv2.drawContours(rgb, cnt, -2, (0, 0, 0), 2) cv2.imshow('count',count) c

I cannot read vuex-persist in v-if

I am trying to use vuex-persist on nuxt.js but when try to read the data in a v-if doesn't work. I created a new file inside plugins called vuex-persis.js with the following code: import VuexPersistence from 'vuex-persist' export default ({ store }) => { new VuexPersistence({ storage: window.localStorage, }).plugin(store); } and into nuxt.config.js I added the following code: plugins: [{ src: '~/plugins/vuex-persist', mode: 'client' }], The code that I use in order to store and get data is the following: this.$store.commit('login', { idToken }); store.state.isLogin and I have added the following file inside the project ./store/index.js export const state = () => ({ isLogin: false, idToken: '', }); export const mutations = { login(state, newState) { state.isLogin = true; state.idToken = newState.idToken; }, logout(state) { state.isLogin = false; state.idToken = ''; }, }; I have

Using lodash get with a string of `object.pair`

I want to use lodash get method to return data in a nested object. The problem is what I'm using can either be a single string, or a string with a not notation representing a nested object. An example of the data: data: { animals: { dogs: { labrador: { age: 1 }, dalmation: { age 5 }, }, lion: { age: 28 } } } To access the lion's age I could use get(data, ["animals", "lion", "age"], []); But let's say I get a string const string = "dogs.labrador" . I wouldn't be able to just swap out lion for string in the get method. Is there an easy way to access the labrador's age? Via Active questions tagged javascript - Stack Overflow https://ift.tt/1BLizxI

Why dynamic values are not being submitted from form with NextJS?

I'm working on React based on NextJS code. If I manually enter values in form fields and submit the form, I get all the values in the component function. But if I dynamically display values in a form field like value={query.campaignid} , the component does not collect any value. import { Button, Input } from "@chakra-ui/react"; import { Field, Form, Formik } from "formik"; import { useRouter } from "next/router"; export default function FormikExample() { const { query } = useRouter(); return ( <> <Formik initialValues={ { // campaignid: " ", } } onSubmit={(values) => { setTimeout(() => { console.log(values); }); }} > {(props) => ( <Form> <Field name="campaignid"> <Input value={query.campaignid} /> </Field>

Find the Slope JavaScript

I have a codewars problem below: Given an array of 4 integers [a,b,c,d] representing two points (a, b) and (c, d), return a string representation of the slope of the line joining these two points. For an undefined slope (division by 0), return undefined . Note that the "undefined" is case-sensitive. a:x1 b:y1 c:x2 d:y2 Assume that [a,b,c,d] and the answer are all integers (no floating numbers!). Slope: https://en.wikipedia.org/wiki/Slope * I can get the slope for any numbers when 0 is not in the denominator (bottom of the fraction). However, whenever 0 is in the denominator, I get this message: *expected undefined to equal '0' I'm not sure on how to solve this part. My code so far is below: function slope(points) { let a = (points[0]); let b = (points[1]); let c = (points[2]); let d = (points[3]); function findSlope(a,b,c,d) { if (c-a === 0) { return 'undefined'; } else if (c-a !== 0) { let slope = (d-b)/

Could not find a version that satisfies the requirement hikari-lightbulb (from versions: none)

I am trying to install this python library hikari-lightbulb but there seems to be some sort of issue which is not letting it get installed. The command on the github repository to install this library is pip install hikari-lightbulb but using that is giving the error: ERROR: Could not find a version that satisfies the requirement hikari-lightbulb (from versions: none) ERROR: No matching distribution found for hikari-lightbulb Any way I could install this package now? source https://stackoverflow.com/questions/71243506/could-not-find-a-version-that-satisfies-the-requirement-hikari-lightbulb-from-v

Make triangle rotate/animate with radio button

I've been working on a WebGl animation program where there are buttons that you can choose to alter a triangle vertice location based on where you click on the screen as well as a slider that runs a recursive function that divides the triangle based on the input. The part i'm stuck on is my last radio button that is supposed to constantly rotate my triangle including the edits to whatever previous changed were made to the triangle with the buttons. Every time I run my application it gives me a warning pointing to javascript line 149 my render2 function: gl.uniform1f(thetaLoc, theta); saying: sierpinski-extended.js:149 WebGL: INVALID_OPERATION: uniform1f: location not for current program. The code below isn't going to work because I need to add external libraries and i'm not sure how to. Though I have uploaded my project on my website: https://www.cis.gvsu.edu/~nunezjo/labs/sierpinski-extended/sierpinski-extended.html Here's an example of my working rotation with

pandas alternative to append change dtypes

since pd.append is deprecated, I've migrated in my code all my df = df.append(temp) to df = pd.concat([df, temp]) Usually, I have processing where I do something like: out = pd.DataFrame(columns=['some', 'cols']) for _, temp in df.groupby('key'): # SOME PROCESSING OF temp df like # temp = pd.merge(out, temp, on=['some', 'cols']) out = pd.concat([out, temp]) # before: out = out.append(temp) Here, since out is an empty df at first but columns are set, it will not keep dtypes from the temp df. For instance, if I have a datetime column, it's converted as object. If I use an empty df without columns, it keeps the dtypes. Is that expected ? Considering append will be deprecated this has huge impact in all my code. source https://stackoverflow.com/questions/71242918/pandas-alternative-to-append-change-dtypes

Why is the font in tkinter not changing in size even though I am changing the number?

So basically I have this GUI on tkinter and I want to change the size of the text on a label, this is my code: Import tkinter as tk #Main Page Attributes main_frame = tk.Tk() main_frame.attributes("-fullscreen", True) main_frame["bg"] = "#000000" main_frame.title("R-Net") label_frame = tk.Frame(main_frame) answer_label = tk.Label(label_frame, text="Welcome, Radwan", font=(70), bg = "black",fg = "white") answer_label.grid(row=0, column=0, sticky = tk.EW) label_frame.place(relx=.5, y=0, anchor="n") No matter how many times I change the number in font=(number) nothing changes. Why is that? source https://stackoverflow.com/questions/71242876/why-is-the-font-in-tkinter-not-changing-in-size-even-though-i-am-changing-the-nu

I'm having keep getting and error while using embeded messages because "cannot read property 'send' of undenifide"

I'm trying to make my bot send embededmessages and each time I send the message it gives me an error like this "cannot read property 'send' of undenified".Here is my code else if(message.content == "testing") { let channel = message.guild.channels.cache.get(832075875612491789) const exampleEmbed = new MessageEmbed() .setColor('#0099ff') .setTitle('v1.1 test') .setThumbnail('https://i0.wp.com/www.mysabah.com/wordpress/wp-content/uploads/2006/06/252.jpg?fit=640%2C392&ssl=1') channel.send({ embeds: [exampleEmbed] }); } Via Active questions tagged javascript - Stack Overflow https://ift.tt/CQ9FJRu

Python and Outlook - Marking message thread as 'read'

My company uses JIRA to track issues, and is set up to send an e-mail to all watchers and tagged users whenever an update is done on the issue. We also have some automation in place that will adjust fields on the issue (like sprint number) whenever it gets closed (this'll also send an e-mail). I also have a filter within Outlook that'll put any e-mail from JIRA into a separate subfolder 'JIRA'. I often receive e-mails on issues that have been closed. I'm trying to write a small Python script that'll mark all these e-mails as read if the JIRA issue has been closed already. The basic idea is I can run this script once a week or so to clean up my mailbox. I'm using the pywin32 and jira packages to do this, but I can't figure out how to change a message status. The fact that documentation is scarce doesn't help... What I have: import re import textwrap from jira import JIRA import pandas as pd import win32com.client jira = JIRA("<JIRA URL&g

Bokeh models to plot interactive addition of columns using CustomJS and CheckboxGroup

I want a CheckboxGroup to represent different columns of a dataframe. The idea is for the user to be able to add multiple column values if they select multiple columns and interactively display the sum as a plot. I have the following plot from a previous help I got: from bokeh.io import output_file, show from bokeh.plotting import figure from bokeh.layouts import layout, widgetbox from bokeh.models import ColumnDataSource, CustomJS from bokeh.models.widgets import CheckboxGroup import pandas as pd output_file('additive_checkbox.html') names = ['Number', 'A', 'B', 'C'] rows = [(340, 77, 70, 15), (341, 80, 73, 15), (342, 83, 76, 16), (343, 86, 78, 17)] data = pd.DataFrame(rows, columns=names) data['combined'] = None source = ColumnDataSource(data) callback = CustomJS(args=dict(source=source), code=""" const labels = cb_obj.labels; const active = cb_obj.active; const data = source.data;

Return the range of a dataframe not within a range of another dataframe

I have the following main dataframe: first.seqnames first.start first.end first.width first.strand second.seqnames second.start second.end second.width second.strand 0 chr1 346212 346975 7 * chr1 10882 10888 7 * 1 chr1 3135476 3136100 2 * chr1 10890 10891 2 * 2 chr1 11473 11484 12 * chr1 10893 10904 12 * 3 chr1 5388140 5388730 2 * chr1 11096 11097 2 * 4 chr1 346213 346984 68 * chr1 11202 11269 68 * I want to return the rows of above dataframe that don't exist within the range of the following dataframe: first.seqnames first.start first.end 3 4 5 3503 chr1 346213 346984 . 0 . 3504 chr1 3135466 3136202 . 0 . 3505 chr1 3190760 3191377 . 0 . 3506 chr1 3354604 3355258 . 0 . 3507 chr1 5388136 5388749 . 0 . Here, the first dataframe's 'first.start' and 'first.end' should not exist within the range(3462

How can I access response data of api call in react js while request is completing?

Actually I am getting pdf bytes from api call and I want to show pdf data as content is being downloaded but I am not able to access response data before the request is completed and for large pdf files I have to wait for few seconds for request to get completed and display it. Via Active questions tagged javascript - Stack Overflow https://ift.tt/CQ9FJRu

Automating the website , and the click function is not working when clicked on the input tag in javascript code?

document.getElementsByClassName('nameInputTag')[0].click(); <input formcontrolname="name" pinputtext="" type="number" class="nameInputTag"> I am automating the website , but the clicking function on input tag with the type = "text" is not working , it s working for all other tags beside this one ? Can anybody help me , what might be the problem ? I noticed when i click the input with the mouse it works and some html tags comes from the database, for others it is not like that . Via Active questions tagged javascript - Stack Overflow https://ift.tt/aZxVgCQ

How to separate tokens(parantheses,colons,etc) when a scanner is scanning a file?

I have created a Python scanner that is a lexical analyzer with created dictionaries. An argument(file) will be passed through command line that will then scan and print out each token. The problem is that if there is no space between tokens, it counts as a single string. Obviously, I do not want that. Is there a way to make a single rule for encountering no white space and create a single whitespace and then continue or will that be a bunch of conditionals for each one? # Implement split() for separation for word in line.split(): # Implementation of block comment encounter # If encountered, skip if tokenize(word).value == 3006: self.insideComment = True return "" if tokenize(word).value == 3007: self.insideComment = False return "" if tokenize(word).value == 3008: return (tokenizedLine) if tokenize(word).value == 3014: self.insideComment ==

¿Hay forma de que una API pueda realizar una búsqueda en masa de datos en personas y empresas sin inconvenientes? [closed]

necesito realizar búsquedas para identificar una serie de datos de mis encargados, pero ha sido imposible con los proveedores que he contratado, ya que el archivo JSON nunca esta completo o simplemente el endpoint se cuelga constantemente... Via Active questions tagged javascript - Stack Overflow https://ift.tt/aZxVgCQ

Python Generate Random Numbers with n standard deviations of a mean

I am dealing with numeric ranges obtained from a normal population that represent +- 2 standard deviations from the mean. Abnormal values are those that extend out past the 2SD limits. I want to generate random values that are skewed to look like the population data. So that I provide a mean and the +-2SD range to a function that generates numbers that produce a perfect bell curve that looks like the original population. So for example, take a lab test like glucose with a reference range of 60 - 100. This represents the values that would be obtained by testing a large group of normal people. The mean is 80 and the 2SD range is 60-100. That is 95% of the total population by definition. Values can extend out from below 50 upwards to 500. I would like to generate random numbers that fit these parameters. I am playing with numpy and scipy but I don't understand the math very well. Is there a function that will do this? source https://stackoverflow.com/questions/71212542/python-gene

Refresh tag value with dynamically generated data

I have a main php page displaying dynamically generated cards through a loop. I am trying to refresh the content for certain tags, but it doesn't seem to work so far. This is my main.php file: <div class="col" style="width: "> <div class="card shadow-sm h-100 border-dark rounded" style="width: 240px; background-color: #ededed"> <span class="mySpan"> <div class="container"> <input type="hidden" class="cardid" name="mycardId" value=" <?php echo $cardId ?>" id="cardid"> <div class="card-body px-0 py-0"> <table id="firstTable" class="table table-responsive-md table-striped table-borderless text-center mb-0" style="width: 237px; table-layout: fixed;"> <thead>

initializing a class variable in a subclass

I hope you guys can help me figure this out. I have this class: class CsvMapping: __mapping = [] @classmethod def initialize(cls, *args): if not args: raise AttributeError('No File/s Passed') filenames = [f for f in args] try: for file in filenames: with open(file, 'r') as csv_file: fieldnames = csv_file.readline().split(',') fieldnames = [f.strip() for f in fieldnames] rows = csv.DictReader(csv_file, fieldnames=fieldnames) for row in rows: cls.__mapping.append(row) except IOError as e: print(strerror(e.errno)) except AttributeError: print('No CsvFiles passed as arguments') except Exception as e: print(e) @classmethod def get_description_by_code(cls, code: str) -> str: try:

Converting Xhr Y min to minutes to do further calculations

I'm new to python and have been given a data set that has time stored in form X hr Y min. I would like to covert the data to an integer (minutes) to do further calculations. I tried the following: movies['Movie Runtime']=movies['Movie Runtime'].str.replace('hr','').str.replace('min','').str.replace(' ','').astype(object) movies['Movie Runtime']=movies['Movie Runtime'].astype(int) movies['Movie Runtime']=((movies['Movie Runtime']//100)*60) +((movies['Movie Runtime']%100)) However, it does not work for data given in form 5hr 3Min source https://stackoverflow.com/questions/71197921/converting-xhr-y-min-to-minutes-to-do-further-calculations

In Django, ModelAdmin, what is the difference between save_form() and save_formset()?

Can somebody explain the differences and/or similarities between save_form and save_formset from ModelAdmin? The only things i could find about this is from source code. def save_form(self, request, form, change): """ Given a ModelForm return an unsaved instance. ``change`` is True if the object is being changed, and False if it's being added. """ return form.save(commit=False) def save_formset(self, request, form, formset, change): """ Given an inline formset save it to the database. """ formset.save() And the docs have only this about save_formset ( https://docs.djangoproject.com/en/4.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_formset ) The save_formset method is given the HttpRequest, the parent ModelForm instance and a boolean value based on whether it is adding or changing the parent object. source https://stackoverflow.c

Trying to use binary search on object attribute

Im trying to do binary search in python for different objects with the same attributes. I started with the code, but dont know why its not working. I want to be able to put any name (attribute) and if its in the list be able to see that the value is there, and if not just return False. class Person: def __init__(self, name,age): self.name = name self.age = age def __lt__(self,other): return self.name < other.name def readfile(file): person = [] with open(file, 'r') as f: for i in f: name, age = i.split('*') person.append(Person(name,age)) return person def binary_search(item_list, item): names = [] first_position = 0 last_position = len(item_list) - 1 for i in item_list: names.append(i.name) # attribute of object names.sort() # sorting list while first_position <= last_position: mid_point = (first_position + last_position) //

How do I submit a form if AJAX validation is false?

I’m trying to validate a PromoCode prior to form submission. I AM able to do that but if the result is false, I am unable to submit the form unless the input field has been cleared. I’m a self-taught hobby coder and don’t really understand JS, AJAX or cfcomponent (this is my first shot at all of it.) I’ve had a great deal of help getting to this point. All additional help is greatly appreciated. SUMMARY: If the PromoCode the user types into the text field matches what’s stored in the DB… all is good. They submit the form and get the discount. If the PromoCode the user types into the text field does NOT match, they get the message “Sorry, that is not a valid promo code” but cannot submit the form unless the text field has been cleared. I need the user to be able to submit the form if the PromoCode is invalid… they just wouldn’t get the discount. We just told them it was invalid so they’re on their own. I'd hate to have the user not understand this and leave the site frustr

React SetState not updating in a function component

i'm working on a MERN project and it's been weeks that i have an issue with React states. I use a state to display a Popup or not. That's the way i'm displaying it: {OptionsPopUpState ? <OptionsPopUp func={OptionsPopUpfunc} name={OptionsPopUpData.name} id={OptionsPopUpData.id} shared={OptionsPopUpData.shared} languageQuestion={OptionsPopUpData.languageQuestion} languageAnswer={OptionsPopUpData.languageAnswer} /> : "" } The function passed in props is the one which hide or display it depending on the state. Here's the function: if(OptionsPopUpState){ SetOptionsPopUpState(false) console.log("New state "+OptionsPopUpState) refresh(); //refresh when close the popup } else{ console.log("display") SetOptionsPopUpState(true); } I don't get why it is not working because i use exactly the same code for an other popup and it works perfectly. On the top of it, when i print

How to drop records with special characters in a dataframe

I am trying to drop records/ Rows in a dataframe with special characters. I have tried many things like: df1['Day'] = df1['Day'].str.replace(r"[\"\'\|\?\=\.\@\#\*\,]", '') df.drop(df[df.ID.str.contains(r'[^0-9a-zA-Z]')].index But i am getting the following recurssion error. Also, is there any way to impute the records with special characters with mean/median/mode --------------------------------------------------------------------------- RecursionError Traceback (most recent call last) /usr/local/lib/python3.7/dist-packages/IPython/core/formatters.py in __call__(self, obj) 697 type_pprinters=self.type_printers, 698 deferred_pprinters=self.deferred_printers) --> 699 printer.pretty(obj) 700 printer.flush() 701 return stream.getvalue() 18 frames ... last 15 frames repeated, from the frame below ... /usr/local/lib/python

Matching ifferent forms of nested JS object / array data matching

I have the results of my MongoDB db query for two variables as follows : foodelectricity [ { food: 'dairy', electricity: 1 }, { food: 'fruitAndVeg', electricity: 1 }, { food: 'grains', electricity: 1 }, { food: 'bakedGoods', electricity: 5 }, { food: 'protein', electricity: 1 } ] foodresults { bakedGoods: 1, dairy: 3, fruitAndVeg: 1, grains: 2, protein: 1 } I need to multiyply the number values in foodresults times the electricity associated with that same item type in food electricity. For example : let helpValue = foodresults.bakedGoods = 1 * foodElectricity.food.bakedGoods = 5. I not believe that MongoDB returns the array in the same order each time -- so some sort of key value matching is required. I am having trouble figuring out how to find the helpValue. Any help is deeply appreciated. With thanks Karen Via Active questions tagged javascript - Stack Overflow https://ift.tt/CcWDh6N

why i can not load dynamic library 'cudart64_110.dll

when I run python Script that use tensorflowi receive this warning message in command line **> Could not load dynamic library 'cudart64_110.'; : cudart64_110.not found** How can i solve this error when using tensorflow and How can i use gpu and enable it when using TensorFlow source https://stackoverflow.com/questions/71188816/why-i-can-not-load-dynamic-library-cudart64-110-dll

How to Split Array Item Values in Firebase Firestore Array in React.js

I have an array in my firestore collection called features and it hold a set of features. Now i want to extract the values from the array and loop them and display them in a list. But when i do so they are displayed stuck together like this: In my firestore it saved as such: How can i get each value to be seperated and shows the icon beside when i loop through the array and print the values? here is my code: const [features, setFeatures] = useState([]); const featuresList = [] const getPropertyDetails = async () => { await firebase.firestore().collection("Properties").where("propertyID","==",propID).get().then((snapshot) => { snapshot.forEach((doc) => { const {features} = doc.data(); featuresList.push({ features:features, }) setFeatures(featuresList) })

Snowflake procedure looping issue with value being incremented implicitly

I am working on a procedure in snowflake (standard edition) that parses query_text from "SNOWFLAKE"."ACCOUNT_USAGE"."QUERY_HISTORY" to identify any tables that are accessed. Since we're on standard edition, we don't have access to the ACCESS_HISTORY table, which appears to only be populated in enterprise edition. I'm using regexp_cnt to identify how many instances of from's and join's exist in the query text and then attempting to loop through each instance to capture the table it hits. Somehow, it is incrementing my variable that I am setting with the regexp_cnt along with the counter that I am setting for looping. I'm not incrementing the regexp_cnt variables anywhere. Procedure is a bit lengthy so I will supply the key components here: This is where I'm setting my from and join count values // get counts of from and join clauses var get_query_history_loops_sql = `create or replace temporary table tmp_query_hist_clean_