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_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
ask/redish
redish/models.py
Model.save
def save(self): """Save this entry. If the entry does not have an :attr:`id`, a new id will be assigned, and the :attr:`id` attribute set accordingly. Pre-save processing of the fields saved can be done by overriding the :meth:`prepare_save` method. Additional actions to be done after the save operation has been completed can be added by defining the :meth:`post_save` method. """ id = self.id or self.objects.id(self.name) self.objects[id] = self.prepare_save(dict(self)) self.id = id self.post_save() return id
python
def save(self): """Save this entry. If the entry does not have an :attr:`id`, a new id will be assigned, and the :attr:`id` attribute set accordingly. Pre-save processing of the fields saved can be done by overriding the :meth:`prepare_save` method. Additional actions to be done after the save operation has been completed can be added by defining the :meth:`post_save` method. """ id = self.id or self.objects.id(self.name) self.objects[id] = self.prepare_save(dict(self)) self.id = id self.post_save() return id
[ "def", "save", "(", "self", ")", ":", "id", "=", "self", ".", "id", "or", "self", ".", "objects", ".", "id", "(", "self", ".", "name", ")", "self", ".", "objects", "[", "id", "]", "=", "self", ".", "prepare_save", "(", "dict", "(", "self", ")",...
Save this entry. If the entry does not have an :attr:`id`, a new id will be assigned, and the :attr:`id` attribute set accordingly. Pre-save processing of the fields saved can be done by overriding the :meth:`prepare_save` method. Additional actions to be done after the save operation has been completed can be added by defining the :meth:`post_save` method.
[ "Save", "this", "entry", "." ]
train
https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/models.py#L62-L80
ask/redish
redish/models.py
Manager.get_many
def get_many(self, ids): """Get several entries at once.""" return [self.instance(id, **fields) for id, fields in zip(ids, self.api.mget(ids))]
python
def get_many(self, ids): """Get several entries at once.""" return [self.instance(id, **fields) for id, fields in zip(ids, self.api.mget(ids))]
[ "def", "get_many", "(", "self", ",", "ids", ")", ":", "return", "[", "self", ".", "instance", "(", "id", ",", "*", "*", "fields", ")", "for", "id", ",", "fields", "in", "zip", "(", "ids", ",", "self", ".", "api", ".", "mget", "(", "ids", ")", ...
Get several entries at once.
[ "Get", "several", "entries", "at", "once", "." ]
train
https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/models.py#L163-L166
ask/redish
redish/models.py
Manager.create
def create(self, **fields): """Create new entry.""" entry = self.instance(**fields) entry.save() return entry
python
def create(self, **fields): """Create new entry.""" entry = self.instance(**fields) entry.save() return entry
[ "def", "create", "(", "self", ",", "*", "*", "fields", ")", ":", "entry", "=", "self", ".", "instance", "(", "*", "*", "fields", ")", "entry", ".", "save", "(", ")", "return", "entry" ]
Create new entry.
[ "Create", "new", "entry", "." ]
train
https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/models.py#L177-L181
jic-dtool/dtoolcore
dtoolcore/utils.py
generous_parse_uri
def generous_parse_uri(uri): """Return a urlparse.ParseResult object with the results of parsing the given URI. This has the same properties as the result of parse_uri. When passed a relative path, it determines the absolute path, sets the scheme to file, the netloc to localhost and returns a parse of the result. """ parse_result = urlparse(uri) if parse_result.scheme == '': abspath = os.path.abspath(parse_result.path) if IS_WINDOWS: abspath = windows_to_unix_path(abspath) fixed_uri = "file://{}".format(abspath) parse_result = urlparse(fixed_uri) return parse_result
python
def generous_parse_uri(uri): """Return a urlparse.ParseResult object with the results of parsing the given URI. This has the same properties as the result of parse_uri. When passed a relative path, it determines the absolute path, sets the scheme to file, the netloc to localhost and returns a parse of the result. """ parse_result = urlparse(uri) if parse_result.scheme == '': abspath = os.path.abspath(parse_result.path) if IS_WINDOWS: abspath = windows_to_unix_path(abspath) fixed_uri = "file://{}".format(abspath) parse_result = urlparse(fixed_uri) return parse_result
[ "def", "generous_parse_uri", "(", "uri", ")", ":", "parse_result", "=", "urlparse", "(", "uri", ")", "if", "parse_result", ".", "scheme", "==", "''", ":", "abspath", "=", "os", ".", "path", ".", "abspath", "(", "parse_result", ".", "path", ")", "if", "...
Return a urlparse.ParseResult object with the results of parsing the given URI. This has the same properties as the result of parse_uri. When passed a relative path, it determines the absolute path, sets the scheme to file, the netloc to localhost and returns a parse of the result.
[ "Return", "a", "urlparse", ".", "ParseResult", "object", "with", "the", "results", "of", "parsing", "the", "given", "URI", ".", "This", "has", "the", "same", "properties", "as", "the", "result", "of", "parse_uri", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/utils.py#L42-L59
jic-dtool/dtoolcore
dtoolcore/utils.py
getuser
def getuser(): """Return the username.""" is_windows = platform.system() == "Windows" no_username_in_env = os.environ.get("USERNAME") is None return cross_platform_getuser(is_windows, no_username_in_env)
python
def getuser(): """Return the username.""" is_windows = platform.system() == "Windows" no_username_in_env = os.environ.get("USERNAME") is None return cross_platform_getuser(is_windows, no_username_in_env)
[ "def", "getuser", "(", ")", ":", "is_windows", "=", "platform", ".", "system", "(", ")", "==", "\"Windows\"", "no_username_in_env", "=", "os", ".", "environ", ".", "get", "(", "\"USERNAME\"", ")", "is", "None", "return", "cross_platform_getuser", "(", "is_wi...
Return the username.
[ "Return", "the", "username", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/utils.py#L79-L83
jic-dtool/dtoolcore
dtoolcore/utils.py
_get_config_dict_from_file
def _get_config_dict_from_file(config_path=None): """Return value if key exists in file. Return empty string ("") if key or file does not exist. """ if config_path is None: config_path = DEFAULT_CONFIG_PATH # Default (empty) content will be used if config file does not exist. config_content = {} # If the config file exists we use that content. if os.path.isfile(config_path): with open(config_path) as fh: config_content = json.load(fh) return config_content
python
def _get_config_dict_from_file(config_path=None): """Return value if key exists in file. Return empty string ("") if key or file does not exist. """ if config_path is None: config_path = DEFAULT_CONFIG_PATH # Default (empty) content will be used if config file does not exist. config_content = {} # If the config file exists we use that content. if os.path.isfile(config_path): with open(config_path) as fh: config_content = json.load(fh) return config_content
[ "def", "_get_config_dict_from_file", "(", "config_path", "=", "None", ")", ":", "if", "config_path", "is", "None", ":", "config_path", "=", "DEFAULT_CONFIG_PATH", "# Default (empty) content will be used if config file does not exist.", "config_content", "=", "{", "}", "# If...
Return value if key exists in file. Return empty string ("") if key or file does not exist.
[ "Return", "value", "if", "key", "exists", "in", "file", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/utils.py#L86-L102
jic-dtool/dtoolcore
dtoolcore/utils.py
write_config_value_to_file
def write_config_value_to_file(key, value, config_path=None): """Write key/value pair to config file. """ if config_path is None: config_path = DEFAULT_CONFIG_PATH # Get existing config. config = _get_config_dict_from_file(config_path) # Add/update the key/value pair. config[key] = value # Create parent directories if they are missing. mkdir_parents(os.path.dirname(config_path)) # Write the content with open(config_path, "w") as fh: json.dump(config, fh, sort_keys=True, indent=2) # Set 600 permissions on the config file. os.chmod(config_path, 33216) return get_config_value_from_file(key, config_path)
python
def write_config_value_to_file(key, value, config_path=None): """Write key/value pair to config file. """ if config_path is None: config_path = DEFAULT_CONFIG_PATH # Get existing config. config = _get_config_dict_from_file(config_path) # Add/update the key/value pair. config[key] = value # Create parent directories if they are missing. mkdir_parents(os.path.dirname(config_path)) # Write the content with open(config_path, "w") as fh: json.dump(config, fh, sort_keys=True, indent=2) # Set 600 permissions on the config file. os.chmod(config_path, 33216) return get_config_value_from_file(key, config_path)
[ "def", "write_config_value_to_file", "(", "key", ",", "value", ",", "config_path", "=", "None", ")", ":", "if", "config_path", "is", "None", ":", "config_path", "=", "DEFAULT_CONFIG_PATH", "# Get existing config.", "config", "=", "_get_config_dict_from_file", "(", "...
Write key/value pair to config file.
[ "Write", "key", "/", "value", "pair", "to", "config", "file", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/utils.py#L105-L127
jic-dtool/dtoolcore
dtoolcore/utils.py
get_config_value_from_file
def get_config_value_from_file(key, config_path=None, default=None): """Return value if key exists in file. Return default if key not in config. """ config = _get_config_dict_from_file(config_path) if key not in config: return default return config[key]
python
def get_config_value_from_file(key, config_path=None, default=None): """Return value if key exists in file. Return default if key not in config. """ config = _get_config_dict_from_file(config_path) if key not in config: return default return config[key]
[ "def", "get_config_value_from_file", "(", "key", ",", "config_path", "=", "None", ",", "default", "=", "None", ")", ":", "config", "=", "_get_config_dict_from_file", "(", "config_path", ")", "if", "key", "not", "in", "config", ":", "return", "default", "return...
Return value if key exists in file. Return default if key not in config.
[ "Return", "value", "if", "key", "exists", "in", "file", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/utils.py#L130-L138
jic-dtool/dtoolcore
dtoolcore/utils.py
get_config_value
def get_config_value(key, config_path=None, default=None): """Get a configuration value. Preference: 1. From environment 2. From JSON configuration file supplied in ``config_path`` argument 3. The default supplied to the function :param key: name of lookup value :param config_path: path to JSON configuration file :param default: default fall back value :returns: value associated with the key """ if config_path is None: config_path = DEFAULT_CONFIG_PATH # Start by setting default value value = default # Update from config file value = get_config_value_from_file( key=key, config_path=config_path, default=value ) # Update from environment variable value = os.environ.get(key, value) return value
python
def get_config_value(key, config_path=None, default=None): """Get a configuration value. Preference: 1. From environment 2. From JSON configuration file supplied in ``config_path`` argument 3. The default supplied to the function :param key: name of lookup value :param config_path: path to JSON configuration file :param default: default fall back value :returns: value associated with the key """ if config_path is None: config_path = DEFAULT_CONFIG_PATH # Start by setting default value value = default # Update from config file value = get_config_value_from_file( key=key, config_path=config_path, default=value ) # Update from environment variable value = os.environ.get(key, value) return value
[ "def", "get_config_value", "(", "key", ",", "config_path", "=", "None", ",", "default", "=", "None", ")", ":", "if", "config_path", "is", "None", ":", "config_path", "=", "DEFAULT_CONFIG_PATH", "# Start by setting default value", "value", "=", "default", "# Update...
Get a configuration value. Preference: 1. From environment 2. From JSON configuration file supplied in ``config_path`` argument 3. The default supplied to the function :param key: name of lookup value :param config_path: path to JSON configuration file :param default: default fall back value :returns: value associated with the key
[ "Get", "a", "configuration", "value", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/utils.py#L141-L169
jic-dtool/dtoolcore
dtoolcore/utils.py
mkdir_parents
def mkdir_parents(path): """Create the given directory path. This includes all necessary parent directories. Does not raise an error if the directory already exists. :param path: path to create """ try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST: pass else: raise
python
def mkdir_parents(path): """Create the given directory path. This includes all necessary parent directories. Does not raise an error if the directory already exists. :param path: path to create """ try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST: pass else: raise
[ "def", "mkdir_parents", "(", "path", ")", ":", "try", ":", "os", ".", "makedirs", "(", "path", ")", "except", "OSError", "as", "exc", ":", "if", "exc", ".", "errno", "==", "errno", ".", "EEXIST", ":", "pass", "else", ":", "raise" ]
Create the given directory path. This includes all necessary parent directories. Does not raise an error if the directory already exists. :param path: path to create
[ "Create", "the", "given", "directory", "path", ".", "This", "includes", "all", "necessary", "parent", "directories", ".", "Does", "not", "raise", "an", "error", "if", "the", "directory", "already", "exists", ".", ":", "param", "path", ":", "path", "to", "c...
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/utils.py#L191-L204
jic-dtool/dtoolcore
dtoolcore/utils.py
timestamp
def timestamp(datetime_obj): """Return Unix timestamp as float. The number of seconds that have elapsed since January 1, 1970. """ start_of_time = datetime.datetime(1970, 1, 1) diff = datetime_obj - start_of_time return diff.total_seconds()
python
def timestamp(datetime_obj): """Return Unix timestamp as float. The number of seconds that have elapsed since January 1, 1970. """ start_of_time = datetime.datetime(1970, 1, 1) diff = datetime_obj - start_of_time return diff.total_seconds()
[ "def", "timestamp", "(", "datetime_obj", ")", ":", "start_of_time", "=", "datetime", ".", "datetime", "(", "1970", ",", "1", ",", "1", ")", "diff", "=", "datetime_obj", "-", "start_of_time", "return", "diff", ".", "total_seconds", "(", ")" ]
Return Unix timestamp as float. The number of seconds that have elapsed since January 1, 1970.
[ "Return", "Unix", "timestamp", "as", "float", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/utils.py#L207-L214
jic-dtool/dtoolcore
dtoolcore/utils.py
name_is_valid
def name_is_valid(name): """Return True if the dataset name is valid. The name can only be 80 characters long. Valid characters: Alpha numeric characters [0-9a-zA-Z] Valid special characters: - _ . """ # The name can only be 80 characters long. if len(name) > MAX_NAME_LENGTH: return False return bool(NAME_VALID_CHARS_REGEX.match(name))
python
def name_is_valid(name): """Return True if the dataset name is valid. The name can only be 80 characters long. Valid characters: Alpha numeric characters [0-9a-zA-Z] Valid special characters: - _ . """ # The name can only be 80 characters long. if len(name) > MAX_NAME_LENGTH: return False return bool(NAME_VALID_CHARS_REGEX.match(name))
[ "def", "name_is_valid", "(", "name", ")", ":", "# The name can only be 80 characters long.", "if", "len", "(", "name", ")", ">", "MAX_NAME_LENGTH", ":", "return", "False", "return", "bool", "(", "NAME_VALID_CHARS_REGEX", ".", "match", "(", "name", ")", ")" ]
Return True if the dataset name is valid. The name can only be 80 characters long. Valid characters: Alpha numeric characters [0-9a-zA-Z] Valid special characters: - _ .
[ "Return", "True", "if", "the", "dataset", "name", "is", "valid", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/utils.py#L217-L227
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
BaseStorageBroker.get_admin_metadata
def get_admin_metadata(self): """Return the admin metadata as a dictionary.""" logger.debug("Getting admin metdata") text = self.get_text(self.get_admin_metadata_key()) return json.loads(text)
python
def get_admin_metadata(self): """Return the admin metadata as a dictionary.""" logger.debug("Getting admin metdata") text = self.get_text(self.get_admin_metadata_key()) return json.loads(text)
[ "def", "get_admin_metadata", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Getting admin metdata\"", ")", "text", "=", "self", ".", "get_text", "(", "self", ".", "get_admin_metadata_key", "(", ")", ")", "return", "json", ".", "loads", "(", "text", ...
Return the admin metadata as a dictionary.
[ "Return", "the", "admin", "metadata", "as", "a", "dictionary", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L214-L218
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
BaseStorageBroker.get_manifest
def get_manifest(self): """Return the manifest as a dictionary.""" logger.debug("Getting manifest") text = self.get_text(self.get_manifest_key()) return json.loads(text)
python
def get_manifest(self): """Return the manifest as a dictionary.""" logger.debug("Getting manifest") text = self.get_text(self.get_manifest_key()) return json.loads(text)
[ "def", "get_manifest", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Getting manifest\"", ")", "text", "=", "self", ".", "get_text", "(", "self", ".", "get_manifest_key", "(", ")", ")", "return", "json", ".", "loads", "(", "text", ")" ]
Return the manifest as a dictionary.
[ "Return", "the", "manifest", "as", "a", "dictionary", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L225-L229
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
BaseStorageBroker.get_overlay
def get_overlay(self, overlay_name): """Return overlay as a dictionary.""" logger.debug("Getting overlay: {}".format(overlay_name)) overlay_key = self.get_overlay_key(overlay_name) text = self.get_text(overlay_key) return json.loads(text)
python
def get_overlay(self, overlay_name): """Return overlay as a dictionary.""" logger.debug("Getting overlay: {}".format(overlay_name)) overlay_key = self.get_overlay_key(overlay_name) text = self.get_text(overlay_key) return json.loads(text)
[ "def", "get_overlay", "(", "self", ",", "overlay_name", ")", ":", "logger", ".", "debug", "(", "\"Getting overlay: {}\"", ".", "format", "(", "overlay_name", ")", ")", "overlay_key", "=", "self", ".", "get_overlay_key", "(", "overlay_name", ")", "text", "=", ...
Return overlay as a dictionary.
[ "Return", "overlay", "as", "a", "dictionary", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L231-L236
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
BaseStorageBroker.put_admin_metadata
def put_admin_metadata(self, admin_metadata): """Store the admin metadata.""" logger.debug("Putting admin metdata") text = json.dumps(admin_metadata) key = self.get_admin_metadata_key() self.put_text(key, text)
python
def put_admin_metadata(self, admin_metadata): """Store the admin metadata.""" logger.debug("Putting admin metdata") text = json.dumps(admin_metadata) key = self.get_admin_metadata_key() self.put_text(key, text)
[ "def", "put_admin_metadata", "(", "self", ",", "admin_metadata", ")", ":", "logger", ".", "debug", "(", "\"Putting admin metdata\"", ")", "text", "=", "json", ".", "dumps", "(", "admin_metadata", ")", "key", "=", "self", ".", "get_admin_metadata_key", "(", ")"...
Store the admin metadata.
[ "Store", "the", "admin", "metadata", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L238-L243
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
BaseStorageBroker.put_manifest
def put_manifest(self, manifest): """Store the manifest.""" logger.debug("Putting manifest") text = json.dumps(manifest, indent=2, sort_keys=True) key = self.get_manifest_key() self.put_text(key, text)
python
def put_manifest(self, manifest): """Store the manifest.""" logger.debug("Putting manifest") text = json.dumps(manifest, indent=2, sort_keys=True) key = self.get_manifest_key() self.put_text(key, text)
[ "def", "put_manifest", "(", "self", ",", "manifest", ")", ":", "logger", ".", "debug", "(", "\"Putting manifest\"", ")", "text", "=", "json", ".", "dumps", "(", "manifest", ",", "indent", "=", "2", ",", "sort_keys", "=", "True", ")", "key", "=", "self"...
Store the manifest.
[ "Store", "the", "manifest", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L245-L250
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
BaseStorageBroker.put_readme
def put_readme(self, content): """Store the readme descriptive metadata.""" logger.debug("Putting readme") key = self.get_readme_key() self.put_text(key, content)
python
def put_readme(self, content): """Store the readme descriptive metadata.""" logger.debug("Putting readme") key = self.get_readme_key() self.put_text(key, content)
[ "def", "put_readme", "(", "self", ",", "content", ")", ":", "logger", ".", "debug", "(", "\"Putting readme\"", ")", "key", "=", "self", ".", "get_readme_key", "(", ")", "self", ".", "put_text", "(", "key", ",", "content", ")" ]
Store the readme descriptive metadata.
[ "Store", "the", "readme", "descriptive", "metadata", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L252-L256
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
BaseStorageBroker.update_readme
def update_readme(self, content): """Update the readme descriptive metadata.""" logger.debug("Updating readme") key = self.get_readme_key() # Back up old README content. backup_content = self.get_readme_content() backup_key = key + "-{}".format( timestamp(datetime.datetime.now()) ) logger.debug("README.yml backup key: {}".format(backup_key)) self.put_text(backup_key, backup_content) self.put_text(key, content)
python
def update_readme(self, content): """Update the readme descriptive metadata.""" logger.debug("Updating readme") key = self.get_readme_key() # Back up old README content. backup_content = self.get_readme_content() backup_key = key + "-{}".format( timestamp(datetime.datetime.now()) ) logger.debug("README.yml backup key: {}".format(backup_key)) self.put_text(backup_key, backup_content) self.put_text(key, content)
[ "def", "update_readme", "(", "self", ",", "content", ")", ":", "logger", ".", "debug", "(", "\"Updating readme\"", ")", "key", "=", "self", ".", "get_readme_key", "(", ")", "# Back up old README content.", "backup_content", "=", "self", ".", "get_readme_content", ...
Update the readme descriptive metadata.
[ "Update", "the", "readme", "descriptive", "metadata", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L258-L271
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
BaseStorageBroker.put_overlay
def put_overlay(self, overlay_name, overlay): """Store the overlay.""" logger.debug("Putting overlay: {}".format(overlay_name)) key = self.get_overlay_key(overlay_name) text = json.dumps(overlay, indent=2) self.put_text(key, text)
python
def put_overlay(self, overlay_name, overlay): """Store the overlay.""" logger.debug("Putting overlay: {}".format(overlay_name)) key = self.get_overlay_key(overlay_name) text = json.dumps(overlay, indent=2) self.put_text(key, text)
[ "def", "put_overlay", "(", "self", ",", "overlay_name", ",", "overlay", ")", ":", "logger", ".", "debug", "(", "\"Putting overlay: {}\"", ".", "format", "(", "overlay_name", ")", ")", "key", "=", "self", ".", "get_overlay_key", "(", "overlay_name", ")", "tex...
Store the overlay.
[ "Store", "the", "overlay", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L273-L278
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
BaseStorageBroker.item_properties
def item_properties(self, handle): """Return properties of the item with the given handle.""" logger.debug("Getting properties for handle: {}".format(handle)) properties = { 'size_in_bytes': self.get_size_in_bytes(handle), 'utc_timestamp': self.get_utc_timestamp(handle), 'hash': self.get_hash(handle), 'relpath': self.get_relpath(handle) } logger.debug("{} properties: {}".format(handle, properties)) return properties
python
def item_properties(self, handle): """Return properties of the item with the given handle.""" logger.debug("Getting properties for handle: {}".format(handle)) properties = { 'size_in_bytes': self.get_size_in_bytes(handle), 'utc_timestamp': self.get_utc_timestamp(handle), 'hash': self.get_hash(handle), 'relpath': self.get_relpath(handle) } logger.debug("{} properties: {}".format(handle, properties)) return properties
[ "def", "item_properties", "(", "self", ",", "handle", ")", ":", "logger", ".", "debug", "(", "\"Getting properties for handle: {}\"", ".", "format", "(", "handle", ")", ")", "properties", "=", "{", "'size_in_bytes'", ":", "self", ".", "get_size_in_bytes", "(", ...
Return properties of the item with the given handle.
[ "Return", "properties", "of", "the", "item", "with", "the", "given", "handle", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L284-L294
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
BaseStorageBroker._document_structure
def _document_structure(self): """Document the structure of the dataset.""" logger.debug("Documenting dataset structure") key = self.get_structure_key() text = json.dumps(self._structure_parameters, indent=2, sort_keys=True) self.put_text(key, text) key = self.get_dtool_readme_key() self.put_text(key, self._dtool_readme_txt)
python
def _document_structure(self): """Document the structure of the dataset.""" logger.debug("Documenting dataset structure") key = self.get_structure_key() text = json.dumps(self._structure_parameters, indent=2, sort_keys=True) self.put_text(key, text) key = self.get_dtool_readme_key() self.put_text(key, self._dtool_readme_txt)
[ "def", "_document_structure", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Documenting dataset structure\"", ")", "key", "=", "self", ".", "get_structure_key", "(", ")", "text", "=", "json", ".", "dumps", "(", "self", ".", "_structure_parameters", ",...
Document the structure of the dataset.
[ "Document", "the", "structure", "of", "the", "dataset", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L296-L304
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
DiskStorageBroker.list_dataset_uris
def list_dataset_uris(cls, base_uri, config_path): """Return list containing URIs in location given by base_uri.""" parsed_uri = generous_parse_uri(base_uri) uri_list = [] path = parsed_uri.path if IS_WINDOWS: path = unix_to_windows_path(parsed_uri.path, parsed_uri.netloc) for d in os.listdir(path): dir_path = os.path.join(path, d) if not os.path.isdir(dir_path): continue storage_broker = cls(dir_path, config_path) if not storage_broker.has_admin_metadata(): continue uri = storage_broker.generate_uri( name=d, uuid=None, base_uri=base_uri ) uri_list.append(uri) return uri_list
python
def list_dataset_uris(cls, base_uri, config_path): """Return list containing URIs in location given by base_uri.""" parsed_uri = generous_parse_uri(base_uri) uri_list = [] path = parsed_uri.path if IS_WINDOWS: path = unix_to_windows_path(parsed_uri.path, parsed_uri.netloc) for d in os.listdir(path): dir_path = os.path.join(path, d) if not os.path.isdir(dir_path): continue storage_broker = cls(dir_path, config_path) if not storage_broker.has_admin_metadata(): continue uri = storage_broker.generate_uri( name=d, uuid=None, base_uri=base_uri ) uri_list.append(uri) return uri_list
[ "def", "list_dataset_uris", "(", "cls", ",", "base_uri", ",", "config_path", ")", ":", "parsed_uri", "=", "generous_parse_uri", "(", "base_uri", ")", "uri_list", "=", "[", "]", "path", "=", "parsed_uri", ".", "path", "if", "IS_WINDOWS", ":", "path", "=", "...
Return list containing URIs in location given by base_uri.
[ "Return", "list", "containing", "URIs", "in", "location", "given", "by", "base_uri", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L372-L400
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
DiskStorageBroker.put_text
def put_text(self, key, text): """Put the text into the storage associated with the key.""" with open(key, "w") as fh: fh.write(text)
python
def put_text(self, key, text): """Put the text into the storage associated with the key.""" with open(key, "w") as fh: fh.write(text)
[ "def", "put_text", "(", "self", ",", "key", ",", "text", ")", ":", "with", "open", "(", "key", ",", "\"w\"", ")", "as", "fh", ":", "fh", ".", "write", "(", "text", ")" ]
Put the text into the storage associated with the key.
[ "Put", "the", "text", "into", "the", "storage", "associated", "with", "the", "key", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L419-L422
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
DiskStorageBroker.get_size_in_bytes
def get_size_in_bytes(self, handle): """Return the size in bytes.""" fpath = self._fpath_from_handle(handle) return os.stat(fpath).st_size
python
def get_size_in_bytes(self, handle): """Return the size in bytes.""" fpath = self._fpath_from_handle(handle) return os.stat(fpath).st_size
[ "def", "get_size_in_bytes", "(", "self", ",", "handle", ")", ":", "fpath", "=", "self", ".", "_fpath_from_handle", "(", "handle", ")", "return", "os", ".", "stat", "(", "fpath", ")", ".", "st_size" ]
Return the size in bytes.
[ "Return", "the", "size", "in", "bytes", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L448-L451
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
DiskStorageBroker.get_utc_timestamp
def get_utc_timestamp(self, handle): """Return the UTC timestamp.""" fpath = self._fpath_from_handle(handle) datetime_obj = datetime.datetime.utcfromtimestamp( os.stat(fpath).st_mtime ) return timestamp(datetime_obj)
python
def get_utc_timestamp(self, handle): """Return the UTC timestamp.""" fpath = self._fpath_from_handle(handle) datetime_obj = datetime.datetime.utcfromtimestamp( os.stat(fpath).st_mtime ) return timestamp(datetime_obj)
[ "def", "get_utc_timestamp", "(", "self", ",", "handle", ")", ":", "fpath", "=", "self", ".", "_fpath_from_handle", "(", "handle", ")", "datetime_obj", "=", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "os", ".", "stat", "(", "fpath", ")", "."...
Return the UTC timestamp.
[ "Return", "the", "UTC", "timestamp", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L453-L459
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
DiskStorageBroker.get_hash
def get_hash(self, handle): """Return the hash.""" fpath = self._fpath_from_handle(handle) return DiskStorageBroker.hasher(fpath)
python
def get_hash(self, handle): """Return the hash.""" fpath = self._fpath_from_handle(handle) return DiskStorageBroker.hasher(fpath)
[ "def", "get_hash", "(", "self", ",", "handle", ")", ":", "fpath", "=", "self", ".", "_fpath_from_handle", "(", "handle", ")", "return", "DiskStorageBroker", ".", "hasher", "(", "fpath", ")" ]
Return the hash.
[ "Return", "the", "hash", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L461-L464
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
DiskStorageBroker.list_overlay_names
def list_overlay_names(self): """Return list of overlay names.""" overlay_names = [] if not os.path.isdir(self._overlays_abspath): return overlay_names for fname in os.listdir(self._overlays_abspath): name, ext = os.path.splitext(fname) overlay_names.append(name) return overlay_names
python
def list_overlay_names(self): """Return list of overlay names.""" overlay_names = [] if not os.path.isdir(self._overlays_abspath): return overlay_names for fname in os.listdir(self._overlays_abspath): name, ext = os.path.splitext(fname) overlay_names.append(name) return overlay_names
[ "def", "list_overlay_names", "(", "self", ")", ":", "overlay_names", "=", "[", "]", "if", "not", "os", ".", "path", ".", "isdir", "(", "self", ".", "_overlays_abspath", ")", ":", "return", "overlay_names", "for", "fname", "in", "os", ".", "listdir", "(",...
Return list of overlay names.
[ "Return", "list", "of", "overlay", "names", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L473-L481
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
DiskStorageBroker.get_item_abspath
def get_item_abspath(self, identifier): """Return absolute path at which item content can be accessed. :param identifier: item identifier :returns: absolute path from which the item content can be accessed """ manifest = self.get_manifest() item = manifest["items"][identifier] item_abspath = os.path.join(self._data_abspath, item["relpath"]) return item_abspath
python
def get_item_abspath(self, identifier): """Return absolute path at which item content can be accessed. :param identifier: item identifier :returns: absolute path from which the item content can be accessed """ manifest = self.get_manifest() item = manifest["items"][identifier] item_abspath = os.path.join(self._data_abspath, item["relpath"]) return item_abspath
[ "def", "get_item_abspath", "(", "self", ",", "identifier", ")", ":", "manifest", "=", "self", ".", "get_manifest", "(", ")", "item", "=", "manifest", "[", "\"items\"", "]", "[", "identifier", "]", "item_abspath", "=", "os", ".", "path", ".", "join", "(",...
Return absolute path at which item content can be accessed. :param identifier: item identifier :returns: absolute path from which the item content can be accessed
[ "Return", "absolute", "path", "at", "which", "item", "content", "can", "be", "accessed", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L483-L492
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
DiskStorageBroker._create_structure
def _create_structure(self): """Create necessary structure to hold a dataset.""" # Ensure that the specified path does not exist and create it. if os.path.exists(self._abspath): raise(StorageBrokerOSError( "Path already exists: {}".format(self._abspath) )) # Make sure the parent directory exists. parent, _ = os.path.split(self._abspath) if not os.path.isdir(parent): raise(StorageBrokerOSError( "No such directory: {}".format(parent))) os.mkdir(self._abspath) # Create more essential subdirectories. for abspath in self._essential_subdirectories: if not os.path.isdir(abspath): os.mkdir(abspath)
python
def _create_structure(self): """Create necessary structure to hold a dataset.""" # Ensure that the specified path does not exist and create it. if os.path.exists(self._abspath): raise(StorageBrokerOSError( "Path already exists: {}".format(self._abspath) )) # Make sure the parent directory exists. parent, _ = os.path.split(self._abspath) if not os.path.isdir(parent): raise(StorageBrokerOSError( "No such directory: {}".format(parent))) os.mkdir(self._abspath) # Create more essential subdirectories. for abspath in self._essential_subdirectories: if not os.path.isdir(abspath): os.mkdir(abspath)
[ "def", "_create_structure", "(", "self", ")", ":", "# Ensure that the specified path does not exist and create it.", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "_abspath", ")", ":", "raise", "(", "StorageBrokerOSError", "(", "\"Path already exists: {}\"",...
Create necessary structure to hold a dataset.
[ "Create", "necessary", "structure", "to", "hold", "a", "dataset", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L494-L514
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
DiskStorageBroker.put_item
def put_item(self, fpath, relpath): """Put item with content from fpath at relpath in dataset. Missing directories in relpath are created on the fly. :param fpath: path to the item on disk :param relpath: relative path name given to the item in the dataset as a handle :returns: the handle given to the item """ # Define the destination path and make any missing parent directories. dest_path = os.path.join(self._data_abspath, relpath) dirname = os.path.dirname(dest_path) mkdir_parents(dirname) # Copy the file across. shutil.copyfile(fpath, dest_path) return relpath
python
def put_item(self, fpath, relpath): """Put item with content from fpath at relpath in dataset. Missing directories in relpath are created on the fly. :param fpath: path to the item on disk :param relpath: relative path name given to the item in the dataset as a handle :returns: the handle given to the item """ # Define the destination path and make any missing parent directories. dest_path = os.path.join(self._data_abspath, relpath) dirname = os.path.dirname(dest_path) mkdir_parents(dirname) # Copy the file across. shutil.copyfile(fpath, dest_path) return relpath
[ "def", "put_item", "(", "self", ",", "fpath", ",", "relpath", ")", ":", "# Define the destination path and make any missing parent directories.", "dest_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_data_abspath", ",", "relpath", ")", "dirname", "...
Put item with content from fpath at relpath in dataset. Missing directories in relpath are created on the fly. :param fpath: path to the item on disk :param relpath: relative path name given to the item in the dataset as a handle :returns: the handle given to the item
[ "Put", "item", "with", "content", "from", "fpath", "at", "relpath", "in", "dataset", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L516-L535
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
DiskStorageBroker.iter_item_handles
def iter_item_handles(self): """Return iterator over item handles.""" path = self._data_abspath path_length = len(path) + 1 for dirpath, dirnames, filenames in os.walk(path): for fn in filenames: path = os.path.join(dirpath, fn) relative_path = path[path_length:] if IS_WINDOWS: relative_path = windows_to_unix_path(relative_path) yield relative_path
python
def iter_item_handles(self): """Return iterator over item handles.""" path = self._data_abspath path_length = len(path) + 1 for dirpath, dirnames, filenames in os.walk(path): for fn in filenames: path = os.path.join(dirpath, fn) relative_path = path[path_length:] if IS_WINDOWS: relative_path = windows_to_unix_path(relative_path) yield relative_path
[ "def", "iter_item_handles", "(", "self", ")", ":", "path", "=", "self", ".", "_data_abspath", "path_length", "=", "len", "(", "path", ")", "+", "1", "for", "dirpath", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "path", ")", ":", ...
Return iterator over item handles.
[ "Return", "iterator", "over", "item", "handles", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L537-L549
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
DiskStorageBroker.add_item_metadata
def add_item_metadata(self, handle, key, value): """Store the given key:value pair for the item associated with handle. :param handle: handle for accessing an item before the dataset is frozen :param key: metadata key :param value: metadata value """ if not os.path.isdir(self._metadata_fragments_abspath): os.mkdir(self._metadata_fragments_abspath) prefix = self._handle_to_fragment_absprefixpath(handle) fpath = prefix + '.{}.json'.format(key) with open(fpath, 'w') as fh: json.dump(value, fh)
python
def add_item_metadata(self, handle, key, value): """Store the given key:value pair for the item associated with handle. :param handle: handle for accessing an item before the dataset is frozen :param key: metadata key :param value: metadata value """ if not os.path.isdir(self._metadata_fragments_abspath): os.mkdir(self._metadata_fragments_abspath) prefix = self._handle_to_fragment_absprefixpath(handle) fpath = prefix + '.{}.json'.format(key) with open(fpath, 'w') as fh: json.dump(value, fh)
[ "def", "add_item_metadata", "(", "self", ",", "handle", ",", "key", ",", "value", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "self", ".", "_metadata_fragments_abspath", ")", ":", "os", ".", "mkdir", "(", "self", ".", "_metadata_fragment...
Store the given key:value pair for the item associated with handle. :param handle: handle for accessing an item before the dataset is frozen :param key: metadata key :param value: metadata value
[ "Store", "the", "given", "key", ":", "value", "pair", "for", "the", "item", "associated", "with", "handle", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L551-L566
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
DiskStorageBroker.get_item_metadata
def get_item_metadata(self, handle): """Return dictionary containing all metadata associated with handle. In other words all the metadata added using the ``add_item_metadata`` method. :param handle: handle for accessing an item before the dataset is frozen :returns: dictionary containing item metadata """ if not os.path.isdir(self._metadata_fragments_abspath): return {} prefix = self._handle_to_fragment_absprefixpath(handle) def list_abspaths(dirname): for f in os.listdir(dirname): yield os.path.join(dirname, f) files = [f for f in list_abspaths(self._metadata_fragments_abspath) if f.startswith(prefix)] metadata = {} for f in files: key = f.split('.')[-2] # filename: identifier.key.json with open(f) as fh: value = json.load(fh) metadata[key] = value return metadata
python
def get_item_metadata(self, handle): """Return dictionary containing all metadata associated with handle. In other words all the metadata added using the ``add_item_metadata`` method. :param handle: handle for accessing an item before the dataset is frozen :returns: dictionary containing item metadata """ if not os.path.isdir(self._metadata_fragments_abspath): return {} prefix = self._handle_to_fragment_absprefixpath(handle) def list_abspaths(dirname): for f in os.listdir(dirname): yield os.path.join(dirname, f) files = [f for f in list_abspaths(self._metadata_fragments_abspath) if f.startswith(prefix)] metadata = {} for f in files: key = f.split('.')[-2] # filename: identifier.key.json with open(f) as fh: value = json.load(fh) metadata[key] = value return metadata
[ "def", "get_item_metadata", "(", "self", ",", "handle", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "self", ".", "_metadata_fragments_abspath", ")", ":", "return", "{", "}", "prefix", "=", "self", ".", "_handle_to_fragment_absprefixpath", "(...
Return dictionary containing all metadata associated with handle. In other words all the metadata added using the ``add_item_metadata`` method. :param handle: handle for accessing an item before the dataset is frozen :returns: dictionary containing item metadata
[ "Return", "dictionary", "containing", "all", "metadata", "associated", "with", "handle", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L568-L598
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
DiskStorageBroker.pre_freeze_hook
def pre_freeze_hook(self): """Pre :meth:`dtoolcore.ProtoDataSet.freeze` actions. This method is called at the beginning of the :meth:`dtoolcore.ProtoDataSet.freeze` method. It may be useful for remote storage backends to generate caches to remove repetitive time consuming calls """ allowed = set([v[0] for v in _STRUCTURE_PARAMETERS.values()]) for d in os.listdir(self._abspath): if d not in allowed: msg = "Rogue content in base of dataset: {}".format(d) raise(DiskStorageBrokerValidationWarning(msg))
python
def pre_freeze_hook(self): """Pre :meth:`dtoolcore.ProtoDataSet.freeze` actions. This method is called at the beginning of the :meth:`dtoolcore.ProtoDataSet.freeze` method. It may be useful for remote storage backends to generate caches to remove repetitive time consuming calls """ allowed = set([v[0] for v in _STRUCTURE_PARAMETERS.values()]) for d in os.listdir(self._abspath): if d not in allowed: msg = "Rogue content in base of dataset: {}".format(d) raise(DiskStorageBrokerValidationWarning(msg))
[ "def", "pre_freeze_hook", "(", "self", ")", ":", "allowed", "=", "set", "(", "[", "v", "[", "0", "]", "for", "v", "in", "_STRUCTURE_PARAMETERS", ".", "values", "(", ")", "]", ")", "for", "d", "in", "os", ".", "listdir", "(", "self", ".", "_abspath"...
Pre :meth:`dtoolcore.ProtoDataSet.freeze` actions. This method is called at the beginning of the :meth:`dtoolcore.ProtoDataSet.freeze` method. It may be useful for remote storage backends to generate caches to remove repetitive time consuming calls
[ "Pre", ":", "meth", ":", "dtoolcore", ".", "ProtoDataSet", ".", "freeze", "actions", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L600-L613
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
DiskStorageBroker.post_freeze_hook
def post_freeze_hook(self): """Post :meth:`dtoolcore.ProtoDataSet.freeze` cleanup actions. This method is called at the end of the :meth:`dtoolcore.ProtoDataSet.freeze` method. In the :class:`dtoolcore.storage_broker.DiskStorageBroker` it removes the temporary directory for storing item metadata fragment files. """ if os.path.isdir(self._metadata_fragments_abspath): shutil.rmtree(self._metadata_fragments_abspath)
python
def post_freeze_hook(self): """Post :meth:`dtoolcore.ProtoDataSet.freeze` cleanup actions. This method is called at the end of the :meth:`dtoolcore.ProtoDataSet.freeze` method. In the :class:`dtoolcore.storage_broker.DiskStorageBroker` it removes the temporary directory for storing item metadata fragment files. """ if os.path.isdir(self._metadata_fragments_abspath): shutil.rmtree(self._metadata_fragments_abspath)
[ "def", "post_freeze_hook", "(", "self", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "self", ".", "_metadata_fragments_abspath", ")", ":", "shutil", ".", "rmtree", "(", "self", ".", "_metadata_fragments_abspath", ")" ]
Post :meth:`dtoolcore.ProtoDataSet.freeze` cleanup actions. This method is called at the end of the :meth:`dtoolcore.ProtoDataSet.freeze` method. In the :class:`dtoolcore.storage_broker.DiskStorageBroker` it removes the temporary directory for storing item metadata fragment files.
[ "Post", ":", "meth", ":", "dtoolcore", ".", "ProtoDataSet", ".", "freeze", "cleanup", "actions", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L615-L625
feliperyan/EinsteinVisionPython
EinsteinVision/EinsteinVision.py
EinsteinVisionService.get_token
def get_token(self): """ Acquires a token for futher API calls, unless you already have a token this will be the first thing you do before you use this. :param email: string, the username for your EinsteinVision service, usually in email form :para pem_file: string, file containing your Secret key. Copy contents of relevant Config Var on Heroku to a file locally. attention: this will set self.token on success attention: currently spitting out results via a simple print returns: requests object """ payload = { 'aud': API_OAUTH, 'exp': time.time()+600, # 10 minutes 'sub': self.email } header = {'Content-type':'application/x-www-form-urlencoded'} assertion = jwt.encode(payload, self.private_key, algorithm='RS256') assertion = assertion.decode('utf-8') response = requests.post( url=API_OAUTH, headers=header, data='grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion='+assertion ) print(response.text) if response.status_code == 200: print('status 200 ok for Token') self.token = response.json()['access_token'] else: print('Could not get Token. Status: ' + str(response.status_code)) return response
python
def get_token(self): """ Acquires a token for futher API calls, unless you already have a token this will be the first thing you do before you use this. :param email: string, the username for your EinsteinVision service, usually in email form :para pem_file: string, file containing your Secret key. Copy contents of relevant Config Var on Heroku to a file locally. attention: this will set self.token on success attention: currently spitting out results via a simple print returns: requests object """ payload = { 'aud': API_OAUTH, 'exp': time.time()+600, # 10 minutes 'sub': self.email } header = {'Content-type':'application/x-www-form-urlencoded'} assertion = jwt.encode(payload, self.private_key, algorithm='RS256') assertion = assertion.decode('utf-8') response = requests.post( url=API_OAUTH, headers=header, data='grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion='+assertion ) print(response.text) if response.status_code == 200: print('status 200 ok for Token') self.token = response.json()['access_token'] else: print('Could not get Token. Status: ' + str(response.status_code)) return response
[ "def", "get_token", "(", "self", ")", ":", "payload", "=", "{", "'aud'", ":", "API_OAUTH", ",", "'exp'", ":", "time", ".", "time", "(", ")", "+", "600", ",", "# 10 minutes", "'sub'", ":", "self", ".", "email", "}", "header", "=", "{", "'Content-type'...
Acquires a token for futher API calls, unless you already have a token this will be the first thing you do before you use this. :param email: string, the username for your EinsteinVision service, usually in email form :para pem_file: string, file containing your Secret key. Copy contents of relevant Config Var on Heroku to a file locally. attention: this will set self.token on success attention: currently spitting out results via a simple print returns: requests object
[ "Acquires", "a", "token", "for", "futher", "API", "calls", "unless", "you", "already", "have", "a", "token", "this", "will", "be", "the", "first", "thing", "you", "do", "before", "you", "use", "this", ".", ":", "param", "email", ":", "string", "the", "...
train
https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L48-L83
feliperyan/EinsteinVisionPython
EinsteinVision/EinsteinVision.py
EinsteinVisionService.get_model_info
def get_model_info(self, model_id, token=None, url=API_GET_MODEL_INFO): """ Gets information about a specific previously trained model, ie: stats and accuracy :param model_id: string, model_id previously supplied by the API returns: requests object """ auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url + '/' + model_id r = requests.get(the_url, headers=h) return r
python
def get_model_info(self, model_id, token=None, url=API_GET_MODEL_INFO): """ Gets information about a specific previously trained model, ie: stats and accuracy :param model_id: string, model_id previously supplied by the API returns: requests object """ auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url + '/' + model_id r = requests.get(the_url, headers=h) return r
[ "def", "get_model_info", "(", "self", ",", "model_id", ",", "token", "=", "None", ",", "url", "=", "API_GET_MODEL_INFO", ")", ":", "auth", "=", "'Bearer '", "+", "self", ".", "check_for_token", "(", "token", ")", "h", "=", "{", "'Authorization'", ":", "a...
Gets information about a specific previously trained model, ie: stats and accuracy :param model_id: string, model_id previously supplied by the API returns: requests object
[ "Gets", "information", "about", "a", "specific", "previously", "trained", "model", "ie", ":", "stats", "and", "accuracy", ":", "param", "model_id", ":", "string", "model_id", "previously", "supplied", "by", "the", "API", "returns", ":", "requests", "object" ]
train
https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L93-L103
feliperyan/EinsteinVisionPython
EinsteinVision/EinsteinVision.py
EinsteinVisionService.get_datasets_info
def get_datasets_info(self, token=None, url=API_GET_DATASETS_INFO): """ Gets information on all datasets for this account returns: requests object """ auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url r = requests.get(the_url, headers=h) return r
python
def get_datasets_info(self, token=None, url=API_GET_DATASETS_INFO): """ Gets information on all datasets for this account returns: requests object """ auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url r = requests.get(the_url, headers=h) return r
[ "def", "get_datasets_info", "(", "self", ",", "token", "=", "None", ",", "url", "=", "API_GET_DATASETS_INFO", ")", ":", "auth", "=", "'Bearer '", "+", "self", ".", "check_for_token", "(", "token", ")", "h", "=", "{", "'Authorization'", ":", "auth", ",", ...
Gets information on all datasets for this account returns: requests object
[ "Gets", "information", "on", "all", "datasets", "for", "this", "account", "returns", ":", "requests", "object" ]
train
https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L106-L115
feliperyan/EinsteinVisionPython
EinsteinVision/EinsteinVision.py
EinsteinVisionService.get_url_image_prediction
def get_url_image_prediction(self, model_id, picture_url, token=None, url=API_GET_PREDICTION_IMAGE_URL): """ Gets a prediction from a supplied picture url based on a previously trained model. :param model_id: string, once you train a model you'll be given a model id to use. :param picture_url: string, in the form of a url pointing to a publicly accessible image file. returns: requests object """ auth = 'Bearer ' + self.check_for_token(token) m = MultipartEncoder(fields={'sampleLocation':picture_url, 'modelId':model_id}) h = {'Authorization': auth, 'Cache-Control':'no-cache', 'Content-Type':m.content_type} the_url = url r = requests.post(the_url, headers=h, data=m) return r
python
def get_url_image_prediction(self, model_id, picture_url, token=None, url=API_GET_PREDICTION_IMAGE_URL): """ Gets a prediction from a supplied picture url based on a previously trained model. :param model_id: string, once you train a model you'll be given a model id to use. :param picture_url: string, in the form of a url pointing to a publicly accessible image file. returns: requests object """ auth = 'Bearer ' + self.check_for_token(token) m = MultipartEncoder(fields={'sampleLocation':picture_url, 'modelId':model_id}) h = {'Authorization': auth, 'Cache-Control':'no-cache', 'Content-Type':m.content_type} the_url = url r = requests.post(the_url, headers=h, data=m) return r
[ "def", "get_url_image_prediction", "(", "self", ",", "model_id", ",", "picture_url", ",", "token", "=", "None", ",", "url", "=", "API_GET_PREDICTION_IMAGE_URL", ")", ":", "auth", "=", "'Bearer '", "+", "self", ".", "check_for_token", "(", "token", ")", "m", ...
Gets a prediction from a supplied picture url based on a previously trained model. :param model_id: string, once you train a model you'll be given a model id to use. :param picture_url: string, in the form of a url pointing to a publicly accessible image file. returns: requests object
[ "Gets", "a", "prediction", "from", "a", "supplied", "picture", "url", "based", "on", "a", "previously", "trained", "model", ".", ":", "param", "model_id", ":", "string", "once", "you", "train", "a", "model", "you", "ll", "be", "given", "a", "model", "id"...
train
https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L118-L131
feliperyan/EinsteinVisionPython
EinsteinVision/EinsteinVision.py
EinsteinVisionService.get_fileb64_image_prediction
def get_fileb64_image_prediction(self, model_id, filename, token=None, url=API_GET_PREDICTION_IMAGE_URL): """ Gets a prediction from a supplied image on your machine, by encoding the image data as b64 and posting to the API. :param model_id: string, once you train a model you'll be given a model id to use. :param filename: string, the name of a file to be posted to the api. returns: requests object """ auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url with open(filename, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()) m = MultipartEncoder(fields={'sampleBase64Content':encoded_string, 'modelId':model_id}) h = {'Authorization': auth, 'Cache-Control':'no-cache', 'Content-Type':m.content_type} r = requests.post(the_url, headers=h, data=m) return r
python
def get_fileb64_image_prediction(self, model_id, filename, token=None, url=API_GET_PREDICTION_IMAGE_URL): """ Gets a prediction from a supplied image on your machine, by encoding the image data as b64 and posting to the API. :param model_id: string, once you train a model you'll be given a model id to use. :param filename: string, the name of a file to be posted to the api. returns: requests object """ auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url with open(filename, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()) m = MultipartEncoder(fields={'sampleBase64Content':encoded_string, 'modelId':model_id}) h = {'Authorization': auth, 'Cache-Control':'no-cache', 'Content-Type':m.content_type} r = requests.post(the_url, headers=h, data=m) return r
[ "def", "get_fileb64_image_prediction", "(", "self", ",", "model_id", ",", "filename", ",", "token", "=", "None", ",", "url", "=", "API_GET_PREDICTION_IMAGE_URL", ")", ":", "auth", "=", "'Bearer '", "+", "self", ".", "check_for_token", "(", "token", ")", "h", ...
Gets a prediction from a supplied image on your machine, by encoding the image data as b64 and posting to the API. :param model_id: string, once you train a model you'll be given a model id to use. :param filename: string, the name of a file to be posted to the api. returns: requests object
[ "Gets", "a", "prediction", "from", "a", "supplied", "image", "on", "your", "machine", "by", "encoding", "the", "image", "data", "as", "b64", "and", "posting", "to", "the", "API", ".", ":", "param", "model_id", ":", "string", "once", "you", "train", "a", ...
train
https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L134-L152
feliperyan/EinsteinVisionPython
EinsteinVision/EinsteinVision.py
EinsteinVisionService.get_b64_image_prediction
def get_b64_image_prediction(self, model_id, b64_encoded_string, token=None, url=API_GET_PREDICTION_IMAGE_URL): """ Gets a prediction from a supplied image enconded as a b64 string, useful when uploading images to a server backed by this library. :param model_id: string, once you train a model you'll be given a model id to use. :param b64_encoded_string: string, a b64 enconded string representation of an image. returns: requests object """ auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url encoded_string = b64_encoded_string m = MultipartEncoder(fields={'sampleBase64Content':encoded_string, 'modelId':model_id}) h = {'Authorization': auth, 'Cache-Control':'no-cache', 'Content-Type':m.content_type} r = requests.post(the_url, headers=h, data=m) return r
python
def get_b64_image_prediction(self, model_id, b64_encoded_string, token=None, url=API_GET_PREDICTION_IMAGE_URL): """ Gets a prediction from a supplied image enconded as a b64 string, useful when uploading images to a server backed by this library. :param model_id: string, once you train a model you'll be given a model id to use. :param b64_encoded_string: string, a b64 enconded string representation of an image. returns: requests object """ auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url encoded_string = b64_encoded_string m = MultipartEncoder(fields={'sampleBase64Content':encoded_string, 'modelId':model_id}) h = {'Authorization': auth, 'Cache-Control':'no-cache', 'Content-Type':m.content_type} r = requests.post(the_url, headers=h, data=m) return r
[ "def", "get_b64_image_prediction", "(", "self", ",", "model_id", ",", "b64_encoded_string", ",", "token", "=", "None", ",", "url", "=", "API_GET_PREDICTION_IMAGE_URL", ")", ":", "auth", "=", "'Bearer '", "+", "self", ".", "check_for_token", "(", "token", ")", ...
Gets a prediction from a supplied image enconded as a b64 string, useful when uploading images to a server backed by this library. :param model_id: string, once you train a model you'll be given a model id to use. :param b64_encoded_string: string, a b64 enconded string representation of an image. returns: requests object
[ "Gets", "a", "prediction", "from", "a", "supplied", "image", "enconded", "as", "a", "b64", "string", "useful", "when", "uploading", "images", "to", "a", "server", "backed", "by", "this", "library", ".", ":", "param", "model_id", ":", "string", "once", "you...
train
https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L155-L172
feliperyan/EinsteinVisionPython
EinsteinVision/EinsteinVision.py
EinsteinVisionService.create_dataset_synchronous
def create_dataset_synchronous(self, file_url, dataset_type='image', token=None, url=API_CREATE_DATASET): """ Creates a dataset so you can train models from it :param file_url: string, url to an accessible zip file containing the necessary image files and folder structure indicating the labels to train. See docs online. :param dataset_type: string, one of the dataset types, available options Nov 2017 were 'image', 'image-detection' and 'image-multi-label'. returns: requests object """ auth = 'Bearer ' + self.check_for_token(token) m = MultipartEncoder(fields={'type':dataset_type, 'path':file_url}) h = {'Authorization': auth, 'Cache-Control':'no-cache', 'Content-Type':m.content_type} the_url = url r = requests.post(the_url, headers=h, data=m) return r
python
def create_dataset_synchronous(self, file_url, dataset_type='image', token=None, url=API_CREATE_DATASET): """ Creates a dataset so you can train models from it :param file_url: string, url to an accessible zip file containing the necessary image files and folder structure indicating the labels to train. See docs online. :param dataset_type: string, one of the dataset types, available options Nov 2017 were 'image', 'image-detection' and 'image-multi-label'. returns: requests object """ auth = 'Bearer ' + self.check_for_token(token) m = MultipartEncoder(fields={'type':dataset_type, 'path':file_url}) h = {'Authorization': auth, 'Cache-Control':'no-cache', 'Content-Type':m.content_type} the_url = url r = requests.post(the_url, headers=h, data=m) return r
[ "def", "create_dataset_synchronous", "(", "self", ",", "file_url", ",", "dataset_type", "=", "'image'", ",", "token", "=", "None", ",", "url", "=", "API_CREATE_DATASET", ")", ":", "auth", "=", "'Bearer '", "+", "self", ".", "check_for_token", "(", "token", "...
Creates a dataset so you can train models from it :param file_url: string, url to an accessible zip file containing the necessary image files and folder structure indicating the labels to train. See docs online. :param dataset_type: string, one of the dataset types, available options Nov 2017 were 'image', 'image-detection' and 'image-multi-label'. returns: requests object
[ "Creates", "a", "dataset", "so", "you", "can", "train", "models", "from", "it", ":", "param", "file_url", ":", "string", "url", "to", "an", "accessible", "zip", "file", "containing", "the", "necessary", "image", "files", "and", "folder", "structure", "indica...
train
https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L175-L189
feliperyan/EinsteinVisionPython
EinsteinVision/EinsteinVision.py
EinsteinVisionService.train_model
def train_model(self, dataset_id, model_name, token=None, url=API_TRAIN_MODEL): """ Train a model given a specifi dataset previously created :param dataset_id: string, the id of a previously created dataset :param model_name: string, what you will call this model attention: This may take a while and a response will be returned before the model has finished being trained. See docos and method get_training_status. returns: requests object """ auth = 'Bearer ' + self.check_for_token(token) m = MultipartEncoder(fields={'name':model_name, 'datasetId':dataset_id}) h = {'Authorization': auth, 'Cache-Control':'no-cache', 'Content-Type':m.content_type} the_url = url r = requests.post(the_url, headers=h, data=m) return r
python
def train_model(self, dataset_id, model_name, token=None, url=API_TRAIN_MODEL): """ Train a model given a specifi dataset previously created :param dataset_id: string, the id of a previously created dataset :param model_name: string, what you will call this model attention: This may take a while and a response will be returned before the model has finished being trained. See docos and method get_training_status. returns: requests object """ auth = 'Bearer ' + self.check_for_token(token) m = MultipartEncoder(fields={'name':model_name, 'datasetId':dataset_id}) h = {'Authorization': auth, 'Cache-Control':'no-cache', 'Content-Type':m.content_type} the_url = url r = requests.post(the_url, headers=h, data=m) return r
[ "def", "train_model", "(", "self", ",", "dataset_id", ",", "model_name", ",", "token", "=", "None", ",", "url", "=", "API_TRAIN_MODEL", ")", ":", "auth", "=", "'Bearer '", "+", "self", ".", "check_for_token", "(", "token", ")", "m", "=", "MultipartEncoder"...
Train a model given a specifi dataset previously created :param dataset_id: string, the id of a previously created dataset :param model_name: string, what you will call this model attention: This may take a while and a response will be returned before the model has finished being trained. See docos and method get_training_status. returns: requests object
[ "Train", "a", "model", "given", "a", "specifi", "dataset", "previously", "created", ":", "param", "dataset_id", ":", "string", "the", "id", "of", "a", "previously", "created", "dataset", ":", "param", "model_name", ":", "string", "what", "you", "will", "call...
train
https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L192-L206
feliperyan/EinsteinVisionPython
EinsteinVision/EinsteinVision.py
EinsteinVisionService.get_training_status
def get_training_status(self, model_id, token=None, url=API_TRAIN_MODEL): """ Gets status on the training process once you create a model :param model_id: string, id of the model to check returns: requests object """ auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url + '/' + model_id r = requests.get(the_url, headers=h) return r
python
def get_training_status(self, model_id, token=None, url=API_TRAIN_MODEL): """ Gets status on the training process once you create a model :param model_id: string, id of the model to check returns: requests object """ auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url + '/' + model_id r = requests.get(the_url, headers=h) return r
[ "def", "get_training_status", "(", "self", ",", "model_id", ",", "token", "=", "None", ",", "url", "=", "API_TRAIN_MODEL", ")", ":", "auth", "=", "'Bearer '", "+", "self", ".", "check_for_token", "(", "token", ")", "h", "=", "{", "'Authorization'", ":", ...
Gets status on the training process once you create a model :param model_id: string, id of the model to check returns: requests object
[ "Gets", "status", "on", "the", "training", "process", "once", "you", "create", "a", "model", ":", "param", "model_id", ":", "string", "id", "of", "the", "model", "to", "check", "returns", ":", "requests", "object" ]
train
https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L209-L219
feliperyan/EinsteinVisionPython
EinsteinVision/EinsteinVision.py
EinsteinVisionService.get_models_info_for_dataset
def get_models_info_for_dataset(self, dataset_id, token=None, url=API_GET_MODELS): """ Gets metadata on all models available for given dataset id :param dataset_id: string, previously obtained dataset id warning: if providing your own url here, also include the dataset_id in the right place as this method will not include it for you. Otherwise use the dataset_id attribute as per usual returns: a requests object """ auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} if url != API_GET_MODELS: r = requests.get(the_url, headers=h) return r the_url = url.replace('<dataset_id>', dataset_id) r = requests.get(the_url, headers=h) return r
python
def get_models_info_for_dataset(self, dataset_id, token=None, url=API_GET_MODELS): """ Gets metadata on all models available for given dataset id :param dataset_id: string, previously obtained dataset id warning: if providing your own url here, also include the dataset_id in the right place as this method will not include it for you. Otherwise use the dataset_id attribute as per usual returns: a requests object """ auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} if url != API_GET_MODELS: r = requests.get(the_url, headers=h) return r the_url = url.replace('<dataset_id>', dataset_id) r = requests.get(the_url, headers=h) return r
[ "def", "get_models_info_for_dataset", "(", "self", ",", "dataset_id", ",", "token", "=", "None", ",", "url", "=", "API_GET_MODELS", ")", ":", "auth", "=", "'Bearer '", "+", "self", ".", "check_for_token", "(", "token", ")", "h", "=", "{", "'Authorization'", ...
Gets metadata on all models available for given dataset id :param dataset_id: string, previously obtained dataset id warning: if providing your own url here, also include the dataset_id in the right place as this method will not include it for you. Otherwise use the dataset_id attribute as per usual returns: a requests object
[ "Gets", "metadata", "on", "all", "models", "available", "for", "given", "dataset", "id", ":", "param", "dataset_id", ":", "string", "previously", "obtained", "dataset", "id", "warning", ":", "if", "providing", "your", "own", "url", "here", "also", "include", ...
train
https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L222-L239
feliperyan/EinsteinVisionPython
EinsteinVision/EinsteinVision.py
EinsteinVisionService.create_language_dataset_from_url
def create_language_dataset_from_url(self, file_url, token=None, url=API_CREATE_LANGUAGE_DATASET): """ Creates a dataset from a publicly accessible file stored in the cloud. :param file_url: string, in the form of a URL to a file accessible on the cloud. Popular options include Dropbox, AWS S3, Google Drive. warning: Google Drive by default gives you a link to a web ui that allows you to download a file NOT to the file directly. There is a way to change the link to point directly to the file as of 2018 as this may change, please search google for a solution. returns: a request object """ auth = 'Bearer ' + self.check_for_token(token) dummy_files = {'type': (None, 'text-intent'), 'path':(None, file_url)} h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url r = requests.post(the_url, headers=h, files=dummy_files) return r
python
def create_language_dataset_from_url(self, file_url, token=None, url=API_CREATE_LANGUAGE_DATASET): """ Creates a dataset from a publicly accessible file stored in the cloud. :param file_url: string, in the form of a URL to a file accessible on the cloud. Popular options include Dropbox, AWS S3, Google Drive. warning: Google Drive by default gives you a link to a web ui that allows you to download a file NOT to the file directly. There is a way to change the link to point directly to the file as of 2018 as this may change, please search google for a solution. returns: a request object """ auth = 'Bearer ' + self.check_for_token(token) dummy_files = {'type': (None, 'text-intent'), 'path':(None, file_url)} h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url r = requests.post(the_url, headers=h, files=dummy_files) return r
[ "def", "create_language_dataset_from_url", "(", "self", ",", "file_url", ",", "token", "=", "None", ",", "url", "=", "API_CREATE_LANGUAGE_DATASET", ")", ":", "auth", "=", "'Bearer '", "+", "self", ".", "check_for_token", "(", "token", ")", "dummy_files", "=", ...
Creates a dataset from a publicly accessible file stored in the cloud. :param file_url: string, in the form of a URL to a file accessible on the cloud. Popular options include Dropbox, AWS S3, Google Drive. warning: Google Drive by default gives you a link to a web ui that allows you to download a file NOT to the file directly. There is a way to change the link to point directly to the file as of 2018 as this may change, please search google for a solution. returns: a request object
[ "Creates", "a", "dataset", "from", "a", "publicly", "accessible", "file", "stored", "in", "the", "cloud", ".", ":", "param", "file_url", ":", "string", "in", "the", "form", "of", "a", "URL", "to", "a", "file", "accessible", "on", "the", "cloud", ".", "...
train
https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L242-L257
feliperyan/EinsteinVisionPython
EinsteinVision/EinsteinVision.py
EinsteinVisionService.train_language_model_from_dataset
def train_language_model_from_dataset(self, dataset_id, name, token=None, url=API_TRAIN_LANGUAGE_MODEL): """ Trains a model given a dataset and its ID. :param dataset_id: string, the ID for a dataset you created previously. :param name: string, name for your model. returns: a request object """ auth = 'Bearer ' + self.check_for_token(token) dummy_files = {'name': (None, name), 'datasetId':(None, dataset_id)} h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url r = requests.post(the_url, headers=h, files=dummy_files) return r
python
def train_language_model_from_dataset(self, dataset_id, name, token=None, url=API_TRAIN_LANGUAGE_MODEL): """ Trains a model given a dataset and its ID. :param dataset_id: string, the ID for a dataset you created previously. :param name: string, name for your model. returns: a request object """ auth = 'Bearer ' + self.check_for_token(token) dummy_files = {'name': (None, name), 'datasetId':(None, dataset_id)} h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url r = requests.post(the_url, headers=h, files=dummy_files) return r
[ "def", "train_language_model_from_dataset", "(", "self", ",", "dataset_id", ",", "name", ",", "token", "=", "None", ",", "url", "=", "API_TRAIN_LANGUAGE_MODEL", ")", ":", "auth", "=", "'Bearer '", "+", "self", ".", "check_for_token", "(", "token", ")", "dummy_...
Trains a model given a dataset and its ID. :param dataset_id: string, the ID for a dataset you created previously. :param name: string, name for your model. returns: a request object
[ "Trains", "a", "model", "given", "a", "dataset", "and", "its", "ID", ".", ":", "param", "dataset_id", ":", "string", "the", "ID", "for", "a", "dataset", "you", "created", "previously", ".", ":", "param", "name", ":", "string", "name", "for", "your", "m...
train
https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L263-L275
feliperyan/EinsteinVisionPython
EinsteinVision/EinsteinVision.py
EinsteinVisionService.get_language_model_status
def get_language_model_status(self, model_id, token=None, url=API_TRAIN_LANGUAGE_MODEL): """ Gets the status of your model, including whether the training has finished. :param model_id: string, the ID for a model you created previously. returns: a request object """ auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url + '/' + model_id r = requests.get(the_url, headers=h) return r
python
def get_language_model_status(self, model_id, token=None, url=API_TRAIN_LANGUAGE_MODEL): """ Gets the status of your model, including whether the training has finished. :param model_id: string, the ID for a model you created previously. returns: a request object """ auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url + '/' + model_id r = requests.get(the_url, headers=h) return r
[ "def", "get_language_model_status", "(", "self", ",", "model_id", ",", "token", "=", "None", ",", "url", "=", "API_TRAIN_LANGUAGE_MODEL", ")", ":", "auth", "=", "'Bearer '", "+", "self", ".", "check_for_token", "(", "token", ")", "h", "=", "{", "'Authorizati...
Gets the status of your model, including whether the training has finished. :param model_id: string, the ID for a model you created previously. returns: a request object
[ "Gets", "the", "status", "of", "your", "model", "including", "whether", "the", "training", "has", "finished", ".", ":", "param", "model_id", ":", "string", "the", "ID", "for", "a", "model", "you", "created", "previously", ".", "returns", ":", "a", "request...
train
https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L278-L288
feliperyan/EinsteinVisionPython
EinsteinVision/EinsteinVision.py
EinsteinVisionService.get_language_prediction_from_model
def get_language_prediction_from_model(self, model_id, document, token=None, url=API_GET_LANGUAGE_PREDICTION): """ Gets a prediction based on a body of text you send to a trained model you created previously. :param model_id: string, the ID for a model you created previously. :param document: string, a body of text to be classified. returns: a request object """ auth = 'Bearer ' + self.check_for_token(token) dummy_files = {'modelId': (None, model_id), 'document':(None, document)} h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url r = requests.post(the_url, headers=h, files=dummy_files) return r
python
def get_language_prediction_from_model(self, model_id, document, token=None, url=API_GET_LANGUAGE_PREDICTION): """ Gets a prediction based on a body of text you send to a trained model you created previously. :param model_id: string, the ID for a model you created previously. :param document: string, a body of text to be classified. returns: a request object """ auth = 'Bearer ' + self.check_for_token(token) dummy_files = {'modelId': (None, model_id), 'document':(None, document)} h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url r = requests.post(the_url, headers=h, files=dummy_files) return r
[ "def", "get_language_prediction_from_model", "(", "self", ",", "model_id", ",", "document", ",", "token", "=", "None", ",", "url", "=", "API_GET_LANGUAGE_PREDICTION", ")", ":", "auth", "=", "'Bearer '", "+", "self", ".", "check_for_token", "(", "token", ")", "...
Gets a prediction based on a body of text you send to a trained model you created previously. :param model_id: string, the ID for a model you created previously. :param document: string, a body of text to be classified. returns: a request object
[ "Gets", "a", "prediction", "based", "on", "a", "body", "of", "text", "you", "send", "to", "a", "trained", "model", "you", "created", "previously", ".", ":", "param", "model_id", ":", "string", "the", "ID", "for", "a", "model", "you", "created", "previous...
train
https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L291-L303
feliperyan/EinsteinVisionPython
EinsteinVision/EinsteinVision.py
EinsteinVisionService.parse_rectlabel_app_output
def parse_rectlabel_app_output(self): """ Internal use mostly, finds all .json files in the current folder expecting them to all have been outputted by the RectLabel app parses each file returning finally an array representing a csv file where each element is a row and the 1st element [0] is the column headers. Could be useful for subsequent string manipulation therefore not prefixed with an underscore RectLabel info: https://rectlabel.com/ """ # get json files only files = [] files = [f for f in os.listdir() if f[-5:] == '.json'] if len(files) == 0: print('No json files found in this directory') return None max_boxes = 0 rows = [] for each_file in files: f = open(each_file, 'r') j = f.read() j = json.loads(j) f.close() # running count of the # of boxes. if len(j['objects']) > max_boxes: max_boxes = len(j['objects']) # Each json file will end up being a row # set labels row = [] for o in j['objects']: labels = {} labels['label'] = o['label'] labels['x'] = o['x_y_w_h'][0] labels['y'] = o['x_y_w_h'][1] labels['width'] = o['x_y_w_h'][2] labels['height'] = o['x_y_w_h'][3] # String manipulation for csv labels_right_format = '\"' + json.dumps(labels).replace('"', '\"\"') + '\"' row.append(labels_right_format) row.insert(0, '\"' + j['filename'] + '\"') rows.append(row) # one array element per row rows = [','.join(i) for i in rows] header = '\"image\"' for box_num in range(0, max_boxes): header += ', \"box\"' + str(box_num) rows.insert(0, header) return rows
python
def parse_rectlabel_app_output(self): """ Internal use mostly, finds all .json files in the current folder expecting them to all have been outputted by the RectLabel app parses each file returning finally an array representing a csv file where each element is a row and the 1st element [0] is the column headers. Could be useful for subsequent string manipulation therefore not prefixed with an underscore RectLabel info: https://rectlabel.com/ """ # get json files only files = [] files = [f for f in os.listdir() if f[-5:] == '.json'] if len(files) == 0: print('No json files found in this directory') return None max_boxes = 0 rows = [] for each_file in files: f = open(each_file, 'r') j = f.read() j = json.loads(j) f.close() # running count of the # of boxes. if len(j['objects']) > max_boxes: max_boxes = len(j['objects']) # Each json file will end up being a row # set labels row = [] for o in j['objects']: labels = {} labels['label'] = o['label'] labels['x'] = o['x_y_w_h'][0] labels['y'] = o['x_y_w_h'][1] labels['width'] = o['x_y_w_h'][2] labels['height'] = o['x_y_w_h'][3] # String manipulation for csv labels_right_format = '\"' + json.dumps(labels).replace('"', '\"\"') + '\"' row.append(labels_right_format) row.insert(0, '\"' + j['filename'] + '\"') rows.append(row) # one array element per row rows = [','.join(i) for i in rows] header = '\"image\"' for box_num in range(0, max_boxes): header += ', \"box\"' + str(box_num) rows.insert(0, header) return rows
[ "def", "parse_rectlabel_app_output", "(", "self", ")", ":", "# get json files only", "files", "=", "[", "]", "files", "=", "[", "f", "for", "f", "in", "os", ".", "listdir", "(", ")", "if", "f", "[", "-", "5", ":", "]", "==", "'.json'", "]", "if", "...
Internal use mostly, finds all .json files in the current folder expecting them to all have been outputted by the RectLabel app parses each file returning finally an array representing a csv file where each element is a row and the 1st element [0] is the column headers. Could be useful for subsequent string manipulation therefore not prefixed with an underscore RectLabel info: https://rectlabel.com/
[ "Internal", "use", "mostly", "finds", "all", ".", "json", "files", "in", "the", "current", "folder", "expecting", "them", "to", "all", "have", "been", "outputted", "by", "the", "RectLabel", "app", "parses", "each", "file", "returning", "finally", "an", "arra...
train
https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L306-L364
feliperyan/EinsteinVisionPython
EinsteinVision/EinsteinVision.py
EinsteinVisionService.save_parsed_data_to_csv
def save_parsed_data_to_csv(self, output_filename='output.csv'): """ Outputs a csv file in accordance with parse_rectlabel_app_output method. This csv file is meant to accompany a set of pictures files in the creation of an Object Detection dataset. :param output_filename string, default makes sense, but for your convenience. """ result = self.parse_rectlabel_app_output() ff = open(output_filename, 'w', encoding='utf8') for line in result: ff.write(line + '\n') ff.close()
python
def save_parsed_data_to_csv(self, output_filename='output.csv'): """ Outputs a csv file in accordance with parse_rectlabel_app_output method. This csv file is meant to accompany a set of pictures files in the creation of an Object Detection dataset. :param output_filename string, default makes sense, but for your convenience. """ result = self.parse_rectlabel_app_output() ff = open(output_filename, 'w', encoding='utf8') for line in result: ff.write(line + '\n') ff.close()
[ "def", "save_parsed_data_to_csv", "(", "self", ",", "output_filename", "=", "'output.csv'", ")", ":", "result", "=", "self", ".", "parse_rectlabel_app_output", "(", ")", "ff", "=", "open", "(", "output_filename", ",", "'w'", ",", "encoding", "=", "'utf8'", ")"...
Outputs a csv file in accordance with parse_rectlabel_app_output method. This csv file is meant to accompany a set of pictures files in the creation of an Object Detection dataset. :param output_filename string, default makes sense, but for your convenience.
[ "Outputs", "a", "csv", "file", "in", "accordance", "with", "parse_rectlabel_app_output", "method", ".", "This", "csv", "file", "is", "meant", "to", "accompany", "a", "set", "of", "pictures", "files", "in", "the", "creation", "of", "an", "Object", "Detection", ...
train
https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L367-L379
feliperyan/EinsteinVisionPython
EinsteinVision/EinsteinVision.py
EinsteinVisionService.XML_save_parsed_data_to_csv
def XML_save_parsed_data_to_csv(self, output_filename='output.csv'): """ Outputs a csv file in accordance with parse_rectlabel_app_output method. This csv file is meant to accompany a set of pictures files in the creation of an Object Detection dataset. :param output_filename string, default makes sense, but for your convenience. """ result = self.XML_parse_rectlabel_app_output() ff = open(output_filename, 'w', encoding='utf8') for line in result: ff.write(line + '\n') ff.close()
python
def XML_save_parsed_data_to_csv(self, output_filename='output.csv'): """ Outputs a csv file in accordance with parse_rectlabel_app_output method. This csv file is meant to accompany a set of pictures files in the creation of an Object Detection dataset. :param output_filename string, default makes sense, but for your convenience. """ result = self.XML_parse_rectlabel_app_output() ff = open(output_filename, 'w', encoding='utf8') for line in result: ff.write(line + '\n') ff.close()
[ "def", "XML_save_parsed_data_to_csv", "(", "self", ",", "output_filename", "=", "'output.csv'", ")", ":", "result", "=", "self", ".", "XML_parse_rectlabel_app_output", "(", ")", "ff", "=", "open", "(", "output_filename", ",", "'w'", ",", "encoding", "=", "'utf8'...
Outputs a csv file in accordance with parse_rectlabel_app_output method. This csv file is meant to accompany a set of pictures files in the creation of an Object Detection dataset. :param output_filename string, default makes sense, but for your convenience.
[ "Outputs", "a", "csv", "file", "in", "accordance", "with", "parse_rectlabel_app_output", "method", ".", "This", "csv", "file", "is", "meant", "to", "accompany", "a", "set", "of", "pictures", "files", "in", "the", "creation", "of", "an", "Object", "Detection", ...
train
https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L382-L394
bovee/Aston
aston/trace/parser.py
tokens
def tokens(istr): """ Same as tokenize, but returns only tokens (and at all parantheses levels). """ # make a list of all alphanumeric tokens toks = re.findall(r'[^\*\\\+\-\^\(\)]+\(?', istr) # remove the functions return [t for t in toks if not t.endswith('(')]
python
def tokens(istr): """ Same as tokenize, but returns only tokens (and at all parantheses levels). """ # make a list of all alphanumeric tokens toks = re.findall(r'[^\*\\\+\-\^\(\)]+\(?', istr) # remove the functions return [t for t in toks if not t.endswith('(')]
[ "def", "tokens", "(", "istr", ")", ":", "# make a list of all alphanumeric tokens", "toks", "=", "re", ".", "findall", "(", "r'[^\\*\\\\\\+\\-\\^\\(\\)]+\\(?'", ",", "istr", ")", "# remove the functions", "return", "[", "t", "for", "t", "in", "toks", "if", "not", ...
Same as tokenize, but returns only tokens (and at all parantheses levels).
[ "Same", "as", "tokenize", "but", "returns", "only", "tokens", "(", "and", "at", "all", "parantheses", "levels", ")", "." ]
train
https://github.com/bovee/Aston/blob/007630fdf074690373d03398fe818260d3d3cf5a/aston/trace/parser.py#L29-L39
bovee/Aston
aston/trace/parser.py
istr_type
def istr_type(istr): """ Given an "ion" specification, determine its "type", e.g. 1D, Events, etc. """ data = set(i.rstrip('0123456789') for i in tokens(istr)) has_events = not data.isdisjoint(istr_type_evts) has_2d = not data.isdisjoint(istr_type_2d) has_1d = data.difference(istr_type_evts).difference(istr_type_2d) != set() if has_events and not (has_1d or has_2d): return 'events' elif has_1d and not has_events: return '1d' elif has_2d and not (has_events or has_1d): return '2d' else: return None
python
def istr_type(istr): """ Given an "ion" specification, determine its "type", e.g. 1D, Events, etc. """ data = set(i.rstrip('0123456789') for i in tokens(istr)) has_events = not data.isdisjoint(istr_type_evts) has_2d = not data.isdisjoint(istr_type_2d) has_1d = data.difference(istr_type_evts).difference(istr_type_2d) != set() if has_events and not (has_1d or has_2d): return 'events' elif has_1d and not has_events: return '1d' elif has_2d and not (has_events or has_1d): return '2d' else: return None
[ "def", "istr_type", "(", "istr", ")", ":", "data", "=", "set", "(", "i", ".", "rstrip", "(", "'0123456789'", ")", "for", "i", "in", "tokens", "(", "istr", ")", ")", "has_events", "=", "not", "data", ".", "isdisjoint", "(", "istr_type_evts", ")", "has...
Given an "ion" specification, determine its "type", e.g. 1D, Events, etc.
[ "Given", "an", "ion", "specification", "determine", "its", "type", "e", ".", "g", ".", "1D", "Events", "etc", "." ]
train
https://github.com/bovee/Aston/blob/007630fdf074690373d03398fe818260d3d3cf5a/aston/trace/parser.py#L42-L58
bovee/Aston
aston/trace/parser.py
is_parans_exp
def is_parans_exp(istr): """ Determines if an expression is a valid function "call" """ fxn = istr.split('(')[0] if (not fxn.isalnum() and fxn != '(') or istr[-1] != ')': return False plevel = 1 for c in '('.join(istr[:-1].split('(')[1:]): if c == '(': plevel += 1 elif c == ')': plevel -= 1 if plevel == 0: return False return True
python
def is_parans_exp(istr): """ Determines if an expression is a valid function "call" """ fxn = istr.split('(')[0] if (not fxn.isalnum() and fxn != '(') or istr[-1] != ')': return False plevel = 1 for c in '('.join(istr[:-1].split('(')[1:]): if c == '(': plevel += 1 elif c == ')': plevel -= 1 if plevel == 0: return False return True
[ "def", "is_parans_exp", "(", "istr", ")", ":", "fxn", "=", "istr", ".", "split", "(", "'('", ")", "[", "0", "]", "if", "(", "not", "fxn", ".", "isalnum", "(", ")", "and", "fxn", "!=", "'('", ")", "or", "istr", "[", "-", "1", "]", "!=", "')'",...
Determines if an expression is a valid function "call"
[ "Determines", "if", "an", "expression", "is", "a", "valid", "function", "call" ]
train
https://github.com/bovee/Aston/blob/007630fdf074690373d03398fe818260d3d3cf5a/aston/trace/parser.py#L115-L130
bovee/Aston
aston/trace/parser.py
parse_ion_string
def parse_ion_string(istr, analyses, twin=None): """ Recursive string parser that handles "ion" strings. """ if istr.strip() == '': return Trace() # remove (unnessary?) pluses from the front # TODO: plus should be abs? istr = istr.lstrip('+') # invert it if preceded by a minus sign if istr[0] == '-': return -parse_ion_string(istr[1:], analyses, twin) # this is a function or paranthesized expression if is_parans_exp(istr): if ')' not in istr: # unbalanced parantheses pass fxn = istr.split('(')[0] args = istr[istr.find('(') + 1:istr.find(')')].split(',') if fxn == '': # strip out the parantheses and continue istr = args[0] else: ts = parse_ion_string(args[0], analyses, twin) # FIXME return ts # return fxn_resolver(ts, fxn, *args[1:]) # all the complicated math is gone, so simple lookup if set(istr).intersection(set('+-/*()')) == set(): if istr in SHORTCUTS: # allow some shortcuts to pull out common ions return parse_ion_string(SHORTCUTS[istr], analyses, twin) elif istr[0] == '!' and all(i in '0123456789.' for i in istr[1:]): # TODO: should this handle negative numbers? return float(istr[1:]) elif istr == '!pi': return np.pi elif istr == '!e': return np.e else: return trace_resolver(istr, analyses, twin) # go through and handle operators for token in '/*+-^': if len(tokenize(istr, token)) != 1: ts = tokenize(istr, token) s = parse_ion_string(ts[0], analyses, twin) for t in ts[1:]: if token == '/': s /= parse_ion_string(t, analyses, twin) elif token == '*': s *= parse_ion_string(t, analyses, twin) elif token == '+': s += parse_ion_string(t, analyses, twin) elif token == '-': s -= parse_ion_string(t, analyses, twin) elif token == '^': s **= parse_ion_string(t, analyses, twin) return s raise Exception('Parser hit a point it shouldn\'t have!')
python
def parse_ion_string(istr, analyses, twin=None): """ Recursive string parser that handles "ion" strings. """ if istr.strip() == '': return Trace() # remove (unnessary?) pluses from the front # TODO: plus should be abs? istr = istr.lstrip('+') # invert it if preceded by a minus sign if istr[0] == '-': return -parse_ion_string(istr[1:], analyses, twin) # this is a function or paranthesized expression if is_parans_exp(istr): if ')' not in istr: # unbalanced parantheses pass fxn = istr.split('(')[0] args = istr[istr.find('(') + 1:istr.find(')')].split(',') if fxn == '': # strip out the parantheses and continue istr = args[0] else: ts = parse_ion_string(args[0], analyses, twin) # FIXME return ts # return fxn_resolver(ts, fxn, *args[1:]) # all the complicated math is gone, so simple lookup if set(istr).intersection(set('+-/*()')) == set(): if istr in SHORTCUTS: # allow some shortcuts to pull out common ions return parse_ion_string(SHORTCUTS[istr], analyses, twin) elif istr[0] == '!' and all(i in '0123456789.' for i in istr[1:]): # TODO: should this handle negative numbers? return float(istr[1:]) elif istr == '!pi': return np.pi elif istr == '!e': return np.e else: return trace_resolver(istr, analyses, twin) # go through and handle operators for token in '/*+-^': if len(tokenize(istr, token)) != 1: ts = tokenize(istr, token) s = parse_ion_string(ts[0], analyses, twin) for t in ts[1:]: if token == '/': s /= parse_ion_string(t, analyses, twin) elif token == '*': s *= parse_ion_string(t, analyses, twin) elif token == '+': s += parse_ion_string(t, analyses, twin) elif token == '-': s -= parse_ion_string(t, analyses, twin) elif token == '^': s **= parse_ion_string(t, analyses, twin) return s raise Exception('Parser hit a point it shouldn\'t have!')
[ "def", "parse_ion_string", "(", "istr", ",", "analyses", ",", "twin", "=", "None", ")", ":", "if", "istr", ".", "strip", "(", ")", "==", "''", ":", "return", "Trace", "(", ")", "# remove (unnessary?) pluses from the front", "# TODO: plus should be abs?", "istr",...
Recursive string parser that handles "ion" strings.
[ "Recursive", "string", "parser", "that", "handles", "ion", "strings", "." ]
train
https://github.com/bovee/Aston/blob/007630fdf074690373d03398fe818260d3d3cf5a/aston/trace/parser.py#L238-L302
PedalPi/Application
application/controller/current_controller.py
CurrentController.set_pedalboard
def set_pedalboard(self, pedalboard, notify=True, force=False): """ Set the current :class:`.Pedalboard` for the pedalboard only if the ``pedalboard != current_pedalboard or force`` Is also possible unload the current pedalboard data with replacing it for ``None``:: >>> current_controller.set_pedalboard(None) .. warning:: Changing the current pedalboard to Nonw, will not be able to call methods to change the pedalboard based in the current, like :meth:`.to_before_pedalboard`, :meth:`.to_next_pedalboard`, :meth:`.to_before_bank` and :meth:`.to_next_bank` :param Pedalboard pedalboard: New current pedalboard :param bool notify: If false, not notify change for :class:`.UpdatesObserver` instances registered in :class:`.Application` :param bool force: Force set pedalboard """ if pedalboard is not None and pedalboard.bank is None: raise CurrentPedalboardError('Pedalboard {} has not added in any bank'.format(pedalboard)) if pedalboard == self.pedalboard and not force: return self._pedalboard = pedalboard self._device_controller.pedalboard = pedalboard self._save_current_pedalboard() if notify: self.app.components_observer.on_current_pedalboard_changed(self.pedalboard)
python
def set_pedalboard(self, pedalboard, notify=True, force=False): """ Set the current :class:`.Pedalboard` for the pedalboard only if the ``pedalboard != current_pedalboard or force`` Is also possible unload the current pedalboard data with replacing it for ``None``:: >>> current_controller.set_pedalboard(None) .. warning:: Changing the current pedalboard to Nonw, will not be able to call methods to change the pedalboard based in the current, like :meth:`.to_before_pedalboard`, :meth:`.to_next_pedalboard`, :meth:`.to_before_bank` and :meth:`.to_next_bank` :param Pedalboard pedalboard: New current pedalboard :param bool notify: If false, not notify change for :class:`.UpdatesObserver` instances registered in :class:`.Application` :param bool force: Force set pedalboard """ if pedalboard is not None and pedalboard.bank is None: raise CurrentPedalboardError('Pedalboard {} has not added in any bank'.format(pedalboard)) if pedalboard == self.pedalboard and not force: return self._pedalboard = pedalboard self._device_controller.pedalboard = pedalboard self._save_current_pedalboard() if notify: self.app.components_observer.on_current_pedalboard_changed(self.pedalboard)
[ "def", "set_pedalboard", "(", "self", ",", "pedalboard", ",", "notify", "=", "True", ",", "force", "=", "False", ")", ":", "if", "pedalboard", "is", "not", "None", "and", "pedalboard", ".", "bank", "is", "None", ":", "raise", "CurrentPedalboardError", "(",...
Set the current :class:`.Pedalboard` for the pedalboard only if the ``pedalboard != current_pedalboard or force`` Is also possible unload the current pedalboard data with replacing it for ``None``:: >>> current_controller.set_pedalboard(None) .. warning:: Changing the current pedalboard to Nonw, will not be able to call methods to change the pedalboard based in the current, like :meth:`.to_before_pedalboard`, :meth:`.to_next_pedalboard`, :meth:`.to_before_bank` and :meth:`.to_next_bank` :param Pedalboard pedalboard: New current pedalboard :param bool notify: If false, not notify change for :class:`.UpdatesObserver` instances registered in :class:`.Application` :param bool force: Force set pedalboard
[ "Set", "the", "current", ":", "class", ":", ".", "Pedalboard", "for", "the", "pedalboard", "only", "if", "the", "pedalboard", "!", "=", "current_pedalboard", "or", "force" ]
train
https://github.com/PedalPi/Application/blob/3fdf6f97cfef97a7f1d90a5881dd04324c229f9d/application/controller/current_controller.py#L63-L95
PedalPi/Application
application/controller/current_controller.py
CurrentController.to_before_pedalboard
def to_before_pedalboard(self): """ Change the current :class:`.Pedalboard` for the previous pedalboard. If the current pedalboard is the first in the current :class:`Bank`, the current pedalboard is will be the **last of the current Bank**. .. warning:: If the current :attr:`.pedalboard` is ``None``, a :class:`.CurrentPedalboardError` is raised. """ if self.pedalboard is None: raise CurrentPedalboardError('The current pedalboard is None') before_index = self.pedalboard.index - 1 if before_index == -1: before_index = len(self.bank.pedalboards) - 1 self.set_pedalboard(self.bank.pedalboards[before_index])
python
def to_before_pedalboard(self): """ Change the current :class:`.Pedalboard` for the previous pedalboard. If the current pedalboard is the first in the current :class:`Bank`, the current pedalboard is will be the **last of the current Bank**. .. warning:: If the current :attr:`.pedalboard` is ``None``, a :class:`.CurrentPedalboardError` is raised. """ if self.pedalboard is None: raise CurrentPedalboardError('The current pedalboard is None') before_index = self.pedalboard.index - 1 if before_index == -1: before_index = len(self.bank.pedalboards) - 1 self.set_pedalboard(self.bank.pedalboards[before_index])
[ "def", "to_before_pedalboard", "(", "self", ")", ":", "if", "self", ".", "pedalboard", "is", "None", ":", "raise", "CurrentPedalboardError", "(", "'The current pedalboard is None'", ")", "before_index", "=", "self", ".", "pedalboard", ".", "index", "-", "1", "if...
Change the current :class:`.Pedalboard` for the previous pedalboard. If the current pedalboard is the first in the current :class:`Bank`, the current pedalboard is will be the **last of the current Bank**. .. warning:: If the current :attr:`.pedalboard` is ``None``, a :class:`.CurrentPedalboardError` is raised.
[ "Change", "the", "current", ":", "class", ":", ".", "Pedalboard", "for", "the", "previous", "pedalboard", "." ]
train
https://github.com/PedalPi/Application/blob/3fdf6f97cfef97a7f1d90a5881dd04324c229f9d/application/controller/current_controller.py#L130-L148
PedalPi/Application
application/controller/current_controller.py
CurrentController.to_next_pedalboard
def to_next_pedalboard(self): """ Change the current :class:`.Pedalboard` for the next pedalboard. If the current pedalboard is the last in the current :class:`.Bank`, the current pedalboard is will be the **first of the current Bank** .. warning:: If the current :attr:`.pedalboard` is ``None``, a :class:`.CurrentPedalboardError` is raised. """ if self.pedalboard is None: raise CurrentPedalboardError('The current pedalboard is None') next_index = self.pedalboard.index + 1 if next_index == len(self.bank.pedalboards): next_index = 0 self.set_pedalboard(self.bank.pedalboards[next_index])
python
def to_next_pedalboard(self): """ Change the current :class:`.Pedalboard` for the next pedalboard. If the current pedalboard is the last in the current :class:`.Bank`, the current pedalboard is will be the **first of the current Bank** .. warning:: If the current :attr:`.pedalboard` is ``None``, a :class:`.CurrentPedalboardError` is raised. """ if self.pedalboard is None: raise CurrentPedalboardError('The current pedalboard is None') next_index = self.pedalboard.index + 1 if next_index == len(self.bank.pedalboards): next_index = 0 self.set_pedalboard(self.bank.pedalboards[next_index])
[ "def", "to_next_pedalboard", "(", "self", ")", ":", "if", "self", ".", "pedalboard", "is", "None", ":", "raise", "CurrentPedalboardError", "(", "'The current pedalboard is None'", ")", "next_index", "=", "self", ".", "pedalboard", ".", "index", "+", "1", "if", ...
Change the current :class:`.Pedalboard` for the next pedalboard. If the current pedalboard is the last in the current :class:`.Bank`, the current pedalboard is will be the **first of the current Bank** .. warning:: If the current :attr:`.pedalboard` is ``None``, a :class:`.CurrentPedalboardError` is raised.
[ "Change", "the", "current", ":", "class", ":", ".", "Pedalboard", "for", "the", "next", "pedalboard", "." ]
train
https://github.com/PedalPi/Application/blob/3fdf6f97cfef97a7f1d90a5881dd04324c229f9d/application/controller/current_controller.py#L150-L168
PedalPi/Application
application/controller/current_controller.py
CurrentController.to_before_bank
def to_before_bank(self): """ Change the current :class:`Bank` for the before bank. If the current bank is the first, the current bank is will be the last bank. The current pedalboard will be the first pedalboard of the new current bank **if it contains any pedalboard**, else will be ``None``. .. warning:: If the current :attr:`.pedalboard` is ``None``, a :class:`.CurrentPedalboardError` is raised. """ if self.pedalboard is None: raise CurrentPedalboardError('The current pedalboard is None') before_index = self.bank.index - 1 if before_index == -1: before_index = len(self._manager.banks) - 1 self.set_bank(self._manager.banks[before_index])
python
def to_before_bank(self): """ Change the current :class:`Bank` for the before bank. If the current bank is the first, the current bank is will be the last bank. The current pedalboard will be the first pedalboard of the new current bank **if it contains any pedalboard**, else will be ``None``. .. warning:: If the current :attr:`.pedalboard` is ``None``, a :class:`.CurrentPedalboardError` is raised. """ if self.pedalboard is None: raise CurrentPedalboardError('The current pedalboard is None') before_index = self.bank.index - 1 if before_index == -1: before_index = len(self._manager.banks) - 1 self.set_bank(self._manager.banks[before_index])
[ "def", "to_before_bank", "(", "self", ")", ":", "if", "self", ".", "pedalboard", "is", "None", ":", "raise", "CurrentPedalboardError", "(", "'The current pedalboard is None'", ")", "before_index", "=", "self", ".", "bank", ".", "index", "-", "1", "if", "before...
Change the current :class:`Bank` for the before bank. If the current bank is the first, the current bank is will be the last bank. The current pedalboard will be the first pedalboard of the new current bank **if it contains any pedalboard**, else will be ``None``. .. warning:: If the current :attr:`.pedalboard` is ``None``, a :class:`.CurrentPedalboardError` is raised.
[ "Change", "the", "current", ":", "class", ":", "Bank", "for", "the", "before", "bank", ".", "If", "the", "current", "bank", "is", "the", "first", "the", "current", "bank", "is", "will", "be", "the", "last", "bank", "." ]
train
https://github.com/PedalPi/Application/blob/3fdf6f97cfef97a7f1d90a5881dd04324c229f9d/application/controller/current_controller.py#L170-L189
PedalPi/Application
application/controller/current_controller.py
CurrentController.to_next_bank
def to_next_bank(self): """ Change the current :class:`Bank` for the next bank. If the current bank is the last, the current bank is will be the first bank. The current pedalboard will be the first pedalboard of the new current bank **if it contains any pedalboard**, else will be ``None``. .. warning:: If the current :attr:`.pedalboard` is ``None``, a :class:`.CurrentPedalboardError` is raised. """ if self.pedalboard is None: raise CurrentPedalboardError('The current pedalboard is None') next_index = self.next_bank_index(self.bank.index) self.set_bank(self._manager.banks[next_index])
python
def to_next_bank(self): """ Change the current :class:`Bank` for the next bank. If the current bank is the last, the current bank is will be the first bank. The current pedalboard will be the first pedalboard of the new current bank **if it contains any pedalboard**, else will be ``None``. .. warning:: If the current :attr:`.pedalboard` is ``None``, a :class:`.CurrentPedalboardError` is raised. """ if self.pedalboard is None: raise CurrentPedalboardError('The current pedalboard is None') next_index = self.next_bank_index(self.bank.index) self.set_bank(self._manager.banks[next_index])
[ "def", "to_next_bank", "(", "self", ")", ":", "if", "self", ".", "pedalboard", "is", "None", ":", "raise", "CurrentPedalboardError", "(", "'The current pedalboard is None'", ")", "next_index", "=", "self", ".", "next_bank_index", "(", "self", ".", "bank", ".", ...
Change the current :class:`Bank` for the next bank. If the current bank is the last, the current bank is will be the first bank. The current pedalboard will be the first pedalboard of the new current bank **if it contains any pedalboard**, else will be ``None``. .. warning:: If the current :attr:`.pedalboard` is ``None``, a :class:`.CurrentPedalboardError` is raised.
[ "Change", "the", "current", ":", "class", ":", "Bank", "for", "the", "next", "bank", ".", "If", "the", "current", "bank", "is", "the", "last", "the", "current", "bank", "is", "will", "be", "the", "first", "bank", "." ]
train
https://github.com/PedalPi/Application/blob/3fdf6f97cfef97a7f1d90a5881dd04324c229f9d/application/controller/current_controller.py#L191-L208
PedalPi/Application
application/controller/current_controller.py
CurrentController.set_bank
def set_bank(self, bank, try_preserve_index=False): """ Set the current :class:`Bank` for the bank only if the ``bank != current_bank`` The current pedalboard will be the first pedalboard of the new current bank **if it contains any pedalboard**, else will be ``None``. .. warning:: If the current :attr:`.pedalboard` is ``None``, a :class:`.CurrentPedalboardError` is raised. :param Bank bank: Bank that will be the current :param bool try_preserve_index: Tries to preserve the index of the current pedalboard when changing the bank. That is, if the current pedalboard is the fifth, when updating the bank, it will attempt to place the fifth pedalboard of the new bank as the current one. If it does not get (``len(bank.pedalboards) < 6``) the current pedalboard will be the first pedalboard. """ if bank not in self._manager: raise CurrentPedalboardError('Bank {} has not added in banks manager'.format(bank)) if self.bank == bank: return if bank.pedalboards: pedalboard = self._equivalent_pedalboard(bank) if try_preserve_index else bank.pedalboards[0] self.set_pedalboard(pedalboard) else: self.set_pedalboard(None)
python
def set_bank(self, bank, try_preserve_index=False): """ Set the current :class:`Bank` for the bank only if the ``bank != current_bank`` The current pedalboard will be the first pedalboard of the new current bank **if it contains any pedalboard**, else will be ``None``. .. warning:: If the current :attr:`.pedalboard` is ``None``, a :class:`.CurrentPedalboardError` is raised. :param Bank bank: Bank that will be the current :param bool try_preserve_index: Tries to preserve the index of the current pedalboard when changing the bank. That is, if the current pedalboard is the fifth, when updating the bank, it will attempt to place the fifth pedalboard of the new bank as the current one. If it does not get (``len(bank.pedalboards) < 6``) the current pedalboard will be the first pedalboard. """ if bank not in self._manager: raise CurrentPedalboardError('Bank {} has not added in banks manager'.format(bank)) if self.bank == bank: return if bank.pedalboards: pedalboard = self._equivalent_pedalboard(bank) if try_preserve_index else bank.pedalboards[0] self.set_pedalboard(pedalboard) else: self.set_pedalboard(None)
[ "def", "set_bank", "(", "self", ",", "bank", ",", "try_preserve_index", "=", "False", ")", ":", "if", "bank", "not", "in", "self", ".", "_manager", ":", "raise", "CurrentPedalboardError", "(", "'Bank {} has not added in banks manager'", ".", "format", "(", "bank...
Set the current :class:`Bank` for the bank only if the ``bank != current_bank`` The current pedalboard will be the first pedalboard of the new current bank **if it contains any pedalboard**, else will be ``None``. .. warning:: If the current :attr:`.pedalboard` is ``None``, a :class:`.CurrentPedalboardError` is raised. :param Bank bank: Bank that will be the current :param bool try_preserve_index: Tries to preserve the index of the current pedalboard when changing the bank. That is, if the current pedalboard is the fifth, when updating the bank, it will attempt to place the fifth pedalboard of the new bank as the current one. If it does not get (``len(bank.pedalboards) < 6``) the current pedalboard will be the first pedalboard.
[ "Set", "the", "current", ":", "class", ":", "Bank", "for", "the", "bank", "only", "if", "the", "bank", "!", "=", "current_bank" ]
train
https://github.com/PedalPi/Application/blob/3fdf6f97cfef97a7f1d90a5881dd04324c229f9d/application/controller/current_controller.py#L217-L247
Locu/chronology
kronos/kronos/core/validator.py
_validate_and_get_value
def _validate_and_get_value(options, options_name, key, _type): """ Check that `options` has a value for `key` with type `_type`. Return that value. `options_name` is a string representing a human-readable name for `options` to be used when printing errors. """ if isinstance(options, dict): has = lambda k: k in options get = lambda k: options[k] elif isinstance(options, object): has = lambda k: hasattr(options, k) get = lambda k: getattr(options, k) else: raise ImproperlyConfigured( '`{}` must be a dictionary-like object.'.format(options_name)) if not has(key): raise ImproperlyConfigured( '`{}` must be specified in `{}`'.format(key, options_name)) value = get(key) if not isinstance(value, _type): raise ImproperlyConfigured( '`{}` in `{}` must be a {}'.format(key, options_name, repr(_type))) return value
python
def _validate_and_get_value(options, options_name, key, _type): """ Check that `options` has a value for `key` with type `_type`. Return that value. `options_name` is a string representing a human-readable name for `options` to be used when printing errors. """ if isinstance(options, dict): has = lambda k: k in options get = lambda k: options[k] elif isinstance(options, object): has = lambda k: hasattr(options, k) get = lambda k: getattr(options, k) else: raise ImproperlyConfigured( '`{}` must be a dictionary-like object.'.format(options_name)) if not has(key): raise ImproperlyConfigured( '`{}` must be specified in `{}`'.format(key, options_name)) value = get(key) if not isinstance(value, _type): raise ImproperlyConfigured( '`{}` in `{}` must be a {}'.format(key, options_name, repr(_type))) return value
[ "def", "_validate_and_get_value", "(", "options", ",", "options_name", ",", "key", ",", "_type", ")", ":", "if", "isinstance", "(", "options", ",", "dict", ")", ":", "has", "=", "lambda", "k", ":", "k", "in", "options", "get", "=", "lambda", "k", ":", ...
Check that `options` has a value for `key` with type `_type`. Return that value. `options_name` is a string representing a human-readable name for `options` to be used when printing errors.
[ "Check", "that", "options", "has", "a", "value", "for", "key", "with", "type", "_type", ".", "Return", "that", "value", ".", "options_name", "is", "a", "string", "representing", "a", "human", "-", "readable", "name", "for", "options", "to", "be", "used", ...
train
https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/kronos/kronos/core/validator.py#L18-L43
Locu/chronology
kronos/kronos/core/validator.py
validate_event_and_assign_id
def validate_event_and_assign_id(event): """ Ensure that the event has a valid time. Assign a random UUID based on the event time. """ event_time = event.get(TIMESTAMP_FIELD) if event_time is None: event[TIMESTAMP_FIELD] = event_time = epoch_time_to_kronos_time(time.time()) elif type(event_time) not in (int, long): raise InvalidEventTime(event_time) # Generate a uuid1-like sequence from the event time with the non-time bytes # set to random values. _id = uuid_from_kronos_time(event_time) event[ID_FIELD] = str(_id) return _id, event
python
def validate_event_and_assign_id(event): """ Ensure that the event has a valid time. Assign a random UUID based on the event time. """ event_time = event.get(TIMESTAMP_FIELD) if event_time is None: event[TIMESTAMP_FIELD] = event_time = epoch_time_to_kronos_time(time.time()) elif type(event_time) not in (int, long): raise InvalidEventTime(event_time) # Generate a uuid1-like sequence from the event time with the non-time bytes # set to random values. _id = uuid_from_kronos_time(event_time) event[ID_FIELD] = str(_id) return _id, event
[ "def", "validate_event_and_assign_id", "(", "event", ")", ":", "event_time", "=", "event", ".", "get", "(", "TIMESTAMP_FIELD", ")", "if", "event_time", "is", "None", ":", "event", "[", "TIMESTAMP_FIELD", "]", "=", "event_time", "=", "epoch_time_to_kronos_time", ...
Ensure that the event has a valid time. Assign a random UUID based on the event time.
[ "Ensure", "that", "the", "event", "has", "a", "valid", "time", ".", "Assign", "a", "random", "UUID", "based", "on", "the", "event", "time", "." ]
train
https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/kronos/kronos/core/validator.py#L46-L62
Locu/chronology
kronos/kronos/core/validator.py
validate_stream
def validate_stream(stream): """ Check that the stream name is well-formed. """ if not STREAM_REGEX.match(stream) or len(stream) > MAX_STREAM_LENGTH: raise InvalidStreamName(stream)
python
def validate_stream(stream): """ Check that the stream name is well-formed. """ if not STREAM_REGEX.match(stream) or len(stream) > MAX_STREAM_LENGTH: raise InvalidStreamName(stream)
[ "def", "validate_stream", "(", "stream", ")", ":", "if", "not", "STREAM_REGEX", ".", "match", "(", "stream", ")", "or", "len", "(", "stream", ")", ">", "MAX_STREAM_LENGTH", ":", "raise", "InvalidStreamName", "(", "stream", ")" ]
Check that the stream name is well-formed.
[ "Check", "that", "the", "stream", "name", "is", "well", "-", "formed", "." ]
train
https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/kronos/kronos/core/validator.py#L65-L70
Locu/chronology
kronos/kronos/core/validator.py
validate_storage_settings
def validate_storage_settings(storage_class, settings): """ Given a `storage_class` and a dictionary of `settings` to initialize it, this method verifies that all the settings are valid. """ if not isinstance(settings, dict): raise ImproperlyConfigured( '{}: storage class settings must be a dict'.format(storage_class)) if not hasattr(storage_class, 'SETTINGS_VALIDATORS'): raise NotImplementedError( '{}: storage class must define `SETTINGS_VALIDATORS`'.format( storage_class)) settings_validators = getattr(storage_class, 'SETTINGS_VALIDATORS') settings = settings.copy() settings.pop('backend', None) # No need to validate the `backend` key. invalid_settings = set(settings.keys()) - set(settings_validators.keys()) if invalid_settings: raise ImproperlyConfigured( '{}: invalid settings: {}'.format(storage_class, invalid_settings)) for setting, value in settings.iteritems(): if not settings_validators[setting](value): raise ImproperlyConfigured( '{}: invalid value for {}'.format(storage_class, setting))
python
def validate_storage_settings(storage_class, settings): """ Given a `storage_class` and a dictionary of `settings` to initialize it, this method verifies that all the settings are valid. """ if not isinstance(settings, dict): raise ImproperlyConfigured( '{}: storage class settings must be a dict'.format(storage_class)) if not hasattr(storage_class, 'SETTINGS_VALIDATORS'): raise NotImplementedError( '{}: storage class must define `SETTINGS_VALIDATORS`'.format( storage_class)) settings_validators = getattr(storage_class, 'SETTINGS_VALIDATORS') settings = settings.copy() settings.pop('backend', None) # No need to validate the `backend` key. invalid_settings = set(settings.keys()) - set(settings_validators.keys()) if invalid_settings: raise ImproperlyConfigured( '{}: invalid settings: {}'.format(storage_class, invalid_settings)) for setting, value in settings.iteritems(): if not settings_validators[setting](value): raise ImproperlyConfigured( '{}: invalid value for {}'.format(storage_class, setting))
[ "def", "validate_storage_settings", "(", "storage_class", ",", "settings", ")", ":", "if", "not", "isinstance", "(", "settings", ",", "dict", ")", ":", "raise", "ImproperlyConfigured", "(", "'{}: storage class settings must be a dict'", ".", "format", "(", "storage_cl...
Given a `storage_class` and a dictionary of `settings` to initialize it, this method verifies that all the settings are valid.
[ "Given", "a", "storage_class", "and", "a", "dictionary", "of", "settings", "to", "initialize", "it", "this", "method", "verifies", "that", "all", "the", "settings", "are", "valid", "." ]
train
https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/kronos/kronos/core/validator.py#L73-L98
Locu/chronology
kronos/kronos/core/validator.py
validate_settings
def validate_settings(settings): """ `settings` is either a dictionary or an object containing Kronos settings (e.g., the contents of conf/settings.py). This function checks that all required settings are present and valid. """ # Validate `storage` storage = _validate_and_get_value(settings, 'settings', 'storage', dict) for name, options in storage.iteritems(): if 'backend' not in options: raise ImproperlyConfigured( '`storage[\'{}\'] must contain a `backend` key'.format(name)) path = options['backend'] module, cls = path.rsplit('.', 1) module = import_module(module) if not hasattr(module, cls): raise NotImplementedError('`{}` not implemented.'.format(cls)) validate_storage_settings(getattr(module, cls), options) # Validate `streams_to_backends` namespace_to_streams_configuration = _validate_and_get_value( settings, 'settings', 'namespace_to_streams_configuration', dict) for namespace, prefix_confs in namespace_to_streams_configuration.iteritems(): if '' not in prefix_confs: raise ImproperlyConfigured( 'Must specify backends for the null prefix') for prefix, options in prefix_confs.iteritems(): if prefix != '': # Validate stream prefix. validate_stream(prefix) backends = _validate_and_get_value( options, "namespace_to_streams_configuration['{}']['{}']".format(namespace, prefix), 'backends', dict) for backend in backends.keys(): if backend not in storage: raise ImproperlyConfigured( "`{}` backend for `namespace_to_streams_configuration['{}']" "['{}']` is not configured in `storage`" .format(backend, namespace, prefix)) read_backend = _validate_and_get_value( options, "namespace_to_streams_configuration['{}']['{}']".format(namespace, prefix), 'read_backend', str) if read_backend not in storage: raise ImproperlyConfigured( "`{}` backend for `namespace_to_streams_configuration['{}']" "['{}']` is not configured in `storage`" .format(read_backend, namespace, prefix)) # Validate `stream` stream = getattr(settings, 'stream', dict) _validate_and_get_value(stream, 'stream', 'format', re._pattern_type) # Validate `node` node = getattr(settings, 'node', dict) _validate_and_get_value(node, 'node', 'greenlet_pool_size', int) _validate_and_get_value(node, 'node', 'id', str)
python
def validate_settings(settings): """ `settings` is either a dictionary or an object containing Kronos settings (e.g., the contents of conf/settings.py). This function checks that all required settings are present and valid. """ # Validate `storage` storage = _validate_and_get_value(settings, 'settings', 'storage', dict) for name, options in storage.iteritems(): if 'backend' not in options: raise ImproperlyConfigured( '`storage[\'{}\'] must contain a `backend` key'.format(name)) path = options['backend'] module, cls = path.rsplit('.', 1) module = import_module(module) if not hasattr(module, cls): raise NotImplementedError('`{}` not implemented.'.format(cls)) validate_storage_settings(getattr(module, cls), options) # Validate `streams_to_backends` namespace_to_streams_configuration = _validate_and_get_value( settings, 'settings', 'namespace_to_streams_configuration', dict) for namespace, prefix_confs in namespace_to_streams_configuration.iteritems(): if '' not in prefix_confs: raise ImproperlyConfigured( 'Must specify backends for the null prefix') for prefix, options in prefix_confs.iteritems(): if prefix != '': # Validate stream prefix. validate_stream(prefix) backends = _validate_and_get_value( options, "namespace_to_streams_configuration['{}']['{}']".format(namespace, prefix), 'backends', dict) for backend in backends.keys(): if backend not in storage: raise ImproperlyConfigured( "`{}` backend for `namespace_to_streams_configuration['{}']" "['{}']` is not configured in `storage`" .format(backend, namespace, prefix)) read_backend = _validate_and_get_value( options, "namespace_to_streams_configuration['{}']['{}']".format(namespace, prefix), 'read_backend', str) if read_backend not in storage: raise ImproperlyConfigured( "`{}` backend for `namespace_to_streams_configuration['{}']" "['{}']` is not configured in `storage`" .format(read_backend, namespace, prefix)) # Validate `stream` stream = getattr(settings, 'stream', dict) _validate_and_get_value(stream, 'stream', 'format', re._pattern_type) # Validate `node` node = getattr(settings, 'node', dict) _validate_and_get_value(node, 'node', 'greenlet_pool_size', int) _validate_and_get_value(node, 'node', 'id', str)
[ "def", "validate_settings", "(", "settings", ")", ":", "# Validate `storage`", "storage", "=", "_validate_and_get_value", "(", "settings", ",", "'settings'", ",", "'storage'", ",", "dict", ")", "for", "name", ",", "options", "in", "storage", ".", "iteritems", "(...
`settings` is either a dictionary or an object containing Kronos settings (e.g., the contents of conf/settings.py). This function checks that all required settings are present and valid.
[ "settings", "is", "either", "a", "dictionary", "or", "an", "object", "containing", "Kronos", "settings", "(", "e", ".", "g", ".", "the", "contents", "of", "conf", "/", "settings", ".", "py", ")", ".", "This", "function", "checks", "that", "all", "require...
train
https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/kronos/kronos/core/validator.py#L101-L165
LasLabs/python-helpscout
helpscout/base_model.py
BaseModel.from_api
def from_api(cls, **kwargs): """Create a new instance from API arguments. This will switch camelCase keys into snake_case for instantiation. It will also identify any ``Instance`` or ``List`` properties, and instantiate the proper objects using the values. The end result being a fully Objectified and Pythonified API response. Returns: BaseModel: Instantiated model using the API values. """ vals = cls.get_non_empty_vals({ cls._to_snake_case(k): v for k, v in kwargs.items() }) remove = [] for attr, val in vals.items(): try: vals[attr] = cls._parse_property(attr, val) except HelpScoutValidationException: remove.append(attr) logger.info( 'Unexpected property received in API response', exc_info=True, ) for attr in remove: del vals[attr] return cls(**cls.get_non_empty_vals(vals))
python
def from_api(cls, **kwargs): """Create a new instance from API arguments. This will switch camelCase keys into snake_case for instantiation. It will also identify any ``Instance`` or ``List`` properties, and instantiate the proper objects using the values. The end result being a fully Objectified and Pythonified API response. Returns: BaseModel: Instantiated model using the API values. """ vals = cls.get_non_empty_vals({ cls._to_snake_case(k): v for k, v in kwargs.items() }) remove = [] for attr, val in vals.items(): try: vals[attr] = cls._parse_property(attr, val) except HelpScoutValidationException: remove.append(attr) logger.info( 'Unexpected property received in API response', exc_info=True, ) for attr in remove: del vals[attr] return cls(**cls.get_non_empty_vals(vals))
[ "def", "from_api", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "vals", "=", "cls", ".", "get_non_empty_vals", "(", "{", "cls", ".", "_to_snake_case", "(", "k", ")", ":", "v", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", "}", ...
Create a new instance from API arguments. This will switch camelCase keys into snake_case for instantiation. It will also identify any ``Instance`` or ``List`` properties, and instantiate the proper objects using the values. The end result being a fully Objectified and Pythonified API response. Returns: BaseModel: Instantiated model using the API values.
[ "Create", "a", "new", "instance", "from", "API", "arguments", "." ]
train
https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/base_model.py#L30-L58
LasLabs/python-helpscout
helpscout/base_model.py
BaseModel.to_api
def to_api(self): """Return a dictionary to send to the API. Returns: dict: Mapping representing this object that can be sent to the API. """ vals = {} for attribute, attribute_type in self._props.items(): prop = getattr(self, attribute) vals[self._to_camel_case(attribute)] = self._to_api_value( attribute_type, prop, ) return vals
python
def to_api(self): """Return a dictionary to send to the API. Returns: dict: Mapping representing this object that can be sent to the API. """ vals = {} for attribute, attribute_type in self._props.items(): prop = getattr(self, attribute) vals[self._to_camel_case(attribute)] = self._to_api_value( attribute_type, prop, ) return vals
[ "def", "to_api", "(", "self", ")", ":", "vals", "=", "{", "}", "for", "attribute", ",", "attribute_type", "in", "self", ".", "_props", ".", "items", "(", ")", ":", "prop", "=", "getattr", "(", "self", ",", "attribute", ")", "vals", "[", "self", "."...
Return a dictionary to send to the API. Returns: dict: Mapping representing this object that can be sent to the API.
[ "Return", "a", "dictionary", "to", "send", "to", "the", "API", "." ]
train
https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/base_model.py#L67-L80
LasLabs/python-helpscout
helpscout/base_model.py
BaseModel._to_api_value
def _to_api_value(self, attribute_type, value): """Return a parsed value for the API.""" if not value: return None if isinstance(attribute_type, properties.Instance): return value.to_api() if isinstance(attribute_type, properties.List): return self._parse_api_value_list(value) return attribute_type.serialize(value)
python
def _to_api_value(self, attribute_type, value): """Return a parsed value for the API.""" if not value: return None if isinstance(attribute_type, properties.Instance): return value.to_api() if isinstance(attribute_type, properties.List): return self._parse_api_value_list(value) return attribute_type.serialize(value)
[ "def", "_to_api_value", "(", "self", ",", "attribute_type", ",", "value", ")", ":", "if", "not", "value", ":", "return", "None", "if", "isinstance", "(", "attribute_type", ",", "properties", ".", "Instance", ")", ":", "return", "value", ".", "to_api", "(",...
Return a parsed value for the API.
[ "Return", "a", "parsed", "value", "for", "the", "API", "." ]
train
https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/base_model.py#L82-L94
LasLabs/python-helpscout
helpscout/base_model.py
BaseModel._parse_api_value_list
def _parse_api_value_list(self, values): """Return a list field compatible with the API.""" try: return [v.to_api() for v in values] # Not models except AttributeError: return list(values)
python
def _parse_api_value_list(self, values): """Return a list field compatible with the API.""" try: return [v.to_api() for v in values] # Not models except AttributeError: return list(values)
[ "def", "_parse_api_value_list", "(", "self", ",", "values", ")", ":", "try", ":", "return", "[", "v", ".", "to_api", "(", ")", "for", "v", "in", "values", "]", "# Not models", "except", "AttributeError", ":", "return", "list", "(", "values", ")" ]
Return a list field compatible with the API.
[ "Return", "a", "list", "field", "compatible", "with", "the", "API", "." ]
train
https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/base_model.py#L96-L102
LasLabs/python-helpscout
helpscout/base_model.py
BaseModel._parse_property
def _parse_property(cls, name, value): """Parse a property received from the API into an internal object. Args: name (str): Name of the property on the object. value (mixed): The unparsed API value. Raises: HelpScoutValidationException: In the event that the property name is not found. Returns: mixed: A value compatible with the internal models. """ prop = cls._props.get(name) return_value = value if not prop: logger.debug( '"%s" with value "%s" is not a valid property for "%s".' % ( name, value, cls, ), ) return_value = None elif isinstance(prop, properties.Instance): return_value = prop.instance_class.from_api(**value) elif isinstance(prop, properties.List): return_value = cls._parse_property_list(prop, value) elif isinstance(prop, properties.Color): return_value = cls._parse_property_color(value) return return_value
python
def _parse_property(cls, name, value): """Parse a property received from the API into an internal object. Args: name (str): Name of the property on the object. value (mixed): The unparsed API value. Raises: HelpScoutValidationException: In the event that the property name is not found. Returns: mixed: A value compatible with the internal models. """ prop = cls._props.get(name) return_value = value if not prop: logger.debug( '"%s" with value "%s" is not a valid property for "%s".' % ( name, value, cls, ), ) return_value = None elif isinstance(prop, properties.Instance): return_value = prop.instance_class.from_api(**value) elif isinstance(prop, properties.List): return_value = cls._parse_property_list(prop, value) elif isinstance(prop, properties.Color): return_value = cls._parse_property_color(value) return return_value
[ "def", "_parse_property", "(", "cls", ",", "name", ",", "value", ")", ":", "prop", "=", "cls", ".", "_props", ".", "get", "(", "name", ")", "return_value", "=", "value", "if", "not", "prop", ":", "logger", ".", "debug", "(", "'\"%s\" with value \"%s\" is...
Parse a property received from the API into an internal object. Args: name (str): Name of the property on the object. value (mixed): The unparsed API value. Raises: HelpScoutValidationException: In the event that the property name is not found. Returns: mixed: A value compatible with the internal models.
[ "Parse", "a", "property", "received", "from", "the", "API", "into", "an", "internal", "object", "." ]
train
https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/base_model.py#L112-L147
LasLabs/python-helpscout
helpscout/base_model.py
BaseModel._parse_property_list
def _parse_property_list(prop, value): """Parse a list property and return a list of the results.""" attributes = [] for v in value: try: attributes.append( prop.prop.instance_class.from_api(**v), ) except AttributeError: attributes.append(v) return attributes
python
def _parse_property_list(prop, value): """Parse a list property and return a list of the results.""" attributes = [] for v in value: try: attributes.append( prop.prop.instance_class.from_api(**v), ) except AttributeError: attributes.append(v) return attributes
[ "def", "_parse_property_list", "(", "prop", ",", "value", ")", ":", "attributes", "=", "[", "]", "for", "v", "in", "value", ":", "try", ":", "attributes", ".", "append", "(", "prop", ".", "prop", ".", "instance_class", ".", "from_api", "(", "*", "*", ...
Parse a list property and return a list of the results.
[ "Parse", "a", "list", "property", "and", "return", "a", "list", "of", "the", "results", "." ]
train
https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/base_model.py#L157-L167
LasLabs/python-helpscout
helpscout/base_model.py
BaseModel._to_snake_case
def _to_snake_case(string): """Return a snake cased version of the input string. Args: string (str): A camel cased string. Returns: str: A snake cased string. """ sub_string = r'\1_\2' string = REGEX_CAMEL_FIRST.sub(sub_string, string) return REGEX_CAMEL_SECOND.sub(sub_string, string).lower()
python
def _to_snake_case(string): """Return a snake cased version of the input string. Args: string (str): A camel cased string. Returns: str: A snake cased string. """ sub_string = r'\1_\2' string = REGEX_CAMEL_FIRST.sub(sub_string, string) return REGEX_CAMEL_SECOND.sub(sub_string, string).lower()
[ "def", "_to_snake_case", "(", "string", ")", ":", "sub_string", "=", "r'\\1_\\2'", "string", "=", "REGEX_CAMEL_FIRST", ".", "sub", "(", "sub_string", ",", "string", ")", "return", "REGEX_CAMEL_SECOND", ".", "sub", "(", "sub_string", ",", "string", ")", ".", ...
Return a snake cased version of the input string. Args: string (str): A camel cased string. Returns: str: A snake cased string.
[ "Return", "a", "snake", "cased", "version", "of", "the", "input", "string", "." ]
train
https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/base_model.py#L170-L181
LasLabs/python-helpscout
helpscout/base_model.py
BaseModel._to_camel_case
def _to_camel_case(string): """Return a camel cased version of the input string. Args: string (str): A snake cased string. Returns: str: A camel cased string. """ components = string.split('_') return '%s%s' % ( components[0], ''.join(c.title() for c in components[1:]), )
python
def _to_camel_case(string): """Return a camel cased version of the input string. Args: string (str): A snake cased string. Returns: str: A camel cased string. """ components = string.split('_') return '%s%s' % ( components[0], ''.join(c.title() for c in components[1:]), )
[ "def", "_to_camel_case", "(", "string", ")", ":", "components", "=", "string", ".", "split", "(", "'_'", ")", "return", "'%s%s'", "%", "(", "components", "[", "0", "]", ",", "''", ".", "join", "(", "c", ".", "title", "(", ")", "for", "c", "in", "...
Return a camel cased version of the input string. Args: string (str): A snake cased string. Returns: str: A camel cased string.
[ "Return", "a", "camel", "cased", "version", "of", "the", "input", "string", "." ]
train
https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/base_model.py#L184-L197
bfontaine/trigrams
trigrams/__init__.py
TrigramsDB.save
def save(self, output=None): """ Save the database to a file. If ``output`` is not given, the ``dbfile`` given in the constructor is used. """ if output is None: if self.dbfile is None: return output = self.dbfile with open(output, 'w') as f: f.write(self._dump())
python
def save(self, output=None): """ Save the database to a file. If ``output`` is not given, the ``dbfile`` given in the constructor is used. """ if output is None: if self.dbfile is None: return output = self.dbfile with open(output, 'w') as f: f.write(self._dump())
[ "def", "save", "(", "self", ",", "output", "=", "None", ")", ":", "if", "output", "is", "None", ":", "if", "self", ".", "dbfile", "is", "None", ":", "return", "output", "=", "self", ".", "dbfile", "with", "open", "(", "output", ",", "'w'", ")", "...
Save the database to a file. If ``output`` is not given, the ``dbfile`` given in the constructor is used.
[ "Save", "the", "database", "to", "a", "file", ".", "If", "output", "is", "not", "given", "the", "dbfile", "given", "in", "the", "constructor", "is", "used", "." ]
train
https://github.com/bfontaine/trigrams/blob/7e3906f7aae83d9b069bd11e611074c56d4e4803/trigrams/__init__.py#L31-L42
bfontaine/trigrams
trigrams/__init__.py
TrigramsDB.feed
def feed(self, text=None, source=None): """ Feed some text to the database, either from a string (``text``) or a file (``source``). >>> db = TrigramsDB() >>> db.feed("This is my text") >>> db.feed(source="some/file.txt") """ if text is not None: words = re.split(r'\s+', text) wlen = len(words) for i in range(wlen - 2): self._insert(words[i:i+3]) if source is not None: with open(source, 'r') as f: self.feed(f.read())
python
def feed(self, text=None, source=None): """ Feed some text to the database, either from a string (``text``) or a file (``source``). >>> db = TrigramsDB() >>> db.feed("This is my text") >>> db.feed(source="some/file.txt") """ if text is not None: words = re.split(r'\s+', text) wlen = len(words) for i in range(wlen - 2): self._insert(words[i:i+3]) if source is not None: with open(source, 'r') as f: self.feed(f.read())
[ "def", "feed", "(", "self", ",", "text", "=", "None", ",", "source", "=", "None", ")", ":", "if", "text", "is", "not", "None", ":", "words", "=", "re", ".", "split", "(", "r'\\s+'", ",", "text", ")", "wlen", "=", "len", "(", "words", ")", "for"...
Feed some text to the database, either from a string (``text``) or a file (``source``). >>> db = TrigramsDB() >>> db.feed("This is my text") >>> db.feed(source="some/file.txt")
[ "Feed", "some", "text", "to", "the", "database", "either", "from", "a", "string", "(", "text", ")", "or", "a", "file", "(", "source", ")", "." ]
train
https://github.com/bfontaine/trigrams/blob/7e3906f7aae83d9b069bd11e611074c56d4e4803/trigrams/__init__.py#L44-L61
bfontaine/trigrams
trigrams/__init__.py
TrigramsDB.generate
def generate(self, **kwargs): """ Generate some text from the database. By default only 70 words are generated, but you can change this using keyword arguments. Keyword arguments: - ``wlen``: maximum length (words) - ``words``: a list of words to use to begin the text with """ words = list(map(self._sanitize, kwargs.get('words', []))) max_wlen = kwargs.get('wlen', 70) wlen = len(words) if wlen < 2: if not self._db: return '' if wlen == 0: words = sample(self._db.keys(), 1)[0].split(self._WSEP) elif wlen == 1: spl = [k for k in self._db.keys() if k.startswith(words[0]+self._WSEP)] words.append(sample(spl, 1)[0].split(self._WSEP)[1]) wlen = 2 while wlen < max_wlen: next_word = self._get(words[-2], words[-1]) if next_word is None: break words.append(next_word) wlen += 1 return ' '.join(words)
python
def generate(self, **kwargs): """ Generate some text from the database. By default only 70 words are generated, but you can change this using keyword arguments. Keyword arguments: - ``wlen``: maximum length (words) - ``words``: a list of words to use to begin the text with """ words = list(map(self._sanitize, kwargs.get('words', []))) max_wlen = kwargs.get('wlen', 70) wlen = len(words) if wlen < 2: if not self._db: return '' if wlen == 0: words = sample(self._db.keys(), 1)[0].split(self._WSEP) elif wlen == 1: spl = [k for k in self._db.keys() if k.startswith(words[0]+self._WSEP)] words.append(sample(spl, 1)[0].split(self._WSEP)[1]) wlen = 2 while wlen < max_wlen: next_word = self._get(words[-2], words[-1]) if next_word is None: break words.append(next_word) wlen += 1 return ' '.join(words)
[ "def", "generate", "(", "self", ",", "*", "*", "kwargs", ")", ":", "words", "=", "list", "(", "map", "(", "self", ".", "_sanitize", ",", "kwargs", ".", "get", "(", "'words'", ",", "[", "]", ")", ")", ")", "max_wlen", "=", "kwargs", ".", "get", ...
Generate some text from the database. By default only 70 words are generated, but you can change this using keyword arguments. Keyword arguments: - ``wlen``: maximum length (words) - ``words``: a list of words to use to begin the text with
[ "Generate", "some", "text", "from", "the", "database", ".", "By", "default", "only", "70", "words", "are", "generated", "but", "you", "can", "change", "this", "using", "keyword", "arguments", "." ]
train
https://github.com/bfontaine/trigrams/blob/7e3906f7aae83d9b069bd11e611074c56d4e4803/trigrams/__init__.py#L63-L99
bfontaine/trigrams
trigrams/__init__.py
TrigramsDB._load
def _load(self): """ Load the database from its ``dbfile`` if it has one """ if self.dbfile is not None: with open(self.dbfile, 'r') as f: self._db = json.loads(f.read()) else: self._db = {}
python
def _load(self): """ Load the database from its ``dbfile`` if it has one """ if self.dbfile is not None: with open(self.dbfile, 'r') as f: self._db = json.loads(f.read()) else: self._db = {}
[ "def", "_load", "(", "self", ")", ":", "if", "self", ".", "dbfile", "is", "not", "None", ":", "with", "open", "(", "self", ".", "dbfile", ",", "'r'", ")", "as", "f", ":", "self", ".", "_db", "=", "json", ".", "loads", "(", "f", ".", "read", "...
Load the database from its ``dbfile`` if it has one
[ "Load", "the", "database", "from", "its", "dbfile", "if", "it", "has", "one" ]
train
https://github.com/bfontaine/trigrams/blob/7e3906f7aae83d9b069bd11e611074c56d4e4803/trigrams/__init__.py#L101-L109
bfontaine/trigrams
trigrams/__init__.py
TrigramsDB._get
def _get(self, word1, word2): """ Return a possible next word after ``word1`` and ``word2``, or ``None`` if there's no possibility. """ key = self._WSEP.join([self._sanitize(word1), self._sanitize(word2)]) key = key.lower() if key not in self._db: return return sample(self._db[key], 1)[0]
python
def _get(self, word1, word2): """ Return a possible next word after ``word1`` and ``word2``, or ``None`` if there's no possibility. """ key = self._WSEP.join([self._sanitize(word1), self._sanitize(word2)]) key = key.lower() if key not in self._db: return return sample(self._db[key], 1)[0]
[ "def", "_get", "(", "self", ",", "word1", ",", "word2", ")", ":", "key", "=", "self", ".", "_WSEP", ".", "join", "(", "[", "self", ".", "_sanitize", "(", "word1", ")", ",", "self", ".", "_sanitize", "(", "word2", ")", "]", ")", "key", "=", "key...
Return a possible next word after ``word1`` and ``word2``, or ``None`` if there's no possibility.
[ "Return", "a", "possible", "next", "word", "after", "word1", "and", "word2", "or", "None", "if", "there", "s", "no", "possibility", "." ]
train
https://github.com/bfontaine/trigrams/blob/7e3906f7aae83d9b069bd11e611074c56d4e4803/trigrams/__init__.py#L118-L128
bfontaine/trigrams
trigrams/__init__.py
TrigramsDB._insert
def _insert(self, trigram): """ Insert a trigram in the DB """ words = list(map(self._sanitize, trigram)) key = self._WSEP.join(words[:2]).lower() next_word = words[2] self._db.setdefault(key, []) # we could use a set here, but sets are not serializables in JSON. This # is the same reason we use dicts instead of defaultdicts. if next_word not in self._db[key]: self._db[key].append(next_word)
python
def _insert(self, trigram): """ Insert a trigram in the DB """ words = list(map(self._sanitize, trigram)) key = self._WSEP.join(words[:2]).lower() next_word = words[2] self._db.setdefault(key, []) # we could use a set here, but sets are not serializables in JSON. This # is the same reason we use dicts instead of defaultdicts. if next_word not in self._db[key]: self._db[key].append(next_word)
[ "def", "_insert", "(", "self", ",", "trigram", ")", ":", "words", "=", "list", "(", "map", "(", "self", ".", "_sanitize", ",", "trigram", ")", ")", "key", "=", "self", ".", "_WSEP", ".", "join", "(", "words", "[", ":", "2", "]", ")", ".", "lowe...
Insert a trigram in the DB
[ "Insert", "a", "trigram", "in", "the", "DB" ]
train
https://github.com/bfontaine/trigrams/blob/7e3906f7aae83d9b069bd11e611074c56d4e4803/trigrams/__init__.py#L136-L149
Locu/chronology
metis/metis/convenience/cohort.py
cohort_queryplan
def cohort_queryplan(plan): """ Input: { 'source': 'kronos', # Name of data source from settings 'cohort': {'stream': CohortTest.EMAIL_STREAM, # Kronos stream to define cohort from. 'transform': lambda x: x, # Transformations on the kstream. 'start': date.now(), # The day of the first cohort. 'unit': DateUnit.XX, # Users are in the same cohort # if they are in the same day/week. 'cohorts': 5 # How many cohorts (days/weeks/months) # to track. 'grouping_key': 'user'}, # What key in an event should we tie # to a key in the action stream? 'action': {'stream': CohortTest.FRONTPAGE_STREAM, # Stream users take actions on. 'transform': lambda x: x # Transformations on the stream. 'unit': DateUnit.XX, # Track events in day/week/months. 'repetitions': 14 # How many days/weeks/months to track. 'grouping_key': 'user_id'} # What key in an event should we tie # to a key in the action stream? } Output: A metis-compatible query plan to return a cohort analysis. """ cohort = plan['cohort'] action = plan['action'] source = plan['source'] # Calculate the start and end dates, in Kronos time, of the # beginning and end of the cohort and action streams that will be # relevant. cohort_start = datetime_to_kronos_time(_date_to_datetime(cohort['start'])) cohort_span = timedelta(**{cohort['unit']: cohort['cohorts']}) cohort_end = cohort['start'] + cohort_span action_span = timedelta(**{action['unit']: action['repetitions']}) action_end = cohort_end + action_span cohort_end = datetime_to_kronos_time(_date_to_datetime(cohort_end)) + 1 action_end = datetime_to_kronos_time(_date_to_datetime(action_end)) + 1 left = _cohort_stream_transform(source, cohort['stream'], cohort_start, cohort_end, cohort.get('transform'), cohort['grouping_key'], cohort['unit']) right = _cohort_stream_transform(source, action['stream'], cohort_start, action_end, action.get('transform'), action['grouping_key'], action['unit']) additional_action_time = (DateUnit.unit_to_kronos_time(action['unit']) * action['repetitions']) left.alias = 'cohort' right.alias = 'action' joined = Join(left, right, (Condition(Condition.Op.EQ, Property('cohort.%s' % cohort['grouping_key']), Property('action.%s' % action['grouping_key'])) & Condition(Condition.Op.GTE, Property('action.%s' % TIMESTAMP_FIELD), Property('cohort.%s' % TIMESTAMP_FIELD)) & Condition(Condition.Op.LT, Property('action.%s' % TIMESTAMP_FIELD), Add([Property('cohort.%s' % TIMESTAMP_FIELD), Constant(additional_action_time)])))) user_aggregated = Aggregate( joined, GroupBy([Property('cohort.date', alias=TIMESTAMP_FIELD), Property('cohort.%s' % cohort['grouping_key'], alias='group'), Floor([Subtract([Property('action.%s' % TIMESTAMP_FIELD), Property('cohort.%s' % TIMESTAMP_FIELD)]), Constant(DateUnit.unit_to_kronos_time(action['unit']))], alias='action_step')]), [Count([], alias='count')] ) aggregated = Aggregate( user_aggregated, GroupBy([Property(TIMESTAMP_FIELD, alias=TIMESTAMP_FIELD), Property('action_step', alias='action_step')]), [Count([], alias='cohort_actions')]) # TODO(marcua): Also sum up the cohort sizes, join with the plan. return aggregated.to_dict()
python
def cohort_queryplan(plan): """ Input: { 'source': 'kronos', # Name of data source from settings 'cohort': {'stream': CohortTest.EMAIL_STREAM, # Kronos stream to define cohort from. 'transform': lambda x: x, # Transformations on the kstream. 'start': date.now(), # The day of the first cohort. 'unit': DateUnit.XX, # Users are in the same cohort # if they are in the same day/week. 'cohorts': 5 # How many cohorts (days/weeks/months) # to track. 'grouping_key': 'user'}, # What key in an event should we tie # to a key in the action stream? 'action': {'stream': CohortTest.FRONTPAGE_STREAM, # Stream users take actions on. 'transform': lambda x: x # Transformations on the stream. 'unit': DateUnit.XX, # Track events in day/week/months. 'repetitions': 14 # How many days/weeks/months to track. 'grouping_key': 'user_id'} # What key in an event should we tie # to a key in the action stream? } Output: A metis-compatible query plan to return a cohort analysis. """ cohort = plan['cohort'] action = plan['action'] source = plan['source'] # Calculate the start and end dates, in Kronos time, of the # beginning and end of the cohort and action streams that will be # relevant. cohort_start = datetime_to_kronos_time(_date_to_datetime(cohort['start'])) cohort_span = timedelta(**{cohort['unit']: cohort['cohorts']}) cohort_end = cohort['start'] + cohort_span action_span = timedelta(**{action['unit']: action['repetitions']}) action_end = cohort_end + action_span cohort_end = datetime_to_kronos_time(_date_to_datetime(cohort_end)) + 1 action_end = datetime_to_kronos_time(_date_to_datetime(action_end)) + 1 left = _cohort_stream_transform(source, cohort['stream'], cohort_start, cohort_end, cohort.get('transform'), cohort['grouping_key'], cohort['unit']) right = _cohort_stream_transform(source, action['stream'], cohort_start, action_end, action.get('transform'), action['grouping_key'], action['unit']) additional_action_time = (DateUnit.unit_to_kronos_time(action['unit']) * action['repetitions']) left.alias = 'cohort' right.alias = 'action' joined = Join(left, right, (Condition(Condition.Op.EQ, Property('cohort.%s' % cohort['grouping_key']), Property('action.%s' % action['grouping_key'])) & Condition(Condition.Op.GTE, Property('action.%s' % TIMESTAMP_FIELD), Property('cohort.%s' % TIMESTAMP_FIELD)) & Condition(Condition.Op.LT, Property('action.%s' % TIMESTAMP_FIELD), Add([Property('cohort.%s' % TIMESTAMP_FIELD), Constant(additional_action_time)])))) user_aggregated = Aggregate( joined, GroupBy([Property('cohort.date', alias=TIMESTAMP_FIELD), Property('cohort.%s' % cohort['grouping_key'], alias='group'), Floor([Subtract([Property('action.%s' % TIMESTAMP_FIELD), Property('cohort.%s' % TIMESTAMP_FIELD)]), Constant(DateUnit.unit_to_kronos_time(action['unit']))], alias='action_step')]), [Count([], alias='count')] ) aggregated = Aggregate( user_aggregated, GroupBy([Property(TIMESTAMP_FIELD, alias=TIMESTAMP_FIELD), Property('action_step', alias='action_step')]), [Count([], alias='cohort_actions')]) # TODO(marcua): Also sum up the cohort sizes, join with the plan. return aggregated.to_dict()
[ "def", "cohort_queryplan", "(", "plan", ")", ":", "cohort", "=", "plan", "[", "'cohort'", "]", "action", "=", "plan", "[", "'action'", "]", "source", "=", "plan", "[", "'source'", "]", "# Calculate the start and end dates, in Kronos time, of the", "# beginning and e...
Input: { 'source': 'kronos', # Name of data source from settings 'cohort': {'stream': CohortTest.EMAIL_STREAM, # Kronos stream to define cohort from. 'transform': lambda x: x, # Transformations on the kstream. 'start': date.now(), # The day of the first cohort. 'unit': DateUnit.XX, # Users are in the same cohort # if they are in the same day/week. 'cohorts': 5 # How many cohorts (days/weeks/months) # to track. 'grouping_key': 'user'}, # What key in an event should we tie # to a key in the action stream? 'action': {'stream': CohortTest.FRONTPAGE_STREAM, # Stream users take actions on. 'transform': lambda x: x # Transformations on the stream. 'unit': DateUnit.XX, # Track events in day/week/months. 'repetitions': 14 # How many days/weeks/months to track. 'grouping_key': 'user_id'} # What key in an event should we tie # to a key in the action stream? } Output: A metis-compatible query plan to return a cohort analysis.
[ "Input", ":", "{", "source", ":", "kronos", "#", "Name", "of", "data", "source", "from", "settings", "cohort", ":", "{", "stream", ":", "CohortTest", ".", "EMAIL_STREAM", "#", "Kronos", "stream", "to", "define", "cohort", "from", ".", "transform", ":", "...
train
https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/metis/metis/convenience/cohort.py#L79-L168
ryanvarley/ExoData
exodata/assumptions.py
planetMassType
def planetMassType(mass): """ Returns the planet masstype given the mass and using planetAssumptions['massType'] """ if mass is np.nan: return None for massLimit, massType in planetAssumptions['massType']: if mass < massLimit: return massType
python
def planetMassType(mass): """ Returns the planet masstype given the mass and using planetAssumptions['massType'] """ if mass is np.nan: return None for massLimit, massType in planetAssumptions['massType']: if mass < massLimit: return massType
[ "def", "planetMassType", "(", "mass", ")", ":", "if", "mass", "is", "np", ".", "nan", ":", "return", "None", "for", "massLimit", ",", "massType", "in", "planetAssumptions", "[", "'massType'", "]", ":", "if", "mass", "<", "massLimit", ":", "return", "mass...
Returns the planet masstype given the mass and using planetAssumptions['massType']
[ "Returns", "the", "planet", "masstype", "given", "the", "mass", "and", "using", "planetAssumptions", "[", "massType", "]" ]
train
https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/assumptions.py#L69-L79
ryanvarley/ExoData
exodata/assumptions.py
planetRadiusType
def planetRadiusType(radius): """ Returns the planet radiustype given the mass and using planetAssumptions['radiusType'] """ if radius is np.nan: return None for radiusLimit, radiusType in planetAssumptions['radiusType']: if radius < radiusLimit: return radiusType
python
def planetRadiusType(radius): """ Returns the planet radiustype given the mass and using planetAssumptions['radiusType'] """ if radius is np.nan: return None for radiusLimit, radiusType in planetAssumptions['radiusType']: if radius < radiusLimit: return radiusType
[ "def", "planetRadiusType", "(", "radius", ")", ":", "if", "radius", "is", "np", ".", "nan", ":", "return", "None", "for", "radiusLimit", ",", "radiusType", "in", "planetAssumptions", "[", "'radiusType'", "]", ":", "if", "radius", "<", "radiusLimit", ":", "...
Returns the planet radiustype given the mass and using planetAssumptions['radiusType']
[ "Returns", "the", "planet", "radiustype", "given", "the", "mass", "and", "using", "planetAssumptions", "[", "radiusType", "]" ]
train
https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/assumptions.py#L82-L92
ryanvarley/ExoData
exodata/assumptions.py
planetType
def planetType(temperature, mass, radius): """ Returns the planet type as 'temperatureType massType' """ if mass is not np.nan: sizeType = planetMassType(mass) elif radius is not np.nan: sizeType = planetRadiusType(radius) else: return None return '{0} {1}'.format(planetTempType(temperature), sizeType)
python
def planetType(temperature, mass, radius): """ Returns the planet type as 'temperatureType massType' """ if mass is not np.nan: sizeType = planetMassType(mass) elif radius is not np.nan: sizeType = planetRadiusType(radius) else: return None return '{0} {1}'.format(planetTempType(temperature), sizeType)
[ "def", "planetType", "(", "temperature", ",", "mass", ",", "radius", ")", ":", "if", "mass", "is", "not", "np", ".", "nan", ":", "sizeType", "=", "planetMassType", "(", "mass", ")", "elif", "radius", "is", "not", "np", ".", "nan", ":", "sizeType", "=...
Returns the planet type as 'temperatureType massType'
[ "Returns", "the", "planet", "type", "as", "temperatureType", "massType" ]
train
https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/assumptions.py#L105-L116
timdiels/pytil
pytil/data_frame.py
split_array_like
def split_array_like(df, columns=None): #TODO rename TODO if it's not a big performance hit, just make them arraylike? We already indicated the column explicitly (sort of) so... ''' Split cells with array-like values along row axis. Column names are maintained. The index is dropped. Parameters ---------- df : ~pandas.DataFrame Data frame ``df[columns]`` should contain :py:class:`~pytil.numpy.ArrayLike` values. columns : ~typing.Collection[str] or str or None Columns (or column) whose values to split. Defaults to ``df.columns``. Returns ------- ~pandas.DataFrame Data frame with array-like values in ``df[columns]`` split across rows, and corresponding values in other columns repeated. Examples -------- >>> df = pd.DataFrame([[1,[1,2],[1]],[1,[1,2],[3,4,5]],[2,[1],[1,2]]], columns=('check', 'a', 'b')) >>> df check a b 0 1 [1, 2] [1] 1 1 [1, 2] [3, 4, 5] 2 2 [1] [1, 2] >>> split_array_like(df, ['a', 'b']) check a b 0 1 1 1 1 1 2 1 2 1 1 3 3 1 1 4 4 1 1 5 5 1 2 3 6 1 2 4 7 1 2 5 8 2 1 1 9 2 1 2 ''' # TODO could add option to keep_index by using reset_index and eventually # set_index. index names trickery: MultiIndex.names, Index.name. Both can be # None. If Index.name can be None in which case it translates to 'index' or # if that already exists, it translates to 'level_0'. If MultiIndex.names is # None, it translates to level_0,... level_N dtypes = df.dtypes if columns is None: columns = df.columns elif isinstance(columns, str): columns = [columns] for column in columns: expanded = np.repeat(df.values, df[column].apply(len).values, axis=0) expanded[:, df.columns.get_loc(column)] = np.concatenate(df[column].tolist()) df = pd.DataFrame(expanded, columns=df.columns) # keep types unchanged for i, dtype in enumerate(dtypes): df.iloc[:,i] = df.iloc[:,i].astype(dtype) return df
python
def split_array_like(df, columns=None): #TODO rename TODO if it's not a big performance hit, just make them arraylike? We already indicated the column explicitly (sort of) so... ''' Split cells with array-like values along row axis. Column names are maintained. The index is dropped. Parameters ---------- df : ~pandas.DataFrame Data frame ``df[columns]`` should contain :py:class:`~pytil.numpy.ArrayLike` values. columns : ~typing.Collection[str] or str or None Columns (or column) whose values to split. Defaults to ``df.columns``. Returns ------- ~pandas.DataFrame Data frame with array-like values in ``df[columns]`` split across rows, and corresponding values in other columns repeated. Examples -------- >>> df = pd.DataFrame([[1,[1,2],[1]],[1,[1,2],[3,4,5]],[2,[1],[1,2]]], columns=('check', 'a', 'b')) >>> df check a b 0 1 [1, 2] [1] 1 1 [1, 2] [3, 4, 5] 2 2 [1] [1, 2] >>> split_array_like(df, ['a', 'b']) check a b 0 1 1 1 1 1 2 1 2 1 1 3 3 1 1 4 4 1 1 5 5 1 2 3 6 1 2 4 7 1 2 5 8 2 1 1 9 2 1 2 ''' # TODO could add option to keep_index by using reset_index and eventually # set_index. index names trickery: MultiIndex.names, Index.name. Both can be # None. If Index.name can be None in which case it translates to 'index' or # if that already exists, it translates to 'level_0'. If MultiIndex.names is # None, it translates to level_0,... level_N dtypes = df.dtypes if columns is None: columns = df.columns elif isinstance(columns, str): columns = [columns] for column in columns: expanded = np.repeat(df.values, df[column].apply(len).values, axis=0) expanded[:, df.columns.get_loc(column)] = np.concatenate(df[column].tolist()) df = pd.DataFrame(expanded, columns=df.columns) # keep types unchanged for i, dtype in enumerate(dtypes): df.iloc[:,i] = df.iloc[:,i].astype(dtype) return df
[ "def", "split_array_like", "(", "df", ",", "columns", "=", "None", ")", ":", "#TODO rename TODO if it's not a big performance hit, just make them arraylike? We already indicated the column explicitly (sort of) so...", "# TODO could add option to keep_index by using reset_index and eventually",...
Split cells with array-like values along row axis. Column names are maintained. The index is dropped. Parameters ---------- df : ~pandas.DataFrame Data frame ``df[columns]`` should contain :py:class:`~pytil.numpy.ArrayLike` values. columns : ~typing.Collection[str] or str or None Columns (or column) whose values to split. Defaults to ``df.columns``. Returns ------- ~pandas.DataFrame Data frame with array-like values in ``df[columns]`` split across rows, and corresponding values in other columns repeated. Examples -------- >>> df = pd.DataFrame([[1,[1,2],[1]],[1,[1,2],[3,4,5]],[2,[1],[1,2]]], columns=('check', 'a', 'b')) >>> df check a b 0 1 [1, 2] [1] 1 1 [1, 2] [3, 4, 5] 2 2 [1] [1, 2] >>> split_array_like(df, ['a', 'b']) check a b 0 1 1 1 1 1 2 1 2 1 1 3 3 1 1 4 4 1 1 5 5 1 2 3 6 1 2 4 7 1 2 5 8 2 1 1 9 2 1 2
[ "Split", "cells", "with", "array", "-", "like", "values", "along", "row", "axis", "." ]
train
https://github.com/timdiels/pytil/blob/086a3f8d52caecdd9d1c9f66c8d8a6d38667b00b/pytil/data_frame.py#L64-L126
timdiels/pytil
pytil/data_frame.py
equals
def equals(df1, df2, ignore_order=set(), ignore_indices=set(), all_close=False, _return_reason=False): ''' Get whether 2 data frames are equal. ``NaN`` is considered equal to ``NaN`` and `None`. Parameters ---------- df1 : ~pandas.DataFrame Data frame to compare. df2 : ~pandas.DataFrame Data frame to compare. ignore_order : ~typing.Set[int] Axi in which to ignore order. ignore_indices : ~typing.Set[int] Axi of which to ignore the index. E.g. ``{1}`` allows differences in ``df.columns.name`` and ``df.columns.equals(df2.columns)``. all_close : bool If `False`, values must match exactly, if `True`, floats are compared as if compared with `numpy.isclose`. _return_reason : bool Internal. If `True`, `equals` returns a tuple containing the reason, else `equals` only returns a bool indicating equality (or equivalence rather). Returns ------- bool Whether they are equal (after ignoring according to the parameters). Internal note: if ``_return_reason``, ``Tuple[bool, str or None]`` is returned. The former is whether they're equal, the latter is `None` if equal or a short explanation of why the data frames aren't equal, otherwise. Notes ----- All values (including those of indices) must be copyable and ``__eq__`` must be such that a copy must equal its original. A value must equal itself unless it's ``NaN``. Values needn't be orderable or hashable (however pandas requires index values to be orderable and hashable). By consequence, this is not an efficient function, but it is flexible. Examples -------- >>> from pytil import data_frame as df_ >>> import pandas as pd >>> df = pd.DataFrame([ ... [1, 2, 3], ... [4, 5, 6], ... [7, 8, 9] ... ], ... index=pd.Index(('i1', 'i2', 'i3'), name='index1'), ... columns=pd.Index(('c1', 'c2', 'c3'), name='columns1') ... ) >>> df columns1 c1 c2 c3 index1 i1 1 2 3 i2 4 5 6 i3 7 8 9 >>> df2 = df.reindex(('i3', 'i1', 'i2'), columns=('c2', 'c1', 'c3')) >>> df2 columns1 c2 c1 c3 index1 i3 8 7 9 i1 2 1 3 i2 5 4 6 >>> df_.equals(df, df2) False >>> df_.equals(df, df2, ignore_order=(0,1)) True >>> df2 = df.copy() >>> df2.index = [1,2,3] >>> df2 columns1 c1 c2 c3 1 1 2 3 2 4 5 6 3 7 8 9 >>> df_.equals(df, df2) False >>> df_.equals(df, df2, ignore_indices={0}) True >>> df2 = df.reindex(('i3', 'i1', 'i2')) >>> df2 columns1 c1 c2 c3 index1 i3 7 8 9 i1 1 2 3 i2 4 5 6 >>> df_.equals(df, df2, ignore_indices={0}) # does not ignore row order! False >>> df_.equals(df, df2, ignore_order={0}) True >>> df2 = df.copy() >>> df2.index.name = 'other' >>> df_.equals(df, df2) # df.index.name must match as well, same goes for df.columns.name False ''' result = _equals(df1, df2, ignore_order, ignore_indices, all_close) if _return_reason: return result else: return result[0]
python
def equals(df1, df2, ignore_order=set(), ignore_indices=set(), all_close=False, _return_reason=False): ''' Get whether 2 data frames are equal. ``NaN`` is considered equal to ``NaN`` and `None`. Parameters ---------- df1 : ~pandas.DataFrame Data frame to compare. df2 : ~pandas.DataFrame Data frame to compare. ignore_order : ~typing.Set[int] Axi in which to ignore order. ignore_indices : ~typing.Set[int] Axi of which to ignore the index. E.g. ``{1}`` allows differences in ``df.columns.name`` and ``df.columns.equals(df2.columns)``. all_close : bool If `False`, values must match exactly, if `True`, floats are compared as if compared with `numpy.isclose`. _return_reason : bool Internal. If `True`, `equals` returns a tuple containing the reason, else `equals` only returns a bool indicating equality (or equivalence rather). Returns ------- bool Whether they are equal (after ignoring according to the parameters). Internal note: if ``_return_reason``, ``Tuple[bool, str or None]`` is returned. The former is whether they're equal, the latter is `None` if equal or a short explanation of why the data frames aren't equal, otherwise. Notes ----- All values (including those of indices) must be copyable and ``__eq__`` must be such that a copy must equal its original. A value must equal itself unless it's ``NaN``. Values needn't be orderable or hashable (however pandas requires index values to be orderable and hashable). By consequence, this is not an efficient function, but it is flexible. Examples -------- >>> from pytil import data_frame as df_ >>> import pandas as pd >>> df = pd.DataFrame([ ... [1, 2, 3], ... [4, 5, 6], ... [7, 8, 9] ... ], ... index=pd.Index(('i1', 'i2', 'i3'), name='index1'), ... columns=pd.Index(('c1', 'c2', 'c3'), name='columns1') ... ) >>> df columns1 c1 c2 c3 index1 i1 1 2 3 i2 4 5 6 i3 7 8 9 >>> df2 = df.reindex(('i3', 'i1', 'i2'), columns=('c2', 'c1', 'c3')) >>> df2 columns1 c2 c1 c3 index1 i3 8 7 9 i1 2 1 3 i2 5 4 6 >>> df_.equals(df, df2) False >>> df_.equals(df, df2, ignore_order=(0,1)) True >>> df2 = df.copy() >>> df2.index = [1,2,3] >>> df2 columns1 c1 c2 c3 1 1 2 3 2 4 5 6 3 7 8 9 >>> df_.equals(df, df2) False >>> df_.equals(df, df2, ignore_indices={0}) True >>> df2 = df.reindex(('i3', 'i1', 'i2')) >>> df2 columns1 c1 c2 c3 index1 i3 7 8 9 i1 1 2 3 i2 4 5 6 >>> df_.equals(df, df2, ignore_indices={0}) # does not ignore row order! False >>> df_.equals(df, df2, ignore_order={0}) True >>> df2 = df.copy() >>> df2.index.name = 'other' >>> df_.equals(df, df2) # df.index.name must match as well, same goes for df.columns.name False ''' result = _equals(df1, df2, ignore_order, ignore_indices, all_close) if _return_reason: return result else: return result[0]
[ "def", "equals", "(", "df1", ",", "df2", ",", "ignore_order", "=", "set", "(", ")", ",", "ignore_indices", "=", "set", "(", ")", ",", "all_close", "=", "False", ",", "_return_reason", "=", "False", ")", ":", "result", "=", "_equals", "(", "df1", ",",...
Get whether 2 data frames are equal. ``NaN`` is considered equal to ``NaN`` and `None`. Parameters ---------- df1 : ~pandas.DataFrame Data frame to compare. df2 : ~pandas.DataFrame Data frame to compare. ignore_order : ~typing.Set[int] Axi in which to ignore order. ignore_indices : ~typing.Set[int] Axi of which to ignore the index. E.g. ``{1}`` allows differences in ``df.columns.name`` and ``df.columns.equals(df2.columns)``. all_close : bool If `False`, values must match exactly, if `True`, floats are compared as if compared with `numpy.isclose`. _return_reason : bool Internal. If `True`, `equals` returns a tuple containing the reason, else `equals` only returns a bool indicating equality (or equivalence rather). Returns ------- bool Whether they are equal (after ignoring according to the parameters). Internal note: if ``_return_reason``, ``Tuple[bool, str or None]`` is returned. The former is whether they're equal, the latter is `None` if equal or a short explanation of why the data frames aren't equal, otherwise. Notes ----- All values (including those of indices) must be copyable and ``__eq__`` must be such that a copy must equal its original. A value must equal itself unless it's ``NaN``. Values needn't be orderable or hashable (however pandas requires index values to be orderable and hashable). By consequence, this is not an efficient function, but it is flexible. Examples -------- >>> from pytil import data_frame as df_ >>> import pandas as pd >>> df = pd.DataFrame([ ... [1, 2, 3], ... [4, 5, 6], ... [7, 8, 9] ... ], ... index=pd.Index(('i1', 'i2', 'i3'), name='index1'), ... columns=pd.Index(('c1', 'c2', 'c3'), name='columns1') ... ) >>> df columns1 c1 c2 c3 index1 i1 1 2 3 i2 4 5 6 i3 7 8 9 >>> df2 = df.reindex(('i3', 'i1', 'i2'), columns=('c2', 'c1', 'c3')) >>> df2 columns1 c2 c1 c3 index1 i3 8 7 9 i1 2 1 3 i2 5 4 6 >>> df_.equals(df, df2) False >>> df_.equals(df, df2, ignore_order=(0,1)) True >>> df2 = df.copy() >>> df2.index = [1,2,3] >>> df2 columns1 c1 c2 c3 1 1 2 3 2 4 5 6 3 7 8 9 >>> df_.equals(df, df2) False >>> df_.equals(df, df2, ignore_indices={0}) True >>> df2 = df.reindex(('i3', 'i1', 'i2')) >>> df2 columns1 c1 c2 c3 index1 i3 7 8 9 i1 1 2 3 i2 4 5 6 >>> df_.equals(df, df2, ignore_indices={0}) # does not ignore row order! False >>> df_.equals(df, df2, ignore_order={0}) True >>> df2 = df.copy() >>> df2.index.name = 'other' >>> df_.equals(df, df2) # df.index.name must match as well, same goes for df.columns.name False
[ "Get", "whether", "2", "data", "frames", "are", "equal", "." ]
train
https://github.com/timdiels/pytil/blob/086a3f8d52caecdd9d1c9f66c8d8a6d38667b00b/pytil/data_frame.py#L128-L231
timdiels/pytil
pytil/data_frame.py
_try_mask_first_row
def _try_mask_first_row(row, values, all_close, ignore_order): ''' mask first row in 2d array values : 2d masked array Each row is either fully masked or not masked at all ignore_order : bool Ignore column order Return whether masked a row. If False, masked nothing. ''' for row2 in values: mask = ma.getmaskarray(row2) assert mask.sum() in (0, len(mask)) # sanity check: all or none masked if mask[0]: # Note: at this point row2's mask is either all False or all True continue # mask each value of row1 in row2 if _try_mask_row(row, row2, all_close, ignore_order): return True # row did not match return False
python
def _try_mask_first_row(row, values, all_close, ignore_order): ''' mask first row in 2d array values : 2d masked array Each row is either fully masked or not masked at all ignore_order : bool Ignore column order Return whether masked a row. If False, masked nothing. ''' for row2 in values: mask = ma.getmaskarray(row2) assert mask.sum() in (0, len(mask)) # sanity check: all or none masked if mask[0]: # Note: at this point row2's mask is either all False or all True continue # mask each value of row1 in row2 if _try_mask_row(row, row2, all_close, ignore_order): return True # row did not match return False
[ "def", "_try_mask_first_row", "(", "row", ",", "values", ",", "all_close", ",", "ignore_order", ")", ":", "for", "row2", "in", "values", ":", "mask", "=", "ma", ".", "getmaskarray", "(", "row2", ")", "assert", "mask", ".", "sum", "(", ")", "in", "(", ...
mask first row in 2d array values : 2d masked array Each row is either fully masked or not masked at all ignore_order : bool Ignore column order Return whether masked a row. If False, masked nothing.
[ "mask", "first", "row", "in", "2d", "array" ]
train
https://github.com/timdiels/pytil/blob/086a3f8d52caecdd9d1c9f66c8d8a6d38667b00b/pytil/data_frame.py#L303-L324
timdiels/pytil
pytil/data_frame.py
_try_mask_row
def _try_mask_row(row1, row2, all_close, ignore_order): ''' if each value in row1 matches a value in row2, mask row2 row1 1d array row2 1d masked array whose mask is all False ignore_order : bool Ignore column order all_close : bool compare with np.isclose instead of == Return whether masked the row ''' if ignore_order: for value1 in row1: if not _try_mask_first_value(value1, row2, all_close): row2.mask = ma.nomask return False else: for value1, value2 in zip(row1, row2): if not _value_equals(value1, value2, all_close): return False row2[:] = ma.masked assert row2.mask.all() # sanity check return True
python
def _try_mask_row(row1, row2, all_close, ignore_order): ''' if each value in row1 matches a value in row2, mask row2 row1 1d array row2 1d masked array whose mask is all False ignore_order : bool Ignore column order all_close : bool compare with np.isclose instead of == Return whether masked the row ''' if ignore_order: for value1 in row1: if not _try_mask_first_value(value1, row2, all_close): row2.mask = ma.nomask return False else: for value1, value2 in zip(row1, row2): if not _value_equals(value1, value2, all_close): return False row2[:] = ma.masked assert row2.mask.all() # sanity check return True
[ "def", "_try_mask_row", "(", "row1", ",", "row2", ",", "all_close", ",", "ignore_order", ")", ":", "if", "ignore_order", ":", "for", "value1", "in", "row1", ":", "if", "not", "_try_mask_first_value", "(", "value1", ",", "row2", ",", "all_close", ")", ":", ...
if each value in row1 matches a value in row2, mask row2 row1 1d array row2 1d masked array whose mask is all False ignore_order : bool Ignore column order all_close : bool compare with np.isclose instead of == Return whether masked the row
[ "if", "each", "value", "in", "row1", "matches", "a", "value", "in", "row2", "mask", "row2" ]
train
https://github.com/timdiels/pytil/blob/086a3f8d52caecdd9d1c9f66c8d8a6d38667b00b/pytil/data_frame.py#L326-L352
timdiels/pytil
pytil/data_frame.py
_try_mask_first_value
def _try_mask_first_value(value, row, all_close): ''' mask first value in row value1 : ~typing.Any row : 1d masked array all_close : bool compare with np.isclose instead of == Return whether masked a value ''' # Compare value to row for i, value2 in enumerate(row): if _value_equals(value, value2, all_close): row[i] = ma.masked return True return False
python
def _try_mask_first_value(value, row, all_close): ''' mask first value in row value1 : ~typing.Any row : 1d masked array all_close : bool compare with np.isclose instead of == Return whether masked a value ''' # Compare value to row for i, value2 in enumerate(row): if _value_equals(value, value2, all_close): row[i] = ma.masked return True return False
[ "def", "_try_mask_first_value", "(", "value", ",", "row", ",", "all_close", ")", ":", "# Compare value to row", "for", "i", ",", "value2", "in", "enumerate", "(", "row", ")", ":", "if", "_value_equals", "(", "value", ",", "value2", ",", "all_close", ")", "...
mask first value in row value1 : ~typing.Any row : 1d masked array all_close : bool compare with np.isclose instead of == Return whether masked a value
[ "mask", "first", "value", "in", "row" ]
train
https://github.com/timdiels/pytil/blob/086a3f8d52caecdd9d1c9f66c8d8a6d38667b00b/pytil/data_frame.py#L354-L370
timdiels/pytil
pytil/data_frame.py
_value_equals
def _value_equals(value1, value2, all_close): ''' Get whether 2 values are equal value1, value2 : ~typing.Any all_close : bool compare with np.isclose instead of == ''' if value1 is None: value1 = np.nan if value2 is None: value2 = np.nan are_floats = np.can_cast(type(value1), float) and np.can_cast(type(value2), float) if all_close and are_floats: return np.isclose(value1, value2, equal_nan=True) else: if are_floats: return value1 == value2 or (value1 != value1 and value2 != value2) else: return value1 == value2
python
def _value_equals(value1, value2, all_close): ''' Get whether 2 values are equal value1, value2 : ~typing.Any all_close : bool compare with np.isclose instead of == ''' if value1 is None: value1 = np.nan if value2 is None: value2 = np.nan are_floats = np.can_cast(type(value1), float) and np.can_cast(type(value2), float) if all_close and are_floats: return np.isclose(value1, value2, equal_nan=True) else: if are_floats: return value1 == value2 or (value1 != value1 and value2 != value2) else: return value1 == value2
[ "def", "_value_equals", "(", "value1", ",", "value2", ",", "all_close", ")", ":", "if", "value1", "is", "None", ":", "value1", "=", "np", ".", "nan", "if", "value2", "is", "None", ":", "value2", "=", "np", ".", "nan", "are_floats", "=", "np", ".", ...
Get whether 2 values are equal value1, value2 : ~typing.Any all_close : bool compare with np.isclose instead of ==
[ "Get", "whether", "2", "values", "are", "equal" ]
train
https://github.com/timdiels/pytil/blob/086a3f8d52caecdd9d1c9f66c8d8a6d38667b00b/pytil/data_frame.py#L372-L392
timdiels/pytil
pytil/data_frame.py
assert_equals
def assert_equals(df1, df2, ignore_order=set(), ignore_indices=set(), all_close=False, _return_reason=False): ''' Assert 2 data frames are equal A more verbose form of ``assert equals(df1, df2, ...)``. See `equals` for an explanation of the parameters. Parameters ---------- df1 : ~pandas.DataFrame Actual data frame. df2 : ~pandas.DataFrame Expected data frame. ignore_order : ~typing.Set[int] ignore_indices : ~typing.Set[int] all_close : bool ''' equals_, reason = equals(df1, df2, ignore_order, ignore_indices, all_close, _return_reason=True) assert equals_, '{}\n\n{}\n\n{}'.format(reason, df1.to_string(), df2.to_string())
python
def assert_equals(df1, df2, ignore_order=set(), ignore_indices=set(), all_close=False, _return_reason=False): ''' Assert 2 data frames are equal A more verbose form of ``assert equals(df1, df2, ...)``. See `equals` for an explanation of the parameters. Parameters ---------- df1 : ~pandas.DataFrame Actual data frame. df2 : ~pandas.DataFrame Expected data frame. ignore_order : ~typing.Set[int] ignore_indices : ~typing.Set[int] all_close : bool ''' equals_, reason = equals(df1, df2, ignore_order, ignore_indices, all_close, _return_reason=True) assert equals_, '{}\n\n{}\n\n{}'.format(reason, df1.to_string(), df2.to_string())
[ "def", "assert_equals", "(", "df1", ",", "df2", ",", "ignore_order", "=", "set", "(", ")", ",", "ignore_indices", "=", "set", "(", ")", ",", "all_close", "=", "False", ",", "_return_reason", "=", "False", ")", ":", "equals_", ",", "reason", "=", "equal...
Assert 2 data frames are equal A more verbose form of ``assert equals(df1, df2, ...)``. See `equals` for an explanation of the parameters. Parameters ---------- df1 : ~pandas.DataFrame Actual data frame. df2 : ~pandas.DataFrame Expected data frame. ignore_order : ~typing.Set[int] ignore_indices : ~typing.Set[int] all_close : bool
[ "Assert", "2", "data", "frames", "are", "equal" ]
train
https://github.com/timdiels/pytil/blob/086a3f8d52caecdd9d1c9f66c8d8a6d38667b00b/pytil/data_frame.py#L394-L411
Knoema/knoema-python-driver
knoema/api_definitions.py
is_equal_strings_ignore_case
def is_equal_strings_ignore_case(first, second): """The function compares strings ignoring case""" if first and second: return first.upper() == second.upper() else: return not (first or second)
python
def is_equal_strings_ignore_case(first, second): """The function compares strings ignoring case""" if first and second: return first.upper() == second.upper() else: return not (first or second)
[ "def", "is_equal_strings_ignore_case", "(", "first", ",", "second", ")", ":", "if", "first", "and", "second", ":", "return", "first", ".", "upper", "(", ")", "==", "second", ".", "upper", "(", ")", "else", ":", "return", "not", "(", "first", "or", "sec...
The function compares strings ignoring case
[ "The", "function", "compares", "strings", "ignoring", "case" ]
train
https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_definitions.py#L6-L11
Knoema/knoema-python-driver
knoema/api_definitions.py
Dataset.find_dimension_by_name
def find_dimension_by_name(self, dim_name): """the method searching dimension with a given name""" for dim in self.dimensions: if is_equal_strings_ignore_case(dim.name, dim_name): return dim return None
python
def find_dimension_by_name(self, dim_name): """the method searching dimension with a given name""" for dim in self.dimensions: if is_equal_strings_ignore_case(dim.name, dim_name): return dim return None
[ "def", "find_dimension_by_name", "(", "self", ",", "dim_name", ")", ":", "for", "dim", "in", "self", ".", "dimensions", ":", "if", "is_equal_strings_ignore_case", "(", "dim", ".", "name", ",", "dim_name", ")", ":", "return", "dim", "return", "None" ]
the method searching dimension with a given name
[ "the", "method", "searching", "dimension", "with", "a", "given", "name" ]
train
https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_definitions.py#L96-L102
Knoema/knoema-python-driver
knoema/api_definitions.py
Dataset.find_dimension_by_id
def find_dimension_by_id(self, dim_id): """the method searching dimension with a given id""" for dim in self.dimensions: if is_equal_strings_ignore_case(dim.id, dim_id): return dim return None
python
def find_dimension_by_id(self, dim_id): """the method searching dimension with a given id""" for dim in self.dimensions: if is_equal_strings_ignore_case(dim.id, dim_id): return dim return None
[ "def", "find_dimension_by_id", "(", "self", ",", "dim_id", ")", ":", "for", "dim", "in", "self", ".", "dimensions", ":", "if", "is_equal_strings_ignore_case", "(", "dim", ".", "id", ",", "dim_id", ")", ":", "return", "dim", "return", "None" ]
the method searching dimension with a given id
[ "the", "method", "searching", "dimension", "with", "a", "given", "id" ]
train
https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_definitions.py#L104-L110
Knoema/knoema-python-driver
knoema/api_definitions.py
PivotRequest.save_to_json
def save_to_json(self): """The method saves data to json from object""" requestvalues = { 'Dataset': self.dataset, 'Header' : self._get_item_array(self.header), 'Filter' : self._get_item_array(self.filter), 'Stub' : self._get_item_array(self.stub), 'Frequencies': self.frequencies } return json.dumps(requestvalues)
python
def save_to_json(self): """The method saves data to json from object""" requestvalues = { 'Dataset': self.dataset, 'Header' : self._get_item_array(self.header), 'Filter' : self._get_item_array(self.filter), 'Stub' : self._get_item_array(self.stub), 'Frequencies': self.frequencies } return json.dumps(requestvalues)
[ "def", "save_to_json", "(", "self", ")", ":", "requestvalues", "=", "{", "'Dataset'", ":", "self", ".", "dataset", ",", "'Header'", ":", "self", ".", "_get_item_array", "(", "self", ".", "header", ")", ",", "'Filter'", ":", "self", ".", "_get_item_array", ...
The method saves data to json from object
[ "The", "method", "saves", "data", "to", "json", "from", "object" ]
train
https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_definitions.py#L151-L160
Knoema/knoema-python-driver
knoema/api_definitions.py
DatasetUpload.save_to_json
def save_to_json(self): """The method saves DatasetUpload to json from object""" requestvalues = { 'DatasetId': self.dataset, 'Name': self.name, 'Description': self.description, 'Source': self.source, 'PubDate': self.publication_date, 'AccessedOn': self.accessed_on, 'Url': self.dataset_ref, 'UploadFormatType': self.upload_format_type, 'Columns': self.columns, 'FileProperty': self.file_property.__dict__, 'FlatDSUpdateOptions': self.flat_ds_update_options, 'Public': self.public } return json.dumps(requestvalues)
python
def save_to_json(self): """The method saves DatasetUpload to json from object""" requestvalues = { 'DatasetId': self.dataset, 'Name': self.name, 'Description': self.description, 'Source': self.source, 'PubDate': self.publication_date, 'AccessedOn': self.accessed_on, 'Url': self.dataset_ref, 'UploadFormatType': self.upload_format_type, 'Columns': self.columns, 'FileProperty': self.file_property.__dict__, 'FlatDSUpdateOptions': self.flat_ds_update_options, 'Public': self.public } return json.dumps(requestvalues)
[ "def", "save_to_json", "(", "self", ")", ":", "requestvalues", "=", "{", "'DatasetId'", ":", "self", ".", "dataset", ",", "'Name'", ":", "self", ".", "name", ",", "'Description'", ":", "self", ".", "description", ",", "'Source'", ":", "self", ".", "sourc...
The method saves DatasetUpload to json from object
[ "The", "method", "saves", "DatasetUpload", "to", "json", "from", "object" ]
train
https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_definitions.py#L271-L287
Knoema/knoema-python-driver
knoema/api_definitions.py
DatasetVerifyRequest.save_to_json
def save_to_json(self): """The method saves data to json from object""" requestvalues = { 'id': self.dataset, 'publicationDate': self.publication_date.strftime('%Y-%m-%d'), 'source': self.source, 'refUrl': self.refernce_url, } return json.dumps(requestvalues)
python
def save_to_json(self): """The method saves data to json from object""" requestvalues = { 'id': self.dataset, 'publicationDate': self.publication_date.strftime('%Y-%m-%d'), 'source': self.source, 'refUrl': self.refernce_url, } return json.dumps(requestvalues)
[ "def", "save_to_json", "(", "self", ")", ":", "requestvalues", "=", "{", "'id'", ":", "self", ".", "dataset", ",", "'publicationDate'", ":", "self", ".", "publication_date", ".", "strftime", "(", "'%Y-%m-%d'", ")", ",", "'source'", ":", "self", ".", "sourc...
The method saves data to json from object
[ "The", "method", "saves", "data", "to", "json", "from", "object" ]
train
https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_definitions.py#L319-L328
ask/redish
redish/proxy.py
Proxy.keyspace
def keyspace(self, keyspace): """ Convenient, consistent access to a sub-set of all keys. """ if FORMAT_SPEC.search(keyspace): return KeyspacedProxy(self, keyspace) else: return KeyspacedProxy(self, self._keyspaces[keyspace])
python
def keyspace(self, keyspace): """ Convenient, consistent access to a sub-set of all keys. """ if FORMAT_SPEC.search(keyspace): return KeyspacedProxy(self, keyspace) else: return KeyspacedProxy(self, self._keyspaces[keyspace])
[ "def", "keyspace", "(", "self", ",", "keyspace", ")", ":", "if", "FORMAT_SPEC", ".", "search", "(", "keyspace", ")", ":", "return", "KeyspacedProxy", "(", "self", ",", "keyspace", ")", "else", ":", "return", "KeyspacedProxy", "(", "self", ",", "self", "....
Convenient, consistent access to a sub-set of all keys.
[ "Convenient", "consistent", "access", "to", "a", "sub", "-", "set", "of", "all", "keys", "." ]
train
https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/proxy.py#L185-L192