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
2,900
18,130,551
Call a python script in a python script
<p>I am trying to call a python script in another python script. The directories are different. I tried </p> <pre><code>import subprocess subprocess.call("C:\temp\hello2.py", shell=True) </code></pre> <p>But got nothing. It does not work. I reviewed many forums, but all of them are about calling it when both scripts ...
<p>Escape backslash (<code>\</code>)</p> <pre><code>"C:\\temp\\hello2.py" </code></pre> <p>or use raw string</p> <pre><code>r"C:\temp\hello2.py" </code></pre> <hr> <pre><code>&gt;&gt;&gt; print "C:\temp\hello2.py" C: emp\hello2.py &gt;&gt;&gt; print "C:\\temp\\hello2.py" C:\temp\hello2.py &gt;&gt;&gt; print r...
python|call|subprocess
6
2,901
18,215,828
Why can't I use yield with return?
<p>I would like you to consider the following code:</p> <pre><code>def func(alist): if len(alist) == 1: return arg * 2 for item in alist: yield item * 2 </code></pre> <p>When I run it, I get this error:</p> <pre><code>SyntaxError: 'return' with argument inside generator </code></pre> <p>Now,...
<p>Python has to decide whether a function is a generator at bytecode compilation time. This is because the semantics of generators say that none of the code in a generator function runs before the first <code>next</code> call; the generator function returns a generator iterator that, when <code>next</code> is called, ...
python|function|return|python-2.x|yield
8
2,902
63,113,416
Python: Is it possible to override/extend an instance method of one class when it is used in another class?
<p>I'm planning out a Python project. I'm going to have classes that use instances of other classes. Is it possible to override/extend a method from within another class, like this:</p> <pre><code>class Foo: a = Bar() b = Bar() c = Bar() class Baz: x = Bar() y = Bar() z = Bar() class Qux: ...
<p>Not in a clean way. In overall this seems like a bad idea. How will you know when <code>do_something</code> behaves how? It's gonna be a debugging nightmare.</p> <p>If <code>do_something</code> needs to do something different, subclass <code>Bar</code> and implement it differently in each subclass.</p> <pre><code>cl...
python|class|methods|overriding|instance
1
2,903
62,999,917
Elements that are in page_source cannot be found when trying to scrape it using BeautifulSoup or Xpath
<p>I'm trying to crawl Booking.com site for reviews and hotel details. I managed to get the hotels details but when it comes to crawling reviews something weird happens !</p> <p>I find the container that covers the reviews, but empty...</p> <p>I made sure the elements I'm looking for are present by inspecting the page ...
<p>The problem is quite simple.</p> <p>The reviews tab is hidden and appears only when the page is load (I'm not good in web and I don't know how they call this technology).</p> <p>So, when you have the option <code>--headless</code> which runs the browser in hidden mode (without loading the UI elements), that hidden t...
python|selenium|xpath|beautifulsoup|scrapy
0
2,904
59,017,908
Selecting rows before and after rows based on value of other group--pandas
<pre><code>import pandas as pd import numpy as np raw_data = {'Country':['UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK'], 'Product':['A','A','A','A','B','B','B','B','B','B','B','B'], 'Week': [1,2,3,4,1,2,3,4,5,6,7,8], 'val': [5,4,3,1,5,6,7,8,9,10,11,12] } have = pd.DataFrame(r...
<p>IIUC:</p> <pre><code>df = pd.DataFrame(raw_data, columns=['Country', 'Product', 'Week', 'val']) max_week = df.loc[df["Product"].eq("A"),"Week"].max() print (df[df["Product"].eq("A")|((df["Week"]&gt;=max_week-1)&amp;(df["Week"]&lt;=max_week+2))]) # Country Product Week val 0 UK A 1 5 1 ...
python|pandas
1
2,905
31,480,866
python returning to the default statement
<p>hey im doing the learn python the hard way thing and im stuck at exercise 39½. i have following code i have been going through this a lot of time trying to find my error/errors first i have a module which i later import to my main project looks like this</p> <pre><code>def new(num_buckets=256): """INITIALIZES A...
<p>With out testing, just looking at the code: </p> <pre><code>if key == kv: </code></pre> <p>should be (around line 25)</p> <pre><code>if key == k: </code></pre> <p>Basically kv doesn't exist so it always tests false and doesn't run the code under the if statement. </p>
python|list|dictionary|default
0
2,906
31,537,345
Ctreate two or more panel indicator using python gtk3 appindicator
<p>I want to create two or more panel indicator using a single indicator class. This is the code:</p> <pre><code>#!/usr/bin/env python import os from gi.repository import Gtk from gi.repository import AppIndicator3 class IndicatorObject: def create_indicator(self, indicator_id): indicator = AppIndicat...
<pre><code>#!/usr/bin/env python import os from gi.repository import Gtk from gi.repository import AppIndicator3 class AppIndicatorExample: def __init__(self, indicator_id): self.ind = AppIndicator3.Indicator.new(str(indicator_id), os.path.abspath('sample_icon.svg'), AppIndicator3.IndicatorCategory.SYSTEM_...
python|gtk3|appindicator
2
2,907
31,258,561
get script directory name - Python
<p>I know I can use this to get the full file path</p> <pre><code>os.path.dirname(os.path.realpath(__file__)) </code></pre> <p>But I want just the name of the folder, my scrip is in. SO if I have my_script.py and it is located at</p> <pre><code>/home/user/test/my_script.py </code></pre> <p>I want to return "test" H...
<pre><code>import os os.path.basename(os.path.dirname(os.path.realpath(__file__))) </code></pre> <p>Broken down:</p> <pre><code>currentFile = __file__ # May be 'my_script', or './my_script' or # '/home/user/test/my_script.py' depending on exactly how # the script was r...
python|file|python-os|getcwd
55
2,908
15,627,908
Python: I am trying to rename (chop off) the last 15 characters from filenames in a single directory
<p>Python: I am trying to rename (chop off) the last 15 characters from all files in a single folder without chopping up 'mychoppingfile.py'. Also, the program must only run one time for each file (i guess this would be handled by moving the output files to a new directory after processing?). This is what I have:</p>...
<p>One way is using a dictionary:</p> <pre><code>import os files = os.listdir('.') seen = dict() for filename in files: if len(filename) &gt; 15 and filename != 'mychoppingfile.py': tofile = filename[:-15] if tofile not in seen: print filename + " -&gt; " + filename[:-15] seen[tofile] = 1 </code...
python
1
2,909
59,538,815
How can I create index for python pandas dataframe?
<p>I am importing several csv files into python using Jupyter notebook and pandas and some are created without a proper index column. Instead, the first column, which is data that I need to manipulate is used. How can I create a regular index column as first column? This seems like a trivial matter, but I can't find an...
<p>Could you please try this:</p> <pre class="lang-py prettyprint-override"><code>df.reset_index(inplace = True, drop = True) </code></pre> <p>Let me know if this works.</p>
python|pandas|indexing
3
2,910
70,793,013
How can I mock django model object?
<p>For example, I have a lot of interrelated tables in my project</p> <pre><code>class A(models.Model): name = models.models.CharField(max_length=16) class B(models.Model): name = models.models.CharField(max_length=16) a = models.ForeignKey(A, on_delete=models.CASCADE) class C(models.Model): name = mo...
<p>After couple of days of research I don't have an answer to my question, but I think I found a tool that takes care of 'preparing the base' before actual testing or greatly simplifies it.</p> <p>I have about 1000 lines of test code in my project and I decided to switch to pytest and rewrite tests almost from scratch,...
python|django|unit-testing|django-rest-framework
0
2,911
70,802,103
Getting an error in while appending an unpacked list in Python
<p>I was trying to construct a function that returns all the ways the target string can be formed using the list of strings</p> <p>For example, for allConstruct('aa', ['a','aa','aaa']), I get [['a', 'a'], ['aa']] as output. But when I pass allConstruct('aaa', ['a','aa','aaa']), I get the following error:</p> <p>&quot;...
<p>Try <code>result.extend(targetWays)</code>. This adds all elements in list to the result.</p> <p>Or if you want to add the list itself just remove <code>*</code> just like this: <code>result.append(targetWays)</code>.</p>
python|dynamic-programming
1
2,912
5,622,885
Django settings outside of project
<p>I have a Django project that uses SQLAlchemy to use some legacy ORM objects. This application also hits up an ldap server for user authentication. I was getting sick of moving from development to production servers for both ldap and the database. I was hoping to create a IS_DEVELOPMENT variable in the settings.py. O...
<p><a href="http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/" rel="nofollow">"Standalone Django Scripts"</a></p>
python|django
3
2,913
30,711,036
filter with prefetch_related
<p>I want to know how I can filter my def to see only questions for the filtered patient. </p> <p>I have try this:</p> <pre><code>def detail3(request, patient_id): patient = get_object_or_404(Patient, pk=patient_id) questions = Question.objects.filter(patient=patient_id).prefetch_related('reply_set').all().or...
<p>You're trying to filter by a field in the <code>Question</code> model that does not exist:</p> <pre><code>Question.objects.filter(patient=patient_id) </code></pre> <p>patient is not a <code>Question</code> field and this is why you're getting this error.</p> <p>In your <code>Reply</code> model, add a <code>relate...
python|django|filter|prefetch
1
2,914
30,408,589
How do you use python-daemon the way that it's documentation dictates?
<p>I'm trying to make a daemon in python and I've come across the python-daemon package. The interesting thing about it is that the most common way I've seen it used isn't even what the <a href="https://www.python.org/dev/peps/pep-3143/" rel="nofollow noreferrer">documentation</a>, which is very sparse, tells you to do...
<p>First, the reason you can't find good documentation is that, to the best of my knowledge, nobody ever wrote it. When Ben Finney proposed the PEP, there was plenty of interest, but then when he asked for someone else to take over the project and champion it, nobody did, so… beyond the PEP, and the sparse documentatio...
python|daemon|python-daemon
12
2,915
30,662,570
Clockwise Shifting a Matrix
<p>The input is a N x N matrix which has to be shifted cyclically (either Clockwise or Counter-Clockwise) by one element.</p> <p><strong>Example Input (Size 3) :</strong> </p> <pre><code>1 2 3 4 5 6 7 8 9 </code></pre> <p><strong>Output :</strong></p> <pre><code>2 3 6 1 5 9 4 7 8 </code></pre> <p><strong>Example I...
<p><strong>For rotation, read elements in the order :</strong><br> i -> 0 to n-1 and j = 0<br> j -> 0 to n-1 and i = n-1<br> i -> n-1 to 0 and j = n-1<br> j -> n-1 to 0 and i = 0<br></p> <pre><code>import collections def shiftMatrix(matrix, layers, num,rotate_direction): for count in range(layers): temp1 =...
python|algorithm|matrix
0
2,916
66,785,522
Pandas filter by date range within each group
<p>I have a df like:</p> <p><a href="https://i.stack.imgur.com/fxGkM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fxGkM.png" alt="enter image description here" /></a></p> <p>and I have to filter my df by having values within two weeks from each ID so for each ID, I have to look ahead next two week...
<h3>Setup</h3> <pre><code>df = pd.DataFrame({ 'Id': np.repeat([2, 3, 4], [4, 3, 4]), 'Date': ['12/31/2019', '1/1/2020', '1/5/2020', '1/20/2020', '1/5/2020', '1/10/2020', '1/30/2020', '2/2/2020', '2/4/2020', '2/10/2020', '2/25/2020'], 'Value': [*'abcbdeefffg'] }) </code></pre> <hr /...
python|pandas
3
2,917
42,822,051
How to pull a certain branch from a upstream repository
<p>Assume I have a local git clone called GitPython. I'm able to commit and push using gitpython:</p> <pre><code>repo = Repo(D:\Dev\Gitpython) print(repo.git.add(".")) print(repo.git.commit(m='my commit message')) print(repo.git.push()) </code></pre> <p>However, how can I pull from the upstream repository using gitpy...
<p>Since the connection already exist your should be able to pull. </p> <pre><code>repo = git.Repo('repo_name') o = repo.remotes.origin o.pull() o = repo.remotes.origin o.fetch('branch_name') </code></pre>
github|gitpython
0
2,918
72,171,864
how to retrive a value from request and do processing and post it to another link flask
<p>I am new to using flask, what I need to know is to listen to a request and do some processing on one field of this request and return some extra value and post it along with this field to another link, what I can think of rn is something like this to retrieve the age should I do something like this? :</p> <pre><code...
<p>Be careful because there are some errors in your piece of code that make it impossible for the application to run.</p> <p>It is not very clear to me what you have to do, once you have obtained the age from the json, you perform a series of calculations and then you can do with it what you want, in this case I will p...
python|flask
0
2,919
72,365,928
pip install python-qpid-proton: how to fix errors on windows?
<p>While running pip install python-qpid-proton I got the following errors:</p> <ol> <li><p><em>error: Microsoft Visual C++ 14.0 or greater is required.</em><br /> I fixed this by installing Visual Studio Build Tools 2022 and Visual Studio Professional 2022</p> </li> <li><p><em>fatal error C1083: Cannot open compiler g...
<p>I fixed the last error by using Python 3.9 instead of Python 3.10. Apparently python-qpid-proton 0.37.0 is only compatible with Python 3.9.</p>
python|pip|amqp|qpid|qpid-proton
1
2,920
50,511,457
python mss mss.exception.ScreenShotError:
<p>I'm newbie. I try use mss to screenshot monitor. My code:</p> <pre><code>for i in range(1, 20000): cactus_box = {'left': 508, 'top': 382, 'width': 30, 'height': 33} sct = mss() sct_img = sct.grab(cactus_box) </code></pre> <p>when i run code, this display error:</p> <pre><code> File "C:\Users\xxxx\AppData\L...
<p>EDIT: this is due to resources not freed. It is fixed in MSS 4.0.0 or newer.</p> <p>Could you try to use MSS ouside the <code>for</code> loop? Something like:</p> <pre><code>with mss() as sct: cactus_box = {'left': 508, 'top': 382, 'width': 30, 'height': 33} for i in range(1, 20000): sct_img = sct....
python|python-3.x|python-mss
0
2,921
50,471,942
Python __doc__ documentation on instances
<p>I'd like to provide documentation (within my program) on certain dynamically created objects, but still fall back to using their class documentation. Setting <code>__doc__</code> seems a suitable way to do so. However, I can't find many details in the Python help in this regard, are there any technical problems with...
<p><code>__doc__</code> is documented as a writable attribute for <em>functions</em>, but not for instances of user defined classes. <a href="https://docs.python.org/3/library/pydoc.html" rel="nofollow noreferrer"><code>pydoc.help(a)</code></a>, for example, will only consider the <code>__doc__</code> defined on the t...
python|python-3.x
5
2,922
50,518,913
Value error storing user input Integer into an array in Python
<p>I'm creating an application for my programming class and I'm unable to get it to run properly. Essentially, the application should take 8 numbers from the user and store them in an array and then add those numbers. However, if the user does not provide a number, or press Q, the program should stop.</p> <pre><code>u...
<p>Try this: Do not convert to int before checking to q.</p> <pre><code>userNumberList = [] counter = 0 while counter &lt; 8: userNumber = input("Welcome! Please provide numbers or press q to quit. ") if userNumber == 'q': print("Entered command to quit!! closing the application") break els...
python|python-3.x
2
2,923
34,948,413
Server information in a Flask app
<h3>Intend</h3> <p>I want to be able to tell which server is running my Flask app.(Either Werkzeug or Gunicorn) And additionally if it is being proxied by NGINX or Apache.</p> <h3>Problem</h3> <p>I think I can get the response with JavaScript and get the server header, but In the case of it being proxy by NGINX or Apac...
<p>Some servers will add <code>SERVER_SOFTWARE</code> into the os environment. Gunicorn will do this.</p> <pre class="lang-python prettyprint-override"><code>@app.route('/server') def server(): return os.environ.get('SERVER_SOFTWARE') </code></pre> <p>Result:</p> <p><a href="https://i.stack.imgur.com/Zvd33.png" ...
python|flask
3
2,924
35,067,902
In list how to count string in a sequence
<p>I have a list with duplicate elements. I want to count the occurrence of each element</p> <p>example-> <code>list1= ["a", "b", "b", "c", "d", "d", "d", "a", "a"]</code></p> <p>output-> <code>result = ["a1", "b2", "c1", "d3", "a2"]</code></p> <p>i.e. output format should be <code>&lt;value&gt;&lt;count&gt;</co...
<p>You could use <code>itertools.groupby</code>:</p> <pre><code>from itertools import groupby list1= ["a", "b", "b", "c", "d", "d", "d", "a", "a"] answer = [group[0] + str(len(list(group[1]))) for group in groupby(list1)] print(answer) </code></pre> <p><strong>Output</strong></p> <pre><code>['a1', 'b2', 'c1', 'd3'...
python|python-2.7|python-3.x
4
2,925
26,812,278
Reading 2d arrays into a 3d array in python
<p>I searched stackoverflow but could not find an answer to this specific question. Sorry if it is a naive question, I am a newbie to python. </p> <p>I have several 2d arrays (or lists) that I would like to read into a 3d array (list) in python. In Matlab, I can simply do</p> <pre><code> for i=1:N # read 2d array...
<p>If you're familiar with MATLAB, translating that into using <a href="http://www.scipy.org/index.html" rel="nofollow">NumPy</a> is fairly straightforward.</p> <p>Lets say you have a couple arrays</p> <pre><code>a = np.eye(3) b = np.arange(9).reshape((3, 3)) print(a) # [[ 1. 0. 0.] # [ 0. 1. 0.] # [ 0. 0. 1...
python|arrays|matlab
1
2,926
26,866,639
Remove substring from a string in python
<p>I have got a file in python with filenames. I want to delete some lines and some substirng of the filename using python code. My file format is the above:</p> <pre><code>img/1.jpg img/10.jpg img/100.jpg 0 143 84 227 ... </code></pre> <p>I want to delete the img/substring from all the file and the lines where the c...
<p>You're attempting to modify the list <code>content</code> while iterating over it. This will very quickly bite you in the knees.</p> <p>Instead, in python you generate a new list:</p> <pre><code>&gt;&gt;&gt; content = [fn for fn in content if not fn.endswith(".jpg\n")] &gt;&gt;&gt; </code></pre> <p>After this yo...
python|string
2
2,927
45,133,245
Write formula to Excel with Python error
<p>I try to follow this <a href="https://stackoverflow.com/questions/39195957/write-formula-to-excel-with-python">question</a> to add some formula in my excel using python and openpyxl package.</p> <p>That link is what i need for my task.</p> <p>but in this code :</p> <pre><code>for i, cellObj in enumerate(Sheet.col...
<p><code>ws.columns</code> and <code>ws.rows</code> are properties that return generators. But openpyxl also supports <a href="http://openpyxl.readthedocs.io/en/latest/tutorial.html#accessing-many-cells" rel="nofollow noreferrer">slicing and indexing for rows and columns</a></p> <p>So, <code>ws['C']</code> will give a...
python|excel|openpyxl
4
2,928
64,736,893
regex or does not work - I do not know what is wrong in my pattern
<p>I have the following strings:</p> <pre><code>2020-10-2125Chavez and Sons 2020-05-02Bean Inc NaNRobinson, Mcmahon and Atkins 2020-04-25Hill-Fisher 2020-04-02Nothing and Sons 52457Carpenter and Sons 0Carpenter and Sons Carpenter and Sons NoneEconomy and Sons 2020-04-02 </code></pre> <p>I want to have it separated:</p>...
<p>You can combine the expressions you want to match with a simple <code>|</code> but remember that the engine will always prefer the first possible match; so you want to put the more specific patterns first, and then fall back to the more generic cases.</p> <p>Try this:</p> <pre><code>my_re = re.compile(r'^([0-9]{4}-[...
python|regex
2
2,929
60,686,210
Printing list of DictReader twice in a row produces different results
<p>I'm using the <code>csv</code> module to use <code>csv.DictReader</code> to read in a csv file. I am a newbie to Python and the following behavior has me stumped.</p> <p>EDIT: See original question afterwards.</p> <pre><code>csv = csv.DictReader(csvFile) print(list(csv)) # prints what I would expect, a sequence of...
<p><code>csv.DictReader</code> is an <strike>generator</strike> iterator, it can only be consumed once. Here is a fix:</p> <pre><code>def removeFooColumn(csv): for row in csv: del row['Foo'] csv = list(csv.DictReader(csvFile)) print(csv) # prints what I would expect, a sequence of OrderedDict's removeFooColumn(...
python|csv
1
2,930
18,709,572
Using GPIO buttons to control Raspbmc
<p>I am trying to write code for a car xbmc project. I made my own button keypad with pull-down resistors and plugged into the GPIO ports. Installed python and the GPIO addon. My goal is to catch button presses, and if the button is held for 1.5 secs, it will execute a different command to xbmc (for example, the rig...
<p>I thought I was just hitting that command and popping the error, but I was iterating the loop first. This makes sense since the event catcher cant be turned on more than once. I simply edited my code to initialize it and add a new event detect only when the button is pressed. I also cleaned up the code I found on...
json|python-2.7|raspberry-pi|gpio|xbmc
1
2,931
18,722,119
wxpython: how to show and hide one shape with button
<p>Hello I am trying to create an on off button and two circles,the one circle is white and the other one red,the circles represent one LED,when I press on I want to see the red circle and wenn I press again see the white. I have write this code but I dont wont to work it with two panels and call the on switch panels f...
<p>Here is one way using a single panel that alters the same button and same circle.</p> <pre><code>import wx class PanelOne(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent=parent) self.state = [('White', 'Turn ON'), ('Red', 'Turn OFF')] self.button = wx.Button(self...
wxpython
1
2,932
55,449,748
Replace cell in DF where cell of DF is index of row desired in other DF
<p>In df1, each cell value is the index of the row I want from df2.</p> <p>I would like to grab the information for the row in df2 trial_ms column and then rename the column in df1 based on the df2 column that was grabbed. </p> <p><strong>Reproducible DF's:</strong></p> <pre><code># df1 nan = np.NaN df1 = {'n1': {0...
<p>I believe you need dictionary from <code>trial_ms</code> column - keys are index of <code>df1</code> and replace values with <code>get</code>, if not matched values is get mising value <code>NaN</code>:</p> <pre><code>d = df2['trial_ms'].to_dict() df3 = df1.applymap(lambda x: d.get(x, np.nan)).add_suffix('_trial_ms...
python|pandas
1
2,933
55,442,528
IE11 XMLHttpRequest do not receive full data from server
<p>I am currently working on a web application and I came across with a strange problem. The request that I send to my flask app from Google Chrome and Firefox with XMLHttpRequest works as intended but in IE11 and possibly older versions it looks like IE closes the connection before the data is fully transferred. I sen...
<p>I ended up changing server side code and client side code a little and made the server to send json data as string and parsing it on the client side.</p> <pre><code>function getData() { var req = new XMLHttpRequest(); req.open("POST", "http://"+window.host+"/text", true); req.addEventListener("readystat...
javascript|python|flask|xmlhttprequest
0
2,934
57,427,933
How Can I import robot file from different locations
<p>I have a path of a project like this.</p> <pre><code>Main project '-Service '-Main service '- A.robot '- B.robot '-resource.robot </code></pre> <p>When I run B.robot I would like to call resource.robot in setting file in my code</p> <pre><code>*** Settings *** Documentation Test building Resource...
<pre><code>Resource resource.robot </code></pre> <p>Would work if resource.robot was at same (directory) level as B.robot...</p> <pre><code>Main project '-Service '-Main service '- A.robot '- B.robot '-resource.robot </code></pre> <p>You could give it the full path.</p> <p>You could just...
python|robotframework
2
2,935
42,544,918
Overwrite columns in DataFrames of different sizes pandas
<p>I have following two Data Frames:</p> <pre><code>df1 = pd.DataFrame({'ids':[1,2,3,4,5],'cost':[0,0,1,1,0]}) df2 = pd.DataFrame({'ids':[1,5],'cost':[1,4]}) </code></pre> <p>And I want to update the values of df1 with the ones on df2 whenever there is a match in the ids. The desired dataframe is this one:</p> <pre>...
<p>You could do this with a left merge:</p> <pre><code>merged = pd.merge(df1, df2, on='ids', how='left') merged['cost'] = merged.cost_x.where(merged.cost_y.isnull(), merged['cost_y']) result = merged[['ids','cost']] </code></pre> <p>However you can avoid the need for the merge (and get better performance) if you set ...
python|pandas|dataframe
4
2,936
59,366,130
File generated by Pyinstaller does not work
<p>When I use this command on my python code file in windows 10 bash shell:</p> <pre><code> pyinstaller Test.py </code></pre> <p>It produces these files (and some others):</p> <p><a href="https://i.stack.imgur.com/fUY8y.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fUY8y.jpg" alt="enter image de...
<p>As I see your screenshot you have tried to run the <code>pyinstaller</code> on <code>Linux</code> OS because the generated <code>*.so</code> files are <code>Linux</code> specified shared objects. Furthermore the <code>Test</code> file is a <code>Linux</code> specified executable without extension.</p> <p>If you wan...
python|exe
2
2,937
53,865,298
Is there a function to find the difference between datetimes?
<p>I have multiple dataframes which can have the same timestamps ( also +-1second) that have milliseconds in them. So when they are all together in the new dataframe i want to filter out the rows where they are more than 1 second different from each other</p> <p>Is there a function similar to <code>dftogether['unique'...
<p>I joined your df1 and df2 to a df, and created a dates list like this:</p> <pre><code>df = pd.concat([df1,df2]).sort_values('DateTime').reset_index(drop=True) date_list = [datetime.strptime(i, '%Y-%m-%d %H:%M:%S.%f') for i in df.DateTime.tolist()] </code></pre> <p>then I get the desired output with a 1 liner:</p>...
python|pandas
2
2,938
58,512,827
How do we check if mock request is actually the correct one?
<p>Since we return mock objects from the requests made by the code, this means that no matter the input to the code under test, as long as the response from the request is handled correctly, the test would always pass. However we don't know if the code made the right request(s) to my site in the first place. For exampl...
<p>You can check the request parameters by using assertions on the mock.</p> <pre><code># setting up the canned response on the mock mock_get.return_value = mockResp() # actually calls the real code under test, i.e. calls makeRequest mock_get_response = makeRequest() # make an assertion about what the code *within*...
python|mocking|python-requests
1
2,939
58,278,491
How to only get file names matching a pattern
<p>I have this below function which looks for the files in the directory. </p> <pre><code>files = list(filter(lambda f: fnmatch.fnmatch(f, FILENAME +"*"), os.listdir(SRC_DIR) </code></pre> <p>Here is the example of how it looks</p> <pre><code>['data.txt',data.done,data_audit.done, data1.trans] </code></pre> <p>I wa...
<p>You can use a list comprehension with a filter on a pair of conditions for what I would consider to be the simplest solution.</p> <pre><code>files = [f for f in os.listdir(SRC_DIR) if f.startswith('data') and not f.endswith('.done')] </code></pre>
python|python-2.7
4
2,940
14,747,210
How to stop infinite loop?
<p>Problem: Compute two integers based upon the user input that in the first is doubled repeatedly while second is divided by two. At each step, if second number is odd add current value of first number to itself until second number is zero.</p> <p>My code doesn't seem to run completely, and I get an infinite loop wha...
<p>Problems:</p> <ul> <li><p>You don't need to write <code>done = False; while not done:</code>. Just loop infinitely (<code>while True</code>) and then use <code>break</code> to exit the loop when you're finished.</p></li> <li><p><code>input</code> <em>executes</em> the code that the user types (think of it like what...
python
2
2,941
41,345,241
Accessing a network path with known drive path
<p>I'm trying to access a network path using the following:</p> <pre><code>open(r"\\path\to\network") </code></pre> <p>However I am getting the following error:</p> <pre><code>Traceback (most recent call last): File "install.py", line 9, in &lt;module&gt; connect_to_network_path("\\path\to\network") File "in...
<p>You're trying to <code>open()</code> a directory. Use <code>os.listdir()</code> to list the directory contents.</p>
python|python-2.7|file-permissions
1
2,942
6,709,133
python: can I use a string formatting operator with a class's getter methods?
<p>I want to do something like this:</p> <pre><code>class Foo(object): def __init__(self, name): self._name = name self._count = 0 def getName(self): return self._name name = property(getName) def getCount(self): c = self._count self._count += 1 return c ...
<p>Just change it to not use <code>self.__dict__</code>. You have to access <code>name</code> and <code>count</code> as properties instead of trying to access them by the names that their properties are bound to:</p> <pre><code>class Foo(object): def __init__(self, name): self._name = name self._c...
python|class|dictionary|format|properties
2
2,943
6,365,128
Is there a way to construct lazy sequences in Python?
<p>There is a Django view that loads <code>Member</code> objects from the database with a certain filter.</p> <p>Now I need to change this logic to <strong>present a specific <code>Member</code> first, and let the rest follow in their natural order</strong>.</p> <p>The most straightforward way is to execute the query...
<p>Use <code>itertools.chain</code>. Something like:</p> <pre><code>import itertools original_members = .... # get an iterator of the data members = itertools.chain([specific_member], original_members) </code></pre> <p>The chain function returns an iterator. The iterator starts by returning the value from the sequenc...
python|django|django-queryset|lazy-sequences|generator-expression
6
2,944
6,848,548
Anagram Code in Python - Compare dynamically generated strings to a txt file
<p>I have written an Anagram solving program in Python. I wanted your opinion on whether I had gone about it right. Let me explain the logic: </p> <ol> <li>First, the user provides input of two words that he/she wants the single word anagram to be generated for (2 string values) </li> <li>The two are concatenated and ...
<p>Why are you doing <code>mystr =''.join(a)</code>? why not just do <code>mystr = a</code>?</p> <p>I don't think that <code>if mystr in line:</code> is right either, because you could have mystr as, for instance 'dog', and line as 'dogger bank', or something like that. You should probably check for equality instead.<...
python|io|anagram
1
2,945
6,884,991
How to delete a directory created with tempfile.mkdtemp?
<p>I have a python program that creates temporary directories under <code>/temp</code> by using <code>tempfile.mkdtemp</code>. Unfortunately, the Python program did not delete the directory after using it. So now the disk space is low.</p> <p>Questions:</p> <ol> <li>How do I delete the temporary directories left unde...
<p>To manage resources (like files) in Python, best practice is to use the <code><a href="http://docs.python.org/2/reference/compound_stmts.html#with" rel="noreferrer">with</a></code> keyword, which automatically releases the resources (i.e., cleans up, like closing files); this is available from Python 2.5.</p> <p>Fr...
python|linux
88
2,946
57,200,192
How to capitalize if an alphanumeric is in a word/sentence
<p>I am not able to use .title() for a alphanumeric word/sentence. It throws any syntax error</p> <pre><code>def LetterCapitalize(str): x=str.title() return x print LetterCapitalize(raw_input()) def LetterCapitalize(str): x=str.title() return x print LetterCapitalize(raw_input()) def LetterCapi...
<p>The syntax in the function call is incorrect</p> <pre><code>print LetterCapitalize(m3k mml) </code></pre> <p>Those are 2 variables m3k and mml, to print them you can either:</p> <pre><code>print LetterCapitalize(m3k + mml) </code></pre> <p>to print both variables concatenated or:</p> <pre><code>print LetterCapi...
python
0
2,947
57,150,135
AttributeError: 'str' object has no attribute 'set'
<p>This is a simple Tic-Tac-Toe game. When the game is completed, the function <code>gameover()</code> is called and a label (congratulatory message i.e playername wins!) has to be displayed on another window. I am trying to achieve this by using a format operator, set() and get() functions. </p> <p>Error:</p> <block...
<p>If what you are trying to do, is just have the player names be outputted. You can just change this code:</p> <pre><code>playerX = StringVar() playerY = StringVar() winplayX = StringVar() winplayY = StringVar() winplayX= playerX.get() winplayY= playerY.get() playerX=winplayX.set() playerY=winplayY.set() </code></p...
python
0
2,948
56,990,538
Double counting loop (n*n code performance)
<p>In Python, I have a table like this, in the form of a list of lists</p> <pre><code>A: 8 B: 6 C: 8 D: 3 E: 4 F: 5 G: 7 </code></pre> <p>I am trying to get, for each line, the number of "neighbours" e.g. the number of lines for which the number is either the same number, -1 or +1. Here it would be:</p> <pre><code>A...
<p>So the number of neighbors that a line with "8" has is the sum of:</p> <ul> <li>Number of 7's</li> <li>Number of 8's</li> <li>Number of 9's</li> </ul> <p>The simple solution is:</p> <p>Create a dictionary that's indexed by count, with the value being the number of lines with that count.</p> <p>Go through your ta...
python|python-3.x|algorithm|performance
3
2,949
44,421,870
Is_Integer returning incorrect result - Python 2.X
<pre><code>dig = 16807 digcount = len(str(dig)) minroot = dig ** (1 / float(digcount)) print minroot print minroot.is_integer() </code></pre> <p><code>minroot</code> returns as 7.0 as a float, but <code>is_integer</code> returns <code>FALSE</code>.</p> <p>I tried <code>(7.0).is_integer()</code>, and it returns <code...
<p>If you want more exact decimal arithmetic, use the decimal module. Decimals do not have an <code>is_integer method</code>, but you can compare to the int value.</p> <pre><code>&gt;&gt;&gt; from decimal import Decimal as D &gt;&gt;&gt; 7**5 16807 &gt;&gt;&gt; from decimal import Decimal as D &gt;&gt;&gt; n = D(16807...
python|python-2.7|python-2.x
1
2,950
23,683,819
How to reference Tkinter widgets inside classes in python
<p>I've created a couple of listbox widgets where selecting some items in one and then pressing a button below moves the items to the other. </p> <p>This worked absolutely fine - but I wanted to reuse the container frame because the layouts of the 2 frames was identical (apart from the heading label, and the functions...
<blockquote> <p>What would be the best way to reference widgets inside instances of other classes?</p> </blockquote> <p>I think the most common-use case for this is reusing an object an indefinite number of times, as it looks like you're trying to do with some listboxes that are set up inside a frame. In this case...
python|tkinter|widget
3
2,951
23,501,955
How to get the last key pressed in python?
<p>First I want to say that I know that there is a solution with curses.<br> My programm is a while loop that is run every second. Every second I want to get the last key that was or is pressed. So in case you press a key while the loop sleeps I want that the key is saved so I can get the key that was pressed last even...
<p>You can install and use the <a href="https://pypi.python.org/pypi/getch" rel="nofollow"><code>getch</code></a> package.</p> <pre><code>import getch from time import sleep while True: char = getch.getch() if char == 111: print("test") break sleep(1) </code></pre> <p>(you might need to us...
python|keyevent
2
2,952
35,960,275
Add a char to the beginning and end of each line in a file
<p>I have a text file that each line contains exactly one word. I want update the file by attaching a char to the beginning and end of each word in each line. Here is my code in Python:</p> <pre><code>appendText='_' names=open("name.txt",'r') updatedNames=open("name2.txt",'a') for name in names: updatedNames.write(a...
<p>You can use <a href="https://docs.python.org/3.5/library/stdtypes.html?highlight=rstrip#str.rstrip" rel="nofollow"><code>str.rstrip()</code></a> to get rid of that <code>\n</code>:</p> <pre><code>appendText = '_' with open("name.txt", 'r') as names: with open("name2.txt", 'a') as updatedNames: for name ...
python|readfile|writefile
2
2,953
15,414,165
django command "django-admin.py startproject mysite"
<pre><code> D:\python\Project&gt;c:\Python30\Scripts\django-admin.py startproject mysite Traceback (most recent call last): File "C:\Python30\Scripts\django-admin.py", line 2, in &lt;module&gt; from django.core import management File "c:\python30\Lib\site-packages\django\core\management\__init__.py", line 9, in &lt;mod...
<p>You use Python 3.x version. This Python version have experimental support in latest django release 1.5, but in any case, this is not so useful.</p> <p>You need to use Python 2.7 for now.</p>
python
0
2,954
15,064,668
Putting two columns into one
<p>I have a data file with two columns and I wanna put the into a singe column.</p> <p>Since now I have splitted the columns with open("test.txt") as input_data:</p> <pre><code>for line in input_data: # This keeps reading the file li=line.strip() #print repr(line) #Each line is being returned as a string ...
<p>You could use <a href="https://stackoverflow.com/questions/509211/the-python-slice-notation">Python's slicing notation</a> combined with the <code>+</code> operator on your columns. For example, joining the first two elements of a list is done by:</p> <pre><code>=&gt;&gt;&gt; l=["a","b","c","d"] &gt;&gt;&gt; a=[l[0...
python
1
2,955
29,572,421
how to avoid class having a __dict__
<p>I noticed many built-in classes do not have a <code>__dict__</code> and even classes in modules such as <code>numpy</code> do not have <code>__dict__</code> defined as they had been defined in C. </p> <p>I want to define <code>__getattr__</code>, but I'm worried about a recursive loop creeping into the (long) code ...
<p>Not having a <code>__dict__</code> will not prevent you from writing an infinite recursive loop.</p> <p>And yes, defining <code>__slots__</code> will prevent the creation of a <code>__dict__</code>.</p>
python-3.x
0
2,956
29,598,086
How to split a string into letters
<p>I need to import a 2 line txt file and change every "e" in the file to "bob" I know you start by the following but I am having a hard time of getting the words in the string into a string of letters so that I can use the .replace("e","bob") method. </p> <p>The txt file is the following:</p> <pre><code>Hey Jim, how...
<p>You don't need to go for splitting just replacing would be enough. </p> <pre><code>with open("file", 'r') as f: for line in f: print(line.replace('e', 'bob'), end="") </code></pre>
python|string|python-3.x|str-replace
7
2,957
46,386,053
How do I clear a label using Tkinter?
<p>I'm using labels to display who wins in a game of Tic Tac Toe I made. However, when the label gets overwritten with different text, the old text under it doesn't get cleared, only overwritten. So, some of the old text sometimes pokes through. Is there a way to clear a label to accomplish this without just making dif...
<p>You only need to update the text in the labels; it is not necessary to re-create and re-grid the labels for each game.<br> The score needs to be updated as well.<br> <code>self.update()</code> may be overkill; you can probably replace it with <code>self.update_idletasks()</code>, or delete it entirely.</p> <pre><co...
python|python-3.x|tkinter
1
2,958
46,285,961
when the if statement checks 'coffee' or 'c' I want is to also be able to check all forms of those too. I.e CofFeE should work but not cofe
<pre><code>coffeortea = input("Would you like coffee or tea? ") if 'coffee' == coffeortea: print("1") elif 'c' == coffeortea: print("2") else: print("3") </code></pre> <p>I would like it if the user types coFfeE to print 1. or if the user types C to type 2. Basically, I want upper and lower case to not be ...
<p>Compare on the if clauses everything uppercase or lowercase</p> <pre><code>coffeortea = input("Would you like coffee or tea? ") if 'coffee' == coffeortea.lower(): print("1") elif 'c' == coffeortea.lower(): print("2") else: print("3") </code></pre>
python
2
2,959
46,453,106
How to install pygame on python 3.4.4 using pip
<p>i am entering </p> <pre><code>pip install pygame </code></pre> <p>into cmd and what is retruned is </p> <pre><code>'pip' is not recognized as an internal or external command, operable program or batch file. </code></pre> <p>i am running windows 10 64 bit and python 3.4.4 64 bit</p>
<p>Entering <code>py -3.4 -m pip install pygame</code> in the command-line is the least error prone way to install pygame on Windows (replace <code>3.4</code> by your specific Python version). </p> <p>That is because you have to click a <a href="https://docs.python.org/3/using/windows.html#installation-steps" rel="nof...
python|pygame
1
2,960
33,355,268
Can't control any servo with my RaspberryPi 2
<p>I am having the problem, that I am not able to control any of my servos I have. I have two servos, one is a normal servo used in model planes and the second one is a micro sized servo. </p> <p>I wired both of them separately (The signal cable to a GPIO pin and the other two cables first directly to the board and af...
<p>The servos position is controlled by the pulsewidth of a 50 Hz PWM signal. Hence, we need to turn the PWM sequence on at 50 Hz. <strong>Note that for a 50 Hz signal, the Period of the signal is 1/50=.02 seconds, or 20 milliseconds.</strong> Keep this Period in mind as we will come back to it later. We start by creat...
python|raspberry-pi|gpio|pwm|servo
0
2,961
73,650,932
Group list of objects by parent property and serialize output to dict
<p><strong>SETUP:</strong></p> <p>I have the three SQLAlchemy classes <code>BusinessUnit</code>, <code>Task</code> and <code>Area</code> that are in a relationship.</p> <pre><code>class BusinessUnit(db.Model) id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String) db.relationship(&quot;Task...
<p>Every time you call <code>res.setdefault(item.business_unit.name, [])</code> there's a chance you create an unnecessary list, which is then going to be garbage collected. You can avoid this by using <code>defaultdict</code>:</p> <pre class="lang-py prettyprint-override"><code>from collections import defaultdict nam...
python|serialization|sqlalchemy
1
2,962
21,416,217
Extracting heading and strong tag with Beautiful Soup
<p>I am looking to extract the text string from a heading inside a <code>div</code> and the text within <code>&lt;strong&gt;</code> tags with BeautifulSoup.</p> <p>I can get the heading with <code>soup.h1</code> but I would like to get the <code>h1</code> that is specifically within the div <code>&lt;div class="site-c...
<p>you can use find <code>attrs</code> parameter, like:</p> <pre><code>soup.find('div', attrs={'class': 'site-content'}).h1 </code></pre> <p>EDIT: to get direct text only</p> <pre><code>for div in soup.findAll('div', attrs={'class': 'site-content'}): print ''.join([x for x in div.h1.contents \ ...
python|html|web-scraping|beautifulsoup
2
2,963
21,808,523
How to install Django REST ApI framework on Windows? I've Django1.7 Development version.
<p>I want to install Django rest framework on Windows.I couldn't install it with pip or git commands as those are linux commands. Also I want to know whether it works with Django 1.7 Development version or I need to install official version of Django</p>
<p>You should just be able to run the following in your shell:</p> <pre><code>pip install djangorestframework </code></pre>
python|django|django-rest-framework
1
2,964
24,557,266
Subtracting 3D numpy arrays in Python Vs Matlab
<p>I have two 3D numpy arrays and I would like to find out the difference between them.</p> <pre><code>&gt;&gt;&gt;A.dtype dtype('uint32') &gt;&gt;&gt;B.dtype dtype('uint32') &gt;&gt;&gt;A.shape (86, 50, 108) &gt;&gt;&gt;B.shape (86, 50, 108) &gt;&gt;&gt;A.min() 0 &gt;&gt;&gt;B.min() 0 &gt;&gt;&gt;A.max() 89478487...
<p>You are using Unsigned 32 bit ints. So you're getting an overflow</p> <pre><code>&gt;&gt;&gt; numpy.uint32(0) - numpy.uint32(1) 4294967295 </code></pre> <p>Try changing your array's to type int…</p> <pre><code>&gt;&gt;&gt; A = numpy.array([0,1,2],'uint32') &gt;&gt;&gt; B = numpy.array([1,2,3],'uint32') &gt;&gt;&g...
python|matlab|python-3.x|numpy
4
2,965
41,105,063
decoding URL encoded byte stream data in python
<p>I'm receiving STX ETX packet data, here's a sample: <img src="https://i.stack.imgur.com/L1nwl.png" alt="POST request received"></p> <p>The data has been URL encoded. Before it is encoded and sent it is like this: <img src="https://i.stack.imgur.com/uJMLy.jpg" alt="Data being sent to me"></p> <p>The relationship be...
<p>You can use the <code>urlparse</code> module to decode that string.</p> <pre><code>import urlparse data = "/type=stxetx&amp;packet=A%d93HX%01%00&amp;serial=1234&amp;foo=bar" new_data = dict(urlparse.parse_qsl(data)) assert len(new_data['packet']) == 7 assert new_data['packet'][0] == 'A' assert ord(new_data['packe...
python|unicode|encoding|utf-8
0
2,966
38,098,522
python multiline comment indent
<p>I have a Django project, and in some places we have multiline comments indented as follows: </p> <pre><code>field = models.IntegerField(default=0, null=True) # 0-initial_email_sent # 1-second_email_sent # 2-third_...
<p>Magic numbers are evil, so the best documentation here is to use named (pseudo) constants:</p> <pre><code>INITIAL_EMAIL_SENT = 0 SECOND_EMAIL_SENT = 1 THIRD_EMAIL_SENT = 2 field = models.IntegerField(default=INITIAL_EMAIL_SENT, null=True) </code></pre> <p>As a general rule, the less you have to comment the better...
python|pep
4
2,967
38,061,320
Workflow for making edits to Python package?
<p>I'd like to add a few features to a package (<a href="https://github.com/scikit-learn-contrib/lightning" rel="nofollow">https://github.com/scikit-learn-contrib/lightning</a>), but am unsure of the proper approach, especially since much of the source is in Cython.</p> <p>From other posts, I've gathered that for maki...
<p>Many possible answers to this one. My preference is to clone the source into a directory, create a symbolic link to the python module folder, and include the symbolic link in my PYTHONPATH environment variable.</p>
python
1
2,968
31,105,931
Interpolation as prediction in Python
<p>I have a LOWESS model fitted to my data using statsmodels and I now I want to use that for inference on my test data. The statsmodels packages doesn't provide an interface for inference, but as I have ~14.000 points describing a quite simple relationship, I am sure that linear interpolation will do just fine.</p> <...
<p>You can use numpy <code>interp</code> on your data like this:</p> <pre><code>import numpy as np new_x_values = [0,1,2] np.interp(new_x_values, lowess[:,0], lowess[:,1]) </code></pre>
python
1
2,969
31,140,384
Python 2.7, urllib2 and SAML Authentication
<p>I have a site that has SAML enabled security on it's web services. How can I use urllib2 to access this site? Are there any examples showing what I have to do in order to get this to work?</p> <p>When I access a SAML secure site, should the service url automatically re-direct me to the SAML login site?</p> <p>Th...
<p>Answering your second question first: yes, when there is an authentication attempt against a SAML secured resource by an unauthenticated user, the site will redirect to the identity provider.</p> <p>I'm not particularly familiar with SAML secured web services. The magic words to ask the provider of the resource is ...
python-2.7|urllib2|urllib|saml|saml-2.0
0
2,970
40,203,620
aiobotocore-aiohttp - Get S3 file content and stream it in the response
<p>I want to get the content of an uploaded file on S3 using botocore and aiohttp service. As the files may have a huge size:</p> <ul> <li>I don't want to store the whole file content in memory,</li> <li>I want to be able to handle other requests while downloading files from S3 (aiobotocore, aiohttp),</li> <li>I want ...
<p>it's because the <code>aiobotocore</code> api is different than the one of <code>botocore</code> , here <code>read()</code> returns a <code>FlowControlStreamReader.read</code> generator for which you need to yield from</p> <p>it looks something like that (taken from <a href="https://github.com/aio-libs/aiobotocore/...
python|amazon-s3|aiohttp|botocore
2
2,971
29,314,372
Itertools product without repeating duplicates
<pre><code>from itertools import product teams = ['india', 'australia', 'new zealand'] word_and = ['and'] tmp = '%s %s %s' items = [teams, word_and, teams] print(list(tmp % a for a in list(product(*items)))) </code></pre> <p>prints:</p> <pre><code>['india and india', 'india and australia', 'india and new zealand', ...
<p>You should use <a href="https://docs.python.org/3/library/itertools.html#itertools.combinations"><code>itertools.combinations</code></a> like this</p> <pre><code>&gt;&gt;&gt; from itertools import combinations &gt;&gt;&gt; teams = ['india', 'australia', 'new zealand'] &gt;&gt;&gt; [" and ".join(items) for items in ...
python|python-3.x|unique|combinations|itertools
28
2,972
58,984,259
How to calculate risk contribution of assets in Python
<p>I'm trying to write a block of code that will allow me to identify the risk contribution of assets in a portfolio. The covariance matrix is a 6x6 pandas dataframe.</p> <p>My code is as follows:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd weights = np.array([.1,.2,.05...
<p>Three problems with your code:</p> <p>Open your list operator square brackets on line 6: </p> <pre class="lang-py prettyprint-override"><code>data = pd.DataFrame(np.random.randn(1000,6),columns = ['a','b','c','d','e','f']) </code></pre> <p>You're using the two dimensional indexing operator wrong. You can't say <c...
python|pandas|numpy
2
2,973
52,134,869
why softmax_cross_entropy_with_logits_v2 return cost even same value
<p>i have tested "softmax_cross_entropy_with_logits_v2" with a random number</p> <pre><code>import tensorflow as tf x = tf.placeholder(tf.float32,shape=[None,5]) y = tf.placeholder(tf.float32,shape=[None,5]) softmax = tf.nn.softmax_cross_entropy_with_logits_v2(logits=x,labels=y) with tf.Session() as sess: feedx=...
<p>The way <code>tf.nn.softmax_cross_entropy_with_logits_v2</code> works is that it does softmax on your <code>x</code> array to turn the array into probabilities:</p> <p><a href="https://i.stack.imgur.com/oXKIH.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/oXKIH.gif" alt="enter image description here"></a...
tensorflow|softmax|cross-entropy
6
2,974
18,846,607
Python Flask Decorators and Apache mod_wsgi
<p>I have created a fairly strait forward example of the Flask/Python application, and then I have decided to split code to the two files, so I have moved all decorators for Authentication to separate file, like following:</p> <pre><code>#### test.py from flask import Flask, request, abort, request, make_response, url...
<p>The Flask debugger will likely not work if it detects that it is running in a multi process configuration as would often be the case for mod_wsgi if you are using embedded mode. Ensure you are using daemon mode of mod_wsgi:</p> <pre><code>WSGIDaemonProcess mysite WSGIProcessGroup mysite </code></pre> <p>Note, do N...
python|apache|flask|decorator|mod-wsgi
0
2,975
69,175,990
How does password checking in bcrypt work?
<p>So, I found the following example in <code>bcrypt</code> <a href="https://pypi.org/project/bcrypt/" rel="nofollow noreferrer">docs</a>:</p> <pre><code>password = b&quot;super secret password&quot; hashed = bcrypt.hashpw(password, bcrypt.gensalt()) if bcrypt.checkpw(password, hashed): print(&quot;It Matches!&quot...
<p>The salt gets saved in the hash itself. The scheme for bcrypt looks like the following:</p> <pre><code>$&lt;used_algorithm&gt;$&lt;cost_factor&gt;$&lt;generated_salt&gt;&lt;hash&gt;$ </code></pre>
python|bcrypt
2
2,976
62,111,692
How do I iterate through a file containing a list of floating point numbers in Python?
<p>I need to write a program that reads a file containing a list of floating-point numbers and counts how many of those numbers are larger than a user-specified threshold. </p> <p>numbers.txt - </p> <ul> <li>5.0</li> <li>15.0</li> <li>25.0</li> </ul> <p>This is my python code - </p> <pre><code>in_file = open("numb...
<pre><code>for line in open("numbers.txt", "r"): line = line.replace("\n","") num = float(line) </code></pre> <p>im sure you can continue from here..</p>
python|file
0
2,977
36,566,333
How to extract feature for an image after neural network training?
<p>Is there a way to learn unsupervised features from set of images. Similar to <code>word2vec</code> or <code>doc2vec</code>, where neural network is learnt and given new document we get its features.</p> <p>Expecting similar to this <a href="https://dato.com/learn/gallery/notebooks/food_retrieval-public.html" rel="n...
<p>If I correctly understood your question, this task is quite common in a deep learning field. In case of images what I consider the best is a convolutional autoencoder. You may read about this architecture e.g. here </p> <p><a href="http://people.idsia.ch/~ciresan/data/icann2011.pdf" rel="nofollow">http://people.ids...
python|machine-learning|keras|neural-network|deep-learning
1
2,978
36,554,318
Validating Classes and Methods are properly documented (type, arguments, returns, exceptions)?
<p>I run through my code using pep8, pyflakes, and pylint; which all validate the content and format of my Python code.</p> <p>What I am looking for now is to validate that my Python code is documented properly and completely. For example, if every method, and each of those methods arguments are also documented, as wel...
<p>pylint has a <a href="https://docs.pylint.org/extensions.html" rel="nofollow">Sphinx checker</a> which is disabled by default.</p>
python|python-sphinx|pylint|pep8
0
2,979
36,336,638
Python: Call a variable from another function within a class
<p>I am very new to Python and OOP in general. I have a very easy question thou that just won't be working for me. I have a class with several functions.</p> <pre><code>class Test: def a(self): var1 = 1 return var1 def b(self): var2 = 2 return var2 def c(self): v...
<p>You need to use <code>self</code> if you want to call an instance method or access a name (instance variable) from other instance methods.</p> <pre><code>def c(self): var3 = self.a() var4 = self.b() </code></pre>
python
2
2,980
19,312,556
python count repeating characters in a string by using dictionary function
<p>I have a string</p> <pre><code>string = 'AAA' </code></pre> <p>When using the <code>string.count('A')</code> the output is equal to 3 and if it is <code>string.count('AA')</code> the output is equal to 1</p> <p>However, there are 2 'AA's in the string.</p> <p>Is there any method to count repeated string like abo...
<p>The problem is Count return the number of (non-overlapping) occurrences of substring sub in string.</p> <p>try this as you can see at this <a href="https://stackoverflow.com/questions/2970520/string-count-with-overlapping-occurances/2970542#2970542">post</a>:</p> <pre><code>def occurrences(string, sub): count ...
python|string|dictionary
1
2,981
13,261,855
`pandas.DataFrame.apply` in a row by row operation
<p>I would like to return a dataFrame with each row sorted (let's say descending). So if I have the <code>pandas.DataFrame</code> named <code>data</code>:</p> <pre><code>In [38]: data Out[38]: c1 c2 c3 c4 c5 c6 Date ...
<p>Well, it's not too easy to do with pandas out of the box. First, familiarize yourself with <code>argsort</code>:</p> <pre><code>In [8]: df Out[8]: 0 1 2 3 4 2012-10-17 1.542735 1.081290 2.602967 0.748706 0.682501 2012-10-18 0.058414 0.148083 0.094104 0.71...
python|pandas
2
2,982
43,769,068
Jupyter notebook: Widget Javascript not detected
<p>Question: I installed python3 and jupyter notebook using pip3 in MacOs 10.9.<br> When I try to run the widget it gives error that there is no javascript widget. I have python3 and R kernels installed in Jupyter-notebook. </p> <p>Code: </p> <pre><code>from ipywidgets import widgets from IPython.display import dis...
<p>Run the following command: <code>jupyter nbextension enable --py --sys-prefix widgetsnbextension</code>, then restart the kernel in Jupyter should do the trick.</p>
python|jupyter-notebook|ipywidgets
7
2,983
54,480,854
How it is the way that the proxy we connect Discript changed when we check in Google "Whatymisoip"
<p>I try to make a tool to change change IP address in the desired time but when I check the ip diwhatismyip does not change</p> <pre><code>try: while True: url = "http://www.google.com" check = open(inputss,'r').readlines() ip = random.choice(check) auah = {"https":ip} ...
<p>I suppose you can change your IP address using the following simple script if you are using a windows machine:</p> <pre><code>import os import time os.system("ipconfig /release") time.sleep(5) os.system("ipconfig /renew") </code></pre> <p>this should do the job, you can then scrape your IP address</p>
python|proxy|urllib
0
2,984
39,413,828
How to extract columns from multiple rows in Python using nested loops?
<p>I have a list with 3 sequences</p> <pre><code>seq_list = ['ACGT', 'ATTT', 'ACCC'] </code></pre> <p>I want to extract the columns from the the list and store it in another list using nested loops in python</p> <p>The final output should be </p> <pre><code>seq_list = ['AAA', 'CTC', 'GTC','TTC'] </code></pre> <p>I...
<p>By your method I made little modification, for each inner <code>for</code> loop i created a <code>string</code> and then after inner <code>for</code> loop ends i appended it to <code>column</code>:</p> <pre><code>seq_list = ['ACGT', 'ATTT', 'ACCC'] column = [] for i in range(len(seq_list[0])): #Length of the row ...
python|python-2.7|for-loop|extract|multiple-columns
2
2,985
52,546,444
how to build and train an lstm network in tensorflow.js
<p>I am trying to build and train an lstm network using tensorflow.js, my data set is like </p> <p>Input: "I don't like these shoes, they are too yellow for me. so returning them." Expected output reason: "color"</p> <p>I can present the text as vectors using a pre-trained word2vec model. Tried reading the documentat...
<p>Here is an example of an RNN with multi-layer LSTM that implements Word2Vec. I don't think you'll need to tweak it much to match your use case- probably only the data source and the hyperparameters. Of course, you'll need to write your own testing function too. Since you said you can supply your own pre-trained Word...
node.js|lstm|tensorflow.js
3
2,986
47,745,209
Proper way of importing Python scripts from separate folders
<p>So I have been fiddling around as well as conducting some serious work with Python for quite some time. Though, I still have some issues with it every once in a while. </p> <p>I find it to be the most comfortable using <code>PyCharm CE</code> when working with Python. The typical scenario is that I just create a ne...
<p>Thanks for all the responses and references to possible solutions. While researching online, I have come across various instances of more or less the same problem that people were having while importing modules and packages. So, this is how I have just resolved it:</p> <ul> <li>Under the <code>important_scripts</co...
python|terminal|pycharm|virtualenv
0
2,987
37,360,626
Integer to String error in my program
<p>I am having a problem with a program I am currently working on. It is a GTIN-8 Code generator. When I try to start the program, I get the error:</p> <pre><code>Type Error: Can't convert 'int' to str implicitly. </code></pre> <p>My code is as follows:</p> <pre><code>sevenNum = "" gtinNum = "" checkDigit = "" total...
<p>You cannot concatenate <code>string</code> and <code>int</code>s together:</p> <pre><code>print("GTIN-8 Code:" + a+b+c+d+e+f+g+checkDigit) </code></pre> <p>It is more correct to use string formatting anyway, for example:</p> <pre><code>print("GTIN-8 Code: {0}{1}{2}{3}{4}{5}{6}{7}".format(a, b, c, d, e, f, g, chec...
python|string|int
0
2,988
34,126,136
Using meshgrid to convert X,Y,Z triplet to three 2D arrays for surface plot in matplotlib
<p>I'm new to Python so please be patient. I appreciate any help! </p> <p><strong>What I have:</strong> three 1D lists (<strong>xr, yr, zr</strong>), one containing x-values, the other two y- and z-values<br> <strong>What I want to do:</strong> create a 3D contour plot in matplotlib </p> <p>I realize...
<p>Well,sample code below works for me</p> <pre><code>import numpy as np import matplotlib.pyplot as plt xr = np.linspace(-20, 20, 100) yr = np.linspace(-25, 25, 110) X, Y = np.meshgrid(xr, yr) #Z = 4*X**2 + Y**2 zr = [] for i in range(0, 110): y = -25.0 + (50./110.)*float(i) for k in range(0, 100): ...
python|matplotlib|surface|mplot3d
1
2,989
39,619,046
lxml xsi:schemaLocation namespace URI validation issue
<p>I'm trying to use <code>lxml.etree</code> to reproduce the CDA example found in the <a href="http://www.lantanagroup.com/resources/free-tools/" rel="noreferrer">CDA QuickStart Guide found here</a>.</p> <p>In particular, I'm running into issues with namespaces trying to recreate this element.</p> <pre><code>&lt;Cli...
<p><code>nsmap</code> is a mapping of prefixes to namespace URIs. <code>urn:hl7-org:v3 CDA.xsd</code> is a valid value for the <code>xsi:schemaLocation</code>attribute, but it is not a valid namespace URI.</p> <p>The solution to a similar question, <a href="https://stackoverflow.com/q/46405690/407651">How to include t...
python|xml|lxml|xml-namespaces|cda
15
2,990
39,606,921
Changing pointplot legend in seaborn
<p>I would like to change the label for the legend and items in the legend for this plot. Right now the label for the legend is "Heart" and the items are 0 and 1. I would like to be able to change all of these to something else, but am unsure how. Here is what I have so far. </p> <pre><code>sns.set_context("talk",font...
<p>An alternative to changing the column names of the data frame, is to create a new legend using the same legend handles (this is what determines the colored markers), but with new text labels:</p> <pre><code>import seaborn as sns tips = sns.load_dataset('tips') ax = sns.pointplot(x='sex', y='total_bill', hue='time'...
python|seaborn
3
2,991
32,018,923
Theano import Error-windows 7
<p>I have a problem in importing theano in python. When I import Theano in the python 27 32 bit, in Windows 7 64 bit, I get the following errors and warning: I also should add that currently I have installed GCC 4.8.1. What I have to do in order to fix it. </p> <p>Thanks, Afshin</p> <pre><code>WARNING (theano.gof.cmo...
<p>You should check your windows path and make sure they are all right.</p>
python|windows-7|64-bit|python-import|theano
1
2,992
9,783,983
Nested, infinite dictionary in python
<p>I want set the keys and values ​​in the dictionary. Here is an example of what I do.</p> <pre><code>class NestedDict(dict): def __getitem__(self, key): if key in self: return self.get(key) return self.setdefault(key, NestedDict()) &gt;&gt;&gt; c = NestedDict() &gt;&gt;&gt; c {} &gt;&gt;&gt; c['...
<p>Since <code>d</code> is non existent in <code>c['a']</code>, what kind of behaviour do you expect when you try to add <code>1</code> to it? It will first call <code>__getitem__</code>, not find the key and then return a <code>NestedDict</code> which doesn't support in place addition with an <code>int</code>. </p> <...
python|dictionary
13
2,993
10,221,926
Get sublayers from group layer with Python in Gimp
<p>I have an XCD file with a nested layers structure:</p> <pre><code>image front-layer content-layer content-layer-name-1 content-layer-name-2 content-layer-name-3 back-layer </code></pre> <p>I open the file with <code>image = pdb.gimp_file_load(xcf_file, xcf_file)</code> and can g...
<p>GIMP Python went mostly unmaintained over this development cycle (you can blame much of that on myself).</p> <p>One of the few updates done was the creation of the "Item" class - and the implementation of a class method on it that allows one to use the numeric ID returned by the PDB methods to retreive an item.</p...
python|layer|gimp|xcf|python-fu
9
2,994
62,969,449
How to change the value of Boolean Field in Model from the views?
<p>The application I've been working uses</p> <ul> <li>Class Based Views</li> </ul> <p>has</p> <ul> <li>two models, Question and Answer.</li> </ul> <p>The Question model has a <code>FileField</code> to store the actual solution to that question and the Answer model has a <code>FileField</code> named <code>result</code>...
<p>So you could do something like this in your <code>CoderCreateView</code>:</p> <pre class="lang-py prettyprint-override"><code> def form_valid(self, form): question = Question.objects.get(pk=self.kwargs['qid']) form.instance.question = question form.instance.question.is_correct = comparator...
python|django|django-views
2
2,995
44,370,075
Azure Storage Table returning empty entities
<p>I have the following Python code:</p> <pre><code>def GetData(tableService, tableName, dataFilter): keyMarkers = {} keyMarkers['nextpartitionkey'] = 0 keyMarkers['nextrowkey'] = 0 b=[] while True: #get a batch of data a = tableService.query_entities(table_name=tableName, filter=da...
<p>On the very first request, can you try passing in 'None' for the marker, rather than a dictionary with 0 and 0 for nextpk / nextrk? I'm not sure, but this might be confusing the service into searching for a table entity with this pk &amp; rk.</p>
python|azure|azure-table-storage
1
2,996
44,260,056
Run Powershell commands from Python
<p>I know related questions where already posted, but I cannot get a hang of them. </p> <p>I have a Powershell-command and put it in Python in a string, say string <code>aa</code>.</p> <p>How can I run command <code>aa</code> from Python. I know I should use <code>subprocess</code>, but I am not sure in what way. </p...
<p>You are looking for <a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow noreferrer">popen</a>.</p> <pre><code>from subprocess import Popen, PIPE process = Popen(['cd', path], stdout=PIPE, stderr=PIPE) stdout, stderr = process.communicate() </code></pre>
python|powershell
0
2,997
27,337,372
Python requests 0.x code port to 2.x
<p>I had a really simple piece of code working with Python requests 0.x but when I updated to 2.x it no longer works.</p> <p>The code would return me the color contained within <code>'field1'</code>:</p> <pre><code>import time import requests # Read the thingspeak feed to get the current colour while True: chee...
<p><a href="https://requests.readthedocs.io/en/latest/api/#requests.Response.json" rel="nofollow noreferrer"><code>response.json()</code></a> is now a <em>method</em>, where in the past it was a property; add <code>()</code> to call it:</p> <pre><code>response = requests.get('http://api.thingspeak.com/channels/1417/fi...
python|python-requests
3
2,998
27,207,088
NaNs comparing equal in Numpy
<p>Consider the following script:</p> <pre><code>import numpy as np a = np.array([np.nan], dtype=float) b = np.array([np.nan], dtype=float) print a == b a = np.array([np.nan], dtype=object) b = np.array([np.nan], dtype=object) print a == b </code></pre> <p>On my machine this prints out</p> <pre><code>[False] [ Tru...
<p>On newer versions of numpy you get this warning:</p> <pre><code>FutureWarning: numpy equal will not check object identity in the future. The comparison did not return the same result as suggested by the identity (`is`)) and will change. </code></pre> <p>my guess is that numpy is using <code>id</code> test as a sho...
python|numpy|nan|ieee-754|multidimensional-array
8
2,999
495,579
Best opensource IDE for building applications on Google App Engine?
<p>Looking to dabble with GAE and python, and I'd like to know what are some of the best tools for this - thanks!</p>
<p>I would spend the time and learn something like <strong><em>emacs</em></strong>. The learning curve is a bit higher, but once you get used to it, you can develop from any terminal. It has fantastic support for python and many other libraries.</p> <p>You have to remember that Python is a dynamically typed language...
python|google-app-engine|ide
15