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
linkedin/luminol
src/luminol/anomaly_detector.py
AnomalyDetector._detect_anomalies
def _detect_anomalies(self): """ Detect anomalies using a threshold on anomaly scores. """ anom_scores = self.anom_scores max_anom_score = anom_scores.max() anomalies = [] if max_anom_score: threshold = self.threshold or max_anom_score * self.score_percent_threshold # Find all the anomaly intervals. intervals = [] start, end = None, None for timestamp, value in anom_scores.iteritems(): if value > threshold: end = timestamp if not start: start = timestamp elif start and end is not None: intervals.append([start, end]) start = None end = None if start is not None: intervals.append([start, end]) # Locate the exact anomaly point within each anomaly interval. for interval_start, interval_end in intervals: interval_series = anom_scores.crop(interval_start, interval_end) self.refine_algorithm_params['time_series'] = interval_series refine_algorithm = self.refine_algorithm(**self.refine_algorithm_params) scores = refine_algorithm.run() max_refine_score = scores.max() # Get the timestamp of the maximal score. max_refine_timestamp = scores.timestamps[scores.values.index(max_refine_score)] anomaly = Anomaly(interval_start, interval_end, interval_series.max(), max_refine_timestamp) anomalies.append(anomaly) self.anomalies = anomalies
python
def _detect_anomalies(self): """ Detect anomalies using a threshold on anomaly scores. """ anom_scores = self.anom_scores max_anom_score = anom_scores.max() anomalies = [] if max_anom_score: threshold = self.threshold or max_anom_score * self.score_percent_threshold # Find all the anomaly intervals. intervals = [] start, end = None, None for timestamp, value in anom_scores.iteritems(): if value > threshold: end = timestamp if not start: start = timestamp elif start and end is not None: intervals.append([start, end]) start = None end = None if start is not None: intervals.append([start, end]) # Locate the exact anomaly point within each anomaly interval. for interval_start, interval_end in intervals: interval_series = anom_scores.crop(interval_start, interval_end) self.refine_algorithm_params['time_series'] = interval_series refine_algorithm = self.refine_algorithm(**self.refine_algorithm_params) scores = refine_algorithm.run() max_refine_score = scores.max() # Get the timestamp of the maximal score. max_refine_timestamp = scores.timestamps[scores.values.index(max_refine_score)] anomaly = Anomaly(interval_start, interval_end, interval_series.max(), max_refine_timestamp) anomalies.append(anomaly) self.anomalies = anomalies
[ "def", "_detect_anomalies", "(", "self", ")", ":", "anom_scores", "=", "self", ".", "anom_scores", "max_anom_score", "=", "anom_scores", ".", "max", "(", ")", "anomalies", "=", "[", "]", "if", "max_anom_score", ":", "threshold", "=", "self", ".", "threshold", "or", "max_anom_score", "*", "self", ".", "score_percent_threshold", "# Find all the anomaly intervals.", "intervals", "=", "[", "]", "start", ",", "end", "=", "None", ",", "None", "for", "timestamp", ",", "value", "in", "anom_scores", ".", "iteritems", "(", ")", ":", "if", "value", ">", "threshold", ":", "end", "=", "timestamp", "if", "not", "start", ":", "start", "=", "timestamp", "elif", "start", "and", "end", "is", "not", "None", ":", "intervals", ".", "append", "(", "[", "start", ",", "end", "]", ")", "start", "=", "None", "end", "=", "None", "if", "start", "is", "not", "None", ":", "intervals", ".", "append", "(", "[", "start", ",", "end", "]", ")", "# Locate the exact anomaly point within each anomaly interval.", "for", "interval_start", ",", "interval_end", "in", "intervals", ":", "interval_series", "=", "anom_scores", ".", "crop", "(", "interval_start", ",", "interval_end", ")", "self", ".", "refine_algorithm_params", "[", "'time_series'", "]", "=", "interval_series", "refine_algorithm", "=", "self", ".", "refine_algorithm", "(", "*", "*", "self", ".", "refine_algorithm_params", ")", "scores", "=", "refine_algorithm", ".", "run", "(", ")", "max_refine_score", "=", "scores", ".", "max", "(", ")", "# Get the timestamp of the maximal score.", "max_refine_timestamp", "=", "scores", ".", "timestamps", "[", "scores", ".", "values", ".", "index", "(", "max_refine_score", ")", "]", "anomaly", "=", "Anomaly", "(", "interval_start", ",", "interval_end", ",", "interval_series", ".", "max", "(", ")", ",", "max_refine_timestamp", ")", "anomalies", ".", "append", "(", "anomaly", ")", "self", ".", "anomalies", "=", "anomalies" ]
Detect anomalies using a threshold on anomaly scores.
[ "Detect", "anomalies", "using", "a", "threshold", "on", "anomaly", "scores", "." ]
42e4ab969b774ff98f902d064cb041556017f635
https://github.com/linkedin/luminol/blob/42e4ab969b774ff98f902d064cb041556017f635/src/luminol/anomaly_detector.py#L106-L145
train
235,900
jpoullet2000/atlasclient
atlasclient/exceptions.py
handle_response
def handle_response(response): """ Given a requests.Response object, throw the appropriate exception, if applicable. """ # ignore valid responses if response.status_code < 400: return cls = _status_to_exception_type.get(response.status_code, HttpError) kwargs = { 'code': response.status_code, 'method': response.request.method, 'url': response.request.url, 'details': response.text, } if response.headers and 'retry-after' in response.headers: kwargs['retry_after'] = response.headers.get('retry-after') raise cls(**kwargs)
python
def handle_response(response): """ Given a requests.Response object, throw the appropriate exception, if applicable. """ # ignore valid responses if response.status_code < 400: return cls = _status_to_exception_type.get(response.status_code, HttpError) kwargs = { 'code': response.status_code, 'method': response.request.method, 'url': response.request.url, 'details': response.text, } if response.headers and 'retry-after' in response.headers: kwargs['retry_after'] = response.headers.get('retry-after') raise cls(**kwargs)
[ "def", "handle_response", "(", "response", ")", ":", "# ignore valid responses", "if", "response", ".", "status_code", "<", "400", ":", "return", "cls", "=", "_status_to_exception_type", ".", "get", "(", "response", ".", "status_code", ",", "HttpError", ")", "kwargs", "=", "{", "'code'", ":", "response", ".", "status_code", ",", "'method'", ":", "response", ".", "request", ".", "method", ",", "'url'", ":", "response", ".", "request", ".", "url", ",", "'details'", ":", "response", ".", "text", ",", "}", "if", "response", ".", "headers", "and", "'retry-after'", "in", "response", ".", "headers", ":", "kwargs", "[", "'retry_after'", "]", "=", "response", ".", "headers", ".", "get", "(", "'retry-after'", ")", "raise", "cls", "(", "*", "*", "kwargs", ")" ]
Given a requests.Response object, throw the appropriate exception, if applicable.
[ "Given", "a", "requests", ".", "Response", "object", "throw", "the", "appropriate", "exception", "if", "applicable", "." ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/exceptions.py#L178-L199
train
235,901
jpoullet2000/atlasclient
atlasclient/models.py
EntityBulkCollection.create
def create(self, data, **kwargs): """ Create classifitions for specific entity """ self.client.post(self.url, data=data)
python
def create(self, data, **kwargs): """ Create classifitions for specific entity """ self.client.post(self.url, data=data)
[ "def", "create", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "self", ".", "client", ".", "post", "(", "self", ".", "url", ",", "data", "=", "data", ")" ]
Create classifitions for specific entity
[ "Create", "classifitions", "for", "specific", "entity" ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/models.py#L259-L263
train
235,902
jpoullet2000/atlasclient
atlasclient/models.py
RelationshipGuid.create
def create(self, **kwargs): """Raise error since guid cannot be duplicated """ raise exceptions.MethodNotImplemented(method=self.create, url=self.url, details='GUID cannot be duplicated, to create a new GUID use the relationship resource')
python
def create(self, **kwargs): """Raise error since guid cannot be duplicated """ raise exceptions.MethodNotImplemented(method=self.create, url=self.url, details='GUID cannot be duplicated, to create a new GUID use the relationship resource')
[ "def", "create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "raise", "exceptions", ".", "MethodNotImplemented", "(", "method", "=", "self", ".", "create", ",", "url", "=", "self", ".", "url", ",", "details", "=", "'GUID cannot be duplicated, to create a new GUID use the relationship resource'", ")" ]
Raise error since guid cannot be duplicated
[ "Raise", "error", "since", "guid", "cannot", "be", "duplicated" ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/models.py#L706-L709
train
235,903
jpoullet2000/atlasclient
atlasclient/utils.py
normalize_underscore_case
def normalize_underscore_case(name): """Normalize an underscore-separated descriptor to something more readable. i.e. 'NAGIOS_SERVER' becomes 'Nagios Server', and 'host_components' becomes 'Host Components' """ normalized = name.lower() normalized = re.sub(r'_(\w)', lambda match: ' ' + match.group(1).upper(), normalized) return normalized[0].upper() + normalized[1:]
python
def normalize_underscore_case(name): """Normalize an underscore-separated descriptor to something more readable. i.e. 'NAGIOS_SERVER' becomes 'Nagios Server', and 'host_components' becomes 'Host Components' """ normalized = name.lower() normalized = re.sub(r'_(\w)', lambda match: ' ' + match.group(1).upper(), normalized) return normalized[0].upper() + normalized[1:]
[ "def", "normalize_underscore_case", "(", "name", ")", ":", "normalized", "=", "name", ".", "lower", "(", ")", "normalized", "=", "re", ".", "sub", "(", "r'_(\\w)'", ",", "lambda", "match", ":", "' '", "+", "match", ".", "group", "(", "1", ")", ".", "upper", "(", ")", ",", "normalized", ")", "return", "normalized", "[", "0", "]", ".", "upper", "(", ")", "+", "normalized", "[", "1", ":", "]" ]
Normalize an underscore-separated descriptor to something more readable. i.e. 'NAGIOS_SERVER' becomes 'Nagios Server', and 'host_components' becomes 'Host Components'
[ "Normalize", "an", "underscore", "-", "separated", "descriptor", "to", "something", "more", "readable", "." ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/utils.py#L32-L42
train
235,904
jpoullet2000/atlasclient
atlasclient/utils.py
normalize_camel_case
def normalize_camel_case(name): """Normalize a camelCase descriptor to something more readable. i.e. 'camelCase' or 'CamelCase' becomes 'Camel Case' """ normalized = re.sub('([a-z])([A-Z])', lambda match: ' '.join([match.group(1), match.group(2)]), name) return normalized[0].upper() + normalized[1:]
python
def normalize_camel_case(name): """Normalize a camelCase descriptor to something more readable. i.e. 'camelCase' or 'CamelCase' becomes 'Camel Case' """ normalized = re.sub('([a-z])([A-Z])', lambda match: ' '.join([match.group(1), match.group(2)]), name) return normalized[0].upper() + normalized[1:]
[ "def", "normalize_camel_case", "(", "name", ")", ":", "normalized", "=", "re", ".", "sub", "(", "'([a-z])([A-Z])'", ",", "lambda", "match", ":", "' '", ".", "join", "(", "[", "match", ".", "group", "(", "1", ")", ",", "match", ".", "group", "(", "2", ")", "]", ")", ",", "name", ")", "return", "normalized", "[", "0", "]", ".", "upper", "(", ")", "+", "normalized", "[", "1", ":", "]" ]
Normalize a camelCase descriptor to something more readable. i.e. 'camelCase' or 'CamelCase' becomes 'Camel Case'
[ "Normalize", "a", "camelCase", "descriptor", "to", "something", "more", "readable", "." ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/utils.py#L45-L53
train
235,905
jpoullet2000/atlasclient
atlasclient/utils.py
version_tuple
def version_tuple(version): """Convert a version string or tuple to a tuple. Should be returned in the form: (major, minor, release). """ if isinstance(version, str): return tuple(int(x) for x in version.split('.')) elif isinstance(version, tuple): return version else: raise ValueError("Invalid version: %s" % version)
python
def version_tuple(version): """Convert a version string or tuple to a tuple. Should be returned in the form: (major, minor, release). """ if isinstance(version, str): return tuple(int(x) for x in version.split('.')) elif isinstance(version, tuple): return version else: raise ValueError("Invalid version: %s" % version)
[ "def", "version_tuple", "(", "version", ")", ":", "if", "isinstance", "(", "version", ",", "str", ")", ":", "return", "tuple", "(", "int", "(", "x", ")", "for", "x", "in", "version", ".", "split", "(", "'.'", ")", ")", "elif", "isinstance", "(", "version", ",", "tuple", ")", ":", "return", "version", "else", ":", "raise", "ValueError", "(", "\"Invalid version: %s\"", "%", "version", ")" ]
Convert a version string or tuple to a tuple. Should be returned in the form: (major, minor, release).
[ "Convert", "a", "version", "string", "or", "tuple", "to", "a", "tuple", "." ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/utils.py#L56-L66
train
235,906
jpoullet2000/atlasclient
atlasclient/utils.py
version_str
def version_str(version): """Convert a version tuple or string to a string. Should be returned in the form: major.minor.release """ if isinstance(version, str): return version elif isinstance(version, tuple): return '.'.join([str(int(x)) for x in version]) else: raise ValueError("Invalid version: %s" % version)
python
def version_str(version): """Convert a version tuple or string to a string. Should be returned in the form: major.minor.release """ if isinstance(version, str): return version elif isinstance(version, tuple): return '.'.join([str(int(x)) for x in version]) else: raise ValueError("Invalid version: %s" % version)
[ "def", "version_str", "(", "version", ")", ":", "if", "isinstance", "(", "version", ",", "str", ")", ":", "return", "version", "elif", "isinstance", "(", "version", ",", "tuple", ")", ":", "return", "'.'", ".", "join", "(", "[", "str", "(", "int", "(", "x", ")", ")", "for", "x", "in", "version", "]", ")", "else", ":", "raise", "ValueError", "(", "\"Invalid version: %s\"", "%", "version", ")" ]
Convert a version tuple or string to a string. Should be returned in the form: major.minor.release
[ "Convert", "a", "version", "tuple", "or", "string", "to", "a", "string", "." ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/utils.py#L69-L79
train
235,907
jpoullet2000/atlasclient
atlasclient/utils.py
generate_http_basic_token
def generate_http_basic_token(username, password): """ Generates a HTTP basic token from username and password Returns a token string (not a byte) """ token = base64.b64encode('{}:{}'.format(username, password).encode('utf-8')).decode('utf-8') return token
python
def generate_http_basic_token(username, password): """ Generates a HTTP basic token from username and password Returns a token string (not a byte) """ token = base64.b64encode('{}:{}'.format(username, password).encode('utf-8')).decode('utf-8') return token
[ "def", "generate_http_basic_token", "(", "username", ",", "password", ")", ":", "token", "=", "base64", ".", "b64encode", "(", "'{}:{}'", ".", "format", "(", "username", ",", "password", ")", ".", "encode", "(", "'utf-8'", ")", ")", ".", "decode", "(", "'utf-8'", ")", "return", "token" ]
Generates a HTTP basic token from username and password Returns a token string (not a byte)
[ "Generates", "a", "HTTP", "basic", "token", "from", "username", "and", "password" ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/utils.py#L81-L88
train
235,908
jpoullet2000/atlasclient
atlasclient/base.py
GeneratedIdentifierMixin.identifier
def identifier(self): """These models have server-generated identifiers. If we don't already have it in memory, then assume that it has not yet been generated. """ if self.primary_key not in self._data: return 'Unknown' return str(self._data[self.primary_key])
python
def identifier(self): """These models have server-generated identifiers. If we don't already have it in memory, then assume that it has not yet been generated. """ if self.primary_key not in self._data: return 'Unknown' return str(self._data[self.primary_key])
[ "def", "identifier", "(", "self", ")", ":", "if", "self", ".", "primary_key", "not", "in", "self", ".", "_data", ":", "return", "'Unknown'", "return", "str", "(", "self", ".", "_data", "[", "self", ".", "primary_key", "]", ")" ]
These models have server-generated identifiers. If we don't already have it in memory, then assume that it has not yet been generated.
[ "These", "models", "have", "server", "-", "generated", "identifiers", "." ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/base.py#L79-L87
train
235,909
jpoullet2000/atlasclient
atlasclient/base.py
QueryableModelCollection.url
def url(self): """The url for this collection.""" if self.parent is None: # TODO: differing API Versions? pieces = [self.client.base_url, 'api', 'atlas', 'v2'] else: pieces = [self.parent.url] pieces.append(self.model_class.path) return '/'.join(pieces)
python
def url(self): """The url for this collection.""" if self.parent is None: # TODO: differing API Versions? pieces = [self.client.base_url, 'api', 'atlas', 'v2'] else: pieces = [self.parent.url] pieces.append(self.model_class.path) return '/'.join(pieces)
[ "def", "url", "(", "self", ")", ":", "if", "self", ".", "parent", "is", "None", ":", "# TODO: differing API Versions?", "pieces", "=", "[", "self", ".", "client", ".", "base_url", ",", "'api'", ",", "'atlas'", ",", "'v2'", "]", "else", ":", "pieces", "=", "[", "self", ".", "parent", ".", "url", "]", "pieces", ".", "append", "(", "self", ".", "model_class", ".", "path", ")", "return", "'/'", ".", "join", "(", "pieces", ")" ]
The url for this collection.
[ "The", "url", "for", "this", "collection", "." ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/base.py#L230-L239
train
235,910
jpoullet2000/atlasclient
atlasclient/base.py
QueryableModelCollection.inflate
def inflate(self): """Load the collection from the server, if necessary.""" if not self._is_inflated: self.check_version() for k, v in self._filter.items(): if '[' in v: self._filter[k] = ast.literal_eval(v) self.load(self.client.get(self.url, params=self._filter)) self._is_inflated = True return self
python
def inflate(self): """Load the collection from the server, if necessary.""" if not self._is_inflated: self.check_version() for k, v in self._filter.items(): if '[' in v: self._filter[k] = ast.literal_eval(v) self.load(self.client.get(self.url, params=self._filter)) self._is_inflated = True return self
[ "def", "inflate", "(", "self", ")", ":", "if", "not", "self", ".", "_is_inflated", ":", "self", ".", "check_version", "(", ")", "for", "k", ",", "v", "in", "self", ".", "_filter", ".", "items", "(", ")", ":", "if", "'['", "in", "v", ":", "self", ".", "_filter", "[", "k", "]", "=", "ast", ".", "literal_eval", "(", "v", ")", "self", ".", "load", "(", "self", ".", "client", ".", "get", "(", "self", ".", "url", ",", "params", "=", "self", ".", "_filter", ")", ")", "self", ".", "_is_inflated", "=", "True", "return", "self" ]
Load the collection from the server, if necessary.
[ "Load", "the", "collection", "from", "the", "server", "if", "necessary", "." ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/base.py#L241-L251
train
235,911
jpoullet2000/atlasclient
atlasclient/base.py
QueryableModelCollection.load
def load(self, response): """Parse the GET response for the collection. This operates as a lazy-loader, meaning that the data are only downloaded from the server if there are not already loaded. Collection items are loaded sequentially. In some rare cases, a collection can have an asynchronous request triggered. For those cases, we handle it here. """ self._models = [] if isinstance(response, dict): for key in response.keys(): model = self.model_class(self, href='') model.load(response[key]) self._models.append(model) else: for item in response: model = self.model_class(self, href=item.get('href')) model.load(item) self._models.append(model)
python
def load(self, response): """Parse the GET response for the collection. This operates as a lazy-loader, meaning that the data are only downloaded from the server if there are not already loaded. Collection items are loaded sequentially. In some rare cases, a collection can have an asynchronous request triggered. For those cases, we handle it here. """ self._models = [] if isinstance(response, dict): for key in response.keys(): model = self.model_class(self, href='') model.load(response[key]) self._models.append(model) else: for item in response: model = self.model_class(self, href=item.get('href')) model.load(item) self._models.append(model)
[ "def", "load", "(", "self", ",", "response", ")", ":", "self", ".", "_models", "=", "[", "]", "if", "isinstance", "(", "response", ",", "dict", ")", ":", "for", "key", "in", "response", ".", "keys", "(", ")", ":", "model", "=", "self", ".", "model_class", "(", "self", ",", "href", "=", "''", ")", "model", ".", "load", "(", "response", "[", "key", "]", ")", "self", ".", "_models", ".", "append", "(", "model", ")", "else", ":", "for", "item", "in", "response", ":", "model", "=", "self", ".", "model_class", "(", "self", ",", "href", "=", "item", ".", "get", "(", "'href'", ")", ")", "model", ".", "load", "(", "item", ")", "self", ".", "_models", ".", "append", "(", "model", ")" ]
Parse the GET response for the collection. This operates as a lazy-loader, meaning that the data are only downloaded from the server if there are not already loaded. Collection items are loaded sequentially. In some rare cases, a collection can have an asynchronous request triggered. For those cases, we handle it here.
[ "Parse", "the", "GET", "response", "for", "the", "collection", "." ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/base.py#L254-L275
train
235,912
jpoullet2000/atlasclient
atlasclient/base.py
QueryableModelCollection.create
def create(self, *args, **kwargs): """Add a resource to this collection.""" href = self.url if len(args) == 1: kwargs[self.model_class.primary_key] = args[0] href = '/'.join([href, args[0]]) model = self.model_class(self, href=href.replace('classifications/', 'classification/'), data=kwargs) model.create(**kwargs) self._models.append(model) return model
python
def create(self, *args, **kwargs): """Add a resource to this collection.""" href = self.url if len(args) == 1: kwargs[self.model_class.primary_key] = args[0] href = '/'.join([href, args[0]]) model = self.model_class(self, href=href.replace('classifications/', 'classification/'), data=kwargs) model.create(**kwargs) self._models.append(model) return model
[ "def", "create", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "href", "=", "self", ".", "url", "if", "len", "(", "args", ")", "==", "1", ":", "kwargs", "[", "self", ".", "model_class", ".", "primary_key", "]", "=", "args", "[", "0", "]", "href", "=", "'/'", ".", "join", "(", "[", "href", ",", "args", "[", "0", "]", "]", ")", "model", "=", "self", ".", "model_class", "(", "self", ",", "href", "=", "href", ".", "replace", "(", "'classifications/'", ",", "'classification/'", ")", ",", "data", "=", "kwargs", ")", "model", ".", "create", "(", "*", "*", "kwargs", ")", "self", ".", "_models", ".", "append", "(", "model", ")", "return", "model" ]
Add a resource to this collection.
[ "Add", "a", "resource", "to", "this", "collection", "." ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/base.py#L277-L288
train
235,913
jpoullet2000/atlasclient
atlasclient/base.py
QueryableModelCollection.update
def update(self, **kwargs): """Update all resources in this collection.""" self.inflate() for model in self._models: model.update(**kwargs) return self
python
def update(self, **kwargs): """Update all resources in this collection.""" self.inflate() for model in self._models: model.update(**kwargs) return self
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "inflate", "(", ")", "for", "model", "in", "self", ".", "_models", ":", "model", ".", "update", "(", "*", "*", "kwargs", ")", "return", "self" ]
Update all resources in this collection.
[ "Update", "all", "resources", "in", "this", "collection", "." ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/base.py#L290-L295
train
235,914
jpoullet2000/atlasclient
atlasclient/base.py
QueryableModelCollection.delete
def delete(self, **kwargs): """Delete all resources in this collection.""" self.inflate() for model in self._models: model.delete(**kwargs) return
python
def delete(self, **kwargs): """Delete all resources in this collection.""" self.inflate() for model in self._models: model.delete(**kwargs) return
[ "def", "delete", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "inflate", "(", ")", "for", "model", "in", "self", ".", "_models", ":", "model", ".", "delete", "(", "*", "*", "kwargs", ")", "return" ]
Delete all resources in this collection.
[ "Delete", "all", "resources", "in", "this", "collection", "." ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/base.py#L297-L302
train
235,915
jpoullet2000/atlasclient
atlasclient/base.py
QueryableModelCollection.wait
def wait(self, **kwargs): """Wait until any pending asynchronous requests are finished for this collection.""" if self.request: self.request.wait(**kwargs) self.request = None return self.inflate()
python
def wait(self, **kwargs): """Wait until any pending asynchronous requests are finished for this collection.""" if self.request: self.request.wait(**kwargs) self.request = None return self.inflate()
[ "def", "wait", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "request", ":", "self", ".", "request", ".", "wait", "(", "*", "*", "kwargs", ")", "self", ".", "request", "=", "None", "return", "self", ".", "inflate", "(", ")" ]
Wait until any pending asynchronous requests are finished for this collection.
[ "Wait", "until", "any", "pending", "asynchronous", "requests", "are", "finished", "for", "this", "collection", "." ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/base.py#L305-L310
train
235,916
jpoullet2000/atlasclient
atlasclient/base.py
QueryableModel.url
def url(self): """Gets the url for the resource this model represents. It will just use the 'href' passed in to the constructor if that exists. Otherwise, it will generated it based on the collection's url and the model's identifier. """ if self._href is not None: return self._href if self.identifier: # for some reason atlas does not use classifications here in the path when considering one classification path = '/'.join([self.parent.url.replace('classifications/', 'classficiation/'), self.identifier]) return path raise exceptions.ClientError("Not able to determine object URL")
python
def url(self): """Gets the url for the resource this model represents. It will just use the 'href' passed in to the constructor if that exists. Otherwise, it will generated it based on the collection's url and the model's identifier. """ if self._href is not None: return self._href if self.identifier: # for some reason atlas does not use classifications here in the path when considering one classification path = '/'.join([self.parent.url.replace('classifications/', 'classficiation/'), self.identifier]) return path raise exceptions.ClientError("Not able to determine object URL")
[ "def", "url", "(", "self", ")", ":", "if", "self", ".", "_href", "is", "not", "None", ":", "return", "self", ".", "_href", "if", "self", ".", "identifier", ":", "# for some reason atlas does not use classifications here in the path when considering one classification", "path", "=", "'/'", ".", "join", "(", "[", "self", ".", "parent", ".", "url", ".", "replace", "(", "'classifications/'", ",", "'classficiation/'", ")", ",", "self", ".", "identifier", "]", ")", "return", "path", "raise", "exceptions", ".", "ClientError", "(", "\"Not able to determine object URL\"", ")" ]
Gets the url for the resource this model represents. It will just use the 'href' passed in to the constructor if that exists. Otherwise, it will generated it based on the collection's url and the model's identifier.
[ "Gets", "the", "url", "for", "the", "resource", "this", "model", "represents", "." ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/base.py#L568-L581
train
235,917
jpoullet2000/atlasclient
atlasclient/base.py
QueryableModel.inflate
def inflate(self): """Load the resource from the server, if not already loaded.""" if not self._is_inflated: if self._is_inflating: # catch infinite recursion when attempting to inflate # an object that doesn't have enough data to inflate msg = ("There is not enough data to inflate this object. " "Need either an href: {} or a {}: {}") msg = msg.format(self._href, self.primary_key, self._data.get(self.primary_key)) raise exceptions.ClientError(msg) self._is_inflating = True try: params = self.searchParameters if hasattr(self, 'searchParameters') else {} # To keep the method same as the original request. The default is GET self.load(self.client.request(self.method, self.url, **params)) except Exception: self.load(self._data) self._is_inflated = True self._is_inflating = False return self
python
def inflate(self): """Load the resource from the server, if not already loaded.""" if not self._is_inflated: if self._is_inflating: # catch infinite recursion when attempting to inflate # an object that doesn't have enough data to inflate msg = ("There is not enough data to inflate this object. " "Need either an href: {} or a {}: {}") msg = msg.format(self._href, self.primary_key, self._data.get(self.primary_key)) raise exceptions.ClientError(msg) self._is_inflating = True try: params = self.searchParameters if hasattr(self, 'searchParameters') else {} # To keep the method same as the original request. The default is GET self.load(self.client.request(self.method, self.url, **params)) except Exception: self.load(self._data) self._is_inflated = True self._is_inflating = False return self
[ "def", "inflate", "(", "self", ")", ":", "if", "not", "self", ".", "_is_inflated", ":", "if", "self", ".", "_is_inflating", ":", "# catch infinite recursion when attempting to inflate", "# an object that doesn't have enough data to inflate", "msg", "=", "(", "\"There is not enough data to inflate this object. \"", "\"Need either an href: {} or a {}: {}\"", ")", "msg", "=", "msg", ".", "format", "(", "self", ".", "_href", ",", "self", ".", "primary_key", ",", "self", ".", "_data", ".", "get", "(", "self", ".", "primary_key", ")", ")", "raise", "exceptions", ".", "ClientError", "(", "msg", ")", "self", ".", "_is_inflating", "=", "True", "try", ":", "params", "=", "self", ".", "searchParameters", "if", "hasattr", "(", "self", ",", "'searchParameters'", ")", "else", "{", "}", "# To keep the method same as the original request. The default is GET", "self", ".", "load", "(", "self", ".", "client", ".", "request", "(", "self", ".", "method", ",", "self", ".", "url", ",", "*", "*", "params", ")", ")", "except", "Exception", ":", "self", ".", "load", "(", "self", ".", "_data", ")", "self", ".", "_is_inflated", "=", "True", "self", ".", "_is_inflating", "=", "False", "return", "self" ]
Load the resource from the server, if not already loaded.
[ "Load", "the", "resource", "from", "the", "server", "if", "not", "already", "loaded", "." ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/base.py#L583-L605
train
235,918
jpoullet2000/atlasclient
atlasclient/base.py
QueryableModel.load
def load(self, response): """The load method parses the raw JSON response from the server. Most models are not returned in the main response body, but in a key such as 'entity', defined by the 'data_key' attribute on the class. Also, related objects are often returned and can be used to pre-cache related model objects without having to contact the server again. This method handles all of those cases. Also, if a request has triggered a background operation, the request details are returned in a 'Requests' section. We need to store that request object so we can poll it until completion. """ if 'href' in response: self._href = response.pop('href') if self.data_key and self.data_key in response: self._data.update(response.pop(self.data_key)) # preload related object collections, if received for rel in [x for x in self.relationships if x in response and response[x]]: rel_class = self.relationships[rel] collection = rel_class.collection_class( self.client, rel_class, parent=self ) self._relationship_cache[rel] = collection(response[rel]) else: self._data.update(response)
python
def load(self, response): """The load method parses the raw JSON response from the server. Most models are not returned in the main response body, but in a key such as 'entity', defined by the 'data_key' attribute on the class. Also, related objects are often returned and can be used to pre-cache related model objects without having to contact the server again. This method handles all of those cases. Also, if a request has triggered a background operation, the request details are returned in a 'Requests' section. We need to store that request object so we can poll it until completion. """ if 'href' in response: self._href = response.pop('href') if self.data_key and self.data_key in response: self._data.update(response.pop(self.data_key)) # preload related object collections, if received for rel in [x for x in self.relationships if x in response and response[x]]: rel_class = self.relationships[rel] collection = rel_class.collection_class( self.client, rel_class, parent=self ) self._relationship_cache[rel] = collection(response[rel]) else: self._data.update(response)
[ "def", "load", "(", "self", ",", "response", ")", ":", "if", "'href'", "in", "response", ":", "self", ".", "_href", "=", "response", ".", "pop", "(", "'href'", ")", "if", "self", ".", "data_key", "and", "self", ".", "data_key", "in", "response", ":", "self", ".", "_data", ".", "update", "(", "response", ".", "pop", "(", "self", ".", "data_key", ")", ")", "# preload related object collections, if received", "for", "rel", "in", "[", "x", "for", "x", "in", "self", ".", "relationships", "if", "x", "in", "response", "and", "response", "[", "x", "]", "]", ":", "rel_class", "=", "self", ".", "relationships", "[", "rel", "]", "collection", "=", "rel_class", ".", "collection_class", "(", "self", ".", "client", ",", "rel_class", ",", "parent", "=", "self", ")", "self", ".", "_relationship_cache", "[", "rel", "]", "=", "collection", "(", "response", "[", "rel", "]", ")", "else", ":", "self", ".", "_data", ".", "update", "(", "response", ")" ]
The load method parses the raw JSON response from the server. Most models are not returned in the main response body, but in a key such as 'entity', defined by the 'data_key' attribute on the class. Also, related objects are often returned and can be used to pre-cache related model objects without having to contact the server again. This method handles all of those cases. Also, if a request has triggered a background operation, the request details are returned in a 'Requests' section. We need to store that request object so we can poll it until completion.
[ "The", "load", "method", "parses", "the", "raw", "JSON", "response", "from", "the", "server", "." ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/base.py#L623-L648
train
235,919
jpoullet2000/atlasclient
atlasclient/base.py
QueryableModel.delete
def delete(self, **kwargs): """Delete a resource by issuing a DELETE http request against it.""" self.method = 'delete' if len(kwargs) > 0: self.load(self.client.delete(self.url, params=kwargs)) else: self.load(self.client.delete(self.url)) self.parent.remove(self) return
python
def delete(self, **kwargs): """Delete a resource by issuing a DELETE http request against it.""" self.method = 'delete' if len(kwargs) > 0: self.load(self.client.delete(self.url, params=kwargs)) else: self.load(self.client.delete(self.url)) self.parent.remove(self) return
[ "def", "delete", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "method", "=", "'delete'", "if", "len", "(", "kwargs", ")", ">", "0", ":", "self", ".", "load", "(", "self", ".", "client", ".", "delete", "(", "self", ".", "url", ",", "params", "=", "kwargs", ")", ")", "else", ":", "self", ".", "load", "(", "self", ".", "client", ".", "delete", "(", "self", ".", "url", ")", ")", "self", ".", "parent", ".", "remove", "(", "self", ")", "return" ]
Delete a resource by issuing a DELETE http request against it.
[ "Delete", "a", "resource", "by", "issuing", "a", "DELETE", "http", "request", "against", "it", "." ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/base.py#L686-L694
train
235,920
jpoullet2000/atlasclient
atlasclient/events.py
publish
def publish(obj, event, event_state, **kwargs): """Publish an event from an object. This is a really basic pub-sub event system to allow for tracking progress on methods externally. It fires the events for the first match it finds in the object hierarchy, going most specific to least. If no match is found for the exact event+event_state, the most specific event+ANY is fired instead. Multiple callbacks can be bound to the event+event_state if desired. All will be fired in the order they were registered. """ # short-circuit if nothing is listening if len(EVENT_HANDLERS) == 0: return if inspect.isclass(obj): pub_cls = obj else: pub_cls = obj.__class__ potential = [x.__name__ for x in inspect.getmro(pub_cls)] # if we don't find a match for this event/event_state we fire the events # for this event/ANY instead for the closest match fallbacks = None callbacks = [] for cls in potential: event_key = '.'.join([cls, event, event_state]) backup_key = '.'.join([cls, event, states.ANY]) if event_key in EVENT_HANDLERS: callbacks = EVENT_HANDLERS[event_key] break elif fallbacks is None and backup_key in EVENT_HANDLERS: fallbacks = EVENT_HANDLERS[backup_key] if fallbacks is not None: callbacks = fallbacks for callback in callbacks: callback(obj, **kwargs) return
python
def publish(obj, event, event_state, **kwargs): """Publish an event from an object. This is a really basic pub-sub event system to allow for tracking progress on methods externally. It fires the events for the first match it finds in the object hierarchy, going most specific to least. If no match is found for the exact event+event_state, the most specific event+ANY is fired instead. Multiple callbacks can be bound to the event+event_state if desired. All will be fired in the order they were registered. """ # short-circuit if nothing is listening if len(EVENT_HANDLERS) == 0: return if inspect.isclass(obj): pub_cls = obj else: pub_cls = obj.__class__ potential = [x.__name__ for x in inspect.getmro(pub_cls)] # if we don't find a match for this event/event_state we fire the events # for this event/ANY instead for the closest match fallbacks = None callbacks = [] for cls in potential: event_key = '.'.join([cls, event, event_state]) backup_key = '.'.join([cls, event, states.ANY]) if event_key in EVENT_HANDLERS: callbacks = EVENT_HANDLERS[event_key] break elif fallbacks is None and backup_key in EVENT_HANDLERS: fallbacks = EVENT_HANDLERS[backup_key] if fallbacks is not None: callbacks = fallbacks for callback in callbacks: callback(obj, **kwargs) return
[ "def", "publish", "(", "obj", ",", "event", ",", "event_state", ",", "*", "*", "kwargs", ")", ":", "# short-circuit if nothing is listening", "if", "len", "(", "EVENT_HANDLERS", ")", "==", "0", ":", "return", "if", "inspect", ".", "isclass", "(", "obj", ")", ":", "pub_cls", "=", "obj", "else", ":", "pub_cls", "=", "obj", ".", "__class__", "potential", "=", "[", "x", ".", "__name__", "for", "x", "in", "inspect", ".", "getmro", "(", "pub_cls", ")", "]", "# if we don't find a match for this event/event_state we fire the events", "# for this event/ANY instead for the closest match", "fallbacks", "=", "None", "callbacks", "=", "[", "]", "for", "cls", "in", "potential", ":", "event_key", "=", "'.'", ".", "join", "(", "[", "cls", ",", "event", ",", "event_state", "]", ")", "backup_key", "=", "'.'", ".", "join", "(", "[", "cls", ",", "event", ",", "states", ".", "ANY", "]", ")", "if", "event_key", "in", "EVENT_HANDLERS", ":", "callbacks", "=", "EVENT_HANDLERS", "[", "event_key", "]", "break", "elif", "fallbacks", "is", "None", "and", "backup_key", "in", "EVENT_HANDLERS", ":", "fallbacks", "=", "EVENT_HANDLERS", "[", "backup_key", "]", "if", "fallbacks", "is", "not", "None", ":", "callbacks", "=", "fallbacks", "for", "callback", "in", "callbacks", ":", "callback", "(", "obj", ",", "*", "*", "kwargs", ")", "return" ]
Publish an event from an object. This is a really basic pub-sub event system to allow for tracking progress on methods externally. It fires the events for the first match it finds in the object hierarchy, going most specific to least. If no match is found for the exact event+event_state, the most specific event+ANY is fired instead. Multiple callbacks can be bound to the event+event_state if desired. All will be fired in the order they were registered.
[ "Publish", "an", "event", "from", "an", "object", "." ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/events.py#L41-L81
train
235,921
jpoullet2000/atlasclient
atlasclient/events.py
subscribe
def subscribe(obj, event, callback, event_state=None): """Subscribe an event from an class. Subclasses of the class/object will also fire events for this class, unless a more specific event exists. """ if inspect.isclass(obj): cls = obj.__name__ else: cls = obj.__class__.__name__ if event_state is None: event_state = states.ANY event_key = '.'.join([cls, event, event_state]) if event_key not in EVENT_HANDLERS: EVENT_HANDLERS[event_key] = [] EVENT_HANDLERS[event_key].append(callback) return
python
def subscribe(obj, event, callback, event_state=None): """Subscribe an event from an class. Subclasses of the class/object will also fire events for this class, unless a more specific event exists. """ if inspect.isclass(obj): cls = obj.__name__ else: cls = obj.__class__.__name__ if event_state is None: event_state = states.ANY event_key = '.'.join([cls, event, event_state]) if event_key not in EVENT_HANDLERS: EVENT_HANDLERS[event_key] = [] EVENT_HANDLERS[event_key].append(callback) return
[ "def", "subscribe", "(", "obj", ",", "event", ",", "callback", ",", "event_state", "=", "None", ")", ":", "if", "inspect", ".", "isclass", "(", "obj", ")", ":", "cls", "=", "obj", ".", "__name__", "else", ":", "cls", "=", "obj", ".", "__class__", ".", "__name__", "if", "event_state", "is", "None", ":", "event_state", "=", "states", ".", "ANY", "event_key", "=", "'.'", ".", "join", "(", "[", "cls", ",", "event", ",", "event_state", "]", ")", "if", "event_key", "not", "in", "EVENT_HANDLERS", ":", "EVENT_HANDLERS", "[", "event_key", "]", "=", "[", "]", "EVENT_HANDLERS", "[", "event_key", "]", ".", "append", "(", "callback", ")", "return" ]
Subscribe an event from an class. Subclasses of the class/object will also fire events for this class, unless a more specific event exists.
[ "Subscribe", "an", "event", "from", "an", "class", "." ]
4548b441143ebf7fc4075d113db5ca5a23e0eed2
https://github.com/jpoullet2000/atlasclient/blob/4548b441143ebf7fc4075d113db5ca5a23e0eed2/atlasclient/events.py#L84-L103
train
235,922
psolin/cleanco
cleanco.py
cleanco.clean_name
def clean_name(self, suffix=True, prefix=False, middle=False, multi=False): "return cleared version of the business name" name = self.business_name # Run it through the string_stripper once more name = self.string_stripper(name) loname = name.lower() # return name without suffixed/prefixed/middle type term(s) for item in suffix_sort: if suffix: if loname.endswith(" " + item): start = loname.find(item) end = len(item) name = name[0:-end-1] name = self.string_stripper(name) if multi==False: break if prefix: if loname.startswith(item+' '): name = name[len(item)+1:] if multi==False: break if middle: term = ' ' + item + ' ' if term in loname: start = loname.find(term) end = start + len(term) name = name[:start] + " " + name[end:] if multi==False: break return self.string_stripper(name)
python
def clean_name(self, suffix=True, prefix=False, middle=False, multi=False): "return cleared version of the business name" name = self.business_name # Run it through the string_stripper once more name = self.string_stripper(name) loname = name.lower() # return name without suffixed/prefixed/middle type term(s) for item in suffix_sort: if suffix: if loname.endswith(" " + item): start = loname.find(item) end = len(item) name = name[0:-end-1] name = self.string_stripper(name) if multi==False: break if prefix: if loname.startswith(item+' '): name = name[len(item)+1:] if multi==False: break if middle: term = ' ' + item + ' ' if term in loname: start = loname.find(term) end = start + len(term) name = name[:start] + " " + name[end:] if multi==False: break return self.string_stripper(name)
[ "def", "clean_name", "(", "self", ",", "suffix", "=", "True", ",", "prefix", "=", "False", ",", "middle", "=", "False", ",", "multi", "=", "False", ")", ":", "name", "=", "self", ".", "business_name", "# Run it through the string_stripper once more", "name", "=", "self", ".", "string_stripper", "(", "name", ")", "loname", "=", "name", ".", "lower", "(", ")", "# return name without suffixed/prefixed/middle type term(s)", "for", "item", "in", "suffix_sort", ":", "if", "suffix", ":", "if", "loname", ".", "endswith", "(", "\" \"", "+", "item", ")", ":", "start", "=", "loname", ".", "find", "(", "item", ")", "end", "=", "len", "(", "item", ")", "name", "=", "name", "[", "0", ":", "-", "end", "-", "1", "]", "name", "=", "self", ".", "string_stripper", "(", "name", ")", "if", "multi", "==", "False", ":", "break", "if", "prefix", ":", "if", "loname", ".", "startswith", "(", "item", "+", "' '", ")", ":", "name", "=", "name", "[", "len", "(", "item", ")", "+", "1", ":", "]", "if", "multi", "==", "False", ":", "break", "if", "middle", ":", "term", "=", "' '", "+", "item", "+", "' '", "if", "term", "in", "loname", ":", "start", "=", "loname", ".", "find", "(", "term", ")", "end", "=", "start", "+", "len", "(", "term", ")", "name", "=", "name", "[", ":", "start", "]", "+", "\" \"", "+", "name", "[", "end", ":", "]", "if", "multi", "==", "False", ":", "break", "return", "self", ".", "string_stripper", "(", "name", ")" ]
return cleared version of the business name
[ "return", "cleared", "version", "of", "the", "business", "name" ]
56ff6542c339df625adcaf7f4ed4c81035fd575a
https://github.com/psolin/cleanco/blob/56ff6542c339df625adcaf7f4ed4c81035fd575a/cleanco.py#L70-L104
train
235,923
mosdef-hub/foyer
foyer/smarts_graph.py
SMARTSGraph._add_nodes
def _add_nodes(self): """Add all atoms in the SMARTS string as nodes in the graph.""" for n, atom in enumerate(self.ast.select('atom')): self.add_node(n, atom=atom) self._atom_indices[id(atom)] = n
python
def _add_nodes(self): """Add all atoms in the SMARTS string as nodes in the graph.""" for n, atom in enumerate(self.ast.select('atom')): self.add_node(n, atom=atom) self._atom_indices[id(atom)] = n
[ "def", "_add_nodes", "(", "self", ")", ":", "for", "n", ",", "atom", "in", "enumerate", "(", "self", ".", "ast", ".", "select", "(", "'atom'", ")", ")", ":", "self", ".", "add_node", "(", "n", ",", "atom", "=", "atom", ")", "self", ".", "_atom_indices", "[", "id", "(", "atom", ")", "]", "=", "n" ]
Add all atoms in the SMARTS string as nodes in the graph.
[ "Add", "all", "atoms", "in", "the", "SMARTS", "string", "as", "nodes", "in", "the", "graph", "." ]
9e39c71208fc01a6cc7b7cbe5a533c56830681d3
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/smarts_graph.py#L51-L55
train
235,924
mosdef-hub/foyer
foyer/smarts_graph.py
SMARTSGraph._add_edges
def _add_edges(self, ast_node, trunk=None): """"Add all bonds in the SMARTS string as edges in the graph.""" atom_indices = self._atom_indices for atom in ast_node.tail: if atom.head == 'atom': atom_idx = atom_indices[id(atom)] if atom.is_first_kid and atom.parent().head == 'branch': trunk_idx = atom_indices[id(trunk)] self.add_edge(atom_idx, trunk_idx) if not atom.is_last_kid: if atom.next_kid.head == 'atom': next_idx = atom_indices[id(atom.next_kid)] self.add_edge(atom_idx, next_idx) elif atom.next_kid.head == 'branch': trunk = atom else: # We traveled through the whole branch. return elif atom.head == 'branch': self._add_edges(atom, trunk)
python
def _add_edges(self, ast_node, trunk=None): """"Add all bonds in the SMARTS string as edges in the graph.""" atom_indices = self._atom_indices for atom in ast_node.tail: if atom.head == 'atom': atom_idx = atom_indices[id(atom)] if atom.is_first_kid and atom.parent().head == 'branch': trunk_idx = atom_indices[id(trunk)] self.add_edge(atom_idx, trunk_idx) if not atom.is_last_kid: if atom.next_kid.head == 'atom': next_idx = atom_indices[id(atom.next_kid)] self.add_edge(atom_idx, next_idx) elif atom.next_kid.head == 'branch': trunk = atom else: # We traveled through the whole branch. return elif atom.head == 'branch': self._add_edges(atom, trunk)
[ "def", "_add_edges", "(", "self", ",", "ast_node", ",", "trunk", "=", "None", ")", ":", "atom_indices", "=", "self", ".", "_atom_indices", "for", "atom", "in", "ast_node", ".", "tail", ":", "if", "atom", ".", "head", "==", "'atom'", ":", "atom_idx", "=", "atom_indices", "[", "id", "(", "atom", ")", "]", "if", "atom", ".", "is_first_kid", "and", "atom", ".", "parent", "(", ")", ".", "head", "==", "'branch'", ":", "trunk_idx", "=", "atom_indices", "[", "id", "(", "trunk", ")", "]", "self", ".", "add_edge", "(", "atom_idx", ",", "trunk_idx", ")", "if", "not", "atom", ".", "is_last_kid", ":", "if", "atom", ".", "next_kid", ".", "head", "==", "'atom'", ":", "next_idx", "=", "atom_indices", "[", "id", "(", "atom", ".", "next_kid", ")", "]", "self", ".", "add_edge", "(", "atom_idx", ",", "next_idx", ")", "elif", "atom", ".", "next_kid", ".", "head", "==", "'branch'", ":", "trunk", "=", "atom", "else", ":", "# We traveled through the whole branch.", "return", "elif", "atom", ".", "head", "==", "'branch'", ":", "self", ".", "_add_edges", "(", "atom", ",", "trunk", ")" ]
Add all bonds in the SMARTS string as edges in the graph.
[ "Add", "all", "bonds", "in", "the", "SMARTS", "string", "as", "edges", "in", "the", "graph", "." ]
9e39c71208fc01a6cc7b7cbe5a533c56830681d3
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/smarts_graph.py#L57-L75
train
235,925
mosdef-hub/foyer
foyer/smarts_graph.py
SMARTSGraph._add_label_edges
def _add_label_edges(self): """Add edges between all atoms with the same atom_label in rings.""" labels = self.ast.select('atom_label') if not labels: return # We need each individual label and atoms with multiple ring labels # would yield e.g. the string '12' so split those up. label_digits = defaultdict(list) for label in labels: digits = list(label.tail[0]) for digit in digits: label_digits[digit].append(label.parent()) for label, (atom1, atom2) in label_digits.items(): atom1_idx = self._atom_indices[id(atom1)] atom2_idx = self._atom_indices[id(atom2)] self.add_edge(atom1_idx, atom2_idx)
python
def _add_label_edges(self): """Add edges between all atoms with the same atom_label in rings.""" labels = self.ast.select('atom_label') if not labels: return # We need each individual label and atoms with multiple ring labels # would yield e.g. the string '12' so split those up. label_digits = defaultdict(list) for label in labels: digits = list(label.tail[0]) for digit in digits: label_digits[digit].append(label.parent()) for label, (atom1, atom2) in label_digits.items(): atom1_idx = self._atom_indices[id(atom1)] atom2_idx = self._atom_indices[id(atom2)] self.add_edge(atom1_idx, atom2_idx)
[ "def", "_add_label_edges", "(", "self", ")", ":", "labels", "=", "self", ".", "ast", ".", "select", "(", "'atom_label'", ")", "if", "not", "labels", ":", "return", "# We need each individual label and atoms with multiple ring labels", "# would yield e.g. the string '12' so split those up.", "label_digits", "=", "defaultdict", "(", "list", ")", "for", "label", "in", "labels", ":", "digits", "=", "list", "(", "label", ".", "tail", "[", "0", "]", ")", "for", "digit", "in", "digits", ":", "label_digits", "[", "digit", "]", ".", "append", "(", "label", ".", "parent", "(", ")", ")", "for", "label", ",", "(", "atom1", ",", "atom2", ")", "in", "label_digits", ".", "items", "(", ")", ":", "atom1_idx", "=", "self", ".", "_atom_indices", "[", "id", "(", "atom1", ")", "]", "atom2_idx", "=", "self", ".", "_atom_indices", "[", "id", "(", "atom2", ")", "]", "self", ".", "add_edge", "(", "atom1_idx", ",", "atom2_idx", ")" ]
Add edges between all atoms with the same atom_label in rings.
[ "Add", "edges", "between", "all", "atoms", "with", "the", "same", "atom_label", "in", "rings", "." ]
9e39c71208fc01a6cc7b7cbe5a533c56830681d3
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/smarts_graph.py#L77-L94
train
235,926
mosdef-hub/foyer
foyer/smarts_graph.py
SMARTSGraph.find_matches
def find_matches(self, topology): """Return sets of atoms that match this SMARTS pattern in a topology. Notes: ------ When this function gets used in atomtyper.py, we actively modify the white- and blacklists of the atoms in `topology` after finding a match. This means that between every successive call of `subgraph_isomorphisms_iter()`, the topology against which we are matching may have actually changed. Currently, we take advantage of this behavior in some edges cases (e.g. see `test_hexa_coordinated` in `test_smarts.py`). """ # Note: Needs to be updated in sync with the grammar in `smarts.py`. ring_tokens = ['ring_size', 'ring_count'] has_ring_rules = any(self.ast.select(token) for token in ring_tokens) _prepare_atoms(topology, compute_cycles=has_ring_rules) top_graph = nx.Graph() top_graph.add_nodes_from(((a.index, {'atom': a}) for a in topology.atoms())) top_graph.add_edges_from(((b[0].index, b[1].index) for b in topology.bonds())) if self._graph_matcher is None: atom = nx.get_node_attributes(self, name='atom')[0] if len(atom.select('atom_symbol')) == 1 and not atom.select('not_expression'): try: element = atom.select('atom_symbol').strees[0].tail[0] except IndexError: try: atomic_num = atom.select('atomic_num').strees[0].tail[0] element = pt.Element[int(atomic_num)] except IndexError: element = None else: element = None self._graph_matcher = SMARTSMatcher(top_graph, self, node_match=self._node_match, element=element) matched_atoms = set() for mapping in self._graph_matcher.subgraph_isomorphisms_iter(): mapping = {node_id: atom_id for atom_id, node_id in mapping.items()} # The first node in the smarts graph always corresponds to the atom # that we are trying to match. atom_index = mapping[0] # Don't yield duplicate matches found via matching the pattern in a # different order. if atom_index not in matched_atoms: matched_atoms.add(atom_index) yield atom_index
python
def find_matches(self, topology): """Return sets of atoms that match this SMARTS pattern in a topology. Notes: ------ When this function gets used in atomtyper.py, we actively modify the white- and blacklists of the atoms in `topology` after finding a match. This means that between every successive call of `subgraph_isomorphisms_iter()`, the topology against which we are matching may have actually changed. Currently, we take advantage of this behavior in some edges cases (e.g. see `test_hexa_coordinated` in `test_smarts.py`). """ # Note: Needs to be updated in sync with the grammar in `smarts.py`. ring_tokens = ['ring_size', 'ring_count'] has_ring_rules = any(self.ast.select(token) for token in ring_tokens) _prepare_atoms(topology, compute_cycles=has_ring_rules) top_graph = nx.Graph() top_graph.add_nodes_from(((a.index, {'atom': a}) for a in topology.atoms())) top_graph.add_edges_from(((b[0].index, b[1].index) for b in topology.bonds())) if self._graph_matcher is None: atom = nx.get_node_attributes(self, name='atom')[0] if len(atom.select('atom_symbol')) == 1 and not atom.select('not_expression'): try: element = atom.select('atom_symbol').strees[0].tail[0] except IndexError: try: atomic_num = atom.select('atomic_num').strees[0].tail[0] element = pt.Element[int(atomic_num)] except IndexError: element = None else: element = None self._graph_matcher = SMARTSMatcher(top_graph, self, node_match=self._node_match, element=element) matched_atoms = set() for mapping in self._graph_matcher.subgraph_isomorphisms_iter(): mapping = {node_id: atom_id for atom_id, node_id in mapping.items()} # The first node in the smarts graph always corresponds to the atom # that we are trying to match. atom_index = mapping[0] # Don't yield duplicate matches found via matching the pattern in a # different order. if atom_index not in matched_atoms: matched_atoms.add(atom_index) yield atom_index
[ "def", "find_matches", "(", "self", ",", "topology", ")", ":", "# Note: Needs to be updated in sync with the grammar in `smarts.py`.", "ring_tokens", "=", "[", "'ring_size'", ",", "'ring_count'", "]", "has_ring_rules", "=", "any", "(", "self", ".", "ast", ".", "select", "(", "token", ")", "for", "token", "in", "ring_tokens", ")", "_prepare_atoms", "(", "topology", ",", "compute_cycles", "=", "has_ring_rules", ")", "top_graph", "=", "nx", ".", "Graph", "(", ")", "top_graph", ".", "add_nodes_from", "(", "(", "(", "a", ".", "index", ",", "{", "'atom'", ":", "a", "}", ")", "for", "a", "in", "topology", ".", "atoms", "(", ")", ")", ")", "top_graph", ".", "add_edges_from", "(", "(", "(", "b", "[", "0", "]", ".", "index", ",", "b", "[", "1", "]", ".", "index", ")", "for", "b", "in", "topology", ".", "bonds", "(", ")", ")", ")", "if", "self", ".", "_graph_matcher", "is", "None", ":", "atom", "=", "nx", ".", "get_node_attributes", "(", "self", ",", "name", "=", "'atom'", ")", "[", "0", "]", "if", "len", "(", "atom", ".", "select", "(", "'atom_symbol'", ")", ")", "==", "1", "and", "not", "atom", ".", "select", "(", "'not_expression'", ")", ":", "try", ":", "element", "=", "atom", ".", "select", "(", "'atom_symbol'", ")", ".", "strees", "[", "0", "]", ".", "tail", "[", "0", "]", "except", "IndexError", ":", "try", ":", "atomic_num", "=", "atom", ".", "select", "(", "'atomic_num'", ")", ".", "strees", "[", "0", "]", ".", "tail", "[", "0", "]", "element", "=", "pt", ".", "Element", "[", "int", "(", "atomic_num", ")", "]", "except", "IndexError", ":", "element", "=", "None", "else", ":", "element", "=", "None", "self", ".", "_graph_matcher", "=", "SMARTSMatcher", "(", "top_graph", ",", "self", ",", "node_match", "=", "self", ".", "_node_match", ",", "element", "=", "element", ")", "matched_atoms", "=", "set", "(", ")", "for", "mapping", "in", "self", ".", "_graph_matcher", ".", "subgraph_isomorphisms_iter", "(", ")", ":", "mapping", "=", "{", "node_id", ":", "atom_id", "for", "atom_id", ",", "node_id", "in", "mapping", ".", "items", "(", ")", "}", "# The first node in the smarts graph always corresponds to the atom", "# that we are trying to match.", "atom_index", "=", "mapping", "[", "0", "]", "# Don't yield duplicate matches found via matching the pattern in a", "# different order.", "if", "atom_index", "not", "in", "matched_atoms", ":", "matched_atoms", ".", "add", "(", "atom_index", ")", "yield", "atom_index" ]
Return sets of atoms that match this SMARTS pattern in a topology. Notes: ------ When this function gets used in atomtyper.py, we actively modify the white- and blacklists of the atoms in `topology` after finding a match. This means that between every successive call of `subgraph_isomorphisms_iter()`, the topology against which we are matching may have actually changed. Currently, we take advantage of this behavior in some edges cases (e.g. see `test_hexa_coordinated` in `test_smarts.py`).
[ "Return", "sets", "of", "atoms", "that", "match", "this", "SMARTS", "pattern", "in", "a", "topology", "." ]
9e39c71208fc01a6cc7b7cbe5a533c56830681d3
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/smarts_graph.py#L150-L203
train
235,927
mosdef-hub/foyer
foyer/smarts_graph.py
SMARTSMatcher.candidate_pairs_iter
def candidate_pairs_iter(self): """Iterator over candidate pairs of nodes in G1 and G2.""" # All computations are done using the current state! G2_nodes = self.G2_nodes # First we compute the inout-terminal sets. T1_inout = set(self.inout_1.keys()) - set(self.core_1.keys()) T2_inout = set(self.inout_2.keys()) - set(self.core_2.keys()) # If T1_inout and T2_inout are both nonempty. # P(s) = T1_inout x {min T2_inout} if T1_inout and T2_inout: for node in T1_inout: yield node, min(T2_inout) else: # First we determine the candidate node for G2 other_node = min(G2_nodes - set(self.core_2)) host_nodes = self.valid_nodes if other_node == 0 else self.G1.nodes() for node in host_nodes: if node not in self.core_1: yield node, other_node
python
def candidate_pairs_iter(self): """Iterator over candidate pairs of nodes in G1 and G2.""" # All computations are done using the current state! G2_nodes = self.G2_nodes # First we compute the inout-terminal sets. T1_inout = set(self.inout_1.keys()) - set(self.core_1.keys()) T2_inout = set(self.inout_2.keys()) - set(self.core_2.keys()) # If T1_inout and T2_inout are both nonempty. # P(s) = T1_inout x {min T2_inout} if T1_inout and T2_inout: for node in T1_inout: yield node, min(T2_inout) else: # First we determine the candidate node for G2 other_node = min(G2_nodes - set(self.core_2)) host_nodes = self.valid_nodes if other_node == 0 else self.G1.nodes() for node in host_nodes: if node not in self.core_1: yield node, other_node
[ "def", "candidate_pairs_iter", "(", "self", ")", ":", "# All computations are done using the current state!", "G2_nodes", "=", "self", ".", "G2_nodes", "# First we compute the inout-terminal sets.", "T1_inout", "=", "set", "(", "self", ".", "inout_1", ".", "keys", "(", ")", ")", "-", "set", "(", "self", ".", "core_1", ".", "keys", "(", ")", ")", "T2_inout", "=", "set", "(", "self", ".", "inout_2", ".", "keys", "(", ")", ")", "-", "set", "(", "self", ".", "core_2", ".", "keys", "(", ")", ")", "# If T1_inout and T2_inout are both nonempty.", "# P(s) = T1_inout x {min T2_inout}", "if", "T1_inout", "and", "T2_inout", ":", "for", "node", "in", "T1_inout", ":", "yield", "node", ",", "min", "(", "T2_inout", ")", "else", ":", "# First we determine the candidate node for G2", "other_node", "=", "min", "(", "G2_nodes", "-", "set", "(", "self", ".", "core_2", ")", ")", "host_nodes", "=", "self", ".", "valid_nodes", "if", "other_node", "==", "0", "else", "self", ".", "G1", ".", "nodes", "(", ")", "for", "node", "in", "host_nodes", ":", "if", "node", "not", "in", "self", ".", "core_1", ":", "yield", "node", ",", "other_node" ]
Iterator over candidate pairs of nodes in G1 and G2.
[ "Iterator", "over", "candidate", "pairs", "of", "nodes", "in", "G1", "and", "G2", "." ]
9e39c71208fc01a6cc7b7cbe5a533c56830681d3
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/smarts_graph.py#L216-L236
train
235,928
mosdef-hub/foyer
foyer/atomtyper.py
find_atomtypes
def find_atomtypes(topology, forcefield, max_iter=10): """Determine atomtypes for all atoms. Parameters ---------- topology : simtk.openmm.app.Topology The topology that we are trying to atomtype. forcefield : foyer.Forcefield The forcefield object. max_iter : int, optional, default=10 The maximum number of iterations. """ rules = _load_rules(forcefield) # Only consider rules for elements found in topology subrules = dict() system_elements = {a.element.symbol for a in topology.atoms()} for key,val in rules.items(): atom = val.node[0]['atom'] if len(atom.select('atom_symbol')) == 1 and not atom.select('not_expression'): try: element = atom.select('atom_symbol').strees[0].tail[0] except IndexError: try: atomic_num = atom.select('atomic_num').strees[0].tail[0] element = pt.Element[int(atomic_num)] except IndexError: element = None else: element = None if element is None or element in system_elements: subrules[key] = val rules = subrules _iterate_rules(rules, topology, max_iter=max_iter) _resolve_atomtypes(topology)
python
def find_atomtypes(topology, forcefield, max_iter=10): """Determine atomtypes for all atoms. Parameters ---------- topology : simtk.openmm.app.Topology The topology that we are trying to atomtype. forcefield : foyer.Forcefield The forcefield object. max_iter : int, optional, default=10 The maximum number of iterations. """ rules = _load_rules(forcefield) # Only consider rules for elements found in topology subrules = dict() system_elements = {a.element.symbol for a in topology.atoms()} for key,val in rules.items(): atom = val.node[0]['atom'] if len(atom.select('atom_symbol')) == 1 and not atom.select('not_expression'): try: element = atom.select('atom_symbol').strees[0].tail[0] except IndexError: try: atomic_num = atom.select('atomic_num').strees[0].tail[0] element = pt.Element[int(atomic_num)] except IndexError: element = None else: element = None if element is None or element in system_elements: subrules[key] = val rules = subrules _iterate_rules(rules, topology, max_iter=max_iter) _resolve_atomtypes(topology)
[ "def", "find_atomtypes", "(", "topology", ",", "forcefield", ",", "max_iter", "=", "10", ")", ":", "rules", "=", "_load_rules", "(", "forcefield", ")", "# Only consider rules for elements found in topology", "subrules", "=", "dict", "(", ")", "system_elements", "=", "{", "a", ".", "element", ".", "symbol", "for", "a", "in", "topology", ".", "atoms", "(", ")", "}", "for", "key", ",", "val", "in", "rules", ".", "items", "(", ")", ":", "atom", "=", "val", ".", "node", "[", "0", "]", "[", "'atom'", "]", "if", "len", "(", "atom", ".", "select", "(", "'atom_symbol'", ")", ")", "==", "1", "and", "not", "atom", ".", "select", "(", "'not_expression'", ")", ":", "try", ":", "element", "=", "atom", ".", "select", "(", "'atom_symbol'", ")", ".", "strees", "[", "0", "]", ".", "tail", "[", "0", "]", "except", "IndexError", ":", "try", ":", "atomic_num", "=", "atom", ".", "select", "(", "'atomic_num'", ")", ".", "strees", "[", "0", "]", ".", "tail", "[", "0", "]", "element", "=", "pt", ".", "Element", "[", "int", "(", "atomic_num", ")", "]", "except", "IndexError", ":", "element", "=", "None", "else", ":", "element", "=", "None", "if", "element", "is", "None", "or", "element", "in", "system_elements", ":", "subrules", "[", "key", "]", "=", "val", "rules", "=", "subrules", "_iterate_rules", "(", "rules", ",", "topology", ",", "max_iter", "=", "max_iter", ")", "_resolve_atomtypes", "(", "topology", ")" ]
Determine atomtypes for all atoms. Parameters ---------- topology : simtk.openmm.app.Topology The topology that we are trying to atomtype. forcefield : foyer.Forcefield The forcefield object. max_iter : int, optional, default=10 The maximum number of iterations.
[ "Determine", "atomtypes", "for", "all", "atoms", "." ]
9e39c71208fc01a6cc7b7cbe5a533c56830681d3
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/atomtyper.py#L7-L43
train
235,929
mosdef-hub/foyer
foyer/atomtyper.py
_load_rules
def _load_rules(forcefield): """Load atomtyping rules from a forcefield into SMARTSGraphs. """ rules = dict() for rule_name, smarts in forcefield.atomTypeDefinitions.items(): overrides = forcefield.atomTypeOverrides.get(rule_name) if overrides is not None: overrides = set(overrides) else: overrides = set() rules[rule_name] = SMARTSGraph(smarts_string=smarts, parser=forcefield.parser, name=rule_name, overrides=overrides) return rules
python
def _load_rules(forcefield): """Load atomtyping rules from a forcefield into SMARTSGraphs. """ rules = dict() for rule_name, smarts in forcefield.atomTypeDefinitions.items(): overrides = forcefield.atomTypeOverrides.get(rule_name) if overrides is not None: overrides = set(overrides) else: overrides = set() rules[rule_name] = SMARTSGraph(smarts_string=smarts, parser=forcefield.parser, name=rule_name, overrides=overrides) return rules
[ "def", "_load_rules", "(", "forcefield", ")", ":", "rules", "=", "dict", "(", ")", "for", "rule_name", ",", "smarts", "in", "forcefield", ".", "atomTypeDefinitions", ".", "items", "(", ")", ":", "overrides", "=", "forcefield", ".", "atomTypeOverrides", ".", "get", "(", "rule_name", ")", "if", "overrides", "is", "not", "None", ":", "overrides", "=", "set", "(", "overrides", ")", "else", ":", "overrides", "=", "set", "(", ")", "rules", "[", "rule_name", "]", "=", "SMARTSGraph", "(", "smarts_string", "=", "smarts", ",", "parser", "=", "forcefield", ".", "parser", ",", "name", "=", "rule_name", ",", "overrides", "=", "overrides", ")", "return", "rules" ]
Load atomtyping rules from a forcefield into SMARTSGraphs.
[ "Load", "atomtyping", "rules", "from", "a", "forcefield", "into", "SMARTSGraphs", "." ]
9e39c71208fc01a6cc7b7cbe5a533c56830681d3
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/atomtyper.py#L46-L59
train
235,930
mosdef-hub/foyer
foyer/atomtyper.py
_iterate_rules
def _iterate_rules(rules, topology, max_iter): """Iteratively run all the rules until the white- and backlists converge. Parameters ---------- rules : dict A dictionary mapping rule names (typically atomtype names) to SMARTSGraphs that evaluate those rules. topology : simtk.openmm.app.Topology The topology that we are trying to atomtype. max_iter : int The maximum number of iterations. """ atoms = list(topology.atoms()) for _ in range(max_iter): max_iter -= 1 found_something = False for rule in rules.values(): for match_index in rule.find_matches(topology): atom = atoms[match_index] if rule.name not in atom.whitelist: atom.whitelist.add(rule.name) atom.blacklist |= rule.overrides found_something = True if not found_something: break else: warn("Reached maximum iterations. Something probably went wrong.")
python
def _iterate_rules(rules, topology, max_iter): """Iteratively run all the rules until the white- and backlists converge. Parameters ---------- rules : dict A dictionary mapping rule names (typically atomtype names) to SMARTSGraphs that evaluate those rules. topology : simtk.openmm.app.Topology The topology that we are trying to atomtype. max_iter : int The maximum number of iterations. """ atoms = list(topology.atoms()) for _ in range(max_iter): max_iter -= 1 found_something = False for rule in rules.values(): for match_index in rule.find_matches(topology): atom = atoms[match_index] if rule.name not in atom.whitelist: atom.whitelist.add(rule.name) atom.blacklist |= rule.overrides found_something = True if not found_something: break else: warn("Reached maximum iterations. Something probably went wrong.")
[ "def", "_iterate_rules", "(", "rules", ",", "topology", ",", "max_iter", ")", ":", "atoms", "=", "list", "(", "topology", ".", "atoms", "(", ")", ")", "for", "_", "in", "range", "(", "max_iter", ")", ":", "max_iter", "-=", "1", "found_something", "=", "False", "for", "rule", "in", "rules", ".", "values", "(", ")", ":", "for", "match_index", "in", "rule", ".", "find_matches", "(", "topology", ")", ":", "atom", "=", "atoms", "[", "match_index", "]", "if", "rule", ".", "name", "not", "in", "atom", ".", "whitelist", ":", "atom", ".", "whitelist", ".", "add", "(", "rule", ".", "name", ")", "atom", ".", "blacklist", "|=", "rule", ".", "overrides", "found_something", "=", "True", "if", "not", "found_something", ":", "break", "else", ":", "warn", "(", "\"Reached maximum iterations. Something probably went wrong.\"", ")" ]
Iteratively run all the rules until the white- and backlists converge. Parameters ---------- rules : dict A dictionary mapping rule names (typically atomtype names) to SMARTSGraphs that evaluate those rules. topology : simtk.openmm.app.Topology The topology that we are trying to atomtype. max_iter : int The maximum number of iterations.
[ "Iteratively", "run", "all", "the", "rules", "until", "the", "white", "-", "and", "backlists", "converge", "." ]
9e39c71208fc01a6cc7b7cbe5a533c56830681d3
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/atomtyper.py#L62-L90
train
235,931
mosdef-hub/foyer
foyer/atomtyper.py
_resolve_atomtypes
def _resolve_atomtypes(topology): """Determine the final atomtypes from the white- and blacklists. """ for atom in topology.atoms(): atomtype = [rule_name for rule_name in atom.whitelist - atom.blacklist] if len(atomtype) == 1: atom.id = atomtype[0] elif len(atomtype) > 1: raise FoyerError("Found multiple types for atom {} ({}): {}.".format( atom.index, atom.element.name, atomtype)) else: raise FoyerError("Found no types for atom {} ({}).".format( atom.index, atom.element.name))
python
def _resolve_atomtypes(topology): """Determine the final atomtypes from the white- and blacklists. """ for atom in topology.atoms(): atomtype = [rule_name for rule_name in atom.whitelist - atom.blacklist] if len(atomtype) == 1: atom.id = atomtype[0] elif len(atomtype) > 1: raise FoyerError("Found multiple types for atom {} ({}): {}.".format( atom.index, atom.element.name, atomtype)) else: raise FoyerError("Found no types for atom {} ({}).".format( atom.index, atom.element.name))
[ "def", "_resolve_atomtypes", "(", "topology", ")", ":", "for", "atom", "in", "topology", ".", "atoms", "(", ")", ":", "atomtype", "=", "[", "rule_name", "for", "rule_name", "in", "atom", ".", "whitelist", "-", "atom", ".", "blacklist", "]", "if", "len", "(", "atomtype", ")", "==", "1", ":", "atom", ".", "id", "=", "atomtype", "[", "0", "]", "elif", "len", "(", "atomtype", ")", ">", "1", ":", "raise", "FoyerError", "(", "\"Found multiple types for atom {} ({}): {}.\"", ".", "format", "(", "atom", ".", "index", ",", "atom", ".", "element", ".", "name", ",", "atomtype", ")", ")", "else", ":", "raise", "FoyerError", "(", "\"Found no types for atom {} ({}).\"", ".", "format", "(", "atom", ".", "index", ",", "atom", ".", "element", ".", "name", ")", ")" ]
Determine the final atomtypes from the white- and blacklists.
[ "Determine", "the", "final", "atomtypes", "from", "the", "white", "-", "and", "blacklists", "." ]
9e39c71208fc01a6cc7b7cbe5a533c56830681d3
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/atomtyper.py#L93-L104
train
235,932
mosdef-hub/foyer
foyer/forcefield.py
generate_topology
def generate_topology(non_omm_topology, non_element_types=None, residues=None): """Create an OpenMM Topology from another supported topology structure.""" if non_element_types is None: non_element_types = set() if isinstance(non_omm_topology, pmd.Structure): return _topology_from_parmed(non_omm_topology, non_element_types) elif has_mbuild: mb = import_('mbuild') if (non_omm_topology, mb.Compound): pmdCompoundStructure = non_omm_topology.to_parmed(residues=residues) return _topology_from_parmed(pmdCompoundStructure, non_element_types) else: raise FoyerError('Unknown topology format: {}\n' 'Supported formats are: ' '"parmed.Structure", ' '"mbuild.Compound", ' '"openmm.app.Topology"'.format(non_omm_topology))
python
def generate_topology(non_omm_topology, non_element_types=None, residues=None): """Create an OpenMM Topology from another supported topology structure.""" if non_element_types is None: non_element_types = set() if isinstance(non_omm_topology, pmd.Structure): return _topology_from_parmed(non_omm_topology, non_element_types) elif has_mbuild: mb = import_('mbuild') if (non_omm_topology, mb.Compound): pmdCompoundStructure = non_omm_topology.to_parmed(residues=residues) return _topology_from_parmed(pmdCompoundStructure, non_element_types) else: raise FoyerError('Unknown topology format: {}\n' 'Supported formats are: ' '"parmed.Structure", ' '"mbuild.Compound", ' '"openmm.app.Topology"'.format(non_omm_topology))
[ "def", "generate_topology", "(", "non_omm_topology", ",", "non_element_types", "=", "None", ",", "residues", "=", "None", ")", ":", "if", "non_element_types", "is", "None", ":", "non_element_types", "=", "set", "(", ")", "if", "isinstance", "(", "non_omm_topology", ",", "pmd", ".", "Structure", ")", ":", "return", "_topology_from_parmed", "(", "non_omm_topology", ",", "non_element_types", ")", "elif", "has_mbuild", ":", "mb", "=", "import_", "(", "'mbuild'", ")", "if", "(", "non_omm_topology", ",", "mb", ".", "Compound", ")", ":", "pmdCompoundStructure", "=", "non_omm_topology", ".", "to_parmed", "(", "residues", "=", "residues", ")", "return", "_topology_from_parmed", "(", "pmdCompoundStructure", ",", "non_element_types", ")", "else", ":", "raise", "FoyerError", "(", "'Unknown topology format: {}\\n'", "'Supported formats are: '", "'\"parmed.Structure\", '", "'\"mbuild.Compound\", '", "'\"openmm.app.Topology\"'", ".", "format", "(", "non_omm_topology", ")", ")" ]
Create an OpenMM Topology from another supported topology structure.
[ "Create", "an", "OpenMM", "Topology", "from", "another", "supported", "topology", "structure", "." ]
9e39c71208fc01a6cc7b7cbe5a533c56830681d3
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L87-L105
train
235,933
mosdef-hub/foyer
foyer/forcefield.py
_topology_from_parmed
def _topology_from_parmed(structure, non_element_types): """Convert a ParmEd Structure to an OpenMM Topology.""" topology = app.Topology() residues = dict() for pmd_residue in structure.residues: chain = topology.addChain() omm_residue = topology.addResidue(pmd_residue.name, chain) residues[pmd_residue] = omm_residue atoms = dict() # pmd.Atom: omm.Atom for pmd_atom in structure.atoms: name = pmd_atom.name if pmd_atom.name in non_element_types: element = non_element_types[pmd_atom.name] else: if (isinstance(pmd_atom.atomic_number, int) and pmd_atom.atomic_number != 0): element = elem.Element.getByAtomicNumber(pmd_atom.atomic_number) else: element = elem.Element.getBySymbol(pmd_atom.name) omm_atom = topology.addAtom(name, element, residues[pmd_atom.residue]) atoms[pmd_atom] = omm_atom omm_atom.bond_partners = [] for bond in structure.bonds: atom1 = atoms[bond.atom1] atom2 = atoms[bond.atom2] topology.addBond(atom1, atom2) atom1.bond_partners.append(atom2) atom2.bond_partners.append(atom1) if structure.box_vectors and np.any([x._value for x in structure.box_vectors]): topology.setPeriodicBoxVectors(structure.box_vectors) positions = structure.positions return topology, positions
python
def _topology_from_parmed(structure, non_element_types): """Convert a ParmEd Structure to an OpenMM Topology.""" topology = app.Topology() residues = dict() for pmd_residue in structure.residues: chain = topology.addChain() omm_residue = topology.addResidue(pmd_residue.name, chain) residues[pmd_residue] = omm_residue atoms = dict() # pmd.Atom: omm.Atom for pmd_atom in structure.atoms: name = pmd_atom.name if pmd_atom.name in non_element_types: element = non_element_types[pmd_atom.name] else: if (isinstance(pmd_atom.atomic_number, int) and pmd_atom.atomic_number != 0): element = elem.Element.getByAtomicNumber(pmd_atom.atomic_number) else: element = elem.Element.getBySymbol(pmd_atom.name) omm_atom = topology.addAtom(name, element, residues[pmd_atom.residue]) atoms[pmd_atom] = omm_atom omm_atom.bond_partners = [] for bond in structure.bonds: atom1 = atoms[bond.atom1] atom2 = atoms[bond.atom2] topology.addBond(atom1, atom2) atom1.bond_partners.append(atom2) atom2.bond_partners.append(atom1) if structure.box_vectors and np.any([x._value for x in structure.box_vectors]): topology.setPeriodicBoxVectors(structure.box_vectors) positions = structure.positions return topology, positions
[ "def", "_topology_from_parmed", "(", "structure", ",", "non_element_types", ")", ":", "topology", "=", "app", ".", "Topology", "(", ")", "residues", "=", "dict", "(", ")", "for", "pmd_residue", "in", "structure", ".", "residues", ":", "chain", "=", "topology", ".", "addChain", "(", ")", "omm_residue", "=", "topology", ".", "addResidue", "(", "pmd_residue", ".", "name", ",", "chain", ")", "residues", "[", "pmd_residue", "]", "=", "omm_residue", "atoms", "=", "dict", "(", ")", "# pmd.Atom: omm.Atom", "for", "pmd_atom", "in", "structure", ".", "atoms", ":", "name", "=", "pmd_atom", ".", "name", "if", "pmd_atom", ".", "name", "in", "non_element_types", ":", "element", "=", "non_element_types", "[", "pmd_atom", ".", "name", "]", "else", ":", "if", "(", "isinstance", "(", "pmd_atom", ".", "atomic_number", ",", "int", ")", "and", "pmd_atom", ".", "atomic_number", "!=", "0", ")", ":", "element", "=", "elem", ".", "Element", ".", "getByAtomicNumber", "(", "pmd_atom", ".", "atomic_number", ")", "else", ":", "element", "=", "elem", ".", "Element", ".", "getBySymbol", "(", "pmd_atom", ".", "name", ")", "omm_atom", "=", "topology", ".", "addAtom", "(", "name", ",", "element", ",", "residues", "[", "pmd_atom", ".", "residue", "]", ")", "atoms", "[", "pmd_atom", "]", "=", "omm_atom", "omm_atom", ".", "bond_partners", "=", "[", "]", "for", "bond", "in", "structure", ".", "bonds", ":", "atom1", "=", "atoms", "[", "bond", ".", "atom1", "]", "atom2", "=", "atoms", "[", "bond", ".", "atom2", "]", "topology", ".", "addBond", "(", "atom1", ",", "atom2", ")", "atom1", ".", "bond_partners", ".", "append", "(", "atom2", ")", "atom2", ".", "bond_partners", ".", "append", "(", "atom1", ")", "if", "structure", ".", "box_vectors", "and", "np", ".", "any", "(", "[", "x", ".", "_value", "for", "x", "in", "structure", ".", "box_vectors", "]", ")", ":", "topology", ".", "setPeriodicBoxVectors", "(", "structure", ".", "box_vectors", ")", "positions", "=", "structure", ".", "positions", "return", "topology", ",", "positions" ]
Convert a ParmEd Structure to an OpenMM Topology.
[ "Convert", "a", "ParmEd", "Structure", "to", "an", "OpenMM", "Topology", "." ]
9e39c71208fc01a6cc7b7cbe5a533c56830681d3
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L108-L143
train
235,934
mosdef-hub/foyer
foyer/forcefield.py
_topology_from_residue
def _topology_from_residue(res): """Converts a openmm.app.Topology.Residue to openmm.app.Topology. Parameters ---------- res : openmm.app.Topology.Residue An individual residue in an openmm.app.Topology Returns ------- topology : openmm.app.Topology The generated topology """ topology = app.Topology() chain = topology.addChain() new_res = topology.addResidue(res.name, chain) atoms = dict() # { omm.Atom in res : omm.Atom in *new* topology } for res_atom in res.atoms(): topology_atom = topology.addAtom(name=res_atom.name, element=res_atom.element, residue=new_res) atoms[res_atom] = topology_atom topology_atom.bond_partners = [] for bond in res.bonds(): atom1 = atoms[bond.atom1] atom2 = atoms[bond.atom2] topology.addBond(atom1, atom2) atom1.bond_partners.append(atom2) atom2.bond_partners.append(atom1) return topology
python
def _topology_from_residue(res): """Converts a openmm.app.Topology.Residue to openmm.app.Topology. Parameters ---------- res : openmm.app.Topology.Residue An individual residue in an openmm.app.Topology Returns ------- topology : openmm.app.Topology The generated topology """ topology = app.Topology() chain = topology.addChain() new_res = topology.addResidue(res.name, chain) atoms = dict() # { omm.Atom in res : omm.Atom in *new* topology } for res_atom in res.atoms(): topology_atom = topology.addAtom(name=res_atom.name, element=res_atom.element, residue=new_res) atoms[res_atom] = topology_atom topology_atom.bond_partners = [] for bond in res.bonds(): atom1 = atoms[bond.atom1] atom2 = atoms[bond.atom2] topology.addBond(atom1, atom2) atom1.bond_partners.append(atom2) atom2.bond_partners.append(atom1) return topology
[ "def", "_topology_from_residue", "(", "res", ")", ":", "topology", "=", "app", ".", "Topology", "(", ")", "chain", "=", "topology", ".", "addChain", "(", ")", "new_res", "=", "topology", ".", "addResidue", "(", "res", ".", "name", ",", "chain", ")", "atoms", "=", "dict", "(", ")", "# { omm.Atom in res : omm.Atom in *new* topology }", "for", "res_atom", "in", "res", ".", "atoms", "(", ")", ":", "topology_atom", "=", "topology", ".", "addAtom", "(", "name", "=", "res_atom", ".", "name", ",", "element", "=", "res_atom", ".", "element", ",", "residue", "=", "new_res", ")", "atoms", "[", "res_atom", "]", "=", "topology_atom", "topology_atom", ".", "bond_partners", "=", "[", "]", "for", "bond", "in", "res", ".", "bonds", "(", ")", ":", "atom1", "=", "atoms", "[", "bond", ".", "atom1", "]", "atom2", "=", "atoms", "[", "bond", ".", "atom2", "]", "topology", ".", "addBond", "(", "atom1", ",", "atom2", ")", "atom1", ".", "bond_partners", ".", "append", "(", "atom2", ")", "atom2", ".", "bond_partners", ".", "append", "(", "atom1", ")", "return", "topology" ]
Converts a openmm.app.Topology.Residue to openmm.app.Topology. Parameters ---------- res : openmm.app.Topology.Residue An individual residue in an openmm.app.Topology Returns ------- topology : openmm.app.Topology The generated topology
[ "Converts", "a", "openmm", ".", "app", ".", "Topology", ".", "Residue", "to", "openmm", ".", "app", ".", "Topology", "." ]
9e39c71208fc01a6cc7b7cbe5a533c56830681d3
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L146-L180
train
235,935
mosdef-hub/foyer
foyer/forcefield.py
_check_independent_residues
def _check_independent_residues(topology): """Check to see if residues will constitute independent graphs.""" for res in topology.residues(): atoms_in_residue = set([atom for atom in res.atoms()]) bond_partners_in_residue = [item for sublist in [atom.bond_partners for atom in res.atoms()] for item in sublist] # Handle the case of a 'residue' with no neighbors if not bond_partners_in_residue: continue if set(atoms_in_residue) != set(bond_partners_in_residue): return False return True
python
def _check_independent_residues(topology): """Check to see if residues will constitute independent graphs.""" for res in topology.residues(): atoms_in_residue = set([atom for atom in res.atoms()]) bond_partners_in_residue = [item for sublist in [atom.bond_partners for atom in res.atoms()] for item in sublist] # Handle the case of a 'residue' with no neighbors if not bond_partners_in_residue: continue if set(atoms_in_residue) != set(bond_partners_in_residue): return False return True
[ "def", "_check_independent_residues", "(", "topology", ")", ":", "for", "res", "in", "topology", ".", "residues", "(", ")", ":", "atoms_in_residue", "=", "set", "(", "[", "atom", "for", "atom", "in", "res", ".", "atoms", "(", ")", "]", ")", "bond_partners_in_residue", "=", "[", "item", "for", "sublist", "in", "[", "atom", ".", "bond_partners", "for", "atom", "in", "res", ".", "atoms", "(", ")", "]", "for", "item", "in", "sublist", "]", "# Handle the case of a 'residue' with no neighbors", "if", "not", "bond_partners_in_residue", ":", "continue", "if", "set", "(", "atoms_in_residue", ")", "!=", "set", "(", "bond_partners_in_residue", ")", ":", "return", "False", "return", "True" ]
Check to see if residues will constitute independent graphs.
[ "Check", "to", "see", "if", "residues", "will", "constitute", "independent", "graphs", "." ]
9e39c71208fc01a6cc7b7cbe5a533c56830681d3
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L183-L193
train
235,936
mosdef-hub/foyer
foyer/forcefield.py
_update_atomtypes
def _update_atomtypes(unatomtyped_topology, res_name, prototype): """Update atomtypes in residues in a topology using a prototype topology. Atomtypes are updated when residues in each topology have matching names. Parameters ---------- unatomtyped_topology : openmm.app.Topology Topology lacking atomtypes defined by `find_atomtypes`. prototype : openmm.app.Topology Prototype topology with atomtypes defined by `find_atomtypes`. """ for res in unatomtyped_topology.residues(): if res.name == res_name: for old_atom, new_atom_id in zip([atom for atom in res.atoms()], [atom.id for atom in prototype.atoms()]): old_atom.id = new_atom_id
python
def _update_atomtypes(unatomtyped_topology, res_name, prototype): """Update atomtypes in residues in a topology using a prototype topology. Atomtypes are updated when residues in each topology have matching names. Parameters ---------- unatomtyped_topology : openmm.app.Topology Topology lacking atomtypes defined by `find_atomtypes`. prototype : openmm.app.Topology Prototype topology with atomtypes defined by `find_atomtypes`. """ for res in unatomtyped_topology.residues(): if res.name == res_name: for old_atom, new_atom_id in zip([atom for atom in res.atoms()], [atom.id for atom in prototype.atoms()]): old_atom.id = new_atom_id
[ "def", "_update_atomtypes", "(", "unatomtyped_topology", ",", "res_name", ",", "prototype", ")", ":", "for", "res", "in", "unatomtyped_topology", ".", "residues", "(", ")", ":", "if", "res", ".", "name", "==", "res_name", ":", "for", "old_atom", ",", "new_atom_id", "in", "zip", "(", "[", "atom", "for", "atom", "in", "res", ".", "atoms", "(", ")", "]", ",", "[", "atom", ".", "id", "for", "atom", "in", "prototype", ".", "atoms", "(", ")", "]", ")", ":", "old_atom", ".", "id", "=", "new_atom_id" ]
Update atomtypes in residues in a topology using a prototype topology. Atomtypes are updated when residues in each topology have matching names. Parameters ---------- unatomtyped_topology : openmm.app.Topology Topology lacking atomtypes defined by `find_atomtypes`. prototype : openmm.app.Topology Prototype topology with atomtypes defined by `find_atomtypes`.
[ "Update", "atomtypes", "in", "residues", "in", "a", "topology", "using", "a", "prototype", "topology", "." ]
9e39c71208fc01a6cc7b7cbe5a533c56830681d3
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L196-L212
train
235,937
mosdef-hub/foyer
foyer/forcefield.py
Forcefield.registerAtomType
def registerAtomType(self, parameters): """Register a new atom type. """ name = parameters['name'] if name in self._atomTypes: raise ValueError('Found multiple definitions for atom type: ' + name) atom_class = parameters['class'] mass = _convertParameterToNumber(parameters['mass']) element = None if 'element' in parameters: element, custom = self._create_element(parameters['element'], mass) if custom: self.non_element_types[element.symbol] = element self._atomTypes[name] = self.__class__._AtomType(name, atom_class, mass, element) if atom_class in self._atomClasses: type_set = self._atomClasses[atom_class] else: type_set = set() self._atomClasses[atom_class] = type_set type_set.add(name) self._atomClasses[''].add(name) name = parameters['name'] if 'def' in parameters: self.atomTypeDefinitions[name] = parameters['def'] if 'overrides' in parameters: overrides = set(atype.strip() for atype in parameters['overrides'].split(",")) if overrides: self.atomTypeOverrides[name] = overrides if 'des' in parameters: self.atomTypeDesc[name] = parameters['desc'] if 'doi' in parameters: dois = set(doi.strip() for doi in parameters['doi'].split(',')) self.atomTypeRefs[name] = dois
python
def registerAtomType(self, parameters): """Register a new atom type. """ name = parameters['name'] if name in self._atomTypes: raise ValueError('Found multiple definitions for atom type: ' + name) atom_class = parameters['class'] mass = _convertParameterToNumber(parameters['mass']) element = None if 'element' in parameters: element, custom = self._create_element(parameters['element'], mass) if custom: self.non_element_types[element.symbol] = element self._atomTypes[name] = self.__class__._AtomType(name, atom_class, mass, element) if atom_class in self._atomClasses: type_set = self._atomClasses[atom_class] else: type_set = set() self._atomClasses[atom_class] = type_set type_set.add(name) self._atomClasses[''].add(name) name = parameters['name'] if 'def' in parameters: self.atomTypeDefinitions[name] = parameters['def'] if 'overrides' in parameters: overrides = set(atype.strip() for atype in parameters['overrides'].split(",")) if overrides: self.atomTypeOverrides[name] = overrides if 'des' in parameters: self.atomTypeDesc[name] = parameters['desc'] if 'doi' in parameters: dois = set(doi.strip() for doi in parameters['doi'].split(',')) self.atomTypeRefs[name] = dois
[ "def", "registerAtomType", "(", "self", ",", "parameters", ")", ":", "name", "=", "parameters", "[", "'name'", "]", "if", "name", "in", "self", ".", "_atomTypes", ":", "raise", "ValueError", "(", "'Found multiple definitions for atom type: '", "+", "name", ")", "atom_class", "=", "parameters", "[", "'class'", "]", "mass", "=", "_convertParameterToNumber", "(", "parameters", "[", "'mass'", "]", ")", "element", "=", "None", "if", "'element'", "in", "parameters", ":", "element", ",", "custom", "=", "self", ".", "_create_element", "(", "parameters", "[", "'element'", "]", ",", "mass", ")", "if", "custom", ":", "self", ".", "non_element_types", "[", "element", ".", "symbol", "]", "=", "element", "self", ".", "_atomTypes", "[", "name", "]", "=", "self", ".", "__class__", ".", "_AtomType", "(", "name", ",", "atom_class", ",", "mass", ",", "element", ")", "if", "atom_class", "in", "self", ".", "_atomClasses", ":", "type_set", "=", "self", ".", "_atomClasses", "[", "atom_class", "]", "else", ":", "type_set", "=", "set", "(", ")", "self", ".", "_atomClasses", "[", "atom_class", "]", "=", "type_set", "type_set", ".", "add", "(", "name", ")", "self", ".", "_atomClasses", "[", "''", "]", ".", "add", "(", "name", ")", "name", "=", "parameters", "[", "'name'", "]", "if", "'def'", "in", "parameters", ":", "self", ".", "atomTypeDefinitions", "[", "name", "]", "=", "parameters", "[", "'def'", "]", "if", "'overrides'", "in", "parameters", ":", "overrides", "=", "set", "(", "atype", ".", "strip", "(", ")", "for", "atype", "in", "parameters", "[", "'overrides'", "]", ".", "split", "(", "\",\"", ")", ")", "if", "overrides", ":", "self", ".", "atomTypeOverrides", "[", "name", "]", "=", "overrides", "if", "'des'", "in", "parameters", ":", "self", ".", "atomTypeDesc", "[", "name", "]", "=", "parameters", "[", "'desc'", "]", "if", "'doi'", "in", "parameters", ":", "dois", "=", "set", "(", "doi", ".", "strip", "(", ")", "for", "doi", "in", "parameters", "[", "'doi'", "]", ".", "split", "(", "','", ")", ")", "self", ".", "atomTypeRefs", "[", "name", "]", "=", "dois" ]
Register a new atom type.
[ "Register", "a", "new", "atom", "type", "." ]
9e39c71208fc01a6cc7b7cbe5a533c56830681d3
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L307-L341
train
235,938
mosdef-hub/foyer
foyer/forcefield.py
Forcefield.run_atomtyping
def run_atomtyping(self, topology, use_residue_map=True): """Atomtype the topology Parameters ---------- topology : openmm.app.Topology Molecular structure to find atom types of use_residue_map : boolean, optional, default=True Store atomtyped topologies of residues to a dictionary that maps them to residue names. Each topology, including atomtypes, will be copied to other residues with the same name. This avoids repeatedly calling the subgraph isomorphism on idential residues and should result in better performance for systems with many identical residues, i.e. a box of water. Note that for this to be applied to independent molecules, they must each be saved as different residues in the topology. """ if use_residue_map: independent_residues = _check_independent_residues(topology) if independent_residues: residue_map = dict() for res in topology.residues(): if res.name not in residue_map.keys(): residue = _topology_from_residue(res) find_atomtypes(residue, forcefield=self) residue_map[res.name] = residue for key, val in residue_map.items(): _update_atomtypes(topology, key, val) else: find_atomtypes(topology, forcefield=self) else: find_atomtypes(topology, forcefield=self) if not all([a.id for a in topology.atoms()][0]): raise ValueError('Not all atoms in topology have atom types') return topology
python
def run_atomtyping(self, topology, use_residue_map=True): """Atomtype the topology Parameters ---------- topology : openmm.app.Topology Molecular structure to find atom types of use_residue_map : boolean, optional, default=True Store atomtyped topologies of residues to a dictionary that maps them to residue names. Each topology, including atomtypes, will be copied to other residues with the same name. This avoids repeatedly calling the subgraph isomorphism on idential residues and should result in better performance for systems with many identical residues, i.e. a box of water. Note that for this to be applied to independent molecules, they must each be saved as different residues in the topology. """ if use_residue_map: independent_residues = _check_independent_residues(topology) if independent_residues: residue_map = dict() for res in topology.residues(): if res.name not in residue_map.keys(): residue = _topology_from_residue(res) find_atomtypes(residue, forcefield=self) residue_map[res.name] = residue for key, val in residue_map.items(): _update_atomtypes(topology, key, val) else: find_atomtypes(topology, forcefield=self) else: find_atomtypes(topology, forcefield=self) if not all([a.id for a in topology.atoms()][0]): raise ValueError('Not all atoms in topology have atom types') return topology
[ "def", "run_atomtyping", "(", "self", ",", "topology", ",", "use_residue_map", "=", "True", ")", ":", "if", "use_residue_map", ":", "independent_residues", "=", "_check_independent_residues", "(", "topology", ")", "if", "independent_residues", ":", "residue_map", "=", "dict", "(", ")", "for", "res", "in", "topology", ".", "residues", "(", ")", ":", "if", "res", ".", "name", "not", "in", "residue_map", ".", "keys", "(", ")", ":", "residue", "=", "_topology_from_residue", "(", "res", ")", "find_atomtypes", "(", "residue", ",", "forcefield", "=", "self", ")", "residue_map", "[", "res", ".", "name", "]", "=", "residue", "for", "key", ",", "val", "in", "residue_map", ".", "items", "(", ")", ":", "_update_atomtypes", "(", "topology", ",", "key", ",", "val", ")", "else", ":", "find_atomtypes", "(", "topology", ",", "forcefield", "=", "self", ")", "else", ":", "find_atomtypes", "(", "topology", ",", "forcefield", "=", "self", ")", "if", "not", "all", "(", "[", "a", ".", "id", "for", "a", "in", "topology", ".", "atoms", "(", ")", "]", "[", "0", "]", ")", ":", "raise", "ValueError", "(", "'Not all atoms in topology have atom types'", ")", "return", "topology" ]
Atomtype the topology Parameters ---------- topology : openmm.app.Topology Molecular structure to find atom types of use_residue_map : boolean, optional, default=True Store atomtyped topologies of residues to a dictionary that maps them to residue names. Each topology, including atomtypes, will be copied to other residues with the same name. This avoids repeatedly calling the subgraph isomorphism on idential residues and should result in better performance for systems with many identical residues, i.e. a box of water. Note that for this to be applied to independent molecules, they must each be saved as different residues in the topology.
[ "Atomtype", "the", "topology" ]
9e39c71208fc01a6cc7b7cbe5a533c56830681d3
https://github.com/mosdef-hub/foyer/blob/9e39c71208fc01a6cc7b7cbe5a533c56830681d3/foyer/forcefield.py#L452-L493
train
235,939
mgedmin/check-manifest
check_manifest.py
cd
def cd(directory): """Change the current working directory, temporarily. Use as a context manager: with cd(d): ... """ old_dir = os.getcwd() try: os.chdir(directory) yield finally: os.chdir(old_dir)
python
def cd(directory): """Change the current working directory, temporarily. Use as a context manager: with cd(d): ... """ old_dir = os.getcwd() try: os.chdir(directory) yield finally: os.chdir(old_dir)
[ "def", "cd", "(", "directory", ")", ":", "old_dir", "=", "os", ".", "getcwd", "(", ")", "try", ":", "os", ".", "chdir", "(", "directory", ")", "yield", "finally", ":", "os", ".", "chdir", "(", "old_dir", ")" ]
Change the current working directory, temporarily. Use as a context manager: with cd(d): ...
[ "Change", "the", "current", "working", "directory", "temporarily", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L164-L174
train
235,940
mgedmin/check-manifest
check_manifest.py
mkdtemp
def mkdtemp(hint=''): """Create a temporary directory, then clean it up. Use as a context manager: with mkdtemp('-purpose'): ... """ dirname = tempfile.mkdtemp(prefix='check-manifest-', suffix=hint) try: yield dirname finally: rmtree(dirname)
python
def mkdtemp(hint=''): """Create a temporary directory, then clean it up. Use as a context manager: with mkdtemp('-purpose'): ... """ dirname = tempfile.mkdtemp(prefix='check-manifest-', suffix=hint) try: yield dirname finally: rmtree(dirname)
[ "def", "mkdtemp", "(", "hint", "=", "''", ")", ":", "dirname", "=", "tempfile", ".", "mkdtemp", "(", "prefix", "=", "'check-manifest-'", ",", "suffix", "=", "hint", ")", "try", ":", "yield", "dirname", "finally", ":", "rmtree", "(", "dirname", ")" ]
Create a temporary directory, then clean it up. Use as a context manager: with mkdtemp('-purpose'): ...
[ "Create", "a", "temporary", "directory", "then", "clean", "it", "up", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L178-L187
train
235,941
mgedmin/check-manifest
check_manifest.py
chmod_plus
def chmod_plus(path, add_bits=stat.S_IWUSR): """Change a file's mode by adding a few bits. Like chmod +<bits> <path> in a Unix shell. """ try: os.chmod(path, stat.S_IMODE(os.stat(path).st_mode) | add_bits) except OSError: # pragma: nocover pass
python
def chmod_plus(path, add_bits=stat.S_IWUSR): """Change a file's mode by adding a few bits. Like chmod +<bits> <path> in a Unix shell. """ try: os.chmod(path, stat.S_IMODE(os.stat(path).st_mode) | add_bits) except OSError: # pragma: nocover pass
[ "def", "chmod_plus", "(", "path", ",", "add_bits", "=", "stat", ".", "S_IWUSR", ")", ":", "try", ":", "os", ".", "chmod", "(", "path", ",", "stat", ".", "S_IMODE", "(", "os", ".", "stat", "(", "path", ")", ".", "st_mode", ")", "|", "add_bits", ")", "except", "OSError", ":", "# pragma: nocover", "pass" ]
Change a file's mode by adding a few bits. Like chmod +<bits> <path> in a Unix shell.
[ "Change", "a", "file", "s", "mode", "by", "adding", "a", "few", "bits", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L190-L198
train
235,942
mgedmin/check-manifest
check_manifest.py
rmtree
def rmtree(path): """A version of rmtree that can deal with read-only files and directories. Needed because the stock shutil.rmtree() fails with an access error when there are read-only files in the directory on Windows, or when the directory itself is read-only on Unix. """ def onerror(func, path, exc_info): # Did you know what on Python 3.3 on Windows os.remove() and # os.unlink() are distinct functions? if func is os.remove or func is os.unlink or func is os.rmdir: if sys.platform != 'win32': chmod_plus(os.path.dirname(path), stat.S_IWUSR | stat.S_IXUSR) chmod_plus(path) func(path) else: raise shutil.rmtree(path, onerror=onerror)
python
def rmtree(path): """A version of rmtree that can deal with read-only files and directories. Needed because the stock shutil.rmtree() fails with an access error when there are read-only files in the directory on Windows, or when the directory itself is read-only on Unix. """ def onerror(func, path, exc_info): # Did you know what on Python 3.3 on Windows os.remove() and # os.unlink() are distinct functions? if func is os.remove or func is os.unlink or func is os.rmdir: if sys.platform != 'win32': chmod_plus(os.path.dirname(path), stat.S_IWUSR | stat.S_IXUSR) chmod_plus(path) func(path) else: raise shutil.rmtree(path, onerror=onerror)
[ "def", "rmtree", "(", "path", ")", ":", "def", "onerror", "(", "func", ",", "path", ",", "exc_info", ")", ":", "# Did you know what on Python 3.3 on Windows os.remove() and", "# os.unlink() are distinct functions?", "if", "func", "is", "os", ".", "remove", "or", "func", "is", "os", ".", "unlink", "or", "func", "is", "os", ".", "rmdir", ":", "if", "sys", ".", "platform", "!=", "'win32'", ":", "chmod_plus", "(", "os", ".", "path", ".", "dirname", "(", "path", ")", ",", "stat", ".", "S_IWUSR", "|", "stat", ".", "S_IXUSR", ")", "chmod_plus", "(", "path", ")", "func", "(", "path", ")", "else", ":", "raise", "shutil", ".", "rmtree", "(", "path", ",", "onerror", "=", "onerror", ")" ]
A version of rmtree that can deal with read-only files and directories. Needed because the stock shutil.rmtree() fails with an access error when there are read-only files in the directory on Windows, or when the directory itself is read-only on Unix.
[ "A", "version", "of", "rmtree", "that", "can", "deal", "with", "read", "-", "only", "files", "and", "directories", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L201-L218
train
235,943
mgedmin/check-manifest
check_manifest.py
copy_files
def copy_files(filelist, destdir): """Copy a list of files to destdir, preserving directory structure. File names should be relative to the current working directory. """ for filename in filelist: destfile = os.path.join(destdir, filename) # filename should not be absolute, but let's double-check assert destfile.startswith(destdir + os.path.sep) destfiledir = os.path.dirname(destfile) if not os.path.isdir(destfiledir): os.makedirs(destfiledir) if os.path.isdir(filename): os.mkdir(destfile) else: shutil.copy2(filename, destfile)
python
def copy_files(filelist, destdir): """Copy a list of files to destdir, preserving directory structure. File names should be relative to the current working directory. """ for filename in filelist: destfile = os.path.join(destdir, filename) # filename should not be absolute, but let's double-check assert destfile.startswith(destdir + os.path.sep) destfiledir = os.path.dirname(destfile) if not os.path.isdir(destfiledir): os.makedirs(destfiledir) if os.path.isdir(filename): os.mkdir(destfile) else: shutil.copy2(filename, destfile)
[ "def", "copy_files", "(", "filelist", ",", "destdir", ")", ":", "for", "filename", "in", "filelist", ":", "destfile", "=", "os", ".", "path", ".", "join", "(", "destdir", ",", "filename", ")", "# filename should not be absolute, but let's double-check", "assert", "destfile", ".", "startswith", "(", "destdir", "+", "os", ".", "path", ".", "sep", ")", "destfiledir", "=", "os", ".", "path", ".", "dirname", "(", "destfile", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "destfiledir", ")", ":", "os", ".", "makedirs", "(", "destfiledir", ")", "if", "os", ".", "path", ".", "isdir", "(", "filename", ")", ":", "os", ".", "mkdir", "(", "destfile", ")", "else", ":", "shutil", ".", "copy2", "(", "filename", ",", "destfile", ")" ]
Copy a list of files to destdir, preserving directory structure. File names should be relative to the current working directory.
[ "Copy", "a", "list", "of", "files", "to", "destdir", "preserving", "directory", "structure", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L221-L236
train
235,944
mgedmin/check-manifest
check_manifest.py
get_one_file_in
def get_one_file_in(dirname): """Return the pathname of the one file in a directory. Raises if the directory has no files or more than one file. """ files = os.listdir(dirname) if len(files) > 1: raise Failure('More than one file exists in %s:\n%s' % (dirname, '\n'.join(sorted(files)))) elif not files: raise Failure('No files found in %s' % dirname) return os.path.join(dirname, files[0])
python
def get_one_file_in(dirname): """Return the pathname of the one file in a directory. Raises if the directory has no files or more than one file. """ files = os.listdir(dirname) if len(files) > 1: raise Failure('More than one file exists in %s:\n%s' % (dirname, '\n'.join(sorted(files)))) elif not files: raise Failure('No files found in %s' % dirname) return os.path.join(dirname, files[0])
[ "def", "get_one_file_in", "(", "dirname", ")", ":", "files", "=", "os", ".", "listdir", "(", "dirname", ")", "if", "len", "(", "files", ")", ">", "1", ":", "raise", "Failure", "(", "'More than one file exists in %s:\\n%s'", "%", "(", "dirname", ",", "'\\n'", ".", "join", "(", "sorted", "(", "files", ")", ")", ")", ")", "elif", "not", "files", ":", "raise", "Failure", "(", "'No files found in %s'", "%", "dirname", ")", "return", "os", ".", "path", ".", "join", "(", "dirname", ",", "files", "[", "0", "]", ")" ]
Return the pathname of the one file in a directory. Raises if the directory has no files or more than one file.
[ "Return", "the", "pathname", "of", "the", "one", "file", "in", "a", "directory", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L239-L250
train
235,945
mgedmin/check-manifest
check_manifest.py
unicodify
def unicodify(filename): """Make sure filename is Unicode. Because the tarfile module on Python 2 doesn't return Unicode. """ if isinstance(filename, bytes): return filename.decode(locale.getpreferredencoding()) else: return filename
python
def unicodify(filename): """Make sure filename is Unicode. Because the tarfile module on Python 2 doesn't return Unicode. """ if isinstance(filename, bytes): return filename.decode(locale.getpreferredencoding()) else: return filename
[ "def", "unicodify", "(", "filename", ")", ":", "if", "isinstance", "(", "filename", ",", "bytes", ")", ":", "return", "filename", ".", "decode", "(", "locale", ".", "getpreferredencoding", "(", ")", ")", "else", ":", "return", "filename" ]
Make sure filename is Unicode. Because the tarfile module on Python 2 doesn't return Unicode.
[ "Make", "sure", "filename", "is", "Unicode", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L253-L261
train
235,946
mgedmin/check-manifest
check_manifest.py
get_archive_file_list
def get_archive_file_list(archive_filename): """Return the list of files in an archive. Supports .tar.gz and .zip. """ if archive_filename.endswith('.zip'): with closing(zipfile.ZipFile(archive_filename)) as zf: return add_directories(zf.namelist()) elif archive_filename.endswith(('.tar.gz', '.tar.bz2', '.tar')): with closing(tarfile.open(archive_filename)) as tf: return add_directories(list(map(unicodify, tf.getnames()))) else: ext = os.path.splitext(archive_filename)[-1] raise Failure('Unrecognized archive type: %s' % ext)
python
def get_archive_file_list(archive_filename): """Return the list of files in an archive. Supports .tar.gz and .zip. """ if archive_filename.endswith('.zip'): with closing(zipfile.ZipFile(archive_filename)) as zf: return add_directories(zf.namelist()) elif archive_filename.endswith(('.tar.gz', '.tar.bz2', '.tar')): with closing(tarfile.open(archive_filename)) as tf: return add_directories(list(map(unicodify, tf.getnames()))) else: ext = os.path.splitext(archive_filename)[-1] raise Failure('Unrecognized archive type: %s' % ext)
[ "def", "get_archive_file_list", "(", "archive_filename", ")", ":", "if", "archive_filename", ".", "endswith", "(", "'.zip'", ")", ":", "with", "closing", "(", "zipfile", ".", "ZipFile", "(", "archive_filename", ")", ")", "as", "zf", ":", "return", "add_directories", "(", "zf", ".", "namelist", "(", ")", ")", "elif", "archive_filename", ".", "endswith", "(", "(", "'.tar.gz'", ",", "'.tar.bz2'", ",", "'.tar'", ")", ")", ":", "with", "closing", "(", "tarfile", ".", "open", "(", "archive_filename", ")", ")", "as", "tf", ":", "return", "add_directories", "(", "list", "(", "map", "(", "unicodify", ",", "tf", ".", "getnames", "(", ")", ")", ")", ")", "else", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "archive_filename", ")", "[", "-", "1", "]", "raise", "Failure", "(", "'Unrecognized archive type: %s'", "%", "ext", ")" ]
Return the list of files in an archive. Supports .tar.gz and .zip.
[ "Return", "the", "list", "of", "files", "in", "an", "archive", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L264-L277
train
235,947
mgedmin/check-manifest
check_manifest.py
strip_toplevel_name
def strip_toplevel_name(filelist): """Strip toplevel name from a file list. >>> strip_toplevel_name(['a', 'a/b', 'a/c', 'a/c/d']) ['b', 'c', 'c/d'] >>> strip_toplevel_name(['a/b', 'a/c', 'a/c/d']) ['b', 'c', 'c/d'] """ if not filelist: return filelist prefix = filelist[0] if '/' in prefix: prefix = prefix.partition('/')[0] + '/' names = filelist else: prefix = prefix + '/' names = filelist[1:] for name in names: if not name.startswith(prefix): raise Failure("File doesn't have the common prefix (%s): %s" % (name, prefix)) return [name[len(prefix):] for name in names]
python
def strip_toplevel_name(filelist): """Strip toplevel name from a file list. >>> strip_toplevel_name(['a', 'a/b', 'a/c', 'a/c/d']) ['b', 'c', 'c/d'] >>> strip_toplevel_name(['a/b', 'a/c', 'a/c/d']) ['b', 'c', 'c/d'] """ if not filelist: return filelist prefix = filelist[0] if '/' in prefix: prefix = prefix.partition('/')[0] + '/' names = filelist else: prefix = prefix + '/' names = filelist[1:] for name in names: if not name.startswith(prefix): raise Failure("File doesn't have the common prefix (%s): %s" % (name, prefix)) return [name[len(prefix):] for name in names]
[ "def", "strip_toplevel_name", "(", "filelist", ")", ":", "if", "not", "filelist", ":", "return", "filelist", "prefix", "=", "filelist", "[", "0", "]", "if", "'/'", "in", "prefix", ":", "prefix", "=", "prefix", ".", "partition", "(", "'/'", ")", "[", "0", "]", "+", "'/'", "names", "=", "filelist", "else", ":", "prefix", "=", "prefix", "+", "'/'", "names", "=", "filelist", "[", "1", ":", "]", "for", "name", "in", "names", ":", "if", "not", "name", ".", "startswith", "(", "prefix", ")", ":", "raise", "Failure", "(", "\"File doesn't have the common prefix (%s): %s\"", "%", "(", "name", ",", "prefix", ")", ")", "return", "[", "name", "[", "len", "(", "prefix", ")", ":", "]", "for", "name", "in", "names", "]" ]
Strip toplevel name from a file list. >>> strip_toplevel_name(['a', 'a/b', 'a/c', 'a/c/d']) ['b', 'c', 'c/d'] >>> strip_toplevel_name(['a/b', 'a/c', 'a/c/d']) ['b', 'c', 'c/d']
[ "Strip", "toplevel", "name", "from", "a", "file", "list", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L280-L303
train
235,948
mgedmin/check-manifest
check_manifest.py
detect_vcs
def detect_vcs(): """Detect the version control system used for the current directory.""" location = os.path.abspath('.') while True: for vcs in Git, Mercurial, Bazaar, Subversion: if vcs.detect(location): return vcs parent = os.path.dirname(location) if parent == location: raise Failure("Couldn't find version control data" " (git/hg/bzr/svn supported)") location = parent
python
def detect_vcs(): """Detect the version control system used for the current directory.""" location = os.path.abspath('.') while True: for vcs in Git, Mercurial, Bazaar, Subversion: if vcs.detect(location): return vcs parent = os.path.dirname(location) if parent == location: raise Failure("Couldn't find version control data" " (git/hg/bzr/svn supported)") location = parent
[ "def", "detect_vcs", "(", ")", ":", "location", "=", "os", ".", "path", ".", "abspath", "(", "'.'", ")", "while", "True", ":", "for", "vcs", "in", "Git", ",", "Mercurial", ",", "Bazaar", ",", "Subversion", ":", "if", "vcs", ".", "detect", "(", "location", ")", ":", "return", "vcs", "parent", "=", "os", ".", "path", ".", "dirname", "(", "location", ")", "if", "parent", "==", "location", ":", "raise", "Failure", "(", "\"Couldn't find version control data\"", "\" (git/hg/bzr/svn supported)\"", ")", "location", "=", "parent" ]
Detect the version control system used for the current directory.
[ "Detect", "the", "version", "control", "system", "used", "for", "the", "current", "directory", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L465-L476
train
235,949
mgedmin/check-manifest
check_manifest.py
normalize_name
def normalize_name(name): """Some VCS print directory names with trailing slashes. Strip them. Easiest is to normalize the path. And encodings may trip us up too, especially when comparing lists of files. Plus maybe lowercase versus uppercase. """ name = os.path.normpath(name) name = unicodify(name) if sys.platform == 'darwin': # Mac OSX may have problems comparing non-ascii filenames, so # we convert them. name = unicodedata.normalize('NFC', name) return name
python
def normalize_name(name): """Some VCS print directory names with trailing slashes. Strip them. Easiest is to normalize the path. And encodings may trip us up too, especially when comparing lists of files. Plus maybe lowercase versus uppercase. """ name = os.path.normpath(name) name = unicodify(name) if sys.platform == 'darwin': # Mac OSX may have problems comparing non-ascii filenames, so # we convert them. name = unicodedata.normalize('NFC', name) return name
[ "def", "normalize_name", "(", "name", ")", ":", "name", "=", "os", ".", "path", ".", "normpath", "(", "name", ")", "name", "=", "unicodify", "(", "name", ")", "if", "sys", ".", "platform", "==", "'darwin'", ":", "# Mac OSX may have problems comparing non-ascii filenames, so", "# we convert them.", "name", "=", "unicodedata", ".", "normalize", "(", "'NFC'", ",", "name", ")", "return", "name" ]
Some VCS print directory names with trailing slashes. Strip them. Easiest is to normalize the path. And encodings may trip us up too, especially when comparing lists of files. Plus maybe lowercase versus uppercase.
[ "Some", "VCS", "print", "directory", "names", "with", "trailing", "slashes", ".", "Strip", "them", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L490-L504
train
235,950
mgedmin/check-manifest
check_manifest.py
read_config
def read_config(): """Read configuration from file if possible.""" # XXX modifies global state, which is kind of evil config = _load_config() if config.get(CFG_IGNORE_DEFAULT_RULES[1], False): del IGNORE[:] if CFG_IGNORE[1] in config: IGNORE.extend(p for p in config[CFG_IGNORE[1]] if p) if CFG_IGNORE_BAD_IDEAS[1] in config: IGNORE_BAD_IDEAS.extend(p for p in config[CFG_IGNORE_BAD_IDEAS[1]] if p)
python
def read_config(): """Read configuration from file if possible.""" # XXX modifies global state, which is kind of evil config = _load_config() if config.get(CFG_IGNORE_DEFAULT_RULES[1], False): del IGNORE[:] if CFG_IGNORE[1] in config: IGNORE.extend(p for p in config[CFG_IGNORE[1]] if p) if CFG_IGNORE_BAD_IDEAS[1] in config: IGNORE_BAD_IDEAS.extend(p for p in config[CFG_IGNORE_BAD_IDEAS[1]] if p)
[ "def", "read_config", "(", ")", ":", "# XXX modifies global state, which is kind of evil", "config", "=", "_load_config", "(", ")", "if", "config", ".", "get", "(", "CFG_IGNORE_DEFAULT_RULES", "[", "1", "]", ",", "False", ")", ":", "del", "IGNORE", "[", ":", "]", "if", "CFG_IGNORE", "[", "1", "]", "in", "config", ":", "IGNORE", ".", "extend", "(", "p", "for", "p", "in", "config", "[", "CFG_IGNORE", "[", "1", "]", "]", "if", "p", ")", "if", "CFG_IGNORE_BAD_IDEAS", "[", "1", "]", "in", "config", ":", "IGNORE_BAD_IDEAS", ".", "extend", "(", "p", "for", "p", "in", "config", "[", "CFG_IGNORE_BAD_IDEAS", "[", "1", "]", "]", "if", "p", ")" ]
Read configuration from file if possible.
[ "Read", "configuration", "from", "file", "if", "possible", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L593-L602
train
235,951
mgedmin/check-manifest
check_manifest.py
_load_config
def _load_config(): """Searches for config files, reads them and returns a dictionary Looks for a ``check-manifest`` section in ``pyproject.toml``, ``setup.cfg``, and ``tox.ini``, in that order. The first file that exists and has that section will be loaded and returned as a dictionary. """ if os.path.exists("pyproject.toml"): config = toml.load("pyproject.toml") if CFG_SECTION_CHECK_MANIFEST in config.get("tool", {}): return config["tool"][CFG_SECTION_CHECK_MANIFEST] search_files = ['setup.cfg', 'tox.ini'] config_parser = ConfigParser.ConfigParser() for filename in search_files: if (config_parser.read([filename]) and config_parser.has_section(CFG_SECTION_CHECK_MANIFEST)): config = {} if config_parser.has_option(*CFG_IGNORE_DEFAULT_RULES): ignore_defaults = config_parser.getboolean(*CFG_IGNORE_DEFAULT_RULES) config[CFG_IGNORE_DEFAULT_RULES[1]] = ignore_defaults if config_parser.has_option(*CFG_IGNORE): patterns = [ p.strip() for p in config_parser.get(*CFG_IGNORE).splitlines() ] config[CFG_IGNORE[1]] = patterns if config_parser.has_option(*CFG_IGNORE_BAD_IDEAS): patterns = [ p.strip() for p in config_parser.get(*CFG_IGNORE_BAD_IDEAS).splitlines() ] config[CFG_IGNORE_BAD_IDEAS[1]] = patterns return config return {}
python
def _load_config(): """Searches for config files, reads them and returns a dictionary Looks for a ``check-manifest`` section in ``pyproject.toml``, ``setup.cfg``, and ``tox.ini``, in that order. The first file that exists and has that section will be loaded and returned as a dictionary. """ if os.path.exists("pyproject.toml"): config = toml.load("pyproject.toml") if CFG_SECTION_CHECK_MANIFEST in config.get("tool", {}): return config["tool"][CFG_SECTION_CHECK_MANIFEST] search_files = ['setup.cfg', 'tox.ini'] config_parser = ConfigParser.ConfigParser() for filename in search_files: if (config_parser.read([filename]) and config_parser.has_section(CFG_SECTION_CHECK_MANIFEST)): config = {} if config_parser.has_option(*CFG_IGNORE_DEFAULT_RULES): ignore_defaults = config_parser.getboolean(*CFG_IGNORE_DEFAULT_RULES) config[CFG_IGNORE_DEFAULT_RULES[1]] = ignore_defaults if config_parser.has_option(*CFG_IGNORE): patterns = [ p.strip() for p in config_parser.get(*CFG_IGNORE).splitlines() ] config[CFG_IGNORE[1]] = patterns if config_parser.has_option(*CFG_IGNORE_BAD_IDEAS): patterns = [ p.strip() for p in config_parser.get(*CFG_IGNORE_BAD_IDEAS).splitlines() ] config[CFG_IGNORE_BAD_IDEAS[1]] = patterns return config return {}
[ "def", "_load_config", "(", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "\"pyproject.toml\"", ")", ":", "config", "=", "toml", ".", "load", "(", "\"pyproject.toml\"", ")", "if", "CFG_SECTION_CHECK_MANIFEST", "in", "config", ".", "get", "(", "\"tool\"", ",", "{", "}", ")", ":", "return", "config", "[", "\"tool\"", "]", "[", "CFG_SECTION_CHECK_MANIFEST", "]", "search_files", "=", "[", "'setup.cfg'", ",", "'tox.ini'", "]", "config_parser", "=", "ConfigParser", ".", "ConfigParser", "(", ")", "for", "filename", "in", "search_files", ":", "if", "(", "config_parser", ".", "read", "(", "[", "filename", "]", ")", "and", "config_parser", ".", "has_section", "(", "CFG_SECTION_CHECK_MANIFEST", ")", ")", ":", "config", "=", "{", "}", "if", "config_parser", ".", "has_option", "(", "*", "CFG_IGNORE_DEFAULT_RULES", ")", ":", "ignore_defaults", "=", "config_parser", ".", "getboolean", "(", "*", "CFG_IGNORE_DEFAULT_RULES", ")", "config", "[", "CFG_IGNORE_DEFAULT_RULES", "[", "1", "]", "]", "=", "ignore_defaults", "if", "config_parser", ".", "has_option", "(", "*", "CFG_IGNORE", ")", ":", "patterns", "=", "[", "p", ".", "strip", "(", ")", "for", "p", "in", "config_parser", ".", "get", "(", "*", "CFG_IGNORE", ")", ".", "splitlines", "(", ")", "]", "config", "[", "CFG_IGNORE", "[", "1", "]", "]", "=", "patterns", "if", "config_parser", ".", "has_option", "(", "*", "CFG_IGNORE_BAD_IDEAS", ")", ":", "patterns", "=", "[", "p", ".", "strip", "(", ")", "for", "p", "in", "config_parser", ".", "get", "(", "*", "CFG_IGNORE_BAD_IDEAS", ")", ".", "splitlines", "(", ")", "]", "config", "[", "CFG_IGNORE_BAD_IDEAS", "[", "1", "]", "]", "=", "patterns", "return", "config", "return", "{", "}" ]
Searches for config files, reads them and returns a dictionary Looks for a ``check-manifest`` section in ``pyproject.toml``, ``setup.cfg``, and ``tox.ini``, in that order. The first file that exists and has that section will be loaded and returned as a dictionary.
[ "Searches", "for", "config", "files", "reads", "them", "and", "returns", "a", "dictionary" ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L605-L646
train
235,952
mgedmin/check-manifest
check_manifest.py
read_manifest
def read_manifest(): """Read existing configuration from MANIFEST.in. We use that to ignore anything the MANIFEST.in ignores. """ # XXX modifies global state, which is kind of evil if not os.path.isfile('MANIFEST.in'): return ignore, ignore_regexps = _get_ignore_from_manifest('MANIFEST.in') IGNORE.extend(ignore) IGNORE_REGEXPS.extend(ignore_regexps)
python
def read_manifest(): """Read existing configuration from MANIFEST.in. We use that to ignore anything the MANIFEST.in ignores. """ # XXX modifies global state, which is kind of evil if not os.path.isfile('MANIFEST.in'): return ignore, ignore_regexps = _get_ignore_from_manifest('MANIFEST.in') IGNORE.extend(ignore) IGNORE_REGEXPS.extend(ignore_regexps)
[ "def", "read_manifest", "(", ")", ":", "# XXX modifies global state, which is kind of evil", "if", "not", "os", ".", "path", ".", "isfile", "(", "'MANIFEST.in'", ")", ":", "return", "ignore", ",", "ignore_regexps", "=", "_get_ignore_from_manifest", "(", "'MANIFEST.in'", ")", "IGNORE", ".", "extend", "(", "ignore", ")", "IGNORE_REGEXPS", ".", "extend", "(", "ignore_regexps", ")" ]
Read existing configuration from MANIFEST.in. We use that to ignore anything the MANIFEST.in ignores.
[ "Read", "existing", "configuration", "from", "MANIFEST", ".", "in", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L649-L659
train
235,953
mgedmin/check-manifest
check_manifest.py
file_matches
def file_matches(filename, patterns): """Does this filename match any of the patterns?""" return any(fnmatch.fnmatch(filename, pat) or fnmatch.fnmatch(os.path.basename(filename), pat) for pat in patterns)
python
def file_matches(filename, patterns): """Does this filename match any of the patterns?""" return any(fnmatch.fnmatch(filename, pat) or fnmatch.fnmatch(os.path.basename(filename), pat) for pat in patterns)
[ "def", "file_matches", "(", "filename", ",", "patterns", ")", ":", "return", "any", "(", "fnmatch", ".", "fnmatch", "(", "filename", ",", "pat", ")", "or", "fnmatch", ".", "fnmatch", "(", "os", ".", "path", ".", "basename", "(", "filename", ")", ",", "pat", ")", "for", "pat", "in", "patterns", ")" ]
Does this filename match any of the patterns?
[ "Does", "this", "filename", "match", "any", "of", "the", "patterns?" ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L774-L778
train
235,954
mgedmin/check-manifest
check_manifest.py
file_matches_regexps
def file_matches_regexps(filename, patterns): """Does this filename match any of the regular expressions?""" return any(re.match(pat, filename) for pat in patterns)
python
def file_matches_regexps(filename, patterns): """Does this filename match any of the regular expressions?""" return any(re.match(pat, filename) for pat in patterns)
[ "def", "file_matches_regexps", "(", "filename", ",", "patterns", ")", ":", "return", "any", "(", "re", ".", "match", "(", "pat", ",", "filename", ")", "for", "pat", "in", "patterns", ")" ]
Does this filename match any of the regular expressions?
[ "Does", "this", "filename", "match", "any", "of", "the", "regular", "expressions?" ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L781-L783
train
235,955
mgedmin/check-manifest
check_manifest.py
strip_sdist_extras
def strip_sdist_extras(filelist): """Strip generated files that are only present in source distributions. We also strip files that are ignored for other reasons, like command line arguments, setup.cfg rules or MANIFEST.in rules. """ return [name for name in filelist if not file_matches(name, IGNORE) and not file_matches_regexps(name, IGNORE_REGEXPS)]
python
def strip_sdist_extras(filelist): """Strip generated files that are only present in source distributions. We also strip files that are ignored for other reasons, like command line arguments, setup.cfg rules or MANIFEST.in rules. """ return [name for name in filelist if not file_matches(name, IGNORE) and not file_matches_regexps(name, IGNORE_REGEXPS)]
[ "def", "strip_sdist_extras", "(", "filelist", ")", ":", "return", "[", "name", "for", "name", "in", "filelist", "if", "not", "file_matches", "(", "name", ",", "IGNORE", ")", "and", "not", "file_matches_regexps", "(", "name", ",", "IGNORE_REGEXPS", ")", "]" ]
Strip generated files that are only present in source distributions. We also strip files that are ignored for other reasons, like command line arguments, setup.cfg rules or MANIFEST.in rules.
[ "Strip", "generated", "files", "that", "are", "only", "present", "in", "source", "distributions", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L786-L794
train
235,956
mgedmin/check-manifest
check_manifest.py
find_suggestions
def find_suggestions(filelist): """Suggest MANIFEST.in patterns for missing files.""" suggestions = set() unknowns = [] for filename in filelist: if os.path.isdir(filename): # it's impossible to add empty directories via MANIFEST.in anyway, # and non-empty directories will be added automatically when we # specify patterns for files inside them continue for pattern, suggestion in SUGGESTIONS: m = pattern.match(filename) if m is not None: suggestions.add(pattern.sub(suggestion, filename)) break else: unknowns.append(filename) return sorted(suggestions), unknowns
python
def find_suggestions(filelist): """Suggest MANIFEST.in patterns for missing files.""" suggestions = set() unknowns = [] for filename in filelist: if os.path.isdir(filename): # it's impossible to add empty directories via MANIFEST.in anyway, # and non-empty directories will be added automatically when we # specify patterns for files inside them continue for pattern, suggestion in SUGGESTIONS: m = pattern.match(filename) if m is not None: suggestions.add(pattern.sub(suggestion, filename)) break else: unknowns.append(filename) return sorted(suggestions), unknowns
[ "def", "find_suggestions", "(", "filelist", ")", ":", "suggestions", "=", "set", "(", ")", "unknowns", "=", "[", "]", "for", "filename", "in", "filelist", ":", "if", "os", ".", "path", ".", "isdir", "(", "filename", ")", ":", "# it's impossible to add empty directories via MANIFEST.in anyway,", "# and non-empty directories will be added automatically when we", "# specify patterns for files inside them", "continue", "for", "pattern", ",", "suggestion", "in", "SUGGESTIONS", ":", "m", "=", "pattern", ".", "match", "(", "filename", ")", "if", "m", "is", "not", "None", ":", "suggestions", ".", "add", "(", "pattern", ".", "sub", "(", "suggestion", ",", "filename", ")", ")", "break", "else", ":", "unknowns", ".", "append", "(", "filename", ")", "return", "sorted", "(", "suggestions", ")", ",", "unknowns" ]
Suggest MANIFEST.in patterns for missing files.
[ "Suggest", "MANIFEST", ".", "in", "patterns", "for", "missing", "files", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L803-L820
train
235,957
mgedmin/check-manifest
check_manifest.py
extract_version_from_filename
def extract_version_from_filename(filename): """Extract version number from sdist filename.""" filename = os.path.splitext(os.path.basename(filename))[0] if filename.endswith('.tar'): filename = os.path.splitext(filename)[0] return filename.partition('-')[2]
python
def extract_version_from_filename(filename): """Extract version number from sdist filename.""" filename = os.path.splitext(os.path.basename(filename))[0] if filename.endswith('.tar'): filename = os.path.splitext(filename)[0] return filename.partition('-')[2]
[ "def", "extract_version_from_filename", "(", "filename", ")", ":", "filename", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "filename", ")", ")", "[", "0", "]", "if", "filename", ".", "endswith", "(", "'.tar'", ")", ":", "filename", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]", "return", "filename", ".", "partition", "(", "'-'", ")", "[", "2", "]" ]
Extract version number from sdist filename.
[ "Extract", "version", "number", "from", "sdist", "filename", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L832-L837
train
235,958
mgedmin/check-manifest
check_manifest.py
zest_releaser_check
def zest_releaser_check(data): """Check the completeness of MANIFEST.in before the release. This is an entry point for zest.releaser. See the documentation at https://zestreleaser.readthedocs.io/en/latest/entrypoints.html """ from zest.releaser.utils import ask source_tree = data['workingdir'] if not is_package(source_tree): # You can use zest.releaser on things that are not Python packages. # It's pointless to run check-manifest in those circumstances. # See https://github.com/mgedmin/check-manifest/issues/9 for details. return if not ask("Do you want to run check-manifest?"): return try: if not check_manifest(source_tree): if not ask("MANIFEST.in has problems. " " Do you want to continue despite that?", default=False): sys.exit(1) except Failure as e: error(str(e)) if not ask("Something bad happened. " " Do you want to continue despite that?", default=False): sys.exit(2)
python
def zest_releaser_check(data): """Check the completeness of MANIFEST.in before the release. This is an entry point for zest.releaser. See the documentation at https://zestreleaser.readthedocs.io/en/latest/entrypoints.html """ from zest.releaser.utils import ask source_tree = data['workingdir'] if not is_package(source_tree): # You can use zest.releaser on things that are not Python packages. # It's pointless to run check-manifest in those circumstances. # See https://github.com/mgedmin/check-manifest/issues/9 for details. return if not ask("Do you want to run check-manifest?"): return try: if not check_manifest(source_tree): if not ask("MANIFEST.in has problems. " " Do you want to continue despite that?", default=False): sys.exit(1) except Failure as e: error(str(e)) if not ask("Something bad happened. " " Do you want to continue despite that?", default=False): sys.exit(2)
[ "def", "zest_releaser_check", "(", "data", ")", ":", "from", "zest", ".", "releaser", ".", "utils", "import", "ask", "source_tree", "=", "data", "[", "'workingdir'", "]", "if", "not", "is_package", "(", "source_tree", ")", ":", "# You can use zest.releaser on things that are not Python packages.", "# It's pointless to run check-manifest in those circumstances.", "# See https://github.com/mgedmin/check-manifest/issues/9 for details.", "return", "if", "not", "ask", "(", "\"Do you want to run check-manifest?\"", ")", ":", "return", "try", ":", "if", "not", "check_manifest", "(", "source_tree", ")", ":", "if", "not", "ask", "(", "\"MANIFEST.in has problems. \"", "\" Do you want to continue despite that?\"", ",", "default", "=", "False", ")", ":", "sys", ".", "exit", "(", "1", ")", "except", "Failure", "as", "e", ":", "error", "(", "str", "(", "e", ")", ")", "if", "not", "ask", "(", "\"Something bad happened. \"", "\" Do you want to continue despite that?\"", ",", "default", "=", "False", ")", ":", "sys", ".", "exit", "(", "2", ")" ]
Check the completeness of MANIFEST.in before the release. This is an entry point for zest.releaser. See the documentation at https://zestreleaser.readthedocs.io/en/latest/entrypoints.html
[ "Check", "the", "completeness", "of", "MANIFEST", ".", "in", "before", "the", "release", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L1000-L1024
train
235,959
mgedmin/check-manifest
check_manifest.py
Git.get_versioned_files
def get_versioned_files(cls): """List all files versioned by git in the current directory.""" files = cls._git_ls_files() submodules = cls._list_submodules() for subdir in submodules: subdir = os.path.relpath(subdir).replace(os.path.sep, '/') files += add_prefix_to_each(subdir, cls._git_ls_files(subdir)) return add_directories(files)
python
def get_versioned_files(cls): """List all files versioned by git in the current directory.""" files = cls._git_ls_files() submodules = cls._list_submodules() for subdir in submodules: subdir = os.path.relpath(subdir).replace(os.path.sep, '/') files += add_prefix_to_each(subdir, cls._git_ls_files(subdir)) return add_directories(files)
[ "def", "get_versioned_files", "(", "cls", ")", ":", "files", "=", "cls", ".", "_git_ls_files", "(", ")", "submodules", "=", "cls", ".", "_list_submodules", "(", ")", "for", "subdir", "in", "submodules", ":", "subdir", "=", "os", ".", "path", ".", "relpath", "(", "subdir", ")", ".", "replace", "(", "os", ".", "path", ".", "sep", ",", "'/'", ")", "files", "+=", "add_prefix_to_each", "(", "subdir", ",", "cls", ".", "_git_ls_files", "(", "subdir", ")", ")", "return", "add_directories", "(", "files", ")" ]
List all files versioned by git in the current directory.
[ "List", "all", "files", "versioned", "by", "git", "in", "the", "current", "directory", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L337-L344
train
235,960
mgedmin/check-manifest
check_manifest.py
Bazaar.get_versioned_files
def get_versioned_files(cls): """List all files versioned in Bazaar in the current directory.""" encoding = cls._get_terminal_encoding() output = run(['bzr', 'ls', '-VR'], encoding=encoding) return output.splitlines()
python
def get_versioned_files(cls): """List all files versioned in Bazaar in the current directory.""" encoding = cls._get_terminal_encoding() output = run(['bzr', 'ls', '-VR'], encoding=encoding) return output.splitlines()
[ "def", "get_versioned_files", "(", "cls", ")", ":", "encoding", "=", "cls", ".", "_get_terminal_encoding", "(", ")", "output", "=", "run", "(", "[", "'bzr'", ",", "'ls'", ",", "'-VR'", "]", ",", "encoding", "=", "encoding", ")", "return", "output", ".", "splitlines", "(", ")" ]
List all files versioned in Bazaar in the current directory.
[ "List", "all", "files", "versioned", "in", "Bazaar", "in", "the", "current", "directory", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L404-L408
train
235,961
mgedmin/check-manifest
check_manifest.py
Subversion.get_versioned_files
def get_versioned_files(cls): """List all files under SVN control in the current directory.""" output = run(['svn', 'st', '-vq', '--xml'], decode=False) tree = ET.XML(output) return sorted(entry.get('path') for entry in tree.findall('.//entry') if cls.is_interesting(entry))
python
def get_versioned_files(cls): """List all files under SVN control in the current directory.""" output = run(['svn', 'st', '-vq', '--xml'], decode=False) tree = ET.XML(output) return sorted(entry.get('path') for entry in tree.findall('.//entry') if cls.is_interesting(entry))
[ "def", "get_versioned_files", "(", "cls", ")", ":", "output", "=", "run", "(", "[", "'svn'", ",", "'st'", ",", "'-vq'", ",", "'--xml'", "]", ",", "decode", "=", "False", ")", "tree", "=", "ET", ".", "XML", "(", "output", ")", "return", "sorted", "(", "entry", ".", "get", "(", "'path'", ")", "for", "entry", "in", "tree", ".", "findall", "(", "'.//entry'", ")", "if", "cls", ".", "is_interesting", "(", "entry", ")", ")" ]
List all files under SVN control in the current directory.
[ "List", "all", "files", "under", "SVN", "control", "in", "the", "current", "directory", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L415-L420
train
235,962
mgedmin/check-manifest
check_manifest.py
Subversion.is_interesting
def is_interesting(entry): """Is this entry interesting? ``entry`` is an XML node representing one entry of the svn status XML output. It looks like this:: <entry path="unchanged.txt"> <wc-status item="normal" revision="1" props="none"> <commit revision="1"> <author>mg</author> <date>2015-02-06T07:52:38.163516Z</date> </commit> </wc-status> </entry> <entry path="added-but-not-committed.txt"> <wc-status item="added" revision="-1" props="none"></wc-status> </entry> <entry path="ext"> <wc-status item="external" props="none"></wc-status> </entry> <entry path="unknown.txt"> <wc-status props="none" item="unversioned"></wc-status> </entry> """ if entry.get('path') == '.': return False status = entry.find('wc-status') if status is None: warning('svn status --xml parse error: <entry path="%s"> without' ' <wc-status>' % entry.get('path')) return False # For SVN externals we get two entries: one mentioning the # existence of the external, and one about the status of the external. if status.get('item') in ('unversioned', 'external'): return False return True
python
def is_interesting(entry): """Is this entry interesting? ``entry`` is an XML node representing one entry of the svn status XML output. It looks like this:: <entry path="unchanged.txt"> <wc-status item="normal" revision="1" props="none"> <commit revision="1"> <author>mg</author> <date>2015-02-06T07:52:38.163516Z</date> </commit> </wc-status> </entry> <entry path="added-but-not-committed.txt"> <wc-status item="added" revision="-1" props="none"></wc-status> </entry> <entry path="ext"> <wc-status item="external" props="none"></wc-status> </entry> <entry path="unknown.txt"> <wc-status props="none" item="unversioned"></wc-status> </entry> """ if entry.get('path') == '.': return False status = entry.find('wc-status') if status is None: warning('svn status --xml parse error: <entry path="%s"> without' ' <wc-status>' % entry.get('path')) return False # For SVN externals we get two entries: one mentioning the # existence of the external, and one about the status of the external. if status.get('item') in ('unversioned', 'external'): return False return True
[ "def", "is_interesting", "(", "entry", ")", ":", "if", "entry", ".", "get", "(", "'path'", ")", "==", "'.'", ":", "return", "False", "status", "=", "entry", ".", "find", "(", "'wc-status'", ")", "if", "status", "is", "None", ":", "warning", "(", "'svn status --xml parse error: <entry path=\"%s\"> without'", "' <wc-status>'", "%", "entry", ".", "get", "(", "'path'", ")", ")", "return", "False", "# For SVN externals we get two entries: one mentioning the", "# existence of the external, and one about the status of the external.", "if", "status", ".", "get", "(", "'item'", ")", "in", "(", "'unversioned'", ",", "'external'", ")", ":", "return", "False", "return", "True" ]
Is this entry interesting? ``entry`` is an XML node representing one entry of the svn status XML output. It looks like this:: <entry path="unchanged.txt"> <wc-status item="normal" revision="1" props="none"> <commit revision="1"> <author>mg</author> <date>2015-02-06T07:52:38.163516Z</date> </commit> </wc-status> </entry> <entry path="added-but-not-committed.txt"> <wc-status item="added" revision="-1" props="none"></wc-status> </entry> <entry path="ext"> <wc-status item="external" props="none"></wc-status> </entry> <entry path="unknown.txt"> <wc-status props="none" item="unversioned"></wc-status> </entry>
[ "Is", "this", "entry", "interesting?" ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L423-L462
train
235,963
awslabs/aws-serverlessrepo-python
serverlessrepo/application_policy.py
ApplicationPolicy.validate
def validate(self): """ Check if the formats of principals and actions are valid. :return: True, if the policy is valid :raises: InvalidApplicationPolicyError """ if not self.principals: raise InvalidApplicationPolicyError(error_message='principals not provided') if not self.actions: raise InvalidApplicationPolicyError(error_message='actions not provided') if any(not self._PRINCIPAL_PATTERN.match(p) for p in self.principals): raise InvalidApplicationPolicyError( error_message='principal should be 12-digit AWS account ID or "*"') unsupported_actions = sorted(set(self.actions) - set(self.SUPPORTED_ACTIONS)) if unsupported_actions: raise InvalidApplicationPolicyError( error_message='{} not supported'.format(', '.join(unsupported_actions))) return True
python
def validate(self): """ Check if the formats of principals and actions are valid. :return: True, if the policy is valid :raises: InvalidApplicationPolicyError """ if not self.principals: raise InvalidApplicationPolicyError(error_message='principals not provided') if not self.actions: raise InvalidApplicationPolicyError(error_message='actions not provided') if any(not self._PRINCIPAL_PATTERN.match(p) for p in self.principals): raise InvalidApplicationPolicyError( error_message='principal should be 12-digit AWS account ID or "*"') unsupported_actions = sorted(set(self.actions) - set(self.SUPPORTED_ACTIONS)) if unsupported_actions: raise InvalidApplicationPolicyError( error_message='{} not supported'.format(', '.join(unsupported_actions))) return True
[ "def", "validate", "(", "self", ")", ":", "if", "not", "self", ".", "principals", ":", "raise", "InvalidApplicationPolicyError", "(", "error_message", "=", "'principals not provided'", ")", "if", "not", "self", ".", "actions", ":", "raise", "InvalidApplicationPolicyError", "(", "error_message", "=", "'actions not provided'", ")", "if", "any", "(", "not", "self", ".", "_PRINCIPAL_PATTERN", ".", "match", "(", "p", ")", "for", "p", "in", "self", ".", "principals", ")", ":", "raise", "InvalidApplicationPolicyError", "(", "error_message", "=", "'principal should be 12-digit AWS account ID or \"*\"'", ")", "unsupported_actions", "=", "sorted", "(", "set", "(", "self", ".", "actions", ")", "-", "set", "(", "self", ".", "SUPPORTED_ACTIONS", ")", ")", "if", "unsupported_actions", ":", "raise", "InvalidApplicationPolicyError", "(", "error_message", "=", "'{} not supported'", ".", "format", "(", "', '", ".", "join", "(", "unsupported_actions", ")", ")", ")", "return", "True" ]
Check if the formats of principals and actions are valid. :return: True, if the policy is valid :raises: InvalidApplicationPolicyError
[ "Check", "if", "the", "formats", "of", "principals", "and", "actions", "are", "valid", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/application_policy.py#L44-L66
train
235,964
awslabs/aws-serverlessrepo-python
serverlessrepo/publish.py
publish_application
def publish_application(template, sar_client=None): """ Create a new application or new application version in SAR. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :return: Dictionary containing application id, actions taken, and updated details :rtype: dict :raises ValueError """ if not template: raise ValueError('Require SAM template to publish the application') if not sar_client: sar_client = boto3.client('serverlessrepo') template_dict = _get_template_dict(template) app_metadata = get_app_metadata(template_dict) stripped_template_dict = strip_app_metadata(template_dict) stripped_template = yaml_dump(stripped_template_dict) try: request = _create_application_request(app_metadata, stripped_template) response = sar_client.create_application(**request) application_id = response['ApplicationId'] actions = [CREATE_APPLICATION] except ClientError as e: if not _is_conflict_exception(e): raise _wrap_client_error(e) # Update the application if it already exists error_message = e.response['Error']['Message'] application_id = parse_application_id(error_message) try: request = _update_application_request(app_metadata, application_id) sar_client.update_application(**request) actions = [UPDATE_APPLICATION] except ClientError as e: raise _wrap_client_error(e) # Create application version if semantic version is specified if app_metadata.semantic_version: try: request = _create_application_version_request(app_metadata, application_id, stripped_template) sar_client.create_application_version(**request) actions.append(CREATE_APPLICATION_VERSION) except ClientError as e: if not _is_conflict_exception(e): raise _wrap_client_error(e) return { 'application_id': application_id, 'actions': actions, 'details': _get_publish_details(actions, app_metadata.template_dict) }
python
def publish_application(template, sar_client=None): """ Create a new application or new application version in SAR. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :return: Dictionary containing application id, actions taken, and updated details :rtype: dict :raises ValueError """ if not template: raise ValueError('Require SAM template to publish the application') if not sar_client: sar_client = boto3.client('serverlessrepo') template_dict = _get_template_dict(template) app_metadata = get_app_metadata(template_dict) stripped_template_dict = strip_app_metadata(template_dict) stripped_template = yaml_dump(stripped_template_dict) try: request = _create_application_request(app_metadata, stripped_template) response = sar_client.create_application(**request) application_id = response['ApplicationId'] actions = [CREATE_APPLICATION] except ClientError as e: if not _is_conflict_exception(e): raise _wrap_client_error(e) # Update the application if it already exists error_message = e.response['Error']['Message'] application_id = parse_application_id(error_message) try: request = _update_application_request(app_metadata, application_id) sar_client.update_application(**request) actions = [UPDATE_APPLICATION] except ClientError as e: raise _wrap_client_error(e) # Create application version if semantic version is specified if app_metadata.semantic_version: try: request = _create_application_version_request(app_metadata, application_id, stripped_template) sar_client.create_application_version(**request) actions.append(CREATE_APPLICATION_VERSION) except ClientError as e: if not _is_conflict_exception(e): raise _wrap_client_error(e) return { 'application_id': application_id, 'actions': actions, 'details': _get_publish_details(actions, app_metadata.template_dict) }
[ "def", "publish_application", "(", "template", ",", "sar_client", "=", "None", ")", ":", "if", "not", "template", ":", "raise", "ValueError", "(", "'Require SAM template to publish the application'", ")", "if", "not", "sar_client", ":", "sar_client", "=", "boto3", ".", "client", "(", "'serverlessrepo'", ")", "template_dict", "=", "_get_template_dict", "(", "template", ")", "app_metadata", "=", "get_app_metadata", "(", "template_dict", ")", "stripped_template_dict", "=", "strip_app_metadata", "(", "template_dict", ")", "stripped_template", "=", "yaml_dump", "(", "stripped_template_dict", ")", "try", ":", "request", "=", "_create_application_request", "(", "app_metadata", ",", "stripped_template", ")", "response", "=", "sar_client", ".", "create_application", "(", "*", "*", "request", ")", "application_id", "=", "response", "[", "'ApplicationId'", "]", "actions", "=", "[", "CREATE_APPLICATION", "]", "except", "ClientError", "as", "e", ":", "if", "not", "_is_conflict_exception", "(", "e", ")", ":", "raise", "_wrap_client_error", "(", "e", ")", "# Update the application if it already exists", "error_message", "=", "e", ".", "response", "[", "'Error'", "]", "[", "'Message'", "]", "application_id", "=", "parse_application_id", "(", "error_message", ")", "try", ":", "request", "=", "_update_application_request", "(", "app_metadata", ",", "application_id", ")", "sar_client", ".", "update_application", "(", "*", "*", "request", ")", "actions", "=", "[", "UPDATE_APPLICATION", "]", "except", "ClientError", "as", "e", ":", "raise", "_wrap_client_error", "(", "e", ")", "# Create application version if semantic version is specified", "if", "app_metadata", ".", "semantic_version", ":", "try", ":", "request", "=", "_create_application_version_request", "(", "app_metadata", ",", "application_id", ",", "stripped_template", ")", "sar_client", ".", "create_application_version", "(", "*", "*", "request", ")", "actions", ".", "append", "(", "CREATE_APPLICATION_VERSION", ")", "except", "ClientError", "as", "e", ":", "if", "not", "_is_conflict_exception", "(", "e", ")", ":", "raise", "_wrap_client_error", "(", "e", ")", "return", "{", "'application_id'", ":", "application_id", ",", "'actions'", ":", "actions", ",", "'details'", ":", "_get_publish_details", "(", "actions", ",", "app_metadata", ".", "template_dict", ")", "}" ]
Create a new application or new application version in SAR. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :return: Dictionary containing application id, actions taken, and updated details :rtype: dict :raises ValueError
[ "Create", "a", "new", "application", "or", "new", "application", "version", "in", "SAR", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L21-L76
train
235,965
awslabs/aws-serverlessrepo-python
serverlessrepo/publish.py
update_application_metadata
def update_application_metadata(template, application_id, sar_client=None): """ Update the application metadata. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :raises ValueError """ if not template or not application_id: raise ValueError('Require SAM template and application ID to update application metadata') if not sar_client: sar_client = boto3.client('serverlessrepo') template_dict = _get_template_dict(template) app_metadata = get_app_metadata(template_dict) request = _update_application_request(app_metadata, application_id) sar_client.update_application(**request)
python
def update_application_metadata(template, application_id, sar_client=None): """ Update the application metadata. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :raises ValueError """ if not template or not application_id: raise ValueError('Require SAM template and application ID to update application metadata') if not sar_client: sar_client = boto3.client('serverlessrepo') template_dict = _get_template_dict(template) app_metadata = get_app_metadata(template_dict) request = _update_application_request(app_metadata, application_id) sar_client.update_application(**request)
[ "def", "update_application_metadata", "(", "template", ",", "application_id", ",", "sar_client", "=", "None", ")", ":", "if", "not", "template", "or", "not", "application_id", ":", "raise", "ValueError", "(", "'Require SAM template and application ID to update application metadata'", ")", "if", "not", "sar_client", ":", "sar_client", "=", "boto3", ".", "client", "(", "'serverlessrepo'", ")", "template_dict", "=", "_get_template_dict", "(", "template", ")", "app_metadata", "=", "get_app_metadata", "(", "template_dict", ")", "request", "=", "_update_application_request", "(", "app_metadata", ",", "application_id", ")", "sar_client", ".", "update_application", "(", "*", "*", "request", ")" ]
Update the application metadata. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :raises ValueError
[ "Update", "the", "application", "metadata", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L79-L100
train
235,966
awslabs/aws-serverlessrepo-python
serverlessrepo/publish.py
_get_template_dict
def _get_template_dict(template): """ Parse string template and or copy dictionary template. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :return: Template as a dictionary :rtype: dict :raises ValueError """ if isinstance(template, str): return parse_template(template) if isinstance(template, dict): return copy.deepcopy(template) raise ValueError('Input template should be a string or dictionary')
python
def _get_template_dict(template): """ Parse string template and or copy dictionary template. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :return: Template as a dictionary :rtype: dict :raises ValueError """ if isinstance(template, str): return parse_template(template) if isinstance(template, dict): return copy.deepcopy(template) raise ValueError('Input template should be a string or dictionary')
[ "def", "_get_template_dict", "(", "template", ")", ":", "if", "isinstance", "(", "template", ",", "str", ")", ":", "return", "parse_template", "(", "template", ")", "if", "isinstance", "(", "template", ",", "dict", ")", ":", "return", "copy", ".", "deepcopy", "(", "template", ")", "raise", "ValueError", "(", "'Input template should be a string or dictionary'", ")" ]
Parse string template and or copy dictionary template. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :return: Template as a dictionary :rtype: dict :raises ValueError
[ "Parse", "string", "template", "and", "or", "copy", "dictionary", "template", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L103-L119
train
235,967
awslabs/aws-serverlessrepo-python
serverlessrepo/publish.py
_create_application_request
def _create_application_request(app_metadata, template): """ Construct the request body to create application. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param template: A packaged YAML or JSON SAM template :type template: str :return: SAR CreateApplication request body :rtype: dict """ app_metadata.validate(['author', 'description', 'name']) request = { 'Author': app_metadata.author, 'Description': app_metadata.description, 'HomePageUrl': app_metadata.home_page_url, 'Labels': app_metadata.labels, 'LicenseUrl': app_metadata.license_url, 'Name': app_metadata.name, 'ReadmeUrl': app_metadata.readme_url, 'SemanticVersion': app_metadata.semantic_version, 'SourceCodeUrl': app_metadata.source_code_url, 'SpdxLicenseId': app_metadata.spdx_license_id, 'TemplateBody': template } # Remove None values return {k: v for k, v in request.items() if v}
python
def _create_application_request(app_metadata, template): """ Construct the request body to create application. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param template: A packaged YAML or JSON SAM template :type template: str :return: SAR CreateApplication request body :rtype: dict """ app_metadata.validate(['author', 'description', 'name']) request = { 'Author': app_metadata.author, 'Description': app_metadata.description, 'HomePageUrl': app_metadata.home_page_url, 'Labels': app_metadata.labels, 'LicenseUrl': app_metadata.license_url, 'Name': app_metadata.name, 'ReadmeUrl': app_metadata.readme_url, 'SemanticVersion': app_metadata.semantic_version, 'SourceCodeUrl': app_metadata.source_code_url, 'SpdxLicenseId': app_metadata.spdx_license_id, 'TemplateBody': template } # Remove None values return {k: v for k, v in request.items() if v}
[ "def", "_create_application_request", "(", "app_metadata", ",", "template", ")", ":", "app_metadata", ".", "validate", "(", "[", "'author'", ",", "'description'", ",", "'name'", "]", ")", "request", "=", "{", "'Author'", ":", "app_metadata", ".", "author", ",", "'Description'", ":", "app_metadata", ".", "description", ",", "'HomePageUrl'", ":", "app_metadata", ".", "home_page_url", ",", "'Labels'", ":", "app_metadata", ".", "labels", ",", "'LicenseUrl'", ":", "app_metadata", ".", "license_url", ",", "'Name'", ":", "app_metadata", ".", "name", ",", "'ReadmeUrl'", ":", "app_metadata", ".", "readme_url", ",", "'SemanticVersion'", ":", "app_metadata", ".", "semantic_version", ",", "'SourceCodeUrl'", ":", "app_metadata", ".", "source_code_url", ",", "'SpdxLicenseId'", ":", "app_metadata", ".", "spdx_license_id", ",", "'TemplateBody'", ":", "template", "}", "# Remove None values", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "request", ".", "items", "(", ")", "if", "v", "}" ]
Construct the request body to create application. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param template: A packaged YAML or JSON SAM template :type template: str :return: SAR CreateApplication request body :rtype: dict
[ "Construct", "the", "request", "body", "to", "create", "application", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L122-L148
train
235,968
awslabs/aws-serverlessrepo-python
serverlessrepo/publish.py
_update_application_request
def _update_application_request(app_metadata, application_id): """ Construct the request body to update application. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :return: SAR UpdateApplication request body :rtype: dict """ request = { 'ApplicationId': application_id, 'Author': app_metadata.author, 'Description': app_metadata.description, 'HomePageUrl': app_metadata.home_page_url, 'Labels': app_metadata.labels, 'ReadmeUrl': app_metadata.readme_url } return {k: v for k, v in request.items() if v}
python
def _update_application_request(app_metadata, application_id): """ Construct the request body to update application. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :return: SAR UpdateApplication request body :rtype: dict """ request = { 'ApplicationId': application_id, 'Author': app_metadata.author, 'Description': app_metadata.description, 'HomePageUrl': app_metadata.home_page_url, 'Labels': app_metadata.labels, 'ReadmeUrl': app_metadata.readme_url } return {k: v for k, v in request.items() if v}
[ "def", "_update_application_request", "(", "app_metadata", ",", "application_id", ")", ":", "request", "=", "{", "'ApplicationId'", ":", "application_id", ",", "'Author'", ":", "app_metadata", ".", "author", ",", "'Description'", ":", "app_metadata", ".", "description", ",", "'HomePageUrl'", ":", "app_metadata", ".", "home_page_url", ",", "'Labels'", ":", "app_metadata", ".", "labels", ",", "'ReadmeUrl'", ":", "app_metadata", ".", "readme_url", "}", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "request", ".", "items", "(", ")", "if", "v", "}" ]
Construct the request body to update application. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :return: SAR UpdateApplication request body :rtype: dict
[ "Construct", "the", "request", "body", "to", "update", "application", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L151-L170
train
235,969
awslabs/aws-serverlessrepo-python
serverlessrepo/publish.py
_create_application_version_request
def _create_application_version_request(app_metadata, application_id, template): """ Construct the request body to create application version. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param template: A packaged YAML or JSON SAM template :type template: str :return: SAR CreateApplicationVersion request body :rtype: dict """ app_metadata.validate(['semantic_version']) request = { 'ApplicationId': application_id, 'SemanticVersion': app_metadata.semantic_version, 'SourceCodeUrl': app_metadata.source_code_url, 'TemplateBody': template } return {k: v for k, v in request.items() if v}
python
def _create_application_version_request(app_metadata, application_id, template): """ Construct the request body to create application version. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param template: A packaged YAML or JSON SAM template :type template: str :return: SAR CreateApplicationVersion request body :rtype: dict """ app_metadata.validate(['semantic_version']) request = { 'ApplicationId': application_id, 'SemanticVersion': app_metadata.semantic_version, 'SourceCodeUrl': app_metadata.source_code_url, 'TemplateBody': template } return {k: v for k, v in request.items() if v}
[ "def", "_create_application_version_request", "(", "app_metadata", ",", "application_id", ",", "template", ")", ":", "app_metadata", ".", "validate", "(", "[", "'semantic_version'", "]", ")", "request", "=", "{", "'ApplicationId'", ":", "application_id", ",", "'SemanticVersion'", ":", "app_metadata", ".", "semantic_version", ",", "'SourceCodeUrl'", ":", "app_metadata", ".", "source_code_url", ",", "'TemplateBody'", ":", "template", "}", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "request", ".", "items", "(", ")", "if", "v", "}" ]
Construct the request body to create application version. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param template: A packaged YAML or JSON SAM template :type template: str :return: SAR CreateApplicationVersion request body :rtype: dict
[ "Construct", "the", "request", "body", "to", "create", "application", "version", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L173-L193
train
235,970
awslabs/aws-serverlessrepo-python
serverlessrepo/publish.py
_wrap_client_error
def _wrap_client_error(e): """ Wrap botocore ClientError exception into ServerlessRepoClientError. :param e: botocore exception :type e: ClientError :return: S3PermissionsRequired or InvalidS3UriError or general ServerlessRepoClientError """ error_code = e.response['Error']['Code'] message = e.response['Error']['Message'] if error_code == 'BadRequestException': if "Failed to copy S3 object. Access denied:" in message: match = re.search('bucket=(.+?), key=(.+?)$', message) if match: return S3PermissionsRequired(bucket=match.group(1), key=match.group(2)) if "Invalid S3 URI" in message: return InvalidS3UriError(message=message) return ServerlessRepoClientError(message=message)
python
def _wrap_client_error(e): """ Wrap botocore ClientError exception into ServerlessRepoClientError. :param e: botocore exception :type e: ClientError :return: S3PermissionsRequired or InvalidS3UriError or general ServerlessRepoClientError """ error_code = e.response['Error']['Code'] message = e.response['Error']['Message'] if error_code == 'BadRequestException': if "Failed to copy S3 object. Access denied:" in message: match = re.search('bucket=(.+?), key=(.+?)$', message) if match: return S3PermissionsRequired(bucket=match.group(1), key=match.group(2)) if "Invalid S3 URI" in message: return InvalidS3UriError(message=message) return ServerlessRepoClientError(message=message)
[ "def", "_wrap_client_error", "(", "e", ")", ":", "error_code", "=", "e", ".", "response", "[", "'Error'", "]", "[", "'Code'", "]", "message", "=", "e", ".", "response", "[", "'Error'", "]", "[", "'Message'", "]", "if", "error_code", "==", "'BadRequestException'", ":", "if", "\"Failed to copy S3 object. Access denied:\"", "in", "message", ":", "match", "=", "re", ".", "search", "(", "'bucket=(.+?), key=(.+?)$'", ",", "message", ")", "if", "match", ":", "return", "S3PermissionsRequired", "(", "bucket", "=", "match", ".", "group", "(", "1", ")", ",", "key", "=", "match", ".", "group", "(", "2", ")", ")", "if", "\"Invalid S3 URI\"", "in", "message", ":", "return", "InvalidS3UriError", "(", "message", "=", "message", ")", "return", "ServerlessRepoClientError", "(", "message", "=", "message", ")" ]
Wrap botocore ClientError exception into ServerlessRepoClientError. :param e: botocore exception :type e: ClientError :return: S3PermissionsRequired or InvalidS3UriError or general ServerlessRepoClientError
[ "Wrap", "botocore", "ClientError", "exception", "into", "ServerlessRepoClientError", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L208-L227
train
235,971
awslabs/aws-serverlessrepo-python
serverlessrepo/publish.py
_get_publish_details
def _get_publish_details(actions, app_metadata_template): """ Get the changed application details after publishing. :param actions: Actions taken during publishing :type actions: list of str :param app_metadata_template: Original template definitions of app metadata :type app_metadata_template: dict :return: Updated fields and values of the application :rtype: dict """ if actions == [CREATE_APPLICATION]: return {k: v for k, v in app_metadata_template.items() if v} include_keys = [ ApplicationMetadata.AUTHOR, ApplicationMetadata.DESCRIPTION, ApplicationMetadata.HOME_PAGE_URL, ApplicationMetadata.LABELS, ApplicationMetadata.README_URL ] if CREATE_APPLICATION_VERSION in actions: # SemanticVersion and SourceCodeUrl can only be updated by creating a new version additional_keys = [ApplicationMetadata.SEMANTIC_VERSION, ApplicationMetadata.SOURCE_CODE_URL] include_keys.extend(additional_keys) return {k: v for k, v in app_metadata_template.items() if k in include_keys and v}
python
def _get_publish_details(actions, app_metadata_template): """ Get the changed application details after publishing. :param actions: Actions taken during publishing :type actions: list of str :param app_metadata_template: Original template definitions of app metadata :type app_metadata_template: dict :return: Updated fields and values of the application :rtype: dict """ if actions == [CREATE_APPLICATION]: return {k: v for k, v in app_metadata_template.items() if v} include_keys = [ ApplicationMetadata.AUTHOR, ApplicationMetadata.DESCRIPTION, ApplicationMetadata.HOME_PAGE_URL, ApplicationMetadata.LABELS, ApplicationMetadata.README_URL ] if CREATE_APPLICATION_VERSION in actions: # SemanticVersion and SourceCodeUrl can only be updated by creating a new version additional_keys = [ApplicationMetadata.SEMANTIC_VERSION, ApplicationMetadata.SOURCE_CODE_URL] include_keys.extend(additional_keys) return {k: v for k, v in app_metadata_template.items() if k in include_keys and v}
[ "def", "_get_publish_details", "(", "actions", ",", "app_metadata_template", ")", ":", "if", "actions", "==", "[", "CREATE_APPLICATION", "]", ":", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "app_metadata_template", ".", "items", "(", ")", "if", "v", "}", "include_keys", "=", "[", "ApplicationMetadata", ".", "AUTHOR", ",", "ApplicationMetadata", ".", "DESCRIPTION", ",", "ApplicationMetadata", ".", "HOME_PAGE_URL", ",", "ApplicationMetadata", ".", "LABELS", ",", "ApplicationMetadata", ".", "README_URL", "]", "if", "CREATE_APPLICATION_VERSION", "in", "actions", ":", "# SemanticVersion and SourceCodeUrl can only be updated by creating a new version", "additional_keys", "=", "[", "ApplicationMetadata", ".", "SEMANTIC_VERSION", ",", "ApplicationMetadata", ".", "SOURCE_CODE_URL", "]", "include_keys", ".", "extend", "(", "additional_keys", ")", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "app_metadata_template", ".", "items", "(", ")", "if", "k", "in", "include_keys", "and", "v", "}" ]
Get the changed application details after publishing. :param actions: Actions taken during publishing :type actions: list of str :param app_metadata_template: Original template definitions of app metadata :type app_metadata_template: dict :return: Updated fields and values of the application :rtype: dict
[ "Get", "the", "changed", "application", "details", "after", "publishing", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L230-L256
train
235,972
awslabs/aws-serverlessrepo-python
serverlessrepo/application_metadata.py
ApplicationMetadata.validate
def validate(self, required_props): """ Check if the required application metadata properties have been populated. :param required_props: List of required properties :type required_props: list :return: True, if the metadata is valid :raises: InvalidApplicationMetadataError """ missing_props = [p for p in required_props if not getattr(self, p)] if missing_props: missing_props_str = ', '.join(sorted(missing_props)) raise InvalidApplicationMetadataError(properties=missing_props_str) return True
python
def validate(self, required_props): """ Check if the required application metadata properties have been populated. :param required_props: List of required properties :type required_props: list :return: True, if the metadata is valid :raises: InvalidApplicationMetadataError """ missing_props = [p for p in required_props if not getattr(self, p)] if missing_props: missing_props_str = ', '.join(sorted(missing_props)) raise InvalidApplicationMetadataError(properties=missing_props_str) return True
[ "def", "validate", "(", "self", ",", "required_props", ")", ":", "missing_props", "=", "[", "p", "for", "p", "in", "required_props", "if", "not", "getattr", "(", "self", ",", "p", ")", "]", "if", "missing_props", ":", "missing_props_str", "=", "', '", ".", "join", "(", "sorted", "(", "missing_props", ")", ")", "raise", "InvalidApplicationMetadataError", "(", "properties", "=", "missing_props_str", ")", "return", "True" ]
Check if the required application metadata properties have been populated. :param required_props: List of required properties :type required_props: list :return: True, if the metadata is valid :raises: InvalidApplicationMetadataError
[ "Check", "if", "the", "required", "application", "metadata", "properties", "have", "been", "populated", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/application_metadata.py#L44-L57
train
235,973
awslabs/aws-serverlessrepo-python
serverlessrepo/parser.py
yaml_dump
def yaml_dump(dict_to_dump): """ Dump the dictionary as a YAML document. :param dict_to_dump: Data to be serialized as YAML :type dict_to_dump: dict :return: YAML document :rtype: str """ yaml.SafeDumper.add_representer(OrderedDict, _dict_representer) return yaml.safe_dump(dict_to_dump, default_flow_style=False)
python
def yaml_dump(dict_to_dump): """ Dump the dictionary as a YAML document. :param dict_to_dump: Data to be serialized as YAML :type dict_to_dump: dict :return: YAML document :rtype: str """ yaml.SafeDumper.add_representer(OrderedDict, _dict_representer) return yaml.safe_dump(dict_to_dump, default_flow_style=False)
[ "def", "yaml_dump", "(", "dict_to_dump", ")", ":", "yaml", ".", "SafeDumper", ".", "add_representer", "(", "OrderedDict", ",", "_dict_representer", ")", "return", "yaml", ".", "safe_dump", "(", "dict_to_dump", ",", "default_flow_style", "=", "False", ")" ]
Dump the dictionary as a YAML document. :param dict_to_dump: Data to be serialized as YAML :type dict_to_dump: dict :return: YAML document :rtype: str
[ "Dump", "the", "dictionary", "as", "a", "YAML", "document", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/parser.py#L61-L71
train
235,974
awslabs/aws-serverlessrepo-python
serverlessrepo/parser.py
parse_template
def parse_template(template_str): """ Parse the SAM template. :param template_str: A packaged YAML or json CloudFormation template :type template_str: str :return: Dictionary with keys defined in the template :rtype: dict """ try: # PyYAML doesn't support json as well as it should, so if the input # is actually just json it is better to parse it with the standard # json parser. return json.loads(template_str, object_pairs_hook=OrderedDict) except ValueError: yaml.SafeLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _dict_constructor) yaml.SafeLoader.add_multi_constructor('!', intrinsics_multi_constructor) return yaml.safe_load(template_str)
python
def parse_template(template_str): """ Parse the SAM template. :param template_str: A packaged YAML or json CloudFormation template :type template_str: str :return: Dictionary with keys defined in the template :rtype: dict """ try: # PyYAML doesn't support json as well as it should, so if the input # is actually just json it is better to parse it with the standard # json parser. return json.loads(template_str, object_pairs_hook=OrderedDict) except ValueError: yaml.SafeLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _dict_constructor) yaml.SafeLoader.add_multi_constructor('!', intrinsics_multi_constructor) return yaml.safe_load(template_str)
[ "def", "parse_template", "(", "template_str", ")", ":", "try", ":", "# PyYAML doesn't support json as well as it should, so if the input", "# is actually just json it is better to parse it with the standard", "# json parser.", "return", "json", ".", "loads", "(", "template_str", ",", "object_pairs_hook", "=", "OrderedDict", ")", "except", "ValueError", ":", "yaml", ".", "SafeLoader", ".", "add_constructor", "(", "yaml", ".", "resolver", ".", "BaseResolver", ".", "DEFAULT_MAPPING_TAG", ",", "_dict_constructor", ")", "yaml", ".", "SafeLoader", ".", "add_multi_constructor", "(", "'!'", ",", "intrinsics_multi_constructor", ")", "return", "yaml", ".", "safe_load", "(", "template_str", ")" ]
Parse the SAM template. :param template_str: A packaged YAML or json CloudFormation template :type template_str: str :return: Dictionary with keys defined in the template :rtype: dict
[ "Parse", "the", "SAM", "template", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/parser.py#L78-L95
train
235,975
awslabs/aws-serverlessrepo-python
serverlessrepo/parser.py
get_app_metadata
def get_app_metadata(template_dict): """ Get the application metadata from a SAM template. :param template_dict: SAM template as a dictionary :type template_dict: dict :return: Application metadata as defined in the template :rtype: ApplicationMetadata :raises ApplicationMetadataNotFoundError """ if SERVERLESS_REPO_APPLICATION in template_dict.get(METADATA, {}): app_metadata_dict = template_dict.get(METADATA).get(SERVERLESS_REPO_APPLICATION) return ApplicationMetadata(app_metadata_dict) raise ApplicationMetadataNotFoundError( error_message='missing {} section in template Metadata'.format(SERVERLESS_REPO_APPLICATION))
python
def get_app_metadata(template_dict): """ Get the application metadata from a SAM template. :param template_dict: SAM template as a dictionary :type template_dict: dict :return: Application metadata as defined in the template :rtype: ApplicationMetadata :raises ApplicationMetadataNotFoundError """ if SERVERLESS_REPO_APPLICATION in template_dict.get(METADATA, {}): app_metadata_dict = template_dict.get(METADATA).get(SERVERLESS_REPO_APPLICATION) return ApplicationMetadata(app_metadata_dict) raise ApplicationMetadataNotFoundError( error_message='missing {} section in template Metadata'.format(SERVERLESS_REPO_APPLICATION))
[ "def", "get_app_metadata", "(", "template_dict", ")", ":", "if", "SERVERLESS_REPO_APPLICATION", "in", "template_dict", ".", "get", "(", "METADATA", ",", "{", "}", ")", ":", "app_metadata_dict", "=", "template_dict", ".", "get", "(", "METADATA", ")", ".", "get", "(", "SERVERLESS_REPO_APPLICATION", ")", "return", "ApplicationMetadata", "(", "app_metadata_dict", ")", "raise", "ApplicationMetadataNotFoundError", "(", "error_message", "=", "'missing {} section in template Metadata'", ".", "format", "(", "SERVERLESS_REPO_APPLICATION", ")", ")" ]
Get the application metadata from a SAM template. :param template_dict: SAM template as a dictionary :type template_dict: dict :return: Application metadata as defined in the template :rtype: ApplicationMetadata :raises ApplicationMetadataNotFoundError
[ "Get", "the", "application", "metadata", "from", "a", "SAM", "template", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/parser.py#L98-L113
train
235,976
awslabs/aws-serverlessrepo-python
serverlessrepo/parser.py
parse_application_id
def parse_application_id(text): """ Extract the application id from input text. :param text: text to parse :type text: str :return: application id if found in the input :rtype: str """ result = re.search(APPLICATION_ID_PATTERN, text) return result.group(0) if result else None
python
def parse_application_id(text): """ Extract the application id from input text. :param text: text to parse :type text: str :return: application id if found in the input :rtype: str """ result = re.search(APPLICATION_ID_PATTERN, text) return result.group(0) if result else None
[ "def", "parse_application_id", "(", "text", ")", ":", "result", "=", "re", ".", "search", "(", "APPLICATION_ID_PATTERN", ",", "text", ")", "return", "result", ".", "group", "(", "0", ")", "if", "result", "else", "None" ]
Extract the application id from input text. :param text: text to parse :type text: str :return: application id if found in the input :rtype: str
[ "Extract", "the", "application", "id", "from", "input", "text", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/parser.py#L116-L126
train
235,977
awslabs/aws-serverlessrepo-python
serverlessrepo/permission_helper.py
make_application_private
def make_application_private(application_id, sar_client=None): """ Set the application to be private. :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :raises ValueError """ if not application_id: raise ValueError('Require application id to make the app private') if not sar_client: sar_client = boto3.client('serverlessrepo') sar_client.put_application_policy( ApplicationId=application_id, Statements=[] )
python
def make_application_private(application_id, sar_client=None): """ Set the application to be private. :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :raises ValueError """ if not application_id: raise ValueError('Require application id to make the app private') if not sar_client: sar_client = boto3.client('serverlessrepo') sar_client.put_application_policy( ApplicationId=application_id, Statements=[] )
[ "def", "make_application_private", "(", "application_id", ",", "sar_client", "=", "None", ")", ":", "if", "not", "application_id", ":", "raise", "ValueError", "(", "'Require application id to make the app private'", ")", "if", "not", "sar_client", ":", "sar_client", "=", "boto3", ".", "client", "(", "'serverlessrepo'", ")", "sar_client", ".", "put_application_policy", "(", "ApplicationId", "=", "application_id", ",", "Statements", "=", "[", "]", ")" ]
Set the application to be private. :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :raises ValueError
[ "Set", "the", "application", "to", "be", "private", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/permission_helper.py#L32-L51
train
235,978
awslabs/aws-serverlessrepo-python
serverlessrepo/permission_helper.py
share_application_with_accounts
def share_application_with_accounts(application_id, account_ids, sar_client=None): """ Share the application privately with given AWS account IDs. :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param account_ids: List of AWS account IDs, or * :type account_ids: list of str :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :raises ValueError """ if not application_id or not account_ids: raise ValueError('Require application id and list of AWS account IDs to share the app') if not sar_client: sar_client = boto3.client('serverlessrepo') application_policy = ApplicationPolicy(account_ids, [ApplicationPolicy.DEPLOY]) application_policy.validate() sar_client.put_application_policy( ApplicationId=application_id, Statements=[application_policy.to_statement()] )
python
def share_application_with_accounts(application_id, account_ids, sar_client=None): """ Share the application privately with given AWS account IDs. :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param account_ids: List of AWS account IDs, or * :type account_ids: list of str :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :raises ValueError """ if not application_id or not account_ids: raise ValueError('Require application id and list of AWS account IDs to share the app') if not sar_client: sar_client = boto3.client('serverlessrepo') application_policy = ApplicationPolicy(account_ids, [ApplicationPolicy.DEPLOY]) application_policy.validate() sar_client.put_application_policy( ApplicationId=application_id, Statements=[application_policy.to_statement()] )
[ "def", "share_application_with_accounts", "(", "application_id", ",", "account_ids", ",", "sar_client", "=", "None", ")", ":", "if", "not", "application_id", "or", "not", "account_ids", ":", "raise", "ValueError", "(", "'Require application id and list of AWS account IDs to share the app'", ")", "if", "not", "sar_client", ":", "sar_client", "=", "boto3", ".", "client", "(", "'serverlessrepo'", ")", "application_policy", "=", "ApplicationPolicy", "(", "account_ids", ",", "[", "ApplicationPolicy", ".", "DEPLOY", "]", ")", "application_policy", ".", "validate", "(", ")", "sar_client", ".", "put_application_policy", "(", "ApplicationId", "=", "application_id", ",", "Statements", "=", "[", "application_policy", ".", "to_statement", "(", ")", "]", ")" ]
Share the application privately with given AWS account IDs. :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param account_ids: List of AWS account IDs, or * :type account_ids: list of str :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :raises ValueError
[ "Share", "the", "application", "privately", "with", "given", "AWS", "account", "IDs", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/permission_helper.py#L54-L77
train
235,979
asifpy/django-crudbuilder
crudbuilder/registry.py
CrudBuilderRegistry.extract_args
def extract_args(cls, *args): """ Takes any arguments like a model and crud, or just one of those, in any order, and return a model and crud. """ model = None crudbuilder = None for arg in args: if issubclass(arg, models.Model): model = arg else: crudbuilder = arg return [model, crudbuilder]
python
def extract_args(cls, *args): """ Takes any arguments like a model and crud, or just one of those, in any order, and return a model and crud. """ model = None crudbuilder = None for arg in args: if issubclass(arg, models.Model): model = arg else: crudbuilder = arg return [model, crudbuilder]
[ "def", "extract_args", "(", "cls", ",", "*", "args", ")", ":", "model", "=", "None", "crudbuilder", "=", "None", "for", "arg", "in", "args", ":", "if", "issubclass", "(", "arg", ",", "models", ".", "Model", ")", ":", "model", "=", "arg", "else", ":", "crudbuilder", "=", "arg", "return", "[", "model", ",", "crudbuilder", "]" ]
Takes any arguments like a model and crud, or just one of those, in any order, and return a model and crud.
[ "Takes", "any", "arguments", "like", "a", "model", "and", "crud", "or", "just", "one", "of", "those", "in", "any", "order", "and", "return", "a", "model", "and", "crud", "." ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/registry.py#L18-L32
train
235,980
asifpy/django-crudbuilder
crudbuilder/registry.py
CrudBuilderRegistry.register
def register(self, *args, **kwargs): """ Register a crud. Two unordered arguments are accepted, at least one should be passed: - a model, - a crudbuilder class """ assert len(args) <= 2, 'register takes at most 2 args' assert len(args) > 0, 'register takes at least 1 arg' model, crudbuilder = self.__class__.extract_args(*args) if not issubclass(model, models.Model): msg = "First argument should be Django Model" raise NotModelException(msg) key = self._model_key(model, crudbuilder) if key in self: msg = "Key '{key}' has already been registered.".format( key=key ) raise AlreadyRegistered(msg) self.__setitem__(key, crudbuilder) return crudbuilder
python
def register(self, *args, **kwargs): """ Register a crud. Two unordered arguments are accepted, at least one should be passed: - a model, - a crudbuilder class """ assert len(args) <= 2, 'register takes at most 2 args' assert len(args) > 0, 'register takes at least 1 arg' model, crudbuilder = self.__class__.extract_args(*args) if not issubclass(model, models.Model): msg = "First argument should be Django Model" raise NotModelException(msg) key = self._model_key(model, crudbuilder) if key in self: msg = "Key '{key}' has already been registered.".format( key=key ) raise AlreadyRegistered(msg) self.__setitem__(key, crudbuilder) return crudbuilder
[ "def", "register", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "assert", "len", "(", "args", ")", "<=", "2", ",", "'register takes at most 2 args'", "assert", "len", "(", "args", ")", ">", "0", ",", "'register takes at least 1 arg'", "model", ",", "crudbuilder", "=", "self", ".", "__class__", ".", "extract_args", "(", "*", "args", ")", "if", "not", "issubclass", "(", "model", ",", "models", ".", "Model", ")", ":", "msg", "=", "\"First argument should be Django Model\"", "raise", "NotModelException", "(", "msg", ")", "key", "=", "self", ".", "_model_key", "(", "model", ",", "crudbuilder", ")", "if", "key", "in", "self", ":", "msg", "=", "\"Key '{key}' has already been registered.\"", ".", "format", "(", "key", "=", "key", ")", "raise", "AlreadyRegistered", "(", "msg", ")", "self", ".", "__setitem__", "(", "key", ",", "crudbuilder", ")", "return", "crudbuilder" ]
Register a crud. Two unordered arguments are accepted, at least one should be passed: - a model, - a crudbuilder class
[ "Register", "a", "crud", "." ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/registry.py#L34-L61
train
235,981
asifpy/django-crudbuilder
crudbuilder/formset.py
BaseInlineFormset.construct_formset
def construct_formset(self): """ Returns an instance of the inline formset """ if not self.inline_model or not self.parent_model: msg = "Parent and Inline models are required in {}".format(self.__class__.__name__) raise NotModelException(msg) return inlineformset_factory( self.parent_model, self.inline_model, **self.get_factory_kwargs())
python
def construct_formset(self): """ Returns an instance of the inline formset """ if not self.inline_model or not self.parent_model: msg = "Parent and Inline models are required in {}".format(self.__class__.__name__) raise NotModelException(msg) return inlineformset_factory( self.parent_model, self.inline_model, **self.get_factory_kwargs())
[ "def", "construct_formset", "(", "self", ")", ":", "if", "not", "self", ".", "inline_model", "or", "not", "self", ".", "parent_model", ":", "msg", "=", "\"Parent and Inline models are required in {}\"", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ")", "raise", "NotModelException", "(", "msg", ")", "return", "inlineformset_factory", "(", "self", ".", "parent_model", ",", "self", ".", "inline_model", ",", "*", "*", "self", ".", "get_factory_kwargs", "(", ")", ")" ]
Returns an instance of the inline formset
[ "Returns", "an", "instance", "of", "the", "inline", "formset" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/formset.py#L18-L29
train
235,982
asifpy/django-crudbuilder
crudbuilder/formset.py
BaseInlineFormset.get_factory_kwargs
def get_factory_kwargs(self): """ Returns the keyword arguments for calling the formset factory """ kwargs = {} kwargs.update({ 'can_delete': self.can_delete, 'extra': self.extra, 'exclude': self.exclude, 'fields': self.fields, 'formfield_callback': self.formfield_callback, 'fk_name': self.fk_name, }) if self.formset_class: kwargs['formset'] = self.formset_class if self.child_form: kwargs['form'] = self.child_form return kwargs
python
def get_factory_kwargs(self): """ Returns the keyword arguments for calling the formset factory """ kwargs = {} kwargs.update({ 'can_delete': self.can_delete, 'extra': self.extra, 'exclude': self.exclude, 'fields': self.fields, 'formfield_callback': self.formfield_callback, 'fk_name': self.fk_name, }) if self.formset_class: kwargs['formset'] = self.formset_class if self.child_form: kwargs['form'] = self.child_form return kwargs
[ "def", "get_factory_kwargs", "(", "self", ")", ":", "kwargs", "=", "{", "}", "kwargs", ".", "update", "(", "{", "'can_delete'", ":", "self", ".", "can_delete", ",", "'extra'", ":", "self", ".", "extra", ",", "'exclude'", ":", "self", ".", "exclude", ",", "'fields'", ":", "self", ".", "fields", ",", "'formfield_callback'", ":", "self", ".", "formfield_callback", ",", "'fk_name'", ":", "self", ".", "fk_name", ",", "}", ")", "if", "self", ".", "formset_class", ":", "kwargs", "[", "'formset'", "]", "=", "self", ".", "formset_class", "if", "self", ".", "child_form", ":", "kwargs", "[", "'form'", "]", "=", "self", ".", "child_form", "return", "kwargs" ]
Returns the keyword arguments for calling the formset factory
[ "Returns", "the", "keyword", "arguments", "for", "calling", "the", "formset", "factory" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/formset.py#L31-L49
train
235,983
asifpy/django-crudbuilder
crudbuilder/helpers.py
import_crud
def import_crud(app): ''' Import crud module and register all model cruds which it contains ''' try: app_path = import_module(app).__path__ except (AttributeError, ImportError): return None try: imp.find_module('crud', app_path) except ImportError: return None module = import_module("%s.crud" % app) return module
python
def import_crud(app): ''' Import crud module and register all model cruds which it contains ''' try: app_path = import_module(app).__path__ except (AttributeError, ImportError): return None try: imp.find_module('crud', app_path) except ImportError: return None module = import_module("%s.crud" % app) return module
[ "def", "import_crud", "(", "app", ")", ":", "try", ":", "app_path", "=", "import_module", "(", "app", ")", ".", "__path__", "except", "(", "AttributeError", ",", "ImportError", ")", ":", "return", "None", "try", ":", "imp", ".", "find_module", "(", "'crud'", ",", "app_path", ")", "except", "ImportError", ":", "return", "None", "module", "=", "import_module", "(", "\"%s.crud\"", "%", "app", ")", "return", "module" ]
Import crud module and register all model cruds which it contains
[ "Import", "crud", "module", "and", "register", "all", "model", "cruds", "which", "it", "contains" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/helpers.py#L162-L179
train
235,984
asifpy/django-crudbuilder
crudbuilder/abstract.py
BaseBuilder.get_model_class
def get_model_class(self): """Returns model class""" try: c = ContentType.objects.get(app_label=self.app, model=self.model) except ContentType.DoesNotExist: # try another kind of resolution # fixes a situation where a proxy model is defined in some external app. if django.VERSION >= (1, 7): return apps.get_model(self.app, self.model) else: return c.model_class()
python
def get_model_class(self): """Returns model class""" try: c = ContentType.objects.get(app_label=self.app, model=self.model) except ContentType.DoesNotExist: # try another kind of resolution # fixes a situation where a proxy model is defined in some external app. if django.VERSION >= (1, 7): return apps.get_model(self.app, self.model) else: return c.model_class()
[ "def", "get_model_class", "(", "self", ")", ":", "try", ":", "c", "=", "ContentType", ".", "objects", ".", "get", "(", "app_label", "=", "self", ".", "app", ",", "model", "=", "self", ".", "model", ")", "except", "ContentType", ".", "DoesNotExist", ":", "# try another kind of resolution", "# fixes a situation where a proxy model is defined in some external app.", "if", "django", ".", "VERSION", ">=", "(", "1", ",", "7", ")", ":", "return", "apps", ".", "get_model", "(", "self", ".", "app", ",", "self", ".", "model", ")", "else", ":", "return", "c", ".", "model_class", "(", ")" ]
Returns model class
[ "Returns", "model", "class" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/abstract.py#L53-L63
train
235,985
asifpy/django-crudbuilder
crudbuilder/templatetags/crudbuilder.py
get_verbose_field_name
def get_verbose_field_name(instance, field_name): """ Returns verbose_name for a field. """ fields = [field.name for field in instance._meta.fields] if field_name in fields: return instance._meta.get_field(field_name).verbose_name else: return field_name
python
def get_verbose_field_name(instance, field_name): """ Returns verbose_name for a field. """ fields = [field.name for field in instance._meta.fields] if field_name in fields: return instance._meta.get_field(field_name).verbose_name else: return field_name
[ "def", "get_verbose_field_name", "(", "instance", ",", "field_name", ")", ":", "fields", "=", "[", "field", ".", "name", "for", "field", "in", "instance", ".", "_meta", ".", "fields", "]", "if", "field_name", "in", "fields", ":", "return", "instance", ".", "_meta", ".", "get_field", "(", "field_name", ")", ".", "verbose_name", "else", ":", "return", "field_name" ]
Returns verbose_name for a field.
[ "Returns", "verbose_name", "for", "a", "field", "." ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/templatetags/crudbuilder.py#L63-L71
train
235,986
asifpy/django-crudbuilder
crudbuilder/views.py
ViewBuilder.generate_modelform
def generate_modelform(self): """Generate modelform from Django modelform_factory""" model_class = self.get_model_class excludes = self.modelform_excludes if self.modelform_excludes else [] _ObjectForm = modelform_factory(model_class, exclude=excludes) return _ObjectForm
python
def generate_modelform(self): """Generate modelform from Django modelform_factory""" model_class = self.get_model_class excludes = self.modelform_excludes if self.modelform_excludes else [] _ObjectForm = modelform_factory(model_class, exclude=excludes) return _ObjectForm
[ "def", "generate_modelform", "(", "self", ")", ":", "model_class", "=", "self", ".", "get_model_class", "excludes", "=", "self", ".", "modelform_excludes", "if", "self", ".", "modelform_excludes", "else", "[", "]", "_ObjectForm", "=", "modelform_factory", "(", "model_class", ",", "exclude", "=", "excludes", ")", "return", "_ObjectForm" ]
Generate modelform from Django modelform_factory
[ "Generate", "modelform", "from", "Django", "modelform_factory" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/views.py#L58-L64
train
235,987
asifpy/django-crudbuilder
crudbuilder/views.py
ViewBuilder.get_template
def get_template(self, tname): """ - Get custom template from CRUD class, if it is defined in it - No custom template in CRUD class, then use the default template """ if self.custom_templates and self.custom_templates.get(tname, None): return self.custom_templates.get(tname) elif self.inlineformset: return 'crudbuilder/inline/{}.html'.format(tname) else: return 'crudbuilder/instance/{}.html'.format(tname)
python
def get_template(self, tname): """ - Get custom template from CRUD class, if it is defined in it - No custom template in CRUD class, then use the default template """ if self.custom_templates and self.custom_templates.get(tname, None): return self.custom_templates.get(tname) elif self.inlineformset: return 'crudbuilder/inline/{}.html'.format(tname) else: return 'crudbuilder/instance/{}.html'.format(tname)
[ "def", "get_template", "(", "self", ",", "tname", ")", ":", "if", "self", ".", "custom_templates", "and", "self", ".", "custom_templates", ".", "get", "(", "tname", ",", "None", ")", ":", "return", "self", ".", "custom_templates", ".", "get", "(", "tname", ")", "elif", "self", ".", "inlineformset", ":", "return", "'crudbuilder/inline/{}.html'", ".", "format", "(", "tname", ")", "else", ":", "return", "'crudbuilder/instance/{}.html'", ".", "format", "(", "tname", ")" ]
- Get custom template from CRUD class, if it is defined in it - No custom template in CRUD class, then use the default template
[ "-", "Get", "custom", "template", "from", "CRUD", "class", "if", "it", "is", "defined", "in", "it", "-", "No", "custom", "template", "in", "CRUD", "class", "then", "use", "the", "default", "template" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/views.py#L66-L77
train
235,988
asifpy/django-crudbuilder
crudbuilder/views.py
ViewBuilder.generate_list_view
def generate_list_view(self): """Generate class based view for ListView""" name = model_class_form(self.model + 'ListView') list_args = dict( model=self.get_model_class, context_object_name=plural(self.model), template_name=self.get_template('list'), table_class=self.get_actual_table(), context_table_name='table_objects', crud=self.crud, permissions=self.view_permission('list'), permission_required=self.check_permission_required, login_required=self.check_login_required, table_pagination={'per_page': self.tables2_pagination or 10}, custom_queryset=self.custom_queryset, custom_context=self.custom_context, custom_postfix_url=self.custom_postfix_url ) list_class = type( name, (BaseListViewMixin, SingleTableView), list_args ) self.classes[name] = list_class return list_class
python
def generate_list_view(self): """Generate class based view for ListView""" name = model_class_form(self.model + 'ListView') list_args = dict( model=self.get_model_class, context_object_name=plural(self.model), template_name=self.get_template('list'), table_class=self.get_actual_table(), context_table_name='table_objects', crud=self.crud, permissions=self.view_permission('list'), permission_required=self.check_permission_required, login_required=self.check_login_required, table_pagination={'per_page': self.tables2_pagination or 10}, custom_queryset=self.custom_queryset, custom_context=self.custom_context, custom_postfix_url=self.custom_postfix_url ) list_class = type( name, (BaseListViewMixin, SingleTableView), list_args ) self.classes[name] = list_class return list_class
[ "def", "generate_list_view", "(", "self", ")", ":", "name", "=", "model_class_form", "(", "self", ".", "model", "+", "'ListView'", ")", "list_args", "=", "dict", "(", "model", "=", "self", ".", "get_model_class", ",", "context_object_name", "=", "plural", "(", "self", ".", "model", ")", ",", "template_name", "=", "self", ".", "get_template", "(", "'list'", ")", ",", "table_class", "=", "self", ".", "get_actual_table", "(", ")", ",", "context_table_name", "=", "'table_objects'", ",", "crud", "=", "self", ".", "crud", ",", "permissions", "=", "self", ".", "view_permission", "(", "'list'", ")", ",", "permission_required", "=", "self", ".", "check_permission_required", ",", "login_required", "=", "self", ".", "check_login_required", ",", "table_pagination", "=", "{", "'per_page'", ":", "self", ".", "tables2_pagination", "or", "10", "}", ",", "custom_queryset", "=", "self", ".", "custom_queryset", ",", "custom_context", "=", "self", ".", "custom_context", ",", "custom_postfix_url", "=", "self", ".", "custom_postfix_url", ")", "list_class", "=", "type", "(", "name", ",", "(", "BaseListViewMixin", ",", "SingleTableView", ")", ",", "list_args", ")", "self", ".", "classes", "[", "name", "]", "=", "list_class", "return", "list_class" ]
Generate class based view for ListView
[ "Generate", "class", "based", "view", "for", "ListView" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/views.py#L85-L111
train
235,989
asifpy/django-crudbuilder
crudbuilder/views.py
ViewBuilder.generate_create_view
def generate_create_view(self): """Generate class based view for CreateView""" name = model_class_form(self.model + 'CreateView') create_args = dict( form_class=self.get_actual_form('create'), model=self.get_model_class, template_name=self.get_template('create'), permissions=self.view_permission('create'), permission_required=self.check_permission_required, login_required=self.check_login_required, inlineformset=self.inlineformset, success_url=reverse_lazy('{}-{}-list'.format(self.app, self.custom_postfix_url)), custom_form=self.createupdate_forms or self.custom_modelform, custom_postfix_url=self.custom_postfix_url ) parent_classes = [self.get_createupdate_mixin(), CreateView] if self.custom_create_view_mixin: parent_classes.insert(0, self.custom_create_view_mixin) create_class = type( name, tuple(parent_classes), create_args ) self.classes[name] = create_class return create_class
python
def generate_create_view(self): """Generate class based view for CreateView""" name = model_class_form(self.model + 'CreateView') create_args = dict( form_class=self.get_actual_form('create'), model=self.get_model_class, template_name=self.get_template('create'), permissions=self.view_permission('create'), permission_required=self.check_permission_required, login_required=self.check_login_required, inlineformset=self.inlineformset, success_url=reverse_lazy('{}-{}-list'.format(self.app, self.custom_postfix_url)), custom_form=self.createupdate_forms or self.custom_modelform, custom_postfix_url=self.custom_postfix_url ) parent_classes = [self.get_createupdate_mixin(), CreateView] if self.custom_create_view_mixin: parent_classes.insert(0, self.custom_create_view_mixin) create_class = type( name, tuple(parent_classes), create_args ) self.classes[name] = create_class return create_class
[ "def", "generate_create_view", "(", "self", ")", ":", "name", "=", "model_class_form", "(", "self", ".", "model", "+", "'CreateView'", ")", "create_args", "=", "dict", "(", "form_class", "=", "self", ".", "get_actual_form", "(", "'create'", ")", ",", "model", "=", "self", ".", "get_model_class", ",", "template_name", "=", "self", ".", "get_template", "(", "'create'", ")", ",", "permissions", "=", "self", ".", "view_permission", "(", "'create'", ")", ",", "permission_required", "=", "self", ".", "check_permission_required", ",", "login_required", "=", "self", ".", "check_login_required", ",", "inlineformset", "=", "self", ".", "inlineformset", ",", "success_url", "=", "reverse_lazy", "(", "'{}-{}-list'", ".", "format", "(", "self", ".", "app", ",", "self", ".", "custom_postfix_url", ")", ")", ",", "custom_form", "=", "self", ".", "createupdate_forms", "or", "self", ".", "custom_modelform", ",", "custom_postfix_url", "=", "self", ".", "custom_postfix_url", ")", "parent_classes", "=", "[", "self", ".", "get_createupdate_mixin", "(", ")", ",", "CreateView", "]", "if", "self", ".", "custom_create_view_mixin", ":", "parent_classes", ".", "insert", "(", "0", ",", "self", ".", "custom_create_view_mixin", ")", "create_class", "=", "type", "(", "name", ",", "tuple", "(", "parent_classes", ")", ",", "create_args", ")", "self", ".", "classes", "[", "name", "]", "=", "create_class", "return", "create_class" ]
Generate class based view for CreateView
[ "Generate", "class", "based", "view", "for", "CreateView" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/views.py#L113-L141
train
235,990
asifpy/django-crudbuilder
crudbuilder/views.py
ViewBuilder.generate_detail_view
def generate_detail_view(self): """Generate class based view for DetailView""" name = model_class_form(self.model + 'DetailView') detail_args = dict( detailview_excludes=self.detailview_excludes, model=self.get_model_class, template_name=self.get_template('detail'), login_required=self.check_login_required, permissions=self.view_permission('detail'), inlineformset=self.inlineformset, permission_required=self.check_permission_required, custom_postfix_url=self.custom_postfix_url ) detail_class = type(name, (BaseDetailViewMixin, DetailView), detail_args) self.classes[name] = detail_class return detail_class
python
def generate_detail_view(self): """Generate class based view for DetailView""" name = model_class_form(self.model + 'DetailView') detail_args = dict( detailview_excludes=self.detailview_excludes, model=self.get_model_class, template_name=self.get_template('detail'), login_required=self.check_login_required, permissions=self.view_permission('detail'), inlineformset=self.inlineformset, permission_required=self.check_permission_required, custom_postfix_url=self.custom_postfix_url ) detail_class = type(name, (BaseDetailViewMixin, DetailView), detail_args) self.classes[name] = detail_class return detail_class
[ "def", "generate_detail_view", "(", "self", ")", ":", "name", "=", "model_class_form", "(", "self", ".", "model", "+", "'DetailView'", ")", "detail_args", "=", "dict", "(", "detailview_excludes", "=", "self", ".", "detailview_excludes", ",", "model", "=", "self", ".", "get_model_class", ",", "template_name", "=", "self", ".", "get_template", "(", "'detail'", ")", ",", "login_required", "=", "self", ".", "check_login_required", ",", "permissions", "=", "self", ".", "view_permission", "(", "'detail'", ")", ",", "inlineformset", "=", "self", ".", "inlineformset", ",", "permission_required", "=", "self", ".", "check_permission_required", ",", "custom_postfix_url", "=", "self", ".", "custom_postfix_url", ")", "detail_class", "=", "type", "(", "name", ",", "(", "BaseDetailViewMixin", ",", "DetailView", ")", ",", "detail_args", ")", "self", ".", "classes", "[", "name", "]", "=", "detail_class", "return", "detail_class" ]
Generate class based view for DetailView
[ "Generate", "class", "based", "view", "for", "DetailView" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/views.py#L143-L160
train
235,991
asifpy/django-crudbuilder
crudbuilder/views.py
ViewBuilder.generate_update_view
def generate_update_view(self): """Generate class based view for UpdateView""" name = model_class_form(self.model + 'UpdateView') update_args = dict( form_class=self.get_actual_form('update'), model=self.get_model_class, template_name=self.get_template('update'), permissions=self.view_permission('update'), permission_required=self.check_permission_required, login_required=self.check_login_required, inlineformset=self.inlineformset, custom_form=self.createupdate_forms or self.custom_modelform, success_url=reverse_lazy('{}-{}-list'.format(self.app, self.custom_postfix_url)), custom_postfix_url=self.custom_postfix_url ) parent_classes = [self.get_createupdate_mixin(), UpdateView] if self.custom_update_view_mixin: parent_classes.insert(0, self.custom_update_view_mixin) update_class = type( name, tuple(parent_classes), update_args ) self.classes[name] = update_class return update_class
python
def generate_update_view(self): """Generate class based view for UpdateView""" name = model_class_form(self.model + 'UpdateView') update_args = dict( form_class=self.get_actual_form('update'), model=self.get_model_class, template_name=self.get_template('update'), permissions=self.view_permission('update'), permission_required=self.check_permission_required, login_required=self.check_login_required, inlineformset=self.inlineformset, custom_form=self.createupdate_forms or self.custom_modelform, success_url=reverse_lazy('{}-{}-list'.format(self.app, self.custom_postfix_url)), custom_postfix_url=self.custom_postfix_url ) parent_classes = [self.get_createupdate_mixin(), UpdateView] if self.custom_update_view_mixin: parent_classes.insert(0, self.custom_update_view_mixin) update_class = type( name, tuple(parent_classes), update_args ) self.classes[name] = update_class return update_class
[ "def", "generate_update_view", "(", "self", ")", ":", "name", "=", "model_class_form", "(", "self", ".", "model", "+", "'UpdateView'", ")", "update_args", "=", "dict", "(", "form_class", "=", "self", ".", "get_actual_form", "(", "'update'", ")", ",", "model", "=", "self", ".", "get_model_class", ",", "template_name", "=", "self", ".", "get_template", "(", "'update'", ")", ",", "permissions", "=", "self", ".", "view_permission", "(", "'update'", ")", ",", "permission_required", "=", "self", ".", "check_permission_required", ",", "login_required", "=", "self", ".", "check_login_required", ",", "inlineformset", "=", "self", ".", "inlineformset", ",", "custom_form", "=", "self", ".", "createupdate_forms", "or", "self", ".", "custom_modelform", ",", "success_url", "=", "reverse_lazy", "(", "'{}-{}-list'", ".", "format", "(", "self", ".", "app", ",", "self", ".", "custom_postfix_url", ")", ")", ",", "custom_postfix_url", "=", "self", ".", "custom_postfix_url", ")", "parent_classes", "=", "[", "self", ".", "get_createupdate_mixin", "(", ")", ",", "UpdateView", "]", "if", "self", ".", "custom_update_view_mixin", ":", "parent_classes", ".", "insert", "(", "0", ",", "self", ".", "custom_update_view_mixin", ")", "update_class", "=", "type", "(", "name", ",", "tuple", "(", "parent_classes", ")", ",", "update_args", ")", "self", ".", "classes", "[", "name", "]", "=", "update_class", "return", "update_class" ]
Generate class based view for UpdateView
[ "Generate", "class", "based", "view", "for", "UpdateView" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/views.py#L162-L189
train
235,992
asifpy/django-crudbuilder
crudbuilder/views.py
ViewBuilder.generate_delete_view
def generate_delete_view(self): """Generate class based view for DeleteView""" name = model_class_form(self.model + 'DeleteView') delete_args = dict( model=self.get_model_class, template_name=self.get_template('delete'), permissions=self.view_permission('delete'), permission_required=self.check_permission_required, login_required=self.check_login_required, success_url=reverse_lazy('{}-{}-list'.format(self.app, self.custom_postfix_url)), custom_postfix_url=self.custom_postfix_url ) delete_class = type(name, (CrudBuilderMixin, DeleteView), delete_args) self.classes[name] = delete_class return delete_class
python
def generate_delete_view(self): """Generate class based view for DeleteView""" name = model_class_form(self.model + 'DeleteView') delete_args = dict( model=self.get_model_class, template_name=self.get_template('delete'), permissions=self.view_permission('delete'), permission_required=self.check_permission_required, login_required=self.check_login_required, success_url=reverse_lazy('{}-{}-list'.format(self.app, self.custom_postfix_url)), custom_postfix_url=self.custom_postfix_url ) delete_class = type(name, (CrudBuilderMixin, DeleteView), delete_args) self.classes[name] = delete_class return delete_class
[ "def", "generate_delete_view", "(", "self", ")", ":", "name", "=", "model_class_form", "(", "self", ".", "model", "+", "'DeleteView'", ")", "delete_args", "=", "dict", "(", "model", "=", "self", ".", "get_model_class", ",", "template_name", "=", "self", ".", "get_template", "(", "'delete'", ")", ",", "permissions", "=", "self", ".", "view_permission", "(", "'delete'", ")", ",", "permission_required", "=", "self", ".", "check_permission_required", ",", "login_required", "=", "self", ".", "check_login_required", ",", "success_url", "=", "reverse_lazy", "(", "'{}-{}-list'", ".", "format", "(", "self", ".", "app", ",", "self", ".", "custom_postfix_url", ")", ")", ",", "custom_postfix_url", "=", "self", ".", "custom_postfix_url", ")", "delete_class", "=", "type", "(", "name", ",", "(", "CrudBuilderMixin", ",", "DeleteView", ")", ",", "delete_args", ")", "self", ".", "classes", "[", "name", "]", "=", "delete_class", "return", "delete_class" ]
Generate class based view for DeleteView
[ "Generate", "class", "based", "view", "for", "DeleteView" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/views.py#L191-L207
train
235,993
contentful/contentful.py
contentful/entry.py
Entry.incoming_references
def incoming_references(self, client=None, query={}): """Fetches all entries referencing the entry API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/links-to-asset :param client Client instance :param query: (optional) Dict with API options. :return: List of :class:`Entry <contentful.entry.Entry>` objects. :rtype: List of contentful.entry.Entry Usage: >>> entries = entry.incoming_references(client) [<Entry[cat] id='happycat'>] """ if client is None: return False query.update({'links_to_entry': self.id}) return client.entries(query)
python
def incoming_references(self, client=None, query={}): """Fetches all entries referencing the entry API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/links-to-asset :param client Client instance :param query: (optional) Dict with API options. :return: List of :class:`Entry <contentful.entry.Entry>` objects. :rtype: List of contentful.entry.Entry Usage: >>> entries = entry.incoming_references(client) [<Entry[cat] id='happycat'>] """ if client is None: return False query.update({'links_to_entry': self.id}) return client.entries(query)
[ "def", "incoming_references", "(", "self", ",", "client", "=", "None", ",", "query", "=", "{", "}", ")", ":", "if", "client", "is", "None", ":", "return", "False", "query", ".", "update", "(", "{", "'links_to_entry'", ":", "self", ".", "id", "}", ")", "return", "client", ".", "entries", "(", "query", ")" ]
Fetches all entries referencing the entry API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/links-to-asset :param client Client instance :param query: (optional) Dict with API options. :return: List of :class:`Entry <contentful.entry.Entry>` objects. :rtype: List of contentful.entry.Entry Usage: >>> entries = entry.incoming_references(client) [<Entry[cat] id='happycat'>]
[ "Fetches", "all", "entries", "referencing", "the", "entry" ]
73fe01d6ae5a1f8818880da65199107b584681dd
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/entry.py#L118-L137
train
235,994
contentful/contentful.py
contentful/resource_builder.py
ResourceBuilder.build
def build(self): """Creates the objects from the JSON response""" if self.json['sys']['type'] == 'Array': if any(k in self.json for k in ['nextSyncUrl', 'nextPageUrl']): return SyncPage( self.json, default_locale=self.default_locale, localized=True ) return self._build_array() return self._build_single()
python
def build(self): """Creates the objects from the JSON response""" if self.json['sys']['type'] == 'Array': if any(k in self.json for k in ['nextSyncUrl', 'nextPageUrl']): return SyncPage( self.json, default_locale=self.default_locale, localized=True ) return self._build_array() return self._build_single()
[ "def", "build", "(", "self", ")", ":", "if", "self", ".", "json", "[", "'sys'", "]", "[", "'type'", "]", "==", "'Array'", ":", "if", "any", "(", "k", "in", "self", ".", "json", "for", "k", "in", "[", "'nextSyncUrl'", ",", "'nextPageUrl'", "]", ")", ":", "return", "SyncPage", "(", "self", ".", "json", ",", "default_locale", "=", "self", ".", "default_locale", ",", "localized", "=", "True", ")", "return", "self", ".", "_build_array", "(", ")", "return", "self", ".", "_build_single", "(", ")" ]
Creates the objects from the JSON response
[ "Creates", "the", "objects", "from", "the", "JSON", "response" ]
73fe01d6ae5a1f8818880da65199107b584681dd
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/resource_builder.py#L51-L62
train
235,995
contentful/contentful.py
contentful/content_type_cache.py
ContentTypeCache.get
def get(cls, content_type_id): """ Fetches a Content Type from the Cache. """ for content_type in cls.__CACHE__: if content_type.sys.get('id') == content_type_id: return content_type return None
python
def get(cls, content_type_id): """ Fetches a Content Type from the Cache. """ for content_type in cls.__CACHE__: if content_type.sys.get('id') == content_type_id: return content_type return None
[ "def", "get", "(", "cls", ",", "content_type_id", ")", ":", "for", "content_type", "in", "cls", ".", "__CACHE__", ":", "if", "content_type", ".", "sys", ".", "get", "(", "'id'", ")", "==", "content_type_id", ":", "return", "content_type", "return", "None" ]
Fetches a Content Type from the Cache.
[ "Fetches", "a", "Content", "Type", "from", "the", "Cache", "." ]
73fe01d6ae5a1f8818880da65199107b584681dd
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/content_type_cache.py#L22-L30
train
235,996
contentful/contentful.py
contentful/errors.py
get_error
def get_error(response): """Gets Error by HTTP Status Code""" errors = { 400: BadRequestError, 401: UnauthorizedError, 403: AccessDeniedError, 404: NotFoundError, 429: RateLimitExceededError, 500: ServerError, 502: BadGatewayError, 503: ServiceUnavailableError } error_class = HTTPError if response.status_code in errors: error_class = errors[response.status_code] return error_class(response)
python
def get_error(response): """Gets Error by HTTP Status Code""" errors = { 400: BadRequestError, 401: UnauthorizedError, 403: AccessDeniedError, 404: NotFoundError, 429: RateLimitExceededError, 500: ServerError, 502: BadGatewayError, 503: ServiceUnavailableError } error_class = HTTPError if response.status_code in errors: error_class = errors[response.status_code] return error_class(response)
[ "def", "get_error", "(", "response", ")", ":", "errors", "=", "{", "400", ":", "BadRequestError", ",", "401", ":", "UnauthorizedError", ",", "403", ":", "AccessDeniedError", ",", "404", ":", "NotFoundError", ",", "429", ":", "RateLimitExceededError", ",", "500", ":", "ServerError", ",", "502", ":", "BadGatewayError", ",", "503", ":", "ServiceUnavailableError", "}", "error_class", "=", "HTTPError", "if", "response", ".", "status_code", "in", "errors", ":", "error_class", "=", "errors", "[", "response", ".", "status_code", "]", "return", "error_class", "(", "response", ")" ]
Gets Error by HTTP Status Code
[ "Gets", "Error", "by", "HTTP", "Status", "Code" ]
73fe01d6ae5a1f8818880da65199107b584681dd
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/errors.py#L203-L221
train
235,997
contentful/contentful.py
contentful/content_type.py
ContentType.field_for
def field_for(self, field_id): """Fetches the field for the given Field ID. :param field_id: ID for Field to fetch. :return: :class:`ContentTypeField <ContentTypeField>` object. :rtype: contentful.ContentTypeField """ for field in self.fields: if field.id == field_id: return field return None
python
def field_for(self, field_id): """Fetches the field for the given Field ID. :param field_id: ID for Field to fetch. :return: :class:`ContentTypeField <ContentTypeField>` object. :rtype: contentful.ContentTypeField """ for field in self.fields: if field.id == field_id: return field return None
[ "def", "field_for", "(", "self", ",", "field_id", ")", ":", "for", "field", "in", "self", ".", "fields", ":", "if", "field", ".", "id", "==", "field_id", ":", "return", "field", "return", "None" ]
Fetches the field for the given Field ID. :param field_id: ID for Field to fetch. :return: :class:`ContentTypeField <ContentTypeField>` object. :rtype: contentful.ContentTypeField
[ "Fetches", "the", "field", "for", "the", "given", "Field", "ID", "." ]
73fe01d6ae5a1f8818880da65199107b584681dd
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/content_type.py#L31-L42
train
235,998
contentful/contentful.py
contentful/content_type_field_types.py
LocationField.coerce
def coerce(self, value, **kwargs): """Coerces value to Location object""" Location = namedtuple('Location', ['lat', 'lon']) return Location(float(value.get('lat')), float(value.get('lon')))
python
def coerce(self, value, **kwargs): """Coerces value to Location object""" Location = namedtuple('Location', ['lat', 'lon']) return Location(float(value.get('lat')), float(value.get('lon')))
[ "def", "coerce", "(", "self", ",", "value", ",", "*", "*", "kwargs", ")", ":", "Location", "=", "namedtuple", "(", "'Location'", ",", "[", "'lat'", ",", "'lon'", "]", ")", "return", "Location", "(", "float", "(", "value", ".", "get", "(", "'lat'", ")", ")", ",", "float", "(", "value", ".", "get", "(", "'lon'", ")", ")", ")" ]
Coerces value to Location object
[ "Coerces", "value", "to", "Location", "object" ]
73fe01d6ae5a1f8818880da65199107b584681dd
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/content_type_field_types.py#L96-L100
train
235,999