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
Unable to send email using gmail server using python
37,483,805
<p>I am trying to send email using python. I tried many solution on Stackoverflow but none worked.</p> <p>my code is - </p> <pre><code>import smtplib fromaddr = 'user_me@gmail.com' toaddrs = 'user_you@gmail.com' msg = 'msg text here' username = 'user_me@gmail.com' password = 'pwd' server = smtplib.SMTP('smtp.gmail.c...
0
2016-05-27T12:38:25Z
37,760,779
<p>Try after turning of Gmail's Security Feature Here. This may be preventing 3rd party application from accessing Gmail for security purpose</p> <p><a href="https://www.google.com/settings/security/lesssecureapps" rel="nofollow">https://www.google.com/settings/security/lesssecureapps</a></p>
0
2016-06-11T06:40:51Z
[ "python", "email", "smtp" ]
Django ORM: Dynamically determine another table name according one field value
37,483,860
<p>I hit one problem when generate orm query upon there tables.</p> <p>I have models here:</p> <pre><code>class Task(models.Model): deliver = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, related_name='task') tasktype = models.PositiveSmallIntegerField(db_index=True) description = models.Cha...
0
2016-05-27T12:41:21Z
37,484,513
<p>You should model the situation in another way:</p> <pre><code>class Task(models.Model): deliver = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, related_name='task') tasktype = models.PositiveSmallIntegerField(db_index=True) description = models.CharField(max_length=500, null=True, blank=Tru...
0
2016-05-27T13:16:07Z
[ "python", "mysql", "django", "orm" ]
Spark: PySpark Slowness , memory issue in writing to Cassandra
37,483,910
<p>I am using pyspark to aggregate and group a largish csv on a low end machine ; 4 GB Ram and 2 CPU Core. This is done to check the memory limits for the prototype. After aggregation I need to store the RDD to Cassandra which is running in another machine.</p> <p>I am using Datastax cassandra-python driver. First I u...
0
2016-05-27T12:43:55Z
37,701,922
<p>I tried the execution in a machine with a bigger RAM - 16 GB; This time I am able to avert the Out if Memory scenario of above;</p> <p>However this time I change the insert a bit to insert to multiple table;</p> <p>So even with <code>session.executeAsysc</code> too I am finding that the python driver is CPU bound...
0
2016-06-08T12:01:26Z
[ "python", "memory", "cassandra", "pyspark" ]
Switching "tab" in accordion programmatically
37,484,027
<p>I want to switch "tab" when the Load file button has been pressed on a file, meaning that when a file has been loaded it should switch to the second AccordionItem. How can I do this programmatically?</p> <pre><code> 42 Accordion: 43 orie...
1
2016-05-27T12:49:53Z
37,496,959
<p>You can use <code>dispatch()</code> method to simulate clicking on <code>AccordionItem</code>:</p> <pre><code>from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.lang import Builder Builder.load_string(''' &lt;MyWidget&gt;: orientation: "vertical" Button: text: "switch" ...
1
2016-05-28T08:39:26Z
[ "python", "kivy" ]
How to access a KEGG entry without specifying the organism using bioservices?
37,484,095
<p>I try to access <a href="http://www.genome.jp/kegg/" rel="nofollow">KEGG</a> via <a href="https://pythonhosted.org/bioservices/kegg_tutorial.html" rel="nofollow">bioservices</a> to get certain information about a list of genes. Problem is that I do not know beforehand to which organism the individual genes belong; i...
3
2016-05-27T12:53:51Z
37,501,287
<p>The output of the find() method is a pure string that is not easy to read but I believe the information you are looking for is in the output. On the third line, you can see:</p> <pre><code>eco:b3640 </code></pre> <p>Now, I am not sure if the output format from KEGG is always having the same structure. If so, assum...
3
2016-05-28T16:19:22Z
[ "python", "web-services", "bioservices" ]
Previous and next item of list python
37,484,146
<p>Can anyone point me towards a practical way of getting the previous and next items of a list. For example:</p> <pre><code>my_list = [100, 200, 300, 400] </code></pre> <p>Is there a practical way of getting the previous and next item (300 and 100).</p> <p>I am using <code>my_list[my_list.index(400) - 1]</code> to ...
-1
2016-05-27T12:56:22Z
37,484,240
<p>I suppose that, when you look for the next element "after" 400; you want to get the first one? In that case; just check for the size of your list:</p> <pre><code>current_index = my_list.index(400) next_index = current_index + 1 if (next_index == len(my_list)): next_index = 0 next_value = my_list[next_index] </...
0
2016-05-27T13:01:37Z
[ "python", "list" ]
Previous and next item of list python
37,484,146
<p>Can anyone point me towards a practical way of getting the previous and next items of a list. For example:</p> <pre><code>my_list = [100, 200, 300, 400] </code></pre> <p>Is there a practical way of getting the previous and next item (300 and 100).</p> <p>I am using <code>my_list[my_list.index(400) - 1]</code> to ...
-1
2016-05-27T12:56:22Z
37,484,253
<p>You could use the modolu operator to "loop" around the list's borders:</p> <pre><code>&gt;&gt;&gt; my_list = [100, 200, 300, 400] &gt;&gt;&gt; val = 400 &gt;&gt;&gt; my_list[(my_list.index(val) + 1) % len(my_list)] # next 100 &gt;&gt;&gt; my_list[(my_list.index(val) - 1) % len(my_list)] # previous 300 </code></pre>...
5
2016-05-27T13:02:15Z
[ "python", "list" ]
Previous and next item of list python
37,484,146
<p>Can anyone point me towards a practical way of getting the previous and next items of a list. For example:</p> <pre><code>my_list = [100, 200, 300, 400] </code></pre> <p>Is there a practical way of getting the previous and next item (300 and 100).</p> <p>I am using <code>my_list[my_list.index(400) - 1]</code> to ...
-1
2016-05-27T12:56:22Z
37,484,263
<p>A simple solution is to use modulo</p> <pre><code>my_list[ (my_list.index(400) + 1) % len(my_list) ] </code></pre> <p>result:</p> <pre><code>&gt;&gt; 100 </code></pre>
5
2016-05-27T13:02:33Z
[ "python", "list" ]
Previous and next item of list python
37,484,146
<p>Can anyone point me towards a practical way of getting the previous and next items of a list. For example:</p> <pre><code>my_list = [100, 200, 300, 400] </code></pre> <p>Is there a practical way of getting the previous and next item (300 and 100).</p> <p>I am using <code>my_list[my_list.index(400) - 1]</code> to ...
-1
2016-05-27T12:56:22Z
37,484,519
<p>You can use operator <code>%</code></p> <pre><code>def get_loop_item(my_list, item, spacing): if isinstance(spacing, int): return my_list[(my_list.index(item) + spacing) % len(my_list)] elif isinstance(spacing, list): return [get_loop_item(my_list, item, space) for space in spacing] ret...
0
2016-05-27T13:16:41Z
[ "python", "list" ]
Why do values in my 3D numpy array change when I write it to file?
37,484,254
<p>strange problem in that I have a 3D array full of labels (lets say from 1-36) called labelled_stack. These are just areas where the value in the array is equal to the label given. A quick 2D example with 5 labels would be something like:</p> <pre><code>labelled_stack = (0 0 0 0 0 0 0 0 0 0) (0 1 1 ...
3
2016-05-27T13:02:18Z
37,484,394
<p>As you can read in the <a href="http://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html?highlight=imwrite#imwrite" rel="nofollow">documentation</a>:</p> <blockquote> <p>The function imwrite saves the image to the specified file. The image format is chosen based on the filename ext...
3
2016-05-27T13:10:00Z
[ "python", "arrays", "opencv", "numpy", "scipy" ]
Why do values in my 3D numpy array change when I write it to file?
37,484,254
<p>strange problem in that I have a 3D array full of labels (lets say from 1-36) called labelled_stack. These are just areas where the value in the array is equal to the label given. A quick 2D example with 5 labels would be something like:</p> <pre><code>labelled_stack = (0 0 0 0 0 0 0 0 0 0) (0 1 1 ...
3
2016-05-27T13:02:18Z
37,484,620
<p>The function <code>imwrite</code> saves the data in an 8 bit format. When the function converts your 32 bit data to 8 bit, it scales the data to use the full bit depth of 8 bits, so for example the maximum of your data is scaled up to 255. See <a href="http://stackoverflow.com/questions/33529401/scipy-imsave-saves...
3
2016-05-27T13:21:35Z
[ "python", "arrays", "opencv", "numpy", "scipy" ]
django-tables2 custom column
37,484,276
<p>I'm working now on my first Django project. I want to render results table which contains all fields from <strong>Priekabos</strong> model and one custom column from <strong>Grafikas</strong> which should contain something similar to <em>SELECT max(kada_moketi) FROM grafikas WHERE priekabos_id = ?</em>. Whatever I t...
0
2016-05-27T13:03:31Z
37,484,867
<p>It sounds like you might be able to fetch the extra field using <a href="https://docs.djangoproject.com/en/1.9/topics/db/aggregation/#generating-aggregates-for-each-item-in-a-queryset" rel="nofollow"><code>annotate</code></a>.</p> <pre><code>from django.db.models import Max queryset = Priekabos.objects.annotate(max...
0
2016-05-27T13:33:39Z
[ "python", "django", "django-tables2" ]
CountVectorizer reading and writing vocabulary
37,484,369
<p>I am currently working on a fairly trivial sentiment classification program. Everything works well in the training phase. However, I am having trouble using CountVectorizer to test new strings of text that contain unseen words.</p> <p>For this reason I am trying to write a lookup vocabulary for vectorization in th...
0
2016-05-27T13:08:35Z
37,484,991
<p>You need to save a copy of your vectorizer using some serializer, e.g. pickle and load it in the test phase. You can also get the vocab using, vocabulary_ attribute see <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html" rel="nofollow">here</a> for more de...
0
2016-05-27T13:39:23Z
[ "python", "machine-learning", "scikit-learn", "vectorization", "sentiment-analysis" ]
Cannot install PIP on Raspbian
37,484,608
<p>I can't get PIP running in my Raspberry (running in Wheezy). After I always got this message:</p> <pre><code>~ $ pip3 /usr/local/lib/python3.2/dist-packages/pip-8.1.2-py3.2.egg/pip/_vendor/pkg_resources/__init__.py:80: UserWarning: Support for Python 3.0-3.2 has been dropped. Future versions will fail here. warni...
0
2016-05-27T13:21:03Z
37,528,692
<p>OK, sorted. Apparently my Python 2.7 install was somewhat corrupted. After I did <code>sudo apt-get -u dist-upgrade</code> which - with some hick-ups - fixed the install. After that I re-built the 3.5.1 binaries and pip3 works now fine.</p>
0
2016-05-30T14:59:20Z
[ "python", "python-3.5", "raspbian-wheezy" ]
Python parse dataframe element
37,484,646
<p>I have a pandas dataframe column (Data Type) which I want to split into three columns</p> <pre><code>target_table_df = LoadS_A [['Attribute Name', 'Data Type', 'Primary Key Indicator']] </code></pre> <p>Example input (target_table_df)</p> <pre><code> ...
1
2016-05-27T13:22:57Z
37,485,178
<p>Use <code>target_table_df['Data Type'].str.extract(pattern)</code></p> <p>You'll need to assign <code>pattern</code> to be a regular expression that captures each of the components you're looking for.</p> <pre><code>pattern = r'([^\(]+)(\(([^,]*),(.*)\))?' </code></pre> <p><code>([^\(]+)</code> says grab as many ...
2
2016-05-27T13:48:26Z
[ "python", "regex", "parsing", "pandas", "dataframe" ]
Change the size of turtle in python 2 on Trinket.io
37,484,701
<p>I am trying to change the size of turtle to something larger. I am not sure if I am either doing it incorrectly, or it I just can't because Trinket.io does not support it. The following is the code I currently have:</p> <pre><code>#python 2 from turtle import * wn = Screen() wn.setup(640,400,0,0) wn.bgcolor("#4885...
1
2016-05-27T13:25:40Z
37,485,298
<p>Unfortunately, if you go to <a href="https://trinket.io/docs/python" rel="nofollow">https://trinket.io/docs/python</a> you will find out that <code>resizemode()</code> and <code>shapesize()</code> are not mentioned as functions. I presume they have not been implemented into trinket interface.</p>
1
2016-05-27T13:54:05Z
[ "python", "python-2.7" ]
Pandas DataFrame construction from a list of OrderedDict: preserving columns order
37,484,738
<p>pd.__version__ = 0.18.0</p> <p>Suppose you have a <em>list</em> of OrderedDict:</p> <pre><code>[OrderedDict([('SecurityCode', 'IDX.MSDENON'), ('DescriptionLong', 'MSCI Norway NR USD (EUR)'), ('DataSrc', 'BGN.COB'), ('Ticker', 'MSDENON Index'), ('LastRun', None)])] </code></pre> <p>if you construct a DataFrame fr...
2
2016-05-27T13:27:20Z
37,498,101
<p>Try this:</p> <pre><code>df = pd.DataFrame.from_dict(data[0], orient='index').T </code></pre>
0
2016-05-28T10:51:18Z
[ "python", "python-3.x", "pandas", "dataframe", "ordereddictionary" ]
Pandas DataFrame construction from a list of OrderedDict: preserving columns order
37,484,738
<p>pd.__version__ = 0.18.0</p> <p>Suppose you have a <em>list</em> of OrderedDict:</p> <pre><code>[OrderedDict([('SecurityCode', 'IDX.MSDENON'), ('DescriptionLong', 'MSCI Norway NR USD (EUR)'), ('DataSrc', 'BGN.COB'), ('Ticker', 'MSDENON Index'), ('LastRun', None)])] </code></pre> <p>if you construct a DataFrame fr...
2
2016-05-27T13:27:20Z
37,521,380
<p>It is indeed an issue on DataFrame constructor (cf my EDIT).<br> I feel columns= option workaround is nicer (syntaxically more understandable) than hhbilly proposed solution.</p>
1
2016-05-30T08:48:36Z
[ "python", "python-3.x", "pandas", "dataframe", "ordereddictionary" ]
Use of cell.value vs cell.internal_value for openpyxl's iter_rows() method
37,484,863
<p>I'm working on a piece of code from two computers. I use openpyxl to read data from an excel sheet, with <code>load_workbook</code> keyword arguments <code>data_only=True</code> and <code>use_iterators=True</code>. Depending on which computer I'm using, I need to use either <code>cell.value</code> or <code>cell.in...
1
2016-05-27T13:33:34Z
37,485,084
<p>I was using a different version of openpyxl on each computer. I had thought they'd be the same since I used Anaconda to install each. The issues was fixed with <code>conda update openpyxl</code>. After updating, using <code>cell.value</code> works for both.</p> <p>I'll leave the question up in case another user ...
0
2016-05-27T13:44:07Z
[ "python", "openpyxl" ]
Django Rest required parameters in URL
37,484,865
<p>I'm using django rest framework. Here is my code:</p> <p><strong>urls.py:</strong></p> <pre><code>urlpatterns = [ url(r'^users/show', UserShow.as_view()), ] </code></pre> <p><strong>view.py:</strong></p> <pre><code>class UserShow(ListAPIView): queryset = User.objects.all() serializer_class = UserSeri...
3
2016-05-27T13:33:38Z
37,487,444
<pre><code>class UserShow(ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer def filter_queryset(self, queryset): username = self.request.query_params.get('username', None) user_id = self.request.query_params.get('user_id', None) if username is not None:...
-1
2016-05-27T15:37:54Z
[ "python", "django", "django-rest-framework", "django-class-based-views" ]
Django Rest required parameters in URL
37,484,865
<p>I'm using django rest framework. Here is my code:</p> <p><strong>urls.py:</strong></p> <pre><code>urlpatterns = [ url(r'^users/show', UserShow.as_view()), ] </code></pre> <p><strong>view.py:</strong></p> <pre><code>class UserShow(ListAPIView): queryset = User.objects.all() serializer_class = UserSeri...
3
2016-05-27T13:33:38Z
37,636,683
<pre><code>class UserIdRetrieve(RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserUsernameRetrieve(UserIdRetrieve): lookup_field = 'username' </code></pre> <p>and in urls:</p> <pre><code>urlpatterns = [ url(r'^users/(?P&lt;pk&gt;\d+)/', UserIdRetrieve.as_vie...
0
2016-06-05T01:47:22Z
[ "python", "django", "django-rest-framework", "django-class-based-views" ]
Calculations while making dataframe aggregation in Pandas
37,484,960
<p>I have a Pandas Dataframe which looks like</p> <pre><code>id rank weight 2 4 2 6 12 1 3 9 1 7 1 2 1 4 4 7 3 1 2 19 2 6 3 2 8 4 3 5 7 1 2 5 2 1 6 1 3 1 1 ...
0
2016-05-27T13:38:09Z
37,485,034
<p>If need only one output column use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.sum.html" rel="nofollow"><code>sum</code></a> and <a...
0
2016-05-27T13:41:48Z
[ "python", "pandas", "dataframe", "aggregate" ]
put_records() only accepts keyword arguments in Kinesis boto3 Python API
37,484,987
<pre><code>from __future__ import print_function # Python 2/3 compatibility import boto3 import json import decimal #kinesis = boto3.resource('kinesis', region_name='eu-west-1') client = boto3.client('kinesis') with open("questions.json") as json_file: questions = json.load(json_file) Records = [] count = ...
0
2016-05-27T13:39:15Z
37,485,343
<p>When passing multiple records, you need to encapsulate the records in a list of records, and then add the stream identifier.</p> <p>Format is like so:</p> <pre><code>{ "Records": [ { "Data": blob, "ExplicitHashKey": "string", "PartitionKey": "string" }, { ...
1
2016-05-27T13:56:03Z
[ "python", "amazon-web-services", "boto3", "amazon-kinesis" ]
put_records() only accepts keyword arguments in Kinesis boto3 Python API
37,484,987
<pre><code>from __future__ import print_function # Python 2/3 compatibility import boto3 import json import decimal #kinesis = boto3.resource('kinesis', region_name='eu-west-1') client = boto3.client('kinesis') with open("questions.json") as json_file: questions = json.load(json_file) Records = [] count = ...
0
2016-05-27T13:39:15Z
37,486,264
<pre><code> from __future__ import print_function # Python 2/3 compatibility import boto3 import json import decimal import time def putdatatokinesis(RecordKinesis): start = time.clock() response = client.put_records(Records=RecordKinesis, StreamName='LoadtestKinesis') p...
0
2016-05-27T14:39:02Z
[ "python", "amazon-web-services", "boto3", "amazon-kinesis" ]
python - locale in dateutil / parser
37,485,174
<p>I set</p> <pre><code>locale.setlocale(locale.LC_TIME, ('de', 'UTF-8')) </code></pre> <p>the string to parse is:</p> <pre><code>Montag, 11. April 2016 19:35:57 </code></pre> <p>I use:</p> <pre><code>note_date = parser.parse(result.group(2)) </code></pre> <p>but get the following error:</p> <blockquote> <p>Tr...
2
2016-05-27T13:48:14Z
37,485,484
<p><code>dateutil.parser</code> doesn't use <code>locale</code>. You'll need to subclass <a href="https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.parserinfo" rel="nofollow"><code>dateutil.parser.parserinfo</code></a> and construct a German equivalent:.</p> <pre><code>from dateutil import parser ...
2
2016-05-27T14:03:43Z
[ "python", "python-dateutil" ]
Import working in console but not in pyCharm
37,485,240
<p>I had a python project with a lot of imports like:</p> <pre><code>from src.main.fr.some.module import someclass </code></pre> <p>and it was working good but my colleagues wanted the imports to be like:</p> <pre><code>from fr.some.module import someclass </code></pre> <p>Then I changed the <code>PYTHONPATH</code>...
2
2016-05-27T13:51:29Z
37,520,474
<p>I solved my issue thanks to Zulan's comment.</p> <p><strong>TLDR:</strong></p> <p>Put the <code>src/main/</code> directory before <code>src/test/</code> one in pycharm interpreter <code>PYTHONPATH</code>.</p> <hr> <p>Using the -v option for python interpreter in both pycharm and console, I have got the following...
0
2016-05-30T07:58:50Z
[ "python", "pycharm" ]
Transform image into other
37,485,310
<p>Using PIL and tkinter, I'm trying to do some manipulations in the pixelMatrix of an image like:</p> <pre><code>start = Image.open("gua.jpg") sta = start.load() i,j = start.size current = np.zeros((i,j,3)) for ix in range(i): for jx in range(j): current[ix,jx] = [elem*0.5 for elem in sta[ix,jx]] curr...
1
2016-05-27T13:54:39Z
37,490,497
<p>You need to specify that the <code>dtype</code> of your array is <code>np.uint8</code>:</p> <pre><code>current = np.zeros((i,j,3),dtype=np.uint8) </code></pre> <p>If you do not specify this when PIL uses the <code>.tobytes()</code> method on the array it gets data that does not make sense for <code>"RGB"</code> be...
1
2016-05-27T18:52:34Z
[ "python", "tkinter", "python-imaging-library" ]
Default int value with xmlrpclib
37,485,334
<p>I tried to execute the following code, but <code>xmlrpclib</code> is raising an exception:</p> <pre><code>&gt;&gt;&gt; import xmlrpclib &gt;&gt;&gt; data = """&lt;?xml version="1.0"?&gt; ... &lt;methodCall&gt; ... &lt;methodName&gt;test_method&lt;/methodName&gt; ... &lt;params&gt; ... &lt;param&gt;...
1
2016-05-27T13:55:36Z
37,494,824
<p>Without passing judgement on Python implementation :) this monkey patch fixes the way end_int() handles empty data. In your example before calling xmlrpclib.loads(data):</p> <pre><code>class MyUnmarshaller(xmlrpclib.Unmarshaller): def end_int(self, data): self.append(int(data or "0")) self._val...
2
2016-05-28T03:14:47Z
[ "python", "xml-rpc", "xmlrpclib" ]
Python: make consistent 3D plot out of point values
37,485,382
<p>In a 2D plane, I have a set of <code>nxn</code> points defined by their <code>(x,y)</code> coordinates. For each point, there exists a certain quantity that I want to plot as a 3D surface. How can I do it in such a way that each point is assigned the relevant value in the plot? I ask because I am getting a messed up...
0
2016-05-27T13:57:50Z
37,492,118
<p>I guess a problem in line <code>Y=X</code>. <code>X, Y</code> are lists. When you write <code>Y=X</code>, it means <code>Y</code> is a reference to <code>X</code>. You need to make a copy, i.e.:</p> <pre><code>Y = [] numpy.copy(Y,X) </code></pre> <p>Test this variant and write what would happened. Otherwise post d...
3
2016-05-27T20:55:41Z
[ "python", "dictionary", "matplotlib", "plot", "3d" ]
pip: Install error with python2.7 on ec2 AMI
37,485,528
<p>After installing pip with get-pip.py </p> <pre><code> wget https://bootstrap.pypa.io/get-pip.py python get-pip.py </code></pre> <p>I get this error when I try to check the installation with <code>pip -V</code></p> <pre><code>Traceback (most recent call last): File "/usr/bin/pip", line 5, in &lt;module&gt; from p...
0
2016-05-27T14:05:33Z
37,486,135
<p>Try installing virtualenv for manage your versions independently:</p> <pre><code>sudo apt-get install virtualenv </code></pre> <p>Create the virtual environment</p> <pre><code>virtualenv newvenv </code></pre> <p>Run your new environment</p> <pre><code>source newvenv/bin/activate </code></pre> <p>Finally</p> <...
3
2016-05-27T14:33:02Z
[ "python", "amazon-ec2", "pip" ]
pip: Install error with python2.7 on ec2 AMI
37,485,528
<p>After installing pip with get-pip.py </p> <pre><code> wget https://bootstrap.pypa.io/get-pip.py python get-pip.py </code></pre> <p>I get this error when I try to check the installation with <code>pip -V</code></p> <pre><code>Traceback (most recent call last): File "/usr/bin/pip", line 5, in &lt;module&gt; from p...
0
2016-05-27T14:05:33Z
37,489,242
<p>Probably you have an Ubuntu image. You need to remove the system pip version before installing the new one.</p> <p>Do a apt-get remove python-pip before your commands and you will have a proper pip installed.</p> <p>For python3: apt-get remove python3-pip</p> <p>Same may apply for CentOS based onesbut you will ha...
0
2016-05-27T17:27:19Z
[ "python", "amazon-ec2", "pip" ]
Sorting a list of IPv4Network and IPv6Network objects
37,485,530
<p>I have a list of IPv4 and IPv6 networks created with <a href="https://docs.python.org/3/library/ipaddress.html#ipaddress.ip_network" rel="nofollow"><code>ipaddress.ip_network()</code></a>, which I want to sort (by family first, then value). What would be the best way to do this? Apparently, a naive sort doesn't work...
0
2016-05-27T14:05:48Z
37,485,651
<p>Just use a <a href="https://docs.python.org/3/library/stdtypes.html#list.sort" rel="nofollow"><code>key</code> function</a> that would allow to compare the values by type first, something like:</p> <pre><code>&gt;&gt;&gt; from ipaddress import ip_network, IPv6Network &gt;&gt;&gt; L = [ip_network(x) for x in ['ff00:...
1
2016-05-27T14:10:56Z
[ "python", "python-3.x", "network-programming" ]
py.test test discovery for a test in a file that does not begin test_*.py
37,485,671
<p>I am new to py.test and want to simply write some test functions next to some other functions in a Python file.</p> <p>My main file is called something like <code>myfile.py</code>. Inside that file I have a function. For example:</p> <pre><code>def pad(bytes): return " "*bytes </code></pre> <p>I want to veri...
0
2016-05-27T14:11:48Z
37,486,428
<p>Create a file called <code>pytest.ini</code>:</p> <pre><code>[pytest] python_files=*.py </code></pre> <p>See <a href="https://pytest.org/latest/example/pythoncollection.html" rel="nofollow">Changing standard (Python) test discovery</a> for more details. (It's not that obvious.) </p>
1
2016-05-27T14:46:37Z
[ "python", "py.test" ]
How to add an OR filter around a nested query with elasticsearch-dsl
37,485,726
<p>I have a nested filter that looks like this:</p> <pre><code>search = search.filter( 'nested', path=path, filter=F('bool', must=queries), inner_hits={'sort': ['p', 'd']} ) </code></pre> <p>I'd like to add an OR filter around the whole thi...
1
2016-05-27T14:14:58Z
37,486,054
<p>A little more perseverance got me this:</p> <pre><code>search = search.filter( 'or', [F( 'nested', path=path, filter=F('bool', must=queries), inner_hits={'sort': ['p', 'd']} ), F('bool', m...
1
2016-05-27T14:29:00Z
[ "python", "elasticsearch", "elasticsearch-dsl" ]
Combine strings (paths) without duplication of parts
37,485,743
<p>I have two paths:</p> <pre><code>a = '/folder1/subfolder/' b = '/subfolder/folder2' </code></pre> <p>How to combine them into </p> <pre><code>c = '/folder1/subfolder/folder2/' </code></pre> <p>in the simplest way?</p>
0
2016-05-27T14:15:50Z
37,486,035
<p>Checking only the last component of <code>a</code>, you could do:</p> <pre><code>A = a.strip('/').split('/') B = b.strip('/').split('/') if A[-1] == B[0]: print("/{}/".format("/".join(A + B[1:]))) </code></pre>
1
2016-05-27T14:28:19Z
[ "python" ]
Taking derivative of function in Python
37,485,756
<p>I've written a simple code that takes derivatives, however it fails to take derivative of trigonometry.</p> <pre><code>from math import sin, radians def sinus(x): return sin(radians(x)) def derivative(func , x): h = 0.0000000001 return (func(x+h)-func(x))/h def f(x): return 2*x**2+x print(deriv...
2
2016-05-27T14:16:28Z
37,485,952
<p>As for the slight difference in the derivative of <code>f()</code>, that comes from your formula not being exact. That general difference quotient gives the exact answer only for an infinitely small value of <code>h</code>. The computer clearly cannot handle an infinitely small value, so you used a "regular" but som...
4
2016-05-27T14:25:00Z
[ "python", "derivative" ]
Taking derivative of function in Python
37,485,756
<p>I've written a simple code that takes derivatives, however it fails to take derivative of trigonometry.</p> <pre><code>from math import sin, radians def sinus(x): return sin(radians(x)) def derivative(func , x): h = 0.0000000001 return (func(x+h)-func(x))/h def f(x): return 2*x**2+x print(deriv...
2
2016-05-27T14:16:28Z
37,486,022
<p>Often in numerical computation, it is not good to perform a computational task as you would on paper. Primarily because you have to be concerned with floating point errors. As such, a better implementation of a derivative is found by the following:</p> <pre><code>def derivative(func, x, h = None): if h is None:...
0
2016-05-27T14:27:54Z
[ "python", "derivative" ]
Taking derivative of function in Python
37,485,756
<p>I've written a simple code that takes derivatives, however it fails to take derivative of trigonometry.</p> <pre><code>from math import sin, radians def sinus(x): return sin(radians(x)) def derivative(func , x): h = 0.0000000001 return (func(x+h)-func(x))/h def f(x): return 2*x**2+x print(deriv...
2
2016-05-27T14:16:28Z
37,486,071
<p>No, you are not wrong on the code.</p> <p>'d/dx sin(radians(x))' is <code>1/180 π cos((π x)/180)</code></p> <p><a href="http://www.wolframalpha.com/input/?i=d%2Fdx+sin(radians(x))" rel="nofollow">http://www.wolframalpha.com/input/?i=d%2Fdx+sin(radians(x))</a></p> <p>and that at 60 is ~ 0.00872746319658</p>
1
2016-05-27T14:29:49Z
[ "python", "derivative" ]
Taking derivative of function in Python
37,485,756
<p>I've written a simple code that takes derivatives, however it fails to take derivative of trigonometry.</p> <pre><code>from math import sin, radians def sinus(x): return sin(radians(x)) def derivative(func , x): h = 0.0000000001 return (func(x+h)-func(x))/h def f(x): return 2*x**2+x print(deriv...
2
2016-05-27T14:16:28Z
37,486,495
<p>The sine derivative is not working as expected because <code>sinus</code> converts the <code>+h</code> part into radians, while the denominator leaves it in degrees. You'll notice that the following function calculates the derivative correctly. </p> <pre><code># treat h as degrees def derivative(func, x): h = 0...
1
2016-05-27T14:50:06Z
[ "python", "derivative" ]
SQLAlchemy: How to convert a value of a colum in ORM-class
37,485,819
<p>I'm using SQLAlchemy do read from a (given) SQLite database. Unfortunately the time value is String and not a TIMESTAMP like "Fri Apr 15 15:57:59 2016"</p> <pre><code>class Test(Base): __tablename__ = 'test' id = Column('id', String, primary_key=True) time = Column('id', String) </code></pre> <p>Is the...
0
2016-05-27T14:19:28Z
37,487,467
<p>I would recommend throwing a property on top of your model:</p> <pre><code>from datetime import datetime class Test(Base): __tablename__ = 'test' id = Column('id', String, primary_key=True) _time = Column('time', String) @property def time(self): return datetime.strptime(self._time, '%...
1
2016-05-27T15:39:08Z
[ "python", "sqlite", "orm", "sqlalchemy" ]
Skip content of specific element when doing findAll() in Beautifoul soup
37,485,835
<p>For example: I want to find contents of element with class "author"(<code>soup.findall(class_='author')</code>) but skip searching inside elements with class "comments"((<code>soup.findall(class_='comments')</code>). </p> <p>So class "author" but not inside any element with class "comments"</p> <p>Is it possible t...
1
2016-05-27T14:20:02Z
37,487,992
<p>I think a way would be using a for loop and if statement to filter using .parent. This can be cleaned up for your needs but it works using item.parent['class'] to get the containing divs class for comparison.</p> <pre><code>from bs4 import BeautifulSoup soup = BeautifulSoup(someHTML, 'html.parser') results = soup...
-1
2016-05-27T16:07:01Z
[ "python", "python-3.x", "beautifulsoup", "html-parsing" ]
Skip content of specific element when doing findAll() in Beautifoul soup
37,485,835
<p>For example: I want to find contents of element with class "author"(<code>soup.findall(class_='author')</code>) but skip searching inside elements with class "comments"((<code>soup.findall(class_='comments')</code>). </p> <p>So class "author" but not inside any element with class "comments"</p> <p>Is it possible t...
1
2016-05-27T14:20:02Z
37,576,389
<pre><code>def AuthorNotInComments(tag): c = tag.get('class') if not c: return False if 'author' in c: if tag.findParents(class_='comments'): return False return True soup.findAll(AuthorNotInComments) </code></pre> <p>or "case insensitive contains" version:</p> <pre><...
0
2016-06-01T18:38:18Z
[ "python", "python-3.x", "beautifulsoup", "html-parsing" ]
python pandas dataframe to list string error
37,485,919
<p>I am relatively new to pandas and now trying to convert pandas DataFrame rows to lists of strings.</p> <p>It works well, however the strings in the original DataFrame are strangely modified in the list, as some append an "L" character for some reason.</p> <p>I appreciate your help very much..</p> <pre><code>&gt;&...
0
2016-05-27T14:24:04Z
37,490,503
<p>Every column in the DataFrame has a specific "type" associated with it.</p> <p>Typically this usually means they are of type "string", "int", or "float".</p> <p>Right now, your .tolist() call converts the row into a list, but it doesn't necessarily change the type of all the values into a string.</p> <p>When you ...
0
2016-05-27T18:52:57Z
[ "python", "pandas" ]
Is it possible to scrape webpage without using third-party libraries in python?
37,485,925
<p>I am trying to understand how beautiful soup works in python. I used beautiful soup,lxml in my past but now trying to implement one script which can read data from given webpage without any third-party libraries but it looks like xml module don't have much options and throwing many errors. Is there any other library...
-1
2016-05-27T14:24:17Z
37,562,405
<p>Third party libraries exist to make your life easier. Yes, of course you could write a program without them (the authors of the libraries had to). However, why reinvent the wheel?</p> <p>Your best options are beautifulsoup and scrappy. However, if your having trouble with beautifulsoup, I wouldn't try scrappy. </p>...
0
2016-06-01T07:43:20Z
[ "python", "xml-parsing", "web-scraping", "beautifulsoup", "html-parsing" ]
Why do I get Permision Denied?
37,485,953
<pre><code>from ipaddress import * from socket import * x = str(IPv4Address('125.67.8.0')) s = socket() s.bind((x,456)) </code></pre> <p>Traceback (most recent call last):</p> <pre><code> File "&lt;stdin&gt;", line 1, in &lt;module&gt; OSError: [Errno 99] Cannot assign requested address </code></pre> <p>even afte...
-1
2016-05-27T14:25:03Z
37,486,802
<p>When you are using the bind command, the parameter for the IP is a string, so a simple <code>s.bind(('125.67.8.0', 456))</code>will work. You don't have to take the IP, as a string, and perform operations on it to turn it back into a string.</p>
0
2016-05-27T15:06:54Z
[ "python", "sockets", "networking" ]
how to put text btween html tag with python webdriver
37,485,974
<p>How to put text between html tag with python WebDriver?</p> <pre><code>&lt;!--html cod--&gt; &lt;span class="py"&gt;&lt;/span&gt; &lt;!--I want to put text between span tag with python WebDriver like this--&gt; &lt;span class="py"&gt;text&lt;/span&gt; </code></pre>
1
2016-05-27T14:26:14Z
37,577,490
<p>You can use selenium to get the element right before you want to add the text, then use javascript to insert the text immediately after the end of that element.</p> <p>For example:</p> <pre><code>node = driver.find_element_by_xpath("//span[@class='py']") script = "arguments[0].insertAdjacentHTML('afterEnd', argume...
0
2016-06-01T19:45:08Z
[ "python", "html", "python-2.7", "python-3.x", "selenium-webdriver" ]
call selenium test with parameters from another python file
37,486,014
<p>I have a selenium test as shown below.I would like to call this test from another python file with additional parameters passed into test. </p> <pre><code>from selenium import webdriver import unittest, time, re class Mytest(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() ...
0
2016-05-27T14:27:40Z
37,521,887
<p>Here is the tutorial, how to create TestCase with parameter: <a href="http://eli.thegreenplace.net/2014/04/02/dynamically-generating-python-test-cases" rel="nofollow">Dynamically generating Python test cases</a>. Here is a answer, how to call a TestCase from other file: <a href="http://stackoverflow.com/questions/15...
0
2016-05-30T09:15:17Z
[ "python", "selenium" ]
Python legend labels as expression
37,486,127
<p>I'm trying to plot 9 lines, each of which belongs to 1 of 3 categories, and I want to show a legend with just 3 labels instead of 9. Right now my code looks like</p> <pre><code>tau = np.array([.1, .2, .3]) num_repeats = 3 plot_colors = ['r-','b-','k-'] labels = ['tau = 0.1','tau = 0.2','tau = 0.3'] plot_handles=[No...
0
2016-05-27T14:32:34Z
37,487,668
<p>One trick to achieve this is to only set a label for one plot in the inner loop. In the following code, <code>label</code> is only non-empty if <code>ell==0</code>:</p> <pre><code>tau = np.array([.1, .2, .3]) num_repeats = 3 plot_colors = ['r-','b-','k-'] labels = ['tau = 0.1','tau = 0.2','tau = 0.3'] plot_handles=...
1
2016-05-27T15:49:20Z
[ "python", "list", "matplotlib", "legend" ]
Python: EOF error in pickle.load
37,486,262
<p>I am following a tutorial and writing a code to store and retrieve cookies using pickle</p> <pre><code>import requests import pickle def save_cookies(cookies, filename): with open(filename, 'wb') as f: pickle.dump(cookies, f) def load_cookies(filename): with open(filename, 'rb') as ...
0
2016-05-27T14:38:56Z
37,486,761
<p>From the looks of it your <code>cookie_store.dat</code> file is currently empty, because you are trying to load prior to saving the cookies on the following lines: </p> <pre><code>r = requests.post(url, data, cookies=load_cookies('cookie_store.dat')) save_cookies(r.cookies, 'cookie_store.dat') </code></pre>
0
2016-05-27T15:04:53Z
[ "python", "pickle" ]
Beautifulsoup - use "find_all" and store all text found in one variable? (number of instances unknown)
37,486,295
<p>I'm hoping to scrape the genre information of a list of movies. However, the movies are listed with different numbers of genres: some have one, others have three, etc.</p> <p>If all the movies had <em>n</em> genres, I could easily use a loop to locate all the text and string them together. But given that the number...
-1
2016-05-27T14:40:27Z
37,488,245
<p>You can obtain an iterable of genres for each movie, by doing something like this:</p> <pre><code>dsoup = BeautifulSoup(d.content, "lxml") all_genres = [] for div in dsoup.find_all("div", {"id": "info"}): genres = (genre.string for genre in div.find_all("span", {"property": "v:genre"})) all_genres.append(ge...
-1
2016-05-27T16:22:09Z
[ "python", "python-2.7", "beautifulsoup", "findall" ]
How to select min record by user in a Pandas data frame while accounting for multiple matches when you only want one
37,486,335
<p>I have a <code>pandas DataFrame</code> that looks like this:</p> <pre><code> record_date userid id priority 1 2016-05-27 02:00:39.600 1rhNGfQjU6 2718376 3 2 2016-05-27 02:00:39.600 EveMoYR1gs 2718377 3 3 2016-05-27 02:00:39.600 iVYGQgU3bX 2718378 3 4 2...
1
2016-05-27T14:42:00Z
37,486,597
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> by column <code>userid</code> and date of <code>datetime</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.date.html" rel="nofollow"><...
1
2016-05-27T14:56:22Z
[ "python", "pandas" ]
click.Choice for multiple arguments
37,486,367
<p>So what I want to achieve is to both assure that the arguments are part of certain predefined set (here tool1, tool2, tool3), like with <code>@click.option</code> and <code>type=click.Choice()</code>, and at the same time to be able to pass multiple arguments like with <code>@click.argument</code> with <code>nargs=-...
1
2016-05-27T14:43:29Z
37,623,873
<p>As it turns out I misunderstood the usage of <code>multiple=True</code> when using <code>@click.option</code>. </p> <p>For example is it possible to invoke <code>-t</code> multiple times </p> <pre><code>python selectTools.py -t tool1 -t tool3 -t tool2 </code></pre> <p>by using </p> <pre><code>@click.option('--to...
0
2016-06-03T21:41:06Z
[ "python", "python-click" ]
Python: Access argument while ArgParsing
37,486,436
<p>I'm trying to parse the arguments passed to a script and execute functionality on the fly</p> <pre><code>#!/usr/bin/python import sys from argparse import ArgumentParser def method_a(sometext): print 'a -- {0}'.format(sometext) def method_b(sometext): print 'b -- {0}'.format(sometext) parser = Argume...
0
2016-05-27T14:47:00Z
37,488,084
<p>The parser instance itself doesn't hold the parsed arguments, as it is a description of what the expected arguments are and how to parse them. The return value from calling <strong>parse_args</strong> holds them. A quick way to get what you want would be:</p> <pre><code>... option_group.add_argument('-a', ...
1
2016-05-27T16:12:01Z
[ "python", "arguments" ]
why does pandas rolling use single dimension ndarray
37,486,502
<p>I was motivated to use pandas <code>rolling</code> feature to perform a rolling multi-factor regression (This question is <strong>NOT</strong> about rolling multi-factor regression). I expected that I'd be able to use <code>apply</code> after a <code>df.rolling(2)</code> and take the resulting <code>pd.DataFrame</c...
3
2016-05-27T14:50:30Z
37,491,779
<p>I wanted to share what I've done to work around this problem.</p> <p>Given a <code>pd.DataFrame</code> and a window, I generate a stacked <code>ndarray</code> using <code>np.dstack</code> (<a href="http://stackoverflow.com/a/37448165/2336654"><strong>see answer</strong></a>). I then convert it to a <code>pd.Panel<...
2
2016-05-27T20:30:24Z
[ "python", "numpy", "pandas" ]
problems installing scipy and pybrain in python 3.5.1
37,486,551
<p>it's my first post here, however i have used this site as a guest through google searches. to the point now. i am learning python and i want to install scipy and pybrain. i have python 3.5.1 installed in the following path</p> <blockquote> <p>C:\Program Files\Python35-32</p> </blockquote> <p>When i use <code>pip...
0
2016-05-27T14:53:03Z
37,486,610
<p>If you're beginning I suggest you to install one of the distributions linked on Scipy website : <a href="https://www.scipy.org/install.html" rel="nofollow">https://www.scipy.org/install.html</a></p> <p>I use Anaconda : it provides Spyder and multiple libraries to help you start with.</p> <p>About your problem, you...
1
2016-05-27T14:56:58Z
[ "python", "windows", "python-3.x" ]
problems installing scipy and pybrain in python 3.5.1
37,486,551
<p>it's my first post here, however i have used this site as a guest through google searches. to the point now. i am learning python and i want to install scipy and pybrain. i have python 3.5.1 installed in the following path</p> <blockquote> <p>C:\Program Files\Python35-32</p> </blockquote> <p>When i use <code>pip...
0
2016-05-27T14:53:03Z
37,487,571
<p>@ Pierre-Louis Sauvage, @ geo: anaconda is useful, yet it is also a fairly heavy application, with about 300MB memory needed. You may therefore want to consider miniconda first. Since you're learning Python, that will most likely be sufficient.</p> <p>So, I write this in 'answer' format instead of comment, since I ...
0
2016-05-27T15:44:26Z
[ "python", "windows", "python-3.x" ]
Packaging Kivy into exe file (without command)
37,486,807
<p>How can I package my python <strong>Kivy</strong> project into an executable <strong>exe</strong> file, <strong>without</strong> using commands explained in <a href="https://kivy.org/docs/guide/packaging-windows.html" rel="nofollow">https://kivy.org/docs/guide/packaging-windows.html</a> page.</p> <p>Thanks for the ...
-1
2016-05-27T15:07:18Z
37,486,942
<p>You could try to use any of the python executable packagers, such as nuitka or cx_freeze. We suggest (and give instructions for) pyinstaller because we've found it the most flexible and practical, though. Note that packaging Kivy involves extra steps beyond simple python scripts because of the compilation and extern...
1
2016-05-27T15:13:00Z
[ "python", "windows", "exe", "kivy", "packaging" ]
Packaging Kivy into exe file (without command)
37,486,807
<p>How can I package my python <strong>Kivy</strong> project into an executable <strong>exe</strong> file, <strong>without</strong> using commands explained in <a href="https://kivy.org/docs/guide/packaging-windows.html" rel="nofollow">https://kivy.org/docs/guide/packaging-windows.html</a> page.</p> <p>Thanks for the ...
-1
2016-05-27T15:07:18Z
37,493,933
<p>Your problem is that you don't want to use commands at all, or that you don't want to use only the commands explained in docs? If it's the first one, well... as a programmer you'll someday find out that this is still one of the pretty packagers. If the second one, there are many other packagers as inclement said.</p...
0
2016-05-28T00:10:04Z
[ "python", "windows", "exe", "kivy", "packaging" ]
Set a variable to a random element from an array and not the elements value. ---python---
37,486,839
<p>This is for a text-based card game.</p> <p>I have been trying to get python to randomly select a variable from a array and store the name of the variable in <code>Fa</code>. However it only stores the value of the variable <code>Fa</code> and not the name of the variable.</p> <p>My code:</p> <pre><code> import ra...
0
2016-05-27T15:09:17Z
37,487,287
<p>The issue is with your data structures: <code>clubs=[A1,B1,C1,D1,E1,F1,G1,H1,I1,J1,K1,L1,M1]</code> will only have the values of your variables within your arrays. If you want to also have the variable name, I would suggest changing it to a <code>dict</code> and having the <code>key</code> be the variable name. Exa...
0
2016-05-27T15:29:20Z
[ "python", "arrays", "variable-names" ]
Set a variable to a random element from an array and not the elements value. ---python---
37,486,839
<p>This is for a text-based card game.</p> <p>I have been trying to get python to randomly select a variable from a array and store the name of the variable in <code>Fa</code>. However it only stores the value of the variable <code>Fa</code> and not the name of the variable.</p> <p>My code:</p> <pre><code> import ra...
0
2016-05-27T15:09:17Z
37,487,290
<h1>If I understood clearly, then make use of dictionary.</h1> <h1>Copy code from my example:</h1> <pre><code>import random dic = {'k' : 'king', 'q' : 'queen'} dic_keys = list(dic.keys()) which = random.choice(dic_keys) selected_v = which selected_v_v = dic[selected_v] print(selected_v, selected_v_v) </code></pr...
0
2016-05-27T15:29:33Z
[ "python", "arrays", "variable-names" ]
Set a variable to a random element from an array and not the elements value. ---python---
37,486,839
<p>This is for a text-based card game.</p> <p>I have been trying to get python to randomly select a variable from a array and store the name of the variable in <code>Fa</code>. However it only stores the value of the variable <code>Fa</code> and not the name of the variable.</p> <p>My code:</p> <pre><code> import ra...
0
2016-05-27T15:09:17Z
37,487,779
<p>You need to realize that python does not pass "variable names" when you create a list.</p> <p>By doing:</p> <pre><code>spades=[A,B,C,D,E,F,G,H,I,J,K,L,M] </code></pre> <p>the list only consists of the values that those variables pointed to, you can see this by just printing out the list:</p> <pre><code>&gt;&gt;&...
0
2016-05-27T15:55:26Z
[ "python", "arrays", "variable-names" ]
Pivot String column on Pyspark Dataframe
37,486,910
<p>I have a simple dataframe like this:</p> <pre><code>rdd = sc.parallelize( [ (0, "A", 223,"201603", "PORT"), (0, "A", 22,"201602", "PORT"), (0, "A", 422,"201601", "DOCK"), (1,"B", 3213,"201602", "DOCK"), (1,"B", 3213,"201601", "PORT"), (2,"C", 2321,"201601", "...
1
2016-05-27T15:11:53Z
37,487,099
<p>Assuming that <code>(id |type | date)</code> combinations are unique and your only goal is pivoting and not aggregation you can use <code>first</code> (or any other function not restricted to numeric values):</p> <pre><code>from pyspark.sql.functions import first (df_data .groupby(df_data.id, df_data.type) ...
1
2016-05-27T15:20:07Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql" ]
Remove a tuple containing nan in list of tuples -- Python
37,486,938
<p>I have a long list of tuples and want to remove any tuple that has a nan in it using Python. </p> <p>What I currently have: x = [('Recording start', 0), (nan, 4), (nan, 7), ..., ('Event marker 1', 150)] </p> <p>Result I'm looking for: x = [('Recording start', 0), ('Event marker 1', 150)]</p> <p>I've tried u...
0
2016-05-27T15:12:51Z
37,486,983
<pre><code>res = [n for n in x if not nan in n] </code></pre> <p>Return all objects in <code>x</code> that do not have an objects <code>nan</code> in them.</p>
0
2016-05-27T15:14:55Z
[ "python", "list", "tuples", null, "spyder" ]
Remove a tuple containing nan in list of tuples -- Python
37,486,938
<p>I have a long list of tuples and want to remove any tuple that has a nan in it using Python. </p> <p>What I currently have: x = [('Recording start', 0), (nan, 4), (nan, 7), ..., ('Event marker 1', 150)] </p> <p>Result I'm looking for: x = [('Recording start', 0), ('Event marker 1', 150)]</p> <p>I've tried u...
0
2016-05-27T15:12:51Z
37,487,031
<p>Using list comprehension:</p> <pre><code>x = [('Recording start', 0), (nan, 4), (nan, 7), ('Event marker 1', 150)] new = [i for i in x if nan not in i] </code></pre>
1
2016-05-27T15:16:53Z
[ "python", "list", "tuples", null, "spyder" ]
Remove a tuple containing nan in list of tuples -- Python
37,486,938
<p>I have a long list of tuples and want to remove any tuple that has a nan in it using Python. </p> <p>What I currently have: x = [('Recording start', 0), (nan, 4), (nan, 7), ..., ('Event marker 1', 150)] </p> <p>Result I'm looking for: x = [('Recording start', 0), ('Event marker 1', 150)]</p> <p>I've tried u...
0
2016-05-27T15:12:51Z
37,487,220
<p>You could use list comprehension which checks if any of the items in a tuple is NaN. Check is done by first checking the type and then with <a href="https://docs.python.org/2/library/math.html#math.isnan" rel="nofollow"><code>math.isnan</code></a> since it doesn't work for other types:</p> <pre><code>import math x...
2
2016-05-27T15:26:14Z
[ "python", "list", "tuples", null, "spyder" ]
Remove a tuple containing nan in list of tuples -- Python
37,486,938
<p>I have a long list of tuples and want to remove any tuple that has a nan in it using Python. </p> <p>What I currently have: x = [('Recording start', 0), (nan, 4), (nan, 7), ..., ('Event marker 1', 150)] </p> <p>Result I'm looking for: x = [('Recording start', 0), ('Event marker 1', 150)]</p> <p>I've tried u...
0
2016-05-27T15:12:51Z
37,487,329
<p>At least at my python usage of nan retured the 'not defined error', this is why I defined it by my self. I think you can use a Python filter function for yor needs. See the example:</p> <pre><code>nan = float('nan') lst = [('Recording start', 0), (nan, 4), (nan, 7), ('Event marker 1', 150)] y = filter( lambda x: na...
0
2016-05-27T15:31:54Z
[ "python", "list", "tuples", null, "spyder" ]
Ansible setup module fails
37,486,939
<p>I have a lot of hosts managing by ansible and on the one hosts setup module fails:</p> <pre><code>user@Work:~ &gt;&gt; ansible -vvvv -i "10.10.10.2," all -m setup [20:00:24] Using /etc/ansible/ansible.cfg as config file Loaded callbac...
1
2016-05-27T15:12:52Z
37,487,610
<p>It worked with -become param: ansible -i "10.10.10.2," all -m 'setup' -become</p> <p>but on the other host it works without this param</p>
0
2016-05-27T15:46:31Z
[ "python", "ubuntu", "ansible" ]
Checking Servers with Motor(Mongodb & Tornado)
37,487,025
<p>I need to create a function that checks to make sure Mongo servers are running using the ping function. I set up the clients right there (the config file has dictionary with ports numbers)</p> <pre><code> clientList = [] for value in configuration["mongodbServer"]: client = motor.motor_tornado.MotorClient('mo...
1
2016-05-27T15:16:47Z
37,488,184
<p>First, there's no "ping" function. Hence MotorClient thinks you're trying to access the database named "ping". The database named "ping" is shown in the "unknown object" exception. For all MongoDB commands like "ping", just use MotorDatabase's <a href="http://motor.readthedocs.io/en/stable/api/motor_database.html#mo...
2
2016-05-27T16:18:26Z
[ "python", "mongodb", "tornado", "pymongo", "tornado-motor" ]
Pandas: multiple bar plot from aggregated columns
37,487,067
<p>In python pandas I have create a dataframe with one value for each year and two subclasses - i.e., one metric for a parameter triplet</p> <pre><code>import pandas, requests, numpy import matplotlib.pyplot as plt df Metric Tag_1 Tag_2 year 0 5770832 FOOBAR1 name1 2008 1 7526436 FOOBAR1 x...
3
2016-05-27T15:18:49Z
37,488,781
<p>This should get you on your way:</p> <pre><code>df = pd.read_csv('path_to_file.csv') # Group by the desired columns new_df = df.groupby(['year', 'Tag_1', 'Tag_2']).sum() # Sort descending new_df.sort('Metric', inplace=True) # Helper function for generation sequence of 'r' 'b' colors def get_color(i): if i%2 ...
1
2016-05-27T16:56:51Z
[ "python", "pandas", "matplotlib", "dataframe" ]
Pandas: multiple bar plot from aggregated columns
37,487,067
<p>In python pandas I have create a dataframe with one value for each year and two subclasses - i.e., one metric for a parameter triplet</p> <pre><code>import pandas, requests, numpy import matplotlib.pyplot as plt df Metric Tag_1 Tag_2 year 0 5770832 FOOBAR1 name1 2008 1 7526436 FOOBAR1 x...
3
2016-05-27T15:18:49Z
37,491,536
<p>you can also do it this way:</p> <pre><code>fig, ax = plt.subplots() df.groupby(['year', 'Tag_1', 'Tag_2']).sum().plot.barh(color=['r','b'], ax=ax) fig.tight_layout() plt.show() </code></pre> <p>PS if don't like scientific notation you can get rid of it:</p> <pre><code>ax.get_xaxis().get_major_formatter().set_sci...
0
2016-05-27T20:10:06Z
[ "python", "pandas", "matplotlib", "dataframe" ]
how to get a list of questions posted by followed users
37,487,078
<p>Friends, I am trying to implement a question answer site in which a logged in user gets a list of questions and answers asked by the users he follows. I am using django-friendship to implement user follows. I want to know how we can fetch all the questions posted by the users whom the current user follows.</p> <p>I...
0
2016-05-27T15:19:18Z
37,487,592
<p><code>posts</code> is a queryset. Thus, <code>questions</code> is a list of querysets and, in your template, you are not iterating over <code>Question</code> instances, but querysets that do NOT have a <code>title</code> attribute. You can try in your view:</p> <pre><code>questions.extend(posts) # not: append </co...
0
2016-05-27T15:45:19Z
[ "python", "django" ]
how to get a list of questions posted by followed users
37,487,078
<p>Friends, I am trying to implement a question answer site in which a logged in user gets a list of questions and answers asked by the users he follows. I am using django-friendship to implement user follows. I want to know how we can fetch all the questions posted by the users whom the current user follows.</p> <p>I...
0
2016-05-27T15:19:18Z
37,487,800
<p>You can fetch all questions without looping</p> <p>views.py </p> <pre><code>def index(request): if request.session.get('current_user'): users = Follow.objects.following(request.user) questions = Question.objects.filter(user__in=users) return render(request, "welcome/index.html",locals()...
0
2016-05-27T15:56:28Z
[ "python", "django" ]
python decorator above something other than def
37,487,129
<p>The usual construct for a decorator in python is</p> <pre><code>@decorator def function(x): &lt;code here&gt; </code></pre> <p>which is equivalent to</p> <pre><code>def function(x): &lt;code here&gt; function = decorator(function) </code></pre> <p>(At least, this is my understanding.) Now suppose we are ...
0
2016-05-27T15:21:53Z
37,487,168
<p>The answer is no, the <code>@</code> syntax cannot be used with arbitrary lines, you need to use <code>mystery_func = decorator(mystery_func)</code>. Using the <code>@</code> syntax like this is a <code>SyntaxError</code>.</p>
1
2016-05-27T15:23:52Z
[ "python", "decorator", "python-decorators" ]
python decorator above something other than def
37,487,129
<p>The usual construct for a decorator in python is</p> <pre><code>@decorator def function(x): &lt;code here&gt; </code></pre> <p>which is equivalent to</p> <pre><code>def function(x): &lt;code here&gt; function = decorator(function) </code></pre> <p>(At least, this is my understanding.) Now suppose we are ...
0
2016-05-27T15:21:53Z
37,488,040
<p>You can also use <a href="https://www.python.org/dev/peps/pep-3129/" rel="nofollow">class decorators</a> which is "something other than def":</p> <p>eg.</p> <pre><code>@foo @bar class A: pass </code></pre> <p>But what you mentioned here:</p> <pre><code>@decorator mystery_func </code></pre> <p>is a <code>Synta...
0
2016-05-27T16:09:35Z
[ "python", "decorator", "python-decorators" ]
python setuptools: "No module named version"
37,487,202
<p>I'm trying to install a package using <code>python setup.py build</code>, but it fails when it cannot find <code>setuptools.version</code>. In fact:</p> <pre><code>import setuptools Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/gpajer/anaconda/lib/python2.7/sit...
0
2016-05-27T15:25:28Z
37,487,334
<p>From <a href="https://anaconda.org/anaconda/setuptools" rel="nofollow">https://anaconda.org/anaconda/setuptools</a>:</p> <blockquote> <p>To install this package with conda run:</p> </blockquote> <pre><code>conda install -c anaconda setuptools=21.2.1 </code></pre>
0
2016-05-27T15:32:19Z
[ "python", "python-2.7", "setuptools" ]
How to update yaml file using python?
37,487,250
<p>I am newbie to python and YAML, I have an situation where I need to keep this file, appended with relevant data</p> <pre><code>__blocks: {} messages: CANMessages: - CAN: !!python/unicode 'IuK-CAN' D0: - 13 D1: - 0 ...
1
2016-05-27T15:27:31Z
37,489,161
<p>You open the output file for appending (<code>open(fileMock, 'a')</code>) and every time write the whole datastructure. You should probably not be using <code>a</code> at all on a YAML file, unless you want to have multiple documents in the file.</p> <p>Append all the elements to the data structure <code>data</code...
0
2016-05-27T17:21:26Z
[ "python", "yaml", "pyyaml" ]
Scrap all tables from div using BeautifulSoup
37,487,276
<p>I needed to extract the <code>&lt;tr&gt;</code> tags from all tables in the <code>&lt;div id="specs-list"&gt;</code>. However it is just fetches only the top six tables. Here is the <a href="http://www.gsmarena.com/lenovo_k3_note-7147.php" rel="nofollow">page</a>. Here is my code. </p> <pre><code>def getPhoneStats(...
0
2016-05-27T15:28:50Z
37,487,986
<p>The HTML is malformed. THe "Memory" table has too many /td and /tr tags at the end. I think that is messing with the parser. I had better luck skipping the div and looking directly for the tables:</p> <pre><code>from bs4 import BeautifulSoup import requests def getPhoneStats(url): try: request= reque...
2
2016-05-27T16:06:46Z
[ "python", "html", "web-scraping", "beautifulsoup" ]
Scrap all tables from div using BeautifulSoup
37,487,276
<p>I needed to extract the <code>&lt;tr&gt;</code> tags from all tables in the <code>&lt;div id="specs-list"&gt;</code>. However it is just fetches only the top six tables. Here is the <a href="http://www.gsmarena.com/lenovo_k3_note-7147.php" rel="nofollow">page</a>. Here is my code. </p> <pre><code>def getPhoneStats(...
0
2016-05-27T15:28:50Z
37,488,016
<p>It's an issue with the html parser. I prefer using the html5lib, but it's slower, so if speed is important, one of the C based parsers may be better (read more <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser" rel="nofollow">here</a>)</p> <p>I just changed <code>sourceCode = Beau...
2
2016-05-27T16:08:16Z
[ "python", "html", "web-scraping", "beautifulsoup" ]
Django REST Framework ModelSerializer - Object not saved
37,487,346
<p>I've a model, and one of it's field refers to an overrided User instance (changed in Django settings).</p> <p>When I'm performing a POST from my client, the route ends up here at the <code>create</code> method:</p> <pre><code>class CatView(ModelViewSet): authentication_classes = (authentication.TokenAuthentica...
1
2016-05-27T15:33:01Z
37,487,985
<p>You seem to be overriding both <code>create</code> and <code>perform_create</code>. If you look at the code for <a href="https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py" rel="nofollow">CreateModelMixin</a> which the <code>ModelViewSet</code> inherits from you will notice tha...
2
2016-05-27T16:06:37Z
[ "python", "django", "django-rest-framework" ]
How to use a custom predicate sort with Python
37,487,406
<p>I have a list of lists like <code>[[1,2,"s"],[1,5,"e"],...]</code> where the 3rd value is always either <code>s</code> or <code>e</code>. How can I call <code>sort()</code> such that the list is sorted based on:</p> <ol> <li>the first index</li> <li>if the first index is same, <code>s</code> comes first.</li> </ol>...
-1
2016-05-27T15:36:23Z
37,487,539
<p>You can pass custom key function to <a href="https://docs.python.org/3/library/stdtypes.html#list.sort" rel="nofollow"><code>list.sort</code></a> that is used to generate the comparison key for the items:</p> <pre><code>&gt;&gt;&gt; l = [[1, 5, 'e'], [1, 2, 's'], [0, 4, 'e']] &gt;&gt;&gt; l.sort(key=lambda x: (x[0]...
2
2016-05-27T15:42:19Z
[ "python", "sorting", "python-3.x" ]
How to use a custom predicate sort with Python
37,487,406
<p>I have a list of lists like <code>[[1,2,"s"],[1,5,"e"],...]</code> where the 3rd value is always either <code>s</code> or <code>e</code>. How can I call <code>sort()</code> such that the list is sorted based on:</p> <ol> <li>the first index</li> <li>if the first index is same, <code>s</code> comes first.</li> </ol>...
-1
2016-05-27T15:36:23Z
37,487,543
<p>Write a custom <code>key</code> function.</p> <pre><code>def sort_key(list_): if list_[2] == 's': return (list_[0], 0) return (list_[0], 1) test_list = [[1, 2, 's'], [1, 5, 'e'], [2, 4, 'e'], [2, 3, 's']] test_list.sort(key=sort_key) # [[1, 2, 's'], [1, 5, 'e'], [2, 3, 's'], [2, 4, 'e']] </code></p...
1
2016-05-27T15:42:44Z
[ "python", "sorting", "python-3.x" ]
matplotlib graph for IMDB Voting vs Rating
37,487,455
<p>Plotting a graph between the voting and ratings for movies from IMDB data, What is the best way to show "Weighted Rank" Voting vs Rating Graph with the help of Pandas and Matplotlib. </p> <p>Tried this so far but doesn't appears in correct format, even the x-axis text is overlapping each other. Any help much apprec...
1
2016-05-27T15:38:26Z
37,489,364
<p>You could do</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set_style('darkgrid') df = pd.DataFrame(np.random.randint(100000, size=(10000, 2)), columns=['Votes', 'Rating']) df.plot(kind='scatter', x='Votes', y='Rating', logx=True,...
1
2016-05-27T17:35:48Z
[ "python", "pandas", "matplotlib", "data-science" ]
computing the weight of each LDA topic in the corpus
37,487,504
<p>I computed my LDA model, I retrieved my topics and now I am looking for the way to compute the weight/percentage of each topic on the corpus. Surprisingly I cannot find the way to do this, so far my code looks like:</p> <pre><code>## Libraries to download from nltk.tokenize import RegexpTokenizer from nltk.corpus i...
-1
2016-05-27T15:40:47Z
37,530,523
<p>You need to state a minimum probability to zero in the lda function:</p> <pre><code>ldamodel = gensim.models.ldamodel.LdaModel(corpus, num_topics=15, id2word = dictionary, passes=50, minimum_probability=0) </code></pre> <p>Moreover, you can just get the topic-distribution for all articles by:</p> <pre><code>for i...
2
2016-05-30T16:52:38Z
[ "python", "lda", "gensim", "corpus" ]
Strange Result from FFT using Scipy
37,487,532
<p>I'm trying to do an FFT of some data (a Gaussian pulse), but I'm finding a strange result. The real and imaginary components of the resultant FFT alternate in sign every index of the array. The absolute values of the arrays, however, are continuous. So, I get something that looks like this:</p> <p><img src="http://...
2
2016-05-27T15:41:59Z
37,488,261
<p>Alternating signs in the frequency domain corresponds to an <code>exp(j*pi*n)</code> complex factor which by the <a href="https://en.wikipedia.org/wiki/Discrete_Fourier_transform#Shift_theorem" rel="nofollow">shift theorem</a> corresponds to a time domain circular shift of <code>N/2</code> samples. Looking at your t...
4
2016-05-27T16:23:23Z
[ "python", "scipy", "fft" ]
How Can I Get RegEx Groups From Python re Without Matching?
37,487,655
<p>If I compile a regex such as:</p> <pre><code>pat = re.compile("/resource/([a-z]*)/") </code></pre> <p>Is it possible to get matching components of this pattern (e.g., "/resource/", "([a-z]*)", "/") or some equivalent without executing <em>match</em>, <em>search</em>, or some other regex call? I want to know how th...
2
2016-05-27T15:48:52Z
37,488,025
<p>Use <a href="https://regex101.com" rel="nofollow">regex101's</a> debugger feature. You can see how your regex failed or succeeded step-by-step.</p> <p>Example:</p> <p><a href="http://i.stack.imgur.com/awSzG.png" rel="nofollow"><img src="http://i.stack.imgur.com/awSzG.png" alt="enter image description here"></a></p...
2
2016-05-27T16:08:36Z
[ "python", "regex", "python-2.7" ]
How to add an id to filename before extension?
37,487,758
<p>I have a filename: name.ext </p> <p>I want to do the following:</p> <pre><code>name + id + '.' + ext for name, ext in filename.split() </code></pre> <p>or find a better way to take a filename and add a random 7 character string to the end before the extension.</p> <p>Here is what I have so far:</p> <pre><code>d...
1
2016-05-27T15:54:18Z
37,487,898
<p>To do it in one line you can try:</p> <pre><code>def append_it(filename): return "{0}_{2}.{1}".format(*filename.rsplit('.', 1) + [generate_id()]) </code></pre> <p>It's not very readable though.</p>
2
2016-05-27T16:02:43Z
[ "python" ]
How to add an id to filename before extension?
37,487,758
<p>I have a filename: name.ext </p> <p>I want to do the following:</p> <pre><code>name + id + '.' + ext for name, ext in filename.split() </code></pre> <p>or find a better way to take a filename and add a random 7 character string to the end before the extension.</p> <p>Here is what I have so far:</p> <pre><code>d...
1
2016-05-27T15:54:18Z
37,487,933
<p>your one line answer with the random generation - </p> <p><code>map(lambda x :x.split(".")[0] + "_" + hashlib.md5(("%.15f" % time.time())+"_"+''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(5))).hexdigest()[:7]+"."+x.split(".")[1], filenames)</code></p> <p>here you can input <code>file...
2
2016-05-27T16:04:04Z
[ "python" ]
How to add an id to filename before extension?
37,487,758
<p>I have a filename: name.ext </p> <p>I want to do the following:</p> <pre><code>name + id + '.' + ext for name, ext in filename.split() </code></pre> <p>or find a better way to take a filename and add a random 7 character string to the end before the extension.</p> <p>Here is what I have so far:</p> <pre><code>d...
1
2016-05-27T15:54:18Z
37,487,996
<p>To fix your generate_id code, you need a list comprehension.</p> <pre><code>def generate_id(size=7, chars=string.ascii_uppercase + string.digits): return '_' + ''.join([random.choice(chars) for _ in range(size)]) </code></pre> <p>Are you using python just to rename files? You can use a command line program lik...
2
2016-05-27T16:07:18Z
[ "python" ]
How to add an id to filename before extension?
37,487,758
<p>I have a filename: name.ext </p> <p>I want to do the following:</p> <pre><code>name + id + '.' + ext for name, ext in filename.split() </code></pre> <p>or find a better way to take a filename and add a random 7 character string to the end before the extension.</p> <p>Here is what I have so far:</p> <pre><code>d...
1
2016-05-27T15:54:18Z
37,488,031
<pre><code>def append_id(filename): parts = filename.split('.') return "".join(parts[:-1])+ '_' + generate_id() + '.' + parts[-1] </code></pre>
2
2016-05-27T16:08:47Z
[ "python" ]
How to add an id to filename before extension?
37,487,758
<p>I have a filename: name.ext </p> <p>I want to do the following:</p> <pre><code>name + id + '.' + ext for name, ext in filename.split() </code></pre> <p>or find a better way to take a filename and add a random 7 character string to the end before the extension.</p> <p>Here is what I have so far:</p> <pre><code>d...
1
2016-05-27T15:54:18Z
37,488,134
<p>I'd suggest something plain and simple - use <a href="https://docs.python.org/2/library/os.path.html#os.path.splitext"><code>os.path.splitext</code></a> to retrieve basename and extension, and after that simple merge all result components via <a href="https://docs.python.org/2/library/stdtypes.html#str.format"><code...
5
2016-05-27T16:15:28Z
[ "python" ]
iPython:Using Pandas, How do I combine multiple text files to find reacurring usernames?
37,487,829
<p>I'm using pandas to count recurring usernames from 2 different large text files. How do I get my code to analyze the data from both files at the same time? Right now I have only been able to run one text file so nothing is occurring more than once. </p> <p>Here is my Code:</p> <pre><code>import pandas as pd fixed...
1
2016-05-27T15:58:31Z
37,488,112
<p>Combine files like this</p> <pre><code>fixed_df1 = pd.read_csv('sample1.txt', sep=';', encoding='latin1') fixed_df2 = pd.read_csv('sample2.txt', sep=';', encoding='latin1') fixed_df = pd.concat([fixed_df1, fixed_df2]) </code></pre>
1
2016-05-27T16:14:03Z
[ "python", "python-3.x", "pandas" ]
How to find probability distribution and parameters for real data? (Python 3)
37,487,830
<p>I have a dataset from <code>sklearn</code> and I plotted the distribution of the <code>load_diabetes.target</code> data (i.e. the values of the regression that the <code>load_diabetes.data</code> are used to predict). </p> <p><em>I used this because it has the fewest number of variables/attributes of the regression...
11
2016-05-27T15:58:31Z
37,570,540
<p>To the best of my knowledge, there is no automatic way of obtaining the distribution type and parameters of a sample (as <em>inferring</em> the distribution of a sample is a statistical problem by itself).</p> <p>In my opinion, the best you can do is:</p> <p>(for each attribute)</p> <ul> <li><p>Try to fit each at...
3
2016-06-01T13:44:19Z
[ "python", "machine-learning", "statistics", "distribution", "data-fitting" ]
How to find probability distribution and parameters for real data? (Python 3)
37,487,830
<p>I have a dataset from <code>sklearn</code> and I plotted the distribution of the <code>load_diabetes.target</code> data (i.e. the values of the regression that the <code>load_diabetes.data</code> are used to predict). </p> <p><em>I used this because it has the fewest number of variables/attributes of the regression...
11
2016-05-27T15:58:31Z
37,647,101
<p>You can use that code to fit (according to the maximum likelihood) different distributions with your datas: </p> <pre><code>import matplotlib.pyplot as plt import scipy import scipy.stats dist_names = ['gamma', 'beta', 'rayleigh', 'norm', 'pareto'] for dist_name in dist_names: dist = getattr(scipy.stats, dist...
1
2016-06-05T21:47:15Z
[ "python", "machine-learning", "statistics", "distribution", "data-fitting" ]
Tensorflow Basics - Computing cumulative moving average
37,487,848
<p>I've just started with Tensorflow and wanted to know if the below code is right approach to compute cumulative rolling average</p> <pre><code>import tensorflow as tf import numpy as np x = tf.Variable(0, name = "x") x_pld = tf.placeholder(tf.int32) update_x = tf.assign(x, x_pld) curr_avg = tf.Variable(tf.constant...
1
2016-05-27T15:59:42Z
37,495,421
<pre><code>import numpy as np import tensorflow as tf # Set Variables # only need single placeholder because only feeding in one value to graph next_val = tf.placeholder(shape=(), dtype=tf.float32) cumulative = tf.Variable(0, dtype=tf.float32) divisor = tf.Variable(0, dtype=tf.float32) #Calculations cumulative = cum...
0
2016-05-28T05:08:53Z
[ "python", "tensorflow" ]
Python/Pycharm Ctrl+Space Suggestion List Does not show explanations
37,488,036
<p>In pycharm ide of python, ctrl+space shortcut is bringing available properties,methods etc.(auto completion also) but the list has no explanations. In other words, I see available options in the list but when i hower the mouse on them there is no explanation is coming so I have no idea what do these options stand fo...
0
2016-05-27T16:09:11Z
37,488,161
<p>Possibly you have to set the path to python environment, so it knows where your packages are and can look through them to tell you tips. Check this in PyCharm interpreter options</p>
1
2016-05-27T16:17:13Z
[ "python", "keyboard-shortcuts", "pycharm" ]
Python/Pycharm Ctrl+Space Suggestion List Does not show explanations
37,488,036
<p>In pycharm ide of python, ctrl+space shortcut is bringing available properties,methods etc.(auto completion also) but the list has no explanations. In other words, I see available options in the list but when i hower the mouse on them there is no explanation is coming so I have no idea what do these options stand fo...
0
2016-05-27T16:09:11Z
37,488,336
<p>After pressing <kbd>Control</kbd>+<kbd>Space</kbd> try <kbd>Control</kbd>+<kbd>Shift</kbd>+<kbd>I</kbd> to see definitions, and <kbd>Ctrl</kbd>+<kbd>Q</kbd> to see documentations. </p>
2
2016-05-27T16:27:58Z
[ "python", "keyboard-shortcuts", "pycharm" ]
Concatenate class variable through inheritance?
37,488,041
<p>I am trying to <strong>implicitly</strong> concatenate class variables through inheritance. I was able to go up one level but not more... It this actually possible?</p> <pre><code>class Base(object): def get_crumbs(self): crumbs = getattr(super(self.__class__, self), 'crumbs', ()) crumbs += geta...
1
2016-05-27T16:09:40Z
37,488,133
<p>You can loop over the <a href="https://docs.python.org/2/library/stdtypes.html#class.__mro__" rel="nofollow"><code>class.__mro__</code> tuple</a>:</p> <pre><code>class Base(object): def get_crumbs(self): crumbs = [] for cls in type(self).__mro__: crumbs.extend(getattr(cls, 'crumbs', ...
3
2016-05-27T16:15:23Z
[ "python", "inheritance" ]
Pandas and NumPy default width change on startup
37,488,043
<p>Is there a way to specify Pandas and NumPy display width on startup of an IPython shell. For example,</p> <pre><code># Run this at startup import numpy as np np.set_printoptions(linewidth=200) import pandas as pd pd.options.display.width = 200 </code></pre>
3
2016-05-27T16:09:45Z
37,488,445
<p>For Windows, for me, I have a startup directory:</p> <pre><code>'C:\Users\username\.ipython\profile_default\startup' </code></pre> <p>In this I create a file:</p> <pre><code>'00-script.py` </code></pre> <p>Files in this directory will be run in alphabetical order by name. I put '00' in front to ensure it gets ru...
3
2016-05-27T16:35:11Z
[ "python", "numpy", "pandas", "ipython" ]
Pandas and NumPy default width change on startup
37,488,043
<p>Is there a way to specify Pandas and NumPy display width on startup of an IPython shell. For example,</p> <pre><code># Run this at startup import numpy as np np.set_printoptions(linewidth=200) import pandas as pd pd.options.display.width = 200 </code></pre>
3
2016-05-27T16:09:45Z
37,489,295
<p>Just to add to the answer by @piRSquared, on Unix-based systems, you can do it by putting a startup script in <code>~/.ipython/profile_default/startup</code>:</p> <pre><code>$ cat ~/.ipython/profile_default/startup/load_pdnp.py import pandas as pd import numpy as np pd.options.display.width = 200 np.set_printopti...
1
2016-05-27T17:30:55Z
[ "python", "numpy", "pandas", "ipython" ]
Simplify database (psycopg2) usage by creating a module
37,488,175
<p>Let me preface this by saying that I am fairly new to Python and I apologize if this is not the appropriate place for this question.</p> <p>I am using the <strong>psycopg2</strong> module to manipulate a PostgreSQL database. The general usage would look something like this:</p> <pre><code># Example 1 import psyco...
1
2016-05-27T16:17:55Z
37,488,812
<p>Your main issue, is that each variable is limited to the function you wrote it in.<br> Unless otherwise declared like such:</p> <pre><code>def db_init(): global conn conn = psycopg2.... </code></pre> <p>A better approach would be to convert this into a class, a basic example would be:</p> <pre><code>impor...
0
2016-05-27T16:58:38Z
[ "python", "sql", "postgresql", "module", "psycopg2" ]