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
4,100
60,080,589
How To Combine Parsed TextFiles In Apache-Beam DataFlow in Python?
<p>This seems to work fine in DirectRunner, but errors out when I switch to DataflowRunner. I basically need to somehow combine the files that are read in, but as soon as I use <code>beam.combiners.ToList()</code> to concatenate my data, it introduces a whole slew of issues. </p> <p><strong>Code Example:</strong> </p>...
<p>Given this error, I suspect that <code>MatchFiles</code> is not actually matching anything (e.g. due to a bad filepattern) and, consequently, the output of <code>beam.combiners.ToList</code> is an empty list. </p>
python|pandas|parallel-processing|google-cloud-dataflow|apache-beam
1
4,101
2,755,833
Renaming TurboGears 2's Repoze Fields with TGAdmin
<p>I've been working on renaming TurboGears 2's Repoze <em>'groups'</em> field to <em>'roles'</em> to free the namespace and db tables for other purposes. Also roles makes much more sense to me then groups because I have a strong Drupal background.</p> <p>Now I have found some of the docs to do this such as these:</p>...
<p>Why cross post with the TurboGears mailing list? <a href="http://groups.google.com/group/turbogears/browse_thread/thread/e6040eb194880fc6/" rel="nofollow noreferrer">http://groups.google.com/group/turbogears/browse_thread/thread/e6040eb194880fc6/</a></p> <p>This just duplicates efforts for people trying to help you...
python|pylons|turbogears2|repoze.who
0
4,102
67,825,043
python correct rounding for dataframe/series
<p>before OP takes down my question, please note that I have viewed posts: <a href="https://stackoverflow.com/questions/31206487/pandas-python-round-not-behaving-correctly">pandas python - round() not behaving correctly</a></p> <p><a href="https://stackoverflow.com/questions/56820/round-doesnt-seem-to-be-rounding-prope...
<p>I realised that I have made this more complicated than it seems, I have just done a little trick, all I had to do was just to add 0.00000001 say into the number and the rounding can be done in the normal way.</p> <pre><code>round(2.25+0.000001, 1) -&gt; 2.3 </code></pre>
python|pandas|dataframe|rounding|series
0
4,103
42,715,738
Pandas: how to compare columns of imported csv files to ensure they are the same?
<p>I have huge data split into 4 csv files. They are supposed to have the same columns and each file is the continuation of the previous. I import the 4 CSV files in Pandas and before merging them I want to compare the columns for all 4 to identify any difference.</p> <ol> <li>How do I do that with Pandas/Python?</li>...
<p>When knowing your column names beforehand, you can explicitly pass them to the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>pd.read_csv</code></a> via the <code>usecols</code> parameter. In case of a column name mismatch between your csv file an...
python|csv|pandas
3
4,104
66,693,266
How to store wise data in a chunks in multiple csv files from list of tuples
<p>I have a list of tuples and I need to write this data in multiple CSV files based on ranges like 500 data in each and every CSV file.</p> <p>The example of data_list:</p> <pre><code>data_list = [(10.01,20.11),(34,20),(33,88),(44,90),(43,99)] </code></pre> <p>In above list I want two tuple in one csv file. so form th...
<p>You can use nested loop. Outer loop will divide the list into sublists. And using inner loop you can write the sublist data to file.</p> <p>You can change the <code>rows_per_file</code> as needed</p> <pre><code>import csv data_list = [(10.01,20.11),(34,20),(33,88),(44,90),(43,99)] fields = ['A','B'] file_name = 'o...
python|list|csv|tuples
0
4,105
65,743,957
Is it a mandatory to have two classes(Node,Tree) while implementing a binary tree?
<p>This may sound silly but trust me , I have searched for various articles online and could not find a proper explanation or no explanation at all , Does it really need two classes one for Node and one for tree to implement binary tree? for Instance , let's take a simple python code :</p> <pre><code>class Node(): ...
<p>You <em>can</em> implement a tree with only a single class, but it will have a much more limited API than you could implement with two separate classes. There are a number of situations where having a separate container object makes a lot more sense, and a single-class implementation will need its users to handle sp...
python|class|object|data-structures|binary-tree
1
4,106
50,975,389
NaN with softmax cross entropy in simple model with dummy inputs
<p>I was simplifying my model in order to see where the NaN error occurs and narrowed it down to my loss function:</p> <pre><code>import tensorflow as tf from tensorflow.python import debug as tf_debug def train_input_fn(): pass def model_fn(features, labels, mode, params): classes = 225 enc = tf.ones((1,20,...
<p>I've tried your given code. I was getting NaN right from the first step. </p> <p>And I've checked the <a href="https://www.tensorflow.org/api_docs/python/tf/nn/sparse_softmax_cross_entropy_with_logits" rel="nofollow noreferrer">official documentation</a>.</p> <pre><code>logits: Unscaled log probabilities of shape ...
python|tensorflow|cross-entropy
1
4,107
50,753,610
TypeError: 'str' object is not callable Flask Redirect
<p>I can't get Flask to redirect! </p> <p>I keep getting a </p> <pre><code>File "/Users/kyle.calica-steinhil/Code/wcp2018/wcp18/app/app.py", line 32, in slackRedirect return redirect(url) TypeError: 'str' object is not callable </code></pre> <p>I have no idea why this is not working. I'm passing a string in redi...
<p>You are redefining what <a href="http://flask.pocoo.org/docs/1.0/api/#flask.redirect" rel="nofollow noreferrer">redirect</a> means. <code>redirect</code> redirects client to target location, so just rename <code>redirect</code> to something else, following line:</p> <pre><code>redirect_url='http://localhost:5000/' ...
python|flask
1
4,108
3,848,829
How to map a list of data to a list of functions?
<p>I have the following Python code:</p> <pre><code>data = ['1', '4.6', 'txt'] funcs = [int, float, str] </code></pre> <p>How to call every function with data in corresponding index as an argument to the function? Now I'm using the code:</p> <pre><code>result = [] for i, func in enumerate(funcs): result.append(...
<p>You could <a href="http://docs.python.org/library/functions.html#zip" rel="noreferrer">use <code>zip</code></a>* to combine many sequences together:</p> <pre><code>zip([a,b,c,...], [x,y,z,...]) == [(a,x), (b,y), (c,z), ...] </code></pre> <p>then you could iterate on this new sequence and make each function apply o...
python|list|function|arguments|mapping
9
4,109
50,430,093
How to avoid double inhertince
<p>I am trying to devlop a qt application and I have decided to make an abstract class named window that inherts from QWidget each window, diaoluge will inhert from her, and will include the basic proprties that window should have. Right now one of the classes that inherts from window also inhert from QMainWindow. My p...
<p>Another option instead using inheritance would be using <a href="https://en.wikipedia.org/wiki/Composition_over_inheritance" rel="nofollow noreferrer">composition</a>, here's a little example:</p> <pre><code>import sys from PyQt5.Qt import * # noqa class GuiBuilder(): def __init__(self, widget, name): ...
python|inheritance|pyqt
0
4,110
50,666,057
Unexpected complex numbers in Python
<p>I'm trying to calculate a total score for a decathlon participant and there are two formulas given, one is for a field events and the other is for track events.</p> <p><code>Points = INT(A(B — P)^C) for track events (faster time produces a better score)</code></p> <p><code>Points = INT(A(P — B)^C) for field events...
<p>The problem is a mix up of metres and centimetres. The Wikipedia page is slightly inaccurate in its recount of the formulae - throws are measured in <strong>metres</strong> but jumps should be measured in <strong>centimetres</strong>. This is why you're getting fractional powers of negative numbers.</p> <p>See the ...
python|python-3.x|math
1
4,111
44,911,474
Cannot install matplotlib on Intel Edison
<p>I am trying to install matplotlib on my Intel Edison board but I am taking errors. I installed Numpy and Spicy successfully but could not manage to install matplotlib. </p> <p>I am getting this error</p> <pre><code>root@edisonwbl:~# pip install matplotlib Collecting matplotlib /usr/lib/python2.7/site-packages/pip/...
<p>I will suggest you to uninstall python and install <strong><a href="https://www.continuum.io/downloads" rel="nofollow noreferrer">Anaconda2</a></strong> for python 2.7. It comes with all necessary module, including matplolib, numpy, pandas all.</p> <p>follow this link: <a href="https://www.continuum.io/downloads" r...
python-2.7|matplotlib|yocto|intel-edison
0
4,112
45,084,538
How to use %d to insert an array into a string of text?
<p>As a beginner at Python, I have learnt that when you want to insert some variable into a string of text, you use the generic format of </p> <pre><code>"Blah blah blah %d" % some_variable </code></pre> <p>And it will output </p> <pre><code>"Blah blah blah some_variable" </code></pre> <p>I am usually okay at doing...
<p><code>%s</code> can be used to represent any data. <code>str</code> will be called to convert the object to a string.</p> <p>You should also enclose multiple items in a tuple. Putting it all together:</p> <pre><code>print "The mean is of %s is %d" % (array, statistics.mean(array)) </code></pre>
python|arrays|vector
1
4,113
64,765,122
Python sys.argv and input combination with a definition NOT working
<p>I have a python script like below that I was trying to run in shell. I want to use either <code>argv</code> or <code>input</code> in order to give specific inputs called index1 and index2 (<code>ACCGTCG</code> and <code>TTCCAGC</code>) and a file name to process. I tried two ways (with sys.argv and input separately)...
<p>Instead of this</p> <pre><code>if __name__ == '__dual_index_positions__': dual_index_positions() </code></pre> <p>Use this</p> <pre><code>if __name__ == '__main__': dual_index_positions() </code></pre> <p><code>__name__ == '__dual_index_positions__'</code> the RHS of that is not the function name you have to...
python|input|pycharm|definition|argv
1
4,114
61,394,088
Finding neighbor cells in a grid with the same value. Ideas how to improve this function?
<p>I am new to Python (learning it for a little over 1 month) and I tried creating Tic Tac Toe. However once I finished it, I decide to expand the board (from 3x3 to 9x9 depending from the customer input) and allow a win by connecting 4 in a row, column or diagonal anywhere in the board.</p> <p>Therefore I needed a fu...
<p>Here's an approach that involves less copying and pasting -- hopefully it gives you some idea of how to break things down into the smallest number of the most reusable pieces possible. :)</p> <p>The general idea here is to come up with a way of expressing the concept of scanning a line across the board in differen...
python|matrix|grid|cell
2
4,115
58,055,560
How to split a long list into each column with equal member
<p>Now, I have a long list of str like this ['aaa','bbb','ccc,'ddd,'eee','fff','ggg','hhh','iii',.......] for 300 members</p> <p>I would like to group into each column with 5 members, the first 5 members go to column1 and the next 5 members go to column2 like this;</p> <p>column1 aaa bbb ccc ddd eee</p> <p>column2 f...
<p>This can be done by using the <i>numpy</i> library<br> Example:</p> <pre><code>import numpy as np #importing the library array = np.array(["aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii"]) #creating a numpy array array = array.reshape(3,3) #reshape the array into a 3x3 "table" array = np.swapaxes(array,0,1...
python-3.x
0
4,116
69,555,991
Regridding from one irregular lat lon grid to another irregular lat lon grid
<p>I have two sets of satellite data. For both sets, I have the pixel geometry (latitude and longitude of each corner of the pixel). I would like to regrid one set to the other. Thus, my goal is area-weighted regridding from an irregular grid to another irregular grid. I am aware of <a href="https://xesmf.readthedocs.i...
<p>I've ran into similar things in the past. I'm on Windows, and xEMSF wasn't really an option for me.</p> <p>I've written this package, and added some methods for computing grid to grid weights: <a href="https://github.com/Deltares/numba_celltree" rel="nofollow noreferrer">https://github.com/Deltares/numba_celltree</a...
python|python-xarray|netcdf4|python-iris
1
4,117
69,316,599
Unable to use multi target loss function in pytorch python
<p>I am unable to use loss function for a multi label classification in pytorch This is my loss function:</p> <pre><code> def loss(self,pred,y_true): pred = torch.tensor(pred) y_true = torch.tensor(y_true) loss = nn.NLLLoss()(torch.log(pred), y_true) return loss </code></pre> <p>On trying to get loss...
<p>I don't believe there is a builtin to compute the multi-label classification cross-entropy. <a href="https://pytorch.org/docs/stable/generated/torch.nn.functional.nll_loss.html#torch.nn.functional.nll_loss" rel="nofollow noreferrer"><code>F.nll_loss</code></a> and <a href="https://pytorch.org/cppdocs/api/function_na...
python|deep-learning|neural-network|pytorch|loss-function
0
4,118
55,506,478
reading data from json file then writing into an embed?
<p>So I was working on a new feature on a discord bot that would tell you all the parties(clans) in the server, and the clan info is stored inside a json file, I would like to send it to the user though send_message(), but it keeps returning this error: discord.ext.commands.errors.CommandInvokeError: Command raised an ...
<p>I suggest you just send a limited amount of information to the users the allow them to get more detailed info via different commands or make them view it on webpage</p> <pre class="lang-py prettyprint-override"><code>data={"clan2": {"Members": "ShareYourGraves#9977"}, "clan1": {"Members": "||CATENARY||#9105,"}} as...
python|python-3.5|discord|discord.py
1
4,119
57,559,249
How could I form a regular expression in which in some cases it starts with * and in others not in python
<p>Good morning I have a question about a regular expression that I am forming the question is that what I want to capture in some cases starts with * and in others not, example:</p> <pre><code>*B:P79COL01 # A:PED77MCY04 # </code></pre> <p>The regular expression I am using to capture this value is as follows:</p> ...
<pre><code>\*?[AB]:(.*?) # </code></pre> <p>Could work.</p> <p><code>\*</code> escapes the * character allowing us to match it.</p> <p><code>?</code> matches 0 or 1 occurrences of the preceding character, which seems to be the core issue of your issue.</p> <p><code>(.*?)</code> matches anything between the <code>:<...
python
0
4,120
42,328,426
gitPython not working from git hook
<p>I am trying to build a git hook in this case post-receive however it only works when called directly from shell.</p> <p>A minimal example script:</p> <pre><code>#! /bin/env python3 import git rep = git.Repo("/var/www/cgi-bin/deployed.everland") print(rep.git.status()) </code></pre> <p>results in the following er...
<p>As it happens I just found the/a solution.</p> <p>The gitPython wrapper does not ignore environment variables. So even though I opened the git repository with a specified directory it is somehow still trying to use the directory specified in <code>GIT_DIR='.'</code>. So in my case I had to delete that variable with...
git|python-3.x|githooks
1
4,121
42,248,376
Stuck using fonts on tkinter for python 3.x.
<p>Basically, I can't set the "underline" and "overstrike" options. My code works perfectly until I try to add those parameters in as a label font:</p> <blockquote> <p><em>Large_Font = ("Verdana", 10, "bold", "italic", <strong>"underline and overstrike"</strong>)</em></p> <p>...</p> <p><em>Lbl = tk.Label(f...
<p>You should create a new <a href="https://www.tutorialspoint.com/python/tk_fonts.htm" rel="nofollow noreferrer"><code>Font</code></a> instance and change its <code>underline</code> and <code>overstrike</code> attributes to <code>True</code>.</p> <pre><code>from tkinter import font large_font = font.Font(family="Ver...
python|python-3.x|tkinter
1
4,122
59,271,717
Override global variable inside function not working with Spyder 4
<p>I try to override globally defined Dataframes from within a function. Somehow the global values do not change, printing the dataframes within the functions works with the expected values.</p> <pre><code>import pandas as pd rawData = pd.read_csv("music.csv") appTitles =pd.DataFrame #also with pd.DataFrame() wont g...
<p>(<em>Spyder maintainer here</em>) You need to go to the menu</p> <p><code>Run &gt; Configuration per file</code></p> <p>and activate the option called <code>Run in console's namespace instead of an empty one</code>, for you to be able to modify global variables in your code.</p>
python|pandas|dataframe|spyder
5
4,123
45,721,086
K-means cluster given a CSV with (tf-idf cosine similarity, doc_id1, doc_id2)?
<p>I have a CSV with the following dataset:</p> <pre><code>similarity | doc_id1 | doc_id2 1 | 34 | 0 1 | 29 | 6 0.997801748 | 22 | 10 0.966014701 | 35 | 16 0.964811948 | 14 | 13 </code></pre> <p>Where "similarity" refers to a value from tf-idf...
<p>I believe that your problem is that you have distances, but K-Means uses Euclidean distances from centroids. This means, that you will need a vector for each document, pretty long vectors in your case. Instead of calculated similarity you should use one dimension for all word, and the score for that word in each doc...
python|csv|cluster-analysis|tf-idf|cosine-similarity
1
4,124
41,401,209
Display Camera in pyqt
<p>Can we display a camera feed in Pyqt? I can only display a simple view through the opencv window in python. I want to add some more options while displaying the pyqt window.</p>
<p>In that case, consider using a QGraphicsView. Its not only a way to display your camera image, but you can draw additional lines, or put text on it if you want. First you initiate it:</p> <pre><code># Create scene self.image_item = QGraphicsPixmapItem() scene = QGraphicsScene(self) scene.addItem(self.image_item) #...
python|opencv|pyqt
3
4,125
41,334,596
default text for foreign key in form in django
<p>I know that is the simple question but I have trouble with this I have a table that shows colors and I used this as foreign key in Post table</p> <pre><code>class Post(models.Model): """docstring for Post""" user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1 ) slug = models.SlugField(unique=T...
<p>In your model form, you can use <code>__init__()</code> to initialize your form. Something like:</p> <pre><code>from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ('post_title', 'color') # fields to show in your form def __...
python|django|forms|foreign-keys
2
4,126
6,606,291
How can I decode this utf-8 string, picked on a random website and saved by the Django ORM, using Python?
<p>I parsed a file and saved its content in a database using Django. The website was 100% in English, so I naively assumed it would be ASCII all along, and saved the text happily as unicode.</p> <p>You guess the rest of the story :-)</p> <p>When I print, I get the usual encoding error:</p> <pre><code>UnicodeEncodeEr...
<p>You are fine. You have the proper data. Yes, the original data is UTF-8 (based on context u2019 makes perfect sense as an apostrophe between "son" and "s"). The weird <code>?</code> error character probably just means your terminal configuration's font doesn't have a glyph for this character (fancy apostrophe). No...
python|django|encoding|utf-8
6
4,127
25,861,817
No output to Map Algebra ArcGIS from script
<p>I have issues with the Map Algebra function from ArcGIS.</p> <p>I have about 200 TIFF files for which I would like to multiply their attributes values by 1000. The script I wrote (see below) seems to work without error, but I don't get any output from it. Why is this?</p> <pre><code># Import system modules impor...
<p>add print gp.GetMessages() after your map algebra function to see if it gives you any idea what is happening</p>
python|arcgis|raster
0
4,128
44,811,157
Google Puzzle Euler Number
<p>This post is twofold. I am a neophyte to Python. </p> <h3>First part.</h3> <p>This is my code for the old Google puzzle: 'First 10 digit prime number in the consecutive digits of e' (<a href="https://google-tale.blogspot.ca/2008/07/google-billboard-puzzle.html" rel="nofollow noreferrer">https://google-tale.blogsp...
<p>For the first part, replace <em>'3'</em> with <em>'2'</em> so that it checks the 3rd digit for oddness, instead of the 4th:</p> <pre><code>euler[i + 3]== '1' or euler[i + 3]== '3' or euler[i + 3]== '7' or euler[i + 3]== '9'): </code></pre> <p>changes to</p> <pre><code>euler[i + 2]== '1' or euler[i + 2]== '3' or e...
python|eulers-number
1
4,129
44,538,316
How to use two tables with same name in two different schema in mysql with django
<p>I am using two mysql schemas X and Y, both contains multiple tables but there is one table that has same name in both the schemas.</p> <p>Both the schemas are as follows:</p> <pre><code>+--------------+--+--------------+ | X | | Y | +--------------+--+--------------+ | name | | albu...
<p>Given your <code>DATABASES</code> configuration, you can try:</p> <ol> <li><p>Change your Models name or create a new app with a different <code>models</code> module for each schema:</p> <pre><code>class YPhoto(models.Model): ... class XPhoto(models.Model): ... </code></pre></li> <li><p>Create a <code>rou...
mysql|django|python-3.x|django-orm
0
4,130
23,689,235
Django ModelForm not saving data
<p>I've tried solutions from the following posts: </p> <p><a href="https://stackoverflow.com/questions/13046488/saving-data-from-modelform">Saving data from ModelForm</a> : Didn't work</p> <p><a href="https://stackoverflow.com/questions/12164680/modelform-data-not-saving-django">ModelForm data not saving django</a> :...
<p>You are POSTing to <code>/testimonials/thanks/</code> which should be changed to your <code>add_testimonial</code> route to have your view handle the POST. So, the solution is to change the <code>action</code> value in your template's form tag.</p> <p>If you can post the relevant code from your urls.py I can provid...
python|django
5
4,131
23,698,543
Adding time to an existing file in python
<p>I want to update an existing file.txt in Python, which has two columns, one for days, and one for time, so that it will sum up a new time in another column on the same file.</p> <pre><code>Sunday 07:00 Monday 07:35 Tuesday 05:35 Wednesday 06:45 Thursday 08:40 </code></pre> <p>For example, adding...
<p>The <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow"><code>datetime</code></a> module is very helpful for this. It lets you create <a href="https://docs.python.org/2/library/datetime.html#time-objects" rel="nofollow"><code>time</code></a> objects and <a href="https://docs.python.org/2/library...
python|datetime|time
2
4,132
20,592,808
Add all elements of an iterable to list
<p>Is there a more concise way of doing the following?</p> <pre><code>t = (1,2,3) t2 = (4,5) l.addAll(t) l.addAll(t2) print l # [1,2,3,4,5] </code></pre> <p>This is what I have tried so far: I would prefer to avoid passing in the list in the parameters.</p> <pre><code>def t_add(t,stuff): for x in t: stu...
<p>Use <code>list.extend()</code>, not <code>list.append()</code> to add all items from an iterable to a list:</p> <pre><code>l.extend(t) l.extend(t2) </code></pre> <p>or</p> <pre><code>l.extend(t + t2) </code></pre> <p>or even:</p> <pre><code>l += t + t2 </code></pre> <p>where <code>list.__iadd__</code> (in-plac...
python|list|tuples
99
4,133
72,060,875
How to manipulate images and such in kivyMD
<p>I wrote this code but now i don't know how to manipulate my images so I am stuck i need help on how to add images if i have multiple screens and how to also add other labels so basically screen manipulation with multiple screens</p> <pre><code>from kivymd.app import MDApp from kivy.lang.builder import Builder from k...
<p>You can use <a href="https://kivy.org/doc/stable/api-kivy.uix.image.html?highlight=image" rel="nofollow noreferrer">Image</a> to put image</p> <pre><code>&lt;ProfileScreen&gt;: name: 'profile' Image: source: '/home/furas/test/lenna.png' MDLabel: text: 'Welcome Nate' ...
python|python-3.x|kivy|kivy-language|kivymd
0
4,134
49,438,437
Python Find string between given delimiters in function
<p>I am working on this game on checkio.org. Its a python game and this level I need to find the word between two defined delimiters. The function calls them. So far I have done alright but I can't get any more help from google probably because I don't know how to ask for what i need. </p> <p>Anyways I am stuck and I ...
<p>This is hackey with the nested <code>if b &gt; 5</code> but it works</p> <pre><code>def between_markers(text: str, begin: str, end: str) -&gt; str: s = text # find the index for begin and end b = s.find(begin) # -1 if not found c = s.find(end, b + len(begin)) # search only after begins match, -1 if not found ...
python-3.x
0
4,135
70,162,510
I clearly see a positional argument defined, so why is it giving me this error?
<p>I'm trying to condense my file format. I've changed the headers to match my function. It's worked previously, but with this new file I'm getting a positional argument error.</p> <pre><code>input_fname = 'basic.xlsx' # input filename output_fname = 'basic-condensed.xlsx' # output filename basic_all = pd.read_excel(...
<p>Just because you have a variable called <code>size_column</code> doesn't mean it was passed in the same/correct position that your function's signature expected.</p> <p>Take this example:</p> <pre class="lang-py prettyprint-override"><code>def foo(x, y, ax=None): return x + y y = 1 foo(y) </code></pre> <p>This ...
python|excel|pandas
1
4,136
53,603,429
ChromeDriver is too slower than GeckoDriver on the first page query through Selenium and Python
<p>I have the latest version of the drivers (chromedriver=2.44.609551), selenium package(3.141.0) and the (headless chrome=70.0.3538.110). (on windows)</p> <p>I am opening multiple windows with the browser. Using firefox, my script is always fast. But on chrome, after switching to a window (with the page already loade...
<p>As you mentioned in your question <em>GeckoDriver</em> / <em>Firefox</em> combination is faster then <em>ChromeDriver</em> / <em>Chrome</em> at this point it is worth to mention that diferent browsers render the <a href="https://www.w3schools.com/js/js_htmldom.asp" rel="nofollow noreferrer">HTML DOM</a> in a differe...
python|selenium|selenium-chromedriver|geckodriver|google-chrome-headless
2
4,137
45,987,959
SQLAlchemy relationship through 2 many-to-many tables
<p>I have the following models:</p> <pre><code>class A(Base): __tablename__ = 'A' a_id = Column(Integer, primary_key=True) class B(Base): __tablename__ = 'B' b_id = Column(Integer, primary_key=True) class C(Base): __tablename__ = 'C' c_id = Column(Integer, primary_key=True) class AB(Bas...
<p>You can use a custom secondary:</p> <pre><code>ab = AB.__table__ bc = BC.__table__ ac = select([ab.c.a_id, bc.c.c_id]).select_from(ab.join(bc, ab.c.b_id == bc.c.b_id)) A.c_collection = relationship("C", secondary=ac, primaryjoin=A.a_id == ac.c.a_id, secon...
python|sqlalchemy
2
4,138
45,826,816
Splitting with Regular Expression in Python
<p>I am relatively new to Python, and I am trying to split a string using re. I have researched a bit, and I have come across a few examples and I tried them out. They seem to work, but with limitation. </p> <p>I am using a dictionary with a string key that is associated with an integer value. I'm trying to apply a we...
<p>You can split using the <code>\W+</code> character, which will split at all not alpha string items and use <code>|_</code> to specifically search for underscores:</p> <pre><code>for key, value in sorted_articles.items(): wordList = print(re.split('\W+|_',key)) </code></pre> <p>For instance:</p> <pre><code>s =...
python|python-3.x
0
4,139
55,007,717
Calculating vorticity for multiple vertical levels in MetPy
<p>I'm trying to calculate vorticity in MetPy for multiple (consecutive) vertical levels. When I try to calculate it for a single level, everything works fine.</p> <p>Here's the code; I've used the example for cross sections from <a href="https://unidata.github.io/MetPy/latest/examples/cross_section.html#sphx-glr-exam...
<p>Unfortunately, the error message that comes up isn't that helpful in this case if you don't know what to look for!</p> <p>The problem with the <code>vorticity</code> function call in your example is that the dimensionality of your input variables do not match. <code>data['u_wind']</code> and <code>data['v_wind']</c...
python|metpy
2
4,140
33,336,881
How to get <a href>'s that appear after a specific <h2>?
<p>This is the layout of the webpage:</p> <pre><code>&lt;h2&gt;Featured Ads&lt;/h2&gt; &lt;a href=""&gt;&lt;/a&gt; &lt;h2&gt;Ads&lt;/h2&gt; &lt;a href=""&gt;&lt;/a&gt; </code></pre> <p>There is nothing in the <code>class</code> of the regular Ads that I can use to differentiate them. What would be an efficient way t...
<p>Locate the <code>h2</code> element and <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-next-siblings-and-find-next-sibling" rel="nofollow">find the next <code>a</code> sibling</a>:</p> <pre><code>h2 = soup.find("h2", text="Ads") a = h2.find_next_sibling("a") </code></pre>
python|html|html-parsing|beautifulsoup
2
4,141
13,061,520
In Python, how can I increment a count conditionallly?
<p>Say I have the list:</p> <pre><code>list = [a,a,b,b,b] </code></pre> <p>I'm looping over the list. The variable "count" increments by 1 when the previous letter is the same as the current letter. Below is only part of the code:</p> <pre><code>for item in list: if item == previous: count +=1 return cou...
<pre><code>def max_contiguous_repeat(data): max_repeats = 0 if data: previous = data[0] count = 0 for item in data[1:]: if item == previous: count += 1 continue max_repeats = max(count, max_repeats) previous = item count = 0 max_r...
python|increment
1
4,142
41,159,674
How to remove duplicate records from multiple lists in order in python
<p>I have three list with four values in each list, I have to remove duplicate values from these three list</p> <p>Here are three lists</p> <pre><code>country_list = ['USA', 'India', 'China', 'India'] city_list = ['New York', 'New Delhi', 'Beijing', 'New Delhi'] event_list = ['First Event', 'Second Event', 'Third Eve...
<p>One simple way is to do the following:</p> <pre><code>country_list = list(set(country_list)) city_list = list(set(city_list)) event_list = list(set(event_list)) </code></pre> <p>Hope this helps.</p>
python
3
4,143
40,872,882
Running out of memory, need alternatives
<p>I'm trying to run the following piece of code:</p> <pre><code>start_time = time.time() csvWriter = ModalitySessions.pivot(index='session_id', columns='context_eid', values='name') print("--- %s seconds ---" % (time.time() - start_time)) </code></pre> <p>which gives me the following error:</p> <pre><code>ValueErro...
<p>You could construct a Python <a href="https://wiki.python.org/moin/Generators" rel="nofollow noreferrer">generator</a> to return chunks of the CSV data at a time. In fact, this is why such a tool exists in Python. The generator could then be used to restrict the nubmer of rows loaded in to memory at any time.</p> <...
python|pandas|pivot
1
4,144
38,293,498
Django 1.9 + Passenger on Dreamhost: Web application could not be started
<p>I'm trying to use Django 1.9 (With Python 3.4) on Dreamhost shared hosting.</p> <p>I followed this tutorial: <a href="https://brobin.me/blog/2015/03/deploying-django-with-virtualenv-on-dreamhost/" rel="nofollow">https://brobin.me/blog/2015/03/deploying-django-with-virtualenv-on-dreamhost/</a></p> <p>And now my pas...
<p>This was solved by using the correct settings in the passenger_wsgi.py:</p> <pre><code>import sys, os cwd = os.getcwd() sys.path.append(cwd) project_location = cwd + '/my_project' sys.path.insert(0,project_location) INTERP = os.path.expanduser("/home/user/python/Python-3.4.3/venv/bin/python") if sys.executable !=...
python|django|passenger|dreamhost
1
4,145
38,326,787
memory management for dictionary in python
<p>I have following code , i don't understand the scenario behind this please any one can explain.</p> <pre><code>import sys data={} print sys.getsizeof(data) ######output is 280 data={ 1:2,2:1,3:2,4:5,5:5,6:6,7:7,8:8,9:9,0:0,11:11,12:12,13:13,14:14,15:15} print sys.getsizeof(data) ######output is 1816 data={1:2,2:1,3...
<blockquote> <p><code>getsizeof()</code> calls the object’s <code>__sizeof__</code> method and adds an additional garbage collector overhead if the object is managed by the garbage collector.</p> </blockquote> <p>Windows x64 - If did like below:</p> <pre><code>data={ 1:2,2:1,3:2,4:5,5:5,6:6,7:7,8:8,9:9,0:0,11:11,12...
python|python-2.7
0
4,146
58,864,113
How to Read file of specific pattern csv(regex) and create DataFrame in python using pandas
<p>I try to create the DataFrame using method to csv.in place of the path I want to give regex pattern so that all file with this pattern gets. But this I don't get the file as per my expectation.</p> <p>Please help me to solve the problem.</p> <pre><code>import pandas as pd df=pd.to_csv(path+"^\d{8}_\d{6}$",sep="|"...
<p>The solution have 2 steps. The first step is you have to find all path that match a specific pattern. The second one is you read data from each <code>DataFrame</code> and concat it after that. The pandas library do not support the 1 step (I think, need recheck soon). So you could use glob library for that.</p> <p><...
python|pandas
1
4,147
52,220,398
MemoryError in jupyter notebook
<p>having some in a jupyter notebook, that reads images into my memory. Unfortunately I get an MemoryError after reading about 2 GB into my memory (which is 64 GB). </p> <p>Anyone an idea why is that? Is it possible to assign more memory to jupyter notebook?</p> <p>Thanks in advance!</p>
<p>So in my special case, the problem was that I used a 32 bit version of python. I was wondering, because the script ran earlier without any problems on a 64 bit version. </p>
python|memory|jupyter-notebook
0
4,148
52,163,529
How to merge four tables in Pandas?
<p>I have four tables: <code>predicted_tags</code>, <code>actual_tags</code>, <code>tags_names</code> and <code>news_text</code>.</p> <p>In tables <code>predicted_tags</code> and <code>actual_tags</code> rows names are tags id. In these tables <code>1</code> means True and <code>0</code> means False.</p> <p>Shape of...
<p>First of all, create a column which holds all the actual/predicted values, such as:</p> <pre><code>predicted_tags['pred_loc'] = predicted_tags.values.tolist() actual_tags['actual_loc'] = actual_tags.values.tolist() </code></pre> <p>Also, if your tag_id (in <code>tag_names dataFrame</code>) is in the same order as ...
python|pandas
2
4,149
51,990,034
Simple LSTM model : No attr named '_XlaCompile' in name error
<p>I am very new to machine learning and I came across an error while attempting to make a simple LSTM model, and I am absolutely clueless how to debug this. I am using Keras version 2.2.2. My code looks more or less like this:</p> <pre><code>model = Sequential() model.add(Embedding(400001, emb_dim, trainable=False, i...
<p>I was using version 1.5.0 of TF initially, upgraded to v1.8.0 and all is working. Issue resolved.</p>
python|python-3.x|tensorflow|keras
1
4,150
68,973,234
Splitting on multiple delimiters but ignore emails, decimals and URLs
<p>I have this code where I split on different delimiters but still include at least one of the delimiters after a text.</p> <p>So if I had multiple <code>!!!</code>, I only retain one after the text. Now if I add an email or URL, it splits on the dot, something I do not want.</p> <p>How would I modify my regex to excl...
<p>This works</p> <pre><code>text = &quot;This is a test. I love it here!!!! I hate this weather!! What should I do?? It's great. My email is cmw@example.com. My website is www.example.com and it's been live for 2.5 months.Another sentence&quot; new_text = re.split(r'(?&lt;=\w[^a-z0-9\s])\W*\s?(?=[A-Z])', text) </code...
python|regex
2
4,151
62,420,515
Create a new Conditional Dataframe Series from multiple Dataframes
<p>I want to create a new data frame from multiple data frames in one statement.</p> <p>For Eg:</p> <pre><code>df.loc[(df[[A,B]].mean(axis=1) &lt;= Const1), 'D'] = df['F'] df.loc[(df[[A,B]].mean(axis=1) &gt; Const1) &amp; (df['E']&lt;=Const2), 'D'] = df['G'] df.loc[(df[[A,B]].mean(axis=1) &gt; Const1) &amp; (df['...
<p>Using <a href="https://numpy.org/doc/stable/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>np.select</code></a> as in the link provided, even if what you want the choices to be series and not constant, it works the same way. </p> <pre><code>import pandas as pd import numpy as np # example d...
python|pandas|dataframe
0
4,152
36,600,093
Performance of D3 treemap with large amounts of data
<p>So my issue is that I'm passing a large JSON file (I'm not sure of the exact size, but it's very very big) into a D3 zoomable treemap. </p> <p>I'm doing this by way of AJAX call to a Python backend. The performance of my browser just degrades completely when I load the file in, it takes 5-10 mins for it to even app...
<p>If simply loading the json is too heavy for the browser, then doing a complete rendering server-side would not help, as the rendered object would one way or another include the same amount of data.</p> <p>But I guess you cannot show that much data at once. Since you are going for a zoomable visualizer, you should p...
javascript|python|ajax|d3.js|flask
0
4,153
19,787,589
Importing python classes, relative to where?
<p>If I have a small python project split into a main directory with 2 subdirs:</p> <pre><code>src/ run.py subdir1/ __init__.py module1.py subdir2/ __init__.py module2.py </code></pre> <p>In order to include module2 in module1 would I...
<p>There are two ways to import module:</p> <ol> <li>absolute import</li> <li>relative import</li> </ol> <p>Absolute import makes python to look for desired module in directories stored in <code>sys.path</code> Relative import address to module relative to current module. You can use relative import inside python pac...
python|module|include
3
4,154
22,005,911
Convert columns to string in Pandas
<p>I have the following DataFrame from a SQL query:</p> <pre><code>(Pdb) pp total_rows ColumnID RespondentCount 0 -1 2 1 3030096843 1 2 3030096845 1 </code></pre> <p>and I want to pivot it like this:</p> <pre><code>total_data = total_rows.pivot_table(cols...
<p>One way to convert to string is to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="noreferrer">astype</a>:</p> <pre><code>total_rows['ColumnID'] = total_rows['ColumnID'].astype(str) </code></pre> <p>However, perhaps you are looking for the <a href="http://pandas.p...
python|pandas|string|type-conversion
540
4,155
43,668,346
Alternate method to avoid loop in pandas dataframe
<p>I have the following dataframe:</p> <pre><code>table2 = pd.DataFrame({ 'Product Type': ['A', 'B', 'C', 'D'], 'State_1_Value': [10, 11, 12, 13], 'State_2_Value': [20, 21, 22, 23], 'State_3_Value': [30, 31, 32, 33], 'State_4_Value': [40, 41, 42, 43], 'State_5_Value': [50, 51, 52, 53], ...
<p>I was able to accomplish this with no loops using the following code:</p> <p>As a result on my 10k x 200 table it ran in 3 minutes instead of the previous 2 hours.</p> <p>Unfortunately now I need to run it on a 10k x 4k table, and I hit MemoryError on that one, but it may be out of the scope of this question.</p> ...
python|performance|python-2.7|loops|pandas
0
4,156
71,114,450
Is there a way to use set().issubset() in an order-aware way in python?
<p>I am trying to check if shorter tuples are contained inside a longer one, but I need the order in which things are placed in the larger tuple to be respected during the checking. Here is an example:</p> <pre><code>A = ('A', 'B', 'C') B = ('A', 'B') C = ('A', 'C') set(B).issubset(A) set(C).issubset(A) </code></pre> <...
<p>as stated in the comments: this makes no sense as &quot;sets'.</p> <p>However, if all your elements are strings, the behavior of the &quot;in&quot; operator for strings may be enough for you. In order for it work you can join your tuples in a single string and then check with &quot;in&quot;:</p> <pre><code>&quot;&qu...
python|tuples|subset
0
4,157
9,248,821
Python Sparse matrix inverse and laplacian calculation
<p>I have two sparse matrix A (affinity matrix) and D (Diagonal matrix) with dimension 100000*100000. I have to compute the Laplacian matrix L = D^(-1/2)*A*D^(-1/2). I am using scipy CSR format for sparse matrix.</p> <p>I didnt find any method to find inverse of sparse matrix. How to find L and inverse of sparse matri...
<p>In general the inverse of a sparse matrix is not sparse which is why you won't find sparse matrix inverters in linear algebra libraries. Since <code>D</code> is diagonal, <code>D^(-1/2)</code> is trivial and the Laplacian matrix calculation is thus trivial to write down. <code>L</code> has the same sparsity pattern ...
python|linear-algebra|sparse-matrix|matrix-inverse
1
4,158
38,966,084
Batching for a non-image data set with Tensorflow
<p>I am a beginner in tensorflow. I have a data set with 43 inputs and one output. I am gonna create a mini-batch of the data to run deep learning. </p> <p>Here are my inputs:</p> <pre><code>x = tf.placeholder(tf.float32, shape=[None, 43]) y_ = tf.placeholder(tf.float32, shape=[None]) </code></pre> <p>which I am fe...
<p>The <code>tf.train.batch</code> and other similar methods are based on Queues, which are best fit in parallel loading huge amount of samples asynchronously. The document <a href="https://www.tensorflow.org/versions/r0.10/how_tos/threading_and_queues/index.html#threading-and-queues" rel="nofollow">here</a> describes ...
python|random|tensorflow|batching
0
4,159
39,010,204
How to create unique pair in dataframe using pandas
<p>I have dataframe of few records as following: </p> <pre><code>1 0 1 0 1 1 1 1 0 0 0 1 0 0 0 1 1 0 0 1 0 1 1 0 0 1 0 1 0 0 1 0 1 1 1 </code></pre> <p>I want to make a pair of two rows from the above dataframe randomly with no repetition. The output should look like this:</p> <pre><code> 0 1 2 3 4 5 6 0 1 ...
<p>You can use <code>np.random.permutation</code>. <code>permutation</code> returns a randomly rearranged version of the array like thing being permuted.</p> <p>To get what you asked for, run <code>permutaion</code> on the index</p> <p>consider the <code>df</code></p> <pre><code>df = pd.DataFrame([[1, 0, 1, 0, 1, 1...
python-3.x|pandas
1
4,160
39,321,495
AttributeError: 'list' object has no attribute 'isdigit'
<p>I want to extract POS in pandas. I do as below</p> <pre><code>import pandas as pd from nltk.tag import pos_tag df = pd.DataFrame({'pos': ['noun', 'Alice', 'good', 'well', 'city']}) s = df['pos'] tagged_sent = pos_tag(s.str.split()) </code></pre> <p>but get a traceback:</p> <pre><code>Traceback (most recent call l...
<p>You can actually pass <code>Series</code> object to the <code>pos_tag()</code> method directly:</p> <pre><code>s = df['pos'] tagged_sent = pos_tag(s) # or pos_tag(s.tolist()) print(tagged_sent) </code></pre> <p>Prints:</p> <pre><code>[('noun', 'JJ'), ('Alice', 'NNP'), ('good', 'JJ'), ('well', 'RB'), ('city', 'NN...
python|nltk|pos-tagger
2
4,161
55,150,419
Comparing Values in Dictionary with Multiple Matching Keys
<p>I have two dictionaries which store product ids as the key and timestamps as the value. The problem is that I have repeating keys with unique values. For example:</p> <pre><code>Dict1 | Dict2 ABCDEF: 12:39:00 | ABCDEF: 10:02:00 ABCDEF: 15:45:00 | ABCDEF: 16:40:00 ABCDEF: 18:30:...
<p>As nicolishen commented, all keys in a dict must be unique. For any given key, your dict will only include the last value added to the original pair of lists.</p> <p>You'll need a different data structure. Consider a dict that contains a single entry for each product ID. The value for that entry could be a pair ...
python|python-2.7|dictionary
1
4,162
52,474,130
When should I use setUpClass and when use just a class member?
<p>When using Python's built-in unittest, there are at least 2 different ways to organize class-level settings, using <code>setUpClass()</code> or just use old-school class member. When to use one, and when another?</p> <pre><code>class TestFoo(unittest.TestCase): @classmethod def setUpClass(cls): cls...
<p>In fact, the 2 snippets in the question above work largely the same, except when you are going to use the <code>@skipUnless(condition)</code> decorator.</p> <pre><code>SETTINGS = json.load(...) @unittest.skipUnless("foo" in SETTINGS, "skipped") class TestFoo(unittest.TestCase): @classmethod def setUpClass...
python|python-unittest
-1
4,163
52,678,357
how a function in python is getting called by just typing the name of function and not using brackets
<p>First of all to find "lcm" of two numbers I made a function <code>lcm(a, b)</code>. Then I thought of finding "hcf" too so I made a decorator <code>decor</code> and defined a function <code>hcf(a, b)</code> in it. And then I returned this function by just typing the name of the function and I didn't put brackets wit...
<p>I don't think you understand decorators. Let's make a minimal example.</p> <pre><code>def my_decorator(some_function): def new_function(*args, **kwargs): 'announces the result of some_function, returns None' result = some_function(*args, **kwargs) print('{} produced {}'.format(so...
python|python-3.x|python-decorators
6
4,164
47,841,513
Is it possible to set a maximum number of retries shared between all pool connections in the same session?
<p>Currently I do the following for setting a maximum number of connection retries for my <code>grequest</code> wrapper:</p> <pre><code>self._s = Session() retries = Retry(total=5, status_forcelist=[500, 502, 503, 504]) self._s.mount('http://, HTTPAdapter(max_retries=retries)) </code></pre> <p>I then create a bunch o...
<p>I think you are out of luck. The <code>Retry</code> docstring says (excerpt):</p> <blockquote> <p>Each retry attempt will create a new Retry object with updated values, so they can be safely reused.</p> </blockquote> <p>So a new object is made, like you said, every connection...and that's done by design.</p> <p...
session|request|python-requests|grequests
0
4,165
37,284,682
Scraping data from a table in drug reports with scrapy
<p>I'm trying to use Scrapy to scrape data from Erowid.org (curated database of drug trip reports). I'm using a modified version of <a href="http://github.com/DavidYi1/Drug-Forum-Data-Mining" rel="nofollow noreferrer">http://github.com/DavidYi1/Drug-Forum-Data-Mining</a>. This allows me to crawl the website and export ...
<p>You can select the dara using xpaths:</p> <pre><code>In [49]: sub = response.xpath("//td[@class='dosechart-substance']/a/text()").extract_first() In [50]: dose = response.xpath("//td[@class='dosechart-amount']/text()").extract_first() In [51]: form = response.xpath("//td[@class='dosechart-form']/b/text()").ext...
python|python-2.7|web-scraping|scrapy|scrapy-spider
1
4,166
34,385,050
Loop through all nested dictionary values and modify value meeting criteria
<p>I'm making regex based search engine. </p> <p>For example if a query matches <code>(?P&lt;filename&gt;\d+@\d+)</code> then I want to run the query <code>{"table": "records", "filter": {"filename": "*filename"}}</code>. But before doing so I want to replace "*filename" with say "2786@20150510201045". </p> <p>So bas...
<pre><code>def myprint(d, groups): new_d = {} for k, v in d.items(): if isinstance(v, dict): new_d[k] = myprint(v, groups) elif isinstance(v, str): new_d[k] = groups[v[1:]] if v.startswith('*') else v else: new_d[k] = v return new_d </code></pre>
python
0
4,167
34,054,706
Opening ExcelFiles Read-only with Xlwings
<p>I've started looking at xlwings for my excel manipulation as the power and speed of python is much different then VBA for what I am hoping to do. (or so I am told)</p> <p>Reading through some of the xlwings documentation I couldn't see if there was a way to open an excel file as read-only. Sometime the file I want ...
<p>What about making a copy of the file, reading that copy, then deleting that copy after? Alternatively, if you use openpyxl, you dont need to "open" the file since you are reading the xml metadata of excel.</p> <pre><code>import openpyxl as xl workbook = xl.load_workbook('path/to/file.xls') worksheet = workbook.get...
python|xlwings
1
4,168
7,219,135
exe created by cx-freeze gives me a error
<p><strong>Log.py</strong></p> <pre><code>import logging import logging.handlers class Log: def __init__(self): FILENAME='LOG' logging.basicConfig(level=logging.INFO) root_logger = logging.getLogger('') logger = logging.handlers.TimedRotatingFileHandler(FILENAME,'midnight',1) ...
<p>Without a stack trace, i can only advise you to try base="Console".</p>
python-3.x|cx-freeze
1
4,169
16,269,442
Sets vs. Regex for string lookup, which is more scalable?
<p>Suppose that I need to handle a very big list of words, and I need to count the number of times I find any of those words in a piece of text I have. Which is the best option in terms of scalability?</p> <p>Option I (regex)</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = re.compile("|".join(big_list)) &gt;&g...
<p>If your words are alphanumeric, I might use something like:</p> <pre><code>s = set(big_list) sum(1 for x in re.finditer(r'\b\w+\b',sentence) if x.group() in s) </code></pre> <p>Since the membership test for a set is on average O(1), this algorithm becomes O(N+M) where N is the number of words in the sentence and M...
python|regex|data-structures|set
2
4,170
31,900,369
Python Potato Cannon
<p>Could someone tell me why the result for height is always 0.00m / -0.00m?</p> <p>What did I do wrong? </p> <pre><code>import math g = 9.8 v = 60 angle = float(input("Angle: ")) def distance(v, angle, g): angle2 = angle * 2 d = v**2 * math.sin(math.radians(angle2))/g return d distance = distance(v,...
<p>You're computing the height of the cannonball (or whatever it is) at the time that it returns to the ground. Which is always zero.</p> <p>You want to pass <code>time / 2</code> into the height calculation (since you're ignoring air resistance here).</p>
python|python-3.x|physics
1
4,171
38,529,807
How do I unit test a method that sets internal data, but doesn't return?
<p>From what I’ve read, unit test should test only one function/method at a time. But I’m not clear on how to test methods that only set internal object data with no return value to test off of, like the setvalue() method in the following Python class (and this is a simple representation of something more complicated):...
<h2>The misconception</h2> <p>The real problem you have here is that you are working on a false premise:</p> <blockquote> <p>If unit test law dictates that we should test every function, one at a time...</p> </blockquote> <p>This is not at all what good unit testing is about.</p> <p>Good unit testing is about decomposi...
python|unit-testing
10
4,172
40,734,895
count and print unique values from python dict
<p>my python dict looks like</p> <pre><code>{'1, ': (' name', '10G')} {'2, ': (' name', '10G')} {'3, ': (' name2', '40G')} {'4, ': (' name2', '40G')} </code></pre> <p>Keys are 1 to 4 and values are name* , *G</p> <p>result I want to get using python : no of 10G entries = 2 and no of 40G entries...
<p>You can simply use <code>Counter</code></p> <pre><code>&gt;&gt;&gt; a = { '1, ': (' name', '10G'), '2, ': (' name', '10G'), '3, ': (' name2', '40G'), '4, ': (' name2', '40G') } &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; c = Counter(a.val...
python-2.7
0
4,173
40,727,042
Python to return multiple different strings that all begin with the same character
<p>I am trying to get python to print out every single occurrence of the character '@' and an undetermined number of characters that comes after it in a .txt document. Not sure if I need to split the entire document up by ' ' and put it into a list, then slice the list? I'm extremely new to all programming.</p> <p>Thi...
<p>i assume you're trying to get all user mentions here. splitting tweets with a space sounds right to start with. you could simply use startswith('@') to look for words beginning with '@'</p> <pre><code>string=tweets_obj.read().replace('\n', ' ') mentions = [] mentions.append(i for i in string.split(' ') if i.startsw...
python|string|slice
0
4,174
26,308,166
How to register an app with django.admin?
<p>I am following the <a href="https://docs.djangoproject.com/en/1.7/intro/tutorial01/" rel="nofollow">django tutorial</a> and am having some trouble registering my app with the admin interface.</p> <p>For reference, I made some slight alteration to the documented "polls" app. Here is my model.py:</p> <pre><code>imp...
<p>You must import your model in <code>admin.py</code>, currently you are missing it.</p> <p>Write at the <code>admin.py</code>: <code>from polls.models import Survey</code></p>
python|django|django-admin
4
4,175
63,109,212
How to push the data from dynamodb through stream
<p>Below is the json file</p> <pre><code>[ { &quot;year&quot;: 2013, &quot;title&quot;: &quot;Rush&quot;, &quot;actors&quot;: [ &quot;Daniel Bruhl&quot;, &quot;Chris Hemsworth&quot;, &quot;Olivia Wilde&quot; ] }, { ...
<p>This lambda just writing the document to DynamoDb, and I will not recommend adding the code in this lambda to push the same object to Elastic search, as lambda function <strong>should perform a single task</strong> and pushing the same document to ELK should be managed as a <strong><a href="https://docs.aws.amazon.c...
python|amazon-web-services|elasticsearch|aws-lambda|amazon-dynamodb
2
4,176
32,539,611
Tkinter, calling a function with arguments
<p>I've recently finished a simple command line Othello game and am now trying to create a GUI for it. My thought was that I would press a frame in an 8 by 8 grid and that that would call my place_tile function (method) with the frames coordinates. I've been able too call functions that require arguments with buttons b...
<p>You can use default arguments to the lambda function , Example -</p> <pre><code>def dummy(frameobj): pass background = Frame(root, height=100, width=100) background.bind("&lt;Button-1&gt;", bye) button = Button(root, text="Bye", command=lambda frameobj=background:hello(frameobj)) </code></pre> <p>When the lam...
python|function|button|tkinter|frame
1
4,177
32,287,729
how to filter objects in Django
<p>models.py</p> <pre><code>class CampaignType(models.Model): name = models.CharField(max_length=100) class Campaign(models.Model): name = models.CharField(max_length=200, unique=True) campaign_type = models.ForeignKey(CampaignType) </code></pre> <p>Target to achieve:</p> <pre><code>for i in CampaignTyp...
<p>Rather than trying to filter manually, you should just be using the reverse relationship accessors that Django provides for you automatically.</p> <pre><code>{% for campaigntype in campaigntypes %} {% for campaign in campaigntype.campaign_set.all %} {{ campaign.name }} {% endfor %} {% endfor %} </c...
python|django
1
4,178
54,843,010
What is an Invalid Resolution Tuple?
<p>I have a Raspberry Pi camera which has a 'best resolution' of 1080p according to the <a href="https://www.amazon.co.uk/Raspberry-Camera-IR-CUT-Vision-Module/dp/B0768Z87JF" rel="nofollow noreferrer">specs</a></p> <p>I have a small script which doesn't achieve anything apart from changing some settings. </p> <pre><c...
<p><code>camera.resolution</code> should be set to a <em>tuple</em> with two integers:</p> <pre><code>camera.resolution = 1920, 1080 </code></pre> <p>Note the comma. From the <a href="https://picamera.readthedocs.io/en/latest/api_camera.html#picamera.PiCamera.resolution" rel="nofollow noreferrer"><code>PiCamera.resol...
python|python-3.5|raspberry-pi3
2
4,179
28,141,435
pandas dataframe substring df['column1'].str[:'column2']
<p>I have a dataframe (df) with columns (A=object, B=int64) what I need is to be able to get a substring of 'A' based on the value of 'B'.</p> <p>I want to get 'C' like this:</p> <pre><code> A B C ===== ===== ========================= Jimmy 4 Jimm Tommy 2 To Karl 3 Kar Jane 1 J ==...
<p>The following works but it won't be fast as it's operating as a loop over every row, the key thing here is to pass param <code>axis=1</code> to operate row-wise and we can than access each column's value:</p> <pre><code>In [46]: df['C'] = df.apply(lambda x: x['A'][:x['B']], axis=1) df Out[46]: A B C 0 ...
python|pandas|lambda|substring
2
4,180
44,368,166
Syntax for HTTP methods in same def using Swagger
<p>I am new to SwaggerUI. In my python code, I have an API called 'work' which supports POST, PUT and DELETE HTTP methods.</p> <p>Now I want to create Swagger Documentation for the same. I am using the following code:</p> <pre><code>@app.route('/work', methods=['POST', 'PUT', 'DELETE']) def work(): """ Micro Serv...
<p>If you are using Flasgger (<a href="http://github.com/rochacbruno/flasgger" rel="nofollow noreferrer">http://github.com/rochacbruno/flasgger</a>) Sadly it does not support defining different HTTP methods in the same docstring yet, there is this <a href="https://github.com/rochacbruno/flasgger/issues/60" rel="nofollo...
python|flask|swagger|swagger-ui|flasgger
1
4,181
32,858,502
Python requests to get Yahoo finance data
<p>I'm trying to use this Yahoo Finance API with Python 2.7 and Requests.</p> <p>Entering in this URL returns the data I need without an issue.</p> <p>URL - <a href="http://chartapi.finance.yahoo.com/instrument/1.0/BHP.AX/chartdata;type=quote;range=1d/csv" rel="nofollow">http://chartapi.finance.yahoo.com/instrument/...
<p>OK, the simple answer is I was using HTTP in python, but the API wanted HTTPS. Explained in another answer here.</p> <p><a href="https://stackoverflow.com/questions/28557466/python-requests-exception-connectionerror-connection-aborted-badstatusline">Python requests.exception.ConnectionError: connection aborted &quo...
python-2.7|python-requests|yahoo-finance
0
4,182
32,630,870
Sympy: How to find longest expression that all N expressions have in common
<p>I have N expressions in Sympy and I need to find the longest expression that all N expressions have in common (like the longest expression is in/contained in all that N expressions)</p> <pre><code>from sympy import Symbol from sympy.logic.boolalg import And, Not, Or a = Symbol("a") b = Symbol("b") expr0 = And(And(...
<p>SymPy objects have the <em>.has( ... )</em> method:</p> <pre><code>&gt;&gt;&gt; expr1.has(expr0) True &gt;&gt;&gt; expr2.has(expr0) False </code></pre> <p>Regarding the rest of Python (i.e. not SymPy), you should better define what you mean by shared expression. Logical operations are usually supposed to return a...
python|sympy|boolean-logic
3
4,183
14,096,189
Creating DampedRotarySpring in pymunk between a dynamic body and a moving static body
<p>I'm trying to do what the title says. I have a character with a gun constrained to its hand, and I'm trying to get the gun to point at the cursor. I figured that a DampedRotarySpring would be a nice way to do it, but it turns out not to be as simple as that. The gun is a dynamic body with a Segment shape, and for th...
<p>The problem with the code in the gist is that you have attached the gun to the hand with two joints to keep them in the same place and same rotation. However, the the hand is a rouge body and wont rotate. Therefor the gun wont rotate when its pulled by the spring between it and the cursor, because that other joint i...
python|pygame|physics|chipmunk|pymunk
2
4,184
26,964,180
No way to convert this string to raw format for parsing
<p>I am writing a program to find the latency of the following IP: '141.101.115.212' (A game server)</p> <p>To find the latency I use the following commands:</p> <pre><code>x = subprocess.Popen(["ping.exe", "141.101.115.212"], stdout=subprocess.PIPE) x = str(x.communicate()[0]) </code></pre> <p>If I print x, I find ...
<p>The problem is there are two back slashes in the string, and you need the specify to split at the first string.</p> <p>the problem</p> <pre><code>lhs, rhs = rhs.split("\\") </code></pre> <p>the solution</p> <pre><code>lhs, rhs = rhs.split("\\", 1) </code></pre>
python
1
4,185
7,731,411
How can I check the data transfer on a network interface in python?
<p>There is a socket method for getting the IP of a given network interface:</p> <pre><code>import socket import fcntl import struct def get_ip_address(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR ...
<p>The best way to poll ethernet interface statistics is through SNMP...</p> <ul> <li><p>It looks like you're using linux... if so, load up your <code>snmpd</code> with these options... after installing <a href="http://www.net-snmp.org/" rel="nofollow"><code>snmpd</code></a>, in your <strong>/etc/defaults/snmpd</stron...
python|linux|networking|snmp|pysnmp
7
4,186
42,011,701
Turn list of strings with mixed inherent types into inherent type
<p>So I have a list of strings, each of which have inherent types.</p> <pre><code>mixedbag = ['True', '2.7', '3', 'Ninety'] </code></pre> <p>I want to transform this to look like this:</p> <pre><code>[True, 2.7, 3, 'Ninety'] </code></pre> <p>What I thought of is to create a large try/except chain to evaluate each i...
<p>You could use <a href="https://docs.python.org/2/library/ast.html#ast.literal_eval" rel="nofollow noreferrer"><code>ast.literal_eval</code></a> in a try-except block. </p> <pre><code>from ast import literal_eval def unmix(ele): try: ele = literal_eval(ele) except ValueError: pass return ...
python|list|types
5
4,187
47,258,599
Python BeautifulSoup remove items with <br/> tags from list
<p>I have a BeautifulSoup object (web page), and I've honed in on one HTML paragraph of interest. It has several items in it, and I'd like to clean out the junk (anything other than text).</p> <p>I have the items from the paragraph in a list after calling the paragraph's Contents attribute (e.g. paragraph_name.content...
<p>It depends what output format you are looking for. Using <code>soup.p.text</code> will give you all the text, but this will include leading spaces. Python can be used to split the text into lines and strip the extra space from each line. This can then be joined back together if required:</p> <pre><code>from bs4 imp...
python|html|list|beautifulsoup|list-comprehension
0
4,188
57,526,586
Library to extract data from open Excel workbooks
<p>I am trying to extract data from workbooks that are already open. </p> <p>I have found the <a href="https://pypi.org/project/xlrd/" rel="nofollow noreferrer">xlrd library</a>, but it appears you can only use this with workbooks you open through Python. The workbooks I will use in my project have already been opened...
<p>Open a workbook test.xlsx currently open in Excel, and read the value in cell A1 of the first worksheet:</p> <pre><code>from win32com.client import GetObject xl = GetObject(None, "Excel.Application") wb = xl.Workbooks("test.xlsx") ws = wb.Sheets(1) ws.Cells(1, 1).Value </code></pre> <p>Read a range as a tuple of t...
python|excel|python-3.x|pycharm
6
4,189
11,578,382
Comapring dictionary with list type values
<p>I have the following 2 dictionaries,</p> <pre><code>d1={"aa":[1,2,3],"bb":[4,5,6],"cc":[7,8,9]} d2={"aa":[1,2,3],"bb":[1,1,1,1,1,1],"cc":[7,8]} </code></pre> <p>How could I compare these two dictionaries and get the positions(indexes) of UNMATCHED key value pairs? since I am dealing with files of size around 2 GB,...
<pre><code>def getUniqueEntry(dictionary1, dictionary2, listOfKeys): assert sorted(dictionary1.keys()) == sorted(dictionary2.keys()), "Keys don't match" #check that they have the same keys for key in dictionary1: if dictionary1[key] != dictionary2[key]: listOfKeys.append(key) </code></pre> ...
python-2.7
1
4,190
11,732,792
Mechanize in Python - Redirect is not working after submit
<p>I just started using mechanize in Python and I'm having some problems with it already. I've looked around on StackOverflow and on Google and I've seen people say that the documentation is great and that it should be easy to get it working, but I think I don't know how to look for that documentation since all I can f...
<p><a href="http://wwwsearch.sourceforge.net/mechanize/documentation.html" rel="noreferrer">http://wwwsearch.sourceforge.net/mechanize/documentation.html</a></p> <p>Avoid using "_http" directly. The first underscore in a name tells us that the developer was thinking on it as something private, and you probably don't n...
python|mechanize|mechanize-python
8
4,191
37,923,403
Extracting data from .nc file by latitude and longitude in python
<p>I have gridded datasets in .nc format. I want to extract data on the basis of latitude and longitude. Latitude and longitude of my datasets are shown below:</p> <pre><code>import netCDF4 from netCDF4 import Dataset f= Dataset('data.nc') f.variables['lat'][:] array([ 31.5, 30.5, 29.5, 28.5, 27.5, 26.5, 25.5, ...
<p>This code will certainly not work:</p> <pre><code>f.variables['temp'][:,29.5,65.5] </code></pre> <p>since you can't (shouldn't) index with floats in <code>numpy</code> or <code>netcdf4</code>.</p> <p>If you want to index by value, I'd suggest checking out <a href="http://xarray.pydata.org/en/stable/" rel="nofollo...
python|numpy|gdal|netcdf
4
4,192
37,689,986
Finding files that have a numeric suffix in Python
<p>Prefacing this by saying I'm completely new to Python, but not new to programming.</p> <p>I've been experimenting with glob.glob in compiling lists of file names for further analysis.</p> <p>I have files that follow a format like the following:</p> <ul> <li>File 1.csv</li> <li>File 2.csv</li> <li>File 3.csv</li> ...
<p>You cannot match an arbitrary amount of digits with glob, if you wanted to specifically match <code>File some_digits.csv</code> you will need a regex:</p> <pre><code>import glob import re import os patt = re.compile(r"File \d+\.csv") for f in os.listdir("."): if patt.match(f): print(f) </code></pre> <p...
python
3
4,193
37,912,620
Splitting python list based on regular expression
<p>I have the following python list:</p> <pre><code>['chhattisgarh_2015_aa.csv', 'chhattisgarh_2016_aa.csv', 'daman_and_diu_2000_aa.csv', 'daman_and_diu_2001_aa.csv', 'daman_and_diu_2002_aa.csv'] </code></pre> <p>How do I separate it into 2 lists:</p> <pre><code>['chhattisgarh_2015_aa.csv', 'chhattisgarh_2016_aa.csv...
<p>Here is one way to get a dictionary, where for each "name" key the value is a list of the strings starting with that name, keeping the order of the original list. This does not use regex and in fact uses no modules at all. You can easily modify this to make a function, remove the trailing underscore from each name, ...
python|regex
4
4,194
37,957,018
How python can read the variables written in perl format?
<p>Hi my python code needs to read variable file (written in perl format) and recognize the variables to use in python script. My variable file (variable.txt) is written as:</p> <pre><code>$x=1.2; $y=90.2; $z=4.2334; $img1='version1.png'; $img2='version2.png'; </code></pre> <p>I would like my python code to read abov...
<p>I'd strongly suggest that you <em>don't</em> want to parse a variables file like this, and instead use a defined data transfer format.</p> <p>Looking at your source data - JSON looks a good bet. To make this easy, insert it into a namespace such as a hash:</p> <pre><code>#!/usr/bin/env perl use strict; use warning...
perl|python-2.7|variables
3
4,195
29,872,995
Numpy sum running length of non-zero values
<p>Looking for a fast vectorized function that returns the rolling number of consecutive non-zero values. The count should start over at 0 whenever encountering a zero. The result should have the same shape as the input array.</p> <p>Given an array like this:</p> <pre><code>x = np.array([2.3, 1.2, 4.1 , 0.0, 0.0, 5....
<p>This post lists a vectorized approach which basically consists of two steps:</p> <ol> <li><p>Initialize a zeros vector of the same size as input vector, x and set ones at places corresponding to non-zeros of <code>x</code>.</p></li> <li><p>Next up, in that vector, we need to put minus of runlengths of each island r...
python|arrays|performance|numpy|vectorization
5
4,196
30,029,997
Using py.test --cov from inside setup.py pytest.main
<p>I'm developing a package with some testing.</p> <p><strong>Working with CMD:</strong></p> <pre><code>py.test --cov my_pkg </code></pre> <p>I get the results with covarage:</p> <pre><code>--------------- coverage: platform win32, python 2.7.9-final-0 ---------------- Name Stmts Miss ...
<p>According to <a href="https://pytest.org/latest/usage.html#calling-pytest-from-python-code">the documentation</a> you should either do:</p> <pre><code>self.pytest_args = ["--cov", "my_pkg"] </code></pre> <p>or:</p> <pre><code>self.pytest_args = "--cov my_pkg" </code></pre>
python|pytest|test-coverage
11
4,197
56,966,341
Python: print condition
<p>I found that I just asked the wrong question a few minutes ago, sorry about that. I ran a code that need to identify if the word in certain location matches my condition. </p> <p>The original code is not in English, I just tried to use a simple way to show you the problem I had. There's actually no space between wo...
<p>Looks like you need Regex:</p> <pre><code>import re message="I do not dislike cars." check_list = {"like", "dislike", "hate", "cool"} pattern = re.compile(r"(\b{}\b)".format("|".join(check_list))) #or re.compile(r"({})".format("|".join(check_list))) m = pattern.search(message) if m: print(m.group(1)) # --&g...
python
2
4,198
27,435,259
pandas installation - numpy version is too old
<p>At my workplace, I use a Virtual Machine (VM) with a better hardware setup than my laptop to work with data (cleaning, organizing, analysis, etc.). I am trying to install Pandas from source (i.e., tar.gz) because the VM is locked down (i.e., it does not have access to hosts outside the company network). I receive t...
<p>I am not sure if this works, but you could try to install <code>pip</code> with this command <code>easy_install pip</code> on the terminal, and then use <code>pip</code> to update the <code>numpy</code> package. </p> <p>With this command <code>pip list --outdated</code> you can see which packages are outdated. </p>...
python|linux|pandas|installation|rhel
2
4,199
65,621,040
Scapy, Pycharm issue needs solving [Cannot find reference 'ARP' in 'all.py']
<p>Right... I've previously had this working correctly after about two days of slamming my head off my keyboard.... However, my SSD failed and I lost all my VM's and I dont remember what I did to solve this problem.</p> <p>After doing some research, I've came to the conclusion that the issue is with Pycharm and how it ...
<p>My solution is to use VS Code and pipenv instead of Pycharm as you get all the benifits of Pycharm withouts it's issues.</p> <ol> <li>Install pipenv globally using <code>sudo pip install pipenv</code></li> <li>Create a virtual enviroment using <code>pipenv install --python 3.8</code> for a specific version of python...
python|pycharm|scapy
0