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
|
---|---|---|---|---|---|---|---|
loads/molotov | molotov/util.py | request | def request(endpoint, verb='GET', session_options=None, **options):
"""Performs a synchronous request.
Uses a dedicated event loop and aiohttp.ClientSession object.
Options:
- endpoint: the endpoint to call
- verb: the HTTP verb to use (defaults: GET)
- session_options: a dict containing options to initialize the session
(defaults: None)
- options: extra options for the request (defaults: None)
Returns a dict object with the following keys:
- content: the content of the response
- status: the status
- headers: a dict with all the response headers
"""
req = functools.partial(_request, endpoint, verb, session_options,
**options)
return _run_in_fresh_loop(req) | python | def request(endpoint, verb='GET', session_options=None, **options):
"""Performs a synchronous request.
Uses a dedicated event loop and aiohttp.ClientSession object.
Options:
- endpoint: the endpoint to call
- verb: the HTTP verb to use (defaults: GET)
- session_options: a dict containing options to initialize the session
(defaults: None)
- options: extra options for the request (defaults: None)
Returns a dict object with the following keys:
- content: the content of the response
- status: the status
- headers: a dict with all the response headers
"""
req = functools.partial(_request, endpoint, verb, session_options,
**options)
return _run_in_fresh_loop(req) | Performs a synchronous request.
Uses a dedicated event loop and aiohttp.ClientSession object.
Options:
- endpoint: the endpoint to call
- verb: the HTTP verb to use (defaults: GET)
- session_options: a dict containing options to initialize the session
(defaults: None)
- options: extra options for the request (defaults: None)
Returns a dict object with the following keys:
- content: the content of the response
- status: the status
- headers: a dict with all the response headers | https://github.com/loads/molotov/blob/bd2c94e7f250e1fbb21940f02c68b4437655bc11/molotov/util.py#L179-L200 |
loads/molotov | molotov/util.py | json_request | def json_request(endpoint, verb='GET', session_options=None, **options):
"""Like :func:`molotov.request` but extracts json from the response.
"""
req = functools.partial(_request, endpoint, verb, session_options,
json=True, **options)
return _run_in_fresh_loop(req) | python | def json_request(endpoint, verb='GET', session_options=None, **options):
"""Like :func:`molotov.request` but extracts json from the response.
"""
req = functools.partial(_request, endpoint, verb, session_options,
json=True, **options)
return _run_in_fresh_loop(req) | Like :func:`molotov.request` but extracts json from the response. | https://github.com/loads/molotov/blob/bd2c94e7f250e1fbb21940f02c68b4437655bc11/molotov/util.py#L203-L208 |
loads/molotov | molotov/util.py | get_var | def get_var(name, factory=None):
"""Gets a global variable given its name.
If factory is not None and the variable is not set, factory
is a callable that will set the variable.
If not set, returns None.
"""
if name not in _VARS and factory is not None:
_VARS[name] = factory()
return _VARS.get(name) | python | def get_var(name, factory=None):
"""Gets a global variable given its name.
If factory is not None and the variable is not set, factory
is a callable that will set the variable.
If not set, returns None.
"""
if name not in _VARS and factory is not None:
_VARS[name] = factory()
return _VARS.get(name) | Gets a global variable given its name.
If factory is not None and the variable is not set, factory
is a callable that will set the variable.
If not set, returns None. | https://github.com/loads/molotov/blob/bd2c94e7f250e1fbb21940f02c68b4437655bc11/molotov/util.py#L225-L235 |
loads/molotov | molotov/worker.py | Worker.step | async def step(self, step_id, session, scenario=None):
""" single scenario call.
When it returns 1, it works. -1 the script failed,
0 the test is stopping or needs to stop.
"""
if scenario is None:
scenario = pick_scenario(self.wid, step_id)
try:
await self.send_event('scenario_start', scenario=scenario)
await scenario['func'](session, *scenario['args'],
**scenario['kw'])
await self.send_event('scenario_success', scenario=scenario)
if scenario['delay'] > 0.:
await cancellable_sleep(scenario['delay'])
return 1
except Exception as exc:
await self.send_event('scenario_failure',
scenario=scenario,
exception=exc)
if self.args.verbose > 0:
self.console.print_error(exc)
await self.console.flush()
return -1 | python | async def step(self, step_id, session, scenario=None):
""" single scenario call.
When it returns 1, it works. -1 the script failed,
0 the test is stopping or needs to stop.
"""
if scenario is None:
scenario = pick_scenario(self.wid, step_id)
try:
await self.send_event('scenario_start', scenario=scenario)
await scenario['func'](session, *scenario['args'],
**scenario['kw'])
await self.send_event('scenario_success', scenario=scenario)
if scenario['delay'] > 0.:
await cancellable_sleep(scenario['delay'])
return 1
except Exception as exc:
await self.send_event('scenario_failure',
scenario=scenario,
exception=exc)
if self.args.verbose > 0:
self.console.print_error(exc)
await self.console.flush()
return -1 | single scenario call.
When it returns 1, it works. -1 the script failed,
0 the test is stopping or needs to stop. | https://github.com/loads/molotov/blob/bd2c94e7f250e1fbb21940f02c68b4437655bc11/molotov/worker.py#L194-L221 |
loads/molotov | molotov/slave.py | main | def main():
"""Moloslave clones a git repo and runs a molotov test
"""
parser = argparse.ArgumentParser(description='Github-based load test')
parser.add_argument('--version', action='store_true', default=False,
help='Displays version and exits.')
parser.add_argument('--virtualenv', type=str, default='virtualenv',
help='Virtualenv executable.')
parser.add_argument('--python', type=str, default=sys.executable,
help='Python executable.')
parser.add_argument('--config', type=str, default='molotov.json',
help='Path of the configuration file.')
parser.add_argument('repo', help='Github repo', type=str, nargs="?")
parser.add_argument('run', help='Test to run', nargs="?")
args = parser.parse_args()
if args.version:
print(__version__)
sys.exit(0)
tempdir = tempfile.mkdtemp()
curdir = os.getcwd()
os.chdir(tempdir)
print('Working directory is %s' % tempdir)
try:
clone_repo(args.repo)
config_file = os.path.join(tempdir, args.config)
with open(config_file) as f:
config = json.loads(f.read())
# creating the virtualenv
create_virtualenv(args.virtualenv, args.python)
# install deps
if 'requirements' in config['molotov']:
install_reqs(config['molotov']['requirements'])
# load deps into sys.path
pyver = '%d.%d' % (sys.version_info.major, sys.version_info.minor)
site_pkg = os.path.join(tempdir, 'venv', 'lib', 'python' + pyver,
'site-packages')
site.addsitedir(site_pkg)
pkg_resources.working_set.add_entry(site_pkg)
# environment
if 'env' in config['molotov']:
for key, value in config['molotov']['env'].items():
os.environ[key] = value
run_test(**config['molotov']['tests'][args.run])
except Exception:
os.chdir(curdir)
shutil.rmtree(tempdir, ignore_errors=True)
raise | python | def main():
"""Moloslave clones a git repo and runs a molotov test
"""
parser = argparse.ArgumentParser(description='Github-based load test')
parser.add_argument('--version', action='store_true', default=False,
help='Displays version and exits.')
parser.add_argument('--virtualenv', type=str, default='virtualenv',
help='Virtualenv executable.')
parser.add_argument('--python', type=str, default=sys.executable,
help='Python executable.')
parser.add_argument('--config', type=str, default='molotov.json',
help='Path of the configuration file.')
parser.add_argument('repo', help='Github repo', type=str, nargs="?")
parser.add_argument('run', help='Test to run', nargs="?")
args = parser.parse_args()
if args.version:
print(__version__)
sys.exit(0)
tempdir = tempfile.mkdtemp()
curdir = os.getcwd()
os.chdir(tempdir)
print('Working directory is %s' % tempdir)
try:
clone_repo(args.repo)
config_file = os.path.join(tempdir, args.config)
with open(config_file) as f:
config = json.loads(f.read())
# creating the virtualenv
create_virtualenv(args.virtualenv, args.python)
# install deps
if 'requirements' in config['molotov']:
install_reqs(config['molotov']['requirements'])
# load deps into sys.path
pyver = '%d.%d' % (sys.version_info.major, sys.version_info.minor)
site_pkg = os.path.join(tempdir, 'venv', 'lib', 'python' + pyver,
'site-packages')
site.addsitedir(site_pkg)
pkg_resources.working_set.add_entry(site_pkg)
# environment
if 'env' in config['molotov']:
for key, value in config['molotov']['env'].items():
os.environ[key] = value
run_test(**config['molotov']['tests'][args.run])
except Exception:
os.chdir(curdir)
shutil.rmtree(tempdir, ignore_errors=True)
raise | Moloslave clones a git repo and runs a molotov test | https://github.com/loads/molotov/blob/bd2c94e7f250e1fbb21940f02c68b4437655bc11/molotov/slave.py#L62-L122 |
joeyespo/gitpress | gitpress/helpers.py | remove_directory | def remove_directory(directory, show_warnings=True):
"""Deletes a directory and its contents.
Returns a list of errors in form (function, path, excinfo)."""
errors = []
def onerror(function, path, excinfo):
if show_warnings:
print 'Cannot delete %s: %s' % (os.path.relpath(directory), excinfo[1])
errors.append((function, path, excinfo))
if os.path.exists(directory):
if not os.path.isdir(directory):
raise NotADirectoryError(directory)
shutil.rmtree(directory, onerror=onerror)
return errors | python | def remove_directory(directory, show_warnings=True):
"""Deletes a directory and its contents.
Returns a list of errors in form (function, path, excinfo)."""
errors = []
def onerror(function, path, excinfo):
if show_warnings:
print 'Cannot delete %s: %s' % (os.path.relpath(directory), excinfo[1])
errors.append((function, path, excinfo))
if os.path.exists(directory):
if not os.path.isdir(directory):
raise NotADirectoryError(directory)
shutil.rmtree(directory, onerror=onerror)
return errors | Deletes a directory and its contents.
Returns a list of errors in form (function, path, excinfo). | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/helpers.py#L13-L28 |
joeyespo/gitpress | gitpress/helpers.py | copy_files | def copy_files(source_files, target_directory, source_directory=None):
"""Copies a list of files to the specified directory.
If source_directory is provided, it will be prepended to each source file."""
try:
os.makedirs(target_directory)
except: # TODO: specific exception?
pass
for f in source_files:
source = os.path.join(source_directory, f) if source_directory else f
target = os.path.join(target_directory, f)
shutil.copy2(source, target) | python | def copy_files(source_files, target_directory, source_directory=None):
"""Copies a list of files to the specified directory.
If source_directory is provided, it will be prepended to each source file."""
try:
os.makedirs(target_directory)
except: # TODO: specific exception?
pass
for f in source_files:
source = os.path.join(source_directory, f) if source_directory else f
target = os.path.join(target_directory, f)
shutil.copy2(source, target) | Copies a list of files to the specified directory.
If source_directory is provided, it will be prepended to each source file. | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/helpers.py#L31-L41 |
joeyespo/gitpress | gitpress/helpers.py | yes_or_no | def yes_or_no(message):
"""Gets user input and returns True for yes and False for no."""
while True:
print message, '(yes/no)',
line = raw_input()
if line is None:
return None
line = line.lower()
if line == 'y' or line == 'ye' or line == 'yes':
return True
if line == 'n' or line == 'no':
return False | python | def yes_or_no(message):
"""Gets user input and returns True for yes and False for no."""
while True:
print message, '(yes/no)',
line = raw_input()
if line is None:
return None
line = line.lower()
if line == 'y' or line == 'ye' or line == 'yes':
return True
if line == 'n' or line == 'no':
return False | Gets user input and returns True for yes and False for no. | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/helpers.py#L44-L55 |
joeyespo/gitpress | gitpress/plugins.py | list_plugins | def list_plugins(directory=None):
"""Gets a list of the installed themes."""
repo = require_repo(directory)
plugins = get_value(repo, 'plugins')
if not plugins or not isinstance(plugins, dict):
return None
return plugins.keys() | python | def list_plugins(directory=None):
"""Gets a list of the installed themes."""
repo = require_repo(directory)
plugins = get_value(repo, 'plugins')
if not plugins or not isinstance(plugins, dict):
return None
return plugins.keys() | Gets a list of the installed themes. | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/plugins.py#L5-L11 |
joeyespo/gitpress | gitpress/plugins.py | add_plugin | def add_plugin(plugin, directory=None):
"""Adds the specified plugin. This returns False if it was already added."""
repo = require_repo(directory)
plugins = get_value(repo, 'plugins', expect_type=dict)
if plugin in plugins:
return False
plugins[plugin] = {}
set_value(repo, 'plugins', plugins)
return True | python | def add_plugin(plugin, directory=None):
"""Adds the specified plugin. This returns False if it was already added."""
repo = require_repo(directory)
plugins = get_value(repo, 'plugins', expect_type=dict)
if plugin in plugins:
return False
plugins[plugin] = {}
set_value(repo, 'plugins', plugins)
return True | Adds the specified plugin. This returns False if it was already added. | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/plugins.py#L14-L23 |
joeyespo/gitpress | gitpress/plugins.py | get_plugin_settings | def get_plugin_settings(plugin, directory=None):
"""Gets the settings for the specified plugin."""
repo = require_repo(directory)
plugins = get_value(repo, 'plugins')
return plugins.get(plugin) if isinstance(plugins, dict) else None | python | def get_plugin_settings(plugin, directory=None):
"""Gets the settings for the specified plugin."""
repo = require_repo(directory)
plugins = get_value(repo, 'plugins')
return plugins.get(plugin) if isinstance(plugins, dict) else None | Gets the settings for the specified plugin. | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/plugins.py#L38-L42 |
joeyespo/gitpress | gitpress/previewing.py | preview | def preview(directory=None, host=None, port=None, watch=True):
"""Runs a local server to preview the working directory of a repository."""
directory = directory or '.'
host = host or '127.0.0.1'
port = port or 5000
# TODO: admin interface
# TODO: use cache_only to keep from modifying output directly
out_directory = build(directory)
# Serve generated site
os.chdir(out_directory)
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer((host, port), Handler)
print ' * Serving on http://%s:%s/' % (host, port)
httpd.serve_forever() | python | def preview(directory=None, host=None, port=None, watch=True):
"""Runs a local server to preview the working directory of a repository."""
directory = directory or '.'
host = host or '127.0.0.1'
port = port or 5000
# TODO: admin interface
# TODO: use cache_only to keep from modifying output directly
out_directory = build(directory)
# Serve generated site
os.chdir(out_directory)
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer((host, port), Handler)
print ' * Serving on http://%s:%s/' % (host, port)
httpd.serve_forever() | Runs a local server to preview the working directory of a repository. | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/previewing.py#L7-L23 |
joeyespo/gitpress | gitpress/repository.py | require_repo | def require_repo(directory=None):
"""Checks for a presentation repository and raises an exception if not found."""
if directory and not os.path.isdir(directory):
raise ValueError('Directory not found: ' + repr(directory))
repo = repo_path(directory)
if not os.path.isdir(repo):
raise RepositoryNotFoundError(directory)
return repo | python | def require_repo(directory=None):
"""Checks for a presentation repository and raises an exception if not found."""
if directory and not os.path.isdir(directory):
raise ValueError('Directory not found: ' + repr(directory))
repo = repo_path(directory)
if not os.path.isdir(repo):
raise RepositoryNotFoundError(directory)
return repo | Checks for a presentation repository and raises an exception if not found. | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/repository.py#L30-L37 |
joeyespo/gitpress | gitpress/repository.py | init | def init(directory=None):
"""Initializes a Gitpress presentation repository at the specified directory."""
repo = repo_path(directory)
if os.path.isdir(repo):
raise RepositoryAlreadyExistsError(directory, repo)
# Initialize repository with default template
shutil.copytree(default_template_path, repo)
message = '"Default presentation content."'
subprocess.call(['git', 'init', '-q', repo])
subprocess.call(['git', 'add', '.'], cwd=repo)
subprocess.call(['git', 'commit', '-q', '-m', message], cwd=repo)
return repo | python | def init(directory=None):
"""Initializes a Gitpress presentation repository at the specified directory."""
repo = repo_path(directory)
if os.path.isdir(repo):
raise RepositoryAlreadyExistsError(directory, repo)
# Initialize repository with default template
shutil.copytree(default_template_path, repo)
message = '"Default presentation content."'
subprocess.call(['git', 'init', '-q', repo])
subprocess.call(['git', 'add', '.'], cwd=repo)
subprocess.call(['git', 'commit', '-q', '-m', message], cwd=repo)
return repo | Initializes a Gitpress presentation repository at the specified directory. | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/repository.py#L45-L59 |
joeyespo/gitpress | gitpress/repository.py | iterate_presentation_files | def iterate_presentation_files(path=None, excludes=None, includes=None):
"""Iterates the repository presentation files relative to 'path',
not including themes. Note that 'includes' take priority."""
# Defaults
if includes is None:
includes = []
if excludes is None:
excludes = []
# Transform glob patterns to regular expressions
includes_pattern = r'|'.join([fnmatch.translate(x) for x in includes]) or r'$.'
excludes_pattern = r'|'.join([fnmatch.translate(x) for x in excludes]) or r'$.'
includes_re = re.compile(includes_pattern)
excludes_re = re.compile(excludes_pattern)
def included(root, name):
"""Returns True if the specified file is a presentation file."""
full_path = os.path.join(root, name)
# Explicitly included files takes priority
if includes_re.match(full_path):
return True
# Ignore special and excluded files
return (not specials_re.match(name)
and not excludes_re.match(full_path))
# Get a filtered list of paths to be built
for root, dirs, files in os.walk(path):
dirs[:] = [d for d in dirs if included(root, d)]
files = [f for f in files if included(root, f)]
for f in files:
yield os.path.relpath(os.path.join(root, f), path) | python | def iterate_presentation_files(path=None, excludes=None, includes=None):
"""Iterates the repository presentation files relative to 'path',
not including themes. Note that 'includes' take priority."""
# Defaults
if includes is None:
includes = []
if excludes is None:
excludes = []
# Transform glob patterns to regular expressions
includes_pattern = r'|'.join([fnmatch.translate(x) for x in includes]) or r'$.'
excludes_pattern = r'|'.join([fnmatch.translate(x) for x in excludes]) or r'$.'
includes_re = re.compile(includes_pattern)
excludes_re = re.compile(excludes_pattern)
def included(root, name):
"""Returns True if the specified file is a presentation file."""
full_path = os.path.join(root, name)
# Explicitly included files takes priority
if includes_re.match(full_path):
return True
# Ignore special and excluded files
return (not specials_re.match(name)
and not excludes_re.match(full_path))
# Get a filtered list of paths to be built
for root, dirs, files in os.walk(path):
dirs[:] = [d for d in dirs if included(root, d)]
files = [f for f in files if included(root, f)]
for f in files:
yield os.path.relpath(os.path.join(root, f), path) | Iterates the repository presentation files relative to 'path',
not including themes. Note that 'includes' take priority. | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/repository.py#L68-L99 |
joeyespo/gitpress | gitpress/config.py | read_config_file | def read_config_file(path):
"""Returns the configuration from the specified file."""
try:
with open(path, 'r') as f:
return json.load(f, object_pairs_hook=OrderedDict)
except IOError as ex:
if ex != errno.ENOENT:
raise
return {} | python | def read_config_file(path):
"""Returns the configuration from the specified file."""
try:
with open(path, 'r') as f:
return json.load(f, object_pairs_hook=OrderedDict)
except IOError as ex:
if ex != errno.ENOENT:
raise
return {} | Returns the configuration from the specified file. | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/config.py#L23-L31 |
joeyespo/gitpress | gitpress/config.py | write_config | def write_config(repo_directory, config):
"""Writes the specified configuration to the presentation repository."""
return write_config_file(os.path.join(repo_directory, config_file), config) | python | def write_config(repo_directory, config):
"""Writes the specified configuration to the presentation repository."""
return write_config_file(os.path.join(repo_directory, config_file), config) | Writes the specified configuration to the presentation repository. | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/config.py#L34-L36 |
joeyespo/gitpress | gitpress/config.py | write_config_file | def write_config_file(path, config):
"""Writes the specified configuration to the specified file."""
contents = json.dumps(config, indent=4, separators=(',', ': ')) + '\n'
try:
with open(path, 'w') as f:
f.write(contents)
return True
except IOError as ex:
if ex != errno.ENOENT:
raise
return False | python | def write_config_file(path, config):
"""Writes the specified configuration to the specified file."""
contents = json.dumps(config, indent=4, separators=(',', ': ')) + '\n'
try:
with open(path, 'w') as f:
f.write(contents)
return True
except IOError as ex:
if ex != errno.ENOENT:
raise
return False | Writes the specified configuration to the specified file. | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/config.py#L39-L49 |
joeyespo/gitpress | gitpress/config.py | get_value | def get_value(repo_directory, key, expect_type=None):
"""Gets the value of the specified key in the config file."""
config = read_config(repo_directory)
value = config.get(key)
if expect_type and value is not None and not isinstance(value, expect_type):
raise ConfigSchemaError('Expected config variable %s to be type %s, got %s'
% (repr(key), repr(expect_type), repr(type(value))))
return value | python | def get_value(repo_directory, key, expect_type=None):
"""Gets the value of the specified key in the config file."""
config = read_config(repo_directory)
value = config.get(key)
if expect_type and value is not None and not isinstance(value, expect_type):
raise ConfigSchemaError('Expected config variable %s to be type %s, got %s'
% (repr(key), repr(expect_type), repr(type(value))))
return value | Gets the value of the specified key in the config file. | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/config.py#L52-L59 |
joeyespo/gitpress | gitpress/config.py | set_value | def set_value(repo_directory, key, value, strict=True):
"""Sets the value of a particular key in the config file. This has no effect when setting to the same value."""
if value is None:
raise ValueError('Argument "value" must not be None.')
# Read values and do nothing if not making any changes
config = read_config(repo_directory)
old = config.get(key)
if old == value:
return old
# Check schema
if strict and old is not None and not isinstance(old, type(value)):
raise ConfigSchemaError('Expected config variable %s to be type %s, got %s'
% (repr(key), repr(type(value)), repr(type(old))))
# Set new value and save results
config[key] = value
write_config(repo_directory, config)
return old | python | def set_value(repo_directory, key, value, strict=True):
"""Sets the value of a particular key in the config file. This has no effect when setting to the same value."""
if value is None:
raise ValueError('Argument "value" must not be None.')
# Read values and do nothing if not making any changes
config = read_config(repo_directory)
old = config.get(key)
if old == value:
return old
# Check schema
if strict and old is not None and not isinstance(old, type(value)):
raise ConfigSchemaError('Expected config variable %s to be type %s, got %s'
% (repr(key), repr(type(value)), repr(type(old))))
# Set new value and save results
config[key] = value
write_config(repo_directory, config)
return old | Sets the value of a particular key in the config file. This has no effect when setting to the same value. | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/config.py#L62-L81 |
joeyespo/gitpress | gitpress/building.py | build | def build(content_directory=None, out_directory=None):
"""Builds the site from its content and presentation repository."""
content_directory = content_directory or '.'
out_directory = os.path.abspath(out_directory or default_out_directory)
repo = require_repo(content_directory)
# Prevent user mistakes
if out_directory == '.':
raise ValueError('Output directory must be different than the source directory: ' + repr(out_directory))
if os.path.basename(os.path.relpath(out_directory, content_directory)) == '..':
raise ValueError('Output directory must not contain the source directory: ' + repr(out_directory))
# TODO: read config
# TODO: use virtualenv
# TODO: init and run plugins
# TODO: process with active theme
# Collect and copy static files
files = presentation_files(repo)
remove_directory(out_directory)
copy_files(files, out_directory, repo)
return out_directory | python | def build(content_directory=None, out_directory=None):
"""Builds the site from its content and presentation repository."""
content_directory = content_directory or '.'
out_directory = os.path.abspath(out_directory or default_out_directory)
repo = require_repo(content_directory)
# Prevent user mistakes
if out_directory == '.':
raise ValueError('Output directory must be different than the source directory: ' + repr(out_directory))
if os.path.basename(os.path.relpath(out_directory, content_directory)) == '..':
raise ValueError('Output directory must not contain the source directory: ' + repr(out_directory))
# TODO: read config
# TODO: use virtualenv
# TODO: init and run plugins
# TODO: process with active theme
# Collect and copy static files
files = presentation_files(repo)
remove_directory(out_directory)
copy_files(files, out_directory, repo)
return out_directory | Builds the site from its content and presentation repository. | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/building.py#L9-L31 |
joeyespo/gitpress | gitpress/command.py | main | def main(argv=None):
"""The entry point of the application."""
if argv is None:
argv = sys.argv[1:]
usage = '\n\n\n'.join(__doc__.split('\n\n\n')[1:])
version = 'Gitpress ' + __version__
# Parse options
args = docopt(usage, argv=argv, version=version)
# Execute command
try:
return execute(args)
except RepositoryNotFoundError as ex:
error('No Gitpress repository found at', ex.directory) | python | def main(argv=None):
"""The entry point of the application."""
if argv is None:
argv = sys.argv[1:]
usage = '\n\n\n'.join(__doc__.split('\n\n\n')[1:])
version = 'Gitpress ' + __version__
# Parse options
args = docopt(usage, argv=argv, version=version)
# Execute command
try:
return execute(args)
except RepositoryNotFoundError as ex:
error('No Gitpress repository found at', ex.directory) | The entry point of the application. | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/command.py#L40-L54 |
joeyespo/gitpress | gitpress/command.py | execute | def execute(args):
"""Executes the command indicated by the specified parsed arguments."""
def info(*message):
"""Displays a message unless -q was specified."""
if not args['-q']:
print ' '.join(map(str, message))
if args['init']:
try:
repo = init(args['<directory>'])
info('Initialized Gitpress repository in', repo)
except RepositoryAlreadyExistsError as ex:
info('Gitpress repository already exists in', ex.repo)
return 0
if args['preview']:
directory, address = resolve(args['<directory>'], args['<address>'])
host, port = split_address(address)
if address and not host and not port:
error('Invalid address', repr(address))
return preview(directory, host=host, port=port)
if args['build']:
require_repo(args['<directory>'])
info('Building site', os.path.abspath(args['<directory>'] or '.'))
try:
out_directory = build(args['<directory>'], args['--out'])
except NotADirectoryError as ex:
error(ex)
info('Site built in', os.path.abspath(out_directory))
return 0
if args['themes']:
theme = args['<theme>']
if args['use']:
try:
switched = use_theme(theme)
except ConfigSchemaError as ex:
error('Could not modify config:', ex)
return 1
except ThemeNotFoundError as ex:
error('Theme %s is not currently installed.' % repr(theme))
return 1
info('Switched to theme %s' if switched else 'Already using %s' % repr(theme))
elif args['install']:
# TODO: implement
raise NotImplementedError()
elif args['uninstall']:
# TODO: implement
raise NotImplementedError()
else:
themes = list_themes()
if themes:
info('Installed themes:')
info(' ' + '\n '.join(themes))
else:
info('No themes installed.')
return 0
if args['plugins']:
plugin = args['<plugin>']
if args['add']:
try:
added = add_plugin(plugin)
except ConfigSchemaError as ex:
error('Could not modify config:', ex)
return 1
info(('Added plugin %s' if added else
'Plugin %s has already been added.') % repr(plugin))
elif args['remove']:
settings = get_plugin_settings(plugin)
if not args['-f'] and settings and isinstance(settings, dict):
warning = 'Plugin %s contains settings. Remove?' % repr(plugin)
if not yes_or_no(warning):
return 0
try:
removed = remove_plugin(plugin)
except ConfigSchemaError as ex:
error('Error: Could not modify config:', ex)
info(('Removed plugin %s' if removed else
'Plugin %s has already been removed.') % repr(plugin))
else:
plugins = list_plugins()
info('Installed plugins:\n ' + '\n '.join(plugins) if plugins else
'No plugins installed.')
return 0
return 1 | python | def execute(args):
"""Executes the command indicated by the specified parsed arguments."""
def info(*message):
"""Displays a message unless -q was specified."""
if not args['-q']:
print ' '.join(map(str, message))
if args['init']:
try:
repo = init(args['<directory>'])
info('Initialized Gitpress repository in', repo)
except RepositoryAlreadyExistsError as ex:
info('Gitpress repository already exists in', ex.repo)
return 0
if args['preview']:
directory, address = resolve(args['<directory>'], args['<address>'])
host, port = split_address(address)
if address and not host and not port:
error('Invalid address', repr(address))
return preview(directory, host=host, port=port)
if args['build']:
require_repo(args['<directory>'])
info('Building site', os.path.abspath(args['<directory>'] or '.'))
try:
out_directory = build(args['<directory>'], args['--out'])
except NotADirectoryError as ex:
error(ex)
info('Site built in', os.path.abspath(out_directory))
return 0
if args['themes']:
theme = args['<theme>']
if args['use']:
try:
switched = use_theme(theme)
except ConfigSchemaError as ex:
error('Could not modify config:', ex)
return 1
except ThemeNotFoundError as ex:
error('Theme %s is not currently installed.' % repr(theme))
return 1
info('Switched to theme %s' if switched else 'Already using %s' % repr(theme))
elif args['install']:
# TODO: implement
raise NotImplementedError()
elif args['uninstall']:
# TODO: implement
raise NotImplementedError()
else:
themes = list_themes()
if themes:
info('Installed themes:')
info(' ' + '\n '.join(themes))
else:
info('No themes installed.')
return 0
if args['plugins']:
plugin = args['<plugin>']
if args['add']:
try:
added = add_plugin(plugin)
except ConfigSchemaError as ex:
error('Could not modify config:', ex)
return 1
info(('Added plugin %s' if added else
'Plugin %s has already been added.') % repr(plugin))
elif args['remove']:
settings = get_plugin_settings(plugin)
if not args['-f'] and settings and isinstance(settings, dict):
warning = 'Plugin %s contains settings. Remove?' % repr(plugin)
if not yes_or_no(warning):
return 0
try:
removed = remove_plugin(plugin)
except ConfigSchemaError as ex:
error('Error: Could not modify config:', ex)
info(('Removed plugin %s' if removed else
'Plugin %s has already been removed.') % repr(plugin))
else:
plugins = list_plugins()
info('Installed plugins:\n ' + '\n '.join(plugins) if plugins else
'No plugins installed.')
return 0
return 1 | Executes the command indicated by the specified parsed arguments. | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/command.py#L57-L145 |
joeyespo/gitpress | gitpress/command.py | gpp | def gpp(argv=None):
"""Shortcut function for running the previewing command."""
if argv is None:
argv = sys.argv[1:]
argv.insert(0, 'preview')
return main(argv) | python | def gpp(argv=None):
"""Shortcut function for running the previewing command."""
if argv is None:
argv = sys.argv[1:]
argv.insert(0, 'preview')
return main(argv) | Shortcut function for running the previewing command. | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/command.py#L152-L157 |
joeyespo/gitpress | gitpress/themes.py | list_themes | def list_themes(directory=None):
"""Gets a list of the installed themes."""
repo = require_repo(directory)
path = os.path.join(repo, themes_dir)
return os.listdir(path) if os.path.isdir(path) else None | python | def list_themes(directory=None):
"""Gets a list of the installed themes."""
repo = require_repo(directory)
path = os.path.join(repo, themes_dir)
return os.listdir(path) if os.path.isdir(path) else None | Gets a list of the installed themes. | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/themes.py#L17-L21 |
joeyespo/gitpress | gitpress/themes.py | use_theme | def use_theme(theme, directory=None):
"""Switches to the specified theme. This returns False if switching to the already active theme."""
repo = require_repo(directory)
if theme not in list_themes(directory):
raise ThemeNotFoundError(theme)
old_theme = set_value(repo, 'theme', theme)
return old_theme != theme | python | def use_theme(theme, directory=None):
"""Switches to the specified theme. This returns False if switching to the already active theme."""
repo = require_repo(directory)
if theme not in list_themes(directory):
raise ThemeNotFoundError(theme)
old_theme = set_value(repo, 'theme', theme)
return old_theme != theme | Switches to the specified theme. This returns False if switching to the already active theme. | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/themes.py#L24-L31 |
wrobstory/vincent | vincent/properties.py | PropertySet.fill_opacity | def fill_opacity(value):
"""ValueRef : int or float, opacity of the fill (0 to 1)
"""
if value.value:
_assert_is_type('fill_opacity.value', value.value,
(float, int))
if value.value < 0 or value.value > 1:
raise ValueError(
'fill_opacity must be between 0 and 1') | python | def fill_opacity(value):
"""ValueRef : int or float, opacity of the fill (0 to 1)
"""
if value.value:
_assert_is_type('fill_opacity.value', value.value,
(float, int))
if value.value < 0 or value.value > 1:
raise ValueError(
'fill_opacity must be between 0 and 1') | ValueRef : int or float, opacity of the fill (0 to 1) | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/properties.py#L89-L97 |
wrobstory/vincent | vincent/properties.py | PropertySet.stroke_width | def stroke_width(value):
"""ValueRef : int, width of the stroke in pixels
"""
if value.value:
_assert_is_type('stroke_width.value', value.value, int)
if value.value < 0:
raise ValueError('stroke width cannot be negative') | python | def stroke_width(value):
"""ValueRef : int, width of the stroke in pixels
"""
if value.value:
_assert_is_type('stroke_width.value', value.value, int)
if value.value < 0:
raise ValueError('stroke width cannot be negative') | ValueRef : int, width of the stroke in pixels | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/properties.py#L111-L117 |
wrobstory/vincent | vincent/properties.py | PropertySet.stroke_opacity | def stroke_opacity(value):
"""ValueRef : number, opacity of the stroke (0 to 1)
"""
if value.value:
_assert_is_type('stroke_opacity.value', value.value,
(float, int))
if value.value < 0 or value.value > 1:
raise ValueError(
'stroke_opacity must be between 0 and 1') | python | def stroke_opacity(value):
"""ValueRef : number, opacity of the stroke (0 to 1)
"""
if value.value:
_assert_is_type('stroke_opacity.value', value.value,
(float, int))
if value.value < 0 or value.value > 1:
raise ValueError(
'stroke_opacity must be between 0 and 1') | ValueRef : number, opacity of the stroke (0 to 1) | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/properties.py#L120-L128 |
wrobstory/vincent | vincent/properties.py | PropertySet.size | def size(value):
"""ValueRef : number, area of the mark in pixels
This is the total area of a symbol. For example, a value of 500 and
a ``shape`` of ``'circle'`` would result in circles with an area of
500 square pixels. Only used if ``type`` is ``'symbol'``.
"""
if value.value:
_assert_is_type('size.value', value.value, int)
if value.value < 0:
raise ValueError('size cannot be negative') | python | def size(value):
"""ValueRef : number, area of the mark in pixels
This is the total area of a symbol. For example, a value of 500 and
a ``shape`` of ``'circle'`` would result in circles with an area of
500 square pixels. Only used if ``type`` is ``'symbol'``.
"""
if value.value:
_assert_is_type('size.value', value.value, int)
if value.value < 0:
raise ValueError('size cannot be negative') | ValueRef : number, area of the mark in pixels
This is the total area of a symbol. For example, a value of 500 and
a ``shape`` of ``'circle'`` would result in circles with an area of
500 square pixels. Only used if ``type`` is ``'symbol'``. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/properties.py#L131-L141 |
wrobstory/vincent | vincent/properties.py | PropertySet.shape | def shape(value):
"""ValueRef : string, type of symbol to use
Possible values are ``'circle'`` (default), ``'square'``,
``'cross'``, ``'diamond'``, ``'triangle-up'``, and
``'triangle-down'``. Only used if ``type`` is ``'symbol'``.
"""
if value.value:
_assert_is_type('shape.value', value.value, str_types)
if value.value not in PropertySet._valid_shapes:
raise ValueError(value.value + ' is not a valid shape') | python | def shape(value):
"""ValueRef : string, type of symbol to use
Possible values are ``'circle'`` (default), ``'square'``,
``'cross'``, ``'diamond'``, ``'triangle-up'``, and
``'triangle-down'``. Only used if ``type`` is ``'symbol'``.
"""
if value.value:
_assert_is_type('shape.value', value.value, str_types)
if value.value not in PropertySet._valid_shapes:
raise ValueError(value.value + ' is not a valid shape') | ValueRef : string, type of symbol to use
Possible values are ``'circle'`` (default), ``'square'``,
``'cross'``, ``'diamond'``, ``'triangle-up'``, and
``'triangle-down'``. Only used if ``type`` is ``'symbol'``. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/properties.py#L148-L158 |
wrobstory/vincent | vincent/properties.py | PropertySet.interpolate | def interpolate(value):
"""ValueRef : string, line interpolation method to use
Possible values for ``area`` types are `'linear'`,
``'step-before'``, ``'step-after'``, ``'basis'``, ``'basis-open'``,
``'cardinal'``, ``'cardinal-open'``, ``'monotone'``. ``line`` types
have all values for ``area`` as well as ``'basis-closed'``,
``'bundle'``, and ``'cardinal-closed'``.
Only used if ``type`` is ``'area'`` or ``'line'``.
"""
if value.value:
_assert_is_type('shape.value', value.value, str_types)
if value.value not in PropertySet._valid_methods:
raise ValueError(value.value + ' is not a valid method') | python | def interpolate(value):
"""ValueRef : string, line interpolation method to use
Possible values for ``area`` types are `'linear'`,
``'step-before'``, ``'step-after'``, ``'basis'``, ``'basis-open'``,
``'cardinal'``, ``'cardinal-open'``, ``'monotone'``. ``line`` types
have all values for ``area`` as well as ``'basis-closed'``,
``'bundle'``, and ``'cardinal-closed'``.
Only used if ``type`` is ``'area'`` or ``'line'``.
"""
if value.value:
_assert_is_type('shape.value', value.value, str_types)
if value.value not in PropertySet._valid_methods:
raise ValueError(value.value + ' is not a valid method') | ValueRef : string, line interpolation method to use
Possible values for ``area`` types are `'linear'`,
``'step-before'``, ``'step-after'``, ``'basis'``, ``'basis-open'``,
``'cardinal'``, ``'cardinal-open'``, ``'monotone'``. ``line`` types
have all values for ``area`` as well as ``'basis-closed'``,
``'bundle'``, and ``'cardinal-closed'``.
Only used if ``type`` is ``'area'`` or ``'line'``. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/properties.py#L206-L220 |
wrobstory/vincent | vincent/properties.py | PropertySet.align | def align(value):
"""ValueRef : string, horizontal alignment of mark
Possible values are ``'left'``, ``'right'``, and ``'center'``. Only
used if ``type`` is ``'image'`` or ``'text'``.
"""
if value.value:
_assert_is_type('shape.value', value.value, str_types)
if value.value not in PropertySet._valid_align:
raise ValueError(value.value + ' is not a valid alignment') | python | def align(value):
"""ValueRef : string, horizontal alignment of mark
Possible values are ``'left'``, ``'right'``, and ``'center'``. Only
used if ``type`` is ``'image'`` or ``'text'``.
"""
if value.value:
_assert_is_type('shape.value', value.value, str_types)
if value.value not in PropertySet._valid_align:
raise ValueError(value.value + ' is not a valid alignment') | ValueRef : string, horizontal alignment of mark
Possible values are ``'left'``, ``'right'``, and ``'center'``. Only
used if ``type`` is ``'image'`` or ``'text'``. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/properties.py#L239-L248 |
wrobstory/vincent | vincent/properties.py | PropertySet.baseline | def baseline(value):
"""ValueRef : string, vertical alignment of mark
Possible values are ``'top'``, ``'middle'``, and ``'bottom'``. Only
used if ``type`` is ``'image'`` or ``'text'``.
"""
if value.value:
_assert_is_type('shape.value', value.value, str_types)
if value.value not in PropertySet._valid_baseline:
raise ValueError(value.value + ' is not a valid baseline') | python | def baseline(value):
"""ValueRef : string, vertical alignment of mark
Possible values are ``'top'``, ``'middle'``, and ``'bottom'``. Only
used if ``type`` is ``'image'`` or ``'text'``.
"""
if value.value:
_assert_is_type('shape.value', value.value, str_types)
if value.value not in PropertySet._valid_baseline:
raise ValueError(value.value + ' is not a valid baseline') | ValueRef : string, vertical alignment of mark
Possible values are ``'top'``, ``'middle'``, and ``'bottom'``. Only
used if ``type`` is ``'image'`` or ``'text'``. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/properties.py#L253-L262 |
wrobstory/vincent | vincent/transforms.py | Transform.type | def type(value):
"""string: property name in which to store the computed transform
value.
The valid transform types are as follows:
'array', 'copy', 'cross', 'facet', 'filter', 'flatten', 'fold',
'formula', 'slice', 'sort', 'stats', 'truncate', 'unique', 'window',
'zip', 'force', 'geo', 'geopath', 'link', 'pie', 'stack', 'treemap',
'wordcloud'
"""
valid_transforms = frozenset([
'array', 'copy', 'cross', 'facet', 'filter',
'flatten', 'fold', 'formula', 'slice', 'sort', 'stats',
'truncate', 'unique', 'window', 'zip', 'force', 'geo', 'geopath',
'link', 'pie', 'stack', 'treemap', 'wordcloud'
])
if value not in valid_transforms:
raise ValueError('Transform type must be'
' one of {0}'.format(str(valid_transforms))) | python | def type(value):
"""string: property name in which to store the computed transform
value.
The valid transform types are as follows:
'array', 'copy', 'cross', 'facet', 'filter', 'flatten', 'fold',
'formula', 'slice', 'sort', 'stats', 'truncate', 'unique', 'window',
'zip', 'force', 'geo', 'geopath', 'link', 'pie', 'stack', 'treemap',
'wordcloud'
"""
valid_transforms = frozenset([
'array', 'copy', 'cross', 'facet', 'filter',
'flatten', 'fold', 'formula', 'slice', 'sort', 'stats',
'truncate', 'unique', 'window', 'zip', 'force', 'geo', 'geopath',
'link', 'pie', 'stack', 'treemap', 'wordcloud'
])
if value not in valid_transforms:
raise ValueError('Transform type must be'
' one of {0}'.format(str(valid_transforms))) | string: property name in which to store the computed transform
value.
The valid transform types are as follows:
'array', 'copy', 'cross', 'facet', 'filter', 'flatten', 'fold',
'formula', 'slice', 'sort', 'stats', 'truncate', 'unique', 'window',
'zip', 'force', 'geo', 'geopath', 'link', 'pie', 'stack', 'treemap',
'wordcloud' | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/transforms.py#L28-L49 |
wrobstory/vincent | vincent/charts.py | data_type | def data_type(data, grouped=False, columns=None, key_on='idx', iter_idx=None):
'''Data type check for automatic import'''
if iter_idx:
return Data.from_mult_iters(idx=iter_idx, **data)
if pd:
if isinstance(data, (pd.Series, pd.DataFrame)):
return Data.from_pandas(data, grouped=grouped, columns=columns,
key_on=key_on)
if isinstance(data, (list, tuple, dict)):
return Data.from_iter(data)
else:
raise ValueError('This data type is not supported by Vincent.') | python | def data_type(data, grouped=False, columns=None, key_on='idx', iter_idx=None):
'''Data type check for automatic import'''
if iter_idx:
return Data.from_mult_iters(idx=iter_idx, **data)
if pd:
if isinstance(data, (pd.Series, pd.DataFrame)):
return Data.from_pandas(data, grouped=grouped, columns=columns,
key_on=key_on)
if isinstance(data, (list, tuple, dict)):
return Data.from_iter(data)
else:
raise ValueError('This data type is not supported by Vincent.') | Data type check for automatic import | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/charts.py#L28-L39 |
wrobstory/vincent | vincent/charts.py | Map.rebind | def rebind(self, column=None, brew='GnBu'):
"""Bind a new column to the data map
Parameters
----------
column: str, default None
Pandas DataFrame column name
brew: str, default None
Color brewer abbreviation. See colors.py
"""
self.data['table'] = Data.keypairs(
self.raw_data, columns=[self.data_key, column])
domain = [Data.serialize(self.raw_data[column].min()),
Data.serialize(self.raw_data[column].quantile(0.95))]
scale = Scale(name='color', type='quantize', domain=domain,
range=brews[brew])
self.scales['color'] = scale | python | def rebind(self, column=None, brew='GnBu'):
"""Bind a new column to the data map
Parameters
----------
column: str, default None
Pandas DataFrame column name
brew: str, default None
Color brewer abbreviation. See colors.py
"""
self.data['table'] = Data.keypairs(
self.raw_data, columns=[self.data_key, column])
domain = [Data.serialize(self.raw_data[column].min()),
Data.serialize(self.raw_data[column].quantile(0.95))]
scale = Scale(name='color', type='quantize', domain=domain,
range=brews[brew])
self.scales['color'] = scale | Bind a new column to the data map
Parameters
----------
column: str, default None
Pandas DataFrame column name
brew: str, default None
Color brewer abbreviation. See colors.py | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/charts.py#L510-L527 |
wrobstory/vincent | vincent/visualization.py | Visualization.viewport | def viewport(value):
"""2-element list of ints : Dimensions of the viewport
The viewport is a bounding box containing the visualization. If the
dimensions of the visualization are larger than the viewport, then
the visualization will be scrollable.
If undefined, then the full visualization is shown.
"""
if len(value) != 2:
raise ValueError('viewport must have 2 dimensions')
for v in value:
_assert_is_type('viewport dimension', v, int)
if v < 0:
raise ValueError('viewport dimensions cannot be negative') | python | def viewport(value):
"""2-element list of ints : Dimensions of the viewport
The viewport is a bounding box containing the visualization. If the
dimensions of the visualization are larger than the viewport, then
the visualization will be scrollable.
If undefined, then the full visualization is shown.
"""
if len(value) != 2:
raise ValueError('viewport must have 2 dimensions')
for v in value:
_assert_is_type('viewport dimension', v, int)
if v < 0:
raise ValueError('viewport dimensions cannot be negative') | 2-element list of ints : Dimensions of the viewport
The viewport is a bounding box containing the visualization. If the
dimensions of the visualization are larger than the viewport, then
the visualization will be scrollable.
If undefined, then the full visualization is shown. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/visualization.py#L77-L91 |
wrobstory/vincent | vincent/visualization.py | Visualization.padding | def padding(value):
"""int or dict : Padding around visualization
The padding defines the distance between the edge of the
visualization canvas to the visualization box. It does not count as
part of the visualization width/height. Values cannot be negative.
If a dict, padding must have all keys ``''top'``, ``'left'``,
``'right'``, and ``'bottom'`` with int values.
"""
if isinstance(value, dict):
required_keys = ['top', 'left', 'right', 'bottom']
for key in required_keys:
if key not in value:
error = ('Padding must have keys "{0}".'
.format('", "'.join(required_keys)))
raise ValueError(error)
_assert_is_type('padding: {0}'.format(key), value[key], int)
if value[key] < 0:
raise ValueError('Padding cannot be negative.')
elif isinstance(value, int):
if value < 0:
raise ValueError('Padding cannot be negative.')
else:
if value not in ("auto", "strict"):
raise ValueError('Padding can only be auto or strict.') | python | def padding(value):
"""int or dict : Padding around visualization
The padding defines the distance between the edge of the
visualization canvas to the visualization box. It does not count as
part of the visualization width/height. Values cannot be negative.
If a dict, padding must have all keys ``''top'``, ``'left'``,
``'right'``, and ``'bottom'`` with int values.
"""
if isinstance(value, dict):
required_keys = ['top', 'left', 'right', 'bottom']
for key in required_keys:
if key not in value:
error = ('Padding must have keys "{0}".'
.format('", "'.join(required_keys)))
raise ValueError(error)
_assert_is_type('padding: {0}'.format(key), value[key], int)
if value[key] < 0:
raise ValueError('Padding cannot be negative.')
elif isinstance(value, int):
if value < 0:
raise ValueError('Padding cannot be negative.')
else:
if value not in ("auto", "strict"):
raise ValueError('Padding can only be auto or strict.') | int or dict : Padding around visualization
The padding defines the distance between the edge of the
visualization canvas to the visualization box. It does not count as
part of the visualization width/height. Values cannot be negative.
If a dict, padding must have all keys ``''top'``, ``'left'``,
``'right'``, and ``'bottom'`` with int values. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/visualization.py#L94-L119 |
wrobstory/vincent | vincent/visualization.py | Visualization.data | def data(value):
"""list or KeyedList of ``Data`` : Data definitions
This defines the data being visualized. See the :class:`Data` class
for details.
"""
for i, entry in enumerate(value):
_assert_is_type('data[{0}]'.format(i), entry, Data) | python | def data(value):
"""list or KeyedList of ``Data`` : Data definitions
This defines the data being visualized. See the :class:`Data` class
for details.
"""
for i, entry in enumerate(value):
_assert_is_type('data[{0}]'.format(i), entry, Data) | list or KeyedList of ``Data`` : Data definitions
This defines the data being visualized. See the :class:`Data` class
for details. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/visualization.py#L122-L129 |
wrobstory/vincent | vincent/visualization.py | Visualization.scales | def scales(value):
"""list or KeyedList of ``Scale`` : Scale definitions
Scales map the data from the domain of the data to some
visualization space (such as an x-axis). See the :class:`Scale`
class for details.
"""
for i, entry in enumerate(value):
_assert_is_type('scales[{0}]'.format(i), entry, Scale) | python | def scales(value):
"""list or KeyedList of ``Scale`` : Scale definitions
Scales map the data from the domain of the data to some
visualization space (such as an x-axis). See the :class:`Scale`
class for details.
"""
for i, entry in enumerate(value):
_assert_is_type('scales[{0}]'.format(i), entry, Scale) | list or KeyedList of ``Scale`` : Scale definitions
Scales map the data from the domain of the data to some
visualization space (such as an x-axis). See the :class:`Scale`
class for details. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/visualization.py#L132-L140 |
wrobstory/vincent | vincent/visualization.py | Visualization.axes | def axes(value):
"""list or KeyedList of ``Axis`` : Axis definitions
Axes define the locations of the data being mapped by the scales.
See the :class:`Axis` class for details.
"""
for i, entry in enumerate(value):
_assert_is_type('axes[{0}]'.format(i), entry, Axis) | python | def axes(value):
"""list or KeyedList of ``Axis`` : Axis definitions
Axes define the locations of the data being mapped by the scales.
See the :class:`Axis` class for details.
"""
for i, entry in enumerate(value):
_assert_is_type('axes[{0}]'.format(i), entry, Axis) | list or KeyedList of ``Axis`` : Axis definitions
Axes define the locations of the data being mapped by the scales.
See the :class:`Axis` class for details. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/visualization.py#L143-L150 |
wrobstory/vincent | vincent/visualization.py | Visualization.marks | def marks(value):
"""list or KeyedList of ``Mark`` : Mark definitions
Marks are the visual objects (such as lines, bars, etc.) that
represent the data in the visualization space. See the :class:`Mark`
class for details.
"""
for i, entry in enumerate(value):
_assert_is_type('marks[{0}]'.format(i), entry, Mark) | python | def marks(value):
"""list or KeyedList of ``Mark`` : Mark definitions
Marks are the visual objects (such as lines, bars, etc.) that
represent the data in the visualization space. See the :class:`Mark`
class for details.
"""
for i, entry in enumerate(value):
_assert_is_type('marks[{0}]'.format(i), entry, Mark) | list or KeyedList of ``Mark`` : Mark definitions
Marks are the visual objects (such as lines, bars, etc.) that
represent the data in the visualization space. See the :class:`Mark`
class for details. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/visualization.py#L153-L161 |
wrobstory/vincent | vincent/visualization.py | Visualization.legends | def legends(value):
"""list or KeyedList of ``Legends`` : Legend definitions
Legends visualize scales, and take one or more scales as their input.
They can be customized via a LegendProperty object.
"""
for i, entry in enumerate(value):
_assert_is_type('legends[{0}]'.format(i), entry, Legend) | python | def legends(value):
"""list or KeyedList of ``Legends`` : Legend definitions
Legends visualize scales, and take one or more scales as their input.
They can be customized via a LegendProperty object.
"""
for i, entry in enumerate(value):
_assert_is_type('legends[{0}]'.format(i), entry, Legend) | list or KeyedList of ``Legends`` : Legend definitions
Legends visualize scales, and take one or more scales as their input.
They can be customized via a LegendProperty object. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/visualization.py#L164-L171 |
wrobstory/vincent | vincent/visualization.py | Visualization.axis_titles | def axis_titles(self, x=None, y=None):
"""Apply axis titles to the figure.
This is a convenience method for manually modifying the "Axes" mark.
Parameters
----------
x: string, default 'null'
X-axis title
y: string, default 'null'
Y-axis title
Example
-------
>>>vis.axis_titles(y="Data 1", x="Data 2")
"""
keys = self.axes.get_keys()
if keys:
for key in keys:
if key == 'x':
self.axes[key].title = x
elif key == 'y':
self.axes[key].title = y
else:
self.axes.extend([Axis(type='x', title=x),
Axis(type='y', title=y)])
return self | python | def axis_titles(self, x=None, y=None):
"""Apply axis titles to the figure.
This is a convenience method for manually modifying the "Axes" mark.
Parameters
----------
x: string, default 'null'
X-axis title
y: string, default 'null'
Y-axis title
Example
-------
>>>vis.axis_titles(y="Data 1", x="Data 2")
"""
keys = self.axes.get_keys()
if keys:
for key in keys:
if key == 'x':
self.axes[key].title = x
elif key == 'y':
self.axes[key].title = y
else:
self.axes.extend([Axis(type='x', title=x),
Axis(type='y', title=y)])
return self | Apply axis titles to the figure.
This is a convenience method for manually modifying the "Axes" mark.
Parameters
----------
x: string, default 'null'
X-axis title
y: string, default 'null'
Y-axis title
Example
-------
>>>vis.axis_titles(y="Data 1", x="Data 2") | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/visualization.py#L173-L201 |
wrobstory/vincent | vincent/visualization.py | Visualization._set_axis_properties | def _set_axis_properties(self, axis):
"""Set AxisProperties and PropertySets"""
if not getattr(axis, 'properties'):
axis.properties = AxisProperties()
for prop in ['ticks', 'axis', 'major_ticks', 'minor_ticks',
'title', 'labels']:
setattr(axis.properties, prop, PropertySet()) | python | def _set_axis_properties(self, axis):
"""Set AxisProperties and PropertySets"""
if not getattr(axis, 'properties'):
axis.properties = AxisProperties()
for prop in ['ticks', 'axis', 'major_ticks', 'minor_ticks',
'title', 'labels']:
setattr(axis.properties, prop, PropertySet()) | Set AxisProperties and PropertySets | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/visualization.py#L203-L209 |
wrobstory/vincent | vincent/visualization.py | Visualization._set_all_axis_color | def _set_all_axis_color(self, axis, color):
"""Set axis ticks, title, labels to given color"""
for prop in ['ticks', 'axis', 'major_ticks', 'minor_ticks', 'title',
'labels']:
prop_set = getattr(axis.properties, prop)
if color and prop in ['title', 'labels']:
prop_set.fill = ValueRef(value=color)
elif color and prop in ['axis', 'major_ticks', 'minor_ticks',
'ticks']:
prop_set.stroke = ValueRef(value=color) | python | def _set_all_axis_color(self, axis, color):
"""Set axis ticks, title, labels to given color"""
for prop in ['ticks', 'axis', 'major_ticks', 'minor_ticks', 'title',
'labels']:
prop_set = getattr(axis.properties, prop)
if color and prop in ['title', 'labels']:
prop_set.fill = ValueRef(value=color)
elif color and prop in ['axis', 'major_ticks', 'minor_ticks',
'ticks']:
prop_set.stroke = ValueRef(value=color) | Set axis ticks, title, labels to given color | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/visualization.py#L211-L220 |
wrobstory/vincent | vincent/visualization.py | Visualization._axis_properties | def _axis_properties(self, axis, title_size, title_offset, label_angle,
label_align, color):
"""Assign axis properties"""
if self.axes:
axis = [a for a in self.axes if a.scale == axis][0]
self._set_axis_properties(axis)
self._set_all_axis_color(axis, color)
if title_size:
axis.properties.title.font_size = ValueRef(value=title_size)
if label_angle:
axis.properties.labels.angle = ValueRef(value=label_angle)
if label_align:
axis.properties.labels.align = ValueRef(value=label_align)
if title_offset:
axis.properties.title.dy = ValueRef(value=title_offset)
else:
raise ValueError('This Visualization has no axes!') | python | def _axis_properties(self, axis, title_size, title_offset, label_angle,
label_align, color):
"""Assign axis properties"""
if self.axes:
axis = [a for a in self.axes if a.scale == axis][0]
self._set_axis_properties(axis)
self._set_all_axis_color(axis, color)
if title_size:
axis.properties.title.font_size = ValueRef(value=title_size)
if label_angle:
axis.properties.labels.angle = ValueRef(value=label_angle)
if label_align:
axis.properties.labels.align = ValueRef(value=label_align)
if title_offset:
axis.properties.title.dy = ValueRef(value=title_offset)
else:
raise ValueError('This Visualization has no axes!') | Assign axis properties | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/visualization.py#L222-L239 |
wrobstory/vincent | vincent/visualization.py | Visualization.common_axis_properties | def common_axis_properties(self, color=None, title_size=None):
"""Set common axis properties such as color
Parameters
----------
color: str, default None
Hex color str, etc
"""
if self.axes:
for axis in self.axes:
self._set_axis_properties(axis)
self._set_all_axis_color(axis, color)
if title_size:
ref = ValueRef(value=title_size)
axis.properties.title.font_size = ref
else:
raise ValueError('This Visualization has no axes!')
return self | python | def common_axis_properties(self, color=None, title_size=None):
"""Set common axis properties such as color
Parameters
----------
color: str, default None
Hex color str, etc
"""
if self.axes:
for axis in self.axes:
self._set_axis_properties(axis)
self._set_all_axis_color(axis, color)
if title_size:
ref = ValueRef(value=title_size)
axis.properties.title.font_size = ref
else:
raise ValueError('This Visualization has no axes!')
return self | Set common axis properties such as color
Parameters
----------
color: str, default None
Hex color str, etc | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/visualization.py#L241-L258 |
wrobstory/vincent | vincent/visualization.py | Visualization.x_axis_properties | def x_axis_properties(self, title_size=None, title_offset=None,
label_angle=None, label_align=None, color=None):
"""Change x-axis title font size and label angle
Parameters
----------
title_size: int, default None
Title size, in px
title_offset: int, default None
Pixel offset from given axis
label_angle: int, default None
label angle in degrees
label_align: str, default None
Label alignment
color: str, default None
Hex color
"""
self._axis_properties('x', title_size, title_offset, label_angle,
label_align, color)
return self | python | def x_axis_properties(self, title_size=None, title_offset=None,
label_angle=None, label_align=None, color=None):
"""Change x-axis title font size and label angle
Parameters
----------
title_size: int, default None
Title size, in px
title_offset: int, default None
Pixel offset from given axis
label_angle: int, default None
label angle in degrees
label_align: str, default None
Label alignment
color: str, default None
Hex color
"""
self._axis_properties('x', title_size, title_offset, label_angle,
label_align, color)
return self | Change x-axis title font size and label angle
Parameters
----------
title_size: int, default None
Title size, in px
title_offset: int, default None
Pixel offset from given axis
label_angle: int, default None
label angle in degrees
label_align: str, default None
Label alignment
color: str, default None
Hex color | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/visualization.py#L260-L279 |
wrobstory/vincent | vincent/visualization.py | Visualization.y_axis_properties | def y_axis_properties(self, title_size=None, title_offset=None,
label_angle=None, label_align=None, color=None):
"""Change y-axis title font size and label angle
Parameters
----------
title_size: int, default None
Title size, in px
title_offset: int, default None
Pixel offset from given axis
label_angle: int, default None
label angle in degrees
label_align: str, default None
Label alignment
color: str, default None
Hex color
"""
self._axis_properties('y', title_size, title_offset, label_angle,
label_align, color)
return self | python | def y_axis_properties(self, title_size=None, title_offset=None,
label_angle=None, label_align=None, color=None):
"""Change y-axis title font size and label angle
Parameters
----------
title_size: int, default None
Title size, in px
title_offset: int, default None
Pixel offset from given axis
label_angle: int, default None
label angle in degrees
label_align: str, default None
Label alignment
color: str, default None
Hex color
"""
self._axis_properties('y', title_size, title_offset, label_angle,
label_align, color)
return self | Change y-axis title font size and label angle
Parameters
----------
title_size: int, default None
Title size, in px
title_offset: int, default None
Pixel offset from given axis
label_angle: int, default None
label angle in degrees
label_align: str, default None
Label alignment
color: str, default None
Hex color | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/visualization.py#L281-L300 |
wrobstory/vincent | vincent/visualization.py | Visualization.legend | def legend(self, title=None, scale='color', text_color=None):
"""Convience method for adding a legend to the figure.
Important: This defaults to the color scale that is generated with
Line, Area, Stacked Line, etc charts. For bar charts, the scale ref is
usually 'y'.
Parameters
----------
title: string, default None
Legend Title
scale: string, default 'color'
Scale reference for legend
text_color: str, default None
Title and label color
"""
self.legends.append(Legend(title=title, fill=scale, offset=0,
properties=LegendProperties()))
if text_color:
color_props = PropertySet(fill=ValueRef(value=text_color))
self.legends[0].properties.labels = color_props
self.legends[0].properties.title = color_props
return self | python | def legend(self, title=None, scale='color', text_color=None):
"""Convience method for adding a legend to the figure.
Important: This defaults to the color scale that is generated with
Line, Area, Stacked Line, etc charts. For bar charts, the scale ref is
usually 'y'.
Parameters
----------
title: string, default None
Legend Title
scale: string, default 'color'
Scale reference for legend
text_color: str, default None
Title and label color
"""
self.legends.append(Legend(title=title, fill=scale, offset=0,
properties=LegendProperties()))
if text_color:
color_props = PropertySet(fill=ValueRef(value=text_color))
self.legends[0].properties.labels = color_props
self.legends[0].properties.title = color_props
return self | Convience method for adding a legend to the figure.
Important: This defaults to the color scale that is generated with
Line, Area, Stacked Line, etc charts. For bar charts, the scale ref is
usually 'y'.
Parameters
----------
title: string, default None
Legend Title
scale: string, default 'color'
Scale reference for legend
text_color: str, default None
Title and label color | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/visualization.py#L302-L325 |
wrobstory/vincent | vincent/visualization.py | Visualization.colors | def colors(self, brew=None, range_=None):
"""Convenience method for adding color brewer scales to charts with a
color scale, such as stacked or grouped bars.
See the colors here: http://colorbrewer2.org/
Or here: http://bl.ocks.org/mbostock/5577023
This assumes that a 'color' scale exists on your chart.
Parameters
----------
brew: string, default None
Color brewer scheme (BuGn, YlOrRd, etc)
range: list, default None
List of colors. Ex: ['#ac4142', '#d28445', '#f4bf75']
"""
if brew:
self.scales['color'].range = brews[brew]
elif range_:
self.scales['color'].range = range_
return self | python | def colors(self, brew=None, range_=None):
"""Convenience method for adding color brewer scales to charts with a
color scale, such as stacked or grouped bars.
See the colors here: http://colorbrewer2.org/
Or here: http://bl.ocks.org/mbostock/5577023
This assumes that a 'color' scale exists on your chart.
Parameters
----------
brew: string, default None
Color brewer scheme (BuGn, YlOrRd, etc)
range: list, default None
List of colors. Ex: ['#ac4142', '#d28445', '#f4bf75']
"""
if brew:
self.scales['color'].range = brews[brew]
elif range_:
self.scales['color'].range = range_
return self | Convenience method for adding color brewer scales to charts with a
color scale, such as stacked or grouped bars.
See the colors here: http://colorbrewer2.org/
Or here: http://bl.ocks.org/mbostock/5577023
This assumes that a 'color' scale exists on your chart.
Parameters
----------
brew: string, default None
Color brewer scheme (BuGn, YlOrRd, etc)
range: list, default None
List of colors. Ex: ['#ac4142', '#d28445', '#f4bf75'] | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/visualization.py#L327-L348 |
wrobstory/vincent | vincent/visualization.py | Visualization.validate | def validate(self, require_all=True, scale='colors'):
"""Validate the visualization contents.
Parameters
----------
require_all : boolean, default True
If True (default), then all fields ``data``, ``scales``,
``axes``, and ``marks`` must be defined. The user is allowed to
disable this if the intent is to define the elements
client-side.
If the contents of the visualization are not valid Vega, then a
:class:`ValidationError` is raised.
"""
super(self.__class__, self).validate()
required_attribs = ('data', 'scales', 'axes', 'marks')
for elem in required_attribs:
attr = getattr(self, elem)
if attr:
# Validate each element of the sets of data, etc
for entry in attr:
entry.validate()
names = [a.name for a in attr]
if len(names) != len(set(names)):
raise ValidationError(elem + ' has duplicate names')
elif require_all:
raise ValidationError(
elem + ' must be defined for valid visualization') | python | def validate(self, require_all=True, scale='colors'):
"""Validate the visualization contents.
Parameters
----------
require_all : boolean, default True
If True (default), then all fields ``data``, ``scales``,
``axes``, and ``marks`` must be defined. The user is allowed to
disable this if the intent is to define the elements
client-side.
If the contents of the visualization are not valid Vega, then a
:class:`ValidationError` is raised.
"""
super(self.__class__, self).validate()
required_attribs = ('data', 'scales', 'axes', 'marks')
for elem in required_attribs:
attr = getattr(self, elem)
if attr:
# Validate each element of the sets of data, etc
for entry in attr:
entry.validate()
names = [a.name for a in attr]
if len(names) != len(set(names)):
raise ValidationError(elem + ' has duplicate names')
elif require_all:
raise ValidationError(
elem + ' must be defined for valid visualization') | Validate the visualization contents.
Parameters
----------
require_all : boolean, default True
If True (default), then all fields ``data``, ``scales``,
``axes``, and ``marks`` must be defined. The user is allowed to
disable this if the intent is to define the elements
client-side.
If the contents of the visualization are not valid Vega, then a
:class:`ValidationError` is raised. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/visualization.py#L350-L377 |
wrobstory/vincent | vincent/visualization.py | Visualization._repr_html_ | def _repr_html_(self):
"""Build the HTML representation for IPython."""
vis_id = str(uuid4()).replace("-", "")
html = """<div id="vis%s"></div>
<script>
( function() {
var _do_plot = function() {
if (typeof vg === 'undefined') {
window.addEventListener('vincent_libs_loaded', _do_plot)
return;
}
vg.parse.spec(%s, function(chart) {
chart({el: "#vis%s"}).update();
});
};
_do_plot();
})();
</script>
<style>.vega canvas {width: 100%%;}</style>
""" % (vis_id, self.to_json(pretty_print=False), vis_id)
return html | python | def _repr_html_(self):
"""Build the HTML representation for IPython."""
vis_id = str(uuid4()).replace("-", "")
html = """<div id="vis%s"></div>
<script>
( function() {
var _do_plot = function() {
if (typeof vg === 'undefined') {
window.addEventListener('vincent_libs_loaded', _do_plot)
return;
}
vg.parse.spec(%s, function(chart) {
chart({el: "#vis%s"}).update();
});
};
_do_plot();
})();
</script>
<style>.vega canvas {width: 100%%;}</style>
""" % (vis_id, self.to_json(pretty_print=False), vis_id)
return html | Build the HTML representation for IPython. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/visualization.py#L379-L399 |
wrobstory/vincent | vincent/visualization.py | Visualization.display | def display(self):
"""Display the visualization inline in the IPython notebook.
This is deprecated, use the following instead::
from IPython.display import display
display(viz)
"""
from IPython.core.display import display, HTML
display(HTML(self._repr_html_())) | python | def display(self):
"""Display the visualization inline in the IPython notebook.
This is deprecated, use the following instead::
from IPython.display import display
display(viz)
"""
from IPython.core.display import display, HTML
display(HTML(self._repr_html_())) | Display the visualization inline in the IPython notebook.
This is deprecated, use the following instead::
from IPython.display import display
display(viz) | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/visualization.py#L401-L410 |
wrobstory/vincent | vincent/data.py | Data.validate | def validate(self, *args):
"""Validate contents of class
"""
super(self.__class__, self).validate(*args)
if not self.name:
raise ValidationError('name is required for Data') | python | def validate(self, *args):
"""Validate contents of class
"""
super(self.__class__, self).validate(*args)
if not self.name:
raise ValidationError('name is required for Data') | Validate contents of class | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/data.py#L122-L127 |
wrobstory/vincent | vincent/data.py | Data.serialize | def serialize(obj):
"""Convert an object into a JSON-serializable value
This is used by the ``from_pandas`` and ``from_numpy`` functions to
convert data to JSON-serializable types when loading.
"""
if isinstance(obj, str_types):
return obj
elif hasattr(obj, 'timetuple'):
return int(time.mktime(obj.timetuple())) * 1000
elif hasattr(obj, 'item'):
return obj.item()
elif hasattr(obj, '__float__'):
if isinstance(obj, int):
return int(obj)
else:
return float(obj)
elif hasattr(obj, '__int__'):
return int(obj)
else:
raise LoadError('cannot serialize index of type '
+ type(obj).__name__) | python | def serialize(obj):
"""Convert an object into a JSON-serializable value
This is used by the ``from_pandas`` and ``from_numpy`` functions to
convert data to JSON-serializable types when loading.
"""
if isinstance(obj, str_types):
return obj
elif hasattr(obj, 'timetuple'):
return int(time.mktime(obj.timetuple())) * 1000
elif hasattr(obj, 'item'):
return obj.item()
elif hasattr(obj, '__float__'):
if isinstance(obj, int):
return int(obj)
else:
return float(obj)
elif hasattr(obj, '__int__'):
return int(obj)
else:
raise LoadError('cannot serialize index of type '
+ type(obj).__name__) | Convert an object into a JSON-serializable value
This is used by the ``from_pandas`` and ``from_numpy`` functions to
convert data to JSON-serializable types when loading. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/data.py#L130-L151 |
wrobstory/vincent | vincent/data.py | Data.from_pandas | def from_pandas(cls, data, columns=None, key_on='idx', name=None,
series_key='data', grouped=False, records=False, **kwargs):
"""Load values from a pandas ``Series`` or ``DataFrame`` object
Parameters
----------
data : pandas ``Series`` or ``DataFrame``
Pandas object to import data from.
columns: list, default None
DataFrame columns to convert to Data. Keys default to col names.
If columns are given and on_index is False, x-axis data will
default to the first column.
key_on: string, default 'index'
Value to key on for x-axis data. Defaults to index.
name : string, default None
Applies to the ``name`` attribute of the generated class. If
``None`` (default), then the ``name`` attribute of ``pd_obj`` is
used if it exists, or ``'table'`` if it doesn't.
series_key : string, default 'data'
Applies only to ``Series``. If ``None`` (default), then defaults to
data.name. For example, if ``series_key`` is ``'x'``, then the
entries of the ``values`` list
will be ``{'idx': ..., 'col': 'x', 'val': ...}``.
grouped: boolean, default False
Pass true for an extra grouping parameter
records: boolean, defaule False
Requires Pandas 0.12 or greater. Writes the Pandas DataFrame
using the df.to_json(orient='records') formatting.
**kwargs : dict
Additional arguments passed to the :class:`Data` constructor.
"""
# Note: There's an experimental JSON encoder floating around in
# pandas land that hasn't made it into the main branch. This
# function should be revisited if it ever does.
if not pd:
raise LoadError('pandas could not be imported')
if not hasattr(data, 'index'):
raise ValueError('Please load a Pandas object.')
if name:
vega_data = cls(name=name, **kwargs)
else:
vega_data = cls(name='table', **kwargs)
pd_obj = data.copy()
if columns:
pd_obj = data[columns]
if key_on != 'idx':
pd_obj.index = data[key_on]
if records:
# The worst
vega_data.values = json.loads(pd_obj.to_json(orient='records'))
return vega_data
vega_data.values = []
if isinstance(pd_obj, pd.Series):
data_key = data.name or series_key
for i, v in pd_obj.iteritems():
value = {}
value['idx'] = cls.serialize(i)
value['col'] = data_key
value['val'] = cls.serialize(v)
vega_data.values.append(value)
elif isinstance(pd_obj, pd.DataFrame):
# We have to explicitly convert the column names to strings
# because the json serializer doesn't allow for integer keys.
for i, row in pd_obj.iterrows():
for num, (k, v) in enumerate(row.iteritems()):
value = {}
value['idx'] = cls.serialize(i)
value['col'] = cls.serialize(k)
value['val'] = cls.serialize(v)
if grouped:
value['group'] = num
vega_data.values.append(value)
else:
raise ValueError('cannot load from data type '
+ type(pd_obj).__name__)
return vega_data | python | def from_pandas(cls, data, columns=None, key_on='idx', name=None,
series_key='data', grouped=False, records=False, **kwargs):
"""Load values from a pandas ``Series`` or ``DataFrame`` object
Parameters
----------
data : pandas ``Series`` or ``DataFrame``
Pandas object to import data from.
columns: list, default None
DataFrame columns to convert to Data. Keys default to col names.
If columns are given and on_index is False, x-axis data will
default to the first column.
key_on: string, default 'index'
Value to key on for x-axis data. Defaults to index.
name : string, default None
Applies to the ``name`` attribute of the generated class. If
``None`` (default), then the ``name`` attribute of ``pd_obj`` is
used if it exists, or ``'table'`` if it doesn't.
series_key : string, default 'data'
Applies only to ``Series``. If ``None`` (default), then defaults to
data.name. For example, if ``series_key`` is ``'x'``, then the
entries of the ``values`` list
will be ``{'idx': ..., 'col': 'x', 'val': ...}``.
grouped: boolean, default False
Pass true for an extra grouping parameter
records: boolean, defaule False
Requires Pandas 0.12 or greater. Writes the Pandas DataFrame
using the df.to_json(orient='records') formatting.
**kwargs : dict
Additional arguments passed to the :class:`Data` constructor.
"""
# Note: There's an experimental JSON encoder floating around in
# pandas land that hasn't made it into the main branch. This
# function should be revisited if it ever does.
if not pd:
raise LoadError('pandas could not be imported')
if not hasattr(data, 'index'):
raise ValueError('Please load a Pandas object.')
if name:
vega_data = cls(name=name, **kwargs)
else:
vega_data = cls(name='table', **kwargs)
pd_obj = data.copy()
if columns:
pd_obj = data[columns]
if key_on != 'idx':
pd_obj.index = data[key_on]
if records:
# The worst
vega_data.values = json.loads(pd_obj.to_json(orient='records'))
return vega_data
vega_data.values = []
if isinstance(pd_obj, pd.Series):
data_key = data.name or series_key
for i, v in pd_obj.iteritems():
value = {}
value['idx'] = cls.serialize(i)
value['col'] = data_key
value['val'] = cls.serialize(v)
vega_data.values.append(value)
elif isinstance(pd_obj, pd.DataFrame):
# We have to explicitly convert the column names to strings
# because the json serializer doesn't allow for integer keys.
for i, row in pd_obj.iterrows():
for num, (k, v) in enumerate(row.iteritems()):
value = {}
value['idx'] = cls.serialize(i)
value['col'] = cls.serialize(k)
value['val'] = cls.serialize(v)
if grouped:
value['group'] = num
vega_data.values.append(value)
else:
raise ValueError('cannot load from data type '
+ type(pd_obj).__name__)
return vega_data | Load values from a pandas ``Series`` or ``DataFrame`` object
Parameters
----------
data : pandas ``Series`` or ``DataFrame``
Pandas object to import data from.
columns: list, default None
DataFrame columns to convert to Data. Keys default to col names.
If columns are given and on_index is False, x-axis data will
default to the first column.
key_on: string, default 'index'
Value to key on for x-axis data. Defaults to index.
name : string, default None
Applies to the ``name`` attribute of the generated class. If
``None`` (default), then the ``name`` attribute of ``pd_obj`` is
used if it exists, or ``'table'`` if it doesn't.
series_key : string, default 'data'
Applies only to ``Series``. If ``None`` (default), then defaults to
data.name. For example, if ``series_key`` is ``'x'``, then the
entries of the ``values`` list
will be ``{'idx': ..., 'col': 'x', 'val': ...}``.
grouped: boolean, default False
Pass true for an extra grouping parameter
records: boolean, defaule False
Requires Pandas 0.12 or greater. Writes the Pandas DataFrame
using the df.to_json(orient='records') formatting.
**kwargs : dict
Additional arguments passed to the :class:`Data` constructor. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/data.py#L154-L234 |
wrobstory/vincent | vincent/data.py | Data.from_numpy | def from_numpy(cls, np_obj, name, columns, index=None, index_key=None,
**kwargs):
"""Load values from a numpy array
Parameters
----------
np_obj : numpy.ndarray
numpy array to load data from
name : string
``name`` field for the data
columns : iterable
Sequence of column names, from left to right. Must have same
length as the number of columns of ``np_obj``.
index : iterable, default None
Sequence of indices from top to bottom. If ``None`` (default),
then the indices are integers starting at 0. Must have same
length as the number of rows of ``np_obj``.
index_key : string, default None
Key to use for the index. If ``None`` (default), ``idx`` is
used.
**kwargs : dict
Additional arguments passed to the :class:`Data` constructor
Notes
-----
The individual elements of ``np_obj``, ``columns``, and ``index``
must return valid values from :func:`Data.serialize`.
"""
if not np:
raise LoadError('numpy could not be imported')
_assert_is_type('numpy object', np_obj, np.ndarray)
# Integer index if none is provided
index = index or range(np_obj.shape[0])
# Explicitly map dict-keys to strings for JSON serializer.
columns = list(map(str, columns))
index_key = index_key or cls._default_index_key
if len(index) != np_obj.shape[0]:
raise LoadError(
'length of index must be equal to number of rows of array')
elif len(columns) != np_obj.shape[1]:
raise LoadError(
'length of columns must be equal to number of columns of '
'array')
data = cls(name=name, **kwargs)
data.values = [
dict([(index_key, cls.serialize(idx))] +
[(col, x) for col, x in zip(columns, row)])
for idx, row in zip(index, np_obj.tolist())]
return data | python | def from_numpy(cls, np_obj, name, columns, index=None, index_key=None,
**kwargs):
"""Load values from a numpy array
Parameters
----------
np_obj : numpy.ndarray
numpy array to load data from
name : string
``name`` field for the data
columns : iterable
Sequence of column names, from left to right. Must have same
length as the number of columns of ``np_obj``.
index : iterable, default None
Sequence of indices from top to bottom. If ``None`` (default),
then the indices are integers starting at 0. Must have same
length as the number of rows of ``np_obj``.
index_key : string, default None
Key to use for the index. If ``None`` (default), ``idx`` is
used.
**kwargs : dict
Additional arguments passed to the :class:`Data` constructor
Notes
-----
The individual elements of ``np_obj``, ``columns``, and ``index``
must return valid values from :func:`Data.serialize`.
"""
if not np:
raise LoadError('numpy could not be imported')
_assert_is_type('numpy object', np_obj, np.ndarray)
# Integer index if none is provided
index = index or range(np_obj.shape[0])
# Explicitly map dict-keys to strings for JSON serializer.
columns = list(map(str, columns))
index_key = index_key or cls._default_index_key
if len(index) != np_obj.shape[0]:
raise LoadError(
'length of index must be equal to number of rows of array')
elif len(columns) != np_obj.shape[1]:
raise LoadError(
'length of columns must be equal to number of columns of '
'array')
data = cls(name=name, **kwargs)
data.values = [
dict([(index_key, cls.serialize(idx))] +
[(col, x) for col, x in zip(columns, row)])
for idx, row in zip(index, np_obj.tolist())]
return data | Load values from a numpy array
Parameters
----------
np_obj : numpy.ndarray
numpy array to load data from
name : string
``name`` field for the data
columns : iterable
Sequence of column names, from left to right. Must have same
length as the number of columns of ``np_obj``.
index : iterable, default None
Sequence of indices from top to bottom. If ``None`` (default),
then the indices are integers starting at 0. Must have same
length as the number of rows of ``np_obj``.
index_key : string, default None
Key to use for the index. If ``None`` (default), ``idx`` is
used.
**kwargs : dict
Additional arguments passed to the :class:`Data` constructor
Notes
-----
The individual elements of ``np_obj``, ``columns``, and ``index``
must return valid values from :func:`Data.serialize`. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/data.py#L237-L291 |
wrobstory/vincent | vincent/data.py | Data.from_mult_iters | def from_mult_iters(cls, name=None, idx=None, **kwargs):
"""Load values from multiple iters
Parameters
----------
name : string, default None
Name of the data set. If None (default), the name will be set to
``'table'``.
idx: string, default None
Iterable to use for the data index
**kwargs : dict of iterables
The ``values`` field will contain dictionaries with keys for
each of the iterables provided. For example,
d = Data.from_iters(idx='x', x=[0, 1, 5], y=(10, 20, 30))
would result in ``d`` having a ``values`` field with
[{'idx': 0, 'col': 'y', 'val': 10},
{'idx': 1, 'col': 'y', 'val': 20}
If the iterables are not the same length, then ValueError is
raised.
"""
if not name:
name = 'table'
lengths = [len(v) for v in kwargs.values()]
if len(set(lengths)) != 1:
raise ValueError('Iterables must all be same length')
if not idx:
raise ValueError('Must provide iter name index reference')
index = kwargs.pop(idx)
vega_vals = []
for k, v in sorted(kwargs.items()):
for idx, val in zip(index, v):
value = {}
value['idx'] = idx
value['col'] = k
value['val'] = val
vega_vals.append(value)
return cls(name, values=vega_vals) | python | def from_mult_iters(cls, name=None, idx=None, **kwargs):
"""Load values from multiple iters
Parameters
----------
name : string, default None
Name of the data set. If None (default), the name will be set to
``'table'``.
idx: string, default None
Iterable to use for the data index
**kwargs : dict of iterables
The ``values`` field will contain dictionaries with keys for
each of the iterables provided. For example,
d = Data.from_iters(idx='x', x=[0, 1, 5], y=(10, 20, 30))
would result in ``d`` having a ``values`` field with
[{'idx': 0, 'col': 'y', 'val': 10},
{'idx': 1, 'col': 'y', 'val': 20}
If the iterables are not the same length, then ValueError is
raised.
"""
if not name:
name = 'table'
lengths = [len(v) for v in kwargs.values()]
if len(set(lengths)) != 1:
raise ValueError('Iterables must all be same length')
if not idx:
raise ValueError('Must provide iter name index reference')
index = kwargs.pop(idx)
vega_vals = []
for k, v in sorted(kwargs.items()):
for idx, val in zip(index, v):
value = {}
value['idx'] = idx
value['col'] = k
value['val'] = val
vega_vals.append(value)
return cls(name, values=vega_vals) | Load values from multiple iters
Parameters
----------
name : string, default None
Name of the data set. If None (default), the name will be set to
``'table'``.
idx: string, default None
Iterable to use for the data index
**kwargs : dict of iterables
The ``values`` field will contain dictionaries with keys for
each of the iterables provided. For example,
d = Data.from_iters(idx='x', x=[0, 1, 5], y=(10, 20, 30))
would result in ``d`` having a ``values`` field with
[{'idx': 0, 'col': 'y', 'val': 10},
{'idx': 1, 'col': 'y', 'val': 20}
If the iterables are not the same length, then ValueError is
raised. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/data.py#L294-L339 |
wrobstory/vincent | vincent/data.py | Data.from_iter | def from_iter(cls, data, name=None):
"""Convenience method for loading data from an iterable.
Defaults to numerical indexing for x-axis.
Parameters
----------
data: iterable
An iterable of data (list, tuple, dict of key/val pairs)
name: string, default None
Name of the data set. If None (default), the name will be set to
``'table'``.
"""
if not name:
name = 'table'
if isinstance(data, (list, tuple)):
data = {x: y for x, y in enumerate(data)}
values = [{'idx': k, 'col': 'data', 'val': v}
for k, v in sorted(data.items())]
return cls(name, values=values) | python | def from_iter(cls, data, name=None):
"""Convenience method for loading data from an iterable.
Defaults to numerical indexing for x-axis.
Parameters
----------
data: iterable
An iterable of data (list, tuple, dict of key/val pairs)
name: string, default None
Name of the data set. If None (default), the name will be set to
``'table'``.
"""
if not name:
name = 'table'
if isinstance(data, (list, tuple)):
data = {x: y for x, y in enumerate(data)}
values = [{'idx': k, 'col': 'data', 'val': v}
for k, v in sorted(data.items())]
return cls(name, values=values) | Convenience method for loading data from an iterable.
Defaults to numerical indexing for x-axis.
Parameters
----------
data: iterable
An iterable of data (list, tuple, dict of key/val pairs)
name: string, default None
Name of the data set. If None (default), the name will be set to
``'table'``. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/data.py#L342-L364 |
wrobstory/vincent | vincent/data.py | Data.keypairs | def keypairs(cls, data, columns=None, use_index=False, name=None):
"""This will format the data as Key: Value pairs, rather than the
idx/col/val style. This is useful for some transforms, and to
key choropleth map data
Standard Data Types:
List: [0, 10, 20, 30, 40]
Paired Tuples: ((0, 1), (0, 2), (0, 3))
Dict: {'A': 10, 'B': 20, 'C': 30, 'D': 40, 'E': 50}
Plus Pandas DataFrame and Series, and Numpy ndarray
Parameters
----------
data:
List, Tuple, Dict, Pandas Series/DataFrame, Numpy ndarray
columns: list, default None
If passing Pandas DataFrame, you must pass at least one column
name.If one column is passed, x-values will default to the index
values.If two column names are passed, x-values are columns[0],
y-values columns[1].
use_index: boolean, default False
Use the DataFrame index for your x-values
"""
if not name:
name = 'table'
cls.raw_data = data
# Tuples
if isinstance(data, tuple):
values = [{"x": x[0], "y": x[1]} for x in data]
# Lists
elif isinstance(data, list):
values = [{"x": x, "y": y}
for x, y in zip(range(len(data) + 1), data)]
# Dicts
elif isinstance(data, dict) or isinstance(data, pd.Series):
values = [{"x": x, "y": y} for x, y in sorted(data.items())]
# Dataframes
elif isinstance(data, pd.DataFrame):
if len(columns) > 1 and use_index:
raise ValueError('If using index as x-axis, len(columns)'
'cannot be > 1')
if use_index or len(columns) == 1:
values = [{"x": cls.serialize(x[0]),
"y": cls.serialize(x[1][columns[0]])}
for x in data.iterrows()]
else:
values = [{"x": cls.serialize(x[1][columns[0]]),
"y": cls.serialize(x[1][columns[1]])}
for x in data.iterrows()]
# NumPy arrays
elif isinstance(data, np.ndarray):
values = cls._numpy_to_values(data)
else:
raise TypeError('unknown data type %s' % type(data))
return cls(name, values=values) | python | def keypairs(cls, data, columns=None, use_index=False, name=None):
"""This will format the data as Key: Value pairs, rather than the
idx/col/val style. This is useful for some transforms, and to
key choropleth map data
Standard Data Types:
List: [0, 10, 20, 30, 40]
Paired Tuples: ((0, 1), (0, 2), (0, 3))
Dict: {'A': 10, 'B': 20, 'C': 30, 'D': 40, 'E': 50}
Plus Pandas DataFrame and Series, and Numpy ndarray
Parameters
----------
data:
List, Tuple, Dict, Pandas Series/DataFrame, Numpy ndarray
columns: list, default None
If passing Pandas DataFrame, you must pass at least one column
name.If one column is passed, x-values will default to the index
values.If two column names are passed, x-values are columns[0],
y-values columns[1].
use_index: boolean, default False
Use the DataFrame index for your x-values
"""
if not name:
name = 'table'
cls.raw_data = data
# Tuples
if isinstance(data, tuple):
values = [{"x": x[0], "y": x[1]} for x in data]
# Lists
elif isinstance(data, list):
values = [{"x": x, "y": y}
for x, y in zip(range(len(data) + 1), data)]
# Dicts
elif isinstance(data, dict) or isinstance(data, pd.Series):
values = [{"x": x, "y": y} for x, y in sorted(data.items())]
# Dataframes
elif isinstance(data, pd.DataFrame):
if len(columns) > 1 and use_index:
raise ValueError('If using index as x-axis, len(columns)'
'cannot be > 1')
if use_index or len(columns) == 1:
values = [{"x": cls.serialize(x[0]),
"y": cls.serialize(x[1][columns[0]])}
for x in data.iterrows()]
else:
values = [{"x": cls.serialize(x[1][columns[0]]),
"y": cls.serialize(x[1][columns[1]])}
for x in data.iterrows()]
# NumPy arrays
elif isinstance(data, np.ndarray):
values = cls._numpy_to_values(data)
else:
raise TypeError('unknown data type %s' % type(data))
return cls(name, values=values) | This will format the data as Key: Value pairs, rather than the
idx/col/val style. This is useful for some transforms, and to
key choropleth map data
Standard Data Types:
List: [0, 10, 20, 30, 40]
Paired Tuples: ((0, 1), (0, 2), (0, 3))
Dict: {'A': 10, 'B': 20, 'C': 30, 'D': 40, 'E': 50}
Plus Pandas DataFrame and Series, and Numpy ndarray
Parameters
----------
data:
List, Tuple, Dict, Pandas Series/DataFrame, Numpy ndarray
columns: list, default None
If passing Pandas DataFrame, you must pass at least one column
name.If one column is passed, x-values will default to the index
values.If two column names are passed, x-values are columns[0],
y-values columns[1].
use_index: boolean, default False
Use the DataFrame index for your x-values | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/data.py#L367-L430 |
wrobstory/vincent | vincent/data.py | Data._numpy_to_values | def _numpy_to_values(data):
'''Convert a NumPy array to values attribute'''
def to_list_no_index(xvals, yvals):
return [{"x": x, "y": np.asscalar(y)}
for x, y in zip(xvals, yvals)]
if len(data.shape) == 1 or data.shape[1] == 1:
xvals = range(data.shape[0] + 1)
values = to_list_no_index(xvals, data)
elif len(data.shape) == 2:
if data.shape[1] == 2:
# NumPy arrays and matrices have different iteration rules.
if isinstance(data, np.matrix):
xidx = (0, 0)
yidx = (0, 1)
else:
xidx = 0
yidx = 1
xvals = [np.asscalar(row[xidx]) for row in data]
yvals = [np.asscalar(row[yidx]) for row in data]
values = [{"x": x, "y": y} for x, y in zip(xvals, yvals)]
else:
raise ValueError('arrays with > 2 columns not supported')
else:
raise ValueError('invalid dimensions for ndarray')
return values | python | def _numpy_to_values(data):
'''Convert a NumPy array to values attribute'''
def to_list_no_index(xvals, yvals):
return [{"x": x, "y": np.asscalar(y)}
for x, y in zip(xvals, yvals)]
if len(data.shape) == 1 or data.shape[1] == 1:
xvals = range(data.shape[0] + 1)
values = to_list_no_index(xvals, data)
elif len(data.shape) == 2:
if data.shape[1] == 2:
# NumPy arrays and matrices have different iteration rules.
if isinstance(data, np.matrix):
xidx = (0, 0)
yidx = (0, 1)
else:
xidx = 0
yidx = 1
xvals = [np.asscalar(row[xidx]) for row in data]
yvals = [np.asscalar(row[yidx]) for row in data]
values = [{"x": x, "y": y} for x, y in zip(xvals, yvals)]
else:
raise ValueError('arrays with > 2 columns not supported')
else:
raise ValueError('invalid dimensions for ndarray')
return values | Convert a NumPy array to values attribute | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/data.py#L433-L460 |
wrobstory/vincent | vincent/data.py | Data.to_json | def to_json(self, validate=False, pretty_print=True, data_path=None):
"""Convert data to JSON
Parameters
----------
data_path : string
If not None, then data is written to a separate file at the
specified path. Note that the ``url`` attribute if the data must
be set independently for the data to load correctly.
Returns
-------
string
Valid Vega JSON.
"""
# TODO: support writing to separate file
return super(self.__class__, self).to_json(validate=validate,
pretty_print=pretty_print) | python | def to_json(self, validate=False, pretty_print=True, data_path=None):
"""Convert data to JSON
Parameters
----------
data_path : string
If not None, then data is written to a separate file at the
specified path. Note that the ``url`` attribute if the data must
be set independently for the data to load correctly.
Returns
-------
string
Valid Vega JSON.
"""
# TODO: support writing to separate file
return super(self.__class__, self).to_json(validate=validate,
pretty_print=pretty_print) | Convert data to JSON
Parameters
----------
data_path : string
If not None, then data is written to a separate file at the
specified path. Note that the ``url`` attribute if the data must
be set independently for the data to load correctly.
Returns
-------
string
Valid Vega JSON. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/data.py#L462-L479 |
wrobstory/vincent | vincent/core.py | initialize_notebook | def initialize_notebook():
"""Initialize the IPython notebook display elements"""
try:
from IPython.core.display import display, HTML
except ImportError:
print("IPython Notebook could not be loaded.")
# Thanks to @jakevdp:
# https://github.com/jakevdp/mpld3/blob/master/mpld3/_display.py#L85
load_lib = """
function vct_load_lib(url, callback){
if(
typeof d3 !== 'undefined' &&
url === '//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.min.js'){
callback()
}
var s = document.createElement('script');
s.src = url;
s.async = true;
s.onreadystatechange = s.onload = callback;
s.onerror = function(){
console.warn("failed to load library " + url);
};
document.getElementsByTagName("head")[0].appendChild(s);
};
var vincent_event = new CustomEvent(
"vincent_libs_loaded",
{bubbles: true, cancelable: true}
);
"""
lib_urls = [
"'//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.min.js'",
("'//cdnjs.cloudflare.com/ajax/libs/d3-geo-projection/0.2.9/"
"d3.geo.projection.min.js'"),
"'//wrobstory.github.io/d3-cloud/d3.layout.cloud.js'",
"'//wrobstory.github.io/vega/vega.v1.3.3.js'"
]
get_lib = """vct_load_lib(%s, function(){
%s
});"""
load_js = get_lib
ipy_trigger = "window.dispatchEvent(vincent_event);"
for elem in lib_urls[:-1]:
load_js = load_js % (elem, get_lib)
load_js = load_js % (lib_urls[-1], ipy_trigger)
html = """
<script>
%s
function load_all_libs(){
console.log('Loading Vincent libs...')
%s
};
if(typeof define === "function" && define.amd){
if (window['d3'] === undefined ||
window['topojson'] === undefined){
require.config(
{paths: {
d3: '//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.min',
topojson: '//cdnjs.cloudflare.com/ajax/libs/topojson/1.6.9/topojson.min'
}
}
);
require(["d3"], function(d3){
console.log('Loading Vincent from require.js...')
window.d3 = d3;
require(["topojson"], function(topojson){
window.topojson = topojson;
load_all_libs();
});
});
} else {
load_all_libs();
};
}else{
console.log('Require.js not found, loading manually...')
load_all_libs();
};
</script>""" % (load_lib, load_js,)
return display(HTML(html)) | python | def initialize_notebook():
"""Initialize the IPython notebook display elements"""
try:
from IPython.core.display import display, HTML
except ImportError:
print("IPython Notebook could not be loaded.")
# Thanks to @jakevdp:
# https://github.com/jakevdp/mpld3/blob/master/mpld3/_display.py#L85
load_lib = """
function vct_load_lib(url, callback){
if(
typeof d3 !== 'undefined' &&
url === '//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.min.js'){
callback()
}
var s = document.createElement('script');
s.src = url;
s.async = true;
s.onreadystatechange = s.onload = callback;
s.onerror = function(){
console.warn("failed to load library " + url);
};
document.getElementsByTagName("head")[0].appendChild(s);
};
var vincent_event = new CustomEvent(
"vincent_libs_loaded",
{bubbles: true, cancelable: true}
);
"""
lib_urls = [
"'//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.min.js'",
("'//cdnjs.cloudflare.com/ajax/libs/d3-geo-projection/0.2.9/"
"d3.geo.projection.min.js'"),
"'//wrobstory.github.io/d3-cloud/d3.layout.cloud.js'",
"'//wrobstory.github.io/vega/vega.v1.3.3.js'"
]
get_lib = """vct_load_lib(%s, function(){
%s
});"""
load_js = get_lib
ipy_trigger = "window.dispatchEvent(vincent_event);"
for elem in lib_urls[:-1]:
load_js = load_js % (elem, get_lib)
load_js = load_js % (lib_urls[-1], ipy_trigger)
html = """
<script>
%s
function load_all_libs(){
console.log('Loading Vincent libs...')
%s
};
if(typeof define === "function" && define.amd){
if (window['d3'] === undefined ||
window['topojson'] === undefined){
require.config(
{paths: {
d3: '//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.min',
topojson: '//cdnjs.cloudflare.com/ajax/libs/topojson/1.6.9/topojson.min'
}
}
);
require(["d3"], function(d3){
console.log('Loading Vincent from require.js...')
window.d3 = d3;
require(["topojson"], function(topojson){
window.topojson = topojson;
load_all_libs();
});
});
} else {
load_all_libs();
};
}else{
console.log('Require.js not found, loading manually...')
load_all_libs();
};
</script>""" % (load_lib, load_js,)
return display(HTML(html)) | Initialize the IPython notebook display elements | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/core.py#L25-L104 |
wrobstory/vincent | vincent/core.py | _assert_is_type | def _assert_is_type(name, value, value_type):
"""Assert that a value must be a given type."""
if not isinstance(value, value_type):
if type(value_type) is tuple:
types = ', '.join(t.__name__ for t in value_type)
raise ValueError('{0} must be one of ({1})'.format(name, types))
else:
raise ValueError('{0} must be {1}'
.format(name, value_type.__name__)) | python | def _assert_is_type(name, value, value_type):
"""Assert that a value must be a given type."""
if not isinstance(value, value_type):
if type(value_type) is tuple:
types = ', '.join(t.__name__ for t in value_type)
raise ValueError('{0} must be one of ({1})'.format(name, types))
else:
raise ValueError('{0} must be {1}'
.format(name, value_type.__name__)) | Assert that a value must be a given type. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/core.py#L107-L115 |
wrobstory/vincent | vincent/core.py | grammar | def grammar(grammar_type=None, grammar_name=None):
"""Decorator to define properties that map to the ``grammar``
dict. This dict is the canonical representation of the Vega grammar
within Vincent.
This decorator is intended for classes that map to some pre-defined JSON
structure, such as axes, data, marks, scales, etc. It is assumed that this
decorates functions with an instance of ``self.grammar``.
Parameters
----------
grammar_type : type or tuple of types, default None
If the argument to the decorated function is not of the given types,
then a ValueError is raised. No type checking is done if the type is
None (default).
grammar_name : string, default None
An optional name to map to the internal ``grammar`` dict. If None
(default), then the key for the dict is the name of the function
being decorated. If not None, then it will be the name specified
here. This is useful if the expected JSON field name is a Python
keyword or has an un-Pythonic name.
This should decorate a "validator" function that should return no value
but raise an exception if the provided value is not valid Vega grammar. If
the validator throws no exception, then the value is assigned to the
``grammar`` dict.
The validator function should take only one argument - the value to be
validated - so that no ``self`` argument is included; the validator
should not modify the class.
If no arguments are given, then no type-checking is done the property
will be mapped to a field with the name of the decorated function.
The doc string for the property is taken from the validator functions's
doc string.
"""
def grammar_creator(validator, name):
def setter(self, value):
if isinstance(grammar_type, (type, tuple)):
_assert_is_type(validator.__name__, value, grammar_type)
validator(value)
self.grammar[name] = value
def getter(self):
return self.grammar.get(name, None)
def deleter(self):
if name in self.grammar:
del self.grammar[name]
return property(getter, setter, deleter, validator.__doc__)
if isinstance(grammar_type, (type, tuple)):
# If grammar_type is a type, return another decorator.
def grammar_dec(validator):
# Make sure to use the grammar name if it's there.
if grammar_name:
return grammar_creator(validator, grammar_name)
else:
return grammar_creator(validator, validator.__name__)
return grammar_dec
elif isinstance(grammar_name, str_types):
# If grammar_name is a string, use that name and return another
# decorator.
def grammar_dec(validator):
return grammar_creator(validator, grammar_name)
return grammar_dec
else:
# Otherwise we assume that grammar_type is actually the function being
# decorated.
return grammar_creator(grammar_type, grammar_type.__name__) | python | def grammar(grammar_type=None, grammar_name=None):
"""Decorator to define properties that map to the ``grammar``
dict. This dict is the canonical representation of the Vega grammar
within Vincent.
This decorator is intended for classes that map to some pre-defined JSON
structure, such as axes, data, marks, scales, etc. It is assumed that this
decorates functions with an instance of ``self.grammar``.
Parameters
----------
grammar_type : type or tuple of types, default None
If the argument to the decorated function is not of the given types,
then a ValueError is raised. No type checking is done if the type is
None (default).
grammar_name : string, default None
An optional name to map to the internal ``grammar`` dict. If None
(default), then the key for the dict is the name of the function
being decorated. If not None, then it will be the name specified
here. This is useful if the expected JSON field name is a Python
keyword or has an un-Pythonic name.
This should decorate a "validator" function that should return no value
but raise an exception if the provided value is not valid Vega grammar. If
the validator throws no exception, then the value is assigned to the
``grammar`` dict.
The validator function should take only one argument - the value to be
validated - so that no ``self`` argument is included; the validator
should not modify the class.
If no arguments are given, then no type-checking is done the property
will be mapped to a field with the name of the decorated function.
The doc string for the property is taken from the validator functions's
doc string.
"""
def grammar_creator(validator, name):
def setter(self, value):
if isinstance(grammar_type, (type, tuple)):
_assert_is_type(validator.__name__, value, grammar_type)
validator(value)
self.grammar[name] = value
def getter(self):
return self.grammar.get(name, None)
def deleter(self):
if name in self.grammar:
del self.grammar[name]
return property(getter, setter, deleter, validator.__doc__)
if isinstance(grammar_type, (type, tuple)):
# If grammar_type is a type, return another decorator.
def grammar_dec(validator):
# Make sure to use the grammar name if it's there.
if grammar_name:
return grammar_creator(validator, grammar_name)
else:
return grammar_creator(validator, validator.__name__)
return grammar_dec
elif isinstance(grammar_name, str_types):
# If grammar_name is a string, use that name and return another
# decorator.
def grammar_dec(validator):
return grammar_creator(validator, grammar_name)
return grammar_dec
else:
# Otherwise we assume that grammar_type is actually the function being
# decorated.
return grammar_creator(grammar_type, grammar_type.__name__) | Decorator to define properties that map to the ``grammar``
dict. This dict is the canonical representation of the Vega grammar
within Vincent.
This decorator is intended for classes that map to some pre-defined JSON
structure, such as axes, data, marks, scales, etc. It is assumed that this
decorates functions with an instance of ``self.grammar``.
Parameters
----------
grammar_type : type or tuple of types, default None
If the argument to the decorated function is not of the given types,
then a ValueError is raised. No type checking is done if the type is
None (default).
grammar_name : string, default None
An optional name to map to the internal ``grammar`` dict. If None
(default), then the key for the dict is the name of the function
being decorated. If not None, then it will be the name specified
here. This is useful if the expected JSON field name is a Python
keyword or has an un-Pythonic name.
This should decorate a "validator" function that should return no value
but raise an exception if the provided value is not valid Vega grammar. If
the validator throws no exception, then the value is assigned to the
``grammar`` dict.
The validator function should take only one argument - the value to be
validated - so that no ``self`` argument is included; the validator
should not modify the class.
If no arguments are given, then no type-checking is done the property
will be mapped to a field with the name of the decorated function.
The doc string for the property is taken from the validator functions's
doc string. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/core.py#L179-L250 |
wrobstory/vincent | vincent/core.py | GrammarClass.validate | def validate(self):
"""Validate the contents of the object.
This calls ``setattr`` for each of the class's grammar properties. It
will catch ``ValueError``s raised by the grammar property's setters
and re-raise them as :class:`ValidationError`.
"""
for key, val in self.grammar.items():
try:
setattr(self, key, val)
except ValueError as e:
raise ValidationError('invalid contents: ' + e.args[0]) | python | def validate(self):
"""Validate the contents of the object.
This calls ``setattr`` for each of the class's grammar properties. It
will catch ``ValueError``s raised by the grammar property's setters
and re-raise them as :class:`ValidationError`.
"""
for key, val in self.grammar.items():
try:
setattr(self, key, val)
except ValueError as e:
raise ValidationError('invalid contents: ' + e.args[0]) | Validate the contents of the object.
This calls ``setattr`` for each of the class's grammar properties. It
will catch ``ValueError``s raised by the grammar property's setters
and re-raise them as :class:`ValidationError`. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/core.py#L302-L313 |
wrobstory/vincent | vincent/core.py | GrammarClass.to_json | def to_json(self, path=None, html_out=False,
html_path='vega_template.html', validate=False,
pretty_print=True):
"""Convert object to JSON
Parameters
----------
path: string, default None
Path to write JSON out. If there is no path provided, JSON
will be returned as a string to the console.
html_out: boolean, default False
If True, vincent will output an simple HTML scaffold to
visualize the vega json output.
html_path: string, default 'vega_template.html'
Path for the html file (if html_out=True)
validate : boolean
If True, call the object's `validate` method before
serializing. Default is False.
pretty_print : boolean
If True (default), JSON is printed in more-readable form with
indentation and spaces.
Returns
-------
string
JSON serialization of the class's grammar properties.
"""
if validate:
self.validate()
if pretty_print:
dumps_args = {'indent': 2, 'separators': (',', ': ')}
else:
dumps_args = {}
def encoder(obj):
if hasattr(obj, 'grammar'):
return obj.grammar
if html_out:
template = Template(
str(resource_string('vincent', 'vega_template.html')))
with open(html_path, 'w') as f:
f.write(template.substitute(path=path))
if path:
with open(path, 'w') as f:
json.dump(self.grammar, f, default=encoder, sort_keys=True,
**dumps_args)
else:
return json.dumps(self.grammar, default=encoder, sort_keys=True,
**dumps_args) | python | def to_json(self, path=None, html_out=False,
html_path='vega_template.html', validate=False,
pretty_print=True):
"""Convert object to JSON
Parameters
----------
path: string, default None
Path to write JSON out. If there is no path provided, JSON
will be returned as a string to the console.
html_out: boolean, default False
If True, vincent will output an simple HTML scaffold to
visualize the vega json output.
html_path: string, default 'vega_template.html'
Path for the html file (if html_out=True)
validate : boolean
If True, call the object's `validate` method before
serializing. Default is False.
pretty_print : boolean
If True (default), JSON is printed in more-readable form with
indentation and spaces.
Returns
-------
string
JSON serialization of the class's grammar properties.
"""
if validate:
self.validate()
if pretty_print:
dumps_args = {'indent': 2, 'separators': (',', ': ')}
else:
dumps_args = {}
def encoder(obj):
if hasattr(obj, 'grammar'):
return obj.grammar
if html_out:
template = Template(
str(resource_string('vincent', 'vega_template.html')))
with open(html_path, 'w') as f:
f.write(template.substitute(path=path))
if path:
with open(path, 'w') as f:
json.dump(self.grammar, f, default=encoder, sort_keys=True,
**dumps_args)
else:
return json.dumps(self.grammar, default=encoder, sort_keys=True,
**dumps_args) | Convert object to JSON
Parameters
----------
path: string, default None
Path to write JSON out. If there is no path provided, JSON
will be returned as a string to the console.
html_out: boolean, default False
If True, vincent will output an simple HTML scaffold to
visualize the vega json output.
html_path: string, default 'vega_template.html'
Path for the html file (if html_out=True)
validate : boolean
If True, call the object's `validate` method before
serializing. Default is False.
pretty_print : boolean
If True (default), JSON is printed in more-readable form with
indentation and spaces.
Returns
-------
string
JSON serialization of the class's grammar properties. | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/core.py#L315-L366 |
alephdata/pantomime | pantomime/__init__.py | useful_mimetype | def useful_mimetype(text):
"""Check to see if the given mime type is a MIME type
which is useful in terms of how to treat this file.
"""
if text is None:
return False
mimetype = normalize_mimetype(text)
return mimetype not in [DEFAULT, PLAIN, None] | python | def useful_mimetype(text):
"""Check to see if the given mime type is a MIME type
which is useful in terms of how to treat this file.
"""
if text is None:
return False
mimetype = normalize_mimetype(text)
return mimetype not in [DEFAULT, PLAIN, None] | Check to see if the given mime type is a MIME type
which is useful in terms of how to treat this file. | https://github.com/alephdata/pantomime/blob/818fe5d799ba045c1d908935f24c94a8438c3a60/pantomime/__init__.py#L19-L26 |
alephdata/pantomime | pantomime/__init__.py | normalize_extension | def normalize_extension(extension):
"""Normalise a file name extension."""
extension = decode_path(extension)
if extension is None:
return
if extension.startswith('.'):
extension = extension[1:]
if '.' in extension:
_, extension = os.path.splitext(extension)
extension = slugify(extension, sep='')
if extension is None:
return
if len(extension):
return extension | python | def normalize_extension(extension):
"""Normalise a file name extension."""
extension = decode_path(extension)
if extension is None:
return
if extension.startswith('.'):
extension = extension[1:]
if '.' in extension:
_, extension = os.path.splitext(extension)
extension = slugify(extension, sep='')
if extension is None:
return
if len(extension):
return extension | Normalise a file name extension. | https://github.com/alephdata/pantomime/blob/818fe5d799ba045c1d908935f24c94a8438c3a60/pantomime/__init__.py#L29-L42 |
alphardex/looter | looter/__init__.py | fetch | def fetch(url: str, **kwargs) -> Selector:
"""
Send HTTP request and parse it as a DOM tree.
Args:
url (str): The url of the site.
Returns:
Selector: allows you to select parts of HTML text using CSS or XPath expressions.
"""
kwargs.setdefault('headers', DEFAULT_HEADERS)
try:
res = requests.get(url, **kwargs)
res.raise_for_status()
except requests.RequestException as e:
print(e)
else:
html = res.text
tree = Selector(text=html)
return tree | python | def fetch(url: str, **kwargs) -> Selector:
"""
Send HTTP request and parse it as a DOM tree.
Args:
url (str): The url of the site.
Returns:
Selector: allows you to select parts of HTML text using CSS or XPath expressions.
"""
kwargs.setdefault('headers', DEFAULT_HEADERS)
try:
res = requests.get(url, **kwargs)
res.raise_for_status()
except requests.RequestException as e:
print(e)
else:
html = res.text
tree = Selector(text=html)
return tree | Send HTTP request and parse it as a DOM tree.
Args:
url (str): The url of the site.
Returns:
Selector: allows you to select parts of HTML text using CSS or XPath expressions. | https://github.com/alphardex/looter/blob/47fb7e44fe39c8528c1d6be94791798660d8804e/looter/__init__.py#L60-L79 |
alphardex/looter | looter/__init__.py | async_fetch | async def async_fetch(url: str, **kwargs) -> Selector:
"""
Do the fetch in an async style.
Args:
url (str): The url of the site.
Returns:
Selector: allows you to select parts of HTML text using CSS or XPath expressions.
"""
kwargs.setdefault('headers', DEFAULT_HEADERS)
async with aiohttp.ClientSession(**kwargs) as ses:
async with ses.get(url, **kwargs) as res:
html = await res.text()
tree = Selector(text=html)
return tree | python | async def async_fetch(url: str, **kwargs) -> Selector:
"""
Do the fetch in an async style.
Args:
url (str): The url of the site.
Returns:
Selector: allows you to select parts of HTML text using CSS or XPath expressions.
"""
kwargs.setdefault('headers', DEFAULT_HEADERS)
async with aiohttp.ClientSession(**kwargs) as ses:
async with ses.get(url, **kwargs) as res:
html = await res.text()
tree = Selector(text=html)
return tree | Do the fetch in an async style.
Args:
url (str): The url of the site.
Returns:
Selector: allows you to select parts of HTML text using CSS or XPath expressions. | https://github.com/alphardex/looter/blob/47fb7e44fe39c8528c1d6be94791798660d8804e/looter/__init__.py#L82-L97 |
alphardex/looter | looter/__init__.py | view | def view(url: str, **kwargs) -> bool:
"""
View the page whether rendered properly. (ensure the <base> tag to make external links work)
Args:
url (str): The url of the site.
"""
kwargs.setdefault('headers', DEFAULT_HEADERS)
html = requests.get(url, **kwargs).content
if b'<base' not in html:
repl = f'<head><base href="{url}">'
html = html.replace(b'<head>', repl.encode('utf-8'))
fd, fname = tempfile.mkstemp('.html')
os.write(fd, html)
os.close(fd)
return webbrowser.open(f'file://{fname}') | python | def view(url: str, **kwargs) -> bool:
"""
View the page whether rendered properly. (ensure the <base> tag to make external links work)
Args:
url (str): The url of the site.
"""
kwargs.setdefault('headers', DEFAULT_HEADERS)
html = requests.get(url, **kwargs).content
if b'<base' not in html:
repl = f'<head><base href="{url}">'
html = html.replace(b'<head>', repl.encode('utf-8'))
fd, fname = tempfile.mkstemp('.html')
os.write(fd, html)
os.close(fd)
return webbrowser.open(f'file://{fname}') | View the page whether rendered properly. (ensure the <base> tag to make external links work)
Args:
url (str): The url of the site. | https://github.com/alphardex/looter/blob/47fb7e44fe39c8528c1d6be94791798660d8804e/looter/__init__.py#L100-L115 |
alphardex/looter | looter/__init__.py | links | def links(res: requests.models.Response,
search: str = None,
pattern: str = None) -> list:
"""Get the links of the page.
Args:
res (requests.models.Response): The response of the page.
search (str, optional): Defaults to None. Search the links you want.
pattern (str, optional): Defaults to None. Search the links use a regex pattern.
Returns:
list: All the links of the page.
"""
hrefs = [link.to_text() for link in find_all_links(res.text)]
if search:
hrefs = [href for href in hrefs if search in href]
if pattern:
hrefs = [href for href in hrefs if re.findall(pattern, href)]
return list(set(hrefs)) | python | def links(res: requests.models.Response,
search: str = None,
pattern: str = None) -> list:
"""Get the links of the page.
Args:
res (requests.models.Response): The response of the page.
search (str, optional): Defaults to None. Search the links you want.
pattern (str, optional): Defaults to None. Search the links use a regex pattern.
Returns:
list: All the links of the page.
"""
hrefs = [link.to_text() for link in find_all_links(res.text)]
if search:
hrefs = [href for href in hrefs if search in href]
if pattern:
hrefs = [href for href in hrefs if re.findall(pattern, href)]
return list(set(hrefs)) | Get the links of the page.
Args:
res (requests.models.Response): The response of the page.
search (str, optional): Defaults to None. Search the links you want.
pattern (str, optional): Defaults to None. Search the links use a regex pattern.
Returns:
list: All the links of the page. | https://github.com/alphardex/looter/blob/47fb7e44fe39c8528c1d6be94791798660d8804e/looter/__init__.py#L118-L136 |
alphardex/looter | looter/__init__.py | save_as_json | def save_as_json(total: list,
name='data.json',
sort_by: str = None,
no_duplicate=False,
order='asc'):
"""Save what you crawled as a json file.
Args:
total (list): Total of data you crawled.
name (str, optional): Defaults to 'data.json'. The name of the file.
sort_by (str, optional): Defaults to None. Sort items by a specific key.
no_duplicate (bool, optional): Defaults to False. If True, it will remove duplicated data.
order (str, optional): Defaults to 'asc'. The opposite option is 'desc'.
"""
if sort_by:
reverse = order == 'desc'
total = sorted(total, key=itemgetter(sort_by), reverse=reverse)
if no_duplicate:
total = [key for key, _ in groupby(total)]
data = json.dumps(total, ensure_ascii=False)
Path(name).write_text(data, encoding='utf-8') | python | def save_as_json(total: list,
name='data.json',
sort_by: str = None,
no_duplicate=False,
order='asc'):
"""Save what you crawled as a json file.
Args:
total (list): Total of data you crawled.
name (str, optional): Defaults to 'data.json'. The name of the file.
sort_by (str, optional): Defaults to None. Sort items by a specific key.
no_duplicate (bool, optional): Defaults to False. If True, it will remove duplicated data.
order (str, optional): Defaults to 'asc'. The opposite option is 'desc'.
"""
if sort_by:
reverse = order == 'desc'
total = sorted(total, key=itemgetter(sort_by), reverse=reverse)
if no_duplicate:
total = [key for key, _ in groupby(total)]
data = json.dumps(total, ensure_ascii=False)
Path(name).write_text(data, encoding='utf-8') | Save what you crawled as a json file.
Args:
total (list): Total of data you crawled.
name (str, optional): Defaults to 'data.json'. The name of the file.
sort_by (str, optional): Defaults to None. Sort items by a specific key.
no_duplicate (bool, optional): Defaults to False. If True, it will remove duplicated data.
order (str, optional): Defaults to 'asc'. The opposite option is 'desc'. | https://github.com/alphardex/looter/blob/47fb7e44fe39c8528c1d6be94791798660d8804e/looter/__init__.py#L139-L159 |
alphardex/looter | looter/__init__.py | cli | def cli():
"""
Commandline for looter :d
"""
argv = docopt(__doc__, version=VERSION)
if argv['genspider']:
name = f"{argv['<name>']}.py"
use_async = argv['--async']
template = 'data_async.tmpl' if use_async else 'data.tmpl'
package_dir = Path(__file__).parent
template_text = package_dir.joinpath('templates', template).read_text()
Path(name).write_text(template_text)
if argv['shell']:
url = argv['<url>'] if argv['<url>'] else input(
'Plz specific a site to crawl\nurl: ')
res = requests.get(url, headers=DEFAULT_HEADERS)
if not res:
exit('Failed to fetch the page.')
tree = Selector(text=res.text)
allvars = {**locals(), **globals()}
try:
from ptpython.repl import embed
print(BANNER)
embed(allvars)
except ImportError:
code.interact(local=allvars, banner=BANNER) | python | def cli():
"""
Commandline for looter :d
"""
argv = docopt(__doc__, version=VERSION)
if argv['genspider']:
name = f"{argv['<name>']}.py"
use_async = argv['--async']
template = 'data_async.tmpl' if use_async else 'data.tmpl'
package_dir = Path(__file__).parent
template_text = package_dir.joinpath('templates', template).read_text()
Path(name).write_text(template_text)
if argv['shell']:
url = argv['<url>'] if argv['<url>'] else input(
'Plz specific a site to crawl\nurl: ')
res = requests.get(url, headers=DEFAULT_HEADERS)
if not res:
exit('Failed to fetch the page.')
tree = Selector(text=res.text)
allvars = {**locals(), **globals()}
try:
from ptpython.repl import embed
print(BANNER)
embed(allvars)
except ImportError:
code.interact(local=allvars, banner=BANNER) | Commandline for looter :d | https://github.com/alphardex/looter/blob/47fb7e44fe39c8528c1d6be94791798660d8804e/looter/__init__.py#L162-L187 |
gtaylor/python-colormath | colormath/color_objects.py | ColorBase.get_value_tuple | def get_value_tuple(self):
"""
Returns a tuple of the color's values (in order). For example,
an LabColor object will return (lab_l, lab_a, lab_b), where each
member of the tuple is the float value for said variable.
"""
retval = tuple()
for val in self.VALUES:
retval += (getattr(self, val),)
return retval | python | def get_value_tuple(self):
"""
Returns a tuple of the color's values (in order). For example,
an LabColor object will return (lab_l, lab_a, lab_b), where each
member of the tuple is the float value for said variable.
"""
retval = tuple()
for val in self.VALUES:
retval += (getattr(self, val),)
return retval | Returns a tuple of the color's values (in order). For example,
an LabColor object will return (lab_l, lab_a, lab_b), where each
member of the tuple is the float value for said variable. | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_objects.py#L32-L41 |
gtaylor/python-colormath | colormath/color_objects.py | IlluminantMixin.set_observer | def set_observer(self, observer):
"""
Validates and sets the color's observer angle.
.. note:: This only changes the observer angle value. It does no conversion
of the color's coordinates.
:param str observer: One of '2' or '10'.
"""
observer = str(observer)
if observer not in color_constants.OBSERVERS:
raise InvalidObserverError(self)
self.observer = observer | python | def set_observer(self, observer):
"""
Validates and sets the color's observer angle.
.. note:: This only changes the observer angle value. It does no conversion
of the color's coordinates.
:param str observer: One of '2' or '10'.
"""
observer = str(observer)
if observer not in color_constants.OBSERVERS:
raise InvalidObserverError(self)
self.observer = observer | Validates and sets the color's observer angle.
.. note:: This only changes the observer angle value. It does no conversion
of the color's coordinates.
:param str observer: One of '2' or '10'. | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_objects.py#L71-L83 |
gtaylor/python-colormath | colormath/color_objects.py | IlluminantMixin.set_illuminant | def set_illuminant(self, illuminant):
"""
Validates and sets the color's illuminant.
.. note:: This only changes the illuminant. It does no conversion
of the color's coordinates. For this, you'll want to refer to
:py:meth:`XYZColor.apply_adaptation <colormath.color_objects.XYZColor.apply_adaptation>`.
.. tip:: Call this after setting your observer.
:param str illuminant: One of the various illuminants.
"""
illuminant = illuminant.lower()
if illuminant not in color_constants.ILLUMINANTS[self.observer]:
raise InvalidIlluminantError(illuminant)
self.illuminant = illuminant | python | def set_illuminant(self, illuminant):
"""
Validates and sets the color's illuminant.
.. note:: This only changes the illuminant. It does no conversion
of the color's coordinates. For this, you'll want to refer to
:py:meth:`XYZColor.apply_adaptation <colormath.color_objects.XYZColor.apply_adaptation>`.
.. tip:: Call this after setting your observer.
:param str illuminant: One of the various illuminants.
"""
illuminant = illuminant.lower()
if illuminant not in color_constants.ILLUMINANTS[self.observer]:
raise InvalidIlluminantError(illuminant)
self.illuminant = illuminant | Validates and sets the color's illuminant.
.. note:: This only changes the illuminant. It does no conversion
of the color's coordinates. For this, you'll want to refer to
:py:meth:`XYZColor.apply_adaptation <colormath.color_objects.XYZColor.apply_adaptation>`.
.. tip:: Call this after setting your observer.
:param str illuminant: One of the various illuminants. | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_objects.py#L86-L101 |
gtaylor/python-colormath | colormath/color_objects.py | IlluminantMixin.get_illuminant_xyz | def get_illuminant_xyz(self, observer=None, illuminant=None):
"""
:param str observer: Get the XYZ values for another observer angle. Must
be either '2' or '10'.
:param str illuminant: Get the XYZ values for another illuminant.
:returns: the color's illuminant's XYZ values.
"""
try:
if observer is None:
observer = self.observer
illums_observer = color_constants.ILLUMINANTS[observer]
except KeyError:
raise InvalidObserverError(self)
try:
if illuminant is None:
illuminant = self.illuminant
illum_xyz = illums_observer[illuminant]
except (KeyError, AttributeError):
raise InvalidIlluminantError(illuminant)
return {'X': illum_xyz[0], 'Y': illum_xyz[1], 'Z': illum_xyz[2]} | python | def get_illuminant_xyz(self, observer=None, illuminant=None):
"""
:param str observer: Get the XYZ values for another observer angle. Must
be either '2' or '10'.
:param str illuminant: Get the XYZ values for another illuminant.
:returns: the color's illuminant's XYZ values.
"""
try:
if observer is None:
observer = self.observer
illums_observer = color_constants.ILLUMINANTS[observer]
except KeyError:
raise InvalidObserverError(self)
try:
if illuminant is None:
illuminant = self.illuminant
illum_xyz = illums_observer[illuminant]
except (KeyError, AttributeError):
raise InvalidIlluminantError(illuminant)
return {'X': illum_xyz[0], 'Y': illum_xyz[1], 'Z': illum_xyz[2]} | :param str observer: Get the XYZ values for another observer angle. Must
be either '2' or '10'.
:param str illuminant: Get the XYZ values for another illuminant.
:returns: the color's illuminant's XYZ values. | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_objects.py#L103-L126 |
gtaylor/python-colormath | colormath/color_objects.py | SpectralColor.get_numpy_array | def get_numpy_array(self):
"""
Dump this color into NumPy array.
"""
# This holds the obect's spectral data, and will be passed to
# numpy.array() to create a numpy array (matrix) for the matrix math
# that will be done during the conversion to XYZ.
values = []
# Use the required value list to build this dynamically. Default to
# 0.0, since that ultimately won't affect the outcome due to the math
# involved.
for val in self.VALUES:
values.append(getattr(self, val, 0.0))
# Create and the actual numpy array/matrix from the spectral list.
color_array = numpy.array([values])
return color_array | python | def get_numpy_array(self):
"""
Dump this color into NumPy array.
"""
# This holds the obect's spectral data, and will be passed to
# numpy.array() to create a numpy array (matrix) for the matrix math
# that will be done during the conversion to XYZ.
values = []
# Use the required value list to build this dynamically. Default to
# 0.0, since that ultimately won't affect the outcome due to the math
# involved.
for val in self.VALUES:
values.append(getattr(self, val, 0.0))
# Create and the actual numpy array/matrix from the spectral list.
color_array = numpy.array([values])
return color_array | Dump this color into NumPy array. | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_objects.py#L245-L262 |
gtaylor/python-colormath | colormath/color_objects.py | SpectralColor.calc_density | def calc_density(self, density_standard=None):
"""
Calculates the density of the SpectralColor. By default, Status T
density is used, and the correct density distribution (Red, Green,
or Blue) is chosen by comparing the Red, Green, and Blue components of
the spectral sample (the values being red in via "filters").
"""
if density_standard is not None:
return density.ansi_density(self, density_standard)
else:
return density.auto_density(self) | python | def calc_density(self, density_standard=None):
"""
Calculates the density of the SpectralColor. By default, Status T
density is used, and the correct density distribution (Red, Green,
or Blue) is chosen by comparing the Red, Green, and Blue components of
the spectral sample (the values being red in via "filters").
"""
if density_standard is not None:
return density.ansi_density(self, density_standard)
else:
return density.auto_density(self) | Calculates the density of the SpectralColor. By default, Status T
density is used, and the correct density distribution (Red, Green,
or Blue) is chosen by comparing the Red, Green, and Blue components of
the spectral sample (the values being red in via "filters"). | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_objects.py#L264-L274 |
gtaylor/python-colormath | colormath/color_objects.py | XYZColor.apply_adaptation | def apply_adaptation(self, target_illuminant, adaptation='bradford'):
"""
This applies an adaptation matrix to change the XYZ color's illuminant.
You'll most likely only need this during RGB conversions.
"""
logger.debug(" \- Original illuminant: %s", self.illuminant)
logger.debug(" \- Target illuminant: %s", target_illuminant)
# If the XYZ values were taken with a different reference white than the
# native reference white of the target RGB space, a transformation matrix
# must be applied.
if self.illuminant != target_illuminant:
logger.debug(" \* Applying transformation from %s to %s ",
self.illuminant, target_illuminant)
# Sets the adjusted XYZ values, and the new illuminant.
apply_chromatic_adaptation_on_color(
color=self,
targ_illum=target_illuminant,
adaptation=adaptation) | python | def apply_adaptation(self, target_illuminant, adaptation='bradford'):
"""
This applies an adaptation matrix to change the XYZ color's illuminant.
You'll most likely only need this during RGB conversions.
"""
logger.debug(" \- Original illuminant: %s", self.illuminant)
logger.debug(" \- Target illuminant: %s", target_illuminant)
# If the XYZ values were taken with a different reference white than the
# native reference white of the target RGB space, a transformation matrix
# must be applied.
if self.illuminant != target_illuminant:
logger.debug(" \* Applying transformation from %s to %s ",
self.illuminant, target_illuminant)
# Sets the adjusted XYZ values, and the new illuminant.
apply_chromatic_adaptation_on_color(
color=self,
targ_illum=target_illuminant,
adaptation=adaptation) | This applies an adaptation matrix to change the XYZ color's illuminant.
You'll most likely only need this during RGB conversions. | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_objects.py#L448-L466 |
gtaylor/python-colormath | colormath/color_objects.py | BaseRGBColor._clamp_rgb_coordinate | def _clamp_rgb_coordinate(self, coord):
"""
Clamps an RGB coordinate, taking into account whether or not the
color is upscaled or not.
:param float coord: The coordinate value.
:rtype: float
:returns: The clamped value.
"""
if not self.is_upscaled:
return min(max(coord, 0.0), 1.0)
else:
return min(max(coord, 1), 255) | python | def _clamp_rgb_coordinate(self, coord):
"""
Clamps an RGB coordinate, taking into account whether or not the
color is upscaled or not.
:param float coord: The coordinate value.
:rtype: float
:returns: The clamped value.
"""
if not self.is_upscaled:
return min(max(coord, 0.0), 1.0)
else:
return min(max(coord, 1), 255) | Clamps an RGB coordinate, taking into account whether or not the
color is upscaled or not.
:param float coord: The coordinate value.
:rtype: float
:returns: The clamped value. | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_objects.py#L530-L542 |
gtaylor/python-colormath | colormath/color_objects.py | BaseRGBColor.get_upscaled_value_tuple | def get_upscaled_value_tuple(self):
"""
Scales an RGB color object from decimal 0.0-1.0 to int 0-255.
"""
# Scale up to 0-255 values.
rgb_r = int(math.floor(0.5 + self.rgb_r * 255))
rgb_g = int(math.floor(0.5 + self.rgb_g * 255))
rgb_b = int(math.floor(0.5 + self.rgb_b * 255))
return rgb_r, rgb_g, rgb_b | python | def get_upscaled_value_tuple(self):
"""
Scales an RGB color object from decimal 0.0-1.0 to int 0-255.
"""
# Scale up to 0-255 values.
rgb_r = int(math.floor(0.5 + self.rgb_r * 255))
rgb_g = int(math.floor(0.5 + self.rgb_g * 255))
rgb_b = int(math.floor(0.5 + self.rgb_b * 255))
return rgb_r, rgb_g, rgb_b | Scales an RGB color object from decimal 0.0-1.0 to int 0-255. | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_objects.py#L565-L574 |
gtaylor/python-colormath | colormath/color_objects.py | BaseRGBColor.get_rgb_hex | def get_rgb_hex(self):
"""
Converts the RGB value to a hex value in the form of: #RRGGBB
:rtype: str
"""
rgb_r, rgb_g, rgb_b = self.get_upscaled_value_tuple()
return '#%02x%02x%02x' % (rgb_r, rgb_g, rgb_b) | python | def get_rgb_hex(self):
"""
Converts the RGB value to a hex value in the form of: #RRGGBB
:rtype: str
"""
rgb_r, rgb_g, rgb_b = self.get_upscaled_value_tuple()
return '#%02x%02x%02x' % (rgb_r, rgb_g, rgb_b) | Converts the RGB value to a hex value in the form of: #RRGGBB
:rtype: str | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_objects.py#L576-L583 |
gtaylor/python-colormath | colormath/color_objects.py | BaseRGBColor.new_from_rgb_hex | def new_from_rgb_hex(cls, hex_str):
"""
Converts an RGB hex string like #RRGGBB and assigns the values to
this sRGBColor object.
:rtype: sRGBColor
"""
colorstring = hex_str.strip()
if colorstring[0] == '#':
colorstring = colorstring[1:]
if len(colorstring) != 6:
raise ValueError("input #%s is not in #RRGGBB format" % colorstring)
r, g, b = colorstring[:2], colorstring[2:4], colorstring[4:]
r, g, b = [int(n, 16) / 255.0 for n in (r, g, b)]
return cls(r, g, b) | python | def new_from_rgb_hex(cls, hex_str):
"""
Converts an RGB hex string like #RRGGBB and assigns the values to
this sRGBColor object.
:rtype: sRGBColor
"""
colorstring = hex_str.strip()
if colorstring[0] == '#':
colorstring = colorstring[1:]
if len(colorstring) != 6:
raise ValueError("input #%s is not in #RRGGBB format" % colorstring)
r, g, b = colorstring[:2], colorstring[2:4], colorstring[4:]
r, g, b = [int(n, 16) / 255.0 for n in (r, g, b)]
return cls(r, g, b) | Converts an RGB hex string like #RRGGBB and assigns the values to
this sRGBColor object.
:rtype: sRGBColor | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_objects.py#L586-L600 |
gtaylor/python-colormath | colormath/color_diff_matrix.py | delta_e_cie1976 | def delta_e_cie1976(lab_color_vector, lab_color_matrix):
"""
Calculates the Delta E (CIE1976) between `lab_color_vector` and all
colors in `lab_color_matrix`.
"""
return numpy.sqrt(
numpy.sum(numpy.power(lab_color_vector - lab_color_matrix, 2), axis=1)) | python | def delta_e_cie1976(lab_color_vector, lab_color_matrix):
"""
Calculates the Delta E (CIE1976) between `lab_color_vector` and all
colors in `lab_color_matrix`.
"""
return numpy.sqrt(
numpy.sum(numpy.power(lab_color_vector - lab_color_matrix, 2), axis=1)) | Calculates the Delta E (CIE1976) between `lab_color_vector` and all
colors in `lab_color_matrix`. | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_diff_matrix.py#L11-L17 |
gtaylor/python-colormath | colormath/color_diff_matrix.py | delta_e_cie1994 | def delta_e_cie1994(lab_color_vector, lab_color_matrix,
K_L=1, K_C=1, K_H=1, K_1=0.045, K_2=0.015):
"""
Calculates the Delta E (CIE1994) of two colors.
K_l:
0.045 graphic arts
0.048 textiles
K_2:
0.015 graphic arts
0.014 textiles
K_L:
1 default
2 textiles
"""
C_1 = numpy.sqrt(numpy.sum(numpy.power(lab_color_vector[1:], 2)))
C_2 = numpy.sqrt(numpy.sum(numpy.power(lab_color_matrix[:, 1:], 2), axis=1))
delta_lab = lab_color_vector - lab_color_matrix
delta_L = delta_lab[:, 0].copy()
delta_C = C_1 - C_2
delta_lab[:, 0] = delta_C
delta_H_sq = numpy.sum(numpy.power(delta_lab, 2) * numpy.array([-1, 1, 1]), axis=1)
# noinspection PyArgumentList
delta_H = numpy.sqrt(delta_H_sq.clip(min=0))
S_L = 1
S_C = 1 + K_1 * C_1
S_H = 1 + K_2 * C_1
LCH = numpy.vstack([delta_L, delta_C, delta_H])
params = numpy.array([[K_L * S_L], [K_C * S_C], [K_H * S_H]])
return numpy.sqrt(numpy.sum(numpy.power(LCH / params, 2), axis=0)) | python | def delta_e_cie1994(lab_color_vector, lab_color_matrix,
K_L=1, K_C=1, K_H=1, K_1=0.045, K_2=0.015):
"""
Calculates the Delta E (CIE1994) of two colors.
K_l:
0.045 graphic arts
0.048 textiles
K_2:
0.015 graphic arts
0.014 textiles
K_L:
1 default
2 textiles
"""
C_1 = numpy.sqrt(numpy.sum(numpy.power(lab_color_vector[1:], 2)))
C_2 = numpy.sqrt(numpy.sum(numpy.power(lab_color_matrix[:, 1:], 2), axis=1))
delta_lab = lab_color_vector - lab_color_matrix
delta_L = delta_lab[:, 0].copy()
delta_C = C_1 - C_2
delta_lab[:, 0] = delta_C
delta_H_sq = numpy.sum(numpy.power(delta_lab, 2) * numpy.array([-1, 1, 1]), axis=1)
# noinspection PyArgumentList
delta_H = numpy.sqrt(delta_H_sq.clip(min=0))
S_L = 1
S_C = 1 + K_1 * C_1
S_H = 1 + K_2 * C_1
LCH = numpy.vstack([delta_L, delta_C, delta_H])
params = numpy.array([[K_L * S_L], [K_C * S_C], [K_H * S_H]])
return numpy.sqrt(numpy.sum(numpy.power(LCH / params, 2), axis=0)) | Calculates the Delta E (CIE1994) of two colors.
K_l:
0.045 graphic arts
0.048 textiles
K_2:
0.015 graphic arts
0.014 textiles
K_L:
1 default
2 textiles | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_diff_matrix.py#L21-L56 |
gtaylor/python-colormath | colormath/color_diff_matrix.py | delta_e_cmc | def delta_e_cmc(lab_color_vector, lab_color_matrix, pl=2, pc=1):
"""
Calculates the Delta E (CIE1994) of two colors.
CMC values
Acceptability: pl=2, pc=1
Perceptability: pl=1, pc=1
"""
L, a, b = lab_color_vector
C_1 = numpy.sqrt(numpy.sum(numpy.power(lab_color_vector[1:], 2)))
C_2 = numpy.sqrt(numpy.sum(numpy.power(lab_color_matrix[:, 1:], 2), axis=1))
delta_lab = lab_color_vector - lab_color_matrix
delta_L = delta_lab[:, 0].copy()
delta_C = C_1 - C_2
delta_lab[:, 0] = delta_C
H_1 = numpy.degrees(numpy.arctan2(b, a))
if H_1 < 0:
H_1 += 360
F = numpy.sqrt(numpy.power(C_1, 4) / (numpy.power(C_1, 4) + 1900.0))
# noinspection PyChainedComparisons
if 164 <= H_1 and H_1 <= 345:
T = 0.56 + abs(0.2 * numpy.cos(numpy.radians(H_1 + 168)))
else:
T = 0.36 + abs(0.4 * numpy.cos(numpy.radians(H_1 + 35)))
if L < 16:
S_L = 0.511
else:
S_L = (0.040975 * L) / (1 + 0.01765 * L)
S_C = ((0.0638 * C_1) / (1 + 0.0131 * C_1)) + 0.638
S_H = S_C * (F * T + 1 - F)
delta_C = C_1 - C_2
delta_H_sq = numpy.sum(numpy.power(delta_lab, 2) * numpy.array([-1, 1, 1]), axis=1)
# noinspection PyArgumentList
delta_H = numpy.sqrt(delta_H_sq.clip(min=0))
LCH = numpy.vstack([delta_L, delta_C, delta_H])
params = numpy.array([[pl * S_L], [pc * S_C], [S_H]])
return numpy.sqrt(numpy.sum(numpy.power(LCH / params, 2), axis=0)) | python | def delta_e_cmc(lab_color_vector, lab_color_matrix, pl=2, pc=1):
"""
Calculates the Delta E (CIE1994) of two colors.
CMC values
Acceptability: pl=2, pc=1
Perceptability: pl=1, pc=1
"""
L, a, b = lab_color_vector
C_1 = numpy.sqrt(numpy.sum(numpy.power(lab_color_vector[1:], 2)))
C_2 = numpy.sqrt(numpy.sum(numpy.power(lab_color_matrix[:, 1:], 2), axis=1))
delta_lab = lab_color_vector - lab_color_matrix
delta_L = delta_lab[:, 0].copy()
delta_C = C_1 - C_2
delta_lab[:, 0] = delta_C
H_1 = numpy.degrees(numpy.arctan2(b, a))
if H_1 < 0:
H_1 += 360
F = numpy.sqrt(numpy.power(C_1, 4) / (numpy.power(C_1, 4) + 1900.0))
# noinspection PyChainedComparisons
if 164 <= H_1 and H_1 <= 345:
T = 0.56 + abs(0.2 * numpy.cos(numpy.radians(H_1 + 168)))
else:
T = 0.36 + abs(0.4 * numpy.cos(numpy.radians(H_1 + 35)))
if L < 16:
S_L = 0.511
else:
S_L = (0.040975 * L) / (1 + 0.01765 * L)
S_C = ((0.0638 * C_1) / (1 + 0.0131 * C_1)) + 0.638
S_H = S_C * (F * T + 1 - F)
delta_C = C_1 - C_2
delta_H_sq = numpy.sum(numpy.power(delta_lab, 2) * numpy.array([-1, 1, 1]), axis=1)
# noinspection PyArgumentList
delta_H = numpy.sqrt(delta_H_sq.clip(min=0))
LCH = numpy.vstack([delta_L, delta_C, delta_H])
params = numpy.array([[pl * S_L], [pc * S_C], [S_H]])
return numpy.sqrt(numpy.sum(numpy.power(LCH / params, 2), axis=0)) | Calculates the Delta E (CIE1994) of two colors.
CMC values
Acceptability: pl=2, pc=1
Perceptability: pl=1, pc=1 | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_diff_matrix.py#L60-L109 |
gtaylor/python-colormath | colormath/color_diff_matrix.py | delta_e_cie2000 | def delta_e_cie2000(lab_color_vector, lab_color_matrix, Kl=1, Kc=1, Kh=1):
"""
Calculates the Delta E (CIE2000) of two colors.
"""
L, a, b = lab_color_vector
avg_Lp = (L + lab_color_matrix[:, 0]) / 2.0
C1 = numpy.sqrt(numpy.sum(numpy.power(lab_color_vector[1:], 2)))
C2 = numpy.sqrt(numpy.sum(numpy.power(lab_color_matrix[:, 1:], 2), axis=1))
avg_C1_C2 = (C1 + C2) / 2.0
G = 0.5 * (1 - numpy.sqrt(numpy.power(avg_C1_C2, 7.0) / (numpy.power(avg_C1_C2, 7.0) + numpy.power(25.0, 7.0))))
a1p = (1.0 + G) * a
a2p = (1.0 + G) * lab_color_matrix[:, 1]
C1p = numpy.sqrt(numpy.power(a1p, 2) + numpy.power(b, 2))
C2p = numpy.sqrt(numpy.power(a2p, 2) + numpy.power(lab_color_matrix[:, 2], 2))
avg_C1p_C2p = (C1p + C2p) / 2.0
h1p = numpy.degrees(numpy.arctan2(b, a1p))
h1p += (h1p < 0) * 360
h2p = numpy.degrees(numpy.arctan2(lab_color_matrix[:, 2], a2p))
h2p += (h2p < 0) * 360
avg_Hp = (((numpy.fabs(h1p - h2p) > 180) * 360) + h1p + h2p) / 2.0
T = 1 - 0.17 * numpy.cos(numpy.radians(avg_Hp - 30)) + \
0.24 * numpy.cos(numpy.radians(2 * avg_Hp)) + \
0.32 * numpy.cos(numpy.radians(3 * avg_Hp + 6)) - \
0.2 * numpy.cos(numpy.radians(4 * avg_Hp - 63))
diff_h2p_h1p = h2p - h1p
delta_hp = diff_h2p_h1p + (numpy.fabs(diff_h2p_h1p) > 180) * 360
delta_hp -= (h2p > h1p) * 720
delta_Lp = lab_color_matrix[:, 0] - L
delta_Cp = C2p - C1p
delta_Hp = 2 * numpy.sqrt(C2p * C1p) * numpy.sin(numpy.radians(delta_hp) / 2.0)
S_L = 1 + ((0.015 * numpy.power(avg_Lp - 50, 2)) / numpy.sqrt(20 + numpy.power(avg_Lp - 50, 2.0)))
S_C = 1 + 0.045 * avg_C1p_C2p
S_H = 1 + 0.015 * avg_C1p_C2p * T
delta_ro = 30 * numpy.exp(-(numpy.power(((avg_Hp - 275) / 25), 2.0)))
R_C = numpy.sqrt((numpy.power(avg_C1p_C2p, 7.0)) / (numpy.power(avg_C1p_C2p, 7.0) + numpy.power(25.0, 7.0)))
R_T = -2 * R_C * numpy.sin(2 * numpy.radians(delta_ro))
return numpy.sqrt(
numpy.power(delta_Lp / (S_L * Kl), 2) +
numpy.power(delta_Cp / (S_C * Kc), 2) +
numpy.power(delta_Hp / (S_H * Kh), 2) +
R_T * (delta_Cp / (S_C * Kc)) * (delta_Hp / (S_H * Kh))) | python | def delta_e_cie2000(lab_color_vector, lab_color_matrix, Kl=1, Kc=1, Kh=1):
"""
Calculates the Delta E (CIE2000) of two colors.
"""
L, a, b = lab_color_vector
avg_Lp = (L + lab_color_matrix[:, 0]) / 2.0
C1 = numpy.sqrt(numpy.sum(numpy.power(lab_color_vector[1:], 2)))
C2 = numpy.sqrt(numpy.sum(numpy.power(lab_color_matrix[:, 1:], 2), axis=1))
avg_C1_C2 = (C1 + C2) / 2.0
G = 0.5 * (1 - numpy.sqrt(numpy.power(avg_C1_C2, 7.0) / (numpy.power(avg_C1_C2, 7.0) + numpy.power(25.0, 7.0))))
a1p = (1.0 + G) * a
a2p = (1.0 + G) * lab_color_matrix[:, 1]
C1p = numpy.sqrt(numpy.power(a1p, 2) + numpy.power(b, 2))
C2p = numpy.sqrt(numpy.power(a2p, 2) + numpy.power(lab_color_matrix[:, 2], 2))
avg_C1p_C2p = (C1p + C2p) / 2.0
h1p = numpy.degrees(numpy.arctan2(b, a1p))
h1p += (h1p < 0) * 360
h2p = numpy.degrees(numpy.arctan2(lab_color_matrix[:, 2], a2p))
h2p += (h2p < 0) * 360
avg_Hp = (((numpy.fabs(h1p - h2p) > 180) * 360) + h1p + h2p) / 2.0
T = 1 - 0.17 * numpy.cos(numpy.radians(avg_Hp - 30)) + \
0.24 * numpy.cos(numpy.radians(2 * avg_Hp)) + \
0.32 * numpy.cos(numpy.radians(3 * avg_Hp + 6)) - \
0.2 * numpy.cos(numpy.radians(4 * avg_Hp - 63))
diff_h2p_h1p = h2p - h1p
delta_hp = diff_h2p_h1p + (numpy.fabs(diff_h2p_h1p) > 180) * 360
delta_hp -= (h2p > h1p) * 720
delta_Lp = lab_color_matrix[:, 0] - L
delta_Cp = C2p - C1p
delta_Hp = 2 * numpy.sqrt(C2p * C1p) * numpy.sin(numpy.radians(delta_hp) / 2.0)
S_L = 1 + ((0.015 * numpy.power(avg_Lp - 50, 2)) / numpy.sqrt(20 + numpy.power(avg_Lp - 50, 2.0)))
S_C = 1 + 0.045 * avg_C1p_C2p
S_H = 1 + 0.015 * avg_C1p_C2p * T
delta_ro = 30 * numpy.exp(-(numpy.power(((avg_Hp - 275) / 25), 2.0)))
R_C = numpy.sqrt((numpy.power(avg_C1p_C2p, 7.0)) / (numpy.power(avg_C1p_C2p, 7.0) + numpy.power(25.0, 7.0)))
R_T = -2 * R_C * numpy.sin(2 * numpy.radians(delta_ro))
return numpy.sqrt(
numpy.power(delta_Lp / (S_L * Kl), 2) +
numpy.power(delta_Cp / (S_C * Kc), 2) +
numpy.power(delta_Hp / (S_H * Kh), 2) +
R_T * (delta_Cp / (S_C * Kc)) * (delta_Hp / (S_H * Kh))) | Calculates the Delta E (CIE2000) of two colors. | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_diff_matrix.py#L113-L169 |
gtaylor/python-colormath | colormath/density.py | ansi_density | def ansi_density(color, density_standard):
"""
Calculates density for the given SpectralColor using the spectral weighting
function provided. For example, ANSI_STATUS_T_RED. These may be found in
:py:mod:`colormath.density_standards`.
:param SpectralColor color: The SpectralColor object to calculate
density for.
:param numpy.ndarray density_standard: NumPy array of filter of choice
from :py:mod:`colormath.density_standards`.
:rtype: float
:returns: The density value for the given color and density standard.
"""
# Load the spec_XXXnm attributes into a Numpy array.
sample = color.get_numpy_array()
# Matrix multiplication
intermediate = sample * density_standard
# Sum the products.
numerator = intermediate.sum()
# This is the denominator in the density equation.
sum_of_standard_wavelengths = density_standard.sum()
# This is the top level of the density formula.
return -1.0 * log10(numerator / sum_of_standard_wavelengths) | python | def ansi_density(color, density_standard):
"""
Calculates density for the given SpectralColor using the spectral weighting
function provided. For example, ANSI_STATUS_T_RED. These may be found in
:py:mod:`colormath.density_standards`.
:param SpectralColor color: The SpectralColor object to calculate
density for.
:param numpy.ndarray density_standard: NumPy array of filter of choice
from :py:mod:`colormath.density_standards`.
:rtype: float
:returns: The density value for the given color and density standard.
"""
# Load the spec_XXXnm attributes into a Numpy array.
sample = color.get_numpy_array()
# Matrix multiplication
intermediate = sample * density_standard
# Sum the products.
numerator = intermediate.sum()
# This is the denominator in the density equation.
sum_of_standard_wavelengths = density_standard.sum()
# This is the top level of the density formula.
return -1.0 * log10(numerator / sum_of_standard_wavelengths) | Calculates density for the given SpectralColor using the spectral weighting
function provided. For example, ANSI_STATUS_T_RED. These may be found in
:py:mod:`colormath.density_standards`.
:param SpectralColor color: The SpectralColor object to calculate
density for.
:param numpy.ndarray density_standard: NumPy array of filter of choice
from :py:mod:`colormath.density_standards`.
:rtype: float
:returns: The density value for the given color and density standard. | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/density.py#L11-L35 |
gtaylor/python-colormath | colormath/density.py | auto_density | def auto_density(color):
"""
Given a SpectralColor, automatically choose the correct ANSI T filter.
Returns a tuple with a string representation of the filter the
calculated density.
:param SpectralColor color: The SpectralColor object to calculate
density for.
:rtype: float
:returns: The density value, with the filter selected automatically.
"""
blue_density = ansi_density(color, ANSI_STATUS_T_BLUE)
green_density = ansi_density(color, ANSI_STATUS_T_GREEN)
red_density = ansi_density(color, ANSI_STATUS_T_RED)
densities = [blue_density, green_density, red_density]
min_density = min(densities)
max_density = max(densities)
density_range = max_density - min_density
# See comments in density_standards.py for VISUAL_DENSITY_THRESH to
# understand what this is doing.
if density_range <= VISUAL_DENSITY_THRESH:
return ansi_density(color, ISO_VISUAL)
elif blue_density > green_density and blue_density > red_density:
return blue_density
elif green_density > blue_density and green_density > red_density:
return green_density
else:
return red_density | python | def auto_density(color):
"""
Given a SpectralColor, automatically choose the correct ANSI T filter.
Returns a tuple with a string representation of the filter the
calculated density.
:param SpectralColor color: The SpectralColor object to calculate
density for.
:rtype: float
:returns: The density value, with the filter selected automatically.
"""
blue_density = ansi_density(color, ANSI_STATUS_T_BLUE)
green_density = ansi_density(color, ANSI_STATUS_T_GREEN)
red_density = ansi_density(color, ANSI_STATUS_T_RED)
densities = [blue_density, green_density, red_density]
min_density = min(densities)
max_density = max(densities)
density_range = max_density - min_density
# See comments in density_standards.py for VISUAL_DENSITY_THRESH to
# understand what this is doing.
if density_range <= VISUAL_DENSITY_THRESH:
return ansi_density(color, ISO_VISUAL)
elif blue_density > green_density and blue_density > red_density:
return blue_density
elif green_density > blue_density and green_density > red_density:
return green_density
else:
return red_density | Given a SpectralColor, automatically choose the correct ANSI T filter.
Returns a tuple with a string representation of the filter the
calculated density.
:param SpectralColor color: The SpectralColor object to calculate
density for.
:rtype: float
:returns: The density value, with the filter selected automatically. | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/density.py#L38-L67 |
gtaylor/python-colormath | colormath/color_diff.py | _get_lab_color1_vector | def _get_lab_color1_vector(color):
"""
Converts an LabColor into a NumPy vector.
:param LabColor color:
:rtype: numpy.ndarray
"""
if not color.__class__.__name__ == 'LabColor':
raise ValueError(
"Delta E functions can only be used with two LabColor objects.")
return numpy.array([color.lab_l, color.lab_a, color.lab_b]) | python | def _get_lab_color1_vector(color):
"""
Converts an LabColor into a NumPy vector.
:param LabColor color:
:rtype: numpy.ndarray
"""
if not color.__class__.__name__ == 'LabColor':
raise ValueError(
"Delta E functions can only be used with two LabColor objects.")
return numpy.array([color.lab_l, color.lab_a, color.lab_b]) | Converts an LabColor into a NumPy vector.
:param LabColor color:
:rtype: numpy.ndarray | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_diff.py#L12-L22 |
gtaylor/python-colormath | colormath/color_diff.py | delta_e_cie1976 | def delta_e_cie1976(color1, color2):
"""
Calculates the Delta E (CIE1976) of two colors.
"""
color1_vector = _get_lab_color1_vector(color1)
color2_matrix = _get_lab_color2_matrix(color2)
delta_e = color_diff_matrix.delta_e_cie1976(color1_vector, color2_matrix)[0]
return numpy.asscalar(delta_e) | python | def delta_e_cie1976(color1, color2):
"""
Calculates the Delta E (CIE1976) of two colors.
"""
color1_vector = _get_lab_color1_vector(color1)
color2_matrix = _get_lab_color2_matrix(color2)
delta_e = color_diff_matrix.delta_e_cie1976(color1_vector, color2_matrix)[0]
return numpy.asscalar(delta_e) | Calculates the Delta E (CIE1976) of two colors. | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_diff.py#L39-L46 |
gtaylor/python-colormath | colormath/color_diff.py | delta_e_cie1994 | def delta_e_cie1994(color1, color2, K_L=1, K_C=1, K_H=1, K_1=0.045, K_2=0.015):
"""
Calculates the Delta E (CIE1994) of two colors.
K_l:
0.045 graphic arts
0.048 textiles
K_2:
0.015 graphic arts
0.014 textiles
K_L:
1 default
2 textiles
"""
color1_vector = _get_lab_color1_vector(color1)
color2_matrix = _get_lab_color2_matrix(color2)
delta_e = color_diff_matrix.delta_e_cie1994(
color1_vector, color2_matrix, K_L=K_L, K_C=K_C, K_H=K_H, K_1=K_1, K_2=K_2)[0]
return numpy.asscalar(delta_e) | python | def delta_e_cie1994(color1, color2, K_L=1, K_C=1, K_H=1, K_1=0.045, K_2=0.015):
"""
Calculates the Delta E (CIE1994) of two colors.
K_l:
0.045 graphic arts
0.048 textiles
K_2:
0.015 graphic arts
0.014 textiles
K_L:
1 default
2 textiles
"""
color1_vector = _get_lab_color1_vector(color1)
color2_matrix = _get_lab_color2_matrix(color2)
delta_e = color_diff_matrix.delta_e_cie1994(
color1_vector, color2_matrix, K_L=K_L, K_C=K_C, K_H=K_H, K_1=K_1, K_2=K_2)[0]
return numpy.asscalar(delta_e) | Calculates the Delta E (CIE1994) of two colors.
K_l:
0.045 graphic arts
0.048 textiles
K_2:
0.015 graphic arts
0.014 textiles
K_L:
1 default
2 textiles | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_diff.py#L50-L68 |
gtaylor/python-colormath | colormath/color_diff.py | delta_e_cie2000 | def delta_e_cie2000(color1, color2, Kl=1, Kc=1, Kh=1):
"""
Calculates the Delta E (CIE2000) of two colors.
"""
color1_vector = _get_lab_color1_vector(color1)
color2_matrix = _get_lab_color2_matrix(color2)
delta_e = color_diff_matrix.delta_e_cie2000(
color1_vector, color2_matrix, Kl=Kl, Kc=Kc, Kh=Kh)[0]
return numpy.asscalar(delta_e) | python | def delta_e_cie2000(color1, color2, Kl=1, Kc=1, Kh=1):
"""
Calculates the Delta E (CIE2000) of two colors.
"""
color1_vector = _get_lab_color1_vector(color1)
color2_matrix = _get_lab_color2_matrix(color2)
delta_e = color_diff_matrix.delta_e_cie2000(
color1_vector, color2_matrix, Kl=Kl, Kc=Kc, Kh=Kh)[0]
return numpy.asscalar(delta_e) | Calculates the Delta E (CIE2000) of two colors. | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_diff.py#L72-L80 |
gtaylor/python-colormath | colormath/color_diff.py | delta_e_cmc | def delta_e_cmc(color1, color2, pl=2, pc=1):
"""
Calculates the Delta E (CMC) of two colors.
CMC values
Acceptability: pl=2, pc=1
Perceptability: pl=1, pc=1
"""
color1_vector = _get_lab_color1_vector(color1)
color2_matrix = _get_lab_color2_matrix(color2)
delta_e = color_diff_matrix.delta_e_cmc(
color1_vector, color2_matrix, pl=pl, pc=pc)[0]
return numpy.asscalar(delta_e) | python | def delta_e_cmc(color1, color2, pl=2, pc=1):
"""
Calculates the Delta E (CMC) of two colors.
CMC values
Acceptability: pl=2, pc=1
Perceptability: pl=1, pc=1
"""
color1_vector = _get_lab_color1_vector(color1)
color2_matrix = _get_lab_color2_matrix(color2)
delta_e = color_diff_matrix.delta_e_cmc(
color1_vector, color2_matrix, pl=pl, pc=pc)[0]
return numpy.asscalar(delta_e) | Calculates the Delta E (CMC) of two colors.
CMC values
Acceptability: pl=2, pc=1
Perceptability: pl=1, pc=1 | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_diff.py#L84-L96 |