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 |
|---|---|---|---|---|---|---|
6,400 | 59,141,054 | Problem reproducing MATLAB code in Python involving a for loop | <p>I have constructed the following code using MATLAB:</p>
<pre><code>numero=60;
a=zeros(numero,1)
b=zeros(numero+1,1)
for i=1:numero+1
a(i)=-cos(pi*(i-1)/numero)
end
figure
plot(a,b, '*')
</code></pre>
<p>It serves to calculate the nodes of a Chebyshev polynomial of order <code>numero</code> and store it in a... | <p>The issue comes about in this line:</p>
<pre><code>for i in range(numero+2)
</code></pre>
<p>compared to:</p>
<pre><code>for i=1:numero+1
</code></pre>
<p>The variable <code>i</code> is starting at <code>0</code>, and really we want it to start at <code>1</code>. We can see that this causes the error from the fo... | python|matlab|numpy|for-loop|sympy | 3 |
6,401 | 63,148,272 | Updating Crontab from Dockerfile in flask | <p>In one of the containers in Docker, it's running a flask application with API endpoints exposed. I'm trying to configure a cron by updating crontab file to consume the api on regular intervals.</p>
<p>Dockerfile</p>
<pre><code>FROM nikolaik/python-nodejs:python3.7-nodejs14
ENV APP /deploy
.....
.......
COPY . /$AP... | <p>My guess would be that you did not delete the container instances and used:</p>
<pre><code>docker compose stop
</code></pre>
<p>instead of</p>
<pre><code>docker compose down
</code></pre>
<p>In that case the container will only be stopped and not removed. when then running the compose up command the containers will ... | python|docker|flask|cron|scheduled-tasks | 0 |
6,402 | 63,148,141 | Python regular expression to format source file to destination file format | <p>I have text file of the below source format. i want to convert it to text file which has the destination format. I'm able to print out just the first pattern. Can someone help how to iterate through the source file to reach until the nth pattern and print result in the destination format?</p>
<p>source file</p>
<pre... | <p>An approach with <a href="https://docs.python.org/2/library/re.html" rel="nofollow noreferrer"><code>re</code></a>, that maybe will be helpful for you</p>
<pre><code>import re
patterns = re.findall(r'(?s)pattern_(\d)_begin\n(.*)\npattern_\1_end',yourstring)
for p in patterns:
for line in p[1].split('\n'):
... | python|regex|loops|formatting|python-2.6 | 1 |
6,403 | 73,225,330 | How do I Convert A GeoJSON List of Coordinate Pairs from Polygons to MultiPolygons? | <p>this is my first SO question so bare with me on it. I'll follow up with any questions you may have about the dataset.
Essentially, I'm trying to export Polygons from a GeoJSON format in Python to MultiPolygons. I'm not dealing with inner rings in this situation and instead, only dealing with separate polygons that a... | <p>For anyone interested, the solution to this problem would be to create a function that runs through each coordinate pair and assigns a list of polygons based on similarity between coordinate x and coordinate y where the parameter 'bag of coordinates' is our list of coordinates.</p>
<pre><code>def coordsToMultiPolygo... | python|gis|geojson | 1 |
6,404 | 15,590,686 | Python 3.3 readlines truncating text file | <p>I am working with Python 3.3 using PyDev for Eclipse, Alright, so this is my code:</p>
<pre><code>countdata = open(countfilename, 'r')
countlist = countdata.readlines()
print(len(countlist))
genecountline = wordlist(countlist[-1])
print(genecountline)
</code></pre>
<p><code>countfilename</code> refers to a rather ... | <p>If you're not reading from a static text file but from the one that generates each time you run your program, it could be that you don't close that file (in which case everything might not have been written to it). If you don't want to close it, you could flush it (.flush() method). </p>
<p>You should post the code... | python|python-3.3 | 1 |
6,405 | 5,708,634 | How can I elegantly implement version checking in Python without throwing off indentation? | <p>I'd like to very elegantly integrate version checking in Python.</p>
<p>I don't want a version checking routine to throw off the indentation of all of my code, however.</p>
<p>I.e.</p>
<pre><code>if old_version:
print 'hey, upgrade.'
else:
# main body of whole script
</code></pre>
<p>In the above implementa... | <p>You can do</p>
<pre><code>import sys
if old_version:
print 'hey, upgrade.'
sys.exit(1) # A non-zero code indicates failure, on Unix (sys.exit() exits too, but it returns a 0 [=success] exit code)
# main body of whole script
</code></pre>
<p>This exits the interpreter if the code needs to be upgraded.</p... | python | 7 |
6,406 | 6,159,900 | Correct way to write line to file? | <p>How do I write a line to a file in modern Python? I heard that this is deprecated:</p>
<pre><code>print >>f, "hi there"
</code></pre>
<p>Also, does <code>"\n"</code> work on all platforms, or should I use <code>"\r\n"</code> on Windows?</p> | <p>This should be as simple as:</p>
<pre><code>with open('somefile.txt', 'a') as the_file:
the_file.write('Hello\n')
</code></pre>
<p>From The Documentation:</p>
<blockquote>
<p>Do not use <code>os.linesep</code> as a line terminator when writing files opened in text mode (the default); use a single <code>'\n'</cod... | python|file-io | 1,458 |
6,407 | 67,969,292 | I created a website using Flask and there is two html pages how to connect them? | <p>I am new in flask and I would like to connect two pages of html the first one is called index which contains a dropdown list, the second on is called results which show the information as a pie chart
for every option in the index file I would like to assign a different URL such as if you chose week 1 the result file... | <p>Assuming you have the code to get the results:</p>
<pre><code>@app.route("/whatever")
def whatever():
return render_template("get_user_input_on_week.html")
</code></pre>
<p>Then in get_user_input_on_week.html:</p>
<pre><code><form action="/showdata">
<select name="week... | python|html|flask | 0 |
6,408 | 67,614,204 | How to replace scipy.misc.imresize with Pillow in my example? | <p>I read up some threads about <code>scipy.misc.imresize</code> being removed in early versions, and how you have to use Pillow instead. The following is my line of code which is producing the error.</p>
<pre><code>image_gray_resized = scipy.misc.imresize(arr=image_gray, size=fraction, interp='bicubic')
</code></pre>
... | <p>Let's check an old documentation page of <a href="https://docs.scipy.org/doc/scipy-1.2.1/reference/generated/scipy.misc.imresize.html" rel="nofollow noreferrer"><code>scipy.misc.imresize</code></a>:</p>
<ul>
<li><code>arr</code> is the image itself as a NumPy array.</li>
<li><code>size</code> can be
<ul>
<li>an <cod... | python|scipy|python-imaging-library | 1 |
6,409 | 67,934,005 | Pytorch CPU CUDA device load without gpu | <p>I found this nice code Pytorch mobilenet which I cant get running on a CPU.
<a href="https://github.com/rdroste/unisal" rel="nofollow noreferrer">https://github.com/rdroste/unisal</a></p>
<p>I am new to Pytorch so I am not shure what to do.</p>
<p>In line 174 of the module train.py the device is set:</p>
<pre><code>... | <p>In <a href="https://pytorch.org/tutorials/beginner/saving_loading_models.html#save-on-gpu-load-on-cpu" rel="nofollow noreferrer">https://pytorch.org/tutorials/beginner/saving_loading_models.html#save-on-gpu-load-on-cpu</a> you'll see there's a <code>map_location</code> keyword argument to send weights to the proper ... | python|pytorch|gpu | 3 |
6,410 | 67,813,685 | python execute formatted string, SyntaxError: unexpected character after line continuation character | <p>The thing sounded to be pretty simple
I've string, written into file, it's the formatted string as a string <br>
I mean, file looks like this:</p>
<pre><code>f\"Welcome {member.name}\\nNice to see you\"
</code></pre>
<p>So the code sees it like this:</p>
<pre><code>'f"Welcome {member.name}\\nNice to s... | <p>i,ve got it like:</p>
<pre><code>print(f"Welcome {member.name} \nNice to see you")
with open('welcome.txt', 'r') as file:
data = file.read()
for member in members:
exec(data)
</code></pre>
<ul>
<li>print(temp) will give you a None, so i deleted it,</li>
<li>used print on the formatting line inste... | python|syntax-error | 0 |
6,411 | 30,599,101 | Translating mathematical functions from MATLAB to Python | <p>I am currently working on a project which involves translating a program which runs in MATLAB to Python to increase speed and efficiency. However, I have hit a stumbling block. First, I am confused as to what the tilde(~) indicates in MATLAB, and how to represent that in a corresponding way in python. Second, I have... | <p>If you're using <code>numpy</code>, then you also use <code>~</code> to invert things just like MATLAB. See: <a href="https://stackoverflow.com/questions/3428014/what-does-the-unary-operator-do-in-numpy">What does the unary operator ~ do in numpy?</a>. The <code>sign</code> function also exists in <code>numpy</co... | python|matlab|numpy|sum|sign | 5 |
6,412 | 42,597,243 | Bootstrap variable passed over to Flask | <p>First of all sorry if that's a silly question, but I am kind of stuck..</p>
<p>I want to pass a couple of variables from my HTML/Bootstrap page to Flask. The variables are obtained in a form.</p>
<p>The variable is to be selected from a dropdown. Once the variable is selected from mySQL2 it should be stored in <co... | <p>Before form submission can't get the submit values. To get posted data in view use:</p>
<pre><code>request.form["selectcustomer"]
</code></pre>
<p><em>note:</em> html <code>select</code> tag should have a name attribute <code><select name="selectcustomer" ...></code> so you can get value with name not the se... | python|html|twitter-bootstrap|flask|flask-wtforms | 0 |
6,413 | 66,651,497 | Most efficient way to replace every possible combination of up to N items in a tuple in Python? | <p>If I have a tuple of a generic length. Given a specific N, what is the most efficient way to create every single possible combination of the tuple where the token <code>""</code> replaces up to N items in the tuple?</p>
<p>For example, non efficient way of doing this</p>
<pre><code> def create_feature_grap... | <p>Binaries! What you are looking for is basically: a letter is either replaced(1) or not (0).</p>
<p>All possible replacements give you 2^N of possible results, so lets iterate over them and replace each letter of input, where corresponding binary index is 1.</p>
<pre><code>def replacements(data, N = 0):
for i in ... | python | 0 |
6,414 | 72,156,735 | Pandas create a new column containing index based on the value of another one | <p>I have a dataframe like this:</p>
<pre><code>a
4.0
5.5
5.5
6.7
7.9
7.9
9.4
</code></pre>
<p>I want to a add a new column named <code>b</code>, 'indexing' the values in first one.
The new dataframe would look like:</p>
<pre><code>a b
4.0 1
5.5 2
5.5 2
6.7 3
7.9 4
7.9 4
9.4 5
</code></pre>
<p>Thank you.</p> | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.factorize.html" rel="nofollow noreferrer"><code>pd.factorize</code></a>:</p>
<pre class="lang-py prettyprint-override"><code>codes, uniques = pd.factorize(df['a'])
df['b'] = codes
</code></pre>
<p>(or <code>df['b'] = codes + 1</c... | pandas|pandas-groupby | 2 |
6,415 | 72,156,750 | Telegram bot to send auto message every n hours with python-telegram-bot | <p>I am quite new in building bots so I created a very simple Telegram bot and it works great but can't figure out how to make the bot send messages every n minutes or n hours when /start_auto command is initiated.</p>
<p>I made a workaround with while loop but it looks stupid and during the loop users won't be able t... | <p><code>python-telegram-bot</code> has a built-in feature for scheduling tasks, called <code>JobQueue</code>. Please have a look at <a href="https://github.com/python-telegram-bot/v13.x-wiki/wiki/Extensions-%E2%80%93-JobQueue" rel="nofollow noreferrer">this wiki page</a> for more info.</p>
<hr />
<p>Disclaimer: I'm cu... | python|scheduled-tasks|telegram|telegram-bot|python-telegram-bot | 2 |
6,416 | 65,516,220 | What is the use of add_callback_threadsafe() method in pika? | <p>From the description in the <code>pika</code> documentation, I can't quite get what <code>add_callback_threadsafe()</code> method does. It says, "Requests a call to the given function as soon as possible in the context of this connection’s thread". Specifically, which event does this callback get associate... | <p>The reason why the method exists:
<a href="https://stackoverflow.com/questions/55373867/how-to-add-multiprocessing-to-consumer-with-pika-rabbitmq-in-python">How to add multiprocessing to consumer with pika (RabbitMQ) in python</a></p>
<p>If you use the same rabbit connection/channel with multiple threads/processes t... | rabbitmq|pika|rabbitmq-exchange|python-pika | 1 |
6,417 | 50,564,928 | How to use sentence vectors from doc2vec in keras Sequntial model for sentence sentiment analysis? | <p>Creating doc2vec model</p>
<p>x:List of Sentences(Movie reviews)</p>
<p>length of x =2000</p>
<pre><code>doc2vec_data = []
for line in x:
temp = ''.join(str(token) for token in line.lower())
doc2vec_data.append(temp)
File = open('doc2vec_data.txt', 'w',encoding="utf-8")
for item in doc2vec_data:
File.write("%s\... | <p>You are already converting the sentences to vectors and re-attempting it with the Keras model. Its complaining that your Embedding layer is not receiving correct indices because it's already embedded. Assuming you have <code>vec.shape == (samples, doc2vec_vector_size)</code> you'll need to remove Embedding because i... | python|keras|deep-learning|sentiment-analysis | 2 |
6,418 | 35,227,584 | Add key/values to dictionary using condition | <p>I have a list of items that I'm adding to dictionary below:</p>
<pre><code>COLS = ['CUST', 'MODEL', 'SN', 'DATE', 'CHARGE', 'QTY', 'TOTAL']
with open('UserfeeInvoicing.csv', 'r') as infile:
ranpak_dict = {
row[2]: dict(zip(COLS, row)) for row in csv.reader(infile)
}
</code></pre>
<p>Is there anyway... | <p>Rather than use <code>csv.reader()</code>, use <a href="https://docs.python.org/2/library/csv.html#csv.DictReader" rel="nofollow"><code>csv.DictReader()</code> object</a>. That object makes it a lot easier to both create your dictionaries and to filter the rows; your code, refactored to use <code>DictReader()</code>... | python|csv|dictionary|conditional-statements | 3 |
6,419 | 26,866,946 | what is wrong about this script? | <p>I am really confused what is exactly wrong. for first part of if the answer is always 0.0 , even separated part of formula are not 0.
what is wrong here?</p>
<pre><code>import numpy as np
def concpt(E,E0,theta):
rad= theta*(np.pi/180)
M=np.cos(rad)
print(M)
thrcondtion= 0.5*E*E0*(1-M)
if thrcon... | <p>Try:</p>
<pre><code>>>> print(3/16)
</code></pre>
<p>at a Python prompt.</p>
<p>It will print</p>
<pre><code>0
</code></pre>
<p>Because the calculation is done using integers, since <code>3</code> and <code>16</code> are both integers. You need e.g. <code>3.0 / 16</code> there, to get <code>0.1875</cod... | python|numpy|integer-division | 1 |
6,420 | 45,210,839 | Setting all values in a cube more than a certain number to zero | <p>I'm trying to set all values in a cube more than a certain number to zero.</p>
<p>I've tried the following noddy way:</p>
<pre><code>cube_tot_lo.data = np.where(cube_tot_lo.data < 1.0e19, cube_tot_lo.data, 0.0)
</code></pre>
<p>but it is a large cube and kills the memory. I was wondering if there is a nicer w... | <p>(1) A more usual numpy idiom would be:</p>
<pre><code>cube.data[cube.data < threshold_value] = 0.0
</code></pre>
<p>I think that should make <em>some</em> impression on the memory problem, as it doesn't compute an entire new floating-point array to assign back.<br>
However, it does need to create a data-sized b... | python|python-2.7|python-iris | 2 |
6,421 | 64,833,155 | creating pivot table in pandas | <p>Can anyone help me to create a pandas pivot table to get the below ouput</p>
<p>please find the data frame</p>
<p><a href="https://i.stack.imgur.com/IyzWU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IyzWU.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/... | <p>Use the following code:</p>
<pre><code>result = pd.crosstab(index=df['Product line'], columns=df.City,
values=df['Stocked Unit'], aggfunc=np.sum, normalize='columns')\
.applymap(lambda x: f'{100 * x:.2f}%').rename_axis(
columns={'City': None}, index={'Product line': 'Row Labels'})
</code></pre>
<p>Import... | pandas|pivot | 1 |
6,422 | 61,503,720 | Best practice to pass PyTorch device name to model | <p>Currently, I separated <code>train.py</code> with <code>model.py</code> for my deep learning project. </p>
<p>So for the datasets, they are sent to cuda device inside the <strong><code>epoch for loop</code></strong> like below.</p>
<p><code>train.py</code></p>
<pre><code>...
device = torch.device('cuda:2' if torc... | <p>You can add a new attribute to <code>MyModel</code> to store the <code>device</code> info and use this in the <code>skip_conn</code> initialization.</p>
<pre><code>class MyNet(nn.Module):
def __init__(self, in_feats, hid_feats, out_feats, device): # <--
super(MyNet, self).__init__()
self.conv1 = GCNConv(... | pytorch | 1 |
6,423 | 61,303,036 | How to properly import an SVG path to manim | <p>I am working on a logo on Inkscape and I would like to import it to manim. The file does import properly with all the paths of the SVG but a weird thing is happening. </p>
<p>My code for running the file is this:</p>
<pre><code>class U_letter(Scene):
def construct(self):
letter = SVGMobject("u_letter")... | <p>As of current date (June 3, 2020), There is no "proper" way to import a SVG object, as you see, you can you use SVGMObject and it will work most of the time, but as manim parses the path itself it ignores many things from the SVG specification in it's implementation, so you would have to fix it yourself or wait unt... | python|svg|inkscape|manim | 0 |
6,424 | 61,303,580 | python Program is saying 2 numbers are different when they are the same | <p>Thanks for the help in advance.</p>
<p>I compare 2 variables which hold numbers with the operation !=</p>
<p>the program takes input like this</p>
<pre><code>4
1 2 3 4
</code></pre>
<p>Then the program should return the highest product exluding a square product. In this case the result should be 12(4x3) not 16(4... | <p>You compare string vs. integer which is always <code>False</code>:</p>
<blockquote>
<pre><code>for integer1 in a: # integer1 is a string
product = int(integer1) * n
if n != integer1: # n is a number
</code></pre>
</blockquote>
<p>Fix:</p>
<pre><code>def max_pairwise_product():
... | python|python-3.x | 1 |
6,425 | 57,920,960 | Wagtail: How to get image rendition url and pass it along with other fields in json? | <p>I am passing all my model's data to the context of the template to use it in a small vue instance:</p>
<pre><code>data = serializers.serialize("json", MyModel.objects.child_of(self).live().public())
</code></pre>
<p>My model has an image:</p>
<pre><code>header = models.ForeignKey(
"wagtailimages.Image",
... | <p>I came back to this and realized my first answer was garbage. I think what you can do is create a property which get's stored as an attribute.</p>
<pre><code>@property
def rendition_url(self):
url = self.header.get_rendition('fill-300x186|jpegquality-60').url
return url
</code></pre>
<p>Then you have to bu... | python|wagtail | 1 |
6,426 | 57,821,782 | Developing ROS Nodes in individual Docker Containers? | <p>I am currently planning a sizeable ROS project which will contain upwards of 15 Nodes developed either in Python2.x or C++ talking to each other. We will try to isolate different tasks as individual nodes to guarentee unit-testability and modularity and to improve reusability for future projects.</p>
<p>The questio... | <p>Creation of isolated ROS nodes in docker containers is not as complicated and already done before:</p>
<ul>
<li><a href="https://answers.ros.org/question/280874/how-can-i-run-two-ros2-nodes-each-in-a-separate-docker-container/" rel="nofollow noreferrer">How can I run two ROS2 nodes each in a separate docker contain... | python|c++|docker|devops|ros | 2 |
6,427 | 69,564,292 | Python unix sockets doesn't work ? Can't find any explanation here | <p>I have running mpv player which supports IPC control throught unix sockets, and it works shiny well:</p>
<p><code>$ echo '{ "command": ["set_property", "pause", true ] }' | socat - /tmp/mpvsocket</code></p>
<blockquote>
<p>{"request_id":0,"error":"success"}... | <p>Comment from @Selcuk is correct. Just needed to add "\n".</p> | python|networking|unix-socket | 0 |
6,428 | 69,381,709 | Find the cumulative number of missing days for a datetime column in pandas | <p>I have a sample dataframe as given below.</p>
<pre><code>import pandas as pd
data = {'ID':['A', 'A', 'A','A','A','A' ,'B','B','B','B','B'],
'Date':['2021-09-20 04:34:57', '2021-09-20 04:37:25', '2021-09-22 04:38:26', '2021-09-23
00:12:29','2021-09-22 11:20:58','2021-09-25 09:20:58','2021-03-11 21:20:00','2... | <p>Answer below will fail with multiple consecutive missing days (Thanks Ben T). We can solve this by using <code>resample</code> per group, than count the <code>NaT</code>:</p>
<pre><code>dfg = df1.groupby("ID").apply(lambda x: x.resample(rule="D", on="Date").first())
dfg["Date"... | python-3.x|pandas|dataframe|datetime|data-science | 1 |
6,429 | 55,346,510 | How do I write scikit-learn dataset to csv file | <p>I can load a data set from <code>scikit-learn</code> using</p>
<pre><code>from sklearn import datasets
data = datasets.load_boston()
print(data)
</code></pre>
<p>What I'd like to do is write this data set to a flat file (<code>.csv</code>)</p>
<p>Using the <code>open()</code> function,</p>
<pre><code>f = open('b... | <p><code>data = datasets.load_boston()</code> will generate a dictionary. In order to write the data to a <code>.csv</code> file you need the actual data <code>data['data']</code> and the columns <code>data['feature_names']</code>. You can use these in order to generate a pandas dataframe and then use <code>to_csv()</c... | python|pandas|scikit-learn | 7 |
6,430 | 55,563,376 | Pytorch. How does pin_memory work in Dataloader? | <p>I want to understand how pin_memory in Dataloader works.</p>
<p>According to the documentation:</p>
<pre><code>pin_memory (bool, optional) – If True, the data loader will copy tensors into CUDA pinned memory before returning them.
</code></pre>
<p>Below is a self-contained code example.</p>
<pre><code>import torchvi... | <p>The documentation is perhaps overly laconic, given that the terms used are fairly niche. In CUDA terms, pinned memory does not mean GPU memory but non-paged CPU memory. The benefits and rationale are provided <a href="https://devblogs.nvidia.com/how-optimize-data-transfers-cuda-cc/" rel="noreferrer">here</a>, but th... | deep-learning|pytorch|torch | 62 |
6,431 | 55,462,778 | Pandas groupby/pivot by date on multiple columns | <p>I'm trying to get the following output from this df. It was constructed from a django query which was converted to a df:</p>
<pre><code>messages = Message.objects.all()
df = pd.DataFrame.from_records(messages.values())
+---+-----------------+------------+---------------------+
| | date_time | error_desc | ... | <p>You can use <code>lambda</code> on multiple columns:</p>
<pre><code>df.groupby('date').apply(lambda x:
pd.Series({'total_count': len(x),
'error_count': (x['error'] == 'Yes').sum(),
'hello_count': (x['greeting'] == 'Yes... | python|pandas | 0 |
6,432 | 57,661,516 | Converting Keras model to multi label output | <p>I have a model which takes in a dataframe which looks like this </p>
<pre><code>image,level
10_left,0
10_right,0
13_left,0
</code></pre>
<p>with model structure like this</p>
<pre><code>base_image_dir = 'extra_data/dr/'
retina_df = pd.read_csv(os.path.join(base_image_dir, 'trainLabels.csv'))
retina_df['PatientId'... | <p>You are trying to train a model with 8 different outputs (length 1 for every output) but your target values is an array of length 8.</p>
<p>The easiest fix is to replace:</p>
<pre><code>output1 = Dense(1, activation = 'sigmoid')(x)
output2 = Dense(1, activation = 'sigmoid')(x)
output3 = Dense(1, activation = 'sig... | python|machine-learning|keras|deep-learning|conv-neural-network | 1 |
6,433 | 42,562,380 | Python Serial Communication Receiving COMMAND UNKNOWN | <p>So I'm trying to control a Thermo Scientific temperature bath over serial (USB-A to USB-B) and when I send a command I get the response "F001" telling me that that command is known. The format is "command" "carriage return" and here is what I have:</p>
<pre><code>ser = serial.Serial('/dev/tty.usbserial-A800dars', 9... | <p>Well as it turns out I was given the incorrect manual by the manufacturer. After finding the correct one and now knowing the correct commands to send over serial all the above code works just fine.</p> | python|serial-port|pyserial | 0 |
6,434 | 42,469,101 | Pandas: filtering by field contained in set | <p>I have a <em>DataFrame df</em> and a set of <em>user_ids: set</em>. How can I choose a slice of <em>df</em> containing only users in the set. Like:</p>
<pre><code>df[df.user_id in user_ids]
</code></pre>
<p>Now working that way because:</p>
<pre><code>'Series' objects are mutable, thus they cannot be hashed
</cod... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow noreferrer"><code>isin</code></a> for <code>boolean mask</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing<... | python|pandas|filter|set | 2 |
6,435 | 54,082,683 | percentile across dataframes, with missing values | <p>I have several pandas dataframes (say a normal python list) which look like the following two. Note that there can be (in fact there are) some missing values at random dates. I need to compute percentiles of TMAX and/or TMAX_ANOM across the several dataframes, for each date, ignoring the missing values. </p>
<pre><... | <pre><code>#dates as indexes
df1.index = pd.to_datetime(dict(year = df1.YYYY, month = df1.MM, day = df1.DD))
df2.index = pd.to_datetime(dict(year = df2.YYYY, month = df2.MM, day = df2.DD))
#binding useful columns
new_df = df1[['TMAX','TMAX_ANOM']].join(df2[['TMAX','TMAX_ANOM']], lsuffix = '_df1', rsuffix = '_df2')
#c... | python|pandas | 0 |
6,436 | 28,774,946 | Selenium Firefox Driver reading from Hosts file | <p>I'm trying to avoid running this particular selenium script in a production environment. When this test is ran manually, I change my /etc/hosts file accordingly. </p>
<pre><code>xx.x.xxx.xx www.url.com
</code></pre>
<p>What is a practical way of passing the test environment IP to the driver? Or perhaps have the... | <p>I'd suggest providing a command line argument that your selenium scripts can reference. This argument can contain the the environment ip address you wish to run your tests against. Or another possible solution would to have a property file included in your selenium project that contains environments you use for test... | python|testing|selenium|selenium-webdriver|automated-tests | 1 |
6,437 | 28,834,921 | Python remove from list the same values | <p>Please help.
I have in input script the differing values and what need only remove the same values.</p>
<p>I do this but there is didn't check the type of value and only just didn't find it.</p>
<p>Example :</p>
<pre><code>import sys
def clean_list(list_to_clean):
c = []
c = list(set(list_to_clean... | <p>Since int 1 and float 1.0 hash to the same value, you need to retain some more information about the object -- it's 'type' is the best candidate here. You can do this in a one liner if you want: </p>
<pre><code>>>> seq = ['asd', 'dsa', 1, '1', 1.0, 'asd', 'dsa', 1]
>>> [pair[1] for pair in {(type... | python|arrays|function | 4 |
6,438 | 14,510,133 | work perfectly in python 2.7.3 but error in python 3 | <p>So, when I run this code in python 2.7.3 with command ./randline.py test.txt this code works fine. However when I try to run this code in python 3 I got an error message "/usr/bin/python: can't open file '3': [Errno 2] No such file or directory"</p>
<pre><code>import random, sys
from optparse import OptionParser
... | <p>Looks like you are running <code>python 3</code> (with a space). You should use <code>python3</code> instead.</p> | python|python-3.x | 5 |
6,439 | 6,341,039 | How to structure a python cmd application which has separate command modules | <p>I'm writing a python command-line tool using the cmd2 module which is an enhanced version of cmd. The tool is an administration application and is used to administer a number of sub-modules.</p>
<p>I'd like to structure the code so that each sub-module has its own class responsible for providing the commands that c... | <p>You may have some luck structuring your SubModules as Plugins to the main ConsoleApp. You'd need a couple of new methods on ConsoleApp. Something like <code>add_command_module(self, klass)</code> which would just append the klass (SubModuleA for example) to some list inside ConsoleApp.</p>
<p>Then in ConsoleApp, ov... | python | 1 |
6,440 | 6,646,331 | Memory leak when running python in Mac OS Terminal | <p>I just ran a python program in the Mac OS Terminal, and there is unusual memory leak.</p>
<p>The program is simple like this:</p>
<pre>
for i in xrange(1000000000, 2000000000, 10):
i2 = i * i
print i, i2, str(i2)[::2]
if str(i2)[::2] == '1234567890':
break
</pre>
<p>When the program is running, it consu... | <p>This isn't a bug; it's actually a feature. Terminal.app, like many other terminal emulators, saves recent output in a buffer so that you can scroll back (with page up or the scroll bar). You can limit how large this is by going to Terminal -> Preferences -> Settings and setting the scrollback limit to something othe... | python|macos|memory-leaks|terminal | 14 |
6,441 | 6,528,263 | Index by word length | <p>My aim was to simply make a hangman game. However, I have been slightly over-ambitious. I want to ask the user to input how long they want the word. Then choose a random word of that length. To index an entire dictionary of that length would take far too long on each iteration. So. I have a dictionary, formatted lik... | <p>It's really not that big of a deal to load an entire dictionary into memory. You can try something like this:</p>
<pre><code>import random
from collections import defaultdict
# load words
index = defaultdict(list)
with open('words.txt') as file:
for line in file:
word = line.strip().lower()
ind... | python|dictionary|indexing|new-operator | 2 |
6,442 | 57,009,965 | Getting semi-transparent text with matplotlib+pgf backend when compiling in LateX | <p>So I am using the <code>pgf backend</code>in matplotlib to include some automatically compiled references to some other parts of my Tex documents (figures, bibliography) in my TeX document.</p>
<pre><code>import matplotlib
matplotlib.use('pgf')
import matplotlib.pyplot as plt
plt.figure()
plt.txt(0.0,0.5,r'Some te... | <p>Thanks to @ImportanceOfBeingErnest I finally made it work with the pgf backend:</p>
<pre><code>import matplotlib
matplotlib.use('pgf')
import matplotlib.pyplot as plt
pgf_with_custom_preamble = {
"text.usetex": True, # use inline math for ticks
"pgf.rcfonts": False, # don't setup fonts from rc parame... | python|matplotlib|latex|pgf | 1 |
6,443 | 15,099,379 | limit input to integer only (text crashes PYTHON program) | <p>Python novice here, trying to limit quiz input to number 1,2 or 3 only.<br>
If text is typed in, the program crashes (because text input is not recognised)<br>
Here is an adaptation of what I have:
Any help most welcome.</p>
<pre><code>choice = input("Enter Choice 1,2 or 3:")
if choice == 1:
print "Your Choice ... | <p>Use <a href="http://docs.python.org/2/library/functions.html#raw_input" rel="noreferrer"><code>raw_input()</code></a> instead, then convert to <code>int</code> (catching the <code>ValueError</code> if that conversion fails). You can even include a range test, and explicitly raise <code>ValueError()</code> if the giv... | python | 8 |
6,444 | 15,372,949 | Preserve ordering when consolidating two lists into a dict | <p>I am using mysqldb to connect to mysql database and I get the metadata/columns in a variable and data/row in another. Now I have to consolidate the list and tuple into a dict and also preserve the order. I know that dicts are orderless but is there any alternative to this?</p>
<pre><code>cursor.description = ['us... | <p>Use an <a href="http://docs.python.org/2/library/collections.html#collections.OrderedDict" rel="nofollow noreferrer"><em><code>OrderedDict</code></em></a>:</p>
<pre><code>from collections import OrderedDict
result = OrderedDict(zip(cursor.description, data))
</code></pre>
<p>Example:</p>
<pre><code>>>> fro... | python|list|dictionary|tuples|mysql-python | 16 |
6,445 | 46,243,954 | How to Send A Consecutive Request by URL : Python-request | <p>I am learning python-request step by step to build a url queries to en.wiktionary.org </p>
<p>I need to build a function that sequentially fetch the url data based on pre-defined key:value dictionary:</p>
<pre><code>Word_Set = {'key1': 'region', 'key2': reason}
</code></pre>
<p>If I put something like this:</p>
... | <p>You need to make a request per word, you can't do it all in one. Simplest way in this case is to loop over the values in your dictionary:</p>
<pre><code>Word_Set = {'key1': 'region', 'key2': 'reason'}
for word in Word_Set.values():
r = requests.get('http://en.wiktionary.org/{}'.format(word))
print(r.url)
</... | python|request | 1 |
6,446 | 49,721,920 | Datetime: Check if date is in 1 week | <p>What I am trying to do is see if <code>date</code> is in 1 week from <code>currdate</code></p>
<pre><code>from datetime import datetime, timedelta
import yagmail
year = datetime.now().year
month = datetime.now().month
day = datetime.now().day
currdate = '{}-{}-{}'.format(year, month, day)
currdate = datetime.strpt... | <p>It is not <code>07</code>. It's <code>07</code> (note the trailing space).</p>
<p>The following change will work:</p>
<pre><code>if int(days[8:11]) == 7:
</code></pre> | python|datetime|timedelta | 2 |
6,447 | 49,649,090 | Separating by <br> tags in get_text() | <p>I am trying to scrape text from a website while keeping its <code><br></code> tags for formatting my output with <code>'\n'</code>s. However, I can't find a way an efficient way to do so. (Note: I can't use <code>get_text(separator='\n')</code> because things like <code><a></code> tags will break it into... | <p>You can create a recursive function which will return all the text including the <code><br></code> tags.</p>
<pre><code>from bs4 import BeautifulSoup, Tag
def get_text_with_br(tag, result=''):
for x in tag.contents:
if isinstance(x, Tag): # check if content is a tag
if x.name == 'br'... | python|python-3.x|web-scraping|beautifulsoup | 4 |
6,448 | 20,910,886 | How to access C structs from a python array | <p>I'm new to python and have been trying to learn it just for this specific project. What I'm doing is using what's essentially an arduino clone and an NRf24 transceiver to send the following struct over the air.</p>
<pre><code>struct SENSOR{
float sensor1;
float sensor2;
float sensor3;
};
struct HEADER{
lon... | <p>Use the <a href="http://docs.python.org/2/library/struct.html" rel="nofollow">struct</a> module.</p>
<p>First, turn your array of integer (byte, really) values into a string representation with something like</p>
<pre><code>''.join(chr(c) for c in recv_buffer)
</code></pre>
<p>...and then pass that string to the ... | python|c|struct|wireless|beagleboneblack | 3 |
6,449 | 53,742,602 | How to get all stored cookies in ones browser with a Python 3 script? | <p>Is there a way to get all stored cookies for a certain browser?</p>
<p>I searched the web but only <a href="https://stackoverflow.com/questions/45721504/how-can-i-read-all-stored-cookies-in-browser">referrals to javascript</a> or something like this
<a href="https://stackoverflow.com/questions/8812420/how-to-get-co... | <p>I think you need this module <a href="https://github.com/borisbabic/browser_cookie3" rel="nofollow noreferrer">https://github.com/borisbabic/browser_cookie3</a>. With that you can simply get list of all cookies for Chrome by:</p>
<p><code>
import browser_cookie3
cookies = list(browser_cookie3.chrome())
</code></p>
... | python|python-3.x|cookies | 4 |
6,450 | 53,625,255 | python crawling beautifulsoup how to crawl several pages? | <p>Please Help.
I want to get all the company names of each pages and they have 12 pages.</p>
<p><a href="http://www.saramin.co.kr/zf_user/jobs/company-labs/list/page/1" rel="nofollow noreferrer">http://www.saramin.co.kr/zf_user/jobs/company-labs/list/page/1</a>
<a href="http://www.saramin.co.kr/zf_user/jobs/company... | <p>So, you want to remove all the <code>headers</code> and get only the <code>string</code> of the company name?
Basically, you can use the <code>soup.findAll</code> to find the list of company in the format like this:</p>
<blockquote>
<pre><code><strong class="company"><span>중소기업진흥공단</span></stro... | python|beautifulsoup|python-requests|web-crawler | 0 |
6,451 | 53,396,193 | Python pandas - boolean filtering. T/F vs. returning the table | <p>I am doing an exercise and have a dataset of school information. I want to filter the data by school year so I have:</p>
<pre><code>data['demographics'] = data['demographics'][data['demographics']['schoolyear'] == 20112012]
</code></pre>
<p>I don't really understand the data['demographics'] at the beginning of the... | <p><code>data['demographics']['schoolyear'] == 20112012</code> tells you if they match or not.</p>
<p>So, <code>[data['demographics']['schoolyear'] == 20112012]</code> gives you a list of <code>True</code> or <code>False</code></p>
<p>So, </p>
<pre><code>data['demographics'][data['demographics']['schoolyear'] == 201... | python|pandas|filter|boolean | 0 |
6,452 | 46,145,562 | Instagram scraping - Unable to get redirected by requests | <p>What I'm trying to achieve is to <strong>obtain</strong> an Instagram <strong>username from an user id</strong>. I'm trying to do this <strong>without</strong> an <strong>Instagram API</strong>, since my app is not approved. As I found out it can be done, at least in a browser, by going to the follow page which redi... | <p>you can try this</p>
<pre><code>follow_url="what_ever_you_put"
cookie={"sessionid":"your_session_id"}
resp=requests.get(follow_url, cookies=cookie , allow_redirects = True)
print(resp.url)
</code></pre>
<p>that is it</p> | python|web-scraping|python-requests|instagram | 1 |
6,453 | 45,921,561 | Dynamically accessing a pandas dataframe column | <p>Consider this simple example</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'one' : [1,2,3],
'two' : [1,0,0]})
df
Out[9]:
one two
0 1 1
1 2 0
2 3 0
</code></pre>
<p>I want to write a function that takes as inputs a dataframe <code>df</code> and a column <code>myc... | <p>You pass a string as the second argument. In effect, you're trying to do something like:</p>
<pre><code>df.'two'
</code></pre>
<p>Which is invalid syntax. If you're trying to dynamically access a column, you'll need to use the index notation, <code>[...]</code> because the dot/attribute accessor notation doesn't w... | python|pandas|dataframe|dynamic|accessor | 4 |
6,454 | 45,966,234 | In python, if extract a tar.gz file, how to get or set the name of the result file | <p>My question is like:
when use:</p>
<pre><code>import tarfile
tar = tarfile.open("sample.tar.gz")
tar.extractall()
tar.close()
</code></pre>
<p>if the file before compress called "sampleFolder", after I doing the above steps, how to return the "sampleFolder" name, better with its full path, or how to set the resul... | <p>It will be extracted to the working directory by default: </p>
<pre><code>import os
os.getcwd()
</code></pre>
<p>So, the path to the extracted data is:</p>
<pre><code>from pathlib import Path
extracted_to_path = Path.cwd() / 'sampleFolder'
</code></pre>
<p>To extract in a different location:</p>
<pre><code>with... | python|tarfile|compression | 8 |
6,455 | 46,163,333 | "Import Error: cannot import name 'unicode_literals' " | <p>Sorry if this is a dumb question but I'm trying to import and open a CSV using pandas in Python. Whenever I hit run I get the syntax error "cannot import name 'unicode_literals'". I have no idea why that is happening and I haven't been able to find any source online which details what this error means.</p>
<p>This ... | <p>You're on the right track! The only thing you have to do is add another parameter to open(). This would yield: </p>
<pre><code>import pandas as pd
with open(r"FILEPATH\File.csv", encoding='utf-8') as rawData:
pd.read_csv(rawData)
</code></pre> | python|python-3.x | -1 |
6,456 | 54,801,513 | How can I download Anaconda for python 3.6 | <p>I was working on Tensorflow object detection project, for this I am using Anaconda 3 with python 3.7 but I am facing some issues while running object detection demo, I read couple of posts here on stackoverflow and found that it can be solved by using Anaconda with python 3.6 but this version is not available at Ana... | <p>As suggested <a href="https://stackoverflow.com/questions/52584907/how-to-downgrade-python-from-3-7-to-3-6">here</a>, with an installation of the last anaconda you can create an environment just <a href="https://stackoverflow.com/a/54801571/1534017">like Cleb explained</a> or downgrade python :</p>
<pre><code>conda ... | python|anaconda | 36 |
6,457 | 54,784,046 | Beginner Python Script to ssh into remote network device and run multiple commands | <p>Please pardon me as I am a very new to any programming language. I have around 25 network devices combination of cisco, juniper, linux etc which i need to remotely access and run some basic cli commands to get the output. Individually SSHing in to the devices will take long time. Can some tell me where to start this... | <p>Try the following:</p>
<pre><code>pip install paramiko
</code></pre>
<p>then in your script:</p>
<pre><code>import base64
import paramiko
key = paramiko.RSAKey(data=base64.b64decode(b'AAA...'))
client = paramiko.SSHClient()
client.get_host_keys().add('ssh.example.com', 'ssh-rsa', key)
client.connect('ssh.example.... | python|junos-automation|pyez | 1 |
6,458 | 73,640,045 | How can i filter a given numpy array for a value and put the remaining values of the array into a new one? | <p>i would like to know why this code doesnt work...
I dont know why it doesnt allow me to use the if condition in this case.</p>
<pre><code>a = np.array(range(30)).reshape(3,10)
a[:,1] = -1 #random values set to -1
a[:,6] = -1
a[:,7] = -1
print(a)
b = []
for i in a:
if i !=-1:
b.append(True)
b --> Value... | <p>The reason you are getting this error is because the element <code>i</code> in <code>a</code> is still a <code>numpy</code> array. The <code>!=</code> operator used in this way needs a single element, so to access these you need to put an additional layer <code>for j in i:</code> and then change the following line w... | python|arrays|numpy|if-statement | 1 |
6,459 | 40,964,416 | Python Tkinter Stippling an arc | <p>I am trying to make a chess game in Tkinter using python. For shading on the pieces, I intend to use stippling, however, although the stipple pattern appears on one of the shapes, it does not work on the arc. Here is the relevant code:</p>
<pre><code>from Tkinter import *
master = Tk()
win = Canvas(master, width=8... | <p>It looks like this is something not directly possible in most Tkinter versions, at least on a Windows platform.</p>
<p>From: <a href="http://www.scoberlin.de/content/media/http/informatik/tkinter/x3009-options.htm" rel="nofollow noreferrer">http://www.scoberlin.de/content/media/http/informatik/tkinter/x3009-options... | python-2.7|tkinter|tkinter-canvas | 1 |
6,460 | 40,955,045 | The simplest way to install Keras/Theano on Windows 10 with Python 3.5 | <p>The past two days have been a <strong>nightmare</strong> trying to follow the Theano installation guide for Windows (<a href="http://deeplearning.net/software/theano/install_windows.html" rel="nofollow noreferrer">http://deeplearning.net/software/theano/install_windows.html</a>). Specifically, getting Keras to work ... | <p>Now, the specific steps to get Keras working, this will simply require a clean install. </p>
<ol>
<li>Destroy every shred of Python on your computer :)</li>
<li>Install Anaconda3</li>
<li>Open CMD prompt and type</li>
</ol>
<blockquote>
<pre><code>conda install --yes numpy scipy mkl-service nose sphinx m2w64-gcc l... | windows|theano|python-3.5|keras | 0 |
6,461 | 31,049,042 | how to merge two data structure in python | <p>I am having two complex data structure(i.e. _to and _from), I want to override the entity of _to with the same entity of _from.
I have given this example.</p>
<pre><code># I am having two data structure _to and _from
# I want to override _to from _from
_to = {'host': 'test',
'domain': [
{
... | <p>It's quite simple:</p>
<pre><code>_to.update(_from)
</code></pre> | python|dictionary|recursion|data-structures|iterator | 7 |
6,462 | 31,117,261 | DeprecationWarning: Module scipy.linalg.blas.fblas is deprecated, use scipy.linalg.blas instead | <p>I've just now installed theano on my machine but when i try to use it - i.e <code>import theano</code>
I get this 'DeprecationWarning':</p>
<pre><code>/usr/lib/python2.7/dist-packages/scipy/lib/_util.py:35: DeprecationWarning: Module scipy.linalg.blas.fblas is deprecated, use scipy.linalg.blas instead
Deprecation... | <p>You could avoid a Deprecation Warning. If you don't want it to show up you could add the following to your code.</p>
<pre><code>import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
</code></pre> | python|numpy|scipy|theano | 0 |
6,463 | 29,046,442 | Debugger not moving to next line after input()? | <p>I am currently learning python from invent with python!
I am on chapter 7 and here is the link to it!
<a href="https://inventwithpython.com/chapter7.html" rel="nofollow">https://inventwithpython.com/chapter7.html</a></p>
<p>I am doing the exercise Find the bug. I am having a problem at line answer = input() given i... | <p>I don't have your debugger at hand, so, I can't confirm that. But, as a wild guess, and assuming you performed the the various operations in the required order:</p>
<p>As of myself, I would <em>step over</em> (pressing the <code>over</code> button). Not <em>step into</em> (pressing the <code>step</code> button).</p... | python|python-3.x | 0 |
6,464 | 8,973,003 | checking if element is in list in gae template | <p>I have class:</p>
<pre><code>class Article(db.Model):
visitedBy = db.ListProperty(int)
context = {
"article": Article(),
"id": 3
}
</code></pre>
<p>In template I try do it:</p>
<pre><code>{% if id in article.visitedBy %}
<p>Eureka</p>
{% endif %}
</code></pre>
<p>But I got error:</... | <p>The problem was older version of django. Using this tutorial </p>
<p><a href="http://code.google.com/intl/pl/appengine/docs/python/gettingstartedpython27/" rel="nofollow">http://code.google.com/intl/pl/appengine/docs/python/gettingstartedpython27/</a></p>
<p>I change version to newer and now it works very well.</p... | python|google-app-engine|templates | 0 |
6,465 | 51,582,654 | subplot using automatic resizing | <p>looking for some "magic" command that make the maps of the subplots (2x2 in my case) well speared not too much but with the right spacing in order to be considered "quality plot" I found that i can set all using the option rect inside <code>plt.tight_layout</code> I spend time to find this parameters : <code>plt.tig... | <p>Sorry I don't have an answer for automatic resizing but since you asked for some hints, there is one possible solution:</p>
<p><a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots_adjust.html" rel="nofollow noreferrer">https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots_adjust.html</a></... | python|matplotlib | 1 |
6,466 | 51,619,151 | Make Try Catch Faster Python | <p>I am creating a trying to call an api, and setting an except to catch any errors that could happen. However, the program lags on the try part for about a minute. Is there a way to make the code give up on the server and choose the except path in a smaller amount of time?</p>
<p>Edit: Here is the code</p>
<pre><cod... | <p>I assume you're using the requests module. The line 'rsp = requests.get(url)' is actually making the rest api call. There is by default some delay in that call, execution time is likely to vary depending on multiple variables, without additional information it's pointless to explore them all. What you're more than l... | python|api|compiler-errors|runtime|try-catch | 0 |
6,467 | 51,587,727 | Install conda-forge mlxtend - Error in installing mlxtend - Permission Denied | <p>I am trying to install mlxtend from terminal by using following command. </p>
<pre><code>conda install -c conda-forge mlxtend
</code></pre>
<p>everything was working well until I got this following error: </p>
<pre><code>Solving environment: done
### Package Plan ##
environment location: /home/uay/anaconda3
a... | <p>You can try an older version of this command. </p>
<blockquote>
<p>conda install -c rasbt mlxtend</p>
</blockquote>
<p>Change your permission for anaconda to current user. Hope it'll work. </p> | python|anaconda|conda | 0 |
6,468 | 18,881,042 | Flask Python String Not Returning Back To Javascript XMLHttpRequest call | <p>I have a Javacscript XMLHttpRequest call which calls python app.py(using flask). The python script myapp.py returns "Hello World". I see in Chromium Debug that is is returning "hello world". But it's not being return to the Javascript XMLHttpRequest in the responsetext value. </p>
<p>Here is my javascript code:</p>... | <p>I believe that you have been solve this problem.
A way to solve this problem is that you should check the xml.readyState==4 && xml.status == 200</p> | javascript|python|xmlhttprequest|flask|uwsgi | 0 |
6,469 | 19,156,647 | Python and SQLite3: Query must return 2 lists | <p>I'm using this query to verify whether 2 waypoints (x[0] and x[2]) are on the given route:</p>
<pre><code>c.execute("SELECT WPNumber, ROUTE, WPID FROM wpnavrte WHERE ROUTE = ? AND (WPID = ? OR WPID = ?)", (x[1], x[0], x[2]))
</code></pre>
<p>If both waypoints are on the route, the result should be something like <... | <p>Perhaps the simplest is to amend your SQL query slightly (applying a <code>LIMIT 3</code> to lighten the query, then check you've only got 2):</p>
<pre><code>results = list(c.execute("SELECT WPNumber, ROUTE, WPID FROM wpnavrte WHERE ROUTE = ? AND (WPID = ? OR WPID = ?) LIMIT 3", (x[1], x[0], x[2])))
if len(results)... | python|list|python-3.x|sqlite | 1 |
6,470 | 18,796,253 | Why numpy.where doesn't work with 'double' sliced arrays? | <p>I don't understand why 'double' slicing doesn't work with where?</p>
<pre><code>>>> t
array([False, True, True, True], dtype=bool)
>>> np.where(t[:3])
(array([1, 2]),)
</code></pre>
<p>But:</p>
<pre><code>>>> np.where(t[1:3])
(array([0, 1]),)
</code></pre> | <p>That is the expected output, because <code>np.where</code> doesn't know the full context of what you've sliced out. Look first at the sliced arrays:</p>
<pre class="lang-py prettyprint-override"><code>In [384]: t[:3]
Out[384]: array([False, True, True], dtype=bool)
# 0 1 2
In [385]: ... | python|arrays|numpy | 2 |
6,471 | 69,195,257 | Memory allocation to class variable without object creation | <p>Whenever we create objects memory is allocated to the data members and value is stored inside them, for example in the following code the memory is allocated to <code>a</code> only after object <code>emp</code> is created. We cannot access <code>a</code> without allocating memory to it.</p>
<pre><code>class Employee... | <p>The class attribute <code>pi</code> is created when the class is created, not when instances of the class are created.</p> | python|python-3.x|oop | 2 |
6,472 | 69,230,631 | How to create a full window of a 30 days on a pandas dataframe with groupby if some days are missing | <p>I have the following dataframe:</p>
<pre><code>Data type state price
2021-01-01 CHR NSW 1.2
2021-01-01 CHR VIC 8
2021-01-04 Kia NSW 2
2021-01-05 CHR NSW 2
</code></pre>
<p>I applied the below:</p>
<p><code>df_daily_grouped = df_daily.groupby(['type','state])</code></p>
<p>t... | <pre><code>df['Data'] = pd.to_datetime(df['Data'])#Coerce Data to datetime
df1=(df.groupby(['type','state'])['Data'].apply(lambda x: x.reindex(pd.date_range(min(df.Data), max(df.Data),freq='D')))
.reset_index().drop('Data',1).rename(columns={'level_2':'Data'})#Insert missing dates by reindexing in a new df
.m... | python|pandas | 0 |
6,473 | 67,451,508 | error while reading serially incoming data to plot live graph | <p>My input data is like 36,45,32
so when I tried to replace comma by '.' i.e dot, so that it doesn't give me a "cannot convert to float" error, the conversion now would be 36.45.32, which is still not plottable on a live graph.</p>
<p>My code is:</p>
<pre><code>from matplotlib.backends.backend_tkagg import F... | <p>EDIT: based on the comments, I'm significantly revising my answer.</p>
<p>I first thought <code>"36,42,45"</code> was meant to be <code>float(36.42)</code>, ignoring the <code>45</code> part, but now you've clarified that it should be interpreted as <code>x=36</code>, <code>y=42</code> and <code>z=45</code... | python | 0 |
6,474 | 36,588,851 | Creating a X input matrix and y output vector via Python | <p>if I have a dataset which has 5 columns and 10 rows(thus 10 observations), where I want X to be a 10 by 4 input matrix representing the first four columns and y to be a 10 by 1 output matrix representing the last column in my dataset, how would I code that on python?
I want my X matrix to incorporate the columns: c... | <p>You can copy the last column to a vector and drop it from the original dataframe. </p>
<pre><code>import pandas as pd
df = pd.read_csv('file_name.csv')
y = df[['gini']]
X = df.drop(['gini'])
</code></pre>
<p>Or you can simply slice out the 'gini' column without dropping </p>
<pre><code>import pandas as pd
... | python|machine-learning | 1 |
6,475 | 19,665,327 | Virtualenvwrapper installation snow leopard python | <p>I am trying to configure <code>virtualenvwrapper</code> with django1.4. I am following <a href="http://www.jeffknupp.com/blog/2012/10/24/starting-a-django-14-project-the-right-way/" rel="nofollow">this post</a> and am trying to do what it says there:</p>
<pre><code>Admin$ pip install virtualenvwrapper
Requirement a... | <p>It looks like you're trying to use python2.7, but you haven't told virtualenvwrapper about that. Try adding <code>export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python2.7</code> (assuming that's where your python2.7 install is located) before <code>source /usr/local/bin/virtualenvwrapper.sh</code> - i.e.</p>
<pre><code>A... | python|django|installation|virtualenv|virtualenvwrapper | 0 |
6,476 | 19,432,148 | pyramid beaker - session never expired | <p>I am currently developing application in pyramid framework. Following are my settings in development.ini</p>
<pre><code>session.type = file
session.data_dir = data/sessions/data
session.lock_dir = data/sessions/lock
session.key = mykey
session.secret = mysecret
session.cookie_on_exception = true
session.cookie_expi... | <p>Maybe you forgot to setup pyramid_beaker properly during application startup as mentioned here</p>
<ul>
<li><a href="https://pyramid_beaker.readthedocs.org/en/latest/index.html#setup" rel="nofollow">https://pyramid_beaker.readthedocs.org/en/latest/index.html#setup</a> </li>
</ul>
<p>If you want more control, follo... | python|pyramid|beaker | 2 |
6,477 | 19,554,127 | How to gain authentication using tweepy | <p>Q1: I am new to tweepy and I am trying to gain an authentication for twitter data by using tweedy </p>
<pre><code>import tweedy
consumer_key='....'
consumer_secret='....'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret,'https://twitter.com')
token = session.get('request_token')
session.delete('request... | <p>If that's your actual code, you haven't defined anything named <code>session</code> anywhere, so presumably your error is something like this:</p>
<pre><code>NameError: name 'session' is not defined
</code></pre>
<p>Since I have no idea what <code>session</code> is supposed to be in your code, it's hard to tell yo... | python|twitter|tweepy | 2 |
6,478 | 17,096,832 | SSL3 POST with Python | <p>I have a pile of tasks to automate within cPanel. There is a cPanel API described at <a href="http://videos.cpanel.net/cpanel-api-automation/" rel="nofollow noreferrer">http://videos.cpanel.net/cpanel-api-automation/</a> but I tried what I thought was easier for me...
<li>
Based on an answer from skyronic at <a href... | <p>I would use the requests library.</p>
<p>I'm the OP and it's been a while since I posted this. I've solved other related tasks (POST to use Instructure's Canvas API) using the requests library and found that code that had worked with urllib/urllib2 is now much shorter and sweeter.</p>
<p>Someone just upvoted this ... | python|http|post|ssl|urllib2 | 0 |
6,479 | 43,723,150 | Append to dataframe with for loop. Python3 | <p>I'm trying to loop through a list(y) and output by appending a row for each item to a dataframe. </p>
<pre><code>y=[datetime.datetime(2017, 3, 29), datetime.datetime(2017, 3, 30), datetime.datetime(2017, 3, 31)]
</code></pre>
<p>Desired Output:</p>
<pre><code>Index Mean Last
2017-03-29 ... | <p>Try:</p>
<pre><code>y = [datetime(2017, 3, 29), datetime(2017, 3, 30),datetime(2017, 3, 31)]
m = [1.5,2.3,1.2]
l = [0.76, .4, 1]
df = pd.DataFrame([],columns=['time','mean','last'])
for y0, m0, l0 in zip(y,m,l):
data = {'time':y0,'mean':m0,'last':l0}
df = df.append(data, ignore_index=True)
</code></pre>
<... | python-3.x|pandas|datetime|for-loop|dataframe | 2 |
6,480 | 9,449,309 | How to correctly install python-numpy in Ubuntu 11.10 Oneiric | <p>According to Scipy website, in Ubuntu 11.10 numpy and scipy comes pre-packaged so what I did was:</p>
<pre><code>apt-get install python2.7
apt-get install python-numpy
apt-get install python-scipy
</code></pre>
<p>Then I tried to call numpy in Python but get an error:</p>
<pre><code>ImportError: cannot import nam... | <p>It looks like you have a broken numpy install in /usr/local/lib/python2.7/dist-packages, the package manager installs numpy to /usr/lib/pyshared/python2.7</p>
<p>You should remove the broken numpy</p>
<pre><code>$ sudo rm -rf /usr/local/lib/python2.7/dist-packages/numpy
</code></pre>
<p>then the numpy you install... | python|ubuntu|numpy|scipy|python-2.7 | 3 |
6,481 | 39,107,336 | Python tkinter lisbox bold | <p>I am trying to bold all of the entries for my python tkinter listbox.</p>
<p>I have a list and it enters it into a listbox:</p>
<p><code>listbox4.insert(END, Words)</code>
Does anyone know the code to bold these entries?</p> | <pre><code>from Tkinter import *
import tkFont
sf= tkFont.Font(family='Helvetica', size=36, weight='bold')
lb = Listbox(root , bd=1, height=10, font=sf)
</code></pre> | python|user-interface|tkinter | 1 |
6,482 | 52,580,875 | How should I go about scraping the text in dd tags between specific dt tags on a page using BeautifulSoup? | <p>I am trying to extract the text from the dd classes in between the dd tags (which are being used for to mark different dates). I tried a really hackey method but it didn't work consistenly enough</p>
<pre><code>timeDiv = mezzrowSource.find_all("dd", class_="orange event-date")
eventDiv = mezzrowSource.find_all("dd"... | <p>If I understand the question correctly you can use zip():</p>
<pre><code>mezzrowSource = BeautifulSoup(html , 'lxml')
timeDiv = [tag.get_text() for tag in mezzrowSource.find_all("dd", class_="orange event-date")]
eventDiv = [tag.get_text().strip() for tag in mezzrowSource.find_all("dd", class_="event")]
print(dict(... | python|html|python-3.x|web-scraping|beautifulsoup | 1 |
6,483 | 52,502,466 | deleting all the rows from oracle table using python taking infinite amount of time | <p>My piece of code is as follows:</p>
<pre><code>my_dsn_tns = cx_Oracle.makedsn('xyz', 1521, sid='SAMPLE')
connection = cx_Oracle.connect(user='asdasdasd', password='TIGER', dsn=my_dsn_tns)
cur = connection.cursor()
cur.execute("delete from SPS_CX_ONHAND_QTY")
connection.commit()
</code></pre>
<p>When I execute the ... | <p>Not python related or the code you have above but generally in SQL, if you are deleting all the rows in a table you can use <code>truncate table SPS_CX_ONHAND_QTY</code>.
This would be almost instantaneous.</p> | database|python-3.x|oracle|oracle11g|oracle-sqldeveloper | 2 |
6,484 | 47,864,803 | Combining or shortening If statements in python | <p>I defined the following function in order to check the number of new books.</p>
<pre><code>def getNewSellerNumber(isbn):
res=requests.get('http://www.amazon.com/dp/'+isbn)
soup = bs4.BeautifulSoup(res.text,'html.parser')
elements=soup.select('#mediaOlp > div > div > div > div.a-fixed-right-g... | <p>Move return None after loop</p>
<pre><code>for i in selectors:
elements = soup.select(i)
if elements:
return elements[0].text
return None
</code></pre> | python|python-3.x|for-loop|if-statement|beautifulsoup | 3 |
6,485 | 34,040,195 | Python tuples and lists | <p>I have an employee record, and It will ask them to enter their name and job and add both these elements to a tuple. I have done it so that it first adds to a list and then converts to a tuple.</p>
<p>However i want to print only the employee name not the job aswell.</p>
<p>I tried to make the final line <code>prin... | <p>You seem to be iterating over a single <code>record</code>, i.e. a list. It sounds as if you think you have a list of lists ("records"), but you never create that structure.</p>
<p>Obviously if you iterate over strings in a list, build a 1-element tuple from each, and then print it, you will end up printing all the... | python | 1 |
6,486 | 72,713,959 | How do I pass AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY to docker run within a Makefile? | <p>I have defined my config and credentials inside <code>~/.aws/</code> as usual.</p>
<p>In my python script running inside Docker, to get <code>boto3</code> to detect the credentials I run</p>
<pre class="lang-bash prettyprint-override"><code>docker run -e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY my_app_name
</code>... | <p>I don't like it, and I would love to hear of a better way, but I ended up doing the following.</p>
<p>In the Makefile,</p>
<pre class="lang-bash prettyprint-override"><code>export AWS_ACCESS_KEY_ID=$(shell aws configure get aws_access_key_id --profile default)
export AWS_SECRET_ACCESS_KEY=$(shell aws configure get a... | python|amazon-web-services|docker|makefile|boto3 | 0 |
6,487 | 39,773,061 | Python unittesting request.get with mocking, not raising specific exception | <p>I have a simple function that sends a get request to an API, and I want to be able to write a Unit test to assert that the scriprt prints an error and then exits if the request returns an exception.</p>
<pre><code>def fetch_members(self):
try:
r = requests.get(api_url, auth=('user', api_key))
except... | <p>Your function catches and handles the exception:</p>
<pre><code>except requests.exceptions.HTTPError as error:
</code></pre>
<p>This means it'll <em>never</em> propagate further, so your <code>assertRaises()</code> fails. Just assert that <code>sys.exit()</code> has been called, that's enough.</p>
<p>There is als... | python|unit-testing | 1 |
6,488 | 40,700,793 | How to solve error in python program named: AttributeError: 'module' object has no attribute 'TensorFlowLinearClassifier' | <p>This is the code which uses tensorflow library.</p>
<pre><code>import tensorflow.contrib.learn as skflow
from sklearn import datasets, metrics
iris = datasets.load_iris()
print iris
classifier = skflow.TensorFlowLinearClassifier(n_classes=3)
classifier.fit(iris.data, iris.target)
score=metrics.accuracy_score(ir... | <p>They have changed the name to <code>LinearClassifier</code>, therefore this will work</p>
<pre><code>classifier = skflow.LinearClassifier(n_classes=3)
</code></pre> | python|tensorflow | 2 |
6,489 | 40,496,599 | Nest IF needed? in Python | <p>This is my first Python program where I've used if, while and functions. I've also passed parameters. The problem is the IF. Can you help me? I wanted the program to give the user two tries to answer and then end. If correct then it ends but if not correct it doesn't stop, keeps looping.</p>
<p>"""this is a quiz on... | <p>The problem is you aren't incrementing the attempt if they get it wrong the second time. You need another <code>attempt = attempt + 1</code> (Or alternatively <code>attempt += 1</code>) after the <code>break</code></p>
<p>So your <code>elif</code> block would look like:</p>
<pre><code> elif answer != q1Answer:
... | python|if-statement | 0 |
6,490 | 9,738,009 | How to use Websockets with Pyramid and socket.io? | <p>I'm trying to create a simple WebSocket application using Pyramid and socket.io frameworks.
Server-side code:</p>
<pre><code>from pyramid.response import Response
from pyramid_socketio.io import SocketIOContext, socketio_manage
import gevent
def includeme(config):
'''
This method is called on the applicati... | <p>You probably want to look at the latest release of gevent-socketio, and its documentation at <a href="http://gevent-socketio.readthedocs.org/">http://gevent-socketio.readthedocs.org/</a></p>
<p>A major overhaul was done at the PyCon 2012 sprints, by John Anderson, Sébastien Béal and myself.</p> | javascript|python|websocket|socket.io|pyramid | 8 |
6,491 | 1,511,808 | Python distutils - copy_tree with filter | <p>I want to copy a data directory into my distribution dir. <code>copy_tree</code> does this just fine. However, the project is also an svn repository, and I don't want the distribution to have all the .svn files that the data dir has. Is there any easy way to do a <code>copy_tree</code> excluding the <code>.svn</code... | <p>I just used <code>shutil.copytree</code>, which takes an <code>ignore</code> kwd arg.</p> | python|file|distribution|py2exe|distutils | 3 |
6,492 | 32,441,783 | Why does dumping Dataframe to Avro file fail to convert bytearray in Python? | <p>I face the following difficulty :
I am using Spark 1.4.1, Python 2.7.8, and spark-avro_2.10-1.0.0</p>
<p>I am trying to store Python byte-arrays in an avro file using spark-avro. My purpose is to store chains of bytes corresponding to chunks of images that have been encoded using a specific image encoder. </p>
<p... | <p>I was using a bad version of spark-avro. After building the latest, everything works fine. </p> | python|apache-spark|avro|spark-dataframe | 4 |
6,493 | 32,414,431 | Python : Move turtles simultaneously | <p>I'm creating a python program and one of the methods must allow two different turtles to approach or 'try' to converge at a single location </p>
<p>The dependency of whether the turtles converge or not depends on the random speeds of the turtles. </p>
<p>But my immediate concern is trying to make two different tu... | <p>You cannot move two objects simultaneously, you can only simulate it.
This is what I gave my grade 10's as a hint on this same question.
Not perfect, but it shows the concept.</p>
<pre><code>##turtleChase.py
##Randomly place the turtles on the screen
##one turtle will then chase the other as it moves across the scr... | python|turtle-graphics | 2 |
6,494 | 27,962,367 | django virtual environment install brukva, Asynchronous Redis client that works within Tornado IO loop | <p>I am using tornado and redis in one of my project.
I want to install brukva to work redis with tornado.</p>
<p>But didn't found any particular guide to install burkva in ubuntu..</p>
<p>I have tried pip install brukva but it dont install the package..</p>
<p>Can anyone help me on how to install brukva?</p> | <p>You can easily install brükva from GitHub:</p>
<pre><code>pip install git+https://github.com/evilkost/brukva.git
</code></pre> | python|django|redis|tornado | 3 |
6,495 | 44,053,244 | How can I sort and add a rank column within a multiindex? | <p>I have a pandas dataframe that looks like this (<code>df3</code>)</p>
<pre><code>df1 = pd.DataFrame({
"period": [1, 2, 3, 4] * 4,
"cat1": ["A"] * 8 + ["B"] * 8,
"cat2": (["X"] * 4 + ["Y"] * 4) * 2,
"amount": [100, 200, 300, 400, 110, 210, 310, 410, 120, 220, 320, 420, 130, 230, 330, 430],
"total... | <p>IIUC:</p>
<pre><code>df4 = df3.groupby(['cat1', 'cat2', 'period']).agg({
"amount": "max"
})
df4.reset_index(inplace=True)
df4 = df4.sort_values(by=['cat1','cat2','amount'],ascending=[True,True,False])
df4 = df4.assign(percentage=df4.groupby(['cat1','cat2'])['amount'].apply(lambda x: (x.notnull().cumsum()/x.size... | python|pandas | 1 |
6,496 | 44,357,774 | Pycharm Unexpected Result Output | <p>I'm a beginner at Pycharm. I'm using Flask web framework to develop a basic web application. I have written a simple code to display "Hello" on my browser, which it did. Strangely, when I add something to 'Hello', such as 'Hello my name is Yusef' and re-run the program; it won't show any changes, it still appears wi... | <p>You need to clear the browser cache, this isn't a Pycharm issue, just clear your browser cache and you should be fine.
Open in incognito mode to avoid such issues.</p> | python|web-applications|flask|pycharm | 0 |
6,497 | 32,962,112 | Splitting arrays in RDD partitions in Pyspark | <p>I have a single file of 3D numerical data which I read from in chunks (since reading in chunks is faster than a single index). For example say there is an MxNx30 array in 'file', I would create an RDD like this:</p>
<pre><code>def read(ind):
f = customFileOpener(file)
return f['data'][:,:,ind[0]:ind[-1]+1]
... | <p>As far as I understand your description something like this should do the trick:</p>
<pre><code>rdd.flatMap(lambda arr: (x for x in np.rollaxis(arr, 2)))
</code></pre>
<p>Or if you prefer a separate function:</p>
<pre><code>def splitArr(arr):
for x in np.rollaxis(arr, 2):
yield x
rdd.flatMap(splitArr... | python|numpy|apache-spark|pyspark | 2 |
6,498 | 32,784,047 | Numbers logarithmically spaced between two floats in numpy | <p>I am trying to get 1000 numbers logarithmically spaced between two floats (say between 0.674 to 100.0) using python. Purpose of this was to get more numbers closer to 0.674 and after than just few large numbers near 100. I tried using '<em>numpy.logspace</em>' function like following</p>
<p><code>NumberRange = np.l... | <p>The first two arguments of <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.logspace.html" rel="noreferrer"><code>numpy.logspace</code></a> are the <em>exponents</em> of the limits. Use</p>
<pre><code>NumberRange = np.logspace(np.log10(0.674), np.log10(100.0), num=1000)
</code></pre>
<p>Recent v... | python|numpy | 30 |
6,499 | 32,732,535 | Find the count of -1 in each column | <p>I have a pandas data frame. Some entries are equal to -1. How to find the number of times -1 exist in every column in the data frame. Based on that count, I am planning to drop the column.</p> | <p>Since you say you want the result for each column separately, you can use the condition like - <code>df[column] == -1</code> , and then take <code>.sum()</code> on the result of the condition to get the count of <code>-1</code> values for that row. Example -</p>
<pre><code>(df[column] == -1).sum()
</code></pre>
<p... | python|numpy|pandas | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.