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
1,000
54,228,373
Why does my code take so long to write CSV file in Dask Python
<p>Below is my Python code:</p> <pre><code>import dask.dataframe as dd VALUE2015 = dd.read_csv('A/SKD - M2M by Salesman (value by uom) (NEWSALES)2015-2016.csv', usecols = VALUEFY, dtype = traintypes1) REPORT = VALUE2015.groupby(index).agg({'JAN':'sum', 'FEB':'sum', 'MAR':'sum', 'APR':'sum', 'MAY':'sum','JUN':'sum',...
<p>Looking through Dask documentation, it says there that, "generally speaking, Dask.dataframe groupby-aggregations are roughly same performance as Pandas groupby-aggregations." So unless you're using a Dask distributed client to manage workers, threads, etc., the benefit from using it over vanilla Pandas isn't always ...
python|pandas|dask|dask-distributed|dask-ml
1
1,001
22,700,455
Program format getting change in wing
<p>if see the picture on this link <a href="https://drive.google.com/file/d/0B_CP5fn_tuEDTDZoclM5M0V0cmc/edit?usp=sharing" rel="nofollow">https://drive.google.com/file/d/0B_CP5fn_tuEDTDZoclM5M0V0cmc/edit?usp=sharing</a></p> <p>this what my program looks when I write in sublime. But when I copy and paste the program in...
<p>By looking at the images it seem likely that the editor settings related to indenting are different in sublime and wing.</p> <p>Check if any of the editors are using tabs instead of spaces when indenting the code and if they are, change the editor to use 4 x whitespace instead of a tab.</p>
python|formatting|indentation
0
1,002
23,562,784
What is more efficient .objects.filter().exists() or get() wrapped on a try
<p>I'm writing tests for a django application and I want to check if an object has been saved to the database. Which is the most efficient/correct way to do it?</p> <pre><code>User.objects.filter(username=testusername).exists() </code></pre> <p>or</p> <pre><code>try: User.objects.get(username=testusername) excep...
<h2>Speed test: <code>exists()</code> vs. <code>get() + try/except</code></h2> <p>Test functions in <strong>test.py</strong>:</p> <pre><code>from testapp.models import User def exists(x): return User.objects.filter(pk=x).exists() def get(x): try: User.objects.get(pk=x) return True except U...
python|django|testing|django-models
29
1,003
31,888,866
I want to deploy using the entries that i have in my database
<p>So i used postgres in development for my django project and have important entries in there and i want to deploy to my app in heroku</p> <p>is there a simple way to do this? </p>
<p>Sure. You just need to export your local database and import it on the Heroku Postgres database. Heroku has a <a href="https://devcenter.heroku.com/articles/heroku-postgres-import-export#import" rel="nofollow">guide</a> to do just that.</p> <ol> <li>Create a dump from your local database. <code>PGPASSWORD=mypasswor...
python|django|postgresql|heroku
0
1,004
32,939,447
name " " is not defined
<pre><code>import math EMPTY = '-' def is_between(value, min_value, max_value): """ (number, number, number) -&gt; bool Precondition: min_value &lt;= max_value Return True if and only if value is between min_value and max_value, or equal to one or both of them. &gt;&gt;&gt; is_between(1.0, 0.0,...
<p>You have NO <code>cells</code> parameter in </p> <pre><code>def make_move( symbol,row_index,col_index,game_board): </code></pre> <p>Next time read the error message carefully so you know in which code line you have a problem. </p>
python|nameerror
1
1,005
37,786,536
How to define policies for Python application in Bluemix Autoscaling service?
<p>I noticed that the policy types depend on the target runtime. For example, for Java it is possible to define policies based on memory, throughput, response time... etc. The only possibility for Python is memory based policy. Is there any workaround for that? </p>
<p>Bluemix Auto scaling service for Liberty for Java™ applications, supports scaling rules for JVM Heap, Memory, and Throughput. Actually, Auto Scaling services on Bluemix works with IBM JVM. </p> <p>For other types of runtimes, including Python runtime, there is only <a href="https://console.ng.bluemix.net/docs/servi...
python|ibm-cloud|autoscaling
0
1,006
37,996,299
Save Game Progress for Multiple Sprites
<p>I'm working on a game in Pygame that includes a player class and an enemy class. Each class has multiple variables within it. I'm trying to figure out how I can save the data of these sprites by using Python's built-in <code>pickle</code> module. I thought of doing something similar to this:</p> <pre><code>data_fil...
<p><strong>Answer</strong></p> <p>Since pickle is object serialization, you should just be able to dump your whole object. The <code>b</code> in <code>wb</code> is for binary. This is because you don't have to know how an object is represented in binary, you can just dump it like so:</p> <pre><code>data_file = open_f...
python|save|pygame|pickle
1
1,007
51,420,774
how to omit tns from response and change tag name in spyne?
<p>how do omit tns from my response and also change the tag name.? my response is like this</p> <pre><code>&lt;soap11env:Envelope xmlns:soap11env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tns="spyne.example"&gt; &lt;soap11env:Body&gt; &lt;tns:FnSchedule_CityResponse&gt; &lt;tns:FnSchedule_CityResul...
<p>In order to change soap11env to soap just simply override the response using</p> <pre><code>application.interface.nsmap['soap'] = application.interface.nsmap['soap11env'] </code></pre> <p>The 'tns' or target namespaces must not be change but there may arrive a few cases, One might need to change a name in order to...
python|python-2.7|spyne
0
1,008
62,783,372
ERROR: Command errored out with exit status 1 while installing requirements.txt
<p>I have been trying to install packages from a requirements.txt file but I'm getting error. I made a virtual environment to install the packages but got his huge array. My machine is running on python 3.8</p> <p>Below is the error what I got in my terminal while trying to install the requirements.txt file in my virut...
<p>Try isolate which line of requirements.txt gives you an error, you can try comment out torch and see how installation goes without it.</p> <p>To replicate your error message try pip install torch, I think it would give you the error message you experienced.</p> <p>Two things after that:</p> <ul> <li>go to torch docu...
python|python-3.x|machine-learning|pip
0
1,009
62,700,468
How to check whether a graph is an undirected graph?
<p>Currently, I am creating a function to check whether a graph is un-directed. The way, my graphs are stored are in this way. This is a un-directed graph of 3 nodes, 1, 2, 3.</p> <pre><code>graph = {1: {2:{...}, 3:{...}}, 2: {1:{...}, 3:{...}}, 3: {1:{...}, 2:{...}}} </code></pre> <p>the {...} represents alternating l...
<p>First off, I think you're abusing terminology by calling a graph with edges in both directions &quot;undirected&quot;. In a real undirected graph, there is no notion of direction to an edge, which often means you don't need redundant direction information in the graph's representation in a computer program. What you...
python|python-3.x|dictionary|graph
1
1,010
53,542,497
How to Return a List of Values From Within a Dictionary?
<p>I need to return a list of values for a given id number using two previously created dictionaries, where the values I need are stored within the dictionaries.</p> <p>The two dictionaries I've created are as follows:</p> <pre><code>{100: ('Mulan', [300, 500], [200, 400]), 200: ('Ariel', [100, 500], [500]), 300: (...
<p>You'll need to use nested loops to go through both dictionaries starting with the first:</p> <pre><code>user_input = 500 for key, value in dictionary1.items(): if user_input == key: for key2, value2 in dictionary2.items(): for items in value[1]: if items == value2[0]: prin...
python|python-3.x|dictionary
0
1,011
54,937,021
Output of python code is one character per line
<p>I'm new to Python and having some trouble with an API scraping I'm attempting. What I want to do is pull a list of book titles using this code:</p> <pre><code>r = requests.get('https://api.dp.la/v2/items?q=magic+AND+wizard&amp;api_key=09a0efa145eaa3c80f6acf7c3b14b588') data = json.loads(r.text) for doc in data["d...
<p>The problem is that you have two types of title in the response, some are plain strings <code>"Germain the wizard"</code> and some others are arrays of string <code>['Joe Strong, the boy wizard : or, The mysteries of magic exposed /']</code>. It seems like in this particular case, all lists have length one, but I gu...
python|python-3.x|for-loop
0
1,012
33,065,510
Convert AngularJS website to Flask
<p>I created an Angular website with ui-router:</p> <pre><code>angular app structure |--index.html |--js |--app.js |--angular.js |-- ... |--stylesheets |--main.css |-- ... |--template |--navbar.html |--about.html |-- ... </code></pre> <p>Each js and css is linked like this:</p> <pre><code>&...
<p>You need to render your template. The best way to do that is </p> <pre><code>@app.route('/') def view(): return render_template('index.html') </code></pre>
python|angularjs|flask
2
1,013
33,407,050
MySQL query throwing 1064 error
<p>I have a huge data which is stored in mysql db. One of the columns in the database is a long string. One of the strings is "iEdge detected the 'warning' condition 'iedge it" which is stored in string_type. I have to query the database and find how many such strings are there.I am querying from my python program. Whe...
<p>Can you try this:</p> <pre><code>sql = "select count(*) from table1 as tmp where tmp.err_string=%s" cursor.execute(sql, [row[r]]) </code></pre> <p>Let the MySQL Python library worry about escaping special characters and how to quote your string.</p> <p>See <a href="https://stackoverflow.com/questions/15798969/pyt...
python|mysql|sql|flask
0
1,014
13,121,212
Python - regular expressions - find every word except in tags
<p>How to find all words except the ones in tags using RE module?</p> <p>I know how to find something, but how to do it opposite way? Like I write something to search for, but acutally I want to search for every word except everything inside tags and tags themselves?</p> <p>So far I managed this:</p> <pre><code>f = ...
<p>If you want to <a href="https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454">avoid</a> using a regular expression, <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow noreferrer">BeautifulSoup</a> makes it very easy to get just the text...
python|regex
2
1,015
21,701,338
Add build information in Jenkins using REST
<p>Does anyone know how to add build information to an existing Jenkins build? </p> <p>What I'm trying to do is replace the #1 build number with the actual full version number that the build represents. I can do this manually by going to http://MyJenkinsServer/job/[jobname]/[buildnumber]/configure</p> <p>I have tried...
<p>It's a bit confusing to reverse engineer this. You just need to submit the <em>json</em> parameter in your POST:</p> <pre><code>p = {'json': '{"displayName":"New Name", "description":"New Description"}'} requests.post('http://jenkins:8080/job/jobname/5/configSubmit', data=p, auth=(user, token)) </code></pre> <p>In...
python|post|jenkins
8
1,016
41,125,598
Suppress warnings for python-xarray
<p>I'm running the following code </p> <pre><code>positive_values = values.where(values &gt; 0) </code></pre> <p>In this example <code>values</code> may contain <code>nan</code> elements. I believe that for this reason, I'm getting the following runtime warning: </p> <pre><code>RuntimeWarning: invalid value enco...
<p>The <a href="https://docs.python.org/3.5/library/warnings.html" rel="nofollow noreferrer"><code>warnings</code></a> module provides the functionality you are looking for.</p> <p>To suppress all warnings do (see <a href="https://stackoverflow.com/a/41126444/1322401">John Coleman's answer</a> for why this is not good...
python|python-3.x|suppress-warnings|python-xarray
6
1,017
38,083,670
How to customize pybusyinfo window in (windows OS) to make it appear at top corner of window and the other formatting options?
<p>I am writing a python script to get the climate conditions in particular area every 30 minutes and give a popup notification.</p> <p>This code gives popup at the center of the screen which is annoying.I wish to have the popup similar to notify-send in linux[which appears at right corner] and the message is aligned ...
<pre><code>screen_size = wx.DisplaySize() d_size = d._infoFrame.GetSize() pos_x = screen_size[0] - d_size[0] # Right - popup.width (aligned to right side) pos_y = screen_size[1] - d_size[1] # Bottom - popup.height (aligned to bottom) d.SetPosition((pos_x,pos_t)) d.Update() # force redraw ... (otherwise your "work " wil...
python|python-2.7|wxpython|notify
0
1,018
38,328,588
Scrapy Logging Level Change
<p>I'm trying to start scrapy spider from my scripty as shown in <a href="http://doc.scrapy.org/en/latest/topics/practices.html#run-scrapy-from-a-script" rel="noreferrer">here</a></p> <pre><code>logging.basicConfig( filename='log.txt', format='%(levelname)s: %(message)s', level=logging.CRITICAL ) configure...
<p>For scrapy itself you should define logging settings in <code>settings.py</code> <a href="http://doc.scrapy.org/en/latest/topics/logging.html?highlight=logging#logging-settings" rel="noreferrer">as described in the docs</a></p> <p>so in <code>settings.py</code> you can set:</p> <pre><code>LOG_LEVEL = 'ERROR' # to...
python-3.x|logging|scrapy
20
1,019
30,926,043
Trouble outputing file size to a label from a listbox in Python 3
<p>I'm using <code>os.path.getsize()</code> to output the size of a file to a label. The file path is stored in a listbox. The function works, but it outputs the file size in bits, so I wrote the following to convert to more appropriate units, and it is now displaying only in TB. It's executing all of the <code>if</cod...
<p>There are couple problems in your code, </p> <ul> <li>You always re-assign <code>fileSizeStr</code>. You need to concatenate new values. </li> <li>You need to check if <code>fileSize</code> greater than or equal to 1024, not smaller. </li> <li>New <code>fileSize</code> should be remainder of the first calculatio...
python-3.x|operating-system
1
1,020
30,949,405
Is there danger in installing 2 versions of Anaconda for Python on one machine?
<p>Some background: I have an intel Mac osx (running Yosemite) and use PyCharm community edition as my main IDE. I usually code in Python 3.4 however, I'm taking some MIT OCW courses which all use Python 2. To make it easier on myself when using MIT's skeleton files I have downloaded Python 2.7 and switch the PyCharm i...
<p>There's no danger, but it's also not the recommended way of achieving this. Rather, you should use <code>conda</code>, the package manager that comes with Anaconda, to create an environment for the other version of Python. For instance, if you started with Anaconda3,</p> <pre><code>conda create -n python27 python=...
python|macos|python-2.7|python-3.x|anaconda
0
1,021
51,891,791
Regex python : find different forms of currency with amount
<p>I try to find the amounts in euros in receipts. I extract the values, but the currency can appear in different ways: "EUR", "E" or"€". I do not succeed in specifying these different forms within the regex. In addition, the "E" must not raise words that also begin with "E" such as "Eggs".</p> <p>Currently my regex ...
<p>There are a couple things going on here. First, you're not capturing what I think you want to capture (you said the values). You should have something like <code>(\d+(?:.|,)\d\d)</code> (the ?: inside the inner parentheses groups the . and , without making it another capturing group). Second, your [(e|eur|euros|€)...
python|regex|currency
0
1,022
51,580,689
Python program to convert words to numbers in a text file containing English words also
<p>I would like to use word2number from <a href="https://pypi.org/project/word2number/" rel="nofollow noreferrer">https://pypi.org/project/word2number/</a> to convert words to numbers in a text file to another file as output. </p> <p>A similar program is available to convert numbers to words. So how do I workaround th...
<p>There's definitely a more pythonic way to do this but here you go, you will need to replace word2number with the function call from the library you want to use where the parameter is a string. Also this will skip newline characters and make one big line.</p> <pre><code>lines = f_input.readlines() nums = list() for...
python|numbers|words
0
1,023
62,220,371
Find the number of clusters in a list of integers
<p>Let's consider the distance <code>d(a, b) = number of digits which are pairwise different in a and b</code>, e.g.:</p> <pre><code>d(1003000000, 1000090000) = 2 # the 4th and 6th digits don't match </code></pre> <p>(we only work with 10-digit numbers) and this list:</p> <pre><code>L = [2678888873, 2678878...
<p>Let's see what we know from a the distance metric. Given a number <code>P</code> (not necessarily in <code>L</code>), if two members of <code>L</code> are within distance 1 of <code>P</code>, they each share 9 digits with <code>P</code>, but not necessarily the same ones, so they are only guaranteed to share 8 digit...
python|numpy|cluster-analysis|nearest-neighbor|levenshtein-distance
1
1,024
36,479,773
Multivariate Optimization - scipy.optimize input parsing error
<p><a href="https://i.stack.imgur.com/pLpi5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pLpi5.jpg" alt="rgb image"></a></p> <p>I have the above rgb image saved as <code>tux.jpg</code>. Now I want to get the closest approximation to this image that is an outer product of two vectors I.e of the fo...
<p>1) <strong>The rendering problem of the first image seems to be an issue in the conversion from numpy array to image. I get the right rendering by running:</strong> </p> <pre><code>imout = Image.fromarray(mout/np.max(mout)*255) </code></pre> <p>(i.e. normalize the image to a maximum value of 255 and let it determi...
python|image|numpy|math|least-squares
0
1,025
36,663,287
Erratic (seemingly random) behavior of seek() and split() in python
<p>Consider the following code:</p> <pre><code>import sys with open(sys.argv[1]) as data_file: data_file.readline() #skipping lines of texts data_file.readline() data_file.readline() #skipping lines of texts data_file.readline() data_file.readline() #skipping lines of texts data_file.readline() #skip...
<p><code>file.readline()</code> uses a <em>read-ahead buffer</em> to find newlines, so it can return you a neat line that ends in <code>\n</code>. The alternative is to read byte by byte until a newline is found, which would be extremely inefficient.</p> <p>As such, your first <code>file.readline()</code> reads in a c...
python
2
1,026
36,390,596
How to access and edit variables inside functions in python
<p>Im new(-ish) to python and I made a game today which after I finished I realised I'd made a big mistake : </p> <p>inside the functions I had to access and edit variables which where also accessed and changed in <em>other</em> functions and maybe in the future outside the functions. And I don't know how to do that.<...
<p>Consider:</p> <pre><code>x=0 z=22 def func(x,y): y=22 z+=1 print x,y,z func('x','y') </code></pre> <p>When you call <code>func</code> you will get <code>UnboundLocalError: local variable 'z' referenced before assignment</code></p> <p>To fix the error in our function, do:</p> <pre><code>x=0 z=22 ...
python|function|variables
0
1,027
13,382,139
python scipy unit test
<p>I have installed a number of python modules into a common Linux directory that a number of people will be using via an NFS mount (yes I understand that there is a performance hit with this esp with python) I have been able to run the scipy.test('full') as the user that owns the NFS mount as well as root.</p> <p>Is...
<p>nvm ... I put the following into the test script:</p> <pre><code>import scipy import os import shutil directory = os.getcwd() userHomeDirectory = ( "/home/" + os.getlogin()) userHomeScipyTests = ( userHomeDirectory + "/scipytests" ) # print ("your current directory location is: " + directory) print...
python|scipy
0
1,028
17,125,978
Memory leak by ctypes pointers used within python class
<p>I try to wrap some C code via ctypes. Altough, my code (attached below) is functional, <a href="https://pypi.python.org/pypi/memory_profiler" rel="noreferrer">memory_profiler</a> suggests it is suffering a memory leak somewhere. The basic C struct, I'm trying to wrap is defined in 'image.h'. It defines an image obje...
<p>It may not be the only issue, but for sure the caching of each <code>_Argtype</code>: <code>LP__Argtype</code> pair in the dict <code>_ctypes._pointer_type_cache</code> is not insignificant. Memory usage should go down if you <code>clear</code> the cache. </p> <p>The pointer and function type caches can be cleared ...
python|pointers|memory-leaks|ctypes
3
1,029
43,916,453
Select related of selected related
<p>Say I have a relationship (by foreign key) like this: <em>Model 1 → Model 2 → Model 3</em>. Can I follow foreign key relationship with <code>select_related()</code> more than one level deep? I.e. not only from <em>Model 1</em> to <em>Model 2</em> but also from <em>Model 2 to Model 3</em>?</p>
<p>Yes, you can, by using the normal double-underscore syntax - as <a href="https://docs.djangoproject.com/en/1.11/ref/models/querysets/#select-related" rel="nofollow noreferrer">explicitly described</a> in the documentation:</p> <pre><code>Model1.objects.select_related('model2__model3') </code></pre>
python|django|orm
2
1,030
43,742,931
how repeat one plot in multiples subplots matplotlib
<p>Please I need repeat a climatological plot (fill_between(x,y1,y2) in multiples subplots, exist any tips to resolve that? Here is part of my code. </p> <pre><code>from matplotlib import pyplot as plt plt.figure() fig, axs = plt.subplots(nrows=2, ncols=2, sharex=True) ax = axs[0,0] ax.fill_between(month, y2,y3 , alph...
<p>Depending on how the data is organized it may be quite easy to loop over the plots to fill them. </p> <pre><code>import numpy as np from matplotlib import pyplot as plt month=np.linspace(1,8) y2 = -0.15*(month-4)**2+2.3 y3 = 0.1*(month-3.7)**2 x = np.logspace(1,5,base=1.5, num=16).reshape(4,4).T y = np.sinc(x-3)**...
python|matplotlib
0
1,031
43,850,001
Python Django project - move div class footer into body
<p>I'm creating a blog with python and django. Most of it has been fine up until i've just tried to create the footer. The footer display's fine on the home page but when you click into the blog post the footer gets constrained by the content container and row div class. When you look at this in firefox dev inspector a...
<p>This is the blog post detail page</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>{% extends 'blog/base.html' %} {% block content %} {% if post.published_dat...
javascript|jquery|python|html|css
0
1,032
43,549,269
Seaborn ImportError: DLL load failed: The specified module could not be found
<p>I am getting the "ImportError: DLL load failed: The specified module could not be found." when importing the module <strong>seaborn</strong>.</p> <p>I tried uninstalling both seaborn and matplotlib, then reinstalling by using </p> <pre><code>pip install seaborn </code></pre> <p>but no luck. I still get the same ...
<p>I was having this issue until I uninstalled and reinstalled scipy with the pip command. Just got to your command line and type <code>pip uninstall scipy</code> and <code>pip install scipy</code>.</p> <p>Hopefully that works for you as well. I also uninstalled/installed seaborn before this although I'm not sure if t...
python|matplotlib|error-handling|seaborn
4
1,033
54,593,163
Find and remove duplicate files using Python
<p>I have several folders which contain duplicate files that have slightly different names (e.g. file_abc.jpg, file_abc(1).jpg), or a suffix with "(1) on the end. I am trying to develop a relative simple method to search through a folder, identify duplicates, and then delete them. The criteria for a duplicate is "(1)" ...
<p>Your code is just a little more complex than necessary, and you didn't apply a proper way to create a file path out of a path and a file name. And I think you should not remove files which have no original (i. e. which aren't duplicates though their name looks like it).</p> <p>Try this:</p> <pre><code>for file_na...
python|python-2.7|file-management|data-management
3
1,034
54,658,862
Is there a way to convert named function arguments to dict
<p>I am trying to find out if there is a way to convert named arguments to <code>dict</code>. </p> <p>I understand using <code>**kwargs</code> in place of individual named arguments would be pretty straight forward.</p> <pre><code>def func(arg1=None, arg2=None, arg3=None): # How can I convert these arguments to {...
<p>You can use <code>locals()</code> to get the local arguments:</p> <pre><code>def func(arg1=None, arg2=None, arg3=None): print(locals()) func() # {'arg3': None, 'arg2': None, 'arg1': None} </code></pre>
python|function|dictionary|parameter-passing|named
5
1,035
52,574,943
How to add values into an empty list from a for loop in python?
<p>The given python code is supposed to accept a number and make a list containing all odd numbers between 0 and that number</p> <pre><code>n = int(input('Enter number : ')) i = 0 series = [] while (i &lt;= n): if (i % 2 != 0): series += [i] print('The list of odd numbers :\n') for num in series: prin...
<p>So, when dealing with lists or arrays, it's very important to understand the difference between referring to an element of the array and the array itself.</p> <p>In your current code, series refers to the list. When you attempt to perform series + [i], you are trying to add [i] to the reference to the list. Now, th...
python|list|loops
2
1,036
47,729,323
Elastic Beanstalk with Django: is there a way to run manage.py shell and have access to environment variables?
<p>Similar question was asked <a href="https://stackoverflow.com/questions/19997343/run-manage-py-from-aws-eb-linux-instance">here</a>, however the solution does not give the shell access to the same environment as the deployment. If I inspect <code>os.environ</code> from within the shell, none of the environment varia...
<p>One of the cases you have to run something once is db schema migrations. Usually you store information about that in the db... So you can use db to sync / ensure that something was triggered only once.</p> <p>Personally I have nothing against using <code>eb ssh</code>, I see problems with it however. If you want to ...
python|django|amazon-web-services|environment-variables|amazon-elastic-beanstalk
0
1,037
47,945,097
Apply multiple if/else statement to groupby object in pandas
<p>I have a very large DataFrame according to below:</p> <pre> id amt date 1 0 2010-02-01 1 0 2012-05-12 1 0 2016-08-09 1 20 1970-01-01 2 0 2016-03-21 2 0 2017-11-10 2 0 2012-09-01 2 0 2016-04-15 </pre> <p>What I want is to reduce it to one row per id according to following logic:</p> ...
<p>I wrote a custom function which you can apply on individual groups</p> <pre><code>def custom_fx(df): if df.amt.sum() == 0: max_date = df.date.max() return df.loc[df.date==max_date,:] elif df.amt.sum() != 0 : return df[df.date.isin(["1970-01-01"])] for groups,data in df.groupby("id"): print(custom_...
python|pandas|group-by
1
1,038
34,403,152
Python csv.reader to separate items by comma but ignore those within pairs of double-quotes
<p>I'm trying to use csv.reader to create a list of items from a string, but I'm having trouble. For instance, I have the following string:</p> <pre><code>bibinfo = "wooldridge1999asymptotic, author = \"Wooldridge, Jeffrey M.\", title = \"Asymptotic Properties of Weighted M-Estimators for Variable Probability Samples\...
<p>It works if the <code>"</code> is at beginning of the item:</p> <pre><code>"author = Wooldridge, Jeffrey M." </code></pre> <p>With the changed text:</p> <pre><code>&gt;&gt;&gt; s = """wooldridge1999asymptotic, "author = Wooldridge, Jeffrey M.", title = "Asymptotic Properties of Weighted M-Estimators for Variable ...
csv|python-3.4
0
1,039
66,278,328
How to set some space between the colorbar and the image
<p>I would like to set some space between the image and the colorbar, I have tried the pad but do nothing, so... This is the image I have: <a href="https://i.stack.imgur.com/liEOY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/liEOY.png" alt="enter image description here" /></a></p> <p>and this is ...
<p>The secondary axes occupies all of the space in the figure that is meant for axes. Therefore, no matter what padding you give to the colorbar of <code>ax</code>, it wont affect <code>ax2</code>.</p> <p>A hacky-ish solution would be to also spit your secondary axes exactly the same as the primary axes, and then delet...
python|matplotlib|colorbar
1
1,040
72,547,507
How to calculate progressively using python
<p>I am creating a fitness wearable device python program that tracks the distance its users walk or run daily. To motivate the users to meet and exceed the target distance, it rewards users with fitness points on a leadership board for the users who meet and exceed the target distance in a week.</p> <p>The fitness poi...
<p>I think you're almost there, just that the comparisons don't need to be so complicated:</p> <pre class="lang-py prettyprint-override"><code>def fitness_app(): while True: distance = int(input(&quot;Please Enter Distance in Km: &quot;)) if distance &lt; 32: fitness_pt = 0 elif ...
python
1
1,041
39,841,451
How to fix python program that appears to be doing an extra loop?
<p>A portion of a python program I am writing seems to be looping an extra time. The part of the program that isn't working is below. It is supposed to ask for a string from the user and create a two-dimensional list where each distinct character of the string is put in its own sub-list. (Hopefully that makes sense... ...
<p>Your mistake lies in this part:</p> <pre><code>if currentElement != compareTo: ... compareTo = listA[i] </code></pre> <p>It should be:</p> <pre><code>if currentElement != compareTo: ... compareTo = listA[elementsCounted] </code></pre> <p>It's an overly complex function for such a simple task.</p>
python|list|loops|if-statement|while-loop
1
1,042
16,156,505
Retrieve Test Parameter Values from Quality Center
<p>I have been trying to get the actual value of my parameters from Quality Center that have been set in my test's test configuration. I am using the OTA API through python. I cannot seem to get anything but the default value. </p> <p>Where should I be retrieving the parameter's value from? The test, design steps,...
<p>Can you post your code. I may be help you out. Have a look at following code. Assuming you know how to set the connection up : ( You need Test lab--> test set usually starts with Root) - hope this helps </p> <pre><code>GetTest=test_lab_folder.TestSetFactory TestSetFilter=GetTest.Filter GetTSList=GetTest.NewList(Tes...
python|hp-quality-center
0
1,043
16,241,944
Playing a sound in a ipython notebook
<p>I would like to be able to play a sound file in a ipython notebook. My aim is to be able to listen to the results of different treatments applied to a sound directly from within the notebook. Is this possible? If yes, what is the best solution to do so?</p>
<p>The previous answer is pretty old. You can use <a href="https://ipython.org/ipython-doc/dev/api/generated/IPython.display.html#IPython.display.Audio" rel="noreferrer">IPython.display.Audio</a> now. Like this:</p> <pre><code>import IPython IPython.display.Audio(&quot;my_audio_file.mp3&quot;) </code></pre> <p>Note tha...
audio|ipython|ipython-notebook
87
1,044
31,805,606
Saving XML using ETree in Python. It's not retaining namespaces, and adding ns0, ns1 and removing xmlns tags
<p>I see there are similar questions here, but nothing that has totally helped me. I've also looked at the official documentation on namespaces but can't find anything that is really helping me, perhaps I'm just too new at XML formatting. I understand that perhaps I need to create my own namespace dictionary? Either w...
<p>You need to <a href="https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.register_namespace" rel="noreferrer">register</a> the prefix and the namespace before you do <code>fromstring()</code> (Reading the xml) to avoid the default namespace prefixes (like <code>ns0</code> and <code>ns1...
python|xml|lxml|elementtree
21
1,045
38,751,084
How to write a customized LSTM in tensorflow?
<p>I am trying to reimplement this paper <a href="http://mi.eng.cam.ac.uk/~thw28/papers/EMNLP15.pdf" rel="nofollow">Semantically Conditioned LSTM-based Natural Language Generation for Spoken Dialogue Systems</a>, in which they add a gate to the LSTM cell and change how the state is computed.</p> <p>How can I do this i...
<p>The <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/nn.html#rnn" rel="nofollow"><code>tf.nn.rnn()</code></a> and <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/nn.html#dynamic_rnn" rel="nofollow"><code>tf.nn.dynamic_rnn()</code></a> functions accept an argument <code>cell</code...
machine-learning|neural-network|tensorflow|lstm
4
1,046
9,882,323
Advice extracting //td text and numbers
<p>I have been working through the tutorial adapting it to a project I want to achieve. I seem to have something going wrong that i just can't find the error to.</p> <p>When using 'scrapy shell' I can get the response I expect. So for this site <a href="http://live.nrlstats.com/nrl/ladder.html" rel="nofollow">Nrl Ladd...
<p>I didn't quite understand your question, but here is a starting point, imo (haven't tested; see some comments in the code):</p> <pre><code>from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from nrl.items import NrlItem class nrl(BaseSpider): name = "nrl" allowed_domains = ...
python|xpath|scrapy
2
1,047
68,138,901
How To Dynamically Use User Input for Jira Python
<p>So I am trying to make an interactive method of pulling out Jira information, based on a Jira Key.</p> <p>Full Code:</p> <pre class="lang-py prettyprint-override"><code>import os from atlassian import Jira import json with open('secrets.json','r') as f: config = json.load(f) jira_instance = Jira( url = &...
<p>So it turns out I was invoking it wrong. I needed to drop the <code>''</code> around the <code>'(jira_key)'</code> and just invoke it as follows with <code>(jira_key)</code> instead:</p> <pre class="lang-py prettyprint-override"><code>import os from atlassian import Jira import json with open('secrets.json','r') as...
python|jira|python-jira
0
1,048
2,265,234
Design pattern to organize non-trivial ORM queries?
<p>I am developing a web API with 10 tables or so in the backend, with several one-to-many and many-to-many associations. The API essentially is a database wrapper that performs validated updates and conditional queries. It's written in Python, and I use SQLAlchemy for ORM and CherryPy for HTTP handling.</p> <p>So far...
<p>The standard way to have global access to the current session in a threaded environment is <a href="http://www.sqlalchemy.org/docs/session.html#contextual-thread-local-sessions" rel="nofollow noreferrer">ScopedSession</a>. There are some important aspects to get right when integrating with your framework, mainly tra...
python|design-patterns|orm|refactoring|sqlalchemy
1
1,049
32,417,242
Scheduling a task in python
<p>i'm trying to schedule a task every 5 seconds, here what i did:</p> <pre><code>import schedule import time import tweepy from threading import Timer def job(): iGen = (i for i in range(1, 6)) for i in iGen: i += 1 mymessage = "My message here " + str(i) print(mymessage) schedule.every(5).second...
<p>Your job is to loop over 2-6, printing for each. It sounds like you want the job to just print once each time it runs. This would do that, but would not number the messages.</p> <pre><code>import schedule import time def job(): print("Message") schedule.every(5).seconds.do(job) while 1: ...
python
2
1,050
28,241,941
Disable OpenGL for Python / Matplotlib
<p>I'm doing a Python course for which I have installed Arch Linux in a VM. When I use Matplotlib.pyplot to plot things (x vs y) I get a bunch of errors.</p> <pre><code>libGL error: pci id for fd 12: 80ee:beef, driver (null) OpenGL Warning: glFlushVertexArrayRangeNV not found in mesa table OpenGL Warning: glVertexArra...
<p>so, despite of all the errors, I never had anything not working actually, the fact that I didn't see graphs was not due to the error in the original post. It was something else, I guess unrelated tot mpl and more related to lack of 3D acceleration in VirtualBox.</p>
linux|opengl|python-3.x|matplotlib|virtualbox
0
1,051
44,082,545
How to use findNumbers in Google PhoneNumberLib?
<p>I am using <a href="https://github.com/googlei18n/libphonenumber" rel="nofollow noreferrer">Googles Phone Number Library</a> to find phone numbers in a text file. That phone number can be in any format or from any country. Regex is not solving the problem. I was coding in <a href="https://github.com/daviddrysdale/py...
<p>IN the python port that you link to, there is a <code>PhoneNumberMatcher</code> class that provides the <code>FindNumbers</code> functionality. The code is <a href="https://github.com/daviddrysdale/python-phonenumbers/blob/dev/python/phonenumbers/phonenumbermatcher.py#L456" rel="nofollow noreferrer">here</a>.</p> ...
java|python|libphonenumber|phonenumberutils
0
1,052
44,344,222
I cant understand this code in Python, can you help me?
<p>I had a code assignment but i could'nt find the answer, so i check it on the net. the code is written in python. The code is absolutely right but i cannot understand it. I am pretty much new to python so plz help me.</p> <p>Here is the question</p> <p>Assume s is a string of lower case characters.</p> <p>Write a ...
<pre><code>s="abdhbdwba" maxLen=0 # sets the current highest length to 0 current=s[0] # sets the current letter to the first letter (this is the output string) longest=s[0] # sets the longest letter to the first letter(just for programming sake) # step through s indices for i in range(len(s) - 1): # goes...
python|iteration
2
1,053
32,896,019
Cursor when returning dictionary and print where are the keys
<p>I am trying to understand the data structures returned by cursor</p> <p>I have the following code:</p> <pre><code>con = psycopg2.connect("dbname='testdb2' user='kevin'") cursor = con.cursor(cursor_factory=psycopg2.extras.DictCursor) cursor.execute("SELECT * FROM Cars") rows = cursor.fetchall() for row in rows:...
<p>Each rown is a <a href="http://initd.org/psycopg/docs/extras.html#psycopg2.extras.DictRow" rel="nofollow"><code>DictRow</code></a> which inherits from <code>list</code>:</p> <p><a href="https://github.com/psycopg/psycopg2/blob/master/lib/extras.py" rel="nofollow">https://github.com/psycopg/psycopg2/blob/master/lib/...
python|postgresql|cursor|psycopg2
1
1,054
54,366,507
Check if the string contains the substring returns true when its actually false
<p>Is it a problem with my editor or what stupid mistake am I making ? Here is the screen-shot</p> <p><a href="https://i.stack.imgur.com/P9nkk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P9nkk.png" alt="enter image description here"></a></p> <p>This code returns true and it actually should</p> ...
<p>works fine: First one returns True, second one returns False:</p> <p>If you're running your code, it should correctly print <code>true</code> because the first set is True, and then prints nothing after that:</p> <pre><code>true </code></pre> <p>if both were True, you would see</p> <pre><code>true true </code></...
python|python-3.x
3
1,055
34,787,590
Error running python manage.py
<p>I'm using <code>flask</code> with Ubuntu, and when I run <code>python manage.py</code> I get this Traceback:</p> <pre><code>Traceback (most recent call last): File "manage.py", line 8, in &lt;module&gt; app.run(debug=True,processes=True) File "/proj/local/lib/python2.7/site-packages/flask/app.py", line 772,...
<p>This means this port on the address you're trying to use (presumably <code>localhost</code>) is <em>already being used by another process</em>. </p> <p>What to do to fix this:</p> <ul> <li>kill Python and restart your script</li> <li>or find a process that's using your port and kill it</li> <li>use another port fo...
python|ubuntu|flask
6
1,056
27,160,796
Using page text to select `html` element using`Beautiful Soup`
<p>I have a page which contains several repetitions of: <code>&lt;div...&gt;&lt;h4&gt;...&lt;p&gt;...</code> For example:</p> <pre><code>html = ''' &lt;div class="proletariat"&gt; &lt;h4&gt;sickle&lt;/h4&gt; &lt;p&gt;Ignore this text&lt;/p&gt; &lt;/div&gt; &lt;div class="proletariat"&gt; &lt;h4&gt;hammer&lt;/h4&gt; &l...
<p><code>:contains()</code> could help here, but it is not supported.</p> <p>Taking this into account, you can use <code>select()</code> in conjunction with the <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-next-siblings-and-find-next-sibling" rel="nofollow"><code>find_next_sibling()</code></a>:<...
python|html|css-selectors|beautifulsoup
1
1,057
27,155,129
Split pandas Series rows containing multiline strings into separate rows
<p>I have a pandas Series that is filled with strings like this:</p> <pre><code>In: s = pd.Series(['This is a single line.', 'This is another one.', 'This is a string\nwith more than one line.']) Out: 0 This is a single line. 1 This is another one. 2 This is a st...
<p>You could loop over each string in each row to create a new series:</p> <pre><code>pd.Series([j for i in s.str.split('\n') for j in i]) </code></pre> <p>It might make more sense to do this on the input rather than creating a temporary series, e.g.:</p> <pre><code>strings = ['This is a single line.', 'This is anot...
python|pandas|split|series
4
1,058
23,397,583
Writing camera matrix into xml/yaml file
<p>I am using opencv and python I have calibrated my camera having the following parameters:</p> <pre><code>camera_matrix=[[ 532.80990646 ,0.0,342.49522219],[0.0,532.93344713,233.88792491],[0.0,0.0,1.0]] dist_coeff = [-2.81325798e-01,2.91150014e-02,1.21234399e-03,-1.40823665e-04,1.54861424e-01] </code></pre> <p>I am...
<h1>Using JSON</h1> <p>JSON seems to be the easiest format for serialization in your case</p> <pre><code>camera_matrix=[[ 532.80990646 ,0.0,342.49522219],[0.0,532.93344713,233.88792491],[0.0,0.0,1.0]] dist_coeff = [-2.81325798e-01,2.91150014e-02,1.21234399e-03,-1.40823665e-04,1.54861424e-01] data = {"camera_matrix": ...
python|opencv
13
1,059
71,033,943
pandas: comparing non-identical list of panda dataframes based on values from a certain column
<p>I have a two lists of panda dataframes as follows,</p> <pre><code>import pandas as pd import numpy as np list_one = [pd.DataFrame({'sent_a.1': [0, 3, 2, 1], 'sent_a.2': [0, 1, 4, 0], 'sent_b.3': [0, 6, 0, 8],'sent_b.4': [1, 1, 8, 6],'ID':['id_1','id_1','id_1','id_1']}), pd.DataFrame({'sent_a.1': [0, 3], 'sen...
<p>Based on your current example</p> <p>For your first question:</p> <blockquote> <p>how can I sort values in these two lists, based on the values from column 'ID'?</p> </blockquote> <pre><code>list_one = sorted(list_one,key=lambda x: x['ID'].unique()[0][3:], reverse=False) list_two =sorted(list_two,key=lambda x: x['ID...
python|pandas|list|dataframe|compare
2
1,060
11,624,050
Using Flask, trying to get AJAX to update a span after updating mongo record, but it's opening a new page
<p>Feel like I am stumbling over something fairly simple here.</p> <p>I am not understanding something about AJAX and Flask.</p> <p>I have a project wherein I display mongodb records in the browser, which has been working fine.</p> <p>I added functionality for users to increment votes on a record; to Vote it up if t...
<p>My guess (based on your edit) is that you have more than one element on the page with the ID of <code>vote_link</code> - this is not allowed in HTML (the ID property must be unique across the document). If you want to have multiple links sharing the same behavior use a class instead (<code>$(".vote_link")</code> fo...
python|mongodb|jquery|flask
3
1,061
46,985,763
Not using all python sys.argv
<p>New to python, but my question is about sys.argv.</p> <p>I have program that I want to execute different sets of code depending on how many arguments are passed to it. </p> <p>python test.py hello awesome world</p> <p>would run a different set of code from</p> <p>python test.py hello world</p> <p>If I define 3 ...
<p>Wrap it in if statements:</p> <pre><code>if len(sys.argv) == 1: #do something elif len(sys.argv) == 2: #do something else elif len(sys.argv) == 3: #do something different else: #do the last possibility </code></pre>
python-3.x
1
1,062
37,912,611
Django -- Process Multiple Form Fields
<p>I am very new to Python / Django and would appreciate any and all help I can get here! </p> <p>I am trying to take in multiple form fields and haven't been able to find a great clean way to do so. My code is trying to take in a foreign Key radio selection (the team), and a number (the bet size), for each instance. ...
<p>I think your manual approach is quite OK, and all you have to do is find a way to uniquely identify the Bet field for each game. You could to this in your html:</p> <pre><code>&lt;input type="number" name="{{game.pk}}-Bet"&gt; </code></pre> <p>And then get the value in your view just before creating your PlayerPic...
python|django|forms
1
1,063
67,915,559
Last occurence of comma in python dataframe
<p>please help me on replace comma with &amp; in the last occurence of comma</p> <p>DF['MSG'] =</p> <p>0 20.00, 20.00 1 4.00, 3.00, 2.00 2 100.00 3 10.00, 70.00, 10.00 4 10.00, 10.00, 10.00, 10.00, 10.00 5 ...
<p>Assuming it's a clean list of numbers, you can change it to a string like this:</p> <pre><code>list_of_numbers = [1, 2, 3, 4] print(', '.join([str(i) for i in list_of_numbers[:-1]]) + f&quot; &amp; {list_of_numbers[-1]}&quot;) </code></pre> <p>gives</p> <p>1, 2, 3 &amp; 4</p>
python
0
1,064
72,422,859
Remove lines containing numbers attached to letters with Python
<p>I have a <em>txt</em> file containing one sentence per line, and there are lines containing numbers attached to letters. For instance:</p> <pre><code>The boy3 was strolling on the beach while four seagulls appeared flying. There were 3 women sunbathing as well. All children were playing happily. </code></pre> <p>I w...
<p>You can use a simple regex pattern. We start with <code>[0-9]+</code>. This pattern detects any number 0-9 an indefinite amounts of times. Meaning 6, or 56, or 56790 works. If you want to detect sentences that have numbers attached to a string you could use something like this: <code>([a-zA-Z][0-9]+)|([0-9]+[a-zA-Z]...
python|data-preprocessing
1
1,065
48,614,891
Pandas - select top N < L most frequent categories for multiple columns and join resulting vectors
<p>In Pandas I have separated my data by type and I need to summarize the frequency of the categorical data. I need to get all levels up to 50 levels. </p> <p>Right now I have something like this (example data follows):</p> <pre><code># Libraries import numpy as np import pandas as pd # Categorical vari...
<p>The key to the solution was in a comment from @JonClements:</p> <pre><code>table2 = df.melt().groupby(['variable', 'value']).size() </code></pre> <p>From there I just added some logic to truncate and transform the results:</p> <pre><code>table2 = table2.to_frame(name='Count') table2 = table2.reset_index(inplace=...
python|pandas
0
1,066
20,252,039
django output empty csv
<p>I'm using django and I'm trying to export the CSV_data list into csv file. Below is my csv.py:</p> <pre><code>#coding=utf-8 from django.http import HttpResponse from django.template import loader, Context from demo.views import CSV_data def output(request, filename): response = HttpResponse(mimetype='text/csv...
<p>As you didn't provide <code>helper.getResultByWeek</code> details and how it is called, I guess it returns a global variable with a list value, and this variable is modified somewhere in between.</p> <pre><code> CSV_data = usageDictWeek </code></pre> <p>do not copy a list, but creates another reference to existing...
python|django|csv
1
1,067
19,967,926
Flask request empty after redirect
<p>Using Flask, I'm able to access request.form data in the function poll(), but after a redirect, request.form is empty. </p> <p>I'm sure this is intentional and I have to explicitly pass this, but how?</p> <pre><code>from flask import render_template, redirect, request from app import app from forms import PollFor...
<p>It's common to redirect from a POST, but you shouldn't need your form data anymore in the details function.</p> <p>You should process the form submission in the poll function and then redirect to details, which I assume would display some updated data - e.g. from a database.</p> <pre><code>@app.route('/poll', meth...
python|request|flask
3
1,068
20,289,450
Python Scrapy not always downloading data from website
<p>Scrapy is used to parse an html page. My question is why sometimes scrapy returns the response I want, but sometimes does not return a response. Is it my fault? Here's my parsing function:</p> <pre><code>class AmazonSpider(BaseSpider): name = "amazon" allowed_domains = ["amazon.org"] start_urls = [ ...
<p>I believe you are just not using the most adequate XPath expression. </p> <p>Amazon's HTML is kinda messy, not very uniform and therefore not very easy to parse. But after some experimenting I could extract all the 12 titles of a couple of search results with the following <code>parse</code> function:</p> <pre><co...
python|request|response|scrapy|sites
0
1,069
51,134,734
Swaping values of two lists based on given index
<p>I have a list which consists out of two numpy arrays, the first one telling the index of a value and the second containing the belonging value itself. It looks a little like this:</p> <pre><code>x_glob = [[0, 2], [85, 30]] </code></pre> <p>A function is now receiving the following input:</p> <pre><code>x = [-10, ...
<p><a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.indexing.html#index-arrays" rel="nofollow noreferrer"><strong><code>NumPy</code></strong> arrays may be indexed with other arrays</a>, which makes this replacement trivial.</p> <p>All you need to do is index your second array with <code>x_glob[0]</code>, ...
python|arrays|list|numpy|indexing
3
1,070
73,598,430
How to make a customized grouped dataframe with multiple aggregations
<p>I have a standard dataframe like the one below :</p> <pre><code> Id Type Speed Efficiency Durability 0 Id001 A OK OK nonOK 1 Id002 A nonOK OK nonOK 2 Id003 B nonOK nonOK nonOK 3 Id004 B nonOK nonOK OK 4 Id005 A nonOK nonOK ...
<p>You can also use the following solution using <code>pandas</code> method chaining:</p> <pre><code>import pandas as pd (pd.melt(df, id_vars='Type', value_vars=['Speed', 'Efficiency', 'Durability'], value_name='Test') .groupby(['Type', 'Test', 'variable']) .size() .reset_index() .pivot(index=['Type', 'Test'], col...
python|pandas
6
1,071
70,713,678
Machine learning with vectors in both features and target
<p>How can I train a model with vectors/arrays as features? I seem to consistently getting errors when doing this...</p> <p>My feature matrix would look something like this:</p> <pre><code> A B C Profile 0 1 4 4 [1,2,3,4] 1 2 4 5 [2,2,4,1] </code></pre> <p>while my target vector wou...
<p>The error is being raised for <code>X</code> (third-to-last part of the traceback): you cannot have an array-valued feature. You need to do some feature engineering to generate a flat table of data to train on; whether that's flattening the arrays into individual features, or extracting some statistic based on thos...
python|dataframe|machine-learning|scikit-learn|linear-regression
1
1,072
69,676,952
How to create the list inside the dictionary using python
<p>I am trying to Automate the dataset creation in quicksight using Boto3. but I am stuck some point . please any one help to solve this. Here my code :</p> <pre><code>qs = boto3.client('quicksight') response = qs.describe_data_set( AwsAccountId='xxxxxxxx', DataSetId='testdatasetv4' ) columns =response['Data...
<p>Here's an example of creating a dictionary and adding different nested elements. You'll need to adapt for solution.</p> <pre><code>columns = ['key1', 'key2', 'key3'] vals = ['1', '2', '3'] mydict = {} mydict['firstkey'] = 1 mydict['anotherkey'] = {} mydict['anotherkey']['secondkey'] = 2 mydict['needalist'] = {} myd...
python|python-3.x|boto3|amazon-quicksight
0
1,073
73,299,066
Regex for finding trigonometry function with variable
<p>I have the string:</p> <pre><code>-15*sin(h)**2+121*sin(h)-216 </code></pre> <p>I'm currently using</p> <pre class="lang-py prettyprint-override"><code>input_text = re.findall(r&quot;sin|cos|tan|\d|\w|\(|\)|\+|-|\*+&quot;, input_text.strip().lower()) </code></pre> <p>to try to tokenize this string, but it returns th...
<p>Don't make <code>(</code>, <code>\w</code>, and <code>)</code> alternatives to the trig functions, make them part of that same match.</p> <pre><code>(?:sin|cos|tan)\(\w\)|\+|-|\*+ </code></pre>
python|regex|tokenize
0
1,074
49,899,298
How does GridSearchCV compute training scores?
<p>I'm having a hard time figuring out parameter <code>return_train_score</code> in <code>GridSearchCV</code>. From the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html#sklearn.model_selection.GridSearchCV" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <p><code>...
<p>It is the train score of the prediction model on all folds <strong>excluding</strong> the one you are testing on. In your case, it is the score over the 9 folds you trained the model on.</p>
python|scikit-learn|cross-validation|grid-search
3
1,075
49,919,919
html to pdf convertion css not working
<p>I try to convert the following page to pdf <a href="https://bootsnipp.com/snippets/P234b" rel="nofollow noreferrer">link</a> </p> <p>using xhtml2pdf library for python. But the problem is the css styles are not working properly. How can i solve the problem ?</p>
<p>You need to write all css in header. Import will not work in pdf.</p> <pre><code>&lt;link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"&gt; </code></pre> <p>this need to be change like following:</p> <pre><code>&lt;style&gt; /*! * Bootstrap v4.0.0 (htt...
django|python-3.x
1
1,076
64,981,825
How to override attribute in Base class Python3 , so that subsequent operations remains same verywhere?
<p>I have a use case, where I have to override one attribute in base class <strong>init</strong>, but the operations after that ( by making use of that attribute ) remains the same.</p> <pre><code>class Person: def __init__(self, name, phone, record_file = None): self.name = name self.phone = phone ...
<p>Your main problem is that you want to change an intermediate value in the <code>Person.__init__</code>, which won't work. But you could create an optional argument for the <code>contents</code> and just use that instead of the default one. Like this:</p> <pre class="lang-py prettyprint-override"><code>class Person: ...
python|python-3.x|class|inheritance
1
1,077
65,259,317
Tensorflow use : codec can't decode byte XX in position XX : invalid continuation byte
<p>i'm trying to train a model, I'm used the code that can be found here : <a href="https://medium.com/@martin.lees/image-recognition-with-machine-learning-in-python-and-tensorflow-b893cd9014d2" rel="nofollow noreferrer">https://medium.com/@martin.lees/image-recognition-with-machine-learning-in-python-and-tensorflow-b8...
<p>The error was really stupid, because I'm on windows, this line</p> <pre><code>saver.save(sess, &quot;./model&quot;) </code></pre> <p>was the cause of the error, so I changed it with this :</p> <pre><code>saver.save(sess, &quot;model\\model&quot;) </code></pre> <p>And now this is working.</p>
python|tensorflow
0
1,078
71,674,381
creating multiple columns with a loop based on other column in pandas
<p>Hello everyone I have a working code in python but it is written in a crude way because I am still learning the fundamentals and require some insight.</p> <p>I am creating 40 columns based on one column like i shared a small part of it below:</p> <pre><code>df[&quot;Bonus Payout 80%&quot;]=0 df[&quot;Bonus Payout 81...
<p>You can use <code>f-strings</code> and <code>for loops</code>:</p> <pre><code>j = 0 for i in range(80,121): df[f&quot;Bonus Payout {i}%&quot;]=df[&quot;Monthly gross salary 100% (LC)&quot;]*j df[f&quot;Bonus Payout {i}%&quot;]=df[f'Bonus Payout {i}%'].apply('{:,.2f}'.format) j += 0.01 </code></pre> <p>P....
python|pandas|dataframe|loops|multiple-columns
1
1,079
61,618,439
Realtime JSON string transfer from android/ios app to a Windows software
<p>I want to create an android/ios app that would send a normal string (or a json) to a software in Windows which i will also make. Example, in my mobile app when i press a button, the text on my Windows software will change to whatever text that was sent by my the mobile app in realtime, not after 1 minute or so.</p>...
<p>your question covers a lot of subjects, but I'll try to give you some basic information. basic best practices</p> <ol> <li>Don't use raw sockets, the industry standard is mostly using an HTTP server (Django or Flask) with RESTful API using JSON as your serialization protocol. I also recommend that you'll make your ...
python|json|sockets|transfer|instant
0
1,080
56,866,244
numpy timedelta64 not showing fraction
<p>I want to convert 847hours into days, Actual result is 847/24= 35,29..</p> <p>But, numpy show only "35 days"</p> <hr> <pre><code>import numpy as np x= np.timedelta64(847, 'h') x= np.timedelta64(x, 'D') print(x) #Returns 35 days, Expected 35,29 </code></pre> <hr>
<p>The magnitude of a <code>timedelta64</code> is always stored as <em>a 64-bit integer</em> (cf. <a href="https://docs.scipy.org/doc/numpy/reference/arrays.datetime.html#datetime-units" rel="nofollow noreferrer">Datetime Units</a>). To obtain fractional days, we can do:</p> <pre><code>import numpy as np x = np.timede...
python-3.x|numpy|timedelta
1
1,081
56,509,345
How can I stop networkx to change the source and the target node?
<p>I make a Graph (not Digraph) from a data frame (Huge network) with networkx. I used this code to creat my graph: nx.from_pandas_edgelist(R,source='A',target='B',create_using=nx.Graph())</p> <p>However, in the output when I check the edge list, my source node and the target node has been changed based on the sort an...
<p>If you mean the order has changed, check out <code>nx.OrderedGraph</code></p>
python|pandas|networkx
0
1,082
60,879,602
Get values from between two other values for each row in the dataframe
<p>I want to extract the integer values for each Hole_ID between the From and To values (inclusive). And save them to a new data frame with the Hole IDs as the column headers.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np df=pd.DataFrame(np.array([['Hole_1',110,117],['Hole_...
<p>Apply a method that returns a series of a range between from and to and then transpose the result, eg:</p> <pre><code>import numpy as np df.set_index('HOLE_ID').apply(lambda v: pd.Series(np.arange(v['FROM'], v['TO'] + 1)), axis=1).T </code></pre> <p>Gives you:</p> <pre><code>HOLE_ID Hole_1 Hole_2 Hole_3 Hole...
python|pandas|range
4
1,083
63,305,130
Removing unwanted characters, and writing from a JSON response
<p>So, I am trying to extract specific data and write it to a file, this JSON response has odd brackets around the information I want and need to be stripped off and I'm not really sure how to get to the 'desired output'.</p> <p>Maybe its better to do it in an xls document? The end goal is to compare this list against ...
<p>You can have it done this way:</p> <pre><code>import csv data = [{'adapter_list_length': 3, 'adapters': ['adapter1', 'adapter2', 'adapter3'], 'id': '', 'labels': ['', ''], 'specific_data.data.hostname': ['HOSTNAME1'], 'specific_data.data.last_seen': '', 'specific_data.data.network_interfaces.ips': ['123.45.67.89'...
python|json|api|csv|python-requests
0
1,084
59,625,229
Append min value of two columns in pandas data frame
<p><strong>df</strong></p> <pre><code>Purchase 1 3 2 5 4 7 </code></pre> <p><strong>df2</strong></p> <pre><code>df2 = pd.DataFrame(columns=['Mean','Median','Max','Col4']) df2 = df2.append({'Mean': (df['Purchase'].mean()),'Median':df['Purchase'].median(),'Max':(df['Purchase'].max()),'Col4':(df2[['Mean','Median']...
<p>Use <code>np.minimum</code> and passed <code>mean</code> with <code>median</code>:</p> <pre><code>df2 = pd.DataFrame(columns=['Mean','Median','Max','Col4']) df2 = (df2.append({'Mean': df['Purchase'].mean(), 'Median':df['Purchase'].median(), 'Max': df['Purchase'].max(), ...
python|python-3.x|pandas
6
1,085
60,027,706
Expected a list of dataframe got just one dataframe
<p>Am trying to convert list of sheets from an excel file into a csv, so beginning with the following codes, i want to read the files first, but i only get the first sheet, and the rest are lost</p> <pre><code>import pandas as pd def accept_xcl_file(file): xcl_file = pd.ExcelFile(file) sheets= xcl_file.sheet_...
<p>The <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html" rel="nofollow noreferrer">read_excel</a> method is already available in pandas to import Excel data.</p> <p>Try this instead of your code:</p> <pre><code>import pandas as pd file = pd.read_excel('Companies.xlsx') # file...
python|pandas
1
1,086
66,897,615
Combining list of numbers and strings in python
<p>As an <code>R</code> user, I know very little about python. I am using <code>python moviepy</code> to pick up a long list of photos to generate a video in <code>RStudio notebook</code>. What I did previously was to use <code>R</code> to generate the list of photos.</p> <p>R code:</p> <pre><code>v_list &lt;- c(paste0...
<p>How about</p> <pre class="lang-py prettyprint-override"><code>v_list = [f&quot;v_{x}.jpg&quot; for x in list(range(1, 10)) + [10] * 5 + [11] * 10] </code></pre>
python|r|list
2
1,087
66,770,996
Recursively copy the secrets from one VAULT path to another
<p>I am trying to copy all the secrets along with the subfolders from one <strong>VAULT</strong> path to another. Example:</p> <pre><code>source = &quot;/path/namespace/TEAM1/jenkins&quot; </code></pre> <p>(note: the above source path consists of subfolders like job1,job2,job3... and all these subfolders contains the r...
<p>Taking vault secret backup from one path to another like. input_path: secret/tmp1 output_path: secret/tmp2 so now with this python script you can sync all secret from secret/tmp1 to secret/tmp2</p> <p>Need to add input_path and output_path in python script then just run. Link for python script. <a href="https://gith...
python-3.x|hashicorp-vault|vault
0
1,088
35,036,077
How do I fix this speed varible writing back to file?
<p>I've been writing a program, I've run into an error. My current code is: </p> <pre><code>import tkinter as tk speed = 80 def onKeyPress(event, value): global speed text.delete("%s-1c" % 'insert', 'insert') text.insert('end', 'Current Speed: %s\n\n' % (speed, )) with open("speed.txt", "r+") as p: ...
<p>One problem (I guess it's the problem you're having) is that you are trying to overwrite the content of file <code>speed.txt</code>, however, the value you are writing contains fewer characters than already contained in the file.</p> <p>This can lead to unexpected values winding up in your file, e.g. if the file co...
python
2
1,089
56,357,209
Pix2pix program terminates after giving Thread warning of Tensorflow
<p>I am trying to run <a href="https://github.com/eriklindernoren/Keras-GAN/blob/master/pix2pix/pix2pix.py" rel="nofollow noreferrer">https://github.com/eriklindernoren/Keras-GAN/blob/master/pix2pix/pix2pix.py</a></p> <pre><code>python pix2pix.py </code></pre> <p>Execution terminates giving following message</p> <pr...
<p>It's not throwing any error. So I'm guessing the script isn't finding the training dataset. Try downloading the dataset and try running it again.</p> <pre><code>bash download_dataset.sh facades python pix2pix.py </code></pre>
tensorflow|keras|deep-learning|generative-adversarial-network
1
1,090
42,538,930
SSL error with Python requests despite up-to-date dependencies
<p>I am getting an SSL "bad handshake" error. Most similar responses to this problem seem to stem from old libraries, 1024bit cert. incompatibility, etc... I <em>think</em> i'm up to date, and can't figure out why i'm getting this error.</p> <p>SETUP:</p> <ul> <li>requests 2.13.0 </li> <li>certifi 2017.01.23</li> <l...
<p>The validation fails because the server you access is setup improperly, i.e. it is not a fault of your setup or code. Looking at the <a href="https://www.ssllabs.com/ssltest/analyze.html?d=api.sidecar.io&amp;s=52.25.112.146&amp;latest" rel="noreferrer">report from SSLLabs</a> you see </p> <blockquote> <p>This ser...
python|ssl|ssl-certificate|python-requests
16
1,091
53,926,506
How to get default browser name using python?
<p>Following solutions (actually it is only one) doesn't work to me :</p> <blockquote> <p><a href="https://stackoverflow.com/questions/19037216/how-to-get-a-name-of-default-browser-using-python">How to get a name of default browser using python</a></p> </blockquote> <hr> <blockquote> <p><a href="https://stackove...
<p>The following works for me on Windows 10 pro:</p> <pre><code>from winreg import HKEY_CURRENT_USER, OpenKey, QueryValueEx reg_path = r'Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice' with OpenKey(HKEY_CURRENT_USER, reg_path) as key: print(QueryValueEx(key, 'ProgId')) </code></pr...
python|python-3.x|browser|windows-10
2
1,092
53,833,151
Dump pandas DataFrame to SQL statements
<p>I need to convert pandas DataFrame object to a series of SQL statements that reproduce the object.</p> <p>For example, suppose I have a DataFrame object:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'manufacturer': ['Audi', 'Volkswagen', 'BMW'], 'model': ['A3', 'Touareg', 'X5']}) &gt;&gt;...
<p>SQLite actually allows one to dump the whole database to a series of SQL statements with <a href="https://www.sqlite.org/cli.html#converting_an_entire_database_to_an_ascii_text_file" rel="nofollow noreferrer">dump command</a>. This functionality is also available in python DB-API interface for SQLite: sqlite3, speci...
python|pandas|sqlite|sqlalchemy
3
1,093
58,351,948
Python requests, how to send json request without " "
<p>my code looks like</p> <pre><code> data = { "undelete_user":'false' } data_json = json.dumps(data) print(data_json) </code></pre> <p>Output is: </p> <pre><code>{"undelete_user": "false"} </code></pre> <p>i need output to be without "" so it can look ...
<pre><code>import json data = { "undelete_user": False } data_json = json.dumps(data) print(data_json) </code></pre> <p>All you had to do was remove 'false' and put False, because you're considering your false as a string, and it should be a boolean. I hope it helped!</p>
python|json|python-3.x
3
1,094
22,599,692
For loop not iterating?
<p>I am a python newbie and I seem to be having an issue and I can't see what I am doing wrong. I am trying to make it so that when I enter a string it turns the string into pig latin. The issue is that when I do this it only prints out the first word in the string converted. Would anyone be able to point me in the rig...
<p>Your <code>return</code> statement is inside the <code>for</code> loop due to bad indentation, so obviously it will return after one iteration.<br> Here is the code that will fix this, along with some other changes:</p> <pre><code>def pigetize(text, wovels): return ((text + "way") if text[0] in wovels else (tex...
python-3.x
0
1,095
22,726,878
Python, append within a loop
<p>So I need to save the results of a loop and I'm having some difficulty. I want to record my results to a new list, but I get "string index out of range" and other errors. The end goal is to record the products of digits 1-5, 2-6, 3-7 etc, eventually keeping the highest product. </p> <pre><code>def product_of_dig...
<p>Similar question some time ago. Hi Chauxvive</p> <p>This is because you are checking until the last index of <code>d</code> as <code>s</code> and then doing <code>d[s+4]</code> and so on... Instead, you should change your <code>while</code> loop to:</p> <p><code>while s &lt; (len(d)-4):</code></p>
python|list|loops|append|product
0
1,096
45,480,459
How to serialize and deserialize objects with cbor2?
<p>I'm trying to serialize and deserialize object using cbor2 but even after following the documentation I cannot properly do it. Let' suppose I have the following two classes:</p> <pre><code>class A(object): def __init__(self): self.a = 5 self.b = set() def a(self): return self.a cla...
<p>Sorry for a late answer.</p> <p>CBOR2 is currently missing support for serializing sets which could be stored as tagged arrays.</p> <p>There is a ticket for adding support here: </p> <p><a href="https://github.com/agronholm/cbor2/issues/14" rel="nofollow noreferrer">https://github.com/agronholm/cbor2/issues/14</a...
python|serialization|deserialization|cbor
0
1,097
28,598,140
Pandas: Incrementally count occurrences in a column
<p>I have a DataFrame (df) which contains a 'Name' column. In a column labeled 'Occ_Number' I would like to keep a running tally on the number of appearances of each value in 'Name'. </p> <p>For example:</p> <pre><code>Name Occ_Number abc 1 def 1 ghi ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="noreferrer"><code>cumcount</code></a> to avoid a dummy column:</p> <pre><code>&gt;&gt;&gt; df["Occ_Number"] = df.groupby("Name").cumcount()+1 &gt;&gt;&gt; df Name Occ_Number 0 abc ...
python|pandas|dataframe
27
1,098
56,973,197
Connection of Event hubs to Azure Databricks
<p>I want to add libraries in Azure Databricks for connecting to Event Hubs. I will be writing notebooks in python. So which library should I add for connecting to Event Hubs?</p> <p>As per my search till now I got a spark connecting library in Maven coordinates. But I don't think I will be able to import it in python...
<p>Structured streaming integration for Azure Event Hubs is ultimately run on the JVM, so you'll need to import the libraries from the Maven coordinate below:</p> <pre><code> groupId = com.microsoft.azure artifactId = azure-eventhubs-spark_2.11 version = 2.3.10 </code></pre> <p><strong>Note:</strong> For Python a...
python|azure|azure-databricks
0
1,099
23,995,473
Having trouble comparing a variable to an input in a while loop
<p>I'm having some trouble working on a basic program I'm making whilst I try and learn Python, the problem is I am trying to compare a users input to a variable that I have set and it is not working when I try and compare them.</p> <p>This is the loop in question:</p> <pre><code> if del_question == "1": symb...
<p>Your bug is a simple logic error. You have an <code>and</code> conditional when you really want an <code>or</code> conditional. Change your second while statement to:</p> <pre><code>while letter in words or len(letter) != 1 </code></pre>
python|variables
1