title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How do I make a variable able to be used for the entire sheet but not for different sheets?
38,487,098
<p>I have a class and I define variables when I call the class. But if I define them in one place they aren't defined in the other. I tried using globals but then I when I call the class it says they are already defined.</p> <p>How do i define it only in one function and have that definition work for the others?</p> ...
0
2016-07-20T17:30:32Z
38,487,141
<p>You have to use instance variables assigned to the instance. And later call them like this,</p> <pre><code>class Addresses(): def __init__(self, address, variableName): self.adress = adress self.variableName = variableName if header == address: # you can use address of self....
2
2016-07-20T17:33:34Z
[ "python", "class", "variables" ]
Python 2.x - sleep call at millisecond level on Windows
38,487,114
<p>I was given some very good hints in this forum about how to code a clock object in Python 2. I've got some code working now. It's a clock that 'ticks' at 60 FPS:</p> <pre><code>import sys import time class Clock(object): def __init__(self): self.init_os() self.fps = 60.0 self._tick = ...
0
2016-07-20T17:31:38Z
38,488,544
<p>You can temporarily lower the timer period to the <code>wPeriodMin</code> value returned by <a href="https://msdn.microsoft.com/en-us/library/dd757627" rel="nofollow"><code>timeGetDevCaps</code></a>. The following defines a <code>timer_resolution</code> context manager that calls the <a href="https://msdn.microsoft....
2
2016-07-20T18:48:53Z
[ "python", "windows", "time", "sleep", "clock" ]
Parse date and time form a csv file
38,487,181
<p>I've some csv files with the following format:</p> <pre><code>330913;23;2;2013;0;0;6;8;7 330914;23;2;2013;0;5;25;8;7 330915;23;2;2013;0;10;11;8;7 330916;23;2;2013;0;15;30;8;7 330917;23;2;2013;0;20;17;8;7 330918;23;2;2013;0;25;4;8;7 </code></pre> <p>I read them into a pandas DataFrame and need to specify a column (...
1
2016-07-20T17:35:21Z
38,487,425
<p>Check out the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a> method. Specifically, the <code>date_parser</code> kwarg is what you are looking for. It takes the resulting string created by the <code>parse_date</code> columns and processes ...
2
2016-07-20T17:49:29Z
[ "python", "datetime", "pandas" ]
pyorient can't connect to orientdb docker
38,487,197
<p>I'm using pyorient 1.5.4 and the docker for orientdb 2.2.5</p> <p>If I use the browser to connect to the database, the server is clearly running. If I connect with pyorient, I get an error.</p> <p>Here is the code I use to connect to the database:</p> <pre><code>import pyorient database = pyorient.OrientDB('127....
0
2016-07-20T17:36:17Z
38,491,410
<p>I found my problem. I was starting the docker container with:</p> <pre><code>-Ddistributed=true </code></pre> <p>removing the parameter enabled me to connect just fine.</p> <p>However, I have found that pyorient gets into an infinite loop when trying to parse the packets that's returned from orientDB under distri...
2
2016-07-20T21:47:23Z
[ "python", "orientdb", "pyorient" ]
how can I parse json with a single line python command?
38,487,200
<p>I would like to use python to parse JSON in batch scripts, for example: </p> <pre><code>HOSTNAME=$(curl -s ${HOST} | python ?) </code></pre> <p>Where the JSON output from curl looks like:</p> <pre><code>'{"hostname":"test","domainname":"example.com"}' </code></pre> <p>How can I do this with a single line python ...
-1
2016-07-20T17:36:26Z
38,487,201
<p>Based on the JSON below being returned from the curl command ...</p> <pre><code>'{"hostname":"test","domainname":"example.com"}' </code></pre> <p>You can then use python to extract the hostname using the python json module:</p> <pre><code>HOSTNAME=$(curl -s ${HOST} | python -c \ 'import json,sys;print json.lo...
1
2016-07-20T17:36:26Z
[ "python", "json" ]
searching for a specific element in default dictionary PYTHOn
38,487,239
<p><strong>My dict:</strong></p> <pre><code>expiry_strike = defaultdict(&lt;type 'list'&gt;, {'2014-02-21': [122.5], '2014-01-24': [123.5, 122.5, 119.0, 123.0]}) expiry_value = defaultdict(&lt;type 'list'&gt;, {'2014-02-21': [-100], '2014-01-24': [-200, 200, 1200, 200]}) </code></pre> <p><strong>My question :</strong...
0
2016-07-20T17:38:46Z
38,487,500
<p>I am going to show you how you can find the most common element, the rest you should handle yourself.</p> <p>There is this nice library called <code>collections</code> which has a <code>Counter</code> class in it. Which counts each element in an iterable and stores them in a dictionary with the keys are the items a...
1
2016-07-20T17:52:23Z
[ "python", "loops", "defaultdict" ]
Gnome python bindings
38,487,291
<p>I am porting a PyGTK/Gnome application.</p> <p>It uses <code>gnome</code> in a couple of places:</p> <pre><code>import gnome gnome.program_init("prog", str(app_version), properties=props) ... gnome.help_display("prog") </code></pre> <p>Searching the <a href="https://lazka.github.io/pgi-docs/" rel="nofollow">gi re...
1
2016-07-20T17:41:45Z
38,495,877
<p>This looks like an old binding with <code>libgnome</code>, which was deprecated a long time ago in C. I suggest you look for calls to gnome methods (like the gnome.help_display), and then look in Gtk3 for similar methods. </p> <p>In the particular case of <code>gnome.help_display</code>, there is no equivalent for...
2
2016-07-21T05:51:32Z
[ "python", "gtk3", "gnome-3" ]
Django Prefetch with custom queryset which uses managers method
38,487,303
<p>Let's look at example from django docs with Pizza and Topping models. One pizza may have multiple toppings.</p> <p>If we make a query:</p> <pre><code>pizzas = Pizza.objects.prefetch_related('toppings') </code></pre> <p>We'll get all the pizzas and their toppings in 2 queries. Now let's suppose that I want to pref...
5
2016-07-20T17:42:36Z
38,914,783
<p>I haven't tested this directly, but you should not invoke a method or filter again in the loop, as prefetch_related has already attached the data. So either of these should work:</p> <pre><code>pizzas = Pizza.objects.prefetch_related( Prefetch('toppings', queryset=Topping.objects.filter(is_vegetarian=True)) ) f...
0
2016-08-12T09:41:16Z
[ "python", "django" ]
pysvn getting previous version
38,487,328
<p>I am working on a script that searches the log for a particular string in log.message and populates all the the revisions having that particular string. But I would like to get the previous version to the one which has the first instance of the string. I am not able to come up with a way that would do this. </p> <...
0
2016-07-20T17:43:34Z
38,973,615
<p>There are two answer depending on what you will do with previous rev.</p> <p>If you just want to do a diff then having figured out that the string is in rev N you can diff between N and N-1.</p> <p>If you want to know the rev of the change before the file with the string you can call log() again providing the path...
0
2016-08-16T11:23:17Z
[ "python", "python-2.7", "pysvn" ]
Pandas/Python memory spike while reading 3.2 GB file
38,487,334
<p>So I have been trying to read a 3.2GB file in memory using pandas <code>read_csv</code> function but I kept on running into some sort of memory leak, my memory usage would spike <code>90%+</code>.</p> <p>So as alternatives </p> <ol> <li><p>I tried defining <code>dtype</code> to avoid keeping the data in memory as ...
1
2016-07-20T17:43:57Z
38,488,420
<p>A file stored in memory as text is not as compact as a compressed binary format, however it is relatively compact data-wise. If it's a simple ascii file, aside from any file header information, each character is only 1 byte. Python strings have a similar relation, where there's some overhead for internal python stuf...
1
2016-07-20T18:42:15Z
[ "python", "csv", "pandas", "memory" ]
Pandas/Python memory spike while reading 3.2 GB file
38,487,334
<p>So I have been trying to read a 3.2GB file in memory using pandas <code>read_csv</code> function but I kept on running into some sort of memory leak, my memory usage would spike <code>90%+</code>.</p> <p>So as alternatives </p> <ol> <li><p>I tried defining <code>dtype</code> to avoid keeping the data in memory as ...
1
2016-07-20T17:43:57Z
38,488,684
<p>Based on your second chart, it looks as though there's a brief period in time where your machine allocates an additional 4.368 GB of memory, which is approximately the size of your 3.2 GB dataset (assuming 1GB overhead, which might be a stretch).</p> <p>I tried to track down a place where this could happen and have...
1
2016-07-20T18:56:39Z
[ "python", "csv", "pandas", "memory" ]
Python- How to make colorbar orientation horizontal?
38,487,440
<p>So I have a plot with a basemap, a colormesh on top, and a colorbar set to cbar. I want the colorbar orientation to be horizontal instead of vertical, but when I set orientation='horizontal' in the cbar=m.colorbar line after extend='max', I get the following error: "colorbar() got multiple values for keyword argumen...
2
2016-07-20T17:50:10Z
38,494,964
<p>You need to use <code>location=bottom</code></p> <pre><code>cbar=m.colorbar(trend, size='3%',ticks=bounds,extend="max",location=bottom) </code></pre> <p>I got that from <a href="https://basemaptutorial.readthedocs.io/en/latest/plotting_data.html#hexbin" rel="nofollow">this</a> example in the basemap documentation....
2
2016-07-21T04:36:51Z
[ "python", "matplotlib", "orientation", "colorbar" ]
Using RegEx to match every segment of a line that starts with a specified term and stopping when that term occurs again.
38,487,441
<p>As the title suggests I am trying to figure out how to use RegEx when reading a line from a text file and store every occurrence of a match in a list. I know using the findall method would do this but I first need to create an appropriate RegEx. What I have so far will only select the first instance of the expressio...
0
2016-07-20T17:50:11Z
38,489,175
<p>It seems like you need </p> <pre><code>(?s)(CAN|NUL|E(?:TX|NQ|SC)|S(?:OH|UB))(?:(?!\1).)* </code></pre> <p>See the <a href="https://regex101.com/r/nG3iF1/1" rel="nofollow">regex demo</a>. </p> <p>The <code>(CAN|NUL|E(?:TX|NQ|SC)|S(?:OH|UB))</code> is a Group 1 capturing your terms (the pattern is a bit optimized ...
0
2016-07-20T19:24:31Z
[ "python", "regex", "python-2.7", "python-3.x" ]
Pandas find how many times a column value appears in dataset
38,487,497
<p>I am trying to sort data by the <code>Name</code> column, by popularity.</p> <p>Right now, I'm doing this:</p> <pre><code>df['Count'] = df.apply(lambda x: len(df[df['Name'] == x['Name']]), axis=1) df[df['Count'] &gt; 50][['Name', 'Description', 'Count']].drop_duplicates('Name').sort_values('Count', ascending=False...
-1
2016-07-20T17:52:12Z
38,487,593
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow"><code>Series.value_counts</code></a>.</p> <pre><code>df = pd.DataFrame([[0, 1], [1, 0], [1, 1]], columns=['a', 'b']) print(df['b'].value_counts()) </code></pre> <p>outputs</p> <pre><code>1 ...
0
2016-07-20T17:56:45Z
[ "python", "pandas" ]
Pandas find how many times a column value appears in dataset
38,487,497
<p>I am trying to sort data by the <code>Name</code> column, by popularity.</p> <p>Right now, I'm doing this:</p> <pre><code>df['Count'] = df.apply(lambda x: len(df[df['Name'] == x['Name']]), axis=1) df[df['Count'] &gt; 50][['Name', 'Description', 'Count']].drop_duplicates('Name').sort_values('Count', ascending=False...
-1
2016-07-20T17:52:12Z
38,487,967
<p>Try this: </p> <pre><code>a = ["jim"]*5 + ["jane"]*10 + ["john"]*15 n = pd.Series(a) sorted((n.value_counts()[n.value_counts() &gt; 5]).index) ['jane', 'john'] </code></pre>
0
2016-07-20T18:16:21Z
[ "python", "pandas" ]
Pandas find how many times a column value appears in dataset
38,487,497
<p>I am trying to sort data by the <code>Name</code> column, by popularity.</p> <p>Right now, I'm doing this:</p> <pre><code>df['Count'] = df.apply(lambda x: len(df[df['Name'] == x['Name']]), axis=1) df[df['Count'] &gt; 50][['Name', 'Description', 'Count']].drop_duplicates('Name').sort_values('Count', ascending=False...
-1
2016-07-20T17:52:12Z
38,557,299
<p>The solution I have been looking for is:</p> <pre><code>df['Count'] = df.groupby('Name')['Name'].transform('count') </code></pre> <p>Big thanks to @Lynob for providing a link with an answer.</p>
0
2016-07-24T22:06:41Z
[ "python", "pandas" ]
What does return['string'] do?
38,487,514
<p>The below block of code below is taken from the following forum <a href="http://stackoverflow.com/questions/37083058/programmatically-searching-google-in-python-using-custom-search">Programmatically searching google in Python using custom search</a></p> <pre><code>from googleapiclient.discovery import build import ...
-3
2016-07-20T17:52:55Z
38,487,612
<p>My guess would be that res is a dictionary object. Returning <code>res['items']</code> will return the values stored with the key <code>'items'</code> in the dictionary object <code>res</code>. </p>
0
2016-07-20T17:58:00Z
[ "python", "return" ]
What does return['string'] do?
38,487,514
<p>The below block of code below is taken from the following forum <a href="http://stackoverflow.com/questions/37083058/programmatically-searching-google-in-python-using-custom-search">Programmatically searching google in Python using custom search</a></p> <pre><code>from googleapiclient.discovery import build import ...
-3
2016-07-20T17:52:55Z
38,487,618
<p>It is returning the value of that key in the variable <code>res</code>.</p> <p>Imagine a data structure like the following:</p> <pre><code>{ "errors": [], "items": [ "item1", "item2", "item3"], "status": "success" } </code></pre> <p>This is a regular python dictionary that you could use in your projec...
2
2016-07-20T17:58:19Z
[ "python", "return" ]
What does return['string'] do?
38,487,514
<p>The below block of code below is taken from the following forum <a href="http://stackoverflow.com/questions/37083058/programmatically-searching-google-in-python-using-custom-search">Programmatically searching google in Python using custom search</a></p> <pre><code>from googleapiclient.discovery import build import ...
-3
2016-07-20T17:52:55Z
38,487,631
<p><code>res</code> is a disctionnary, here is an example of what it could contain :</p> <pre><code>res = { 'item_count': 50, 'items': ['item1', 'item2', 'item3'], 'search' : 'search terms here' } </code></pre> <p>If you return <code>res</code>, then you get everything in the results. In my example you c...
0
2016-07-20T17:58:51Z
[ "python", "return" ]
PyQt4 connect signals between classes
38,487,621
<p>I am new in gui programming with pyQt. I have setup a simple gui with a button that shall execute a method from a separate class when it is clicked. But when I click the button the following error comes up:</p> <p><strong>* Process received signal <em></strong> Signal: Segmentation fault (11) Signal code: Address n...
0
2016-07-20T17:58:25Z
38,490,502
<p>I cannot reproduce the segfault with your code on my system, but it must be because your are not keeping references to the objects that are supposed to live till the end of Qt app. </p> <p>In <code>Main.__init__</code> you assign newly created <code>MyWindow</code> and <code>A</code> to local variables. These ob...
0
2016-07-20T20:44:05Z
[ "python", "user-interface", "pyqt4" ]
Python CaesarCipher IndexError
38,487,663
<p>Running python 3.5. I'm start a study of basic encryption and I decided to try my hand at writing a simple Caesar cipher. Pretty straight forward logic:</p> <p>1) for a given plaintext message, find the index for each message symbol in my LETTERS string</p> <p>2) add the shift key to the index</p> <p>3) the resul...
1
2016-07-20T18:00:28Z
38,487,933
<p>Python indexes lists starting at 0. This will have the following effects:</p> <pre><code>&gt;&gt;&gt; x = ['a', 'b', 'c', 'd'] &gt;&gt;&gt; len(x) 4 &gt;&gt;&gt; x[0] 'a' &gt;&gt;&gt; x[3] 'd' &gt;&gt;&gt; x[4] IndexError: list index out of range </code></pre> <p>Notice that <code>x[4]</code> is already out-of-sco...
2
2016-07-20T18:14:24Z
[ "python" ]
ValueError: invalid literal for int() with base 10:
38,487,701
<pre><code>height_feet = int(input("Enter portion of height in feet ")) height_inch = int(input("Enter portion of heigh in inches")) height_in_inch = height_feet * 12 + height_inch height_in_cm = height_in_inch * 2.54 print (height_in_cm) Enter portion of height in feet 6 Enter portion of heigh in inches1.5 Traceback ...
1
2016-07-20T18:02:41Z
38,487,744
<p>This should be a <code>float</code> type, not an <code>int</code> type.</p>
0
2016-07-20T18:05:30Z
[ "python", "python-3.x" ]
ValueError: invalid literal for int() with base 10:
38,487,701
<pre><code>height_feet = int(input("Enter portion of height in feet ")) height_inch = int(input("Enter portion of heigh in inches")) height_in_inch = height_feet * 12 + height_inch height_in_cm = height_in_inch * 2.54 print (height_in_cm) Enter portion of height in feet 6 Enter portion of heigh in inches1.5 Traceback ...
1
2016-07-20T18:02:41Z
38,488,220
<p>In Python and elsewhere, ints are only <em>whole</em> numbers. 1.5, 1.2, pi, anything with a decimal is not an int. You want <code>float</code> to describe them. It's short for floating point number. </p>
0
2016-07-20T18:30:28Z
[ "python", "python-3.x" ]
Fetching *list* contents from a text file in Python
38,487,763
<p>I need help to fetch list back from a file where each line is stored as a list. For example, check the following lists.txt file</p> <pre><code>["1","Andy Allen","Administrator"] ["2","Bob Benny","Moderator"] ["3","Zed Zen","Member"] </code></pre> <p>I need the content to be accessible and be displayed in the follo...
0
2016-07-20T18:06:19Z
38,487,869
<p>This format, using only double quotes and not single, looks like <a href="https://en.wikipedia.org/wiki/JSON" rel="nofollow">JSON (JavaScript object notation)</a>. Fortunately, the <code>json</code> module that comes with Python 2.6 or later can parse JSON. So read each line, parse it as JSON (using <code>json.loads...
1
2016-07-20T18:11:10Z
[ "python", "list", "implicit-conversion" ]
Fetching *list* contents from a text file in Python
38,487,763
<p>I need help to fetch list back from a file where each line is stored as a list. For example, check the following lists.txt file</p> <pre><code>["1","Andy Allen","Administrator"] ["2","Bob Benny","Moderator"] ["3","Zed Zen","Member"] </code></pre> <p>I need the content to be accessible and be displayed in the follo...
0
2016-07-20T18:06:19Z
38,489,245
<p>How about using grep to grab all the contents inside the [ ]?</p>
0
2016-07-20T19:28:19Z
[ "python", "list", "implicit-conversion" ]
Unsubscribing from ROS Topic - Python
38,487,816
<p>So I have a Class and in its init function, I subscribe to a camera, whose callback function is created in my class. i.e:</p> <pre><code>class example(object): def __init__(self): rospy.subscriber("/cameras/left_hand_camera/image",Image,self.callback_viewer) def callback_viewer(self,data): try: cv...
0
2016-07-20T18:08:35Z
38,491,956
<p>I don't understand exactly what you have to do, but when you subscribe to a topic, you can write something like this:</p> <pre><code>sub = rospy.subscriber("/cameras/left_hand_camera/image",Image,self.callback_viewer) </code></pre> <p>Then when you have to unsubscribe you just have to do:</p> <pre><code>sub.unreg...
2
2016-07-20T22:32:49Z
[ "python", "ros", "unsubscribe" ]
How to get a list of index values after groupby().mean() in pandas?
38,487,840
<p>I am stuck with this. I would like to get a list of <code>name</code> from the following, a result of <code>groupby().mean()</code> with the application of pandas DataFrame. Most specifically, I would like to get <code>["John", "Mary", "Suzan", "Eric"]</code>.</p> <pre><code> score name John 85.0 Mary...
1
2016-07-20T18:09:42Z
38,487,912
<p>You can use:</p> <pre><code>print (list(means.index)) ['John', 'Mary', 'Suzan', 'Eric'] </code></pre> <p>Another better solution is use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unique.html" rel="nofollow"><code>Series.unique</code></a> and omit <code>groupby</code>:</p> <pre><c...
1
2016-07-20T18:13:42Z
[ "python", "pandas", "dataframe", "group-by", "mean" ]
How to get a list of index values after groupby().mean() in pandas?
38,487,840
<p>I am stuck with this. I would like to get a list of <code>name</code> from the following, a result of <code>groupby().mean()</code> with the application of pandas DataFrame. Most specifically, I would like to get <code>["John", "Mary", "Suzan", "Eric"]</code>.</p> <pre><code> score name John 85.0 Mary...
1
2016-07-20T18:09:42Z
38,487,981
<p>Just look at the index if you have an Index. If you have a MultiIndex, see @jezrael's answer with <code>get_level_values</code>.</p> <pre><code>means.index.tolist() </code></pre>
3
2016-07-20T18:17:17Z
[ "python", "pandas", "dataframe", "group-by", "mean" ]
AttributeError: module 'pandas.io.sql' has no attribute 'frame_query'
38,487,878
<p>I am trying to read a posgresql table into a python data frame using following code.</p> <pre><code>import psycopg2 as pg import pandas.io.sql as psql connection = pg.connect("dbname=BeaconDB user=admin password=root") dataframe = psql.frame_query("SELECT * from encounters", connection) </code></pre> <p>But I get...
1
2016-07-20T18:11:38Z
38,487,959
<p>Looking at the pandas.io.sql source, there is no frame_query.</p> <p><a href="https://github.com/pydata/pandas/blob/master/pandas/io/sql.py" rel="nofollow">https://github.com/pydata/pandas/blob/master/pandas/io/sql.py</a></p> <p>Documentation for pandas.io.sql is here: <a href="http://pandas.pydata.org/pandas-docs...
0
2016-07-20T18:16:04Z
[ "python", "pandas", "attributes" ]
Dictionary parsing python
38,487,894
<p>I have a dictionary which has a key with a list of values . Something like this:</p> <pre><code>{'a': ['a1', 'a2'], 'b': ['b1', 'b2'], 'c': ['c1', 'c2']} </code></pre> <p>My code for building this :</p> <pre><code>import csv reader = csv.DictReader(open('abc.csv')) print(reader) result = {} for row in reader: ...
1
2016-07-20T18:12:21Z
38,487,951
<p>The <code>DictReader</code> instance is an iterator that already contains the dictionaries that you seek. You would not need to modify the reader, just turn it into a list:</p> <pre><code>import csv reader = csv.DictReader(open('abc.csv')) result = list(reader) </code></pre> <p><code>result</code> will be a list ...
2
2016-07-20T18:15:40Z
[ "python", "excel", "csv", "dictionary" ]
Python - Using a loop to write a new line into a text file
38,487,896
<p>I want to add onto this program to save each crashPoint to a text file, with a new crash point being added onto a new line. I've attempted to do it from past work, but I can't seem to get it to work together.</p> <pre><code>#Imports from bs4 import BeautifulSoup from urllib import urlopen import time #Required Fie...
-1
2016-07-20T18:12:36Z
38,488,025
<p>I haven't worked with some of the exact modules you're using so unless they do something weird I can't gleam from this. The problems I can see are...</p> <ol> <li>It seems like you have an infinite loop, while pageCount > 0 and pageCount+=1 so this could be an issue</li> <li>You're printing to the console not to a ...
0
2016-07-20T18:20:01Z
[ "python", "file", "text", "append" ]
Python - Using a loop to write a new line into a text file
38,487,896
<p>I want to add onto this program to save each crashPoint to a text file, with a new crash point being added onto a new line. I've attempted to do it from past work, but I can't seem to get it to work together.</p> <pre><code>#Imports from bs4 import BeautifulSoup from urllib import urlopen import time #Required Fie...
-1
2016-07-20T18:12:36Z
38,488,149
<p>to print to text file</p> <pre><code>from bs4 import BeautifulSoup from urllib import urlopen import time #Required Fields pageCount = 1287528 fp = open ("logs.txt","w") #Loop while(pageCount&gt;0): time.sleep(1) html = urlopen('https://www.csgocrash.com/game/1/%s' %(pageCount)).read() soup = Beautifu...
0
2016-07-20T18:27:07Z
[ "python", "file", "text", "append" ]
Python - Using a loop to write a new line into a text file
38,487,896
<p>I want to add onto this program to save each crashPoint to a text file, with a new crash point being added onto a new line. I've attempted to do it from past work, but I can't seem to get it to work together.</p> <pre><code>#Imports from bs4 import BeautifulSoup from urllib import urlopen import time #Required Fie...
-1
2016-07-20T18:12:36Z
38,488,150
<p>Doing this is pretty straightforward if you just open the output file in append mode:</p> <pre><code>#Loop logFile = open("logFile.txt", "a") while(pageCount&gt;0): time.sleep(1) html = urlopen('https://www.csgocrash.com/game/1/%s' % (pageCount)).read() soup = BeautifulSoup(html, "html.parser") tr...
0
2016-07-20T18:27:10Z
[ "python", "file", "text", "append" ]
Python - Using a loop to write a new line into a text file
38,487,896
<p>I want to add onto this program to save each crashPoint to a text file, with a new crash point being added onto a new line. I've attempted to do it from past work, but I can't seem to get it to work together.</p> <pre><code>#Imports from bs4 import BeautifulSoup from urllib import urlopen import time #Required Fie...
-1
2016-07-20T18:12:36Z
38,488,172
<p>Write the data into the file by opening it in append mode. If you are iterating through the file loop, just open the file once and keep writing the new data.</p> <pre><code>with open("test.txt", "a") as myfile: myfile.write(crashPoint[0:-1]) </code></pre> <p><a href="http://stackoverflow.com/questions/4706499/...
0
2016-07-20T18:28:16Z
[ "python", "file", "text", "append" ]
How to put an opencv function to play videos in django views?
38,487,913
<p>I have some python code that uses opencv to play a video from a certain path and I've been reading about how to incorporate that python code with Django and I saw that the python code can be put into the django views.py file but my question is what am I supposed to put as a parameter for the piece of code that rende...
0
2016-07-20T18:13:51Z
38,489,209
<p>Quick answer: Don't bother with templates and <code>render()</code>, just use an <a href="https://docs.djangoproject.com/en/1.9/ref/request-response/#django.http.HttpResponse" rel="nofollow"><code>HttpResponse</code></a>. The video will play, then the response will be returned so it all works out in the end.</p> <p...
0
2016-07-20T19:25:58Z
[ "python", "html", "django", "opencv" ]
How to print a df in Terminal without loosing format?
38,487,945
<p>How can I print a df in the Terminal without loosing the format?</p> <p>Lets say I have a df like this:</p> <pre><code>In: df Out: TFs No Esenciales Genes regulados Genes Regulados Positivamente Genes Regulados Negativamente No Tentativo de genes a silenciar No Real de genes a silenciar No Tentativo de ...
1
2016-07-20T18:15:16Z
38,488,768
<p>There are display <a href="http://pandas.pydata.org/pandas-docs/stable/options.html" rel="nofollow">options</a> that can be used to control how the <code>DataFrame</code> will be printed. You probably want:</p> <pre><code>In [28]: pd.set_option('expand_frame_repr', False) In [29]: pd.set_option('display.max_colum...
1
2016-07-20T19:00:46Z
[ "python", "shell", "pandas", "printing", "dataframe" ]
How to print a df in Terminal without loosing format?
38,487,945
<p>How can I print a df in the Terminal without loosing the format?</p> <p>Lets say I have a df like this:</p> <pre><code>In: df Out: TFs No Esenciales Genes regulados Genes Regulados Positivamente Genes Regulados Negativamente No Tentativo de genes a silenciar No Real de genes a silenciar No Tentativo de ...
1
2016-07-20T18:15:16Z
38,489,412
<p><a href="http://pandas.pydata.org/pandas-docs/stable/options.html" rel="nofollow">DOCUMENTATION</a></p> <p>There are 2 things going on that control for the formatting you may see.</p> <ol> <li><p>Controlling for the the character width that the display can handle.</p> <ul> <li>This is handled with the pandas opti...
2
2016-07-20T19:38:12Z
[ "python", "shell", "pandas", "printing", "dataframe" ]
Target KeyboardInterrupt to subprocess
38,487,972
<p>I wish to launch a rather long-running subprocess in Python, and would like to be able to terminate it with <code>^C</code>. However, pressing <code>^C</code> leads to the parent receiving <code>KeyboardInterrupt</code> and terminating (and sometimes leaves <code>sleep</code> as a defunct process).</p> <pre><code>i...
0
2016-07-20T18:16:36Z
38,488,062
<p>Use <code>signal</code> to catch SIGINT, and make the signal handler terminate the subprocess.</p> <p>Look at this for more information (if it's for Python 2.x):</p> <p><a href="https://docs.python.org/2/library/signal.html" rel="nofollow">https://docs.python.org/2/library/signal.html</a></p>
1
2016-07-20T18:22:26Z
[ "python", "subprocess" ]
Target KeyboardInterrupt to subprocess
38,487,972
<p>I wish to launch a rather long-running subprocess in Python, and would like to be able to terminate it with <code>^C</code>. However, pressing <code>^C</code> leads to the parent receiving <code>KeyboardInterrupt</code> and terminating (and sometimes leaves <code>sleep</code> as a defunct process).</p> <pre><code>i...
0
2016-07-20T18:16:36Z
38,488,100
<p>Not sure if it's a workaround but it works fine (at least on Windows which handles CTRL+C differently)</p> <pre><code>import subprocess try: subprocess.call(r"C:\msys64\usr\bin\sleep 100".split()) except KeyboardInterrupt: print("** BREAK **") print("continuing the python program") </code></pre> <p>executi...
0
2016-07-20T18:24:33Z
[ "python", "subprocess" ]
Target KeyboardInterrupt to subprocess
38,487,972
<p>I wish to launch a rather long-running subprocess in Python, and would like to be able to terminate it with <code>^C</code>. However, pressing <code>^C</code> leads to the parent receiving <code>KeyboardInterrupt</code> and terminating (and sometimes leaves <code>sleep</code> as a defunct process).</p> <pre><code>i...
0
2016-07-20T18:16:36Z
38,521,390
<p>As suggested by Jacob, one way (thanks to a colleague) to do is to handle SIGNAL and pass it on to the child. So a wrapper like this would be:</p> <pre><code>import signal import subprocess def run_cmd(cmd, **kwargs): try: p = None # Register handler to pass keyboard interrupt to the subproces...
0
2016-07-22T08:10:57Z
[ "python", "subprocess" ]
Append item to every list in list of list
38,488,034
<p>I am looking to append item to every list in a list of list.</p> <p>I had expected the following code to work:</p> <pre><code>start_list = [["a", "b"], ["c", "d"]] end_list = [item.append("test") for item in start_list] </code></pre> <p>with expected output <code>[["a", "b", "test"], ["c", "d", "test"]]</code></...
1
2016-07-20T18:20:42Z
38,488,060
<p><a href="https://docs.python.org/3/tutorial/datastructures.html#more-on-lists" rel="nofollow"><code>append</code></a> modifies the list and returns None.</p> <p>If you want to generate a new list:</p> <pre><code>end_list = [item + ["test"] for item in start_list] </code></pre> <p>If you want to modify the old lis...
6
2016-07-20T18:22:24Z
[ "python", "python-3.x" ]
add PyQt5 to `install_require`
38,488,063
<p>Here is a part of my code: (<strong>setup.py</strong>)</p> <pre><code>args = { 'name' : 'ModernGL.PyQt5', 'version' : Version, 'description' : ShortDescription, 'long_description' : LongDescription, 'url' : 'https://github.com/cprogrammer1994/ModernGL.PyQt5', 'download_url' : 'https://github...
1
2016-07-20T18:22:33Z
38,488,261
<p>Distributions for <code>PyQt5</code> aren't on PyPi. You would have the same problem with any other python library that doesn't use the python distribution tools. The <code>PyQt5</code> project doesn't have a <code>setup.py</code> installer. <code>Qt</code> and <code>PyQt</code> are generally installed via OS pac...
1
2016-07-20T18:32:16Z
[ "python", "python-3.x", "pip" ]
scikit-learn's LabelEncoder() memory issue
38,488,120
<p>I have a <code>train</code> pandas df with 20 million rows and a <code>test</code> pandas df with around 10 million rows.</p> <p>There are columns in both of the df's that I want to apply LabelEncoder() to, but I keep getting a <code>Memory Error</code> on my laptop and even on a 64 gig RAM AWS instance.</p> <p>Is...
0
2016-07-20T18:25:24Z
38,488,881
<p>I have not used LabelEncoder before, but from my work with Sklearn, I know that there are options that can help parallelize. Have you tried looking into parallelizing this task? Either using a parameter like n_jobs which many sklearn classifiers have, or even the python multiprocessing library.</p>
1
2016-07-20T19:05:58Z
[ "python", "pandas", "scikit-learn" ]
Get the Flask view function that matches a url
38,488,134
<p>I have some url paths and want to check if they point to a url rule in my Flask app. How can I check this using Flask?</p> <pre><code>from flask import Flask, json, request, Response app = Flask('simple_app') @app.route('/foo/&lt;bar_id&gt;', methods=['GET']) def foo_bar_id(bar_id): if request.method == 'GET...
1
2016-07-20T18:26:06Z
38,488,506
<p><a href="http://flask.pocoo.org/docs/0.11/api/#flask.Flask.url_map" rel="nofollow"><code>app.url_map</code></a> stores the object that maps and matches rules with endpoints. <a href="http://flask.pocoo.org/docs/0.11/api/#flask.Flask.view_functions" rel="nofollow"><code>app.view_functions</code></a> maps endpoints t...
3
2016-07-20T18:46:52Z
[ "python", "flask", "werkzeug" ]
Python reading a file into unicode strings
38,488,186
<p>I am having some troubles with understanding the correct way to handle unicode strings in Python. I have read many questions about it but it is still unclear what should I do to avoid problems when reading and writing files.</p> <p>My goal is to read some huge (up to 7GB) files efficiently line by line. I was doing...
0
2016-07-20T18:29:04Z
38,488,278
<p>Your data is probably <em>not</em> UTF-8 encoded. Figure out the correct encoding and use that instead. We can't tell you what codec is right, because we can't see your data.</p> <p>If you must specify an error handler, you may as well do so when opening the file. Use the <a href="https://docs.python.org/2/library/...
2
2016-07-20T18:33:29Z
[ "python", "string", "file", "unicode" ]
How do I create a Python Decimal object from C++?
38,488,205
<p>...or any Python object that exists in an importable library. I have found PyDateTime_* functions in the <a href="https://docs.python.org/3/c-api/datetime.html" rel="nofollow">documentation</a> for creating objects from the datetime module, but I can't find anything to do with the python decimal module. Is this poss...
1
2016-07-20T18:29:50Z
38,489,304
<p>Should be straightforward enough. Although untested, something like the following should work:</p> <pre><code>PyObject * decimal_mod = PyImport_ImportModule("decimal"); assert(decimal_mod); PyObject * decimal_ctor = PyObject_GetAttrString(decimal_mod, "Decimal"); assert(decimal_ctor); PyObject * four = PyObject_Ca...
1
2016-07-20T19:31:40Z
[ "python", "c++", "c", "boost-python" ]
How do I create a Python Decimal object from C++?
38,488,205
<p>...or any Python object that exists in an importable library. I have found PyDateTime_* functions in the <a href="https://docs.python.org/3/c-api/datetime.html" rel="nofollow">documentation</a> for creating objects from the datetime module, but I can't find anything to do with the python decimal module. Is this poss...
1
2016-07-20T18:29:50Z
38,489,597
<p>In Boost.Python that would be something like</p> <pre><code>bp::object decimal = bp::import("decimal").attr("Decimal"); bp::object decimal_obj = decimal(1, 4); </code></pre>
1
2016-07-20T19:49:01Z
[ "python", "c++", "c", "boost-python" ]
How to iterate through a column in dataframe and update two new columns simultaneously?
38,488,207
<p>I understand I can add a column to a dataframe and update its values to the values returned from a function, like this:</p> <pre><code>df=pd.DataFrame({'x':[1,2,3,4]}) def square(x): return x*x df['x_squared'] = [square(i) for i in df['x']] </code></pre> <p>However, I am facing a problem that the actual func...
3
2016-07-20T18:29:53Z
38,488,253
<p>You could do in a vectorized fashion, like so -</p> <pre><code>df['x_squared'], df['x_cubed'] = df.x**2,df.x**3 </code></pre> <p>Or with that custom function, like so -</p> <pre><code>df['x_squared'], df['x_cubed'] = squareAndCube(df.x) </code></pre> <hr> <p>Back to your loopy case, on the right side of the ass...
3
2016-07-20T18:31:43Z
[ "python", "numpy", "pandas", "dataframe", "multiple-columns" ]
How to iterate through a column in dataframe and update two new columns simultaneously?
38,488,207
<p>I understand I can add a column to a dataframe and update its values to the values returned from a function, like this:</p> <pre><code>df=pd.DataFrame({'x':[1,2,3,4]}) def square(x): return x*x df['x_squared'] = [square(i) for i in df['x']] </code></pre> <p>However, I am facing a problem that the actual func...
3
2016-07-20T18:29:53Z
38,489,117
<p>How about using <code>df.loc</code> like this:</p> <pre><code>df=pd.DataFrame({'x':[1,2,3,4]}) def square(x): return x*x df['x_squared'] = df['x_cubed'] = None df.loc[:, ['x_squared', 'x_cubed']] = [squareAndCube(i) for i in df['x']] </code></pre> <p>gives</p> <pre><code> x x_squared x_cubed 0 1 ...
0
2016-07-20T19:20:27Z
[ "python", "numpy", "pandas", "dataframe", "multiple-columns" ]
How to iterate through a column in dataframe and update two new columns simultaneously?
38,488,207
<p>I understand I can add a column to a dataframe and update its values to the values returned from a function, like this:</p> <pre><code>df=pd.DataFrame({'x':[1,2,3,4]}) def square(x): return x*x df['x_squared'] = [square(i) for i in df['x']] </code></pre> <p>However, I am facing a problem that the actual func...
3
2016-07-20T18:29:53Z
38,490,191
<p>This works for positive numbers. Thinking how to generalize but the brevity of this solution has me distracted.</p> <pre><code>df = pd.DataFrame(range(1, 10)) a = np.arange(1, 4).reshape(1, -1) np.exp(np.log(df).dot(a)) </code></pre> <p><a href="http://i.stack.imgur.com/EIB3C.png" rel="nofollow"><img src="http:/...
1
2016-07-20T20:23:14Z
[ "python", "numpy", "pandas", "dataframe", "multiple-columns" ]
Twitter dataset filtering for only English language text using Python
38,488,387
<p>Is there a way to filter already processed dataset for only English language text using Python? Maybe some NLTK features or something like that. The data was extracted from Twitter, and it's format is the following:</p> <pre><code>&lt;tweetid&gt;, &lt;username&gt;, &lt;userid&gt; &amp;8888 &lt;tweet text&gt; </code...
1
2016-07-20T18:40:13Z
38,488,743
<p>What you need is the language detection module.</p> <pre><code>from textblob import TextBlob textBlob('your tweet').detect_language() </code></pre>
1
2016-07-20T18:59:28Z
[ "python", "twitter", "nlp", "text-mining", "tweets" ]
How, with Python / the NLTK / Wordnet, can avoid a nondescript error message?
38,488,431
<p>I am periodically getting <code>AttributeError: 'Synset' object has no attribute 'lower'</code>. My code, all in one file, is generating the error:</p> <pre><code>Synset('book.n.01') [Synset('book.n.01')] Traceback (most recent call last): File "./map", line 124, in &lt;module&gt; print print_nodes(word) Fi...
1
2016-07-20T18:42:44Z
38,490,777
<p>I'm not sure what your code really looks like or what you are trying to do, but the nltk <a href="http://www.nltk.org/howto/wordnet.html" rel="nofollow">wordnet howto</a> shows how to create a synset if you already know its identifier:</p> <pre><code>&gt;&gt;&gt; from nltk.corpus.reader import wordnet as wn &gt;&gt...
3
2016-07-20T21:01:04Z
[ "python", "nltk", "wordnet" ]
Does appending a list slice back to the original list just copy the addresses?
38,488,464
<p>If I have a list of objects as such in Python:</p> <pre><code>li = [obj1, obj2, obj3, ob4, obj5] </code></pre> <p>And I append the last two objects to the end of the list again:</p> <pre><code>li.extend(li[-2:]) </code></pre> <p>Do duplicates in <code>li</code> now have the same or different addresses? If I make...
1
2016-07-20T18:44:48Z
38,488,567
<p>The same addresses - you can check this with <a href="https://docs.python.org/3/library/functions.html#id" rel="nofollow"><code>id</code></a>. If the elements of the list are mutable, then modifying one will modify the other. If the elements of the list are immutable, then you cannot modify them.</p> <pre><code>li ...
3
2016-07-20T18:50:16Z
[ "python", "list", "copy" ]
Does appending a list slice back to the original list just copy the addresses?
38,488,464
<p>If I have a list of objects as such in Python:</p> <pre><code>li = [obj1, obj2, obj3, ob4, obj5] </code></pre> <p>And I append the last two objects to the end of the list again:</p> <pre><code>li.extend(li[-2:]) </code></pre> <p>Do duplicates in <code>li</code> now have the same or different addresses? If I make...
1
2016-07-20T18:44:48Z
38,488,721
<p>Yes, python will <em>reference</em> the same object in memory if you use the <code>extend()</code> method in this way, if this is your desired outcome, then simply execute:</p> <pre><code>li.extend(li[-2:]) </code></pre> <p>Example:</p> <pre><code>a = object() b = object() c = object() d = object() # Alternativel...
2
2016-07-20T18:58:13Z
[ "python", "list", "copy" ]
Cubic Interpolation doesn't show, but linear does?
38,488,471
<p>So I made a few data points and I plotted them. Then, I wanted to interpolate and plot its cubic function. However, when I plotted, only 3 of the functions showed up. How do I make it so all functions show? Additionally, when I plotted the interpolated linear function, all lines showed up nicely.</p> <pre><code>xne...
0
2016-07-20T18:45:17Z
38,490,746
<p>In the end, I realized that some points of data were math.nan. They didn't allow interpolation. </p> <p>I had to take my main file and cut it into different separate files where the redshift bin would match my mass bin. Hence, I took away math.nan and I could do the interpolation.</p> <p>My solution is a pretty du...
1
2016-07-20T20:59:36Z
[ "python", "matlab", "plot", "scipy", "interpolation" ]
A DRY approach to Python try-except blocks?
38,488,476
<p><strong>Objective:</strong> I have several lines of code each capable of producing the same type of error, and warranting the same kind of response. How do I prevent a 'do not repeat yourself' problem with the try-except blocks.</p> <p><strong>Background:</strong></p> <p>I using ReGex to scrape poorly formatted da...
0
2016-07-20T18:45:32Z
38,488,523
<p>You can have any number of <code>except</code> blocks over and over, handling different kinds of exceptions. There's also nothing wrong with having multiple statements in the same try/catch block.</p> <pre><code>try: doMyDangerousThing() except ValueError: print "ValueError!" except HurrDurrError: print...
0
2016-07-20T18:47:57Z
[ "python", "python-2.7", "try-except" ]
A DRY approach to Python try-except blocks?
38,488,476
<p><strong>Objective:</strong> I have several lines of code each capable of producing the same type of error, and warranting the same kind of response. How do I prevent a 'do not repeat yourself' problem with the try-except blocks.</p> <p><strong>Background:</strong></p> <p>I using ReGex to scrape poorly formatted da...
0
2016-07-20T18:45:32Z
38,488,581
<p>What about refactoring a function out of it?</p> <pre><code>def maybe_find_field(name, datum): try: return find_field(name, datum)[0] except IndexError: # Example of specific exception to catch return '' sample.thickness = maybe_find_field('Thickness', sample_datum) sample.max_tension = may...
5
2016-07-20T18:50:44Z
[ "python", "python-2.7", "try-except" ]
A DRY approach to Python try-except blocks?
38,488,476
<p><strong>Objective:</strong> I have several lines of code each capable of producing the same type of error, and warranting the same kind of response. How do I prevent a 'do not repeat yourself' problem with the try-except blocks.</p> <p><strong>Background:</strong></p> <p>I using ReGex to scrape poorly formatted da...
0
2016-07-20T18:45:32Z
38,488,626
<p>When you find yourself repeating code, encapsulate it in a function. In this case, create a function that handles the exception for you.</p> <pre><code>def try_find_field(field_name, datum, default_value): try: return find_field(field_name, datum)[0] except: return default_value </code></pr...
1
2016-07-20T18:53:18Z
[ "python", "python-2.7", "try-except" ]
matplotlib not showing graph
38,488,532
<p>I have written this code to show a line graph but the plot is not showing up. The window opens and shows the labels and axis but no plot. I'm not sure what I'm doing wrong. Maybe it's a small mistake that I'm overlooking</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt import s...
0
2016-07-20T18:48:20Z
38,503,064
<p>Your upper y axis limit is 0.08 but your y values are in the range of 9-19.</p>
0
2016-07-21T11:28:34Z
[ "python", "matplotlib", "seaborn" ]
How can I share a logger across a large application?
38,488,659
<p>I have an application that consists of many distinct modules, yet everything is still part of a single application. How can I properly share a logger, so that everything writes to the same file. Do I need to pass a logger around? I'd prefer not to have to do this.</p> <p>Example project layout:</p> <pre><code>/ ...
0
2016-07-20T18:54:59Z
38,489,297
<p>I think the point that you are missing is that by default, Python loggers are hierarchical. In your main application you simply create a logger with a fixed name (you can use the name of the main script). For example:</p> <pre><code>mainapp.py: import logging root_logger = logging.getLogger(appname()) # do any lo...
2
2016-07-20T19:31:27Z
[ "python", "logging" ]
When does mutability of python class objects affect assignments?
38,488,695
<p>My understanding of python's mutable feature for classes/objects is that if you make an assignment then any change to the original changes the assigned variable/object as well. I confused about this <a href="https://codesays.com/2014/solution-to-flatten-binary-tree-to-linked-list-by-leetcode/" rel="nofollow">piece o...
0
2016-07-20T18:56:59Z
38,489,121
<p>Assignment in Python <em>always works the same way.</em> It changes the thing on the left side of the <code>=</code> sign to refer to the value of the expression on the right side. There is <em>absolutely nothing whatsoever</em> "different in the implementation" as you ask in a comment.</p> <p>Sometimes the item on...
2
2016-07-20T19:20:49Z
[ "python", "class", "object", "mutable" ]
jira-python hanging on request on Windows without any kind of failure or notification
38,488,710
<p>My script returns changelog history for <code>JIRA</code> tickets, and it seems to work fine on my dev machine (Mac Pro). It hung a few times when I tried to implement async to pull the requests faster, but with a single threaded process it works every time. </p> <p>When I deployed on our Windows production serve...
0
2016-07-20T18:57:34Z
38,489,179
<p>I'd suggest a single worker to see if that works better</p>
0
2016-07-20T19:24:34Z
[ "python", "jira", "jira-rest-api" ]
Calculator - Power Button
38,488,767
<p>I have been trying to code a calculator with tkinter, and so far I have made all the four basic operations, addition, subtraction, multiplication, and division. I've also made a clear button and buttons for all numbers. Now I want to make a "power" button and I don't know how. When I put it in the calculator the ans...
0
2016-07-20T19:00:44Z
38,488,820
<p><code>^</code> is xor, use <code>**</code> instead to raise a number to a power in Python.</p> <p>Replacing the final <code>^</code> with <code>**</code> in <code>power = Button(evenmore, padx = 16, pady = 16, bd = 8, text = '^', command = lambda:set_text('^'))</code> will give you the correct result, but it will d...
2
2016-07-20T19:03:22Z
[ "python", "python-3.x", "tkinter", "calculator" ]
Import Variable from Python FilePath
38,488,789
<p>I'm writing a clean up script from one of our applications and I need a few variables from a python file in a separate directory.</p> <p>Now normally I would go:</p> <pre><code>from myfile import myvariable print myvariable </code></pre> <p>However this doesn't work for files outside of the directory. I'd like a ...
3
2016-07-20T19:01:40Z
38,498,502
<p>You can do a more targeted import using the <a href="https://docs.python.org/2/library/imp.html" rel="nofollow">imp</a> module. While it has a few functions, I found the only one that allowed me access to internal variables was <code>load_source</code>.</p> <pre><code>import imp import os filename = 'variables_fil...
2
2016-07-21T08:08:17Z
[ "python", "python-2.7", "python-import" ]
Interactive Python - solutions for relative imports
38,488,860
<p>From <a href="http://stackoverflow.com/questions/14132789/python-relative-imports-for-the-billionth-time">Python relative imports for the billionth time</a>:</p> <ul> <li>For a <code>from .. import</code> to work, the module's name must have at least as many dots as there are in the <code>import</code> statement.</...
0
2016-07-20T19:04:57Z
38,488,861
<p>The solution I currently use is to append the parent package to <code>sys.path</code>.</p> <pre><code>import sys sys.path.append("/Users/.../package/") import subpackage1.moduleX import subpackage2.moduleZ </code></pre>
1
2016-07-20T19:04:57Z
[ "python", "python-2.7", "ipython", "ipython-notebook", "jupyter-notebook" ]
Python OrderedDict to CSV: Eliminating Blank Lines
38,488,923
<p>When I run this code...</p> <pre><code>from simple_salesforce import Salesforce sf = Salesforce(username='un', password='pw', security_token='tk') cons = sf.query_all("SELECT Id, Name FROM Contact WHERE IsDeleted=false LIMIT 2") import csv with open('c:\test.csv', 'w') as csvfile: fieldnames = ['contact_name_...
0
2016-07-20T19:08:22Z
38,489,188
<p>Two likely possibilities: the output file needs to be opened in binary mode and/or the writer needs to be told not to use DOS style line endings.</p> <p>To open the file in binary mode in Python 3 replace your current <code>with open</code> line with:</p> <pre><code>with open('c:\test.csv', 'w', newline='') as csv...
1
2016-07-20T19:25:05Z
[ "python", "csv", "line-breaks", "ordereddictionary" ]
Python: Copy files between two remote servers
38,488,957
<p>I want to understand the best way to copy files from one remote server to another remote server using python.</p> <p>My setup looks something like this:</p> <pre><code>+--------------+ | Server A | +--------------+ ...
1
2016-07-20T19:10:43Z
38,489,057
<p><strike>I would use <code>rsync</code> to handle this problem.</strike> You might be able to just directly call <code>scp</code> from Python using the <code>subprocess</code> module or try an existing Python module that wraps or implements <code>rsync</code></p> <p>It will be much easier to call <code>scp</code> vi...
1
2016-07-20T19:17:08Z
[ "python", "python-2.7", "paramiko" ]
how can i restore the backup.py plugin data of errbot running in a docker container
38,488,977
<p>I'm running errbot in a docker container, we did the !backup and we have the backup.py, but when i start the docker container it just run /app/venv/bin/run.sh but i cannot pass -r /srv/backup.py to have all my data restored.</p> <p>any ideas?</p> <p>all the data is safe since the /srv is a mounted volume</p>
2
2016-07-20T19:12:19Z
38,557,886
<p>I think the best if you run Errbot in a container is to run it with a real database for the persistence (redis for example).</p> <p>Then you can simply run <code>backup.py</code> from anywhere (including your dev machine).</p> <p>Even better, you can just do a backup of your redis directly.</p>
1
2016-07-24T23:31:20Z
[ "python", "docker", "errbot" ]
unpack two columns of lists with corresponding elements
38,489,060
<p>I have the following data frame:</p> <pre><code>df = pd.DataFrame({'A' : [['on', 'ne', 'on'], ['tw'], ['th', 'hr', 'ree'], []], 'B' : ['one', 'two', 'three','four'], 'C' : [0.2,0.6,-1.4,0.7], 'D' : [[0.2,0.3,-1.2],[0.5], ...
0
2016-07-20T19:17:22Z
38,489,592
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html" rel="nofollow"><code>join</code></a>:</p> <pre><code>#DataFrame from Series, remove level 1 df1 = pd.DataFrame({'A':df.A.apply(pd.Series).stack(), 'D':df.D.apply(pd.Series).stack()}).reset_ind...
0
2016-07-20T19:48:50Z
[ "python", "python-2.7", "pandas" ]
Return a dict in a function, then print its contents in another function
38,489,075
<p>I have a function (items) that returns a dict (details_dict) and would like to print out this dict in another function (contents). </p> <p>The contents of details_dict after the for loop are to be:</p> <pre><code>details_dict = { 'car' : 'fast', 'bike' : 'faster', 'train' : 'slow' } </code></pre> <p>Here are the...
-2
2016-07-20T19:18:13Z
38,489,975
<p>There's a missing parenthesis in your print statement and possible indentation issues. Here's a modified version of what you're doing, ignoring the details of how the dict is built:</p> <pre><code>def buildItems(): return { 'car': 'fast', 'bike': 'faster', 'train': 'slow' } def cont...
0
2016-07-20T20:11:10Z
[ "python" ]
Return a dict in a function, then print its contents in another function
38,489,075
<p>I have a function (items) that returns a dict (details_dict) and would like to print out this dict in another function (contents). </p> <p>The contents of details_dict after the for loop are to be:</p> <pre><code>details_dict = { 'car' : 'fast', 'bike' : 'faster', 'train' : 'slow' } </code></pre> <p>Here are the...
-2
2016-07-20T19:18:13Z
38,490,106
<p>Without knowing the structure of your data I have made a best guess.</p> <pre><code>list_a = ['car', 'bike', 'train'] list_b = ['fast', 'faster', 'slow'] def items (one, two): the_dict = {} for (i,j) in zip(one, two): the_dict[i] = j return the_dict def contents(a_dict): for key in a_dict:...
0
2016-07-20T20:18:14Z
[ "python" ]
Write Avro in ruby and read in Python
38,489,137
<p>I'm facing issues trying to decode Avro bytes written in Ruby to a Kafka topic. On eyeballing the avro byte string I can see that it looks fine. But when I try to decode, I get a 'UnicodeDecodeError: 'utf8' codec can't decode byte 0x98 in position 32: invalid start byte'. </p> <pre><code>import avro.schema import a...
1
2016-07-20T19:22:14Z
38,490,778
<p>Modifying the code this way solved the problem</p> <pre><code>bytes_reader = io.BytesIO(msg.value) reader = DataFileReader(bytes_reader, DatumReader()) for r in reader: print r </code></pre>
0
2016-07-20T21:01:19Z
[ "python", "ruby", "avro" ]
Idiomatic way to combine strings via list comprehension
38,489,151
<p>Can you suggest a better way to combine strings from lists?</p> <p>Here is an example:</p> <pre><code>[ 'prefix-' + a + '-' + b for a in [ '1', '2' ] for b in [ 'a', 'b' ] ] </code></pre> <p>which results in: </p> <pre><code>['prefix-1-a', 'prefix-1-b', 'prefix-2-a', 'prefix-2-b'] </code></pre> <hr> <p>The ac...
0
2016-07-20T19:23:02Z
38,489,234
<p>How about with <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow"><code>str.join</code></a>.</p> <pre><code>['-'.join(('prefix', a, b)) for a, b in zip('12', 'ab')] </code></pre> <p>As others mentioned, you should use <a href="https://docs.python.org/3/library/os.path.html#os.path.jo...
1
2016-07-20T19:27:45Z
[ "python", "list-comprehension", "idiomatic" ]
Idiomatic way to combine strings via list comprehension
38,489,151
<p>Can you suggest a better way to combine strings from lists?</p> <p>Here is an example:</p> <pre><code>[ 'prefix-' + a + '-' + b for a in [ '1', '2' ] for b in [ 'a', 'b' ] ] </code></pre> <p>which results in: </p> <pre><code>['prefix-1-a', 'prefix-1-b', 'prefix-2-a', 'prefix-2-b'] </code></pre> <hr> <p>The ac...
0
2016-07-20T19:23:02Z
38,489,251
<p>First one: <code>['prefix-%s-%s' % (a,b) for a in [1, 2] for b in 'ab']</code></p> <p>The second one could be the same way but you may want to use <code>os.path.join</code> to normalize for Windows:</p> <pre><code>[os.path.join('home', dir_, file_) for dir_ in ['dir1', 'dir2'] for file_ in ['file1', 'file2']] </co...
0
2016-07-20T19:28:52Z
[ "python", "list-comprehension", "idiomatic" ]
Idiomatic way to combine strings via list comprehension
38,489,151
<p>Can you suggest a better way to combine strings from lists?</p> <p>Here is an example:</p> <pre><code>[ 'prefix-' + a + '-' + b for a in [ '1', '2' ] for b in [ 'a', 'b' ] ] </code></pre> <p>which results in: </p> <pre><code>['prefix-1-a', 'prefix-1-b', 'prefix-2-a', 'prefix-2-b'] </code></pre> <hr> <p>The ac...
0
2016-07-20T19:23:02Z
38,489,260
<p>You can use list comprehension, <code>os.path.join</code> function and <code>itertools</code> module:</p> <pre><code>[os.path.join('home', a, b) for a, b in itertools.product(ddirs, files)] </code></pre>
3
2016-07-20T19:29:25Z
[ "python", "list-comprehension", "idiomatic" ]
Idiomatic way to combine strings via list comprehension
38,489,151
<p>Can you suggest a better way to combine strings from lists?</p> <p>Here is an example:</p> <pre><code>[ 'prefix-' + a + '-' + b for a in [ '1', '2' ] for b in [ 'a', 'b' ] ] </code></pre> <p>which results in: </p> <pre><code>['prefix-1-a', 'prefix-1-b', 'prefix-2-a', 'prefix-2-b'] </code></pre> <hr> <p>The ac...
0
2016-07-20T19:23:02Z
38,489,263
<p>You could use cartesian product for lists.</p> <pre><code>import itertools for element in itertools.product(["1", "2"], ["a", "b"]): print element # Gives ('1', 'a') ('1', 'b') ('2', 'a') ('2', 'b') </code></pre> <p>Then join them however you want.</p>
1
2016-07-20T19:29:38Z
[ "python", "list-comprehension", "idiomatic" ]
Idiomatic way to combine strings via list comprehension
38,489,151
<p>Can you suggest a better way to combine strings from lists?</p> <p>Here is an example:</p> <pre><code>[ 'prefix-' + a + '-' + b for a in [ '1', '2' ] for b in [ 'a', 'b' ] ] </code></pre> <p>which results in: </p> <pre><code>['prefix-1-a', 'prefix-1-b', 'prefix-2-a', 'prefix-2-b'] </code></pre> <hr> <p>The ac...
0
2016-07-20T19:23:02Z
38,489,270
<p>For working specifically with file paths, use <code>os.path.join</code>:</p> <pre><code>dirs = ['dir1', 'dir2'] files = ['file1', 'file2'] [os.path.join('home', d, f) for d in dirs for f in files] </code></pre>
3
2016-07-20T19:29:47Z
[ "python", "list-comprehension", "idiomatic" ]
unconverted data remains python strptime
38,489,160
<p>I am trying to convert strings to datetime in python, but I am getting an error "unconverted data remains: 11". The strings I am dealing with have a form like "Dec\xa031 2011". I think the unicode character is causing a problem. I have tried splitting on \xa0 which gives me ['Dec', '31 2011'], then joining. I have a...
0
2016-07-20T19:23:34Z
38,489,252
<p>That works for your example:</p> <pre><code>import datetime s = "Dec\xa031 2011" datetime.datetime.strptime(s, "%b\xa0%d %Y") </code></pre> <p>Outputs:</p> <pre><code>datetime.datetime(2011, 12, 31, 0, 0) </code></pre>
1
2016-07-20T19:28:53Z
[ "python", "datetime" ]
Python requests. 403 Forbidden
38,489,386
<p>I'm need to parse a <a href="http://worldagnetwork.com/" rel="nofollow">site</a>, but i got an error 403 Forbidden. Here is a code:</p> <pre><code>url = 'http://worldagnetwork.com/' result = requests.get(url) print(result.content.decode()) </code></pre> <p>It's out:</p> <pre><code>&lt;html&gt; &lt;head&gt;&lt;tit...
0
2016-07-20T19:36:46Z
38,489,588
<p>It seems the page rejects <code>GET</code> requests that do not identify a <code>User-Agent</code>. I visited the page with a browser (Chrome) and copied the <code>User-Agent</code> header of the <code>GET</code> request (look in the Network tab of the developer tools):</p> <pre><code>import requests url = 'http://...
2
2016-07-20T19:48:31Z
[ "python", "python-requests" ]
IOError with Python write but the directory exists
38,489,418
<p>I'm trying to open and write to a file which may or may not exist. I'm have Windows 7 and am using Python. I'm getting an IOError because the file was not found. Here is my code to save my file:</p> <pre><code>dirBool = os.path.exists(saveDir) print dirBool if not dirBool: os.mkdir(saveDir) if saveDir == os.pa...
0
2016-07-20T19:38:33Z
38,490,591
<p>When using network drives with Windows, the drive has to be mapped to a drive letter. This can be done by right clicking My Computer > Map Network Drive. After that, use the mapped drive letter in the path to <code>open()</code>. </p>
0
2016-07-20T20:49:38Z
[ "python", "path", "save", "ioerror" ]
Run function in separate folder
38,489,589
<p>In my project folder I have two directories: <code>classes</code> and <code>fonts</code>.<br> The <code>fonts</code> directory contains my game's fonts' .ttf and related files (like special letter properties and widths). For example my <code>item</code> font has an associated <code>item.ttf</code> file and an <code>...
0
2016-07-20T19:48:45Z
38,493,301
<p>Following what Mad Physicist said, editing <code>sys.path</code> to include the project directory works fine, like so:</p> <pre><code>import sys sys.path.append('C:\\Path\\to\\Project\\') import fonts </code></pre> <p>Same code works for modules anywhere else by adding their respective paths as well.</p> <p>Answe...
0
2016-07-21T01:12:47Z
[ "python" ]
recursive relations django queires
38,489,593
<p>I created a many to many recursive relationship in Django. How do you query the recursive field subfolder in the code below. That is given a folder list all its subfolder?</p> <pre><code>class Folder(models.Model): """Folder Model, can contain many folders and many files""" name = models.CharField(max_length=6...
0
2016-07-20T19:48:51Z
38,489,701
<p>A <em>self-referencing</em> many-to-many field works the same way as a conventional one. Given a <code>folder</code> you can access all subfolders with:</p> <pre><code>sub_folders = folder.subfolders.all() </code></pre>
0
2016-07-20T19:55:03Z
[ "python", "django", "django-models" ]
How to pack/unpack tuples and list with use msgpack (generic solution for any object)?
38,489,617
<p>Here is some problem with pack/unpack tuples. As I know msgpack not distinguish between list and tuple and there is not hook to force list or tuple be ExtType. It generates frustrating problems.</p> <p>Assume that I want do generic solution for all types of objects not only for Period - it is simple to assume that ...
1
2016-07-20T19:50:02Z
38,825,561
<p>For your objects, you would have to write hooks for <code>dict</code> as well, this is because your keys <code>Period((2016,7))</code> etc are hashable ( being a tuple ) in the original object, get converted to list which is unhashable. For your custom hooks, you can store the dict as tuples of key-value pairs, i....
0
2016-08-08T09:26:29Z
[ "python", "python-2.7", "serialization", "msgpack" ]
BeautifulSoup lxml parser closing tags where it shouldn't be
38,489,674
<p>I'm using BeautifulSoup's lxml parser to parse some html. However, it's not being parsed as it's written. For instance, the following code:</p> <pre><code>import bs4 my_html = ''' &lt;html&gt; &lt;body&gt; &lt;B&gt; &lt;P&gt; Hello, I am some bolded text &lt;/P&gt; &lt;/B&gt; &lt;/body&gt; &lt;/html&gt; ''' soup ...
1
2016-07-20T19:53:27Z
38,490,138
<p>This is because you can't have a <code>&lt;p&gt;</code> tag inside of a <code>&lt;b&gt;</code> tag, so the parser is trying to fix broken HTML. Using html5lib's <code>html5lib</code> parser or Python's <code>html.parser</code> will result in your expected output (I only know this because I just tested it).</p>
1
2016-07-20T20:20:25Z
[ "python", "html", "beautifulsoup" ]
BeautifulSoup lxml parser closing tags where it shouldn't be
38,489,674
<p>I'm using BeautifulSoup's lxml parser to parse some html. However, it's not being parsed as it's written. For instance, the following code:</p> <pre><code>import bs4 my_html = ''' &lt;html&gt; &lt;body&gt; &lt;B&gt; &lt;P&gt; Hello, I am some bolded text &lt;/P&gt; &lt;/B&gt; &lt;/body&gt; &lt;/html&gt; ''' soup ...
1
2016-07-20T19:53:27Z
38,490,179
<p>That's because paragraphs are not allowed inside the <code>&lt;b&gt;</code> tag.</p> <p>Only tags that accept flow content are allowed as the parent of <a href="https://developer.mozilla.org/en/docs/Web/HTML/Element/p" rel="nofollow"><code>&lt;p&gt;</code></a> tags. See <a href="https://developer.mozilla.org/en-US/...
2
2016-07-20T20:22:30Z
[ "python", "html", "beautifulsoup" ]
Culling certain numbers from a List
38,489,754
<p>I have a series of variable lists inside a list, and I'm comparing it to another list. I want, run through each list in aList, analyze each number and as soon its a match in bList, append that number to finalList. I want to return the first match in other words and ignore future matches. For Example:</p> <pre><c...
0
2016-07-20T19:58:33Z
38,489,798
<p>Use a for loop with a <a href="https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops" rel="nofollow"><code>break</code></a>.</p> <pre><code>finalList = [] for sl in aList: for item in sl: if item in bList: finalList.append(item) ...
1
2016-07-20T20:01:07Z
[ "python", "list", "compare" ]
Python script to type something in terminal
38,489,755
<p>I'm trying to make a python script that opens a separate terminal window and immediately enters a command without the user having to type anything.</p> <p>I use <code>os.system("gnome-terminal")</code> to open the second terminal but I have no clue how to make it go ahead an enter a command. I tried <code>os.system...
1
2016-07-20T19:58:35Z
38,493,278
<p>you can try a few ways</p> <p>such as:</p> <pre><code>os.system("gnome-terminal -e 'bash -c \"sudo apt-get update; exec bash\"'") </code></pre> <p>Although on windows i opt for a sub-process, heres an example from stack:</p> <pre><code>import subprocess as sub sub.Popen('cmd /K dir') sub.Popen(['cmd', '/K', 'di...
1
2016-07-21T01:09:33Z
[ "python", "terminal" ]
How can I select only a particular row in a CSV file?
38,489,761
<p>I have a little program that just needs to read one (and only one) row from a csv file and write the column values to a series of files. The program has three system arguments: the path to the data file, the job id (uuid), and the target row number, i.e. the row in the csv that I want to parse. It's not working, h...
0
2016-07-20T19:58:48Z
38,490,023
<p>the csv library DictReader() object has the ability to display the current line number with:</p> <pre><code>reader = csv.DictReader(csv_file) reader.line_num </code></pre> <p>you could iterate through and do nothing until you reach the correct line number that you need, something like this:</p> <pre><code>for row...
2
2016-07-20T20:13:33Z
[ "python", "csv" ]
How can I select only a particular row in a CSV file?
38,489,761
<p>I have a little program that just needs to read one (and only one) row from a csv file and write the column values to a series of files. The program has three system arguments: the path to the data file, the job id (uuid), and the target row number, i.e. the row in the csv that I want to parse. It's not working, h...
0
2016-07-20T19:58:48Z
38,491,289
<p>Assuming you count rows from 1 (rather than 0), here's a standalone function that will do it:</p> <pre><code>import csv from contextlib import contextmanager import sys import itertools @contextmanager def multi_file_manager(files, mode='r'): """ Context manager for multiple files. """ files = [open(file, ...
1
2016-07-20T21:38:10Z
[ "python", "csv" ]
SSL Error On Python Request
38,489,767
<p>I'm trying to make a request to an API using Python, but I'm getting an <strong>SSL error</strong>. I've searched it everywhere, but can't seem to find a fix.</p> <p>This is the versions I have installed on my virtual environment:</p> <pre><code>Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 26 2016, 12:10:39) [GCC 4.2...
0
2016-07-20T19:59:29Z
38,490,149
<blockquote> <p>msesandbox.cisco.com:8081</p> </blockquote> <p>This server supports only TLS 1.2, i.e. no TLS 1.0 or worse.</p> <blockquote> <p>'OpenSSL 0.9.8zg 14 July 2015'</p> </blockquote> <p>This OpenSSL version does not support TLS 1.2 yet. You need at least OpenSSL 1.0.1 for this.</p>
1
2016-07-20T20:21:01Z
[ "python", "ssl", "request" ]
Is there a pythonic way to process tree-structured dict keys?
38,489,772
<p>I'm looking for a pythonic idiom to turn a list of keys and a value into a dict with those keys nested. For example:</p> <pre><code>dtree(["a", "b", "c"]) = 42 or dtree("a/b/c".split(sep='/')) = 42 </code></pre> <p>would return the nested dict:</p> <pre><code>{"a": {"b": {"c": 42}}} </code></pre> <p>This co...
8
2016-07-20T19:59:45Z
38,489,875
<blockquote> <p>I'm looking for a pythonic idiom to turn a list of keys and a value into a dict with those keys nested.</p> </blockquote> <pre><code>reduce(lambda v, k: {k: v}, reversed("a/b/c".split("/")), 42) </code></pre> <blockquote> <p>This could be used to turn a set of values with hierarchical keys into a ...
11
2016-07-20T20:05:45Z
[ "python", "dictionary", "tree" ]
Is there a pythonic way to process tree-structured dict keys?
38,489,772
<p>I'm looking for a pythonic idiom to turn a list of keys and a value into a dict with those keys nested. For example:</p> <pre><code>dtree(["a", "b", "c"]) = 42 or dtree("a/b/c".split(sep='/')) = 42 </code></pre> <p>would return the nested dict:</p> <pre><code>{"a": {"b": {"c": 42}}} </code></pre> <p>This co...
8
2016-07-20T19:59:45Z
38,545,579
<p>Or just for grins since <code>reduce</code> is the coolest thing since sliced bread, you could save one SLOC by using it twice :-)</p> <pre><code>def dmerge(x, y): result = x.copy() k = next(iter(y)) if k in x: result[k] = dmerge(x[k], y[k]) else: result.update(y) return result ...
0
2016-07-23T19:16:38Z
[ "python", "dictionary", "tree" ]
How can I stop App Engine images.get_serving_url returning a scaled down image?
38,489,813
<p>I have just started using google.appengine.api.images.get_serving_url to serve images uploaded to Google Cloud Storage (GCS). Following the <a href="https://cloud.google.com/appengine/docs/python/refdocs/google.appengine.api.images" rel="nofollow">docs</a> I am just calling</p> <pre><code>url = google.appengine.api...
0
2016-07-20T20:01:41Z
38,513,079
<p>Adding <code>=s0</code> to the end of the URL will return the original size.</p>
1
2016-07-21T19:44:19Z
[ "python", "google-app-engine" ]
Changing row data in case it doesn't match different row
38,489,882
<p>I ran into an issue while was trying to work with a CSV file. Basically, I have a CSV file which contains names and ID's. Header looks something similar to this:<br></p> <p>New ID | name | ID that needs to be changed | name |<br></p> <p>In the column[0], New ID column, there are numbers from 1 to 980. in the colum...
0
2016-07-20T20:06:16Z
38,489,966
<p>3 problems here:</p> <ul> <li>first you don't specify the delimiter, I assume it's pipe. csv parser cannot autodetect the delimiter.</li> <li>second, you create the reader but scan the raw input file instead, which explains that when you write the csv back, it creates as many cells as there are letters (iterates ov...
1
2016-07-20T20:10:51Z
[ "python", "mysql", "csv" ]
Generate an image tag with a Django static url in the view instead of the template
38,489,920
<p>I want to generate an image with a static url in a view, then render it in a template. I use <code>mark_safe</code> so that the HTML won't be escaped. However, it still doesn't render the image. How do I generate the image tag in Python?</p> <pre><code>from django.shortcuts import render from django.utils.safest...
1
2016-07-20T20:08:04Z
38,490,081
<p>You've marked the string, containing a template directive, as safe. However, templates are rendered in one pass. When you render that string, that's it, it doesn't go through and then render any directives that were in rendered strings. You need to <a href="http://stackoverflow.com/a/17738606/400617">generate the...
5
2016-07-20T20:16:47Z
[ "python", "django" ]
How do I import information from a web page to python
38,489,933
<p>I am relatively new to programming and I am not sure how to import information from websites into python. I am running python 2.7 through Aptana software. I would like to write a program that accesses an online dictionary, finds a word, and then creates a game of hangman.</p> <p>My main problem is I have no idea ...
-2
2016-07-20T20:09:03Z
38,490,140
<p>Try the <a href="http://docs.python-requests.org/en/master/" rel="nofollow">Requests</a> library. Figure out where on the page words will be found and maybe utilise another library called <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">BeautifulSoup</a> to fetch all div's (or other ht...
0
2016-07-20T20:20:33Z
[ "python", "webpage", "aptana" ]
Python: Convert Cyclical dictionary to JSON
38,490,051
<p>I'm trying to convert a nested cyclical dictionary to JSON. I am getting an overflow error:</p> <pre><code>In [8]: xx = json.dumps(d) --------------------------------------------------------------------------- OverflowError Traceback (most recent call last) &lt;ipython-input-8-95e57b3e2c...
0
2016-07-20T20:14:57Z
38,490,145
<p>Python's json decoder does have a feature to check for cyclical objects - <code>check_circular</code> - which defaults to True. Its behavior is exactly to raise the overflowerro you are seeing.</p> <p>(In Python 3.5 I get a <code>ValueError</code> with <code>check_circular</code> enabled and a <code>RecursionError<...
0
2016-07-20T20:20:41Z
[ "python", "json", "dictionary", "circular-dependency" ]
Python: Convert Cyclical dictionary to JSON
38,490,051
<p>I'm trying to convert a nested cyclical dictionary to JSON. I am getting an overflow error:</p> <pre><code>In [8]: xx = json.dumps(d) --------------------------------------------------------------------------- OverflowError Traceback (most recent call last) &lt;ipython-input-8-95e57b3e2c...
0
2016-07-20T20:14:57Z
38,490,667
<p>How to make a cyclical dictionary, shortest example I can think of:</p> <pre><code>&gt;&gt;&gt; foo = { 'bar': None } &gt;&gt;&gt; foo['bar'] = foo &gt;&gt;&gt; foo {'bar': {...}} &gt;&gt;&gt; foo['bar'] {'bar': {...}} &gt;&gt;&gt; foo['bar']['bar'] {'bar': {...}} </code></pre> <p>So the question is what your ques...
0
2016-07-20T20:54:10Z
[ "python", "json", "dictionary", "circular-dependency" ]
Writing a join in SQLAlchemy error: sqlalchemy.exc.InvalidRequestError:
38,490,125
<p>This is the first table I created</p> <pre><code>class Candidate(Base): __tablename__ = 'candidates' id = Column(Integer, primary_key=True) first = Column(String, nullable=False) last = Column(String) title = Column(String) company = Column(String, nullable=False) def __repr__(self): return "&lt...
0
2016-07-20T20:19:28Z
38,490,488
<p>I'm fairly new to SQLAlchemy but I think you need to update your join relationship under the role table to:</p> <pre><code>user = relationship("Candidate", back_populates="role", order_by=id). </code></pre>
0
2016-07-20T20:42:54Z
[ "python", "sqlalchemy" ]
Set QListWidget's items selection mandatory
38,490,137
<p>I have a QWizardPage in which I have a QListWidget. I wish that the next button will only be enabled when at least one item was selected in the QListWidget. I tried to use registerField(...) and set it as mandatory, but it didn't seem to do anything. I also tried to change the property in the registerField command t...
0
2016-07-20T20:20:19Z
38,490,220
<p>QListWidgets have a signal for when an item is activated (selected). You can connect this signal to a slot that enables the next button.</p> <p>You can use something like</p> <pre><code>QListWidget.itemActivated.connect(self.enable_button) </code></pre> <p>and in your <code>enable_button</code> function, you coul...
0
2016-07-20T20:25:24Z
[ "python", "qt", "pyqt", "qlistwidget" ]