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
Why does map return a map object instead of a list in Python 3?
40,015,439
<p>I am interested in understanding the <a href="http://stackoverflow.com/questions/1303347/getting-a-map-to-return-a-list-in-python-3-x">new language design of Python 3.x</a>.</p> <p>I do enjoy, in Python 2.7, the function <code>map</code>:</p> <pre><code>Python 2.7.12 In[2]: map(lambda x: x+1, [1,2,3]) Out[2]: [2, ...
20
2016-10-13T08:01:41Z
40,015,905
<p>Guido answers this question <a href="https://docs.python.org/3/whatsnew/3.0.html">here</a>: "<em>since creating a list would just be wasteful</em>". </p> <p>He also says that the correct transformation is to use a regular <code>for</code> loop.</p> <p>Converting <code>map()</code> from 2 to 3 might not just be a ...
6
2016-10-13T08:27:25Z
[ "python", "python-3.x" ]
Python how to decode unicode with hex characters
40,015,477
<p>I have extracted a string from web crawl script as following:</p> <pre><code>u'\xe3\x80\x90\xe4\xb8\xad\xe5\xad\x97\xe3\x80\x91' </code></pre> <p>I want to decode <code>u'\xe3\x80\x90\xe4\xb8\xad\xe5\xad\x97\xe3\x80\x91'</code> with utf-8. With <a href="http://ddecode.com/hexdecoder/" rel="nofollow">http://ddecode...
2
2016-10-13T08:04:01Z
40,015,550
<p>Just keep msg as string not unicode.</p> <pre><code>msg = '\xe3\x80\x90\xe4\xb8\xad\xe5\xad\x97\xe3\x80\x91' result = msg.decode('utf8') </code></pre>
0
2016-10-13T08:08:18Z
[ "python", "utf-8", "python-2.x" ]
Python how to decode unicode with hex characters
40,015,477
<p>I have extracted a string from web crawl script as following:</p> <pre><code>u'\xe3\x80\x90\xe4\xb8\xad\xe5\xad\x97\xe3\x80\x91' </code></pre> <p>I want to decode <code>u'\xe3\x80\x90\xe4\xb8\xad\xe5\xad\x97\xe3\x80\x91'</code> with utf-8. With <a href="http://ddecode.com/hexdecoder/" rel="nofollow">http://ddecode...
2
2016-10-13T08:04:01Z
40,015,562
<ol> <li><p>Perhaps you should fix the crawl script instead, a Unicode string should contain <code>u'【中字】'</code> (<code>u'\u3010\u4e2d\u5b57\u3011'</code>) already, instead of the raw UTF-8 bytes.</p></li> <li><p>To convert <code>msg</code> to the correct encoding, first you need to turn the wrong Unicode stri...
2
2016-10-13T08:09:26Z
[ "python", "utf-8", "python-2.x" ]
Python how to decode unicode with hex characters
40,015,477
<p>I have extracted a string from web crawl script as following:</p> <pre><code>u'\xe3\x80\x90\xe4\xb8\xad\xe5\xad\x97\xe3\x80\x91' </code></pre> <p>I want to decode <code>u'\xe3\x80\x90\xe4\xb8\xad\xe5\xad\x97\xe3\x80\x91'</code> with utf-8. With <a href="http://ddecode.com/hexdecoder/" rel="nofollow">http://ddecode...
2
2016-10-13T08:04:01Z
40,017,764
<p>The problem with</p> <pre><code>msg = u'\xe3\x80\x90\xe4\xb8\xad\xe5\xad\x97\xe3\x80\x91' result = msg.decode('utf8') </code></pre> <p>is that you are trying to decode Unicode. That doesn't really make sense. You can encode <em>from</em> Unicode to some type of encoding, or you can decode a byte string <em>to</em>...
1
2016-10-13T09:53:11Z
[ "python", "utf-8", "python-2.x" ]
Django filter based on specific item from reverse relation
40,015,616
<p>I have two models that could look something like this: </p> <pre><code>Course(models.Model): pass WeeklyPrice(models.Model): num_weeks = models.IntegerField() price = models.DecimalField() course = models.ForeignKey(Course) is_erased = models.BooleanField() </code></pre> <p>The thing is i have a search...
-1
2016-10-13T08:11:46Z
40,016,393
<p>Ok, so i ended up finding out it's a lot simpler than it sounds...</p> <p>The filter needed is: </p> <pre><code>courses.filter(weekly_prices__is_erased=False, weekly_prices__num_weeks=duration) </code></pre>
0
2016-10-13T08:52:03Z
[ "python", "django" ]
Grouping a pandas dataframe in a suitable format for creating a chart
40,015,666
<p>Suppose I have the following pandas dataframe:</p> <pre><code>In [1]: df Out[1]: sentiment date 0 pos 2016-10-08 1 neu 2016-10-08 2 pos 2016-10-09 3 neg 2016-10-09 4 neg 2016-10-09 </code></pre> <p>I can indeed create a dataframe that makes summary statistics about the s...
2
2016-10-13T08:14:55Z
40,015,705
<p>You need add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unstack.html" rel="nofollow"><code>unstack</code></a>:</p> <pre><code>gf = df.groupby(["date", "sentiment"]).size().unstack(fill_value=0).reset_index() #remove column name 'sentiment' gf.columns.name = None print (gf) ...
2
2016-10-13T08:16:34Z
[ "python", "pandas", "dataframe", "pivot-table", "reshape" ]
Accepting an Excel file with io stream
40,015,789
<p>Currently I am working on an Excel file and taking its path as input as</p> <pre><code>myObj = ProcessExcelFile("C:\SampleExcel.xlsx") </code></pre> <p>constructor is as</p> <pre><code>def __init__(self, filepath): ''' Constructor ''' if not os.path.isfile(filepath): raise FileNotFoundErro...
0
2016-10-13T08:21:16Z
40,015,866
<p>You would need to modify your class to allow streams as well. Pass the stream to <code>open_workbook</code> via <code>file_contents</code>.</p> <pre><code>def __init__(self, filepath, stream=False): ''' Constructor ''' if stream: self.datawb = xlrd.open_workbook(file_contents=filepath.read()...
0
2016-10-13T08:25:20Z
[ "python", "excel", "io", "xlrd" ]
Use all coordinates in grid [python]
40,015,824
<p>For a minesweeper I have created a board using python and pygame. If you click a bomb, you should see the entire board. I have separate functions that contain the (randomised) bomb positions, and create the numbers around the bombs(on the proper coordinates). How do I make sure it checks the coordinates 0 to GRID_TI...
0
2016-10-13T08:22:59Z
40,026,216
<p>I got the solution:</p> <pre><code>def show_board(): for x in range(0,GRID_TILES): for y in range(0, GRID_TILES): draw_item(CELLS[x][y], x, y, (x+1,y+1)) </code></pre> <p>If I call this after hitting a bomb, it will show the entire board. If I just wanted to use every single coordinate on a grid, just<...
1
2016-10-13T16:20:42Z
[ "python", "python-3.x", "pygame" ]
How we stash Data to Cloudant DB in IBM Bluemix?
40,015,836
<p>Currently I am trying to stash data into Cloudant DB from a notebook using Python's Pixiedust package. After establishing a connection it gives me this error when trying to insert data into the database.</p> <pre><code>nPy4JJavaError: An error occurred while calling o172.save. : org.apache.spark.SparkException: Job...
0
2016-10-13T08:24:01Z
40,031,314
<p>This issue has been addressed and a new version of PixieDust has been uploaded to PyPI. You can download the latest version in your notebook by issuing the following command:</p> <p><code>!pip install --user --upgrade --no-deps pixiedust</code></p> <p>Restart your kernel after the upgrade is complete.</p> <p>You ...
0
2016-10-13T21:29:06Z
[ "python", "ibm-bluemix", "cloudant", "pixiedust" ]
How to stream POST data into Python requests?
40,015,869
<p>I'm using the Python <code>requests</code> library to send a POST request. The part of the program that produces the POST data can <strong>write</strong> into an arbitrary file-like object (output stream).</p> <p>How can I make these two parts fit?</p> <p>I would have expected that <code>requests</code> provides a...
2
2016-10-13T08:25:30Z
40,018,118
<p>The only way of connecting a data producer that requires a push interface for its data sink with a data consumer that requires a pull interface for its data source is through an intermediate buffer. Such a system can be operated only by running the producer and the consumer in "parallel" - the producer fills the buf...
0
2016-10-13T10:10:34Z
[ "python", "xml", "http", "python-requests", "generator" ]
How to stream POST data into Python requests?
40,015,869
<p>I'm using the Python <code>requests</code> library to send a POST request. The part of the program that produces the POST data can <strong>write</strong> into an arbitrary file-like object (output stream).</p> <p>How can I make these two parts fit?</p> <p>I would have expected that <code>requests</code> provides a...
2
2016-10-13T08:25:30Z
40,018,547
<p><code>request</code> does take an iterator or generator as <code>data</code> argument, the details are described in <a href="http://docs.python-requests.org/en/master/user/advanced/#chunk-encoded-requests" rel="nofollow">Chunk-Encoded Requests</a>. The transfer encoding needs to be chunked in this case because the d...
3
2016-10-13T10:32:29Z
[ "python", "xml", "http", "python-requests", "generator" ]
How To Share Mutable Variables Across Python Modules?
40,015,876
<p>I need to share variables across multiple modules. These variables will be changed asynchronously by threads as the program runs.</p> <p>I need to be able to access the most resent state of the variable by multi modules at the same time.</p> <p>Multiple modules will also be writing to the same variable.</p> <p>B...
0
2016-10-13T08:26:02Z
40,016,435
<p>Place all your global variables in a module, for example config.py and import it throughout your modules:</p> <p>config.py:</p> <pre><code>a=None varlock=None </code></pre> <p>main.py:</p> <pre><code>import config import threading config.a = 42 config.varlock = threading.RLock() ... </code></pre> <p>Then you c...
1
2016-10-13T08:53:36Z
[ "python", "python-multithreading" ]
Test if byte is empty in python
40,015,912
<p>I'd like to test the content of a variable containing a byte in a way like this: </p> <pre><code>line = [] while True: for c in self.ser.read(): # read() from pySerial line.append(c) if c == binascii.unhexlify('0A').decode('utf8'): print("Line: " + line) line = [] ...
2
2016-10-13T08:27:36Z
40,017,463
<p>If you want to verify the contents of your variable or string which you want to read from pySerial, use the <code>repr()</code> function, something like:</p> <pre><code>import serial import repr as reprlib from binascii import unhexlify self.ser = serial.Serial(self.port_name, self.baudrate, self.bytesize, self.par...
1
2016-10-13T09:40:12Z
[ "python", "byte" ]
Get a file name with tkinter.filedialog.asksaveasfilename to append in it
40,015,914
<p>from an GUI application designed with <code>tkinter</code>, I wish to save some datas in a file in appending mode. To get the file's name I use <code>asksaveasfilename</code> from <code>filedialog</code> module. Here is the code:</p> <pre><code>from tkinter.filedialog import asksaveasfilename def save_file(): ...
1
2016-10-13T08:27:55Z
40,017,696
<p>Use the option <code>confirmoverwrite</code> to prevent the message, when selecting an existing file.</p> <pre><code>import tkFileDialog import time class Example(): dlg = tkFileDialog.asksaveasfilename(confirmoverwrite=False) fname = dlg if fname != '': try: f = open(fname, "rw+")...
1
2016-10-13T09:49:59Z
[ "python", "tkinter", "filedialog" ]
Get a file name with tkinter.filedialog.asksaveasfilename to append in it
40,015,914
<p>from an GUI application designed with <code>tkinter</code>, I wish to save some datas in a file in appending mode. To get the file's name I use <code>asksaveasfilename</code> from <code>filedialog</code> module. Here is the code:</p> <pre><code>from tkinter.filedialog import asksaveasfilename def save_file(): ...
1
2016-10-13T08:27:55Z
40,019,904
<p>The <code>asksaveasfilename</code> dialog accepts a <code>confirmoverwrite</code> argument to enable or disable the file existence check.</p> <pre><code>file_name = asksaveasfilename(confirmoverwrite=False) </code></pre> <p>This can be found in the Tk manual for <a href="http://www.tcl.tk/man/tcl8.5/TkCmd/getOpenF...
2
2016-10-13T11:37:28Z
[ "python", "tkinter", "filedialog" ]
Python .append() to a vector in a single line
40,015,949
<p>I'm having problems in <code>append</code> in array. I'm expecting a result like:</p> <pre><code>['44229#0:', '2016/10/11', '11:15:57','11:15:57','11:15:57','11:15:58' '0'] </code></pre> <p>but I'm having this result:</p> <pre><code>['44229#0:', '2016/10/11', '11:15:57'] ['11:15:57'] ['11:15:57'] ['11:15:58'] ['4...
2
2016-10-13T08:29:12Z
40,015,993
<p>Shouldn't the <code>if printList</code> block be unindented?</p> <p>Or at least not set the list to [] every single line.</p>
0
2016-10-13T08:31:25Z
[ "python", "parsing", "nginx", "python-textprocessing" ]
Python .append() to a vector in a single line
40,015,949
<p>I'm having problems in <code>append</code> in array. I'm expecting a result like:</p> <pre><code>['44229#0:', '2016/10/11', '11:15:57','11:15:57','11:15:57','11:15:58' '0'] </code></pre> <p>but I'm having this result:</p> <pre><code>['44229#0:', '2016/10/11', '11:15:57'] ['11:15:57'] ['11:15:57'] ['11:15:58'] ['4...
2
2016-10-13T08:29:12Z
40,017,834
<p>To save the file, it's easier to do it using numpy. The original array is split at every element containing a '#'</p> <pre><code>import numpy as np import re file = open('log_to_parse.txt', 'r') openFile = file.readlines() file.close() #resultsFile = open('resultsFile.txt', 'a') printList = [] identifierNew ="45" ...
1
2016-10-13T09:56:26Z
[ "python", "parsing", "nginx", "python-textprocessing" ]
How to make a related field mandatory in Django?
40,016,025
<p>Suppose I have the following many-to-one relationship in Django:</p> <pre><code>from django.db import models class Person(models.Model): # ... class Address(models.Model): # ... person = models.ForeignKey(Person, on_delete=models.CASCADE) </code></pre> <p>This allows a person to have multiple address...
3
2016-10-13T08:33:03Z
40,024,797
<p>Why not make Address a many to many relationship on Person? That seems to be a more natural expression of your data. </p> <p>But regardless, you can't really enforce the many to many realation on the db. You could perhaps override the save of Person to check for an address. But I would prefer to handle it in the fo...
0
2016-10-13T15:12:14Z
[ "python", "django", "django-models", "relationship" ]
How to make a related field mandatory in Django?
40,016,025
<p>Suppose I have the following many-to-one relationship in Django:</p> <pre><code>from django.db import models class Person(models.Model): # ... class Address(models.Model): # ... person = models.ForeignKey(Person, on_delete=models.CASCADE) </code></pre> <p>This allows a person to have multiple address...
3
2016-10-13T08:33:03Z
40,026,172
<p>As previously said, there's no way to enforce a relationship directly on the database. </p> <p>However, you can take care of it by validating the model before saving using the <code>clean()</code> method. It will be automatically triggered on save for Django models.</p> <pre><code>class Person(models.Model): ....
0
2016-10-13T16:18:17Z
[ "python", "django", "django-models", "relationship" ]
python pandas : group by several columns and count value for one column
40,016,097
<p>I have <strong>df</strong>:</p> <pre><code> orgs feature1 feature2 feature3 0 org1 True True NaN 1 org1 NaN True NaN 2 org2 NaN True True 3 org3 True True NaN 4 org4 True True True 5 ...
2
2016-10-13T08:36:40Z
40,016,302
<p>You can add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html" rel="nofollow"><code>sum</code></a> to previous <a href="http://stackoverflow.com/a/40004637/2901002">solution</a>:</p> <pre><code>df1 = df.groupby('orgs') .apply(lambda x: x.iloc[:,1:].apply(lambda y: y.nu...
1
2016-10-13T08:47:59Z
[ "python", "pandas", "count", "group-by", "stack" ]
Why does the python filter do not overflow when it processes an infinite sequence?
40,016,145
<pre><code>def _odd_iter(): n = 1 while True: n = n + 2 yield n def filt(n): return lambda x: x % n &gt; 0 def primes(): yield 2 it = _odd_iter() while True: n = next(it) yield n it = filter(filt(n),it) </code></pre> <p>For example: 【3,5,7,9,11,13,15 ...
0
2016-10-13T08:39:47Z
40,016,274
<p>In Python 3, as your post is tagged, <code>filter</code> is a lazily-evaluated generator-type object. If you tried to evaluate that entire <code>filter</code> object with e.g. <code>it = list(filter(filt(n),it))</code>, you would have a bad time. You would have an equally bad time if you ran your code in Python 2, i...
1
2016-10-13T08:46:21Z
[ "python", "python-3.x", "functional-programming" ]
Request object's unique identifier - django or django rest framework
40,016,151
<p>Whenever a request goes to a server, I think there would be a unique identifier for each request object. But I couldn't find how to access that unique identifier. </p> <p>I have already read the docs for <a href="https://docs.djangoproject.com/en/1.10/ref/request-response/#django.http.HttpRequest" rel="nofollow">dj...
2
2016-10-13T08:40:04Z
40,019,330
<p>I think <code>No</code>. There is no unique identifier for each and every request something like <code>request-id</code>.We have to generate it from server or generate from client side and pass to server via <code>Header</code>. Also there is no <code>time</code> in <code>HTTP request</code> according to <a href="ht...
0
2016-10-13T11:07:44Z
[ "python", "django", "request", "django-rest-framework" ]
Inverting large JSON dictionary
40,016,192
<p>I have a JSON dictionary containing multiple entries (roughly 8 million) of the following form:</p> <pre><code>{"Some_String": {"Name0": 1, "Name1": 1, "Name42": 2, "Name5": 2, ... }, ...} </code></pre> <p>It contains strings that have been used to reference discrete named entities along with counts of how many ti...
3
2016-10-13T08:42:23Z
40,016,604
<p>Something like</p> <pre><code>from collections import defaultdict result = defaultdict(dict) for somestring, namesdict in initialdata.items(): for name, amount in namesdict.items(): result[name][something] = amount </code></pre> <p>Would do it, but with 8 million items it may become time to look at da...
0
2016-10-13T09:01:59Z
[ "python", "arrays", "json", "dictionary" ]
Reading and closing large amount of files in new class result in OSError: Too many open files
40,016,280
<p>I have large amount of files and I need to traverse them and search for some strings, when string is found, the file is copied into new folder, otherwise its closed.</p> <p>Here is example code:</p> <pre><code>import os import stringsfilter def apply_filter(path, filter_dict): dirlist = os.listdir(path) ...
1
2016-10-13T08:46:34Z
40,086,288
<p>Reason why you have same thing logged multiple times: Every time <code>main.get_module_logger("StringsFilter")</code> is called, you call <code>logger.addHandler(...)</code> on <strong>the same logger</strong> returned from <code>logging.getLogger(name)</code>, so you get multiple handlers in one logger. Better make...
0
2016-10-17T12:22:26Z
[ "python", "python-3.4" ]
How to store the resulted image from OpenCV using Python in directory?
40,016,287
<p>I have experimenting with a python script which scales the images by 2 times and it is working fine, but the problem is how to store this resulted image in my disk so I can compare the results before and after.</p> <pre><code>import cv2 import numpy as np img = cv2.imread('input.jpg') res = cv2.resize(img,None,fx...
-1
2016-10-13T08:47:01Z
40,016,514
<p>You can use imwrite function. </p> <p>You can find the description of this function <a href="http://docs.opencv.org/2.4.13/modules/highgui/doc/reading_and_writing_images_and_video.html" rel="nofollow">here</a></p>
1
2016-10-13T08:57:20Z
[ "python", "image", "python-2.7", "opencv", "numpy" ]
Index the first and the last n elements of a list
40,016,359
<p>the first n and the last n element of the python list</p> <pre><code>l=[1,2,3,4,5,6,7,8,9,10] </code></pre> <p>can be indexed by the expressions</p> <pre><code>print l[:3] [1, 2, 3] </code></pre> <p>and</p> <pre><code>print l[-3:] [8, 9, 10] </code></pre> <p>is there a way to combine both in a single expressio...
5
2016-10-13T08:50:17Z
40,016,402
<p>Just concatenate the results:</p> <pre><code>l[:3] + l[-3:] </code></pre> <p>There is no dedicated syntax to combine disjoint slices.</p>
5
2016-10-13T08:52:13Z
[ "python", "list" ]
Index the first and the last n elements of a list
40,016,359
<p>the first n and the last n element of the python list</p> <pre><code>l=[1,2,3,4,5,6,7,8,9,10] </code></pre> <p>can be indexed by the expressions</p> <pre><code>print l[:3] [1, 2, 3] </code></pre> <p>and</p> <pre><code>print l[-3:] [8, 9, 10] </code></pre> <p>is there a way to combine both in a single expressio...
5
2016-10-13T08:50:17Z
40,016,409
<p>No, but you can use:</p> <pre><code>l[:3] + l [-3:] </code></pre>
2
2016-10-13T08:52:29Z
[ "python", "list" ]
Index the first and the last n elements of a list
40,016,359
<p>the first n and the last n element of the python list</p> <pre><code>l=[1,2,3,4,5,6,7,8,9,10] </code></pre> <p>can be indexed by the expressions</p> <pre><code>print l[:3] [1, 2, 3] </code></pre> <p>and</p> <pre><code>print l[-3:] [8, 9, 10] </code></pre> <p>is there a way to combine both in a single expressio...
5
2016-10-13T08:50:17Z
40,016,450
<p>Do you mean like:</p> <pre><code>l[:3]+l[-3:] </code></pre> <p>then using variable:</p> <pre><code>l[:x]+l[-y:] </code></pre>
3
2016-10-13T08:54:06Z
[ "python", "list" ]
Index the first and the last n elements of a list
40,016,359
<p>the first n and the last n element of the python list</p> <pre><code>l=[1,2,3,4,5,6,7,8,9,10] </code></pre> <p>can be indexed by the expressions</p> <pre><code>print l[:3] [1, 2, 3] </code></pre> <p>and</p> <pre><code>print l[-3:] [8, 9, 10] </code></pre> <p>is there a way to combine both in a single expressio...
5
2016-10-13T08:50:17Z
40,016,602
<p>If it is allowed to change list, You can use this:</p> <pre><code>del(a[n:-n]) </code></pre> <p>If not, create new list and then do this.</p> <pre><code>b = [x for x in a] del(b[n:-n]) </code></pre>
2
2016-10-13T09:01:55Z
[ "python", "list" ]
Python-like multiprocessing in C++
40,016,373
<p>I am new to C++, and I am coming from a long background of Python. </p> <p>I am searching for a way to run a function in parallel in C++. I read a lot about <code>std::async</code>, but it is still not very clear for me. </p> <ol> <li><p>The following code does some really interesting thing</p> <pre><code>#includ...
4
2016-10-13T08:50:56Z
40,016,591
<p>1) <code>result.get();</code> does not start the thread. It only <strong>waits</strong> for the result. The parallel thread is launched with <code>std::async(called_from_async)</code> call (or whenever the compiler decides).</p> <p>However <code>std::cout</code> is guaranteed to be internally thread safe. So the re...
5
2016-10-13T09:01:29Z
[ "python", "c++", "asynchronous", "multiprocessing" ]
Extract weight of an item from its description using regex in python
40,016,431
<p>I have a list of product descriptions. for example:</p> <pre><code> items = ['avuhovi Grillikaapeli 320g','Savuhovi Kisamakkara 320g', 'Savuhovi Raivo 250g', 'AitoMaku str.garl.sal.dres.330ml', 'Rydbergs 225ml Hollandaise sauce'] </code></pre> <p>I want to extract the weights that is, 320g, 320g, 250ml, 330ml. I ...
3
2016-10-13T08:53:32Z
40,016,560
<p>He is one solution that may work (using <code>search</code> and <code>group</code> suggested by Wiktor):</p> <pre><code>&gt;&gt;&gt; for t in items : ... re.search(r'([0-9]+(g|ml))', t).group(1) ... '320g' '320g' '250g' '330ml' '225ml' </code></pre> <p>Indeed a better solution (thanks Wiktor) would be to test i...
5
2016-10-13T08:59:54Z
[ "python", "regex" ]
Extract weight of an item from its description using regex in python
40,016,431
<p>I have a list of product descriptions. for example:</p> <pre><code> items = ['avuhovi Grillikaapeli 320g','Savuhovi Kisamakkara 320g', 'Savuhovi Raivo 250g', 'AitoMaku str.garl.sal.dres.330ml', 'Rydbergs 225ml Hollandaise sauce'] </code></pre> <p>I want to extract the weights that is, 320g, 320g, 250ml, 330ml. I ...
3
2016-10-13T08:53:32Z
40,016,633
<p><a href="https://regex101.com/r/gy5YTp/4" rel="nofollow">https://regex101.com/r/gy5YTp/4</a></p> <p>Match any digit with <code>\d+</code> then create a matching but non selecting group with <code>(?:ml|g)</code> this will match ml or g. </p> <pre><code>import re items = ['avuhovi Grillikaapeli 320g', 'Savuhovi 33...
-1
2016-10-13T09:03:24Z
[ "python", "regex" ]
How to schedule and cancel tasks with asyncio
40,016,501
<p>I am writing a client-server application. While connected, client sends to the server a "heartbeat" signal, for example, every second. On the server-side I need a mechanism where I can add tasks (or coroutines or something else) to be executed asynchronously. Moreover, I want to cancel tasks from a client, when it s...
0
2016-10-13T08:56:56Z
40,022,171
<p>You can use <code>asyncio</code> <code>Task</code> wrappers to execute a task via the <a href="https://docs.python.org/3/library/asyncio-task.html#asyncio.ensure_future" rel="nofollow"><code>ensure_future()</code></a> method.</p> <p><code>ensure_future</code> will automatically wrap your coroutine in a <code>Task</...
2
2016-10-13T13:19:37Z
[ "python", "python-asyncio" ]
From 3D to 2D-array Basemap plot (Python)
40,016,519
<p>I'm trying to plot data on a map (basemap) according lon/lat arrays with the following shapes:</p> <pre><code>lon (Ntracks, Npoints) lat (Ntracks, Npoints) data(Ntracks, Npoints, Ncycles) </code></pre> <p>The problem is that, with the code I did below, nothing is displayed on the map (and it's terribly slow! even ...
1
2016-10-13T08:57:43Z
40,110,849
<p>This map seems to be a very nice tool, thank you for the hint :)</p> <p>If I get it right, Data should be a 2D-Array containing a value for each x-y-pair? But you fill only the first Npoints entries of Data, and then you just reshape it -- so you did not write anything in any rows besides the first of your Npoints ...
0
2016-10-18T14:23:43Z
[ "python", "arrays", "numpy" ]
Compare items in list if tuples Python
40,016,521
<p>If have this list of tuples:</p> <pre><code>l1 = [('aa', 1),('de', 1),('ac', 3),('ab', 2),('de', 2),('bc', 4)] </code></pre> <p>I want to loop over it, and check if the second item in each tuple is the same as another second item in a tuple in this list. If it is, I want to put this tuple in a new list of tuples.<...
0
2016-10-13T08:57:54Z
40,016,588
<p>You'll need two passes: one to count how many times the second element exists, and another to then build the new list based on those counts:</p> <pre><code>from collections import Counter counts = Counter(id_ for s, id_ in l1) l2 = [(s, id_) for s, id_ in l1 if counts[id_] &gt; 1] </code></pre> <p>Demo:</p> <pre...
3
2016-10-13T09:01:25Z
[ "python", "python-2.7" ]
How to schedule a job to execute Python script in cloud to load data into bigquery?
40,016,694
<p>I am trying to setup a schedule job/process in cloud to load csv data into Bigquery from google buckets using a python script. I have manage to get hold off the python code to do this but not sure where do I need to save this code so that this task could be completed as an automated process rather than running the g...
2
2016-10-13T09:07:02Z
40,018,591
<p><a href="https://cloud.google.com/solutions/reliable-task-scheduling-compute-engine" rel="nofollow">Reliable Task Scheduling on Google Compute Engine  |  Solutions  |  Google Cloud Platform</a>, the 1st link in Google on "google cloud schedule a cron job", gives a high-level overview. <a href="https://cloud.goog...
1
2016-10-13T10:34:38Z
[ "python", "google-bigquery", "google-cloud-platform", "gsutil" ]
How to detect if a string is already utf8-encoded?
40,016,832
<p>I have some strings like this:</p> <pre><code>u'Thaïlande' </code></pre> <p>This was "Thaïlande" and I dont know how it's been encoded, but I need to bring it back to "Thaïlande", then URL-encode it.</p> <p>Is there a way to guess if a string has already been encoded with Python 2?</p>
0
2016-10-13T09:13:44Z
40,016,915
<p>You have what is called a <a href="https://en.wikipedia.org/wiki/Mojibake" rel="nofollow">Mojibake</a>. You could use statistical analysis to see if there is a unusual number of Latin-1 characters in there in a combination typical of UTF-8 bytes, or if there are any CP1252-specific characters in there.</p> <p>There...
1
2016-10-13T09:16:57Z
[ "python", "python-2.7", "character-encoding" ]
Change Python version for evaluating file with SublimREPL plugin
40,016,838
<p>I am using Sublim Text 3 on Mac OS X El Capitan. What I need to do is to evaluate a Python file within Sublime Text 3.</p> <p>I have installed <code>Package Control</code> and then <code>SublimREPL</code> plugins.</p> <p>I have set up a 2 rows layout (<code>View &gt; Layout &gt; Rows: 2</code>) in order to display...
0
2016-10-13T09:13:56Z
40,131,394
<p>It appears you are modifying the incorrect configuration files and perhaps a few things are causing issues.</p> <blockquote> <p>I then launch the Python interpreter with <code>Tools &gt; Command Palette... &gt; SublimeREPL: Python</code></p> </blockquote> <p>There is no command palette item "SublimeREPL: Python"...
0
2016-10-19T12:27:29Z
[ "python", "osx", "sublimetext3", "osx-elcapitan", "sublimerepl" ]
Scraping dynamic website to get elements in <script tag> using BeautifulSoup and Selenium
40,016,884
<p>I am trying to scrape a dynamic website by using beautifulsoup and selenium. The attributes I would like to filter and put into a CSV are contained within a <code>&lt;script&gt;</code> tag. I would like to extract contained in </p> <p>Script: window.IS24 = window.IS24 || {}; IS24.ssoAppName = "search";...
0
2016-10-13T09:15:53Z
40,017,181
<p>Here is how you can pull out attribute values from a tag with beautifulSoup.</p> <pre><code>import urllib2 from bs4 import BeautifulSoup req = urllib2.Request('http://website_to_grab_things_from.com') response = urllib2.urlopen(req) html = response.read() soup = BeautifulSoup(html, "html.parser") alltext = soup.ge...
0
2016-10-13T09:27:58Z
[ "jquery", "python", "selenium", "web-scraping", "beautifulsoup" ]
Python to update JSON file
40,016,895
<p>After googling around and checking some other posts I still haven't found a solution for my issue. </p> <p>Let me quickly explain what I'm after:</p> <p>I've got a JSON configuration file with the following syntax:</p> <pre><code> [ { "name": "Name 1", "provider": "Provi...
0
2016-10-13T09:16:23Z
40,017,401
<p>You can try something similar to below;</p> <pre><code> myList = [ { "name": "Name 1", "provider": "Provider 1", "url": "/1", "source": "URL" }, { "name": "Name 2", ...
0
2016-10-13T09:37:41Z
[ "python", "json" ]
Python to update JSON file
40,016,895
<p>After googling around and checking some other posts I still haven't found a solution for my issue. </p> <p>Let me quickly explain what I'm after:</p> <p>I've got a JSON configuration file with the following syntax:</p> <pre><code> [ { "name": "Name 1", "provider": "Provi...
0
2016-10-13T09:16:23Z
40,017,726
<p>Assuming <code>test.json</code> is your json file containing the text you inserted in the question, you can do the following</p> <pre><code>import json with open('test.json') as my_file: json_content = json.load(my_file) for ele in json_content: print(ele) </code></pre> <p>{'name': 'Name 1', 'provider': 'P...
0
2016-10-13T09:51:37Z
[ "python", "json" ]
Python to update JSON file
40,016,895
<p>After googling around and checking some other posts I still haven't found a solution for my issue. </p> <p>Let me quickly explain what I'm after:</p> <p>I've got a JSON configuration file with the following syntax:</p> <pre><code> [ { "name": "Name 1", "provider": "Provi...
0
2016-10-13T09:16:23Z
40,018,098
<p>Thank you very much both answers do work I just need to adapt some more code in order to make it ready as @MMF suggested the script should then run via cron.</p> <p>Thanks a lot for your help guys!!</p>
0
2016-10-13T10:09:28Z
[ "python", "json" ]
Tensorflow: Fine tune Inception model
40,016,933
<p>For a few days I am following the instructions here:<a href="https://github.com/tensorflow/models/tree/master/inception" rel="nofollow">https://github.com/tensorflow/models/tree/master/inception</a> for fine-tuning inception model. The problem is that my dataset is huge so converting it to TFRecords format would fil...
0
2016-10-13T09:17:34Z
40,031,748
<p>Fine-tuning is independent of the data format; you're fine there. TFRecords promotes training and scoring speed; it shouldn't affect the quantity of iterations or epochs needed, nor the ultimate classification accuracy.</p>
0
2016-10-13T22:00:53Z
[ "python", "machine-learning", "tensorflow", "deep-learning" ]
Regular expression finding '\n'
40,016,950
<p>I'm in the process of making a program to pattern match phone numbers in text.</p> <p>I'm loading this text:</p> <pre><code>(01111-222222)fdf 01111222222 (01111)222222 01111 222222 01111.222222 </code></pre> <p>Into a variable, and using "findall" it's returning this:</p> <pre><code>('(01111-222222)', '(01111', ...
4
2016-10-13T09:18:24Z
40,017,060
<p>The <code>\s</code> matches both <em>horizontal</em> and <em>veritcal</em> whitespace symbols. If you have a <code>re.VERBOSE</code>, you can match a normal space with an escaped space <code>\ </code>. Or, you may exclude <code>\r</code> and <code>\n</code> from <code>\s</code> with <code>[^\S\r\n]</code> to match h...
4
2016-10-13T09:22:54Z
[ "python", "regex" ]
If I terminate the process, the thread would also stop?
40,017,328
<p>I've following code :</p> <pre><code>#!/usr/bin/python3 import os import subprocess import time import threading class StartJar(threading.Thread): def run(self): os.system("java -jar &lt;nazwa_appki&gt;.jar") jarFileRun = StartJar current_location = subprocess.getoutput("pwd") while True: ...
0
2016-10-13T09:34:44Z
40,018,246
<p>If you terminate the process,all threads corresponding to that process would terminate. the process will still run if you terminate one of the threads in process.</p>
0
2016-10-13T10:17:07Z
[ "python", "multithreading", "python-3.x", "python-3.4", "python-multithreading" ]
If I terminate the process, the thread would also stop?
40,017,328
<p>I've following code :</p> <pre><code>#!/usr/bin/python3 import os import subprocess import time import threading class StartJar(threading.Thread): def run(self): os.system("java -jar &lt;nazwa_appki&gt;.jar") jarFileRun = StartJar current_location = subprocess.getoutput("pwd") while True: ...
0
2016-10-13T09:34:44Z
40,018,361
<p>No it will not terminate because the value <code>daemon</code> is by default False and it means that the thread doesn't stop when the main process finishes, it's totally independent. However, if you set the thread's daemon value to <code>True</code> it will run as long as the main process runs too.</p> <p>In order ...
-1
2016-10-13T10:23:41Z
[ "python", "multithreading", "python-3.x", "python-3.4", "python-multithreading" ]
Is numpy.polyfit with 1 degree of fitting, TLS or OLS?
40,017,357
<p>I have two timeseries x and y, both have the same length. Using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html" rel="nofollow">numpy.polyfit</a>, I fit a straight line through the data with:</p> <pre><code>numpy.polyfit(x,y,1) </code></pre> <p>Is this <a href="https://en.wikipedia....
2
2016-10-13T09:35:46Z
40,017,928
<p>You can use <a href="http://docs.scipy.org/doc/scipy/reference/odr.html" rel="nofollow">scipy.odr</a> it will compute orthogonal regression which should be equal to tls. </p>
1
2016-10-13T10:00:44Z
[ "python", "numpy", "scipy" ]
Passing parameter (directory) to %cd command in ipython notebook
40,017,360
<p>I'm trying to pass a parameter (directory) to a %cd command in ipython notebook as below:</p> <pre><code> rootdir = "D:\mydoc" %cd rootdir </code></pre> <p>but i get the following error:</p> <pre><code> [Error 2] The system cannot find the file specified: u'rootdir' D:\mydoc </code></pre> <p>when i'm doing </p...
0
2016-10-13T09:35:59Z
40,017,458
<p>You can use <code>$</code> to use the value in a variable.</p> <pre><code>%cd $rootdir </code></pre>
1
2016-10-13T09:39:55Z
[ "python", "directory", "ipython", "parameter-passing", "jupyter-notebook" ]
xml ns0: prefix cant make the previous solutions work
40,017,379
<p>i know there are several questions that are already answered about this topic but for some reason i cant make it work when i read the file. </p> <p>this is the code i have </p> <pre><code>import xml.etree.ElementTree as etree import copy etree.register_namespace("","http://www.w3.org/2001/XMLSchema") etree.registe...
1
2016-10-13T09:36:54Z
40,040,868
<p>I understand the problem now, you have unwanted ns0 prefixes in your output. In order to avoid them you may need to register all the namespaces with their corresponding prefixes:</p> <pre><code>etree.register_namespace("xs","http://www.w3.org/2001/XMLSchema") etree.register_namespace("xsi","http://www.w3.org/2001/X...
0
2016-10-14T10:24:38Z
[ "python", "xml", "elementtree" ]
Saving Django 400 bad requests for analyzing purposes
40,017,391
<p>I have a Django-based API.</p> <p>Sometimes my customers inform me that some of the their requests return 400 (bad request) even that they're not supposed to.</p> <p>I thought about a good way to handle and debug that exact problem, by saving the failed-requests, with all of the headers (such as the Access Token) ...
2
2016-10-13T09:37:20Z
40,019,364
<p>If the 400 response is generated by Django, you can use a <a href="https://docs.djangoproject.com/en/1.10/topics/http/middleware/" rel="nofollow">custom middleware</a> (beware: the middleware api changed in 1.10, for django &lt;= 1.9 the doc is <a href="https://docs.djangoproject.com/en/1.9/topics/http/middleware/" ...
1
2016-10-13T11:09:41Z
[ "python", "django" ]
Moviepy - TypeError: Can't convert 'bytes' object to str implicitly
40,017,394
<pre><code>from moviepy.editor import * clip = VideoFileClip("vid.mov") clip.write_videofile("movie.mp4") </code></pre> <p>^ Gives the error </p> <pre><code>TypeError: Can't convert 'bytes' object to str implicitly. </code></pre> <p>It prints "Building video movie.mp4" and "Writing audio in movieTEMP_MPY_wvf_snd.mp3...
0
2016-10-13T09:37:28Z
40,024,390
<p>As per <a href="https://github.com/Zulko/moviepy/issues/330" rel="nofollow">this</a> answer, the issue was that there is an error in the moviepy script which generates an incorrect error output. The correct output indicates that I had not install the libmp3lame codec when I installed ffmpeg, so it could not write au...
0
2016-10-13T14:52:37Z
[ "python", "raspberry-pi", "raspbian", "moviepy" ]
What am I doing wrong with this negative lookahead? Filtering out certain numbers in a regex
40,017,590
<p>I have a big piece of code produced by a software. Each instruction has an identifier number and I have to modify only certain numbers:</p> <pre><code>grr.add(new GenericRuleResult(RULEX_RULES.get(String.valueOf(11)), new Result(0,Boolean.FALSE,"ROSSO"))); grr.add(new GenericRuleResult(RULEX_RULES.get(String.valueO...
0
2016-10-13T09:45:54Z
40,018,064
<p>Your problem is that you are assuming a negative look ahead changes the cursor position, it does not. </p> <p>That is, a negative lookahead of the form <code>(?!xy)</code> merely verifies that the <em>next</em> two characters are not <code>xy</code>. It does not then swallow two characters from the text. As its ...
1
2016-10-13T10:07:22Z
[ "python", "regex", "sublimetext3" ]
Getting the correct dimensions after using np.nonzero on array
40,017,986
<p>When using the the np.nonzero on a 1d array: </p> <pre><code>l = np.array([0, 1, 2, 3, 0]) np.nonzero(l) array([1,2,3], dtype=int64) </code></pre> <p>How do I get the index information as a 1d array and not as a tuple in the most effecient way? </p>
1
2016-10-13T10:03:12Z
40,018,005
<p><code>np.nonzero</code> will return the index information as a 1d tuple only. However, if you are looking for an alternative,Use <code>np.argwhere</code></p> <pre><code>import numpy as np l = np.array([0, 1, 2, 3, 0]) non_zero = np.argwhere(l!=0) </code></pre> <p>However, this will return a column matrix. To conve...
0
2016-10-13T10:04:14Z
[ "python", "arrays", "numpy", "shape", "zero" ]
Getting the correct dimensions after using np.nonzero on array
40,017,986
<p>When using the the np.nonzero on a 1d array: </p> <pre><code>l = np.array([0, 1, 2, 3, 0]) np.nonzero(l) array([1,2,3], dtype=int64) </code></pre> <p>How do I get the index information as a 1d array and not as a tuple in the most effecient way? </p>
1
2016-10-13T10:03:12Z
40,018,540
<p>You are looking for <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.flatnonzero.html" rel="nofollow"><code>np.flatnonzero</code></a> for use on a <code>1D</code> array -</p> <pre><code>In [5]: l Out[5]: array([0, 1, 2, 3, 0]) In [6]: np.flatnonzero(l) Out[6]: array([1, 2, 3]) </code></pre...
0
2016-10-13T10:32:12Z
[ "python", "arrays", "numpy", "shape", "zero" ]
Getting the correct dimensions after using np.nonzero on array
40,017,986
<p>When using the the np.nonzero on a 1d array: </p> <pre><code>l = np.array([0, 1, 2, 3, 0]) np.nonzero(l) array([1,2,3], dtype=int64) </code></pre> <p>How do I get the index information as a 1d array and not as a tuple in the most effecient way? </p>
1
2016-10-13T10:03:12Z
40,019,626
<p>Just index the tuple</p> <pre><code>Idn = np.nonzero(l)[0] </code></pre> <p>Code of <code>flatnonzero</code> does</p> <pre><code>return a.ravel().nonzero()[0] </code></pre>
0
2016-10-13T11:23:10Z
[ "python", "arrays", "numpy", "shape", "zero" ]
prettify adding extra lines in xml
40,018,043
<p>I'm using Prettify to make my XML file readable. I am adding some new info in to an excising XML file but when i save it to a file i get extra lines in between the lines. is there a way of removing these line? Below is the code i'm using </p> <pre><code>import xml.etree.ElementTree as xml import xml.dom.minidom as ...
0
2016-10-13T10:06:21Z
40,019,783
<p>The new content added is being printed fine. Removing any "prettification" of the existing text solves the issue </p> <p>Add </p> <pre><code>for elem in root.iter('*'): if elem == e: print "Added XML node does not need to be stripped" continue if elem.text is not None: elem.text = e...
0
2016-10-13T11:31:22Z
[ "python", "xml", "prettify" ]
Binning of data along one axis in numpy
40,018,125
<p>I have a large two dimensional array <code>arr</code> which I would like to bin over the second axis using numpy. Because <code>np.histogram</code> flattens the array I'm currently using a for loop:</p> <pre><code>import numpy as np arr = np.random.randn(100, 100) nbins = 10 binned = np.empty((arr.shape[0], nbins...
2
2016-10-13T10:10:57Z
40,018,765
<p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.apply_along_axis.html" rel="nofollow"><code>np.apply_along_axis</code></a>:</p> <pre><code>x = np.array([range(20), range(1, 21), range(2, 22)]) nbins = 2 &gt;&gt;&gt; np.apply_along_axis(lambda a: np.histogram(a, bins=nbins)[0], 1, x...
1
2016-10-13T10:42:12Z
[ "python", "numpy", "histogram", "binning" ]
Binning of data along one axis in numpy
40,018,125
<p>I have a large two dimensional array <code>arr</code> which I would like to bin over the second axis using numpy. Because <code>np.histogram</code> flattens the array I'm currently using a for loop:</p> <pre><code>import numpy as np arr = np.random.randn(100, 100) nbins = 10 binned = np.empty((arr.shape[0], nbins...
2
2016-10-13T10:10:57Z
40,059,479
<p>You have to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogramdd.html#numpy.histogramdd" rel="nofollow">numpy.histogramdd</a> specifically meant for your problem </p>
0
2016-10-15T13:16:40Z
[ "python", "numpy", "histogram", "binning" ]
Run function after t time
40,018,172
<p>I got a problem is: have a variable total time is <code>t_total</code> after a time in <code>t_total</code> i want to run some function and the time continue count up or down to the end of <code>t_total</code>. It look like: <code>---t1---t2--</code> when time equal t1 run a function and in t2 run another function. ...
0
2016-10-13T10:13:03Z
40,018,239
<p>Add into function 1 to start a new timer starting at time t. You can export the value of t, t1 and t2 into function 1 and continue a new timer.</p>
0
2016-10-13T10:16:42Z
[ "python" ]
Run function after t time
40,018,172
<p>I got a problem is: have a variable total time is <code>t_total</code> after a time in <code>t_total</code> i want to run some function and the time continue count up or down to the end of <code>t_total</code>. It look like: <code>---t1---t2--</code> when time equal t1 run a function and in t2 run another function. ...
0
2016-10-13T10:13:03Z
40,018,369
<p>You can do using <a href="https://docs.python.org/2/library/threading.html" rel="nofollow">thread</a></p> <pre><code>import threading for t in range(t_total): t = t + 1 time.sleep(1) if t = t1: threading.Thread(target=function1).start() </code></pre>
4
2016-10-13T10:24:18Z
[ "python" ]
Python How to open an URL and get source code at the same time?
40,018,348
<p>What I had try are as following:</p> <p>1)</p> <pre><code>response = urllib2.urlopen(url) html = response.read() </code></pre> <p>In this way, I can't open the url in browser.</p> <p>2)</p> <pre><code>webbrowser.open(url) </code></pre> <p>In this way, I can't get source code of the url.</p> <p>So, how can I o...
0
2016-10-13T10:22:59Z
40,018,429
<p>Have a look at BeautifulSoup: <a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">https://www.crummy.com/software/BeautifulSoup/</a></p> <p>You can request a website and then read the HTML source code from it:</p> <pre><code>import requests from bs4 import BeautifulSoup r = requests.get(YourUR...
1
2016-10-13T10:26:37Z
[ "python" ]
Converting a string into list of desired tokens using python
40,018,391
<p>I have ingredients for thousands of products for example:</p> <pre><code>Ingredient = 'Beef stock (beef bones, water, onion, carrot, beef meat, parsnip, thyme, parsley, clove, black pepper, bay leaf), low lactose cream (28%), onion, mustard, modified maize starch,tomato puree, modified potato starch, butter sugar, ...
1
2016-10-13T10:25:09Z
40,019,132
<p>You might try two approaches.</p> <p>The first one is to remove all <code>(...)</code> substrings and anything that is not <code>,</code> after (that is not followed with non-word boundary).</p> <pre><code>\s*\([^()]*\)[^,]*(?:,\b[^,]*)* </code></pre> <p>See the <a href="https://regex101.com/r/XvpB0t/1" rel="nofo...
1
2016-10-13T10:59:25Z
[ "python", "regex" ]
list() uses more memory than list comprehension
40,018,398
<p>So i was playing with <code>list</code> objects and found little strange thing that if <code>list</code> is created with <code>list()</code> it uses more memory, than list comprehension? I'm using Python 3.5.2</p> <pre><code>In [1]: import sys In [2]: a = list(range(100)) In [3]: sys.getsizeof(a) Out[3]: 1008 In [4...
54
2016-10-13T10:25:25Z
40,018,719
<p>I think you're seeing over-allocation patterns this is a <a href="https://github.com/python/cpython/blob/3.5/Objects/listobject.c#L42" rel="nofollow">sample from the source</a>:</p> <pre><code>/* This over-allocates proportional to the list size, making room * for additional growth. The over-allocation is mild, b...
41
2016-10-13T10:40:13Z
[ "python", "list", "list-comprehension" ]
list() uses more memory than list comprehension
40,018,398
<p>So i was playing with <code>list</code> objects and found little strange thing that if <code>list</code> is created with <code>list()</code> it uses more memory, than list comprehension? I'm using Python 3.5.2</p> <pre><code>In [1]: import sys In [2]: a = list(range(100)) In [3]: sys.getsizeof(a) Out[3]: 1008 In [4...
54
2016-10-13T10:25:25Z
40,019,900
<p>Thanks everyone for helping me to understand that awesome Python.</p> <p>I don't want to make question that massive(that why i'm posting answer), just want to show and share my thoughts.</p> <p>As @ReutSharabani noted correctly: "list() deterministically determines list size". You can see it from that graph.</p> ...
23
2016-10-13T11:37:10Z
[ "python", "list", "list-comprehension" ]
Cython- Cannot open include file: 'io.h': No such file or directory
40,018,405
<p>Just starting learning cython. I was trying to compile a simple .pyx file.</p> <pre><code>print("hello") </code></pre> <p>Here's my setup.py:</p> <pre><code>from distutils.core import setup from Cython.Build import cythonize setup( ext_modules = cythonize("hello.pyx") ) </code></pre> <p>Then I run the comma...
0
2016-10-13T10:25:36Z
40,037,613
<p>Well... the error went away after I uninstalled all Microsoft and python related software and install Anaconda and VS2015 Express again. However, another error came along... </p>
0
2016-10-14T07:40:54Z
[ "python", "cython" ]
How to pretty print dictionaries in iPython
40,018,594
<p>I'm currently using RethinkDB, which has a nice web UI with a Data Explorer which allows the user to print out the contents of the database like this:</p> <p><a href="https://i.stack.imgur.com/bKKgU.png" rel="nofollow"><img src="https://i.stack.imgur.com/bKKgU.png" alt="enter image description here"></a></p> <p>No...
0
2016-10-13T10:34:44Z
40,019,015
<p>You could use <a href="https://docs.python.org/3/library/json.html#json.dumps" rel="nofollow"><code>json.dumps()</code></a>:</p> <pre><code>import json for row in r.db(....).run(conn): print(json.dumps(row, indent=4)) </code></pre> <p>Although this does not display the keys in sorted order, as appears to be ...
3
2016-10-13T10:54:14Z
[ "python", "rethinkdb" ]
How to pretty print dictionaries in iPython
40,018,594
<p>I'm currently using RethinkDB, which has a nice web UI with a Data Explorer which allows the user to print out the contents of the database like this:</p> <p><a href="https://i.stack.imgur.com/bKKgU.png" rel="nofollow"><img src="https://i.stack.imgur.com/bKKgU.png" alt="enter image description here"></a></p> <p>No...
0
2016-10-13T10:34:44Z
40,023,364
<p><a href="http://stackoverflow.com/users/21945/mhawke">mhawke</a>'s answer works if one adds the keyword argument <code>time_format="raw"</code> to RethinkDB's <code>run()</code> command. (Otherwise, you get a <code>TypeError</code> because RethinkDB's object containing the time zone is not JSON serializable). The re...
0
2016-10-13T14:09:05Z
[ "python", "rethinkdb" ]
Sphinx cross referencing breaks for inherited objects imported and documented in a parent module
40,018,681
<p>I'm trying to get my Sphinx documentation build correctly and have cross-references (including those from inherited relations) work right.</p> <p>In my project, I have a situation which is depicted in the example below, which I replicated for convenience on <a href="https://github.com/anjos/sphinx-broken-xref" rel=...
2
2016-10-13T10:38:34Z
40,040,000
<p>Sphinx uses the value of the <code>__module__</code> attribute to figure out the name of the module in which a class/function/method was defined (see <a href="https://docs.python.org/2/reference/datamodel.html#the-standard-type-hierarchy" rel="nofollow">https://docs.python.org/2/reference/datamodel.html#the-standard...
1
2016-10-14T09:43:31Z
[ "python", "python-sphinx" ]
What is the "role" argument in QTableWidgetItem.data(self, int *role*)?
40,018,723
<p>I am looking through the documentation at:</p> <ul> <li><a href="http://pyqt.sourceforge.net/Docs/PyQt4/qtablewidgetitem.html#data" rel="nofollow">http://pyqt.sourceforge.net/Docs/PyQt4/qtablewidgetitem.html#data</a></li> </ul> <p>I can put the line <code>IDList.append(item.data())</code> into my code, and print t...
1
2016-10-13T10:40:16Z
40,021,010
<p>An item has many kinds of data associated with it, such as text, font, background, tooltip, etc. The <code>role</code> is a value from the <a href="https://doc.qt.io/qt-4.8/qt.html#ItemDataRole-enum" rel="nofollow">ItemDataRole enum</a> that allows you to specify which kind of data you want.</p> <p>Some of these it...
2
2016-10-13T12:29:02Z
[ "python", "pyqt", "qtablewidgetitem" ]
how do you map a pandas dataframe column to a function which requires more than one parameter
40,018,755
<p>I have a function which has two arguments, the first argument is some text the second a regex pattern. </p> <p>I want to pass each row of a certain column from my dataframe to a function using .map however I am not sure how to direct the data from the dataframe to be the first argument and the regex (which will be ...
1
2016-10-13T10:41:58Z
40,019,301
<p>I think you need <code>lambda</code> function with parameters <code>pattern</code> and <code>x</code>:</p> <pre><code>df['new_column'] = df['source_code'].map(lambda x: some_function(pattern, x)) df['new_column'] = df['source_code'].apply(lambda x: some_function(pattern, x)) </code></pre> <p>Thank you <a href="ht...
1
2016-10-13T11:06:26Z
[ "python", "regex", "pandas" ]
SQLalchemy slow with Redshift
40,018,778
<p>I have a 44k rows table in a pandas Data Frame. When I try to export this table (or any other table) to a Redshift database, the process takes ages. I'm using sqlalchemy to create a conexion like this:</p> <pre><code>import sqlalchemy as sal engine = sal.create_engine('redshift+psycopg2://blablamyhost/myschema') </...
0
2016-10-13T10:42:46Z
40,106,504
<p>Yes, it is normal to be that slow (and possibly slower for large clusters). Regular sql inserts (as generated by sqlalchemy) are very slow for Redshift, and should be avoided.</p> <p>You should consider using S3 as an intermediate staging layer, your data flow will be: dataframe->S3->redshift</p> <p>Ideally, you s...
1
2016-10-18T11:03:48Z
[ "python", "sqlalchemy" ]
Python - Interactive phonebook
40,018,832
<p>I need help with adding a name and phone number to a dictionary in ONE line with <code>raw_input</code>. It should look like this: <code>add John 123</code> (adds the name John with the number 123). Here is my code:</p> <pre><code>def phonebook(): pb={} while True: val,q,w=raw_input().split(" ") ...
0
2016-10-13T10:45:44Z
40,019,202
<p>The following line assume that you type exactly 3 words each separated by a space character:</p> <pre><code>val, q, w = raw_input().split(" ") </code></pre> <p>If you have less or more than 3 words (which is the case when you use the lookup command, isn't it?), you will get an unpack error.</p> <p>You could get t...
2
2016-10-13T11:02:12Z
[ "python", "split", "interactive" ]
Python - Interactive phonebook
40,018,832
<p>I need help with adding a name and phone number to a dictionary in ONE line with <code>raw_input</code>. It should look like this: <code>add John 123</code> (adds the name John with the number 123). Here is my code:</p> <pre><code>def phonebook(): pb={} while True: val,q,w=raw_input().split(" ") ...
0
2016-10-13T10:45:44Z
40,019,287
<p>I think you get an unpack error when you lookup someone with "lookup john". The code looks for a third value in the split(" ") but doesn't find one.</p> <p>I'm not sure if this might help:</p> <pre><code>def phonebook(): pb={} while True: vals = raw_input().split(" ") if vals[0] == 'add': q = vals[...
1
2016-10-13T11:05:58Z
[ "python", "split", "interactive" ]
How do I resize rows with setRowHeight and resizeRowToContents in PyQt4?
40,019,022
<p>I have a small issue with proper resizing of rows in my tableview. I have a vertical header and no horizontal header. I tried:</p> <pre><code>self.Popup.table.setModel(notesTableModel(datainput)) self.Popup.table.horizontalHeader().setVisible(False) self.Popup.table.verticalHeader().setFixedWidth(200) for n in xran...
0
2016-10-13T10:54:43Z
40,043,620
<p>For me, both <code>setRowHeight</code> and <code>resizeRowsToContents</code> work as expected. Here's the test script I used:</p> <pre><code>from PyQt4 import QtCore, QtGui class Window(QtGui.QWidget): def __init__(self, rows, columns): super(Window, self).__init__() self.table = QtGui.QTableVi...
0
2016-10-14T12:50:20Z
[ "python", "pyqt4", "qtableview" ]
PHP exec command is not returning full data from Python script
40,019,042
<p>I am connecting to a server through PHP SSH and then using exec to run a python program on that server. </p> <p>If I connect to that server through putty and execute the same command through command line, I get result like:</p> <blockquote> <p>Evaluating....</p> <p>Connecting....</p> <p>Retrieving data...
0
2016-10-13T10:55:17Z
40,019,200
<p>Perhaps it's caused by buffering of the output. Try adding the <code>-u</code> option to your Python command - this forces stdout, stdin and stderr to be unbuffered.</p>
1
2016-10-13T11:02:07Z
[ "php", "python", "ssh", "centos", "exec" ]
Build nested dictionary in shell script
40,019,081
<p>My aim is to create a dictionary structure as mentioned below in shell script and pass that as an argument to a python script. I can build that dictionary in python script itself by passing all variable value from shell. Actually that will be too much of arguments for my python script.</p> <pre><code>{ "a": "He...
1
2016-10-13T10:57:13Z
40,019,857
<p>You can create a json file with your dictionary and pass to python script with argparse</p> <p>For example:</p> <pre><code>import os import argparse import json def execute(json_file): if os.path.isfile(json_file): with open(json_file) as json_data: data = json.load(json_data) ...
0
2016-10-13T11:35:01Z
[ "python", "shell", "dictionary" ]
Unable to use JSON.parse in my django template
40,019,107
<p>I have a variable data1 in my Django view which has been returned in the following way -</p> <pre><code>def dashboard(request): df1 = pd.read_excel("file.xlsx") str1= df1.to_json(orient = 'records') data1 = json.loads(str1) return render(request, 'dashboard/new 1.html',{'data1' : data1}) </code></pre> ...
1
2016-10-13T10:58:14Z
40,019,153
<p>Try outputting it as a string:</p> <pre><code>&lt;script type = text/javascript&gt; var ob2 = JSON.parse( "{{ data1 }}" ); document.write(ob2); &lt;/script&gt; </code></pre> <p>If this is not producing the results, I suggest just printing <code>{{ data1 }}</code> on screen and seeing exactly what is being ...
1
2016-10-13T11:00:15Z
[ "javascript", "python", "json", "django" ]
Unable to use JSON.parse in my django template
40,019,107
<p>I have a variable data1 in my Django view which has been returned in the following way -</p> <pre><code>def dashboard(request): df1 = pd.read_excel("file.xlsx") str1= df1.to_json(orient = 'records') data1 = json.loads(str1) return render(request, 'dashboard/new 1.html',{'data1' : data1}) </code></pre> ...
1
2016-10-13T10:58:14Z
40,019,199
<p>Besides The Brewmaster's answer, the other problems are:</p> <pre><code>data1 = json.loads(str1) </code></pre> <p>That turns the JSON string back into a Python data structure. Just send <code>str1</code> itself to the template, and call it <code>a</code> as that's what you use in the template:</p> <pre><code>retu...
1
2016-10-13T11:02:04Z
[ "javascript", "python", "json", "django" ]
Unable to use JSON.parse in my django template
40,019,107
<p>I have a variable data1 in my Django view which has been returned in the following way -</p> <pre><code>def dashboard(request): df1 = pd.read_excel("file.xlsx") str1= df1.to_json(orient = 'records') data1 = json.loads(str1) return render(request, 'dashboard/new 1.html',{'data1' : data1}) </code></pre> ...
1
2016-10-13T10:58:14Z
40,019,543
<p>Try this by remove <code>Parse</code></p> <pre><code> &lt;script type = text/javascript&gt; document.write("{{ data1 }}"); &lt;/script&gt; </code></pre>
0
2016-10-13T11:19:24Z
[ "javascript", "python", "json", "django" ]
parse xml files in subdirectories using beautifulsoup in python
40,019,122
<p>I have more than 5000 XML files in multiple sub directories named f1, f2, f3, f4,... Each folder contains more than 200 files. At the moment I want to extract all the files using BeautifulSoup only as I have already tried lxml, elemetTree and minidom but am struggling to get it done through BeautifulSoup. </p> <p>I...
0
2016-10-13T10:58:54Z
40,019,427
<p>Use <code>glob.glob</code> to find the XML documents:</p> <pre><code>import glob from bs4 import BeautifulSoup for filename in glob.glob('//Folder/*/*.XML'): content = BeautifulSoup(filename, 'lxml-xml') print(content.prettify()) </code></pre> <p><em>note</em>: don't shadow the builtin function/class <co...
0
2016-10-13T11:12:47Z
[ "python", "xml-parsing", "beautifulsoup" ]
parse xml files in subdirectories using beautifulsoup in python
40,019,122
<p>I have more than 5000 XML files in multiple sub directories named f1, f2, f3, f4,... Each folder contains more than 200 files. At the moment I want to extract all the files using BeautifulSoup only as I have already tried lxml, elemetTree and minidom but am struggling to get it done through BeautifulSoup. </p> <p>I...
0
2016-10-13T10:58:54Z
40,019,432
<p>If I understood you correctly, then you do need to loop through the files, as you had already thought:</p> <pre><code>from bs4 import BeautifulSoup from pathlib import Path for filepath in Path('./Folder').glob('*/*.XML'): with filepath.open() as f: soup = BeautifulSoup(f,'lxml-xml') print(soup.pre...
1
2016-10-13T11:13:03Z
[ "python", "xml-parsing", "beautifulsoup" ]
putting bounding box around text in a image
40,019,315
<p>I want to compare two screenshots containing text. Basically both the screenshots contains some pretty formatted text. I want to compare if the same formatting being reflected in both the pictures as well as same text appearing at same location in both images. </p> <p>How I am doing it right now is - </p> <pre><co...
0
2016-10-13T11:07:13Z
40,022,760
<p>I'm not sure to understand what do you want exactly but to get bounding box around word in image, i could do this :</p> <ol> <li>Apply processing to get good a thresholding : only text, background in black, text in white. This step depends on the type and quality of your image.</li> <li>Compute the sum of each line...
0
2016-10-13T13:44:17Z
[ "python", "opencv", "image-processing" ]
How to insert ' into postgresql?
40,019,347
<p>I use <code>python</code> package <code>psycopg2</code> to update database.</p> <pre><code>cur.execute("UPDATE scholars SET name='{}' WHERE id={} and name is null".format(author, scholar_id)) </code></pre> <p><code>psycopg2.ProgrammingError: syntax error at or near "Neill" LINE 1: UPDATE scholars SET name='O'Neill...
0
2016-10-13T11:08:22Z
40,021,767
<p>Use <a href="http://initd.org/psycopg/docs/usage.html#query-parameters" rel="nofollow">Psycopg's parameter passing functionality</a>:</p> <pre><code>cur.execute (""" UPDATE scholars SET name = %s WHERE id = %s and name is null """, (author, scholar_id) ) </code></pre> <p><a href="https://docs...
1
2016-10-13T13:00:19Z
[ "python", "postgresql", "psycopg2" ]
Python Iterate over a list
40,019,371
<p>trying to figure this one out, i have 3 dictionaries and i am after adding them to a list, but how can i loop over list and print out that list.</p> <pre><code>def_person = {'name' : 'TEST1','JobRole' : 'TESTJOB'} def_person1 = {'name' : 'TEST2','JobRole' : 'TESTJOB1'} def_person2 = {'name' : 'TEST3','JobRole' : 'T...
-3
2016-10-13T11:10:05Z
40,068,266
<p>Actually you cannot assume that all dictionaries having the same keys would display the keys in the same order - this is in no way guaranteed. Instead you should have a list of keys that you'd print in order, and then iterate over this key list for each dictionary, pulling values for each key.</p> <p>I show how to ...
2
2016-10-16T08:11:02Z
[ "python", "python-3.x" ]
HTTP Server with active TCP connections in python
40,019,418
<p>I am writing a pseudo-http application in python, the requirements for which are:</p> <ol> <li>It should handle HTTP requests.</li> <li>The connections between the client and the server outlive the request-response, i.e. the underlying TCP connection remains alive after a response has been sent to a client.</li> <l...
1
2016-10-13T11:12:33Z
40,063,132
<p>Since you cannot use websockets or http/2, and you require the ability to push data from the server to the client, then long-polling is probably the best option remaining.</p> <p>See Nevow, at <a href="https://github.com/twisted/nevow" rel="nofollow">https://github.com/twisted/nevow</a>, for one possible implementa...
1
2016-10-15T19:08:51Z
[ "python", "tcp", "twisted", "httpserver" ]
Python tkinter displaying images as movie stream
40,019,449
<p>I am trying to screen-grab and display the image quickly like a recording. It seems to all function well except the display window is "blinking" occasionally with a white frame. It doesn't appear to be every update or every other frame, but rather every 5 or so. Any thoughts on the cause?</p> <pre><code>from tkinte...
0
2016-10-13T11:14:26Z
40,021,002
<p>You should avoid making Tk calls on non GUI threads. This works much more smoothly if you get rid of the threads entirely and use <code>after</code> to schedule the image capture.</p> <pre><code>from tkinter import * from PIL import Image, ImageGrab, ImageTk from io import BytesIO class buildFrame: def __init_...
0
2016-10-13T12:28:39Z
[ "python", "tkinter", "pillow" ]
While loop only responding to second condition
40,019,501
<p>My while loop is only ending when it matches the second condition, the first one is being ignored, I have no idea what I am doing wrong</p> <pre><code>while (response !=0) or (cont != 5): response = os.system("ping -c 2 " + hostname) cont=cont+1 print cont print response </code></pre>
0
2016-10-13T11:17:06Z
40,019,668
<p>Change your <code>or</code> to <code>and</code>. When it is checking the first condition and if that is false and the second condition is true, whole condition will be true. It means either first condition is true or second condition is true.</p> <pre><code>While ( false or true ) will be while ( true ) </code></pr...
0
2016-10-13T11:25:23Z
[ "python" ]
While loop only responding to second condition
40,019,501
<p>My while loop is only ending when it matches the second condition, the first one is being ignored, I have no idea what I am doing wrong</p> <pre><code>while (response !=0) or (cont != 5): response = os.system("ping -c 2 " + hostname) cont=cont+1 print cont print response </code></pre>
0
2016-10-13T11:17:06Z
40,019,809
<p>With <code>subprocess.call</code>:</p> <pre><code>import subprocess for count in range(5); response = subprocess.call(["ping", "-c", "2", hostname]) if not response: break </code></pre> <p>Prefer an iteration with <code>range</code> or <code>xrange</code>.</p>
0
2016-10-13T11:32:38Z
[ "python" ]
Play audio file when keyboard is pressed
40,019,533
<p>I have the following code in which I capture the user input and then I want to parse it and evaluate each character in string using ASCII code to play a certain .mp3 file: </p> <p>The problem is that this code works only for the first character. For example, if I have the input as <code>ab</code> I only hear the a...
0
2016-10-13T11:18:55Z
40,020,420
<p>If the mp3 file name always follow the path "letter(1),mp3" you can do something like:</p> <pre><code>import os wrd = input("Please write something: ") wrd = wrd.lower() for char in wrd: try: os.system("start " + char +'(1).mp3') except: ValueError </code></pre> <p>otherwise you can use a dic...
0
2016-10-13T12:00:32Z
[ "python", "os.system" ]
Python regex alpha-numeric string with numeric part between two values
40,019,664
<p>I am terrible at regex in general, but I would be interested to know if there is a method to check if the numeric part of an alpha-numeric string is between two values, or less/greater than a certain value?</p> <p>For example if I have a string to search in a file which has multiple numeric variations like below:</...
0
2016-10-13T11:25:10Z
40,019,874
<p>You can use re.findall() to search along with regex.</p> <p><strong>Explanation of regex as below:</strong></p> <pre><code>key_string\s+\((\d+)\s+bytes\) </code></pre> <p><img src="https://www.debuggex.com/i/H8MpT5EfCmy2_MaX.png" alt="Regular expression visualization"></p> <p><a href="https://www.debuggex.com/r/...
1
2016-10-13T11:35:55Z
[ "python", "regex" ]
Methods for finding the Eigenvalues of a matrix using python?
40,019,734
<p>I am currently attempting to find the eigenvalues of a matrix H. I have tried using both numpy.linalg.eig and scipy.linalg.eig, although both apparently use the same underlying method.</p> <p>The problem is that my matrix H is purely real, and the eigenvalues have to be real and also positive.</p> <p>But the scip...
1
2016-10-13T11:28:08Z
40,020,062
<p>Standard method would be to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eig.html" rel="nofollow">numpy.linalg.eig</a>.</p> <pre><code>from numpy import linalg as LA w, v = LA.eig(np.diag((1, 2, 3))) # w: # array([ 1., 2., 3.]) # v: # array([[ 1., 0., 0.], # [ 0., 1., 0...
2
2016-10-13T11:45:20Z
[ "python", "numpy", "scipy", "eigenvalue" ]
Methods for finding the Eigenvalues of a matrix using python?
40,019,734
<p>I am currently attempting to find the eigenvalues of a matrix H. I have tried using both numpy.linalg.eig and scipy.linalg.eig, although both apparently use the same underlying method.</p> <p>The problem is that my matrix H is purely real, and the eigenvalues have to be real and also positive.</p> <p>But the scip...
1
2016-10-13T11:28:08Z
40,020,171
<p>Have you tried with <a href="http://eigen.tuxfamily.org" rel="nofollow">libeigen</a>? There's a nice Python wrapper for it, called <a href="https://pypi.python.org/pypi/minieigen" rel="nofollow">minieigen</a>.</p> <pre><code>#!/usr/bin/env python3 import minieigen as eigen M = eigen.Matrix3(1, 0, 0, 0, 2, 0, 0, 0...
1
2016-10-13T11:49:35Z
[ "python", "numpy", "scipy", "eigenvalue" ]
Methods for finding the Eigenvalues of a matrix using python?
40,019,734
<p>I am currently attempting to find the eigenvalues of a matrix H. I have tried using both numpy.linalg.eig and scipy.linalg.eig, although both apparently use the same underlying method.</p> <p>The problem is that my matrix H is purely real, and the eigenvalues have to be real and also positive.</p> <p>But the scip...
1
2016-10-13T11:28:08Z
40,060,880
<p>Your matrix does not have any Hamiltonian structure as </p> <pre><code>J.dot(A).dot(J.T) - A.T </code></pre> <p>is not zero where <code>J</code> is given by</p> <pre><code># J = [0 I] # [-I 0] J = np.rot90(sp.linalg.block_diag(np.rot90(-eye(9)),np.rot90(eye(9)))) </code></pre> <p>hence there is no condition...
1
2016-10-15T15:28:41Z
[ "python", "numpy", "scipy", "eigenvalue" ]
How to use transactions with Django REST framework?
40,019,769
<p>I wish to use Django REST framework to create a number of model objects "together" -- i.e. in a single transaction. </p> <p>The objective is that each of the objects will only be visible at the (successful) end of the transaction.</p> <p>How can I do that?</p>
0
2016-10-13T11:30:41Z
40,019,862
<p>Use <code>atomic</code> from <code>django.db.transaction</code> as a decorator around a function performing the database operations you are after:</p> <p>If <code>obj_list</code> contains a list of populated (but not saved) model objects, this will execute all operations as part of one transaction.</p> <p><code> @...
0
2016-10-13T11:35:15Z
[ "python", "django", "rest", "django-models", "django-rest-framework" ]
How to use transactions with Django REST framework?
40,019,769
<p>I wish to use Django REST framework to create a number of model objects "together" -- i.e. in a single transaction. </p> <p>The objective is that each of the objects will only be visible at the (successful) end of the transaction.</p> <p>How can I do that?</p>
0
2016-10-13T11:30:41Z
40,019,924
<p>You can achieve this by using <code>django db transactions</code>. Refer to the code below</p> <pre><code>from django.db import transaction with transaction.atomic(): model_instance = form.save(commit=False) model_instance.creator = self.request.user model_instance.img_field.field.upload_to = 'director...
0
2016-10-13T11:38:23Z
[ "python", "django", "rest", "django-models", "django-rest-framework" ]
Get Pixel count using RGB values in Python
40,019,830
<p>I have to find count of pixels of RGB which is using by RGB values. So i need logic for that one.</p> <p>Example.</p> <p>i have image called image.jpg. That image contains width = 100 and height = 100 and Red value is 128. Green is 0 and blue is 128. so that i need to find how much RGB pixels have that image. can ...
0
2016-10-13T11:33:50Z
40,020,490
<p>As already mentioned in <a href="http://stackoverflow.com/questions/138250/how-can-i-read-the-rgb-value-of-a-given-pixel-in-python">this</a> question, by using <code>Pillow</code> you can do the following:</p> <pre><code>from PIL import Image im = Image.open('image.jpg', 'r') </code></pre> <p>If successful, this f...
0
2016-10-13T12:03:42Z
[ "python" ]
sympy - cos of a list of variables
40,019,839
<p>I try to implement a cos function of a list with variables with sympy. Here an easy example: </p> <pre><code> from sympy import * x = Symbol('x') cos([x+1,x+2,x+3]) </code></pre> <p>But then the error </p> <pre><code>AttributeError: 'list' object has no attribute 'is_Number' </code></pre> <p>occurs a...
-1
2016-10-13T11:34:33Z
40,019,910
<p>Use the <a href="https://docs.python.org/3/library/functions.html#map" rel="nofollow">Python builtin <code>map</code> function</a> to apply <code>sympy.cos</code> to each element in the list:</p> <pre><code>import sympy as sy x = sy.Symbol('x') print(list(map(sy.cos, [x+1,x+2,x+3]))) </code></pre> <p>yields</p> <...
2
2016-10-13T11:37:44Z
[ "python", "sympy" ]
Django - distinct rows/objects distinguished by date/day from datetime field
40,019,886
<p>I'v searched quite a while now and know about several answers on sof but none of the solutions does work at my end even if my problem is pretty simple:</p> <p>What I need (using postgres + django 1.10): I have many rows with many duplicate dates (=days) within a datetime field. I want a queryset containing one row/...
0
2016-10-13T11:36:32Z
40,020,269
<p>you can use a Queryset to get the results from your table by a distinct on the created value because you are using postgresql.</p> <p>Maybe a query like this should do the work :</p> <pre><code>MyModel.objects.all().distinct('created__date') </code></pre> <p>I refer you too the queryset documentation of django : ...
0
2016-10-13T11:53:55Z
[ "python", "django", "postgresql", "datetime" ]
How to map a column with dask
40,019,905
<p>I want to apply a mapping on a DataFrame column. With Pandas this is straight forward:</p> <pre><code>df["infos"] = df2["numbers"].map(lambda nr: custom_map(nr, hashmap)) </code></pre> <p>This writes the <code>infos</code> column, based on the <code>custom_map</code> function, and uses the rows in numbers for the ...
0
2016-10-13T11:37:32Z
40,020,855
<p>You can use the <a href="http://dask.pydata.org/en/latest/dataframe-api.html#dask.dataframe.Series.map" rel="nofollow">.map</a> method, exactly as in Pandas</p> <pre><code>In [1]: import dask.dataframe as dd In [2]: import pandas as pd In [3]: df = pd.DataFrame({'x': [1, 2, 3]}) In [4]: ddf = dd.from_pandas(df, ...
2
2016-10-13T12:21:18Z
[ "python", "pandas", "dask" ]
Collecting Revit Warnings
40,019,955
<p>Where are Warnings in the Revit Database? </p> <p>I'd like to use python to create my own error report (similar to the HTML export), but not sure where to find this information.</p> <p>I cant find anything in the Revit API (Revit 2015) referring to warnings. How would i collect these?</p> <p>I suspected that war...
0
2016-10-13T11:40:12Z
40,049,892
<p>Sadly, not possible. Errors "happen" during opening, audits and other events. You can catch them sometimes, but not very cleanly. Jeremy Tammik has at least one blog post with a partial unsupported workaround.</p> <p>Vote for my enhancement request on this topic: <a href="https://forums.autodesk.com/t5/revit-ideas/...
0
2016-10-14T18:31:32Z
[ "python", "warnings", "revit-api" ]