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
Cleaner method for finding the shortest distance between points in a python list?
39,396,310
<p>I have a list of tuples and an individual point in python e.g. [(1,2) , (2,5), (6,7), (9,3)] and (2,1) , and I want to figure out the fastest path possible created by all combinations of the individual point to the list of points.(Basically I want to find the most efficient way to get to all of the points starting f...
2
2016-09-08T16:44:04Z
39,396,555
<p>Try to find all combination, then check the shortest distance.</p>
-1
2016-09-08T17:00:05Z
[ "python", "for-loop", "while-loop", "distance", "heuristics" ]
Cleaner method for finding the shortest distance between points in a python list?
39,396,310
<p>I have a list of tuples and an individual point in python e.g. [(1,2) , (2,5), (6,7), (9,3)] and (2,1) , and I want to figure out the fastest path possible created by all combinations of the individual point to the list of points.(Basically I want to find the most efficient way to get to all of the points starting f...
2
2016-09-08T16:44:04Z
39,396,903
<p>Since you don't have so many point, you can easily use a solution that try every possibility.</p> <p>Here is what you can do:</p> <p>First get all combinations:</p> <pre><code>&gt;&gt;&gt; list_of_points = [(1,2) , (2,5), (6,7), (9,3)] &gt;&gt;&gt; list(itertools.permutations(list_of_points)) [((1, 2), (2, 5), (6...
2
2016-09-08T17:23:58Z
[ "python", "for-loop", "while-loop", "distance", "heuristics" ]
Cleaner method for finding the shortest distance between points in a python list?
39,396,310
<p>I have a list of tuples and an individual point in python e.g. [(1,2) , (2,5), (6,7), (9,3)] and (2,1) , and I want to figure out the fastest path possible created by all combinations of the individual point to the list of points.(Basically I want to find the most efficient way to get to all of the points starting f...
2
2016-09-08T16:44:04Z
39,397,687
<p>If this is anything like the traveling salesman problem, then you want to check out the <a href="https://networkx.github.io/" rel="nofollow">NetworkX</a> python module. </p>
0
2016-09-08T18:17:43Z
[ "python", "for-loop", "while-loop", "distance", "heuristics" ]
Making a Twitter clone in Django, having trouble with displaying the right user when displaying tweets
39,396,328
<p>I have user registration. Whenever I log in as a certain user, all the tweets are said to be tweeted by that user, even if it wasn't.</p> <p><strong>forms.py</strong></p> <pre><code>from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField...
-1
2016-09-08T16:44:55Z
39,396,363
<p>In your template, you are showing the logged in user <code>{{user.username}}</code> instead of <code>{{howl.author.username}}</code></p>
0
2016-09-08T16:47:19Z
[ "python", "django" ]
Making a Twitter clone in Django, having trouble with displaying the right user when displaying tweets
39,396,328
<p>I have user registration. Whenever I log in as a certain user, all the tweets are said to be tweeted by that user, even if it wasn't.</p> <p><strong>forms.py</strong></p> <pre><code>from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField...
-1
2016-09-08T16:44:55Z
39,399,445
<p>On my HowlCreate view, I didn't set the author to the howl. I only set the content. </p> <pre><code>class HowlCreate(CreateView): model = Howl fields = ['content'] # This sets up the author def form_valid(self, form): instance = form.save(commit=False) instance.author = self.reques...
0
2016-09-08T20:14:34Z
[ "python", "django" ]
Kivy: get parent inside widget which is added in python
39,396,372
<p>How do I get the reference to a parent inside a widget that is not added by kvlang but in python. Normally you would just call <code>self.parent</code> however that returns <code>Null</code> if the widget is added in python to the parent.</p> <p>An example:</p> <pre><code>import kivy kivy.require('1.9.0') # replac...
0
2016-09-08T16:47:38Z
39,399,594
<p>Widgets added with <code>add_widget</code> actually has a valid reference to their parent:</p> <pre><code>from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen from kivy.lang import Builder Builder.load_string(''' &lt;ScreenTwo&gt; Label: text: 'Hello, world' ''') class...
0
2016-09-08T20:24:25Z
[ "python", "kivy" ]
Is there a way to use the python -m mymod syntax from within the python interpreter?
39,396,373
<p>Many packages like unittest have an easy to use command line interface, e.g. the test discovery feature in unittest: <a href="https://docs.python.org/2/library/unittest.html#test-discovery" rel="nofollow">https://docs.python.org/2/library/unittest.html#test-discovery</a></p> <p>However, to achieve the same from wit...
0
2016-09-08T16:47:38Z
39,401,172
<p>You can use the <a href="https://docs.python.org/2/library/runpy.html#runpy.run_module" rel="nofollow"><code>runpy.run_module</code> function</a>:</p> <pre><code>import runpy import sys sys.argv[1:] = ['arg1', 'arg2', 'arg3'] runpy.run_module('module.name', run_name='__main__', alter_sys=True) </code></pre> <p>Th...
1
2016-09-08T22:34:11Z
[ "python" ]
logging how to control the times in which flush to log file
39,396,393
<p>I've to use logging module and wonder if there is a way to log into existing log file , by appending my data to the existing file and more important if I can control the times I flush into the file.</p> <p>Currently I need to be able to flush all the time to the file because, there are cases in which the script run...
1
2016-09-08T16:48:44Z
39,396,567
<p>If you use <code>logging.FileHandler</code> and choose an existing log file, by default it will append to that file. The method that actually writes the log record is the <code>emit()</code> method on logging handlers. If you look at the source code for the <code>FileHandler</code>, it <code>flush</code>'s after <...
1
2016-09-08T17:00:36Z
[ "python", "python-2.7", "logging", "flush" ]
Django refuses to accept my one-off default value for FloatField
39,396,610
<p>I have a class and I'm trying to add a new <code>FloatField</code> to it. Django wants a default value to populate existing rows (reasonable). However, it refuses to accept any value I give it.</p> <pre><code>You are trying to add a non-nullable field 'FIELDNAME' to CLASS without a default; we can't do that (the da...
1
2016-09-08T17:03:18Z
39,396,672
<p>You should select option 1 and then input your value</p> <pre><code> 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py 1 </code></pre> <p>After selecting 1. It would ask to provide your default value.</p> <pre><co...
1
2016-09-08T17:08:05Z
[ "python", "django" ]
Adding Lat Lon coordinates to separate columns (python/dataframe)
39,396,678
<p>I'm sure this is a simple thing to do but I am new to Python and cannot work it out!</p> <p>I have a data frame with one column containing coordinates and I am wanting to remove the brackets and add the Lat/Lon values into separate columns.</p> <p>Current dataframe:</p> <pre><code>gridReference (56.37769816725615...
-1
2016-09-08T17:08:18Z
39,396,974
<pre><code>&gt;&gt;&gt; df = pd.DataFrame({'latlong': ['(12, 32)', '(43, 54)']}) &gt;&gt;&gt; df latlong 0 (12, 32) 1 (43, 54) &gt;&gt;&gt; split_data = df.latlong.str.strip(')').str.strip('(').str.split(', ') &gt;&gt;&gt; df['lat'] = split_data.apply(lambda x: x[0]) &gt;&gt;&gt; df['long'] = split_data.apply(la...
0
2016-09-08T17:29:10Z
[ "python", "pandas", "dataframe" ]
Adding Lat Lon coordinates to separate columns (python/dataframe)
39,396,678
<p>I'm sure this is a simple thing to do but I am new to Python and cannot work it out!</p> <p>I have a data frame with one column containing coordinates and I am wanting to remove the brackets and add the Lat/Lon values into separate columns.</p> <p>Current dataframe:</p> <pre><code>gridReference (56.37769816725615...
-1
2016-09-08T17:08:18Z
39,406,674
<pre><code>df['gridReference'].str.strip('()') \ .str.split(', ', expand=True) \ .rename(columns={0:'Latitude', 1:'Longitude'}) Latitude Longitude 0 56.37769816725615 -4.325049868061924 1 56.3776981672561...
1
2016-09-09T08:01:04Z
[ "python", "pandas", "dataframe" ]
TypeError: list indices must be integers, not str. Know the issue, not the answer
39,396,683
<p>Unique situation, I know the problem, just dont know a solution. </p> <pre><code>import string timefile = open('lasttimemultiple.txt','r+')#opens the file that contains the last time run lasttime = timefile.read()#reads the last time file items= int(2) splitlines = string.split(lasttime,'\n') print splitli...
0
2016-09-08T17:08:44Z
39,396,800
<p>You should show the actual traceback. If you had, you would have seen that the error is in this line:</p> <pre><code>if splitlines[items][0:2] == PullType: </code></pre> <p>That's because <code>items</code> here has been redefined by the for loop in the line before. In a for loop in Python, the variable is not a c...
0
2016-09-08T17:16:37Z
[ "python" ]
Running tensorflow as daemon and piping all output to log file
39,396,694
<p>To run tensorflow model as daemon I use : </p> <pre><code>nohup python translate.py --data_dir data &amp; </code></pre> <p>This logs error messages to nohup.out but it does not capture Tensorflow stdout . This thread offers describes related : <a href="https://groups.google.com/a/tensorflow.org/forum/#!topic/discu...
0
2016-09-08T17:09:42Z
39,398,882
<p>Why not try </p> <pre><code>nohup python translate.py --data_dir data &amp;&gt; outputfile.txt </code></pre> <p>You can then suspend the file your self with kill -19 %1 to suspend the first job or whatever number its present as. Then kill -CONT %1 to restart it. </p> <p>Other options:</p> <ul> <li>"disown" comma...
0
2016-09-08T19:34:46Z
[ "python", "linux", "tensorflow" ]
Class property inheritance when property is another class' property in python
39,396,798
<p>I have a class:</p> <pre><code>class a(): def __init__(self): self.x = ["a", "b"] </code></pre> <p>and another class:</p> <pre><code>class b(): def __init__(self, r): self.y = r def chg(self, a): self.y = a </code></pre> <p>I do:</p> <pre><code>&gt;&gt;&gt; m = a() &gt;&gt;&g...
-1
2016-09-08T17:16:33Z
39,396,863
<p>Inheritance does not work this way in Python. However, I think your problem is mutability rather than inheritance itself. (You did not apply inheritance, I said these because you used it as a tag and in the title.)</p> <p>Try it like this.</p> <pre><code>class a(): def __init__(self): self.x = [5] cla...
2
2016-09-08T17:21:07Z
[ "python", "class", "inheritance", "properties" ]
Class property inheritance when property is another class' property in python
39,396,798
<p>I have a class:</p> <pre><code>class a(): def __init__(self): self.x = ["a", "b"] </code></pre> <p>and another class:</p> <pre><code>class b(): def __init__(self, r): self.y = r def chg(self, a): self.y = a </code></pre> <p>I do:</p> <pre><code>&gt;&gt;&gt; m = a() &gt;&gt;&g...
-1
2016-09-08T17:16:33Z
39,396,948
<p>Oke so you need to do a little reading up on how memory works in python. What you do here:</p> <pre><code>&gt;&gt;&gt; n = b(m.x) &gt;&gt;&gt; n.y 5 </code></pre> <p>Is asking for the value m.x en sending it to the constructor of n. The value of m.x is 5 at that moment so 5 is passed to the constructor which then ...
1
2016-09-08T17:26:45Z
[ "python", "class", "inheritance", "properties" ]
no module named AppConfig
39,396,929
<p>I'm trying to run a server on my computer in Python/Django. In my installed_apps, I had a program called csvimport. It didn't work, so I had to install django-csvimport and I had to change it to csvimport.app.AppConfig in my installed-apps. However, I still get an importerror message saying "no module named AppConfi...
1
2016-09-08T17:25:42Z
39,396,993
<p><code>AppConfig</code> is Django's base class for the configuration class of custom apps, not necessarily the name of the config class of the app. But you're almost there:</p> <p><a href="https://github.com/edcrewe/django-csvimport/blob/master/csvimport/app.py#L5" rel="nofollow"><code>csvimport.app.CSVImportConf</c...
0
2016-09-08T17:30:23Z
[ "python", "django", "python-2.7" ]
SQLAlchemy - AttributeError: _reverse_property
39,396,934
<p>I'm having some trouble working and learning SQLALCHEMY and I think the issue is to do with my back_populates in relationships, but I've not been able to suss it out. Can you please point me in the right direction? </p> <p>The tables are created successfully and everything seems to be in order until I try and creat...
0
2016-09-08T17:25:53Z
39,397,346
<p>Relationship back_populates reference other relationships, not columns.</p> <p>Revised code:</p> <pre><code>from sqlalchemy import Column, ForeignKey, Integer, String, Boolean, DateTime from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, sessionmaker from sqlalchemy imp...
0
2016-09-08T17:54:51Z
[ "python", "python-3.x", "sqlalchemy" ]
compute mean of a column with python
39,396,973
<p>I have a dataframe df : </p> <pre><code>TIMESTAMP equipement1 equipement2 2016-05-10 13:20:00 0.000000 0.000000 2016-05-10 14:40:00 0.400000 0.500000 2016-05-10 15:20:00 0.500000 0.500000 </code></pre> <p>I would like to compute for each equipmeentx the ratio when timestamp in [TS_min, TS_max] For example functio...
0
2016-09-08T17:29:02Z
39,397,189
<p>Assuming TIMESTAMP is a datetime type, here is one way:</p> <pre><code>df = df.set_index('TIMESTAMP') r = df.ix['2016-05-10 14:40:00':'2016-05-10 15:20:00'] r/r.sum() equipement1 equipement2 TIMESTAMP 2016-05-10 14:40:00 0.444444 0.5 2016-05-10 15:20:00 0.555556 0.5 ...
1
2016-09-08T17:43:53Z
[ "python", "pandas" ]
To how list group by values and values in that category
39,396,984
<p>I want my template to display my group by category as a header, and then all the values for that group by category under it. For example, my table looks like this:</p> <pre><code>['John','Physics'] ['Jim','Physics'] ['Sam','Biology'] ['Sarah','Biology'] </code></pre> <p>And I want the template to output this:</p> ...
0
2016-09-08T17:29:51Z
39,397,062
<p>The template (department.html) is the place where you're going to list all the student. You must have some similar to this:</p> <pre><code>{% if students %} {% for student in students %} &lt;p&gt;{{ student.NAME_FIELD }}&lt;/p&gt; {{ student.DEPARTMENT_FIELD}} {% endfor %} {% else %} No ...
1
2016-09-08T17:34:57Z
[ "python", "django", "django-templates", "django-views", "django-1.10" ]
How does Python Pandas process a list of tables?
39,397,024
<p>I have this simple clean_data function, which will round the numbers in the input data frame. The code works, but I am very puzzled why it works. Could anybody help me understand?</p> <p>The part where I got confused is this. table_list is a new list of data frame, so after running the code, each item inside table_...
1
2016-09-08T17:32:17Z
39,397,480
<p>Simplest way is to break down this code completely:</p> <pre><code># List of 3 dataframes table_list = [tablea, tableb, tablec] # function that cleans 1 dataframe # This will get applied to each dataframe in table_list # when the python function map is used AFTER this function def clean_data(df): # for loop. ...
0
2016-09-08T18:03:58Z
[ "python", "pandas" ]
How does Python Pandas process a list of tables?
39,397,024
<p>I have this simple clean_data function, which will round the numbers in the input data frame. The code works, but I am very puzzled why it works. Could anybody help me understand?</p> <p>The part where I got confused is this. table_list is a new list of data frame, so after running the code, each item inside table_...
1
2016-09-08T17:32:17Z
39,400,652
<p>In Python, a list of dataframes, or any complicated objects, is simply a list of references that will point to the underlying data frames. For example, the first element of table_list is a reference to tablea. Therefore, clean_data will go directly to the data frame, i.e., tablea, following the reference given by ta...
0
2016-09-08T21:43:04Z
[ "python", "pandas" ]
Script works differently when ran from the terminal and ran from Python
39,397,034
<p>I have a short bash script <code>foo.sh</code></p> <pre><code>#!/bin/bash cat /dev/urandom | tr -dc 'a-z1-9' | fold -w 4 | head -n 1 </code></pre> <p>When I run it directly from the shell, it runs fine, exiting when it is done</p> <pre><code>$ ./foo.sh m1un $ </code></pre> <p>but when I run it from Python</p> ...
8
2016-09-08T17:32:50Z
39,398,969
<p>Adding the <code>trap -p</code> command to the bash script, stopping the hung python process and running <code>ps</code> shows what's going on:</p> <pre><code>$ cat foo.sh #!/bin/bash trap -p cat /dev/urandom | tr -dc 'a-z1-9' | fold -w 4 | head -n 1 $ python -c "import subprocess; subprocess.call(['./foo.sh'])" ...
8
2016-09-08T19:40:06Z
[ "python", "bash", "subprocess", "pipeline" ]
Script works differently when ran from the terminal and ran from Python
39,397,034
<p>I have a short bash script <code>foo.sh</code></p> <pre><code>#!/bin/bash cat /dev/urandom | tr -dc 'a-z1-9' | fold -w 4 | head -n 1 </code></pre> <p>When I run it directly from the shell, it runs fine, exiting when it is done</p> <pre><code>$ ./foo.sh m1un $ </code></pre> <p>but when I run it from Python</p> ...
8
2016-09-08T17:32:50Z
39,438,276
<p>The problem with Python 2 handling <code>SIGPIPE</code> in a non-standard way (i.e., being ignored) is already coined in Leon's answer, and the fix is given in the link: set <code>SIGPIPE</code> to default (<code>SIG_DFL</code>) with, e.g.,</p> <pre><code>import signal signal.signal(signal.SIGPIPE,signal.SIG_DFL) <...
1
2016-09-11T16:32:25Z
[ "python", "bash", "subprocess", "pipeline" ]
Set test case files for travis
39,397,160
<p>I have this <a href="https://github.com/b5y/log2html" rel="nofollow">project</a> on GitHub which has test case files. I run tests locally via pytest and all passed. But travis does not pass these tests and outputs errors:</p> <p><code>OSError: [Errno 2] No such file or directory: '/home/travis/build/b5y/log2html/te...
0
2016-09-08T17:41:11Z
39,397,468
<p>Somehow your tests are being run from the log directory inside your build directory. Make sure that travis-ci is in the same directory when it runs tests as you are when you run tests. It may be helpful to include a <code>pwd</code> or <code>ls</code> in the <code>script:</code> section of your <code>.travis.yml</co...
0
2016-09-08T18:03:13Z
[ "python", "travis-ci", "py.test" ]
How to get selected attributes of an object in to a python list?
39,397,332
<p>How do I create a list with the selected attributes of an object in python ? Using list comprehensions.</p> <p>E.g: </p> <p>My object A has</p> <pre><code>A.name A.age A.height </code></pre> <p>and many more attributes</p> <p>How do I create a list <code>[name,age]</code></p> <p>I can do it manually but it loo...
0
2016-09-08T17:53:47Z
39,397,350
<p>What you're looking for is <a href="https://docs.python.org/2/library/operator.html#operator.attrgetter" rel="nofollow"><code>operator.attrgetter</code></a></p> <pre><code>attrs = ['name', 'age'] l = list(operator.attrgetter(*attrs)(A)) </code></pre>
1
2016-09-08T17:55:16Z
[ "python", "list", "list-comprehension", "python-2.x" ]
How to get selected attributes of an object in to a python list?
39,397,332
<p>How do I create a list with the selected attributes of an object in python ? Using list comprehensions.</p> <p>E.g: </p> <p>My object A has</p> <pre><code>A.name A.age A.height </code></pre> <p>and many more attributes</p> <p>How do I create a list <code>[name,age]</code></p> <p>I can do it manually but it loo...
0
2016-09-08T17:53:47Z
39,397,351
<p>Why not just <code>[A.name, A.age]</code>? <code>list</code> literals are simple. <a href="https://docs.python.org/3/library/operator.html#operator.attrgetter">You could use <code>operator.attrgetter</code> if you need to do it a lot</a>, though it returns <code>tuple</code>s when fetching multiple attributes, not <...
5
2016-09-08T17:55:22Z
[ "python", "list", "list-comprehension", "python-2.x" ]
How to get selected attributes of an object in to a python list?
39,397,332
<p>How do I create a list with the selected attributes of an object in python ? Using list comprehensions.</p> <p>E.g: </p> <p>My object A has</p> <pre><code>A.name A.age A.height </code></pre> <p>and many more attributes</p> <p>How do I create a list <code>[name,age]</code></p> <p>I can do it manually but it loo...
0
2016-09-08T17:53:47Z
39,397,461
<p>You can collect them going through all <code>A</code> class attributes and checking if they aren't method or built-in.</p> <pre><code>import inspect def collect_props(): for name in dir(A): if not inspect.ismethod(getattr(A, name)) and\ not name.startswith('__'): yield name prin...
0
2016-09-08T18:02:46Z
[ "python", "list", "list-comprehension", "python-2.x" ]
Creating new columns from unique values across rows in pandas
39,397,389
<p>I'm trying to use unique values in a pandas column to generate a new set of column. Here's an example <code>DataFrame</code>:</p> <pre><code> meas1 meas2 side newindex 0 1 3 L 0 1 2 4 R 0 2 6 8 L 1 3 7 9 R 1 </code></p...
0
2016-09-08T17:57:47Z
39,397,657
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow"><code>DataFrame.pivot</code></a>:</p> <pre><code># Perform the pivot. df = df.pivot(index='newindex', columns='side').rename_axis(None) # Format the columns. df.columns = df.columns.map('_'.join) </code><...
3
2016-09-08T18:15:26Z
[ "python", "pandas", "dataframe" ]
Creating new columns from unique values across rows in pandas
39,397,389
<p>I'm trying to use unique values in a pandas column to generate a new set of column. Here's an example <code>DataFrame</code>:</p> <pre><code> meas1 meas2 side newindex 0 1 3 L 0 1 2 4 R 0 2 6 8 L 1 3 7 9 R 1 </code></p...
0
2016-09-08T17:57:47Z
39,397,857
<p>Another solution using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.prod.html" rel="nofollow"><code>groupby.prod</code></a>:</p> <pre><code>df = df.groupby(['side', 'newindex']).prod().unstack(level=0) df.columns = ['_'.join(c[0::]) for c in df.columns] meas1...
1
2016-09-08T18:27:52Z
[ "python", "pandas", "dataframe" ]
split in python return an excess blank character
39,397,392
<p>I have a file with some data that I read,split with <code>space</code>,<code>,</code> ,<code>\n</code> and take it in a matrix. But my code return an excess blank character into my matrix. Can anybody help me find this bug? Thanks. code:</p> <pre><code>import re lines = [re.split('[,\n ]',line) for line in open('li...
0
2016-09-08T17:57:52Z
39,397,427
<p>lines read from a text file generally have a newline on the end (unless they're the last line in which case they might not). It's pretty common to see that newline stripped off (e.g. using <a href="https://docs.python.org/3/library/stdtypes.html#str.rstrip" rel="nofollow"><code>str.rstrip</code></a>):</p> <pre><co...
2
2016-09-08T18:00:33Z
[ "python", "regex", "split" ]
How to get the needed varibales due to the condition?
39,397,476
<p>I have lists with values like this for example:</p> <pre><code>values = [value_one, value_two, list_A[], list_B[], list_C[]] </code></pre> <p>... which are in a map (all these lists have the same structure as the example above, but with different values!):</p> <pre><code>{ key_one: valuesA, key_two: valuesB...
0
2016-09-08T18:03:44Z
39,397,900
<p>If you can determine under different conditions which lists to be extracted before do_calculate, I suggest you use the positions of lists in the <code>data</code> tuple to extract them.</p> <pre><code>def positions_of_list(): # conditions return pos1, pos2 def calculate_process(map): for key, data in m...
0
2016-09-08T18:30:05Z
[ "python", "python-2.7" ]
Can I get a list (name - email) of fans who likes a public page using the facebook SDK and python?
39,397,544
<p>I was trying to get a list of fans who likes a public page.</p> <p>If that is not possible a list of people who likes comments made in that public page.</p> <p>This link make me thing that in fact it is possible:</p> <p><a href="https://www.facebook.com/search/102381354573/likers?ref=about" rel="nofollow">https:/...
0
2016-09-08T18:08:06Z
39,401,286
<p>No, there is no API to get a list of fans. You can only get a list of users who commented or liked something on your Page, but there is no way to get their email. It would be weird anyway, what would you want to do with the email? Without explicit approval of the user, you would not even be allowed to store the emai...
2
2016-09-08T22:49:11Z
[ "python", "json", "facebook", "facebook-graph-api", "sdk" ]
Django Admin add edit/create buttons to Parent
39,397,545
<p>I'm trying to add an add and edit link to my Django admin for the ForeignKey field category. I already have this on the schedule field, however this is handled by djcelery and i cannot figure out how they do this:</p> <p><a href="http://i.stack.imgur.com/1DtMB.png" rel="nofollow"><img src="http://i.stack.imgur.com/...
0
2016-09-08T18:08:07Z
39,397,731
<p>Facepalm! I got the desiredresult once i added a admin for categories:</p> <pre><code>admin.site.register(Category) </code></pre> <p><a href="http://i.stack.imgur.com/J7dHK.png" rel="nofollow"><img src="http://i.stack.imgur.com/J7dHK.png" alt="enter image description here"></a></p> <p>However, if any one know how...
0
2016-09-08T18:20:15Z
[ "python", "django", "django-admin", "celery", "django-celery" ]
Django Admin add edit/create buttons to Parent
39,397,545
<p>I'm trying to add an add and edit link to my Django admin for the ForeignKey field category. I already have this on the schedule field, however this is handled by djcelery and i cannot figure out how they do this:</p> <p><a href="http://i.stack.imgur.com/1DtMB.png" rel="nofollow"><img src="http://i.stack.imgur.com/...
0
2016-09-08T18:08:07Z
39,407,684
<p>I cannot comment because of low reputation. So adding as an answer. Returning an empty dict from get_model_perms excludes the model admin from index page, whilst still allowing you to edit instances directly. <a href="http://stackoverflow.com/questions/2431727/django-admin-hide-a-model/4871511#4871511">Here is the m...
1
2016-09-09T08:59:24Z
[ "python", "django", "django-admin", "celery", "django-celery" ]
ordered word perminuations in python
39,397,626
<p>So my question is simple, and half of it is already working. I need help with generating ordered word-permutations. </p> <p>My code:</p> <pre><code>from os.path import isfile from string import printable def loadRuleSet(fileLocation): rules = {} assert isfile(fileLocation) for x in open(fileLocation)....
-1
2016-09-08T18:13:47Z
39,397,648
<p>In your case you can use <code>permutations</code> function which could return all possible orderings, no repeated elements.</p> <pre><code>from itertools import permutations from operator import itemgetter perm_one = sorted(set([''.join(x) for x in permutations('@aa')])) perm_two = sorted(set([''.join(x) for x in...
2
2016-09-08T18:14:46Z
[ "python", "data-generation" ]
identify global symbols in lambda expressions
39,397,679
<p>I need to get the list of names of all symbols which I must have available in order to evaluate or execute a piece of code. I tried to use <code>symtable</code> module but it seems that it does not handle properly lambdas and inner functions (<code>def</code>s inside other code). Consider this:</p> <pre><code>impor...
0
2016-09-08T18:17:16Z
39,398,038
<p>Without much ado... I need to look into child symbol tables. Recursion is the tool of choice:</p> <pre><code>import symtable def find_global_symbols(table): symbols = set() for t in table.get_children(): symbols |= find_global_symbols(t) symbols |= set(s.get_name() for s in table.get_symbols() ...
0
2016-09-08T18:38:43Z
[ "python", "lambda" ]
how to call def from another .py in different folder
39,397,720
<p>I have following structure: utils_dir has generator.py file which has 3 defs.</p> <p>I have test.py in inline_dir. And I am trying to use defs from generator.py in test.py. </p> <p>inline_dir and utils_dir are in different folders. How can I achieve it to use defs?</p> <p>Tried with creating <code>_init_.py</code...
2
2016-09-08T18:19:34Z
39,398,291
<p>It sounds like you're trying to execute a .py file in a subdirectory.</p> <p>Assuming the following directory structure:</p> <pre><code>. ├── inline │   ├── __init__.py │   └── main.py └── utils ├── __init__.py └── generator.py </code></pre> <p>And your <code>ma...
1
2016-09-08T18:55:08Z
[ "python" ]
how to call def from another .py in different folder
39,397,720
<p>I have following structure: utils_dir has generator.py file which has 3 defs.</p> <p>I have test.py in inline_dir. And I am trying to use defs from generator.py in test.py. </p> <p>inline_dir and utils_dir are in different folders. How can I achieve it to use defs?</p> <p>Tried with creating <code>_init_.py</code...
2
2016-09-08T18:19:34Z
39,398,501
<p>This is a kind of a python path problem. When you import, python will search current directory and default system path directory. Since utils_dir is not your current work directory (when import, you work in inline_dir), nor in default python search system path, that is why the import not work.</p> <p>A simple way t...
1
2016-09-08T19:09:31Z
[ "python" ]
Is "python2" / "python3" safe on a script's shebang?
39,397,745
<p>Sometimes I see <code>#!/usr/bin/python2</code> and <code>#!/usr/bin/python3</code> as opposed to simply <code>#!/usr/bin/python</code>. I get the appeal of this approach, you get to explicitly say if you need Python 2 or 3 without doing some weird version checking.</p> <p>Are these <code>python2</code> and <code>p...
1
2016-09-08T18:21:02Z
39,397,764
<p>As a single point of reference -- I don't have a <code>python2</code> executable on my system:</p> <pre><code>$ python2 -bash: python2: command not found </code></pre> <p>So I would definitely not consider this one to be portable. Obviously I could still run your script by selecting an executable explicitly:</p> ...
1
2016-09-08T18:22:06Z
[ "python", "scripting", "portability", "shebang" ]
Python list manipulation based on indexing
39,397,853
<p>I have two lists:</p> <p>The first list consists of all the titles of various publications where as the second list consists of all the author names.</p> <pre><code>list B = ['Moe Terry M 2005 ', 'March James G and Johan P Olsen 2006 ', 'Kitschelt Herbert 2000 ', 'Bates Robert H 1981 ' , .......] list A = ['"Link...
0
2016-09-08T18:27:34Z
39,398,006
<p>Is this is what you are looking for?</p> <pre><code>list B = ['Moe Terry M 2005 ', 'March James G and Johan P Olsen 2006 ', 'Kitschelt Herbert 2000 ', 'Bates Robert H 1981 ' , .......] list A = ['"Linkages between Citizens and Politicians in Democratic Polities,"', '"Winners Take All: The Politics of Partial Refor...
1
2016-09-08T18:36:49Z
[ "python", "list" ]
cannot downloads file using python socket programming
39,397,878
<p>i want to download a file from this url (<a href="http://justlearn.16mb.com/a.jpg" rel="nofollow">http://justlearn.16mb.com/a.jpg</a>) using python sockets only and i dont know how to do it as i am a novice in python.</p> <p>Actually my main goal is to download files in half part using wifi connection and other hal...
1
2016-09-08T18:28:49Z
39,399,007
<p>You might want to try something like this instead. I am unable to test it due to a proxy, but the example should help you in the right direction. Using sockets directly would make this unnecessarily difficult.</p> <pre><code>#! /usr/bin/env python3 import http.client def main(): connection = http.client.HTTPC...
0
2016-09-08T19:42:41Z
[ "python", "sockets", "wifi", "ethernet", "download-manager" ]
Replace multi line code using python
39,397,883
<p>I am trying to replace some lines in HTML file using python.</p> <pre><code>#! /usr/local/bin/python import os,sys,string,filecmp,shutil,stat,pwd,datetime,time,copy,glob,re,getpass,commands sys.path.insert(0,os.path.join(os.environ['ADM_TOOLS'],'llib')) import tooldets,CSrcPrj,comnfuncs,COraConnect patchHtmlName =...
1
2016-09-08T18:29:02Z
39,399,451
<p>Try this one</p> <pre><code>import re ... ... newJSCode = re.sub(r'.*%s'%contents1, contents2, contents, re.DOTALL) </code></pre> <p>This will replace contents1 with contents2 in contents. I'm not sure whether I undestood which one is to be replaced, but anyway if you want the opposite just change contents1 to co...
0
2016-09-08T20:14:50Z
[ "python" ]
Running a Regex loop in a Pandas Dataframe
39,397,897
<p>I currently have a date column that has some issues. I have attempted to fix the problem but cannot come to a conclusion.</p> <p>Here is the data:</p> <pre><code># Import data df_views = pd.read_excel('PageViews.xlsx') # Check data types df_views.dtypes Out[57]: Date object Customer ID int64 dtype: ...
2
2016-09-08T18:29:58Z
39,398,702
<p>As <a href="http://stackoverflow.com/questions/39397897/running-a-regex-loop-in-a-pandas-dataframe/39398702#comment66122084_39397897">@BrenBam has already written in the comment</a> - try to avoid using loops. Pandas gives us tons of vectorized (read fast and efficient) methods:</p> <pre><code>In [67]: df Out[67]: ...
1
2016-09-08T19:22:07Z
[ "python", "regex", "loops", "pandas", "numpy" ]
Using third party Email system for Django Password Reset
39,398,013
<p>I have a Django App hosted on Google Compute Engine(which doesn't allow port 25/465/587 to send Emails). So, I integrated a third party Email system in the Django App. Third party Email system works find on Google Compute Engine too. </p> <p>But when I use Django Reset Password, that email is still getting sent ove...
1
2016-09-08T18:37:16Z
39,398,101
<p>There is something like <a href="https://docs.djangoproject.com/el/1.10/topics/email/#email-backends" rel="nofollow">Email backends</a></p> <pre><code># settings.py EMAIL_BACKEND = 'project.backends.mail.CustomEmailBackend' # project/backends/mail.py from django.core.mail.backends.base import BaseEmailBackend clas...
1
2016-09-08T18:43:09Z
[ "python", "django", "email", "passwords", "google-compute-engine" ]
Referring to outer scope from python class
39,398,019
<p>I have a (simplified) module, something like this:</p> <pre><code>import tkinter as tk __outerVar = {&lt;dict stuff&gt;} class Editor(tk.Frame): ... def _insideFunction(self): for p in __outerVar.keys(): &lt;do stuff&gt; </code></pre> <p>I'm getting a <code>NameError: name '_Editor__outer...
1
2016-09-08T18:37:46Z
39,398,068
<p>You're seeing name mangling in effect. From the <a href="https://docs.python.org/2/tutorial/classes.html#tut-private" rel="nofollow">documentation</a>:</p> <blockquote> <p>Any identifier of the form <code>__spam</code> (at least two leading underscores, at most one trailing underscore) is textually replaced with...
3
2016-09-08T18:41:00Z
[ "python", "class", "python-3.x", "module", "scope" ]
Referring to outer scope from python class
39,398,019
<p>I have a (simplified) module, something like this:</p> <pre><code>import tkinter as tk __outerVar = {&lt;dict stuff&gt;} class Editor(tk.Frame): ... def _insideFunction(self): for p in __outerVar.keys(): &lt;do stuff&gt; </code></pre> <p>I'm getting a <code>NameError: name '_Editor__outer...
1
2016-09-08T18:37:46Z
39,398,072
<p>Python replaces any names preceded by a double underscore <code>__</code> in order to simulate 'private attributes'. In essence <code>__name</code> becomes <code>_classname__name</code>. This, called name mangling, happens only within classes as documented <a href="https://docs.python.org/3/tutorial/classes.html#pri...
3
2016-09-08T18:41:12Z
[ "python", "class", "python-3.x", "module", "scope" ]
Django BooleanField as a dropdown
39,398,031
<p>Is there a way to make a Django BooleanField a drop down in a form?</p> <p>Right now it renders as a radio button. Is it possible to have a dropdown with options: 'Yes', 'No' ?</p> <p>Currently my form definition for this field is:</p> <pre><code>attending = forms.BooleanField(required=True) </code></pre>
1
2016-09-08T18:38:18Z
39,399,015
<p>I believe a solution that can solve your problem is something along the lines of this:</p> <pre><code>TRUE_FALSE_CHOICE = ( (True, "Yes"), (False, "No") } boolfield = forms.ChoiceField(choices = TRUE_FALSE_CHOICES, label="Some Label", initial='', widget=forms.Select(), requir...
3
2016-09-08T19:43:11Z
[ "python", "django" ]
what is correct way of type hint a function that return only a specific set of values?
39,398,138
<p>I have a function that can only return <code>a</code>, <code>b</code> or <code>c</code> all of them are of type <code>T</code> but I want to make part of its signature this fact because of the special meaning they carry in the context of the function, how I do that?</p> <p>currently I use this</p> <pre><code>def f...
1
2016-09-08T18:45:31Z
39,398,193
<p>If all are of the same exact type just <em>add that as the return type</em>:</p> <pre><code>def func(...) -&gt; T: # or int or whatever else </code></pre> <blockquote> <p>I want to express in the signature that the function only return those specific values</p> </blockquote> <p>Type hints don't specify a name o...
0
2016-09-08T18:48:56Z
[ "python", "python-3.x", "type-hinting" ]
what is correct way of type hint a function that return only a specific set of values?
39,398,138
<p>I have a function that can only return <code>a</code>, <code>b</code> or <code>c</code> all of them are of type <code>T</code> but I want to make part of its signature this fact because of the special meaning they carry in the context of the function, how I do that?</p> <p>currently I use this</p> <pre><code>def f...
1
2016-09-08T18:45:31Z
39,398,431
<p>You can't specify that your function returns only a subset of a type's values using type hinting alone. As the name implies, type hinting is all about <em>types</em> not values.</p> <p>However, you can create a new <code>enum.Enum</code> subtype that only has the values you're going to return and use it in the func...
5
2016-09-08T19:05:17Z
[ "python", "python-3.x", "type-hinting" ]
Expert system (used for database access) vs. ORM
39,398,181
<p>I have recently discovered <a href="http://pyke.sourceforge.net" rel="nofollow">PyKE</a>, and noticed that one of the given examples of a potential use (actually, the use for which it was originally built) was to compile SELECT statements to query a database, and map the result to a dictionary. The author emphasizes...
0
2016-09-08T18:47:40Z
39,511,064
<h3>To your first question</h3> <p>An ORM is a layer between your logic and data that maps one to the other. Relational DBs often don't store data the way your objects use that data, so ORMs aim to abstract away the mental gymnastics needed to write the SQL to transform the data from one representation to another. (im...
2
2016-09-15T12:29:22Z
[ "python", "orm", "language-agnostic", "expert-system", "pyke" ]
What is the equivalent function in Biopython for BioPerl's Bio::DB::Fasta?
39,398,183
<p>I'm translating a Perl code to a Python code using BioPython.</p> <p>I got something like:</p> <pre><code>my $db = Bio::DB::Fasta-&gt;new($path,$options) </code></pre> <p>and I'm looking for a similar function in Biopython. Is there anything like this?</p>
0
2016-09-08T18:47:53Z
39,400,180
<p>You can find the IO for FASTA files at <a href="http://biopython.org/DIST/docs/api/Bio.SeqIO-module.html" rel="nofollow">http://biopython.org/DIST/docs/api/Bio.SeqIO-module.html</a></p> <p>About the indexing, I think Biopython doesn't handle '.fai' files like Bio::DB:Fasta. You can have a dictionary (like a perl ha...
1
2016-09-08T21:04:19Z
[ "python", "perl", "biopython", "bioperl" ]
Create unique MultiIndex from Non-unique Index Python Pandas
39,398,251
<p>I have a pandas DataFrame with a non-unique index:</p> <pre><code>index = [1,1,1,1,2,2,2,3] df = pd.DataFrame(data = {'col1': [1,3,7,6,2,4,3,4]}, index=index) df Out[12]: col1 1 1 1 3 1 7 1 6 2 2 2 4 2 3 3 4 </code></pre> <p>I'd like to turn this into unique MultiIndex and pre...
2
2016-09-08T18:53:06Z
39,398,424
<p>You can do a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow"><code>groupby.cumcount</code></a> on the index, and then append it as a new level to the index using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.se...
2
2016-09-08T19:04:25Z
[ "python", "pandas" ]
How to remove/hide total sum in tree view in odoo?
39,398,260
<p>I have odoo tree view in which there are some warehouse stock values displaying in columns. And its calculating total sum of these warehouse values in the bottom. I want to remove total sum in the bottom in tree view, how i can do that? you can see my tree view code i applied sum="false", total="false" but its not w...
1
2016-09-08T18:53:23Z
39,398,430
<p>If you just want to go to Settings/User Technical -> Interface -> Views you can edit the view like this. Just remove the sum tag entirely from the rows you wish not to be totalled.</p> <pre><code>&lt;tree string="Warehouse Product" editable="bottom" create="false" edit="false" delete="false"&gt; &lt;field name="...
3
2016-09-08T19:05:07Z
[ "python", "xml", "openerp", "views", "odoo-8" ]
How to remove/hide total sum in tree view in odoo?
39,398,260
<p>I have odoo tree view in which there are some warehouse stock values displaying in columns. And its calculating total sum of these warehouse values in the bottom. I want to remove total sum in the bottom in tree view, how i can do that? you can see my tree view code i applied sum="false", total="false" but its not w...
1
2016-09-08T18:53:23Z
39,398,447
<p>Just get rid of the sum attribute(s)</p> <pre><code>&lt;tree string="Warehouse Product" editable="bottom" create="false" edit="false" delete="false"&gt; &lt;field name="warehouse_id"/&gt; &lt;field name="qty" /&gt; &lt;field name="incoming_qty" /&gt; &lt;field name="outgoing_qty" /&gt; ...
1
2016-09-08T19:05:47Z
[ "python", "xml", "openerp", "views", "odoo-8" ]
How to remove/hide total sum in tree view in odoo?
39,398,260
<p>I have odoo tree view in which there are some warehouse stock values displaying in columns. And its calculating total sum of these warehouse values in the bottom. I want to remove total sum in the bottom in tree view, how i can do that? you can see my tree view code i applied sum="false", total="false" but its not w...
1
2016-09-08T18:53:23Z
39,398,489
<p>Its done, i just remove sum="" from every field and it remove bottom line of total sum, here is my updated code</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;tr...
0
2016-09-08T19:08:50Z
[ "python", "xml", "openerp", "views", "odoo-8" ]
How to resolve memory issue of pandas while reading big csv files
39,398,283
<p>I have a 100GB csv file with millions of rows. I need to read, say, 10,000 rows at a time in pandas dataframe and write that to the SQL server in chunks. </p> <p>I used chunksize as well as iteartor as suggested on <a href="http://pandas-docs.github.io/pandas-docs-travis/io.html#iterating-through-files-chunk-by-chu...
2
2016-09-08T18:54:36Z
39,399,220
<p>Demo:</p> <pre><code>for chunk in pd.read_csv(filename, chunksize=10**5): chunk.to_sql('table_name', conn, if_exists='append') </code></pre> <p>where <code>conn</code> is a SQLAlchemy engine (created by <code>sqlalchemy.create_engine(...)</code>)</p>
1
2016-09-08T19:57:44Z
[ "python", "csv", "pandas", "dataframe", "iterator" ]
How to write python code that finishes a read from stdin even though the read buffer isn't full
39,398,297
<p>Python question:</p> <pre><code>$ python -V Python 2.4.3 </code></pre> <p>Searched for the answer to this and maybe didn't know what search to use.</p> <p>Basically the question is simple. I have perl code like this and it works perfect.</p> <pre><code>while ($count) { $count = sysread(STDIN,$data,2000); ...
1
2016-09-08T18:55:31Z
39,400,253
<p>Non-blocking mode can be enabled for stdin like shown below. I added some sleep there to prevent CPU hogging.</p> <pre><code>#!/usr/bin/env python import os import sys import time import fcntl # Set stdin to non-blocking mode flags = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL) fcntl.fcntl(sys.stdin.fileno(), f...
0
2016-09-08T21:10:12Z
[ "python", "stdin" ]
How to write python code that finishes a read from stdin even though the read buffer isn't full
39,398,297
<p>Python question:</p> <pre><code>$ python -V Python 2.4.3 </code></pre> <p>Searched for the answer to this and maybe didn't know what search to use.</p> <p>Basically the question is simple. I have perl code like this and it works perfect.</p> <pre><code>while ($count) { $count = sysread(STDIN,$data,2000); ...
1
2016-09-08T18:55:31Z
39,459,742
<p>I think I figured out the best way. Unless someone can figure out how to make read behave like C and sysread in perl. I make it non-blocking like above, but use a select to wait until data is available. Combining both, I get what I want. Wait until data is available and read the available data without blocking. Yea!...
1
2016-09-12T22:33:16Z
[ "python", "stdin" ]
How to write python code that finishes a read from stdin even though the read buffer isn't full
39,398,297
<p>Python question:</p> <pre><code>$ python -V Python 2.4.3 </code></pre> <p>Searched for the answer to this and maybe didn't know what search to use.</p> <p>Basically the question is simple. I have perl code like this and it works perfect.</p> <pre><code>while ($count) { $count = sysread(STDIN,$data,2000); ...
1
2016-09-08T18:55:31Z
39,461,317
<p>In the event you are able to use Python 3 instead:</p> <pre><code>while True: buf = sys.stdin.buffer.raw.read(10) if buf:: print("Read", len(buf)) </code></pre> <p>Then:</p> <pre><code>while (( 1 )) do echo Sending ab 1&gt;&amp;2 echo -n ab sleep 1 done | ./go.py </code></pre> <p>give...
0
2016-09-13T02:17:47Z
[ "python", "stdin" ]
How does asyncio.sleep work with negative values?
39,398,312
<p>I decided to implement sleep sort (<a href="https://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort" rel="nofollow">https://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort</a>) using Python's <code>asyncio</code> when I made a strange discovery: it works with negative values (and returns immediately with 0)!</...
4
2016-09-08T18:56:37Z
39,399,052
<p>If you take a look at the asyncio source, <code>sleep</code> <a href="https://github.com/python/cpython/blob/ce83a8c892ff17dc5eaba2420854d82589b269cd/Lib/asyncio/tasks.py#L505-L507" rel="nofollow">special cases 0</a> and returns immediately.</p> <pre><code>if delay == 0: yield return result </code></pre> <...
4
2016-09-08T19:45:52Z
[ "python", "sorting", "sleep", "python-asyncio" ]
How does asyncio.sleep work with negative values?
39,398,312
<p>I decided to implement sleep sort (<a href="https://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort" rel="nofollow">https://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort</a>) using Python's <code>asyncio</code> when I made a strange discovery: it works with negative values (and returns immediately with 0)!</...
4
2016-09-08T18:56:37Z
39,399,607
<p>Well, looking at the <a href="https://hg.python.org/cpython/file/3.5/Lib/asyncio/tasks.py#l503" rel="nofollow">source</a>:</p> <ul> <li><code>delay == 0</code> is special-cased to return immediately, it doesn't even try to sleep.</li> <li>Non-zero delay calls <code>events.get_event_loop()</code>. Since there are no...
2
2016-09-08T20:25:02Z
[ "python", "sorting", "sleep", "python-asyncio" ]
Using Pycharm virtualenv with preexisting files
39,398,318
<p>I was sent a bunch of Python files that have various custom dependencies inside nested folders. I used to run the main file from Terminal by first navigating to the main folder, then running <code>python main.py</code>. This worked until I needed to update some modules and ran into permissions problems.</p> <p>So I...
2
2016-09-08T18:56:47Z
39,409,962
<p>In PyCharm, do File -> Open and point at the directory. It will turn that directory into a "project" (meaning, it will create a .idea subdirectory). Depending on how you named your virtualenv, it will likely detect the virtualenv and assign it the project's interpreter.</p>
1
2016-09-09T10:54:19Z
[ "python", "pycharm", "virtualenv" ]
How Would I Go About Making My Python Scoring System Work?
39,398,378
<p>I've been learning through an online course and I was trying to come up with ideas for things I could create to "test" myself as it were so I came up with a rock paper scissors game. It was working well so I decided to try and add a way of keeping track of your score vs the computer. Didn't go so well.</p> <p>Here'...
1
2016-09-08T19:01:36Z
39,398,484
<p>At least one problem is this: your main has if...if...elif...else. The second if probably needs to be an elif. Tip: When you have a flow-of-control problem, put print statements inside each control branch, printing out the control variable and everything else that might possibly be relevant. This tells you which bra...
0
2016-09-08T19:08:33Z
[ "python" ]
How Would I Go About Making My Python Scoring System Work?
39,398,378
<p>I've been learning through an online course and I was trying to come up with ideas for things I could create to "test" myself as it were so I came up with a rock paper scissors game. It was working well so I decided to try and add a way of keeping track of your score vs the computer. Didn't go so well.</p> <p>Here'...
1
2016-09-08T19:01:36Z
39,398,597
<pre><code>from random import randint class newgame(): ai_score = 0 user_score = 0 def __init__(self): self.ai_score = 0 self.user_score = 0 def playgame(self): print('New Game') try: while(1): ai_guess = str(randint(1,3)) p...
2
2016-09-08T19:15:23Z
[ "python" ]
How Would I Go About Making My Python Scoring System Work?
39,398,378
<p>I've been learning through an online course and I was trying to come up with ideas for things I could create to "test" myself as it were so I came up with a rock paper scissors game. It was working well so I decided to try and add a way of keeping track of your score vs the computer. Didn't go so well.</p> <p>Here'...
1
2016-09-08T19:01:36Z
39,398,654
<p>It seems that the variable <code>option</code> is not '1', right ? Well, that's because the function <code>input</code> does not return a character string, but an <code>integer</code>. You can see this by adding a little trace in this program.</p> <pre><code>print (option, type (option)) </code></pre> <p>after a ...
1
2016-09-08T19:18:54Z
[ "python" ]
Find group of strings that are anagrams
39,398,444
<p>This question refers to <a href="http://www.lintcode.com/en/problem/anagrams/" rel="nofollow">this problem on lintcode</a>. I have a working solution, but it takes too long for the huge testcase. I am wondering how can it be improved? Maybe I can decrease the number of comparisons I make in the outer loop.</p> <pr...
4
2016-09-08T19:05:43Z
39,398,607
<p>Why not this? </p> <pre><code>str1 = "cafe" str2 = "face" def isanagram(s1,s2): return all(sorted(list(str1)) == sorted(list(str2))) if isanagram(str1, str2): print "Woo" </code></pre>
0
2016-09-08T19:15:46Z
[ "python", "string", "anagram" ]
Find group of strings that are anagrams
39,398,444
<p>This question refers to <a href="http://www.lintcode.com/en/problem/anagrams/" rel="nofollow">this problem on lintcode</a>. I have a working solution, but it takes too long for the huge testcase. I am wondering how can it be improved? Maybe I can decrease the number of comparisons I make in the outer loop.</p> <pr...
4
2016-09-08T19:05:43Z
39,398,637
<p>Skip strings you already placed in the set. Don't test them again.</p> <pre><code># @param strs: A list of strings # @return: A list of strings def anagrams(self, strs): # write your code here ret=set() for i in range(0,len(strs)): for j in range(i+1,len(strs)): # If both anagrams e...
3
2016-09-08T19:17:46Z
[ "python", "string", "anagram" ]
Find group of strings that are anagrams
39,398,444
<p>This question refers to <a href="http://www.lintcode.com/en/problem/anagrams/" rel="nofollow">this problem on lintcode</a>. I have a working solution, but it takes too long for the huge testcase. I am wondering how can it be improved? Maybe I can decrease the number of comparisons I make in the outer loop.</p> <pr...
4
2016-09-08T19:05:43Z
39,398,767
<p>As an addition to @Mike's great answer, here is a nice Pythonic way to do it:</p> <pre><code>import collections class Solution: # @param strs: A list of strings # @return: A list of strings def anagrams(self, strs): patterns = Solution.find_anagram_words(strs) return [word for word in ...
1
2016-09-08T19:27:36Z
[ "python", "string", "anagram" ]
Find group of strings that are anagrams
39,398,444
<p>This question refers to <a href="http://www.lintcode.com/en/problem/anagrams/" rel="nofollow">this problem on lintcode</a>. I have a working solution, but it takes too long for the huge testcase. I am wondering how can it be improved? Maybe I can decrease the number of comparisons I make in the outer loop.</p> <pr...
4
2016-09-08T19:05:43Z
39,398,876
<p>Instead of comparing all pairs of strings, you can just create a dictionary (or <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>collections.defaultdict</code></a>) mapping each of the letter-counts to the words having those counts. For getting the letter-coun...
2
2016-09-08T19:34:32Z
[ "python", "string", "anagram" ]
Find group of strings that are anagrams
39,398,444
<p>This question refers to <a href="http://www.lintcode.com/en/problem/anagrams/" rel="nofollow">this problem on lintcode</a>. I have a working solution, but it takes too long for the huge testcase. I am wondering how can it be improved? Maybe I can decrease the number of comparisons I make in the outer loop.</p> <pr...
4
2016-09-08T19:05:43Z
39,399,047
<p>Your solution is slow because you're not taking advantage of python's data structures. </p> <p>Here's a solution that collects results in a dict:</p> <pre><code>class Solution: def anagrams(self, strs): d = {} for word in strs: key = tuple(sorted(word)) try: ...
1
2016-09-08T19:45:28Z
[ "python", "string", "anagram" ]
Grouping of items based on criteria
39,398,539
<p>I have a list of items:</p> <pre><code>ShelvesToPack = [{'ShelfLength': 2278.0, 'ShelfWidth': 356.0, 'ShelfArea': 759152.0, 'ItemNames': 1}, {'ShelfLength': 1220.0, 'ShelfWidth': 610.0, 'ShelfArea': 372100.0, 'ItemNames': 2}, {'ShelfLength': 2310.0, 'ShelfWidth': 762.0, 'ShelfArea': 1760220.0, 'ItemNames': 3}, {'Sh...
0
2016-09-08T19:11:43Z
39,398,866
<p>Here is a simplified version of your code:</p> <pre><code>data = [{'ShelfLength': 2278.0, 'ShelfWidth': 356.0, 'ShelfArea': 759152.0, 'ItemNames': 1}, {'ShelfLength': 1220.0, 'ShelfWidth': 610.0, 'ShelfArea': 372100.0, 'ItemNames': 2}, {'ShelfLength': 2310.0, 'ShelfWidth': 762.0, 'ShelfArea': 1760220.0, '...
0
2016-09-08T19:33:51Z
[ "python", "python-3.x" ]
Grouping of items based on criteria
39,398,539
<p>I have a list of items:</p> <pre><code>ShelvesToPack = [{'ShelfLength': 2278.0, 'ShelfWidth': 356.0, 'ShelfArea': 759152.0, 'ItemNames': 1}, {'ShelfLength': 1220.0, 'ShelfWidth': 610.0, 'ShelfArea': 372100.0, 'ItemNames': 2}, {'ShelfLength': 2310.0, 'ShelfWidth': 762.0, 'ShelfArea': 1760220.0, 'ItemNames': 3}, {'Sh...
0
2016-09-08T19:11:43Z
39,401,609
<p>Here's something that appears to work correctly. Since the order of shelves in a combination doesn't matter, it simply does things using a brute-force approach that checks every possible combination of the shelves. Because there may be a very large number of them to process, it's important to write code which is fai...
0
2016-09-08T23:28:01Z
[ "python", "python-3.x" ]
Python: Get javascript file from href tag of html
39,398,592
<p>Consider a website similar to this one:</p> <p><a href="http://a810-bisweb.nyc.gov/bisweb/COsByLocationServlet?requestid=1&amp;allbin=3055311" rel="nofollow">http://a810-bisweb.nyc.gov/bisweb/COsByLocationServlet?requestid=1&amp;allbin=3055311</a></p> <p>As one can see, the website contains links to pdf files refe...
1
2016-09-08T19:14:59Z
39,399,333
<p>I downloaded few files and compared direct link with its name and all elements required in link you have in filename</p> <p>Filename:</p> <pre><code>form_cofo_pdf_view_B000114563.PDF </code></pre> <p>Direct link:</p> <pre><code>http://a810-bisweb.nyc.gov/bisweb/CofoDocumentContentServlet ?passjobnumber=null &amp...
0
2016-09-08T20:05:08Z
[ "javascript", "python", "html", "web", "web-scraping" ]
In pycharm can I run every file for django?
39,398,625
<p>I'm new to Django. My localhost site is running fine. Since I am using pycharm it is easy to run any file. I decided to run each file in my django project, and came across several errors, such as this one in my views.py:</p> <pre><code>django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB...
1
2016-09-08T19:17:06Z
39,399,060
<p>You cannot run each file present in your django project individual.</p> <p>No matter those are file with <code>.py</code> extension. They depend on the django framework to get the project running.</p> <p>The reason you might be seeing that error is because you might be using the attributes present in the <code>set...
0
2016-09-08T19:46:16Z
[ "python", "django", "pycharm" ]
In pycharm can I run every file for django?
39,398,625
<p>I'm new to Django. My localhost site is running fine. Since I am using pycharm it is easy to run any file. I decided to run each file in my django project, and came across several errors, such as this one in my views.py:</p> <pre><code>django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB...
1
2016-09-08T19:17:06Z
39,604,322
<p><strong>You can run</strong> any individual <strong>python file</strong> in a Django Project with Django, but keep in mind that the settings for Django must be supplied. This is not a good practise to run individual file with Django but for debugging purposes you may use it (<em>for example. to test a parser that yo...
0
2016-09-20T21:54:42Z
[ "python", "django", "pycharm" ]
Pandas groupby datatime index, possible bug
39,398,821
<p>I have a Pandas DataFrame with a column that is a tz-aware TimeStamp and I tried to groupby(level=0).first(). I get an incorrect result. Am I missing something or is it a pandas bug?</p> <pre><code>x = pd.DataFrame(index = [1,1,2,2,2], data = pd.date_range("7:00", "9:00", freq="30min", tz = 'US/Eastern')) In [58]:...
3
2016-09-08T19:31:01Z
39,408,751
<p>I don't believe that it is a bug. If you go through the <a href="http://pytz.sourceforge.net/" rel="nofollow"><code>pytz</code></a> docs, it is clearly indicated that for timezone US/Eastern, there is no way to specify before / after the end-of-daylight-saving-time transition. </p> <p>In such cases, sticking with U...
1
2016-09-09T09:51:54Z
[ "python", "pandas", "timestamp" ]
Pandas groupby datatime index, possible bug
39,398,821
<p>I have a Pandas DataFrame with a column that is a tz-aware TimeStamp and I tried to groupby(level=0).first(). I get an incorrect result. Am I missing something or is it a pandas bug?</p> <pre><code>x = pd.DataFrame(index = [1,1,2,2,2], data = pd.date_range("7:00", "9:00", freq="30min", tz = 'US/Eastern')) In [58]:...
3
2016-09-08T19:31:01Z
39,411,972
<p>This is actually a pandas bug reported here:</p> <p><a href="https://github.com/pydata/pandas/issues/10668" rel="nofollow">https://github.com/pydata/pandas/issues/10668</a></p>
0
2016-09-09T12:47:21Z
[ "python", "pandas", "timestamp" ]
Permute list of lists with mixed elements (np.random.permutation() fails with ValueError)
39,398,877
<p>I'm trying to permute a list composed of sublists with mixed-type elements:</p> <pre><code>import numpy as np a0 = ['122', 877.503017, 955.471176, [21.701201, 1.315585]] a1 = ['176', 1134.076908, 1125.504758, [19.436181, 0.9987899]] a2 = ['177', 1038.686843, 1018.987868, [19.539959, 1.183997]] a3 = ['178', 878.999...
2
2016-09-08T19:34:35Z
39,398,973
<p>You need to convert your list to numpy arrays with with type <code>object()</code>, so that <code>random.permutation()</code> can interpret the lists as numpy types rather than sequence:</p> <pre><code>&gt;&gt;&gt; a = [np.array(i, dtype='object') for i in a] &gt;&gt;&gt; &gt;&gt;&gt; np.random.permutation(a) arra...
1
2016-09-08T19:40:22Z
[ "python", "numpy", "permutation" ]
Permute list of lists with mixed elements (np.random.permutation() fails with ValueError)
39,398,877
<p>I'm trying to permute a list composed of sublists with mixed-type elements:</p> <pre><code>import numpy as np a0 = ['122', 877.503017, 955.471176, [21.701201, 1.315585]] a1 = ['176', 1134.076908, 1125.504758, [19.436181, 0.9987899]] a2 = ['177', 1038.686843, 1018.987868, [19.539959, 1.183997]] a3 = ['178', 878.999...
2
2016-09-08T19:34:35Z
39,399,013
<p>What about using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.shuffle.html" rel="nofollow">np.random.shuffle</a>?</p> <pre><code># if you want the result in another list, otherwise just apply shuffle to a b = a[:] # shuffle the elements np.random.shuffle(b) # see the result of the shuff...
2
2016-09-08T19:43:02Z
[ "python", "numpy", "permutation" ]
Permute list of lists with mixed elements (np.random.permutation() fails with ValueError)
39,398,877
<p>I'm trying to permute a list composed of sublists with mixed-type elements:</p> <pre><code>import numpy as np a0 = ['122', 877.503017, 955.471176, [21.701201, 1.315585]] a1 = ['176', 1134.076908, 1125.504758, [19.436181, 0.9987899]] a2 = ['177', 1038.686843, 1018.987868, [19.539959, 1.183997]] a3 = ['178', 878.999...
2
2016-09-08T19:34:35Z
39,399,107
<p>random.shuffle() changes the list in place.</p> <p>Python API methods that alter a structure in-place generally return None.</p> <p>Please try <code>random.sample(a,len(a))</code></p> <p>The code would look like:</p> <pre><code>a = a[:] b = random.sample(a,len(a)) </code></pre>
0
2016-09-08T19:50:12Z
[ "python", "numpy", "permutation" ]
Permute list of lists with mixed elements (np.random.permutation() fails with ValueError)
39,398,877
<p>I'm trying to permute a list composed of sublists with mixed-type elements:</p> <pre><code>import numpy as np a0 = ['122', 877.503017, 955.471176, [21.701201, 1.315585]] a1 = ['176', 1134.076908, 1125.504758, [19.436181, 0.9987899]] a2 = ['177', 1038.686843, 1018.987868, [19.539959, 1.183997]] a3 = ['178', 878.999...
2
2016-09-08T19:34:35Z
39,399,202
<p>If you just want to create a random permutation of <code>a = [a0, a1, a2, a3]</code>, might I suggest permuting the indices instead?</p> <pre><code>&gt;&gt;&gt; random_indices = np.random.permutation(np.arange(len(a))) &gt;&gt;&gt; a_perm = [a[i] for i in random_indices] ... # Or just use the indices as you see fit...
2
2016-09-08T19:56:21Z
[ "python", "numpy", "permutation" ]
Difficulty accessing multi-dimensional array from JSON data
39,398,913
<p>Here is the JSON data in question:</p> <pre><code>{ "result_index": 0, "results": [ { "alternatives": [ { "confidence": 0.994, "transcript": "thunderstorms could produce large hail isolated tornadoes and heavy rain " } ], "final": true } ] </code><...
0
2016-09-08T19:36:19Z
39,398,950
<p>Your <code>results</code> and <code>alternatives</code> are not objects; but arrays of objects.</p> <pre><code>print(parsed['results'][0]['alternatives'][0]['transcript']) </code></pre>
1
2016-09-08T19:38:38Z
[ "python", "json" ]
Error setting dtypes of an array
39,398,933
<p>I was attempting to make a 1x5 numpy array with the following code</p> <pre><code>testArray = np.array([19010913, "Hershey", "Bar", "Birthday", 12.34]) </code></pre> <p>but encountered the unwanted result that</p> <pre><code>testArray.dtype dtype("&lt;U8") </code></pre> <p>I want each column to be a specific dat...
2
2016-09-08T19:37:36Z
39,399,470
<p>First off, I am not sure if <code>f10</code> is something known. </p> <p>Note that structured arrays need to be defined as "list of tuples". Try the following:</p> <pre><code>testArray = np.array([(19010913, "Hershey", "Bar", "Birthday", 12.34)], dtype=[('f0','&lt;i8'),('f1','&lt;U64'),('f2','&lt;U64'),('f3','&lt;...
1
2016-09-08T20:15:31Z
[ "python", "arrays", "numpy" ]
How to preprocess and load a "big data" tsv file into a python dataframe?
39,398,986
<p>I am currently trying to import the following large tab-delimited file into a dataframe-like structure within Python---naturally I am using <code>pandas</code> dataframe, though I am open to other options. </p> <p>This file is several GB in size, and is not a standard <code>tsv</code> file---it is broken, i.e. the ...
2
2016-09-08T19:41:31Z
39,399,727
<pre><code>$ cat &gt; pandas.awk BEGIN { PROCINFO["sorted_in"]="@ind_str_asc" # traversal order for for(i in a) } NR==1 { # the header cols is in the beginning of data file # FORGET THIS: header cols from another file replace NR==1 with NR==FNR and see * below split($0,a," ...
4
2016-09-08T20:33:00Z
[ "python", "pandas", "awk", "sed", "dataframe" ]
How to preprocess and load a "big data" tsv file into a python dataframe?
39,398,986
<p>I am currently trying to import the following large tab-delimited file into a dataframe-like structure within Python---naturally I am using <code>pandas</code> dataframe, though I am open to other options. </p> <p>This file is several GB in size, and is not a standard <code>tsv</code> file---it is broken, i.e. the ...
2
2016-09-08T19:41:31Z
39,516,975
<p>Another version which takes a separate column file as parameter or uses the first record. Run either way:</p> <pre><code>awk -f pandas2.awk pandas.txt # first record as header awk -f pandas2.awk cols.txt pandas.txt # first record from cols.txt awk -v cols="cols.txt" -f pandas2.awk pandas.txt # read cols from cols.t...
3
2016-09-15T17:24:51Z
[ "python", "pandas", "awk", "sed", "dataframe" ]
How to preprocess and load a "big data" tsv file into a python dataframe?
39,398,986
<p>I am currently trying to import the following large tab-delimited file into a dataframe-like structure within Python---naturally I am using <code>pandas</code> dataframe, though I am open to other options. </p> <p>This file is several GB in size, and is not a standard <code>tsv</code> file---it is broken, i.e. the ...
2
2016-09-08T19:41:31Z
39,523,179
<p>You can do this more cleanly completely in Pandas.</p> <p>Suppose you have two independent data frames with only one overlapping column:</p> <pre><code>&gt;&gt;&gt; df1 A B 0 1 2 &gt;&gt;&gt; df2 B C 1 3 4 </code></pre> <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#c...
1
2016-09-16T03:04:31Z
[ "python", "pandas", "awk", "sed", "dataframe" ]
My loss with fit_generator is 0.0000e+00 (using Keras)
39,399,029
<p>I am trying to use Keras on a “large” dataset for my GPU. To do so, I make use of fit_generator, the problem is that my loss is 0.0000e+00 every time.</p> <p>My print class and generator function:</p> <pre><code>class printbatch(callbacks.Callback): def on_batch_end(self, batch, logs={}): if batch%...
0
2016-09-08T19:44:15Z
39,437,121
<p>I solved this issue. The problem was that in '.theanorc' I had float16: this is not enough, so I changed it to float64 and now it works. </p> <p>This is my '.theanorc' at the moment:</p> <pre><code>[global] device = gpu floatX = float64 optimizer_including=cudnn [lib] cnmem=0.90 [blas] ldflags = -L/usr/local/lib...
0
2016-09-11T14:31:29Z
[ "python", "deep-learning", "keras", "autoencoder" ]
Python3 script not showing same result as MySQL engine for same query
39,399,033
<p>My python3 script is not generating the same result as MySQL. My query returns those rows whose value have changed over the week.</p> <p>Python script:</p> <pre><code>query = "SELECT cw.opportunityid, cw.probability, pw.probability, cw.stage, pw.stage, cw.amount, pw.amount, " \ "cw.closedate, pw.closedate " \ ...
0
2016-09-08T19:44:27Z
39,399,465
<p>A Python dictionary consists of unique key value pairs, so one key can just appear once in a dictionary. As your raw SQL query returns two distinct values from the same column in a single row, the second occurrence of the column overwrites the first in the dictionary. However, you can easily fix this by specifying a...
1
2016-09-08T20:15:29Z
[ "python", "mysql", "sql", "python-3.x" ]
Django bulk_create a list of lists
39,399,049
<p>As the title indicates, is there a way to bulk_create list of lists. Like right now I bulk_create it like - </p> <pre><code>for i in range(len(x)) arr1 = [] for m in range(len(y)): arr1.append(DataModel(foundation=foundation, date=dates[m], price=price[m])) DataModel.objects.bulk_create(arr1) </code>...
0
2016-09-08T19:45:32Z
39,399,177
<p>Append your object to <code>arr</code>, not <code>arr1</code>.<br> Or you can make flat list before <code>bulk_create</code>:</p> <pre><code>import itertools arr = list(itertools.chain(*arr)) </code></pre>
0
2016-09-08T19:54:59Z
[ "python", "django" ]
Django bulk_create a list of lists
39,399,049
<p>As the title indicates, is there a way to bulk_create list of lists. Like right now I bulk_create it like - </p> <pre><code>for i in range(len(x)) arr1 = [] for m in range(len(y)): arr1.append(DataModel(foundation=foundation, date=dates[m], price=price[m])) DataModel.objects.bulk_create(arr1) </code>...
0
2016-09-08T19:45:32Z
39,399,222
<p>Try this....</p> <pre><code>arr = [] for i in range(len(x)) arr1 = [] for m in range(len(y)): arr1.append(DataModel(foundation=foundation, date=dates[m], price=price[m])) #instead of appending the list, add list together to make one arr = arr + arr1 DataModel.objects.bulk_create(arr) </code></pre> ...
0
2016-09-08T19:57:49Z
[ "python", "django" ]
strip left and right in php
39,399,069
<p>I am converting the following python into php</p> <p>the aim is to remove scores from a string like "Liverpool 1 v 0 Everton"</p> <pre><code>home, away = event_data.get("desc").split(' v ') # remove scores from event desc if home.rsplit(' ', 1)[1].isdigit() and away.split(' ', 1)[0].isdigit(): event_name = ho...
2
2016-09-08T19:46:53Z
39,399,183
<p>Using <code>preg_repalce</code> in PHP you can replace digits around <code>" v "</code>:</p> <pre><code>$str = "Liverpool 1 v 0 Everton"; $event_name = preg_replace('/\h+\d+\h+v\h+\d+\h+/', ' v ', $str); echo $event_name . "\n"; //=&gt; Liverpool v Everton </code></pre>
2
2016-09-08T19:55:19Z
[ "php", "python", "regex" ]
Python+Selenium, can't click the 'button' wrapped by span
39,399,266
<p>I am new to selenium here. I am trying to use selenium to click a 'more' button to expand the review section everytime after refreshing the page. </p> <p>The website is TripAdvisor. The logic of <code>more</code> button is, as long as you click on the first <code>more</code> button, it will automatically expand all...
1
2016-09-08T20:00:31Z
39,399,403
<p>Try using an <a href="http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.action_chains" rel="nofollow"><code>ActionChains</code></a>:</p> <pre><code>from selenium.webdriver.common.action_chains import ActionChains # Your existing code here # Minus the `button.click()` line ActionChains(...
0
2016-09-08T20:11:07Z
[ "python", "selenium", "onclick", "css-selectors", "webdriver" ]
Python+Selenium, can't click the 'button' wrapped by span
39,399,266
<p>I am new to selenium here. I am trying to use selenium to click a 'more' button to expand the review section everytime after refreshing the page. </p> <p>The website is TripAdvisor. The logic of <code>more</code> button is, as long as you click on the first <code>more</code> button, it will automatically expand all...
1
2016-09-08T20:00:31Z
39,399,507
<blockquote> <p>WebDriverException: Message: Element is not clickable at point (318.5, 7.100006103515625). Other element would receive the click....</p> </blockquote> <p>This error to be occur when element is not in the view port and selenium couldn't click due to some other overlay element on it. In this case you s...
1
2016-09-08T20:18:25Z
[ "python", "selenium", "onclick", "css-selectors", "webdriver" ]
Converting stdout stream to html (add <br> on linebreaks)
39,399,281
<p>I'm trying to take some console output text and render it through django/js in a modal on my site. When printing the console output the line breaks work fine, but when rendered on the site it shows them all as one line. I tried replacing all the \n with <code>&lt;br&gt;</code> but it didn't seem to have any effect. ...
0
2016-09-08T20:01:48Z
39,401,918
<p>Simple mistake, I should have been passing the HTML, not the text. Also, adding pre tags to the text is much simpler than replacing all \n</p> <pre><code>input_modal.find('.modal-body').html('Analysis complete'+response.console_output) </code></pre>
0
2016-09-09T00:09:03Z
[ "javascript", "python", "html", "django" ]
Why is it considered bad practice to hardcode the name of a class inside that class's methods?
39,399,372
<p>In python, why is it a bad thing to do something like this:</p> <pre><code>class Circle: pi = 3.14159 # class variable def __init__(self, r = 1): self.radius = r def area(self): return Circle.pi * squared(self.radius) def squared(base): return pow(base, 2) </code></pre> <p>The area method could be d...
4
2016-09-08T20:08:46Z
39,399,506
<p>Because in case you subclass the class it will no longer refer to the class, but its parent. In your case it really doesn't make a difference, but in many cases it does:</p> <pre><code>class Rectangle(object): name = "Rectangle" def print_name(self): print(self.__class__.name) # or print(type(self)....
4
2016-09-08T20:18:24Z
[ "python", "oop" ]
Why is it considered bad practice to hardcode the name of a class inside that class's methods?
39,399,372
<p>In python, why is it a bad thing to do something like this:</p> <pre><code>class Circle: pi = 3.14159 # class variable def __init__(self, r = 1): self.radius = r def area(self): return Circle.pi * squared(self.radius) def squared(base): return pow(base, 2) </code></pre> <p>The area method could be d...
4
2016-09-08T20:08:46Z
39,399,604
<p>I can name here two reasons </p> <p>Inheritance</p> <pre><code>class WeirdCircle(Circle): pi = 4 c = WeirdCircle() print(c.area()) # returning 4 with self.__class__.pi # and 3.14159 with Circle.pi </code></pre> <p>When you want to rename the class, there is only one spot to modify. </p>
2
2016-09-08T20:24:51Z
[ "python", "oop" ]
Why is it considered bad practice to hardcode the name of a class inside that class's methods?
39,399,372
<p>In python, why is it a bad thing to do something like this:</p> <pre><code>class Circle: pi = 3.14159 # class variable def __init__(self, r = 1): self.radius = r def area(self): return Circle.pi * squared(self.radius) def squared(base): return pow(base, 2) </code></pre> <p>The area method could be d...
4
2016-09-08T20:08:46Z
39,399,877
<blockquote> <p>Why is it considered bad practice to hardcode the name of a class inside that class's methods?</p> </blockquote> <p><strong>It's not.</strong> I don't know why you think it is.</p> <p>There are plenty of good reasons to hardcode the name of a class inside its methods. For example, using <code>super<...
2
2016-09-08T20:41:29Z
[ "python", "oop" ]
Why is it considered bad practice to hardcode the name of a class inside that class's methods?
39,399,372
<p>In python, why is it a bad thing to do something like this:</p> <pre><code>class Circle: pi = 3.14159 # class variable def __init__(self, r = 1): self.radius = r def area(self): return Circle.pi * squared(self.radius) def squared(base): return pow(base, 2) </code></pre> <p>The area method could be d...
4
2016-09-08T20:08:46Z
39,399,961
<p>Zen of python says keep your code as simple as possible to make it readable. Why to get into using the class name or super. If you just use self then it will refer the relevant class and print its relevant variable. Refer below code.</p> <pre><code>class Rectangle(object): self.name = "Rectangle" def print_...
0
2016-09-08T20:48:01Z
[ "python", "oop" ]
Fabric runs bash script that ask for sudo password - How to send this password
39,399,393
<p>I want to use fabric to deploy some application on remote machines. For this, I use fabric to retrieve a bash script from a VCS (bitbucket or github) and execute it. However, the first step of my script is to add the current user to the sudoers, so I am requested for a password.</p> <p>Is it possible to send this p...
0
2016-09-08T20:10:22Z
39,437,636
<p>Use fabric's "<strong>sudo</strong>" function instead of "<strong>run</strong>" function. Script won't prompt for password since it will be running with sudo privilege.</p> <pre><code>def deploy(): env.hosts = ['192.168.100.160'] source_folder = '/home/username/src' branch = 'dev' puts('Pulling changes ...
1
2016-09-11T15:23:47Z
[ "python", "bash", "fabric" ]
Prime Sieve/pairs in a range
39,399,396
<p>I am trying to write a prime sieve generator that I convert to a list for printing and then print the primes in a given range. I'm pretty sure my number of pairs is correct but for some reason I am getting some extra values in my list of primes that aren't prime. (I caught this right away because my last value in th...
0
2016-09-08T20:10:37Z
39,399,682
<p>your sieve function is incorrect. You mark all numbers as not prime, starting by "2". You need to start by the next multiple of the prime which is <code>prime*prime</code></p> <p>Hence, you have to start at <code>i*i</code> not <code>i</code> (I used <code>i*2</code> which works but is redundant because already cov...
0
2016-09-08T20:29:56Z
[ "python", "primes", "sieve-of-eratosthenes", "sieve" ]