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
600
42,257,512
Difference between subprocess.Popen preexec_fn and start_new_session in python
<p>What is the difference between these two options to start a new process with <code>subprocess.Popen</code> for <code>python3.2+</code> under <code>Linux</code>:</p> <pre><code>proc = subprocess.Popen(args, ..., preexec_fn=os.setsid) # 1 proc = subprocess.Popen(args, ..., start_new_session=True) # 2 </code></pre> ...
<p>According to the official <a href="https://docs.python.org/3.4/library/subprocess.html?highlight=subprocess#popen-constructor" rel="noreferrer">Python Docs</a>,</p> <blockquote> <p>The preexec_fn parameter is not safe to use in the presence of threads in your application. The child process could deadlock before exec...
python|subprocess|popen|kill-process|setsid
18
601
58,248,093
How can I make my dictionary be able to be indexed by a function in python 3.x
<p>I am trying to make a program that finds out how many integers in a list are not the integer that is represented the most in that list. To do that I have a command which creates a dictionary with every value in the list and the number of times it is represented in it. Next I try to create a new list with all items f...
<p>The variable you called <code>dictionary</code> is not a <code>dict</code> but a <code>dict_items</code>. </p> <pre><code>&gt;&gt;&gt; type(dictionary) &lt;class 'dict_items'&gt; &gt;&gt;&gt; help(dict.items) items(...) D.items() -&gt; a set-like object providing a view on D's items </code></pre> <p>and sets a...
python-3.x|dictionary|indexing
1
602
58,350,799
Difference between id and equality in python
<p>How is the <code>id</code> of an object computed? <a href="https://docs.python.org/3/library/functions.html#id" rel="nofollow noreferrer">https://docs.python.org/3/library/functions.html#id</a></p> <p>It seems there is a place in a class to do equality, with <code>__eq__</code> but where is the <code>is</code> oper...
<p>You can think of <code>id(obj)</code> as some sort of address of the object. The way it is computed, and what the value represents, is implementation-dependent, and you should not make any assumptions about the value.</p> <p>What you need to know:</p> <ol> <li>Object's <code>id</code> will not change as long as th...
python
2
603
58,301,581
Command line python and jupyter notebooks use two different versions of torch
<p>On my conda environment importing torch from command line Python and from a jupyter notebook yields two different results.</p> <p>Command line Python:</p> <pre><code>$ source activate GNN (GNN) $ python &gt;&gt;&gt; import torch &gt;&gt;&gt; print(torch.__file__) /home/riccardo/.local/lib/python3.7/site-packages/t...
<p>You need to sort of make the Anaconda environment recognized in Jupyter using </p> <pre><code>conda activate myenv conda install -n myenv ipykernel python -m ipykernel install --user --name myenv --display-name "Python (myenv)" </code></pre> <p>Replace <code>myenv</code> with the name of your environment. Later on...
python|jupyter-notebook|anaconda|pytorch|conda
1
604
65,432,087
Is there a way to use the secrets python module with a seed?
<p><code>Random.seed()</code> Is less secure than secrets, but I can't find any documentation on using a seed with secrets? or is random.seed just as fine?</p>
<p>No, there isn't. <a href="https://github.com/python/cpython/blob/master/Lib/secrets.py" rel="noreferrer"><code>secrets</code> uses <code>random</code>'s <code>SystemRandom</code> class</a>, which <a href="https://docs.python.org/3/library/random.html#random.SystemRandom" rel="noreferrer">reads from the operating sys...
python|random
6
605
45,600,902
Matplotlib stacked bar chart
<p>Hi I'm fairly new to matplotlib but I'm trying to plot a stacked bar chart. Instead of stacking, my bars are overlapping one another.</p> <p>This is the dictionary where I'm storing data. </p> <pre><code>eventsDict = { 'A' : [30.427007371788505, 3.821656050955414], 'B' : [15.308879925288613, 25.477707006369428], ...
<p>You'll need to set <code>bottom</code> differently - this tells matplotlib where to place the bottom of the bar you're plotting, so it needs to be the sum of all of the heights of the bars that came before.</p> <p>You could for example track the current heights of the bars with a list like so:</p> <pre><code>curre...
python|matplotlib|bar-chart|stacked-chart
1
606
45,581,807
Muscle Multiple Sequence Alignment with Biopython?
<p>I just learned to use python (and Biopython) so this question may bespeak my inexperience.</p> <p>In order to carry out MSA of sequences in a file (FileA.fasta), I use the following code:</p> <pre><code>from Bio.Align.Applications import MuscleCommandline inp = 'FileA.fasta' outp = 'FileB.fasta' cline = MuscleComm...
<p>First make sure you know where you installed <code>muscle</code>. If, for example, you installed muscle in:</p> <pre><code>/usr/bin/muscle3.8.31_i86darwin64 </code></pre> <p>then you <a href="https://stackoverflow.com/questions/7703041/editing-path-variable-on-mac">edit <code>/etc/paths</code></a> with:</p> <pre>...
python|alignment|bioinformatics|biopython
1
607
45,425,355
Two dimensional FFT using python results in slightly shifted frequency
<p>I know there have been several questions about using the Fast Fourier Transform (FFT) method in python, but unfortunately none of them could help me with my problem:</p> <p>I want to use python to calculate the Fast Fourier Transform of a given two dimensional signal f, i.e. f(x,y). Pythons documentation helps a lo...
<p>I found a number of issues</p> <p>you use <code>2 * np.pi</code> twice, you should choose one of either linspace or the arg to sine as radians if you want a nice integer number of cycles</p> <p>additionally <code>np.linspace</code> defaults to <code>endpoint=True</code>, giving you an extra point for 101 instead o...
python|fft|dft
3
608
28,467,719
Monkey patching Python Property setters (and getters?)
<p>So, monkey patching is pretty awesome, but what if I want to monkey patch a <code>@property</code>?</p> <p>For example, to monkey patch a method:</p> <pre><code>def new_method(): print('do stuff') SomeClass.some_method = new_method </code></pre> <p>however, properties in python re-write the = sign.</p> <p>Qu...
<p>Using <code>_ClassName__attribute</code>, you can access the attribute:</p> <pre><code>&gt;&gt;&gt; class MyClass(object): ... def __init__(self): ... self.__x = 3 ... @property ... def x(self): ... return self.__x ... @x.setter ... def x(self, value): ... if value != 3: ...
python|monkeypatching
2
609
41,410,238
Path Finder code, __getitem__ TypeError
<p>I am trying to make a "path finder"</p> <pre><code>def find_all_paths(start, end, graph, path=[]): path = path + [start] if start == end: return [path] paths = [] for node in graph[start]: if node not in path: newpaths = find_all_paths(graph, node, end, path) ...
<p>There are several awkwardness and errors:</p> <p>Instead of initialising the <em>path</em> parameter with a list, use <code>None</code>. And create the empty list in the function body.</p> <pre><code>def find_all_paths(start, end, graph, path=None): path = path or [] </code></pre> <p>The values passed to the ...
python|python-2.7|typeerror
2
610
6,554,455
Loading SQLite3 values into Python variables
<p>I have a project built in Python 2.7, using SQLite3 as the database. I need to know how to load an item from a particular row and column into an existing Python variable.</p> <p>TY!</p>
<p>Here are the basic steps:</p> <pre><code>import sqlite3 conn = sqlite3.connect(':memory:') curs = conn.cursor() results = curs.execute( """SELECT mycol FROM mytable WHERE somecol = ?;""", (some_var,) ).fetchall() curs.close() conn.close() </code></pre> <p>...
python|sqlite
3
611
56,909,602
I am getting pip version upgrade message while installing pygmaps
<p>I am getting this error while installing <code>pygmaps</code> package in pycharm.</p> <pre><code>Could not find a version that satisfies the requirement pygmaps (from versions: ) No matching distribution found for pygmaps You are using pip version 10.0.1, however version 19.1.1 is available. You should consider upg...
<p><code>pip install git+https://github.com/thearn/pygmaps-extended</code> can you try this one ? </p> <p>if it doesnt work </p> <p><a href="https://code.google.com/archive/p/pygmaps/downloads" rel="nofollow noreferrer">https://code.google.com/archive/p/pygmaps/downloads</a> go to this link and download it manuall...
python|pip|version
0
612
57,089,919
Where is spark/pyspark saving my parquet files?
<p>I'm saving a dataframe in pyspark to a particular location, but cannot see the file/files in the directory. Where are they? How do I get to them out side of pyspark? And how do I delete them? And what is it that I am missing about how spark works? </p> <p>Here's how I save them...</p> <pre><code>df.write.format('p...
<p>Ok, a colleague and I have figured it out. It's not complicated but we are but simple data scientists so it wasn't obvious to us.</p> <p>Basically the files were being saved in a different hdfs drive, not the drive from which we run our queries using Jupyter notebooks.</p> <p>We found them by doing;</p> <pre><cod...
python-3.x|apache-spark|pyspark|cloudera
1
613
57,278,821
How does one fit multiple independent and overlapping Lorentzian peaks in a set of data?
<p>I need to fit several Lorentzian peaks in the same dataset, some of which are overlapping. What I need most from the function is the peak positions (centers) however I can't seem to fit all the peaks in these data. </p> <p>I first tried using scipy's optimize curve fit, however I wasn't able to get the bounds to wo...
<p>Actually, just adding a quadratic background and lifting the bounds on the centroids should give a decent fit.</p> <p>Using your data, I modified your example a little::</p> <pre><code>#!/usr/bin/env python import matplotlib.pyplot as plt import numpy as np from lmfit.models import LorentzianModel, QuadraticModel ...
python|curve-fitting|data-fitting|model-fitting|scipy-optimize
2
614
25,469,950
Matplot: How to plot true/false or active/deactive data?
<p>I want to plot a <code>true/false</code> or <code>active/deactive</code> binary data similar to the following picture: <img src="https://i.stack.imgur.com/GncSv.jpg" alt="True/False Plot"></p> <p>The horizontal axis is time and the vertical axis is some entities(Here some sensors) which is active(white) or deactive...
<p>What you are looking for is <code>imshow</code>:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np # get some data with true @ probability 80 % data = np.random.random((20, 500)) &gt; .2 fig = plt.figure() ax = fig.add_subplot(111) ax.imshow(data, aspect='auto', cmap=plt.cm.gray, interpolation='ne...
python|matplotlib|plot|scipy
31
615
25,590,456
Can not clone cStringIO object properly
<p>I have the following code to get an image from a url:</p> <pre><code>im = cStringIO.StringIO(image_buffer) </code></pre> <p>now i have to do different operations on the original image such as:</p> <pre><code>Image.open(im).crop(box=(1, 1, 1, 1) </code></pre> <p>but this will edit the im itsself so i can't reuse...
<p>You can create a copy of a <code>cStringIO.StringIO</code> file object by simply getting out the string value and creating a new object, using the <a href="https://docs.python.org/2/library/stringio.html#StringIO.StringIO.getvalue" rel="nofollow"><code>StringIO.getvalue()</code> method</a>:</p> <pre><code>new_file ...
python|django|python-imaging-library|pillow
4
616
61,700,645
Add wT*x+b after CNN Python
<p>I have a problem.</p> <p>I have to take the output of last conv layer of EfficientNet(shape=(,7,7,1280), I call this x) and then calculate H = wT*x+b. My w is [49,49]. After that I have to apply softmax on H and then do <a href="https://i.stack.imgur.com/yvjF1.png" rel="nofollow noreferrer"><img src="https://i.sta...
<p>I see you use Tensorflow only (I mean without Keras). </p> <p>If you want to multiply <code>H</code> and <code>X</code> elementwise, and <code>H</code> and <code>X</code> are tensors with the same shape, you may use the elementwise multiplication functionality available in Tensorflow. If they are not tensors, you m...
python|tensorflow|keras|conv-neural-network|efficientnet
1
617
23,940,520
Removing lines from a text file using python and regular expressions
<p>I have some text files, and I want to remove all lines that begin with the asterisk (“*”).</p> <p>Made-up example:</p> <pre><code>words *remove me words words *remove me </code></pre> <p>My current code fails. It follows below:</p> <pre><code>import re program = open(program_path, "r") program_contents = progr...
<p>You <em>don't</em> want to use a <code>[^...]</code> negative character class; you are matching <em>all</em> characters except for the <code>*</code> or <code>.</code> characters now.</p> <p><code>*</code> is a meta character, you want to escape that to <code>\*</code>. The <code>.</code> 'match any character' syn...
python|regex
1
618
24,335,419
Matplotlib -- mplot3d: triplot projected on z=0 axis in 3d plot?
<p>I'm trying to plot a function in two variables, piecewise defined on a set of known triangles, more or less like so:</p> <pre><code>import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import random def f( x, y): if x + y &lt; 1: return 0 else: return 1 x = [0, 1, 1, 0] y = [0, 0, 1, 1] tri...
<p>I'm not an expert, but this was an interesting problem. After doing some poking around, I think I got something close. I made the Triangulation object manually and then passed it and a z list of zeros into plot_trisurf, and it put the triangles in the right place on z=0.</p> <pre><code>import matplotlib.pyplot as...
python|matplotlib|plot|triangulation|mplot3d
1
619
23,994,233
Calling a method from an existing instance
<p>My understanding of Object Orientated Programming is a little shaky so if you have any links that would help explain the concepts it would be great to see them!</p> <p>I've shortened the code somewhat. The basic principle is that I have a game that starts with an instance of the main Controller class. When the ga...
<p>You can pass the instance like this</p> <pre><code>class StartPopUp(Popup): def __init__(self, controller, **kw): super(StartPopUp, self).__init__(**kw) self.controller = controller def start_click(self): self.controller.start_game() </code></pre> <p>and in Controller</p> <pre><c...
android|python|python-2.7|kivy
2
620
24,268,020
Compare 2 files in Python
<p>I am trying to compare two files, A and C, in Python and for some reason the double for loop doesn't seem to work properly:</p> <pre><code>with open(locationA + filenameC,'r') as fileC, open(locationA + filenameA,'r') as fileA: for lineC in fileC: fieldC = lineC.split('#') for lineA in fileA:...
<p>Your problem is that once you iterate over <code>fileA</code> once you need to change the pointer to the beginning of the file again. So what you might do is create two lists from both files and iterate over them as many times as you want. For example:</p> <pre><code>fileC_list = fileC.readlines() fileA_list = fil...
python
1
621
72,096,196
Connectionn error Jupyter and Elasticsearch (Docker)
<p>I am trying to make a connection from Jupyter Notebook to Elasticsearch both in Docker containers but connected to the same network (bridge).</p> <p>Here is my code:</p> <pre class="lang-py prettyprint-override"><code>elastic_client = Elasticsearch(hosts=[&quot;http://localhost:9200/&quot;], http_auth=('generator', ...
<p>Issue in your case is using <b>localhost:9200</b> as connection string. Because ES is not &quot;localhost&quot; inside your Jupiter container. Eeach container gets its own localhost reference. You need to adjust the connection string to your Docker's DNS record so service/container name you set up inside your docker...
python|docker|elasticsearch|jupyter-notebook
2
622
71,791,533
Return entire row and append to value in a dataframe
<p>I am trying to write a function that searches a data frame row by row for a values in a column then appends entire row to the right side of the value if that value is found in any row.</p> <pre><code>Dataframe1 Col1 Col2 Col3 Lookup 400 60 80 90 50 90 68 80 </code></pre> <p>What I want is a following...
<p>You can try this out;</p> <pre><code>df1 = df.iloc[:,0:-1] new = pd.DataFrame() for val in df['Lookup']: s = df1[df1.eq(val).any(1)] new = new.append(s,ignore_index = True) new.insert(0,'Lookup',df['Lookup']) print(new) # Lookup Col1 Col2 Col3 # 0 90 50 90 68 # 1 80 400 60 8...
python|pandas|dataframe|loops
2
623
36,106,823
To sum up values of same items in a list of tuples while they are string
<p>If I have list of tuples like this: </p> <pre><code>my_list = [('books', '$5'), ('books', '$10'), ('ink', '$20'), ('paper', '$15'), ('paper', '$20'), ('paper', '$15')] </code></pre> <p>how can I turn the list to this:</p> <pre><code>[('books', '$15'), ('ink', '$20'), ('paper', '$50')] </code></pre> <p>i.e. to a...
<p>You can use <a href="https://docs.python.org/3.6/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a> to do this:</p> <pre><code>&gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; my_list = [('books', '$5'), ('books', '$10'), ('ink', '$20'), ('paper', '$15'), ('pa...
python|string|list|tuples
2
624
29,402,905
How can resolve recursion depth exceeded (Goose-extractor)
<p>I am one problem with goose-extractor This is my code:</p> <pre><code> for resultado in soup.find_all('a', href=True,text=re.compile(llave)): url = resultado['href'] article = g.extract(url=url) print article.title </code></pre> <p>and take a look at my problem. </p> <pre><code>RuntimeErr...
<p>As mentioned in the comments, you can increase the recursion limit with <code>sys.setrecursionlimit()</code> (<a href="https://docs.python.org/2/library/sys.html#sys.setrecursionlimit" rel="nofollow">2</a>/<a href="https://docs.python.org/3/library/sys.html#sys.setrecursionlimit" rel="nofollow">3</a>):</p> <pre><co...
python|extractor|goose
0
625
62,473,201
How do I enable Pylint in VSCode?
<p>I can't get pylint errors to show up in VSCode. I installed pylint globally (sudo apt install pylint), I created venv and installed it there with pip, I selected pylint as linter in VSCode, enabled it, ran it, and it doesnt show any errors in my file. If I check from the command line, it shows many errors in my file...
<p>Simplest way using UI:</p> <ol> <li><em>Press</em> &quot;<strong>Ctrl + Shift + P</strong>&quot; <em>to get Command Palette</em></li> <li><em>Type</em> &quot;<strong>Lint</strong>&quot;</li> </ol> <p><a href="https://i.stack.imgur.com/ijYzY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ijYzY.png" alt="en...
python|visual-studio-code|pylint
14
626
70,028,076
pyparsing nestedExpr and double closing characters
<p>I am trying to parse nested column type definitions such as</p> <pre><code>1 string 2 struct&lt;col_1:string,col_2:int&gt; 3 row(col_1 string,array(col_2 string),col_3 boolean) 4 array&lt;struct&lt;col_1:string,col_2:int&gt;,col_3:boolean&gt; 5 array&lt;struct&lt;col_1:string,col2:int&gt;&gt; </code></pre> <p>U...
<p><code>nestedExpr</code> and <code>infixNotation</code> are not really appropriate for this project. <code>nestedExpr</code> is generally a short-cut expression for stuff you don't really want to go into details parsing, you just want to detect and step over some chunk of text that happens to have some nesting in ope...
python|pyparsing|column-types
1
627
45,933,743
Python Loop, .remove, and List Exercise
<p>So we have an exercise that we are giving to the children and we need to use a list(or array), as well as the '.remove()' method, and a loop. </p> <p>I have the following code and the code isn't working. </p> <pre><code>usernames = [ 'Steph','JHG','Greg','Matt','Rodney','David', 'Chris','Sally','Gemma','Pa...
<p>Or as a <code>while</code> loop:</p> <pre><code>while 'JHG' in usernames: usernames.remove('JHG') </code></pre>
python|loops
1
628
54,915,861
How can I delete multiple files using a Python script?
<p>I am playing around with some python scripts and I ran into a problem with the script I'm writing. It's supposed to find all the files in a folder that meets the criteria and then delete it. However, it finds the files, but at the time of deleting the file, it says that the file is not found.</p> <p>This is my code...
<p><a href="https://docs.python.org/2.7/library/os.html#os.unlink" rel="nofollow noreferrer"><code>os.unlink</code></a> takes the <strong>path</strong> to the file, not only its <code>filename</code>. Try <strong>pre-pending</strong> your <code>filename</code> with the <code>dirname</code>. Like this</p> <pre><code>im...
python
1
629
54,779,518
How to scrape wikipedia infobox and store it into a csv file
<p>I already done scraping of wikipedia's infobox but I don't know how to store taht data in csv file. Please help me out.</p> <pre><code>from bs4 import BeautifulSoup as bs from urllib.request import urlopen def infobox(query) : query = query url = 'https://en.wikipedia.org/wiki/'+query raw = urlopen(url...
<p>You have to collect the required data and write in csv file, you can use csv module see below example:</p> <pre><code>from bs4 import BeautifulSoup as bs from urllib import urlopen import csv def infobox(query) : query = query content_list = [] url = 'https://en.wikipedia.org/wiki/'+query raw = ur...
python|web-scraping|beautifulsoup
0
630
33,114,468
Append input to existing list
<p>I'm running through a beginners guide to Python and I'm currently working on lists. Now I've created this sample code, but I can't seem to add the user input dynamically to the list that I've created. If you enter an item from the list, you get a success message, but if the item isn't on the list I try to append it ...
<p>I think you mean to say</p> <pre><code>elif ( first_topping not in topping_list_one ): topping_list_one.append(first_topping) </code></pre> <p>ie. "not in" instead of "in" and remove the quotes from 'first_topping'</p>
python
2
631
73,591,884
How to change some characters at the same time in Vscode?
<p>i have Vscode and Anaconda.</p> <p>There are 50+ ipynb tutorial files that i studied. I work with cells. These files have some Turkih characters that i want to change. These characters are both in uppercase and lowercase.</p> <pre><code>Ç --&gt; C Ğ --&gt; G Ö --&gt; O Ş --&gt; S Ü --&gt; U İ --&gt; I ç --&gt; c ğ ...
<p>use the extension <a href="https://marketplace.visualstudio.com/items?itemName=bhughes339.replacerules" rel="nofollow noreferrer">Replace Rules</a></p> <p>Add the following to your settings:</p> <pre class="lang-json prettyprint-override"><code> &quot;replacerules.rules&quot;: { &quot;Replace Turkih&quot;: { ...
python|visual-studio-code|jupyter-notebook
1
632
73,717,231
Is it possible to get the xpath (source) of an element using selenium in python?
<p>If you take a look at this <a href="https://example.com/" rel="nofollow noreferrer">site</a>, you will see the title/text &quot;Example Domain&quot;. Is it possible to get its xpath which is <code>/html/body/div/h1</code> using selenium? Is there any other possibilities? I mean I want to get xpath itself and not its...
<p>What you need (based on how you worded your question: I honestly doubt this is what you <strong>really</strong> need, and I'm sure that if you would state your end goal, someone would put you on the right path) is this:</p> <p><a href="https://gist.github.com/ergoithz/6cf043e3fdedd1b94fcf" rel="nofollow noreferrer">...
python|selenium|web-scraping|xpath|xml.etree
2
633
73,563,343
python PIL image.getdata() returns data returns more data than is expected
<p>the following:</p> <pre><code>image = Image.open(name, 'r') data = np.array(image.getdata()) data.reshape(image.size) </code></pre> <p>returns:</p> <pre><code>Traceback (most recent call last): File &quot;/home/usr/colorviewer/main.py&quot;, line 207, in &lt;module&gt; print(getPalette()) File &quot;/home/us...
<p>Every pixel uses three values <code>R,G,B</code> so you have <code>640*480*3</code> which gives <code>921600</code> bytes.</p> <p>So you need reshape into <code>(640,480,3)</code>. And it needs <code>*</code> to unpack <code>size</code>.</p> <pre><code>data.reshape(*image.size, 3) </code></pre> <p>If image can be tr...
python|image|image-processing|python-imaging-library
0
634
21,432,947
How to compress 300GB file using python
<p>I am trying to compress a virtual machine file with size 300GB.</p> <p>Every single time the python script is killed because the actually memory usage of the <code>gzip</code> module exceeds 30GB (virtual memory). </p> <p>Is there any way to achieve large file(300GB to 64TB) compression using python?</p> <pre><co...
<pre><code>with gzip.open(compressedFileName, 'wb') as compressedFH: compressedFH.writelines(fileHandle) </code></pre> <p>writes the file <code>fileHandle</code> <em>line by line</em>, i. e. splits it into chunks separated by the <code>\n</code> character.</p> <p>While it is quite probable that this character occ...
python|compression
3
635
41,057,516
Python: Find all pairwise distances between points and return points along with distance
<p>I have a list containing list of points with a name and coordinates in 3D. Something like this with a <strong>much larger length of the list</strong>:</p> <pre><code>group=[[gr1, 5, 8, 9], [gr2, 7, 4, 5], [gr3, 3, 8, 1], [gr4, 3, 4, 8]] </code></pre> <p>I want to calculate <strong>all possible pairwise distances</...
<p>Maybe you could try two nested for-loops to combine every element in "group" except the last one with every other element to the right:</p> <pre><code>group=[["gr1", 5, 8, 9], ["gr2", 7, 4, 5], ["gr3", 3, 8, 1], ["gr4", 3, 4, 8]] distances=[] for i,g in enumerate(group[:-1]): for h in group[i+1:]: d =...
list|python-3.x|numpy|scipy
1
636
29,127,350
completely connected subgraphs from a larger graph in networkx
<p>I have tried not to repost here, but I think my request is very simple and I am just inexperienced with network graphs. When using the networkx module in python, I would like to recover, from a connected graph, the subgraphs where all nodes are connected to each other (where the number of nodes is greater than 2). I...
<p>It sounds like you want to discover the cliques in your graph. For this you could use <a href="http://networkx.lanl.gov/reference/generated/networkx.algorithms.clique.find_cliques.html#networkx.algorithms.clique.find_cliques" rel="nofollow"><code>nx.clique.find_cliques()</code></a>:</p> <pre><code>&gt;&gt;&gt; list...
python|nodes|networkx|subgraph
3
637
29,260,404
create a multidimensional random matrix in spark
<p>With the python API of Spark I am able to quickly create an RDD vector with random normal number and perform a calculation with the following code: </p> <pre><code>from pyspark.mllib.random import RandomRDDs RandomRDDs.uniformRDD(sc, 1000000L, 10).sum() </code></pre> <p>where <code>sc</code> is an available SparkC...
<p>Spark evolved a bit since this question was asked and Spark will probably have better support still in the future. </p> <p>In the meantime you can be a bit creative with the <code>.zip</code> method of RDD's as well as DataFrames to get close to what numpy can do. It is a bit more verbose, but it works. </p> <pre>...
python|numpy|multidimensional-array|apache-spark
1
638
52,083,470
Writing to an Excel File With Python
<p>I am doing some webscraping with BeautifulSoup and Selenium and I want to write my data to an excel file </p> <pre><code># coding: utf-8 import requests import bs4 from datetime import datetime import re import os import urllib import urllib2 from bs4 import BeautifulSoup from selenium import webdriver import time...
<p>The error is triggered when the code tries to write the file. Confirm that you have write permissions to that directory, and that the file doesn't already exist. It's unlikely that you have access to <code>/home</code>.</p>
python|excel|xlsxwriter
1
639
51,993,599
unable to run print statements from loss function when calling model.fit in Keras
<p>I have created a custom loss function called </p> <p><code>def customLoss(true, pred) //do_stuff //print(variables) return loss</code></p> <p>Now I'm calling compile as <code>model.compile(optimizer='Adamax', loss = customLoss)</code></p> <p>EDIT: I tried tf.Print and this is my result.</p> <pre><code> def ...
<p>It's not because Keras dumps buffers or does magic, it simply doesn't call them! The loss function is called once to construct the <em>computation graph</em> and then the symbolic tensor that represents the loss value is returned. Tensorflow uses that to compute the loss, gradients etc.</p> <p>You might instead be ...
python|tensorflow|neural-network|keras
2
640
51,720,851
Issue when trying to login with Docusign API by official python lib on live account
<p>I have issue when trying to login with API on live account, while on sandbox all works great. When doing request on login, I must get on response data object <code>login_accounts</code>. Data in object looks like this(I've delete few symbols in password for sequrity reasons)</p> <pre><code>``` {'api_password': 'ZQQ...
<p>The AuthenticationApi.login() method is intended to be used with Legacy Header authentication. For JWT/OAuth you would want to use the Get UserInfo method. Unfortunately, that method hasn't yet been implemented in the Python client. You'll need to make that call manually into the SDK is updated to include that funct...
python|docusignapi
0
641
51,849,871
How to tune scipy interpolate function?
<p>I'm not sure why it's doing such a crappy job. Here's the set of 189 data points I was hoping to get smoothed. Why is it lagging so much?</p> <pre><code>y = data x = range(len(y)) tck, _ = splprep([x,y]) x2, y2 = splev(np.linspace(0,1,len(y)), tck) plt.plot(y, 'b') plt.plot(y2, 'g') plt.show() </code></pre> <p><...
<p>Smoothing is a fairly common problem in time series analysis. Have you tried out <a href="https://en.wikipedia.org/wiki/Exponential_smoothing" rel="nofollow noreferrer">exponential smoothing</a>? The package <a href="http://www.statsmodels.org/dev/tsa.html" rel="nofollow noreferrer">StatsModels</a> has a lot of call...
python|matplotlib|scipy
0
642
59,709,094
Read n tables in csv file to separate pandas DataFrames
<p>I have a single .csv file with four tables, each a different financial statement four Southwest Airlines from 2001-1986. I know I could separate each table into separate files, but they are initially downloaded as one.</p> <p>I would like to read each table to its own pandas DataFrame for analysis.Here is a subset ...
<p>What you want to do if far beyond what <code>read_csv</code> can do. If fact you input file struct can be modeled as:</p> <pre class="lang-none prettyprint-override"><code>REPEAT: Dataframe name Header line REPEAT: Data line BLANK LINE OR END OF FILE </code></pre> <p>IMHO, the simplest way i...
python|pandas|file|csv|dataframe
1
643
19,229,389
Beautiful Soup crashes upon special chars like "&quot;" and "&lt;"
<p>I'm trying to scrape an atom based RSS feed using beautiful soup, but it's proving difficult. Capturing the data goes just fine until an <code>&lt;item&gt;</code> comes up that breaks the code and crashes the script. Such <code>&lt;item&gt;</code>s consistently have tags (firefox marks them in orange) like "&amp; ...
<p>Not sure which problem you are talking about, but I got this error while running you code:</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\u2018' in position 54: ordinal not in range(128) </code></pre> <p>To fix it I just added encoding:</p> <pre><code>for thing in news_stuff: print...
python|web-scraping|beautifulsoup
2
644
18,911,903
Python requests, can't log into a site
<p>I am trying to use Python (3.2) requests to login to a site and navigate protected content on subsequent pages. However, when I login it seems to just leave me at the original login page (not navigating to the success page), and the subsequent page call is only showing the unprotected content. Can you please help me...
<p>I figured out the problem. I needed to change self.payload to: self.payload = {'login':username,'password':password,'submit_login':'Login'}</p>
python|python-3.x|python-requests
0
645
62,056,312
How can I use python to convert multiple date columns into one date column and sum up their values (example below)?
<p>Following is the table I have -</p> <pre><code>Market 05-20 06-20 07-20 08-20 HK 5 5 5 5 US 2 2 2 2 HK 3 3 3 3 UK 7 7 7 7 UK 2 2 2 2 </code></pre> <p>Follwoing is what I want to make of it -</p> <pre><cod...
<p>First you can use </p> <pre><code> df = df.groupby("Market").sum() </code></pre> <p>Result:</p> <pre><code> 05-20 06-20 07-20 08-20 Market HK 8 8 8 8 UK 9 9 9 9 US 2 2 2 2 </code></pre> <p>Next you can <...
python
1
646
67,497,778
Why am I unable to scrape values from a Hidden tooltip of a Highchart using selenium python?
<p>I've particularly asked a couple of questions on the same topic before asking it one final time. To begin with, I am scraping values from <a href="https://www.similarweb.com/website/zalando.de/#overview" rel="nofollow noreferrer">https://www.similarweb.com/website/zalando.de/#overview</a></p> <p>I am trying to scrap...
<p>I have a solution that works. I took the time to identify a way to hover over each of the points, print the data, and move to the next. This could be way cleaner, but it works. Here's my python file:</p> <pre><code>from selenium import webdriver import chromedriver_autoinstaller from selenium.webdriver.support.ui ...
python|json|selenium|selenium-webdriver|lxml
1
647
67,313,416
How to multiply tuple values in array?
<p>I've tried everything to multiply the values in the tuple, but I get the error: TypeError: can't multiply sequence by non-int of type 'tuple' .</p> <pre><code>from itertools import product arr = 0 val_x = [] val_y = [] n = int(input('n = ')) def multiply(product, *nums): factor = product for num in nums: ...
<p>As your description in comments, you need to change <code>multiply()</code>. In the following implementation, <code>multiply()</code> receives a list of tuples and returns a list by multiplying all elements of each tuple in input list. It is required to cast <code>str</code> to <code>int</code> before multiplication...
python|python-3.x
2
648
63,723,147
'utf-8' codec can't decode byte 0xff in position 0: invalid start byte / unexpected end of data
<p>I am trying to pass some functions from C++ to Python using the Qt library (Pyside2 in python). At the moment everything works correctly passing the code from one side to the other and adapting it to Python, but when I start treating images errors happen.</p> <p>The only thing that I achieve is to correctly parse th...
<p>The code you’ve posted doesn’t work because there are several errors, but none that would cause the error message you’re observing.</p> <p>Here’s the code with those errors fixed. This should work (though it doesn’t work with the data you provided, since that is truncated):</p> <pre><code>def convertGBAR4444(array, ...
python|pyside2
1
649
36,357,036
server doesn't send data to clients
<p>I have this piece of code for server to handle clients. it properly receive data but when i want to send received data to clients nothing happens.</p> <p><strong>server</strong></p> <pre><code>import socket from _thread import * class GameServer: def __init__(self): # Game parameters board ...
<p>I modified your code a little(as I have python 2.7) and <code>conn.send()</code> seems to work fine. You can also try <code>conn.sendall()</code>. Here is the code I ran:</p> <p><strong>Server code:</strong></p> <pre><code>import socket from thread import * class GameServer: def __init__(self): # G...
sockets|python-3.x|networking|network-programming|python-sockets
0
650
19,489,040
Invert alternation regex
<p>I have an alternation regex that I want to invert but can't seem to get it working, it looks like this:</p> <pre><code>( |\w+-\w+| \+\w+|\w) </code></pre> <p>which will extract all special characters except for - in the middle of a word or + in front of a word. The problem is that I want to remove everything that ...
<p>Your question is a bit unclear, are you looking for this?</p> <pre><code>a = "abc def,ghi remove - this keep-that foo + bar +keep!" import re print re.sub(r'[^\w\s+-]|(?&lt;!\w)-(?!\w)|\+(?!\w)', '', a) #abc defghi remove this keep-that foo bar +keep </code></pre> <p>The more accurate regexp:</p> <pre><code>[^\...
python|regex
2
651
43,808,714
Creating a New DataFrame Column by Using a Comparison Operator
<p>I have a DataFrame that looks like something similar to this:</p> <pre><code> 0 0 3 1 11 2 7 3 15 </code></pre> <p>And I want to add a column using two comparison operators. Something like this: </p> <pre><code>df[1] = np.where(df[1]&lt;= 10,1 &amp; df[1]&gt;10,0) </code></pre> <p>I want my return to lo...
<p><strong>Setup</strong></p> <pre><code>df = pd.DataFrame({'0': {0: 3, 1: 11, 2: 7, 3: 15}}) Out[1292]: 0 0 3 1 11 2 7 3 15 </code></pre> <p><strong>Solution</strong></p> <pre><code>#compare df['0'] to 10 and convert the results to int and assign it to df['1'] df['1'] = (df['0']&lt;10).astype(int) df Ou...
python|pandas|dataframe
1
652
54,613,623
Return boolean in for-loop evaluating multiple lists
<p>I'm attempting to iterate over multiple text articles, comparing whether these articles have keywords in 2 disparate lists. If the article has a keyword from both lists, then it should return 'true.' If an article only has a keyword from one list, then it should be 'false'. </p> <p>Note: I'm breaking down a larger...
<p>what about </p> <blockquote> <p>Westies will eat avocado, even figs. [eat, avocado, figs]</p> </blockquote> <p>which has multiple keyterms, do you want to check each one of them. I mean return True when each keyterm is present in both lists or what? </p> <p>Check if the solution works for you? </p> <pre><cod...
python|python-3.x
0
653
54,332,079
Pip install for warrant fails
<p>I tried installing warrant using pip and got the following error:</p> <pre><code>Command "c:\...\venv\scripts\python.exe -u -c "import setuptools, tokenize; __file__='C:\\...\\AppData\\Local\\Temp\\1\\pip-install-lahy2d9f\\pycryptodome\\setup.py'; f=getattr(tokenize, 'open', open)(__file__); code=f.read().replace('...
<p>I had the same issue when I ran <code>pip3 install warrant</code>. I fixed the issue by installing a C compiler. Try installing Visual Studio build tools which provides a bunch of compilers.</p> <p><a href="https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=BuildTools" rel="nofollow norefer...
python
1
654
71,295,114
JSON file loaded as one row, one column using pandas read_json; expecting a full dataframe
<p>I was provided with a JSON file which looks something like below when opened with Atom:</p> <pre><code>[&quot;[{\&quot;column1\&quot;:value1,\&quot;column2\&quot;:value2,\&quot;column3\&quot;:value3 ... </code></pre> <p>I tried loading it in Jupyter with pandas read_json as such:</p> <pre><code>data = pd.read_json('...
<p>Ok so I think as <code>head()</code> only shows one entry that the outer brackets are not needed. I would try to read your file as a string and change the string to something that <code>pd.read_json()</code> can parse. I assume that your file contains data in a form like this:</p> <pre><code>[&quot;[{\&quot;column1\...
python|json|pandas|dataframe
0
655
9,170,638
PyQT - setting the text color for a QTabWidget
<p>Is there any way to set the text color of a certain tab that's part of a QTabWidget? <a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qtabbar.html#setTabTextColor" rel="nofollow">QTabBar</a> seems to have a method to set the tab text color, but I do not see a similar method for <a href="http://www...
<p>The tab text color can be set via the tab-widget's <a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qtabwidget.html#tabBar" rel="noreferrer">tabBar</a> method:</p> <pre><code>tabwidget.tabBar().setTabTextColor(index, color) </code></pre>
python|pyqt|qtabwidget
6
656
9,357,268
Django related key of the same model
<p>I'm working on a feature for an app much like a Twitter Retweet.</p> <p>In the model for <code>Item</code>, I want to add a related field for <code>reposted_from</code> that will reference another <code>Item</code>. I dont think I use <code>ForeignKey</code> for this, since it's the same Model, but what do I use in...
<p>It is common to add a <a href="https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey" rel="nofollow">foreign key to self</a> as such:</p> <pre><code>class Item(models.Model): parent = models.ForeignKey('self') </code></pre> <p>You may specify a <a href="https://docs.djangoproject.com/en/dev/ref/m...
python|django
7
657
9,121,826
Class and Array Problems
<p>I am absolutely useless with python and I'm struggling to do what seems to be simple things. I need to read a text file which contains a network routing table which contains the distance between each node on the network (below)</p> <pre><code>0,2,4,1,6,0,0 2,0,0,0,5,0,0 4,0,0,0,0,5,0 1,0,0,0,1,1,0 6,5,0,1,0,5,5 0,0...
<h2>Redundant line</h2> <p>Strings in Python are <strong>immutable</strong>, thus with the following line:</p> <pre><code>line.strip(' \n' '\r') </code></pre> <p>you are only getting a copy of the <code>line</code> string, stripped of some characters, but you do not assign it to anything. Change it into:</p> <pre>...
python
4
658
39,367,593
Repeating a for in line loop python
<p>How would I repeat this (excluding the opening of the file and the setting of the variables)? this is my code in python3 </p> <pre><code>file = ('file.csv','r') count = 0 #counts number of times i was equal to 1 i = 0 #column number for line in file: line = line.split(",") if line[i] == 1: ...
<p>If I understand the question, try this and adjust for however you want to format. Replace <code>NUM_COLUMNS</code> with the number of times you want it repeating</p> <pre><code>file = open('file.csv','r') data = file.readlines() for i in range(NUM_COLUMNS): count = 0 for line in data: line = line...
python|list|python-3.x|csv|repeat
1
659
55,474,353
Python syntax for an unless statement
<p>My request is simple but I do not know how to proceed:</p> <p>I would like to translate an unless statement in python as followed:</p> <pre><code>taken_asks -= 1 unless taken_asks == 0 </code></pre> <p>This is just one line of code which is part of a very big function. Any idea? </p> <p>Thank you in advance !</...
<p><code>taken_asks -= (1 if taken_asks != 0 else 0)</code></p>
python
6
660
52,510,176
How to make data persistent when setData method is used
<p>The code below creates a single <code>QComboBox</code>. The combo's <code>QStandardItem</code>s are set with <code>data_obj</code> using <code>setData</code> method. Changing <code>combo</code>'s current index triggers <code>run</code> method which iterates <code>combo</code>' and prints the <code>data_obj</code> w...
<p>Below is the working solution to this problem:</p> <p><a href="https://i.stack.imgur.com/V8tGy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V8tGy.png" alt="enter image description here"></a></p> <pre><code>app = QApplication(list()) class DataObj(dict): def __init__(self, **kwargs): ...
python|pyside|qcombobox|qstandarditem
0
661
47,933,019
How to properly sample truncated distributions?
<p>I am trying to learn how to sample truncated distributions. To begin with I decided to try a simple example I found here <a href="https://darrenjw.wordpress.com/2012/06/04/metropolis-hastings-mcmc-when-the-proposal-and-target-have-differing-support/" rel="nofollow noreferrer">example</a></p> <p>I didn't really unde...
<p>You say you want to learn the basic idea of sampling a truncated distribution, but your source is a blog post about <a href="https://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm" rel="noreferrer">Metropolis–Hastings algorithm</a>? Do you actually need this "method for obtaining a sequence of random s...
python|numpy|random|probability|mcmc
9
662
37,541,311
Unique ID in html for generating Buttons
<p>sorry if the title is misleading.</p> <p>I'm having the following problem. I am creating multiple rows in HTML using Genshi. For each row I have a button at the end of the row for delete purposes. </p> <p>The code looks like this:</p> <pre><code>&lt;form action="/deleteAusleihe" method="post"&gt; &lt;table&...
<p>The issue is that all the hidden inputs inside the <code>&lt;form&gt;</code> element get submitted at once.</p> <p>There are various ways you could solve this. Probably the easiest would be to move the form tag inside the loop, so that there are multiple forms and each one only wraps a single input and button.</p>
python|html|python-2.7|turbogears2|genshi
2
663
34,291,661
Setuptools pip failed with error code 1 when installing Hue browser for Apache Hadoop
<p>I'm trying to install Hue browser for Apache Hadoop on my mac. So I retrieve the git folder :</p> <pre><code>git clone https://github.com/cloudera/hue.git </code></pre> <p>I followed this tutorial <a href="http://blog.cloudera.com/blog/2015/04/how-to-install-hue-on-a-mac/" rel="nofollow">here</a> </p> <p>But when...
<p>try <code>sudo make apps</code></p> <p>it works for me on Sierra.</p>
python|pip|hue
0
664
66,289,384
Create Panorama from Non-Sequential Video Frames
<p>There is a <a href="https://stackoverflow.com/questions/23856786/video-to-panorama-image">similar question</a> (not that detailed and no exact solution). I want to create <strong>a single panorama image</strong> from video frames. And for that, I need to get <strong>minimum non-sequential video frames</strong> at fi...
<p>My approach to decimating the video is to pretty much do what a stitching program would do to try and stitch two frames together. I look for matching feature points and I only save frames once the number of matched points dip below what I think is an acceptable level.</p> <p>To stitch, I just used OpenCV's built-in ...
python|opencv|video|ffmpeg|duplicates
1
665
7,275,710
mutagen: how to detect and embed album art in mp3, flac and mp4
<p>I'd like to be able to detect whether an audio file has embedded album art and, if not, add album art to that file. I'm using mutagen</p> <p>1) Detecting album art. Is there a simpler method than this pseudo code:</p> <pre><code>from mutagen import File audio = File('music.ext') test each of audio.pictures, audio...
<p>Embed flac:</p> <pre><code>from mutagen import File from mutagen.flac import Picture, FLAC def add_flac_cover(filename, albumart): audio = File(filename) image = Picture() image.type = 3 if albumart.endswith('png'): mime = 'image/png' else: mime = 'image/jpeg' image....
python|metadata|albumart|mutagen
4
666
7,567,318
How to make a list of n numbers in Python and randomly select any number?
<p>I have taken a count of something and it came out to N.</p> <p>Now I would like to have a list, containing 1 to N numbers in it.</p> <p>Example:</p> <p>N = 5</p> <p>then, <code>count_list = [1, 2, 3, 4, 5]</code></p> <p>Also, once I have created the list, I would like to randomly select a number from that list ...
<p>You can create the enumeration of the elements by something like this:</p> <pre><code>mylist = list(xrange(10)) </code></pre> <p>Then you can use the <code>random.choice</code> function to select your items:</p> <pre><code>import random ... random.choice(mylist) </code></pre> <p>As Asim Ihsan correctly stated, m...
python|list|random
41
667
16,574,746
How to get id of the tweet posted in tweepy
<p>I want to check if a certain tweet is a reply to the tweet that I sent. Here is how I think I can do it:</p> <p>Step1: Post a tweet and store id of posted tweet</p> <p>Step2: Listen to my handle and collect all the tweets that have my handle in it</p> <p>Step3: Use <code>tweet.in_reply_to_status_id</code> to see ...
<p>What one could do, is get the last nth tweet from a user, and then get the tweet.id of the relevant tweet. This can be done doing:</p> <p><code>latestTweets = api.user_timeline(screen_name = 'user', count = n, include_rts = False)</code></p> <p>I, however, doubt that it is the most efficient way.</p>
python|twitter|tweepy
0
668
31,681,194
Using keyboard actions to open files outside of Python
<p>Brand new to programming....</p> <p>I am trying to set up a program that can be controlled using keyboard shortcuts. I want the keyboard shortcuts to be linked to specific excel files. I have figured out how to open the excel files by themselves but now I want to attach the shortcuts to them. This is all I have:</p...
<p>This makes a Tkinter window which you can type in to. If the 'shortcut' (in this code, 'a') is pressed, you can cause something to happen such as opening your Excel file. </p> <pre><code>import tkinter as tk import os def onKeyPress(event): if event.char == 'a': os.system('start C:\mold\MoldFlowMaster_...
python|excel
1
669
40,740,525
Pycharm recognizes kwargs in print as wrong (python3)
<p>Whenever I do something like this:</p> <pre><code>print("Hello World", flush=True, file=sys.stderr) </code></pre> <p>PyCharm complains about</p> <pre><code>End of statement expected Statement expected, found Py:DEDENT Statement expected, found Py:RPAR </code></pre> <p>Because of that "Syntax Error" all definitio...
<p>My settings for the python interpreter were wrong. To change it, I went to <code>Settings-&gt;Project-&gt;Project Interpreter</code>. Everything is working fine now!</p> <p>Thanks for the comments which leads to the solution!</p>
python-3.x|pycharm
4
670
10,237,608
Python MYSQLDB Insert Syntax Error
<p>I'm trying to insert data into my database and I get a MYSQL syntax error using this code:</p> <pre><code>import MySQLdb db=MySQLdb.connect(host="localhost",user="root",passwd="",db="database") cursor = db.cursor() sql = "INSERT INTO table1('col1','col2') values ('val1','val2');" cursor.execute(sql) db.commit() </c...
<p>No quotes around the column names.</p> <pre><code>INSERT INTO table1(col1, col2) VALUES ('val1', 'val2'); </code></pre> <p>You could use backticks around the column names, but not single quotes.</p>
python|mysql
2
671
9,667,462
Backspace behavior in Python statement, what is correct behavior of printing a '\b' in code?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/2856344/backspace-character-weirdness">backspace character weirdness</a> </p> </blockquote> <p>I have noticed that 1. If I print only backspaces, i.e. a sequence of \b in Python, then it is completely blank. 2....
<p>Expanded answer: The backspace doesn't delete anything, it moves the cursor to the left and it gets covered up by what you write afterwards. If you were writing to a device that can display overstriking (such as an old-fashioned "hard copy" terminal, which works like a typewriter), you'd actually see the new charact...
python
13
672
26,290,298
Inclusive range of list Python
<p>I'm trying to find the minimum elements within a section of a list. In the following example, a is the start and b is the end. I would like these indexes to partition the list inclusively, so that if the list is [1,2,3,9,4,10] the indexes 1 to 4 would include 2 and 4.</p> <pre><code>def minimum (a,b,list): retu...
<p>By default, no.</p> <p>For this case, it is more conventional to do:</p> <pre><code>min(li[a:b + 1]) </code></pre> <p>Also beware of naming your variable list, as it can have unintended consequences (silent namespace issues), as "list" also names the built-in list container type.</p> <p>If you simply want to wri...
python-2.7|python-3.x
2
673
60,110,915
Install specific python library version based on another library version
<p>In setup.py I have </p> <pre><code> install_requires=[ "python-consul", "library_a", "library_b" ] </code></pre> <p>library_b is also imported by library_a but it is pinned in library_a. </p> <p>Is it possible to pin library_b to what it is pinned in library_a. I know I can...
<p>Probably you can just omit one of the libraries, but not sure without concrete examples.</p> <p>Anyhow, you can use <a href="https://pip.pypa.io/en/stable/reference/pip_install/#requirement-specifiers" rel="nofollow noreferrer">requirement specifiers</a> for versions that will define rules for versions and pin this...
python|setup.py
0
674
62,898,802
Git: How to save and return to a specific version
<p>I'm new here so I apologize if this isn't the place to ask this question. I'm writing a python script for my company that looks through files in certain commits and compares them. Well I'm not familiar with git and how commits work so maybe someone more knowledgeable than me can help. What I have so far is something...
<p>For anyone looking for the answer to this question, what worked was LeGEC's solution in the comments. I used:</p> <pre><code>import subprocess # Here is where I got info on the current commit with changes subprocess.run([&quot;git&quot;, &quot;stash&quot;]) # Here is where I got info on the older commit version ...
python|python-3.x|git
0
675
32,242,446
try and except in while-loop python
<p>I am working on a live plot of incoming data. The data comes from a spectrum analyser and sometimes I get faulty data. Faulty in the meaning that there are on some positions letters instead of numbers. </p> <p>I save the incoming data as a list and then I convert it to a <code>numpy.array</code> with</p> <pre><cod...
<p>I would recommend putting in the <code>try/except</code> clause only what you expect to raise an exception. The code would be more clear and you would be sure that the exception is raised by what you expect to raise it. Something like:</p> <pre><code>try: trace = np.array(trace, np.float) except ValueError: ...
python|numpy|matplotlib|plot|try-except
0
676
28,155,535
Numpy-style error tracebacks?
<p>In numpy, when you make a mistake, the error doesn't tell you about all the numpy internals, just the user-level error made. For example:</p> <pre><code>import numpy as np A = np.ones([1,2]) B = np.ones([2,3]) A+B </code></pre> <p>spits back</p> <pre><code>Traceback (most recent call last): File "/home/roderic/...
<p>The only reason that <code>A+B</code> doesn't show any internal stack frames is that <code>numpy.ndarray.__add__()</code> happens to be implemented in C, so there are no Python stack frames after the one containing the <code>A+B</code> to show. numpy is not doing anything special to clean up the stack trace.</p>
python|numpy|traceback
1
677
44,058,215
Dissecting a permutation algorithm in Python
<p>I am trying to get my head around how this permutation algorithm works:</p> <pre><code>def perm(n, i): if i == len(n) - 1: print n else: for j in range(i, len(n)): n[i], n[j] = n[j], n[i] perm(n, i + 1) n[i], n[j] = n[j], n[i] # swap back, for the next lo...
<p>It <em>does</em> skip the <code>if</code> at the top level. It drops into the <code>else</code> and iterates <code>j</code> through the list. The first iteration has i == j == 0, so the swap does nothing, and you recur with ([1, 2, 3], 1).</p> <p>This process repeats for the that instance, having i == j == 1. Th...
python|algorithm|permutation
3
678
13,819,019
Add element to a bibtexfile in Python
<p>I have created a script which scrapes many pdfs for abstract and keywords. I also have a collection of bibtex-files in which I want to place the texts I've extracted. What I'm looking for is a way of adding elements to the bibtex files. </p> <p>I have written a short parser: </p> <pre><code>#!/usr/bin/python #-*- ...
<p>I've never used pybtex, but from a quick glance, you can add entries. Since <code>self.bibs.entries</code> appears to be a <code>dict</code>, you can come up with a unique key, and add more entries to it. Example:</p> <pre><code>key = "some_unique_string" new_entry = Entry('article', fields={ 'l...
python|bibtex
1
679
13,840,697
Xlib control keyboard events
<p>How does one simulate keyboard key presses in python (Xlib) I have been using Xlib-python for simulating mouse pointer events such as movements and clicks. But I haven't been able to find enough help for doing a similar thing for keyboard presses.</p> <p>Preferred platform : python on linux</p>
<p>I'm no expert on Xlib, but managed to piece together this code for the PyAutoGUI module. Here's the minimum viable example that can simulate a <code>keyDown()</code> and <code>keyUp()</code> for a keyboard key:</p> <pre><code># You must run `pip3 install python3-xlib` to get the Xlib modules. import os from Xlib....
python|linux|xlib
3
680
8,084,260
How to print a file to stdout?
<p>I've searched and I can only find questions about the other way around: writing stdin to a file.</p> <p>Is there a quick and easy way to dump the contents of a file to <code>stdout</code>?</p>
<p>Sure. Assuming you have a string with the file's name called <code>fname</code>, the following does the trick.</p> <pre><code>with open(fname, 'r') as fin: print(fin.read()) </code></pre>
python
136
681
1,101,550
Why my Python test generator simply doesn't work?
<p>This is a sample script to test the use of yield... am I doing it wrong? It always returns '1'...</p> <pre><code>#!/usr/bin/python def testGen(): for a in [1,2,3,4,5,6,7,8,9,10]: yield a w = 0 while w &lt; 10: print testGen().next() w += 1 </code></pre>
<p>You're creating a new generator each time. You should only call <code>testGen()</code> once and then use the object returned. Try:</p> <pre><code>w = 0 g = testGen() while w &lt; 10: print g.next() w += 1 </code></pre> <p>Then of course there's the normal, idiomatic generator usage:</p> <pre><code>for n i...
python|testing|generator|yield
10
682
326,254
Packaging a Python library
<p>I have a few Munin plugins which report stats from an Autonomy database. They all use a small library which scrapes the XML status output for the relevant numbers.</p> <p>I'm trying to bundle the library and plugins into a Puppet-installable RPM. The actual RPM-building should be straightforward; once I have a <cod...
<p>You need to create a <em>package</em> to do what you want. You'd need a directory named <code>idol7stats</code> containing a file called <code>__init__.py</code> and any other library modules to package. Also, this will affect your scripts' imports; if you put <code>idol7stats.py</code> in a package called <code>i...
python|packaging|distutils
2
683
41,978,603
removing outline color of scatter plot in matplotlib python
<p>Suppose I have gridded data with dimensions (x,y) and values are in z. so simply we can make scatter plot for third dimension by:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x = np.random.random(10) y = np.random.random(10) z = np.random.random(10) plt.scatter(x, y, c = z, s=150, cmap = 'jet'...
<ul> <li>Pass the argument <code>edgecolors='none'</code> to <code>plt.scatter</code>. The patch boundary will not be drawn. </li> <li>Pass the argument <code>marker='s'</code> to <code>plt.scatter</code>. The marker style will be square. </li> </ul> <p>Then, we have,</p> <p><a href="https://i.stack.imgur.com/kA440.p...
python|matplotlib|plot
8
684
47,418,621
Error compiling python
<p>Whenever I try to execute this code: </p> <pre><code>name = input("What's your name?") print("Hello World", name) </code></pre> <p>By running the command <code>python myprogram.py</code> on the command line, it gives me this error: </p> <pre><code>What's your name?John Traceback (most recent call last): ...
<p>In Python 2 you should use <code>raw_input</code> instead of <code>input</code> in this case.</p>
python
1
685
33,935,076
Python: Add strings to a list full of integers
<p>Simple example:</p> <p>I got a list full of integers which looks like this:</p> <pre><code>mylist1 = [1, 2, 3, 4, 5] print mylist1 [1, 2, 3, 4, 5] </code></pre> <p>Now I want to add a string to every integer in the list. It should look like this afterwards:</p> <pre><code>['1 Hi', '2 How', '3 Are', '4 You', '5 ...
<pre><code>&gt;&gt;&gt; mylist1 = [1, 2, 3, 4, 5] &gt;&gt;&gt; mylist2 = ['Hi', 'How', 'Are', 'You', 'Doing'] &gt;&gt;&gt; map(lambda x,y:str(x)+" "+y, mylist1,mylist2) ['1 Hi', '2 How', '3 Are', '4 You', '5 Doing'] </code></pre>
python|string|list|integer
4
686
29,878,151
Why is re.findall matching the string, but not returning the results correctly?
<p>I want to find a substring of the pattern <code>([A-Z][0-9]+)+</code> in another string.</p> <p>One way to do this would be:</p> <pre><code>import re re.findall("([A-Z][0-9]+)+", "asdf A0B52X4 asdf")[0] </code></pre> <p>Curiously, this yields <code>'X4'</code>, not <code>'A0B52X4'</code>, which was the result I e...
<p>It's because your matching group only matches one instance of the pattern at a time. The <code>+</code> just means to match all of them that occur in a row. It still only captures the first part of the match at one time.</p> <p>Wrap your regex in an outer group, like this:</p> <pre><code>((?:[A-Z][0-9]+)+) </code>...
python|regex|string
2
687
61,309,144
Python sqlite query based on logged username
<p><em>I am struggling to understand why I cannot get the expected result from my query. I am using flask with SQLite and can easily return the username to the webpage with the</em> <strong>"userlogin = session['username']"</strong> <em>What i am trying to get is to query the database based on the username of the logg...
<p>The sql query isn't correct. You use should <code>=</code> instead of <code>IS</code>.</p> <p>I would recommend making the following changes:</p> <p>1) use a parameterised query to avoid sql injection attacks. So pass the parameters to <code>sql_query()</code> as a tuple:</p> <pre><code>def sql_query(query, param...
python|sqlite|flask
1
688
27,891,546
Use built-in setattr simultaneously with index slicing
<p>A class I am writing requires the use of variable-name attributes storing numpy arrays. I would like to assign values to slices of these arrays. I have been using setattr so that I can leave the attribute name to vary. My attempts to assign values to slices are these:</p> <pre><code>class Dummy(object): def...
<p>Think about how you would normally write this bit of code:</p> <pre><code>d.x[0:3] = [8, 8, 8] # an index operation is really a function call on the given object # eg. the following has the same effect as the above d.x.__setitem__(slice(0, 3, None), [8, 8, 8]) </code></pre> <p>Thus, to do the indexing operating yo...
python|numpy|slice|setattr
3
689
27,804,600
Python function got 2 lists but only changes 1
<p>why does Lista1 get changed but Lista2 doesn't? which methods change directly the list?</p> <pre><code>def altera(L1, L2): for elemento in L2: L1.append(elemento) L2 = L2 + [4] L1[1]= 10 del L2[0] return L2[:] Lista1 = [1, 2, 3] Lista2 = [1, 2, 3] Lista3 = altera(Lista1, Lista2) print...
<pre><code>L2 = L2 + [4] </code></pre> <p>reassigns the address of L2 so it is a different list than was passed in .... thats the easy explanation at least</p> <p>you can see this by printing <code>id(L2)</code> before the assignment and after</p> <p>if you changed it to </p> <pre><code>L2.append(4) </code></pre> ...
python|list|methods|mutability
1
690
43,192,986
Stuck parallelisation with sklearn with large number of features (n_jobs=-1)
<p>When trying to run a simple <code>GridSearchCV</code> with <code>n_job=-1</code> often results in stuck processing. For example, </p> <pre><code>&gt;&gt; parameters_SGD = {'clf__l1_ratio': np.linspace(0,1,30), 'clf__alpha': np.logspace(-5,-1,5), 'clf__penalty':['elasticnet'], 'clf__class_weight': [None, 'balanced']...
<h1>Reason</h1> <p>Parallelization in this case is based on copying all the data and send a copy to each of the different parallel processes (sklearn is based on <a href="https://pythonhosted.org/joblib/parallel.html" rel="nofollow noreferrer">joblib</a>). This means using <code>X cores</code> needs at least <code>x-t...
python|parallel-processing|scikit-learn
1
691
43,297,903
is there a way to make movement smoother in the Python Tk canvas?
<p>I am making a dot move around a screen, but it seems to pause(stop moving) for a bit when changing direction. </p> <p>Is there a better way to make the movement smoother, or just stop the delay in changing directions?</p> <p>Here is what i am using to move it:</p> <pre><code>def keypress(event): key = (event....
<p>Naming constants makes it easier to change them and experiment, especially when the same constant is used in multiple places in the code. In the code below, you just need to change one copy of <code>20</code> to experiment, as Bryan suggested.</p> <pre><code>distance = 20 movements = { 'w': (0, -distance), ...
python|tkinter|tk
0
692
36,960,402
PYTHON - input decimal to fraction
<p>When working on <strong>python</strong>, I was able to convert a fraction to a decimal where the user would input a numerator, then a denominator and then the <code>n/d = the result</code> (fairly simple). But i can't work out how to convert a decimal into a fraction. I want the user to input any decimal ( ie <cod...
<p>Use the <code>fractions</code> module.</p> <pre><code>from fractions import Fraction f1 = Fraction(14, 8) print(f) # Output: 7/4 print(float(f)) # Output: 1.75 f1 = Fraction(1.75) print(f) # Output: 7/4 print(float(f)) # Output: 1.75 </code></pre> <p>It accepts both pairs of numerator/d...
python-3.x
1
693
48,825,031
Is there a simple way to copy text from the debug console of PyCharm?
<p>Is there a sane way to copy log text from the PyCharm console, instead of selecting it slowly with the mouse (espacially when there's a bundance of text there)? There seem to be no "Select All" from the debug console. Is it on porpose? Is there any way to copy (all of) the text from the console sanely?</p> <p>I do...
<p>With VIM emulation on:</p> <ol> <li>Use scrollbar to scroll to the end of what you want to copy. (click/drag bar) </li> <li>Click and drag up to highlight a few lines.</li> <li>Use scrollbar again to scroll to the start of what you want to copy.</li> <li>Shift/click at the start of the text you want to copy. (shoul...
python|pycharm|jetbrains-ide
0
694
48,873,893
List within a dataframe cell - counting the number of items in list
<p>I currently have a dataframe that contains a list of floats within a column, and I want to add a second column to the df that counts the length of the list within the first column (the number of items within that list). What would be the easiest way to go about doing this and would I have to write a function that it...
<p>This should work:</p> <pre><code>df['list_len'] = df['list_column'].str.len() </code></pre>
python|pandas|dataframe
2
695
48,663,698
How to read specific sheets from My XLS file in Python
<p>As of now i can read EXCEL file's all sheet.</p> <pre><code>e.msgbox("select Excel File") updated_deleted_xls = e.fileopenbox() book = xlrd.open_workbook(updated_deleted_xls, formatting_info=True) openfile = e.fileopenbox() for sheet in book.sheets(): for row in range(sheet.nrows): for col in range(sheet.ncols): th...
<p>If you open your editor from the desktop or command line, you would have to specify the file path while trying to read the file:</p> <pre><code>import pandas as pd df = pd.read_excel(r'File path', sheet_name='Sheet name') </code></pre> <p>Alternatively, if you open your editor in the file's directory, then you cou...
python|excel|xlsx
4
696
48,719,077
Is there a way to raise normal Django form validation through ajax?
<p>I found a <a href="https://stackoverflow.com/questions/7766621/django-form-validation-message-not-render-in-viewa-in-jquery-ajax-post">similar question</a> which is quite a bit outdated. I wonder if it's possible without the use of another library. </p> <p>Currently, the <code>forms.ValidationError</code> will tri...
<p>Sou you have your error response in JSON formatted as <code>{field_key: err_codes, ...}</code>. Then all you have to do is for example create <code>&lt;div class="error" style="display: none;"&gt;&lt;/div&gt;</code> under every rendered form field, which can be done by manually rendering the form field by field or y...
javascript|python|django|django-forms|django-templates
1
697
4,782,028
How to create a variable containing input from a list in Python
<p>I've a lists containing .las Files of different length. I couldn't figure out how it is possible to create a variable containing all the list entries separated by a ";" ? </p> <p>Thanks for your help,</p> <p>Mauro</p>
<p>Well am not sure if I get you but:</p> <pre><code>some_list = ['file.las', 'another_file.las', 'something.las'] e = ';'.join(some_list) </code></pre>
python
3
698
48,119,587
Regex Search program, how not to duplicate answers during iterate thru text? (Python3)
<p>I am working on a 'Regex Search' project from the book Automate boring stuff with python. I tried searching for answer, but I failed to find related thread in python.</p> <p>The task is: <em>"Write a program that opens all .txt files in a folder and searches for any line that matches a user-supplied regular express...
<p>That's because you are missing the <em>word boundaries</em> in your regular expression pattern and <code>by</code> from the "nearby" word was also matched:</p> <pre><code>In [3]: import re In [4]: whatToFind = re.compile(r'panda|by|NOUN') In [5]: s = 'The ADJECTIVE panda walked to the NOUN and then VERB. A nearby...
python|regex|python-3.x
1
699
48,037,991
Create instances from list of classes
<p>How do I create instances of classes from a list of classes? I've looked at other SO answers but did understand them.</p> <p>I have a list of classes:</p> <pre><code>list_of_classes = [Class1, Class2] </code></pre> <p>Now I want to create instances of those classes, where the variable name storing the class is th...
<p>You say that you want "the variable name storing the class [to be] the name of the class", but that's a very bad idea. Variable names are not data. The names are for programmers to use, so there's seldom a good reason to generate them using code.</p> <p>Instead, you should probably populate a list of instances, or ...
python-3.x
2