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
5,800
61,114,280
django.core.exceptions.ImproperlyConfigured: The included URLconf 'api.urls' does not appear to have any patterns in it
<p>Having a hard time understanding why I am receiving this error. If I just leave the api/user/ path it works fine but when I try to add api/user/date_counter/ path I get this error. Using Django 3. Any help would be appreciated.</p> <p>Pseudo-graphics like below is based on how maven shows the output of dependency:t...
<p>I think the problem is how you registering your ViewSet to <code>urlpatterns</code>. Try like this:</p> <pre><code>from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('date_counter', views.DateCounterViewSet) urlpatterns = [ path('', include(router.urls)), ] </code></pre>...
python|django|django-rest-framework
1
5,801
61,041,810
Why doesn't my hash function output a dynamic value?
<p>I'm a newbie in this field and am trying to learn a bit about how to write cryptographic hash functions.</p> <p>To get some hands-on, I tried updating the <a href="https://github.com/thomdixon/pysha2" rel="nofollow noreferrer">PySHA2</a> algorithm for Python 3.6 and up (the original version doesn't work on Python 2...
<p>You'll always have to pad the message. Padding and adding the length are always required as last step of the SHA-2 process. Currently you weren't performing that last step (to completion).</p> <p>Here are my last two comments that pointed you in the right direction:</p> <blockquote> <p>So generally you try and t...
python|hash|sha|sha512
1
5,802
21,305,551
numpy, scipy, interp1d - TypeError: tuple indices must be integers, not str
<p>I am doing interp1 using scipy.</p> <pre><code>N = 200 gam = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
<p>You are passing the arguments to <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html" rel="nofollow"><code>interp1d</code></a> in the wrong order: <code>kind</code> (e.g. <code>'linear'</code>) should be the third argument, the fourth is <code>axis</code>, which should be an ...
python|numpy|scipy
2
5,803
21,004,029
Python: Sorting an array based on a subvalue
<p>I have the following data structure:</p> <pre><code>[ { some: thing9, key: 9, }, { some: thing3, key: 3, }, { some: thing2, key: 2, }, { some: thing1, key: 1, } ] </code></pre> <p>How can I sort this array based on the key value of the dictionary so I get:<...
<pre><code>sorted(data, key=operator.itemgetter('key')) </code></pre> <p>The <a href="http://docs.python.org/3/howto/sorting.html" rel="nofollow">Sorting HOWTO</a> explains this in more detail. But the basic idea is that all sort-related functions take a <code>key</code> argument, a callable that's applied to each val...
python|python-2.7
4
5,804
21,197,305
Collision Detection between a line and a circle in python(tkinter)
<p>I writing a python program in which a circle bounces off of user drawn lines. There are multiple circles that bounce off the wall. For each one, the shortest distance from the center of the circle and the ball should be calculated. I would prefer if this code was very efficient because my current algorithm lags the ...
<p>To be correct we are not speaking not about lines, but rather segments.</p> <p>I would suggest the following idea:</p> <p>Since the ball is moving in some direction, the only points that might collide with something lie on a 180° arc - the part that is moving forward. Meaning at some point of time when you check f...
algorithm|math|python-3.x|tkinter|collision-detection
1
5,805
70,145,519
What is the meaning of this idiom assigning from an empty list to an empty list?
<p>I ran into a code that calls a function f():</p> <pre class="lang-py prettyprint-override"><code>def f(): return 1, [] a, [] = f() </code></pre> <p>I was wondering why didn't the author use <code>a, _ = f()</code>. Why is this syntax even allowed?</p> <pre class="lang-py prettyprint-override"><code>[] = [] a, [...
<p>Consider a less strange-looking example:</p> <pre><code>def f(): return 1, [2, 3] a, [b, c] = f() </code></pre> <p>This is an ordinary <a href="https://stackoverflow.com/questions/tagged/python+destructuring">destructuring assignment</a>; we simple assign <code>a = 1</code>, <code>b = 2</code> and <code>c = 3</...
python|syntax
4
5,806
45,734,058
How do I plot a vector field within an arbitrary plane using Python?
<p>I have a 3d velocity vector field in a numpy array of shape (zlength, ylength, xlength, 3). The '3' contains the velocity components (u,v,w).</p> <p>I can quite easily plot the vector field in the orthogonal x-y, x-z, and y-z planes using quiver, e.g.</p> <pre><code>X, Y = np.meshgrid(xvalues, yvalues) xyfieldfig...
<p>You're close. Daniel F's suggestion was right, you just need to know how to do the interpolation. Here's a worked example</p> <pre><code>from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import numpy as np import scipy.interpolate def norm(v,axis=0): return np.sqrt(np.sum(v**2,axis=axi...
python|numpy|matplotlib|vector|3d
2
5,807
46,164,378
How to update the value of one record based on another record with specific criteria in the same dataframes
<p>In python, I have a dataframes table of GDP records like this</p> <pre><code>Quarter Vaule percentage 2017Q1-Q4 100 18% 2017Q1-Q3 60 20% 2017Q1-Q2 30 15% 2017Q1-Q1 10 10% 2016Q1-Q4 10 28% 2016Q1-Q3 6 50% 2016Q1-Q2 3 45% 2016Q1-Q1 1 20% </code></pre> <p>I want the output like th...
<p>IIUC:</p> <pre><code>In [20]: df.loc[~df.Quarter.str.contains(r'\d+Q1-Q1'), 'Vaule'] = df.Vaule.diff(-1) In [21]: df Out[21]: Quarter Vaule percentage 0 2017Q1-Q4 40.0 18% 1 2017Q1-Q3 30.0 20% 2 2017Q1-Q2 20.0 15% 3 2017Q1-Q1 10.0 10% 4 2016Q1-Q4 4.0 28% 5 ...
python|loops|dataframe
1
5,808
54,844,331
How to remove certain unwanted files from a Torrent file?
<p>I have a list of torrent files (2000) in a folder. Each torrent file contains about 500 downloadable files. Around 1 million total downloadable files. I only want to download some of them that match a certain criteria.</p> <p>I have created a dictionary in Python that contains torrent file names as keys and a list ...
<p>You can use <a href="https://github.com/eliasson/pieces/blob/master/pieces/bencoding.py" rel="nofollow noreferrer">this lib to parse *.torrent files</a> and make result dict.</p> <p>Decode example:</p> <pre><code>from pieces.bencoding import Decoder Decoder(b'i123e').decode() </code></pre> <p>Working with torrent...
python|scripting|torrent
0
5,809
33,310,791
Disable popup of cmd windows when using gitpython and py2exe?
<p>On using gitpython on Windows with py2exe, every operation that is invoked by gitpython results in a cmd popup window. It seems to be that gitpython is using subprocess internally. Is there a way to specify the following equivalent in gitpython?</p> <pre><code>creationflags=win32process.CREATE_NO_WINDOW </code></p...
<p>Found the solution. The way to solve this is to do this for gitpython is by setting before using the Git() object.</p> <pre><code>Git.USE_SHELL=True </code></pre>
python|git|gitpython
0
5,810
33,186,846
Highly customized admin - Create an app or hack the source code?
<p>I have been facing a big challenge with django since I was assigned the task to rebuild the admin page of our platform. I started unsure of what to do and now that I am half way on, I am even more unsure.</p> <p>Here is my question:</p> <h1>If I want to build a highly customized admin, should I do a giant hack on th...
<p>There is no need to overwrite admin views. The easiest way is to overwrite the templates and add your own css &amp; javascripts. </p> <p>I have added my own navbar, sidebars and bottom. It is really easy if you overwrite the admin base templates. </p> <p>If needed you can provide custom data to the template by usi...
python|django|django-admin
0
5,811
24,807,804
How to read(python[, argspecs])?
<p>I tried to create a mock object like this, without wanting to manually specify the bases (since I don't need any bases):</p> <pre><code>&gt;&gt;&gt; type('dummy_thing', dict={'dummy_attr': 'potato'}) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: type() takes 1 or 3 ...
<p>If the documentation doesn't specifically describe an argument as being a named argument than you shouldn't assume that it has a name. This is true even when in fact does does have a name (eg. most functions defined in Python code), because unless the documentation describes it as being a named argument no promises ...
python
0
5,812
38,472,671
Unable to execute code on Jupyter Notebook
<p>I have been watching tutorials on data mining using python. I have installed Anaconda Python 3.5 package for windows 64 bit with default installation. I have made the program available to all users on my laptop. I am running windows 10 64 bit. I am able to open Jupyter notebook on localhost at <a href="http://local...
<p>The info here <a href="http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Running%20Code.html" rel="nofollow">http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Running%20Code.html</a> says try <code>shift+enter</code> or green rectangle button. Would it not be easier to just save the...
ipython|jupyter-notebook
0
5,813
30,765,060
How do I get flask-cor to return Access-Control-Allow-Origin on Google App Engine?
<p>My python app does not throw any errors on Google App Engine, but the Allow-Control-Access-Origin header is never sent. How can I ensure that I am sending it with flask-cors?</p> <pre><code>import MySQLdb import os import webapp2 import json import flask from flask import Flask, jsonify, render_template, request fr...
<p>It appears that this code actually does work, although I do not see the Allow-Control-Access-Origin header when I use cURL to test the url. The logs in Google App Engine show CORS selectively adding the header unless the client specifically skipped it. Also, the Javascript client is no longer showing an error, and ...
python|google-app-engine|flask
0
5,814
31,132,394
Avoid code duplication with class inheritance python
<p>I’m looking for a nice solution to avoid code duplication, my code look like this; </p> <pre><code>class HostEnvironment(AbstractEnvironment): def provision(self, wait_for_sshd=True): some code def __init__(self, layer_info): pass class VCBEnvironment(HostEnvironment): def provisio...
<p>E.g. like this:</p> <pre><code>class AbstractEnvironment: pass class HostEnvironment (AbstractEnvironment): def __init__ (self, layer_info): pass def provision (self, wait_for_sshd = True): print 'some code' class VCBEnvironment (HostEnvironment): def __init__(self, layer_info): ...
python|python-2.7|object|code-duplication
1
5,815
28,908,142
Python 3.4 and 2.7 installation no Script folder and no pip installed
<p>I was doing a fresh installation for <code>Python 2.7.9</code> and <code>3.4.3</code> on <code>Win7 X64</code> today, and I found that there is no <code>Script</code> folder in <code>Python27</code> and <code>Python34</code> folder as first child level folder, but there is one in <code>Tools</code>. However, I could...
<p>If you used the PSF (python.org) .msi Windows installers, pip (and dependencies) should be installed in pythonxy/Lib/site-packages for 3.4.0+ and 2.7.9+. There should also be pythonxy/Scripts containing about 5 .exes. This is the last part of the install process. A command prompt window should briefly appear. Per...
python|python-2.7|python-3.x|pip
14
5,816
52,035,966
PyQT - Group cells in QTableWidget
<p>I'm searching how to create headers like HTML-tables in QTableWidget, something like that:<a href="https://i.stack.imgur.com/dqfFH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dqfFH.png" alt="enter image description here"></a></p> <p>I can do it in QTextEdit (HTML-table with images in cells), ...
<blockquote> <p>QTableView.setSpan(row, column, rowSpan, columnSpan)</p> <p>Parameters:<br> row – PySide.QtCore.int<br> column – PySide.QtCore.int<br> rowSpan – PySide.QtCore.int<br> columnSpan – PySide.QtCore.int </p> <p>Sets the span of the table element at (row , column ) to the number of ro...
python|pyqt
4
5,817
51,857,870
How can I compile .py to .dll
<p>i have written python function that imports several packages to detect and interps barcode in a pic. and know i want to use this function in C#. and my question is how can i compile .py to .dll </p>
<p>You can not, at least with CPython (the reference implementation of Python).</p> <p>However, you may try using <a href="http://ironpython.net/" rel="nofollow noreferrer">IronPython</a> — a .NET implementation of Python. It allows your python code to use .NET libraries and vice versa. Note that it only supports Pyth...
python|python-3.x|dll
1
5,818
52,002,330
Squish sharing step definitions across test suites (BDD)
<p>On <a href="https://kb.froglogic.com/display/KB/Sharing+step+definitions+across+test+suites+%28BDD%29" rel="nofollow noreferrer">https://kb.froglogic.com/display/KB/Sharing+step+definitions+across+test+suites+%28BDD%29</a> it is described how to share step definition across test suits, but is not working for me.</p>...
<p>In order to share steps across test suite and you want to change the default location for steps, and put steps folder in Global scripts, you have to pass in collectStepDefinitions() the entire path of your steps location director</p> <p>ex: if your steps are located to ('E:/myproject/squish/lib/panels/steps') than ...
python|bdd|squish
-1
5,819
51,599,586
Combining numbers together to form multiple digit number
<p>I'm trying to combine multiple numbers together in python 3.7 but I'm having no luck.</p> <p>I want it to be like such:</p> <pre><code>1 + 4 + 5 = 145 </code></pre> <p>I know this is simple but I'm getting nowhere!</p>
<p>You can use <code>reduce</code> to do this in a mathematical way</p> <pre><code>&gt;&gt;&gt; l = [1, 4, 5] &gt;&gt;&gt; &gt;&gt;&gt; from functools import reduce &gt;&gt;&gt; reduce(lambda x,y: 10*x+y, l) 145 </code></pre> <p>Alternatively, you can use string concat</p> <pre><code>&gt;&gt;&gt; int(''.join(map(st...
python|math|python-3.7
4
5,820
18,808,169
python ThreadedTCPServer can only access local connections on windows 7
<p>I'm using ThreadedTCPServer to start a TCP server. Here is the code:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import socket import threading import SocketServer import time class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): recv1 = self.request.recv...
<p>Your program does seem to be listening for connections correctly. And looking at this post from the superuser's stack exchange, it appears that your configuration is correct. See: <a href="https://superuser.com/questions/386436/the-meaning-of-port-0-in-netstat-output">https://superuser.com/questions/386436/the-meani...
python|multithreading|sockets|tcp
1
5,821
62,269,182
UnboundLocalError UnboundLocalError: local variable 'username' referenced before assignment
<p>Can any one help me with this UnboundLocalError: local variable 'username' referenced before assignment</p> <p><a href="https://i.stack.imgur.com/hhpif.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hhpif.png" alt="enter image description here"></a></p> <pre><code>@app.route("/login", methods=[...
<p>The error is pretty straightforward.If <code>method==POST</code> you define <code>username</code> but if method is not post <code>username</code> is not defined.Add <code>username = None</code> just after <code>def login</code> </p>
python|flask
0
5,822
67,290,650
What is JaxNumpy-compatible equivalent to this Python function?
<p>How do I implement the below in a JAX-compatable way (e.g., using <code>jax.numpy</code>)?</p> <pre><code>def actions(state: tuple[int, ...]) -&gt; list[tuple[int, ...]]: l = [] iterables = [range(1, i+1) for i in state] ns = list(range(len(iterables))) for i, iterable in enumerate(iterables): ...
<p>Jax, like numpy, cannot efficiently operate on Python container types like lists and tuples, so there's not really any JAX-compatible way to create a function with the exact signature you specify above.</p> <p>But if you're alright with the return value being a two-dimensional array, you could do something like this...
python|numpy|jax
1
5,823
36,259,409
Python - Adding space to left side of legend between marker and border
<p>I am having a problem where the markers are very close to the edge of the legend. I created a rectangle for an empty entry, and also hoping that I could adjust the width so it would add space on the left.</p> <p>I am trying to add space to the left side of the legend only. Using borderpad adds space to all sides of...
<p>To increase space on the left side of the legend only, increase the handlelength parameter. At the moment you have it set to 0. </p>
python|matplotlib|plot|legend|rectangles
1
5,824
36,350,979
Python pandas data frame: how to perform operations on two columns with the same name
<p>Say you have a data frame like the one which follows (notice that some columns have the same name):</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame(np.random.rand(4,5), columns = list('abcab')) </code></pre> <p>The issue is if you want to perform some operations on the two columns 'a', how...
<p>You should be able to change the label of the columns doing:</p> <pre><code>df.columns = ['a', 'b', 'c', 'd', 'e'] </code></pre>
python|numpy|pandas|dataframe
0
5,825
36,606,355
Best way to reverse a dictionary with list as values?
<p>I currently have a dictionary like so:</p> <pre><code>app_dict = {test1 : [[u'app-1', u'app-2', u'app-3', u'app-4']]} </code></pre> <p>I have a function that reverses the dictionary (which is proven to be working with another dictionary).</p> <pre><code>def reverse_dictionary(self, app_dict): """ In order to ...
<p>The error is simply saying that lists cannot be used as a key in a dictionary because they are mutable. However, tuples are immutable and therefore can be used as a key.</p> <p>A possible work around could be:</p> <pre><code>def reverse_dictionary(self, app_dict): """ In order to search by value, reversing the...
python|list|dictionary
0
5,826
19,720,311
How to split a text file to its words in python?
<p>I am very new to python and also didn't work with text before...I have 100 text files, each has around 100 to 150 lines of unstructured text describing patient's condition. I read one file in python using:</p> <pre><code>with open("C:\\...\\...\\...\\record-13.txt") as f: content = f.readlines() print (cont...
<p>It depends on how you define <code>words</code>, or what you regard as the <code>delimiters</code>.<br> Notice <code>string.split</code> in Python receives an optional parameter <code>delimiter</code>, so you could pass it as this:</p> <pre><code>for lines in content[0].split(): for word in lines.split(','): ...
python
9
5,827
19,387,101
Python Connection with mongoHQ fails?
<p>I want to connect to mongoHq database through python. here is what i have done so far</p> <p>an environmental variable is set:</p> <pre><code>MONGOHQ_URL = mongodb://myusername:mypassword@paulo.mongohq.com:10084/mydb </code></pre> <p>and the app.py file</p> <pre><code>import os import datetime import pymongo fro...
<p>I think , there is no need of setting environment variable for testing it in local machine , and maybe the error is because it didn't get set properly.</p> <p>Another issue I can see , that you haven't replaced user and pass with your username password of user you created for particular database.Try connecting your...
python|mongodb|pymongo|mongohq
0
5,828
19,309,355
Selecting data from groups within a csv and appending data to text file
<p>I have a problem which I do not know how to solve currently. I have a csv with the format as shown below. Now what i need to do is perform some match scenarios and append some text strings to a file. </p> <pre><code>x,classA,uniqueclassindicator1,1,125,21.8,1,5.22, x,classc,uniqueclassindicator1,3,125,21.8,2,5.22, ...
<p>You can store information keyed by column 2 in a dictionary for easy lookup; for each unique column value keep a list of entries to match against later on.</p> <p>A <code>collections.defaultdict()</code> object makes the first part easy. I'd use <code>csv.DictReader()</code> to give each column a meaningful name; i...
python|csv|python-2.7|itertools
5
5,829
54,504,138
Keras: Re-use trained weights in a new experiment
<p>I am quite new to Keras so apologies in advance for any stupid mistakes. I am currently attempting to try out some good old cross-domain transfer learning between two datasets. I have a model here that is trained and executed on a voice recognition dataset that I have generated (code is at the bottom of this questio...
<p>In short, to fine-tune Model_3 from Model_1, just call <code>model.load_weights('/path/to/model_1.h5', by_name=True)</code> after <code>model.compile(...)</code>. Of course, you must have saved the trained Model_1 first.</p> <p>If I understood correct, you have the same number of features and classes among the two ...
python|tensorflow|machine-learning|keras|neural-network
0
5,830
54,397,337
How do I make keyword shuffle on pandas
<p>I want to make longer extension keywod that <code>bale cale</code> mean the same with <code>cale bale</code>, all keyword on string</p> <p>Here's my dataset</p> <pre><code>Keyword Category_1 Category_2 Category_3 ale bale cale bale cale cale bale cale cale cale ale </code></...
<p>Use <a href="https://docs.python.org/3/library/itertools.html#itertools.permutations" rel="nofollow noreferrer"><code>itertools.permutations</code></a> with splitted values and flatten list comprehension, then join values together by space and add index value to helper <code>DataFrame</code> - <code>df1</code>. Last...
pandas|dataframe
2
5,831
71,422,719
Find and replace values in txt file with the data provided in another excel file
<p>I have an excel file like this: <a href="https://i.stack.imgur.com/ulObD.png" rel="nofollow noreferrer">Excel</a></p> <p>And another txt file like this:</p> <p>.subckt blockA vdd vss A B C Out</p> <p>xi01 vdd vss vdd vss x1 A inv cpp=64n m=1 ln=22n lp=22n nf_n=1 nf_p=1 nfin_n=4 nfin_p=4</p> <p>xi02 vdd vss vdd vss x...
<pre><code>import xlwings as xw import pandas as pd import re wb = xw.Book(r&quot;cir1.xlsx&quot;) app = wb.app app.interactive = False app.visible = False df = wb.sheets.__iter__().__next__()[&quot;A1&quot;].options(pd.DataFrame, index=False, expand=&quot;table&quot;).value PATTERN_ID = re.compile(r&quot;xi\d+&quo...
python|python-3.x|function
0
5,832
71,347,182
Color a Pandas DataFrame column based on distinct values
<p>My DataFrame looks something like this</p> <pre><code>d1 = pd.DataFrame({&quot;Country&quot;:['xx','xx','xy','xz','xz'], &quot;year&quot;:['y1','y2','y1','y1','y2'], &quot;population&quot;:[100,200,120,140,190]}) </code></pre> <p>What would be the best way to highlight all the distinct ...
<p>You can use a list of colors and make a mapping dictionary from the list of countries, then use <code>style.applymap</code>:</p> <pre><code>import matplotlib colors = dict(zip(d1['Country'].unique(), (f'background-color: {c}' for c in matplotlib.colors.cnames.values()))) d1.style.applymap(colors....
python|pandas
1
5,833
38,982,002
Using argparse or docopt for pdftk replacement
<p>I have am writing a program that accepts arguements in the following form.</p> <pre><code>SYNOPSIS pdf_form.py &lt;input PDF file | - | PROMPT&gt; [ &lt;operation&gt; &lt;operation arguments&gt; ] [ output &lt;output filename | - | PROMPT&gt; ] [ flatten ] Where: &lt;operation&gt; may be empty, or: [generat...
<p>One argument could be</p> <pre><code>parser.add_argument('-o','--output', default='-') </code></pre> <p>and later</p> <pre><code>if args.output in ['PROMPT']: ... input... </code></pre> <p>others:</p> <pre><code>parser.add_argument('--flatten', action='store_true') parser.add_argument('--fill_form', dest='f...
python|command-line-arguments|argparse|docopt
0
5,834
52,554,917
Not able to replace the string containing $ in pandas column
<p>I have a <code>dataframe</code></p> <pre><code>df = pd.DataFrame({'a':[1,2,3], 'b':[5, '12$sell', '1$sell']}) </code></pre> <p>I want to replace <strong>$sell</strong> from column b.</p> <p>So I tried <code>replace()</code> method like below</p> <pre><code>df['b'] = df['b'].str.replace("$sell","") </code></pre> ...
<p>It is regex metacharacter (end of string), escape it or add parameter <code>regex=False</code>:</p> <pre><code>df['b'] = df['b'].str.replace("\$sell","") print (df) a b 0 1 NaN 1 2 12 2 3 1 </code></pre> <hr> <pre><code>df['b'] = df['b'].str.replace("$sell","", regex=False) </code></pre> <p>If wan...
python|string|pandas|series
7
5,835
47,946,347
Python multiprocessing script partial output
<p>I am following the principles laid down in this <a href="https://stackoverflow.com/questions/6524635/writing-to-a-file-with-multiprocessing">post</a> to safely output the results which will eventually be written to a file. Unfortunately, the code only print 1 and 2, and not 3 to 6. </p> <pre><code>import os import...
<p>The error is somehow with the <code>task_done()</code> call. If you remove that one, then it works, don't ask me why (IMO that's a bug). But the way it works then is that the <code>queueIn.get(block=False)</code> call throws an exception because the queue is empty. This might be just enough for your use case, a bett...
python-3.x|multiprocessing
0
5,836
37,371,703
Python backdoor
<p>So hello everybody, Im building a python backdoor. So when I start the netcat for listener and I start the backdoor it connects and everything but when I type ipconfig for example it says "The specified file directory cannot be found" or something like that. Here is the code:</p> <pre><code>#!/usr/bin/python impor...
<h2>Try this:</h2> <p>Hope its not too much. I added a few features as well. You're godamm welcome :)</p> <pre><code>#!/usr/bin/python # Import the required librarys for the job import subprocess import socket import os # Set variables used in the script HOST = '10.0.0.98' # IP for remote connection PORT = 4444 # P...
python|remote-access
0
5,837
7,082,027
Python get selected text
<p>How would I, using Python "catch" text that a user has selecting in, for example, a web browser? The script would idle in the background, and when a certain key combination is pressed, it "gets" the text the user has selected. Think copy &amp; paste, only it copies to my application instead of a clipboard.</p> <p>T...
<ol> <li><p>Install <code>xsel</code></p> <pre><code>sudo apt-get install xclip xsel -y </code></pre></li> <li><p>Save this as <code>get-selected.py</code></p> <pre><code>import os print(os.popen('xsel').read()) </code></pre></li> <li><p>Select text</p></li> <li><p>Run</p> <pre><code>python get-selected.py </code></...
python|macos|selection|clipboard
3
5,838
16,232,257
Python striping a variable everything after - dash
<p>I have the following code.</p> <pre><code>message.gateway_message_id = parsed_response['gateway_message_id'].strip() </code></pre> <p>After this is run <code>message.gateway_message_id</code> variable contains this:</p> <pre><code>18271817281-3 </code></pre> <p><strong>I would now like to take <code>message.gate...
<p><code>str.partition</code> (or <code>str.rpartition</code> depending on which side to strip the dash) was built for this, it will also be the fastest</p> <pre><code>message.gateway_message_id.rpartition('-')[0] </code></pre> <hr> <pre><code>&gt;&gt;&gt; text = '18271817281-3' &gt;&gt;&gt; text.rpartition('-')[0] ...
python|python-2.7
4
5,839
16,524,680
Python cross-module globale variable
<p>I'm new to Python and I was trying out nose as a unit test framework. I came across a behavior I didn't expect, but maybe this is normal, hence my question.</p> <p>I have two (very basic) files:</p> <p>__init__.py:</p> <pre><code>#!/usr/bin/env python glob = 0 def setup(): global glob glob = 42 print...
<p>When you do <code>from . import glob</code> at the top of your test file, you get a reference to the value of <code>glob</code> in your namespace. This happens before you call <code>setup()</code>. When you call <code>setup()</code> the value of <code>glob</code> is updated in the <code>__init__.py</code> namespace ...
python|nose|python-import
2
5,840
31,717,903
WebDriver Wait does not work properly
<p>I'm trying not to wait until the whole page is loaded. As far as I'm concerned <code>WebDriverWait</code> should help with that so I've tried put it into my code but there is probably something that I don't know because it raises <code>TimeoutException</code> although I can see the tag.</p> <pre><code>self.driver....
<p>try this one:</p> <pre><code>self.driver.get('http://www.quoka.de/') self.wait.until(EC.presence_of_element_located((By.ID, 'search1'))) self.driver.find_element_by_id("search1").send_keys('nachhilfe') self.driver.find_element_by_id('searchbutton').click() </code></pre> <p>invisibility_of_element_located waits for...
python|html|selenium|selenium-webdriver|webdriver
0
5,841
38,902,433
TensorFlow strings: what they are and how to work with them
<p>When I read file with <code>tf.read_file</code> I get something with type <code>tf.string</code>. Documentation says only that it is "Variable length byte arrays. Each element of a Tensor is a byte array." (<a href="https://www.tensorflow.org/versions/r0.10/resources/dims_types.html" rel="noreferrer">https://www.ten...
<p>Unlike Python, where a string can be treated as a list of characters for the purposes of slicing and such, TensorFlow's <code>tf.string</code>s are indivisible values. For instance, <code>x</code> below is a <code>Tensor</code> with shape <code>(2,)</code> whose each element is a variable length string.</p> <pre><c...
python|string|numpy|tensorflow|tfrecord
20
5,842
40,411,757
Deleting cells contents of a csv file using python
<p>I have comma separated csv file like this:</p> <pre><code>A,B,C,D,E 1,4,5,6,7 9,52,12,0,7 1,5,15,6,9 </code></pre> <p>I want to delete the content of the 4th column, but not the header.</p> <p>the desired output is as following:</p> <pre><code>A,B,C,D,E 1,4,5,,4 9,52,12,,7 1,5,15,,9 </code></pre> <p>how can i d...
<p>First open your file, attach it to a csv reader object.</p> <p>Read the title by iterating manually on the <code>csv.reader</code> object (special case). Then open your output file, read the input rows, delete the 4th element and write back the rows in the output file:</p> <pre><code>import csv with open("input.c...
python|excel|csv|module
0
5,843
10,097,102
Is it possible to thread a subclass within a class?
<p>This is for a moderation bot for C&amp;C Renegade, in case anyone wants some background.</p> <p>I have a class which will act as a parent to a load of subclasses that provide IRC connections, connections to the gamelog (UDP socket), etc, and I want to know if it is possible to split some of these subclasses (notabl...
<p>It is feasible, take a look at:</p> <p><a href="http://docs.python.org/dev/library/multiprocessing.html" rel="nofollow">multiprocessing</a></p> <p>Besides the simple process forking, it also provides memory sharing - which is likely to be needed.</p>
python|multithreading|parent-child|irc|subclass
1
5,844
26,179,390
Scrapy spider_idle call to restart scrape
<p>I have a scrape setup in Scrapy that is targeting 1M unique urls in a numeric sequence. For example: <a href="http://www.foo.com/PIN=000000000001" rel="nofollow">http://www.foo.com/PIN=000000000001</a></p> <p>I hold the PINs in a DB. Rather than load 1M PINs into memory and creating 1M start_urls, I'm using the s...
<p>Instead of restarting the spider, I would query the database for <code>unscraped</code> items until there is nothing left:</p> <pre><code>class Foo(Spider): name = 'foo' allowed_domains = ['foo.com'] def start_requests(self): while True: data = self.coll.find({'status': 'unscraped'}...
python|scrapy
2
5,845
26,403,721
Python array, write a large array
<p>I have a 100*100 array in python and I used: <code>f.open(file_name)</code> and <code>f.write(matrix_name)</code> to write it in this file. Actually the matrix was written in the file but in this format:</p> <pre><code>[[ 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 8 91 1 ...
<p>To write a Numpy array to a text file, you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html#numpy.savetxt" rel="nofollow"><code>numpy.savetxt()</code></a> or the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tofile.html#numpy.ndarray.tofile" rel="no...
python|numpy
1
5,846
32,200,685
Python for merging multiple files from a directory into one single file
<p>I need a single file with many columns(=number of files in the directory), from multiple file in the directory.. Each files has unique IDs which will not change for all files and so I need to merge these files based on that id.</p> <p>For example, file_1 looks like this</p> <pre><code>id pool1 ABL1 1352 A...
<p>I found a solution ,</p> <pre><code> path = '/Pool1' files = os.listdir(path) files_txt = [os.path.join(path,i) for i in files if i.endswith('.txt_samplecount')] ## Change it into dataframe dfs = [pd.DataFrame.from_csv(x, sep='\t') for x in files_txt] ##Concatenate it merged = pd.concat(dfs, axis=1) </code></p...
python|pandas
2
5,847
27,909,019
Loading a pandas Dataframe into a sql database with Django
<p>I describe the outcome of a strategy by numerous rows. Each row contains a symbol (describing an asset), a timestamp (think of a backtest) and a price + weight. Before a strategy runs I delete all previous results from this particular strategy (I have many strategies). I then loop over all symbols and all times. </p...
<p>I don't think the first thing you should try is the raw SQL route (more on that in a bit) But I think it's because of calling <code>row.save()</code> on many objects, that operation is known to be slow.</p> <p>I'd look into <code>StrategyRow.objects.bulk_create()</code> first, <a href="https://docs.djangoproject.co...
mysql|django|pandas
1
5,848
28,357,159
write() creates empty file
<p>I want to write to a file but if I open as <code>open(file,"w")</code> it outputs a blank file, it does work with <code>open(file,"a")</code> but I don't want to append since it gets really large really fast and I just need to update the file.</p> <p>This is the code:</p> <pre><code>p1 = open("C:\\Users\\JoãoPedro...
<p>Your code should have given your IndexError for sure at the end of the while because of these</p> <pre><code>i += 1 x = x * int(Prime_list[i]) </code></pre> <p>Not to mention there is a </p> <pre><code>while (i &lt;= L_List): </code></pre> <p>which will allow one more iteration that will lead to IndexError with ...
python|python-3.x|file-io
0
5,849
44,361,448
Tensorflow 1.1 MultiRNNCell Shape Errors (Init_State related)
<p><strong><em>UPDATE</strong>: I believe strongly that the error is related to the init_state as created and fed into the tf.nn.dynamic_rnn(...) as an argument. So the question becomes, what is the correct shape of, or way to construct, an initial state for a stacked RNN?</em></p> <p>I am trying to get a MultiRNNCe...
<p>Based on Allen Lavoie's comment above, the corrected code is:</p> <pre><code>def gru_cell(state_size): cell = tf.contrib.rnn.GRUCell(state_size) return cell num_layers = 2 # &lt;--------- graph = tf.Graph() with graph.as_default(): x = tf.placeholder(tf.float32, [batch_size, num_samples], name="In...
python|tensorflow
1
5,850
32,782,462
Check if the date of a timezone is passed current time
<p>I receive time in the format <code>12:00</code> and I also have a timezone in the format <code>&lt;DstTzInfo 'Europe/Paris' PMT+0:09:00 STD&gt;</code>. I want to see, if this date is already passed current time in that timezone. </p> <p>My current timezone may be different from the timezone I receive, so I use the ...
<p>What about this:</p> <pre><code>from datetime import datetime from dateutil import tz tz = tz.gettz('Europe/Paris') now = datetime.now().replace(tzinfo=tz) d = datetime.strptime("{0}/{1}/{2} 14:39".format(now.year,now.month,now.day), "%Y/%m/%d %H:%M").replace(tzinfo=tz) print (d-now).total_seconds() </code></pre>...
python|date|datetime|timezone|pytz
0
5,851
32,633,096
BeautifulSoup error Python 3.4.3
<p>Python 3.4.3 (64 bit) Windows 7 My bs4/requests were running fine then I got all this stuff from my program bs1.py: </p> <pre><code>Traceback (most recent call last): File "&lt;frozen importlib._bootstrap&gt;", line 2218, in _find_and_load_unlocked AttributeError: 'module' object has no attribute '__path__' Durin...
<p>You have a local file named <code>html.py</code> that masks the standard library package named <code>html</code>.</p> <p>Rename the file, or delete it altogether. If you have trouble locating it, import it to print the filename:</p> <pre><code>import html; print(html.__file__) </code></pre> <p>Once out of the way...
python|python-3.x|beautifulsoup
0
5,852
14,001,259
python write lines to file avoid the newline at end of file
<p>I am processing text files with python under windows, some contents of source files like this:</p> <hr> <pre><code>FSZHB1 04 2012-11-24 1346 S000009106 BC14D01137 0 788 0 0 0 788 FSZHB1 04 2012-11-24 1425 S000009107 BC14D01587 0 1088 0 0 0 1088 FSZHB1 04 2012-11-24...
<p>You can eliminate "new line" entries at the end of sentences by ".rstrip()". There are plenty of tutorials on web about such string processing tools. "tutorialspoint.com" can be a good start.</p> <p>If you are familiar with linux and able to integrate your code with a shell script, then you can use the built-in reg...
python|text
0
5,853
27,347,391
Change window.screen.width/height in webdriver.Firefox by python
<p>For test i need change a screen resolution of browser (window.screen.*). I testing a javascript what working with browser depending on window.screen.width/height values. Can't find a solution. In side of html-page it's can do next code:</p> <pre><code>window.screen.__defineGetter__('width', function(){return 800;}...
<p>You cannot change the resolution of the screen using Selenium. You can simulate it with window size by using the <code>set_window_size</code> method:</p> <pre><code>from selenium import webdriver driver = webdriver.Firefox() driver.set_window_size(800, 600) </code></pre>
python|selenium-webdriver|screen-resolution
0
5,854
12,534,995
How to ignore or pass xpath xml IndexError in Python
<p>How can I force python to ignore <code>IndexError</code> without using <code>try</code> &amp; <code>except</code> every single value that I am extracting? </p> <p>My XML have multiple values that needed to be extracted. Some records don't have the value / at root[0], so I have to manually use <code>try</code> &amp...
<p>Test for the return value <em>before</em> trying to retrieve the first match:</p> <pre><code>a = etree.XPath('/Data/a/b/nodeA/text()')(root) if a: # do something with a[0] </code></pre> <p>Alternatively, set <code>a</code> to an empty string or the first value on a single line:</p> <pre><code>a = etree.XPath('...
python|xml|lxml
1
5,855
7,896,541
Trying to install PyCrypto on Ubuntu via Buildout, src/config.h: No such file or directory
<p>I'm trying to install PyCrypto on an Ubuntu instance via Buildout (via easy_install) and I'm getting the following error:</p> <pre><code>Getting distribution for 'pycrypto&gt;=1.9'. Running easy_install: /usr/bin/python "-S" "-c" "import sys,os;p = sys.path[:];import site;sys.path[:] = p; [sys.modules.pop(k) for...
<p>Even with the newest pycrypto I keep having this problem, so I just run <code>./configure</code> and the src/config.h is created, so now just run pip or, easy_install or, setup.py... </p>
python|ubuntu|pycrypto
2
5,856
47,343,649
Tokenize words stored in a string in Python
<p>So in my program, I have an input text file. I iterate through the list, add all the words in the list into a string called "text". Then, I use tokenizer on the string, which fails.</p> <pre><code>x = open("Tokens.txt") text = "" for line in iter(x): text += line[0:-1] + " " x.close() for i in tokenizer(text)...
<p>I do not have the reputation to comment, so I am posting as an answer. Iterating over your file (<code>for line in iter(x)</code>) is better done as <code>for line in x.readlines()</code></p>
python
0
5,857
11,636,225
Dynamic Drawing with Cairo and wxPython
<p>I'm working on a new project that is written using wxPython and Cairo in order to dynamically draw objects on a canvas. Everything works pretty well, though I'm noticing a big caveat with wxPython that I'm having a hard time working around. I'm am fairly new to wxPython, and very new to Cairo, so the answer may be o...
<p>I did as Mike Driscoll directed me to do (<a href="https://stackoverflow.com/questions/11636225/dynamic-drawing-with-cairo-and-wxpython/11659235#comment15416775_11636225">in the comment above</a>) and posted my question on both the <strong>wxPython group</strong> and the <strong>Cairo mailing list</strong>, and the ...
python|dynamic|wxpython|cairo
0
5,858
33,635,342
Guess whether word is verb with regex?
<p>I'm trying to write a code that identifies verbs in a .txt by common word endings. If a word isn't identified I want to guess with regex if a word could be a verb and let the user decide whether I'm right.</p> <p>But I'm having difficulties with this part of the code. There is an error in the first line. I don't ev...
<p>The <code>==</code> operator checks for <em>string equality</em>. It doesn't perform regex matching or any other kind of matching. In order to do this, you need a library, like the <a href="https://docs.python.org/2/library/re.html" rel="nofollow"><code>re</code></a> library.</p> <p>For example:</p> <pre><code>imp...
python|regex
1
5,859
46,946,110
How to Extract the li tag content present inside the Div tag using python selenium
<p>I am trying to get the data which is present inside the div class <strong>"credit-list linelist"</strong></p> <p>From the site</p> <p><a href="https://www.usgbc.org/rpc/LEED%20V4%20BD+C:%20HOMR/v4/1593?location=Littlefield,%20Arizona&amp;lat=36.9161976&amp;lng=-113.95254890000001" rel="nofollow noreferrer">https:/...
<p>You can either use <code>regex</code> + <code>pandas dataframe</code> or <code>string-digit-check</code> + <code>pandas dataframe</code>:</p> <pre><code>%%timeit html_list = driver.find_element_by_xpath('//*[@id="mainCol"]/div[5]/ul') items = html_list.find_elements_by_tag_name("li") a,b,c,a1,b1,c1 = [],[],[],[],[...
python|selenium
0
5,860
37,721,851
Custom xticks for multiple subplots?
<p>Using Matplotlib, I have two subplots and I want them to have the same custom string xticks.</p> <p>Here is a minimal example what I tried so far:</p> <pre><code>import matplotlib.pyplot as plt f, axs = plt.subplots(ncols=2, sharex=True) plt.xticks(range(6), [str(x)+"foo" for x in range(6)], rotation='45') for i i...
<p>If <code>sharex</code> is not principal use this code:</p> <pre><code>import matplotlib.pyplot as plt f, axs = plt.subplots(ncols=2) for i in range(2): ax = axs[i] ax.set_xticks(range(6)) ax.set_xticklabels([str(x)+"foo" for x in range(6)], rotation=45) ax.plot(range(6), range(6)) plt.show() </code>...
python|matplotlib
12
5,861
67,847,913
I don't understand what "driver.find_element_by_..." command I have to use - could someone help me?
<p>I want to investigate the following page: <a href="https://jackpot-qr.rewe.de/?c=939393938" rel="nofollow noreferrer">https://jackpot-qr.rewe.de/?c=939393938</a> and want Selenium to look, if it shows me the red error-code when you press &quot;OK&quot;.</p> <p>This is my code so far, but it never find the code (Im n...
<p>You should look into <a href="https://selenium-python.readthedocs.io/waits.html" rel="nofollow noreferrer">Explicit Waits</a></p> <p>When you click OK, the element showing the error code does not immediately appear. Thus, we need to wait until it appears before you can proceed with the rest of your code:</p> <pre cl...
python|selenium|webdriver
0
5,862
30,160,143
How to convert string with UTC offset
<p>I have date as </p> <pre><code>In [1]: a = "Sun 10 May 2015 13:34:36 -0700" </code></pre> <p>When I try to convert it using <a href="https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior" rel="nofollow"><code>strptime</code></a>, its giving error.</p> <pre><code>In [3]: datetime.strptime(a, "...
<p><strong>From the link you provided for the python doc, I found that you are using Python 2.7</strong> </p> <p>It looks as if strptime doesn't always support <code>%z</code>. Python appears to just call the <code>C</code> function, and strptime doesn't support <code>%z</code> on your platform.</p> <p><strong>Note:<...
python|datetime|strptime
3
5,863
57,256,600
How to create horizontal bar plot from nominal data?
<p>I would like to create a horizontal bar chart in python from nominal values, however, I cannot solve it by myself and I didn't find any good example on StackOverflow.</p> <p>I would like to see changes in year's rotation of two seasons (duration, beginning, ending) from the year 1983 to the year 2019.</p> <p>I hav...
<p><a href="https://jwork.org/dmelt" rel="nofollow noreferrer">DataMelt project</a> has several examples implemented in Python/Java that show how to make charts with horizontal error bars. You can look at <a href="https://jwork.org/home/popularity_of_programs_for_data_science" rel="nofollow noreferrer">this blog</a> t...
python|pandas|matplotlib|seaborn
1
5,864
27,451,582
maximum sum of adjacent path down a triangle
<p>I'm working on the following challenge:</p> <p><a href="https://www.codeeval.com/open_challenges/89/" rel="nofollow">https://www.codeeval.com/open_challenges/89/</a></p> <p>My solution:</p> <pre><code>import sys test_cases = open(sys.argv[1], 'r') sum_track=0 index_track = 0 for test in test_cases: test = tes...
<p>Consider a triangle like this:</p> <pre><code> 1 2 3 99 4 5 </code></pre> <p>Your algorithm will "greedily" follow the largest number it sees and end up finding <code>1+3+5</code>. Clearly this is not the biggest sum, as it ignores the obvious <code>99</code> in the triangle!</p>
python
3
5,865
65,907,127
Recursive function in python seems to ignore nested functions if statement
<p>I'm having some odd behaviour with a recursive function, and I can't quite figure out whats going wrong.</p> <pre><code>def setGM(): global guild_master guild_master = input('&gt;&gt;&gt; Enter your name: ').strip() # This statement is triggered by hitting enter to the guild_master input without typing any...
<p>Answered by Axe319 in a comment above:</p> <p>Python wasn't &quot;ignoring&quot; my if statement, it was actually running it twice. Once inside the recursion, and afterwords the initial function picked up where it left off without me realizing it. A return statement after the second call stopped the duplicate check....
python|python-3.x|function|recursion
0
5,866
43,303,062
Python pulp constraint
<p>I am trying to add a constraint to linear programming problem in python using <code>pulp</code> library. I tried code below.</p> <pre><code>for week in range(14,52), i in I.index: k = week model += sum(x[(i, j, week, B)] for week in range(k, k+13), j in J.index) &lt;...
<p>Or Duan's comment looks correct the syntax used should be</p> <pre><code>for week in range(14,52), i in I.index: k = week model += sum(x[(i, j, week, B)] for week in range(k, k+13) for j in J.index) &lt;= 1 </code></pre> <p>but in this case it will be much faster if you ...
python|pandas|mathematical-optimization|linear-programming|pulp
0
5,867
43,177,637
Getting "This field is required" error even though I set null=True and blank=True
<p>I have a <code>Post</code> model for users submitting posts. I've given the <code>content</code> field of <code>Post</code> an attribute of <code>blank=True</code>. But for some reason django tells me <code>content</code> is still required. <code>form_post.errors</code> prints this:</p> <pre><code>&lt;ul class="err...
<p>The reason for this, is because you're <a href="https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#overriding-the-default-fields" rel="nofollow noreferrer"><code>overriding the default model field</code></a>. Both <code>content</code> and <code>title</code>.</p> <p>Although, <code>content</code> can be...
python|django|django-forms
2
5,868
66,837,130
Compute all palindromic substrings of length ≥ 7 of a textfile
<p>Write a program that given a long string (say order 1.000.000 characters), computes all palindromic substrings of length ≥ 7, i.e. substrings spelled identical read forwards and backwards. You can use the below code to read a complete text from a file to a string, convert it to lower case, and remove everything exce...
<p>Your function will return <code>True</code> whenever the length of a word is greater or equal to 7, regardless of it being a palindrome. You can check whether the reversed version of a string is the same as the original string: <code>string[::-1] == string</code> would suffice.</p> <p>It seems to me that &quot;palin...
python|list|function|palindrome
1
5,869
4,390,942
How can I show the output of two print statements on the same line?
<p>I have 2 separate print statements:</p> <p>print "123"</p> <p>print "456"</p> <p>How can i make these 2 print statement appear on the same line? Note i need to use 2 print statements</p> <p>output:</p> <p>123456</p>
<p>In python 1.x and 2.x, a trailing comma will do what you want (with the caveat mentioned by others about the extra space inserted):</p> <pre><code>print "123", print "456" </code></pre> <p>In python 3.x — or in python 2.6-2.7 with <code>from __future__ import print_function</code> — <code>print</code> is a functio...
python
7
5,870
48,268,149
Tensorflow on Anaconda error cannot find cudnn64_6.dll
<p>I am having a problem with Tensorflow running on Spyder. When I installed it in cmd, it had the same problem that it couldn't find the path to cudnn64_6.dll, and so I added pathway to it and it seemed to import. Then, I installed the theano library and the keras and it seemed ok, then when I tried to import the kera...
<p>Its Ok I just had to get rid of some environment paths and restart. My bad</p>
tensorflow|anaconda|spyder|cudnn
-1
5,871
51,322,554
SMOTE with missing values
<p>I am trying to use SMOTE from <code>imblearn</code> package in Python, but my data has a lot of missing values and I got the following error:</p> <blockquote> <p>ValueError: Input contains NaN, infinity or a value too large for dtype('float64').</p> </blockquote> <p>I checked the parameters <a href="http://contr...
<p>SMOTE does not perform filling up your missing or NaN values. You need to fill them up and then feed for SMOTE analysis. Dealing with missing values is a different task altogether, you can take a look at <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.Imputer.html" rel="nofollow noref...
python|scikit-learn|imblearn
3
5,872
51,330,281
Sum values of column based on the unique values of another column
<p>I have a data frame of</p> <pre><code>Column1 Column2 1 20 2 25 3 30 2 40 4 18 1 24 </code></pre> <p>and I want to sum Column2 based on the unique values of Column1. We can find sum based on a specific value such as 1 using this way:</p> <pre><code>df.loc[df[...
<p>I believe you're looking for <code>groupby</code>. You can find documentation <a href="https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.DataFrame.groupby.html" rel="noreferrer">here</a></p> <pre><code>df.groupby('Column1')['Column2'].sum() Column1 Column2 1 44 2 65 3 3...
python|pandas|dataframe|sum
22
5,873
17,516,967
ImageOps.fit() with transparent parts in ICO images
<p>I have a source file <code>image.ico</code> of any size and want to create a thumbnail. This is the code i am using right now:</p> <pre><code> converted_file = cStringIO.StringIO() thumb = ImageOps.fit(image, (width, height), Image.ANTIALIAS) thumb.save(converted_file, format='png') </code></pre> <p>I c...
<p>The Problem is indeed that PIL does not know how to exactly read ICO files. There are two possibilities how to fix this:</p> <ol> <li>Add a plugin to PIL that registers the ICO format</li> <li>Use Pillow, a fork of PIL that is more frequently updated</li> </ol> <p>I chose to use Pillow which is also Python 3 compa...
python|python-imaging-library|alpha
1
5,874
50,009,055
Django Model: ValueError: Missing staticfiles manifest entry for "file_name.ext"
<p>Before you mark it as duplicate, I have read <a href="https://stackoverflow.com/questions/44160666/valueerror-missing-staticfiles-manifest-entry-for-favicon-ico">ValueError: Missing staticfiles manifest entry for 'favicon.ico' </a>, and it does not solve my problem.</p> <p>I have the following model: </p> <pre>...
<h3>Solution:</h3> <p>You can circumvent this issue and improve the code by moving the <code>static()</code> call out of the model field and changing the default value to the string <code>&quot;pledges/images/no-profile-photo.png&quot;</code>. It should look like this:</p> <p><code>avatar_url = models.URLField(default=...
python|django|django-models|django-staticfiles
5
5,875
66,482,763
Python identifying tab as a string when reading a data file
<p>so I had been trying to debug this for a long time now and can't seem to find a solution.</p> <p>Essentially, I opened a .txt file in excel as a tab delimited file in a MacOs. Then, copied and pasted the columns I wanted and created a new file. When I use readline() to read the first line in the file with my python ...
<p>line 21 should be :</p> <pre><code>var_names_list = var_names_str.split(&quot;\t&quot;) </code></pre> <p>to split at the tabs instead of including them.</p>
python-3.x|readlines
0
5,876
63,980,107
Display Azure OCR output in logic order / reading-direction
<p>I've an Azure OCR Output as result of this JSON read-script (Microsoft template code):</p> <pre><code># Extract the word bounding boxes and text. line_infos = [region[&quot;lines&quot;] for region in analysis[&quot;regions&quot;]] word_infos = [] for line in line_infos: for word_metadata in line: for wor...
<p>In your code you are already getting the line info.</p> <pre><code>line_infos = [region[&quot;lines&quot;] for region in analysis[&quot;regions&quot;]] </code></pre> <p>For instance, I have taken this <a href="https://upload.wikimedia.org/wikipedia/commons/thumb/a/af/Atomist_quote_from_Democritus.png/338px-Atomist_q...
python|json|azure|ocr
1
5,877
71,732,702
What are the base cases in this recursive BST algorithm?
<p>I have not often written recursive functions/methods. I successfully understand the &quot;base case&quot; in simpler functions such as the following:</p> <pre><code>def countdown(num): if num == 0: # Base case return print(num) # Action countdown(num-1) # Reduction and recurse def factorial(num)...
<p>For a recursive function, any state that doesn't require recursive computation can be a base case. Even if calculating the base value requires some computation (that isn't recursive), it qualifies as a base case, since it ends the recursion there.</p> <p>Similarly, any statement that does or does not do any computat...
python|algorithm|recursion|binary-search-tree
0
5,878
71,503,905
Extract all lines after word
<p>I want to extract all lines that will be printed after this marker: <code>PossibleErrs</code></p> <pre class="lang-py prettyprint-override"><code>s1 = ( ' DIMM Error Summary\r\n' ' Skt Chan Dimm Slot DimmSN KnownErrs PossibleErrs\r\n' ' 0 5 0 DIMM_F1 XD12F 0 2\r\n' ' 0 5 ...
<p>You don't need a regular expression to do this: you just need to split on the CRLFs (<code>\r\n</code>s) to get a list of lines (slicing off the first two lines and the last line), and then split each line on whitespace:</p> <pre class="lang-py prettyprint-override"><code>lines = s1.split(&quot;\r\n&quot;)[2:-1] res...
python|string
2
5,879
71,302,464
Replace NaN with column value on a row by row basis
<p>In my Pandas DataFrame I'd like to replace all instances of NaN (np.nan) on a row by row basis with the corresponding value from column &quot;E&quot;.</p> <p>This DataFrame here..</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>A</th> <th>B</th> <th>C</th> <th>D</th> <th>E</th> </tr> </t...
<p>You could transpose + <code>fillna</code> + transpose back:</p> <pre><code>df = df.T.fillna(df['E']).T.astype(int) </code></pre> <p>Output:</p> <pre><code> A B C D E 0 1 88 3 88 88 1 55 5 55 4 55 </code></pre>
python|python-3.x|pandas|dataframe
3
5,880
70,089,950
Pytest: capture logs for a specific
<p>I use pytest as my automation framework. I want to capture all the emitted logs from a specific test and store it somewhere. How do I access logs after the test is finished? Thank you</p>
<p><strong>First things first - <a href="https://docs.pytest.org/en/6.2.x/logging.html" rel="nofollow noreferrer">RTFM</a></strong></p> <p>Few things you can do right away:</p> <ul> <li>pass <code>-vvv</code> switch in the CLI</li> <li>redirect <code>stdout</code> to a file</li> <li>check out plugins like <a href="http...
python|pytest
0
5,881
59,190,621
Is there a way to draw a piechart in 3D with matplotlib or any other libarires?
<p>What I want to do is to draw multiple pie charts and layer them in z axis. So a pie chart would be on top of another one in 3D. Do you have anything I could refer to maybe using matplotlib or any other python libraries? Thanks in advance.</p>
<pre><code>from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt fig = plt.figure() ax1 = plt.axes(projection='3d') x = [4,2,5,7,8,2,9,3,7,8] y = [5,6,7,8,2,5,6,3,7,2] z = [1,2,6,3,2,7,3,3,7,2] x2 = [-1,-2,-3,-4,-5,-6,-7,-8,-9,-10] y2 = [-5,-6,-7,-8,-2,-5,-6,-3,-7,-2] z2 = [1,2,6,3,2,7,3,3,7,2] ax1...
python|matplotlib
2
5,882
58,719,479
configure function for tkinter
<p>I am trying to make a button change when it is pressed but the <code>configure</code> function when I use it returns the error:</p> <pre><code>A1.config(text="X", state="disabled", relief="SUNKEN") AttributeError: 'NoneType' object has no attribute 'config' </code></pre> <p>I also tried using <code>configure</code...
<p>You can't define a variable and place it in the same line. Try this:</p> <pre><code>A1 = Button(window, text="", width=5, height=1) A1.place(x=100, y=100) </code></pre> <p>also <code>"SUNKEN"</code> isn't valid, either do <code>"sunken"</code> or <code>SUNKEN</code></p>
python|tkinter
0
5,883
59,032,019
Python pptx - part of text in cell with different color
<p>I am using pptx module to generate slide with table. I am able to change font in each cell, but what I also need is change font of specific word in text. In example "Generating <strong>random</strong> sentence as example". In this world "random" is bold. </p> <p>Found similar case at <a href="https://stackoverflow....
<p>If you use <code>cell</code> where that example uses <code>text_frame</code> (or perhaps <code>tf</code> in that particular example) the rest of the code is the same. So to create "A sentence with a <strong>red</strong> word" where "red" appears in red color:</p> <pre><code>from docx.shared import RGBColor # ---re...
python|powerpoint|cell|python-pptx
2
5,884
25,396,898
How to set file modification time via ftp with python
<p>How to change a modification time of file via ftp?</p> <p>Any suggestions? Thanks!</p>
<p>According to <a href="https://filezilla-project.org/specs/draft-somers-ftp-mfxx-04.txt" rel="nofollow noreferrer">FileZilla</a>, the command is MFMT:</p> <p>The syntax of the MFMT command is:</p> <blockquote> <p>mfmt = "MFMT" SP time-val SP pathname CRLF</p> <p>As with all FTP commands, the "MFMT" command l...
python-2.7|ftp
2
5,885
72,307,948
find_digit is not defined in Pylance - PYTHON
<p>class TimeUtil():</p> <pre><code>def calculate_seconds(self, input): if any(x in input.lower() for x in ['weeks', 'week','wks','wk']): return (int(find_digit(self, input))*604800) elif any(x in input.lower() for x in ['days', 'day']): return (int(find_digit(self, input))*86400) el...
<p>I noticed that the way your calling <code>find_digit()</code> is like that:</p> <pre><code>find_digit(self, input) </code></pre> <p>You probably meant to write it like that:</p> <pre><code>TimeUtil.find_digit(self, input) </code></pre> <p>but you should write it like that because it's more readable:</p> <pre><code>s...
python
0
5,886
72,395,569
resample dataframe and divide values over new sample frequency
<p>How do I upsample a dataframe using resample() to get the initial values divided over the new sample frequency?</p> <p>Dataframe with monthly sample frequency</p> <pre><code> date revenue 0 2021-11-01 00:00:00+00:00 300 1 2021-10-01 00:00:00+00:00 500 2 2021-09-01 00:00:00+...
<p>You can use <code>asfreq</code> to convert the timeseries from monthly to daily frequency, then use <code>ffill</code> to forward fill the values then divide the <code>revenue</code> by <code>daysinmonth</code> attribute of <code>datetimeindex</code> to calculate distributed revenue</p> <pre><code>s = df.set_index('...
python|pandas|dataframe|resample
2
5,887
50,492,194
Python Pandas search for strings with metacharacters
<p>Currently I have a DataFrame as below:</p> <pre><code> index Name Value 0 j_smith[1] 32 1 j_smith[32] 46 2 r_lee[2] 52 3 m_brent[3] 61 4 j_perry[4] 75 5 j_perry[6] 81 6 j[3] ...
<p>Simply escape the <code>[</code> and <code>]</code> characters using <code>\</code>:</p> <pre><code>Score = DF[DF['Name'].str.contains('j_perry\[\d+\]|j\[\d+\]')] &gt;&gt;&gt; Score index Name Value 4 4 j_perry[4] 75 5 5 j_perry[6] 81 6 6 j[3] 92 7 7 ...
python|pandas
1
5,888
58,099,074
How to select rows in dataframe based on a condition
<p>I have an emails dataframe in which I have given this query:</p> <pre><code>williams = emails[emails["employee"] == "kean-s"] </code></pre> <p>This selects all the rows that have employee kean-s. Then I count the frequencies and print the top most. This is how it's done:</p> <pre><code>williams["X-Folder"].value_...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> for v...
python|pandas
1
5,889
55,224,227
Convert a column of dates from ordinal numbers to the standard date format - pandas
<p>I have to convert a column of dates from the integer/date format to the date format d-m-Y. Example:</p> <pre><code>import pandas as pd col1 = [737346, 737346, 737346, 737346, 737059, 737346] col2 = ['cod1', 'cod2', 'cod3', 'cod4', 'cod1', 'cod2'] dict = {'V1' : col1, 'V2' : col2} df = pd.DataFrame.from_dict(dict...
<p>datetime <code>fromordinal</code> should help.</p> <pre><code>import datetime as dt col1 = [737346, 737346, 737346, 737346, 737059, 737346] col2 = ['cod1', 'cod2', 'cod3', 'cod4', 'cod1', 'cod2'] dd = {'V1' : col1, 'V2' : col2} df = pd.DataFrame.from_dict(dd) df['V1'] = df['V1'].apply(dt.datetime.fromordinal) ...
python|pandas|date|integer|calculated-columns
6
5,890
54,095,509
How to merge the Time Series Panda Data Frame without loosing the row?
<h2>Heading</h2> <ol> <li>How to Merge the Time Series DataFrame without loosing rows?</li> <li>The final result DataFrame shape should based on which DataFrame have larger DataFrame shape.</li> </ol> <p>DF1:</p> <pre><code>0 17.12.2014 13:56:56 1.9 1 17.12.2014 13:56:58 ...
<p>The join method is built exactly for these types of situations. You can join any number of DataFrames together with it. The calling DataFrame joins with the index of the collection of passed DataFrames. To work with multiple DataFrames, you must put the joining columns in the index.</p> <pre><code>dfs = [df1, df2, ...
python|pandas|datetime|dataframe|time-series
1
5,891
28,740,955
Working with pathos multiprocessing tool in Python and
<p>I have some code for performing some operations using the pathos extension of the multiprocessing library. My question is how to employ a more complex worker function - in this case named <code>New_PP</code>. How should I format the thpool line to handle a dictionary that my worker function requires in order to give...
<p>There are a few issues going on here:</p> <ol> <li><p>your code above has a bunch of errors/typos.</p></li> <li><p>when you send off <code>mapp.New_PP</code>, it makes a copy of <code>mapp.New_PP</code>… so it does not share <code>access_dict</code> between instances because those instances are created and destroye...
python|multiprocessing|python-multiprocessing|pathos
0
5,892
53,774,648
KeyError: 'ifname' in convert an OpenWRT tar.gz to NetJSON
<p>I was trying to use the <code>netjsonconfig</code> command line utility and tried the convert an <code>OpenWRT tar.gz</code> to <code>NetJSON</code> and print to standard output (with 4 space indentation) utility</p> <p><code>netjsonconfig --native network --backend openwrt --method json -a indent=" "</code></p...
<p>What does <code>network</code> contain?</p> <p>The exception you're getting looks like a bug though, you shouldn't get an exception but a failure.</p> <p>Maybe is better to open an issue in <a href="https://github.com/openwisp/netjsonconfig" rel="nofollow noreferrer">https://github.com/openwisp/netjsonconfig</a></...
linux|python-2.7|ubuntu-14.04|openwrt|openwisp
0
5,893
54,871,840
Retry requests mechanism
<p>Im trying to build web <strong>scraper</strong> project one of the thing im trying to do is smart retry mechanism using urlib3 and requests and beautiful soup</p> <p>when im set the timeout=1 in order to fail the retry and check retry its break with exception code below :</p> <pre><code>import requests import re fro...
<p>I usually do something like:</p> <pre><code>def get(url, retries=3): try: r = requests.get(url) return r except ValueError as err: print(err) if retries &lt; 1: raise ValueError('No more retries!') return get(href, retries - 1) </code></pre>
python|web-scraping|beautifulsoup|python-requests|urllib3
1
5,894
38,319,785
Creating and Deleting Buckets Programmatically in Google Cloud Storage
<p>I am using Google App Engine and Google Cloud Storage. I would like to create a bucket daily using a cron job. Also, delete a bucket programmatically. I was able to manually create a bucket using the Google Cloud Console.</p> <p>How do I create/delete buckets from GAE using python? </p> <p>Also, is it a good desig...
<p>It's probably not the best idea to create a new bucket every day. There's not a lot of harm in it, but there's also no advantage, as a single bucket can grow to be pretty much as big as you might ever need. It's generally a better idea to use different buckets for logically different kinds of data.</p> <p>As far as...
python|google-app-engine|google-cloud-storage|bucket
2
5,895
34,142,924
Python PIL crop doesn't crop image
<p>I have the following function to crop an image:</p> <pre><code>def crop(original_image): original_image = Image.open(original_image) original_image.crop((25, 25, 50, 50)) #original_image.load() thumb_io = StringIO.StringIO() original_image.save(thumb_io, format='JPEG') thumb_file = InMem...
<p>change this line: </p> <pre><code> original_image = original_image.crop((25, 25, 50, 50)) </code></pre> <p>because the return value of crop function is a rect area but you don't save it! </p>
python|django|image|python-2.7|python-imaging-library
5
5,896
27,228,980
Writing a regular expression, better solutions
<p>I want to capture the two times in this string</p> <pre><code>u'11:00 a.m. - 6:00 p.m.' #ideally to ('11:00', 'a.m'), (6:00,) </code></pre> <p>Right now, I have </p> <pre><code>(\d{1,2}:\d{2})\s(\w\.\w).+(\d{1,2}:\d{2})\s(\S+) # result [u'11:00', u'a.m', u'6:00', u'p.m.'] </code></pre> <p>Which is ok, I guess. B...
<p>Why not simply split the string according to <code>-</code> and then:</p> <pre><code># first part '11:00 a.m.'.replace('a.m.', 'AM') # second part (after split you'll have it as a variable and not hardcoded) '11:00 p.m.'.replace('p.m.', 'PM') </code></pre> <p>And then simply:</p> <pre><code>datetime.strptime(fir...
python|regex
3
5,897
47,266,531
TypeError: conversion from Series to Decimal is not supported
<p>Any ideas on how to convert a series (column) from float to decimal? I am on Python 3.6. I have read the Decimal documentation, but it offers no help.</p> <pre><code>df['rate'].dtype Out[158]: dtype('float64') Decimal(df['rate']) Traceback (most recent call last): File "C:\Users\user\Anaconda3\lib\site-packages\I...
<p>You can't cast like this, you will need to do </p> <pre><code>df['rate'] = df['rate'].apply(Decimal) </code></pre> <p><code>pandas</code> does support <code>Decimal</code> but you can't cast like that</p> <p>Example:</p> <pre><code>In[28]: from decimal import * df = pd.DataFrame(np.random.randn(5,3), columns=lis...
python-3.x|pandas|numpy|decimal
10
5,898
36,231,681
How to perform os.environ join in python?
<p>I have a configuration of <code>os.environ</code> with default values (that cover 90% of my needs). I have a special application-framework-package, for example called <code>SALOME</code>, that does not provide package installation into system environment and tries to be self contained, it also requires use of specia...
<p>Let's assume you have done something like the following to serialize the environment:</p> <pre><code>import json import os with open('environ.json', 'w') as f: json.dump(dict(**os.environ), f) </code></pre> <p>You can now read those back like this (in another program)</p> <pre><code>import json import os wi...
python|python-2.7|environment-variables
9
5,899
46,327,089
How to combine 3 variables. Pretty simple
<p>I have a problem that asks me to combine three numeric variables, for example, <strong>a = 1 , b = 2 , c = 3</strong>. We're supposed to make d = ' 1|2|3 '. I've done some scripting in BASH where <strong>"|"</strong> refers to piping. How would you accomplish this in Python, and what does <strong>"|"</strong> mean?...
<p>The vertical bar is merely a character. Treat this the same way you would a comma or a dash. Convert each integer to string, and concatenate them with the bar in between. This is merely an exercise in string manipulation; nothing particularly deep or tricky.</p>
python|python-2.7|python-3.x
5