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
6,600
35,758,928
Copy Python project folder to computer without python, can I run it?
<p>So I develop a python application and I plan to copy the whole folder for my friend to use it as end-user. </p> <p>But my friend does not have python installed in the computer and I don't want to make them install it since he is not a developer. In my project I have set up the <code>virtualenv</code> with python.ex...
<p><code>virtualenv</code> is a good option if you are transferring the folder between two same operating systems. In order to include the correspond site packages that are already installed in your computer, install them inside the <code>virtualenv</code> context by doing <code>pip install</code> in the virtualenv she...
python|virtualenv
1
6,601
31,372,429
Selecting rows depending on conditions for multiple columns
<p>I have an array and I want to select rows where I have some condition on different columns of those rows in Python using NumPy. For example consider this array: </p> <pre><code>test_array = numpy.array(([1,2,3,5],[4,5,6,7],[7,8,9,4])) </code></pre> <p>Now I want all rows where column 1 is <code>1</code> and column...
<pre><code>[list(x) for x in test_array if x[0]==1 and x[3]==5] </code></pre> <p>This gives you the desired output:</p> <pre><code>[[1, 2, 3, 5]] </code></pre> <p>For an array like this</p> <pre><code>test_array=numpy.array(([1,2,3,5],[4,5,6,7],[7,8,9,4],[1,98,76,5])) </code></pre> <p>you would then obtain</p> <p...
python|arrays|numpy
1
6,602
31,257,576
OpenCV doesn't come with "external" libraries
<p>I tried <a href="https://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_feature2d/py_matcher/py_matcher.html" rel="nofollow">this example</a> from the OpenCV website:</p> <pre><code>import numpy as np import cv2 from matplotlib import pyplot as plt # changed the image names from box* since the sa...
<p>I'm not entirely sure if this is applicable, but at some point they stopped supporting SIFT in the later versions of opencv I believe due to the fact that it is patented or something related (source?), however an alternate is to use ORB which will have a similar effect. </p> <p>You could try something like this:</p...
python|opencv|dependency-management|opencv3.0
0
6,603
59,663,804
How to keep list items that fall between two values
<p>I would like to keep a list of items that fall between two values in the list.</p> <p>Below is a representation of the list I have:</p> <pre><code>List = ['Waste','Waste','Start','Data','Data','End','Waste','Waste'] </code></pre> <p>I need to keep the <code>'Data'</code> strings.</p> <p>Desired result below.</p>...
<p>Assuming <code>'Start'</code> and <code>'End'</code> elements exist, with <code>'Start'</code> occurring before <code>'End'</code>, you can use:</p> <pre><code>List[List.index('Start'):List.index('End')+1] </code></pre>
python
5
6,604
59,668,845
Duplicate value from one column in another dataframe with matching column
<p>I could not find a solution to this problem because the length of the indexes of the two dataframe is not the same so it prevents me from using all the pd.merge, join, etc..</p> <p>Here is a toy model of what I try to do:</p> <pre><code>data1= pd.DataFrame({'Supplier' : ['001', '001', '001', '001', '002', '002', '...
<p>I think your problem is that you are setting the wrong index. If you run the next line you get the result you want.</p> <pre><code>d4 = data1.join(data2.set_index("Supplier"), on="Supplier") </code></pre> <p>Output:</p> <pre><code> Supplier Quantity lead_time 0 001 200 7 1 001 ...
python|pandas
1
6,605
49,131,591
Python: remove white spaces in dictionary return 'list' object has no attribute 'rstrip'
<p>I have a dictionary which has whitespaces in the beginning and end of the items that I want to remove.</p> <pre><code>Alpha = {'Active': [{'Last': u' 0.023', 'Name': u' Bard1 Life Sciences Limited ', 'Vol': u' 439,937,304', 'pc': u' 130.0', 'Change': u' 0.013...
<p>Before solving this, you have to become aware of your structure: you don't have a dictionary with whitespaces in the beginning, but a dictionary string → list of dictionaries of whose values are some with strings having whitespace around it.</p> <p>That sounds complicated, and it is (a little bit). But that's why y...
python|dictionary|strip
3
6,606
25,107,806
Estimate formants using LPC in Python
<p>I'm new to signal processing (and numpy, scipy, and matlab for that matter). I'm trying to estimate vowel formants with LPC in Python by adapting this matlab code:</p> <p><a href="http://www.mathworks.com/help/signal/ug/formant-estimation-with-lpc-coefficients.html" rel="noreferrer">http://www.mathworks.com/help/si...
<p>The problem had to do with the order being passed to the lpc function. <code>2 + fs / 1000</code> where <code>fs</code> is the sampling frequency is the rule of thumb according to:</p> <p><a href="http://www.phon.ucl.ac.uk/courses/spsci/matlab/lect10.html" rel="nofollow">http://www.phon.ucl.ac.uk/courses/spsci/matl...
python|matlab|numpy|scipy|signal-processing
3
6,607
60,133,622
Is there a way to randomize the position of an object in python?
<p>I'm trying to program my first game where a part of the game involves randomizing the position of a red block along the x axis while keeping its y coordinate a constant. </p> <p><strong>What I actually want</strong> is for the box to appear at random positions between (-400, 350) [the left-most position] to (400, 3...
<p>You need to put <code>droid_pos</code> inside the for loop, if you put it outside it alway be constant. And you also need to put the <code>droid_box</code> initialize code outside for loop to make it only one object. Try this:</p> <pre><code>droid_box = turtle.Turtle() droid_box.speed(0) droid_box.shape("square") d...
python
0
6,608
2,938,757
File encryption with Python
<p>Is there a way to encrypt files (.zip, .doc, .exe, ... any type of file) with Python? </p> <p>I've looked at a bunch of crypto libraries for Python including pycrypto and ezpycrypto but as far as I see they only offer string encryption.</p>
<p>In Python versions prior to version 3.0, the <a href="http://docs.python.org/library/stdtypes.html#file.read" rel="nofollow noreferrer"><code>read</code> method</a> of a <a href="http://docs.python.org/library/stdtypes.html#file-objects" rel="nofollow noreferrer"><code>file</code> object</a> will return a string, pr...
python|encryption
2
6,609
2,795,331
Python download without supplying a filename
<p>How do I download a file with progress report using python but without supplying a filename.</p> <p>I have tried urllib.urlretrieve but I seem to have to supply a filename for the downloaded file to save as.</p> <p>So for example:</p> <p>I don't want to supply this:</p> <pre><code>urllib.urlretrieve("http://www....
<p>Here is a complete way to do it with python3 and no filename specified in url:</p> <pre><code>from urllib.request import urlopen from urllib.request import urlretrieve import cgi url = "http://cloud.ine.ru/s/JDbPr6W4QXnXKgo/download" remotefile = urlopen(url) blah = remotefile.info()['Content-Disposition'] value, ...
python|download|urllib2|urllib
28
6,610
5,760,030
Using ParentClass.method(self, *args, **kwargs) or super(MyClass, self).method(*args, **kwargs)
<p>When one has a class that inherits from a single class, what is the preferred, and most pythonic, way to call parent methods? There are two ways that I know of to call the parent method.</p> <p><em>Option 1:</em></p> <pre><code>ParentClass.method(self, *args, **kwargs) </code></pre> <p><em>Option 2:</em></p> <pr...
<p>First of all, if you have old-style classes you need to use <em>Option 1</em>.</p> <p>If not, it depends on the code:</p> <ul> <li>If the superclass (or subclasses) uses <code>super</code> (or nothing), you can safely use super. This also means your subclsses <em>must</em> use <code>super</code> instead of <code>P...
syntax|python
6
6,611
67,609,177
is it possible to set a position of a turtle relative to screensize
<p>say I have a screensize of 10, 10</p> <p>and a pos of 2, 2</p> <p>if screensize were changed to 5, 5</p> <p>the pos would be 1, 1</p> <p>or maybe is there a way to change relative to screen resolution?</p>
<p>turtle automatically sets up a <code>ScrolledCanvas</code> so, resizing window will attempt to keep things in approx the same position, but there's limits.</p> <p>You can place your turtle in a proportional-position to begin with, then draw from that scale.</p> <p>Just think of your sizes &amp; movements as division...
python|turtle-graphics|python-turtle
0
6,612
67,702,494
(python) Let a string be recognised as a already defined variable
<pre><code>x= 1 a_1_add = &quot;message 1&quot; a_2_add = &quot;message 2&quot; while x&lt;3: y = &quot;a_&quot; + x + &quot;_add&quot; print(y) x += 1 </code></pre> <p>How do I get python to get make it print &quot;message 1', &quot;message 2&quot; instead of &quot;a_1_add&quot;? I want to <strong>specifica...
<p>Since you're beginner, I would assume, you should look toward something like this instead:</p> <pre><code>a_1_add = &quot;message 1&quot; a_2_add = &quot;message 2&quot; container = [a_1_add, a_2_add] for element in container: print(element) </code></pre> <p>Note, you can still access the contents of both vari...
python|string|variables
1
6,613
66,885,351
How to get rid of the default window in QT5
<p>how can I get rid of the &quot;outside default window&quot; on my QT5 project ?</p> <p>What I have : <a href="https://i.stack.imgur.com/jRyjC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jRyjC.jpg" alt="" /></a></p> <p>What I want : <a href="https://i.stack.imgur.com/8cm3m.jpg" rel="nofollow no...
<p>Use <code>Qt.FramelessWindowHint</code></p> <pre class="lang-py prettyprint-override"><code>from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import Qt if __name__ == &quot;__main__&quot;: app = QtWidgets.QApplication([]) widget = QtWidgets.QWidget() widget.setWindowFlags(widget.windowFlags()...
python|pyqt5|qt5
2
6,614
64,088,157
How to downgrade CUDA to 10.0.10 with conda, without conflicts?
<p>I would like to go to CUDA (cudatoolkit) version compatible with <code>Nvidie-430</code> driver, i.e., <code>10.0.130</code> as recommended by the <a href="https://docs.nvidia.com/deploy/cuda-compatibility/index.html" rel="nofollow noreferrer">Nvidias site</a>.</p> <p>Based on <a href="https://stackoverflow.com/a/23...
<p>Check current version with</p> <pre><code>torch.version.cuda </code></pre> <p>I had 10.2. But I need 10.1 according to: table 1 <a href="https://docs.nvidia.com/deploy/cuda-compatibility/index.html" rel="nofollow noreferrer">here</a> and my 430 NVIDIA driver installed.</p> <p><strong>Uninstall and Install</strong></...
python|pytorch|conda
0
6,615
42,585,931
Does calling the new_csrf_token() method on a Pyramid session object invalidate previously issued tokens?
<p>Using the Pyramid web framework, when the <code>new_csrf_token()</code> method is called on a session object, does it invalidate previously issued CSRF tokens?</p> <p>For example:</p> <pre><code>old_token = session.get_csrf_token() new_token = session.new_csrf_token() # Is old_token still valid for requests? </cod...
<p>Calling the <code>new_csrf_token()</code> method on one of Pyramid's session objects will invalidate all previously issued CSRF tokens for that session.</p> <p>Pyramid's <code>ISession</code> interface only defines two methods that deal with CSRF tokens, <code>get_csrf_token()</code> and <code>new_csrf_token()</cod...
python|session|csrf|pyramid|csrf-protection
2
6,616
42,594,477
Use python pandas to find consecutive same values string and sum duration
<p>I'm new to pandas and I'm a bit confused about how to get my program to work. I found some solutions out there but they don't work properly in my case. I have the following dataframe:</p> <pre><code># Day Date/Time Applicationname 1 2016-11-30 2016-11-30 01:27:47.722 comtesl...
<p>From your solution example it seems like you want to group by day as well, even though you don't explicitly mention that. If that's the case you should be able to do something like this:</p> <pre><code>grouped = df.groupby(['Day', 'Applicationname']) min_max = grouped.agg({'Date/Time': [np.min, np.max]}) </code></p...
python|pandas|dataframe
0
6,617
42,988,507
Hashed password becomes the real password
<p>When I try to change user's fields in the django admin and then I save it, the hashed password ends up becoming the true password.</p> <p>So, If the password is hashed like this pbkdf2adhfkhadqeqerqfavghhfyb, and I change another field in the users model, this hashed password becomes my not hashed password.</p> <p...
<p>I think this is occurring because the <code>UserChangeForm</code> default uses a <code>ReadOnlyPasswordHashField</code> for the field <code>password</code>.</p> <p>I would try:</p> <pre><code>class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)...
python|django|django-forms|django-admin
1
6,618
42,630,717
Keep getting element is not attached to the page document
<p>I am running the following code to verify the text on the page:</p> <pre><code>def verifyText(self, Text): try: self.switchToFrame(*MainPageLocatars.FRAMEONE) self.switchToFrame(*MainPageLocatars.SUBLISTFRAME) except: pass self.row.find_element_by_xpath(ListViewLocatars.VERIFYTEXT %...
<p>This is simplified version of how <code>StaleElementReferenceException</code> can be triggered and how to avoid it.</p> <p>I suppose your code works like below:</p> <pre><code>self.row = self.driver.find_element_by_xpath(ListViewLocatars.ROWPARENT % INDEX_MAP[index]) # Now your self.row is accessible. You can use ...
python|selenium
1
6,619
42,769,544
Configure setup.py to install requirement from repository URL
<p>I am creating a module and need to prepare my <code>setup.py</code> file to have some requirements. One of the requirements is a fork of one package that is already in PyPI so I want to reference my GitHub repository directly.</p> <p>I tried two configurations, the first one is:</p> <pre class="lang-py prettyprint...
<p>For dependency links to work you need to add the version number of the package to <code>https://github.com/ihhcarus/myrequirement.git#egg=myrequirement_alt</code>. or it will not know what to install.</p> <p>e.g.:</p> <pre><code>setup( 'name': 'mymodule', # other arguments install_requires=[ '...
python|pip|setuptools|pypi|egg
1
6,620
66,654,504
TypeError: expected str, bytes or os.PathLike object, not int
<p>So I am trying to make a Twitter bot that will automatically reply, like, and Retweet the Tweet which mentions a certain <code>#</code>. In the code below, whenever someone mentions the bot and <code>#amrevx</code> in their Tweet, it's going to automatically reply, like, Retweet, and also store the Tweet ID so it do...
<p>On the last line of your reply function, you have <code>store_last_seen(FILE_NAME, tweet.id)</code>.<br /> You're passing <code>FILE_NAME</code> as <code>last_seen</code> and <code>tweet.id</code> as <code>FILE_NAME</code>, instead of the other way around.</p>
python|twitter|tweepy
0
6,621
51,096,446
how to transfer log files from cloudwatch logs to redshift
<p>Anybody have any idea? please help </p>
<p>Though question is very generic and constrained are not specified, hence there could be multiple solutions. But in my opinion, following could be good approach.</p> <ol> <li>Export Cloudwatch Logs to S3</li> <li>Copy logs from S3 to Redshift using Copy command</li> </ol> <p>Here are some basic information about S...
python-2.7|amazon-web-services|amazon-redshift|local|amazon-cloudwatchlogs
0
6,622
51,048,839
Python -- how do I successfully copy data from one object and change one variable without changing the other?
<p>I would like to do something like this:</p> <pre><code>class test(): def __init__(self): self.initfunc() def initfunc(self): self.a = 'test' a = test() b = test() a = b a.a = 'test3' b.a = 'test4' print(a.a, b.a) </code></pre> <p>The output is:</p> <pre><code>test4 test4 </code></pre> ...
<p>It is not entirely clear to me what you want to achieve, but after</p> <pre><code>a = b </code></pre> <p>both names point to the same object. You can verify this like so:</p> <pre><code>a = test() b = test() print(id(a), id(b)) a = b print(id(a), id(b)) </code></pre> <p>In other languages you maybe call thi...
python|python-3.x
0
6,623
3,486,536
Wxpython app exiting abnormally
<p>I have a wxpython app designed using XRC which has a multiline textctrl inside nested boxlayouts.</p> <p>I'm adding some text(retrieved from the web) to the text control using SetValue(), inside the longtask method from a separate thread using the following code</p> <pre><code>thread.start_new_thread(self.longta...
<p>Directly calling methods of GUI elements from a different thread is dangerous. Without getting too much into your code, I'd recommend you to consider a robust multi-threaded design. For example, you can use <code>Queue</code> objects to pass data between threads. Alternatively, use wx's events.</p> <p><a href="http...
python|wxpython
2
6,624
3,324,920
Use of properties in python like in example C#
<p>I currently work with Python for a while and I came to the point where I questioned myself whether I should use "Properties" in Python as often as in C#. In C# I've mostly created properties for the majority of my classes.</p> <p>It seems that properties are not that popular in python, am I wrong? How to use proper...
<p>Properties are often no required if all you do is set and query member variables. Because Python has no concept of encapsulation, all member variables are public and often there is no need to encapsulate accesses. However, properties are possible, perfectly legitimate and popular:</p> <pre><code>class C(object): ...
c#|python|properties
14
6,625
56,473,741
Calculating confidence interval as quantile
<p>I need to find the 95% confidence interval as 2.5 and 97.5 quantiles</p> <pre><code>boot_mean_diff = [] for i in range(3000): boot_before = before_proportion boot_after = after_proportion boot_mean_diff.append(boot_after.mean()-boot_before.mean()) # Calculating a 95% confidence interval from boot_mean_...
<p>I was too facing the same error. Try the below code</p> <pre><code># A bootstrap analysis of the reduction of deaths due to handwashing boot_mean_diff = [] for i in range(3000): boot_before = before_proportion.sample(frac=1, replace=True) boot_after = after_proportion.sample(frac=1, replace=True) boot_m...
python|confidence-interval
0
6,626
45,016,458
TensorFlow: tf.summary.text and linebreaks
<p>How do you use tf.summary.text to emit text that contains linebreaks?</p> <p>I have tried replacing <code>'\n'</code> with <code>&lt;br&gt;</code> but I cannot get the output to show proper linebreaks. Without proper linebreaks makes it very hard to read yaml output as shown here:</p> <p><a href="https://i.stack.i...
<p>Tensorboard <code>text</code> uses the markdown format (though it doesn't support all its features). That means you need to add 2 spaces before <code>\n</code> to produce a linebreak, e.g. <code>line_1 \nline_2 \nline_3</code></p>
text|tensorflow|summary|tensorboard
18
6,627
64,738,062
Keep the subprocess program running and accepting new arguments
<p>I have the program that takes about 4-5 seconds to launch each time I open it with Python's subprocess:</p> <pre><code>command = ['./command', arg1] # my command to launch the program p = subprocess.Popen(command, stdout=subprocess.PIPE, bufsize=-1) # launch the program (takes about 4 seconds) print(p.stdout.read()...
<p>When <code>run</code> returns, the program you ran <em>has exited and is no longer in memory</em>. There's no pre-initialized copy still in RAM to reuse (by re-invoking its <code>main</code> with different arguments).</p>
python|python-3.x|shell|command-line|subprocess
1
6,628
61,347,195
How can i try all possible combinations of a dataframe, but mantaining the order of row items, in Python?
<p>As the title goes,i have to maintain the order of row items , so , something as "combinations" from itertools doesn't actually help</p> <p>what this means, if you think about it, is that we have to shift the space between items in columns to have different combinations that don't change order. example:</p> <p>Fro...
<p>I'm not sure I'm clear on what you're looking to do, but I think this might be it.</p> <pre><code># setup mock dataframe meals_df = pd.DataFrame([ {"MON": "bread", "TUE": "chocolate", "WED": "wine", "THU": "chocolate"}, {"MON": "pizza", "TUE": "bread", "WED": "bread", "THU": "chocolate"}, {"MON": "bread...
python|python-3.x|dataframe|combinations|itertools
1
6,629
61,602,572
ValueError: Found input variables with inconsistent numbers of samples: [84, 5]
<p>I am making a CNN model using VGG16 and some custom layers at the end. The dataset is as follows:</p> <pre><code>Found 200 images belonging to 2 classes. Found 84 images belonging to 2 classes. </code></pre> <p>The hyperparameters are:</p> <pre><code>epochs= 25 lr = 1e-4 BS = 16 </code></pre> <p>The model is as...
<p>your y_pred and test_generator.classes should have the same shape its either a [5, 5] or a [84,84]</p>
tensorflow|keras|deep-learning|computer-vision|confusion-matrix
0
6,630
57,971,925
How to delete a directory in Python 3.x with files in it?
<pre><code>import os shutil.rmtree('Path') </code></pre> <p>It does not delete it and gives me an error. I am using Python 3.7.4 The error is </p> <blockquote> <p>Traceback (most recent call last): File "C:\Users\Muneeb Khurram\Desktop\gpa.py", line 2, in shutil.rmtree('C:/Users/Muneeb Khurram/Desktop/P...
<p>First you need to <code>pip install shutil</code> into your computer. And <code>import shutil</code>, before you use <code>shutil.rmtree('Path')</code>.</p>
python-3.x
2
6,631
56,037,524
Unable to install openpifpaf and pycocotools with pip. ERROR: Failed building wheel for openpifpaf/pycocotools
<p>Configuration:</p> <ul> <li>macOS 10.14</li> <li>Python 3.7.1</li> </ul> <p>I am trying to install pycocotools and openpifpaf by issuing this command that should install <code>openpifpaf</code> and <code>pycocotools</code>:</p> <pre><code>pip3 install 'openpifpaf[train,test]'==0.5.2 </code></pre> <p>as it is men...
<p><code>pycocotools</code> is a bit special. It requires pre-installed <code>Cython</code> and <code>numpy</code> and pure pip cannot handle an order in the dependencies. You have to run <code>pip3 install numpy cython</code> before you can install openpifpaf with the <code>train</code> dependency.</p> <p>I hope you ...
python|macos|pip|installation
1
6,632
56,088,646
flask pass variable from one function to another function
<p>As you can see the code. I want to pass variable <code>q</code> from function <code>home()</code> into function <code>search()</code>.</p> <pre><code>@app.route("/",methods=['GET','POST']) def home(): result = Mylist.query.all() return render_template('index.html',result=result) q = request.form.get("q"...
<p>Where an <code>index.html</code> will contain:</p> <pre><code>&lt;form action="/search.html" method="get" autocomplete="off" class="subscribe-form"&gt; &lt;div class="form-group d-flex"&gt; &lt;input type="text" class="form-control" placeholder="Enter your search" name="q" id="q" value="{{q}}"&gt; ...
python|function|flash-message
4
6,633
18,659,844
Python inverse template, get vars from a string
<p>With <a href="http://docs.python.org/2/library/string.html#template-strings" rel="nofollow">python template</a>, I can generate outputs. like </p> <pre><code>&gt;&gt;&gt; from string import Template &gt;&gt;&gt; s = Template('$who likes $what') &gt;&gt;&gt; s.substitute(who='tim', what='kung pao') 'tim likes kung p...
<p>You'd have to parse the string. One approach is to use a regular expression:</p> <pre><code>import re m = re.match(r'(.*?) likes (.*?)', 'tim likes kung pao') if m: who, what = m.groups() </code></pre> <p>Note that this is subject to ambiguity; for example, what happens if you pass the string "tim likes mary w...
python|string|templates
2
6,634
69,352,765
Invoke Lambda in another region and make changes in the invoked region
<p>I'm pretty sure I know the answer, but I thought I'd ask anyways. Is there a way to invoke a Lambda function in another region but utilize data in the invoked region. I am able to invoke a Lambda function from one region in another, but the invoked function runs against the region that it's in. What I'm attempting t...
<p>In general, with the Python boto3 api, when you create a client you specify the region for that client. <a href="https://stackoverflow.com/a/40377889/230055">https://stackoverflow.com/a/40377889/230055</a> is a useful reference. So in your code, you would need to make it so the value given for <code>region_name</c...
python|amazon-web-services|aws-lambda
2
6,635
55,361,836
Is it possible to overwrite a Python built-in for the whole Python package?
<p>I have a Python package with dozens of subpackages/modules. Nearly each of the modules uses <code>open</code> built-in Python function. I have written an own implementation of the file opening function and would like to "redirect" all <code>open</code> calls I have in the package modules to <code>my_open</code> func...
<p>Think about what you're asking to do with this module: you've written your own package, a personal change to the way a built-in function is linked. You want to redefine a standard language feature. That's okay ... part of the power of a language is the capability to do things the way you define.</p> <p>The proble...
python|package|built-in|monkeypatching|shadowing
1
6,636
42,458,082
Regex: How can i get both teams of an event as cleanly as possible
<p>I have been trying for a while now to successfully parse through bookmaker sites and retrieve markets/odds.</p> <p>I have come to a point where I fetch the .text attribute of a Selenium web-element so I have something like this:</p> <p><strong>Edited to showcase more examples</strong></p> <pre><code>BPZ vs Griffi...
<p>This pattern should do the trick:</p> <pre><code>(?P&lt;event&gt;(?P&lt;outcome1&gt;[^-]+?) vs (?P&lt;outcome2&gt;[^-]+) -.*?) -[^\b]*?(?P&lt;date&gt;(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) \d+/\d+(?:/\d+)?)[^.]*(?P&lt;outcome1odds&gt;\d+\.\d+)\s+(?P&lt;time&gt;\d+:\d+[AP]M)[^.]*(?P&lt;outcome2odds&gt;\d+\.\d+) </code></pr...
python|regex|string
1
6,637
53,879,189
How do I use parameter epsabs in scipy.integrate.quad in Python?
<p>I am trying to compute the integrals more precise by specifying the parameter <code>epsabs</code> for <code>scipy.integrate.quad</code>, say we are integrating the function <em>sin(x) / x^2</em> from 1e-16 to 1.0</p> <pre class="lang-py prettyprint-override"><code>from scipy.integrate import quad import numpy integ...
<p>According to scipy manual <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html#scipy.integrate.quad" rel="noreferrer">quad function</a> has <code>limit</code> argument to specify </p> <blockquote> <p>An upper bound on the number of subintervals used in the adaptive algorithm.</p...
python|scipy|precision|integrate|quad
5
6,638
22,584,431
How to properly set GEOIP_PATH for Django in OS X?
<p>I'm just doing my first steps with Python a Django and I'd like to use it with GeoIP on my Mac. I've used Homebrew and pip for installing everything I need, but I haven't figured out how to set path for GeoIP. So I always get this error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line...
<p>You need the GeoIP data which you can <a href="http://dev.maxmind.com/geoip/legacy/geolite/" rel="noreferrer">download from MaxMind</a>, and you need to set up GEOIP_PATH in your settings.py module to point to wherever you download that GeoIP data. </p> <p>Your directory structure might not be exactly the same as ...
python|django|macos|python-2.7
5
6,639
22,941,804
Find the minimum and display the variable name in python
<p>You have got three variables like</p> <pre><code> a = 1 b = 2 c = 3 </code></pre> <p>and you find the minimum can you somehow display the variable name instead of the value it has</p> <p>Example</p> <pre><code> d = min[a,b,c] </code></pre> <p>after this operation d should become c since c is the grea...
<p>Put variables into a dictionary and call <code>min()</code> with specifying dictionary <code>get</code> as a <code>key</code>: </p> <pre><code>&gt;&gt;&gt; a = 1 &gt;&gt;&gt; b = 2 &gt;&gt;&gt; c = 3 &gt;&gt;&gt; data = {'a': a, 'b': b, 'c': c} &gt;&gt;&gt; min(data, key=data.get) 'a' </code></pre>
python
5
6,640
22,479,267
Large loop nest design, anyway to improve speed?
<p>I want to loop through a list and check all the possible combinations in it. Currently, I'm using a series of nested for loops, and obviously I'm not ecstatic with the speed using this method. It's very slow and can take 20-30 minutes to go through all the combinations.</p> <pre><code>for n1 in list1: list.appe...
<p>It looks like you want to cover all combinations of one item picked from <code>list1</code>, then two each from <code>list2</code> - <code>list5</code>. If correct, you can certainly make things more efficient:</p> <pre><code>from itertools import chain, combinations, product for comb in product(combinations(list1...
python|performance|algorithm
4
6,641
28,558,807
Multiple Excel sheets to txt
<p>I am new to python , and I need to perform Sentiment Analysis on multiple excel sheets in a folder.Is there any way to convert these excel sheets to txt files for sentiment analysis?</p>
<p>You can use <a href="https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html?p=4966" rel="nofollow">xlrd</a> to read Excel files.</p>
python|nltk
0
6,642
28,530,102
How to detect facial angles?
<p>I have over 2000 grayscale images with 96x96 pixel dimensions in numpy. I have (x,y) coordinated of facial key points such as left_eye_center, right_eye_center, nose_center, mouth_left, mouth_right etc..</p> <p>Many of the faces in the dataset are tilted either left or right or up or down. So I would like to find o...
<p>cmon, it's just plain maths:</p> <pre><code> double eyeXdis = eye_r.x - eye_l.x; double eyeYdis = eye_r.y - eye_l.y; double angle = atan(eyeYdis/eyeXdis); double degree = angle*180/CV_PI; </code></pre> <p>[edit:]</p> <p>it seems, what you're looking for is actually "head pose estimation" (or "po...
opencv|numpy|machine-learning
1
6,643
6,579,876
How to match a substring in a string, ignoring case
<p>I'm looking for ignore case string comparison in Python.</p> <p>I tried with:</p> <pre><code>if line.find('mandy') &gt;= 0: </code></pre> <p>but no success for ignore case. I need to find a set of words in a given text file. I am reading the file line by line. The word on a line can be <em>mandy</em>, <em>Mandy</...
<p>If you don't want to use <code>str.lower()</code>, you can use a <a href="http://en.wikipedia.org/wiki/Regular_expression" rel="noreferrer">regular expression</a>:</p> <pre><code>import re if re.search('mandy', 'Mandy Pande', re.IGNORECASE): # Is True </code></pre>
python|perl
197
6,644
57,026,129
converting to exe and modules suddenly not working
<p>I am using pyinstaller to convert my .py file to exe. When I run my py file from the command line, it works perfectly, however when I convert it to .exe using pyinstaller, I get errors on lines containing modules I imported. I understand I may need to edit the spec file, however even with this I am very confused. A...
<p>PyInstaller would handle all the above modules except for <code>pandas</code> module which needs to be used with <a href="https://pythonhosted.org/PyInstaller/advanced-topics.html#the-toc-and-tree-classes" rel="nofollow noreferrer"><code>Tree</code></a> class to bundle lib folder with executable.</p> <p>I only add ...
python|module|exe|pyinstaller
0
6,645
57,110,071
How to start Eclipse from Ubuntu on startup
<p>I want to start Eclipse on startup of Ubuntu 18. Because I need the variables from .bashrc I need to start it from the terminal. Manually starting eclipse from the terminal works. But it won't start on startup when I use a script.</p> <p>I have a python3 script running on startup of Ubuntu 18. I want to start Eclip...
<p>I've found the solution. The problem was the location of eclipse. It was installed in the home directory. The solution was to add this path to ~/.profile and to export my toolchain paths.</p>
python|python-3.x|eclipse|ubuntu
0
6,646
57,121,649
Get JavaScript Web by requests-html given OpenSSL.SSL.Error'SSL routines', 'tls_process_server_certificate', 'certificate verify failed
<p>I'm following this <a href="https://html.python-requests.org/" rel="nofollow noreferrer">guide of requests-html</a> library and found this error in my laptop.</p> <p>In JavaScript Support I try to code like this page:</p> <pre><code>from requests_html import HTMLSession session = HTMLSession() r = session.get('htt...
<p>I solve problem with :</p> <pre><code>pip install pyppdf </code></pre> <p>then in the code first use:</p> <pre><code>import pyppdf.patch_pyppeteer </code></pre> <p>Source : <a href="https://github.com/miyakogi/pyppeteer/issues/258#issuecomment-563075764" rel="nofollow noreferrer">https://github.com/miyakogi/pypp...
javascript|python-3.x|python-requests
3
6,647
25,689,649
dictionary difference operation
<p>I have two dictionaries, A and B, and I want to take those key:value pairs that exist in B but not A, and add them to A. I don't want the values of B with matching keys to be added to or overwritten in A.</p> <pre><code>A = {'one':1, 'two':2} B = {'one':1, 'two':999, 'three':3} </code></pre> <p>I want the resultin...
<p>You can use <a href="https://docs.python.org/3/library/stdtypes.html#dict.setdefault" rel="nofollow"><code>dict.setdefault()</code></a>:</p> <pre><code>A = {'one':1, 'two':2} B = {'one':1, 'two':999, 'three':3} for k,v in B.items(): A.setdefault(k, v) print(A) </code></pre> <pre> {'two': 2, 'one': 1, 'three'...
python|dictionary
3
6,648
25,478,527
Convert Data Pulled from Server To String
<p>I have been working on a TwitchTV Python chat bot for a while now, but I'm still getting to grips with Python.</p> <p>It may seem simple, but this has confused me so I decided I would ask:</p> <p>I'm currently pulling messages from Twitch Chat using <code>data = irc.recv</code></p> <p>What I want to do is use the...
<p>Try this:</p> <pre><code>data = irc.recv (4096) # msg = data() capsTime = "30s" mystr = repr(data) if mystr.isupper(): message("[-] Woah! Hold back on the caps! (Timeout " + capsTime + ")") message("/timeout " + user + capsTime) # variable "user" already defined </code></pre> <p>Don't use reserved keyword.</...
python|string|twitch|chatbot
0
6,649
44,773,579
Django template nested for loop
<p>I have 2 tables:</p> <pre><code>Table1: [A-Foriegn Key, field1] Table2: [Table1-Foriegn Key, field2] </code></pre> <p>I want to display a list with distinct values of Table1 field1 if items are present in Table2. and inside that list I want to display all the elements of Table2 corresponding to that field1 of Tabl...
<p>You can use foreign key mappings in the templates to reference objects.</p> <p>Suppose you have two tables Table1 and Table2, with a mapping like Table1 -&gt; Table2, with a foreign key field in Table2 referencing Table1, you can do something like this:</p> <p>Your <code>views.py</code> would be something like this:...
python|django-templates
5
6,650
44,514,968
Numpy for windows 10 64 bit python 2.7
<p>I tried installing numpy 1.11.2 on my windows 10 64 bit pc. but I have problem importing it in python(version 2.7 64 bit), what steps should i follow. and if a wheel has to be installed then which verison and how do i install it please?</p>
<p>You can use the Anaconda distribution which comes with many scientific packages preinstalled from <a href="https://www.continuum.io/DOWNLOADS" rel="nofollow noreferrer">here</a></p> <p>I am sure you tried <code>pip install numpy</code> , an alternative would be to download numpy wheel from here <a href="http://www....
python|windows|numpy
1
6,651
44,385,147
using groupby attribute in pandas
<p>I have a DataFrame with 3 columns (A,B,C) and a large number of rows. There are different types of elements in each of these columns: A1,A2... B1,B2... and C1, C2... respectively.</p> <p>I want to find the number of times a particular combination (say (A1,B2,C2)) occurs in a row. Then I want to generate a (summary)...
<pre><code>df = pd.DataFrame({'A':['A1','A1','A2','A3'], 'B':[4,4,6,4], 'C':[7,7,9,7]}) print (df) A B C 0 4 7 C1 1 4 7 C1 2 6 9 C2 3 4 7 C3 </code></pre> <p>For count of all combination use <a href="http://pandas.pydata.org/pandas-docs/stable/generated...
python|pandas|numpy|dataframe|frequency
1
6,652
61,980,420
How to access parent of a node in n-ary tree?
<p>I am trying to create a Node class that implements an n-ary tree but I also want to keep track of the parent of each node to trace back to the root. </p> <pre><code>class Node(object): def __init__(self, state, children=None, parent=None): self.state = state self.children = children or [] ...
<pre><code>self.children.append(Node(obj)) </code></pre> <p>Here you are creating a Node instance on the fly and appending it to the children list</p> <pre><code>Node(obj).parent = self.state </code></pre> <p>That is an extra instance of Node on the fly which you are assigning its parent to be self.state</p> <p>I t...
python|class|tree|nodes|parent
1
6,653
23,783,236
Python: isPrime function much slower after adding lookup of pregenerated list?
<p>I am solving Project Euler problems with Python. I have seen some solvers use <code>isPrime()</code> functions that simply test whether <code>x % y == 0</code> for all y from <code>2 to x ** 0.5</code>. That is not efficient and I want to write a better <code>isPrime()</code> function, based on the <code>num % 30</c...
<p>The reason it is slower is because the list lookup is O(n). Instead of using lists use sets:</p> <pre><code>primes = set() primes.add(num) </code></pre> <p>The <code>num in primes</code> check will be now O(1).</p> <p>Also forget about this "optimization": <code>primes[3:]</code>. It actually slows down your code...
python|performance|primes
5
6,654
35,877,058
matplotlib annotate basemap in data coordinates
<p>I have a hammer projection plot which I am trying to add text at the center of the plot (latitude = 0, longitude = 0). For some reason, the string '0' is plotted at the bottom left of the figure.</p> <p>I have the following code.</p> <pre><code>from mpl_toolkits.basemap import Basemap import numpy as np import mat...
<p>You have to first convert your latitude/longitude coordinates to their equivalent x,y coordinates using your <a href="http://matplotlib.org/basemap/api/basemap_api.html#mpl_toolkits.basemap.Basemap" rel="noreferrer">Basemap</a> instance. matplotlib does not do this automatically for you because it doesn't know anyth...
python|matplotlib|matplotlib-basemap|annotate
5
6,655
35,918,605
How to delete a table in SQLAlchemy?
<p>I want to delete a table using SQLAlchemy.</p> <p>Since I am testing over and over again, I want to delete the table <code>my_users</code> so that I can start from scratch every single time.</p> <p>So far I am using SQLAlchemy to execute raw SQL through the <a href="http://docs.sqlalchemy.org/en/latest/core/connec...
<p>Just call <code>drop()</code> against the table object. From <a href="http://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.Table.drop" rel="noreferrer">the docs</a>: </p> <blockquote> <p>Issue a DROP statement for this Table, using the given Connectable for connectivity.</p> </blockquote> <p...
python|sqlite|sqlalchemy|drop-table
81
6,656
29,779,195
Python Numpy efficient Polar euclidean distance
<p>I have a list of n polar coordinates, and a distance function which takes in two coordinates.</p> <p>I want to create an n x n matrix which contains the pairwise distances under my function. I realize I probably need to use some form of vectorization with numpy but am not sure exactly how to do so.</p>
<p>A simple code segment is below for your reference</p> <pre><code>import numpy as np length = 10 coord_r = np.random.rand(length)*10 coord_alpha = np.random.rand(length)*np.pi # Repeat vector to matrix form coord_r_X = np.tile(coord_r, [length,1]) coord_r_Y = coord_r_X.T coord_alpha_X = np.tile(coord_alpha, [leng...
python|numpy|matrix|vectorization|euclidean-distance
1
6,657
46,533,994
User.py Exception Type: TypeError Exception Value: 'Manager' object is not iterable
<p>Hello I have a little problem in Django, I created a database and now I want to print the queries of this, so I have in my user.py file the following code </p> <pre><code>def user(request): user_list = User.objects user_dict = {'user_data': user_list} return render(request,'AppTwo/User.html',context=user_dict) <...
<p><code>User.objects</code> doesn't return a result as a <a href="https://docs.djangoproject.com/en/1.11/ref/models/querysets/" rel="nofollow noreferrer">queryset</a>, it's just the reference to the <em>manager</em> associated to the model. </p> <p>A <em>Manager</em> is a class object which provides all the methods a...
python|django
3
6,658
46,385,453
QISKit Implementation of the Cuccaro Adder
<p>I'm new to quantum computing and am trying to codify a 2bit Cuccaro et all adder as described here: <a href="https://arxiv.org/pdf/quant-ph/0410184.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/quant-ph/0410184.pdf</a> and here: <a href="https://arxiv.org/pdf/1202.6614.pdf" rel="nofollow noreferrer">https://a...
<p>Figured it out! My syntax for CNOT's was inverted. Needed to open an example in Composer and see the QASM statements</p>
python-3.x|ibm-cloud|quantum-computing|qiskit
0
6,659
46,570,170
Calculating an average of multiple random numbers Python
<p>I am fairly new to Python and have run into a roadblock with trying to calculate an average of a bunch of random numbers.The general overview of the program is that it is a die rolling program which prompts the user to enter a certain amount of sides and it then rolls until the program outputs snake eyes. It also ke...
<p>I made a few changes in your code if you like to take a look. I assumed that you wanted the average to be calculated as an integer although you can change that. You use <code>die_1</code> and <code>die_2</code> as simple integer variables and thus they hold only the last value generated by <code>random.randint(1,use...
python|python-3.x|python-3.6
0
6,660
49,717,006
Exhaustive list of links for a specific domain
<p>I have a function that parses the content of a given URL (usually the root of a domain) and returns a list of all links which point somewhere else within that domain –it doesn't include external links and it doesn't allow repeated links.</p> <p>What would be the most simple way to run that function for each of the ...
<p>This is simple algorithm to do that</p> <pre><code>links_to_crawl = set() crawled_links = set() def function crawl(link): if (link not in crawled_links): new_links = findAllLinks (link) for new_link in new_links: #if new_link is not external: links_to_crawl.add(new_link) ...
python-3.x|list|recursion|hyperlink
0
6,661
21,321,804
Django Categories Admin interface behaviour
<p>I am confused with the django-categories admin interface:</p> <p>My code:</p> <pre><code># views.py from django.db import models from categories.models import CategoryBase class Category(CategoryBase): pass class Article(models.Model): titl...
<ol> <li><p>django-categories is registering the first one in its <code>admin.py</code>, and you are registering the second one in your <code>admin.py</code>. </p> <p>You only need both if you are planning to use both the provided <code>Category</code> model and your own custom model derived from <code>CategoryBase</c...
python|django|django-admin
0
6,662
21,011,953
QUiLoader.createWidget equivalent in PyQt
<p>I have a PySide application that I'm investigating making compatible with PyQt4. Obviously this shouldn't be too difficult, but I'd like to minimise the number of code changes necessary. The biggest difference I've come across (which affects my program) is the fact that PyQt does not wrap the <code>QUiLoader</code> ...
<p>This turns out to be quite easy, so long as you are willing to promote the relevant widgets in Qt Designer.</p> <p>The idea is to add a dummy module to <code>sys.modules</code> and then dynamically modify the custom widget classes it contains.</p> <p>So if the "Header file" was set to "mylib.dummy" when promoting ...
python|pyqt|pyside
1
6,663
70,269,022
How to send javascript list from template to request.POST (django framework)
<p>I have the javascript below that gets all checked box and it works well.</p> <pre><code>&lt;script&gt; function addlist() { var array = [] var checkboxes = document.querySelectorAll('input[type=checkbox]:checked') for (var i = 0; i &lt; che...
<p>I solved the question in the follow way:</p> <p>I created a hidden input to receive the list by javascript:</p> <pre><code> &lt;script&gt; function addlist() { var array = [] var checkboxes = document.querySelectorAll('input[type=checkbox]:checked') for (var i = 0; i &...
javascript|python|django
0
6,664
70,155,913
When trying to save a workbook with openpyxl i get a TypError - why?
<p>I'm building an application with which my company analyzes provided table data.</p> <p>So far so good, but when I try to save the results to a workbook, I get a</p> <blockquote> <p>TypeError: '&lt;' not supported between instances of 'str' and 'int'</p> </blockquote> <p>Does anyone know what to do about it?</p> <p>t...
<p>Your problem is this line:</p> <pre><code>col = ss.row_dimensions['23'] </code></pre> <p><code>row_dimensions</code> appears to accept either an integer or string input. However, when saving it requires an integer input, not a string. Admittedly, I found this quite hard to find and had to do a deep dive into openpyx...
python|openpyxl
1
6,665
45,866,371
nptdms channel_data doesn't load the data I see in the file, why?
<p>I have an issue with reading tdms files with nptdms module, I seem to use it correctly looking at the examples but the output differs from expected. Here is my code:</p> <pre><code>tdms_file = TdmsFile("path_to_file\file.tdms") channel0 = tdms_file.object("FBdata", "FBchannel0") data0 = channel0.data print data0[0]...
<p>In the meantime I solved the issue. Apparently the tdms files were produced with a " , " delimiter and this was causing the issue. Once the settings in LabView were changed to specify " . " as the delimiter, the produced files could be correctly read with the npTDMS Python module. </p>
python|labview
0
6,666
46,061,738
How to extract specific fields and values from a JSON with python?
<p>I am iterating a JSON and I want to extract the following fields from this object:</p> <ol> <li>Id, </li> <li>Open_date</li> <li>User </li> <li>Ticket_status</li> <li>End_date </li> </ol> <p>The data structure that I have is like the following :</p> <pre><code>filtered_data = [{'id': 1021972, 'Aging_Deferred_Tr...
<p><code>filtered_data</code> is an ordinary list, so you can access individual dictionaries from it using ordinary indexing or iteration. You can take each element and put them into a new dictionary, keyed by user name:</p> <pre><code>filtered_data = [{'id': 1021972, 'Aging_Deferred_Transferred': '', 'Aging_Open_Issu...
python|json|python-3.x
3
6,667
46,026,134
python threading why I can use global variable outside the thread only once
<p>I'd like to use variable a outside my thread. In this example, I was expecting the program to print "a" every time after "update()" runs. I got "a" to print once, but that was it, I can see "updating" printed every second, so I know my thread is running properly, but I simply can't get what's in the thread out. Why?...
<p>In your first block of code, you only print the value of <code>a</code> once. However, your threads do continue to update it.</p> <p>Instead of just <code>print(a)</code> at the end of your code, try printing <code>a</code> in a loop, like this:</p> <pre><code>import threading,time a = 1 def update(): global...
python|multithreading
1
6,668
33,109,744
FiPy interior conducting boundary conditions
<p>I am a newcomer to FiPy and I am solving the Poisson's equation for the potential inside a 3D volume. It works fine for surface boundary conditions but now I need to place a conductor inside. This will be a constant potential surface and I realize that you cannot use potential.constrain for interior surfaces.</p> <...
<p>The discussion at <a href="http://www.ctcms.nist.gov/fipy/documentation/USAGE.html#applying-internal-boundary-conditions" rel="nofollow">http://www.ctcms.nist.gov/fipy/documentation/USAGE.html#applying-internal-boundary-conditions</a> describes exactly what you are trying to do. I think I know why it might not have ...
python|fipy
2
6,669
33,202,665
Compare a users input list to a set list in order with duplicates
<p>I am trying to take a set of answers either 'A' 'B' 'C' or 'D' in a specific order such as a multiple choice test and have the user input his answers. After I would like it to create a third list and print out what was right and wrong. Here is what I have so far.</p> <pre><code> userAnswersList = [] correctAnswe...
<p>There is no question here, so I'll assume you're asking what's wrong with what you have.</p> <p>The compare section uses the same variable i in both lists but even if it was different it wouldn't work.</p> <p>You'll need something along the following lines:</p> <pre><code>for i in range(len(correctAnswers)): ...
python|list|duplicates|compare
1
6,670
21,623,524
how to split a string with a " " delimiter?
<p>i have a file that i created that contains counts bad ip addresses and and puts that count in front of the ip address like this:</p> <pre><code> 2 88.208.222.32 3 162.209.53.127 6 218.2.22.103 6 218.2.22.117 357 218.2.22.114 462 222.186.62.23 484 61.160.215.176 566 60.169.74.2...
<p>Use <a href="http://docs.python.org/2/library/stdtypes#str.split"><code>str.split</code></a> without argument:</p> <pre><code>&gt;&gt;&gt; ' 6 218.2.22.103'.split() ['6', '218.2.22.103'] </code></pre> <p>According to the documentation, if no argument (or <code>None</code>) is given:</p> <blockquote> <p>run...
python|string
5
6,671
24,768,702
CSV to LIBSVM using phraug
<p>I try to convert my CSV file to LIBSVM by using phraug python scripts. (<a href="https://github.com/zygmuntz/phraug" rel="nofollow noreferrer">https://github.com/zygmuntz/phraug</a>) </p> <p>Here is my dataset, which contains a label on first position and a header: <a href="https://www.dropbox.com/s/j4wsh5pde76o8ax...
<p>You might be missing the meaning of <code>4</code> of the post <a href="https://stackoverflow.com/questions/23170152/converting-csv-file-to-libsvm-compatible-data-file-using-python">Converting CSV file to LIBSVM compatible data file using python</a></p> <p>As I saw your data, the first element seems target. Right? ...
python|csv|svm|libsvm
0
6,672
24,650,693
Interconnection between two processes
<p>I have two processes and I need to send messages between them. Here's the first file:</p> <pre><code>import socket from info import socket1_filename, socket2_filename socket1 = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) socket1.bind(socket1_filename) socket2 = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)...
<p>As Tichodroma said, you'll need to retry. Define a timeout (say, 10 seconds), and, while that time doesn't expire, catch <code>socket.error</code> and keep retrying. If it still fails after the timeout, fail loudly.</p> <p>You'll need to <code>bind</code> before you attempt to <code>connect</code> on <em>both</em> ...
python|sockets|unix-socket
1
6,673
24,495,569
Eclipse IDE: How to add this configuration during running?
<p>For running of one of my C++ programs, using terminal(Ubuntu) I use</p> <p>Note: I'm trying to Embed Python in C++. Hence, PYTHONPATH in C++. Refer to Python/C API for more details.</p> <pre><code>$ PYTHONPATH=. ./prog_name </code></pre> <p>Sorry, I didn't know how to ask this question on Google. I want to do th...
<p>Hi to all those facing the same problem, i found the solution! setenv() is a function defined in which sets the environment variable. Just have to run it!</p> <pre><code>setenv("PYTHONPATH",".",1); </code></pre> <p>for more info on setenv:</p> <pre><code>$ man setenv </code></pre> <p>All the best :)</p>
eclipse|eclipse-cdt|pythonpath
0
6,674
38,097,941
Is brute force the best option for multiple regression using Python?
<p>In the linear model = 0 + 1 × i + 2 × j + 3 × k + , what values for ,j,k ∈ [1,100] results in the model with the highest R-Squared?</p> <p>The data set consists of 100 independent variables and one dependent variable. Each variable has 50 observations.</p> <p>My only guess is to loop through all possible combina...
<p>Exhaustive search is going to be the slowest way of doing this</p> <p>The fastest way to do this is mentioned in one of the comments. You should pre-specify your model based on theory/intuition/logic and come up with a set of variables that you hypothesize will be good predictors of your outcome.</p> <p>The differ...
python|statistics|scikit-learn|regression|multiple-regression
1
6,675
38,257,496
While loop on click
<p>Designing a control graphics window and need it to repeat as long as the window is being clicked in.</p> <p>Here is the code for the object to be repeated</p> <pre><code># Limit the bounds of the buttons def moveBob(): if 80&lt;x&lt;120 and 10&lt;y&lt;50: moveForward= Bob.move(0,-20) if 80&lt;x&lt;...
<p>Moving the statements into the while loop solved it ie:</p> <pre><code>while True: point= Control.getMouse() x= point.getX() y= point.getY() moveBob() </code></pre>
python|graphics
0
6,676
30,927,742
Number format with commas and one decimal
<p>I have a number with 1 decimal point such as <code>123456.1</code> i would like to format it to <code>123,456.1</code></p> <p>Tried to use locale to format the number but was unable to get it to work</p> <p>Instead I used the following:</p> <pre><code>def format(n): r = [] for i, c in enumerate(reversed(s...
<p>Use <a href="https://docs.python.org/3.4/library/string.html" rel="nofollow">string formatting</a>.</p> <pre><code>&gt;&gt;&gt; '{:,}'.format(123456.1) '123,456.1' </code></pre>
python
0
6,677
30,900,477
Scan function from Theano replicates non_sequences shared variables
<p>I'm trying to implement a custom convolutional layer for a CNN network in Theano, and in order to do so I'm using the scan function. The idea is to apply the new convolution mask to each pixel.</p> <p>The <code>scan</code> function compiles correctly, but for some reason I get an out-of-memory error. The debug (see...
<p>It is possible that, when the scan is first created or at some point during the optimization process, a symbolic <code>Alloc</code> with that shape is created. However, it should be optimized at a later stage of the optimization process.</p> <p>We are aware that there was a but related to that recently, which shoul...
python|theano|deep-learning
2
6,678
31,043,106
How to pass int[] as argument between plpython functions
<p>I'm working with PostgreSQL and plpython functions.</p> <p>I have a function <code>func1</code>:</p> <pre><code>CREATE OR REPLACE FUNCTION func1(a integer, b timestamp with time zone, c integer[]) RETURNS SETOF x AS $BODY$ parts=plpy.execute("SELECT * FROM func2(%s)"%c) $BODY$ LANGUAGE plpythonu VOLATILE </cod...
<p>Probe this:</p> <pre><code>create or replace function func1(t text[]) returns integer as $$ p = plpy.prepare("select func2($1) v", ["text[]",]) r = plpy.execute(p, [t,]) return r[0]["v"] $$ language 'plpythonu'; create or replace function func2(t text[]) returns integer as $$ return len(t) $$ lang...
python|sql|postgresql|plpython
1
6,679
39,949,990
Kivy: how to reference widgets from python code?
<p>Basic Kivy question. Given this kv file:</p> <pre><code>BoxLayout: MainMenu: MyCanvasWidget: &lt;MainMenu&gt;: Button: on_press: root.do_action() </code></pre> <p>How do I call a method of MyCanvasWidget (for drawing something) from the do_action method when the button in MainMenu is pressed?<...
<pre><code>BoxLayout: MainMenu: do_action: mycanvas.method MyCanvasWidget: id: mycanvas &lt;MainMenu&gt;: Button: on_press: root.do_action() </code></pre> <p>Got some inspiration from <a href="https://stackoverflow.com/questions/39807997/how-to-access-some-widget-attribute-from-ano...
python|python-2.7|kivy|kivy-language
0
6,680
28,919,482
Google maps API marker refresh
<p>I'm building a web site service for a GPS localisation service using a Syrus GPS modem. I have two files, one python code to catch the info coming from the modem and another <code>HTML</code> file which is the webpage, the python script rewrites directly to the HTML using:</p> <pre><code> def replace_line(file_name...
<p>Yes. But I'm not sure how easy it's going to be because I'm not entirely sure how you're updating the map via Python in the first place. I.e. are you using websockets, re-rendering the template, etc... </p> <p>When I was stuck doing the same thing, I used web sockets (specifically, socket.io) along with my Flask ap...
python|html|google-maps|gps|refresh
2
6,681
28,927,821
How to get a picture out of raw hex data in python?
<p>I am using pydicom for extracting image data out of a dicom file. Unfortunately pydicom fails to directly extract a numpy array of data I can directly use, but I get a data string containing all values in hex (i.e. f.eks. <code>\x03\x80\x01\x0c\xa0\x00\x02P\x00\x04@\x00\t\x80\x00\x03...</code>. I know that the image...
<p>Second parameter (size) to <code>Image.fromstring</code> should be 2-tuple with height and width:</p> <pre><code> :param size: A 2-tuple, containing (width, height) in pixels. </code></pre>
python|image|numpy|pydicom
1
6,682
8,778,691
Profiled performance of len(set) vs. set.__len__() in Python 3
<p>While profiling my Python's application, I've discovered that <code>len()</code> seems to be a very expensive one when using sets. See the below code:</p> <pre><code>import cProfile def lenA(s): for i in range(1000000): len(s); def lenB(s): for i in range(1000000): s.__len__(); def main()...
<p>Obviously, <code>len</code> has some overhead, since it does a function call and translates <code>AttributeError</code> to <code>TypeError</code>. Also, <code>set.__len__</code> is such a simple operation that it's bound to be very fast in comparison to just about anything, but I still don't find anything like the 1...
python|performance|profiling|set
22
6,683
52,358,691
Query a pandas dataframe column for a text phrase that may or may not have words within that phrase
<p>Goal: To query a pandas dataframe column for a text phrase that may or may not have words within that phrase. At a high level a phrase is "word1 word2". Between word1 and word 2 there may or may not be other words. </p> <p>This sounds like a dupe, however I tried the SO answers here:</p> <p><a href="https://stacko...
<p>The second <code>'\s'</code> is in the wrong position. You need it only if the two words are not adjacent:</p> <pre><code>df[df.str.contains(r'pieces\s(?:.+?\s)?delivered')] #3 some pieces delivered on time #4 all pieces not delivered #5 most pieces were never delivered at all #6 ...
python|regex|python-3.x|pandas
1
6,684
52,276,351
Find and replace in cells from excel in python
<p>Where I have a cell in an .xlsx file that is "=..." I want to replace the "=" with '=, so can see the cells as strings rather than as the values. </p> <p>For example, </p> <pre><code>A1 = 5 A2 = 10 A3 = (A1/A2) = 0.5 </code></pre> <p>I want to see <code>=A1/A2</code> rather than 0.5. </p> <p>Thank you in advan...
<p>As suggested <a href="https://openpyxl.readthedocs.io/en/stable/" rel="nofollow noreferrer">openpyxl</a> solves this problem:</p> <pre><code>import openpyxl from openpyxl.utils.cell import get_column_letter wb = openpyxl.load_workbook('example.xlsx') wb.sheetnames sheet = wb["Sheet1"] amountOfRows = sheet.max_row ...
python|excel|python-3.x
3
6,685
51,734,628
unable to scrape the current stock price from yahoo finance website using scrapy
<p>I want to scrape the Current Stock Value of any company using <code>scrapy</code> whenever I run the <code>spider</code> from the below <a href="https://in.finance.yahoo.com/quote/ZUO/key-statistics?p=ZUO" rel="nofollow noreferrer">Yahoo Finance</a> : </p> <p>But i am unable to extract it using scrapy shell as show...
<p>If you can't find an element that is supposed to be in a page, I suggest you use <code>view(response)</code>. It shows you how the scrapy see the page. In this case, if you use it by yourself, you can see that in fetched HTML, there is no price element. I set a normal user agent in the request and it worked properl...
python|scrapy
0
6,686
18,994,302
Python Program not outputting correctly?
<p>I have recently started learning how to program in Python using the site Codecademy.com, and it uses Python 2.7, and while I have installed both 2.7.3 and 3.3.2 on my computer I am creating the program in Python 3.</p> <p>The program itself is a simple little proof of concept from the lessons on the site, a Pig Lat...
<p><code>raw_input.replace(' ', '').isalpha</code></p> <p>You didn't call the function <code>isalpha</code>, only referenced it. Add <code>()</code></p> <hr> <p><code>if first_letter == 'a' or 'e' or 'i' or 'o' or 'u':</code></p> <p>Is the same as:</p> <p><code>if (first_letter == 'a') or ('e') or ('i') or ('o') o...
python|python-3.x
2
6,687
62,238,654
How to find specific word followed by number in a dataframe using Python
<p>I have a dataframe which contains a series of patterns.</p> <p>Example dataframe:</p> <pre><code>mydata: [ 'Ticket number INS 00909', 'Ticket number INS00909', 'Ticket number REQ 8776', 'Ticket number REQ#8777', 'Ticket number REQ #8778', 'Ticket number REQ8778', 'Number is CR 0098445554', 'No INS number', 'No RE...
<p>This will give you a new df column. The indices of the mydata strings are used to take slices with only your desired info. The last if/else block checks to see if there are numbers in the string to avoid appending false positive matches. </p> <pre><code>order_list = [] for idx, row in df.iterrows(): if 'INS' ...
python|regex|pandas
2
6,688
67,257,248
How to delete last row using SQLAlchemy?
<p>I need to exec next query:</p> <pre class="lang-sql prettyprint-override"><code>DELETE FROM &lt;table_name&gt; ORDER BY &lt;column_name&gt; DESC LIMIT 1 </code></pre> <p>I trying:</p> <pre class="lang-python prettyprint-override"><code>query = session.query(MyTable) query.order_by(MyTable.my_column.desc()).limit(1)....
<p>Since you're dealing with ORM objects you can just retrieve the &quot;last&quot; item and then delete it:</p> <pre class="lang-py prettyprint-override"><code># ORM class for demo class Team(Base): __tablename__ = &quot;team&quot; id = Column(Integer, primary_key=True) name = Column(String(50)) rank =...
python|sql|sqlalchemy|orm
1
6,689
36,408,334
Why are Basemap south polar stereographic map projection coordinates not agreeing with those of data sets in the same projection?
<p>Some satellite based earth observation products provide latitude/longitude information while others provide the X/Y coordinates within a given grid projection (and there are also some having both, see example). My approach in the second case is to set up a Basemap map which has the same parameters (projection, elli...
<p>I did some experimentation and it seems like changing <code>lat_ts</code> has no effect with <code>projection='spstere'</code>. In fact, it seems as if the projection latitude is implicitly assumed to be <code>lat_ts=-90.</code> regardless of what value you assign.</p> <p>I had more success using <code>projection=...
python|matplotlib-basemap|map-projections
2
6,690
19,677,777
How to catch write aborts in python-tornado?
<p>I want to stream a long database result set through Tornado. I obviously need a server cursor since its not feasible to load the whole query in memory.</p> <p>So I have the following code:</p> <pre><code>class QueryStreamer(RequestHandler): def get(self): cursor.execute("Select * from ...") chunk ...
<p>You need to make the handler asynchronous and use <code>ioloop.add_timeout</code> instead of <code>time.sleep</code>, because that blocks the loop:</p> <pre><code>import tornado.ioloop import tornado.web import tornado.gen class PingHandler(tornado.web.RequestHandler): connection_closed = False def on_...
python|tornado
7
6,691
22,425,596
Trigger cursor positioning and selection on going to Normal mode or ESC map
<p>Anyone knows how can I trigger cursor positioning and selection from python when going to Normal?</p> <p>This is <a href="https://github.com/oblitum/YouCompleteMe/blob/clang_complete-params/python/ycm/param_completion/clang_complete.py" rel="nofollow">the script</a> and I had to comment out the <kbd>ESC</kbd> mappi...
<p>TL;DR, <code>set ttimeout=100</code> (or less) and InsertLeave auto-commands will be processed much sooner (specifically, in that many milliseconds). </p> <p><code>:imap</code>ing <code>&lt;Esc&gt;</code> will cause cursor keys and function keys to stop working in insert mode, so don't do that. With the improved ti...
python|vim|vim-plugin
2
6,692
17,039,881
Audio signal processing using Python
<p>I have been on homework about audio signal processing. I have read some paper and am confused about a formula:<img src="https://i.stack.imgur.com/WBNLP.png" alt="enter image description here">. The formula is used to process a 44100Hz, 16 bit, single channel audio. The audio has been preprocessed and is sliced into ...
<p>Assuming you've got a signal <code>x = [ x_1, x_2, ..., x_N ]</code> then you would compute the formula above in python (with scipy imported):</p> <pre><code>E = sum( abs(fft(x))[:len(x)/2]**2 ) / len(x) </code></pre> <p>About the normalization factor <code>N = len(x)</code> I'm not 100% sure — this depends on the...
python|audio|signal-processing|fft
0
6,693
54,276,516
Google API Python Client: "from six.moves import zip ImportError: No module named moves"
<p>I am trying to use the Google Sheets API in my Python 2.7 code using the googleapiclient but I get the following error: "from six.moves import zip ImportError: No module named moves ".</p> <p>I am using Python 2.7.10 on Mac.</p> <p>My programme is built using Webapp2, deployed on Google AppEngine and is connected ...
<p>The <code>six</code> module is one of the <a href="https://cloud.google.com/appengine/docs/standard/python/tools/built-in-libraries-27" rel="nofollow noreferrer">built-in third party libraries</a> in the App Engine Python 2.7 runtime. The only available version is <code>1.9.0</code>, but this version has the <code>s...
python|google-app-engine|google-sheets|google-cloud-platform|google-api
0
6,694
54,583,292
Django - call celery Task from view
<p>i want to call a celery task from my views.py but for some reason i get the following error:</p> <p>...</p> <p>tasks.py</p> <p>...</p> <p>urls.py</p> <pre><code>... </code></pre> <p>Thanks in advance</p>
<p>You are not passing the pk of the user in the url, so it is always <code>None</code> and the user with <code>pk=None</code> doesn't exists. You should add the pk to the url, like <code>url(r'^user/wallet_deposit/new_addr_btc/(?P&lt;pk&gt;\d+)$', MyProject_Accounts.wallet_deposit_gen_new_addr_btc, name='wallet_deposi...
python|django|task|celery
0
6,695
54,369,664
best practice to deploy aws lambda to another region using cloud9
<p>The problem: lambda can't use an s3 trigger hosted in London if I deploy the lambda in Ireland. Ideally I would just launch a cloud9 instance in London but this service is not yet available in London.</p> <p>Cloud9 is great for testing and developing a lambda which needs to interact with other aws services, code re...
<p>It sounds like you want to change the AWS Region that the AWS Cloud9 IDE is currently set to and then deploy your AWS Lambda function to that new Region. If so, see the following instructions, which describe how to change the Region: <a href="https://docs.aws.amazon.com/cloud9/latest/user-guide/lambda-functions.html...
python|bash|amazon-ec2|aws-lambda|aws-cloud9
0
6,696
54,353,378
Why does this Python Script run much faster on a slower computer?
<p>I have the following very simple code, that seems to run much faster on a friends computer.</p> <pre><code>count = 0 maxcount = 100000000 while(count &lt;= maxcount): count += 1 if(count == 100000000): print(count) </code></pre> <p>I would assume that my computer which is newer an...
<p>Assuming you are using the same operating system and all other factors are controlled, this is likely because your Quad-core processor speeds up to 3.6GHz boost, then reaches thermal limitations and throttles down to 2.6GHz or slower for most of the time it takes to run the program. Whereas your friend's computer is...
python|performance|architecture
4
6,697
71,356,316
Why can't I get my account info binance api
<p><em>When I use the function <code>print(client.get_account())</code> this is my code followed by the output</em></p> <pre class="lang-py prettyprint-override"><code>from binance.client import Client, import pandas as pd, import mplfinance as mpl, import numpy as np, import os, import matplotlib.pyplot as plt, #I se...
<p>This is a very common problem, and the solution is very simple. For the Binance API to work, your system time should be synced with the Binance time.</p> <p><strong>Fix: In Windows, go to your Date &amp; Time setting and click on &quot;Sync now&quot;. Voila! fixed.</strong></p>
python|binance-api-client
0
6,698
52,797,084
Unable to return serializer class in Django reset framework
<p>I am developing a Web API using the Django REST framework. I am new to Django and Python. The problem I am having now is that I cannot return the serializer class.</p> <p>This is my project structure</p> <p><a href="https://i.stack.imgur.com/YRF8p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/...
<p>This doesn't have anything to do with "returning a serializer class".</p> <p>The problem is in your urls.py; this isn't at all how you use a ViewSet there. You need to use it with a Router: see <a href="https://www.django-rest-framework.org/api-guide/viewsets/" rel="nofollow noreferrer">the documentation</a>, which...
python|django|django-rest-framework
0
6,699
52,563,510
How to find a specific string in a python list, if found print the positions else print 0
<pre><code>input_String = str(input()) # Input is comma separated word cargo_status = str(input()) # String to look into input string list = input_String.split(",") i = 0 length = len(list) print(length) for x in list: if x == cargo_status: i=i+1 print(i) elif (not cargo_status in x) and (i==le...
<p>You should move <code>i = i + 1</code> outside of the condition.</p> <p>Maybe you wanted to write <code>not cargo_status in list</code>.</p> <p>Anyway it's not efficient. Here is an option:</p> <pre><code>statuses = str(input()).split(',') query = str(input()) positions = [i for i, status in enumerate(statuses) ...
python|string|python-3.x
1