questions
stringlengths
50
48.9k
answers
stringlengths
0
58.3k
Sympy: How to calculate the t value for a point on a 3D Line Using sympy how would one go about to solve for the t value for a specific point on a line or line segment?p1 = sympy.Point3D(0,0,0)p2 = sympy.Point3D(1,1,1)p3 = sympy.Point3D(0.5,0.5,0.5)lineSegment = sympy.Segment(p1,p2)eqnV = lineSegment.arbitrary_point()i...
You can get a list of coordinate equations and pass them to sympy's solve function:In [112]: solve((lineSegment.arbitrary_point() - p3).coordinates)Out[112]: {t: 1/2}
Python Dataframe add new row based on column name How do I add a new row to my dataframe, with values that are based on the column names?For exampleDog = 'happy'Cat = 'sad'df = pd.DataFrame(columns=['Dog', 'Cat'])I want to add a new line to the dataframe where is pulls in the variable of the column heading Dog C...
You can try append:df.append({'Dog':Dog,'Cat':Cat}, ignore_index=True)Output: Dog Cat0 happy sad
Write Data to BigQuery table using load_table_from_dataframe method ERROR - 'str' object has no attribute 'to_api_repr' I am trying to read the data from Cloud storage and write the data into BigQuery table. Used Pandas library for reading the data from GCS and to write the data used client.load_table_from_dataframe me...
Basically Panda consider string as object, but BigQuery doesn't know it. We need to explicitly convert the object to string using Panda in order to make it load the data to BQ table.df[columnname] = df[columnname].astype(str)
Python tracemalloc's "compare_to" function delivers always "StatisticDiff" objects with len(traceback)=1 Using Python's 3.5 tracemalloc module as followstracemalloc.start(25) # (I also tried PYTHONTRACEMALLOC=25)snapshot_start = tracemalloc.take_snapshot()... # my code is runningsnapshot_stop = tracemalloc.take_snaps...
You need to use 'traceback' instead of 'lineno' when calling compare_to() to get more than one line.BTW, I also answered a similar question here with a little more detail.
Filter objects manyTomany with users manyTomany I want to filter the model Foo by its manyTomany field bar with users bar.Modelsclass User(models.Model): bar = models.ManyToManyField("Bar", verbose_name=_("Bar"), blank=True)class Foo(models.Model): bar = models.ManyToManyField("Bar", ver...
foos = Foo.objects.filter(bar__in=user.bar.all())
Not able to align specific patterns side by side in this grid So I tried different methods to do this like:a = ("+ " + "- "*4)b = ("|\n"*4)print(a + a + "\n" + b + a + a + "\n" + b + a + a)But the basic problem I am facing is how to print the vertical pattern on the sixth column i.e in the middle as well as, at the l...
I got it actually and thought of posting the solution I might help others:we ought to make use of the do_twice and do_four function:def draw_grid_art(): a = "+ - - - - + - - - - +" def do_twice(f): f() f() def do_four(f): do_twice(f) do_twice(f) def vertical(): b = "| | |" ...
How to remove rows that contains a repeating number pandas python I have a dataframe like:'a' 'b' 'c' 'd' 0 1 2 3 3 3 4 5 9 8 8 8and I want to remove rows that have a number that repeats more than once. So the answer is :'a' 'b' 'c' 'd' 0 1 2 3Thanks.
Use DataFrame.nunique with compare length of columns ad filter by boolean indexing:df = df[df.nunique(axis=1) == len(df.columns)]print (df) 'a' 'b' 'c' 'd'0 0 1 2 3
Slowly updating global window side inputs In Python I try to get the updating sideinputs working in python as stated in the Documentation (there is only a java example provided) [https://beam.apache.org/documentation/patterns/side-inputs/]I already found this thread here on Stackoverflow: [https://stackoverflow.com/que...
The reason why all of the elements from PeriodicImpulse are emitted at the same time is because of the parameters you use when creating the transform. The documentation of the transform states that the arguments start_timestamp and stop_timestamp are timestamps, and (despite the documentation not stating that), interva...
StaleElementReferenceException while looping over list I'm trying to make a webscraper for this website. The idea is that code iterates over all institutions by selecting the institution's name (3B-Wonen at first instance), closes the pop-up screen, clicks the download button, and does it all again for all items in the...
This code worked for me. But I am not doing driver.find_element_by_id("utils-export-spreadsheet").click()from selenium import webdriverimport timefrom selenium.webdriver.common.action_chains import ActionChainsdriver = webdriver.Chrome(executable_path="path")driver.maximize_window()driver.implicitly...
SQLite|Pandas|Python: Select rows that contain values in any column? I have an SQLite table with 13500 rows with the following SQL schema:PRAGMA foreign_keys = false;-- ------------------------------ Table structure for numbers-- ----------------------------DROP TABLE IF EXISTS "numbers";CREATE TABLE "nu...
Here's an SQLite query that will give you the results you want. It creates a CTE of all the values of interest, then joins your numbers table to the CTE if any of the columns contain the value from the CTE, selecting only RowId values from numbers where the number of rows in the join is exactly 3 (using GROUP BY and HA...
How to configure logging with colour, format etc in separate setting file in python? I am trying to call python script from bash script.(Note: I am using python version 3.7)Following is the Directory structure (so_test is a directory)so_test shell_script_to_call_py.sh main_file.py log_settings.pyfiles are as below,s...
I got the code working with the following changes:Declare 'log' variable outside the function in log_settings.py, so that it can be imported by other programs.Rename the function named log_config to log_conf, which is referred in the main program.In the main program, update the import statements to import 'log' and 'lo...
How to slice Data frame with Pandas, and operate on each slice I'm new into pandas and python in general and I want to know your opinion about the best way to create a new data frame using slices of an "original" data frame.input (original df): date author_id time_spent 0 2020-01-02 1 ...
What we will dodf = df.groupby(['date','author_id'])['time_spent'].sum().reset_index() date author_id time_spent0 2020-01-01 1 3.01 2020-01-01 2 3.02 2020-01-01 3 3.53 2020-01-02 1 4.04 2020-01-02 2 0.5
Convert one-hot encoded data-frame columns into one column In the pandas data frame, the one-hot encoded vectors are present as columns, i.e:Rows A B C D E0 0 0 0 1 01 0 0 1 0 02 0 1 0 0 03 0 0 0 1 04 1 0 0 0 04 0 0 0 0 1How to convert these columns into one d...
Try with argmax#df=df.set_index('Rows')df['New']=df.values.argmax(1)+1dfOut[231]: A B C D E NewRows 0 0 0 0 1 0 41 0 0 1 0 0 32 0 1 0 0 0 23 0 0 0 1 0 44 1 0 0 0 0 14 0 0 0 0 1 5
Odoo 11 - Action Server Here is my code for a custom action declaration: <record id="scheduler_synchronization_update_school_and_grade" model="ir.cron"> <field name="name">Action automatisee ...</field> <field name="user_id" ref="base.user_root"/> <fiel...
You missed the state field in the cron definition. This is the "Action To Do" field. Try following: <record id="scheduler_synchronization_update_school_and_grade" model="ir.cron"> <field name="name">Action automatisee ...</field> <field name="user_id" ref="base.user_root"/> ...
Execute python script in Qlik Sense load script I am trying to run python script inside my load script in Qlik Sense app.I know that I need to put OverrideScriptSecurity=1 in Settings.iniI putExecute py lib://python/getSolution.py 100 'bla'; // 100 and 'bla' are parametersand I get no error in qlik sense, but script is...
I figure out what was wrong. For all others that would have similar problems:Problem is in space in path. If I move my script in c:\Windows\getSolution.py it work. I also need to change the python path to c:\Windows\py.exeso end script looks like:Execute c:\Windows\py.exe c:\Windows\getSolution.py 100 'bla';But I still...
openAI Gym NameError in Google Colaboratory I've just installed openAI gym on Google Colab, but when I try to run 'CartPole-v0' environment as explained here.Code:import gymenv = gym.make('CartPole-v0')for i_episode in range(20): observation = env.reset() for t in range(100): env.render() print(obse...
One way to render gym environment in google colab is to use pyvirtualdisplay and store rgb frame array while running environment. Environment frames can be animated using animation feature of matplotlib and HTML function used for Ipython display module.You can find the implementation here. Make sure you install require...
I need example on how to mention using PTB I need further elaboration on this thread How can I mention Telegram users without a username?Can someone give me an example of how to use the markdown style? I am also using PTB libraryThe code I want modifiedcontext.bot.send_message(chat_id=-1111111111, text="hi")
Alright, so I finally found the answer. The example below should work.context.bot.send_message(chat_id=update.effective_chat.id, parse_mode = ParseMode.MARKDOWN_V2, text = "[inline mention of a user](tg://user?id=123456789)")
Increasing distances among nodes in NetworkX I'm trying to create a network of approximately 6500 nodes for retweets. The shape of network looks so bad with a very low distance among node. I've tried spring_layout to increase the distances but it didn't change anything.nx.draw(G, with_labels=False, node_color=color_map...
I swapped "layout=..." with "pos=..." and it worked
Selenium not sending keys to input field I'm trying to scrape this url https://www.veikkaus.fi/fi/tulokset#!/tarkennettu-hakuThere's three main parts to the scrape:Select the correct game type from "Valitse peli" For this I want to choose "Eurojackpot"Set the date range from variables. In the full v...
For me, simply doing the following works:driver.find_element_by_css_selector('.date-input.from-date').send_keys(from_date)ActionChains(driver).send_keys(Keys.RETURN).perform()driver.find_element_by_css_selector('.date-input.to-date').send_keys(to_date)ActionChains(driver).send_keys(Keys.RETURN).perform()
Python Multiple Datetimes To One I have two types of datetime format in a Dataframe.Date2019-01-06 00:00:00 (%Y-%d-%m %H:%M:%S')07/17/2018 ('%m/%d/%Y')I want to convert into one specific datetime format. Below is the script that I am usingd1 = pd.to_datetime(df1['DATE'], format='%m/%d/%Y',errors='coerce')d2 = pd.to_da...
If there are mixed format also in format 2019-01-06 00:00:00 - it means it should be January or June, only ways is prioritize one format - e.g. here first months and add first format d2 and then d3 in chained fillna:d1 = pd.to_datetime(df1['DATE'], format='%m/%d/%Y',errors='coerce')d2 = pd.to_datetime(df1['DATE'], for...
pandas change all rows with Type X if 1 Type X Result = 1 Here is a simple pandas df:>>> df Type Var1 Result0 A 1 NaN1 A 2 NaN2 A 3 NaN3 B 4 NaN4 B 5 NaN5 B 6 NaN6 C 1 NaN7 C 2 NaN8 C 3 NaN9 D ...
Create boolean mask and for True/False to 1/0 mapp convert values to integers:df['Result'] = df['Type'].isin(df.loc[df['Var1'].eq(3), 'Type']).astype(int)#alternativedf['Result'] = np.where(df['Type'].isin(df.loc[df['Var1'].eq(3), 'Type']), 1, 0)print (df) Type Var1 Result0 A 1 11 A 2 12...
Referencing folder without absolute path I am writing a code that will be implemented alongside my company's software. My code is written in Python and requires access to a data file (.ini format) that will be stored on the user's desktop, inside the software's shortcuts folder.This being said, I want to be able to rea...
In windows, desktop absolute path looks like this:%systemdrive%\users\%username%\DesktopSo this path will fit your requirements:%systemdrive%\users\%username%\Desktop\Parameters\ParameterUpdate.iniPlease make sure u don't actually mean public desktop path, with will be:%public%\Desktop\Parameters\ParameterUpdate.ini
Subscription modelling in Flask SQLAlchemy I am trying to model the following scenario in Flask SQLAlchemy:There are a list of SubscriptionPacks available for purchase. When a particular User buys a SubscriptionPack they start an instance of that Subscription.The model is as follows:A User can have many Subscriptions (...
For those who stumble upon this, what I was looking for was the bidirectional SQLAlchemy Association Object pattern.This allows the intermediate table of a Many-to-Many to have it's own stored details. In my instance above the Subscription table needed to be an Association Object (has it's own class).
Append information to failed tests I have some details I have to print out for a failed test. Right now I'm just outputting this information to STDOUT and I use the -s to see this information. But I would like to append this information to the test case details when it failed, and not need to use the -s option.
You can just keep printing to stdout and simply not use -s. If you do this py.test will put the details you printed next to the assertion failure message when the test fails, in a "captured stdout" section.When using -s things get worse since they are also printed to stdout even if the test passes and it also displays...
Install Numpy Requirement in a Dockerfile. Results in error I am attempting to install a numpy dependancy inside a docker container. (My code heavily uses it). On building the container the numpy library simply does not install and the build fails. This is on OS raspbian-buster/stretch. This does however work when buil...
To use Numpy on python3 here, we first head over to the official documentation to find what dependencies are required to build Numpy.Mainly these 5 packages + their dependencies must be installed:Python3 - 70 mbPython3-dev - 25 mbgfortran - 20 mbgcc - 70 mbmusl-dev -10 mb (used for tracking unexpected behaviour/debuggi...
Python program can not import dot parser I am trying to run a huge evolution simulating python software from the command line. The software is dependent on the following python packages:1-networkX 2-pyparsing3-numpy4-pydot 5-matplotlib6-graphvizThe error I get is this:Couldn't import dot_parser, loading of dot files wi...
Any particular reason you're not using the newest version of pydot?This revision of 1.0.2 looks like it fixes exactly that problem:https://code.google.com/p/pydot/source/diff?spec=svn10&r=10&format=side&path=/trunk/pydot.pySee line 722.
How to extract specific time period from Alpha Vantage in Python? outputsize='compact' is giving last 100 days, and outputsize='full' is giving whole history which is too much data. Any idea how to write a code that extract some specific period? ts=TimeSeries(key='KEY', output_format='pandas')data, meta_data = ts.get_d...
This is how I was able to get the dates to workts = TimeSeries (key=api_key, output_format = "pandas")data_daily, meta_data = ts.get_daily_adjusted(symbol=stock_ticker, outputsize ='full')start_date = datetime.datetime(2000, 1, 1)end_date = datetime.datetime(2019, 12, 31) # Create a filtered dataframe, and...
How do I get hundreds of DLL files? I am using python and I am trying to install the GDAL library. I kept having an error telling me that many DLL files were missing so I used the software Dependency Walker and it showed me that 330 DLL files were missing...My question is: How do I get that much files without downloadi...
First of all, never download .dll files from shady websites.The best way of repairing missing dependencies is to reinstall the software that shipped the .dll files completely.
How to change the performance metric from accuracy to precision, recall and other metrics in the code below? As a beginner in scikit-learn, and trying to classify the iris dataset, I'm having problems with adjusting the scoring metric from scoring='accuracy' to others like precision, recall, f1 etc., in the cross-valid...
1) I guess the above is happening because 'precision' and 'recall' are defined in scikit-learn only for binary classification-is that correct?No. Precision & recall are certainly valid for multi-class problems, too - see the docs for precision & recall. If yes, then, which command(s) should replace scoring='...
Cannot find django.views.generic . Where is generic. Looked in all folders for the file I know this is a strange question but I am lost on what to do. i cloned pinry... It is working and up . I am trying to find django.views.generic. I have searched the directory in my text editor, I have looked in django.views. But I ...
Try running this from a Python interpreter: >>> import django.views.generic>>> django.views.generic.__file__This will show you the location of the gerneric as a string path. In my case the output is:'/.../python3.5/site-packages/django/views/generic/__init__.py'If you look at this __init__.py you will...
Django- limit_choices_to using 2 different tables I fear that what I am trying to do might be impossible but here we go:Among my models, I have the followingClass ParentCategory(models.Model): name = models.CharField(max_length=128) def __unicode__(self): return self.name Class Category(models.Model): ...
Maybe this will work:limit_choices_to={'parentCategory__name': 'comp method'}
How to reduce the retry count for kubernetes cluster in kubernetes-client-python I need to reduce the retry count for unavailable/deleted kubernetes cluster using kubernetes-client-python, currently by default it is 3.WARNING Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connectio...
Sadly it seems that it's not possible because:Python client use urlib3 PoolManager to make requests as you can see there https://github.com/kubernetes-client/python/blob/master/kubernetes/client/rest.py#L162r = self.pool_manager.request(method, url, body=request_body, ...
Sum value by group by and cumulatively add to separate list or numpy array cumulatively and use the last value in conditional statement I want to sum the values for multi-level index pandas dataframe. I would then like to add this value to another value in a cumulative fashion. I would then like to use a conditional st...
Let's change balance to a pd.Series:balance = pd.Series([20000])Your code#change this linedf['BET'] = np.where(df.groupby(level = 0)['LIABILITY'].transform('sum') < 0.75*balance.values.tolist()[-1], df['POT_BET'], 0)Your codebalance = pd.concat([balance, results]).cumsum().tolist()Output:[20000.0, 20023.872099225347...
Questions Tags Users Unanswered shifting specific column to before/after specific column in dataframe In dataframe example : medcine_preg_oth medcine_preg_oth1 medcine_preg_oth2 medcine_preg_oth30 Berplex Berplex None None1 NaN NaN N...
You can re-arrange your columns like this:re_ordered_columns = ['medicine_pred_oth','medcine_preg_oth1','medcine_preg_oth2','medcine_preg_oth3']df = df[re_ordered_columns+df.columns.difference(re_ordered_columns).tolist()]add the remaining columns in place of ...
padding a batch with 0 vectors in dynamic rnn I have a prediction task working with variable sequences of input data. Directly using a dynamic rnn will run into the trouble of splitting the outputs according to this post:Using a variable for num_splits for tf.split()So, I am wondering if is it possible to pad an entire...
These days (2022) two methods you can use to pad sequences in tensorflow are using a tf.data.Dataset pipeline, or preprocessing with tf.keras.utils.pad_sequences.Method 1: Use Tensorflow Pipelines (tf.data.Dataset)The padded_batch() method can be used in place of a normal batch() method to pad the elements of a tf.data...
Login to a website then open it in browser I am trying to write a Python 3 code that logins in to a website and then opens it in a web browser to be able to take a screenshot of it.Looking online I found that I could do webbrowser.open('example.com')This opens the website, but cannot login.Then I found that it is possi...
Have you considered Selenium? It drives a browser natively as a user would, and its Python client is pretty easy to use. Here is one of my latest works with Selenium. It is a script to scrape multiple pages from a certain website and save their data into a csv file:import osimport timeimport csvfrom selenium import web...
scrapy callback doesnt work in function When executing the first yield it will not go into the function parse_url and when executing the second yield it will not go back the function parse and it just end. During the whole process, there are no exceptions. I don't know how to deal with this problem, I need help.import ...
If you carefully looked at the logs then you might have noticed that scrapy filtered offsite domain requests. This means when scrapy tried to ping short.58.com and jxjump.58.com, it did not follow through. You can add those domains to the allowed_domains filter in your Spider class and you will see the requests being s...
Splitting HTML text by while using beautifulsoup HTML code:<td> <label class="identifier">Speed (avg./max):</label> </td> <td class="value"> <span class="block">4.5 kn<br>7.1 kn</span> </td>I need to get values 4.5 kn and 7.1 as separate list items so I could appen...
Locate the "Speed (avg./max)" label first and then go to the value via .find_next():from bs4 import BeautifulSoup data = '<td> <label class="identifier">Speed (avg./max):</label> </td> <td class="value"> <span class="block">4.5 kn<br>7.1 kn</span> </td>'soup = Bea...
Repeating if statement I am having a problem with my code mapping a random walk in 3D space. The purpose of this code is to simulate N steps of a random walk in 3 dimensions. At each step, a random direction is chosen (north, south, east, west, up, down) and a step of size 1 is taken in that direction. Here is my code:...
If you remove the multiple n = random.random() from within the if statements and replace by a single n = random.random() at start of the while loop then there will be only one step per loop.
Trying to create and use a class; name 'is_empty' is not defined I'm trying to create a class called Stack (it's probably not very useful for writing actual programmes, I'm just doing it to learn about creating classes in general) and this is my code, identical to the example in the guide I'm following save for one fun...
The method is_empty() is part of the class. To call it you need to my_stack.is_empty()
How to control if a component exists in a Tk object/window? I would like to know what is the most effecient way to control if a certain component (label, button or entry) exists already on the Tk object/window.I have searched on the web for a while and the only thing I found is:if component.winfo_exists(): # But this d...
I think your second approach is good enough.self.label = None # Initialize `self.label` as None somewhere....if not self.label: self.label = Label(self, text="Label")This will work, because before the label creation, self.label is evaluated as false when used as predicate (bool(None) is False), and will be evaluat...
How to determine the version of PyJWT? I have two different software environments (Environment A and Environment B) and I'm trying to run PyJWT on both environments. It is working perfectly fine on one environment Environment A but fail on Environment B. The error I'm getting on Environment B when I call jwt.encode() w...
The PyJWT .__version__ attribute appeared in 0.2.2 in this commit.Generally, to find the version of the package, that was installed via setuptools, you need to run following code:import pkg_resourcesprint pkg_resources.require("jwt")[0].versionIf pip was used to install the package, you could try from linux shell:pip s...
Setting up proxy with selenium / python I am using selenium with python.I need to configure a proxy.It is working for HTTP but not for HTTPS.The code I am using is:# configure firefoxprofile = webdriver.FirefoxProfile()profile.set_preference("network.proxy.type", 1)profile.set_preference("network.proxy.http", '11.111.1...
Check out browsermob proxy for setting up a proxies for use with seleniumfrom browsermobproxy import Serverserver = Server("path/to/browsermob-proxy")server.start()proxy = server.create_proxy()from selenium import webdriverprofile = webdriver.FirefoxProfile()profile.set_proxy(proxy.selenium_proxy())driver = webdriver....
link in html do not function python 2.7 DJANGO 1.11.14 win7when I click the link in FWinstance_list_applied_user.html it was supposed to jump to FW_detail.html but nothing happenedurl.pyurlpatterns += [ url(r'^myFWs/', views.LoanedFWsByUserListView.as_view(), name='my-applied'), url(r'^myFWs/(?P<pk>[0-9...
You haven't terminated your "my-applied" URL pattern, so it matches everything beginning with "myFWs/" - including things that that would match the detail URL. Make sure you always use a terminating $ with regex URLs.url(r'^myFWs/$', views.LoanedFWsByUserListView.as_view(), name='my-applied'),
Allow_Other with fusepy? I have a 16.04 ubuntu server with b2_fuse mounting my b2 cloud storage bucket which uses pyfuse. The problem is, I have no idea how I can pass the allow_other argument like with FUSE! This is an issue because other services running under different users cannot see the mounted drive.Does anybo...
Inside of file b2fuse.py if you change the line:FUSE(filesystem, mountpoint, nothreads=True, foreground=True)toFUSE(filesystem, mountpoint, nothreads=True, foreground=True,**{'allow_other': True})the volume will be mounted with allow_other.
Python3 + vagrant ubuntu 16.04 + ssl request = [Errno 104] Connection reset by peer I'm using on my Mac Vagrant with "bento/ubuntu-16.04" box. I'm trying to use Google Adwords Api via python library but got error [Errno 104] Connection reset by peerI make sample script to check possibility to send requests:import urlli...
I found solution. It looks like bug in Virtualbox 5.1.8 version. You can read about it hereSo, you can fix it by downgrade Virtualbox to < 5.1.6
While loop causing issues with CSV read Everything was going fine until I tried to combine a while loop with a CSV read and I am just unsure where to go with this.The code that I am struggling with:airport = input('Please input the airport ICAO code: ')with open('airport-codes.csv', encoding='Latin-1') as f: reader ...
I had a different suggestion using functions:import csvdef findAirportCode(airport): with open('airport-codes.csv', encoding='Latin-1') as f: reader = csv.reader(f, delimiter=',') for row in reader: if airport.lower() == row[0].lower(): airportCode = row[2] + "/" + row...
Getting next Timestamp Value What is the proper solution in pandas to get the next timestamp value?I have the following timestamp:Timestamp('2017-11-01 00:00:00', freq='MS')I want to get this as the result for the next timestamp value:Timestamp('2017-12-01 00:00:00', freq='MS')Edit:I am working with multiple frequencie...
General solution is convert strings to offset and add to timestamp:L = ['1min', '5min', '15min', '60min', 'D', 'W-SUN', 'MS']t = pd.Timestamp('2017-11-01 00:00:00', freq='MS')t1 = [t + pd.tseries.frequencies.to_offset(x) for x in L]print (t1)[Timestamp('2017-11-01 00:01:00', freq='MS'), Timestamp('2017-11-01 00:05:00'...
Django 1.10 Count on Models ForeignKey I guess this must be simple, but I've been trying for hours and can't find anything to help.I have 2 models. One for a Template Categories and another for a TemplateI'm listing the Template Categories on the Homepage and for each Category I want to show how many templates have tha...
Views.pyfrom django.shortcuts import HttpResponsefrom django.shortcuts import render, get_object_or_404from django.db.models import Countfrom .models import TemplateTypefrom .models import TemplateFiledef home(request): queryset = TemplateType.objects.order_by('type_title').annotate(num_file=Count('file_count')) ...
Internal Error 500 when using Flask and Apache I am working on a small college project using Raspberry Pi. Basically, the project is to provide an html interface to control a sensor attached to the Pi. I wrote a very simple Python code attached with a very basic html code also. Everything is done in this path /var/www/...
The problem was in led.conf. The user needs to be pi.<virtualhost *:80> ServerName 10.0.0.146 WSGIDaemonProcess led user=pi group=www-data threads=5 home=/var/www/NewTest/ WSGIScriptAlias / /var/www/NewTest/led.wsgi <directory /var/www/NewTest> WSGIProcessGroup led WSGIApplicationG...
lmdb no locks available error I have a data.mdb and lock.mdb file in test/ directory. I was trying to use the python lmdb package to read/write data from the lmdb database. I triedimport lmdbenv = lmdb.open('test', map_size=(1024**3), readonly=True)but got the following error:lmdb.Error: test: No locks availableThen ...
Use the -r option in mdb_stat to check the number of readers in the reader lock table. You may be hitting the max limit for number of readers. You can try setting this limit to a higher number.
Neural networks pytorch I am very new in pytorch and implementing my own network of image classifier. However I see for each epoch training accuracy is very good but validation accuracy is 0.i noted till 5th epoch. I am using Adam optimizer and have learning rate .001. also resampling the whole data set after each epoc...
I think you did not take into account that acc += torch.sum(predClass == labels.data) returns a tensor instead of a float value. Depending on the version of pytorch you are using I think you should change it to:acc += torch.sum(predClass == labels.data).cpu().data[0] #pytorch 0.3acc += torch.sum(predClass == labels.dat...
How to feed weights into igraph community detection [Python/C/R] When using commuinity_leading_eigenvector of igraph, assuming a graph g has already been created, how do I pass the list of weights of graph g to community_leading_eigenvector? community_leading_eigenvector(clusters=None, weights=None, arpack_options=No...
You can either pass the name of the attribute containing the weights to the weights parameter, or retrieve all the weights into a list using g.es["weight"] and then pass that to the weights parameter. So, either of these would suffice, assuming that your weights are in the weight edge attribute:g.community_leading_eige...
Aggregation fails when using lambdas I'm trying to port parts of my application from pandas to dask and I hit a roadblock when using a lamdba function in a groupby on a dask DataFrame.import dask.dataframe as dddask_df = dd.from_pandas(pandasDataFrame, npartitions=2)dask_df = dask_df.groupby( ['o...
From the Dask docs:"Dask supports Pandas’ aggregate syntax to run multiple reductions on the same groups. Common reductions such as max, sum, list and mean are directly supported.Dask also supports user defined reductions. To ensure proper performance, the reduction has to be formulated in terms of three independe...
how to convert pandas series to tuple of index and value I'm looking for an efficient way to convert a series to a tuple of its index with its values.s = pd.Series([1, 2, 3], ['a', 'b', 'c'])I want an array, list, series, some iterable:[(1, 'a'), (2, 'b'), (3, 'c')]
Well it seems simply zip(s,s.index) works too!For Python-3.x, we need to wrap it with list -list(zip(s,s.index))To get a tuple of tuples, use tuple() : tuple(zip(s,s.index)).Sample run -In [8]: sOut[8]: a 1b 2c 3dtype: int64In [9]: list(zip(s,s.index))Out[9]: [(1, 'a'), (2, 'b'), (3, 'c')]In [10]: tuple(zip(s,...
Python Kivy: Add Background loop I want to paste a background loop into my Python-Kivy script. The problem is, that I've got only a App().run() under my script. So, if I put a loop, somewhere in the the App-Class, the whole App stopps updating and checking for events. Is there a function name like build(self), that's r...
In case you need to schedule a repeated activity in a loop, you can use Clock.schedule_interval() to call a function on a regular schedule:def my_repeated_function(data): print ("My function called.")Clock.schedule_interval(my_repeated_function, 1.0 / 30) # no brackets on function reference ...
How to learn multi-class multi-output CNN with TensorFlow I want to train a convolutional neural network with TensorFlow to do multi-output multi-class classification.For example: If we take the MNIST sample set and always combine two random images two a single one and then want to classify the resulting image. The res...
For nomenclature of classification problems, you can have a look at this link:http://scikit-learn.org/stable/modules/multiclass.htmlSo your problem is called "Multilabel Classification". In normal TensorFlow multiclass classification (classic MNIST) you will have 10 output units and you will use softmax at the end for ...
Using Tweepy to determine the age on an account I'm looking to use Tweepy for a small project. I'd like to be able to write a bit of code that returns the age of a given Twitter account. The best way I can think of to do this is to return all Tweets from the very first page, find the earliest Tweet and check the date/t...
The get_user method returns a user object that includes a created_at field.Check https://dev.twitter.com/overview/api/users
how to remove /n and comma while extracting using response.css I am trying to crawl amazon to get product name, price and [savings information]. i am using response.css to extract [saving information] as belowpython code to extract [savings information]:savingsinfo = amzscrape.css(".a-color-secondary .a-row , .a-row.a-...
output = ''.join(savingsinfo['savingsinfo_item'])
BeautifulSoup not defined when called in function My web scraper is throwing NameError: name 'BeautifulSoup' is not defined when I call BeautifulSoup() inside my function, but it works normally when I call it outside the function and pass the Soup as an argument. Here is the working code:from teams.models import *from ...
I guess you are doing some spelling mistake of BeautifulSoup, its case sensitive. if not, use requests in your code as:from teams.models import *from bs4 import BeautifulSoupfrom django.conf import settingsimport requests, os, stringdef scrapeTeamPage(url): res = requests.get(url) soup = BeautifulSoup(res.content...
Missing parameters when creating new table in Google BigQuery through Python API V2 I'm trying to create new table using BigQuery's Python API:bigquery.tables().insert( projectId="xxxxxxxxxxxxxx", datasetId="xxxxxxxxxxxxxx", body='{ "tableReference": { "projectId":"xxxxxxxxxxxxxx", ...
The only required parameter for a tables.insert is the tableReference, which must have tableId, datasetId, and projectId fields. I think the actual issue may be that you're passing the JSON string when you could just pass a dict with the values. For instance, the following code works to create a table (note the dataset...
Loop does not iterate over all data I have code that produces the following df as output: year month day category keywords0 '2021' '09' '06' 'us' ['afghan, refugees, volunteers']1 '2021' '09' '...
I think the problem is that with:for p in df.loc[i, 'keywords']:you are iterating over the letters in the first entry. So you will stop at that count.This should work for you:for teststr in df['keywords']: splitstr = teststr.split() for p1 in splitstr: dict_1 = {'word': p1} df1.loc[len(df1)] = dict_...
How use asyncio with pyqt6? qasync doesn't support pyqt6 yet and I'm trying to run discord.py in the same loop as pyqt but so far I'm not doing the best. I've tried multiprocess, multithread, and even running synchronous code from non-synchronous code but I either end up with blocking code that makes the pyqt program n...
qasync does not currently support PyQt6 but I have created a PR that implements it.At the moment you can install my version of qasync using the following command:pip install git+https://github.com/eyllanesc/qasync.git@PyQt6Probably in future releases my PR will be accepted so there will already be support for PyQt6 The...
Used IDs are not available anymore in Selenium Python I am using Python and Selenium to scrape some data out of an website. This website has the following structure:First group item has the following base ID: frmGroupList_Label_GroupName and then you add _2 or _3 at the end of this base ID to get the 2nd/3rd group's I...
As the saying goes... it ain't stupid, if it works.def refresh(): # accessing the groups page url = "https://google.com" browser.get(url) time.sleep(5) url = "https://my_url.com" browser.get(url) time.sleep(5)While trying to debug this, and finding a solution, I thought: "w...
Finding an unfilled circle in an image of finite size using Python Trying to find a circle in an image that has finite radius. Started off using 'HoughCircles' method from OpenCV as the parameters for it seemed very much related to my situation. But it is failing to find it. Looks like the image may need more pre-proce...
simple, draw your circles: cv2.HoughCircles returns a list of circles..take care of maxRadius = 100for i in circles[0,:]: # draw the outer circle cv2.circle(image,(i[0],i[1]),i[2],(255,255,0),2) # draw the center of the circle cv2.circle(image,(i[0],i[1]),2,(255,0,255),3)a full working code (you have to ch...
How to Plot Time Stamps HH:MM on Python Matplotlib "Clock" Polar Plot I am trying to plot mammalian feeding data on time points on a polar plot. In the example below, there is only one day, but each day will eventually be plotted on the same graph (via different axes). I currently have all of the aesthetics worked out,...
import numpy as npfrom matplotlib import pyplot as pltimport datetimedf = pd.DataFrame({'Day': {0: '5/22', 1: '5/22', 2: '5/22', 3: '5/22', 4: '5/22'}, 'Time': {0: '16:15', 1: '19:50', 2: '20:15', 3: '21:00', 4: '23:30'}, 'Feeding_Quality': {0: 'G', 1: 'G', 2: 'G', 3: 'F', 4: 'G'}, ...
How to fix 'else' outputting more than 1 outcome Very basic problem, trying to output if a number is divisible by 3/5/both/none but else will return 2 statements when they are not true. How do I fix this?I've tried to move where the else is indented, first time it wouldn't output for the numbers that are not multiples ...
If you incorporate all the comment suggestions so far you get something like this:while True: z = input("Please enter a number- to end the program enter z as -1 ") # cast to int z = int(z) # break early if z == -1: break elif z % 3 == 0 and z % 5 == 0: print("Your number is a multiple of...
pytest will not run the test files in subdirectories I am new to pytest and trying to run a simple test to check if pytest works. I'm using windows 10, python 3.8.5 and pytest 6.0.1.Here is my project directory:projects/ tests/ __init__.py test_sample.pyHere is what I put in test_sample.py:def func(x): re...
The "best practices" approach to configuring a project with pytest is using a config file. The simplest solution is a pytest.ini that looks like this:# pytest.ini[pytest]testpaths = testsThis configures the testpaths relative to your rootdir (pytest will tell you what both paths are whenever you run it). This...
Updating R that is used within IPython/ Jupyter I wanted to use R within Jupyter Notebook so I installed via R Essentials (see: https://www.continuum.io/blog/developer/jupyter-and-conda-r). The version that got installed is the following:R.Version()Out[2]:$platform"x86_64-w64-mingw32"$arch"x86_64"$os"mingw32"$system"x8...
If you want to stay with conda packages, try conda update --all, but I think there are still no R 3.2.x packages for windows.You can also install R via the binary installer available at r-project.org, install the R kernel manually; e.g. via install_github("irkernel/repr")install_github("irkernel/IRdisplay")install_gith...
How to find orphan process's pid How can I find child process pid after the parent process died.I have program that creates child process that continues running after it (the parent) terminates.i.e.,I run a program from python script (PID = 2).The script calls program P (PID = 3, PPID = 2)P calls fork(), and now I have...
The information is lost when a process-in-the-middle terminates. So in your situation there is no way to find this out.You can, of course, invent your own infrastructure to store this information at forking time. The middle process (PID 3 in your example) can of course save the information which child PIDs it created...
"Threading" in Python, plotting received data and sending simultaneously I am asking for some high level advice here. I am using Python to plot data that is received constantly through serial. At the same time, I want the user to be able to input data through a prompt (such as the Python shell). That data will then...
Disclaimer: I don't think that the following is good practice.You can put the execution of the wx stuff inside a separate thread.app = wx.App()window = DataLoggerWindow()import threadingclass WindowThread(threading.Thread): def run(self): window.Show() app.MainLoop()WindowThread().start()That way, the ...
building dictionary to be JSON encoded - python I have a list of class objects. Each object needs to be added to a dictionary so that it can be json encoded. I've already determined that I will need to use the json library and dump method. The objects look like this:class Metro: def __init__(self, code, name, countr...
dict comprehension will not be very complicated.import jsonlist_of_metros = [Metro(...), Metro(...)]fields = ('code', 'name', 'country', 'continent', 'timezone', 'coordinates', 'population', 'region',)d = { 'metros': [ {f:getattr(metro, f) for f in fields} for metro in list_of_metros ]}json...
Tensorflow: building graph with batch sizes varying in dimension 1? I'm trying to build a CNN model in Tensorflow where all the inputs within a batch are equal shape, but between batches the inputs vary in dimension 1 (i.e. minibatch sizes are the same but minibatch shapes are not). To make this clearer, I have data (N...
There is no way to do this, as you want to use a differently shaped matrix (for fully-connected layer) for every distinct batch. One possible solution is to use global average pooling (along all spatial dimensions) to get a tensor of shape (batch_size, 1, 1, NUM_CHANNELS) regardless of the second dimension.
How can I find out if a file-like object performs newline translation? I have a library that does some kind of binary search in a seekable open file that it receives as an argument.The file must have been opened with open(..., newline="\n"), otherwise .seek() and .tell() might not work properly if there's newline trans...
I see two ways around this. One is Python 3.7's io.TextIOWrapper.reconfigure() (thanks @martineau!).The second one is to make some tests to see whether seek/tell work as expected. A simple but inefficient way to do it is this:from io import SEEK_ENDdef has_newlines_translated(f): f.seek(0) file_size_1 = len(f.rea...
Opencv - Ellipse Contour Not fitting correctly I want to draw contours around the concentric ellipses shown in the image appended below. I am not getting the expected result. I have tried the following steps:Read the Image Convert Image to Grayscale.Apply GaussianBlurGet the Canny edgesDraw the ellipse contourHere is t...
Algorithm can be simple:Convert RGB to HSV, split and working with a V channel.Threshold for delete all color lines.HoughLinesP for delete non color lines.dilate + erosion for close holes in ellipses.findContours + fitEllipse.Result:With new image (added black curve) my approach do not works. It seems that you need to ...
How can I delete stopwords from a column in a df? I've been trying to delete the stopwords from a column in a df, but I'm having trouble doing it.discografia["SSW"] = [word for word in discografia.CANCIONES if not word in stopwords.words('spanish')]But in the new column I just get the same words as in the col...
We can use explode in conjunction with grouping by the original index to assign back to the original DataFrame.stopwords = ["buzz"]df = pd.DataFrame({"CANCIONES": [["fizz", "buzz", "foo"], ["baz", "buzz"]]})words = r".|".join(stopwords)expl...
Running interactive python script from emacs I am a fairly proficient vim user, but friends of mine told me so much good stuff about emacs that I decided to give it a try -- especially after finding about the aptly-named evil mode...Anyways, I am currently working on a python script that requires user input (a subclass...
I don't know about canonical, but if I needed to interact with a script I'd do M-xshellRET and run the script from there.There's also M-xterminal-emulator for more serious terminal emulation, not just shell stuff.
How can I print the entire converted sentence on a single line? I am trying to expand on Codeacademy's Pig Latin converter to practice basic programming concepts. I believe I have the logic nearly right (I'm sure it's not as concise as it could be!) and now I am trying to output the converted Pig Latin sentence entered...
Try:pyg = 'ay'print ("Welcome to Matt's Pig Latin Converter!")def convert(original): while True: if len(original) > 0 and (original.isalpha() or " " in original): final_sentence = "" print "You entered \"%s\"." % original split_list = original.split() for word in...
How to use if statments on Tags in Beautiful Soup? I'm a beginner using Beautiful Soup and I have a question to do with 'if' statements.I am trying to scrap data from tables from a webpage but there are pro-ceding and post-ceding tables too.All the required tables have divisions with the form , while the useless tables...
This would get you what you are looking for I believe.for result in results: if 'align="center"' in str(result.contents[0]): #append to some list
How to click HTML button in Python + Selenium I am trying to simulate button click in Python using Selenium. <li class="next" role="button" aria-disabled="false"><a href="www.abc.com">Next →</a></li>The Python script is driver.find_element_by_class_name('next').click().This gives an error. Can ...
You can try the following code:from selenium.webdriver.support import uifrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.common.by import Byui.WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".next[role='button']"))).click()Hope it helps you!
Algorithm for grouping points in given distance I'm currently searching for an efficient algorithm that takes in a set of points from three dimensional spaces and groups them into classes (maybe represented by a list). A point should belong to a class if it is close to one or more other points from the class. Two class...
What I ended up doingAfter following all the suggestions of your comments, help from cs.stackexchange and doing some research I was able to write down two different methods for solving this problem. In case someone might be interested, I decided to share them here. Again, the problem is to write a program that takes in...
Please help. I get this error: "SyntaxError: Unexpected EOF while parsing" try: f1=int(input("enter first digit")) f2=int(input("enter second digit")) answ=(f1/f2) print (answ)except ZeroDivisionError:
You can't have an except line with nothing after it. You have to have some code there, even if it doesn't do anything.try: f1=int(input("enter first digit")) f2=int(input("enter second digit")) answ=(f1/f2) print (answ)except ZeroDivisionError: pass
what is the role of magic method in python? Base on my understanding, magic methods such as __str__ , __next__, __setattr__ are built-in features in Python. They will automatically called when a instance object is created. It also plays a role of overridden. What else some important features of magic method do I omit o...
"magic" methods in python do specific things in specific contexts.For example, to "override" the addition operator (+), you'd define a __add__ method. subtraction is __sub__, etc.Other methods are called during object creation (__new__, __init__). Other methods are used with specific language constructs (__enter__, _...
Persisting test data across apps My Django site has two apps — Authors and Books. My Books app has a model which has a foreign key to a model in Authors. I have some tests for the Authors app which tests all my models and managers and this works fine. However, my app Books require some data from the Authors app in orde...
Create a fixture containing the test data you need. You can then load the same data for both your Authors and Books tests.For details, see docs on Testcase.fixures and Introduction to Python/Django tests: Fixtures.
loop through numpy arrays, plot all arrays to single figure (matplotlib) the functions below each plot a single numpy array plot1D, plot2D, and plot3D take arrays with 1, 2, and 3 columns, respectivelyimport numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3Ddef plot1D(data): x=np.ara...
To plot multiple data sets on the same axes, you can do something like this:def plot2D_list(data,*args,**kwargs): # type: (object) -> object #if 2d, make a scatter n = len(data) fig,ax = plt.subplots() #create figure and axes for i in range(n): #now plot data set i ax.plot(data[i][:,0], ...
remove arguments passed to chrome by selenium / chromedriver I'm using selenium with python and chromium / chromedriver. I want to REMOVE switches passed to chrome (e.g. --full-memory-crash-report), but so far I could only find out how to add further switches.My current setup:from selenium import webdriverdriver = webd...
It helped me:options = webdriver.ChromeOptions()options.add_experimental_option("excludeSwitches", ["test-type"])options.add_argument("--incognito")driver = webdriver.Chrome(options=options)Found solution here https://help.applitools.com/hc/en-us/articles/360007189411--Chrome-is-being-controlled-by-automated-test-softw...
importing from a text file to a dictionary filename:dictionary.txtYAHOO:YHOOGOOGLE INC:GOOGHarley-Davidson:HOGYamana Gold:AUYSotheby’s:BIDinBev:BUDcode:infile = open('dictionary.txt', 'r')content= infile.readlines()infile.close()counters ={}for line in content: counters.append(content) print(counters)i am...
First off, instead of opening and closing the files explicitly you can use with statement for opening the files which, closes the file automatically at the end of the block.Secondly, as the file objects are iterator-like objects (one shot iterable) you can loop over the lines and split them with : character. You can do...
Python Daemon: checking to have one daemon run at all times myalert.pyfrom daemon import Daemonimport os, time, sysclass alertDaemon(Daemon): def run(self): while True: time.sleep(1)if __name__ == "__main__": alert_pid = '/tmp/ex.pid' # if pid doesnt exists run if os.path.isfile(alert_pid)...
The python-daemon library, which is the reference implementation for PEP 3143: "Standard daemon process library", handles this by using a file lock (via the lockfile library) on the pid file you pass to the DaemonContext object. The underlying OS guarantees that the file lock will be released when the daemon process ex...
Where (at which point in the code) does pyAMF client accept SSL certificate? I've set up a server listening on an SSL port. I am able to connect to it and with proper credentials I am able to access the services (echo service in the example below)The code below works fine, but I don't understand at which point the clie...
PyAMF uses httplib under the hood to power the remoting requests. When connecting via https://, httplib.HTTPSConnection is used as the connection attribute to the RemotingService.It states in the docs that (in reference to HTTPSConnection): Note: This does not do any certificate verificationSo, in answer to your quest...
NameError: name 'self' is not defined Why such structureclass A: def __init__(self, a): self.a = a def p(self, b=self.a): print bgives an error NameError: name 'self' is not defined?
Default argument values are evaluated at function define-time, but self is an argument only available at function call time. Thus arguments in the argument list cannot refer each other.It's a common pattern to default an argument to None and add a test for that in code:def p(self, b=None): if b is None: b = s...
How to send post requests using multi threading in python? I'm trying to use multi threading to send post requests with tokens from a txt file.I only managed to send GET requests,if i try to send post requests it results in a error.I tried modifying the GET to POST but it gets an error.I want to send post requests with...
I finally managed to do post requests using multi threading.If anyone sees an error or if you can do an improvement for my code feel free to do it :)import requestsfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom time import timeurl_list = [ "https://www.google.com/api/"]tokens = {'Token...
Scrolled Panel not working in wxPython class Frame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None,-1, "SCSM Observatory Log", size=(700, 700)) panel = wxScrolledPanel.ScrolledPanel(self,-1, size=(800,10000)) panel.SetupScrolling()Could someone please explain why this code is not wo...
Not sure why it is not working for you, following a sample which works for me. I like using sized_controls as they handle sizers nicely (in my view).#!/usr/bin/env python# -*- coding: utf-8 -*-import wxprint(wx.VERSION_STRING)import wx.lib.sized_controls as SCclass MyCtrl(SC.SizedPanel): def __init__(self, parent):...
Not able to add a column from a pandas data frame to mysql in python I have connected to mysql from python and I can add a whole data frame to sql by using df.to_sql command. When I am adding/updating a single column from pd.DataFrame, not able udate/add.Here is the information about dataset, result,In [221]: result.sh...
You cannot add a column to your table with data in it all in one step. You must use at least two separate statements to perform the DDL first (ALTER TABLE) and the DML second (UPDATE or INSERT ... ON DUPLICATE KEY UPDATE).This means that to add a column with a NOT NULL constraint requires three steps:Add nullable colum...
count how often each field point is inside a contour I'm working with 2D geographical data. I have a long list of contour paths. Now I want to determine for every point in my domain inside how many contours it resides (i.e. I want to compute the spatial frequency distribution of the features represented by the contours...
If your input polygons are actually contours, then you're better off working directly with your input grids than calculating contours and testing if a point is inside them.Contours follow a constant value of gridded data. Each contour is a polygon enclosing areas of the input grid greater than that value.If you need t...
Sending raw bytes over ZeroMQ in Python I'm porting some Python code that uses raw TCP sockets to ZeroMQ for better stability and a cleaner interface.Right off the bat I can see that a single packet of raw bytes is not sent as I'm expecting.In raw sockets:import socketsock = socket.socket(socket.AF_INET, socket.SOCK_ST...
Oh. Wow. I overlooked a major flaw in my test, the remote server I was testing on was expecting a raw TCP connection, not a ZMQ connection.Of course ZMQ wasn't able to transfer the message, it didn't even negotiate the connection successfully. When I tested locally I was testing with a dummy ZMQ server, so it worked fi...
How to filter for specific objects in a HDF5 file Learning the ILNumerics HDF5 API. I really like the option to setup a complex HDF5 file in one expression using C# object initializers. I created the following file: using (var f = new H5File("myFile.h5")) { f.Add(new H5Group("myTopNode") { new H5Dataset("dsNo...
H5Group provides the Find<T> method which does just what you are looking for. It iterates over the whole subtree, taking arbitrary predicates into account: var matches = f.Find<H5Dataset>( predicate: ds => ds.Attributes.Any(a => a.Name.Contains("att")));Why not make your function retur...
Total/Average/Changing Salary 1,2,3,4 Menu Change your program so there is a main menu for the manager to select from with four options: Print the total weekly salaries bill.Print the average salary.Change a player’s salary.QuitWhen I run the program, I enter the number 1 and the program stops. How do I link it to the ...
Put the raw input in a while. while True: user_input = raw_input("Welcome!...") if user_input == 1: ... elif user_unput == 2: ... else: print "this salary is ridic..."After completing a 1,2,3... input ask the user if they would like to do something else y/n, if n: break, this will end the loop. If y, the loop begins...
How to get python's json module to cope with right quotation marks? I am trying to load a utf-8 encoded json file using python's json module. The file contains several right quotation marks, encoded as E2 80 9D. When I calljson.load(f, encoding='utf-8')I receive the message:UnicodeDecodeError: 'charmap' codec can't dec...
There is no encoding in the signature of json.load. The solution should be simply:with open(filename, encoding='utf-8') as f: x = json.load(f)
How do I get pending windows updates in python? I am trying to get pending windows updates on python but no module returns me the pending windows updates, only windows update history, I don't need especifiation about the update I just need to know if there are pending updates or not, I'm trying to use this code:from wi...
There was no solution in python, so I did a vbs script and called from inside my function.the vbs script isSet updateSession = CreateObject("Microsoft.Update.Session")Set updateSearcher = updateSession.CreateupdateSearcher() Set searchResult = updateSearcher.Search("IsInstalled=0 and Type='Softwar...
Python: get values from list of dictionaries I am using python-sudoers to parse a massive load of sudoers files, alas this library returns some weird data.looks like a list of dictionaries, i dont really know.[{'run_as': ['ALL'], 'tags': ['NOPASSWD'], 'command': 'TSM_SSI'}, {'run_as': ['ALL'], 'tags': ['NOPASSWD'], 'co...
So because in each dict we have repeated variable names the only possible solution is to name them extracted_run_as_0 = 'ALL', extracted_run_as_1 = 'ALL' etc.for i, dictionary in enumerate(lst): for k, v in dictionary.items(): v = v[0] if isinstance(v, list) else v exec(f"extracted_{k}_{i} = {v!r}...