func_code_string stringlengths 52 1.94M | func_documentation_string stringlengths 1 47.2k |
|---|---|
def _get_adaptation_matrix(wp_src, wp_dst, observer, adaptation):
# Get the appropriate transformation matrix, [MsubA].
m_sharp = color_constants.ADAPTATION_MATRICES[adaptation]
# In case the white-points are still input as strings
# Get white-points for illuminant
if isinstance(wp_src, str):
... | Calculate the correct transformation matrix based on origin and target
illuminants. The observer angle must be the same between illuminants.
See colormath.color_constants.ADAPTATION_MATRICES for a list of possible
adaptations.
Detailed conversion documentation is available at:
http://brucelindbloo... |
def apply_chromatic_adaptation(val_x, val_y, val_z, orig_illum, targ_illum,
observer='2', adaptation='bradford'):
# It's silly to have to do this, but some people may want to call this
# function directly, so we'll protect them from messing up upper/lower case.
adaptation... | Applies a chromatic adaptation matrix to convert XYZ values between
illuminants. It is important to recognize that color transformation results
in color errors, determined by how far the original illuminant is from the
target illuminant. For example, D65 to A could result in very high maximum
deviance.
... |
def apply_chromatic_adaptation_on_color(color, targ_illum, adaptation='bradford'):
xyz_x = color.xyz_x
xyz_y = color.xyz_y
xyz_z = color.xyz_z
orig_illum = color.illuminant
targ_illum = targ_illum.lower()
observer = color.observer
adaptation = adaptation.lower()
# Return individual ... | Convenience function to apply an adaptation directly to a Color object. |
def example_lab_to_xyz():
print("=== Simple Example: Lab->XYZ ===")
# Instantiate an Lab color object with the given values.
lab = LabColor(0.903, 16.296, -2.22)
# Show a string representation.
print(lab)
# Convert to XYZ.
xyz = convert_color(lab, XYZColor)
print(xyz)
print("===... | This function shows a simple conversion of an Lab color to an XYZ color. |
def example_lchab_to_lchuv():
print("=== Complex Example: LCHab->LCHuv ===")
# Instantiate an LCHab color object with the given values.
lchab = LCHabColor(0.903, 16.447, 352.252)
# Show a string representation.
print(lchab)
# Convert to LCHuv.
lchuv = convert_color(lchab, LCHuvColor)
... | This function shows very complex chain of conversions in action.
LCHab to LCHuv involves four different calculations, making this the
conversion requiring the most steps. |
def example_lab_to_rgb():
print("=== RGB Example: Lab->RGB ===")
# Instantiate an Lab color object with the given values.
lab = LabColor(0.903, 16.296, -2.217)
# Show a string representation.
print(lab)
# Convert to XYZ.
rgb = convert_color(lab, sRGBColor)
print(rgb)
print("=== ... | Conversions to RGB are a little more complex mathematically. There are also
several kinds of RGB color spaces. When converting from a device-independent
color space to RGB, sRGB is assumed unless otherwise specified with the
target_rgb keyword arg. |
def example_rgb_to_xyz():
print("=== RGB Example: RGB->XYZ ===")
# Instantiate an Lab color object with the given values.
rgb = sRGBColor(120, 130, 140)
# Show a string representation.
print(rgb)
# Convert RGB to XYZ using a D50 illuminant.
xyz = convert_color(rgb, XYZColor, target_illu... | The reverse is similar. |
def example_spectral_to_xyz():
print("=== Example: Spectral->XYZ ===")
spc = SpectralColor(
observer='2', illuminant='d50',
spec_380nm=0.0600, spec_390nm=0.0600, spec_400nm=0.0641,
spec_410nm=0.0654, spec_420nm=0.0645, spec_430nm=0.0605,
spec_440nm=0.0562, spec_450nm=0.0543,... | Instantiate an Lab color object with the given values. Note that the
spectral range can run from 340nm to 830nm. Any omitted values assume a
value of 0.0, which is more or less ignored. For the distribution below,
we are providing an example reading from an X-Rite i1 Pro, which only
measures between 380... |
def example_lab_to_ipt():
print("=== Simple Example: XYZ->IPT ===")
# Instantiate an XYZ color object with the given values.
xyz = XYZColor(0.5, 0.5, 0.5, illuminant='d65')
# Show a string representation.
print(xyz)
# Convert to IPT.
ipt = convert_color(xyz, IPTColor)
print(ipt)
... | This function shows a simple conversion of an XYZ color to an IPT color. |
def apply_RGB_matrix(var1, var2, var3, rgb_type, convtype="xyz_to_rgb"):
convtype = convtype.lower()
# Retrieve the appropriate transformation matrix from the constants.
rgb_matrix = rgb_type.conversion_matrices[convtype]
logger.debug(" \* Applying RGB conversion matrix: %s->%s",
... | Applies an RGB working matrix to convert from XYZ to RGB.
The arguments are tersely named var1, var2, and var3 to allow for the
passing of XYZ _or_ RGB values. var1 is X for XYZ, and R for RGB. var2 and
var3 follow suite. |
def color_conversion_function(start_type, target_type):
def decorator(f):
f.start_type = start_type
f.target_type = target_type
_conversion_manager.add_type_conversion(start_type, target_type, f)
return f
return decorator | Decorator to indicate a function that performs a conversion from one color
space to another.
This decorator will return the original function unmodified, however it will
be registered in the _conversion_manager so it can be used to perform color
space transformations between color spaces that do not ha... |
def Spectral_to_XYZ(cobj, illuminant_override=None, *args, **kwargs):
# If the user provides an illuminant_override numpy array, use it.
if illuminant_override:
reference_illum = illuminant_override
else:
# Otherwise, look up the illuminant from known standards based
# on the va... | Converts spectral readings to XYZ. |
def Lab_to_LCHab(cobj, *args, **kwargs):
lch_l = cobj.lab_l
lch_c = math.sqrt(
math.pow(float(cobj.lab_a), 2) + math.pow(float(cobj.lab_b), 2))
lch_h = math.atan2(float(cobj.lab_b), float(cobj.lab_a))
if lch_h > 0:
lch_h = (lch_h / math.pi) * 180
else:
lch_h = 360 - (mat... | Convert from CIE Lab to LCH(ab). |
def Lab_to_XYZ(cobj, *args, **kwargs):
illum = cobj.get_illuminant_xyz()
xyz_y = (cobj.lab_l + 16.0) / 116.0
xyz_x = cobj.lab_a / 500.0 + xyz_y
xyz_z = xyz_y - cobj.lab_b / 200.0
if math.pow(xyz_y, 3) > color_constants.CIE_E:
xyz_y = math.pow(xyz_y, 3)
else:
xyz_y = (xyz_y -... | Convert from Lab to XYZ |
def Luv_to_LCHuv(cobj, *args, **kwargs):
lch_l = cobj.luv_l
lch_c = math.sqrt(math.pow(cobj.luv_u, 2.0) + math.pow(cobj.luv_v, 2.0))
lch_h = math.atan2(float(cobj.luv_v), float(cobj.luv_u))
if lch_h > 0:
lch_h = (lch_h / math.pi) * 180
else:
lch_h = 360 - (math.fabs(lch_h) / mat... | Convert from CIE Luv to LCH(uv). |
def Luv_to_XYZ(cobj, *args, **kwargs):
illum = cobj.get_illuminant_xyz()
# Without Light, there is no color. Short-circuit this and avoid some
# zero division errors in the var_a_frac calculation.
if cobj.luv_l <= 0.0:
xyz_x = 0.0
xyz_y = 0.0
xyz_z = 0.0
return XYZCo... | Convert from Luv to XYZ. |
def LCHab_to_Lab(cobj, *args, **kwargs):
lab_l = cobj.lch_l
lab_a = math.cos(math.radians(cobj.lch_h)) * cobj.lch_c
lab_b = math.sin(math.radians(cobj.lch_h)) * cobj.lch_c
return LabColor(
lab_l, lab_a, lab_b, illuminant=cobj.illuminant, observer=cobj.observer) | Convert from LCH(ab) to Lab. |
def LCHuv_to_Luv(cobj, *args, **kwargs):
luv_l = cobj.lch_l
luv_u = math.cos(math.radians(cobj.lch_h)) * cobj.lch_c
luv_v = math.sin(math.radians(cobj.lch_h)) * cobj.lch_c
return LuvColor(
luv_l, luv_u, luv_v, illuminant=cobj.illuminant, observer=cobj.observer) | Convert from LCH(uv) to Luv. |
def xyY_to_XYZ(cobj, *args, **kwargs):
# avoid division by zero
if cobj.xyy_y == 0.0:
xyz_x = 0.0
xyz_y = 0.0
xyz_z = 0.0
else:
xyz_x = (cobj.xyy_x * cobj.xyy_Y) / cobj.xyy_y
xyz_y = cobj.xyy_Y
xyz_z = ((1.0 - cobj.xyy_x - cobj.xyy_y) * xyz_y) / cobj.xyy_... | Convert from xyY to XYZ. |
def XYZ_to_xyY(cobj, *args, **kwargs):
xyz_sum = cobj.xyz_x + cobj.xyz_y + cobj.xyz_z
# avoid division by zero
if xyz_sum == 0.0:
xyy_x = 0.0
xyy_y = 0.0
else:
xyy_x = cobj.xyz_x / xyz_sum
xyy_y = cobj.xyz_y / xyz_sum
xyy_Y = cobj.xyz_y
return xyYColor(
... | Convert from XYZ to xyY. |
def XYZ_to_Luv(cobj, *args, **kwargs):
temp_x = cobj.xyz_x
temp_y = cobj.xyz_y
temp_z = cobj.xyz_z
denom = temp_x + (15.0 * temp_y) + (3.0 * temp_z)
# avoid division by zero
if denom == 0.0:
luv_u = 0.0
luv_v = 0.0
else:
luv_u = (4.0 * temp_x) / denom
luv... | Convert from XYZ to Luv |
def XYZ_to_Lab(cobj, *args, **kwargs):
illum = cobj.get_illuminant_xyz()
temp_x = cobj.xyz_x / illum["X"]
temp_y = cobj.xyz_y / illum["Y"]
temp_z = cobj.xyz_z / illum["Z"]
if temp_x > color_constants.CIE_E:
temp_x = math.pow(temp_x, (1.0 / 3.0))
else:
temp_x = (7.787 * temp_... | Converts XYZ to Lab. |
def XYZ_to_RGB(cobj, target_rgb, *args, **kwargs):
temp_X = cobj.xyz_x
temp_Y = cobj.xyz_y
temp_Z = cobj.xyz_z
logger.debug(" \- Target RGB space: %s", target_rgb)
target_illum = target_rgb.native_illuminant
logger.debug(" \- Target native illuminant: %s", target_illum)
logger.debug("... | XYZ to RGB conversion. |
def RGB_to_XYZ(cobj, target_illuminant=None, *args, **kwargs):
# Will contain linearized RGB channels (removed the gamma func).
linear_channels = {}
if isinstance(cobj, sRGBColor):
for channel in ['r', 'g', 'b']:
V = getattr(cobj, 'rgb_' + channel)
if V <= 0.04045:
... | RGB to XYZ conversion. Expects 0-255 RGB values.
Based off of: http://www.brucelindbloom.com/index.html?Eqn_RGB_to_XYZ.html |
def __RGB_to_Hue(var_R, var_G, var_B, var_min, var_max):
if var_max == var_min:
return 0.0
elif var_max == var_R:
return (60.0 * ((var_G - var_B) / (var_max - var_min)) + 360) % 360.0
elif var_max == var_G:
return 60.0 * ((var_B - var_R) / (var_max - var_min)) + 120
elif var... | For RGB_to_HSL and RGB_to_HSV, the Hue (H) component is calculated in
the same way. |
def RGB_to_HSV(cobj, *args, **kwargs):
var_R = cobj.rgb_r
var_G = cobj.rgb_g
var_B = cobj.rgb_b
var_max = max(var_R, var_G, var_B)
var_min = min(var_R, var_G, var_B)
var_H = __RGB_to_Hue(var_R, var_G, var_B, var_min, var_max)
if var_max == 0:
var_S = 0
else:
var_S = ... | Converts from RGB to HSV.
H values are in degrees and are 0 to 360.
S values are a percentage, 0.0 to 1.0.
V values are a percentage, 0.0 to 1.0. |
def RGB_to_HSL(cobj, *args, **kwargs):
var_R = cobj.rgb_r
var_G = cobj.rgb_g
var_B = cobj.rgb_b
var_max = max(var_R, var_G, var_B)
var_min = min(var_R, var_G, var_B)
var_H = __RGB_to_Hue(var_R, var_G, var_B, var_min, var_max)
var_L = 0.5 * (var_max + var_min)
if var_max == var_min:
... | Converts from RGB to HSL.
H values are in degrees and are 0 to 360.
S values are a percentage, 0.0 to 1.0.
L values are a percentage, 0.0 to 1.0. |
def __Calc_HSL_to_RGB_Components(var_q, var_p, C):
if C < 0:
C += 1.0
if C > 1:
C -= 1.0
# Computing C of vector (Color R, Color G, Color B)
if C < (1.0 / 6.0):
return var_p + ((var_q - var_p) * 6.0 * C)
elif (1.0 / 6.0) <= C < 0.5:
return var_q
elif 0.5 <= C... | This is used in HSL_to_RGB conversions on R, G, and B. |
def HSV_to_RGB(cobj, target_rgb, *args, **kwargs):
H = cobj.hsv_h
S = cobj.hsv_s
V = cobj.hsv_v
h_floored = int(math.floor(H))
h_sub_i = int(h_floored / 60) % 6
var_f = (H / 60.0) - (h_floored // 60)
var_p = V * (1.0 - S)
var_q = V * (1.0 - var_f * S)
var_t = V * (1.0 - (1.0 - v... | HSV to RGB conversion.
H values are in degrees and are 0 to 360.
S values are a percentage, 0.0 to 1.0.
V values are a percentage, 0.0 to 1.0. |
def HSL_to_RGB(cobj, target_rgb, *args, **kwargs):
H = cobj.hsl_h
S = cobj.hsl_s
L = cobj.hsl_l
if L < 0.5:
var_q = L * (1.0 + S)
else:
var_q = L + S - (L * S)
var_p = 2.0 * L - var_q
# H normalized to range [0,1]
h_sub_k = (H / 360.0)
t_sub_R = h_sub_k + (1.0 / ... | HSL to RGB conversion. |
def RGB_to_CMY(cobj, *args, **kwargs):
cmy_c = 1.0 - cobj.rgb_r
cmy_m = 1.0 - cobj.rgb_g
cmy_y = 1.0 - cobj.rgb_b
return CMYColor(cmy_c, cmy_m, cmy_y) | RGB to CMY conversion.
NOTE: CMYK and CMY values range from 0.0 to 1.0 |
def CMY_to_RGB(cobj, target_rgb, *args, **kwargs):
rgb_r = 1.0 - cobj.cmy_c
rgb_g = 1.0 - cobj.cmy_m
rgb_b = 1.0 - cobj.cmy_y
return target_rgb(rgb_r, rgb_g, rgb_b) | Converts CMY to RGB via simple subtraction.
NOTE: Returned values are in the range of 0-255. |
def CMY_to_CMYK(cobj, *args, **kwargs):
var_k = 1.0
if cobj.cmy_c < var_k:
var_k = cobj.cmy_c
if cobj.cmy_m < var_k:
var_k = cobj.cmy_m
if cobj.cmy_y < var_k:
var_k = cobj.cmy_y
if var_k == 1:
cmyk_c = 0.0
cmyk_m = 0.0
cmyk_y = 0.0
else:
... | Converts from CMY to CMYK.
NOTE: CMYK and CMY values range from 0.0 to 1.0 |
def CMYK_to_CMY(cobj, *args, **kwargs):
cmy_c = cobj.cmyk_c * (1.0 - cobj.cmyk_k) + cobj.cmyk_k
cmy_m = cobj.cmyk_m * (1.0 - cobj.cmyk_k) + cobj.cmyk_k
cmy_y = cobj.cmyk_y * (1.0 - cobj.cmyk_k) + cobj.cmyk_k
return CMYColor(cmy_c, cmy_m, cmy_y) | Converts CMYK to CMY.
NOTE: CMYK and CMY values range from 0.0 to 1.0 |
def XYZ_to_IPT(cobj, *args, **kwargs):
if cobj.illuminant != 'd65' or cobj.observer != '2':
raise ValueError('XYZColor for XYZ->IPT conversion needs to be D65 adapted.')
xyz_values = numpy.array(cobj.get_value_tuple())
lms_values = numpy.dot(
IPTColor.conversion_matrices['xyz_to_lms'],
... | Converts XYZ to IPT.
NOTE: XYZ values need to be adapted to 2 degree D65
Reference:
Fairchild, M. D. (2013). Color appearance models, 3rd Ed. (pp. 271-272). John Wiley & Sons. |
def IPT_to_XYZ(cobj, *args, **kwargs):
ipt_values = numpy.array(cobj.get_value_tuple())
lms_values = numpy.dot(
numpy.linalg.inv(IPTColor.conversion_matrices['lms_to_ipt']),
ipt_values)
lms_prime = numpy.sign(lms_values) * numpy.abs(lms_values) ** (1 / 0.43)
xyz_values = numpy.dot(
... | Converts IPT to XYZ. |
def convert_color(color, target_cs, through_rgb_type=sRGBColor,
target_illuminant=None, *args, **kwargs):
if isinstance(target_cs, str):
raise ValueError("target_cs parameter must be a Color object.")
if not issubclass(target_cs, ColorBase):
raise ValueError("target_cs par... | Converts the color to the designated color space.
:param color: A Color instance to convert.
:param target_cs: The Color class to convert to. Note that this is not
an instance, but a class.
:keyword BaseRGBColor through_rgb_type: If during your conversion between
your original and target co... |
def add_type_conversion(self, start_type, target_type, conversion_function):
self.registered_color_spaces.add(start_type)
self.registered_color_spaces.add(target_type)
logger.debug(
'Registered conversion from %s to %s', start_type, target_type) | Register a conversion function between two color spaces.
:param start_type: Starting color space.
:param target_type: Target color space.
:param conversion_function: Conversion function. |
def _adaptation(self, f_l, l_a, xyz, xyz_w, xyz_b, xyz_p=None, p=None, helson_judd=False, discount_illuminant=True):
rgb = self.xyz_to_rgb(xyz)
logger.debug('RGB: {}'.format(rgb))
rgb_w = self.xyz_to_rgb(xyz_w)
logger.debug('RGB_W: {}'.format(rgb_w))
y_w = xyz_w[1]
... | :param f_l: Luminance adaptation factor
:param l_a: Adapting luminance
:param xyz: Stimulus color in XYZ
:param xyz_w: Reference white color in XYZ
:param xyz_b: Background color in XYZ
:param xyz_p: Proxima field color in XYZ
:param p: Simultaneous contrast/assimilation ... |
def adjust_white_for_scc(cls, rgb_p, rgb_b, rgb_w, p):
p_rgb = rgb_p / rgb_b
rgb_w = rgb_w * (((1 - p) * p_rgb + (1 + p) / p_rgb) ** 0.5) / (((1 + p) * p_rgb + (1 - p) / p_rgb) ** 0.5)
return rgb_w | Adjust the white point for simultaneous chromatic contrast.
:param rgb_p: Cone signals of proxima field.
:param rgb_b: Cone signals of background.
:param rgb_w: Cone signals of reference white.
:param p: Simultaneous contrast/assimilation parameter.
:return: Adjusted cone signal... |
def _get_cct(x, y, z):
x_e = 0.3320
y_e = 0.1858
n = ((x / (x + z + z)) - x_e) / ((y / (x + z + z)) - y_e)
a_0 = -949.86315
a_1 = 6253.80338
a_2 = 28.70599
a_3 = 0.00004
t_1 = 0.92159
t_2 = 0.20039
t_3 = 0.07125
cct = a_0 +... | Reference
Hernandez-Andres, J., Lee, R. L., & Romero, J. (1999).
Calculating correlated color temperatures across the entire gamut of daylight and skylight chromaticities.
Applied Optics, 38(27), 5703-5709. |
def _compute_adaptation(self, xyz, xyz_w, f_l, d):
# Transform input colors to cone responses
rgb = self._xyz_to_rgb(xyz)
logger.debug("RGB: {}".format(rgb))
rgb_b = self._xyz_to_rgb(self._xyz_b)
rgb_w = self._xyz_to_rgb(xyz_w)
rgb_w = Hunt.adjust_white_for_scc(r... | Modified adaptation procedure incorporating simultaneous chromatic contrast from Hunt model.
:param xyz: Stimulus XYZ.
:param xyz_w: Reference white XYZ.
:param f_l: Luminance adaptation factor
:param d: Degree of adaptation.
:return: Tuple of adapted rgb and rgb_w arrays. |
def errors(self):
if self.ok():
return {}
errors = self.content
if(not isinstance(errors, dict)):
errors = {"error": errors} # convert to dict for consistency
elif('errors' in errors):
errors = errors['errors']
return errors | :return error dict if no success: |
def create(self, email, phone, country_code=1, send_install_link_via_sms=False):
data = {
"user": {
"email": email,
"cellphone": phone,
"country_code": country_code
},
'send_install_link_via_sms': send_install_link_via_... | sends request to create new user.
:param string email:
:param string phone:
:param string country_code:
:param bool send_install_link_via_sms:
:return: |
def verification_start(self, phone_number, country_code, via='sms',
locale=None, code_length=4):
if via != 'sms' and via != 'call':
raise AuthyFormatException("Invalid Via. Expected 'sms' or 'call'.")
options = {
'phone_number': phone_number,
... | :param string phone_number: stored in your databse or you provided while creating new user.
:param string country_code: stored in your databse or you provided while creating new user.
:param string via: verification method either sms or call
:param string locale: optional default none
:p... |
def verification_check(self, phone_number, country_code, verification_code):
options = {
'phone_number': phone_number,
'country_code': country_code,
'verification_code': verification_code
}
resp = self.get("/protected/json/phones/verification/check", ... | :param phone_number:
:param country_code:
:param verification_code:
:return: |
def send_request(self, user_id, message, seconds_to_expire=None, details={}, hidden_details={}, logos=[]):
self._validate_request(user_id, message)
data = {
"message": message[:MAX_STRING_SIZE],
"seconds_to_expire": seconds_to_expire,
"details": self.__clean_... | OneTouch verification request. Sends a request for Auth App. For more info https://www.twilio.com/docs/api/authy/authy-onetouch-api
:param string user_id: user_id User's authy id stored in your database
:param string message: Required, the message shown to the user when the approval request arrives.
... |
def clean_logos(self, logos):
if not len(logos):
return logos # Allow nil hash
if not isinstance(logos, list):
raise AuthyFormatException(
'Invalid logos list. Only res and url required')
temp_array = {}
clean_logos = []
for logo ... | Validate logos input.
:param list logos:
:return list logos: |
def get_approval_status(self, uuid):
request_url = "/onetouch/json/approval_requests/{0}".format(uuid)
response = self.get(request_url)
return OneTouchResponse(self, response) | OneTouch verification request. Sends a request for Auth App. For more info https://www.twilio.com/docs/api/authy/authy-onetouch-api
:param string uuid Required. The approval request ID. (Obtained from the response to an ApprovalRequest):
:return OneTouchResponse the server response Json Object: |
def validate_one_touch_signature(self, signature, nonce, method, url, params):
if not signature or not isinstance(signature, str):
raise AuthyFormatException(
"Invalid signature - should not be empty. It is required")
if not nonce:
raise AuthyFormatExcept... | Function to validate signature in X-Authy-Signature key of headers.
:param string signature: X-Authy-Signature key of headers.
:param string nonce: X-Authy-Signature-Nonce key of headers.
:param string method: GET or POST - configured in app settings for OneTouch.
:param string url: bas... |
def __make_http_query(self, params, topkey=''):
if len(params) == 0:
return ""
result = ""
# is a dictionary?
if type(params) is dict:
for key in params.keys():
newkey = quote(key)
if topkey != '':
newke... | Function to covert params into url encoded query string
:param dict params: Json string sent by Authy.
:param string topkey: params key
:return string: url encoded Query. |
def compile(script, vars={}, library_paths=[]):
return _pyjq.Script(script.encode('utf-8'), vars=vars,
library_paths=library_paths) | Compile a jq script, retuning a script object.
library_paths is a list of strings that defines the module search path. |
def apply(script, value=None, vars={}, url=None, opener=default_opener, library_paths=[]):
return all(script, value, vars, url, opener, library_paths) | Transform value by script, returning all results as list. |
def first(script, value=None, default=None, vars={}, url=None, opener=default_opener, library_paths=[]):
return compile(script, vars, library_paths).first(_get_value(value, url, opener), default) | Transform object by jq script, returning the first result.
Return default if result is empty. |
def one(script, value=None, vars={}, url=None, opener=default_opener, library_paths=[]):
return compile(script, vars, library_paths).one(_get_value(value, url, opener)) | Transform object by jq script, returning the first result.
Raise ValueError unless results does not include exactly one element. |
def calculate_mypypath() -> List[str]:
typeshed_root = None
count = 0
started = time.time()
for parent in itertools.chain(
# Look in current script's parents, useful for zipapps.
Path(__file__).parents,
# Look around site-packages, useful for virtualenvs.
Path(mypy.a... | Return MYPYPATH so that stubs have precedence over local sources. |
def send(channel, message, **kwargs):
pubnub = Pubnub(
publish_key=settings.PUBNUB_PUB_KEY,
subscribe_key=settings.PUBNUB_SUB_KEY,
secret_key=settings.PUBNUB_SEC_KEY,
ssl_on=kwargs.pop('ssl_on', False), **kwargs)
return pubnub.publish(channel=channel, message={"text": messag... | Site: http://www.pubnub.com/
API: https://www.mashape.com/pubnub/pubnub-network
Desc: real-time browser notifications
Installation and usage:
pip install -U pubnub
Tests for browser notification http://127.0.0.1:8000/browser_notification/ |
def send(token, title, **kwargs):
headers = {
"Content-type": "application/x-www-form-urlencoded",
"User-Agent": "DBMail/%s" % get_version(),
}
data = {
"user_credentials": token,
"notification[title]": from_unicode(title),
"notification[sound]": "notifier-2"
... | Site: https://boxcar.io/
API: http://help.boxcar.io/knowledgebase/topics/48115-boxcar-api
Desc: Best app for system administrators |
def send(channel, message, **kwargs):
headers = {
"Content-type": "application/x-www-form-urlencoded",
"User-Agent": "DBMail/%s" % get_version(),
}
username = from_unicode(kwargs.pop("username", settings.SLACK_USERNAME))
hook_url = from_unicode(kwargs.pop("hook_url", settings.SLACK_... | Site: https://slack.com
API: https://api.slack.com
Desc: real-time messaging |
def send(sms_to, sms_body, **kwargs):
headers = {
"User-Agent": "DBMail/%s" % get_version(),
}
kwargs.update({
'user': settings.SMSAERO_LOGIN,
'password': settings.SMSAERO_MD5_PASSWORD,
'from': kwargs.pop('sms_from', settings.SMSAERO_FROM),
'to': sms_to.replace('... | Site: http://smsaero.ru/
API: http://smsaero.ru/api/ |
def email_list_to_email_dict(email_list):
if email_list is None:
return {}
result = {}
for value in email_list:
realname, address = email.utils.parseaddr(value)
result[address] = realname if realname and address else address
return result | Convert a list of email to a dict of email. |
def email_address_to_list(email_address):
realname, address = email.utils.parseaddr(email_address)
return (
[address, realname] if realname and address else
[email_address, email_address]
) | Convert an email address to a list. |
def send(sender_instance):
m = Mailin(
"https://api.sendinblue.com/v2.0",
sender_instance._kwargs.get("api_key")
)
data = {
"to": email_list_to_email_dict(sender_instance._recipient_list),
"cc": email_list_to_email_dict(sender_instance._cc),
"bcc": email_list_to_... | Send a transactional email using SendInBlue API.
Site: https://www.sendinblue.com
API: https://apidocs.sendinblue.com/ |
def send(sms_to, sms_body, **kwargs):
headers = {
"User-Agent": "DBMail/%s" % get_version(),
'Authorization': 'Basic %s' % b64encode(
"%s:%s" % (
settings.IQSMS_API_LOGIN, settings.IQSMS_API_PASSWORD
)).decode("ascii")
}
kwargs.update({
'p... | Site: http://iqsms.ru/
API: http://iqsms.ru/api/ |
def send(device_id, description, **kwargs):
headers = {
"X-Parse-Application-Id": settings.PARSE_APP_ID,
"X-Parse-REST-API-Key": settings.PARSE_API_KEY,
"User-Agent": "DBMail/%s" % get_version(),
"Content-type": "application/json",
}
data = {
"where": {
... | Site: http://parse.com
API: https://www.parse.com/docs/push_guide#scheduled/REST
Desc: Best app for system administrators |
def send(api_key, description, **kwargs):
headers = {
"User-Agent": "DBMail/%s" % get_version(),
"Content-type": "application/x-www-form-urlencoded"
}
application = from_unicode(kwargs.pop("app", settings.PROWL_APP), 256)
event = from_unicode(kwargs.pop("event", 'Alert'), 1024)
... | Site: http://prowlapp.com
API: http://prowlapp.com/api.php
Desc: Best app for system administrators |
def send(token_hex, message, **kwargs):
is_enhanced = kwargs.pop('is_enhanced', False)
identifier = kwargs.pop('identifier', 0)
expiry = kwargs.pop('expiry', 0)
alert = {
"title": kwargs.pop("event"),
"body": message,
"action": kwargs.pop(
'apns_action', defaults... | Site: https://apple.com
API: https://developer.apple.com
Desc: iOS notifications |
def send(ch, message, **kwargs):
params = {
'type': kwargs.pop('req_type', 'self'),
'key': settings.PUSHALL_API_KEYS[ch]['key'],
'id': settings.PUSHALL_API_KEYS[ch]['id'],
'title': kwargs.pop(
"title", settings.PUSHALL_API_KEYS[ch].get('title') or ""),
'text'... | Site: https://pushall.ru
API: https://pushall.ru/blog/api
Desc: App for notification to devices/browsers and messaging apps |
def send(to, message, **kwargs):
available_kwargs_keys = [
'parse_mode',
'disable_web_page_preview',
'disable_notification',
'reply_to_message_id',
'reply_markup'
]
available_kwargs = {
k: v for k, v in kwargs.iteritems() if k in available_kwargs_keys
... | SITE: https://github.com/nickoala/telepot
TELEGRAM API: https://core.telegram.org/bots/api
Installation:
pip install 'telepot>=10.4' |
def send(reg_id, message, **kwargs):
subscription_info = kwargs.pop('subscription_info')
payload = {
"title": kwargs.pop("event"),
"body": message,
"url": kwargs.pop("push_url", None)
}
payload.update(kwargs)
wp = WebPusher(subscription_info)
response = wp.send(
... | Site: https://developers.google.com
API: https://developers.google.com/web/updates/2016/03/web-push-encryption
Desc: Web Push notifications for Chrome and FireFox
Installation:
pip install 'pywebpush>=0.4.0' |
def send(token_hex, message, **kwargs):
priority = kwargs.pop('priority', 10)
topic = kwargs.pop('topic', None)
alert = {
"title": kwargs.pop("event"),
"body": message,
"action": kwargs.pop(
'apns_action', defaults.APNS_PROVIDER_DEFAULT_ACTION)
}
data = {
... | Site: https://apple.com
API: https://developer.apple.com
Desc: iOS notifications
Installation and usage:
pip install hyper |
def send(sms_to, sms_body, **kwargs):
headers = {
"Content-type": "application/x-www-form-urlencoded",
"User-Agent": "DBMail/%s" % get_version(),
'Authorization': 'Basic %s' % b64encode(
"%s:%s" % (
settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN
... | Site: https://www.twilio.com/
API: https://www.twilio.com/docs/api/rest/sending-messages |
def send(user, message, **kwargs):
headers = {
"Content-type": "application/x-www-form-urlencoded",
"User-Agent": "DBMail/%s" % get_version(),
}
title = from_unicode(kwargs.pop("title", settings.PUSHOVER_APP))
message = from_unicode(message)
data = {
"token": settings.PU... | Site: https://pushover.net/
API: https://pushover.net/api
Desc: real-time notifications |
def send(user, message, **kwargs):
headers = {
"Content-type": "application/json",
"Authorization": "key=" + kwargs.pop("gcm_key", settings.GCM_KEY)
}
hook_url = 'https://android.googleapis.com/gcm/send'
data = {
"registration_ids": [user],
"data": {
"tit... | Site: https://developers.google.com
API: https://developers.google.com/cloud-messaging/
Desc: Android notifications |
def rotate_lv(*, device, size, debug, forward):
import augeas
class Augeas(augeas.Augeas):
def get_int(self, key):
return int(self.get(key + '/int'))
def set_int(self, key, val):
return self.set(key + '/int', '%d' % val)
def incr(self, key, by=1):
... | Rotate a logical volume by a single PE.
If forward:
Move the first physical extent of an LV to the end
else:
Move the last physical extent of a LV to the start
then poke LVM to refresh the mapping. |
def _mpv_coax_proptype(value, proptype=str):
if type(value) is bytes:
return value;
elif type(value) is bool:
return b'yes' if value else b'no'
elif proptype in (str, int, float):
return str(proptype(value)).encode('utf-8')
else:
raise TypeError('Cannot coax value of... | Intelligently coax the given python value into something that can be understood as a proptype property. |
def _make_node_str_list(l):
char_ps = [ c_char_p(_mpv_coax_proptype(e, str)) for e in l ]
node_list = MpvNodeList(
num=len(l),
keys=None,
values=( MpvNode * len(l))( *[ MpvNode(
format=MpvFormat.STRING,
val=MpvNodeUnion(string=p))
for p in... | Take a list of python objects and make a MPV string node array from it.
As an example, the python list ``l = [ "foo", 23, false ]`` will result in the following MPV node object::
struct mpv_node {
.format = MPV_NODE_ARRAY,
.u.list = *(struct mpv_node_array){
.num = ... |
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(s... | Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around |
def terminate(self):
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reap... | Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor. |
def command(self, name, *args):
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args)) | Execute a raw command. |
def seek(self, amount, reference="relative", precision="default-precise"):
self.command('seek', amount, reference, precision) | Mapped mpv seek command, see man mpv(1). |
def screenshot_to_file(self, filename, includes='subtitles'):
self.command('screenshot_to_file', filename.encode(fs_enc), includes) | Mapped mpv screenshot_to_file command, see man mpv(1). |
def screenshot_raw(self, includes='subtitles'):
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['for... | Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object. |
def loadfile(self, filename, mode='replace', **options):
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options)) | Mapped mpv loadfile command, see man mpv(1). |
def loadlist(self, playlist, mode='replace'):
self.command('loadlist', playlist.encode(fs_enc), mode) | Mapped mpv loadlist command, see man mpv(1). |
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride) | Mapped mpv overlay_add command, see man mpv(1). |
def observe_property(self, name, handler):
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE) | Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function... |
def property_observer(self, name):
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper | Function decorator to register a property observer. See ``MPV.observe_property`` for details. |
def unobserve_property(self, name, handler):
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff) | Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``. |
def unobserve_all_properties(self, handler):
for name in self._property_handlers:
self.unobserve_property(name, handler) | Unregister a property observer from *all* observed properties. |
def unregister_message_handler(self, target_or_handler):
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._... | Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered. |
def message_handler(self, target):
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register | Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def ... |
def event_callback(self, *event_types):
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
... | Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callbac... |
def on_key_press(self, keydef, mode='force'):
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register | Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def bi... |
def key_binding(self, keydef, mode='force'):
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fu... | Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the litera... |
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the ... | Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details. |
def unregister_key_binding(self, keydef):
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_nam... | Unregister a key binding by keydef. |
def _process_origin(self, req, resp, origin):
if self._cors_config['allow_all_origins']:
if self.supports_credentials:
self._set_allow_origin(resp, origin)
else:
self._set_allow_origin(resp, '*')
return True
if origin in self._... | Inspects the request and adds the Access-Control-Allow-Origin
header if the requested origin is allowed.
Returns:
``True`` if the header was added and the requested origin
is allowed, ``False`` if the origin is not allowed and the
header has not been added. |
def _process_allow_headers(self, req, resp, requested_headers):
if not requested_headers:
return True
elif self._cors_config['allow_all_headers']:
self._set_allowed_headers(resp, requested_headers)
return True
approved_headers = []
for header ... | Adds the Access-Control-Allow-Headers header to the response,
using the cors settings to determine which headers are allowed.
Returns:
True if all the headers the client requested are allowed.
False if some or none of the headers the client requested are allowed. |
def _process_methods(self, req, resp, resource):
requested_method = self._get_requested_method(req)
if not requested_method:
return False
if self._cors_config['allow_all_methods']:
allowed_methods = self._get_resource_methods(resource)
self._set_allow... | Adds the Access-Control-Allow-Methods header to the response,
using the cors settings to determine which methods are allowed. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.