repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser._example_from_definition
def _example_from_definition(self, prop_spec): """Get an example from a property specification linked to a definition. Args: prop_spec: specification of the property you want an example of. Returns: An example. """ # Get value from definition definition_name = self.get_definition_name_from_ref(prop_spec['$ref']) if self.build_one_definition_example(definition_name): example_dict = self.definitions_example[definition_name] if not isinstance(example_dict, dict): return example_dict example = dict((example_name, example_value) for example_name, example_value in example_dict.items()) return example
python
def _example_from_definition(self, prop_spec): """Get an example from a property specification linked to a definition. Args: prop_spec: specification of the property you want an example of. Returns: An example. """ # Get value from definition definition_name = self.get_definition_name_from_ref(prop_spec['$ref']) if self.build_one_definition_example(definition_name): example_dict = self.definitions_example[definition_name] if not isinstance(example_dict, dict): return example_dict example = dict((example_name, example_value) for example_name, example_value in example_dict.items()) return example
[ "def", "_example_from_definition", "(", "self", ",", "prop_spec", ")", ":", "# Get value from definition", "definition_name", "=", "self", ".", "get_definition_name_from_ref", "(", "prop_spec", "[", "'$ref'", "]", ")", "if", "self", ".", "build_one_definition_example", ...
Get an example from a property specification linked to a definition. Args: prop_spec: specification of the property you want an example of. Returns: An example.
[ "Get", "an", "example", "from", "a", "property", "specification", "linked", "to", "a", "definition", "." ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L332-L349
train
30,000
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser._example_from_complex_def
def _example_from_complex_def(self, prop_spec): """Get an example from a property specification. In case there is no "type" key in the root of the dictionary. Args: prop_spec: property specification you want an example of. Returns: An example. """ if 'schema' not in prop_spec: return [{}] elif 'type' not in prop_spec['schema']: definition_name = self.get_definition_name_from_ref(prop_spec['schema']['$ref']) if self.build_one_definition_example(definition_name): return self.definitions_example[definition_name] elif prop_spec['schema']['type'] == 'array': # Array with definition # Get value from definition if 'items' in prop_spec.keys(): definition_name = self.get_definition_name_from_ref(prop_spec['items']['$ref']) else: if '$ref' in prop_spec['schema']['items']: definition_name = self.get_definition_name_from_ref(prop_spec['schema']['items']['$ref']) else: definition_name = self.get_definition_name_from_ref(prop_spec['schema']['items']['type']) return [definition_name] return [self.definitions_example[definition_name]] else: return self.get_example_from_prop_spec(prop_spec['schema'])
python
def _example_from_complex_def(self, prop_spec): """Get an example from a property specification. In case there is no "type" key in the root of the dictionary. Args: prop_spec: property specification you want an example of. Returns: An example. """ if 'schema' not in prop_spec: return [{}] elif 'type' not in prop_spec['schema']: definition_name = self.get_definition_name_from_ref(prop_spec['schema']['$ref']) if self.build_one_definition_example(definition_name): return self.definitions_example[definition_name] elif prop_spec['schema']['type'] == 'array': # Array with definition # Get value from definition if 'items' in prop_spec.keys(): definition_name = self.get_definition_name_from_ref(prop_spec['items']['$ref']) else: if '$ref' in prop_spec['schema']['items']: definition_name = self.get_definition_name_from_ref(prop_spec['schema']['items']['$ref']) else: definition_name = self.get_definition_name_from_ref(prop_spec['schema']['items']['type']) return [definition_name] return [self.definitions_example[definition_name]] else: return self.get_example_from_prop_spec(prop_spec['schema'])
[ "def", "_example_from_complex_def", "(", "self", ",", "prop_spec", ")", ":", "if", "'schema'", "not", "in", "prop_spec", ":", "return", "[", "{", "}", "]", "elif", "'type'", "not", "in", "prop_spec", "[", "'schema'", "]", ":", "definition_name", "=", "self...
Get an example from a property specification. In case there is no "type" key in the root of the dictionary. Args: prop_spec: property specification you want an example of. Returns: An example.
[ "Get", "an", "example", "from", "a", "property", "specification", "." ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L351-L380
train
30,001
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser._example_from_array_spec
def _example_from_array_spec(self, prop_spec): """Get an example from a property specification of an array. Args: prop_spec: property specification you want an example of. Returns: An example array. """ # if items is a list, then each item has its own spec if isinstance(prop_spec['items'], list): return [self.get_example_from_prop_spec(item_prop_spec) for item_prop_spec in prop_spec['items']] # Standard types in array elif 'type' in prop_spec['items'].keys(): if 'format' in prop_spec['items'].keys() and prop_spec['items']['format'] == 'date-time': return self._get_example_from_basic_type('datetime') else: return self._get_example_from_basic_type(prop_spec['items']['type']) # Array with definition elif ('$ref' in prop_spec['items'].keys() or ('schema' in prop_spec and'$ref' in prop_spec['schema']['items'].keys())): # Get value from definition definition_name = self.get_definition_name_from_ref(prop_spec['items']['$ref']) or \ self.get_definition_name_from_ref(prop_spec['schema']['items']['$ref']) if self.build_one_definition_example(definition_name): example_dict = self.definitions_example[definition_name] if not isinstance(example_dict, dict): return [example_dict] if len(example_dict) == 1: try: # Python 2.7 res = example_dict[example_dict.keys()[0]] except TypeError: # Python 3 res = example_dict[list(example_dict)[0]] return res else: return_value = {} for example_name, example_value in example_dict.items(): return_value[example_name] = example_value return [return_value] elif 'properties' in prop_spec['items']: prop_example = {} for prop_name, prop_spec in prop_spec['items']['properties'].items(): example = self.get_example_from_prop_spec(prop_spec) if example is not None: prop_example[prop_name] = example return [prop_example]
python
def _example_from_array_spec(self, prop_spec): """Get an example from a property specification of an array. Args: prop_spec: property specification you want an example of. Returns: An example array. """ # if items is a list, then each item has its own spec if isinstance(prop_spec['items'], list): return [self.get_example_from_prop_spec(item_prop_spec) for item_prop_spec in prop_spec['items']] # Standard types in array elif 'type' in prop_spec['items'].keys(): if 'format' in prop_spec['items'].keys() and prop_spec['items']['format'] == 'date-time': return self._get_example_from_basic_type('datetime') else: return self._get_example_from_basic_type(prop_spec['items']['type']) # Array with definition elif ('$ref' in prop_spec['items'].keys() or ('schema' in prop_spec and'$ref' in prop_spec['schema']['items'].keys())): # Get value from definition definition_name = self.get_definition_name_from_ref(prop_spec['items']['$ref']) or \ self.get_definition_name_from_ref(prop_spec['schema']['items']['$ref']) if self.build_one_definition_example(definition_name): example_dict = self.definitions_example[definition_name] if not isinstance(example_dict, dict): return [example_dict] if len(example_dict) == 1: try: # Python 2.7 res = example_dict[example_dict.keys()[0]] except TypeError: # Python 3 res = example_dict[list(example_dict)[0]] return res else: return_value = {} for example_name, example_value in example_dict.items(): return_value[example_name] = example_value return [return_value] elif 'properties' in prop_spec['items']: prop_example = {} for prop_name, prop_spec in prop_spec['items']['properties'].items(): example = self.get_example_from_prop_spec(prop_spec) if example is not None: prop_example[prop_name] = example return [prop_example]
[ "def", "_example_from_array_spec", "(", "self", ",", "prop_spec", ")", ":", "# if items is a list, then each item has its own spec", "if", "isinstance", "(", "prop_spec", "[", "'items'", "]", ",", "list", ")", ":", "return", "[", "self", ".", "get_example_from_prop_sp...
Get an example from a property specification of an array. Args: prop_spec: property specification you want an example of. Returns: An example array.
[ "Get", "an", "example", "from", "a", "property", "specification", "of", "an", "array", "." ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L382-L429
train
30,002
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser.get_dict_definition
def get_dict_definition(self, dict, get_list=False): """Get the definition name of the given dict. Args: dict: dict to test. get_list: if set to true, return a list of definition that match the body. if False, only return the first. Returns: The definition name or None if the dict does not match any definition. If get_list is True, return a list of definition_name. """ list_def_candidate = [] for definition_name in self.specification['definitions'].keys(): if self.validate_definition(definition_name, dict): if not get_list: return definition_name list_def_candidate.append(definition_name) if get_list: return list_def_candidate return None
python
def get_dict_definition(self, dict, get_list=False): """Get the definition name of the given dict. Args: dict: dict to test. get_list: if set to true, return a list of definition that match the body. if False, only return the first. Returns: The definition name or None if the dict does not match any definition. If get_list is True, return a list of definition_name. """ list_def_candidate = [] for definition_name in self.specification['definitions'].keys(): if self.validate_definition(definition_name, dict): if not get_list: return definition_name list_def_candidate.append(definition_name) if get_list: return list_def_candidate return None
[ "def", "get_dict_definition", "(", "self", ",", "dict", ",", "get_list", "=", "False", ")", ":", "list_def_candidate", "=", "[", "]", "for", "definition_name", "in", "self", ".", "specification", "[", "'definitions'", "]", ".", "keys", "(", ")", ":", "if",...
Get the definition name of the given dict. Args: dict: dict to test. get_list: if set to true, return a list of definition that match the body. if False, only return the first. Returns: The definition name or None if the dict does not match any definition. If get_list is True, return a list of definition_name.
[ "Get", "the", "definition", "name", "of", "the", "given", "dict", "." ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L431-L451
train
30,003
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser.validate_additional_properties
def validate_additional_properties(self, valid_response, response): """Validates additional properties. In additional properties, we only need to compare the values of the dict, not the keys Args: valid_response: An example response (for example generated in _get_example_from_properties(self, spec)) Type is DICT response: The actual dict coming from the response Type is DICT Returns: A boolean - whether the actual response validates against the given example """ assert isinstance(valid_response, dict) assert isinstance(response, dict) # the type of the value of the first key/value in valid_response is our # expected type - if it is a dict or list, we must go deeper first_value = valid_response[list(valid_response)[0]] # dict if isinstance(first_value, dict): # try to find a definition for that first value definition = None definition_name = self.get_dict_definition(first_value) if definition_name is None: definition = self._definition_from_example(first_value) definition_name = 'self generated' for item in response.values(): if not self.validate_definition(definition_name, item, definition=definition): return False return True # TODO: list if isinstance(first_value, list): raise Exception("Not implemented yet") # simple types # all values must be of that type in both valid and actual response try: assert all(isinstance(y, type(first_value)) for _, y in response.items()) assert all(isinstance(y, type(first_value)) for _, y in valid_response.items()) return True except Exception: return False
python
def validate_additional_properties(self, valid_response, response): """Validates additional properties. In additional properties, we only need to compare the values of the dict, not the keys Args: valid_response: An example response (for example generated in _get_example_from_properties(self, spec)) Type is DICT response: The actual dict coming from the response Type is DICT Returns: A boolean - whether the actual response validates against the given example """ assert isinstance(valid_response, dict) assert isinstance(response, dict) # the type of the value of the first key/value in valid_response is our # expected type - if it is a dict or list, we must go deeper first_value = valid_response[list(valid_response)[0]] # dict if isinstance(first_value, dict): # try to find a definition for that first value definition = None definition_name = self.get_dict_definition(first_value) if definition_name is None: definition = self._definition_from_example(first_value) definition_name = 'self generated' for item in response.values(): if not self.validate_definition(definition_name, item, definition=definition): return False return True # TODO: list if isinstance(first_value, list): raise Exception("Not implemented yet") # simple types # all values must be of that type in both valid and actual response try: assert all(isinstance(y, type(first_value)) for _, y in response.items()) assert all(isinstance(y, type(first_value)) for _, y in valid_response.items()) return True except Exception: return False
[ "def", "validate_additional_properties", "(", "self", ",", "valid_response", ",", "response", ")", ":", "assert", "isinstance", "(", "valid_response", ",", "dict", ")", "assert", "isinstance", "(", "response", ",", "dict", ")", "# the type of the value of the first ke...
Validates additional properties. In additional properties, we only need to compare the values of the dict, not the keys Args: valid_response: An example response (for example generated in _get_example_from_properties(self, spec)) Type is DICT response: The actual dict coming from the response Type is DICT Returns: A boolean - whether the actual response validates against the given example
[ "Validates", "additional", "properties", ".", "In", "additional", "properties", "we", "only", "need", "to", "compare", "the", "values", "of", "the", "dict", "not", "the", "keys" ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L453-L500
train
30,004
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser.validate_definition
def validate_definition(self, definition_name, dict_to_test, definition=None): """Validate the given dict according to the given definition. Args: definition_name: name of the the definition. dict_to_test: dict to test. Returns: True if the given dict match the definition, False otherwise. """ if (definition_name not in self.specification['definitions'].keys() and definition is None): # reject unknown definition return False # Check all required in dict_to_test spec_def = definition or self.specification['definitions'][definition_name] all_required_keys_present = all(req in dict_to_test.keys() for req in spec_def.get('required', {})) if 'required' in spec_def and not all_required_keys_present: return False # Check no extra arg & type properties_dict = spec_def.get('properties', {}) for key, value in dict_to_test.items(): if value is not None: if key not in properties_dict: # Extra arg return False else: # Check type if not self._validate_type(properties_dict[key], value): return False return True
python
def validate_definition(self, definition_name, dict_to_test, definition=None): """Validate the given dict according to the given definition. Args: definition_name: name of the the definition. dict_to_test: dict to test. Returns: True if the given dict match the definition, False otherwise. """ if (definition_name not in self.specification['definitions'].keys() and definition is None): # reject unknown definition return False # Check all required in dict_to_test spec_def = definition or self.specification['definitions'][definition_name] all_required_keys_present = all(req in dict_to_test.keys() for req in spec_def.get('required', {})) if 'required' in spec_def and not all_required_keys_present: return False # Check no extra arg & type properties_dict = spec_def.get('properties', {}) for key, value in dict_to_test.items(): if value is not None: if key not in properties_dict: # Extra arg return False else: # Check type if not self._validate_type(properties_dict[key], value): return False return True
[ "def", "validate_definition", "(", "self", ",", "definition_name", ",", "dict_to_test", ",", "definition", "=", "None", ")", ":", "if", "(", "definition_name", "not", "in", "self", ".", "specification", "[", "'definitions'", "]", ".", "keys", "(", ")", "and"...
Validate the given dict according to the given definition. Args: definition_name: name of the the definition. dict_to_test: dict to test. Returns: True if the given dict match the definition, False otherwise.
[ "Validate", "the", "given", "dict", "according", "to", "the", "given", "definition", "." ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L502-L533
train
30,005
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser._validate_type
def _validate_type(self, properties_spec, value): """Validate the given value with the given property spec. Args: properties_dict: specification of the property to check (From definition not route). value: value to check. Returns: True if the value is valid for the given spec. """ if 'type' not in properties_spec.keys(): # Validate sub definition def_name = self.get_definition_name_from_ref(properties_spec['$ref']) return self.validate_definition(def_name, value) # Validate array elif properties_spec['type'] == 'array': if not isinstance(value, list): return False # Check type if ('type' in properties_spec['items'].keys() and any(not self.check_type(item, properties_spec['items']['type']) for item in value)): return False # Check ref elif ('$ref' in properties_spec['items'].keys()): def_name = self.get_definition_name_from_ref(properties_spec['items']['$ref']) if any(not self.validate_definition(def_name, item) for item in value): return False else: # Classic types if not self.check_type(value, properties_spec['type']): return False return True
python
def _validate_type(self, properties_spec, value): """Validate the given value with the given property spec. Args: properties_dict: specification of the property to check (From definition not route). value: value to check. Returns: True if the value is valid for the given spec. """ if 'type' not in properties_spec.keys(): # Validate sub definition def_name = self.get_definition_name_from_ref(properties_spec['$ref']) return self.validate_definition(def_name, value) # Validate array elif properties_spec['type'] == 'array': if not isinstance(value, list): return False # Check type if ('type' in properties_spec['items'].keys() and any(not self.check_type(item, properties_spec['items']['type']) for item in value)): return False # Check ref elif ('$ref' in properties_spec['items'].keys()): def_name = self.get_definition_name_from_ref(properties_spec['items']['$ref']) if any(not self.validate_definition(def_name, item) for item in value): return False else: # Classic types if not self.check_type(value, properties_spec['type']): return False return True
[ "def", "_validate_type", "(", "self", ",", "properties_spec", ",", "value", ")", ":", "if", "'type'", "not", "in", "properties_spec", ".", "keys", "(", ")", ":", "# Validate sub definition", "def_name", "=", "self", ".", "get_definition_name_from_ref", "(", "pro...
Validate the given value with the given property spec. Args: properties_dict: specification of the property to check (From definition not route). value: value to check. Returns: True if the value is valid for the given spec.
[ "Validate", "the", "given", "value", "with", "the", "given", "property", "spec", "." ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L535-L569
train
30,006
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser.get_paths_data
def get_paths_data(self): """Get data for each paths in the swagger specification. Get also the list of operationId. """ for path, path_spec in self.specification['paths'].items(): path = u'{0}{1}'.format(self.base_path, path) self.paths[path] = {} # Add path-level parameters default_parameters = {} if 'parameters' in path_spec: self._add_parameters(default_parameters, path_spec['parameters']) for http_method in path_spec.keys(): if http_method not in self._HTTP_VERBS: continue self.paths[path][http_method] = {} # Add to operation list action = path_spec[http_method] tag = action['tags'][0] if 'tags' in action.keys() and action['tags'] else None if 'operationId' in action.keys(): self.operation[action['operationId']] = (path, http_method, tag) else: # Note: the encoding chosen below isn't very important in this # case; what matters is a byte string that is unique. # URL paths and http methods should encode to UTF-8 safely. h = hashlib.sha256() h.update(("{0}|{1}".format(http_method, path)).encode('utf-8')) self.generated_operation[h.hexdigest()] = (path, http_method, tag) # Get parameters self.paths[path][http_method]['parameters'] = default_parameters.copy() if 'parameters' in action.keys(): self._add_parameters(self.paths[path][http_method]['parameters'], action['parameters']) # Get responses self.paths[path][http_method]['responses'] = action['responses'] # Get mime types for this action if 'consumes' in action.keys(): self.paths[path][http_method]['consumes'] = action['consumes']
python
def get_paths_data(self): """Get data for each paths in the swagger specification. Get also the list of operationId. """ for path, path_spec in self.specification['paths'].items(): path = u'{0}{1}'.format(self.base_path, path) self.paths[path] = {} # Add path-level parameters default_parameters = {} if 'parameters' in path_spec: self._add_parameters(default_parameters, path_spec['parameters']) for http_method in path_spec.keys(): if http_method not in self._HTTP_VERBS: continue self.paths[path][http_method] = {} # Add to operation list action = path_spec[http_method] tag = action['tags'][0] if 'tags' in action.keys() and action['tags'] else None if 'operationId' in action.keys(): self.operation[action['operationId']] = (path, http_method, tag) else: # Note: the encoding chosen below isn't very important in this # case; what matters is a byte string that is unique. # URL paths and http methods should encode to UTF-8 safely. h = hashlib.sha256() h.update(("{0}|{1}".format(http_method, path)).encode('utf-8')) self.generated_operation[h.hexdigest()] = (path, http_method, tag) # Get parameters self.paths[path][http_method]['parameters'] = default_parameters.copy() if 'parameters' in action.keys(): self._add_parameters(self.paths[path][http_method]['parameters'], action['parameters']) # Get responses self.paths[path][http_method]['responses'] = action['responses'] # Get mime types for this action if 'consumes' in action.keys(): self.paths[path][http_method]['consumes'] = action['consumes']
[ "def", "get_paths_data", "(", "self", ")", ":", "for", "path", ",", "path_spec", "in", "self", ".", "specification", "[", "'paths'", "]", ".", "items", "(", ")", ":", "path", "=", "u'{0}{1}'", ".", "format", "(", "self", ".", "base_path", ",", "path", ...
Get data for each paths in the swagger specification. Get also the list of operationId.
[ "Get", "data", "for", "each", "paths", "in", "the", "swagger", "specification", "." ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L571-L614
train
30,007
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser._add_parameters
def _add_parameters(self, parameter_map, parameter_list): """Populates the given parameter map with the list of parameters provided, resolving any reference objects encountered. Args: parameter_map: mapping from parameter names to parameter objects parameter_list: list of either parameter objects or reference objects """ for parameter in parameter_list: if parameter.get('$ref'): # expand parameter from $ref if not specified inline parameter = self.specification['parameters'].get(parameter.get('$ref').split('/')[-1]) parameter_map[parameter['name']] = parameter
python
def _add_parameters(self, parameter_map, parameter_list): """Populates the given parameter map with the list of parameters provided, resolving any reference objects encountered. Args: parameter_map: mapping from parameter names to parameter objects parameter_list: list of either parameter objects or reference objects """ for parameter in parameter_list: if parameter.get('$ref'): # expand parameter from $ref if not specified inline parameter = self.specification['parameters'].get(parameter.get('$ref').split('/')[-1]) parameter_map[parameter['name']] = parameter
[ "def", "_add_parameters", "(", "self", ",", "parameter_map", ",", "parameter_list", ")", ":", "for", "parameter", "in", "parameter_list", ":", "if", "parameter", ".", "get", "(", "'$ref'", ")", ":", "# expand parameter from $ref if not specified inline", "parameter", ...
Populates the given parameter map with the list of parameters provided, resolving any reference objects encountered. Args: parameter_map: mapping from parameter names to parameter objects parameter_list: list of either parameter objects or reference objects
[ "Populates", "the", "given", "parameter", "map", "with", "the", "list", "of", "parameters", "provided", "resolving", "any", "reference", "objects", "encountered", "." ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L616-L627
train
30,008
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser.get_path_spec
def get_path_spec(self, path, action=None): """Get the specification matching with the given path. Args: path: path we want the specification. action: get the specification for the given action. Returns: A tuple with the base name of the path and the specification. Or (None, None) if no specification is found. """ # Get the specification of the given path path_spec = None path_name = None for base_path in self.paths.keys(): if path == base_path: path_spec = self.paths[base_path] path_name = base_path # Path parameter if path_spec is None: for base_path in self.paths.keys(): regex_from_path = re.compile(re.sub('{[^/]*}', '([^/]*)', base_path) + r'$') if re.match(regex_from_path, path): path_spec = self.paths[base_path] path_name = base_path # Test action if given if path_spec is not None and action is not None: if action not in path_spec.keys(): return (None, None) else: path_spec = path_spec[action] return (path_name, path_spec)
python
def get_path_spec(self, path, action=None): """Get the specification matching with the given path. Args: path: path we want the specification. action: get the specification for the given action. Returns: A tuple with the base name of the path and the specification. Or (None, None) if no specification is found. """ # Get the specification of the given path path_spec = None path_name = None for base_path in self.paths.keys(): if path == base_path: path_spec = self.paths[base_path] path_name = base_path # Path parameter if path_spec is None: for base_path in self.paths.keys(): regex_from_path = re.compile(re.sub('{[^/]*}', '([^/]*)', base_path) + r'$') if re.match(regex_from_path, path): path_spec = self.paths[base_path] path_name = base_path # Test action if given if path_spec is not None and action is not None: if action not in path_spec.keys(): return (None, None) else: path_spec = path_spec[action] return (path_name, path_spec)
[ "def", "get_path_spec", "(", "self", ",", "path", ",", "action", "=", "None", ")", ":", "# Get the specification of the given path", "path_spec", "=", "None", "path_name", "=", "None", "for", "base_path", "in", "self", ".", "paths", ".", "keys", "(", ")", ":...
Get the specification matching with the given path. Args: path: path we want the specification. action: get the specification for the given action. Returns: A tuple with the base name of the path and the specification. Or (None, None) if no specification is found.
[ "Get", "the", "specification", "matching", "with", "the", "given", "path", "." ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L643-L677
train
30,009
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser.validate_request
def validate_request(self, path, action, body=None, query=None): """Check if the given request is valid. Validates the body and the query # Rules to validate the BODY: # Let's limit this to mime types that either contain 'text' or 'json' # 1. if body is None, there must not be any required parameters in # the given schema # 2. if the mime type contains 'json', body must not be '', but can # be {} # 3. if the mime type contains 'text', body can be any string # 4. if no mime type ('consumes') is given.. DISALLOW # 5. if the body is empty ('' or {}), there must not be any required parameters # 6. if there is something in the body, it must adhere to the given schema # -> will call the validate body function Args: path: path of the request. action: action of the request(get, post, delete...). body: body of the request. query: dict with the query parameters. Returns: True if the request is valid, False otherwise. TODO: - For every http method, we might want to have some general checks before we go deeper into the parameters - Check form data parameters """ path_name, path_spec = self.get_path_spec(path) if path_spec is None: # reject unknown path logging.warn("there is no path") return False if action not in path_spec.keys(): # reject unknown http method logging.warn("this http method is unknown '{0}'".format(action)) return False action_spec = path_spec[action] # check general post body guidelines (body + mime type) if action == 'post': is_ok, msg = _validate_post_body(body, action_spec) if not is_ok: logging.warn("the general post body did not validate due to '{0}'".format(msg)) return False # If the body is empty and it validated so far, we can return here # unless there is something in the query parameters we need to check body_is_empty = body in [None, {}, ''] if body_is_empty and query is None: return True # Check body parameters is_ok, msg = self._validate_body_parameters(body, action_spec) if not is_ok: logging.warn("the parameters in the body did not validate due to '{0}'".format(msg)) return False # Check query parameters if query is not None and not self._validate_query_parameters(query, action_spec): return False return True
python
def validate_request(self, path, action, body=None, query=None): """Check if the given request is valid. Validates the body and the query # Rules to validate the BODY: # Let's limit this to mime types that either contain 'text' or 'json' # 1. if body is None, there must not be any required parameters in # the given schema # 2. if the mime type contains 'json', body must not be '', but can # be {} # 3. if the mime type contains 'text', body can be any string # 4. if no mime type ('consumes') is given.. DISALLOW # 5. if the body is empty ('' or {}), there must not be any required parameters # 6. if there is something in the body, it must adhere to the given schema # -> will call the validate body function Args: path: path of the request. action: action of the request(get, post, delete...). body: body of the request. query: dict with the query parameters. Returns: True if the request is valid, False otherwise. TODO: - For every http method, we might want to have some general checks before we go deeper into the parameters - Check form data parameters """ path_name, path_spec = self.get_path_spec(path) if path_spec is None: # reject unknown path logging.warn("there is no path") return False if action not in path_spec.keys(): # reject unknown http method logging.warn("this http method is unknown '{0}'".format(action)) return False action_spec = path_spec[action] # check general post body guidelines (body + mime type) if action == 'post': is_ok, msg = _validate_post_body(body, action_spec) if not is_ok: logging.warn("the general post body did not validate due to '{0}'".format(msg)) return False # If the body is empty and it validated so far, we can return here # unless there is something in the query parameters we need to check body_is_empty = body in [None, {}, ''] if body_is_empty and query is None: return True # Check body parameters is_ok, msg = self._validate_body_parameters(body, action_spec) if not is_ok: logging.warn("the parameters in the body did not validate due to '{0}'".format(msg)) return False # Check query parameters if query is not None and not self._validate_query_parameters(query, action_spec): return False return True
[ "def", "validate_request", "(", "self", ",", "path", ",", "action", ",", "body", "=", "None", ",", "query", "=", "None", ")", ":", "path_name", ",", "path_spec", "=", "self", ".", "get_path_spec", "(", "path", ")", "if", "path_spec", "is", "None", ":",...
Check if the given request is valid. Validates the body and the query # Rules to validate the BODY: # Let's limit this to mime types that either contain 'text' or 'json' # 1. if body is None, there must not be any required parameters in # the given schema # 2. if the mime type contains 'json', body must not be '', but can # be {} # 3. if the mime type contains 'text', body can be any string # 4. if no mime type ('consumes') is given.. DISALLOW # 5. if the body is empty ('' or {}), there must not be any required parameters # 6. if there is something in the body, it must adhere to the given schema # -> will call the validate body function Args: path: path of the request. action: action of the request(get, post, delete...). body: body of the request. query: dict with the query parameters. Returns: True if the request is valid, False otherwise. TODO: - For every http method, we might want to have some general checks before we go deeper into the parameters - Check form data parameters
[ "Check", "if", "the", "given", "request", "is", "valid", ".", "Validates", "the", "body", "and", "the", "query" ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L679-L744
train
30,010
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser._validate_query_parameters
def _validate_query_parameters(self, query, action_spec): """Check the query parameter for the action specification. Args: query: query parameter to check. action_spec: specification of the action. Returns: True if the query is valid. """ processed_params = [] for param_name, param_value in query.items(): if param_name in action_spec['parameters'].keys(): processed_params.append(param_name) # Check array if action_spec['parameters'][param_name]['type'] == 'array': if not isinstance(param_value, list): # Not an array return False else: for i in param_value: # Check type of all elements in array if not self.check_type(i, action_spec['parameters'][param_name]['items']['type']): return False elif not self.check_type(param_value, action_spec['parameters'][param_name]['type']): return False # Check required if not all(param in processed_params for param, spec in action_spec['parameters'].items() if spec['in'] == 'query' and 'required' in spec and spec['required']): return False return True
python
def _validate_query_parameters(self, query, action_spec): """Check the query parameter for the action specification. Args: query: query parameter to check. action_spec: specification of the action. Returns: True if the query is valid. """ processed_params = [] for param_name, param_value in query.items(): if param_name in action_spec['parameters'].keys(): processed_params.append(param_name) # Check array if action_spec['parameters'][param_name]['type'] == 'array': if not isinstance(param_value, list): # Not an array return False else: for i in param_value: # Check type of all elements in array if not self.check_type(i, action_spec['parameters'][param_name]['items']['type']): return False elif not self.check_type(param_value, action_spec['parameters'][param_name]['type']): return False # Check required if not all(param in processed_params for param, spec in action_spec['parameters'].items() if spec['in'] == 'query' and 'required' in spec and spec['required']): return False return True
[ "def", "_validate_query_parameters", "(", "self", ",", "query", ",", "action_spec", ")", ":", "processed_params", "=", "[", "]", "for", "param_name", ",", "param_value", "in", "query", ".", "items", "(", ")", ":", "if", "param_name", "in", "action_spec", "["...
Check the query parameter for the action specification. Args: query: query parameter to check. action_spec: specification of the action. Returns: True if the query is valid.
[ "Check", "the", "query", "parameter", "for", "the", "action", "specification", "." ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L746-L777
train
30,011
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser._validate_body_parameters
def _validate_body_parameters(self, body, action_spec): """Check the body parameter for the action specification. Args: body: body parameter to check. action_spec: specification of the action. Returns: True if the body is valid. A string containing an error msg in case the body did not validate, otherwise the string is empty """ processed_params = [] for param_name, param_spec in action_spec['parameters'].items(): if param_spec['in'] == 'body': processed_params.append(param_name) # Check type if 'type' in param_spec.keys() and not self.check_type(body, param_spec['type']): msg = "Check type did not validate for {0} and {1}".format(param_spec['type'], body) return False, msg # Check schema elif 'schema' in param_spec.keys(): if 'type' in param_spec['schema'].keys() and param_spec['schema']['type'] == 'array': # It is an array get value from definition definition_name = self.get_definition_name_from_ref(param_spec['schema']['items']['$ref']) if len(body) > 0 and not self.validate_definition(definition_name, body[0]): msg = "The body did not validate against its definition" return False, msg elif ('type' in param_spec['schema'].keys() and not self.check_type(body, param_spec['schema']['type'])): # Type but not array msg = "Check type did not validate for {0} and {1}".format(param_spec['schema']['type'], body) return False, msg else: definition_name = self.get_definition_name_from_ref(param_spec['schema']['$ref']) if not self.validate_definition(definition_name, body): msg = "The body did not validate against its definition" return False, msg # Check required if not all(param in processed_params for param, spec in action_spec['parameters'].items() if spec['in'] == 'body' and 'required' in spec and spec['required']): msg = "Not all required parameters were present" return False, msg return True, ""
python
def _validate_body_parameters(self, body, action_spec): """Check the body parameter for the action specification. Args: body: body parameter to check. action_spec: specification of the action. Returns: True if the body is valid. A string containing an error msg in case the body did not validate, otherwise the string is empty """ processed_params = [] for param_name, param_spec in action_spec['parameters'].items(): if param_spec['in'] == 'body': processed_params.append(param_name) # Check type if 'type' in param_spec.keys() and not self.check_type(body, param_spec['type']): msg = "Check type did not validate for {0} and {1}".format(param_spec['type'], body) return False, msg # Check schema elif 'schema' in param_spec.keys(): if 'type' in param_spec['schema'].keys() and param_spec['schema']['type'] == 'array': # It is an array get value from definition definition_name = self.get_definition_name_from_ref(param_spec['schema']['items']['$ref']) if len(body) > 0 and not self.validate_definition(definition_name, body[0]): msg = "The body did not validate against its definition" return False, msg elif ('type' in param_spec['schema'].keys() and not self.check_type(body, param_spec['schema']['type'])): # Type but not array msg = "Check type did not validate for {0} and {1}".format(param_spec['schema']['type'], body) return False, msg else: definition_name = self.get_definition_name_from_ref(param_spec['schema']['$ref']) if not self.validate_definition(definition_name, body): msg = "The body did not validate against its definition" return False, msg # Check required if not all(param in processed_params for param, spec in action_spec['parameters'].items() if spec['in'] == 'body' and 'required' in spec and spec['required']): msg = "Not all required parameters were present" return False, msg return True, ""
[ "def", "_validate_body_parameters", "(", "self", ",", "body", ",", "action_spec", ")", ":", "processed_params", "=", "[", "]", "for", "param_name", ",", "param_spec", "in", "action_spec", "[", "'parameters'", "]", ".", "items", "(", ")", ":", "if", "param_sp...
Check the body parameter for the action specification. Args: body: body parameter to check. action_spec: specification of the action. Returns: True if the body is valid. A string containing an error msg in case the body did not validate, otherwise the string is empty
[ "Check", "the", "body", "parameter", "for", "the", "action", "specification", "." ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L779-L824
train
30,012
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser.get_response_example
def get_response_example(self, resp_spec): """Get a response example from a response spec. """ if 'schema' in resp_spec.keys(): if '$ref' in resp_spec['schema']: # Standard definition definition_name = self.get_definition_name_from_ref(resp_spec['schema']['$ref']) return self.definitions_example[definition_name] elif 'items' in resp_spec['schema'] and resp_spec['schema']['type'] == 'array': # Array if '$ref' in resp_spec['schema']['items']: definition_name = self.get_definition_name_from_ref(resp_spec['schema']['items']['$ref']) else: if 'type' in resp_spec['schema']['items']: definition_name = self.get_definition_name_from_ref(resp_spec['schema']['items']) return [definition_name] else: logging.warn("No item type in: " + resp_spec['schema']) return '' return [self.definitions_example[definition_name]] elif 'type' in resp_spec['schema']: return self.get_example_from_prop_spec(resp_spec['schema']) else: return ''
python
def get_response_example(self, resp_spec): """Get a response example from a response spec. """ if 'schema' in resp_spec.keys(): if '$ref' in resp_spec['schema']: # Standard definition definition_name = self.get_definition_name_from_ref(resp_spec['schema']['$ref']) return self.definitions_example[definition_name] elif 'items' in resp_spec['schema'] and resp_spec['schema']['type'] == 'array': # Array if '$ref' in resp_spec['schema']['items']: definition_name = self.get_definition_name_from_ref(resp_spec['schema']['items']['$ref']) else: if 'type' in resp_spec['schema']['items']: definition_name = self.get_definition_name_from_ref(resp_spec['schema']['items']) return [definition_name] else: logging.warn("No item type in: " + resp_spec['schema']) return '' return [self.definitions_example[definition_name]] elif 'type' in resp_spec['schema']: return self.get_example_from_prop_spec(resp_spec['schema']) else: return ''
[ "def", "get_response_example", "(", "self", ",", "resp_spec", ")", ":", "if", "'schema'", "in", "resp_spec", ".", "keys", "(", ")", ":", "if", "'$ref'", "in", "resp_spec", "[", "'schema'", "]", ":", "# Standard definition", "definition_name", "=", "self", "....
Get a response example from a response spec.
[ "Get", "a", "response", "example", "from", "a", "response", "spec", "." ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L826-L848
train
30,013
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser.get_request_data
def get_request_data(self, path, action, body=None): """Get the default data and status code of the given path + action request. Args: path: path of the request. action: action of the request(get, post, delete...) body: body sent, used to sent it back for post request. Returns: A tuple with the default response data and status code In case of default status_code, use 0 """ body = body or '' path_name, path_spec = self.get_path_spec(path) response = {} # Get all status code if path_spec is not None and action in path_spec.keys(): for status_code in path_spec[action]['responses'].keys(): resp = path_spec[action]['responses'][status_code] try: response[int(status_code)] = self.get_response_example(resp) except ValueError: response[status_code] = self.get_response_example(resp) # If there is no status_code add a default 400 if response == {}: response[400] = '' return response
python
def get_request_data(self, path, action, body=None): """Get the default data and status code of the given path + action request. Args: path: path of the request. action: action of the request(get, post, delete...) body: body sent, used to sent it back for post request. Returns: A tuple with the default response data and status code In case of default status_code, use 0 """ body = body or '' path_name, path_spec = self.get_path_spec(path) response = {} # Get all status code if path_spec is not None and action in path_spec.keys(): for status_code in path_spec[action]['responses'].keys(): resp = path_spec[action]['responses'][status_code] try: response[int(status_code)] = self.get_response_example(resp) except ValueError: response[status_code] = self.get_response_example(resp) # If there is no status_code add a default 400 if response == {}: response[400] = '' return response
[ "def", "get_request_data", "(", "self", ",", "path", ",", "action", ",", "body", "=", "None", ")", ":", "body", "=", "body", "or", "''", "path_name", ",", "path_spec", "=", "self", ".", "get_path_spec", "(", "path", ")", "response", "=", "{", "}", "#...
Get the default data and status code of the given path + action request. Args: path: path of the request. action: action of the request(get, post, delete...) body: body sent, used to sent it back for post request. Returns: A tuple with the default response data and status code In case of default status_code, use 0
[ "Get", "the", "default", "data", "and", "status", "code", "of", "the", "given", "path", "+", "action", "request", "." ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L850-L878
train
30,014
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser.get_send_request_correct_body
def get_send_request_correct_body(self, path, action): """Get an example body which is correct to send to the given path with the given action. Args: path: path of the request action: action of the request (get, post, put, delete) Returns: A dict representing a correct body for the request or None if no body is required. """ path_name, path_spec = self.get_path_spec(path) if path_spec is not None and action in path_spec.keys(): for name, spec in path_spec[action]['parameters'].items(): if spec['in'] == 'body': # Get body parameter if 'type' in spec.keys(): # Get value from type return self.get_example_from_prop_spec(spec) elif 'schema' in spec.keys(): if 'type' in spec['schema'].keys() and spec['schema']['type'] == 'array': # It is an array # Get value from definition if '$ref' in spec['schema']['items']: definition_name = self.get_definition_name_from_ref(spec['schema'] ['items']['$ref']) return [self.definitions_example[definition_name]] else: definition_name = self.get_definition_name_from_ref(spec['schema'] ['items']['type']) return [definition_name] elif 'type' in spec['schema'].keys(): # Type but not array return self.get_example_from_prop_spec(spec['schema']) else: # Get value from definition definition_name = self.get_definition_name_from_ref(spec['schema']['$ref']) return self.definitions_example[definition_name]
python
def get_send_request_correct_body(self, path, action): """Get an example body which is correct to send to the given path with the given action. Args: path: path of the request action: action of the request (get, post, put, delete) Returns: A dict representing a correct body for the request or None if no body is required. """ path_name, path_spec = self.get_path_spec(path) if path_spec is not None and action in path_spec.keys(): for name, spec in path_spec[action]['parameters'].items(): if spec['in'] == 'body': # Get body parameter if 'type' in spec.keys(): # Get value from type return self.get_example_from_prop_spec(spec) elif 'schema' in spec.keys(): if 'type' in spec['schema'].keys() and spec['schema']['type'] == 'array': # It is an array # Get value from definition if '$ref' in spec['schema']['items']: definition_name = self.get_definition_name_from_ref(spec['schema'] ['items']['$ref']) return [self.definitions_example[definition_name]] else: definition_name = self.get_definition_name_from_ref(spec['schema'] ['items']['type']) return [definition_name] elif 'type' in spec['schema'].keys(): # Type but not array return self.get_example_from_prop_spec(spec['schema']) else: # Get value from definition definition_name = self.get_definition_name_from_ref(spec['schema']['$ref']) return self.definitions_example[definition_name]
[ "def", "get_send_request_correct_body", "(", "self", ",", "path", ",", "action", ")", ":", "path_name", ",", "path_spec", "=", "self", ".", "get_path_spec", "(", "path", ")", "if", "path_spec", "is", "not", "None", "and", "action", "in", "path_spec", ".", ...
Get an example body which is correct to send to the given path with the given action. Args: path: path of the request action: action of the request (get, post, put, delete) Returns: A dict representing a correct body for the request or None if no body is required.
[ "Get", "an", "example", "body", "which", "is", "correct", "to", "send", "to", "the", "given", "path", "with", "the", "given", "action", "." ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L880-L917
train
30,015
ubernostrum/webcolors
webcolors.py
normalize_hex
def normalize_hex(hex_value): """ Normalize a hexadecimal color value to 6 digits, lowercase. """ match = HEX_COLOR_RE.match(hex_value) if match is None: raise ValueError( u"'{}' is not a valid hexadecimal color value.".format(hex_value) ) hex_digits = match.group(1) if len(hex_digits) == 3: hex_digits = u''.join(2 * s for s in hex_digits) return u'#{}'.format(hex_digits.lower())
python
def normalize_hex(hex_value): """ Normalize a hexadecimal color value to 6 digits, lowercase. """ match = HEX_COLOR_RE.match(hex_value) if match is None: raise ValueError( u"'{}' is not a valid hexadecimal color value.".format(hex_value) ) hex_digits = match.group(1) if len(hex_digits) == 3: hex_digits = u''.join(2 * s for s in hex_digits) return u'#{}'.format(hex_digits.lower())
[ "def", "normalize_hex", "(", "hex_value", ")", ":", "match", "=", "HEX_COLOR_RE", ".", "match", "(", "hex_value", ")", "if", "match", "is", "None", ":", "raise", "ValueError", "(", "u\"'{}' is not a valid hexadecimal color value.\"", ".", "format", "(", "hex_value...
Normalize a hexadecimal color value to 6 digits, lowercase.
[ "Normalize", "a", "hexadecimal", "color", "value", "to", "6", "digits", "lowercase", "." ]
558bd81a917647ea2b392f5f4e9cd7ae5ff162a5
https://github.com/ubernostrum/webcolors/blob/558bd81a917647ea2b392f5f4e9cd7ae5ff162a5/webcolors.py#L329-L342
train
30,016
ubernostrum/webcolors
webcolors.py
html5_parse_simple_color
def html5_parse_simple_color(input): """ Apply the simple color parsing algorithm from section 2.4.6 of HTML5. """ # 1. Let input be the string being parsed. # # 2. If input is not exactly seven characters long, then return an # error. if not isinstance(input, unicode) or len(input) != 7: raise ValueError( u"An HTML5 simple color must be a Unicode string " u"exactly seven characters long." ) # 3. If the first character in input is not a U+0023 NUMBER SIGN # character (#), then return an error. if not input.startswith('#'): raise ValueError( u"An HTML5 simple color must begin with the " u"character '#' (U+0023)." ) # 4. If the last six characters of input are not all ASCII hex # digits, then return an error. if not all(c in string.hexdigits for c in input[1:]): raise ValueError( u"An HTML5 simple color must contain exactly six ASCII hex digits." ) # 5. Let result be a simple color. # # 6. Interpret the second and third characters as a hexadecimal # number and let the result be the red component of result. # # 7. Interpret the fourth and fifth characters as a hexadecimal # number and let the result be the green component of result. # # 8. Interpret the sixth and seventh characters as a hexadecimal # number and let the result be the blue component of result. # # 9. Return result. return HTML5SimpleColor( int(input[1:3], 16), int(input[3:5], 16), int(input[5:7], 16) )
python
def html5_parse_simple_color(input): """ Apply the simple color parsing algorithm from section 2.4.6 of HTML5. """ # 1. Let input be the string being parsed. # # 2. If input is not exactly seven characters long, then return an # error. if not isinstance(input, unicode) or len(input) != 7: raise ValueError( u"An HTML5 simple color must be a Unicode string " u"exactly seven characters long." ) # 3. If the first character in input is not a U+0023 NUMBER SIGN # character (#), then return an error. if not input.startswith('#'): raise ValueError( u"An HTML5 simple color must begin with the " u"character '#' (U+0023)." ) # 4. If the last six characters of input are not all ASCII hex # digits, then return an error. if not all(c in string.hexdigits for c in input[1:]): raise ValueError( u"An HTML5 simple color must contain exactly six ASCII hex digits." ) # 5. Let result be a simple color. # # 6. Interpret the second and third characters as a hexadecimal # number and let the result be the red component of result. # # 7. Interpret the fourth and fifth characters as a hexadecimal # number and let the result be the green component of result. # # 8. Interpret the sixth and seventh characters as a hexadecimal # number and let the result be the blue component of result. # # 9. Return result. return HTML5SimpleColor( int(input[1:3], 16), int(input[3:5], 16), int(input[5:7], 16) )
[ "def", "html5_parse_simple_color", "(", "input", ")", ":", "# 1. Let input be the string being parsed.", "#", "# 2. If input is not exactly seven characters long, then return an", "# error.", "if", "not", "isinstance", "(", "input", ",", "unicode", ")", "or", "len", "(", ...
Apply the simple color parsing algorithm from section 2.4.6 of HTML5.
[ "Apply", "the", "simple", "color", "parsing", "algorithm", "from", "section", "2", ".", "4", ".", "6", "of", "HTML5", "." ]
558bd81a917647ea2b392f5f4e9cd7ae5ff162a5
https://github.com/ubernostrum/webcolors/blob/558bd81a917647ea2b392f5f4e9cd7ae5ff162a5/webcolors.py#L651-L698
train
30,017
ubernostrum/webcolors
webcolors.py
html5_serialize_simple_color
def html5_serialize_simple_color(simple_color): """ Apply the serialization algorithm for a simple color from section 2.4.6 of HTML5. """ red, green, blue = simple_color # 1. Let result be a string consisting of a single "#" (U+0023) # character. result = u'#' # 2. Convert the red, green, and blue components in turn to # two-digit hexadecimal numbers using lowercase ASCII hex # digits, zero-padding if necessary, and append these numbers # to result, in the order red, green, blue. format_string = '{:02x}' result += format_string.format(red) result += format_string.format(green) result += format_string.format(blue) # 3. Return result, which will be a valid lowercase simple color. return result
python
def html5_serialize_simple_color(simple_color): """ Apply the serialization algorithm for a simple color from section 2.4.6 of HTML5. """ red, green, blue = simple_color # 1. Let result be a string consisting of a single "#" (U+0023) # character. result = u'#' # 2. Convert the red, green, and blue components in turn to # two-digit hexadecimal numbers using lowercase ASCII hex # digits, zero-padding if necessary, and append these numbers # to result, in the order red, green, blue. format_string = '{:02x}' result += format_string.format(red) result += format_string.format(green) result += format_string.format(blue) # 3. Return result, which will be a valid lowercase simple color. return result
[ "def", "html5_serialize_simple_color", "(", "simple_color", ")", ":", "red", ",", "green", ",", "blue", "=", "simple_color", "# 1. Let result be a string consisting of a single \"#\" (U+0023)", "# character.", "result", "=", "u'#'", "# 2. Convert the red, green, and blue compo...
Apply the serialization algorithm for a simple color from section 2.4.6 of HTML5.
[ "Apply", "the", "serialization", "algorithm", "for", "a", "simple", "color", "from", "section", "2", ".", "4", ".", "6", "of", "HTML5", "." ]
558bd81a917647ea2b392f5f4e9cd7ae5ff162a5
https://github.com/ubernostrum/webcolors/blob/558bd81a917647ea2b392f5f4e9cd7ae5ff162a5/webcolors.py#L701-L723
train
30,018
ubernostrum/webcolors
webcolors.py
html5_parse_legacy_color
def html5_parse_legacy_color(input): """ Apply the legacy color parsing algorithm from section 2.4.6 of HTML5. """ # 1. Let input be the string being parsed. if not isinstance(input, unicode): raise ValueError( u"HTML5 legacy color parsing requires a Unicode string as input." ) # 2. If input is the empty string, then return an error. if input == "": raise ValueError( u"HTML5 legacy color parsing forbids empty string as a value." ) # 3. Strip leading and trailing whitespace from input. input = input.strip() # 4. If input is an ASCII case-insensitive match for the string # "transparent", then return an error. if input.lower() == u"transparent": raise ValueError( u'HTML5 legacy color parsing forbids "transparent" as a value.' ) # 5. If input is an ASCII case-insensitive match for one of the # keywords listed in the SVG color keywords section of the CSS3 # Color specification, then return the simple color # corresponding to that keyword. keyword_hex = CSS3_NAMES_TO_HEX.get(input.lower()) if keyword_hex is not None: return html5_parse_simple_color(keyword_hex) # 6. If input is four characters long, and the first character in # input is a "#" (U+0023) character, and the last three # characters of input are all ASCII hex digits, then run these # substeps: if len(input) == 4 and \ input.startswith(u'#') and \ all(c in string.hexdigits for c in input[1:]): # 1. Let result be a simple color. # # 2. Interpret the second character of input as a hexadecimal # digit; let the red component of result be the resulting # number multiplied by 17. # # 3. Interpret the third character of input as a hexadecimal # digit; let the green component of result be the resulting # number multiplied by 17. # # 4. Interpret the fourth character of input as a hexadecimal # digit; let the blue component of result be the resulting # number multiplied by 17. result = HTML5SimpleColor( int(input[1], 16) * 17, int(input[2], 16) * 17, int(input[3], 16) * 17 ) # 5. Return result. return result # 7. Replace any characters in input that have a Unicode code # point greater than U+FFFF (i.e. any characters that are not # in the basic multilingual plane) with the two-character # string "00". # This one's a bit weird due to the existence of multiple internal # Unicode string representations in different versions and builds # of Python. # # From Python 2.2 through 3.2, Python could be compiled with # "narrow" or "wide" Unicode strings (see PEP 261). Narrow builds # handled Unicode strings with two-byte characters and surrogate # pairs for non-BMP code points. Wide builds handled Unicode # strings with four-byte characters and no surrogates. This means # ord() is only sufficient to identify a non-BMP character on a # wide build. # # Starting with Python 3.3, the internal string representation # (see PEP 393) is now dynamic, and Python chooses an encoding -- # either latin-1, UCS-2 or UCS-4 -- wide enough to handle the # highest code point in the string. # # The code below bypasses all of that for a consistently effective # method: encode the string to little-endian UTF-32, then perform # a binary unpack of it as four-byte integers. Those integers will # be the Unicode code points, and from there filtering out non-BMP # code points is easy. encoded_input = input.encode('utf_32_le') # Format string is '<' (for little-endian byte order), then a # sequence of 'L' characters (for 4-byte unsigned long integer) # equal to the length of the original string, which is also # one-fourth the encoded length. For example, for a six-character # input the generated format string will be '<LLLLLL'. format_string = '<' + ('L' * (int(len(encoded_input) / 4))) codepoints = struct.unpack(format_string, encoded_input) input = ''.join(u'00' if c > 0xffff else unichr(c) for c in codepoints) # 8. If input is longer than 128 characters, truncate input, # leaving only the first 128 characters. if len(input) > 128: input = input[:128] # 9. If the first character in input is a "#" (U+0023) character, # remove it. if input.startswith(u'#'): input = input[1:] # 10. Replace any character in input that is not an ASCII hex # digit with the character "0" (U+0030). if any(c for c in input if c not in string.hexdigits): input = ''.join(c if c in string.hexdigits else u'0' for c in input) # 11. While input's length is zero or not a multiple of three, # append a "0" (U+0030) character to input. while (len(input) == 0) or (len(input) % 3 != 0): input += u'0' # 12. Split input into three strings of equal length, to obtain # three components. Let length be the length of those # components (one third the length of input). length = int(len(input) / 3) red = input[:length] green = input[length:length*2] blue = input[length*2:] # 13. If length is greater than 8, then remove the leading # length-8 characters in each component, and let length be 8. if length > 8: red, green, blue = (red[length-8:], green[length-8:], blue[length-8:]) length = 8 # 14. While length is greater than two and the first character in # each component is a "0" (U+0030) character, remove that # character and reduce length by one. while (length > 2) and (red[0] == u'0' and green[0] == u'0' and blue[0] == u'0'): red, green, blue = (red[1:], green[1:], blue[1:]) length -= 1 # 15. If length is still greater than two, truncate each # component, leaving only the first two characters in each. if length > 2: red, green, blue = (red[:2], green[:2], blue[:2]) # 16. Let result be a simple color. # # 17. Interpret the first component as a hexadecimal number; let # the red component of result be the resulting number. # # 18. Interpret the second component as a hexadecimal number; let # the green component of result be the resulting number. # # 19. Interpret the third component as a hexadecimal number; let # the blue component of result be the resulting number. # # 20. Return result. return HTML5SimpleColor( int(red, 16), int(green, 16), int(blue, 16) )
python
def html5_parse_legacy_color(input): """ Apply the legacy color parsing algorithm from section 2.4.6 of HTML5. """ # 1. Let input be the string being parsed. if not isinstance(input, unicode): raise ValueError( u"HTML5 legacy color parsing requires a Unicode string as input." ) # 2. If input is the empty string, then return an error. if input == "": raise ValueError( u"HTML5 legacy color parsing forbids empty string as a value." ) # 3. Strip leading and trailing whitespace from input. input = input.strip() # 4. If input is an ASCII case-insensitive match for the string # "transparent", then return an error. if input.lower() == u"transparent": raise ValueError( u'HTML5 legacy color parsing forbids "transparent" as a value.' ) # 5. If input is an ASCII case-insensitive match for one of the # keywords listed in the SVG color keywords section of the CSS3 # Color specification, then return the simple color # corresponding to that keyword. keyword_hex = CSS3_NAMES_TO_HEX.get(input.lower()) if keyword_hex is not None: return html5_parse_simple_color(keyword_hex) # 6. If input is four characters long, and the first character in # input is a "#" (U+0023) character, and the last three # characters of input are all ASCII hex digits, then run these # substeps: if len(input) == 4 and \ input.startswith(u'#') and \ all(c in string.hexdigits for c in input[1:]): # 1. Let result be a simple color. # # 2. Interpret the second character of input as a hexadecimal # digit; let the red component of result be the resulting # number multiplied by 17. # # 3. Interpret the third character of input as a hexadecimal # digit; let the green component of result be the resulting # number multiplied by 17. # # 4. Interpret the fourth character of input as a hexadecimal # digit; let the blue component of result be the resulting # number multiplied by 17. result = HTML5SimpleColor( int(input[1], 16) * 17, int(input[2], 16) * 17, int(input[3], 16) * 17 ) # 5. Return result. return result # 7. Replace any characters in input that have a Unicode code # point greater than U+FFFF (i.e. any characters that are not # in the basic multilingual plane) with the two-character # string "00". # This one's a bit weird due to the existence of multiple internal # Unicode string representations in different versions and builds # of Python. # # From Python 2.2 through 3.2, Python could be compiled with # "narrow" or "wide" Unicode strings (see PEP 261). Narrow builds # handled Unicode strings with two-byte characters and surrogate # pairs for non-BMP code points. Wide builds handled Unicode # strings with four-byte characters and no surrogates. This means # ord() is only sufficient to identify a non-BMP character on a # wide build. # # Starting with Python 3.3, the internal string representation # (see PEP 393) is now dynamic, and Python chooses an encoding -- # either latin-1, UCS-2 or UCS-4 -- wide enough to handle the # highest code point in the string. # # The code below bypasses all of that for a consistently effective # method: encode the string to little-endian UTF-32, then perform # a binary unpack of it as four-byte integers. Those integers will # be the Unicode code points, and from there filtering out non-BMP # code points is easy. encoded_input = input.encode('utf_32_le') # Format string is '<' (for little-endian byte order), then a # sequence of 'L' characters (for 4-byte unsigned long integer) # equal to the length of the original string, which is also # one-fourth the encoded length. For example, for a six-character # input the generated format string will be '<LLLLLL'. format_string = '<' + ('L' * (int(len(encoded_input) / 4))) codepoints = struct.unpack(format_string, encoded_input) input = ''.join(u'00' if c > 0xffff else unichr(c) for c in codepoints) # 8. If input is longer than 128 characters, truncate input, # leaving only the first 128 characters. if len(input) > 128: input = input[:128] # 9. If the first character in input is a "#" (U+0023) character, # remove it. if input.startswith(u'#'): input = input[1:] # 10. Replace any character in input that is not an ASCII hex # digit with the character "0" (U+0030). if any(c for c in input if c not in string.hexdigits): input = ''.join(c if c in string.hexdigits else u'0' for c in input) # 11. While input's length is zero or not a multiple of three, # append a "0" (U+0030) character to input. while (len(input) == 0) or (len(input) % 3 != 0): input += u'0' # 12. Split input into three strings of equal length, to obtain # three components. Let length be the length of those # components (one third the length of input). length = int(len(input) / 3) red = input[:length] green = input[length:length*2] blue = input[length*2:] # 13. If length is greater than 8, then remove the leading # length-8 characters in each component, and let length be 8. if length > 8: red, green, blue = (red[length-8:], green[length-8:], blue[length-8:]) length = 8 # 14. While length is greater than two and the first character in # each component is a "0" (U+0030) character, remove that # character and reduce length by one. while (length > 2) and (red[0] == u'0' and green[0] == u'0' and blue[0] == u'0'): red, green, blue = (red[1:], green[1:], blue[1:]) length -= 1 # 15. If length is still greater than two, truncate each # component, leaving only the first two characters in each. if length > 2: red, green, blue = (red[:2], green[:2], blue[:2]) # 16. Let result be a simple color. # # 17. Interpret the first component as a hexadecimal number; let # the red component of result be the resulting number. # # 18. Interpret the second component as a hexadecimal number; let # the green component of result be the resulting number. # # 19. Interpret the third component as a hexadecimal number; let # the blue component of result be the resulting number. # # 20. Return result. return HTML5SimpleColor( int(red, 16), int(green, 16), int(blue, 16) )
[ "def", "html5_parse_legacy_color", "(", "input", ")", ":", "# 1. Let input be the string being parsed.", "if", "not", "isinstance", "(", "input", ",", "unicode", ")", ":", "raise", "ValueError", "(", "u\"HTML5 legacy color parsing requires a Unicode string as input.\"", ")", ...
Apply the legacy color parsing algorithm from section 2.4.6 of HTML5.
[ "Apply", "the", "legacy", "color", "parsing", "algorithm", "from", "section", "2", ".", "4", ".", "6", "of", "HTML5", "." ]
558bd81a917647ea2b392f5f4e9cd7ae5ff162a5
https://github.com/ubernostrum/webcolors/blob/558bd81a917647ea2b392f5f4e9cd7ae5ff162a5/webcolors.py#L726-L901
train
30,019
inveniosoftware/invenio-records
invenio_records/api.py
Record.create
def create(cls, data, id_=None, **kwargs): r"""Create a new record instance and store it in the database. #. Send a signal :data:`invenio_records.signals.before_record_insert` with the new record as parameter. #. Validate the new record data. #. Add the new record in the database. #. Send a signal :data:`invenio_records.signals.after_record_insert` with the new created record as parameter. :Keyword Arguments: * **format_checker** -- An instance of the class :class:`jsonschema.FormatChecker`, which contains validation rules for formats. See :func:`~invenio_records.api.RecordBase.validate` for more details. * **validator** -- A :class:`jsonschema.IValidator` class that will be used to validate the record. See :func:`~invenio_records.api.RecordBase.validate` for more details. :param data: Dict with the record metadata. :param id_: Specify a UUID to use for the new record, instead of automatically generated. :returns: A new :class:`Record` instance. """ from .models import RecordMetadata with db.session.begin_nested(): record = cls(data) before_record_insert.send( current_app._get_current_object(), record=record ) record.validate(**kwargs) record.model = RecordMetadata(id=id_, json=record) db.session.add(record.model) after_record_insert.send( current_app._get_current_object(), record=record ) return record
python
def create(cls, data, id_=None, **kwargs): r"""Create a new record instance and store it in the database. #. Send a signal :data:`invenio_records.signals.before_record_insert` with the new record as parameter. #. Validate the new record data. #. Add the new record in the database. #. Send a signal :data:`invenio_records.signals.after_record_insert` with the new created record as parameter. :Keyword Arguments: * **format_checker** -- An instance of the class :class:`jsonschema.FormatChecker`, which contains validation rules for formats. See :func:`~invenio_records.api.RecordBase.validate` for more details. * **validator** -- A :class:`jsonschema.IValidator` class that will be used to validate the record. See :func:`~invenio_records.api.RecordBase.validate` for more details. :param data: Dict with the record metadata. :param id_: Specify a UUID to use for the new record, instead of automatically generated. :returns: A new :class:`Record` instance. """ from .models import RecordMetadata with db.session.begin_nested(): record = cls(data) before_record_insert.send( current_app._get_current_object(), record=record ) record.validate(**kwargs) record.model = RecordMetadata(id=id_, json=record) db.session.add(record.model) after_record_insert.send( current_app._get_current_object(), record=record ) return record
[ "def", "create", "(", "cls", ",", "data", ",", "id_", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", ".", "models", "import", "RecordMetadata", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "record", "=", "cls", "(", "d...
r"""Create a new record instance and store it in the database. #. Send a signal :data:`invenio_records.signals.before_record_insert` with the new record as parameter. #. Validate the new record data. #. Add the new record in the database. #. Send a signal :data:`invenio_records.signals.after_record_insert` with the new created record as parameter. :Keyword Arguments: * **format_checker** -- An instance of the class :class:`jsonschema.FormatChecker`, which contains validation rules for formats. See :func:`~invenio_records.api.RecordBase.validate` for more details. * **validator** -- A :class:`jsonschema.IValidator` class that will be used to validate the record. See :func:`~invenio_records.api.RecordBase.validate` for more details. :param data: Dict with the record metadata. :param id_: Specify a UUID to use for the new record, instead of automatically generated. :returns: A new :class:`Record` instance.
[ "r", "Create", "a", "new", "record", "instance", "and", "store", "it", "in", "the", "database", "." ]
b0b1481d04012e45cb71b5ae4019e91dde88d1e2
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/api.py#L141-L189
train
30,020
inveniosoftware/invenio-records
invenio_records/api.py
Record.get_record
def get_record(cls, id_, with_deleted=False): """Retrieve the record by id. Raise a database exception if the record does not exist. :param id_: record ID. :param with_deleted: If `True` then it includes deleted records. :returns: The :class:`Record` instance. """ with db.session.no_autoflush: query = RecordMetadata.query.filter_by(id=id_) if not with_deleted: query = query.filter(RecordMetadata.json != None) # noqa obj = query.one() return cls(obj.json, model=obj)
python
def get_record(cls, id_, with_deleted=False): """Retrieve the record by id. Raise a database exception if the record does not exist. :param id_: record ID. :param with_deleted: If `True` then it includes deleted records. :returns: The :class:`Record` instance. """ with db.session.no_autoflush: query = RecordMetadata.query.filter_by(id=id_) if not with_deleted: query = query.filter(RecordMetadata.json != None) # noqa obj = query.one() return cls(obj.json, model=obj)
[ "def", "get_record", "(", "cls", ",", "id_", ",", "with_deleted", "=", "False", ")", ":", "with", "db", ".", "session", ".", "no_autoflush", ":", "query", "=", "RecordMetadata", ".", "query", ".", "filter_by", "(", "id", "=", "id_", ")", "if", "not", ...
Retrieve the record by id. Raise a database exception if the record does not exist. :param id_: record ID. :param with_deleted: If `True` then it includes deleted records. :returns: The :class:`Record` instance.
[ "Retrieve", "the", "record", "by", "id", "." ]
b0b1481d04012e45cb71b5ae4019e91dde88d1e2
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/api.py#L192-L206
train
30,021
inveniosoftware/invenio-records
invenio_records/api.py
Record.get_records
def get_records(cls, ids, with_deleted=False): """Retrieve multiple records by id. :param ids: List of record IDs. :param with_deleted: If `True` then it includes deleted records. :returns: A list of :class:`Record` instances. """ with db.session.no_autoflush: query = RecordMetadata.query.filter(RecordMetadata.id.in_(ids)) if not with_deleted: query = query.filter(RecordMetadata.json != None) # noqa return [cls(obj.json, model=obj) for obj in query.all()]
python
def get_records(cls, ids, with_deleted=False): """Retrieve multiple records by id. :param ids: List of record IDs. :param with_deleted: If `True` then it includes deleted records. :returns: A list of :class:`Record` instances. """ with db.session.no_autoflush: query = RecordMetadata.query.filter(RecordMetadata.id.in_(ids)) if not with_deleted: query = query.filter(RecordMetadata.json != None) # noqa return [cls(obj.json, model=obj) for obj in query.all()]
[ "def", "get_records", "(", "cls", ",", "ids", ",", "with_deleted", "=", "False", ")", ":", "with", "db", ".", "session", ".", "no_autoflush", ":", "query", "=", "RecordMetadata", ".", "query", ".", "filter", "(", "RecordMetadata", ".", "id", ".", "in_", ...
Retrieve multiple records by id. :param ids: List of record IDs. :param with_deleted: If `True` then it includes deleted records. :returns: A list of :class:`Record` instances.
[ "Retrieve", "multiple", "records", "by", "id", "." ]
b0b1481d04012e45cb71b5ae4019e91dde88d1e2
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/api.py#L209-L221
train
30,022
inveniosoftware/invenio-records
invenio_records/api.py
Record.patch
def patch(self, patch): """Patch record metadata. :params patch: Dictionary of record metadata. :returns: A new :class:`Record` instance. """ data = apply_patch(dict(self), patch) return self.__class__(data, model=self.model)
python
def patch(self, patch): """Patch record metadata. :params patch: Dictionary of record metadata. :returns: A new :class:`Record` instance. """ data = apply_patch(dict(self), patch) return self.__class__(data, model=self.model)
[ "def", "patch", "(", "self", ",", "patch", ")", ":", "data", "=", "apply_patch", "(", "dict", "(", "self", ")", ",", "patch", ")", "return", "self", ".", "__class__", "(", "data", ",", "model", "=", "self", ".", "model", ")" ]
Patch record metadata. :params patch: Dictionary of record metadata. :returns: A new :class:`Record` instance.
[ "Patch", "record", "metadata", "." ]
b0b1481d04012e45cb71b5ae4019e91dde88d1e2
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/api.py#L223-L230
train
30,023
inveniosoftware/invenio-records
invenio_records/api.py
Record.commit
def commit(self, **kwargs): r"""Store changes of the current record instance in the database. #. Send a signal :data:`invenio_records.signals.before_record_update` with the current record to be committed as parameter. #. Validate the current record data. #. Commit the current record in the database. #. Send a signal :data:`invenio_records.signals.after_record_update` with the committed record as parameter. :Keyword Arguments: * **format_checker** -- An instance of the class :class:`jsonschema.FormatChecker`, which contains validation rules for formats. See :func:`~invenio_records.api.RecordBase.validate` for more details. * **validator** -- A :class:`jsonschema.IValidator` class that will be used to validate the record. See :func:`~invenio_records.api.RecordBase.validate` for more details. :returns: The :class:`Record` instance. """ if self.model is None or self.model.json is None: raise MissingModelError() with db.session.begin_nested(): before_record_update.send( current_app._get_current_object(), record=self ) self.validate(**kwargs) self.model.json = dict(self) flag_modified(self.model, 'json') db.session.merge(self.model) after_record_update.send( current_app._get_current_object(), record=self ) return self
python
def commit(self, **kwargs): r"""Store changes of the current record instance in the database. #. Send a signal :data:`invenio_records.signals.before_record_update` with the current record to be committed as parameter. #. Validate the current record data. #. Commit the current record in the database. #. Send a signal :data:`invenio_records.signals.after_record_update` with the committed record as parameter. :Keyword Arguments: * **format_checker** -- An instance of the class :class:`jsonschema.FormatChecker`, which contains validation rules for formats. See :func:`~invenio_records.api.RecordBase.validate` for more details. * **validator** -- A :class:`jsonschema.IValidator` class that will be used to validate the record. See :func:`~invenio_records.api.RecordBase.validate` for more details. :returns: The :class:`Record` instance. """ if self.model is None or self.model.json is None: raise MissingModelError() with db.session.begin_nested(): before_record_update.send( current_app._get_current_object(), record=self ) self.validate(**kwargs) self.model.json = dict(self) flag_modified(self.model, 'json') db.session.merge(self.model) after_record_update.send( current_app._get_current_object(), record=self ) return self
[ "def", "commit", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "model", "is", "None", "or", "self", ".", "model", ".", "json", "is", "None", ":", "raise", "MissingModelError", "(", ")", "with", "db", ".", "session", ".", "begin...
r"""Store changes of the current record instance in the database. #. Send a signal :data:`invenio_records.signals.before_record_update` with the current record to be committed as parameter. #. Validate the current record data. #. Commit the current record in the database. #. Send a signal :data:`invenio_records.signals.after_record_update` with the committed record as parameter. :Keyword Arguments: * **format_checker** -- An instance of the class :class:`jsonschema.FormatChecker`, which contains validation rules for formats. See :func:`~invenio_records.api.RecordBase.validate` for more details. * **validator** -- A :class:`jsonschema.IValidator` class that will be used to validate the record. See :func:`~invenio_records.api.RecordBase.validate` for more details. :returns: The :class:`Record` instance.
[ "r", "Store", "changes", "of", "the", "current", "record", "instance", "in", "the", "database", "." ]
b0b1481d04012e45cb71b5ae4019e91dde88d1e2
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/api.py#L232-L278
train
30,024
inveniosoftware/invenio-records
invenio_records/api.py
Record.revert
def revert(self, revision_id): """Revert the record to a specific revision. #. Send a signal :data:`invenio_records.signals.before_record_revert` with the current record as parameter. #. Revert the record to the revision id passed as parameter. #. Send a signal :data:`invenio_records.signals.after_record_revert` with the reverted record as parameter. :param revision_id: Specify the record revision id :returns: The :class:`Record` instance corresponding to the revision id """ if self.model is None: raise MissingModelError() revision = self.revisions[revision_id] with db.session.begin_nested(): before_record_revert.send( current_app._get_current_object(), record=self ) self.model.json = dict(revision) db.session.merge(self.model) after_record_revert.send( current_app._get_current_object(), record=self ) return self.__class__(self.model.json, model=self.model)
python
def revert(self, revision_id): """Revert the record to a specific revision. #. Send a signal :data:`invenio_records.signals.before_record_revert` with the current record as parameter. #. Revert the record to the revision id passed as parameter. #. Send a signal :data:`invenio_records.signals.after_record_revert` with the reverted record as parameter. :param revision_id: Specify the record revision id :returns: The :class:`Record` instance corresponding to the revision id """ if self.model is None: raise MissingModelError() revision = self.revisions[revision_id] with db.session.begin_nested(): before_record_revert.send( current_app._get_current_object(), record=self ) self.model.json = dict(revision) db.session.merge(self.model) after_record_revert.send( current_app._get_current_object(), record=self ) return self.__class__(self.model.json, model=self.model)
[ "def", "revert", "(", "self", ",", "revision_id", ")", ":", "if", "self", ".", "model", "is", "None", ":", "raise", "MissingModelError", "(", ")", "revision", "=", "self", ".", "revisions", "[", "revision_id", "]", "with", "db", ".", "session", ".", "b...
Revert the record to a specific revision. #. Send a signal :data:`invenio_records.signals.before_record_revert` with the current record as parameter. #. Revert the record to the revision id passed as parameter. #. Send a signal :data:`invenio_records.signals.after_record_revert` with the reverted record as parameter. :param revision_id: Specify the record revision id :returns: The :class:`Record` instance corresponding to the revision id
[ "Revert", "the", "record", "to", "a", "specific", "revision", "." ]
b0b1481d04012e45cb71b5ae4019e91dde88d1e2
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/api.py#L322-L355
train
30,025
inveniosoftware/invenio-records
invenio_records/ext.py
_RecordsState.validate
def validate(self, data, schema, **kwargs): """Validate data using schema with ``JSONResolver``.""" if not isinstance(schema, dict): schema = {'$ref': schema} return validate( data, schema, resolver=self.ref_resolver_cls.from_schema(schema), types=self.app.config.get('RECORDS_VALIDATION_TYPES', {}), **kwargs )
python
def validate(self, data, schema, **kwargs): """Validate data using schema with ``JSONResolver``.""" if not isinstance(schema, dict): schema = {'$ref': schema} return validate( data, schema, resolver=self.ref_resolver_cls.from_schema(schema), types=self.app.config.get('RECORDS_VALIDATION_TYPES', {}), **kwargs )
[ "def", "validate", "(", "self", ",", "data", ",", "schema", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "schema", ",", "dict", ")", ":", "schema", "=", "{", "'$ref'", ":", "schema", "}", "return", "validate", "(", "data", ","...
Validate data using schema with ``JSONResolver``.
[ "Validate", "data", "using", "schema", "with", "JSONResolver", "." ]
b0b1481d04012e45cb71b5ae4019e91dde88d1e2
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/ext.py#L32-L42
train
30,026
filestack/filestack-python
filestack/models/filestack_audiovisual.py
AudioVisual.to_filelink
def to_filelink(self): """ Checks is the status of the conversion is complete and, if so, converts to a Filelink *returns* [Filestack.Filelink] ```python filelink = av_convert.to_filelink() ``` """ if self.status != 'completed': return 'Audio/video conversion not complete!' response = utils.make_call(self.url, 'get') if response.ok: response = response.json() handle = re.match( r'(?:https:\/\/cdn\.filestackcontent\.com\/)(\w+)', response['data']['url'] ).group(1) return filestack.models.Filelink(handle, apikey=self.apikey, security=self.security) raise Exception(response.text)
python
def to_filelink(self): """ Checks is the status of the conversion is complete and, if so, converts to a Filelink *returns* [Filestack.Filelink] ```python filelink = av_convert.to_filelink() ``` """ if self.status != 'completed': return 'Audio/video conversion not complete!' response = utils.make_call(self.url, 'get') if response.ok: response = response.json() handle = re.match( r'(?:https:\/\/cdn\.filestackcontent\.com\/)(\w+)', response['data']['url'] ).group(1) return filestack.models.Filelink(handle, apikey=self.apikey, security=self.security) raise Exception(response.text)
[ "def", "to_filelink", "(", "self", ")", ":", "if", "self", ".", "status", "!=", "'completed'", ":", "return", "'Audio/video conversion not complete!'", "response", "=", "utils", ".", "make_call", "(", "self", ".", "url", ",", "'get'", ")", "if", "response", ...
Checks is the status of the conversion is complete and, if so, converts to a Filelink *returns* [Filestack.Filelink] ```python filelink = av_convert.to_filelink() ```
[ "Checks", "is", "the", "status", "of", "the", "conversion", "is", "complete", "and", "if", "so", "converts", "to", "a", "Filelink" ]
f4d54c48987f3eeaad02d31cc5f6037e914bba0d
https://github.com/filestack/filestack-python/blob/f4d54c48987f3eeaad02d31cc5f6037e914bba0d/filestack/models/filestack_audiovisual.py#L34-L57
train
30,027
filestack/filestack-python
filestack/models/filestack_filelink.py
Filelink._return_tag_task
def _return_tag_task(self, task): """ Runs both SFW and Tags tasks """ if self.security is None: raise Exception('Tags require security') tasks = [task] transform_url = get_transform_url( tasks, handle=self.handle, security=self.security, apikey=self.apikey ) response = make_call( CDN_URL, 'get', handle=self.handle, security=self.security, transform_url=transform_url ) return response.json()
python
def _return_tag_task(self, task): """ Runs both SFW and Tags tasks """ if self.security is None: raise Exception('Tags require security') tasks = [task] transform_url = get_transform_url( tasks, handle=self.handle, security=self.security, apikey=self.apikey ) response = make_call( CDN_URL, 'get', handle=self.handle, security=self.security, transform_url=transform_url ) return response.json()
[ "def", "_return_tag_task", "(", "self", ",", "task", ")", ":", "if", "self", ".", "security", "is", "None", ":", "raise", "Exception", "(", "'Tags require security'", ")", "tasks", "=", "[", "task", "]", "transform_url", "=", "get_transform_url", "(", "tasks...
Runs both SFW and Tags tasks
[ "Runs", "both", "SFW", "and", "Tags", "tasks" ]
f4d54c48987f3eeaad02d31cc5f6037e914bba0d
https://github.com/filestack/filestack-python/blob/f4d54c48987f3eeaad02d31cc5f6037e914bba0d/filestack/models/filestack_filelink.py#L52-L67
train
30,028
filestack/filestack-python
filestack/models/filestack_filelink.py
Filelink.url
def url(self): """ Returns the URL for the instance, which can be used to retrieve, delete, and overwrite the file. If security is enabled, signature and policy parameters will be included, *returns* [String] ```python filelink = client.upload(filepath='/path/to/file') filelink.url # https://cdn.filestackcontent.com/FILE_HANDLE ``` """ return get_url(CDN_URL, handle=self.handle, security=self.security)
python
def url(self): """ Returns the URL for the instance, which can be used to retrieve, delete, and overwrite the file. If security is enabled, signature and policy parameters will be included, *returns* [String] ```python filelink = client.upload(filepath='/path/to/file') filelink.url # https://cdn.filestackcontent.com/FILE_HANDLE ``` """ return get_url(CDN_URL, handle=self.handle, security=self.security)
[ "def", "url", "(", "self", ")", ":", "return", "get_url", "(", "CDN_URL", ",", "handle", "=", "self", ".", "handle", ",", "security", "=", "self", ".", "security", ")" ]
Returns the URL for the instance, which can be used to retrieve, delete, and overwrite the file. If security is enabled, signature and policy parameters will be included, *returns* [String] ```python filelink = client.upload(filepath='/path/to/file') filelink.url # https://cdn.filestackcontent.com/FILE_HANDLE ```
[ "Returns", "the", "URL", "for", "the", "instance", "which", "can", "be", "used", "to", "retrieve", "delete", "and", "overwrite", "the", "file", ".", "If", "security", "is", "enabled", "signature", "and", "policy", "parameters", "will", "be", "included" ]
f4d54c48987f3eeaad02d31cc5f6037e914bba0d
https://github.com/filestack/filestack-python/blob/f4d54c48987f3eeaad02d31cc5f6037e914bba0d/filestack/models/filestack_filelink.py#L84-L98
train
30,029
filestack/filestack-python
filestack/mixins/filestack_imagetransform_mixin.py
ImageTransformationMixin.zip
def zip(self, store=False, store_params=None): """ Returns a zip file of the current transformation. This is different from the zip function that lives on the Filestack Client *returns* [Filestack.Transform] """ params = locals() params.pop('store') params.pop('store_params') new_transform = self.add_transform_task('zip', params) if store: return new_transform.store(**store_params) if store_params else new_transform.store() return utils.make_call(CDN_URL, 'get', transform_url=new_transform.url)
python
def zip(self, store=False, store_params=None): """ Returns a zip file of the current transformation. This is different from the zip function that lives on the Filestack Client *returns* [Filestack.Transform] """ params = locals() params.pop('store') params.pop('store_params') new_transform = self.add_transform_task('zip', params) if store: return new_transform.store(**store_params) if store_params else new_transform.store() return utils.make_call(CDN_URL, 'get', transform_url=new_transform.url)
[ "def", "zip", "(", "self", ",", "store", "=", "False", ",", "store_params", "=", "None", ")", ":", "params", "=", "locals", "(", ")", "params", ".", "pop", "(", "'store'", ")", "params", ".", "pop", "(", "'store_params'", ")", "new_transform", "=", "...
Returns a zip file of the current transformation. This is different from the zip function that lives on the Filestack Client *returns* [Filestack.Transform]
[ "Returns", "a", "zip", "file", "of", "the", "current", "transformation", ".", "This", "is", "different", "from", "the", "zip", "function", "that", "lives", "on", "the", "Filestack", "Client" ]
f4d54c48987f3eeaad02d31cc5f6037e914bba0d
https://github.com/filestack/filestack-python/blob/f4d54c48987f3eeaad02d31cc5f6037e914bba0d/filestack/mixins/filestack_imagetransform_mixin.py#L119-L135
train
30,030
filestack/filestack-python
filestack/mixins/filestack_imagetransform_mixin.py
ImageTransformationMixin.av_convert
def av_convert(self, preset=None, force=None, title=None, extname=None, filename=None, width=None, height=None, upscale=None, aspect_mode=None, two_pass=None, video_bitrate=None, fps=None, keyframe_interval=None, location=None, watermark_url=None, watermark_top=None, watermark_bottom=None, watermark_right=None, watermark_left=None, watermark_width=None, watermark_height=None, path=None, access=None, container=None, audio_bitrate=None, audio_sample_rate=None, audio_channels=None, clip_length=None, clip_offset=None): """ ```python from filestack import Client client = Client("<API_KEY>") filelink = client.upload(filepath='path/to/file/doom.mp4') av_convert= filelink.av_convert(width=100, height=100) while av_convert.status != 'completed': print(av_convert.status) filelink = av_convert.to_filelink() print(filelink.url) ``` """ new_transform = self.add_transform_task('video_convert', locals()) transform_url = utils.get_transform_url( new_transform._transformation_tasks, external_url=new_transform.external_url, handle=new_transform.handle, security=new_transform.security, apikey=new_transform.apikey, video=True ) response = utils.make_call(transform_url, 'get') if not response.ok: raise Exception(response.text) uuid = response.json()['uuid'] timestamp = response.json()['timestamp'] return filestack.models.AudioVisual( transform_url, uuid, timestamp, apikey=new_transform.apikey, security=new_transform.security )
python
def av_convert(self, preset=None, force=None, title=None, extname=None, filename=None, width=None, height=None, upscale=None, aspect_mode=None, two_pass=None, video_bitrate=None, fps=None, keyframe_interval=None, location=None, watermark_url=None, watermark_top=None, watermark_bottom=None, watermark_right=None, watermark_left=None, watermark_width=None, watermark_height=None, path=None, access=None, container=None, audio_bitrate=None, audio_sample_rate=None, audio_channels=None, clip_length=None, clip_offset=None): """ ```python from filestack import Client client = Client("<API_KEY>") filelink = client.upload(filepath='path/to/file/doom.mp4') av_convert= filelink.av_convert(width=100, height=100) while av_convert.status != 'completed': print(av_convert.status) filelink = av_convert.to_filelink() print(filelink.url) ``` """ new_transform = self.add_transform_task('video_convert', locals()) transform_url = utils.get_transform_url( new_transform._transformation_tasks, external_url=new_transform.external_url, handle=new_transform.handle, security=new_transform.security, apikey=new_transform.apikey, video=True ) response = utils.make_call(transform_url, 'get') if not response.ok: raise Exception(response.text) uuid = response.json()['uuid'] timestamp = response.json()['timestamp'] return filestack.models.AudioVisual( transform_url, uuid, timestamp, apikey=new_transform.apikey, security=new_transform.security )
[ "def", "av_convert", "(", "self", ",", "preset", "=", "None", ",", "force", "=", "None", ",", "title", "=", "None", ",", "extname", "=", "None", ",", "filename", "=", "None", ",", "width", "=", "None", ",", "height", "=", "None", ",", "upscale", "=...
```python from filestack import Client client = Client("<API_KEY>") filelink = client.upload(filepath='path/to/file/doom.mp4') av_convert= filelink.av_convert(width=100, height=100) while av_convert.status != 'completed': print(av_convert.status) filelink = av_convert.to_filelink() print(filelink.url) ```
[ "python", "from", "filestack", "import", "Client" ]
f4d54c48987f3eeaad02d31cc5f6037e914bba0d
https://github.com/filestack/filestack-python/blob/f4d54c48987f3eeaad02d31cc5f6037e914bba0d/filestack/mixins/filestack_imagetransform_mixin.py#L137-L177
train
30,031
filestack/filestack-python
filestack/mixins/filestack_imagetransform_mixin.py
ImageTransformationMixin.add_transform_task
def add_transform_task(self, transformation, params): """ Adds a transform task to the current instance and returns it *returns* Filestack.Transform """ if not isinstance(self, filestack.models.Transform): instance = filestack.models.Transform(apikey=self.apikey, security=self.security, handle=self.handle) else: instance = self params.pop('self') params = {k: v for k, v in params.items() if v is not None} transformation_url = utils.return_transform_task(transformation, params) instance._transformation_tasks.append(transformation_url) return instance
python
def add_transform_task(self, transformation, params): """ Adds a transform task to the current instance and returns it *returns* Filestack.Transform """ if not isinstance(self, filestack.models.Transform): instance = filestack.models.Transform(apikey=self.apikey, security=self.security, handle=self.handle) else: instance = self params.pop('self') params = {k: v for k, v in params.items() if v is not None} transformation_url = utils.return_transform_task(transformation, params) instance._transformation_tasks.append(transformation_url) return instance
[ "def", "add_transform_task", "(", "self", ",", "transformation", ",", "params", ")", ":", "if", "not", "isinstance", "(", "self", ",", "filestack", ".", "models", ".", "Transform", ")", ":", "instance", "=", "filestack", ".", "models", ".", "Transform", "(...
Adds a transform task to the current instance and returns it *returns* Filestack.Transform
[ "Adds", "a", "transform", "task", "to", "the", "current", "instance", "and", "returns", "it" ]
f4d54c48987f3eeaad02d31cc5f6037e914bba0d
https://github.com/filestack/filestack-python/blob/f4d54c48987f3eeaad02d31cc5f6037e914bba0d/filestack/mixins/filestack_imagetransform_mixin.py#L180-L197
train
30,032
filestack/filestack-python
filestack/mixins/filestack_common.py
CommonMixin.download
def download(self, destination_path, params=None): """ Downloads a file to the given local path and returns the size of the downloaded file if successful *returns* [Integer] ```python from filestack import Client client = Client('API_KEY', security=sec) filelink = client.upload(filepath='/path/to/file') # if successful, returns size of downloaded file in bytes response = filelink.download('path/to/file') ``` """ if params: CONTENT_DOWNLOAD_SCHEMA.check(params) with open(destination_path, 'wb') as new_file: response = utils.make_call(CDN_URL, 'get', handle=self.handle, params=params, security=self.security, transform_url=(self.url if isinstance(self, filestack.models.Transform) else None)) if response.ok: for chunk in response.iter_content(1024): if not chunk: break new_file.write(chunk) return response
python
def download(self, destination_path, params=None): """ Downloads a file to the given local path and returns the size of the downloaded file if successful *returns* [Integer] ```python from filestack import Client client = Client('API_KEY', security=sec) filelink = client.upload(filepath='/path/to/file') # if successful, returns size of downloaded file in bytes response = filelink.download('path/to/file') ``` """ if params: CONTENT_DOWNLOAD_SCHEMA.check(params) with open(destination_path, 'wb') as new_file: response = utils.make_call(CDN_URL, 'get', handle=self.handle, params=params, security=self.security, transform_url=(self.url if isinstance(self, filestack.models.Transform) else None)) if response.ok: for chunk in response.iter_content(1024): if not chunk: break new_file.write(chunk) return response
[ "def", "download", "(", "self", ",", "destination_path", ",", "params", "=", "None", ")", ":", "if", "params", ":", "CONTENT_DOWNLOAD_SCHEMA", ".", "check", "(", "params", ")", "with", "open", "(", "destination_path", ",", "'wb'", ")", "as", "new_file", ":...
Downloads a file to the given local path and returns the size of the downloaded file if successful *returns* [Integer] ```python from filestack import Client client = Client('API_KEY', security=sec) filelink = client.upload(filepath='/path/to/file') # if successful, returns size of downloaded file in bytes response = filelink.download('path/to/file') ```
[ "Downloads", "a", "file", "to", "the", "given", "local", "path", "and", "returns", "the", "size", "of", "the", "downloaded", "file", "if", "successful" ]
f4d54c48987f3eeaad02d31cc5f6037e914bba0d
https://github.com/filestack/filestack-python/blob/f4d54c48987f3eeaad02d31cc5f6037e914bba0d/filestack/mixins/filestack_common.py#L15-L45
train
30,033
filestack/filestack-python
filestack/mixins/filestack_common.py
CommonMixin.get_content
def get_content(self, params=None): """ Returns the raw byte content of a given Filelink *returns* [Bytes] ```python from filestack import Client client = Client('API_KEY') filelink = client.upload(filepath='/path/to/file/foo.jpg') byte_content = filelink.get_content() ``` """ if params: CONTENT_DOWNLOAD_SCHEMA.check(params) response = utils.make_call(CDN_URL, 'get', handle=self.handle, params=params, security=self.security, transform_url=(self.url if isinstance(self, filestack.models.Transform) else None)) return response.content
python
def get_content(self, params=None): """ Returns the raw byte content of a given Filelink *returns* [Bytes] ```python from filestack import Client client = Client('API_KEY') filelink = client.upload(filepath='/path/to/file/foo.jpg') byte_content = filelink.get_content() ``` """ if params: CONTENT_DOWNLOAD_SCHEMA.check(params) response = utils.make_call(CDN_URL, 'get', handle=self.handle, params=params, security=self.security, transform_url=(self.url if isinstance(self, filestack.models.Transform) else None)) return response.content
[ "def", "get_content", "(", "self", ",", "params", "=", "None", ")", ":", "if", "params", ":", "CONTENT_DOWNLOAD_SCHEMA", ".", "check", "(", "params", ")", "response", "=", "utils", ".", "make_call", "(", "CDN_URL", ",", "'get'", ",", "handle", "=", "self...
Returns the raw byte content of a given Filelink *returns* [Bytes] ```python from filestack import Client client = Client('API_KEY') filelink = client.upload(filepath='/path/to/file/foo.jpg') byte_content = filelink.get_content() ```
[ "Returns", "the", "raw", "byte", "content", "of", "a", "given", "Filelink" ]
f4d54c48987f3eeaad02d31cc5f6037e914bba0d
https://github.com/filestack/filestack-python/blob/f4d54c48987f3eeaad02d31cc5f6037e914bba0d/filestack/mixins/filestack_common.py#L47-L68
train
30,034
filestack/filestack-python
filestack/mixins/filestack_common.py
CommonMixin.get_metadata
def get_metadata(self, params=None): """ Metadata provides certain information about a Filehandle, and you can specify which pieces of information you will receive back by passing in optional parameters. ```python from filestack import Client client = Client('API_KEY') filelink = client.upload(filepath='/path/to/file/foo.jpg') metadata = filelink.get_metadata() # or define specific metadata to receive metadata = filelink.get_metadata({'filename': true}) ``` """ metadata_url = "{CDN_URL}/{handle}/metadata".format( CDN_URL=CDN_URL, handle=self.handle ) response = utils.make_call(metadata_url, 'get', params=params, security=self.security) return response.json()
python
def get_metadata(self, params=None): """ Metadata provides certain information about a Filehandle, and you can specify which pieces of information you will receive back by passing in optional parameters. ```python from filestack import Client client = Client('API_KEY') filelink = client.upload(filepath='/path/to/file/foo.jpg') metadata = filelink.get_metadata() # or define specific metadata to receive metadata = filelink.get_metadata({'filename': true}) ``` """ metadata_url = "{CDN_URL}/{handle}/metadata".format( CDN_URL=CDN_URL, handle=self.handle ) response = utils.make_call(metadata_url, 'get', params=params, security=self.security) return response.json()
[ "def", "get_metadata", "(", "self", ",", "params", "=", "None", ")", ":", "metadata_url", "=", "\"{CDN_URL}/{handle}/metadata\"", ".", "format", "(", "CDN_URL", "=", "CDN_URL", ",", "handle", "=", "self", ".", "handle", ")", "response", "=", "utils", ".", ...
Metadata provides certain information about a Filehandle, and you can specify which pieces of information you will receive back by passing in optional parameters. ```python from filestack import Client client = Client('API_KEY') filelink = client.upload(filepath='/path/to/file/foo.jpg') metadata = filelink.get_metadata() # or define specific metadata to receive metadata = filelink.get_metadata({'filename': true}) ```
[ "Metadata", "provides", "certain", "information", "about", "a", "Filehandle", "and", "you", "can", "specify", "which", "pieces", "of", "information", "you", "will", "receive", "back", "by", "passing", "in", "optional", "parameters", "." ]
f4d54c48987f3eeaad02d31cc5f6037e914bba0d
https://github.com/filestack/filestack-python/blob/f4d54c48987f3eeaad02d31cc5f6037e914bba0d/filestack/mixins/filestack_common.py#L70-L91
train
30,035
filestack/filestack-python
filestack/mixins/filestack_common.py
CommonMixin.delete
def delete(self, params=None): """ You may delete any file you have uploaded, either through a Filelink returned from the client or one you have initialized yourself. This returns a response of success or failure. This action requires security.abs *returns* [requests.response] ```python from filestack import Client, security # a policy requires at least an expiry policy = {'expiry': 56589012} sec = security(policy, 'APP_SECRET') client = Client('API_KEY', security=sec) filelink = client.upload(filepath='/path/to/file/foo.txt') response = filelink.delete() ``` """ if params: params['key'] = self.apikey else: params = {'key': self.apikey} return utils.make_call(API_URL, 'delete', path=FILE_PATH, handle=self.handle, params=params, security=self.security, transform_url=self.url if isinstance(self, filestack.models.Transform) else None)
python
def delete(self, params=None): """ You may delete any file you have uploaded, either through a Filelink returned from the client or one you have initialized yourself. This returns a response of success or failure. This action requires security.abs *returns* [requests.response] ```python from filestack import Client, security # a policy requires at least an expiry policy = {'expiry': 56589012} sec = security(policy, 'APP_SECRET') client = Client('API_KEY', security=sec) filelink = client.upload(filepath='/path/to/file/foo.txt') response = filelink.delete() ``` """ if params: params['key'] = self.apikey else: params = {'key': self.apikey} return utils.make_call(API_URL, 'delete', path=FILE_PATH, handle=self.handle, params=params, security=self.security, transform_url=self.url if isinstance(self, filestack.models.Transform) else None)
[ "def", "delete", "(", "self", ",", "params", "=", "None", ")", ":", "if", "params", ":", "params", "[", "'key'", "]", "=", "self", ".", "apikey", "else", ":", "params", "=", "{", "'key'", ":", "self", ".", "apikey", "}", "return", "utils", ".", "...
You may delete any file you have uploaded, either through a Filelink returned from the client or one you have initialized yourself. This returns a response of success or failure. This action requires security.abs *returns* [requests.response] ```python from filestack import Client, security # a policy requires at least an expiry policy = {'expiry': 56589012} sec = security(policy, 'APP_SECRET') client = Client('API_KEY', security=sec) filelink = client.upload(filepath='/path/to/file/foo.txt') response = filelink.delete() ```
[ "You", "may", "delete", "any", "file", "you", "have", "uploaded", "either", "through", "a", "Filelink", "returned", "from", "the", "client", "or", "one", "you", "have", "initialized", "yourself", ".", "This", "returns", "a", "response", "of", "success", "or"...
f4d54c48987f3eeaad02d31cc5f6037e914bba0d
https://github.com/filestack/filestack-python/blob/f4d54c48987f3eeaad02d31cc5f6037e914bba0d/filestack/mixins/filestack_common.py#L93-L121
train
30,036
filestack/filestack-python
filestack/mixins/filestack_common.py
CommonMixin.overwrite
def overwrite(self, url=None, filepath=None, params=None): """ You may overwrite any Filelink by supplying a new file. The Filehandle will remain the same. *returns* [requests.response] ```python from filestack import Client, security # a policy requires at least an expiry policy = {'expiry': 56589012} sec = security(policy, 'APP_SECRET') client = Client('API_KEY', security=sec) ``` """ if params: OVERWRITE_SCHEMA.check(params) data, files = None, None if url: data = {'url': url} elif filepath: filename = os.path.basename(filepath) mimetype = mimetypes.guess_type(filepath)[0] files = {'fileUpload': (filename, open(filepath, 'rb'), mimetype)} else: raise ValueError("You must include a url or filepath parameter") return utils.make_call(API_URL, 'post', path=FILE_PATH, params=params, handle=self.handle, data=data, files=files, security=self.security, transform_url=self.url if isinstance(self, filestack.models.Transform) else None)
python
def overwrite(self, url=None, filepath=None, params=None): """ You may overwrite any Filelink by supplying a new file. The Filehandle will remain the same. *returns* [requests.response] ```python from filestack import Client, security # a policy requires at least an expiry policy = {'expiry': 56589012} sec = security(policy, 'APP_SECRET') client = Client('API_KEY', security=sec) ``` """ if params: OVERWRITE_SCHEMA.check(params) data, files = None, None if url: data = {'url': url} elif filepath: filename = os.path.basename(filepath) mimetype = mimetypes.guess_type(filepath)[0] files = {'fileUpload': (filename, open(filepath, 'rb'), mimetype)} else: raise ValueError("You must include a url or filepath parameter") return utils.make_call(API_URL, 'post', path=FILE_PATH, params=params, handle=self.handle, data=data, files=files, security=self.security, transform_url=self.url if isinstance(self, filestack.models.Transform) else None)
[ "def", "overwrite", "(", "self", ",", "url", "=", "None", ",", "filepath", "=", "None", ",", "params", "=", "None", ")", ":", "if", "params", ":", "OVERWRITE_SCHEMA", ".", "check", "(", "params", ")", "data", ",", "files", "=", "None", ",", "None", ...
You may overwrite any Filelink by supplying a new file. The Filehandle will remain the same. *returns* [requests.response] ```python from filestack import Client, security # a policy requires at least an expiry policy = {'expiry': 56589012} sec = security(policy, 'APP_SECRET') client = Client('API_KEY', security=sec) ```
[ "You", "may", "overwrite", "any", "Filelink", "by", "supplying", "a", "new", "file", ".", "The", "Filehandle", "will", "remain", "the", "same", "." ]
f4d54c48987f3eeaad02d31cc5f6037e914bba0d
https://github.com/filestack/filestack-python/blob/f4d54c48987f3eeaad02d31cc5f6037e914bba0d/filestack/mixins/filestack_common.py#L123-L158
train
30,037
filestack/filestack-python
filestack/models/filestack_security.py
validate
def validate(policy): """ Validates a policy and its parameters and raises an error if invalid """ for param, value in policy.items(): if param not in ACCEPTED_SECURITY_TYPES.keys(): raise SecurityError('Invalid Security Parameter: {}'.format(param)) if type(value) != ACCEPTED_SECURITY_TYPES[param]: raise SecurityError('Invalid Parameter Data Type for {}, ' 'Expecting: {} Received: {}'.format( param, ACCEPTED_SECURITY_TYPES[param], type(value)))
python
def validate(policy): """ Validates a policy and its parameters and raises an error if invalid """ for param, value in policy.items(): if param not in ACCEPTED_SECURITY_TYPES.keys(): raise SecurityError('Invalid Security Parameter: {}'.format(param)) if type(value) != ACCEPTED_SECURITY_TYPES[param]: raise SecurityError('Invalid Parameter Data Type for {}, ' 'Expecting: {} Received: {}'.format( param, ACCEPTED_SECURITY_TYPES[param], type(value)))
[ "def", "validate", "(", "policy", ")", ":", "for", "param", ",", "value", "in", "policy", ".", "items", "(", ")", ":", "if", "param", "not", "in", "ACCEPTED_SECURITY_TYPES", ".", "keys", "(", ")", ":", "raise", "SecurityError", "(", "'Invalid Security Para...
Validates a policy and its parameters and raises an error if invalid
[ "Validates", "a", "policy", "and", "its", "parameters", "and", "raises", "an", "error", "if", "invalid" ]
f4d54c48987f3eeaad02d31cc5f6037e914bba0d
https://github.com/filestack/filestack-python/blob/f4d54c48987f3eeaad02d31cc5f6037e914bba0d/filestack/models/filestack_security.py#L10-L23
train
30,038
filestack/filestack-python
filestack/models/filestack_security.py
security
def security(policy, app_secret): """ Creates a valid signature and policy based on provided app secret and parameters ```python from filestack import Client, security # a policy requires at least an expiry policy = {'expiry': 56589012, 'call': ['read', 'store', 'pick']} sec = security(policy, 'APP_SECRET') client = Client('API_KEY', security=sec) ``` """ validate(policy) policy_enc = base64.urlsafe_b64encode(json.dumps(policy).encode('utf-8')) signature = hmac.new(app_secret.encode('utf-8'), policy_enc, hashlib.sha256).hexdigest() return {'policy': policy_enc, 'signature': signature}
python
def security(policy, app_secret): """ Creates a valid signature and policy based on provided app secret and parameters ```python from filestack import Client, security # a policy requires at least an expiry policy = {'expiry': 56589012, 'call': ['read', 'store', 'pick']} sec = security(policy, 'APP_SECRET') client = Client('API_KEY', security=sec) ``` """ validate(policy) policy_enc = base64.urlsafe_b64encode(json.dumps(policy).encode('utf-8')) signature = hmac.new(app_secret.encode('utf-8'), policy_enc, hashlib.sha256).hexdigest() return {'policy': policy_enc, 'signature': signature}
[ "def", "security", "(", "policy", ",", "app_secret", ")", ":", "validate", "(", "policy", ")", "policy_enc", "=", "base64", ".", "urlsafe_b64encode", "(", "json", ".", "dumps", "(", "policy", ")", ".", "encode", "(", "'utf-8'", ")", ")", "signature", "="...
Creates a valid signature and policy based on provided app secret and parameters ```python from filestack import Client, security # a policy requires at least an expiry policy = {'expiry': 56589012, 'call': ['read', 'store', 'pick']} sec = security(policy, 'APP_SECRET') client = Client('API_KEY', security=sec) ```
[ "Creates", "a", "valid", "signature", "and", "policy", "based", "on", "provided", "app", "secret", "and", "parameters", "python", "from", "filestack", "import", "Client", "security" ]
f4d54c48987f3eeaad02d31cc5f6037e914bba0d
https://github.com/filestack/filestack-python/blob/f4d54c48987f3eeaad02d31cc5f6037e914bba0d/filestack/models/filestack_security.py#L26-L47
train
30,039
filestack/filestack-python
filestack/models/filestack_client.py
Client.transform_external
def transform_external(self, external_url): """ Turns an external URL into a Filestack Transform object *returns* [Filestack.Transform] ```python from filestack import Client, Filelink client = Client("API_KEY") transform = client.transform_external('http://www.example.com') ``` """ return filestack.models.Transform(apikey=self.apikey, security=self.security, external_url=external_url)
python
def transform_external(self, external_url): """ Turns an external URL into a Filestack Transform object *returns* [Filestack.Transform] ```python from filestack import Client, Filelink client = Client("API_KEY") transform = client.transform_external('http://www.example.com') ``` """ return filestack.models.Transform(apikey=self.apikey, security=self.security, external_url=external_url)
[ "def", "transform_external", "(", "self", ",", "external_url", ")", ":", "return", "filestack", ".", "models", ".", "Transform", "(", "apikey", "=", "self", ".", "apikey", ",", "security", "=", "self", ".", "security", ",", "external_url", "=", "external_url...
Turns an external URL into a Filestack Transform object *returns* [Filestack.Transform] ```python from filestack import Client, Filelink client = Client("API_KEY") transform = client.transform_external('http://www.example.com') ```
[ "Turns", "an", "external", "URL", "into", "a", "Filestack", "Transform", "object" ]
f4d54c48987f3eeaad02d31cc5f6037e914bba0d
https://github.com/filestack/filestack-python/blob/f4d54c48987f3eeaad02d31cc5f6037e914bba0d/filestack/models/filestack_client.py#L26-L39
train
30,040
filestack/filestack-python
filestack/models/filestack_client.py
Client.urlscreenshot
def urlscreenshot(self, external_url, agent=None, mode=None, width=None, height=None, delay=None): """ Takes a 'screenshot' of the given URL *returns* [Filestack.Transform] ```python from filestack import Client client = Client("API_KEY") # returns a Transform object screenshot = client.url_screenshot('https://www.example.com', width=100, height=100, agent="desktop") filelink = screenshot.store() ```` """ params = locals() params.pop('self') params.pop('external_url') params = {k: v for k, v in params.items() if v is not None} url_task = utils.return_transform_task('urlscreenshot', params) new_transform = filestack.models.Transform(apikey=self.apikey, security=self.security, external_url=external_url) new_transform._transformation_tasks.append(url_task) return new_transform
python
def urlscreenshot(self, external_url, agent=None, mode=None, width=None, height=None, delay=None): """ Takes a 'screenshot' of the given URL *returns* [Filestack.Transform] ```python from filestack import Client client = Client("API_KEY") # returns a Transform object screenshot = client.url_screenshot('https://www.example.com', width=100, height=100, agent="desktop") filelink = screenshot.store() ```` """ params = locals() params.pop('self') params.pop('external_url') params = {k: v for k, v in params.items() if v is not None} url_task = utils.return_transform_task('urlscreenshot', params) new_transform = filestack.models.Transform(apikey=self.apikey, security=self.security, external_url=external_url) new_transform._transformation_tasks.append(url_task) return new_transform
[ "def", "urlscreenshot", "(", "self", ",", "external_url", ",", "agent", "=", "None", ",", "mode", "=", "None", ",", "width", "=", "None", ",", "height", "=", "None", ",", "delay", "=", "None", ")", ":", "params", "=", "locals", "(", ")", "params", ...
Takes a 'screenshot' of the given URL *returns* [Filestack.Transform] ```python from filestack import Client client = Client("API_KEY") # returns a Transform object screenshot = client.url_screenshot('https://www.example.com', width=100, height=100, agent="desktop") filelink = screenshot.store() ````
[ "Takes", "a", "screenshot", "of", "the", "given", "URL" ]
f4d54c48987f3eeaad02d31cc5f6037e914bba0d
https://github.com/filestack/filestack-python/blob/f4d54c48987f3eeaad02d31cc5f6037e914bba0d/filestack/models/filestack_client.py#L41-L67
train
30,041
filestack/filestack-python
filestack/models/filestack_client.py
Client.zip
def zip(self, destination_path, files): """ Takes array of files and downloads a compressed ZIP archive to provided path *returns* [requests.response] ```python from filestack import Client client = Client("<API_KEY>") client.zip('/path/to/file/destination', ['files']) ``` """ zip_url = "{}/{}/zip/[{}]".format(CDN_URL, self.apikey, ','.join(files)) with open(destination_path, 'wb') as new_file: response = utils.make_call(zip_url, 'get') if response.ok: for chunk in response.iter_content(1024): if not chunk: break new_file.write(chunk) return response return response.text
python
def zip(self, destination_path, files): """ Takes array of files and downloads a compressed ZIP archive to provided path *returns* [requests.response] ```python from filestack import Client client = Client("<API_KEY>") client.zip('/path/to/file/destination', ['files']) ``` """ zip_url = "{}/{}/zip/[{}]".format(CDN_URL, self.apikey, ','.join(files)) with open(destination_path, 'wb') as new_file: response = utils.make_call(zip_url, 'get') if response.ok: for chunk in response.iter_content(1024): if not chunk: break new_file.write(chunk) return response return response.text
[ "def", "zip", "(", "self", ",", "destination_path", ",", "files", ")", ":", "zip_url", "=", "\"{}/{}/zip/[{}]\"", ".", "format", "(", "CDN_URL", ",", "self", ".", "apikey", ",", "','", ".", "join", "(", "files", ")", ")", "with", "open", "(", "destinat...
Takes array of files and downloads a compressed ZIP archive to provided path *returns* [requests.response] ```python from filestack import Client client = Client("<API_KEY>") client.zip('/path/to/file/destination', ['files']) ```
[ "Takes", "array", "of", "files", "and", "downloads", "a", "compressed", "ZIP", "archive", "to", "provided", "path" ]
f4d54c48987f3eeaad02d31cc5f6037e914bba0d
https://github.com/filestack/filestack-python/blob/f4d54c48987f3eeaad02d31cc5f6037e914bba0d/filestack/models/filestack_client.py#L69-L94
train
30,042
filestack/filestack-python
filestack/models/filestack_transform.py
Transform.url
def url(self): """ Returns the URL for the current transformation, which can be used to retrieve the file. If security is enabled, signature and policy parameters will be included *returns* [String] ```python transform = client.upload(filepath='/path/to/file') transform.url() # https://cdn.filestackcontent.com/TRANSFORMS/FILE_HANDLE ``` """ return utils.get_transform_url( self._transformation_tasks, external_url=self.external_url, handle=self.handle, security=self.security, apikey=self.apikey )
python
def url(self): """ Returns the URL for the current transformation, which can be used to retrieve the file. If security is enabled, signature and policy parameters will be included *returns* [String] ```python transform = client.upload(filepath='/path/to/file') transform.url() # https://cdn.filestackcontent.com/TRANSFORMS/FILE_HANDLE ``` """ return utils.get_transform_url( self._transformation_tasks, external_url=self.external_url, handle=self.handle, security=self.security, apikey=self.apikey )
[ "def", "url", "(", "self", ")", ":", "return", "utils", ".", "get_transform_url", "(", "self", ".", "_transformation_tasks", ",", "external_url", "=", "self", ".", "external_url", ",", "handle", "=", "self", ".", "handle", ",", "security", "=", "self", "."...
Returns the URL for the current transformation, which can be used to retrieve the file. If security is enabled, signature and policy parameters will be included *returns* [String] ```python transform = client.upload(filepath='/path/to/file') transform.url() # https://cdn.filestackcontent.com/TRANSFORMS/FILE_HANDLE ```
[ "Returns", "the", "URL", "for", "the", "current", "transformation", "which", "can", "be", "used", "to", "retrieve", "the", "file", ".", "If", "security", "is", "enabled", "signature", "and", "policy", "parameters", "will", "be", "included" ]
f4d54c48987f3eeaad02d31cc5f6037e914bba0d
https://github.com/filestack/filestack-python/blob/f4d54c48987f3eeaad02d31cc5f6037e914bba0d/filestack/models/filestack_transform.py#L96-L113
train
30,043
filestack/filestack-python
filestack/models/filestack_transform.py
Transform.store
def store(self, filename=None, location=None, path=None, container=None, region=None, access=None, base64decode=None): """ Uploads and stores the current transformation as a Fileink *returns* [Filestack.Filelink] ```python filelink = transform.store() ``` """ if path: path = '"{}"'.format(path) filelink_obj = self.add_transform_task('store', locals()) response = utils.make_call(filelink_obj.url, 'get') if response.ok: data = json.loads(response.text) handle = re.match(r'(?:https:\/\/cdn\.filestackcontent\.com\/)(\w+)', data['url']).group(1) return filestack.models.Filelink(handle, apikey=self.apikey, security=self.security) else: raise Exception(response.text)
python
def store(self, filename=None, location=None, path=None, container=None, region=None, access=None, base64decode=None): """ Uploads and stores the current transformation as a Fileink *returns* [Filestack.Filelink] ```python filelink = transform.store() ``` """ if path: path = '"{}"'.format(path) filelink_obj = self.add_transform_task('store', locals()) response = utils.make_call(filelink_obj.url, 'get') if response.ok: data = json.loads(response.text) handle = re.match(r'(?:https:\/\/cdn\.filestackcontent\.com\/)(\w+)', data['url']).group(1) return filestack.models.Filelink(handle, apikey=self.apikey, security=self.security) else: raise Exception(response.text)
[ "def", "store", "(", "self", ",", "filename", "=", "None", ",", "location", "=", "None", ",", "path", "=", "None", ",", "container", "=", "None", ",", "region", "=", "None", ",", "access", "=", "None", ",", "base64decode", "=", "None", ")", ":", "i...
Uploads and stores the current transformation as a Fileink *returns* [Filestack.Filelink] ```python filelink = transform.store() ```
[ "Uploads", "and", "stores", "the", "current", "transformation", "as", "a", "Fileink" ]
f4d54c48987f3eeaad02d31cc5f6037e914bba0d
https://github.com/filestack/filestack-python/blob/f4d54c48987f3eeaad02d31cc5f6037e914bba0d/filestack/models/filestack_transform.py#L115-L136
train
30,044
filestack/filestack-python
filestack/models/filestack_transform.py
Transform.debug
def debug(self): """ Returns a JSON object with inforamtion regarding the current transformation *returns* [Dict] """ debug_instance = self.add_transform_task('debug', locals()) response = utils.make_call(debug_instance.url, 'get') return response.json()
python
def debug(self): """ Returns a JSON object with inforamtion regarding the current transformation *returns* [Dict] """ debug_instance = self.add_transform_task('debug', locals()) response = utils.make_call(debug_instance.url, 'get') return response.json()
[ "def", "debug", "(", "self", ")", ":", "debug_instance", "=", "self", ".", "add_transform_task", "(", "'debug'", ",", "locals", "(", ")", ")", "response", "=", "utils", ".", "make_call", "(", "debug_instance", ".", "url", ",", "'get'", ")", "return", "re...
Returns a JSON object with inforamtion regarding the current transformation *returns* [Dict]
[ "Returns", "a", "JSON", "object", "with", "inforamtion", "regarding", "the", "current", "transformation" ]
f4d54c48987f3eeaad02d31cc5f6037e914bba0d
https://github.com/filestack/filestack-python/blob/f4d54c48987f3eeaad02d31cc5f6037e914bba0d/filestack/models/filestack_transform.py#L138-L146
train
30,045
tox-dev/tox-venv
src/tox_venv/hooks.py
real_python3
def real_python3(python, version_dict): """ Determine the path of the real python executable, which is then used for venv creation. This is necessary, because an active virtualenv environment will cause venv creation to malfunction. By getting the path of the real executable, this issue is bypassed. The provided `python` path may be either: - A real python executable - A virtual python executable (with venv) - A virtual python executable (with virtualenv) If the virtual environment was created with virtualenv, the `sys` module will have a `real_prefix` attribute, which points to the directory where the real python files are installed. If `real_prefix` is not present, the environment was not created with virtualenv, and the python executable is safe to use. The `version_dict` is used for attempting to derive the real executable path. This is necessary when the name of the virtual python executable does not exist in the Python installation's directory. For example, if the `basepython` is explicitly set to `python`, tox will use this name instead of attempting `pythonX.Y`. In many cases, Python 3 installations do not contain an executable named `python`, so we attempt to derive this from the version info. e.g., `python3.6.5`, `python3.6`, then `python3`. """ args = [python, '-c', 'import sys; print(sys.real_prefix)'] # get python prefix try: output = subprocess.check_output(args, stderr=subprocess.STDOUT) prefix = output.decode('UTF-8').strip() except subprocess.CalledProcessError: # process fails, implies *not* in active virtualenv return python # determine absolute binary path if os.name == 'nt': # pragma: no cover paths = [os.path.join(prefix, os.path.basename(python))] else: paths = [os.path.join(prefix, 'bin', python) for python in [ os.path.basename(python), 'python%(major)d.%(minor)d.%(micro)d' % version_dict, 'python%(major)d.%(minor)d' % version_dict, 'python%(major)d' % version_dict, 'python', ]] for path in paths: if os.path.isfile(path): break else: path = None # the executable path must exist assert path, '\n- '.join(['Could not find interpreter. Attempted:'] + paths) v1 = subprocess.check_output([python, '--version']) v2 = subprocess.check_output([path, '--version']) assert v1 == v2, 'Expected versions to match (%s != %s).' % (v1, v2) return path
python
def real_python3(python, version_dict): """ Determine the path of the real python executable, which is then used for venv creation. This is necessary, because an active virtualenv environment will cause venv creation to malfunction. By getting the path of the real executable, this issue is bypassed. The provided `python` path may be either: - A real python executable - A virtual python executable (with venv) - A virtual python executable (with virtualenv) If the virtual environment was created with virtualenv, the `sys` module will have a `real_prefix` attribute, which points to the directory where the real python files are installed. If `real_prefix` is not present, the environment was not created with virtualenv, and the python executable is safe to use. The `version_dict` is used for attempting to derive the real executable path. This is necessary when the name of the virtual python executable does not exist in the Python installation's directory. For example, if the `basepython` is explicitly set to `python`, tox will use this name instead of attempting `pythonX.Y`. In many cases, Python 3 installations do not contain an executable named `python`, so we attempt to derive this from the version info. e.g., `python3.6.5`, `python3.6`, then `python3`. """ args = [python, '-c', 'import sys; print(sys.real_prefix)'] # get python prefix try: output = subprocess.check_output(args, stderr=subprocess.STDOUT) prefix = output.decode('UTF-8').strip() except subprocess.CalledProcessError: # process fails, implies *not* in active virtualenv return python # determine absolute binary path if os.name == 'nt': # pragma: no cover paths = [os.path.join(prefix, os.path.basename(python))] else: paths = [os.path.join(prefix, 'bin', python) for python in [ os.path.basename(python), 'python%(major)d.%(minor)d.%(micro)d' % version_dict, 'python%(major)d.%(minor)d' % version_dict, 'python%(major)d' % version_dict, 'python', ]] for path in paths: if os.path.isfile(path): break else: path = None # the executable path must exist assert path, '\n- '.join(['Could not find interpreter. Attempted:'] + paths) v1 = subprocess.check_output([python, '--version']) v2 = subprocess.check_output([path, '--version']) assert v1 == v2, 'Expected versions to match (%s != %s).' % (v1, v2) return path
[ "def", "real_python3", "(", "python", ",", "version_dict", ")", ":", "args", "=", "[", "python", ",", "'-c'", ",", "'import sys; print(sys.real_prefix)'", "]", "# get python prefix", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "args", ",",...
Determine the path of the real python executable, which is then used for venv creation. This is necessary, because an active virtualenv environment will cause venv creation to malfunction. By getting the path of the real executable, this issue is bypassed. The provided `python` path may be either: - A real python executable - A virtual python executable (with venv) - A virtual python executable (with virtualenv) If the virtual environment was created with virtualenv, the `sys` module will have a `real_prefix` attribute, which points to the directory where the real python files are installed. If `real_prefix` is not present, the environment was not created with virtualenv, and the python executable is safe to use. The `version_dict` is used for attempting to derive the real executable path. This is necessary when the name of the virtual python executable does not exist in the Python installation's directory. For example, if the `basepython` is explicitly set to `python`, tox will use this name instead of attempting `pythonX.Y`. In many cases, Python 3 installations do not contain an executable named `python`, so we attempt to derive this from the version info. e.g., `python3.6.5`, `python3.6`, then `python3`.
[ "Determine", "the", "path", "of", "the", "real", "python", "executable", "which", "is", "then", "used", "for", "venv", "creation", ".", "This", "is", "necessary", "because", "an", "active", "virtualenv", "environment", "will", "cause", "venv", "creation", "to"...
e740a96c81e076d850065e6a8444ae1cd833468b
https://github.com/tox-dev/tox-venv/blob/e740a96c81e076d850065e6a8444ae1cd833468b/src/tox_venv/hooks.py#L8-L69
train
30,046
shinux/PyTime
pytime/pytime.py
today
def today(year=None): """this day, last year""" return datetime.date(int(year), _date.month, _date.day) if year else _date
python
def today(year=None): """this day, last year""" return datetime.date(int(year), _date.month, _date.day) if year else _date
[ "def", "today", "(", "year", "=", "None", ")", ":", "return", "datetime", ".", "date", "(", "int", "(", "year", ")", ",", "_date", ".", "month", ",", "_date", ".", "day", ")", "if", "year", "else", "_date" ]
this day, last year
[ "this", "day", "last", "year" ]
f2b9f877507e2a1dddf5dd255fdff243a5dbed48
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/pytime.py#L50-L52
train
30,047
shinux/PyTime
pytime/pytime.py
tomorrow
def tomorrow(date=None): """tomorrow is another day""" if not date: return _date + datetime.timedelta(days=1) else: current_date = parse(date) return current_date + datetime.timedelta(days=1)
python
def tomorrow(date=None): """tomorrow is another day""" if not date: return _date + datetime.timedelta(days=1) else: current_date = parse(date) return current_date + datetime.timedelta(days=1)
[ "def", "tomorrow", "(", "date", "=", "None", ")", ":", "if", "not", "date", ":", "return", "_date", "+", "datetime", ".", "timedelta", "(", "days", "=", "1", ")", "else", ":", "current_date", "=", "parse", "(", "date", ")", "return", "current_date", ...
tomorrow is another day
[ "tomorrow", "is", "another", "day" ]
f2b9f877507e2a1dddf5dd255fdff243a5dbed48
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/pytime.py#L55-L61
train
30,048
shinux/PyTime
pytime/pytime.py
yesterday
def yesterday(date=None): """yesterday once more""" if not date: return _date - datetime.timedelta(days=1) else: current_date = parse(date) return current_date - datetime.timedelta(days=1)
python
def yesterday(date=None): """yesterday once more""" if not date: return _date - datetime.timedelta(days=1) else: current_date = parse(date) return current_date - datetime.timedelta(days=1)
[ "def", "yesterday", "(", "date", "=", "None", ")", ":", "if", "not", "date", ":", "return", "_date", "-", "datetime", ".", "timedelta", "(", "days", "=", "1", ")", "else", ":", "current_date", "=", "parse", "(", "date", ")", "return", "current_date", ...
yesterday once more
[ "yesterday", "once", "more" ]
f2b9f877507e2a1dddf5dd255fdff243a5dbed48
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/pytime.py#L64-L70
train
30,049
shinux/PyTime
pytime/pytime.py
days_range
def days_range(first=None, second=None, wipe=False): """ get all days between first and second :param first: datetime, date or string :param second: datetime, date or string :param wipe: boolean, excludes first and last date from range when True. Default is False. :return: list """ _first, _second = parse(first), parse(second) (_start, _end) = (_second, _first) if _first > _second else (_first, _second) days_between = (_end - _start).days date_list = [_end - datetime.timedelta(days=x) for x in range(0, days_between + 1)] if wipe and len(date_list) >= 2: date_list = date_list[1:-1] return date_list
python
def days_range(first=None, second=None, wipe=False): """ get all days between first and second :param first: datetime, date or string :param second: datetime, date or string :param wipe: boolean, excludes first and last date from range when True. Default is False. :return: list """ _first, _second = parse(first), parse(second) (_start, _end) = (_second, _first) if _first > _second else (_first, _second) days_between = (_end - _start).days date_list = [_end - datetime.timedelta(days=x) for x in range(0, days_between + 1)] if wipe and len(date_list) >= 2: date_list = date_list[1:-1] return date_list
[ "def", "days_range", "(", "first", "=", "None", ",", "second", "=", "None", ",", "wipe", "=", "False", ")", ":", "_first", ",", "_second", "=", "parse", "(", "first", ")", ",", "parse", "(", "second", ")", "(", "_start", ",", "_end", ")", "=", "(...
get all days between first and second :param first: datetime, date or string :param second: datetime, date or string :param wipe: boolean, excludes first and last date from range when True. Default is False. :return: list
[ "get", "all", "days", "between", "first", "and", "second" ]
f2b9f877507e2a1dddf5dd255fdff243a5dbed48
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/pytime.py#L78-L93
train
30,050
squaresLab/BugZoo
bugzoo/client/bug.py
BugManager.is_installed
def is_installed(self, bug: Bug) -> bool: """ Determines whether the Docker image for a given bug has been installed on the server. """ r = self.__api.get('bugs/{}/installed'.format(bug.name)) if r.status_code == 200: answer = r.json() assert isinstance(answer, bool) return answer # TODO bug not registered on server if r.status_code == 404: raise KeyError("no bug found with given name: {}".format(bug.name)) self.__api.handle_erroneous_response(r)
python
def is_installed(self, bug: Bug) -> bool: """ Determines whether the Docker image for a given bug has been installed on the server. """ r = self.__api.get('bugs/{}/installed'.format(bug.name)) if r.status_code == 200: answer = r.json() assert isinstance(answer, bool) return answer # TODO bug not registered on server if r.status_code == 404: raise KeyError("no bug found with given name: {}".format(bug.name)) self.__api.handle_erroneous_response(r)
[ "def", "is_installed", "(", "self", ",", "bug", ":", "Bug", ")", "->", "bool", ":", "r", "=", "self", ".", "__api", ".", "get", "(", "'bugs/{}/installed'", ".", "format", "(", "bug", ".", "name", ")", ")", "if", "r", ".", "status_code", "==", "200"...
Determines whether the Docker image for a given bug has been installed on the server.
[ "Determines", "whether", "the", "Docker", "image", "for", "a", "given", "bug", "has", "been", "installed", "on", "the", "server", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/bug.py#L82-L98
train
30,051
squaresLab/BugZoo
bugzoo/client/bug.py
BugManager.uninstall
def uninstall(self, bug: Bug) -> bool: """ Uninstalls the Docker image associated with a given bug. """ r = self.__api.post('bugs/{}/uninstall'.format(bug.name)) raise NotImplementedError
python
def uninstall(self, bug: Bug) -> bool: """ Uninstalls the Docker image associated with a given bug. """ r = self.__api.post('bugs/{}/uninstall'.format(bug.name)) raise NotImplementedError
[ "def", "uninstall", "(", "self", ",", "bug", ":", "Bug", ")", "->", "bool", ":", "r", "=", "self", ".", "__api", ".", "post", "(", "'bugs/{}/uninstall'", ".", "format", "(", "bug", ".", "name", ")", ")", "raise", "NotImplementedError" ]
Uninstalls the Docker image associated with a given bug.
[ "Uninstalls", "the", "Docker", "image", "associated", "with", "a", "given", "bug", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/bug.py#L130-L135
train
30,052
squaresLab/BugZoo
bugzoo/client/bug.py
BugManager.build
def build(self, bug: Bug): """ Instructs the server to build the Docker image associated with a given bug. """ r = self.__api.post('bugs/{}/build'.format(bug.name)) if r.status_code == 204: return if r.status_code == 200: raise Exception("bug already built: {}".format(bug.name)) # TODO: implement ImageBuildFailed.from_dict if r.status_code == 400: raise Exception("build failure") if r.status_code == 404: raise KeyError("no bug found with given name: {}".format(bug.name)) self.__api.handle_erroneous_response(r)
python
def build(self, bug: Bug): """ Instructs the server to build the Docker image associated with a given bug. """ r = self.__api.post('bugs/{}/build'.format(bug.name)) if r.status_code == 204: return if r.status_code == 200: raise Exception("bug already built: {}".format(bug.name)) # TODO: implement ImageBuildFailed.from_dict if r.status_code == 400: raise Exception("build failure") if r.status_code == 404: raise KeyError("no bug found with given name: {}".format(bug.name)) self.__api.handle_erroneous_response(r)
[ "def", "build", "(", "self", ",", "bug", ":", "Bug", ")", ":", "r", "=", "self", ".", "__api", ".", "post", "(", "'bugs/{}/build'", ".", "format", "(", "bug", ".", "name", ")", ")", "if", "r", ".", "status_code", "==", "204", ":", "return", "if",...
Instructs the server to build the Docker image associated with a given bug.
[ "Instructs", "the", "server", "to", "build", "the", "Docker", "image", "associated", "with", "a", "given", "bug", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/bug.py#L153-L170
train
30,053
squaresLab/BugZoo
bugzoo/mgr/source.py
SourceManager.refresh
def refresh(self) -> None: """ Reloads all sources that are registered with this server. """ logger.info('refreshing sources') for source in list(self): self.unload(source) if not os.path.exists(self.__registry_fn): return # TODO add version with open(self.__registry_fn, 'r') as f: registry = yaml.load(f) assert isinstance(registry, list) for source_description in registry: source = Source.from_dict(source_description) self.load(source) logger.info('refreshed sources')
python
def refresh(self) -> None: """ Reloads all sources that are registered with this server. """ logger.info('refreshing sources') for source in list(self): self.unload(source) if not os.path.exists(self.__registry_fn): return # TODO add version with open(self.__registry_fn, 'r') as f: registry = yaml.load(f) assert isinstance(registry, list) for source_description in registry: source = Source.from_dict(source_description) self.load(source) logger.info('refreshed sources')
[ "def", "refresh", "(", "self", ")", "->", "None", ":", "logger", ".", "info", "(", "'refreshing sources'", ")", "for", "source", "in", "list", "(", "self", ")", ":", "self", ".", "unload", "(", "source", ")", "if", "not", "os", ".", "path", ".", "e...
Reloads all sources that are registered with this server.
[ "Reloads", "all", "sources", "that", "are", "registered", "with", "this", "server", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/source.py#L70-L90
train
30,054
squaresLab/BugZoo
bugzoo/mgr/source.py
SourceManager.update
def update(self) -> None: """ Ensures that all remote sources are up-to-date. """ for source_old in self: if isinstance(source_old, RemoteSource): repo = git.Repo(source_old.location) origin = repo.remotes.origin origin.pull() sha = repo.head.object.hexsha version = repo.git.rev_parse(sha, short=8) if version != source_old.version: source_new = RemoteSource(source_old.name, source_old.location, source_old.url, version) logger.info("updated source: %s [%s -> %s]", source_old.name, source_old.version, source_new.version) self.load(source_new) else: logger.debug("no updates for source: %s", source_old.name) # write to disk # TODO local directory may be corrupted if program terminates between # repo being updated and registry being saved; could add a "fix" # command to recalculate versions for remote sources self.save()
python
def update(self) -> None: """ Ensures that all remote sources are up-to-date. """ for source_old in self: if isinstance(source_old, RemoteSource): repo = git.Repo(source_old.location) origin = repo.remotes.origin origin.pull() sha = repo.head.object.hexsha version = repo.git.rev_parse(sha, short=8) if version != source_old.version: source_new = RemoteSource(source_old.name, source_old.location, source_old.url, version) logger.info("updated source: %s [%s -> %s]", source_old.name, source_old.version, source_new.version) self.load(source_new) else: logger.debug("no updates for source: %s", source_old.name) # write to disk # TODO local directory may be corrupted if program terminates between # repo being updated and registry being saved; could add a "fix" # command to recalculate versions for remote sources self.save()
[ "def", "update", "(", "self", ")", "->", "None", ":", "for", "source_old", "in", "self", ":", "if", "isinstance", "(", "source_old", ",", "RemoteSource", ")", ":", "repo", "=", "git", ".", "Repo", "(", "source_old", ".", "location", ")", "origin", "=",...
Ensures that all remote sources are up-to-date.
[ "Ensures", "that", "all", "remote", "sources", "are", "up", "-", "to", "-", "date", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/source.py#L92-L122
train
30,055
squaresLab/BugZoo
bugzoo/mgr/source.py
SourceManager.save
def save(self) -> None: """ Saves the contents of the source manager to disk. """ logger.info('saving registry to: %s', self.__registry_fn) d = [s.to_dict() for s in self] os.makedirs(self.__path, exist_ok=True) with open(self.__registry_fn, 'w') as f: yaml.dump(d, f, indent=2, default_flow_style=False) logger.info('saved registry to: %s', self.__registry_fn)
python
def save(self) -> None: """ Saves the contents of the source manager to disk. """ logger.info('saving registry to: %s', self.__registry_fn) d = [s.to_dict() for s in self] os.makedirs(self.__path, exist_ok=True) with open(self.__registry_fn, 'w') as f: yaml.dump(d, f, indent=2, default_flow_style=False) logger.info('saved registry to: %s', self.__registry_fn)
[ "def", "save", "(", "self", ")", "->", "None", ":", "logger", ".", "info", "(", "'saving registry to: %s'", ",", "self", ".", "__registry_fn", ")", "d", "=", "[", "s", ".", "to_dict", "(", ")", "for", "s", "in", "self", "]", "os", ".", "makedirs", ...
Saves the contents of the source manager to disk.
[ "Saves", "the", "contents", "of", "the", "source", "manager", "to", "disk", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/source.py#L124-L134
train
30,056
squaresLab/BugZoo
bugzoo/mgr/source.py
SourceManager.unload
def unload(self, source: Source) -> None: """ Unloads a registered source, causing all of its associated bugs, tools, and blueprints to also be unloaded. If the given source is not loaded, this function will do nothing. """ logger.info('unloading source: %s', source.name) try: contents = self.contents(source) del self.__contents[source.name] del self.__sources[source.name] for name in contents.bugs: bug = self.__installation.bugs[name] self.__installation.bugs.remove(bug) for name in contents.blueprints: blueprint = self.__installation.build[name] self.__installation.build.remove(blueprint) for name in contents.tools: tool = self.__installation.tools[name] self.__installation.tools.remove(tool) except KeyError: pass logger.info('unloaded source: %s', source.name)
python
def unload(self, source: Source) -> None: """ Unloads a registered source, causing all of its associated bugs, tools, and blueprints to also be unloaded. If the given source is not loaded, this function will do nothing. """ logger.info('unloading source: %s', source.name) try: contents = self.contents(source) del self.__contents[source.name] del self.__sources[source.name] for name in contents.bugs: bug = self.__installation.bugs[name] self.__installation.bugs.remove(bug) for name in contents.blueprints: blueprint = self.__installation.build[name] self.__installation.build.remove(blueprint) for name in contents.tools: tool = self.__installation.tools[name] self.__installation.tools.remove(tool) except KeyError: pass logger.info('unloaded source: %s', source.name)
[ "def", "unload", "(", "self", ",", "source", ":", "Source", ")", "->", "None", ":", "logger", ".", "info", "(", "'unloading source: %s'", ",", "source", ".", "name", ")", "try", ":", "contents", "=", "self", ".", "contents", "(", "source", ")", "del", ...
Unloads a registered source, causing all of its associated bugs, tools, and blueprints to also be unloaded. If the given source is not loaded, this function will do nothing.
[ "Unloads", "a", "registered", "source", "causing", "all", "of", "its", "associated", "bugs", "tools", "and", "blueprints", "to", "also", "be", "unloaded", ".", "If", "the", "given", "source", "is", "not", "loaded", "this", "function", "will", "do", "nothing"...
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/source.py#L136-L159
train
30,057
squaresLab/BugZoo
bugzoo/mgr/source.py
SourceManager.add
def add(self, name: str, path_or_url: str) -> Source: """ Attempts to register a source provided by a given URL or local path under a given name. Returns: a description of the registered source. Raises: NameInUseError: if an existing source is already registered under the given name. IOError: if no directory exists at the given path. IOError: if downloading the remote source failed. (FIXME) """ logger.info("adding source: %s -> %s", name, path_or_url) if name in self.__sources: logger.info("name already used by existing source: %s", name) raise NameInUseError(name) is_url = False try: scheme = urllib.parse.urlparse(path_or_url).scheme is_url = scheme in ['http', 'https'] logger.debug("source determined to be remote: %s", path_or_url) except ValueError: logger.debug("source determined to be local: %s", path_or_url) if is_url: url = path_or_url # convert url to a local path path = url.replace('https://', '') path = path.replace('/', '_') path = path.replace('.', '_') path = os.path.join(self.__path, path) # download from remote to local shutil.rmtree(path, ignore_errors=True) try: # TODO shallow clone logger.debug("cloning repository %s to %s", url, path) repo = git.Repo.clone_from(url, path) logger.debug("cloned repository %s to %s", url, path) sha = repo.head.object.hexsha version = repo.git.rev_parse(sha, short=8) except: # TODO determine error type shutil.rmtree(path, ignore_errors=True) logger.error("failed to download remote source to local: %s -> %s", url, path) raise IOError("failed to download remote source to local installation: '{}' -> '{}'".format(url, path)) source = RemoteSource(name, path, url, version) else: path = os.path.abspath(path_or_url) if not os.path.isdir(path): raise IOError("no directory found at path: {}".format(path)) source = LocalSource(name, path) self.load(source) self.save() logger.info('added source: %s', name)
python
def add(self, name: str, path_or_url: str) -> Source: """ Attempts to register a source provided by a given URL or local path under a given name. Returns: a description of the registered source. Raises: NameInUseError: if an existing source is already registered under the given name. IOError: if no directory exists at the given path. IOError: if downloading the remote source failed. (FIXME) """ logger.info("adding source: %s -> %s", name, path_or_url) if name in self.__sources: logger.info("name already used by existing source: %s", name) raise NameInUseError(name) is_url = False try: scheme = urllib.parse.urlparse(path_or_url).scheme is_url = scheme in ['http', 'https'] logger.debug("source determined to be remote: %s", path_or_url) except ValueError: logger.debug("source determined to be local: %s", path_or_url) if is_url: url = path_or_url # convert url to a local path path = url.replace('https://', '') path = path.replace('/', '_') path = path.replace('.', '_') path = os.path.join(self.__path, path) # download from remote to local shutil.rmtree(path, ignore_errors=True) try: # TODO shallow clone logger.debug("cloning repository %s to %s", url, path) repo = git.Repo.clone_from(url, path) logger.debug("cloned repository %s to %s", url, path) sha = repo.head.object.hexsha version = repo.git.rev_parse(sha, short=8) except: # TODO determine error type shutil.rmtree(path, ignore_errors=True) logger.error("failed to download remote source to local: %s -> %s", url, path) raise IOError("failed to download remote source to local installation: '{}' -> '{}'".format(url, path)) source = RemoteSource(name, path, url, version) else: path = os.path.abspath(path_or_url) if not os.path.isdir(path): raise IOError("no directory found at path: {}".format(path)) source = LocalSource(name, path) self.load(source) self.save() logger.info('added source: %s', name)
[ "def", "add", "(", "self", ",", "name", ":", "str", ",", "path_or_url", ":", "str", ")", "->", "Source", ":", "logger", ".", "info", "(", "\"adding source: %s -> %s\"", ",", "name", ",", "path_or_url", ")", "if", "name", "in", "self", ".", "__sources", ...
Attempts to register a source provided by a given URL or local path under a given name. Returns: a description of the registered source. Raises: NameInUseError: if an existing source is already registered under the given name. IOError: if no directory exists at the given path. IOError: if downloading the remote source failed. (FIXME)
[ "Attempts", "to", "register", "a", "source", "provided", "by", "a", "given", "URL", "or", "local", "path", "under", "a", "given", "name", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/source.py#L274-L334
train
30,058
squaresLab/BugZoo
bugzoo/mgr/source.py
SourceManager.remove
def remove(self, source: Source) -> None: """ Unregisters a given source with this server. If the given source is a remote source, then its local copy will be removed from disk. Raises: KeyError: if the given source is not registered with this server. """ self.unload(source) if isinstance(source, RemoteSource): shutil.rmtree(source.location, ignore_errors=True) self.save()
python
def remove(self, source: Source) -> None: """ Unregisters a given source with this server. If the given source is a remote source, then its local copy will be removed from disk. Raises: KeyError: if the given source is not registered with this server. """ self.unload(source) if isinstance(source, RemoteSource): shutil.rmtree(source.location, ignore_errors=True) self.save()
[ "def", "remove", "(", "self", ",", "source", ":", "Source", ")", "->", "None", ":", "self", ".", "unload", "(", "source", ")", "if", "isinstance", "(", "source", ",", "RemoteSource", ")", ":", "shutil", ".", "rmtree", "(", "source", ".", "location", ...
Unregisters a given source with this server. If the given source is a remote source, then its local copy will be removed from disk. Raises: KeyError: if the given source is not registered with this server.
[ "Unregisters", "a", "given", "source", "with", "this", "server", ".", "If", "the", "given", "source", "is", "a", "remote", "source", "then", "its", "local", "copy", "will", "be", "removed", "from", "disk", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/source.py#L336-L347
train
30,059
squaresLab/BugZoo
bugzoo/mgr/bug.py
BugManager.is_installed
def is_installed(self, bug: Bug) -> bool: """ Determines whether or not the Docker image for a given bug has been installed onto this server. See: `BuildManager.is_installed` """ return self.__installation.build.is_installed(bug.image)
python
def is_installed(self, bug: Bug) -> bool: """ Determines whether or not the Docker image for a given bug has been installed onto this server. See: `BuildManager.is_installed` """ return self.__installation.build.is_installed(bug.image)
[ "def", "is_installed", "(", "self", ",", "bug", ":", "Bug", ")", "->", "bool", ":", "return", "self", ".", "__installation", ".", "build", ".", "is_installed", "(", "bug", ".", "image", ")" ]
Determines whether or not the Docker image for a given bug has been installed onto this server. See: `BuildManager.is_installed`
[ "Determines", "whether", "or", "not", "the", "Docker", "image", "for", "a", "given", "bug", "has", "been", "installed", "onto", "this", "server", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/bug.py#L73-L80
train
30,060
squaresLab/BugZoo
bugzoo/mgr/bug.py
BugManager.build
def build(self, bug: Bug, force: bool = True, quiet: bool = False ) -> None: """ Builds the Docker image associated with a given bug. See: `BuildManager.build` """ self.__installation.build.build(bug.image, force=force, quiet=quiet)
python
def build(self, bug: Bug, force: bool = True, quiet: bool = False ) -> None: """ Builds the Docker image associated with a given bug. See: `BuildManager.build` """ self.__installation.build.build(bug.image, force=force, quiet=quiet)
[ "def", "build", "(", "self", ",", "bug", ":", "Bug", ",", "force", ":", "bool", "=", "True", ",", "quiet", ":", "bool", "=", "False", ")", "->", "None", ":", "self", ".", "__installation", ".", "build", ".", "build", "(", "bug", ".", "image", ","...
Builds the Docker image associated with a given bug. See: `BuildManager.build`
[ "Builds", "the", "Docker", "image", "associated", "with", "a", "given", "bug", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/bug.py#L82-L94
train
30,061
squaresLab/BugZoo
bugzoo/mgr/bug.py
BugManager.uninstall
def uninstall(self, bug: Bug, force: bool = False, noprune: bool = False ) -> None: """ Uninstalls all Docker images associated with this bug. See: `BuildManager.uninstall` """ self.__installation.build.uninstall(bug.image, force=force, noprune=noprune)
python
def uninstall(self, bug: Bug, force: bool = False, noprune: bool = False ) -> None: """ Uninstalls all Docker images associated with this bug. See: `BuildManager.uninstall` """ self.__installation.build.uninstall(bug.image, force=force, noprune=noprune)
[ "def", "uninstall", "(", "self", ",", "bug", ":", "Bug", ",", "force", ":", "bool", "=", "False", ",", "noprune", ":", "bool", "=", "False", ")", "->", "None", ":", "self", ".", "__installation", ".", "build", ".", "uninstall", "(", "bug", ".", "im...
Uninstalls all Docker images associated with this bug. See: `BuildManager.uninstall`
[ "Uninstalls", "all", "Docker", "images", "associated", "with", "this", "bug", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/bug.py#L96-L108
train
30,062
squaresLab/BugZoo
bugzoo/mgr/bug.py
BugManager.validate
def validate(self, bug: Bug, verbose: bool = True) -> bool: """ Checks that a given bug successfully builds, and that it produces an expected set of test suite outcomes. Parameters: verbose: toggles verbosity of output. If set to `True`, the outcomes of each test will be printed to the standard output. Returns: `True` if bug behaves as expected, else `False`. """ # attempt to rebuild -- don't worry, Docker's layer caching prevents us # from actually having to rebuild everything from scratch :-) try: self.build(bug, force=True, quiet=True) except docker.errors.BuildError: print("failed to build bug: {}".format(self.identifier)) return False # provision a container validated = True try: c = None c = self.__installation.containers.provision(bug) # ensure we can compile the bug # TODO: check compilation status! print_task_start('Compiling') self.__installation.containers.compile(c) print_task_end('Compiling', 'OK') for t in bug.tests: if t.expected_outcome is True: task = 'Running test: {}'.format(t.name) print_task_start(task) outcome = \ self.__installation.containers.execute(c, t, verbose=verbose) if not outcome.passed: validated = False print_task_end(task, 'UNEXPECTED: FAIL') response = textwrap.indent(outcome.response.output, ' ' * 4) print('\n' + response) else: print_task_end(task, 'OK') if t.expected_outcome is False: task = 'Running test: {}'.format(t.name) print_task_start(task) outcome = \ self.__installation.containers.execute(c, t, verbose=verbose) if outcome.passed: validated = False print_task_end(task, 'UNEXPECTED: PASS') response = textwrap.indent(outcome.response.output, ' ' * 4) print('\n' + response) else: print_task_end(task, 'OK') # ensure that the container is destroyed! finally: if c: del self.__installation.containers[c.uid] return validated
python
def validate(self, bug: Bug, verbose: bool = True) -> bool: """ Checks that a given bug successfully builds, and that it produces an expected set of test suite outcomes. Parameters: verbose: toggles verbosity of output. If set to `True`, the outcomes of each test will be printed to the standard output. Returns: `True` if bug behaves as expected, else `False`. """ # attempt to rebuild -- don't worry, Docker's layer caching prevents us # from actually having to rebuild everything from scratch :-) try: self.build(bug, force=True, quiet=True) except docker.errors.BuildError: print("failed to build bug: {}".format(self.identifier)) return False # provision a container validated = True try: c = None c = self.__installation.containers.provision(bug) # ensure we can compile the bug # TODO: check compilation status! print_task_start('Compiling') self.__installation.containers.compile(c) print_task_end('Compiling', 'OK') for t in bug.tests: if t.expected_outcome is True: task = 'Running test: {}'.format(t.name) print_task_start(task) outcome = \ self.__installation.containers.execute(c, t, verbose=verbose) if not outcome.passed: validated = False print_task_end(task, 'UNEXPECTED: FAIL') response = textwrap.indent(outcome.response.output, ' ' * 4) print('\n' + response) else: print_task_end(task, 'OK') if t.expected_outcome is False: task = 'Running test: {}'.format(t.name) print_task_start(task) outcome = \ self.__installation.containers.execute(c, t, verbose=verbose) if outcome.passed: validated = False print_task_end(task, 'UNEXPECTED: PASS') response = textwrap.indent(outcome.response.output, ' ' * 4) print('\n' + response) else: print_task_end(task, 'OK') # ensure that the container is destroyed! finally: if c: del self.__installation.containers[c.uid] return validated
[ "def", "validate", "(", "self", ",", "bug", ":", "Bug", ",", "verbose", ":", "bool", "=", "True", ")", "->", "bool", ":", "# attempt to rebuild -- don't worry, Docker's layer caching prevents us", "# from actually having to rebuild everything from scratch :-)", "try", ":", ...
Checks that a given bug successfully builds, and that it produces an expected set of test suite outcomes. Parameters: verbose: toggles verbosity of output. If set to `True`, the outcomes of each test will be printed to the standard output. Returns: `True` if bug behaves as expected, else `False`.
[ "Checks", "that", "a", "given", "bug", "successfully", "builds", "and", "that", "it", "produces", "an", "expected", "set", "of", "test", "suite", "outcomes", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/bug.py#L129-L199
train
30,063
squaresLab/BugZoo
bugzoo/mgr/bug.py
BugManager.coverage
def coverage(self, bug: Bug) -> TestSuiteCoverage: """ Provides coverage information for each test within the test suite for the program associated with this bug. Parameters: bug: the bug for which to compute coverage. Returns: a test suite coverage report for the given bug. """ # determine the location of the coverage map on disk fn = os.path.join(self.__installation.coverage_path, "{}.coverage.yml".format(bug.name)) # is the coverage already cached? if so, load. if os.path.exists(fn): return TestSuiteCoverage.from_file(fn) # if we don't have coverage information, compute it mgr_ctr = self.__installation.containers container = None try: container = mgr_ctr.provision(bug) coverage = mgr_ctr.coverage(container) # save to disk with open(fn, 'w') as f: yaml.dump(coverage.to_dict(), f, default_flow_style=False) finally: if container: del mgr_ctr[container.id] return coverage
python
def coverage(self, bug: Bug) -> TestSuiteCoverage: """ Provides coverage information for each test within the test suite for the program associated with this bug. Parameters: bug: the bug for which to compute coverage. Returns: a test suite coverage report for the given bug. """ # determine the location of the coverage map on disk fn = os.path.join(self.__installation.coverage_path, "{}.coverage.yml".format(bug.name)) # is the coverage already cached? if so, load. if os.path.exists(fn): return TestSuiteCoverage.from_file(fn) # if we don't have coverage information, compute it mgr_ctr = self.__installation.containers container = None try: container = mgr_ctr.provision(bug) coverage = mgr_ctr.coverage(container) # save to disk with open(fn, 'w') as f: yaml.dump(coverage.to_dict(), f, default_flow_style=False) finally: if container: del mgr_ctr[container.id] return coverage
[ "def", "coverage", "(", "self", ",", "bug", ":", "Bug", ")", "->", "TestSuiteCoverage", ":", "# determine the location of the coverage map on disk", "fn", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__installation", ".", "coverage_path", ",", "\"{}.c...
Provides coverage information for each test within the test suite for the program associated with this bug. Parameters: bug: the bug for which to compute coverage. Returns: a test suite coverage report for the given bug.
[ "Provides", "coverage", "information", "for", "each", "test", "within", "the", "test", "suite", "for", "the", "program", "associated", "with", "this", "bug", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/bug.py#L201-L234
train
30,064
squaresLab/BugZoo
bugzoo/mgr/container.py
ContainerManager.clear
def clear(self) -> None: """ Closes all running containers. """ logger.debug("clearing all running containers") all_uids = [uid for uid in self.__containers.keys()] for uid in all_uids: try: del self[uid] except KeyError: # Already deleted pass logger.debug("cleared all running containers")
python
def clear(self) -> None: """ Closes all running containers. """ logger.debug("clearing all running containers") all_uids = [uid for uid in self.__containers.keys()] for uid in all_uids: try: del self[uid] except KeyError: # Already deleted pass logger.debug("cleared all running containers")
[ "def", "clear", "(", "self", ")", "->", "None", ":", "logger", ".", "debug", "(", "\"clearing all running containers\"", ")", "all_uids", "=", "[", "uid", "for", "uid", "in", "self", ".", "__containers", ".", "keys", "(", ")", "]", "for", "uid", "in", ...
Closes all running containers.
[ "Closes", "all", "running", "containers", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/container.py#L51-L63
train
30,065
squaresLab/BugZoo
bugzoo/mgr/container.py
ContainerManager.bug
def bug(self, container: Container) -> Bug: """ Returns a description of the bug inside a given container. """ name = container.bug return self.__installation.bugs[name]
python
def bug(self, container: Container) -> Bug: """ Returns a description of the bug inside a given container. """ name = container.bug return self.__installation.bugs[name]
[ "def", "bug", "(", "self", ",", "container", ":", "Container", ")", "->", "Bug", ":", "name", "=", "container", ".", "bug", "return", "self", ".", "__installation", ".", "bugs", "[", "name", "]" ]
Returns a description of the bug inside a given container.
[ "Returns", "a", "description", "of", "the", "bug", "inside", "a", "given", "container", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/container.py#L113-L118
train
30,066
squaresLab/BugZoo
bugzoo/mgr/container.py
ContainerManager.mktemp
def mktemp(self, container: Container) -> str: """ Creates a named temporary file within a given container. Returns: the absolute path to the created temporary file. """ logger.debug("creating a temporary file inside container %s", container.uid) response = self.command(container, "mktemp") if response.code != 0: msg = "failed to create temporary file for container {}: [{}] {}" msg = msg.format(uid, response.code, response.output) logger.error(msg) raise Exception(msg) # FIXME add new exception assert response.code == 0, "failed to create temporary file" fn = response.output.strip() logger.debug("created temporary file inside container %s: %s", container.uid, fn) return fn
python
def mktemp(self, container: Container) -> str: """ Creates a named temporary file within a given container. Returns: the absolute path to the created temporary file. """ logger.debug("creating a temporary file inside container %s", container.uid) response = self.command(container, "mktemp") if response.code != 0: msg = "failed to create temporary file for container {}: [{}] {}" msg = msg.format(uid, response.code, response.output) logger.error(msg) raise Exception(msg) # FIXME add new exception assert response.code == 0, "failed to create temporary file" fn = response.output.strip() logger.debug("created temporary file inside container %s: %s", container.uid, fn) return fn
[ "def", "mktemp", "(", "self", ",", "container", ":", "Container", ")", "->", "str", ":", "logger", ".", "debug", "(", "\"creating a temporary file inside container %s\"", ",", "container", ".", "uid", ")", "response", "=", "self", ".", "command", "(", "contain...
Creates a named temporary file within a given container. Returns: the absolute path to the created temporary file.
[ "Creates", "a", "named", "temporary", "file", "within", "a", "given", "container", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/container.py#L239-L260
train
30,067
squaresLab/BugZoo
bugzoo/mgr/container.py
ContainerManager.is_alive
def is_alive(self, container: Container) -> bool: """ Determines whether a given container is still alive. Returns: `True` if the underlying Docker container for the given BugZoo container is still alive, otherwise `False`. """ uid = container.uid return uid in self.__dockerc and \ self.__dockerc[uid].status == 'running'
python
def is_alive(self, container: Container) -> bool: """ Determines whether a given container is still alive. Returns: `True` if the underlying Docker container for the given BugZoo container is still alive, otherwise `False`. """ uid = container.uid return uid in self.__dockerc and \ self.__dockerc[uid].status == 'running'
[ "def", "is_alive", "(", "self", ",", "container", ":", "Container", ")", "->", "bool", ":", "uid", "=", "container", ".", "uid", "return", "uid", "in", "self", ".", "__dockerc", "and", "self", ".", "__dockerc", "[", "uid", "]", ".", "status", "==", "...
Determines whether a given container is still alive. Returns: `True` if the underlying Docker container for the given BugZoo container is still alive, otherwise `False`.
[ "Determines", "whether", "a", "given", "container", "is", "still", "alive", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/container.py#L262-L272
train
30,068
squaresLab/BugZoo
bugzoo/mgr/container.py
ContainerManager.coverage_extractor
def coverage_extractor(self, container: Container) -> CoverageExtractor: """ Retrieves the coverage extractor for a given container. """ return CoverageExtractor.build(self.__installation, container)
python
def coverage_extractor(self, container: Container) -> CoverageExtractor: """ Retrieves the coverage extractor for a given container. """ return CoverageExtractor.build(self.__installation, container)
[ "def", "coverage_extractor", "(", "self", ",", "container", ":", "Container", ")", "->", "CoverageExtractor", ":", "return", "CoverageExtractor", ".", "build", "(", "self", ".", "__installation", ",", "container", ")" ]
Retrieves the coverage extractor for a given container.
[ "Retrieves", "the", "coverage", "extractor", "for", "a", "given", "container", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/container.py#L349-L353
train
30,069
squaresLab/BugZoo
bugzoo/mgr/container.py
ContainerManager.coverage
def coverage(self, container: Container, tests: Optional[Iterable[TestCase]] = None, *, instrument: bool = True ) -> TestSuiteCoverage: """ Computes line coverage information over a provided set of tests for the program inside a given container. """ extractor = self.coverage_extractor(container) if tests is None: bugs = self.__installation.bugs bug = bugs[container.bug] tests = bug.tests return extractor.run(tests, instrument=instrument)
python
def coverage(self, container: Container, tests: Optional[Iterable[TestCase]] = None, *, instrument: bool = True ) -> TestSuiteCoverage: """ Computes line coverage information over a provided set of tests for the program inside a given container. """ extractor = self.coverage_extractor(container) if tests is None: bugs = self.__installation.bugs bug = bugs[container.bug] tests = bug.tests return extractor.run(tests, instrument=instrument)
[ "def", "coverage", "(", "self", ",", "container", ":", "Container", ",", "tests", ":", "Optional", "[", "Iterable", "[", "TestCase", "]", "]", "=", "None", ",", "*", ",", "instrument", ":", "bool", "=", "True", ")", "->", "TestSuiteCoverage", ":", "ext...
Computes line coverage information over a provided set of tests for the program inside a given container.
[ "Computes", "line", "coverage", "information", "over", "a", "provided", "set", "of", "tests", "for", "the", "program", "inside", "a", "given", "container", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/container.py#L364-L379
train
30,070
squaresLab/BugZoo
bugzoo/mgr/container.py
ContainerManager.execute
def execute(self, container: Container, test: TestCase, verbose: bool = False ) -> TestOutcome: """ Runs a specified test inside a given container. Returns: the outcome of the test execution. """ bug = self.__installation.bugs[container.bug] # type: Bug response = self.command(container, cmd=test.command, context=test.context, stderr=True, time_limit=test.time_limit, kill_after=test.kill_after, verbose=verbose) passed = test.oracle.check(response) return TestOutcome(response, passed)
python
def execute(self, container: Container, test: TestCase, verbose: bool = False ) -> TestOutcome: """ Runs a specified test inside a given container. Returns: the outcome of the test execution. """ bug = self.__installation.bugs[container.bug] # type: Bug response = self.command(container, cmd=test.command, context=test.context, stderr=True, time_limit=test.time_limit, kill_after=test.kill_after, verbose=verbose) passed = test.oracle.check(response) return TestOutcome(response, passed)
[ "def", "execute", "(", "self", ",", "container", ":", "Container", ",", "test", ":", "TestCase", ",", "verbose", ":", "bool", "=", "False", ")", "->", "TestOutcome", ":", "bug", "=", "self", ".", "__installation", ".", "bugs", "[", "container", ".", "b...
Runs a specified test inside a given container. Returns: the outcome of the test execution.
[ "Runs", "a", "specified", "test", "inside", "a", "given", "container", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/container.py#L381-L401
train
30,071
squaresLab/BugZoo
bugzoo/mgr/container.py
ContainerManager.compile_with_instrumentation
def compile_with_instrumentation(self, container: Container, verbose: bool = False ) -> CompilationOutcome: """ Attempts to compile the program inside a given container with instrumentation enabled. See: `Container.compile` """ bug = self.__installation.bugs[container.bug] bug.compiler.clean(self, container, verbose=verbose) # TODO port return bug.compiler.compile_with_coverage_instrumentation(self, container, verbose=verbose)
python
def compile_with_instrumentation(self, container: Container, verbose: bool = False ) -> CompilationOutcome: """ Attempts to compile the program inside a given container with instrumentation enabled. See: `Container.compile` """ bug = self.__installation.bugs[container.bug] bug.compiler.clean(self, container, verbose=verbose) # TODO port return bug.compiler.compile_with_coverage_instrumentation(self, container, verbose=verbose)
[ "def", "compile_with_instrumentation", "(", "self", ",", "container", ":", "Container", ",", "verbose", ":", "bool", "=", "False", ")", "->", "CompilationOutcome", ":", "bug", "=", "self", ".", "__installation", ".", "bugs", "[", "container", ".", "bug", "]"...
Attempts to compile the program inside a given container with instrumentation enabled. See: `Container.compile`
[ "Attempts", "to", "compile", "the", "program", "inside", "a", "given", "container", "with", "instrumentation", "enabled", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/container.py#L428-L442
train
30,072
squaresLab/BugZoo
bugzoo/mgr/container.py
ContainerManager.copy_to
def copy_to(self, container: Container, fn_host: str, fn_container: str ) -> None: """ Copies a file from the host machine to a specified location inside a container. Raises: FileNotFound: if the host file wasn't found. subprocess.CalledProcessError: if the file could not be copied to the container. """ logger.debug("Copying file to container, %s: %s -> %s", container.uid, fn_host, fn_container) if not os.path.exists(fn_host): logger.error("Failed to copy file [%s] to [%s] in container [%s]: not found.", # noqa: pycodestyle fn_host, fn_container, container.uid) raise FileNotFound(fn_host) cmd = "docker cp '{}' '{}:{}'".format(fn_host, container.id, fn_container) try: subprocess.check_output(cmd, shell=True) logger.debug("Copied file to container, %s: %s -> %s", container.uid, fn_host, fn_container) r = self.command(container, "sudo chown $(whoami) '{}'".format(fn_container)) if r.code != 0: m = "failed to update permissions for container file [{}] (exit code: {}): {}" # noqa: pycodestyle m = m.format(fn_container, r.code, r.output) raise BugZooException(m) # TODO implement error handling except subprocess.CalledProcessError: logger.exception("Failed to copy file to container, %s: %s -> %s", container.uid, fn_host, fn_container) raise
python
def copy_to(self, container: Container, fn_host: str, fn_container: str ) -> None: """ Copies a file from the host machine to a specified location inside a container. Raises: FileNotFound: if the host file wasn't found. subprocess.CalledProcessError: if the file could not be copied to the container. """ logger.debug("Copying file to container, %s: %s -> %s", container.uid, fn_host, fn_container) if not os.path.exists(fn_host): logger.error("Failed to copy file [%s] to [%s] in container [%s]: not found.", # noqa: pycodestyle fn_host, fn_container, container.uid) raise FileNotFound(fn_host) cmd = "docker cp '{}' '{}:{}'".format(fn_host, container.id, fn_container) try: subprocess.check_output(cmd, shell=True) logger.debug("Copied file to container, %s: %s -> %s", container.uid, fn_host, fn_container) r = self.command(container, "sudo chown $(whoami) '{}'".format(fn_container)) if r.code != 0: m = "failed to update permissions for container file [{}] (exit code: {}): {}" # noqa: pycodestyle m = m.format(fn_container, r.code, r.output) raise BugZooException(m) # TODO implement error handling except subprocess.CalledProcessError: logger.exception("Failed to copy file to container, %s: %s -> %s", container.uid, fn_host, fn_container) raise
[ "def", "copy_to", "(", "self", ",", "container", ":", "Container", ",", "fn_host", ":", "str", ",", "fn_container", ":", "str", ")", "->", "None", ":", "logger", ".", "debug", "(", "\"Copying file to container, %s: %s -> %s\"", ",", "container", ".", "uid", ...
Copies a file from the host machine to a specified location inside a container. Raises: FileNotFound: if the host file wasn't found. subprocess.CalledProcessError: if the file could not be copied to the container.
[ "Copies", "a", "file", "from", "the", "host", "machine", "to", "a", "specified", "location", "inside", "a", "container", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/container.py#L446-L484
train
30,073
squaresLab/BugZoo
bugzoo/mgr/container.py
ContainerManager.copy_from
def copy_from(self, container: Container, fn_container: str, fn_host: str ) -> None: """ Copies a given file from the container to a specified location on the host machine. """ logger.debug("Copying file from container, %s: %s -> %s", container.uid, fn_container, fn_host) cmd = "docker cp '{}:{}' '{}'".format(container.id, fn_container, fn_host) try: subprocess.check_output(cmd, shell=True) logger.debug("Copied file from container, %s: %s -> %s", container.uid, fn_container, fn_host) # TODO implement error handling except subprocess.CalledProcessError: logger.exception("Failed to copy file from container, %s: %s -> %s", # noqa: pycodestyle container.uid, fn_container, fn_host) raise
python
def copy_from(self, container: Container, fn_container: str, fn_host: str ) -> None: """ Copies a given file from the container to a specified location on the host machine. """ logger.debug("Copying file from container, %s: %s -> %s", container.uid, fn_container, fn_host) cmd = "docker cp '{}:{}' '{}'".format(container.id, fn_container, fn_host) try: subprocess.check_output(cmd, shell=True) logger.debug("Copied file from container, %s: %s -> %s", container.uid, fn_container, fn_host) # TODO implement error handling except subprocess.CalledProcessError: logger.exception("Failed to copy file from container, %s: %s -> %s", # noqa: pycodestyle container.uid, fn_container, fn_host) raise
[ "def", "copy_from", "(", "self", ",", "container", ":", "Container", ",", "fn_container", ":", "str", ",", "fn_host", ":", "str", ")", "->", "None", ":", "logger", ".", "debug", "(", "\"Copying file from container, %s: %s -> %s\"", ",", "container", ".", "uid"...
Copies a given file from the container to a specified location on the host machine.
[ "Copies", "a", "given", "file", "from", "the", "container", "to", "a", "specified", "location", "on", "the", "host", "machine", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/container.py#L486-L506
train
30,074
squaresLab/BugZoo
bugzoo/mgr/container.py
ContainerManager.command
def command(self, container: Container, cmd: str, context: Optional[str] = None, stdout: bool = True, stderr: bool = False, block: bool = True, verbose: bool = False, time_limit: Optional[int] = None, kill_after: Optional[int] = 1 ) -> Union[ExecResponse, PendingExecResponse]: """ Executes a provided shell command inside a given container. Parameters: time_limit: an optional parameter that is used to specify the number of seconds that the command should be allowed to run without completing before it is aborted. Only supported by blocking calls. Returns: a description of the response. Raises: TimeoutError: if a time limit is given and the command fails to complete within that time. Only supported by blocking calls. """ cmd_original = cmd logger_c = logger.getChild(container.uid) logger_c.debug('executing command "%s"', cmd) bug = self.__installation.bugs[container.bug] # TODO: we need a better long-term alternative if context is None: context = os.path.join(bug.source_dir, '..') logger_c.debug('using execution context: %s', context) cmd = 'source /.environment && cd {} && {}'.format(context, cmd) cmd_wrapped = "/bin/bash -c '{}'".format(cmd) if time_limit is not None and time_limit > 0: logger_c.debug("running command with time limit: %d seconds", time_limit) # noqa: pycodestyle cmd_template = "timeout --kill-after={} --signal=SIGTERM {} {}" cmd_wrapped = cmd_template.format(kill_after, time_limit, cmd_wrapped) cmd = cmd_wrapped # based on: https://github.com/roidelapluie/docker-py/commit/ead9ffa34193281967de8cc0d6e1c0dcbf50eda5 logger_c.debug("executing raw command: %s", cmd) logger_c.debug('creating exec object for command: %s', cmd) docker_client = self.__installation.docker try: response = docker_client.api.exec_create(container.id, cmd, tty=True, stdout=stdout, stderr=stderr) except docker.errors.APIError: logger_c.exception('failed to create exec object for command: %s', cmd) # noqa: pycodestyle raise logger_c.debug("created exec object for command: %s", cmd) exec_id = response['Id'] time_start = timer() out = self.__api_docker.exec_start(exec_id, stream=True) if not block: return PendingExecResponse(response, out) output = [] for line in out: line = line.decode('utf-8').rstrip('\n') if verbose: print(line, flush=True) output.append(line) time_running = timer() - time_start output = '\n'.join(output) code = self.__api_docker.exec_inspect(exec_id)['ExitCode'] logger_c.debug('finished executing command: %s. (exited with code %d and took %.2f seconds.)\n%s', # noqa: pycodestyle cmd_original, code, time_running, output) return ExecResponse(code, time_running, output)
python
def command(self, container: Container, cmd: str, context: Optional[str] = None, stdout: bool = True, stderr: bool = False, block: bool = True, verbose: bool = False, time_limit: Optional[int] = None, kill_after: Optional[int] = 1 ) -> Union[ExecResponse, PendingExecResponse]: """ Executes a provided shell command inside a given container. Parameters: time_limit: an optional parameter that is used to specify the number of seconds that the command should be allowed to run without completing before it is aborted. Only supported by blocking calls. Returns: a description of the response. Raises: TimeoutError: if a time limit is given and the command fails to complete within that time. Only supported by blocking calls. """ cmd_original = cmd logger_c = logger.getChild(container.uid) logger_c.debug('executing command "%s"', cmd) bug = self.__installation.bugs[container.bug] # TODO: we need a better long-term alternative if context is None: context = os.path.join(bug.source_dir, '..') logger_c.debug('using execution context: %s', context) cmd = 'source /.environment && cd {} && {}'.format(context, cmd) cmd_wrapped = "/bin/bash -c '{}'".format(cmd) if time_limit is not None and time_limit > 0: logger_c.debug("running command with time limit: %d seconds", time_limit) # noqa: pycodestyle cmd_template = "timeout --kill-after={} --signal=SIGTERM {} {}" cmd_wrapped = cmd_template.format(kill_after, time_limit, cmd_wrapped) cmd = cmd_wrapped # based on: https://github.com/roidelapluie/docker-py/commit/ead9ffa34193281967de8cc0d6e1c0dcbf50eda5 logger_c.debug("executing raw command: %s", cmd) logger_c.debug('creating exec object for command: %s', cmd) docker_client = self.__installation.docker try: response = docker_client.api.exec_create(container.id, cmd, tty=True, stdout=stdout, stderr=stderr) except docker.errors.APIError: logger_c.exception('failed to create exec object for command: %s', cmd) # noqa: pycodestyle raise logger_c.debug("created exec object for command: %s", cmd) exec_id = response['Id'] time_start = timer() out = self.__api_docker.exec_start(exec_id, stream=True) if not block: return PendingExecResponse(response, out) output = [] for line in out: line = line.decode('utf-8').rstrip('\n') if verbose: print(line, flush=True) output.append(line) time_running = timer() - time_start output = '\n'.join(output) code = self.__api_docker.exec_inspect(exec_id)['ExitCode'] logger_c.debug('finished executing command: %s. (exited with code %d and took %.2f seconds.)\n%s', # noqa: pycodestyle cmd_original, code, time_running, output) return ExecResponse(code, time_running, output)
[ "def", "command", "(", "self", ",", "container", ":", "Container", ",", "cmd", ":", "str", ",", "context", ":", "Optional", "[", "str", "]", "=", "None", ",", "stdout", ":", "bool", "=", "True", ",", "stderr", ":", "bool", "=", "False", ",", "block...
Executes a provided shell command inside a given container. Parameters: time_limit: an optional parameter that is used to specify the number of seconds that the command should be allowed to run without completing before it is aborted. Only supported by blocking calls. Returns: a description of the response. Raises: TimeoutError: if a time limit is given and the command fails to complete within that time. Only supported by blocking calls.
[ "Executes", "a", "provided", "shell", "command", "inside", "a", "given", "container", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/container.py#L508-L589
train
30,075
squaresLab/BugZoo
bugzoo/mgr/container.py
ContainerManager.persist
def persist(self, container: Container, image: str) -> None: """ Persists the state of a given container to a BugZoo image on this server. Parameters: container: the container to persist. image: the name of the Docker image that should be created. Raises: ImageAlreadyExists: if the image name is already in use by another Docker image on this server. """ logger_c = logger.getChild(container.uid) logger_c.debug("Persisting container as a Docker image: %s", image) try: docker_container = self.__dockerc[container.uid] except KeyError: logger_c.exception("Failed to persist container: container no longer exists.") # noqa: pycodestyle raise try: _ = self.__client_docker.images.get(image) logger_c.error("Failed to persist container: image, '%s', already exists.", # noqa: pycodestyle image) raise ImageAlreadyExists(image) except docker.errors.ImageNotFound: pass cmd = "docker commit {} {}" cmd = cmd.format(docker_container.id, image) try: subprocess.check_output(cmd, shell=True) except subprocess.CalledProcessError: logger.exception("Failed to persist container (%s) to image (%s).", # noqa: pycodestyle container.uid, image) raise logger_c.debug("Persisted container as a Docker image: %s", image)
python
def persist(self, container: Container, image: str) -> None: """ Persists the state of a given container to a BugZoo image on this server. Parameters: container: the container to persist. image: the name of the Docker image that should be created. Raises: ImageAlreadyExists: if the image name is already in use by another Docker image on this server. """ logger_c = logger.getChild(container.uid) logger_c.debug("Persisting container as a Docker image: %s", image) try: docker_container = self.__dockerc[container.uid] except KeyError: logger_c.exception("Failed to persist container: container no longer exists.") # noqa: pycodestyle raise try: _ = self.__client_docker.images.get(image) logger_c.error("Failed to persist container: image, '%s', already exists.", # noqa: pycodestyle image) raise ImageAlreadyExists(image) except docker.errors.ImageNotFound: pass cmd = "docker commit {} {}" cmd = cmd.format(docker_container.id, image) try: subprocess.check_output(cmd, shell=True) except subprocess.CalledProcessError: logger.exception("Failed to persist container (%s) to image (%s).", # noqa: pycodestyle container.uid, image) raise logger_c.debug("Persisted container as a Docker image: %s", image)
[ "def", "persist", "(", "self", ",", "container", ":", "Container", ",", "image", ":", "str", ")", "->", "None", ":", "logger_c", "=", "logger", ".", "getChild", "(", "container", ".", "uid", ")", "logger_c", ".", "debug", "(", "\"Persisting container as a ...
Persists the state of a given container to a BugZoo image on this server. Parameters: container: the container to persist. image: the name of the Docker image that should be created. Raises: ImageAlreadyExists: if the image name is already in use by another Docker image on this server.
[ "Persists", "the", "state", "of", "a", "given", "container", "to", "a", "BugZoo", "image", "on", "this", "server", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/container.py#L593-L629
train
30,076
squaresLab/BugZoo
bugzoo/server/__init__.py
ephemeral
def ephemeral(*, port: int = 6060, timeout_connection: int = 30, verbose: bool = False ) -> Iterator[Client]: """ Launches an ephemeral server instance that will be immediately close when no longer in context. Parameters: port: the port that the server should run on. verbose: if set to True, the server will print its output to the stdout, otherwise it will remain silent. Returns: a client for communicating with the server. """ url = "http://127.0.0.1:{}".format(port) cmd = ["bugzood", "--debug", "-p", str(port)] try: stdout = None if verbose else subprocess.DEVNULL stderr = None if verbose else subprocess.DEVNULL proc = subprocess.Popen(cmd, preexec_fn=os.setsid, stdout=stdout, stderr=stderr) yield Client(url, timeout_connection=timeout_connection) finally: os.killpg(proc.pid, signal.SIGTERM)
python
def ephemeral(*, port: int = 6060, timeout_connection: int = 30, verbose: bool = False ) -> Iterator[Client]: """ Launches an ephemeral server instance that will be immediately close when no longer in context. Parameters: port: the port that the server should run on. verbose: if set to True, the server will print its output to the stdout, otherwise it will remain silent. Returns: a client for communicating with the server. """ url = "http://127.0.0.1:{}".format(port) cmd = ["bugzood", "--debug", "-p", str(port)] try: stdout = None if verbose else subprocess.DEVNULL stderr = None if verbose else subprocess.DEVNULL proc = subprocess.Popen(cmd, preexec_fn=os.setsid, stdout=stdout, stderr=stderr) yield Client(url, timeout_connection=timeout_connection) finally: os.killpg(proc.pid, signal.SIGTERM)
[ "def", "ephemeral", "(", "*", ",", "port", ":", "int", "=", "6060", ",", "timeout_connection", ":", "int", "=", "30", ",", "verbose", ":", "bool", "=", "False", ")", "->", "Iterator", "[", "Client", "]", ":", "url", "=", "\"http://127.0.0.1:{}\"", ".",...
Launches an ephemeral server instance that will be immediately close when no longer in context. Parameters: port: the port that the server should run on. verbose: if set to True, the server will print its output to the stdout, otherwise it will remain silent. Returns: a client for communicating with the server.
[ "Launches", "an", "ephemeral", "server", "instance", "that", "will", "be", "immediately", "close", "when", "no", "longer", "in", "context", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/server/__init__.py#L67-L95
train
30,077
squaresLab/BugZoo
bugzoo/mgr/coverage/extractor.py
register
def register(name: str): """ Registers a coverage extractor class under a given name. .. code: python from bugzoo.mgr.coverage import CoverageExtractor, register @register('mycov') class MyCoverageExtractor(CoverageExtractor): ... """ def decorator(cls: Type['CoverageExtractor']): cls.register(name) return cls return decorator
python
def register(name: str): """ Registers a coverage extractor class under a given name. .. code: python from bugzoo.mgr.coverage import CoverageExtractor, register @register('mycov') class MyCoverageExtractor(CoverageExtractor): ... """ def decorator(cls: Type['CoverageExtractor']): cls.register(name) return cls return decorator
[ "def", "register", "(", "name", ":", "str", ")", ":", "def", "decorator", "(", "cls", ":", "Type", "[", "'CoverageExtractor'", "]", ")", ":", "cls", ".", "register", "(", "name", ")", "return", "cls", "return", "decorator" ]
Registers a coverage extractor class under a given name. .. code: python from bugzoo.mgr.coverage import CoverageExtractor, register @register('mycov') class MyCoverageExtractor(CoverageExtractor): ...
[ "Registers", "a", "coverage", "extractor", "class", "under", "a", "given", "name", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/coverage/extractor.py#L23-L38
train
30,078
squaresLab/BugZoo
bugzoo/mgr/coverage/extractor.py
register_as_default
def register_as_default(language: Language): """ Registers a coverage extractor class as the default coverage extractor for a given language. Requires that the coverage extractor class has already been registered with a given name. .. code: python from bugzoo.core import Language from bugzoo.mgr.coverage import CoverageExtractor, register, \ register_as_default @register_as_default(Language.CPP) @register('mycov') class MyCoverageExtractor(CoverageExtractor): ... """ def decorator(cls: Type['CoverageExtractor']): cls.register_as_default(language) return cls return decorator
python
def register_as_default(language: Language): """ Registers a coverage extractor class as the default coverage extractor for a given language. Requires that the coverage extractor class has already been registered with a given name. .. code: python from bugzoo.core import Language from bugzoo.mgr.coverage import CoverageExtractor, register, \ register_as_default @register_as_default(Language.CPP) @register('mycov') class MyCoverageExtractor(CoverageExtractor): ... """ def decorator(cls: Type['CoverageExtractor']): cls.register_as_default(language) return cls return decorator
[ "def", "register_as_default", "(", "language", ":", "Language", ")", ":", "def", "decorator", "(", "cls", ":", "Type", "[", "'CoverageExtractor'", "]", ")", ":", "cls", ".", "register_as_default", "(", "language", ")", "return", "cls", "return", "decorator" ]
Registers a coverage extractor class as the default coverage extractor for a given language. Requires that the coverage extractor class has already been registered with a given name. .. code: python from bugzoo.core import Language from bugzoo.mgr.coverage import CoverageExtractor, register, \ register_as_default @register_as_default(Language.CPP) @register('mycov') class MyCoverageExtractor(CoverageExtractor): ...
[ "Registers", "a", "coverage", "extractor", "class", "as", "the", "default", "coverage", "extractor", "for", "a", "given", "language", ".", "Requires", "that", "the", "coverage", "extractor", "class", "has", "already", "been", "registered", "with", "a", "given", ...
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/coverage/extractor.py#L41-L61
train
30,079
squaresLab/BugZoo
bugzoo/mgr/coverage/extractor.py
CoverageExtractor.build
def build(installation: 'BugZoo', container: Container ) -> 'CoverageExtractor': """ Constructs a CoverageExtractor for a given container using the coverage instructions provided by its accompanying bug description. """ bug = installation.bugs[container.bug] # type: Bug instructions = bug.instructions_coverage if instructions is None: raise exceptions.NoCoverageInstructions name = instructions.__class__.registered_under_name() extractor_cls = _NAME_TO_EXTRACTOR[name] builder = extractor_cls.from_instructions extractor = builder(installation, container, instructions) return extractor
python
def build(installation: 'BugZoo', container: Container ) -> 'CoverageExtractor': """ Constructs a CoverageExtractor for a given container using the coverage instructions provided by its accompanying bug description. """ bug = installation.bugs[container.bug] # type: Bug instructions = bug.instructions_coverage if instructions is None: raise exceptions.NoCoverageInstructions name = instructions.__class__.registered_under_name() extractor_cls = _NAME_TO_EXTRACTOR[name] builder = extractor_cls.from_instructions extractor = builder(installation, container, instructions) return extractor
[ "def", "build", "(", "installation", ":", "'BugZoo'", ",", "container", ":", "Container", ")", "->", "'CoverageExtractor'", ":", "bug", "=", "installation", ".", "bugs", "[", "container", ".", "bug", "]", "# type: Bug", "instructions", "=", "bug", ".", "inst...
Constructs a CoverageExtractor for a given container using the coverage instructions provided by its accompanying bug description.
[ "Constructs", "a", "CoverageExtractor", "for", "a", "given", "container", "using", "the", "coverage", "instructions", "provided", "by", "its", "accompanying", "bug", "description", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/coverage/extractor.py#L144-L160
train
30,080
squaresLab/BugZoo
bugzoo/mgr/coverage/extractor.py
CoverageExtractor.run
def run(self, tests: Iterable[TestCase], *, instrument: bool = True ) -> TestSuiteCoverage: """ Computes line coverage information for a given set of tests. Parameters: tests: the tests for which coverage should be computed. instrument: if set to True, calls prepare and cleanup before and after running the tests. If set to False, prepare and cleanup are not called, and the responsibility of calling those methods is left to the user. """ container = self.container logger.debug("computing coverage for container: %s", container.uid) try: if instrument: logger.debug("instrumenting container") self.prepare() else: logger.debug("not instrumenting container") except Exception: msg = "failed to instrument container." raise exceptions.FailedToComputeCoverage(msg) cov = {} for test in tests: logger.debug("Generating coverage for test %s in container %s", test.name, container.uid) outcome = self.__installation.containers.execute(container, test) filelines = self.extract() test_coverage = TestCoverage(test.name, outcome, filelines) logger.debug("Generated coverage for test %s in container %s", test.name, container.uid) cov[test.name] = test_coverage self.cleanup() coverage = TestSuiteCoverage(cov) logger.debug("Computed coverage for container: %s", container.uid) return coverage
python
def run(self, tests: Iterable[TestCase], *, instrument: bool = True ) -> TestSuiteCoverage: """ Computes line coverage information for a given set of tests. Parameters: tests: the tests for which coverage should be computed. instrument: if set to True, calls prepare and cleanup before and after running the tests. If set to False, prepare and cleanup are not called, and the responsibility of calling those methods is left to the user. """ container = self.container logger.debug("computing coverage for container: %s", container.uid) try: if instrument: logger.debug("instrumenting container") self.prepare() else: logger.debug("not instrumenting container") except Exception: msg = "failed to instrument container." raise exceptions.FailedToComputeCoverage(msg) cov = {} for test in tests: logger.debug("Generating coverage for test %s in container %s", test.name, container.uid) outcome = self.__installation.containers.execute(container, test) filelines = self.extract() test_coverage = TestCoverage(test.name, outcome, filelines) logger.debug("Generated coverage for test %s in container %s", test.name, container.uid) cov[test.name] = test_coverage self.cleanup() coverage = TestSuiteCoverage(cov) logger.debug("Computed coverage for container: %s", container.uid) return coverage
[ "def", "run", "(", "self", ",", "tests", ":", "Iterable", "[", "TestCase", "]", ",", "*", ",", "instrument", ":", "bool", "=", "True", ")", "->", "TestSuiteCoverage", ":", "container", "=", "self", ".", "container", "logger", ".", "debug", "(", "\"comp...
Computes line coverage information for a given set of tests. Parameters: tests: the tests for which coverage should be computed. instrument: if set to True, calls prepare and cleanup before and after running the tests. If set to False, prepare and cleanup are not called, and the responsibility of calling those methods is left to the user.
[ "Computes", "line", "coverage", "information", "for", "a", "given", "set", "of", "tests", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/coverage/extractor.py#L209-L252
train
30,081
squaresLab/BugZoo
bugzoo/exceptions.py
BugZooException.from_dict
def from_dict(d: Dict[str, Any]) -> 'BugZooException': """ Reconstructs a BugZoo exception from a dictionary-based description. """ assert 'error' in d d = d['error'] cls = getattr(sys.modules[__name__], d['kind']) assert issubclass(cls, BugZooException) return cls.from_message_and_data(d['message'], d.get('data', {}))
python
def from_dict(d: Dict[str, Any]) -> 'BugZooException': """ Reconstructs a BugZoo exception from a dictionary-based description. """ assert 'error' in d d = d['error'] cls = getattr(sys.modules[__name__], d['kind']) assert issubclass(cls, BugZooException) return cls.from_message_and_data(d['message'], d.get('data', {}))
[ "def", "from_dict", "(", "d", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "'BugZooException'", ":", "assert", "'error'", "in", "d", "d", "=", "d", "[", "'error'", "]", "cls", "=", "getattr", "(", "sys", ".", "modules", "[", "__name__", "]"...
Reconstructs a BugZoo exception from a dictionary-based description.
[ "Reconstructs", "a", "BugZoo", "exception", "from", "a", "dictionary", "-", "based", "description", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/exceptions.py#L42-L52
train
30,082
squaresLab/BugZoo
bugzoo/exceptions.py
BugZooException.from_message_and_data
def from_message_and_data(cls, message: str, data: Dict[str, Any] ) -> 'BugZooException': """ Reproduces an exception from the message and data contained in its dictionary-based description. """ return cls(message)
python
def from_message_and_data(cls, message: str, data: Dict[str, Any] ) -> 'BugZooException': """ Reproduces an exception from the message and data contained in its dictionary-based description. """ return cls(message)
[ "def", "from_message_and_data", "(", "cls", ",", "message", ":", "str", ",", "data", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "'BugZooException'", ":", "return", "cls", "(", "message", ")" ]
Reproduces an exception from the message and data contained in its dictionary-based description.
[ "Reproduces", "an", "exception", "from", "the", "message", "and", "data", "contained", "in", "its", "dictionary", "-", "based", "description", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/exceptions.py#L66-L74
train
30,083
squaresLab/BugZoo
bugzoo/exceptions.py
BugZooException.to_dict
def to_dict(self) -> Dict[str, Any]: """ Creates a dictionary-based description of this exception, ready to be serialised as JSON or YAML. """ jsn = { 'kind': self.__class__.__name__, 'message': self.message } # type: Dict[str, Any] data = self.data if data: jsn['data'] = data jsn = {'error': jsn} return jsn
python
def to_dict(self) -> Dict[str, Any]: """ Creates a dictionary-based description of this exception, ready to be serialised as JSON or YAML. """ jsn = { 'kind': self.__class__.__name__, 'message': self.message } # type: Dict[str, Any] data = self.data if data: jsn['data'] = data jsn = {'error': jsn} return jsn
[ "def", "to_dict", "(", "self", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "jsn", "=", "{", "'kind'", ":", "self", ".", "__class__", ".", "__name__", ",", "'message'", ":", "self", ".", "message", "}", "# type: Dict[str, Any]", "data", "=", ...
Creates a dictionary-based description of this exception, ready to be serialised as JSON or YAML.
[ "Creates", "a", "dictionary", "-", "based", "description", "of", "this", "exception", "ready", "to", "be", "serialised", "as", "JSON", "or", "YAML", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/exceptions.py#L80-L93
train
30,084
squaresLab/BugZoo
bugzoo/core/patch.py
Hunk._read_next
def _read_next(cls, lines: List[str]) -> 'Hunk': """ Constructs a hunk from a supplied fragment of a unified format diff. """ header = lines[0] assert header.startswith('@@ -') # sometimes the first line can occur on the same line as the header. # in that case, we inject a new line into the buffer end_header_at = header.index(' @@') bonus_line = header[end_header_at+3:] if bonus_line != "": lines.insert(1, bonus_line) header = header[4:end_header_at] left, _, right = header.partition(' +') old_start_at = int(left.split(',')[0]) new_start_at = int(right.split(',')[0]) old_line_num = old_start_at new_line_num = new_start_at last_insertion_at = old_start_at hunk_lines = [] # type: List[HunkLine] while True: # discarding the previous line ensures that we only consume lines # from the line buffer that belong to the hunk lines.pop(0) if not lines: break line = lines[0] # inserted line if line.startswith('+'): hunk_lines.append(InsertedLine(line[1:])) new_line_num += 1 # deleted line elif line.startswith('-'): hunk_lines.append(DeletedLine(line[1:])) old_line_num += 1 # context line elif line.startswith(' '): hunk_lines.append(ContextLine(line[1:])) new_line_num += 1 old_line_num += 1 # end of hunk else: break return Hunk(old_start_at, new_start_at, hunk_lines)
python
def _read_next(cls, lines: List[str]) -> 'Hunk': """ Constructs a hunk from a supplied fragment of a unified format diff. """ header = lines[0] assert header.startswith('@@ -') # sometimes the first line can occur on the same line as the header. # in that case, we inject a new line into the buffer end_header_at = header.index(' @@') bonus_line = header[end_header_at+3:] if bonus_line != "": lines.insert(1, bonus_line) header = header[4:end_header_at] left, _, right = header.partition(' +') old_start_at = int(left.split(',')[0]) new_start_at = int(right.split(',')[0]) old_line_num = old_start_at new_line_num = new_start_at last_insertion_at = old_start_at hunk_lines = [] # type: List[HunkLine] while True: # discarding the previous line ensures that we only consume lines # from the line buffer that belong to the hunk lines.pop(0) if not lines: break line = lines[0] # inserted line if line.startswith('+'): hunk_lines.append(InsertedLine(line[1:])) new_line_num += 1 # deleted line elif line.startswith('-'): hunk_lines.append(DeletedLine(line[1:])) old_line_num += 1 # context line elif line.startswith(' '): hunk_lines.append(ContextLine(line[1:])) new_line_num += 1 old_line_num += 1 # end of hunk else: break return Hunk(old_start_at, new_start_at, hunk_lines)
[ "def", "_read_next", "(", "cls", ",", "lines", ":", "List", "[", "str", "]", ")", "->", "'Hunk'", ":", "header", "=", "lines", "[", "0", "]", "assert", "header", ".", "startswith", "(", "'@@ -'", ")", "# sometimes the first line can occur on the same line as t...
Constructs a hunk from a supplied fragment of a unified format diff.
[ "Constructs", "a", "hunk", "from", "a", "supplied", "fragment", "of", "a", "unified", "format", "diff", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/core/patch.py#L58-L112
train
30,085
squaresLab/BugZoo
bugzoo/core/patch.py
FilePatch._read_next
def _read_next(cls, lines: List[str]) -> 'FilePatch': """ Destructively extracts the next file patch from the line buffer. """ # keep munching lines until we hit one starting with '---' while True: if not lines: raise Exception("illegal file patch format: couldn't find line starting with '---'") line = lines[0] if line.startswith('---'): break lines.pop(0) assert lines[0].startswith('---') assert lines[1].startswith('+++') old_fn = lines.pop(0)[4:].strip() new_fn = lines.pop(0)[4:].strip() hunks = [] while lines: if not lines[0].startswith('@@'): break hunks.append(Hunk._read_next(lines)) return FilePatch(old_fn, new_fn, hunks)
python
def _read_next(cls, lines: List[str]) -> 'FilePatch': """ Destructively extracts the next file patch from the line buffer. """ # keep munching lines until we hit one starting with '---' while True: if not lines: raise Exception("illegal file patch format: couldn't find line starting with '---'") line = lines[0] if line.startswith('---'): break lines.pop(0) assert lines[0].startswith('---') assert lines[1].startswith('+++') old_fn = lines.pop(0)[4:].strip() new_fn = lines.pop(0)[4:].strip() hunks = [] while lines: if not lines[0].startswith('@@'): break hunks.append(Hunk._read_next(lines)) return FilePatch(old_fn, new_fn, hunks)
[ "def", "_read_next", "(", "cls", ",", "lines", ":", "List", "[", "str", "]", ")", "->", "'FilePatch'", ":", "# keep munching lines until we hit one starting with '---'", "while", "True", ":", "if", "not", "lines", ":", "raise", "Exception", "(", "\"illegal file pa...
Destructively extracts the next file patch from the line buffer.
[ "Destructively", "extracts", "the", "next", "file", "patch", "from", "the", "line", "buffer", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/core/patch.py#L150-L174
train
30,086
squaresLab/BugZoo
bugzoo/core/patch.py
Patch.from_unidiff
def from_unidiff(cls, diff: str) -> 'Patch': """ Constructs a Patch from a provided unified format diff. """ lines = diff.split('\n') file_patches = [] while lines: if lines[0] == '' or lines[0].isspace(): lines.pop(0) continue file_patches.append(FilePatch._read_next(lines)) return Patch(file_patches)
python
def from_unidiff(cls, diff: str) -> 'Patch': """ Constructs a Patch from a provided unified format diff. """ lines = diff.split('\n') file_patches = [] while lines: if lines[0] == '' or lines[0].isspace(): lines.pop(0) continue file_patches.append(FilePatch._read_next(lines)) return Patch(file_patches)
[ "def", "from_unidiff", "(", "cls", ",", "diff", ":", "str", ")", "->", "'Patch'", ":", "lines", "=", "diff", ".", "split", "(", "'\\n'", ")", "file_patches", "=", "[", "]", "while", "lines", ":", "if", "lines", "[", "0", "]", "==", "''", "or", "l...
Constructs a Patch from a provided unified format diff.
[ "Constructs", "a", "Patch", "from", "a", "provided", "unified", "format", "diff", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/core/patch.py#L209-L221
train
30,087
squaresLab/BugZoo
bugzoo/client/container.py
ContainerManager.clear
def clear(self) -> None: """ Destroys all running containers. """ r = self.__api.delete('containers') if r.status_code != 204: self.__api.handle_erroneous_response(r)
python
def clear(self) -> None: """ Destroys all running containers. """ r = self.__api.delete('containers') if r.status_code != 204: self.__api.handle_erroneous_response(r)
[ "def", "clear", "(", "self", ")", "->", "None", ":", "r", "=", "self", ".", "__api", ".", "delete", "(", "'containers'", ")", "if", "r", ".", "status_code", "!=", "204", ":", "self", ".", "__api", ".", "handle_erroneous_response", "(", "r", ")" ]
Destroys all running containers.
[ "Destroys", "all", "running", "containers", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/container.py#L87-L93
train
30,088
squaresLab/BugZoo
bugzoo/client/container.py
ContainerManager.provision
def provision(self, bug: Bug, *, plugins: Optional[List[Tool]] = None ) -> Container: """ Provisions a container for a given bug. """ if plugins is None: plugins = [] logger.info("provisioning container for bug: %s", bug.name) endpoint = 'bugs/{}/provision'.format(bug.name) payload = { 'plugins': [p.to_dict() for p in plugins] } # type: Dict[str, Any] r = self.__api.post(endpoint, json=payload) if r.status_code == 200: container = Container.from_dict(r.json()) logger.info("provisioned container (id: %s) for bug: %s", container.uid, bug.name) return container if r.status_code == 404: raise KeyError("no bug registered with given name: {}".format(bug.name)) self.__api.handle_erroneous_response(r)
python
def provision(self, bug: Bug, *, plugins: Optional[List[Tool]] = None ) -> Container: """ Provisions a container for a given bug. """ if plugins is None: plugins = [] logger.info("provisioning container for bug: %s", bug.name) endpoint = 'bugs/{}/provision'.format(bug.name) payload = { 'plugins': [p.to_dict() for p in plugins] } # type: Dict[str, Any] r = self.__api.post(endpoint, json=payload) if r.status_code == 200: container = Container.from_dict(r.json()) logger.info("provisioned container (id: %s) for bug: %s", container.uid, bug.name) return container if r.status_code == 404: raise KeyError("no bug registered with given name: {}".format(bug.name)) self.__api.handle_erroneous_response(r)
[ "def", "provision", "(", "self", ",", "bug", ":", "Bug", ",", "*", ",", "plugins", ":", "Optional", "[", "List", "[", "Tool", "]", "]", "=", "None", ")", "->", "Container", ":", "if", "plugins", "is", "None", ":", "plugins", "=", "[", "]", "logge...
Provisions a container for a given bug.
[ "Provisions", "a", "container", "for", "a", "given", "bug", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/container.py#L110-L138
train
30,089
squaresLab/BugZoo
bugzoo/client/container.py
ContainerManager.mktemp
def mktemp(self, container: Container) -> str: """ Generates a temporary file for a given container. Returns: the path to the temporary file inside the given container. """ r = self.__api.post('containers/{}/tempfile'.format(container.uid)) if r.status_code == 200: return r.json() self.__api.handle_erroneous_response(r)
python
def mktemp(self, container: Container) -> str: """ Generates a temporary file for a given container. Returns: the path to the temporary file inside the given container. """ r = self.__api.post('containers/{}/tempfile'.format(container.uid)) if r.status_code == 200: return r.json() self.__api.handle_erroneous_response(r)
[ "def", "mktemp", "(", "self", ",", "container", ":", "Container", ")", "->", "str", ":", "r", "=", "self", ".", "__api", ".", "post", "(", "'containers/{}/tempfile'", ".", "format", "(", "container", ".", "uid", ")", ")", "if", "r", ".", "status_code",...
Generates a temporary file for a given container. Returns: the path to the temporary file inside the given container.
[ "Generates", "a", "temporary", "file", "for", "a", "given", "container", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/container.py#L140-L150
train
30,090
squaresLab/BugZoo
bugzoo/client/container.py
ContainerManager.is_alive
def is_alive(self, container: Container) -> bool: """ Determines whether or not a given container is still alive. """ uid = container.uid r = self.__api.get('containers/{}/alive'.format(uid)) if r.status_code == 200: return r.json() if r.status_code == 404: raise KeyError("no container found with given UID: {}".format(uid)) self.__api.handle_erroneous_response(r)
python
def is_alive(self, container: Container) -> bool: """ Determines whether or not a given container is still alive. """ uid = container.uid r = self.__api.get('containers/{}/alive'.format(uid)) if r.status_code == 200: return r.json() if r.status_code == 404: raise KeyError("no container found with given UID: {}".format(uid)) self.__api.handle_erroneous_response(r)
[ "def", "is_alive", "(", "self", ",", "container", ":", "Container", ")", "->", "bool", ":", "uid", "=", "container", ".", "uid", "r", "=", "self", ".", "__api", ".", "get", "(", "'containers/{}/alive'", ".", "format", "(", "uid", ")", ")", "if", "r",...
Determines whether or not a given container is still alive.
[ "Determines", "whether", "or", "not", "a", "given", "container", "is", "still", "alive", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/container.py#L164-L177
train
30,091
squaresLab/BugZoo
bugzoo/client/container.py
ContainerManager.extract_coverage
def extract_coverage(self, container: Container) -> FileLineSet: """ Extracts a report of the lines that have been executed since the last time that a coverage report was extracted. """ uid = container.uid r = self.__api.post('containers/{}/read-coverage'.format(uid)) if r.status_code == 200: return FileLineSet.from_dict(r.json()) self.__api.handle_erroneous_response(r)
python
def extract_coverage(self, container: Container) -> FileLineSet: """ Extracts a report of the lines that have been executed since the last time that a coverage report was extracted. """ uid = container.uid r = self.__api.post('containers/{}/read-coverage'.format(uid)) if r.status_code == 200: return FileLineSet.from_dict(r.json()) self.__api.handle_erroneous_response(r)
[ "def", "extract_coverage", "(", "self", ",", "container", ":", "Container", ")", "->", "FileLineSet", ":", "uid", "=", "container", ".", "uid", "r", "=", "self", ".", "__api", ".", "post", "(", "'containers/{}/read-coverage'", ".", "format", "(", "uid", ")...
Extracts a report of the lines that have been executed since the last time that a coverage report was extracted.
[ "Extracts", "a", "report", "of", "the", "lines", "that", "have", "been", "executed", "since", "the", "last", "time", "that", "a", "coverage", "report", "was", "extracted", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/container.py#L179-L188
train
30,092
squaresLab/BugZoo
bugzoo/client/container.py
ContainerManager.instrument
def instrument(self, container: Container ) -> None: """ Instruments the program inside the container for computing test suite coverage. Params: container: the container that should be instrumented. """ path = "containers/{}/instrument".format(container.uid) r = self.__api.post(path) if r.status_code != 204: logger.info("failed to instrument container: %s", container.uid) self.__api.handle_erroneous_response(r)
python
def instrument(self, container: Container ) -> None: """ Instruments the program inside the container for computing test suite coverage. Params: container: the container that should be instrumented. """ path = "containers/{}/instrument".format(container.uid) r = self.__api.post(path) if r.status_code != 204: logger.info("failed to instrument container: %s", container.uid) self.__api.handle_erroneous_response(r)
[ "def", "instrument", "(", "self", ",", "container", ":", "Container", ")", "->", "None", ":", "path", "=", "\"containers/{}/instrument\"", ".", "format", "(", "container", ".", "uid", ")", "r", "=", "self", ".", "__api", ".", "post", "(", "path", ")", ...
Instruments the program inside the container for computing test suite coverage. Params: container: the container that should be instrumented.
[ "Instruments", "the", "program", "inside", "the", "container", "for", "computing", "test", "suite", "coverage", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/container.py#L190-L204
train
30,093
squaresLab/BugZoo
bugzoo/client/container.py
ContainerManager.coverage
def coverage(self, container: Container, *, instrument: bool = True ) -> TestSuiteCoverage: """ Computes complete test suite coverage for a given container. Parameters: container: the container for which coverage should be computed. rebuild: if set to True, the program will be rebuilt before coverage is computed. """ uid = container.uid logger.info("Fetching coverage information for container: %s", uid) uri = 'containers/{}/coverage'.format(uid) r = self.__api.post(uri, params={'instrument': 'yes' if instrument else 'no'}) if r.status_code == 200: jsn = r.json() coverage = TestSuiteCoverage.from_dict(jsn) # type: ignore logger.info("Fetched coverage information for container: %s", uid) return coverage try: self.__api.handle_erroneous_response(r) except exceptions.BugZooException as err: logger.exception("Failed to fetch coverage information for container %s: %s", uid, err.message) # noqa: pycodestyle raise except Exception as err: logger.exception("Failed to fetch coverage information for container %s due to unexpected failure: %s", uid, err) # noqa: pycodestyle raise
python
def coverage(self, container: Container, *, instrument: bool = True ) -> TestSuiteCoverage: """ Computes complete test suite coverage for a given container. Parameters: container: the container for which coverage should be computed. rebuild: if set to True, the program will be rebuilt before coverage is computed. """ uid = container.uid logger.info("Fetching coverage information for container: %s", uid) uri = 'containers/{}/coverage'.format(uid) r = self.__api.post(uri, params={'instrument': 'yes' if instrument else 'no'}) if r.status_code == 200: jsn = r.json() coverage = TestSuiteCoverage.from_dict(jsn) # type: ignore logger.info("Fetched coverage information for container: %s", uid) return coverage try: self.__api.handle_erroneous_response(r) except exceptions.BugZooException as err: logger.exception("Failed to fetch coverage information for container %s: %s", uid, err.message) # noqa: pycodestyle raise except Exception as err: logger.exception("Failed to fetch coverage information for container %s due to unexpected failure: %s", uid, err) # noqa: pycodestyle raise
[ "def", "coverage", "(", "self", ",", "container", ":", "Container", ",", "*", ",", "instrument", ":", "bool", "=", "True", ")", "->", "TestSuiteCoverage", ":", "uid", "=", "container", ".", "uid", "logger", ".", "info", "(", "\"Fetching coverage information ...
Computes complete test suite coverage for a given container. Parameters: container: the container for which coverage should be computed. rebuild: if set to True, the program will be rebuilt before coverage is computed.
[ "Computes", "complete", "test", "suite", "coverage", "for", "a", "given", "container", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/container.py#L261-L293
train
30,094
squaresLab/BugZoo
bugzoo/client/container.py
ContainerManager.exec
def exec(self, container: Container, command: str, context: Optional[str] = None, stdout: bool = True, stderr: bool = False, time_limit: Optional[int] = None ) -> ExecResponse: """ Executes a given command inside a provided container. Parameters: container: the container to which the command should be issued. command: the command that should be executed. context: the working directory that should be used to perform the execution. If no context is provided, then the command will be executed at the root of the container. stdout: specifies whether or not output to the stdout should be included in the execution summary. stderr: specifies whether or not output to the stderr should be included in the execution summary. time_limit: an optional time limit that is applied to the execution. If the command fails to execute within the time limit, the command will be aborted and treated as a failure. Returns: a summary of the outcome of the execution. Raises: KeyError: if the container no longer exists on the server. """ # FIXME perhaps these should be encoded as path variables? payload = { 'command': command, 'context': context, 'stdout': stdout, 'stderr': stderr, 'time-limit': time_limit } path = "containers/{}/exec".format(container.uid) r = self.__api.post(path, json=payload) if r.status_code == 200: return ExecResponse.from_dict(r.json()) if r.status_code == 404: raise KeyError("no container found with given UID: {}".format(container.uid)) self.__api.handle_erroneous_response(r)
python
def exec(self, container: Container, command: str, context: Optional[str] = None, stdout: bool = True, stderr: bool = False, time_limit: Optional[int] = None ) -> ExecResponse: """ Executes a given command inside a provided container. Parameters: container: the container to which the command should be issued. command: the command that should be executed. context: the working directory that should be used to perform the execution. If no context is provided, then the command will be executed at the root of the container. stdout: specifies whether or not output to the stdout should be included in the execution summary. stderr: specifies whether or not output to the stderr should be included in the execution summary. time_limit: an optional time limit that is applied to the execution. If the command fails to execute within the time limit, the command will be aborted and treated as a failure. Returns: a summary of the outcome of the execution. Raises: KeyError: if the container no longer exists on the server. """ # FIXME perhaps these should be encoded as path variables? payload = { 'command': command, 'context': context, 'stdout': stdout, 'stderr': stderr, 'time-limit': time_limit } path = "containers/{}/exec".format(container.uid) r = self.__api.post(path, json=payload) if r.status_code == 200: return ExecResponse.from_dict(r.json()) if r.status_code == 404: raise KeyError("no container found with given UID: {}".format(container.uid)) self.__api.handle_erroneous_response(r)
[ "def", "exec", "(", "self", ",", "container", ":", "Container", ",", "command", ":", "str", ",", "context", ":", "Optional", "[", "str", "]", "=", "None", ",", "stdout", ":", "bool", "=", "True", ",", "stderr", ":", "bool", "=", "False", ",", "time...
Executes a given command inside a provided container. Parameters: container: the container to which the command should be issued. command: the command that should be executed. context: the working directory that should be used to perform the execution. If no context is provided, then the command will be executed at the root of the container. stdout: specifies whether or not output to the stdout should be included in the execution summary. stderr: specifies whether or not output to the stderr should be included in the execution summary. time_limit: an optional time limit that is applied to the execution. If the command fails to execute within the time limit, the command will be aborted and treated as a failure. Returns: a summary of the outcome of the execution. Raises: KeyError: if the container no longer exists on the server.
[ "Executes", "a", "given", "command", "inside", "a", "provided", "container", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/container.py#L295-L342
train
30,095
squaresLab/BugZoo
bugzoo/client/container.py
ContainerManager.persist
def persist(self, container: Container, image_name: str) -> None: """ Persists the state of a given container as a Docker image on the server. Parameters: container: the container that should be persisted. image_name: the name of the Docker image that should be created. Raises: ContainerNotFound: if the given container does not exist on the server. ImageAlreadyExists: if the given image name is already in use by another Docker image on the server. """ logger.debug("attempting to persist container (%s) to image (%s).", container.id, image_name) path = "containers/{}/persist/{}".format(container.id, image_name) r = self.__api.put(path) if r.status_code == 204: logger.debug("persisted container (%s) to image (%s).", container.id, image_name) return try: self.__api.handle_erroneous_response(r) except Exception: logger.exception("failed to persist container (%s) to image (%s).", # noqa: pycodestyle container.id, image_name) raise
python
def persist(self, container: Container, image_name: str) -> None: """ Persists the state of a given container as a Docker image on the server. Parameters: container: the container that should be persisted. image_name: the name of the Docker image that should be created. Raises: ContainerNotFound: if the given container does not exist on the server. ImageAlreadyExists: if the given image name is already in use by another Docker image on the server. """ logger.debug("attempting to persist container (%s) to image (%s).", container.id, image_name) path = "containers/{}/persist/{}".format(container.id, image_name) r = self.__api.put(path) if r.status_code == 204: logger.debug("persisted container (%s) to image (%s).", container.id, image_name) return try: self.__api.handle_erroneous_response(r) except Exception: logger.exception("failed to persist container (%s) to image (%s).", # noqa: pycodestyle container.id, image_name) raise
[ "def", "persist", "(", "self", ",", "container", ":", "Container", ",", "image_name", ":", "str", ")", "->", "None", ":", "logger", ".", "debug", "(", "\"attempting to persist container (%s) to image (%s).\"", ",", "container", ".", "id", ",", "image_name", ")",...
Persists the state of a given container as a Docker image on the server. Parameters: container: the container that should be persisted. image_name: the name of the Docker image that should be created. Raises: ContainerNotFound: if the given container does not exist on the server. ImageAlreadyExists: if the given image name is already in use by another Docker image on the server.
[ "Persists", "the", "state", "of", "a", "given", "container", "as", "a", "Docker", "image", "on", "the", "server", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/container.py#L363-L394
train
30,096
squaresLab/BugZoo
bugzoo/compiler/__init__.py
SimpleCompiler.from_dict
def from_dict(d: dict) -> 'SimpleCompiler': """ Loads a SimpleCompiler from its dictionary-based description. """ cmd = d['command'] cmd_with_instrumentation = d.get('command_with_instrumentation', None) time_limit = d['time-limit'] context = d['context'] cmd_clean = d.get('command_clean', 'exit 0') return SimpleCompiler(command=cmd, command_clean=cmd_clean, command_with_instrumentation=cmd_with_instrumentation, context=context, time_limit=time_limit)
python
def from_dict(d: dict) -> 'SimpleCompiler': """ Loads a SimpleCompiler from its dictionary-based description. """ cmd = d['command'] cmd_with_instrumentation = d.get('command_with_instrumentation', None) time_limit = d['time-limit'] context = d['context'] cmd_clean = d.get('command_clean', 'exit 0') return SimpleCompiler(command=cmd, command_clean=cmd_clean, command_with_instrumentation=cmd_with_instrumentation, context=context, time_limit=time_limit)
[ "def", "from_dict", "(", "d", ":", "dict", ")", "->", "'SimpleCompiler'", ":", "cmd", "=", "d", "[", "'command'", "]", "cmd_with_instrumentation", "=", "d", ".", "get", "(", "'command_with_instrumentation'", ",", "None", ")", "time_limit", "=", "d", "[", "...
Loads a SimpleCompiler from its dictionary-based description.
[ "Loads", "a", "SimpleCompiler", "from", "its", "dictionary", "-", "based", "description", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/compiler/__init__.py#L101-L114
train
30,097
matiskay/html-similarity
html_similarity/structural_similarity.py
get_tags
def get_tags(doc): ''' Get tags from a DOM tree :param doc: lxml parsed object :return: ''' tags = list() for el in doc.getroot().iter(): if isinstance(el, lxml.html.HtmlElement): tags.append(el.tag) elif isinstance(el, lxml.html.HtmlComment): tags.append('comment') else: raise ValueError('Don\'t know what to do with element: {}'.format(el)) return tags
python
def get_tags(doc): ''' Get tags from a DOM tree :param doc: lxml parsed object :return: ''' tags = list() for el in doc.getroot().iter(): if isinstance(el, lxml.html.HtmlElement): tags.append(el.tag) elif isinstance(el, lxml.html.HtmlComment): tags.append('comment') else: raise ValueError('Don\'t know what to do with element: {}'.format(el)) return tags
[ "def", "get_tags", "(", "doc", ")", ":", "tags", "=", "list", "(", ")", "for", "el", "in", "doc", ".", "getroot", "(", ")", ".", "iter", "(", ")", ":", "if", "isinstance", "(", "el", ",", "lxml", ".", "html", ".", "HtmlElement", ")", ":", "tags...
Get tags from a DOM tree :param doc: lxml parsed object :return:
[ "Get", "tags", "from", "a", "DOM", "tree" ]
eef5586b1cf30134254690b2150260ef82cbd18f
https://github.com/matiskay/html-similarity/blob/eef5586b1cf30134254690b2150260ef82cbd18f/html_similarity/structural_similarity.py#L7-L24
train
30,098
squaresLab/BugZoo
bugzoo/client/api.py
APIClient._url
def _url(self, path: str) -> str: """ Computes the URL for a resource located at a given path on the server. """ url = "{}/{}".format(self.__base_url, path) logger.debug("transformed path [%s] into url: %s", path, url) return url
python
def _url(self, path: str) -> str: """ Computes the URL for a resource located at a given path on the server. """ url = "{}/{}".format(self.__base_url, path) logger.debug("transformed path [%s] into url: %s", path, url) return url
[ "def", "_url", "(", "self", ",", "path", ":", "str", ")", "->", "str", ":", "url", "=", "\"{}/{}\"", ".", "format", "(", "self", ".", "__base_url", ",", "path", ")", "logger", ".", "debug", "(", "\"transformed path [%s] into url: %s\"", ",", "path", ",",...
Computes the URL for a resource located at a given path on the server.
[ "Computes", "the", "URL", "for", "a", "resource", "located", "at", "a", "given", "path", "on", "the", "server", "." ]
68664f1977e85b37a78604f7c570382ffae1fa3b
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/api.py#L71-L77
train
30,099