repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
ssato/python-anyconfig
|
src/anyconfig/cli.py
|
make_parser
|
def make_parser(defaults=None):
"""
:param defaults: Default option values
"""
if defaults is None:
defaults = DEFAULTS
ctypes = API.list_types()
ctypes_s = ", ".join(ctypes)
type_help = "Select type of %s config files from " + \
ctypes_s + " [Automatically detected by file ext]"
mts = API.MERGE_STRATEGIES
mts_s = ", ".join(mts)
mt_help = "Select strategy to merge multiple configs from " + \
mts_s + " [%(merge)s]" % defaults
parser = argparse.ArgumentParser(usage=USAGE)
parser.set_defaults(**defaults)
parser.add_argument("inputs", type=str, nargs='*', help="Input files")
parser.add_argument("--version", action="version",
version="%%(prog)s %s" % anyconfig.globals.VERSION)
lpog = parser.add_argument_group("List specific options")
lpog.add_argument("-L", "--list", action="store_true",
help="List supported config types")
spog = parser.add_argument_group("Schema specific options")
spog.add_argument("--validate", action="store_true",
help="Only validate input files and do not output. "
"You must specify schema file with -S/--schema "
"option.")
spog.add_argument("--gen-schema", action="store_true",
help="Generate JSON schema for givne config file[s] "
"and output it instead of (merged) configuration.")
gspog = parser.add_argument_group("Query/Get/set options")
gspog.add_argument("-Q", "--query", help=_QUERY_HELP)
gspog.add_argument("--get", help=_GET_HELP)
gspog.add_argument("--set", help=_SET_HELP)
parser.add_argument("-o", "--output", help="Output file path")
parser.add_argument("-I", "--itype", choices=ctypes, metavar="ITYPE",
help=(type_help % "Input"))
parser.add_argument("-O", "--otype", choices=ctypes, metavar="OTYPE",
help=(type_help % "Output"))
parser.add_argument("-M", "--merge", choices=mts, metavar="MERGE",
help=mt_help)
parser.add_argument("-A", "--args", help="Argument configs to override")
parser.add_argument("--atype", choices=ctypes, metavar="ATYPE",
help=_ATYPE_HELP_FMT % ctypes_s)
cpog = parser.add_argument_group("Common options")
cpog.add_argument("-x", "--ignore-missing", action="store_true",
help="Ignore missing input files")
cpog.add_argument("-T", "--template", action="store_true",
help="Enable template config support")
cpog.add_argument("-E", "--env", action="store_true",
help="Load configuration defaults from "
"environment values")
cpog.add_argument("-S", "--schema", help="Specify Schema file[s] path")
cpog.add_argument("-e", "--extra-opts",
help="Extra options given to the API call, "
"--extra-options indent:2 (specify the "
"indent for pretty-printing of JSON outputs) "
"for example")
cpog.add_argument("-v", "--verbose", action="count", dest="loglevel",
help="Verbose mode; -v or -vv (more verbose)")
return parser
|
python
|
def make_parser(defaults=None):
"""
:param defaults: Default option values
"""
if defaults is None:
defaults = DEFAULTS
ctypes = API.list_types()
ctypes_s = ", ".join(ctypes)
type_help = "Select type of %s config files from " + \
ctypes_s + " [Automatically detected by file ext]"
mts = API.MERGE_STRATEGIES
mts_s = ", ".join(mts)
mt_help = "Select strategy to merge multiple configs from " + \
mts_s + " [%(merge)s]" % defaults
parser = argparse.ArgumentParser(usage=USAGE)
parser.set_defaults(**defaults)
parser.add_argument("inputs", type=str, nargs='*', help="Input files")
parser.add_argument("--version", action="version",
version="%%(prog)s %s" % anyconfig.globals.VERSION)
lpog = parser.add_argument_group("List specific options")
lpog.add_argument("-L", "--list", action="store_true",
help="List supported config types")
spog = parser.add_argument_group("Schema specific options")
spog.add_argument("--validate", action="store_true",
help="Only validate input files and do not output. "
"You must specify schema file with -S/--schema "
"option.")
spog.add_argument("--gen-schema", action="store_true",
help="Generate JSON schema for givne config file[s] "
"and output it instead of (merged) configuration.")
gspog = parser.add_argument_group("Query/Get/set options")
gspog.add_argument("-Q", "--query", help=_QUERY_HELP)
gspog.add_argument("--get", help=_GET_HELP)
gspog.add_argument("--set", help=_SET_HELP)
parser.add_argument("-o", "--output", help="Output file path")
parser.add_argument("-I", "--itype", choices=ctypes, metavar="ITYPE",
help=(type_help % "Input"))
parser.add_argument("-O", "--otype", choices=ctypes, metavar="OTYPE",
help=(type_help % "Output"))
parser.add_argument("-M", "--merge", choices=mts, metavar="MERGE",
help=mt_help)
parser.add_argument("-A", "--args", help="Argument configs to override")
parser.add_argument("--atype", choices=ctypes, metavar="ATYPE",
help=_ATYPE_HELP_FMT % ctypes_s)
cpog = parser.add_argument_group("Common options")
cpog.add_argument("-x", "--ignore-missing", action="store_true",
help="Ignore missing input files")
cpog.add_argument("-T", "--template", action="store_true",
help="Enable template config support")
cpog.add_argument("-E", "--env", action="store_true",
help="Load configuration defaults from "
"environment values")
cpog.add_argument("-S", "--schema", help="Specify Schema file[s] path")
cpog.add_argument("-e", "--extra-opts",
help="Extra options given to the API call, "
"--extra-options indent:2 (specify the "
"indent for pretty-printing of JSON outputs) "
"for example")
cpog.add_argument("-v", "--verbose", action="count", dest="loglevel",
help="Verbose mode; -v or -vv (more verbose)")
return parser
|
:param defaults: Default option values
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/cli.py#L118-L187
|
ssato/python-anyconfig
|
src/anyconfig/cli.py
|
_exit_with_output
|
def _exit_with_output(content, exit_code=0):
"""
Exit the program with printing out messages.
:param content: content to print out
:param exit_code: Exit code
"""
(sys.stdout if exit_code == 0 else sys.stderr).write(content + os.linesep)
sys.exit(exit_code)
|
python
|
def _exit_with_output(content, exit_code=0):
"""
Exit the program with printing out messages.
:param content: content to print out
:param exit_code: Exit code
"""
(sys.stdout if exit_code == 0 else sys.stderr).write(content + os.linesep)
sys.exit(exit_code)
|
Exit the program with printing out messages.
:param content: content to print out
:param exit_code: Exit code
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/cli.py#L190-L198
|
ssato/python-anyconfig
|
src/anyconfig/cli.py
|
_show_psrs
|
def _show_psrs():
"""Show list of info of parsers available
"""
sep = os.linesep
types = "Supported types: " + ", ".join(API.list_types())
cids = "IDs: " + ", ".join(c for c, _ps in API.list_by_cid())
x_vs_ps = [" %s: %s" % (x, ", ".join(p.cid() for p in ps))
for x, ps in API.list_by_extension()]
exts = "File extensions:" + sep + sep.join(x_vs_ps)
_exit_with_output(sep.join([types, exts, cids]))
|
python
|
def _show_psrs():
"""Show list of info of parsers available
"""
sep = os.linesep
types = "Supported types: " + ", ".join(API.list_types())
cids = "IDs: " + ", ".join(c for c, _ps in API.list_by_cid())
x_vs_ps = [" %s: %s" % (x, ", ".join(p.cid() for p in ps))
for x, ps in API.list_by_extension()]
exts = "File extensions:" + sep + sep.join(x_vs_ps)
_exit_with_output(sep.join([types, exts, cids]))
|
Show list of info of parsers available
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/cli.py#L201-L213
|
ssato/python-anyconfig
|
src/anyconfig/cli.py
|
_parse_args
|
def _parse_args(argv):
"""
Show supported config format types or usage.
:param argv: Argument list to parse or None (sys.argv will be set).
:return: argparse.Namespace object or None (exit before return)
"""
parser = make_parser()
args = parser.parse_args(argv)
LOGGER.setLevel(to_log_level(args.loglevel))
if args.inputs:
if '-' in args.inputs:
args.inputs = sys.stdin
else:
if args.list:
_show_psrs()
elif args.env:
cnf = os.environ.copy()
_output_result(cnf, args.output, args.otype or "json", None, None)
sys.exit(0)
else:
parser.print_usage()
sys.exit(1)
if args.validate and args.schema is None:
_exit_with_output("--validate option requires --scheme option", 1)
return args
|
python
|
def _parse_args(argv):
"""
Show supported config format types or usage.
:param argv: Argument list to parse or None (sys.argv will be set).
:return: argparse.Namespace object or None (exit before return)
"""
parser = make_parser()
args = parser.parse_args(argv)
LOGGER.setLevel(to_log_level(args.loglevel))
if args.inputs:
if '-' in args.inputs:
args.inputs = sys.stdin
else:
if args.list:
_show_psrs()
elif args.env:
cnf = os.environ.copy()
_output_result(cnf, args.output, args.otype or "json", None, None)
sys.exit(0)
else:
parser.print_usage()
sys.exit(1)
if args.validate and args.schema is None:
_exit_with_output("--validate option requires --scheme option", 1)
return args
|
Show supported config format types or usage.
:param argv: Argument list to parse or None (sys.argv will be set).
:return: argparse.Namespace object or None (exit before return)
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/cli.py#L216-L244
|
ssato/python-anyconfig
|
src/anyconfig/cli.py
|
_do_get
|
def _do_get(cnf, get_path):
"""
:param cnf: Configuration object to print out
:param get_path: key path given in --get option
:return: updated Configuration object if no error
"""
(cnf, err) = API.get(cnf, get_path)
if cnf is None: # Failed to get the result.
_exit_with_output("Failed to get result: err=%s" % err, 1)
return cnf
|
python
|
def _do_get(cnf, get_path):
"""
:param cnf: Configuration object to print out
:param get_path: key path given in --get option
:return: updated Configuration object if no error
"""
(cnf, err) = API.get(cnf, get_path)
if cnf is None: # Failed to get the result.
_exit_with_output("Failed to get result: err=%s" % err, 1)
return cnf
|
:param cnf: Configuration object to print out
:param get_path: key path given in --get option
:return: updated Configuration object if no error
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/cli.py#L256-L266
|
ssato/python-anyconfig
|
src/anyconfig/cli.py
|
_output_type_by_input_path
|
def _output_type_by_input_path(inpaths, itype, fmsg):
"""
:param inpaths: List of input file paths
:param itype: Input type or None
:param fmsg: message if it cannot detect otype by 'inpath'
:return: Output type :: str
"""
msg = ("Specify inpath and/or outpath type[s] with -I/--itype "
"or -O/--otype option explicitly")
if itype is None:
try:
otype = API.find(inpaths[0]).type()
except API.UnknownFileTypeError:
_exit_with_output((fmsg % inpaths[0]) + msg, 1)
except (ValueError, IndexError):
_exit_with_output(msg, 1)
else:
otype = itype
return otype
|
python
|
def _output_type_by_input_path(inpaths, itype, fmsg):
"""
:param inpaths: List of input file paths
:param itype: Input type or None
:param fmsg: message if it cannot detect otype by 'inpath'
:return: Output type :: str
"""
msg = ("Specify inpath and/or outpath type[s] with -I/--itype "
"or -O/--otype option explicitly")
if itype is None:
try:
otype = API.find(inpaths[0]).type()
except API.UnknownFileTypeError:
_exit_with_output((fmsg % inpaths[0]) + msg, 1)
except (ValueError, IndexError):
_exit_with_output(msg, 1)
else:
otype = itype
return otype
|
:param inpaths: List of input file paths
:param itype: Input type or None
:param fmsg: message if it cannot detect otype by 'inpath'
:return: Output type :: str
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/cli.py#L269-L288
|
ssato/python-anyconfig
|
src/anyconfig/cli.py
|
_try_dump
|
def _try_dump(cnf, outpath, otype, fmsg, extra_opts=None):
"""
:param cnf: Configuration object to print out
:param outpath: Output file path or None
:param otype: Output type or None
:param fmsg: message if it cannot detect otype by 'inpath'
:param extra_opts: Map object will be given to API.dump as extra options
"""
if extra_opts is None:
extra_opts = {}
try:
API.dump(cnf, outpath, otype, **extra_opts)
except API.UnknownFileTypeError:
_exit_with_output(fmsg % outpath, 1)
except API.UnknownProcessorTypeError:
_exit_with_output("Invalid output type '%s'" % otype, 1)
|
python
|
def _try_dump(cnf, outpath, otype, fmsg, extra_opts=None):
"""
:param cnf: Configuration object to print out
:param outpath: Output file path or None
:param otype: Output type or None
:param fmsg: message if it cannot detect otype by 'inpath'
:param extra_opts: Map object will be given to API.dump as extra options
"""
if extra_opts is None:
extra_opts = {}
try:
API.dump(cnf, outpath, otype, **extra_opts)
except API.UnknownFileTypeError:
_exit_with_output(fmsg % outpath, 1)
except API.UnknownProcessorTypeError:
_exit_with_output("Invalid output type '%s'" % otype, 1)
|
:param cnf: Configuration object to print out
:param outpath: Output file path or None
:param otype: Output type or None
:param fmsg: message if it cannot detect otype by 'inpath'
:param extra_opts: Map object will be given to API.dump as extra options
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/cli.py#L291-L306
|
ssato/python-anyconfig
|
src/anyconfig/cli.py
|
_output_result
|
def _output_result(cnf, outpath, otype, inpaths, itype,
extra_opts=None):
"""
:param cnf: Configuration object to print out
:param outpath: Output file path or None
:param otype: Output type or None
:param inpaths: List of input file paths
:param itype: Input type or None
:param extra_opts: Map object will be given to API.dump as extra options
"""
fmsg = ("Uknown file type and cannot detect appropriate backend "
"from its extension, '%s'")
if not anyconfig.utils.is_dict_like(cnf):
_exit_with_output(str(cnf)) # Print primitive types as it is.
if not outpath or outpath == "-":
outpath = sys.stdout
if otype is None:
otype = _output_type_by_input_path(inpaths, itype, fmsg)
_try_dump(cnf, outpath, otype, fmsg, extra_opts=extra_opts)
|
python
|
def _output_result(cnf, outpath, otype, inpaths, itype,
extra_opts=None):
"""
:param cnf: Configuration object to print out
:param outpath: Output file path or None
:param otype: Output type or None
:param inpaths: List of input file paths
:param itype: Input type or None
:param extra_opts: Map object will be given to API.dump as extra options
"""
fmsg = ("Uknown file type and cannot detect appropriate backend "
"from its extension, '%s'")
if not anyconfig.utils.is_dict_like(cnf):
_exit_with_output(str(cnf)) # Print primitive types as it is.
if not outpath or outpath == "-":
outpath = sys.stdout
if otype is None:
otype = _output_type_by_input_path(inpaths, itype, fmsg)
_try_dump(cnf, outpath, otype, fmsg, extra_opts=extra_opts)
|
:param cnf: Configuration object to print out
:param outpath: Output file path or None
:param otype: Output type or None
:param inpaths: List of input file paths
:param itype: Input type or None
:param extra_opts: Map object will be given to API.dump as extra options
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/cli.py#L309-L330
|
ssato/python-anyconfig
|
src/anyconfig/cli.py
|
_load_diff
|
def _load_diff(args, extra_opts):
"""
:param args: :class:`argparse.Namespace` object
:param extra_opts: Map object given to API.load as extra options
"""
try:
diff = API.load(args.inputs, args.itype,
ac_ignore_missing=args.ignore_missing,
ac_merge=args.merge,
ac_template=args.template,
ac_schema=args.schema,
**extra_opts)
except API.UnknownProcessorTypeError:
_exit_with_output("Wrong input type '%s'" % args.itype, 1)
except API.UnknownFileTypeError:
_exit_with_output("No appropriate backend was found for given file "
"'%s'" % args.itype, 1)
_exit_if_load_failure(diff,
"Failed to load: args=%s" % ", ".join(args.inputs))
return diff
|
python
|
def _load_diff(args, extra_opts):
"""
:param args: :class:`argparse.Namespace` object
:param extra_opts: Map object given to API.load as extra options
"""
try:
diff = API.load(args.inputs, args.itype,
ac_ignore_missing=args.ignore_missing,
ac_merge=args.merge,
ac_template=args.template,
ac_schema=args.schema,
**extra_opts)
except API.UnknownProcessorTypeError:
_exit_with_output("Wrong input type '%s'" % args.itype, 1)
except API.UnknownFileTypeError:
_exit_with_output("No appropriate backend was found for given file "
"'%s'" % args.itype, 1)
_exit_if_load_failure(diff,
"Failed to load: args=%s" % ", ".join(args.inputs))
return diff
|
:param args: :class:`argparse.Namespace` object
:param extra_opts: Map object given to API.load as extra options
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/cli.py#L333-L353
|
ssato/python-anyconfig
|
src/anyconfig/cli.py
|
_do_filter
|
def _do_filter(cnf, args):
"""
:param cnf: Mapping object represents configuration data
:param args: :class:`argparse.Namespace` object
:return: 'cnf' may be updated
"""
if args.query:
cnf = API.query(cnf, args.query)
elif args.get:
cnf = _do_get(cnf, args.get)
elif args.set:
(key, val) = args.set.split('=')
API.set_(cnf, key, anyconfig.parser.parse(val))
return cnf
|
python
|
def _do_filter(cnf, args):
"""
:param cnf: Mapping object represents configuration data
:param args: :class:`argparse.Namespace` object
:return: 'cnf' may be updated
"""
if args.query:
cnf = API.query(cnf, args.query)
elif args.get:
cnf = _do_get(cnf, args.get)
elif args.set:
(key, val) = args.set.split('=')
API.set_(cnf, key, anyconfig.parser.parse(val))
return cnf
|
:param cnf: Mapping object represents configuration data
:param args: :class:`argparse.Namespace` object
:return: 'cnf' may be updated
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/cli.py#L356-L370
|
ssato/python-anyconfig
|
src/anyconfig/cli.py
|
main
|
def main(argv=None):
"""
:param argv: Argument list to parse or None (sys.argv will be set).
"""
args = _parse_args((argv if argv else sys.argv)[1:])
cnf = os.environ.copy() if args.env else {}
extra_opts = dict()
if args.extra_opts:
extra_opts = anyconfig.parser.parse(args.extra_opts)
diff = _load_diff(args, extra_opts)
if cnf:
API.merge(cnf, diff)
else:
cnf = diff
if args.args:
diff = anyconfig.parser.parse(args.args)
API.merge(cnf, diff)
if args.validate:
_exit_with_output("Validation succeds")
cnf = API.gen_schema(cnf) if args.gen_schema else _do_filter(cnf, args)
_output_result(cnf, args.output, args.otype, args.inputs, args.itype,
extra_opts=extra_opts)
|
python
|
def main(argv=None):
"""
:param argv: Argument list to parse or None (sys.argv will be set).
"""
args = _parse_args((argv if argv else sys.argv)[1:])
cnf = os.environ.copy() if args.env else {}
extra_opts = dict()
if args.extra_opts:
extra_opts = anyconfig.parser.parse(args.extra_opts)
diff = _load_diff(args, extra_opts)
if cnf:
API.merge(cnf, diff)
else:
cnf = diff
if args.args:
diff = anyconfig.parser.parse(args.args)
API.merge(cnf, diff)
if args.validate:
_exit_with_output("Validation succeds")
cnf = API.gen_schema(cnf) if args.gen_schema else _do_filter(cnf, args)
_output_result(cnf, args.output, args.otype, args.inputs, args.itype,
extra_opts=extra_opts)
|
:param argv: Argument list to parse or None (sys.argv will be set).
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/cli.py#L373-L400
|
ssato/python-anyconfig
|
src/anyconfig/schema.py
|
_validate_all
|
def _validate_all(data, schema):
"""
See the descritpion of :func:`validate` for more details of parameters and
return value.
:seealso: https://python-jsonschema.readthedocs.io/en/latest/validate/,
a section of 'iter_errors' especially
"""
vldtr = jsonschema.Draft4Validator(schema) # :raises: SchemaError, ...
errors = list(vldtr.iter_errors(data))
return (not errors, [err.message for err in errors])
|
python
|
def _validate_all(data, schema):
"""
See the descritpion of :func:`validate` for more details of parameters and
return value.
:seealso: https://python-jsonschema.readthedocs.io/en/latest/validate/,
a section of 'iter_errors' especially
"""
vldtr = jsonschema.Draft4Validator(schema) # :raises: SchemaError, ...
errors = list(vldtr.iter_errors(data))
return (not errors, [err.message for err in errors])
|
See the descritpion of :func:`validate` for more details of parameters and
return value.
:seealso: https://python-jsonschema.readthedocs.io/en/latest/validate/,
a section of 'iter_errors' especially
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/schema.py#L51-L62
|
ssato/python-anyconfig
|
src/anyconfig/schema.py
|
_validate
|
def _validate(data, schema, ac_schema_safe=True, **options):
"""
See the descritpion of :func:`validate` for more details of parameters and
return value.
Validate target object 'data' with given schema object.
"""
try:
jsonschema.validate(data, schema, **options)
except (jsonschema.ValidationError, jsonschema.SchemaError,
Exception) as exc:
if ac_schema_safe:
return (False, str(exc)) # Validation was failed.
raise
return (True, '')
|
python
|
def _validate(data, schema, ac_schema_safe=True, **options):
"""
See the descritpion of :func:`validate` for more details of parameters and
return value.
Validate target object 'data' with given schema object.
"""
try:
jsonschema.validate(data, schema, **options)
except (jsonschema.ValidationError, jsonschema.SchemaError,
Exception) as exc:
if ac_schema_safe:
return (False, str(exc)) # Validation was failed.
raise
return (True, '')
|
See the descritpion of :func:`validate` for more details of parameters and
return value.
Validate target object 'data' with given schema object.
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/schema.py#L65-L81
|
ssato/python-anyconfig
|
src/anyconfig/schema.py
|
validate
|
def validate(data, schema, ac_schema_safe=True, ac_schema_errors=False,
**options):
"""
Validate target object with given schema object, loaded from JSON schema.
See also: https://python-jsonschema.readthedocs.org/en/latest/validate/
:parae data: Target object (a dict or a dict-like object) to validate
:param schema: Schema object (a dict or a dict-like object)
instantiated from schema JSON file or schema JSON string
:param options: Other keyword options such as:
- ac_schema_safe: Exception (jsonschema.ValidationError or
jsonschema.SchemaError or others) will be thrown during validation
process due to any validation or related errors. However, these will
be catched by default, and will be re-raised if 'ac_safe' is False.
- ac_schema_errors: Lazily yield each of the validation errors and
returns all of them if validation fails.
:return: (True if validation succeeded else False, error message[s])
"""
if not JSONSCHEMA_IS_AVAIL:
return (True, _NA_MSG)
options = anyconfig.utils.filter_options(("cls", ), options)
if ac_schema_errors:
return _validate_all(data, schema, **options)
return _validate(data, schema, ac_schema_safe, **options)
|
python
|
def validate(data, schema, ac_schema_safe=True, ac_schema_errors=False,
**options):
"""
Validate target object with given schema object, loaded from JSON schema.
See also: https://python-jsonschema.readthedocs.org/en/latest/validate/
:parae data: Target object (a dict or a dict-like object) to validate
:param schema: Schema object (a dict or a dict-like object)
instantiated from schema JSON file or schema JSON string
:param options: Other keyword options such as:
- ac_schema_safe: Exception (jsonschema.ValidationError or
jsonschema.SchemaError or others) will be thrown during validation
process due to any validation or related errors. However, these will
be catched by default, and will be re-raised if 'ac_safe' is False.
- ac_schema_errors: Lazily yield each of the validation errors and
returns all of them if validation fails.
:return: (True if validation succeeded else False, error message[s])
"""
if not JSONSCHEMA_IS_AVAIL:
return (True, _NA_MSG)
options = anyconfig.utils.filter_options(("cls", ), options)
if ac_schema_errors:
return _validate_all(data, schema, **options)
return _validate(data, schema, ac_schema_safe, **options)
|
Validate target object with given schema object, loaded from JSON schema.
See also: https://python-jsonschema.readthedocs.org/en/latest/validate/
:parae data: Target object (a dict or a dict-like object) to validate
:param schema: Schema object (a dict or a dict-like object)
instantiated from schema JSON file or schema JSON string
:param options: Other keyword options such as:
- ac_schema_safe: Exception (jsonschema.ValidationError or
jsonschema.SchemaError or others) will be thrown during validation
process due to any validation or related errors. However, these will
be catched by default, and will be re-raised if 'ac_safe' is False.
- ac_schema_errors: Lazily yield each of the validation errors and
returns all of them if validation fails.
:return: (True if validation succeeded else False, error message[s])
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/schema.py#L84-L113
|
ssato/python-anyconfig
|
src/anyconfig/schema.py
|
array_to_schema
|
def array_to_schema(arr, **options):
"""
Generate a JSON schema object with type annotation added for given object.
:param arr: Array of mapping objects like dicts
:param options: Other keyword options such as:
- ac_schema_strict: True if more strict (precise) schema is needed
- ac_schema_typemap: Type to JSON schema type mappings
:return: Another mapping objects represents JSON schema of items
"""
(typemap, strict) = _process_options(**options)
arr = list(arr)
scm = dict(type=typemap[list],
items=gen_schema(arr[0] if arr else "str", **options))
if strict:
nitems = len(arr)
scm["minItems"] = nitems
scm["uniqueItems"] = len(set(arr)) == nitems
return scm
|
python
|
def array_to_schema(arr, **options):
"""
Generate a JSON schema object with type annotation added for given object.
:param arr: Array of mapping objects like dicts
:param options: Other keyword options such as:
- ac_schema_strict: True if more strict (precise) schema is needed
- ac_schema_typemap: Type to JSON schema type mappings
:return: Another mapping objects represents JSON schema of items
"""
(typemap, strict) = _process_options(**options)
arr = list(arr)
scm = dict(type=typemap[list],
items=gen_schema(arr[0] if arr else "str", **options))
if strict:
nitems = len(arr)
scm["minItems"] = nitems
scm["uniqueItems"] = len(set(arr)) == nitems
return scm
|
Generate a JSON schema object with type annotation added for given object.
:param arr: Array of mapping objects like dicts
:param options: Other keyword options such as:
- ac_schema_strict: True if more strict (precise) schema is needed
- ac_schema_typemap: Type to JSON schema type mappings
:return: Another mapping objects represents JSON schema of items
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/schema.py#L126-L148
|
ssato/python-anyconfig
|
src/anyconfig/schema.py
|
object_to_schema
|
def object_to_schema(obj, **options):
"""
Generate a node represents JSON schema object with type annotation added
for given object node.
:param obj: mapping object such like a dict
:param options: Other keyword options such as:
- ac_schema_strict: True if more strict (precise) schema is needed
- ac_schema_typemap: Type to JSON schema type mappings
:yield: Another mapping objects represents JSON schema of object
"""
(typemap, strict) = _process_options(**options)
props = dict((k, gen_schema(v, **options)) for k, v in obj.items())
scm = dict(type=typemap[dict], properties=props)
if strict:
scm["required"] = sorted(props.keys())
return scm
|
python
|
def object_to_schema(obj, **options):
"""
Generate a node represents JSON schema object with type annotation added
for given object node.
:param obj: mapping object such like a dict
:param options: Other keyword options such as:
- ac_schema_strict: True if more strict (precise) schema is needed
- ac_schema_typemap: Type to JSON schema type mappings
:yield: Another mapping objects represents JSON schema of object
"""
(typemap, strict) = _process_options(**options)
props = dict((k, gen_schema(v, **options)) for k, v in obj.items())
scm = dict(type=typemap[dict], properties=props)
if strict:
scm["required"] = sorted(props.keys())
return scm
|
Generate a node represents JSON schema object with type annotation added
for given object node.
:param obj: mapping object such like a dict
:param options: Other keyword options such as:
- ac_schema_strict: True if more strict (precise) schema is needed
- ac_schema_typemap: Type to JSON schema type mappings
:yield: Another mapping objects represents JSON schema of object
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/schema.py#L151-L171
|
ssato/python-anyconfig
|
src/anyconfig/schema.py
|
gen_schema
|
def gen_schema(data, **options):
"""
Generate a node represents JSON schema object with type annotation added
for given object node.
:param data: Configuration data object (dict[-like] or namedtuple)
:param options: Other keyword options such as:
- ac_schema_strict: True if more strict (precise) schema is needed
- ac_schema_typemap: Type to JSON schema type mappings
:return: A dict represents JSON schema of this node
"""
if data is None:
return dict(type="null")
_type = type(data)
if _type in _SIMPLE_TYPES:
typemap = options.get("ac_schema_typemap", _SIMPLETYPE_MAP)
scm = dict(type=typemap[_type])
elif anyconfig.utils.is_dict_like(data):
scm = object_to_schema(data, **options)
elif anyconfig.utils.is_list_like(data):
scm = array_to_schema(data, **options)
return scm
|
python
|
def gen_schema(data, **options):
"""
Generate a node represents JSON schema object with type annotation added
for given object node.
:param data: Configuration data object (dict[-like] or namedtuple)
:param options: Other keyword options such as:
- ac_schema_strict: True if more strict (precise) schema is needed
- ac_schema_typemap: Type to JSON schema type mappings
:return: A dict represents JSON schema of this node
"""
if data is None:
return dict(type="null")
_type = type(data)
if _type in _SIMPLE_TYPES:
typemap = options.get("ac_schema_typemap", _SIMPLETYPE_MAP)
scm = dict(type=typemap[_type])
elif anyconfig.utils.is_dict_like(data):
scm = object_to_schema(data, **options)
elif anyconfig.utils.is_list_like(data):
scm = array_to_schema(data, **options)
return scm
|
Generate a node represents JSON schema object with type annotation added
for given object node.
:param data: Configuration data object (dict[-like] or namedtuple)
:param options: Other keyword options such as:
- ac_schema_strict: True if more strict (precise) schema is needed
- ac_schema_typemap: Type to JSON schema type mappings
:return: A dict represents JSON schema of this node
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/schema.py#L174-L202
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
ensure_outdir_exists
|
def ensure_outdir_exists(filepath):
"""
Make dir to dump 'filepath' if that dir does not exist.
:param filepath: path of file to dump
"""
outdir = os.path.dirname(filepath)
if outdir and not os.path.exists(outdir):
LOGGER.debug("Making output dir: %s", outdir)
os.makedirs(outdir)
|
python
|
def ensure_outdir_exists(filepath):
"""
Make dir to dump 'filepath' if that dir does not exist.
:param filepath: path of file to dump
"""
outdir = os.path.dirname(filepath)
if outdir and not os.path.exists(outdir):
LOGGER.debug("Making output dir: %s", outdir)
os.makedirs(outdir)
|
Make dir to dump 'filepath' if that dir does not exist.
:param filepath: path of file to dump
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L63-L73
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
to_method
|
def to_method(func):
"""
Lift :func:`func` to a method; it will be called with the first argument
'self' ignored.
:param func: Any callable object
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""Wrapper function.
"""
return func(*args[1:], **kwargs)
return wrapper
|
python
|
def to_method(func):
"""
Lift :func:`func` to a method; it will be called with the first argument
'self' ignored.
:param func: Any callable object
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""Wrapper function.
"""
return func(*args[1:], **kwargs)
return wrapper
|
Lift :func:`func` to a method; it will be called with the first argument
'self' ignored.
:param func: Any callable object
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L76-L89
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
load_with_fn
|
def load_with_fn(load_fn, content_or_strm, container, allow_primitives=False,
**options):
"""
Load data from given string or stream 'content_or_strm'.
:param load_fn: Callable to load data
:param content_or_strm: data content or stream provides it
:param container: callble to make a container object
:param allow_primitives:
True if the parser.load* may return objects of primitive data types
other than mapping types such like JSON parser
:param options: keyword options passed to 'load_fn'
:return: container object holding data
"""
ret = load_fn(content_or_strm, **options)
if anyconfig.utils.is_dict_like(ret):
return container() if (ret is None or not ret) else container(ret)
return ret if allow_primitives else container(ret)
|
python
|
def load_with_fn(load_fn, content_or_strm, container, allow_primitives=False,
**options):
"""
Load data from given string or stream 'content_or_strm'.
:param load_fn: Callable to load data
:param content_or_strm: data content or stream provides it
:param container: callble to make a container object
:param allow_primitives:
True if the parser.load* may return objects of primitive data types
other than mapping types such like JSON parser
:param options: keyword options passed to 'load_fn'
:return: container object holding data
"""
ret = load_fn(content_or_strm, **options)
if anyconfig.utils.is_dict_like(ret):
return container() if (ret is None or not ret) else container(ret)
return ret if allow_primitives else container(ret)
|
Load data from given string or stream 'content_or_strm'.
:param load_fn: Callable to load data
:param content_or_strm: data content or stream provides it
:param container: callble to make a container object
:param allow_primitives:
True if the parser.load* may return objects of primitive data types
other than mapping types such like JSON parser
:param options: keyword options passed to 'load_fn'
:return: container object holding data
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L555-L574
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
dump_with_fn
|
def dump_with_fn(dump_fn, data, stream, **options):
"""
Dump 'data' to a string if 'stream' is None, or dump 'data' to a file or
file-like object 'stream'.
:param dump_fn: Callable to dump data
:param data: Data to dump
:param stream: File or file like object or None
:param options: optional keyword parameters
:return: String represents data if stream is None or None
"""
if stream is None:
return dump_fn(data, **options)
return dump_fn(data, stream, **options)
|
python
|
def dump_with_fn(dump_fn, data, stream, **options):
"""
Dump 'data' to a string if 'stream' is None, or dump 'data' to a file or
file-like object 'stream'.
:param dump_fn: Callable to dump data
:param data: Data to dump
:param stream: File or file like object or None
:param options: optional keyword parameters
:return: String represents data if stream is None or None
"""
if stream is None:
return dump_fn(data, **options)
return dump_fn(data, stream, **options)
|
Dump 'data' to a string if 'stream' is None, or dump 'data' to a file or
file-like object 'stream'.
:param dump_fn: Callable to dump data
:param data: Data to dump
:param stream: File or file like object or None
:param options: optional keyword parameters
:return: String represents data if stream is None or None
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L577-L592
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
LoaderMixin._container_factory
|
def _container_factory(self, **options):
"""
The order of prirorities are ac_dict, backend specific dict class
option, ac_ordered.
:param options: Keyword options may contain 'ac_ordered'.
:return: Factory (class or function) to make an container.
"""
ac_dict = options.get("ac_dict", False)
_dicts = [x for x in (options.get(o) for o in self.dict_options())
if x]
if self.dict_options() and ac_dict and callable(ac_dict):
return ac_dict # Higher priority than ac_ordered.
if _dicts and callable(_dicts[0]):
return _dicts[0]
if self.ordered() and options.get("ac_ordered", False):
return anyconfig.compat.OrderedDict
return dict
|
python
|
def _container_factory(self, **options):
"""
The order of prirorities are ac_dict, backend specific dict class
option, ac_ordered.
:param options: Keyword options may contain 'ac_ordered'.
:return: Factory (class or function) to make an container.
"""
ac_dict = options.get("ac_dict", False)
_dicts = [x for x in (options.get(o) for o in self.dict_options())
if x]
if self.dict_options() and ac_dict and callable(ac_dict):
return ac_dict # Higher priority than ac_ordered.
if _dicts and callable(_dicts[0]):
return _dicts[0]
if self.ordered() and options.get("ac_ordered", False):
return anyconfig.compat.OrderedDict
return dict
|
The order of prirorities are ac_dict, backend specific dict class
option, ac_ordered.
:param options: Keyword options may contain 'ac_ordered'.
:return: Factory (class or function) to make an container.
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L175-L194
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
LoaderMixin._load_options
|
def _load_options(self, container, **options):
"""
Select backend specific loading options.
"""
# Force set dict option if available in backend. For example,
# options["object_hook"] will be OrderedDict if 'container' was
# OrderedDict in JSON backend.
for opt in self.dict_options():
options.setdefault(opt, container)
return anyconfig.utils.filter_options(self._load_opts, options)
|
python
|
def _load_options(self, container, **options):
"""
Select backend specific loading options.
"""
# Force set dict option if available in backend. For example,
# options["object_hook"] will be OrderedDict if 'container' was
# OrderedDict in JSON backend.
for opt in self.dict_options():
options.setdefault(opt, container)
return anyconfig.utils.filter_options(self._load_opts, options)
|
Select backend specific loading options.
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L196-L206
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
LoaderMixin.load_from_string
|
def load_from_string(self, content, container, **kwargs):
"""
Load config from given string '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
"""
_not_implemented(self, content, container, **kwargs)
|
python
|
def load_from_string(self, content, container, **kwargs):
"""
Load config from given string '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
"""
_not_implemented(self, content, container, **kwargs)
|
Load config from given string '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
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L208-L218
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
LoaderMixin.load_from_path
|
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
"""
_not_implemented(self, filepath, container, **kwargs)
|
python
|
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
"""
_not_implemented(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
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L220-L230
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
LoaderMixin.load_from_stream
|
def load_from_stream(self, stream, container, **kwargs):
"""
Load config from given file like object '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
"""
_not_implemented(self, stream, container, **kwargs)
|
python
|
def load_from_stream(self, stream, container, **kwargs):
"""
Load config from given file like object '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
"""
_not_implemented(self, stream, container, **kwargs)
|
Load config from given file like object '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
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L232-L242
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
LoaderMixin.loads
|
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
"""
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)
|
python
|
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
"""
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)
|
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
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L244-L262
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
LoaderMixin.load
|
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
"""
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
|
python
|
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
"""
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
|
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
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L264-L298
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
DumperMixin.dump_to_path
|
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
"""
_not_implemented(self, cnf, filepath, **kwargs)
|
python
|
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
"""
_not_implemented(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
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L328-L336
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
DumperMixin.dump_to_stream
|
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
"""
_not_implemented(self, cnf, stream, **kwargs)
|
python
|
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
"""
_not_implemented(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
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L338-L348
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
DumperMixin.dumps
|
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
"""
kwargs = anyconfig.utils.filter_options(self._dump_opts, kwargs)
return self.dump_to_string(cnf, **kwargs)
|
python
|
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
"""
kwargs = anyconfig.utils.filter_options(self._dump_opts, kwargs)
return self.dump_to_string(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
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L350-L360
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
DumperMixin.dump
|
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.
"""
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)
|
python
|
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.
"""
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)
|
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.
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L362-L380
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
FromStringLoaderMixin.load_from_stream
|
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
"""
return self.load_from_string(stream.read(), container, **kwargs)
|
python
|
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
"""
return self.load_from_string(stream.read(), 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
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L407-L417
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
FromStringLoaderMixin.load_from_path
|
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
"""
with self.ropen(filepath) as inp:
return self.load_from_stream(inp, container, **kwargs)
|
python
|
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
"""
with self.ropen(filepath) as inp:
return self.load_from_stream(inp, 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
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L419-L430
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
FromStreamLoaderMixin.load_from_string
|
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
"""
return self.load_from_stream(anyconfig.compat.StringIO(content),
container, **kwargs)
|
python
|
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
"""
return self.load_from_stream(anyconfig.compat.StringIO(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
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L441-L452
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
ToStringDumperMixin.dump_to_path
|
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
"""
with self.wopen(filepath) as out:
out.write(self.dump_to_string(cnf, **kwargs))
|
python
|
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
"""
with self.wopen(filepath) as out:
out.write(self.dump_to_string(cnf, **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
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L477-L486
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
ToStringDumperMixin.dump_to_stream
|
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
"""
stream.write(self.dump_to_string(cnf, **kwargs))
|
python
|
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
"""
stream.write(self.dump_to_string(cnf, **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
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L488-L498
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
ToStreamDumperMixin.dump_to_string
|
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
"""
stream = anyconfig.compat.StringIO()
self.dump_to_stream(cnf, stream, **kwargs)
return stream.getvalue()
|
python
|
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
"""
stream = anyconfig.compat.StringIO()
self.dump_to_stream(cnf, stream, **kwargs)
return stream.getvalue()
|
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
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L510-L521
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
ToStreamDumperMixin.dump_to_path
|
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
"""
with self.wopen(filepath) as out:
self.dump_to_stream(cnf, out, **kwargs)
|
python
|
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
"""
with self.wopen(filepath) as out:
self.dump_to_stream(cnf, out, **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
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L523-L532
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
StringStreamFnParser.load_from_string
|
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
"""
return load_with_fn(self._load_from_string_fn, content, container,
allow_primitives=self.allow_primitives(),
**options)
|
python
|
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
"""
return load_with_fn(self._load_from_string_fn, content, container,
allow_primitives=self.allow_primitives(),
**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
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L618-L630
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
StringStreamFnParser.load_from_stream
|
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
"""
return load_with_fn(self._load_from_stream_fn, stream, container,
allow_primitives=self.allow_primitives(),
**options)
|
python
|
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
"""
return load_with_fn(self._load_from_stream_fn, stream, container,
allow_primitives=self.allow_primitives(),
**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
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L632-L644
|
ssato/python-anyconfig
|
src/anyconfig/backend/base.py
|
StringStreamFnParser.dump_to_stream
|
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
"""
dump_with_fn(self._dump_to_stream_fn, cnf, stream, **kwargs)
|
python
|
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
"""
dump_with_fn(self._dump_to_stream_fn, 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
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L657-L667
|
ssato/python-anyconfig
|
src/anyconfig/ioinfo.py
|
guess_io_type
|
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: ...
"""
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)
|
python
|
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: ...
"""
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)
|
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: ...
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/ioinfo.py#L23-L50
|
ssato/python-anyconfig
|
src/anyconfig/ioinfo.py
|
inspect_io_obj
|
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
"""
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)
|
python
|
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
"""
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)
|
:param obj: a path string, a pathlib.Path or a file / file-like object
:return: A tuple of (objtype, objpath, objopener)
:raises: UnknownFileTypeError
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/ioinfo.py#L53-L80
|
ssato/python-anyconfig
|
src/anyconfig/ioinfo.py
|
make
|
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
"""
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)
|
python
|
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
"""
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)
|
: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
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/ioinfo.py#L83-L97
|
ssato/python-anyconfig
|
src/anyconfig/backend/shellvars.py
|
_parseline
|
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')
"""
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 '')
|
python
|
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')
"""
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 '')
|
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')
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/shellvars.py#L35-L64
|
ssato/python-anyconfig
|
src/anyconfig/backend/shellvars.py
|
load
|
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'}
"""
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
|
python
|
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'}
"""
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
|
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'}
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/shellvars.py#L67-L103
|
ssato/python-anyconfig
|
src/anyconfig/backend/shellvars.py
|
Parser.dump_to_stream
|
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
"""
for key, val in anyconfig.compat.iteritems(cnf):
stream.write("%s='%s'%s" % (key, val, os.linesep))
|
python
|
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
"""
for key, val in anyconfig.compat.iteritems(cnf):
stream.write("%s='%s'%s" % (key, val, os.linesep))
|
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
|
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/shellvars.py#L128-L137
|
jsvine/spectra
|
spectra/__init__.py
|
cmyk
|
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.
"""
return Color("cmyk", c, m, y, k)
|
python
|
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.
"""
return Color("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.
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/__init__.py#L63-L75
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.RgbToHsl
|
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)
'''
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)
|
python
|
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)
'''
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)
|
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)
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L365-L408
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.HslToRgb
|
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)
'''
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)
|
python
|
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)
'''
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)
|
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)
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L419-L453
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.RgbToHsv
|
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)
'''
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)
|
python
|
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)
'''
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)
|
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)
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L456-L492
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.HsvToRgb
|
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)
'''
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)
|
python
|
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)
'''
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)
|
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)
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L495-L533
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.RgbToYiq
|
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)'
'''
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)
|
python
|
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)'
'''
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)
|
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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L536-L560
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.YiqToRgb
|
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)'
'''
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)
|
python
|
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)'
'''
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)
|
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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L563-L587
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.RgbToYuv
|
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)'
'''
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)
|
python
|
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)'
'''
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)
|
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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L590-L614
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.YuvToRgb
|
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)'
'''
r = y + (v * 1.13983)
g = y - (u * 0.39465) - (v * 0.58060)
b = y + (u * 2.03211)
return (r, g, b)
|
python
|
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)'
'''
r = y + (v * 1.13983)
g = y - (u * 0.39465) - (v * 0.58060)
b = y + (u * 2.03211)
return (r, g, b)
|
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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L617-L641
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.RgbToXyz
|
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)'
'''
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)
|
python
|
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)'
'''
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)
|
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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L644-L677
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.XyzToRgb
|
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)'
'''
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)))
|
python
|
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)'
'''
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)))
|
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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L680-L708
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.XyzToLab
|
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)'
'''
# 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)
|
python
|
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)'
'''
# 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)
|
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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L711-L750
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.LabToXyz
|
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)'
'''
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)))
|
python
|
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)'
'''
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)))
|
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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L753-L782
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.CmykToCmy
|
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)'
'''
mk = 1-k
return ((c*mk + k), (m*mk + k), (y*mk + k))
|
python
|
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)'
'''
mk = 1-k
return ((c*mk + k), (m*mk + k), (y*mk + 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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L785-L809
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.CmyToCmyk
|
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)'
'''
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)
|
python
|
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)'
'''
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)
|
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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L812-L837
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.RgbToIntTuple
|
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)
'''
return tuple(int(round(v*255)) for v in (r, g, b))
|
python
|
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)
'''
return tuple(int(round(v*255)) for v in (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)
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L888-L909
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.RgbToHtml
|
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'
'''
return '#%02x%02x%02x' % tuple((min(round(v*255), 255) for v in (r, g, b)))
|
python
|
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'
'''
return '#%02x%02x%02x' % tuple((min(round(v*255), 255) for v in (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'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L934-L952
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.HtmlToRgb
|
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)'
'''
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))
|
python
|
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)'
'''
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))
|
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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L955-L998
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.RgbToPil
|
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'
'''
r, g, b = [min(int(round(v*255)), 255) for v in (r, g, b)]
return (b << 16) + (g << 8) + r
|
python
|
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'
'''
r, g, b = [min(int(round(v*255)), 255) for v in (r, g, b)]
return (b << 16) + (g << 8) + r
|
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'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1001-L1020
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.PilToRgb
|
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)'
'''
r = 0xff & pil
g = 0xff & (pil >> 8)
b = 0xff & (pil >> 16)
return tuple((v / 255.0 for v in (r, g, b)))
|
python
|
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)'
'''
r = 0xff & pil
g = 0xff & (pil >> 8)
b = 0xff & (pil >> 16)
return tuple((v / 255.0 for v in (r, g, b)))
|
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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1023-L1042
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color._WebSafeComponent
|
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.
'''
# 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
|
python
|
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.
'''
# 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
|
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.
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1045-L1077
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.RgbToWebSafe
|
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)'
'''
webSafeComponent = Color._WebSafeComponent
return tuple((webSafeComponent(v, alt) for v in (r, g, b)))
|
python
|
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)'
'''
webSafeComponent = Color._WebSafeComponent
return tuple((webSafeComponent(v, alt) for v in (r, g, b)))
|
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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1080-L1106
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.RgbToGreyscale
|
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)'
'''
v = (r + g + b) / 3.0
return (v, v, v)
|
python
|
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)'
'''
v = (r + g + b) / 3.0
return (v, v, v)
|
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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1109-L1132
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.RgbToRyb
|
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
'''
d = hue % 15
i = int(hue / 15)
x0 = _RybWheel[i]
x1 = _RybWheel[i+1]
return x0 + (x1-x0) * d / 15
|
python
|
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
'''
d = hue % 15
i = int(hue / 15)
x0 = _RybWheel[i]
x1 = _RybWheel[i+1]
return x0 + (x1-x0) * d / 15
|
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
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1135-L1153
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.RybToRgb
|
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
'''
d = hue % 15
i = int(hue / 15)
x0 = _RgbWheel[i]
x1 = _RgbWheel[i+1]
return x0 + (x1-x0) * d / 15
|
python
|
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
'''
d = hue % 15
i = int(hue / 15)
x0 = _RgbWheel[i]
x1 = _RgbWheel[i+1]
return x0 + (x1-x0) * d / 15
|
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
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1156-L1174
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.NewFromRgb
|
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)
'''
return Color((r, g, b), 'rgb', alpha, wref)
|
python
|
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)
'''
return Color((r, g, b), 'rgb', alpha, 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)
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1177-L1201
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.NewFromHsl
|
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)
'''
return Color((h, s, l), 'hsl', alpha, wref)
|
python
|
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)
'''
return Color((h, s, l), 'hsl', alpha, 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)
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1204-L1228
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.NewFromHsv
|
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)
'''
h2, s, l = Color.RgbToHsl(*Color.HsvToRgb(h, s, v))
return Color((h, s, l), 'hsl', alpha, wref)
|
python
|
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)
'''
h2, s, l = Color.RgbToHsl(*Color.HsvToRgb(h, s, v))
return Color((h, s, l), 'hsl', alpha, 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)
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1231-L1256
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.NewFromYiq
|
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)'
'''
return Color(Color.YiqToRgb(y, i, q), 'rgb', alpha, wref)
|
python
|
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)'
'''
return Color(Color.YiqToRgb(y, i, q), 'rgb', alpha, 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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1259-L1283
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.NewFromYuv
|
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)'
'''
return Color(Color.YuvToRgb(y, u, v), 'rgb', alpha, wref)
|
python
|
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)'
'''
return Color(Color.YuvToRgb(y, u, v), 'rgb', alpha, 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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1286-L1310
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.NewFromXyz
|
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)'
'''
return Color(Color.XyzToRgb(x, y, z), 'rgb', alpha, wref)
|
python
|
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)'
'''
return Color(Color.XyzToRgb(x, y, z), 'rgb', alpha, 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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1313-L1337
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.NewFromLab
|
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)'
'''
return Color(Color.XyzToRgb(*Color.LabToXyz(l, a, b, wref)), 'rgb', alpha, wref)
|
python
|
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)'
'''
return Color(Color.XyzToRgb(*Color.LabToXyz(l, a, b, wref)), 'rgb', alpha, 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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1340-L1368
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.NewFromCmy
|
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)
'''
return Color(Color.CmyToRgb(c, m, y), 'rgb', alpha, wref)
|
python
|
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)
'''
return Color(Color.CmyToRgb(c, m, y), 'rgb', alpha, 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)
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1371-L1395
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.NewFromCmyk
|
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)'
'''
return Color(Color.CmyToRgb(*Color.CmykToCmy(c, m, y, k)), 'rgb', alpha, wref)
|
python
|
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)'
'''
return Color(Color.CmyToRgb(*Color.CmykToCmy(c, m, y, k)), 'rgb', alpha, 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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1398-L1424
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.NewFromHtml
|
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)'
'''
return Color(Color.HtmlToRgb(html), 'rgb', alpha, wref)
|
python
|
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)'
'''
return Color(Color.HtmlToRgb(html), 'rgb', alpha, 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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1427-L1455
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.NewFromPil
|
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)'
'''
return Color(Color.PilToRgb(pil), 'rgb', alpha, wref)
|
python
|
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)'
'''
return Color(Color.PilToRgb(pil), 'rgb', alpha, 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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1458-L1478
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.ColorWithWhiteRef
|
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)'
'''
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)
|
python
|
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)'
'''
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)
|
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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1565-L1602
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.ColorWithHue
|
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)
'''
h, s, l = self.__hsl
return Color((hue, s, l), 'hsl', self.__a, self.__wref)
|
python
|
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)
'''
h, s, l = self.__hsl
return Color((hue, s, l), 'hsl', self.__a, self.__wref)
|
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)
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1604-L1621
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.ColorWithSaturation
|
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)
'''
h, s, l = self.__hsl
return Color((h, saturation, l), 'hsl', self.__a, self.__wref)
|
python
|
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)
'''
h, s, l = self.__hsl
return Color((h, saturation, l), 'hsl', self.__a, self.__wref)
|
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)
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1623-L1644
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.ColorWithLightness
|
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)
'''
h, s, l = self.__hsl
return Color((h, s, lightness), 'hsl', self.__a, self.__wref)
|
python
|
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)
'''
h, s, l = self.__hsl
return Color((h, s, lightness), 'hsl', self.__a, self.__wref)
|
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)
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1646-L1663
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.LighterColor
|
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)
'''
h, s, l = self.__hsl
return Color((h, s, min(l + level, 1)), 'hsl', self.__a, self.__wref)
|
python
|
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)
'''
h, s, l = self.__hsl
return Color((h, s, min(l + level, 1)), 'hsl', self.__a, self.__wref)
|
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)
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1685-L1703
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.WebSafeDither
|
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)'
'''
return (
Color(Color.RgbToWebSafe(*self.__rgb), 'rgb', self.__a, self.__wref),
Color(Color.RgbToWebSafe(alt=True, *self.__rgb), 'rgb', self.__a, self.__wref))
|
python
|
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)'
'''
return (
Color(Color.RgbToWebSafe(*self.__rgb), 'rgb', self.__a, self.__wref),
Color(Color.RgbToWebSafe(alt=True, *self.__rgb), 'rgb', self.__a, self.__wref))
|
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)'
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1745-L1762
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.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)]
'''
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
|
python
|
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)]
'''
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
|
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)]
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1764-L1797
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.ComplementaryColor
|
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)
'''
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)
|
python
|
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)
'''
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)
|
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)
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1799-L1822
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.MonochromeScheme
|
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)']
'''
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))
|
python
|
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)']
'''
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))
|
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)']
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1824-L1858
|
jsvine/spectra
|
spectra/grapefruit.py
|
Color.TriadicScheme
|
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)
'''
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))
|
python
|
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)
'''
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))
|
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)
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1860-L1902
|
jsvine/spectra
|
spectra/core.py
|
Color.from_html
|
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.
"""
rgb = GC.NewFromHtml(html_string).rgb
return cls("rgb", *rgb)
|
python
|
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.
"""
rgb = GC.NewFromHtml(html_string).rgb
return cls("rgb", *rgb)
|
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.
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/core.py#L33-L43
|
jsvine/spectra
|
spectra/core.py
|
Color.to
|
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.
"""
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())
|
python
|
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.
"""
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())
|
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.
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/core.py#L45-L56
|
jsvine/spectra
|
spectra/core.py
|
Color.blend
|
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
"""
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)
|
python
|
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
"""
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)
|
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
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/core.py#L68-L85
|
jsvine/spectra
|
spectra/core.py
|
Color.brighten
|
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
"""
lch = self.to("lch")
l, c, h = lch.values
new_lch = self.__class__("lch", l + amount, c, h)
return new_lch.to(self.space)
|
python
|
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
"""
lch = self.to("lch")
l, c, h = lch.values
new_lch = self.__class__("lch", l + amount, c, h)
return new_lch.to(self.space)
|
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
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/core.py#L87-L102
|
jsvine/spectra
|
spectra/core.py
|
Scale.colorspace
|
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.
"""
new_colors = [ c.to(space) for c in self.colors ]
return self.__class__(new_colors, self._domain)
|
python
|
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.
"""
new_colors = [ c.to(space) for c in self.colors ]
return self.__class__(new_colors, self._domain)
|
Create a new scale in the given color space.
:param str space: The new color space.
:rtype: Scale
:returns: A new color.Scale object.
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/core.py#L211-L221
|
jsvine/spectra
|
spectra/core.py
|
Scale.range
|
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.
"""
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
|
python
|
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.
"""
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
|
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.
|
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/core.py#L223-L238
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.