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
Print a 'X' pattern of '*'
38,025,263
<p>I'm trying to print this pattern in Python:</p> <pre><code>* * * * * * * * * * * * * </code></pre> <p>And came up with this code:</p> <pre><code>size = 7 inner_size = size - 3 space=0 for i in range(inner_size): print (' ' * space + '*' + ' ' * inner_size + '*') inner_size -=2 s...
2
2016-06-25T05:20:34Z
38,025,381
<p>Just another way of solving the problem:</p> <pre><code>for i in range(5): for j in range(5): if ((i==j) or j==(5-i-1)): print " *", else: print " ", print "" </code></pre> <p>~ </p>
1
2016-06-25T05:40:37Z
[ "python" ]
Print a 'X' pattern of '*'
38,025,263
<p>I'm trying to print this pattern in Python:</p> <pre><code>* * * * * * * * * * * * * </code></pre> <p>And came up with this code:</p> <pre><code>size = 7 inner_size = size - 3 space=0 for i in range(inner_size): print (' ' * space + '*' + ' ' * inner_size + '*') inner_size -=2 s...
2
2016-06-25T05:20:34Z
38,025,396
<p>You can also do it like this:</p> <pre><code>pattern_size = 7 for t in range(pattern_size): pattern = list(" " * pattern_size) pattern[t] = "*" pattern[-(t+1)] = "*" print("".join(pattern)) </code></pre> <p>Output:</p> <pre><code>* * * * * * * * * * * * * </code></pre...
1
2016-06-25T05:42:43Z
[ "python" ]
Print a 'X' pattern of '*'
38,025,263
<p>I'm trying to print this pattern in Python:</p> <pre><code>* * * * * * * * * * * * * </code></pre> <p>And came up with this code:</p> <pre><code>size = 7 inner_size = size - 3 space=0 for i in range(inner_size): print (' ' * space + '*' + ' ' * inner_size + '*') inner_size -=2 s...
2
2016-06-25T05:20:34Z
38,025,400
<p>I have used ideas from your existing code in the question and made a few tweaks to do it in a single loop with simple, crystal clear code:</p> <pre><code>def xprint(size): i,j = 0,size - 1 while j &gt;= 0 and i &lt; size: initial_spaces = ' '*min(i,j) middle_spaces = ' '*(abs(i - j) - 1) ...
1
2016-06-25T05:43:25Z
[ "python" ]
Python convert Excel 2004 xml to csv(or excel)
38,025,320
<p>I am trying to convert a excel xlm file into csv (or excel) format, could anyone suggest how to do it by python? I tried to search in this web for answer, but all answer using xlst, but I am a fresh man to python, could you please demonstrate it in detail?</p> <p>Thank you. Here is the file opened by textpad tools:...
0
2016-06-25T05:30:35Z
38,026,009
<p>if you are using windows,you can use code as follow(you need pythonwin) <a href="http://i.stack.imgur.com/xyDxT.png" rel="nofollow">enter image description here</a></p> <p>then use like<a href="http://i.stack.imgur.com/pIpHC.png" rel="nofollow">enter image description here</a></p> <p>and for write into csv file,i ...
0
2016-06-25T07:13:21Z
[ "python", "excel", "vba", "csv" ]
Python convert Excel 2004 xml to csv(or excel)
38,025,320
<p>I am trying to convert a excel xlm file into csv (or excel) format, could anyone suggest how to do it by python? I tried to search in this web for answer, but all answer using xlst, but I am a fresh man to python, could you please demonstrate it in detail?</p> <p>Thank you. Here is the file opened by textpad tools:...
0
2016-06-25T05:30:35Z
38,053,526
<p>For starters, the Excel 2014 XML format is, well, <em>XML</em>. In order to parse that, you need to read up on how to <a href="https://docs.python.org/2/library/xml.html#module-xml" rel="nofollow">process XML with Python</a>.</p> <p>To write out to a CSV file, you can use <a href="https://docs.python.org/2/library/...
0
2016-06-27T12:04:50Z
[ "python", "excel", "vba", "csv" ]
Replace unique values of pandas data-frame
38,025,341
<p>Hi I'm new to python and pandas.</p> <p>I have extracted the unique values of one of the column using pandas. Now after getting the unique values of the column, which are string.</p> <pre><code>['Others, Senior Management-Finance, Senior Management-Sales' 'Consulting, Strategic planning, Senior Management-Financ...
1
2016-06-25T05:33:43Z
38,025,451
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html" rel="nofollow"><code>factorize</code></a>:</p> <pre><code>df['Col1'] = pd.factorize(df.Col1)[0] + 1 print (df) Col1 0 1 1 1 2 2 3 2 4 2 5 3 6 3 </code></pre> <p><a href="http://pandas.pydata.org...
1
2016-06-25T05:52:40Z
[ "python", "pandas", "replace", "dataframe", "categories" ]
How Can I follow A Link to a specific post and scrape the data from the
38,025,466
<p>I am trying to follow links from posts that I have scraped so I can save the text. I am partly there. I just need to tweak some things which is why I'm here. Instead of different posts I am getting duplicates. and not only that, they are surrounded in brackets like this</p> <pre><code>[[&lt;div class="article-body"...
1
2016-06-25T05:56:06Z
38,029,893
<p>I figured it out</p> <pre><code>def sprinkle(): url_two = 'http://www.vladtv.com' html = requests.get(url_two, headers=headers) soup = BeautifulSoup(html.text, 'html5lib') titles = soup.find_all('div', {'class': 'entry-pos-1'}) def make_soup(url): the_comments_pa...
2
2016-06-25T15:14:43Z
[ "python", "django", "web-scraping", "beautifulsoup" ]
Merge two csv files with custom columns
38,025,512
<p>I have two csv files: test1</p> <pre><code>A B 1 a 2 b 3 c 4 d 5 e </code></pre> <p>test2</p> <pre><code>A C D B 3 x 25 101 2 y 0.35 11 1 z 0.45 111 6 k 0.55 1101 7 l 0.65 1010 </code></pre> <p>I want to merge them on = A but i need only the columns test1.A,B a...
1
2016-06-25T06:03:33Z
38,025,558
<p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow"><code>drop</code></a> column <code>C</code> in <code>csv2</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a> with para...
1
2016-06-25T06:08:33Z
[ "python", "csv", "pandas", "dataframe", "merge" ]
Publish python project with imported modules
38,025,550
<p>I would like to publish a python project, but i use modules in it like socket. How do i add to the project code that is not mine? Is that even legal?</p>
0
2016-06-25T06:07:44Z
38,026,035
<p>There's no need to add modules that are in the standard library. For other dependencies, you can </p> <ul> <li>test if the module is available (<code>try: import x except: error()</code>) and notify the user to install it or even automatically install it</li> <li><a href="https://pypi.python.org/pypi" rel="nofollow...
0
2016-06-25T07:17:02Z
[ "python", "publishing" ]
Caffe LeNet: Difference between `solver.step(1)` and `solver.net.forward()`
38,025,639
<p>I was checking the Caffe LeNet Tutorial <a href="http://nbviewer.jupyter.org/github/BVLC/caffe/blob/master/examples/01-learning-lenet.ipynb" rel="nofollow">here</a> and a question came to mind:</p> <p>What's the difference between these 2 codes:</p> <pre><code>self.solver.step(1) </code></pre> <p>and</p> <pre><c...
1
2016-06-25T06:21:47Z
38,063,044
<p><strong>step</strong> does one full iteration, covering all three phases: <strong>forward</strong> evaluation, <strong>backward</strong> propagation, and <strong>update</strong>. The call to <strong>forward</strong> does only the first of these. There are also differences in the signature (parameter list).</p>
2
2016-06-27T20:53:04Z
[ "python", "neural-network", "deep-learning", "caffe", "conv-neural-network" ]
TemplateDoesnotExist at polls
38,025,663
<p>When I am trying to apply template for views by loader module, I'm getting the following error.I want to know whether this error is due to my proxy network or error related to directories of template.</p> <p>views.py is :</p> <pre><code>from django.shortcuts import render from django.http import HttpResponse from ...
-1
2016-06-25T06:25:24Z
38,033,705
<p>make sure inside your <strong>polls</strong> app directory there's a folder called <strong>templates</strong> and inside it, there's another folder called <strong>polls</strong> where the index.html is located. That way the template loader will automatically detect the file. The path to the index file should look li...
0
2016-06-25T23:04:37Z
[ "python", "django", "templates" ]
how to store rabbitMQ messages
38,025,791
<p>I am using a RabbitMQ server with python for sending and receiving messages to the server This is the code I am using for sending a message in to code.</p> <pre><code>import numpy as np import pandas as pd import pika connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) c...
0
2016-06-25T06:41:59Z
38,027,224
<blockquote> <p>The problem is I want to save this message i.e. "Hello World" to a variable and then use it in my program</p> </blockquote> <p>You've got a variable already which you can use in you program - <code>body</code>. If you'd like to decouple the <em>infrastructure code</em> (i.e. RabbitMq/pika) from the <...
0
2016-06-25T10:00:00Z
[ "python", "rabbitmq", "pika" ]
Regex to allow mathmetical operation
38,025,811
<p>This is the regex that I currently have (which doesn't work)</p> <pre><code>^(pow|sqrt|[0-9*,/\-\+\(\)])+$ </code></pre> <p>What I want is to ONLY allow the following characters: <code>+</code> <code>-</code> <code>/</code> <code>,</code> <code>*</code> <code>(</code> <code>)</code>, numbers <code>0-9</code> and t...
0
2016-06-25T06:45:05Z
38,025,843
<p>I spotted two errors, you should escape <code>/</code> as well, and you forgot the number <code>0</code>. But this may differ over different regex implementations.</p> <pre><code>^(pow|sqrt|[0-9*,\/\-\+\(\)])+$ </code></pre> <p>Of course, this regex in no way ensures that the sentence is a valid math operation, fo...
2
2016-06-25T06:50:27Z
[ "python", "regex", "django" ]
Regex to allow mathmetical operation
38,025,811
<p>This is the regex that I currently have (which doesn't work)</p> <pre><code>^(pow|sqrt|[0-9*,/\-\+\(\)])+$ </code></pre> <p>What I want is to ONLY allow the following characters: <code>+</code> <code>-</code> <code>/</code> <code>,</code> <code>*</code> <code>(</code> <code>)</code>, numbers <code>0-9</code> and t...
0
2016-06-25T06:45:05Z
38,025,846
<p>You have some syntax issues :</p> <pre><code>^(pow|sqrt|[0-9\*\,/\-\+\(\)])+$ </code></pre> <p>should works. But it doesn't take care of character order, "pow9(10,sqrt" will be correct and you can't do this with regex.</p>
0
2016-06-25T06:50:46Z
[ "python", "regex", "django" ]
Regex to allow mathmetical operation
38,025,811
<p>This is the regex that I currently have (which doesn't work)</p> <pre><code>^(pow|sqrt|[0-9*,/\-\+\(\)])+$ </code></pre> <p>What I want is to ONLY allow the following characters: <code>+</code> <code>-</code> <code>/</code> <code>,</code> <code>*</code> <code>(</code> <code>)</code>, numbers <code>0-9</code> and t...
0
2016-06-25T06:45:05Z
38,025,914
<p>Although this does not directly answer OP's problem. I feel that these are a required reading, specially when dealing with USER input.</p> <blockquote> <ul> <li>SANDBOX ESCAPE<br> This is the traditional rationale against using eval(). You cannot simply let the user to run arbitrary code on the server, as the...
1
2016-06-25T07:01:15Z
[ "python", "regex", "django" ]
natural language processing the response is taking more then 10 sec in python
38,025,819
<p>I am using spacy for precessing language. Passing content from PHP file to python and getting response which is taking more then 10 sec, below is my code:</p> <pre><code>import spacy import pymongo import datetime import sys, json, time from nltk.chunk import * from dateutil import parser aList = [] from spacy.en i...
-1
2016-06-25T06:46:15Z
38,025,856
<p>I think generators may solve your problem.To know more about generators visit this <a href="http://anandology.com/python-practice-book/iterators.html" rel="nofollow">http://anandology.com/python-practice-book/iterators.html</a>. 5.3.1 may be useful to you. </p>
0
2016-06-25T06:52:29Z
[ "python", "nlp", "delay", "language" ]
how to edit shopify fulfillment using python api
38,025,834
<p>how to add tracking number and tracking url in existing shopify fulfillment using shopify python api.</p> <p>code:</p> <pre><code>token = &lt;token&gt; session = shopify.Session("&lt;shop-name&gt;.myshopify.com", token) shopify.ShopifyResource.activate_session(session) a = shopify.Fulfillment.find(2642971265,order...
1
2016-06-25T06:48:19Z
38,027,813
<p>I forgot to add the other details i.e tracking_urls and tracking_numbers</p> <pre><code>a = shopify.Fulfillment.find(order_id = 3386116225)[0] a.tracking_company = "pickrr" a.tracking_number = '12345678' l = [] l.append('12345678') a.tracking_numbers = l a.tracking_url = "pickrr.com/12345678" l = [] l.append("pickr...
0
2016-06-25T11:08:05Z
[ "python", "api", "shopify" ]
Normalizing images in OpenCV
38,025,838
<p>I wrote the following code to work normalize an image using NORM_L1 in OpenCV. But the output image was just black.How to solve this ?</p> <pre><code>import cv2 import numpy as np import Image img = cv2.imread('img7.jpg') gray_image = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) a = np.asarray(gray_image) dst = np.zeros...
4
2016-06-25T06:49:01Z
38,041,997
<p>When you normalize a matrix using NORM_L1, you are dividing every pixel value by the sum of absolute values of all the pixels in the image. As a result, all pixel values become much less than 1 and you get a black image. Try NORM_MINMAX instead of NORM_L1.</p>
4
2016-06-26T18:49:52Z
[ "python", "opencv" ]
Normalizing images in OpenCV
38,025,838
<p>I wrote the following code to work normalize an image using NORM_L1 in OpenCV. But the output image was just black.How to solve this ?</p> <pre><code>import cv2 import numpy as np import Image img = cv2.imread('img7.jpg') gray_image = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) a = np.asarray(gray_image) dst = np.zeros...
4
2016-06-25T06:49:01Z
39,037,135
<p>If you want to change the range to [0, 1], make sure the output data type is <code>float</code>.</p> <pre><code>image = cv2.imread("lenacolor512.tiff", cv2.IMREAD_COLOR) # uint8 image norm_image = cv2.normalize(image, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F) </code></pre>
3
2016-08-19T10:48:04Z
[ "python", "opencv" ]
How can I use py2neo to store a dictionary as one property value to single property key of a node in neo4j?
38,025,955
<p>I have a node and I want to add one property <code>property_x</code> whose value I want to be <code>{"year1":value, "year2":value}</code>. Making more than one node for each year is not needed as I need these values in my processing together.</p>
0
2016-06-25T07:06:08Z
38,026,494
<p>Neo4j only supports certain kinds of properties (<a href="http://www.neo4j.com/docs/rest-docs/current/#rest-api-property-values" rel="nofollow">docs</a>):</p> <blockquote> <p>...there are restrictions as to what types of values can be used as property values. Allowed value types are as follows:</p> <ul> ...
1
2016-06-25T08:25:12Z
[ "python", "dictionary", "neo4j", "py2neo" ]
Cython: Segmentation Fault Using API Embedding Cython to C
38,026,198
<p>I'm trying to embed Cython code into C following <a href="https://github.com/hnakamur/exposing_cython_code_to_c/tree/master/mechanism2" rel="nofollow">O'reilly Cython book</a> chapter 8. I found this paragraph on Cython's <a href="http://docs.cython.org/src/userguide/external_C_code.html#c-api-declarations" rel="nof...
3
2016-06-25T07:42:51Z
38,028,619
<p>In that Makefile there is </p> <pre><code>transcendentals.so: setup.py transcendentals.pyx python setup.py build_ext --inplace </code></pre> <p>Unless <code>python</code> refers to <code>/Users/spacegoing/anaconda/bin/python3</code> it should be replaced since the module may be compiled for wrong python versio...
1
2016-06-25T12:38:42Z
[ "python", "cython" ]
Exec and variable scope
38,026,279
<p>Python 3.5.1</p> <p>Could you have a look at the code and the picture.</p> <p>This is some Django code, but the question relates to Python.</p> <p>Well, I get the error: </p> <pre><code>Exception Value: name 'objects' is not defined Exception Location: /home/michael/workspace/pharchive/pharchive/general/temp...
0
2016-06-25T07:53:52Z
38,026,532
<p>A much easier approach than building and <code>exec</code>uting the code as a string would be to access the attribute using the built-in <a href="https://docs.python.org/2/library/functions.html#getattr" rel="nofollow"><code>getattr</code></a> function. This makes it clearer what's going on and side-steps your curre...
0
2016-06-25T08:28:50Z
[ "python" ]
indexError:list index out of range
38,026,359
<p>The program is for quick sort with duplicate keys.The code runs perfectly once or twice and then gives the IndexError next time eventhough the list is not empty.When I print the indices they lie within range.Is it a problem with my computer specifically?</p> <p>EDIT-added the traceback</p> <pre><code>import random...
-1
2016-06-25T08:05:03Z
38,030,669
<p>The problem is in row 11:</p> <pre><code> while(n[i]&lt;=n[lt] and i&lt;=gt): </code></pre> <p>you need to change it to:</p> <pre><code> while(i&lt;=gt and n[i]&lt;=n[lt]): </code></pre> <p>because python first checks first condition (in this case it is i&lt;=gt) and if it is true than he checks the second...
0
2016-06-25T16:43:08Z
[ "python" ]
indexError:list index out of range
38,026,359
<p>The program is for quick sort with duplicate keys.The code runs perfectly once or twice and then gives the IndexError next time eventhough the list is not empty.When I print the indices they lie within range.Is it a problem with my computer specifically?</p> <p>EDIT-added the traceback</p> <pre><code>import random...
-1
2016-06-25T08:05:03Z
38,033,229
<p>Your code was sometimes getting out of bounds indexes because of the order you were checking your conditions in your inner <code>while</code> loop.</p> <p>Often an easy best way to debug issues like this is to add <code>try</code> and <code>except</code> blocks to the code, with the <code>except</code> block printi...
0
2016-06-25T21:44:17Z
[ "python" ]
flask required attribute cause TemplateSyntaxError: invalid syntax for function call expression
38,026,371
<p>I tried to combine flask-wtf with required attribute below, but I reviced TemplateSyntaxError: invalid syntax for function call expression</p> <pre><code>{{ form.StudentName(class="Tj-inp1 fl",placeholder='学生姓名:',required)}} </code></pre> <p>Then I run the program, I reviced TemplateSyntaxError: invalid sy...
0
2016-06-25T08:06:47Z
38,026,559
<p>You get a <code>TemplateSyntaxError</code> because you have a syntax error in your code. Even in jinja2 (which is what you are probably using) a positional argument can't follow keyword arguments.</p> <p>You have two keyword arguments: <code>class</code> and <code>placeholder</code>. After that you are passing <cod...
0
2016-06-25T08:32:46Z
[ "python", "flask", "flask-wtforms" ]
Selenium WebDriver closes after everything is done
38,026,399
<p>So I'm trying to make a Messenger bot using Selenium and Python. I don't have any code errors my code works just fine, the problem is that after it's done it just kills the WebDriver. Here's my code: </p> <p><pre>from selenium import webdriver</p> <p>login_email = "" #Your facebook email login_password = "" #Your ...
0
2016-06-25T08:10:47Z
38,026,700
<p>I have not tried it but I think here is what you could do and I believe this would only work with firefox but that should not be a problem for you as you are not testing any specific browser</p> <ul> <li>Launch Browser outside of your script, so when you your scripts exit your browser remain up. Alternatively you ...
1
2016-06-25T08:53:05Z
[ "python", "selenium" ]
Selenium WebDriver closes after everything is done
38,026,399
<p>So I'm trying to make a Messenger bot using Selenium and Python. I don't have any code errors my code works just fine, the problem is that after it's done it just kills the WebDriver. Here's my code: </p> <p><pre>from selenium import webdriver</p> <p>login_email = "" #Your facebook email login_password = "" #Your ...
0
2016-06-25T08:10:47Z
38,085,207
<p>Put a breakpoint on the last line of code you want executed before it stops and then run it in debug mode (this will vary depending on your IDE). Once it pauses, you can kill the run and take over the browser or whatever else you want to do.</p>
0
2016-06-28T19:56:17Z
[ "python", "selenium" ]
Python 3.4 compatibility with numpy, scipy, and matplotlib
38,026,670
<p>I am very new to Python and am wondering what versions of numpy/scipy/matplotlib are compatible with different versions of Python--or to what degree it matters that they match up. </p> <p>Right now I am using Python 3.4.3, numpy 1.8.2, scipy 0.13.3 and matplotlib 1.3.1. I saw on the <a href="https://www.scipy.org/s...
2
2016-06-25T08:48:04Z
38,026,871
<p>I would recommend you to take a closer look at the <a href="https://www.continuum.io/why-anaconda" rel="nofollow">Anaconda</a> installation.</p> <p>You will install all needed packages in one step and beside that all the packages will be mutually compatible and <strong>tested</strong>. </p> <p>If you need packages...
2
2016-06-25T09:17:00Z
[ "python", "numpy", "matplotlib", "scipy" ]
Python 3.4 compatibility with numpy, scipy, and matplotlib
38,026,670
<p>I am very new to Python and am wondering what versions of numpy/scipy/matplotlib are compatible with different versions of Python--or to what degree it matters that they match up. </p> <p>Right now I am using Python 3.4.3, numpy 1.8.2, scipy 0.13.3 and matplotlib 1.3.1. I saw on the <a href="https://www.scipy.org/s...
2
2016-06-25T08:48:04Z
38,027,890
<p>Current versions, numpy 0.11.0 and scipy 0.17.1, should be perfectly fine with python 3.4 and 3.5.</p> <p>To a first approximation, any non-ancient version of numpy or scipy is going to be OK with python 3.4.</p> <p>It's good idea anyway to run self-tests after installation: <code>&gt;&gt;&gt; from numpy import t...
1
2016-06-25T11:15:44Z
[ "python", "numpy", "matplotlib", "scipy" ]
Python 3.4 compatibility with numpy, scipy, and matplotlib
38,026,670
<p>I am very new to Python and am wondering what versions of numpy/scipy/matplotlib are compatible with different versions of Python--or to what degree it matters that they match up. </p> <p>Right now I am using Python 3.4.3, numpy 1.8.2, scipy 0.13.3 and matplotlib 1.3.1. I saw on the <a href="https://www.scipy.org/s...
2
2016-06-25T08:48:04Z
38,030,930
<p>From the very same page:</p> <blockquote> <p>NumPy and SciPy support the Python 2.x series, (versions 2.6 and 2.7), as well as <strong>Python 3.2</strong> and newer</p> </blockquote> <p>Python versions in the 3.x line should all be backwards compatible anyway.</p>
1
2016-06-25T17:11:07Z
[ "python", "numpy", "matplotlib", "scipy" ]
Python selenium masked field
38,026,681
<p>I'm tying to fill masked phone field <code>+7(___)___-__-__</code> with python and selenium</p> <pre><code>&lt;input type="tel" name="PHONE" id="phone" class="js-phone-masked"&gt; </code></pre> <p>My code: </p> <pre><code>driver.find_element_by_id('phone').click() time.sleep(2) driver.find_element_by_id('phone')....
0
2016-06-25T08:50:08Z
38,029,646
<p>I would guess that either there are multiple elements for that phone field, or the underlying javascript is somehow preventing the entire string from writing. You could try sending each digit individually perhaps:</p> <pre><code>driver.find_element_by_id('phone').click() for digit in '9353232222': driver.find_...
2
2016-06-25T14:43:27Z
[ "javascript", "python", "selenium", "selenium-webdriver", "maskedtextbox" ]
python program that prints number of characters, words and lines in a file
38,026,833
<p>I am new to programming in Python and wanted help writing a python program that prints number of characters, words and lines in a file. For example say the name of the file is time.txt</p>
-5
2016-06-25T09:12:29Z
38,026,900
<p>You have to learn about work with files in python.</p> <p><a href="https://docs.python.org/2/tutorial/inputoutput.html" rel="nofollow">https://docs.python.org/2/tutorial/inputoutput.html</a> - python v. 2.*</p> <p><a href="https://docs.python.org/3/tutorial/inputoutput.html" rel="nofollow">https://docs.python.org/...
0
2016-06-25T09:20:58Z
[ "python" ]
facing ImportError: No module named discriminant_analysis
38,026,834
<p>I am using <code>Ubuntu 14.04 , python=2.7 , numpy=1.10.1 , scikit-learn=0.17.1 , scipy=0.17.1</code> but I have Import Error both in <code>IDLE</code> and in <code>Spyder</code> (conda=4.1.3 , conda-env=2.5.0a0) in the import part of the code:</p> <pre><code>import numpy as np from sklearn.cross_validation import ...
1
2016-06-25T09:12:33Z
39,237,951
<p>I had this same issue. It turned out that there were two different installations of <code>scikit</code>:</p> <ul> <li>one in <code>/usr/lib/python2.7/dist-packages/sklearn/</code> (which <strong>does not have</strong> the <code>discriminant_analysis</code> module); and </li> <li>the other in <code>/usr/local/lib/py...
0
2016-08-30T22:20:20Z
[ "python", "numpy", "scikit-learn", "classification" ]
cross validation and text categorization
38,026,842
<p>I have the same question which has been asked in <a href="http://stackoverflow.com/questions/22672436/sklearn-vectorizing-in-cross-validation-for-text-classification">here</a>: </p> <p>I have a question about using cross validation in text classification in <code>sklearn</code>. It is problematic to vectorize all d...
0
2016-06-25T09:13:33Z
38,029,661
<p>I may be missing the meaning of your question and am unfamiliar with Weka, but you can pass the vocabulary as a dictionary into the vectorizer you use in sklearn. Here is an example that will skip the word 'second' in the test set, using only features from the train set. </p> <pre><code>from sklearn.feature_extract...
0
2016-06-25T14:45:27Z
[ "python", "scikit-learn", "cross-validation" ]
cross validation and text categorization
38,026,842
<p>I have the same question which has been asked in <a href="http://stackoverflow.com/questions/22672436/sklearn-vectorizing-in-cross-validation-for-text-classification">here</a>: </p> <p>I have a question about using cross validation in text classification in <code>sklearn</code>. It is problematic to vectorize all d...
0
2016-06-25T09:13:33Z
38,040,467
<p>I think using the cross-validation iterator as an outer loop is a good idea and a starting point that would make your steps clear and readable:</p> <pre><code>from sklearn.cross_validation import KFold X = np.array(["Science today", "Data science", "Titanic", "Batman"]) #raw text y = np.array([1, 1, 2, 2]) #categor...
0
2016-06-26T16:10:57Z
[ "python", "scikit-learn", "cross-validation" ]
Dynamic initialisation of DB in constructor
38,026,961
<p>I am using motor with tornado. I have the following class:</p> <pre><code>class N(): def __init__(self,collectionName host='localhost', port=27017): self.con=motor.MotorClient(host,port) self.xDb=self.con.XDb setattr(self,collectionName,self.xDb[collectionName]) </code></pre> <p>This is act...
1
2016-06-25T09:28:08Z
38,029,181
<p>Set another variable:</p> <pre><code>class N(): def __init__(self, collectionName, host='localhost', port=27017): # ... your existing code ... self.collectionName = collectionName @tornado.gen.coroutine def dropDB(self): yield self.xDb.drop_collection(self.collectionName) </code></p...
2
2016-06-25T13:45:23Z
[ "python", "tornado-motor" ]
How do I calculate a pandas column with multiple columns as arguments?
38,026,984
<p>I was using a wind speed calculation function from lon and lat components:</p> <pre><code>def wind_speed(u, v): return np.sqrt(u ** 2 + v ** 2) </code></pre> <p>and calling it to calculate a new pandas column from two existing ones:</p> <pre><code>df['wspeed'] = map(wind_speed, df['lonwind'], df['latwind']) <...
1
2016-06-25T09:31:02Z
38,027,005
<p>I would try to stick to existing numpy/scipy functions as they are extremely fast and optimized (<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.hypot.html" rel="nofollow">numpy.hypot</a>):</p> <pre><code>df['wspeed'] = np.hypot(df.latwind, df.lonwind) </code></pre> <p><strong>Timing:</strong> a...
1
2016-06-25T09:33:24Z
[ "python", "pandas" ]
How do I calculate a pandas column with multiple columns as arguments?
38,026,984
<p>I was using a wind speed calculation function from lon and lat components:</p> <pre><code>def wind_speed(u, v): return np.sqrt(u ** 2 + v ** 2) </code></pre> <p>and calling it to calculate a new pandas column from two existing ones:</p> <pre><code>df['wspeed'] = map(wind_speed, df['lonwind'], df['latwind']) <...
1
2016-06-25T09:31:02Z
38,027,022
<p>If want to use <a href="https://docs.python.org/3/library/functions.html#map" rel="nofollow"><code>map</code></a>, add <code>list</code>:</p> <pre><code>df = pd.DataFrame({'lonwind':[1,2,3], 'latwind':[4,5,6]}) print (df) latwind lonwind 0 4 1 1 5 2 2 6 ...
1
2016-06-25T09:34:47Z
[ "python", "pandas" ]
whats wrong with this scrapy spider? scrapes only last url
38,027,195
<p>In method <code>parse()</code> spider crawls 4 urls and then sends to method <code>parse_dir_contents()</code> to scrape some data but only 4th url is being scraped I don't understand why it is not scraping other 3 urls? </p> <pre><code>import scrapy from v_one.items import VOneItem import json class linkedin(scra...
0
2016-06-25T09:56:30Z
38,027,681
<p>By inspecting the pages I think that there is no need of the <code>for</code> loop in the <code>parse_dir_contents</code> function. Make the function like this:</p> <pre><code>def parse_dir_contents(self, response): item = VOneItem() item['name'] = response.xpath('//*[@id="name"]/text()').extract() ...
0
2016-06-25T10:53:32Z
[ "python", "web-scraping", "scrapy", "web-crawler" ]
JSON to data frame after some calculations python
38,027,220
<p>I have a JSON file</p> <pre><code> { "b0:47:bf:af:c1:42": { "No. of visits": 10, "cities": { "Mumbai": {"count": 5,"last_visited": "5/22/2016"}, "Kolkata": {"count": 2,"last_visited": "5/22/2016"}, "Amritsar":{"count": 3,"last_visited": "5/22/2016"} } ...
0
2016-06-25T09:59:29Z
38,027,572
<pre><code>import json d = { "b0:47:bf:af:c1:42": { "No. of visits": 10, "cities": { "Mumbai": {"count": 5,"last_visited": "5/22/2016"}, "Kolkata": {"count": 2,"last_visited": "5/22/2016"}, "Amritsar":{"count": 3,"last_visited": "5/22/2016"} } }, "k...
1
2016-06-25T10:43:03Z
[ "python", "json", "python-2.7" ]
JSON to data frame after some calculations python
38,027,220
<p>I have a JSON file</p> <pre><code> { "b0:47:bf:af:c1:42": { "No. of visits": 10, "cities": { "Mumbai": {"count": 5,"last_visited": "5/22/2016"}, "Kolkata": {"count": 2,"last_visited": "5/22/2016"}, "Amritsar":{"count": 3,"last_visited": "5/22/2016"} } ...
0
2016-06-25T09:59:29Z
38,068,600
<p>The solution above should work well. But if you need to deal with large volume dataset, it may take a lot of time in this linear format of execution.</p> <p>Provided you are using Python, you could go for concurrent execution by dividing your dataset into various small chunks and applying the same solution concurre...
1
2016-06-28T06:29:03Z
[ "python", "json", "python-2.7" ]
How to giving a specific word to word2vec model in tensorflow
38,027,289
<p>How to giving a specific word to test a trained word2vec model?</p> <p>For example </p> <p>Input "dog", and return nearst word like "cat", "bird" etc..</p> <p>Thanks!</p> <p><a href="https://github.com/tensorflow/tensorflow/blob/r0.9/tensorflow/examples/tutorials/word2vec/word2vec_basic.py" rel="nofollow">word2v...
0
2016-06-25T10:07:24Z
38,028,004
<p>That tensor flow example already has a function to compute similarities and show nearest words. The easiest way is to use that function. </p> <p>In step 4 after defining valid_examples, you can give your own words.</p> <pre><code>valid_examples = np.random.choice(valid_window, valid_size, replace=False) num_sample...
1
2016-06-25T11:30:00Z
[ "python", "tensorflow", "word2vec" ]
Adding up specific probabilities from a Python's Pandas DataFrame based on a 4 element list index
38,027,378
<p>I have a pandas DataFrame that looks like this:</p> <pre><code> Pr(X,O) (H, H, H, H) 0.042743 (H, H, H, C) 0.003664 (H, H, C, H) 0.073274 (H, H, C, C) 0.021982 (H, C, H, H) 0.005234 (H, C, H, C) 0.000449 (H, C, C, H) 0.031403 (H, C, C, C) 0.009421 (C, H, H, H) 0.113982 (C, H, H, C) 0.009770 ...
1
2016-06-25T10:20:00Z
38,027,535
<p>You can first create new columns from <code>tuples</code>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow"><code>melt</code></a> and last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code...
1
2016-06-25T10:38:55Z
[ "python", "pandas" ]
Adding up specific probabilities from a Python's Pandas DataFrame based on a 4 element list index
38,027,378
<p>I have a pandas DataFrame that looks like this:</p> <pre><code> Pr(X,O) (H, H, H, H) 0.042743 (H, H, H, C) 0.003664 (H, H, C, H) 0.073274 (H, H, C, C) 0.021982 (H, C, H, H) 0.005234 (H, C, H, C) 0.000449 (H, C, C, H) 0.031403 (H, C, C, C) 0.009421 (C, H, H, H) 0.113982 (C, H, H, C) 0.009770 ...
1
2016-06-25T10:20:00Z
38,027,822
<p>I tried to do it with taking the result of <code>itertools.product</code> as a MultiIndex.</p> <pre><code>index = pd.MultiIndex.from_tuples(itertools.product(('H', 'C'), repeat=4)) </code></pre> <p>We then groupby by the different levels, and concatenate them.</p> <pre><code>pd.concat( [df.groupby(level=[i]).sum(...
5
2016-06-25T11:09:13Z
[ "python", "pandas" ]
Permute rows in "slices" of 3d array to match each other
38,027,432
<p>I have a series of 2d arrays where the rows are points in some space. Many similar points occur across all arrays but in different row order. <strong>I want to sort the rows so they have the most similar order.</strong> Also the points are too different for clustering with K-means or DBSCAN. The problem can also be ...
4
2016-06-25T10:27:02Z
38,031,213
<p>Sorry I should have looked at your code sample; that was very informative.</p> <p>Seems like this here gives an out-of-the-box solution to your problem:</p> <p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linear_sum_assignment.html#scipy.optimize.linear_sum_assignment" rel="nofollow"...
1
2016-06-25T17:39:37Z
[ "python", "arrays", "sorting", "numpy", "cluster-analysis" ]
python ctype _pack_ vs g++ #pragma pack
38,027,473
<p>I intent to serialize a struct like this to a "compacted" binary:</p> <pre><code>#include &lt;cstdio&gt; #include &lt;iostream&gt; using namespace std; #define print(x) cout &lt;&lt; x &lt;&lt; endl #pragma pack(1) class Foo { uint32_t a: 1; uint32_t b: 2; uint32_t c: 5; uint64_t d; }; int main...
0
2016-06-25T10:32:33Z
38,121,191
<p>If you want the sizeof of <code>RawMessage</code>to be 9, you need to use <code>c_uint8</code>for the bit-fields and <code>c_ulonglong</code> for the unsigned 64 bit field (you used <code>c_ulong</code> which is only 4 bytes / 32-bit).</p> <p>python 3 code, but the idea should be transposable to python 2.7 :</p> <...
0
2016-06-30T11:00:27Z
[ "python", "ctypes" ]
Move item in one list to another for a card game Python
38,027,527
<p>Ok so I'm trying to make a poker game in Python.. and I want to move the used cards from the list to another list where I will store the used cards. I'm using this code :</p> <pre><code>deck = ['AS', 'KS', 'QS', 'JS', '10S', '9S', '8S', '7S', '6S', '5S', '4S', '3S', '2S',\ 'AD', 'KD', 'QD', 'JD', '10D', '9...
1
2016-06-25T10:37:53Z
38,027,564
<p>You just need to append the drawn cards to your <code>used</code> list, and not back into <code>deck</code>:</p> <pre><code>used.append(drawn_card) #instead of deck.append(..) </code></pre>
1
2016-06-25T10:42:12Z
[ "python", "poker" ]
Move item in one list to another for a card game Python
38,027,527
<p>Ok so I'm trying to make a poker game in Python.. and I want to move the used cards from the list to another list where I will store the used cards. I'm using this code :</p> <pre><code>deck = ['AS', 'KS', 'QS', 'JS', '10S', '9S', '8S', '7S', '6S', '5S', '4S', '3S', '2S',\ 'AD', 'KD', 'QD', 'JD', '10D', '9...
1
2016-06-25T10:37:53Z
38,027,624
<pre><code>while (a &lt; 2): drawn_card = random.choice(deck) used.append(drawn_card) deck = [f for f in deck if f not in used] p1.append(drawn_card) a+=1 </code></pre> <p><strong>used.append(drawn_card)</strong></p>
1
2016-06-25T10:48:03Z
[ "python", "poker" ]
Move item in one list to another for a card game Python
38,027,527
<p>Ok so I'm trying to make a poker game in Python.. and I want to move the used cards from the list to another list where I will store the used cards. I'm using this code :</p> <pre><code>deck = ['AS', 'KS', 'QS', 'JS', '10S', '9S', '8S', '7S', '6S', '5S', '4S', '3S', '2S',\ 'AD', 'KD', 'QD', 'JD', '10D', '9...
1
2016-06-25T10:37:53Z
38,027,915
<p>The simple fix is to use <code>used.append(drawn_card)</code> as others have suggested. A better way is to randomly shuffle your deck and then slice the required number of cards from it:</p> <pre><code>CARDS_PER_HAND = 2 random.shuffle(deck) hand = deck[:CARDS_PER_HAND] </code></pre> <p>However, you are probably...
0
2016-06-25T11:18:42Z
[ "python", "poker" ]
Find number in a variable python
38,027,575
<p>I am trying to make a Twitch plays Roller Coaster Tycoon 2 (for fun) with help from <a href="http://www.wituz.com/tutorial-make-your-own-twitch-plays-stream.html" rel="nofollow">this site</a> and a slightly modified version of <a href="http://stackoverflow.com/questions/1181464/controlling-mouse-with-python">this</a...
0
2016-06-25T10:43:25Z
38,027,618
<p>You can use a regular expression:</p> <pre><code>import re regex = re.compile('.* (\d+) (\d+') if "!click" in msg: clickMSG = msg xpos, ypos = map(int, regex.match(msg).groups()) </code></pre> <p><code>.</code> means any character, and <code>*</code> means zero or more times. Therefore, <code>.*</code> ...
0
2016-06-25T10:47:21Z
[ "python", "python-2.7", "variables", "click" ]
Find number in a variable python
38,027,575
<p>I am trying to make a Twitch plays Roller Coaster Tycoon 2 (for fun) with help from <a href="http://www.wituz.com/tutorial-make-your-own-twitch-plays-stream.html" rel="nofollow">this site</a> and a slightly modified version of <a href="http://stackoverflow.com/questions/1181464/controlling-mouse-with-python">this</a...
0
2016-06-25T10:43:25Z
38,030,375
<p>You can do it without re (regular expression), here is my code:</p> <pre><code>msg = "!click 10 10" clickMSG = "" if "!click" in msg: clickMSG = msg.strip("!click ") # removes "!click" from msg xpos, ypos = clickMSG.split() xpos = int(xpos) # ypos = int(ypos) # converts string (e.g. "10") t...
0
2016-06-25T16:09:24Z
[ "python", "python-2.7", "variables", "click" ]
Quick way to test if all dictionary items are 'True'
38,027,651
<p>Hello in a program I am making I require the user to enter their shipping details, and once they have done this they can continue to confirm their order. However I do not want the user to prematurely skip past the shipping details form without filling out all of the fields. Here is the dictionary for storing their d...
1
2016-06-25T10:50:43Z
38,027,728
<pre><code>&gt;&gt;&gt; user_details.values() [None, None, None, None, None] &gt;&gt;&gt; if None in user_details.values(): ... print "none in there" ... none in there </code></pre>
4
2016-06-25T10:58:32Z
[ "python", "python-3.x", "dictionary" ]
Quick way to test if all dictionary items are 'True'
38,027,651
<p>Hello in a program I am making I require the user to enter their shipping details, and once they have done this they can continue to confirm their order. However I do not want the user to prematurely skip past the shipping details form without filling out all of the fields. Here is the dictionary for storing their d...
1
2016-06-25T10:50:43Z
38,027,775
<pre><code>all(user_details.values()) </code></pre> <p>This will return true if all the values are not none, otherwise false</p>
2
2016-06-25T11:04:07Z
[ "python", "python-3.x", "dictionary" ]
how to read a text file before being created by another function in python
38,027,726
<p>In my python code, I call a function written in FreeFem++ and then I save the output from FreeFem++ code in a text file and I want to read this in python.</p> <pre><code>def f(x): os.system("Here the FreeFem++ code will be called and the result will be saved as out.txt") myfile=open("out.txt") return my...
1
2016-06-25T10:58:21Z
38,027,824
<p>Use <a href="https://docs.python.org/3/library/subprocess.html#subprocess.run" rel="nofollow"><code>subprocess.run()</code></a> to call your freefem++ program, and make sure that your call actually generates the file before it exists. You could check that by adding a breakpoint just before the <code>open</code>.</p>...
4
2016-06-25T11:09:28Z
[ "python", "function", "text", "readfile" ]
Is there a way to use regular expressions to match two numbers in any order while exclude other numbers?
38,027,747
<p>I am trying to match numbers that contains the digits 1 and 2 in any order and but that doesn't contain digits 0,3 or 4.</p> <p>My results should include:</p> <p>192,129,291,127,261</p> <pre><code>import re exampleLine = 'prices xom 91.43.91.44.19.192,129,291,201,124,127,261' regEx = re.findall(r'\d[1+=2][^034]...
0
2016-06-25T11:01:06Z
38,027,939
<p>You can do it like this:</p> <pre><code>\b[5-9]*(?:1[15-9]*2|2[25-9]*1)[125-9]*\b </code></pre> <p>You need first to use word-boundaries to avoid numbers to be truncated.</p> <p>Then you can use character classes to be sure that numbers use only allowed digits.</p> <p>To finish, you must describe the two possibl...
1
2016-06-25T11:22:22Z
[ "python", "regex" ]
Is there a way to use regular expressions to match two numbers in any order while exclude other numbers?
38,027,747
<p>I am trying to match numbers that contains the digits 1 and 2 in any order and but that doesn't contain digits 0,3 or 4.</p> <p>My results should include:</p> <p>192,129,291,127,261</p> <pre><code>import re exampleLine = 'prices xom 91.43.91.44.19.192,129,291,201,124,127,261' regEx = re.findall(r'\d[1+=2][^034]...
0
2016-06-25T11:01:06Z
38,033,051
<p>@Robert Jones: This could meet your needs:</p> <pre><code>\b[5-9]*(?:1[15-9]?2|2[25-9]?1)[5-9]*\b </code></pre> <p>@Casimir et Hippolyte: Excellently devised!</p>
0
2016-06-25T21:17:33Z
[ "python", "regex" ]
Is there a way to use regular expressions to match two numbers in any order while exclude other numbers?
38,027,747
<p>I am trying to match numbers that contains the digits 1 and 2 in any order and but that doesn't contain digits 0,3 or 4.</p> <p>My results should include:</p> <p>192,129,291,127,261</p> <pre><code>import re exampleLine = 'prices xom 91.43.91.44.19.192,129,291,201,124,127,261' regEx = re.findall(r'\d[1+=2][^034]...
0
2016-06-25T11:01:06Z
38,075,735
<p>@Robert Jones: Trying to solve your further request...</p> <p><strong>1.</strong></p> <blockquote> <p>3 digit numbers range from 5-9 but, exclude duplicate numbers</p> </blockquote> <pre><code>\b([5-9])((?!\1)(?:[5-9]))((?!\1|\2)(?:[5-9]))\b </code></pre> <p><a href="https://regex101.com/r/bK1vY3/1" rel="nofol...
0
2016-06-28T12:03:35Z
[ "python", "regex" ]
Increment value of integer in Python dictionary
38,027,965
<p>So I write an app that counts amount of yellow cards in football matches through all the games of the tournament. So let's say I count all Brazil's goals and I need to increment the amount of yellow cards with each game I go through in a loop. So I have this dictionary cards_per_team_dictionary that looks like this:...
1
2016-06-25T11:25:29Z
38,028,063
<p>You have created a <em>set</em> not a <em>dict</em>:</p> <pre><code>In [4]: d = {"Brazil",0} In [5]: d["Brazil"] += 3 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-5-8db3ec29e78a&gt; in &lt;m...
5
2016-06-25T11:36:46Z
[ "python", "dictionary" ]
pandas read_hdf with large set of conditions
38,027,984
<p>I trying to read a HDF file of 64 GB (compressed with blosc) with the pandas library. The Dataframe contais 3 columns and 11410996915 rows. I am trying to select concrete rows by index with the method pandas.read_hdf and the argument where. The problem is that sometimes I need to get thousands of rows, so in my whe...
3
2016-06-25T11:27:28Z
38,028,344
<p>you can use the following technique:</p> <pre><code>pd.read_hdf(filename, 'key', where='index = vals') </code></pre> <p>where <code>vals</code> is <code>pd.Series</code> or a <code>Python list</code> variable</p> <p>You can also use columns belonging to other DF for filtering:</p> <pre><code>In [201]: another_df...
1
2016-06-25T12:05:32Z
[ "python", "pandas", "dataframe", "pytables" ]
500 internal server error when deploy django with gunicorn and nginx
38,028,099
<p>I created a simple django app for user authentication, then I want to deploy on nginx with gunicorn. I create my custom user model with 2 fields: username, password.I have tested using:</p> <pre><code>python manange.py runserver 0.0.0.0:8000 </code></pre> <p>It runs fine! But when I try to deploy on nginx with gun...
2
2016-06-25T11:39:28Z
38,928,598
<p>After spending whole day of debugging, it turns out that my authentication app's name (which is auth) is conflict with django default auth. Somehow, when I serve my app through gunicorn, it used django default auth app instead of mine. If you look at the log carefully, it's querying the default User model of django....
0
2016-08-13T02:22:10Z
[ "python", "django", "nginx", "gunicorn" ]
How do I get rid of the ' the program is still running are you sure you want to kill it' warning on python?
38,028,151
<pre><code>print ('Password Request Initiative') password = 'abcd' user_input = input('Please Enter Password: ') if user_input != password: print("Haha. Nope") quit() elif user_input == password: print ("User is now logged in...") enter code here </code></pre> <p>that's the code, but when I...
0
2016-06-25T11:46:23Z
38,060,392
<p>To avoid the message when running from IDLE, do not use <code>quit()</code> or <code>exit()</code> in a program. They are not part of the language and are not intended for this use. They are (usually) added by the site package for <a href="https://docs.python.org/3/library/constants.html#quit" rel="nofollow">inter...
0
2016-06-27T18:03:10Z
[ "python", "python-idle" ]
Does this create a TCP or UDP connection for the server?
38,028,357
<pre><code>from socket import * host=gethostname() port=7776 s=socket() s.bind((host, port)) </code></pre> <p>Is it UDP or TCP-IP? How do I write this as TCP-IP if it's UDP and vice versa?</p>
0
2016-06-25T12:06:26Z
38,028,440
<p>This will create a TCP socket because the type argument of <code>socket.socket(...)</code> defaults to <code>SOCK_STREAM</code>. For UDP you would need to use <code>SOCK_DGRAM</code> as type instead. See <a href="https://docs.python.org/3/library/socket.html" rel="nofollow">the extensive documentation</a> for more d...
2
2016-06-25T12:16:37Z
[ "python", "sockets" ]
How does this basic Python code based on booleans work?
38,028,361
<pre><code>x = False if x: print 'x was True!' else: print 'I will be printed in any case where x is not true' </code></pre> <p>In the first line of the code, we assign the value of x = False.</p> <p>I want to understand what does the line 'if x:' means. When x has a value of False, doesn't it imply that ...
-5
2016-06-25T12:07:08Z
38,028,459
<p>else block will execute only if the if condition is false. So in this code on giving False here it will jumps to else block. </p>
0
2016-06-25T12:18:40Z
[ "python", "boolean" ]
How does this basic Python code based on booleans work?
38,028,361
<pre><code>x = False if x: print 'x was True!' else: print 'I will be printed in any case where x is not true' </code></pre> <p>In the first line of the code, we assign the value of x = False.</p> <p>I want to understand what does the line 'if x:' means. When x has a value of False, doesn't it imply that ...
-5
2016-06-25T12:07:08Z
38,028,465
<p>The syntax of an if...else statement is :</p> <pre><code>if boolean_expression : # statement(s) will execute if the boolean expression is true else # statement(s) will execute if the boolean expression is false </code></pre> <p>If the Boolean expression evaluates to True, then the if block will be executed...
0
2016-06-25T12:19:08Z
[ "python", "boolean" ]
How does this basic Python code based on booleans work?
38,028,361
<pre><code>x = False if x: print 'x was True!' else: print 'I will be printed in any case where x is not true' </code></pre> <p>In the first line of the code, we assign the value of x = False.</p> <p>I want to understand what does the line 'if x:' means. When x has a value of False, doesn't it imply that ...
-5
2016-06-25T12:07:08Z
38,028,501
<p>Python does't understand English. It has <strong>no idea</strong> what the stuff in quotes after <code>print</code> actually <em>means</em>. So if execution gets to the line <code>print 'x was True!'</code> it just blindly prints out that text. But execution <em>won't</em> get to that line. </p> <p>In</p> <pre><co...
2
2016-06-25T12:23:15Z
[ "python", "boolean" ]
Beautifulsoup : Is there a difference between .find() and .select() - python 3.xx
38,028,384
<p>Best</p> <p>I've a simple question : </p> <p>when you use <strong><em>Beautiful Soup</em></strong> to scrape a certain part of a website, you can use <em>data.find() / data.findAll() or data.select()</em></p> <p>Now the question is. Is there a significant difference between the <strong>.find()</strong> and the <s...
2
2016-06-25T12:09:28Z
38,033,910
<p>To summarise the comments:</p> <ul> <li><em>select</em> finds multiple instances and returns a list, <em>find</em> finds the first, so they don't do the same thing. <em>select_one</em> would be the equivalent to <em>find</em>. </li> <li>I almost always use css selectors when chaining tags or using <em>tag.classname...
2
2016-06-25T23:39:42Z
[ "python", "python-3.x", "beautifulsoup" ]
Trigonometric identities with Python and Sympy, tan(A/2) = (sin A )/(1 + cos A)
38,028,416
<p>I'm not sure how to get Sympy to perform / simplify these types of identities? </p> <p>It does things like <code>sin(a + b)</code>, but doesn't seem to do others (like the one in the title)</p>
2
2016-06-25T12:13:00Z
38,029,907
<p>One approach is to try various combinations of simplification functions/methods such as <code>rewrite</code> and <code>simplify</code>. For example, the following gives the result you want:</p> <pre><code>import sympy as sp x = sp.var('x', real = True) f = sp.tan(x/2) sp.re(f.rewrite(sp.exp).simplify().rewrite(s...
2
2016-06-25T15:15:42Z
[ "python", "math", "trigonometry", "sympy", "symbolic-math" ]
converting pdf to html page wise using python
38,028,426
<p>I have this </p> <pre><code>for root, dirnames, filenames in os.walk('FilePath'): for filename in fnmatch.filter(filenames, 'page-*.pdf'): # matches.append(os.path.join(root, filename)) subprocess.call('pdf2txt.py &gt; myoutput.html', shell = True) </code></pre> <p>I need to write subprocess for ever...
0
2016-06-25T12:15:03Z
38,029,971
<p>Consider using <code>glob</code> with <code>os</code> module to capture both the <em>.pdf</em> pattern and full absolute paths of input .pdf and output .html files:</p> <pre><code>import os import glob # CURRENT DIRECTORY OF SCRIPT cd = os.path.dirname(os.path.abspath(__file__)) for pdf in glob.glob(cd+'/*.pdf'...
0
2016-06-25T15:23:02Z
[ "python", "html", "pdf", "subprocess" ]
How do I read a multi-line list from a file in Python?
38,028,428
<p>I have a file which has lists spanned across multiple lines - with the length of the lists as constant. However, in each line the number of elements can varied. How do I read this file in Python to read each list as a whole? </p> <p>Edit: Would prefer a non-regex solution.</p> <p>The file which looks something lik...
6
2016-06-25T12:15:07Z
38,028,654
<pre><code>import re p=re.compile(r'\[.*\]', re.S) num=re.compile(r'\S+') f=open("lst", "r") s=f.read() f.close() l=p.findall(s) lst=[] for i in l: tmp=[] num_list=num.findall(i) del num_list[0] for n in num_list: if n!=']': tmp.append(n) lst.append(tmp) pri...
2
2016-06-25T12:42:45Z
[ "python", "list", "file" ]
How do I read a multi-line list from a file in Python?
38,028,428
<p>I have a file which has lists spanned across multiple lines - with the length of the lists as constant. However, in each line the number of elements can varied. How do I read this file in Python to read each list as a whole? </p> <p>Edit: Would prefer a non-regex solution.</p> <p>The file which looks something lik...
6
2016-06-25T12:15:07Z
38,028,813
<p>I wrote this piece of code as a solution to the question that you are asking for. Please let me know if this works for you. Thanks in advance!</p> <pre><code>f=open('sample.txt','r') y=[] for a in f: b=a.split() for c in b: if c[0]=='[': d=c[1:] elif c[-1]==']': ...
2
2016-06-25T13:03:41Z
[ "python", "list", "file" ]
How do I read a multi-line list from a file in Python?
38,028,428
<p>I have a file which has lists spanned across multiple lines - with the length of the lists as constant. However, in each line the number of elements can varied. How do I read this file in Python to read each list as a whole? </p> <p>Edit: Would prefer a non-regex solution.</p> <p>The file which looks something lik...
6
2016-06-25T12:15:07Z
38,028,878
<p>You don't need a regex, just strip and split, mapping to float if you want floats:</p> <pre><code>def sections(): with open("in.txt") as f: tmp = [] for line in f: data = list(map(float, line.strip(" []\n").split())) if line.rstrip().endswith("]"): yield ...
2
2016-06-25T13:11:20Z
[ "python", "list", "file" ]
How do I read a multi-line list from a file in Python?
38,028,428
<p>I have a file which has lists spanned across multiple lines - with the length of the lists as constant. However, in each line the number of elements can varied. How do I read this file in Python to read each list as a whole? </p> <p>Edit: Would prefer a non-regex solution.</p> <p>The file which looks something lik...
6
2016-06-25T12:15:07Z
38,029,832
<p>Here is a another solution:</p> <pre><code> file = open('database.txt', 'r') text = file.read() file.close() ## long version lists = text.split(']') lists = lists[:-1] # remove last element which is empty (because of split) lists = [i.strip() for i in lists] # ...
2
2016-06-25T15:07:25Z
[ "python", "list", "file" ]
Create dataframe of all rows AFTER varying amount of header data Python Pandas
38,028,468
<p>I have dataframes with a varying amount of header data. I need to remove the header data, (ie. create a new dataframe containing only the data that comes after this header)</p> <p>I have used the following code to find the row where the header data ends.</p> <pre><code>df = xlsx_file.parse('ActualSheet',header= No...
0
2016-06-25T12:19:38Z
38,028,587
<p>IIUC you can do it this way:</p> <pre><code>df = df[df_Header.index.max():] </code></pre> <p>or </p> <pre><code>df = df[~(df[0].isin(value_list) &amp; (df[1].isin(value_list)))] </code></pre> <p>PS you may also want to make use of <code>header</code> and / or <code>skiprows</code> parameters of the <a href="htt...
1
2016-06-25T12:34:37Z
[ "python", "pandas" ]
how to convert wav file to mp3 frame by frame by using ffmpeg in python
38,028,486
<p>i am trying to code something like VOIP in python. i use pyaudio to record voice and send these frames to another computer through socket. but the size of each frame is much more than mp3 frames.<br > so i have decided to covert these frame to mp3 before send them. i think ffmpeg is good choice to convert these fra...
1
2016-06-25T12:21:48Z
38,028,527
<p>You will probably need to buffer small portions of the audio input. Then you can use ffmpeg pipes to pipe in audio. You can get more information in this stackoverflow question: <a href="http://stackoverflow.com/questions/12999674/ffmpeg-which-file-formats-support-stdin-usage">ffmpeg: which file formats support stdin...
1
2016-06-25T12:27:58Z
[ "python", "sockets", "audio", "ffmpeg" ]
sparse BLAS solver used in a shared library doesn't work (returns '-1')
38,028,717
<p>I have tried to program a solver-function in C (with Ubuntu in Code::Blocks). I want to call that solver from a Python script, so I have build it as a shared library and called it with 'ctypes' in Python. At first have tried the example from there <a href="http://www.netlib.org/blas/blast-forum/chapter3.pdf" rel="no...
0
2016-06-25T12:52:12Z
38,030,073
<p>You could read the doc of <code>dussv()</code> in your link, page 121.</p> <p><a href="http://www.netlib.org/blas/blast-forum/chapter3.pdf" rel="nofollow">http://www.netlib.org/blas/blast-forum/chapter3.pdf</a></p> <p><code>dussv()</code> requires your <code>A</code> to be a triangular matrix, which means</p> <bl...
0
2016-06-25T15:35:40Z
[ "python", "c", "sparse-matrix", "solver", "blas" ]
OutOfRangeError: RandomShuffleQueue
38,028,762
<p>Hi I am trying to run a conv. neural network addapted from MINST2 tutorial in tensorflow. I am having the following error, but i am not sure what is going on:</p> <pre><code>W tensorflow/core/framework/op_kernel.cc:909] Invalid argument: Shape mismatch in tuple component 0. Expected [784], got [6272] W tensorflow/c...
2
2016-06-25T12:57:23Z
38,028,949
<p>This looks like an issue with your image.set_shape([784]). The error is saying that it was expecting something of size [784] but it got [6272]. I'm semi-familiar with this tutorial and the images should be 28x28 which would give you a size of 784 but maybe there are 6272 images and your dimensions are confused becau...
0
2016-06-25T13:19:40Z
[ "python", "tensorflow", "conv-neural-network" ]
Python: Returning a function that runs a given function n times
38,028,781
<p>I'm trying to write a function that takes a function as its argument and returns a new function that runs said function a given number of times.</p> <p>For example, if I had a function:</p> <pre><code>def doubleNumber(num): return num * 2 </code></pre> <p>and I did the following:</p> <pre><code>doubleThrice ...
1
2016-06-25T12:59:04Z
38,028,824
<p>If you want to apply a function several times, you probably need a loop that repeats that many times:</p> <pre><code>def repeatFunction(func, n): def inner(inp): for i in range(n): inp = func(inp) return inp return inner </code></pre>
2
2016-06-25T13:05:31Z
[ "python", "function", "closures", "decorator" ]
Rasperry Pi import error: No module named xxxxxx
38,028,861
<p>I'm working on a raspberry-pi project and getting this error:</p> <blockquote> <p>import error: No module named Pubnub</p> </blockquote>
-1
2016-06-25T13:09:10Z
38,290,492
<p>I am guessing that you are new to Python programming,and that you have found a script in a google search result and have copied and pasted it (or similar) on to your Raspberry Pi. </p> <p>The import statement is a mechanism by which your code is able to access code in a different module. In order for this to work,...
0
2016-07-10T09:33:53Z
[ "python", "raspberry-pi" ]
Move item from list to another one for poker card game Python
38,028,932
<p>I'm trying to make poker game in Python. In the while fuction I want to move the used cards in a separate(used cards) list. The problem is sometimes when I print the hand I can get duplicates. Something is wrong with my sorting strategy and I don't know what. Can you help me?</p> <pre><code>import random deck = ['...
1
2016-06-25T13:17:30Z
38,028,953
<p>Well the random choice is not guaranteed to be <strong>unique</strong>, thus when you do:</p> <pre><code>drawn_card = random.choice(deck) .. p1.append(drawn_card) </code></pre> <p>you may end up having duplicates (that explains that you some time see duplicates and some not).</p> <p>Check if <code>drawn_card</cod...
1
2016-06-25T13:20:04Z
[ "python" ]
How to assign sounds to channels in Pygame?
38,028,970
<p>I'm trying to play multiple sounds simultaneously in Pygame. I have a background music and I want a rain sound to play continuously and play ocasional thunder sounds.</p> <p>I have tried the following but my rain sound stops when thunder sound is playing. I have tried using channels but I don't know how to choose w...
0
2016-06-25T13:21:21Z
38,033,438
<p>You can only play one Sound at a time per channel, but you can play multiple channels at once. If you don't name the channels, pygame selects an unused channel to play a Sound; by default, pygame has 8 channels around. You can specify a channel by creating a Channel object. As for looping a sound indefinitely, you c...
1
2016-06-25T22:17:30Z
[ "python", "python-2.7", "audio", "pygame" ]
Script to continuously execute javascript function on website
38,029,072
<p>A friend of mine has recently posted his javascript game online. You first go to the homepage and then you click on a button that brings you to the game.</p> <p>Something like this when I inspect element:</p> <pre><code>onclick="playgame()" </code></pre> <p>When somebody clicks this, a counter increments so he kn...
0
2016-06-25T13:33:39Z
38,029,132
<p>I am not sure, if this work in your situation, but if you would like to do something x times, you can do it with a loop like in any other language.</p> <p>For example if you would like to call a function x times, you could do it this way:</p> <pre><code>function someFunction(x) { console.log(x) } var iterations = ...
0
2016-06-25T13:40:29Z
[ "javascript", "php", "python", "onclick" ]
Script to continuously execute javascript function on website
38,029,072
<p>A friend of mine has recently posted his javascript game online. You first go to the homepage and then you click on a button that brings you to the game.</p> <p>Something like this when I inspect element:</p> <pre><code>onclick="playgame()" </code></pre> <p>When somebody clicks this, a counter increments so he kn...
0
2016-06-25T13:33:39Z
38,029,953
<p>Just use simple iteration, make a function like this and run it.</p> <pre><code>function click1k() { var clicks=1000; for (var i=clicks; i&gt;0; i--) { playgame(); } } </code></pre> <p>And run:</p> <pre><code>click1k(); </code></pre>
0
2016-06-25T15:20:59Z
[ "javascript", "php", "python", "onclick" ]
Script to continuously execute javascript function on website
38,029,072
<p>A friend of mine has recently posted his javascript game online. You first go to the homepage and then you click on a button that brings you to the game.</p> <p>Something like this when I inspect element:</p> <pre><code>onclick="playgame()" </code></pre> <p>When somebody clicks this, a counter increments so he kn...
0
2016-06-25T13:33:39Z
38,030,059
<p>If it's a website you could use something like iMacros addon for firefox and just record a macro, you can even use js for more complex scripts but a simple loop would do it.</p>
0
2016-06-25T15:33:43Z
[ "javascript", "php", "python", "onclick" ]
Script to continuously execute javascript function on website
38,029,072
<p>A friend of mine has recently posted his javascript game online. You first go to the homepage and then you click on a button that brings you to the game.</p> <p>Something like this when I inspect element:</p> <pre><code>onclick="playgame()" </code></pre> <p>When somebody clicks this, a counter increments so he kn...
0
2016-06-25T13:33:39Z
38,030,946
<p>You can trigger that button continuously. Here is the code.</p> <pre><code> setInterval(function(){ $("Selector").click(); }, 5000); </code></pre> <p>It will click automatically selected button or any element every 5 seconds. You can increase or decrease the time so it will look real to get play counter in ti...
0
2016-06-25T17:12:52Z
[ "javascript", "php", "python", "onclick" ]
Python tkinter: buttons are not displaying
38,029,138
<p>I'm new to tkinter and I'm trying to display two buttons on the window. Currently the buttons are not displaying on the window. I would be very grateful if someone could point out my errors. Thank you.</p> <pre><code>class Application(Frame): def __init__(self, master): super(Application, self).__init__...
0
2016-06-25T13:40:55Z
38,029,327
<p>There is a problem in your __init__bmethod, and from what I see you do not launch the application anywhere. Does this work for you?</p> <pre><code>from Tkinter import * class Application(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() ...
0
2016-06-25T14:03:39Z
[ "python", "tkinter" ]
Python tkinter: buttons are not displaying
38,029,138
<p>I'm new to tkinter and I'm trying to display two buttons on the window. Currently the buttons are not displaying on the window. I would be very grateful if someone could point out my errors. Thank you.</p> <pre><code>class Application(Frame): def __init__(self, master): super(Application, self).__init__...
0
2016-06-25T13:40:55Z
38,029,399
<p>Your function <code>creat_widgets</code> is spelled differently than above in the <code>__init__</code>. </p>
0
2016-06-25T14:14:32Z
[ "python", "tkinter" ]
Error installing cx_Freeze on Ubuntu 16.04 [Errno 2]
38,029,238
<p>I am trying to install cx_Freeze on Ubuntu 16.04. Pip installation does not work, so I have downloaded a tarball (tar.gz), extracted it and moved the cx_Freeze folder to my home directory. </p> <p>I have navigated to the cx_freeze folder and used this command:</p> <pre><code>sudo python setup.py build </code></pre...
0
2016-06-25T13:51:29Z
38,058,552
<p>J.J. Hakala's suggestion to install the newest version of cx_freeze with pip, as well as him providing the correct link to the source, made it possible for me to install cx_freeze with the code he posted in his comment:</p> <pre><code>sudo pip install https://bitbucket.org/anthony_tuininga/cx_freeze/get/tip.tar.bz2...
1
2016-06-27T16:05:27Z
[ "python", "install", "cx-freeze", "setup.py", "ubuntu-16.04" ]
Is there a way to replace Django's smart_str with a Python native solution?
38,029,253
<p>I am passing with a code base that is using the <code>smart_str</code> method of Django:</p> <pre><code> for p in pro: print smart_str(p["title"]) </code></pre> <p>I want to replace it with a native python solution without involving django inside but I am not sure what <code>smart_str</code> exactly do:</p...
0
2016-06-25T13:52:50Z
38,030,891
<p>I replaced it with this dummy function that apply <code>unicode(x).encode("utf-8")</code> if the string is unicode, and convert it to <code>str</code> if it's a number:</p> <pre><code>def smart_str(x): if isinstance(x, unicode): return unicode(x).encode("utf-8") elif isinstance(x, int) or isinstance...
0
2016-06-25T17:06:17Z
[ "python", "django", "unicode", "bytestring" ]
Is there some module/function in NLTK/SKLearn which will do basic analysis of the text data?
38,029,270
<p>I have multiple text files such that each line has exactly one document. I want to do a basic analysis on the text and answer questions like:</p> <ul> <li>Number of Unigrams </li> <li>Average length of doc </li> <li>SD of length of doc</li> </ul> <p>etc.</p> <p>Is there a function in NLTK/SKLEARN to do it? I won'...
-1
2016-06-25T13:55:31Z
38,135,486
<p>1) # of Unigram</p> <pre><code>from itertools import tee, izip def bigrams(iterable): a, b = tee(iterable) next(b, None) return izip(a, b) with open("data.txt", 'r') as f: for line in f: words = line.strip().split() uni = words bi = bigrams(words) print uni ...
1
2016-07-01T00:58:37Z
[ "python", "text", "nlp", "scikit-learn", "nltk" ]
How can i use SteamAPI with Django?
38,029,282
<p>How can this be possible? I am trying to add steam authentication button in my website and get general information: username, steam id. </p> <p>something like this as example:</p> <p><code>views.py</code>:</p> <pre><code># Example from django.shortcuts import render from django.http return HttpResponse def index...
0
2016-06-25T13:58:11Z
38,031,243
<p>You can use the <a href="https://pypi.python.org/pypi/python-social-auth/" rel="nofollow"><code>python-social-auth</code></a> package that has native support for both django and the steam API:</p> <blockquote> <h3>Multiple frameworks are supported:</h3> <ul> <li><strong>Django</strong></li> <li>Flask</li...
1
2016-06-25T17:42:18Z
[ "python", "django", "steam", "steam-web-api" ]
Return to Menu Button TKinter
38,029,284
<p>I'm developing a program for a game in tkinter on Python, and have been trying to formulate a 'Return to Main Menu' button at the moment, but to no avail. Please could I have some help?</p> <p>Here is my code so far:</p> <pre><code>from tkinter import * from tkinter import ttk root = Tk() def MainMenu(): Game...
2
2016-06-25T13:58:47Z
38,029,518
<p>Ok, several suggestions:</p> <p>1) Keep your Tkinter information in a class. This will make it much easier to keep track of later down the line when whatever it is you're making becomes more complicated.</p> <p>2) Use <code>grid()</code> instead of <code>pack()</code>, it's more flexible and powerful.</p> <p>3) U...
1
2016-06-25T14:29:19Z
[ "python", "python-3.x", "button", "tkinter", "menu" ]
Return to Menu Button TKinter
38,029,284
<p>I'm developing a program for a game in tkinter on Python, and have been trying to formulate a 'Return to Main Menu' button at the moment, but to no avail. Please could I have some help?</p> <p>Here is my code so far:</p> <pre><code>from tkinter import * from tkinter import ttk root = Tk() def MainMenu(): Game...
2
2016-06-25T13:58:47Z
38,030,412
<p>The best solution for this type of problem is to make each "screen" a frame with whatever you want in the screen. For example:</p> <pre><code>def help_screen(parent): screen = Frame(parent, ...) label = Label(screen, ...) ... return screen def other_screen(parent): screen = Frame(parent, ...) ...
0
2016-06-25T16:12:58Z
[ "python", "python-3.x", "button", "tkinter", "menu" ]
"TypeError: unhashable type " while trying to retrieve information using BeautifulSoup, Python
38,029,314
<p>I was trying to use the TumblrAPI, PyTumblr to be specific, to crawl some images in posts with certain tags,</p> <p>that's the code I use, quite simple: </p> <pre><code>import pytumblr from bs4 import BeautifulSoup # Authenticate via API Key client = pytumblr.TumblrRestClient('#Here is my API Key#') print client....
-1
2016-06-25T14:02:23Z
38,029,353
<p>The <code>client.post()</code> call returns a <em>Python dictionary</em>, not a string containing HTML; it has parsed the JSON response for you already. Because BeautifulSoup is trying to treat it as a string you get your error, as <code>:5</code> is passed to the dictionary as a <em>slice object</em>, and this is n...
2
2016-06-25T14:08:03Z
[ "python", "beautifulsoup", "typeerror", "pytumblr" ]
Fill a matrix in parallel
38,029,359
<p>I have a question about how to fill a matrix in parallel. I'm trying to do it in Python row-by-row. But the time to do it in parallel is worst than the sequential processing time. How can I do it efficiently? Note: I need to know the value of the indices (<em>i</em> and <em>j</em>).</p> <p><strong>Squential</strong...
1
2016-06-25T14:09:03Z
38,030,787
<p>Your code raises a whole bunch of questions, too many to put in comments.</p> <pre><code>def something(pos, size): global matrix </code></pre> <p>What is <code>matrix</code>? Why <code>global</code>? Since you are mutating it you don't need the global even it is defined outside this function. But I'd ...
2
2016-06-25T16:56:14Z
[ "python", "loops", "numpy", "parallel-processing" ]
Recursive walk trough a JSON file extracting SELECTED strings
38,029,421
<p>I need to recursively walk trough a JSON files (post responses from an API), extracting the strings that have ["text"] as a key <code>{"text":"this is a string"}</code></p> <p>I need to start to parse from the source that has the oldest date in metadata, extract the strings from that source and then move to the 2nd...
3
2016-06-25T14:16:19Z
38,031,576
<p>I think this will do what you want, as far as selecting the right strings. I also changed the way type-checking was done to use <a href="https://docs.python.org/2/library/functions.html?highlight=isinstance#isinstance" rel="nofollow"><code>isinstance()</code></a>, which is considered a better way to do it because it...
2
2016-06-25T18:18:26Z
[ "python", "json", "string", "recursion" ]
How can I split code-blocks into a list?
38,029,456
<p>I want to split the contents of a CSS file into code blocks and push each block of code into a list using Python 3.5.</p> <p>So, given this CSS:</p> <pre><code>h1 {color: #333, background-color: transparent} h2 { font-weight:300 } h3 { font-weight: 200 } </code></pre> <p>We can clearly tell that it has multip...
4
2016-06-25T14:20:45Z
38,029,636
<p>This implementation is done using <code>tinycss</code>, a simple pure python <a href="http://pythonhosted.org/tinycss/index.html" rel="nofollow">css parser</a>.</p> <p>This works on <strong>untidied</strong> css. As long as it is legal.</p> <pre><code>import tinycss from collections import defaultdict parser = ti...
4
2016-06-25T14:41:57Z
[ "python", "css", "regex", "list", "python-3.x" ]
How can I split code-blocks into a list?
38,029,456
<p>I want to split the contents of a CSS file into code blocks and push each block of code into a list using Python 3.5.</p> <p>So, given this CSS:</p> <pre><code>h1 {color: #333, background-color: transparent} h2 { font-weight:300 } h3 { font-weight: 200 } </code></pre> <p>We can clearly tell that it has multip...
4
2016-06-25T14:20:45Z
38,029,919
<p>You can achieve this with a simple file read and replace:</p> <pre><code>styles = [] with open('file.css') as file: style = [] for line in file.readlines(): # If line is empty if not line.strip(): # If a block is non-empty if style: styles.append("".jo...
2
2016-06-25T15:16:45Z
[ "python", "css", "regex", "list", "python-3.x" ]
ValueError in Django when running "python manage.py test"
38,029,534
<p>I'm going through the Django tuturial from this site: <a href="https://docs.djangoproject.com/en/1.9/intro/tutorial05/" rel="nofollow">https://docs.djangoproject.com/en/1.9/intro/tutorial05/</a></p> <p>When I try to run "python manage.py test" i get the error message below:</p> <p>Am running Django with PyCharm wi...
0
2016-06-25T14:31:18Z
38,030,540
<p>You have error in <a href="https://bitbucket.org/RasmusRavnFrost/djangotestingforstackoverflow/src/52df9670131089d70467ad6969940faa98f73732/DjangoTest/polls/migrations/0001_initial.py?at=master&amp;fileviewer=file-view-default#0001_initial.py-36" rel="nofollow">polls/migrations/0001_initial.py line no 36</a> <code>t...
1
2016-06-25T16:29:14Z
[ "python", "django", "python-3.5" ]
PyQt crashes on start after (Qt?) update
38,029,574
<p>Recently, after update (which presumably included Qt5) my pyQt5 apps stopped working, crashing on start-up:</p> <pre><code>... from PyQt5.QtWidgets import QDialog ImportError: /usr/lib64/python3.4/site-packages/PyQt5/QtCore.so: symbol _ZN20QMetaPropertyBuilder8setFinalEb, version Qt_5 not defined in file libQt5...
0
2016-06-25T14:35:27Z
38,029,855
<p>Ok, I solved the issue by installing the package python3-qt5 built against Qt 5.6 from KDE:/Qt_56 repository.</p>
0
2016-06-25T15:10:52Z
[ "python", "linux", "qt", "crash", "pyqt5" ]
How to quickly calculate cosine similarity for large number of vectors in Python?
38,029,656
<p>I have a set of <strong>100 thousand</strong> vectors and I need to retrieve top-25 closest vector based on cosine similarity.</p> <p>Scipy and Sklearn have implementations for computing cosine distance/similarity 2 vectors but I will need to compute the Cosine Sim for 100k X 100k size and then take out top-25. Is ...
2
2016-06-25T14:44:59Z
38,034,880
<p>I would try smarter algorithms first, rather than speeding up brute force (computing all pairs of vectors). KDTrees might work, scipy.spatial.KDTree(), if your vectors are of low dimension. If they are high dimension then you might need a random projection first: <a href="http://scikit-learn.org/stable/modules/ran...
1
2016-06-26T03:11:14Z
[ "python", "vector", "scipy", "scikit-learn", "sklearn-pandas" ]