content
stringlengths 85
101k
| title
stringlengths 0
150
| question
stringlengths 15
48k
| answers
list | answers_scores
list | non_answers
list | non_answers_scores
list | tags
list | name
stringlengths 35
137
|
|---|---|---|---|---|---|---|---|---|
Q:
Node.js: ECONNRESET when making multipart/form-data post request?
I am getting the following error:
(node:12268) [https://github.com/node-fetch/node-fetch/issues/1167] DeprecationWarning: form-data doesn't follow the spec and requires special treatment. Use alternative package
(Use `node --trace-deprecation ...` to show where the warning was created)
FetchError: request to https://api.nordigen.com/v2/report failed, reason: socket hang up
at ClientRequest.<anonymous> (file:///home/doejohn/www/work/johndoe/backend/Scripts/nordigen-scripts/node_modules/node-fetch/src/index.js:108:11)
at ClientRequest.emit (node:events:539:35)
at TLSSocket.socketCloseListener (node:_http_client:427:11)
at TLSSocket.emit (node:events:539:35)
at node:net:709:12
at TCP.done (node:_tls_wrap:582:7) {
type: 'system',
errno: 'ECONNRESET',
code: 'ECONNRESET',
erroredSysCall: undefined
}
When I do the following request:
const data = new FormData();
data.append("input", file);
const init = {
method: "POST",
headers: {
Authorization: `Bearer ${oauthToken}`,
},
body: data,
};
fetch("https://api.nordigen.com/v2/report", init)
.then((res) => res.json())
I got it working perfectly with Python. But somehow when converting it to Node.js I seem to be doing something wrong.
resReport = requests.post("https://api.nordigen.com/v2/report", files={'input': open('test2.json', 'rb')}, headers={"Authorization": f"Bearer {token}"})
The file input at node.js and python are same file on disk. I also checked the auth token and it is correct.
The docs at the API have the following curl request as example:
curl -X POST \
-H 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
-F input=@example.json \
https://api.nordigen.com/v2/report
How to solve this?
A:
Adding the following solved the issues.
data.append(
'input',
fs.createReadStream(`./data/transactions_${process.env.GEBRUIKER}.json`)
)
A:
replace:
const data = new FormData();
with:
const data = new URLSearchParams();
|
Node.js: ECONNRESET when making multipart/form-data post request?
|
I am getting the following error:
(node:12268) [https://github.com/node-fetch/node-fetch/issues/1167] DeprecationWarning: form-data doesn't follow the spec and requires special treatment. Use alternative package
(Use `node --trace-deprecation ...` to show where the warning was created)
FetchError: request to https://api.nordigen.com/v2/report failed, reason: socket hang up
at ClientRequest.<anonymous> (file:///home/doejohn/www/work/johndoe/backend/Scripts/nordigen-scripts/node_modules/node-fetch/src/index.js:108:11)
at ClientRequest.emit (node:events:539:35)
at TLSSocket.socketCloseListener (node:_http_client:427:11)
at TLSSocket.emit (node:events:539:35)
at node:net:709:12
at TCP.done (node:_tls_wrap:582:7) {
type: 'system',
errno: 'ECONNRESET',
code: 'ECONNRESET',
erroredSysCall: undefined
}
When I do the following request:
const data = new FormData();
data.append("input", file);
const init = {
method: "POST",
headers: {
Authorization: `Bearer ${oauthToken}`,
},
body: data,
};
fetch("https://api.nordigen.com/v2/report", init)
.then((res) => res.json())
I got it working perfectly with Python. But somehow when converting it to Node.js I seem to be doing something wrong.
resReport = requests.post("https://api.nordigen.com/v2/report", files={'input': open('test2.json', 'rb')}, headers={"Authorization": f"Bearer {token}"})
The file input at node.js and python are same file on disk. I also checked the auth token and it is correct.
The docs at the API have the following curl request as example:
curl -X POST \
-H 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
-F input=@example.json \
https://api.nordigen.com/v2/report
How to solve this?
|
[
"Adding the following solved the issues.\ndata.append(\n'input',\nfs.createReadStream(`./data/transactions_${process.env.GEBRUIKER}.json`)\n)\n\n",
"replace:\nconst data = new FormData();\n\nwith:\nconst data = new URLSearchParams();\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"fetch",
"http",
"javascript",
"node.js",
"python"
] |
stackoverflow_0071709706_fetch_http_javascript_node.js_python.txt
|
Q:
how do I find a curve fit model is good for the data?
I have a 2D array and I am trying to fit a curve on the data. my objective function is a polynomial function:
def objective(x, a, b, c):
return a * x + b * x**2 + c
I used curve_fit from scipy.optimize to find the suitable curve for the data. But, I need to know how much this model is good. what is the difference between actual data and estimated curve?
how can I find this? dose curve_fit use mean square error to find the curve? how can I control this difference?
A:
You are better off using np.polynomial.polynomial.polyfit` to do polynomial fits.
A:
According to the documentation of curve_fit, setting the input argument full_output to True, the function returns some additional information about the optimization; in particular, the function returns a dictionary (infodict) with an entry fvec, that contains the residuals (y - y_star) evaluated at the solution. Moreover, the default method used for the optimization is the least squares, if applicable (look at the method argument).
So, if you want to know the error of the fitted function, you can use those information:
from scipy.optimize import curve_fit
import numpy as np
def objective(x, a, b, c):
return a * x + b * x**2 + c
x = np.arange(-10, 10, 1)
data = objective(x, 1, 2, 3) + np.random.normal(0, 10, (len(x),))
potp, pcov, info, msg, ier = curve_fit(objective, x, data, full_output=True, method='lm')
y_hat = objective(x, *potp.tolist())
# residuals are in the entry 'fvec' of the info dict.
# These are the residuals evaluated at the solution, i.e., f(x) - data
# Compute sum of squared residuals
err = np.dot(info['fvec'], info['fvec'])
This is the plot representing the original data and the interpolation in the previous code
Moreover, the documentation states that curve_fit uses leastsq as optimization method if bounds are not provided; in particular, it tries to minimize the sum of squares of an error function. If bounds are provided or the number of observations is less than the number of variables, curve_fit uses least_squares; least_square solves a bounded nonlinear least-squares problem.
|
how do I find a curve fit model is good for the data?
|
I have a 2D array and I am trying to fit a curve on the data. my objective function is a polynomial function:
def objective(x, a, b, c):
return a * x + b * x**2 + c
I used curve_fit from scipy.optimize to find the suitable curve for the data. But, I need to know how much this model is good. what is the difference between actual data and estimated curve?
how can I find this? dose curve_fit use mean square error to find the curve? how can I control this difference?
|
[
"You are better off using np.polynomial.polynomial.polyfit` to do polynomial fits.\n",
"According to the documentation of curve_fit, setting the input argument full_output to True, the function returns some additional information about the optimization; in particular, the function returns a dictionary (infodict) with an entry fvec, that contains the residuals (y - y_star) evaluated at the solution. Moreover, the default method used for the optimization is the least squares, if applicable (look at the method argument).\nSo, if you want to know the error of the fitted function, you can use those information:\nfrom scipy.optimize import curve_fit\nimport numpy as np\n\ndef objective(x, a, b, c):\n return a * x + b * x**2 + c\n\nx = np.arange(-10, 10, 1)\ndata = objective(x, 1, 2, 3) + np.random.normal(0, 10, (len(x),))\n\npotp, pcov, info, msg, ier = curve_fit(objective, x, data, full_output=True, method='lm')\ny_hat = objective(x, *potp.tolist())\n\n# residuals are in the entry 'fvec' of the info dict.\n# These are the residuals evaluated at the solution, i.e., f(x) - data\n# Compute sum of squared residuals\nerr = np.dot(info['fvec'], info['fvec'])\n\nThis is the plot representing the original data and the interpolation in the previous code\n\nMoreover, the documentation states that curve_fit uses leastsq as optimization method if bounds are not provided; in particular, it tries to minimize the sum of squares of an error function. If bounds are provided or the number of observations is less than the number of variables, curve_fit uses least_squares; least_square solves a bounded nonlinear least-squares problem.\n"
] |
[
0,
0
] |
[] |
[] |
[
"curve_fitting",
"optimization",
"python",
"python_3.x",
"scipy"
] |
stackoverflow_0074483555_curve_fitting_optimization_python_python_3.x_scipy.txt
|
Q:
Python library to convert between SI unit prefixes
I'm looking for a python library which comes with support to convert numbers between various SI prefixes, for example, kilo to pico, nano to giga and so on.What would you recommend?
A:
I ported a simple function (original C version written by
Jukka “Yucca” Korpela) to Python for formatting numbers according to SI standards. I use it often, for example, to set tick labels on plots, etc.
You can install it with:
pip install si-prefix
The source is available on GitHub.
Example usage:
from si_prefix import si_format
print si_format(.5)
# 500.0m (default precision is 1)
print si_format(.01331, precision=2)
# 13.31m
print si_format(1331, precision=2)
# 1.33k
print si_format(1331, precision=0)
# 1k
A:
Dictionaries
If you don't want to use any 3rd-party library like the ones listed below, you can actually implement your own parsing function.
Use a dictionary to match up the prefixes to their values. I've done it for you already:
_prefix = {'y': 1e-24, # yocto
'z': 1e-21, # zepto
'a': 1e-18, # atto
'f': 1e-15, # femto
'p': 1e-12, # pico
'n': 1e-9, # nano
'u': 1e-6, # micro
'm': 1e-3, # mili
'c': 1e-2, # centi
'd': 1e-1, # deci
'k': 1e3, # kilo
'M': 1e6, # mega
'G': 1e9, # giga
'T': 1e12, # tera
'P': 1e15, # peta
'E': 1e18, # exa
'Z': 1e21, # zetta
'Y': 1e24, # yotta
}
Then you can use regex (as described by my answer here) to search or parse the input and use the dictionary for getting the appropriate value.
Unum
Unum is well finished and thoroughly documented library.
Pros:
allows you to define arbitrary units (magnitude only supports user-defined units as long as they are a combination of the base units).
Cons:
doesn't handle prefixes well
clutters your namespace with all its unit definitions (you end up with variables named M, S etc. in your namespace)
Magnitude
You can also use Magnitude, another library. It supports all the kinds of SI unit prefixes you're talking about, plus it'll handle the parsing as well. From the site:
A physical quantity is a number with a unit, like 10 km/h. Units are specified as strings. They can be any of the SI units, plus a bunch of non-SI, bits, dollars, and any combination of them. They can include the standard SI prefixes.
...
All standard prefixes are understood, from yocto to yotta and from kibi to exbi.
A:
QuantiPhy is a new package that converts to and from numbers with SI scale factors. It is often a better choice that the unit packages such as Unum and Magnitude that are heavier and focused on the units rather than the scale factors.
QuantiPhy provides Quantity, which is an object that combines a number with its unit of measure (the units are optional). When creating a quantity you can use SI unit prefixes. Once you have a Quantity you can use it in expressions, where it acts as a float. Or you can convert it to a string, in which case it uses the SI unit prefixes by default.
>>> from quantiphy import Quantity
# convert strings to quantities
>>> duration = Quantity('0.12 ks')
>>> print(duration)
120 s
# convert to other units when rendering to a string
>>> print(duration.render(scale='min'))
2 min
# quantities act like floats in expressions
>>> rate = 1/duration
>>> print(rate)
0.008333333333333333
# convert floats to quantities
>>> rate = Quantity(rate, 'Hz')
>>> print(rate)
8.3333 mHz
# can be used in format strings
>>> print(f'Duration = {duration:<12.3} Rate = {rate}')
Duration = 120 s Rate = 8.3333 mHz
By default QuantiPhy uses the natural prefix when rendering to a string, which is probably what you want. But you can force it to render to a specific prefix using scaling:
>>> mass = Quantity('1000 g')
>>> print(mass)
1 kg
>>> print(mass.render(show_si=False))
1e3 g
>>> print(mass.render(show_si=False, scale=(1e-12, 'pg')))
1e9 pg
In this case you must turn off SI unit prefixes to avoid getting multiple prefixes: '1 npg'.
A more natural example might be where you are converting units:
>>> l = Quantity('2um')
>>> print(l.render(scale='Å'))
20 kÅ
>>> print(f'{l:sÅ}')
20 kÅ
The last example shows that you can place your desired units in the format string after the type and the conversion will be done for you automatically.
A:
I don't know if this is the best answer but it is working in my case. Feel free to verify my solution. I am working for first time with Python and constructive criticism is welcome... along with positive feedback :D
This is my code:
class Units:
def __init__(self):
global si;
si = {
-18 : {'multiplier' : 10 ** 18, 'prefix' : 'a'},
-17 : {'multiplier' : 10 ** 18, 'prefix' : 'a'},
-16 : {'multiplier' : 10 ** 18, 'prefix' : 'a'},
-15 : {'multiplier' : 10 ** 15, 'prefix' : 'f'},
-14 : {'multiplier' : 10 ** 15, 'prefix' : 'f'},
-13 : {'multiplier' : 10 ** 15, 'prefix' : 'f'},
-12 : {'multiplier' : 10 ** 12, 'prefix' : 'p'},
-11 : {'multiplier' : 10 ** 12, 'prefix' : 'p'},
-10 : {'multiplier' : 10 ** 12, 'prefix' : 'p'},
-9 : {'multiplier' : 10 ** 9, 'prefix' : 'n'},
-8 : {'multiplier' : 10 ** 9, 'prefix' : 'n'},
-7 : {'multiplier' : 10 ** 9, 'prefix' : 'n'},
-6 : {'multiplier' : 10 ** 6, 'prefix' : 'u'},
-5 : {'multiplier' : 10 ** 6, 'prefix' : 'u'},
-4 : {'multiplier' : 10 ** 6, 'prefix' : 'u'},
-3 : {'multiplier' : 10 ** 3, 'prefix' : 'm'},
-2 : {'multiplier' : 10 ** 2, 'prefix' : 'c'},
-1 : {'multiplier' : 10 ** 1, 'prefix' : 'd'},
0 : {'multiplier' : 1, 'prefix' : ''},
1 : {'multiplier' : 10 ** 1, 'prefix' : 'da'},
2 : {'multiplier' : 10 ** 3, 'prefix' : 'k'},
3 : {'multiplier' : 10 ** 3, 'prefix' : 'k'},
4 : {'multiplier' : 10 ** 3, 'prefix' : 'k'},
5 : {'multiplier' : 10 ** 3, 'prefix' : 'k'},
6 : {'multiplier' : 10 ** 6, 'prefix' : 'M'},
7 : {'multiplier' : 10 ** 6, 'prefix' : 'M'},
8 : {'multiplier' : 10 ** 6, 'prefix' : 'M'},
9 : {'multiplier' : 10 ** 9, 'prefix' : 'G'},
10 : {'multiplier' : 10 ** 9, 'prefix' : 'G'},
11 : {'multiplier' : 10 ** 9, 'prefix' : 'G'},
12 : {'multiplier' : 10 ** 12, 'prefix' : 'T'},
13 : {'multiplier' : 10 ** 12, 'prefix' : 'T'},
14 : {'multiplier' : 10 ** 12, 'prefix' : 'T'},
15 : {'multiplier' : 10 ** 15, 'prefix' : 'P'},
16 : {'multiplier' : 10 ** 15, 'prefix' : 'P'},
17 : {'multiplier' : 10 ** 15, 'prefix' : 'P'},
18 : {'multiplier' : 10 ** 18, 'prefix' : 'E'},
}
def convert(self, number):
# Checking if its negative or positive
if number < 0:
negative = True;
else:
negative = False;
# if its negative converting to positive (math.log()....)
if negative:
number = number - (number*2);
# Taking the exponent
exponent = int(math.log10(number));
# Checking if it was negative converting it back to negative
if negative:
number = number - (number*2);
# If the exponent is smaler than 0 dividing the exponent with -1
if exponent < 0:
exponent = exponent-1;
return [number * si[exponent]['multiplier'], si[exponent]['prefix']];
# If the exponent bigger than 0 just return it
elif exponent > 0:
return [number / si[exponent]['multiplier'], si[exponent]['prefix']];
# If the exponent is 0 than return only the value
elif exponent == 0:
return [number, ''];
And this is how it works:
c1 = +1.189404E-010
fres = -4.07237500000000E+007;
ls = +1.943596E-005;
units = sci.Units();
rValue, rPrefix = units.convert(c1);
print rValue;
print rPrefix;
print units.convert(fres);
print units.convert(ls);
And the response is:
118.9404
p
[-40.72375, 'M']
[19.435959999999998, 'u']
I don't know if anyone will find this helpful or not. I hope you do. I've posted here so the people who want help to see it also to give them an idea maybe they can optimize it :)
A:
I know this is an old thread, but I'd just like to throw out a reference to a python library I wrote which handles all manner of prefix unit conversion handling
Bitmath - Docs
Bitmath - GitHub
Here's the major feature list:
Converting between SI and NIST prefix units (kB to GiB)
Converting between units of the same type (SI to SI, or NIST to NIST)
Automatic human-readable prefix selection (like in hurry.filesize https://pypi.python.org/pypi/hurry.filesize)
Basic arithmetic operations (subtracting 42KiB from 50GiB)
Rich comparison operations (1024 Bytes == 1KiB)
bitwise operations (<<, >>, &, |, ^)
Reading a device's storage capacity (Linux/OS X support only)
argparse https://docs.python.org/2/library/argparse.html
integration as a custom type
progressbar https://code.google.com/p/python-progressbar/
integration as a better file transfer speed widget
String parsing
Sorting
A:
@naitsirhc, thanks for your package.
i have added a little function idea to use your package
import pandas as pd
import collections
Measure = collections.namedtuple('Measure', 'SLOT TEXT AVG HIGH LAST LOW SIGMA SWEEPS')
d=[Measure(SLOT='1', TEXT='CH1,AMPLITUDE', AVG='584.4782173493248E-3', HIGH='603.9744119119119E-3', LAST='594.125218968969E-3', LOW='561.1797735235235E-3', SIGMA='5.0385410346638E-3', SWEEPS='237996'), Measure(SLOT='2', TEXT='CH1,FREQUENCY', AVG='873.9706607717992E+6', HIGH='886.1564731675113E+6', LAST='873.9263571643770E+6', LOW='854.8833348698727E+6', SIGMA='4.382200567330E+6', SWEEPS='20705739'), Measure(SLOT='3', TEXT='CH4,PERIOD', AVG='1.1428492411436E-9', HIGH='1.1718844685593E-9', LAST='1.1432428766843E-9', LOW='1.1261916413092E-9', SIGMA='6.6735923746950E-12', SWEEPS='20680921'), Measure(SLOT='4', TEXT='CH4,FREQUENCY', AVG='875.0358282079155E+6', HIGH='887.9483414008331E+6', LAST='874.780693212961E+6', LOW='853.3264385945507E+6', SIGMA='5.0993358972092E+6', SWEEPS='20681008')]
from si_prefix import si_format
import si_prefix
si_prefix.SI_PREFIX_UNITS="yzafpnum kMGTPEZY"
def siSuffixNotation(element):
try:
ret=float(element)
return str(si_format(ret)).replace(' ','')
except ValueError:
return element
df=pd.DataFrame(d)
df.T.applymap(siSuffixNotation) #<= nice pretty print output table
0 1 2 3
SLOT 1.0 2.0 3.0 4.0
TEXT CH1,AMPLITUDE CH1,FREQUENCY CH4,PERIOD CH4,FREQUENCY
AVG 584.5m 874.0M 1.1n 875.1M
HIGH 604.0m 885.6M 1.2n 887.9M
LAST 586.5m 874.2M 1.1n 874.9M
LOW 561.2m 854.9M 1.1n 854.1M
SIGMA 5.0m 4.4M 6.7p 5.1M
SWEEPS 191.5k 16.7M 16.6M 16.6M
Thanks to you, i can know have a pretty print table as i like it.
(i don't like space between the number and the suffix, and i do not like the unicode type, i prefer u for micro)
++
A:
You can use Prefixed, which has a float type with additional formatting options.
You can create float-like numbers by including the prefix
>>> from prefixed import Float
>>> Float('2k')
Float(2000.0)
prefixed.Float is a subclass of float, so you can use it just like a float, but when you want to output, it supports additional format specifiers.
num = Float('2k')
>>> f'{num}'
'2000.0'
>>> f'{num:.2h}'
'2.00k'
Binary prefixes are also supported and some additional formatting options. See the docs for more info.
|
Python library to convert between SI unit prefixes
|
I'm looking for a python library which comes with support to convert numbers between various SI prefixes, for example, kilo to pico, nano to giga and so on.What would you recommend?
|
[
"I ported a simple function (original C version written by\nJukka “Yucca” Korpela) to Python for formatting numbers according to SI standards. I use it often, for example, to set tick labels on plots, etc.\nYou can install it with:\npip install si-prefix\n\nThe source is available on GitHub.\nExample usage:\nfrom si_prefix import si_format\n\nprint si_format(.5)\n# 500.0m (default precision is 1)\n\nprint si_format(.01331, precision=2)\n# 13.31m\n\nprint si_format(1331, precision=2)\n# 1.33k\n\nprint si_format(1331, precision=0)\n# 1k\n\n",
"Dictionaries\nIf you don't want to use any 3rd-party library like the ones listed below, you can actually implement your own parsing function.\nUse a dictionary to match up the prefixes to their values. I've done it for you already:\n_prefix = {'y': 1e-24, # yocto\n 'z': 1e-21, # zepto\n 'a': 1e-18, # atto\n 'f': 1e-15, # femto\n 'p': 1e-12, # pico\n 'n': 1e-9, # nano\n 'u': 1e-6, # micro\n 'm': 1e-3, # mili\n 'c': 1e-2, # centi\n 'd': 1e-1, # deci\n 'k': 1e3, # kilo\n 'M': 1e6, # mega\n 'G': 1e9, # giga\n 'T': 1e12, # tera\n 'P': 1e15, # peta\n 'E': 1e18, # exa\n 'Z': 1e21, # zetta\n 'Y': 1e24, # yotta\n }\n\nThen you can use regex (as described by my answer here) to search or parse the input and use the dictionary for getting the appropriate value.\n\nUnum\nUnum is well finished and thoroughly documented library. \nPros: \n\nallows you to define arbitrary units (magnitude only supports user-defined units as long as they are a combination of the base units). \n\nCons:\n\ndoesn't handle prefixes well\nclutters your namespace with all its unit definitions (you end up with variables named M, S etc. in your namespace)\n\n\nMagnitude\nYou can also use Magnitude, another library. It supports all the kinds of SI unit prefixes you're talking about, plus it'll handle the parsing as well. From the site:\n\nA physical quantity is a number with a unit, like 10 km/h. Units are specified as strings. They can be any of the SI units, plus a bunch of non-SI, bits, dollars, and any combination of them. They can include the standard SI prefixes.\n ...\nAll standard prefixes are understood, from yocto to yotta and from kibi to exbi.\n\n",
"QuantiPhy is a new package that converts to and from numbers with SI scale factors. It is often a better choice that the unit packages such as Unum and Magnitude that are heavier and focused on the units rather than the scale factors.\nQuantiPhy provides Quantity, which is an object that combines a number with its unit of measure (the units are optional). When creating a quantity you can use SI unit prefixes. Once you have a Quantity you can use it in expressions, where it acts as a float. Or you can convert it to a string, in which case it uses the SI unit prefixes by default.\n>>> from quantiphy import Quantity\n\n# convert strings to quantities\n>>> duration = Quantity('0.12 ks')\n>>> print(duration)\n120 s\n\n# convert to other units when rendering to a string\n>>> print(duration.render(scale='min'))\n2 min\n\n# quantities act like floats in expressions\n>>> rate = 1/duration\n>>> print(rate)\n0.008333333333333333\n\n# convert floats to quantities\n>>> rate = Quantity(rate, 'Hz')\n>>> print(rate)\n8.3333 mHz\n\n# can be used in format strings\n>>> print(f'Duration = {duration:<12.3} Rate = {rate}')\nDuration = 120 s Rate = 8.3333 mHz\n\nBy default QuantiPhy uses the natural prefix when rendering to a string, which is probably what you want. But you can force it to render to a specific prefix using scaling:\n>>> mass = Quantity('1000 g')\n>>> print(mass)\n1 kg\n\n>>> print(mass.render(show_si=False))\n1e3 g\n\n>>> print(mass.render(show_si=False, scale=(1e-12, 'pg')))\n1e9 pg\n\nIn this case you must turn off SI unit prefixes to avoid getting multiple prefixes: '1 npg'.\nA more natural example might be where you are converting units:\n>>> l = Quantity('2um') \n>>> print(l.render(scale='Å')) \n20 kÅ \n\n>>> print(f'{l:sÅ}') \n20 kÅ\n\nThe last example shows that you can place your desired units in the format string after the type and the conversion will be done for you automatically.\n",
"I don't know if this is the best answer but it is working in my case. Feel free to verify my solution. I am working for first time with Python and constructive criticism is welcome... along with positive feedback :D \nThis is my code:\nclass Units:\ndef __init__(self):\n global si;\n si = {\n -18 : {'multiplier' : 10 ** 18, 'prefix' : 'a'},\n -17 : {'multiplier' : 10 ** 18, 'prefix' : 'a'},\n -16 : {'multiplier' : 10 ** 18, 'prefix' : 'a'},\n -15 : {'multiplier' : 10 ** 15, 'prefix' : 'f'},\n -14 : {'multiplier' : 10 ** 15, 'prefix' : 'f'},\n -13 : {'multiplier' : 10 ** 15, 'prefix' : 'f'},\n -12 : {'multiplier' : 10 ** 12, 'prefix' : 'p'},\n -11 : {'multiplier' : 10 ** 12, 'prefix' : 'p'},\n -10 : {'multiplier' : 10 ** 12, 'prefix' : 'p'},\n -9 : {'multiplier' : 10 ** 9, 'prefix' : 'n'},\n -8 : {'multiplier' : 10 ** 9, 'prefix' : 'n'},\n -7 : {'multiplier' : 10 ** 9, 'prefix' : 'n'},\n -6 : {'multiplier' : 10 ** 6, 'prefix' : 'u'},\n -5 : {'multiplier' : 10 ** 6, 'prefix' : 'u'},\n -4 : {'multiplier' : 10 ** 6, 'prefix' : 'u'},\n -3 : {'multiplier' : 10 ** 3, 'prefix' : 'm'},\n -2 : {'multiplier' : 10 ** 2, 'prefix' : 'c'},\n -1 : {'multiplier' : 10 ** 1, 'prefix' : 'd'},\n 0 : {'multiplier' : 1, 'prefix' : ''},\n 1 : {'multiplier' : 10 ** 1, 'prefix' : 'da'},\n 2 : {'multiplier' : 10 ** 3, 'prefix' : 'k'},\n 3 : {'multiplier' : 10 ** 3, 'prefix' : 'k'},\n 4 : {'multiplier' : 10 ** 3, 'prefix' : 'k'},\n 5 : {'multiplier' : 10 ** 3, 'prefix' : 'k'},\n 6 : {'multiplier' : 10 ** 6, 'prefix' : 'M'},\n 7 : {'multiplier' : 10 ** 6, 'prefix' : 'M'},\n 8 : {'multiplier' : 10 ** 6, 'prefix' : 'M'},\n 9 : {'multiplier' : 10 ** 9, 'prefix' : 'G'},\n 10 : {'multiplier' : 10 ** 9, 'prefix' : 'G'},\n 11 : {'multiplier' : 10 ** 9, 'prefix' : 'G'},\n 12 : {'multiplier' : 10 ** 12, 'prefix' : 'T'},\n 13 : {'multiplier' : 10 ** 12, 'prefix' : 'T'},\n 14 : {'multiplier' : 10 ** 12, 'prefix' : 'T'},\n 15 : {'multiplier' : 10 ** 15, 'prefix' : 'P'},\n 16 : {'multiplier' : 10 ** 15, 'prefix' : 'P'},\n 17 : {'multiplier' : 10 ** 15, 'prefix' : 'P'},\n 18 : {'multiplier' : 10 ** 18, 'prefix' : 'E'},\n }\n\ndef convert(self, number):\n # Checking if its negative or positive\n if number < 0:\n negative = True;\n else:\n negative = False;\n\n # if its negative converting to positive (math.log()....)\n if negative:\n number = number - (number*2);\n\n # Taking the exponent\n exponent = int(math.log10(number));\n\n # Checking if it was negative converting it back to negative\n if negative:\n number = number - (number*2);\n\n # If the exponent is smaler than 0 dividing the exponent with -1\n if exponent < 0:\n exponent = exponent-1;\n return [number * si[exponent]['multiplier'], si[exponent]['prefix']]; \n # If the exponent bigger than 0 just return it\n elif exponent > 0:\n return [number / si[exponent]['multiplier'], si[exponent]['prefix']]; \n # If the exponent is 0 than return only the value\n elif exponent == 0:\n return [number, ''];\n\n\nAnd this is how it works:\nc1 = +1.189404E-010\nfres = -4.07237500000000E+007;\nls = +1.943596E-005;\n\nunits = sci.Units();\nrValue, rPrefix = units.convert(c1);\nprint rValue;\nprint rPrefix;\n\nprint units.convert(fres);\nprint units.convert(ls);\n\nAnd the response is: \n118.9404\np\n[-40.72375, 'M']\n[19.435959999999998, 'u']\n\nI don't know if anyone will find this helpful or not. I hope you do. I've posted here so the people who want help to see it also to give them an idea maybe they can optimize it :)\n",
"I know this is an old thread, but I'd just like to throw out a reference to a python library I wrote which handles all manner of prefix unit conversion handling\n\nBitmath - Docs\nBitmath - GitHub\n\nHere's the major feature list:\n\nConverting between SI and NIST prefix units (kB to GiB)\nConverting between units of the same type (SI to SI, or NIST to NIST)\nAutomatic human-readable prefix selection (like in hurry.filesize https://pypi.python.org/pypi/hurry.filesize)\nBasic arithmetic operations (subtracting 42KiB from 50GiB)\nRich comparison operations (1024 Bytes == 1KiB)\nbitwise operations (<<, >>, &, |, ^)\nReading a device's storage capacity (Linux/OS X support only)\nargparse https://docs.python.org/2/library/argparse.html\nintegration as a custom type\nprogressbar https://code.google.com/p/python-progressbar/\nintegration as a better file transfer speed widget\nString parsing\nSorting\n\n",
"@naitsirhc, thanks for your package.\ni have added a little function idea to use your package\nimport pandas as pd\nimport collections\nMeasure = collections.namedtuple('Measure', 'SLOT TEXT AVG HIGH LAST LOW SIGMA SWEEPS')\nd=[Measure(SLOT='1', TEXT='CH1,AMPLITUDE', AVG='584.4782173493248E-3', HIGH='603.9744119119119E-3', LAST='594.125218968969E-3', LOW='561.1797735235235E-3', SIGMA='5.0385410346638E-3', SWEEPS='237996'), Measure(SLOT='2', TEXT='CH1,FREQUENCY', AVG='873.9706607717992E+6', HIGH='886.1564731675113E+6', LAST='873.9263571643770E+6', LOW='854.8833348698727E+6', SIGMA='4.382200567330E+6', SWEEPS='20705739'), Measure(SLOT='3', TEXT='CH4,PERIOD', AVG='1.1428492411436E-9', HIGH='1.1718844685593E-9', LAST='1.1432428766843E-9', LOW='1.1261916413092E-9', SIGMA='6.6735923746950E-12', SWEEPS='20680921'), Measure(SLOT='4', TEXT='CH4,FREQUENCY', AVG='875.0358282079155E+6', HIGH='887.9483414008331E+6', LAST='874.780693212961E+6', LOW='853.3264385945507E+6', SIGMA='5.0993358972092E+6', SWEEPS='20681008')]\n\nfrom si_prefix import si_format\n\nimport si_prefix\nsi_prefix.SI_PREFIX_UNITS=\"yzafpnum kMGTPEZY\"\n\ndef siSuffixNotation(element):\n try:\n ret=float(element)\n return str(si_format(ret)).replace(' ','')\n except ValueError:\n return element\n\ndf=pd.DataFrame(d)\n\ndf.T.applymap(siSuffixNotation) #<= nice pretty print output table\n 0 1 2 3\nSLOT 1.0 2.0 3.0 4.0\nTEXT CH1,AMPLITUDE CH1,FREQUENCY CH4,PERIOD CH4,FREQUENCY\nAVG 584.5m 874.0M 1.1n 875.1M\nHIGH 604.0m 885.6M 1.2n 887.9M\nLAST 586.5m 874.2M 1.1n 874.9M\nLOW 561.2m 854.9M 1.1n 854.1M\nSIGMA 5.0m 4.4M 6.7p 5.1M\nSWEEPS 191.5k 16.7M 16.6M 16.6M\n\nThanks to you, i can know have a pretty print table as i like it.\n(i don't like space between the number and the suffix, and i do not like the unicode type, i prefer u for micro)\n++\n",
"You can use Prefixed, which has a float type with additional formatting options.\nYou can create float-like numbers by including the prefix\n>>> from prefixed import Float\n\n>>> Float('2k')\nFloat(2000.0)\n\nprefixed.Float is a subclass of float, so you can use it just like a float, but when you want to output, it supports additional format specifiers.\nnum = Float('2k')\n>>> f'{num}'\n'2000.0'\n>>> f'{num:.2h}'\n'2.00k'\n\nBinary prefixes are also supported and some additional formatting options. See the docs for more info.\n"
] |
[
17,
6,
6,
4,
3,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0010969759_python.txt
|
Q:
Type Hinting: Use type of a class member as function return type (for inheritance)
What is the correct way to reuse the type of a class member to type hint other items in the class? As an example:
from typing import Type
class Model:
pass
class ChildModel:
childvar = "Child Model"
class Base:
var: Type[Model]
def fn(self) -> ??:
return self.var
class Child(Base):
var = ChildModel
def new_fn(self):
x = self.fn() # Type of x should be "ChildModel"
print(x.childvar)
Child().new_fn() # Prints "Child Model" successfully
I am looking for what would work to replace ?? such that the return type of fn() can be inferred for all child classes.
MyPy does not accept changing ?? to Type[Model] to match Base.var: Incompatible types in assignment (expression has type "Type[ChildModel]", base class "Base" defined the type as "Type[Model]" (though it is possible I made a mistake here). Even if this were allowed, this would allow Base.fn() to return any Model or Model subclass, not strictly the type of var (as defined in a child of Base)
Something like T = TypeVar("T", bound=Type[Model]) seems disallowed without generics, which don't seem quite applicable since the type can be inferred without generic-style specification. I think the solution would likely also work to type hint method arguments, method-local variables, and other class member variables.
What is the best way to do this (if possible)?
Edit: adding clarification, corrected issue with code
A:
This can be accomplished with Generics.
from typing import Generic, TypeVar
T = TypeVar("T", bound="Model")
class Model:
pass
class ChildModel(Model):
childvar = "Child Model"
class Base(Generic[T]):
var: type[T]
def fn(self) -> type[T]:
return self.var
class Child(Base[ChildModel]):
var = ChildModel
def new_fn(self):
x = self.fn() # Type of x is type["ChildModel"]
print(x.childvar)
Child().new_fn()
A:
Though this probably fails the "Explicit is better than Implicit" test, I suppose this will get you what you want while avoiding typing in two places. In this case, rather than defining var on the Child, the var is pulled from the annotation.
Tested on Python 3.10
import typing
from typing import Generic, TypeVar
T = TypeVar("T", bound="Model")
class Model:
pass
class ChildModel(Model):
childvar = "Child Model"
class Base(Generic[T]):
@classmethod
@property
def var(cls) -> type[T]:
for superclass in cls.__orig_bases__:
if getattr(superclass, "__origin__", None) == Base:
return typing.get_args(superclass)[0]
def fn(self) -> type[T]:
return self.var
class Child(Base[ChildModel]):
def new_fn(self):
x = self.fn() # Type of x is type["ChildModel"]
print(x.childvar)
|
Type Hinting: Use type of a class member as function return type (for inheritance)
|
What is the correct way to reuse the type of a class member to type hint other items in the class? As an example:
from typing import Type
class Model:
pass
class ChildModel:
childvar = "Child Model"
class Base:
var: Type[Model]
def fn(self) -> ??:
return self.var
class Child(Base):
var = ChildModel
def new_fn(self):
x = self.fn() # Type of x should be "ChildModel"
print(x.childvar)
Child().new_fn() # Prints "Child Model" successfully
I am looking for what would work to replace ?? such that the return type of fn() can be inferred for all child classes.
MyPy does not accept changing ?? to Type[Model] to match Base.var: Incompatible types in assignment (expression has type "Type[ChildModel]", base class "Base" defined the type as "Type[Model]" (though it is possible I made a mistake here). Even if this were allowed, this would allow Base.fn() to return any Model or Model subclass, not strictly the type of var (as defined in a child of Base)
Something like T = TypeVar("T", bound=Type[Model]) seems disallowed without generics, which don't seem quite applicable since the type can be inferred without generic-style specification. I think the solution would likely also work to type hint method arguments, method-local variables, and other class member variables.
What is the best way to do this (if possible)?
Edit: adding clarification, corrected issue with code
|
[
"This can be accomplished with Generics.\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\", bound=\"Model\")\n\n\nclass Model:\n pass\n\n\nclass ChildModel(Model):\n childvar = \"Child Model\"\n\n\nclass Base(Generic[T]):\n var: type[T]\n\n def fn(self) -> type[T]:\n return self.var\n\n\nclass Child(Base[ChildModel]):\n var = ChildModel\n\n def new_fn(self):\n x = self.fn() # Type of x is type[\"ChildModel\"]\n print(x.childvar)\n\n\nChild().new_fn()\n\n",
"Though this probably fails the \"Explicit is better than Implicit\" test, I suppose this will get you what you want while avoiding typing in two places. In this case, rather than defining var on the Child, the var is pulled from the annotation.\nTested on Python 3.10\nimport typing\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\", bound=\"Model\")\n\n\nclass Model:\n pass\n\n\nclass ChildModel(Model):\n childvar = \"Child Model\"\n\n\nclass Base(Generic[T]):\n @classmethod\n @property\n def var(cls) -> type[T]:\n for superclass in cls.__orig_bases__:\n if getattr(superclass, \"__origin__\", None) == Base:\n return typing.get_args(superclass)[0]\n\n def fn(self) -> type[T]:\n return self.var\n\n\nclass Child(Base[ChildModel]):\n def new_fn(self):\n x = self.fn() # Type of x is type[\"ChildModel\"]\n print(x.childvar)\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"mypy",
"python",
"python_3.x",
"python_typing",
"type_hinting"
] |
stackoverflow_0072581534_mypy_python_python_3.x_python_typing_type_hinting.txt
|
Q:
Not able to access all results in notion DB (via python)
I have a DB with 106 entries and I can't seem to access the first 6 entries. I tried adding start_cursor and page_size keys to my request but they don't seem to have any effect. If I add them as ints the request gets rejected so I'm adding them as strings - not sure if this is the issue (I also tried converting to bytes). Whatever I do, it seems to return the last 100 results.
import requests
_url = 'https://api.notion.com/v1/databases/xxxxx/query'
_header = {
'Authorization': _auth,
'Content-Type': 'application/json',
'Notion-Version': '2021-08-16',
'page_size': '3',
'start_cursor': '0'}
_result = requests.post(_url, headers=_header)
Any idea how I can get all the results, or change my request to get the first six results?
A:
As it said in the documentation, you can retrieve no more than 100 items per one request, but you can send many consecutive requests. You need to grab the property next_cursor from the response to the previous request and then pass it as a parameter start_cursor in your next request. While the has_more property is True, you can get more and more items.
A:
I was adding the data wrong - it needs to be added like this:
_data = {'start_cursor': _next_cursor}
requests.post(_url, headers=self.to_header(), data=json.dumps(_data))
|
Not able to access all results in notion DB (via python)
|
I have a DB with 106 entries and I can't seem to access the first 6 entries. I tried adding start_cursor and page_size keys to my request but they don't seem to have any effect. If I add them as ints the request gets rejected so I'm adding them as strings - not sure if this is the issue (I also tried converting to bytes). Whatever I do, it seems to return the last 100 results.
import requests
_url = 'https://api.notion.com/v1/databases/xxxxx/query'
_header = {
'Authorization': _auth,
'Content-Type': 'application/json',
'Notion-Version': '2021-08-16',
'page_size': '3',
'start_cursor': '0'}
_result = requests.post(_url, headers=_header)
Any idea how I can get all the results, or change my request to get the first six results?
|
[
"As it said in the documentation, you can retrieve no more than 100 items per one request, but you can send many consecutive requests. You need to grab the property next_cursor from the response to the previous request and then pass it as a parameter start_cursor in your next request. While the has_more property is True, you can get more and more items.\n",
"I was adding the data wrong - it needs to be added like this:\n_data = {'start_cursor': _next_cursor}\nrequests.post(_url, headers=self.to_header(), data=json.dumps(_data))\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"notion_api",
"python"
] |
stackoverflow_0074493865_notion_api_python.txt
|
Q:
how to replace the comma in numbers in dataframe by dot?
I have this dataframe that I wish to replace all the comma by dot, for example it would be 50.5 and 81.5.
Unnamed: 0 NB Ppt Resale 5 yrs 10 yrs 15 yrs 20 yrs
1 VLCC 120 114 87 64 50,5 37
3 SUEZMAX 81,5 80 62 45 36 24
5 LR 2 69 72 57 42 32 20
7 AFRAMAX 66 68 55 40,5 30,5 19
9 LR 1 58 58 40 28 21 13,5
11 MR2 44 44,5 38 29 21 13
As dtypes for all the columns are object, I tried
df_useful[['NB', 'Ppt Resale ', '5 yrs', '10 yrs', '15 yrs',
'20 yrs']] = df_useful[['NB', 'Ppt Resale ', '5 yrs', '10 yrs', '15 yrs',
'20 yrs']].apply(pd.to_numeric, errors='coerce')
then the numbers with comma would become NAN.
A:
A simple way:
out = df.replace(',', '.', regex=True)
Output:
Unnamed: 0 NB Ppt Resale 5 yrs 10 yrs 15 yrs 20 yrs
1 VLCC 120 114 87 64 50.5 37
3 SUEZMAX 81.5 80 62 45 36 24
5 LR 2 69 72 57 42 32 20
7 AFRAMAX 66 68 55 40.5 30.5 19
9 LR 1 58 58 40 28 21 13.5
11 MR2 44 44.5 38 29 21 13
If your goal is to convert to numeric automatically, you can use:
df2 = (df
.drop(columns='Unnamed: 0')
.select_dtypes(exclude='number')
.apply(lambda s: pd.to_numeric(s.str.replace(',', '.'),
errors='coerce'))
)
df[list(df2)] = df2
Output:
Unnamed: 0 NB Ppt Resale 5 yrs 10 yrs 15 yrs 20 yrs
1 VLCC 120.0 114.0 87 64.0 50.5 37.0
3 SUEZMAX 81.5 80.0 62 45.0 36.0 24.0
5 LR 2 69.0 72.0 57 42.0 32.0 20.0
7 AFRAMAX 66.0 68.0 55 40.5 30.5 19.0
9 LR 1 58.0 58.0 40 28.0 21.0 13.5
11 MR2 44.0 44.5 38 29.0 21.0 13.0
dtypes:
print(df.dtypes)
Unnamed: 0 object
NB float64
Ppt Resale float64
5 yrs int64
10 yrs float64
15 yrs float64
20 yrs float64
dtype: object
A:
Another possible solution, based on the following idea:
Convert the dataframe to CSV format and then read the CSV string back, using the decimal separator parameter of pd.read_csv to have decimal dots instead of decimal commas.
from io import StringIO
pd.read_csv(StringIO(df.to_csv()), decimal=',', index_col=0)
Output:
Unnamed: 0 NB Ppt Resale 5 yrs 10 yrs 15 yrs 20 yrs
1 VLCC 120.0 114.0 87 64.0 50.5 37.0
3 SUEZMAX 81.5 80.0 62 45.0 36.0 24.0
5 LR 2 69.0 72.0 57 42.0 32.0 20.0
7 AFRAMAX 66.0 68.0 55 40.5 30.5 19.0
9 LR 1 58.0 58.0 40 28.0 21.0 13.5
11 MR2 44.0 44.5 38 29.0 21.0 13.0
|
how to replace the comma in numbers in dataframe by dot?
|
I have this dataframe that I wish to replace all the comma by dot, for example it would be 50.5 and 81.5.
Unnamed: 0 NB Ppt Resale 5 yrs 10 yrs 15 yrs 20 yrs
1 VLCC 120 114 87 64 50,5 37
3 SUEZMAX 81,5 80 62 45 36 24
5 LR 2 69 72 57 42 32 20
7 AFRAMAX 66 68 55 40,5 30,5 19
9 LR 1 58 58 40 28 21 13,5
11 MR2 44 44,5 38 29 21 13
As dtypes for all the columns are object, I tried
df_useful[['NB', 'Ppt Resale ', '5 yrs', '10 yrs', '15 yrs',
'20 yrs']] = df_useful[['NB', 'Ppt Resale ', '5 yrs', '10 yrs', '15 yrs',
'20 yrs']].apply(pd.to_numeric, errors='coerce')
then the numbers with comma would become NAN.
|
[
"A simple way:\nout = df.replace(',', '.', regex=True)\n\nOutput:\n Unnamed: 0 NB Ppt Resale 5 yrs 10 yrs 15 yrs 20 yrs\n1 VLCC 120 114 87 64 50.5 37\n3 SUEZMAX 81.5 80 62 45 36 24\n5 LR 2 69 72 57 42 32 20\n7 AFRAMAX 66 68 55 40.5 30.5 19\n9 LR 1 58 58 40 28 21 13.5\n11 MR2 44 44.5 38 29 21 13\n\nIf your goal is to convert to numeric automatically, you can use:\ndf2 = (df\n .drop(columns='Unnamed: 0')\n .select_dtypes(exclude='number')\n .apply(lambda s: pd.to_numeric(s.str.replace(',', '.'),\n errors='coerce')) \n)\ndf[list(df2)] = df2\n\nOutput:\n Unnamed: 0 NB Ppt Resale 5 yrs 10 yrs 15 yrs 20 yrs\n1 VLCC 120.0 114.0 87 64.0 50.5 37.0\n3 SUEZMAX 81.5 80.0 62 45.0 36.0 24.0\n5 LR 2 69.0 72.0 57 42.0 32.0 20.0\n7 AFRAMAX 66.0 68.0 55 40.5 30.5 19.0\n9 LR 1 58.0 58.0 40 28.0 21.0 13.5\n11 MR2 44.0 44.5 38 29.0 21.0 13.0\n\ndtypes:\nprint(df.dtypes)\n\nUnnamed: 0 object\nNB float64\nPpt Resale float64\n5 yrs int64\n10 yrs float64\n15 yrs float64\n20 yrs float64\ndtype: object\n\n",
"Another possible solution, based on the following idea:\n\nConvert the dataframe to CSV format and then read the CSV string back, using the decimal separator parameter of pd.read_csv to have decimal dots instead of decimal commas.\n\nfrom io import StringIO\n \npd.read_csv(StringIO(df.to_csv()), decimal=',', index_col=0)\n\nOutput:\n Unnamed: 0 NB Ppt Resale 5 yrs 10 yrs 15 yrs 20 yrs\n1 VLCC 120.0 114.0 87 64.0 50.5 37.0\n3 SUEZMAX 81.5 80.0 62 45.0 36.0 24.0\n5 LR 2 69.0 72.0 57 42.0 32.0 20.0\n7 AFRAMAX 66.0 68.0 55 40.5 30.5 19.0\n9 LR 1 58.0 58.0 40 28.0 21.0 13.5\n11 MR2 44.0 44.5 38 29.0 21.0 13.0\n\n"
] |
[
2,
2
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074493938_dataframe_pandas_python.txt
|
Q:
How does one invert an area of an image with python?
I was prompted to modify one of our filters so that we can specify which portion of the image should be modified.
row1 and col1 : the top left coordinates the rectangle to modify
row2 and col2: the bottom right coordinates of the rectangle to modify
I have attmepted this but it has not worked.
This is what I have attempted thus far
`
def invertspot(pic, row1, col1, row2, col2):
# Go through each row and column
for row in range(pic.height):
for col in range(pic.width):
# Gets a pixel at row/col
pixel = pic.pixels[row1][col1][row2][col2]
# Get the RGB values of this pixel
red = pixel.red
green = pixel.green
blue = pixel.blue
# Resave them and get the inverse by subtracting 255 from the value of the
#color
pixel.red = 255 - red
pixel.green = 255 - green
pixel.blue = 255 - blue
# Finally, reset the pixel stored at that spot
pic.pixels[row][col] = pixel
`
A:
I would do this in numpy. Easier and runs faster.
from PIL import Image
import numpy as np
img = Image.open("test186_img.jpg")
def invertspot(pic, row1, col1, row2, col2):
array = np.array(img)
subset = array[row1:row2, col1:col2]
subset = 255 - subset
array[row1:row2, col1:col2] = subset
return Image.fromarray(array)
invertspot(img, 200, 600, 500, 800)
Example output:
(Image credit: Wikipedia)
A:
Sticking just with PIL, you can do that like this:
#!/usr/bin/env python3
from PIL import Image, ImageChops
# Open image
im = Image.open('artistic-swirl.jpg')
# Define bounding box (left, upper, right, lower)
bbox = (100, 150, 300, 350)
# Extract the ROI, invert it and paste it back
ROI = im.crop(bbox)
ROI = ImageChops.invert(ROI)
im.paste(ROI, bbox)
im.save('result.png')
Which turns this:
into this:
|
How does one invert an area of an image with python?
|
I was prompted to modify one of our filters so that we can specify which portion of the image should be modified.
row1 and col1 : the top left coordinates the rectangle to modify
row2 and col2: the bottom right coordinates of the rectangle to modify
I have attmepted this but it has not worked.
This is what I have attempted thus far
`
def invertspot(pic, row1, col1, row2, col2):
# Go through each row and column
for row in range(pic.height):
for col in range(pic.width):
# Gets a pixel at row/col
pixel = pic.pixels[row1][col1][row2][col2]
# Get the RGB values of this pixel
red = pixel.red
green = pixel.green
blue = pixel.blue
# Resave them and get the inverse by subtracting 255 from the value of the
#color
pixel.red = 255 - red
pixel.green = 255 - green
pixel.blue = 255 - blue
# Finally, reset the pixel stored at that spot
pic.pixels[row][col] = pixel
`
|
[
"I would do this in numpy. Easier and runs faster.\nfrom PIL import Image\nimport numpy as np\n\nimg = Image.open(\"test186_img.jpg\")\n\ndef invertspot(pic, row1, col1, row2, col2):\n array = np.array(img)\n subset = array[row1:row2, col1:col2]\n subset = 255 - subset\n array[row1:row2, col1:col2] = subset\n return Image.fromarray(array)\ninvertspot(img, 200, 600, 500, 800)\n\nExample output:\n\n(Image credit: Wikipedia)\n",
"Sticking just with PIL, you can do that like this:\n#!/usr/bin/env python3\n\nfrom PIL import Image, ImageChops\n\n# Open image\nim = Image.open('artistic-swirl.jpg')\n\n# Define bounding box (left, upper, right, lower)\nbbox = (100, 150, 300, 350)\n\n# Extract the ROI, invert it and paste it back\nROI = im.crop(bbox)\nROI = ImageChops.invert(ROI)\nim.paste(ROI, bbox)\nim.save('result.png')\n\nWhich turns this:\n\ninto this:\n\n"
] |
[
2,
2
] |
[] |
[] |
[
"python",
"python_imaging_library"
] |
stackoverflow_0074493191_python_python_imaging_library.txt
|
Q:
mongodb find returns json object with keys that start with unwanted dollar sign ($date, $binary..)
I am using python 3.9.12 to query mongodb,
I then read the values into variables and continue with my logic.
Problem is, some of my values have keys that start with dollar sign.
Here is an example of a json I get:
[
{
"_id": {
"$oid": "234876234875236752309823"
},
"createdAt": {
"$date": "2022-11-13T20:50:18.184Z"
},
"moreFields": {
"key1": "blabla1",
"key2": "blabla2",
"key3": "blabla3"
},
"entityId": {
"$binary": {
"base64": "z0kWDTHiSlawpI2wHjyrWA==",
"subType": "04"
}
}
}
]
I understand that those mongodb field types (bson, datetime...).
But this makes my life hard in trying to access those values using python.
I was reading and looking but I couldn't find a method to convert them to "normal" keys.
Ideally I would want to correct my mongodb query (get datetime as strings and $binary as UUID strings).
I have found a stupid workaround in python but unfortunately it is very stupid and I want to correct my ways.
Any ideas?
Thanks :)
I would really be happy if the result of my mongodb query would change to:
[
{
"_id": "234876234875236752309823",
"createdAt": "2022-11-13T20:50:18.184Z",
"moreFields": {
"key1": "blabla1",
"key2": "blabla2",
"key3": "blabla3"
},
"entityId": "e87b22b2-ea15-4176-9100-c65f79f0e5b2"
}
]
A:
If your data is in a string format (say, from a file), use loads from the bson.json_util module. https://pymongo.readthedocs.io/en/stable/api/bson/json_util.html
For the second part, that is just formatting; but beware, this just creates another string output. Chances are the data you are interested in is actually in the record object.
The following snippet converts the input string, loads it into MongoDB, and then formats it back to a string using a custom encoder:
import datetime
import json
import bson
from bson import json_util
from pymongo import MongoClient
db = MongoClient()['mydatabase']
records = '''[
{
"_id": {
"$oid": "234876234875236752309823"
},
"createdAt": {
"$date": "2022-11-13T20:50:18.184Z"
},
"moreFields": {
"key1": "blabla1",
"key2": "blabla2",
"key3": "blabla3"
},
"entityId": {
"$binary": {
"base64": "z0kWDTHiSlawpI2wHjyrWA==",
"subType": "04"
}
}
}
]'''
db.mycollection.insert_many(json_util.loads(records))
class MyJsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.isoformat() # Format dates as ISO strings
elif isinstance(obj, bson.Binary) and obj.subtype == bson.binary.UUID_SUBTYPE:
return obj.as_uuid() # Format binary data as UUIDs
elif hasattr(obj, '__str__'):
return str(obj) # This will handle ObjectIds
return super(MyJsonEncoder, self).default(obj)
record = db.mycollection.find_one()
print(json.dumps(record, cls=MyJsonEncoder, indent=4))
prints:
{
"_id": "234876234875236752309823",
"createdAt": "2022-11-13T20:50:18.184000",
"moreFields": {
"key1": "blabla1",
"key2": "blabla2",
"key3": "blabla3"
},
"entityId": "cf49160d-31e2-4a56-b0a4-8db01e3cab58"
}
|
mongodb find returns json object with keys that start with unwanted dollar sign ($date, $binary..)
|
I am using python 3.9.12 to query mongodb,
I then read the values into variables and continue with my logic.
Problem is, some of my values have keys that start with dollar sign.
Here is an example of a json I get:
[
{
"_id": {
"$oid": "234876234875236752309823"
},
"createdAt": {
"$date": "2022-11-13T20:50:18.184Z"
},
"moreFields": {
"key1": "blabla1",
"key2": "blabla2",
"key3": "blabla3"
},
"entityId": {
"$binary": {
"base64": "z0kWDTHiSlawpI2wHjyrWA==",
"subType": "04"
}
}
}
]
I understand that those mongodb field types (bson, datetime...).
But this makes my life hard in trying to access those values using python.
I was reading and looking but I couldn't find a method to convert them to "normal" keys.
Ideally I would want to correct my mongodb query (get datetime as strings and $binary as UUID strings).
I have found a stupid workaround in python but unfortunately it is very stupid and I want to correct my ways.
Any ideas?
Thanks :)
I would really be happy if the result of my mongodb query would change to:
[
{
"_id": "234876234875236752309823",
"createdAt": "2022-11-13T20:50:18.184Z",
"moreFields": {
"key1": "blabla1",
"key2": "blabla2",
"key3": "blabla3"
},
"entityId": "e87b22b2-ea15-4176-9100-c65f79f0e5b2"
}
]
|
[
"If your data is in a string format (say, from a file), use loads from the bson.json_util module. https://pymongo.readthedocs.io/en/stable/api/bson/json_util.html\nFor the second part, that is just formatting; but beware, this just creates another string output. Chances are the data you are interested in is actually in the record object.\nThe following snippet converts the input string, loads it into MongoDB, and then formats it back to a string using a custom encoder:\nimport datetime\nimport json\nimport bson\nfrom bson import json_util\nfrom pymongo import MongoClient\n\ndb = MongoClient()['mydatabase']\n\nrecords = '''[\n {\n \"_id\": {\n \"$oid\": \"234876234875236752309823\"\n },\n \"createdAt\": {\n \"$date\": \"2022-11-13T20:50:18.184Z\"\n },\n \"moreFields\": {\n \"key1\": \"blabla1\",\n \"key2\": \"blabla2\",\n \"key3\": \"blabla3\"\n },\n \"entityId\": {\n \"$binary\": {\n \"base64\": \"z0kWDTHiSlawpI2wHjyrWA==\",\n \"subType\": \"04\"\n }\n }\n }\n]'''\n\n\ndb.mycollection.insert_many(json_util.loads(records))\n\n\nclass MyJsonEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, datetime.datetime):\n return obj.isoformat() # Format dates as ISO strings\n elif isinstance(obj, bson.Binary) and obj.subtype == bson.binary.UUID_SUBTYPE:\n return obj.as_uuid() # Format binary data as UUIDs\n elif hasattr(obj, '__str__'):\n return str(obj) # This will handle ObjectIds\n\n return super(MyJsonEncoder, self).default(obj)\n\n\nrecord = db.mycollection.find_one()\nprint(json.dumps(record, cls=MyJsonEncoder, indent=4))\n\nprints:\n{\n \"_id\": \"234876234875236752309823\",\n \"createdAt\": \"2022-11-13T20:50:18.184000\",\n \"moreFields\": {\n \"key1\": \"blabla1\",\n \"key2\": \"blabla2\",\n \"key3\": \"blabla3\"\n },\n \"entityId\": \"cf49160d-31e2-4a56-b0a4-8db01e3cab58\"\n}\n\n"
] |
[
0
] |
[] |
[] |
[
"bson",
"dollar_sign",
"mongodb",
"pymongo",
"python"
] |
stackoverflow_0074486368_bson_dollar_sign_mongodb_pymongo_python.txt
|
Q:
Unable to write a code to read table from word document in python
I am a newbie and I started learning Python on my own by seeing videos. I have a task to read table from word document using python and populate it to database.
I can able to write the code to read the paragraphs by using the below code. Can anyone please guide me how to write the code for reading the table form word document? Thanks
import docx
doc = docx.Document('Text.docx')
doc.paragraphs
doc.paragraphs[0].text
doc.paragraphs[1].text
Samlpe table:
Heading
Name1 Desc1
Desc1 Desc2
Name3 Desc3
Name4 Desc4
Desc1 Desc5
Name6 Desc6
Name7 Desc7
I tried writing code to read paragraphs but I am searching how to write the code to read the table
A:
You can use the docx library:
from docx import Document
doc = Document('Text.docx')
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
print cell.text
Similar question can be found here: How to read contents of an Table in MS-Word file Using Python?
|
Unable to write a code to read table from word document in python
|
I am a newbie and I started learning Python on my own by seeing videos. I have a task to read table from word document using python and populate it to database.
I can able to write the code to read the paragraphs by using the below code. Can anyone please guide me how to write the code for reading the table form word document? Thanks
import docx
doc = docx.Document('Text.docx')
doc.paragraphs
doc.paragraphs[0].text
doc.paragraphs[1].text
Samlpe table:
Heading
Name1 Desc1
Desc1 Desc2
Name3 Desc3
Name4 Desc4
Desc1 Desc5
Name6 Desc6
Name7 Desc7
I tried writing code to read paragraphs but I am searching how to write the code to read the table
|
[
"You can use the docx library:\nfrom docx import Document\n\ndoc = Document('Text.docx')\n\nfor table in doc.tables:\n for row in table.rows:\n for cell in row.cells:\n print cell.text\n\nSimilar question can be found here: How to read contents of an Table in MS-Word file Using Python?\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074494045_python.txt
|
Q:
Adding a absolute path that has a \f in it
While adding an absolute path to my script because it has a \f in it the code won't run properly.
C:\Users\showoi\Desktop\website\repository\fileAdder\softwarelisting.xlsx
The file is in the same directory as the script but using a relative path won't work. No misspellings or anything.
A:
Use python r string
path=r'C:\Users\showoi\Desktop\website\repository\fileAdder\softwarelisting.xlsx'
A:
Use one of the following ways:
r"C:\Users\showoi\Desktop\website\repository\fileAdder\softwarelisting.xlsx"
"C:\\Users\\showoi\\Desktop\\website\\repository\\fileAdder\\softwarelisting.xlsx"
"C:/Users/showoi/Desktop/website/repository/fileAdder/softwarelisting.xlsx
|
Adding a absolute path that has a \f in it
|
While adding an absolute path to my script because it has a \f in it the code won't run properly.
C:\Users\showoi\Desktop\website\repository\fileAdder\softwarelisting.xlsx
The file is in the same directory as the script but using a relative path won't work. No misspellings or anything.
|
[
"Use python r string\npath=r'C:\\Users\\showoi\\Desktop\\website\\repository\\fileAdder\\softwarelisting.xlsx'\n\n",
"Use one of the following ways:\n\nr\"C:\\Users\\showoi\\Desktop\\website\\repository\\fileAdder\\softwarelisting.xlsx\"\n\n\"C:\\\\Users\\\\showoi\\\\Desktop\\\\website\\\\repository\\\\fileAdder\\\\softwarelisting.xlsx\"\n\n\"C:/Users/showoi/Desktop/website/repository/fileAdder/softwarelisting.xlsx\n\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074494202_python.txt
|
Q:
Find mean grouped by column in Spark
I have a dataframe such as:
Col1
Value
0
20
1
30
1
20
1
10
0
10
2
30
I want to calculate mean and group by Col1, so that the result is:
Col1
Value2
0
15
1
20
2
30
I don't know how to get the result (the aggregated mean). One additional problem is that when I try df.groupBy("Col1") the 0 value does not appear.
Thank you
A:
In PySpark version 3, the following code accomplishes exactly what you have pictured above.
Welcome to
____ __
/ __/__ ___ _____/ /__
_\ \/ _ \/ _ `/ __/ '_/
/__ / .__/\_,_/_/ /_/\_\ version 3.1.1-amzn-0
/_/
Using Python version 3.7.10 (default, Jun 3 2021 00:02:01)
>>> from pyspark.sql.functions import avg
>>> df = spark.createDataFrame([
... {"Col1": 0, "Value": 20},
... {"Col1": 1, "Value": 30},
... {"Col1": 1, "Value": 20},
... {"Col1": 1, "Value": 10},
... {"Col1": 0, "Value": 10},
... {"Col1": 2, "Value": 30}
... ])
>>> df.show()
+----+-----+
|Col1|Value|
+----+-----+
| 0| 20|
| 1| 30|
| 1| 20|
| 1| 10|
| 0| 10|
| 2| 30|
+----+-----+
>>> grouped = df.groupBy("Col1").agg(avg("Value").alias("Value2"))
>>> grouped.show()
+----+------+
|Col1|Value2|
+----+------+
| 1| 20.0|
| 2| 30.0|
| 0| 15.0|
+----+------+
If you do not need the aggregated column re-aliased to "Value2", you can skip the import and just do grouped = df.groupBy("Col1").avg("Value") and your averaged column will just be called "avg(Value)".
If this "does not work" according to your example, please provide the exact code (or a minimal reproducible example) that can be inspected as to why it might not be returning desired results.
|
Find mean grouped by column in Spark
|
I have a dataframe such as:
Col1
Value
0
20
1
30
1
20
1
10
0
10
2
30
I want to calculate mean and group by Col1, so that the result is:
Col1
Value2
0
15
1
20
2
30
I don't know how to get the result (the aggregated mean). One additional problem is that when I try df.groupBy("Col1") the 0 value does not appear.
Thank you
|
[
"In PySpark version 3, the following code accomplishes exactly what you have pictured above.\nWelcome to\n ____ __\n / __/__ ___ _____/ /__\n _\\ \\/ _ \\/ _ `/ __/ '_/\n /__ / .__/\\_,_/_/ /_/\\_\\ version 3.1.1-amzn-0\n /_/\n\nUsing Python version 3.7.10 (default, Jun 3 2021 00:02:01)\n>>> from pyspark.sql.functions import avg\n>>> df = spark.createDataFrame([\n... {\"Col1\": 0, \"Value\": 20},\n... {\"Col1\": 1, \"Value\": 30},\n... {\"Col1\": 1, \"Value\": 20},\n... {\"Col1\": 1, \"Value\": 10},\n... {\"Col1\": 0, \"Value\": 10},\n... {\"Col1\": 2, \"Value\": 30}\n... ])\n\n>>> df.show()\n+----+-----+\n|Col1|Value|\n+----+-----+\n| 0| 20|\n| 1| 30|\n| 1| 20|\n| 1| 10|\n| 0| 10|\n| 2| 30|\n+----+-----+\n\n>>> grouped = df.groupBy(\"Col1\").agg(avg(\"Value\").alias(\"Value2\"))\n>>> grouped.show()\n+----+------+\n|Col1|Value2|\n+----+------+\n| 1| 20.0|\n| 2| 30.0|\n| 0| 15.0|\n+----+------+\n\nIf you do not need the aggregated column re-aliased to \"Value2\", you can skip the import and just do grouped = df.groupBy(\"Col1\").avg(\"Value\") and your averaged column will just be called \"avg(Value)\".\nIf this \"does not work\" according to your example, please provide the exact code (or a minimal reproducible example) that can be inspected as to why it might not be returning desired results.\n"
] |
[
0
] |
[] |
[] |
[
"apache_spark",
"python"
] |
stackoverflow_0074494082_apache_spark_python.txt
|
Q:
Sorting list of strings based on both sides of a delimiter ("|") in Python 3
I'm looking to sort a list of of strings which illustrate dependencies (the structure of a Bayesian Networks determined through the PC Algorithm).
e.g.
verbose_struct = ['A', 'C|A,E', 'E', 'B|C,D', 'D']
sorted_struct = ['A', 'E', 'D', 'C|A,E', 'B|C,D']
The order of the strings is determined by whether or not the dependencies (the letters following the delimiter '|', e.g. B is dependent on C and D) have been previously listed. As in the above, 'E' should be positioned before 'C|A,E' as C is dependent on E. Strings with no dependencies should be positioned before all strings with dependencies, e.g. 'D' before 'C|A,E' and 'B|C,D'.
How would I go about this?
I have managed to order the strings by whether or not they have dependencies using the following:
sorted_struct = sorted(verbose_struct, key=lambda x: len(x.split('|')))
I am unsure how to then further sort the variables by their dependencies, as I am fairly unfamiliar with lambda functions in Python.
A:
I would just "make the jump" here to making a class to hold these objects. by doing so, you can implement your own __lt__ method, which is all that is needed for all of the default sorting methods to sort the objects.
Note: This example class just deals with "labels" so when you are adding dependencies, you are just adding labels of other things. A more sophisticated class would hold the Element values of the dependencies instead of the labels, then you could kinda chain things together by looking up the dependencies of the dependencies, which you cannot do with this simple example. In order to make that work, you would need to define things in some kind of logical order (or do something more complicated) so that the earliest dependencies in the tree were added first. There are probably a bunch of examples out there for node-arc setups (which is what this describes) that do that.
The main thing here is that you can make a custom function to enable sorting by comparing 2 elements. You could also "peel out" this 2-item comparison function, make the pieces on the fly, and pass that function to the sort() method and it would also work without the class.
Code:
# Bayesian Elements
class Element():
def __init__(self, data: str):
self.label = data
if '|' in data:
# dependency...break it up
self.base, dependencies = data.split('|')
# break up the dependencies
self.dependencies = set(dependencies.split(','))
else: # it is a single base element
self.base = data
self.dependencies = None
def get_dependencies(self):
return self.dependencies
def get_base(self):
return self.base
def get_label(self):
return self.label
def __str__(self):
return f'base: {self.base}, dep: {self.dependencies}'
def __repr__(self):
return self.label
# in order to compare class elements, you must create a custom "less than" function
# it is the basis of sort
def __lt__(self, other: 'Element'):
# case 1: both are singletons, just alphabetically sort them:
if self.dependencies is None and other.dependencies is None:
return self.label < other.label
# case 2: self has no dependencies, but other does
elif self.dependencies is None and other.dependencies is not None:
return True
# case 3: other has no dependencies, self does
elif other.dependencies is None and self.dependencies is not None:
return False
# case 4: both have dependencies, check if self depends on other:
else:
if self.base in other.dependencies:
return True
elif other.base in self.dependencies:
return False
else: # sort by the base element
return self.base < other.base
data = ['B', 'A', 'C|A,E', 'E', 'B|C,D', 'D']
# make "elements" from the strings
elements = [Element(t) for t in data]
elements.sort()
print(elements)
# example
print(elements[4].get_dependencies())
Output:
[A, B, D, E, C|A,E, B|C,D]
{'A', 'E'}
A:
ideally you should create a dependacy tree and start from adding the leafs and removing the leafs.
however for simpe example as yours you could just do a simple queue and start appending in your called "sorted" array
import queue
a = list(filter(lambda x: len(x) == 1, verbose_struct ))
b = {x.split('|')[0]: tuple(x.split('|')[1].split(',')) for x in filter(lambda x: len(x) > 1, verbose_struct )}
nodes = a[:]
q = queue.deque(b.keys())
while q:
cur = q.pop()
if all(map(lambda x: x in nodes, b[cur])):
nodes.append(cur[0])
a.append(f"{cur}|" + ",".join(b[cur]))
else:
q.appendleft(cur)
a will be your sorted output
|
Sorting list of strings based on both sides of a delimiter ("|") in Python 3
|
I'm looking to sort a list of of strings which illustrate dependencies (the structure of a Bayesian Networks determined through the PC Algorithm).
e.g.
verbose_struct = ['A', 'C|A,E', 'E', 'B|C,D', 'D']
sorted_struct = ['A', 'E', 'D', 'C|A,E', 'B|C,D']
The order of the strings is determined by whether or not the dependencies (the letters following the delimiter '|', e.g. B is dependent on C and D) have been previously listed. As in the above, 'E' should be positioned before 'C|A,E' as C is dependent on E. Strings with no dependencies should be positioned before all strings with dependencies, e.g. 'D' before 'C|A,E' and 'B|C,D'.
How would I go about this?
I have managed to order the strings by whether or not they have dependencies using the following:
sorted_struct = sorted(verbose_struct, key=lambda x: len(x.split('|')))
I am unsure how to then further sort the variables by their dependencies, as I am fairly unfamiliar with lambda functions in Python.
|
[
"I would just \"make the jump\" here to making a class to hold these objects. by doing so, you can implement your own __lt__ method, which is all that is needed for all of the default sorting methods to sort the objects.\nNote: This example class just deals with \"labels\" so when you are adding dependencies, you are just adding labels of other things. A more sophisticated class would hold the Element values of the dependencies instead of the labels, then you could kinda chain things together by looking up the dependencies of the dependencies, which you cannot do with this simple example. In order to make that work, you would need to define things in some kind of logical order (or do something more complicated) so that the earliest dependencies in the tree were added first. There are probably a bunch of examples out there for node-arc setups (which is what this describes) that do that.\nThe main thing here is that you can make a custom function to enable sorting by comparing 2 elements. You could also \"peel out\" this 2-item comparison function, make the pieces on the fly, and pass that function to the sort() method and it would also work without the class.\nCode:\n# Bayesian Elements\n\nclass Element():\n\n def __init__(self, data: str):\n self.label = data\n if '|' in data:\n # dependency...break it up\n self.base, dependencies = data.split('|')\n # break up the dependencies\n self.dependencies = set(dependencies.split(','))\n else: # it is a single base element\n self.base = data\n self.dependencies = None\n\n def get_dependencies(self):\n return self.dependencies\n\n def get_base(self):\n return self.base\n\n def get_label(self):\n return self.label\n\n def __str__(self):\n return f'base: {self.base}, dep: {self.dependencies}'\n\n def __repr__(self):\n return self.label\n\n # in order to compare class elements, you must create a custom \"less than\" function\n # it is the basis of sort\n def __lt__(self, other: 'Element'):\n # case 1: both are singletons, just alphabetically sort them:\n if self.dependencies is None and other.dependencies is None:\n return self.label < other.label\n # case 2: self has no dependencies, but other does\n elif self.dependencies is None and other.dependencies is not None:\n return True\n # case 3: other has no dependencies, self does\n elif other.dependencies is None and self.dependencies is not None:\n return False\n # case 4: both have dependencies, check if self depends on other:\n else:\n if self.base in other.dependencies:\n return True\n elif other.base in self.dependencies:\n return False\n else: # sort by the base element\n return self.base < other.base\n\ndata = ['B', 'A', 'C|A,E', 'E', 'B|C,D', 'D']\n\n# make \"elements\" from the strings\nelements = [Element(t) for t in data]\n\nelements.sort()\n\nprint(elements)\n\n# example\nprint(elements[4].get_dependencies())\n\nOutput:\n[A, B, D, E, C|A,E, B|C,D]\n{'A', 'E'}\n\n",
"ideally you should create a dependacy tree and start from adding the leafs and removing the leafs.\nhowever for simpe example as yours you could just do a simple queue and start appending in your called \"sorted\" array\nimport queue\n\na = list(filter(lambda x: len(x) == 1, verbose_struct ))\nb = {x.split('|')[0]: tuple(x.split('|')[1].split(',')) for x in filter(lambda x: len(x) > 1, verbose_struct )}\nnodes = a[:]\nq = queue.deque(b.keys())\nwhile q:\n cur = q.pop()\n if all(map(lambda x: x in nodes, b[cur])):\n nodes.append(cur[0])\n a.append(f\"{cur}|\" + \",\".join(b[cur]))\n else:\n q.appendleft(cur)\n\na will be your sorted output\n"
] |
[
1,
0
] |
[] |
[] |
[
"bayesian_networks",
"python",
"python_3.x",
"sorting"
] |
stackoverflow_0074491679_bayesian_networks_python_python_3.x_sorting.txt
|
Q:
fixing date shape in pandas
dataset in question
Hello, I have been trying to standardize the date in the year column to get rid of the decimals and and the random format and keep only the years.
Is there an efficient way to do this in Pandas?
A:
Setup
import pandas as pd # 1.5.1
so = pd.DataFrame({
"Countries": [*["Canada"]*5, *["Brazil"]*5],
"Year": [1990.0, 1991.0, 1992.0, 1993.0, 1994.0, 2020.0, 2021.0, 2021.0, "2011-21", 2021.0],
"Value": 1 # placeholder
})
print(so)
Countries Year Value
0 Canada 1990.0 1
1 Canada 1991.0 1
2 Canada 1992.0 1
3 Canada 1993.0 1
4 Canada 1994.0 1
5 Brazil 2020.0 1
6 Brazil 2021.0 1
7 Brazil 2021.0 1
8 Brazil 2011-21 1
9 Brazil 2021.0 1
Explanation
Inspecting the .dtype of so.Year we get object
print(so.Year.dtype)
object
I'm making an assumption that all years in so.Year will be 4-digit, so I convert to str and limit to the first four characters
so["NewYear"] = so.Year.astype(str).str[:4]
print(so)
Countries Year Value NewYear
0 Canada 1990.0 1 1990
1 Canada 1991.0 1 1991
2 Canada 1992.0 1 1992
3 Canada 1993.0 1 1993
4 Canada 1994.0 1 1994
5 Brazil 2020.0 1 2020
6 Brazil 2021.0 1 2021
7 Brazil 2021.0 1 2021
8 Brazil 2011-21 1 2011
9 Brazil 2021.0 1 2021
Now you can either use the NewYear column as-is, or convert to some other dtype.
|
fixing date shape in pandas
|
dataset in question
Hello, I have been trying to standardize the date in the year column to get rid of the decimals and and the random format and keep only the years.
Is there an efficient way to do this in Pandas?
|
[
"Setup\nimport pandas as pd # 1.5.1\n\n\nso = pd.DataFrame({\n \"Countries\": [*[\"Canada\"]*5, *[\"Brazil\"]*5],\n \"Year\": [1990.0, 1991.0, 1992.0, 1993.0, 1994.0, 2020.0, 2021.0, 2021.0, \"2011-21\", 2021.0],\n \"Value\": 1 # placeholder\n})\n\nprint(so)\n\n Countries Year Value\n0 Canada 1990.0 1\n1 Canada 1991.0 1\n2 Canada 1992.0 1\n3 Canada 1993.0 1\n4 Canada 1994.0 1\n5 Brazil 2020.0 1\n6 Brazil 2021.0 1\n7 Brazil 2021.0 1\n8 Brazil 2011-21 1\n9 Brazil 2021.0 1\n\nExplanation\nInspecting the .dtype of so.Year we get object\nprint(so.Year.dtype)\n\nobject\n\nI'm making an assumption that all years in so.Year will be 4-digit, so I convert to str and limit to the first four characters\nso[\"NewYear\"] = so.Year.astype(str).str[:4]\n\nprint(so)\n\n Countries Year Value NewYear\n0 Canada 1990.0 1 1990\n1 Canada 1991.0 1 1991\n2 Canada 1992.0 1 1992\n3 Canada 1993.0 1 1993\n4 Canada 1994.0 1 1994\n5 Brazil 2020.0 1 2020\n6 Brazil 2021.0 1 2021\n7 Brazil 2021.0 1 2021\n8 Brazil 2011-21 1 2011\n9 Brazil 2021.0 1 2021\n\nNow you can either use the NewYear column as-is, or convert to some other dtype.\n"
] |
[
0
] |
[] |
[] |
[
"dataframe",
"pandas",
"python",
"python_3.x"
] |
stackoverflow_0074493847_dataframe_pandas_python_python_3.x.txt
|
Q:
Get a column, modify, re insert into dataframe as new column?
I have a dataframe and I am pulling out a specific column with the index. I want to perform a split on that column and get the [1] value.
The column looks like;
Name
t_alpaha_omega
t_bravo_omega
d_charlie_omega
t_delta_omega
I need to split on _ and get alpha, bravo, charlie, delta. Then add those values as a new column in my dataframe.
I am getting the name column like;
final_df.loc[:,"Name"]
I can do the splitting, I just don't know how to insert the data as a new column.
I am playing with this and seeing if I can use a variation of it.
final_df.insert(1, "Test", final_df.loc[:,"Name"], True)
A:
Hope the below code helps.
newCol= []
for i in range(len(df)):
a = df.iloc[i].to_list()
requiredValue = a.split("_")[1]
newCol.append(requiredValue)
df["newValue"] = requiredValue
It works perfectly for a string though.
A:
For this purpose we could use pd.Series.str.extract and define a named capturing group like (?P<New_Column_Name>...):
df['Value'] = df.Name.str.extract('(?P<Value>(?<=_)\w+(?=_))')
df
Name Value
0 t_alpaha_omega alpaha
1 t_bravo_omega bravo
2 t_charlie_omega charlie
3 t_delta_omega delta
If you would like to change the position of the column. We could first extract it with pd.Series.pop and the we insert it at the column index we would like:
new_column = df.pop('Value')
df.insert(0, 'Value', new_column)
Value Name
0 alpaha t_alpaha_omega
1 bravo t_bravo_omega
2 charlie t_charlie_omega
3 delta t_delta_omega
|
Get a column, modify, re insert into dataframe as new column?
|
I have a dataframe and I am pulling out a specific column with the index. I want to perform a split on that column and get the [1] value.
The column looks like;
Name
t_alpaha_omega
t_bravo_omega
d_charlie_omega
t_delta_omega
I need to split on _ and get alpha, bravo, charlie, delta. Then add those values as a new column in my dataframe.
I am getting the name column like;
final_df.loc[:,"Name"]
I can do the splitting, I just don't know how to insert the data as a new column.
I am playing with this and seeing if I can use a variation of it.
final_df.insert(1, "Test", final_df.loc[:,"Name"], True)
|
[
"Hope the below code helps.\nnewCol= [] \nfor i in range(len(df)):\n a = df.iloc[i].to_list()\n requiredValue = a.split(\"_\")[1]\n newCol.append(requiredValue)\ndf[\"newValue\"] = requiredValue\n\nIt works perfectly for a string though.\n\n",
"For this purpose we could use pd.Series.str.extract and define a named capturing group like (?P<New_Column_Name>...):\ndf['Value'] = df.Name.str.extract('(?P<Value>(?<=_)\\w+(?=_))')\ndf\n\n Name Value\n0 t_alpaha_omega alpaha\n1 t_bravo_omega bravo\n2 t_charlie_omega charlie\n3 t_delta_omega delta\n\nIf you would like to change the position of the column. We could first extract it with pd.Series.pop and the we insert it at the column index we would like:\nnew_column = df.pop('Value')\ndf.insert(0, 'Value', new_column)\n\n Value Name\n0 alpaha t_alpaha_omega\n1 bravo t_bravo_omega\n2 charlie t_charlie_omega\n3 delta t_delta_omega\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074494263_dataframe_pandas_python.txt
|
Q:
thread communication, stop the work of a thread until data is entered PySide
I've written a simple window with a start button that starts a Qthread. After a few instructions in the thread, I would like to display a SubWindow using Signal. Unfortunately, Qthread does not stop after displaying subWindow.
I'm looking for a solution like while Qthread is running: stop the Qthread, display a SubWindow, input the data, and send it directly to the Qthread, then start the thread.
One way I can think of is to open a window directly from the thread, but I don't think that's necessarily a good practice because I need to create a new instance of the app. In addition, there is still the problem of sending data from SubWindow to the thread
Problems:
how to stop Qthread while displaying sub window
how to pass data from sub window to Qthread
Code:
from PySide2 import QtWidgets
from PySide2 import QtCore
import sys, time
class InsertWindow(QtWidgets.QDialog):
signal_return_data = QtCore.Signal(str)
def __init__(self):
super().__init__()
self.layout = QtWidgets.QVBoxLayout()
self.line = QtWidgets.QLineEdit("")
self.push = QtWidgets.QPushButton("Send")
self.push.clicked.connect(self.send_it)
self.layout.addWidget(self.line)
self.layout.addWidget(self.push)
self.setLayout(self.layout)
def send_it(self):
if self.line.text() == '':
msg = QtWidgets.QMessageBox()
msg.setText("Not Empty")
msg.show
else:
self.signal_return_data.emit(self.line.text())
self.close()
class Window(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.layout = QtWidgets.QVBoxLayout()
self.txt = QtWidgets.QLabel("Welcome!")
self.push = QtWidgets.QPushButton("Start")
self.progres = QtWidgets.QProgressBar()
self.layout.addWidget(self.txt)
self.layout.addWidget(self.push)
self.layout.addWidget(self.progres)
self.setLayout(self.layout)
self.push.clicked.connect(self.p_start)
def show_insert_popup(self):
self.insert_win = InsertWindow()
self.insert_win.signal_return_data.connect(self.send_to_thread)
self.insert_win.exec_()
def p_start(self):
self.progres.setMinimum(0)
self.progres.setMaximum(0)
self.worker = Worker()
self.worker.signal_open_insert.connect(self.show_insert_popup)
self.worker.finished.connect(self.stop_)
self.worker.start()
def stop_(self):
self.progres.setMinimum(0)
self.progres.setMaximum(100)
@QtCore.Slot(str)
def send_to_thread(self, txt):
self.txt.setText(f"{txt} Get It here, but need it in thread")
class Worker(QtCore.QThread):
signal_open_insert = QtCore.Signal()
def run(self):
for x in range(2):
print("I working in thread")
time.sleep(2)
# here I need stop thread (until the data will entered ), open subwindow, and get entered data to display
self.signal_open_insert.emit()
for x in range(2):
print("Here i would like display dafa from insert window")
time.sleep(1)
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.show()
app.exec_()
A:
probably just send it over a queue, queue.get() is a blocking function so it will pause the thread execution until someone puts something in the queue.
just create a queue in the caller, let's call it result_queue, the child will call result_queue.get() on it to sleep and wait for an item to be put in it and the main thread will put the txt in it using self.result_queue.put(txt).
just make sure you always put something in it even if an exception happens or the user cancels the operation otherwise the thread will hang forever, as i did by overriding the reject method of the dialog box.
from PySide2 import QtWidgets
from PySide2 import QtCore
import sys, time
import queue
from typing import Optional
class InsertWindow(QtWidgets.QDialog):
signal_return_data = QtCore.Signal(str)
def __init__(self):
super().__init__()
self.layout = QtWidgets.QVBoxLayout()
self.line = QtWidgets.QLineEdit("")
self.push = QtWidgets.QPushButton("Send")
self.push.clicked.connect(self.send_it)
self.layout.addWidget(self.line)
self.layout.addWidget(self.push)
self.setLayout(self.layout)
def reject(self) -> None:
self.signal_return_data.emit('')
super().reject()
def send_it(self):
if self.line.text() == '':
msg = QtWidgets.QMessageBox()
msg.setText("Not Empty")
msg.show
else:
self.signal_return_data.emit(self.line.text())
self.close()
class Window(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.layout = QtWidgets.QVBoxLayout()
self.txt = QtWidgets.QLabel("Welcome!")
self.push = QtWidgets.QPushButton("Start")
self.progres = QtWidgets.QProgressBar()
self.layout.addWidget(self.txt)
self.layout.addWidget(self.push)
self.layout.addWidget(self.progres)
self.setLayout(self.layout)
self.push.clicked.connect(self.p_start)
self.result_queue: Optional[queue.Queue] = None
def show_insert_popup(self):
self.insert_win = InsertWindow()
self.insert_win.signal_return_data.connect(self.send_to_thread)
self.insert_win.exec_()
def p_start(self):
self.progres.setMinimum(0)
self.progres.setMaximum(0)
self.result_queue = queue.Queue()
self.worker = Worker(self.result_queue)
self.worker.signal_open_insert.connect(self.show_insert_popup)
self.worker.finished.connect(self.stop_)
self.worker.start()
def stop_(self):
self.progres.setMinimum(0)
self.progres.setMaximum(100)
@QtCore.Slot(str)
def send_to_thread(self, txt):
self.result_queue.put(txt)
self.txt.setText(f"{txt} Get It here, but need it in thread")
class Worker(QtCore.QThread):
signal_open_insert = QtCore.Signal()
def __init__(self, results_queue: queue.Queue):
self.results_queue = results_queue
super().__init__()
def run(self):
for x in range(2):
print("I working in thread")
time.sleep(2)
# here I need stop thread (until the data will entered ), open subwindow, and get entered data to display
self.signal_open_insert.emit()
result = self.results_queue.get()
for x in range(2):
print("Here i would like display dafa from insert window")
print(result)
time.sleep(1)
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.show()
app.exec_()
|
thread communication, stop the work of a thread until data is entered PySide
|
I've written a simple window with a start button that starts a Qthread. After a few instructions in the thread, I would like to display a SubWindow using Signal. Unfortunately, Qthread does not stop after displaying subWindow.
I'm looking for a solution like while Qthread is running: stop the Qthread, display a SubWindow, input the data, and send it directly to the Qthread, then start the thread.
One way I can think of is to open a window directly from the thread, but I don't think that's necessarily a good practice because I need to create a new instance of the app. In addition, there is still the problem of sending data from SubWindow to the thread
Problems:
how to stop Qthread while displaying sub window
how to pass data from sub window to Qthread
Code:
from PySide2 import QtWidgets
from PySide2 import QtCore
import sys, time
class InsertWindow(QtWidgets.QDialog):
signal_return_data = QtCore.Signal(str)
def __init__(self):
super().__init__()
self.layout = QtWidgets.QVBoxLayout()
self.line = QtWidgets.QLineEdit("")
self.push = QtWidgets.QPushButton("Send")
self.push.clicked.connect(self.send_it)
self.layout.addWidget(self.line)
self.layout.addWidget(self.push)
self.setLayout(self.layout)
def send_it(self):
if self.line.text() == '':
msg = QtWidgets.QMessageBox()
msg.setText("Not Empty")
msg.show
else:
self.signal_return_data.emit(self.line.text())
self.close()
class Window(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.layout = QtWidgets.QVBoxLayout()
self.txt = QtWidgets.QLabel("Welcome!")
self.push = QtWidgets.QPushButton("Start")
self.progres = QtWidgets.QProgressBar()
self.layout.addWidget(self.txt)
self.layout.addWidget(self.push)
self.layout.addWidget(self.progres)
self.setLayout(self.layout)
self.push.clicked.connect(self.p_start)
def show_insert_popup(self):
self.insert_win = InsertWindow()
self.insert_win.signal_return_data.connect(self.send_to_thread)
self.insert_win.exec_()
def p_start(self):
self.progres.setMinimum(0)
self.progres.setMaximum(0)
self.worker = Worker()
self.worker.signal_open_insert.connect(self.show_insert_popup)
self.worker.finished.connect(self.stop_)
self.worker.start()
def stop_(self):
self.progres.setMinimum(0)
self.progres.setMaximum(100)
@QtCore.Slot(str)
def send_to_thread(self, txt):
self.txt.setText(f"{txt} Get It here, but need it in thread")
class Worker(QtCore.QThread):
signal_open_insert = QtCore.Signal()
def run(self):
for x in range(2):
print("I working in thread")
time.sleep(2)
# here I need stop thread (until the data will entered ), open subwindow, and get entered data to display
self.signal_open_insert.emit()
for x in range(2):
print("Here i would like display dafa from insert window")
time.sleep(1)
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.show()
app.exec_()
|
[
"probably just send it over a queue, queue.get() is a blocking function so it will pause the thread execution until someone puts something in the queue.\njust create a queue in the caller, let's call it result_queue, the child will call result_queue.get() on it to sleep and wait for an item to be put in it and the main thread will put the txt in it using self.result_queue.put(txt).\njust make sure you always put something in it even if an exception happens or the user cancels the operation otherwise the thread will hang forever, as i did by overriding the reject method of the dialog box.\nfrom PySide2 import QtWidgets\nfrom PySide2 import QtCore\nimport sys, time\nimport queue\nfrom typing import Optional\n\nclass InsertWindow(QtWidgets.QDialog):\n signal_return_data = QtCore.Signal(str)\n\n def __init__(self):\n super().__init__()\n\n self.layout = QtWidgets.QVBoxLayout()\n self.line = QtWidgets.QLineEdit(\"\")\n self.push = QtWidgets.QPushButton(\"Send\")\n self.push.clicked.connect(self.send_it)\n self.layout.addWidget(self.line)\n self.layout.addWidget(self.push)\n self.setLayout(self.layout)\n\n def reject(self) -> None:\n self.signal_return_data.emit('')\n super().reject()\n\n def send_it(self):\n if self.line.text() == '':\n msg = QtWidgets.QMessageBox()\n msg.setText(\"Not Empty\")\n msg.show\n else:\n self.signal_return_data.emit(self.line.text())\n self.close()\n\n\nclass Window(QtWidgets.QWidget):\n def __init__(self):\n super().__init__()\n\n self.layout = QtWidgets.QVBoxLayout()\n self.txt = QtWidgets.QLabel(\"Welcome!\")\n self.push = QtWidgets.QPushButton(\"Start\")\n self.progres = QtWidgets.QProgressBar()\n self.layout.addWidget(self.txt)\n self.layout.addWidget(self.push)\n self.layout.addWidget(self.progres)\n self.setLayout(self.layout)\n self.push.clicked.connect(self.p_start)\n self.result_queue: Optional[queue.Queue] = None\n\n def show_insert_popup(self):\n self.insert_win = InsertWindow()\n self.insert_win.signal_return_data.connect(self.send_to_thread)\n self.insert_win.exec_()\n\n def p_start(self):\n self.progres.setMinimum(0)\n self.progres.setMaximum(0)\n self.result_queue = queue.Queue()\n self.worker = Worker(self.result_queue)\n self.worker.signal_open_insert.connect(self.show_insert_popup)\n self.worker.finished.connect(self.stop_)\n self.worker.start()\n\n def stop_(self):\n self.progres.setMinimum(0)\n self.progres.setMaximum(100)\n\n @QtCore.Slot(str)\n def send_to_thread(self, txt):\n self.result_queue.put(txt)\n self.txt.setText(f\"{txt} Get It here, but need it in thread\")\n\n\nclass Worker(QtCore.QThread):\n signal_open_insert = QtCore.Signal()\n\n def __init__(self, results_queue: queue.Queue):\n self.results_queue = results_queue\n super().__init__()\n\n def run(self):\n for x in range(2):\n print(\"I working in thread\")\n time.sleep(2)\n\n # here I need stop thread (until the data will entered ), open subwindow, and get entered data to display\n self.signal_open_insert.emit()\n result = self.results_queue.get()\n\n for x in range(2):\n print(\"Here i would like display dafa from insert window\")\n print(result)\n time.sleep(1)\n\n\napp = QtWidgets.QApplication(sys.argv)\nwindow = Window()\nwindow.show()\napp.exec_()\n\n"
] |
[
0
] |
[] |
[] |
[
"multithreading",
"pyside",
"python"
] |
stackoverflow_0074493500_multithreading_pyside_python.txt
|
Q:
NameError: name 'dishID' is not defined. Did you mean: 'dishid'?
this is the code of the following function
Function:
def dishID():
query = 'select count(*), max(DishID) from Dish'
cur.execute(query)
fetch = cur.fetchall()
for i in fetch:
if i[0] == 0:
return 1
else:
return (int(i[1]) + 1)
Error code
dishname = input('Enter Dish Name: ')
dishprice = input('Enter Dish Price: ')
dishid = str(dishID())
query = 'insert into Dish values({}, {}, {})'.format(
dishname, dishprice, dishid)
cur.execute(query)
con.commit()
print("Dish has added successfully")
Full code: https://srcb.in/l1RdtphmhF
This is code is restaurant Database management system. I am taking the help of mysql and making this system. all the functions work fine but when i call the dishID function it produces an error where it cant read the function. To be precise i want the code to work so it can insert some values
A:
Okay I looked at your link and the issue is extremely simple; you defined the function dishID only after you actually call it. Here's a simple example of this issue - here's some code that works fine:
def test_function():
print('hi')
test_function()
Output: hi
Versus this code, which references test_function before its definition:
test_function()
def test_function():
print('hi')
Output: NameError: name 'test_function' is not defined
|
NameError: name 'dishID' is not defined. Did you mean: 'dishid'?
|
this is the code of the following function
Function:
def dishID():
query = 'select count(*), max(DishID) from Dish'
cur.execute(query)
fetch = cur.fetchall()
for i in fetch:
if i[0] == 0:
return 1
else:
return (int(i[1]) + 1)
Error code
dishname = input('Enter Dish Name: ')
dishprice = input('Enter Dish Price: ')
dishid = str(dishID())
query = 'insert into Dish values({}, {}, {})'.format(
dishname, dishprice, dishid)
cur.execute(query)
con.commit()
print("Dish has added successfully")
Full code: https://srcb.in/l1RdtphmhF
This is code is restaurant Database management system. I am taking the help of mysql and making this system. all the functions work fine but when i call the dishID function it produces an error where it cant read the function. To be precise i want the code to work so it can insert some values
|
[
"Okay I looked at your link and the issue is extremely simple; you defined the function dishID only after you actually call it. Here's a simple example of this issue - here's some code that works fine:\ndef test_function():\n print('hi')\n\ntest_function()\n\nOutput: hi\n\nVersus this code, which references test_function before its definition:\ntest_function()\n\ndef test_function():\n print('hi')\n\nOutput: NameError: name 'test_function' is not defined\n\n"
] |
[
0
] |
[] |
[] |
[
"function",
"mysql",
"mysql_connector",
"python"
] |
stackoverflow_0074494295_function_mysql_mysql_connector_python.txt
|
Q:
Calculate mean/median of values in a column based on dates of another column using Python
I have a dataframe consisting of temperature values on one column, and the corresponding dates on another column.
The dataframe has a time period of 7 days, with measurements taken every minute, the problem is that I don't know how to calculate the mean/median of the temperature and see the output per day.
Any thoughts?
The data looks like this
A:
Firstly, make sure that the 'Timestamp_0' colum is in datetime format. df.Timestamp_0 = pd.to_datetime(df.Timestamp_0)
Then, create a column of day: df['day'] = df['Timestamp_0'].dt.day
Then group the Temperature values by that newly created column and apply either mean or median function:
per_day_mean_temp = df.groupby('day').mean()
or
per_day_median_temp = df.groupby('day').median()
|
Calculate mean/median of values in a column based on dates of another column using Python
|
I have a dataframe consisting of temperature values on one column, and the corresponding dates on another column.
The dataframe has a time period of 7 days, with measurements taken every minute, the problem is that I don't know how to calculate the mean/median of the temperature and see the output per day.
Any thoughts?
The data looks like this
|
[
"Firstly, make sure that the 'Timestamp_0' colum is in datetime format. df.Timestamp_0 = pd.to_datetime(df.Timestamp_0)\nThen, create a column of day: df['day'] = df['Timestamp_0'].dt.day\nThen group the Temperature values by that newly created column and apply either mean or median function:\nper_day_mean_temp = df.groupby('day').mean()\n\nor\nper_day_median_temp = df.groupby('day').median()\n\n"
] |
[
1
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074494320_pandas_python.txt
|
Q:
python readline module giving PermissionError: [Errno 1] only when run at startup
I'm making a console based game that saves input history, to help with debugging I created a function that will automatically input commands on start
def __readfile (self) -> None:
lines = None
with open("insts.txt", "r") as f:
lines = f.read().split("\n")
if (lines == None):
print("attempted to read insts.txt for instructions, could not find file")
return
self.__initfile = True
for line in lines:
self.parse_input(line)
self.__initfile = False
in the instance of the error "self.parse_input" ultimately leads to "readline.read_history_file" and none of the code in between the two has any effect on the error
but it gives this error message:
Traceback (most recent call last):
File "main.py", line 9, in <module>
game.start()
File "/Users/tristans/Documents/GitHub/console-rpg/classes.py", line 1353, in start
self.__readfile()
File "/Users/tristans/Documents/GitHub/console-rpg/classes.py", line 1345, in __readfile
self.parse_input(line)
File "/Users/tristans/Documents/GitHub/console-rpg/classes.py", line 1223, in parse_input
self._parse_dialog(text)
File "/Users/tristans/Documents/GitHub/console-rpg/classes.py", line 1128, in _parse_dialog
self._parse_dialog("leave")
File "/Users/tristans/Documents/GitHub/console-rpg/classes.py", line 1101, in _parse_dialog
self._load_hist_scope()
File "/Users/tristans/Documents/GitHub/console-rpg/classes.py", line 1331, in _load_hist_scope
readline.read_history_file("history.txt")
PermissionError: [Errno 1] Operation not permitted
I have looked everywhere for an answer to where this error is coming from and can't find one
I've tried changing the file read operation from the "with open("insts.txt")" to a hardcoded list but that didn't work, os.access("history.txt", os.R_OK) also returns true when called just before "readline.read_history_file"
A:
It appears to be a Mac-specific issue with readline. According to this answer, you need to use gnureadline on the Mac, rather than readline.
import gnureadline as readline
|
python readline module giving PermissionError: [Errno 1] only when run at startup
|
I'm making a console based game that saves input history, to help with debugging I created a function that will automatically input commands on start
def __readfile (self) -> None:
lines = None
with open("insts.txt", "r") as f:
lines = f.read().split("\n")
if (lines == None):
print("attempted to read insts.txt for instructions, could not find file")
return
self.__initfile = True
for line in lines:
self.parse_input(line)
self.__initfile = False
in the instance of the error "self.parse_input" ultimately leads to "readline.read_history_file" and none of the code in between the two has any effect on the error
but it gives this error message:
Traceback (most recent call last):
File "main.py", line 9, in <module>
game.start()
File "/Users/tristans/Documents/GitHub/console-rpg/classes.py", line 1353, in start
self.__readfile()
File "/Users/tristans/Documents/GitHub/console-rpg/classes.py", line 1345, in __readfile
self.parse_input(line)
File "/Users/tristans/Documents/GitHub/console-rpg/classes.py", line 1223, in parse_input
self._parse_dialog(text)
File "/Users/tristans/Documents/GitHub/console-rpg/classes.py", line 1128, in _parse_dialog
self._parse_dialog("leave")
File "/Users/tristans/Documents/GitHub/console-rpg/classes.py", line 1101, in _parse_dialog
self._load_hist_scope()
File "/Users/tristans/Documents/GitHub/console-rpg/classes.py", line 1331, in _load_hist_scope
readline.read_history_file("history.txt")
PermissionError: [Errno 1] Operation not permitted
I have looked everywhere for an answer to where this error is coming from and can't find one
I've tried changing the file read operation from the "with open("insts.txt")" to a hardcoded list but that didn't work, os.access("history.txt", os.R_OK) also returns true when called just before "readline.read_history_file"
|
[
"It appears to be a Mac-specific issue with readline. According to this answer, you need to use gnureadline on the Mac, rather than readline.\nimport gnureadline as readline\n\n"
] |
[
0
] |
[] |
[] |
[
"permission_denied",
"python",
"readline"
] |
stackoverflow_0070735564_permission_denied_python_readline.txt
|
Q:
pyodbc with MultiSubnetFailover
Recently, one of our servers was migrated to 3-node cluster from a pylon server. The connection string below is what I used previously via python and pyodbc and never had any issues.
server = 'test_server'
database = 'test_db'
cnxn = 'DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';Trusted_Connection=yes'
With the new server I started receiving time out errors. So i thought I had to add MultiSubnetFailover to the connection string such as the following
server = 'test_server'
database = 'test_db'
cnxn = 'DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';Trusted_Connection=yes;MultiSubnetFailover=True'
However, I am still receiving a time out error as well as an additiaonl error seen below
[Microsoft][ODBC SQL Server Driver]Login timeout expired (0) (SQLDriverConnect); [HYT00] [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (0)
Does pyodbc support MultiSubnetFailover? I couldn't find documentation one way or another.
If so, how do I implement it? On the other side, if it does not, how would i go about connecting?
Lastly, should I use the IP address instead?
A:
The ancient SQL Server ODBC driver that ships with Windows doesn't support MultiSubnetFailover. I suggest you move to a modern driver or have your DBA set RegisterAllProvidersIP to zero to support down level clients.
In the interim, you could specify the current listener IP address or the host name of the current primary node. However, that will fail if the primary is failed over to a secondary node on a different subnet.
|
pyodbc with MultiSubnetFailover
|
Recently, one of our servers was migrated to 3-node cluster from a pylon server. The connection string below is what I used previously via python and pyodbc and never had any issues.
server = 'test_server'
database = 'test_db'
cnxn = 'DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';Trusted_Connection=yes'
With the new server I started receiving time out errors. So i thought I had to add MultiSubnetFailover to the connection string such as the following
server = 'test_server'
database = 'test_db'
cnxn = 'DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';Trusted_Connection=yes;MultiSubnetFailover=True'
However, I am still receiving a time out error as well as an additiaonl error seen below
[Microsoft][ODBC SQL Server Driver]Login timeout expired (0) (SQLDriverConnect); [HYT00] [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (0)
Does pyodbc support MultiSubnetFailover? I couldn't find documentation one way or another.
If so, how do I implement it? On the other side, if it does not, how would i go about connecting?
Lastly, should I use the IP address instead?
|
[
"The ancient SQL Server ODBC driver that ships with Windows doesn't support MultiSubnetFailover. I suggest you move to a modern driver or have your DBA set RegisterAllProvidersIP to zero to support down level clients.\nIn the interim, you could specify the current listener IP address or the host name of the current primary node. However, that will fail if the primary is failed over to a secondary node on a different subnet.\n"
] |
[
0
] |
[] |
[] |
[
"database_connection",
"odbc",
"pyodbc",
"python",
"sql_server"
] |
stackoverflow_0074494262_database_connection_odbc_pyodbc_python_sql_server.txt
|
Q:
How do I call the function next() without type it again?
The idea is to be able to call the next number every time it is called data, but as you know I cant type next() everytime in the code, is there a way to achieve that? thanks for your help.
class Sample():
def __init__(self, begin, end):
self.begin = begin
self.end = end
#self.counter = 0
def number(self):
for i in range(self.begin, self.end):
#self.counter +=1
yield i
instance = Sample(begin=525, end=535)
data = instance.number()
print(next(data))
print(next(data))
print(next(data))
I cant use loops this time becuse I want to get one number one by one everytime it called data, example call data: 526. calls data 527. calls data 527 like this. not 526,527,528,529...... thanks
A:
You can hide the call to next() in a property getter.
class Sample():
def __init__(self, begin, end):
self.begin = begin
self.end = end
self._sequence = self.number()
def number(self):
for i in range(self.begin, self.end):
yield i
@property
def counter(self):
return next(self._sequence)
instance = Sample(begin=525, end=535)
print(instance.counter) # prints 525
print(instance.counter) # prints 526
However, if you use it this way, you'll need your own handler for the StopIteration exception that's raised when you reach the end of the iterator.
|
How do I call the function next() without type it again?
|
The idea is to be able to call the next number every time it is called data, but as you know I cant type next() everytime in the code, is there a way to achieve that? thanks for your help.
class Sample():
def __init__(self, begin, end):
self.begin = begin
self.end = end
#self.counter = 0
def number(self):
for i in range(self.begin, self.end):
#self.counter +=1
yield i
instance = Sample(begin=525, end=535)
data = instance.number()
print(next(data))
print(next(data))
print(next(data))
I cant use loops this time becuse I want to get one number one by one everytime it called data, example call data: 526. calls data 527. calls data 527 like this. not 526,527,528,529...... thanks
|
[
"You can hide the call to next() in a property getter.\nclass Sample():\n def __init__(self, begin, end):\n self.begin = begin\n self.end = end\n self._sequence = self.number()\n\n def number(self):\n for i in range(self.begin, self.end):\n yield i\n\n @property\n def counter(self):\n return next(self._sequence)\n\ninstance = Sample(begin=525, end=535)\n\nprint(instance.counter) # prints 525\nprint(instance.counter) # prints 526\n\nHowever, if you use it this way, you'll need your own handler for the StopIteration exception that's raised when you reach the end of the iterator.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0074493990_python_python_3.x.txt
|
Q:
F-string with jinja templating in airflow to pass dynamic values to op_kwargs
I am trying to pull values using xcom_pull in airflow dynamically
The below mentioned formatting doesn't work for me when I piece together jinja templating with f-strings in op_kwargs. Appreciate if anyone can help me here.
op_kwargs={'names':"{{ ti.xcom_pull(key = '" + f'name{i+1}' + ", task_ids='places' ) }}"}
A:
Using fstring require to set proper number of brackets for Jinja. You can do:
op_kwargs={'names': f"{{{{ ti.xcom_pull(key='name{i+1}', task_ids='places') }}}}"}
Example (This is just a minimal example for your parameters to clarify how this works):
from datetime import datetime
from airflow import DAG
from airflow.operators.python import PythonOperator
default_args = {
'owner': 'airflow',
'start_date': datetime(2017, 2, 1)
}
def func1(ti):
ti.xcom_push(key="name2", value="helloworld")
def func2(names):
print(names)
with DAG('fstring_dag', default_args=default_args, catchup=False, schedule=None):
a = PythonOperator(
task_id='places',
python_callable=func1,
)
i = 1
b = PythonOperator(
task_id='places2',
python_callable=func2,
op_kwargs={'names': f"{{{{ ti.xcom_pull(key='name{i+1}', task_ids='places') }}}}"}
)
a >> b
Render tab:
Log:
|
F-string with jinja templating in airflow to pass dynamic values to op_kwargs
|
I am trying to pull values using xcom_pull in airflow dynamically
The below mentioned formatting doesn't work for me when I piece together jinja templating with f-strings in op_kwargs. Appreciate if anyone can help me here.
op_kwargs={'names':"{{ ti.xcom_pull(key = '" + f'name{i+1}' + ", task_ids='places' ) }}"}
|
[
"Using fstring require to set proper number of brackets for Jinja. You can do:\nop_kwargs={'names': f\"{{{{ ti.xcom_pull(key='name{i+1}', task_ids='places') }}}}\"}\n\nExample (This is just a minimal example for your parameters to clarify how this works):\nfrom datetime import datetime\nfrom airflow import DAG\nfrom airflow.operators.python import PythonOperator\n\ndefault_args = {\n 'owner': 'airflow',\n 'start_date': datetime(2017, 2, 1)\n}\n\n\ndef func1(ti):\n ti.xcom_push(key=\"name2\", value=\"helloworld\")\n\n\ndef func2(names):\n print(names)\n\n\nwith DAG('fstring_dag', default_args=default_args, catchup=False, schedule=None):\n\n a = PythonOperator(\n task_id='places',\n python_callable=func1,\n )\n\n i = 1\n\n b = PythonOperator(\n task_id='places2',\n python_callable=func2,\n op_kwargs={'names': f\"{{{{ ti.xcom_pull(key='name{i+1}', task_ids='places') }}}}\"}\n )\n a >> b\n\nRender tab:\n\nLog:\n\n"
] |
[
0
] |
[] |
[] |
[
"airflow",
"f_string",
"jinja2",
"keyword_argument",
"python"
] |
stackoverflow_0074494267_airflow_f_string_jinja2_keyword_argument_python.txt
|
Q:
What's the correct way to use a TypeVar with a parameterized bound?
I occasionally run into a scenario like the following:
from typing import Generic, TypeVar
T = TypeVar('T')
class Widget(Generic[T]):
content: T
class Jibbit(Generic[T]):
element: T
class ThingHolder:
thing: Widget | Jibbit
In the Python standard library, this situation arises in logging.handlers.QueueListener, where the QueueListener.queue attribute is equivalent to ThingHolder.thing above.
Now I want to convert ThingHolder so that it is parameterized by the type of the thing that it holds, so that I can differentiate between, for example, ThingHolder[Widget[int]] and ThingHolder[Jibbit[int]].
How do you spell this correctly with a TypeVar? If I write
Thing = TypeVar('Thing', bound=Widget | Jibbit)
then I get an error because I didn't specify a parameter for the two parameterized types.
A:
It appears that you're supposed to parameterize the types in the bound= itself, and not attempt to parameterize the new type variable:
Thing = TypeVar('Thing', bound=Widget[Any] | Jibbit[Any])
class ThingHolder(Generic[Thing]):
thing: Thing
def __init__(self, thing: Thing) -> None:
self.thing = thing
I originally thought that this wouldn't work, because the "inner" type parameter isn't written anywhere in the definition. But it does in fact work:
# OK
w_int: Widget[int] = Widget(1)
th_w_int: ThingHolder[Widget[int]] = ThingHolder(w_int)
# OK
w_str: Widget[str] = Widget("hello")
th_w_str: ThingHolder[Widget[str]] = ThingHolder(w_str)
# Errors!
th_w_str = ThingHolder(w_int)
th_w_int = ThingHolder(w_str)
reveal_type(ThingHolder(Jibbit(None)))
# __main__.ThingHolder[__main__.Jibbit[None]]
reveal_type(ThingHolder(Jibbit([1,2,3])))
# __main__.ThingHolder[__main__.Jibbit[builtins.list[builtins.int]]]
I think it works because something like Widget[int] is indeed a subtype of Widget[Any] | Jibbit[Any], while something like list[int] is not. Clearly, Mypy is smart enough to track the "inner" types, even when they are not explicitly written in the class definition. Moreover, if you had the opportunity to inject your own type variable in the inner parameter, you might accidentally mess it up by using the wrong type variance for the inner parameter.
|
What's the correct way to use a TypeVar with a parameterized bound?
|
I occasionally run into a scenario like the following:
from typing import Generic, TypeVar
T = TypeVar('T')
class Widget(Generic[T]):
content: T
class Jibbit(Generic[T]):
element: T
class ThingHolder:
thing: Widget | Jibbit
In the Python standard library, this situation arises in logging.handlers.QueueListener, where the QueueListener.queue attribute is equivalent to ThingHolder.thing above.
Now I want to convert ThingHolder so that it is parameterized by the type of the thing that it holds, so that I can differentiate between, for example, ThingHolder[Widget[int]] and ThingHolder[Jibbit[int]].
How do you spell this correctly with a TypeVar? If I write
Thing = TypeVar('Thing', bound=Widget | Jibbit)
then I get an error because I didn't specify a parameter for the two parameterized types.
|
[
"It appears that you're supposed to parameterize the types in the bound= itself, and not attempt to parameterize the new type variable:\nThing = TypeVar('Thing', bound=Widget[Any] | Jibbit[Any])\n\n\nclass ThingHolder(Generic[Thing]):\n thing: Thing\n\n def __init__(self, thing: Thing) -> None:\n self.thing = thing\n\nI originally thought that this wouldn't work, because the \"inner\" type parameter isn't written anywhere in the definition. But it does in fact work:\n# OK\nw_int: Widget[int] = Widget(1)\nth_w_int: ThingHolder[Widget[int]] = ThingHolder(w_int)\n\n# OK\nw_str: Widget[str] = Widget(\"hello\")\nth_w_str: ThingHolder[Widget[str]] = ThingHolder(w_str)\n\n# Errors!\nth_w_str = ThingHolder(w_int)\nth_w_int = ThingHolder(w_str)\n\nreveal_type(ThingHolder(Jibbit(None)))\n# __main__.ThingHolder[__main__.Jibbit[None]]\n\nreveal_type(ThingHolder(Jibbit([1,2,3])))\n# __main__.ThingHolder[__main__.Jibbit[builtins.list[builtins.int]]]\n\nI think it works because something like Widget[int] is indeed a subtype of Widget[Any] | Jibbit[Any], while something like list[int] is not. Clearly, Mypy is smart enough to track the \"inner\" types, even when they are not explicitly written in the class definition. Moreover, if you had the opportunity to inject your own type variable in the inner parameter, you might accidentally mess it up by using the wrong type variance for the inner parameter.\n"
] |
[
1
] |
[] |
[] |
[
"mypy",
"python",
"type_hinting"
] |
stackoverflow_0074494466_mypy_python_type_hinting.txt
|
Q:
Compare with another column value
train.loc[:,'nd_mean_2021-04-15':'nd_mean_2021-08-27'] > train['q_5']
I get Automatic reindexing on DataFrame vs Series comparisons is deprecated and will raise ValueError in a future version. Do left, right = left.align(right, axis=1, copy=False)before e.g.left == right` and something strange output with a lot of columns, but I did expect cell values masked with True or False for calculate sum on next step.
Comparing each columns separately works just fine
train['nd_mean_2021-04-15'] > train['q_5']
But works slowly and messy code.
A:
I've tested your original solution, and two additional ways of performing this comparison you want to make.
To cut to the chase, the following option had the smallest execution time:
%%timeit
sliced_df = df.loc[:, 'nd_mean_2021-04-15':'nd_mean_2021-08-27']
comparisson_df = pd.DataFrame({col: df['q_5'] for col in sliced_df.columns})
(sliced_df > comparisson_df)
# 1.46 ms ± 610 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Drawback: it's little bit messy and requires you to create 2 new objects (sliced_df and comparisson_df)
Option 2: Using DataFrame.apply (slower but more readable)
The second option although slower than your original and the above implementations, in my opinion is the cleanest and easiest to read of them all. If you're not trying to process large amounts of data (I assume not, since you're using pandas instead of Dask or Spark that are tools more suitable for processing large volumes of data) then it's worth bringing it to the discussion table:
%%timeit
df.loc[:, 'nd_mean_2021-04-15':'nd_mean_2021-08-27'].apply(lambda col: col > df['q_5'])
# 5.66 ms ± 897 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Original Solution
I've also tested the performance of your original implementation and here's what I got:
%%timeit
df.loc[:, 'nd_mean_2021-04-15':'nd_mean_2021-08-27'] > df['q_5']
# 2.02 ms ± 175 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Side-Note: If the FutureWarning message is bothering you, there's always the option to ignore them, adding the following code after your script imports:
import warnings
warnings.filterwarnings('ignore', category=FutureWarning)
DataFrame Used for Testing
All of the above implementations used the same dataframe, that I created using the following code:
import pandas as pd
import numpy as np
columns = list(
map(
lambda value: f'nd_mean_{value}',
pd.date_range('2021-04-15', '2021-08-27', freq='W').to_series().dt.strftime('%Y-%m-%d').to_list()
)
)
df = pd.DataFrame(
{col: np.random.randint(0, 100, 10) for col in [*columns, 'q_5']}
)
Screenshots
|
Compare with another column value
|
train.loc[:,'nd_mean_2021-04-15':'nd_mean_2021-08-27'] > train['q_5']
I get Automatic reindexing on DataFrame vs Series comparisons is deprecated and will raise ValueError in a future version. Do left, right = left.align(right, axis=1, copy=False)before e.g.left == right` and something strange output with a lot of columns, but I did expect cell values masked with True or False for calculate sum on next step.
Comparing each columns separately works just fine
train['nd_mean_2021-04-15'] > train['q_5']
But works slowly and messy code.
|
[
"I've tested your original solution, and two additional ways of performing this comparison you want to make.\nTo cut to the chase, the following option had the smallest execution time:\n\n%%timeit\n\nsliced_df = df.loc[:, 'nd_mean_2021-04-15':'nd_mean_2021-08-27']\ncomparisson_df = pd.DataFrame({col: df['q_5'] for col in sliced_df.columns})\n(sliced_df > comparisson_df)\n# 1.46 ms ± 610 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\n\nDrawback: it's little bit messy and requires you to create 2 new objects (sliced_df and comparisson_df)\nOption 2: Using DataFrame.apply (slower but more readable)\nThe second option although slower than your original and the above implementations, in my opinion is the cleanest and easiest to read of them all. If you're not trying to process large amounts of data (I assume not, since you're using pandas instead of Dask or Spark that are tools more suitable for processing large volumes of data) then it's worth bringing it to the discussion table:\n\n%%timeit\n\ndf.loc[:, 'nd_mean_2021-04-15':'nd_mean_2021-08-27'].apply(lambda col: col > df['q_5'])\n# 5.66 ms ± 897 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\n\nOriginal Solution\nI've also tested the performance of your original implementation and here's what I got:\n\n%%timeit\n\ndf.loc[:, 'nd_mean_2021-04-15':'nd_mean_2021-08-27'] > df['q_5']\n# 2.02 ms ± 175 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n\n\nSide-Note: If the FutureWarning message is bothering you, there's always the option to ignore them, adding the following code after your script imports:\n\nimport warnings\n\nwarnings.filterwarnings('ignore', category=FutureWarning)\n\n\nDataFrame Used for Testing\nAll of the above implementations used the same dataframe, that I created using the following code:\n\nimport pandas as pd\nimport numpy as np\n\n\ncolumns = list(\n map(\n lambda value: f'nd_mean_{value}',\n pd.date_range('2021-04-15', '2021-08-27', freq='W').to_series().dt.strftime('%Y-%m-%d').to_list()\n )\n)\n\ndf = pd.DataFrame(\n {col: np.random.randint(0, 100, 10) for col in [*columns, 'q_5']}\n)\n\n\n\nScreenshots\n\n"
] |
[
1
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074494050_pandas_python.txt
|
Q:
Passing wildcard LIKE parameter to read_sql_query()
Every time I run the code below, I receive an execution failed on sql error.
lookup = f'12545%'
sql = pd.read_sql_query(
'''
Select *
From table
Where Name like ?
'''
,conn,lookup)
Basically, I think I need the following passed inside the double quotes as a parameter: "'12545%'"
Not sure what the best way there is to do this.
I've tried escaping ' and % but still get the same error or it says none of 12545 exists.
A:
You need to pass the parameters as a keyword argument, because it's the 5th positional argument to the function.
You have to put all the parameters in a list or tuple, not a single string.
ql = pd.read_sql_query(
'''
Select *
From table
Where Name like ?
'''
,conn,params=[lookup])
|
Passing wildcard LIKE parameter to read_sql_query()
|
Every time I run the code below, I receive an execution failed on sql error.
lookup = f'12545%'
sql = pd.read_sql_query(
'''
Select *
From table
Where Name like ?
'''
,conn,lookup)
Basically, I think I need the following passed inside the double quotes as a parameter: "'12545%'"
Not sure what the best way there is to do this.
I've tried escaping ' and % but still get the same error or it says none of 12545 exists.
|
[
"You need to pass the parameters as a keyword argument, because it's the 5th positional argument to the function.\nYou have to put all the parameters in a list or tuple, not a single string.\nql = pd.read_sql_query(\n'''\nSelect *\nFrom table\nWhere Name like ?\n'''\n,conn,params=[lookup])\n\n"
] |
[
2
] |
[] |
[] |
[
"pandas",
"pyodbc",
"python",
"sql"
] |
stackoverflow_0074494522_pandas_pyodbc_python_sql.txt
|
Q:
TypeError: only integer scalar arrays can be converted to a scalar index for Phase Estimation
Write a function to estimate the phase of an image from a symmetric region at the center of k-space. Hint: use the method shown in class, which includes zero-padding and filtering. (see format below. Note: The format below is an example format. You can change it as you wish.)
def estimate_phs(k_space,N):
kx, ky = kdata.shape
phase = np.zeros((N, N), dtype=kdata.dtype)
phase_ref = (ky - (N // 2)) * 2
hamming = window('hamming', (kx, phase_ref))
phase[:, ky - phase:ky] = kdata[:, ky - phase_ref:ky] * hamming
estimated_phase = np.angle(ifft2c(x=phase))
return estimated_phase
phs_estimated = estimate_phs(k_space=kdata,N=N_y)
plt.imshow(abs(phs_estimated),cmap="gray",norm=clr.PowerNorm(gamma=0.3))
plt.title("Estimated Phase")
plt.show()
Error:
TypeError: only integer scalar arrays can be converted to a scalar
index
A:
def estimate_phs (kdata,N):
kx, ky = kdata.shape
phase = np.zeros((kx,N), dtype=kdata.dtype)
phase_ref = (ky - (N // 2)) * 2
hamming = window('hamm', (kx, phase_ref))
phase[:, ky - phase_ref:ky] = kdata[:, ky - phase_ref:ky] * hamming
estimated_phase = np.angle(ifft2c(x=phase))
return estimated_phase
phs_estimated = estimate_phs(kdata,N=N_y)
plt.imshow(abs(phs_estimated),cmap="gray")
plt.title("Estimated Phase")
plt.show()
This code worked. I changed this line
phase = np.zeros((kx,N), dtype=kdata.dtype)
|
TypeError: only integer scalar arrays can be converted to a scalar index for Phase Estimation
|
Write a function to estimate the phase of an image from a symmetric region at the center of k-space. Hint: use the method shown in class, which includes zero-padding and filtering. (see format below. Note: The format below is an example format. You can change it as you wish.)
def estimate_phs(k_space,N):
kx, ky = kdata.shape
phase = np.zeros((N, N), dtype=kdata.dtype)
phase_ref = (ky - (N // 2)) * 2
hamming = window('hamming', (kx, phase_ref))
phase[:, ky - phase:ky] = kdata[:, ky - phase_ref:ky] * hamming
estimated_phase = np.angle(ifft2c(x=phase))
return estimated_phase
phs_estimated = estimate_phs(k_space=kdata,N=N_y)
plt.imshow(abs(phs_estimated),cmap="gray",norm=clr.PowerNorm(gamma=0.3))
plt.title("Estimated Phase")
plt.show()
Error:
TypeError: only integer scalar arrays can be converted to a scalar
index
|
[
"def estimate_phs (kdata,N):\n kx, ky = kdata.shape\n phase = np.zeros((kx,N), dtype=kdata.dtype)\n phase_ref = (ky - (N // 2)) * 2\n hamming = window('hamm', (kx, phase_ref))\n phase[:, ky - phase_ref:ky] = kdata[:, ky - phase_ref:ky] * hamming\n estimated_phase = np.angle(ifft2c(x=phase))\n return estimated_phase\nphs_estimated = estimate_phs(kdata,N=N_y)\nplt.imshow(abs(phs_estimated),cmap=\"gray\")\nplt.title(\"Estimated Phase\")\nplt.show()\n\nThis code worked. I changed this line\nphase = np.zeros((kx,N), dtype=kdata.dtype)\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"signal_processing"
] |
stackoverflow_0074480682_python_signal_processing.txt
|
Q:
How to extract a nested tag?
I want to extract 'span' tag from 'p' but I don't know how to do it
html = "
<div id="tab-description" class="plugin-description section">
<h2 id="description-header">Description</h2>
<p><span class="embed-youtube" style="text-align:center; display: block;"><iframe class="youtube-player"src="https://www.youtube.com/"></iframe></span></p>
</div>
"
soup = BeautifulSoup(html,'lxml')
description = soup.find(id="tab-description").find('p')
I tried to decompose() it but returns an error.
A:
To get <span> select it directly:
soup.find(id="tab-description").p.span
or
soup.find(id="tab-description").find('span')
or
soup.select_one('#tab-description p > span')
Be aware Not an option to scrape contents from the <iframe>, if this should be the intension. If so? This would be predestined for asking a new question with exact this focus.
To delete <span> and its contents from soup:
soup.find(id="tab-description").p.span.decompose()
|
How to extract a nested tag?
|
I want to extract 'span' tag from 'p' but I don't know how to do it
html = "
<div id="tab-description" class="plugin-description section">
<h2 id="description-header">Description</h2>
<p><span class="embed-youtube" style="text-align:center; display: block;"><iframe class="youtube-player"src="https://www.youtube.com/"></iframe></span></p>
</div>
"
soup = BeautifulSoup(html,'lxml')
description = soup.find(id="tab-description").find('p')
I tried to decompose() it but returns an error.
|
[
"To get <span> select it directly:\nsoup.find(id=\"tab-description\").p.span\n\nor\nsoup.find(id=\"tab-description\").find('span')\n\nor\nsoup.select_one('#tab-description p > span')\n\nBe aware Not an option to scrape contents from the <iframe>, if this should be the intension. If so? This would be predestined for asking a new question with exact this focus.\n\nTo delete <span> and its contents from soup:\nsoup.find(id=\"tab-description\").p.span.decompose()\n\n"
] |
[
0
] |
[] |
[] |
[
"beautifulsoup",
"html",
"python",
"web_scraping"
] |
stackoverflow_0074494504_beautifulsoup_html_python_web_scraping.txt
|
Q:
How to plot this dataset? (error: no numeric data to plot)
So this is how my dataset looks like but when i use
plot.line()
it gives me the error " no numeric data to plot"
apply to numeric doesn't seem to work
A:
check if the below code helps.
import matplotlib.pyplot as plt
x = df.iloc[:,0]
y = df.iloc[:,1]
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.show()
|
How to plot this dataset? (error: no numeric data to plot)
|
So this is how my dataset looks like but when i use
plot.line()
it gives me the error " no numeric data to plot"
apply to numeric doesn't seem to work
|
[
"check if the below code helps.\nimport matplotlib.pyplot as plt\nx = df.iloc[:,0]\ny = df.iloc[:,1]\nplt.scatter(x, y, s=area, c=colors, alpha=0.5)\nplt.show()\n\n"
] |
[
0
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074494627_dataframe_pandas_python.txt
|
Q:
Snake Game keep adding food and removing
i created a snake game and i have one problem in function food() it keep adding food on screen and removing it i don't know how to fix this i tried with food_statement like = "wait" when there's a food in screen and draw when it's not food can you help me code is working properly until hit food function?
import pygame
import time
import random
pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption('Snake Game by Joelinton')
blue=(0,0,255)
x_change = 0.2
y_change = 0.2
x = 400
y = 250
def creatingsnake():
pygame.draw.rect(screen,blue,[x,y,20,20])
def gameover():
font = pygame.font.SysFont('freesansbold.ttf', 100)
text = font.render('Game Over', True,(255,255,255))
screen.blit(text, (250, 250))
def food():
foodx = random.randint(0,750)
foody = random.randint(0,550)
pygame.draw.rect(screen,blue,[foodx,foody,20,20])
running = True
while running:
screen.fill((0,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x -= x_change
if keys[pygame.K_RIGHT]:
x += x_change
if keys[pygame.K_UP]:
y -= y_change
if keys[pygame.K_DOWN]:
y += y_change
if x < 0 or x > 780 or y < 0 or y > 580:
gameover()
running = False
time.sleep(1)
food()
creatingsnake()
pygame.display.update()
A:
food is called in each frame. Thus, when the coordinates are generated in the function 'food', new random coordinates are generated in each frame. You must set the coordinates of the food once before the application loop:
foodx = random.randint(0,750)
foody = random.randint(0,550)
def food():
pygame.draw.rect(screen,blue,[foodx,foody,20,20])
running = True
while running:
# [...]
food()
creatingsnake()
pygame.display.update()
|
Snake Game keep adding food and removing
|
i created a snake game and i have one problem in function food() it keep adding food on screen and removing it i don't know how to fix this i tried with food_statement like = "wait" when there's a food in screen and draw when it's not food can you help me code is working properly until hit food function?
import pygame
import time
import random
pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption('Snake Game by Joelinton')
blue=(0,0,255)
x_change = 0.2
y_change = 0.2
x = 400
y = 250
def creatingsnake():
pygame.draw.rect(screen,blue,[x,y,20,20])
def gameover():
font = pygame.font.SysFont('freesansbold.ttf', 100)
text = font.render('Game Over', True,(255,255,255))
screen.blit(text, (250, 250))
def food():
foodx = random.randint(0,750)
foody = random.randint(0,550)
pygame.draw.rect(screen,blue,[foodx,foody,20,20])
running = True
while running:
screen.fill((0,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x -= x_change
if keys[pygame.K_RIGHT]:
x += x_change
if keys[pygame.K_UP]:
y -= y_change
if keys[pygame.K_DOWN]:
y += y_change
if x < 0 or x > 780 or y < 0 or y > 580:
gameover()
running = False
time.sleep(1)
food()
creatingsnake()
pygame.display.update()
|
[
"food is called in each frame. Thus, when the coordinates are generated in the function 'food', new random coordinates are generated in each frame. You must set the coordinates of the food once before the application loop:\nfoodx = random.randint(0,750)\nfoody = random.randint(0,550)\n\ndef food():\n pygame.draw.rect(screen,blue,[foodx,foody,20,20])\n\nrunning = True\nwhile running:\n # [...]\n\n food()\n creatingsnake()\n pygame.display.update()\n\n"
] |
[
0
] |
[] |
[] |
[
"pygame",
"python"
] |
stackoverflow_0074494680_pygame_python.txt
|
Q:
Is it possible to paginate put_item in boto3?
When I use boto3 I can paginate if I am making a query or scan
Is it possible to do the same with put_item?
A:
The closest to "paginating" PutItem with boto3 is probably the included BatchWriter class and associated context manager. This class handles buffering and sending items in batches. Aside from PutItem, it supports DeleteItem as well.
Here is an example of how to use it:
import boto3
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table("name")
with table.batch_writer() as batch_writer:
for _ in range(1000):
batch_writer.put_item(Item={"HashKey": "...",
"Otherstuff": "..."})
A:
Paginating is when DynamoDB reaches its maximum of 1MB response size or it you are using --limit. It allows you to get the next "page" of data.
That does not make sense with a PutItem as you are simply putting a single item.
If what you mean is you want to put more than 1 item at a time, then use BatchWriteItem API where you can pass in a batch of up to 25 items.
You can also use high level interfaces like the batch_writer in boto3 where you can give it a list of items any size and it breaks the list into chunks of 25 for you and writes those batches while also handling any retry logic:
import boto3
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table("name")
with table.batch_writer() as batch_writer:
for _ in range(1000):
batch_writer.put_item(Item=myitem)
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/dynamodb.html#
|
Is it possible to paginate put_item in boto3?
|
When I use boto3 I can paginate if I am making a query or scan
Is it possible to do the same with put_item?
|
[
"The closest to \"paginating\" PutItem with boto3 is probably the included BatchWriter class and associated context manager. This class handles buffering and sending items in batches. Aside from PutItem, it supports DeleteItem as well.\nHere is an example of how to use it:\nimport boto3\n\ndynamodb = boto3.resource(\"dynamodb\")\ntable = dynamodb.Table(\"name\")\n\nwith table.batch_writer() as batch_writer:\n for _ in range(1000):\n batch_writer.put_item(Item={\"HashKey\": \"...\",\n \"Otherstuff\": \"...\"}) \n\n\n",
"Paginating is when DynamoDB reaches its maximum of 1MB response size or it you are using --limit. It allows you to get the next \"page\" of data.\nThat does not make sense with a PutItem as you are simply putting a single item.\nIf what you mean is you want to put more than 1 item at a time, then use BatchWriteItem API where you can pass in a batch of up to 25 items.\nYou can also use high level interfaces like the batch_writer in boto3 where you can give it a list of items any size and it breaks the list into chunks of 25 for you and writes those batches while also handling any retry logic:\nimport boto3\n\ndynamodb = boto3.resource(\"dynamodb\")\ntable = dynamodb.Table(\"name\")\n\nwith table.batch_writer() as batch_writer:\n for _ in range(1000):\n batch_writer.put_item(Item=myitem) \n\nhttps://boto3.amazonaws.com/v1/documentation/api/latest/guide/dynamodb.html#\n"
] |
[
2,
1
] |
[] |
[] |
[
"amazon_dynamodb",
"amazon_web_services",
"boto3",
"python"
] |
stackoverflow_0074493780_amazon_dynamodb_amazon_web_services_boto3_python.txt
|
Q:
How can I check for Python version in a program that uses new language features?
If I have a Python script that requires at least a particular
version of Python, what is the correct way to fail gracefully
when an earlier version of Python is used to launch the script?
How do I get control early enough to issue an error message
and exit?
For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks
(new in 2.6). I wrote a simple little interpreter-version
checker routine which is the first thing the script would
call ... except it doesn't get that far. Instead, the
script fails during python compilation, before my routines
are even called. Thus the user of the script sees some very
obscure synax error tracebacks - which pretty much require
an expert to deduce that it is simply the case of running
the wrong version of Python.
I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program:
import sys
if sys.version_info < (2, 4):
raise "must use python 2.5 or greater"
else:
# syntax error in 2.4, ok in 2.5
x = 1 if True else 2
print x
When run under 2.4, I want this result
$ ~/bin/python2.4 tern.py
must use python 2.5 or greater
and not this result:
$ ~/bin/python2.4 tern.py
File "tern.py", line 5
x = 1 if True else 2
^
SyntaxError: invalid syntax
(Channeling for a coworker.)
A:
You can test using eval:
try:
eval("1 if True else 2")
except SyntaxError:
# doesn't have ternary
Also, with is available in Python 2.5, just add from __future__ import with_statement.
EDIT: to get control early enough, you could split it into different .py files and check compatibility in the main file before importing (e.g. in __init__.py in a package):
# __init__.py
# Check compatibility
try:
eval("1 if True else 2")
except SyntaxError:
raise ImportError("requires ternary support")
# import from another module
from impl import *
A:
Have a wrapper around your program that does the following.
import sys
req_version = (2,5)
cur_version = sys.version_info
if cur_version >= req_version:
import myApp
myApp.run()
else:
print "Your Python interpreter is too old. Please consider upgrading."
You can also consider using sys.version(), if you plan to encounter people who are using pre-2.0 Python interpreters, but then you have some regular expressions to do.
And there might be more elegant ways to do this.
A:
Try
import platform
platform.python_version()
Should give you a string like "2.3.1". If this is not exactly waht you want there is a rich set of data available through the "platform" build-in. What you want should be in there somewhere.
A:
Probably the best way to do do this version comparison is to use the sys.hexversion. This is important because comparing version tuples will not give you the desired result in all python versions.
import sys
if sys.hexversion < 0x02060000:
print "yep!"
else:
print "oops!"
A:
import sys
# prints whether python is version 3 or not
python_version = sys.version_info.major
if python_version == 3:
print("is python 3")
else:
print("not python 3")
A:
Answer from Nykakin at AskUbuntu:
You can also check Python version from code itself using platform module from standard library.
There are two functions:
platform.python_version() (returns string).
platform.python_version_tuple() (returns tuple).
The Python code
Create a file for example: version.py)
Easy method to check version:
import platform
print(platform.python_version())
print(platform.python_version_tuple())
You can also use the eval method:
try:
eval("1 if True else 2")
except SyntaxError:
raise ImportError("requires ternary support")
Run the Python file in a command line:
$ python version.py
2.7.11
('2', '7', '11')
The output of Python with CGI via a WAMP Server on Windows 10:
Helpful resources
https://askubuntu.com/questions/505081/what-version-of-python-do-i-have
A:
Sets became part of the core language in Python 2.4, in order to stay backwards compatible. I did this back then, which will work for you as well:
if sys.version_info < (2, 4):
from sets import Set as set
A:
Although the question is:
How do I get control early enough to issue an error message and exit?
The question that I answer is:
How do I get control early enough to issue an error message before starting the app?
I can answer it a lot differently then the other posts.
Seems answers so far are trying to solve your question from within Python.
I say, do version checking before launching Python. I see your path is Linux or unix.
However I can only offer you a Windows script. I image adapting it to linux scripting syntax wouldn't be too hard.
Here is the DOS script with version 2.7:
@ECHO OFF
REM see http://ss64.com/nt/for_f.html
FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul
IF NOT ErrorLevel 1 GOTO Python27
ECHO must use python2.7 or greater
GOTO EOF
:Python27
python.exe tern.py
GOTO EOF
:EOF
This does not run any part of your application and therefore will not raise a Python Exception. It does not create any temp file or add any OS environment variables. And it doesn't end your app to an exception due to different version syntax rules. That's three less possible security points of access.
The FOR /F line is the key.
FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul
For multiple python version check check out url:
http://www.fpschultze.de/modules/smartfaq/faq.php?faqid=17
And my hack version:
[MS script; Python version check prelaunch of Python module]
http://pastebin.com/aAuJ91FQ
A:
import sys
sys.version
will be getting answer like this
'2.7.6 (default, Oct 26 2016, 20:30:19) \n[GCC 4.8.4]'
here 2.7.6 is version
A:
As noted above, syntax errors occur at compile time, not at run time. While Python is an "interpreted language", Python code is not actually directly interpreted; it's compiled to byte code, which is then interpreted. There is a compile step that happens when a module is imported (if there is no already-compiled version available in the form of a .pyc or .pyd file) and that's when you're getting your error, not (quite exactly) when your code is running.
You can put off the compile step and make it happen at run time for a single line of code, if you want to, by using eval, as noted above, but I personally prefer to avoid doing that, because it causes Python to perform potentially unnecessary run-time compilation, for one thing, and for another, it creates what to me feels like code clutter. (If you want, you can generate code that generates code that generates code - and have an absolutely fabulous time modifying and debugging that in 6 months from now.) So what I would recommend instead is something more like this:
import sys
if sys.hexversion < 0x02060000:
from my_module_2_5 import thisFunc, thatFunc, theOtherFunc
else:
from my_module import thisFunc, thatFunc, theOtherFunc
.. which I would do even if I only had one function that used newer syntax and it was very short. (In fact I would take every reasonable measure to minimize the number and size of such functions. I might even write a function like ifTrueAElseB(cond, a, b) with that single line of syntax in it.)
Another thing that might be worth pointing out (that I'm a little amazed no one has pointed out yet) is that while earlier versions of Python did not support code like
value = 'yes' if MyVarIsTrue else 'no'
..it did support code like
value = MyVarIsTrue and 'yes' or 'no'
That was the old way of writing ternary expressions. I don't have Python 3 installed yet, but as far as I know, that "old" way still works to this day, so you can decide for yourself whether or not it's worth it to conditionally use the new syntax, if you need to support the use of older versions of Python.
A:
Put the following at the very top of your file:
import sys
if float(sys.version.split()[0][:3]) < 2.7:
print "Python 2.7 or higher required to run this code, " + sys.version.split()[0] + " detected, exiting."
exit(1)
Then continue on with the normal Python code:
import ...
import ...
other code...
A:
I think the best way is to test for functionality rather than versions. In some cases, this is trivial, not so in others.
eg:
try :
# Do stuff
except : # Features weren't found.
# Do stuff for older versions.
As long as you're specific in enough in using the try/except blocks, you can cover most of your bases.
A:
I just found this question after a quick search whilst trying to solve the problem myself and I've come up with a hybrid based on a few of the suggestions above.
I like DevPlayer's idea of using a wrapper script, but the downside is that you end up maintaining multiple wrappers for different OSes, so I decided to write the wrapper in python, but use the same basic "grab the version by running the exe" logic and came up with this.
I think it should work for 2.5 and onwards. I've tested it on 2.66, 2.7.0 and 3.1.2 on Linux and 2.6.1 on OS X so far.
import sys, subprocess
args = [sys.executable,"--version"]
output, error = subprocess.Popen(args ,stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()
print("The version is: '%s'" %error.decode(sys.stdout.encoding).strip("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLMNBVCXZ,.+ \n") )
Yes, I know the final decode/strip line is horrible, but I just wanted to quickly grab the version number. I'm going to refine that.
This works well enough for me for now, but if anyone can improve it (or tell me why it's a terrible idea) that'd be cool too.
A:
For standalone python scripts, the following module docstring trick to enforce a python version (here v2.7.x) works (tested on *nix).
#!/bin/sh
''''python -V 2>&1 | grep -q 2.7 && exec python -u -- "$0" ${1+"$@"}; echo "python 2.7.x missing"; exit 1 # '''
import sys
[...]
This should handle missing python executable as well but has a dependency on grep. See here for background.
A:
I'm expanding on akhan's excellent answer, which prints a helpful message before the Python script is even compiled.
If you want to ensure that the script is being run with Python 3.6 or newer, add these two lines to the top of your Python script:
#!/bin/sh
''''python3 -c 'import sys; sys.exit(sys.version_info < (3, 6))' && exec python3 -u -- "$0" ${1+"$@"}; echo 'This script requires Python 3.6 or newer.'; exit 1 # '''
(Note: The second line starts with four single-quotes and ends with three single-quotes. This may look strange, but it is not a typo.)
The advantage of this solution is that code like print(f'Hello, {name}!') won't cause a SyntaxError if a Python version older than 3.6 is used. You'll see this helpful message instead:
This script requires Python 3.6 or newer.
Of course, this solution only works on Unix-like shells, and only when the script is invoked directly (such as: ./script.py), and with the proper eXecute permission bits set.
A:
A simple way to print a useful message if the user is running your Python 3 script with a Python 2 exe:
Put this as the first line of code:
f' Error: This script requires Python 3.6 or later.'
It does nothing in Python 3.6+ (when f-strings were introduced) but fails to compile in Python 2, and prints on the console:
File "test.py", line 34
f' Error: Error: This script requires Python 3.6 or later.'
^
SyntaxError: invalid syntax
A:
You can check with sys.hexversion or sys.version_info.
sys.hexversion isn't very human-friendly because it's a hexadecimal number. sys.version_info is a tuple, so it's more human-friendly.
Check for Python 3.6 or newer with sys.hexversion:
import sys, time
if sys.hexversion < 0x30600F0:
print("You need Python 3.6 or greater.")
for _ in range(1, 5): time.sleep(1)
exit()
Check for Python 3.6 or newer with sys.version_info:
import sys, time
if sys.version_info[0] < 3 and sys.version_info[1] < 6:
print("You need Python 3.6 or greater.")
for _ in range(1, 5): time.sleep(1)
exit()
sys.version_info is more human-friendly, but takes more characters. I would reccomend sys.hexversion, even though it is less human-friendly.
I hope this helped you!
|
How can I check for Python version in a program that uses new language features?
|
If I have a Python script that requires at least a particular
version of Python, what is the correct way to fail gracefully
when an earlier version of Python is used to launch the script?
How do I get control early enough to issue an error message
and exit?
For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks
(new in 2.6). I wrote a simple little interpreter-version
checker routine which is the first thing the script would
call ... except it doesn't get that far. Instead, the
script fails during python compilation, before my routines
are even called. Thus the user of the script sees some very
obscure synax error tracebacks - which pretty much require
an expert to deduce that it is simply the case of running
the wrong version of Python.
I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program:
import sys
if sys.version_info < (2, 4):
raise "must use python 2.5 or greater"
else:
# syntax error in 2.4, ok in 2.5
x = 1 if True else 2
print x
When run under 2.4, I want this result
$ ~/bin/python2.4 tern.py
must use python 2.5 or greater
and not this result:
$ ~/bin/python2.4 tern.py
File "tern.py", line 5
x = 1 if True else 2
^
SyntaxError: invalid syntax
(Channeling for a coworker.)
|
[
"You can test using eval:\ntry:\n eval(\"1 if True else 2\")\nexcept SyntaxError:\n # doesn't have ternary\n\nAlso, with is available in Python 2.5, just add from __future__ import with_statement.\nEDIT: to get control early enough, you could split it into different .py files and check compatibility in the main file before importing (e.g. in __init__.py in a package):\n# __init__.py\n\n# Check compatibility\ntry:\n eval(\"1 if True else 2\")\nexcept SyntaxError:\n raise ImportError(\"requires ternary support\")\n\n# import from another module\nfrom impl import *\n\n",
"Have a wrapper around your program that does the following.\nimport sys\n\nreq_version = (2,5)\ncur_version = sys.version_info\n\nif cur_version >= req_version:\n import myApp\n myApp.run()\nelse:\n print \"Your Python interpreter is too old. Please consider upgrading.\"\n\nYou can also consider using sys.version(), if you plan to encounter people who are using pre-2.0 Python interpreters, but then you have some regular expressions to do.\nAnd there might be more elegant ways to do this.\n",
"Try \n\nimport platform\nplatform.python_version()\n\nShould give you a string like \"2.3.1\". If this is not exactly waht you want there is a rich set of data available through the \"platform\" build-in. What you want should be in there somewhere. \n",
"Probably the best way to do do this version comparison is to use the sys.hexversion. This is important because comparing version tuples will not give you the desired result in all python versions.\nimport sys\nif sys.hexversion < 0x02060000:\n print \"yep!\"\nelse:\n print \"oops!\"\n\n",
"import sys \n# prints whether python is version 3 or not\npython_version = sys.version_info.major\nif python_version == 3:\n print(\"is python 3\")\nelse:\n print(\"not python 3\")\n\n",
"\nAnswer from Nykakin at AskUbuntu:\n\nYou can also check Python version from code itself using platform module from standard library.\nThere are two functions:\n\nplatform.python_version() (returns string).\nplatform.python_version_tuple() (returns tuple).\n\n\nThe Python code\n\nCreate a file for example: version.py)\n\nEasy method to check version:\nimport platform\n\nprint(platform.python_version())\nprint(platform.python_version_tuple())\n\nYou can also use the eval method:\ntry:\n eval(\"1 if True else 2\")\nexcept SyntaxError:\n raise ImportError(\"requires ternary support\")\n\n\nRun the Python file in a command line:\n$ python version.py \n2.7.11\n('2', '7', '11')\n\nThe output of Python with CGI via a WAMP Server on Windows 10:\n\n\nHelpful resources\n\nhttps://askubuntu.com/questions/505081/what-version-of-python-do-i-have\n\n",
"Sets became part of the core language in Python 2.4, in order to stay backwards compatible. I did this back then, which will work for you as well:\nif sys.version_info < (2, 4):\n from sets import Set as set\n\n",
"Although the question is:\nHow do I get control early enough to issue an error message and exit?\nThe question that I answer is:\nHow do I get control early enough to issue an error message before starting the app?\nI can answer it a lot differently then the other posts.\nSeems answers so far are trying to solve your question from within Python.\nI say, do version checking before launching Python. I see your path is Linux or unix.\nHowever I can only offer you a Windows script. I image adapting it to linux scripting syntax wouldn't be too hard.\nHere is the DOS script with version 2.7:\n@ECHO OFF\nREM see http://ss64.com/nt/for_f.html\nFOR /F \"tokens=1,2\" %%G IN ('\"python.exe -V 2>&1\"') DO ECHO %%H | find \"2.7\" > Nul\nIF NOT ErrorLevel 1 GOTO Python27\nECHO must use python2.7 or greater\nGOTO EOF\n:Python27\npython.exe tern.py\nGOTO EOF\n:EOF\n\nThis does not run any part of your application and therefore will not raise a Python Exception. It does not create any temp file or add any OS environment variables. And it doesn't end your app to an exception due to different version syntax rules. That's three less possible security points of access.\nThe FOR /F line is the key.\nFOR /F \"tokens=1,2\" %%G IN ('\"python.exe -V 2>&1\"') DO ECHO %%H | find \"2.7\" > Nul\n\nFor multiple python version check check out url:\nhttp://www.fpschultze.de/modules/smartfaq/faq.php?faqid=17\nAnd my hack version:\n[MS script; Python version check prelaunch of Python module]\nhttp://pastebin.com/aAuJ91FQ\n",
"import sys\nsys.version\n\nwill be getting answer like this \n\n'2.7.6 (default, Oct 26 2016, 20:30:19) \\n[GCC 4.8.4]'\n\nhere 2.7.6 is version\n",
"As noted above, syntax errors occur at compile time, not at run time. While Python is an \"interpreted language\", Python code is not actually directly interpreted; it's compiled to byte code, which is then interpreted. There is a compile step that happens when a module is imported (if there is no already-compiled version available in the form of a .pyc or .pyd file) and that's when you're getting your error, not (quite exactly) when your code is running. \nYou can put off the compile step and make it happen at run time for a single line of code, if you want to, by using eval, as noted above, but I personally prefer to avoid doing that, because it causes Python to perform potentially unnecessary run-time compilation, for one thing, and for another, it creates what to me feels like code clutter. (If you want, you can generate code that generates code that generates code - and have an absolutely fabulous time modifying and debugging that in 6 months from now.) So what I would recommend instead is something more like this:\nimport sys\nif sys.hexversion < 0x02060000:\n from my_module_2_5 import thisFunc, thatFunc, theOtherFunc\nelse:\n from my_module import thisFunc, thatFunc, theOtherFunc\n\n.. which I would do even if I only had one function that used newer syntax and it was very short. (In fact I would take every reasonable measure to minimize the number and size of such functions. I might even write a function like ifTrueAElseB(cond, a, b) with that single line of syntax in it.)\nAnother thing that might be worth pointing out (that I'm a little amazed no one has pointed out yet) is that while earlier versions of Python did not support code like\nvalue = 'yes' if MyVarIsTrue else 'no'\n\n..it did support code like\nvalue = MyVarIsTrue and 'yes' or 'no'\n\nThat was the old way of writing ternary expressions. I don't have Python 3 installed yet, but as far as I know, that \"old\" way still works to this day, so you can decide for yourself whether or not it's worth it to conditionally use the new syntax, if you need to support the use of older versions of Python.\n",
"Put the following at the very top of your file:\nimport sys\n\nif float(sys.version.split()[0][:3]) < 2.7:\n print \"Python 2.7 or higher required to run this code, \" + sys.version.split()[0] + \" detected, exiting.\"\n exit(1)\n\nThen continue on with the normal Python code:\nimport ...\nimport ...\nother code...\n\n",
"I think the best way is to test for functionality rather than versions. In some cases, this is trivial, not so in others.\neg:\ntry :\n # Do stuff\nexcept : # Features weren't found.\n # Do stuff for older versions.\n\nAs long as you're specific in enough in using the try/except blocks, you can cover most of your bases.\n",
"I just found this question after a quick search whilst trying to solve the problem myself and I've come up with a hybrid based on a few of the suggestions above.\nI like DevPlayer's idea of using a wrapper script, but the downside is that you end up maintaining multiple wrappers for different OSes, so I decided to write the wrapper in python, but use the same basic \"grab the version by running the exe\" logic and came up with this. \nI think it should work for 2.5 and onwards. I've tested it on 2.66, 2.7.0 and 3.1.2 on Linux and 2.6.1 on OS X so far.\nimport sys, subprocess\nargs = [sys.executable,\"--version\"]\n\noutput, error = subprocess.Popen(args ,stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()\nprint(\"The version is: '%s'\" %error.decode(sys.stdout.encoding).strip(\"qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLMNBVCXZ,.+ \\n\") )\n\nYes, I know the final decode/strip line is horrible, but I just wanted to quickly grab the version number. I'm going to refine that.\nThis works well enough for me for now, but if anyone can improve it (or tell me why it's a terrible idea) that'd be cool too.\n",
"For standalone python scripts, the following module docstring trick to enforce a python version (here v2.7.x) works (tested on *nix).\n#!/bin/sh\n''''python -V 2>&1 | grep -q 2.7 && exec python -u -- \"$0\" ${1+\"$@\"}; echo \"python 2.7.x missing\"; exit 1 # '''\n\nimport sys\n[...]\n\nThis should handle missing python executable as well but has a dependency on grep. See here for background.\n",
"I'm expanding on akhan's excellent answer, which prints a helpful message before the Python script is even compiled.\nIf you want to ensure that the script is being run with Python 3.6 or newer, add these two lines to the top of your Python script:\n#!/bin/sh\n''''python3 -c 'import sys; sys.exit(sys.version_info < (3, 6))' && exec python3 -u -- \"$0\" ${1+\"$@\"}; echo 'This script requires Python 3.6 or newer.'; exit 1 # '''\n\n(Note: The second line starts with four single-quotes and ends with three single-quotes. This may look strange, but it is not a typo.)\nThe advantage of this solution is that code like print(f'Hello, {name}!') won't cause a SyntaxError if a Python version older than 3.6 is used. You'll see this helpful message instead:\nThis script requires Python 3.6 or newer.\n\nOf course, this solution only works on Unix-like shells, and only when the script is invoked directly (such as: ./script.py), and with the proper eXecute permission bits set.\n",
"A simple way to print a useful message if the user is running your Python 3 script with a Python 2 exe:\nPut this as the first line of code:\nf' Error: This script requires Python 3.6 or later.'\n\nIt does nothing in Python 3.6+ (when f-strings were introduced) but fails to compile in Python 2, and prints on the console:\n\n File \"test.py\", line 34\n f' Error: Error: This script requires Python 3.6 or later.'\n ^\nSyntaxError: invalid syntax\n\n",
"You can check with sys.hexversion or sys.version_info.\nsys.hexversion isn't very human-friendly because it's a hexadecimal number. sys.version_info is a tuple, so it's more human-friendly.\nCheck for Python 3.6 or newer with sys.hexversion:\nimport sys, time\nif sys.hexversion < 0x30600F0:\n print(\"You need Python 3.6 or greater.\")\n for _ in range(1, 5): time.sleep(1)\n exit()\n\nCheck for Python 3.6 or newer with sys.version_info:\nimport sys, time\nif sys.version_info[0] < 3 and sys.version_info[1] < 6:\n print(\"You need Python 3.6 or greater.\")\n for _ in range(1, 5): time.sleep(1)\n exit()\n\nsys.version_info is more human-friendly, but takes more characters. I would reccomend sys.hexversion, even though it is less human-friendly.\nI hope this helped you!\n"
] |
[
117,
107,
34,
22,
15,
9,
8,
7,
3,
2,
2,
1,
1,
1,
1,
1,
0
] |
[
"How about this:\nimport sys\n\ndef testPyVer(reqver):\n if float(sys.version[:3]) >= reqver:\n return 1\n else:\n return 0\n\n#blah blah blah, more code\n\nif testPyVer(3.0) == 1:\n #do stuff\nelse:\n #print python requirement, exit statement\n\n",
"The problem is quite simple. You checked if the version was less than 2.4, not less than or equal to. So if the Python version is 2.4, it's not less than 2.4.\nWhat you should have had was:\n if sys.version_info **<=** (2, 4):\n\n, not\n if sys.version_info < (2, 4):\n\n"
] |
[
-2,
-3
] |
[
"python",
"version"
] |
stackoverflow_0000446052_python_version.txt
|
Q:
Split list of dictionaries in separate lists based primarily on list size but secondarily based on condition
I currently have a list of dictionaries that looks like that:
total_list = [
{'email': 'usera@email.com', 'id': 1, 'country': 'UK'},
{'email': 'usera@email.com', 'id': 1, 'country': 'Germany'},
{'email': 'userb@email.com', 'id': 2, 'country': 'UK'}
{'email': 'userc@email.com', 'id': 3, 'country': 'Italy'},
{'email': 'userc@email.com', 'id': 3, 'country': 'Netherland'},
{'email': 'userd@email.com', 'id': 4, 'country': 'France'},
...
]
I want to split it primarily based on size, so let's say that the new size list is 3 items per list, But I also want to make sure that all the same users will be in the same new sublist.
So the result I am trying to create is:
list_a = [
{'email': 'usera@email.com', 'id': 1, 'country': 'UK'},
{'email': 'userb@email.com', 'id': 2, 'country': 'UK'}
{'email': 'usera@email.com', 'id': 1, 'country': 'Germany'}
]
list_b = [
{'email': 'userc@email.com', 'id': 3, 'country': 'Italy'},
{'email': 'userd@email.com', 'id': 4, 'country': 'France'}
{'email': 'userc@email.com', 'id': 3, 'country': 'Netherland'},
...
]
Obviously in the example that I provided the users were located really close to each other in the list, but in reality, they could be spread way more.
I was considering sorting the list based on the email and then splitting them, but I am not sure what happens if the items that are supposed to be grouped together happen to be at the exact location that
the main list will be divided.
What I have tried so far is:
def list_splitter(main_list, size):
for i in range(0, len(main_list), size):
yield main_list[i:i + size]
# calculating the needed number of sublists
max_per_batch = 3
number_of_sublists = ceil(len(total_list) / max_per_batch)
# sort the data by email
total_list.sort(key=lambda x: x['email'])
sublists = list(list_splitter(main_list=total_list, size=max_per_batch))
The issue is that with this logic I cannot 100% ensure that if there are any items with the same email value they will end up in the same sublist. Because of the sorting, chances are that this will happen, but it is not certain.
Basically, I need a method to make sure that items with the same email will always be in the same sublist, but the main condition of the split is the sublist size.
A:
This solution starts of by only working with the list of all emails. The emails are then grouped based on their frequency and the limit on group size. Later the remaining data, i.e. id and country, are joined back on the email groups.
The first function create_groups works on the list of emails. It counts the number of occurrences of each email and groups them. Each new group starts with the most frequent email. If there is room left in the group it looks for the most frequent that also fits in the group. If such an item exists, it is added to the group.
This is repeated until the group is full; then, a new group is started.
from operator import itemgetter
from itertools import groupby, chain
from collections import Counter
def create_groups(items, group_size_limit):
# Count the frequency of all items and create a list of items
# sorted by descending frequency
items_not_grouped = Counter(items).most_common()
groups = []
while items_not_grouped:
# Start a new group with the most frequent ungrouped item
item, count = items_not_grouped.pop(0)
group, group_size = [item], count
while group_size < group_size_limit:
# If there is room left in the group, look for a new group member
for index, (candidate, candidate_count) \
in enumerate(items_not_grouped):
if candidate_count <= group_size_limit - group_size:
# If the candidate fits, add it to the group
group.append(candidate)
group_size += candidate_count
# ... and remove it from the items not grouped
items_not_grouped.pop(index)
break
else:
# If the for loop did not break, no items fit in the group
break
groups.append(group)
return groups
This is the result of using that function on your example:
users = [
{'email': 'usera@email.com', 'id': 1, 'country': 'UK',},
{'email': 'userb@email.com', 'id': 2, 'country': 'UK'},
{'email': 'usera@email.com', 'id': 1, 'country': 'Germany'},
{'email': 'userc@email.com', 'id': 3, 'country': 'Italy'},
{'email': 'userd@email.com', 'id': 4, 'country': 'France'},
{'email': 'userc@email.com', 'id': 3, 'country': 'Netherland'}
]
emails = [user["email"] for user in users]
email_groups = create_groups(emails, 3)
# -> [
# ['usera@email.com', 'userb@email.com'],
# ['userc@email.com', 'userd@email.com']
# ]
Finally, when the groups have been created, the function join_data_on_groups, groups the original dictionary of users. It takes the email-groups from before and the list of dictionaries as arguments:
def join_data_on_groups(groups, item_to_data):
item_to_data = {item: list(data) for item, data in item_to_data}
groups = [(item_to_data[item] for item in group) for group in groups]
groups = [list(chain(*group)) for group in groups]
return groups
email_getter = itemgetter("email")
users_grouped_by_email = groupby(sorted(users, key=email_getter), email_getter)
user_groups = join_data_on_groups(email_groups, users_grouped_by_email)
print(user_groups)
Result:
[
[
{'email': 'usera@email.com', 'id': 1, 'country': 'UK'},
{'email': 'usera@email.com', 'id': 1, 'country': 'Germany'},
{'email': 'userb@email.com', 'id': 2, 'country': 'UK'}
],
[
{'email': 'userc@email.com', 'id': 3, 'country': 'Italy'},
{'email': 'userc@email.com', 'id': 3, 'country': 'Netherland'},
{'email': 'userd@email.com', 'id': 4, 'country': 'France'}
]
]
A:
I would consider using a queue or fifo type and popping elements off for use, instead of saving dicts in a list. But working with what you have you could either create a new sorted list first and do what you were doing (kinda), or here's another solution as there are many solutions to organizing data in any way imaginable (in fact, your constrainst is different in that you want to assign each output object to a variable name? I'll ignore that part):
Create a dictionary D of type str:list where your key is the user email, and the list is a list of all dict entries from total_list that at first is empty []. If you have a lot of data, queing/generators would be better but the point is your filtering/formatting your input.
Parse your total_list into D, so every hit of an identical user email, you append that dict to that key's value list. total_list could be deleted.
Parse D now, forming your output list (or generator) with lists of dictionaries, with a limit of 3 dicts per list. This could be a generator similar to what you have now.
A:
General solution (explanation below):
import pandas as pd
import numpy as np
from numberpartitioning import karmarkar_karp
def solution(data, groupby: str, partition_size: int):
df = pd.DataFrame(data)
groups = df.groupby([groupby]).count()
groupby_counts = groups.iloc[:, 0].values
num_parts = len(df) // partition_size
result = karmarkar_karp(groupby_counts, num_parts=num_parts, return_indices=True)
part_keys = groups.index.values[np.array(result.partition)]
partitions = [df.loc[df[groupby].isin(key)].to_dict('records') for key in part_keys]
return partitions
solution(total_list, groupby="email", partition_size=3)
Gives a valid solution (although grouped slightly differently from your example solution)
[[{'country': 'UK', 'email': 'userb@email.com', 'id': 2},
{'country': 'Italy', 'email': 'userc@email.com', 'id': 3},
{'country': 'Netherland', 'email': 'userc@email.com', 'id': 3}],
[{'country': 'UK', 'email': 'usera@email.com', 'id': 1},
{'country': 'Germany', 'email': 'usera@email.com', 'id': 1},
{'country': 'France', 'email': 'userd@email.com', 'id': 4}]]
Explanation
We can use a partitioning algorithm, like the
Karmarkar-Karp Algorithm. It partitions a set of numbers into k partitions such that sum of each partition is as close as possible. There already exists a pure Python implementation numberpartition. Just python3 -m pip install numberpartitioning.
The algorithm only works with numbers, but we can encode groups of emails using just the count of emails per group. Let's use a dataframe to hold your data:
>>> df = pd.DataFrame(total_list)
Then find the counts, grouped by email:
>>> email_counts = df.groupby(["email"])["id"].count().rename("count")
For example, the group counts for total_list:
>>> email_counts
email
usera@email.com 2
userb@email.com 1
userc@email.com 2
userd@email.com 1
Name: count, dtype: int64
In your example we want 3 entries per partition (so partition_size=3), which means the number of partitions is num_parts = len(total_list)/partition_size = 2
So then if we do karmarkar_karp([2, 1, 2, 1], num_parts=True), we get the following partition [[2, 1], [2, 1]], and partition sizes [3, 3].
But we don't care about the counts, we care about which email is associated with each count. So, we simply return the indices:
>>> result = karmarkar_karp(email_counts.values, num_parts=2, return_indices=True)
>>> result
PartitioningResult(partition=[[2, 1], [0, 3]], sizes=[3, 3])
Based on the indices, the groupings are:
partition 1: indices [2, 1] -> [userc, userb]
partition 2: indices [0, 3] -> [usera, userd]
which is a little different than what you wrote, but nevertheless a valid solution.
We find the email partitions by running:
>>> email_partitions = email_counts.index.values[np.array(result.partition)]
Given the email partitions, we now just have to split every entry in total_list based on which partition it belongs to.
>>> partitions = [df.loc[df["email"].isin(emails)].to_dict('records') for emails in email_partitions]
And then printing partitions, we have:
>>> partitions
[[{'email': 'userb@email.com', 'id': 2, 'country': 'UK'},
{'email': 'userc@email.com', 'id': 3, 'country': 'Italy'},
{'email': 'userc@email.com', 'id': 3, 'country': 'Netherland'}],
[{'email': 'usera@email.com', 'id': 1, 'country': 'UK'},
{'email': 'usera@email.com', 'id': 1, 'country': 'Germany'},
{'email': 'userd@email.com', 'id': 4, 'country': 'France'}]]
|
Split list of dictionaries in separate lists based primarily on list size but secondarily based on condition
|
I currently have a list of dictionaries that looks like that:
total_list = [
{'email': 'usera@email.com', 'id': 1, 'country': 'UK'},
{'email': 'usera@email.com', 'id': 1, 'country': 'Germany'},
{'email': 'userb@email.com', 'id': 2, 'country': 'UK'}
{'email': 'userc@email.com', 'id': 3, 'country': 'Italy'},
{'email': 'userc@email.com', 'id': 3, 'country': 'Netherland'},
{'email': 'userd@email.com', 'id': 4, 'country': 'France'},
...
]
I want to split it primarily based on size, so let's say that the new size list is 3 items per list, But I also want to make sure that all the same users will be in the same new sublist.
So the result I am trying to create is:
list_a = [
{'email': 'usera@email.com', 'id': 1, 'country': 'UK'},
{'email': 'userb@email.com', 'id': 2, 'country': 'UK'}
{'email': 'usera@email.com', 'id': 1, 'country': 'Germany'}
]
list_b = [
{'email': 'userc@email.com', 'id': 3, 'country': 'Italy'},
{'email': 'userd@email.com', 'id': 4, 'country': 'France'}
{'email': 'userc@email.com', 'id': 3, 'country': 'Netherland'},
...
]
Obviously in the example that I provided the users were located really close to each other in the list, but in reality, they could be spread way more.
I was considering sorting the list based on the email and then splitting them, but I am not sure what happens if the items that are supposed to be grouped together happen to be at the exact location that
the main list will be divided.
What I have tried so far is:
def list_splitter(main_list, size):
for i in range(0, len(main_list), size):
yield main_list[i:i + size]
# calculating the needed number of sublists
max_per_batch = 3
number_of_sublists = ceil(len(total_list) / max_per_batch)
# sort the data by email
total_list.sort(key=lambda x: x['email'])
sublists = list(list_splitter(main_list=total_list, size=max_per_batch))
The issue is that with this logic I cannot 100% ensure that if there are any items with the same email value they will end up in the same sublist. Because of the sorting, chances are that this will happen, but it is not certain.
Basically, I need a method to make sure that items with the same email will always be in the same sublist, but the main condition of the split is the sublist size.
|
[
"This solution starts of by only working with the list of all emails. The emails are then grouped based on their frequency and the limit on group size. Later the remaining data, i.e. id and country, are joined back on the email groups.\nThe first function create_groups works on the list of emails. It counts the number of occurrences of each email and groups them. Each new group starts with the most frequent email. If there is room left in the group it looks for the most frequent that also fits in the group. If such an item exists, it is added to the group.\nThis is repeated until the group is full; then, a new group is started.\nfrom operator import itemgetter\nfrom itertools import groupby, chain\nfrom collections import Counter\n\n\ndef create_groups(items, group_size_limit):\n # Count the frequency of all items and create a list of items \n # sorted by descending frequency\n items_not_grouped = Counter(items).most_common()\n groups = []\n\n while items_not_grouped:\n # Start a new group with the most frequent ungrouped item\n item, count = items_not_grouped.pop(0)\n group, group_size = [item], count\n while group_size < group_size_limit:\n # If there is room left in the group, look for a new group member\n for index, (candidate, candidate_count) \\\n in enumerate(items_not_grouped):\n if candidate_count <= group_size_limit - group_size:\n # If the candidate fits, add it to the group\n group.append(candidate)\n group_size += candidate_count\n # ... and remove it from the items not grouped\n items_not_grouped.pop(index)\n break\n else:\n # If the for loop did not break, no items fit in the group\n break\n\n groups.append(group)\n\n return groups\n\nThis is the result of using that function on your example:\nusers = [\n {'email': 'usera@email.com', 'id': 1, 'country': 'UK',},\n {'email': 'userb@email.com', 'id': 2, 'country': 'UK'},\n {'email': 'usera@email.com', 'id': 1, 'country': 'Germany'},\n {'email': 'userc@email.com', 'id': 3, 'country': 'Italy'},\n {'email': 'userd@email.com', 'id': 4, 'country': 'France'},\n {'email': 'userc@email.com', 'id': 3, 'country': 'Netherland'}\n]\n\nemails = [user[\"email\"] for user in users]\nemail_groups = create_groups(emails, 3)\n# -> [\n# ['usera@email.com', 'userb@email.com'], \n# ['userc@email.com', 'userd@email.com']\n# ]\n\n\nFinally, when the groups have been created, the function join_data_on_groups, groups the original dictionary of users. It takes the email-groups from before and the list of dictionaries as arguments:\ndef join_data_on_groups(groups, item_to_data):\n item_to_data = {item: list(data) for item, data in item_to_data}\n\n groups = [(item_to_data[item] for item in group) for group in groups]\n groups = [list(chain(*group)) for group in groups]\n\n return groups\n\n\nemail_getter = itemgetter(\"email\")\nusers_grouped_by_email = groupby(sorted(users, key=email_getter), email_getter)\n\nuser_groups = join_data_on_groups(email_groups, users_grouped_by_email)\n\nprint(user_groups)\n\nResult:\n[\n [\n {'email': 'usera@email.com', 'id': 1, 'country': 'UK'},\n {'email': 'usera@email.com', 'id': 1, 'country': 'Germany'}, \n {'email': 'userb@email.com', 'id': 2, 'country': 'UK'}\n ],\n [\n {'email': 'userc@email.com', 'id': 3, 'country': 'Italy'},\n {'email': 'userc@email.com', 'id': 3, 'country': 'Netherland'},\n {'email': 'userd@email.com', 'id': 4, 'country': 'France'}\n ]\n]\n\n",
"I would consider using a queue or fifo type and popping elements off for use, instead of saving dicts in a list. But working with what you have you could either create a new sorted list first and do what you were doing (kinda), or here's another solution as there are many solutions to organizing data in any way imaginable (in fact, your constrainst is different in that you want to assign each output object to a variable name? I'll ignore that part):\n\nCreate a dictionary D of type str:list where your key is the user email, and the list is a list of all dict entries from total_list that at first is empty []. If you have a lot of data, queing/generators would be better but the point is your filtering/formatting your input.\nParse your total_list into D, so every hit of an identical user email, you append that dict to that key's value list. total_list could be deleted.\nParse D now, forming your output list (or generator) with lists of dictionaries, with a limit of 3 dicts per list. This could be a generator similar to what you have now.\n\n",
"General solution (explanation below):\nimport pandas as pd\nimport numpy as np\nfrom numberpartitioning import karmarkar_karp\n\ndef solution(data, groupby: str, partition_size: int):\n df = pd.DataFrame(data)\n groups = df.groupby([groupby]).count()\n groupby_counts = groups.iloc[:, 0].values\n num_parts = len(df) // partition_size\n result = karmarkar_karp(groupby_counts, num_parts=num_parts, return_indices=True)\n part_keys = groups.index.values[np.array(result.partition)]\n partitions = [df.loc[df[groupby].isin(key)].to_dict('records') for key in part_keys]\n return partitions\n\n\nsolution(total_list, groupby=\"email\", partition_size=3)\n\nGives a valid solution (although grouped slightly differently from your example solution)\n[[{'country': 'UK', 'email': 'userb@email.com', 'id': 2},\n {'country': 'Italy', 'email': 'userc@email.com', 'id': 3},\n {'country': 'Netherland', 'email': 'userc@email.com', 'id': 3}],\n [{'country': 'UK', 'email': 'usera@email.com', 'id': 1},\n {'country': 'Germany', 'email': 'usera@email.com', 'id': 1},\n {'country': 'France', 'email': 'userd@email.com', 'id': 4}]]\n\n\nExplanation\nWe can use a partitioning algorithm, like the\nKarmarkar-Karp Algorithm. It partitions a set of numbers into k partitions such that sum of each partition is as close as possible. There already exists a pure Python implementation numberpartition. Just python3 -m pip install numberpartitioning.\nThe algorithm only works with numbers, but we can encode groups of emails using just the count of emails per group. Let's use a dataframe to hold your data:\n>>> df = pd.DataFrame(total_list)\n\nThen find the counts, grouped by email:\n>>> email_counts = df.groupby([\"email\"])[\"id\"].count().rename(\"count\")\n\nFor example, the group counts for total_list:\n>>> email_counts\nemail\nusera@email.com 2\nuserb@email.com 1\nuserc@email.com 2\nuserd@email.com 1\nName: count, dtype: int64\n\nIn your example we want 3 entries per partition (so partition_size=3), which means the number of partitions is num_parts = len(total_list)/partition_size = 2\nSo then if we do karmarkar_karp([2, 1, 2, 1], num_parts=True), we get the following partition [[2, 1], [2, 1]], and partition sizes [3, 3].\nBut we don't care about the counts, we care about which email is associated with each count. So, we simply return the indices:\n>>> result = karmarkar_karp(email_counts.values, num_parts=2, return_indices=True)\n>>> result\nPartitioningResult(partition=[[2, 1], [0, 3]], sizes=[3, 3])\n\nBased on the indices, the groupings are:\npartition 1: indices [2, 1] -> [userc, userb]\npartition 2: indices [0, 3] -> [usera, userd]\n\nwhich is a little different than what you wrote, but nevertheless a valid solution.\nWe find the email partitions by running:\n>>> email_partitions = email_counts.index.values[np.array(result.partition)]\n\nGiven the email partitions, we now just have to split every entry in total_list based on which partition it belongs to.\n>>> partitions = [df.loc[df[\"email\"].isin(emails)].to_dict('records') for emails in email_partitions]\n\nAnd then printing partitions, we have:\n>>> partitions\n[[{'email': 'userb@email.com', 'id': 2, 'country': 'UK'},\n {'email': 'userc@email.com', 'id': 3, 'country': 'Italy'},\n {'email': 'userc@email.com', 'id': 3, 'country': 'Netherland'}],\n [{'email': 'usera@email.com', 'id': 1, 'country': 'UK'},\n {'email': 'usera@email.com', 'id': 1, 'country': 'Germany'},\n {'email': 'userd@email.com', 'id': 4, 'country': 'France'}]]\n\n"
] |
[
3,
0,
0
] |
[] |
[] |
[
"dictionary",
"list",
"python"
] |
stackoverflow_0074319258_dictionary_list_python.txt
|
Q:
How to calculate percentage change with zero in pandas?
I want to calculate the percentage change for the following data frame.
import pandas as pd
df = pd.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C'],
'points': [12, 0, 19, 22, 0, 25, 0, 30],
'score': [12, 0, 19, 22, 0, 25, 0, 30]
})
print(df)
When I applied this step, it returns inf which is obvious because we are dividing by zero.
df['score'] = df.groupby('team', sort=False)['score'].apply(
lambda x: x.pct_change()).to_numpy()
But if we see in each column the change from 0 to 19 the change is 100%, from 0 to 25 the change is 100%, and from 0 to 30 the change is 100%. So, I was wondering how can I calculate those values.
current result
Expected result is
A:
So you just want to replace the infinite values with 1?
import numpy as np
df[['points', 'score']] = (
df.groupby('team')
.pct_change()
.replace(np.inf, 1)
)
Output:
team points score
0 A NaN NaN
1 A -1.0 -1.0
2 A 1.0 1.0
3 B NaN NaN
4 B -1.0 -1.0
5 B 1.0 1.0
6 C NaN NaN
7 C 1.0 1.0
A:
Not sure if you want to count the drops in score as a negative, but this will give you the calculation you're looking for (multiplying by 100 to get to how you're representing the percentages in your output). Basically, diff calculates the difference between current and prior.
df = pd.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C'],
'points': [12, 0, 19, 22, 0, 25, 0, 30],
'score': [12, 0, 19, 22, 0, 25, 0, 30]
})
df["score"] = df.groupby('team', sort=False)['score'].diff() * 100
print(df)
To set the rows to 1 / -1, simply use loc for positive / negative values and set accordingly like so
df.loc[df["score"] < 0, "score"] = -1
df.loc[df["score"] > 0, "score"] = 1
A:
# take the sign using np.sign for the diff b/w two consecutive rows
df['chg']=np.sign(df.groupby('team')['score'].diff())
df
team points score chg
0 A 12 12 NaN
1 A 0 0 -1.0
2 A 19 19 1.0
3 B 22 22 NaN
4 B 0 0 -1.0
5 B 25 25 1.0
6 C 0 0 NaN
7 C 30 30 1.0
|
How to calculate percentage change with zero in pandas?
|
I want to calculate the percentage change for the following data frame.
import pandas as pd
df = pd.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C'],
'points': [12, 0, 19, 22, 0, 25, 0, 30],
'score': [12, 0, 19, 22, 0, 25, 0, 30]
})
print(df)
When I applied this step, it returns inf which is obvious because we are dividing by zero.
df['score'] = df.groupby('team', sort=False)['score'].apply(
lambda x: x.pct_change()).to_numpy()
But if we see in each column the change from 0 to 19 the change is 100%, from 0 to 25 the change is 100%, and from 0 to 30 the change is 100%. So, I was wondering how can I calculate those values.
current result
Expected result is
|
[
"So you just want to replace the infinite values with 1?\nimport numpy as np\n\ndf[['points', 'score']] = (\n df.groupby('team')\n .pct_change()\n .replace(np.inf, 1)\n)\n\nOutput:\n team points score\n0 A NaN NaN\n1 A -1.0 -1.0\n2 A 1.0 1.0\n3 B NaN NaN\n4 B -1.0 -1.0\n5 B 1.0 1.0\n6 C NaN NaN\n7 C 1.0 1.0\n\n",
"Not sure if you want to count the drops in score as a negative, but this will give you the calculation you're looking for (multiplying by 100 to get to how you're representing the percentages in your output). Basically, diff calculates the difference between current and prior.\ndf = pd.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C'],\n 'points': [12, 0, 19, 22, 0, 25, 0, 30],\n 'score': [12, 0, 19, 22, 0, 25, 0, 30]\n\n })\n\ndf[\"score\"] = df.groupby('team', sort=False)['score'].diff() * 100\n\nprint(df)\n\nTo set the rows to 1 / -1, simply use loc for positive / negative values and set accordingly like so\ndf.loc[df[\"score\"] < 0, \"score\"] = -1\ndf.loc[df[\"score\"] > 0, \"score\"] = 1\n\n",
"# take the sign using np.sign for the diff b/w two consecutive rows\ndf['chg']=np.sign(df.groupby('team')['score'].diff())\ndf\n\n team points score chg\n0 A 12 12 NaN\n1 A 0 0 -1.0\n2 A 19 19 1.0\n3 B 22 22 NaN\n4 B 0 0 -1.0\n5 B 25 25 1.0\n6 C 0 0 NaN\n7 C 30 30 1.0\n\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"data_science_experience",
"dataframe",
"group_by",
"pandas",
"python"
] |
stackoverflow_0074494441_data_science_experience_dataframe_group_by_pandas_python.txt
|
Q:
How do i make a working slash command in discord.py
I am trying to make a slash command with discord.py I have tried a lot of stuff it doesn't seem to be working. Help would be appreciated.
A:
Note: I will include a version for pycord at the end because I think it's much simpler, also it was the original answer.
discord.py version
First make sure that you have the newest version of discord.py installed.
In your code, you first import the library:
import discord
from discord import app_commands
and then you define your client and tree:
intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
The tree holds all of your application commands. Then you can define your command:
@tree.command(name = "commandname", description = "My first application Command", guild=discord.Object(id=12417128931)) #Add the guild ids in which the slash command will appear. If it should be in all, remove the argument, but note that it will take some time (up to an hour) to register the command if it's for all guilds.
async def first_command(interaction):
await interaction.response.send_message("Hello!")
Then you also have to sync your commands to discord once the client is ready, so we do that in the on_ready event:
@client.event
async def on_ready():
await tree.sync(guild=discord.Object(id=Your guild id))
print("Ready!")
And at the end we have to run our client:
client.run("token")
pycord version
To install py-cord, first run pip uninstall discord.py and then pip install py-cord.
Then in your code, first import the library with
import discord
from discord.ext import commands
create you bot class with
bot = commands.Bot()
and create your slash command with
@bot.slash_command(name="first_slash", guild_ids=[...]) #Add the guild ids in which the slash command will appear. If it should be in all, remove the argument, but note that it will take some time (up to an hour) to register the command if it's for all guilds.
async def first_slash(ctx):
await ctx.respond("You executed the slash command!")
and then run the bot with your token
bot.run(TOKEN)
A:
They're sort of in the middle of adding slash commands to discord.py but you can see a few examples in https://gist.github.com/Rapptz/c4324f17a80c94776832430007ad40e6 You seem to be using discord_slash, which I have not used.
The main documentation for this stuff is https://discordpy.readthedocs.io/en/master/interactions/api.html?highlight=dropdown#decorators but the main "how to" is that you've gotta make a "tree", attach commands to that tree, and sync your tree for the commands to show up. discord.ext.Bot makes its own tree, which is why I'm using that instead of client, which I think doesn't make a tree by default.
If you specify the guilds, the commands sync takes place instantly, but if you don't specify the guild, I think it takes an hour to update or something like that, so specify the guild until you're ready for deployment.
I'm not quite sure how to do it in cogs, because I have mine in groups but basically what I'm doing is a combination of @bot.tree.command() in the main bot file and a few groups in separate files.
So here's my main file
import discord
import simplegeneralgroup
from config import TOKEN
MY_GUILD = discord.Object(id=1234567890)
class MyBot(discord.ext.commands.Bot):
async def on_ready(self):
await self.tree.sync(guild=MY_GUILD)
bot: discord.ext.commands.Bot = MyBot
@bot.tree.command(guild=MY_GUILD)
async def slash(interaction: discord.Interaction, number: int, string: str):
await interaction.response.send_message(f'Modify {number=} {string=}', ephemeral=True)
bot.tree.add_command(simplegeneralgroup.Generalgroup(bot), guild=MY_GUILD)
if __name__ == "__main__":
bot.run(TOKEN)
and then the simplegeneralgroup file
import discord
from discord import app_commands as apc
class Generalgroup(apc.Group):
"""Manage general commands"""
def __init__(self, bot: discord.ext.commands.Bot):
super().__init__()
self.bot = bot
@apc.command()
async def hello(self, interaction: discord.Interaction):
await interaction.response.send_message('Hello')
@apc.command()
async def version(self, interaction: discord.Interaction):
"""tells you what version of the bot software is running."""
await interaction.response.send_message('This is an untested test version')
There should be three commands: /slash, which will prompt the user for a number and string, /generalgroup hello, and /generalgroup version
A:
discord.py does not support slash commands. I recommend you use discord-py-interactions for slash commands. To install it is to do python3.exe -m pip install discord-py-interactions. It works well. Here is a sample code to base off:
import interactions
bot = interactions.Client(token="your_secret_bot_token")
@bot.command(
name="my_first_command",
description="This is the first command I made!",
scope=the_id_of_your_guild,
)
async def my_first_command(ctx: interactions.CommandContext):
await ctx.send("Hi there!")
bot.start()
A:
# This is new in the discord.py 2.0 update
# imports
import discord
import discord.ext
# setting up the bot
intents = discord.Intents.all()
# if you don't want all intents you can do discord.Intents.default()
client = discord.Client(intents=intents)
tree = discord.app_commands.CommandTree(client)
# sync the slash command to your server
@client.event
async def on_ready():
await await tree.sync(guild=discord.Object(id=Your guild ID here))
# print "ready" in the console when the bot is ready to work
print("ready")
# make the slash command
@tree.command(name="name", description="description")
async def slashing_commanding(int: discord.Interaction):
await int.response.send_message("command")
# run the bot
client.run("token")
|
How do i make a working slash command in discord.py
|
I am trying to make a slash command with discord.py I have tried a lot of stuff it doesn't seem to be working. Help would be appreciated.
|
[
"Note: I will include a version for pycord at the end because I think it's much simpler, also it was the original answer.\n\ndiscord.py version\nFirst make sure that you have the newest version of discord.py installed.\nIn your code, you first import the library:\nimport discord\nfrom discord import app_commands\n\nand then you define your client and tree:\nintents = discord.Intents.default()\nclient = discord.Client(intents=intents)\ntree = app_commands.CommandTree(client)\n\nThe tree holds all of your application commands. Then you can define your command:\n@tree.command(name = \"commandname\", description = \"My first application Command\", guild=discord.Object(id=12417128931)) #Add the guild ids in which the slash command will appear. If it should be in all, remove the argument, but note that it will take some time (up to an hour) to register the command if it's for all guilds.\nasync def first_command(interaction):\n await interaction.response.send_message(\"Hello!\")\n\nThen you also have to sync your commands to discord once the client is ready, so we do that in the on_ready event:\n@client.event\nasync def on_ready():\n await tree.sync(guild=discord.Object(id=Your guild id))\n print(\"Ready!\")\n\nAnd at the end we have to run our client:\nclient.run(\"token\")\n\n\npycord version\nTo install py-cord, first run pip uninstall discord.py and then pip install py-cord.\nThen in your code, first import the library with\nimport discord\nfrom discord.ext import commands\n\ncreate you bot class with\nbot = commands.Bot()\n\nand create your slash command with\n@bot.slash_command(name=\"first_slash\", guild_ids=[...]) #Add the guild ids in which the slash command will appear. If it should be in all, remove the argument, but note that it will take some time (up to an hour) to register the command if it's for all guilds.\nasync def first_slash(ctx): \n await ctx.respond(\"You executed the slash command!\")\n\nand then run the bot with your token\nbot.run(TOKEN)\n\n",
"They're sort of in the middle of adding slash commands to discord.py but you can see a few examples in https://gist.github.com/Rapptz/c4324f17a80c94776832430007ad40e6 You seem to be using discord_slash, which I have not used.\nThe main documentation for this stuff is https://discordpy.readthedocs.io/en/master/interactions/api.html?highlight=dropdown#decorators but the main \"how to\" is that you've gotta make a \"tree\", attach commands to that tree, and sync your tree for the commands to show up. discord.ext.Bot makes its own tree, which is why I'm using that instead of client, which I think doesn't make a tree by default.\nIf you specify the guilds, the commands sync takes place instantly, but if you don't specify the guild, I think it takes an hour to update or something like that, so specify the guild until you're ready for deployment.\nI'm not quite sure how to do it in cogs, because I have mine in groups but basically what I'm doing is a combination of @bot.tree.command() in the main bot file and a few groups in separate files.\nSo here's my main file\nimport discord\nimport simplegeneralgroup\nfrom config import TOKEN\nMY_GUILD = discord.Object(id=1234567890)\n\nclass MyBot(discord.ext.commands.Bot):\n async def on_ready(self):\n await self.tree.sync(guild=MY_GUILD)\n\nbot: discord.ext.commands.Bot = MyBot\n\n@bot.tree.command(guild=MY_GUILD)\nasync def slash(interaction: discord.Interaction, number: int, string: str):\n await interaction.response.send_message(f'Modify {number=} {string=}', ephemeral=True)\n\nbot.tree.add_command(simplegeneralgroup.Generalgroup(bot), guild=MY_GUILD)\n\nif __name__ == \"__main__\":\n bot.run(TOKEN)\n\nand then the simplegeneralgroup file\nimport discord\nfrom discord import app_commands as apc\nclass Generalgroup(apc.Group):\n \"\"\"Manage general commands\"\"\"\n def __init__(self, bot: discord.ext.commands.Bot):\n super().__init__()\n self.bot = bot\n\n @apc.command()\n async def hello(self, interaction: discord.Interaction):\n await interaction.response.send_message('Hello')\n\n @apc.command()\n async def version(self, interaction: discord.Interaction):\n \"\"\"tells you what version of the bot software is running.\"\"\"\n await interaction.response.send_message('This is an untested test version')\n\nThere should be three commands: /slash, which will prompt the user for a number and string, /generalgroup hello, and /generalgroup version\n",
"discord.py does not support slash commands. I recommend you use discord-py-interactions for slash commands. To install it is to do python3.exe -m pip install discord-py-interactions. It works well. Here is a sample code to base off:\nimport interactions\n\nbot = interactions.Client(token=\"your_secret_bot_token\")\n\n@bot.command(\n name=\"my_first_command\",\n description=\"This is the first command I made!\",\n scope=the_id_of_your_guild,\n)\nasync def my_first_command(ctx: interactions.CommandContext):\n await ctx.send(\"Hi there!\")\n\nbot.start()\n\n",
"# This is new in the discord.py 2.0 update\n\n# imports\nimport discord\nimport discord.ext\n\n# setting up the bot\nintents = discord.Intents.all() \n# if you don't want all intents you can do discord.Intents.default()\nclient = discord.Client(intents=intents)\ntree = discord.app_commands.CommandTree(client)\n\n# sync the slash command to your server\n@client.event\nasync def on_ready():\n await await tree.sync(guild=discord.Object(id=Your guild ID here))\n # print \"ready\" in the console when the bot is ready to work\n print(\"ready\")\n\n# make the slash command\n@tree.command(name=\"name\", description=\"description\")\nasync def slashing_commanding(int: discord.Interaction): \n await int.response.send_message(\"command\")\n\n# run the bot\nclient.run(\"token\")\n\n"
] |
[
13,
2,
1,
0
] |
[
"discord.py does not support slash commands and will never add support for slash commands (as it has shut down) thus I recommend disnake (a popular fork). Specifically disnake because out of all the forks disnake seems to be the more intellectual one.\n"
] |
[
-12
] |
[
"discord",
"discord.py",
"python"
] |
stackoverflow_0071165431_discord_discord.py_python.txt
|
Q:
Why sum function is slower if the 'start' argument is an instance of custom class?
I was playing around with sum function and observed the following behaviour.
case 1:
source = """
class A:
def __init__(self, a):
self.a = a
def __add__(self, other):
return self.a + other;
sum([*range(10000)], start=A(10))
"""
import timeit
print(timeit.timeit(stmt=source))
As you can see I am using an instance of custom class as start argument to the sum function. Benchmarking above code takes around 192.60747704200003 seconds in my system.
case 2:
source = """
class A:
def __init__(self, a):
self.a = a
def __add__(self, other):
return self.a + other;
sum([*range(10000)], start=10). <- Here
"""
import timeit
print(timeit.timeit(stmt=source))
But if I remove the custom class instance and use int object directly it tooks only 111.48285191600007 seconds. I am curious to understand the reason for this speed difference?
My system info:
>>> import platform
>>> platform.platform()
'macOS-12.5-arm64-arm-64bit'
>>> import sys
>>> sys.version
'3.11.0 (v3.11.0:deaf509e8f, Oct 24 2022, 14:43:23) [Clang 13.0.0 (clang-1300.0.29.30)]'
A:
builtin_sum_impl has 2 implementations inside, one if the start is a number which skips creating python "number objects" and just sums numbers in C.
the other slower implementation when start is not a number, which forces the __add__ method of "number objects" to be called, (because it assumes you are summing some weird classes).
you forced it to use the slower one.
|
Why sum function is slower if the 'start' argument is an instance of custom class?
|
I was playing around with sum function and observed the following behaviour.
case 1:
source = """
class A:
def __init__(self, a):
self.a = a
def __add__(self, other):
return self.a + other;
sum([*range(10000)], start=A(10))
"""
import timeit
print(timeit.timeit(stmt=source))
As you can see I am using an instance of custom class as start argument to the sum function. Benchmarking above code takes around 192.60747704200003 seconds in my system.
case 2:
source = """
class A:
def __init__(self, a):
self.a = a
def __add__(self, other):
return self.a + other;
sum([*range(10000)], start=10). <- Here
"""
import timeit
print(timeit.timeit(stmt=source))
But if I remove the custom class instance and use int object directly it tooks only 111.48285191600007 seconds. I am curious to understand the reason for this speed difference?
My system info:
>>> import platform
>>> platform.platform()
'macOS-12.5-arm64-arm-64bit'
>>> import sys
>>> sys.version
'3.11.0 (v3.11.0:deaf509e8f, Oct 24 2022, 14:43:23) [Clang 13.0.0 (clang-1300.0.29.30)]'
|
[
"builtin_sum_impl has 2 implementations inside, one if the start is a number which skips creating python \"number objects\" and just sums numbers in C.\nthe other slower implementation when start is not a number, which forces the __add__ method of \"number objects\" to be called, (because it assumes you are summing some weird classes).\nyou forced it to use the slower one.\n"
] |
[
5
] |
[
"Maybe looking at the byte-code can help understand what happens. If you run\nimport dis\n\ndef test_range():\n class A:\n def __init__(self, a):\n self.a = a\n\n def __add__(self, other):\n return self.a + other\n\n sum([*range(10000)], start=10)\n\ndis.dis(test_range)\n\nthe version with start=A(10) generates 2 more instructions:\n2 LOAD_CONST 1 (<code object A at 0x7ff0bfa25c90, file \"/.../main.py\", line 5>)\n...\n26 LOAD_CONST 4 (10)\n28 LOAD_CONST 5 (('start',))\n30 CALL_FUNCTION_KW 2\n32 POP_TOP\n34 LOAD_CONST 0 (None)\n36 RETURN_VALUE\n\nvs\n2 LOAD_CONST 1 (<code object A at 0x7ff0bfa25c90, file \"/.../main.py\", line 5>)\n...\n26 LOAD_FAST 0 (A) <--- here\n28 LOAD_CONST 4 (10)\n30 CALL_FUNCTION 1 <--- and here\n32 LOAD_CONST 5 (('start',))\n34 CALL_FUNCTION_KW 2\n36 POP_TOP\n38 LOAD_CONST 0 (None)\n40 RETURN_VALUE\n\nComplete byte-code for version with start=A(10) is here.\nMy (limited) understanding is that those 2 lines point to the initialization of A. Please, someone confirm.\n"
] |
[
-1
] |
[
"cpython",
"optimization",
"python",
"python_3.11",
"python_3.x"
] |
stackoverflow_0074489410_cpython_optimization_python_python_3.11_python_3.x.txt
|
Q:
Rock paper scissors game how to make it infinite
How can I make it so the game is infinite? and is there a way to simplify this code?
I have tried to work around but can't seem to figure it out.
# A rock paper scissors game.
import random
Move1=input("Enter your move: (r)ock (p)aper (s)cissors or (q)uit: ").lower()
Move2=["r","p","s"]
while Move1 != "q":
if Move1 == "r" or "p" or "s" or "q":
# print(random.choice(Move2))
Move2=random.choice(Move2)
if Move1=="r" and Move2=="s":
print("You've won")
break
elif Move2=="p":
print("You lost!")
break
elif Move2=="r":
print("You went even!")
break
if Move1=="p" and Move2=="s":
print("You lost!")
break
elif Move2=="p":
print("You went even!")
break
elif Move2=="r":
print("You won!")
break
if Move1=="s" and Move2=="s":
print("You went even!")
break
elif Move2=="p":
print("You won!")
break
elif Move2=="r":
print("You lost!")
break
else:
print("You've quit the game!")
exit()
Tried to remove break
A:
You have to re-evaluate the input at the end of the while loop. Or you put it into the while condition. So you could do while (Move1 := input(...)) != "q".
Also your first if check is always true because of the or "p". You would have to do or Move1 == "p" or Move1 == "s" or Move1 == "q"
You could simplify it with if Move1 in {"r", "p", "s", "q"}
A:
Move the request for input inside the loop. Use while True: around the loop to make it infinite. Remove all the break statements after reporting the winners and losers.
Don't use the same variable Move2 for the list of moves and the computer's move. That will prevent making a computer choice on the 2nd round.
# A rock paper scissors game.
import random
allowed_moves=["r","p","s"]
while True:
player_move=input("Enter your move: (r)ock (p)aper (s)cissors or (q)uit: ").lower()
if player_move in allowed_moves:
Move2=random.choice(allowed_moves)
if player_move=="r" and Move2=="s":
print("You've won")
elif Move2=="p":
print("You lost!")
elif Move2=="r":
print("You went even!")
if player_move=="p" and Move2=="s":
print("You lost!")
elif Move2=="p":
print("You went even!")
elif Move2=="r":
print("You won!")
if player_move=="s" and Move2=="s":
print("You went even!")
elif Move2=="p":
print("You won!")
elif Move2=="r":
print("You lost!")
else if player_move == 'q':
print("You've quit the game!")
break
else:
print("That's not a valid move!")
A:
Abstracting some of the game logic to a function is a start in the direction of simplifying. But there are other ways to simplify. Here's an example of it along with what I think you mean by making the game infinite.
def play(move1, move2):
# the logic
print("you win")
# more logic
is_playing = True
while is_playing:
Move1 = input(
"Enter your move: (r)ock (p)aper (s)cissors or (q)uit: ").lower()
Move2 = ["r", "p", "s"]
if Move1 == 'q':
print("You've quit the game!")
is_playing = False
break
play(Move1, Move2)
Let me know if that helps or not
|
Rock paper scissors game how to make it infinite
|
How can I make it so the game is infinite? and is there a way to simplify this code?
I have tried to work around but can't seem to figure it out.
# A rock paper scissors game.
import random
Move1=input("Enter your move: (r)ock (p)aper (s)cissors or (q)uit: ").lower()
Move2=["r","p","s"]
while Move1 != "q":
if Move1 == "r" or "p" or "s" or "q":
# print(random.choice(Move2))
Move2=random.choice(Move2)
if Move1=="r" and Move2=="s":
print("You've won")
break
elif Move2=="p":
print("You lost!")
break
elif Move2=="r":
print("You went even!")
break
if Move1=="p" and Move2=="s":
print("You lost!")
break
elif Move2=="p":
print("You went even!")
break
elif Move2=="r":
print("You won!")
break
if Move1=="s" and Move2=="s":
print("You went even!")
break
elif Move2=="p":
print("You won!")
break
elif Move2=="r":
print("You lost!")
break
else:
print("You've quit the game!")
exit()
Tried to remove break
|
[
"You have to re-evaluate the input at the end of the while loop. Or you put it into the while condition. So you could do while (Move1 := input(...)) != \"q\".\nAlso your first if check is always true because of the or \"p\". You would have to do or Move1 == \"p\" or Move1 == \"s\" or Move1 == \"q\"\nYou could simplify it with if Move1 in {\"r\", \"p\", \"s\", \"q\"}\n",
"Move the request for input inside the loop. Use while True: around the loop to make it infinite. Remove all the break statements after reporting the winners and losers.\nDon't use the same variable Move2 for the list of moves and the computer's move. That will prevent making a computer choice on the 2nd round.\n# A rock paper scissors game.\nimport random\n\nallowed_moves=[\"r\",\"p\",\"s\"]\n\nwhile True:\n player_move=input(\"Enter your move: (r)ock (p)aper (s)cissors or (q)uit: \").lower()\n if player_move in allowed_moves:\n Move2=random.choice(allowed_moves)\n if player_move==\"r\" and Move2==\"s\":\n print(\"You've won\")\n elif Move2==\"p\":\n print(\"You lost!\")\n elif Move2==\"r\":\n print(\"You went even!\")\n if player_move==\"p\" and Move2==\"s\":\n print(\"You lost!\")\n elif Move2==\"p\":\n print(\"You went even!\")\n elif Move2==\"r\":\n print(\"You won!\")\n if player_move==\"s\" and Move2==\"s\":\n print(\"You went even!\")\n elif Move2==\"p\":\n print(\"You won!\")\n elif Move2==\"r\":\n print(\"You lost!\")\n else if player_move == 'q':\n print(\"You've quit the game!\")\n break\n else:\n print(\"That's not a valid move!\")\n\n",
"Abstracting some of the game logic to a function is a start in the direction of simplifying. But there are other ways to simplify. Here's an example of it along with what I think you mean by making the game infinite.\ndef play(move1, move2):\n # the logic\n print(\"you win\")\n # more logic\n\n\nis_playing = True\nwhile is_playing:\n Move1 = input(\n \"Enter your move: (r)ock (p)aper (s)cissors or (q)uit: \").lower()\n Move2 = [\"r\", \"p\", \"s\"]\n if Move1 == 'q':\n print(\"You've quit the game!\")\n is_playing = False\n break\n play(Move1, Move2)\n\nLet me know if that helps or not\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074494604_python.txt
|
Q:
How do I concatenate integers with lists in Python?
I have a python script that creates lists of numbers and I add some of those numbers together as integers.
ddtricks = [deal.dd_tricks("4SN"), \
deal.dd_tricks("5HE"),deal.dd_tricks("5DE"),deal.dd_tricks("5CE"), \
deal.dd_tricks("5HW"),deal.dd_tricks("5DW"),deal.dd_tricks("5CW") ]
ddscores = [deal.dd_score("4SN", NS_Vul), \
deal.dd_score("5HW", EW_Vul), deal.dd_score("5DE", EW_Vul), deal.dd_score("5CW", EW_Vul), \
deal.dd_score("5HE", EW_Vul), deal.dd_score("5DW", EW_Vul), deal.dd_score("5CE", EW_Vul)]
TotNSScore = TotNSScore + deal.dd_score("4SN", NS_Vul)
MaxEWScore = max(deal.dd_score("5HW", EW_Vul), deal.dd_score("5DE", EW_Vul), deal.dd_score("5CW", EW_Vul), \
deal.dd_score("5HE", EW_Vul), deal.dd_score("5DW", EW_Vul), deal.dd_score("5CE", EW_Vul))
TotEWScore = TotEWScore + MaxEWScore
Then I want to print those out together:
outputlist = ddtricks+ddscores+MaxEWScore+Bid4SGood
for x in outputlist :
f.write(str(x)+", ")
f.write("\n")
Creating outputlist gives this error: "outputlist = ddtricks+ddscores+MaxEWScore+Bid4SGood
TypeError: can only concatenate list (not "int") to list"
If I make TotEWScore and MaxEWScore lists, I don't think I can add them together and get the arithmetic sum. And I can't find anything that allows me to type cast those variables as a list to allow concatenation.
I'm pretty new to python. Programming experience mainly in Fortran and pascal, so data structures like lists are foreign to me.
Any suggestions?
A:
You can either wrap them in a list to concatenate them with other lists:
outputlist = ddtricks + ddscores + [MaxEWScore, Bid4SGood]
or use spread syntax for the existing lists:
outputlist = [*ddtricks, *ddscores, MaxEWScore, Bid4SGood]
And when you're writing to the file, you can use join() instead of a loop:
f.write(", ".join(outputlist) + "\n")
|
How do I concatenate integers with lists in Python?
|
I have a python script that creates lists of numbers and I add some of those numbers together as integers.
ddtricks = [deal.dd_tricks("4SN"), \
deal.dd_tricks("5HE"),deal.dd_tricks("5DE"),deal.dd_tricks("5CE"), \
deal.dd_tricks("5HW"),deal.dd_tricks("5DW"),deal.dd_tricks("5CW") ]
ddscores = [deal.dd_score("4SN", NS_Vul), \
deal.dd_score("5HW", EW_Vul), deal.dd_score("5DE", EW_Vul), deal.dd_score("5CW", EW_Vul), \
deal.dd_score("5HE", EW_Vul), deal.dd_score("5DW", EW_Vul), deal.dd_score("5CE", EW_Vul)]
TotNSScore = TotNSScore + deal.dd_score("4SN", NS_Vul)
MaxEWScore = max(deal.dd_score("5HW", EW_Vul), deal.dd_score("5DE", EW_Vul), deal.dd_score("5CW", EW_Vul), \
deal.dd_score("5HE", EW_Vul), deal.dd_score("5DW", EW_Vul), deal.dd_score("5CE", EW_Vul))
TotEWScore = TotEWScore + MaxEWScore
Then I want to print those out together:
outputlist = ddtricks+ddscores+MaxEWScore+Bid4SGood
for x in outputlist :
f.write(str(x)+", ")
f.write("\n")
Creating outputlist gives this error: "outputlist = ddtricks+ddscores+MaxEWScore+Bid4SGood
TypeError: can only concatenate list (not "int") to list"
If I make TotEWScore and MaxEWScore lists, I don't think I can add them together and get the arithmetic sum. And I can't find anything that allows me to type cast those variables as a list to allow concatenation.
I'm pretty new to python. Programming experience mainly in Fortran and pascal, so data structures like lists are foreign to me.
Any suggestions?
|
[
"You can either wrap them in a list to concatenate them with other lists:\noutputlist = ddtricks + ddscores + [MaxEWScore, Bid4SGood]\n\nor use spread syntax for the existing lists:\noutputlist = [*ddtricks, *ddscores, MaxEWScore, Bid4SGood]\n\nAnd when you're writing to the file, you can use join() instead of a loop:\nf.write(\", \".join(outputlist) + \"\\n\")\n\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074494658_python.txt
|
Q:
Django regroup tag get fields values
I have a web page where I have two models for Products and Categories. I have this navbar where you can filter the Productos by categories, so in order to make it dynamic I passed the categories to the navbar and then applied a regroup since I'm getting the categories from the model Products since is the one the page is using to show the products.
When I try to filter catching the value from the regroup and pass it to my view:
class Categoria_Filter(ListView):
model = Productos
paginate_by = 10
template_name = 'mail/category-filter.html'
def get_queryset(self):
categoria = self.kwargs['slug']
print(categoria)
if categoria == 'Todos':
return Productos.objects.all()
else:
return Productos.objects.filter(categoria = categoria)
I get the following result when printing:
GroupedResult(grouper=<Categorias: Guantes de Box>, list=[<Productos: Guantes Básico ADX>])
which according to the docs is a namedtuple()
I have tried the following:
print(getattr(categoria, 'GroupedResult'))
print(getattr(categoria, 'grouper'))
print(getattr(categoria, 'Categorias'))
They all give me:
AttributeError: 'str' object has no attribute 'whatever field I have tried'
Also, I print by index and for example:
print(categoria[1])
gives me
r
I know is the r from GroupedResult and what I want to get from the namedtuple is Guantes de Box not:
GroupedResult(grouper=<Categorias: Guantes de Box>, list=[<Productos: Guantes Básico ADX>])
This is the regroup in template:
{% regroup object_list by categoria as categoria_list %}
{% for item in categoria_list%}
<li class="nav-item">
<a class="nav-link text-white" href="{% url 'categoria-filter' item %}">{{ item.grouper }}</a>
</li>
{% endfor %}
A:
Based on the below line which you have in your get_queryset() of your class-based view:
categoria = self.kwargs['slug']
categoria is the value of 'slug' key in the request and of course it is an instance of str data type in python programming language.
But based on what I can find out from your question you need to Guantes de Box and with the below code and in {{ x.grouper }}, you can see the phrase Guantes de Box.
{% regroup object by object.property as newname %}
{% for x in newname %}
{{ x.grouper }} --> this expression gives you the grouper names
{% for y in x.list %}
<p>{{ y.blobfield }}: {{ y.blobblobfield }}</p>
{% endfor %}
{% endfor %}
|
Django regroup tag get fields values
|
I have a web page where I have two models for Products and Categories. I have this navbar where you can filter the Productos by categories, so in order to make it dynamic I passed the categories to the navbar and then applied a regroup since I'm getting the categories from the model Products since is the one the page is using to show the products.
When I try to filter catching the value from the regroup and pass it to my view:
class Categoria_Filter(ListView):
model = Productos
paginate_by = 10
template_name = 'mail/category-filter.html'
def get_queryset(self):
categoria = self.kwargs['slug']
print(categoria)
if categoria == 'Todos':
return Productos.objects.all()
else:
return Productos.objects.filter(categoria = categoria)
I get the following result when printing:
GroupedResult(grouper=<Categorias: Guantes de Box>, list=[<Productos: Guantes Básico ADX>])
which according to the docs is a namedtuple()
I have tried the following:
print(getattr(categoria, 'GroupedResult'))
print(getattr(categoria, 'grouper'))
print(getattr(categoria, 'Categorias'))
They all give me:
AttributeError: 'str' object has no attribute 'whatever field I have tried'
Also, I print by index and for example:
print(categoria[1])
gives me
r
I know is the r from GroupedResult and what I want to get from the namedtuple is Guantes de Box not:
GroupedResult(grouper=<Categorias: Guantes de Box>, list=[<Productos: Guantes Básico ADX>])
This is the regroup in template:
{% regroup object_list by categoria as categoria_list %}
{% for item in categoria_list%}
<li class="nav-item">
<a class="nav-link text-white" href="{% url 'categoria-filter' item %}">{{ item.grouper }}</a>
</li>
{% endfor %}
|
[
"Based on the below line which you have in your get_queryset() of your class-based view:\n\ncategoria = self.kwargs['slug']\n\n\ncategoria is the value of 'slug' key in the request and of course it is an instance of str data type in python programming language.\nBut based on what I can find out from your question you need to Guantes de Box and with the below code and in {{ x.grouper }}, you can see the phrase Guantes de Box.\n{% regroup object by object.property as newname %}\n\n{% for x in newname %}\n {{ x.grouper }} --> this expression gives you the grouper names\n {% for y in x.list %}\n <p>{{ y.blobfield }}: {{ y.blobblobfield }}</p>\n {% endfor %}\n{% endfor %}\n\n"
] |
[
1
] |
[] |
[] |
[
"django",
"django_templates",
"django_views",
"python",
"templatetags"
] |
stackoverflow_0074494575_django_django_templates_django_views_python_templatetags.txt
|
Q:
How can I run my class only once in a while loop in pygame?
I have this function:
def draw_image(image, xy ,draw_img=True,camera=False):
all_images.append(Image(image, xy, draw_img, camera))
#draw all images
for image in all_images:
image.run()
pass
and in the class I have this:
class Image:
def __init__(self, image, xy, draw_img, camera):
self.image = image
self.x = list(xy)[0]
self.y = list(xy)[1]
self.draw_img = draw_img
self.camera = camera
pass
def run(self):
global
col_up,col_down,col_left,col_right,right_speed,left_speed,up_speed,down_speed,left_key,up_key,down_key,jump_velocity, left_key,right_key,up_key,down_key,run_once6,run_once3,jumped, time, last_time,change_x,player_speed,change_y
if self.draw_img:
if not camera:
screen.blit(self.image, (self.x, self.y))
if camera:
if change_x == 'x-':
self.x += player_speed
if change_x == 'x+':
self.x -= player_speed
if change_y == 'y-':
self.y += player_speed
if change_y == 'y+':
self.y -= player_speed
if self.draw_img:
if camera:
screen.blit(self.image, (self.x, self.y))
pass
pass
I need to call draw_image() in a while loop.
So, two things occur:
The first thing that occurs is that the program keeps adding to the list.
I can fix this by placing the variable in the while loop.
The second thing is that the init file runs every frame.
As such, everything in init() is ran multiple times, which is not supposed to happen.
When I say self.x += 1, it is instantly reset to 0. As such, I'm not able to change the position of the image.
A:
If you want to control something over time in Pygame you have two options:
Use pygame.time.get_ticks() to measure time and and implement logic that controls the object depending on the time.
Use the timer event. Use pygame.time.set_timer() to repeatedly create a USEREVENT in the event queue. Change object states when the event occurs.
e.g.: Spawning multiple instances of the same object concurrently in python
|
How can I run my class only once in a while loop in pygame?
|
I have this function:
def draw_image(image, xy ,draw_img=True,camera=False):
all_images.append(Image(image, xy, draw_img, camera))
#draw all images
for image in all_images:
image.run()
pass
and in the class I have this:
class Image:
def __init__(self, image, xy, draw_img, camera):
self.image = image
self.x = list(xy)[0]
self.y = list(xy)[1]
self.draw_img = draw_img
self.camera = camera
pass
def run(self):
global
col_up,col_down,col_left,col_right,right_speed,left_speed,up_speed,down_speed,left_key,up_key,down_key,jump_velocity, left_key,right_key,up_key,down_key,run_once6,run_once3,jumped, time, last_time,change_x,player_speed,change_y
if self.draw_img:
if not camera:
screen.blit(self.image, (self.x, self.y))
if camera:
if change_x == 'x-':
self.x += player_speed
if change_x == 'x+':
self.x -= player_speed
if change_y == 'y-':
self.y += player_speed
if change_y == 'y+':
self.y -= player_speed
if self.draw_img:
if camera:
screen.blit(self.image, (self.x, self.y))
pass
pass
I need to call draw_image() in a while loop.
So, two things occur:
The first thing that occurs is that the program keeps adding to the list.
I can fix this by placing the variable in the while loop.
The second thing is that the init file runs every frame.
As such, everything in init() is ran multiple times, which is not supposed to happen.
When I say self.x += 1, it is instantly reset to 0. As such, I'm not able to change the position of the image.
|
[
"If you want to control something over time in Pygame you have two options:\n\nUse pygame.time.get_ticks() to measure time and and implement logic that controls the object depending on the time.\n\nUse the timer event. Use pygame.time.set_timer() to repeatedly create a USEREVENT in the event queue. Change object states when the event occurs.\n\n\ne.g.: Spawning multiple instances of the same object concurrently in python\n"
] |
[
0
] |
[] |
[] |
[
"pygame",
"python"
] |
stackoverflow_0074308675_pygame_python.txt
|
Q:
on_message not being triggered when using interactions.Client
I'm using Interactions.py (client = interactions.Client) so that I can use its sophisticated slash commands system, but as a result the on_message event method is no longer triggered. When I use Discord.py (client = discord.Client) the on_message method works successfully.
How do I get on_message to work while using the slash command system of Interactions.py?
import os
import os.path
import interactions
import mysql.connector
import ast
from asyncio.windows_events import NULL
import operator as op
import discord
import inspect
from math import sqrt
from dotenv import load_dotenv
intents = discord.Intents
intents.messages = True
client = interactions.Client(token=TOKEN)
@client.command(
#command details here
)
async def count(ctx: interactions.CommandContext, command: str):
#manage incoming commands
#this only works correctly when I use client = interactions.Client
@client.event
async def on_message(message):
#do things based on message contents
#this only works correctly when I use client = discord.Client
client.Start()
Thanks!
A:
It would be on_message_create, as this is the name that the discord api uses
|
on_message not being triggered when using interactions.Client
|
I'm using Interactions.py (client = interactions.Client) so that I can use its sophisticated slash commands system, but as a result the on_message event method is no longer triggered. When I use Discord.py (client = discord.Client) the on_message method works successfully.
How do I get on_message to work while using the slash command system of Interactions.py?
import os
import os.path
import interactions
import mysql.connector
import ast
from asyncio.windows_events import NULL
import operator as op
import discord
import inspect
from math import sqrt
from dotenv import load_dotenv
intents = discord.Intents
intents.messages = True
client = interactions.Client(token=TOKEN)
@client.command(
#command details here
)
async def count(ctx: interactions.CommandContext, command: str):
#manage incoming commands
#this only works correctly when I use client = interactions.Client
@client.event
async def on_message(message):
#do things based on message contents
#this only works correctly when I use client = discord.Client
client.Start()
Thanks!
|
[
"It would be on_message_create, as this is the name that the discord api uses\n"
] |
[
1
] |
[] |
[] |
[
"discord.py",
"discord_interactions",
"python"
] |
stackoverflow_0074332471_discord.py_discord_interactions_python.txt
|
Q:
Can't import scipy in Spyder: ImportError results
I updated some packages this morning using conda, including scipy. The new version is 1.9.3. I can no longer import certain modules from my Spyder console:
>>> import scipy.special
Traceback (most recent call last):
File "C:\Users\igurin\AppData\Local\Temp\ipykernel_19736\2717555404.py", line 1, in <module>
import scipy.special
File "C:\Users\igurin\Anaconda3\envs\latest\lib\site-packages\scipy\special\__init__.py", line 649, in <module>
from . import _ufuncs
ImportError: DLL load failed while importing _ufuncs: The specified procedure could not be found.
It works in a "plain" IPython session (launched from the Anaconda prompt), though.
To make matters worse, I can't seem to use conda to install any version of scipy other than 1.9.3.
Version info
Spyder version: 5.3.3 (conda)
Python version: 3.10.8 64-bit
Qt version: 5.15.2
PyQt5 version: 5.15.7
Operating System: Windows 10
Attempted solutions
Tried this.
Deleted my whole environment and reinstalled from scratch.
A:
I found an answer on GitHub for Spyder. I removed Anaconda from my Windows path, and the import works now. I'm treating this as a workaround rather than a solution, though.
|
Can't import scipy in Spyder: ImportError results
|
I updated some packages this morning using conda, including scipy. The new version is 1.9.3. I can no longer import certain modules from my Spyder console:
>>> import scipy.special
Traceback (most recent call last):
File "C:\Users\igurin\AppData\Local\Temp\ipykernel_19736\2717555404.py", line 1, in <module>
import scipy.special
File "C:\Users\igurin\Anaconda3\envs\latest\lib\site-packages\scipy\special\__init__.py", line 649, in <module>
from . import _ufuncs
ImportError: DLL load failed while importing _ufuncs: The specified procedure could not be found.
It works in a "plain" IPython session (launched from the Anaconda prompt), though.
To make matters worse, I can't seem to use conda to install any version of scipy other than 1.9.3.
Version info
Spyder version: 5.3.3 (conda)
Python version: 3.10.8 64-bit
Qt version: 5.15.2
PyQt5 version: 5.15.7
Operating System: Windows 10
Attempted solutions
Tried this.
Deleted my whole environment and reinstalled from scratch.
|
[
"I found an answer on GitHub for Spyder. I removed Anaconda from my Windows path, and the import works now. I'm treating this as a workaround rather than a solution, though.\n"
] |
[
0
] |
[] |
[] |
[
"import",
"python",
"scipy",
"spyder"
] |
stackoverflow_0074494510_import_python_scipy_spyder.txt
|
Q:
Forming a frame of zeros around a matrix in python
I am trying to pad a matrix with zeros, but am not really sure how to do it. Basically I need to surround a matrix with an n amount of zeros. The input matrix is huge (it represents an image)
Example:
Input:
1 2 3 4
5 6 7 8
4 3 2 1
n = 2
Output:
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 1 2 3 4 0 0
0 0 5 6 7 8 0 0
0 0 4 3 2 1 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
The problem is that I get "k" is not accessed and "l" is not accessed.
Code:
import numpy as np
n = 2
matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[4, 3, 2, 1]]
modified_matrix = np.zeros(shape=((len(matrix) + n), (len(matrix[0]) + n)), dtype=int)
k = n
l = n
modified_matrix = [[l] for l in range(len(matrix[k])] for k in range(len(matrix))]
A:
You can use NumPy's slice notation.
import numpy as np
#input matrix
A = np.array([[1,2,3,4],
[3,4,5,6]])
#get matrix shape
x,y=A.shape
#set amount of zeros
n=2
#create zero's matrix
B=np.zeros((x+2*n,y+2*n),dtype=int)
# insert & slice
B[n:x+n, n:y+n] = A
#show result
for row in B:
print(row)
Output:
[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]
[0 0 1 2 3 4 0 0]
[0 0 3 4 5 6 0 0]
[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]
|
Forming a frame of zeros around a matrix in python
|
I am trying to pad a matrix with zeros, but am not really sure how to do it. Basically I need to surround a matrix with an n amount of zeros. The input matrix is huge (it represents an image)
Example:
Input:
1 2 3 4
5 6 7 8
4 3 2 1
n = 2
Output:
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 1 2 3 4 0 0
0 0 5 6 7 8 0 0
0 0 4 3 2 1 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
The problem is that I get "k" is not accessed and "l" is not accessed.
Code:
import numpy as np
n = 2
matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[4, 3, 2, 1]]
modified_matrix = np.zeros(shape=((len(matrix) + n), (len(matrix[0]) + n)), dtype=int)
k = n
l = n
modified_matrix = [[l] for l in range(len(matrix[k])] for k in range(len(matrix))]
|
[
"You can use NumPy's slice notation.\nimport numpy as np\n\n#input matrix\nA = np.array([[1,2,3,4],\n [3,4,5,6]])\n\n#get matrix shape\nx,y=A.shape\n\n#set amount of zeros\nn=2 \n\n#create zero's matrix\nB=np.zeros((x+2*n,y+2*n),dtype=int)\n\n# insert & slice\nB[n:x+n, n:y+n] = A\n\n#show result\nfor row in B:\n print(row) \n\nOutput:\n[0 0 0 0 0 0 0 0]\n[0 0 0 0 0 0 0 0]\n[0 0 1 2 3 4 0 0]\n[0 0 3 4 5 6 0 0]\n[0 0 0 0 0 0 0 0]\n[0 0 0 0 0 0 0 0]\n\n"
] |
[
0
] |
[] |
[] |
[
"matrix",
"padding",
"python",
"zero_pad",
"zero_padding"
] |
stackoverflow_0074494304_matrix_padding_python_zero_pad_zero_padding.txt
|
Q:
How do i analyze the running time of a function with a for loop with an if statement?
For example, let the function consist:
def myfunc():
total = 0
for i in range(0, n):
total+=i
if total >= n:
return total
return 0
What would the running time be?
I cant seem to figure out a way to analyze this problem.
A:
You can define your own decorator, like this:
def timed_function(f):
def wrapper(*args, **kwargs):
import time
start_time = time.time()
result = f(*args, **kwargs)
elapsed = time.time() - start_time
print("{} took {} seconds to run.".format(f, elapsed))
return result
return wrapper
@timed_function
def adding():
a = 0
for i in range(10000000):
a = a + 1
return a
adding()
<function adding at 0x0000023711A0EE50> took 0.49866580963134766 seconds to run.
Edit: Maybe you just need the basics? Then import the time module, and measure before and after running your code, and then print the result. For example:
import time
start_time = time.time()
#your code goes here
end_time = time.time()
time_elapsed = end_time - start_time
print("Took", time_elapsed)
|
How do i analyze the running time of a function with a for loop with an if statement?
|
For example, let the function consist:
def myfunc():
total = 0
for i in range(0, n):
total+=i
if total >= n:
return total
return 0
What would the running time be?
I cant seem to figure out a way to analyze this problem.
|
[
"You can define your own decorator, like this:\ndef timed_function(f):\n def wrapper(*args, **kwargs):\n import time\n start_time = time.time()\n result = f(*args, **kwargs)\n elapsed = time.time() - start_time\n print(\"{} took {} seconds to run.\".format(f, elapsed))\n return result\n return wrapper\n\n\n@timed_function\ndef adding():\n a = 0\n for i in range(10000000):\n a = a + 1\n return a\n\nadding()\n\n\n<function adding at 0x0000023711A0EE50> took 0.49866580963134766 seconds to run.\n\nEdit: Maybe you just need the basics? Then import the time module, and measure before and after running your code, and then print the result. For example:\nimport time\n\nstart_time = time.time()\n\n#your code goes here\n\nend_time = time.time()\ntime_elapsed = end_time - start_time\nprint(\"Took\", time_elapsed)\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"running_count"
] |
stackoverflow_0074494820_python_running_count.txt
|
Q:
Insert multiple rows while inheriting cell styles
I have an XLSX file which I want to use as a minimum template to be expanded and filled with user data using openpyxl. With 'minimum' I mean that I want to define just one or two rows within the XLSX template in the way that I later insert further rows while keeping the format / style of the rows from the template.
Example
| A | B | C | D
---+----------+----------+----------+-----...
| | | |
...
---+----------+----------+----------+-----...
| | | |
4 | | | |
| | | |
---+----------+----------+----------+-----...
| | | |
5 | TEMPLATE | TEMPLATE | TEMPLATE | TEMPLATE
| | | |
---+----------+----------+----------+-----...
| | | |
6 | TEMPLATE | TEMPLATE | TEMPLATE | TEMPLATE
| | | |
---+----------+----------+----------+-----...
| | | |
7 | | | |
| | | |
---+----------+----------+----------+-----...
| | | |
...
Now, within the template XLSX file (see example above), the rows 5 and 6 are specifically formatted regarding font, font size, border style, foreground color, vertical adjustment, ... as well as their row heights, (not standard or automatic but about 35,09 to hold about 3 lines of text).
Using openpyxl I read in the example XLSX file and then I use a Python loop to
insert a new row at "row 6" which should result in a new row between row 5 and 6 and should be my "new row 6" when doing further adjustments.
using another loop to go through each cell of the new row and copy the formats / styles from the "former row 6" (or even "row 5") into the new "new row 6"
adjusting row height of my "new row 6" to be like the one of the "former row 6" (or even "row 5").
Here is the code:
import copy
# with "ws" being the pointer to the current worksheet
# set column span
max_cols = ws.max_column
# apply for desired number of rows
for _iRow in range(10):
# create new row
ws.insert_rows(6)
# set format of entire row
for _iCol in range(1, max_cols +1):
# cell styles
ws.cell(6, _iCol).font = copy.copy(ws.cell(7, _iCol).font)
ws.cell(6, _iCol).fill = copy.copy(ws.cell(7, _iCol).fill)
ws.cell(6, _iCol).border = copy.copy(ws.cell(7, _iCol).border)
ws.cell(6, _iCol).alignment = copy.copy(ws.cell(7, _iCol).alignment)
# column dimensions
ws.row_dimensions[6].height = ws.row_dimensions[5].height
While the single cell formats / styles get transferred into the new rows, correctly, the row height does only for the first new row. all further rows seem to be set to "automatic" row height and not to the one of the former inserted row.
Is this a known effect? Does anybody know a workaround?
A:
I had the same issue and came up with that function which inserts a number of rows under the "pointer" row and copies the style from each cell in that row to the newly inserted rows.
import openpyxl.worksheet.worksheet as _sheet
from copy import copy
def insertRowsFormat(rowP: int, number: int, sheet: _sheet.Worksheet):
# insert rows right under the pointer row to keep same index
sheet.insert_rows(rowP + 1, number)
# copy style cell by cell using the reference cell at the top of the column
for j in range(1, sheet.max_column):
refCell = sheet.cell(rowP, j)
for i in range(rowP, rowP + number + 1):
sheet.cell(i, j).font = copy(refCell.font)
sheet.cell(i, j).border = copy(refCell.border)
sheet.cell(i, j).fill = copy(refCell.fill)
sheet.cell(i, j).number_format = copy(refCell.number_format)
sheet.cell(i, j).protection = copy(refCell.protection)
sheet.cell(i, j).alignment = copy(refCell.alignment)enter code here
I hope this can help someone.
|
Insert multiple rows while inheriting cell styles
|
I have an XLSX file which I want to use as a minimum template to be expanded and filled with user data using openpyxl. With 'minimum' I mean that I want to define just one or two rows within the XLSX template in the way that I later insert further rows while keeping the format / style of the rows from the template.
Example
| A | B | C | D
---+----------+----------+----------+-----...
| | | |
...
---+----------+----------+----------+-----...
| | | |
4 | | | |
| | | |
---+----------+----------+----------+-----...
| | | |
5 | TEMPLATE | TEMPLATE | TEMPLATE | TEMPLATE
| | | |
---+----------+----------+----------+-----...
| | | |
6 | TEMPLATE | TEMPLATE | TEMPLATE | TEMPLATE
| | | |
---+----------+----------+----------+-----...
| | | |
7 | | | |
| | | |
---+----------+----------+----------+-----...
| | | |
...
Now, within the template XLSX file (see example above), the rows 5 and 6 are specifically formatted regarding font, font size, border style, foreground color, vertical adjustment, ... as well as their row heights, (not standard or automatic but about 35,09 to hold about 3 lines of text).
Using openpyxl I read in the example XLSX file and then I use a Python loop to
insert a new row at "row 6" which should result in a new row between row 5 and 6 and should be my "new row 6" when doing further adjustments.
using another loop to go through each cell of the new row and copy the formats / styles from the "former row 6" (or even "row 5") into the new "new row 6"
adjusting row height of my "new row 6" to be like the one of the "former row 6" (or even "row 5").
Here is the code:
import copy
# with "ws" being the pointer to the current worksheet
# set column span
max_cols = ws.max_column
# apply for desired number of rows
for _iRow in range(10):
# create new row
ws.insert_rows(6)
# set format of entire row
for _iCol in range(1, max_cols +1):
# cell styles
ws.cell(6, _iCol).font = copy.copy(ws.cell(7, _iCol).font)
ws.cell(6, _iCol).fill = copy.copy(ws.cell(7, _iCol).fill)
ws.cell(6, _iCol).border = copy.copy(ws.cell(7, _iCol).border)
ws.cell(6, _iCol).alignment = copy.copy(ws.cell(7, _iCol).alignment)
# column dimensions
ws.row_dimensions[6].height = ws.row_dimensions[5].height
While the single cell formats / styles get transferred into the new rows, correctly, the row height does only for the first new row. all further rows seem to be set to "automatic" row height and not to the one of the former inserted row.
Is this a known effect? Does anybody know a workaround?
|
[
"I had the same issue and came up with that function which inserts a number of rows under the \"pointer\" row and copies the style from each cell in that row to the newly inserted rows.\nimport openpyxl.worksheet.worksheet as _sheet\nfrom copy import copy\n\ndef insertRowsFormat(rowP: int, number: int, sheet: _sheet.Worksheet):\n # insert rows right under the pointer row to keep same index\n sheet.insert_rows(rowP + 1, number)\n # copy style cell by cell using the reference cell at the top of the column\n for j in range(1, sheet.max_column):\n refCell = sheet.cell(rowP, j)\n for i in range(rowP, rowP + number + 1):\n sheet.cell(i, j).font = copy(refCell.font)\n sheet.cell(i, j).border = copy(refCell.border)\n sheet.cell(i, j).fill = copy(refCell.fill)\n sheet.cell(i, j).number_format = copy(refCell.number_format)\n sheet.cell(i, j).protection = copy(refCell.protection)\n sheet.cell(i, j).alignment = copy(refCell.alignment)enter code here\n\nI hope this can help someone.\n"
] |
[
0
] |
[] |
[] |
[
"openpyxl",
"python"
] |
stackoverflow_0066933271_openpyxl_python.txt
|
Q:
How to apply default value to Python dataclass field when None was passed?
I need a class that will accept a number of parameters, I know that all parameters will be provided but some maybe passed as None in which case my class will have to provide default values.
I want to setup a simple dataclass with a some default values like so:
@dataclass
class Specs1:
a: str
b: str = 'Bravo'
c: str = 'Charlie'
I would like to be able to get the default value for the second field but still set a value for the third one. I cannot do this with None because it is happily accepted as a value for my string:
r1 = Specs1('Apple', None, 'Cherry') # Specs1(a='Apple', b=None, c='Cherry')
I have come up with the following solution:
@dataclass
class Specs2:
def_b: ClassVar = 'Bravo'
def_c: ClassVar = 'Charlie'
a: str
b: str = def_b
c: str = def_c
def __post_init__(self):
self.b = self.def_b if self.b is None else self.b
self.c = self.def_c if self.c is None else self.c
Which seems to behave as intended:
r2 = Specs2('Apple', None, 'Cherry') # Specs2(a='Apple', b='Bravo', c='Cherry')
However, I feel it is quite ugly and that I am maybe missing something here. My actual class will have more fields so it will only get uglier.
The parameters passed to the class contain None and I do not have control over this aspect.
A:
The simple solution is to just implement the default arguments in __post_init__() only!
@dataclass
class Specs2:
a: str
b: str
c: str
def __post_init__(self):
if self.b is None:
self.b = 'Bravo'
if self.c is None:
self.c = 'Charlie'
(Code is not tested. If I got some detail wrong, it wouldn't be the first time)
A:
Here is another solution.
Define DefaultVal and NoneRefersDefault types:
from dataclasses import dataclass, fields
@dataclass
class DefaultVal:
val: Any
@dataclass
class NoneRefersDefault:
def __post_init__(self):
for field in fields(self):
# if a field of this data class defines a default value of type
# `DefaultVal`, then use its value in case the field after
# initialization has either not changed or is None.
if isinstance(field.default, DefaultVal):
field_val = getattr(self, field.name)
if isinstance(field_val, DefaultVal) or field_val is None:
setattr(self, field.name, field.default.val)
Usage:
@dataclass
class Specs3(NoneRefersDefault):
a: str
b: str = DefaultVal('Bravo')
c: str = DefaultVal('Charlie')
r3 = Specs3('Apple', None, 'Cherry') # Specs3(a='Apple', b='Bravo', c='Cherry')
EDIT #1: Rewritten NoneRefersDefault such that the following is possible as well:
@dataclass
r3 = Specs3('Apple', None) # Specs3(a='Apple', b='Bravo', c='Charlie')
EDIT #2: Note that if no class inherits from Spec, it might be better to have no default values in the dataclass and a "constructor" function create_spec instead:
@dataclass
class Specs4:
a: str
b: str
c: str
def create_spec(
a: str,
b: str = None,
c: str = None,
):
if b is None:
b = 'Bravo'
if c is None:
c = 'Charlie'
return Spec4(a=a, b=b, c=c)
also see dataclass-abc/example
A:
I know this is a little late, but inspired by MikeSchneeberger's answer I made a small adaptation to the __post_init__ function that allows you to keep the defaults in the standard format:
from dataclasses import dataclass, fields
def __post_init__(self):
# Loop through the fields
for field in fields(self):
# If there is a default and the value of the field is none we can assign a value
if not isinstance(field.default, dataclasses._MISSING_TYPE) and getattr(self, field.name) is None:
setattr(self, field.name, field.default)
Adding this to your dataclass should then ensure that the default values are enforced without requiring a new default class.
A:
In data classes you can access a default value of class attribute: Specs.b
You can check for None and pass default value if needed
Code for this:
dataclasses.dataclass()
class Specs1:
a: str
b: str = 'Bravo'
c: str = 'Charlie'
a = 'Apple'
b = None
c = 'Potato'
specs = Specs1(a=a, b=b or Specs1.b, c=c or Specs1.c)
>>> specs
Specs1(a='Apple', b='Bravo', c='Potato')
A:
Use key based parameters. You can just do r2 = Specs1('Apple', c='Cherry'). You don't have to use None. Refer here.
Output:
Specs1(a='Apple', b='Bravo', c='Cherry')
A:
Perhaps the most efficient and convenient approach that I can think of for this task, involves using metaclasses in Python to automatically generate a __post_init__() method for the class, which will set the default value specified for a field if a None value is passed in for that field to __init__().
Assume we have these contents in a module metaclasses.py:
import logging
LOG = logging.getLogger(__name__)
logging.basicConfig(level='DEBUG')
def apply_default_values(name, bases, dct):
"""
Metaclass to generate a __post_init__() for the class, which sets the
default values for any fields that are passed in a `None` value in the
__init__() method.
"""
# Get class annotations, which `dataclasses` uses to determine which
# fields to add to the __init__() method.
cls_annotations = dct['__annotations__']
# This is a dict which will contain: {'b': 'Bravo', 'c': 'Charlie'}
field_to_default_val = {field: dct[field] for field in cls_annotations
if field in dct}
# Now we generate the lines of the __post_init()__ method
body_lines = []
for field, default_val in field_to_default_val.items():
body_lines.append(f'if self.{field} is None:')
body_lines.append(f' self.{field} = {default_val!r}')
# Then create the function, and add it to the class
fn = _create_fn('__post_init__',
('self', ),
body_lines)
dct['__post_init__'] = fn
# Return new class with the __post_init__() added
cls = type(name, bases, dct)
return cls
def _create_fn(name, args, body, *, globals=None):
"""
Create a new function. Adapted from `dataclasses._create_fn`, so we
can also log the function definition for debugging purposes.
"""
args = ','.join(args)
body = '\n'.join(f' {b}' for b in body)
# Compute the text of the entire function.
txt = f'def {name}({args}):\n{body}'
# Log the function declaration
LOG.debug('Creating new function:\n%s', txt)
ns = {}
exec(txt, globals, ns)
return ns[name]
Now in our main module, we can import and use the metaclass we just defined:
from dataclasses import dataclass
from metaclasses import apply_default_values
@dataclass
class Specs1(metaclass=apply_default_values):
a: str
b: str = 'Bravo'
c: str = 'Charlie'
r1 = Specs1('Apple', None, 'Cherry')
print(r1)
Output:
DEBUG:metaclasses:Creating new function:
def __post_init__(self):
if self.b is None:
self.b = 'Bravo'
if self.c is None:
self.c = 'Charlie'
Specs1(a='Apple', b='Bravo', c='Cherry')
To confirm that this approach is actually as efficient as stated, I've set up a small test case to create a lot of Spec objects, in order to time it against the version in @Lars's answer, which essentially does the same thing.
from dataclasses import dataclass
from timeit import timeit
from metaclasses import apply_default_values
@dataclass
class Specs1(metaclass=apply_default_values):
a: str
b: str = 'Bravo'
c: str = 'Charlie'
@dataclass
class Specs2:
a: str
b: str
c: str
def __post_init__(self):
if self.b is None:
self.b = 'Bravo'
if self.c is None:
self.c = 'Charlie'
n = 100_000
print('Manual: ', timeit("Specs2('Apple', None, 'Cherry')",
globals=globals(), number=n))
print('Metaclass: ', timeit("Specs1('Apple', None, 'Cherry')",
globals=globals(), number=n))
Timing for n=100,000 runs, the results show it's close enough to not really matter:
Manual: 0.059566365
Metaclass: 0.053688744999999996
A:
I understand that you just want positional arguments. This can be accomplished with in-line conditionals (for code readability).
class Specs():
def __init__(self, a=None,b=None,c=None):
self.a = a if a is not None else 'Apple'
sefl.b = b if b is not None else 'Bravo'
self.c = c if c is not None else 'Cherry'
example = Specs('Apple', None, 'Cherry')
This approach can be done without an init method, if you prefer it that way.
However, you may considered an __init__() method with named arguments.
class Specs():
def __init__(self, a = 'Apple', b = 'Bravo', c = 'Cherry'):
self.a = a
self.b = b
self.c = c
example = Specs('Apple', c = 'Cherry')
A:
@dataclass
class Specs1:
a: str
b: str = field(default='Bravo')
c: str = field(default='Charlie')
|
How to apply default value to Python dataclass field when None was passed?
|
I need a class that will accept a number of parameters, I know that all parameters will be provided but some maybe passed as None in which case my class will have to provide default values.
I want to setup a simple dataclass with a some default values like so:
@dataclass
class Specs1:
a: str
b: str = 'Bravo'
c: str = 'Charlie'
I would like to be able to get the default value for the second field but still set a value for the third one. I cannot do this with None because it is happily accepted as a value for my string:
r1 = Specs1('Apple', None, 'Cherry') # Specs1(a='Apple', b=None, c='Cherry')
I have come up with the following solution:
@dataclass
class Specs2:
def_b: ClassVar = 'Bravo'
def_c: ClassVar = 'Charlie'
a: str
b: str = def_b
c: str = def_c
def __post_init__(self):
self.b = self.def_b if self.b is None else self.b
self.c = self.def_c if self.c is None else self.c
Which seems to behave as intended:
r2 = Specs2('Apple', None, 'Cherry') # Specs2(a='Apple', b='Bravo', c='Cherry')
However, I feel it is quite ugly and that I am maybe missing something here. My actual class will have more fields so it will only get uglier.
The parameters passed to the class contain None and I do not have control over this aspect.
|
[
"The simple solution is to just implement the default arguments in __post_init__() only!\n@dataclass\nclass Specs2:\n a: str\n b: str\n c: str\n\n def __post_init__(self):\n if self.b is None:\n self.b = 'Bravo'\n if self.c is None:\n self.c = 'Charlie'\n\n(Code is not tested. If I got some detail wrong, it wouldn't be the first time)\n",
"Here is another solution.\nDefine DefaultVal and NoneRefersDefault types:\nfrom dataclasses import dataclass, fields\n\n@dataclass\nclass DefaultVal:\n val: Any\n\n\n@dataclass\nclass NoneRefersDefault:\n def __post_init__(self):\n for field in fields(self):\n\n # if a field of this data class defines a default value of type\n # `DefaultVal`, then use its value in case the field after \n # initialization has either not changed or is None.\n if isinstance(field.default, DefaultVal):\n field_val = getattr(self, field.name)\n if isinstance(field_val, DefaultVal) or field_val is None:\n setattr(self, field.name, field.default.val)\n\nUsage:\n@dataclass\nclass Specs3(NoneRefersDefault):\n a: str\n b: str = DefaultVal('Bravo')\n c: str = DefaultVal('Charlie')\n\nr3 = Specs3('Apple', None, 'Cherry') # Specs3(a='Apple', b='Bravo', c='Cherry')\n\nEDIT #1: Rewritten NoneRefersDefault such that the following is possible as well:\n@dataclass\nr3 = Specs3('Apple', None) # Specs3(a='Apple', b='Bravo', c='Charlie')\n\nEDIT #2: Note that if no class inherits from Spec, it might be better to have no default values in the dataclass and a \"constructor\" function create_spec instead:\n@dataclass\nclass Specs4:\n a: str\n b: str\n c: str\n\ndef create_spec(\n a: str,\n b: str = None,\n c: str = None,\n):\n if b is None:\n b = 'Bravo'\n if c is None:\n c = 'Charlie'\n\n return Spec4(a=a, b=b, c=c)\n\nalso see dataclass-abc/example \n",
"I know this is a little late, but inspired by MikeSchneeberger's answer I made a small adaptation to the __post_init__ function that allows you to keep the defaults in the standard format:\nfrom dataclasses import dataclass, fields\ndef __post_init__(self):\n # Loop through the fields\n for field in fields(self):\n # If there is a default and the value of the field is none we can assign a value\n if not isinstance(field.default, dataclasses._MISSING_TYPE) and getattr(self, field.name) is None:\n setattr(self, field.name, field.default)\n\nAdding this to your dataclass should then ensure that the default values are enforced without requiring a new default class.\n",
"In data classes you can access a default value of class attribute: Specs.b\nYou can check for None and pass default value if needed\nCode for this:\ndataclasses.dataclass()\nclass Specs1:\n a: str\n b: str = 'Bravo'\n c: str = 'Charlie'\na = 'Apple'\nb = None\nc = 'Potato'\nspecs = Specs1(a=a, b=b or Specs1.b, c=c or Specs1.c)\n\n>>> specs\nSpecs1(a='Apple', b='Bravo', c='Potato')\n\n",
"Use key based parameters. You can just do r2 = Specs1('Apple', c='Cherry'). You don't have to use None. Refer here.\nOutput:\nSpecs1(a='Apple', b='Bravo', c='Cherry')\n\n",
"Perhaps the most efficient and convenient approach that I can think of for this task, involves using metaclasses in Python to automatically generate a __post_init__() method for the class, which will set the default value specified for a field if a None value is passed in for that field to __init__().\nAssume we have these contents in a module metaclasses.py:\nimport logging\n\n\nLOG = logging.getLogger(__name__)\nlogging.basicConfig(level='DEBUG')\n\n\ndef apply_default_values(name, bases, dct):\n \"\"\"\n Metaclass to generate a __post_init__() for the class, which sets the\n default values for any fields that are passed in a `None` value in the\n __init__() method.\n \"\"\"\n\n # Get class annotations, which `dataclasses` uses to determine which\n # fields to add to the __init__() method.\n cls_annotations = dct['__annotations__']\n\n # This is a dict which will contain: {'b': 'Bravo', 'c': 'Charlie'}\n field_to_default_val = {field: dct[field] for field in cls_annotations\n if field in dct}\n\n # Now we generate the lines of the __post_init()__ method\n body_lines = []\n for field, default_val in field_to_default_val.items():\n body_lines.append(f'if self.{field} is None:')\n body_lines.append(f' self.{field} = {default_val!r}')\n\n # Then create the function, and add it to the class\n fn = _create_fn('__post_init__',\n ('self', ),\n body_lines)\n\n dct['__post_init__'] = fn\n\n # Return new class with the __post_init__() added\n cls = type(name, bases, dct)\n return cls\n\n\ndef _create_fn(name, args, body, *, globals=None):\n \"\"\"\n Create a new function. Adapted from `dataclasses._create_fn`, so we\n can also log the function definition for debugging purposes.\n \"\"\"\n args = ','.join(args)\n body = '\\n'.join(f' {b}' for b in body)\n\n # Compute the text of the entire function.\n txt = f'def {name}({args}):\\n{body}'\n\n # Log the function declaration\n LOG.debug('Creating new function:\\n%s', txt)\n\n ns = {}\n exec(txt, globals, ns)\n return ns[name]\n\nNow in our main module, we can import and use the metaclass we just defined:\nfrom dataclasses import dataclass\n\nfrom metaclasses import apply_default_values\n\n\n@dataclass\nclass Specs1(metaclass=apply_default_values):\n a: str\n b: str = 'Bravo'\n c: str = 'Charlie'\n\n\nr1 = Specs1('Apple', None, 'Cherry')\nprint(r1)\n\nOutput:\nDEBUG:metaclasses:Creating new function:\ndef __post_init__(self):\n if self.b is None:\n self.b = 'Bravo'\n if self.c is None:\n self.c = 'Charlie'\nSpecs1(a='Apple', b='Bravo', c='Cherry')\n\n\nTo confirm that this approach is actually as efficient as stated, I've set up a small test case to create a lot of Spec objects, in order to time it against the version in @Lars's answer, which essentially does the same thing.\nfrom dataclasses import dataclass\nfrom timeit import timeit\n\nfrom metaclasses import apply_default_values\n\n\n@dataclass\nclass Specs1(metaclass=apply_default_values):\n a: str\n b: str = 'Bravo'\n c: str = 'Charlie'\n\n\n@dataclass\nclass Specs2:\n a: str\n b: str\n c: str\n\n def __post_init__(self):\n if self.b is None:\n self.b = 'Bravo'\n if self.c is None:\n self.c = 'Charlie'\n\n\nn = 100_000\n\nprint('Manual: ', timeit(\"Specs2('Apple', None, 'Cherry')\",\n globals=globals(), number=n))\nprint('Metaclass: ', timeit(\"Specs1('Apple', None, 'Cherry')\",\n globals=globals(), number=n))\n\nTiming for n=100,000 runs, the results show it's close enough to not really matter:\nManual: 0.059566365\nMetaclass: 0.053688744999999996\n\n",
"I understand that you just want positional arguments. This can be accomplished with in-line conditionals (for code readability).\nclass Specs():\n def __init__(self, a=None,b=None,c=None):\n self.a = a if a is not None else 'Apple'\n sefl.b = b if b is not None else 'Bravo'\n self.c = c if c is not None else 'Cherry'\nexample = Specs('Apple', None, 'Cherry')\n\nThis approach can be done without an init method, if you prefer it that way.\nHowever, you may considered an __init__() method with named arguments.\nclass Specs():\n def __init__(self, a = 'Apple', b = 'Bravo', c = 'Cherry'):\n self.a = a\n self.b = b\n self.c = c\nexample = Specs('Apple', c = 'Cherry')\n\n",
"@dataclass\nclass Specs1:\n a: str\n b: str = field(default='Bravo')\n c: str = field(default='Charlie')\n\n"
] |
[
17,
11,
11,
5,
2,
1,
0,
0
] |
[
"Not too clear what you are trying to do with your Class. Should these defaults not rather be properties? \nMaybe you need a definition used by your class that has default parameters such as: \ndef printMessage(name, msg = \"My name is \"): \n print(\"Hello! \",msg + name)\n\nprintMessage(\"Jack\")\n\nSame thing applies to Classes. \nSimilar debate about \"None\" can be found here: Call function without optional arguments if they are None \n"
] |
[
-2
] |
[
"default_value",
"python",
"python_3.x",
"python_dataclasses"
] |
stackoverflow_0056665298_default_value_python_python_3.x_python_dataclasses.txt
|
Q:
Groupby: how to compute a tranformation and division in every value by group
I have a database like this:
participant time1 time2 ... time27
1 0.003 0.001 0.003
1 0.003 0.002 0.001
1 0.006 0.003 0.003
1 0.003 0.001 0.003
2 0.003 0.003 0.001
2 0.003 0.003 0.001
3 0.006 0.003 0.003
3 0.007 0.044 0.006
3 0.000 0.005 0.007
I need to perform a transformation using np.log1p() per participant and divide every value by the maximum of each participant.
(log [X + 1]) / Xmax
How can I do this?
A:
You can use:
df.join(df.groupby('participant')
.transform(lambda s: np.log1p(s)/s.max())
.add_suffix('_trans')
)
Output (as new columns):
participant time1 time2 time27 time1_trans time2_trans time27_trans
0 1 0.003 0.001 0.003 0.499251 0.333167 0.998503
1 1 0.003 0.002 0.001 0.499251 0.666001 0.333167
2 1 0.006 0.003 0.003 0.997012 0.998503 0.998503
3 1 0.003 0.001 0.003 0.499251 0.333167 0.998503
4 2 0.003 0.003 0.001 0.998503 0.998503 0.999500
5 2 0.003 0.003 0.001 0.998503 0.998503 0.999500
6 3 0.006 0.003 0.003 0.854582 0.068080 0.427930
7 3 0.007 0.044 0.006 0.996516 0.978625 0.854582
8 3 0.000 0.005 0.007 0.000000 0.113353 0.996516
|
Groupby: how to compute a tranformation and division in every value by group
|
I have a database like this:
participant time1 time2 ... time27
1 0.003 0.001 0.003
1 0.003 0.002 0.001
1 0.006 0.003 0.003
1 0.003 0.001 0.003
2 0.003 0.003 0.001
2 0.003 0.003 0.001
3 0.006 0.003 0.003
3 0.007 0.044 0.006
3 0.000 0.005 0.007
I need to perform a transformation using np.log1p() per participant and divide every value by the maximum of each participant.
(log [X + 1]) / Xmax
How can I do this?
|
[
"You can use:\ndf.join(df.groupby('participant')\n .transform(lambda s: np.log1p(s)/s.max())\n .add_suffix('_trans')\n )\n\nOutput (as new columns):\n participant time1 time2 time27 time1_trans time2_trans time27_trans\n0 1 0.003 0.001 0.003 0.499251 0.333167 0.998503\n1 1 0.003 0.002 0.001 0.499251 0.666001 0.333167\n2 1 0.006 0.003 0.003 0.997012 0.998503 0.998503\n3 1 0.003 0.001 0.003 0.499251 0.333167 0.998503\n4 2 0.003 0.003 0.001 0.998503 0.998503 0.999500\n5 2 0.003 0.003 0.001 0.998503 0.998503 0.999500\n6 3 0.006 0.003 0.003 0.854582 0.068080 0.427930\n7 3 0.007 0.044 0.006 0.996516 0.978625 0.854582\n8 3 0.000 0.005 0.007 0.000000 0.113353 0.996516\n\n"
] |
[
2
] |
[] |
[] |
[
"group_by",
"pandas",
"python"
] |
stackoverflow_0074494675_group_by_pandas_python.txt
|
Q:
how to sample points in 3D in python with origin and normal vector
I have two points p1(x1, y1, z1) and p2(x2, y2, z2) in 3D. And I want to sample points in a circle with radius r that is centered at p1, and the plane which is perpendicular to the vector p2-p1 (so p2-p1 would be the normal vector of that plane). I have the code for sampling in XOY plane using polar system, but suffering on how to generalize to a different normal than (0, 0, 1)
rho = np.linspace(0, 2*np.pi, 50)
r = 1
x = np.cos(rho) * r
y = np.sin(rho) * r
z = np.zeros(rho.shape)
Sampled points
A:
At first you need to define two base vectors in the circle's plane.
The first one is arbitrary vector orthogonal to normal n = p2-p1
Choose component of normal with the largest magnitude and component with the second magnitude.
Exchange their values, negate the largest, and make the third component zero (note that dot product of result with normal is zero, so they are othogonal)
For example, if n.y is the largest and n.z is the second, make
v = (0, n.z, -n.y)
Then calculate the second base vector using vector product
u = n x v
Normalize vectors v and u. Circle points using center point p1 on vector form:
f(rho) = p1 + r * v * cos(rho) + r * u * sin(rho)
or in components:
f.x = p1.x + r * v.x * cos(rho) + r * u.x * sin(rho)
and so on
A:
Lets say we have a vector n and we want to find a circle of points around a center p1 with radius r which are orthogonal to n. Here is a working example with code
p1 = np.array([-21.03181359, 4.54876345, 19.26943601])
n = np.array([-0.06592715, 0.00713031, -0.26809672])
n = n / np.linalg.norm(n) # normalise n
r = 0.5
x = np.array([1,0,0]).astype(np.float64) # take a random vector of magnitude 1
x -= x.dot(n) * n / np.linalg.norm(n)**2 # make it orthogonal to n
x /= np.linalg.norm(x) # normalize
# find first point on circle (x1).
# currently it has magnitude of 1, so we multiply it by the r
x1 = p1 + (x*r)
# vector from lumen centre to first circle point
p1x1 = x1 - p1
def rotation_matrix(axis, theta):
"""
Return the rotation matrix associated with counterclockwise rotation about
the given axis by theta radians.
"""
axis = np.asarray(axis)
axis = axis / math.sqrt(np.dot(axis, axis))
a = math.cos(theta / 2.0)
b, c, d = -axis * math.sin(theta / 2.0)
aa, bb, cc, dd = a * a, b * b, c * c, d * d
bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d
return np.array([[aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)],
[2 * (bc - ad), aa + cc - bb - dd, 2 * (cd + ab)],
[2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc]])
# rotate the vector p1x1 around the axis n with angle theta
circle = []
for theta in range(0,360,6):
circle_i = np.dot(rotation_matrix(n, np.deg2rad(theta)), p1x1)
circle.append(circle_i+p1)
ax = axes3d.Axes3D(plt.figure(figsize=(10,10)))
ax.scatter3D(*np.array(circle).T, s=10, c='red')
ax.scatter3D(*p1.T, s=10, c='black')
ax.set_xlabel('X', size=40)
ax.set_ylabel('Y', size=40)
ax.set_zlabel('Z', size=40)
ax.set_xlim(-19,-22)
ax.set_ylim(2,5)
ax.set_zlim(18,21)
|
how to sample points in 3D in python with origin and normal vector
|
I have two points p1(x1, y1, z1) and p2(x2, y2, z2) in 3D. And I want to sample points in a circle with radius r that is centered at p1, and the plane which is perpendicular to the vector p2-p1 (so p2-p1 would be the normal vector of that plane). I have the code for sampling in XOY plane using polar system, but suffering on how to generalize to a different normal than (0, 0, 1)
rho = np.linspace(0, 2*np.pi, 50)
r = 1
x = np.cos(rho) * r
y = np.sin(rho) * r
z = np.zeros(rho.shape)
Sampled points
|
[
"At first you need to define two base vectors in the circle's plane.\nThe first one is arbitrary vector orthogonal to normal n = p2-p1\nChoose component of normal with the largest magnitude and component with the second magnitude.\nExchange their values, negate the largest, and make the third component zero (note that dot product of result with normal is zero, so they are othogonal)\nFor example, if n.y is the largest and n.z is the second, make\nv = (0, n.z, -n.y)\n\nThen calculate the second base vector using vector product\nu = n x v \n\nNormalize vectors v and u. Circle points using center point p1 on vector form:\n f(rho) = p1 + r * v * cos(rho) + r * u * sin(rho)\n\nor in components:\n f.x = p1.x + r * v.x * cos(rho) + r * u.x * sin(rho)\nand so on\n\n",
"Lets say we have a vector n and we want to find a circle of points around a center p1 with radius r which are orthogonal to n. Here is a working example with code\np1 = np.array([-21.03181359, 4.54876345, 19.26943601])\nn = np.array([-0.06592715, 0.00713031, -0.26809672])\nn = n / np.linalg.norm(n) # normalise n\nr = 0.5\n\n\nx = np.array([1,0,0]).astype(np.float64) # take a random vector of magnitude 1\nx -= x.dot(n) * n / np.linalg.norm(n)**2 # make it orthogonal to n\nx /= np.linalg.norm(x) # normalize\n\n# find first point on circle (x1). \n# currently it has magnitude of 1, so we multiply it by the r\nx1 = p1 + (x*r)\n\n# vector from lumen centre to first circle point\np1x1 = x1 - p1\n\ndef rotation_matrix(axis, theta):\n \"\"\"\n Return the rotation matrix associated with counterclockwise rotation about\n the given axis by theta radians.\n \"\"\"\n axis = np.asarray(axis)\n axis = axis / math.sqrt(np.dot(axis, axis))\n a = math.cos(theta / 2.0)\n b, c, d = -axis * math.sin(theta / 2.0)\n aa, bb, cc, dd = a * a, b * b, c * c, d * d\n bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d\n return np.array([[aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)],\n [2 * (bc - ad), aa + cc - bb - dd, 2 * (cd + ab)],\n [2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc]])\n\n\n# rotate the vector p1x1 around the axis n with angle theta\ncircle = []\nfor theta in range(0,360,6):\n circle_i = np.dot(rotation_matrix(n, np.deg2rad(theta)), p1x1)\n circle.append(circle_i+p1)\n\nax = axes3d.Axes3D(plt.figure(figsize=(10,10)))\nax.scatter3D(*np.array(circle).T, s=10, c='red')\nax.scatter3D(*p1.T, s=10, c='black')\nax.set_xlabel('X', size=40)\nax.set_ylabel('Y', size=40)\nax.set_zlabel('Z', size=40)\n\nax.set_xlim(-19,-22)\nax.set_ylim(2,5)\nax.set_zlim(18,21)\n\n\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"geometry",
"linear_algebra",
"numpy",
"python"
] |
stackoverflow_0071160423_geometry_linear_algebra_numpy_python.txt
|
Q:
BeautifulSoup not returning links
For my python bootcamp I am trying to create a log of the articles from this site, and return the highest upvoted. The rest of the code works, but I cannot get it to return the href properly. I get "none." I have tried everything I know to do... can anyone provide any guidance?
from bs4 import BeautifulSoup
import requests
response = requests.get("https://news.ycombinator.com/")
yc_web_page = response.text
soup = BeautifulSoup(yc_web_page, "html.parser")
articles = soup.find_all(name="span", class_="titleline")
article_texts = []
article_links = []
for article_tag in articles:
article_text = article_tag.get_text()
article_texts.append(article_text)
article_link = article_tag.get("href")
article_links.append(article_link)
article_upvotes = [int(score.getText().split()[0]) for score in soup.find_all(name="span", class_="score")]
largest_number = max(article_upvotes)
largest_index = article_upvotes.index(largest_number)
print(article_texts[largest_index])
print(article_links[largest_index])
print(article_upvotes[largest_index])`
I have tried to change the 'href' to just an 'a' tag and it returned the same value of "none"
A:
Try:
...
article_link = article_tag.a.get("href") # <--- put .a here
...
from bs4 import BeautifulSoup
import requests
response = requests.get("https://news.ycombinator.com/")
yc_web_page = response.text
soup = BeautifulSoup(yc_web_page, "html.parser")
articles = soup.find_all(name="span", class_="titleline")
article_texts = []
article_links = []
for article_tag in articles:
article_text = article_tag.get_text()
article_texts.append(article_text)
article_link = article_tag.a.get("href") # <--- put .a here
article_links.append(article_link)
article_upvotes = [
int(score.getText().split()[0])
for score in soup.find_all(name="span", class_="score")
]
largest_number = max(article_upvotes)
largest_index = article_upvotes.index(largest_number)
print(article_texts[largest_index])
print(article_links[largest_index])
print(article_upvotes[largest_index])
Prints:
Fred Brooks has died (twitter.com/stevebellovin)
https://twitter.com/stevebellovin/status/1593414068634734592
1368
A:
Here's a bit shorter approach:
import requests
from bs4 import BeautifulSoup
url = "https://news.ycombinator.com/"
soup = BeautifulSoup(requests.get(url).text, "lxml")
all_scores = [
[
int(x.getText().replace(" points", "")),
x["id"].replace("score_", ""),
]
for x in soup.find_all("span", class_="score")
]
votes, tr_id = sorted(all_scores, key=lambda x: x[0], reverse=True)[0]
table_row = soup.find("tr", id=tr_id)
text = table_row.select_one("span a").getText()
link = table_row.select_one("span a")["href"]
print(f"{text}\n{link}\n{votes} votes")
Output:
Fred Brooks has died
https://twitter.com/stevebellovin/status/1593414068634734592
1377 votes
|
BeautifulSoup not returning links
|
For my python bootcamp I am trying to create a log of the articles from this site, and return the highest upvoted. The rest of the code works, but I cannot get it to return the href properly. I get "none." I have tried everything I know to do... can anyone provide any guidance?
from bs4 import BeautifulSoup
import requests
response = requests.get("https://news.ycombinator.com/")
yc_web_page = response.text
soup = BeautifulSoup(yc_web_page, "html.parser")
articles = soup.find_all(name="span", class_="titleline")
article_texts = []
article_links = []
for article_tag in articles:
article_text = article_tag.get_text()
article_texts.append(article_text)
article_link = article_tag.get("href")
article_links.append(article_link)
article_upvotes = [int(score.getText().split()[0]) for score in soup.find_all(name="span", class_="score")]
largest_number = max(article_upvotes)
largest_index = article_upvotes.index(largest_number)
print(article_texts[largest_index])
print(article_links[largest_index])
print(article_upvotes[largest_index])`
I have tried to change the 'href' to just an 'a' tag and it returned the same value of "none"
|
[
"Try:\n\n...\n\n article_link = article_tag.a.get(\"href\") # <--- put .a here\n\n...\n\n\nfrom bs4 import BeautifulSoup\nimport requests\n\n\nresponse = requests.get(\"https://news.ycombinator.com/\")\nyc_web_page = response.text\n\n\nsoup = BeautifulSoup(yc_web_page, \"html.parser\")\narticles = soup.find_all(name=\"span\", class_=\"titleline\")\n\narticle_texts = []\narticle_links = []\n\nfor article_tag in articles:\n\n article_text = article_tag.get_text()\n article_texts.append(article_text)\n\n article_link = article_tag.a.get(\"href\") # <--- put .a here\n article_links.append(article_link)\n\n\narticle_upvotes = [\n int(score.getText().split()[0])\n for score in soup.find_all(name=\"span\", class_=\"score\")\n]\n\n\nlargest_number = max(article_upvotes)\nlargest_index = article_upvotes.index(largest_number)\n\nprint(article_texts[largest_index])\nprint(article_links[largest_index])\nprint(article_upvotes[largest_index])\n\nPrints:\nFred Brooks has died (twitter.com/stevebellovin)\nhttps://twitter.com/stevebellovin/status/1593414068634734592\n1368\n\n",
"Here's a bit shorter approach:\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = \"https://news.ycombinator.com/\"\n\nsoup = BeautifulSoup(requests.get(url).text, \"lxml\")\n\nall_scores = [\n [\n int(x.getText().replace(\" points\", \"\")),\n x[\"id\"].replace(\"score_\", \"\"),\n ]\n for x in soup.find_all(\"span\", class_=\"score\")\n]\n\nvotes, tr_id = sorted(all_scores, key=lambda x: x[0], reverse=True)[0]\n\ntable_row = soup.find(\"tr\", id=tr_id)\ntext = table_row.select_one(\"span a\").getText()\nlink = table_row.select_one(\"span a\")[\"href\"]\n\nprint(f\"{text}\\n{link}\\n{votes} votes\")\n\nOutput:\nFred Brooks has died\nhttps://twitter.com/stevebellovin/status/1593414068634734592\n1377 votes\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"beautifulsoup",
"html_parsing",
"parsing",
"python"
] |
stackoverflow_0074494747_beautifulsoup_html_parsing_parsing_python.txt
|
Q:
Limit overpy query to specific area (e.g. country)
In the following code I am defining the spatial extent of the query using a bounding box. How could I modify the code to instead use a country as the extent of my query? Thank you.
api = overpy.Overpass()
result = api.query("""<osm-script>
<query type="node">
<has-kv k="crossing" v="zebra"/>
<bbox-query e="6.608804" n="53.417560" s="51.967099" w="4.655094"/>
</query>
<print/>
</osm-script>""")
len(result.nodes)
A:
In overpass turbo a count of the zebra crossings in Ireland:
[out:json];
area["name"="Ireland"]->.boundaryarea;
(
nwr(area.boundaryarea)[crossing=zebra];
);
out body;
And with overpy a count of the zebra crossings in Ireland:
import overpy
api = overpy.Overpass()
result = api.query("""
area["name"="Ireland"]->.boundaryarea;
(
nwr(area.boundaryarea)[crossing=zebra];
);
out body;
""")
print(len(result.nodes))
|
Limit overpy query to specific area (e.g. country)
|
In the following code I am defining the spatial extent of the query using a bounding box. How could I modify the code to instead use a country as the extent of my query? Thank you.
api = overpy.Overpass()
result = api.query("""<osm-script>
<query type="node">
<has-kv k="crossing" v="zebra"/>
<bbox-query e="6.608804" n="53.417560" s="51.967099" w="4.655094"/>
</query>
<print/>
</osm-script>""")
len(result.nodes)
|
[
"In overpass turbo a count of the zebra crossings in Ireland:\n[out:json];\narea[\"name\"=\"Ireland\"]->.boundaryarea;\n(\n nwr(area.boundaryarea)[crossing=zebra];\n);\n\nout body;\n\nAnd with overpy a count of the zebra crossings in Ireland:\nimport overpy\n\napi = overpy.Overpass()\n\nresult = api.query(\"\"\"\n area[\"name\"=\"Ireland\"]->.boundaryarea;\n (\n nwr(area.boundaryarea)[crossing=zebra];\n );\n\n out body;\n \"\"\")\nprint(len(result.nodes))\n\n"
] |
[
0
] |
[] |
[] |
[
"openstreetmap",
"overpass_api",
"python"
] |
stackoverflow_0071433686_openstreetmap_overpass_api_python.txt
|
Q:
PySimpleGUI is only showing black screen (python)
When i start this python script:
import PySimpleGUI as sg
layout = [[sg.Text("Hello from PySimpleGUI")], [sg.Button("OK")]]
# Create the window
window = sg.Window("Demo", layout)
# Create an event loop
while True:
event, values = window.read()
# End program if user closes window or
# presses the OK button
if event == "OK" or event == sg.WIN_CLOSED:
break
window.close()
I get this GUI instead of a text with button:
A:
In VSCode I had to update the settings.json of python
"python.defaultInterpreterPath": "/your/venv/bin/python",
Reference: Pylint "unresolved import" error in Visual Studio Code
|
PySimpleGUI is only showing black screen (python)
|
When i start this python script:
import PySimpleGUI as sg
layout = [[sg.Text("Hello from PySimpleGUI")], [sg.Button("OK")]]
# Create the window
window = sg.Window("Demo", layout)
# Create an event loop
while True:
event, values = window.read()
# End program if user closes window or
# presses the OK button
if event == "OK" or event == sg.WIN_CLOSED:
break
window.close()
I get this GUI instead of a text with button:
|
[
"In VSCode I had to update the settings.json of python\n\"python.defaultInterpreterPath\": \"/your/venv/bin/python\",\n\nReference: Pylint \"unresolved import\" error in Visual Studio Code\n"
] |
[
0
] |
[] |
[] |
[
"pysimplegui",
"python",
"user_interface"
] |
stackoverflow_0074483062_pysimplegui_python_user_interface.txt
|
Q:
Find perpendicular to given vector (Velocity) in 3D
I have a object A move with Velocity (v1, v2, v3) in 3D space.
Object position is (px,py,pz)
Now i want to add certain particles around object A (in radius dis) on plane which perpendicular to its Velocity direction.
I find something call "cross product" but seen that no use in this case.
Anyone can help?
I'm new to python and don't really know how to crack it.
A:
The plane perpendicular to a vector ⟨A, B, C⟩ has the general equation Ax + By + Cz + K = 0.
A:
The equation of the plane is:
v1*(x-px) + v2*(y-py) + v3*(z-pz) = 0
When you know (x,y) you can find z and so on.
Example:
z = pz - (v1*(x-px) + v2*(y-py))/v3
A:
Lets say we have a point p1, and we want to build a circle of points around it with radius r so that all points on the circle are orthogonal to a vector n.. here is a working example
p1 = np.array([-21.03181359, 4.54876345, 19.26943601])
n = np.array([-0.06592715, 0.00713031, -0.26809672])
n = n / np.linalg.norm(n) # normalise n
r = 0.5
x = np.array([1,0,0]).astype(np.float64) # take a random vector of magnitude 1
x -= x.dot(n) * n / np.linalg.norm(n)**2 # make it orthogonal to n
x /= np.linalg.norm(x) # normalize
# find first point on circle (x1).
# currently it has magnitude of 1, so we multiply it by the r
x1 = p1 + (x*r)
# vector from lumen centre to first circle point
p1x1 = x1 - p1
def rotation_matrix(axis, theta):
"""
Return the rotation matrix associated with counterclockwise rotation about
the given axis by theta radians.
"""
axis = np.asarray(axis)
axis = axis / math.sqrt(np.dot(axis, axis))
a = math.cos(theta / 2.0)
b, c, d = -axis * math.sin(theta / 2.0)
aa, bb, cc, dd = a * a, b * b, c * c, d * d
bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d
return np.array([[aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)],
[2 * (bc - ad), aa + cc - bb - dd, 2 * (cd + ab)],
[2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc]])
# rotate the vector p1x1 around the axis n with angle theta
circle = []
for theta in range(0,360,6):
circle_i = np.dot(rotation_matrix(n, np.deg2rad(theta)), p1x1)
circle.append(circle_i+p1)
ax = axes3d.Axes3D(plt.figure(figsize=(10,10)))
ax.scatter3D(*np.array(circle).T, s=10, c='red')
ax.scatter3D(*p1.T, s=10, c='black')
ax.set_xlabel('X', size=40)
ax.set_ylabel('Y', size=40)
ax.set_zlabel('Z', size=40)
ax.set_xlim(-19,-22)
ax.set_ylim(2,5)
ax.set_zlim(18,21)
|
Find perpendicular to given vector (Velocity) in 3D
|
I have a object A move with Velocity (v1, v2, v3) in 3D space.
Object position is (px,py,pz)
Now i want to add certain particles around object A (in radius dis) on plane which perpendicular to its Velocity direction.
I find something call "cross product" but seen that no use in this case.
Anyone can help?
I'm new to python and don't really know how to crack it.
|
[
"The plane perpendicular to a vector ⟨A, B, C⟩ has the general equation Ax + By + Cz + K = 0.\n",
"The equation of the plane is:\nv1*(x-px) + v2*(y-py) + v3*(z-pz) = 0\n\nWhen you know (x,y) you can find z and so on.\nExample:\nz = pz - (v1*(x-px) + v2*(y-py))/v3\n",
"Lets say we have a point p1, and we want to build a circle of points around it with radius r so that all points on the circle are orthogonal to a vector n.. here is a working example\np1 = np.array([-21.03181359, 4.54876345, 19.26943601])\nn = np.array([-0.06592715, 0.00713031, -0.26809672])\nn = n / np.linalg.norm(n) # normalise n\nr = 0.5\n\n\nx = np.array([1,0,0]).astype(np.float64) # take a random vector of magnitude 1\nx -= x.dot(n) * n / np.linalg.norm(n)**2 # make it orthogonal to n\nx /= np.linalg.norm(x) # normalize\n\n# find first point on circle (x1). \n# currently it has magnitude of 1, so we multiply it by the r\nx1 = p1 + (x*r)\n\n# vector from lumen centre to first circle point\np1x1 = x1 - p1\n\ndef rotation_matrix(axis, theta):\n \"\"\"\n Return the rotation matrix associated with counterclockwise rotation about\n the given axis by theta radians.\n \"\"\"\n axis = np.asarray(axis)\n axis = axis / math.sqrt(np.dot(axis, axis))\n a = math.cos(theta / 2.0)\n b, c, d = -axis * math.sin(theta / 2.0)\n aa, bb, cc, dd = a * a, b * b, c * c, d * d\n bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d\n return np.array([[aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)],\n [2 * (bc - ad), aa + cc - bb - dd, 2 * (cd + ab)],\n [2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc]])\n\n\n# rotate the vector p1x1 around the axis n with angle theta\ncircle = []\nfor theta in range(0,360,6):\n circle_i = np.dot(rotation_matrix(n, np.deg2rad(theta)), p1x1)\n circle.append(circle_i+p1)\n\nax = axes3d.Axes3D(plt.figure(figsize=(10,10)))\nax.scatter3D(*np.array(circle).T, s=10, c='red')\nax.scatter3D(*p1.T, s=10, c='black')\nax.set_xlabel('X', size=40)\nax.set_ylabel('Y', size=40)\nax.set_zlabel('Z', size=40)\n\nax.set_xlim(-19,-22)\nax.set_ylim(2,5)\nax.set_zlim(18,21)\n\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"python",
"vector"
] |
stackoverflow_0011134610_python_vector.txt
|
Q:
GPA Calculator + failure testing
My code is only inputting one print command when there are two that need to be put out. I know this problem is simple but I need a new perspective
here is my code:
name = input("What is your name? \n")
h1 = ("Class Name")
h2 = ("Class Grade")
h3 = ("Credit Hours")
point = input("\nEnter your class name followed by your letter grade and hours (say Done to stop input):\n")
class_data = []
while point != "Done":
words = point.split(" ")
if len(words) == 1:
print("Error: No spaces in string. Try again.")
elif len(words) > 4:
print("Error: Too many spaces in input. Try again. ")
else:
try:
class_name = words[0]
grades = (words[1])
hrs = int(words[2])
print("Name of class:", class_name)
print("Grade:", grades)
print("Class Hours:", hrs)
class_data.append((class_name, grades, hrs,))
except ValueError:
print("Error: Space not followed by an integer.")
point = input("\nEnter your class name followed by your letter grade and hours (say Done to stop input):\n")
def gpa_calculator(grades):
points = 0
i = 0
grade_c = {"A":4,"A-":3.67,"B+":3.33,"B":3.0,"B-":2.67, "C+":2.33,"C":2.0,"C-":1.67,"D+":1.33,"D":1.0,"F":0}
if grades != class_data:
for grade in grades:
points += grade_c[item[1]]
gpa = points / len(class_data)
return gpa
else:
return None
print("Name: ", name)
print("-" * 66)
print("%-17s|%13s|%7s|" % (h1, h2, h3))
print("-" * 66)
for item in class_data:
print("%-17s|%13s|%12s|" % (item[0], item[1], item[2]))
print("-" * 66)
print('Your projected GPA is: ',(gpa_calculator(grades)))
print("-" * 66)
if item[0] == "Computer-Science" and item[1] == "D":
print ("failing CS")
if item[0] == "Programming" and item[1] == "D":
print ("failing programming")
what i need help with are the last four lines
output:
What is your name?
Nich
Enter your class name followed by your letter grade and hours (say Done to stop input):
Programming D 10
Name of class: Programming
Grade: D
Class Hours: 10
Enter your class name followed by your letter grade and hours (say Done to stop input):
Computer-Science D 10
Name of class: Computer-Science
Grade: D
Class Hours: 10
Enter your class name followed by your letter grade and hours (say Done to stop input):
Done
Name: Nich
------------------------------------------------------------------
Class Name |Class Grade|Credit Hours|
------------------------------------------------------------------
Programming | D| 10|
Computer-Science| D| 10|
------------------------------------------------------------------
Your projected GPA is: 0.5
------------------------------------------------------------------
failing CS
I've tried elif and true commands this is the closest I've been to solving this.
A:
You need another loop, like the one you used to print the grade table.
for item in class_data:
if item[1] in ("D", "F"):
print(f"failing {item[0]}")
|
GPA Calculator + failure testing
|
My code is only inputting one print command when there are two that need to be put out. I know this problem is simple but I need a new perspective
here is my code:
name = input("What is your name? \n")
h1 = ("Class Name")
h2 = ("Class Grade")
h3 = ("Credit Hours")
point = input("\nEnter your class name followed by your letter grade and hours (say Done to stop input):\n")
class_data = []
while point != "Done":
words = point.split(" ")
if len(words) == 1:
print("Error: No spaces in string. Try again.")
elif len(words) > 4:
print("Error: Too many spaces in input. Try again. ")
else:
try:
class_name = words[0]
grades = (words[1])
hrs = int(words[2])
print("Name of class:", class_name)
print("Grade:", grades)
print("Class Hours:", hrs)
class_data.append((class_name, grades, hrs,))
except ValueError:
print("Error: Space not followed by an integer.")
point = input("\nEnter your class name followed by your letter grade and hours (say Done to stop input):\n")
def gpa_calculator(grades):
points = 0
i = 0
grade_c = {"A":4,"A-":3.67,"B+":3.33,"B":3.0,"B-":2.67, "C+":2.33,"C":2.0,"C-":1.67,"D+":1.33,"D":1.0,"F":0}
if grades != class_data:
for grade in grades:
points += grade_c[item[1]]
gpa = points / len(class_data)
return gpa
else:
return None
print("Name: ", name)
print("-" * 66)
print("%-17s|%13s|%7s|" % (h1, h2, h3))
print("-" * 66)
for item in class_data:
print("%-17s|%13s|%12s|" % (item[0], item[1], item[2]))
print("-" * 66)
print('Your projected GPA is: ',(gpa_calculator(grades)))
print("-" * 66)
if item[0] == "Computer-Science" and item[1] == "D":
print ("failing CS")
if item[0] == "Programming" and item[1] == "D":
print ("failing programming")
what i need help with are the last four lines
output:
What is your name?
Nich
Enter your class name followed by your letter grade and hours (say Done to stop input):
Programming D 10
Name of class: Programming
Grade: D
Class Hours: 10
Enter your class name followed by your letter grade and hours (say Done to stop input):
Computer-Science D 10
Name of class: Computer-Science
Grade: D
Class Hours: 10
Enter your class name followed by your letter grade and hours (say Done to stop input):
Done
Name: Nich
------------------------------------------------------------------
Class Name |Class Grade|Credit Hours|
------------------------------------------------------------------
Programming | D| 10|
Computer-Science| D| 10|
------------------------------------------------------------------
Your projected GPA is: 0.5
------------------------------------------------------------------
failing CS
I've tried elif and true commands this is the closest I've been to solving this.
|
[
"You need another loop, like the one you used to print the grade table.\nfor item in class_data:\n if item[1] in (\"D\", \"F\"):\n print(f\"failing {item[0]}\")\n\n"
] |
[
0
] |
[] |
[] |
[
"computer_science",
"gpa",
"python"
] |
stackoverflow_0074494900_computer_science_gpa_python.txt
|
Q:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: unsupported operand type(s) for +: 'int and NoneType
I was coding a Tax calculator system and when I'm using the function It gives me the error : discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: unsupported operand type(s) for +: 'int' and 'NoneType', I tried Everything but it didn't work.
Here's the function (tax calculator):
async def tax(args):
args3 = 5
protax= round(int(args)*args3/100)
if protax == 0:
protax = 1
And here's where I called it:
c.execute("SELECT price FROM netflix")
netfprice = c.fetchall()
netprice = netfprice[0][0]
netprix = await tax(netprice*amount)
embed = discord.Embed(
title="transfer system",
description=f"Please transfer:{netprice + netprix}"
)
the full traceback:
Ignoring exception in command buy:
Traceback (most recent call last):
File "C:\Users\sidal\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 127, in wrapped
ret = await coro(arg)
File "C:\Users\sidal\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 911, in _invoke
await self.callback(ctx, **kwargs)
File "c:\Users\sidal\Desktop\Sidtho\main.py", line 227, in buy
description=f"Please transfer:{netprice + netprix}"
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\sidal\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1008, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\sidal\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 359, in invoke
await injected(ctx)
File "C:\Users\sidal\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 135, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
A:
Your tax() function isn't returning anything, so by default it returns None.
I suppose you want to send the protax variable. If that is the case, this code should work:
async def tax(args):
args3 = 5
protax= round(int(args)*args3/100)
if protax == 0:
protax = 1
return protax
|
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: unsupported operand type(s) for +: 'int and NoneType
|
I was coding a Tax calculator system and when I'm using the function It gives me the error : discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: unsupported operand type(s) for +: 'int' and 'NoneType', I tried Everything but it didn't work.
Here's the function (tax calculator):
async def tax(args):
args3 = 5
protax= round(int(args)*args3/100)
if protax == 0:
protax = 1
And here's where I called it:
c.execute("SELECT price FROM netflix")
netfprice = c.fetchall()
netprice = netfprice[0][0]
netprix = await tax(netprice*amount)
embed = discord.Embed(
title="transfer system",
description=f"Please transfer:{netprice + netprix}"
)
the full traceback:
Ignoring exception in command buy:
Traceback (most recent call last):
File "C:\Users\sidal\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 127, in wrapped
ret = await coro(arg)
File "C:\Users\sidal\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 911, in _invoke
await self.callback(ctx, **kwargs)
File "c:\Users\sidal\Desktop\Sidtho\main.py", line 227, in buy
description=f"Please transfer:{netprice + netprix}"
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\sidal\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1008, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\sidal\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 359, in invoke
await injected(ctx)
File "C:\Users\sidal\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 135, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
|
[
"Your tax() function isn't returning anything, so by default it returns None.\nI suppose you want to send the protax variable. If that is the case, this code should work:\nasync def tax(args):\n args3 = 5\n protax= round(int(args)*args3/100)\n if protax == 0:\n protax = 1\n return protax\n\n"
] |
[
0
] |
[] |
[] |
[
"discord",
"discord.py",
"pycord",
"python",
"python_3.x"
] |
stackoverflow_0074493862_discord_discord.py_pycord_python_python_3.x.txt
|
Q:
How to use tkinter as ttk
I am working on a big programme and I want Combobox to accept text only to be entered in it
I use This Code
import tkinter
import ttk
import re
win = tkinter.Tk()
def num_only(num):
if str.isdecimal(num):
return True
elif num=="":
return True
else:
return False
def text_only(txt):
if re.match("^\[a-z\]*$",txt.lower()):
return True
elif re.match("^\[أ-ي\]*$",txt):
return True
elif txt == "":
return True
else:
return False
ttk.combobox(win,font="none 12 bold",validate="key",validatecommand(self.text_only,"%P"),values("value1","value2","value3","value4")
win.mainloop()
the validate don't work but it worked with tk.Entry
A:
ttk is a module of tkinter, so you have to import it like this:
from tkinter import ttk
Or instead of calling ttk.Combobox (note that python is case sensitive, so a call to ttk.combobox will not work), you can call it like
tkinter.ttk.Combobox
Also, according to this post, you have to register your validate command using the .register method on your Tk object. That is, add the line: text_only_Command = win.register(text_only), and call text_only_Command instead of text_only.
Finally, you have to pack your widget (so you need to create a Combobox object and then use the method .pack() on it)
Altogether, your code should look like this:
import tkinter
# from tkinter import ttk
import re
win = tkinter.Tk()
def num_only(num):
if str.isdecimal(num): return True
elif num=="": return True
else: return False
def text_only(txt):
if re.match("^[a-z]$",txt.lower()): return True
elif re.match("^[أ-ي]$",txt): return True
elif txt == "": return True
else: return False
text_only_Command = win.register(text_only)
num_only_Command = win.register(num_only)
combo = tkinter.ttk.Combobox(win, font="none 12 bold", validate="key",
validatecommand=(text_only_Command ,"%P"),
values=("value1","value2","value3","value4"))
combo.pack()
win.mainloop()
|
How to use tkinter as ttk
|
I am working on a big programme and I want Combobox to accept text only to be entered in it
I use This Code
import tkinter
import ttk
import re
win = tkinter.Tk()
def num_only(num):
if str.isdecimal(num):
return True
elif num=="":
return True
else:
return False
def text_only(txt):
if re.match("^\[a-z\]*$",txt.lower()):
return True
elif re.match("^\[أ-ي\]*$",txt):
return True
elif txt == "":
return True
else:
return False
ttk.combobox(win,font="none 12 bold",validate="key",validatecommand(self.text_only,"%P"),values("value1","value2","value3","value4")
win.mainloop()
the validate don't work but it worked with tk.Entry
|
[
"ttk is a module of tkinter, so you have to import it like this:\nfrom tkinter import ttk\n\nOr instead of calling ttk.Combobox (note that python is case sensitive, so a call to ttk.combobox will not work), you can call it like\ntkinter.ttk.Combobox\n\nAlso, according to this post, you have to register your validate command using the .register method on your Tk object. That is, add the line: text_only_Command = win.register(text_only), and call text_only_Command instead of text_only.\nFinally, you have to pack your widget (so you need to create a Combobox object and then use the method .pack() on it)\nAltogether, your code should look like this:\nimport tkinter \n# from tkinter import ttk \nimport re \n\nwin = tkinter.Tk() \n\ndef num_only(num): \n if str.isdecimal(num): return True \n elif num==\"\": return True \n else: return False\n\ndef text_only(txt): \n if re.match(\"^[a-z]$\",txt.lower()): return True \n elif re.match(\"^[أ-ي]$\",txt): return True \n elif txt == \"\": return True\n else: return False \n\ntext_only_Command = win.register(text_only)\nnum_only_Command = win.register(num_only)\n\ncombo = tkinter.ttk.Combobox(win, font=\"none 12 bold\", validate=\"key\",\n validatecommand=(text_only_Command ,\"%P\"),\n values=(\"value1\",\"value2\",\"value3\",\"value4\")) \n \ncombo.pack()\n\nwin.mainloop() \n\n"
] |
[
0
] |
[] |
[] |
[
"combobox",
"python",
"tkinter",
"ttk"
] |
stackoverflow_0074494569_combobox_python_tkinter_ttk.txt
|
Q:
Pandas Converting CSV to Parquet - String having , not able to convert
I am using Pandas to Convert CSV to Parquet and below is the code, it is straight Forward.
import pandas as pd
df = pd.read_csv('path/xxxx.csv')
print(df)
df.to_parquet('path/xxxx.parquet')
Problem
In a String for Example :- David,Johnson. If there is a , getting error saying there is a problem in the data.
If i remove the , the CSV File is converting to Parquet.
Any suggesions, need help
Thanks
Madhu
If i remove the , the CSV File is converting to Parquet
A:
Do you need to keep comma in the name of the file? Otherwise you can do input='David,Johnson', output=input.replace(',','_'). I don't think it is generally a good practice to have comma in your file names.
|
Pandas Converting CSV to Parquet - String having , not able to convert
|
I am using Pandas to Convert CSV to Parquet and below is the code, it is straight Forward.
import pandas as pd
df = pd.read_csv('path/xxxx.csv')
print(df)
df.to_parquet('path/xxxx.parquet')
Problem
In a String for Example :- David,Johnson. If there is a , getting error saying there is a problem in the data.
If i remove the , the CSV File is converting to Parquet.
Any suggesions, need help
Thanks
Madhu
If i remove the , the CSV File is converting to Parquet
|
[
"Do you need to keep comma in the name of the file? Otherwise you can do input='David,Johnson', output=input.replace(',','_'). I don't think it is generally a good practice to have comma in your file names.\n"
] |
[
0
] |
[] |
[] |
[
"dataframe",
"pandas",
"pip",
"pyarrow",
"python"
] |
stackoverflow_0074494249_dataframe_pandas_pip_pyarrow_python.txt
|
Q:
Searching for substrings in a list of dicts
I have a list of dicts
I need to search through the "Receiver" keys, and only output dicts that share the last X characters, inside the receiver value, with any other dict.
In this case, we search the last 3 characters of each Receiver value against all other Receiver values.
This is what i have so far
transactions = [
{"Receiver":"alice111","Amount":50},
{"Receiver":"alice222","Amount":60},
{"Receiver":"alice111","Amount":70},
{"Receiver":"bob111","Amount":50},
{"Receiver":"bob222","Amount":150},
{"Receiver":"bob333","Amount":100},
{"Receiver":"kyle444","Amount":260},
{"Receiver":"richard555","Amount":260}
]
new_list=[]
for value in transactions:
receiver = value["Receiver"]
last_3 = receiver[-3:]
#print(receiver)
#print(last_3)
for substring in transactions:
if re.search(last_3 + r"$",substring["Receiver"]):
#print("MATCH" + str(substring))
new_list.append(substring)
print(new_list)
#[{'Receiver': 'alice111', 'Amount': 50}, {'Receiver': 'alice111', 'Amount': 70}, {'Receiver': 'bob111', 'Amount': 50}, {'Receiver': 'alice222', 'Amount': 60}, {'Receiver': 'bob222', 'Amount': 150}, {'Receiver': 'alice111', 'Amount': 50}, {'Receiver': 'alice111', 'Amount': 70}, {'Receiver': 'bob111', 'Amount': 50}, {'Receiver': 'alice111', 'Amount': 50}, {'Receiver': 'alice111', 'Amount': 70}, {'Receiver': 'bob111', 'Amount': 50}, {'Receiver': 'alice222', 'Amount': 60}, {'Receiver': 'bob222', 'Amount': 150}, {'Receiver': 'bob333', 'Amount': 100}, {'Receiver': 'kyle444', 'Amount': 260}, {'Receiver': 'richard555', 'Amount': 260}]
Unfortunately it's all wrong because it goes over the same values multiple times. With a longer list this would be a total disaster.
desired output
[{"Receiver":"alice111","Amount":50},{"Receiver":"alice222","Amount":60},{"Receiver":"alice111","Amount":70},{"Receiver":"bob111","Amount":50},{"Receiver":"bob222","Amount":150}]
The following should be omitted
[{"Receiver":"bob333","Amount":100},{"Receiver":"kyle444","Amount":260},{"Receiver":"richard555","Amount":260}
]
As you can see, there is no "333" or "444" or "555" as the last characters in any other receiver value, so they are omitted, as i'm not interested in outputting uniques
Update:
what if i wish to match entries that DONT have the same preceeding prefix of characters (before the last 3 character suffix),
transactions1 = [
{"Receiver":"alice111","Amount":50},
{"Receiver":"alice111","Amount":70},
{"Receiver":"bob222","Amount":50},
{"Receiver":"bob222","Amount":150},
{"Receiver":"bob222","Amount":100},
{"Receiver":"richard111","Amount":260},
{"Receiver":"bob333","Amount":100},
{"Receiver":"alice333","Amount":300},
]
new desired output:
[{"Receiver":"alice111","Amount":50}, {"Receiver":"alice111","Amount":70},{"Receiver":"richard111","Amount":50},{"Receiver":"bob333","Amount":100},{"Receiver":"alice333","Amount":300}]
So what's happening is we're only matching if :
-the last 3characters suffix matches AND a differnet name prefix exists
Hope that's clear.
A:
You can first count the occurences and then filter the list according to the count.
from collections import Counter
transactions = [
{"Receiver":"alice111","Amount":50},
{"Receiver":"alice222","Amount":60},
{"Receiver":"alice111","Amount":70},
{"Receiver":"bob111","Amount":50},
{"Receiver":"bob222","Amount":150},
{"Receiver":"bob333","Amount":100},
{"Receiver":"kyle444","Amount":260},
{"Receiver":"richard555","Amount":260}
]
counter = Counter(transaction['Receiver'][-3:] for transaction in transactions)
output = [transaction for transaction in transactions if counter[transaction['Receiver'][-3:]] > 1]
print(output)
# [{'Receiver': 'alice111', 'Amount': 50},
# {'Receiver': 'alice222', 'Amount': 60},
# {'Receiver': 'alice111', 'Amount': 70},
# {'Receiver': 'bob111', 'Amount': 50},
# {'Receiver': 'bob222', 'Amount': 150}]
A:
I hope I've understood your question right. With new input from your question:
transactions1 = [
{"Receiver": "alice111", "Amount": 50},
{"Receiver": "alice111", "Amount": 70},
{"Receiver": "bob222", "Amount": 50},
{"Receiver": "bob222", "Amount": 150},
{"Receiver": "bob222", "Amount": 100},
{"Receiver": "richard111", "Amount": 260},
{"Receiver": "bob333", "Amount": 100},
{"Receiver": "alice333", "Amount": 300},
]
tmp = {}
for t in transactions1:
suffix = t["Receiver"][-3:]
tmp.setdefault(suffix, set()).add(t["Receiver"])
out = [t for t in transactions1 if len(tmp[t["Receiver"][-3:]]) > 1]
print(out)
Prints:
[
{"Receiver": "alice111", "Amount": 50},
{"Receiver": "alice111", "Amount": 70},
{"Receiver": "richard111", "Amount": 260},
{"Receiver": "bob333", "Amount": 100},
{"Receiver": "alice333", "Amount": 300},
]
|
Searching for substrings in a list of dicts
|
I have a list of dicts
I need to search through the "Receiver" keys, and only output dicts that share the last X characters, inside the receiver value, with any other dict.
In this case, we search the last 3 characters of each Receiver value against all other Receiver values.
This is what i have so far
transactions = [
{"Receiver":"alice111","Amount":50},
{"Receiver":"alice222","Amount":60},
{"Receiver":"alice111","Amount":70},
{"Receiver":"bob111","Amount":50},
{"Receiver":"bob222","Amount":150},
{"Receiver":"bob333","Amount":100},
{"Receiver":"kyle444","Amount":260},
{"Receiver":"richard555","Amount":260}
]
new_list=[]
for value in transactions:
receiver = value["Receiver"]
last_3 = receiver[-3:]
#print(receiver)
#print(last_3)
for substring in transactions:
if re.search(last_3 + r"$",substring["Receiver"]):
#print("MATCH" + str(substring))
new_list.append(substring)
print(new_list)
#[{'Receiver': 'alice111', 'Amount': 50}, {'Receiver': 'alice111', 'Amount': 70}, {'Receiver': 'bob111', 'Amount': 50}, {'Receiver': 'alice222', 'Amount': 60}, {'Receiver': 'bob222', 'Amount': 150}, {'Receiver': 'alice111', 'Amount': 50}, {'Receiver': 'alice111', 'Amount': 70}, {'Receiver': 'bob111', 'Amount': 50}, {'Receiver': 'alice111', 'Amount': 50}, {'Receiver': 'alice111', 'Amount': 70}, {'Receiver': 'bob111', 'Amount': 50}, {'Receiver': 'alice222', 'Amount': 60}, {'Receiver': 'bob222', 'Amount': 150}, {'Receiver': 'bob333', 'Amount': 100}, {'Receiver': 'kyle444', 'Amount': 260}, {'Receiver': 'richard555', 'Amount': 260}]
Unfortunately it's all wrong because it goes over the same values multiple times. With a longer list this would be a total disaster.
desired output
[{"Receiver":"alice111","Amount":50},{"Receiver":"alice222","Amount":60},{"Receiver":"alice111","Amount":70},{"Receiver":"bob111","Amount":50},{"Receiver":"bob222","Amount":150}]
The following should be omitted
[{"Receiver":"bob333","Amount":100},{"Receiver":"kyle444","Amount":260},{"Receiver":"richard555","Amount":260}
]
As you can see, there is no "333" or "444" or "555" as the last characters in any other receiver value, so they are omitted, as i'm not interested in outputting uniques
Update:
what if i wish to match entries that DONT have the same preceeding prefix of characters (before the last 3 character suffix),
transactions1 = [
{"Receiver":"alice111","Amount":50},
{"Receiver":"alice111","Amount":70},
{"Receiver":"bob222","Amount":50},
{"Receiver":"bob222","Amount":150},
{"Receiver":"bob222","Amount":100},
{"Receiver":"richard111","Amount":260},
{"Receiver":"bob333","Amount":100},
{"Receiver":"alice333","Amount":300},
]
new desired output:
[{"Receiver":"alice111","Amount":50}, {"Receiver":"alice111","Amount":70},{"Receiver":"richard111","Amount":50},{"Receiver":"bob333","Amount":100},{"Receiver":"alice333","Amount":300}]
So what's happening is we're only matching if :
-the last 3characters suffix matches AND a differnet name prefix exists
Hope that's clear.
|
[
"You can first count the occurences and then filter the list according to the count.\nfrom collections import Counter\n\ntransactions = [\n {\"Receiver\":\"alice111\",\"Amount\":50},\n {\"Receiver\":\"alice222\",\"Amount\":60},\n {\"Receiver\":\"alice111\",\"Amount\":70},\n {\"Receiver\":\"bob111\",\"Amount\":50},\n {\"Receiver\":\"bob222\",\"Amount\":150},\n {\"Receiver\":\"bob333\",\"Amount\":100},\n {\"Receiver\":\"kyle444\",\"Amount\":260},\n {\"Receiver\":\"richard555\",\"Amount\":260}\n]\n\ncounter = Counter(transaction['Receiver'][-3:] for transaction in transactions)\noutput = [transaction for transaction in transactions if counter[transaction['Receiver'][-3:]] > 1]\n\nprint(output)\n# [{'Receiver': 'alice111', 'Amount': 50},\n# {'Receiver': 'alice222', 'Amount': 60},\n# {'Receiver': 'alice111', 'Amount': 70},\n# {'Receiver': 'bob111', 'Amount': 50},\n# {'Receiver': 'bob222', 'Amount': 150}]\n\n",
"I hope I've understood your question right. With new input from your question:\ntransactions1 = [\n {\"Receiver\": \"alice111\", \"Amount\": 50},\n {\"Receiver\": \"alice111\", \"Amount\": 70},\n {\"Receiver\": \"bob222\", \"Amount\": 50},\n {\"Receiver\": \"bob222\", \"Amount\": 150},\n {\"Receiver\": \"bob222\", \"Amount\": 100},\n {\"Receiver\": \"richard111\", \"Amount\": 260},\n {\"Receiver\": \"bob333\", \"Amount\": 100},\n {\"Receiver\": \"alice333\", \"Amount\": 300},\n]\n\ntmp = {}\nfor t in transactions1:\n suffix = t[\"Receiver\"][-3:]\n tmp.setdefault(suffix, set()).add(t[\"Receiver\"])\n\nout = [t for t in transactions1 if len(tmp[t[\"Receiver\"][-3:]]) > 1]\nprint(out)\n\nPrints:\n[\n {\"Receiver\": \"alice111\", \"Amount\": 50},\n {\"Receiver\": \"alice111\", \"Amount\": 70},\n {\"Receiver\": \"richard111\", \"Amount\": 260},\n {\"Receiver\": \"bob333\", \"Amount\": 100},\n {\"Receiver\": \"alice333\", \"Amount\": 300},\n]\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"dictionary",
"list",
"python",
"regex",
"substring"
] |
stackoverflow_0074493831_dictionary_list_python_regex_substring.txt
|
Q:
How fix this error on python (selenium) - json.decoder.JSONDecodeError:
Iniciado!
[WDM] - Downloading: 19.0kB [00:00, 19.5MB/s]
Traceback (most recent call last):
File "main.py", line 58, in
FIREFOX(login)
File "main.py", line 26, in FIREFOX
driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())
File "C:\Users\moonl\AppData\Local\Programs\Python\Python38\lib\site-packages\webdriver_manager\firefox.py", line 37, in install
driver_path = self.get_driver_path(self.driver)
File "C:\Users\moonl\AppData\Local\Programs\Python\Python38\lib\site-packages\webdriver_manager\core\manager.py", line 26, in get_driver_path
binary_path = self.driver_cache.find_driver(driver)
File "C:\Users\moonl\AppData\Local\Programs\Python\Python38\lib\site-packages\webdriver_manager\core\driver_cache.py", line 101, in find_driver
metadata = self.get_metadata()
File "C:\Users\moonl\AppData\Local\Programs\Python\Python38\lib\site-packages\webdriver_manager\core\driver_cache.py", line 135, in get_metadata
return json.load(outfile)
File "C:\Users\moonl\AppData\Local\Programs\Python\Python38\lib\json_init.py", line 293, in load
return loads(fp.read(),
File "C:\Users\moonl\AppData\Local\Programs\Python\Python38\lib\json_init.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Users\moonl\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\moonl\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
enter image description here
i am trying to start a selenium program but i get this error
A:
Its very unclear, but seems that is libary error. We need see a part of your code that points to json.
See that if you have the:
import json
If you trying to read a txt file as json, try:
with open('/xxxx/xxxxx/xxxx.xxx') as jsonfile:
data = json.load(jsonfile)
Other topic in stackoverflow can help you, please check the awnser in:
Why am I getting the error: "JSONDecodeError: Expecting value: line 1 column 1 (char 0)" after iteration 28?
PS: One sugestion, try put Try and Catch in your code and put in some blocks, this help see where the error is on the code. One example is:
try
if xxx.......
............
Finnaly
print some error
|
How fix this error on python (selenium) - json.decoder.JSONDecodeError:
|
Iniciado!
[WDM] - Downloading: 19.0kB [00:00, 19.5MB/s]
Traceback (most recent call last):
File "main.py", line 58, in
FIREFOX(login)
File "main.py", line 26, in FIREFOX
driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())
File "C:\Users\moonl\AppData\Local\Programs\Python\Python38\lib\site-packages\webdriver_manager\firefox.py", line 37, in install
driver_path = self.get_driver_path(self.driver)
File "C:\Users\moonl\AppData\Local\Programs\Python\Python38\lib\site-packages\webdriver_manager\core\manager.py", line 26, in get_driver_path
binary_path = self.driver_cache.find_driver(driver)
File "C:\Users\moonl\AppData\Local\Programs\Python\Python38\lib\site-packages\webdriver_manager\core\driver_cache.py", line 101, in find_driver
metadata = self.get_metadata()
File "C:\Users\moonl\AppData\Local\Programs\Python\Python38\lib\site-packages\webdriver_manager\core\driver_cache.py", line 135, in get_metadata
return json.load(outfile)
File "C:\Users\moonl\AppData\Local\Programs\Python\Python38\lib\json_init.py", line 293, in load
return loads(fp.read(),
File "C:\Users\moonl\AppData\Local\Programs\Python\Python38\lib\json_init.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Users\moonl\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\moonl\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
enter image description here
i am trying to start a selenium program but i get this error
|
[
"Its very unclear, but seems that is libary error. We need see a part of your code that points to json.\nSee that if you have the:\nimport json\nIf you trying to read a txt file as json, try:\nwith open('/xxxx/xxxxx/xxxx.xxx') as jsonfile:\ndata = json.load(jsonfile)\nOther topic in stackoverflow can help you, please check the awnser in:\nWhy am I getting the error: \"JSONDecodeError: Expecting value: line 1 column 1 (char 0)\" after iteration 28?\nPS: One sugestion, try put Try and Catch in your code and put in some blocks, this help see where the error is on the code. One example is:\ntry\n if xxx.......\n ............\nFinnaly\n print some error\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"selenium",
"selenium_webdriver"
] |
stackoverflow_0074493794_python_selenium_selenium_webdriver.txt
|
Q:
elif not working as expected and the loop starts again
inside a while loop all the if and elif statements are working except elif user_choice.upper() == "C"
I tried inputting the choice C and expected the program to print "miles travelled" but the program went and again asked for input
# Game info
print("Welcome to camel")
print("You have stolen a camel too make your way across the great Mobi desert")
print("The natives are chasing you and want their camel back. Survive and run out the natives")
# Storing values in variables
miles_travelled = 0
drinks_canteen = 3
natives_travelled = -20
camel_tiredness = 0
players_thirst = 0
done = False
# Making the loop
while not done:
print("A. Drink from your canteen")
print("B. Ahead moderate speed")
print("C. Ahead full speed")
print("D. Stop for the night")
print("E. Status check")
print("F. Quit")
user_choice = input("Your choice? ")
if user_choice.upper() == "A":
if drinks_canteen == 0:
print("No drinks in your canteen")
user_choice = input("Your choice? ")
elif drinks_canteen != 0:
drinks_canteen -= 1
elif user_choice.upper() == "B":
miles_travelled += 7
print("Miles travelled:", miles_travelled)
players_thirst += 1
camel_tiredness += 1
natives_travelled += 9
elif user_choice.upper == "C":
miles_travelled += 15
print("Miles travelled:", miles_travelled)
players_thirst += 1
camel_tiredness += 3
natives_travelled += 9
elif user_choice.upper() == "D":
camel_tiredness = 0
print("The camel is happy")
natives_travelled += 9
elif user_choice.upper() == "E":
print("Miles travelled:", miles_travelled)
print("Drinks in canteen:", drinks_canteen)
print("The natives are", natives_travelled, "behind you")
elif user_choice.upper() == "F":
print("Game Ends")
done = True
elif 4 < players_thirst < 6:
print("You are thirsty")
elif players_thirst > 6:
print("You died of thirst")
done = True
elif 5 < camel_tiredness < 8:
print("Your camel is getting tired")
elif camel_tiredness > 8:
print("Your camel died")
done = True
elif miles_travelled == natives_travelled:
print("The natives caught up")
done = True
elif miles_travelled > 200:
print("You won")
done = True
elif miles_travelled == natives_travelled + 15:
print("The natives are getting close")
A:
You are missing a pair of brackets. Replace elif user_choice.upper == "C": with elif user_choice.upper() == "C":. Complete code below:
# Game info
print("Welcome to camel")
print("You have stolen a camel too make your way across the great Mobi desert")
print("The natives are chasing you and want their camel back. Survive and run out the natives")
# Storing values in variables
miles_travelled = 0
drinks_canteen = 3
natives_travelled = -20
camel_tiredness = 0
players_thirst = 0
done = False
# Making the loop
while not done:
print("A. Drink from your canteen")
print("B. Ahead moderate speed")
print("C. Ahead full speed")
print("D. Stop for the night")
print("E. Status check")
print("F. Quit")
user_choice = input("Your choice? ")
if user_choice.upper() == "A":
if drinks_canteen == 0:
print("No drinks in your canteen")
user_choice = input("Your choice? ")
elif drinks_canteen != 0:
drinks_canteen -= 1
elif user_choice.upper() == "B":
miles_travelled += 7
print("Miles travelled:", miles_travelled)
players_thirst += 1
camel_tiredness += 1
natives_travelled += 9
elif user_choice.upper == "C":
miles_travelled += 15
print("Miles travelled:", miles_travelled)
players_thirst += 1
camel_tiredness += 3
natives_travelled += 9
elif user_choice.upper() == "D":
camel_tiredness = 0
print("The camel is happy")
natives_travelled += 9
elif user_choice.upper() == "E":
print("Miles travelled:", miles_travelled)
print("Drinks in canteen:", drinks_canteen)
print("The natives are", natives_travelled, "behind you")
elif user_choice.upper() == "F":
print("Game Ends")
done = True
elif 4 < players_thirst < 6:
print("You are thirsty")
elif players_thirst > 6:
print("You died of thirst")
done = True
elif 5 < camel_tiredness < 8:
print("Your camel is getting tired")
elif camel_tiredness > 8:
print("Your camel died")
done = True
elif miles_travelled == natives_travelled:
print("The natives caught up")
done = True
elif miles_travelled > 200:
print("You won")
done = True
elif miles_travelled == natives_travelled + 15:
print("The natives are getting close")
A:
You were missing a pair of parentheses at the user_choice.upper = "C". Also, you need to split your if statements into two sections: one for getting input and one for calculating the effect. Finally, you need to remove the user input after print("No drinks in your canteen"). Here is the updated code:
# Game info
print("Welcome to camel")
print("You have stolen a camel too make your way across the great Mobi desert")
print("The natives are chasing you and want their camel back. Survive and run out the natives")
# Storing values in variables
miles_travelled = 0
drinks_canteen = 3
natives_travelled = -20
camel_tiredness = 0
players_thirst = 0
done = False
# Making the loop
while not done:
print("A. Drink from your canteen")
print("B. Ahead moderate speed")
print("C. Ahead full speed")
print("D. Stop for the night")
print("E. Status check")
print("F. Quit")
user_choice = input("Your choice? ")
if user_choice.upper() == "A":
if drinks_canteen == 0:
print("No drinks in your canteen")
#user_choice = input("Your choice? ")
elif drinks_canteen != 0:
drinks_canteen -= 1
elif user_choice.upper() == "B":
miles_travelled += 7
print("Miles travelled:", miles_travelled)
players_thirst += 1
camel_tiredness += 1
natives_travelled += 9
elif user_choice.upper() == "C":
miles_travelled += 15
print("Miles travelled:", miles_travelled)
players_thirst += 1
camel_tiredness += 3
natives_travelled += 9
elif user_choice.upper() == "D":
camel_tiredness = 0
print("The camel is happy")
natives_travelled += 9
elif user_choice.upper() == "E":
print("Miles travelled:", miles_travelled)
print("Drinks in canteen:", drinks_canteen)
print("The natives are", natives_travelled, "behind you")
elif user_choice.upper() == "F":
print("Game Ends")
done = True
if 4 < players_thirst < 6:
print("You are thirsty")
elif players_thirst > 6:
print("You died of thirst")
done = True
elif 5 < camel_tiredness < 8:
print("Your camel is getting tired")
elif camel_tiredness > 8:
print("Your camel died")
done = True
elif miles_travelled == natives_travelled:
print("The natives caught up")
done = True
elif miles_travelled > 200:
print("You won")
done = True
elif miles_travelled == natives_travelled + 15:
print("The natives are getting close")
|
elif not working as expected and the loop starts again
|
inside a while loop all the if and elif statements are working except elif user_choice.upper() == "C"
I tried inputting the choice C and expected the program to print "miles travelled" but the program went and again asked for input
# Game info
print("Welcome to camel")
print("You have stolen a camel too make your way across the great Mobi desert")
print("The natives are chasing you and want their camel back. Survive and run out the natives")
# Storing values in variables
miles_travelled = 0
drinks_canteen = 3
natives_travelled = -20
camel_tiredness = 0
players_thirst = 0
done = False
# Making the loop
while not done:
print("A. Drink from your canteen")
print("B. Ahead moderate speed")
print("C. Ahead full speed")
print("D. Stop for the night")
print("E. Status check")
print("F. Quit")
user_choice = input("Your choice? ")
if user_choice.upper() == "A":
if drinks_canteen == 0:
print("No drinks in your canteen")
user_choice = input("Your choice? ")
elif drinks_canteen != 0:
drinks_canteen -= 1
elif user_choice.upper() == "B":
miles_travelled += 7
print("Miles travelled:", miles_travelled)
players_thirst += 1
camel_tiredness += 1
natives_travelled += 9
elif user_choice.upper == "C":
miles_travelled += 15
print("Miles travelled:", miles_travelled)
players_thirst += 1
camel_tiredness += 3
natives_travelled += 9
elif user_choice.upper() == "D":
camel_tiredness = 0
print("The camel is happy")
natives_travelled += 9
elif user_choice.upper() == "E":
print("Miles travelled:", miles_travelled)
print("Drinks in canteen:", drinks_canteen)
print("The natives are", natives_travelled, "behind you")
elif user_choice.upper() == "F":
print("Game Ends")
done = True
elif 4 < players_thirst < 6:
print("You are thirsty")
elif players_thirst > 6:
print("You died of thirst")
done = True
elif 5 < camel_tiredness < 8:
print("Your camel is getting tired")
elif camel_tiredness > 8:
print("Your camel died")
done = True
elif miles_travelled == natives_travelled:
print("The natives caught up")
done = True
elif miles_travelled > 200:
print("You won")
done = True
elif miles_travelled == natives_travelled + 15:
print("The natives are getting close")
|
[
"You are missing a pair of brackets. Replace elif user_choice.upper == \"C\": with elif user_choice.upper() == \"C\":. Complete code below:\n# Game info\nprint(\"Welcome to camel\")\nprint(\"You have stolen a camel too make your way across the great Mobi desert\")\nprint(\"The natives are chasing you and want their camel back. Survive and run out the natives\")\n\n# Storing values in variables\nmiles_travelled = 0\ndrinks_canteen = 3\nnatives_travelled = -20\ncamel_tiredness = 0\nplayers_thirst = 0\ndone = False\n\n# Making the loop\nwhile not done:\n print(\"A. Drink from your canteen\")\n print(\"B. Ahead moderate speed\")\n print(\"C. Ahead full speed\")\n print(\"D. Stop for the night\")\n print(\"E. Status check\")\n print(\"F. Quit\")\n user_choice = input(\"Your choice? \")\n if user_choice.upper() == \"A\":\n if drinks_canteen == 0:\n print(\"No drinks in your canteen\")\n user_choice = input(\"Your choice? \")\n elif drinks_canteen != 0:\n drinks_canteen -= 1\n elif user_choice.upper() == \"B\":\n miles_travelled += 7\n print(\"Miles travelled:\", miles_travelled)\n players_thirst += 1\n camel_tiredness += 1\n natives_travelled += 9\n elif user_choice.upper == \"C\":\n miles_travelled += 15\n print(\"Miles travelled:\", miles_travelled)\n players_thirst += 1\n camel_tiredness += 3\n natives_travelled += 9\n elif user_choice.upper() == \"D\":\n camel_tiredness = 0\n print(\"The camel is happy\")\n natives_travelled += 9\n elif user_choice.upper() == \"E\":\n print(\"Miles travelled:\", miles_travelled)\n print(\"Drinks in canteen:\", drinks_canteen)\n print(\"The natives are\", natives_travelled, \"behind you\")\n elif user_choice.upper() == \"F\":\n print(\"Game Ends\")\n done = True\n elif 4 < players_thirst < 6:\n print(\"You are thirsty\")\n elif players_thirst > 6:\n print(\"You died of thirst\")\n done = True\n elif 5 < camel_tiredness < 8:\n print(\"Your camel is getting tired\")\n elif camel_tiredness > 8:\n print(\"Your camel died\")\n done = True\n elif miles_travelled == natives_travelled:\n print(\"The natives caught up\")\n done = True\n elif miles_travelled > 200:\n print(\"You won\")\n done = True\n elif miles_travelled == natives_travelled + 15:\n print(\"The natives are getting close\")\n\n",
"You were missing a pair of parentheses at the user_choice.upper = \"C\". Also, you need to split your if statements into two sections: one for getting input and one for calculating the effect. Finally, you need to remove the user input after print(\"No drinks in your canteen\"). Here is the updated code:\n# Game info\nprint(\"Welcome to camel\")\nprint(\"You have stolen a camel too make your way across the great Mobi desert\")\nprint(\"The natives are chasing you and want their camel back. Survive and run out the natives\")\n\n# Storing values in variables\nmiles_travelled = 0\ndrinks_canteen = 3\nnatives_travelled = -20\ncamel_tiredness = 0\nplayers_thirst = 0\ndone = False\n\n# Making the loop\nwhile not done:\n print(\"A. Drink from your canteen\")\n print(\"B. Ahead moderate speed\")\n print(\"C. Ahead full speed\")\n print(\"D. Stop for the night\")\n print(\"E. Status check\")\n print(\"F. Quit\")\n user_choice = input(\"Your choice? \")\n if user_choice.upper() == \"A\":\n if drinks_canteen == 0:\n print(\"No drinks in your canteen\")\n #user_choice = input(\"Your choice? \")\n elif drinks_canteen != 0:\n drinks_canteen -= 1\n elif user_choice.upper() == \"B\":\n miles_travelled += 7\n print(\"Miles travelled:\", miles_travelled)\n players_thirst += 1\n camel_tiredness += 1\n natives_travelled += 9\n elif user_choice.upper() == \"C\":\n miles_travelled += 15\n print(\"Miles travelled:\", miles_travelled)\n players_thirst += 1\n camel_tiredness += 3\n natives_travelled += 9\n elif user_choice.upper() == \"D\":\n camel_tiredness = 0\n print(\"The camel is happy\")\n natives_travelled += 9\n elif user_choice.upper() == \"E\":\n print(\"Miles travelled:\", miles_travelled)\n print(\"Drinks in canteen:\", drinks_canteen)\n print(\"The natives are\", natives_travelled, \"behind you\")\n elif user_choice.upper() == \"F\":\n print(\"Game Ends\")\n done = True\n\n if 4 < players_thirst < 6:\n print(\"You are thirsty\")\n elif players_thirst > 6:\n print(\"You died of thirst\")\n done = True\n elif 5 < camel_tiredness < 8:\n print(\"Your camel is getting tired\")\n elif camel_tiredness > 8:\n print(\"Your camel died\")\n done = True\n elif miles_travelled == natives_travelled:\n print(\"The natives caught up\")\n done = True\n elif miles_travelled > 200:\n print(\"You won\")\n done = True\n elif miles_travelled == natives_travelled + 15:\n print(\"The natives are getting close\")\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"conditional_statements",
"if_statement",
"python",
"while_loop"
] |
stackoverflow_0074494943_conditional_statements_if_statement_python_while_loop.txt
|
Q:
Count how many times each function gets called
I want to count how many times each function get called.
I have a wrapper to do the counting and save it into a global variable
def counter(f):
global function_calls
function_calls = 0
def wrapper(*args, **kwargs):
global function_calls
function_calls += 1
return f(*args, **kwargs)
return wrapper
and then other two functions to be decorated for counting
@counter
def square(x):
return x * x
@counter
def addition_by_self(x):
return x + x
Now when I call the function five time each the global variable function_calls returns 10. Which makes sense.
print(square(x=4))
print(square(x=4))
print(square(x=4))
print(square(x=4))
print(square(x=4))
print(addition_by_self(x=4))
print(addition_by_self(x=4))
print(addition_by_self(x=4))
print(addition_by_self(x=4))
print(addition_by_self(x=4))
print(f"Number of the function got called: {function_calls}")
running the file gives the output.
16
16
16
16
16
8
8
8
8
8
Number of the function got called: 10
Now I need some solutions or ideas on how to make the decorator return how many times each function got called, not an aggregation of all the calls. I might have other functions which I need track the number of times they also got called.
Essentially I want to do something like print(function_calls) # or something proper
and get the out like: sqaure got called 5 times and addition_by_self got called 5 times
A:
Instead of a single global int, store per-function counts in a dict.
def counter(f):
global function_calls
function_calls = {}
def wrapper(*args, **kwargs):
global function_calls
function_calls[f.__name__] = function_calls.setdefault(f.__name__, 0) + 1
return f(*args, **kwargs)
return wrapper
f might make a better key than f.__name__ (multiple distinct functions could have the same name), but this works as a simple example.
A:
Using a list and an attribute:
def counter(f):
global funs
try:
len(funs)
except NameError:
funs = []
funs.append(f)
f.function_calls = 0
def wrapper(*args, **kwargs):
f.function_calls += 1
return f(*args, **kwargs)
return wrapper
@counter
def square(x):
return x * x
@counter
def addition_by_self(x):
return x + x
for i in range(10):
print(square(3))
print(addition_by_self(2))
print(addition_by_self(4))
for f in funs:
print(f'function: {f.__name__}, calls: {f.function_calls}')
|
Count how many times each function gets called
|
I want to count how many times each function get called.
I have a wrapper to do the counting and save it into a global variable
def counter(f):
global function_calls
function_calls = 0
def wrapper(*args, **kwargs):
global function_calls
function_calls += 1
return f(*args, **kwargs)
return wrapper
and then other two functions to be decorated for counting
@counter
def square(x):
return x * x
@counter
def addition_by_self(x):
return x + x
Now when I call the function five time each the global variable function_calls returns 10. Which makes sense.
print(square(x=4))
print(square(x=4))
print(square(x=4))
print(square(x=4))
print(square(x=4))
print(addition_by_self(x=4))
print(addition_by_self(x=4))
print(addition_by_self(x=4))
print(addition_by_self(x=4))
print(addition_by_self(x=4))
print(f"Number of the function got called: {function_calls}")
running the file gives the output.
16
16
16
16
16
8
8
8
8
8
Number of the function got called: 10
Now I need some solutions or ideas on how to make the decorator return how many times each function got called, not an aggregation of all the calls. I might have other functions which I need track the number of times they also got called.
Essentially I want to do something like print(function_calls) # or something proper
and get the out like: sqaure got called 5 times and addition_by_self got called 5 times
|
[
"Instead of a single global int, store per-function counts in a dict.\ndef counter(f):\n global function_calls\n function_calls = {}\n\n def wrapper(*args, **kwargs):\n global function_calls\n function_calls[f.__name__] = function_calls.setdefault(f.__name__, 0) + 1\n return f(*args, **kwargs)\n\n return wrapper\n\nf might make a better key than f.__name__ (multiple distinct functions could have the same name), but this works as a simple example.\n",
"Using a list and an attribute:\ndef counter(f):\n global funs\n try:\n len(funs)\n except NameError:\n funs = []\n funs.append(f)\n f.function_calls = 0\n\n def wrapper(*args, **kwargs):\n f.function_calls += 1\n return f(*args, **kwargs)\n\n return wrapper\n\n@counter\ndef square(x):\n return x * x\n\n\n@counter\ndef addition_by_self(x):\n return x + x\n\nfor i in range(10):\n print(square(3))\n print(addition_by_self(2))\n print(addition_by_self(4))\n\nfor f in funs:\n print(f'function: {f.__name__}, calls: {f.function_calls}')\n\n"
] |
[
3,
1
] |
[] |
[] |
[
"decorator",
"python",
"python_3.x",
"python_decorators"
] |
stackoverflow_0074494811_decorator_python_python_3.x_python_decorators.txt
|
Q:
Setting a value in a nested Python dictionary given a list of indices and value
I'm trying to programmatically set a value in a dictionary, potentially nested, given a list of indices and a value.
So for example, let's say my list of indices is:
['person', 'address', 'city']
and the value is
'New York'
I want as a result a dictionary object like:
{ 'Person': { 'address': { 'city': 'New York' } }
Basically, the list represents a 'path' into a nested dictionary.
I think I can construct the dictionary itself, but where I'm stumbling is how to set the value. Obviously if I was just writing code for this manually it would be:
dict['Person']['address']['city'] = 'New York'
But how do I index into the dictionary and set the value like that programmatically if I just have a list of the indices and the value?
Python
A:
Something like this could help:
def nested_set(dic, keys, value):
for key in keys[:-1]:
dic = dic.setdefault(key, {})
dic[keys[-1]] = value
And you can use it like this:
>>> d = {}
>>> nested_set(d, ['person', 'address', 'city'], 'New York')
>>> d
{'person': {'address': {'city': 'New York'}}}
A:
I took the freedom to extend the code from the answer of Bakuriu. Therefore upvotes on this are optional, as his code is in and of itself a witty solution, which I wouldn't have thought of.
def nested_set(dic, keys, value, create_missing=True):
d = dic
for key in keys[:-1]:
if key in d:
d = d[key]
elif create_missing:
d = d.setdefault(key, {})
else:
return dic
if keys[-1] in d or create_missing:
d[keys[-1]] = value
return dic
When setting create_missing to True, you're making sure to only set already existing values:
# Trying to set a value of a nonexistent key DOES NOT create a new value
print(nested_set({"A": {"B": 1}}, ["A", "8"], 2, False))
>>> {'A': {'B': 1}}
# Trying to set a value of an existent key DOES create a new value
print(nested_set({"A": {"B": 1}}, ["A", "8"], 2, True))
>>> {'A': {'B': 1, '8': 2}}
# Set the value of an existing key
print(nested_set({"A": {"B": 1}}, ["A", "B"], 2))
>>> {'A': {'B': 2}}
A:
First off, you probably want to look at setdefault.
As a function I'd write it as
def get_leaf_dict(dct, key_list):
res=dct
for key in key_list:
res=res.setdefault(key, {})
return res
This would be used as:
get_leaf_dict( dict, ['Person', 'address', 'city']) = 'New York'
This could be cleaned up with error handling and such. Also using *args rather than a single key-list argument might be nice; but the idea is that
you can iterate over the keys, pulling up the appropriate dictionary at each level.
A:
Here's another option:
from collections import defaultdict
recursivedict = lambda: defaultdict(recursivedict)
mydict = recursivedict()
I originally got this from here: Set nested dict value and create intermediate keys.
It is quite clever and elegant if you ask me.
A:
Here is my simple solution: just write
terms = ['person', 'address', 'city']
result = nested_dict(3, str)
result[terms] = 'New York' # as easy as it can be
You can even do:
terms = ['John', 'Tinkoff', '1094535332'] # account in Tinkoff Bank
result = nested_dict(3, float)
result[terms] += 2375.30
Now the backstage:
from collections import defaultdict
class nesteddict(defaultdict):
def __getitem__(self, key):
if isinstance(key, list):
d = self
for i in key:
d = defaultdict.__getitem__(d, i)
return d
else:
return defaultdict.__getitem__(self, key)
def __setitem__(self, key, value):
if isinstance(key, list):
d = self[key[:-1]]
defaultdict.__setitem__(d, key[-1], value)
else:
defaultdict.__setitem__(self, key, value)
def nested_dict(n, type):
if n == 1:
return nesteddict(type)
else:
return nesteddict(lambda: nested_dict(n-1, type))
A:
The dotty_dict library for Python 3 can do this. See documentation, Dotty Dict for more clarity.
from dotty_dict import dotty
dot = dotty()
string = '.'.join(['person', 'address', 'city'])
dot[string] = 'New York'
print(dot)
Output:
{'person': {'address': {'city': 'New York'}}}
A:
Use these pair of methods
def gattr(d, *attrs):
"""
This method receives a dict and list of attributes to return the innermost value of the give dict
"""
try:
for at in attrs:
d = d[at]
return d
except:
return None
def sattr(d, *attrs):
"""
Adds "val" to dict in the hierarchy mentioned via *attrs
For ex:
sattr(animals, "cat", "leg","fingers", 4) is equivalent to animals["cat"]["leg"]["fingers"]=4
This method creates necessary objects until it reaches the final depth
This behaviour is also known as autovivification and plenty of implementation are around
This implementation addresses the corner case of replacing existing primitives
https://gist.github.com/hrldcpr/2012250#gistcomment-1779319
"""
for attr in attrs[:-2]:
# If such key is not found or the value is primitive supply an empty dict
if d.get(attr) is None or isinstance(d.get(attr), dict):
d[attr] = {}
d = d[attr]
d[attrs[-2]] = attrs[-1]
A:
Here's a variant of Bakuriu's answer that doesn't rely on a separate function:
keys = ['Person', 'address', 'city']
value = 'New York'
nested_dict = {}
# Build nested dictionary up until 2nd to last key
# (Effectively nested_dict['Person']['address'] = {})
sub_dict = nested_dict
for key_ind, key in enumerate(keys[:-1]):
if not key_ind:
# Point to newly added piece of dictionary
sub_dict = nested_dict.setdefault(key, {})
else:
# Point to newly added piece of sub-dictionary
# that is also added to original dictionary
sub_dict = sub_dict.setdefault(key, {})
# Add value to last key of nested structure of keys
# (Effectively nested_dict['Person']['address']['city'] = value)
sub_dict[keys[-1]] = value
print(nested_dict)
>>> {'Person': {'address': {'city': 'New York'}}}
A:
This is a pretty good use case for a recursive function. So you can do something like this:
def parse(l: list, v: str) -> dict:
copy = dict()
k, *s = l
if len(s) > 0:
copy[k] = parse(s, v)
else:
copy[k] = v
return copy
This effectively pops off the first value of the passed list l as a key for the dict copy that we initialize, then runs the remaining list through the same function, creating a new key under that key until there's nothing left in the list, whereupon it assigns the last value to the v param.
|
Setting a value in a nested Python dictionary given a list of indices and value
|
I'm trying to programmatically set a value in a dictionary, potentially nested, given a list of indices and a value.
So for example, let's say my list of indices is:
['person', 'address', 'city']
and the value is
'New York'
I want as a result a dictionary object like:
{ 'Person': { 'address': { 'city': 'New York' } }
Basically, the list represents a 'path' into a nested dictionary.
I think I can construct the dictionary itself, but where I'm stumbling is how to set the value. Obviously if I was just writing code for this manually it would be:
dict['Person']['address']['city'] = 'New York'
But how do I index into the dictionary and set the value like that programmatically if I just have a list of the indices and the value?
Python
|
[
"Something like this could help:\ndef nested_set(dic, keys, value):\n for key in keys[:-1]:\n dic = dic.setdefault(key, {})\n dic[keys[-1]] = value\n\nAnd you can use it like this:\n>>> d = {}\n>>> nested_set(d, ['person', 'address', 'city'], 'New York')\n>>> d\n{'person': {'address': {'city': 'New York'}}}\n\n",
"I took the freedom to extend the code from the answer of Bakuriu. Therefore upvotes on this are optional, as his code is in and of itself a witty solution, which I wouldn't have thought of.\ndef nested_set(dic, keys, value, create_missing=True):\n d = dic\n for key in keys[:-1]:\n if key in d:\n d = d[key]\n elif create_missing:\n d = d.setdefault(key, {})\n else:\n return dic\n if keys[-1] in d or create_missing:\n d[keys[-1]] = value\n return dic\n\nWhen setting create_missing to True, you're making sure to only set already existing values:\n# Trying to set a value of a nonexistent key DOES NOT create a new value\nprint(nested_set({\"A\": {\"B\": 1}}, [\"A\", \"8\"], 2, False))\n>>> {'A': {'B': 1}}\n\n# Trying to set a value of an existent key DOES create a new value\nprint(nested_set({\"A\": {\"B\": 1}}, [\"A\", \"8\"], 2, True))\n>>> {'A': {'B': 1, '8': 2}}\n\n# Set the value of an existing key\nprint(nested_set({\"A\": {\"B\": 1}}, [\"A\", \"B\"], 2))\n>>> {'A': {'B': 2}}\n\n",
"First off, you probably want to look at setdefault.\nAs a function I'd write it as\ndef get_leaf_dict(dct, key_list):\n res=dct\n for key in key_list:\n res=res.setdefault(key, {})\n return res\n\nThis would be used as:\nget_leaf_dict( dict, ['Person', 'address', 'city']) = 'New York'\n\nThis could be cleaned up with error handling and such. Also using *args rather than a single key-list argument might be nice; but the idea is that\nyou can iterate over the keys, pulling up the appropriate dictionary at each level.\n",
"Here's another option:\nfrom collections import defaultdict\nrecursivedict = lambda: defaultdict(recursivedict)\nmydict = recursivedict()\n\nI originally got this from here: Set nested dict value and create intermediate keys.\nIt is quite clever and elegant if you ask me.\n",
"Here is my simple solution: just write\nterms = ['person', 'address', 'city'] \nresult = nested_dict(3, str)\nresult[terms] = 'New York' # as easy as it can be\n\nYou can even do:\nterms = ['John', 'Tinkoff', '1094535332'] # account in Tinkoff Bank\nresult = nested_dict(3, float)\nresult[terms] += 2375.30\n\nNow the backstage:\nfrom collections import defaultdict\n\n\nclass nesteddict(defaultdict):\n def __getitem__(self, key):\n if isinstance(key, list):\n d = self\n for i in key:\n d = defaultdict.__getitem__(d, i)\n return d\n else:\n return defaultdict.__getitem__(self, key)\n def __setitem__(self, key, value):\n if isinstance(key, list):\n d = self[key[:-1]]\n defaultdict.__setitem__(d, key[-1], value)\n else:\n defaultdict.__setitem__(self, key, value)\n\n\ndef nested_dict(n, type):\n if n == 1:\n return nesteddict(type)\n else:\n return nesteddict(lambda: nested_dict(n-1, type))\n\n",
"The dotty_dict library for Python 3 can do this. See documentation, Dotty Dict for more clarity.\nfrom dotty_dict import dotty\n\ndot = dotty()\nstring = '.'.join(['person', 'address', 'city'])\ndot[string] = 'New York'\n\nprint(dot)\n\nOutput:\n{'person': {'address': {'city': 'New York'}}}\n\n",
"Use these pair of methods\ndef gattr(d, *attrs):\n \"\"\"\n This method receives a dict and list of attributes to return the innermost value of the give dict\n \"\"\"\n try:\n for at in attrs:\n d = d[at]\n return d\n except:\n return None\n\n\ndef sattr(d, *attrs):\n \"\"\"\n Adds \"val\" to dict in the hierarchy mentioned via *attrs\n For ex:\n sattr(animals, \"cat\", \"leg\",\"fingers\", 4) is equivalent to animals[\"cat\"][\"leg\"][\"fingers\"]=4\n This method creates necessary objects until it reaches the final depth\n This behaviour is also known as autovivification and plenty of implementation are around\n This implementation addresses the corner case of replacing existing primitives\n https://gist.github.com/hrldcpr/2012250#gistcomment-1779319\n \"\"\"\n for attr in attrs[:-2]:\n # If such key is not found or the value is primitive supply an empty dict\n if d.get(attr) is None or isinstance(d.get(attr), dict):\n d[attr] = {}\n d = d[attr]\n d[attrs[-2]] = attrs[-1]\n\n",
"Here's a variant of Bakuriu's answer that doesn't rely on a separate function:\nkeys = ['Person', 'address', 'city']\nvalue = 'New York'\n\nnested_dict = {}\n\n# Build nested dictionary up until 2nd to last key\n# (Effectively nested_dict['Person']['address'] = {})\nsub_dict = nested_dict\nfor key_ind, key in enumerate(keys[:-1]):\n if not key_ind:\n # Point to newly added piece of dictionary\n sub_dict = nested_dict.setdefault(key, {})\n else:\n # Point to newly added piece of sub-dictionary\n # that is also added to original dictionary\n sub_dict = sub_dict.setdefault(key, {})\n# Add value to last key of nested structure of keys\n# (Effectively nested_dict['Person']['address']['city'] = value)\nsub_dict[keys[-1]] = value\n\nprint(nested_dict)\n\n>>> {'Person': {'address': {'city': 'New York'}}}\n\n",
"This is a pretty good use case for a recursive function. So you can do something like this:\ndef parse(l: list, v: str) -> dict:\n copy = dict()\n k, *s = l\n if len(s) > 0:\n copy[k] = parse(s, v)\n else:\n copy[k] = v\n return copy\n\nThis effectively pops off the first value of the passed list l as a key for the dict copy that we initialize, then runs the remaining list through the same function, creating a new key under that key until there's nothing left in the list, whereupon it assigns the last value to the v param.\n"
] |
[
72,
5,
3,
3,
2,
2,
1,
1,
0
] |
[
"This is much easier in Perl:\nmy %hash;\n$hash{\"aaa\"}{\"bbb\"}{\"ccc\"}=1; # auto creates each of the intermediate levels\n # of the hash (aka: dict or associated array)\n\n"
] |
[
-2
] |
[
"dictionary",
"list",
"python"
] |
stackoverflow_0013687924_dictionary_list_python.txt
|
Q:
Optimizing Python Code: String Assignment from List
I have a CSV file and I read the contents. I need to verify that every element of each row is not empty:
fname = row[0]
if fname is None:
flag = -1
lname = row[1]
if lname is None:
flag = -1
phone = row[2]
if phone is None:
flag = -1
email = row[3]
if email is None:
flag = -1
[...]
Is there a way to optimize this code? Is there a way to do something like this in Python:
fname = row[0] if None else flag = -1 ?
[...]
At the end I will check if flag is -1, I send an error notification (because this is a background task)
A:
if all([len(e) for e in row]):
# Row is good
else:
# Row is bad
We can't just do all(row) because there may be a non-empty but falsey value.
A:
This could help you
with open('testdata1.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
for row in csv_reader:
if not row[0]:
continue # this will skip to the next for loop iteration
# do your processing here
Found it at https://www.folkstalk.com/tech/python-csv-row-index-is-empty-with-code-examples/
|
Optimizing Python Code: String Assignment from List
|
I have a CSV file and I read the contents. I need to verify that every element of each row is not empty:
fname = row[0]
if fname is None:
flag = -1
lname = row[1]
if lname is None:
flag = -1
phone = row[2]
if phone is None:
flag = -1
email = row[3]
if email is None:
flag = -1
[...]
Is there a way to optimize this code? Is there a way to do something like this in Python:
fname = row[0] if None else flag = -1 ?
[...]
At the end I will check if flag is -1, I send an error notification (because this is a background task)
|
[
"if all([len(e) for e in row]):\n # Row is good\nelse:\n # Row is bad\n\n\nWe can't just do all(row) because there may be a non-empty but falsey value.\n",
"This could help you\nwith open('testdata1.csv', 'r') as csv_file:\ncsv_reader = csv.reader(csv_file)\nfor row in csv_reader:\n if not row[0]:\n continue # this will skip to the next for loop iteration\n # do your processing here\n\nFound it at https://www.folkstalk.com/tech/python-csv-row-index-is-empty-with-code-examples/\n"
] |
[
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074494740_python.txt
|
Q:
How could I find the Sender Department in Microsoft Outlook using win32com in Python?
I am programming a script to return each person - along with their department - that was a part of a thread in my Junk folder. As of now I have managed to correctly return their names, however despite trying multiple different methods, I have been unable to access the Departments property.
Here is an example of what I am currently working with:
import win32com.client
output_dir = Path.cwd() / "Output"
output_dir.mkdir(parents=True, exist_ok=True)
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
gal = outlook.Session.GetGlobalAddressList()
entries = gal.AddressEntries
inbox = outlook.GetDefaultFolder(23)
messages = inbox.Items
num = 0
for message in messages:
author = message.SenderName
recipient = outlook.CreateRecipient(f"{message.SenderEmailAddress.partition('-')[2]}@placeholder.com")
recipient.Resolve()
target_folder = output_dir / str(num)
target_folder.mkdir(parents=True, exist_ok=True)
Path(target_folder / "EMAIL_author.txt").write_text(str(message.SenderName))
Path(target_folder / "EMAIL_YEAR.txt").write_text(str(recipient.AddressEntry.GetExchangeUser().GetExchangeUserManager()))
num += 1
Currently working in Python 3.10.8
Any help is appreciated.
A:
There is no reason to use CreateRecipient / Recipient.Resolve - MailItem.Sender property already exposes the AddressEntry object for the sender. Once you get ExchangeUser object from AddressEntry.GetExchangeUser() (check for null), just use the ExchangeUser.Department property.
|
How could I find the Sender Department in Microsoft Outlook using win32com in Python?
|
I am programming a script to return each person - along with their department - that was a part of a thread in my Junk folder. As of now I have managed to correctly return their names, however despite trying multiple different methods, I have been unable to access the Departments property.
Here is an example of what I am currently working with:
import win32com.client
output_dir = Path.cwd() / "Output"
output_dir.mkdir(parents=True, exist_ok=True)
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
gal = outlook.Session.GetGlobalAddressList()
entries = gal.AddressEntries
inbox = outlook.GetDefaultFolder(23)
messages = inbox.Items
num = 0
for message in messages:
author = message.SenderName
recipient = outlook.CreateRecipient(f"{message.SenderEmailAddress.partition('-')[2]}@placeholder.com")
recipient.Resolve()
target_folder = output_dir / str(num)
target_folder.mkdir(parents=True, exist_ok=True)
Path(target_folder / "EMAIL_author.txt").write_text(str(message.SenderName))
Path(target_folder / "EMAIL_YEAR.txt").write_text(str(recipient.AddressEntry.GetExchangeUser().GetExchangeUserManager()))
num += 1
Currently working in Python 3.10.8
Any help is appreciated.
|
[
"There is no reason to use CreateRecipient / Recipient.Resolve - MailItem.Sender property already exposes the AddressEntry object for the sender. Once you get ExchangeUser object from AddressEntry.GetExchangeUser() (check for null), just use the ExchangeUser.Department property.\n"
] |
[
1
] |
[] |
[] |
[
"outlook",
"python"
] |
stackoverflow_0074494922_outlook_python.txt
|
Q:
I am trying to install requirements.txt for my project but it returns the error given below?
Trying to install these packages but the same thing comes up every time.
What should I do ?
tensorflow==2.4.1
nltk==3.5
keras==2.4.3
numpy==1.19.5
streamlit==0.52.1
seaborn==0.11.1
tweepy==3.10.0
textblob==0.15.3
flask==1.1.2
pandas==1.2.2
matplotlib==3.2
scikit_learn==0.24.1
statsmodels==0.12.2
yfinance==0.1.54
alpha_vantage==2.3.1
https://pypi.anaconda.org/berber/simple/tweet-preprocessor/0.5.0/tweet-preprocessor-0.5.0.tar.gz
Output that i have been getting
A:
It says that requirements.txt does not exist in the current working directory. Is the file in the directory \Stock-Market..?
Another thing that I noticed is that you don't have a virtual environment activated. But I don't know if you want to install it specifically in a venv.
|
I am trying to install requirements.txt for my project but it returns the error given below?
|
Trying to install these packages but the same thing comes up every time.
What should I do ?
tensorflow==2.4.1
nltk==3.5
keras==2.4.3
numpy==1.19.5
streamlit==0.52.1
seaborn==0.11.1
tweepy==3.10.0
textblob==0.15.3
flask==1.1.2
pandas==1.2.2
matplotlib==3.2
scikit_learn==0.24.1
statsmodels==0.12.2
yfinance==0.1.54
alpha_vantage==2.3.1
https://pypi.anaconda.org/berber/simple/tweet-preprocessor/0.5.0/tweet-preprocessor-0.5.0.tar.gz
Output that i have been getting
|
[
"It says that requirements.txt does not exist in the current working directory. Is the file in the directory \\Stock-Market..?\nAnother thing that I noticed is that you don't have a virtual environment activated. But I don't know if you want to install it specifically in a venv.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"requirements.txt"
] |
stackoverflow_0074494896_python_requirements.txt.txt
|
Q:
Why do I get module 'numpy' has no attribute 'json_normalize' when using pd.json_normalize()
I have a simple code that scrapes reviews from an app in Google Playstore.
The scrapping runs well and returns a json data. I decided to normalize it and get pandas dataframe.
All I keep getting is module 'numpy' has no attribute 'json_normalize'
Please I need help, all solutions I saw online have not worked. Below is my code
from google_play_scraper import app, Sort, reviews, reviews_all
import pandas as pd
import numpy as pd
reviews = reviews_all(
'com.hikingproject.android',
sleep_milliseconds=0, # defaults to 0
lang='en', # defaults to 'en'
country='NG', # defaults to 'us'
sort=Sort.MOST_RELEVANT, # defaults to Sort.MOST_RELEVANT
#filter_score_with=5 # defaults to None(means all score)
)
opay_data = pd.json_normalize(reviews)
opay_data.to_csv('opay.csv', index = None)
print(opay_data.head())
from google_play_scraper import app, Sort, reviews, reviews_all
import pandas as pd
import numpy as pd
reviews = reviews_all(
'com.hikingproject.android',
sleep_milliseconds=0, # defaults to 0
lang='en', # defaults to 'en'
country='NG', # defaults to 'us'
sort=Sort.MOST_RELEVANT, # defaults to Sort.MOST_RELEVANT
#filter_score_with=5 # defaults to None(means all score)
)
opay_data = pd.json_normalize(reviews)
opay_data.to_csv('opay.csv', index = None)
print(opay_data.head())
A:
Your renaming your pandas import as pd, then renaming numpy also as pd - as the numpy import is last, it is now pd instead of pandas.
import pandas as pd
import numpy as pd
change it to this (assuming you need to import numpy at all):
import pandas as pd
import numpy as np
|
Why do I get module 'numpy' has no attribute 'json_normalize' when using pd.json_normalize()
|
I have a simple code that scrapes reviews from an app in Google Playstore.
The scrapping runs well and returns a json data. I decided to normalize it and get pandas dataframe.
All I keep getting is module 'numpy' has no attribute 'json_normalize'
Please I need help, all solutions I saw online have not worked. Below is my code
from google_play_scraper import app, Sort, reviews, reviews_all
import pandas as pd
import numpy as pd
reviews = reviews_all(
'com.hikingproject.android',
sleep_milliseconds=0, # defaults to 0
lang='en', # defaults to 'en'
country='NG', # defaults to 'us'
sort=Sort.MOST_RELEVANT, # defaults to Sort.MOST_RELEVANT
#filter_score_with=5 # defaults to None(means all score)
)
opay_data = pd.json_normalize(reviews)
opay_data.to_csv('opay.csv', index = None)
print(opay_data.head())
from google_play_scraper import app, Sort, reviews, reviews_all
import pandas as pd
import numpy as pd
reviews = reviews_all(
'com.hikingproject.android',
sleep_milliseconds=0, # defaults to 0
lang='en', # defaults to 'en'
country='NG', # defaults to 'us'
sort=Sort.MOST_RELEVANT, # defaults to Sort.MOST_RELEVANT
#filter_score_with=5 # defaults to None(means all score)
)
opay_data = pd.json_normalize(reviews)
opay_data.to_csv('opay.csv', index = None)
print(opay_data.head())
|
[
"Your renaming your pandas import as pd, then renaming numpy also as pd - as the numpy import is last, it is now pd instead of pandas.\nimport pandas as pd\nimport numpy as pd\n\nchange it to this (assuming you need to import numpy at all):\nimport pandas as pd\nimport numpy as np\n\n"
] |
[
1
] |
[] |
[] |
[
"dataframe",
"numpy",
"pandas",
"python"
] |
stackoverflow_0074495157_dataframe_numpy_pandas_python.txt
|
Q:
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet | APScheduler
I have this APScheduler code:
import atexit
from apscheduler.schedulers.background import BackgroundScheduler
from main.utils import run_employee_import
scheduler = BackgroundScheduler()
scheduler.add_job(run_employee_import, "interval", minutes=2)
scheduler.start()
# Shut down the scheduler when exiting the app
atexit.register(lambda: scheduler.shutdown())
When I add this code to settings.py to run it when the app starts to run, it gives me the following error:
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
PS: I did not include the run_employee_import code because I tested it already (replaced its content with a simple pass) and nothing changed, so it is irrelevant to the error.
A:
I completely changed the way I run the scheduler. And it worked, let me share the solution with you:
I create a .py file inside the app:
app/bulk_task.py
I create a start function and put the schedule code in it:
from apscheduler.schedulers.background import BackgroundScheduler
from main.utils import **<MY_TASK>**
def start():
scheduler = BackgroundScheduler()
scheduler.add_job(**<MY_TASK>**, "interval", minutes=5)
scheduler.start()
Then I open the apps.py file of my app, and I add the following code:
from django.apps import AppConfig
class MainConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "main"
def ready(self):
from . import bulk_task
bulk_task.start()
And that's it ;)
|
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet | APScheduler
|
I have this APScheduler code:
import atexit
from apscheduler.schedulers.background import BackgroundScheduler
from main.utils import run_employee_import
scheduler = BackgroundScheduler()
scheduler.add_job(run_employee_import, "interval", minutes=2)
scheduler.start()
# Shut down the scheduler when exiting the app
atexit.register(lambda: scheduler.shutdown())
When I add this code to settings.py to run it when the app starts to run, it gives me the following error:
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
PS: I did not include the run_employee_import code because I tested it already (replaced its content with a simple pass) and nothing changed, so it is irrelevant to the error.
|
[
"I completely changed the way I run the scheduler. And it worked, let me share the solution with you:\nI create a .py file inside the app:\napp/bulk_task.py\n\nI create a start function and put the schedule code in it:\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom main.utils import **<MY_TASK>**\n \ndef start():\n scheduler = BackgroundScheduler()\n scheduler.add_job(**<MY_TASK>**, \"interval\", minutes=5)\n scheduler.start()\n\nThen I open the apps.py file of my app, and I add the following code:\nfrom django.apps import AppConfig\n\n\nclass MainConfig(AppConfig):\n default_auto_field = \"django.db.models.BigAutoField\"\n name = \"main\"\n\n def ready(self):\n from . import bulk_task\n\n bulk_task.start()\n\nAnd that's it ;)\n"
] |
[
0
] |
[] |
[] |
[
"apscheduler",
"django",
"python"
] |
stackoverflow_0074495052_apscheduler_django_python.txt
|
Q:
Best way to constantly check for scheduled events on a website
So I am making a website, and something that required for part of the security is having a waiting period when trying to do something, for example trying to delete something, this would help incase someone's account was stolen and someone tried to ruin their account.
I'm already using SQLite so I'm going to create a table in there where scheduled events will be defined.
What I'm wondering is what is the best way to constantly check these scheduled events, it may also be important to note I want to check at least every hour. My immediate thought was creating a separate thread and running a function on there with a while loop in it which will constantly run a chunk of code with a time.sleep(3600) at the end of the function, like this:
def check_events(self):
while True:
# code
time.sleep(3600)
I'm not sure though if this is the most efficient way of doing it.
That function currently is inside my website code class hence the self, is that something I need to put on the outside or no?
A:
I would either create a cron job on your server (which is the most straightforward)
or use a schedule module to schedule your task, see example:
import time
import schedule
from sharepoint_cleaner import main as cleaner
from sharepoint_uploader import main as uploader
from transfer_statistics import main as transfer_stats
schedule.every(1).hours.do(uploader)
schedule.every(1).hours.do(transfer_stats)
schedule.every().sunday.do(cleaner)
while True:
schedule.run_pending()
time.sleep(10)
https://github.com/ansys/automatic-installer/blob/4d59573f8623c838aadfd49c312eeaca964c6601/sharepoint/scheduler.py#L3
|
Best way to constantly check for scheduled events on a website
|
So I am making a website, and something that required for part of the security is having a waiting period when trying to do something, for example trying to delete something, this would help incase someone's account was stolen and someone tried to ruin their account.
I'm already using SQLite so I'm going to create a table in there where scheduled events will be defined.
What I'm wondering is what is the best way to constantly check these scheduled events, it may also be important to note I want to check at least every hour. My immediate thought was creating a separate thread and running a function on there with a while loop in it which will constantly run a chunk of code with a time.sleep(3600) at the end of the function, like this:
def check_events(self):
while True:
# code
time.sleep(3600)
I'm not sure though if this is the most efficient way of doing it.
That function currently is inside my website code class hence the self, is that something I need to put on the outside or no?
|
[
"I would either create a cron job on your server (which is the most straightforward)\nor use a schedule module to schedule your task, see example:\nimport time\n\nimport schedule\nfrom sharepoint_cleaner import main as cleaner\nfrom sharepoint_uploader import main as uploader\nfrom transfer_statistics import main as transfer_stats\n\nschedule.every(1).hours.do(uploader)\nschedule.every(1).hours.do(transfer_stats)\nschedule.every().sunday.do(cleaner)\n\n\nwhile True:\n schedule.run_pending()\n time.sleep(10)\n\nhttps://github.com/ansys/automatic-installer/blob/4d59573f8623c838aadfd49c312eeaca964c6601/sharepoint/scheduler.py#L3\n"
] |
[
0
] |
[] |
[] |
[
"multithreading",
"python",
"scheduled_tasks"
] |
stackoverflow_0074495057_multithreading_python_scheduled_tasks.txt
|
Q:
Pandas: Pivot multi-index, with one 'shared' column
I have a pandas dataframe that can be represented like:
test_dict = {('a', 1) : {'shared':0,'x':1, 'y':2, 'z':3},
('a', 2) : {'shared':1,'x':2, 'y':4, 'z':6},
('b', 1) : {'shared':0,'x':10, 'y':20, 'z':30},
('b', 2) : {'shared':1,'x':100, 'y':200, 'z':300}}
example = pd.DataFrame.from_dict(test_dict).T
I am trying to figure out a way to turn this into a dataframe that looks like this dictionary representation:
res_dict = {1 : {'shared':0,'a':{'x':1, 'y':2, 'z':3}, 'b':{'x':10, 'y':20, 'z':30}},
2 : {'shared':1,'a':{'x':2, 'y':4, 'z':6},'b':{'x':100, 'y':200, 'z':300}}}
Any suggestions appreciated!
Thanks
A:
A possible solution, which uses only dataframe manipulations and then converts to dictionary:
xyz = ['x', 'y', 'z']
out = (example.assign(xyz=example[xyz].apply(list, axis=1)).reset_index()
.pivot(index='level_0', columns=['level_1', 'shared'], values='xyz')
.applymap(lambda x: dict(zip(xyz, x))))
out.columns = out.columns.rename(None, level=0)
out.index = out.index.rename(None)
(pd.concat([out.droplevel(1, axis=1),
out.columns.to_frame().reset_index(drop=True).iloc[:,1]
.to_frame().T.set_axis(out.columns.get_level_values(0), axis=1)])
.iloc[np.arange(-1, len(out))].to_dict())
Output:
{
1: {
'shared': 0,
'a': {'x': 1, 'y': 2, 'z': 3},
'b': {'x': 10, 'y': 20, 'z': 30}
},
2: {
'shared': 1,
'a': {'x': 2, 'y': 4, 'z': 6},
'b': {'x': 100, 'y': 200, 'z': 300}
}
}
|
Pandas: Pivot multi-index, with one 'shared' column
|
I have a pandas dataframe that can be represented like:
test_dict = {('a', 1) : {'shared':0,'x':1, 'y':2, 'z':3},
('a', 2) : {'shared':1,'x':2, 'y':4, 'z':6},
('b', 1) : {'shared':0,'x':10, 'y':20, 'z':30},
('b', 2) : {'shared':1,'x':100, 'y':200, 'z':300}}
example = pd.DataFrame.from_dict(test_dict).T
I am trying to figure out a way to turn this into a dataframe that looks like this dictionary representation:
res_dict = {1 : {'shared':0,'a':{'x':1, 'y':2, 'z':3}, 'b':{'x':10, 'y':20, 'z':30}},
2 : {'shared':1,'a':{'x':2, 'y':4, 'z':6},'b':{'x':100, 'y':200, 'z':300}}}
Any suggestions appreciated!
Thanks
|
[
"A possible solution, which uses only dataframe manipulations and then converts to dictionary:\nxyz = ['x', 'y', 'z']\nout = (example.assign(xyz=example[xyz].apply(list, axis=1)).reset_index()\n .pivot(index='level_0', columns=['level_1', 'shared'], values='xyz')\n .applymap(lambda x: dict(zip(xyz, x))))\n\nout.columns = out.columns.rename(None, level=0)\nout.index = out.index.rename(None)\n\n(pd.concat([out.droplevel(1, axis=1), \n out.columns.to_frame().reset_index(drop=True).iloc[:,1]\n .to_frame().T.set_axis(out.columns.get_level_values(0), axis=1)])\n .iloc[np.arange(-1, len(out))].to_dict())\n\nOutput:\n{\n 1: {\n 'shared': 0,\n 'a': {'x': 1, 'y': 2, 'z': 3},\n 'b': {'x': 10, 'y': 20, 'z': 30}\n },\n 2: {\n 'shared': 1,\n 'a': {'x': 2, 'y': 4, 'z': 6},\n 'b': {'x': 100, 'y': 200, 'z': 300}\n }\n}\n\n"
] |
[
1
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074494291_pandas_python.txt
|
Q:
Why is Django trying to find my image in such directory?
Instead"/media/", it tries to find here
???
The idea was to put several images in one object and everything works in the admin panel, but in the html template it paves the wrong path to the image. Tell me what am I doing wrong?
models.py
`
class Product(models.Model):
name = models.CharField(max_length=255, verbose_name='Название товара')
description = models.TextField(blank=True, verbose_name='Описание')
price = models.DecimalField(max_digits=10, decimal_places=0, verbose_name='Цена')
created = models.DateTimeField(auto_now_add=True, verbose_name='Время создания')
updated = models.DateTimeField(auto_now=True, verbose_name='Время обновления')
is_published = models.BooleanField(default=True, verbose_name='Публикация')
available = models.BooleanField(default=True, verbose_name='Наличие')
catalog = models.ForeignKey('Catalog', on_delete=models.PROTECT, verbose_name='Каталог')
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('product', kwargs={'product_id': self.pk})
class Meta:
verbose_name = "Товар"
verbose_name_plural = "Товары"
ordering = ['created']
class Images(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images')
images = models.ImageField(upload_to='images/%Y/%m/%d/')
def __str__(self):
return self.product.name
`
admin.py
`
class ImagesInline(admin.TabularInline):
fk_name = 'product'
model = Images
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
inlines = [ImagesInline, ]
list_display = ('id', 'name', 'price', 'created', 'updated', 'is_published', 'available', 'catalog')
list_display_links = ('id', )
search_fields = ('name', )
list_editable = ('name', 'price', 'is_published', 'available', 'catalog')
list_filter = ('is_published', 'available', 'created', 'catalog')
`
settings.py
`
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
`
shop/urls.py
`
urlpatterns = [
path('', index, name='home'),
path('about/', about, name='about'),
path('catalog/', catalog, name='catalog'),
path('basket/', cart, name='cart'),
path('register/', register, name='register'),
path('delivery/', delivery, name='delivery'),
path('product/<int:product_id>', show_product, name='product'),
path('category/<int:catalog_id>', show_category, name='category')[enter image description here](https://i.stack.imgur.com/xf9r5.png)
]
`
The only way it works for me is to just add several fields to the Product model.
image_one =
image_two =
image_three =
But I still want to fix my mistake.
I really hope for your help!
A:
Add this to your project urls.py (not the one in the app).
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
Why is Django trying to find my image in such directory?
|
Instead"/media/", it tries to find here
???
The idea was to put several images in one object and everything works in the admin panel, but in the html template it paves the wrong path to the image. Tell me what am I doing wrong?
models.py
`
class Product(models.Model):
name = models.CharField(max_length=255, verbose_name='Название товара')
description = models.TextField(blank=True, verbose_name='Описание')
price = models.DecimalField(max_digits=10, decimal_places=0, verbose_name='Цена')
created = models.DateTimeField(auto_now_add=True, verbose_name='Время создания')
updated = models.DateTimeField(auto_now=True, verbose_name='Время обновления')
is_published = models.BooleanField(default=True, verbose_name='Публикация')
available = models.BooleanField(default=True, verbose_name='Наличие')
catalog = models.ForeignKey('Catalog', on_delete=models.PROTECT, verbose_name='Каталог')
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('product', kwargs={'product_id': self.pk})
class Meta:
verbose_name = "Товар"
verbose_name_plural = "Товары"
ordering = ['created']
class Images(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images')
images = models.ImageField(upload_to='images/%Y/%m/%d/')
def __str__(self):
return self.product.name
`
admin.py
`
class ImagesInline(admin.TabularInline):
fk_name = 'product'
model = Images
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
inlines = [ImagesInline, ]
list_display = ('id', 'name', 'price', 'created', 'updated', 'is_published', 'available', 'catalog')
list_display_links = ('id', )
search_fields = ('name', )
list_editable = ('name', 'price', 'is_published', 'available', 'catalog')
list_filter = ('is_published', 'available', 'created', 'catalog')
`
settings.py
`
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
`
shop/urls.py
`
urlpatterns = [
path('', index, name='home'),
path('about/', about, name='about'),
path('catalog/', catalog, name='catalog'),
path('basket/', cart, name='cart'),
path('register/', register, name='register'),
path('delivery/', delivery, name='delivery'),
path('product/<int:product_id>', show_product, name='product'),
path('category/<int:catalog_id>', show_category, name='category')[enter image description here](https://i.stack.imgur.com/xf9r5.png)
]
`
The only way it works for me is to just add several fields to the Product model.
image_one =
image_two =
image_three =
But I still want to fix my mistake.
I really hope for your help!
|
[
"Add this to your project urls.py (not the one in the app).\nurlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n"
] |
[
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0074494992_django_python.txt
|
Q:
how can I display the other elements of my code?
This is my code:
def formater_les_parties(parties):
from datetime import datetime
i = f'{(len(parties[:-1]))} : {parties[0].get("date")}, {parties[0].get("joueurs")[0]} {"vs"} {parties[0].get("joueurs")[1]}, {"gagnant"}: {parties[0].get("gagnant")} \n'
for w in range((len(parties))):
i += str(w)
return i
and this is the test I made:
test1 = formater_les_parties([
{
"id": "5559cafd-6966-4465-af6f-67a784016b41",
"date": "2022-09-23 11:58:20",
"joueurs": ["IDUL", "automate"],
"gagnant": None
},
...
{
"id": "80a0a0d2-059d-4539-9d53-78b3f6045943",
"date": "2022-09-24 14:23:59",
"joueurs": ["IDUL", "automate"],
"gagnant": "automate"
}
])
print(test1)
this is my result :
1 : 2022-09-23 11:58:20, IDUL vs automate, gagnant: None
0
but this is what is supposed to be :
1 : 2022-09-23 11:58:20, IDUL vs automate
...
20: 2022-09-24 14:23:59, IDUL vs automate, gagnant: automate
I tried to add all number of my parties to i, and I don't know how I am supposed to do it?
A:
Not only what @quamrana said, but you only use parties[0]; here's what you wanted to do:
def formater_les_parties(parties):
from datetime import datetime
i = ''
for w in range((len(parties))):
i += f'{w} : {parties[w].get("date")}, {parties[w].get("joueurs")[0]} {"vs"} {parties[w].get("joueurs")[1]}, {"gagnant"}: {parties[w].get("gagnant")} \n'
return i
A:
The return was indented improperly, and the lines weren't generated correctly.
This is a bit simplified using enumerate for less indexing:
def formater_les_parties(parties):
result = ''
for i, party in enumerate(parties):
result += f'{i:<2}: {party["date"]}, {" vs ".join(party["joueurs"])}, "gagnant": {party["gagnant"]}\n'
return result
test1 = formater_les_parties([
{
"id": "5559cafd-6966-4465-af6f-67a784016b41",
"date": "2022-09-23 11:58:20",
"joueurs": ["IDUL", "automate"],
"gagnant": None
},
{
"id": "80a0a0d2-059d-4539-9d53-78b3f6045943",
"date": "2022-09-24 14:23:59",
"joueurs": ["IDUL", "automate"],
"gagnant": "automate"
}
])
print(test1)
Output:
0 : 2022-09-23 11:58:20, IDUL vs automate, "gagnant": None
1 : 2022-09-24 14:23:59, IDUL vs automate, "gagnant": automate
|
how can I display the other elements of my code?
|
This is my code:
def formater_les_parties(parties):
from datetime import datetime
i = f'{(len(parties[:-1]))} : {parties[0].get("date")}, {parties[0].get("joueurs")[0]} {"vs"} {parties[0].get("joueurs")[1]}, {"gagnant"}: {parties[0].get("gagnant")} \n'
for w in range((len(parties))):
i += str(w)
return i
and this is the test I made:
test1 = formater_les_parties([
{
"id": "5559cafd-6966-4465-af6f-67a784016b41",
"date": "2022-09-23 11:58:20",
"joueurs": ["IDUL", "automate"],
"gagnant": None
},
...
{
"id": "80a0a0d2-059d-4539-9d53-78b3f6045943",
"date": "2022-09-24 14:23:59",
"joueurs": ["IDUL", "automate"],
"gagnant": "automate"
}
])
print(test1)
this is my result :
1 : 2022-09-23 11:58:20, IDUL vs automate, gagnant: None
0
but this is what is supposed to be :
1 : 2022-09-23 11:58:20, IDUL vs automate
...
20: 2022-09-24 14:23:59, IDUL vs automate, gagnant: automate
I tried to add all number of my parties to i, and I don't know how I am supposed to do it?
|
[
"Not only what @quamrana said, but you only use parties[0]; here's what you wanted to do:\ndef formater_les_parties(parties):\n from datetime import datetime\n i = ''\n for w in range((len(parties))):\n i += f'{w} : {parties[w].get(\"date\")}, {parties[w].get(\"joueurs\")[0]} {\"vs\"} {parties[w].get(\"joueurs\")[1]}, {\"gagnant\"}: {parties[w].get(\"gagnant\")} \\n'\n \n return i\n\n",
"The return was indented improperly, and the lines weren't generated correctly.\nThis is a bit simplified using enumerate for less indexing:\ndef formater_les_parties(parties):\n result = ''\n for i, party in enumerate(parties):\n result += f'{i:<2}: {party[\"date\"]}, {\" vs \".join(party[\"joueurs\"])}, \"gagnant\": {party[\"gagnant\"]}\\n'\n return result\n\ntest1 = formater_les_parties([\n {\n \"id\": \"5559cafd-6966-4465-af6f-67a784016b41\",\n \"date\": \"2022-09-23 11:58:20\",\n \"joueurs\": [\"IDUL\", \"automate\"],\n \"gagnant\": None\n },\n {\n \"id\": \"80a0a0d2-059d-4539-9d53-78b3f6045943\",\n \"date\": \"2022-09-24 14:23:59\",\n \"joueurs\": [\"IDUL\", \"automate\"],\n \"gagnant\": \"automate\"\n }\n])\nprint(test1)\n\nOutput:\n0 : 2022-09-23 11:58:20, IDUL vs automate, \"gagnant\": None\n1 : 2022-09-24 14:23:59, IDUL vs automate, \"gagnant\": automate\n\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0074495154_python_python_3.x.txt
|
Q:
How to get keyboard input in pygame?
I am making a game in pygame 1.9.2.
It's a faily simple game in which a ship moves between five columns of bad guys who attack by moving slowly downward. I am attempting to make it so that the ship moves left and right with the left and right arrow keys. Here is my code:
keys=pygame.key.get_pressed()
if keys[K_LEFT]:
location-=1
if location==-1:
location=0
if keys[K_RIGHT]:
location+=1
if location==5:
location=4
It works too well. The ship moves too fast. It is near impossible to have it move only one location, left or right. How can i make it so the ship only moves once every time the key is pressed?
A:
You can get the events from pygame and then watch out for the KEYDOWN event, instead of looking at the keys returned by get_pressed()(which gives you keys that are currently pressed down, whereas the KEYDOWN event shows you which keys were pressed down on that frame).
What's happening with your code right now is that if your game is rendering at 30fps, and you hold down the left arrow key for half a second, you're updating the location 15 times.
events = pygame.event.get()
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
location -= 1
if event.key == pygame.K_RIGHT:
location += 1
To support continuous movement while a key is being held down, you would have to establish some sort of limitation, either based on a forced maximum frame rate of the game loop or by a counter which only allows you to move every so many ticks of the loop.
move_ticker = 0
keys=pygame.key.get_pressed()
if keys[K_LEFT]:
if move_ticker == 0:
move_ticker = 10
location -= 1
if location == -1:
location = 0
if keys[K_RIGHT]:
if move_ticker == 0:
move_ticker = 10
location+=1
if location == 5:
location = 4
Then somewhere during the game loop you would do something like this:
if move_ticker > 0:
move_ticker -= 1
This would only let you move once every 10 frames (so if you move, the ticker gets set to 10, and after 10 frames it will allow you to move again)
A:
pygame.key.get_pressed() returns a list with the state of each key. If a key is held down, the state for the key is 1, otherwise 0. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement:
while True:
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x -= speed
if keys[pygame.K_RIGHT]:
x += speed
if keys[pygame.K_UP]:
y -= speed
if keys[pygame.K_DOWN]:
y += speed
This code can be simplified by subtracting "left" from "right" and "up" from "down":
while True:
keys = pygame.key.get_pressed()
x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * speed
y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * speed
The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action or movement:
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x -= speed
if event.key == pygame.K_RIGHT:
x += speed
if event.key == pygame.K_UP:
y -= speed
if event.key == pygame.K_DOWN:
y += speed
See also Key and Keyboard event
Minimal example of continuous movement: replit.com/@Rabbid76/PyGame-ContinuousMovement
import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
rect = pygame.Rect(0, 0, 20, 20)
rect.center = window.get_rect().center
vel = 5
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
print(pygame.key.name(event.key))
keys = pygame.key.get_pressed()
rect.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel
rect.y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * vel
rect.centerx = rect.centerx % window.get_width()
rect.centery = rect.centery % window.get_height()
window.fill(0)
pygame.draw.rect(window, (255, 0, 0), rect)
pygame.display.flip()
pygame.quit()
exit()
Minimal example for a single action: replit.com/@Rabbid76/PyGame-ShootBullet
import pygame
pygame.init()
window = pygame.display.set_mode((500, 200))
clock = pygame.time.Clock()
tank_surf = pygame.Surface((60, 40), pygame.SRCALPHA)
pygame.draw.rect(tank_surf, (0, 96, 0), (0, 00, 50, 40))
pygame.draw.rect(tank_surf, (0, 128, 0), (10, 10, 30, 20))
pygame.draw.rect(tank_surf, (32, 32, 96), (20, 16, 40, 8))
tank_rect = tank_surf.get_rect(midleft = (20, window.get_height() // 2))
bullet_surf = pygame.Surface((10, 10), pygame.SRCALPHA)
pygame.draw.circle(bullet_surf, (64, 64, 62), bullet_surf.get_rect().center, bullet_surf.get_width() // 2)
bullet_list = []
run = True
while run:
clock.tick(60)
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
bullet_list.insert(0, tank_rect.midright)
for i, bullet_pos in enumerate(bullet_list):
bullet_list[i] = bullet_pos[0] + 5, bullet_pos[1]
if bullet_surf.get_rect(center = bullet_pos).left > window.get_width():
del bullet_list[i:]
break
window.fill((224, 192, 160))
window.blit(tank_surf, tank_rect)
for bullet_pos in bullet_list:
window.blit(bullet_surf, bullet_surf.get_rect(center = bullet_pos))
pygame.display.flip()
pygame.quit()
exit()
A:
import pygame
pygame.init()
pygame.display.set_mode()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit(); #sys.exit() if sys is imported
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_0:
print("Hey, you pressed the key, '0'!")
if event.key == pygame.K_1:
print("Doing whatever")
In note that K_0 and K_1 aren't the only keys, to see all of them, see pygame documentation, otherwise, hit tab after typing in
pygame.
(note the . after pygame) into an idle program. Note that the K must be capital. Also note that if you don't give pygame a display size (pass no args), then it will auto-use the size of the computer screen/monitor. Happy coding!
A:
I think you can use:
pygame.time.delay(delayTime)
in which delayTime is in milliseconds.
Put it before events.
A:
Try this:
keys=pygame.key.get_pressed()
if keys[K_LEFT]:
if count == 10:
location-=1
count=0
else:
count +=1
if location==-1:
location=0
if keys[K_RIGHT]:
if count == 10:
location+=1
count=0
else:
count +=1
if location==5:
location=4
This will mean you only move 1/10 of the time. If it still moves to fast you could try increasing the value you set "count" too.
A:
The reason behind this is that the pygame window operates at 60 fps (frames per second) and when you press the key for just like 1 sec it updates 60 frames as per the loop of the event block.
clock = pygame.time.Clock()
flag = true
while flag :
clock.tick(60)
Note that if you have animation in your project then the number of images will define the number of values in tick(). Let's say you have a character and it requires 20 sets images for walking and jumping then you have to make tick(20) to move the character the right way.
A:
Just fyi, if you're trying to ensure the ship doesn't go off of the screen with
location-=1
if location==-1:
location=0
you can probably better use
location -= 1
location = max(0, location)
This way if it skips -1 your program doesn't break
A:
make something like this, but based on time delay. i call my function first time immediately and then lunch timer, and while button is pressed i call it every button_press_delta seconds
from time import time
before main loop:
button_press_delta = 0.2
right_button_pressed = 0
while not done:
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT]:
if not right_button_pressed:
call_my_function()
right_button_pressed = 1
right_button_pressed_time_start = time()
if right_button_pressed:
right_button_pressed_time = (
time() - right_button_pressed_time_start)
if right_button_pressed_time > button_press_delta:
call_my_function()
right_button_pressed_time_start = time()
else:
right_button_pressed = 0
|
How to get keyboard input in pygame?
|
I am making a game in pygame 1.9.2.
It's a faily simple game in which a ship moves between five columns of bad guys who attack by moving slowly downward. I am attempting to make it so that the ship moves left and right with the left and right arrow keys. Here is my code:
keys=pygame.key.get_pressed()
if keys[K_LEFT]:
location-=1
if location==-1:
location=0
if keys[K_RIGHT]:
location+=1
if location==5:
location=4
It works too well. The ship moves too fast. It is near impossible to have it move only one location, left or right. How can i make it so the ship only moves once every time the key is pressed?
|
[
"You can get the events from pygame and then watch out for the KEYDOWN event, instead of looking at the keys returned by get_pressed()(which gives you keys that are currently pressed down, whereas the KEYDOWN event shows you which keys were pressed down on that frame).\nWhat's happening with your code right now is that if your game is rendering at 30fps, and you hold down the left arrow key for half a second, you're updating the location 15 times.\nevents = pygame.event.get()\nfor event in events:\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n location -= 1\n if event.key == pygame.K_RIGHT:\n location += 1\n\nTo support continuous movement while a key is being held down, you would have to establish some sort of limitation, either based on a forced maximum frame rate of the game loop or by a counter which only allows you to move every so many ticks of the loop.\nmove_ticker = 0\nkeys=pygame.key.get_pressed()\nif keys[K_LEFT]:\n if move_ticker == 0:\n move_ticker = 10\n location -= 1\n if location == -1:\n location = 0\nif keys[K_RIGHT]:\n if move_ticker == 0: \n move_ticker = 10 \n location+=1\n if location == 5:\n location = 4\n\nThen somewhere during the game loop you would do something like this:\nif move_ticker > 0:\n move_ticker -= 1\n\nThis would only let you move once every 10 frames (so if you move, the ticker gets set to 10, and after 10 frames it will allow you to move again)\n",
"pygame.key.get_pressed() returns a list with the state of each key. If a key is held down, the state for the key is 1, otherwise 0. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement:\nwhile True:\n\n keys = pygame.key.get_pressed()\n if keys[pygame.K_LEFT]:\n x -= speed\n if keys[pygame.K_RIGHT]:\n x += speed\n if keys[pygame.K_UP]:\n y -= speed\n if keys[pygame.K_DOWN]:\n y += speed\n\nThis code can be simplified by subtracting \"left\" from \"right\" and \"up\" from \"down\":\nwhile True:\n\n keys = pygame.key.get_pressed()\n x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * speed\n y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * speed\n\nThe keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action or movement:\nwhile True:\n\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n x -= speed\n if event.key == pygame.K_RIGHT:\n x += speed\n if event.key == pygame.K_UP:\n y -= speed\n if event.key == pygame.K_DOWN:\n y += speed\n\nSee also Key and Keyboard event\n\nMinimal example of continuous movement: replit.com/@Rabbid76/PyGame-ContinuousMovement\n\nimport pygame\n\npygame.init()\nwindow = pygame.display.set_mode((300, 300))\nclock = pygame.time.Clock()\n\nrect = pygame.Rect(0, 0, 20, 20)\nrect.center = window.get_rect().center\nvel = 5\n\nrun = True\nwhile run:\n clock.tick(60)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n if event.type == pygame.KEYDOWN:\n print(pygame.key.name(event.key))\n\n keys = pygame.key.get_pressed()\n \n rect.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel\n rect.y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * vel\n \n rect.centerx = rect.centerx % window.get_width()\n rect.centery = rect.centery % window.get_height()\n\n window.fill(0)\n pygame.draw.rect(window, (255, 0, 0), rect)\n pygame.display.flip()\n\npygame.quit()\nexit()\n\n\nMinimal example for a single action: replit.com/@Rabbid76/PyGame-ShootBullet\n\nimport pygame\npygame.init()\n\nwindow = pygame.display.set_mode((500, 200))\nclock = pygame.time.Clock()\n\ntank_surf = pygame.Surface((60, 40), pygame.SRCALPHA)\npygame.draw.rect(tank_surf, (0, 96, 0), (0, 00, 50, 40))\npygame.draw.rect(tank_surf, (0, 128, 0), (10, 10, 30, 20))\npygame.draw.rect(tank_surf, (32, 32, 96), (20, 16, 40, 8))\ntank_rect = tank_surf.get_rect(midleft = (20, window.get_height() // 2))\n\nbullet_surf = pygame.Surface((10, 10), pygame.SRCALPHA)\npygame.draw.circle(bullet_surf, (64, 64, 62), bullet_surf.get_rect().center, bullet_surf.get_width() // 2)\nbullet_list = []\n\nrun = True\nwhile run:\n clock.tick(60)\n current_time = pygame.time.get_ticks()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n\n if event.type == pygame.KEYDOWN:\n bullet_list.insert(0, tank_rect.midright)\n\n for i, bullet_pos in enumerate(bullet_list):\n bullet_list[i] = bullet_pos[0] + 5, bullet_pos[1]\n if bullet_surf.get_rect(center = bullet_pos).left > window.get_width():\n del bullet_list[i:]\n break\n\n window.fill((224, 192, 160))\n window.blit(tank_surf, tank_rect)\n for bullet_pos in bullet_list:\n window.blit(bullet_surf, bullet_surf.get_rect(center = bullet_pos))\n pygame.display.flip()\n\npygame.quit()\nexit()\n\n",
"import pygame\npygame.init()\npygame.display.set_mode()\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit(); #sys.exit() if sys is imported\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_0:\n print(\"Hey, you pressed the key, '0'!\")\n if event.key == pygame.K_1:\n print(\"Doing whatever\")\n\nIn note that K_0 and K_1 aren't the only keys, to see all of them, see pygame documentation, otherwise, hit tab after typing in\n\npygame.\n\n(note the . after pygame) into an idle program. Note that the K must be capital. Also note that if you don't give pygame a display size (pass no args), then it will auto-use the size of the computer screen/monitor. Happy coding!\n",
"I think you can use:\npygame.time.delay(delayTime)\n\nin which delayTime is in milliseconds.\nPut it before events.\n",
"Try this:\nkeys=pygame.key.get_pressed()\nif keys[K_LEFT]:\n if count == 10:\n location-=1\n count=0\n else:\n count +=1\n if location==-1:\n location=0\nif keys[K_RIGHT]:\n if count == 10:\n location+=1\n count=0\n else:\n count +=1\n if location==5:\n location=4\n\nThis will mean you only move 1/10 of the time. If it still moves to fast you could try increasing the value you set \"count\" too.\n",
"The reason behind this is that the pygame window operates at 60 fps (frames per second) and when you press the key for just like 1 sec it updates 60 frames as per the loop of the event block.\nclock = pygame.time.Clock()\nflag = true\nwhile flag :\n clock.tick(60)\n\nNote that if you have animation in your project then the number of images will define the number of values in tick(). Let's say you have a character and it requires 20 sets images for walking and jumping then you have to make tick(20) to move the character the right way.\n",
"Just fyi, if you're trying to ensure the ship doesn't go off of the screen with\nlocation-=1\nif location==-1:\n location=0\n\nyou can probably better use\nlocation -= 1\nlocation = max(0, location)\n\nThis way if it skips -1 your program doesn't break\n",
"make something like this, but based on time delay. i call my function first time immediately and then lunch timer, and while button is pressed i call it every button_press_delta seconds\nfrom time import time\nbefore main loop:\nbutton_press_delta = 0.2\nright_button_pressed = 0\nwhile not done:\n keys = pygame.key.get_pressed()\n if keys[pygame.K_RIGHT]:\n if not right_button_pressed:\n call_my_function()\n right_button_pressed = 1\n right_button_pressed_time_start = time()\n if right_button_pressed:\n right_button_pressed_time = (\n time() - right_button_pressed_time_start)\n if right_button_pressed_time > button_press_delta:\n call_my_function()\n right_button_pressed_time_start = time()\n else:\n right_button_pressed = 0\n\n"
] |
[
111,
17,
12,
2,
1,
1,
0,
0
] |
[
"You should use clock.tick(10) as stated in the docs.\n",
"all of the answers above are too complexicated i would just change the variables by 0.1 instead of 1\nthis makes the ship 10 times slower\nif that is still too fast change the variables by 0.01\nthis makes the ship 100 times slower\ntry this\nkeys=pygame.key.get_pressed()\nif keys[K_LEFT]:\n location -= 0.1 #or 0.01\n if location==-1:\n location=0\nif keys[K_RIGHT]:\n location += 0.1 #or 0.01\n if location==5:\n location=4\n\n",
"To slow down your game, use pygame.clock.tick(10)\n"
] |
[
-2,
-3,
-3
] |
[
"keyboard",
"pygame",
"python"
] |
stackoverflow_0016044229_keyboard_pygame_python.txt
|
Q:
How to use a Django (Python) Login Form?
I builded a login form in Django. Now I have a problem with the routing.
When I select the login button, the form doesn`t send the correct awnser.
I think the form in the frontend cannot gets the correct awnser from the
view.py file. So it will send no awnser and the login process canot work and
the form is a simple static html form.
I hope you can help me.
HTML:
<form class="windowlogscreen-content" method="POST">
{% csrf_token %}
<input type="text" placeholder="account" name="username">
<br>
<input type="password" placeholder="password" name="password">
<br>
<button style="margin: 20px;" type="submit">join</button>
</div>
</div>
</form>
views.py
def loginuser(request):
if request.method == "POST":
username = request.POST['accountName']
password = request.POST['accountPassword']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return views.homepage
else:
return redirect('start')
else:
return render(request, 'start', {})
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', start),
path('homepage/', include('homepage.urls'))
]
homepage urls.py
urlpatterns = [
path('login/', views.login, name="login"),
path('register/', views.register, name="register"),
path('', views.homepage, name="homepage"),
path('account/', views.account, name="account")
]
A:
def login(request):
if request.method = 'POST':
username = request.POST['username']
password = request.method = POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return redirect(#User to the dashboard!)
else:
message.info(request, "invalid credentials")
return redirect('login')
else:
return render(request, 'login.html')
Login.html:
<form method="POST" action="{% url 'login' %}">
{% csrf_token %}
<div class="form-group">
<label class="text-primary text-dark font-weight-bold">Enter Username</label>
<input type="text" class="form-control" name="username" placeholder="Enter Username">
</div>
<br>
<div class="form-group">
<label class="text-primary text-dark font-weight-bold">Enter Password</label>
<input type="password" class="form-control" name="password" placeholder="Enter Password">
</div>
<br>
<button type="submit" class="btn btn-primary btn-lg">Log in</button>
</form>
Docs
|
How to use a Django (Python) Login Form?
|
I builded a login form in Django. Now I have a problem with the routing.
When I select the login button, the form doesn`t send the correct awnser.
I think the form in the frontend cannot gets the correct awnser from the
view.py file. So it will send no awnser and the login process canot work and
the form is a simple static html form.
I hope you can help me.
HTML:
<form class="windowlogscreen-content" method="POST">
{% csrf_token %}
<input type="text" placeholder="account" name="username">
<br>
<input type="password" placeholder="password" name="password">
<br>
<button style="margin: 20px;" type="submit">join</button>
</div>
</div>
</form>
views.py
def loginuser(request):
if request.method == "POST":
username = request.POST['accountName']
password = request.POST['accountPassword']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return views.homepage
else:
return redirect('start')
else:
return render(request, 'start', {})
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', start),
path('homepage/', include('homepage.urls'))
]
homepage urls.py
urlpatterns = [
path('login/', views.login, name="login"),
path('register/', views.register, name="register"),
path('', views.homepage, name="homepage"),
path('account/', views.account, name="account")
]
|
[
"def login(request):\n if request.method = 'POST':\n username = request.POST['username']\n password = request.method = POST['password']\n\n user = auth.authenticate(username=username, password=password)\n\n if user is not None:\n auth.login(request, user)\n return redirect(#User to the dashboard!)\n else:\n message.info(request, \"invalid credentials\")\n return redirect('login')\n else:\n return render(request, 'login.html')\n\nLogin.html:\n<form method=\"POST\" action=\"{% url 'login' %}\">\n {% csrf_token %}\n <div class=\"form-group\">\n <label class=\"text-primary text-dark font-weight-bold\">Enter Username</label>\n <input type=\"text\" class=\"form-control\" name=\"username\" placeholder=\"Enter Username\">\n </div>\n\n <br>\n <div class=\"form-group\">\n <label class=\"text-primary text-dark font-weight-bold\">Enter Password</label>\n <input type=\"password\" class=\"form-control\" name=\"password\" placeholder=\"Enter Password\">\n </div>\n \n\n <br>\n <button type=\"submit\" class=\"btn btn-primary btn-lg\">Log in</button>\n </form>\n\nDocs\n"
] |
[
0
] |
[] |
[] |
[
"django",
"html",
"python"
] |
stackoverflow_0074495020_django_html_python.txt
|
Q:
AWS Lambda Python Cryptography - Cannot open shared object files
I am working on a Serverless Flask app that is deployed to AWS Lambda. The program uses the Cryptography library (using version 3.4.7). Locally, the program runs fine without any issue. However, whenever deployed on Lambda, the following error appears:
from cryptography.fernet import Fernet
File "/var/task/cryptography/fernet.py", line 16, in <module>
from cryptography.hazmat.primitives import hashes, padding
File "/var/task/cryptography/hazmat/primitives/padding.py", line 11, in <module>
from cryptography.hazmat.bindings._padding import lib
ImportError: /var/task/cryptography/hazmat/bindings/_padding.abi3.so: cannot open shared object file: No such file or directory
And when using some required functions from the "Hazardous Material" module, a very similar error appears:
File "/var/task/cryptography/hazmat/primitives/kdf/pbkdf2.py", line 28, in __init__
backend = _get_backend(backend)
File "/var/task/cryptography/hazmat/backends/__init__.py", line 23, in _get_backend
return default_backend()
File "/var/task/cryptography/hazmat/backends/__init__.py", line 14, in default_backend
from cryptography.hazmat.backends.openssl.backend import backend
File "/var/task/cryptography/hazmat/backends/openssl/__init__.py", line 6, in <module>
from cryptography.hazmat.backends.openssl.backend import backend
File "/var/task/cryptography/hazmat/backends/openssl/backend.py", line 113, in <module>
from cryptography.hazmat.bindings.openssl import binding
File "/var/task/cryptography/hazmat/bindings/openssl/binding.py", line 14, in <module>
from cryptography.hazmat.bindings._openssl import ffi, lib
ImportError: /var/task/cryptography/hazmat/bindings/_openssl.abi3.so: cannot open shared object file: No such file or directory
However, the library files referenced do exist and they are in the exact paths indicated.
The app includes cryptography==3.4.7 in the requirements.txt as a dependency. Serverless then installs the packages while deploying to AWS with sls deploy. Serverless puts everything in a zip and uploads it to AWS. I can see all the files in this zip folder as expected.
I thought that it might be an issue with serverless incorrectly uploading or installing the packages when deploying, so I even tried including the cryptography folder directly in my project. However, despite any changes to the serverless configuration or the cryptography package itself, I have been unsuccessful in using this package on my deployed Lambda. Does anyone have any ideas what I could do to make this work?
A:
I had a similar problem before that was resolved by running the deployment command from a linux machine. I use a mac for development and I was trying to deploy my lambda function from my mac. However, when it was deployed some of the dependencies threw import errors.
From my experience, it was due to the operating system that packages the dependencies differently when it runs in a mac or a linux environment. Hence, try running the serverless deployment command from inside a linux machine to see if that works.
In my case, I set up a gitlab CI/CD pipeline to run the command inside the environment of gitlab pipeline and that resolved the problem.
A:
What I did to fix a similar problem, while trying to add a layer with the cryptography library to a lambda function, was to use the same runtime and processor architecture, in both the lambda function and layer.
For example, my problem was that I had a lambda function running with Python 3.9, and in a arm64 architecture. But I was creating the layer .zip file running python 3.8, and in a x86_64 architecture.
Don't ask me why it was easier for me to re-create the lambda in Python 3.8 and in x86_64, rather than the other way around.
Anyhow, as soon as I added the layer (with the cryptography library) to the lambda, it ran smoothly.
So, my theory is that you need to match both the runtime and architecture in order for a layer to work properly with a lambda function.
Additionally, now that I look up my solution, it is actually backed up by this article: https://docs.aws.amazon.com/lambda/latest/dg/invocation-layers.html
(see the notes in it)
A:
I had similar errors after migrating my Lambda functions from python 3.6 to python 3.9
I use an amazonlinux docker container for development, testing, and deployment (via serverless).
In cryptography's documentation, the installation steps for Linux are not as straightforward as in macOS as cryptography ships manylinux wheels (as of 2.0).
Here's what you could try:
Upgrade pip and reinstall cryptography via pip again.
or
Compile cryptography yourself (you’ll need a C compiler, a Rust compiler, headers for Python (if you’re not using pypy), and headers for the OpenSSL and libffiInstall), these packages are redhat-rpm-config gcc libffi-devel python3-devel openssl-devel cargo, using your package manager and then run:
pip install cryptography --no-binary cryptography
In cryptography's FAQ page, there's a section about AWS Lambda.
A:
One recommendation Amazon presents is to use the "sam" tool to build the distribution by using a Docker container. However, in my situation I wasn't able to use docker in the build environment.
Amazon provides some other documentation on how to use pip to install requirements by passing very explicit command line flags to ensure the Lambda environment's version is downloaded:
pip install \
--platform manylinux2014_x86_64 \
--implementation cp \
--python 3.9 \
--only-binary=:all: --upgrade \
--target=build/package \
cryptography==38.0.3
The "build/package" path will cause the dependencies to be downloaded and installed into that directory, to allow for easy zip for upload into a Lambda.
These flags can also be used if you have a setup.cfg or pyproject.toml file by using "." as the resource to load, rather than the explicitly named library.
I expect that as Amazon introduces new runtime environments and deprecates older ones, the given --platform and --python flags will need to change.
|
AWS Lambda Python Cryptography - Cannot open shared object files
|
I am working on a Serverless Flask app that is deployed to AWS Lambda. The program uses the Cryptography library (using version 3.4.7). Locally, the program runs fine without any issue. However, whenever deployed on Lambda, the following error appears:
from cryptography.fernet import Fernet
File "/var/task/cryptography/fernet.py", line 16, in <module>
from cryptography.hazmat.primitives import hashes, padding
File "/var/task/cryptography/hazmat/primitives/padding.py", line 11, in <module>
from cryptography.hazmat.bindings._padding import lib
ImportError: /var/task/cryptography/hazmat/bindings/_padding.abi3.so: cannot open shared object file: No such file or directory
And when using some required functions from the "Hazardous Material" module, a very similar error appears:
File "/var/task/cryptography/hazmat/primitives/kdf/pbkdf2.py", line 28, in __init__
backend = _get_backend(backend)
File "/var/task/cryptography/hazmat/backends/__init__.py", line 23, in _get_backend
return default_backend()
File "/var/task/cryptography/hazmat/backends/__init__.py", line 14, in default_backend
from cryptography.hazmat.backends.openssl.backend import backend
File "/var/task/cryptography/hazmat/backends/openssl/__init__.py", line 6, in <module>
from cryptography.hazmat.backends.openssl.backend import backend
File "/var/task/cryptography/hazmat/backends/openssl/backend.py", line 113, in <module>
from cryptography.hazmat.bindings.openssl import binding
File "/var/task/cryptography/hazmat/bindings/openssl/binding.py", line 14, in <module>
from cryptography.hazmat.bindings._openssl import ffi, lib
ImportError: /var/task/cryptography/hazmat/bindings/_openssl.abi3.so: cannot open shared object file: No such file or directory
However, the library files referenced do exist and they are in the exact paths indicated.
The app includes cryptography==3.4.7 in the requirements.txt as a dependency. Serverless then installs the packages while deploying to AWS with sls deploy. Serverless puts everything in a zip and uploads it to AWS. I can see all the files in this zip folder as expected.
I thought that it might be an issue with serverless incorrectly uploading or installing the packages when deploying, so I even tried including the cryptography folder directly in my project. However, despite any changes to the serverless configuration or the cryptography package itself, I have been unsuccessful in using this package on my deployed Lambda. Does anyone have any ideas what I could do to make this work?
|
[
"I had a similar problem before that was resolved by running the deployment command from a linux machine. I use a mac for development and I was trying to deploy my lambda function from my mac. However, when it was deployed some of the dependencies threw import errors.\nFrom my experience, it was due to the operating system that packages the dependencies differently when it runs in a mac or a linux environment. Hence, try running the serverless deployment command from inside a linux machine to see if that works.\nIn my case, I set up a gitlab CI/CD pipeline to run the command inside the environment of gitlab pipeline and that resolved the problem.\n",
"What I did to fix a similar problem, while trying to add a layer with the cryptography library to a lambda function, was to use the same runtime and processor architecture, in both the lambda function and layer.\nFor example, my problem was that I had a lambda function running with Python 3.9, and in a arm64 architecture. But I was creating the layer .zip file running python 3.8, and in a x86_64 architecture.\nDon't ask me why it was easier for me to re-create the lambda in Python 3.8 and in x86_64, rather than the other way around.\nAnyhow, as soon as I added the layer (with the cryptography library) to the lambda, it ran smoothly.\nSo, my theory is that you need to match both the runtime and architecture in order for a layer to work properly with a lambda function.\nAdditionally, now that I look up my solution, it is actually backed up by this article: https://docs.aws.amazon.com/lambda/latest/dg/invocation-layers.html\n(see the notes in it)\n",
"I had similar errors after migrating my Lambda functions from python 3.6 to python 3.9\nI use an amazonlinux docker container for development, testing, and deployment (via serverless).\nIn cryptography's documentation, the installation steps for Linux are not as straightforward as in macOS as cryptography ships manylinux wheels (as of 2.0).\nHere's what you could try:\n\nUpgrade pip and reinstall cryptography via pip again.\nor\n\nCompile cryptography yourself (you’ll need a C compiler, a Rust compiler, headers for Python (if you’re not using pypy), and headers for the OpenSSL and libffiInstall), these packages are redhat-rpm-config gcc libffi-devel python3-devel openssl-devel cargo, using your package manager and then run:\npip install cryptography --no-binary cryptography\n\n\nIn cryptography's FAQ page, there's a section about AWS Lambda.\n",
"One recommendation Amazon presents is to use the \"sam\" tool to build the distribution by using a Docker container. However, in my situation I wasn't able to use docker in the build environment.\nAmazon provides some other documentation on how to use pip to install requirements by passing very explicit command line flags to ensure the Lambda environment's version is downloaded:\npip install \\\n --platform manylinux2014_x86_64 \\\n --implementation cp \\\n --python 3.9 \\\n --only-binary=:all: --upgrade \\\n --target=build/package \\\n cryptography==38.0.3\n\nThe \"build/package\" path will cause the dependencies to be downloaded and installed into that directory, to allow for easy zip for upload into a Lambda.\nThese flags can also be used if you have a setup.cfg or pyproject.toml file by using \".\" as the resource to load, rather than the explicitly named library.\nI expect that as Amazon introduces new runtime environments and deprecates older ones, the given --platform and --python flags will need to change.\n"
] |
[
1,
1,
0,
0
] |
[] |
[] |
[
"amazon_web_services",
"aws_lambda",
"python",
"python_cryptography",
"serverless_framework"
] |
stackoverflow_0067646196_amazon_web_services_aws_lambda_python_python_cryptography_serverless_framework.txt
|
Q:
Slice of 2d numpy array with another array
I have a quite large 2d array, and I need to get both the index of the maximum value in axis 1, and the maximum value itself. I can retrieve these two values as follows:
import numpy as np
a = np.arange(27).reshape(9, 3)
idx = np.argmax(a, axis=1)
max_val = np.max(a, axis=1)
However, since I have already found the index of the maximum value, it feels like I should be able to construct the array of maximum values using idx without having to look up the value again.
I realise I can use np.choose(idx, a.T) but this involves transposing the matrix which will be much more expensive than just using max. I can do something like np.array([a[i][idx[i]] for i in range(len(a))]) but this involves creating a list which again seems more expensive that just calling np.max.
Is there any way to slice a with idx in numpy without restructuring the array?
A:
Your a and argmax:
In [602]: a
Out[602]:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17],
[18, 19, 20],
[21, 22, 23],
[24, 25, 26]])
In [603]: idx
Out[603]: array([2, 2, 2, 2, 2, 2, 2, 2, 2], dtype=int64)
A common way of using that index array:
In [606]: a[np.arange(a.shape[0]),idx]
Out[606]: array([ 2, 5, 8, 11, 14, 17, 20, 23, 26])
A newer tool, that may be easier to use (if not familiar with the first):
In [607]: np.take_along_axis(a,idx[:,None],1)
Out[607]:
array([[ 2],
[ 5],
[ 8],
[11],
[14],
[17],
[20],
[23],
[26]])
|
Slice of 2d numpy array with another array
|
I have a quite large 2d array, and I need to get both the index of the maximum value in axis 1, and the maximum value itself. I can retrieve these two values as follows:
import numpy as np
a = np.arange(27).reshape(9, 3)
idx = np.argmax(a, axis=1)
max_val = np.max(a, axis=1)
However, since I have already found the index of the maximum value, it feels like I should be able to construct the array of maximum values using idx without having to look up the value again.
I realise I can use np.choose(idx, a.T) but this involves transposing the matrix which will be much more expensive than just using max. I can do something like np.array([a[i][idx[i]] for i in range(len(a))]) but this involves creating a list which again seems more expensive that just calling np.max.
Is there any way to slice a with idx in numpy without restructuring the array?
|
[
"Your a and argmax:\nIn [602]: a\nOut[602]: \narray([[ 0, 1, 2],\n [ 3, 4, 5],\n [ 6, 7, 8],\n [ 9, 10, 11],\n [12, 13, 14],\n [15, 16, 17],\n [18, 19, 20],\n [21, 22, 23],\n [24, 25, 26]])\n\nIn [603]: idx\nOut[603]: array([2, 2, 2, 2, 2, 2, 2, 2, 2], dtype=int64)\n\nA common way of using that index array:\nIn [606]: a[np.arange(a.shape[0]),idx]\nOut[606]: array([ 2, 5, 8, 11, 14, 17, 20, 23, 26])\n\nA newer tool, that may be easier to use (if not familiar with the first):\nIn [607]: np.take_along_axis(a,idx[:,None],1)\nOut[607]: \narray([[ 2],\n [ 5],\n [ 8],\n [11],\n [14],\n [17],\n [20],\n [23],\n [26]])\n\n"
] |
[
1
] |
[] |
[] |
[
"arrays",
"numpy",
"performance",
"python"
] |
stackoverflow_0074495151_arrays_numpy_performance_python.txt
|
Q:
discord.py get server id with on_ready() function
I want to load some information about a server from a json file, each server is identified within this file by its guild.id.
However if I want to try and load some data at the start with on_ready(), I cant use ctx, which I need to get the current servers guild.id, so I can identify it within the file.
(sorry if that's a bad explanation but just look at line 6 of my code and you'll understand what I'm trying to do)
Here is my current code:
@bot.event
async def on_ready():
with open("server_info.json", "r") as infoRaw:
infoJson = json.load(infoRaw)
for server in infoJson["Servers"]: #search each server data
if (server["id"] == ctx.message.guild.id): #compare id in file to current id (error line)
data = server[data]
break
I cant find any other ways online of getting the the servers id without a user sending a message first.
A:
You can use discord.utils, which would look like the following:
guild = discord.utils.get(bot.guilds, id=378473289473829)
You can use what every ID you want, just be sure to replace bot with the name of your Client instance.
This works in on_ready, without any ctx
A:
You could use bot.guilds which is a list of all guilds the bot is in and then check if the ID matches with an extra loop
|
discord.py get server id with on_ready() function
|
I want to load some information about a server from a json file, each server is identified within this file by its guild.id.
However if I want to try and load some data at the start with on_ready(), I cant use ctx, which I need to get the current servers guild.id, so I can identify it within the file.
(sorry if that's a bad explanation but just look at line 6 of my code and you'll understand what I'm trying to do)
Here is my current code:
@bot.event
async def on_ready():
with open("server_info.json", "r") as infoRaw:
infoJson = json.load(infoRaw)
for server in infoJson["Servers"]: #search each server data
if (server["id"] == ctx.message.guild.id): #compare id in file to current id (error line)
data = server[data]
break
I cant find any other ways online of getting the the servers id without a user sending a message first.
|
[
"You can use discord.utils, which would look like the following:\nguild = discord.utils.get(bot.guilds, id=378473289473829)\n\nYou can use what every ID you want, just be sure to replace bot with the name of your Client instance.\nThis works in on_ready, without any ctx\n",
"You could use bot.guilds which is a list of all guilds the bot is in and then check if the ID matches with an extra loop\n"
] |
[
2,
1
] |
[] |
[] |
[
"discord",
"discord.py",
"python",
"python_3.x"
] |
stackoverflow_0074493134_discord_discord.py_python_python_3.x.txt
|
Q:
Recursive function to check if a given number is Fibonacci
I'm new to python and I'm am having problems building a recursive function that checks if a given number is a Fibonacci number.
This is my code.
def isFib(n):
if n <= 1:
return n
else:
return (n - 1) + (n - 2)
if isFib(n) == 1 or isFib(n) == isFib(n - 1) + isFib(n - 2):
return True
It should print True in both cases, but instead it print True and False, and I can't find what's wrong
print(all([isFib(i) for i in [1,2,3,5,8,13,21,34,55]]))
print(all([not isFib(2*i) for i in [1,2,3,5,8,13,21,34,55]]))
A:
The first part of your function is an if statement. If True, it returns a value - if False, it also returns a value. So, the second part of your function cannot possible execute, and the function isn't recursive (since you don't call the function again in either return statement).
More generally, what you're doing will never work. The logic seems to be: "a Fibonacci number is the sum of the previous Fibonacci number and the number before that, so I can reverse that logic by computing n - 1 and n - 2 and if they are Fibonacci numbers, then so is n" - or something like that.
But that doesn't work: 5 is a Fibonacci number, but (5-1) is not, so the logic breaks right there. If you were thinking only the sum needed to be a Fibonacci number: 13 is a Fibonacci number, but (13-1) + (13-2) = 23 and that's not a Fibonacci number either.
An easy way to solve this would be to just generate a Fibonacci sequence and return True as soon as the number you're checking comes up:
def is_fib(n, seq=None):
if seq is None:
seq = [0, 1]
# n is Fibonacci if the last number in the sequence is
# or if the last number has not yet past n, then compute the next and try again
return n == seq[-1] or (seq[-1] < n and is_fib(n, seq + [seq[-2] + seq[-1]]))
print([is_fib(i) for i in [1,2,3,5,8,13,21,34,55]])
print(is_fib(23))
|
Recursive function to check if a given number is Fibonacci
|
I'm new to python and I'm am having problems building a recursive function that checks if a given number is a Fibonacci number.
This is my code.
def isFib(n):
if n <= 1:
return n
else:
return (n - 1) + (n - 2)
if isFib(n) == 1 or isFib(n) == isFib(n - 1) + isFib(n - 2):
return True
It should print True in both cases, but instead it print True and False, and I can't find what's wrong
print(all([isFib(i) for i in [1,2,3,5,8,13,21,34,55]]))
print(all([not isFib(2*i) for i in [1,2,3,5,8,13,21,34,55]]))
|
[
"The first part of your function is an if statement. If True, it returns a value - if False, it also returns a value. So, the second part of your function cannot possible execute, and the function isn't recursive (since you don't call the function again in either return statement).\nMore generally, what you're doing will never work. The logic seems to be: \"a Fibonacci number is the sum of the previous Fibonacci number and the number before that, so I can reverse that logic by computing n - 1 and n - 2 and if they are Fibonacci numbers, then so is n\" - or something like that.\nBut that doesn't work: 5 is a Fibonacci number, but (5-1) is not, so the logic breaks right there. If you were thinking only the sum needed to be a Fibonacci number: 13 is a Fibonacci number, but (13-1) + (13-2) = 23 and that's not a Fibonacci number either.\nAn easy way to solve this would be to just generate a Fibonacci sequence and return True as soon as the number you're checking comes up:\ndef is_fib(n, seq=None):\n if seq is None:\n seq = [0, 1]\n # n is Fibonacci if the last number in the sequence is\n # or if the last number has not yet past n, then compute the next and try again\n return n == seq[-1] or (seq[-1] < n and is_fib(n, seq + [seq[-2] + seq[-1]]))\n\n\nprint([is_fib(i) for i in [1,2,3,5,8,13,21,34,55]])\nprint(is_fib(23))\n\n"
] |
[
2
] |
[] |
[] |
[
"fibonacci",
"function",
"python",
"recursion"
] |
stackoverflow_0074495255_fibonacci_function_python_recursion.txt
|
Q:
Error on installing pyqt5(pip install pyqt5)
I have installed pyqt5 once on another pc.
I am trying to install pyqt5 on my notebook.
My notebook specs are:
64bit AMD Ryzen 7 5800H
MS Windows 10 Pro
I tried :
> pip install pyqt5
on cmd
and had error:
Using cached PyQt5-5.15.6.tar.gz (3.2 MB)
Installing build dependencies ... error
error: subprocess-exited-with-error
× pip subprocess to install build dependencies did not run successfully.
│ exit code: 1
╰─> [140 lines of output]
Collecting sip<7,>=6.4
Using cached sip-6.6.1.tar.gz (1.1 MB)
Installing build dependencies: started
Installing build dependencies: finished with status 'done'
Getting requirements to build wheel: started
Getting requirements to build wheel: finished with status 'done'
Preparing metadata (pyproject.toml): started
Preparing metadata (pyproject.toml): finished with status 'done'
Collecting PyQt-builder<2,>=1.9
Using cached PyQt_builder-1.12.2-py3-none-any.whl (5.6 MB)
Collecting ply
Using cached ply-3.11-py2.py3-none-any.whl (49 kB)
Collecting toml
Using cached toml-0.10.2-py2.py3-none-any.whl (16 kB)
Collecting packaging
Using cached packaging-21.3-py3-none-any.whl (40 kB)
Collecting setuptools
Using cached setuptools-62.3.2-py3-none-any.whl (1.2 MB)
Collecting pyparsing!=3.0.5,>=2.0.2
Using cached pyparsing-3.0.9-py3-none-any.whl (98 kB)
Building wheels for collected packages: sip
Building wheel for sip (pyproject.toml): started
Building wheel for sip (pyproject.toml): finished with status 'error'
error: subprocess-exited-with-error
Building wheel for sip (pyproject.toml) did not run successfully.
exit code: 1
[105 lines of output]
running bdist_wheel
running build
running build_py
creating build
creating build\lib.mingw_x86_64_clang-cpython-39
creating build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\abstract_builder.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\abstract_project.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\api.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\argument_parser.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\bindings.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\bindings_configuration.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\buildable.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\builder.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\configurable.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\distutils_builder.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\exceptions.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\installable.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\project.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\pyproject.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\py_versions.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\setuptools_builder.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\version.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\__init__.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
creating build\lib.mingw_x86_64_clang-cpython-39\sipbuild\distinfo
copying sipbuild\distinfo\distinfo.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\distinfo
copying sipbuild\distinfo\main.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\distinfo
copying sipbuild\distinfo\__init__.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\distinfo
creating build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator
copying sipbuild\generator\python_slots.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator
copying sipbuild\generator\specification.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator
copying sipbuild\generator\templates.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator
copying sipbuild\generator\utils.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator
copying sipbuild\generator\__init__.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator
creating build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module
copying sipbuild\module\abi_version.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module
copying sipbuild\module\main.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module
copying sipbuild\module\module.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module
copying sipbuild\module\__init__.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module
creating build\lib.mingw_x86_64_clang-cpython-39\sipbuild\tools
copying sipbuild\tools\build.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\tools
copying sipbuild\tools\install.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\tools
copying sipbuild\tools\sdist.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\tools
copying sipbuild\tools\wheel.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\tools
copying sipbuild\tools\__init__.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\tools
creating build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator\parser
copying sipbuild\generator\parser\annotations.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator\parser
copying sipbuild\generator\parser\instantiations.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator\parser
copying sipbuild\generator\parser\parser.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator\parser
copying sipbuild\generator\parser\parser_manager.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator\parser
copying sipbuild\generator\parser\parsetab.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator\parser
copying sipbuild\generator\parser\python_exceptions.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator\parser
copying sipbuild\generator\parser\rules.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator\parser
copying sipbuild\generator\parser\tokens.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator\parser
copying sipbuild\generator\parser\__init__.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator\parser
creating build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source
creating build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\apiversions.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\array.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\array.h -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\bool.cpp -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\descriptors.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\int_convertors.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\LICENSE -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\LICENSE-GPL2 -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\LICENSE-GPL3 -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\MANIFEST.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\objmap.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\pyproject.toml -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\qtlib.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\README.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\setup.cfg.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\setup.py.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\sip.h.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\sip.pyi -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\sip.rst.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\sipint.h -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\siplib.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\threads.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\voidptr.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
creating build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\array.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\array.h -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\bool.cpp -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\descriptors.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\int_convertors.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\LICENSE -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\LICENSE-GPL2 -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\LICENSE-GPL3 -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\MANIFEST.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\objmap.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\pyproject.toml -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\README.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\setup.cfg.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\setup.py.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\sip.h.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\sip.pyi -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\sip.rst.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\sipint.h -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\siplib.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\threads.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\voidptr.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
running build_ext
building 'sipbuild.code_generator' extension
error: --plat-name must be one of ('win32', 'win-amd64', 'win-arm32', 'win-arm64')
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for sip
Failed to build sip
ERROR: Could not build wheels for sip, which is required to install pyproject.toml-based projects
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error
× pip subprocess to install build dependencies did not run successfully.
│ exit code: 1
╰─> See above for output.
note: This error originates from a subprocess, and is likely not a problem with pip.
I searched for this error and tried several solutions:
> pip install --user --upgrade pip
> pip install pyqt5
> pip3 install pyqt5
> python3 -m pip install PyQt5
> python -m pip install --upgrade pip
> python -m pip install pyqt5
Also, I read the article that my python version is 3.10 or higher may cause problems, so I tried reinstalling the python version to 3.9.
The above solution doesn't seem to solve the problem
A:
I was able to solve the problem by installing the latest Python version 3.10.5, updating pip alone did not help. I was using Python 3.8.9 before that.
A:
You may have python installed somewhere else on your computer that isn't the latest version and your system environment variables is pointing to that. Make sure there isn't a Python installation in another program or library. For example, I had a python installation in MSYS2 and once I uninstalled it from my computer it installed.
A:
For me installing version 5.12.2 of PyQt5 solved the issues.
pip install PyQt5==5.12.2
Pip install PyQtWebEngine==5.12
|
Error on installing pyqt5(pip install pyqt5)
|
I have installed pyqt5 once on another pc.
I am trying to install pyqt5 on my notebook.
My notebook specs are:
64bit AMD Ryzen 7 5800H
MS Windows 10 Pro
I tried :
> pip install pyqt5
on cmd
and had error:
Using cached PyQt5-5.15.6.tar.gz (3.2 MB)
Installing build dependencies ... error
error: subprocess-exited-with-error
× pip subprocess to install build dependencies did not run successfully.
│ exit code: 1
╰─> [140 lines of output]
Collecting sip<7,>=6.4
Using cached sip-6.6.1.tar.gz (1.1 MB)
Installing build dependencies: started
Installing build dependencies: finished with status 'done'
Getting requirements to build wheel: started
Getting requirements to build wheel: finished with status 'done'
Preparing metadata (pyproject.toml): started
Preparing metadata (pyproject.toml): finished with status 'done'
Collecting PyQt-builder<2,>=1.9
Using cached PyQt_builder-1.12.2-py3-none-any.whl (5.6 MB)
Collecting ply
Using cached ply-3.11-py2.py3-none-any.whl (49 kB)
Collecting toml
Using cached toml-0.10.2-py2.py3-none-any.whl (16 kB)
Collecting packaging
Using cached packaging-21.3-py3-none-any.whl (40 kB)
Collecting setuptools
Using cached setuptools-62.3.2-py3-none-any.whl (1.2 MB)
Collecting pyparsing!=3.0.5,>=2.0.2
Using cached pyparsing-3.0.9-py3-none-any.whl (98 kB)
Building wheels for collected packages: sip
Building wheel for sip (pyproject.toml): started
Building wheel for sip (pyproject.toml): finished with status 'error'
error: subprocess-exited-with-error
Building wheel for sip (pyproject.toml) did not run successfully.
exit code: 1
[105 lines of output]
running bdist_wheel
running build
running build_py
creating build
creating build\lib.mingw_x86_64_clang-cpython-39
creating build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\abstract_builder.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\abstract_project.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\api.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\argument_parser.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\bindings.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\bindings_configuration.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\buildable.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\builder.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\configurable.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\distutils_builder.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\exceptions.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\installable.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\project.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\pyproject.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\py_versions.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\setuptools_builder.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\version.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
copying sipbuild\__init__.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild
creating build\lib.mingw_x86_64_clang-cpython-39\sipbuild\distinfo
copying sipbuild\distinfo\distinfo.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\distinfo
copying sipbuild\distinfo\main.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\distinfo
copying sipbuild\distinfo\__init__.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\distinfo
creating build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator
copying sipbuild\generator\python_slots.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator
copying sipbuild\generator\specification.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator
copying sipbuild\generator\templates.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator
copying sipbuild\generator\utils.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator
copying sipbuild\generator\__init__.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator
creating build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module
copying sipbuild\module\abi_version.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module
copying sipbuild\module\main.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module
copying sipbuild\module\module.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module
copying sipbuild\module\__init__.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module
creating build\lib.mingw_x86_64_clang-cpython-39\sipbuild\tools
copying sipbuild\tools\build.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\tools
copying sipbuild\tools\install.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\tools
copying sipbuild\tools\sdist.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\tools
copying sipbuild\tools\wheel.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\tools
copying sipbuild\tools\__init__.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\tools
creating build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator\parser
copying sipbuild\generator\parser\annotations.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator\parser
copying sipbuild\generator\parser\instantiations.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator\parser
copying sipbuild\generator\parser\parser.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator\parser
copying sipbuild\generator\parser\parser_manager.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator\parser
copying sipbuild\generator\parser\parsetab.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator\parser
copying sipbuild\generator\parser\python_exceptions.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator\parser
copying sipbuild\generator\parser\rules.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator\parser
copying sipbuild\generator\parser\tokens.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator\parser
copying sipbuild\generator\parser\__init__.py -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\generator\parser
creating build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source
creating build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\apiversions.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\array.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\array.h -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\bool.cpp -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\descriptors.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\int_convertors.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\LICENSE -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\LICENSE-GPL2 -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\LICENSE-GPL3 -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\MANIFEST.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\objmap.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\pyproject.toml -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\qtlib.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\README.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\setup.cfg.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\setup.py.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\sip.h.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\sip.pyi -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\sip.rst.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\sipint.h -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\siplib.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\threads.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
copying sipbuild\module\source\12\voidptr.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\12
creating build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\array.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\array.h -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\bool.cpp -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\descriptors.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\int_convertors.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\LICENSE -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\LICENSE-GPL2 -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\LICENSE-GPL3 -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\MANIFEST.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\objmap.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\pyproject.toml -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\README.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\setup.cfg.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\setup.py.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\sip.h.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\sip.pyi -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\sip.rst.in -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\sipint.h -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\siplib.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\threads.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
copying sipbuild\module\source\13\voidptr.c -> build\lib.mingw_x86_64_clang-cpython-39\sipbuild\module\source\13
running build_ext
building 'sipbuild.code_generator' extension
error: --plat-name must be one of ('win32', 'win-amd64', 'win-arm32', 'win-arm64')
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for sip
Failed to build sip
ERROR: Could not build wheels for sip, which is required to install pyproject.toml-based projects
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error
× pip subprocess to install build dependencies did not run successfully.
│ exit code: 1
╰─> See above for output.
note: This error originates from a subprocess, and is likely not a problem with pip.
I searched for this error and tried several solutions:
> pip install --user --upgrade pip
> pip install pyqt5
> pip3 install pyqt5
> python3 -m pip install PyQt5
> python -m pip install --upgrade pip
> python -m pip install pyqt5
Also, I read the article that my python version is 3.10 or higher may cause problems, so I tried reinstalling the python version to 3.9.
The above solution doesn't seem to solve the problem
|
[
"I was able to solve the problem by installing the latest Python version 3.10.5, updating pip alone did not help. I was using Python 3.8.9 before that.\n",
"You may have python installed somewhere else on your computer that isn't the latest version and your system environment variables is pointing to that. Make sure there isn't a Python installation in another program or library. For example, I had a python installation in MSYS2 and once I uninstalled it from my computer it installed.\n",
"For me installing version 5.12.2 of PyQt5 solved the issues.\npip install PyQt5==5.12.2\nPip install PyQtWebEngine==5.12\n\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"pip",
"pyqt",
"pyqt5",
"python"
] |
stackoverflow_0072424212_pip_pyqt_pyqt5_python.txt
|
Q:
How to handle duplicate messages in Kafka
I know duplicate messages can produce on both the producer side and the consumer side.
And I also know, Kafka deduplicates messages on the producer side by enabling idempotency.
But how about the consumer side?
I see two different solutions:
Writing idempotent consumer if possible
Keep the message ID in the consumer's database to ignore duplicate messages.
The first solution is not possible in my case, and the second one does not have benefits.
For example, we have the following code:
message = consumer.poll()
save_order(message.order)
consumer.commit()
And after implementing the second solution we change the code like this:
message = consumer.poll()
if is_duplicate(message.id):
return
save_order(message.order)
save_message_id(message.id)
consumer.commit()
Ok, now nothing goes wrong if the consumer crashes before consumer.commit(). But wait, what happens if the consumer crashes before save_message_id(message.id)?
I think we gain nothing!
Of course, we can use transactions to ensure save_order() and save_message_id() are done atomically, but we don't have this option in some cases (for example if we need to just call an API in the consumer without any database operation).
Is there any other option? How do big companies handle this? Why we don't see duplicate transactions in the banks?
A:
As Paweł Szymczyk and OneCricketeer said in the comments, we should use the Transactional Outbox pattern in these cases.
Using this pattern we can even convert non-database operations to database operations too.
For example, we can use the Transactional Outbox pattern to trigger another event that calls an API instead of calling it directly.
|
How to handle duplicate messages in Kafka
|
I know duplicate messages can produce on both the producer side and the consumer side.
And I also know, Kafka deduplicates messages on the producer side by enabling idempotency.
But how about the consumer side?
I see two different solutions:
Writing idempotent consumer if possible
Keep the message ID in the consumer's database to ignore duplicate messages.
The first solution is not possible in my case, and the second one does not have benefits.
For example, we have the following code:
message = consumer.poll()
save_order(message.order)
consumer.commit()
And after implementing the second solution we change the code like this:
message = consumer.poll()
if is_duplicate(message.id):
return
save_order(message.order)
save_message_id(message.id)
consumer.commit()
Ok, now nothing goes wrong if the consumer crashes before consumer.commit(). But wait, what happens if the consumer crashes before save_message_id(message.id)?
I think we gain nothing!
Of course, we can use transactions to ensure save_order() and save_message_id() are done atomically, but we don't have this option in some cases (for example if we need to just call an API in the consumer without any database operation).
Is there any other option? How do big companies handle this? Why we don't see duplicate transactions in the banks?
|
[
"As Paweł Szymczyk and OneCricketeer said in the comments, we should use the Transactional Outbox pattern in these cases.\nUsing this pattern we can even convert non-database operations to database operations too.\nFor example, we can use the Transactional Outbox pattern to trigger another event that calls an API instead of calling it directly.\n"
] |
[
0
] |
[] |
[] |
[
"apache_kafka",
"python"
] |
stackoverflow_0074483533_apache_kafka_python.txt
|
Q:
AWS CodeArtifact error with 401 Unauthorized when trying to upload with twine
I'm having issues pushing python package into CodeArtifact using twine. I would love your ideas on what this might be and how to debug this.
I've setup the repository following this doc.
Running aws codeartifact login --tool twine is successful and I see the password updated in the ~/.pypirc file:
$ aws codeartifact login --tool twine --repository myrepo --domain mydomain --domain-owner 111122223333 --region us-east-1 --profile myprofile
Successfully configured twine to use AWS CodeArtifact repository https://mydomain-111122223333.d.codeartifact.us-east-1.amazonaws.com/pypi/myrepo/
Login expires in 12 hours at 2022-11-03 06:52:46-04:00
but then when I try to upload I get an unauthorized error:
$ twine upload --verbose --repository myrepo ./dist/mylib-0.0.2.tar.gz
INFO Using configuration from ~/.pypirc
Uploading distributions to https://mydomain-111122223333.d.codeartifact.us-east-1.amazonaws.com/pypi/myrepo/
INFO ./dist/mylib-0.0.2.tar.gz (7.8 KB)
INFO username set by command options
INFO password set by command options
INFO username: aws
INFO password: <hidden>
Uploading mylib-0.0.2.tar.gz
100% ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 13.3/13.3 kB • 00:00 • 26.8 MB/s
INFO Response from https://mydomain-111122223333.d.codeartifact.us-east-1.amazonaws.com/pypi/myrepo/:
401 Unauthorized
INFO Unauthenticated: request used expired credentials. Please renew your credentials.
ERROR HTTPError: 401 Unauthorized from https://mydomain-111122223333.d.codeartifact.us-east-1.amazonaws.com/pypi/myrepo/
Unauthorized
What do you think?
A:
As a workaround, I created a new repository and migrated to it. After a while deleted the problematic repository. Never got to the bottom of this.
|
AWS CodeArtifact error with 401 Unauthorized when trying to upload with twine
|
I'm having issues pushing python package into CodeArtifact using twine. I would love your ideas on what this might be and how to debug this.
I've setup the repository following this doc.
Running aws codeartifact login --tool twine is successful and I see the password updated in the ~/.pypirc file:
$ aws codeartifact login --tool twine --repository myrepo --domain mydomain --domain-owner 111122223333 --region us-east-1 --profile myprofile
Successfully configured twine to use AWS CodeArtifact repository https://mydomain-111122223333.d.codeartifact.us-east-1.amazonaws.com/pypi/myrepo/
Login expires in 12 hours at 2022-11-03 06:52:46-04:00
but then when I try to upload I get an unauthorized error:
$ twine upload --verbose --repository myrepo ./dist/mylib-0.0.2.tar.gz
INFO Using configuration from ~/.pypirc
Uploading distributions to https://mydomain-111122223333.d.codeartifact.us-east-1.amazonaws.com/pypi/myrepo/
INFO ./dist/mylib-0.0.2.tar.gz (7.8 KB)
INFO username set by command options
INFO password set by command options
INFO username: aws
INFO password: <hidden>
Uploading mylib-0.0.2.tar.gz
100% ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 13.3/13.3 kB • 00:00 • 26.8 MB/s
INFO Response from https://mydomain-111122223333.d.codeartifact.us-east-1.amazonaws.com/pypi/myrepo/:
401 Unauthorized
INFO Unauthenticated: request used expired credentials. Please renew your credentials.
ERROR HTTPError: 401 Unauthorized from https://mydomain-111122223333.d.codeartifact.us-east-1.amazonaws.com/pypi/myrepo/
Unauthorized
What do you think?
|
[
"As a workaround, I created a new repository and migrated to it. After a while deleted the problematic repository. Never got to the bottom of this.\n"
] |
[
0
] |
[] |
[] |
[
"amazon_web_services",
"aws_cli",
"aws_codeartifact",
"python",
"twine"
] |
stackoverflow_0074296513_amazon_web_services_aws_cli_aws_codeartifact_python_twine.txt
|
Q:
Python runs on terminal, not on web browser
I'm trying to run a simple python script on my webserver, but it's not showing up in the web browser.
In terminal I check if python is installed:
whereis python
python: /usr/bin/python2.7 /usr/bin/python2.7-config /usr/bin/python /usr/lib/python2.7 /usr/lib64/python2.7 /etc/python /usr/local/bin/python3.9-config /usr/local/bin/python3.9 /usr/local/lib/python3.9 /usr/include/python2.7 /opt/imh-python/bin/python2.7 /opt/imh-python/bin/python2.7-config /opt/imh-python/bin/python3.9 /opt/imh-python/bin/python /usr/share/man/man1/python.1.gz
This tells me that I have python installed. I created a simple file that contains this code:
#! /usr/bin/python
print('Content-Type: text/html\r\n\r\n')
print('\r\n')
print('Hello World')
I ran dos2unix and chmod a+x on the file.
I ran the file in terminal and get this output:
Content-Type: text/html
Hello World
When I try to open the file in the web browser this is the output I get:
#! /usr/bin/python
print('Content-Type: text/html\r\n\r\n')
print('\r\n')
print('Hello World')
I changed the single quotes in the print statement to double. I tried different ways of entering new lines, but nothing seems to work. Am I missing or overlooking something crucial here?
A:
The browser doesn't have a Python interpreter. So opening the file in a browser is just going to show your source code. If you want it to show on a browser you need to run it on a server where it can be interpreted. A simple solution is to use Flask, which comes with a development server. Once you've installed flask:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello World'
app.run()
Then navigate to http://localhost:5000 in your browser.
|
Python runs on terminal, not on web browser
|
I'm trying to run a simple python script on my webserver, but it's not showing up in the web browser.
In terminal I check if python is installed:
whereis python
python: /usr/bin/python2.7 /usr/bin/python2.7-config /usr/bin/python /usr/lib/python2.7 /usr/lib64/python2.7 /etc/python /usr/local/bin/python3.9-config /usr/local/bin/python3.9 /usr/local/lib/python3.9 /usr/include/python2.7 /opt/imh-python/bin/python2.7 /opt/imh-python/bin/python2.7-config /opt/imh-python/bin/python3.9 /opt/imh-python/bin/python /usr/share/man/man1/python.1.gz
This tells me that I have python installed. I created a simple file that contains this code:
#! /usr/bin/python
print('Content-Type: text/html\r\n\r\n')
print('\r\n')
print('Hello World')
I ran dos2unix and chmod a+x on the file.
I ran the file in terminal and get this output:
Content-Type: text/html
Hello World
When I try to open the file in the web browser this is the output I get:
#! /usr/bin/python
print('Content-Type: text/html\r\n\r\n')
print('\r\n')
print('Hello World')
I changed the single quotes in the print statement to double. I tried different ways of entering new lines, but nothing seems to work. Am I missing or overlooking something crucial here?
|
[
"The browser doesn't have a Python interpreter. So opening the file in a browser is just going to show your source code. If you want it to show on a browser you need to run it on a server where it can be interpreted. A simple solution is to use Flask, which comes with a development server. Once you've installed flask:\nfrom flask import Flask\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef hello():\n return 'Hello World'\n\n\napp.run()\n\nThen navigate to http://localhost:5000 in your browser.\n"
] |
[
1
] |
[] |
[] |
[
"html",
"python",
"python_2.7",
"web"
] |
stackoverflow_0074495234_html_python_python_2.7_web.txt
|
Q:
How do I type the `__prepare__` method for a metaclass?
I’m trying to write a simple metaclass that intercepts every function declaration and replaces it with a dummy function:
from dataclasses import dataclass
from typing import Any, Mapping
@dataclass
class DummyCall:
args: tuple[Any, ...]
kwargs: dict[str, Any]
def _dummy_function(*args: Any, **kwargs: Any) -> DummyCall:
return DummyCall(args, kwargs)
class _dummy_dict(dict[str, Any]):
def __setitem__(self, key: str, value: Any) -> None:
if callable(value):
super().__setitem__(key, _dummy_function)
else:
super().__setitem__(key, value)
class dummy(type):
@classmethod
def __prepare__(metcls, name, bases, **kwds):
return _dummy_dict()
I now want to type-hint the __prepare__ method. I’ve tried the following:
def __prepare__(*_, *__): …
…but of course this doesn’t work. From the error I got I tried to reconstruct the type, and ended up with the following:
def __prepare__(metcls: Any, name: str, bases: tuple[type, ...], **kwds: Any) -> Mapping[str, Any]: …
Unfortunately, this still doesn’t satisfy MyPy. I get the following error:
error: Signature of "__prepare__" incompatible with supertype "type"
note: Superclass:
note: def __prepare__(metacls, str, Tuple[type, ...], **kwds: Any) -> Mapping[str, object]
note: Subclass:
note: @classmethod
note: def __prepare__(metcls, name: str, bases: Tuple[type, ...], **kwds: Any) -> Mapping[str, Any]
I also interestingly get different errors in my code editor with a MyPy plugin:
Signature of "__prepare__" incompatible with supertype "type"mypy
Superclass:mypy
@classmethodmypy
def __prepare__(metacls, str, Tuple[type, ...], **kwds: Any) -> Mapping[str, object]mypy
Subclass:mypy
@classmethodmypy
def __prepare__(metcls, name: str, bases: Tuple[type, ...], **kwds: Any) -> Mapping[str, Any]mypy
Here, it is reported that the superclass definition is annotated with @classmethod, while the command-line mypy doesn’t say this.
A:
The reason was that I didn’t use the exact same argument names as in the .pyi file.
This works:
@classmethod
def __prepare__(metacls, __name: str, __bases: tuple[type, ...], **kwds: Any) -> Mapping[str, object]:
…
Interestingly, the type doesn’t need to match exactly. I was able to use tuple instead of Tuple in the typestub.
|
How do I type the `__prepare__` method for a metaclass?
|
I’m trying to write a simple metaclass that intercepts every function declaration and replaces it with a dummy function:
from dataclasses import dataclass
from typing import Any, Mapping
@dataclass
class DummyCall:
args: tuple[Any, ...]
kwargs: dict[str, Any]
def _dummy_function(*args: Any, **kwargs: Any) -> DummyCall:
return DummyCall(args, kwargs)
class _dummy_dict(dict[str, Any]):
def __setitem__(self, key: str, value: Any) -> None:
if callable(value):
super().__setitem__(key, _dummy_function)
else:
super().__setitem__(key, value)
class dummy(type):
@classmethod
def __prepare__(metcls, name, bases, **kwds):
return _dummy_dict()
I now want to type-hint the __prepare__ method. I’ve tried the following:
def __prepare__(*_, *__): …
…but of course this doesn’t work. From the error I got I tried to reconstruct the type, and ended up with the following:
def __prepare__(metcls: Any, name: str, bases: tuple[type, ...], **kwds: Any) -> Mapping[str, Any]: …
Unfortunately, this still doesn’t satisfy MyPy. I get the following error:
error: Signature of "__prepare__" incompatible with supertype "type"
note: Superclass:
note: def __prepare__(metacls, str, Tuple[type, ...], **kwds: Any) -> Mapping[str, object]
note: Subclass:
note: @classmethod
note: def __prepare__(metcls, name: str, bases: Tuple[type, ...], **kwds: Any) -> Mapping[str, Any]
I also interestingly get different errors in my code editor with a MyPy plugin:
Signature of "__prepare__" incompatible with supertype "type"mypy
Superclass:mypy
@classmethodmypy
def __prepare__(metacls, str, Tuple[type, ...], **kwds: Any) -> Mapping[str, object]mypy
Subclass:mypy
@classmethodmypy
def __prepare__(metcls, name: str, bases: Tuple[type, ...], **kwds: Any) -> Mapping[str, Any]mypy
Here, it is reported that the superclass definition is annotated with @classmethod, while the command-line mypy doesn’t say this.
|
[
"The reason was that I didn’t use the exact same argument names as in the .pyi file.\nThis works:\n@classmethod\ndef __prepare__(metacls, __name: str, __bases: tuple[type, ...], **kwds: Any) -> Mapping[str, object]:\n …\n\nInterestingly, the type doesn’t need to match exactly. I was able to use tuple instead of Tuple in the typestub.\n"
] |
[
1
] |
[] |
[] |
[
"mypy",
"python",
"type_hinting"
] |
stackoverflow_0074495312_mypy_python_type_hinting.txt
|
Q:
How to change a Label text on another screen by pressing a Button Python Kivy
How can I change the value of text in Label on the 2nd screen by pressing a Button on the 1st screen?
In my example, I have 2 screens, on the first there are 3 buttons; one should change the text to "1st text", second should change the text to "2nd text" and the third is used to move between these two screens.
On the second screen, there is a Label which text should be changed by pressing the buttons. Then, there is also the button used to move to the first screen.
My .py looks like:
import kivy
kivy.require("1.10.1")
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.app import App
class Screen1(Screen):
pass
class Screen2(Screen):
pass
class Select_text(App):
def build(self):
sm = ScreenManager(transition=FadeTransition())
sm.add_widget(Screen1(name = "scr1"))
sm.add_widget(Screen2(name = "scr2"))
return sm
app = Select_text()
app.run()
My .kv seems like:
<Screen1>:
id: scr1
orientation: "vertical"
canvas.before:
Rectangle:
pos: self.pos
size: self.size
source: "Background.png"
Button:
id: change_to_1
pos: (root.width-self.width)/2, 400
size: 1200, 200
size_hint: None, None
text: "Change the text on the 2nd screen to »1st text«"
#on_press: (I don‘t know what should be there)
Button:
id: change_to_2
pos: (root.width-self.width)/2, 800
size: 1200, 200
size_hint: None, None
text: "Change the text on the 2nd screen to »2nd text«"
#on_press: (I don‘t know what should be there)
Button:
id: go_to_other_screen
pos: (root.width-self.width)/2, 1400
size: 600, 200
size_hint: None, None
text: "Go to other screen"
on_press: root.manager.current = "scr2"
<Screen2>:
id: scr2
orientation: "vertical"
canvas.before:
Rectangle:
pos: self.pos
size: self.size
source: "Background.png"
Label:
id: text
text: "Text which should be changed"
pos: (root.width-self.width)/2, 800
size: 600, 200
Button:
id: go_to_other_screen
pos: (root.width-self.width)/2, 1400
size: 600, 200
size_hint: None, None
text: "Go to other screen"
on_press: root.manager.current = "scr1"
I tried to search on the internet, but it didn't solve the main issue.
Thanks for any answer.
A:
In the kv file call a function in the screen 1 class. You can then use the get_screen function to access the other screen and change its text in that function.
Would probably look something like:
(in the kv file)
on_press: root.functionname()
(main python file)
def functionname(self):
self.manager.get_screen('scr2').ids.text.text = "whatever you want here"
May i also suggest changing the id of the text ur changing to something else, because it looks a bit confusing with ids.text.text
For more info about the get_screen function if you are confused about that https://medium.com/nerd-for-tech/kivy-use-get-screen-to-access-objects-from-other-screens-8d4d6f288f3
|
How to change a Label text on another screen by pressing a Button Python Kivy
|
How can I change the value of text in Label on the 2nd screen by pressing a Button on the 1st screen?
In my example, I have 2 screens, on the first there are 3 buttons; one should change the text to "1st text", second should change the text to "2nd text" and the third is used to move between these two screens.
On the second screen, there is a Label which text should be changed by pressing the buttons. Then, there is also the button used to move to the first screen.
My .py looks like:
import kivy
kivy.require("1.10.1")
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.app import App
class Screen1(Screen):
pass
class Screen2(Screen):
pass
class Select_text(App):
def build(self):
sm = ScreenManager(transition=FadeTransition())
sm.add_widget(Screen1(name = "scr1"))
sm.add_widget(Screen2(name = "scr2"))
return sm
app = Select_text()
app.run()
My .kv seems like:
<Screen1>:
id: scr1
orientation: "vertical"
canvas.before:
Rectangle:
pos: self.pos
size: self.size
source: "Background.png"
Button:
id: change_to_1
pos: (root.width-self.width)/2, 400
size: 1200, 200
size_hint: None, None
text: "Change the text on the 2nd screen to »1st text«"
#on_press: (I don‘t know what should be there)
Button:
id: change_to_2
pos: (root.width-self.width)/2, 800
size: 1200, 200
size_hint: None, None
text: "Change the text on the 2nd screen to »2nd text«"
#on_press: (I don‘t know what should be there)
Button:
id: go_to_other_screen
pos: (root.width-self.width)/2, 1400
size: 600, 200
size_hint: None, None
text: "Go to other screen"
on_press: root.manager.current = "scr2"
<Screen2>:
id: scr2
orientation: "vertical"
canvas.before:
Rectangle:
pos: self.pos
size: self.size
source: "Background.png"
Label:
id: text
text: "Text which should be changed"
pos: (root.width-self.width)/2, 800
size: 600, 200
Button:
id: go_to_other_screen
pos: (root.width-self.width)/2, 1400
size: 600, 200
size_hint: None, None
text: "Go to other screen"
on_press: root.manager.current = "scr1"
I tried to search on the internet, but it didn't solve the main issue.
Thanks for any answer.
|
[
"In the kv file call a function in the screen 1 class. You can then use the get_screen function to access the other screen and change its text in that function.\nWould probably look something like:\n(in the kv file)\non_press: root.functionname()\n\n(main python file)\ndef functionname(self):\n self.manager.get_screen('scr2').ids.text.text = \"whatever you want here\"\n\nMay i also suggest changing the id of the text ur changing to something else, because it looks a bit confusing with ids.text.text\nFor more info about the get_screen function if you are confused about that https://medium.com/nerd-for-tech/kivy-use-get-screen-to-access-objects-from-other-screens-8d4d6f288f3\n"
] |
[
1
] |
[] |
[] |
[
"kivy",
"kivy_language",
"python"
] |
stackoverflow_0074495199_kivy_kivy_language_python.txt
|
Q:
How to pd.read_xml from zipfile with UTF-16 encoding?
I have a Zip archive with a number of xml files, which I would like to read into a Pandas data frame. The xml files are UTF-16 encoded, hence they can be read as:
import pandas as pd
# works
with open("data1.xml", encoding='utf-16') as f:
data = pd.read_xml(f)
# works
data = pd.read_xml("data1.xml", encoding='utf-16')
However, I cannot read the same file directly from the Zip archive without extracting it manually first.
import zipfile
import pandas as pd
# does not work
with zipfile.open("data1.xml") as f:
data = pd.read_xml(f, encoding='utf-16')
The problem seems to be the encoding, but I cannot manage to specify the UTF-16 correctly.
Many thanks for your help.
A:
ZipFile.open reads in binary mode. To read as UTF-16 text wrap in a TextIoWrapper.
Below assumes a test.zip file with UTF-16-encoded test.xml inside:
import zipfile
import pandas as pd
import io
z = zipfile.ZipFile('test.zip')
with z.open("test.xml") as f:
t = io.TextIOWrapper(f, encoding='utf-16')
data = pd.read_xml(t)
If the .zip file has a single .xml file in it, this works as well and is documented in pandas.read_xml (see the compression parameter):
data = pd.read_xml('test.zip', encoding='utf-16')
|
How to pd.read_xml from zipfile with UTF-16 encoding?
|
I have a Zip archive with a number of xml files, which I would like to read into a Pandas data frame. The xml files are UTF-16 encoded, hence they can be read as:
import pandas as pd
# works
with open("data1.xml", encoding='utf-16') as f:
data = pd.read_xml(f)
# works
data = pd.read_xml("data1.xml", encoding='utf-16')
However, I cannot read the same file directly from the Zip archive without extracting it manually first.
import zipfile
import pandas as pd
# does not work
with zipfile.open("data1.xml") as f:
data = pd.read_xml(f, encoding='utf-16')
The problem seems to be the encoding, but I cannot manage to specify the UTF-16 correctly.
Many thanks for your help.
|
[
"ZipFile.open reads in binary mode. To read as UTF-16 text wrap in a TextIoWrapper.\nBelow assumes a test.zip file with UTF-16-encoded test.xml inside:\nimport zipfile\nimport pandas as pd\nimport io\n\nz = zipfile.ZipFile('test.zip')\nwith z.open(\"test.xml\") as f:\n t = io.TextIOWrapper(f, encoding='utf-16')\n data = pd.read_xml(t)\n\nIf the .zip file has a single .xml file in it, this works as well and is documented in pandas.read_xml (see the compression parameter):\ndata = pd.read_xml('test.zip', encoding='utf-16')\n\n"
] |
[
2
] |
[] |
[] |
[
"pandas",
"python",
"python_3.x",
"xml",
"zip"
] |
stackoverflow_0074491605_pandas_python_python_3.x_xml_zip.txt
|
Q:
How to install SciPy on Apple Silicon (ARM / M1)
I have successfully installed python 3.9.1 with Numpy and Matplotlib on a new Mac mini with Apple Silicon. However, I cannot install SciPy : I get compilation errors when using
python3 -m pip install scipy
I also tried installing everything from brew, and import scipy works, but using it gives a seg fault. I have installed ARM versions of lapack and openblas, but this does not fix the problem.
Has anyone succeeded? (I am interested in running it natively, not through Rosetta).
A:
It's possible to install on regular arm64 brew python, you need to compile it yourself.
If numpy is already installed (from wheels) you'll need to uninstall it:
pip3 uninstall -y numpy pythran
I had to compile numpy, which requires cython and pybind11:
pip3 install cython pybind11
Then numpy can be compiled:
pip3 install --no-binary :all: --no-use-pep517 numpy
Scipy needs pythran (this should happen after installing numpy):
pip3 install pythran
Then we need to compile scipy itself, it depends on fortran and BLAS/LACK:
brew install openblas gfortran
Tell scipy where it can find this library:
export OPENBLAS=/opt/homebrew/opt/openblas/lib/
Then finally compilescipy:
pip3 install --no-binary :all: --no-use-pep517 scipy
A:
This one worked for me after wasting hours:
pip install --pre -i https://pypi.anaconda.org/scipy-wheels-nightly/simple scipy
A:
This solution worked on my M1 machine with pyenv:
brew install openblas
OPENBLAS="$(brew --prefix openblas)" pip install numpy scipy
A:
You can install miniforge from https://github.com/conda-forge/miniforge#miniforge3
and then install those packages with,
conda install numpy scipy matplotlib
A:
For me the easiest solutions:
brew install scipy
Probably good idea to edit the PATH, so the homebrew version will be the default.
A:
I managed to get scipy installed on Apple Silicon. I mostly followed the instructions by lutzroeder here: https://github.com/scipy/scipy/issues/13409
Those instructions weren't successful for me, but running 'pip3 install scipy' worked afterwards. I think this fixed the problem for me:
/opt/homebrew/bin/brew install openblas
export OPENBLAS=$(/opt/homebrew/bin/brew --prefix openblas)
export CFLAGS="-falign-functions=8 ${CFLAGS}"
A:
For those who need it for short-term purposes and don't want too much hustle - it seems to work with python 3.6.4 and scipy 1.5.4 out of the box (Big Sur 11.5.2, M1 chip).
A:
In addition, if someone has this error message>
########### CLIB COMPILER OPTIMIZATION ###########
Platform :
Architecture: aarch64
Compiler : clang
CPU baseline :
Requested : 'min'
Enabled : none
Flags : none
Extra checks: none
CPU dispatch :
Requested : 'max -xop -fma4'
Enabled : none
Generated : none
CCompilerOpt.cache_flush[809] : write cache to path
I found this solution before compile numpy and scipy
Analysis of reasons:
From the above error message, you can see that the last error shows that clang has an error, so it is speculated that it should be an error caused by the compiler, because the new version of the xcode command tool uses the arm version of the compilation method by default, and if we want to use For x86 architecture, we need to manually set the specific architecture through environment variables.
export ARCHFLAGS="-arch x86_64"
example:
3c790c45799ec8c598753ebb22/build/temp.macosx-10.14.6-arm64-3.8/ccompiler_opt_cache_clib.py
----------------------------------------
ERROR: Command errored out with exit status 1: /Users/daniel_edu/Projects/PERSONAL/great_expectation_demo/.env/bin/python3 -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/zb/c_b9kh2x1px7vl5683rwz8fr0000gn/T/pip-install-y8alaej_/numpy_3d813a3c790c45799ec8c598753ebb22/setup.py'"'"'; __file__='"'"'/private/var/folders/zb/c_b9kh2x1px7vl5683rwz8fr0000gn/T/pip-install-y8alaej_/numpy_3d813a3c790c45799ec8c598753ebb22/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/zb/c_b9kh2x1px7vl5683rwz8fr0000gn/T/pip-record-q9vraevr/install-record.txt --single-version-externally-managed --compile --install-headers /Users/daniel_edu/Projects/PERSONAL/great_expectation_demo/.env/include/site/python3.8/numpy Check the logs for full command output.
(.env) ➜ great_expectation_demo git:(master) ✗ export ARCHFLAGS="-arch x86_64"
(.env) ➜ great_expectation_demo git:(master) ✗ pip install --no-binary :all: --no-use-pep517 numpy
Collecting numpy
Using cached numpy-1.21.5.zip (10.7 MB)
Preparing metadata (setup.py) ... done
Skipping wheel build for numpy, due to binaries being disabled for it.
Installing collected packages: numpy
Running setup.py install for numpy ... done
Successfully installed numpy-1.21.5
A:
What version of scipy you're trying to install?
To me running on Macbook air M1, I needed to increase the version from scipy==1.5.1 to scipy==1.7.3, so I guess you should use 1.7.3 version or above it and all will be fine...
pip install -Iv scipy==1.7.3
Or just add in your file requirements.txt this line:
scipy==1.7.3
A:
The following worked for me.
I'm currently using Python 3.10.8, installed using brew.
And currently, when installing numpy==1.23.4, setuptools < 60.0.0 is required.
I'm using (brew --prefix)/bin/python3 -m pip for explicitly calling the pip from python 3.10 installed by brew.
Here are the versions I've just installed.
# python 3.10.8
# pip 22.3
# setuptools 59.8.0
# wheel 0.37.1
# numpy 1.23.4
# scipy 1.9.3
# pandas 1.5.1
# scikit-learn 1.1.3
# seaborn 0.12.1
# statsmodels 0.13.2
# gcc 12.2.0
# openblas 0.3.21
# gfortran 12
# pybind11 2.10.0
# Cython 0.29.32
# pythran 0.12.0
Here are the steps I followed:
# setuptools < 60.0.0 is required for numpy==1.23.4 in Python 3.10.8
$(brew --prefix)/bin/python3 -m pip install --upgrade pip==22.3 setuptools==59.8.0 wheel==0.37.1
# uninstall numpy and pythran first
$(brew --prefix)/bin/python3 -m pip uninstall -y numpy pythran
# uninstall scipy
$(brew --prefix)/bin/python3 -m pip uninstall -y scipy
# install prerequisites (with brew)
brew install gcc
brew install openblas
brew install gfortran
# set environment variables for compilers to find openblas
export LDFLAGS="-L/opt/homebrew/opt/openblas/lib"
export CPPFLAGS="-I/opt/homebrew/opt/openblas/include"
# install the prerequisites (with pip)
$(brew --prefix)/bin/python3 -m pip install pybind11
$(brew --prefix)/bin/python3 -m pip install Cython
# install numpy
$(brew --prefix)/bin/python3 -m pip install --no-binary :all: numpy
# install pythran after installing numpy, before installing scipy
$(brew --prefix)/bin/python3 -m pip install pythran
# install scipy
export OPENBLAS="$(brew --prefix)/opt/openblas/lib/"
$(brew --prefix)/bin/python3 -m pip install scipy
# install pandas
$(brew --prefix)/bin/python3 -m pip install pandas
# install scikit-learn
$(brew --prefix)/bin/python3 -m pip install scikit-learn
# install seaborn
$(brew --prefix)/bin/python3 -m pip install seaborn
# install statsmodels
$(brew --prefix)/bin/python3 -m pip install statsmodels
A:
I use conda install scipy to resolve this problem. Conda have a custom version of scipy for Apple M1. Update macOS to 12 if you don't want to use Conda.
A:
According to this Github issue, Scipy doesn't work on MacOS 11 (Big Sur). If none of these solutions are working for you I'd suggest updating your OS.
|
How to install SciPy on Apple Silicon (ARM / M1)
|
I have successfully installed python 3.9.1 with Numpy and Matplotlib on a new Mac mini with Apple Silicon. However, I cannot install SciPy : I get compilation errors when using
python3 -m pip install scipy
I also tried installing everything from brew, and import scipy works, but using it gives a seg fault. I have installed ARM versions of lapack and openblas, but this does not fix the problem.
Has anyone succeeded? (I am interested in running it natively, not through Rosetta).
|
[
"It's possible to install on regular arm64 brew python, you need to compile it yourself.\nIf numpy is already installed (from wheels) you'll need to uninstall it:\npip3 uninstall -y numpy pythran\n\nI had to compile numpy, which requires cython and pybind11:\npip3 install cython pybind11\n\nThen numpy can be compiled:\npip3 install --no-binary :all: --no-use-pep517 numpy\n\nScipy needs pythran (this should happen after installing numpy):\npip3 install pythran\n\nThen we need to compile scipy itself, it depends on fortran and BLAS/LACK:\nbrew install openblas gfortran\n\nTell scipy where it can find this library:\nexport OPENBLAS=/opt/homebrew/opt/openblas/lib/\n\nThen finally compilescipy:\npip3 install --no-binary :all: --no-use-pep517 scipy\n\n",
"This one worked for me after wasting hours:\npip install --pre -i https://pypi.anaconda.org/scipy-wheels-nightly/simple scipy\n\n",
"This solution worked on my M1 machine with pyenv:\nbrew install openblas\nOPENBLAS=\"$(brew --prefix openblas)\" pip install numpy scipy\n\n",
"You can install miniforge from https://github.com/conda-forge/miniforge#miniforge3\nand then install those packages with,\nconda install numpy scipy matplotlib\n\n",
"For me the easiest solutions:\nbrew install scipy\n\nProbably good idea to edit the PATH, so the homebrew version will be the default.\n",
"I managed to get scipy installed on Apple Silicon. I mostly followed the instructions by lutzroeder here: https://github.com/scipy/scipy/issues/13409\nThose instructions weren't successful for me, but running 'pip3 install scipy' worked afterwards. I think this fixed the problem for me:\n/opt/homebrew/bin/brew install openblas\n\nexport OPENBLAS=$(/opt/homebrew/bin/brew --prefix openblas)\n\nexport CFLAGS=\"-falign-functions=8 ${CFLAGS}\"\n\n",
"For those who need it for short-term purposes and don't want too much hustle - it seems to work with python 3.6.4 and scipy 1.5.4 out of the box (Big Sur 11.5.2, M1 chip).\n",
"In addition, if someone has this error message>\n########### CLIB COMPILER OPTIMIZATION ###########\nPlatform :\n Architecture: aarch64\n Compiler : clang\n\nCPU baseline :\n Requested : 'min'\n Enabled : none\n Flags : none\n Extra checks: none\n\nCPU dispatch :\n Requested : 'max -xop -fma4'\n Enabled : none\n Generated : none\nCCompilerOpt.cache_flush[809] : write cache to path \n\nI found this solution before compile numpy and scipy\nAnalysis of reasons:\nFrom the above error message, you can see that the last error shows that clang has an error, so it is speculated that it should be an error caused by the compiler, because the new version of the xcode command tool uses the arm version of the compilation method by default, and if we want to use For x86 architecture, we need to manually set the specific architecture through environment variables.\nexport ARCHFLAGS=\"-arch x86_64\"\n\nexample:\n3c790c45799ec8c598753ebb22/build/temp.macosx-10.14.6-arm64-3.8/ccompiler_opt_cache_clib.py\n ----------------------------------------\nERROR: Command errored out with exit status 1: /Users/daniel_edu/Projects/PERSONAL/great_expectation_demo/.env/bin/python3 -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '\"'\"'/private/var/folders/zb/c_b9kh2x1px7vl5683rwz8fr0000gn/T/pip-install-y8alaej_/numpy_3d813a3c790c45799ec8c598753ebb22/setup.py'\"'\"'; __file__='\"'\"'/private/var/folders/zb/c_b9kh2x1px7vl5683rwz8fr0000gn/T/pip-install-y8alaej_/numpy_3d813a3c790c45799ec8c598753ebb22/setup.py'\"'\"';f = getattr(tokenize, '\"'\"'open'\"'\"', open)(__file__) if os.path.exists(__file__) else io.StringIO('\"'\"'from setuptools import setup; setup()'\"'\"');code = f.read().replace('\"'\"'\\r\\n'\"'\"', '\"'\"'\\n'\"'\"');f.close();exec(compile(code, __file__, '\"'\"'exec'\"'\"'))' install --record /private/var/folders/zb/c_b9kh2x1px7vl5683rwz8fr0000gn/T/pip-record-q9vraevr/install-record.txt --single-version-externally-managed --compile --install-headers /Users/daniel_edu/Projects/PERSONAL/great_expectation_demo/.env/include/site/python3.8/numpy Check the logs for full command output.\n(.env) ➜ great_expectation_demo git:(master) ✗ export ARCHFLAGS=\"-arch x86_64\"\n(.env) ➜ great_expectation_demo git:(master) ✗ pip install --no-binary :all: --no-use-pep517 numpy\nCollecting numpy\n Using cached numpy-1.21.5.zip (10.7 MB)\n Preparing metadata (setup.py) ... done\nSkipping wheel build for numpy, due to binaries being disabled for it.\nInstalling collected packages: numpy\n Running setup.py install for numpy ... done\nSuccessfully installed numpy-1.21.5\n\n\n",
"What version of scipy you're trying to install?\nTo me running on Macbook air M1, I needed to increase the version from scipy==1.5.1 to scipy==1.7.3, so I guess you should use 1.7.3 version or above it and all will be fine...\n pip install -Iv scipy==1.7.3\n\nOr just add in your file requirements.txt this line:\nscipy==1.7.3\n\n",
"The following worked for me.\nI'm currently using Python 3.10.8, installed using brew.\nAnd currently, when installing numpy==1.23.4, setuptools < 60.0.0 is required.\nI'm using (brew --prefix)/bin/python3 -m pip for explicitly calling the pip from python 3.10 installed by brew.\nHere are the versions I've just installed.\n# python 3.10.8\n\n# pip 22.3\n# setuptools 59.8.0\n# wheel 0.37.1\n\n# numpy 1.23.4\n# scipy 1.9.3\n# pandas 1.5.1\n# scikit-learn 1.1.3\n# seaborn 0.12.1\n# statsmodels 0.13.2\n\n# gcc 12.2.0\n# openblas 0.3.21\n# gfortran 12\n# pybind11 2.10.0\n# Cython 0.29.32\n# pythran 0.12.0\n\nHere are the steps I followed:\n# setuptools < 60.0.0 is required for numpy==1.23.4 in Python 3.10.8\n$(brew --prefix)/bin/python3 -m pip install --upgrade pip==22.3 setuptools==59.8.0 wheel==0.37.1\n\n# uninstall numpy and pythran first\n$(brew --prefix)/bin/python3 -m pip uninstall -y numpy pythran\n\n# uninstall scipy\n$(brew --prefix)/bin/python3 -m pip uninstall -y scipy\n\n# install prerequisites (with brew)\nbrew install gcc\nbrew install openblas\nbrew install gfortran\n\n# set environment variables for compilers to find openblas\nexport LDFLAGS=\"-L/opt/homebrew/opt/openblas/lib\"\nexport CPPFLAGS=\"-I/opt/homebrew/opt/openblas/include\"\n\n# install the prerequisites (with pip)\n$(brew --prefix)/bin/python3 -m pip install pybind11\n$(brew --prefix)/bin/python3 -m pip install Cython\n\n# install numpy\n$(brew --prefix)/bin/python3 -m pip install --no-binary :all: numpy\n\n# install pythran after installing numpy, before installing scipy\n$(brew --prefix)/bin/python3 -m pip install pythran\n\n# install scipy\nexport OPENBLAS=\"$(brew --prefix)/opt/openblas/lib/\"\n$(brew --prefix)/bin/python3 -m pip install scipy\n\n# install pandas\n$(brew --prefix)/bin/python3 -m pip install pandas\n\n# install scikit-learn\n$(brew --prefix)/bin/python3 -m pip install scikit-learn\n\n# install seaborn\n$(brew --prefix)/bin/python3 -m pip install seaborn\n\n# install statsmodels\n$(brew --prefix)/bin/python3 -m pip install statsmodels\n\n",
"I use conda install scipy to resolve this problem. Conda have a custom version of scipy for Apple M1. Update macOS to 12 if you don't want to use Conda.\n",
"According to this Github issue, Scipy doesn't work on MacOS 11 (Big Sur). If none of these solutions are working for you I'd suggest updating your OS.\n"
] |
[
70,
64,
46,
12,
10,
4,
3,
2,
2,
1,
0,
0
] |
[] |
[] |
[
"apple_m1",
"apple_silicon",
"arm",
"python",
"scipy"
] |
stackoverflow_0065745683_apple_m1_apple_silicon_arm_python_scipy.txt
|
Q:
pandas converting floats to strings without decimals
I have a dataframe
df = pd.DataFrame([
['2', '3', 'nan'],
['0', '1', '4'],
['5', 'nan', '7']
])
print df
0 1 2
0 2 3 nan
1 0 1 4
2 5 nan 7
I want to convert these strings to numbers and sum the columns and convert back to strings.
Using astype(float) seems to get me to the number part. Then summing is easy with sum(). Then back to strings should be easy too with astype(str)
df.astype(float).sum().astype(str)
0 7.0
1 4.0
2 11.0
dtype: object
That's almost what I wanted. I wanted the string version of integers. But floats have decimals. How do I get rid of them?
I want this
0 7
1 4
2 11
dtype: object
A:
Converting to int (i.e. with .astype(int).astype(str)) won't work if your column contains nulls; it's often a better idea to use string formatting to explicitly specify the format of your string column; (you can set this in pd.options):
>>> pd.options.display.float_format = '{:,.0f}'.format
>>> df.astype(float).sum()
0 7
1 4
2 11
dtype: float64
A:
Add a astype(int) in the mix:
df.astype(float).sum().astype(int).astype(str)
0 7
1 4
2 11
dtype: object
Demonstration of example with empty cells. This was not a requirement from the OP but to satisfy the detractors
df = pd.DataFrame([
['2', '3', 'nan', None],
[None, None, None, None],
['0', '1', '4', None],
['5', 'nan', '7', None]
])
df
0 1 2 3
0 2 3 nan None
1 None None None None
2 0 1 4 None
3 5 nan 7 None
Then
df.astype(float).sum().astype(int).astype(str)
0 7
1 4
2 11
3 0
dtype: object
Because the OP didn't specify what they'd like to happen when a column was all missing, presenting zero is a reasonable option.
However, we could also drop those columns
df.dropna(1, 'all').astype(float).sum().astype(int).astype(str)
0 7
1 4
2 11
dtype: object
A:
For pandas >= 1.0:
<NA> type was introduced for 'Int64'. You can now do this:
df['your_column'].astype('Int64').astype('str')
And it will properly convert 1.0 to 1.
Alternative:
If you do not want to change the display options of all pandas, @maxymoo solution does, you can use apply:
df['your_column'].apply(lambda x: f'{x:.0f}')
A:
Add astype(int) right before conversion to a string:
print (df.astype(float).sum().astype(int).astype(str))
Generates the desired result.
A:
based on toto_tico's solution - alternative , minor changes to avoid null case become nan
df['your_column'].apply(lambda x: f'{x:.0f}' if not pd.isnull(x) else '')
A:
The above solutions, when converting to string, will turn NaN into a string as well. To get around that and retain NaN, use:
c = ... # your column
np.where(
df[c].isnull(), np.nan,
df[c].apply('{:.0f}'.format)
)
Retaining NaN allows you to do stuff like convert a nullable column of integers like 19991231, 20000101, np.nan, 20000102 into date time without triggering date parsing errors.
|
pandas converting floats to strings without decimals
|
I have a dataframe
df = pd.DataFrame([
['2', '3', 'nan'],
['0', '1', '4'],
['5', 'nan', '7']
])
print df
0 1 2
0 2 3 nan
1 0 1 4
2 5 nan 7
I want to convert these strings to numbers and sum the columns and convert back to strings.
Using astype(float) seems to get me to the number part. Then summing is easy with sum(). Then back to strings should be easy too with astype(str)
df.astype(float).sum().astype(str)
0 7.0
1 4.0
2 11.0
dtype: object
That's almost what I wanted. I wanted the string version of integers. But floats have decimals. How do I get rid of them?
I want this
0 7
1 4
2 11
dtype: object
|
[
"Converting to int (i.e. with .astype(int).astype(str)) won't work if your column contains nulls; it's often a better idea to use string formatting to explicitly specify the format of your string column; (you can set this in pd.options):\n>>> pd.options.display.float_format = '{:,.0f}'.format\n>>> df.astype(float).sum()\n0 7\n1 4\n2 11\ndtype: float64\n\n",
"Add a astype(int) in the mix:\ndf.astype(float).sum().astype(int).astype(str)\n\n0 7\n1 4\n2 11\ndtype: object\n\n\nDemonstration of example with empty cells. This was not a requirement from the OP but to satisfy the detractors\ndf = pd.DataFrame([\n ['2', '3', 'nan', None],\n [None, None, None, None],\n ['0', '1', '4', None],\n ['5', 'nan', '7', None]\n ])\n\ndf\n\n 0 1 2 3\n0 2 3 nan None\n1 None None None None\n2 0 1 4 None\n3 5 nan 7 None\n\nThen\ndf.astype(float).sum().astype(int).astype(str)\n\n0 7\n1 4\n2 11\n3 0\ndtype: object\n\nBecause the OP didn't specify what they'd like to happen when a column was all missing, presenting zero is a reasonable option.\nHowever, we could also drop those columns\ndf.dropna(1, 'all').astype(float).sum().astype(int).astype(str)\n\n0 7\n1 4\n2 11\ndtype: object\n\n",
"For pandas >= 1.0:\n<NA> type was introduced for 'Int64'. You can now do this:\ndf['your_column'].astype('Int64').astype('str')\n\nAnd it will properly convert 1.0 to 1. \n\nAlternative:\nIf you do not want to change the display options of all pandas, @maxymoo solution does, you can use apply:\ndf['your_column'].apply(lambda x: f'{x:.0f}')\n\n",
"Add astype(int) right before conversion to a string:\nprint (df.astype(float).sum().astype(int).astype(str))\n\nGenerates the desired result.\n",
"based on toto_tico's solution - alternative , minor changes to avoid null case become nan\ndf['your_column'].apply(lambda x: f'{x:.0f}' if not pd.isnull(x) else '')\n\n",
"The above solutions, when converting to string, will turn NaN into a string as well. To get around that and retain NaN, use:\nc = ... # your column\nnp.where(\n df[c].isnull(), np.nan,\n df[c].apply('{:.0f}'.format)\n)\n\nRetaining NaN allows you to do stuff like convert a nullable column of integers like 19991231, 20000101, np.nan, 20000102 into date time without triggering date parsing errors.\n"
] |
[
30,
23,
23,
3,
0,
0
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0038516316_pandas_python.txt
|
Q:
How to generate valid timestamps from YouTube subtitles, downloaded with wrong timestamps? (using pytube)
Using pytube, I am trying to download a YouTube video, translate the subtitles and embed the translated subtitles back into the video, then download it to my PC.
This is a part of my code, changed so it will be easy to understand.
from pytube import YouTube as YT
yt = YT("https://www.youtube.com/watch?v=ZFGAz6vZx1E")
caption_code = ''
try:
captions = yt.captions['en']
caption_code = 'en'
except:
try:
captions = yt.captions['a.en']
caption_code = 'a.en'
except Exception as e:
raise e
captions = yt.captions.get_by_language_code(caption_code)
test_captions(captions)
### just a function to test how's the cations are structured.
def test_captions(captions):
caption_list = []
index = 0
for line in str(captions.generate_srt_captions()).split('\n'):
if index == 0:
caption_list.append({})
if index in (1, 2):
caption_list[len(caption_list)-1][('time', 'caption')[index-1]] = line
index += 1
if line == '':
index = 0
for dic in caption_list:
print('{} : {}'.format(dic['time'], dic['caption']))
At the original YouTube video, the captions start at the 1st second (should be around 00:00:01,000 )
First downloaded caption sentence with timestamps :
"00:01:20,000 --> 00:52:00,000 : what's going on guys john elder here"
As you can see from the console, the subtitles have wrong timestamps, according to SRT timestamps convention.
(SRT timestamps convention explained at https://www.3playmedia.com/)
The 1st timestamps basically says that the sentence should be displayed from the 1sr minute and 20 seconds, to minute 52, which is clearly wrong.
Is it possible to fix it, and if not, how to do I normalize the captions' timestamps to fit the valid SRT timestamps format?
A:
when you generate the caption as xml, you will notice that the time multiplied to 1000 for some reason
Time after "t=" is the when text starts to appear in seconds, "d=" is when it ends
So i just spilled the time, divide it by 1000 , make it in as "hour:minutes:second" , take the text and put all in my file.srt
|
How to generate valid timestamps from YouTube subtitles, downloaded with wrong timestamps? (using pytube)
|
Using pytube, I am trying to download a YouTube video, translate the subtitles and embed the translated subtitles back into the video, then download it to my PC.
This is a part of my code, changed so it will be easy to understand.
from pytube import YouTube as YT
yt = YT("https://www.youtube.com/watch?v=ZFGAz6vZx1E")
caption_code = ''
try:
captions = yt.captions['en']
caption_code = 'en'
except:
try:
captions = yt.captions['a.en']
caption_code = 'a.en'
except Exception as e:
raise e
captions = yt.captions.get_by_language_code(caption_code)
test_captions(captions)
### just a function to test how's the cations are structured.
def test_captions(captions):
caption_list = []
index = 0
for line in str(captions.generate_srt_captions()).split('\n'):
if index == 0:
caption_list.append({})
if index in (1, 2):
caption_list[len(caption_list)-1][('time', 'caption')[index-1]] = line
index += 1
if line == '':
index = 0
for dic in caption_list:
print('{} : {}'.format(dic['time'], dic['caption']))
At the original YouTube video, the captions start at the 1st second (should be around 00:00:01,000 )
First downloaded caption sentence with timestamps :
"00:01:20,000 --> 00:52:00,000 : what's going on guys john elder here"
As you can see from the console, the subtitles have wrong timestamps, according to SRT timestamps convention.
(SRT timestamps convention explained at https://www.3playmedia.com/)
The 1st timestamps basically says that the sentence should be displayed from the 1sr minute and 20 seconds, to minute 52, which is clearly wrong.
Is it possible to fix it, and if not, how to do I normalize the captions' timestamps to fit the valid SRT timestamps format?
|
[
"when you generate the caption as xml, you will notice that the time multiplied to 1000 for some reason\nTime after \"t=\" is the when text starts to appear in seconds, \"d=\" is when it ends\nSo i just spilled the time, divide it by 1000 , make it in as \"hour:minutes:second\" , take the text and put all in my file.srt\n"
] |
[
0
] |
[] |
[] |
[
"caption",
"python",
"pytube",
"srt"
] |
stackoverflow_0074330836_caption_python_pytube_srt.txt
|
Q:
Pandas dataframe with N columns
I need to use Python with Pandas to write a DataFrame with N columns. This is a simplified version of what I have:
Ind=[[1, 2, 3],[4, 5, 6],[7, 8, 9],[10, 11, 12]]
DAT = pd.DataFrame([Ind[0],Ind[1],Ind[2],Ind[3]], index=None).T
DAT.head()
Out
0 1 2 3
0 1 4 7 10
1 2 5 8 11
2 3 6 9 12
This is the result that I want, but my real Ind has 121 sets of points and I really don't want to write each one in the DataFrame's argument. Is there a way to write this easily? I tried using a for loop, but that didn't work out.
A:
You can just pass the list directly:
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
df = pd.DataFrame(data, index=None).T
df.head()
Outputs:
0 1 2
0 1 2 3
1 4 5 6
2 7 8 9
3 10 11 12
|
Pandas dataframe with N columns
|
I need to use Python with Pandas to write a DataFrame with N columns. This is a simplified version of what I have:
Ind=[[1, 2, 3],[4, 5, 6],[7, 8, 9],[10, 11, 12]]
DAT = pd.DataFrame([Ind[0],Ind[1],Ind[2],Ind[3]], index=None).T
DAT.head()
Out
0 1 2 3
0 1 4 7 10
1 2 5 8 11
2 3 6 9 12
This is the result that I want, but my real Ind has 121 sets of points and I really don't want to write each one in the DataFrame's argument. Is there a way to write this easily? I tried using a for loop, but that didn't work out.
|
[
"You can just pass the list directly:\ndata = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]\ndf = pd.DataFrame(data, index=None).T\ndf.head()\n\nOutputs:\n 0 1 2\n0 1 2 3\n1 4 5 6\n2 7 8 9\n3 10 11 12\n\n"
] |
[
2
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074495578_pandas_python.txt
|
Q:
Why does tf.executing_eagerly() return False in TensorFlow 2?
Let me explain my set up. I am using TensorFlow 2.1, the Keras version shipped with TF, and TensorFlow Probability 0.9.
I have a function get_model that creates (with the functional API) and returns a model using Keras and custom layers. In the __init__ method of these custom layers A, I call a method A.m, which executes the statement print(tf.executing_eagerly()), but it returns False. Why?
To be more precise, this is roughly my setup
def get_model():
inp = Input(...)
x = A(...)(inp)
x = A(...)(x)
...
model = Model(inp, out)
model.compile(...)
return model
class A(tfp.layers.DenseFlipout): # TensorFlow Probability
def __init__(...):
self.m()
def m(self):
print(tf.executing_eagerly()) # Prints False
The documentation of tf.executing_eagerly says
Eager execution is enabled by default and this API returns True in most of cases. However, this API might return False in the following use cases.
Executing inside tf.function, unless under tf.init_scope or tf.config.experimental_run_functions_eagerly(True) is previously called.
Executing inside a transformation function for tf.dataset.
tf.compat.v1.disable_eager_execution() is called.
But these cases are not my case, so tf.executing_eagerly() should return True in my case, but no. Why?
Here's a simple complete example (in TF 2.1) that illustrates the problem.
import tensorflow as tf
class MyLayer(tf.keras.layers.Layer):
def call(self, inputs):
tf.print("tf.executing_eagerly() =", tf.executing_eagerly())
return inputs
def get_model():
inp = tf.keras.layers.Input(shape=(1,))
out = MyLayer(8)(inp)
model = tf.keras.Model(inputs=inp, outputs=out)
model.summary()
return model
def train():
model = get_model()
model.compile(optimizer="adam", loss="mae")
x_train = [2, 3, 4, 1, 2, 6]
y_train = [1, 0, 1, 0, 1, 1]
model.fit(x_train, y_train)
if __name__ == '__main__':
train()
This example prints tf.executing_eagerly() = False.
See the related Github issue.
A:
As far as I know, when an input to a custom layer is symbolic input, then the layer is executed in graph (non-eager) mode. However, if your input to the custom layer is an eager tensor (as in the following example #1, then the custom layer is executed in the eager mode. So your model's output tf.executing_eagerly() = False is expected.
Example #1
from tensorflow.keras import layers
class Linear(layers.Layer):
def __init__(self, units=32, input_dim=32):
super(Linear, self).__init__()
w_init = tf.random_normal_initializer()
self.w = tf.Variable(initial_value=w_init(shape=(input_dim, units),
dtype='float32'),
trainable=True)
b_init = tf.zeros_initializer()
self.b = tf.Variable(initial_value=b_init(shape=(units,),
dtype='float32'),
trainable=True)
def call(self, inputs):
print("tf.executing_eagerly() =", tf.executing_eagerly())
return tf.matmul(inputs, self.w) + self.b
x = tf.ones((1, 2)) # returns tf.executing_eagerly() = True
#x = tf.keras.layers.Input(shape=(2,)) #tf.executing_eagerly() = False
linear_layer = Linear(4, 2)
y = linear_layer(x)
print(y)
#output in graph mode: Tensor("linear_9/Identity:0", shape=(None, 4), dtype=float32)
#output in Eager mode: tf.Tensor([[-0.03011466 0.02563028 0.01234017 0.02272708]], shape=(1, 4), dtype=float32)
Here is another example with Keras functional API where custom layer was used (similar to you). This model is executed in graph mode and prints tf.executing_eagerly() = False as in your case.
from tensorflow import keras
from tensorflow.keras import layers
class CustomDense(layers.Layer):
def __init__(self, units=32):
super(CustomDense, self).__init__()
self.units = units
def build(self, input_shape):
self.w = self.add_weight(shape=(input_shape[-1], self.units),
initializer='random_normal',
trainable=True)
self.b = self.add_weight(shape=(self.units,),
initializer='random_normal',
trainable=True)
def call(self, inputs):
print("tf.executing_eagerly() =", tf.executing_eagerly())
return tf.matmul(inputs, self.w) + self.b
inputs = keras.Input((4,))
outputs = CustomDense(10)(inputs)
model = keras.Model(inputs, outputs)
A:
You might be running in a Colab. If so, try the following immediately after importing Tensorflow:
tf.compat.v1.enable_v2_behavior()
More generally, check the docs at https://www.tensorflow.org/api_docs/python/tf/executing_eagerly for more information on eager execution.
|
Why does tf.executing_eagerly() return False in TensorFlow 2?
|
Let me explain my set up. I am using TensorFlow 2.1, the Keras version shipped with TF, and TensorFlow Probability 0.9.
I have a function get_model that creates (with the functional API) and returns a model using Keras and custom layers. In the __init__ method of these custom layers A, I call a method A.m, which executes the statement print(tf.executing_eagerly()), but it returns False. Why?
To be more precise, this is roughly my setup
def get_model():
inp = Input(...)
x = A(...)(inp)
x = A(...)(x)
...
model = Model(inp, out)
model.compile(...)
return model
class A(tfp.layers.DenseFlipout): # TensorFlow Probability
def __init__(...):
self.m()
def m(self):
print(tf.executing_eagerly()) # Prints False
The documentation of tf.executing_eagerly says
Eager execution is enabled by default and this API returns True in most of cases. However, this API might return False in the following use cases.
Executing inside tf.function, unless under tf.init_scope or tf.config.experimental_run_functions_eagerly(True) is previously called.
Executing inside a transformation function for tf.dataset.
tf.compat.v1.disable_eager_execution() is called.
But these cases are not my case, so tf.executing_eagerly() should return True in my case, but no. Why?
Here's a simple complete example (in TF 2.1) that illustrates the problem.
import tensorflow as tf
class MyLayer(tf.keras.layers.Layer):
def call(self, inputs):
tf.print("tf.executing_eagerly() =", tf.executing_eagerly())
return inputs
def get_model():
inp = tf.keras.layers.Input(shape=(1,))
out = MyLayer(8)(inp)
model = tf.keras.Model(inputs=inp, outputs=out)
model.summary()
return model
def train():
model = get_model()
model.compile(optimizer="adam", loss="mae")
x_train = [2, 3, 4, 1, 2, 6]
y_train = [1, 0, 1, 0, 1, 1]
model.fit(x_train, y_train)
if __name__ == '__main__':
train()
This example prints tf.executing_eagerly() = False.
See the related Github issue.
|
[
"As far as I know, when an input to a custom layer is symbolic input, then the layer is executed in graph (non-eager) mode. However, if your input to the custom layer is an eager tensor (as in the following example #1, then the custom layer is executed in the eager mode. So your model's output tf.executing_eagerly() = False is expected.\nExample #1\nfrom tensorflow.keras import layers\n\n\nclass Linear(layers.Layer):\n\n def __init__(self, units=32, input_dim=32):\n super(Linear, self).__init__()\n w_init = tf.random_normal_initializer()\n self.w = tf.Variable(initial_value=w_init(shape=(input_dim, units),\n dtype='float32'),\n trainable=True)\n b_init = tf.zeros_initializer()\n self.b = tf.Variable(initial_value=b_init(shape=(units,),\n dtype='float32'),\n trainable=True)\n\n def call(self, inputs):\n print(\"tf.executing_eagerly() =\", tf.executing_eagerly())\n return tf.matmul(inputs, self.w) + self.b\n\nx = tf.ones((1, 2)) # returns tf.executing_eagerly() = True\n#x = tf.keras.layers.Input(shape=(2,)) #tf.executing_eagerly() = False\nlinear_layer = Linear(4, 2)\ny = linear_layer(x)\nprint(y) \n#output in graph mode: Tensor(\"linear_9/Identity:0\", shape=(None, 4), dtype=float32)\n#output in Eager mode: tf.Tensor([[-0.03011466 0.02563028 0.01234017 0.02272708]], shape=(1, 4), dtype=float32)\n\nHere is another example with Keras functional API where custom layer was used (similar to you). This model is executed in graph mode and prints tf.executing_eagerly() = False as in your case.\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nclass CustomDense(layers.Layer):\n def __init__(self, units=32):\n super(CustomDense, self).__init__()\n self.units = units\n\n def build(self, input_shape):\n self.w = self.add_weight(shape=(input_shape[-1], self.units),\n initializer='random_normal',\n trainable=True)\n self.b = self.add_weight(shape=(self.units,),\n initializer='random_normal',\n trainable=True)\n\n def call(self, inputs):\n print(\"tf.executing_eagerly() =\", tf.executing_eagerly())\n return tf.matmul(inputs, self.w) + self.b\n\n\ninputs = keras.Input((4,))\noutputs = CustomDense(10)(inputs)\n\nmodel = keras.Model(inputs, outputs) \n\n",
"You might be running in a Colab. If so, try the following immediately after importing Tensorflow:\ntf.compat.v1.enable_v2_behavior()\n\nMore generally, check the docs at https://www.tensorflow.org/api_docs/python/tf/executing_eagerly for more information on eager execution.\n"
] |
[
2,
1
] |
[] |
[] |
[
"keras",
"python",
"tensorflow",
"tensorflow2.0",
"tensorflow_probability"
] |
stackoverflow_0061355474_keras_python_tensorflow_tensorflow2.0_tensorflow_probability.txt
|
Q:
Python tkinter: configure multiple labels with a loop
I have a window with multiple labels. Instead of configuring each label individually, I want to use a for loop to configure them.
Basically, what I get from the below code is all labels are showing the text 'question #3', but I want each label label to show the right text accordingly - so label1 needs to have the text 'question #1', label2 needs to show 'question #2' and label3 needs to show 'question #3'. Can somebody please help.
from tkinter import *
root = Tk()
string = 'Question #'
nums = ['1', '2', '3']
#labels
label_1 = Label(root)
label_1.pack()
label_2 = Label(root)
label_2.pack()
label_3 = Label(root)
label_3.pack()
# end of labels
labels = [label_1, label_2, label_3]
for x in nums:
jk = string + x
for l in labels:
l.config(text=jk)
root.mainloop()
A:
The easiest way to do so by only modifying your code will involve using zip. Your code just have some looping issues.
for x, l in zip(nums,labels): #change your for loops to this
jk = string + x
l.config(text=jk)
Writing a concise code involving this: generating the label and the text together could save you many lines of codes. This works the same for your code
from tkinter import *
root = Tk()
string = 'Question #'
nums = ['1', '2', '3']
labels=[] #creates an empty list for your labels
for x in nums: #iterates over your nums
jk = string + x
label = Label(root,text=jk) #set your text
label.pack()
labels.append(label) #appends the label to the list for further use
root.mainloop()
A:
this works for me:
result of code is given below;
code explain: I have one recipe that has a 3 foods and one drink for the small buffet.
I want pide (food)+ayran (drink), some body want kebap(food) + ayran etc.
Is it possible the customer to see three different foods plus a drink in a row?, yes of course!.
Then I coded something like below. I finally came to solution after tried many times.
class Class1:
def __init__(self,master,pide=14,ayran=2,kebap=16,sucuk=12): #Class variables
self.master=master
master.title("A simple recipe")
self.ayran=ayran
self.pide=pide
self.kebap=kebap
self.sucuk=sucuk
def hesapla(self):
pa=self.pide+self.ayran #food +drink
ka=self.kebap+self.ayran
sa=self.sucuk+self.ayran
#print (pa)
fiyatlar= [pa,ka,sa] #arrays of foods+drinks
for x in range(3):
L = tk.Label( text=fiyatlar[x]) #labels for price tags in a 3 rows
L.grid(row=x,column=1)
yazilar=["pide+ayran=","kebap+ayran=","sucuk+ayran="] #names of foods and drinks
for x in range(3):
L2 = tk.Label( text=yazilar[x])
L2.grid(row=x,column=0)
for x in range(3):
L3 = tk.Label( text="$") # $ sign near the price tags
L3.grid(row=x,column=2)
def main(): # let codes work
uyg = Tk()
hes1 = Class1(uyg)
hes1.hesapla()
uyg.mainloop()
if __name__ == '__main__': #if you want use another .py file, call it.
main()
A:
import tkinter
from tkinter import *
root = Tk()
class Class1:
def __init__(self,cam):
self.cam = cam
cam.title("Abcd egfh")
self.frame1=Frame(cam, padx=5)
self.frame1.grid(column=0,row=1)
self.labels= ["LABELS","label 1","label 2","label 3","label 4"]
Editlabel=Label(self.frame1,text="EDITS")
Editlabel.grid(row=0,column=1)
self.edits= ["ed1","ed2","ed3","ed4"]
for x in range(5):
self.L = Label( self.frame1,text=self.labels[x])
self.L.grid(row=x,column=0)
class Class2(Class1):
def __init__(self,ws):
super().__init__(ws)
for x in range(1,5):
self.L = Entry(self.frame1)
self.L.grid(row=x,column=1)
root.geometry("200x150")
my_gui = Class1(root)
my_gui2 = Class2(root)
root.mainloop()
|
Python tkinter: configure multiple labels with a loop
|
I have a window with multiple labels. Instead of configuring each label individually, I want to use a for loop to configure them.
Basically, what I get from the below code is all labels are showing the text 'question #3', but I want each label label to show the right text accordingly - so label1 needs to have the text 'question #1', label2 needs to show 'question #2' and label3 needs to show 'question #3'. Can somebody please help.
from tkinter import *
root = Tk()
string = 'Question #'
nums = ['1', '2', '3']
#labels
label_1 = Label(root)
label_1.pack()
label_2 = Label(root)
label_2.pack()
label_3 = Label(root)
label_3.pack()
# end of labels
labels = [label_1, label_2, label_3]
for x in nums:
jk = string + x
for l in labels:
l.config(text=jk)
root.mainloop()
|
[
"The easiest way to do so by only modifying your code will involve using zip. Your code just have some looping issues. \nfor x, l in zip(nums,labels): #change your for loops to this\n jk = string + x\n l.config(text=jk)\n\nWriting a concise code involving this: generating the label and the text together could save you many lines of codes. This works the same for your code\nfrom tkinter import *\nroot = Tk()\nstring = 'Question #'\nnums = ['1', '2', '3']\nlabels=[] #creates an empty list for your labels\nfor x in nums: #iterates over your nums\n jk = string + x\n label = Label(root,text=jk) #set your text\n label.pack()\n labels.append(label) #appends the label to the list for further use\n\nroot.mainloop()\n\n",
"this works for me:\nresult of code is given below;\n\ncode explain: I have one recipe that has a 3 foods and one drink for the small buffet.\nI want pide (food)+ayran (drink), some body want kebap(food) + ayran etc.\nIs it possible the customer to see three different foods plus a drink in a row?, yes of course!.\nThen I coded something like below. I finally came to solution after tried many times.\nclass Class1:\n def __init__(self,master,pide=14,ayran=2,kebap=16,sucuk=12): #Class variables\n self.master=master\n master.title(\"A simple recipe\")\n self.ayran=ayran\n self.pide=pide\n self.kebap=kebap\n self.sucuk=sucuk\n \n\n def hesapla(self): \n\n pa=self.pide+self.ayran #food +drink\n ka=self.kebap+self.ayran\n sa=self.sucuk+self.ayran\n #print (pa)\n fiyatlar= [pa,ka,sa] #arrays of foods+drinks\n \n for x in range(3):\n\n L = tk.Label( text=fiyatlar[x]) #labels for price tags in a 3 rows\n L.grid(row=x,column=1)\n\n yazilar=[\"pide+ayran=\",\"kebap+ayran=\",\"sucuk+ayran=\"] #names of foods and drinks\n for x in range(3):\n\n L2 = tk.Label( text=yazilar[x])\n L2.grid(row=x,column=0)\n \n for x in range(3):\n\n L3 = tk.Label( text=\"$\") # $ sign near the price tags\n L3.grid(row=x,column=2)\n\n def main(): # let codes work\n uyg = Tk()\n hes1 = Class1(uyg)\n hes1.hesapla()\n uyg.mainloop()\n\n if __name__ == '__main__': #if you want use another .py file, call it.\n main()\n\n",
"import tkinter\nfrom tkinter import *\n\n\nroot = Tk()\n\nclass Class1:\n\n def __init__(self,cam):\n\n self.cam = cam\n cam.title(\"Abcd egfh\")\n\n self.frame1=Frame(cam, padx=5)\n self.frame1.grid(column=0,row=1)\n\n self.labels= [\"LABELS\",\"label 1\",\"label 2\",\"label 3\",\"label 4\"]\n Editlabel=Label(self.frame1,text=\"EDITS\")\n Editlabel.grid(row=0,column=1)\n self.edits= [\"ed1\",\"ed2\",\"ed3\",\"ed4\"]\n\n for x in range(5):\n\n self.L = Label( self.frame1,text=self.labels[x]) \n self.L.grid(row=x,column=0)\n\nclass Class2(Class1):\n\n def __init__(self,ws):\n\n super().__init__(ws)\n\n for x in range(1,5):\n\n self.L = Entry(self.frame1) \n self.L.grid(row=x,column=1)\n\n\n root.geometry(\"200x150\")\n\n\n\n my_gui = Class1(root)\n\n my_gui2 = Class2(root)\n\n root.mainloop()\n\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"for_loop",
"loops",
"python",
"tkinter"
] |
stackoverflow_0042599924_for_loop_loops_python_tkinter.txt
|
Q:
Getting ALL picture file names from wikimedia commons search
So I'm trying to get all the picture files names for a wikimedia image search, but I'm only getting 10 results.
As an example, I tried running:
import json
from io import StringIO
import pandas as pd
import numpy as np
import cv2
import matplotlib.pyplot as plt
import urllib.request
import requests
import time
import shutil
from bs4 import BeautifulSoup
from newspaper import Article
import sys
import html2text
import xmltodict
from xml.etree import ElementTree
import urllib
headers = {'Accept': 'application/json', 'Content-Type': 'application/json', }
plants_df = pd.DataFrame()
pic_searches = ['blue+marble']
df_all = pd.DataFrame()
for pic_search in pic_searches:
url = str(r'https://commons.wikimedia.org/w/api.php?action=query&prop=imageinfo|categories&+\ generator=search&gsrsearch=File:') + str(pic_search) + str('&format=jsonfm&origin=*& + \ iiprop=extmetadata&iiextmetadatafilter=ImageDescription|ObjectName') + \
response = urllib.request.urlopen(url).read()
soup = BeautifulSoup(response, 'html.parser')
spans = soup.find_all('span', {'class': 's2'})
lines = [span.get_text() for span in spans]
new_list = [item.replace('"', '') for item in lines]
new_list2 = [x for x in new_list if x.startswith('File')]
new_list3 = [x[5:] for x in new_list2]
new_list4 = [x.replace(' ','_') for x in new_list3]
print(new_list4)
I got the result ['Blue_Marble_2021.png', 'Blue_Marble_2022.jpg', 'Blue_Marble_Comparsion.png', 'Blue_Marble_Eastern_Hemisphere.jpg', 'Blue_Marble_Western_Hemisphere.jpg', 'Blue_Marble_transparent.png', 'The_Blue_Marble.jpg', 'The_Blue_Marble_(5052124705).jpg', 'The_Blue_Marble_White_Balancing.jpg', 'The_Earth_seen_from_Apollo_17.jpg']. But this is only 10 file names. When I type blue marble into wikimedia commons image search, hundreds of results come up. How can I get all the image file names?
A:
MediaWiki API queries are paginated. This means that each API call will return a maximum number of results, and you will need to include additional parameters in subsequent requests in order to retrieve the remaining results.
The official documentation has an example that demonstrates how to submit the continuation requests.
Since you are already importing requests, I would suggest using that library instead of urllib.request.urlopen for this. You definitely should not be using BeautifulSoup to parse these responses - you can specify format=json and use json instead.
It will be easier to handle the continuation requests if you use a dictionary for the query params instead of manually crafting a string.
Example using Requests:
def get_image_names(pic_search):
session = requests.Session()
url = 'https://commons.wikimedia.org/w/api.php'
params = {
'action': 'query',
'prop': 'imageinfo|categories',
'generator': 'search',
'gsrsearch': f'File:{pic_search}',
'format': 'json',
'origin': '*',
'iiprop': 'extmetadata',
'iiextmetadatafilter': 'ImageDescription|ObjectName',
'formatversion': 2, # only if the target wiki is running mediawiki 1.25 or above
}
resp = session.get(url, params=params).json()
names = [page['title'] for page in resp['query']['pages']]
continue_params = resp.get('continue')
while continue_params:
params.update(continue_params)
resp = session.get(url, params=params).json()
names.extend(page['title'] for page in resp['query']['pages'])
continue_params = resp.get('continue')
return names
|
Getting ALL picture file names from wikimedia commons search
|
So I'm trying to get all the picture files names for a wikimedia image search, but I'm only getting 10 results.
As an example, I tried running:
import json
from io import StringIO
import pandas as pd
import numpy as np
import cv2
import matplotlib.pyplot as plt
import urllib.request
import requests
import time
import shutil
from bs4 import BeautifulSoup
from newspaper import Article
import sys
import html2text
import xmltodict
from xml.etree import ElementTree
import urllib
headers = {'Accept': 'application/json', 'Content-Type': 'application/json', }
plants_df = pd.DataFrame()
pic_searches = ['blue+marble']
df_all = pd.DataFrame()
for pic_search in pic_searches:
url = str(r'https://commons.wikimedia.org/w/api.php?action=query&prop=imageinfo|categories&+\ generator=search&gsrsearch=File:') + str(pic_search) + str('&format=jsonfm&origin=*& + \ iiprop=extmetadata&iiextmetadatafilter=ImageDescription|ObjectName') + \
response = urllib.request.urlopen(url).read()
soup = BeautifulSoup(response, 'html.parser')
spans = soup.find_all('span', {'class': 's2'})
lines = [span.get_text() for span in spans]
new_list = [item.replace('"', '') for item in lines]
new_list2 = [x for x in new_list if x.startswith('File')]
new_list3 = [x[5:] for x in new_list2]
new_list4 = [x.replace(' ','_') for x in new_list3]
print(new_list4)
I got the result ['Blue_Marble_2021.png', 'Blue_Marble_2022.jpg', 'Blue_Marble_Comparsion.png', 'Blue_Marble_Eastern_Hemisphere.jpg', 'Blue_Marble_Western_Hemisphere.jpg', 'Blue_Marble_transparent.png', 'The_Blue_Marble.jpg', 'The_Blue_Marble_(5052124705).jpg', 'The_Blue_Marble_White_Balancing.jpg', 'The_Earth_seen_from_Apollo_17.jpg']. But this is only 10 file names. When I type blue marble into wikimedia commons image search, hundreds of results come up. How can I get all the image file names?
|
[
"MediaWiki API queries are paginated. This means that each API call will return a maximum number of results, and you will need to include additional parameters in subsequent requests in order to retrieve the remaining results.\nThe official documentation has an example that demonstrates how to submit the continuation requests.\nSince you are already importing requests, I would suggest using that library instead of urllib.request.urlopen for this. You definitely should not be using BeautifulSoup to parse these responses - you can specify format=json and use json instead.\nIt will be easier to handle the continuation requests if you use a dictionary for the query params instead of manually crafting a string.\nExample using Requests:\ndef get_image_names(pic_search):\n session = requests.Session()\n url = 'https://commons.wikimedia.org/w/api.php'\n params = {\n 'action': 'query',\n 'prop': 'imageinfo|categories',\n 'generator': 'search',\n 'gsrsearch': f'File:{pic_search}',\n 'format': 'json',\n 'origin': '*',\n 'iiprop': 'extmetadata',\n 'iiextmetadatafilter': 'ImageDescription|ObjectName',\n 'formatversion': 2, # only if the target wiki is running mediawiki 1.25 or above\n }\n resp = session.get(url, params=params).json()\n names = [page['title'] for page in resp['query']['pages']]\n continue_params = resp.get('continue')\n while continue_params:\n params.update(continue_params)\n resp = session.get(url, params=params).json()\n names.extend(page['title'] for page in resp['query']['pages'])\n continue_params = resp.get('continue')\n return names\n\n"
] |
[
0
] |
[] |
[] |
[
"image",
"python",
"wikimedia_commons"
] |
stackoverflow_0074495385_image_python_wikimedia_commons.txt
|
Q:
How to change a dataframe column from String type to Double type in PySpark?
I have a dataframe with column as String.
I wanted to change the column type to Double type in PySpark.
Following is the way, I did:
toDoublefunc = UserDefinedFunction(lambda x: x,DoubleType())
changedTypedf = joindf.withColumn("label",toDoublefunc(joindf['show']))
Just wanted to know, is this the right way to do it as while running
through Logistic Regression, I am getting some error, so I wonder,
is this the reason for the trouble.
A:
There is no need for an UDF here. Column already provides cast method with DataType instance :
from pyspark.sql.types import DoubleType
changedTypedf = joindf.withColumn("label", joindf["show"].cast(DoubleType()))
or short string:
changedTypedf = joindf.withColumn("label", joindf["show"].cast("double"))
where canonical string names (other variations can be supported as well) correspond to simpleString value. So for atomic types:
from pyspark.sql import types
for t in ['BinaryType', 'BooleanType', 'ByteType', 'DateType',
'DecimalType', 'DoubleType', 'FloatType', 'IntegerType',
'LongType', 'ShortType', 'StringType', 'TimestampType']:
print(f"{t}: {getattr(types, t)().simpleString()}")
BinaryType: binary
BooleanType: boolean
ByteType: tinyint
DateType: date
DecimalType: decimal(10,0)
DoubleType: double
FloatType: float
IntegerType: int
LongType: bigint
ShortType: smallint
StringType: string
TimestampType: timestamp
and for example complex types
types.ArrayType(types.IntegerType()).simpleString()
'array<int>'
types.MapType(types.StringType(), types.IntegerType()).simpleString()
'map<string,int>'
A:
Preserve the name of the column and avoid extra column addition by using the same name as input column:
from pyspark.sql.types import DoubleType
changedTypedf = joindf.withColumn("show", joindf["show"].cast(DoubleType()))
A:
Given answers are enough to deal with the problem but I want to share another way which may be introduced the new version of Spark (I am not sure about it) so given answer didn't catch it.
We can reach the column in spark statement with col("colum_name") keyword:
from pyspark.sql.functions import col
changedTypedf = joindf.withColumn("show", col("show").cast("double"))
A:
PySpark version:
df = <source data>
df.printSchema()
from pyspark.sql.types import *
# Change column type
df_new = df.withColumn("myColumn", df["myColumn"].cast(IntegerType()))
df_new.printSchema()
df_new.select("myColumn").show()
A:
the solution was simple -
toDoublefunc = UserDefinedFunction(lambda x: float(x),DoubleType())
changedTypedf = joindf.withColumn("label",toDoublefunc(joindf['show']))
A:
One issue with other answers (depending on your version of Pyspark) is usage of withColumn. Performance issues have been observed at least in v2.4.4 (see this thread). The spark docs mention this about withColumn:
this method introduces a projection internally. Therefore, calling it multiple times, for instance, via loops in order to add multiple columns can generate big plans which can cause performance issues and even StackOverflowException. To avoid this, use select with the multiple columns at once.
One way to achieve the recommended usage of select instead in general would be:
from pyspark.sql.types import *
from pyspark.sql import functions as F
cols_to_fix = ['show']
other_cols = [col for col in joindf.columns if not col in cols_to_fix]
joindf = joindf.select(
*other_cols,
F.col('show').cast(DoubleType())
)
|
How to change a dataframe column from String type to Double type in PySpark?
|
I have a dataframe with column as String.
I wanted to change the column type to Double type in PySpark.
Following is the way, I did:
toDoublefunc = UserDefinedFunction(lambda x: x,DoubleType())
changedTypedf = joindf.withColumn("label",toDoublefunc(joindf['show']))
Just wanted to know, is this the right way to do it as while running
through Logistic Regression, I am getting some error, so I wonder,
is this the reason for the trouble.
|
[
"There is no need for an UDF here. Column already provides cast method with DataType instance :\nfrom pyspark.sql.types import DoubleType\n\nchangedTypedf = joindf.withColumn(\"label\", joindf[\"show\"].cast(DoubleType()))\n\nor short string:\nchangedTypedf = joindf.withColumn(\"label\", joindf[\"show\"].cast(\"double\"))\n\nwhere canonical string names (other variations can be supported as well) correspond to simpleString value. So for atomic types:\nfrom pyspark.sql import types \n\nfor t in ['BinaryType', 'BooleanType', 'ByteType', 'DateType', \n 'DecimalType', 'DoubleType', 'FloatType', 'IntegerType', \n 'LongType', 'ShortType', 'StringType', 'TimestampType']:\n print(f\"{t}: {getattr(types, t)().simpleString()}\")\n\nBinaryType: binary\nBooleanType: boolean\nByteType: tinyint\nDateType: date\nDecimalType: decimal(10,0)\nDoubleType: double\nFloatType: float\nIntegerType: int\nLongType: bigint\nShortType: smallint\nStringType: string\nTimestampType: timestamp\n\nand for example complex types\ntypes.ArrayType(types.IntegerType()).simpleString() \n\n'array<int>'\n\ntypes.MapType(types.StringType(), types.IntegerType()).simpleString()\n\n'map<string,int>'\n\n",
"Preserve the name of the column and avoid extra column addition by using the same name as input column:\nfrom pyspark.sql.types import DoubleType\nchangedTypedf = joindf.withColumn(\"show\", joindf[\"show\"].cast(DoubleType()))\n\n",
"Given answers are enough to deal with the problem but I want to share another way which may be introduced the new version of Spark (I am not sure about it) so given answer didn't catch it.\nWe can reach the column in spark statement with col(\"colum_name\") keyword:\nfrom pyspark.sql.functions import col\nchangedTypedf = joindf.withColumn(\"show\", col(\"show\").cast(\"double\"))\n\n",
"PySpark version:\ndf = <source data>\ndf.printSchema()\n\nfrom pyspark.sql.types import *\n\n# Change column type\ndf_new = df.withColumn(\"myColumn\", df[\"myColumn\"].cast(IntegerType()))\ndf_new.printSchema()\ndf_new.select(\"myColumn\").show()\n\n",
"the solution was simple -\ntoDoublefunc = UserDefinedFunction(lambda x: float(x),DoubleType())\nchangedTypedf = joindf.withColumn(\"label\",toDoublefunc(joindf['show']))\n\n",
"One issue with other answers (depending on your version of Pyspark) is usage of withColumn. Performance issues have been observed at least in v2.4.4 (see this thread). The spark docs mention this about withColumn:\n\nthis method introduces a projection internally. Therefore, calling it multiple times, for instance, via loops in order to add multiple columns can generate big plans which can cause performance issues and even StackOverflowException. To avoid this, use select with the multiple columns at once.\n\nOne way to achieve the recommended usage of select instead in general would be:\nfrom pyspark.sql.types import *\nfrom pyspark.sql import functions as F\n\ncols_to_fix = ['show']\nother_cols = [col for col in joindf.columns if not col in cols_to_fix]\njoindf = joindf.select(\n *other_cols,\n F.col('show').cast(DoubleType())\n)\n\n"
] |
[
254,
77,
15,
6,
1,
0
] |
[] |
[] |
[
"apache_spark",
"apache_spark_sql",
"dataframe",
"pyspark",
"python"
] |
stackoverflow_0032284620_apache_spark_apache_spark_sql_dataframe_pyspark_python.txt
|
Q:
How to fit multiple gaussians on one plot?
I'm interested in fitting multiple Gaussian curves to the plot below in python. I need to be able to determine the mean of each gaussian to be able to estimate what 1 photoelectron corresponds to for a signal reading device that took this data. I need to know how to do this for an undetermined amount of peaks as each dataset might contain fewer / more photoelectron peaks. Any help would be appreciated!
Looked into gaussian mixtures, but couldn't find how to extract the individual Gaussians that fit the overall curve.
A:
I suppose you're using Gaussian Mixture Model from sklearn.
In that case from the docs
import numpy as np
from sklearn.mixture import GaussianMixture
X = np.array([[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]])
gm = GaussianMixture(n_components=2, random_state=0).fit(X)
The attributes gm.means_ are the means of each mixture component.
And gm.covariances_ are the covariance (or variance for 1D) of each mixture component.
With those (using a for) you can easily plot each component using, for example, something like bellow for the first component:
from scipy.stats import norm
from matplotlib import pyplot as plt
import numpy as np
x = np.linspace(...) # your x space sampled
p = norm.pdf(x, gm.means_[0], gm.covariances_[0])
plt.plot(x, p)
And you can even sum them up, as you wish, to make a combined plot of their pdf's.
|
How to fit multiple gaussians on one plot?
|
I'm interested in fitting multiple Gaussian curves to the plot below in python. I need to be able to determine the mean of each gaussian to be able to estimate what 1 photoelectron corresponds to for a signal reading device that took this data. I need to know how to do this for an undetermined amount of peaks as each dataset might contain fewer / more photoelectron peaks. Any help would be appreciated!
Looked into gaussian mixtures, but couldn't find how to extract the individual Gaussians that fit the overall curve.
|
[
"I suppose you're using Gaussian Mixture Model from sklearn.\nIn that case from the docs\nimport numpy as np\nfrom sklearn.mixture import GaussianMixture\nX = np.array([[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]])\ngm = GaussianMixture(n_components=2, random_state=0).fit(X)\n\nThe attributes gm.means_ are the means of each mixture component.\nAnd gm.covariances_ are the covariance (or variance for 1D) of each mixture component.\nWith those (using a for) you can easily plot each component using, for example, something like bellow for the first component:\nfrom scipy.stats import norm\nfrom matplotlib import pyplot as plt \nimport numpy as np\n\nx = np.linspace(...) # your x space sampled\np = norm.pdf(x, gm.means_[0], gm.covariances_[0])\nplt.plot(x, p)\n\nAnd you can even sum them up, as you wish, to make a combined plot of their pdf's.\n"
] |
[
0
] |
[] |
[] |
[
"gaussian_mixture_model",
"python",
"scikit_learn",
"statistics"
] |
stackoverflow_0074495113_gaussian_mixture_model_python_scikit_learn_statistics.txt
|
Q:
list of lists coordinates to a list of coordinates with space for SVG file
I have a list
my_list = [[200.0, 10.0], [250.0, 190.0], [160.0, 210.0]]
I want get the list of these coordinate with space between them
req_list = "200,10 250,190 160,210"
to write these in SVG format for polygons.
I tried replacing "[]" with " " but replace doesn't work for an array
my_list.replace("[", " ")
A:
You can use str.join to the sublists:
my_list = [[200.0, 10.0], [250.0, 190.0], [160.0, 210.0]]
req_list = " ".join(",".join(f"{int(v)}" for v in l) for l in my_list)
print(req_list)
Prints:
200,10 250,190 160,210
A:
You can iterate through the list and append them into an empty string defined, for example:
req_list = ""
for cor in my_list:
req_list += '{},{} '.format(int(cor[0]),int(cor[1]))
print(req_list[:-1])
Prints:
200,10 250,190 160,210
Indexed till -1 is to ignore the last white space.
|
list of lists coordinates to a list of coordinates with space for SVG file
|
I have a list
my_list = [[200.0, 10.0], [250.0, 190.0], [160.0, 210.0]]
I want get the list of these coordinate with space between them
req_list = "200,10 250,190 160,210"
to write these in SVG format for polygons.
I tried replacing "[]" with " " but replace doesn't work for an array
my_list.replace("[", " ")
|
[
"You can use str.join to the sublists:\nmy_list = [[200.0, 10.0], [250.0, 190.0], [160.0, 210.0]]\n\nreq_list = \" \".join(\",\".join(f\"{int(v)}\" for v in l) for l in my_list)\nprint(req_list)\n\nPrints:\n200,10 250,190 160,210\n\n",
"You can iterate through the list and append them into an empty string defined, for example:\nreq_list = \"\"\nfor cor in my_list:\n req_list += '{},{} '.format(int(cor[0]),int(cor[1]))\nprint(req_list[:-1])\n\nPrints:\n200,10 250,190 160,210\n\nIndexed till -1 is to ignore the last white space.\n"
] |
[
1,
1
] |
[] |
[] |
[
"list",
"python",
"python_3.x"
] |
stackoverflow_0074495642_list_python_python_3.x.txt
|
Q:
non sequitur, should be quick fix. why is y=2, (y==int() False)what did I miss:
I just typed this into IDLE shell.
maybe somethigns up with it? or it was a snake and it bit me ( as the saying goes)
the statement is:
y=2
y==int()
output:
false
I even tried:
y=23
type(y)
output:
<class 'int'>
input:
y==int()
output:
False
what am I missing?
hoping to learn something here
A:
Type in print(int()) into your shell. It will print 0. Since 0 != 2, y != int().
You likely want either:
type(y) == int
type(y) is int
or
isinstance(y, int)
with the latter being better practice than the former, because it works with class inheritance (thanks to @dskrypa for his comment).
Note: From the documentation, if int is called without arguments, it will return 0. This is because int() is declared as:
class int(x=0)
|
non sequitur, should be quick fix. why is y=2, (y==int() False)what did I miss:
|
I just typed this into IDLE shell.
maybe somethigns up with it? or it was a snake and it bit me ( as the saying goes)
the statement is:
y=2
y==int()
output:
false
I even tried:
y=23
type(y)
output:
<class 'int'>
input:
y==int()
output:
False
what am I missing?
hoping to learn something here
|
[
"Type in print(int()) into your shell. It will print 0. Since 0 != 2, y != int().\nYou likely want either:\ntype(y) == int\n\ntype(y) is int\n\nor\nisinstance(y, int)\n\nwith the latter being better practice than the former, because it works with class inheritance (thanks to @dskrypa for his comment).\nNote: From the documentation, if int is called without arguments, it will return 0. This is because int() is declared as:\nclass int(x=0)\n\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074495769_python.txt
|
Q:
Python code is not syntax highlighted in Pycharm notebook?
In the screenshot we see a pretty normal-ish python code cell within the Pycharm notebook viewer The viewer "understands" the notebook: it is bringing up the managed Jupyter server option and knows this is [python] code:
So then where did the syntax highlighting go to? How can it be [re-]enabled ?
A:
@Wayne was headed the right direction: that link he provided Wrong Code Highlighting in Jupyter Notebooks had suggestion to reload the python interpreter.
Well in my case the interpreter is Synapse Pyspark and is grayed out since i'm presently running locally. I need to figure out how to change the interpreter: will update here at that point.
Update I needed to edit the json source of the ipynb file to find and remove the synapse kernel.
|
Python code is not syntax highlighted in Pycharm notebook?
|
In the screenshot we see a pretty normal-ish python code cell within the Pycharm notebook viewer The viewer "understands" the notebook: it is bringing up the managed Jupyter server option and knows this is [python] code:
So then where did the syntax highlighting go to? How can it be [re-]enabled ?
|
[
"@Wayne was headed the right direction: that link he provided Wrong Code Highlighting in Jupyter Notebooks had suggestion to reload the python interpreter.\nWell in my case the interpreter is Synapse Pyspark and is grayed out since i'm presently running locally. I need to figure out how to change the interpreter: will update here at that point.\nUpdate I needed to edit the json source of the ipynb file to find and remove the synapse kernel.\n\n"
] |
[
0
] |
[] |
[] |
[
"jupyter_notebook",
"pycharm",
"python",
"syntax_highlighting"
] |
stackoverflow_0074494641_jupyter_notebook_pycharm_python_syntax_highlighting.txt
|
Q:
Py-cord command won't let go
I have been trying to update my discord bot to discord.py v2.0 and wanted to switch over to slash commands and cogs. When trying different techniques of achieving this I once used py-cord. I created a test command called latency and it worked but since I struggled with py-cord I uninstalled py-cord and found a new technique. The problem is that the latency (my py-cord) command is still there on the list where you can choose what slash command to use and so I wonder how do I remove this from the bot command selection?
A:
When working with slash commands, the discord API registers and deregisters the slash commands on their own servers, and then sets up hooks for your bot.
This means that, when the bot connects, it sends an API call to discord to tell it what commands it has, after which you need to wait for Discord to register that properly. They don't guarantee to do that instantly, not for deletion nor registration.
So, in short, you don't remove it from the bot section; you wait until Discord does that for you. They guarantee that they do that in 24 hours of your bot being online, but, realistically, it's usually done in less than 2.
You can set debug_guilds if you want to register commands faster, which would allow you to have a few guilds (servers) that would get updated first, usually quite close to immediately. However, from my own experience, that helped very little for deletion, as Discord usually took its time for that.
One more advantage of debug_guilds is that, when passed, any new or deleted commands are only registered for those specific guilds, allowing you for more free testing. However, it is not perfect, as changed excising commands are of course still run trough your testing bot.
Instead, my advice would be this: Create a second bot, and use that one for testing stuff. Once it's done, you can update the new bot with the verified code. This way, no one gets annoyed at multiple registered commands and all that! If you know how to use git: just run one bot on the main branch, and the other on the development branch. :-)
I hope this helps! :-)
|
Py-cord command won't let go
|
I have been trying to update my discord bot to discord.py v2.0 and wanted to switch over to slash commands and cogs. When trying different techniques of achieving this I once used py-cord. I created a test command called latency and it worked but since I struggled with py-cord I uninstalled py-cord and found a new technique. The problem is that the latency (my py-cord) command is still there on the list where you can choose what slash command to use and so I wonder how do I remove this from the bot command selection?
|
[
"When working with slash commands, the discord API registers and deregisters the slash commands on their own servers, and then sets up hooks for your bot.\nThis means that, when the bot connects, it sends an API call to discord to tell it what commands it has, after which you need to wait for Discord to register that properly. They don't guarantee to do that instantly, not for deletion nor registration.\nSo, in short, you don't remove it from the bot section; you wait until Discord does that for you. They guarantee that they do that in 24 hours of your bot being online, but, realistically, it's usually done in less than 2.\nYou can set debug_guilds if you want to register commands faster, which would allow you to have a few guilds (servers) that would get updated first, usually quite close to immediately. However, from my own experience, that helped very little for deletion, as Discord usually took its time for that.\nOne more advantage of debug_guilds is that, when passed, any new or deleted commands are only registered for those specific guilds, allowing you for more free testing. However, it is not perfect, as changed excising commands are of course still run trough your testing bot.\nInstead, my advice would be this: Create a second bot, and use that one for testing stuff. Once it's done, you can update the new bot with the verified code. This way, no one gets annoyed at multiple registered commands and all that! If you know how to use git: just run one bot on the main branch, and the other on the development branch. :-)\nI hope this helps! :-)\n"
] |
[
2
] |
[] |
[] |
[
"discord",
"discord.py",
"pycord",
"python"
] |
stackoverflow_0074495649_discord_discord.py_pycord_python.txt
|
Q:
Multi-label classification predicting exactly n out of m options
Say I have m objects and I want to pick which n will be chosen (where m and n are both known). I could run multi-label classification and get the probability that each of the m is chosen and take the n most likely, but that ignores the correlation between items. I'm wondering if there is a modeling approach (ideally in Keras?) that considers the correlations.
For example, suppose a soccer team has 18 players and I'm trying to predict which 11 will start the next game. The 11 players who are individually most likely to start do not necessarily comprise the most likely group of 11 players to start. For instance, maybe the team has two goalkeepers, each of whom has a 50% chance of starting, but no configuration will start both of them.
One option is to predict the set of 11 directly, but that would be multiclass categorization problem with (18 choose 11) cases... Any thoughts on better routes?
A:
Seems kind of similar to a language model where you want to predict the most likely sentence. If you have the output probabilities for all words, you wouldn't just pick the n likeliest since the sentence would probably make no sense. Instead you condition it on the words you've already chosen.
So in your case, the input would include the already selected players. Each pass through the model you add the player with the highest output to the team. To increase the quality you may also want to use beam search, where you keep the best k teams each pass through.
|
Multi-label classification predicting exactly n out of m options
|
Say I have m objects and I want to pick which n will be chosen (where m and n are both known). I could run multi-label classification and get the probability that each of the m is chosen and take the n most likely, but that ignores the correlation between items. I'm wondering if there is a modeling approach (ideally in Keras?) that considers the correlations.
For example, suppose a soccer team has 18 players and I'm trying to predict which 11 will start the next game. The 11 players who are individually most likely to start do not necessarily comprise the most likely group of 11 players to start. For instance, maybe the team has two goalkeepers, each of whom has a 50% chance of starting, but no configuration will start both of them.
One option is to predict the set of 11 directly, but that would be multiclass categorization problem with (18 choose 11) cases... Any thoughts on better routes?
|
[
"Seems kind of similar to a language model where you want to predict the most likely sentence. If you have the output probabilities for all words, you wouldn't just pick the n likeliest since the sentence would probably make no sense. Instead you condition it on the words you've already chosen.\nSo in your case, the input would include the already selected players. Each pass through the model you add the player with the highest output to the team. To increase the quality you may also want to use beam search, where you keep the best k teams each pass through.\n"
] |
[
0
] |
[] |
[] |
[
"classification",
"deep_learning",
"keras",
"neural_network",
"python"
] |
stackoverflow_0074493406_classification_deep_learning_keras_neural_network_python.txt
|
Q:
Kivy Python - getting "FileNotFoundError: [Errno 2] No such file or directory: 'unzip'"
I tried to create an APK file by using WSL and get this:
# Unpacking Android NDK
# Run ['unzip', '-q', '/home/tarpetos/.buildozer/android/platform/android-ndk-r23b-linux.zip']
# Cwd /home/tarpetos/.buildozer/android/platform
Traceback (most recent call last):
File "/usr/local/bin/buildozer", line 11, in <module>
load_entry_point('buildozer==1.4.1.dev0', 'console_scripts', 'buildozer')()
File "/usr/local/lib/python3.8/dist-packages/buildozer-1.4.1.dev0-py3.8.egg/buildozer/scripts/client.py", line 13, in main
Buildozer().run_command(sys.argv[1:])
File "/usr/local/lib/python3.8/dist-packages/buildozer-1.4.1.dev0-py3.8.egg/buildozer/__init__.py", line 1024, in run_command
self.target.run_commands(args)
File "/usr/local/lib/python3.8/dist-packages/buildozer-1.4.1.dev0-py3.8.egg/buildozer/target.py", line 93, in run_commands
func(args)
File "/usr/local/lib/python3.8/dist-packages/buildozer-1.4.1.dev0-py3.8.egg/buildozer/target.py", line 103, in cmd_debug
self.buildozer.prepare_for_build()
File "/usr/local/lib/python3.8/dist-packages/buildozer-1.4.1.dev0-py3.8.egg/buildozer/__init__.py", line 172, in prepare_for_build
self.target.install_platform()
File "/usr/local/lib/python3.8/dist-packages/buildozer-1.4.1.dev0-py3.8.egg/buildozer/targets/android.py", line 701, in install_platform
self._install_android_ndk()
File "/usr/local/lib/python3.8/dist-packages/buildozer-1.4.1.dev0-py3.8.egg/buildozer/targets/android.py", line 497, in _install_android_ndk
self.buildozer.file_extract(archive,
File "/usr/local/lib/python3.8/dist-packages/buildozer-1.4.1.dev0-py3.8.egg/buildozer/__init__.py", line 616, in file_extract
self.cmd(["unzip", "-q", join(cwd, archive)], cwd=cwd)
File "/usr/local/lib/python3.8/dist-packages/buildozer-1.4.1.dev0-py3.8.egg/buildozer/__init__.py", line 289, in cmd
process = Popen(command, **kwargs)
File "/usr/lib/python3.8/subprocess.py", line 858, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.8/subprocess.py", line 1704, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'unzip'
I have a main.py file and a connection_voice.ogg file in the same directory and at first I thought the problem was connecting the audio file. But now I understand that the problem is not in the audio file.
music = SoundLoader.load('connection_voice.ogg')
if music:
music.play()
And I don't understand what an 'unzip' file or directory is. Please give some advice
A:
So, to solve this you need to enter to terminal sudo apt-get install unzip. And than this problem will be solved.
|
Kivy Python - getting "FileNotFoundError: [Errno 2] No such file or directory: 'unzip'"
|
I tried to create an APK file by using WSL and get this:
# Unpacking Android NDK
# Run ['unzip', '-q', '/home/tarpetos/.buildozer/android/platform/android-ndk-r23b-linux.zip']
# Cwd /home/tarpetos/.buildozer/android/platform
Traceback (most recent call last):
File "/usr/local/bin/buildozer", line 11, in <module>
load_entry_point('buildozer==1.4.1.dev0', 'console_scripts', 'buildozer')()
File "/usr/local/lib/python3.8/dist-packages/buildozer-1.4.1.dev0-py3.8.egg/buildozer/scripts/client.py", line 13, in main
Buildozer().run_command(sys.argv[1:])
File "/usr/local/lib/python3.8/dist-packages/buildozer-1.4.1.dev0-py3.8.egg/buildozer/__init__.py", line 1024, in run_command
self.target.run_commands(args)
File "/usr/local/lib/python3.8/dist-packages/buildozer-1.4.1.dev0-py3.8.egg/buildozer/target.py", line 93, in run_commands
func(args)
File "/usr/local/lib/python3.8/dist-packages/buildozer-1.4.1.dev0-py3.8.egg/buildozer/target.py", line 103, in cmd_debug
self.buildozer.prepare_for_build()
File "/usr/local/lib/python3.8/dist-packages/buildozer-1.4.1.dev0-py3.8.egg/buildozer/__init__.py", line 172, in prepare_for_build
self.target.install_platform()
File "/usr/local/lib/python3.8/dist-packages/buildozer-1.4.1.dev0-py3.8.egg/buildozer/targets/android.py", line 701, in install_platform
self._install_android_ndk()
File "/usr/local/lib/python3.8/dist-packages/buildozer-1.4.1.dev0-py3.8.egg/buildozer/targets/android.py", line 497, in _install_android_ndk
self.buildozer.file_extract(archive,
File "/usr/local/lib/python3.8/dist-packages/buildozer-1.4.1.dev0-py3.8.egg/buildozer/__init__.py", line 616, in file_extract
self.cmd(["unzip", "-q", join(cwd, archive)], cwd=cwd)
File "/usr/local/lib/python3.8/dist-packages/buildozer-1.4.1.dev0-py3.8.egg/buildozer/__init__.py", line 289, in cmd
process = Popen(command, **kwargs)
File "/usr/lib/python3.8/subprocess.py", line 858, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.8/subprocess.py", line 1704, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'unzip'
I have a main.py file and a connection_voice.ogg file in the same directory and at first I thought the problem was connecting the audio file. But now I understand that the problem is not in the audio file.
music = SoundLoader.load('connection_voice.ogg')
if music:
music.play()
And I don't understand what an 'unzip' file or directory is. Please give some advice
|
[
"So, to solve this you need to enter to terminal sudo apt-get install unzip. And than this problem will be solved.\n"
] |
[
0
] |
[] |
[] |
[
"android",
"filenotfounderror",
"kivy",
"python"
] |
stackoverflow_0074495652_android_filenotfounderror_kivy_python.txt
|
Q:
How to set the default value for float in sqlalchemy?
Using Flask-SQLAlchemy. I wish to set a default value for a property on a model:
priority = sa.Column(sa.Float, server_default='0.5')
But it does not get set in table:
priority double precision,
A:
i had the same problem, this is what i used to solve it.
server_default=u'0.5'
|
How to set the default value for float in sqlalchemy?
|
Using Flask-SQLAlchemy. I wish to set a default value for a property on a model:
priority = sa.Column(sa.Float, server_default='0.5')
But it does not get set in table:
priority double precision,
|
[
"i had the same problem, this is what i used to solve it.\nserver_default=u'0.5'\n\n"
] |
[
1
] |
[] |
[] |
[
"flask",
"flask_sqlalchemy",
"python",
"sqlalchemy"
] |
stackoverflow_0031558023_flask_flask_sqlalchemy_python_sqlalchemy.txt
|
Q:
Error while using numpy random.normalvariate()
I tried to generate random probs by using the following line code:
probs = [np.clip(random.normalvariate(0.1, 0.05), 0, 1) for x in range(1000)]
Unexpectedly I faced the following error message:
AttributeError: module 'numpy.random' has no attribute 'normalvariate'
Any idea how to solve this? I checked out the docs I find that this attribute exists in the numpy.random however it doesn't work when I used it in above code.
Any help to fix this issue will be appreciated.
A:
It seems that you make confusion between random module whose documenttion is : https://docs.python.org/3.11/library/random.html
And random sub-module that belongs to numpy, its documentation can be found here https://numpy.org/doc/stable/reference/random/index.html
Error origin
It seems that you imported numpy.random and you tried to use normalvariate while the latter function belongs to random module.
Solution
So to solve the issue write the following import:
import random
probs = [np.clip(random.normalvariate(0.1, 0.05), 0, 1) for x in range(1000)]
Output:
[0.10399310517618868,
0.10416076922742254,
0.10683877729386676,
0.14789317007499886,
0.11551976284566698,
...
|
Error while using numpy random.normalvariate()
|
I tried to generate random probs by using the following line code:
probs = [np.clip(random.normalvariate(0.1, 0.05), 0, 1) for x in range(1000)]
Unexpectedly I faced the following error message:
AttributeError: module 'numpy.random' has no attribute 'normalvariate'
Any idea how to solve this? I checked out the docs I find that this attribute exists in the numpy.random however it doesn't work when I used it in above code.
Any help to fix this issue will be appreciated.
|
[
"It seems that you make confusion between random module whose documenttion is : https://docs.python.org/3.11/library/random.html\nAnd random sub-module that belongs to numpy, its documentation can be found here https://numpy.org/doc/stable/reference/random/index.html\nError origin\nIt seems that you imported numpy.random and you tried to use normalvariate while the latter function belongs to random module.\nSolution\nSo to solve the issue write the following import:\nimport random\n\nprobs = [np.clip(random.normalvariate(0.1, 0.05), 0, 1) for x in range(1000)]\n\nOutput:\n[0.10399310517618868,\n 0.10416076922742254,\n 0.10683877729386676,\n 0.14789317007499886,\n 0.11551976284566698,\n...\n\n"
] |
[
-1
] |
[] |
[] |
[
"numpy",
"python",
"random"
] |
stackoverflow_0074495445_numpy_python_random.txt
|
Q:
Python selenium timeout exception without message when clicking
I want to search specific word in ScienceDirect and when is shows results I want to click 100 result per page at the bottom on page.
HTML code:
<a class="anchor" data-aa-region="srp-pagination-options" data-aa-name="srp-100-results-per-page" href="/search?qs=Python&show=100"><span class="anchor-text">100</span></a>
And that's my code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("https://www.sciencedirect.com/")
assert "Science" in driver.title
elem = driver.find_element(By.ID, "qs-searchbox-input")
elem.clear()
elem.send_keys("Python")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, ".data-aa-name[value='srp-100-results-per-page']"))
)
element.click()
driver.close()
And exception:
Traceback (most recent call last):
File "X:\pythonProject\selenium\count_cited.py", line 15, in <module>
element = WebDriverWait(driver, 10).until(
File "X:\pythonProject\selenium\venv\lib\site-packages\selenium\webdriver\support\wait.py", line 95, in until
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:
A:
Use for example this CSS selector:
"div#srp-pagination-options li:nth-child(3)"
|
Python selenium timeout exception without message when clicking
|
I want to search specific word in ScienceDirect and when is shows results I want to click 100 result per page at the bottom on page.
HTML code:
<a class="anchor" data-aa-region="srp-pagination-options" data-aa-name="srp-100-results-per-page" href="/search?qs=Python&show=100"><span class="anchor-text">100</span></a>
And that's my code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("https://www.sciencedirect.com/")
assert "Science" in driver.title
elem = driver.find_element(By.ID, "qs-searchbox-input")
elem.clear()
elem.send_keys("Python")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, ".data-aa-name[value='srp-100-results-per-page']"))
)
element.click()
driver.close()
And exception:
Traceback (most recent call last):
File "X:\pythonProject\selenium\count_cited.py", line 15, in <module>
element = WebDriverWait(driver, 10).until(
File "X:\pythonProject\selenium\venv\lib\site-packages\selenium\webdriver\support\wait.py", line 95, in until
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:
|
[
"Use for example this CSS selector:\n \"div#srp-pagination-options li:nth-child(3)\"\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"selenium"
] |
stackoverflow_0074493243_python_selenium.txt
|
Q:
Replace dataframe null values with dictionary in Python
I have a dataframe (really big) what have some null values and I can replaces them because there are two columns: Name and Weight, Name appears many times, sometimes with weight, sometimes not. This is a little example and what I tried for solve it.
First I created the dataframe:
import pandas as pd
import numpy as np
lst1 = ["AA","BB","CC","AA","BB","CC","AA","BB","CC"]
lst2 = [12,np.nan,14,12,15,14,np.nan,np.nan,14]
df = pd.DataFrame(list(zip(lst1,lst2)), columns = ['Name','Weight'])
Next I found the weight values for every name with a dictionary:
df_2 = df.groupby('Name')['Weight'].max()
dic = df_2.to_dict()
Finally I created a loop for replaces it all:
for k,v in dic:
for i in range(len(df)):
if df['Weight'][i] == None and k == df['Name'][i]:
df['Weight'][i] = v
else:
print(df)
But it returns the same dataframe and I don't know what more doing.
I'll really thanks you if you could help me or give an advice. :)
A:
Maybe you can fill the NaNs in .groupby:
df["Weight"] = df.groupby("Name", group_keys=False)["Weight"].apply(
lambda x: x.fillna(x.max())
)
print(df)
Prints:
Name Weight
0 AA 12.0
1 BB 15.0
2 CC 14.0
3 AA 12.0
4 BB 15.0
5 CC 14.0
6 AA 12.0
7 BB 15.0
8 CC 14.0
OR:
x = df.groupby("Name")["Weight"].max()
df = df.set_index("Name")
df["Weight"] = df["Weight"].fillna(x)
df = df.reset_index()
print(df)
Prints:
Name Weight
0 AA 12.0
1 BB 15.0
2 CC 14.0
3 AA 12.0
4 BB 15.0
5 CC 14.0
6 AA 12.0
7 BB 15.0
8 CC 14.0
|
Replace dataframe null values with dictionary in Python
|
I have a dataframe (really big) what have some null values and I can replaces them because there are two columns: Name and Weight, Name appears many times, sometimes with weight, sometimes not. This is a little example and what I tried for solve it.
First I created the dataframe:
import pandas as pd
import numpy as np
lst1 = ["AA","BB","CC","AA","BB","CC","AA","BB","CC"]
lst2 = [12,np.nan,14,12,15,14,np.nan,np.nan,14]
df = pd.DataFrame(list(zip(lst1,lst2)), columns = ['Name','Weight'])
Next I found the weight values for every name with a dictionary:
df_2 = df.groupby('Name')['Weight'].max()
dic = df_2.to_dict()
Finally I created a loop for replaces it all:
for k,v in dic:
for i in range(len(df)):
if df['Weight'][i] == None and k == df['Name'][i]:
df['Weight'][i] = v
else:
print(df)
But it returns the same dataframe and I don't know what more doing.
I'll really thanks you if you could help me or give an advice. :)
|
[
"Maybe you can fill the NaNs in .groupby:\ndf[\"Weight\"] = df.groupby(\"Name\", group_keys=False)[\"Weight\"].apply(\n lambda x: x.fillna(x.max())\n)\nprint(df)\n\nPrints:\n Name Weight\n0 AA 12.0\n1 BB 15.0\n2 CC 14.0\n3 AA 12.0\n4 BB 15.0\n5 CC 14.0\n6 AA 12.0\n7 BB 15.0\n8 CC 14.0\n\n\nOR:\nx = df.groupby(\"Name\")[\"Weight\"].max()\n\ndf = df.set_index(\"Name\")\ndf[\"Weight\"] = df[\"Weight\"].fillna(x)\ndf = df.reset_index()\n\nprint(df)\n\nPrints:\n Name Weight\n0 AA 12.0\n1 BB 15.0\n2 CC 14.0\n3 AA 12.0\n4 BB 15.0\n5 CC 14.0\n6 AA 12.0\n7 BB 15.0\n8 CC 14.0\n\n"
] |
[
1
] |
[] |
[] |
[
"dataframe",
"dictionary",
"loops",
"pandas",
"python"
] |
stackoverflow_0074495757_dataframe_dictionary_loops_pandas_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.