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
How do I optimise this Python code?
39,899,567
<p>I'm doing a coding challenge for fun and to work on my skills - some of you may remember the Advent of Code challenge from last December, I'm working through that. I've got this code as the solution to one of the problems, which works, but it's uselessly slow.</p> <pre><code>inp = "1113122113" def iterate(num): ...
0
2016-10-06T15:07:13Z
39,900,068
<p>Using <code>itertools.groupby</code> will make this very fast.</p> <pre><code>from itertools import groupby def next_say(s): return ''.join(str(sum(1 for _ in g))+k for k, g in groupby(s)) def iterate(num): """Generator that yields the first num iterations""" val = '1' for i in range(num): ...
1
2016-10-06T15:30:25Z
[ "python", "optimization" ]
Float value behaviour in Python 2.6 and Python 2.7
39,899,580
<p>I have to convert string to tuple of float. In Python 2.7, it gives correct conversion, but in Python it is not same case.</p> <p>I want same behaviour in Python 2.6 </p> <p>Can anyone help me why this is not same in Python 2.6 and how to do in Python 2.6.</p> <p><strong>Python 2.6</strong></p> <pre><code>&gt;&g...
4
2016-10-06T15:07:54Z
39,899,817
<p>In order to get the same result in Python 2.6, you have to explicitly do:</p> <pre><code>'%.12g' % float_variable </code></pre> <p>Better to create a custom function to do this as:</p> <pre><code>def convert_to_my_float(float_value): return float('%.12g' % float_value) </code></pre> <hr> <p>As per <a href="...
4
2016-10-06T15:18:10Z
[ "python", "python-2.7" ]
Same xpath returns different values on Centos, Ubuntu
39,899,632
<p>We're trying to port our application from a Centos environment into other linuxes, in particular Ubuntu. The application is python-based so there should be no problems, however we noticed an odd behaviour when parsing XPATHs.</p> <p>Sample file:</p> <pre><code>&lt;root&gt; &lt;outer&gt; &lt;inner&gt; ...
2
2016-10-06T15:09:55Z
39,956,501
<p>The result on CentOS is incorrect.</p> <p><code>libxml2</code> 2.9.0 introduced a regression, see <a href="https://bugzilla.gnome.org/show_bug.cgi?id=695699" rel="nofollow">libxml 2.9.0 XPath evaluation issue</a>. It is fixed in 2.9.2 but not in 2.9.1.</p> <p>Debian has integrated the patch in version 2.9.1+dfsg1-...
1
2016-10-10T10:45:56Z
[ "python", "linux", "xpath", "centos", "lxml" ]
Django template doesn't show model items
39,899,687
<p>I'm very new to Django and I'm currently trying to create a movie database for a few of my favorite directors. I've been following tutorial videos, and I'm currently trying to get my detail view to display all the added movies for each director. However when I go into the director, it does not display their films.</...
1
2016-10-06T15:12:18Z
39,899,821
<p>This should solve it:</p> <pre><code>{% for film in director.films_set.all %} &lt;li&gt;{{ film.title }} - {{ film.rating }}&lt;/li&gt; {% endfor %} </code></pre> <p>You want each movie's title and rating, so I guess using <code>direct.title</code> and <code>direct.rating</code> was the problem. Also, the variable...
0
2016-10-06T15:18:22Z
[ "python", "django" ]
Django template doesn't show model items
39,899,687
<p>I'm very new to Django and I'm currently trying to create a movie database for a few of my favorite directors. I've been following tutorial videos, and I'm currently trying to get my detail view to display all the added movies for each director. However when I go into the director, it does not display their films.</...
1
2016-10-06T15:12:18Z
39,899,868
<p>In your view, you only pass one context object to the template, <code>direct</code>. This <code>direct</code> is a member of your director model: it makes sense that <code>direct</code> in your template displays the name of the director, since that is how you define the <code>__str__</code> method for that model.</p...
0
2016-10-06T15:20:11Z
[ "python", "django" ]
Pandas - Grouping rows in time buckets
39,899,737
<p>I have a data frame with thousands of line looking like this:</p> <pre><code> time type value 0 09:30:01.405735 EVENT_0 2.1 0 09:30:01.405761 EVENT_0 2.1 0 09:30:01.419743 EVENT_0 1.1 1 09:30:02.419769 EVENT_0 32.1 2 09:30:02.419775 EVENT_0 2....
0
2016-10-06T15:14:26Z
39,900,167
<p>Assuming you time column is of datetime format and the data frame is sorted according to the time column:</p> <pre><code># calculate the windows, gives a unique number per entry associating it to its respective window windows = (data.time.diff().apply(lambda x: x.total_seconds()) &gt;= 1).astype(int).cumsum() # gro...
2
2016-10-06T15:34:57Z
[ "python", "pandas" ]
Will this image always load into the .py app if it's in the same directory?
39,899,809
<p>I'm writing an application that I would like to use this .gif file in. If I want to execute this app with this picture in the same folder as the .py file will it simply show with this code or do I have to embed them into the app using base64? Thanks for your help.</p> <pre><code>jlu_logo = tkinter.PhotoImage(file="...
0
2016-10-06T15:17:56Z
39,907,141
<p>you could try something like</p> <pre><code>import os jlu_logo = tkinter.PhotoImage(file=os.path.join(os.path.dirname(__file__), "jlu-logo.gif")) jlulogo = tkinter.Label(main, image = jlu_logo) jlulogo.place(x=255, y=230, anchor="s") </code></pre>
0
2016-10-06T23:27:07Z
[ "python", "python-3.x", "tkinter" ]
Python Pyramid url replacement variable restrictions
39,899,880
<p>I'm developing in Pyramid 1.7 and running into an interesting scenario where some URL dispatch replacement variables match the route, while others do not. These variables are numbers, which may not be best practice or even be allowed from what I can tell in the documentation:</p> <p><a href="http://docs.pylonsproj...
1
2016-10-06T15:20:53Z
40,113,324
<p>I made a test case which passes fine with your examples. Feel free to play with this until it reproduces your issues, but until then I'm not sure how to help.</p> <pre><code>from pyramid.config import Configurator from webtest import TestApp config = Configurator() config.add_route('my_route', '/path/more_path/{nu...
0
2016-10-18T16:18:32Z
[ "python", "pyramid" ]
Running python in parallel
39,899,929
<p>I have this bash script:</p> <pre><code>#!/bin/bash for i in `seq 1 32`; do python run.py file$i.txt &amp; if (( $i % 10 == 0 )); then wait; fi done wait </code></pre> <p>I want to run it on a cluster with 64 cores. How will the 10 files be distributed among the cores? IF I have 10 free cores at the same time, eac...
0
2016-10-06T15:23:30Z
39,900,745
<p>When you run the scripts from the shell in paralel, you are delegating responsibility of process managment to the OS scheduler, which is not a bad idea, because the OS knows well how to handle process through the processor cores, but sometimes you need more control about the tasks execution (maybe because you will r...
0
2016-10-06T16:03:01Z
[ "python", "bash", "parallel-processing" ]
directory listing to xml - cannot concatenate 'str' and 'NoneType' objects - How To Handle?
39,899,986
<p>Using part of a script I found on here to run through the directories on a Windows PC to produce an XML file. However I am running into the above error and I am not sure how to handle the error. I have added a try/except in however it still crashes out. This works perfectly if i set the directory to be my Current Wo...
0
2016-10-06T15:26:13Z
39,900,465
<p>Based on your comments below about getting and wanting to ignore any path access errors, I modified the code in my answer below to do that as best it can. Note that it will still terminate if some other type of exception occurs.</p> <pre><code>def DirTree3(path): try: result = '&lt;dir&gt;%s\n' % xml_qu...
1
2016-10-06T15:49:05Z
[ "python", "xml" ]
Passing a JSON string to django using JQuery and Ajax
39,899,989
<p>I'm a bit new to Django and trying to understand it. Currently, I'm creating a network topology visualiser (think routers and switches connected together). It works fine and all of the data is saved in a javascript object.</p> <p>I want to have the ability to, when a user clicks a button, send this javascript objec...
1
2016-10-06T15:26:24Z
39,900,177
<p>You're trying to access <code>body</code> on <code>request.POST</code>. But body is an attribute directly of the request. Your code should be:</p> <pre><code> request_data = request.body print("Raw Data: " + request_data) </code></pre> <p>Also note, in your Javascript that <code>$(document).ready</code> lin...
0
2016-10-06T15:35:22Z
[ "javascript", "jquery", "python", "ajax", "django" ]
Passing a JSON string to django using JQuery and Ajax
39,899,989
<p>I'm a bit new to Django and trying to understand it. Currently, I'm creating a network topology visualiser (think routers and switches connected together). It works fine and all of the data is saved in a javascript object.</p> <p>I want to have the ability to, when a user clicks a button, send this javascript objec...
1
2016-10-06T15:26:24Z
39,900,221
<p>first of all you dont even need to use all this in your ajax call data: JSON.stringify(nodes.get(),null,4), replace by data: nodes.get(), should be enougth as long as this method returns a valid json object</p> <p>second one, I ´d strongly recommend you to use a framework to help you to parse JSON p...
0
2016-10-06T15:37:32Z
[ "javascript", "jquery", "python", "ajax", "django" ]
Passing a JSON string to django using JQuery and Ajax
39,899,989
<p>I'm a bit new to Django and trying to understand it. Currently, I'm creating a network topology visualiser (think routers and switches connected together). It works fine and all of the data is saved in a javascript object.</p> <p>I want to have the ability to, when a user clicks a button, send this javascript objec...
1
2016-10-06T15:26:24Z
39,902,705
<p>For those reading this later, this is what I did:</p> <p>mainapp/urls.py</p> <pre><code>from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^NetworkTopology/', include('OpenAutomation.NetworkTopology.urls')), url(r'^admin/', admin.site.urls), ] </code></pre> <...
0
2016-10-06T17:57:10Z
[ "javascript", "jquery", "python", "ajax", "django" ]
"ValueError: chunksize cannot exceed dimension size" when trying to write xarray to netcdf
39,900,011
<p>I got the following error when trying to write a xarray object to netcdf file: </p> <pre><code>"ValueError: chunksize cannot exceed dimension size" </code></pre> <p>The data is too big for my memory and needs to be chunked.<br> The routine is basically as follows: </p> <pre><code>import xarray as xr ds=xr.op...
0
2016-10-06T15:27:28Z
39,960,638
<p>It was an issue of the engine in the writing command. You need to change the engine from netcdf4 (default) to scipy if you are using chunks! </p> <pre><code>myds.to_netcdf("somenewfile.nc",engine='scipy') </code></pre> <p>The netcdf4 package is NOT capable of writing such files.</p>
0
2016-10-10T14:29:14Z
[ "python", "netcdf4" ]
Python subprocess not returning
39,900,020
<p>I want to call a Python script from Jenkins and have it build my app, FTP it to the target, and run it.</p> <p>I am trying to build and the <code>subprocess</code> command fails. I have tried this with both <code>subprocess.call()</code> and <code>subprocess.popen()</code>, with the same result.</p> <p>When I eval...
1
2016-10-06T15:28:11Z
39,900,993
<p>Ok, I go it. No comments or answers so far, but, rather then delete the question, I will leave it here in case it helps anyone in future.</p> <p>I Googled further and found <a href="https://www.webcodegeeks.com/python/python-subprocess-example/" rel="nofollow">this page</a>, which, at 1.2 says </p> <blockquote> ...
0
2016-10-06T16:16:35Z
[ "python", "python-2.7", "subprocess" ]
Sort lists in a Pandas Dataframe column
39,900,061
<p>I have a Dataframe column which is a collection of lists</p> <pre><code> a ['a', 'b'] ['b', 'a'] ['a', 'c'] ['c', 'a'] </code></pre> <p>I would like to use this list to group by its unique values (['a', 'b'] &amp; ['a', 'c']). However, this generates an error </p> <pre><code>TypeError: unhashable type: 'list' ...
3
2016-10-06T15:30:05Z
39,900,295
<p>list are unhashable. however, tuples are hashable</p> <p>use</p> <pre><code>df.groupby([df.a.apply(tuple)]) </code></pre> <p><strong><em>setup</em></strong><br> <code>df = pd.DataFrame(dict(a=[list('ab'), list('ba'), list('ac'), list('ca')]))</code><br> <strong><em>results</em></strong><br> <code>df.groupby([df....
3
2016-10-06T15:41:14Z
[ "python", "pandas" ]
Sort lists in a Pandas Dataframe column
39,900,061
<p>I have a Dataframe column which is a collection of lists</p> <pre><code> a ['a', 'b'] ['b', 'a'] ['a', 'c'] ['c', 'a'] </code></pre> <p>I would like to use this list to group by its unique values (['a', 'b'] &amp; ['a', 'c']). However, this generates an error </p> <pre><code>TypeError: unhashable type: 'list' ...
3
2016-10-06T15:30:05Z
39,901,889
<p>You can also sort values by column.</p> <p>Example:</p> <pre><code>x = [['a', 'b'], ['b', 'a'], ['a', 'c'], ['c', 'a']] df = pandas.DataFrame({'a': Series(x)}) df.a.sort_values() a 0 [a, b] 2 [a, c] 1 [b, a] 3 [c, a] </code></pre> <p>However, for what I understand, you want to sort <code>[b, a]</cod...
2
2016-10-06T17:07:07Z
[ "python", "pandas" ]
Unable to install tweepy in Python on Windows 7
39,900,113
<p>I have Python 3.5.2 installed on Windows 7 (64bit). Pip module is installed as well by default. I am new to installing Python packages. I am trying to install tweepy module, but keep running into the problem described below:</p> <p>1) I tried to install tweepy navigating to C:...\Python35\Scripts in command line an...
-1
2016-10-06T15:32:25Z
39,900,520
<p>Your first screenshot is clear.</p> <p>The sentence <em>Requirement already satisfied</em> makes me thinks that you have already installed <strong>tweepy</strong>.</p> <p>To check this I suggest you to go in <em>C:...\Python35\Scripts</em> and type </p> <pre><code>pip freeze </code></pre> <p>This command shows a...
0
2016-10-06T15:51:51Z
[ "python", "windows", "pip", "tweepy", "six" ]
Unable to install tweepy in Python on Windows 7
39,900,113
<p>I have Python 3.5.2 installed on Windows 7 (64bit). Pip module is installed as well by default. I am new to installing Python packages. I am trying to install tweepy module, but keep running into the problem described below:</p> <p>1) I tried to install tweepy navigating to C:...\Python35\Scripts in command line an...
-1
2016-10-06T15:32:25Z
39,917,445
<p>After some testing I was finally able to successfully import tweety in Python interpreter as well as all its dependencies (that includes modules <em>six, requests, requests-oauthlib</em> and <em>oauthlib</em>).</p> <p>The solution was the following:</p> <p>I installed <em>six</em> using <code>pip install C:...\Pyt...
0
2016-10-07T12:34:05Z
[ "python", "windows", "pip", "tweepy", "six" ]
How to get unique rows and their occurrences for 2D array?
39,900,208
<p>I have a 2D array, and it has some duplicate columns. I would like to be able to see which unique columns there are, and where the duplicates are.</p> <p>My own array is too large to put here, but here is an example:</p> <pre><code>a = np.array([[ 1., 0., 0., 0., 0.],[ 2., 0., 4., 3., 0.],]) </code></pre> ...
4
2016-10-06T15:36:49Z
39,901,297
<p>For small arrays:</p> <pre><code> from collections import defaultdict indices = defaultdict(list) for index, column in enumerate(a.transpose()): indices[tuple(column)].append(index) unique = [kk for kk, vv in indices.items() if len(vv) == 1] non_unique = {kk:vv for kk, vv in indices.items...
-1
2016-10-06T16:32:35Z
[ "python", "arrays", "numpy", "unique" ]
How to get unique rows and their occurrences for 2D array?
39,900,208
<p>I have a 2D array, and it has some duplicate columns. I would like to be able to see which unique columns there are, and where the duplicates are.</p> <p>My own array is too large to put here, but here is an example:</p> <pre><code>a = np.array([[ 1., 0., 0., 0., 0.],[ 2., 0., 4., 3., 0.],]) </code></pre> ...
4
2016-10-06T15:36:49Z
39,901,407
<p>Here's a vectorized approach to give us a list of arrays as output -</p> <pre><code>ids = np.ravel_multi_index(a.astype(int),a.max(1).astype(int)+1) sidx = ids.argsort() sorted_ids = ids[sidx] out = np.split(sidx,np.nonzero(sorted_ids[1:] &gt; sorted_ids[:-1])[0]+1) </code></pre> <p>Sample run -</p> <pre><code>In...
0
2016-10-06T16:38:48Z
[ "python", "arrays", "numpy", "unique" ]
How to get unique rows and their occurrences for 2D array?
39,900,208
<p>I have a 2D array, and it has some duplicate columns. I would like to be able to see which unique columns there are, and where the duplicates are.</p> <p>My own array is too large to put here, but here is an example:</p> <pre><code>a = np.array([[ 1., 0., 0., 0., 0.],[ 2., 0., 4., 3., 0.],]) </code></pre> ...
4
2016-10-06T15:36:49Z
39,903,835
<p>The <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package (disclaimer: I am its author) contains efficient functionality for computing these kind of things:</p> <pre><code>import numpy_indexed as npi unique_columns = npi.unique(a, axis=1) non_unique_column_idx =...
0
2016-10-06T19:05:50Z
[ "python", "arrays", "numpy", "unique" ]
How create the Decay function in ElasticSearch DSL python
39,900,211
<p>I am querying the Elastic Search with <a href="https://pypi.python.org/pypi/elasticsearch-dsl/2.0.0" rel="nofollow">elasticsearch-dsl/2.0.0</a></p> <pre><code> "linear": { "date": { "origin": "now", "scale": "10d", "offset": "5d", "decay" : 0.5 ...
2
2016-10-06T15:36:54Z
39,909,469
<p>Try the following query</p> <pre><code>from elasticsearch import Elasticsearch from elasticsearch_dsl import Search, query client = Elasticsearch() s = Search(using=client) function_score_query = query.Q( 'function_score', query=query.Q('match', your_field='your_query'), functions=[ ...
1
2016-10-07T04:36:07Z
[ "python", "elasticsearch" ]
Ansible prompt_vars error: GetPassWarning: Cannot control echo on the terminal
39,900,282
<p>I am using Ansible and Docker for automating the environment build process. I use prompt_vars to try to collect the username and password for the git repo but unfortunately i got this error: </p> <blockquote> <p>GetPassWarning: Cannot control echo on the terminal</p> </blockquote> <p>The docker ubuntu version is...
0
2016-10-06T15:40:20Z
39,901,858
<p>The error</p> <blockquote> <p>GetPassWarning: Cannot control echo on the terminal</p> </blockquote> <p>is raised by Python and indicates that the terminal you are using does not provide <code>stdin</code>, <code>stdout</code> and <code>stderr</code>. In this case its <code>stderr</code>.</p> <p>As there is not ...
0
2016-10-06T17:04:55Z
[ "python", "docker", "ansible" ]
Installing python package on AWS lambda
39,900,449
<p>I have deployed my <code>zipped</code> project without <code>psycopg2</code> package. I want to install this package on my <code>lambda</code> without re-uploading my fixed project (i haven't access to my project right now). How can i install this <code>package</code> on my <code>lambda</code>? Is it possible to do ...
0
2016-10-06T15:48:06Z
39,900,507
<p>It's not possible to do with <code>pip</code>. You have to add the dependency to your zipped Lambda deployment file. You can't modify your Lambda deployment without uploading a new zipped deployment file.</p>
0
2016-10-06T15:51:13Z
[ "python", "amazon-web-services", "pip", "aws-lambda", "psycopg2" ]
Installing python package on AWS lambda
39,900,449
<p>I have deployed my <code>zipped</code> project without <code>psycopg2</code> package. I want to install this package on my <code>lambda</code> without re-uploading my fixed project (i haven't access to my project right now). How can i install this <code>package</code> on my <code>lambda</code>? Is it possible to do ...
0
2016-10-06T15:48:06Z
39,902,104
<p>It is not possible to use <strong>pip directly on the lambda</strong>. Rather I use a custom build script to create zip package [this can give you a brief idea - it can certainly be made much simpler]</p> <pre><code>rm -rf ~/devops/tempenv &gt; /dev/null virtualenv ~/devops/tempenv source ~/devops/tempenv/bin/activ...
0
2016-10-06T17:20:23Z
[ "python", "amazon-web-services", "pip", "aws-lambda", "psycopg2" ]
Pandas pivot_table do not comply with values order
39,900,493
<p>I have an issue with pandas pivot_table.</p> <p>Sometimes, the order of the columns specified on "values" list does not match</p> <pre><code>In [11]: p = pivot_table(df, values=["x","y"], cols=["month"], rows="name", aggfunc=np.sum) </code></pre> <p>i get the wrong order (y,x) instea...
3
2016-10-06T15:50:33Z
39,903,058
<p>According to the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow">pandas documentation</a>, <code>values</code> should take the name of a single column, not an iterable.</p> <blockquote> <p>values : column to aggregate, optional</p> </blockquote>
1
2016-10-06T18:19:13Z
[ "python", "pandas", "pivot-table" ]
How to apply a function can test whether an element in a list in data frame with python-pandas?
39,900,505
<p>For a data frame <code>df</code>, it has a column <code>col</code> contains <code>list</code> value:</p> <pre><code> id col 1 [1, 10, 23] 2 [2, 11, 19, 29] .. </code></pre> <p>I tried:</p> <pre><code>df[1 in df.col] </code></pre> <p>But got an error:</p> <pre><code>KeyError: True </code></pre> <p...
2
2016-10-06T15:51:08Z
39,900,621
<p>option using <code>apply</code><br> <code>df.col.apply(lambda x: 1 in x)</code></p> <p><strong><em>demo</em></strong><br> <code>df[df.col.apply(lambda x: 1 in x)]</code><br> <a href="http://i.stack.imgur.com/wRvd7.png" rel="nofollow"><img src="http://i.stack.imgur.com/wRvd7.png" alt="enter image description here"><...
3
2016-10-06T15:57:12Z
[ "python", "pandas" ]
How to apply a function can test whether an element in a list in data frame with python-pandas?
39,900,505
<p>For a data frame <code>df</code>, it has a column <code>col</code> contains <code>list</code> value:</p> <pre><code> id col 1 [1, 10, 23] 2 [2, 11, 19, 29] .. </code></pre> <p>I tried:</p> <pre><code>df[1 in df.col] </code></pre> <p>But got an error:</p> <pre><code>KeyError: True </code></pre> <p...
2
2016-10-06T15:51:08Z
39,900,874
<p>try read the "apply" function in pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow">document</a>.</p> <pre><code>df['has_element'] = df['col'].apply(lambda x: element in x) </code></pre>
1
2016-10-06T16:10:21Z
[ "python", "pandas" ]
How to make a python program that lists the positions and displays and error message if not found
39,900,510
<p>I did this code:</p> <pre><code>sentence = input("Type in your sentance ").lower().split() Word = input("What word would you like to find? ") Keyword = Word.lower().split().append(Word) positions = [] for (S, subword) in enumerate(sentence): if (subword == Word): positions.append print("The wor...
1
2016-10-06T15:51:19Z
39,900,786
<p>Your code is having multiple errors. I am pasting here the sample code for your reference:</p> <pre><code>from collections import defaultdict sentence_string = raw_input('Enter Sentence: ') # Enter Sentence: Here is the content I need to check for index of all words as Yes Hello Yes Yes Hello Yes word_string = ra...
1
2016-10-06T16:05:37Z
[ "python" ]
How to make a python program that lists the positions and displays and error message if not found
39,900,510
<p>I did this code:</p> <pre><code>sentence = input("Type in your sentance ").lower().split() Word = input("What word would you like to find? ") Keyword = Word.lower().split().append(Word) positions = [] for (S, subword) in enumerate(sentence): if (subword == Word): positions.append print("The wor...
1
2016-10-06T15:51:19Z
39,901,121
<blockquote> <p>Use index.</p> </blockquote> <pre><code>a = 'Some sentence of multiple words' b = 'a word' def list_matched_indices(list_of_words, word): pos = 0 indices = [] while True: try: pos = list_of_words.index(word, pos) indices.append(pos) pos+=1 ...
0
2016-10-06T16:23:36Z
[ "python" ]
Pulling elements from 2D array based on index array
39,900,543
<p>I have an array as:</p> <pre><code>import numpy as np A = np.arange(15).reshape(3, 5) </code></pre> <p>I also have an index array as:</p> <pre><code>ind = np.asarray([1,2,0,2,2]) </code></pre> <p>The elements of ind represent the row number of A for each column of A.</p> <p>i.e </p> <p>I want to pull <code>ind...
1
2016-10-06T15:53:12Z
39,900,638
<p>Using <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#combining-advanced-and-basic-indexing" rel="nofollow">Numpy's <code>fancy-indexing</code></a> -</p> <pre><code>A[ind,np.arange(ind.size)] </code></pre>
2
2016-10-06T15:58:18Z
[ "python", "numpy" ]
With python how can I have the start of my weeks start on Wednesday instead of Sunday or Monday?
39,900,627
<p>I am using <code>gmtime, strftime and datetime.</code></p> <p>To give context I am setting up an on call schedule, and to allow people to easily switch people's on call schedules I wrote a script to change the xml file to accomplish that. To make it a bit easier on everyone on call I set the script up so that you c...
0
2016-10-06T15:57:40Z
39,908,836
<p>Why don't you just manually calculate week # yourself.<br> Basic algorithm:</p> <ul> <li>Get current day of year</li> <li>Shift back to the nearest Wednesday (or whatever day you want)</li> <li>Divide by 7 + 1 = Week # (assuming the first partial week is 0)</li> </ul> <p>In code:</p> <pre><code>&gt;&gt;&gt; wedne...
1
2016-10-07T03:20:13Z
[ "python", "python-3.x" ]
PyObject_CallObject failing on bytearray method
39,900,630
<p>In the following code I create a pointer to a PyObject, representing a bytearray, using the Python C API. I then extract the method "endswith" from the bytearray and try to call it on the original bytearray itself, expecting it to return <code>Py_True.</code> However, it returns <code>NULL</code> and the program pr...
3
2016-10-06T15:57:51Z
39,913,456
<p>If you add the line <a href="https://docs.python.org/2/c-api/exceptions.html" rel="nofollow"><code>PyErr_PrintEx(1)</code></a> it helpfully tells you:</p> <blockquote> <p>TypeError: argument list must be a tuple</p> </blockquote> <p>This is confirmed by <a href="https://docs.python.org/2/c-api/object.html" rel="...
1
2016-10-07T09:03:59Z
[ "python", "c++", "python-c-api" ]
Moving average by id/group with a defined interval in python
39,900,708
<p>Given is a csv dataset with the following columns and values (example). I want to <strong>add a new column</strong> in my csv data with a <strong>moving average</strong> of S1 according to each id. S1 are my measurements. The timeframe t should be 3.That's how my dataset currently looks.</p> <pre><code>id S1 1 ...
2
2016-10-06T16:01:18Z
39,901,244
<p>use <code>groupby</code> and <code>rolling</code> with <code>mean</code></p> <pre><code>g = df.groupby('id').S1 rolls = [2, 3, 4, 5] pd.concat([g.rolling(i).mean() for i in rolls], axis=1, keys=rolls) </code></pre> <p><a href="http://i.stack.imgur.com/2veRn.png" rel="nofollow"><img src="http://i.stack.imgur.com/2v...
2
2016-10-06T16:29:58Z
[ "python", "csv", "pandas", "numpy", "moving-average" ]
How to change directories within Python?
39,900,734
<p>I have the following code. It works for the first directory but not the second one... What I am trying to do is to count the lines on each of the files in different directory.</p> <pre><code>import csv import copy import os import sys import glob os.chdir('Deployment/Work/test1/src') names={} for fn in glob.glob('...
0
2016-10-06T16:02:37Z
39,900,790
<p>Your <code>os.chdir</code> is interpreted relative to the current working directory. Your first <code>os.chdir</code> changes the working directory. The system tries to find the second path relative to the first path.</p> <p>There are several ways to solve this. You can keep track of the current directory and chang...
2
2016-10-06T16:06:04Z
[ "python" ]
How to change directories within Python?
39,900,734
<p>I have the following code. It works for the first directory but not the second one... What I am trying to do is to count the lines on each of the files in different directory.</p> <pre><code>import csv import copy import os import sys import glob os.chdir('Deployment/Work/test1/src') names={} for fn in glob.glob('...
0
2016-10-06T16:02:37Z
39,900,802
<p>You'll either have to return to the root directory using as many <code>..</code> as required, store the root directory or specify a full directory from your home:</p> <pre><code>curr_path = os.getcwd() os.chdir('Deployment/Work/test2/src') os.chdir(curr_path) os.chdir('Deployment/Work/test2/src') </code></pre> <p...
2
2016-10-06T16:06:27Z
[ "python" ]
How to change directories within Python?
39,900,734
<p>I have the following code. It works for the first directory but not the second one... What I am trying to do is to count the lines on each of the files in different directory.</p> <pre><code>import csv import copy import os import sys import glob os.chdir('Deployment/Work/test1/src') names={} for fn in glob.glob('...
0
2016-10-06T16:02:37Z
39,900,882
<p>I suppose the script is not working because you are trying to change the directory using a relative path. This means that when you execute the first <code>os.chdir</code> you change your working directory from the current one to <code>'Deployment/Work/test1/src'</code> and when you call <code>os.chdir</code> the sec...
0
2016-10-06T16:10:43Z
[ "python" ]
Python - tkinter - dynamic checkboxes
39,900,839
<p>One of my courses made a passing reference to tkinter, and that it was out of the scope of what the introductory course offered. It piqued my curiosity though and I wanted to dig deeper into it.</p> <p>I have the basics down - I can get checkboxes to appear where I want them to, but I'd like to make it more dynami...
-1
2016-10-06T16:08:17Z
39,901,643
<p>If you first click checkbox <code>Focus #1</code> then it shows new checkboxes and they work as expected</p> <p>But if you click other checkbox as first then you get error message </p> <blockquote> <p>AttributeError: 'Application' object has no attribute 'checkBoxF1A'</p> </blockquote> <p>Problem is because in ...
0
2016-10-06T16:53:55Z
[ "python", "user-interface", "checkbox", "tkinter", "python-3.5" ]
conda install fails even i found the package by conda info package
39,900,964
<p>I am on windows using Anaconda with python 3.5, I want to install opencv3.1, so I found a channel called conda-forge has the opencv3.2 for my python version, but when I try to install it by:</p> <blockquote> <p>conda install -c conda-forge opencv</p> </blockquote> <p>I got error message:</p> <pre><code>Fetchi...
0
2016-10-06T16:14:51Z
40,090,173
<p>Please check the link <a href="https://github.com/ContinuumIO/anaconda-issues/issues/1074" rel="nofollow">here</a>. As far as I understand, it is an issue related to the new version of anaconda. If you need to find a fast solution, you can simply create a virtual environment, activate the environment, and install op...
0
2016-10-17T15:22:32Z
[ "python", "opencv", "anaconda", "conda" ]
Python - Gathering File Information Recursively Leads to Memory Error
39,901,031
<p>I am writing a script to recurse over all directories and subdirectories of a starting folder but I'm running into memory errors (the error is <code>MemoryError</code>). My guess would be that maybe my <code>data_dicts</code> list is getting too big but I'm not sure. Any advice would be appreciated.</p> <pre><code>...
0
2016-10-06T16:18:26Z
39,901,647
<p>You shouldn't supply <code>data_dicts</code> as an argument to your function <code>get_file_sizes_folder()</code>. Doing so will produce many, many duplicates of your entries, at a rate that is probably nearly factorial. No wonder that your computer runs out of memory very quickly!</p> <p>Instead, use only <code>st...
3
2016-10-06T16:54:08Z
[ "python", "recursion" ]
Python - Gathering File Information Recursively Leads to Memory Error
39,901,031
<p>I am writing a script to recurse over all directories and subdirectories of a starting folder but I'm running into memory errors (the error is <code>MemoryError</code>). My guess would be that maybe my <code>data_dicts</code> list is getting too big but I'm not sure. Any advice would be appreciated.</p> <pre><code>...
0
2016-10-06T16:18:26Z
39,912,697
<p>You shouldn't perform a recursion at all. Use <a href="https://docs.python.org/2.7/library/os.html#os.walk" rel="nofollow"><code>os.walk</code></a></p> <p>Example:</p> <pre><code>def get_file_sizes_folder(starting_folder): data_dicts = list() for root, _, files in os.walk(starting_folder): data_dic...
1
2016-10-07T08:22:23Z
[ "python", "recursion" ]
A split image can't be merged after performing a .dot on any of the split bands using pillow/numpy
39,901,043
<p>I am trying to correct the color in images using pillow and numpy. Using im.split() in combination with np.array.</p> <p>I would like to multiply all colours in the red band, but can't find a way of doing it.</p> <p>I've tried all kinds of things and after a lot of googling had hoped that this would be the solutio...
2
2016-10-06T16:19:06Z
39,901,729
<p><code>Image.merge</code> fails because rgb images are not of the same mode (see <a href="http://pillow.readthedocs.io/en/3.1.x/handbook/concepts.html#concept-modes" rel="nofollow">PIL Image modes</a>). You can check the mode this way:</p> <pre><code>&gt;&gt;&gt; Image.fromarray(datar).mode 'I' &gt;&gt;&gt; Image.fr...
2
2016-10-06T16:58:28Z
[ "python", "arrays", "python-2.7", "numpy", "pillow" ]
Can I setup a PHP Twilio application server and grant push capabilities
39,901,053
<p>I currently use a Python Twilio application server and grant push capabilities to my tokens with the following lines of code:</p> <pre><code>@app.route('/accessToken') def token(): account_sid = os.environ.get("ACCOUNT_SID", ACCOUNT_SID) api_key = os.environ.get("API_KEY", API_KEY) api_key_secret = os.environ...
2
2016-10-06T16:19:32Z
39,910,755
<p>Thanks to a tip from Zack with Twilio, I finally got this working!</p> <pre><code>include('./vendor/autoload.php'); include('./config.php'); include('./randos.php'); use Twilio\Jwt\AccessToken; use Twilio\Jwt\Grants; use Twilio\Jwt\Grants\VoiceGrant; use Twilio\Rest\Client; // choose a random username for the con...
1
2016-10-07T06:26:30Z
[ "php", "python", "twilio" ]
Finding Range of active/selected cell in Excel using Python and xlwings
39,901,092
<p>I am trying to write a simple function in Python (with xlwings) that reads a current 'active' cell value in Excel and then writes that cell value to the cell in the next column along from the active cell.</p> <p>If I specify the cell using an absolute reference, for example range(3, 2), then I everything is ok. Ho...
0
2016-10-06T16:22:06Z
39,905,568
<p>You have to get the app object from the workbook. You'd only use <code>xw.App</code> directly if you wanted to instantiate a new app. Also, <code>selection</code> returns a Range object, so do this: </p> <pre><code>cellRange = wb.app.selection rowNum = cellRange.row colNum = cellRange.column </code></pre>
0
2016-10-06T21:02:32Z
[ "python", "xlwings" ]
How to avoid encoding parameter when opening file in Python3
39,901,130
<p>When I am working on a .txt file on a Windows device I must save as either: ANSI, Unicode, Unicode big endian, or UTF-8. When I run Python3 on an OSX device and try to import and read the .txt file, I have to do something along the lines of:</p> <pre><code>with open('ships.txt', 'r', encoding='utf-8') as f: for...
0
2016-10-06T16:24:08Z
39,911,243
<p>Call <code>locale.getpreferredencoding(False)</code> on your OSX device. That's the default encoding used for reading a file on that device. Save in that encoding on Windows and you won't need to specify the encoding on your OSX device.</p> <p>But as the <a href="https://www.python.org/dev/peps/pep-0020/" rel="no...
0
2016-10-07T06:59:17Z
[ "python", "unicode", "encoding", "python-import" ]
Python check if string got a certain word (or combination of characters)
39,901,140
<p>Ok so I have this string (for example):</p> <pre><code>var = "I eat breakfast." </code></pre> <p>What i would like to do is to check if that string has the letters "ea", and I wanted to be able to put those values into a list.</p> <p>I tried using var[x] but I can only have one character at the same time and not ...
-1
2016-10-06T16:24:23Z
39,901,202
<p>Use <code>word in sentence</code>. For example:</p> <pre><code>&gt;&gt;&gt; 'el' in 'Hello' True &gt;&gt;&gt; 'xy' in 'Hello' False </code></pre> <p>For your reference, check: <a href="http://kracekumar.com/post/22512660850/python-in-operator-use-cases" rel="nofollow">python <code>in</code> operator use cases</a><...
1
2016-10-06T16:27:29Z
[ "python", "python-3.x" ]
Python check if string got a certain word (or combination of characters)
39,901,140
<p>Ok so I have this string (for example):</p> <pre><code>var = "I eat breakfast." </code></pre> <p>What i would like to do is to check if that string has the letters "ea", and I wanted to be able to put those values into a list.</p> <p>I tried using var[x] but I can only have one character at the same time and not ...
-1
2016-10-06T16:24:23Z
39,901,218
<p>Simple:</p> <pre><code>&gt;&gt;&gt; var = "I eat breakfast." &gt;&gt;&gt; 'ea' in var True </code></pre> <p>I'm not clear what you mean by "put those values into a list." I assume you mean the words:</p> <pre><code>&gt;&gt;&gt; [w for w in var.split() if 'ea' in w] ['eat', 'breakfast.'] </code></pre>
1
2016-10-06T16:28:11Z
[ "python", "python-3.x" ]
Python check if string got a certain word (or combination of characters)
39,901,140
<p>Ok so I have this string (for example):</p> <pre><code>var = "I eat breakfast." </code></pre> <p>What i would like to do is to check if that string has the letters "ea", and I wanted to be able to put those values into a list.</p> <p>I tried using var[x] but I can only have one character at the same time and not ...
-1
2016-10-06T16:24:23Z
39,901,234
<p>You can use <code>in</code> to check if a string contains a substring. It also sounds like you want to add <code>var</code> to a list if it contains a substring. Observe the following interactive session:</p> <pre><code>In [1]: var = "I eat breakfast." In [2]: lst = [] In [3]: if "ea" in var: ...: lst.appe...
0
2016-10-06T16:29:19Z
[ "python", "python-3.x" ]
Python check if string got a certain word (or combination of characters)
39,901,140
<p>Ok so I have this string (for example):</p> <pre><code>var = "I eat breakfast." </code></pre> <p>What i would like to do is to check if that string has the letters "ea", and I wanted to be able to put those values into a list.</p> <p>I tried using var[x] but I can only have one character at the same time and not ...
-1
2016-10-06T16:24:23Z
39,901,395
<p>This is a duplicate of <a href="http://stackoverflow.com/questions/3873361/finding-multiple-occurrences-of-a-string-within-a-string-in-python#3873422">Finding multiple occurrences of a string within a string in Python</a></p> <p>You can use <code>find(str, startIndex)</code> like so:</p> <pre><code>var = "I eat br...
1
2016-10-06T16:37:51Z
[ "python", "python-3.x" ]
Replace values of two columns in pandas
39,901,162
<p>What is the fastest way to replace values of two columns in pandas? Let's say given is:</p> <pre><code>A B 0 2 1 3 </code></pre> <p>and we want to get:</p> <pre><code>A B 2 0 3 1 </code></pre>
2
2016-10-06T16:25:13Z
39,901,255
<p>This code flips the values between the columns:</p> <pre><code>&gt;&gt;&gt; df_name[['A', 'B']] = df_name[['B', 'A']] &gt;&gt;&gt; print(df_name) A B 2 0 3 1 </code></pre>
4
2016-10-06T16:31:02Z
[ "python", "pandas" ]
Installing librdkafka on Windows to support Python development
39,901,163
<p>A little background: I am working on some python modules that other developers on our team will use. A common theme of each module is that one or more messages will be published to Kafka. We intend at this time to use the Confluent Kafka client. We are pretty new to python development in our organization -- we have ...
2
2016-10-06T16:25:15Z
39,916,730
<p>I'm not sure where the ideal place to install on Windows would be, but I ran the following test with some success.</p> <p>I copied my output and headers to <code>C:\test\lib</code> and <code>C:\test\include</code>, then ran a pip install with the following options:</p> <pre><code> pip install --global-option=build...
1
2016-10-07T11:59:03Z
[ "python", "windows", "apache-kafka" ]
Create directory of dynamically created html files. Flask
39,901,177
<p>I've got a simple flask app, with a templates folder with a bunch of html files that are created by a separate program. I want to (1) serve each of these html files by hitting <code>localhost:8888/&lt;html_filename&gt;</code> and (2) create a directory with hyperlinks to these endpoints on my main <code>/</code> end...
0
2016-10-06T16:26:11Z
39,922,137
<p>Off the top of my head and not tested in any way define a route along the lines of the following:</p> <pre><code>@route("/&lt;string:slug&gt;/", methods=['GET']) def page(self, slug): if slug_exists_as_a_html_file(slug): return render_template(slug) abort(404) </code></pre> <p>The function (or i...
0
2016-10-07T16:39:11Z
[ "python", "flask" ]
How do you make a list inclusive?
39,901,195
<p>I have homework that asks me to make a list from 1 to 52 inclusive. (for a deck of cards) I was just wondering how do you make a list inclusive?</p> <p>I know how to make a list, just am not sure how to make it inclusive. I searched on here for awhile and couldn't really find anything helpful.</p>
-3
2016-10-06T16:27:02Z
39,901,246
<p>This will create list with <code>[0,51]</code> values</p> <pre><code>list_of_cards = [i for i in range(52)] </code></pre> <p>This will create list with <code>[1,52]</code> values (This is what you want to use):</p> <pre><code>list_of_cards = [i for i in range(1,53)] </code></pre>
0
2016-10-06T16:30:21Z
[ "python", "list", "python-3.x" ]
How do you make a list inclusive?
39,901,195
<p>I have homework that asks me to make a list from 1 to 52 inclusive. (for a deck of cards) I was just wondering how do you make a list inclusive?</p> <p>I know how to make a list, just am not sure how to make it inclusive. I searched on here for awhile and couldn't really find anything helpful.</p>
-3
2016-10-06T16:27:02Z
39,901,369
<p>Use built-in <a href="https://docs.python.org/2/library/functions.html#range" rel="nofollow"><code>range()</code></a> function which returns the list of numbers. For example:</p> <p><strong>In Python 2.7</strong>:</p> <pre><code># To get numbers from 0 to n-1. Here, 'n' = 10 &gt;&gt;&gt; range(10) [0, 1, 2, 3, 4, ...
0
2016-10-06T16:36:15Z
[ "python", "list", "python-3.x" ]
How do you make a list inclusive?
39,901,195
<p>I have homework that asks me to make a list from 1 to 52 inclusive. (for a deck of cards) I was just wondering how do you make a list inclusive?</p> <p>I know how to make a list, just am not sure how to make it inclusive. I searched on here for awhile and couldn't really find anything helpful.</p>
-3
2016-10-06T16:27:02Z
39,901,495
<p>Inclusive is a term that is often used when expressing bounds. It means that the range of this bound includes all values <strong>including</strong> the the inclusive value. An example of this would be:</p> <p><em>Print all integers 1-5 inclusive.</em> The expected output would be:</p> <p>1 2 3 4 5</p> <p>The ant...
1
2016-10-06T16:44:31Z
[ "python", "list", "python-3.x" ]
Merge two vectors with alternate locations
39,901,209
<p>I have:</p> <pre><code>import numpy as np A = np.asarray([1,3,5,7,9]) B = np.asarray([2,4,6,8,10]) </code></pre> <p>I want to create:</p> <pre><code>C = np.asarray([1,2,3, 4,5,6,7,8,9,10]) </code></pre> <p>Is there a better way to do than to run a for loop</p>
0
2016-10-06T16:27:46Z
39,901,289
<p>You can the <em>stack</em> arrays vertically using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html#numpy.vstack" rel="nofollow"><code>vstack</code></a>, <em>transpose</em> and then <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.ravel.html" rel="nofollow"><cod...
1
2016-10-06T16:32:16Z
[ "python", "numpy" ]
Merge two vectors with alternate locations
39,901,209
<p>I have:</p> <pre><code>import numpy as np A = np.asarray([1,3,5,7,9]) B = np.asarray([2,4,6,8,10]) </code></pre> <p>I want to create:</p> <pre><code>C = np.asarray([1,2,3, 4,5,6,7,8,9,10]) </code></pre> <p>Is there a better way to do than to run a for loop</p>
0
2016-10-06T16:27:46Z
39,901,293
<p>Try the following :</p> <pre><code>import numpy as np A = np.asarray([1,3,5,7,9]) B = np.asarray([2,4,6,8,10]) C = np.sort(np.hstack((A,B))) #array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) </code></pre>
0
2016-10-06T16:32:25Z
[ "python", "numpy" ]
pytest: xfail on given exception, pass otherwise
39,901,211
<p>I have a test that uses <code>requests</code> and needs an active connection.</p> <p>I would like it to <code>xfail</code> if the connection is down but pass normally otherwise.</p> <p>Here is what I tried:</p> <pre><code>from requests import ConnectionError @pytest.mark.xfail(raises=ConnectionError) class TestS...
1
2016-10-06T16:27:52Z
39,983,314
<p>pytest supports imperative xfail from within a test or setup function.</p> <p>Use the try/except code you have, and include <code>pytest.xfail('some message')</code> in the <code>except</code> body.</p> <p>See: <a href="http://doc.pytest.org/en/latest/skipping.html#imperative-xfail-from-within-a-test-or-setup-func...
1
2016-10-11T17:39:13Z
[ "python", "py.test" ]
pytest: xfail on given exception, pass otherwise
39,901,211
<p>I have a test that uses <code>requests</code> and needs an active connection.</p> <p>I would like it to <code>xfail</code> if the connection is down but pass normally otherwise.</p> <p>Here is what I tried:</p> <pre><code>from requests import ConnectionError @pytest.mark.xfail(raises=ConnectionError) class TestS...
1
2016-10-06T16:27:52Z
39,992,948
<p>Calling <code>xfail</code> when <code>ConnectionError</code> was caught is a solution.</p> <p>It is even better to check connection in a fixture (the same way - try-except with <code>pytest.xfail</code>) and use that fixture in all tests that need a connection. </p> <p>That way such fixture will cause all dependen...
1
2016-10-12T07:33:30Z
[ "python", "py.test" ]
How to implement quaternary search?
39,901,240
<p>I know this algorithm is no better than binary search, but it's an interesting thought experiment for understanding recursion. I haven't been able to get very far on this though(way too much recursion for my brain to handle.). Anyone know how to actually implement this?</p> <p>I have the following, which is nowhe...
0
2016-10-06T16:29:32Z
39,901,503
<p>Start with a correct implementation of binary search. Then replace each recursive call with an inline version of the whole search (minus any initialization), i.e expand the binary search code in place as if it were a macro expansion [change variable names as necessary]. I believe if you do it right you will then h...
0
2016-10-06T16:45:06Z
[ "python", "algorithm", "search", "binary-search" ]
How to implement quaternary search?
39,901,240
<p>I know this algorithm is no better than binary search, but it's an interesting thought experiment for understanding recursion. I haven't been able to get very far on this though(way too much recursion for my brain to handle.). Anyone know how to actually implement this?</p> <p>I have the following, which is nowhe...
0
2016-10-06T16:29:32Z
39,902,159
<p>How is this solution ? </p> <pre><code>#start = 0 #first_quarter = int(len(a_list)/4) - 1 #mid_point = int(len(a_list)/2) - 1 #third_quarter = int(len(a_list)*3/4) - 1 #end = len(a_list) - 1 def search(a_list, elem): return search_recur(a_list, elem, *generate_quartets(a_list, 0)) def generate_quartets(a_list...
1
2016-10-06T17:23:35Z
[ "python", "algorithm", "search", "binary-search" ]
When using Q objects in django queryset for OR condition error occured
39,901,266
<p>I want to use filter with OR condition in django. For this i want to use Q objects. My code is this</p> <pre><code>def product(request): try: proTitle = request.GET.get('title') ProDescription = request.GET.get('description') except: pass list0 = [] result = Product.obje...
1
2016-10-06T16:31:19Z
39,901,483
<p>You may set the defaults of the <code>get</code> method to something other than <code>None</code>, say empty string:</p> <pre><code>proTitle = request.GET.get('title', '') ProDescription = request.GET.get('description', '') funAria = request.GET.get('funAria', '') femaleReq = request.GET.get('femaleReq', '') </code...
1
2016-10-06T16:43:44Z
[ "python", "django" ]
When using Q objects in django queryset for OR condition error occured
39,901,266
<p>I want to use filter with OR condition in django. For this i want to use Q objects. My code is this</p> <pre><code>def product(request): try: proTitle = request.GET.get('title') ProDescription = request.GET.get('description') except: pass list0 = [] result = Product.obje...
1
2016-10-06T16:31:19Z
39,901,487
<p>You can build the <code>Q</code> object in a loop, discarding all values that are none. Note that after consideration, it appears that your <code>except</code> will never be reached because <code>get</code> will simply return <code>None</code> if the Get parameter is not present. You can thus replace the <code>try</...
0
2016-10-06T16:44:10Z
[ "python", "django" ]
When using Q objects in django queryset for OR condition error occured
39,901,266
<p>I want to use filter with OR condition in django. For this i want to use Q objects. My code is this</p> <pre><code>def product(request): try: proTitle = request.GET.get('title') ProDescription = request.GET.get('description') except: pass list0 = [] result = Product.obje...
1
2016-10-06T16:31:19Z
39,901,520
<p>Your error seems to mean that one of your values is <code>None</code>:</p> <pre><code>def product(request): try: proTitle = request.GET.get('title') ProDescription = request.GET.get('description') funAria = request.GET.get('funAria') femaleReq = request.GET.get('femaleReq') ...
0
2016-10-06T16:45:57Z
[ "python", "django" ]
Write a list into a file onto HDFS
39,901,442
<p>I am writing a python code to run on a Hadoop Cluster and need to store some intermediate data in a file. Since I want to run the code on the cluster, I want to write the intermediate data into the <code>/tmp</code> directory on HDFS. I will delete the file immediately after I use it for the next steps. How can I do...
0
2016-10-06T16:41:12Z
39,903,286
<p>You're facing that error because HDFS cannot append the files when written from shell. You need to create new files each time you want to dump files.</p> <p>A better way to do this would be to use a python HDFS client to do the dumping for you. I can recommend <a href="https://github.com/spotify/snakebite" rel="nof...
0
2016-10-06T18:32:08Z
[ "python", "hadoop", "subprocess" ]
compare List of attributes against an object inside list
39,901,524
<p>This is how my Input looks like:</p> <pre><code>cust1Attributes = [{'Key': 'FirstName', 'Value': 'SomeFirstName'}, {'Key': 'LastName', 'Value': 'SomeLastName'}] </code></pre> <p>This is how my MandatoryData list looks like:</p> <pre><code>class MustHaveData(object): def __init__(self, name, defaultValue): ...
0
2016-10-06T16:46:12Z
39,901,644
<p>Build a <em>set</em> from the dictionary containing the items at each <code>Key</code> and use a <em>list comprehension</em> to filter out objects with names in the set:</p> <pre><code>custset = {x['Key'] for x in cust1Attributes} result = [obj for obj in customerMandatoryData if obj.name not in custset] </code></p...
2
2016-10-06T16:53:56Z
[ "python" ]
how to make if conditions work with specific string characters?
39,901,537
<p>I want to develop a program that takes input in the form of bits and outputs the decimal equivalent. </p> <p>I am restricted in the kind of functions I can use so this is what I came up with:</p> <pre><code>digits=raw_input("enter 1's and 0's") a=len(digits) repeat=a c=0 total=0 while (c &lt; repeat): if digit...
0
2016-10-06T16:46:53Z
39,901,728
<p><code>if 1==1</code> means if number 1 is equal 1</p> <p><code>if "1"=="1"</code> means if string ("1") is equal "1"</p> <p>You need to learn difference between data types.</p> <pre><code>counter = 100 # An integer assignment miles = 1000.0 # A floating point name = "John" # A string </c...
1
2016-10-06T16:58:25Z
[ "python" ]
how to make if conditions work with specific string characters?
39,901,537
<p>I want to develop a program that takes input in the form of bits and outputs the decimal equivalent. </p> <p>I am restricted in the kind of functions I can use so this is what I came up with:</p> <pre><code>digits=raw_input("enter 1's and 0's") a=len(digits) repeat=a c=0 total=0 while (c &lt; repeat): if digit...
0
2016-10-06T16:46:53Z
39,901,770
<p>The reason its not working is that the variable digits is string and when you compare it with integer one it won't work you have to convert it to the below</p> <pre><code>if int(digits[c]) == 1: </code></pre> <p>or </p> <pre><code>if str(digits[c]) == "1": </code></pre> <p>Also your code has a lot of unwanted li...
0
2016-10-06T17:00:31Z
[ "python" ]
Python: UserWarning: This pattern has match groups. To actually get the groups, use str.extract
39,901,550
<p>I have a dataframe and I try to get string, where on of column contain some string Df looks like</p> <pre><code>member_id,event_path,event_time,event_duration 30595,"2016-03-30 12:27:33",yandex.ru/,1 30595,"2016-03-30 12:31:42",yandex.ru/,0 30595,"2016-03-30 12:31:43",yandex.ru/search/?lr=10738&amp;msid=22901.25826...
2
2016-10-06T16:47:36Z
39,902,267
<p>At least one of the regex patterns in <code>urls</code> must use a capturing group. <code>str.contains</code> only returns True or False for each row in <code>df['event_time']</code> -- it does not make use of the capturing group. Thus, the <code>UserWarning</code> is alerting you that the regex uses a capturing gro...
3
2016-10-06T17:30:23Z
[ "python", "regex", "pandas" ]
Parsing HTML with Beautiful Soup to get link after href
39,901,554
<p>This is a result of a <code>find_all('a')</code> (it's very long):</p> <pre><code>&lt;/a&gt;, &lt;a class="btn text-default text-dark clear_filters pull-right group-ib" href="#" id="export_dialog_close" title="Cancel"&gt;&lt;span class="glyphicon glyphicon-remove"&gt;&lt;/span&gt;&lt;span&gt;Cancel&lt;/span&gt;&lt;...
2
2016-10-06T16:47:52Z
39,901,685
<p>Try the following list comprehension:</p> <pre><code>[h.get('href') for h in ase if 'string' in h.get('href', '')] </code></pre> <p>This will give you a list containing only the links that contain the substring <code>'string'</code>.</p> <h1>Update:</h1> <p>As <strong>@PadraicCunningham</strong> pointed out in ...
2
2016-10-06T16:56:11Z
[ "python", "html", "beautifulsoup" ]
Parsing HTML with Beautiful Soup to get link after href
39,901,554
<p>This is a result of a <code>find_all('a')</code> (it's very long):</p> <pre><code>&lt;/a&gt;, &lt;a class="btn text-default text-dark clear_filters pull-right group-ib" href="#" id="export_dialog_close" title="Cancel"&gt;&lt;span class="glyphicon glyphicon-remove"&gt;&lt;/span&gt;&lt;span&gt;Cancel&lt;/span&gt;&lt;...
2
2016-10-06T16:47:52Z
39,901,769
<p>I would still advice you to use regex, as it is more concise and saves you another loop over the list. </p> <pre><code>import re find_all('a', href=re.compile("/en/ais/details/ships/shipid:")) </code></pre> <p>In the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all" rel="nofollow">documenta...
0
2016-10-06T17:00:30Z
[ "python", "html", "beautifulsoup" ]
Parsing HTML with Beautiful Soup to get link after href
39,901,554
<p>This is a result of a <code>find_all('a')</code> (it's very long):</p> <pre><code>&lt;/a&gt;, &lt;a class="btn text-default text-dark clear_filters pull-right group-ib" href="#" id="export_dialog_close" title="Cancel"&gt;&lt;span class="glyphicon glyphicon-remove"&gt;&lt;/span&gt;&lt;span&gt;Cancel&lt;/span&gt;&lt;...
2
2016-10-06T16:47:52Z
39,903,911
<p><a href="http://stackoverflow.com/a/39901685/771848">@elethan's answer</a> is not the best one. It would <strong>find you all the links and only then filter them out</strong>. Why don't we just <em>get the links we needed straight with no extra filtering</em> - <code>BeautifulSoup</code> is very capable of that:</p>...
3
2016-10-06T19:09:48Z
[ "python", "html", "beautifulsoup" ]
Creating a dictionary in python by combining two .csv files
39,901,640
<p>I am trying to create a dictionary in python by combining data from two .csv files, by matching the first column of the two files. This is what I have so far </p> <pre><code>import csv with open('a.csv', 'r') as my_file1 : rows1 = list(csv.reader(my_file1)) with open('aa.csv', 'r') as my_file2 : rows2 = l...
1
2016-10-06T16:53:46Z
39,901,719
<p>You're creating a new dictionary on every iteration of your <code>for</code>, so only the update from the last iteration is kept, others have been thrown away.</p> <p>You can solve this by moving the dictionary setup outside the <code>for</code>:</p> <pre><code>new_dict = {} for i in range(10): ... </code></pr...
1
2016-10-06T16:58:00Z
[ "python", "dictionary" ]
Python: printing result of multiple inputs
39,901,750
<p>I'm pretty new to python programming, but i'm trying to write a program that goes as follows:</p> <p>First: the program asks the user for a fixed number. Then: the user can input as many numbers as he wants, until he writes "stop". (this is not really where i'm having trouble)</p> <p>the output needs to be somethi...
-3
2016-10-06T16:59:16Z
39,901,862
<pre><code>input_list = [] sum = 0 while True: user_input = int(input('Enter the number')) if user_input != 'stop' input_list.append(user_input) elif user_input == 'stop': break; for i in input_list: sum += i print(sum) </code></pre>
0
2016-10-06T17:05:26Z
[ "python", "loops", "sum" ]
Python: printing result of multiple inputs
39,901,750
<p>I'm pretty new to python programming, but i'm trying to write a program that goes as follows:</p> <p>First: the program asks the user for a fixed number. Then: the user can input as many numbers as he wants, until he writes "stop". (this is not really where i'm having trouble)</p> <p>the output needs to be somethi...
-3
2016-10-06T16:59:16Z
39,902,077
<pre><code>random_number = int(input("Enter random number:")) number_list = [random_number] flag = True while flag: try: number = int(input("Enter number: ")) number_list.append(number) except: # if not a number, break the loop flag = False print random_number for i in range(1...
0
2016-10-06T17:18:28Z
[ "python", "loops", "sum" ]
asyncio server and client to handle input from console
39,901,813
<p>I have an asyncio TCP server that take messages from client, do stuff() on server and sends texts back. Server works well in the sense that receives and sends data correctly. Problem is that I can't takes messages back from server in the client because I have the blocking routine on input from console (basically the...
0
2016-10-06T17:02:51Z
39,903,445
<p>I've found solution to implement an async_input for asyncio here: <a href="https://gist.github.com/nathan-hoad/8966377" rel="nofollow">https://gist.github.com/nathan-hoad/8966377</a></p> <p>Just need to fix imports for Stream classes for python 3.5</p>
0
2016-10-06T18:40:50Z
[ "python", "tcpclient", "python-asyncio" ]
asyncio server and client to handle input from console
39,901,813
<p>I have an asyncio TCP server that take messages from client, do stuff() on server and sends texts back. Server works well in the sense that receives and sends data correctly. Problem is that I can't takes messages back from server in the client because I have the blocking routine on input from console (basically the...
0
2016-10-06T17:02:51Z
39,914,294
<p>You could consider using <a href="https://github.com/vxgmichel/aioconsole" rel="nofollow">aioconsole.ainput</a>:</p> <pre><code>from aioconsole import ainput async def some_coroutine(): line = await ainput("&gt;&gt;&gt; ") [...] </code></pre> <p>The project is available on <a href="https://pypi.python.org...
1
2016-10-07T09:48:22Z
[ "python", "tcpclient", "python-asyncio" ]
Assigning float as a dictionary key changes its precision (Python)
39,901,833
<p>I have a list of floats (actually it's a pandas Series object, if it changes anything) which looks like this:</p> <pre><code>mySeries: ... 22 16.0 23 14.0 24 12.0 25 10.0 26 3.1 ... </code></pre> <p>(So elements of this Series are on the right, indices on the left.) Then I'm trying to as...
4
2016-10-06T17:03:38Z
39,901,950
<p>The value is already that way in the Series:</p> <pre><code>&gt;&gt;&gt; x = pd.Series([16,14,12,10,3.1]) &gt;&gt;&gt; x 0 16.0 1 14.0 2 12.0 3 10.0 4 3.1 dtype: float64 &gt;&gt;&gt; x.iloc[4] 3.1000000000000001 </code></pre> <p>This has to do with floating point precision:</p> <pre><code>&gt;&gt;...
3
2016-10-06T17:10:35Z
[ "python", "pandas", "dictionary", "floating-point" ]
Assigning float as a dictionary key changes its precision (Python)
39,901,833
<p>I have a list of floats (actually it's a pandas Series object, if it changes anything) which looks like this:</p> <pre><code>mySeries: ... 22 16.0 23 14.0 24 12.0 25 10.0 26 3.1 ... </code></pre> <p>(So elements of this Series are on the right, indices on the left.) Then I'm trying to as...
4
2016-10-06T17:03:38Z
39,901,954
<p>The dictionary isn't changing the floating point representation of 3.1, but it is actually displaying the full precision. Your print of mySeries[26] is truncating the precision and showing an approximation.</p> <p>You can prove this:</p> <pre><code>pd.set_option('precision', 20) </code></pre> <p>Then view mySerie...
6
2016-10-06T17:10:56Z
[ "python", "pandas", "dictionary", "floating-point" ]
Assigning float as a dictionary key changes its precision (Python)
39,901,833
<p>I have a list of floats (actually it's a pandas Series object, if it changes anything) which looks like this:</p> <pre><code>mySeries: ... 22 16.0 23 14.0 24 12.0 25 10.0 26 3.1 ... </code></pre> <p>(So elements of this Series are on the right, indices on the left.) Then I'm trying to as...
4
2016-10-06T17:03:38Z
39,901,991
<p>You can round it to the accuracy you can accept:</p> <pre><code>&gt;&gt;&gt; hash(round(3.1, 2)) 2093862195 &gt;&gt;&gt; hash(round(3.1000000000000001, 2)) 2093862195 </code></pre>
0
2016-10-06T17:13:11Z
[ "python", "pandas", "dictionary", "floating-point" ]
Webscraping using Python - Link is unchanged with form input
39,901,841
<p>I planned to retrieve the historical data from the open web available. From the link:</p> <p><a href="https://www.entsoe.eu/db-query/consumption/mhlv-a-specific-country-for-a-specific-day" rel="nofollow">https://www.entsoe.eu/db-query/consumption/mhlv-a-specific-country-for-a-specific-day</a></p> <p>Ideally, I am ...
0
2016-10-06T17:04:04Z
39,903,792
<p>First of all, you need to understand what happens when you click "Send" button. A POST request is sent to the same URL with parameters corresponding to values you've selected on the form. You can see this request in the browser developer tools - "Network" tab. Now, you need to simulate this request in your code (I'l...
1
2016-10-06T19:03:23Z
[ "python", "web-scraping", "beautifulsoup", "scrapy", "mechanize" ]
What does defining a function with in the __init__ constructor in python mean?
39,901,860
<p>I have just seen the following code and would like to know what the function within the <code>__init__</code> function means</p> <pre><code>def __init__(self): def program(percept): return raw_input('Percept=%s; action? ' % percept) self.program = program self.alive = True </code></pre>
0
2016-10-06T17:05:20Z
39,902,110
<p>This code</p> <pre><code>class Foo: def __init__(self): def program(percept): return raw_input('Percept=%s; action? ' % percept) self.program = program </code></pre> <p>AFAIK, is actually the exact same as this since <code>self.program = program</code>. </p> <pre><code>class Foo: ...
0
2016-10-06T17:20:29Z
[ "python", "constructor", "init" ]
adding tuples to a list in an if loop (python)
39,901,930
<p>I'm working in python with symbulate for a probability course and running some simulations. </p> <p>Setup: Two teams, A and B, are playing in a “best of n” game championship series, where n is an odd number. For this example, n=7, and the probability team A wins any individual game is 0.55. Approximate the prob...
-1
2016-10-06T17:09:28Z
39,901,955
<p>So you're looking to store the results of each test? Why not store them in a <code>list</code>?</p> <pre><code>test1_results = [] for x in range(0,10000): test1 = test[x] # check if first element in sequence of game outcomes is a win for team A if test1[0] == 1: # or '1' if you're expecting string ...
1
2016-10-06T17:11:02Z
[ "python" ]
adding tuples to a list in an if loop (python)
39,901,930
<p>I'm working in python with symbulate for a probability course and running some simulations. </p> <p>Setup: Two teams, A and B, are playing in a “best of n” game championship series, where n is an odd number. For this example, n=7, and the probability team A wins any individual game is 0.55. Approximate the prob...
-1
2016-10-06T17:09:28Z
39,901,996
<p>Based on your comment:</p> <pre><code>results_that_start_with_one = [] for result in test: result_string = str(result) if result_string[0] == "1": results_that_start_with_one.append(result_string) </code></pre> <p>This iterates through each of your results in the list "test". It convert each t...
0
2016-10-06T17:13:20Z
[ "python" ]
Django: How do you associate an Object_PK in the URL to the Foreign_Key relation field when creating a new object?
39,902,029
<p>I am building an FAQ system. The models extend from Topic -> Section -> Article. When creating a new Article the User will select a Topic then a Section then the create Article button.</p> <p>The url will look something like //mysite.org/Topic_PK/Section_PK/Article_Create</p> <p>In Django it should look like this:...
0
2016-10-06T17:15:19Z
39,912,337
<p>Let's say that you have this url</p> <pre><code>url(r'^ironfaq/(?P&lt;topic_pk&gt;\d+)/article/create$', ArticleCreateView.as_view(), name=’article-create’) </code></pre> <p>Where <code>topic_pk</code> will be pk of topic you want to be associated with your Article. </p> <p>Then you just need to retrieve it i...
0
2016-10-07T08:01:06Z
[ "python", "django" ]
Django - Template tags not working properly after form validation
39,902,092
<p>I am having a form which takes some value as input, and I am processing the input and returning the required output. Now when I tried to display the output it not displaying on the webpage. </p> <p>The following is my forms.py:</p> <pre><code>class CompForm(forms.ModelForm): class Meta: model = Comp ...
0
2016-10-06T17:19:37Z
39,902,200
<p>You are trying to called the method <code>as_p</code> on strings which doesn't make sense. </p> <p><a href="https://docs.djangoproject.com/en/1.10/topics/forms/#form-rendering-options" rel="nofollow"><code>as_p()</code></a> is a helper method on form instances to make it easier to render them in the template so you...
1
2016-10-06T17:26:07Z
[ "python", "django" ]
passing radio buttons from javascript to django views as a paramater
39,902,125
<p>I have a html page where I am passing the selected checkboxes to django views as parameter which works completely fine.</p> <p>layout.html</p> <pre><code>&lt;form action="{% url 'URL Which calls view' %}" method="post"&gt; {% csrf_token %} &lt;label class="checkbox"&gt; &lt;input type="checkbox" name="checks" va...
1
2016-10-06T17:21:16Z
39,904,750
<p>Django will not handle onClick events or anything of sort, you are better off with javascript and or jquery for that.</p> <p><strong>Jquery</strong></p> <pre><code>$(function(){ $('input[type="radio"]').click(function(){ if ($(this).is(':checked')) { alert($(this).val()); } }); }); </code></p...
0
2016-10-06T20:04:18Z
[ "php", "python", "html", "django" ]
Generate features from "comments" column in dataframe
39,902,151
<p>I have a dataset with a column that has comments. This comments are words separated by commas.</p> <p>df_pat['reason'] = </p> <ol> <li>chest pain</li> <li>chest pain, dyspnea</li> <li>chest pain, hypertrophic obstructive cariomyop...</li> <li>chest pain </li> <li>chest pain</li> <li>cad, rca stents</li> <li>non-is...
0
2016-10-06T17:22:52Z
39,902,292
<p><code>sklearn.feature_extraction.text</code> has something for you! It looks like you may be trying to predict something. If so - and if you're planning to use sci-kit learn at some point, then you can bypass making a dataframe with len(set(words)) number of columns and just use <code>CountVectorizer</code>. This me...
0
2016-10-06T17:31:55Z
[ "python", "text", "dataframe", "comments" ]
install theano with python centos-7
39,902,181
<p>I could successfully install theano with python2 by following the instructions here <a href="http://deeplearning.net/software/theano/install_centos6.html#install-centos6" rel="nofollow">http://deeplearning.net/software/theano/install_centos6.html#install-centos6</a>. Since I do not have root access, I asked my admin...
0
2016-10-06T17:25:08Z
39,916,218
<p>Seems like you didn't correctly install all the header files and static libraries for python dev. If you have administrative problems you can use Anaconda from <code>https://www.continuum.io/downloads</code> Else, the most preferred way is using your package manager to install them system-wide. </p> <p><code>sudo ...
1
2016-10-07T11:32:43Z
[ "python", "centos", "theano" ]
Setting up PyOpenGL with freeglut for Python 3.5.2
39,902,238
<p>I am trying to set up my machine to use PyOpenGL with freeglut. I have Python version 3.5.2 and a 64 bit copy of Windows 8.</p> <p>I have downloaded PyOpenGL using pip, then downloaded freeglut and placed the <code>include\</code> and <code>lib\</code> folders at <code>C:\Program Files\Common Files\MSVC\freeglut</c...
0
2016-10-06T17:28:45Z
39,902,290
<p>place the <code>glut32.dll</code> next to the <code>py</code> file.</p> <p>Check this <a href="http://stackoverflow.com/questions/39181192/attempt-to-call-an-undefined-function-glutinit">link</a></p>
0
2016-10-06T17:31:55Z
[ "python", "freeglut", "pyopengl" ]
Setting up PyOpenGL with freeglut for Python 3.5.2
39,902,238
<p>I am trying to set up my machine to use PyOpenGL with freeglut. I have Python version 3.5.2 and a 64 bit copy of Windows 8.</p> <p>I have downloaded PyOpenGL using pip, then downloaded freeglut and placed the <code>include\</code> and <code>lib\</code> folders at <code>C:\Program Files\Common Files\MSVC\freeglut</c...
0
2016-10-06T17:28:45Z
39,906,848
<p>I fixed this by switching to the 32 bit <code>freeglut.dll</code> file. I thought that the 32bit vs 64bit was dependent on your operating system but it's actually dependent on which kind of Python you have, as I have 32 bit Python I need the 32 bit dll.</p>
0
2016-10-06T22:55:09Z
[ "python", "freeglut", "pyopengl" ]
Multiple relative Imports in python 3.5
39,902,333
<p>This structure is just an example</p> <pre><code>pkg\ test\ __init__.py test.py __init__.py source.py another_source.py </code></pre> <p>another_source.py</p> <pre><code>class Bar(): def __init__(self): self.name = "bar" </code></pre> <p>source.py</p> <pre><code>from another_source import ...
2
2016-10-06T17:35:23Z
39,902,394
<p><code>pkg.source</code> is trying to import things from the <code>pkg.another_source</code> module as if it were top-level. That import needs to be corrected:</p> <pre><code>from .another_source import Bar # or from pkg.another_source import another_source </code></pre>
1
2016-10-06T17:38:31Z
[ "python" ]
How to set the current working directory in the Python sh module?
39,902,365
<p>Is there a way to set the current working directory within a call to the Python <a href="http://amoffat.github.io/sh/" rel="nofollow">sh</a> module?</p> <p>I'd like to be able to execute a command --- and only the command --- in a different directory than the one I'm currently in. Something along the lines of:</p> ...
0
2016-10-06T17:37:18Z
39,902,550
<p>Use the <a href="https://amoffat.github.io/sh/special_arguments.html#special-keyword-arguments" rel="nofollow"><code>_cwd</code> parameter</a> to set the current working directory on a per-command basis:</p> <pre><code>import sh print(sh.ls(_cwd='/tmp')) </code></pre> <p>This works for any command, not just <code>...
1
2016-10-06T17:48:36Z
[ "python" ]
pyspark redueByKey modify single results
39,902,387
<p>I have a dataset that looks like this in pyspark:</p> <pre><code>samp = sc.parallelize([(1,'TAGA'), (1, 'TGGA'), (1, 'ATGA'), (1, 'GTGT'), (2, 'GTAT'), (2, 'ATGT'), (3, 'TAAT'), (4, 'TAGC')]) </code></pre> <p>I have a function that I'm using to combine the strings:</p> <pre><code> def combine_strings(x,y): ...
0
2016-10-06T17:38:14Z
39,902,956
<p>You could first map the values into lists and then only combine those lists:</p> <pre><code>samp.mapValues(lambda x : [x]).reduceByKey(lambda x,y : x + y).collect() </code></pre> <p>The problem here is that those singletons are not affected by <code>reduceByKey</code>. Here is another example:</p> <pre><code>samp...
0
2016-10-06T18:13:41Z
[ "python", "mapreduce", "pyspark" ]
FullCalendar in Django
39,902,405
<p>So, I have an appointment models </p> <pre><code>class Appointment(models.Model): user = models.ForeignKey(User) date = models.DateField() time = models.TimeField() doctorName = models.CharField(max_length=50)` </code></pre> <p>And I want to implement this in the <code>FullCalendar</code> tool. I'm...
1
2016-10-06T17:39:23Z
39,904,284
<p>Since your question shows you haven't tried anything , guessing you know javascript and tried some hands on full calendar js.</p> <p>Suppose you have model named Event for displaying different events in calendar.</p> <pre><code>class Events(models.Model): even_id = models.AutoField(primary_key=True) event_...
3
2016-10-06T19:34:49Z
[ "python", "django", "fullcalendar" ]
Bug with a program for a guessing game
39,902,412
<p>I am creating a program where a user had to guess a random number in a specific range and has 3 tries to do so. After each try, if the guess is correct you tell the user they won and if the guess is wrong you tell them its wrong and how many tries they have got remaining. When the number of tries exceed 3 without a ...
1
2016-10-06T17:39:52Z
39,902,488
<p>You need to make guess equal to <code>True</code> in your second <code>else</code> or else it will never satisfy stop condition for while loop. Do you understand?</p> <pre><code>import random x =round(random.random()*5) guess = False tries = 0 while guess != True: if tries&lt;=3: inp = input("Guess the ...
1
2016-10-06T17:44:28Z
[ "python", "python-2.7" ]
Bug with a program for a guessing game
39,902,412
<p>I am creating a program where a user had to guess a random number in a specific range and has 3 tries to do so. After each try, if the guess is correct you tell the user they won and if the guess is wrong you tell them its wrong and how many tries they have got remaining. When the number of tries exceed 3 without a ...
1
2016-10-06T17:39:52Z
39,902,495
<p>You need to update tries. Additionally you need to break out of your loop even if guess != True</p> <pre><code>import random x =round(random.random()*5) guess = False tries = 0 while guess != True: if tries&lt;=3: inp = input("Guess the number: ") if tries&lt;3: if inp == x: ...
0
2016-10-06T17:44:55Z
[ "python", "python-2.7" ]
Bug with a program for a guessing game
39,902,412
<p>I am creating a program where a user had to guess a random number in a specific range and has 3 tries to do so. After each try, if the guess is correct you tell the user they won and if the guess is wrong you tell them its wrong and how many tries they have got remaining. When the number of tries exceed 3 without a ...
1
2016-10-06T17:39:52Z
39,902,501
<p>You need to move where you set guess = True</p> <pre><code>import random x =round(random.random()*5) guess = False tries = 0 while guess != True: if tries&lt;=3: inp = input("Guess the number: ") if tries&lt;3: if inp == x: guess = True print "Correct!...
1
2016-10-06T17:45:19Z
[ "python", "python-2.7" ]
Bug with a program for a guessing game
39,902,412
<p>I am creating a program where a user had to guess a random number in a specific range and has 3 tries to do so. After each try, if the guess is correct you tell the user they won and if the guess is wrong you tell them its wrong and how many tries they have got remaining. When the number of tries exceed 3 without a ...
1
2016-10-06T17:39:52Z
39,902,534
<p>I guess this is it. Tested this out. Working Perfect (Y)</p> <pre><code>import random x =round(random.random()*5) guess = False tries = 0 while guess != True: if tries&lt;=3: inp = input("Guess the number: ") if tries&lt;3: if inp == x: guess = True pr...
3
2016-10-06T17:47:24Z
[ "python", "python-2.7" ]