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
Adding nodes to a linked list in Python
38,679,388
<p>The addToList() function takes a value as an argument. Values are passed to the addToList() function many times consecutively. </p> <pre><code>def addToList(value): node = {} node["data"] = value node["next"] = None head = node </code></pre> <p>The question is: how do I create many different nodes?...
0
2016-07-30T23:23:11Z
38,679,445
<p>There are pretty much two possibilities (unless you want to go to object oriented code, then there is a third option). For simplicity I assume that we add element in front (and not at the end) of the list.</p> <h3>global scope</h3> <p>Meaning that you have just one list at the time</p> <pre><code>head = None def ...
1
2016-07-30T23:32:57Z
[ "python", "linked-list", "nodes" ]
Python Script to Find and Move Files
38,679,463
<p>The purpose of the below python code is to find all the .jpg files included in any folder within the rootdir1 path and move all the files to the targetfolder. </p> <p>When I spot checked the work of the code, I found a few jpg that were not copied to the target folder. What am I missing in the code?</p> <pre><co...
0
2016-07-30T23:34:36Z
38,679,484
<p>You should fix the indentation:</p> <pre><code>import os import shutil RootDir1 = r'/Users/brianwuollet/Desktop/Takeout' TargetFolder = r'/Users/brianwuollet/Desktop/Photos' for root, dirs, files in os.walk((os.path.normpath(RootDir1)), topdown=False): for name in files: if name.endswith('.jpg'): ...
1
2016-07-30T23:39:34Z
[ "python", "shutil" ]
Python Script to Find and Move Files
38,679,463
<p>The purpose of the below python code is to find all the .jpg files included in any folder within the rootdir1 path and move all the files to the targetfolder. </p> <p>When I spot checked the work of the code, I found a few jpg that were not copied to the target folder. What am I missing in the code?</p> <pre><co...
0
2016-07-30T23:34:36Z
38,679,502
<p>The indentation of your code is incorrect. The lines:</p> <pre><code>SourceFolder = os.path.join(root,name) shutil.copy2(SourceFolder, TargetFolder) #copies file to target folder </code></pre> <p>will be executed only once for each directory traversed by <code>os.walk()</code> resulting in just one file being copi...
1
2016-07-30T23:43:17Z
[ "python", "shutil" ]
How to load data in chunks from a pandas dataframe to a spark dataframe
38,679,474
<p>I have read data in chunks over a pyodbc connection using something like this :</p> <pre><code>import pandas as pd import pyodbc conn = pyodbc.connect("Some connection Details") sql = "SELECT * from TABLES;" df1 = pd.read_sql(sql,conn,chunksize=10) </code></pre> <p>Now I want to read all these chunks into one sing...
1
2016-07-30T23:37:18Z
38,679,524
<p>The documentation for <a href="https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame.unionAll" rel="nofollow"><code>.unionAll()</code></a> states that it returns a new dataframe so you'd have to assign back to the <code>df2</code> DataFrame: </p> <pre><code>i = 0 for chunk in df1: ...
3
2016-07-30T23:46:19Z
[ "python", "pandas", "apache-spark", "pyspark" ]
Using user input from arcGis to chose certain csv column
38,679,516
<p>I'm currently a beginner in coding and very new in python coding.</p> <p>I actually wanted to rewrite csv file (<em>read csv and save it to another csv</em>)</p> <p>What I'm gonna ask you is how to read a certain csv column from arcGis User input.</p> <p>I use "field" datatypes and "multivalues" for input so i ca...
0
2016-07-30T23:44:55Z
38,679,636
<p>From @jedwards comment, the answer is like this:</p> <pre><code>data = [] with csvdata as csvfile: reader = csv.DictReader(csvfile, delimiter=",") for row in reader: try: new_row = [row[k] for k in headersList] data.append(new_row) except IndexError as e: ...
1
2016-07-31T00:10:18Z
[ "python", "csv", "arcgis" ]
Setting GenericForeignKey field value in Django
38,679,577
<p>I've been reading lately about the generic relations. I know that <code>GenericForeignKey</code> is to define and manaeg the generic relation using <code>ForeignKey</code> and <code>PositiveIntegerField</code> fields. I dove into the source code in search for the <code>__set__</code> method of the <code>GenericForei...
0
2016-07-30T23:57:13Z
38,679,609
<p>The <code>__set__</code> method is for <a href="https://docs.python.org/3/howto/descriptor.html" rel="nofollow">descriptors</a>.</p> <p>The following simple example will show what the arguments passed to <code>__set__</code> are:</p> <pre><code>class MyDescriptor: def __set__(self, instance, value): pr...
0
2016-07-31T00:03:25Z
[ "python", "django", "django-contenttypes" ]
Python iterating through large json file
38,679,607
<p>So ive recently been trying to learn how to use django by creating a website that enables the user to create magic the gathering decks. This question is more related to just python though and not the django framework itself.</p> <p>Anyway im trying to parse a huge json file that contains around 200 sets for MTG and...
0
2016-07-31T00:02:52Z
38,679,970
<p>It's a memory allocation error. Python dicts aren't good allocating memory with large datasets.</p> <p>You can try out other container datatypes. As namedtuples (lighter than dict):</p> <pre><code>from collections import namedtuple import json with open(yourfile) as f: json_object = json.load( f, ...
0
2016-07-31T01:29:09Z
[ "python", "json", "django" ]
Finding values based on specific categories
38,679,614
<p>I was wondering how would find estimated values based on several different categories. Two of the columns are categorical, one of the other columns contains two strings of interest and the last contain numeric values I have a csv file called sports.csv</p> <pre><code>import pandas as pd import numpy as np #loading...
0
2016-07-31T00:05:57Z
38,679,753
<p>You can create a <code>mask</code> with all your conditions specified and then use the mask for subsetting:</p> <pre><code>mask = (df['Region'] == 4) &amp; (df['Type'] == 1) &amp; \ (df['enroll'] &lt;= 260) &amp; (df['enroll'] &gt;= 240) &amp; \ df['Gym'].str.contains('Baseball') &amp; df['Gym'].str....
0
2016-07-31T00:34:37Z
[ "python", "csv", "pandas" ]
Finding values based on specific categories
38,679,614
<p>I was wondering how would find estimated values based on several different categories. Two of the columns are categorical, one of the other columns contains two strings of interest and the last contain numeric values I have a csv file called sports.csv</p> <pre><code>import pandas as pd import numpy as np #loading...
0
2016-07-31T00:05:57Z
38,679,782
<p>I had to add an instance that would actually meet your criteria, or else you will get an empty result. You want to use <code>df.loc</code> with conditions as follows:</p> <pre><code>In [1]: import pandas as pd, numpy as np, io In [2]: in_string = io.StringIO("""Region Type enroll estimates price Gym .....
0
2016-07-31T00:42:29Z
[ "python", "csv", "pandas" ]
Slicing a Python list with a NumPy array of indices -- any fast way?
38,679,666
<p>I have a regular <code>list</code> called <code>a</code>, and a NumPy array of indices <code>b</code>.<br> (No, it is not possible for me to convert <code>a</code> to a NumPy array.)</p> <p>Is there any way for me to the same effect as "<code>a[b]</code>" efficiently? To be clear, this implies that I don't want to...
3
2016-07-31T00:15:49Z
38,679,861
<pre><code>a = list(range(1000000)) b = np.random.randint(0, len(a), 10000) %timeit np.array(a)[b] 10 loops, best of 3: 84.8 ms per loop %timeit [a[x] for x in b] 100 loops, best of 3: 2.93 ms per loop %timeit operator.itemgetter(*b)(a) 1000 loops, best of 3: 1.86 ms per loop %timeit np.take(a, b) 10 loops, best of...
3
2016-07-31T01:00:39Z
[ "python", "arrays", "performance", "numpy", "optimization" ]
Slicing a Python list with a NumPy array of indices -- any fast way?
38,679,666
<p>I have a regular <code>list</code> called <code>a</code>, and a NumPy array of indices <code>b</code>.<br> (No, it is not possible for me to convert <code>a</code> to a NumPy array.)</p> <p>Is there any way for me to the same effect as "<code>a[b]</code>" efficiently? To be clear, this implies that I don't want to...
3
2016-07-31T00:15:49Z
38,680,028
<p>Write a cython function:</p> <pre><code>import cython from cpython cimport PyList_New, PyList_SET_ITEM, Py_INCREF @cython.wraparound(False) @cython.boundscheck(False) def take(list alist, Py_ssize_t[:] arr): cdef: Py_ssize_t i, idx, n = arr.shape[0] list res = PyList_New(n) object obj ...
3
2016-07-31T01:45:55Z
[ "python", "arrays", "performance", "numpy", "optimization" ]
how could i generate larger sample that its population?
38,679,725
<pre><code>import random random.sample(range(10,18),100) Traceback (most recent call last): File "&lt;ipython-input-6-f5d60cc38869&gt;", line 1, in &lt;module&gt; random.sample(range(10,18),100) File "C:\Users\shamsul\Anaconda3\lib\random.py", line 315, in sample raise ValueError("Sample larger than popu...
0
2016-07-31T00:27:44Z
38,679,745
<pre><code>sample = [random.randrange(10,18) for _ in range(100)] </code></pre> <p>So <a href="https://en.wikipedia.org/wiki/Pigeonhole_principle" rel="nofollow">obviously you're going to have repeats</a>, because the sample is larger than the population, but this will give you an evenly distributed sample. Generally ...
2
2016-07-31T00:31:51Z
[ "python" ]
FindRootTest not working
38,679,763
<pre class="lang-none prettyprint-override"><code>File "/Users/SalamonCreamcheese/Documents/4.py", line 31, in &lt;module&gt; testFindRoot() File "/Users/SalamonCreamcheese/Documents/4.py", line 29, in testFindRoot print " ", result**power, " ~= ", x TypeError: unsupported operand type(s) for ** or pow(): 'tupl...
1
2016-07-31T00:36:30Z
38,679,805
<p>After</p> <pre><code>result = (x, power, epsilon) </code></pre> <p><code>result</code> is bound to a 3-element tuple. So the error message is thoroughly accurate you're later trying to raise that tuple to the integer power <code>power</code>. Python doesn't define <code>__pow__</code> for tuples, and that's all ...
5
2016-07-31T00:46:57Z
[ "python" ]
How can I call a Subclass object from a Superclass and is there a better way to do this? (Python 3)
38,679,784
<p>I am creating a game in python(3) and I have a main class with the game loop and a bunch of variables in it. I have a subclass of this to create "path" objects, and I need the variables from the main class. I also need to call the subclass from the main, superclass. Every time I call the subclass, it also calls the ...
0
2016-07-31T00:43:03Z
38,679,902
<p>You are misunderstanding the purpose of subclasses. Inheritance isn't for sharing data, it's for making special cases of a general type. </p> <p>If <code>Sub</code> should be exactly like <code>Main</code> with a few specializations then you should use inheritance. When you say that "Sub" is a subclass of "Main", y...
2
2016-07-31T01:11:05Z
[ "python", "class", "python-3.x", "oop" ]
Gmail API: Python Email Dict appears to be Missing Keys
38,679,825
<p>I'm experiencing a strange issue that seems to be inconsistent with google's gmail API:</p> <p>If you look <a href="https://developers.google.com/gmail/api/v1/reference/users/messages#resource" rel="nofollow" title="here">here</a>, you can see that gmail's representation of an email has keys "snippet" and "id", amo...
0
2016-07-31T00:51:45Z
38,680,283
<p>As @jedwards said in his comment, just because a message 'can' contain all of the fields specified in documentation, doesn't mean it will. 'list' provides the bare minimum amount of information for each message, because it provides a lot of messages and wants to be as lazy as possible. For individual messages that I...
1
2016-07-31T02:39:41Z
[ "python", "gmail-api" ]
Flask Security rest API
38,679,884
<p><strong>Context</strong><br> I'm creating a quote generation script using Python and Digital Ocean server (Ubuntu 16.04). Here's how it works: </p> <ol> <li>End user fills out a form on HubSpot hosted website </li> <li>the form submission triggers a POST request to my server X.X.X.X:SpecificSocket</li> <li>that re...
2
2016-07-31T01:07:40Z
38,680,009
<p>The POST request will be sent <strong>unencrypted</strong> and so you should set up SLS (HTTPS). There is some very good documentation on that <a href="http://flask.pocoo.org/snippets/111/" rel="nofollow">here</a> which allows you to set up OpenSSL to serve requests with HTTPS with Flask only. Without this, all your...
0
2016-07-31T01:42:21Z
[ "python", "security", "post", "flask" ]
Flask Security rest API
38,679,884
<p><strong>Context</strong><br> I'm creating a quote generation script using Python and Digital Ocean server (Ubuntu 16.04). Here's how it works: </p> <ol> <li>End user fills out a form on HubSpot hosted website </li> <li>the form submission triggers a POST request to my server X.X.X.X:SpecificSocket</li> <li>that re...
2
2016-07-31T01:07:40Z
38,685,457
<p>Here's a <a href="https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-16-04" rel="nofollow">guide</a> from Digital Ocean on how to set up SSL. If you want to do it via Werkzeug's built-in development server, try this:</p> <pre><code>if __name__ == "__main__": contex...
0
2016-07-31T15:22:09Z
[ "python", "security", "post", "flask" ]
How Does Deque Work in Python
38,679,914
<p>I am having trouble understanding how the deque works in the snippet of code below, while trying to recreate a queue and a stack in Python.</p> <p><strong>Stack Example - Understood</strong></p> <pre><code>stack = ["a", "b", "c"] # push operation stack.append("e") print(stack) # pop operation stack.pop() print(s...
1
2016-07-31T01:14:11Z
38,679,934
<p><a href="https://docs.python.org/3/library/collections.html#collections.deque" rel="nofollow">A deque is a generalization of stack and a queue (It is short for "double-ended queue")</a>.</p> <p>Thus, the pop() operation still causes it to act like a stack, just as it would have as a list. To make it act like a queu...
4
2016-07-31T01:18:50Z
[ "python", "queue" ]
Beautiful soup just extract header of a table
38,680,057
<p>I want to extract information from the table in the following website using beautiful soup in python 3.5. </p> <pre><code>http://www.askapatient.com/viewrating.asp?drug=19839&amp;name=ZOLOFT </code></pre> <p>I have to save the web-page first, since my program needs to work off-line. </p> <p>I saved the web-page i...
1
2016-07-31T01:51:59Z
38,684,961
<p>This is because of the <em>broken HTML</em> of the page. You need to switch to a more <em>lenient parser</em> like <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser" rel="nofollow"><code>html5lib</code></a>. Here is what works for me:</p> <pre><code>from pprint import pprint impor...
1
2016-07-31T14:25:23Z
[ "python", "python-3.x", "beautifulsoup", "bs4" ]
How to I make a new line every use in openpyxl?
38,680,073
<p>I am trying to set up an easy way to mark my business' records through a python program and I am using the module openpyxl for the excel sheets part and I am wondering <strong><em>how I can make it so every time I use the program it uses the next line in the excel sheet</em></strong>. Thank you!</p> <pre><code>from...
1
2016-07-31T01:56:14Z
38,680,095
<p>You can use <a href="http://openpyxl.readthedocs.io/en/default/_modules/openpyxl/worksheet/worksheet.html" rel="nofollow"><code>ws.max_row</code></a> here. Also make sure you load the previously saved file instead of opening up a new file each time.</p> <pre><code>import openpyxl wb = openpyxl.load_workbook('sampl...
1
2016-07-31T01:58:46Z
[ "python", "excel", "openpyxl" ]
using count method to count a certain word in text file
38,680,111
<p>I'm trying to count the number of times the word 'the' appears in two books saved as text files. The code I'm running returns zero for each book.</p> <p>Here's my code:</p> <pre><code>def word_count(filename): """Count specified words in a text""" try: with open(filename) as f_obj: con...
1
2016-07-31T02:02:05Z
38,680,137
<p>Unless the word 'the' appears on the last line of each file, you'll see zeros.</p> <p>You likely want to initialize the <code>word_count</code> variable to zero then use augmented addition (<code>+=</code>):</p> <p>For example:</p> <pre><code>def word_count(filename): """Count specified words in a text""" ...
1
2016-07-31T02:06:20Z
[ "python", "file", "text", "count" ]
using count method to count a certain word in text file
38,680,111
<p>I'm trying to count the number of times the word 'the' appears in two books saved as text files. The code I'm running returns zero for each book.</p> <p>Here's my code:</p> <pre><code>def word_count(filename): """Count specified words in a text""" try: with open(filename) as f_obj: con...
1
2016-07-31T02:02:05Z
38,680,154
<p>You are re-assigning <code>word_count</code> for each iteration. That means that at the end it will be the same as the number of occurrences of <code>the</code> in the last line of the file. You should be getting the sum. Another thing: should <code>there</code> match? Probably not. You probably want to use <co...
3
2016-07-31T02:09:22Z
[ "python", "file", "text", "count" ]
using count method to count a certain word in text file
38,680,111
<p>I'm trying to count the number of times the word 'the' appears in two books saved as text files. The code I'm running returns zero for each book.</p> <p>Here's my code:</p> <pre><code>def word_count(filename): """Count specified words in a text""" try: with open(filename) as f_obj: con...
1
2016-07-31T02:02:05Z
38,680,158
<pre><code>import os def word_count(filename): """Count specified words in a text""" if os.path.exists(filename): if not os.path.isdir(filename): with open(filename) as f_obj: print(f_obj.read().lower().count('t')) else: print("is path to folder, not to fi...
0
2016-07-31T02:10:04Z
[ "python", "file", "text", "count" ]
Executing a while loop while constantly checking sensor input
38,680,152
<p>what I'm trying to do is have my RC respond to user keystroke and then drive accordingly (forward, reverse, turn left and right, etc). However, I have also mounted a sensor at the front. I want to constantly measure that reading and if it's below a threshold, it break out of the loop and the program stops. I'm havin...
0
2016-07-31T02:08:59Z
38,680,247
<p>If <code>distance()</code> function is ok it should work</p> <pre><code>d1 = distance() while (d1 &gt;= 20): d1 = distance() char = getch() if (char == "w"): drive("forward") char = "" #maybe this typo ? drive("stop") #there is no need for overlaping logic in case of 20 GPIO.cleanup() </...
0
2016-07-31T02:31:26Z
[ "python", "while-loop", "raspberry-pi", "sensor", "car" ]
In Python, how do I specify directory separator in os.path.join() function?
38,680,155
<p>I tried the code as below, attempting to change directory separator to forward slash <code>/</code> but still stuck in the backslash <code>\</code>. The documentation says the function joins paths using directory separator <code>os.sep</code>, but this didn't work in my case.</p> <pre><code>import os os.sep = '/' p...
0
2016-07-31T02:09:33Z
38,680,185
<p>You can take a look at the source code for the different operating systems. For example, the Mac version is:</p> <pre><code>def join(s, *p): path = s for t in p: if (not s) or isabs(t): path = t continue if t[:1] == ':': t = t[1:] if ':' not in ...
1
2016-07-31T02:17:42Z
[ "python", "operating-system" ]
In Python, how do I specify directory separator in os.path.join() function?
38,680,155
<p>I tried the code as below, attempting to change directory separator to forward slash <code>/</code> but still stuck in the backslash <code>\</code>. The documentation says the function joins paths using directory separator <code>os.sep</code>, but this didn't work in my case.</p> <pre><code>import os os.sep = '/' p...
0
2016-07-31T02:09:33Z
38,680,204
<p>I think <a href="http://stackoverflow.com/a/12086287/3165737">this</a> answers the questions why Python uses a particular separator.</p> <p>That said, you can use the <a href="https://docs.python.org/3.5/library/pathlib.html#module-pathlib" rel="nofollow"><code>Pathlib</code></a> module to construct your paths and ...
1
2016-07-31T02:22:42Z
[ "python", "operating-system" ]
In Python, how do I specify directory separator in os.path.join() function?
38,680,155
<p>I tried the code as below, attempting to change directory separator to forward slash <code>/</code> but still stuck in the backslash <code>\</code>. The documentation says the function joins paths using directory separator <code>os.sep</code>, but this didn't work in my case.</p> <pre><code>import os os.sep = '/' p...
0
2016-07-31T02:09:33Z
38,680,533
<p>You can replace function in os.path, with self own:</p> <pre><code>import os path = "public\\INSTALL\\" print("Initial unmodified join return: '%s'" % os.path.join('.', path) ) native_os_path_join = os.path.join def modified_join(*args, **kwargs): return native_os_path_join(*args, **kwargs).replace('\\', '/') o...
0
2016-07-31T03:38:36Z
[ "python", "operating-system" ]
Python: TypeError: unbound method, must be called with (class) instance
38,680,172
<p>Could someone help me understand this bug? Inside my class "Creature" I have this:</p> <pre><code>def mate_action(self): if self.mate == 1: for creature in creature_list: if creature.mate == 1: self.str_nb = (self.str + creature.str) / 2 self.attr_nb = (self.a...
0
2016-07-31T02:14:12Z
38,680,223
<p>The answer was given by @zondo. I needed to change <code>creature_list.append(Creature)</code> to <code>creature_list.append(Creature())</code></p>
0
2016-07-31T02:27:43Z
[ "python" ]
Modifying a style attribute in Selenium with execute_script, but the attribute's value doesn't change
38,680,356
<p>Using: Selenium with PhantomJS in Python</p> <p>I need to set a style attribute of an input tag to '' because it is set to "display:None" which prevents me from filling the input with send_keys in Selenium.</p> <p>I am using execute_script to achieve this. execute_script runs, but the style attribute remains unalt...
3
2016-07-31T02:59:47Z
38,680,564
<p>Try as below :-</p> <pre><code>password = driver.find_element_by_name("vb_login_password") password = driver.execute_script("arguments[0].style.display = 'block'; return arguments[0];", password) print(password.value_of_css_property("display")) #now you can set value using send_keys password.send_keys("your valu...
0
2016-07-31T03:45:21Z
[ "python", "selenium-webdriver", "phantomjs" ]
Python-3x Unicode Print vs Write
38,680,361
<p>I created the following program to try to work through what I believe to be a unicode issue:</p> <pre><code>s = '7/02/16;07:30:00;São Paulo-8;Reachability: 18.5%' s_type = type(s) print ("variable s contains: ",s) print ("variable s type is: ", s_type) text_file = open("test_file.txt", "w") text_file.write(s) text...
1
2016-07-31T03:01:40Z
38,680,479
<p>Your error can be reproduced, even on systems that have different defaults, with something like:</p> <pre><code>text_file = open("test_file.txt", "w", encoding='ascii') text_file.write('\xe3') </code></pre> <p>The issue is that your default text encoding is ascii. Or at least that's what Python is understanding i...
2
2016-07-31T03:28:20Z
[ "python", "unicode" ]
How to select several rows in a dataframe based on index in pandas
38,680,381
<p>I have a DataFrame object whose label index is not a position integer but a name, how can I extract several rows:</p> <p>e.g. select the 3rd, 4th row</p> <pre><code>df.iloc[[2],[3]] </code></pre> <p>This gives me an error, telling me I could only extract one row at a time.</p>
0
2016-07-31T03:06:28Z
38,681,063
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow">loc</a> is a standard way to extract data via the labels of an index.</p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow">iloc</a> is a standard way t...
0
2016-07-31T05:32:30Z
[ "python", "pandas", "dataframe" ]
In Python, bool(a.append(3)) is False. Why?
38,680,430
<p>It seems <code>bool(a.append)</code> and <code>bool(a)</code> are all <code>True</code>, but why <code>bool(a.append(3))</code> is <code>False</code>?</p> <p>My question is from the code here:</p> <pre><code>class MovingAverage(object): def __init__(self, size): self.next = lambda v, q=collections.dequ...
-1
2016-07-31T03:18:13Z
38,680,496
<p>In Python, the following things are considered <code>False</code>. In other words, if you call <code>bool</code> with them as arguments, you get <code>False</code> back:</p> <ul> <li><code>False</code> itself.</li> <li><code>0</code>, in integer or floating point form.</li> <li>empty sequence types; strings, lists,...
6
2016-07-31T03:31:02Z
[ "python", "boolean" ]
datastax opscenter 'API' metrics error
38,680,440
<p>I am using datastax opscenter api to retrive metrics through python script and trying to match the results with the graphs on opscenter<br> While I am trying to to get data for 'TBL : LiveDisk Used' as you can see in the graph below: <a href="http://i.stack.imgur.com/nk3ec.png" rel="nofollow">enter image descripti...
1
2016-07-31T03:19:26Z
38,680,544
<p>In your screenshot, opscenter is reading the 1 minute period metrics. Your query is pulling the 2 hour period which may not have data in your start/end range (yet). Try running with <code>step:1</code>.</p>
0
2016-07-31T03:40:54Z
[ "python", "apache", "cassandra", "datastax", "opscenter" ]
Making a GET request JSON with parameters using Python
38,680,442
<p>I was wondering how do I make a GET request to a specific url with two query parameters? These query parameters contain two id numbers So far I have:</p> <pre><code>import json, requests url = 'http://' requests.post(url) </code></pre> <p>But they gave me query paramters first_id=### and last_id=###. I don't kno...
-2
2016-07-31T03:19:56Z
38,680,450
<p>To make a GET request you need the <a href="http://docs.python-requests.org/en/master/api/#requests.get" rel="nofollow"><code>get()</code> method</a>, for parameters use <code>params</code> argument:</p> <pre><code>response = requests.get(url, params={'first_id': 1, 'last_id': 2}) </code></pre> <hr> <p>If the res...
2
2016-07-31T03:22:03Z
[ "python", "json", "get" ]
Polar to Cartesian returning strange results
38,680,461
<p>I'm not sure if it's my maths or my Python which isn't up to scratch... but the code below is giving unexpected results. It still plots a circle of points, but in a strange order and a non-uniform manner (even allowing for int rounding errors) i.e. the points aren't sequential around the circle as degree increases...
2
2016-07-31T03:24:06Z
38,680,481
<p>looks like numpy is working in radians, not degrees</p>
4
2016-07-31T03:28:38Z
[ "python", "python-2.7", "math", "coordinates", "polar-coordinates" ]
Polar to Cartesian returning strange results
38,680,461
<p>I'm not sure if it's my maths or my Python which isn't up to scratch... but the code below is giving unexpected results. It still plots a circle of points, but in a strange order and a non-uniform manner (even allowing for int rounding errors) i.e. the points aren't sequential around the circle as degree increases...
2
2016-07-31T03:24:06Z
38,680,489
<p>The functions of <code>sin()</code> and <code>cos()</code> of numpy take inputs in radians instead of degrees. Converting the degrees to radians should solve your problem.</p>
2
2016-07-31T03:30:20Z
[ "python", "python-2.7", "math", "coordinates", "polar-coordinates" ]
Polar to Cartesian returning strange results
38,680,461
<p>I'm not sure if it's my maths or my Python which isn't up to scratch... but the code below is giving unexpected results. It still plots a circle of points, but in a strange order and a non-uniform manner (even allowing for int rounding errors) i.e. the points aren't sequential around the circle as degree increases...
2
2016-07-31T03:24:06Z
38,680,499
<p>Your code is fine, only problem is that the numpy.cos(angle) takes its argument in radians, not degrees. You can either change the tester to range from 0 to <code>2*numpy.pi</code> or convert the degrees to radians by adding <code>angle = 180*angle/numpy.pi</code> on line 2.</p>
2
2016-07-31T03:31:42Z
[ "python", "python-2.7", "math", "coordinates", "polar-coordinates" ]
pickle.dump blocks the main thread in multithreaded python application because of GIL
38,680,485
<p>Currently I'm using python 3.4.3 and developing PyQt5 application.</p> <p>In my app, there's a QThread, and some large object(100MB) is being (pickle) dumped by the thread.</p> <p>However, dumping that object requires 1~2 seconds, and it blocks the main thread about 1~2 seconds because of GIL.</p> <p>How can I so...
0
2016-07-31T03:29:39Z
38,712,208
<p>I solved my issue.</p> <p>The solution was </p> <ol> <li><p>Making my object really simple. In my case, I converted my object to array of simple stringified dictionaries.</p></li> <li><p>I used <code>file.write(stringified_dictionaries)</code> directly instead of using pickle. This reduced time for serializing pyt...
1
2016-08-02T05:15:13Z
[ "python", "multithreading", "cython", "pickle", "gil" ]
How to vstack efficiently a sequence of large numpy array chunks?
38,680,508
<p>I am generating a sequence of numpy arrays as follows:</p> <pre><code>def chunker(seq, size): return (seq[pos:pos + size] for pos in range(0, len(seq), size)) for i in chunker(X,10000): e = function(i) print('new marix',e) new matrix (10000, 3208) new matrix (10000, 3208) new matrix (10000, 3208) new ...
1
2016-07-31T03:34:02Z
38,680,587
<p>One way, although probably not the most efficient, would be to create a list of the lists you want to stack, then stack once, outside the loop. </p> <p>For example:</p> <pre><code>import numpy as np def chunker(seq, size): return (seq[pos:pos + size] for pos in range(0, len(seq), size)) # Some fake function...
1
2016-07-31T03:50:14Z
[ "python", "python-3.x", "numpy", "scipy" ]
ImportError: No module named google.protobuf
38,680,593
<p>I am following this guide (<a href="https://developers.google.com/protocol-buffers/docs/pythontutorial" rel="nofollow">https://developers.google.com/protocol-buffers/docs/pythontutorial</a>) and using the exact sample of addressbook.proto.</p> <p>Post the content of compiler generated addressbook_pb2.py file as wel...
1
2016-07-31T03:51:48Z
38,680,611
<p>You should run:</p> <pre><code>pip install protobuf </code></pre> <p>That will install Google protobuf and after that you can run that Python script.</p> <p>As per <a href="https://pypi.python.org/pypi/protobuf" rel="nofollow">this link</a>.</p>
1
2016-07-31T03:54:19Z
[ "python", "python-2.7", "protocol-buffers", "google-protobuf" ]
ImportError: No module named google.protobuf
38,680,593
<p>I am following this guide (<a href="https://developers.google.com/protocol-buffers/docs/pythontutorial" rel="nofollow">https://developers.google.com/protocol-buffers/docs/pythontutorial</a>) and using the exact sample of addressbook.proto.</p> <p>Post the content of compiler generated addressbook_pb2.py file as wel...
1
2016-07-31T03:51:48Z
38,682,585
<p>When <code>pip</code> tells you that you already have <code>protobuf</code>, but PyCharm (or other) tells you that you don't have it, it means that <code>pip</code> and PyCharm are using a different Python interpreter. This is a very common issue, especially on a Mac, with no standard Python package management.</p> ...
2
2016-07-31T09:28:18Z
[ "python", "python-2.7", "protocol-buffers", "google-protobuf" ]
Python concurrent.futures calling same function twice
38,680,621
<p>I have no problem using concurrent.futures if all my processes are started from different functions. But if I want to call the same function with different parameters I can't seem to get the syntax right. This is what I got so far but it doesn't work:</p> <pre><code>tasks = ((serial_port_local, serial_options_loc...
-1
2016-07-31T03:56:00Z
38,681,645
<p>It seems that serial_cross_over takes 4 arguments (correct me if I'm wrong) and you do not provide them when .map so, maybe take a look at this answer: <a href="http://stackoverflow.com/questions/6785226/pass-multiple-parameters-to-concurrent-futures-executor-map">Pass multiple parameters to concurrent.futures.Execu...
0
2016-07-31T07:09:39Z
[ "python", "concurrent-programming" ]
How to use BeautifulSoup to get content between<hr class = 'calibre2'> ... <hr class="calibre2" />
38,680,626
<pre><code>&lt;hr class="calibre2" /&gt; &lt;h3 class="calibre5"&gt;-ability&lt;/h3&gt; (in nouns 构成名词) : &lt;br class="calibre4" /&gt; &lt;blockquote class="calibre6"&gt;&lt;p class="calibre_1"&gt;&lt;span class="italic"&gt;◊ capability 能力 &lt;/span&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;blockquote clas...
1
2016-07-31T03:57:21Z
38,680,650
<p>You can loop over all <code>hr</code> elements and use <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-next-siblings-and-find-next-sibling" rel="nofollow"><code>.find_next_siblings()</code></a> to iterate over the next sibling elements. Then, if you meet <code>hr</code>, break the loop:</p> <pr...
1
2016-07-31T04:03:09Z
[ "python", "beautifulsoup", "html-parsing" ]
How to use BeautifulSoup to get content between<hr class = 'calibre2'> ... <hr class="calibre2" />
38,680,626
<pre><code>&lt;hr class="calibre2" /&gt; &lt;h3 class="calibre5"&gt;-ability&lt;/h3&gt; (in nouns 构成名词) : &lt;br class="calibre4" /&gt; &lt;blockquote class="calibre6"&gt;&lt;p class="calibre_1"&gt;&lt;span class="italic"&gt;◊ capability 能力 &lt;/span&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;blockquote clas...
1
2016-07-31T03:57:21Z
38,681,116
<p>You can check for the hr and calibre2 class in conjunction with find_all_next <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all-next-and-find-next" rel="nofollow">https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all-next-and-find-next</a> </p> <pre><code>from bs4 import BeautifulS...
0
2016-07-31T05:41:35Z
[ "python", "beautifulsoup", "html-parsing" ]
tkinter window and background image don't align properly
38,680,668
<p>I am writing a Simpsons trivia game as my first big programming project. My question is twofold:</p> <ol> <li>Is this the right way to go about creating a background image? Keep in mind that my plan is to include the Simpsons theme song playing in the background as well as one or two buttons on top of the backgroun...
1
2016-07-31T04:07:24Z
38,684,629
<p>I'm not sure I understand everything, but I managed to get rid of the border (at least on Linux) by doing:</p> <pre><code>from tkinter import * from tkinter import ttk from PIL import Image, ImageTk root = Tk() root.title("The Simpsons Trivia Game") root.geometry("400x600") root.resizable(0,0) image = Image.open(...
0
2016-07-31T13:50:39Z
[ "python", "tkinter", "python-3.4" ]
Using a proxy with phantomjs (selenium webdriver)
38,680,743
<p>I'm using phantomJS as a driver for selenium. My code is written in python. I followed the advice from similar questions, and am using the following: </p> <pre><code>service_args = [ '--proxy=78.23.244.145:80', '--proxy-type=http', ] driver = webdriver.PhantomJS(service_args=service_args) driver.get('ht...
0
2016-07-31T04:28:57Z
38,681,429
<p>I suspect that the proxy you are using is incorrect. I tried the following where used proxy behave sanely in windows 8.</p> <pre><code>from selenium.webdriver.common.proxy import * from selenium import webdriver from selenium.webdriver.common.by import By phantomjs_path = r"E:\Software &amp; Tutorial\Phantom\phanto...
1
2016-07-31T06:35:43Z
[ "python", "selenium", "proxy", "phantomjs" ]
Dataframe operations involving nan
38,680,797
<p>I want to subtract row with nan values from all rows in a Dataframe. For this I am using </p> <pre><code>dataframe.sub(row, axis= 1) </code></pre> <p>this ignores nan values, i.e. if either of the values in two rows is nan, the result is nan. I want that if either of the values is not nan, the subtraction should ...
2
2016-07-31T04:39:42Z
38,680,852
<blockquote> <p>I want that if either of the values is not nan, the subtraction should proceed taking the nan value to be 0. If both are not nan, the result should be the difference.</p> </blockquote> <p>Use <code>fillna</code> to set <code>nan</code>-values to 0, then apply a mask to reset the result to <code>nan</...
3
2016-07-31T04:50:37Z
[ "python", "numpy", "pandas" ]
Django Raw SQL query does not return todays records
38,680,844
<p>I was making a appointment system using Django! I wanted to display todays appointments. This raw query must be returning today's records but it isn't returning any record!</p> <p><strong>Query looks like this:</strong></p> <pre><code>todays_appointments = Appointment.objects.raw(""" SELECT appointment_Appoint...
0
2016-07-31T04:47:34Z
38,680,927
<p>Date is a DateField so you need to compare it to a date, not the formatted representation of the date (see this answer: <a href="http://stackoverflow.com/a/18505739/5679413">http://stackoverflow.com/a/18505739/5679413</a>). By using format, you are converting today into numbers and dashes. You're SQL query needs to ...
0
2016-07-31T05:03:17Z
[ "python", "django", "django-models" ]
What is the AUC score in sklearn.metrics?
38,680,879
<p>In <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.auc.html" rel="nofollow">here</a> it is discussed the auc score but this is different from the regular roc_auc_score. I see no description of this, what is it and what it is used for?</p>
2
2016-07-31T04:53:59Z
38,680,912
<p>As the documentation says, it is the area under an arbitrary curve, i.e., the definite integral (computed with the trapezoidal approximation). Some examples are linked at the bottom of the documentation page showing its use.</p>
1
2016-07-31T04:59:45Z
[ "python", "scikit-learn", "auc" ]
What is the AUC score in sklearn.metrics?
38,680,879
<p>In <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.auc.html" rel="nofollow">here</a> it is discussed the auc score but this is different from the regular roc_auc_score. I see no description of this, what is it and what it is used for?</p>
2
2016-07-31T04:53:59Z
38,705,540
<p><code>sklearn.auc</code> is a general fuction to calculate the area under a curve using trapezoid rule. It is used to calculate <code>sklearn.metrics.roc_auc_score</code>. </p> <p>To calculate roc_auc_score, sklearn evaluates the false positive and true positive rates using the <code>sklearn.metrics.roc_curve</code...
1
2016-08-01T18:18:35Z
[ "python", "scikit-learn", "auc" ]
Parsing JSON to CSV with Python - AttributeError: 'str' object has no attribute 'keys'
38,680,884
<p>This JSON to CSV code example is working great:</p> <pre><code>employee_data = '{"info":[{"employee_name": "James", "email": "james@gmail.com", "job_profile": "Sr. Developer"},{"employee_name": "Smith", "email": "Smith@gmail.com", "job_profile": "Project Lead"}]}' #This can be parsed and converted to CSV using pyt...
0
2016-07-31T04:55:25Z
38,680,945
<p>The problem is that your code expects the JSON keys to be arrays. This loop here:</p> <pre><code>for emp in emp_data: </code></pre> <p>Expects each top level JSON key to be iterable (loopable). On your original JSON, the key <code>info</code> maps to a list:</p> <pre><code>[{"employee_name": "James", "email (...)...
0
2016-07-31T05:06:56Z
[ "python", "json", "csv" ]
Python Tkinter: If-statement not working
38,680,932
<pre><code>from tkinter import * def callbackX(button, win, buttonNR): print("Pressed button", buttonNR) player1.append(buttonNR) win.destroy() gameScreen() def gameScreen(): win = Tk() #f = Frame(win) if '1' in player1 == 'True': b1 = Button(win, text="X", command=lambda: callba...
0
2016-07-31T05:04:32Z
38,680,980
<p>'True' is a string, just remove the quotes, as True is a bool. </p> <p>Actually, just simply use </p> <p>if '1' in player1: </p> <p>is OK in your case.</p>
1
2016-07-31T05:13:50Z
[ "python", "if-statement", "button", "tkinter", "tic-tac-toe" ]
Python parse datestring to date
38,681,032
<p>I am trying to parse a datetime string to date in Python. The input value is of the form:</p> <pre><code> "February 19, 1989" </code></pre> <p>I have been trying so far </p> <pre><code> datetime.datetime.strptime("February 19, 1989", "%B %d, %y") </code></pre> <p>but I am always getting error. What is t...
1
2016-07-31T05:25:24Z
38,681,042
<p>The following works (changed small case <code>y</code> to uppercase <code>Y</code>):</p> <pre><code>datetime.datetime.strptime("February 19, 1989", "%B %d, %Y") </code></pre> <p>The reason is that <code>%y</code> is for <code>99</code>, <code>98</code> and such, while <code>%Y</code> is for full year. You can read...
2
2016-07-31T05:28:07Z
[ "python", "date" ]
Python parse datestring to date
38,681,032
<p>I am trying to parse a datetime string to date in Python. The input value is of the form:</p> <pre><code> "February 19, 1989" </code></pre> <p>I have been trying so far </p> <pre><code> datetime.datetime.strptime("February 19, 1989", "%B %d, %y") </code></pre> <p>but I am always getting error. What is t...
1
2016-07-31T05:25:24Z
38,681,105
<p>In addition to David's <a href="http://stackoverflow.com/a/38681042/189134">answer</a>, if you have a list of strings that have a variety of formats (say, some have two digit years and others have four), you can utilize the <a href="https://pypi.python.org/pypi/python-dateutil" rel="nofollow"><code>dateutil</code></...
1
2016-07-31T05:39:38Z
[ "python", "date" ]
python string replacement using tuple values
38,681,035
<p>This code will return the text that I am looking for. But I am not able to adjust the punctuation marks.</p> <pre><code>fieldnames = ("user","messageid","message","destination", "code","mobile","mytimestamp") newData = ["\'%s\': %s" % (tup, tup) for tup in fieldnames if tup!='destination' ] </code></pre> <p>newDat...
-2
2016-07-31T05:26:46Z
38,681,069
<p>You can change the code to something like</p> <pre><code>newData = ("\"[" + ", ".join("\\'%s\\': %s" % (tup, tup) for tup in fieldnames if tup!='destination') + "]\"") </code></pre> <p>Note: I am assuming you want the double quotes, backslash and single quotes being part...
0
2016-07-31T05:33:25Z
[ "python" ]
python string replacement using tuple values
38,681,035
<p>This code will return the text that I am looking for. But I am not able to adjust the punctuation marks.</p> <pre><code>fieldnames = ("user","messageid","message","destination", "code","mobile","mytimestamp") newData = ["\'%s\': %s" % (tup, tup) for tup in fieldnames if tup!='destination' ] </code></pre> <p>newDat...
-2
2016-07-31T05:26:46Z
38,681,118
<p>What about:</p> <pre><code>fieldnames = ("user","messageid","message","destination", "code","mobile","mytimestamp") s = "[%s]" % ', '.join(["\\'%s\\': %s" % (t,t) for t in fieldnames if t != 'destination']) print(s) </code></pre>
2
2016-07-31T05:42:13Z
[ "python" ]
python string replacement using tuple values
38,681,035
<p>This code will return the text that I am looking for. But I am not able to adjust the punctuation marks.</p> <pre><code>fieldnames = ("user","messageid","message","destination", "code","mobile","mytimestamp") newData = ["\'%s\': %s" % (tup, tup) for tup in fieldnames if tup!='destination' ] </code></pre> <p>newDat...
-2
2016-07-31T05:26:46Z
38,686,521
<p>You have it almost done. You only need these minor changes:</p> <ol> <li><p>Use raw strings, just add an <code>r</code> before the string you already have:</p> <p><code>r"\'%s\': %s"</code></p></li> <li><p>You have a list with all the string groups you need. Just join them using <code>str.join</code>:</p> <p><cod...
1
2016-07-31T17:16:25Z
[ "python" ]
Weird behaviour when trying to estimate an unknown variable
38,681,102
<p>I'm trying to estimate an unknown variable (p) with a very high precision. What I have is a large number of ordered values (I call them t-values). Each value has a sequence number (n). Each of those t-values is basically the result of multiplying n with p and then adding a random offset ("noise"). My idea is to simp...
0
2016-07-31T05:39:32Z
38,681,764
<p>Your problem is due to the nature of your sampling. As you increase the percentage chance of dropping values, the overall percentage of dropped values will increase <em>exponentially</em> and will drastically reduce your accuracy and precision. </p> <p>Needless to say, such a significant change in the sampling popu...
0
2016-07-31T07:29:34Z
[ "python", "statistics" ]
Weird behaviour when trying to estimate an unknown variable
38,681,102
<p>I'm trying to estimate an unknown variable (p) with a very high precision. What I have is a large number of ordered values (I call them t-values). Each value has a sequence number (n). Each of those t-values is basically the result of multiplying n with p and then adding a random offset ("noise"). My idea is to simp...
0
2016-07-31T05:39:32Z
38,685,440
<p>Not sure I fully understand your question, but I'm trying to be helpful.</p> <p>I do believe the result your seeing is to be expected. Suppose the drop rate increase such that in average every second measurement is dropped. The average difference between two consecutive remaining measurements will be twice the valu...
0
2016-07-31T15:20:43Z
[ "python", "statistics" ]
Weird behaviour when trying to estimate an unknown variable
38,681,102
<p>I'm trying to estimate an unknown variable (p) with a very high precision. What I have is a large number of ordered values (I call them t-values). Each value has a sequence number (n). Each of those t-values is basically the result of multiplying n with p and then adding a random offset ("noise"). My idea is to simp...
0
2016-07-31T05:39:32Z
38,760,158
<p>For completeness here is the actual problem I'm trying to solve:</p> <p>Two computers are connected to the internet. Computer A is sending a special kind of packets to computer B with a fixed interval (the packets are based on UDP). Computer B needs to estimate what this interval is with very high accuracy.</p> <p...
0
2016-08-04T06:40:57Z
[ "python", "statistics" ]
Why won't Django load my static CSS files?
38,681,270
<p>I'm having trouble getting Django to load my CSS for my html template. I'm aware that there are a lot of posts like this, such as <a href="http://stackoverflow.com/questions/15428146/django-server-error-loading-static-files">here</a> and <a href="http://stackoverflow.com/questions/13446325/django-css-is-not-not-work...
0
2016-07-31T06:10:59Z
38,681,375
<p>You should have this to serve static file in project directory...</p> <pre><code>STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"),] </code></pre> <p><code>os.path.dirname(os.path.abspath(__file__))</code> This is pointing to Personal_Website folder where settings all file is there...</p>
1
2016-07-31T06:26:44Z
[ "python", "html", "css", "django" ]
django create custom shell command to create app with custom layout
38,681,307
<p>i have different layout for my app in my django project,i.e my app layout is as below,</p> <pre><code>myapp/ models.py/ __init__.py rest_api/ __init__.py services/ __init__.py __init__.py admin.py apps.py models.py views.py tests.py </code></pr...
0
2016-07-31T06:16:54Z
38,681,371
<p>Django allows your to create an custom project structure using template flag. For eg:</p> <pre><code>django-admin.py startproject \ --template=https://github.com/caktus/django-project-template/zipball/master \ --extension=py,rst,yml \ --name=Makefile,gulpfile.js,package.json &lt;project_name&gt; </code></pr...
2
2016-07-31T06:25:56Z
[ "python", "django" ]
installing opencv3 for python3 in OSX
38,681,312
<p>So I followed <a href="http://tsaith.github.io/install-opencv-3-for-python-3-on-osx.html" rel="nofollow">this tutorial</a> and got this error:</p> <pre><code>brew link --overwrite eigen brew install opencv3 --with-python3 --with-contrib </code></pre> <p>wrote this in <code>~/.profile</code> and sourced it:</p> <p...
0
2016-07-31T06:17:35Z
38,685,867
<p>Since you installed OpenCV3 using Homebrew, your symlink might be corrupted.</p> <p>Since the current version of OpenCV in homebrew/science is 3.1.0, your symlink probably should point to</p> <pre><code>/usr/local/Cellar/opencv3/3.1.0_3/lib/python3.5/site-packages </code></pre> <p>3.1.0_3 and python3.5 might diff...
0
2016-07-31T16:04:12Z
[ "python", "osx", "python-3.x", "opencv", "opencv3.0" ]
installing opencv3 for python3 in OSX
38,681,312
<p>So I followed <a href="http://tsaith.github.io/install-opencv-3-for-python-3-on-osx.html" rel="nofollow">this tutorial</a> and got this error:</p> <pre><code>brew link --overwrite eigen brew install opencv3 --with-python3 --with-contrib </code></pre> <p>wrote this in <code>~/.profile</code> and sourced it:</p> <p...
0
2016-07-31T06:17:35Z
38,688,201
<p>You need to <strong>link</strong> your opencv to python site-packages</p> <p>Link <strong>cv.py</strong> and <strong>cv2.so</strong> using <code>ln -s [cellar-opencv-site-packages-path] [lib-python-site-packages-path]</code> </p> <pre><code>ln -s /usr/local/Cellar/opencv3/3.1.0_3/lib/python3.4.1/site-packages/cv.p...
0
2016-07-31T20:38:54Z
[ "python", "osx", "python-3.x", "opencv", "opencv3.0" ]
Pandas `period_range` gives strange results
38,681,319
<p>I want a pandas period range with 25 hours offset, and I saw there are two ways to do this (see <a href="https://github.com/AileenNielsen/TimeSeriesAnalysisWithPython/blob/master/1.%20Dates%20%26%20Times.ipynb" rel="nofollow">here</a>):</p> <p>The first way is to use <code>freq=25H</code>, which I tried, and gave m...
4
2016-07-31T06:18:04Z
38,685,169
<p>The bug has already been identified and <a href="https://github.com/pydata/pandas/issues/13730" rel="nofollow">reported on GitHub</a>.</p> <p>EDIT: <a href="https://github.com/pydata/pandas/commit/81819b7aa2537469448fbaeb4cd9e3d500f4e2a1" rel="nofollow">A fix</a> has been merged and will be included in v0.19.</p>
4
2016-07-31T14:51:14Z
[ "python", "pandas" ]
I get some error and problems when install "matplotlib"
38,681,412
<p>I have get a virtual env on '/home/name/pyenv' for python2.7.9; Now I want to install 'matplotlib' for it; then I activate this virtual env and install 'matplotlib' as below:</p> <ul> <li>by command "sudo apt-get install python-matplotlib"; (if delete "sudo", permission denied), it runs well and I find "matplotlib"...
0
2016-07-31T06:32:33Z
38,681,636
<p>One possibility is to install matplotlib globally then create your virtualenv <strong>with</strong> the site packages, see <a href="http://stackoverflow.com/questions/12079607/make-virtualenv-inherit-specific-packages-from-your-global-site-packages">here</a> for someone with exactly the same problem, by using <code>...
0
2016-07-31T07:08:10Z
[ "python", "matplotlib", "pip", "virtualenv" ]
Working with calculating GCD - Python function return
38,681,432
<p>I wrote a code which calculates the GCD of two numbers. The gcd of (24,12) is 12. The function <code>compute_gcd</code> computes the GCD and returns it which gets printed in the main function. However, the output is <code>none</code> when I return it to the main function and it is 12 when I print it in the <code>com...
1
2016-07-31T06:35:58Z
38,681,452
<p>You forgot to put a <code>return</code> in the <code>else</code> branch. This works:</p> <pre><code>def compute_gcd(a,b): if b == 0: return a else: return compute_gcd(b,a%b) def main(): a=24 b=12 print compute_gcd(a,b) # Prints 12 main() </code></pre>
4
2016-07-31T06:38:40Z
[ "python", "python-2.7", "return", "return-value", "greatest-common-divisor" ]
Working with calculating GCD - Python function return
38,681,432
<p>I wrote a code which calculates the GCD of two numbers. The gcd of (24,12) is 12. The function <code>compute_gcd</code> computes the GCD and returns it which gets printed in the main function. However, the output is <code>none</code> when I return it to the main function and it is 12 when I print it in the <code>com...
1
2016-07-31T06:35:58Z
38,681,526
<p>Your else condition has no return hence output is none. If you change that to</p> <pre><code>else: return compute_gcd(b,a%b) </code></pre> <p>You'll get <code>12</code>.</p>
-2
2016-07-31T06:52:09Z
[ "python", "python-2.7", "return", "return-value", "greatest-common-divisor" ]
Working with calculating GCD - Python function return
38,681,432
<p>I wrote a code which calculates the GCD of two numbers. The gcd of (24,12) is 12. The function <code>compute_gcd</code> computes the GCD and returns it which gets printed in the main function. However, the output is <code>none</code> when I return it to the main function and it is 12 when I print it in the <code>com...
1
2016-07-31T06:35:58Z
38,681,847
<p>try this ... you have to do a <code>return</code> inside the <code>else</code> statement</p> <pre><code>def compute_gcd(a,b): if(b==0): return a else: return compute_gcd(b,a%b) def main(): a = 24 b = 12 print(compute_gcd(a,b)) main() </code></pre>
0
2016-07-31T07:41:36Z
[ "python", "python-2.7", "return", "return-value", "greatest-common-divisor" ]
Can this be done with SQLAhclemy / Python?
38,681,548
<p>I'm trying to create a database in SQL, with python. Was wondering if it would be possible to group things together like the below image? (I know we can do this in Excel. But I was wondering if it would be possible to do it in SQL?)</p> <p><a href="http://i.stack.imgur.com/BNSkC.png" rel="nofollow"><img src="http:/...
1
2016-07-31T06:55:32Z
38,681,680
<p>Yes, it is possible to achieve that with SQL. All you have to do is create a table like this:</p> <pre><code>CREATE TABLE data ( names TEXT, counter INT, ratio1_2012 INT, ratio2_2012 INT, ratio3_2012 INT, ratio4_2012 INT, ratio1_2013 INT, ... ); </code></pre> <p>Of course, this is n...
0
2016-07-31T07:16:30Z
[ "python", "sql", "sqlalchemy" ]
HMM loaded from pickle looks untrained
38,681,698
<p>I am trying to serialise nltk.tag.hmm.HiddenMarkovModelTagger into a pickle to use it when needed without re-training. However, after loading from .pkl my HMM looks untrained. My two questions here are:</p> <ol> <li>What am I doing wrong? </li> <li>Is it a good idea at all to serialise HMM when one has a <em>big</e...
1
2016-07-31T07:18:25Z
38,685,226
<p>1) After In[22], you need to add - </p> <pre><code>corpus = [[tuple(l) for l in sentence] for sentence in corpus] </code></pre> <p>2) Re-training model every time for testing purpose will be time consuming. So, It is good to pickle.dump your model and load it.</p>
0
2016-07-31T14:57:20Z
[ "python", "nltk", "pickle" ]
Locust, upload test
38,681,714
<p>I am new to locust and trying to make my first test, upload simple file with headers and path, and cant seem to manage to make it work</p> <p>will be glad for any help, thanks!</p> <p>my current test is:</p> <pre><code>class UserBehavior(TaskSet): @task def post_img(self): self.cli...
0
2016-07-31T07:22:05Z
38,684,143
<p>Managed to write a test that uploads a file:</p> <pre><code>class HttpSession(TaskSet): @task def post_img(self): headers = {'1': '1', '2': '2'} test_file = '/pathTo/file.jpg' self.client.request('POST', 'url', files={'file': open(test_file, 'rb')}, headers=he...
1
2016-07-31T12:49:51Z
[ "python", "upload", "locust" ]
Python replace value in text file
38,681,740
<p>I'm trying to replace a value in a specific line in a text file.</p> <p>My text file contains count of the searchterm,searchterm &amp; date and time</p> <p>text file:</p> <pre><code>MemTotal,5,2016-07-30 12:02:33,781 model name,3,2016-07-30 13:37:59,074 model,3,2016-07-30 15:39:59,075 </code></pre> <p>How can i ...
-2
2016-07-31T07:25:33Z
38,682,440
<p>You have to change three things in your code to get the job done:</p> <ol> <li><p>Read the file using <code>readlines</code>. </p> <pre><code>filedata = f.readlines() </code></pre></li> <li><p>Modify the line you want to change (keep in mind that Python indices start at 0 and don't forget to add a newline charact...
0
2016-07-31T09:08:23Z
[ "python", "search", "replace" ]
Python replace value in text file
38,681,740
<p>I'm trying to replace a value in a specific line in a text file.</p> <p>My text file contains count of the searchterm,searchterm &amp; date and time</p> <p>text file:</p> <pre><code>MemTotal,5,2016-07-30 12:02:33,781 model name,3,2016-07-30 13:37:59,074 model,3,2016-07-30 15:39:59,075 </code></pre> <p>How can i ...
-2
2016-07-31T07:25:33Z
38,683,072
<p>My solution:</p> <pre><code>count = 0 line_number = 0 replace = "" f = open('examen.log','r') term = "MemTotal" for line in f.read().split('\n'): if term in line: replace= line.replace("5", "25", 1) line_number = count count = count + 1 print line_number f.close() f =...
0
2016-07-31T10:33:55Z
[ "python", "search", "replace" ]
pandas not condition with filtering
38,681,802
<p>How I can implement not condition on the filtering </p> <pre><code>grouped = store_ids_with_visits.groupby(level=[0, 1, 2]) grouped.filter(lambda x: (len(x) == 1 and x['template_fk'] == exterior_template)) </code></pre> <p>I want to get all entries that not answering on the condition</p> <p>I tried doing:</p> <p...
1
2016-07-31T07:34:15Z
38,682,103
<p>IIUC, you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isin.html" rel="nofollow"><code>isin</code></a> to check for bool conditions and take only the <code>NOT(~)</code> values of the grouped dataframe: </p> <pre><code> df[~df.isin(grouped.filter(lambda x: (len(x) == 1 a...
1
2016-07-31T08:22:01Z
[ "python", "pandas", "dataframe" ]
Reshape pandas dataframe from rows to columns
38,681,821
<p>I'm trying to reshape my data. At first glance, it sounds like a transpose, but it's not. I tried melts, stack/unstack, joins, etc.</p> <p><strong>Use Case</strong></p> <p>I want to have only one row per unique individual, and put all job history on the columns. For clients, it can be easier to read information ac...
7
2016-07-31T07:37:37Z
38,682,055
<p>This is not exactly what you were asking but here is a way to print the data frame as you wanted:</p> <pre><code>df = pd.DataFrame(data1) for name, jobs in df.groupby('Name').groups.iteritems(): print '{0:&lt;15}'.format(name), for job in jobs: print '{0:&lt;15}{1:&lt;15}'.format(df['Job'].ix[job], ...
0
2016-07-31T08:15:56Z
[ "python", "pandas", "group-by", "reshape" ]
Reshape pandas dataframe from rows to columns
38,681,821
<p>I'm trying to reshape my data. At first glance, it sounds like a transpose, but it's not. I tried melts, stack/unstack, joins, etc.</p> <p><strong>Use Case</strong></p> <p>I want to have only one row per unique individual, and put all job history on the columns. For clients, it can be easier to read information ac...
7
2016-07-31T07:37:37Z
38,682,179
<p>Say you start by unstacking:</p> <pre><code>df2 = df2.set_index(['Name', 'Job']).unstack() &gt;&gt;&gt; df2 Job Eff Date Job Analyst Director Manager Name Jane 1/1/2015 None 1/1/2016 Joe 1/1/2015 7/1/2016 1/1/2016 In [29]: df2 </code></pre> <p>Now, to make things easier, flatten ...
2
2016-07-31T08:30:58Z
[ "python", "pandas", "group-by", "reshape" ]
Reshape pandas dataframe from rows to columns
38,681,821
<p>I'm trying to reshape my data. At first glance, it sounds like a transpose, but it's not. I tried melts, stack/unstack, joins, etc.</p> <p><strong>Use Case</strong></p> <p>I want to have only one row per unique individual, and put all job history on the columns. For clients, it can be easier to read information ac...
7
2016-07-31T07:37:37Z
38,682,183
<p>Here is a possible workaround. Here, I first create a dictionary of the proper form and create a DataFrame based on the new dictionary:</p> <pre><code>df = pd.DataFrame(data1) dic = {} for name, jobs in df.groupby('Name').groups.iteritems(): if not dic: dic['Name'] = [] dic['Name'].append(name) ...
1
2016-07-31T08:31:17Z
[ "python", "pandas", "group-by", "reshape" ]
Reshape pandas dataframe from rows to columns
38,681,821
<p>I'm trying to reshape my data. At first glance, it sounds like a transpose, but it's not. I tried melts, stack/unstack, joins, etc.</p> <p><strong>Use Case</strong></p> <p>I want to have only one row per unique individual, and put all job history on the columns. For clients, it can be easier to read information ac...
7
2016-07-31T07:37:37Z
38,682,517
<pre><code>g = df2.groupby('Name').groups names = list(g.keys()) data2 = {'Name': names} cols = ['Name'] temp1 = [g[y] for y in names] job_str = 'Job' job_date_str = 'Job Eff Date' for i in range(max([len(x) for x in g.values()])): temp = [x[i] if len(x) &gt; i else '' for x in temp1] job_str_curr = job_str + s...
1
2016-07-31T09:19:44Z
[ "python", "pandas", "group-by", "reshape" ]
Reshape pandas dataframe from rows to columns
38,681,821
<p>I'm trying to reshape my data. At first glance, it sounds like a transpose, but it's not. I tried melts, stack/unstack, joins, etc.</p> <p><strong>Use Case</strong></p> <p>I want to have only one row per unique individual, and put all job history on the columns. For clients, it can be easier to read information ac...
7
2016-07-31T07:37:37Z
38,685,439
<p><code>.T</code> within <code>groupby</code></p> <pre><code>def tgrp(df): df = df.drop('Name', axis=1) return df.reset_index(drop=True).T df2.groupby('Name').apply(tgrp).unstack() </code></pre> <p><a href="http://i.stack.imgur.com/4b3Nx.png" rel="nofollow"><img src="http://i.stack.imgur.com/4b3Nx.png" alt=...
6
2016-07-31T15:20:33Z
[ "python", "pandas", "group-by", "reshape" ]
Reshape pandas dataframe from rows to columns
38,681,821
<p>I'm trying to reshape my data. At first glance, it sounds like a transpose, but it's not. I tried melts, stack/unstack, joins, etc.</p> <p><strong>Use Case</strong></p> <p>I want to have only one row per unique individual, and put all job history on the columns. For clients, it can be easier to read information ac...
7
2016-07-31T07:37:37Z
38,689,330
<p>Diving into @piRSquared answer.... </p> <pre><code>def tgrp(df): df = df.drop('Name', axis=1) print df, '\n' out = df.reset_index(drop=True) print out, '\n' out.T print out.T, '\n\n' return out.T dfxx = df2.groupby('Name').apply(tgrp).unstack() dfxx </code></pre> <p>The outpu...
0
2016-07-31T23:44:28Z
[ "python", "pandas", "group-by", "reshape" ]
find the shortest path between two points in a circular list in python
38,681,844
<p>I have a list like the following : <code>a =[1,2,3,4]</code></p> <p>The list is a circular list. The <strong>values in the list does not represent nodes</strong>,but the index of the list represent nodes. So the list may contain duplicated elements. example,</p> <pre><code>if i take index (1,3) (ie source is at in...
-3
2016-07-31T07:41:18Z
38,971,144
<p>Looks that this is what you want:</p> <pre><code>L = [1, 2, 3, 4, 5, 6] a = L[1] b = L[3] cnt1 = [] cnt2 = [] for x in range(L.index(a), L.index(b) + 1): cnt1.append(L[x]) for x in range(L.index(a), L.index(b) -(len(L) + 1), -1): cnt2.append(L[x]) if len(cnt1) &lt;= len(cnt2): print(cnt1) else: pri...
0
2016-08-16T09:25:02Z
[ "python", "algorithm" ]
What's the correct way to add Python.h and/or python3-dev in Ubuntu 14.04?
38,681,862
<p>On Ubuntu 14.04.4 LTS I was trying to install <a href="https://github.com/coursera-dl/coursera-dl" rel="nofollow">courseara-dl</a> with the default python 3.4.3 and met the error:</p> <pre><code>src/MD2.c:31:20: fatal error: Python.h: No such file or directory #include "Python.h" ^ compilatio...
1
2016-07-31T07:44:24Z
38,684,203
<p>According to this: <a href="http://packages.ubuntu.com/trusty/python3" rel="nofollow">http://packages.ubuntu.com/trusty/python3</a> the official default python3 version of 14.04 from Ubuntu is 3.4.0. According to this: <a href="http://packages.ubuntu.com/trusty-updates/python3.4" rel="nofollow">http://packages.ubunt...
1
2016-07-31T12:56:42Z
[ "python", "ubuntu" ]
What's the correct way to add Python.h and/or python3-dev in Ubuntu 14.04?
38,681,862
<p>On Ubuntu 14.04.4 LTS I was trying to install <a href="https://github.com/coursera-dl/coursera-dl" rel="nofollow">courseara-dl</a> with the default python 3.4.3 and met the error:</p> <pre><code>src/MD2.c:31:20: fatal error: Python.h: No such file or directory #include "Python.h" ^ compilatio...
1
2016-07-31T07:44:24Z
38,728,781
<p>I don't remember exactly how I got python 3.4.3 in my Ubuntu, maybe through ubuntu auto upgrade?</p> <p>The problem was <code>libexpat1</code>:</p> <pre><code>apt-cache policy libexpat1 libexpat1: Installed: 2.1.0-4ubuntu1.1 Candidate: 2.1.0-4ubuntu1.1 Version table: *** 2.1.0-4ubuntu1.1 0 100 /var/...
0
2016-08-02T19:17:36Z
[ "python", "ubuntu" ]
gurobi milp model to maximize npv
38,681,871
<p>I am trying to model a simple inventory maximizing income with gurobi MILP but i have been getting trouble about how to write the objective function for Net Present Value Maximizing.</p> <p>an array A=np.random.randint(100,1500,100) is the value from every 100 items in the inventory</p> <pre><code>from gurobipy i...
0
2016-07-31T07:45:49Z
38,690,807
<p><code>quicksum()</code> evaluates a linear expression; you need to convert your nested expressions into a single linear expression. You can do this by computing the coefficient values.</p>
0
2016-08-01T03:57:19Z
[ "python", "optimization", "gurobi" ]
'libavformat/avformat.h' file not found #include <libavformat/avformat.h>
38,681,912
<p>When following the <a href="https://gist.github.com/ranveeraggarwal/f1499a586dabafb63392" rel="nofollow">below tutorial</a>:</p> <blockquote> <p>brew install python3 pip3 install numpy brew install cmake git clone --depth=1 <a href="https://github.com/Itseez/opencv.git" rel="nofollow">https://github.com/Itseez/...
0
2016-07-31T07:51:50Z
38,758,097
<p>So this is how I solved the problem. Please let me know if you might have further questions:</p> <pre><code> ~  c   master ⭑  Face_Recognition  ls  10:03:38 PM 3.1.0.zip 3.1.0.zip.1 ...
0
2016-08-04T03:38:39Z
[ "python", "osx", "python-3.x", "opencv", "cmake" ]
python-re.sub() and unicode
38,681,921
<p>I want to replace all emoji with <code>''</code> but my regEx doesn't work.<BR>For example, </p> <pre><code>content= u'?\u86cb\u767d12\U0001f633\uff0c\u4f53\u6e29\u65e9\u6668\u6b63\u5e38\uff0c\u5348\u540e\u665a\u95f4\u53d1\u70ed\uff0c\u6211\u73b0\u5728\u8be5\u548b\U0001f633?' </code></pre> <p>and I want to replace...
2
2016-07-31T07:52:36Z
38,682,213
<p>You won't be able to recognize properly decoded unicode codepoints that way (as strings containing <code>\uXXXX</code>, etc.) Properly decoded, by the time the regex parser gets to them, each is a* character.</p> <p>Depending on whether your python was compiled with only 16-bit unicode code points or not, you'll w...
3
2016-07-31T08:35:10Z
[ "python", "python-2.7", "unicode" ]
Python pip command returning 'Command "python setup.py egg_info" failed with error code1'
38,681,940
<p>I keep getting the error "Python pip command returning 'Command "python setup.py egg_info" failed with error code1'" when trying to install PyEZ/junos-eznc for some reason. My setuptool and ez-setup are all up to date. Here is a snap of the error:</p> <pre><code>C:\Users\???&gt;py -m pip install junos-eznc Collecti...
1
2016-07-31T07:55:48Z
38,685,578
<p>It looks like the issue is that the description in <code>ncclient</code>'s <code>setup.py</code> file is being loaded in the wrong encoding. A few other packages seem to have similar issues like the one <a href="https://github.com/lxyu/pinyin/issues/9" rel="nofollow">here</a>, so I suggest you try this:</p> <ul> <l...
2
2016-07-31T15:36:03Z
[ "python", "python-3.x", "pip", "setuptools" ]
Python pip command returning 'Command "python setup.py egg_info" failed with error code1'
38,681,940
<p>I keep getting the error "Python pip command returning 'Command "python setup.py egg_info" failed with error code1'" when trying to install PyEZ/junos-eznc for some reason. My setuptool and ez-setup are all up to date. Here is a snap of the error:</p> <pre><code>C:\Users\???&gt;py -m pip install junos-eznc Collecti...
1
2016-07-31T07:55:48Z
38,697,469
<p>Finally found a solution for this problem.</p> <p>Step 1) As Aurora0001 stated, download zip file, delete lines 31 and 32 and replace with: </p> <pre><code>long_description = "Placeholder" </code></pre> <p>then, use pip to install.</p> <p>Step 2) execute this command:</p> <pre><code>set STATICBUILD=true &amp;&a...
0
2016-08-01T11:16:47Z
[ "python", "python-3.x", "pip", "setuptools" ]
Why the installed numpy in my system does not have matmul?
38,682,115
<p>I have installed numpy as following in ubuntu 14.04, but as is indicated in the sample code using matmul leads to error.</p> <pre><code>sudo apt-get install python3-numpy $ python3 Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more informat...
1
2016-07-31T08:24:41Z
38,682,136
<p><code>np.matmul</code> was added in <code>numpy 1.10.0</code>, as per the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.matmul.html" rel="nofollow">docs</a>:</p> <blockquote> <p>New in version 1.10.0</p> </blockquote>
4
2016-07-31T08:26:30Z
[ "python", "numpy" ]
Condition Codes In Python Programing
38,682,200
<p>I typed in Microsoft Visual Studio that</p> <pre><code>answer = input("What Is Your Age ? ") if answer &gt;= "18" : print("You Have The Right To Cast Vote In India.") else : print("You Have No Right To Cast Vote In India.") </code></pre> <p>When user is typing the number greater than equal t...
-4
2016-07-31T08:33:33Z
38,682,220
<p>You are comparing strings, not integers. When comparing strings the comparison is lexicographic:</p> <pre><code>print('101' &gt; '18') &gt;&gt; False </code></pre> <p>You should convert <code>answer</code> to <code>int</code> and then compare as integers:</p> <pre><code>answer = int(input("What Is Your Age ? ")) ...
0
2016-07-31T08:35:56Z
[ "python" ]
Condition Codes In Python Programing
38,682,200
<p>I typed in Microsoft Visual Studio that</p> <pre><code>answer = input("What Is Your Age ? ") if answer &gt;= "18" : print("You Have The Right To Cast Vote In India.") else : print("You Have No Right To Cast Vote In India.") </code></pre> <p>When user is typing the number greater than equal t...
-4
2016-07-31T08:33:33Z
38,682,227
<p>You're trying to compare a string <code>answer</code> to a string <code>"18"</code> as if they were both numbers. This won't work - Python tries to compare them based on alphabetical order instead of numerically.</p> <p>To achieve what you want, convert <code>answer</code> to an integer number using the <code>int</...
0
2016-07-31T08:36:31Z
[ "python" ]
How to nest numba jitclass
38,682,260
<p>I'm trying to understand how the @jitclass decorator works with nested classes. I have written two dummy classes: fifi and toto fifi has a toto attribute. Both classes have the @jitclass decorator but compilation fails. Here's the code:</p> <p>fifi.py</p> <pre><code>from numba import jitclass, float64 from toto im...
4
2016-07-31T08:40:16Z
38,684,908
<p>It is possible to use a jitclass as a member of another jitclass, although the way of doing this isn't well documented. You need to use a <code>deferred_type</code> instance. This works in Numba 0.27 and possibly earlier. Change <code>fifi.py</code> to:</p> <pre><code>from numba import jitclass, float64, deferred_t...
2
2016-07-31T14:18:00Z
[ "python", "jit", "numba" ]
Printing passwords as encrypted in log file
38,682,261
<p>I have a Python code like below:</p> <pre><code>myargs = [param,/PASSWORD="{}",.format(myData['PASSWORD'])] </code></pre> <p>When I print it in my log file I use the following statement:</p> <pre><code>logging.info(myargs) </code></pre> <p>It prints the statement correctly, what I need is all passwords should be...
-1
2016-07-31T08:40:18Z
38,684,727
<p>First off, <code>base 64</code> is not encrypted, it's encoded. There is a big difference. Secondly, use hashing. </p> <p>Check out the <a href="https://docs.python.org/2/library/hashlib.html" rel="nofollow">hashlib</a> module. There are various secure hash algorithms you can use. SHA1, SHA224, SHA256, SHA384, and ...
0
2016-07-31T14:01:28Z
[ "python", "logging", "passwords", "password-encryption" ]
Many-to-many fields with intermediate tables must not be symmetrical
38,682,303
<p>I'm trying to figure out how to store prices between cities in my project so I can work with that comfortabely and admin can change those prices comfortably. </p> <p>I've decided to create a <code>through</code> model, according to this <a href="http://stackoverflow.com/a/4098843/3371056">ANSWER</a>, which is calle...
0
2016-07-31T08:45:17Z
38,683,712
<p>The error is pretty clear you can't have M2M relation with <code>intermediate</code> table and <code>symmetrical=True</code>, it must be <code>symmetrical=False</code>.</p> <p>So try with: </p> <pre><code>rides = models.ManyToManyField('self', through='Ride', symmetrical=False) </code></pre> <p>However, I think s...
0
2016-07-31T11:54:28Z
[ "python", "django", "django-models" ]
Why favor object.__setattr__(self, name, value) only in new style classes?
38,682,318
<p>According to Python 2.7.12 documentation:</p> <blockquote> <p>If <code>__setattr__()</code> wants to assign to an instance attribute, it should not simply execute <code>self.name = value</code> — this would cause a recursive call to itself. Instead, it should insert the value in the dictionary of instance...
0
2016-07-31T08:48:03Z
38,682,359
<p>New-style classes could be using <em>slots</em>, at which point there is no <code>__dict__</code> to assign to. New-style classes also support other <em>data descriptors</em>, objects defined on the class that handle attribute setting or deletion for certain names.</p> <p>From the <a href="https://docs.python.org/2...
3
2016-07-31T08:55:21Z
[ "python", "class", "inheritance", "setattr", "new-style-class" ]
Comparing two date as string
38,682,320
<p>I need to compare two dates in a server with python on every row of data. I used <code>datetime</code> in this case but due to some limitations it will consume a lot of time on big data. I used below code to create a <code>datetime</code> object and use in further:</p> <pre><code>first_date = datetime.strptime(line...
3
2016-07-31T08:48:11Z
38,682,515
<p>Yes - date parsing with Python is pretty slow because dates and times are <a href="https://news.ycombinator.com/item?id=2725015" rel="nofollow">complex things</a>. According to <a href="http://stackoverflow.com/a/14163523/2550354">this</a> stackoverflow thread, regex might be faster for parsing.</p> <p>I would thin...
2
2016-07-31T09:19:28Z
[ "python", "datetime" ]
PyGObject: How to work with objects in thread?
38,682,348
<p>Is there a way to create objects and work with them not in the main thread? I've read <a href="https://wiki.gnome.org/Projects/PyGObject/Threading" rel="nofollow">this link</a>, but don't understand how to apply it to my example (see below).</p> <pre class="lang-py prettyprint-override"><code>import threading from...
0
2016-07-31T08:54:23Z
38,707,344
<p>Here is an example of one way to do it: <a href="https://github.com/pithos/pithos/blob/f2e0ddaf44a3451907efc45b2c23cd0551d05aaa/pithos/gobject_worker.py" rel="nofollow">pithos/gobject_worker.py</a></p> <p>You have a Queue of jobs you want on another thread and then your callback is called on the main thread once th...
0
2016-08-01T20:14:00Z
[ "python", "multithreading", "pygtk", "pygobject" ]
Instances & classes: requiring x arguments when x-1 given
38,682,435
<p>I have written the following classes to be able to test different encryption schemes. However, I'm having trouble instantiating objects from the different encryption scheme. Could someone point out to something that doesn't make sense that I'm not catching atm? I'm not sure why it doesn't work. It gives a <code>Typ...
0
2016-07-31T09:06:47Z
38,682,444
<p>You are passing in <strong>one</strong> argument to a bound method:</p> <pre><code>return self.bc1.encrypt( self.bc2.encrypt(tweak) * self.bc3.encrypt(message) + self.bc4.encrypt(tweak)) </code></pre> <p>That's one argument to the <code>BC.encrypt()</code> method each, and this method takes 2 beyond <code...
1
2016-07-31T09:08:41Z
[ "python", "python-3.x", "instantiation", "self", "pycrypto" ]
Why is using the Python mmap module much slower than calling POSIX mmap from C++?
38,682,501
<p>C++ code:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;string&gt; #include &lt;fcntl.h&gt; #include &lt;sys/mman.h&gt; #include &lt;unistd.h&gt; #include &lt;sys/time.h&gt; using namespace std; #define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) int main() { timeval tv1, tv2, tv3, t...
0
2016-07-31T09:18:00Z
38,682,698
<p>Not <code>mmap</code> is slower, but the filling of a array with values. Python is known, to be slow on doing primitive operations. Use higher-level operations:</p> <pre><code>buffer[:] = 'S' * size </code></pre>
5
2016-07-31T09:44:43Z
[ "python", "c++", "performance", "posix", "mmap" ]