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
Web Scraping with Python - Looping for city name, clicking and get interested value
37,977,609
<p>This is my first time with Python and web scraping. Have been looking around and still unable to get what I need to do.</p> <p>Below are print screen of the elements that I've used via Chrome.</p> <p>As you can see, it is from the dropdown 'Apartments'.</p> <p>My 1st step in trying to do is get the list of cities...
0
2016-06-22T20:24:24Z
37,977,986
<p>You can access the elements by the class and a child "a" node. Then access the attribute "href" and add a domain name. </p> <pre><code>import requests from bs4 import BeautifulSoup url = 'http://www.homestead.ca/apartments-for-rent/' response = requests.get(url) html = response.content soup = BeautifulSoup(html,'l...
0
2016-06-22T20:48:34Z
[ "python", "web-scraping" ]
Best way to define multiple dictionary in one line versus many lines
37,977,617
<p>Which method is better and why?</p> <pre><code>a = dict() b = dict() c = dict() </code></pre> <p>or</p> <pre><code>a, b, c = dict(), dict(), dict() </code></pre> <p>All three dictionaries will have different keys and are for different purpose.</p>
0
2016-06-22T20:24:51Z
37,977,632
<blockquote> <p>All 3 dictionaries will have different keys and are for different purpose ?</p> </blockquote> <p><strong>Keep it on different lines</strong> -- they are more readable that way. Readability of a python code matters a lot. That being said, you could:</p> <pre><code>a = {} # or dict(..) b = {} c = {}...
1
2016-06-22T20:25:45Z
[ "python" ]
How to make a new dict from two dict
37,977,734
<p>I'm trying to build a new dict from dict of just keys and a another dict of keys values pairs. In the second dict there could be more then one item mapped to same key. In the new dict, I would like to collect all those items together in a list and map it to a key. I have this code so far but it doesn't work. I get <...
0
2016-06-22T20:30:46Z
37,977,854
<p>Use a list of tuples instead:</p> <pre><code>result = [('2', 'Berat'), ('3', 'Ayn Daflah'), ('4', 'Eastern'), ('5', 'Canillo'), ('1', 'Badgis'), ('4', "Manu'a"), etc. ] </code></pre> <p>Then do something like this:</p> <pre><code>dictionary = {} for (key, val) in result: if not key in dictionary: d...
0
2016-06-22T20:38:10Z
[ "python", "dictionary" ]
Python: using pandas.pivot_table to flatten activity logs and display time spent doing activities
37,977,881
<p>I'm looking at using python and pandas to flatten our VLE (Blackboard inc.) activity table. I'm trying to sum the total time spent per day on accessing courses as opposed to doing other non course activity in the activity logs/table. </p> <p>I've created some fake data and code below (python) to simulate the questi...
1
2016-06-22T20:40:54Z
37,981,310
<p>You're right (in your comment): you'll need <code>dataframe.shift</code>.</p> <p>If I'm understanding your question correctly, you want to record the time <em>elapsed</em> since the last timestamp, so timestamps signify the beginning of an activity, and when the last activity was <code>null</code> we should not rec...
1
2016-06-23T02:24:43Z
[ "python", "pandas", "lambda", "pivot-table" ]
Python Tkinter :removing widgets that were created using a for loop
37,977,885
<p>I'm currently learning how to use the Tkinter library on python to create a GUI that takes in longitude and latitude points and outputing that into a file. Basically I'm trying to automate the process of having to copy the correct format of line of points to another file.</p> <p>So I created a Entry and button fiel...
1
2016-06-22T20:41:33Z
37,977,974
<p>You need to hold on to references to all those widgets, usually via a list. Try initializing a list (<code>list_of_widgets</code>) before your loop, then every time you create a widget, append it to that list. When you clear, you can iterate through that list of widgets and destroy each one. Once you're done clearin...
1
2016-06-22T20:47:30Z
[ "python", "tkinter" ]
Rearrange the columns of a pandas DataFrame so that the column with highest total is first
37,977,929
<p>I have this DataFrame:</p> <pre><code>df = pd.DataFrame({'c1':[1,2,3,4] ,'c2':[2,4,5,6] ,'c3':[5,7,9,10] ,'c4':[-1,3,1,0] ,'c5':[100,1000,1,2]}) df c1 c2 c3 c4 c5 0 1 2 5 -1 100 1 2 4 7 3 1000 2 ...
2
2016-06-22T20:44:46Z
37,977,978
<p>Apologies for the trivial question - it is easier than I thought:</p> <pre><code>df[df.sum().sort_values(ascending = False).index] </code></pre>
1
2016-06-22T20:47:52Z
[ "python", "pandas" ]
Retry .complete() for WrapperTask
37,977,959
<p>I am using Luigi to run several tasks, and then I need to bulk transfer the output to a standardized file location. I've written a WrapperTask with an overridden <code>complete()</code> method to do this:</p> <pre><code>from luigi.task import flatten class TaskX(luigi.WrapperTask): date = luigi.DateParameter()...
0
2016-06-22T20:46:00Z
37,995,183
<p>I still think that overriding <code>.complete()</code> should in theory have been able to do this, and I'm still not sure why it's not, but if you're just looking for a way to bulk-transfer files after running a process, a workable solution is just to have the transfer take place within a <code>.run()</code> method:...
0
2016-06-23T14:55:29Z
[ "python", "luigi" ]
Line comprehension in python
37,977,985
<p>I want to write a small program that replaces certain values in an array with the desired value. The array (called "arr") contains about 10,000 elements of integer type and i would like to replace the digits 3,4 and 5 with 1. </p> <p>I wrote the following code but it does not perform the desired function. Could som...
1
2016-06-22T20:48:31Z
37,978,034
<p>What you are doing now is called: <code>bitwise OR</code>. You should use a logical or: <code>or</code>.</p> <p>Better yet, you can use <code>in</code> operator to test. </p> <pre><code>a = [1 if x in (3,4,5) else x for x in arr] </code></pre>
3
2016-06-22T20:51:46Z
[ "python", "list-comprehension" ]
Line comprehension in python
37,977,985
<p>I want to write a small program that replaces certain values in an array with the desired value. The array (called "arr") contains about 10,000 elements of integer type and i would like to replace the digits 3,4 and 5 with 1. </p> <p>I wrote the following code but it does not perform the desired function. Could som...
1
2016-06-22T20:48:31Z
37,978,047
<p>Logical OR is <code>or</code>, not <code>|</code>. <code>|</code> is bitwise OR. This list comprehension should be written as</p> <pre><code>a = [1 if x == 3 or x == 4 or x == 5 else x for x in arr] </code></pre> <p>or</p> <pre><code>a = [1 if x in (3, 4, 5) else x for x in arr] </code></pre> <p>Libraries like N...
1
2016-06-22T20:52:50Z
[ "python", "list-comprehension" ]
Python; scientific notation string to number
37,978,022
<p>I am currently converting a file from csv to xlsx. The problem is that the data is default converted all to strings. How can I convert the numbers (typically shown as +1.50000000000E+009 or " +1.50000000000E+009" (leading space) from string to number representations. I've tried typecasting and general workarounds bu...
1
2016-06-22T20:50:39Z
37,978,121
<p>You can accomplish this using <code>float()</code>.</p> <pre><code>&gt;&gt;&gt; float("+1.50000000000E+009") &gt;&gt;&gt; 1500000000.0 </code></pre>
1
2016-06-22T20:57:49Z
[ "python", "csv" ]
Python; scientific notation string to number
37,978,022
<p>I am currently converting a file from csv to xlsx. The problem is that the data is default converted all to strings. How can I convert the numbers (typically shown as +1.50000000000E+009 or " +1.50000000000E+009" (leading space) from string to number representations. I've tried typecasting and general workarounds bu...
1
2016-06-22T20:50:39Z
37,978,162
<p>You <strong>should</strong> use <code>float()</code> :</p> <pre><code>float("+1.50000000000E+009") </code></pre> <p>you can also use <code>eval()</code>, however this could be potentially <em>dangerous</em> if you do not know for certain the type of input you'll be passing as a parameter. </p> <pre><code>eval("+1...
1
2016-06-22T21:00:18Z
[ "python", "csv" ]
Do python scripts need to be exited?
37,978,136
<p>I've been using Python more and more recently, and I'd like to know if Python scripts need an exit statement at the end? If they don't is it proper to always add an exit statement at the end of a script?</p>
-1
2016-06-22T20:59:02Z
37,978,185
<p>You do not need an exit statement in Python code, unless you want to set the exit code yourself</p>
0
2016-06-22T21:02:06Z
[ "python", "python-3.x" ]
Do python scripts need to be exited?
37,978,136
<p>I've been using Python more and more recently, and I'd like to know if Python scripts need an exit statement at the end? If they don't is it proper to always add an exit statement at the end of a script?</p>
-1
2016-06-22T20:59:02Z
37,978,210
<p>No, python scripts do not need an exit- in fact, a raw <code>quit()</code> or <code>exit()</code> at the end of many things may break them - in the case of importing something, all top-level code is executed: if that contains an <code>exit()</code>, the whole importing program will exit, which is almost certainly no...
1
2016-06-22T21:03:30Z
[ "python", "python-3.x" ]
Do python scripts need to be exited?
37,978,136
<p>I've been using Python more and more recently, and I'd like to know if Python scripts need an exit statement at the end? If they don't is it proper to always add an exit statement at the end of a script?</p>
-1
2016-06-22T20:59:02Z
37,978,212
<p>This is unnecessary. There is no such thing as an "exit statement" in Python, and calling a function like <code>sys.exit()</code> at the end of your program does the same thing as just letting execution flow off the end of your program.</p>
0
2016-06-22T21:03:33Z
[ "python", "python-3.x" ]
Specifying vertex position via coordinates in python graph-tool
37,978,154
<p>Is it possible to plot a vertex at a particular position on the xy-axis by specifying coordinates? I want to have a square lattice of vertices without the edges between them (and then add edges later as I see fit).</p> <p>Thanks</p>
0
2016-06-22T21:00:03Z
38,043,114
<p>Suppose you have a graph called "g".</p> <p>First create a property map by typing:</p> <pre><code>position = g.new_vertex_property("vector&lt;double&gt;") </code></pre> <p>You can manually add the coordinates of each vertex. For example if you want vertex 5 to be a position (2.5, -1.9) type:</p> <pre><code>posit...
3
2016-06-26T20:57:57Z
[ "python", "graph-tool" ]
Deleting rows with certain keywords of csv file
37,978,160
<p>I have a large data file and I need to delete rows that have certain keywords. </p> <p>Here is an example of the file I'm using:</p> <pre><code>User Name DN MB31212 CN=MB31212,CN=Users,DC=prod,DC=trovp,DC=net MB23423 CN=MB23423 ,OU=Generic Mailbox,DC=prod,DC=trovp,DC=net MB23424 CN=MB23424 ,C...
1
2016-06-22T21:00:14Z
37,978,749
<p>You can try this two-step filtering as your logic. Use the <code>str.contains</code> method to filter out rows with <code>OU=DNA</code> and use <code>str.replace</code> method with regular expression to trim the leading <code>CN=x</code>:</p> <pre><code>newDf = df.loc[~df.DN.str.contains("OU=DNA")] newDf.DN = newDf...
3
2016-06-22T21:40:33Z
[ "python", "python-3.x", "pandas" ]
Deleting rows with certain keywords of csv file
37,978,160
<p>I have a large data file and I need to delete rows that have certain keywords. </p> <p>Here is an example of the file I'm using:</p> <pre><code>User Name DN MB31212 CN=MB31212,CN=Users,DC=prod,DC=trovp,DC=net MB23423 CN=MB23423 ,OU=Generic Mailbox,DC=prod,DC=trovp,DC=net MB23424 CN=MB23424 ,C...
1
2016-06-22T21:00:14Z
37,979,095
<p>To read the file sample you gave I used:</p> <pre><code>df = pd.read_csv('sample.csv', sep=' ', encoding='latin1', engine="python") </code></pre> <p>and then:</p> <pre><code>df = df.drop(df[df.DN.str.contains("OU=DNA")].index) df.DN = df.DN.str.replace('(CN=MB[0-9]{5}\s*,)', '') df </code></pre> <p>gave the ...
1
2016-06-22T22:10:05Z
[ "python", "python-3.x", "pandas" ]
django-import-export ForeignKeyWidget doesn't do lookup
37,978,208
<p>I'm trying to import an xls file with django-import-export. </p> <p>This is what I have:</p> <pre><code>class CourseResource(resources.ModelResource): course_number = fields.Field(column_name='Kursnummer', attribute='course_number', widget=CharWidget()) school_year = fields.Field(column_name='Schuljahr', a...
1
2016-06-22T21:03:23Z
37,985,603
<p>I found the answer now. My CourseAdmin was missing the resource class, so my CourseResource had no effect at all. I added this: </p> <pre><code>class CourseAdmin(ImportExportActionModelAdmin, ImportExportModelAdmin): list_display = ('course_number', 'school_year', 'school_subject', 'teacher', 'lessons_per_week'...
0
2016-06-23T08:04:59Z
[ "python", "django", "excel", "django-import-export" ]
Replace some accented letters from word in python
37,978,225
<p>I'm trying to replace some accented letters from Portuguese words in Python.</p> <pre><code>accentedLetters = ['à', 'á', 'â', 'ã', 'é', 'ê', 'í', 'ó', 'ô', 'õ', 'ú', 'ü'] letters = ['a', 'a', 'a', 'a', 'e', 'e', 'i', 'o', 'o', 'o', 'u', 'u'] </code></pre> <p>So the accentedLetters will be repla...
0
2016-06-22T21:04:29Z
37,978,435
<p>A simple translation dictionary should do the trick. For each letter, if the letter is in the dictionary, use its translation. Otherwise, use the original. Join the individual characters back into a word.</p> <pre><code>def removeAccents(word): repl = {'à': 'a', 'á': 'a', 'â': 'a', 'ã': 'a', ...
5
2016-06-22T21:19:35Z
[ "python" ]
Replace some accented letters from word in python
37,978,225
<p>I'm trying to replace some accented letters from Portuguese words in Python.</p> <pre><code>accentedLetters = ['à', 'á', 'â', 'ã', 'é', 'ê', 'í', 'ó', 'ô', 'õ', 'ú', 'ü'] letters = ['a', 'a', 'a', 'a', 'e', 'e', 'i', 'o', 'o', 'o', 'u', 'u'] </code></pre> <p>So the accentedLetters will be repla...
0
2016-06-22T21:04:29Z
37,978,821
<p>You can view the Unidecode library for Python3.</p> <p>For example:</p> <pre><code>from unidecode import unidecode a = ['à', 'á', 'â', 'ã', 'é', 'ê', 'í', 'ó', 'ô', 'õ', 'ú', 'ü'] for k in a: print (unidecode(u'{0}'.format(k))) </code></pre> <p>Result:</p> <p>a a a a e e i o o o u u</p>
1
2016-06-22T21:46:25Z
[ "python" ]
Replace some accented letters from word in python
37,978,225
<p>I'm trying to replace some accented letters from Portuguese words in Python.</p> <pre><code>accentedLetters = ['à', 'á', 'â', 'ã', 'é', 'ê', 'í', 'ó', 'ô', 'õ', 'ú', 'ü'] letters = ['a', 'a', 'a', 'a', 'e', 'e', 'i', 'o', 'o', 'o', 'u', 'u'] </code></pre> <p>So the accentedLetters will be repla...
0
2016-06-22T21:04:29Z
37,993,633
<p>I have finally solved my problem:</p> <pre><code>#! /usr/bin/python # -*- coding: utf-8 -*- import sys def removeAccents(word): replaceDict = {'à'.decode('utf-8'): 'a', 'á'.decode('utf-8'): 'a', 'â'.decode('utf-8'): 'a', 'ã'.decode('utf-8'): 'a', ...
0
2016-06-23T13:51:59Z
[ "python" ]
Opencv python incorrect blocksize
37,978,271
<pre><code>def adaptive_gaussian_thresholding(self, filename): im = cv2.imread(filename, 0) filtered_image = cv2.adaptiveThreshold(im, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, 3, cv2.THRESH_BINARY, 3, 0) cv2.imwrite(filename, filtered_image) </code></pre> <blockquote> <pre><code>filtered_image = cv2.adaptiveTh...
1
2016-06-22T21:09:01Z
37,978,531
<p>If you do call the <code>help()</code> for that function in python, the call needs to respect the following form:</p> <pre><code>Help on built-in function adaptiveThreshold in module cv2: adaptiveThreshold(...) adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C[, dst]) </code></pre> ...
0
2016-06-22T21:25:29Z
[ "python", "opencv" ]
Opencv python incorrect blocksize
37,978,271
<pre><code>def adaptive_gaussian_thresholding(self, filename): im = cv2.imread(filename, 0) filtered_image = cv2.adaptiveThreshold(im, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, 3, cv2.THRESH_BINARY, 3, 0) cv2.imwrite(filename, filtered_image) </code></pre> <blockquote> <pre><code>filtered_image = cv2.adaptiveTh...
1
2016-06-22T21:09:01Z
37,978,540
<p>You are calling <code>adaptiveThreshold</code> with an extra argument. You have incorrectly placed a <code>3</code> in between the <code>adaptiveMethod</code> and <code>thresholdType</code> arguments. In your invocation, the <code>cv2.THRESH_BINARY</code> flag is in the position expected for the <code>blockSize</cod...
3
2016-06-22T21:26:14Z
[ "python", "opencv" ]
Parallelizing 3D numpy array calculation using dask.array.core.map_blocks
37,978,336
<p>I have a 3D numpy array (dimensions: depth, latitude, longtitude) and I am trying to do some parallelized calculation using the data along the depth axis at each lat-lon point and so far I have been unsuccessful. I've looked at the documentation for <code>dask.array.core.map_blocks</code> but it has not been helpful...
0
2016-06-22T21:14:13Z
37,978,626
<p>Chunks should either be a tuple of integers specifying a uniform chunkshape across the full array</p> <pre><code>chunks=(49, 32, 12) </code></pre> <p>Or it should be a tuple of tuples, each tuple defining how to chunk up each dimension.</p> <pre><code>chunks=((20, 20, 9), (8, 8, 8, 8), (12, 24, 24, 12)) </code></...
0
2016-06-22T21:32:30Z
[ "python", "numpy", "parallel-processing", "dask" ]
GUI with Tkinter, auto refresh an image
37,978,529
<pre><code>from __future__ import print_function from Tkinter import * from tkFont import Font #import RPi.GPIO as GPIO from subprocess import call import time from time import sleep from PIL import Image from PIL import ImageTk ###STARTING A CLASS### class MyDialog(Frame): def __init__(self, parent): ...
0
2016-06-22T21:25:28Z
37,983,837
<p>You need to call <code>root.mainloop()</code> in <code>main()</code>. You need to call this in every Tkinter app.</p>
1
2016-06-23T06:29:50Z
[ "python", "user-interface", "tkinter" ]
Plot multiple functions with the same properties in matplotlib
37,978,542
<p>I try to visualise multiple function coming from the single parameter. I need to do some kind of loop over parameter. I would like to do assign the same colour, legend etc to all plotted functions of given parameter.</p> <p>The problem is that all plots I try, matplotlib assign different colours and always give a l...
1
2016-06-22T21:26:19Z
38,015,084
<p>I think now I understand what you want. You'll never run out of colors, because <code>matplotlib</code> supports a wide range of color definitions. Any legal HTML-name, any RGB-triple, ...</p> <p>I'm don't know how to conditionally set the label for artists, so that part of the following (the <code>if</code>) is a ...
0
2016-06-24T13:52:16Z
[ "python", "matplotlib" ]
How to export array in csv or txt in Python
37,978,624
<p>I'm trying to export array to txt or csv file. I've been trying with numpy but i always get some error like <code>TypeError: Mismatch between array dtype ('&lt;U14') and format specifier ('%.18e')</code></p> <p>Here is my code without numpy that works great but I need help with part how to export it.</p> <pre><co...
0
2016-06-22T21:32:07Z
37,979,006
<p>Looks like you are doing something like:</p> <pre><code>In [1339]: peoples=[] In [1340]: for _ in range(3): ......: peoples.append([234, datetime.datetime.now().strftime("%d/%m/%y %H:%M")]) ......: In [1341]: peoples Out[1341]: [[234, '22/06/16 14:57'], [234, '22/06/16 14:57'], [234, '22/06/16 14:5...
1
2016-06-22T22:01:51Z
[ "python", "arrays", "csv", "numpy" ]
How to export array in csv or txt in Python
37,978,624
<p>I'm trying to export array to txt or csv file. I've been trying with numpy but i always get some error like <code>TypeError: Mismatch between array dtype ('&lt;U14') and format specifier ('%.18e')</code></p> <p>Here is my code without numpy that works great but I need help with part how to export it.</p> <pre><co...
0
2016-06-22T21:32:07Z
37,979,164
<p><a href="http://stackoverflow.com/a/37979006/2141635">hpauj's</a> answer explains you why your code error but using the <em>csv</em> lib and writing as you go is probably a lot easier:</p> <pre><code>import csv with open("out.csv", "w") as f: wr = csv.writer(f) for content in driver.find_elements_by_class_...
1
2016-06-22T22:17:03Z
[ "python", "arrays", "csv", "numpy" ]
Tensorflow softmax_cross...() function float type error
37,978,809
<p>I resolved in issue from <a href="http://stackoverflow.com/questions/37973619/tensorflow-converging-but-bad-predictions/37973844#37973844">this</a> post, and the use Olivier recommended using the <code>softmax_cross_entropy_with_logits()</code> function. He is correct, but I'm getting a weird data type error. </p> ...
0
2016-06-22T21:45:23Z
37,978,910
<p>You have created a placeholder with:</p> <pre><code>y = tf.placeholder(tf.float32, [None, n_input, n_input, n_classes], name="ground_truth") </code></pre> <p>The error is quite clear:</p> <blockquote> <p>You must feed a value for placeholder tensor 'ground_truth'</p> </blockquote> <p>When calling <code>sess.ru...
1
2016-06-22T21:53:20Z
[ "python", "machine-learning", "neural-network", "artificial-intelligence", "tensorflow" ]
how to create a django migration for splitting model into multiple models
37,978,823
<p>I have a django model that I am splitting into multiple models (django 1.9) The app is more or less a system for tracking items and sets of items, which are usually associated with a file. (these files are not uploaded, or added by users, this is why I do no use the file field)</p> <p>Here is a toy example of one o...
1
2016-06-22T21:46:38Z
38,021,174
<p>You can create the new model migration using south, then copy/create new objects for the new classes, then remove the fields from the original model. Here's what I do:</p> <ol> <li>Create the new model (ItemFile), DO NOT remove the fields from ItemA</li> <li>Generate a south migration using the standard methods</li...
2
2016-06-24T19:56:26Z
[ "python", "django" ]
How to pair up numbers in tournament given k and a specific condition
37,978,846
<p>I was asked during the interview. I didn't take a note, so the problem description may be a bit vague.</p> <p>number is the rank in tournament.</p> <pre><code>k=1, return (1, 2) k=2, return ((1, 4), (2, 3)) k=3, return (((1, 8), (4, 5)), ((2, 7), (3, 6))) k=4, return ((((1, 16), (8, 9)), ((4, 13), (5, 12))), (((...
-2
2016-06-22T21:48:16Z
37,978,933
<p>wow hopefully the interviewers did a much better job of explaining the problem statement</p> <p>maybe this is what you want</p> <pre><code>def get_pairs(L): L = sorted(L) middle = len(L)//2 result=list(zip(L[:middle],L[:middle-1:-1])) if len(result) &gt; 2: return get_pairs(result) retu...
1
2016-06-22T21:55:25Z
[ "python", "algorithm", "data-structures", "nested-loops" ]
When patching 2 objects, second return first patched value
37,978,880
<p>I am writing UT for one of my function where I have to patch 2 objects.</p> <pre><code>@patch('mypackage.models.db_models.MongoClient', return_value={}) @patch('mypackage.models.db_models.GridFS') def test_file_in_db(self, mock_mongoclient, mock_gridfs): print "*"*80 print mock_gridfs print mock_...
0
2016-06-22T21:51:16Z
38,023,023
<p>You have them in the wrong order, put the params in the reverse order you define them.</p> <pre><code>@patch('mypackage.models.db_models.MongoClient', return_value={}) @patch('mypackage.models.db_models.GridFS') def test_file_in_db(self, mock_gridfs, mock_mongoclient): </code></pre>
1
2016-06-24T22:35:54Z
[ "python", "mocking", "patch", "python-unittest", "magicmock" ]
finding annual averages using pandas in python
37,978,891
<p>my data looks like this</p> <pre><code>unit year SURQ 10001 2012 89 10002 2012 83 10003 2012 88 10001 2013 75 10002 2013 69 10003 2013 59 10001 2014 36 10002 2014 59 10003 2014 84 </code></pre> <p>I want to find the annual average values for SURQ by unit. For example average SURQ in ...
1
2016-06-22T21:51:46Z
37,978,952
<pre><code>&gt;&gt;&gt; df.reset_index().groupby(['unit','year'])['SURQ'].mean() unit year 10001 2012 89 2013 75 2014 36 10002 2012 83 2013 69 2014 59 10003 2012 88 2013 59 2014 84 Name: SURQ, dtype: int64 </code></pre> <p>Or with a pivot table:...
0
2016-06-22T21:57:17Z
[ "python", "pandas", "pivot-table" ]
finding annual averages using pandas in python
37,978,891
<p>my data looks like this</p> <pre><code>unit year SURQ 10001 2012 89 10002 2012 83 10003 2012 88 10001 2013 75 10002 2013 69 10003 2013 59 10001 2014 36 10002 2014 59 10003 2014 84 </code></pre> <p>I want to find the annual average values for SURQ by unit. For example average SURQ in ...
1
2016-06-22T21:51:46Z
37,979,299
<p>if you want to do it using <code>pivot_table()</code>:</p> <pre><code>In [169]: x.pivot_table(index=[x.index,'year'], values='SURQ').reset_index() Out[169]: unit year SURQ 0 10001 2012 89 1 10001 2013 75 2 10001 2014 36 3 10002 2012 83 4 10002 2013 69 5 10002 2014 59 6 10003 20...
0
2016-06-22T22:29:57Z
[ "python", "pandas", "pivot-table" ]
TensorFlow MLP unhashable type 'list'
37,979,037
<p>I'm trying to feed a MLP with an array. The input array contains 120 floats and the output contains 2.</p> <pre><code>sess.run(init) # Training cycle train = True if train is True: for i in range(50): for letter in d1: #print(letter[0][0][0:5]) letter[0][0][0:5] = sorted(letter[0...
0
2016-06-22T22:04:24Z
37,996,755
<p>I suppose you had at the beginning of your code two placeholder <code>x</code> and <code>y</code>:</p> <pre class="lang-py prettyprint-override"><code>x = tf.placeholder(tf.float32) y = tf.placeholder(tf.float32) </code></pre> <hr> <p>The issue is that in your code, you use again the same name <code>x</code> and ...
0
2016-06-23T16:09:17Z
[ "python", "list", "tensorflow" ]
Update GTK menu from Web Flask App
37,979,079
<p>I am trying to create an Ubuntu indicator, that launches a Flask app in a separate thread (using <code>multiprocessing.Process</code>), and from an action in the Flask app, add an item to the indicator menu (in this simplified code, just when the root page is loaded, a menu item with the current datetime should be ...
1
2016-06-22T22:08:19Z
38,019,104
<p>Solved, it was all about the module <code>multiprocessing.Process</code>. Replaced with <code>threading.Thread</code> and everything works fine now.</p>
0
2016-06-24T17:32:44Z
[ "python", "ubuntu", "flask", "gtk3", "python-multithreading" ]
Display merged values using a condition, while including NaN values
37,979,138
<p>I have a resultant dataset (called Result) after merging two datasets. I want to display only those rows from Result where company_name1 is equal to company_name2. The output is stored in Result1.This can be done as follows:</p> <ul> <li>Result1=Result[Result.company_name1==Result.company_name2] </li> </ul> <p>The...
0
2016-06-22T22:14:32Z
37,979,248
<p>try this:</p> <pre><code>Result1=Result[(Result.company_name1==Result.company_name2) | \ (pd.isnull(Result.company_name1) | pd.isnull(Result.company_name2))] </code></pre>
0
2016-06-22T22:24:59Z
[ "python", "pandas" ]
how to parallelize many (fuzzy) string comparisons using apply in Pandas?
37,979,167
<p>I have the following problem</p> <p>I have a dataframe <strong>master</strong> that contains sentences, such as</p> <pre><code>master Out[8]: original 0 this is a nice sentence 1 this is another one 2 stackoverflow is nice </code></pre> <p>For every row in Master, I lookup into another...
0
2016-06-22T22:17:18Z
37,979,876
<p>You can parallelize this with Dask.dataframe. This will work almost the same except that you can't use column assignment and will instead need to use the <code>assign</code> method</p> <pre><code>&gt;&gt;&gt; dmaster = dd.from_pandas(master, npartitions=4) &gt;&gt;&gt; dmaster = dmaster.assign(my_value=dmaster.ori...
5
2016-06-22T23:30:31Z
[ "python", "pandas", "parallel-processing", "dask", "fuzzywuzzy" ]
Coinbase Wallet API python Authentication Error, Invalid Signature
37,979,170
<p>Python 3.4 Coinbase Wallet API V2</p> <hr> <p>I have been stuck for some time trying to figure out while this buy call (and other api calls like get_payment_methods() and get_accounts() ) run into authentication errors. I have successfully been able to run some of these api calls alone in a separate file.</p> <h...
0
2016-06-22T22:17:29Z
37,980,539
<p>after extensive static analysis, I have concluded this is probably your issue. </p> <pre><code>buy = api.buy('COIN-BS', 1) -&gt; buy = api.buy_c('COIN-BS', 1) </code></pre> <p>also figure out why your stack trace has <code>client.buy_c</code> instead of <code>client.buy</code></p>
0
2016-06-23T00:50:54Z
[ "python", "authentication", "coinbase" ]
How to make Python only look at commas with no space before or after as delimiters
37,979,192
<p>I have a csv file that I'm trying to read into python, manipulate, then write to another csv file.</p> <p>My current problem is that although the file is comma delimited, not all commas are delimiters. </p> <p>Only the commas that are <strong>NOT</strong> preceded and/or followed by a space should be counted as de...
3
2016-06-22T22:19:39Z
37,979,253
<p>A regex may be your best bet:</p> <pre><code>import re patt = re.compile(r"\b,\b") with open("in.csv") as f: for row in map(patt.split, f): print(row) </code></pre> <p>Which would give you:</p> <pre><code>['Date', 'Name', 'City\n'] ['May 30, 2016', 'Ryan', 'Boston'] </code></pre> <p>You will have to...
2
2016-06-22T22:25:22Z
[ "python", "csv", "delimiter", "python-3.5" ]
How to make Python only look at commas with no space before or after as delimiters
37,979,192
<p>I have a csv file that I'm trying to read into python, manipulate, then write to another csv file.</p> <p>My current problem is that although the file is comma delimited, not all commas are delimiters. </p> <p>Only the commas that are <strong>NOT</strong> preceded and/or followed by a space should be counted as de...
3
2016-06-22T22:19:39Z
38,056,975
<p>For those who are facing the same problem, you might also try the Pandas library, especially if Padraic's suggested solution doesn't work for you. It is very easy to use.</p>
0
2016-06-27T14:45:53Z
[ "python", "csv", "delimiter", "python-3.5" ]
Writing to CSV issue
37,979,232
<p>I've done this 100 times, but for some reason I can't get this to work. What am I doing wrong?</p> <pre><code>csv_file = open('test_a.csv', 'wb') writer = csv.writer(csv_file) writer.writerow('test') </code></pre> <p>OR</p> <pre><code>csv_file = open('test_a.csv', 'wb') writer = csv.writer(csv_file) writer.writer...
-3
2016-06-22T22:23:43Z
37,979,307
<p>The <code>writerow</code> method expects a list of values. You're giving it a string, which is iterable.. so you end up with <code>t, e, s, t</code> which is probably not what you want. Make sure you are passing a list:</p> <pre><code>writer.writerow(['test']) </code></pre>
-1
2016-06-22T22:30:49Z
[ "python" ]
Writing to CSV issue
37,979,232
<p>I've done this 100 times, but for some reason I can't get this to work. What am I doing wrong?</p> <pre><code>csv_file = open('test_a.csv', 'wb') writer = csv.writer(csv_file) writer.writerow('test') </code></pre> <p>OR</p> <pre><code>csv_file = open('test_a.csv', 'wb') writer = csv.writer(csv_file) writer.writer...
-3
2016-06-22T22:23:43Z
37,979,315
<p>Call a <code>.close()</code> on the file object or open <code>with</code> a context manager:</p> <pre><code>with open('test_a.csv', 'wb') as csv_file: writer = csv.writer(csv_file) writer.writerow(['test']) </code></pre>
1
2016-06-22T22:32:10Z
[ "python" ]
TensorFlow: product equivalent of tf.add_n
37,979,238
<p>Is there a product equivalent of tf.add_n, returning the elementwise product of a list of tensors?</p>
1
2016-06-22T22:24:18Z
37,979,571
<p>Solution 1:</p> <p>You can use higher order functions tf.foldl and tf.foldr. Here is an example:</p> <pre><code>x = tf.constant([5, 2, 4, 3]) y = tf.constant([2, 2, 1, 6]) z = tf.constant([24, 2, 1, 6]) xyz=[x,y,z] product = tf.foldl(tf.mul, xyz) with tf.Session() as sess: print product.eval() </code></pre>...
1
2016-06-22T22:58:18Z
[ "python", "tensorflow" ]
How can I avoid webpage receiving Gateway Timeout when calling slow Python CGI script?
37,979,262
<p>I have a LAMP server set up in EC2. A simple website hosted on this web server in <code>/var/www/html/</code> allows a user to upload an audio file of people having a discussion via an input form:</p> <pre><code>&lt;form action="../cgi-bin/store_mp3_view" method="post" accept-charset="utf-8" enctype="multipart/form...
0
2016-06-22T22:26:05Z
37,979,340
<p>Generally the way to handle long delay is using <code>yield</code> and sending partial data to client. Instead of <code>obj.wait()</code> you need a loop to check if status is finished and if not printing something like: <code>...</code> and sleep for one second. This way you will not receive timeout.</p>
0
2016-06-22T22:35:22Z
[ "python", "web-services" ]
How can I avoid webpage receiving Gateway Timeout when calling slow Python CGI script?
37,979,262
<p>I have a LAMP server set up in EC2. A simple website hosted on this web server in <code>/var/www/html/</code> allows a user to upload an audio file of people having a discussion via an input form:</p> <pre><code>&lt;form action="../cgi-bin/store_mp3_view" method="post" accept-charset="utf-8" enctype="multipart/form...
0
2016-06-22T22:26:05Z
38,032,665
<p>While Ali Nikneshans answer was helpful, it seems CGI is not the right tool for the job. I decided to stop using a LAMP stack/CGI apps and setup a Tornado web server with web sockets, which allows me to do async calls easily, background tasks, and use coroutines to setup a data pipeline for polling the API endpoint ...
0
2016-06-25T20:24:37Z
[ "python", "web-services" ]
pass parameter to PowerShell script when calling from Python
37,979,266
<p>From python I want to call a powershell script and pass a parameter to it</p> <p>The Powershell function header is listed here:</p> <pre><code>Function Invoke-Neo4j { [cmdletBinding(SupportsShouldProcess=$false,ConfirmImpact='Low')] param ( [Parameter(Mandatory=$false,ValueFromPipeline=$false,Position=0)] ...
0
2016-06-22T22:26:31Z
37,982,234
<p>I couldn't make the Powershell command work from Python. I actually found a .bat file with a command that works. I just inserted the 'start' parameter I call the bat file from python. It works like a charm. It's not optimal but it does the job for me.</p> <pre><code>SETLOCAL Powershell -NoProfile -NonInteractive -N...
0
2016-06-23T04:15:36Z
[ "python", "function", "powershell", "parameter-passing" ]
pass parameter to PowerShell script when calling from Python
37,979,266
<p>From python I want to call a powershell script and pass a parameter to it</p> <p>The Powershell function header is listed here:</p> <pre><code>Function Invoke-Neo4j { [cmdletBinding(SupportsShouldProcess=$false,ConfirmImpact='Low')] param ( [Parameter(Mandatory=$false,ValueFromPipeline=$false,Position=0)] ...
0
2016-06-22T22:26:31Z
38,001,791
<p>Running a script, in either PowerShell or Python, that only defines a function but does not call it has no other effect than defining function. The script needs to include a specific call to that function. In your case, you might as well put the logic at the top level of the script instead of inside a function then ...
0
2016-06-23T21:00:44Z
[ "python", "function", "powershell", "parameter-passing" ]
How can I build a Django query without knowing what fields I will query on?
37,979,286
<p>I'm new to Django and kinda new to Python too, and I'm trying to build a query. I have some fields in a dictionary and I don't know which will be used in a query (they're coming in from a form.)</p> <p>I've got something kinda working, but I can tell it's broke, and it's terrible, not reusable code:</p> <pre><code...
1
2016-06-22T22:28:35Z
37,982,155
<p>There's no built in way to do it by you can kinda optimise it.</p> <pre><code>def set_if_not_none(mapping, key, value): if value is not None: mapping[key] = value def view(request): sort_params = {} get_params_needed = ['street_number', 'street_name', 'district'] # And list all of them you nee...
1
2016-06-23T04:06:28Z
[ "python", "mysql", "django" ]
Given an object, how to get a list of bound methods which are called during runtime
37,979,365
<p>The question comes from this scenario:</p> <p>We've built a framework to test northbound apis of our project, based on pytest. And now we want to have a coverage report about how many apis are tested(basically, are called) by running the test scripts we have.</p> <p>We already have a well-defined client manager, w...
2
2016-06-22T22:37:37Z
37,979,615
<p>I don't know if you can get this from coverage library itself, but you can definitely get this information by processing files yourself.</p> <p>Have a look at the <a href="https://docs.python.org/2/library/ast.html" rel="nofollow">AST</a> module. It allows you to parse the all the files reported by coverage and gen...
0
2016-06-22T23:02:20Z
[ "python", "py.test", "coverage.py", "python-coverage" ]
Given an object, how to get a list of bound methods which are called during runtime
37,979,365
<p>The question comes from this scenario:</p> <p>We've built a framework to test northbound apis of our project, based on pytest. And now we want to have a coverage report about how many apis are tested(basically, are called) by running the test scripts we have.</p> <p>We already have a well-defined client manager, w...
2
2016-06-22T22:37:37Z
37,989,113
<p>Coverage.py does not have this feature. You'll need to use the <code>trace</code> module, or post-process the coverage results to get the method names.</p>
0
2016-06-23T10:32:30Z
[ "python", "py.test", "coverage.py", "python-coverage" ]
Django retrieve all rows from a table but the last three
37,979,398
<p>I have the last three rows by using <code>Book.objects.order_by('-id')[:3]</code>, is there a way to get all the rows excluding those three elements?</p>
0
2016-06-22T22:41:21Z
37,979,459
<p>This should work,</p> <pre><code>Book.objects.order_by('-id')[3:] </code></pre> <p>if you want to get them in order</p> <pre><code>Book.objects.order_by('-id')[3:][::-1] </code></pre>
1
2016-06-22T22:47:58Z
[ "python", "django", "database" ]
Django retrieve all rows from a table but the last three
37,979,398
<p>I have the last three rows by using <code>Book.objects.order_by('-id')[:3]</code>, is there a way to get all the rows excluding those three elements?</p>
0
2016-06-22T22:41:21Z
37,979,508
<p>As you have </p> <pre><code>books = Book.objects.order_by('-id')[:3] list_to_exclude = [b.id for b in books] </code></pre> <p>and then</p> <pre><code>books_excl = Book.objects.all().exclude(id__in=list_to_exclude) </code></pre>
0
2016-06-22T22:52:14Z
[ "python", "django", "database" ]
Django retrieve all rows from a table but the last three
37,979,398
<p>I have the last three rows by using <code>Book.objects.order_by('-id')[:3]</code>, is there a way to get all the rows excluding those three elements?</p>
0
2016-06-22T22:41:21Z
37,981,085
<p>Use:</p> <pre><code>Book.objects.exclude(pk__in=Book.objects.order_by('-id')[:3]) </code></pre> <p>Note: above query tested on postgres 9.5.3</p>
0
2016-06-23T01:59:53Z
[ "python", "django", "database" ]
how to associate a newly created EC2 security group with an instance
37,979,434
<p>How do I add an EC2 instance to a newly created security group? The security group was created with</p> <pre><code>client = session.client("ec2") group_id = client.create_security_group( DryRun=False, GroupName=group_name, VpcId=vpc_id, Description=description ) </code></pre>
1
2016-06-22T22:45:37Z
37,980,045
<p>You will want to modify the attributes of the instance:</p> <pre><code>modify_attribute(attribute, value, dry_run=False) </code></pre> <p><code>modify_attribute</code> changes an attribute of this instance. Use the attribute <strong>groupSet</strong> - <em>Set of Security Groups or IDs</em></p> <pre><code>i.modif...
1
2016-06-22T23:51:53Z
[ "python", "amazon-web-services", "amazon-ec2", "boto3" ]
code using the Spark on pyspark
37,979,565
<p>I have problem in pyspark. I have executed just these lines on Spark using pyspark as given below, it gives me following error,</p> <pre><code>&gt;&gt;&gt; text_file=sc.textFile("/Users/Aroon/spark/Scala/word") </code></pre> <blockquote> <p>Traceback (most recent call last): File "", line 1, in NameError:...
0
2016-06-22T22:57:52Z
37,983,622
<p>The error message quite clearly states that the sparkContext is not created on the sc variable. This would have automatically got create incase you are on the pyspark shell. Since it does not, I predict you are running it through spark-submit. In that case, add the below boiler plate code to get your script running....
1
2016-06-23T06:14:09Z
[ "python", "apache-spark", "pyspark" ]
Python - convert list to dict
37,979,641
<p>I have the following list:</p> <pre><code>l = [('Alice',12),('Bob',10),('Celine',11)] </code></pre> <p>I want to get the following <code>dict</code> (as correctly pointed in a comment below, this is not a dict. In reality, I just want a list of dicts):</p> <pre><code>[ {'name':'Alice','age':12}, {'name':'...
-6
2016-06-22T23:06:22Z
37,979,693
<p>You can create a <em>list of dictionaries</em> this way</p> <pre><code>d = [{'name': x[0], 'age': x[1]} for x in l] </code></pre> <p>Your example had a <em>set/dictionary? of dictionaries</em> which isn't really possible since dictionaries can't be hashed, and therefore can be used in sets or as dictionary keys.</...
2
2016-06-22T23:11:35Z
[ "python", "list", "python-2.7", "dictionary", "dict-comprehension" ]
Python - convert list to dict
37,979,641
<p>I have the following list:</p> <pre><code>l = [('Alice',12),('Bob',10),('Celine',11)] </code></pre> <p>I want to get the following <code>dict</code> (as correctly pointed in a comment below, this is not a dict. In reality, I just want a list of dicts):</p> <pre><code>[ {'name':'Alice','age':12}, {'name':'...
-6
2016-06-22T23:06:22Z
37,979,714
<p>That would be a list of dictionaries, since each entry has to have a key in order for the whole thing to be a dictionary.</p> <p>You can make one with a dictionary inside a list comprehension like this:</p> <pre><code>[{'name': name, 'age': age} for name, age in l] </code></pre> <p>Also note that while dictionari...
2
2016-06-22T23:13:38Z
[ "python", "list", "python-2.7", "dictionary", "dict-comprehension" ]
Parse BeautifulSoup element into Selenium
37,979,644
<p>I want to get the source code of a website using selenium; find a particular element using BeautifulSoup; and then parse it back into selenium as a selenium.webdriver.remote.webelement object. Like so:</p> <pre><code>driver.get("www.google.com") soup = BeautifulSoup(driver.source) element = soup.find(title="Search"...
2
2016-06-22T23:06:35Z
37,979,715
<p>I don't know of any way to pass from bs4 to selenium but you can just use selenium to find the element:</p> <pre><code>driver.find_element_by_xpath('//input[@title="Search"]').click() </code></pre> <p>Or to find using just the title text like your bs4 find:</p> <pre><code>driver.find_element_by_xpath('//*[@title=...
0
2016-06-22T23:13:47Z
[ "python", "html", "selenium", "beautifulsoup" ]
Using ManyToMany through correctly for complex model in django
37,979,749
<p>I have a semi complex model relationship in my django app.</p> <p>I have a Group (a business) which can have many locations So </p> <p>A group can have many providers (person) as well. The thing is, the Provider is connected to a particular group through the group location. That is to say a provider can have that...
1
2016-06-22T23:17:07Z
37,980,278
<blockquote> <p>My question is, does my Group (and/or Provider) model need to have some sort of relationship specified in their model definitions?</p> </blockquote> <p>Yes a many to many relationship. And you only need to define it for one model or the other because many to many can be traversed in both direction....
1
2016-06-23T00:18:18Z
[ "python", "django", "django-models" ]
Counting match between two arrays at same index position and having non zero values
37,979,785
<p>I have two arrays as below:</p> <pre><code>b = array([[1, 0, 1], [0, 0, 1]]) c = array([[ 0.5 , 0. ], [ 0.34, 1. ], [ 0. , 1. ]]) </code></pre> <p>How to count matching values of two arrays based on same index value AND the element value of the array should non zero. Here ...
0
2016-06-22T23:20:57Z
37,979,914
<p>Your critical problem is checking that the "non-zero" values are equal: you need an <strong>and</strong> here, not <strong>==</strong>:</p> <pre><code> sum += np.sum((b[x,:]!=0) &amp; (c[:,x]!=0)) </code></pre> <p>This yields the desired result of <strong>2</strong>.</p> <pre><code>import numpy as np b = np.a...
1
2016-06-22T23:35:34Z
[ "python", "numpy" ]
Django - How to sort through a queryset based on the value of an attribute
37,979,899
<p>I have created the following model which stores information for an html5 banner. I have a ForeignKey to associate the banner with a specific project.</p> <pre><code>class BannerCode(models.Model): ROUNDS_LIST = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'),...
1
2016-06-22T23:33:22Z
37,981,337
<p>In your view:</p> <pre><code>banners = BannerCode.objects.all().order_by('review_round') </code></pre> <p>***if you want to reverse order use <code>'-review_round'</code></p> <p>Then in your template:</p> <pre><code>{% for item in banners %} &lt;li&gt;{{ item.name }}&lt;/li&gt; {% endfor %} </code></pre>
0
2016-06-23T02:28:03Z
[ "python", "django" ]
Django - How to sort through a queryset based on the value of an attribute
37,979,899
<p>I have created the following model which stores information for an html5 banner. I have a ForeignKey to associate the banner with a specific project.</p> <pre><code>class BannerCode(models.Model): ROUNDS_LIST = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'),...
1
2016-06-22T23:33:22Z
37,982,206
<p>you change <code>{{ b.review_round }}</code> in you template to <code>{{ b.name }}</code></p>
0
2016-06-23T04:12:14Z
[ "python", "django" ]
Django - How to sort through a queryset based on the value of an attribute
37,979,899
<p>I have created the following model which stores information for an html5 banner. I have a ForeignKey to associate the banner with a specific project.</p> <pre><code>class BannerCode(models.Model): ROUNDS_LIST = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'),...
1
2016-06-22T23:33:22Z
37,982,369
<p>In this scenario you're either going to have to have different sections in your template for the different review rounds, or define the context for your template differently to render the headers.</p> <p>Here's an example which defines the variable <code>review_round_groups</code> to hold our template context. <co...
0
2016-06-23T04:30:29Z
[ "python", "django" ]
Remove backslash with str.translate
37,979,920
<p>I wrote the following Python2.7 code to remove digits and the backslash character (\) from some string. I attempted to use the str.translate method, because I had learned that it is very efficient. The code below successfully removed digits from the string x, but is unable to remove the single backslash in y. What d...
0
2016-06-22T23:36:31Z
37,979,960
<p>You don't have any strings with backslashes. <code>x</code> has the characters <code>'x'</code>, <code>'b'</code>, and <code>'7'</code>, while <code>y</code> has a single character, <code>'·'</code>, denoted by the hex code <code>b7</code>. If you want the literal string <code>'\xb7'</code>, with four characters in...
1
2016-06-22T23:40:21Z
[ "python", "string", "python-2.7" ]
Remove backslash with str.translate
37,979,920
<p>I wrote the following Python2.7 code to remove digits and the backslash character (\) from some string. I attempted to use the str.translate method, because I had learned that it is very efficient. The code below successfully removed digits from the string x, but is unable to remove the single backslash in y. What d...
0
2016-06-22T23:36:31Z
37,979,991
<p>Your algorithm works much better when there's actually a backslash to remove. Tigerhawk already showed you your hexadecimal string. Here's another simplistic example to help, showing the unchanged original <strong>y</strong>.</p> <pre><code>import string x = 'xb7' y = '\\xb7' print x, y kill = '\\' + string.digit...
0
2016-06-22T23:45:38Z
[ "python", "string", "python-2.7" ]
Scrapy: Requesting a different html inside parse()
37,979,924
<p>Is it possible to request a new HTML while inside parse?</p> <p>My code currently is reading HTML links in a CSV file and then putting all links on it in the <code>start_urls</code> list.</p> <p>What I want to happen is when it gets a link on <code>start_urls</code>, parses it, loops on all pages until it satisfie...
1
2016-06-22T23:36:58Z
37,980,613
<p>I think you can do something like this. Note that while statements were replaced and code looks much nicer. Yo may want to do a recursive algorithm to resolve this, but I'm not sure what exactly you want to acomplish. The following code is not tested.</p> <pre><code> ... for url in start_urls: entry...
0
2016-06-23T01:01:08Z
[ "python", "scrapy", "scrapy-spider" ]
Scrapy: Requesting a different html inside parse()
37,979,924
<p>Is it possible to request a new HTML while inside parse?</p> <p>My code currently is reading HTML links in a CSV file and then putting all links on it in the <code>start_urls</code> list.</p> <p>What I want to happen is when it gets a link on <code>start_urls</code>, parses it, loops on all pages until it satisfie...
1
2016-06-22T23:36:58Z
37,982,450
<p>Fixed it after a 4 hours.</p> <p>I learned how to use Scrapy's "self.make_requests_from_url" and <code>yield</code> command in python.</p> <p>Fixed code:</p> <pre><code>with open('C:\Users\MDuh\Desktop\scrape\scrappy_demo.csv', 'rb') as csvfile: linkreader = csv.reader(csvfile, dialect=csv.excel) for row in linkr...
0
2016-06-23T04:37:19Z
[ "python", "scrapy", "scrapy-spider" ]
How can I output a dictionary in a class?
37,979,934
<p>So I got a class like this:</p> <pre><code>class Useraccount(): def __init__(self, saving, checking, PIN): self.save = saving self.check = checking self.passwd = PIN </code></pre> <p>I want a output like this:</p> <pre><code>&gt;&gt;&gt; a = Useraccount(2000,3000,1234) &gt;&gt;&gt; a &gt;&gt;&gt; {12...
-1
2016-06-22T23:38:03Z
37,980,144
<p>Other answers modify <code>__repr__</code>, which only affects the string representation. To actually output a dictionary, you can define a method within UserAccount that returns in the specific format:</p> <pre><code>class UserAccount(object): def __init__(self, saving, checking, PIN): self.save = sav...
1
2016-06-23T00:02:11Z
[ "python" ]
How can I output a dictionary in a class?
37,979,934
<p>So I got a class like this:</p> <pre><code>class Useraccount(): def __init__(self, saving, checking, PIN): self.save = saving self.check = checking self.passwd = PIN </code></pre> <p>I want a output like this:</p> <pre><code>&gt;&gt;&gt; a = Useraccount(2000,3000,1234) &gt;&gt;&gt; a &gt;&gt;&gt; {12...
-1
2016-06-22T23:38:03Z
37,980,146
<p>You can define a <code>__repr__</code> method on the Class that formats it's print output.</p> <pre><code>class Useraccount(): def __init__(self, saving, checking, PIN): self.save = saving self.check = checking self.passwd = PIN def __repr__(self): return '&lt;Useraccount({...
0
2016-06-23T00:02:25Z
[ "python" ]
How can I output a dictionary in a class?
37,979,934
<p>So I got a class like this:</p> <pre><code>class Useraccount(): def __init__(self, saving, checking, PIN): self.save = saving self.check = checking self.passwd = PIN </code></pre> <p>I want a output like this:</p> <pre><code>&gt;&gt;&gt; a = Useraccount(2000,3000,1234) &gt;&gt;&gt; a &gt;&gt;&gt; {12...
-1
2016-06-22T23:38:03Z
37,980,186
<p>so, if you are using Python2.x then you should override the <strong>unicode</strong> method to represent a object of your Useraccount class.</p> <pre><code>def __unicode__(self): return '{%d: [%d,%d]}' % (self.save, self.check, self.passwd) </code></pre> <p>and if u are using Python3.x</p> <pre><code>def __st...
0
2016-06-23T00:06:54Z
[ "python" ]
How can I output a dictionary in a class?
37,979,934
<p>So I got a class like this:</p> <pre><code>class Useraccount(): def __init__(self, saving, checking, PIN): self.save = saving self.check = checking self.passwd = PIN </code></pre> <p>I want a output like this:</p> <pre><code>&gt;&gt;&gt; a = Useraccount(2000,3000,1234) &gt;&gt;&gt; a &gt;&gt;&gt; {12...
-1
2016-06-22T23:38:03Z
38,364,009
<p>This seems to be doing what you describe:</p> <pre><code>class Useraccount(object): def __new__(cls, save, check, pin): return {saving: [check, pin]} </code></pre> <p>Example:</p> <pre><code>a = Useraccount(2000, 3000, 1234) a Out[53]: {2000: [3000, 1234]} </code></pre> <p>Not sure if it's a good pr...
0
2016-07-14T01:09:35Z
[ "python" ]
.py files default to Xcode on Mac?
37,979,941
<p>When I open a .py file on my Mac it opens in Xcode but wont run. Why does this happen and how do I fix this? </p> <p>Xcode doesn't seem to recognize Python syntax. How do I fix this? (for example <code>True</code> and <code>False</code> are not recognized as keywords)</p>
0
2016-06-22T23:38:28Z
37,980,181
<p>The default application for .py files on Mac is set to open in Xcode. Usually at installation time, you're provided with a list of checkboxes of extensions to associate with the program you're installing.</p> <p>To fix this, follow this tutorial: <a href="http://www.imore.com/how-change-default-apps-os-x" rel="nof...
0
2016-06-23T00:06:31Z
[ "python", "xcode" ]
having two input matrices in regression
37,979,956
<p>I wish to learn some coefficients of which some are sparse, and others are simply regularised as usual. The sparse part is done keeping Relevance Vector Machines in mind. My model is as follows:</p> <pre><code>with pm.Model() as model: b0 = pm.Normal('b0',mu=0,sd=10) beta = pm.Normal('beta',mu=0,sd=30,shape...
0
2016-06-22T23:40:02Z
38,037,685
<p>In the above, you are multiplying the vector of coefficients and matrix of data element-wise. You should take their dot product instead. For example:</p> <pre><code>x_train.dot(beta) </code></pre>
2
2016-06-26T10:45:36Z
[ "python", "theano", "bayesian", "pymc3" ]
Using regex to deal with escape characters in URLs
37,980,061
<p>I'm in the process of tokenizing strings which contain URLs. Here is the part I use to pick up the URLs:</p> <pre><code>regex_str = [r'http[s]?://(?:[a-z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-f][0-9a-f]))+'] </code></pre> <p>It picks up "regular" URLs perfectly fine; however some of the URLs look like this:</p>...
0
2016-06-22T23:54:04Z
37,980,188
<p>As pointed out in this <a href="http://stackoverflow.com/questions/1856785/characters-allowed-in-a-url">other question</a>, you can't add a "\" in a url. You regex seems ok to me, i've tested <a href="http://regexr.com/3dm7s" rel="nofollow">against regxr</a>. The only thing I've done is scape the backslashes after ...
0
2016-06-23T00:07:09Z
[ "python", "regex", "token", "tokenize" ]
Using regex to deal with escape characters in URLs
37,980,061
<p>I'm in the process of tokenizing strings which contain URLs. Here is the part I use to pick up the URLs:</p> <pre><code>regex_str = [r'http[s]?://(?:[a-z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-f][0-9a-f]))+'] </code></pre> <p>It picks up "regular" URLs perfectly fine; however some of the URLs look like this:</p>...
0
2016-06-22T23:54:04Z
37,992,387
<p>Calling <code>re.sub</code> before you apply the regex would work</p> <pre><code>re.sub(r"\\","",r"https:\/\/abc.com\/defg") </code></pre>
0
2016-06-23T12:59:23Z
[ "python", "regex", "token", "tokenize" ]
Objects in column of csv file are lists. How do I combine these into one giant list using Python?
37,980,119
<p>I have a csv file whose columns consists entirely of lists like ['spam', 'eggs', ..., 'spam']. Ideally I want to aggregate all of these lists together into one giant list, but am running into trouble doing that; initially I thought something like:</p> <pre><code>import csv with open(&lt;filepath&gt;, 'r') as csvfil...
0
2016-06-22T23:59:10Z
37,980,354
<p>A file containing <code>['spam', 'eggs', 'spam', 'eggs']</code> is not a CSV file. The content appears more like a string literal version of a Python list. Given that you might be better off treating them as Python list literals, and parsing them with <code>ast.literal_eval()</code>:</p> <pre><code>from ast import ...
0
2016-06-23T00:28:11Z
[ "python", "csv" ]
Automatic test input causes end of file error with python
37,980,153
<p>I am currently writing a program that is supposed to return certain values when it completes, but the system that tests it is a black box (don't know how it tests the program), and even though I think it would work if I ran the program by itself, the automated tester always raises an end of file error when it encoun...
0
2016-06-23T00:03:21Z
38,020,551
<p>It is quite possible that the tester is not supplying any input at all. In which case, you (I) have to supply the values in the program itself, not as input but as defined values.</p>
0
2016-06-24T19:11:48Z
[ "python", "input" ]
Python Code Error - Sum of Numbers
37,980,283
<p>This is the error code that I am getting with the Python Run Command, I have tried multiple ways to work this out with no answers. Can anyone point out what I am doing wrong and how to fix it?</p> <pre><code>Traceback (most recent call last): File "J:\Python\SumOfNumbers.py", line 24, in &lt;module&gt; main () File...
-5
2016-06-23T00:19:12Z
37,980,314
<p>In your code, you write</p> <pre><code>total += float(num) </code></pre> <p>However, num is not the name of the variable. You should have written</p> <pre><code>total += float(number) </code></pre>
0
2016-06-23T00:23:33Z
[ "python" ]
Python Code Error - Sum of Numbers
37,980,283
<p>This is the error code that I am getting with the Python Run Command, I have tried multiple ways to work this out with no answers. Can anyone point out what I am doing wrong and how to fix it?</p> <pre><code>Traceback (most recent call last): File "J:\Python\SumOfNumbers.py", line 24, in &lt;module&gt; main () File...
-5
2016-06-23T00:19:12Z
37,980,436
<p>Here you go. The variable called num wasn't initialized, in your program it was called number. Watch out you indents as python uses them to define code blocks.</p> <pre><code>def main(): line = '' total = 0.0 number = 0.0 # Open numbers.txt file and make sure that numbers.txt is in the same # f...
0
2016-06-23T00:38:19Z
[ "python" ]
Python Find minimum object using special comparator
37,980,286
<p>So I got <a href="https://stackoverflow.com/questions/37973944/minimax-python-how-to-efficiently-find-alternating-max-and-mins-in-a-tree/37974066#37974066">my question answered</a> on how to find the minimum value, but what if I want the minimum object? Can we similarly simplify this code?</p> <pre><code> mi...
1
2016-06-23T00:19:19Z
37,980,702
<p>You know your types (list/tuples) and how to adjust them, so you can use technique like this:</p> <pre><code>list_min = [1,2,3,4] # list to demonstrate m = lambda mn,lst: filter(lambda x: x &lt;mn,lst) # get the minimum out of list minimum = 3 # test value print m(minimum,list_min) </code></pre>
0
2016-06-23T01:12:46Z
[ "python", "comparator" ]
Python Find minimum object using special comparator
37,980,286
<p>So I got <a href="https://stackoverflow.com/questions/37973944/minimax-python-how-to-efficiently-find-alternating-max-and-mins-in-a-tree/37974066#37974066">my question answered</a> on how to find the minimum value, but what if I want the minimum object? Can we similarly simplify this code?</p> <pre><code> mi...
1
2016-06-23T00:19:19Z
37,980,833
<p>Use built-in function <a href="https://docs.python.org/2/library/functions.html#min" rel="nofollow">min(iterable[, key])</a>:</p> <pre><code>&gt;&gt;&gt; class Foo(object): ... def __init__(self, value): ... self.value = value ... &gt;&gt;&gt; &gt;&gt;&gt; l = [Foo(2), Foo(1), Foo(3)] &gt;&gt;&gt; &gt;&...
1
2016-06-23T01:29:50Z
[ "python", "comparator" ]
Python Find minimum object using special comparator
37,980,286
<p>So I got <a href="https://stackoverflow.com/questions/37973944/minimax-python-how-to-efficiently-find-alternating-max-and-mins-in-a-tree/37974066#37974066">my question answered</a> on how to find the minimum value, but what if I want the minimum object? Can we similarly simplify this code?</p> <pre><code> mi...
1
2016-06-23T00:19:19Z
37,980,987
<p>I used the answer I selected plus the answer from my other question to use this:</p> <pre><code>minChild = min(currentRoot.children, key = lambda child: child.score) </code></pre>
0
2016-06-23T01:47:17Z
[ "python", "comparator" ]
Indexing matrix with values from vector in theano
37,980,327
<p>I'm working on a cost function in theano and faced the following problem: I have a matrix M (say <code>[[3,4],[5,6]]</code>), a vector v (<code>[0,1]</code>) and I would like to get the vector of entries in M corresponding to the indexes contained in v (here <code>[3,6]</code>). Is there a command to do exactly that...
0
2016-06-23T00:24:58Z
37,980,406
<p>This should work. </p> <pre><code>VecOut = [M[i][j] for i,j in enumerate(V)] </code></pre> <p>enumerate returns indices and vector values to i (row index) and j (value of vector component), which can be used to get corresponding values from matrix.</p> <p>example:</p> <p><a href="http://i.stack.imgur.com/x5kZR....
0
2016-06-23T00:34:17Z
[ "python", "matrix", "vector", "indexing", "theano" ]
Getting index of an array value
37,980,417
<p>I have two arrays as follows: </p> <pre><code>e = np.array([True, False, True, True]) f = np.array([True, False, False, True]) </code></pre> <p>I want to get the index <code>i</code> where <code>e[i] and f[i] == True</code>.</p> <p>The expected output for the above will be:</p> <pre><code>[0,3] since e[0] ==...
0
2016-06-23T00:35:22Z
37,980,455
<p>You can just use a list comprehension to pick them out:</p> <pre><code>&gt;&gt;&gt; e = np.array([True, False, True, True]) &gt;&gt;&gt; f = np.array([True, False, False, True]) &gt;&gt;&gt; [i for i,v in enumerate(e&amp;f, 1) if v] [1, 4] </code></pre> <p>Using <a href="https://docs.python.org/3/library/funct...
1
2016-06-23T00:40:55Z
[ "python", "numpy" ]
Getting index of an array value
37,980,417
<p>I have two arrays as follows: </p> <pre><code>e = np.array([True, False, True, True]) f = np.array([True, False, False, True]) </code></pre> <p>I want to get the index <code>i</code> where <code>e[i] and f[i] == True</code>.</p> <p>The expected output for the above will be:</p> <pre><code>[0,3] since e[0] ==...
0
2016-06-23T00:35:22Z
37,980,469
<p>Take a look at numpy.where in the docs</p> <pre><code>np.where(e&amp;f)[0] </code></pre> <p>Outputs:</p> <pre><code> array([0, 3]) </code></pre>
3
2016-06-23T00:42:41Z
[ "python", "numpy" ]
Getting index of an array value
37,980,417
<p>I have two arrays as follows: </p> <pre><code>e = np.array([True, False, True, True]) f = np.array([True, False, False, True]) </code></pre> <p>I want to get the index <code>i</code> where <code>e[i] and f[i] == True</code>.</p> <p>The expected output for the above will be:</p> <pre><code>[0,3] since e[0] ==...
0
2016-06-23T00:35:22Z
37,980,474
<p>or simply this </p> <pre><code>np.where(e&amp;f) </code></pre>
1
2016-06-23T00:43:11Z
[ "python", "numpy" ]
Getting index of an array value
37,980,417
<p>I have two arrays as follows: </p> <pre><code>e = np.array([True, False, True, True]) f = np.array([True, False, False, True]) </code></pre> <p>I want to get the index <code>i</code> where <code>e[i] and f[i] == True</code>.</p> <p>The expected output for the above will be:</p> <pre><code>[0,3] since e[0] ==...
0
2016-06-23T00:35:22Z
37,980,547
<p>Something else if you don't want to be dependent on numpy:</p> <pre><code>e=[True, False, True, True] f=[True, False, False, True] for idx, val in enumerate(e): if cmp(e[idx], f[idx]) is 0: print idx+1, val </code></pre>
1
2016-06-23T00:51:57Z
[ "python", "numpy" ]
Using SSHTunnelForwarder to connect to a MySQL db via SSH
37,980,493
<p>I am trying to connect to a mysql db over ssh in python, but am getting an error. I have the following saved in a python file 'forward.py'. My code is as follows:</p> <p>forward.py</p> <pre><code>from sshtunnel import SSHTunnelForwarder import MySQLdb with SSHTunnelForwarder( ('ssh_host', 22), ssh_pa...
1
2016-06-23T00:45:43Z
38,002,620
<p>I think your issue lies in the fact that you're creating a local SSH tunnel but attempting to connect directly to a remote host, which defeats the purpose of using a SSH tunnel.</p> <p>I believe if you change your connection string from <code>host='mysql_host'</code> to <code>host='127.0.0.1'</code> you will have s...
0
2016-06-23T22:01:00Z
[ "python", "mysql", "ssh", "mysql-python" ]
Using SSHTunnelForwarder to connect to a MySQL db via SSH
37,980,493
<p>I am trying to connect to a mysql db over ssh in python, but am getting an error. I have the following saved in a python file 'forward.py'. My code is as follows:</p> <p>forward.py</p> <pre><code>from sshtunnel import SSHTunnelForwarder import MySQLdb with SSHTunnelForwarder( ('ssh_host', 22), ssh_pa...
1
2016-06-23T00:45:43Z
38,104,150
<p>If you're using SSH tunnel forwarding you need to connect to the 'localhost:3306' instead of your actual 'mysql-host:3306'.</p> <p>Let me explain what happened:</p> <ol> <li>You establish connection with SSH to the remote mysql host</li> <li>Your client setup tunnel and listen for TCP:3306 on your local host: loca...
0
2016-06-29T15:34:57Z
[ "python", "mysql", "ssh", "mysql-python" ]
How to assert if I have specific unique values in a subdictionary?
37,980,506
<pre><code>dictionary = {'key01' : {'value_a': 1, 'value_b': 4, 'value_c': 1, 'value_d': 1}, 'key02' : {'value_a': 2, 'value_b': 5, 'value_c': 2, 'value_d': 6}, 'key03' : {'value_a': 3, 'value_b': 6, 'value_c': 2, 'value_d': 9}} </code></pre> <p>Each <code>value_a</code> must be unique in compa...
1
2016-06-23T00:46:58Z
37,980,598
<p>Here you go:</p> <pre><code>dictionary = { 'key01': { 'value_a': 1, 'value_b': 4, 'value_c': 1, 'value_d': 1 }, 'key02': { 'value_a': 2, 'value_b': 5, 'value_c': 2, 'value_d': 6 }, 'key03': { 'value_a': 3, 'value_b': 6, 'value_c': 2, 'value_d': 9 } } for key_first, key_second in itert...
2
2016-06-23T00:58:53Z
[ "python", "python-2.7", "python-3.x", "dictionary" ]
How to assert if I have specific unique values in a subdictionary?
37,980,506
<pre><code>dictionary = {'key01' : {'value_a': 1, 'value_b': 4, 'value_c': 1, 'value_d': 1}, 'key02' : {'value_a': 2, 'value_b': 5, 'value_c': 2, 'value_d': 6}, 'key03' : {'value_a': 3, 'value_b': 6, 'value_c': 2, 'value_d': 9}} </code></pre> <p>Each <code>value_a</code> must be unique in compa...
1
2016-06-23T00:46:58Z
37,980,620
<p>You can convert the dictionary to a data frame and then check the unique values of each row for which we can check if the length of the row and the size of the unique values <code>(set(row))</code> are the same, if not, throw an exception:</p> <pre><code>import pandas as pd df = pd.DataFrame(dictionary) df # ...
1
2016-06-23T01:02:12Z
[ "python", "python-2.7", "python-3.x", "dictionary" ]
How to assert if I have specific unique values in a subdictionary?
37,980,506
<pre><code>dictionary = {'key01' : {'value_a': 1, 'value_b': 4, 'value_c': 1, 'value_d': 1}, 'key02' : {'value_a': 2, 'value_b': 5, 'value_c': 2, 'value_d': 6}, 'key03' : {'value_a': 3, 'value_b': 6, 'value_c': 2, 'value_d': 9}} </code></pre> <p>Each <code>value_a</code> must be unique in compa...
1
2016-06-23T00:46:58Z
37,980,627
<p>Lets generalise it and assume that the subdictionaries may contain different keys. Then lets find the distinct keys (eg <code>value_1</code>, <code>value_2</code>, ...) across all of the values in <code>dictionary</code></p> <pre><code>value_keys = set.union(*(set(v) for v in dictionary.values())) </code></pre> <...
2
2016-06-23T01:03:18Z
[ "python", "python-2.7", "python-3.x", "dictionary" ]
How to assert if I have specific unique values in a subdictionary?
37,980,506
<pre><code>dictionary = {'key01' : {'value_a': 1, 'value_b': 4, 'value_c': 1, 'value_d': 1}, 'key02' : {'value_a': 2, 'value_b': 5, 'value_c': 2, 'value_d': 6}, 'key03' : {'value_a': 3, 'value_b': 6, 'value_c': 2, 'value_d': 9}} </code></pre> <p>Each <code>value_a</code> must be unique in compa...
1
2016-06-23T00:46:58Z
37,980,693
<p>Here is a super long list comprehension I came up with:</p> <pre><code>assrt( False not in [[False if list(set([dictionary[k][val] for k in [key for key in dictionary.keys()]])) != [dictionary[k][val] for k in [key for key in dictionary.keys()]] else True] for val in dictionary["key01"].keys()]) </code></pre> <p...
0
2016-06-23T01:12:16Z
[ "python", "python-2.7", "python-3.x", "dictionary" ]
Writing a txt file in Python with Apache
37,980,533
<p>Sorry if the title is vague, but what I'm trying to do is create a text file and populate it with whatever the user types in an html form. So far I have a standard form called "pathBox" and I want to save whatever the user types in that box to a text file in the "settings" directory. I have tried the basic:</p> <pr...
0
2016-06-23T00:50:18Z
38,003,720
<p>I figured it out. It was a permissions error. My script was trying to write to a folder that it didn't have write permissions to. </p>
0
2016-06-24T00:00:02Z
[ "python", "apache" ]
Writing piece-wise functions in TensorFlow / if then in TensorFlow
37,980,543
<p>How do I write a piece-wise TensorFlow function i.e. a function that has an if-statement inside it?</p> <p>Current code</p> <pre><code>import tensorflow as tf my_fn = lambda x : x ** 2 if x &gt; 0 else x + 5 with tf.Session() as sess: x = tf.Variable(tf.random_normal([100, 1])) output = tf.map_fn(my_fn, x) </...
0
2016-06-23T00:51:19Z
37,986,180
<p>You should take a look at <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/control_flow_ops.html#select" rel="nofollow"><code>tf.select</code></a>.</p> <p>For your example, you could do:</p> <pre class="lang-py prettyprint-override"><code>condition = tf.greater(x, 0) res = tf.select(condition, tf....
1
2016-06-23T08:31:22Z
[ "python", "tensorflow" ]
Writing piece-wise functions in TensorFlow / if then in TensorFlow
37,980,543
<p>How do I write a piece-wise TensorFlow function i.e. a function that has an if-statement inside it?</p> <p>Current code</p> <pre><code>import tensorflow as tf my_fn = lambda x : x ** 2 if x &gt; 0 else x + 5 with tf.Session() as sess: x = tf.Variable(tf.random_normal([100, 1])) output = tf.map_fn(my_fn, x) </...
0
2016-06-23T00:51:19Z
37,990,135
<p>The problem here is that <code>my_fn</code> has no means of checking the condition <code>x&gt;0</code>, since <code>x</code> is a <code>tf.Tensor</code>, which means that it will be filled with values only if a tensorflow session is started and you request to run a part of the graph that includes <code>x</code>. To ...
1
2016-06-23T11:18:33Z
[ "python", "tensorflow" ]
split every 50,000 lines and write file in python
37,980,545
<p>I read files which contains 75,151 lines. I want to split every 50,000 lines. So I made 2 files, one files have 50,000 lines and the other file has 25,151 lines.</p> <p>I made code like this (INSERT_NUMBER : 50,000)</p> <pre><code> for index, data in enumerate(lines): if ((index % INSERT_NUMBER) == 0 and index ...
0
2016-06-23T00:51:40Z
37,981,058
<p>Here's one way using <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby()</code></a>:</p> <pre><code>from itertools import groupby out_filename = '/tmp/f{}.txt' lines_per_file = 50000 with open('infile.txt') as infile: for file_number, lines in ...
1
2016-06-23T01:55:32Z
[ "python" ]
Hours not being added to date object in Python
37,980,560
<p>I am using psycopg2 to insert values from a csv file into a postgres database. I need to increment my starting time by 6 hours each time I read a new line from my csv file. I am trying to accomplish this with the following:</p> <pre><code>date_product_str = '2015-03-05 12:00:00' date_product = datetime.datetime.str...
0
2016-06-23T00:53:43Z
37,980,618
<p>A <code>date</code> object has no concept of hours, minutes, seconds, or microseconds - only year, month, and day. In <code>date + timedelta</code> arithmetic - as the docs say - "<code>timedelta.seconds</code> and <code>timedelta.microseconds</code> are ignored."</p> <p>If you need to account for hours, you need ...
3
2016-06-23T01:01:53Z
[ "python", "postgresql", "csv", "psycopg2" ]
How to get __init__() to raise a more useful exception instead of TypeError when incorrect # of arguments?
37,980,612
<p>I have a class with an <strong>init</strong> that takes many arguments--some required, some not.</p> <p>If one of the needed arguments is not supplied, you may get a TypeError, with an unhelpful message like 'requires at least 10 arguments (14 given)'.</p> <p>I would like to have a custom TypeError subclass that a...
5
2016-06-23T01:01:08Z
37,981,082
<p>If you want to use kwargs, you can set in <strong>init</strong> a list of required arguments and then check if all required kwargs are present. Check out the following example.</p> <pre><code>class Something(): def __init__(self, **kwargs): required_args = ['arg_1', 'arg_2'] for arg in required...
5
2016-06-23T01:59:26Z
[ "python", "django", "typeerror" ]