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 |
|---|---|---|---|---|---|---|---|---|---|
Fast lookup from floating point index into array | 39,721,958 | <p>Suppose I have <code>n</code> intervals of length <code>len</code> on an axis. Each of them is assigned a value in an <code>ndarray</code>. Now I'd like to look-up some values at positions <code>query_pos</code> given as floating point numbers. Currently, I plan to do it the following way:</p>
<pre><code>n = 100
le... | 0 | 2016-09-27T10:11:28Z | 39,722,216 | <p>Instead of dividing each element of <code>query_pos</code> by that scalar, we can pre-calculate the reciprocal of the scalar and use multiplication instead for some speedup there. The intuition is that division is a more costly affair than multiplication.</p>
<p>Here's a quick runtime test on it -</p>
<pre><code>I... | 4 | 2016-09-27T10:24:15Z | [
"python",
"numpy",
"optimization",
"floating-point",
"indices"
] |
Fast lookup from floating point index into array | 39,721,958 | <p>Suppose I have <code>n</code> intervals of length <code>len</code> on an axis. Each of them is assigned a value in an <code>ndarray</code>. Now I'd like to look-up some values at positions <code>query_pos</code> given as floating point numbers. Currently, I plan to do it the following way:</p>
<pre><code>n = 100
le... | 0 | 2016-09-27T10:11:28Z | 39,723,171 | <p>You can output the result of the division straight to an <code>int</code> array:</p>
<pre><code>idx = np.empty_like(query_pos, int)
np.divide(query_pos, len, out=idx, casting='unsafe')
</code></pre>
<p>This will be noticeably faster only for large arrays. But this code is harder to read, so only optimize if it's a... | 1 | 2016-09-27T11:11:47Z | [
"python",
"numpy",
"optimization",
"floating-point",
"indices"
] |
Pandas: count some values in a column | 39,722,185 | <p>I have dataframe, it's part of them</p>
<pre><code> ID,"url","app_name","used_at","active_seconds","device_connection","device_os","device_type","device_usage"
e990fae0f48b7daf52619b5ccbec61bc,"",Phone,2015-05-01 09:29:11,13,3g,android,smartphone,home
e990fae0f48b7daf52619b5ccbec61bc,"",Phone,2015-05-0... | 1 | 2016-09-27T10:22:48Z | 39,722,273 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> by <code>ID</code>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.month.html" rel="nofollow"><code>month</code></a> and <a href="htt... | 1 | 2016-09-27T10:27:08Z | [
"python",
"datetime",
"pandas",
"aggregate",
"days"
] |
Unable to serve the nested css & js files via nginx? | 39,722,236 | <p>I've read some documentation and tried and number of alternatives from previous answers on this site but cannot get nginx to serve my css & js files from my flask app. In my code i have for example:</p>
<pre><code><link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}"/>
<scrip... | -1 | 2016-09-27T10:25:23Z | 39,730,495 | <p>Not only do you mix the case (<code>CSS</code> vs <code>css</code>), you include <code>../static/</code> in the JavaScript path. Fix the capitalization and remove the <code>../static/</code>.</p>
| 0 | 2016-09-27T17:03:52Z | [
"python",
"nginx",
"flask",
"gunicorn",
"nginx-location"
] |
Getting Django function to return and render HTML page | 39,722,274 | <p>I have function (inside a <a href="https://docs.python.org/3/tutorial/classes.html#classes" rel="nofollow">class</a>) that returns <code>True</code> if a user <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/auth/#django.contrib.auth.models.User.is_authenticated" rel="nofollow">is_authenticate()</a> and <... | -1 | 2016-09-27T10:27:11Z | 39,722,485 | <p>First of all your class really is redundant, calling it takes one line and modifying your view is also one line</p>
<pre><code>from django.http import HttpResponse, Http404
def authUsers(request):
if request.user.is_authenticated() and request.user.is_active:
raise Http404
else :
return render(... | 0 | 2016-09-27T10:38:54Z | [
"python",
"django"
] |
Is it a good idea to apply ML libraries on pandas data frame? | 39,722,279 | <p>i am building a cognitive miner AI Bot. where My Bot has two task , one is train and other is predict.i'm using some/few ML functionalities. so here i have lots of documents(~200,000 docs) which i'm training. and then in predicting for a query, i'm following some steps to find most accurate matched document(by looki... | 1 | 2016-09-27T10:27:28Z | 39,722,582 | <p>It probably won't make much of a difference either way, in terms of performance.</p>
<p>Pandas is extremely efficient for loading data and munging it (grouping it in different ways, pivoting, creating new columns from existing columns, and so forth). </p>
<p>Once your data is ready for passing to a machine learnin... | 1 | 2016-09-27T10:43:29Z | [
"python",
"pandas",
"numpy",
"artificial-intelligence"
] |
Python how to reference variable | 39,722,409 | <p>I'm getting a problem when referencing variables on a python file. Here is the code:</p>
<pre><code>FG_E = 9
FG_R = 8
START = 7
READY = 9
MC = 3
BRAKE = 5
ERROR = 6
a = 2
b = 3
position = 0
def build_message(signal):
message = position
message = message | (0b1<<signal)
s = bin(message)
s = s... | 0 | 2016-09-27T10:34:36Z | 39,722,503 | <p>The problematic line is actually <code>position = s_final</code> in the function <code>build_message</code>.</p>
<p>If it wasn't there then <code>message = position</code> would work because the Python interpreter would know to which <code>position</code> variable you are referring. </p>
<p>But in this case it is ... | 3 | 2016-09-27T10:39:52Z | [
"python"
] |
Python how to reference variable | 39,722,409 | <p>I'm getting a problem when referencing variables on a python file. Here is the code:</p>
<pre><code>FG_E = 9
FG_R = 8
START = 7
READY = 9
MC = 3
BRAKE = 5
ERROR = 6
a = 2
b = 3
position = 0
def build_message(signal):
message = position
message = message | (0b1<<signal)
s = bin(message)
s = s... | 0 | 2016-09-27T10:34:36Z | 39,722,515 | <p>You need to use <code>global</code> keyword to access global variable. </p>
<pre><code>def build_message(signal):
global position
message = position
</code></pre>
| 1 | 2016-09-27T10:40:25Z | [
"python"
] |
Python how to reference variable | 39,722,409 | <p>I'm getting a problem when referencing variables on a python file. Here is the code:</p>
<pre><code>FG_E = 9
FG_R = 8
START = 7
READY = 9
MC = 3
BRAKE = 5
ERROR = 6
a = 2
b = 3
position = 0
def build_message(signal):
message = position
message = message | (0b1<<signal)
s = bin(message)
s = s... | 0 | 2016-09-27T10:34:36Z | 39,722,567 | <p>If you are using an outside variable into a function maybe you should consider passing it as an argument, like:</p>
<pre><code>def build_message(signal,position):
pass
</code></pre>
| 0 | 2016-09-27T10:43:03Z | [
"python"
] |
Django error while saving Foreign Key - Can not assign none , Doesn't allow null values | 39,722,410 | <p>I have two models - Events and Tenants. </p>
<pre><code>class EventsModel(models.Model):
sys_id = models.AutoField(primary_key=True, null=False, blank=True)
tenant_sys_id = models.ForeignKey('tenant.TenantModel', on_delete = models.CASCADE, null=False, blank=True)
name = models.CharField(max_length=80, ... | -1 | 2016-09-27T10:34:39Z | 39,722,792 | <p>Your ForeignKey should be called <code>tenant_sys</code>, not <code>tenant_sys_id</code>. Django will automatically add the <code>_id</code> suffix to the underlying database field, but the value you have in Python is actually an instance of the target model, not an ID.</p>
<p>With the code you have, you are still ... | 0 | 2016-09-27T10:54:11Z | [
"python",
"django",
"django-models",
"foreign-keys"
] |
Error logged while trying to run Robot Test in IE11 - WebDriverException: 404 - File or directory not found | 39,722,647 | <p>I'm trying to execute certain tests in Robot framework - tests that are working fine with Chrome using the Chrome Driver.</p>
<p>Once execution starts, I get an exception in the command prompt and execution stops without the browser even opening (Attaching the log.html file screenshot and snippet)</p>
<pre><code>S... | -1 | 2016-09-27T10:46:38Z | 39,738,517 | <blockquote>
<p>For IE 11 only, you will need to set a registry entry on the target computer so that the driver can maintain a connection to the instance of Internet Explorer it creates. For 32-bit Windows installations, the key you must examine in the registry editor is HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet... | 0 | 2016-09-28T05:11:32Z | [
"python",
"selenium",
"internet-explorer-11",
"robotframework",
"selenium-iedriver"
] |
Python error: Index out of range | 39,722,762 | <pre><code>seq_sum = []
for i in range(len(sequence)):
seq_sum[i] = sequence[i] + inv_sequence[i]
print (seq_sum)
</code></pre>
<p>When I try to run this code it return an error: list assignment index out of range. How can I fix the problem?
sequence and inv_sequence are arrays of integers.</p>
| -1 | 2016-09-27T10:52:40Z | 39,722,790 | <p><code>seq_sum[i]</code> will raise an <code>IndexError</code> as the <code>seq_sum</code> list is empty. You should use <code>append</code> instead:</p>
<pre><code>seq_sum = []
for i in range(len(sequence)):
seq_sum.append(sequence[i] + inv_sequence[i])
print(seq_sum)
</code></pre>
<p>You can achieve the same ... | 8 | 2016-09-27T10:54:07Z | [
"python",
"python-3.x"
] |
Python error: Index out of range | 39,722,762 | <pre><code>seq_sum = []
for i in range(len(sequence)):
seq_sum[i] = sequence[i] + inv_sequence[i]
print (seq_sum)
</code></pre>
<p>When I try to run this code it return an error: list assignment index out of range. How can I fix the problem?
sequence and inv_sequence are arrays of integers.</p>
| -1 | 2016-09-27T10:52:40Z | 39,722,819 | <p>You've declared <code>seq_sum</code> to be an empty list. You then try and index in a position other than <code>0</code> which results in an <code>IndexError</code>.</p>
<p>Expanding a list to make it larger is essentially done with <code>append</code>ing, <code>extend</code>ing or <code>slice</code> assignments. S... | 1 | 2016-09-27T10:55:09Z | [
"python",
"python-3.x"
] |
Merging all rows with common value | 39,722,874 | <p>Here's what I want to do using Python:</p>
<p><code>file1.csv</code> contains:</p>
<pre><code>Code,Expenditure
1,Meal
2,Taxi
3,Apartment
4,Laundry
</code></pre>
<p><code>file2.csv</code> contains:</p>
<pre><code>Code,Amount
1,150
2,90
2,100
2,85
3,5000
</code></pre>
<p>Now I want to merge them into another file... | -1 | 2016-09-27T10:57:21Z | 39,723,771 | <p>Read about file handling and python basics. As @Scott hunter told, you should try something, if you face any problems you can ask your question with your code here.</p>
<p>Anyway, <strong>Here is what you need,</strong></p>
<pre><code>a=open('a.txt','r').readlines()
b=open('b.txt','r').readlines()
for i in a:
... | -1 | 2016-09-27T11:41:59Z | [
"python",
"csv",
"merge"
] |
Are Python modules compiled? | 39,722,984 | <p>Trying to understand whether python libraries are compiled because I want to know if the interpreted code I write will perform the same or worse.</p>
<p>e.g. I saw it mentioned somewhere that numpy and scipy are efficient because they are compiled. I don't think this means byte code compiled so how was this done? W... | 1 | 2016-09-27T11:02:46Z | 39,723,231 | <p>NumPy and several other libraries are partly wrappers for code written in C and other languages like FORTRAN, which when compiled will run faster than Python. This helps by avoiding the cost of loops, pointer indirection and per-element dynamic type checking in Python. This is explained in <a href="http://stackoverf... | 4 | 2016-09-27T11:15:23Z | [
"python",
"numpy",
"compilation"
] |
Are Python modules compiled? | 39,722,984 | <p>Trying to understand whether python libraries are compiled because I want to know if the interpreted code I write will perform the same or worse.</p>
<p>e.g. I saw it mentioned somewhere that numpy and scipy are efficient because they are compiled. I don't think this means byte code compiled so how was this done? W... | 1 | 2016-09-27T11:02:46Z | 39,728,900 | <p>Python can execute functions written in Python (interpreted) and compiled functions. There are whole API docs about writing code for integration with Python. <code>cython</code> is one of the easier tools for doing this. </p>
<p>Libraries can be any combination - pure Python, Python plus interfaces to compiled co... | 1 | 2016-09-27T15:40:30Z | [
"python",
"numpy",
"compilation"
] |
Python: coursera assignments - Dictionary chapter | 39,722,987 | <p>I'm trying to solve the assignments from coursera - Python.</p>
<p>Write a program to read through the mbox-short.txt and figure out who has the sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program create... | 0 | 2016-09-27T11:03:00Z | 39,723,564 | <p>Check line 3726 and 3763. There is a colon after <strong>From</strong>. I think you are missing that while searching manually.</p>
<blockquote>
<p>Line 3726 From cwen@iupui.edu Thu Jan 3 16:23:48 2008 </p>
<p>Line 3763 From: cwen@iupui.edu</p>
</blockquote>
<p>Otherwise the code is correct. It is showing c... | 0 | 2016-09-27T11:32:27Z | [
"python",
"dictionary"
] |
Python: coursera assignments - Dictionary chapter | 39,722,987 | <p>I'm trying to solve the assignments from coursera - Python.</p>
<p>Write a program to read through the mbox-short.txt and figure out who has the sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program create... | 0 | 2016-09-27T11:03:00Z | 39,779,835 | <p>Thanks to all for hints. I checked manually and the answer is correct to be 10, which means my code is ok. The desired output of "5", was indicated by the assignment from Coursera courses (as i follow them).
Thank a lot for the help! </p>
| 0 | 2016-09-29T20:53:43Z | [
"python",
"dictionary"
] |
How to extract date form data frame column? | 39,723,061 | <p>I have data frame like that:</p>
<pre><code> month items
0 1962-01-01 589
1 1962-02-01 561
2 1962-03-01 640
3 1962-04-01 656
4 1962-05-01 723
</code></pre>
<p>I need to get year or month from this data frame and create array, but I don't know how to do that.</p>
<p>expected result:</p>
<p... | 2 | 2016-09-27T11:06:11Z | 39,723,167 | <p>Assuming this is <code>pandas</code> you may need to convert the month column to dtype <code>datetime</code> and then you can use <code>.dt</code> accessor for the year and month attributes:</p>
<pre><code>In [33]:
df['month'] = pd.to_datetime(df['month'])
df.info()
<class 'pandas.core.frame.DataFrame'>
Int6... | 2 | 2016-09-27T11:11:20Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
Cant see image from project directory | 39,723,072 | <p>I tried to handle this but I gave up. I have folder with images and I want to display my some image in html view but It wont work.</p>
<p>I followed this tutorial <a href="https://docs.djangoproject.com/en/1.10/howto/static-files/#serving-files-uploaded-by-a-user-during-development" rel="nofollow">enter link descri... | 0 | 2016-09-27T11:06:39Z | 39,723,634 | <p><code>MEDIA_ROOT</code> is the absolute filesystem path to the directory that will hold user-uploaded files.</p>
<p><code>STATIC_ROOT</code> is the absolute filesystem path to the directory from which youâd like to serve these files.</p>
<p>Since, you would like to serve images, give the absolute path of your st... | 1 | 2016-09-27T11:36:01Z | [
"python",
"django"
] |
Cant see image from project directory | 39,723,072 | <p>I tried to handle this but I gave up. I have folder with images and I want to display my some image in html view but It wont work.</p>
<p>I followed this tutorial <a href="https://docs.djangoproject.com/en/1.10/howto/static-files/#serving-files-uploaded-by-a-user-during-development" rel="nofollow">enter link descri... | 0 | 2016-09-27T11:06:39Z | 39,724,404 | <p>The only thing you have to do is</p>
<pre><code>MEDIA_ROOT = '/absolutepath/to/djangoproject/webstore/media/'
</code></pre>
<p>Then you have already</p>
<pre><code>MEDIA_URL = '/media/'
</code></pre>
<p>and try </p>
<pre><code><img src="/media/example.jpg" />
</code></pre>
| 1 | 2016-09-27T12:15:35Z | [
"python",
"django"
] |
Cant see image from project directory | 39,723,072 | <p>I tried to handle this but I gave up. I have folder with images and I want to display my some image in html view but It wont work.</p>
<p>I followed this tutorial <a href="https://docs.djangoproject.com/en/1.10/howto/static-files/#serving-files-uploaded-by-a-user-during-development" rel="nofollow">enter link descri... | 0 | 2016-09-27T11:06:39Z | 39,724,655 | <p><code>MEDIA_URL</code> is the base URL to serve the media files uploaded by users, and <code>MEDIA_ROOT</code> is the local path where they reside.</p>
<p>so try to use it on your <code>setting.py</code></p>
<pre><code>MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
</code></pre>
<p>and on you... | 1 | 2016-09-27T12:25:38Z | [
"python",
"django"
] |
Python->BeautifulSoup->Webscraping->Drop Down Menu | 39,723,135 | <p>So I am trying to dump all of the reports from this website:</p>
<p><a href="https://www.treasurydirect.gov/govt/reports/tfmp/tfmp_utf.htm" rel="nofollow">https://www.treasurydirect.gov/govt/reports/tfmp/tfmp_utf.htm</a></p>
<p>State: All States (Not the Reed Act Benefit or Reed Act Admin)</p>
<p>Report: Transact... | 1 | 2016-09-27T11:09:55Z | 39,723,455 | <h1>A good first approach to scraping: Pattern Matching Heuristic</h1>
<p>What you want to do, at a high level, is this:</p>
<ol>
<li>Identify a pattern in the source.</li>
<li>Represent the nature of the pattern in the code.</li>
<li>Scrape according to that code.</li>
</ol>
<h3>I won't code the entire thing here, ... | -1 | 2016-09-27T11:26:52Z | [
"python",
"drop-down-menu",
"web-scraping",
"beautifulsoup"
] |
Python->BeautifulSoup->Webscraping->Drop Down Menu | 39,723,135 | <p>So I am trying to dump all of the reports from this website:</p>
<p><a href="https://www.treasurydirect.gov/govt/reports/tfmp/tfmp_utf.htm" rel="nofollow">https://www.treasurydirect.gov/govt/reports/tfmp/tfmp_utf.htm</a></p>
<p>State: All States (Not the Reed Act Benefit or Reed Act Admin)</p>
<p>Report: Transact... | 1 | 2016-09-27T11:09:55Z | 39,724,429 | <p>You will have to do a little hardcoding, the requests is put together with the code in <a href="https://www.treasurydirect.gov/js/utfnav.js" rel="nofollow">utfnav.js</a>, the main part we are interested in is below:</p>
<pre><code>//assembles path to reports
ReportPath = "/govt/reports/tfmp/utf/"+StateN... | 2 | 2016-09-27T12:16:17Z | [
"python",
"drop-down-menu",
"web-scraping",
"beautifulsoup"
] |
Django Standalone Script | 39,723,310 | <p>I am trying to access my Django (v1.10) app DB from another python script and having some trouble doing so.</p>
<p>This is my file and folder structure:</p>
<pre><code>store
store
__init.py__
settings.py
urls.py
wsgi.py
store_app
__init.py__
admin.py
apps.py
models.py
...
db.sqlite3
... | 1 | 2016-09-27T11:19:54Z | 39,723,527 | <p>try to import from <code>store_app.models</code> - as the surrounding <code>store</code> folder is not a python module and should not be used when importing.</p>
<pre><code>import django
from django.conf import settings
settings.configure(DEBUG=True)
django.setup()
from store_app.models import MyModel
</code></pr... | 0 | 2016-09-27T11:30:38Z | [
"python",
"django"
] |
Django Standalone Script | 39,723,310 | <p>I am trying to access my Django (v1.10) app DB from another python script and having some trouble doing so.</p>
<p>This is my file and folder structure:</p>
<pre><code>store
store
__init.py__
settings.py
urls.py
wsgi.py
store_app
__init.py__
admin.py
apps.py
models.py
...
db.sqlite3
... | 1 | 2016-09-27T11:19:54Z | 39,723,977 | <p>This sounds like a great use case for <a href="https://docs.djangoproject.com/en/1.10/howto/custom-management-commands/" rel="nofollow">Django Management commands.</a> which has the added bonus you can run it scheduled from cron, direct from the commandline, or call from inside django. This gives the script full ac... | 2 | 2016-09-27T11:53:56Z | [
"python",
"django"
] |
Django Standalone Script | 39,723,310 | <p>I am trying to access my Django (v1.10) app DB from another python script and having some trouble doing so.</p>
<p>This is my file and folder structure:</p>
<pre><code>store
store
__init.py__
settings.py
urls.py
wsgi.py
store_app
__init.py__
admin.py
apps.py
models.py
...
db.sqlite3
... | 1 | 2016-09-27T11:19:54Z | 39,724,171 | <p>Try this</p>
<pre><code>import sys, os, django
sys.path.append("/path/to/store") #here store is root folder(means parent).
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "store.settings")
django.setup()
from store_app.models import MyModel
</code></pre>
<p>This script you can use anywhere in your system.</p>
| 0 | 2016-09-27T12:03:52Z | [
"python",
"django"
] |
How to inherit Base class with singleton in python | 39,723,398 | <p>I have base class which is singleton, i need to inherit that in my another class but i get error message as
TypeError: Error when calling the metaclass bases
function() argument 1 must be code, not str</p>
<p>Can someone help with this.
Below is sample code.</p>
<pre><code>def singleton(cls):
instances = {}... | 1 | 2016-09-27T11:23:56Z | 39,726,451 | <p>You must make the <code>singleton</code> a class instead of a function for derivation to work. Here is an example that has been tested on both Python 2.7 and 3.5:</p>
<pre><code>class singleton(object):
instances = {}
def __new__(cls, clz = None):
if clz is None:
# print ("Creating objec... | 0 | 2016-09-27T13:48:56Z | [
"python",
"python-2.7"
] |
python subprocess: order of output changes when using subprocess.PIPE | 39,723,437 | <p>When I write a python script called <code>outer.py</code> containing</p>
<pre><code>p = subprocess.Popen(['./inner.py'])
print('Called inner.py without options, waiting for process...')
p.wait()
print('Waited for inner.py without options')
p = subprocess.Popen(['./inner.py'], stdout=subprocess.PIPE)
print('Called ... | 2 | 2016-09-27T11:25:58Z | 39,724,806 | <p>I would guess that, for some reason (related to pipes vs. ttys, see <a href="http://stackoverflow.com/questions/107705/disable-output-buffering/107717#comment24604506_107717">this comment</a>), the output of the <code>inner.py</code> Python process is unbuffered the first time you call it, and buffered the second ti... | 1 | 2016-09-27T12:33:26Z | [
"python",
"order",
"pipe",
"subprocess",
"python-3.5"
] |
Unable to install Xvfb on Suse Linux | 39,723,439 | <p>I am trying to run the selenium-webdriver using the python library on Suse 11.4 (64-bit)
For it to run headlessly, it requires another python package "pyvirtualdisplay" to run. I have been able to install both perfectly.
The problem now is that pyvirtualdisplay requires a system level package called Xvfb which is no... | -1 | 2016-09-27T11:25:59Z | 39,729,149 | <p>According to <a href="http://unix.stackexchange.com/questions/11364/installing-xvfb-on-suse">this</a> post Xvfb is provided by the <code>xorg-x11-server</code> package. Since you dont have access to zypper you can download that package directly from <a href="https://software.opensuse.org/package/xorg-x11-server" rel... | 0 | 2016-09-27T15:52:21Z | [
"python",
"selenium",
"suse",
"xvfb",
"pyvirtualdisplay"
] |
How to select list item with dynamically generated ids - Selenium test Python | 39,723,473 | <p>I have a problem here where I am unable to locate the list items. </p>
<pre><code><ul id="select2-id_faculty_advisor-results" class="select2-results__options" role="tree" aria-multiselectable="true" aria-expanded="true" aria-hidden="false">
<li id="select2-id_faculty_advisor-result-0pu4-1" class="selec... | 0 | 2016-09-27T11:27:44Z | 39,723,592 | <p>Use the part of the id that does not change in a css selector like:<br>
<code>li[id*='faculty_advisor-result']</code> </p>
<p>You can also add extra attributes if needed, for example aria-selected like:<br>
<code>li[id*='faculty_advisor-result'][aria-selected='false']</code> or any other attribute.</p>
<p>If yo... | 0 | 2016-09-27T11:33:48Z | [
"python",
"selenium",
"selenium-webdriver"
] |
How to select list item with dynamically generated ids - Selenium test Python | 39,723,473 | <p>I have a problem here where I am unable to locate the list items. </p>
<pre><code><ul id="select2-id_faculty_advisor-results" class="select2-results__options" role="tree" aria-multiselectable="true" aria-expanded="true" aria-hidden="false">
<li id="select2-id_faculty_advisor-result-0pu4-1" class="selec... | 0 | 2016-09-27T11:27:44Z | 39,724,825 | <p>the best way to do it make collection of list by xpath "//ul[@id='select2-id_faculty_advisor-results']/li"</p>
<p>after that you can select them by index from the collection.</p>
| 0 | 2016-09-27T12:34:49Z | [
"python",
"selenium",
"selenium-webdriver"
] |
GitPython List all commits for a specific file | 39,723,521 | <p>I am writing a Python script and there I need to know all commits for a specific file. In my code I use <a href="http://gitpython.readthedocs.io/en/stable/intro.html" rel="nofollow">GitPython</a> for other tasks but for this problem I can't find something.</p>
<p>In cmd line I use:</p>
<pre><code>git log --pretty=... | 0 | 2016-09-27T11:30:19Z | 39,723,678 | <p>What we are looking for in Git is:</p>
<pre><code>git log --follow filename
</code></pre>
<p>not sure GitPython has it tho.</p>
| 0 | 2016-09-27T11:37:48Z | [
"python",
"git",
"gitpython"
] |
how to create a text file through python | 39,723,570 | <p>Looking to create a program that needs to take the users sentence, list its positions, and also identify each individual positions of word and then save a list of the position numbers to a file, I've got as far as:</p>
<pre><code> text = input('Please type your sentence: ')
sentence = text.split()
word= input('Th... | -2 | 2016-09-27T11:32:54Z | 39,723,639 | <p>Use the open function with the 'w' or 'a' access modifier.</p>
<p>e.g.</p>
<pre><code>fo = open("foo.txt", "w")
</code></pre>
| 0 | 2016-09-27T11:36:12Z | [
"python",
"file"
] |
how to create a text file through python | 39,723,570 | <p>Looking to create a program that needs to take the users sentence, list its positions, and also identify each individual positions of word and then save a list of the position numbers to a file, I've got as far as:</p>
<pre><code> text = input('Please type your sentence: ')
sentence = text.split()
word= input('Th... | -2 | 2016-09-27T11:32:54Z | 39,723,680 | <p>Refer article - <a href="https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files" rel="nofollow">File Operation In Python</a></p>
<p>Example to create a file</p>
<pre><code>f = open('file_path', 'w')
f.write('0123456789abcdef')
f.close()
</code></pre>
<p>EDIT: added mode</p>
| -1 | 2016-09-27T11:37:53Z | [
"python",
"file"
] |
how to create a text file through python | 39,723,570 | <p>Looking to create a program that needs to take the users sentence, list its positions, and also identify each individual positions of word and then save a list of the position numbers to a file, I've got as far as:</p>
<pre><code> text = input('Please type your sentence: ')
sentence = text.split()
word= input('Th... | -2 | 2016-09-27T11:32:54Z | 39,723,840 | <p>if you use the open function with "w+" and there is no such file "open" will create a new file. </p>
<pre><code>file = open(Max.txt","w+")
</code></pre>
<p>for more infos about r,r+,w,w+... <a href="http://stackoverflow.com/questions/1466000/python-open-built-in-function-difference-between-modes-a-a-w-w-and-r">he... | 0 | 2016-09-27T11:46:12Z | [
"python",
"file"
] |
Compare two csv files and color code the difference in csv | 39,723,619 | <p>I want to compare two CSV files. If there is difference in a particular cell (Ex: 5th row and 3rd column) then give red color to that cell.</p>
<p>I can able to compare two files but unable to give red color to the difference cell I have tried this code</p>
<pre><code>def compare():
try:
assert_frame_equal(df_... | -1 | 2016-09-27T11:35:06Z | 39,724,334 | <p>You can't set a colour in a csv file. Want you can do is doing it in excel:
Have a look at those two questions: <a href="http://stackoverflow.com/q/10532367/3659824">How to change background color of excel cell with python xlwt library?</a> and <a href="http://stackoverflow.com/q/11444207/3659824">Setting a cell's ... | 0 | 2016-09-27T12:12:07Z | [
"python",
"csv",
"pandas"
] |
Compare two csv files and color code the difference in csv | 39,723,619 | <p>I want to compare two CSV files. If there is difference in a particular cell (Ex: 5th row and 3rd column) then give red color to that cell.</p>
<p>I can able to compare two files but unable to give red color to the difference cell I have tried this code</p>
<pre><code>def compare():
try:
assert_frame_equal(df_... | -1 | 2016-09-27T11:35:06Z | 39,724,400 | <p>You can only apply conditional formatting to excel files (e.g. xlsx), not .csv</p>
<p>I would organise the code in the following way:</p>
<ul>
<li>Use pandas to compare the two csv and create a dataframe with a flag for the differences</li>
<li>Use xlsx module to write a xlsx file, coloring in red the cells where ... | 0 | 2016-09-27T12:15:18Z | [
"python",
"csv",
"pandas"
] |
Python Queue double threading | 39,723,702 | <p>I am trying to run 5 threads which run another 10 threads each. Something like:</p>
<pre><code>dictionaryFileQueue = Queue.Queue()
with open(dictionaryFile, "r") as wordsToCheck:
for word in wordsToCheck:
dictionaryFileQueue.put(word)
for wordToScan in wordsList:
#...some code
dictionaryFileOpen =... | 0 | 2016-09-27T11:38:41Z | 39,726,658 | <p>It turns out, that was so easy to do.
Just need to paste this part:</p>
<pre><code>dictionaryFileQueue = Queue.Queue()
for word in linesOfDictionary:
dictionaryFileQueue.put(word.strip())
</code></pre>
<p>Inside of this part:</p>
<pre><code>for wordToScan in wordsList:
#...some code
# INSTEAD OF THIS LI... | 0 | 2016-09-27T13:57:02Z | [
"python",
"multithreading",
"queue"
] |
How to separate a CSV file when there are "" lines? | 39,723,925 | <p>When I am reading in a CSV file that looks like this:</p>
<pre><code>To, ,New York ,Norfolk ,Charleston ,Savannah
Le Havre (Fri), ,15 ,18 ,22 ,24
Rotterdam (Sun) ,"",13 ,16 ,20 ,22
Hamburg (Thu) ,"",11 ,14 ,18 ,20
Southampton (Fri) , "" ,8 ,11 ,15 ,17
</code></pre>
<p>using pandas, as follows:</p>
<pre><c... | 2 | 2016-09-27T11:51:01Z | 39,724,505 | <p>Just use csv library in python,
import it and use .</p>
<pre><code>import csv
file_obj = #your_file_object_read_mode
rows = file_obj.readlines()
for raw in csv.DictReader(rows, delimiter=","):
print(raw) # the raw will be a dictionary and you can use it well for any need.
</code></pre>
<p>each raw will loo... | 0 | 2016-09-27T12:19:44Z | [
"python",
"csv",
"pandas"
] |
How to separate a CSV file when there are "" lines? | 39,723,925 | <p>When I am reading in a CSV file that looks like this:</p>
<pre><code>To, ,New York ,Norfolk ,Charleston ,Savannah
Le Havre (Fri), ,15 ,18 ,22 ,24
Rotterdam (Sun) ,"",13 ,16 ,20 ,22
Hamburg (Thu) ,"",11 ,14 ,18 ,20
Southampton (Fri) , "" ,8 ,11 ,15 ,17
</code></pre>
<p>using pandas, as follows:</p>
<pre><c... | 2 | 2016-09-27T11:51:01Z | 39,724,573 | <p>You need <code>quoting=csv.QUOTE_NONE</code> because there are <code>quoting</code> in <code>file</code>:</p>
<pre><code>df = pd.read_csv('TAT_AX1_westbound_style3.csv', quoting=csv.QUOTE_NONE)
print (df)
To New York Norfolk Charleston Savannah
0 Le Havre (Fri) ... | 3 | 2016-09-27T12:22:24Z | [
"python",
"csv",
"pandas"
] |
How to separate a CSV file when there are "" lines? | 39,723,925 | <p>When I am reading in a CSV file that looks like this:</p>
<pre><code>To, ,New York ,Norfolk ,Charleston ,Savannah
Le Havre (Fri), ,15 ,18 ,22 ,24
Rotterdam (Sun) ,"",13 ,16 ,20 ,22
Hamburg (Thu) ,"",11 ,14 ,18 ,20
Southampton (Fri) , "" ,8 ,11 ,15 ,17
</code></pre>
<p>using pandas, as follows:</p>
<pre><c... | 2 | 2016-09-27T11:51:01Z | 39,724,665 | <p>From your sample you have provided, it is clear that the problem is with the data set and pandas is working correctly.</p>
<p>Only the first row is separated correctly, the second row is all in one column; as a single string (pay attention to the <code>"</code>). If I replace the <code>,</code> with <code>|</code>,... | 0 | 2016-09-27T12:26:03Z | [
"python",
"csv",
"pandas"
] |
Pandas and apply function to match a string | 39,724,182 | <p>I have a df column containing various links, some of them containing the string <code>"search"</code>.</p>
<p>I want to create a function that - being applied to the column - returns a column containing <code>"search"</code> or <code>"other"</code>.</p>
<p>I write a function like:</p>
<pre><code>search = 'search'... | 1 | 2016-09-27T12:04:36Z | 39,724,270 | <p>I think you need <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>:</p>
<pre><code>df = pd.DataFrame({'link':['search','homepage d','login dd', 'profile t', 'ff']})
print (df)
link
0 search
1 homepage d
2 login dd
3 ... | 0 | 2016-09-27T12:08:59Z | [
"python",
"string",
"pandas",
"condition",
"contains"
] |
Pandas and apply function to match a string | 39,724,182 | <p>I have a df column containing various links, some of them containing the string <code>"search"</code>.</p>
<p>I want to create a function that - being applied to the column - returns a column containing <code>"search"</code> or <code>"other"</code>.</p>
<p>I write a function like:</p>
<pre><code>search = 'search'... | 1 | 2016-09-27T12:04:36Z | 39,724,774 | <p><code>.str</code> applies to the whole Series but here you are dealing with the value inside the Series.</p>
<p>You can either do : <code>df['link'].str.contains(search)</code><br>
Or like you want : <code>df['link'].apply(lambda x: 'Search' if search in x else 'Other')</code></p>
<p><strong>Edit</strong> </p>
... | 1 | 2016-09-27T12:31:26Z | [
"python",
"string",
"pandas",
"condition",
"contains"
] |
Pandas and apply function to match a string | 39,724,182 | <p>I have a df column containing various links, some of them containing the string <code>"search"</code>.</p>
<p>I want to create a function that - being applied to the column - returns a column containing <code>"search"</code> or <code>"other"</code>.</p>
<p>I write a function like:</p>
<pre><code>search = 'search'... | 1 | 2016-09-27T12:04:36Z | 39,726,510 | <p>You can use also a <code>list comprehesion</code> if you want to find the word search within a link:</p>
<p>Fo example:</p>
<pre><code>df['Search'] = [('search' if 'search' in item else 'other') for item in df['link']]
</code></pre>
<p>The output:</p>
<pre><code> ColumnA link Search
0 ... | 0 | 2016-09-27T13:51:17Z | [
"python",
"string",
"pandas",
"condition",
"contains"
] |
Comparing strings in a list | 39,724,216 | <p>I'm trying to filter out search results from an API by trying to find and exclude dictionary entries which have 'affiliation names' which are all the same.</p>
<p>To cut a long story short, in the code below, entry2 is a list of 20 dictionaries all of which have nested dictionaries within them, one of which is 'aff... | 1 | 2016-09-27T12:06:29Z | 39,724,340 | <p>The <em>filter</em> condition of your <em>list comprehension</em> is not properly structured. <code>any</code> returns a boolean which you're comparing with the <code>affilname</code> entry - a string. That would return all the entries since a string will never be equal to a boolean.</p>
<p>You can instead check if... | 2 | 2016-09-27T12:12:29Z | [
"python",
"python-3.5"
] |
HTTP/1.1 400 Bad Request. Bad number of command parts | 39,724,225 | <p>Im trying to execute the following code from Chapter 12 of the book "Python for Informatics". </p>
<pre><code>import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))
mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
while True:
data = my... | 1 | 2016-09-27T12:06:46Z | 39,724,680 | <p>You need to change
mysock.send('GET <a href="http://www.py4inf.com/code/romeo.txt" rel="nofollow">http://www.py4inf.com/code/romeo.txt</a> HTTP/1.0\n \n')
to</p>
<pre><code>mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\r \n')
</code></pre>
<p>To properly end a stream of bytes, you need to use ... | -1 | 2016-09-27T12:26:33Z | [
"python",
"sockets",
"http",
"web",
"bad-request"
] |
HTTP/1.1 400 Bad Request. Bad number of command parts | 39,724,225 | <p>Im trying to execute the following code from Chapter 12 of the book "Python for Informatics". </p>
<pre><code>import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))
mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
while True:
data = my... | 1 | 2016-09-27T12:06:46Z | 39,724,949 | <p>On your Python installation, machine, or your network, something is rewriting requests and injecting its own code. Prime suspects are</p>
<ul>
<li>Anything marketed as "Anti-Virus"</li>
<li>Anything marketed as "Network Security Solution"</li>
<li>Malware on your computer or router</li>
<li>A network-wide (transpar... | 1 | 2016-09-27T12:40:13Z | [
"python",
"sockets",
"http",
"web",
"bad-request"
] |
Pandas extract comment lines | 39,724,298 | <p>I have a data file containing a first few lines of comments and then the actual data.</p>
<pre><code>#param1 : val1
#param2 : val2
#param3 : val3
12
2
1
33
12
0
12
...
</code></pre>
<p>I can read the data as <code>pandas.read_csv(filename, comment='#',header=None)</code>. However I also wish to separately read th... | 0 | 2016-09-27T12:10:28Z | 39,724,905 | <p>In the call to <code>read_csv</code> you can't really. If you're just processing a header you can open the file, extract the commented lines and process them, then read in the data in a separate call.</p>
<pre><code>from itertools import takewhile
with open(filename, 'r') as fobj:
# takewhile returns an iterato... | 2 | 2016-09-27T12:38:27Z | [
"python",
"pandas"
] |
Pandas extract comment lines | 39,724,298 | <p>I have a data file containing a first few lines of comments and then the actual data.</p>
<pre><code>#param1 : val1
#param2 : val2
#param3 : val3
12
2
1
33
12
0
12
...
</code></pre>
<p>I can read the data as <code>pandas.read_csv(filename, comment='#',header=None)</code>. However I also wish to separately read th... | 0 | 2016-09-27T12:10:28Z | 39,725,204 | <p>Maybe you can read this file again in normal way, read each line to get your parameters.</p>
<pre><code>def get_param( filename):
para_dic = {}
with open(filename,'r') as cmt_file: # open file
for line in cmt_file: # read each line
if line[0] == '#': # check the first character... | 1 | 2016-09-27T12:52:12Z | [
"python",
"pandas"
] |
Tree view in django template | 39,724,358 | <p>I try to create simple TODOList app. Where you can create Project, then create tasks for project, subtasks for tasks and subtasks. I create a template to show task:</p>
<pre><code><li class='task'>
<div class="collapsible-header" id="task-name"> {{task.title}}</div>
<div class="collapsible-body... | 0 | 2016-09-27T12:13:18Z | 39,729,832 | <p>The <em>global</em> var's name is <code>task</code>. But your <em>local</em> var is <strong>also</strong> called <code>task</code>.</p>
<pre><code>{% for task in project.tasks.all %}
{% include 'ProjectManager/views/task_view.html' with task=task%}
{%endfor%}
</code></pre>
<p>so i guess what you where <em>tryi... | 0 | 2016-09-27T16:26:59Z | [
"python",
"django",
"django-templates"
] |
Form wizard with ModelForms having parameters in __init__ | 39,724,387 | <p>I am using python 2.7, Django 1.9.4 on Ubuntu 14.04.</p>
<p>I have been struggling with django-formtools (specifically form wizard) for quite a few days now. The scenario is as follows:</p>
<p>The form wizard is just a 2 step process:</p>
<ol>
<li>1st step: I have a ModelForm based on a Model. The form's <code>__... | 0 | 2016-09-27T12:14:46Z | 39,725,194 | <p>You need to override <a href="https://django-formtools.readthedocs.io/en/latest/wizard.html#formtools.wizard.views.WizardView.get_form_kwargs" rel="nofollow"><code>get_form_kwargs</code></a> and include the <code>user_id</code>.</p>
<pre><code>class CreatePublisherWizard(SessionWizardView):
...
def get_form... | 0 | 2016-09-27T12:51:35Z | [
"python",
"django",
"python-2.7",
"django-formwizard"
] |
Sqlite date field error for transactions | 39,724,411 | <p>trying to build two databases, one for houses, and another for the dates and prices that they were sold for in the last 16 years </p>
<pre><code>conn = sqlite3.connect('houses_in_london.db')
database = conn.cursor()
database.execute('CREATE TABLE houses (id INTEGER PRIMARY KEY, address TEXT,'
' are... | 1 | 2016-09-27T12:15:45Z | 39,724,551 | <p>This more concise syntax does the needeful</p>
<pre><code>database.execute(
'CREATE TABLE transactions (transaction_id INTEGER, house_id INTEGER '
'REFERENCES houses(id), date TEXT, sale_price INTEGER )')
</code></pre>
<p>Alternatively, you need to move the constraints to the end of the create statement</p>
... | 1 | 2016-09-27T12:21:56Z | [
"python",
"database",
"sqlite"
] |
Sqlite date field error for transactions | 39,724,411 | <p>trying to build two databases, one for houses, and another for the dates and prices that they were sold for in the last 16 years </p>
<pre><code>conn = sqlite3.connect('houses_in_london.db')
database = conn.cursor()
database.execute('CREATE TABLE houses (id INTEGER PRIMARY KEY, address TEXT,'
' are... | 1 | 2016-09-27T12:15:45Z | 39,724,912 | <p>From the docs: </p>
<blockquote>
<p>CREATE TABLE includes one or more column definitions, optionally followed by a list of table constraints.</p>
</blockquote>
<p><a href="https://www.sqlite.org/lang_createtable.html" rel="nofollow">https://www.sqlite.org/lang_createtable.html</a></p>
<p>This is syntactiaclly a... | 0 | 2016-09-27T12:38:36Z | [
"python",
"database",
"sqlite"
] |
matlab to python port optimization | 39,724,538 | <p>I have ported a matlab piece of code to python and faced problems with efficiency.</p>
<p>For instance, here comes a snippet : </p>
<pre><code>G = np.vstack((Gx.toarray(), Gy.toarray(), Gd1.toarray(), Gd2.toarray()))
</code></pre>
<p>Here all elements to be stacked are 22500 by 22500 sparce matrices. It dies dire... | 1 | 2016-09-27T12:21:02Z | 39,725,023 | <p>For stacking sparse matrices, you can use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.vstack.html" rel="nofollow">Scipy sparse's vstack function</a> instead of NumPy's <code>vstack</code> one, like so -</p>
<pre><code>import scipy.sparse as sp
Gout = sp.vstack((Gx,Gy,Gd1,Gd2))
</code>... | 1 | 2016-09-27T12:43:01Z | [
"python",
"matlab",
"numpy"
] |
Pandas broadcasting values given logical condition in group by | 39,724,586 | <p>I have a data fram according to example below:</p>
<pre>
key1 key2 value1
1 201501 NaN
1 201502 NaN
1 201503 201503
1 201504 NaN
2 201507 NaN
2 201508 NaN
2 201509 NaN
3 201509 NaN
3 201510 201509
3 ... | 1 | 2016-09-27T12:22:55Z | 39,724,878 | <p>IIUC you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.ffill.html" rel="nofollow"><code>ffill</code></a>:</p>
<pre><code>df['value2'] = df.groupby('key1')['value1'].ffill()
df.value2 = np.where(df.value2.notnull(),1,0)
print (df)
key1 key2 value1 v... | 0 | 2016-09-27T12:36:29Z | [
"python",
"pandas",
"transform"
] |
Pandas broadcasting values given logical condition in group by | 39,724,586 | <p>I have a data fram according to example below:</p>
<pre>
key1 key2 value1
1 201501 NaN
1 201502 NaN
1 201503 201503
1 201504 NaN
2 201507 NaN
2 201508 NaN
2 201509 NaN
3 201509 NaN
3 201510 201509
3 ... | 1 | 2016-09-27T12:22:55Z | 39,724,927 | <p>You can do:</p>
<pre><code>df['value2'] = df.groupby('key1')['value1'].apply(lambda x: (~pd.isnull(x)).cumsum())
In [50]: df
Out[50]:
key1 key2 value1 value2
0 1 201501 NaN 0
1 1 201502 NaN 0
2 1 201503 201503 1
3 1 201504 NaN 1
4 2 201507 ... | 0 | 2016-09-27T12:39:20Z | [
"python",
"pandas",
"transform"
] |
Bold text with asterisks | 39,724,626 | <p>In my Django project I want to make text bold if asterisks <code>*</code> are there at the start and end of text, the same feature we have here on Stack Overflow. Although I convert <code>**</code> to <code><b></code>, due to output escaping it becomes <code>&lt;b&gt;</code>. What is the right approach... | -1 | 2016-09-27T12:24:38Z | 39,724,740 | <p>if you want the full suite of all markdown features, go with an existing markdown library.</p>
<p>if you just want <b> to print directly to the source code w/o escaping, use</p>
<pre><code> {{ some_var|safe }}
</code></pre>
| 0 | 2016-09-27T12:29:16Z | [
"python",
"django"
] |
Bold text with asterisks | 39,724,626 | <p>In my Django project I want to make text bold if asterisks <code>*</code> are there at the start and end of text, the same feature we have here on Stack Overflow. Although I convert <code>**</code> to <code><b></code>, due to output escaping it becomes <code>&lt;b&gt;</code>. What is the right approach... | -1 | 2016-09-27T12:24:38Z | 39,727,294 | <p>I did it in following way.</p>
<p>views.py</p>
<pre><code>i.description = i.description.split() #use of split()
</code></pre>
<p>template file (format_text is <code>custom template filter</code>)</p>
<pre><code>{% for text in anidea.description %}
{{ text|format_text }}
{% endfor %}
</code></pre>
<p>filt... | 0 | 2016-09-27T14:25:23Z | [
"python",
"django"
] |
Get the range of colors in an image using Python OpenCV | 39,724,764 | <p>I'm trying to build a portable green screen photo booth. There's no way to know the lighting conditions ahead of time so I can't hard code the the color values for chroma key.</p>
<p>I thought the easiest way to get around this issue would be to build a calibration script that will take a picture of the blank backg... | 1 | 2016-09-27T12:31:12Z | 39,732,275 | <p>HUE colors have specified intervals, get the green interval and then do an <code>inRange</code> using it, ignoring the saturation and value, that would give you all degrees of green, to minimize noise much, make the value range to be from 20% to 80%, that would avoid the too much light, or too much dark regions, and... | 1 | 2016-09-27T18:52:10Z | [
"python",
"opencv"
] |
I get a linear regression using the SVR by python scikit-learn when the data is not linear | 39,724,999 | <pre><code>train.sort_values(by=['mass'], ascending=True, inplace=True)
x = train['mass']
y = train['pa']
# Fit regression model
svr_rbf = SVR(kernel='rbf', C=1e3, gamma=0.1)
svr_lin = SVR(kernel='linear', C=1e3)
svr_poly = SVR(kernel='poly', C=1e3, degree=2)
x_train = x.reshape(x.shape[0], 1)
x = x_train
y_rbf = svr_... | 0 | 2016-09-27T12:41:54Z | 39,733,330 | <p>Most likely has to do with the scale of your data. You are using the same penalty hyper-parameter as they are in the example, but your y values are orders of magnitude greater. Thus, the SVR algorithm will favor simplicity over accuracy since your penalty for error is now small compared to your y values. You need to... | 0 | 2016-09-27T20:01:22Z | [
"python",
"machine-learning",
"scikit-learn",
"svm"
] |
How do I execute multiple shell commands with a single python subprocess call? | 39,725,120 | <p>Ideally it should be like a list of commands that I want to execute and execute all of them using a single subprocess call. I was able to do something similar by storing all the commands as a shell script and calling that script using subprocess, but I want a pure python solution.I will be executing the commands wit... | 0 | 2016-09-27T12:47:25Z | 39,725,358 | <p>Use semicolon to chain them if they're independent.</p>
<p>For example, (Python 3)</p>
<pre><code>>>> import subprocess
>>> result = subprocess.run('echo Hello ; echo World', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
>>> result
CompletedProcess(args='echo Hello ; echo... | 0 | 2016-09-27T12:59:44Z | [
"python",
"subprocess"
] |
insertion sort in python not working | 39,725,226 | <p>I have tried the following code for insertion sort in python</p>
<pre><code>a=[int(x) for x in input().split()]
for i in range(1,len(a)):
temp=a[i]
for k in range (i,1,-1):
a[k]=a[k-1]
if a[k]<temp:
a[k]=temp
break
print(a)
</code></pre>
<p>input: 6 4 3 2 5 8 1</p... | -4 | 2016-09-27T12:52:58Z | 39,725,917 | <p>It <em>does not work</em> because your implementation is faulty.<br>
When trying to shift the partially sorted list, you overwrite existing numbers by assigning <code>a[k] = a[k-1]</code> -- but where's the former value of <code>a[k]</code> then?</p>
<p>A very basic solution (yet not in-place as the original defini... | 0 | 2016-09-27T13:26:51Z | [
"python",
"insertion-sort"
] |
Nested defaultdicts | 39,725,255 | <p>Why does the below work</p>
<pre><code>x = defaultdict(dict)
for a,b,c in [('eg', 'ef', 'ee'), ('eg', 'eu', 'e4'), ('kk', 'nn', 'bb')]:
x[a][b] = c
</code></pre>
<p>And the below throws an error ?</p>
<pre><code>x = defaultdict(dict)
for a,b,c,d in [('eg', 'ef', 'ee', 'gg'), ('eg', 'eu', 'e4', 'hh'),
... | 1 | 2016-09-27T12:54:11Z | 39,735,596 | <p>The issue here is that <code>defaultdict</code> accepts a callable, which is used as a factory to generate the value when a key is missing. Once you understand that, the behaviour is clear:</p>
<pre><code>x = defaultdict(dict)
x # it's a default dict
x['a'] # it's just a dict()
x[... | 1 | 2016-09-27T22:58:32Z | [
"python",
"python-2.7"
] |
DeprecationWarning while using knn algorithm in scikit-learn | 39,725,403 | <p>I am trying my hands on scikit-learn library. I imported the iris dataset, and tried to train knn algorithm to predict some outcomes. Here is the code:</p>
<pre><code>from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
iris = datasets.load_iris()
knn = KNeighborsClassifier(n_neighbors=... | -2 | 2016-09-27T13:02:02Z | 39,738,702 | <p>Thank you @tttthomasssss for the help. Here is what I was doing wrong:</p>
<p>When I write <code>[3, 4, 5, 2]</code>, python interprets it as an array of dimensions 4X1, but when I write <code>[[3, 4, 5, 2]]</code>, python interprets it as 1X4 array. Since it is one data point having 4 different values for differen... | 0 | 2016-09-28T05:27:10Z | [
"python",
"scikit-learn",
"knn"
] |
Checking if element in list by substring | 39,725,411 | <p>I have a list of urls (<code>unicode</code>), and there is a lot of repetition.
For example, urls <code>http://www.myurlnumber1.com</code> and <code>http://www.myurlnumber1.com/foo+%bar%baz%qux</code> lead to the same place.</p>
<p>So I need to weed out all of those duplicates.</p>
<p>My first idea was to check if... | 5 | 2016-09-27T13:02:35Z | 39,725,573 | <p>You can try adding another for loop, if you are fine with that.
Something like:</p>
<pre><code>for url in list:
for i in range(len(list)):
if url[:30] not in list[i]:
print(url)
</code></pre>
<p>That will compare every word with every other word to check for sameness. That's just an exa... | 0 | 2016-09-27T13:10:53Z | [
"python",
"list"
] |
Checking if element in list by substring | 39,725,411 | <p>I have a list of urls (<code>unicode</code>), and there is a lot of repetition.
For example, urls <code>http://www.myurlnumber1.com</code> and <code>http://www.myurlnumber1.com/foo+%bar%baz%qux</code> lead to the same place.</p>
<p>So I need to weed out all of those duplicates.</p>
<p>My first idea was to check if... | 5 | 2016-09-27T13:02:35Z | 39,725,580 | <p>If you consider any netloc's to be the same you can parse with <a href="https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlparse" rel="nofollow"><code>urllib.parse</code></a></p>
<pre><code>from urllib.parse import urlparse # python2 from urlparse import urlparse
u = "http://www.myurlnumber1.co... | 6 | 2016-09-27T13:11:02Z | [
"python",
"list"
] |
Solving sets of non-linear equations as an array | 39,725,419 | <p>I'm trying to solve for the intersection of the two equations: <code>y=Rx^1.75</code> and <code>y=ax^2+bx+c</code> for all rows in my dataframe (about 100K rows). Each value of <code>R,a,b,c</code> is different for each row. I can solve them one by one by iterating through the dataframe and calling <code>fsolve()<... | 1 | 2016-09-27T13:02:56Z | 39,726,868 | <p>Maybe you can use Newton's method:</p>
<pre><code>import numpy as np
data = np.array(
[[0.5, -0.01, -0.50, 32.42],
[0.6, 0.00, 0.07, 14.12],
[0.7, -0.01, -0.50, 32.42]])
R, a, b, c = data.T
x = np.full(a.shape, 10.0)
m = 1.0
for i in range(20):
x = x - m * (-R*x**1.75 + a*x**2 + b*x + c)/... | 0 | 2016-09-27T14:06:36Z | [
"python",
"pandas",
"numpy",
"scipy"
] |
Solving sets of non-linear equations as an array | 39,725,419 | <p>I'm trying to solve for the intersection of the two equations: <code>y=Rx^1.75</code> and <code>y=ax^2+bx+c</code> for all rows in my dataframe (about 100K rows). Each value of <code>R,a,b,c</code> is different for each row. I can solve them one by one by iterating through the dataframe and calling <code>fsolve()<... | 1 | 2016-09-27T13:02:56Z | 39,730,719 | <p>You could get rid of one variable, then use Numpy's array broadcasting:</p>
<pre><code># Your `df`:
#R a b c x y
#0 0.5 -0.01 -0.50 32.42 9.69483 26.6327
#1 0.6 0.00 0.07 14.12 6.18463 14.5529
#2 0.7 -0.01 -0.50 32.42 8.17467 27.6644
# Solved in one go
coefs = df.values[:, 0:4]
def... | 0 | 2016-09-27T17:17:53Z | [
"python",
"pandas",
"numpy",
"scipy"
] |
Only allowing a loop of odd numbers in a function | 39,725,498 | <p>I am teaching myself python but am getting really stuck on this question. It asks to "Write a function which accepts as input a list of odd numbers. Loop over the list of odd numbers and turn each into an even number. Store each even number in a new list and return that new list." </p>
<p>I'm happy with the latter ... | 1 | 2016-09-27T13:07:15Z | 39,725,727 | <p>I would agree with the comments by @jonrsharpe, @ShadowRanger, and @deceze that you probably don't need to include testing, but it wouldn't hurt. I'll use @deceze's line for that check here. Remember, you must declare your list <strong>outside</strong> the loop using it, or the loop will reset it each iteration. ... | 2 | 2016-09-27T13:18:05Z | [
"python",
"list",
"function",
"for-loop"
] |
Extract string from regex | 39,725,519 | <p>For the below python code, I am using regex to parse the string. However I am struggling to extract the string from the matched pattern.</p>
<pre><code>import re
rx = re.compile(
r'^(?P<interesting>.+?)-(?P<uid>\b\w{8}-(?:\w{4}-){3}\w{12}\b)(?P<junk>.+)$',
re.MULTILINE | re.VERBOSE)
test... | 0 | 2016-09-27T13:08:15Z | 39,725,826 | <p>You have a named group in your regex so just use it:</p>
<pre><code>import re
rx = re.compile(r'^(?P<interesting>.+?)-(?P<uid>\b\w{8}-(?:\w{4}-){3}\w{12}\b)(?P<junk>.+)$', re.MULTILINE | re.VERBOSE)
test_str = u"00000 Gin-12-a19ea68e-64bf-4471-b4d1-44f6bd9c1708-62fa6ae2-599c-4ff1-8249-bf6411ce3b... | 1 | 2016-09-27T13:23:07Z | [
"python",
"regex"
] |
How to convert to json file formate in python | 39,725,906 | <p>Here is my output:</p>
<pre><code>xyz information
+-----+------+------+
| A | B | C |
+-----+------+------+
| 23 | 76 | 87 |
| 76 | 36 | 37 |
| 83 | 06 | 27 |
+-----+------+------+
</code></pre>
<p>I want to convert this output to json format in python
can anybody suggest how to do that.</p>... | -2 | 2016-09-27T13:26:21Z | 39,726,666 | <p>Given</p>
<pre><code>xyz = '''+-----+------+------+
| A | B | C |
+-----+------+------+
| 23 | 76 | 87 |
| 76 | 36 | 37 |
| 83 | 06 | 27 |
+-----+------+------+'''
</code></pre>
<p>Do</p>
<pre><code>import json
import collections
xyz_rows = [map(str.strip, row.split('|')[1:-1]) for row in ... | 0 | 2016-09-27T13:57:26Z | [
"python",
"json",
"python-2.7"
] |
Django 1.9 pushing our code to go live today but have static directory issue | 39,725,934 | <p>We are pushing our code up to go live today, and before we do I need to figure out where to put my static files. I have in the project directory a folder called static. Inside I have an admin and an image folder. When looking through the docs it looks like these should not be placed inside the actual project. But in... | 0 | 2016-09-27T13:27:22Z | 39,726,772 | <p>Basically what you have to do, is to tell django STATICFILES_DIR settings where all your static folder live</p>
<pre><code>STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
os.path.join(BASE_DIR, 'mycssfolder'),
os.path.join(BASE_DIR, 'otherstaticfolder')
]
</code></pre>
<p>so when you run django... | 0 | 2016-09-27T14:01:47Z | [
"python",
"django",
"django-admin",
"django-staticfiles"
] |
Django 1.9 pushing our code to go live today but have static directory issue | 39,725,934 | <p>We are pushing our code up to go live today, and before we do I need to figure out where to put my static files. I have in the project directory a folder called static. Inside I have an admin and an image folder. When looking through the docs it looks like these should not be placed inside the actual project. But in... | 0 | 2016-09-27T13:27:22Z | 39,726,869 | <p>You can store your static files in multiple folders which can reside anywhere</p>
<p>It will look like this in settings</p>
<pre><code>STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
#You can have multiple directories here
)
</code></pre>
<p>Set the STATIC_ROOT like this in settings</p>
<pre><code... | 1 | 2016-09-27T14:06:37Z | [
"python",
"django",
"django-admin",
"django-staticfiles"
] |
Python - In-line boolean evaluation without IF statements | 39,726,028 | <p>I am trying to assess the value of a column of a dataframe to determine the value of another column. I did this by using an <code>if</code> statement and <code>.apply()</code> function successfully. I.e. </p>
<pre><code>if Col x < 0.3:
return y
elif Col x > 0.6:
return z
</code></pre>
<p>Etc. The p... | 0 | 2016-09-27T13:31:19Z | 39,740,389 | <p>From what I have read so far, the performance gap is issued by the <em>parser</em> backend chosen by <code>pandas</code>. There's the regular python parser as a backand and, additionally, a pandas parsing backend.<br>
The docs say, that there is no performance gain if using plain old python over pandas here: <a href... | 1 | 2016-09-28T07:10:14Z | [
"python",
"performance",
"if-statement",
"boolean",
"apply"
] |
difference between range / len etc. when iterating over tuples | 39,726,103 | <p>One thing upfront: I am fairly now to the coding world so maybe my question is a bit stupid ... I was trying to write a function that returns the every other element of a tuple. The easiest way obviously is </p>
<pre><code>def oddTuples(aTup):
return aTup[::2]
</code></pre>
<p>I tried to solve it differently ... | 0 | 2016-09-27T13:34:18Z | 39,726,269 | <pre><code>newTup = ()
b = True
for i in aTup:
if b:
newTup = newTup + (i,)
b = not b
return newTup
</code></pre>
<p>Try that on for size. The <code>for</code> statement gives us the tuple values one by one, and the <code>boolean</code> b lets us skip every other one. </p>
<p>The best way to do this... | 0 | 2016-09-27T13:41:32Z | [
"python",
"for-loop",
"range",
"iteration",
"tuples"
] |
difference between range / len etc. when iterating over tuples | 39,726,103 | <p>One thing upfront: I am fairly now to the coding world so maybe my question is a bit stupid ... I was trying to write a function that returns the every other element of a tuple. The easiest way obviously is </p>
<pre><code>def oddTuples(aTup):
return aTup[::2]
</code></pre>
<p>I tried to solve it differently ... | 0 | 2016-09-27T13:34:18Z | 39,726,284 | <pre><code>for i in len(aTup):
</code></pre>
<p>Will raise an error because <code>len()</code> returns an integer which can not be iterated over in a <code>for</code> loop.</p>
<p>In the case of:</p>
<pre><code>for i in range(len(aTup)):
</code></pre>
<p>In each iteration of the loop <code>i</code> will be an integ... | 0 | 2016-09-27T13:41:46Z | [
"python",
"for-loop",
"range",
"iteration",
"tuples"
] |
difference between range / len etc. when iterating over tuples | 39,726,103 | <p>One thing upfront: I am fairly now to the coding world so maybe my question is a bit stupid ... I was trying to write a function that returns the every other element of a tuple. The easiest way obviously is </p>
<pre><code>def oddTuples(aTup):
return aTup[::2]
</code></pre>
<p>I tried to solve it differently ... | 0 | 2016-09-27T13:34:18Z | 39,726,287 | <p>The <code>i</code> will not give you the index instead it will return the value.</p>
<p>You can solve your problem simply by defining a local variable that can be incriminated for each iteration and use that to get the odd indexed values.</p>
<p>Summery: Use a local variable to act as an index as Python for will r... | 0 | 2016-09-27T13:42:02Z | [
"python",
"for-loop",
"range",
"iteration",
"tuples"
] |
difference between range / len etc. when iterating over tuples | 39,726,103 | <p>One thing upfront: I am fairly now to the coding world so maybe my question is a bit stupid ... I was trying to write a function that returns the every other element of a tuple. The easiest way obviously is </p>
<pre><code>def oddTuples(aTup):
return aTup[::2]
</code></pre>
<p>I tried to solve it differently ... | 0 | 2016-09-27T13:34:18Z | 39,726,292 | <p>Here is an example you can use to finish the program.</p>
<pre><code>myTup = (1,2,3,4,5,6,7,8)
for i in range(len(myTup)):
if i%2 != 0:
print("Tuple items: " ,myTup[i])
print("i here is: " , i)
</code></pre>
<p><strong>len</strong> -> gives you the length of a object ; eg. if you say len(myTup... | 1 | 2016-09-27T13:42:17Z | [
"python",
"for-loop",
"range",
"iteration",
"tuples"
] |
difference between range / len etc. when iterating over tuples | 39,726,103 | <p>One thing upfront: I am fairly now to the coding world so maybe my question is a bit stupid ... I was trying to write a function that returns the every other element of a tuple. The easiest way obviously is </p>
<pre><code>def oddTuples(aTup):
return aTup[::2]
</code></pre>
<p>I tried to solve it differently ... | 0 | 2016-09-27T13:34:18Z | 39,726,296 | <p>Python's <code>for</code> loop is a <a href="https://en.wikipedia.org/wiki/Foreach_loop" rel="nofollow"><em>foreach</em> construct</a>; it'll loop over a sequence or iterable and bind the target variable (<code>i</code> in your case) to each element in that sequence one by one.</p>
<p>So for <code>for i in aTuple:<... | 0 | 2016-09-27T13:42:37Z | [
"python",
"for-loop",
"range",
"iteration",
"tuples"
] |
Dictionary of dictionaries vs dictionary of class instances | 39,726,124 | <p>I understand what a class is, a bundle of attributes and methods stored together in one object. However, i don't think i have ever really grasped their full power. I taught myself to manipulate large volumes of data by using 'dictionary of dictionary' data structures. I'm now thinking if i want to fit in with the re... | 3 | 2016-09-27T13:35:32Z | 39,728,328 | <p>I am trying to guess what you are trying to do since I have no idea what your "row" looks like. I assume you have the variable <code>columns</code> which is a list of column names. If that is the case, please consider this code snippet:</p>
<pre><code>class SalesOrder(object):
def __init__(self, columns, row):
... | 1 | 2016-09-27T15:14:47Z | [
"python",
"class",
"dictionary"
] |
Dictionary of dictionaries vs dictionary of class instances | 39,726,124 | <p>I understand what a class is, a bundle of attributes and methods stored together in one object. However, i don't think i have ever really grasped their full power. I taught myself to manipulate large volumes of data by using 'dictionary of dictionary' data structures. I'm now thinking if i want to fit in with the re... | 3 | 2016-09-27T13:35:32Z | 39,730,180 | <p>Classes are mostly useful for coupling data to behaviour, and for providing structure (naming and documenting the association of certain properties, for example).</p>
<p>You're not doing either of those here - there's no real behaviour in your class (it doesn't <em>do</em> anything to the data), and all the structu... | 1 | 2016-09-27T16:46:12Z | [
"python",
"class",
"dictionary"
] |
How to find Bragg reflexes fast with numpy? | 39,726,139 | <p>For x-ray diffraction one needs to find the solutions to the so called Laue-Equation</p>
<p>G_hkl - k_in + |k_in|*(sin(theta) cos(phi) , sin(theta) sin(phi) , cos(theta))=0</p>
<p>where G_hkl is a given 3 dimensional vector, k_in can be chosen as (0,0,1) and theta and phi are free parameters to fulfill the equatio... | 1 | 2016-09-27T13:36:13Z | 39,727,260 | <p>There's a dependency as <code>Ghkl</code> is being updated at each iteration and re-used at the next. The corresponding closed form might be difficult to trace out. So, I would focus on improving the performance on the rest of the code inside that innermost loop.</p>
<p>Now, there we are calculating <code>norm_vec<... | 3 | 2016-09-27T14:23:33Z | [
"python",
"performance",
"numpy",
"scientific-computing"
] |
NetworkX: How do I iteratively apply a network layout like spring_layout? | 39,726,267 | <p>I have a graph <code>G</code> and I want to layout the graph using the function </p>
<p><code>node_positions=nx.spring_layout(G, iterations=5)</code></p>
<p>However, I want to apply this function say 10 times and see how the layout changes with each application. Seems like every time I apply it, it starts from scr... | 0 | 2016-09-27T13:41:22Z | 39,727,780 | <p><code>spring_layout</code> takes an argument <code>pos</code> which serves as the initial condition.</p>
<p>So <code>pos = nx.spring_layout(G, pos= pos, iterations=5)</code> will work. For the first time through, just set <code>pos=None</code>.</p>
| 1 | 2016-09-27T14:49:08Z | [
"python",
"graph",
"networkx"
] |
How to authenticate user for a specific object rather than whole class in django? | 39,726,291 | <p>I am working on making an app to add clubs in website. This is my model.py file</p>
<pre><code>from django.db import models
from stdimage import StdImageField
# Create your models here.
class Club(models.Model):
ClubName = models.CharField(max_length=200)
ClubLogo = StdImageField(upload_to='club_logo', va... | -3 | 2016-09-27T13:42:08Z | 39,726,397 | <p>This is a problem with which many users have been struggling with. </p>
<p>I have been using couple of external packages, and couple of self made solutions. But the best one I have found so far is <a href="https://github.com/django-guardian/django-guardian" rel="nofollow">Django Guardian</a> It's an implementation ... | 1 | 2016-09-27T13:46:50Z | [
"python",
"django"
] |
Dynamic renormalize in matplotlib after set_data | 39,726,334 | <p>I am making an interactive display of 3d data in 2d via .imshow() method. I let the user to change the mode between viewing a single 2d layer and viewing the sum along all 2d layers. This results in large changes of range of the displayed values. For this reason keeping the same color mapping all the time results in... | 0 | 2016-09-27T13:44:02Z | 39,731,470 | <pre><code>import matplotlib.pyplot as plt
import numpy as np
fig, (ax1, ax2) = plt.subplots(1, 2)
data = np.random.rand(10, 10)
im1 = ax1.imshow(data, interpolation='none', cmap='viridis')
im2 = ax2.imshow(data, interpolation='none', cmap='viridis')
im2.set_clim(0, .5)
</code></pre>
<p><a href="http://i.stack.imgu... | 0 | 2016-09-27T18:03:56Z | [
"python",
"matplotlib"
] |
Counting occurrence of a gender in a dataframe by age | 39,726,335 | <p>I have a dataframe like</p>
<pre><code>age gender
69 M
29 F
61 F
66 F
52 M
</code></pre>
<p>What I would like to know is how many males and females there are in each age group. Is there somehow I could use <code>groupby</code> to group the data by age and then use <code>agg</code> to count the instances of m... | 1 | 2016-09-27T13:44:03Z | 39,726,358 | <p>you can groupby age AND gender:</p>
<pre><code>df.groupby(['age','gender']).size()
df.reset_index(inplace=True)
</code></pre>
<p>will give</p>
<pre><code>age gender
69 M 1
29 F 1
61 F 1
66 F 1
52 M 1
</code></pre>
| 3 | 2016-09-27T13:45:02Z | [
"python",
"pandas"
] |
How to subtract QPainterPaths, QPolygon? | 39,726,477 | <p>I'm trying to understand how <code>path1.subtracted(path2)</code> works. </p>
<ul>
<li><p>I have path1 and path2: <a href="http://i.stack.imgur.com/HcyA0.png" rel="nofollow"><img src="http://i.stack.imgur.com/HcyA0.png" alt="image1"></a></p></li>
<li><p>And I'm getting path3 using <code>path3=path1.subtracted(path2... | 2 | 2016-09-27T13:50:07Z | 39,733,789 | <p><code>QpainterPath.subtracted()</code> doesn't subtract path elements but path areas,
<a href="http://doc.qt.io/qt-5/qpainterpath.html#subtracted" rel="nofollow">see documentation</a></p>
<p>same effect if <code>QpainterPath::operator-()</code> is used:</p>
<pre><code> # path3 = self.path1.subtracted(self.... | 1 | 2016-09-27T20:33:02Z | [
"python",
"qt",
"pyqt",
"pyqt5"
] |
How can I out put an Excel file as Email attachment in SAP CMC? | 39,726,495 | <p>I have been trying to schedule a report in SAP BO CMC. This report was initially written in Python and built into a .exe file. This .exe application runs to save the report into an .xlsx file in a local folder.
I want to utilize the convenient scheduling functions in SAP BO CMC to send the report in Emails. I tried... | 0 | 2016-09-27T13:50:54Z | 39,727,668 | <p>It's kind of hack-ish, but it can be done. Have the program (exe) write out the bytes of the Excel file to standard output. Then configure the program object for email destination, and set the filename to a specific name (ex. "whatever.xlsx").</p>
<p>When emailing a program object, the attached file will contain ... | 1 | 2016-09-27T14:42:26Z | [
"python",
"excel",
"email",
"sap",
"business-objects"
] |
How to determine what fields are required by a REST API, from the API? | 39,726,577 | <p>I'm working with a networking appliance that has vague API documentation. I'm able to execute PATCH and GET requests fine, but POST isn't working. I receive HTTP status error 422 as a response, I'm missing a field in the JSON request, but I am providing the required fields as specified in the documentation. I have t... | 3 | 2016-09-27T13:54:04Z | 39,726,781 | <p>No this does not exist in general. Some services support an OPTIONS request to the route in question, which should return you documentation about the route. If you are lucky this is machine generated from the same source code that implements the route, so is more accurate than static documentation. However, it may j... | 1 | 2016-09-27T14:02:13Z | [
"python",
"rest",
"pycurl",
"http-status-code-422"
] |
Plot is behaving weird | 39,726,583 | <p>I am trying to plot some trajectories in 3D. I noticed that the plot function is behaving weird. </p>
<p>I defined a variable named <code>pos</code>, which is a 2 dimensional matrix. It has 3 columns, where each column represents a coordinate axis. Please see the complete code below-</p>
<pre><code>import numpy as... | 3 | 2016-09-27T13:54:21Z | 39,728,895 | <h2>The fix</h2>
<p>Replace the line</p>
<pre><code>ax.plot(pos[:, 0], pos[:, 1], pos[:, 2])
</code></pre>
<p>with</p>
<pre><code>ax.plot(list(pos[:, 0]), list(pos[:, 1]), list(pos[:, 2]))
</code></pre>
<p>and it will work as expected for global <code>pos</code>.</p>
<h2>Explanation</h2>
<p>The problem is that <... | 1 | 2016-09-27T15:40:15Z | [
"python",
"matplotlib"
] |
How can I travel through the words of a file in PYTHON? | 39,726,737 | <p>I have a file .txt and I want to travel through the words of it. I have a problem, I need to remove the punctuation marks before travelling through the words. I have tried this, but it isn't removing the punctuation marks.</p>
<pre><code>file=open(file_name,"r")
for word in file.read().strip(",;.:- '").split():
... | 2 | 2016-09-27T14:00:15Z | 39,726,900 | <p>The problem with your current method is that <code>.strip()</code> doesn't really do what you want. It removes leading and trailing characters (and you want to remove ones within the text), and if you want to specify characters in addition to whitespace, they need to be in a list.</p>
<p>Another problem is that th... | 2 | 2016-09-27T14:07:42Z | [
"python",
"python-2.7",
"text",
"punctuation"
] |
How can I travel through the words of a file in PYTHON? | 39,726,737 | <p>I have a file .txt and I want to travel through the words of it. I have a problem, I need to remove the punctuation marks before travelling through the words. I have tried this, but it isn't removing the punctuation marks.</p>
<pre><code>file=open(file_name,"r")
for word in file.read().strip(",;.:- '").split():
... | 2 | 2016-09-27T14:00:15Z | 39,726,956 | <p>I would remove the punctuation marks with the <code>replace</code> function after storing the words in a list like so:</p>
<pre><code>with open(file_name,"r") as f_r:
words = []
for row in f_r:
words.append(row.split())
punctuation = [',', ';', '.', ':', '-']
words = [x.replace(y, '') for y in punct... | 0 | 2016-09-27T14:10:27Z | [
"python",
"python-2.7",
"text",
"punctuation"
] |
How can I travel through the words of a file in PYTHON? | 39,726,737 | <p>I have a file .txt and I want to travel through the words of it. I have a problem, I need to remove the punctuation marks before travelling through the words. I have tried this, but it isn't removing the punctuation marks.</p>
<pre><code>file=open(file_name,"r")
for word in file.read().strip(",;.:- '").split():
... | 2 | 2016-09-27T14:00:15Z | 39,727,047 | <p>You can try using the <code>re</code> module:</p>
<pre><code>import re
with open(file_name) as f:
for word in re.split('\W+', f.read()):
print word
</code></pre>
<p>See the <a href="https://docs.python.org/2/library/re.html" rel="nofollow">re documentation</a> for more details.</p>
<p>Edit: In case of... | 1 | 2016-09-27T14:14:27Z | [
"python",
"python-2.7",
"text",
"punctuation"
] |
How can I travel through the words of a file in PYTHON? | 39,726,737 | <p>I have a file .txt and I want to travel through the words of it. I have a problem, I need to remove the punctuation marks before travelling through the words. I have tried this, but it isn't removing the punctuation marks.</p>
<pre><code>file=open(file_name,"r")
for word in file.read().strip(",;.:- '").split():
... | 2 | 2016-09-27T14:00:15Z | 39,727,067 | <p><code>strip()</code>only removes characters found at the beginning or end of a string.
So <code>split()</code> first to cut into words, then <code>strip()</code> to remove punctuation.</p>
<pre><code>import string
with open(file_name, "rt") as finput:
for line in finput:
for word in line.split():
... | 2 | 2016-09-27T14:15:06Z | [
"python",
"python-2.7",
"text",
"punctuation"
] |
How can I travel through the words of a file in PYTHON? | 39,726,737 | <p>I have a file .txt and I want to travel through the words of it. I have a problem, I need to remove the punctuation marks before travelling through the words. I have tried this, but it isn't removing the punctuation marks.</p>
<pre><code>file=open(file_name,"r")
for word in file.read().strip(",;.:- '").split():
... | 2 | 2016-09-27T14:00:15Z | 39,754,324 | <p>The following code preserves apostrophes and blanks, and could easily be modified to preserve double quotations marks, if desired. It works by using a translation table based on a subclass of the string object. I think the code is fairly easy to understand. It might be made more efficient if necessary.</p>
<pre><c... | 1 | 2016-09-28T17:43:41Z | [
"python",
"python-2.7",
"text",
"punctuation"
] |
Generating regex string to be used in re.match() | 39,726,805 | <p>I am trying to a string to be used as regex String.<br>
In the following code: <br>
<code>_pattern</code> is a pattern like <code>abba</code> and I am trying to check <code>_string</code> follows the <code>_pattern</code> (eg. <code>catdogdogcat</code>)<br></p>
<p><code>rxp</code> in the following code is the regul... | 1 | 2016-09-27T14:03:23Z | 39,726,843 | <p>You should use string formatting, and not hard-code <code>rxp</code> into the string:</p>
<pre><code>print re.match(r'%s'%rxp, _string)
</code></pre>
| 0 | 2016-09-27T14:05:28Z | [
"python",
"regex"
] |
Generating regex string to be used in re.match() | 39,726,805 | <p>I am trying to a string to be used as regex String.<br>
In the following code: <br>
<code>_pattern</code> is a pattern like <code>abba</code> and I am trying to check <code>_string</code> follows the <code>_pattern</code> (eg. <code>catdogdogcat</code>)<br></p>
<p><code>rxp</code> in the following code is the regul... | 1 | 2016-09-27T14:03:23Z | 39,727,628 | <p>The thing is that your regex string variable has double <code>\\</code> instead of a single one.</p>
<p>You can use </p>
<pre><code>rxp.replace("\\\\", "\\")
</code></pre>
<p>in <code>.match</code> like this:</p>
<pre><code>>>> print re.match(rxp.replace("\\\\", "\\"), _string)
<_sre.SRE_Match object... | 1 | 2016-09-27T14:40:42Z | [
"python",
"regex"
] |
401 error for tastypie for api_client | 39,726,850 | <p>Hi I am trying to write a test case for my app. URL = '/api/project/'. I have enabled get, post and put methods along with authentication. But still i get 401 error for post request</p>
<pre><code>class EntryResourceTest(ResourceTestCaseMixin, TestCase):
class Meta:
queryset = Project.objects.all()
... | 0 | 2016-09-27T14:05:46Z | 39,742,007 | <p>Use <code>BasicAuthentication</code> instead of <code>Authentication</code>.</p>
<p><code>self.create_basic(...)</code> create a headers for <code>BasicAuthentication</code>.</p>
<pre><code>def create_basic(self, username, password):
"""
Creates & returns the HTTP ``Authorization`` header for use with ... | 0 | 2016-09-28T08:30:13Z | [
"python",
"django",
"tastypie",
"django-unittest"
] |
Split CSV file using Python shows not all data in Excel | 39,726,884 | <p>I am trying to dump the values in my Django database to a csv, then write the contents of the csv to an Excel spreadsheet which looks like a table (one value per cell), so that my users can export a spreadsheet of all records in the database from Django admin. Right now when I export the file, I get this (only one r... | 0 | 2016-09-27T14:07:10Z | 39,728,754 | <p>Your CSV file could be read in and written as follows:</p>
<pre><code>import csv
workbook = xlsxwriter.Workbook('output.xlsx')
worksheet_s = workbook.add_worksheet("Summary")
with open(r'\Users\nicoletorek\emarshal\myfile.csv', 'rb') as f_input:
csv_input = csv.reader(f_input)
for row_index, row_data in ... | 0 | 2016-09-27T15:33:15Z | [
"python",
"django",
"csv",
"split",
"list-comprehension"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.