Unnamed: 0 int64 0 1.91M | id int64 337 73.8M | title stringlengths 10 150 | question stringlengths 21 64.2k | answer stringlengths 19 59.4k | tags stringlengths 5 112 | score int64 -10 17.3k |
|---|---|---|---|---|---|---|
8,700 | 17,912,259 | Pagination with appengine ndb Cursor - python : Same cursor is being generated leading to repeatition of output results | <p>I realised from my appengine log that the same cursor is being generated each time, the call to the Homehandler is made.
Please any idea what i am doing wrong, below is a snippet of my code:</p>
<pre><code>class HomeHandler(webapp2.RequestHandler):
def get(self):
#page=self.request.get("page", default_value="1"... | <p>It looks like you're using the <code>get()</code> method for both displaying a page and to handle an AJAX request. It's correctly generating a page with an initial cursor, but your <code>$.ajax()</code> method is expecting it to return JSON data.</p>
<p>Split the page request and AJAX request into two methods. Tr... | python|google-app-engine|google-cloud-datastore | 1 |
8,701 | 61,002,144 | Python Dash graph legend covering x-axis labels | <p>My Python web app has a Plotly Dash "Graph" whose legend covers the x-axis labels. I've tried adjusting the following elements, with no success and no visible changes at all:</p>
<ol>
<li>legend style 'margin-top'</li>
<li>margin 'b'</li>
<li>padding 'b'</li>
</ol>
<p>Here's the code:</p>
<pre><code> import da... | <p>I found the solution <a href="https://i.stack.imgur.com/dnBy6.png" rel="nofollow noreferrer">here</a> in the documentation. </p>
<blockquote>
<p>y
Parent: layout.legend
Type: number between or equal to -2 and 3
Sets the y position (in normalized coordinates) of the legend. Defaults to "1" for
vertical le... | python|plotly-dash|plotly-python | 1 |
8,702 | 66,126,249 | How to add columns to pandas dataframe for class object in python | <p>I want to create a class object to deal with my dataset automatically</p>
<p>For example:</p>
<pre><code>x = pd.DataFrame({'a':[1,2,3],"b":[4,5,6]})
class newdata(object):
def __init__(self,dataset):
self.a = dataset.a
self.b = dataset.b
self.dataset = dataset
def add_column... | <p>As far as I know it's not possible to assign attributes like this: <code>self[c] = a + 3</code>.
I could not reproduce the TypeError, but to use the <code>a</code> attribute from <code>newdata()</code> you have to write <code>self.a</code>, otherwise <code>a</code> will not be defined.
There are different ways to as... | python|pandas|dataframe|class | 0 |
8,703 | 68,872,687 | Groupby two columns pandas dataframe and shift().rolling() | <p>I want to groupby two columns, 'Y' and 'A', then <code>shift().rolling()</code> for column 'ValueA'.
I tried this code but result is not correct.</p>
<p>Code</p>
<pre><code>df = pd.DataFrame({
'Y' : [0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1],
'A' : ['b','c','a','c','a','c','b','c','a', 'a', 'b', 'b','c','a','a','b'],... | <p><strong>We need to to perform both <code>shift</code> and <code>rolling</code> operation per group</strong>, but instead you are performing the <code>shift</code> operation per group then rolling operation for the entire column which is producing the incorrect output.</p>
<pre><code>df['ValueX'] = df.groupby(['Y', '... | python|pandas|dataframe | 2 |
8,704 | 69,118,204 | collectIng identical rows of an np array by list comprehension | <p>I have a 2d np array and want to collect identical rows by list comprehension.
My implementation returns the desired result and a better solution can be found <a href="https://stackoverflow.com/questions/25532983/finding-identical-rows-and-columns-in-a-numpy-array">here</a>:</p>
<pre class="lang-py prettyprint-overr... | <p>Here is a solution using <code>numpy.equal</code> on A versus itself (broadcasted), and <code>itertools.groupby</code> to reshape the output:</p>
<pre><code>from itertools import groupby
a,b = np.equal(A, A[:,None]).all(2).nonzero()
{tuple(b[i] for i in g) for i,g in groupby(range(len(a)), lambda i:a[i])}
</code></p... | python|numpy|grouping|rows | 1 |
8,705 | 68,341,495 | How to draw 3D dynamic curve with python | <p>I continue to output three-dimensional coordinates, and use these coordinates to output three-dimensional dynamic curves. Here is my code, but there is nothing in the figure.</p>
<pre><code>plt.ion()
x = [0]
y = [0]
z = [0]
x_now = 0
fig = plt.figure()
ax1 = plt.axes(projection='3d')
for i in range(50):
plt.c... | <p>Where do you launch this script? If it is <code>jupyter-notebook</code>, add this line on top:</p>
<pre><code>%matplotlib inline
</code></pre>
<p>If you are using <code>jupyter-console</code>, it will be</p>
<pre><code>%matplotlib <backend>
</code></pre>
<p>where <code><backend></code> is one of (<code>'... | python | 1 |
8,706 | 63,287,960 | Python: Rotate plane (set of points) to match new normal vector using scipy.spatial.transform.Rotation | <p>So I'm currently trying to take slices on a plane orthogonal to a spline.
Direction doesn't really matter too much since I'm using the points to interpolate 3D scans</p>
<p>I'm mainly unsure about the rotmat method (this is a stripped down version of my class, technically a NURBS-Python surface derived class), where... | <p>I think I ended up producing something that seems to work in the end:</p>
<pre><code>import numpy as np
import vg
from pytransform3d.rotations import matrix_from_axis_angle
def _rotmat(self, vector, points):
"""
Rotates a 3xn array of 3D coordinates from the +z normal to an
arbitrary new ... | python|vector|scipy|3d|rotation | 0 |
8,707 | 63,223,650 | How to merge dict of dict in python | <p>Two dictionary is below</p>
<pre><code>d1 = {'1': {'index': '1', 'sc': '4', 'st': '3'}, '2': {'index': '2', 'sc': '5', 'st': '5'}}
d2 = {'1': {'diff': 1}, '2': {'diff': 0}}
</code></pre>
<p>Code is below</p>
<p><code>z = {**d2, **d1}</code> why this is not working</p>
<p>Tried below code also</p>
<pre><code>def Mer... | <p>an alternate way using <code>pandas</code></p>
<pre><code>>>> import pandas as pd
>>> df = pd.DataFrame(d1)
>>> df2 = pd.DataFrame(d2)
>>> merged_dict = pd.concat([df,df2]).to_dict()
</code></pre>
<p>output</p>
<pre><code>>>> merged_dict
{'1': {'index': '1', 'sc': '4', 's... | python | 3 |
8,708 | 62,184,321 | Set node color based on attribute | <p>I built a direct graph with default blue nodes as you can see in the image below.</p>
<p>Each node is an object that was created from the class "Node" and each has the attribute "state", which can have one of the following values: <code>{-1, 0, 1}</code>.</p>
<p>I want to show different node colours on the graph b... | <p>Let's use the following random graph as an example:</p>
<pre><code>G = nx.barabasi_albert_graph(20, 1)
plt.figure(figsize=(12, 8))
pos = nx.spring_layout(G, scale=20, k=3/np.sqrt(G.order()))
nx.draw(G, pos=pos, with_labels=True, k=13.8, node_color='lightgreen', node_size=800)
</code></pre>
<p><a href="https://i.s... | python|python-3.x|graph|networkx|graph-theory | 1 |
8,709 | 35,543,366 | RaspberryPi OpenCV ImportError undefined symbol | <p>I installed opencv-2.4.9 on my raspberry pi.When i try to run facedetect.py sample file,i am getting that error:</p>
<pre><code>Traceback (most recent call last):
File "facedetect.py", line 10,in <module>
import cv2.cv as cv
ImportError: /usr/lib/arm-linux-gnueabihf/libQtGui.so.4: undefined symbol:
</c... | <p>It looks like you're either missing a shared library, or there's a version mismatch between the versions of OpenCV and Qt installed.</p>
<p>You'll need to check what the missing/undefined symbol is, which version of libQtGui.so provides it and then check if you have the correct version installed.</p> | python|opencv|image-processing|raspberry-pi | 0 |
8,710 | 31,655,300 | How to display and update remaining time in a single line | <p>I have a program asking user for answers to some riddles and I'd like to implement of stopwatch of sorts. Is it possible to count from 0 to 30, but to make seconds update "over each other", so that it doesn't display:</p>
<pre><code>01
02
03
...
</code></pre>
<p>or</p>
<pre><code>01 02 03 ...
</code></pre>
<p>bu... | <p>If this program output in the command line it won't be possible to overwrite the digits. Command line output is not set up to be dynamic.</p>
<p>Right now you seem to be inputing and printing variables through the command line. Once you are comfortable with python, you might want to look into using a framework ( <a... | python-2.7 | 0 |
8,711 | 59,565,650 | Is there a way to save the input (float) from a variable created in a user interface in Python? | <p>I have been trying to make a <strong>user interface</strong> (by using tkinter)in Python that <strong>saves the number you enter</strong>. In this case I want the user to be able to give a start value and an end value of a measurement, which afterwards will be implemented in a code. For this to work, I need the user... | <p>In your <code>add_text</code> function you could first get the string of the textbox:</p>
<p><code>val1 = Start_text_box.get()</code></p>
<p>Then convert it to double:</p>
<p><code>val1 = float(val1)</code></p>
<p>Then print it </p>
<p><code>label1 = tk.Label(root, text="You have entered the start {0} and end i... | python|tkinter | 1 |
8,712 | 48,909,330 | Meaning of values returned by tensorflow accuracy metric | <p>I'm a bit confused about the values returned by the functions of the module tf.metrics (for example <a href="https://www.tensorflow.org/api_docs/python/tf/metrics/accuracy" rel="nofollow noreferrer">tf.metrics.accuracy</a>).</p>
<p>A simple piece of code in which I calculate accuracy using tf.metrics.accuracy and u... | <pre><code>import tensorflow as tf
from sklearn.metrics import accuracy_score
# true and predicted tensors
y_p = tf.placeholder(dtype=tf.int64)
y_t = tf.placeholder(dtype=tf.int64)
# Count true positives, true negatives, false positives and false negatives.
tp = tf.count_nonzero(y_p * y_t)
tn = tf.count_nonzero((y_p ... | python|tensorflow|metrics | 3 |
8,713 | 49,213,512 | Exceptions are seeing while Monitoring Ethernet interface kernel events using pyroute2 IPDB functionality | <p>I am trying to monitor the kernel network interface(link) up or down events using <strong>pyroute2 IPDB</strong> functionality. Exceptions are seen while fetching the interface index information from the callback function. But here in the "msg" there is an index field. I coded based on this reference <strong><a hre... | <p>There are multiple kernel messages coming from the kernel to the callback function, when the link is made up or down. Some of the messages doesn't have "index" field due to which the key error is been seen. The below modified function shall resolve </p>
<pre><code>def my_call_back(ipdb, msg, action):
if 'index' ... | python|netlink | 1 |
8,714 | 25,172,220 | How to hide QComboBox items instead of clearing them out | <p>I can't find a way to hide <code>QComboBox</code> items. So far the only way to filter its items out is to delete the existing ones (with <code>.clear()</code> method). And then to rebuild the entire <code>QComboBox</code> again using its <code>.addItem()</code> method.</p>
<p>I would rather temporary hide the item... | <p>In case someone still looking for an answer:</p>
<p>By default, <code>QComboBox</code> uses <code>QListView</code> to display the popup list and <code>QListView</code> has the <code>setRowHidden()</code> method:</p>
<pre><code>qobject_cast<QListView *>(comboBox->view())->setRowHidden(0, true);
</code></p... | python|pyqt | 11 |
8,715 | 60,074,361 | Measuring plots of data with PCA or t-SNE and Matplotlib | <p>My goal is to find out if I can manipulate and measure data from a PCA or t-SNE plot in Python. I want to know if there is a way I can find distances of points from a center of clusters.</p>
<p>I think there is a way but I'm not too sure. </p> | <p>You don't specify so much but maybe this can help you:</p>
<p>Clustering techniques information:
<a href="https://scikit-learn.org/stable/modules/clustering.html#clustering" rel="nofollow noreferrer">https://scikit-learn.org/stable/modules/clustering.html#clustering</a></p>
<p>Dimensionality reduction:
<a href="ht... | python|matplotlib|keras|pca|dimensionality-reduction | 0 |
8,716 | 5,769,567 | python django Localization | <p>I'm using django Internationalization current now.
When i use in template such as</p>
<pre><code>{% trans "i love you" %}
</code></pre>
<p>it works fine.</p>
<p>But when i define it in python file</p>
<pre><code>_("i love you")
</code></pre>
<p>it still outputs the English word.</p>
<p>If I replace <code>_("i ... | <p>you shouldn't replace <code>_("i love you")</code> in your views.py but in the .po file generated by <code>django-admin.py compilemessages</code> (<a href="http://docs.djangoproject.com/en/dev/howto/i18n/" rel="nofollow">see here</a>).</p>
<p>hope it helps</p> | python|django | 0 |
8,717 | 67,736,945 | VS Code trying to run .../Activat.ps1 in cmd terminal | <p>I'm using VS Code for a Python project using a virtualenv. I switched my deafult terminal from <strong>powershell</strong> to <strong>cmd</strong> as VS Code was not happy executing powershell scripts.</p>
<p>Now when I open a terminal in my project it opens cmd (as desired), but automatically tries tor run <code>..... | <p>This is a problem related to the Python extension, it should be fixed in the last update.</p>
<p>You can get some information from <a href="https://github.com/microsoft/vscode-python/issues/16175" rel="nofollow noreferrer">here</a>.</p> | python|visual-studio-code|cmd|virtualenv | 1 |
8,718 | 68,004,827 | Get row with closest date in other dataframe pandas | <p>I have 2 dataframes
Dataframe1:</p>
<pre><code>id date1
1 11-04-2022
1 03-02-2011
2 03-05-2222
3 01-01-2001
4 02-02-2012
</code></pre>
<p>and Dataframe2:</p>
<pre><code>id date2 data data2
1 11-02-2222 1 3
1 11-02-1999 3 4
1 11-03-2022 4 5
2 22-03-4444 5 6
2 22-02-2020 7 8
...
</code></pre>
<p>What I would like to d... | <p>Try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html#pandas-merge-asof" rel="nofollow noreferrer"><code>pd.merge_asof</code></a>, but first convert date1, date2 to datetime and sort both timeframes:</p>
<pre class="lang-py prettyprint-override"><code>df1["date1"] =... | python|pandas|dataframe | 4 |
8,719 | 30,371,094 | python encode the defined variable from txt file | <p>how to get the the text itself from a txt file in python 3?
so, I've a file that contains string like that:</p>
<pre><code>"name":"\u0414\u043e\u0436\u0434\u044c"
</code></pre>
<p>The code I wrote is:</p>
<pre><code>with open(r'C:\Temp\f1.txt','r') as f1:
data=f1.read()
f1.close()
#print(data)
f2 = open(r'C:\... | <p>In Python 3 it's a little trickier, you have to convert the string to bytes first and then decode it:</p>
<pre><code>bytes(var, 'ascii').decode('unicode-escape')
</code></pre>
<p>Since you have the text stored in a file, you can read the file in binary mode. Then it is cleaner:</p>
<pre><code>with open(r'C:\Temp\... | python|python-3.x|encoding | 1 |
8,720 | 42,763,094 | How to save final model using keras? | <p>I use KerasClassifier to train the classifier.</p>
<p>The code is below:</p>
<pre><code>import numpy
from pandas import read_csv
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier
from keras.utils import np_utils
from sklearn.model_selection i... | <p>The model has a <code>save</code> method, which saves all the details necessary to reconstitute the model. An example from the <a href="https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model" rel="noreferrer">keras documentation</a>:</p>
<pre><code>from keras.models import load_model
model.save('my_mod... | python|machine-learning|keras | 130 |
8,721 | 42,914,920 | Problems configuring nginx for a flask site | <p>I am having trouble getting nginx to serve the small flask site I am working on. I followed some tutorials from Digital Ocean, and I get it mostly right, but here is the problem:</p>
<p>In my /etc/nginx/sites-available/xproject configuration file, my server block has <code>listen 80</code> as well as <code>server_... | <p>Nginx serves static files and it cannot execute and host Python applications. You should use uWSGI or something similar. I preferably use Gunicorn.</p> | python|nginx | 0 |
8,722 | 65,681,689 | How to write specified columns and rows to excel file from an existing dataframe? | <p>Reposting this since no answer.</p>
<p>How can I write multiple columns upto a certain row into an excel file from an exisiting data frame ?
The image below is the contents of my data frame say df2:</p>
<p><a href="https://i.stack.imgur.com/cy5kV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cy... | <p>If I am understanding correctly what you need, basically to only save the first 5 rows of your data to excel, you can do it with <code>head()</code>, and <code>to_excel</code>:</p>
<pre><code>import pandas as pd
df.head(5).to_excel(r'C:\Users\....\filename.xlsx')
</code></pre> | python|excel|pandas|dataframe | 0 |
8,723 | 3,331,220 | Strip the last character sent by JavaScript through websockets to Python | <p>I'm currently trying out websockets, creating a client in JavaScript and a server in Python.</p>
<p>I'm stuck on a simple problem, though: when I send something from the client to the server it always contains a special ending character, but I don't know how to remove it.</p>
<p>I've tried <code>data[:-1]</code> t... | <p>The expression "data[:-1]" is an expression that produces a copy of data missing the last character. It doesn't modify the "data" variable. To do that, you have to assign back to "data", like so:</p>
<pre><code>data = data[:-1]
</code></pre>
<p>My suspicion is the "special ending character" is a bug, somewhere, ... | javascript|python|websocket | 1 |
8,724 | 3,569,020 | Refactoring a function definition | <p>I am using Pydev on Eclipse to write python code. I am new to Pydev and to Eclipse. I love the feature where by I can use rightClick -> Refactoring -> Rename... to rename a variable. </p>
<p>I was wondering if there is something similar to change a function everywhere in the project, if I change its definition.</p>... | <p>no IDE may support this as when you call a function it requires variable which may not be the <code>c</code> all the time,</p>
<p>what I suggest is keep the parameter c as optional like</p>
<pre><code>thisVar = myFunction(a, b, c = None)
</code></pre>
<p>and when you actually realize that it requires c then you c... | python|eclipse|refactoring|pydev | 2 |
8,725 | 26,595,520 | Insert a related object by ID, using endpoints-proto-datastore | <p>I'm trying to insert a Category object, but I like to link a Category to a Store using the Store ID. The ID is by endpoints-proto-datastore. How Can I do that?</p>
<p>Actually, to save a Category, the API require the Category name and the Store Key.</p>
<p>This is my api method:</p>
<pre><code>@Category.method(u... | <p>Assuming that you already have a Store entity that you want to include in your Category entity, be sure to use the Store key entity and not the id. You can find the key entity in the datastore viewer (old version).</p>
<p>If you add the entityKey default property like so you can get the key in queries of your enti... | python|google-app-engine|endpoints-proto-datastore | 0 |
8,726 | 26,794,029 | How to remove duplicate letters in a comma separated cell | <p>Hi I want to remove duplicate entries in single column in my datasheet. Is there a short way to do that when writing my output file? It is python3 script.</p>
<pre><code>with open(input) as infile, open (output, 'w') as outfile:
reader = csv.reader(infile, delimiter='\t')
writer = csv.writer(outfile, delimi... | <p>You have to split string with comma</p>
<pre><code>>>> a = "A,B,B,C"
>>> a.split(',')
['A', 'B', 'B', 'C']
</code></pre>
<p>Then use set to get unique values.</p>
<pre><code>>>> set(a.split(','))
set(['A', 'C', 'B'])
</code></pre>
<p>And join again with comma</p>
<pre><code>>>&g... | python|python-3.x | 2 |
8,727 | 44,963,818 | Extracting integers from a list | <p>I have a list like this:</p>
<pre><code>fmt_string="I am a smoker male of 25 years who wants a policy for 30
yrs with a sum assured amount of 1000000 rupees"
</code></pre>
<p>from the above list I removed stopwords and got this
Now I have a list as following:</p>
<pre><code>['smoker', 'male', '25', 'years', 'wa... | <p>This should be helpful</p>
<pre><code>import re
# Variation in places of the numbers in strings:
str1 = "I am a smoker male of 25 years who wants a policy for 30 yrs with a sum assured amount of 1000000 rupees"
str2 = "I am a smoker male of 25 years who wants a for 30 policy yrs with a sum assured amount of 10000... | python|python-2.7|nlp | 0 |
8,728 | 64,720,671 | Pass file variables from a python script to a bash script | <p>I am having a problem getting my python variable (1 file) to pass to my bash script. The python program pulls the file (csv file) and assigns it to var1 and then passes it to the bash script. The bash script uploads it to a server. The bash script works, but when I try to pass a file variable from python to bash, i... | <p>The <code>var1="data_file.csv"</code> the left hand side of the value of the variable was using a quote, variables are expanded if you are using speech marks.</p>
<p>If you want to use single quotes to avoid the additional escaping, you can instead mix and match quotes in the same argument:</p>
<p>For exam... | python|bash | 1 |
8,729 | 61,371,963 | Compare a pandas moving window to a list to find the window with least error | <p>I have reduced my data set to the last few steps. My pandas dataframe looks like this </p>
<pre><code> FAC
0 1
1 2
2 1
3 3
4 2
5 1
6 2
7 1
8 1
9 3
10 2
11 1
12 2
13 3
14 1
</code></pre>
<p>I also have a list that I have identified to match.</p>
<pre><code>match_list = [1, 2, 1, 1, 3]
<... | <p>This can be done with <code>rolling</code>:</p>
<pre><code>match_list = [1, 2, 1, 1, 3]
match_list = np.array(match_list)
def match(x):
return (len(x)==len(match_list) and (x==match_list).all())
df['error'] = np.where(df.FAC.rolling(5, center=True).apply(match)==1, 0, 'some value')
</code></pre>
<p>Output:<... | python|pandas|moving-average|rolling-computation | 3 |
8,730 | 60,367,604 | How to split a list of data frames into two lists? | <p>This is my initial data frame <code>df</code>:</p>
<pre><code>col1 col2 col3
1 0.5 10
1 0.3 11
5 1.4 1
3 1.5 2
1 0.9 10
3 0.4 7
1 1.2 9
3 0.1 11
4 0.1 11
</code></pre>
<p>I converted it into a list of ... | <p>You can use <code>random_integers</code> from <code>numpy</code> to get list of indices to keep, and then filter <code>list_df</code></p>
<pre><code>import numpy as np
import math
# compute what is 70% of the elements of list_df
n_70pct = math.floor(len(list_df)*0.7)
# take a sample of 70% of indexes in list_df
i... | python|pandas | 1 |
8,731 | 57,869,485 | Linux ModuleNotFoundError after installing python module | <p>I'm getting this:</p>
<pre><code>No module named 'pandas'
</code></pre>
<p>Although I did this:</p>
<pre><code>pip install pandas
</code></pre>
<p><code>whereis python</code> shows this:</p>
<pre><code>python: /usr/bin/python2.7-config /usr/bin/python2.7
/usr/bin/python3.6m-config /usr/bin/python3.6m /usr/bin/p... | <p>at first, execute the upgrade</p>
<pre><code>sudo pip3 install --upgrade pip
</code></pre>
<p>then install the pandas as "root"(administrator).</p>
<pre><code>sudo pip3 install pandas
</code></pre> | python|python-3.x|linux|python-2.7|pip | -1 |
8,732 | 56,079,744 | How to I layer area and text charts like this with Vegalite? | <p>I'm trying to understand if it's possible to layer two charts together here, so an area chart, and a text chart both appear together with vega lite. </p>
<p>I'm working with altair, which in turn is generating the vega specs being rendered.</p>
<p>Vega specs can be quite verbose, so the full dataset and generated ... | <p>The problem is that you cannot layer faceted charts (in general, there is no guarantee that the facets will align). What you need to do is facet the layered chart.</p>
<p>I'm unable to test the code without a dataset, but it might look something like this:</p>
<pre><code>area_chart = alt.Chart(width=600, height=40... | python|vega-lite|altair | 0 |
8,733 | 69,324,059 | How to make a gif or short mp4 video in python from figures containing multiple different animations on it? | <p>I want to create a gif or mp4 of multiple figures in python, thus containing at least four animations. I have four different groups of figures, and if I create four different gifs from those, How can I place them in one frame? <a href="https://drive.google.com/file/d/1HMVA3fa6ra0iKR6IifquQzebN9nvIURJ/view?usp=sharin... | <p>You can save the images as a bunch of pngs, then you can create a gif like this:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import matplotlib.pyplot as plt
import imageio
# Create PNGs
y = np.random.randint(30, 40, size=(40))
for i in range(4):
plt.plot(y[:i - 3])
plt.ylim(20,50)... | python | 0 |
8,734 | 57,311,789 | TypeError: Failed to convert object of type <class 'list'> to Tensor. Contents: [None, -1, 3]. Consider casting elements to a supported type | <p>I get an error for datatype mismatch in Tensorflow.</p>
<p>I tried to do:</p>
<pre><code>prediction = tf.convert_to_tensor(prediction)
y = tf.convert_to_tensor(y)
</code></pre>
<p>before passing it to loss function </p>
<pre class="lang-py prettyprint-override"><code>def train():
print("Training")
# tf ... | <p>I understood where the problem is</p>
<p>when you are putting these dimensions into a list object it converts int32 to Dimension(x) you can try to cast it with tensorflow but it did not work for me and as you again need to convert it to a Tensor , so you can use the below code to cast it without tensorflow</p>
<pre>... | list|tensorflow|seq2seq | 0 |
8,735 | 57,721,158 | Installing a pip package with cupy as a requirement puts install in never ending loop | <p>I am trying to make a pip package with cupy as one of the requirements, but I include cupy in the requirement, the pip install ends up in a never ending loop. I am trying to install the package on Google Colab, which already has Cupy install, so it should only check if Cupy is already installed and not try to instal... | <p>CuPy currently provides source package named <code>cupy</code> and binary distribution packages named <code>cupy-cudaXX</code> (where XX is a CUDA version).
Currently Google Colab is shipped with <code>cupy-cuda100</code> because it is using CUDA 10.0.
If you specify <code>cupy</code> as an requirement of your packa... | python|pip|google-colaboratory|cupy | 1 |
8,736 | 54,116,997 | How to encode character '\u0107' in python | <p>I'm trying to scrape data from Wikipedia page (it is a table of top 100 singles of certain years), while saving output to csv it got from 1951-1959 then it gave an error:</p>
<blockquote>
<p>line 43, in
writer.writerow(songs) File "C:\Python36_64\lib\encodings\cp1252.py", </p>
<p>line 19, in encode ret... | <p>I think you can correct this by using the correct unicode encoding when writing your output:</p>
<pre><code>writer = csv.writer(open('songs.csv', 'w', encoding='utf-8'),
delimiter=',', lineterminator='\n', quotechar='"')
</code></pre> | python|python-3.x|character-encoding|non-ascii-characters | 1 |
8,737 | 58,265,400 | How to set SetGlobalSpanCostCoefficient and the capacity parameter in AddDimension properly? | <p>I'm using OR-Tool to solve a VRP problem. I have experimented a bit with the exemple problem in the doc and managed to write a functioning program, but, I do not understand the purpose of the SetGlobalSpanCostCoefficient and how to set it properly. According to <a href="http://google.github.io/or-tools/python/ortool... | <p>The documentation is so cryptic it's very hard to actually understand what's going on. There is a lot of jargon but it's never defined clearly (formally). But here is my guess based on what I imagine it does (based on pure guess and experimentations).</p>
<p>First I think this tool uses linear programming (solver). ... | python|or-tools | 7 |
8,738 | 58,329,770 | Using Sanic's inbuilt webserver in Production | <p>Django <a href="https://docs.djangoproject.com/en/2.2/intro/tutorial01/" rel="nofollow noreferrer">documentation</a> states regarding their development server:</p>
<blockquote>
<p>Don’t use this server in anything resembling a production environment.
It’s intended only for use while developing. (We’re in the b... | <p>Issue 1 deals with request size and timeout settings that allow for DoS attacks by flooding the server with too much data. These settings can be adjusted by the admin, according to the server hardware and the requirements of the site being run. That being said, the defaults probably should be lower than they are, to... | python|python-3.x|deployment|server|sanic | 5 |
8,739 | 65,094,144 | I want to create only one Tkinter Radiobutton with two options: one click = select another click = unselected. How can I do this? | <pre><code>Radiobutton(register_win, variable=var, value=1, bg="#a1c4cc", activebackground="#a1c4cc").place(x=15, y=249)
</code></pre>
<p>In this code I can select but I can not unselect</p> | <p>As stated in the comments, radio buttons will remain checked unless another radio button in the group is selected.
The below example show how to use radio buttons and check buttons.</p>
<pre><code>import tkinter as tk
root = tk.Tk()
v = tk.IntVar()
v.set(0)
w = tk.IntVar()
w.set(1)
rbtn1 = tk.Radiobutton(root,text... | python|user-interface|tkinter|radio-button | 1 |
8,740 | 22,909,531 | SqlAlchemy - Many to Many outer join with conditions on join | <p>Here is my code:</p>
<pre><code>Table('contacts', self.metadata,
Column('id', PGUuid, primary_key=True),
Column('first_name', String(150), nullable=False),
Column('middle_name', String(150), nullable=True),
Column('last_name', String(150), nullable=False, index=True),
Column('friendly_name', Str... | <p>if you need a JOIN condition different from what the <code>relationship()</code> defines, then you can't use that relationship to do the join. You have to spell it out explcitly:</p>
<pre><code>query(Contact).filter(Contact._id == contact_id) \
.filter(Contact._is_deleted == False) \
.outer... | python-3.x|sqlalchemy|many-to-many|outer-join | 5 |
8,741 | 45,411,714 | trouble writing to csv with BeautifullSoup and Python | <p>I have a problem with writing the scraped data to a csv file. While the pages are loaded and the first part of the scripts works, the writing to csv causes a problem. Now I tried to make integers from the scraped data, because this worked well for me in other projects. However, in this project there seems to be prob... | <p>A couple of changes to be made here since stopping integer conversion of parsed text:</p>
<ul>
<li>Initialize <code>BeautifulSoup</code> using the <code>html5lib</code> this way:</li>
</ul>
<pre><code>BeautifulSoup(page1, "html5lib")</code></pre>
<ul>
<li>Read the response. <code>BeautifulSoup</code> needs to be ... | python|csv|selenium|web-scraping|beautifulsoup | 0 |
8,742 | 14,510,303 | List or Dictionary for storing game map | <p>So I currently have a 2d list of objects that define the map of a game where each object represents a tile on that map. As I was repurposing the code for something else, I wondered if it would make more sense to use a dictionary to store the map data or to continue using a list. With a list, the indices represent th... | <p>I would be wary of premature optimization.</p>
<p>Does your current approach have unacceptable performance? Does the data structure you're using make it harder to reason about or write your code?</p>
<p>If there isn't a specific problem you need to solve that can't be addressed with your current architecture, I wo... | python|list|dictionary | 2 |
8,743 | 6,479,405 | List Compherension with sublist | <p>Suppose I have a list of sublist:</p>
<pre><code>lst = [ ['A', 'is', 'from', 'B,', '2', 'm', 'from', 'C', '1.2', 'm', 'from', 'D.'],
['0.3', 'm', 'from', 'D.'] ]
</code></pre>
<p>and I wanted to organize the letters after the word "from" so I want to have </p>
<pre><code>new_lst = [ [B,C,D], [D] ]
</code... | <p>As you're talking about list comprehensions, you're probably writing in Python.</p>
<p>So I wrote the most awesome comprehension you may find to solve that problem.</p>
<pre><code>>>> [[next(i) for j in i if j == 'from'] for i in (iter(x) for x in lst)]
[['B,', 'C', 'D.'], ['D.']]
</code></pre>
<p><img s... | python|list|list-comprehension | 6 |
8,744 | 57,265,045 | How to sort the values (from smallest to larger) of a column in an ascii file using python? | <p>I have an ASCII file with the following columns : </p>
<pre><code>ID, val1, val2, val3
</code></pre>
<p>where ID is a row_number but not sorted. I want to write a new ascii file with the same columns with sorted ID (from smaller to larger). </p>
<p>How I could do that in python?</p>
<p>In fact, this file has bee... | <p>So, you need to sort the data in csv format you have in ascending order on the basis of Id.
You can use this function to do it</p>
<pre><code>def Sort(sub_li):
sub_li.sort(key = lambda x: x[0])
return sub_li
</code></pre>
<p>x[0] to sort according to Id means first column or you can change according to ... | python|sorting|ascii | 0 |
8,745 | 25,924,352 | Python returns list but to variable, but variable is null | <pre><code>def left(q):
return q[0]
def op(q):
return q[1]
def right(q):
return q[2]
def isInside(v, q):
if isinstance(q, list):
return isInside(v, (left(q))) or isInside(v, (right(q)))
else:
return v == q
def solve(v, q):
if isInside(v, left(q)):
q3 ... | <p>Your "solving" function's "else" branch is buggy:</p>
<pre><code>else:
if op(left(q)) == '+':
solvingAdd(v, q)
else:
return "v not on left of q"
</code></pre>
<p>should be</p>
<pre><code>else:
if op(left(q)) == '+':
return solvingAdd(v, q) #you forgot to return this value
e... | python|function|null|return | 0 |
8,746 | 44,400,877 | Webscraping an angularjs site | <p>I am attempting to webscrape an angularjs site using beautifulsoup. The site is an angularjs site and completely generated from javascript.</p>
<p>The site is: <a href="https://sports.bovada.lv/baseball/mlb/pitcher-props-market-group" rel="nofollow noreferrer">https://sports.bovada.lv/baseball/mlb/pitcher-props-mar... | <p>Have you tried requests? i just tried a quick and dirty script and it got more than <code><html><head><body></code> tags.</p>
<pre><code>#!/usr/bin/python3
import requests, bs4
res = requests.get('https://sports.bovada.lv/baseball/mlb/pitcher-props-market-group')
soup = bs4.BeautifulSoup(res.tex... | python|selenium|web-scraping|beautifulsoup | 0 |
8,747 | 44,401,414 | Slicing pandas dtype object from end not working | <p>I have a dataframe:<a href="https://i.stack.imgur.com/I7yim.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I7yim.jpg" alt="enter image description here"></a></p>
<p>where series_id is a dtype object. When I run:</p>
<pre><code>df['dataType'] = df['series_id'].apply(lambda x: x[-1:])
</code></pr... | <p>and of course the answer was extra whitespace at the end,:</p>
<pre><code> df['dataType'] = df['series_id'].apply(lambda x: x.strip()[-1:])
</code></pre>
<p>.strip() takes care of it. Hope that helps someone.</p> | python|pandas | 0 |
8,748 | 44,617,474 | Pyspark code is not performant enough when compared to pure python alternative | <p>I transformed the existing code which was in python pasted below was in pyspark. </p>
<p>Python code:</p>
<pre><code>import json
import csv
def main():
# create a simple JSON array
with open('paytm_tweets_data_1495614657.json') as str:
tweetsList = []
# change the JSON string into a JSON... | <p>If you want to parallely process something in PySpark, don't <code>collect()</code> back to a Python list</p>
<pre><code>def calc_sentiment(tweetsDf): # You should pass a dataframe
from sentiment import sentiment_score
# Add a new column over the Tweets for the sentiment
return tweetsDf.withColumn('se... | python|apache-spark|pyspark|apache-spark-mllib | 2 |
8,749 | 20,407,420 | Python 2.7 Tkinter, OOP, and Callbacks | <p>I'm just starting to piece together a simple utility for turning on a projector and selecting some presets on it. I was using it from a command line but then thought it would be a good excuse to start learning Tkinter. I'm struggling with the OOP design, since clearly you can do this with functions and so on. As I s... | <p>If you have simillar buttons with simillar functions you can use loop (<code>for</code>) to create that buttons and you can use one function with different argument. You have to use <code>lambda</code> function to call function with arguments. </p>
<p>(not complet) example:</p>
<pre><code>def my_func(a, b):
pr... | oop|python-2.7|tkinter | 2 |
8,750 | 35,844,873 | use a 2-axes colormap in matplotlib | <p>Is there a practical way to use/define a "nice" Matplotlib color maps that would be dependent on two real variables <code>cmap2d(a1,a2)</code>, of course such as: <code>0.<= a1 <= 1. & 0.<= a2 <= 1.</code> ?</p>
<p>Basically it should be defined as a regular colormap but defined on a 2d frame ... <... | <p>Yes, you can define a 2D colour map. </p>
<p>Because the output of your 2D colour map is univariate (let's forget about the RGB channels for now), you can always express it in two steps:</p>
<ol>
<li>compute a function <code>f(a1, a2)</code></li>
<li>pass the output of the function to the colour map of your choice... | python|matplotlib|color-mapping | 0 |
8,751 | 15,065,338 | Django timezone localization not working as expected | <p>I'm using Django 1.4.3 and Postgres 9.1.3. Here is my template where <code>message.created_at</code> is a python <code>datetime</code> object and it clearly tells me that the datetime object is stored in GMT as I can debug by passing <code>e</code> in <code>date</code> filter. The conversion to my local time which i... | <p>Are you doing an <code>activate</code> to activate the local time-zone? See <a href="https://docs.djangoproject.com/en/dev/topics/i18n/timezones/#default-time-zone-and-current-time-zone" rel="nofollow">this</a>.</p> | django|datetime|python-2.7|django-templates|timezone | 1 |
8,752 | 15,340,422 | While loop variable not updating | <p>I have a loop in a method like this:</p>
<pre><code>from random import randint
class Player:
def __init__(self, position=0):
self.position = position
def move(self, move):
self.position += move
class Game:
def __init__(self, size=10, p1=1, p2=1):
self.size = size
self.... | <pre><code> def jump(self, iterations):
move1, move2, i = 0,0,0
while i < iterations:
print(move1, move2) # move1 is 0 again
a = Game(self.size, self.p1.position+1, self.p2.position)
x = a.run()
print("who won game a? : " + str(x)) # x is either 1 o... | python|loops | 1 |
8,753 | 14,946,086 | Append a new character to a string using pass by referencce | <p>I am trying to add a string to another string by passing the value to another function but does not append. </p>
<pre><code>def test2(s1,s2):
s1 = s1+s2
s1 = 'z'+s1
return len(s1)
def test(s1,s2):
i = test2(s1,s2)
print(i)
print(s1)
String1 = raw_input()
String2 = raw_input()
test(String1, Stri... | <p>There is no such thing as "pass by reference" in Python and string objects are immutable so you cannot modify the string passed to a function.</p> | python|arrays|string|pass-by-reference | 3 |
8,754 | 29,588,177 | Save full text of a tweet with tweepy | <p>I am a novice programmer in python. I am having troubles trying to extract the text of a series of tweets with <code>tweepy</code> and saving it to a text file (I ommit the authentication and stuff)</p>
<pre><code>search = api.search("hello", count=10)
textlist=[]
for i in range(0,len(search)):
textlist.appen... | <p>With tweepy, you can get the full text using <code>tweet_mode='extended'</code> (not documented in the Tweepy doc). For instance:</p>
<p>(not extended)</p>
<pre><code>print api.get_status('862328512405004288')._json['text']
</code></pre>
<blockquote>
<p>@tousuncotefoot @equipedefrance @CreditAgricole @AntoGriez... | python|twitter|tweepy | 10 |
8,755 | 29,722,851 | Why is variable not global in BGE Python | <p>I'm trying to make a simple game in Blender Game Engine using Python controller.</p>
<p>I have a Python controller attached to an Always sensor on a pulse mode and a game property called 'first' on a Sphere, which is also the controlled object. </p>
<p>I want to run a few lines of code only for the first time the ... | <p>They are only defined if your first if statement evaluates to <code>True</code>. You access every time in all your if statements which are evaluated each time and in <code>player.applyTorque((ForBack, LeftRight, 0), False)</code>.</p>
<p>You should set the initial value for both <strong>outside</strong> the first... | python|game-engine|blender | 1 |
8,756 | 29,585,289 | Splitting a list within a list in python | <p>How can I make a function to return the lowest number in a list like:</p>
<pre><code>listA = [[10,20,30],[40,50,60],[70,80,90]]
</code></pre>
<p>I want it to return 10</p> | <p>Flatten the list by using <code>itertools.chain</code>, then find the minimum as you would otherwise:</p>
<pre><code>from itertools import chain
listA = [[10,20,30],[40,50,60],[70,80,90]]
min(chain.from_iterable(listA))
# 10
</code></pre> | python|list|python-2.7 | 2 |
8,757 | 62,831,423 | I cannot get new line in python | <p>my code:</p>
<pre><code>question_prompts = [
"What color are apples?]\n(a) Red/Green \n(b) Yellow \n(c) Purple\n\n",
]
print(question_prompts)
</code></pre>
<p><code>\n</code> in this array <code>[]</code> didn't work. It cannot be down a new line. Hope to get your help</p> | <p>That's because you are printing the list and not the string whose inside the list, try this:</p>
<pre><code>question_prompts = [
"What color are apples?]\n(a) Red/Green \n(b) Yellow \n(c) Purple\n\n",
]
for prompt in question_prompts:
print(prompt)
</code></pre> | python | 1 |
8,758 | 62,690,184 | Deleting rows in pandas dataframe based on pair value | <p>I have dataframe as below:</p>
<pre><code>df = pd.DataFrame({'User':['a','a','a','b','b','b'],
'Type':['101','102','101','101','101','102'],
'Qty':[10, -10, 10, 30, 5, -5]})
</code></pre>
<p>I want to remove pair value of df['Type'] = 101 and 102 where df['Qty'] net off each other. ... | <p>Idea is create combinations of index values per groups and test if each subgroup contains both <code>Type</code>s and sum is <code>0</code> for set ot this matched pairs:</p>
<pre><code>#solution need unique index values
df = df.reset_index(drop=True)
from itertools import combinations
out = set()
def f(x):
... | python|pandas|duplicates | 3 |
8,759 | 53,472,840 | pytube-Youtube function not initializing | <p>I have <code>pytube</code> installed, i am getting an error when i run it(I am using python 3.7), the problem seems to be with the <code>pytube</code> itself ,i am using exact code of tutorials for this module. </p>
<pre><code>import pytube
link ='https://www.youtube.com/watch?v=9bZkp7q19f0'
yt = pytube.YouTube(l... | <p>I had this issue last week. Since I'm on Ubuntu, what worked for me was navigating to:</p>
<pre><code>/home/<username>/anaconda3/lib/python3.6/site-packages/pytube
</code></pre>
<p>and adding </p>
<pre><code>r'\bc\s*&&\s*d\.set\([^,]+,.*?\((?P<sig>[a-zA-Z0-9$]+)\(\(0\s*,\s*window.decodeURIComp... | python|python-3.x|youtube | 1 |
8,760 | 53,594,136 | Calculate hash of an h2o frame | <p>I would like to calculate some hash value of an <code>h2o.frame.H2OFrame</code>. Ideally, in both <code>R</code> and <code>python</code>. My understanding of <code>h2o.frame.H2OFrame</code> is that these objects basically "live" on the <code>h2o</code> server (i.e., are represented by some <code>Java</code> objects)... | <p>It is available in the REST API <a href="https://i.stack.imgur.com/UwiR4.png" rel="nofollow noreferrer">1</a> (see screenshot) you can probably get to it in the H2OFrame object in Python as well but it is not directly exposed.</p> | python|r|h2o | 2 |
8,761 | 55,127,406 | Is there any difference using TimeDistributed on single Dense Layer? | <p>Is there any difference between adding a TimeDistributed wrapper around a single Dense layer? Both have the same number of parameters (2,208) and same output shape of (None, 6, 32). The purpose is I have a sequence of data that is 6 time steps long with each time step having 64 features that I want to pass through a... | <p>No, there is no difference between the 2 examples.</p>
<p>By default if <code>len(input_shape) = 2</code> for the <code>Dense</code> layer (excluding the batch dimension) then it behaves in the same way like using <code>TimeDistributed</code> layer.</p>
<p>However, if you flatten (<code>Flatten</code> layer) your ... | python|tensorflow|keras|deep-learning | 0 |
8,762 | 54,877,358 | copying data from csv and paste those into another csv | <p>I have two CSV file. and trying to parse datas from file1 and paste those datas to file2. But having some issue to parsing data in file1.</p>
<p>Trying to get <code>利用額(Fee込み)</code> row's <code>全体</code> But having some issue. With below code I can just parse Company AAA total. Not BBB together... </p>
<p>And whe... | <p>The column and index of your dataframe is unclear. What is probably most useful is if you set column A and row 2 as your index and column of the dataframe. I would use this to import:</p>
<pre><code>df = pd.read_csv("201902.csv", index_col=0, header=1)
</code></pre>
<p>Then you can use <code>loc</code> to index a ... | python|python-3.x|pandas|numpy | 0 |
8,763 | 33,512,541 | cross compiling gdb for arm with python failed | <p>I want to debug ARM application on devices like Android machine, i prefer to use gdb(ARM version) than gdb with gdbserver to debug, because there is a <a href="https://github.com/cyrus-and/gdb-dashboard" rel="noreferrer" title="gdb-dashboard">dashboard</a> , a visual interface for GDB in Python.</p>
<p>It must coop... | <p>I ran into this problem when attempting to cross-compile a python wrapper module built with SWIG, but it looks to me like it will happen to anyone cross compiling python-linked C code on a Debian system.</p>
<p>Apparently the Debian python-dev packages are not set up with the header files to facilitate a cross comp... | python|linux|android-ndk|cross-compiling | 11 |
8,764 | 73,702,204 | Django how to copy subset of object values to a new object? | <p>I need to create a new Django DB object by inheriting some values from an existing objects.</p>
<p>If I just wanted to create a new copy of an objects I would simply do this:</p>
<pre><code>objB =OBJ.objects.get(pk=objA_id)
objB.pk = None
objB.save()
</code></pre>
<p>But I want only copy certain values from the obje... | <p>It depends on what exactly it is you're trying to achieve. Maybe, clarify what exactly it is you're attempting to implement.</p>
<p>One thing I WILL say though, is you absolutely do <strong>NOT</strong> want to write code that nullifies your PK or ID without providing a replacement or alternate primary key for it to... | python|django | -2 |
8,765 | 73,541,085 | Count occurence of an event regarding two intervals [Python] | <p>Sorry if the title of my question is unclear, I had trouble finding an appropriate title for my problem. I am new to Python programming and trying to learn data analysis on my own.</p>
<p>I have the following pandas data frame :</p>
<pre><code>|Event| y | x |bins_x |bins_y |
|:---:|:-:|:-:|:------:|:------:|
|0 ... | <p>That's fairly simple, just use <code>.value_counts()</code> on a slice of the dataframe:</p>
<pre><code>df = pd.DataFrame({'Event': [0,1,2,3,4,5],
'y': [80,78,79,80,72,77],
'x': [34,40,32,36,44,57],
'bins_x': [(20,40),(20,40),(20,40),(20,40),(40,60),(40,60)],
... | python|python-3.x|dataframe | 1 |
8,766 | 13,015,456 | List of tuples, first tuple as key, grouping by key into into a dictionary | <p>I have a list of tuples. The first part is an identifier that may or may not be repeated. I want to process this list into a dictionary, keyed by identifier. The problem, I've been unable to think around overwriting by key:</p>
<pre><code>def response_items(self):
ri = self.response_items_listing#(gets the ... | <p>you can use <code>setdefault()</code>:</p>
<pre><code>In [79]: dic={}
In [80]: for x in lis:
dic.setdefault(x[0],[]).append(x[1:])
....:
....:
In [82]: dic
Out[82]: {'123': [('abc', 'def'), ('efg', 'hij')], '456': [('klm', 'nop')]}
</code></pre> | python|list|dictionary|tuples|grouping | 2 |
8,767 | 13,132,765 | Getting an expression over a horizon for a given recursive equation in sympy/numpy | <p>The following example is stated just for the purpose of precise definition of the query. Consider a recursive equation x[k+1] = a*x[k] where a is some constant. Now, is there an easier way or an existing method within sympy/numpy that does the following (i.e., gives an expression over a horizon for a given recursive... | <p>I was going to suggest using SymPy's <code>rsolve</code> to try to find a closed form solution to your equation, but it seems that at least for this specific one, there is a bug that prevents it from working. See <a href="http://code.google.com/p/sympy/issues/detail?id=2943" rel="nofollow">http://code.google.com/p/... | python|numpy|scipy|sympy | 1 |
8,768 | 12,744,779 | formatted string of series of numpy array elements | <p>It seems quit trivial to me but I'm still missing an efficient and "clean" way to insert a series of element belonging to numpy array (as <code>aa[:,:]</code>) in a formatted string to be printed/written.
In fact the extended element-by-element specification syntaxes like:</p>
<pre><code>formattedline= '%10.6f %10... | <p>You could convert it to a tuple:</p>
<pre><code>formattedline = '%10.6f %10.6f %10.6f' % ( tuple(aa[ii,:]) )
</code></pre>
<p>In a more general case you could use a <code>join</code>:</p>
<pre><code>formattedline = ' '.join('%10.6f'%F for F in aa[ii,:] )
</code></pre> | python|arrays|numpy|formatted-text | 6 |
8,769 | 21,910,304 | Python Mail with Mandrill To Multiple email id | <p>Email With Mandrill to multiple emailId but it only deliver to id which is first in the list to rest it does not send.I want to send mail to multiple users using mandrill API </p>
<pre><code>here is my code :
class mandrillClass:
def mandrillMail(self,param):
import smtplib
from email.mime.mul... | <p>Since you're using smtplib, you'll want to review the documentation for that SMTP library on how you specify multiple recipients. SMTP libraries vary in how they handle multiple recipients. Looks like this StackOverflow post has information about passing multiple recipients with smtplib: <a href="https://stackoverf... | python|mandrill | 1 |
8,770 | 24,939,467 | NVD3 charts with Django - web page not responding upon call | <p>I have the following view in my django project;</p>
<pre><code>def ChartView(request):
connection = SQLSeverConnection('MSSQLServerDataSource')
times = connection.getColumnData('DateTimeStamp', 'reqColumn', '2011-01-01 00:00:00.000', '2011-01-21 19:30:00.000')
string_times = []
for theTime in times:
string_ti... | <p>So I got it working, thankfully. The issue was with my ydata. From the database query it was in the following format;</p>
<pre><code>[(4.4, ), (4.8, ), (4.2, ), (4.0, ), (4.2, ), (4.8, ), (2.0, ), (2.4, ), (3.0, )]
</code></pre>
<p>It should have looked like this for nvd3;</p>
<pre><code>[4.4, 4.8, 4.2, 4.0, 4.2,... | python|django|charts|nvd3.js | 0 |
8,771 | 40,892,913 | Python - Writing file to a directory built by user input | <p>So, we have a script that has some raw inputs at the beginning. Typically the script will run and create the new files right in the same directory. I'm trying to get it to use one of the inputs to create a new directory and build the files in that directory.</p>
<pre><code>import os
import sys
import socket
import... | <p>The <code>open()</code> function doesn't take a separate path and filename, it only takes a path to a file. You need to combine the path and filename into a single string.</p>
<pre><code>import os
with open(os.path.join(path, 'derp_s1_config.txt'), 'w'):
# ...
</code></pre>
<p>The error you're getting is beca... | python|python-2.7 | 1 |
8,772 | 30,829,028 | Running Python clicker based on keylogger inputs on the background in Windows | <p>I wanted to write a program in Python for Windows that would act as a clicker, in which according to a key the user presses a click is made at a known location on the screen. This is used for an automated option selection from a list in a webpage. I have the clicking part working, but I wanted to be able to make sev... | <p>All you need here is move your click part to a thread and share the user input using a shareble object such as queue. It sounds like a overkill , but that's the way to keep your tasks in background.</p>
<p>And BTW, you have many GUI application frameworks available in Python like tkinter ,wxpython which can ease yo... | python|windows|service|cmd|user-input | 1 |
8,773 | 40,091,435 | Remove only double letters sequences in word with best speed with python | <p>Very popular task for finding/replacing double letters in a string. But exist solution, where you can make remove double letters through few steps. For example, we have string <code>"skalallapennndraaa"</code>, and after replacing double letters we need to get in output <code>"skalpendra"</code>. I tried solution wi... | <p>You can use this double replacement:</p>
<pre><code>>>> s = 'skalallapennndraaa'
>>> print re.sub(r'([a-z])\1', '', re.sub(r'([a-z])([a-z])\2\1', '', s))
skalpendra
</code></pre>
<p><code>([a-z])([a-z])\2\1</code> will remove <code>alla</code> type of cases and <code>([a-z])\1</code> will remove ... | python|regex|string | 2 |
8,774 | 59,709,789 | How to keep unique inner lists within a list of lists by ignoring one element of the inner list | <p>I have a list of lists, and would like to keep the unique lists by ignoring one element of the list.</p>
<p><strong>MWE</strong>:</p>
<pre><code>my_list_of_lists = [['b','c','1','d'],['b','c','1','d'],['b','c','2','e']]
print(my_list_of_lists)
new_list_of_lists = []
for the_list in my_list_of_lists:
if the_... | <p>This is not "Pythonic" per se, but it is relatively short and gets the job done:</p>
<pre><code>my_list_of_lists = [['b','c','1','d'],['b','c','3','d'],['b','c','2','e']]
print(my_list_of_lists)
new_list_of_lists = []
ignore = 2
for the_list in my_list_of_lists:
if all(
any(e != other_list[i]
... | python|list | 2 |
8,775 | 19,557,434 | Python Convert/Verify 5 or 6 Digit Int as a valid Time | <p>This is Homework. I have a function that needs to recieve a 5 or 6 digit integer "setStart(clock)" . I need to verify that the integer correpsonds to a value for a valid time. The actual homework states :
Parameter 1: "clock" is a 5- or 6-digit integer in the format HMMSS or HHMMSS, where H is the 1- or 2-digit hou... | <p>Well, if it's within the bounds of your assignment, you should let <code>datetime</code> do the heavy lifting for you.</p>
<pre><code>try:
datetime.strptime(clock,'%H%M%S')
except ValueError as e:
#raise whatever exception you want here, or reraise
</code></pre>
<p>Note that you do NOT need a "full time va... | python|datetime|python-2.7|time | 1 |
8,776 | 22,435,710 | sort python list of dictionaires based on value of 2 keys | <p>I have a list of dictionaries that I would like to sort based on the value of a key 'index' as long as another key called 'verifier' is equal to 1. Both keys are present in all dictionaries on the list</p>
<p>I can sort the list with the code below... but not sure how to add another condition (I would prefer not to... | <p>The key function can return a tuple of sort keys; when the first value in the tuple is equal for two values, the second item in the tuple is compared, etc.:</p>
<pre><code>product_list = sorted(product_list, key=lambda k: (k['verifier'] == 1, k['index']))
</code></pre>
<p>This returns a <code>(boolean, k['index'])... | python|sorting|dictionary | 2 |
8,777 | 16,620,607 | Python Unicode Handling Errors - How To Simply Remove Unicode | <p>There are literally dozens, maybe even hundreds of questions on this site about unicode handling errors with python. Here is an example of what I am talking about:</p>
<blockquote>
<p>UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 2310: ordinal not in range(128)</p>
</blockquote>
<p>A great... | <p>You can do <code>line.decode('ascii', 'ignore')</code>. This will decode as ASCII everything that it can, ignoring any errors.</p>
<p>However, if you do this, prepare for pain. Unicode exists for a reason. Throwing away parts of your data without even knowing what you're throwing away will almost always cause pr... | python|unicode | 12 |
8,778 | 43,917,613 | Dillema with prediction with TensorFlow on MNIST set | <p>currently I am a newbie on TensorFlow, I have trained a model using MNIST set and now I have made some pictures with numbers and I want to try to test the precision. I think I have a syntax or understanding of how things in TensorFlow are working
This is my model:</p>
<pre><code>x = tf.placeholder(tf.float32, shape... | <p><code>y_conv</code> will provide you what you need to make recommendations. You're probably just not understanding the form the data takes on in that tensor.</p>
<p>In your code you have a loss function and an optimizer:</p>
<pre><code>cross_entropy = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labe... | python|machine-learning|tensorflow|scikit-learn|computer-vision | 0 |
8,779 | 43,547,507 | bad request error 400 with Requests library | <p>I am attempting to automate the process of passing text from a website to a tool in order the estimated reading level of the text. However, when I pass the url-encoded text via a post method, i get error 400 bad request.</p>
<pre><code>article = 'The quick brown fox jumps over the lazy dog.'
headers = ({'Host': 'a... | <p>You <em>are</em> missing something simple , you don't have to encode <code>data</code> , <code>requests</code> does it for you : </p>
<pre><code>article = 'The quick brown fox jumps over the lazy dog.'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0',
... | python|python-3.x|post|python-requests | 1 |
8,780 | 43,921,331 | What does Instance() do in Python? | <p>What does this line do in python?</p>
<pre><code>user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
</code></pre>
<p>note that <code>UserMagics</code> is an empty class defined in <code>IPython.core.magics.__init__.py</code> like this:</p>
<pre><code>@magics_class
class UserMagics(Magics):
... | <p><code>Instance</code> is part of the <a href="https://traitlets.readthedocs.io/en/stable/trait_types.html#classes-and-instances" rel="nofollow noreferrer"><code>traitlets</code> package</a>. From the documentation:</p>
<blockquote>
<p>In short, traitlets let the user define classes that have</p>
<ol>
<li>A... | python|python-2.7|python-3.x | 2 |
8,781 | 54,467,249 | Toolchain not downloading the tool | <p>Hi I'm trying to set up a toolchain for the Fn project. The approach is to set up a toolchain per binary available in GitHub and then, in theory use it in a rule. </p>
<p>I have a common package which has the available binaries:</p>
<pre><code>default_version = "0.5.44"
os_list = [
"linux",
"mac",
"wi... | <p>Two things:</p>
<p>One, I suspect this is your actual issue: <a href="https://github.com/bazelbuild/bazel/issues/6828" rel="nofollow noreferrer">https://github.com/bazelbuild/bazel/issues/6828</a>
The core of the problem is that, is the toolchain_type target is in an external repository, it <em>always</em> needs to... | python|bazel|skylark|starlark | 3 |
8,782 | 54,390,735 | Transform a tensor into another | <p>I have a list of arrays </p>
<pre><code>T = [np.array([[1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]]), np.array([[1, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0]]), np.array([[0, 0, 1], [0, 0, 1], [1, 0, 0], [0, 1,
0]]), np.array([[0, 1, 0], [0, 0, 1], [0, 1, 0], [0, 0, 1]]), np.array([[1, 0, 0], [1, 0, 0], [0, 0, 1], [0,... | <p>Use the following</p>
<pre><code>np.transpose(T, (1, 0, 2))
</code></pre>
<p>The second parameter refers to the position of axes of the tensor. Since <code>T</code> has a shape of <code>(5, 4, 3)</code>, which means axis <code>0</code> is <code>5</code>, axis <code>1</code> is <code>4</code>, and axis <code>2</cod... | python|arrays|list|numpy | 2 |
8,783 | 9,321,741 | Printing to screen and writing to a file at the same time | <p>I found some code online that generally works, but I want to use it multiple times in the same program (write different things to different files, while still printing to the screen the whole time). </p>
<p>That is to say, when it closes, I think sys.stdout closes, so printing at all, and using this class again fai... | <p>You are trying to reproduce poorly something that is done very well by the Python Standard Library; please check the <a href="http://docs.python.org/library/logging.html" rel="noreferrer">logging module</a>. </p>
<p>With this module you can do exactly what you want, but in a much simpler, standard, and extensible m... | python | 176 |
8,784 | 52,596,040 | Searching for multiple strings in a stream at once without doing "text1" or "text2" or "text3" or | <p>I was wondering if there's a way in python that I can search for multiple strings in a stream at once without jamming them all into one line. Can I put them in some sort of list and substitute that for the long line of 'or's?</p>
<pre><code>if re.search("japan" or "japanese" or "nihon" or "nippon", str(comment.body... | <p>You could do this with list comprehension, if you prefer how this looks</p>
<pre><code>search_terms = ["japan", "japanese", "nihon", "nippon"]
if any([x in str(comment.body).lower() for x in search_terms]):
return True
</code></pre> | python|string|bots | 1 |
8,785 | 52,814,798 | Why is my prime number checking code not displaying the correct output? | <p>I have a code that checks whether a number is prime or not, and outputs "Yes" or "No" accordingly. But when I input 1763, it outputs "Yes" even though it isn't a prime. The code checks whether a number is prime or not by checking if it can be divisible by any number between 2 and n-1. So when I input 1763, it should... | <p>The problem is that you are not accounting for all the divisors. As soon as your first condition (<code>if n%i==0:</code>) is false, you execute the second <code>elif</code> condition and print "Yes". </p>
<p>Solution: You can use a flag which will be turned 1 <strong>only</strong> when a divisor will be found, whi... | python|python-3.x|primes|primality-test | 1 |
8,786 | 47,913,140 | Beautifulsoup get('value') | <pre><code><ul class="mainview">
<li>
<input value="ABCD" class="origianl">
</li>
</ul>
</code></pre>
<p>this is HTML lines and</p>
<pre><code>mainview = soup.find(class_="mainview")
child = mainview.children
child_value = child.get("value")
[print(x) for x in child_value... | <p><code>children</code> (similar to <code>'list_iterator'</code>) means many items so you get list not single item. It can be even list with one item or empty list but it is still a list. You have to use <code>for</code> loop to use <code>get()</code> with every item on the list or use index <code>[0]</code> to get on... | python|beautifulsoup | 0 |
8,787 | 47,970,758 | import speech_recognition as sr doesn't work on Mac? | <p>import speech_recognition as sr I am trying to program a personal assistance for learning but it says command not found. Does anybody know how I can fix that problem? And if this doesnt work on MAC does anybody have an alternative?</p> | <p>If you are just trying to do <code>import speech_recognition as sr</code> into your terminal, that wont work. (Not sure if that's what you are trying to do or not, the question is a little bit unclear.) It needs to be in a python file and executed. </p>
<p>If it is in a python file and you are running it via <code>... | python|macos | 0 |
8,788 | 47,843,203 | Where Python adds class names for private methods | <pre><code>class User(object):
def __private_function(self):
print("private")
user = User()
print(dir(user))
Output: ['_User__private_function', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex... | <p><a href="https://github.com/python/cpython/blob/master/Python/compile.c" rel="nofollow noreferrer">https://github.com/python/cpython/blob/master/Python/compile.c</a></p>
<pre><code> 220 PyObject *
221 _Py_Mangle(PyObject *privateobj, PyObject *ident)
222 {
223 /* Name mangling: __private becomes _classname__... | python|python-3.x|python-2.7 | 2 |
8,789 | 39,788,262 | Obtaining the most informative features after dimensionality reduction | <p>I basically have a python script that tries a variety of dimensionality reduction techniques combined with a variety of classifiers.
I attempted to collect the most informative features for each classifier:</p>
<pre><code>if 'forest' in type(classifier).__name__.lower():
importances = classifier.feature... | <p>You can't.</p>
<p>When you do dimensionality reduction (like PCA), what you get is some new vectors and not a subset of the original feature set. And in the process you lose information. You project the the features of the original feature set, from a high dimensional space to a new (lower) space. You can't go back... | python|machine-learning|scikit-learn | 1 |
8,790 | 16,308,340 | Facebook friend handling via python and GraphAPI | <p>i am learning about handling the graph api in python via the FacePy module.</p>
<p>I am just curious as to see if it was possible to delete friends via the Graph API?</p> | <p>Because of possible misuse that might happen, feature like deleting friends via Facebook is not available. You can although send <a href="https://developers.facebook.com/docs/reference/dialogs/friends/" rel="nofollow">Friend Requests</a> but the app should not use this feature to encourage users to friend other user... | python|facebook | 0 |
8,791 | 38,631,274 | using terminal command into python code | <p>I have a file named <strong>myosm.osm</strong>. If I run the command </p>
<pre><code> $ ogrinfo myosm.osm
</code></pre>
<p>then I get the following output:</p>
<pre><code>Had to open data source read-only.
INFO: Open of `myosm.osm'
using driver `OSM' successful.
1: points (Point)
2: lines (Line String)
3: m... | <p>Using <a href="https://plumbum.readthedocs.io/" rel="nofollow">plumbum</a>:</p>
<pre><code>from plumbum.cmd import ogrinfo
output = ogrinfo('myosm.osm')
</code></pre>
<p>(to install: <code>pip install plumbum</code>)</p> | python-2.7|command-line|openstreetmap | 1 |
8,792 | 40,694,380 | Forcing multiplication to use __rmul__() instead of Numpy array __mul__() or bypassing the broadcasting | <p>This question is close to what is asked in <a href="https://stackoverflow.com/questions/40252765/overriding-other-rmul-with-your-classs-mul">Overriding other __rmul__ with your class's __mul__</a> but I am under the impression that this is a more general problem then only numerical data. Also that is not answere... | <p>By default, NumPy assumes that unknown object (not inheriting from ndarray) are scalars, and it needs to "vectorize" multiplication over each element of any NumPy arrays.</p>
<p>To control the operations yourself, you need to set either <code>__array_priority__</code> (most backwards compatible) or <code>__array_uf... | python|arrays|python-3.x|numpy|array-broadcasting | 3 |
8,793 | 9,683,340 | GDAL: Get pointer/handle of underlying C object | <p>I have the following setup:</p>
<ul>
<li>GDAL library with Python bindings (SWIG)</li>
<li>Some glue code (Python)</li>
<li>A C library, interfaced with ctypes</li>
</ul>
<p>I want to pass the underlying dataset pointer/handle of the SWIG <code>Dataset</code> object to my C library. How can I retrieve this pointer... | <p>It was actually quite easy, and I hope that my solution is portable. Given, that my C function definition looks somewhat like this:</p>
<pre><code>int myfunc(GDALDatasetH ds);
</code></pre>
<p>Then my <code>ctypes</code> definition is like this:</p>
<pre><code>_lib = C.LibraryLoader(C.CDLL).LoadLibrary(lib_path)... | python|swig|ctypes|gdal | 1 |
8,794 | 28,197,347 | Python: How do i log requests to multiple files | <p>I'm writing a web-crawler and having an issue, I would like to log each different level of message to its own log file.</p>
<p>I thought this would work but it only creates 'crawler-debug.log'</p>
<pre><code>logging.basicConfig(level=logging.DEBUG, filename='crawler-debug.log')
logging.basicConfig(level=logging.WA... | <p>You will need to create a file handler for each log level. Formatting can be applied to each handler to add the timestamp. <a href="https://docs.python.org/2/howto/logging-cookbook.html#multiple-handlers-and-formatters" rel="nofollow noreferrer">Python Logging Cookbook - Multiple handlers and formatters</a></p>
<p>... | python|logging | 0 |
8,795 | 32,942,723 | How to extract content from webpage as seen from browser using python | <p>I am trying to extract the data that is on this website "<a href="https://www.ncbi.nlm.nih.gov/nucleotide/209750423?report=genbank#" rel="nofollow">https://www.ncbi.nlm.nih.gov/nucleotide/209750423?report=genbank#</a>". When I use urllib to extract the content, I am able to extract data that which I get by choosing ... | <p>Data are loaded by js so you can get the data below:</p>
<pre><code>import requests
from pyquery import PyQuery
r = requests.get("https://www.ncbi.nlm.nih.gov/sviewer/viewer.fcgi?val=209750423&db=nuccore&dopt=genbank&extrafeat=976&fmt_mask=0&retmode=html&withmarkup=on&log$=seqview&m... | python|extract|webpage | 1 |
8,796 | 14,328,338 | Python - why the button sometime works and sometime fails to execute all the logic assigned? | <p>In my python script i have such button, its very weired when i press the button, it sometimes works but sometimes fails to do the self.buttononTop() call and takes a while to execute <code>subprocess.call(...)</code> only what it does correctly is the part <code>urllib2.urlopen</code> all the rest fails, its not sta... | <p>Have to use as multi-threading.</p>
<pre><code>import threading
def task1():
urllib2.urlopen(blabla)
class bla:
def disconnectButton(self, w):
print "Window Resize"
self.buttononTop()
#urllib2.urlopen(disconnect_url).read()
t1 = threading.Thread(target=task1)
subprocess.call("/var/tmp/rest... | python|linux|python-2.7 | 1 |
8,797 | 34,855,440 | How to remove statements form Django query_utils Q? | <p>I know how to chain together certain filters for my qs.</p>
<pre><code>from django.db.models import Q
f = models.Q(public=True)
f |= models.Q(owner=user)
f == models.Q(public=True) | models.Q(owner=user)
</code></pre>
<p>I also want to remove certain filters, but I don't know how. Something like this:</p>
<pre... | <p>Like this:</p>
<pre><code>f = models.Q(public=True) | ~models.Q(owner=user)
</code></pre>
<p>the <code>~</code> means <code>NOT</code></p> | python|django | 0 |
8,798 | 27,160,020 | Why do Ipython cells stop executing? | <p>I'm sure this is a very newb question, so I apologize in advance. I'm trying to use ipython notebook for a group project. The program we are building is fairly large and pulls in a large number of external datasets. Much of the time, Ipython seems to stop working. I'll try to run a cell or multiple cells and nothing... | <p>The asterisk next to a cell <code>[*]</code> indicates that the cell is currently executing. While IPython provides each notebook with it's own kernel, there is only <em>one</em> kernel per notebook. When that kernel is busy executing code (either a cell, or a series of cells) it cannot accept or run any further cod... | python|ipython|ipython-notebook | 20 |
8,799 | 23,054,326 | Need to input text into a POST website using python | <p>I need to input text into the text boxon this website:</p>
<pre><code>http://www.link.cs.cmu.edu/link/submit-sentence-4.html
</code></pre>
<p>I then require the return page's html to be returned.
I have looked at other solutions. But i am aware that there is no solution for all.
I have seen selenium, but im do no... | <p>Check out the requests module. It is super easy to use to make any kind of HTTP request and gives you complete control of any extra headers or form completion payload data you would need to POST data to the website you want to.</p>
<p>P.S. If all else fails, make the request you want to make to the website in a web... | python|selenium|beautifulsoup | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.