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
3,100
56,304,895
How can I label the numpy array based on values?
<p>I have a numpy array of certain values ([5,6,7,8,10,11,12,14]); I want to label each value as:</p> <ol> <li><p>'N' if value is less than or equal 10</p></li> <li><p>'Y' if value is greater than 10</p></li> </ol> <p>My output will be an array/list that has the values: ['N','N','N','N','N','Y','Y','Y']</p> <p>I am ...
<p>There are many ways of doing this. Here are a few options:</p> <pre><code>In [1]: import numpy In [2]: x = numpy.array([5,6,7,8,10,11,12,14]) In [3]: x Out[3]: array([ 5, 6, 7, 8, 10, 11, 12, 14]) In [4]: x &gt; 10 Out[4]: array([False, False, False, False, False, True, True, True], dtype=bool) In [5]: ['...
numpy
1
3,101
71,483,915
I get the following error when trying to plot modelled data: ValueError: Length of passed values is 2, index implies 9. How to fix this?
<p>I am trying to plot observed and modelled data. This is an example of dataframe and below the code. I get this error #### ValueError: Length of passed values is 2, index implies 9####. I don't know how else to plot the modelled data.</p> <pre><code>all = [treatment1, treatment2] [ x y intercept 0 25...
<p>I assume you want to plot the function your model learned?<br /> If this is the case here is a simple implementation using the code snippets from the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html" rel="nofollow noreferrer">Official docs scipy.optimize.curve_fit</a>:</p> ...
python|pandas|matplotlib|linear-regression|curve-fitting
0
3,102
69,320,066
running file with exec or subprocess with python inputs
<p>My file is</p> <pre><code>#Requesting input of price from the cashier in dollars and cents price = round(100 * float(input(&quot;Enter the price of item bought:&quot;))) #Requesting input of amount of money given to the cashier in dollars and cents pay = round(100 * float(input(&quot;Enter the amount of money you g...
<p>Ok answer is easy</p> <pre><code>p = subprocess.Popen([&quot;python&quot;,f&quot;{i}&quot;],text=True,stdin=subprocess.PIPE) #, stdout=subprocess.PIPE) p.communicate(&quot;1 \n 2&quot;,timeout=None) </code></pre>
python|subprocess
0
3,103
69,301,115
Optimization of functions using pyomo models
<p>I have a problem with the optimization code. The code I have written should optimize the two objectives considering their expressions and produce value that can be plotted. This is my code as mentioned below.</p> <pre><code> from pyomo.environ import * import numpy as np import pandas as pd import random im...
<p>The problem is that your model is unbounded. You are trying to maximize it and there is no upper constraint, so the values could be infinite.</p> <p>You should always check the solver status first after solve to see what you got before digging in. Add this:</p> <pre><code>result = solver.solve(model); print(result...
python|pyomo|objective-function
0
3,104
57,449,252
How can I kill a child_process spwaned by node.js/electron correctly in windows?
<p>I am using Electron, Python and Flask to develop an app in Windows.</p> <p>I use</p> <pre><code>require('child_process').spawn('python', [_script,port]) </code></pre> <p>to start a child_process, but I cannot kill this child_process correctly.</p> <p>When the electron app was closed, there was still a process c...
<p>I don't see any reason for the Windows-specific branch there, I assume you added it when <code>pyProc.kill()</code> didn't work.</p> <p><a href="https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal" rel="nofollow noreferrer"><code>kill</code></a> defaults to SIGTERM. I'd expect that to wor...
javascript|python|node.js|electron
2
3,105
42,331,049
How to test Python classes that depend on argparse?
<p>The below paste contains relevant snippets from three separate Python files. The first is a script called from the command line which instantiates CIPuller given certain arguments. What happens is that the script gets called with something like: <code>script.py ci</code> (other args to be swallowed by argparse).</p>...
<p>Unittesting for <code>argparse</code> is tricky. There is a <code>test/test_argparse.py</code> file that is run as part of the overall Python unittest. But it has a complicated custom testing harness to handle most cases.</p> <p>There are three basic issues, 1) calling <code>parse_args</code> with test values, 2)...
python|argparse|pytest
9
3,106
54,152,752
How to read dict data from file and covert to JSON in Python
<p>I have following data in file. Getting error while I read and try convert to JSON.</p> <p><strong>File(modes.txt) :</strong> </p> <pre><code>{'status': True, 'mode': 'full'} {'status': False, 'mode': 'half'} </code></pre> <p>Code:</p> <pre><code>with open("modes.txt",'r') as f: ds = json.dumps(json.load(f)) <...
<p>Three issues with your source file's json format (tl;dr: it's not valid json)</p> <ol> <li>it's a series of dicts, but they aren't in a list, they're bare</li> <li><code>True</code> is <code>true</code> in json, same for <code>False</code> which is <code>false</code></li> <li>As you noted, single vs double quotes. ...
python|json
2
3,107
54,194,772
Iterate over loop and adding list to dataframe in new row or new column
<p>I'm sure this is simple but I'm quite new to Python. I have trouble how to add a list to a dataframe column or row after each iteration of the loop. I want to loop through a list of around hundred URLs with the outer for-loop and extract the data with the inner loop. Every time </p> <p>With the code now I can creat...
<p>I assume you meant every iteration of the outer loop in a new "row". This would create a 2 dimensional array (list) as a result, for each element in link_href_list you would get a new "row". Although, I have no idea what the to_frame() method is, I assume it is a printout.</p> <pre><code>list_columns = [] for x in...
python|list|loops|dataframe
3
3,108
53,827,374
Cannot import six on GAE local development environment
<p>I got below error when trying to run my GAE Python 2.7 app.</p> <pre><code>ImportError: No module named six </code></pre> <p>I have followed <a href="https://cloud.google.com/appengine/docs/standard/python/tools/built-in-libraries-27" rel="nofollow noreferrer">this</a> page and set up my <code>app.yaml</code> file...
<p>I've experienced issues with random libraries that are present in production being absent in my localhost (namely pycrypto on osx)</p> <p>So, in addition to having a <code>lib</code> folder for all my third party libs: <a href="https://cloud.google.com/appengine/docs/standard/python/tools/using-libraries-python-27"...
python|google-app-engine|google-cloud-platform
1
3,109
58,261,669
Creating word frequency pairs, keeping both words and both frequencies
<p>I have a list of word pairs in Icelandic that are spelled similarly but mean different things (for example leyti and leiti, kyrkja and kirkja). The list is just a single element list, not a list of tuples (so just [leyti, leiti, kyrkja, kirkja]). I'm using a big corpus to get each word's frequency, so I could end up...
<p>Even with your current solution, you don't need to iterate over the entire <code>freqdic</code> every time, you want one value from it. You can just do:</p> <pre class="lang-py prettyprint-override"><code>for i in ywords: yfreq[i] = freqdic[i] </code></pre> <p>If you want to have the words together with their ...
python|nlp|word-frequency
0
3,110
58,380,737
Python: money variable is not updating after coin toss. Can someone tell me what I'm doing wrong?
<p>I'm new to programming and part of my Python class assignment is to create random chance games. First game is suppose to be "Coin Flip" and there is a money variable involved. I got the coin flip function to work but for some reason it's not updating the money variable outside of the function. Can someone tell me...
<p>In your function you need to declare that money is <strong>global</strong> like this:</p> <pre><code>def coinflip(bet, choice): global money ... </code></pre> <p>Also, you are not assigning new value, instead comparing two values. Use = instead of == in places like this one:</p> <pre><code>money == money ...
python-3.x
3
3,111
58,206,250
Parsing XML: Python ElementTree, find elements and its parent elements without other elements in same parent
<p>I am using python's ElementTree library to parse an XML file which has the following structure. I am trying to get the xml string corresponding to entity with id = 192 with all its parents (folders) but without other entities</p> <pre><code> &lt;catalog&gt; &lt;folder name="entities"&gt; &lt;e...
<p>The challenge here is to bypass the fact that ET has no parent information. The solution is to use <code>parent_map</code> </p> <pre><code>import copy import xml.etree.ElementTree as ET import xml.dom.minidom as minidom xml = '''&lt;catalog&gt; &lt;folder name="entities"&gt; &lt;entity id="102"...
python|xml|python-2.7
2
3,112
65,470,132
Please suggest python code to clone repository from gitub having user and password
<p>username = rohan Password = rohan!@#$ clonerepourl = https://rd667j@codecloud.web.att.com/scm/~vy381y/dcae_ms_status.git MyDir = C://python//Rohan</p> <p>I want to write python code to clone this repo to MyDir . Please help . I tried below but didnt helped . git clone https://rohan:rohan!@#$@https://rd667j@codecloud...
<p>First: Try to get de exactly command that you put in your console when you try to clone a repository: For example:</p> <pre><code>git clone https://username:password@github.com/username/repository.git </code></pre> <p>Then you can use the <code>system</code> module in order to perform that command:</p> <pre><code>fr...
python|python-3.x|eclipse
0
3,113
65,425,099
List comprehension with a Boolean whose value changes throughout iterations
<p>I'm attempting to create a list comprehension from a nested for loop with if statements, and I can't figure it out. I scanned the internet for hours but couldn't find a solution.</p> <p>The loop looks like that:</p> <pre><code>lengths = [] data_frame = p.read_excel(fasta_path_[:-2] + 'xlsx', engine='openpyxl') seqid...
<p>The interpretation what this code is doing, or trying to do, comes down to this clause:</p> <pre><code>for seq_id in seqids: if seq_id in line: identical_ids = True continue else: identical_ids = False continue </code></pre> <p>As @AnnZen notes in her answer, this is effective...
python|if-statement|list-comprehension|nested-loops
1
3,114
65,180,184
Unable to read some files found using os.walk
<p>I am unable to read handful of files in my computer using python. Most of the folders in the computer look ok, but 200 or so files in the whole computer can't be read.</p> <p>Code on a high level is doing this</p> <pre><code>for root, dirs, files in os.walk(r'C:\DR\SomeFolder'): for f in files: print(f, ...
<p>Yes. the user has permissions. I am running it as myself and is able to open the file in explorer</p>
python|filesystems|python-os
0
3,115
65,309,885
Skipping a nested for loop iteration - Python
<p>First off, let me explain what I'm attempting to do.</p> <p>I'm wanting to print a quadrilateral(square shape) using strings from a list. Like so:</p> <pre><code>John o h h o nhoJ </code></pre> <p>I get the printed results I'm wanting except my for loop is printing more than needed. I just need to skip a few loop ...
<p>Don't use nested loops, that creates a cross product between the forward and reverse lists. Use <code>zip()</code> to loop over them together.</p> <pre><code>for i, j in zip(norm_list[1:-1], reve_list[1:-1]): print(f&quot;{i}{spaces}{j}&quot;) </code></pre>
python|for-loop|shapes|nested-for-loop
1
3,116
22,758,469
Is it a clean way to implement a kind of "__tuple__" method?
<p>Let that an object a of a class A has an attribute ".my_tuple". I want to be able to get this attribute calling.</p> <pre><code>tuple(a) </code></pre> <p>the simplier way I found is to define A such as:</p> <pre><code>class A(): # other things def __iter__(self): return self.my_tuple.__iter__() </...
<p>The built-in <code>tuple()</code> is not designed as a point of customization for your classes. As far as I know there is no customization point for conversion to tuple.</p> <p>So instead you've used a designed point of customization, the <code>iter()</code> built-in and corresponding <code>__iter__</code> method. ...
python|python-3.x
4
3,117
28,643,072
ImageField not uploading correctly
<p>I am trying to upload an image to the server. No matter what I do, it doesn't appear to properly upload the image. Here is my field in the model: </p> <pre><code>image = models.ImageField(upload_to='uploads/images/staff', verbose_name='Staff Member Photo', help_text='Required Dimensions: Square, about 275px heig...
<p>You should use the absolute path in the <code>MEDIA_ROOT</code> property. For example:</p> <pre><code>MEDIA_ROOT = '/var/www/mysite/static/media/' </code></pre> <p>BTW, what error you get then uploading the image? Is it a path-related problem?</p>
django|python-2.6|django-1.5|imagefield
0
3,118
6,382,705
Add two matrices in python
<p>I'm trying to write a function that adds two matrices to pass the following doctests:</p> <pre><code> &gt;&gt;&gt; a = [[1, 2], [3, 4]] &gt;&gt;&gt; b = [[2, 2], [2, 2]] &gt;&gt;&gt; add_matrices(a, b) [[3, 4], [5, 6]] &gt;&gt;&gt; c = [[8, 2], [3, 4], [5, 7]] &gt;&gt;&gt; d = [[3, 2], [9, 2], [10, 12]] ...
<h2>Matrix library</h2> <p>You can use the <code>numpy</code> module, which has support for this.</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.matrix([[1, 2], [3, 4]]) &gt;&gt;&gt; b = np.matrix([[2, 2], [2, 2]]) &gt;&gt;&gt; a+b matrix([[3, 4], [5, 6]]) </code></pre> <hr> <h2>Home-g...
python|nested-lists
23
3,119
57,185,196
Regarding Time complexity of program
<p>I have done question in one of competitive exam but I am struggling to find out the <strong>time complexity</strong> of program i.e whether it is <strong>O(n) or O(n^2)</strong> in python 3.can any one help me. </p> <p>I asked one of my friends some of them told it is O(n),and some of them told it is O(n^2) so I am...
<p>Where </p> <p><code>n = len(s) m = len(b)</code> </p> <p>your code will scale with time complexity</p> <pre><code>O(m*n) </code></pre> <p>Since in the worst case you loop through the whole base string and perform <code>m</code> maximum constant time if operations. N is often used as a placeholder in theory but ...
python|string|time-complexity
0
3,120
25,528,709
builtins.True syntax error
<p>Why does the following code generate a syntax error?</p> <pre><code>&gt;&gt;&gt; import builtins &gt;&gt;&gt; dir(builtins) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'C...
<p><code>True</code> is a reserved keyword, and that means you cannot use it as an attribute name either. Like names, attributes must be valid Python identifiers.</p> <p>You can still access the object as an attribute with <code>getattr()</code>:</p> <pre><code>&gt;&gt;&gt; import builtins &gt;&gt;&gt; getattr(built...
python|python-3.x|boolean|built-in
7
3,121
44,542,944
python pandas: group time series by cumsum defined value, reset sum if value is reached
<p>I have a data frame with column A and B. Desired outcome: If cumsum of B reaches value >=15, following operations for the rows between 0 and cumsum >=15 shall be computed: df["Amean"] =df["A"].mean() and df["Bsum15"] = df["B"].sum() ; then cumsum shall be reset to 0 again and the loop continues.</p> <p><a href="ht...
<p>lets say, we take a simpler example</p> <pre><code>df=pd.DataFrame([1,2,3,4,5,6,7,8,9,10],columns=['B']) def accum(vals): acc=0 for i in vals: acc+=i if acc&gt;=15: yield acc acc=0 else: yield np.nan df['accu']=list(accum(df['B'].values)) </code></...
python|pandas|reset|cumsum
0
3,122
23,706,268
Updating by index in an multi-dimensional numpy array
<p>I am using numpy to tally a lot of values across many large arrays, and keep track of which positions the maximum values appear in.</p> <p>In particular, imagine I have a 'counts' array:</p> <pre><code>data = numpy.array([[ 5, 10, 3], [ 6, 9, 12], [13, 3, 9], ...
<p>You could use so-called <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#integer" rel="nofollow">advanced integer indexing</a> (aka <a href="http://wiki.scipy.org/Cookbook/Indexing#head-4775c8118fff07ae55b6e3b95c3b48e540160fc2" rel="nofollow">Multidimensional list-of-locations indexing</a>):</...
python|numpy
2
3,123
72,056,551
Calling FileField objects in template renders incorrect path
<p>I've implemented a FileField model in my project. I can successfully upload svg files and they save to the desired location.</p> <p>Within my project, I make heavy use of user uploaded images (JPGs) and they save to the correct location and I can display them in my templates with no issue.</p> <p>However, when I upl...
<p>You need to pass the <code>url</code> of image, as it contains the original url which links to all media files.</p> <p>Try this:</p> <pre><code>&lt;img src=&quot;{{account.image.url}}&quot; /&gt; </code></pre> <p>It will give you desired output.</p>
python|django|django-templates
1
3,124
71,987,009
Group data by ranges in pandas
<p>I have a df as shown:</p> <pre><code>Value 1 2 3 4 5 4 5 5 6 6 7 7 8 8 9 9 </code></pre> <p>Now I want to divide this df into 5 categories namely as per score range</p> <pre><code>0-2: Very Low 2-4: Low 4-6: Medium 6-8: High 8-10:Very High </code></pre> <p>Hence the resultant df should be given as:</p> <pre><code>Va...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html" rel="nofollow noreferrer"><code>pd.cut</code></a>, for example:</p> <pre class="lang-py prettyprint-override"><code>labels = [&quot;Very Low&quot;, &quot;Low&quot;, &quot;Medium&quot;, &quot;High&quot;, &quot;Very High&q...
pandas|dataframe|group-by
1
3,125
72,083,685
np.random.choice not producing expected histogram
<p>I'm looking to generate <code>random normally distributed</code> numbers between 1 and 0, but as the <code>mean</code> moves closer to 1 or 0, the right or left side respectively becomes &quot;squished&quot;.</p> <p>After modifying the normal distribution and playing around with sliders in geogebra, I came up with t...
<p>It looks like there is a problem with the first argument in the call <code>np.random.choice(samples, p=probabilities)</code>. The first argument should be <code>x</code>, not <code>samples</code>.</p> <p><strong>ADDITION BY AUTHOR:</strong></p> <p>The reason for this is the <code>samples</code> are the values of th...
python|numpy
1
3,126
36,002,422
Python: Unite a 2d array and a 1d array in a 3 column array
<p>I am new to python, I really appreciate it if you could help me.</p> <p>I have a 2 column array <em>i.e. d.T</em>, and a 1 column array <em>i.e. result</em> and want to unite them in a 3 column array, I tried many times around but could not find the best way to do so, even I tried np.vstack but it doesn't work due ...
<p>Try </p> <p>data = np.column_stack((d.T, myarray))</p> <p>No need for data = []</p>
python|numpy
2
3,127
14,998,399
How to parse with one regular expression this string in Python
<p>I need to parse this string, with only one regular expression in Python. For every group I need to save the value in a specific field. <strong>The problem is that one or more of the parameters may be missing or be in a different order.</strong> (i.e. <code>domain 66666 ip nonce</code>, with the middle part missing)<...
<p>It's probably not a good idea to use one regex to parse the whole string. but I think the solution is to use <code>named groups</code> (see: <a href="http://www.regular-expressions.info/named.html" rel="nofollow">Named groups on Regex Tutorial</a>. <code>Named groups</code> can be captured by <code>(?P&lt;nameofgrou...
python|regex
1
3,128
14,946,015
Proxying requests to Tornado with Apache - 502 Error
<p>Trying to figure out why we get <code>502 ProxyError</code> on our requests, especially when serving long-running requests on our Python servers. </p> <p>Our servers are on CentOS, and we use <code>httpd</code> to proxy Web requests, which then get routed to a Tornado server running a WSGI REST application (which ...
<p>Try this </p> <p>ProxyPass /rest/ http:// server_ip:8000/ <strong>connectiontimeout=5 timeout=30</strong></p> <p>Change the timeouts to whatever suits you best.</p> <p>More info on <a href="http://httpd.apache.org/docs/current/mod/mod_proxy.html" rel="nofollow">http://httpd.apache.org/docs/current/mod/mod_proxy.h...
python|apache|proxy|reverse-proxy
1
3,129
46,522,252
Python multiprocessing and too many open files
<p>I have problem with multiprocessing in python. In code below I call 7 workers (multiprocessing.Process) and one result threading.Thread. Before and after processing of data (extracting some metadata from files), I run:</p> <pre><code>lsof | grep ' &lt;user&gt; ' | grep 'python3' </code></pre> <p>And I get some ope...
<p>Already solved, I needed to send some ending signals to workers and result thread to stop never-ending loop</p>
python|python-3.x|python-multiprocessing|python-multithreading
0
3,130
21,069,294
Parse the JavaScript returned from BeautifulSoup
<p>I would like to parse the webpage <a href="http://dcsd.nutrislice.com/menu/meadow-view/lunch/">http://dcsd.nutrislice.com/menu/meadow-view/lunch/</a> to grab today's lunch menu. (I've built an Adafruit #IoT Thermal Printer and I'd like to automatically print the menu each day.)</p> <p>I initially approached this us...
<p>All you need is a little string slicing:</p> <pre><code>import json soup = BeautifulSoup(urllib2.urlopen(url).read()) script = soup.findAll('script')[1].string data = script.split("bootstrapData['menuMonthWeeks'] = ", 1)[-1].rsplit(';', 1)[0] data = json.loads(data) </code></pre> <p>JSON is, after all, a subset o...
javascript|python|beautifulsoup|html-parsing
11
3,131
20,940,076
Ellipse Tool in Python part 2
<p>I am currently making changes to the way my ellipse tool works as it was not working the correct way previously. I am creating it for my paint program using python 2.7.5 and pygame. I have recently encountered this error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\Wisdom1\Desktop\Comp Science...
<p>You could also use a ternary statement in the form of:</p> <pre><code>draw.ellipse(screen,(c),(x,y,radx,rady), sz2 if sz2 &lt; max(radx, raxy) else 0) </code></pre> <p>Sincerely,</p> <p>Another Massey student working on a Sunday night ;)</p>
python|pygame|paint|draw|ellipse
1
3,132
62,484,167
Why HTML file that I got from Google Translate using my script, is different from what I really want?
<p>I want to make a web scraper that will automatically take the translation of a word from Google Translate, in my console environment using my python script.</p> <p>I saw that HTML code which I got from python <code>Requests</code> module, is very different from what it is on the website, you can see the <a href="htt...
<p>You can use <a href="https://pypi.org/project/googletrans/" rel="nofollow noreferrer">googletrans</a> module of Python to translate some text through free API.</p> <p>But if you want to scrape the Google Translate then you can do the following</p> <pre><code>import requests_html from bs4 import BeautifulSoup as BS ...
python|python-requests
0
3,133
62,879,867
Tensorflow Installation Error in Conda Environment
<p>I am trying to install Tenserflow through <a href="https://docs.conda.io/en/latest/" rel="nofollow noreferrer">Conda</a>. When I run:</p> <p><code>pip install --upgrade tensorflow</code></p> <p>I get the following error:</p> <pre><code>Collecting tensorflow Downloading tensorflow-2.2.0-cp36-cp36m-win_amd64.whl (45...
<p>Please follow the link given below. This has helped me and my friends a lot of times.</p> <p><a href="https://youtu.be/O8yye2AHCOk" rel="nofollow noreferrer">https://youtu.be/O8yye2AHCOk</a></p>
python|tensorflow|pip|conda
0
3,134
46,064,849
Error installing scipy whl file using pip inPython 3.6
<p>I am trying to install scipy for 3.6, but i get an error: </p> <blockquote> <p>"scipy.....whl is not supported on this platform."</p> </blockquote> <p>I have been attempting to do this via my scripts and using pip install but i am unsure why this is not working.</p>
<p>For 32-bit Python you need scipy‑0.19.1‑cp36‑cp36m‑win32.whl. To install scipy‑0.19.1‑cp36‑cp36m‑win_amd64.whl you need 64-bit Python.</p>
python|installation|scipy|pip|python-3.6
2
3,135
54,857,477
Compare accuracy of different models
<p>I am trying to build a way to plot the accuracy of different ML models such as </p> <pre><code>from sklearn import model_selection from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier </code></pre> <p>I have used this...
<p><code>plt.plot</code> will plot lines as you noticed. What you need is <code>plt.bar</code> which will plot a barplot. Provided the names of the models are stored in a list <code>names</code> and the accuracies in a list <code>results</code> like in your code snippet, this should do:</p> <pre><code>plt.bar(names,re...
python-3.x|matplotlib|plot|scikit-learn
0
3,136
54,821,729
how to add just the values in key s1
<pre><code>students={ 1: {"pup1": "001", "s1": 10, "s2": 20}, 2: {"pup2": "124", "s1": 20, "s2": 30}, 3: {"pup3": "125", "s1": 30, "s2": 40}} </code></pre> <ol> <li>List item</li> </ol>
<p>If you want to add all the values of s1, you need to iterate over the values() of dictionary students.</p> <pre><code>students={ 1: {&quot;pup1&quot;: &quot;001&quot;, &quot;s1&quot;: 10, &quot;s2&quot;: 20}, 2: {&quot;pup2&quot;: &quot;124&quot;, &quot;s1&quot;: 20, &quot;s2&quot;: 30}, 3: {&quot;pup3...
python|dictionary
-2
3,137
33,481,849
Can a Google Apps domain admin list the messages of a user?
<p>We created an application for Google Apps Marketplace. We want our application to check how many emails each user sent and received per day. I tried to test the form on <a href="https://developers.google.com/gmail/api/v1/reference/users/messages/list" rel="nofollow">https://developers.google.com/gmail/api/v1/referen...
<p>It is possible. For this, you would need to impersonate the user and then make the same call to the API that you mentioned.</p> <p>In order to impersonate a user an act on hi's behalf, you have to implement <a href="https://developers.google.com/drive/web/delegation" rel="nofollow">domain wide delegation</a> of aut...
python|google-apps|google-apps-marketplace
1
3,138
12,813,265
quick and dirty binary xor function
<p><img src="https://i.stack.imgur.com/d4Kpq.jpg" alt="the basic function i am trying to do">Hey me again o'merciless stack overflow gods.</p> <p>I'm just looking for a way to get started on a simple xor hash function. I'm a tad prevented from accessing my usual sources as the Ethernet cable has been mysteriously disc...
<p>After reading your assignment question:</p> <p>First, you need to convert your text into the binary encoding for the ascii values of its characters:</p> <pre><code>''.join(bin(ascii)[2:] for ascii in [ord(char) for char in my_text]) </code></pre> <p>This gives you the binary encoded ascii values for all character...
python|hash|binary
1
3,139
21,882,460
Filter Specific Part of Speech NLTK
<p>this must be simple but I'm missing it somehow. I have the code:</p> <pre><code>import nltk f=open('...\\t.txt','rU') raw=f.read() tokens = nltk.word_tokenize(raw) print nltk.pos_tag(tokens) </code></pre> <p>which returns for instance:</p> <p>"[('processes', 'NNS'), ('a', 'DT'), ('sequence', 'NN'), ('of', 'IN')...
<p>You can extract only the tags you want with a list comprehension, e.g.:</p> <pre><code>&gt;&gt;&gt; tags = nltk.pos_tag(tokens) &gt;&gt;&gt; dt_tags = [t for t in tags if t[1] == "DT"] &gt;&gt;&gt; dt_tags [('a', 'DT')] </code></pre>
python|filter|nltk|pos-tagger
5
3,140
38,328,021
Passing several variables from Excel to Python with XLwings
<p>I have the same question as this post but with multiple variable (and with a macro instead of a function) (<a href="https://stackoverflow.com/questions/34167920/passing-a-variable-from-excel-to-python-with-xlwings">Passing a variable from Excel to Python with XLwings</a>)</p> <p>I try this </p> <pre><code>Sub Hell...
<p>Your string resolves to a single argument. Fix the single quotes like this:</p> <pre><code>RunPython ("import Test; Test.sayhi('" &amp; Name1 &amp; "' , '" &amp; Name2 &amp; "')" </code></pre>
python|xlwings
1
3,141
38,234,003
Pandas Dataframe find and replace
<p>I have two lists:</p> <pre><code>single = ['A','B'] double = ['AA','BB'] </code></pre> <p>Data stored in dataframe <code>df</code>:</p> <pre><code> 0 1 2 3 0 All 1 AA Yes 1 A 2 All No </code></pre> <p>where All means <code>['A','B']</code> in column 0 and means <code>['AA','BB']</code> in ...
<pre><code>import pandas as pd single = ['A','B'] double = ['AA','BB'] df = pd.DataFrame([['All',1,'AA','Yes'],['A',2,'All','No']]) first = pd.DataFrame([x for item in single for x in [('All', item), (item, item)]], columns=[0, 'first']) third = pd.DataFrame([x for item in double ...
python|pandas
2
3,142
30,893,565
PyQt / Qt, tableview with custom delegate to use ellipsis for text overflowing cell
<p>Without custom delegate everything works fine:</p> <p><img src="https://i.imgur.com/hb46SAg.png" alt="enter image description here"></p> <p>But my tableview shows search results and part of the text needs to be bold to indicate where it matches the searched query.</p> <p>Once I use the delegate to get html tags w...
<pre><code>painter.setClipRect(textRect.translated(-textRect.topLeft())) </code></pre> <p>I thoughtI had it in my delegate, its in all other answers around here, well it does the clipping correctly, though no fancy ellipsis, but thats ok I guess. I assumed previously that theres just some value that I have to enable t...
python|qt|pyqt|qtableview
2
3,143
8,948,763
Unable to save to database. Submitting form refreshes form page instead
<p>I'm trying to carry over player_id and save to the Stakes table referencing that player_id, which is the foreign key for the Stakes table. However, I am not sure how to do so. I have edited my views.py to reflect two of the answers below, but it still seems to refresh the form and not save to the database. The only ...
<p>This answer was given to me by someone a different website. He had no desire to repost it here, but I will copy/paste in order to accept the answer and for future reference.</p> <p>In the view, looking up the player_id should be called even if the POST data was not sent. That ensures you get a 404 anytime there is ...
python|mysql|django
0
3,144
52,442,658
How to convert hex to dec manually in python?
<p>This is my first time using this QnA site... I had this task in my class which asks me to convert numbers from any basis into decimal using method... I'm very confused about converting alphabets contained in a hex number. Here is the program which I type: </p> <pre><code>def base_n_to_dec(num_string, base): dec...
<pre><code>alphabet = '0123456789ABCDEF' def base_n_to_dec(num_string, base): ''' :param num_string: string containing number in base10 :param base: integer between 2 and 16 :returns: num_string based base as a string ''' b10_num = 0 for digit in num_string: b10_num *= ...
python
0
3,145
19,208,856
MySQL, should I stay connected or connect when needed?
<p>I have been logging temperatures at home to a MySQL database (read 10 sensors in total every 5 minutes), and have been using Python, but I am wondering something...</p> <p>Currently when I first run my program, I run the normal connect to MySQL, which is only run once.</p> <pre><code>db = MySQLdb.connect(mysql_ser...
<p>MySQL servers are configured to handle a fixed limited number of connections. It's not a good practice to tie up a connection that you are not using constantly. So typically you should close the connection as soon as you are done with it, and reconnect only when you need it again. MySQLdb's connections are context m...
python|mysql
8
3,146
69,173,546
Unable to fetch Web table data via Python
<p>I am unable to fetch data with following program, it does not show any error but except header nothing else is fetched. Kindly guide me. This program works with other links, but not with this specific link, also I want to fetch data from all pages , without using selenium</p> <pre class="lang-py prettyprint-override...
<p>The table is generated dynamically with JavaScript, so you won't get it with <code>bs4</code> as it's simply not in the source HTML.</p> <p>However, there's an endpoint you can query that returns all the data that's used to populate the table.</p> <p>Here's how:</p> <pre class="lang-py prettyprint-override"><code>im...
python|python-requests
0
3,147
62,160,413
unsupported operand type(s) for +: 'int' and 'Entry'
<p>I get that <code>z</code> is an <code>Entry</code> and that 5 is an <code>integer</code> but I don't know how to change <code>z</code> to be an <code>integer</code> that the user could enter.<br> This is my code:</p> <pre><code>import smtplib from tkinter import * window = Tk() z = Entry(window, width=35, bg="whi...
<p>In tkinter you have <code>StringVar()</code> and <code>IntVar()</code> for string and integer respectively. So here you need to use a keyword argument to Entry widget called <code>Entry(.....,textvariable=my_var)</code> and in tkinter you have to define the variable before using it, so here is your code and I have s...
python|tkinter
1
3,148
67,305,932
Error Handling in Python3 - Finding location of specific letters in a list of words
<p>I am running into issues getting my code to run through a list of words and list the location of the letters in the list. It works fine in listing location for the first two words, but when it encounters a word without the specified letter, the code skips. I will paste the problem and my current code as well as curr...
<p>Use try and except block to get the position of letters in the word.</p> <pre><code>for letter in words: try: print(letter.index(&quot;o&quot;)) except: print(&quot;not found&quot;) pass </code></pre>
python|python-3.x|list|error-handling|letter
1
3,149
19,621,297
How do I display a copyleft symbol?
<p>I use Google AppEngine, Python 2.7 and Jinja2 template. I tried this one <a href="https://en.wikipedia.org/wiki/Copyleft#Symbol" rel="nofollow">https://en.wikipedia.org/wiki/Copyleft#Symbol</a> from Wikipedia. As html it prints fine on my browser. But when I insert it in a jinja2 template and try testing it in my G...
<p>I suggest replacing the copyright symbol <code>©</code> in the template with <code>&amp;copy;</code></p>
python|google-app-engine|jinja2
3
3,150
13,494,234
Python Alt Hooking
<p>I was writing this type-recording program when I encountered a problem - <kbd>Alt</kbd> key doesn't have an Ascii number so I can't hook it in the regular way. This is my source code without the <kbd>Alt</kbd> hooking try, the question is - how do I hook <kbd>Alt</kbd>? I know that there is Class variable named "Alt...
<p>Instead of using <strong>event.Ascii</strong> when mapping keys, use <strong>event.KeyID</strong>.</p> <p>Note that keys like <strong>AltGr</strong> have 2 mapping IDs: one for pressed key and another for released key.</p>
python|hook|alt|pyhook
0
3,151
13,526,654
Tracking a multicolor object
<p>I want to track a multicolored object(4 colors). Currently, I am parsing the image into HSV and applying multiple color filter ranges on the camera feed and finally adding up filtered images. Then I filter the contours based on area. </p> <p>This method is quite stable most of the time but when the external light v...
<p>For a full proof track you need to combine more than one method...following are some of the hints...</p> <ol> <li><p>if you have prior knowledge of the object then you can use template matching...but template matching is little process intensive...if you are using GPU then you might have some benefit</p></li> <li><...
python|opencv|tracking
0
3,152
22,410,512
How can I access the virtualenv management commands?
<p>I can't access any of the virtualenv management commands, such Get-VirtualEnvironment. I did the following in Windows-XP: </p> <ol> <li>Installed C:\Python27. </li> <li>Installed pip and setuptools in C:\Python27\Lib\site-packages. </li> <li>Using PowerShell, ran "pip install virtualenv". </li> <li>Created the envi...
<p><strong>First:</strong> Install virtualenv with pip install (in your Python <code>\Scripts</code> dir)</p> <pre><code>C:\Python2\Scripts&gt;pip install virtualenv Downloading/unpacking virtualenv Downloading virtualenv-1.11.5.tar.gz (1.8MB): 1.8MB downloaded Running setup.py egg_info for package virtualenv ...
python|windows|virtualenv
0
3,153
22,124,648
How to make script not crash when wrong username and password is entered? (smtplib - gmail login)
<p>I have this problem where when the user enters the wrong username and password, it would receive this error and crash (I am fairly new to python):</p> <pre><code>File "/Users/19austinh/Google Drive/Other/Python/Login.py", line 156, in &lt;module&gt; user.login(euser, epass) File "/Library/Frameworks/...
<p>Use nested <code>while</code> loop:</p> <pre><code>while True: user = smtplib.SMTP('smtp.gmail.com', 587) user.starttls() while True: euser = input("Enter Gmail Username: ") epass = input("Enter Gmail Password: ") try: user.login(euser, epass) except smtplib.S...
python|python-3.x|input|smtp|smtp-auth
1
3,154
16,965,802
Testing for pygame sprite collision
<p>I have been going through some pygame tutorials, and I have developed my own code based off of these tutorials. It is as follows:</p> <pre><code>#!/usr/bin/python import pygame, sys from pygame.locals import * size = width, height = 320, 320 clock = pygame.time.Clock() xDirection = 0 yDirection = 0 xPosition = 3...
<p>The problem with your code is that your character is moving more than one pixel each step. For example, when moving at maximum velocity, your character moves 22 pixels each step. So if he's 10 pixels above the grass one step, he'll be 12 pixels <em>below</em> the grass on the next step. To fix this, you test to see ...
python|pygame|collision-detection
3
3,155
54,407,027
Use API to write to json file
<p>I am facing this problem while I try to loop <code>tweet_id</code> using the API and write it to <code>tweet_json.txt</code>, the output for all data is <code>Failed</code> which I know is wrong </p> <p>Before it was working good but when I try to Run all the code again it starts to show failed</p> <pre><code>for ...
<p>Your <code>except</code> is swallowing whatever exception is causing your code to die. Until you comment out the <code>except</code> or make it more specific you won't know if your problem is the Twitter API or file I/O or something else. Good luck!</p>
python
0
3,156
39,267,981
expand plot for readability without expanding lines
<p>I am plotting 2 lines and a dot, X axis is a date range. The dot is most important, but it appears on the boundary of the plot. I want to "expand" the plot further right so that the dot position is more visible. In other words I want to expand the X axis without adding new values to Y values of lines. However if I j...
<p>There are a couple of ways to do this.</p> <p>An easy, automatic way to do this, without needing knowledge of the existing <code>xlim</code> is to use <a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.margins" rel="nofollow"><code>ax.margins</code></a>. This will add a certain fraction of the da...
python|matplotlib|plot
3
3,157
52,701,522
TypeError: get_tier_by_name() takes exactly 2 arguments (3 given) in Pycharm
<p>During the execution of this code on pycharm I got the following error:</p> <pre><code>TypeError: get_tier_by_name() takes exactly 2 arguments (3 given) </code></pre> <p>Here is the code</p> <pre><code>import os import tgt from pydub import AudioSegment tg = tgt.read_textgrid("arabic1_0.TextGrid") ipu_tier = tg...
<p>You are passing 2 arguments, it requires 1:</p> <p>in tgt/core.py:</p> <pre><code> def get_tier_by_name(self, name): '''Get the first tier with the specified name.''' for tier in self._tiers: if tier.name == name: return tier raise ValueError('Textgrid ' ...
python
0
3,158
47,707,784
OpenSimplex noise generation problems (just seems random, is my function wrong?)
<p>I'm working on a 2d tile based game in pygame and I'm trying to use a noise map to generate my map.</p> <p>I've installed the OpenSimplex library and everything works fine there. Problem is that I don't seem to be getting a smooth random gradient, it looks more like random noise. </p> <p>Here's the function I'm u...
<p>OpenSimplex is used with floating non-integers. What you see is a kind of zoomed out version of the noise. You should decide a scale variable to easily fix this. A scale of about 100 would work really well with your example. Feel free to change it around.</p> <pre><code>def generate_noise(seed,game): scale = 100...
python|pygame|simplex-noise
0
3,159
34,092,776
Issue with translation in Django + Mezzanine
<p>I have followed the approach described <a href="http://blog.karolmajta.com/robust-internationalized-urls-for-django/" rel="nofollow">here</a>.</p> <p>On the index page I have a form which allows me to switch between website languages. I have added "next" post attribute enable redirection to the correct language ver...
<p>I have solved my problem in following way. Firstly, changed the form:</p> <pre><code>&lt;form action="{% url 'set_language' %}" method="post"&gt; {% csrf_token %} &lt;input name="language" type="hidden" value="{{ language.code }}" /&gt; {% if request.path|slice:"4:"|length &gt; 0 %} &lt;input name="next" type="...
python|django|mezzanine
1
3,160
66,262,446
Use Virtuoso store with RDFLIB
<p>I am trying to use <a href="https://pythonhosted.org/virtuoso/" rel="nofollow noreferrer">https://pythonhosted.org/virtuoso/</a> with RDFlib but I keep getting the following import error</p> <pre><code>~\miniconda3\envs\dlvr\lib\site-packages\virtuoso\__init__.py in &lt;module&gt; 2 from pkg_resources import D...
<p>A quick Google search suggests <a href="https://www.roseindia.net/answers/viewqa/pythonquestions/37045-ModuleNotFoundError-No-module-named-alchemy.html" rel="nofollow noreferrer">you need to install the alchemy library for Python</a>.</p>
python|sparql|virtuoso|rdflib
1
3,161
7,339,339
reading, grouping, finding average
<p>I am new dummy to python...please help me in the following problem</p> <p>I have a data in *.txt format as 4 colums <code>name|items| a1| a2|</code>, here I am interested only in 3rd and 4th column. Items column goes like a set <code>[1,1]</code>, <code>[12,12,2]</code> etc., I need to open the text file, read the ...
<p>Here are some sections from the Python tutorial you may find helpful:</p> <ul> <li><p><a href="http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files" rel="nofollow">Reading and writing files</a></p></li> <li><p><a href="http://docs.python.org/tutorial/introduction.html#using-python-as-a-calcula...
python
1
3,162
72,514,229
Basic python defining function
<p>I'm having difficulty applying my knowledge of defining functions with def to my own function.</p> <p>I want to create a function where I can filter my data frame based on my 1. columns I'd like to drop + their axis 2. using .dropna</p> <p>I've used it on one of my data frames like this :</p> <p><code>total_adj_gros...
<p>Based on what you want to achieve, you don't need to pass any axis parameter. Also, you want to pass a list of columns as a parameter to drop the different columns (axis=1 for <code>drop()</code> and axis=0 for <code>dropna()</code>, which is the default parameter value). And finally, <code>dropna()</code> is not in...
python|user-defined-functions
0
3,163
72,714,613
Write values in a list of dictionaries
<p>I am trying to loop over a list of dictionaries and write values to this specific dictionary:</p> <pre><code>from model.statistic_model import Sher, Op, Npp TODAY = &quot;today&quot; OVERALL = &quot;overall&quot; SHER = &quot;sherlock&quot; OP = &quot;oprisk&quot; NPP = &quot;npp&quot; popular_search_terms = {SHER...
<p>You don't have to do it via the list. Python only saves a reference to the dictionary in the list. You can directly modify your dictionary with the <code>update</code> function.</p> <p>Let's say</p> <pre><code>popular_search_terms = {SHER:{OVERALL:{&quot;Test_SHER_overall&quot;:20}}} print(engines_container_over...
python
2
3,164
72,682,731
how to set DTL(Django Tamplate language) for loop and value through javascript
<p>I want to set django for loop to set value through javascript like this. is this correct way? or Is there any other way?</p> <pre><code> var table = $('.checkbox-datatable').DataTable({ 'scrollCollapse': true, 'autoWidth': false, 'responsive': true, &quot;lengthMenu&quot;: [[10, 25...
<p>urls.py:</p> <pre><code>urlpatterns = [ path('get_department_data/', views.get_department_data, name = &quot;get_department_data&quot;) # ... ] </code></pre> <p>views:</p> <pre><code>def get_department_data(request): if request.is_ajax and request.method == &quot;GET&quot;: q = YourModel.object...
javascript|python|django
1
3,165
39,805,113
How to output chinese characters in Python?
<p>The column <code>['douban_info']</code> in my dataset is info about movies in Chinese which stored in JSON, so when I do <code>df['douban_info'][0]</code>, it returns:</p> <p><a href="https://i.stack.imgur.com/6WCkU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6WCkU.png" alt="enter image descri...
<p>This is how Python 2 works. It by default displays the <code>repr()</code> when generating display strings for lists and strings. You have to <code>print</code> strings to see the Unicode characters:</p> <pre><code>&gt;&gt;&gt; D = {u'aka': [u'2019\u730e\u8840\u90fd\u5e02(\u6e2f)', u'\u9ece\u660e\u65f6\u5206']} &...
python|unicode|jupyter-notebook
2
3,166
31,822,350
Skip blank columns in csv.DictReader
<p>A sample of my input looks like this , Too give a brief understanding. This is a matrix of User ratings where the columns are product numbers.</p> <pre><code>User 95 94 97 101 99 87 98 86 103 105 106 100 92 89 91 96 27669 15 19 2 1 27670 ...
<p>You could use <code>defaultdict</code> and do it all in one step.</p> <pre><code>#!/usr/bin/python from csv import DictReader from collections import defaultdict users = defaultdict(dict) for row in DictReader(open('./file.csv', 'rb')): key = row.pop('User') tmp_dict = {int(k):int(v) for k,v in row.iteri...
python
3
3,167
31,941,938
Scraping and string-formatting issue : one time scrape with '' another time with ""
<p>This code : </p> <pre><code> url="http://www.royalcanin.fr/nos-aliments/gammes-pour-chiens/tous-les-aliments-pour-chiens/les-aliments-chez-les-veterinaires/chiens-en-bonne-sante/small/chien-sterilise/neutered-adult-small-dog"## read URL from an array coming from an Url-CSV #print(url) page_0=urllib.request.urlo...
<p>You are not missing anything , Python printed the last with double quotes because the body of that string already had single quote so instead of printing with single quotes and showing the inner single quote escaped , Python printed that string using double quotes .</p> <p>Irrespective of that all the elements of t...
python|format|beautifulsoup
2
3,168
31,731,483
enter a command using python when ready while reading serial from arduino
<p>I was trying to send a command to arduino using python program. but I also want to program to read the serial output coming from the arduino. This is my python program:</p> <pre><code>import wx, wx.html import sys import time import serial import smtplib import msvcrt TO = '*******@yahoo.com' GMAIL_USER = 's****l@...
<p>I haven't tried to run your example, but serial.readline does block if no timeout is specified.</p> <p>The docs are here: <a href="http://pyserial.sourceforge.net/shortintro.html#readline" rel="nofollow">http://pyserial.sourceforge.net/shortintro.html#readline</a></p>
python
0
3,169
38,641,954
what is 'SingleBlockManager' in pandas?
<p>I get an error message when I am using some library</p> <pre><code>AttributeError: 'SingleBlockManager' object has no attribute 'to_dense' </code></pre> <p>to_dense is a method for dataframe, therefore I assume SingleBlockManager should be a dataframe in my case. Does anyone know what SingleBlockManager is in Pand...
<p><code>SingleBlockManager</code> is an internal data structure which (essentially) holds the pieces of a <code>Series</code> - the index and values. You'd need to post some more context to see what's actually triggering the error.</p> <pre><code>In [1]: s = pd.Series([1,2,3]) In [2]: s._data Out[2]: SingleBlockMan...
python|pandas
2
3,170
40,496,176
Average of Groupby into a dataframe timedelta64[ns]
<p>df1</p> <pre><code>|Project |Days |A |20 days |B |10 days |A |10 days |C |5 days |C |7 days |B |8 days </code></pre> <p>R = df1['Days'].groupby(df1['Project'])</p> <p>R</p> <pre><code>|20 days |10 days |Name: Days, dtype: timedelta64[ns],('A', 30 15 days) |10 days |8 days |N...
<pre><code>import pandas as pd df1 = pd.DataFrame( {'Days': ['20 days', '10 days', '10 days', '5 days', '7 days', '8 days'], 'Project': ['A', 'B', 'A', 'C', 'C', 'B']}) df2 = pd.DataFrame( {'Date': ['1/10/16', '1/8/16', '1/2/16', '1/9/16'], 'Project': ['A', 'A', 'C', 'B']}) df1['Days'] = pd.to_time...
python|dataframe
0
3,171
40,676,324
ElasticSearch updates are not immediate, how do you wait for ElasticSearch to finish updating it's index?
<p>I'm attempting to improve performance on a suite that tests against ElasticSearch. </p> <p>The tests take a long time because Elasticsearch does not update it's indexes immediately after updating. For instance, the following code runs without raising an assertion error.</p> <pre><code>from elasticsearch import Ela...
<p>As of version 5.0.0, elasticsearch has an option:</p> <pre><code> ?refresh=wait_for </code></pre> <p>on the Index, Update, Delete, and Bulk api's. This way, the request won't receive a response until the result is visible in ElasticSearch. (Yay!)</p> <p>See <a href="https://www.elastic.co/guide/en/elasticsearch/r...
python|elasticsearch|synchronization|wait|polling
47
3,172
68,252,175
Mongodb pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s,
<p>I am trying to locally connect to my db. I've established a connection to the database on MongoDB Compass, but when I run my simple code, I get this error:</p> <blockquote> <p>pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: &lt;Topology...
<p>This problem was also happening in my stack, I had my connection string in an env file to connect to mongo atlas.</p> <pre><code>MONGO_URI=mongodb://&lt;username&gt;:&lt;password&gt;@cluster-details </code></pre> <p>But the right way to do this is</p> <pre><code>MONGO_URI=&quot;mongodb://&lt;username&gt;:&lt;passwor...
python|mongodb|localhost|pymongo
2
3,173
2,163,765
How can I run a loop against 2 random elements from a list at a time?
<p>Let's say I have a list in python with several strings in it. I do not know the size. How can I run a loop to do an operation on 2 random elements of this string? </p> <p>What if I wanted to favour a certain subset of the strings in this randomization, to be selected more often, but still make it possible for th...
<p>you need to look into <a href="http://docs.python.org/library/random.html" rel="nofollow noreferrer"><code>random</code></a> module. It has for example a <code>random.choice</code> function that lets you select a random element from a sequence or a <a href="http://docs.python.org/library/random.html#random.sample" r...
python|probability
4
3,174
44,251,993
gce startup startup-script not firing
<p>I have the following startup script variable defined in my python script:</p> <pre><code>default_startup_script = """ #! /bin/bash cd ~/git/gcloud; git config --global user.email "my.email@gmail.com"; git config --global user.name "my.name"; git stash; git pull https://user:pw@bitbucket.org/url/my_repo.git; """ </c...
<p>This works. My issue was related to user accounts. I was not logging in as the default user (<strong>Eg</strong>: <code>username@instance-id</code>).</p> <p>If you are reading this question just be sure of which username you are intending to run this for and manage accordingly.</p>
python|google-compute-engine
0
3,175
32,792,411
Get ALL results of a word mapping with a dictionary
<p>I got a word like this: <code>kfc</code></p> <p>Then a dictionary: <code>{'k':'1', 'c':'3'}</code></p> <p>How can I get a list like that?</p> <p><code>kfc, 1fc, kf3, 1f3</code></p> <p>It means there always will be <code>2^n</code> possibilities, with <code>n</code> is the number of dictionary's keys in that word...
<p>You can use <code>itertools.product</code>. For example, let's define the preliminaries:</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; s = 'kfc' &gt;&gt;&gt; d = {'k':'1', 'c':'3'} </code></pre> <p>Now, let's compute the result:</p> <pre><code>&gt;&gt;&gt; [ ''.join(x) for x in itertools.product( *[(...
python|dictionary|mapping
2
3,176
12,626,045
pytz and astimezone() cannot be applied to a naive datetime
<p>I have a date and I need to make it time zone aware.</p> <pre><code>local_tz = timezone('Asia/Tokyo') start_date = '2012-09-27' start_date = datetime.strptime(start_date, "%Y-%m-%d") start_date = start_date.astimezone(local_tz) now_utc = datetime.now(timezone('UTC')) local_now = now_utc.astimezone(local_tz) </...
<p>For <code>pytz</code> timezones, use their <code>.localize()</code> method to turn a naive <code>datetime</code> object into one with a timezone:</p> <pre><code>start_date = local_tz.localize(start_date) </code></pre> <p>For timezones without a DST transition, the <a href="http://docs.python.org/library/datetime.h...
python|datetime|timezone|pytz
60
3,177
7,873,828
How to convert date to timestamp using Python?
<p>I need to convert this result to timestamp:</p> <pre><code>&gt;&gt;&gt; print (datetime.date(2010, 1, 12) + datetime.timedelta(days = 3)) 2010-01-15 </code></pre> <p>I need to compare the value with this timestamp:</p> <pre><code>&gt;&gt;&gt; datetime.datetime.now() 2011-10-24 10:43:43.371294 </code></pre> <p>Ho...
<blockquote> <p>I need to convert this result to timestamp</p> </blockquote> <pre><code>import time mydate = datetime.date(2010, 1, 12) + datetime.timedelta(days = 3) time.mktime(mydate.timetuple()) </code></pre> <blockquote> <p>I need to compare the value with this timestamp:</p> </blockquote> <pre><code>a = ...
python|datetime-conversion
8
3,178
546,337
How Do I Perform Introspection on an Object in Python 2.x?
<p>I'm using Python 2.x and I have an object I'm summoning from the aether; the documentation on it is not particularly clear. I would like to be able to get a list of properties for that object and the type of each property. </p> <p>Similarly, I'd like to get a list of methods for that object, as well, plus any oth...
<p>Well ... Your first stop will be a simple dir(object). This will show you all the object's members, both fields and methods. Try it in an interactive Python shell, and play around a little.</p> <p>For instance:</p> <pre><code>&gt; class Foo: def __init__(self): self.a = "bar" self.b = 4711 &gt; a=Foo()...
python|introspection|python-datamodel
25
3,179
41,755,805
Shell/Python program: How to convert my log file into an vim quick fix format?
<p>For example, I've got a big log file like this:</p> <pre><code>[2016-02-10 13:17:56.885597] [WARNING] [53171] [src/root/mylinux/test01.cpp:300] </code></pre> <p>As you could see, this format contain several parts:</p> <pre><code>1. The time stamp, day+hour+minute+second+microsecond 2. Some spaces and the [WA...
<p>You can set Vim's <code>errorformat</code> option like this:</p> <pre><code>set errorformat+=\[%.%#\]\ \ \ \ \[%m\]\ \ \ \[%.%#\]\ \[%f:%l\] </code></pre> <p>which should give you the result below with the sample you gave:</p> <p><a href="https://i.stack.imgur.com/B3qkJ.png" rel="nofollow noreferrer"><img src="ht...
python|shell|gcc|vim|format
3
3,180
57,468,245
Webscrape images and their alt text in Python when you know part of a URL
<p>I want to webscrape a site, and save some, but not all images to my computer. I want to save about 5,600 images, so doing it manually would be difficult. All of the images urls start with </p> <pre><code>https://assets.pokemon.com/assets/cms2/img/cards/ </code></pre> <p>and then some other stuff that is specific t...
<p>Here's what I ended up doing:</p> <pre><code>import requests import urllib.request contents = requests.get(url) # Get request to site data = contents.text # Get HTMl file as text x = data.split("\"") # Splits it into an array using double quotes as separators (Because all of the image urls were in quotes) for a...
python|python-3.x|web-scraping
1
3,181
70,873,223
If I pull data from an API and save it in a variable, does it hit the API every time I call that variable?
<p>I'm grabbing a list from a website using their API and saving it as variable &quot;playlistNames&quot;. In a later function when I call &quot;playlistNames&quot; to manipulate the data, is it making another API call? or is the data just stored locally in the &quot;playlistNames&quot; variable?</p> <p>Sorry for such ...
<p>If you saved the API response to a variable, it won't call the API every time you access that variable.</p> <pre><code>r = requests.get(&quot;https://google.com&quot;) print(r.text) # doesn't call again... print(r.status_code) # doesn't call again... </code></pre>
python
2
3,182
11,538,170
Creating and accessing list of lists in python
<p>I am bit new to python. I started today. My code looks like this as follows</p> <pre><code>testcases=[ (([0.5,0.4,0.3],'HHTH'),[0.4166666666666667, 0.432, 0.42183098591549295, 0.43639398998330553]), (([0.14,0.32,0.42,0.81,0.21],'HHHTTTHHH'),[0.5255789473684211, 0.6512136991788505, 0.7295055220497553, 0.618713945348...
<p>Seems like you need a nested loop for that. e.g:</p> <pre><code>for inputs,output in testcases: for output in outputs: print output </code></pre>
python|list
0
3,183
33,915,152
Python: weird set comprehension: partial apply? implicit carrying?
<p>Consider the line from concurrent.futures example ( <a href="https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor-example" rel="nofollow">https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor-example</a> ):</p> <pre><code>future_to_url = {executor.submit(load_url, url,...
<p><code>load_url</code> is a method defined just above (<code>load_url(url, timeout)</code>).</p> <p>I guess <code>executor.submit(load_url,url,60)</code> calls at some point <code>load_url(url,60)</code>. So 60 is the timeout (probably because 60s=1mn). </p> <p>The dictionary comprehension applies <code>executor.su...
python|list-comprehension
1
3,184
33,543,968
Is it possible to get a python IDE working inside a PYQT4 widget?
<p>I'm doing some work that require a python IDE inside a PYQT4 window, I've searched around and the general idea for this is that it is possible but non of them say how. If someone can post some code that gets an IDE inside of the window i can adapt it from there.</p> <p>thanks</p> <p>Python 3.5, PYQT4, if any more ...
<p>You could use the exec-command</p> <p>get the Command by typing it into an editLine</p> <pre><code>z = self.editFunktion.text() #put the Funktion in z z = str(z) #converted it into str() (sometimes needed) exec z #exec takes the String and executes it </code></pre> <p>If...
python|ide|pyqt4
0
3,185
33,562,605
Django rest framework/simplejson error __init__() got an unexpected keyword argument
<p>I've found this issue with django-rest-framework <code>TypeError at /rest/events/ __init__() got an unexpected keyword argument 'iterable_as_array'</code> </p> <p>error tracelog:</p> <pre><code>Environment: Request Method: GET Request URL: http://www.kenyabuzz.com/rest/events/ Django Version: 1.5.5 Python Versi...
<p>Simplejson 3.3.1 was released before the fix was merged. You need to either wait or use the current master branch for simplejson.</p>
python|django|django-rest-framework|simplejson
1
3,186
46,757,362
Append new value to existing value of column in MySQL
<p>I'm new to Python and MySQL. I have a database named examples in my localhost which has 3 columns. </p> <pre><code>mysql&gt; select * from words; +----+--------+------------------------------------+ | id | userid | inputs | +----+--------+------------------------------------+ | 1 | anee...
<p>You can write and update statement and keep appending it with existing value.</p> <p>Assuming <code>v_input</code> is what you get from user input and for <code>v_userid</code></p> <pre><code> UPDATE words SET inputs = CONCAT(inputs, v_input) WHERE userid =v_userid </code></pre>
python|mysql|sql-update
0
3,187
37,639,644
listdir a directory and find if a file name that endswith ".mp4""
<p>Original question:</p> <pre><code>a = [1, 2, 3, 4, 5, 6, 4] print [True for i in a if i == 4] </code></pre> <p>result:</p> <pre><code>[True, True] </code></pre> <p>How do I code to break at first number 4?</p> <p>Following comments, edited to:</p> <p>I exactly want to listdir a directory with so many files. A...
<p>Your comment: "<em>I exactly want to listdir a directory with so many files. And find if a file endswith ".mp4"</em>"</p> <p>That is quite a bit different to the original question you posted. There are several ways to do this:</p> <pre><code>import glob import os.path dir = '.' files = glob.glob(os.path.join(dir...
python
12
3,188
61,257,151
Making an array from another defined array with no duplicates using list comprehension
<p>I had tried to make a list free of duplicates from another defined list using list comprehension as follows,</p> <pre><code>num = [1, 2, 2, 2, 3, 3, 4, 4, 4, 5] my_list = [] my_list = [x for x in num if x not in my_list] </code></pre> <p>Upon calling <code>my_list</code>, I get back the same array</p> <pre><code>...
<p><code>my_list</code> isn't updated until after the comprehension is complete. During the comprehension <code>my_list</code> is an empty list.</p> <p>If order matters the approach you want to take is:</p> <pre><code>num = [1, 2, 2, 2, 3, 3, 4, 4, 4, 5] my_list = [] check_set = set() for x in num: if x not in ch...
python|python-3.x|list|list-comprehension
3
3,189
27,763,628
is raven.contrib.django.handlers.SentryHandler async?
<p>it say <a href="http://raven.readthedocs.org/en/latest/transports/index.html#threaded-default" rel="nofollow">here</a> that "<em>threaded+http</em>" is the default transport for <strong>raven</strong> is it also true for <strong>raven.contrib.django.handlers.SentryHandler</strong>?</p>
<p>it depends on your Django settings, look at the settings variable <code>RAVEN_CONFIG</code>:</p> <pre><code>RAVEN_CONFIG = { 'dsn': "&lt;transport&gt;://&lt;sentry_url&gt;" } </code></pre> <p>if your <strong></strong> is "<strong>threaded+https</strong>" or "<strong>threaded+http</strong>" then the answer is ye...
python|logging|asynchronous|raven
2
3,190
27,564,320
Using Regular Expressions on my Raspberry Pi
<p>Is there an editor that I could install on the Raspbian OS to practice Regex with? If not, what about through Python? If so, is there a good python IDE out there for Raspbian that supports Regexs?</p>
<p>Python itself supports regexes (via a built-in module). If you're just interested in playing around with them, <code>import re</code> in an interactive shell, and you have access to Python's regular expression engine.</p>
python|regex|raspberry-pi|raspbian
2
3,191
65,797,412
How to know when an overfitting is taking place?
<p>I have a training data with 3961 different rows and 32 columns I want to fit to a Random Forest and a Gradient Boosting model. While training, I need to fine-tune the hyper-parameters of the models to get the best AUC possible. To do so, I minimize the quantity 1-AUC(Y_real,Y_pred) using the Basin-Hopping algorithm...
<p>To know if your are overfitting you have to compute:</p> <ul> <li>Training set accuracy (or 1-AUC in your case)</li> <li>Test set accuracy (or 1-AUC in your case)<em>(You can use validation data set if you have it)</em></li> </ul> <p>Once you have calculated this scores, compare it. <strong>If training set score is ...
python|scikit-learn|overfitting-underfitting
0
3,192
65,859,090
python - doing a left merge and getting wrong output
<p>df1:</p> <pre><code>id score 1000 174 1001 181 1002 162 1003 182 1005 97 ... ... 3313 95 3316 91 3322 151 *1928 rows × 2 columns </code></pre> <p>df2:</p> <pre><code>date id 01/03/2019 1002 01/03/2019 1004 01/03/2019 1013 01/03/2019 1014 01/03/2019 1015 ... ...
<p>Based on the comments, here is the answer. If ID is unique in df1, but not in df2, pandas has no way of knowing the “correct” date from df2 and hence all dates will be merged to the same score for a given ID.</p> <p>I suspect you would need a third dataframe where you have information that matches the (presumably) b...
python|pandas|merge
1
3,193
37,126,553
stackedWidget using pyqt
<p>Im new at Python, QT4 and pyqt and I can't get the widgets to change using setCurrentIndex. I'm sure I am not using it correctly, but here's my initial code. First is the pyqt code:</p> <pre><code># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'mainwindow.ui' # # Created: Thu May 5 ...
<p>The error message means exactly what it says: <code>MyDialog</code> doesn't create a member variable named <code>self.stackedWidget</code>, but it tries to access such a variable in <code>Change</code>, so an AttributeError is raised when you click the button. The variable you want is a member of <code>self.ui</cod...
python|pyqt|qt4
0
3,194
36,785,554
Python - extract and modify a file path in all files in a directory in linux
<p>I have files .sh files and .json files in which there are file paths given to point to a specific directory, but I should keep on changing the file path, depending on where my python scipt is run.</p> <p>eg:content of one of my .sh file is "cd /home/aswany/BotStudioInstallation/databricks/platform/databricksastro...
<p>Not sure I 100% understood your issue, but maybe I can help nonetheless.</p> <p>As pointed out by <a href="https://stackoverflow.com/users/4279/j-f-sebastian">J.F. Sebastian</a>, you can use relative paths and remove the base part of the path. Using <code>./databricks/platform/devsettings.json</code> might be enoug...
python|linux
1
3,195
48,824,283
python call vim open multiple files
<p>I'm trying to call vim from a python script to open multiple files.</p> <pre><code>files = [] for i in sys.argv[1:]: files.append(i) string = " ".join(str(x) for x in files) call(["vim", string]) </code></pre> <p>when I call <code>./open.py 11 42 39</code> it only open one file called "11 42 39".</p> <p>How ...
<p>You need to have the seperate files as seperate items in your list:</p> <pre><code>call(["vim"] + files) </code></pre> <p>That is because when you pass a list, then each element in the list after the first one is given to vim as a seperate argument. So you are just giving vim the argument <code>"11 42 39"</code>. ...
python|vim|call
3
3,196
48,681,536
Highlighting multiple cells in a row based on other values in the row in a Pandas DataFrame
<p>I am trying to highlight cells in my pandas dataframe based on two conditions:</p> <ul> <li><p>If A cell - B cell > 10 highlight B cell in green else if ((B cell - A cell)/B cell * 100) > 20 highlight B cell in red</p></li> <li><p>If A cell - C cell > 10 highlight C cell in green else if ((C cell - A cell)/C cell *...
<p>Try looking at : <a href="https://xlsxwriter.readthedocs.io/" rel="nofollow noreferrer">https://xlsxwriter.readthedocs.io/</a></p> <p>You'll basically end up with something like:</p> <pre><code> excel_file = StringIO.StringIO() writer = pd.ExcelWriter(excel_file, engine='xlsxwrit...
python|excel|pandas|dataframe|slice
1
3,197
20,333,910
How do I correctly update several levels of nested sizers when some inner content changes its size?
<p>I’m building a WX app in which the main window (“frame”) has two content areas: a main content area on the left and a sidebar on the right. The sidebar consists of a vertically-stacked collection of panels, and each of these panels consists of a title and a content area. The main window’s view hierarchy looks like ...
<p>You'll have to call Layout() on any widget or the sizer that the widget is in. This has actually been explained quite well by Robin Dunn (creator of wxPython) on the wxPython wiki here:</p> <ul> <li><a href="http://wiki.wxpython.org/WhenAndHowToCallLayout" rel="nofollow">http://wiki.wxpython.org/WhenAndHowToCallLay...
wxpython|wxwidgets
2
3,198
4,147,901
is there a more efficient way to write results from a query in python?
<p><a href="http://www.pha.com.au/kb/index.php/Python_-_MS_SQL_Server_Modules#Example_2" rel="nofollow">This</a> is effectively how i'm using _mssql.</p> <p>Everything works fine, even after i use <code>fetch_array()</code>.</p> <p>The problem is, when I iterate through <code>fetch_array()</code>, it takes over ten m...
<p>Could you show us some code of iterating through the results and creating an email? If I had to make a wild guess, I would say you are probably violating this idiom: "Build strings as a list and use ''.join at the end." If you keep adding to a string as you go you create a new (and progressively larger) string on ea...
python|sql-server-2005
1
3,199
69,368,822
Recover deleted file PyCharm
<p>I'm working on a password manager using python in the PyCharm IDE. I am working with a database to store the passwords, which makes a .db file in the project folder. Then i wanted to clear that file as i wanted a clear db to work with. So i deleted the .db file from my folder, thinking it would create a new file and...
<p>The error is being thrown by this:</p> <pre class="lang-py prettyprint-override"><code>cursor.execute('SELECT * FROM vault') if cursor.fetchall() != None: i = 0 while True: cursor.execute('SELECT * FROM vault') array = cursor.fetchall() Label(vault, text=(array[i][1]), font=(&quot;Hel...
python|database|pycharm
1