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
format date based on format in JavaScript
38,545,759
<p>I have a date variable like:</p> <pre><code>var date_value = new Date( parseInt(date.year()), parseInt(date.month()) - 1, parseInt(date.day())); // date_value = Date 2016-07-24T21:00:00.000Z </code></pre> <p>I want to format that date into many formats. Is there is any built-in function in JavaScript to for...
0
2016-07-23T19:37:11Z
38,545,808
<p>There is not built-in functionality to format dates. You need to use an external library like <a href="http://momentjs.com/docs/#/displaying/format/" rel="nofollow">moment.js</a>.</p>
-1
2016-07-23T19:44:31Z
[ "javascript", "jquery", "python", "datetime" ]
format date based on format in JavaScript
38,545,759
<p>I have a date variable like:</p> <pre><code>var date_value = new Date( parseInt(date.year()), parseInt(date.month()) - 1, parseInt(date.day())); // date_value = Date 2016-07-24T21:00:00.000Z </code></pre> <p>I want to format that date into many formats. Is there is any built-in function in JavaScript to for...
0
2016-07-23T19:37:11Z
38,545,854
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>date_value = moment().year(year).month(month).date(day); // or date_value = moment(date); date_value.format("M/D/Y HH:mm:ss")...
-1
2016-07-23T19:50:54Z
[ "javascript", "jquery", "python", "datetime" ]
BeautifulSoup parser not properly splitting by tags
38,545,778
<p>I'm scraping a site and then attempting to split into paragraphs. I can very clearly see by looking at the scraped text that some paragraph delimiters are not being split properly. See below for code to recreate the problem! </p> <pre><code>from bs4 import BeautifulSoup import requests link = "http://www.presidenc...
1
2016-07-23T19:40:08Z
38,548,017
<p>Have you tried, <code>lxml</code> parser? I had similar issues and <code>lxml</code> solved my problems.</p> <pre><code>import lxml ... soup = BeautifulSoup(response.text, "lxml") </code></pre> <p>Also instead of <code>response.content</code> try <code>response.text</code> to get unicode object. </p>
0
2016-07-24T01:50:28Z
[ "python", "python-2.7", "parsing", "web-scraping", "beautifulsoup" ]
BeautifulSoup parser not properly splitting by tags
38,545,778
<p>I'm scraping a site and then attempting to split into paragraphs. I can very clearly see by looking at the scraped text that some paragraph delimiters are not being split properly. See below for code to recreate the problem! </p> <pre><code>from bs4 import BeautifulSoup import requests link = "http://www.presidenc...
1
2016-07-23T19:40:08Z
38,548,049
<p>This is by design. It happens because the page contains nested paragraphs, e.g.:</p> <pre><code>&lt;p&gt;Neurosurgeon Ben Carson. [&lt;i&gt;applause&lt;/i&gt;] &lt;p&gt;New Jersey </code></pre> <p>I would use this little hack to resolve the problem:</p> <pre><code>html = response.content.replace('&lt;p&gt;', '&l...
0
2016-07-24T01:57:05Z
[ "python", "python-2.7", "parsing", "web-scraping", "beautifulsoup" ]
pandas describe by - additional parameters
38,545,828
<p>I see that the pandas library has a <code>Describe by</code> function which returns some useful statistics. However, is there a way to add additional rows to the output such as standard deviation (.std) and median absolute deviation (.mad) or the count of unique values?</p> <p>I get <code>df.describe()</code> but ...
2
2016-07-23T19:47:25Z
38,546,205
<p>Try this: </p> <pre><code> df.describe() num1 num2 count 3.0 3.0 mean 2.0 5.0 std 1.0 1.0 min 1.0 4.0 25% 1.5 4.5 50% 2.0 5.0 75% 2.5 5.5 max 3.0 6.0 </code></pre> <p>Build a second DataFrame. </p> <pre><code> pd.DataFrame(df.mad() , columns = ["Mad"] ).T ...
2
2016-07-23T20:36:56Z
[ "python", "pandas" ]
pandas describe by - additional parameters
38,545,828
<p>I see that the pandas library has a <code>Describe by</code> function which returns some useful statistics. However, is there a way to add additional rows to the output such as standard deviation (.std) and median absolute deviation (.mad) or the count of unique values?</p> <p>I get <code>df.describe()</code> but ...
2
2016-07-23T19:47:25Z
38,547,818
<p>the default <code>describe</code> looks like this:</p> <pre><code>np.random.seed([3,1415]) df = pd.DataFrame(np.random.rand(100, 5), columns=list('ABCDE')) df.describe() </code></pre> <p><a href="http://i.stack.imgur.com/Dql3N.png" rel="nofollow"><img src="http://i.stack.imgur.com/Dql3N.png" alt="enter image desc...
3
2016-07-24T01:07:29Z
[ "python", "pandas" ]
python multithreading queues not running or exiting cleanly
38,545,832
<p>I'm learning python multithreading and queues. The following creates a bunch of threads that pass data through a queue to another thread for printing:</p> <pre><code>import time import threading import Queue queue = Queue.Queue() def add(data): return ["%sX" % x for x in data] class PrintThread(threading.Thr...
0
2016-07-23T19:48:10Z
38,545,905
<p>Your <code>PrintThread</code> does not loop but instead only prints out a single queue item and then stops running. </p> <p>Therefore, the queue will never be empty and the <code>queue.join()</code> statement will prevent the main program from terminating</p> <p>Change the <code>run()</code> method of your <code>P...
0
2016-07-23T19:56:09Z
[ "python", "multithreading", "python-2.7", "python-multithreading" ]
Function that acts on all elements of numpy array?
38,545,954
<p>I wonder if you can define a function to act on all elements of a 1-D numpy array simultaneously, so that you don't have to loop over the array. Similar to the way you can, for example, square all elements of an array without looping. An example of what I'm after is to replace this code:</p> <pre><code>A = np.array...
0
2016-07-23T20:03:52Z
38,546,050
<p>Try:</p> <pre><code>np.apply_along_axis(F, 1, A) </code></pre>
3
2016-07-23T20:15:03Z
[ "python", "arrays", "performance", "function", "numpy" ]
Replace single with double quote inside pair of single quotes
38,545,982
<p>Here is what i am looking for:</p> <pre><code>curl -X POST -H "Content-type: application/json" -d '{"group":"stash-adt_ooms-dev","users":['stack', 'overflow']}' "url" </code></pre> <p>Result:</p> <pre><code>curl -X POST -H "Content-type: application/json" -d '{"group":"admin","users":["stack", "overflow"]}' </cod...
-2
2016-07-23T20:06:50Z
38,546,285
<p>You need to get the position of the open bracket and close brackets and then replace the <code>'</code> with <code>"</code>. You can do something like this:</p> <pre><code>_str = """curl -X POST -H "Content-type: application/json" -d '{"group":"stash-adt_ooms-dev","users":['stack', 'overflow']}' "url" """ start = ...
0
2016-07-23T20:47:41Z
[ "python", "regex" ]
Replace single with double quote inside pair of single quotes
38,545,982
<p>Here is what i am looking for:</p> <pre><code>curl -X POST -H "Content-type: application/json" -d '{"group":"stash-adt_ooms-dev","users":['stack', 'overflow']}' "url" </code></pre> <p>Result:</p> <pre><code>curl -X POST -H "Content-type: application/json" -d '{"group":"admin","users":["stack", "overflow"]}' </cod...
-2
2016-07-23T20:06:50Z
38,546,563
<p>A regex approach using a lambda inside <code>re.sub</code> instead of a replacement string pattern:</p> <pre><code>import re s = """curl -X POST -H "Content-type: application/json" -d '{"group":"stash-adt_ooms-dev","users":['stack', 'overflow']}' "url" """ res = re.sub(r"\[.*?]", lambda x: x.group().replace("'", '"...
0
2016-07-23T21:26:09Z
[ "python", "regex" ]
Replace single with double quote inside pair of single quotes
38,545,982
<p>Here is what i am looking for:</p> <pre><code>curl -X POST -H "Content-type: application/json" -d '{"group":"stash-adt_ooms-dev","users":['stack', 'overflow']}' "url" </code></pre> <p>Result:</p> <pre><code>curl -X POST -H "Content-type: application/json" -d '{"group":"admin","users":["stack", "overflow"]}' </cod...
-2
2016-07-23T20:06:50Z
38,546,599
<pre><code>a = "curl -X POST -H \"Content-type: application/json\" -d '{\"group\":\"stash-adt_ooms-dev\",\"users\":['stack', 'overflow']}' \"url\"" b = re.sub(r'\[\'(\w+)\', \'(\w+)\'\]',r'["\1", "\2"]' , a) </code></pre> <p>printing b will result in below:</p> <pre><code>'curl -X POST -H "Content-type: application/...
0
2016-07-23T21:31:09Z
[ "python", "regex" ]
I want to transfer data from text file to array
38,546,005
<p>i'm new here and also new with programming with python as an exercise i have to read data (lat &amp; lon) from a txt file with many rows and convert them into shapefile with QGIS </p> <p>After reading i find a way to extract data into array, as step1, but i have soem issues..</p> <p>I use the following code</p> ...
0
2016-07-23T20:09:44Z
38,546,025
<p><code>line</code> already is the line. Get the triplets by</p> <pre><code>triplets = line.split() </code></pre>
0
2016-07-23T20:11:56Z
[ "python" ]
I want to transfer data from text file to array
38,546,005
<p>i'm new here and also new with programming with python as an exercise i have to read data (lat &amp; lon) from a txt file with many rows and convert them into shapefile with QGIS </p> <p>After reading i find a way to extract data into array, as step1, but i have soem issues..</p> <p>I use the following code</p> ...
0
2016-07-23T20:09:44Z
38,546,046
<p><code>for line in f:</code> already iterates through the lines in the file, reading as it goes along. As such, it should be:</p> <pre><code>for line in f: triplets = line.split() </code></pre> <p>Alternatively, you could do as below, though I recommend the method above.</p> <pre><code>with open('D:/test_data/...
3
2016-07-23T20:14:04Z
[ "python" ]
Creating list of objects using data from numpy arrays
38,546,261
<p>I have several numpy arrays containing data, and a class I defined, with attributes corresponding to each of my numpy arrays. I would like to quickly make another array containing a list of objects, with each objects attributes defined by the corresponding element of the numpy array. Basically, the equivalent of the...
0
2016-07-23T20:43:31Z
38,546,328
<p>That iteration is 'pythonic'.</p> <p><code>numpy</code> does have a function that works in this case, and may be a bit faster. It's not magical:</p> <pre><code>In [142]: a=np.linspace(0,100,10) In [143]: b=np.linspace(0,50,10) # change to match a size In [144]: f=np.frompyfunc(test,2,1) In [145]: c=f(a,b) In [1...
1
2016-07-23T20:54:10Z
[ "python", "arrays", "object", "numpy" ]
Dividing data-frame columns and getting ZeroDivisionError: float division by zero
38,546,275
<p>I have a data frame <code>dayData</code> which includes the columns the following columns <code>'ratio'</code> and <code>'first_power'</code> with the following types:</p> <pre><code>Name: ratio, dtype: float64 first power Name: first_power, dtype: object average power ratio average_power 0 5 ...
1
2016-07-23T20:46:18Z
38,546,577
<p>You can initially set all values to zero, then create a mask locating all rows with a valid denominator, i.e. where <code>power</code> is greater than zero (<code>gt(0)</code>). Finally, use the mask together with <code>loc</code> to calculate <code>second_step_power</code>.</p> <pre><code>df['second_step_power'] ...
3
2016-07-23T21:27:39Z
[ "python", "pandas" ]
How do I run zeroRpc server in thread in python?
38,546,293
<p>I have problem with launching zeroRPC server in python. I did it according to <a href="http://www.zerorpc.io/" rel="nofollow">official example</a>, but when I call run() method it works in endless loop, so my program can't continue after launching this server. I tried to run it in new thread but I got following exce...
0
2016-07-23T20:48:35Z
38,575,155
<p>In short, you cannot use os threads with zerorpc.</p> <p>Longer answer: zerorpc-python uses gevent for IO. This means your project MUST use gevent and be compatible with it. Native OS threads and gevent coroutines (also called greenlet, green threads etc) are not really friends.</p> <p>There is a native threadpool...
1
2016-07-25T18:38:01Z
[ "python", "multithreading", "server", "zeromq", "zerorpc" ]
Can't import wxPython on OSX 10.11.5
38,546,304
<p>I cannot seem to get <code>wxpython</code> to install on Mac. I have tried a number of approaches, but the closest I've gotten is using Homebrew. When I do <code>brew list</code>, both <code>wxmac</code> and <code>wxpython</code> are listed, and when I type <code>brew link &lt;n&gt;</code> for either of those pack...
0
2016-07-23T20:50:16Z
38,546,346
<p>Like some python libraries, the name of the library is different from the name that you should use to import it. For wxpython, you should use <code>import wx</code> instead of <code>import wxpython</code></p> <pre><code>import wx print wx.VERSION_STRING </code></pre>
1
2016-07-23T20:56:28Z
[ "python", "python-2.7", "wxpython" ]
tflearn / tensorflow | Multi-stream/Multiscale/Ensemble model definition
38,546,495
<p>I am trying to define a multi-stream model with tflearn so that there are two copies of the same architecture (or you can think of it as an ensemble model) that I feed with different crops of the same image but not sure how I would go and implement that with tflearn.</p> <p>I basically have this data:</p> <pre><co...
0
2016-07-23T21:15:41Z
38,565,325
<p>You do not need to split X1 and X2, they will automatically be assigned to your input layers netIn1 and netIn2 (in the same order you define them).</p>
0
2016-07-25T10:28:01Z
[ "python", "machine-learning", "computer-vision", "tensorflow", "deep-learning" ]
Manage optional dynamic segment of URL in Flask with class based view
38,546,539
<p>I want to reproduce the behavior of having multiple URL linked to one endpoint while using Flask class based views. Using classic Flask views I would do :</p> <pre><code>@app.route("/users") @app.route("/users/&lt;int:id&gt;", defaults={"id": None}) def users(id): # Function </code></pre> <p>But how to reprodu...
1
2016-07-23T21:22:17Z
38,547,671
<p>Normally, after you defined your class based view, just <code>add_url_rule</code> rules of each route, taking the example mentioned in <a href="http://flask.pocoo.org/docs/0.11/views/#method-views-for-apis" rel="nofollow">Flask's Docs</a>:</p> <pre><code>class UserAPI(MethodView): def get(self, user_id): ...
1
2016-07-24T00:41:51Z
[ "python", "flask" ]
How to extract value from a class in beautiful Soup
38,546,575
<p>I have a web document which looks like this :- </p> <pre><code> &lt;table class="table "&gt;&lt;col width="75px"&gt;&lt;/col&gt;&lt;col width="1px"&gt;&lt;/col&gt;&lt;tbody&gt;&lt;tr class="tablerow style2" prodid="143012"&gt;&lt;td class="pricecell"&gt;&lt;span class="WebRupee"&gt;Rs.&lt;/span&gt; 29 &lt;br/&gt...
0
2016-07-23T21:27:27Z
38,549,727
<p>You need to dig deeper to get the specific data you're after. For example, to get the prices, search for the table cells with class "pricecell". Then you can get the contained text and just parse that. Some sample code (not tested):</p> <pre><code>price_cells = soup.findAll('td', {'class': 'pricecell'}) for price_c...
1
2016-07-24T07:29:35Z
[ "python", "beautifulsoup" ]
Tkinter GUI size on high resolution screens
38,546,580
<p>So it appears that matplotlib gui plots (a la <code>plt.show()</code>) don't adapt to monitor resolution and appear tiny on high resolution screens. Is there a matplotlib/tkinter fix or do I have fiddle around somewhere in Windows settings?</p> <p>Thanks<a href="http://i.stack.imgur.com/HuLZy.jpg" rel="nofollow"><i...
2
2016-07-23T21:28:08Z
38,546,859
<p>Before <code>plt.show()</code> call these functions:</p> <pre><code>mng = plt.get_current_fig_manager() mng.frame.Maximize(True) </code></pre> <p>Maybe it solve your issue.</p>
1
2016-07-23T22:11:12Z
[ "python", "user-interface", "matplotlib", "tkinter" ]
Grab the frame from gst pipeline to opencv with python
38,546,602
<p>I'm using <a href="http://opencv.org/" rel="nofollow">OpenCV</a> and GStreamer <strong>0.10</strong>. </p> <p>I use this pipeline to receive the MPEG ts packets over UDP with a custom socket <code>sockfd</code> provided by python and display it with <code>xvimagesink</code>, and it works perfectly. Following commen...
1
2016-07-23T21:31:18Z
38,618,529
<p>Thanks, I have tried to use rtph264pay to broadcast the live video steam to udpsink. Following commend line is for the gst pipeline: </p> <pre><code>PIPELINE_DEF = "udpsrc name=src !" \ "mpegtsdemux !" \ "queue !" \ "h264parse !" \ "rtph264pay !" \ "udpsink host=127.0.0.1 p...
0
2016-07-27T16:27:39Z
[ "python", "opencv", "gstreamer-0.10" ]
Using numpy arrays to avoid for loops - combinatorics
38,546,628
<p>There's got to be a more pythonic way of doing:</p> <pre><code>r = np.arange(100) results = [] for i in r: for j in r: for k in r: for l in r: #Here f is some predefined function if f(i,j,k,l) &lt; 5.0: results.append(f(i,j,k,l)) </code>...
2
2016-07-23T21:35:02Z
38,546,682
<p>Use <code>itertools</code> cartesian product:</p> <pre><code>import itertools r = np.arange(100) results = [] for (i,j,k,l) in itertools.product(r,repeat=4): if f(i,j,k,l) &lt; 5.0: results.append(f(i,j,k,l)) </code></pre> <p>Or even more compact way, using list comprehension:</p> <pre><code>[ f(i,j,...
5
2016-07-23T21:44:36Z
[ "python", "arrays", "numpy" ]
Using numpy arrays to avoid for loops - combinatorics
38,546,628
<p>There's got to be a more pythonic way of doing:</p> <pre><code>r = np.arange(100) results = [] for i in r: for j in r: for k in r: for l in r: #Here f is some predefined function if f(i,j,k,l) &lt; 5.0: results.append(f(i,j,k,l)) </code>...
2
2016-07-23T21:35:02Z
38,638,668
<p>The for loops and the if statement can be avoided by using NumPy's <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfunction.html#numpy.fromfunction" rel="nofollow"><code>fromfunction</code></a> and <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays"...
0
2016-07-28T13:59:12Z
[ "python", "arrays", "numpy" ]
Finding Palidrome from a permutation in Python
38,546,663
<p>I have a string, I need to find out <code>palindromic sub-string of length 4</code>( <code>all</code> <code>4 indexes</code> sub-strings), in which the indexes should be in <code>ascending order (index1&lt;index2&lt;index3&lt;index4)</code>. My code is working fine for small string like <code>mystr</code>. But when ...
1
2016-07-23T21:40:45Z
38,547,247
<p>If you want to stick with the basic structure of your current algorithm, a few ways to speed it up would be to use <code>combinations</code> instead of the <code>permutations</code>, which will return an iterable in sorted order. This means you don't need to check that the indexes are in ascending order. Secondly y...
0
2016-07-23T23:17:40Z
[ "python", "algorithm", "permutation", "palindrome" ]
How to scrape aspx pages with python
38,546,665
<p>I am trying to scrape a site, <a href="https://www.searchiqs.com/nybro/" rel="nofollow">https://www.searchiqs.com/nybro/</a> (you have to click the "Log In as Guest" to get to the search form. If I search for a Party 1 term like say "Andrew" the results have pagination and also, the request type is POST so the URL ...
0
2016-07-23T21:41:22Z
38,547,098
<p>I disabled Javascript and visited <a href="https://www.searchiqs.com/nybro/" rel="nofollow">https://www.searchiqs.com/nybro/</a> and the form looks like this:</p> <p><a href="http://i.stack.imgur.com/U8GZf.png" rel="nofollow"><img src="http://i.stack.imgur.com/U8GZf.png" alt="enter image description here"></a> </p>...
0
2016-07-23T22:53:30Z
[ "python", "web-scraping", "beautifulsoup", "python-requests", "mechanize" ]
How do I populate a <p> tag with text in Selenium Webdriver using PhantomJS?
38,546,693
<p>I have an input form that I need to populate with text. It's a div and it has a child node that is a <p> tag that needs to be populated with text in order to submit the form. </p> <p>I've tried send_keys on the div itself to no avail, and in my browser I selected the <p> tag and changed it's TextContent property wh...
2
2016-07-23T21:46:21Z
38,546,826
<p><code>send_keys()</code> works only on that element which needs to be set value on their <code>value</code> attribute means <code>input</code> and <code>textarea</code>, but here you are trying to set value on <code>p</code> element which need to be set on their <code>textContent</code>, So here you should try using...
0
2016-07-23T22:06:32Z
[ "python", "selenium", "webdriver", "phantomjs", "webautomation" ]
Python csv search script
38,546,724
<p>I wish to write a Python script which reads from a csv. The csv comprises of 2 columns. I want the script to read through the first column row by row and find the corresponding value in the second row. If it finds the value in the second row I want it to input a value into a third column.</p> <p><a href="http://i.s...
0
2016-07-23T21:51:56Z
38,547,019
<p>this script read <code>test.csv</code> file and parse it an write to <code>OUTPUT.txt</code></p> <pre><code>f = open("test.csv","r") d={} s={} for line in f: l=line.split(",") if not l[0] in d: d[l[0]]=l[1].rstrip() s[l[0]]='' else: s[l[0]]+...
0
2016-07-23T22:40:11Z
[ "python", "csv", "scripting" ]
Python Multiple Strings to Tuples
38,546,776
<p>Hi everyone I wonder if you can help with my problem.</p> <p>I am defining a function which takes a string and converts it into 5 items in a tuple. The function will be required to take a number of strings, in which some of the items will vary in length. How would I go about doing this as using the indexes of the s...
0
2016-07-23T21:58:46Z
38,546,849
<p>With Python 3, you can just <code>split()</code> and use <a href="https://www.python.org/dev/peps/pep-3132/" rel="nofollow">"catch-all" tuple unpacking</a> with <code>*</code>:</p> <pre><code>&gt;&gt;&gt; string = "Doctor E212 40000 Peter David Jones" &gt;&gt;&gt; job, dep, sal, *other, names = string.split() &gt;...
4
2016-07-23T22:09:48Z
[ "python" ]
How to generate the same image with the function of imshow() from matplotlib(python) and imshow() in matlab?
38,546,853
<p>For the same matrix, the image generated by the function imshow() from matplotlib and matlab is different. how to change some parameters of imshow() in matplotlib can get same result in matlab </p> <pre><code>%matlab img = 255*rand(101); img(:,1:50)=3; img(:,52:101)=1; img(:,51)=2; trans_img=imtranslate(img,[3*cos(...
-1
2016-07-23T22:10:16Z
38,547,151
<p>Unfortunately I don't have an up-to-date enough version of Matlab that has the <code>imtranslate</code> function, but thankfully the <code>image</code> package in Octave does, which I'm sure is equivalent. Equally, I will be using the <code>oct2py</code> module instead of <code>mlab</code> as a result, for python to...
0
2016-07-23T23:02:12Z
[ "python", "matlab", "matplotlib" ]
Pandas MultiIndex get all rows with label value
38,546,881
<p>Assume you have a Panda DataFrame with a MultiIndex. You want to get all the rows that have a label with a particular value. How do you do this?</p> <p>My first thought was a boolean mask...</p> <p><code>df[df.index.labels == 1].head()</code></p> <p>but this does not work.</p> <p>Thanks!</p>
1
2016-07-23T22:15:38Z
38,546,992
<p>You need to specify which index you use. In my example I took the second index (My dataframe is s because it was so in Multiindex page of Pandas):</p> <pre><code>s[s.index.labels[1]==1] </code></pre> <p>You can actually see how index is constructed if you type:</p> <pre><code>s.index </code></pre> <p>The resulti...
2
2016-07-23T22:36:21Z
[ "python", "pandas", "multi-index" ]
Pandas MultiIndex get all rows with label value
38,546,881
<p>Assume you have a Panda DataFrame with a MultiIndex. You want to get all the rows that have a label with a particular value. How do you do this?</p> <p>My first thought was a boolean mask...</p> <p><code>df[df.index.labels == 1].head()</code></p> <p>but this does not work.</p> <p>Thanks!</p>
1
2016-07-23T22:15:38Z
38,549,393
<p>I would use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.xs.html" rel="nofollow"><code>xs</code> (cross-section)</a>:</p> <pre><code>In [11]: df = pd.DataFrame([[1, 2, 3], [3, 4, 5]], columns=list("ABC")).set_index(["A", "B"]) In [12]: df Out[12]: C A B 1 2 3 3 4 5 </code>...
1
2016-07-24T06:31:01Z
[ "python", "pandas", "multi-index" ]
Pandas MultiIndex get all rows with label value
38,546,881
<p>Assume you have a Panda DataFrame with a MultiIndex. You want to get all the rows that have a label with a particular value. How do you do this?</p> <p>My first thought was a boolean mask...</p> <p><code>df[df.index.labels == 1].head()</code></p> <p>but this does not work.</p> <p>Thanks!</p>
1
2016-07-23T22:15:38Z
38,550,371
<p>alternative solution:</p> <pre><code>In [62]: df = pd.DataFrame({'idx1': ['A','B','C'], 'idx2':[1,2,3], 'val': [30,10,20]}).set_index(['idx1','idx2']) In [63]: df Out[63]: val idx1 idx2 A 1 30 B 2 10 C 3 20 In [64]: df[df.index.get_level_values('idx2') == 2] Out[64]: ...
0
2016-07-24T09:05:33Z
[ "python", "pandas", "multi-index" ]
Date and Legend are not Showing Correctly at MatplotLib
38,546,902
<p>My goal is to create a chart (with correct xy labels and legend) with a data from Worldbank API at GUI TKinter.</p> <p>I have been dealing with issues such as the x label shows number instead of year, and the legend does not appear.<a href="http://i.stack.imgur.com/y5nyE.jpg" rel="nofollow"><img src="http://i.stack...
0
2016-07-23T22:18:32Z
38,547,303
<p>For your x-axis labels, one solution is updating your dataframe index type to <code>datetime</code>. Right now the index type is <code>object</code>.</p> <p>As for the legends, you have to specify <code>labels</code> in the <code>legend</code> method. Check out the added and updated lines after the comments in the ...
1
2016-07-23T23:27:24Z
[ "python", "matplotlib", "tkinter" ]
semantic segmentation with tensorflow - ValueError in loss function (sparse-softmax)
38,546,903
<p>So, I'm working on a building a fully convolutional network (FCN), based off of <a href="https://github.com/MarvinTeichmann/tensorflow-fcn" rel="nofollow">Marvin Teichmann's tensorflow-fcn</a> </p> <p>My input image data, for the time being is a 750x750x3 RGB image. After running through the network, I use logits o...
2
2016-07-23T22:19:19Z
38,548,088
<p>Closing. Turns out the code in the loss function was missing a mean summation. For anyone else facing this problem, modify the loss function as below, and it should work fine.</p> <pre><code> cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits, labels, name='Cross_Entropy') cross_entropy_me...
1
2016-07-24T02:04:43Z
[ "python", "tensorflow", "image-segmentation" ]
Execution time of multithreaded python program
38,546,940
<p>Considering GIL, I expected this program to finish in 9 seconds, but to my surprise, it ends in 4 seconds. Looking for probable reasons or am I missing something?</p> <pre><code>import time import threading def get_data(start, end): res = [] for i in range(start, end): time.sleep(1) res.app...
0
2016-07-23T22:27:02Z
38,547,871
<p>Normally, if you don't use multithreading this program finish in 9 seconds because python runs lines one by one so when you put time.sleep(1), python just wait one second and on the other hand do not anything. But when you use multithreading the program runs thread functions separately. So for example if you call th...
1
2016-07-24T01:17:40Z
[ "python", "multithreading" ]
Remove element from list when using enumerate() in python
38,546,951
<p>Object is a decoded json object that contains a list called items. </p> <pre><code>obj = json.loads(response.body_as_unicode()) for index, item in enumerate(obj['items']): if not item['name']: obj['items'].pop(index) </code></pre> <p>I iterate over those items and want to remove an item when a certain ...
0
2016-07-23T22:29:32Z
38,547,020
<p>Don't remove items from a list while iterating over it; iteration will <a href="https://stackoverflow.com/questions/17299581/loop-forgets-to-remove-some-items">skip items</a> as the iteration index is not updated to account for elements removed.</p> <p>Instead, <em>rebuild</em> the list minus the items you want rem...
5
2016-07-23T22:40:13Z
[ "python", "loops" ]
Remove element from list when using enumerate() in python
38,546,951
<p>Object is a decoded json object that contains a list called items. </p> <pre><code>obj = json.loads(response.body_as_unicode()) for index, item in enumerate(obj['items']): if not item['name']: obj['items'].pop(index) </code></pre> <p>I iterate over those items and want to remove an item when a certain ...
0
2016-07-23T22:29:32Z
38,547,121
<p>Use a <code>while</code> loop and change the iterator as you need it:</p> <pre><code>obj = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # remove all items that are smaller than 5 index = 0 # while index in range(len(obj)): improved according to comment while index &lt; len(obj): if obj[index] &lt; 5: obj.pop(index)...
2
2016-07-23T22:57:26Z
[ "python", "loops" ]
Merge items in list with delimiter python
38,547,047
<p>I have the following list:</p> <pre><code>[50.0, 100.0, 150.0, 5.0, 200.0, 300.0, 10.0, 400.0] </code></pre> <p>and I would like to merge items in my list using the <code>:</code> delimiter, to create the following list: </p> <pre><code>[50.0, 100.0:150.0:5, 200.0:300.0:10.0, 400.0] </code></pre> <p>I would like...
1
2016-07-23T22:44:58Z
38,547,182
<p>You can't have numbers delimited by <code>:</code> without wrapping them with <code>""</code> (i.e as strings). You can however do what you intend using <code>slice</code>:</p> <pre><code>s = [50.0, 100.0, 150.0, 5.0, 200.0, 300.0, 10.0, 400.0] it = iter(s[1:-1]) s[1:-1] = map(slice, *(it,)*3) print(s) # [50.0, sl...
3
2016-07-23T23:05:45Z
[ "python", "list", "numpy" ]
Merge items in list with delimiter python
38,547,047
<p>I have the following list:</p> <pre><code>[50.0, 100.0, 150.0, 5.0, 200.0, 300.0, 10.0, 400.0] </code></pre> <p>and I would like to merge items in my list using the <code>:</code> delimiter, to create the following list: </p> <pre><code>[50.0, 100.0:150.0:5, 200.0:300.0:10.0, 400.0] </code></pre> <p>I would like...
1
2016-07-23T22:44:58Z
38,547,191
<p>I think you are talking about doing:</p> <pre><code>In [152]: [50.0, 100.0, 150.0, 5.0, 200.0, 300.0, 10.0, 400.0] Out[152]: [50.0, 100.0, 150.0, 5.0, 200.0, 300.0, 10.0, 400.0] In [153]: np.r_[50.0, 100.0:150.0:5.0, 200.0:300.0:10.0, 400.0] Out[153]: array([ 50., 100., 105., 110., 115., 120., 125., 130.,...
2
2016-07-23T23:07:24Z
[ "python", "list", "numpy" ]
Python print redirect as stdin command line argument
38,547,049
<p>I have a binary foo which requires two command line arguments: username and password. </p> <p>I have written script.py to generate the username and password. Currently, I am using print to print them to stdout and then manually copy and paste them in the shell when I call foo in shell, i.e.,</p> <pre><code>$python...
1
2016-07-23T22:45:12Z
38,547,136
<p>So <code>subprocess</code> worked but you didn't used because you than didn't got the output from 'foo' (the binary)?</p> <p>You can use the <a href="https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate" rel="nofollow">communicate()</a> function to get output from the binary back.</p>
1
2016-07-23T23:00:17Z
[ "python", "shell" ]
Python print redirect as stdin command line argument
38,547,049
<p>I have a binary foo which requires two command line arguments: username and password. </p> <p>I have written script.py to generate the username and password. Currently, I am using print to print them to stdout and then manually copy and paste them in the shell when I call foo in shell, i.e.,</p> <pre><code>$python...
1
2016-07-23T22:45:12Z
38,548,646
<p>Run:</p> <pre><code>./foo $(python script.py) </code></pre> <p>To demonstrates that this works and provides <code>foo</code> with two arguments, let's use this script.py:</p> <pre><code>$ cat script.py #!/usr/bin/python print("name1 pass1") </code></pre> <p>And let's use this <code>foo</code> so that we can see ...
2
2016-07-24T04:06:59Z
[ "python", "shell" ]
django-wysiwyg-redactor's RedactorField
38,547,070
<p>I'm using django-wysiwyg-redactor and I have two question</p> <ol> <li>How can I send RedactorField input to the template as a field in the form?</li> <li>I'm using django-modeltranslation as well, but in admin site other language fileds for redactor input is ordinary TextField.<a href="http://i.stack.imgur.com...
0
2016-07-23T22:49:39Z
39,675,040
<p>Use this FAQ <a href="https://imperavi.com/redactor/docs/how-to-install/" rel="nofollow">https://imperavi.com/redactor/docs/how-to-install/</a>. </p> <p>To install Redactor, place the following code between the <code>&lt;head&gt;&lt;/head&gt;</code> tags: </p> <pre><code>&lt;link rel="stylesheet" href="/js/redacto...
0
2016-09-24T09:57:18Z
[ "python", "django" ]
Error In Spyder After Anaconda Install
38,547,165
<p>I just installed Anaconda. I already had Spyder 3.0.0 installed on my Windows 8.1 (64 bit). I also already had Python 3.4 installed. But, after installing Anaconda, I went into Preferences and pointed the Python executable to the Anaconda3 folder to utilize the 3.5 version. But when I started up Spyder again, go...
0
2016-07-23T23:04:18Z
38,550,873
<p>Suggestion:</p> <ul> <li>rename your directory "C:\WinPython-64bit-3.4.4.2" in "C:\WinPython-64bit-3.4.4.2bis"</li> <li>relaunch your Anaconda Spyder</li> <li>if it doesn't help, rename it back to "C:\WinPython-64bit-3.4.4.2"</li> </ul>
0
2016-07-24T10:08:36Z
[ "python", "installation", "anaconda", "spyder" ]
How to install ImageHash on Ubuntu 14.0.4?
38,547,249
<p>I would like to install ImageHash and I did :</p> <pre><code>pip install pillow==2.6.1 imagehash==0.3 </code></pre> <p>but I get :</p> <pre><code>ImportError: No module named numpy.distutils.core ---------------------------------------- Cleaning up... Command /usr/bin/python -c "import setuptools, tokenize;__fil...
0
2016-07-23T23:17:51Z
38,547,265
<p>The requirements are Pillow, numpy and scipy. so we should follow:</p> <p>for numpy/scipy: </p> <pre><code>sudo apt-get install libblas-dev liblapack-dev libatlas-base-dev gfortran sudo pip install scipy </code></pre> <p>then: </p> <pre><code>sudo pip install Pillow sudo pip install imagehash </code></pre>
0
2016-07-23T23:20:49Z
[ "python", "hash", "install" ]
regular expression match issue in Python
38,547,280
<p>For input string, want to match text which starts with <code>{(P)</code> and ends with <code>(P)}</code>, and I just want to match the parts in the middle. Wondering if we can write one regular expression to resolve this issue?</p> <p>For example, in the following example, for the input string, I want to retrieve <...
3
2016-07-23T23:24:08Z
38,547,309
<p>You can try <code>{\(P\)(.*)\(P\)}</code>, and use parenthesis in the pattern to capture everything between <code>{(P)</code> and <code>(P)}</code>:</p> <pre><code>import re re.findall(r'{\(P\)(.*)\(P\)}', "python {(P)hello world(P)} java") # ['hello world'] </code></pre> <p><code>.*</code> also matches unicode c...
4
2016-07-23T23:29:02Z
[ "python", "regex", "python-2.7" ]
regular expression match issue in Python
38,547,280
<p>For input string, want to match text which starts with <code>{(P)</code> and ends with <code>(P)}</code>, and I just want to match the parts in the middle. Wondering if we can write one regular expression to resolve this issue?</p> <p>For example, in the following example, for the input string, I want to retrieve <...
3
2016-07-23T23:24:08Z
38,547,333
<p>You can also do this without regular expressions:</p> <pre><code>s = 'python {(P)hello world(P)} java' r = s.split('(P)')[1] print(r) # 'hello world' </code></pre>
2
2016-07-23T23:33:08Z
[ "python", "regex", "python-2.7" ]
regular expression match issue in Python
38,547,280
<p>For input string, want to match text which starts with <code>{(P)</code> and ends with <code>(P)}</code>, and I just want to match the parts in the middle. Wondering if we can write one regular expression to resolve this issue?</p> <p>For example, in the following example, for the input string, I want to retrieve <...
3
2016-07-23T23:24:08Z
38,547,355
<p>You can use positive look-arounds to ensure that it only matches if the text is preceded and followed by the start and end tags. For instance, you could use this pattern:</p> <pre><code>(?&lt;={\(P\)).*?(?=\(P\)}) </code></pre> <p>See the <a href="https://regex101.com/r/jA9uP2/1" rel="nofollow">demo</a>.</p> <ul...
3
2016-07-23T23:37:28Z
[ "python", "regex", "python-2.7" ]
Write recursive data in excel from python list
38,547,325
<p>I have a list of webpages called: <code>html</code></p> <p>in each and every <code>html(i)</code> element I extracted emails addresses. I put these emails addresses in the list: <code>email</code></p> <p>I want to generate an excel file like this:</p> <p><a href="http://i.stack.imgur.com/3ufWN.png" rel="nofollow...
0
2016-07-23T23:31:57Z
38,547,554
<p>I don't know about xlwt but considering you have a list of <code>emails</code> for each <code>html</code> would something like this work?</p> <pre><code> import xlwt wb = Workbook() for html_index, html in enumerate(html): sheet1.write(html_index, 0, html.address) for email_index, email in enumerate(em...
0
2016-07-24T00:17:31Z
[ "python", "excel", "list", "for-loop", "xlwt" ]
Write recursive data in excel from python list
38,547,325
<p>I have a list of webpages called: <code>html</code></p> <p>in each and every <code>html(i)</code> element I extracted emails addresses. I put these emails addresses in the list: <code>email</code></p> <p>I want to generate an excel file like this:</p> <p><a href="http://i.stack.imgur.com/3ufWN.png" rel="nofollow...
0
2016-07-23T23:31:57Z
38,547,578
<pre><code>import xlwt wb = Workbook() sheet1 = wb.add_sheet("Sheet 1") htmls = generate_htmls() #Imaginary function to pretend it's initialized. for i in xrange(len(htmls)): sheet1.write(i, 0, htmls[i]) emails = extract_emails(htmls[i]) #Imaginary function to pretend it's extracted for j in xrange(len(ema...
0
2016-07-24T00:22:33Z
[ "python", "excel", "list", "for-loop", "xlwt" ]
Is there a way to avoid polling when looking for serial port changes in Python?
38,547,381
<p>Currently I am using <a href="https://github.com/pyserial/pyserial" rel="nofollow"><em>pySerial</em></a> and its <code>list_ports.comports()</code> function to poll for changes of the currently available serial ports of devices with a certain vid/pid. I'd like to know if there is a way to avoid polling and get notif...
1
2016-07-23T23:43:15Z
38,547,403
<p>Probably you have to deal with some of C/C++ code, integrated with Python: <a href="https://docs.python.org/3/extending/extending.html" rel="nofollow">https://docs.python.org/3/extending/extending.html</a>. I'm afraid, such low-level functions are almost impossible in hi-level programming language like Python. Also ...
0
2016-07-23T23:48:21Z
[ "python", "python-3.x", "serial-port", "pyserial" ]
Error in converting multiple FASTA files to Nexus using Biopython
38,547,418
<p>I want to convert multiple FASTA format files (DNA sequences) to the NEXUS format using BIO.SeqIO module but I get this error:</p> <pre><code>Traceback (most recent call last): File "fasta2nexus.py", line 28, in &lt;module&gt; print(process(fullpath)) File "fasta2nexus.py", line 23, in process alphabet=...
1
2016-07-23T23:51:20Z
38,547,486
<ol> <li>NameError</li> </ol> <p>You imported SeqIO but are calling seqIO.convert(). Python is case-sensitive. The line should read:</p> <pre><code>return SeqIO.convert(filename + '.fa', "fasta", filename + '.nex', "nexus", alphabet=IUPAC.ambiguous_dna) </code></pre> <ol start="2"> <li>IOError: <code>for files in os...
0
2016-07-24T00:05:42Z
[ "python", "biopython", "fasta" ]
Error in converting multiple FASTA files to Nexus using Biopython
38,547,418
<p>I want to convert multiple FASTA format files (DNA sequences) to the NEXUS format using BIO.SeqIO module but I get this error:</p> <pre><code>Traceback (most recent call last): File "fasta2nexus.py", line 28, in &lt;module&gt; print(process(fullpath)) File "fasta2nexus.py", line 23, in process alphabet=...
1
2016-07-23T23:51:20Z
38,547,954
<p>This code should solve the majority of problems I can see.</p> <pre><code>from __future__ import print_function # or just use Python 3! import fileinput import os import re import sys from Bio import SeqIO, Nexus from Bio.Alphabet import IUPAC test = "/Users/teton/Desktop" def process(filename): # retuns ("...
3
2016-07-24T01:36:01Z
[ "python", "biopython", "fasta" ]
OOP workflow for data
38,547,555
<p>I've worked with the Python basics for some time and fall back to <code>mysql</code> for data analysis. Now I want to learn how to do OOP the Python way, but with all the reading about classes, objects and their attributes: I got lost on the way experimenting and am looking for directions.</p> <p>I use Python modul...
0
2016-07-24T00:17:44Z
38,549,645
<p>Object-orientation is about objects which are bundles of data and functions (or messages that the objects understand) that operate on the data. Instead of starting with plain data structures and dividing them, you should start to think which operations you want to do in your program. Then, cluster these into entitie...
1
2016-07-24T07:17:54Z
[ "python", "class", "oop", "object", "dictionary" ]
How to use Beautiful Soup to extract string in <script> tag?
38,547,569
<p>In a given .html page, I have a script tag like so:</p> <pre><code> &lt;script&gt;jQuery(window).load(function () { setTimeout(function(){ jQuery("input[name=Email]").val("name@email.com"); }, 1000); });&lt;/script&gt; </code></pre> <p>How can I use Beautiful Soup to extract the email address?</p>
2
2016-07-24T00:21:02Z
38,547,945
<p>not possible using only BeautifulSoup, but you can do it for example with BS + regular expressions</p> <pre><code>import re from bs4 import BeautifulSoup as BS html = """&lt;script&gt; ... &lt;/script&gt;""" bs = BS(html) txt = bs.script.get_text() email = re.match(r'.+val\("(.+?)"\);', txt).group(1) </code></p...
1
2016-07-24T01:34:18Z
[ "python", "web-scraping", "beautifulsoup" ]
How to use Beautiful Soup to extract string in <script> tag?
38,547,569
<p>In a given .html page, I have a script tag like so:</p> <pre><code> &lt;script&gt;jQuery(window).load(function () { setTimeout(function(){ jQuery("input[name=Email]").val("name@email.com"); }, 1000); });&lt;/script&gt; </code></pre> <p>How can I use Beautiful Soup to extract the email address?</p>
2
2016-07-24T00:21:02Z
38,549,684
<p>To add a bit more to the <a href="http://stackoverflow.com/a/38547945/771848">@Bob's answer</a> and assuming you need to also locate the <code>script</code> tag in the HTML which may have other <code>script</code> tags.</p> <p>The idea is to define a regular expression that would be used for both <a href="https://w...
2
2016-07-24T07:22:39Z
[ "python", "web-scraping", "beautifulsoup" ]
Fastest way to classify surnames in python
38,547,598
<p>I have a list with 12K asian surnames from a census and a list with 200K names. I'd like to classify those 200K people as asians or non-asians based on wether their surname appears on my 12K list.</p> <p>Is there a fast way to verify if one of the elemenst in the list contains one of the surnames in the 12K list?</...
0
2016-07-24T00:27:13Z
38,548,620
<p>Depends on what you mean by "fast".</p> <p>James suggested using Python's built-in <code>set</code> to test for membership. Python's <code>set</code> implementation uses hash tables. <strong>Average</strong> time complexity is O(1) but the worst case <em>can</em> be O(n) where n is the cardinality of the set of asi...
-1
2016-07-24T04:01:05Z
[ "python", "nlp", "classification", "nltk" ]
Fastest way to classify surnames in python
38,547,598
<p>I have a list with 12K asian surnames from a census and a list with 200K names. I'd like to classify those 200K people as asians or non-asians based on wether their surname appears on my 12K list.</p> <p>Is there a fast way to verify if one of the elemenst in the list contains one of the surnames in the 12K list?</...
0
2016-07-24T00:27:13Z
38,548,652
<p>The best way to do this is to convert your 12K list into a set data structure. Then you can iterate over the census data and check if each is in the set.</p> <pre><code># O(n) where n is the length of the surname_list surname_set = set(surname_list) for name in census: # This is now O(1) operation if name ...
4
2016-07-24T04:08:53Z
[ "python", "nlp", "classification", "nltk" ]
Fastest way to classify surnames in python
38,547,598
<p>I have a list with 12K asian surnames from a census and a list with 200K names. I'd like to classify those 200K people as asians or non-asians based on wether their surname appears on my 12K list.</p> <p>Is there a fast way to verify if one of the elemenst in the list contains one of the surnames in the 12K list?</...
0
2016-07-24T00:27:13Z
38,553,660
<p>It depend to your real problem. do you want machine learning(as you tag: classification) to predict asian/non-asian name?</p> <p>If yes: Try some semi supervised methods. To do this, first randomly select(near 10%) of your 200k data, then search for it in 12k, if it exist, label it to 1, else label it to 0. then us...
0
2016-07-24T15:26:34Z
[ "python", "nlp", "classification", "nltk" ]
Fastest way to classify surnames in python
38,547,598
<p>I have a list with 12K asian surnames from a census and a list with 200K names. I'd like to classify those 200K people as asians or non-asians based on wether their surname appears on my 12K list.</p> <p>Is there a fast way to verify if one of the elemenst in the list contains one of the surnames in the 12K list?</...
0
2016-07-24T00:27:13Z
38,575,091
<p>I would recommend to use <a href="https://en.wikipedia.org/wiki/Locality-sensitive_hashing" rel="nofollow">local sensitive hashing</a> in the first step before training any machine learning models. That probably will help as you don't have many features. If you want something stronger you can use Naive Bayes and som...
0
2016-07-25T18:34:16Z
[ "python", "nlp", "classification", "nltk" ]
Implementing Stack via Array in Python. Error: Stack' object has no attribute 'top'
38,547,655
<p>I was trying to implement Stack via array using Python. Here is my code.</p> <pre><code>class Stack: def init(self,top,size): self.size = 4 self.top = [] def isEmpty(self): if len(self.top) == 0: return True else: return False def length(self):...
0
2016-07-24T00:38:11Z
38,547,683
<p>You need to call your <code>init()</code> method <code>__init__()</code>.</p> <p>Also you should inherit from <code>object</code> as per: <a href="http://stackoverflow.com/questions/15374857/should-all-python-classes-extend-object">Should all Python classes extend object?</a> e.g.:</p> <pre><code>class Stack(objec...
0
2016-07-24T00:44:32Z
[ "python", "runtime-error" ]
How to get index of a sorted list of dictionary in python?
38,547,662
<p>So I know the way to sort a list of dict but I just cannot figure out how to get the index at the same time. Suppose I have a dict like this:</p> <pre><code>cities = [{'city': 'Harford', 'state': 'Connecticut'}, {'city': 'Boston', 'state': 'Massachusetts'}, {'city': 'Worcester', 'state': 'Massac...
0
2016-07-24T00:39:50Z
38,547,763
<pre><code>new_cities = sorted(enumerate(cities), key=lambda x: x[1]['state']) </code></pre> <p>enumerating it first will give you the index of the original <code>cities</code> list which can then be sorted. </p> <pre><code>&gt;&gt;&gt; new_cities [(0, {'city': 'Harford', 'state': 'Connecticut'}), (1, {'city': 'Bost...
1
2016-07-24T00:58:32Z
[ "python", "dictionary", "sorted" ]
Regex search pair of parenthesis at different lines in python
38,547,776
<p>This is the example string in a file I work with:</p> <pre><code>apple (sweet fruit) at home </code></pre> <p>If I want to find anything between parenthesis and remove it, how to do it? This is the result that I expect for:</p> <pre><code>apple at home </code></pre> <p>I tried below but it doesn't work as abo...
0
2016-07-24T01:00:47Z
38,547,802
<p>Try: </p> <pre><code>re.sub(r'\s*\([^)]+\)', '', line) </code></pre> <p>In a python regex, <code>(</code> and <code>)</code> are normally used for grouping. Because you want to match literal parens, not do grouping, we replace <code>(</code> by <code>\(</code> and we replace <code>)</code> by <code>\)</code>.</p>...
2
2016-07-24T01:05:19Z
[ "python", "regex" ]
Regex search pair of parenthesis at different lines in python
38,547,776
<p>This is the example string in a file I work with:</p> <pre><code>apple (sweet fruit) at home </code></pre> <p>If I want to find anything between parenthesis and remove it, how to do it? This is the result that I expect for:</p> <pre><code>apple at home </code></pre> <p>I tried below but it doesn't work as abo...
0
2016-07-24T01:00:47Z
38,548,182
<p>You'll need to use re.MULTILINE and non-greedy match.</p> <pre><code>re.sub(r'\(.+?\)', '', line, re.MULTILINE) </code></pre> <p>Reference: <a href="https://docs.python.org/2/library/re.html" rel="nofollow">https://docs.python.org/2/library/re.html</a></p>
0
2016-07-24T02:25:10Z
[ "python", "regex" ]
Embedded python crashes upon import of matplotlib.pyplot
38,547,856
<p>I am messing about, trying to build something similar to IPython/Jupyter notebooks. I'm writing my application in QT5, so much of this is related to 'embedding' Python in a native application.</p> <p>I figured out how to embed python and how to allow it to execute scripts entered by the user. I would like to be abl...
1
2016-07-24T01:13:13Z
38,549,536
<p>The reason of this crash turned out to be a conflict between QT versions.</p> <p>First of all, the issue can be reproduced using the following minimal code. Commenting out the "Q_OBJECT" line in main.h prevents the crash in all cases.</p> <p>File main.h:</p> <pre><code>#ifndef MAIN_H #define MAIN_H #include &lt;...
1
2016-07-24T06:58:48Z
[ "python", "c++", "qt", "matplotlib" ]
Python Attribute Error if statement
38,547,864
<p>I have been working on this code for about a day now. A few hours on just this one part it keeps saying I have an attribute error on line 26. Unfortunately that is all the information I have. I have tried countless different ways to fix it and have searched many websites/forums. I appreciate any help. Here is the co...
0
2016-07-24T01:15:57Z
38,547,897
<p>The problem is that <code>monthdays</code> does not have a <code>get()</code> method, and that is because <code>monthdays</code> is a <code>set</code>, not a <code>dict</code> as you probably expect.</p> <p>Looking at your code it seems that a list or tuple would be appropriate for <code>monthdays</code>. A set is ...
0
2016-07-24T01:22:18Z
[ "python", "attributes", "attributeerror" ]
Python Attribute Error if statement
38,547,864
<p>I have been working on this code for about a day now. A few hours on just this one part it keeps saying I have an attribute error on line 26. Unfortunately that is all the information I have. I have tried countless different ways to fix it and have searched many websites/forums. I appreciate any help. Here is the co...
0
2016-07-24T01:15:57Z
38,547,911
<p>set objects ('monthdays' in your case) don't have attribute 'get'</p> <p>you should iterate over it or convert it to list, e.g.:</p> <p><code>list(monthdays)[0]</code> will return the first item of the resulting list</p>
-2
2016-07-24T01:25:00Z
[ "python", "attributes", "attributeerror" ]
How to implement pre and post increment in Python lists?
38,547,931
<p>In Python how can we increment or decrement an index within the square braces of a list?</p> <p>For instance, in Java the following code </p> <pre><code>array[i] = value i-- </code></pre> <p>can be written as </p> <pre><code>array[i--] </code></pre> <p>In <strong>Python</strong>, how can we implement it? <cod...
3
2016-07-24T01:30:42Z
38,547,955
<p>Python does not have a -- or ++ command. For reasons why, see <a href="http://stackoverflow.com/questions/3654830/why-are-there-no-and-operators-in-python">Why are there no ++ and --​ operators in Python?</a></p> <p>Your method is idiomatic Python and works fine - I see no reason to change it.</p>
4
2016-07-24T01:36:02Z
[ "java", "python", "post-increment", "pre-increment" ]
How to implement pre and post increment in Python lists?
38,547,931
<p>In Python how can we increment or decrement an index within the square braces of a list?</p> <p>For instance, in Java the following code </p> <pre><code>array[i] = value i-- </code></pre> <p>can be written as </p> <pre><code>array[i--] </code></pre> <p>In <strong>Python</strong>, how can we implement it? <cod...
3
2016-07-24T01:30:42Z
38,547,957
<p>If what you need is to iterate backwards over a list, this may help you: </p> <pre><code>&gt;&gt;&gt; a = ["foo", "bar", "baz"] &gt;&gt;&gt; for i in reversed(a): ... print i ... baz bar foo </code></pre> <p>Or: </p> <pre><code>for item in my_list[::-1]: print item </code></pre> <p>The first way is how ...
4
2016-07-24T01:36:09Z
[ "java", "python", "post-increment", "pre-increment" ]
How to iterate over all these possibilities?
38,547,980
<p>Assume we have a python list</p> <pre><code>list = [[1,2,3],[4,5,6],[7,8,9]] </code></pre> <p>I define the sum as the following,</p> <p>sum: is the total sum of single entries (different index) from each of the sublists.</p> <p>This sounds complex so I will give an example,</p> <p>for the above list, 1 + 5 + 9 ...
1
2016-07-24T01:41:39Z
38,548,076
<p>The naive implementation uses <code>itertools.product</code> to produce all possible pairings, then filters out the ones that won't work due to indexing issues.</p> <pre><code>from itertools import product lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] with_indices = [ [(idx, val) for idx, val in enumerate(sublst)] for ...
0
2016-07-24T02:01:32Z
[ "python", "algorithm" ]
How to iterate over all these possibilities?
38,547,980
<p>Assume we have a python list</p> <pre><code>list = [[1,2,3],[4,5,6],[7,8,9]] </code></pre> <p>I define the sum as the following,</p> <p>sum: is the total sum of single entries (different index) from each of the sublists.</p> <p>This sounds complex so I will give an example,</p> <p>for the above list, 1 + 5 + 9 ...
1
2016-07-24T01:41:39Z
38,548,101
<p>This is a classic problem that can be solved using <a href="https://en.wikipedia.org/wiki/Hungarian_algorithm">Hungarian algorithm</a>. There is an implementation in sklearn:</p> <pre><code>from sklearn.utils.linear_assignment_ import linear_assignment import numpy as np M = [[1,2,3],[4,5,6],[7,8,9]] M = np.array...
8
2016-07-24T02:07:19Z
[ "python", "algorithm" ]
How to iterate over all these possibilities?
38,547,980
<p>Assume we have a python list</p> <pre><code>list = [[1,2,3],[4,5,6],[7,8,9]] </code></pre> <p>I define the sum as the following,</p> <p>sum: is the total sum of single entries (different index) from each of the sublists.</p> <p>This sounds complex so I will give an example,</p> <p>for the above list, 1 + 5 + 9 ...
1
2016-07-24T01:41:39Z
38,548,709
<p>I don't know about <strong>execution efficiency</strong>, but for code writing efficiency you can consider:</p> <pre><code>for k in itertools.permutations(lst): print(sum([j[i] for i, j in enumerate(k)])) </code></pre> <p>Will only work for square list as in OP example.</p>
0
2016-07-24T04:19:32Z
[ "python", "algorithm" ]
Represent sparse matrix in Python without library usage
38,547,996
<p>I want to represent sparse matrix in Python in a data structure that does not waste space but in the same time preserves constant access time. Is there any easy/trivial way of doing it? I know that libraries such as scipy have it.</p>
0
2016-07-24T01:44:52Z
38,548,006
<p>Lots of ways to do it. For example you could keep a list where each list element is either one of your data objects, or an integer representing N blank items.</p>
0
2016-07-24T01:47:42Z
[ "python", "data-structures" ]
Represent sparse matrix in Python without library usage
38,547,996
<p>I want to represent sparse matrix in Python in a data structure that does not waste space but in the same time preserves constant access time. Is there any easy/trivial way of doing it? I know that libraries such as scipy have it.</p>
0
2016-07-24T01:44:52Z
38,548,024
<p>Dict with tuples as keys might work.</p>
0
2016-07-24T01:51:01Z
[ "python", "data-structures" ]
Represent sparse matrix in Python without library usage
38,547,996
<p>I want to represent sparse matrix in Python in a data structure that does not waste space but in the same time preserves constant access time. Is there any easy/trivial way of doing it? I know that libraries such as scipy have it.</p>
0
2016-07-24T01:44:52Z
38,548,640
<p>The <code>scipy.sparse</code> library uses different formats depending on the purpose. All implement a 2d matrix</p> <ul> <li><p>dictionary of keys - the data structure is a dictionary, with a tuple of the coordinates as key. This is easiest to setup and use.</p></li> <li><p>list of lists - has 2 lists of lists. ...
0
2016-07-24T04:06:00Z
[ "python", "data-structures" ]
Kivy get TextInput from Popup
38,548,075
<p>I have a simple app that asks for your name and age in a <code>TextInput</code> field. When you click the save button a <code>Popup</code> opens and you can save the name and age from the <code>TextInput</code> in a file.</p> <p>Question: How can I access the Name and Age when the <code>Popup</code> is already ope...
1
2016-07-24T02:01:28Z
38,552,214
<p>Yoy can pass your object to the popup object. That way you can accsess all the widgets attributes for the popup object. An example of this can look like this.</p> <pre><code>from kivy.uix.popup import Popup from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.textinput import Te...
1
2016-07-24T12:49:55Z
[ "python", "kivy" ]
Output redirection to multiple files
38,548,121
<p>I need to run a python script for multiple input files and for each one, I want to generate a new corresponding output file (e.g. for input_16jun.txt I want the output file to be 16jun_output.txt). I tried doing something like:</p> <pre><code>nohup python script.py input_{16..22}jun.txt &gt; {16..22}jun_output.txt ...
1
2016-07-24T02:12:09Z
38,552,405
<p>Looping over each input file like this with bash should work.</p> <pre><code>for f in input_*.txt; do python script.py $f &gt; "${f:6:-4}"_output.txt; done </code></pre> <p>Alternatively if you want to do the loop in a python script.</p> <pre><code>import glob import os input_files = glob.glob("input_*.txt") fo...
2
2016-07-24T13:11:39Z
[ "python", "bash", "redirect" ]
Dynamically add/remove plot using 'bokeh serve' (bokeh 0.12.0)
38,548,442
<p>My question is quite similar to <a href="http://stackoverflow.com/questions/28813266/bokeh-0-7-1-dynamically-add-plot-to-bokeh-server-generated-existing-page">another thread</a> using bokeh 0.7.1, but the API for bokeh servers has changed enough in 0.12.0, that I am struggling to adapt that answer to the new version...
4
2016-07-24T03:24:22Z
39,986,194
<p>A similar problem was answered on the Bokeh Github page <a href="https://github.com/bokeh/bokeh/issues/3937" rel="nofollow">here</a>. </p> <p>Essentially, instead of messing with <code>curdoc()</code> you instead modify the children of the layout object e.g. <code>someLayoutHandle.children</code>. </p> <p>A simple...
2
2016-10-11T20:30:16Z
[ "python", "bokeh" ]
list populate by append function can't be sorted by sort function
38,548,535
<p>I create a list with a loop using append function to populate the list. and after I want to sort it with the list sort function on one of the element's attribute. but it doesn't work, can you guys help me, thank a lot. here is the code</p> <pre><code>def processRawUrlData(): rawData = readHtml() taskList = ...
-6
2016-07-24T03:43:35Z
38,549,264
<p>I think you may have to be more specific and provide a comparison function so that your list can be sorted. Took the code below from the following site. Hope it helps:</p> <p><a href="https://wiki.python.org/moin/HowTo/Sorting" rel="nofollow">https://wiki.python.org/moin/HowTo/Sorting</a></p> <pre><code> &gt;&g...
0
2016-07-24T06:08:08Z
[ "python", "list", "sorting" ]
Connection to IRC server with python socket
38,548,615
<p>Alright so, the following code allows me to connect to some IRC servers pretty well. However I can't seem to connect to others, could be because of auth, not sure. Specifically one of those servers is irc.d2jsp.org</p> <p>So my question is, how do I connect to this server and why doesn't my console say something wh...
0
2016-07-24T03:59:59Z
38,550,111
<p>It is not because of your code. The server listening at irc.d2jsp.org:6667 accepts connections, but does not send anything.</p> <p>The only reaction I can get from it is that it closes the connection after we send a <code>QUIT</code> command.</p> <hr> <p>PS: That is totally unrelated to your problem, but on this ...
0
2016-07-24T08:27:48Z
[ "python", "sockets", "bots", "irc" ]
Reading Matrix Market Graphs in igraph
38,548,688
<p>is there any possibility to read MatrixMarket (*.mtx) graphs using the python igraph framework? <a href="http://networkrepository.com/" rel="nofollow">http://networkrepository.com/</a> provides a huge set of different test networks, which would be helpful in case igraph could read them.</p>
0
2016-07-24T04:16:56Z
38,548,726
<p>Just found a solution. The graphs provided at <a href="http://networkrepository.com/" rel="nofollow">http://networkrepository.com/</a> are in edgelist format. Removing trailing 2 lines (a line of comments and a line of summary about the graph) leaves a normal edgelist file, which can be read with</p> <pre><code>imp...
0
2016-07-24T04:23:32Z
[ "python", "igraph" ]
Python 2.7 protobuf .py file generation issue
38,548,773
<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>Here is the content of generated addressbook_pb2.py file, question is...
1
2016-07-24T04:32:40Z
38,624,802
<p>The <code>Person</code> class is defined in this line of your <code>addressbook_pb2.py</code>:</p> <pre><code>Person = _reflection.GeneratedProtocolMessageType('Person', (_message.Message,), dict( ... ) ) </code></pre> <p>And similarly for the <code>AddressBook</code> class. Note that the <code>PhoneNumber</code> ...
1
2016-07-27T23:31:12Z
[ "python", "python-2.7", "protocol-buffers", "google-protobuf" ]
Python 2.7 protobuf .py file generation issue
38,548,773
<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>Here is the content of generated addressbook_pb2.py file, question is...
1
2016-07-24T04:32:40Z
38,624,805
<p>The Python classes are generated dynamically at runtime.</p> <p>Quoting from the documentation page that you have linked to:</p> <blockquote> <p>The important line in each class is <strong>metaclass</strong> = reflection.GeneratedProtocolMessageType. While the details of how Python metaclasses work is beyond...
1
2016-07-27T23:31:25Z
[ "python", "python-2.7", "protocol-buffers", "google-protobuf" ]
TkInter; Non-responsive when being told to update
38,548,826
<p>I have a GUI program built using Tkinter in python 2.7.10.</p> <p>It works flawlessly, for it's root cause anyways.</p> <p>Unfortunately, it briefly goes into windows dreaded "Not Responding" state when being interacted with.</p> <p>Here's the layout in short:</p> <p>Launch script launches Main script. Main scri...
-1
2016-07-24T04:42:58Z
38,549,202
<p>The linked duplicate question held an answer. A bad one - but an answer none the less. </p> <p><code>update_idletasks</code>.</p> <p>I tried that, and, it Worked! Well. Sort of.</p> <p>It worked at first, then the same result came about. The GUI temporarily froze.</p> <p>Then an idea popped in my head. Why not t...
0
2016-07-24T05:57:55Z
[ "python", "windows", "user-interface", "tkinter" ]
Python - Use external function as class method
38,548,953
<p>Say I have some very long function <code>module.my_function</code> that's something like this:</p> <pre><code>def my_function(param1,param2,param3='foo',param4='bar',param5=None,...) </code></pre> <p>With a large number of args and keyword args. I want this function to be usable both as a part of module <code>modu...
0
2016-07-24T05:12:27Z
38,549,072
<p>You can convert the function to bound method by calling its <code>__get__</code> method (since all function as <a href="https://docs.python.org/3/howto/descriptor.html" rel="nofollow">descriptors</a> as well, thus have this method)</p> <pre><code>def t(*args, **kwargs): print(args) print(kwargs) class Test...
0
2016-07-24T05:36:48Z
[ "python", "function", "class", "methods" ]
Discord Bot written in Python minigame while loop not working
38,548,965
<p>This piece of code i wrote for a Discord Bot is not working and i would like to find out why and how to make it work and maybe different methods.</p> <pre><code>def russian_roulette(author, message): game_active = True client.send_message(message.channel, "Russian Roulette game started.6 chambers. 1 loaded....
-1
2016-07-24T05:15:02Z
38,549,060
<p>I'm assuming that you're using <a href="https://github.com/Rapptz/discord.py" rel="nofollow">this API wrapper for discord</a>.</p> <p>In that case, what you'll need to do is create a function with the decorator client.event so that it responds to messages properly. Like so:</p> <pre><code>@client.event async def o...
0
2016-07-24T05:33:50Z
[ "python", "bots" ]
Running True/False statements on coordinates stored in two separate documents
38,548,978
<p>still pretty new to this all so any help, advice, etc is really appreciated.</p> <p>Heres my code:</p> <pre><code>import math import pandas file1 = pandas.read_excel('Book1.xlsx') file2 = pandas.read_excel('Book2.xlsx') file1['RA_diff'] = file2['RA'] - file1['RA'] file1['DEC_diff'] = file2['DEC'] - file1['DEC'] di...
0
2016-07-24T05:16:26Z
38,550,309
<p>The problem is in this line:</p> <pre><code>if dist.values &gt;= 5: print False </code></pre> <p><code>dist.values</code> is a pandas series. You even proved this when you printed and got <code>0 4.472136</code>. When you compare a series to a number, you get another series where each member of the series...
3
2016-07-24T08:55:27Z
[ "python", "excel", "pandas", "math", "coordinates" ]
draw a simple board for tic tac toe in python, gives error of IndentationError
38,548,983
<pre><code>def display_board(board): print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | |') print('-----------') print(' | |') print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) print(' | |') print('-----------') print(' | ...
-3
2016-07-24T05:17:49Z
38,549,008
<p>Python style guidelines suggest using 4 spaces instead of tab characters - your issue is almost certainly because in your file, you have mixed tabs and spaces or indented improperly. I suggest either using an editor that converts tabs to spaces or using spaces yourself.</p> <p>As your code stands here, it is perfec...
0
2016-07-24T05:23:19Z
[ "python" ]
Tensorflow seq2seq multidimensional regression
38,549,040
<p>I try to do a sequence-to-sequence (seq2seq) regression with multidimensional inputs and outputs. I tried something which yields the following loss over time: </p> <p><a href="http://i.stack.imgur.com/uNOdt.png" rel="nofollow"><img src="http://i.stack.imgur.com/uNOdt.png" alt="Loss function over time"></a></p> <p>...
0
2016-07-24T05:30:57Z
38,576,320
<p>For learning functions like sin(x), it is not good to use softmax loss. * softmax losses are generally used for multi-class <em>discrete</em> predictions * for continuous predictions, use, e.g., l2_loss</p> <p>Also, since sin(x) is a function of x, I don't think you need an RNN for that. I'd really first try a 2-la...
1
2016-07-25T19:55:49Z
[ "python", "machine-learning", "tensorflow", "deep-learning", "recurrent-neural-network" ]
How to close sqlite connection in daemon thread?
38,549,088
<p>I have multiple threads that process data and puts it on a queue, and a single thread that takes data from a queue and then saves it to a database. </p> <p>I think the following will cause a memory leak:</p> <pre><code>class DBThread(threading.Thread): def __init__(self, myqueue): threading.Thread.__in...
0
2016-07-24T05:39:21Z
38,552,077
<p>If you can use a sentinel value that will not appear in your normal data, e.g. <code>None</code>, you can signal the thread to stop and close the database connection in a <code>finally</code> clause:</p> <pre><code>import threading import Queue import sqlite3 class DBThread(threading.Thread): def __init__(self...
0
2016-07-24T12:34:19Z
[ "python", "multithreading", "python-2.7", "sqlite3", "python-multithreading" ]
How to convert protobuf graph to binary wire format?
38,549,153
<p>I have a method to convert binary wire format to human readable format but I cannot do the inverse of this </p> <pre><code>import tensorflow as tf from tensorflow.python.platform import gfile def converter(filename): with gfile.FastGFile(filename,'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFrom...
7
2016-07-24T05:51:35Z
38,706,193
<p>You can perform the reverse translation using the <code>google.protobuf.text_format</code> module:</p> <pre><code>import tensorflow as tf from google.protobuf import text_format def convert_pbtxt_to_graphdef(filename): """Returns a `tf.GraphDef` proto representing the data in the given pbtxt file. Args: f...
2
2016-08-01T18:58:56Z
[ "python", "python-2.7", "tensorflow", "protocol-buffers" ]
How to convert protobuf graph to binary wire format?
38,549,153
<p>I have a method to convert binary wire format to human readable format but I cannot do the inverse of this </p> <pre><code>import tensorflow as tf from tensorflow.python.platform import gfile def converter(filename): with gfile.FastGFile(filename,'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFrom...
7
2016-07-24T05:51:35Z
38,832,082
<p>You can use <a href="https://www.tensorflow.org/versions/master/api_docs/python/framework.html#Graph.as_graph_def" rel="nofollow"><code>tf.Graph.as_graph_def()</code></a> and then Protobuf's <a href="https://developers.google.com/protocol-buffers/docs/pythontutorial" rel="nofollow"><code>SerializeToString()</code></...
1
2016-08-08T14:38:28Z
[ "python", "python-2.7", "tensorflow", "protocol-buffers" ]
django doesn't dump tables into database
38,549,163
<p>I'm having trouble trying to dump tables into a sqlite database. My settings.py is as follows:</p> <pre><code>INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ...
0
2016-07-24T05:52:14Z
38,552,578
<p>Is your <code>settings.py</code>correctly configured to use the SQL file you are looking at?</p> <pre><code>DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } </code></pre>
0
2016-07-24T13:32:53Z
[ "python", "django", "sqlite" ]
Could not display Product image in an API
38,549,312
<p>I have been trying to design a rest API using Django Rest Framework for creating mobile application. I could design an API for Store list which shows store owner(merchant) information, store information, category of store and Product but product image is not displayed. Why my code is not showing product image? Could...
1
2016-07-24T06:16:35Z
38,549,381
<p>In your models.py create:</p> <pre><code>import os </code></pre> <p>Remove Product foreign key from your ProductImage model:</p> <pre><code>class ProductImage(models.Model): image = models.ImageField(upload_to='products/images/') updated = models.DateTimeField(auto_now_add=False, auto_now=True) @prop...
1
2016-07-24T06:28:54Z
[ "python", "django", "api", "django-rest-framework" ]
heapq.merge default key?
38,549,365
<p>Refer to the following code copied from solution 4 of this page - <a href="https://discuss.leetcode.com/topic/50450/slow-1-liner-to-fast-solutions/2" rel="nofollow">https://discuss.leetcode.com/topic/50450/slow-1-liner-to-fast-solutions/2</a>:</p> <pre><code> streams = map(lambda u: ([u+v, u, v] for v in nums2),...
-1
2016-07-24T06:26:29Z
38,549,451
<p>It's not merely sorting on <code>u+v</code>, it's sorting on the entire <code>[u+v, u, v]</code> list. The standard way that Python compares two ordered collections is by comparing corresponding elements, starting at the lowest index and working up until a pair of corresponding elements are unequal. If one sequence ...
1
2016-07-24T06:41:38Z
[ "python", "algorithm", "sorting", "heap" ]
How to toggle microphone on and off using python
38,549,391
<p>I am wondering if there is a way to use python to mute and microphone? I am working on a project that requires the Microphone setting to be set to "Listen to this device". However, to prevent the Microphone from picking up unwanted noise from a TV or radio, I need a way to toggle between Mute and Unmute through a py...
0
2016-07-24T06:30:46Z
38,549,618
<p><a href="http://people.csail.mit.edu/hubert/pyaudio/" rel="nofollow">PyAudio</a> is one cross-platform option for this. It's more than just direct access to the audio device controls, so it's moderately complicated to use. <a href="http://pymedia.org/docs/pymedia.audio.sound.html" rel="nofollow">pymedia</a> is anoth...
0
2016-07-24T07:13:12Z
[ "python", "python-3.x" ]
MySQL-python install Mac
38,549,431
<p>I am trying to install MySQLdb for Python on my mac so I can use it to test. I am running <em>OS X 10.11.4</em>. Everywhere I look says to use </p> <pre><code>pip install MySQL-python </code></pre> <p>Every time I do that I get an error saying.</p> <pre><code>Command "python setup.py egg_info" failed with error...
1
2016-07-24T06:37:43Z
38,549,501
<p>install mysql connector using homebrew <code>brew install mysql-connector-c</code> then install mysql-python using pip <code>pip install mysql-python</code> or try PyMySQL its a pure python client library, you can install using <code>pip install PyMySQL</code> and upgrade <code>setuptools</code>. <code>pip install -...
2
2016-07-24T06:51:34Z
[ "python", "mysql", "osx" ]
How and where to use Python's __and__, __or__, __invert__ magic methods properly
38,549,444
<p>I was googling around to find any use cases or examples of these methods but could not find any detailed explanation, they are just listed along other similar methods. Actually, I was looking through some code on github and came across these methods but could not understand the usage. Can somebody please provide a d...
0
2016-07-24T06:40:15Z
38,549,904
<p>The magic methods <code>__and__</code>, <code>__or__</code> and <code>__invert__</code> are used to override the operators <code>a &amp; b</code>, <code>a | b</code> and <code>~a</code> respectively. That is, if we have a class</p> <pre><code>class QueryImpl(object): def __and__(self, other): return ......
3
2016-07-24T07:55:27Z
[ "python", "magic-methods" ]
Python-Pygame Not Working
38,549,469
<p>I installed python(2.7) using anaconda on an ubuntu machine.</p> <p>I installed pygame.</p> <p>When I import pygame I get the error:</p> <pre><code>ImportError: No module named pygame </code></pre> <p>Interestingly, when I use <code>/usr/bin/python</code>, </p> <p>the interpreter now gives no error for import p...
0
2016-07-24T06:44:52Z
38,552,913
<p>Which version are you using? You most import pygame to a Python 2.7 shell. <a href="http://pygame.org/download.shtml" rel="nofollow">http://pygame.org/download.shtml</a> is for <a href="https://www.python.org/" rel="nofollow">https://www.python.org/</a> version 2.7. Make sure you have downloaded and made the setup f...
0
2016-07-24T14:08:34Z
[ "python", "linux", "python-2.7", "error-handling", "pygame" ]
for loop in thread runs once in Python 3
38,549,482
<p>I've written a Python script to fetch certificates of a list of IP address to match a domain:</p> <pre><code>#! /usr/bin/env python3 import ssl import socket import argparse from threading import Thread, Lock from itertools import islice class scanThread(Thread): def __init__(self,iplist, q, hostname, port): ...
0
2016-07-24T06:47:18Z
38,549,496
<p>This might be because you are clearing the list in the main function.</p> <pre><code> t = scanThread(iplist, hostPool, hostname, port) t.start() threads.append(t) iplist.clear() // here you are clearing. </code></pre> <p>Can you try:</p> <pre><code>class scanThread(Thread): def __init__(self,ip...
0
2016-07-24T06:51:06Z
[ "python", "multithreading", "ssl", "certificate" ]