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 |
|---|---|---|---|---|---|---|
2,000 | 55,054,049 | python 3 complex mathematics wrong answer | <p>So I was trying to get <code>e^(pi*I)=-1</code>, but python 3 gives me another, weird result:
<code>print(cmath.exp(cmath.pi * cmath.sqrt(-1)))</code>
Result:</p>
<pre><code>(-1+1.2246467991473532e-16j)
</code></pre>
<p>This should in theory return -1, no?</p> | <p><em>(Partial answer to the revised question.)</em></p>
<p>In theory, the result should be <code>-1</code>, but in practice the theory is slightly wrong.</p>
<p>The <code>cmath</code> unit uses floating-point variables to do its calculations--one float value for the real part of a complex number and another float v... | python-3.x|math|cmath | 3 |
2,001 | 54,973,657 | Django display radio button choice | <p>i want to display vaule_fields of my User model as selectable choice radiobuttons, any idea how to do this?</p>
<pre><code>...
</code></pre>
<p>template.html</p>
<pre><code>....
</code></pre>
<p>currently they are displayed as input fields?!</p> | <p>Here is an example of gender choices displayed as radio buttons.</p>
<pre><code>MODELS.PY ********************************************************
#GENDER CHOICES OPTIONS
GENDER_COICES = (
('M', 'Male'),
('F', 'Female'),
('O', 'Other'),
)
gender = models.CharField(max_length=3, choices=GENDER_CO... | python|django|forms | 0 |
2,002 | 54,854,675 | How to fit a set of 3D data points using a third or higher degree of polynomial surface regression? | <p>I have input data points (x,y,z), all positive, and need to fit them to a surface. More specifically, I have to create a grid from the x and y data points and evaluate the data points on this grid to obtain a surface of z-values to plot.</p>
<p>How can I do a 3rd or higher polynomial regression to fit a surface to ... | <p>Here is a non-linear 3D surface fitter with 3D scatter plot, 3D surface plot, and contour plot. This should be all of the graphs.</p>
<pre><code>import numpy, scipy, scipy.optimize
import matplotlib
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm # to colormap 3D surfaces from blue to red
import ... | python|algorithm|regression|surface|non-linear-regression | 1 |
2,003 | 40,802,309 | Geod ValueError : undefined inverse geodesic | <p>I want to compute the distance between two lon / lat points by using <code>Geod</code> class from <code>pyproj</code> library.</p>
<pre class="lang-py prettyprint-override"><code>from pyproj import Geod
g = Geod(ellps='WGS84')
lonlat1 = 10.65583081724002, -7.313341167341917
lonlat2 = 10.655830383300781, -7.3133406... | <p>Those two points are only a few centimetres apart. It looks like <code>pyproj</code> / <code>Geod</code> doesn't cope well with points which are that close together. That's a bit strange, since simple plane geometry is more than adequate at such distances. Also, that error message is a bit suspicious, since it's sug... | python|geospatial|pyproj | 6 |
2,004 | 38,099,645 | consumer not acknowledging message | <p>I have a channel.basic_ack however when I check in the rabbitmq admin ui, it stays unacked rather than acked. Here is my code to ack the message</p>
<pre><code>def handle_payload(self, channel, method, properties, body):
#self.taskhub.server.invoke('SendTaskNotification', body['userId'], body['taskId'])
... | <p>Pika documentation <a href="http://pika.readthedocs.io/en/0.10.0/modules/adapters/blocking.html" rel="nofollow">http://pika.readthedocs.io/en/0.10.0/modules/adapters/blocking.html</a> says, delivery_tag is a default parameter.
change the above code with the below line:</p>
<pre><code>
channel.basic_ack(delivery_ta... | python-2.7|rabbitmq|message-queue|amqp|pika | 1 |
2,005 | 31,055,033 | Caffe: Extremely high loss while learning simple linear functions | <p>I'm trying to train a neural net to learn the function <code>y = x1 + x2 + x3</code>. The objective is to play around with Caffe in order to learn and understand it better. The data required are synthetically generated in python and written to memory as an lmdb database file.</p>
<p>Code for data generation:</p>
<... | <p>The loss generated is a lot in this case because Caffe only accepts data (i.e. <code>datum.data</code>) in the <code>uint8</code> format and labels (<code>datum.label</code>) in <code>int32</code> format. However, for the labels, <code>numpy.int64</code> format also seems to be working. I think <code>datum.data</cod... | python|neural-network|deep-learning|caffe|lmdb | 1 |
2,006 | 52,085,394 | Discrepancy between my pandas.cut output category and the ones shown in pandas documentation | <p>I'm learning pandas.cut to put my data into different bins. I'm running the example code from the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow noreferrer">pandas documentation</a>. But somehow the category shown in the outputs I generated are different. </p>
<p>The ... | <p>I think this might be a bug, but it has been fixed now. On 0.23.4, it returns float64 as expected.</p>
<pre><code>pd.cut(s, 6)
a (1.992, 3.333]
b (3.333, 4.667]
c (4.667, 6.0]
d (7.333, 8.667]
e (8.667, 10.0]
dtype: category
Categories (6, interval[float64]): [(1.992, 3.333] < (3.333, 4.667] &... | python|pandas | 1 |
2,007 | 36,438,478 | Is it possible to create a query command that takes in a list of variables in python-mysql | <p>I am trying to do a multiquery which utilizes <code>executemany</code> in MySQLDb library. After searching around, I found that I'll have to create a command that uses <code>INSERT INTO</code> along with <code>ON DUPLICATE KEY</code> instead of <code>UPDATE</code> in order to use <code>executemany</code></p>
<p>All... | <p>Assuming that you have a list of tuples for the set piece of your command:</p>
<pre><code>listUpdate = [('f1', 'i'), ('f2', '2')]
setCommand = ', '.join([' %s = %s' % x for x in listUpdate])
all_columns = 'id, id2, num1, num2'
vals = '%s, %s, %s, %s'
update_query = """
INSERT INTO `my_table`
... | python|mysql|mysql-python | 1 |
2,008 | 43,908,462 | how to skip lines in pandas dataframe at the end of the xls | <p>I have a dataframe:</p>
<pre><code> Energy Supply Energy Supply per Capita % Renewable
Country
Afghanistan 3.210000... | <p>It seems you need parameter <code>skip_footer = 5</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html" rel="nofollow noreferrer"><code>read_excel</code></a>:</p>
<blockquote>
<p><strong>skip_footer</strong> : int, default 0</p>
<p>Rows at the end to skip (0-indexed)</p>
</... | python|pandas|dataframe | 4 |
2,009 | 47,953,752 | How to concatenate pandas DataFrame with built-in logic? | <p>I have two pandas data frame and I would like to produce the output shown in the <code>expected</code> data frame.</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'a':['aaa', 'bbb', 'ccc', 'ddd'],
'b':['eee', 'fff', 'ggg', 'hhh']})
df2 = pd.DataFrame({'a':['aaa', 'bbb', 'ccc', 'ddd'],
... | <p>Use builtin <code>update</code> by replacing '' with <code>nan</code> i.e </p>
<pre><code>df1['b'].update(df2['update'].replace('',np.nan))
a b
0 aaa eee
1 bbb X
2 ccc ggg
3 ddd Y
</code></pre>
<p>You can also use <code>np.where</code> i.e </p>
<pre><code>out = df1.assign(b=np.where(df2['updat... | python|python-3.x|pandas|dataframe | 5 |
2,010 | 47,875,416 | Use tf.TextLineReader to read to a np.array in TensorFlow | <p>I need to read a file in my train module into a np.array (i want to use the array as label_keys in a DNNClassifier).</p>
<p>I tried tf.read_file and tf.TextLineReader() but i can´t get them to just output the rows to a np.array.</p>
<p>Is it possible?</p>
<p>(why not just read a file with open? I´m training in GC... | <p>To access a file from GCS using TensorFlow, you can use the Python <a href="https://www.tensorflow.org/api_docs/python/tf/gfile/GFile" rel="nofollow noreferrer"><code>tf.gfile.GFile</code></a> API, which acts like a regular Python file object, but allows you to use TensorFlow's filesystem connectors:</p>
<pre><cod... | tensorflow | 2 |
2,011 | 37,178,536 | Blank python path | <p>When I run echo $PYTHONPATH in bash, I receive a blank line then the prompt again. My .bash_profile is this:</p>
<pre><code># Setting PATH for Python 2.7
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/2.7/bin:${PATH}"
export PATH
</code></pre>
<p>I'm runn... | <p>Blank line means the variable <code>PYTHONPATH</code> is not set with any value. </p>
<p>Note that <code>PATH</code> and <code>PYTHONPATH</code> are 2 different variables.</p>
<p><code>PATH</code> has a list of directories to find executables when running in <code>bash</code> whereas <code>PYTHONPATH</code> has a ... | python-2.7|path|bash | 1 |
2,012 | 34,063,932 | Returning found char and index in list - Python | <p>I have the following code:</p>
<p>I am trying to compare each char in the userInputList with the Letters array, if found in the letters array i would like to return it along with its index number; so if a user was to type hello: it would check if 'h' exists in Letters which it does, return the value and also return... | <p>This should work:</p>
<pre><code># Python 2 users add the following line:
from __future__ import print_function
for letter in userInputList:
print(letter, end=': ')
try:
print('found at index', Letters.index(letter))
except ValueError:
print('not found')
</code></pre>
<p>You can iterat... | python|list|char|compare | 0 |
2,013 | 39,785,873 | multiprocessing pool.map() got "TypeError: list indices must be integers, not str" | <p>I do a multiprocessing with python's <code>multiprocessing.Pool</code> module, but got <code>TypeError: list indices must be integers, not str</code> Error:</p>
<p>Here is my code:</p>
<pre><code> def getData(qid):
r = requests.get("http://api.xxx.com/api?qid=" + qid)
if r.status == 200:
DBC.save... | <p>When a worker task raises an exception, <code>Pool</code> catches it, sends it back to the parent process, and reraises the exception, but this doesn't preserve the original traceback (so you just see where it was reraised in the parent process, which isn't very helpful). At a guess, something in <code>DBC.save</cod... | python|multiprocessing | 3 |
2,014 | 42,110,124 | How to give a condition along with cv2.waitKey() in python? | <p>I need to capture video and stop video after 10 seconds.But when i give condition along with cv2.waitKey() video stops instantly.When i separate the condition the second condition(elapsed==10) doesn't work.My sample code is</p>
<pre><code>import cv2
import time
cap = cv2.VideoCapture(0)
start_time=time.time()
while... | <p>Try using <code>elapsed>=10</code>.<br>
It's not sure your code will EXACTLY hit the <code>10</code> elapsed seconds. <br>
If <code>10.1</code> or <code>10.000000000001</code> seconds are elapsed your program will miss the time and never stop, because the condition will never be met.</p> | python | 1 |
2,015 | 33,613,270 | Hide Lines from Matplotlib Plot without redrawing them? | <p>I have a new issue with matplotlib and 'hiding' lineplots.</p>
<p>I have a wxFrame with a matplotlib plot and an cursor to give values. Works perfectly well.
In the plot are up to 13 lines and I want to show and hide them using checkboxes, this is working fine, too.</p>
<p>This is my code to 'redraw'
</p>
<pre><c... | <p>Here's a bad one:</p>
<p>Try setting <code>alpha=0</code> to effectively hide a line doing something along the lines of <code>self._axes.lines[mylineindex].set_alpha(0.0)</code>. In this way you should only have to redraw that one line.</p> | python|matplotlib | 0 |
2,016 | 20,044,522 | PyQt4 Gui that prints loop | <p>I'm trying to learn PyQt4 and has made the following Gui for this purpose - it has no other use.</p>
<p>The code works almost as expected - the only thing that doesn't is the 'else' clause.</p>
<pre><code>import sys
import time
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Form(QDialog):
def __in... | <p>Add the following line in your else part</p>
<pre><code>QApplication.processEvents()
</code></pre>
<p>like</p>
<pre><code>while state:
time.sleep(.1)
if i % 10 == 1:
self.browser.append(str(i))
QApplication.processEvents()
i += 1
else:
self.browser.append('Stop loop')
QApplicat... | python|python-2.7|pyqt4|pyserial | 1 |
2,017 | 20,061,850 | Searching two things | <p>I am using <code>re</code> and would like to search a string between two strings. My problem is the string that I would like to search may end with either newline(\n) or another string. So what I want to do is if it is newline or another string it should give me back the string. The reason why I want to do that is s... | <p>I'm assuming nothing needs to be done if the group isn't found. Simplest is to just skip the error.</p>
<pre><code>try:
recipientsList = reciBody.group(1).encode("utf-8").split(',')
except AttributeError:
pass # nothing needs to be done
</code></pre>
<p>Instead of <code>pass</code> you may need to set <cod... | python|string|search | 0 |
2,018 | 48,375,639 | Pandas: equivalent to excel look up in python | <p>I have a data frame such that</p>
<pre><code>A B
v1 2
v2 4
v3 6
v4 3
v5 5
v6 3
</code></pre>
<p>now I want to look up (col <code>B</code> value) for a value = v3 in column <code>A</code>. It shall give me an output 6. How shall I do that in python? </p> | <p>You need create <code>Series</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> and select by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.loc.html" rel="nofollow noreferrer"><c... | python|pandas|lookup | 2 |
2,019 | 25,782,392 | Start AVD from jenkins | <p>I am try to launch an android emulator from jenkins.
I have written a batch file as follows: </p>
<pre><code>cd E:\android-sdk\tools
emulator.exe -avd "AVD" -wipe-data
</code></pre>
<p>I execute this batch file from jenkins. But it does not launch the emulator.</p>
<p>I have also tried launching it from python as... | <p>I think, it should be permission issue. Try running the jenkins client as admin.</p>
<p>For Python, change your subprocess call to </p>
<pre><code>process = subprocess.Popen(['emulator.exe', '-avd', 'AVD'], cwd=bash)
</code></pre> | android|python|jenkins|jenkins-plugins | 0 |
2,020 | 44,598,207 | Failing to format regex correctly to locate and then parse out paragraph from text document between regex1 & regex2 using python | <p>I am trying to scrape the content between the line starting with 2) and the line starting with 3)</p>
<p>I have managed to iterate through the document, but I'm drawing a blank as to how to get the script to begin storing the document's contents between line 2) and line 3).</p>
<p>Eventually, I want to be able to ... | <p>I managed to figure out this question and wanted to share the results. It isn't the most elegant, but it works like a charm.</p>
<p>The code iterates thru the document, locates the first search string, scrapes 2 hostnames (and converts them to ip addresses) from the first search string, then begins scraping lines o... | python|python-3.x | 0 |
2,021 | 61,865,540 | Can't access memory map from child process (Python 3.8) | <p>I'm writing a program that uses Python's <code>multiprocessing</code> module to speed up CPU-bound tasks, and I want the child processes I create to access a memory map that initially gets created in the parent process without duplicating it. According to the <a href="https://docs.python.org/3/library/multiprocessin... | <p>Thanks to Eryk Sun's comments, I was able to make a working implementation:</p>
<pre class="lang-py prettyprint-override"><code>DATA = r"data.csv"
from sys import platform
if platform.startswith("win"):
WINDOWS = True
from msvcrt import get_osfhandle
else:
WINDOWS = False
import os
from multiprocessing... | python-3.x|windows|multiprocessing|python-multiprocessing|memory-mapped-files | 0 |
2,022 | 24,353,999 | Transferring user entered data from an Excel worksheet to a Python Script | <p>I'm writing a script and I would like to be able to interact with MS Excel. Once I run the script, I would like to open up an excel worksheet, have the user enter some data, do some basic calcs in excel, and then return the calculated data and some of the user entered data to the script. </p>
<p>I'm doing this beca... | <p>Here's a potential approach using pandas. If the input file doesn't exist, it writes a dummy file (modify this to suit), then opens the excel file, and reads back into a dataframe once the user has closed. Replace <code>excel_path</code> with a path to your Excel install (I'm using LibreOffice to here).</p>
<pre>... | python|excel|pandas | 0 |
2,023 | 35,904,647 | Peewee SQL query join where none of many match | <p>The following SQL finds all posts which haven't any associated tags named 'BadTag'.</p>
<pre><code>select * from post t1
where not exists
(select 1 from tag t2
where t1.id == t2.post_id and t2.name=='BadTag');
</code></pre>
<p>How can I write this functionality in Peewee ORM? If I write something along the line... | <p>Do not use manecosta's solution, it is inefficient.</p>
<p>Here is how to do a NOT EXISTS with a subquery:</p>
<pre><code>(Post
.select()
.where(~fn.EXISTS(
Tag.select().where(
(Tag.post == Post.id) & (Tag.name == 'BadTag'))))
</code></pre>
<p>You can also do a join:</p>
<pre><code>(Post
.... | python|sql|sqlite|peewee | 3 |
2,024 | 29,591,125 | Calculating number of adjacent odd numbers | <p>I am trying to write a code in Python where the user is asked to enter the number of numbers in a sequence, then the numbers themselves. And finally, the program outputs the number of pairs of adjacent odd numbers. Here's a sample output:</p>
<p><strong>Enter the length of the sequence: 6<br/>
Enter number 1: 3<br... | <p>check if the current element and the next are both odd and sum:</p>
<pre><code>length = int(input("Enter the length of the sequence: "))
nums = [int(input("Enter number: {}: ".format(i))) for i in range(1, length + 1)]
print(sum(ele % 2 and nums[i] % 2 for i,ele in enumerate(nums, 1)))
</code></pre>
<p><code>en... | python|count | 1 |
2,025 | 29,607,116 | Issues Translating Custom Discrete Fourier Transform from MATLAB to Python | <p>I'm developing Python software for someone and they specifically requested that I use their DFT function, written in MATLAB, in my program. My translation is just plain not working, tested with sin(2*pi*r).
The MATLAB function below:</p>
<pre><code>function X=dft(t,x,f)
% Compute DFT (Discrete Fourier Transform) at... | <p>Numpy arrays do element wise multiplication with <code>*</code>.</p>
<p>You need <code>np.dot(w1,w2)</code> for matrix multiplication using numpy arrays (not the case for numpy matrices)</p>
<p>Make sure you are clear on the <a href="https://stackoverflow.com/questions/4151128/what-are-the-differences-between-nump... | python|matlab|numpy|dft | 1 |
2,026 | 46,552,161 | Write DataFrame to mysql table using pySpark | <p>I am attempting to insert records into a <code>MySql</code> table. The table contains <code>id</code> and <code>name</code> as columns.</p>
<p>I am doing like below in a <code>pyspark</code> shell.</p>
<pre><code>name = 'tester_1'
id = '103'
import pandas as pd
l = [id,name]
df = pd.DataFrame([l])
df.write.for... | <blockquote>
<p>Use Spark DataFrame instead of pandas', as <code>.write</code> is available on Spark Dataframe only </p>
</blockquote>
<p>So the final code could be</p>
<pre><code>data =['103', 'tester_1']
df = sc.parallelize(data).toDF(['id', 'name'])
df.write.format('jdbc').options(
url='jdbc:mysql://loca... | python|mysql|apache-spark|pyspark|apache-spark-sql | 20 |
2,027 | 46,358,666 | Globally getting context in Wagtail site | <p>I am working on a Wagtail project consisting of a few semi-static pages (homepage, about, etc.) and a blog. In the homepage, I wanted to list the latest blog entries, which I could do adding the following code to the HomePage model:</p>
<pre><code>def blog_posts(self):
# Get list of live blog pages that are des... | <p>This sounds like a good case for a <a href="https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/" rel="noreferrer">custom template tag</a>.</p>
<p>A good place for this would be in <code>blog/templatetags/blog_tags.py</code>:</p>
<pre class="lang-py prettyprint-override"><code>import datetime
from dj... | python|django|wagtail | 6 |
2,028 | 46,256,267 | xlwings runpython EOL error | <p>I have recently installed xlwings on my Mac and am currently trying to write a small programme to update some data(via requests). As a test, I tried to update the cryptocurrency prices via an API and write them into excel.
Without using runpython, the code works. However as soon as I run my VBA code,
I get this erro... | <p>Solved this. I just wanted to post the solution for anyone who might be confronted with the same issue.</p>
<p>I went to check my xlwings.conf file, in order to see the setup for "INTERPRETER" and "PYTHONPATH". I never did editing on this, however, it was formatted incorrectly.</p>
<p>The <strong>correct</strong> ... | python|excel|vba|xlwings | 0 |
2,029 | 49,743,041 | Failed building wheel for | <p>I'm trying to install Pillow using</p>
<pre><code>pip install pillow
</code></pre>
<p>But everytime it does that:</p>
<hr>
<p>Failed building wheel for Pillow Running setup.py clean for Pillow
Failed to build Pillow</p>
<p>Command "/data/data/com.termux/files/usr/bin/python -u -c "import setupto... | <p>I solved this by installing clang</p>
<pre><code>pkg install clang
</code></pre>
<p>Thank you to abarnet and sorry for late answer to myself haha I'm late because I sixed this week ago.</p> | python | 1 |
2,030 | 70,161,646 | Trying to get the next 3 characters after regex string match | <p>I have a problem from college that I am trying to solve. I have a log file, from which I want to extract just the HTTP codes.</p>
<p>I have included a bit of that log file below:</p>
<pre><code>45.132.51.36 - - [19/Dec/2020:18:00:08 +0100] "POST /index.php?option=com_contact&view=contact&id=1 HTTP/1.1&q... | <p>I'm not sure you need a regex here:</p>
<pre><code>with open("access.log") as file:
for line in file:
print(line.split()[8])
# Output:
200
200
200
200
200
200
200
200
200
200
200
200
</code></pre> | python|python-3.x|regex | 1 |
2,031 | 53,459,626 | pygame making the sprite go upwards and downwards | <p>I am trying to make the sprite move up and down by using the arrow keys but it schemes to only be moving slightly upwards and slightly downwards: there is a speed for the x and y axis and also a position. There are also two functions which are draw and update (which gets the new xpos and the new ypos). here is my co... | <p>You've written <code>self.xpos =+ self.speed_x</code> (which is interpret as <code>self.xpos = +self.speed_x</code>) instead of <code>self.xpos += self.speed_x</code>. So you're not adding the speed to the position, you're overwriting it.</p> | python|pygame | 1 |
2,032 | 53,552,804 | AWS lambda to delete default VPC | <p>New to cloud, Can anyone help to correct this code</p>
<p>This module is to list the regions and delete the complete default vpc via a lambda function.</p>
<p>Getting below error while testing this:
Syntax error in module 'lambda function': unindent does not match any outer indentation level </p>
<p>Please help o... | <p>It looks to me a code indentation issue. Please try with this</p>
<pre><code>def lambda_handler(event, context):
# TODO implement
#for looping across the regions
regionList=[]
region=boto3.client('ec2')
regions=region.describe_regions()
#print('the total region in aws are : ',len(regions['Regions']))
... | python|amazon-web-services|lambda|boto3|vpc | 2 |
2,033 | 33,448,070 | How could I access localstorage under Python requests | <p>I found I need to send a session id <code>x-connection-id</code> which is stored by server side Javascript <code>localStorage.setItem("x-connection-id")</code></p>
<p>If and only if I get this id, so that I can keep going the following request.</p>
<p>Any idea ?</p>
<pre><code>headers = {
'User-Agent': 'Mozi... | <p>Seems like it's impossible</p>
<blockquote>
<p>Local storage is specific to browser.</p>
<p>Local Storage is a way to store persistent data using JavaScript. It
should be used only with HTML5 compatible web browser.</p>
<p>To access Local storage in python, a compatible browser's python API is required.</p>
</blockq... | javascript|python|web-crawler|python-requests | 5 |
2,034 | 33,418,741 | Modifying python variables based on config file entries | <p>Relative Python newbie, and I'm writing a script that takes as its input a csv file, splits it into its constituent fields line-by-line and spits it out in another format. What I have so far generally works very well.</p>
<p>Each incoming csv line has specific fields that are read into variables 'txnname' and 'txnm... | <p>There are a few options. </p>
<p>The simplest way is to create a global <code>config</code> module with your string variables and modifiers defined and import it into this module. Basically that will just centralize all these variables into a single location so when you need to modify, you just change the <code>con... | python|csv|configparser | 2 |
2,035 | 73,627,693 | Tkinter scrollbar not updating to cover expanded canvas | <p>I'm having a scrollbar issue with a Tkinter GUI that I'm creating. The GUI contains a class <code>Gen_Box</code> that reproduces a given widget vertically downwards as many times as the widgets <code>add_btn</code> is called. Obviously, this runs off the window frame pretty quickly.</p>
<p>I've tried adding a scroll... | <p>When a new monitor section is added, it is the inner frame (<code>self.inner_frame</code>) get resized, not the canvas (<code>self.canvas</code>). So the <code><Configure></code> event should be bound on the inner frame instead of the canvas:</p>
<pre class="lang-py prettyprint-override"><code>class Form(tk.Fr... | python|python-3.x|user-interface|tkinter|tkinter-canvas | 1 |
2,036 | 12,768,504 | Python: an efficient way to slice a list with a index list | <p>I wish to know an efficient way and code saving to slice a list of thousand of elements</p>
<p>example: </p>
<pre><code>b = ["a","b","c","d","e","f","g","h"]
index = [1,3,6,7]
</code></pre>
<p>I wish a result like as:</p>
<pre><code>c = ["b","d","g","h"]
</code></pre> | <p>The most direct way to do this with lists is to use a list comprehension:</p>
<pre><code>c = [b[i] for i in index]
</code></pre>
<p>But, depending on exactly what your data looks like and what else you need to do with it, you could use numpy arrays - in which case:</p>
<pre><code>c = b[index]
</code></pre>
<p>wo... | python|performance|list|indexing|slice | 17 |
2,037 | 21,710,088 | How to import files while running? | <p>I have following Problem:</p>
<p><code>file1.py</code> has functions and variables wich I need for <code>file2.py</code>.
With <code>from file1 import myclass1</code> there is no problem with that.
The problem is, I also want to "send" variables from <code>file2.py</code> to <code>file1.py</code> while running <cod... | <p>If the question is "how do I import from module1 into module2 when module2 imports from module1", the simple answer is "you can't", and the solution is either </p>
<ul>
<li>merge both modules, </li>
<li>or extract the common dependencies into a third module</li>
<li>or pass needed objects (hint : classes and functi... | python|import | 1 |
2,038 | 24,786,499 | Generate a tree from a text file using python | <p>I Have a txt file which has data like this:</p>
<pre><code>arp
show
show ip
show ip route
show ip route static
show ip default-gateway
show ip default-gateway static
show ip interface
show partition
no
no logging
no logging on
no logging override
</code></pre>
<p>I have to print a tree in the following way:</p>
<... | <p>The count of words - 1 indicates tab depth. Loop through each line and prepend a tab using this heuristic in combination with pulling only word X for display.</p> | python-2.7 | 0 |
2,039 | 38,230,170 | Django extending user model tutorial isn't work for me | <p>I've use this tutorial and do exactly what they do:
<a href="https://docs.djangoproject.com/ja/1.9/topics/auth/customizing/#extending-the-existing-user-model" rel="nofollow">https://docs.djangoproject.com/ja/1.9/topics/auth/customizing/#extending-the-existing-user-model</a></p>
<p>my model.py:</p>
<pre><code>from ... | <p>Could it possible that you didn't register Chess model?</p>
<p>Try add <code>admin.site.register(Chess, ChessAdmin)</code> at the bottom of admin.py. Of course you might have to create a simple ChessAdmin for display first.</p> | python|django|model|extend | 0 |
2,040 | 38,484,179 | Cannot connect to ssh via python | <p>so I just setted up a fresh new raspberry pi and I want it to communicate with python using ssh from my computer to my ssh server, the pi.. I first try to connect using putty and it work, I could execute all the commands I wanted, then I tried using librarys such as Paramiko, Spur and they didn't work.</p>
<p>Spur ... | <p>You need to accept the host key, similarly to what is shown <a href="https://iliaselmatani.wordpress.com/2014/04/16/spur/" rel="nofollow">here</a></p>
<pre><code>import spur
shell = spur.SshShell("192.168.1.114",
"pi",
"raspberry",
missing_host_ke... | python|ssh | 3 |
2,041 | 40,275,244 | Yahoo! Fantasy API Maximum Count? | <p>I am trying to get all the available players for a position with JSON returned by the Yahoo! Fantasy API, using this resource:</p>
<pre><code>http://fantasysports.yahooapis.com/fantasy/v2/game/nfl/players;status=A;position=RB
</code></pre>
<p>It seems like it always returns a maximum of 25 players with this API. I... | <p>I did solve this. What I found was that the maximum "count" is 25, but the "start" parameter is the key to this operation. It seems the the API attaches an index to each of the players (however it is sorted) and the "start" parameter is the index to start out. It might seem odd, but the only way I could find was to ... | python|json|oauth|yahoo-api | 2 |
2,042 | 52,278,546 | How can I iterate through numpy 3d array | <p>So I have an array:</p>
<pre><code>array([[[27, 27, 28],
[27, 14, 28]],
[[14, 5, 4],
[ 5, 6, 14]]])
</code></pre>
<p>How can I iterate through it and on each iteration get the [a, b, c] values, I try like that:</p>
<pre><code>for v in np.nditer(a):
print(v)
</code></pre>
<p>but it ... | <pre><code>b = a.reshape(-1, 3)
for triplet in b:
...
</code></pre> | python|loops|numpy | 2 |
2,043 | 51,713,955 | How to Resolve 'Error while installing steem-python' | <p>I have a VM with Ubuntu 18.04.1.</p>
<p><code>python3 --version</code> says 3.6.5.</p>
<p>I installed pip without any failure (seems like).
Then I tried to install steem-python with</p>
<pre><code>pip install steem
</code></pre>
<p>but I get a failure, which looks like:</p>
<pre><code>bla bla bla
...
^~~~~~~~... | <p>You will need to install python3-dev on ubuntu (in addition to unixodbc-dev) and it did work.</p>
<p>Please ensure you've installed these:</p>
<p>$ sudo apt-get install python3-dev</p>
<p>$ sudo apt-get install unixodbc-dev</p>
<p>FYI : Python 2.x users, will need python-dev instead.</p> | python|python-3.x|ubuntu|steemit | 0 |
2,044 | 51,852,787 | How to give command line args to scrapy? | <p>I want to give command line args to scrapy and use that sys.argv[] in spider to check which urls have that argument. How can I do like this for spider named urls?</p>
<p>$scrapy crawl urls "August 01,2018"?</p> | <p>You can pass arguments to a spider's <code>__init__()</code> by using <code>-a</code>, as specified in the docs: <a href="https://doc.scrapy.org/en/latest/topics/spiders.html#spider-arguments" rel="nofollow noreferrer">https://doc.scrapy.org/en/latest/topics/spiders.html#spider-arguments</a></p>
<p>The default meth... | python|scrapy | 2 |
2,045 | 51,968,603 | using the re and urllib.request module | <p>im using python 3.7 and i wanted to write a program that takes name of a city and returns the weather forcast .
i started my code with :</p>
<pre><code>import re
import urllib.request
#https://www.weather-forecast.com/locations/Tel-Aviv-Yafo/forecasts/latest
city=input("entercity:")
url="https://www.weather-foreca... | <p>There must be some spelling mistake in the city name you have entered. I tried running the following code</p>
<pre><code> import re
import urllib2
city=input("enter city:")
url="https://www.weather-forecast.com/locations/" + city +"/forecasts/latest"
data=urllib2.urlopen(url).read()
print(data.decode('utf-8'))... | python|module|urllib | 1 |
2,046 | 69,226,760 | Receiving error when trying to create list | <p>Below is the assignment</p>
<blockquote>
<p>Design a Python script that starts with a list of your own, containing a mix of integers, floating point decimals, and strings. Include this starting list near the beginning of your script. The output of your script should be another list containing only non-string element... | <p>you can't use <code>-</code> to remove an item from list. and remove items from a list you are iterating over</p>
<pre><code>print("This script starts with a given list and outputs another list containing only non-string elements in the original list.")
print()
list1 = [21,99,-99,"cool","sch... | python|python-3.x|list | 0 |
2,047 | 56,347,325 | Matplotlib dot plot with two categorical variables | <p>I would like to produce a specific type of visualization, consisting of a rather simple <a href="https://en.wikipedia.org/wiki/Dot_plot_(statistics)" rel="nofollow noreferrer">dot plot</a> but with a twist: both of the axes are categorical variables (i.e. ordinal or non-numerical values). And this complicates matter... | <p>you could first convert <code>time</code> and <code>sex</code> to categorical type and tweak it a little bit:</p>
<pre><code>df.sex = pd.Categorical(df.sex)
df.time = pd.Categorical(df.time)
axes = sns.scatterplot(x=df.time.cat.codes+np.random.uniform(-0.1,0.1, len(df)),
y=df.sex.cat.codes+... | python|matplotlib|seaborn|categorical-data | 2 |
2,048 | 67,359,874 | find max-min values for one column based on another | <p>I have a dataset that looks like this.</p>
<pre><code>datetime id
2020-01-22 11:57:09.286 UTC 5
2020-01-22 11:57:02.303 UTC 6
2020-01-22 11:59:02.303 UTC 5
</code></pre>
<p>Ids are not unique and give different datetime values. Let's say:</p>
<p>duration = max(datetime)-min(datetime).</p>
<p>I wan... | <p>Do you want this? :</p>
<pre><code>df.datetime = pd.to_datetime(df.datetime)
c = 0
def count(x):
global c
x = x.sort_values('datetime')
if len(x) > 1:
diff = (x.iloc[-1]['datetime'] - x.iloc[0]['datetime'])
if diff < timedelta(seconds=2):
c += 1
return x.head... | python|pandas|dataframe|datetime|data-analysis | 0 |
2,049 | 36,280,562 | Check if one series is subset of another in Pandas | <p>I have 2 columns from 2 different dataframes. I want to check if column 1 is a subset of column 2.</p>
<p>I was using the following code:</p>
<pre><code>set(col1).issubset(set(col2))
</code></pre>
<p>The issue with this is that if col1 has only integers and col2 has both integers and strings, then this returns fa... | <p>You could use <a href="https://www.google.ru/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&cad=rja&uact=8&ved=0ahUKEwi19d_UzuXLAhUCQpoKHQHDCl0QFgggMAE&url=http%3A%2F%2Fpandas.pydata.org%2Fpandas-docs%2Fstable%2Fgenerated%2Fpandas.Series.isin.html&usg=AFQjCNHEOa4btqDkFrnduWNtwXrgJ6q... | python|pandas|subset | 7 |
2,050 | 16,716,049 | Does twisted epollreactor use non-blocking dns lookup? | <p>It seems obvious that it would use the twisted names api and not any blocking way to resolve host names.
However digging in the source code, I have been unable to find the place where the name resolution occurs. Could someone point me to the relevant source code where the host resolution occurs ( when trying to do a... | <p>It <em>seems</em> obvious, doesn't it?</p>
<p>Unfortunately:</p>
<ol>
<li>Name resolution is not always configured in the obvious way. You think you just have to read <code>/etc/resolv.conf</code>? Even in the specific case of Linux and DNS, you might have to look in an arbitrary number of files looking for name ... | python|dns|twisted | 3 |
2,051 | 43,617,192 | recursively counting the number of elements in a list that are not v | <p>For a list I want to recursively count the number of elements that are not v. </p>
<p>My code so far looks like:</p>
<pre><code>def number_not(thelist, v):
"""Returns: number of elements in thelist that are NOT v.
Precondition: thelist is a list of ints
v is an int"""
total = 0
if thelist is []:
... | <p>All the code is fine, just the termination condition you have added is not correct,</p>
<p>it should be <code>if not thelist:</code></p>
<p>Change your code to check the empty list, <code>if thelist is []:</code> to the above.</p> | python|list|recursion|return | 4 |
2,052 | 54,475,071 | Monkey patching pandas and matplotlib to remove spines for df.plot() | <p><strong>The question:</strong></p>
<p>I'm trying to grasp the concept of <a href="https://riptutorial.com/python/example/9909/monkey-patching" rel="nofollow noreferrer">monkey patching</a> and at the same time make a function to produce the perfect time-series plot. How can I include the following matplotlib functi... | <p>This seems like an <a href="http://xyproblem.info" rel="nofollow noreferrer">xyproblem</a>.</p>
<h2>Monkey patching (The Y)</h2>
<p>The question asks for monkey patching pandas plot function to add additional features. This can in this case be done by replacing the <code>pandas.plotting._core.plot_frame</code> fun... | python|pandas|matplotlib|monkeypatching | 2 |
2,053 | 71,300,413 | How to fix positioning of labels in tkinter? | <p>So I am trying to have a GUI for my Converter (it is intentionally meant to go up to 255 aka 8bits)
And I have got it to work on the button layout as planned. But to make it more user-friendly I wanted to put a 'Convert From' label/text above the buttons. However, as soon as I shifted the buttons down a row it didn'... | <p>Answer to my question as the Issue is now resolved. Fixed it using columnspan which allows you to set a box across several columns.</p>
<pre><code>label = tkinter.Label(self._window, text="Convert From ", font=MainWindow.FONT)
label.grid(row=0, column=2,columnspan=3, padx=5, pady=5)
</code></pre>
<... | python|user-interface|tkinter | 0 |
2,054 | 55,233,204 | IP address must be specified when pinging a website with Python | <p>So I'm trying to ping a website such as Microsoft or Google and print out the results, but when I run the script it just says: "IP address must be specified.". I've tried looking around to see why this is happening, but can't seem to narrow down a solution. </p>
<p>Here's my code:</p>
<pre><code>import subprocess
... | <p>To show the output of the subprocess call you can use <code>check_output</code> method: <a href="https://stackoverflow.com/a/8700414/3129414">See this answer for details</a></p>
<pre><code>import subprocess
def ping():
print('Ping www.microsoft.com')
print()
address = 'www.microsoft.com'
print(subprocess.c... | python|ip|ping | 1 |
2,055 | 52,671,370 | Programming a run schedule | <p>Currently I'm trying to add a seasonal run schedule to a current program that I have. I've come up with the following code bellow that works but I'm trying to do this without having to regularly update the year in my defined dates.</p>
<pre><code>from datetime import date
td = date.today()
fs = date(2018, 3, 31)
f... | <p>It looks like the code is independent of the year (or am I missunderstanding your code??), so maybe you could just take the current year as the base.</p>
<pre><code>from datetime import date
td = date.today()
current_year = td.year
fa_s = date(current_year , 3, 31)
fa_e = date(current_year , 10, 18)
wi_s =... | python|schedule | 0 |
2,056 | 47,967,881 | Empty response after submit a form with (requests) python package | <p>I'm trying to submit a form using (requests) module.</p>
<p>Here is the form that I want to submit:</p>
<pre><code><form method="POST" enctype="multipart/form-data" action="/cgi-bin/claws72.pl">
<input type="hidden" name="email" value="a.nobody@here.ac.uk"><br>
<br>
Select tagset:
<input... | <p>If You check request data using <code>Firebug</code> or some similar tool, You'd see that request data is actually in following format:</p>
<pre><code>-----------------------------41184676334
Content-Disposition: form-data; name="email"
a.nobody@here.ac.uk
-----------------------------41184676334
Content-Dispositi... | python|python-3.x|python-requests | 1 |
2,057 | 47,575,226 | fakename() not populating into gmail | <p><code>fake.name()</code> appears to give a random name, no errors, but I can see in selenium chromedriver that nothing is input. Any idea why this is ? </p>
<pre><code>from faker import Faker
fake = Faker('it_IT')
for _ in range(1):
print(fake.name())
username = driver.find_element_by_css_selector("#em... | <p>Use this for storing the name as a variable rather than using the function.</p>
<pre><code>from faker import Faker
fake = Faker('it_IT')
for _ in range(1):
name = fake.name()
print(name)
username = driver.find_element_by_css_selector("#emailPass")
username.send_keys(name)
time.sleep(2)
</code></... | python|python-3.x|selenium|selenium-webdriver | 0 |
2,058 | 66,241,741 | MYSQL python list index out of range | <p>I'm wring a web scraping program to collect data from truecar.com
my database has 3 columns
and when I run the program I get an error which is this : list indext out of range
here is what I've done so far:</p>
<pre><code>import mysql.connector
from bs4 import BeautifulSoup
import requests
import re
# take the car's... | <p>Ya you are hard coding the length. Change how you are iterating through your soup elements. So:</p>
<pre><code>import mysql.connector
from bs4 import BeautifulSoup
import requests
# take the car's name
requested_car_name = input('Enter car name: ')
# inject the car's name into the URL
my_request = requests.get('... | python|mysql|web-scraping | 1 |
2,059 | 7,380,490 | Alternative to using 'in' with numpy.where() | <p>Lets say I have an array, 'foo', with two columns. Column 0 has values 1 to 12 indicating months. Column 1 has the corresponding measurement values. If I wanted to create a mask of measurement values from December, January and February (12,1,2) I would suspect that I could:</p>
<pre><code>numpy.where(foo[:,1] in (1... | <p>I think the reason the 'in (12, 1, 2)' does not work is that the element before the 'in' has to be a single element. </p>
<p>But for this, numpy has the function <code>in1d</code> (<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html" rel="nofollow">documentation</a>) to do a 'in' with a num... | python|numpy|scipy | 4 |
2,060 | 7,646,001 | Split the string 'abcde' into a list with separate elements | <p>I have a string like <code>'g fmnc wms bgblr rpylqjyrc gr zw fylb'</code>. I use the <code>.split()</code> function in python and get <code>['g', 'fmnc', 'wms', 'bgblr', 'rpylqjyrc', 'gr', 'zw', 'fylb']</code></p>
<p>Now I want to split each of the elements into seperated lists like: <code>[['g'], [['f'],['m'],['n'... | <p>Try this:</p>
<pre><code>[list(item) for item in s.split()]
</code></pre>
<p>It will give you this <code>[['g'], ['f', 'm', 'n', 'c'], ...]</code> which isn't quite what you asked for, but probably what you meant.</p> | python|python-2.7 | 4 |
2,061 | 72,713,761 | Convert from integer to dictionary with repeating digits | <p>I need to take an integer <code>n</code> and add all its digits into a Python dictionary <em>(hashtable)</em> to later access them with an <code>O(1)</code> complexity.</p>
<pre><code>n = 941726149
d = {}
for i in str(n):
d[i] = None
print(d)
</code></pre>
<p>The problem is when there are repeating digits, the ... | <p>Here's an example, that for each digit present in the number, it stores its indexes. <br>As a note, digits not present in the number won't be present in the structure either, so trying to index them (<code>structure[digit_not_existing_in_number]</code>) will yield <em>KeyError</em> (that's why <em>dict.get</em> is r... | python|dictionary|data-structures|hashmap | 0 |
2,062 | 40,726,079 | python - reconnect stomp connection when dead | <p>As per the <a href="http://jasonrbriggs.github.io/stomp.py/api.html#establishing-a-connection" rel="nofollow noreferrer">documentation</a>, given that I've instantiated a connection:</p>
<pre><code>>>> import stomp
>>> c = stomp.Connection([('127.0.0.1', 62615)])
>>> c.start()
>>>... | <p>You can wrap your connection and check if its connected every call.</p>
<pre><code>import stomp
def reconnect(connection):
"""reconnect here"""
class ReconnectWrapper(object):
def __init__(self, connection):
self.__connection = connection
def __getattr__(self, item):
if not self.__c... | python|connection|queue|stomp | 1 |
2,063 | 40,713,063 | difference between the next function and the next method | <p>When you make a generator by calling a function or method that has the <code>yield</code> keyword in it you get an object that has a <code>next</code> method.</p>
<p>So far as I can tell, there isn't a difference between using this method and using the <code>next</code> builtin function.</p>
<p>e.g. <code>my_gener... | <p>In Python 2 the internal method for an iterator is <code>next()</code> in Python 3 it is <code>__next__()</code>. The builtin function <code>next()</code> is aware of this and always calls the right method making the code compatible with both versions. Also it adds the <code>default</code> argument for more easy han... | python | 1 |
2,064 | 68,255,645 | Is there an equivalent of typedefs for mypy? | <p>Sometimes when coding, I want "special sorts of strings" and "special sorts of integers" for documentation.</p>
<p>For example you might have.</p>
<p><code>def make_url(name:str) -> URL:</code></p>
<p>where <code>URL</code> is really a string. In some languages like C you can use a typedef for... | <p>You can use the <a href="https://docs.python.org/3/library/typing.html#newtype" rel="nofollow noreferrer"><code>NewType</code></a> helper function to create new types.
Here's a small example:</p>
<pre><code>from typing import NewType
UserId = NewType('UserId', int)
some_id = UserId(524313)
def foo(a: UserId):
... | python|typedef|mypy | 1 |
2,065 | 1,526,002 | creating a .mat file from python | <p>I have a variable <code>exon = [[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10]]]</code>. I would like to create a mat file like the following </p>
<pre><code>>>
exon : [3*2 double] [2*2 double]
</code></pre>
<p>When I used the python code to do the same it is showing error message. here is my python code</p>
... | <p>You seem to want two different arrays linked to same variable name in Matlab. That is not possible. In MATLAB you can have cell arrays, or structs, which contain other arrays, but you cannot have just a tuple of arrays assigned to a single variable (which is what you have in mdict={'exon': (exon[0], exon<a href="htt... | python|scipy|mat-file | 10 |
2,066 | 2,168,409 | Can access AppEngine SDK sites via local ip-address when localhost works just fine and a MacOSX | <p>Can access AppEngine SDK sites via local ip-address when localhost works just fine and a MacOSX using the GoogleAppEngineLauncher.</p>
<p>I'm trying to setup facebook development site (using a dyndns.org hostname pointing at my firewall which redirects the call to my mac book).</p>
<p>It seems like GoogleAppEngine... | <p>As per the latest <a href="https://developers.google.com/appengine/docs/python/tools/devserver?csw=1#Python_Command-line_arguments" rel="noreferrer">documentation</a> <code>-a</code> wont work anymore.</p>
<p>This is possible by passing <code>--host</code> argument with <code>dev_appserver.py</code> command</p>
<p... | python|google-app-engine|facebook|macos | 9 |
2,067 | 54,816,434 | Python turtle tic tac toe | <p>I'm new to python and I programed a tic tac toe with an AI that plays against you. Everything is working but I used textboxes to inform the AI what the player chose. Now I want to upgrade my game so that the player can click on the box he wants to fill instead of typing it in the textbox. My idea was to use <code>on... | <p>Assuming you have named your Screen() in the turtle module, you should then put</p>
<pre><code>screen.onscreenclick(whichbox)
</code></pre>
<p>instead of:</p>
<pre><code>onscreenclick(whichbox)
</code></pre>
<p>Example:</p>
<pre><code>from turtle import Turtle, Screen
turtle = Turtle()
screen = Screen()
def Ex... | python|turtle-graphics|tic-tac-toe|python-turtle | 2 |
2,068 | 28,373,999 | Why do changes to a temporary variable representing a row of a matrix, affect the row of the matrix itself? | <p>I was trying to write a code that can do elementary row operations on matrices and I have run into some issues. I realize that there are libraries that have functions that can be used to complete these operations; however, I am doing this for my own gratification.</p>
<p>The problem arises with the replacement oper... | <p>The problem is that <code>temp_row</code> is not a <em>copy</em> of the row in your matrix but a <em>reference</em> to it. Anything you do to <code>temp_row</code> therefore happens to the corresponding row in your matrix, since it is happening to the same object (which happens to be referenced in two different ways... | python|python-2.7 | 1 |
2,069 | 28,334,871 | Why do Python regex strings sometimes work without using raw strings? | <p>Python recommends using raw strings when defining regular expressions in the <code>re</code> module. From the <a href="https://docs.python.org/2/library/re.html#module-re" rel="noreferrer">Python documentation</a>:</p>
<blockquote>
<p>Regular expressions use the backslash character ('\') to indicate special forms... | <p>The example above works because <code>\s</code> and <code>\d</code> are not escape sequences in python. According to the docs: </p>
<blockquote>
<p>Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the string. </p>
</blockquote>
<p>But it's bes... | python|regex|string | 8 |
2,070 | 44,182,348 | Tensorflow/Python: Function tuple returning copies of first element | <p>I want to return 7 values from a function and later print those values.
But when I print them out, I always get seven copies of the first value.</p>
<p>I can't seem to understand what I'm doing wrong though.</p>
<p>What the code is doing is comparing a tensor(array) of <code>n</code> elements, and checking the per... | <p>You're passing <code>one</code> into each set of operations on the second line i.e.</p>
<pre><code>fifteen = tf.multiply(tf.divide(tf.cast(one,dtype=tf.float32),n ),m)
^^
</code></pre> | python|tensorflow | 0 |
2,071 | 44,163,637 | PyUSB: No backend available | <p>I'm trying to reach out and find what USB devices are tied to my computer. I'm going through the "Programming with PyUSB 1.0" tutorial. I can't get anything I'm using there to work, I keep getting a "ValueError: No background available" error. What is missing from my code? I'm on a 64 bit Windows 10 machine. I insta... | <p>If it's a windows OS you should download the installer from <a href="http://www.craftedge.com/products/libusb.html" rel="nofollow noreferrer">here</a></p>
<p>If it's Linux, did you install libusb-1.0 or openusb as a backends? If no, you should.</p> | python|pyusb | 4 |
2,072 | 32,731,977 | Operator != vs <> | <p>Learning python. I’ve doubt on use of following operators:</p>
<pre><code>!= —> Checks if the value of two operands is equal or not, if values are not equal then condition becomes true.
<> —> Checks if the value of two operands is equal or not, if values are not equal then condition becomes true.
</cod... | <p>From <a href="https://docs.python.org/2/reference/expressions.html#not-in" rel="nofollow">the documentation -</a></p>
<blockquote>
<p>The forms <code><></code> and <code>!=</code> are equivalent; for consistency with C, <code>!=</code> is preferred; where <code>!=</code> is mentioned below <code><></c... | python|python-2.7|operators|comparison-operators | 3 |
2,073 | 13,827,941 | Read label values and store into a variable | <p>I'm trying to read data from a website and have that data stored into a variable.
Example:</p>
<p><a href="http://www.example.com/example-info.php" rel="nofollow">http://www.example.com/example-info.php</a> -> </p>
<p>Name: Bob</p>
<p>Address: 1234 Street</p>
<p>Telephone: 000-000-0000</p>
<p>Email: Bobs-email@... | <p>Are you trying to <a href="http://en.wikipedia.org/wiki/Data_scraping" rel="nofollow">screen scrape</a> the website? If so, using <a href="http://docs.python-requests.org/en/latest/" rel="nofollow">requests</a> or <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">BeautifulSoup</a> are g... | python|python-2.7 | 0 |
2,074 | 27,339,025 | How to export Python 3.4 input information to JSON? | <p>I am trying to build an artificial intelligence program that will keep track of information and other stuff, but am having issues with trying to get it to export the information to a a file. I am new to Python and would like some help identifying what could be the issue.</p>
<p>Here is the source code.</p>
<pre><c... | <p>You never <em>do</em> anything with the name the user enters:</p>
<pre><code>def prog_loop():
global game_state
name = input (str("What is your name?: "))
save_game()
</code></pre>
<p><code>name</code> is just a local variable there. If you wanted to save that as the name for the human, then you need t... | python|json|save | 0 |
2,075 | 27,368,782 | Reversing a Dict | <p>I am currently trying to make a function which reverses a dict's keys and values. I was looking online and came across this:</p>
<pre><code>def reverse(d):
return dict([(v, k) for k, v in d.iteritems()])
</code></pre>
<p>My problem is that I'm not sure what this means. I understand the idea of a for loop on th... | <p><code>for k, v in d.iteritems()</code> is each <code>key k</code> and <code>value v</code> so reversing v and k with <code>(v, k)</code> makes the old value the key and the old key the new value</p>
<pre><code>In [7]: d = {1:10,2:20}
In [8]: d.items()
Out[8]: dict_items([(1, 10), (2, 20)]) # tuples of key and valu... | python|for-loop|dictionary | 4 |
2,076 | 23,104,201 | How to merge list to become string without adding any character in python? | <p>I found that I can join them with '-'.join(name) but I dont want to add any character. Lets say I have
<code>['stanje1', '|', 'st6', ',' 'stanje2', '|', '#']</code>
and I want to be like this</p>
<pre><code>stanje1|st6,stanje2|#
</code></pre> | <p>Just ommit the -:</p>
<pre><code>''.join(name)
</code></pre> | python|string|list|merge | 2 |
2,077 | 8,239,432 | How to Get The field value dynamically in python? | <p>I have a form view. I entered a value in a field. How can i retrieve that value and have it assigned to some variable in .py for making operations</p>
<p>For Example:
I have ActiveFrom field.I entered value 23-11-2011 to field in form view. I want to get that value dynamically in openerp. How can I do that?</p> | <p>I suspect you want the <a href="http://doc.openerp.com/v6.0/developer/2_6_views_events/events/events.html#on-change" rel="nofollow"><code>on_change</code> event</a>. It lets you trigger server-side code when the user changes a field's value. You can then change the value of other fields, or pop up a warning message.... | python|openerp|postgresql-9.1 | 1 |
2,078 | 41,972,573 | Tensorflow: jointly training CNN + LSTM | <p>There are quite a few examples on how to use LSTMs alone in TF, but I couldn't find any good examples on how to train CNN + LSTM jointly.
From what I see, it is not quite straightforward how to do such training, and I can think of a few options here:</p>
<ul>
<li>First, I believe the simplest solution (or the most... | <p>For joint training, you can consider using tf.map_fn as described in the documentation <a href="https://www.tensorflow.org/api_docs/python/tf/map_fn" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/map_fn</a>.</p>
<p>Lets assume that the CNN is built along similar lines as described here <a ... | tensorflow|deep-learning|convolution|lstm|recurrent-neural-network | 2 |
2,079 | 47,189,624 | Maintain a streaming microphone input in Python | <p>I'm streaming microphone input from my laptop computer using Python. I'm currently using PyAudio and .wav to create a 2 second batches (code below) and then read out the frame representations of the newly created .wav file in a loop. </p>
<p>However I really just want the <code>np.ndarray</code> represented by "sig... | <p>Yes, you can give a callback to the <code>stream</code> variable and do with that audio whatever you would like:</p>
<pre><code>def callback(input_data, frame_count, time_info, flags):
...
return input_data, pyaudio.paContinue
stream = audio.open(format=FORMAT,
channels=CHANNELS,
... | python|pyaudio|wave | 3 |
2,080 | 57,443,045 | How to determine an object's value in Python | <p>From the Documentation</p>
<blockquote>
<p>Every object has an identity, a type and a value.</p>
</blockquote>
<ul>
<li><code>type(obj)</code> returns the type of the object</li>
<li><code>id(obj)</code> returns the id of the object</li>
</ul>
<p>is there something that returns its value? What does the value of... | <p>to really see your object values/attributes you should use the <a href="https://stackoverflow.com/questions/19907442/python-explain-dict-attribute">magic method</a> <code>__dict__</code>.</p>
<p>Here is a simple example: </p>
<pre><code>class My:
def __init__(self, x):
self.x = x
self.pow2_x = ... | python|object|expression | 1 |
2,081 | 58,309,191 | Calling C++ dll from python | <p>I have a created dll library in c++ and exported it as c type dll. The library header is this:
<strong>library.h</strong></p>
<pre class="lang-cpp prettyprint-override"><code>struct Surface
{
char surfReq[10];
};
struct GeneralData
{
Surface surface;
char weight[10];
};
struct Output
{
GeneralData ... | <p>Changed the python ctypes to <code>c_char * 10</code>:</p>
<pre class="lang-py prettyprint-override"><code>class StructSurface(Structure):
_fields_ = [("surfReq", c_char * 10)]
class StructGeneralData(Structure):
_fields_ = [("surface", StructSurface),
("weight", c_char * 10)]
class OutDat... | python|c++|struct|dll|char | 0 |
2,082 | 33,733,189 | Stiff ODE-solver | <p>I need an ODE-solver for a stiff problem similar to MATLAB ode15s.</p>
<p>For my problem I need to check how many steps (calculations) is needed for different initial values and compare this to my own ODE-solver.</p>
<p>I tried using</p>
<pre><code>solver = scipy.integrate.ode(f)
solver.set_integrator('vode', met... | <p>I'm seeing something similar; with the <code>'vode'</code> solver, changing methods between <code>'adams'</code> and <code>'bdf'</code> doesn't change the number of steps by very much. (By the way, there is no point in using <code>order=15</code>; the maximum order of the <code>'bdf'</code> method of the <code>'vode... | python|numpy|scipy | 8 |
2,083 | 46,945,466 | Python - List of lists of different lengths | <p>I need to create a list which contains two lists.
Something like</p>
<pre><code>biglist = [list1,list2]
</code></pre>
<p>with </p>
<pre><code>list1 = [1,2,3]
list2 = [4,5,6,7,8]
</code></pre>
<p>where <code>list1</code> and <code>list2</code> have DIFFERENT length and are imported from file.</p>
<p>I did it the... | <p>please try:</p>
<pre><code>biglist.append(list(list1))
biglist.append(list(list2))
</code></pre>
<p>or if they are numpy arrays</p>
<pre><code>biglist.append(list1.tolist())
biglist.append(list2.tolist())
</code></pre> | python|arrays|list | 3 |
2,084 | 37,852,065 | Gathering statistics on how a program is used | <p>I have a few programs that do similar things, but they're written in different languages. I want to somehow monitor the way the programs I write are used - how many times is the code ran? How many times is a particular method/function used? How long did it take to compile? </p>
<p>My goal with this is to get a gra... | <p>I'll recommend looking at <a href="https://docs.getsentry.com/on-premise/" rel="nofollow">sentry</a>. It's free and has clients for many languages.</p>
<p>Basic usage: </p>
<pre><code>import time
from raven import Client
client = Client('https://<key>:<secret>@app.getsentry.com/<project>')
sta... | python|usage-statistics | 0 |
2,085 | 37,770,860 | How to save Matplotlib.pyplot.loglog to file? | <p>I am trying to generate the log-log plot of a vector, and save the generated plot to file. </p>
<p>This is what I have tried so far:</p>
<pre><code>import matplotlib.pyplot as plt
...
plt.loglog(deg_distribution,'b-',marker='o')
plt.savefig('LogLog.png')
</code></pre>
<p>I am using Jupyter Notebook, in which I g... | <p>Notice that pyplot has the concept of the current figure and the current axes. All plotting commands apply to the current axes. So, make sure you plot in the right axes. Here is a WME.</p>
<pre><code>import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.loglog(range(100), 'b-',marker='o')
plt.savefig('test.... | python|matplotlib|save|loglog | 1 |
2,086 | 65,799,949 | Add values to a data frame column at a specific row number | <p>I have a data frame <code>df</code> call which looks like:</p>
<pre><code> A B C
Date
02/02/2007 14.8966 0.289371 0.009984836
05/02/2007 14.8719 0.288368 -0.001659473
06/02/2007 14.9295 0.279869 0.003865595
07/02/2007 15.0035 0.283038 0.004944386
0... | <p>It's hard to verify what you are trying to do. From your code, this is what I guess:</p>
<pre><code>df['D'] = (df['A'].shift() # correspond to `Calc_df.iloc[-1, Calc_df.columns.get_loc('A')]`
.sub( df['B']) # subtract df['B']
.mul(df['C'].gt(0)) # only look at `df['C']>0`
... | python|pandas | 0 |
2,087 | 65,565,570 | Django+ HTML: EmptyPage at /HomeFeed/ Error: This page gets no errors | <p>Django+ HTML: EmptyPage at /HomeFeed/ Error: This page gets no errors. This happens when i log out and try to access the same page. When I am logged in, I am able to access the same exact page. Does it have to do with my views or my template. If you require a part of my template, please let me know :)</p>
<p>Thank y... | <p>I think it's caused by this.</p>
<p>blog_post = BlogPost.objects.filter(author=request.user.id)</p>
<p>if a user is not logged in it can't get the request.user.id</p>
<p>so either you make this page only for the authenticated or display something else if user is not authenticated.</p>
<p>you can add the <code>@login... | python|html|django|django-models|django-views | 0 |
2,088 | 72,222,674 | How to create a new column with a null value using Pyspark DataFrame? | <p>I'm having issues with using pyspark dataframes. I have a column called <strong>eventkey</strong> which is a concatenation of the following elements: <strong>account_type</strong>, <strong>counter_type</strong> and <strong>billable_item_sid</strong>. I have a function called <strong>apply_event_key_transform</strong... | <p>Found out the issue was caused when writing the DataFrame to json.Fixed this by upgrading pyspark to 3.1.1, which has a called <code>ignoreNullFields=False</code></p> | python|pyspark | 0 |
2,089 | 4,373,002 | splitting a string->list to be checked | <p>I've been lurking for a few weeks, and decided to join in order to be more hands-on with my learning of Python.</p>
<p>What I'm trying to do is take a single string, containing several web addresses, and come up with a list containing all the addresses with a domain name of 2-4 characters. The hypothetical addresse... | <p>Assuming you only care about the length of the TLD:</p>
<pre><code>[url for url in urlstring.split(',') if 2 <= len(url.split('.')[-2]) <= 4]
</code></pre> | python|string|split | 1 |
2,090 | 4,241,832 | most negative value for python | <p>I expect the most negative for python is <code>-maxint-1</code></p>
<p>I expect having -2, will make integer overflow.</p>
<pre><code>from sys import maxint
maximum_int = maxint
minimum_int = -maxint - 2
# 2147483647
# -2147483649
print maximum_int
print minimum_int
</code></pre>
<p>Yet. Correct result is displa... | <p>Here you can see the result is promoted to a long</p>
<pre><code>>>> from sys import maxint
>>> type(-maxint)
<type 'int'>
>>> type(-maxint-1)
<type 'int'>
>>> type(-maxint-2)
<type 'long'>
>>>
</code></pre>
<p>note that the usual convention for signe... | python | 18 |
2,091 | 69,563,455 | Django migration not working properly on Heroku | <p>I have deployed a Django App like 3 months ago and i was able to migrate changes easily on the heroku bash. Right now i'm trying this:</p>
<pre class="lang-sh prettyprint-override"><code>heroku run python manage.py migrate
</code></pre>
<p>Also tried this:</p>
<pre class="lang-sh prettyprint-override"><code>heroku r... | <p>If you are using SQlite, the migration changes on Heroku are applied and removed immediately. You have to use Heroku Postgres add-on (check on the your project overview if it's already installed) and add this to your settings.py</p>
<pre><code>if "DATABASE_URL" in os.environ:
import dj_database_url
... | python|django|bash|heroku | 0 |
2,092 | 51,117,323 | Python: How to change data type and override a variable from imported module | <p>I have two python programs in same folder named <strong>main.py</strong> and <strong>tk_version.py</strong>
I am importing main.py in tk_version.py
I have a variable in main.py which has default value lets say 'xyz'
Now in tk_version.py I am taking the value for the variable from user using Tkinter GUI.</p>
<p>So w... | <p>Just add <code>main.</code> before your variable name.</p>
<p><strong><code>tk_version.py</code></strong></p>
<pre><code>from tkinter import *
import main
Main = Tk()
main.var = StringVar()
def e1chk():
main.var = e1.get()
main.show()
return
e1 = Entry(Main, textvariable=main.var, width=50)
e1.... | python|tkinter | 0 |
2,093 | 17,665,180 | no module named requests | <p>I will first state I have searched for this problem, and found the exact same problem here ( <a href="https://stackoverflow.com/questions/16265368/importerror-no-module-named-requests">ImportError: No module named 'requests'</a> ) but that hasn't helped me.</p>
<p>I am using macports on osx (mountain lion).... | <p>In trying to sort this out, I have broken python, and eventually I got it going again. </p>
<p>I think initially I had not run one of the <code>port select --set...</code> commands. Once I realised this might be the case, I did so, but that produced the errors at the top. MAXREPEATS, a circular reference perhaps? N... | python|macos|import | 0 |
2,094 | 64,456,258 | How can I use the ValueError function correctly? | <p>This is my code:</p>
<pre><code>from time import sleep
def Kontostand_Berechnen():
if float(Kontostand_Nachfragen) >= float(Preis_Nachfragen):
sleep(1)
print("")
print("Du hast genug Geld!")
print("")
sleep(1)
else:
sleep(1)
... | <p>If you want to take advantage of the <code>ValueError</code> you need to use <a href="https://docs.python.org/3/tutorial/errors.html#handling-exceptions" rel="nofollow noreferrer"><code>try</code>/<code>except</code></a>. You will deal with the error in the <code>except</code> block. A simplified example might look ... | python|string|input|valueerror | 1 |
2,095 | 64,553,432 | Encoding binary file chunk by chunk fails | <p>The Zip file I need to encode seems to be too heavy and the method below gives me error:</p>
<pre><code>with open("/tmp/pdf/pdffiles.zip", "rb") as f:
binary_file = f.read()
encoded = base64.b64encode(binary_file)
self.download_zip = encoded
</code></pre>
<p>so I tried to chunk it but th... | <p>When chunking base64, it's important that your chunk sizes are multiples of 6, otherwise the data won't concatenate properly. You can try a number like <code>8208</code> and it should work.</p> | python|encode|binaryfiles | 2 |
2,096 | 64,572,969 | No module in python | <p>I am getting this warning. What should I do about it?</p>
<pre><code>File "alexis.py", line 17, in <module>
import wikipedia
ModuleNotFoundError: No module named 'wikipedia'
</code></pre> | <p>if you are using VS Code terminal try:</p>
<pre><code>py -m pip install wikipedia
</code></pre> | python|wikipedia | 1 |
2,097 | 69,947,408 | I'm using http.server with python3 and I want to store a request as a variable | <p>I have this code</p>
<pre><code>httpd = HTTPServer(('127.0.0.1', 8000),SimpleHTTPRequestHandler)
httpd.handle_request()
</code></pre>
<p>httpd.handle_request() serves one request and then kills the server like intended. I want to capture this request as a variable so I can parse it later on.
Something like</p>
<pre>... | <p>You could extend the <code>BaseHTTPRequestHandler</code> and implement your own <code>do_GET</code> (resp. <code>do_POST</code>) method which is called when the server receives a GET (resp. POST) request.</p>
<p>Check out the documentation to see what instance variables a <code>BaseHTTPRequestHandler</code> object y... | python|python-3.x|simplehttpserver|http.server|simplehttprequesthandler | 1 |
2,098 | 73,053,822 | How to logging to different log files by using for loop in python | <p>I am writing python script which establish ssh connection using paramiko and receive response of executed different commands on different NE and write logs for each NE in different log file. I am using below code in which i have defined logger main function and writing log to other function within same class. It is ... | <p>Here is the answer of above asked question</p>
<pre><code>def debug_file(self, debugfile):
global logger
logger = logging.getLogger(debugfile)
logger.setLevel(logging.DEBUG)
log_format = logging.Formatter('%(asctime)s %(message)s')
debug = logging.FileHandler(debugfile, mode='... | python-3.x|logging|paramiko | 0 |
2,099 | 66,363,019 | Code optimization by reducing number of if else statement | <p>I am writing code for library where thousand different color codes are stored and according to the normalized passed value the color will be selected. Here is the code for reference for just ten color to be returned :</p>
<pre><code>colour_coding=[]
i=0
step=0
while i<1000:
temp=(step,0,0)
colour_coding.a... | <p>Not a solution but this might give you an idea:</p>
<pre><code> import math
def color_code(value):
return color_code[math.ceil(value * 10) -1]
</code></pre>
<p>This code should be able to handle all of the conditions in your code above. You'll need to add condition to handle the index > 9 scenario.</p>
<p>Fo... | python-3.x|optimization | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.