code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
container = self._container_factory(**options) if not content or content is None: return container() options = self._load_options(container, **options) return self.load_from_string(content, container, **options)
def loads(self, content, **options)
Load config from given string 'content' after some checks. :param content: Config file content :param options: options will be passed to backend specific loading functions. please note that options have to be sanitized w/ :func:`anyconfig.utils.filter_options` later to filter out options not in _load_opts. :return: dict or dict-like object holding configurations
4.888038
6.425478
0.760728
container = self._container_factory(**options) options = self._load_options(container, **options) if not ioi: return container() if anyconfig.utils.is_stream_ioinfo(ioi): cnf = self.load_from_stream(ioi.src, container, **options) else: if ac_ignore_missing and not os.path.exists(ioi.path): return container() cnf = self.load_from_path(ioi.path, container, **options) return cnf
def load(self, ioi, ac_ignore_missing=False, **options)
Load config from a file path or a file / file-like object which 'ioi' refering after some checks. :param ioi: 'anyconfig.globals.IOInfo' namedtuple object provides various info of input object to load data from :param ac_ignore_missing: Ignore and just return empty result if given `ioi` object does not exist in actual. :param options: options will be passed to backend specific loading functions. please note that options have to be sanitized w/ :func:`anyconfig.utils.filter_options` later to filter out options not in _load_opts. :return: dict or dict-like object holding configurations
3.560462
3.297995
1.079584
_not_implemented(self, cnf, filepath, **kwargs)
def dump_to_path(self, cnf, filepath, **kwargs)
Dump config 'cnf' to a file 'filepath'. :param cnf: Configuration data to dump :param filepath: Config file path :param kwargs: optional keyword parameters to be sanitized :: dict
9.581933
10.594787
0.904401
_not_implemented(self, cnf, stream, **kwargs)
def dump_to_stream(self, cnf, stream, **kwargs)
Dump config 'cnf' to a file-like object 'stream'. TODO: How to process socket objects same as file objects ? :param cnf: Configuration data to dump :param stream: Config file or file like object :param kwargs: optional keyword parameters to be sanitized :: dict
9.376679
10.121011
0.926457
kwargs = anyconfig.utils.filter_options(self._dump_opts, kwargs) return self.dump_to_string(cnf, **kwargs)
def dumps(self, cnf, **kwargs)
Dump config 'cnf' to a string. :param cnf: Configuration data to dump :param kwargs: optional keyword parameters to be sanitized :: dict :return: string represents the configuration
6.818774
10.799241
0.631412
kwargs = anyconfig.utils.filter_options(self._dump_opts, kwargs) if anyconfig.utils.is_stream_ioinfo(ioi): self.dump_to_stream(cnf, ioi.src, **kwargs) else: ensure_outdir_exists(ioi.path) self.dump_to_path(cnf, ioi.path, **kwargs)
def dump(self, cnf, ioi, **kwargs)
Dump config 'cnf' to output object of which 'ioi' refering. :param cnf: Configuration data to dump :param ioi: an 'anyconfig.globals.IOInfo' namedtuple object provides various info of input object to load data from :param kwargs: optional keyword parameters to be sanitized :: dict :raises IOError, OSError, AttributeError: When dump failed.
3.954359
3.980794
0.993359
return self.load_from_string(stream.read(), container, **kwargs)
def load_from_stream(self, stream, container, **kwargs)
Load config from given stream 'stream'. :param stream: Config file or file-like object :param container: callble to make a container object later :param kwargs: optional keyword parameters to be sanitized :: dict :return: Dict-like object holding config parameters
3.571828
6.569494
0.543699
with self.ropen(filepath) as inp: return self.load_from_stream(inp, container, **kwargs)
def load_from_path(self, filepath, container, **kwargs)
Load config from given file path 'filepath'. :param filepath: Config file path :param container: callble to make a container object later :param kwargs: optional keyword parameters to be sanitized :: dict :return: Dict-like object holding config parameters
5.134552
9.140392
0.561743
return self.load_from_stream(anyconfig.compat.StringIO(content), container, **kwargs)
def load_from_string(self, content, container, **kwargs)
Load config from given string 'cnf_content'. :param content: Config content string :param container: callble to make a container object later :param kwargs: optional keyword parameters to be sanitized :: dict :return: Dict-like object holding config parameters
5.352719
9.158331
0.584464
with self.wopen(filepath) as out: out.write(self.dump_to_string(cnf, **kwargs))
def dump_to_path(self, cnf, filepath, **kwargs)
Dump config 'cnf' to a file 'filepath'. :param cnf: Configuration data to dump :param filepath: Config file path :param kwargs: optional keyword parameters to be sanitized :: dict
4.717131
8.04352
0.586451
stream.write(self.dump_to_string(cnf, **kwargs))
def dump_to_stream(self, cnf, stream, **kwargs)
Dump config 'cnf' to a file-like object 'stream'. TODO: How to process socket objects same as file objects ? :param cnf: Configuration data to dump :param stream: Config file or file like object :param kwargs: optional keyword parameters to be sanitized :: dict
4.178791
5.50194
0.759512
stream = anyconfig.compat.StringIO() self.dump_to_stream(cnf, stream, **kwargs) return stream.getvalue()
def dump_to_string(self, cnf, **kwargs)
Dump config 'cnf' to a string. :param cnf: Configuration data to dump :param kwargs: optional keyword parameters to be sanitized :: dict :return: Dict-like object holding config parameters
4.283532
6.606283
0.648403
with self.wopen(filepath) as out: self.dump_to_stream(cnf, out, **kwargs)
def dump_to_path(self, cnf, filepath, **kwargs)
Dump config 'cnf' to a file 'filepath`. :param cnf: Configuration data to dump :param filepath: Config file path :param kwargs: optional keyword parameters to be sanitized :: dict
4.989728
9.133993
0.546281
return load_with_fn(self._load_from_string_fn, content, container, allow_primitives=self.allow_primitives(), **options)
def load_from_string(self, content, container, **options)
Load configuration data from given string 'content'. :param content: Configuration string :param container: callble to make a container object :param options: keyword options passed to '_load_from_string_fn' :return: container object holding the configuration data
7.624712
8.654342
0.881027
return load_with_fn(self._load_from_stream_fn, stream, container, allow_primitives=self.allow_primitives(), **options)
def load_from_stream(self, stream, container, **options)
Load data from given stream 'stream'. :param stream: Stream provides configuration data :param container: callble to make a container object :param options: keyword options passed to '_load_from_stream_fn' :return: container object holding the configuration data
7.177563
8.545215
0.839951
dump_with_fn(self._dump_to_stream_fn, cnf, stream, **kwargs)
def dump_to_stream(self, cnf, stream, **kwargs)
Dump config 'cnf' to a file-like object 'stream'. TODO: How to process socket objects same as file objects ? :param cnf: Configuration data to dump :param stream: Config file or file like object :param kwargs: optional keyword parameters to be sanitized :: dict
5.980629
10.612025
0.563571
if obj is None: return IOI_NONE if anyconfig.utils.is_path(obj): return IOI_PATH_STR if anyconfig.utils.is_path_obj(obj): return IOI_PATH_OBJ if anyconfig.utils.is_file_stream(obj): return IOI_STREAM raise ValueError("Unknown I/O type object: %r" % obj)
def guess_io_type(obj)
Guess input or output type of 'obj'. :param obj: a path string, a pathlib.Path or a file / file-like object :return: IOInfo type defined in anyconfig.globals.IOI_TYPES >>> apath = "/path/to/a_conf.ext" >>> assert guess_io_type(apath) == IOI_PATH_STR >>> from anyconfig.compat import pathlib >>> if pathlib is not None: ... assert guess_io_type(pathlib.Path(apath)) == IOI_PATH_OBJ >>> assert guess_io_type(open(__file__)) == IOI_STREAM >>> guess_io_type(1) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: ...
3.451464
2.313337
1.491985
itype = guess_io_type(obj) if itype == IOI_PATH_STR: ipath = anyconfig.utils.normpath(obj) ext = anyconfig.utils.get_file_extension(ipath) opener = open elif itype == IOI_PATH_OBJ: ipath = anyconfig.utils.normpath(obj.as_posix()) ext = anyconfig.utils.get_file_extension(ipath) opener = obj.open elif itype == IOI_STREAM: ipath = anyconfig.utils.get_path_from_stream(obj) ext = anyconfig.utils.get_file_extension(ipath) if ipath else None opener = anyconfig.utils.noop elif itype == IOI_NONE: ipath = ext = None opener = anyconfig.utils.noop else: raise UnknownFileTypeError("%r" % obj) return (itype, ipath, opener, ext)
def inspect_io_obj(obj)
:param obj: a path string, a pathlib.Path or a file / file-like object :return: A tuple of (objtype, objpath, objopener) :raises: UnknownFileTypeError
2.614075
2.318195
1.127634
if anyconfig.utils.is_ioinfo(obj): return obj (itype, ipath, opener, ext) = inspect_io_obj(obj) return IOInfo(src=obj, type=itype, path=ipath, opener=opener, extension=ext)
def make(obj)
:param obj: a path string, a pathlib.Path or a file / file-like object :return: Namedtuple object represents a kind of input object such as a file / file-like object, path string or pathlib.Path object :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError
7.514824
7.81884
0.961118
match = re.match(r"^\s*(export)?\s*(\S+)=(?:(?:" r"(?:\"(.*[^\\])\")|(?:'(.*[^\\])')|" r"(?:([^\"'#\s]+)))?)\s*#*", line) if not match: LOGGER.warning("Invalid line found: %s", line) return (None, None) tpl = match.groups() vals = list(itertools.dropwhile(lambda x: x is None, tpl[2:])) return (tpl[1], vals[0] if vals else '')
def _parseline(line)
Parse a line contains shell variable definition. :param line: A string to parse, must not start with '#' (comment) :return: A tuple of (key, value), both key and value may be None >>> _parseline("aaa=") ('aaa', '') >>> _parseline("aaa=bbb") ('aaa', 'bbb') >>> _parseline("aaa='bb b'") ('aaa', 'bb b') >>> _parseline('aaa="bb#b"') ('aaa', 'bb#b') >>> _parseline('aaa="bb\\"b"') ('aaa', 'bb"b') >>> _parseline("aaa=bbb # ccc") ('aaa', 'bbb')
4.386787
4.122356
1.064146
ret = container() for line in stream.readlines(): line = line.rstrip() if line is None or not line: continue (key, val) = _parseline(line) if key is None: LOGGER.warning("Empty val in the line: %s", line) continue ret[key] = val return ret
def load(stream, container=dict)
Load and parse a file or file-like object 'stream' provides simple shell variables' definitions. :param stream: A file or file like object :param container: Factory function to create a dict-like object to store properties :return: Dict-like object holding shell variables' definitions >>> from anyconfig.compat import StringIO as to_strm >>> load(to_strm('')) {} >>> load(to_strm("# ")) {} >>> load(to_strm("aaa=")) {'aaa': ''} >>> load(to_strm("aaa=bbb")) {'aaa': 'bbb'} >>> load(to_strm("aaa=bbb # ...")) {'aaa': 'bbb'}
3.758975
5.045121
0.745071
for key, val in anyconfig.compat.iteritems(cnf): stream.write("%s='%s'%s" % (key, val, os.linesep))
def dump_to_stream(self, cnf, stream, **kwargs)
Dump config 'cnf' to a file or file-like object 'stream'. :param cnf: Shell variables data to dump :param stream: Shell script file or file like object :param kwargs: backend-specific optional keyword parameters :: dict
4.834301
6.984382
0.692159
return Color("cmyk", c, m, y, k)
def cmyk(c, m, y, k)
Create a spectra.Color object in the CMYK color space. :param float c: c coordinate. :param float m: m coordinate. :param float y: y coordinate. :param float k: k coordinate. :rtype: Color :returns: A spectra.Color object in the CMYK color space.
4.743866
8.187755
0.579385
'''Convert the color from RGB coordinates to HSL. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (h, s, l) tuple in the range: h[0...360], s[0...1], l[0...1] >>> Color.RgbToHsl(1, 0.5, 0) (30.0, 1.0, 0.5) ''' minVal = min(r, g, b) # min RGB value maxVal = max(r, g, b) # max RGB value l = (maxVal + minVal) / 2.0 if minVal==maxVal: return (0.0, 0.0, l) # achromatic (gray) d = maxVal - minVal # delta RGB value if l < 0.5: s = d / (maxVal + minVal) else: s = d / (2.0 - maxVal - minVal) dr, dg, db = [(maxVal-val) / d for val in (r, g, b)] if r==maxVal: h = db - dg elif g==maxVal: h = 2.0 + dr - db else: h = 4.0 + dg - dr h = (h*60.0) % 360.0 return (h, s, l)
def RgbToHsl(r, g, b)
Convert the color from RGB coordinates to HSL. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (h, s, l) tuple in the range: h[0...360], s[0...1], l[0...1] >>> Color.RgbToHsl(1, 0.5, 0) (30.0, 1.0, 0.5)
2.037763
1.54448
1.319384
'''Convert the color from HSL coordinates to RGB. Parameters: :h: The Hue component value [0...1] :s: The Saturation component value [0...1] :l: The Lightness component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> Color.HslToRgb(30.0, 1.0, 0.5) (1.0, 0.5, 0.0) ''' if s==0: return (l, l, l) # achromatic (gray) if l<0.5: n2 = l * (1.0 + s) else: n2 = l+s - (l*s) n1 = (2.0 * l) - n2 h /= 60.0 hueToRgb = Color._HueToRgb r = hueToRgb(n1, n2, h + 2) g = hueToRgb(n1, n2, h) b = hueToRgb(n1, n2, h - 2) return (r, g, b)
def HslToRgb(h, s, l)
Convert the color from HSL coordinates to RGB. Parameters: :h: The Hue component value [0...1] :s: The Saturation component value [0...1] :l: The Lightness component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> Color.HslToRgb(30.0, 1.0, 0.5) (1.0, 0.5, 0.0)
2.307095
1.587365
1.453412
'''Convert the color from RGB coordinates to HSV. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (h, s, v) tuple in the range: h[0...360], s[0...1], v[0...1] >>> Color.RgbToHsv(1, 0.5, 0) (30.0, 1.0, 1.0) ''' v = float(max(r, g, b)) d = v - min(r, g, b) if d==0: return (0.0, 0.0, v) s = d / v dr, dg, db = [(v - val) / d for val in (r, g, b)] if r==v: h = db - dg # between yellow & magenta elif g==v: h = 2.0 + dr - db # between cyan & yellow else: # b==v h = 4.0 + dg - dr # between magenta & cyan h = (h*60.0) % 360.0 return (h, s, v)
def RgbToHsv(r, g, b)
Convert the color from RGB coordinates to HSV. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (h, s, v) tuple in the range: h[0...360], s[0...1], v[0...1] >>> Color.RgbToHsv(1, 0.5, 0) (30.0, 1.0, 1.0)
2.186405
1.5564
1.404784
'''Convert the color from RGB coordinates to HSV. Parameters: :h: The Hus component value [0...1] :s: The Saturation component value [0...1] :v: The Value component [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> Color.HslToRgb(30.0, 1.0, 0.5) (1.0, 0.5, 0.0) ''' if s==0: return (v, v, v) # achromatic (gray) h /= 60.0 h = h % 6.0 i = int(h) f = h - i if not(i&1): f = 1-f # if i is even m = v * (1.0 - s) n = v * (1.0 - (s * f)) if i==0: return (v, n, m) if i==1: return (n, v, m) if i==2: return (m, v, n) if i==3: return (m, n, v) if i==4: return (n, m, v) return (v, m, n)
def HsvToRgb(h, s, v)
Convert the color from RGB coordinates to HSV. Parameters: :h: The Hus component value [0...1] :s: The Saturation component value [0...1] :v: The Value component [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> Color.HslToRgb(30.0, 1.0, 0.5) (1.0, 0.5, 0.0)
2.36299
1.485142
1.591087
'''Convert the color from RGB to YIQ. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (y, i, q) tuple in the range: y[0...1], i[0...1], q[0...1] >>> '(%g, %g, %g)' % Color.RgbToYiq(1, 0.5, 0) '(0.592263, 0.458874, -0.0499818)' ''' y = (r * 0.29895808) + (g * 0.58660979) + (b *0.11443213) i = (r * 0.59590296) - (g * 0.27405705) - (b *0.32184591) q = (r * 0.21133576) - (g * 0.52263517) + (b *0.31129940) return (y, i, q)
def RgbToYiq(r, g, b)
Convert the color from RGB to YIQ. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (y, i, q) tuple in the range: y[0...1], i[0...1], q[0...1] >>> '(%g, %g, %g)' % Color.RgbToYiq(1, 0.5, 0) '(0.592263, 0.458874, -0.0499818)'
2.920139
1.771748
1.648168
'''Convert the color from YIQ coordinates to RGB. Parameters: :y: Tte Y component value [0...1] :i: The I component value [0...1] :q: The Q component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % Color.YiqToRgb(0.592263, 0.458874, -0.0499818) '(1, 0.5, 5.442e-07)' ''' r = y + (i * 0.9562) + (q * 0.6210) g = y - (i * 0.2717) - (q * 0.6485) b = y - (i * 1.1053) + (q * 1.7020) return (r, g, b)
def YiqToRgb(y, i, q)
Convert the color from YIQ coordinates to RGB. Parameters: :y: Tte Y component value [0...1] :i: The I component value [0...1] :q: The Q component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % Color.YiqToRgb(0.592263, 0.458874, -0.0499818) '(1, 0.5, 5.442e-07)'
3.334773
1.42603
2.338501
'''Convert the color from RGB coordinates to YUV. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (y, u, v) tuple in the range: y[0...1], u[-0.436...0.436], v[-0.615...0.615] >>> '(%g, %g, %g)' % Color.RgbToYuv(1, 0.5, 0) '(0.5925, -0.29156, 0.357505)' ''' y = (r * 0.29900) + (g * 0.58700) + (b * 0.11400) u = -(r * 0.14713) - (g * 0.28886) + (b * 0.43600) v = (r * 0.61500) - (g * 0.51499) - (b * 0.10001) return (y, u, v)
def RgbToYuv(r, g, b)
Convert the color from RGB coordinates to YUV. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (y, u, v) tuple in the range: y[0...1], u[-0.436...0.436], v[-0.615...0.615] >>> '(%g, %g, %g)' % Color.RgbToYuv(1, 0.5, 0) '(0.5925, -0.29156, 0.357505)'
2.270073
1.276597
1.778222
'''Convert the color from YUV coordinates to RGB. Parameters: :y: The Y component value [0...1] :u: The U component value [-0.436...0.436] :v: The V component value [-0.615...0.615] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % Color.YuvToRgb(0.5925, -0.2916, 0.3575) '(0.999989, 0.500015, -6.3276e-05)' ''' r = y + (v * 1.13983) g = y - (u * 0.39465) - (v * 0.58060) b = y + (u * 2.03211) return (r, g, b)
def YuvToRgb(y, u, v)
Convert the color from YUV coordinates to RGB. Parameters: :y: The Y component value [0...1] :u: The U component value [-0.436...0.436] :v: The V component value [-0.615...0.615] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % Color.YuvToRgb(0.5925, -0.2916, 0.3575) '(0.999989, 0.500015, -6.3276e-05)'
2.761265
1.260745
2.190184
'''Convert the color from sRGB to CIE XYZ. The methods assumes that the RGB coordinates are given in the sRGB colorspace (D65). .. note:: Compensation for the sRGB gamma correction is applied before converting. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (x, y, z) tuple in the range: x[0...1], y[0...1], z[0...1] >>> '(%g, %g, %g)' % Color.RgbToXyz(1, 0.5, 0) '(0.488941, 0.365682, 0.0448137)' ''' r, g, b = [((v <= 0.03928) and [v / 12.92] or [((v+0.055) / 1.055) **2.4])[0] for v in (r, g, b)] x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805) y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722) z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505) return (x, y, z)
def RgbToXyz(r, g, b)
Convert the color from sRGB to CIE XYZ. The methods assumes that the RGB coordinates are given in the sRGB colorspace (D65). .. note:: Compensation for the sRGB gamma correction is applied before converting. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (x, y, z) tuple in the range: x[0...1], y[0...1], z[0...1] >>> '(%g, %g, %g)' % Color.RgbToXyz(1, 0.5, 0) '(0.488941, 0.365682, 0.0448137)'
2.371046
1.279468
1.853149
'''Convert the color from CIE XYZ coordinates to sRGB. .. note:: Compensation for sRGB gamma correction is applied before converting. Parameters: :x: The X component value [0...1] :y: The Y component value [0...1] :z: The Z component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % Color.XyzToRgb(0.488941, 0.365682, 0.0448137) '(1, 0.5, 6.81883e-08)' ''' r = (x * 3.2406255) - (y * 1.5372080) - (z * 0.4986286) g = -(x * 0.9689307) + (y * 1.8757561) + (z * 0.0415175) b = (x * 0.0557101) - (y * 0.2040211) + (z * 1.0569959) return tuple((((v <= _srgbGammaCorrInv) and [v * 12.92] or [(1.055 * (v ** (1/2.4))) - 0.055])[0] for v in (r, g, b)))
def XyzToRgb(x, y, z)
Convert the color from CIE XYZ coordinates to sRGB. .. note:: Compensation for sRGB gamma correction is applied before converting. Parameters: :x: The X component value [0...1] :y: The Y component value [0...1] :z: The Z component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % Color.XyzToRgb(0.488941, 0.365682, 0.0448137) '(1, 0.5, 6.81883e-08)'
2.99118
1.665778
1.795665
'''Convert the color from CIE XYZ to CIE L*a*b*. Parameters: :x: The X component value [0...1] :y: The Y component value [0...1] :z: The Z component value [0...1] :wref: The whitepoint reference, default is 2° D65. Returns: The color as an (L, a, b) tuple in the range: L[0...100], a[-1...1], b[-1...1] >>> '(%g, %g, %g)' % Color.XyzToLab(0.488941, 0.365682, 0.0448137) '(66.9518, 0.43084, 0.739692)' >>> '(%g, %g, %g)' % Color.XyzToLab(0.488941, 0.365682, 0.0448137, Color.WHITE_REFERENCE['std_D50']) '(66.9518, 0.411663, 0.67282)' ''' # White point correction x /= wref[0] y /= wref[1] z /= wref[2] # Nonlinear distortion and linear transformation x, y, z = [((v > 0.008856) and [v**_oneThird] or [(7.787 * v) + _sixteenHundredsixteenth])[0] for v in (x, y, z)] # Vector scaling l = (116 * y) - 16 a = 5.0 * (x - y) b = 2.0 * (y - z) return (l, a, b)
def XyzToLab(x, y, z, wref=_DEFAULT_WREF)
Convert the color from CIE XYZ to CIE L*a*b*. Parameters: :x: The X component value [0...1] :y: The Y component value [0...1] :z: The Z component value [0...1] :wref: The whitepoint reference, default is 2° D65. Returns: The color as an (L, a, b) tuple in the range: L[0...100], a[-1...1], b[-1...1] >>> '(%g, %g, %g)' % Color.XyzToLab(0.488941, 0.365682, 0.0448137) '(66.9518, 0.43084, 0.739692)' >>> '(%g, %g, %g)' % Color.XyzToLab(0.488941, 0.365682, 0.0448137, Color.WHITE_REFERENCE['std_D50']) '(66.9518, 0.411663, 0.67282)'
3.115166
1.640506
1.898906
'''Convert the color from CIE L*a*b* to CIE 1931 XYZ. Parameters: :l: The L component [0...100] :a: The a component [-1...1] :b: The a component [-1...1] :wref: The whitepoint reference, default is 2° D65. Returns: The color as an (x, y, z) tuple in the range: x[0...q], y[0...1], z[0...1] >>> '(%g, %g, %g)' % Color.LabToXyz(66.9518, 0.43084, 0.739692) '(0.488941, 0.365682, 0.0448137)' >>> '(%g, %g, %g)' % Color.LabToXyz(66.9518, 0.411663, 0.67282, Color.WHITE_REFERENCE['std_D50']) '(0.488941, 0.365682, 0.0448138)' ''' y = (l + 16) / 116 x = (a / 5.0) + y z = y - (b / 2.0) return tuple((((v > 0.206893) and [v**3] or [(v - _sixteenHundredsixteenth) / 7.787])[0] * w for v, w in zip((x, y, z), wref)))
def LabToXyz(l, a, b, wref=_DEFAULT_WREF)
Convert the color from CIE L*a*b* to CIE 1931 XYZ. Parameters: :l: The L component [0...100] :a: The a component [-1...1] :b: The a component [-1...1] :wref: The whitepoint reference, default is 2° D65. Returns: The color as an (x, y, z) tuple in the range: x[0...q], y[0...1], z[0...1] >>> '(%g, %g, %g)' % Color.LabToXyz(66.9518, 0.43084, 0.739692) '(0.488941, 0.365682, 0.0448137)' >>> '(%g, %g, %g)' % Color.LabToXyz(66.9518, 0.411663, 0.67282, Color.WHITE_REFERENCE['std_D50']) '(0.488941, 0.365682, 0.0448138)'
3.652744
1.558652
2.343528
'''Convert the color from CMYK coordinates to CMY. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :k: The Black component value [0...1] Returns: The color as an (c, m, y) tuple in the range: c[0...1], m[0...1], y[0...1] >>> '(%g, %g, %g)' % Color.CmykToCmy(1, 0.32, 0, 0.5) '(1, 0.66, 0.5)' ''' mk = 1-k return ((c*mk + k), (m*mk + k), (y*mk + k))
def CmykToCmy(c, m, y, k)
Convert the color from CMYK coordinates to CMY. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :k: The Black component value [0...1] Returns: The color as an (c, m, y) tuple in the range: c[0...1], m[0...1], y[0...1] >>> '(%g, %g, %g)' % Color.CmykToCmy(1, 0.32, 0, 0.5) '(1, 0.66, 0.5)'
2.852116
1.390321
2.051408
'''Convert the color from CMY coordinates to CMYK. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] Returns: The color as an (c, m, y, k) tuple in the range: c[0...1], m[0...1], y[0...1], k[0...1] >>> '(%g, %g, %g, %g)' % Color.CmyToCmyk(1, 0.66, 0.5) '(1, 0.32, 0, 0.5)' ''' k = min(c, m, y) if k==1.0: return (0.0, 0.0, 0.0, 1.0) mk = 1-k return ((c-k) / mk, (m-k) / mk, (y-k) / mk, k)
def CmyToCmyk(c, m, y)
Convert the color from CMY coordinates to CMYK. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] Returns: The color as an (c, m, y, k) tuple in the range: c[0...1], m[0...1], y[0...1], k[0...1] >>> '(%g, %g, %g, %g)' % Color.CmyToCmyk(1, 0.66, 0.5) '(1, 0.32, 0, 0.5)'
2.613049
1.450911
1.800971
'''Convert the color from (r, g, b) to an int tuple. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...255], g[0...2551], b[0...2551] >>> Color.RgbToIntTuple(1, 0.5, 0) (255, 128, 0) ''' return tuple(int(round(v*255)) for v in (r, g, b))
def RgbToIntTuple(r, g, b)
Convert the color from (r, g, b) to an int tuple. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...255], g[0...2551], b[0...2551] >>> Color.RgbToIntTuple(1, 0.5, 0) (255, 128, 0)
2.770406
1.317938
2.102076
'''Convert the color from (r, g, b) to #RRGGBB. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: A CSS string representation of this color (#RRGGBB). >>> Color.RgbToHtml(1, 0.5, 0) '#ff8000' ''' return '#%02x%02x%02x' % tuple((min(round(v*255), 255) for v in (r, g, b)))
def RgbToHtml(r, g, b)
Convert the color from (r, g, b) to #RRGGBB. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: A CSS string representation of this color (#RRGGBB). >>> Color.RgbToHtml(1, 0.5, 0) '#ff8000'
2.687254
1.45002
1.853252
'''Convert the HTML color to (r, g, b). Parameters: :html: the HTML definition of the color (#RRGGBB or #RGB or a color name). Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] Throws: :ValueError: If html is neither a known color name or a hexadecimal RGB representation. >>> '(%g, %g, %g)' % Color.HtmlToRgb('#ff8000') '(1, 0.501961, 0)' >>> '(%g, %g, %g)' % Color.HtmlToRgb('ff8000') '(1, 0.501961, 0)' >>> '(%g, %g, %g)' % Color.HtmlToRgb('#f60') '(1, 0.4, 0)' >>> '(%g, %g, %g)' % Color.HtmlToRgb('f60') '(1, 0.4, 0)' >>> '(%g, %g, %g)' % Color.HtmlToRgb('lemonchiffon') '(1, 0.980392, 0.803922)' ''' html = html.strip().lower() if html[0]=='#': html = html[1:] elif html in Color.NAMED_COLOR: html = Color.NAMED_COLOR[html][1:] if len(html)==6: rgb = html[:2], html[2:4], html[4:] elif len(html)==3: rgb = ['%c%c' % (v,v) for v in html] else: raise ValueError('input #%s is not in #RRGGBB format' % html) return tuple(((int(n, 16) / 255.0) for n in rgb))
def HtmlToRgb(html)
Convert the HTML color to (r, g, b). Parameters: :html: the HTML definition of the color (#RRGGBB or #RGB or a color name). Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] Throws: :ValueError: If html is neither a known color name or a hexadecimal RGB representation. >>> '(%g, %g, %g)' % Color.HtmlToRgb('#ff8000') '(1, 0.501961, 0)' >>> '(%g, %g, %g)' % Color.HtmlToRgb('ff8000') '(1, 0.501961, 0)' >>> '(%g, %g, %g)' % Color.HtmlToRgb('#f60') '(1, 0.4, 0)' >>> '(%g, %g, %g)' % Color.HtmlToRgb('f60') '(1, 0.4, 0)' >>> '(%g, %g, %g)' % Color.HtmlToRgb('lemonchiffon') '(1, 0.980392, 0.803922)'
2.331407
1.413266
1.649658
'''Convert the color from RGB to a PIL-compatible integer. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: A PIL compatible integer (0xBBGGRR). >>> '0x%06x' % Color.RgbToPil(1, 0.5, 0) '0x0080ff' ''' r, g, b = [min(int(round(v*255)), 255) for v in (r, g, b)] return (b << 16) + (g << 8) + r
def RgbToPil(r, g, b)
Convert the color from RGB to a PIL-compatible integer. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: A PIL compatible integer (0xBBGGRR). >>> '0x%06x' % Color.RgbToPil(1, 0.5, 0) '0x0080ff'
2.904355
1.446145
2.008343
'''Convert the color from a PIL-compatible integer to RGB. Parameters: pil: a PIL compatible color representation (0xBBGGRR) Returns: The color as an (r, g, b) tuple in the range: the range: r: [0...1] g: [0...1] b: [0...1] >>> '(%g, %g, %g)' % Color.PilToRgb(0x0080ff) '(1, 0.501961, 0)' ''' r = 0xff & pil g = 0xff & (pil >> 8) b = 0xff & (pil >> 16) return tuple((v / 255.0 for v in (r, g, b)))
def PilToRgb(pil)
Convert the color from a PIL-compatible integer to RGB. Parameters: pil: a PIL compatible color representation (0xBBGGRR) Returns: The color as an (r, g, b) tuple in the range: the range: r: [0...1] g: [0...1] b: [0...1] >>> '(%g, %g, %g)' % Color.PilToRgb(0x0080ff) '(1, 0.501961, 0)'
3.765743
1.417972
2.655725
'''Convert a color component to its web safe equivalent. Parameters: :c: The component value [0...1] :alt: If True, return the alternative value instead of the nearest one. Returns: The web safe equivalent of the component value. ''' # This sucks, but floating point between 0 and 1 is quite fuzzy... # So we just change the scale a while to make the equality tests # work, otherwise it gets wrong at some decimal far to the right. sc = c * 100.0 # If the color is already safe, return it straight away d = sc % 20 if d==0: return c # Get the lower and upper safe values l = sc - d u = l + 20 # Return the 'closest' value according to the alt flag if alt: if (sc-l) >= (u-sc): return l/100.0 else: return u/100.0 else: if (sc-l) >= (u-sc): return u/100.0 else: return l/100.0
def _WebSafeComponent(c, alt=False)
Convert a color component to its web safe equivalent. Parameters: :c: The component value [0...1] :alt: If True, return the alternative value instead of the nearest one. Returns: The web safe equivalent of the component value.
5.195755
3.934726
1.320487
'''Convert the color from RGB to 'web safe' RGB Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] :alt: If True, use the alternative color instead of the nearest one. Can be used for dithering. Returns: The color as an (r, g, b) tuple in the range: the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % Color.RgbToWebSafe(1, 0.55, 0.0) '(1, 0.6, 0)' ''' webSafeComponent = Color._WebSafeComponent return tuple((webSafeComponent(v, alt) for v in (r, g, b)))
def RgbToWebSafe(r, g, b, alt=False)
Convert the color from RGB to 'web safe' RGB Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] :alt: If True, use the alternative color instead of the nearest one. Can be used for dithering. Returns: The color as an (r, g, b) tuple in the range: the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % Color.RgbToWebSafe(1, 0.55, 0.0) '(1, 0.6, 0)'
3.898693
1.492404
2.612358
'''Convert the color from RGB to its greyscale equivalent Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (r, g, b) tuple in the range: the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % Color.RgbToGreyscale(1, 0.8, 0) '(0.6, 0.6, 0.6)' ''' v = (r + g + b) / 3.0 return (v, v, v)
def RgbToGreyscale(r, g, b)
Convert the color from RGB to its greyscale equivalent Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (r, g, b) tuple in the range: the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % Color.RgbToGreyscale(1, 0.8, 0) '(0.6, 0.6, 0.6)'
3.116332
1.326354
2.349547
'''Maps a hue on the RGB color wheel to Itten's RYB wheel. Parameters: :hue: The hue on the RGB color wheel [0...360] Returns: An approximation of the corresponding hue on Itten's RYB wheel. >>> Color.RgbToRyb(15) 26.0 ''' d = hue % 15 i = int(hue / 15) x0 = _RybWheel[i] x1 = _RybWheel[i+1] return x0 + (x1-x0) * d / 15
def RgbToRyb(hue)
Maps a hue on the RGB color wheel to Itten's RYB wheel. Parameters: :hue: The hue on the RGB color wheel [0...360] Returns: An approximation of the corresponding hue on Itten's RYB wheel. >>> Color.RgbToRyb(15) 26.0
4.828063
2.02416
2.385218
'''Maps a hue on Itten's RYB color wheel to the standard RGB wheel. Parameters: :hue: The hue on Itten's RYB color wheel [0...360] Returns: An approximation of the corresponding hue on the standard RGB wheel. >>> Color.RybToRgb(15) 8.0 ''' d = hue % 15 i = int(hue / 15) x0 = _RgbWheel[i] x1 = _RgbWheel[i+1] return x0 + (x1-x0) * d / 15
def RybToRgb(hue)
Maps a hue on Itten's RYB color wheel to the standard RGB wheel. Parameters: :hue: The hue on Itten's RYB color wheel [0...360] Returns: An approximation of the corresponding hue on the standard RGB wheel. >>> Color.RybToRgb(15) 8.0
5.492454
2.119704
2.591141
'''Create a new instance based on the specifed RGB values. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.NewFromRgb(1.0, 0.5, 0.0) (1.0, 0.5, 0.0, 1.0) >>> Color.NewFromRgb(1.0, 0.5, 0.0, 0.5) (1.0, 0.5, 0.0, 0.5) ''' return Color((r, g, b), 'rgb', alpha, wref)
def NewFromRgb(r, g, b, alpha=1.0, wref=_DEFAULT_WREF)
Create a new instance based on the specifed RGB values. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.NewFromRgb(1.0, 0.5, 0.0) (1.0, 0.5, 0.0, 1.0) >>> Color.NewFromRgb(1.0, 0.5, 0.0, 0.5) (1.0, 0.5, 0.0, 0.5)
2.342365
1.264838
1.851909
'''Create a new instance based on the specifed HSL values. Parameters: :h: The Hue component value [0...1] :s: The Saturation component value [0...1] :l: The Lightness component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5) (1.0, 0.5, 0.0, 1.0) >>> Color.NewFromHsl(30, 1, 0.5, 0.5) (1.0, 0.5, 0.0, 0.5) ''' return Color((h, s, l), 'hsl', alpha, wref)
def NewFromHsl(h, s, l, alpha=1.0, wref=_DEFAULT_WREF)
Create a new instance based on the specifed HSL values. Parameters: :h: The Hue component value [0...1] :s: The Saturation component value [0...1] :l: The Lightness component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5) (1.0, 0.5, 0.0, 1.0) >>> Color.NewFromHsl(30, 1, 0.5, 0.5) (1.0, 0.5, 0.0, 0.5)
2.452529
1.27791
1.919173
'''Create a new instance based on the specifed HSV values. Parameters: :h: The Hus component value [0...1] :s: The Saturation component value [0...1] :v: The Value component [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.NewFromHsv(30, 1, 1) (1.0, 0.5, 0.0, 1.0) >>> Color.NewFromHsv(30, 1, 1, 0.5) (1.0, 0.5, 0.0, 0.5) ''' h2, s, l = Color.RgbToHsl(*Color.HsvToRgb(h, s, v)) return Color((h, s, l), 'hsl', alpha, wref)
def NewFromHsv(h, s, v, alpha=1.0, wref=_DEFAULT_WREF)
Create a new instance based on the specifed HSV values. Parameters: :h: The Hus component value [0...1] :s: The Saturation component value [0...1] :v: The Value component [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.NewFromHsv(30, 1, 1) (1.0, 0.5, 0.0, 1.0) >>> Color.NewFromHsv(30, 1, 1, 0.5) (1.0, 0.5, 0.0, 0.5)
2.991392
1.45758
2.052301
'''Create a new instance based on the specifed YIQ values. Parameters: :y: The Y component value [0...1] :i: The I component value [0...1] :q: The Q component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> str(Color.NewFromYiq(0.5922, 0.45885,-0.05)) '(0.999902, 0.499955, -6.6905e-05, 1)' >>> str(Color.NewFromYiq(0.5922, 0.45885,-0.05, 0.5)) '(0.999902, 0.499955, -6.6905e-05, 0.5)' ''' return Color(Color.YiqToRgb(y, i, q), 'rgb', alpha, wref)
def NewFromYiq(y, i, q, alpha=1.0, wref=_DEFAULT_WREF)
Create a new instance based on the specifed YIQ values. Parameters: :y: The Y component value [0...1] :i: The I component value [0...1] :q: The Q component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> str(Color.NewFromYiq(0.5922, 0.45885,-0.05)) '(0.999902, 0.499955, -6.6905e-05, 1)' >>> str(Color.NewFromYiq(0.5922, 0.45885,-0.05, 0.5)) '(0.999902, 0.499955, -6.6905e-05, 0.5)'
2.889098
1.231822
2.345386
'''Create a new instance based on the specifed YUV values. Parameters: :y: The Y component value [0...1] :u: The U component value [-0.436...0.436] :v: The V component value [-0.615...0.615] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> str(Color.NewFromYuv(0.5925, -0.2916, 0.3575)) '(0.999989, 0.500015, -6.3276e-05, 1)' >>> str(Color.NewFromYuv(0.5925, -0.2916, 0.3575, 0.5)) '(0.999989, 0.500015, -6.3276e-05, 0.5)' ''' return Color(Color.YuvToRgb(y, u, v), 'rgb', alpha, wref)
def NewFromYuv(y, u, v, alpha=1.0, wref=_DEFAULT_WREF)
Create a new instance based on the specifed YUV values. Parameters: :y: The Y component value [0...1] :u: The U component value [-0.436...0.436] :v: The V component value [-0.615...0.615] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> str(Color.NewFromYuv(0.5925, -0.2916, 0.3575)) '(0.999989, 0.500015, -6.3276e-05, 1)' >>> str(Color.NewFromYuv(0.5925, -0.2916, 0.3575, 0.5)) '(0.999989, 0.500015, -6.3276e-05, 0.5)'
2.786368
1.219413
2.285008
'''Create a new instance based on the specifed CIE-XYZ values. Parameters: :x: The Red component value [0...1] :y: The Green component value [0...1] :z: The Blue component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> str(Color.NewFromXyz(0.488941, 0.365682, 0.0448137)) '(1, 0.5, 6.81883e-08, 1)' >>> str(Color.NewFromXyz(0.488941, 0.365682, 0.0448137, 0.5)) '(1, 0.5, 6.81883e-08, 0.5)' ''' return Color(Color.XyzToRgb(x, y, z), 'rgb', alpha, wref)
def NewFromXyz(x, y, z, alpha=1.0, wref=_DEFAULT_WREF)
Create a new instance based on the specifed CIE-XYZ values. Parameters: :x: The Red component value [0...1] :y: The Green component value [0...1] :z: The Blue component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> str(Color.NewFromXyz(0.488941, 0.365682, 0.0448137)) '(1, 0.5, 6.81883e-08, 1)' >>> str(Color.NewFromXyz(0.488941, 0.365682, 0.0448137, 0.5)) '(1, 0.5, 6.81883e-08, 0.5)'
2.938586
1.257287
2.337244
'''Create a new instance based on the specifed CIE-LAB values. Parameters: :l: The L component [0...100] :a: The a component [-1...1] :b: The a component [-1...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> str(Color.NewFromLab(66.9518, 0.43084, 0.739692)) '(1, 0.5, 1.09491e-08, 1)' >>> str(Color.NewFromLab(66.9518, 0.43084, 0.739692, wref=Color.WHITE_REFERENCE['std_D50'])) '(1.01238, 0.492011, -0.14311, 1)' >>> str(Color.NewFromLab(66.9518, 0.43084, 0.739692, 0.5)) '(1, 0.5, 1.09491e-08, 0.5)' >>> str(Color.NewFromLab(66.9518, 0.43084, 0.739692, 0.5, Color.WHITE_REFERENCE['std_D50'])) '(1.01238, 0.492011, -0.14311, 0.5)' ''' return Color(Color.XyzToRgb(*Color.LabToXyz(l, a, b, wref)), 'rgb', alpha, wref)
def NewFromLab(l, a, b, alpha=1.0, wref=_DEFAULT_WREF)
Create a new instance based on the specifed CIE-LAB values. Parameters: :l: The L component [0...100] :a: The a component [-1...1] :b: The a component [-1...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> str(Color.NewFromLab(66.9518, 0.43084, 0.739692)) '(1, 0.5, 1.09491e-08, 1)' >>> str(Color.NewFromLab(66.9518, 0.43084, 0.739692, wref=Color.WHITE_REFERENCE['std_D50'])) '(1.01238, 0.492011, -0.14311, 1)' >>> str(Color.NewFromLab(66.9518, 0.43084, 0.739692, 0.5)) '(1, 0.5, 1.09491e-08, 0.5)' >>> str(Color.NewFromLab(66.9518, 0.43084, 0.739692, 0.5, Color.WHITE_REFERENCE['std_D50'])) '(1.01238, 0.492011, -0.14311, 0.5)'
2.557651
1.18821
2.152524
'''Create a new instance based on the specifed CMY values. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.NewFromCmy(0, 0.5, 1) (1, 0.5, 0, 1.0) >>> Color.NewFromCmy(0, 0.5, 1, 0.5) (1, 0.5, 0, 0.5) ''' return Color(Color.CmyToRgb(c, m, y), 'rgb', alpha, wref)
def NewFromCmy(c, m, y, alpha=1.0, wref=_DEFAULT_WREF)
Create a new instance based on the specifed CMY values. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.NewFromCmy(0, 0.5, 1) (1, 0.5, 0, 1.0) >>> Color.NewFromCmy(0, 0.5, 1, 0.5) (1, 0.5, 0, 0.5)
2.618972
1.321325
1.982081
'''Create a new instance based on the specifed CMYK values. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :k: The Black component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> str(Color.NewFromCmyk(1, 0.32, 0, 0.5)) '(0, 0.34, 0.5, 1)' >>> str(Color.NewFromCmyk(1, 0.32, 0, 0.5, 0.5)) '(0, 0.34, 0.5, 0.5)' ''' return Color(Color.CmyToRgb(*Color.CmykToCmy(c, m, y, k)), 'rgb', alpha, wref)
def NewFromCmyk(c, m, y, k, alpha=1.0, wref=_DEFAULT_WREF)
Create a new instance based on the specifed CMYK values. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :k: The Black component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> str(Color.NewFromCmyk(1, 0.32, 0, 0.5)) '(0, 0.34, 0.5, 1)' >>> str(Color.NewFromCmyk(1, 0.32, 0, 0.5, 0.5)) '(0, 0.34, 0.5, 0.5)'
2.542444
1.347453
1.886851
'''Create a new instance based on the specifed HTML color definition. Parameters: :html: The HTML definition of the color (#RRGGBB or #RGB or a color name). :alpha: The color transparency [0...1], default is opaque. :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> str(Color.NewFromHtml('#ff8000')) '(1, 0.501961, 0, 1)' >>> str(Color.NewFromHtml('ff8000')) '(1, 0.501961, 0, 1)' >>> str(Color.NewFromHtml('#f60')) '(1, 0.4, 0, 1)' >>> str(Color.NewFromHtml('f60')) '(1, 0.4, 0, 1)' >>> str(Color.NewFromHtml('lemonchiffon')) '(1, 0.980392, 0.803922, 1)' >>> str(Color.NewFromHtml('#ff8000', 0.5)) '(1, 0.501961, 0, 0.5)' ''' return Color(Color.HtmlToRgb(html), 'rgb', alpha, wref)
def NewFromHtml(html, alpha=1.0, wref=_DEFAULT_WREF)
Create a new instance based on the specifed HTML color definition. Parameters: :html: The HTML definition of the color (#RRGGBB or #RGB or a color name). :alpha: The color transparency [0...1], default is opaque. :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> str(Color.NewFromHtml('#ff8000')) '(1, 0.501961, 0, 1)' >>> str(Color.NewFromHtml('ff8000')) '(1, 0.501961, 0, 1)' >>> str(Color.NewFromHtml('#f60')) '(1, 0.4, 0, 1)' >>> str(Color.NewFromHtml('f60')) '(1, 0.4, 0, 1)' >>> str(Color.NewFromHtml('lemonchiffon')) '(1, 0.980392, 0.803922, 1)' >>> str(Color.NewFromHtml('#ff8000', 0.5)) '(1, 0.501961, 0, 0.5)'
2.401185
1.211646
1.981755
'''Create a new instance based on the specifed PIL color. Parameters: :pil: A PIL compatible color representation (0xBBGGRR) :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> str(Color.NewFromPil(0x0080ff)) '(1, 0.501961, 0, 1)' >>> str(Color.NewFromPil(0x0080ff, 0.5)) '(1, 0.501961, 0, 0.5)' ''' return Color(Color.PilToRgb(pil), 'rgb', alpha, wref)
def NewFromPil(pil, alpha=1.0, wref=_DEFAULT_WREF)
Create a new instance based on the specifed PIL color. Parameters: :pil: A PIL compatible color representation (0xBBGGRR) :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> str(Color.NewFromPil(0x0080ff)) '(1, 0.501961, 0, 1)' >>> str(Color.NewFromPil(0x0080ff, 0.5)) '(1, 0.501961, 0, 0.5)'
3.901101
1.386219
2.814202
'''Create a new instance based on this one with a new white reference. Parameters: :wref: The whitepoint reference. :labAsRef: If True, the L*a*b* values of the current instance are used as reference for the new color; otherwise, the RGB values are used as reference. Returns: A grapefruit.Color instance. >>> c = Color.NewFromRgb(1.0, 0.5, 0.0, 1.0, Color.WHITE_REFERENCE['std_D65']) >>> c2 = c.ColorWithWhiteRef(Color.WHITE_REFERENCE['sup_D50']) >>> c2.rgb (1.0, 0.5, 0.0) >>> '(%g, %g, %g)' % c2.whiteRef '(0.96721, 1, 0.81428)' >>> c2 = c.ColorWithWhiteRef(Color.WHITE_REFERENCE['sup_D50'], labAsRef=True) >>> '(%g, %g, %g)' % c2.rgb '(1.01463, 0.490339, -0.148131)' >>> '(%g, %g, %g)' % c2.whiteRef '(0.96721, 1, 0.81428)' >>> '(%g, %g, %g)' % c.lab '(66.9518, 0.43084, 0.739692)' >>> '(%g, %g, %g)' % c2.lab '(66.9518, 0.43084, 0.739693)' ''' if labAsRef: l, a, b = self.__GetLAB() return Color.NewFromLab(l, a, b, self.__a, wref) else: return Color(self.__rgb, 'rgb', self.__a, wref)
def ColorWithWhiteRef(self, wref, labAsRef=False)
Create a new instance based on this one with a new white reference. Parameters: :wref: The whitepoint reference. :labAsRef: If True, the L*a*b* values of the current instance are used as reference for the new color; otherwise, the RGB values are used as reference. Returns: A grapefruit.Color instance. >>> c = Color.NewFromRgb(1.0, 0.5, 0.0, 1.0, Color.WHITE_REFERENCE['std_D65']) >>> c2 = c.ColorWithWhiteRef(Color.WHITE_REFERENCE['sup_D50']) >>> c2.rgb (1.0, 0.5, 0.0) >>> '(%g, %g, %g)' % c2.whiteRef '(0.96721, 1, 0.81428)' >>> c2 = c.ColorWithWhiteRef(Color.WHITE_REFERENCE['sup_D50'], labAsRef=True) >>> '(%g, %g, %g)' % c2.rgb '(1.01463, 0.490339, -0.148131)' >>> '(%g, %g, %g)' % c2.whiteRef '(0.96721, 1, 0.81428)' >>> '(%g, %g, %g)' % c.lab '(66.9518, 0.43084, 0.739692)' >>> '(%g, %g, %g)' % c2.lab '(66.9518, 0.43084, 0.739693)'
2.887632
1.241519
2.325886
'''Create a new instance based on this one with a new hue. Parameters: :hue: The hue of the new color [0...360]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).ColorWithHue(60) (1.0, 1.0, 0.0, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).ColorWithHue(60).hsl (60, 1, 0.5) ''' h, s, l = self.__hsl return Color((hue, s, l), 'hsl', self.__a, self.__wref)
def ColorWithHue(self, hue)
Create a new instance based on this one with a new hue. Parameters: :hue: The hue of the new color [0...360]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).ColorWithHue(60) (1.0, 1.0, 0.0, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).ColorWithHue(60).hsl (60, 1, 0.5)
3.571657
1.644838
2.171435
'''Create a new instance based on this one with a new saturation value. .. note:: The saturation is defined for the HSL mode. Parameters: :saturation: The saturation of the new color [0...1]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).ColorWithSaturation(0.5) (0.75, 0.5, 0.25, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).ColorWithSaturation(0.5).hsl (30, 0.5, 0.5) ''' h, s, l = self.__hsl return Color((h, saturation, l), 'hsl', self.__a, self.__wref)
def ColorWithSaturation(self, saturation)
Create a new instance based on this one with a new saturation value. .. note:: The saturation is defined for the HSL mode. Parameters: :saturation: The saturation of the new color [0...1]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).ColorWithSaturation(0.5) (0.75, 0.5, 0.25, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).ColorWithSaturation(0.5).hsl (30, 0.5, 0.5)
3.519031
1.537316
2.289075
'''Create a new instance based on this one with a new lightness value. Parameters: :lightness: The lightness of the new color [0...1]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).ColorWithLightness(0.25) (0.5, 0.25, 0.0, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).ColorWithLightness(0.25).hsl (30, 1, 0.25) ''' h, s, l = self.__hsl return Color((h, s, lightness), 'hsl', self.__a, self.__wref)
def ColorWithLightness(self, lightness)
Create a new instance based on this one with a new lightness value. Parameters: :lightness: The lightness of the new color [0...1]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).ColorWithLightness(0.25) (0.5, 0.25, 0.0, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).ColorWithLightness(0.25).hsl (30, 1, 0.25)
3.261102
1.597862
2.040916
'''Create a new instance based on this one but lighter. Parameters: :level: The amount by which the color should be lightened to produce the new one [0...1]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).LighterColor(0.25) (1.0, 0.75, 0.5, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).LighterColor(0.25).hsl (30, 1, 0.75) ''' h, s, l = self.__hsl return Color((h, s, min(l + level, 1)), 'hsl', self.__a, self.__wref)
def LighterColor(self, level)
Create a new instance based on this one but lighter. Parameters: :level: The amount by which the color should be lightened to produce the new one [0...1]. Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).LighterColor(0.25) (1.0, 0.75, 0.5, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).LighterColor(0.25).hsl (30, 1, 0.75)
3.55576
1.591718
2.233913
'''Return the two websafe colors nearest to this one. Returns: A tuple of two grapefruit.Color instances which are the two web safe colors closest this one. >>> c = Color.NewFromRgb(1.0, 0.45, 0.0) >>> c1, c2 = c.WebSafeDither() >>> str(c1) '(1, 0.4, 0, 1)' >>> str(c2) '(1, 0.6, 0, 1)' ''' return ( Color(Color.RgbToWebSafe(*self.__rgb), 'rgb', self.__a, self.__wref), Color(Color.RgbToWebSafe(alt=True, *self.__rgb), 'rgb', self.__a, self.__wref))
def WebSafeDither(self)
Return the two websafe colors nearest to this one. Returns: A tuple of two grapefruit.Color instances which are the two web safe colors closest this one. >>> c = Color.NewFromRgb(1.0, 0.45, 0.0) >>> c1, c2 = c.WebSafeDither() >>> str(c1) '(1, 0.4, 0, 1)' >>> str(c2) '(1, 0.6, 0, 1)'
4.500936
2.041766
2.204433
'''Create a list with the gradient colors between this and the other color. Parameters: :target: The grapefruit.Color at the other end of the gradient. :steps: The number of gradients steps to create. Returns: A list of grapefruit.Color instances. >>> c1 = Color.NewFromRgb(1.0, 0.0, 0.0, alpha=1) >>> c2 = Color.NewFromRgb(0.0, 1.0, 0.0, alpha=0) >>> c1.Gradient(c2, 3) [(0.75, 0.25, 0.0, 0.75), (0.5, 0.5, 0.0, 0.5), (0.25, 0.75, 0.0, 0.25)] ''' gradient = [] rgba1 = self.__rgb + (self.__a,) rgba2 = target.__rgb + (target.__a,) steps += 1 for n in range(1, steps): d = 1.0*n/steps r = (rgba1[0]*(1-d)) + (rgba2[0]*d) g = (rgba1[1]*(1-d)) + (rgba2[1]*d) b = (rgba1[2]*(1-d)) + (rgba2[2]*d) a = (rgba1[3]*(1-d)) + (rgba2[3]*d) gradient.append(Color((r, g, b), 'rgb', a, self.__wref)) return gradient
def Gradient(self, target, steps=100)
Create a list with the gradient colors between this and the other color. Parameters: :target: The grapefruit.Color at the other end of the gradient. :steps: The number of gradients steps to create. Returns: A list of grapefruit.Color instances. >>> c1 = Color.NewFromRgb(1.0, 0.0, 0.0, alpha=1) >>> c2 = Color.NewFromRgb(0.0, 1.0, 0.0, alpha=0) >>> c1.Gradient(c2, 3) [(0.75, 0.25, 0.0, 0.75), (0.5, 0.5, 0.0, 0.5), (0.25, 0.75, 0.0, 0.25)]
2.464075
1.499947
1.642775
'''Create a new instance which is the complementary color of this one. Parameters: :mode: Select which color wheel to use for the generation (ryb/rgb). Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).ComplementaryColor(mode='rgb') (0.0, 0.5, 1.0, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).ComplementaryColor(mode='rgb').hsl (210, 1, 0.5) ''' h, s, l = self.__hsl if mode == 'ryb': h = Color.RgbToRyb(h) h = (h+180)%360 if mode == 'ryb': h = Color.RybToRgb(h) return Color((h, s, l), 'hsl', self.__a, self.__wref)
def ComplementaryColor(self, mode='ryb')
Create a new instance which is the complementary color of this one. Parameters: :mode: Select which color wheel to use for the generation (ryb/rgb). Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).ComplementaryColor(mode='rgb') (0.0, 0.5, 1.0, 1.0) >>> Color.NewFromHsl(30, 1, 0.5).ComplementaryColor(mode='rgb').hsl (210, 1, 0.5)
3.547318
1.695795
2.091832
'''Return 4 colors in the same hue with varying saturation/lightness. Returns: A tuple of 4 grapefruit.Color in the same hue as this one, with varying saturation/lightness. >>> c = Color.NewFromHsl(30, 0.5, 0.5) >>> ['(%g, %g, %g)' % clr.hsl for clr in c.MonochromeScheme()] ['(30, 0.2, 0.8)', '(30, 0.5, 0.3)', '(30, 0.2, 0.6)', '(30, 0.5, 0.8)'] ''' def _wrap(x, min, thres, plus): if (x-min) < thres: return x + plus else: return x-min h, s, l = self.__hsl s1 = _wrap(s, 0.3, 0.1, 0.3) l1 = _wrap(l, 0.5, 0.2, 0.3) s2 = s l2 = _wrap(l, 0.2, 0.2, 0.6) s3 = s1 l3 = max(0.2, l + (1-l)*0.2) s4 = s l4 = _wrap(l, 0.5, 0.2, 0.3) return ( Color((h, s1, l1), 'hsl', self.__a, self.__wref), Color((h, s2, l2), 'hsl', self.__a, self.__wref), Color((h, s3, l3), 'hsl', self.__a, self.__wref), Color((h, s4, l4), 'hsl', self.__a, self.__wref))
def MonochromeScheme(self)
Return 4 colors in the same hue with varying saturation/lightness. Returns: A tuple of 4 grapefruit.Color in the same hue as this one, with varying saturation/lightness. >>> c = Color.NewFromHsl(30, 0.5, 0.5) >>> ['(%g, %g, %g)' % clr.hsl for clr in c.MonochromeScheme()] ['(30, 0.2, 0.8)', '(30, 0.5, 0.3)', '(30, 0.2, 0.6)', '(30, 0.5, 0.8)']
2.673347
1.80443
1.481546
'''Return two colors forming a triad or a split complementary with this one. Parameters: :angle: The angle between the hues of the created colors. The default value makes a triad. :mode: Select which color wheel to use for the generation (ryb/rgb). Returns: A tuple of two grapefruit.Color forming a color triad with this one or a split complementary. >>> c1 = Color.NewFromHsl(30, 1, 0.5) >>> c2, c3 = c1.TriadicScheme(mode='rgb') >>> c2.hsl (150.0, 1, 0.5) >>> c3.hsl (270.0, 1, 0.5) >>> c2, c3 = c1.TriadicScheme(angle=40, mode='rgb') >>> c2.hsl (190.0, 1, 0.5) >>> c3.hsl (230.0, 1, 0.5) ''' h, s, l = self.__hsl angle = min(angle, 120) / 2.0 if mode == 'ryb': h = Color.RgbToRyb(h) h += 180 h1 = (h - angle) % 360 h2 = (h + angle) % 360 if mode == 'ryb': h1 = Color.RybToRgb(h1) h2 = Color.RybToRgb(h2) return ( Color((h1, s, l), 'hsl', self.__a, self.__wref), Color((h2, s, l), 'hsl', self.__a, self.__wref))
def TriadicScheme(self, angle=120, mode='ryb')
Return two colors forming a triad or a split complementary with this one. Parameters: :angle: The angle between the hues of the created colors. The default value makes a triad. :mode: Select which color wheel to use for the generation (ryb/rgb). Returns: A tuple of two grapefruit.Color forming a color triad with this one or a split complementary. >>> c1 = Color.NewFromHsl(30, 1, 0.5) >>> c2, c3 = c1.TriadicScheme(mode='rgb') >>> c2.hsl (150.0, 1, 0.5) >>> c3.hsl (270.0, 1, 0.5) >>> c2, c3 = c1.TriadicScheme(angle=40, mode='rgb') >>> c2.hsl (190.0, 1, 0.5) >>> c3.hsl (230.0, 1, 0.5)
3.149694
1.54467
2.039073
rgb = GC.NewFromHtml(html_string).rgb return cls("rgb", *rgb)
def from_html(cls, html_string)
Create sRGB color from a web-color name or hexcode. :param str html_string: Web-color name or hexcode. :rtype: Color :returns: A spectra.Color in the sRGB color space.
30.601519
44.555706
0.686815
if space == self.space: return self new_color = convert_color(self.color_object, COLOR_SPACES[space]) return self.__class__(space, *new_color.get_value_tuple())
def to(self, space)
Convert color to a different color space. :param str space: Name of the color space. :rtype: Color :returns: A new spectra.Color in the given color space.
6.931212
6.274456
1.104672
keep = 1.0 - ratio if not self.space == other.space: raise Exception("Colors must belong to the same color space.") values = tuple(((u * keep) + (v * ratio) for u, v in zip(self.values, other.values))) return self.__class__(self.space, *values)
def blend(self, other, ratio=0.5)
Blend this color with another color in the same color space. By default, blends the colors half-and-half (ratio: 0.5). :param Color other: The color to blend. :param float ratio: How much to blend (0 -> 1). :rtype: Color :returns: A new spectra.Color
4.515359
4.940555
0.913938
lch = self.to("lch") l, c, h = lch.values new_lch = self.__class__("lch", l + amount, c, h) return new_lch.to(self.space)
def brighten(self, amount=10)
Brighten this color by `amount` luminance. Converts this color to the LCH color space, and then increases the `L` parameter by `amount`. :param float amount: Amount to increase the luminance. :rtype: Color :returns: A new spectra.Color
4.223915
4.5235
0.933771
new_colors = [ c.to(space) for c in self.colors ] return self.__class__(new_colors, self._domain)
def colorspace(self, space)
Create a new scale in the given color space. :param str space: The new color space. :rtype: Scale :returns: A new color.Scale object.
5.590292
8.106457
0.68961
if count <= 1: raise ValueError("Range size must be greater than 1.") dom = self._domain distance = dom[-1] - dom[0] props = [ self(dom[0] + distance * float(x)/(count-1)) for x in range(count) ] return props
def range(self, count)
Create a list of colors evenly spaced along this scale's domain. :param int count: The number of colors to return. :rtype: list :returns: A list of spectra.Color objects.
5.171056
4.817567
1.073375
root_order = ["jsonrpc", "result", "error", "id"] error_order = ["code", "message", "data"] req = OrderedDict(sorted(response.items(), key=lambda k: root_order.index(k[0]))) if "error" in response: req["error"] = OrderedDict( sorted(response["error"].items(), key=lambda k: error_order.index(k[0])) ) return req
def sort_response(response: Dict[str, Any]) -> OrderedDict
Sort the keys in a JSON-RPC response object. This has no effect other than making it nicer to read. Useful in Python 3.5 only, dictionaries are already sorted in newer Python versions. Example:: >>> json.dumps(sort_response({'id': 2, 'result': 5, 'jsonrpc': '2.0'})) {"jsonrpc": "2.0", "result": 5, "id": 1} Args: response: Deserialized JSON-RPC response. Returns: The same response, sorted in an OrderedDict.
2.284276
2.455446
0.93029
if isinstance(data, list): return sum([1 for d in data if d.ok == ok]) elif isinstance(data, JSONRPCResponse): return int(data.ok == ok) return 0
def total_results( data: Union[List[JSONRPCResponse], JSONRPCResponse, None], *, ok: bool = True ) -> int
Returns the total parsed responses, given the return value from parse().
2.635535
2.487683
1.059434
with async_timeout.timeout(self.timeout): async with self.session.post( self.endpoint, data=request, ssl=self.ssl ) as response: response_text = await response.text() return Response(response_text, raw=response)
async def send_message( self, request: str, response_expected: bool, **kwargs: Any ) -> Response
Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object.
3.002851
3.143195
0.95535
await self.socket.send(request) if response_expected: response_text = await self.socket.recv() return Response(response_text) return Response("")
async def send_message( self, request: str, response_expected: bool, **kwargs: Any ) -> Response
Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object.
3.260062
3.704261
0.880085
module = path[: path.rindex(".")] callable_name = path[path.rindex(".") + 1 :] callable_ = getattr(importlib.import_module(module), callable_name) return callable_()
def parse_callable(path: str) -> Iterator
ConfigParser converter. Calls the specified object, e.g. Option "id_generators.decimal" returns `id_generators.decimal()`.
3.299876
3.440781
0.959048
while True: yield "".join([choice(chars) for _ in range(length)])
def random(length: int = 8, chars: str = digits + ascii_lowercase) -> Iterator[str]
A random string. Not unique, but has around 1 in a million chance of collision (with the default 8 character length). e.g. 'fubui5e6' Args: length: Length of the random string. chars: The characters to randomly choose from.
2.941629
4.816555
0.610733
if "error" in response: return ErrorResponse(**response) return SuccessResponse(**response)
def get_response(response: Dict[str, Any]) -> JSONRPCResponse
Converts a deserialized response into a JSONRPCResponse object. The dictionary be either an error or success response, never a notification. Args: response: Deserialized response dictionary. We can assume the response is valid JSON-RPC here, since it passed the jsonschema validation.
5.456021
7.667003
0.711624
# If the response is empty, we can't deserialize it; an empty string is valid # JSON-RPC, but not valid JSON. if not response_text: if batch: # An empty string is a valid response to a batch request, when there were # only notifications in the batch. return [] else: # An empty string is valid response to a Notification request. return NotificationResponse() # If a string, ensure it's json-deserializable deserialized = deserialize(response_text) # Validate the response against the Response schema (raises # jsonschema.ValidationError if invalid) if validate_against_schema: jsonschema.validate(deserialized, schema) # Batch response if isinstance(deserialized, list): return [get_response(r) for r in deserialized if "id" in r] # Single response return get_response(deserialized)
def parse( response_text: str, *, batch: bool, validate_against_schema: bool = True ) -> Union[JSONRPCResponse, List[JSONRPCResponse]]
Parses response text, returning JSONRPCResponse objects. Args: response_text: JSON-RPC response string. batch: If the response_text is an empty string, this determines how to parse. validate_against_schema: Validate against the json-rpc schema. Returns: Either a JSONRPCResponse, or a list of them. Raises: json.JSONDecodeError: The response was not valid JSON. jsonschema.ValidationError: The response was not a valid JSON-RPC response object.
4.414981
4.308304
1.024761
# We need both the serialized and deserialized version of the request if isinstance(request, str): request_text = request request_deserialized = deserialize(request) else: request_text = serialize(request) request_deserialized = request batch = isinstance(request_deserialized, list) response_expected = batch or "id" in request_deserialized self.log_request(request_text, trim_log_values=trim_log_values) response = await self.send_message( request_text, response_expected=response_expected, **kwargs ) self.log_response(response, trim_log_values=trim_log_values) self.validate_response(response) response.data = parse( response.text, batch=batch, validate_against_schema=validate_against_schema ) # If received a single error response, raise if isinstance(response.data, ErrorResponse): raise ReceivedErrorResponseError(response.data) return response
async def send( self, request: Union[str, Dict, List], trim_log_values: bool = False, validate_against_schema: bool = True, **kwargs: Any ) -> Response
Async version of Client.send.
2.956934
2.912565
1.015234
headers = dict(self.DEFAULT_HEADERS) headers.update(kwargs.pop("headers", {})) response = await self.client.fetch( self.endpoint, method="POST", body=request, headers=headers, **kwargs ) return Response(response.body.decode(), raw=response)
async def send_message( # type: ignore self, request: str, response_expected: bool, **kwargs: Any ) -> Response
Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object.
3.326962
3.463773
0.960502
exit_status = 0 # Extract the jsonrpc arguments positional = [a for a in context.args if "=" not in a] named = {a.split("=")[0]: a.split("=")[1] for a in context.args if "=" in a} # Create the request if request_type == "notify": req = Notification(method, *positional, **named) else: req = Request(method, *positional, request_id=id, **named) # type: ignore # Sending? if send: client = HTTPClient(send) try: response = client.send(req) except JsonRpcClientError as e: click.echo(str(e), err=True) exit_status = 1 else: click.echo(response.text) # Otherwise, simply output the JSON-RPC request. else: click.echo(str(req)) sys.exit(exit_status)
def main( context: click.core.Context, method: str, request_type: str, id: Any, send: str ) -> None
Create a JSON-RPC request.
2.854961
2.602654
1.096942
if extra is None: extra = {} # Clean up the message for logging if message: message = message.replace("\n", "").replace(" ", " ").replace("{ ", "{") if trim: message = _trim_message(message) # Log. getattr(logger, level)(message, extra=extra)
def log_( message: str, logger: logging.Logger, level: str = "info", extra: Optional[Dict] = None, trim: bool = False, ) -> None
Log a request or response Args: message: JSON-RPC request or response string. level: Log level. extra: More details to include in the log entry. trim: Abbreviate log messages.
3.982939
3.862546
1.031169
sort_order = ["jsonrpc", "method", "params", "id"] return OrderedDict(sorted(request.items(), key=lambda k: sort_order.index(k[0])))
def sort_request(request: Dict[str, Any]) -> OrderedDict
Sort a JSON-RPC request dict. This has no effect other than making the request nicer to read. >>> json.dumps(sort_request( ... {'id': 2, 'params': [2, 3], 'method': 'add', 'jsonrpc': '2.0'})) '{"jsonrpc": "2.0", "method": "add", "params": [2, 3], "id": 2}' Args: request: JSON-RPC request in dict format.
3.135538
4.726992
0.663326
# Request handler if len(request_log.handlers) == 0: request_handler = logging.StreamHandler() request_handler.setFormatter( logging.Formatter(fmt=self.DEFAULT_REQUEST_LOG_FORMAT) ) request_log.addHandler(request_handler) request_log.setLevel(logging.INFO) # Response handler if len(response_log.handlers) == 0: response_handler = logging.StreamHandler() response_handler.setFormatter( logging.Formatter(fmt=self.DEFAULT_RESPONSE_LOG_FORMAT) ) response_log.addHandler(response_handler) response_log.setLevel(logging.INFO)
def basic_logging(self) -> None
Call this on the client object to create log handlers to output request and response messages.
1.772969
1.632757
1.085874
return log_(request, request_log, "info", trim=trim_log_values, **kwargs)
def log_request( self, request: str, trim_log_values: bool = False, **kwargs: Any ) -> None
Log a request. Args: request: The JSON-RPC request string. trim_log_values: Log an abbreviated version of the request.
13.860272
14.333539
0.966982
return log_(response.text, response_log, "info", trim=trim_log_values, **kwargs)
def log_response( self, response: Response, trim_log_values: bool = False, **kwargs: Any ) -> None
Log a response. Note this is different to log_request, in that it takes a Response object, not a string. Args: response: The Response object to log. Note this is different to log_request which takes a string. trim_log_values: Log an abbreviated version of the response.
15.983236
17.937197
0.891067
return self.send( Notification(method_name, *args, **kwargs), trim_log_values=trim_log_values, validate_against_schema=validate_against_schema, )
def notify( self, method_name: str, *args: Any, trim_log_values: Optional[bool] = None, validate_against_schema: Optional[bool] = None, **kwargs: Any ) -> Response
Send a JSON-RPC request, without expecting a response. Args: method_name: The remote procedure's method name. args: Positional arguments passed to the remote procedure. kwargs: Keyword arguments passed to the remote procedure. trim_log_values: Abbreviate the log entries of requests and responses. validate_against_schema: Validate response against the JSON-RPC schema.
2.121562
2.316833
0.915717
return self.send( Request(method_name, id_generator=id_generator, *args, **kwargs), trim_log_values=trim_log_values, validate_against_schema=validate_against_schema, )
def request( self, method_name: str, *args: Any, trim_log_values: bool = False, validate_against_schema: bool = True, id_generator: Optional[Iterator] = None, **kwargs: Any ) -> Response
Send a request by passing the method and arguments. >>> client.request("cat", name="Yoko") <Response[1] Args: method_name: The remote procedure's method name. args: Positional arguments passed to the remote procedure. kwargs: Keyword arguments passed to the remote procedure. trim_log_values: Abbreviate the log entries of requests and responses. validate_against_schema: Validate response against the JSON-RPC schema. id_generator: Iterable of values to use as the "id" part of the request.
1.984559
2.234626
0.888095
payload = str(request) + self.delimiter self.socket.send(payload.encode(self.encoding)) response = bytes() decoded = None # Receive the response until we find the delimiter. # TODO Do not wait for a response if the message sent is a notification. while True: response += self.socket.recv(1024) decoded = response.decode(self.encoding) if len(decoded) < self.delimiter_length: continue # TODO Check that're not in the middle of the response. elif decoded[-self.delimiter_length :] == self.delimiter: break assert decoded is not None return Response(decoded[: -self.delimiter_length])
def send_message( self, request: str, response_expected: bool, **kwargs: Any ) -> Response
Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object.
4.534997
4.379014
1.035621
response = self.session.post(self.endpoint, data=request.encode(), **kwargs) return Response(response.text, raw=response)
def send_message( self, request: str, response_expected: bool, **kwargs: Any ) -> Response
Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object.
4.596635
5.342785
0.860344
self.socket.send_string(request) return Response(self.socket.recv().decode())
def send_message( self, request: str, response_expected: bool, **kwargs: Any ) -> Response
Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object.
6.00173
6.35208
0.944845
func = InvokeFunction('init') tx_hash = self.__sdk.get_network().send_neo_vm_transaction(self.__hex_contract_address, acct, payer_acct, gas_limit, gas_price, func) return tx_hash
def init(self, acct: Account, payer_acct: Account, gas_limit: int, gas_price: int) -> str
This interface is used to call the TotalSupply method in ope4 that initialize smart contract parameter. :param acct: an Account class that used to sign the transaction. :param payer_acct: an Account class that used to pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: the hexadecimal transaction hash value.
7.040846
7.312531
0.962847
func = InvokeFunction('totalSupply') response = self.__sdk.get_network().send_neo_vm_transaction_pre_exec(self.__hex_contract_address, None, func) try: total_supply = ContractDataParser.to_int(response['Result']) except SDKException: total_supply = 0 return total_supply
def get_total_supply(self) -> int
This interface is used to call the TotalSupply method in ope4 that return the total supply of the oep4 token. :return: the total supply of the oep4 token.
9.213976
8.927822
1.032052
func = InvokeFunction('balanceOf') Oep4.__b58_address_check(b58_address) address = Address.b58decode(b58_address).to_bytes() func.set_params_value(address) result = self.__sdk.get_network().send_neo_vm_transaction_pre_exec(self.__hex_contract_address, None, func) try: balance = ContractDataParser.to_int(result['Result']) except SDKException: balance = 0 return balance
def balance_of(self, b58_address: str) -> int
This interface is used to call the BalanceOf method in ope4 that query the ope4 token balance of the given base58 encode address. :param b58_address: the base58 encode address. :return: the oep4 token balance of the base58 encode address.
8.249653
7.644918
1.079103
func = InvokeFunction('transfer') if not isinstance(value, int): raise SDKException(ErrorCode.param_err('the data type of value should be int.')) if value < 0: raise SDKException(ErrorCode.param_err('the value should be equal or great than 0.')) if not isinstance(from_acct, Account): raise SDKException(ErrorCode.param_err('the data type of from_acct should be Account.')) Oep4.__b58_address_check(b58_to_address) from_address = from_acct.get_address().to_bytes() to_address = Address.b58decode(b58_to_address).to_bytes() func.set_params_value(from_address, to_address, value) tx_hash = self.__sdk.get_network().send_neo_vm_transaction(self.__hex_contract_address, from_acct, payer_acct, gas_limit, gas_price, func, False) return tx_hash
def transfer(self, from_acct: Account, b58_to_address: str, value: int, payer_acct: Account, gas_limit: int, gas_price: int) -> str
This interface is used to call the Transfer method in ope4 that transfer an amount of tokens from one account to another account. :param from_acct: an Account class that send the oep4 token. :param b58_to_address: a base58 encode address that receive the oep4 token. :param value: an int value that indicate the amount oep4 token that will be transferred in this transaction. :param payer_acct: an Account class that used to pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: the hexadecimal transaction hash value.
3.31105
3.338616
0.991743
func = InvokeFunction('transferMulti') for index, item in enumerate(transfer_list): Oep4.__b58_address_check(item[0]) Oep4.__b58_address_check(item[1]) if not isinstance(item[2], int): raise SDKException(ErrorCode.param_err('the data type of value should be int.')) if item[2] < 0: raise SDKException(ErrorCode.param_err('the value should be equal or great than 0.')) from_address_array = Address.b58decode(item[0]).to_bytes() to_address_array = Address.b58decode(item[1]).to_bytes() transfer_list[index] = [from_address_array, to_address_array, item[2]] for item in transfer_list: func.add_params_value(item) params = func.create_invoke_code() unix_time_now = int(time.time()) params.append(0x67) bytearray_contract_address = bytearray.fromhex(self.__hex_contract_address) bytearray_contract_address.reverse() for i in bytearray_contract_address: params.append(i) if len(signers) == 0: raise SDKException(ErrorCode.param_err('payer account is None.')) payer_address = payer_acct.get_address().to_bytes() tx = Transaction(0, 0xd1, unix_time_now, gas_price, gas_limit, payer_address, params, bytearray(), []) for signer in signers: tx.add_sign_transaction(signer) tx_hash = self.__sdk.get_network().send_raw_transaction(tx) return tx_hash
def transfer_multi(self, transfer_list: list, payer_acct: Account, signers: list, gas_limit: int, gas_price: int)
This interface is used to call the TransferMulti method in ope4 that allow transfer amount of token from multiple from-account to multiple to-account multiple times. :param transfer_list: a parameter list with each item contains three sub-items: base58 encode transaction sender address, base58 encode transaction receiver address, amount of token in transaction. :param payer_acct: an Account class that used to pay for the transaction. :param signers: a signer list used to sign this transaction which should contained all sender in args. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: the hexadecimal transaction hash value.
3.404233
3.374979
1.008668