Unnamed: 0
int64
0
1.91M
id
int64
337
73.8M
title
stringlengths
10
150
question
stringlengths
21
64.2k
answer
stringlengths
19
59.4k
tags
stringlengths
5
112
score
int64
-10
17.3k
8,000
46,251,999
Pytest how do I use inline variables in my step arguments?
<p>I'm writing some pytest test files which are attached to feature files that have no example or steps tables. What I'm failing to understand is how I can use my inline variables (USER1 and USER2) which are strings within my Given, When and Then steps (simple example below for when) so that the first time the 'when' ...
<p>If what you're saying is you want to run all of your tests once with USER1, and once again with USER2, then what you're looking for is <a href="https://docs.pytest.org/en/latest/example/parametrize.html" rel="nofollow noreferrer">parametrized tests</a>.</p> <p>Essentially, you define your test once. You then define...
python|variables|arguments|inline|pytest
0
8,001
46,273,475
Split into trainset and testset with a string with an input
<p>I´m really new in python's world. I have allready seen an example of an splitting in trainset and testset. But only with numeric type. The example:</p> <pre><code>import random with open("datafile.txt", "rb") as f: data = f.read().split('\n') random.shuffle(data) train_data = data[:50] test_data = data[50:]...
<p>Use pandas for that and numpy:</p> <pre><code>import pandas as pd import numpy as np df = pd.read_table('datafile.txt', sep='\s+', header=None) df.fillna(0, inplace=True) print(df) print(df.reindex(np.random.permutation(df.index))) </code></pre> <p>The output of the first <code>print</code> is:</p> <pre><code>...
python|prediction|training-data
1
8,002
49,504,321
iterrows producing extra unwanted output from dataframe
<p>In the code below I'm trying to get the 'proid' value and 'uim' value for each row of a dataframe. I'm trying to parse the first and second values from the 'proid' value and use them to create a new directory for each record. So for example for the first record it would create the directory '/stuff/_place/1/2' for...
<p>What is the problem? I had to edit the code so that it runs, and it works without a problem. Next time, write the code so that it is possible to copy and past it and then run it without needing to change anything. </p> <p>The following code, adapted from yours</p> <pre><code>import os import numpy as np import pan...
python|python-2.7|pandas
0
8,003
70,172,191
Scatter plot to show the majorities and include extreme numbers
<p>Simple data as below and I want to put them in a scatter plot.</p> <p>It goes well if there's not outliers (i.e. extremely big numbers).</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() dates = [&quot;2021-...
<p>If you don't want to use a log scale, you can break the plot in two (or more) and plot the values below/above a threshold:</p> <pre><code>df = pd.DataFrame({'num': numbers}, index=dates) thresh = 12000 f, (ax1, ax2) = plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': (1,3...
python|matplotlib|scatter-plot
1
8,004
53,382,770
Unit test case for file upload flask
<p>I have created a flask application, where I am uploading a file and then predicting the type of the file. I want to write unit test case for the same. I am new to unit test in python and therefore very confused!. There are 2 parts to my code, the first is the Main function, which then calls the classification method...
<p>I have finally stumbled upon how to test it, in case anybody was looking out for something similar. </p> <pre><code>from predict_main_restplus import func_predict from werkzeug.datastructures import FileStorage file = None def test_classification_correct(): with open('W8-EXP_1.pdf', 'rb') as fp: file ...
python-3.x|unit-testing
1
8,005
45,893,671
How to bundle COM dlls into a portable app?
<p>I need to write a program that uses some COM objects, accessed from the python comtypes package. I use the clsid and/or progid to create and use them. These objects are provided by a third party, and normally they are installed with a normal installer (setup.exe or MSI file). </p> <p>Let's suppose that these DLL fi...
<p>You're asking a lot of questions here. There are a lot of ways to accomplish what you're trying to accomplish, and it's hard to answer such a broad set of questions. If you have specific questions on how to do a specific thing, please start new posts for those.</p> <p>That said, I will try to give you some informat...
python-3.x|com|dllregistration|portable-applications|comtypes
3
8,006
45,926,033
KeyError: "['avg_sparsity_int'] not in index" while merging two dataframe
<p>I would like to merge three dataframes and my code does merge two at a time. Problem is I get an error from merging two dataframes.</p> <p>Here's an error:</p> <pre><code>KeyError: "['avg'] not in index" </code></pre> <p>Here's my code:</p> <pre><code>df_features = pd.merge(max[['id', 'max']], variance[['id', 'v...
<p>It was an issue of wrong column name('avg' was not correctly defined above), but it merged successfully. </p>
python|pandas
1
8,007
45,847,463
Python TypeError: 'numpy.int32' object is not iterable
<p>I am trying to take the entropy of my k-means result dataframe and I am getting the error back: TypeError: 'numpy.int32' object is not iterable I dont understand why. </p> <pre><code>from collections import Counter def calcEntropy(x): p, lens = Counter(x), np.float(len(x)) return -np.sum(count/lens*np.log2...
<p>Ok this is a first attempt. It looks like your dataframe stores the cluster index in the <code>'cluster'</code> column. So what you need to do is get each cluster based on the index, and then pass that cluster to your <code>calcEntropy</code> function, something like</p> <pre><code>for i in xrange(len(k_means_sp[...
python|pandas|typeerror|ipython-notebook|entropy
0
8,008
54,869,181
If anaconda has a package and it is not in pip, how do I install it?
<p>I want to install <a href="https://anaconda.org/conda-forge/gudhi/files" rel="nofollow noreferrer"><code>gudhi</code></a> packages. </p> <p>It seems that the package only says that it can be installed only with anaconda. But I want to install it with <code>pip</code> , not anaconda.</p> <p>When I checked the packa...
<p>There is no <code>pip install gudhi</code> available. If you don't want to go with conda, you will have to follow the <a href="https://gudhi.inria.fr/python/latest/installation.html" rel="nofollow noreferrer">installation guide</a>.</p> <p>If <code>make cython</code> works, you can then <code>[sudo] python[3] setup...
python-3.x|pip
0
8,009
54,937,264
package for graph creation and processing in python
<p>I am trying to create and process graphs, for example, checking if a graph contains a cycle and I'm doing this in python.</p> <p>Is there an API or Library that has implemented these basic capabilities?</p>
<p>So, I know about <code>NetworkX</code> library.</p> <pre><code>import networkx as nx G1 = nx.Graph() G1.add_edges_from([(0, 1),(0, 2),(0, 3),(8, 9)]) l = list(nx.strongly_connected_components(G1)) # Gives a list of all strong connected components # You can also try # l = list(nx.weakly_connected_components(G1)) # ...
python|graph
0
8,010
54,964,173
pandas read csv by taking samples
<p>I have a large CSV file and I just want to take a 1% sample from it. Is there a good way to read the samples directly into pandas data frame without having to read the whole file and then discard 99% of the data?</p>
<p>Assuming the number of lines are large enough for the law of large #'s to take effect, and you don't need it to be exactly 1% (just very close to it), you could do the following:</p> <pre><code>import csv from random import random import pandas with open('data.csv', 'r') as fin: reader = csv.reader(fin) row...
python|pandas|csv
2
8,011
55,057,283
What type of CNN will be suitable for underwater image processing?
<p>The primary objective (my assigned work) is to do an image segmentation for the underwater images using a convolutional neural network. The camera shots taken from the underwater structure will have poor image quality due to severe noise and bad light exposure. In order to achieve higher classification accuracy, I ...
<p>What do you need to segment? I'd be nice so see some labels of the segmentation.</p> <p>You may not need to enhance the image, if all your dataset has that same amount of noise, the network will generalize properly.</p> <p>Regarding CNNs architectures, it depends on the constraints you have with processing power a...
python-3.x|image-processing|computer-vision|conv-neural-network|image-segmentation
1
8,012
24,833,574
Using NetworkX to position Nodes on PyQt QgraphicsScene
<p>Hello I have been looking at graph libraries that will allow me to create interactive graphs on PyQt QgraphicsScene,(kind of like facebook/LinkedIn social graphs) while I have not found many python libraries that work well with Qt/PyQt(fast, with numerous layout algorithms) At first I thought I would use Boost Grap...
<p>Hi Just to add on to the answer, here is the code I implemented,</p> <pre><code>def generate_graph_and_update_scene(self): try: local_params=locals() #for error log get local paramters this_function_name=sys._getframe().f_code.co_name #for error log get function name self.vertex_dic...
python-2.7|numpy|qt4|pyqt4|networkx
2
8,013
24,592,919
Make Pycharm run the currently edited file
<p>When pressing the "run" button in Pycharm, I want to make it run the currently opened file, instead of automatically using run configs of other files and running those. </p> <p>This is kind of like Eclipse. I'm used to Eclipse and not this, and so it'll cause me to make errors thinking I'm running the currently ope...
<p>Either press:</p> <pre><code>ctrl + shift + f10 </code></pre> <p>Or right click your file name in the editor as such: <img src="https://i.stack.imgur.com/RMlNd.png" alt="Run"></p> <p>And press run. Next time the green button will automatically run the current file.</p>
python|pycharm
4
8,014
30,885,466
Django error "add a non-nullable field"
<p>i am getting error django model like this when i try to makemigrations:</p> <pre><code> You are trying to add a non-nullable field 'person' to owner without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on...
<p>Your code isn't wrong. Just follow the instructions provided by the message...</p> <p>The <code>person</code> field within your <code>Operator</code> model can't be <code>null</code> (because <code>null=True</code> isn't set). You must already have Operators in your database, so Django doesn't know what to do with ...
python|django|django-models
4
8,015
39,911,442
Binary Tree Traversal - Preorder - visit to parent
<p>I'm trying to understand the recursive implementation of preorder traversal as shown in this link <a href="http://interactivepython.org/runestone/static/pythonds/Trees/TreeTraversals.html" rel="nofollow">http://interactivepython.org/runestone/static/pythonds/Trees/TreeTraversals.html</a></p> <pre><code>def preorder...
<p><code>preorder(tree.getLefChild())</code> goes through all the left children for the current tree. That method then returns, just like all other methods, then continues on with the parent's right children. </p> <p>A quick visualization </p> <pre><code>def preorder(tree): if tree: print(tree.getRootV...
python|recursion|binary-tree
0
8,016
40,224,066
ipdb commands obscured by variables
<p>When i try to debug this sample script with ipdb:</p> <pre><code>n = 1 next = 1 print('end') </code></pre> <p>I can't execute line 3 because python variables obscure pdb commands:</p> <pre><code>$ ipdb test.py &gt; /tmp/test.py(1)&lt;module&gt;() ----&gt; 1 n = 1 2 next = 1 3 print('end') ipdb&gt; ne...
<p><strong>Update in 12/14/2016:</strong></p> <p>Finally the iPython team decide to <a href="https://github.com/ipython/ipython/pull/10050" rel="nofollow noreferrer">revoke this design</a>.</p> <hr> <p>The solution of your problem is use <code>!!</code> statement to force standard behavior.</p> <pre><code>&gt; /hom...
python|debugging|ipython|pdb|ipdb
2
8,017
52,417,197
Error in pandas moving average crossover backtest
<p>I am trying to backtest moving average crossover strategy with pandas.</p> <p>First, I defined a class (Book) where number of stocks, amount of cash, and total amount of asset.</p> <p>In the class there are 3 functions that calculates book status as buy or sell signals is generated.</p> <p>Here is my code, but wh...
<p>I have updated your code as below and now it seems to be somewhat better and improved, I have added additional info in <code>df</code> for debugging purpose, which you can remove as per your requirement:</p> <pre><code>import pandas as pd from pandas_datareader import data as pdr # download dataframe test = pdr.ge...
python|pandas
2
8,018
18,844,274
Tweaking celery for high performance
<p>I'm trying to send ~400 HTTP GET requests and collect the results. I'm running from django. My solution was to use celery with gevent.</p> <p>To start the celery tasks I call <strong>get_reports</strong> :</p> <pre><code>def get_reports(self, clients, *args, **kw): sub_tasks = [] for client in clients: ...
<p>Are you really running on Windows 8 without a Virtual Machine? I did the following simple test on 2 Core Macbook 8GB RAM running OS X 10.7:</p> <pre><code>import celery from time import time @celery.task def test_task(i): return i grp = celery.group(test_task.s(i) for i in range(400)) tic1 = time(); res = grp(...
python|django|performance|rabbitmq|celery
7
8,019
19,011,111
should __exit__ superclass method be called from subclass in python
<p>I am not sure why this even dawned on me but if I have a context manager compliant class that is a subclass of another context manager class as shown below. I have shown the "typical" model where __exit__ calls close(). My question is: should bar.__exit__() explicitly call super(bar,self).__exit__(args) or should ...
<p>As it might be impossible to know in general case what the <code>__exit__</code> method does, I'd call it with the same arguments; if I want to throw an exception, then give it that exception instead in its <code>__exit__</code>, and then raise it after the exception has returned... but all in all this sounds a bit ...
python|subclass|exit|superclass
2
8,020
19,184,116
Counting Loop Iterations (Python)
<p>I've got a quick question about counting loop iterations in Python. I've created objects that "age" with each iteration and are supposed to "die" at a certain age, but sometimes they live substantially longer. Here's a snippet of my program:</p> <pre><code>def reproduce(): class Offspring(Species): def ...
<p>One thing that may or may not be intended: when you pass a list to list(), a copy of the list is returned (<a href="http://docs.python.org/2/library/functions.html#list" rel="nofollow">http://docs.python.org/2/library/functions.html#list</a>). So when you do for x in list(petri_dish), you are getting elements from a...
python|loops|object|iteration
1
8,021
19,298,377
regex to see if one specific letter is always followed by another specific letter
<p>I have a word entered by user. I want to check if the word satisfied the following rule or not. </p> <p>Rule : The letter q is always written with u.</p> <pre><code>user word : qeen </code></pre> <p>the output will be </p> <pre><code>not match with the rule. edited word : queen </code></pre> <p>one more examp...
<p>That's a perfect fit for a <a href="http://www.regular-expressions.info/lookaround.html">lookahead assertion</a>:</p> <pre><code>q(?=u) </code></pre> <p>matches a <code>q</code> only if it's followed by <code>u</code>, whereas</p> <pre><code>q(?!u) </code></pre> <p>matches a <code>q</code> only if it's <em>not</...
python|regex
10
8,022
62,454,476
Relative path in python on win 10
<p>All I want in python 3 is to use a relative path on a win 10 PC. like:</p> <pre><code>open('folder_for_text\text_subfolder\myText.txt') </code></pre> <p>I've tried:</p> <pre><code>open('folder_for_text/text_subfolder/myText.txt') # this should also work in python open('folder_for_text\\text_subfolder\myText.txt'...
<p>If you are running the script from a different folder, the relative path must be from the place where you are running the script:</p> <p>e.g. if the script is in <code>Documents</code> and you are running it from your <code>home</code> folder like</p> <pre><code>python Documents/script.py </code></pre> <p>the rel...
python|relative-path
1
8,023
67,324,945
Python - Selenium - Some elements found, but other not
<p>the first 10 'td' are found, but none of the other 800 or so. How come this is happening, its very frustrating.</p> <p>I just want a list of all the TD on the that page, but only some are found even though all are visible.</p> <pre><code>driver.get(&quot;http://www.skyracing.com.au/index.php?component=racing&amp;tas...
<p>Why not just loop over the list returned by <code>driver.find_elements_by_xpath('//td')</code>?</p> <pre class="lang-py prettyprint-override"><code>for idx, elem in enumerate(driver.find_elements_by_xpath('//td')): print(i+1, elem.text) </code></pre>
python|selenium|tags
0
8,024
36,424,159
Converting a list of lists to an array in Python
<p>I've been looking this up, but I couldn't find anything that helped. I'm having some trouble making an array of the size I want. </p> <p>So far, I have created a list of lists with this code: </p> <pre><code>n=4 def matrixA(k): A=[] for m in range(0,k): row=[] #A.append([]) for n in...
<p>Welcome in numpy world.</p> <p>It seems that you want :</p> <pre><code>array([[ 128., -64., 0., 0.], [ -64., 128., -64., 0.], [ 0., -64., 128., -64.], [ 0., 0., -64., 128.]]) </code></pre> <p>It's difficult to think in terms of rows and cols indices when building list...
python|arrays|list|numpy
2
8,025
36,385,213
How can I write multiple files using for loop?
<p>Hi I want to create files with name file1.txt, file2.txt, ... etc. I am getting limit error for it. What do I need to do in my code to make it work?</p> <pre><code>from bs4 import BeautifulSoup f = open('reut2-000.sgm', 'r') data= f.read() soup = BeautifulSoup(data, "html.parser") contents = soup.findAll('body') ...
<blockquote> <p>ValueError: need more than 1 value to unpack</p> </blockquote> <p>The <code>contents</code> in your case would contain a list of <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#tag" rel="nofollow"><code>bs4.Tag</code></a> instances. If you want to "index" them - use <a href="https://do...
python|file|for-loop|beautifulsoup
0
8,026
13,370,867
Set Python27 Google AppEngine default encoding for entire app
<p>I would like to set the default encoding to utf-8 for my python27 appengine site. The default is ascii.</p> <p>There was a similar question answered <a href="http://code.google.com/p/googleappengine/issues/detail?id=5923" rel="nofollow">http://code.google.com/p/googleappengine/issues/detail?id=5923</a>. It says to ...
<p>You can start your python 27 code (every Python file) with:</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import unicode_literals </code></pre> <p>But sometimes you have to use .encode('ascii') if you use HMAC or you have to set http headers. Or you can use: </p> <pre><code>self.respons...
google-app-engine|encoding|python-2.7
3
8,027
21,945,864
PyZMQ one-way communication
<p>I took a look at the various ZMQ messaging patterns and I'm not sure which one would do for my project. All I want to do is be able to connect to a server and send a command (the client never receive anything). On the server side, I want to be able to check if there is a message, if there is one, process it, else co...
<p>First, since you want one-way communication with only one socket receiving messages, that generally means PUSH-PULL. Here is a version of the client:</p> <pre><code>import zmq ctx = zmq.Context.instance() s = ctx.socket(zmq.PUSH) url = 'tcp://127.0.0.1:5555' s.connect(url) while True: msg = raw_input("msg &gt...
python|sockets|zeromq|pyzmq
9
8,028
22,000,432
numpy applying aggregated information across a 2D array
<p>i have a list of agent's "health" in a 2D array:</p> <pre><code>health=[[0.5,0.8],[0.1,0.5],[0.5,0.7]] </code></pre> <p>and a set of actions( one per agent):</p> <pre><code>actions=[[0,1],[2,0],[1,1]] </code></pre> <p>(possible actions = {0,1,2}</p> <p>depending on their actions, their health gets increased, ac...
<p>Using numpy you can use integer arrays directly to index other arrays. For example <code>A[[0, 1, 2], [11, 12, 13]]</code> will return an array with 3 elements which are <code>A[0, 11], A[1, 12] and A[2, 13]</code>. Here is how you can apply this concept to your problem.</p> <pre><code>import numpy as np health = ...
python|numpy|multidimensional-array
0
8,029
22,151,540
Have zipped this , and need it on a format [x1, y1]
<p>Have a problem, i have zipped two lists. Now u see this:</p> <pre><code>[(1951, 720)] [(1927, 107000)] [(1952, 1914)] [(1976, 780)] [(1902, 4239)] [(1919, 910)] </code></pre> <p>How can i get it on this format:</p> <pre><code>[1976, 780] [1902, 4239] [1919, 910] </code></pre> <p>I have made the lists like this:<...
<p>Having read both this and your earlier question, it seems to me you actually want to get to a text representation of your data - where your data is originally in a list of tuples.</p> <p>This is best done by iterating over the list and printing out in the format you actually need. If you started out with</p> <pre>...
python-2.7
0
8,030
43,509,061
How to pass the id of the html button to python file by using django?
<p>I have the following code in my HTML file that is to created the dynamic button.</p> <pre><code> {% for i in loop_times %} &lt;button type="submit" class="'btn btn-lg" name="{{ i }}" id="{{ i }}" onclick="alert(this.id)" formmethod="post"&gt;&lt;a href="{% url 'button' %}"&gt;{{i|safe}}&lt;/a&gt;&lt;/button&gt;&l...
<p>Try using this:</p> <pre><code>labelid = request.GET.get("id", False) </code></pre> <p>instead of this:</p> <pre><code>labelid = request.GET[("id", False)] </code></pre> <p>Your current method is trying to get <code>("id", False)</code> as a dictionary value, but obviously that's not what you are trying to do.</...
javascript|python|html|django
1
8,031
71,261,075
file not found error when running python script through tkinter .exe application No Such file or Directory
<p>I have created my python script and linked in tkinter UI both .py files are running fine when i ran it visual studio code. But I have converted tkinter UI .py file to .exe file to run my python script in executable file. I have successfuly converted the executable file. But when i run through the executable file(App...
<p>To import <code>myprogram.py</code> into <code>UI.py</code> you can do this:</p> <pre><code>import myprogram.py </code></pre> <p>The when you build it into an .exe file with pyinstaller you can add the <code>--onefile</code> option to build both scripts into one file. Here's an example:</p> <pre><code>pyinstaller --...
python|tkinter
0
8,032
71,365,923
How to remove suffix from scraped links?
<p>I'm looking for a solution to get full-size images from a website.</p> <p>By using the code I recently finished through someone's help on stackoverflow, I was able to download both full-size images and down-sized images.</p> <p>What I want is for all downloaded images to be full-sized.</p> <p>For example, some image...
<p>I would go with something like this:</p> <pre><code>import re url = 'https://kickstart.bikeexif.com/wp-content/uploads/2018/01/1968-harley-davidson-shovelhead-625x417.jpg' new_url = re.sub('(.*)-\d+x\d+(\.jpg)', r'\1\2', url) #https://kickstart.bikeexif.com/wp-content/uploads/2018/01/1968-harley-davidson-shovelhea...
python|regex|web-scraping
0
8,033
9,335,768
Application asks for internet connection
<p>When I start any application, that I wrote with python for my Nokia 5800(software version 60.0.003), it asks me for internet connection. Application doesn't use it or need it. And if I skip it applications works fine.</p> <p>I'm using ensymble(PyS60 application packager 2.0.0) with Python 2.5.2 to create applicatio...
<p>It's not Python itself. I've traced it and it doesn't open any sockets when starting up. Check the capabilities that are set on the Python interpreter. Maybe it has the NetworkServices capability set because it <em>can</em> use sockets.</p>
python|symbian|nokia|pys60
0
8,034
52,629,543
Python - script hangs on open() function
<p>I have a Python script that first kills all <code>hostapd</code> processes then starts a fresh one. I want to capture the output of the <code>hostapd</code> start command to determine if it returns <code>AP-ENABLED</code> or <code>AP-DISABLED</code> so I decided to write it to a temporary file then read it.</p> <p>...
<p>OK so I will explain You why You have problem here.</p> <p>So <code>hostapd</code> is daemon process (Look at the last <strong>d</strong> in the name, most linux daemons have it).</p> <p>So You are trying to start this daemon with the <code>os.system</code>. In the documentation I have checked that this function s...
python|raspberry-pi|subprocess|sys|hostapd
2
8,035
52,573,183
How to count occurrences of a list of string inside of a list in python?
<p>For example my list is </p> <pre><code>lst=['hello','world','this','is','hello','world','world','hello'] subString=['hello','world'] </code></pre> <p>The result I'm looking for is in this case is 2 since the list ['hello','world'] occurs twice with that same order.</p> <p>I tried doing</p> <pre><code>list(filter...
<p>You could use <code>" ".join()</code> on both lists to create a string and then use <code>str.count()</code> to count the number of occurrences of <code>subString</code> in <code>lst</code></p> <pre><code>lst=['hello','world','this','is','hello','world','world','hello'] subString=['hello','world'] l = " ".join(lst...
python|python-3.x
0
8,036
52,879,733
Pandas .apply() function not always being called in python 3
<p>Hello I wanted to increment a global variable 'count' through a function which will be called on a pandas dataframe of length 1458.</p> <p>I have read other answers where they talk about .apply() not being inplace. I therefore follow their advice but the count variable still is 4</p> <pre><code>count = 0 def cc(x)...
<p>Yes, the observed effect is because you have categorical type of the column. This is smart of pandas that it just calculates apply for each category. Is counting only thing you're doing there? I guess not, but why you need such a calculation? Can't you use df.shape?</p> <p>Couple of options I see here:</p> <ol> <l...
python-3.x|pandas|global-variables|apply
1
8,037
47,771,582
How to convert list into excel?
<pre><code>ordered_list = [ "Mon","Tue","Wed","Thu","Fri","Sat","Sun"] wb = Workbook('dem.xlsx') ws = wb.add_worksheet("New Sheet") first_row=0 for header in ordered_list: col=ordered_list.index(header) ws.write(first_row,col,header) col=1 for j in po: row=ordered_list.index(j[0]) ws.write(col,row,j...
<p>With the help of pandas you may get it simple.</p> <pre><code>import pandas as pd po = [('Mon', 6421), ('Tue', 6412), ('Wed', 12416), ('Thu', 23483), ('Fri', 8978), ('Sat', 7657), ('Sun', 6555)] # Generate dataframe from list and write to xlsx. pd.DataFrame(po).to_excel('output.xlsx', header=False, index=False) <...
python
6
8,038
37,174,371
Pandas create multiple aggregations
<p>Trying to see how hard or easy this is to do with Pandas. </p> <p>Let's say one has a two columns with data such as:</p> <pre><code>Cat1 Cat2 A 1 A 2 A 3 B 1 B 2 C 1 C 2 C 3 D 4 </code></pre> <p>As you see <code>A</code> and <code>C</code> have three...
<p>You can use <code>groupby</code> twice to achieve this.</p> <pre><code>df = df.groupby('Cat1')['Cat2'].apply(lambda x: tuple(set(x))).reset_index() df = df.groupby('Cat2')['Cat1'].apply(lambda x: tuple(set(x))).reset_index() </code></pre> <p>I'm using <code>tuple</code> because pandas needs elements to be hashable...
python|pandas
3
8,039
34,058,144
Azure Web-App Maximum Execution Time Issue
<p>I am developing a python django app for my project. Due the nature of one of my apps, I need to run a certain script for a long period of time (maybe several hours).</p> <p>Obviously everything is fine in my local environment. However, when I publish that app to the azure, the app crashes after a period of time due...
<p>You can try to leverage <a href="https://azure.microsoft.com/en-us/documentation/articles/web-sites-create-web-jobs/" rel="nofollow">WebJobs</a> to run your certain scripts or programs for on demand, continuously, or on a schedule tasks on background. </p> <p>And at the same time, as web apps are unloaded if they a...
python|django|azure
0
8,040
34,272,327
Saving an image using splinter python
<p>I have an image in site and i want to save it to my computer but i cant find way. the html relevent code is:</p> <pre><code>&lt;div class="rfloatL text-field"&gt; &lt;img src="/register/tb135/tb_getimage.php?uid=1450109984&amp;start=" title style:="border:1-x solid;"&gt; &lt;/div&gt; </code></pre> <p>i tried th...
<p>You can use <strong>find_by_tag("img")</strong> to get the img element.</p>
python|selenium|splinter
0
8,041
66,198,119
pygame - constant frame rate
<p>I would like to achieve a frame rate as constant as possible in my Pygame game.</p> <p>This answer (<a href="https://stackoverflow.com/questions/35617246/setting-a-fixed-fps-in-pygame-python-3">Setting a fixed FPS in Pygame, Python 3</a>) explains how to give a fluent and frame-rate-independant result, but this is n...
<p>I believe that you can call <code>clock.tick()</code> with your desired frame rate, and it will do the right thing. That is, you can replace the last three lines of your code with just <code>clock.tick(FPS)</code>.</p>
python|pygame|pygame-clock|pygame-tick
0
8,042
40,333,806
Changing attributes in other panels
<p>Here is the code I am working on:</p> <pre><code>import wx import wx.aui import wx.lib.scrolledpanel from parse import * import settings parser=parse() ID_OPEN = 101 ID_SAVE = 102 ID_QUIT = 103 factors = ['Power','Fuel','Pot Water','Bottled Water','Storage Area','Personnel','Grey Water','Black Water','Solid ...
<p>You have correctly started with binding the EVT_TEXT_ENTER to UpdateEstValues. There you get the entered value, and the only thing you need is to transfer this value into the second tab, right? You also seem to be using the parser as a "model", that keeps the currently valid values right? So in UpdateEstValues you ...
python|wxpython|panel|wxtextctrl|wxnotebook
1
8,043
40,429,774
Take a list as an input and return the median value
<p>Been stuck on this the last while and for the life of me can't find what's wrong. So the exercise in question is:</p> <blockquote> <p>Write a function called median that takes a list as an input and returns the median value of the list. For example: <code>median([1,1,2])</code> should return 1.</p> </blockquote> ...
<p>Open a Python 2 REPL and try the following:</p> <pre><code>&gt;&gt;&gt; (4+5)/2 4 </code></pre> <p>You can force float division by using <code>2.0</code>.</p> <pre><code>&gt;&gt;&gt; (4+5)/2.0 4.5 </code></pre> <p>In Python 3 the first example would produce <code>4.5</code>, which would account for the differenc...
python|list|median
2
8,044
40,491,909
Creating a N sets of combinations of variables from the given range of each variable
<p>This may be a very vague question -- I apologize in advance. </p> <p>y is a function of a,b,c,d,e. a can go from 1 to 130; b from 0.5 to 1; c from 3 to 10; d from 0 to 1; and e is 1-d. </p> <p>Is there a way in python I can create N (say, 10,000) sets of combinations of a,b,c,d and e from the given range?</p>
<p>I assume you want floating point numbers for all of these. If you want <code>int</code>s use <code>random.randint</code> </p> <pre><code>from random import uniform inputs = [[uniform(1,130), uniform(.5, 1), uniform(3,10), uniform(0,1)] for _ in range(N)] for input_list in inputs: input_list.append(1-input_li...
python|list|simulation|montecarlo
0
8,045
68,325,353
Unable to convert the scientific notation to float type python
<p><code>a = 6.2e-05</code></p> <p>I have tried the below methods:</p> <ol> <li><code>a = float(&quot;{:.6f}&quot;.format(float(a)))</code></li> <li><code>format(a,'f')</code></li> <li><code>pd.options.display.float_format = &quot;{:,.6f}&quot;.format</code></li> </ol> <p>I am able to print the <code>a</code> variable...
<p>6.2e-05 and 0.000062 both values are same so you can use any of these in your code. But if you want to print the value as 0.000062 you can use this:</p> <pre><code>a = 6.2e-05 print(&quot;{:.6f}&quot;.format(a)) </code></pre>
python
1
8,046
26,096,174
How to add time index from a date and time column in pandas
<p>I have a OHLC dataframe as following:</p> <pre> trade_date trade_time open_price high_price low_price close_price volumn 19911223 15:00 27.70 27.9 27.60 27.80 1270 19911224 15:00 27.90 29.3 27.00 29.05 1050 19911225 15:00 29....
<p>This is a fully vectorized soln.</p> <p>Convert the trade_date column to a <code>datetime64[ns]</code> dtype (it can be a <code>int64</code> or <code>object</code> dtype a-priori). Convert the trade_time to a <code>timedelta64[ns]</code> dtype. You need to give the hint that the time is a hh:mm by adding the second...
python|pandas
1
8,047
54,955,174
Sum TimeField hours/minutes with Pandas
<p>I am trying to use Pandas to sum the time (hours, minutes) of a series. The data comes from a TimeField</p> <pre><code>class PhoneRecord ( models.Model ): et = models.TimeField ( null=True, blank=True ) </code></pre> <p>In python I get the record and convert to a dataframe.</p> <pre><code>phone = PhoneRecord...
<h2>You just need to run a custom 1-liner here to combine <code>time</code> objects into <code>timedelta</code> objects which can then be summed together. (see the "print" line)</h2> <pre><code>from datetime import datetime, timedelta import pandas as pd phone = PhoneRecord.objects.all() df = pd.DataFrame(list([i.__...
python|django|pandas
2
8,048
44,284,104
Python beginner trying to understand how to run input() function
<p>this is my first post on this site and please tell me if I posted on wrong place or something.</p> <p>So... I'm using Mac version of Python 3.x which I started learning a few weeks ago and am facing a bit of trouble understanding here.</p> <p>In the text editor, I wrote and saved:</p> <pre><code>&gt;a = input("&g...
<p>If you are using python 2.7 write <code>school</code> in double quotes to get it as string.</p> <p>E.g. an example from Python 2.7 idle:</p> <pre><code>&gt;&gt;&gt; a = input("&gt; ") &gt; "school" &gt;&gt;&gt; print("A boy goes to " + a) A boy goes to school </code></pre>
python|python-3.x
1
8,049
44,369,538
Creating Django Filter in a bootstrap dropdown based on the django-admin created categories
<p>I am 2 months into Python-Django and I do not have the full experience to carry on with my what I want to do. </p> <p>I like to create a <strong>Filter or a Dropdown Filter</strong> such that anyone can choose from the <strong>for-loop rendered categories in the dropdown</strong> to filter or search by category. I ...
<p>In accordance to the comment given by @TimS and some other helps from another community, I wrote a solution to filter by category and it works. </p> <p>Below is the hack that made its work:</p> <p><strong>home.html</strong></p> <p>This is the looped dropdown from categories table. I created a name element called ...
django|python-2.7|django-views
0
8,050
32,940,369
How do I setup the python interpreter in pycharm for a cross-platform project?
<p>I have a cross-platform python project (it's a whole bunch of scripts) that I run (and develop) on Windows as well as Linux (Redhat and Ubuntu). Everything works fine except the fact that I have to go and "Configure Python Interpreter" everytime I open the project in a different operating system.</p> <p>My python e...
<p>Actually I jumped the gun on this one...some one has already answered this question here: <a href="https://stackoverflow.com/questions/14440025/share-a-pycharm-project-across-multiple-operating-systems-different-interpreter">Share a PyCharm project across multiple operating systems (different interpreter paths)</a><...
python|pycharm
0
8,051
14,184,623
Preferred way to format a dictionary being passed to a function?
<p>How would I format:</p> <pre><code>self.bot = servo.Robot({ 'waist': servo.Servo(3, 90, .02, 0), 'shoulder': servo.Servo(4, 130, .03, 15), 'elbow': servo.Servo(5, 110, .02, 19), 'wrist': servo.Servo(6, 20, .01, 9), 'claw': servo.Servo(7, 40, .01, 0) }, [5, 15, 25]) </code...
<p>Using the <code>dict</code> constructor, you can at least eliminate typing a bunch of quotes:</p> <pre><code>self.bot = servo.Robot(dict( waist = servo.Servo(3, 90, .02, 0), shoulder = servo.Servo(4, 130, .03, 15), elbow = servo.Servo(5, 110, .02, 19), wrist = servo.Servo(6, 20, .01,...
python|formatting|format
2
8,052
14,345,816
How to read named FIFO non-blockingly?
<p>I create a FIFO, and periodically open it in read-only and non-blockingly mode from a.py:</p> <pre><code>os.mkfifo(cs_cmd_fifo_file, 0777) io = os.open(fifo, os.O_RDONLY | os.O_NONBLOCK) buffer = os.read(io, BUFFER_SIZE) </code></pre> <p>From b.py, open the fifo for writing:</p> <pre><code>out = open(fifo, 'w') o...
<p>According to the manpage of <code>read(2)</code>:</p> <blockquote> <pre><code> EAGAIN or EWOULDBLOCK The file descriptor fd refers to a socket and has been marked nonblocking (O_NONBLOCK), and the read would block. POSIX.1-2001 allows either error to be returned for...
python|nonblocking|fifo
17
8,053
34,613,881
AdminSettings API using service account auth/keyword failures
<p>Trying to retreive domain number of users, 'GetCurrentNumberOfUsers()', using AdminSettings API via a Service Account in <strong>Python</strong>. Enabled delegation wide authority and scope, but getting errors. I have used service account for Calendar API, Directory API, EmailSettings API, but not working for Admin...
<p>The old GData Python library service objects don't actually support OAuth 2.0 which is what you need to be using. However you can hack a access token on there. Try something like:</p> <pre><code>credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key, scope='https://apps-apis.google.com/a/feeds/domai...
python-2.7|google-admin-sdk|google-admin-settings-api
0
8,054
960,733
Python creating a dictionary of lists
<p>I want to create a dictionary whose values are lists. For example: </p> <pre><code>{ 1: ['1'], 2: ['1','2'], 3: ['2'] } </code></pre> <p>If I do:</p> <pre><code>d = dict() a = ['1', '2'] for i in a: for j in range(int(i), int(i) + 2): d[j].append(i) </code></pre> <p>I get a KeyError, because ...
<p>You can use <a href="http://docs.python.org/library/collections.html#collections.defaultdict" rel="noreferrer">defaultdict</a>:</p> <pre><code>&gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; d = defaultdict(list) &gt;&gt;&gt; a = ['1', '2'] &gt;&gt;&gt; for i in a: ... for j in range(int(i), int(i) ...
python|dictionary
306
8,055
491,921
Unicode (UTF-8) reading and writing to files in Python
<p>I'm having some brain failure in understanding reading and writing text to a file (Python 2.4).</p> <pre><code># The string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) </code></pre> <blockquote> <p>("u'Capit\xe1n'", "'Capit\xc3\xa1n'")</p> </blockquote> <pre><code...
<p>Rather than mess with <code>.encode</code> and <code>.decode</code>, specify the encoding when opening the file. The <a href="https://docs.python.org/3/library/io.html#io.open" rel="nofollow noreferrer"><code>io</code> module</a>, added in Python 2.6, provides an <code>io.open</code> function, which allows specifyin...
python|unicode|utf-8|io
838
8,056
47,141,998
How to get user id from JWT
<p>How to get user id from JWT token. My JWT token has payload something like this:</p> <pre><code>{ "username": "Steve", "is_admin": false, "id": 1 } </code></pre> <p>How do I get access to <code>user id</code>? I actually want to update certain fields in database as per the id, that are for a specific user.</...
<p><strong>serializers.py</strong> </p> <pre><code>from django.contrib.auth import get_user_model from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() exclude = () </code></pre> <p><strong>views.py</strong></p> <pre><code>...
python|django|django-rest-framework
1
8,057
47,151,398
Why does this python code produce an error:?
<p>Basically in python 3.0 I tried to use two %s string substitutes and concatenate it. However, it seems to produce an error.</p> <p><strong>CODE</strong></p> <pre><code> print "%s"+"%s" %("John", "rows") </code></pre> <p>I am new to programming so I would be thankful if I could get a simple explanation. Thanks</p>
<p>In <a href="/questions/tagged/python-2.x" class="post-tag" title="show questions tagged &#39;python-2.x&#39;" rel="tag">python-2.x</a>, which appears to be the language that line of code was written in (you treated <code>print</code> as a statement), you will get an error <code>TypeError: not all arguments converted...
string|python-3.x|concat
0
8,058
47,265,472
How to query data from MYSQLdb with Python2.7 if I want query "date-1"?
<p>So, I need to query data from MYSQLdb in every day, that's why I prefer to use a query which one I can query the actual date - 1 data. For example if I run my script today at Nov 13, I need the all information from Nov 12 (from the ACTUAL_DATE - on the picture).</p> <p>I have got a column in the MYSQLdb, which look...
<p>You can make use off the function STR_TO_DATE to format the VARCHAR format into a DATETIME format. </p> <p><strong>Query</strong></p> <pre><code>SELECT * FROM ( # test data replace this with your table name SELECT 'Sunday, Nov 12' AS A UNION ALL SELECT 'Saturday, Nov 11' ) AS records WHER...
python|mysql|sql|debian|mysql-python
1
8,059
70,942,279
I want to serach some text on multiple files [CLOSED}
<p>In one directory i have lots of file and in every 4 hours new file named as filename_date is getting created so i just want to check on last 5 created files only. for example</p> <pre><code>-rw-r--r-- 1 root root 5686 Jan 31 06:12 process_list.txt_20220131_061218.txt -rw-r--r-- 1 root root 8921 Jan 3...
<p>I am able to figure out this problem and fixed it for now. Adding code snippet</p> <pre><code>files = glob.glob(process_list_file_path) # Need to check file is avail or not in files if len(files) != 0: files.sort(key=os.path.getmtime) # If length is...
python|python-3.x|python-2.7
0
8,060
11,661,983
Selenium Web Driver access Javascript global variable in Jquery
<p>I am trying to run a functional test in Python using Selenium, and I want to retrieve the value of a global variable in Javascript that has been declared on a certain page. </p> <p>Normally <code>browser.execute_script("return globalVar;")</code> works fine, but this variable is declared within <code>$(document).re...
<p>That's not a global variable. It is local to the scope of the anonymous function. So no, you can't access it.</p>
javascript|jquery|python|selenium|functional-testing
2
8,061
33,811,864
How do I, within python, retrieve a sparse matrix stored by julia in a .jld file?
<p>Using julia, I can save a sparse matrix in a .jld file (which is using the HDF5 format) like so:</p> <pre><code>a=spzeros(3,3); a[1,1]=2.0 a[2,1]=1.0 a[3,1]=5 @save("sparsematrix.jld",a) </code></pre> <p>Now I want to retrieve this matrix in python (using h5py), so I tried the following:</p> <pre><code>import h5p...
<p>Ok, found it myself, after wrapping my head around the CSC format:</p> <pre><code>import h5py from scipy.sparse import csc_matrix filename="sparsematrix.jld" f = h5py.File(filename, 'r') data= f["a"][()] column_ptr=f[data[2]][:]-1 ## correct indexing from julia (starts at 1) indices=f[data[3]][:]-1 ## correct in...
python|python-2.7|julia|hdf5
1
8,062
33,878,179
Use value of variable rather than keyword in python numpy.savez
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.savez.html#numpy.savez" rel="nofollow">numpy.savez</a></p> <p>In the last example, using savez with **kwds, the arrays are saved with the keyword names.</p> <pre><code>outfile = TemporaryFile() np.savez(outfile, x=x, y=y) outfile.seek(0) npzfile = ...
<p>You could make a dictionary and then use <code>**</code> to pass its contents in the form of keyword arguments to <code>np.savez</code>. For example:</p> <pre><code>&gt;&gt;&gt; x = np.arange(10) &gt;&gt;&gt; y = np.sin(x) &gt;&gt;&gt; x_name = 'foo' &gt;&gt;&gt; y_name = 'bar' &gt;&gt;&gt; outfile = TemporaryFile...
python|arrays|numpy|keyword
5
8,063
47,071,450
Concatenate a variable number of lists in Python
<p>I have a number of lists called: index_1, index_2, index_3, ...., index_n.<br> What I want is to concatenate them all in a new list.</p> <p>My code so far:</p> <pre><code>index_all=[] for i in range(1,n+1): index_all = index_all + globals()["index_"+str(i)] </code></pre> <p>However, I get an error:</p> <b...
<p>you may want to use map and filter , and the globals().items() feature:</p> <pre><code>concat_list = map ( lambda list_var : list_var[1] , filter ( lambda list_var : list_var[0].startswith("list"), globals().items())) </code></pre> <p>your concat_list is the list of all items from all lists</p>
python|list|concatenation
1
8,064
67,759,732
histogram subplots with multiple axes
<p>I have 4 sets (i.e bbs) of 3 .csv files (i.e. replicas) with 2 columns each: time (X-Axis) and interaction Frequency (Y-Axis 1). I also need to plot error bars to a second y axis which i have achieved. Since they have similar paths, I am reading them through filename = with %s for each set and replica.</p> <p>Right ...
<p>For simplicity, I create the following data set:</p> <pre><code>data = pd.DataFrame([[0.0, 0.368683 , 16,3], [1.0, 0.364314 , 15, 1], [2.0 , 0.358840 , 16 , 3], [3.0 , 0.321033 , 17 , 3], [4.0 , 0.361127 ,17 , 3]], columns=[&quot;time&quot;, &quot;distance&quot;, &quot;mol&q...
python|pandas|matplotlib|multiple-axes
0
8,065
57,137,703
Multidimensional array reshape with numpy
<p>I've been stuck on this numpy operation for a while now. I have an <code>np.array</code> of <code>np.shape</code> (x, y, z) that I want to make into an array of <code>np.shape</code> (y, x, z). I am having a hard time understanding the order on which <code>np.reshape</code> is done. For instance, I would like the va...
<p>I think what you are looking for is <code>swapaxes</code>:</p> <pre><code>np.swapaxes(x,0,1) #x is your array </code></pre>
python|numpy
2
8,066
27,797,705
python login 163 mail server
<p>When I use this script to login the 163 mail server,there is something wrong! My python env is python 2.7.8 Please help me!</p> <pre><code>import imaplib def open_connect(verbose=False): host = 'imap.163.com' port = 993 if verbose:print 'Connecting to',host connection = imaplib.IMAP4_SSL(host) ...
<p>After netease blocking your own client, they will send you an email named <strong>网易邮箱提醒:阻止了一次不安全的收信请求</strong> by <code>mail@service.netease.com</code>.</p> <p>On the bottom of the email, they provided a link to the configure page:</p> <p><a href="http://config.mail.163.com/settings/imap/index.jsp?uid=YOUR_EMAIL_...
python|email|imap
4
8,067
27,432,540
How to convert API timestamp into python datetime object
<p>I am getting the following string from an API call:</p> <pre><code>s = '2014-12-11T20:46:12Z' </code></pre> <p>How would I then convert this into a python object? Is there an easy way, or should I be splitting up the string, for example:</p> <pre><code>year = s.split('-')[0] month = s.split('-')[1] day = s.split(...
<p>You can use the <a href="https://docs.python.org/3/library/datetime.html" rel="nofollow"><code>datetime.datetime.strptime</code></a> function:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; s = '2014-12-11T20:46:12Z' &gt;&gt;&gt; datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ') datetime.datetime(2...
python|datetime|timestamp|rfc3339
2
8,068
27,470,712
Append single package folder to sys.path
<p>I use a script under virtualenv, that requires bzrlib package which is not available in my virtualenv but is included in my system python packages: <code>/usr/lib/python2.7/dist-packages/bzrlib/</code></p> <p>If I want to use it, one option is to extend sys.path, but I would have to include the parent folder <code>...
<p>What about creating a link in different directory and importing using that? Or even in your own project.</p> <pre><code>ln -s /package/dir/path /project/dir/path </code></pre> <p>If you have to load it remotely, here is the link provided by @unutbu showing how to do it:</p> <p><a href="https://stackoverflow.com/q...
python
1
8,069
72,291,476
Why is the difference of my two images blank?
<p>I tried to get the difference of two images. Here are my two images.</p> <p><a href="https://i.stack.imgur.com/rybih.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rybih.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/5CNIp.png" rel="nofollow noreferrer"><...
<p>This works fine for me in Python/OpenCV using cv2.absdiff(). I suggest you use cv2.imshow() to view your results and cv2.imwrite() to save your results.</p> <pre><code>import cv2 import numpy as np image1 = cv2.imread('image1.png') image2 = cv2.imread('image2.png') diff = cv2.absdiff(image1, image2) print(np.amin(...
python|opencv|matplotlib|image-processing
2
8,070
43,098,028
Assign a particular ID to each item in a list and generate a new list with repeated IDs
<p>I have 2 lists, each have 5 items in them. But the items in the 'start' list are lists:</p> <pre><code>start = [[3606,5599,6312,7897], [2394], [84,1046], [1046], [1]] id = ['AB022430', 'AB024537', 'AB043103', 'AB051349', 'AB051628'] </code></pre> <p>I would like to created a new list with the format (I'm thinking...
<p>You can use a list comprehension:</p> <pre><code>[(ID, v) for ID, val in zip(id, start) for v in val] #[('AB022430', 3606), # ('AB022430', 5599), # ('AB022430', 6312), # ('AB022430', 7897), # ('AB024537', 2394), # ('AB043103', 84), # ('AB043103', 1046), # ('AB051349', 1046), # ('AB051628', 1)] </code></pre>
python|list|zip
1
8,071
43,312,282
Unable to install python-levenshtein package on Mac using Python 3.6
<p>I was trying to install the <code>python-levenshtein</code> library using terminal. However, I kept encountering errors. The Python version that I am using is Python 3.6 and the command I had been using to install the package is <code>pip install python-levenshtein</code>.</p> <p>Could someone tell me what I am doi...
<p>For Anaconda users, it is better use the following command as it helped in my case:</p> <pre><code>conda install -c conda-forge python-levenshtein </code></pre>
python|python-3.x
2
8,072
48,507,077
Running parametric tests in Python
<p>I usually keep my parametric tests as follow</p> <pre><code>class ShouldCheckSomeCondition(unittest.TestCase): def __init__(self, parameters...): ... def runTest(): # given ... cases = [(p1, ...), (p2, ...), ...] </code></pre> <p>Then build them at the bottom of the file and create a main to ru...
<p>since you're working with nose i'd say have a look at <a href="https://pypi.python.org/pypi/parameterized" rel="nofollow noreferrer">parameterized</a> which is a continuation from <a href="https://pypi.python.org/pypi/nose-parameterized/" rel="nofollow noreferrer">nose-parameterized</a></p>
python|unit-testing|python-unittest|nose
0
8,073
69,548,378
Implementing decorators in a Python C/C++ extension that can wrap/decorate functions in Python
<p>Python decorators are a very &quot;pythonic&quot; solution to a lot of problems. Because of this, I'd like to include a pre-defined decorator in my C-extension that can decorate functions that are called in Python files that include my extension.</p> <p>I can't seem to find anything in the CPython api documentation ...
<p>For problems like this, it's often helpful to first mock things up in Python. In your case, I expected there'd be two benefits:</p> <ul> <li><p>If you do end up implementing the decorator entirely in an extension module, this will help you understand how it should work and what state will be held by which objects yo...
python|c|cpython|python-c-api
0
8,074
48,240,021
Alter edge length and cluster spacing in networkx/matplotlib force graph
<p>I'm trying to use python to output a PNG of a force graph using networkx and matplotlib. Here's what it currently looks like:</p> <p><a href="https://i.stack.imgur.com/Gi3if.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gi3if.png" alt="networkx/matplotlib force graph"></a></p> <p>The nodes ove...
<p>I've found a way to make this work, by using <code>graphviz_layout()</code> rather than <code>spring_layout()</code> (thanks to a tip found <a href="https://stackoverflow.com/questions/46031272/preventing-overlap-of-edges-and-nodes-with-netwrokx-matplotlib/48260769#48260769">here</a>). This requires installing some ...
python|d3.js|matplotlib|graph|networkx
3
8,075
48,046,883
Sprite moving faster left than right pygame
<p>I think I'm having a rounding problem causing my sprite to move faster/jump farther while moving left.</p> <p>My sprites update method is calling move, which calls move_single_axis for each axis. Inside this I'm doing some collision detection where I rely on pygame's rect class to both detect the collision, and set...
<p>I ripped out everything except for the hero and the <code>QuestGame</code> class and could see the incorrect movement, so the problem was not caused by <code>pyscroll</code> (unless there are more issues). </p> <p>The reason for the movement problems is that you set the <code>self._position</code> in the update met...
python|pygame|pytmx
1
8,076
51,195,348
Give a list and an image as input to a keras model
<p>I want to give an image and a list to a keras model for a GAN. The discriminator will get image and some list both are of fixed size i.e. 128x128x3 and 384 and the generator will produce images of 128x128x3 that the disc has to mark fake. So the problem is that I can't figure out what should be the input shape for t...
<p>One possible fix I can think of is appending the same embedding to the generator output before feeding it to the discriminator input and loss computation. </p>
python|tensorflow|input|keras
0
8,077
73,777,566
Cleaning many string variables at once with strip()
<p>I'm trying to get rid of two special character combinations from all my variables with strip. is there a better way to do this with a loop?</p> <pre><code>currentdisk = currentdisk.strip(&quot;└─&quot;) currentdisk = currentdisk.strip(&quot;├─&quot;) currentmpath = currentmpath.strip(&quot;└─&quot;) currentmpath = c...
<ol> <li>Group all variables in a dict.</li> <li>Iterate over with your 2 strip operations.</li> <li>Get each variable by key.</li> </ol> <pre><code># 1. fill the dict my_values = { 'currentdisk': currentdisk, 'currentmpath': currentmpath, 'currentpartition': currentpartition, 'volumegroup': volumegroup...
python
1
8,078
73,773,052
Need a sequence that grows by 1 until a certain number
<p>I'm very new to coding and I'm trying to figure out how to make a sequence that grows like 1+(1+1)+(2+1)+(3+1)+(4+1) etc. until it reaches exactly 180 (in python). So pretty much adds 1 to the last answer. Then when it reaches 180 it should come back down like (&quot;last number of going up&quot;-1)-(&quot;last resu...
<p>Your pseudo code looks like it reveals some C or C++ thinking.</p> <p>I guess you simply need a <strong>for</strong>-loop:</p> <pre><code>import numpy as np for angle in np.arange(0,181,1): print(f'{angle=}') </code></pre> <p>The <strong>arange</strong> function, as it is used here, takes two or three arguments...
python
0
8,079
17,392,488
Dictionary syntax error while getting top 20 results using dictionary in python
<p>I have an input file, each line of which has a set of words. Next i take a query and compute similarity scores between each line of the input file and the query. I am trying to do this by using dictionary, keeping the maximum size of dictionary as 20(to get top 20 results, if sorted by value) But i'm getting the fol...
<p>As the error says, you <strong>can't</strong> assign to a function call:</p> <pre><code>result.item()[20].key()=str(line) </code></pre> <p>which is exactly what you're trying to do!</p> <p>as I don't understand how you got the <code>result</code> object, I can't give you a better advice on how to change the value...
python|dictionary|syntax-error
2
8,080
64,385,830
Getting n gram suffix using sklearn count vectorizer
<p>I am trying to get 1,2,3 gram suffix for a word and use them as features in my model.</p> <p>Example,</p> <pre><code>word = &quot;Apple&quot; 1 gram suffix = 'e' 2 gram suffix = 'le' 3 gram suffix = 'ple' </code></pre> <p>I have used <code>CountVectorizer</code> in sklearn with <code>ngram_range=(1,3)</code> but ...
<p>Yo can define a custom <code>analyzer</code> to define how the features are obtained from the input. For your case, a simple lambda function to obtain the suffixes from a word will suffice:</p> <pre><code>from sklearn.feature_extraction.text import CountVectorizer word = [&quot;Orange&quot;,&quot;Apple&quot;, &quot...
python|machine-learning|scikit-learn|nlp|n-gram
5
8,081
64,261,980
update\replace df [cols] by df [cols]
<p>i have two df with the same index, and i like to update\replace list of cols only when name==&quot;A&quot;.</p> <p>so where i got name==&quot;A&quot; i want it to replace lits of cols -&gt;cols=[col1,col2,col3,col4]</p> <p>so i have this df</p> <pre><code>first_data={&quot;col1&quot;:[2,3,4,5,7], &quot;col2&quot;:[4...
<p>IIUC you can <code>update</code>:</p> <pre><code>df1 = df1.set_index(&quot;name&quot;, append=True) df1.update(df2[df2[&quot;name&quot;].eq(&quot;A&quot;)].set_index(&quot;name&quot;, append=True).filter(like=&quot;col&quot;)) </code></pre> <p>If you don't need to care about the column <code>name</code> and solely ...
python|pandas|replace|updates
1
8,082
73,504,964
Trying to remove an item from a list using a variable
<p>Made a number guessing game, automatically updates a list of facts based off the random number the program creates. If user guesses incorrectly, the program offers a hint from the list. I want the program to remove this hint from the list after it is used, so there are no duplicates.</p> <p>I tried to assign X as a ...
<p>The function <code>random.choice</code> does not return a random number, it returns a random value from the sequence you pass as an argument. You are setting <code>x = random.choice</code>, meaning <code>x</code> is now the function <code>random.choice</code> so passing that to the <code>pop()</code> function will t...
python|list
1
8,083
66,420,109
Keras training and trainable attribute in BN Layer
<p>As stated <a href="https://keras.io/api/layers/normalization_layers/batch_normalization/" rel="nofollow noreferrer">here</a></p> <blockquote> <p>However, in the case of the BatchNormalization layer, setting trainable = False on the layer means that the layer will be subsequently run in inference mode (meaning that i...
<p>Okay. So, I got the answer from <a href="https://keras.io/guides/transfer_learning/" rel="nofollow noreferrer">here</a></p> <blockquote> <p>When you unfreeze a model that contains BatchNormalization layers in order to do fine-tuning, you should keep the BatchNormalization layers in inference mode by passing training...
tensorflow|keras|deep-learning|neural-network
0
8,084
64,725,932
discord.py send a message if author isnt in a voice channel
<p>I want my bot to send a message if im not in a voice channel when i type a command.</p> <p>Heres my current code:</p> <pre><code>@client.command() async def play(ctx): channel = ctx.author.voice.channel if channel: await channel.connect() await ctx.send('Joining voicechat.') elif channe...
<p><code>Member.voice</code> will be None, you need to check that</p> <p>Below is the revised code:</p> <pre class="lang-py prettyprint-override"><code>@client.command() async def play(ctx): channel = ctx.author.voice if channel: await channel.channel.connect() await ctx.send('Joining voicechat...
python-3.x|discord.py
1
8,085
63,819,326
Get Options from Models post on Html Django
<p>I'm having some issues trying to get the list out of the model and print it dynamically on my HTML view. Here's what I've done so far, and what I've got as view.</p> <p>models.py</p> <pre><code>class Projeto(models.Model): acoes = ( ('', &quot;---------&quot;), ('Projeto', &quot;Projeto&quot;), ...
<p>You just need to access the individual properties of the tuple in your template. Replace this:</p> <pre><code>{% for acao in acoes %} &lt;option name=&quot;{{acao}}&quot;&gt; {{acao}} &lt;/option&gt; {% endfor %} </code></pre> <p>with</p> <pre><code>{% for acao in acoes %} &lt;option name=&quot;{{acao.0}}&quot...
python|html|django
0
8,086
63,766,698
Time difference between some actions in a pandas DataFrame
<p>I have dataframe of members of a site and action they have done in specific time from time =0 :</p> <pre><code>import pandas as pd times = [21 , 34, 37, 40, 55, 65, 67, 84, 88, 90 , 91, 97, 104,105, 108] names = ['bob', 'alice', 'bob', 'bob', 'ali', 'alice', 'bob', 'ali', 'moji', 'ali', 'moji', 'ali', 'bob', 'bob', ...
<p>Try with <code>cumsum</code> and do the subgroupby key, then we do <code>groupby</code> with <code>np.ptp</code></p> <pre><code>df['new'] = df.action.eq('purchase').iloc[::-1].groupby(df.name).cumsum() df = df.drop_duplicates(['name','action','new'],keep='last') s = df.loc[df.action.isin(['enter','purchase'])].group...
python|pandas|dataframe
1
8,087
53,224,094
Forecasting multiple series on python using autoarima or SARIMAX
<p>I am trying to forecast multiple time series that exist in a single dataframe. However I am struggling with the loop. In my head, I want to go through each column (each product), forecast using autoarima, save the results in a new dataframe and move onto the next.</p> <p>The dataframe looks as follows</p> <p>Date|...
<p>With the AutoArima of github.com/statsforecast you can train multiple series. You just need your data to be in the following formar |Product Nr|Date|Vale</p>
python|for-loop|time-series|forecasting|arima
1
8,088
65,342,815
Python loop files
<p>I have the script below that basically queries an api that transcribes an audio. However at the moment I am putting one audio at a time, I would like to help because inside the 'audios' folder I have a list of .wav files. What would be the best way to read all .wav files</p> <pre><code>import requests from datetime...
<p>The <a href="https://docs.python.org/3/library/glob.html" rel="nofollow noreferrer">glob</a> module provides useful function for accesing file names that match a pattern:</p> <pre class="lang-py prettyprint-override"><code>import glob for filename in glob.glob(&quot;audios/*.wav&quot;): with open(filename) as a...
python|python-3.x
-1
8,089
65,267,772
FileNotFound : [WinError 2] The system cannot find the file specified” Error while using selenium
<p>I am on Windows pro 10 and using Firefox to execute the python selenium program. Trying to run:</p> <pre><code>from selenium import webdriver wb = webdriver.Firefox() wb.get(&quot;https://stackoverflow.com&quot;) </code></pre> <p>Getting the following error(please ignore the web browser in the error message) :</p> ...
<p>As clearly mentioned in the error message, very first install the appropriate browser driver and give its path to the <code>system variable</code> path. Like in my case:</p> <pre><code>from selenium import webdriver driver_path = r&quot;G:\Python\geckodriver.exe&quot; #since on windows use raw strings wb = webdrive...
python|python-3.x|selenium|selenium-webdriver
0
8,090
71,813,771
How to replace brackets by using regex
<p>I have written a calculator for solving quadratic equations, using cmath.</p> <p>So far I've successfully replaced 'j' into 'i' in the results, but failed to find a way to replace the brackets and the &quot;0i&quot; (if exist).</p> <pre><code>import cmath a_2 = float(input('a: ')) b_1 = float(input('b: ')) c_0 = flo...
<p>Take a look at <code>str.replace()</code> or <code>str.strip()</code>. It will be much simpler and intuitive than using regex. (Same thing applies to your replacing <code>j</code> with <code>i</code>)</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; sol1i.strip(&quot;)(&quot;) '-1+0i' &gt;&gt;&gt; # ...
python|string
1
8,091
68,590,044
Sum value between overlapping interval slices per group
<p>I have a pyspark dataframe as below:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd from pyspark.sql import SparkSession spark = (SparkSession.builder .master(&quot;local&quot;) .getOrCreate()) spark.conf.set(&quot;spark.sql.session.timeZone&quot;, &quot;UTC&quot;) INPU...
<p>You can use <a href="http://spark.apache.org/docs/3.1.1/api/python/reference/api/pyspark.sql.functions.sequence.html" rel="nofollow noreferrer">sequence</a> to expand the intervals into single days, <a href="http://spark.apache.org/docs/3.1.1/api/python/reference/api/pyspark.sql.functions.explode.html" rel="nofollow...
python|pyspark|intervals|overlap
1
8,092
68,572,835
How to add file to github repo in python
<p>I have a folder inside a branch in a repository. I want to add a file to that folder from python. I looked at the github api docs but the examples are in js and it is confusing to me. Can anyone give an example of how to add a file to a github repo in python? I would appreciate it.</p>
<p>You have quite a few options:</p> <ol> <li>Use PyGit2 which binds libgit2: <a href="https://www.pygit2.org/" rel="nofollow noreferrer">https://www.pygit2.org/</a></li> <li>Use GitPython which wraps calls to <code>git</code> binary: <a href="https://gitpython.readthedocs.io/en/stable/tutorial.html" rel="nofollow nore...
python|github
0
8,093
71,764,689
Writing data in csv file using pandas
<p>I am trying to write data into a csv file Rest all the fields are getting written fine , but not the date field can someone please explain me what is going wrong</p> <p>Here is my code</p> <p>def writeData(self):</p> <pre><code> query_string=f'https://query1.finance.yahoo.com/v7/finance/download/{self.ticker}?per...
<p>First of all, column B in the screenshot is not wide enough so all values show <code>########</code>, it's impossible for us to see the actual output values.</p> <p>Secondly, make sure the datetime values are actually interpreted as datetime datatypes when reading the file. So add <code>dayfirst=True, parse_dates=Tr...
pandas|dataframe|csv
0
8,094
62,483,776
Why is text within inner tag ignored, how to fix it?
<pre><code>&lt;p&gt;The latest media Tweets from Yohir Akerman (@yohirakerman). My bio changes all the time. /// akermancolumnista&lt;strong&gt;@gmail.com&lt;/strong&gt;. Airplane&lt;/p&gt; </code></pre> <p>I try to extract the entire text as follows:</p> <pre><code> body = response.xpath('//*[@id="b_results"]/p/t...
<p>Dont use <code>text() </code>. Inside</p> <pre><code>body = response.xpath('//*[@id=&quot;b_results&quot;]/p&quot;).getall() print(body) </code></pre> <p>Then join body and clean body of all tags.</p>
python|html|beautifulsoup
1
8,095
61,856,512
Pandas - filter dataframe with sorted index
<p>I have this <code>df_player_means</code>, with 5 items:</p> <pre><code>Pierre-Emerick Aubameyang 0.629630 Sergio Aguero 0.592593 Danny Ings 0.555556 Mohamed Salah 0.538462 Sadio Mane 0.500000 </code></pre> <p>And this <code>df_player_colors</code...
<p>IIUC, try with <code>join</code> and <code>drop_duplicates</code> maybe if you have duplicated colors for same player</p> <pre><code>df_player_means.to_frame(name='mean')\ .join(df_player_colors.to_frame(name='color'), how='left')\ .drop_duplicates() </code></pre> <p>or maybe with loc...
python|pandas
2
8,096
60,724,333
Python Selenium Chrome Webdrives closes unexpectedly after the execution of program
<p>I have updated the version of chrome and accordingly webdriver. The chrome closes automatically after the execution of the last line. It was a simple code to open a chrome driver and click the links. After I run in command prompt it generated the error message <strong><em>"failed to load pepper module from internal-...
<p>I've experienced this (quite) a while ago. In my case an Adobe Flash Player update was required for Chrome: in <code>chrome://components</code> find the Adobe Flash Player entry and check for updates.</p> <p>Alternatively, disable extensions:</p> <pre><code>options = webdriver.ChromeOptions() options.add_argument(...
python|selenium|google-chrome|webdriver
0
8,097
62,290,956
Category detection
<p>i have used this code for category detection..</p> <pre><code>import numpy as np # Words -&gt; category categories = {word: key for key, words in data.items() for word in words} # Load the whole embedding matrix embeddings_index = {} with open('glove.6B.100d.txt', encoding="utf8") as f: for line in f: value...
<pre><code>def process(query): query_embed = embeddings_index[query] scores = {} for word, embed in data_embeddings.items(): category = categories[word] dist = query_embed.dot(embed) dist /= len(data[category]) scores[category] = scores.get(category, 0) + dist return max(scores, key=scores.get) ...
python|glove
0
8,098
59,022,483
Writing a composite Key in Flask SQL Alchemy
<p>I have my table like something below:</p> <pre><code>class Dummies(db.Model): __tablename__ = 'dummies' id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(100), index=True, nullable=True) value = db.Column(db.String(100), index=True, nullable=True) sum_...
<p>If you want enforce the unique constraint on multiple columns you can explicitly set it like this: </p> <pre><code> __tablename__ = 'dummies' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), nullable=True) value = db.Column(db.String(100), nullable=True) sum_id = db...
python|sqlalchemy
0
8,099
49,016,683
Python dictionaries formatting
<p>Python3 I have a dictionary with alphabet count, shown below</p> <pre><code>a 24873 b 5293 c 7301 d 15567 e 38088 f 6499 g 7109 h 20360 i 20283 j 751 k 3207 l 12780 m 7686 n 21510 o 24944 p 5275 q 191 r 16751 s 18831 t 30897 u 9624 v 2551 w 8390 x 439 y 7139 z 161 </code></pre> <p>and i want a function to print it...
<p>You can use <code>dict.items()</code> to get the key-value pairs as a list of tuples. Then sort this list by the value.</p> <p>For example:</p> <pre><code>d = { 'a': 24873, 'b': 5293, 'c': 7301, 'd': 15567 } for k, v in sorted(d.items(), key=lambda x: x[1], reverse=True): print("{} {}".format(...
python-3.x|dictionary|tabular
1