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
10,700
17,473,739
Python regex to match 2 distinct delimiters
<p>I'm trying to craft a regular expression that will match something like this:</p> <p><code>[[uid::page name|page alias]]</code></p> <p>for example:</p> <p><code>[[nw::Home|Home page]]</code></p> <p>The uid and page alias are both optional.</p> <p>I want to allow the delimiters <code>::</code> or <code>|</code> ...
<p>If I understand your needs correctly, you could use this:</p> <pre><code>\[\[(?:(?&lt;uid&gt;\w+)::)?(?!.*::)(?&lt;page&gt;[^|\t\n\r\f\v]+)(?:\|(?&lt;alias&gt;[^|\t\n\r\f\v]+))?\]\] ^^^^^^^^ </code></pre> <p>See <a href="http://www.regex101.com/r/mT4mY4" rel="nofollow">here</a> for a demo. I ...
python|regex|regex-negation
4
10,701
17,658,092
Unable to find vcvarsall.bat using Python 3.3 in Windows 8
<p>I am having an issue when I try to run:</p> <pre><code>pip install numpy </code></pre> <p>I get:</p> <pre><code>unable to find vcvarsall.bat. </code></pre> <p>I followed this procedure: <a href="https://stackoverflow.com/questions/3297254/how-to-use-mingws-gcc-compiler-when-installing-python-package-using-pip">H...
<p>As other people have already mentioned, it appears that you do not have Microsoft Visual Studio 2010 installed on your computer. Older versions of Python used Visual Studio 2008, but now the 2010 version is used. The 2010 version in particular is used to compile some of the code (not 2008, 2013, or any other version...
python|visual-studio|python-3.x|mingw|pip
11
10,702
55,869,511
groupby and join result has indices and data type included in output
<p>The objective is to take a data frame that looks like this:</p> <pre><code>keywords group word1 x word2 x word3 x </code></pre> <p>with group and keywords as strings within a pandas dataframe.</p> <p>and create a dataframe that looks like this:</p> <pre><code>x |word1|word2|word3 </cod...
<p>Use:</p> <pre><code>df.groupby('group')['keywords'].apply(lambda x: '|'+'|'.join(x)) </code></pre> <hr> <pre><code>group x |word1|word2|word3 </code></pre>
python|pandas
2
10,703
55,763,189
Passing a string to print a variable
<p>I have multiple variables with values that I like to access with the output from a string. I can get the string value but don't know how to convert the string "P2", so I can print or access the content of variable P2.</p> <p>been searching for different ways to print lists and been using for loops, but I am lost, a...
<p>Have a look at globals() and id() from built-in functions: <a href="https://docs.python.org/3/library/functions.html#built-in-functions" rel="nofollow noreferrer">https://docs.python.org/3/library/functions.html#built-in-functions</a></p> <p>Example:</p> <pre><code>def objname(obj): return [name for name, obj...
python-3.x
0
10,704
49,993,361
Creating a new 2 column numpy array from filtering through the first coumn/array
<p>I am trying to create a new 2 dimensional or 2 column array, which will consist of (data value &lt;=20000) from the first column, and their associated ID values in the second column. Mathematically I am doing the following: I am reading data from a text file. I am finding distance to all the points from the last poi...
<p>Between the question you asked, and the code you have provided, I am still somewhat unclear on what you what to accomplish. But I can at least show you where there are errors in the code, and perhaps give you the tools you need.</p> <p>As your code is now, x, y, z are all vectors. So the result of the neighbors dis...
python|arrays|numpy
1
10,705
64,954,713
Django Serializer - How to know which parameters was input wrongly
<p>I always put <code>serializers</code> in an <code>try</code> statement that returns <code>false</code> when have invalid format.</p> <p>Like this:</p> <p>Sample model:</p> <pre><code>from rest_framework import serializers class CommentSerializer(serializers.Serializer): email = serializers.EmailField() cont...
<p>You can access the <code>.errors</code>, this is a dictionary that maps the names of the fields to a list of errors:</p> <pre><code>from django.http import JsonResponse serializer = testSerializer(data=b) if not serializer.is_valid(): return JsonResponse({'errors': serializer<b>.errors</b>}, status_code=400)</...
python|django|django-serializer
1
10,706
65,234,151
I have started making a bot in discord but the bot is not sending dms to the members of the server
<p>I have been running the following code and after various changes the bot still never returns an welcome dm to the user, even after making sure that the permission to message users from the server is enabled.</p> <pre><code>import os import discord from dotenv import load_dotenv load_dotenv() TOKEN = os.getenv('DIS...
<p>You need to enable <code>dm</code> intents (there are quite a few so I suggest you enabling default intents) and <code>intents.members</code></p> <pre class="lang-py prettyprint-override"><code>intents = discord.Intents.default() intents.members = True client = discord.Client(intents=intents) </code></pre> <p>Don't...
python-3.x|discord|bots|discord.py
1
10,707
62,551,804
extracting a partially matched string in python
<p>I have a folder in which the files are all named like</p> <p>&quot;12345input789&quot;</p> <p>&quot;12345output291&quot;</p> <p>I want to find each pair of files where the start bit (&quot;12345&quot;) matches and perform some operation on both of the files</p> <pre><code>for file_name in os.listdir(directory): ...
<p>You could save all file names in two dictionaries:</p> <pre><code>inputs, outputs = {}, {} for file_name in os.listdir(directory): if &quot;input&quot; in filename: pre, _, post = filename.partition(&quot;input&quot;) inputs[pre] = filename elif &quot;output&quot; in filename: pre,...
python-3.x|string-matching
1
10,708
68,907,886
Script import errors while in another folder to main script
<p>I have a script (script 1) that imports another script (script 2) which is in a folder with the same directory as script 1. This is fine as I added <code>import [folder].[script 2]</code> However script 2 imports another script (script 3) which is in the same folder as script 2 but when I run script 1 script 2 can't...
<p>Here is some code to mimic the situation you described:</p> <pre><code># subfolder/script3.py def f3(): print(&quot;Hello&quot;) </code></pre> <pre><code># subfolder/script2.py from script3 import f3 def f2(): f3() </code></pre> <pre><code># script1_v1.py from script2 import f2 f2() ## -&gt; ModuleNotFoundEr...
python|import|directory
0
10,709
68,283,948
How can i replace a code within my pandas dataframe with a dict mapping?
<p>I have a table like below:</p> <pre><code>Group col1 col2 col3 A shop_101 shop_102 shop_104 B shop_101 shop_105 shop_108 C shop_101 shop_103 shop_109 C shop_111 shop_122 shop_104 </code></pre> <p>I also have a dict which has mappings of these e.g.:</p> <pre><code>{'group_name':...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html" rel="nofollow noreferrer"><code>DataFrame.replace</code></a> for substrings replacement values of dict with convert keys to strings:</p> <pre><code>d = {'group_name': {103: 'AUTO', 104: 'BUSINESS', 105: 'STORES'...
python-3.x|pandas|dataframe
1
10,710
54,815,883
How to detect new objects that were not there using OpenCV python?
<p>I want to make a drone that can detect objects from up. I found examples of Background Subtraction but it detects things and then considers new image as background object. I want the drone to come to it's way point and see if something new is detected. Drone will fly by itself and the image processing will be done...
<p>Background subtraction don't works on drones, a stabilized camera don't help. It need to search a homography matrix between frames with subpixel quality and create custom background subtraction algorithm. This work is not work Raspberry and Python.</p> <p>If you know anything about objects then try to use neural ne...
python|opencv|object|detection
0
10,711
54,889,342
Match a filter dict to another one - Python
<p>I have the following configuration file, it's a .yml with the following fields.</p> <pre><code>filter: mic : - 'XMAD' - 'XSTUB' cfi : - 'CF5334' </code></pre> <p>My problem is the following one.</p> <p>I am loading rows from a XML file, they have the following structure.</p> <pre><code>...
<p>You could invert the logic and search the values from row in filter under the same key, if present. Code could be (thanks to the Python <code>for ... else ...</code>):</p> <pre><code>for row in xml_file: for key, value in row.items(): if key in filter and row[key] not in filter[key]: break ...
python|filter
1
10,712
41,824,989
Walk through nodes in linked list python
<p>I'm set to do a binary tree search like the one <a href="http://www.cs.armstrong.edu/liang/animation/web/BST.html" rel="nofollow noreferrer">here</a>. I have a problem to set the nodes correctly. </p> <p>The problem: When a new node should be created, the root node seems to be overwriten. First time </p> <pre><co...
<p>Yeah you're right I screwed it up a little bit.</p> <p><pre>class Node(): def <strong>init</strong>(self): self.data = None self.left = None self.right = None</p> <p>class Bintree: def <strong>init</strong>(self): self.root = None</p> <code> def put(self, newvalue): ...
python|linked-list
2
10,713
64,496,843
Count occurrences over a period
<p>If I have a table with a column per day for a whole month with series of 1 and 0, is there a possibility to count how many groupings I have of 1?</p> <p>With this I mean, if I have <code>1 1 1 1 0 0 1 1 0 1 0 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 1 1 0 0 1</code>, is there a way to say in that month I had <code>4+2+1+3+4+2+...
<p>This should help you:</p> <pre><code>string = '1 1 1 1 0 0 1 1 0 1 0 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 1 1 0 0 1' num_lst = [int(element) for element in string.split(' ')] occurrences = 0 prev = 0 occurrences_lst = [] for num in num_lst: if num == 1: occurrences += 1 else: if occurrences != ...
python
0
10,714
70,571,517
In Python3, for Unix, we have os.sync(). What is its counterpart for windows?
<p>I am trying to handle writing, getting(through SFTP) and file management of large amount files. I see that after writing a file, I am checking for the file with os.path.exits for the file which is resulting in False. After some time around (10-15 secs), I am able to see the files present there. I am checking for the...
<p>You can use a combination of <code>f.flush()</code> and <code>os.fsync()</code>:</p> <pre><code>with open(...) as f: ... f.flush() os.fsync(f.fileno()) </code></pre>
python-3.x|windows
0
10,715
72,847,318
Is it possible to capture standard deviation from %%timeit -o?
<p>I get average time to take running function but cannot get standard deviation.</p> <pre><code>import random def average_py(n): s = 0 for i in range(n): s += random.random() return s / n n = 10_000_000 </code></pre> <pre><code>result_py = %timeit -o average_py(n) </code></pre> <blockquote> <p>670 ...
<p>It is accessible through <code>result_py.stdev</code>.</p> <pre><code>In [1]: import random ...: def average_py(n): ...: s = 0 ...: for i in range(n): ...: s += random.random() ...: return s / n ...: n = 10_000_000 In [2]: result_py = %timeit -o average_py(n) 1.37 s ± 40.5 ms p...
jupyter-notebook|ipython|jupyter-lab
1
10,716
73,194,843
If key of a dictionary is not in a list, move that key and value to a new dictionary
<p>I have a list as below:</p> <p><code>fruits_exclude = ['grapes', 'banana', 'apple']</code></p> <p>I have two dictionaries as below:</p> <p><code>fruits_have = {'apple': 3, 'banana': 4, 'mango': 5, 'grapes': 5}</code></p> <p><code>final_dict = {}</code></p> <p>I want to move the item <code>'mango': 5</code> into <cod...
<pre><code>final_dict = {key: val for (key,val) in fruits_have.items() if key not in fruits_exclude} </code></pre>
python|dictionary
1
10,717
64,868,090
Convert date to day of year without using datetime
<p>I have to return the day of the year (int) for a given string date (e.g. <em>&quot;September, 14, 2019&quot;</em>) WITHOUT using <code>datetime</code>. I also have to make it basic enough to where I can make two other similar functions for different calendars.</p> <hr /> <p>This is what I had before:</p> <pre><code>...
<p>This should achieve the desired effect. I'm making a few assumptions since you didn't specify output format or input data.</p> <pre class="lang-py prettyprint-override"><code>def day_of_year_to_date(day_of_year, year): sum_of_days = 0 for month_name, days_in_month in month_days.items(): sum_of_days +...
python|date|date-arithmetic|days
1
10,718
53,174,671
python def function and input
<p>I am trying to set up a function using input , Is this possible ?</p> <pre><code>function = input('Please enter a function example') def f(x): return function print(f(2)) </code></pre> <p>So if the function input is x**2 it should print the num 4 . I know this syntax is not right because functions is an alphanu...
<p><strong>Disclaimer</strong>: see comments, and no, you should not put this in a web page/service which people seem to assume you are writing. However for creating your toy calculator which you run locally at home, this built-in function is enough.<br> For safety, refer <a href="https://docs.python.org/3/library/ast....
python|function|math|input
-2
10,719
71,953,556
Is it possible to run two functions (one running FastAPI - ASGI, and one running Flask - WSGI), in one Azure function App?
<p>Im trying testing if its possible to run two functions in one Azure function app one running FastAPI and the other one running Flask.</p> <p>I tried to specify a different route for each <code>function.json</code> file but to no avail.</p> <pre><code># FastAPI function.json { &quot;scriptFile&quot;: &quot;__init...
<p>If you deploy using GitHub, you can run two functions in one Azure function app.</p> <ul> <li>To do this push the required code in a GitHub repository.</li> <li>Then in the azure function go to the <strong>development center</strong> section.</li> <li>Then select source as GitHub it will ask you to login and for per...
python-3.x|flask|azure-functions|fastapi
0
10,720
72,133,343
Convert a list of dictionaries (with a nested list as values) into a data frame
<p>I would really appreciate some help with this. I am extracting headings and associated list of words under each heading from a website. I have ended up with a list of dictionaries with a value list for each dictionary key:</p> <pre><code>[{'You Led a Project': &quot;['Chaired', 'Controlled', 'Coordinated', 'Executed...
<p>You can transfer the data into a list of records (rows), then construct a dataframe with <code>.from_records()</code>:</p> <pre class="lang-py prettyprint-override"><code>records = list() for elem in data: for key, value in elem.items(): for v in value: records.append([key, v]) </code></pre>...
python
0
10,721
68,860,277
Adding a python list parameter in a neo4j query
<p>I'm about to run a query in neo4j with a parameter, but it always returns me an error.</p> <pre><code>&gt; query= (&quot;MATCH (p1:Item),(p2:Item) where p1.value=$name &gt; RETURN p1.value AS from, p2.value AS to, &gt; gds.alpha.similarity.euclideanDistance((p1.embeddingNode2vec), &gt; (p2.embeddingNode2vec)) AS si...
<pre><code>MATCH (p1:Item),(p2:Item) where p1.value=$params RETURN p1.value AS from, p2.value AS to, gds.alpha.similarity.euclideanDistance((p1.embeddingNode2vec), (p2.embeddingNode2vec)) AS similarity order by similarity desc limit 40 </code></pre> <p>and then call the query execution like this:</p> <pre><code>nodes ...
python|neo4j|cypher|py2neo
1
10,722
4,846,813
Django template able to pass parameters? Getting the current user
<p>In my template, I use a method in a model as follows...</p> <p>The model is defined like this:</p> <pre><code>class Category(model.Model): title = models.CharField('title', max_length=255) description = models.TextField('description', blank=True) def pub_set(self): ... return so...
<p>I'm not 100% clear what you are asking. Inside of Category.pub_set() are you trying to access the request.user? If so, you can't do that unfortunately. There might be some sort of hack that will work, but it isn't the recommended way in Django.</p> <p>You might want to check out template tags, they will allow you t...
python|django|django-templates
1
10,723
5,188,068
building Python py2app issue on Mac
<p>I am trying to build an MacOS app using Python and py2app. The build error I get is </p> <blockquote> <p>No such file or directory: '/Library/Python/2.6/site-packages/py2app-0.5.2-py2.6.egg/py2app/bundletemplate/prebuilt/main-i386'</p> </blockquote> <p>I searched in multiple directories and files but I am unable...
<p>better use to version 0.5.3.</p> <pre><code>svn co http://svn.pythonmac.org/py2app/py2app/trunk py2app cd py2app sudo /usr/bin/python setup.py install ls /Library/Python/2.6/site-packages/py2app-0.5.3-py2.6.egg/py2app/bundletemplate/prebuilt/ main-fat main-fat3 main-i386 main-intel main-ppc ...
python|py2app
1
10,724
4,898,614
How to avoid PHP exec() by using WSGI to execute a Python script?
<p>Right now I am launching a Python script from PHP using exec() as I have to pass some dynamic variables from the website/MySQL to the command line. However, I would like to improve both the speed and the security of this operation so I thought of using WSGI. I was thinking that it might be possible to embed the Pyth...
<p>First off, can you do it all in either Python or PHP? Using multiple languages is normally seen as an anti-pattern. That's not to say it's always a bad idea, but you should be questioning why first, and only then if you're convinced it's a good idea move forward.</p> <p>As far as the specifics of what you want to...
php|python|wsgi
1
10,725
62,657,235
Prevent pyBullet from printing build time on import
<p>When I import pyBullet, it immediately prints a line with the time when it was build:</p> <pre><code>In [1]: import pybullet pybullet build time: Jun 19 2020 04:01:58 </code></pre> <p>Is there a way to prevent this?</p>
<p>Change the source code. Jokes aside, I think there is no obivious way to prevent this from happening. Since it happens when you import the module, there is not much you can do in configuration of pybullet. Because it is literally the first thing you do with it.</p> <p>Maybe you can reroute stdout during the import o...
python|pybullet
1
10,726
62,637,580
SUMY Text Summarizer fails to summarize and returns original text
<pre><code>LANGUAGE = &quot;english&quot; stemmer = Stemmer(LANGUAGE) def get_luhn_summary(text): summ = list() parser = PlaintextParser.from_string(text, Tokenizer(LANGUAGE)) summarizer = LuhnSummarizer() summarizer.stop_words = get_stop_words(LANGUAGE) for sentence i...
<p>The summarization is done by sentence count.</p> <pre><code>import nltk from sumy.parsers.plaintext import PlaintextParser from sumy.nlp.tokenizers import Tokenizer from sumy.summarizers.luhn import LuhnSummarizer as Summarizer from sumy.nlp.stemmers import Stemmer from sumy.utils import get_stop_words LANGUAGE = &...
python|text|summarization
0
10,727
62,032,239
Create tuples of (lemma, NER type) in python , Nlp problem
<p>I wrote the code below, and I made a dictionary for it, but I want Create tuples of (lemma, NER type) and Collect counts over the tuples I dont know how to do it? can you pls help me? NER type means name entity recognition</p> <pre><code>text = """ Seville. Summers in the flamboyant Andalucían capital often nudge 4...
<p>I hope the following code snippets solve your problem.</p> <pre><code>import spacy # Load English tokenizer, tagger, parser, NER and word vectors nlp = spacy.load("en_core_web_sm") text = ("Seville. Summers in the flamboyant Andalucían capital often nudge 40C, but spring is a delight, with the parks in bloom and ...
python|nlp|nltk
1
10,728
61,910,585
How to flatten a column in a pandas dataframe with a list of nested dictionaries
<p>i received single JSON's (500 JSON's) and modified it by adding them to the end of an existing list with the append() method.</p> <pre><code>d_path = r'--PATH HERE--' d_files = [f for f in listdir(d_path) if isfile(join(d_path,f))] n = num_data d_dicts=[] for counter,d_file in enumerate(d_files): with open(d_pa...
<p>You can try the following approach:</p> <pre><code>def f(x): d = {} # Each element of the dict for k,v in x.items(): # Check value type if isinstance(v,list): # If list: iter sub dict for k_s, v_s in v[0].items(): d["{}_{}".format(k, k_s)] = v_s else: d[k] = ...
python|json|pandas|normalize
4
10,729
63,330,679
pandas loc attribute behaves as not expected
<p>Could someone please explain why <code>loc</code> behaves different from what I expect?</p> <p>The code is</p> <pre><code>educated_less = df.loc[ ~df['education'].isin(['Masters', 'Bachelors', 'Doctorate'])] </code></pre> <p>It seems that <code>loc</code> should return only one column 'education' following the isin ...
<p>Because <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>.loc</code></a> indexing has two parts:</p> <pre><code>df.loc[left_part, right_part] left_part &lt;- where you define by which index to filter right_part &lt;- where you define whic...
python|pandas|dataframe|pandas-loc
0
10,730
18,050,016
Python loops through CSV, but writes header row twice
<p>I have csv files with unwanted first characters in the header row except the first column. The while loop strips the first character from the headers and writes the new header row to a new file (exit by counter). The else statement then writes the rest of the rows to the new file. The problem is the else statement b...
<p>If you only want to change the header and copy the remaining lines without change:</p> <pre><code>with open('file.csv', 'r') as src, open('file2.csv', 'w') as dst: dst.write(next(src).replace(" ", "")) # delete whitespaces from header dst.writelines(line for line in src) </code></pre> <p>If you want to...
python|csv|python-2.7
1
10,731
60,769,583
How to round predictions
<p>When I use cross-validation in sklearn, it returns me an RMSE value. The RMSE value is calculated by the root mean square of the predicted y value(for example, 7.11) - the real y value( for example, 6). I want to calculate RMSE by using the root mean square of the rounded predicted y value(for example, round(7.11) =...
<p>In that case you can first round your predicted y value. To round it to the nearest number you can use np.round(), to round it to the next number you can use np.ceil(), or to round it to. The previous number you can use np.floor().</p> <p>And then you can calculate your rmse value .</p> <pre><code>y_pred=model.pre...
python|numpy|scikit-learn
2
10,732
61,004,751
How can I get change_data compare yesterday and today using python from JSON data?
<p>I have the following code but don't know how to write the formula for change_data so I have included it in quotes below.</p> <pre><code>import json with open('data.kospi', 'r') as f: data = json.load(f) loaded_data = data time_series_data = loaded_data["Time Series (Daily)"] temp = "^KS11" for date, date_...
<pre><code>from dateutil.parser import parse import pandas as pd import json with open ('data.kospi') as f: data = json.load(f) time_series_data = data["Time Series (Daily)"] temp = "^KS11" for date, date_data in time_series_data.items(): formatted_date = date.replace("-","") low_data = date_data["...
python|json
0
10,733
66,083,720
Programming a Discord bot in Python- How do I make a mute command?
<p>I'm trying to make a mute command for my bot, here's my code:</p> <pre><code>@client.command(pass_context = True) async def mute(ctx, member: discord.Member): role = discord.utils.get(member.guild.roles, name='Muted') await client.add_roles(member, role) embed=discord.Embed(title=&quot;User Muted!&quot;, descr...
<p>As you can see in the error, <a href="https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot" rel="nofollow noreferrer"><code>discord.ext.commands.Bot</code></a> object has no attribute <code>add_roles</code>, but <a href="https://discordpy.readthedocs.io/en/latest/api.html#discord...
python|discord.py
3
10,734
69,126,725
Proportional sampling and assign treatment group via Python for N times
<p>In a hypothetical pandas Dataframe I have two types of fruits (ie. apple and orange. Column &quot;fruitType&quot;). Inside the apple category, I have 10 items and inside the orange category, I have 5 items. Please check out the screenshot below.</p> <p><a href="https://i.stack.imgur.com/6BO6T.png" rel="nofollow nore...
<pre><code>import pandas as pd import numpy as np import time data = {'fruitName': ['fuji apple', 'gala apple', 'green apple', 'red apple', 'blue apple', 'black apple','pink apple','brown apple','old apple','ripe apple','mandarin orange', 'dark orange', 'ugly orange', 'beautiful orange','sour orange'], 'fruitW...
python|arrays|pandas|numpy|sampling
0
10,735
68,891,655
How to avoid losing data when using "outer" in pandas merging?
<p>I'm working with two dataframes in pandas that look like those bellow (the ones i'm using have more columns, though):</p> <pre><code>&gt;&gt;&gt; df_download date | app_name | downloads | app_id __________________________________________________________ 0 2021-01-01 | music app | 5...
<p>You lost anything, your <code>merge</code> function (almost) works:</p> <pre><code>out = pd.merge(df_active_users, df_downloads, on=['date', 'app_id', 'app_name'], how='outer') </code></pre> <pre><code>&gt;&gt;&gt; out date app_name active_users app_id downloads 0 2...
python|pandas|dataframe|merge
1
10,736
68,028,415
How to get fingerprints using cv2 in Python?
<p>What would you recommend me in order to get a better fingerprints extraction? I doesn't look so well. Thank you. Here's my code:</p> <pre><code>import cv2 import numpy as np img = cv2.imread(&quot;huella.jpg&quot;) img = cv2.resize(img, None, fx=0.7, fy=1.0, interpolation=cv2.INTER_AREA) w, h = img.shape[:2] fp = c...
<p>You need to use morphological operation.</p> <p>First. Try to use <code>cv2.dilate()</code> and then <code>cv2.erode()</code>. This should remove all small and far object.</p> <p>You can see full documentation here.</p> <p><a href="https://opencv24-python-tutorials.readthedocs.io/en/latest/py_tutorials/py_imgproc/py...
python|image|cv2
2
10,737
68,386,530
Why is skimage.euler_number gives me euler number of 1, but according to the formula it should give me 2
<pre><code>import numpy as np from skimage.measure import euler_number n = 7 cube = np.zeros((n, n, n), dtype=int) cube[1:6,1:6,1:6] = 1 #creates a cube of 5x5 euler_no = euler_number(cube) </code></pre> <p>'This is giving me o/p as 1 but according to the formula euler_number = F + V − E it should give me 2 as number o...
<p>It looks like skimage does this wrong. The <a href="https://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.euler_number" rel="nofollow noreferrer">documentation</a> states:</p> <blockquote> <p>For 3D objects, the Euler number is obtained as the number of objects plus the number of holes, minus th...
python|image-processing|shapes
0
10,738
59,050,023
How to drop duplicates index of dataframes, which are in list form?
<p>I have a list where every element is Dataframe itself. And theses Dfs have duplicate date time index. I want to remove every duplicate index for every Df in that list.</p> <pre><code> list_dfs = [df_1, df_2, df_3, df_4] dtype='datetime64[ns]' #Index of all Dfs in list_dfs </code></pre> <p>I am Using this list co...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.duplicated.html" rel="nofollow noreferrer"><code>Index.duplicated</code></a> with filtering by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean in...
python|pandas|indexing|duplicates
1
10,739
59,398,271
How to open videos which has .mpg format, in python
<p>I am doing object tracking on my videos which are in .mpg format what i am doing is i am using OpenCV to track the objects but i am facing some while opening it in my code i have attached my code. </p> <pre><code>import cv2 import sys (major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.') if __name__...
<p>POSSIBLY WRONG PATH Check if Stroll.mpg is in right there in your working directory. If yes try with an .mp4 video. Most probably the path is wrong or file name Is misspelled. Refer: <a href="https://answers.opencv.org/question/1965/cv2videocapture-cannot-read-from-file/" rel="nofollow noreferrer">https://answers.op...
python|opencv|video|tracking
1
10,740
59,400,827
I am trying to round a nested string that has both string and int
<p>I have tried newlist= is list i want to round but without the string but i m having troubles putting the string in their right place since its nested list.</p> <pre><code>numerosArredondados = [[round(val, 2) for val in sublst] for sublst in newList] </code></pre> <p>is there a way to get that to work while ignori...
<pre><code>[[round(val, 2) if isinstance(val, (int, float)) else val for val in sublst] for sublst in newList] </code></pre> <p>works many thanks to @Tomerikoo</p>
python-3.x
0
10,741
59,044,473
Not able to exit the loop in python
<p>I am very new to Python and trying to execute below code. The program is to calculate compound interest.</p> <p>I created basic program and passed values as argument and it worked. Later I created user input program and it worked.</p> <p>Now when I tried to handle negative or 0 values I am not able to exit program...
<p>maybe try <code>import sys</code> and then use <code>sys.exit()</code> .</p>
python
0
10,742
72,979,676
how to execute root command inside non-root process running inside docker container
<p>I have a docker container running which start up few daemon processes post run with normal user (say with non-root privileges) id. The process which was running with normal user has to create some files and directories under /dev inside the container by calling python function which executes <code>os.system('mkdir -...
<p>You should give /dev directory a permission to write files for your non-root user.</p>
python-3.x|docker
-1
10,743
62,342,328
Casting string to ArrayType(DoubleType) pyspark dataframe
<p>I have a dataframe in spark with the following schema: schema: </p> <pre><code>StructType(List(StructField(id,StringType,true), StructField(daily_id,StringType,true), StructField(activity,StringType,true))) </code></pre> <p>Column activity is a String, sample content:</p> <p><strong>{1.33,0.567,1.897,0,0.78}</str...
<p>A simple approach (without regex) using Spark SQL:</p> <pre><code>df2=(df1 .withColumn('col1',expr(&quot;&quot;&quot; transform( split( substring(activity,2,length(activity)-2),','), x-&gt;DOUBLE(x)) &quot;&quot;&quot;)) ) </code></pre>
python|arrays|dataframe|apache-spark|casting
0
10,744
62,261,228
Reading Gmail inbox using Gmail API and service account credentials
<p>My goal is to have a script on my server to check the inbox of a specific Gmail account and when new emails come in, respond to them. </p> <p>There are many examples of code using OAuth2, however, I don't want to use that since I need to work without GUI and I only need to authorise it for one Gmail account owned b...
<p>Service accounts only work with Gsuite gmail accounts. You will need the domain admin to <a href="https://developers.google.com/gmail/api/guides/delegate_settings" rel="nofollow noreferrer">enable domain wide</a> authorization to your service account to allow it to send and check emails on behalf of the owner of th...
python|authentication|gmail|gmail-api
3
10,745
58,640,848
How to send JSON value to FullCalendar and show event in calendar
<pre><code>0: Title: "start" description: "yes" end: 1609286400000 id: 210 name: "xyz" start: 1609286400000 </code></pre> <p>this is array I want to show in Full Calendar.</p> <p>Here is code of javascript</p> <pre><code>$('#calendar').fullCalendar({ // ... your code events: { url: "/appointments/get...
<p>If you need to do some custom processing of the event data after it's downloaded then you need to use the events-as-a-function pattern as described <a href="https://fullcalendar.io/docs/v1/events-function" rel="nofollow noreferrer">in the documentation</a>. You are then provided with a callback function which you us...
javascript|python|json|fullcalendar|fullcalendar-1
0
10,746
58,751,172
top 10 most frequent wordlengths in a list of words
<p>I am writing a function that returns the top 10 most frequent word lengths in a file called wordlist.txt that contains all words starting from a to z. I have wrote a function (named 'value_length') that returns a list of each word's length inside a certain list. I also applied the Counter module in a dictionary (tha...
<p>There's no need to store the lengths in a list, or to use the list's <code>count</code> method; you've imported <code>Counter</code> already, so just use that to do the counting.</p> <pre class="lang-py prettyprint-override"><code>c = Counter() for word in seq: length = len(word) c[length] += 1 </code></pre...
python
0
10,747
73,378,230
Why is self.kill() not removing the object from the group?
<p>I've asked this question a while ago but the answers weren't entirely helpful and I don't believe I posted a minimum reproducible example. I'm trying to kill my bullet after some time (self.lifetime) has passed. The self.kill() command is executed, but it does not remove the bullet from the camera group, which is wh...
<p>The problem has to do with the <a href="https://docs.python.org/3/tutorial/classes.html#multiple-inheritance" rel="nofollow noreferrer">Multiple Inheritance</a>. Each * <code>Bullet</code> has 2 base classes which are derived from <code>pygame.sprite.Sprite</code> So each <code>Bullet</code> actually consists of 2 s...
python|pygame
0
10,748
15,887,413
pop() method in python lists doesn't work properly
<p>When I execute the following code in Python 2.7.3:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- class A(object): def __init__(self): self.s = [] class B(object): def __init__(self): self.a = A() class C(object): def __init__(self): self.b = B() c = C() pr...
<p>you should not modify a list as you iterate it! </p> <p>try </p> <pre><code>for _ in range(len(c.b.a.s)): c.b.a.s.pop() </code></pre> <p>instead</p>
python|list|built-in
4
10,749
59,712,275
pandas read_csv skip rows of unwanted descriptions and blank lines till the real data part
<p>I have many csv files and want to read in. I want to skip the beginning rows till the line begins with real data. My files happen to begin with certain string like "OPQ" or "BST". The files look like:</p> <pre><code>"This is a new record. There are some missing data. The test condition is 60 degree" OPQ , 11 ,...
<p>You should be able to do this in the following manner -</p> <pre><code>my_cols = ["A", "B", "C", "D", "E"] #You will need to add all column names here since your data is not uniform df = pd.read_csv("YOUR_CSV_HERE.csv", names=my_cols, engine='python') start_val= "OPQ" start_index = df.A[df.A == start_val].index....
python|pandas
3
10,750
49,167,705
Is there any explanation for Token keyword in value of Authorization header?
<p>Using jupyterhub 0.8.1. while making Rest-Api calls to Jupyterhub (for user/services and Servers management in Jupyterhub) we need to provide Authorization headers with Value </p> <p>e.g. "token e9f6bdea27b5e3d2bs906ad1de0d2739"</p> <p>e.g. of header</p> <pre><code>Authorization: token e9f6bdea27b5e3d2bs906ad1de0...
<p><code>The Authorization: &lt;type&gt; &lt;credentials&gt;</code> pattern was introduced by the W3C in HTTP 1.0, and has been reused in many places since. Many web servers support multiple methods of authorization. In those cases sending just the token isn't sufficient.</p> <p>Sites that use the</p> <p>Authorizatio...
python|rest|jupyter-notebook|tornado|jupyterhub
1
10,751
25,062,999
Should python mix-in classes inherit only from object?
<p>I have a mix-in class called <code>WithAutoNumbering</code> for classes that need a special numbering of a given attribute. Appart from that I have a nice class mix-in called <code>WithIndexing</code> for those classes that need indexing capabilities... which needs the capabilities of <code>WithAutoNumbering</code>....
<p>The issue with making a choice about what your mixins inherit from is that your choice will affect the final MRO of classes which use those mixins. </p> <blockquote> <p>should <code>WithIndexing</code> inherit from WithAutoNumbering</p> </blockquote> <p>As you say, <code>WithIndexing</code> uses <code>WithAutoNu...
python|inheritance|multiple-inheritance|mixins
1
10,752
70,848,444
Best fit curve (polynomial) on scatter plot with bokeh
<p>I have created a scatter plot with bokeh. I want to generate a best fit polynomial curve on the data, and superimpose the curve on the cloud of points.</p> <p>I have generated a 2nd degree polyline with <code>polyfit</code>:</p> <pre><code>import numpy as np from bokeh.plotting import figure, output_file, show mode...
<p>As mentioned in the comments, <a href="https://docs.bokeh.org/en/latest/docs/reference/plotting/figure.html?highlight=line#bokeh.plotting.Figure.line" rel="nofollow noreferrer"><code>graph.line()</code></a> adds a line plot. Now, we just need an evenly spaced x-range over which we plot the fitted function:</p> <pre>...
python|bokeh
3
10,753
3,061,924
How to get the level of the logging record in a custom logging.Handler in Python?
<p>I would like to make custom logger methods either by a custom logging handlers or a custom logger class and dispatch the logging records to different targets.</p> <p>For example:</p> <pre><code>log = logging.getLogger('application') log.progress('time remaining %d sec' % i) custom method for logging to: ...
<p><code>record</code> is an instance of <a href="http://docs.python.org/library/logging.html?highlight=logging.handler#logging.LogRecord" rel="noreferrer">LogRecord</a>:</p> <pre><code>&gt;&gt;&gt; import logging &gt;&gt;&gt; rec = logging.LogRecord('bob', 1, 'foo', 23, 'ciao', (), False) </code></pre> <p>and your m...
python|logging
12
10,754
3,085,263
Create an utf-8 csv file in Python
<p>I can't create an utf-8 csv file in Python.</p> <p>I'm trying to read it's docs, and in the <a href="http://docs.python.org/library/csv.html#csv-examples" rel="noreferrer">examples section</a>, it says:</p> <blockquote> <p>For all other encodings the following UnicodeReader and UnicodeWriter classes can be u...
<p>You don't have to use <code>codecs.open</code>; <code>UnicodeWriter</code> takes Unicode input and takes care of encoding everything into UTF-8. When <code>UnicodeWriter</code> writes into the file handle you passed to it, everything is already in UTF-8 encoding (therefore it works with a normal file you opened with...
python|encoding|utf-8|csv
14
10,755
42,754,690
DataFrame Multiple Column Comparison using LAMBDA
<p>I have a dataframe which contain some integer values, I want to create a new dataframe of the row only if multiple columns [col1, col3, col4] are not ALL zeroes. Example:</p> <pre><code> col1 col2 col3 col4 col5 col6 0 0 text1 3 0 22 0 1 9 text2 ...
<p>There's no need for any custom function at all. We can just select the columns we want, do our boolean comparison, and then use that to index into your dataframe:</p> <pre><code>In [28]: df[["col1", "col3", "col4"]] == 0 Out[28]: col1 col3 col4 0 True False True 1 False False False 2 True True...
python-2.7|numpy|lambda
1
10,756
66,566,499
Why doesn't DRF enforce non-empty field?
<p>I am using a custom user model:</p> <pre class="lang-py prettyprint-override"><code>from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): username = models.CharField(max_length=120, unique=True, blank=False, v...
<p>Unfortunately, <code>blank=False</code> is not enforced on the database level, it is only checked when you're validating model in your code, which is not happening by itself when calling <code>save()</code> on it. You need to invoke <code>clean_fields</code> at least before saving the model.</p> <p>Read about valida...
python-3.x|django|django-rest-framework
0
10,757
66,343,958
Importing data from an API and exporting it into MySQL database using Python
<p>I am trying to import JSON data from an API and export it into my MySQL database by using a Python script. I am getting this error in my code:</p> <pre><code>pymysql.err.OperationalError: (1136, &quot;Column count doesn't match value count at row 1&quot;) </code></pre> <p>So I was looking at similar articles on Stac...
<p>So, what you have to do is build up your query along with your value list. For example:</p> <pre><code># some test data I made up package_json = [ { 'cdc_case_earliest_dt' : 'a', 'cdc_report_dt' : 'b', 'pos_spec_dt' : 'c', 'onset_dt' : 'd', ...
python|mysql|json
0
10,758
72,141,155
How to create a list of all elements present in a single cell of a dataframe?
<p>Let say I have a dataframe:</p> <p><img src="https://i.stack.imgur.com/gxymX.png" alt="dataframe snapshot" /></p> <p>now i want list of the elements present in the column <code>NAME</code></p> <p>like this:</p> <pre><code>['s', 'a', 'c', 'h', 'i', 'n'] </code></pre> <p>how can we do this in pyspark?</p> <p>doing thi...
<p>You should be able to just split on the space.</p> <pre><code>from pyspark.sql.functions import split df = spark.createDataFrame([(1, &quot;s a c h i n&quot;)],[&quot;id&quot;, &quot;name&quot;]) df.withColumn('split_name', split('name', ' ')).show() </code></pre> <p>Output</p> <pre><code>+---+-----------+----------...
python|list|pyspark
1
10,759
72,280,433
Can't install Flask-WTF
<p>Ok so i wanted to get into Flask-WTF but whatever I would try I just can't seem to install it.I'm trying to learn it from a course , in the requirements.txt file i've already added the Flask==2.0.3' 'itsdangerous==2.1.0' 'flask and it doesnt seem to work. Pip installs dont work , the cmd doesnt work and I do not kno...
<p>your term is not recognized. you should setting environment variable thing, look Environement Variables in Advanced system setting. add the path <strong>anaconda</strong></p>
python|flask|installation|pip
0
10,760
3,607,001
Create a new array from numpy array based on the conditions from a list
<p>Suppose that I have an array defined by:</p> <pre><code>data = np.array([('a1v1', 'a2v1', 'a3v1', 'a4v1', 'a5v1'), ('a1v1', 'a2v1', 'a3v1', 'a4v2', 'a5v1'), ('a1v3', 'a2v1', 'a3v1', 'a4v1', 'a5v2'), ('a1v2', 'a2v2', 'a3v1', 'a4v1', 'a5v2'), ('a1v2', 'a2v3', 'a3v2', 'a4v1', 'a5v2'), ...
<p>If I'm understanding you correctly, you want to list the entire row, where a given tuple of columns is equal to some value. In that case, this should be what you want, though it's a bit verbose and obscure:</p> <pre><code>test_cols = data[['a1', 'a4']] test_vals = np.array(('a1v1', 'a4v1'), test_cols.dtype) data[t...
python|arrays|numpy|recarray
1
10,761
3,798,386
Write MP3 in Python
<p>I have a bunch of frames (generated by a function) that I want to write to a MP3 file using Python. I tried using <code>pymedia</code> but I always get a Segmentation fault.</p> <p>Doe anyone know an extension to write MP3 files using Python?</p> <p>Thanks!</p>
<p>If you're on Gnome, <a href="http://soundconverter.org/" rel="nofollow">soundconverter</a> might help; but I don't know of a stand-alone equivalent.</p>
python|file|mp3
2
10,762
26,757,207
Google App Engine & Polymer | Configuration
<p>I'm developing a web application on Google App Engine using Python, I understand how to use basically the app.yaml and manage the different files; now I'd like to upgrade my application and use <a href="https://www.polymer-project.org/" rel="nofollow">Polymer</a>. The root folder has this configuration:</p> <ul> <l...
<p>There isn't really anything to configure here. These are all static files, exactly the same as the files you have under /assets: so you should point to them in the same way you do with the assets paths.</p>
python|google-app-engine|polymer|app.yaml
4
10,763
26,442,015
Why import specific sub-packages in Python when the entire package has already been imported?
<p>I am not a Python programmer, but I read a lot of Python scripts that import sub-packages from whole packages already imported.</p> <p>For example:</p> <pre><code> import multiprocessing from multiprocessing import Process </code></pre> <p>What exactly is the purpose of importing Process specifically when its ...
<p>It makes the namespace/module accessible.</p> <p>Then you can write :</p> <pre><code>p = Process(target=f, args=('bob',)) p.start() p.join() </code></pre> <p>Otherwise, if you had not used the line <code>from multiprocessing import Process</code>, you would have written:</p> <pre><code>p = multiprocessin...
python
2
10,764
64,785,905
Why is check_password_hash function returning false? Using Flask, SQLite3 and Werkzeug
<p>I am trying to create a basic login function using Flask, Werkzeug and SQLite. The users are able to register and a hash of their password is stored in a SQLite database, though when I try to login using the correct password the check_password_hash returns false.</p> <p>Currently I am comparing the password provide...
<p>Aha! Solved it. Syntax error, pwhash` is a tuple because that is what fetchone() returns, so it need to be check_password_hash(pwhash[0], request.form.get(&quot;password&quot;)) Thank you so much for the support. It hadn't occurred to me to test the check_password_hash function in isolation, doing that made me reali...
python|flask|werkzeug
0
10,765
57,797,101
Fast lookup in large datasets using python
<p>I am processing the human genome and have ~10 million SNPs (identified by a "SNP_ID") in a single patient. I have two reference TSV's which contain rows, each row contains a SNP_ID and a floating point number (as well as lots of other metadata), it is all in ASCII format. These reference TSV's are 300-500GB in size....
<p>Your data size is large enough that you should not be working with data structures in memory. Instead, consider using a relational database system. You can start with <a href="https://docs.python.org/3/library/sqlite3.html" rel="nofollow noreferrer">sqlite</a>, which comes bundled with Python.</p> <p><a href="https...
python|bigdata
0
10,766
58,122,199
Regular Expression failing in REGEXP_EXTRACT within the read_gbq function
<p>I’m failing to successfully execute a Regular Expression function (i.e., REGEXP_EXTRACT) within the read_gbq function. </p> <p>The read_gbq is sourced from the pandas_gbq module. </p> <p>The import statement in my Python program is: from pandas_gbq import read_gbq. </p> <p>The version of pandas-gbq in my environ...
<p>If <code>co.jsonPayload.response</code> is a valid JSON string, you could use <code>JSON_EXTRACT_SCALAR(co.jsonPayload.response, '$.customerOrderId')</code>.</p>
python|regex|google-bigquery|escaping
1
10,767
18,419,657
Dataframe Merge in Pandas
<p>For some reason, I cannot get this merge to work correctly.</p> <p>This Dataframe (rspars) has 2,000+ rows...</p> <pre><code> rsparid f1mult f2mult f3mult 0 1 0.318 0.636 0.810 1 2 0.348 0.703 0.893 2 3 0.384 0.777 0.000 3 4 0.296 0.590 0.911 4 ...
<p>The <code>NaN</code>s mean they have no values in <code>rsparid</code> in common. This can be tricky when merging things that may look the same when they <code>repr</code></p> <p>The repr of small <code>DataFrames</code> with strings (of integers) or integers looks the same and no <code>dtype</code> information is ...
python|pandas
4
10,768
69,539,748
Assign point to closest polygon
<p>I have this situation in which I want to detect elements that ought to be contained on the boundary of a geometrical feature, but because of a variety of reason these point-wise objects can be &quot;seen&quot; within or outside the geometry. The within part is not an issue since I wish to use &quot;contains&quot; as...
<p>So, I found a way to answer my question. There might be something better than that and I would be grateful for an answer that makes mine seem cumbersome.</p> <p>The idea is to create a buffer zone around the polygons in such a way that points will be absorded by the buffered poygon, then <code>sjoin</code> BUT keepi...
geopandas
0
10,769
55,185,944
How do I iterate through nested dictionaries in a list of dictionaries?
<p>Still new to Python and need a little help here. I've found some answers for iterating through a list of dictionaries but not for nested dictionaries in a list of dictionaries. </p> <p>Here is the a rough structure of a single dictionary within the dictionary list</p> <pre><code>[{ 'a':'1', 'b':'2', 'c':'3', 'd':{...
<p>Following the ducktype style encouraged with Python, just guess everything has a <code>.values</code> member, and catch it if they do not:</p> <pre><code>import ujson as json with open('test.json', 'r') as f: json_text = f.read() dict_list = json.loads(json_text) for dic in dict_list: for val in dic.valu...
python|json
5
10,770
57,728,158
How do I install caffe on debian with pip3?
<p>I am trying to do <strong>pip3 install caffe</strong>, but I am getting this on Ubuntu x64 machine:</p> <pre><code>Exception: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/lib/python3/dist-packages/p...
<p>Caffe should be installed on Ubuntu/Debian via <strong>apt-get install cafe-cpu</strong> or <strong>apt-get install cafe-gpu</strong>.</p>
python-3.x|pip|caffe
0
10,771
57,613,390
Finding out key for minimum value of dictionary
<pre><code>scores = {5: 35044.51299744237, 25: 29016.41319191076, 50: 27405.930473214907, 100: 27282.50803885739, 250: 27893.822225701646, 500: 29454.18598068598} </code></pre> <p>Scores is a dict I have defined and now I want to find out the key, for the minimum value in the dictionary, which should return me 100.</p...
<p>From the <a href="https://docs.python.org/3/howto/sorting.html#key-functions" rel="nofollow noreferrer">docs</a> provided by Patrick</p> <blockquote> <p>The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes.</p> </blockquote> <p>So basicall...
python|python-3.x
1
10,772
58,259,517
How to install pocketsphinx 0.1.15 on ubuntu 16.04
<p>I tried to install pocketsphinx 0.1.15 on my ubuntu machine ubuntu16.04 .I used the command <code>pip install pocketsphinx</code> but it is throwing me error .I have added the error here. <a href="https://pastebin.com/raw/3125YWKF" rel="nofollow noreferrer">https://pastebin.com/raw/3125YWKF</a>. Can anyone help me t...
<p>The following line in the output reveals the culprit:</p> <blockquote> <p>deps/sphinxbase/src/libsphinxad/ad_pulse.c:44:30: fatal error: pulse/pulseaudio.h: No such file or directory</p> </blockquote> <p>Looks like you need to install the <code>libpulse-dev</code> package to get this header file.</p>
python|ubuntu-16.04
0
10,773
58,451,477
How to optimise the code considering different input sizes?
<p>I would like to calculate steam properties in most efficient way considering scalar, vector and matrix as two-argument input options. What I am bothered with is that I have to use if blocks with respect to the size of input (scalar, vector or matrix) making the code pretty long. I am simple mechanical engineer quite...
<p>You really do only one calculation, but in two different ways. You can pull it out and apply it to whatever the function gets as input using the built-in <code>map</code>. If that fails, then you have a single (non-iterable) value and you apply your calculation directly.</p> <pre><code># Define a dummy func to make...
python|python-3.x|performance|optimization
0
10,774
65,065,447
How to detect lines in a football field using OpenCV
<p>I am trying to detect lines in a football field video, but unfortunately I can't get it to work with my pictures. <a href="https://i.stack.imgur.com/ApQFp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ApQFp.png" alt="Original picture" /></a></p> <p>I am using Canny to detect edges, then Hough Li...
<p>Here's the solution code in Python:</p> <pre><code>import cv2 from matplotlib import pyplot as plt import numpy im = cv2.imread(&quot;foot.png&quot;) B = im[:,:,2] Y = 255-B thresh = cv2.adaptiveThreshold(Y,255,cv2.ADAPTIVE_THRESH_MEAN_C,\ cv2.THRESH_BINARY_INV,35,5) contours, hierarchy = cv2.findCont...
python|opencv|image-processing|hough-transform
1
10,775
65,289,421
How to iterate through Tuple<List<String>> in Python
<pre><code>class App: def filter(*input): result = [] print(type(input)) for arrayOfColors in input: print(type(arrayOfColors)) goodColors = getGoodColors(arrayOfColors) result.add(goodColors) return result def getGoodColors(arrayOfColors): se...
<p>You can see the problem if you add <code>print(input)</code> right under <code>def filter(*input):</code>; you'll see</p> <pre><code>(&lt;__main__.App object at 0x00000211E39C0A48&gt;, ['blue', 'red'], ['gray', 'blue']) </code></pre> <p>That is the result of <code>self</code> in every class. You can avoid it in your...
python
0
10,776
45,289,482
How to plot int to datetime on x axis using seaborn?
<p>I am trying to use seaborn to plot a graph</p> <pre><code>sns.lmplot(x=&quot;when_start&quot;, y=&quot;how_long&quot;,hue= 'state', data=apps_pd.loc[(apps_pd['user'] == 'xavi')],lowess=True); </code></pre> <p>Where <em><strong>apps_pd</strong></em> is a dataframe. And fileds in <em><strong>apps_pd['when_s...
<p>First of all when you post data post it in text format not image.</p> <p>You can convert col <code>when_start</code> to date time format as follow:</p> <pre><code>apps_pd['when_start'] = pd.to_datetime(apps_pd['when_start'], unit='ms') </code></pre> <p>However scatter plot which is one of calls of <a href="https:...
python|pandas|matplotlib|seaborn
11
10,777
7,011,291
How to get a single result from a SQL query in python?
<p>Is there an elegant way of getting a single result from an SQLite SELECT query when using Python?</p> <p>for example:</p> <pre><code>conn = sqlite3.connect('db_path.db') cursor=conn.cursor() cursor.execute(&quot;SELECT MAX(value) FROM table&quot;) for row in cursor: for elem in row: maxVal = elem </code...
<p>I think you're looking for <a href="http://docs.python.org/library/sqlite3.html#sqlite3.Cursor.fetchone" rel="noreferrer">Cursor.fetchone()</a> :</p> <pre><code>cursor.fetchone()[0] </code></pre>
python|sql|sqlite|python-db-api
83
10,778
57,257,180
Should I use a SQLite database or Pandas for my application
<p>I have a user installable application the takes a 2-5 MB JSON file and then queries the data for metrics. It will pull metrics like the number of unique items, or the number of items with a field set to a certain value, etc. Sometimes, it pulls metrics that are more tabular like returning all items with certain pr...
<p>You are comparing a database to an in-memory processing library. They are two seperate ideas. Do you need persistent storage over multiple runs of code? Use SQLite (since you're using metrics I would guess this is the path you need). You could use Pandas to write CSV's/TSV's and use those as permanent storage but yo...
python|json|pandas|sqlite
1
10,779
57,285,705
How to replace text among numbers within object feature
<p>I have an object feature "Year-Of-Publication" which I'd like to convert into numeric type. The feature contains values like 2009, 2018, 1995, ... DK-Something, ... I think I need to find all strings within the feature and replace them with some default, but I don't know how to do that practically.</p> <p>I've trie...
<p>Use <code>pandas.to_numeric</code> with <code>fillna</code>:</p> <pre><code>import pandas as pd s = pd.Series([2009, 2018, 1995, 'DK-Something']) pd.to_numeric(s, 'coerce').fillna(-1, downcast = 'infer') </code></pre> <p>Output:</p> <pre><code>0 2009 1 2018 2 1995 3 -1 dtype: int64 </code></pre> <...
python|pandas|numpy
1
10,780
57,240,608
TypeError: 'coroutine' object is not callable
<p>Im trying to get my bot to create a server (guild) and im having the issue of it saying its not awaiting even though i made it await.</p> <p>ive tried awaiting it</p> <pre class="lang-py prettyprint-override"><code>import discord, random, string, asyncio from discord.ext import commands def randomString(stringLen...
<p>You're trying to use <a href="https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.create_guild" rel="nofollow noreferrer"><code>Client.create_guild</code></a> as a decorator, which it is not. </p> <p>Your code is equivalent to </p> <pre><code>async def temp(): await client.create_guild(randomStr...
python|async-await|discord.py|coroutine
0
10,781
61,753,878
MySQL python connector UPDATE error: check right syntax to use near %s. What is going wrong?
<p>this should be relatively quick and easy:</p> <p>When I run this in my python IDE</p> <p><code>mycursor.executemany("UPDATE table42 SET date = %s ", [('2020-05-11')])</code></p> <p>For some reason it is getting completely tripped up at the string placeholder (%s). The reason I am using executemany is because soon...
<p>There needs to be a comma after the date string, so that the list is a list of tuples (it's commas that create tuples, not the parentheses).</p> <pre><code>mycursor.executemany("UPDATE table42 SET date = %s ", [('2020-05-11',)]) </code></pre> <p>This is because the <a href="https://www.python.org/dev/peps/pep-0249...
python|mysql|mariadb|mysql-python
1
10,782
61,993,565
Count the number of nodes in a linked list recursively
<p>Problem: Return the number of nodes in the linked list.</p> <p>I am learning recursion recently. I know how to use iteration to solve this problem but I am stick by the recursion way. The following is my code and it always return 1 instead of the real count of the linked list. I cannot figure out the problem and ho...
<p>Recursion is a poor choice for this sort of thing (adds overhead and risks blowing the call stack for no good reason), but if you do use it for educational purposes, it's easiest to pass the total up the call stack, not down:</p> <pre><code>def linked_list_len(head): return linked_list_len(head.next) + 1 if head...
python|recursion|linked-list
4
10,783
23,916,585
Clean list of strings that are included on the own strings
<p>I have a text-file, <code>lists.txt</code>, that looks like this:</p> <pre><code>HI family what are u doing ? HI Family what are Channel 5 is very cheap Channel 5 is Channel 5 is very Pokemon The best Pokemon is Pikachu </code></pre> <p>I want to clean it up, removing any lines that are completely included inside ...
<p>If I understand your question correctly, you want to take a list of strings and remove from it any strings that are substrings of other strings in the list.</p> <p>In pseudo-code,</p> <pre><code>outer: for string s in l for string s2 in l if s substringOf s2 continue outer print s </cod...
python|string|bash|list|shell
7
10,784
23,804,064
Using Or Clause in PostgreSQL to search for a specific record
<p>I am trying to create a search record scenario in my module. I have been using Or clause with PostgreSQL . The scenario is that I have 7-8 fields in my module. I want to search for the product from the details given in the fields. My python code is below:</p> <pre><code>cr.execute("select pt.id,pt.name from product...
<p>What about using <code>and</code> and <code>like</code> operators?</p> <pre><code>cr.execute("select pt.id,pt.name from product_template pt inner join product_product pp on pt.id=pp.id where (pp.radio_phone like'%"+str(radio_phone)+"' and pp.person_phone like '%"+str(person_phone)+"' and pp.phone_num_phone like '%"...
python|sql|postgresql
0
10,785
20,448,568
Having some trouble converting a tk PhotoImage back to a PIL image to save
<p>I'm working on a program that will convert an image to grayscale, or invert the colors. It's using different algorithms for grayscale and most everything is working fine but I have a couple of problems that I've been trying to overcome. One issue I have is trying to save the image out. So that I could handle differe...
<p>Remove <code>pic = Image.open(tkPic2)</code> in <code>saveImage()</code> </p> <p>To save file use:</p> <pre><code>def saveImage(): global pic toSave = filedialog.asksaveasfile(mode='w',defaultextension='.jpg') pic.save(toSave) </code></pre> <hr> <p><strong>BTW:</strong> for object better use <code>No...
python-3.x|tkinter|python-imaging-library
3
10,786
15,210,704
Ignore imaginary roots in sympy
<p>I'm using sympy to solve a polynomial:</p> <pre><code>x = Symbol('x') y = solve(int(row["scaleA"])*x**3 + int(row["scaleB"])*x**2 + int(row["scaleC"])*x + int(row["scaleD"]), x) </code></pre> <p>y is a list of possible solutions. However, I need to ignore the imaginary ones and only use the real solutions. Also, I...
<p>If you set <code>x</code> to be real, SymPy will only give you the real solutions</p> <pre><code>x = Symbol('x', real=True) solve(..., x) </code></pre>
python|math|sympy
14
10,787
15,263,789
Using extend correctly?
<pre><code>class BTNode(object): &quot;&quot;&quot;A node in a binary tree.&quot;&quot;&quot; def __init__(self, item, left=None, right=None): &quot;&quot;&quot;(BTNode, object, BTNode, BTNode) -&gt; NoneType Initialize this node to store item and have children left and right, as well as depth 0. &quot...
<p>You do not need to explicitly declare empty list if you want to recursively solve this problem. Just aggregate each sub-problem's result.</p> <p>Here is my approach:</p> <pre><code>def leaves_and_internals(self): if not self.left and not self.right: #leaf.append(self.item) return ([], [self.it...
python|list|tree|extend
1
10,788
29,548,574
How to validate Google reCAPTCHA v2 in django
<p>I have been trying to use the Google reCAPTCHA on a website that I've been making. The captcha loads on the webpage but I've been unable to validate it using several methods. I've tried the recaptcha validation using the method given at <a href="https://stackoverflow.com/questions/1440239/how-to-use-python-plugin-re...
<p>Here is a simple example to verify Google reCAPTCHA v2 within Django view using <code>requests</code> library (<a href="http://docs.python-requests.org/en/latest/" rel="noreferrer">http://docs.python-requests.org/en/latest/</a>):</p> <pre><code>import requests from django.conf import settings def get_client_ip(req...
python|django|validation|recaptcha
27
10,789
29,371,494
spss: rename a variable label
<p>I have a list of variable labels I would like to capitalize them</p> <p>(i.e.) Variable label.</p> <pre><code> L0K3V "PROBLÈME AVEC VOS ENFANTS" PK34 "QUEL ÂGE AVIEZ-VOUS?" ML9KL "RÉPONDANT A-T'IL DÉJA ÉTÉ LÉGALEMENT MARIÉ(E)" ... </code></pre> <p>program</p> <pre><code>BEGIN PROGRAM PYTHON...
<p>1) You have an error suggesting Submit cannot be used from within a Dataset.</p> <p>2) <a href="http://www-01.ibm.com/support/knowledgecenter/SSLVMB_21.0.0/com.ibm.spss.statistics.help/syn_variable_labels.htm" rel="nofollow">VARIABLE LABEL</a> is the correct command to relabel a variable.</p> <p>Here is a simplifi...
python|spss
2
10,790
29,782,358
Python 2.x - Why are strings contained a list not encoded in output?
<p>When I run this python script:</p> <pre><code>#!/usr/bin/env python # coding: windows-1250 lst = ['č'] s = 'č' print lst print s </code></pre> <p>I get this output:</p> <pre><code>['\xc4\x8d'] č </code></pre> <p>Why do they look different?</p>
<h1>Theory</h1> <p><code>print s</code> calls <code>s.__str__()</code>, which returns an encoded string.</p> <p>However, <code>print lst</code> calls <code>lst.__str__()</code> which in turn calls <code>__repr__()</code> on the members of the list. Unlike <code>__str__</code>, <code>__repr__</code> which does <strong...
python|encoding
4
10,791
46,245,643
WebSocket connection between reactjs Client and flask-socketio Server doesn't open
<p>In my project I am using a React front-end and a Flask server with a RESTful API. The basic functionality is that the front-end fetches data from the server and displays it. This works fine, but I figured I'd improve upon it by making the client automatically re-fetch whenever the server receives new data from elsew...
<p>You are confusing Socket.IO with WebSocket. The Socket.IO protocol is built on top of WebSocket and HTTP. Your connection failures result from you using a plain WebSocket client to connect to a Socket.IO server. You need to use a Socket.IO client, like <a href="https://github.com/socketio/socket.io-client" rel="nore...
javascript|python|reactjs|websocket|flask-socketio
9
10,792
49,427,239
Unable to install pip with easy_install
<p>I'm trying to install <code>pip</code> with:</p> <pre><code>$ sudo easy_install pip </code></pre> <p>Getting this error:</p> <pre><code>Searching for pip Reading https://pypi.python.org/simple/pip/ Couldn't find index page for 'pip' (maybe misspelled?) Scanning index of all packages (this may take a while) Readin...
<p>Why not follow the official doc?</p> <blockquote> <p>To install pip, securely download get-pip.py. <a href="https://bootstrap.pypa.io/get-pip.py" rel="nofollow noreferrer" title="pip file">2</a></p> <p>Then run the following:</p> </blockquote> <pre><code>$ python get-pip.py </code></pre> <p>from <a href="https://pip...
python|macos|pip
3
10,793
53,595,927
Count the number of cells with red text in excel file using xlrd in python
<p>I am using xlrd to open an excel file in my computer and I have numbers in red, numbers in black, I want to count the number of numbers in red, do anyone have any idea how to approach this?</p> <pre><code>import xlrd filename = "data.xls" book = xlrd.open_workbook(filenmae, formatting_info = True) </code></pre>
<pre><code>import xlrd filename = 'data.xls' book = xlrd.open_workbook(filename, formatting_info=True) sheet = book.sheet_by_index(0) max_row = sheet.nrows max_col = sheet.ncols count = 0 for row in range(max_row): for col in range(max_col): cell = sheet.cell(row, col) frmt = book.xf_list[cell.xf_i...
python|xlrd
0
10,794
45,966,023
calling an object with inheritance in python
<p>First things first, I'm reasonably new to python, but I have been working hard and doing lots of tutorials and sample projects to get better, so, if I'm missing something obvious, I appologize.</p> <p>I've been trying to figure this out for a while now, and I've done a number of searches here and through the google...
<ol> <li>You need to call the parent class's constructor <code>Super1.__init__(self)</code></li> <li>You also need to allow <code>Sub1</code> to take the arguments for the parent class's constructor.</li> </ol> <p>With the modifications above, your code becomes:</p> <pre><code>class Sub1(Super1): def __init__(sel...
python|inheritance|composition
3
10,795
55,065,396
How to split a string using any word from a list of word
<p>How to split a string using any word from a list of word</p> <p>I have a list of string <code>l = ['IV', 'IX', 'XL', 'XC', 'CD', 'CM']</code> </p> <p>I need to split for example 'XCVI' based on this list like <code>'XC-V-I'</code></p>
<p>Here's one solution but I'm not sure if it's the best way to do that:</p> <pre><code>def split(s, l): tokens = [] i = 0 while i &lt; len(s): if s[i:i+2] in l: tokens.append(s[i:i+2]) i += 2 else: tokens.append(s[i]) i += 1 return '-'.jo...
python-3.x
1
10,796
33,431,039
Flask: Set header on static files
<p>I've got the following flask route which serves static content:</p> <pre><code>@app.route('/static/&lt;path:path&gt;') @resourceDecorator def getStaticFile(path): return send_from_directory('static', path) </code></pre> <p><code>@resourceDecorator</code> is declared as follows:</p> <pre><code>def resourceDeco...
<p>For static files, flask sets the default cache timeout to 12 hours/43200s hence your problem. You can change the default cache timeout in <code>send_from_directory</code> by passing the <code>cache_timeout</code> value directly since it uses the <a href="http://flask.pocoo.org/docs/1.0/api/#flask.send_file" rel="nof...
python|flask
1
10,797
21,581,724
syntax for new ExpectedCondition class in Selenium webdriver python
<p>I am using selenium webdriver with python. I would like to create an explicit wait for a popup window to appear. Unfortunately, the common methods of the EC module do not include a ready-made solution for this problem. Searching many other posts, I gather that I have to write my own EC condition, with <code>.until(...
<p>If you want to wait for arbitrary conditions, you don't have to use <code>ExpectedCondition</code> at all. You can just pass a function to the <code>until</code> method:</p> <pre><code>from selenium.webdriver.support.ui import WebDriverWait def condition(driver): ret = False # ... # Actual code to chec...
python|selenium|selenium-webdriver
5
10,798
24,509,285
Django: How to modify the value of a Model attribute
<p>Say I have a Django <code>Person</code> model connected to a sqlite3 database:</p> <blockquote> <pre><code>class Person(models.Model): name = models.CharField(max_length=128) def __unicode__(self): return self.name </code></pre> </blockquote> <p>Then I create an instance</p> <blockquote> <pre><co...
<p>You have to save your change :</p> <pre><code>person = Person.objects.get(pk=1) person.name = "Alfred" person.save() </code></pre>
python|django|sqlite
3
10,799
38,461,366
Multiple lookup_fields for django rest framework
<p>I have multiple API which historically work using <code>id</code> as the lookup field:</p> <pre><code>/api/organization/10 </code></pre> <p>I have a frontend consuming those api.</p> <p>I'm building a new interface and for some reasons, I would like to use a slug instead an id:</p> <pre><code>/api/organization/my-or...
<p>Try this</p> <pre><code>from django.db.models import Q import operator from functools import reduce from django.shortcuts import get_object_or_404 class MultipleFieldLookupMixin(object): def get_object(self): queryset = self.get_queryset() # Get the base queryset queryset = self.filt...
python|django|rest|django-rest-framework
11