repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
getfleety/coralillo | coralillo/core.py | Form.set_engine | def set_engine(cls, neweng):
''' Sets the given coralillo engine so the model uses it to communicate
with the redis database '''
assert isinstance(neweng, Engine), 'Provided object must be of class Engine'
if hasattr(cls, 'Meta'):
cls.Meta.engine = neweng
else:
... | python | def set_engine(cls, neweng):
''' Sets the given coralillo engine so the model uses it to communicate
with the redis database '''
assert isinstance(neweng, Engine), 'Provided object must be of class Engine'
if hasattr(cls, 'Meta'):
cls.Meta.engine = neweng
else:
... | [
"def",
"set_engine",
"(",
"cls",
",",
"neweng",
")",
":",
"assert",
"isinstance",
"(",
"neweng",
",",
"Engine",
")",
",",
"'Provided object must be of class Engine'",
"if",
"hasattr",
"(",
"cls",
",",
"'Meta'",
")",
":",
"cls",
".",
"Meta",
".",
"engine",
... | Sets the given coralillo engine so the model uses it to communicate
with the redis database | [
"Sets",
"the",
"given",
"coralillo",
"engine",
"so",
"the",
"model",
"uses",
"it",
"to",
"communicate",
"with",
"the",
"redis",
"database"
] | train | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/core.py#L126-L137 |
getfleety/coralillo | coralillo/core.py | Model.save | def save(self):
''' Persists this object to the database. Each field knows how to store
itself so we don't have to worry about it '''
redis = type(self).get_redis()
pipe = to_pipeline(redis)
pipe.hset(self.key(), 'id', self.id)
for fieldname, field in self.proxy:
... | python | def save(self):
''' Persists this object to the database. Each field knows how to store
itself so we don't have to worry about it '''
redis = type(self).get_redis()
pipe = to_pipeline(redis)
pipe.hset(self.key(), 'id', self.id)
for fieldname, field in self.proxy:
... | [
"def",
"save",
"(",
"self",
")",
":",
"redis",
"=",
"type",
"(",
"self",
")",
".",
"get_redis",
"(",
")",
"pipe",
"=",
"to_pipeline",
"(",
"redis",
")",
"pipe",
".",
"hset",
"(",
"self",
".",
"key",
"(",
")",
",",
"'id'",
",",
"self",
".",
"id"... | Persists this object to the database. Each field knows how to store
itself so we don't have to worry about it | [
"Persists",
"this",
"object",
"to",
"the",
"database",
".",
"Each",
"field",
"knows",
"how",
"to",
"store",
"itself",
"so",
"we",
"don",
"t",
"have",
"to",
"worry",
"about",
"it"
] | train | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/core.py#L166-L192 |
getfleety/coralillo | coralillo/core.py | Model.update | def update(self, **kwargs):
''' validates the given data against this object's rules and then
updates '''
redis = type(self).get_redis()
errors = ValidationErrors()
for fieldname, field in self.proxy:
if not field.fillable:
continue
given... | python | def update(self, **kwargs):
''' validates the given data against this object's rules and then
updates '''
redis = type(self).get_redis()
errors = ValidationErrors()
for fieldname, field in self.proxy:
if not field.fillable:
continue
given... | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"redis",
"=",
"type",
"(",
"self",
")",
".",
"get_redis",
"(",
")",
"errors",
"=",
"ValidationErrors",
"(",
")",
"for",
"fieldname",
",",
"field",
"in",
"self",
".",
"proxy",
":",
"if... | validates the given data against this object's rules and then
updates | [
"validates",
"the",
"given",
"data",
"against",
"this",
"object",
"s",
"rules",
"and",
"then",
"updates"
] | train | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/core.py#L194-L224 |
getfleety/coralillo | coralillo/core.py | Model.get | def get(cls, id):
''' Retrieves an object by id. Returns None in case of failure '''
if not id:
return None
redis = cls.get_redis()
key = '{}:{}:obj'.format(cls.cls_key(), id)
if not redis.exists(key):
return None
obj = cls(id=id)
obj._... | python | def get(cls, id):
''' Retrieves an object by id. Returns None in case of failure '''
if not id:
return None
redis = cls.get_redis()
key = '{}:{}:obj'.format(cls.cls_key(), id)
if not redis.exists(key):
return None
obj = cls(id=id)
obj._... | [
"def",
"get",
"(",
"cls",
",",
"id",
")",
":",
"if",
"not",
"id",
":",
"return",
"None",
"redis",
"=",
"cls",
".",
"get_redis",
"(",
")",
"key",
"=",
"'{}:{}:obj'",
".",
"format",
"(",
"cls",
".",
"cls_key",
"(",
")",
",",
"id",
")",
"if",
"not... | Retrieves an object by id. Returns None in case of failure | [
"Retrieves",
"an",
"object",
"by",
"id",
".",
"Returns",
"None",
"in",
"case",
"of",
"failure"
] | train | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/core.py#L233-L259 |
getfleety/coralillo | coralillo/core.py | Model.q | def q(cls, **kwargs):
''' Creates an iterator over the members of this class that applies the
given filters and returns only the elements matching them '''
redis = cls.get_redis()
return QuerySet(cls, redis.sscan_iter(cls.members_key())) | python | def q(cls, **kwargs):
''' Creates an iterator over the members of this class that applies the
given filters and returns only the elements matching them '''
redis = cls.get_redis()
return QuerySet(cls, redis.sscan_iter(cls.members_key())) | [
"def",
"q",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"redis",
"=",
"cls",
".",
"get_redis",
"(",
")",
"return",
"QuerySet",
"(",
"cls",
",",
"redis",
".",
"sscan_iter",
"(",
"cls",
".",
"members_key",
"(",
")",
")",
")"
] | Creates an iterator over the members of this class that applies the
given filters and returns only the elements matching them | [
"Creates",
"an",
"iterator",
"over",
"the",
"members",
"of",
"this",
"class",
"that",
"applies",
"the",
"given",
"filters",
"and",
"returns",
"only",
"the",
"elements",
"matching",
"them"
] | train | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/core.py#L262-L267 |
getfleety/coralillo | coralillo/core.py | Model.reload | def reload(self):
''' reloads this object so if it was updated in the database it now
contains the new values'''
key = self.key()
redis = type(self).get_redis()
if not redis.exists(key):
raise ModelNotFoundError('This object has been deleted')
data = debyte_... | python | def reload(self):
''' reloads this object so if it was updated in the database it now
contains the new values'''
key = self.key()
redis = type(self).get_redis()
if not redis.exists(key):
raise ModelNotFoundError('This object has been deleted')
data = debyte_... | [
"def",
"reload",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"key",
"(",
")",
"redis",
"=",
"type",
"(",
"self",
")",
".",
"get_redis",
"(",
")",
"if",
"not",
"redis",
".",
"exists",
"(",
"key",
")",
":",
"raise",
"ModelNotFoundError",
"(",
"... | reloads this object so if it was updated in the database it now
contains the new values | [
"reloads",
"this",
"object",
"so",
"if",
"it",
"was",
"updated",
"in",
"the",
"database",
"it",
"now",
"contains",
"the",
"new",
"values"
] | train | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/core.py#L276-L296 |
getfleety/coralillo | coralillo/core.py | Model.get_or_exception | def get_or_exception(cls, id):
''' Tries to retrieve an instance of this model from the database or
raises an exception in case of failure '''
obj = cls.get(id)
if obj is None:
raise ModelNotFoundError('This object does not exist in database')
return obj | python | def get_or_exception(cls, id):
''' Tries to retrieve an instance of this model from the database or
raises an exception in case of failure '''
obj = cls.get(id)
if obj is None:
raise ModelNotFoundError('This object does not exist in database')
return obj | [
"def",
"get_or_exception",
"(",
"cls",
",",
"id",
")",
":",
"obj",
"=",
"cls",
".",
"get",
"(",
"id",
")",
"if",
"obj",
"is",
"None",
":",
"raise",
"ModelNotFoundError",
"(",
"'This object does not exist in database'",
")",
"return",
"obj"
] | Tries to retrieve an instance of this model from the database or
raises an exception in case of failure | [
"Tries",
"to",
"retrieve",
"an",
"instance",
"of",
"this",
"model",
"from",
"the",
"database",
"or",
"raises",
"an",
"exception",
"in",
"case",
"of",
"failure"
] | train | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/core.py#L299-L307 |
getfleety/coralillo | coralillo/core.py | Model.get_by | def get_by(cls, field, value):
''' Tries to retrieve an isinstance of this model from the database
given a value for a defined index. Return None in case of failure '''
redis = cls.get_redis()
key = cls.cls_key()+':index_'+field
id = redis.hget(key, value)
if id:
... | python | def get_by(cls, field, value):
''' Tries to retrieve an isinstance of this model from the database
given a value for a defined index. Return None in case of failure '''
redis = cls.get_redis()
key = cls.cls_key()+':index_'+field
id = redis.hget(key, value)
if id:
... | [
"def",
"get_by",
"(",
"cls",
",",
"field",
",",
"value",
")",
":",
"redis",
"=",
"cls",
".",
"get_redis",
"(",
")",
"key",
"=",
"cls",
".",
"cls_key",
"(",
")",
"+",
"':index_'",
"+",
"field",
"id",
"=",
"redis",
".",
"hget",
"(",
"key",
",",
"... | Tries to retrieve an isinstance of this model from the database
given a value for a defined index. Return None in case of failure | [
"Tries",
"to",
"retrieve",
"an",
"isinstance",
"of",
"this",
"model",
"from",
"the",
"database",
"given",
"a",
"value",
"for",
"a",
"defined",
"index",
".",
"Return",
"None",
"in",
"case",
"of",
"failure"
] | train | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/core.py#L310-L321 |
getfleety/coralillo | coralillo/core.py | Model.get_all | def get_all(cls):
''' Gets all available instances of this model from the database '''
redis = cls.get_redis()
return list(map(
lambda id: cls.get(id),
map(
debyte_string,
redis.smembers(cls.members_key())
)
)) | python | def get_all(cls):
''' Gets all available instances of this model from the database '''
redis = cls.get_redis()
return list(map(
lambda id: cls.get(id),
map(
debyte_string,
redis.smembers(cls.members_key())
)
)) | [
"def",
"get_all",
"(",
"cls",
")",
":",
"redis",
"=",
"cls",
".",
"get_redis",
"(",
")",
"return",
"list",
"(",
"map",
"(",
"lambda",
"id",
":",
"cls",
".",
"get",
"(",
"id",
")",
",",
"map",
"(",
"debyte_string",
",",
"redis",
".",
"smembers",
"... | Gets all available instances of this model from the database | [
"Gets",
"all",
"available",
"instances",
"of",
"this",
"model",
"from",
"the",
"database"
] | train | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/core.py#L333-L343 |
getfleety/coralillo | coralillo/core.py | Model.tree_match | def tree_match(cls, field, string):
''' Given a tree index, retrieves the ids atached to the given prefix,
think of if as a mechanism for pattern suscription, where two models
attached to the `a`, `a:b` respectively are found by the `a:b` string,
because both model's subscription key mat... | python | def tree_match(cls, field, string):
''' Given a tree index, retrieves the ids atached to the given prefix,
think of if as a mechanism for pattern suscription, where two models
attached to the `a`, `a:b` respectively are found by the `a:b` string,
because both model's subscription key mat... | [
"def",
"tree_match",
"(",
"cls",
",",
"field",
",",
"string",
")",
":",
"if",
"not",
"string",
":",
"return",
"set",
"(",
")",
"redis",
"=",
"cls",
".",
"get_redis",
"(",
")",
"prefix",
"=",
"'{}:tree_{}'",
".",
"format",
"(",
"cls",
".",
"cls_key",
... | Given a tree index, retrieves the ids atached to the given prefix,
think of if as a mechanism for pattern suscription, where two models
attached to the `a`, `a:b` respectively are found by the `a:b` string,
because both model's subscription key matches the string. | [
"Given",
"a",
"tree",
"index",
"retrieves",
"the",
"ids",
"atached",
"to",
"the",
"given",
"prefix",
"think",
"of",
"if",
"as",
"a",
"mechanism",
"for",
"pattern",
"suscription",
"where",
"two",
"models",
"attached",
"to",
"the",
"a",
"a",
":",
"b",
"res... | train | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/core.py#L346-L369 |
getfleety/coralillo | coralillo/core.py | Model.key | def key(self):
''' Returns the redis key to access this object's values '''
prefix = type(self).cls_key()
return '{}:{}:obj'.format(prefix, self.id) | python | def key(self):
''' Returns the redis key to access this object's values '''
prefix = type(self).cls_key()
return '{}:{}:obj'.format(prefix, self.id) | [
"def",
"key",
"(",
"self",
")",
":",
"prefix",
"=",
"type",
"(",
"self",
")",
".",
"cls_key",
"(",
")",
"return",
"'{}:{}:obj'",
".",
"format",
"(",
"prefix",
",",
"self",
".",
"id",
")"
] | Returns the redis key to access this object's values | [
"Returns",
"the",
"redis",
"key",
"to",
"access",
"this",
"object",
"s",
"values"
] | train | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/core.py#L383-L387 |
getfleety/coralillo | coralillo/core.py | Model.fqn | def fqn(self):
''' Returns a fully qualified name for this object '''
prefix = type(self).cls_key()
return '{}:{}'.format(prefix, self.id) | python | def fqn(self):
''' Returns a fully qualified name for this object '''
prefix = type(self).cls_key()
return '{}:{}'.format(prefix, self.id) | [
"def",
"fqn",
"(",
"self",
")",
":",
"prefix",
"=",
"type",
"(",
"self",
")",
".",
"cls_key",
"(",
")",
"return",
"'{}:{}'",
".",
"format",
"(",
"prefix",
",",
"self",
".",
"id",
")"
] | Returns a fully qualified name for this object | [
"Returns",
"a",
"fully",
"qualified",
"name",
"for",
"this",
"object"
] | train | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/core.py#L389-L393 |
getfleety/coralillo | coralillo/core.py | Model.to_json | def to_json(self, *, include=None):
''' Serializes this model to a JSON representation so it can be sent
via an HTTP REST API '''
json = dict()
if include is None or 'id' in include or '*' in include:
json['id'] = self.id
if include is None or '_type' in include or ... | python | def to_json(self, *, include=None):
''' Serializes this model to a JSON representation so it can be sent
via an HTTP REST API '''
json = dict()
if include is None or 'id' in include or '*' in include:
json['id'] = self.id
if include is None or '_type' in include or ... | [
"def",
"to_json",
"(",
"self",
",",
"*",
",",
"include",
"=",
"None",
")",
":",
"json",
"=",
"dict",
"(",
")",
"if",
"include",
"is",
"None",
"or",
"'id'",
"in",
"include",
"or",
"'*'",
"in",
"include",
":",
"json",
"[",
"'id'",
"]",
"=",
"self",... | Serializes this model to a JSON representation so it can be sent
via an HTTP REST API | [
"Serializes",
"this",
"model",
"to",
"a",
"JSON",
"representation",
"so",
"it",
"can",
"be",
"sent",
"via",
"an",
"HTTP",
"REST",
"API"
] | train | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/core.py#L403-L447 |
getfleety/coralillo | coralillo/core.py | Model.delete | def delete(self):
''' Deletes this model from the database, calling delete in each field
to properly delete special cases '''
redis = type(self).get_redis()
for fieldname, field in self.proxy:
field.delete(redis)
redis.delete(self.key())
redis.srem(type(self... | python | def delete(self):
''' Deletes this model from the database, calling delete in each field
to properly delete special cases '''
redis = type(self).get_redis()
for fieldname, field in self.proxy:
field.delete(redis)
redis.delete(self.key())
redis.srem(type(self... | [
"def",
"delete",
"(",
"self",
")",
":",
"redis",
"=",
"type",
"(",
"self",
")",
".",
"get_redis",
"(",
")",
"for",
"fieldname",
",",
"field",
"in",
"self",
".",
"proxy",
":",
"field",
".",
"delete",
"(",
"redis",
")",
"redis",
".",
"delete",
"(",
... | Deletes this model from the database, calling delete in each field
to properly delete special cases | [
"Deletes",
"this",
"model",
"from",
"the",
"database",
"calling",
"delete",
"in",
"each",
"field",
"to",
"properly",
"delete",
"special",
"cases"
] | train | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/core.py#L460-L482 |
MonsterDeveloper/python-telegraphapi | telegraphapi/main.py | Telegraph.createAccount | def createAccount(self, short_name, author_name=None, author_url=None):
"""Creates Telegraph account
:param short_name: Required. Account name, helps users with several accounts remember which they are currently using.
Displayed to the user above the "Edit/Publish" button on Telegra.ph, oth... | python | def createAccount(self, short_name, author_name=None, author_url=None):
"""Creates Telegraph account
:param short_name: Required. Account name, helps users with several accounts remember which they are currently using.
Displayed to the user above the "Edit/Publish" button on Telegra.ph, oth... | [
"def",
"createAccount",
"(",
"self",
",",
"short_name",
",",
"author_name",
"=",
"None",
",",
"author_url",
"=",
"None",
")",
":",
"r",
"=",
"self",
".",
"make_method",
"(",
"\"createAccount\"",
",",
"{",
"\"short_name\"",
":",
"short_name",
",",
"\"author_n... | Creates Telegraph account
:param short_name: Required. Account name, helps users with several accounts remember which they are currently using.
Displayed to the user above the "Edit/Publish" button on Telegra.ph, other users don't see this name.
:type short_name: str
:param autho... | [
"Creates",
"Telegraph",
"account",
":",
"param",
"short_name",
":",
"Required",
".",
"Account",
"name",
"helps",
"users",
"with",
"several",
"accounts",
"remember",
"which",
"they",
"are",
"currently",
"using",
".",
"Displayed",
"to",
"the",
"user",
"above",
"... | train | https://github.com/MonsterDeveloper/python-telegraphapi/blob/6ee58fd47d1ce9fb67ef063bc7b54052d4874bb7/telegraphapi/main.py#L34-L56 |
MonsterDeveloper/python-telegraphapi | telegraphapi/main.py | Telegraph.editAccountInfo | def editAccountInfo(self, short_name=None, author_name=None, author_url=None):
"""Use this method to update information about a Telegraph account.
:param short_name: Optional. New account name.
:type short_name: str
:param author_name: Optional. New default author name used when ... | python | def editAccountInfo(self, short_name=None, author_name=None, author_url=None):
"""Use this method to update information about a Telegraph account.
:param short_name: Optional. New account name.
:type short_name: str
:param author_name: Optional. New default author name used when ... | [
"def",
"editAccountInfo",
"(",
"self",
",",
"short_name",
"=",
"None",
",",
"author_name",
"=",
"None",
",",
"author_url",
"=",
"None",
")",
":",
"return",
"self",
".",
"make_method",
"(",
"\"editAccountInfo\"",
",",
"{",
"\"access_token\"",
":",
"self",
"."... | Use this method to update information about a Telegraph account.
:param short_name: Optional. New account name.
:type short_name: str
:param author_name: Optional. New default author name used when creating new articles.
:type author_name: str
:param author_url: Option... | [
"Use",
"this",
"method",
"to",
"update",
"information",
"about",
"a",
"Telegraph",
"account",
".",
":",
"param",
"short_name",
":",
"Optional",
".",
"New",
"account",
"name",
".",
":",
"type",
"short_name",
":",
"str",
":",
"param",
"author_name",
":",
"Op... | train | https://github.com/MonsterDeveloper/python-telegraphapi/blob/6ee58fd47d1ce9fb67ef063bc7b54052d4874bb7/telegraphapi/main.py#L63-L84 |
MonsterDeveloper/python-telegraphapi | telegraphapi/main.py | Telegraph.getAccountInfo | def getAccountInfo(self, fields=None):
"""Use this method to get information about a Telegraph account.
:param fields: List of account fields to return.
Available fields: short_name, author_name, author_url, auth_url, page_count.
:type fields: list
:returns: Account obje... | python | def getAccountInfo(self, fields=None):
"""Use this method to get information about a Telegraph account.
:param fields: List of account fields to return.
Available fields: short_name, author_name, author_url, auth_url, page_count.
:type fields: list
:returns: Account obje... | [
"def",
"getAccountInfo",
"(",
"self",
",",
"fields",
"=",
"None",
")",
":",
"return",
"self",
".",
"make_method",
"(",
"\"getAccountInfo\"",
",",
"{",
"\"access_token\"",
":",
"self",
".",
"access_token",
",",
"\"fields\"",
":",
"json",
".",
"dumps",
"(",
... | Use this method to get information about a Telegraph account.
:param fields: List of account fields to return.
Available fields: short_name, author_name, author_url, auth_url, page_count.
:type fields: list
:returns: Account object on success. | [
"Use",
"this",
"method",
"to",
"get",
"information",
"about",
"a",
"Telegraph",
"account",
".",
":",
"param",
"fields",
":",
"List",
"of",
"account",
"fields",
"to",
"return",
".",
"Available",
"fields",
":",
"short_name",
"author_name",
"author_url",
"auth_ur... | train | https://github.com/MonsterDeveloper/python-telegraphapi/blob/6ee58fd47d1ce9fb67ef063bc7b54052d4874bb7/telegraphapi/main.py#L85-L97 |
MonsterDeveloper/python-telegraphapi | telegraphapi/main.py | Telegraph.createPage | def createPage(self, title, author_name=None, author_url=None,
content=None, html_content=None, return_content=False):
"""Use this method to create a new Telegraph page.
:param title: Required. Page title.
:type title: str
:param author_name: Optional. Author na... | python | def createPage(self, title, author_name=None, author_url=None,
content=None, html_content=None, return_content=False):
"""Use this method to create a new Telegraph page.
:param title: Required. Page title.
:type title: str
:param author_name: Optional. Author na... | [
"def",
"createPage",
"(",
"self",
",",
"title",
",",
"author_name",
"=",
"None",
",",
"author_url",
"=",
"None",
",",
"content",
"=",
"None",
",",
"html_content",
"=",
"None",
",",
"return_content",
"=",
"False",
")",
":",
"if",
"content",
"is",
"None",
... | Use this method to create a new Telegraph page.
:param title: Required. Page title.
:type title: str
:param author_name: Optional. Author name, displayed below the article's title.
:type author_name: str
:param author_url: Optional. Profile link, opened when users click ... | [
"Use",
"this",
"method",
"to",
"create",
"a",
"new",
"Telegraph",
"page",
".",
":",
"param",
"title",
":",
"Required",
".",
"Page",
"title",
".",
":",
"type",
"title",
":",
"str",
":",
"param",
"author_name",
":",
"Optional",
".",
"Author",
"name",
"di... | train | https://github.com/MonsterDeveloper/python-telegraphapi/blob/6ee58fd47d1ce9fb67ef063bc7b54052d4874bb7/telegraphapi/main.py#L108-L140 |
MonsterDeveloper/python-telegraphapi | telegraphapi/main.py | Telegraph.editPage | def editPage(self, path, title, content=None, html_content=None,
author_name=None, author_url=None, return_content=False):
"""Use this method to edit an existing Telegraph page.
:param path: Required. Path to the page.
:type path: str
:param title: Required. Pag... | python | def editPage(self, path, title, content=None, html_content=None,
author_name=None, author_url=None, return_content=False):
"""Use this method to edit an existing Telegraph page.
:param path: Required. Path to the page.
:type path: str
:param title: Required. Pag... | [
"def",
"editPage",
"(",
"self",
",",
"path",
",",
"title",
",",
"content",
"=",
"None",
",",
"html_content",
"=",
"None",
",",
"author_name",
"=",
"None",
",",
"author_url",
"=",
"None",
",",
"return_content",
"=",
"False",
")",
":",
"if",
"content",
"... | Use this method to edit an existing Telegraph page.
:param path: Required. Path to the page.
:type path: str
:param title: Required. Page title.
:type title: str
:param content: Required. Content of the page in NODES format.
:param html_content: Optional. Co... | [
"Use",
"this",
"method",
"to",
"edit",
"an",
"existing",
"Telegraph",
"page",
".",
":",
"param",
"path",
":",
"Required",
".",
"Path",
"to",
"the",
"page",
".",
":",
"type",
"path",
":",
"str",
":",
"param",
"title",
":",
"Required",
".",
"Page",
"ti... | train | https://github.com/MonsterDeveloper/python-telegraphapi/blob/6ee58fd47d1ce9fb67ef063bc7b54052d4874bb7/telegraphapi/main.py#L141-L184 |
MonsterDeveloper/python-telegraphapi | telegraphapi/main.py | Telegraph.getPage | def getPage(self, path, return_content=True, return_html=True):
"""Use this method to get a Telegraph page.
:param path: Required. Path to the Telegraph page
(in the format Title-12-31, i.e. everything that comes after http://telegra.ph/).
:type path: str
:param return_c... | python | def getPage(self, path, return_content=True, return_html=True):
"""Use this method to get a Telegraph page.
:param path: Required. Path to the Telegraph page
(in the format Title-12-31, i.e. everything that comes after http://telegra.ph/).
:type path: str
:param return_c... | [
"def",
"getPage",
"(",
"self",
",",
"path",
",",
"return_content",
"=",
"True",
",",
"return_html",
"=",
"True",
")",
":",
"if",
"path",
"is",
"None",
":",
"raise",
"TelegraphAPIException",
"(",
"\"Error while executing getPage: \"",
"\"PAGE_NOT_FOUND\"",
")",
"... | Use this method to get a Telegraph page.
:param path: Required. Path to the Telegraph page
(in the format Title-12-31, i.e. everything that comes after http://telegra.ph/).
:type path: str
:param return_content: Optional. If true, content field will be returned in Page object.
... | [
"Use",
"this",
"method",
"to",
"get",
"a",
"Telegraph",
"page",
".",
":",
"param",
"path",
":",
"Required",
".",
"Path",
"to",
"the",
"Telegraph",
"page",
"(",
"in",
"the",
"format",
"Title",
"-",
"12",
"-",
"31",
"i",
".",
"e",
".",
"everything",
... | train | https://github.com/MonsterDeveloper/python-telegraphapi/blob/6ee58fd47d1ce9fb67ef063bc7b54052d4874bb7/telegraphapi/main.py#L185-L211 |
MonsterDeveloper/python-telegraphapi | telegraphapi/main.py | Telegraph.getPageList | def getPageList(self, offset=0, limit=50):
"""Use this method to get a list of pages belonging to a Telegraph account.
:param offset: Optional. Sequential number of the first page to be returned.
:type offset: int
:param limit: Optional. Limits the number of pages to be retrieved... | python | def getPageList(self, offset=0, limit=50):
"""Use this method to get a list of pages belonging to a Telegraph account.
:param offset: Optional. Sequential number of the first page to be returned.
:type offset: int
:param limit: Optional. Limits the number of pages to be retrieved... | [
"def",
"getPageList",
"(",
"self",
",",
"offset",
"=",
"0",
",",
"limit",
"=",
"50",
")",
":",
"return",
"self",
".",
"make_method",
"(",
"\"getPageList\"",
",",
"{",
"\"access_token\"",
":",
"self",
".",
"access_token",
",",
"\"offset\"",
":",
"offset",
... | Use this method to get a list of pages belonging to a Telegraph account.
:param offset: Optional. Sequential number of the first page to be returned.
:type offset: int
:param limit: Optional. Limits the number of pages to be retrieved.
:type limit: int
:returns: PageLi... | [
"Use",
"this",
"method",
"to",
"get",
"a",
"list",
"of",
"pages",
"belonging",
"to",
"a",
"Telegraph",
"account",
".",
":",
"param",
"offset",
":",
"Optional",
".",
"Sequential",
"number",
"of",
"the",
"first",
"page",
"to",
"be",
"returned",
".",
":",
... | train | https://github.com/MonsterDeveloper/python-telegraphapi/blob/6ee58fd47d1ce9fb67ef063bc7b54052d4874bb7/telegraphapi/main.py#L212-L228 |
MonsterDeveloper/python-telegraphapi | telegraphapi/main.py | Telegraph.getViews | def getViews(self, path, year=None, month=None, day=None, hour=None):
"""Use this method to get the number of views for a Telegraph article.
:param path: Required. Path to the Telegraph page
(in the format Title-12-31, where 12 is the month and 31 the day the article was first published).
... | python | def getViews(self, path, year=None, month=None, day=None, hour=None):
"""Use this method to get the number of views for a Telegraph article.
:param path: Required. Path to the Telegraph page
(in the format Title-12-31, where 12 is the month and 31 the day the article was first published).
... | [
"def",
"getViews",
"(",
"self",
",",
"path",
",",
"year",
"=",
"None",
",",
"month",
"=",
"None",
",",
"day",
"=",
"None",
",",
"hour",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"raise",
"TelegraphAPIException",
"(",
"\"Error while execut... | Use this method to get the number of views for a Telegraph article.
:param path: Required. Path to the Telegraph page
(in the format Title-12-31, where 12 is the month and 31 the day the article was first published).
:type path: str
:param year: Required if month is passed.
... | [
"Use",
"this",
"method",
"to",
"get",
"the",
"number",
"of",
"views",
"for",
"a",
"Telegraph",
"article",
".",
":",
"param",
"path",
":",
"Required",
".",
"Path",
"to",
"the",
"Telegraph",
"page",
"(",
"in",
"the",
"format",
"Title",
"-",
"12",
"-",
... | train | https://github.com/MonsterDeveloper/python-telegraphapi/blob/6ee58fd47d1ce9fb67ef063bc7b54052d4874bb7/telegraphapi/main.py#L229-L265 |
20c/munge | munge/click.py | Context.init | def init(self):
"""
call after updating options
"""
# remove root logger, so we can reinit
# TODO only remove our own
# TODO move to _init, let overrides use init()
logging.getLogger().handlers = []
if self.debug:
logging.basicConfig(level=log... | python | def init(self):
"""
call after updating options
"""
# remove root logger, so we can reinit
# TODO only remove our own
# TODO move to _init, let overrides use init()
logging.getLogger().handlers = []
if self.debug:
logging.basicConfig(level=log... | [
"def",
"init",
"(",
"self",
")",
":",
"# remove root logger, so we can reinit",
"# TODO only remove our own",
"# TODO move to _init, let overrides use init()",
"logging",
".",
"getLogger",
"(",
")",
".",
"handlers",
"=",
"[",
"]",
"if",
"self",
".",
"debug",
":",
"log... | call after updating options | [
"call",
"after",
"updating",
"options"
] | train | https://github.com/20c/munge/blob/e20fef8c24e48d4b0a5c387820fbb2b7bebb0af0/munge/click.py#L114-L130 |
heuer/cablemap | cablemap.core/cablemap/core/models.py | cable_from_file | def cable_from_file(filename):
"""\
Returns a cable from the provided file.
`filename`
An absolute path to the cable file.
"""
html = codecs.open(filename, 'rb', 'utf-8').read()
return cable_from_html(html, reader.reference_id_from_filename(filename)) | python | def cable_from_file(filename):
"""\
Returns a cable from the provided file.
`filename`
An absolute path to the cable file.
"""
html = codecs.open(filename, 'rb', 'utf-8').read()
return cable_from_html(html, reader.reference_id_from_filename(filename)) | [
"def",
"cable_from_file",
"(",
"filename",
")",
":",
"html",
"=",
"codecs",
".",
"open",
"(",
"filename",
",",
"'rb'",
",",
"'utf-8'",
")",
".",
"read",
"(",
")",
"return",
"cable_from_html",
"(",
"html",
",",
"reader",
".",
"reference_id_from_filename",
"... | \
Returns a cable from the provided file.
`filename`
An absolute path to the cable file. | [
"\\",
"Returns",
"a",
"cable",
"from",
"the",
"provided",
"file",
".",
"filename",
"An",
"absolute",
"path",
"to",
"the",
"cable",
"file",
"."
] | train | https://github.com/heuer/cablemap/blob/42066c8fc2972d237a2c35578e14525aaf705f38/cablemap.core/cablemap/core/models.py#L27-L35 |
heuer/cablemap | cablemap.core/cablemap/core/models.py | cable_from_html | def cable_from_html(html, reference_id=None):
"""\
Returns a cable from the provided HTML page.
`html`
The HTML page of the cable
`reference_id`
The reference identifier of the cable. If the reference_id is ``None``
this function tries to detect it.
"""
if not html:
... | python | def cable_from_html(html, reference_id=None):
"""\
Returns a cable from the provided HTML page.
`html`
The HTML page of the cable
`reference_id`
The reference identifier of the cable. If the reference_id is ``None``
this function tries to detect it.
"""
if not html:
... | [
"def",
"cable_from_html",
"(",
"html",
",",
"reference_id",
"=",
"None",
")",
":",
"if",
"not",
"html",
":",
"raise",
"ValueError",
"(",
"'The HTML page of the cable must be provided, got: \"%r\"'",
"%",
"html",
")",
"if",
"not",
"reference_id",
":",
"reference_id",... | \
Returns a cable from the provided HTML page.
`html`
The HTML page of the cable
`reference_id`
The reference identifier of the cable. If the reference_id is ``None``
this function tries to detect it. | [
"\\",
"Returns",
"a",
"cable",
"from",
"the",
"provided",
"HTML",
"page",
".",
"html",
"The",
"HTML",
"page",
"of",
"the",
"cable",
"reference_id",
"The",
"reference",
"identifier",
"of",
"the",
"cable",
".",
"If",
"the",
"reference_id",
"is",
"None",
"thi... | train | https://github.com/heuer/cablemap/blob/42066c8fc2972d237a2c35578e14525aaf705f38/cablemap.core/cablemap/core/models.py#L38-L56 |
heuer/cablemap | cablemap.core/cablemap/core/models.py | cable_from_row | def cable_from_row(row):
"""\
Returns a cable from the provided row (a tuple/list).
Format of the row:
<identifier>, <creation-date>, <reference-id>, <origin>, <classification-level>, <references-to-other-cables>, <header>, <body>
Note:
The `<identifier>` and `<references-to-other-cab... | python | def cable_from_row(row):
"""\
Returns a cable from the provided row (a tuple/list).
Format of the row:
<identifier>, <creation-date>, <reference-id>, <origin>, <classification-level>, <references-to-other-cables>, <header>, <body>
Note:
The `<identifier>` and `<references-to-other-cab... | [
"def",
"cable_from_row",
"(",
"row",
")",
":",
"def",
"format_creation_date",
"(",
"created",
")",
":",
"date",
",",
"time",
"=",
"created",
".",
"split",
"(",
")",
"month",
",",
"day",
",",
"year",
",",
"hour",
",",
"minute",
"=",
"[",
"x",
".",
"... | \
Returns a cable from the provided row (a tuple/list).
Format of the row:
<identifier>, <creation-date>, <reference-id>, <origin>, <classification-level>, <references-to-other-cables>, <header>, <body>
Note:
The `<identifier>` and `<references-to-other-cables>` columns are ignored.
... | [
"\\",
"Returns",
"a",
"cable",
"from",
"the",
"provided",
"row",
"(",
"a",
"tuple",
"/",
"list",
")",
"."
] | train | https://github.com/heuer/cablemap/blob/42066c8fc2972d237a2c35578e14525aaf705f38/cablemap.core/cablemap/core/models.py#L59-L84 |
heuer/cablemap | cablemap.core/cablemap/core/models.py | Cable.wl_uris | def wl_uris(self):
"""\
Returns cable IRIs to WikiLeaks (mirrors).
"""
def year_month(d):
date, time = d.split()
return date.split('-')[:2]
if not self.created:
raise ValueError('The "created" property must be provided')
year, month = y... | python | def wl_uris(self):
"""\
Returns cable IRIs to WikiLeaks (mirrors).
"""
def year_month(d):
date, time = d.split()
return date.split('-')[:2]
if not self.created:
raise ValueError('The "created" property must be provided')
year, month = y... | [
"def",
"wl_uris",
"(",
"self",
")",
":",
"def",
"year_month",
"(",
"d",
")",
":",
"date",
",",
"time",
"=",
"d",
".",
"split",
"(",
")",
"return",
"date",
".",
"split",
"(",
"'-'",
")",
"[",
":",
"2",
"]",
"if",
"not",
"self",
".",
"created",
... | \
Returns cable IRIs to WikiLeaks (mirrors). | [
"\\",
"Returns",
"cable",
"IRIs",
"to",
"WikiLeaks",
"(",
"mirrors",
")",
"."
] | train | https://github.com/heuer/cablemap/blob/42066c8fc2972d237a2c35578e14525aaf705f38/cablemap.core/cablemap/core/models.py#L182-L199 |
peterldowns/djoauth2 | djoauth2/views.py | access_token_endpoint | def access_token_endpoint(request):
""" Generates :py:class:`djoauth2.models.AccessTokens` if provided with
sufficient authorization.
This endpoint only supports two grant types:
* ``authorization_code``: http://tools.ietf.org/html/rfc6749#section-4.1
* ``refresh_token``: http://tools.ietf.org/html/rfc67... | python | def access_token_endpoint(request):
""" Generates :py:class:`djoauth2.models.AccessTokens` if provided with
sufficient authorization.
This endpoint only supports two grant types:
* ``authorization_code``: http://tools.ietf.org/html/rfc6749#section-4.1
* ``refresh_token``: http://tools.ietf.org/html/rfc67... | [
"def",
"access_token_endpoint",
"(",
"request",
")",
":",
"# TODO(peter): somehow implement the anti-brute-force requirement specified",
"# by http://tools.ietf.org/html/rfc6749#section-2.3.1 :",
"#",
"# Since this client authentication method involves a password, the",
"# authorization ... | Generates :py:class:`djoauth2.models.AccessTokens` if provided with
sufficient authorization.
This endpoint only supports two grant types:
* ``authorization_code``: http://tools.ietf.org/html/rfc6749#section-4.1
* ``refresh_token``: http://tools.ietf.org/html/rfc6749#section-6
For further documentation,... | [
"Generates",
":",
"py",
":",
"class",
":",
"djoauth2",
".",
"models",
".",
"AccessTokens",
"if",
"provided",
"with",
"sufficient",
"authorization",
"."
] | train | https://github.com/peterldowns/djoauth2/blob/151c7619d1d7a91d720397cfecf3a29fcc9747a9/djoauth2/views.py#L17-L214 |
peterldowns/djoauth2 | djoauth2/views.py | generate_access_token_from_authorization_code | def generate_access_token_from_authorization_code(request, client):
""" Generates a new AccessToken from a request with an authorization code.
Read the specification: http://tools.ietf.org/html/rfc6749#section-4.1.3
"""
authorization_code_value = request.POST.get('code')
if not authorization_code_value:
... | python | def generate_access_token_from_authorization_code(request, client):
""" Generates a new AccessToken from a request with an authorization code.
Read the specification: http://tools.ietf.org/html/rfc6749#section-4.1.3
"""
authorization_code_value = request.POST.get('code')
if not authorization_code_value:
... | [
"def",
"generate_access_token_from_authorization_code",
"(",
"request",
",",
"client",
")",
":",
"authorization_code_value",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'code'",
")",
"if",
"not",
"authorization_code_value",
":",
"raise",
"InvalidRequest",
"(",
"'... | Generates a new AccessToken from a request with an authorization code.
Read the specification: http://tools.ietf.org/html/rfc6749#section-4.1.3 | [
"Generates",
"a",
"new",
"AccessToken",
"from",
"a",
"request",
"with",
"an",
"authorization",
"code",
"."
] | train | https://github.com/peterldowns/djoauth2/blob/151c7619d1d7a91d720397cfecf3a29fcc9747a9/djoauth2/views.py#L217-L281 |
peterldowns/djoauth2 | djoauth2/views.py | generate_access_token_from_refresh_token | def generate_access_token_from_refresh_token(request, client):
""" Generates a new AccessToken from a request containing a refresh token.
Read the specification: http://tools.ietf.org/html/rfc6749#section-6.
"""
refresh_token_value = request.POST.get('refresh_token')
if not refresh_token_value:
raise Inv... | python | def generate_access_token_from_refresh_token(request, client):
""" Generates a new AccessToken from a request containing a refresh token.
Read the specification: http://tools.ietf.org/html/rfc6749#section-6.
"""
refresh_token_value = request.POST.get('refresh_token')
if not refresh_token_value:
raise Inv... | [
"def",
"generate_access_token_from_refresh_token",
"(",
"request",
",",
"client",
")",
":",
"refresh_token_value",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'refresh_token'",
")",
"if",
"not",
"refresh_token_value",
":",
"raise",
"InvalidRequest",
"(",
"'no \"r... | Generates a new AccessToken from a request containing a refresh token.
Read the specification: http://tools.ietf.org/html/rfc6749#section-6. | [
"Generates",
"a",
"new",
"AccessToken",
"from",
"a",
"request",
"containing",
"a",
"refresh",
"token",
"."
] | train | https://github.com/peterldowns/djoauth2/blob/151c7619d1d7a91d720397cfecf3a29fcc9747a9/djoauth2/views.py#L284-L383 |
thomasleese/mo | mo/steps.py | help | def help(project, task, step, variables):
"""Run a help step."""
task_name = step.args or variables['task']
try:
task = project.find_task(task_name)
except NoSuchTaskError as e:
yield events.task_not_found(task_name, e.similarities)
raise StopTask
text = f'# {task.name}\n'... | python | def help(project, task, step, variables):
"""Run a help step."""
task_name = step.args or variables['task']
try:
task = project.find_task(task_name)
except NoSuchTaskError as e:
yield events.task_not_found(task_name, e.similarities)
raise StopTask
text = f'# {task.name}\n'... | [
"def",
"help",
"(",
"project",
",",
"task",
",",
"step",
",",
"variables",
")",
":",
"task_name",
"=",
"step",
".",
"args",
"or",
"variables",
"[",
"'task'",
"]",
"try",
":",
"task",
"=",
"project",
".",
"find_task",
"(",
"task_name",
")",
"except",
... | Run a help step. | [
"Run",
"a",
"help",
"step",
"."
] | train | https://github.com/thomasleese/mo/blob/b757f52b42e51ad19c14724ceb7c5db5d52abaea/mo/steps.py#L96-L113 |
bretth/woven | woven/deploy.py | post_install_postgresql | def post_install_postgresql():
"""
example default hook for installing postgresql
"""
from django.conf import settings as s
with settings(warn_only=True):
sudo('/etc/init.d/postgresql-8.4 restart')
sudo("""psql template1 -c "ALTER USER postgres with encrypted password '%s';" """% env... | python | def post_install_postgresql():
"""
example default hook for installing postgresql
"""
from django.conf import settings as s
with settings(warn_only=True):
sudo('/etc/init.d/postgresql-8.4 restart')
sudo("""psql template1 -c "ALTER USER postgres with encrypted password '%s';" """% env... | [
"def",
"post_install_postgresql",
"(",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"as",
"s",
"with",
"settings",
"(",
"warn_only",
"=",
"True",
")",
":",
"sudo",
"(",
"'/etc/init.d/postgresql-8.4 restart'",
")",
"sudo",
"(",
"\"\"\"psql templ... | example default hook for installing postgresql | [
"example",
"default",
"hook",
"for",
"installing",
"postgresql"
] | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/deploy.py#L4-L19 |
ssato/python-anytemplate | anytemplate/cli.py | option_parser | def option_parser():
"""
:return: Option parsing object :: optparse.OptionParser
"""
defaults = dict(template_paths=[], contexts=[], schema=None, output='-',
engine=None, list_engines=False, verbose=1)
psr = argparse.ArgumentParser()
psr.set_defaults(**defaults)
psr.add... | python | def option_parser():
"""
:return: Option parsing object :: optparse.OptionParser
"""
defaults = dict(template_paths=[], contexts=[], schema=None, output='-',
engine=None, list_engines=False, verbose=1)
psr = argparse.ArgumentParser()
psr.set_defaults(**defaults)
psr.add... | [
"def",
"option_parser",
"(",
")",
":",
"defaults",
"=",
"dict",
"(",
"template_paths",
"=",
"[",
"]",
",",
"contexts",
"=",
"[",
"]",
",",
"schema",
"=",
"None",
",",
"output",
"=",
"'-'",
",",
"engine",
"=",
"None",
",",
"list_engines",
"=",
"False"... | :return: Option parsing object :: optparse.OptionParser | [
":",
"return",
":",
"Option",
"parsing",
"object",
"::",
"optparse",
".",
"OptionParser"
] | train | https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/cli.py#L23-L61 |
ssato/python-anytemplate | anytemplate/cli.py | get_loglevel | def get_loglevel(level):
"""
Set log level.
>>> assert get_loglevel(2) == logging.WARN
>>> assert get_loglevel(10) == logging.INFO
"""
try:
return [logging.DEBUG, logging.INFO, logging.WARN][level]
except IndexError:
return logging.INFO | python | def get_loglevel(level):
"""
Set log level.
>>> assert get_loglevel(2) == logging.WARN
>>> assert get_loglevel(10) == logging.INFO
"""
try:
return [logging.DEBUG, logging.INFO, logging.WARN][level]
except IndexError:
return logging.INFO | [
"def",
"get_loglevel",
"(",
"level",
")",
":",
"try",
":",
"return",
"[",
"logging",
".",
"DEBUG",
",",
"logging",
".",
"INFO",
",",
"logging",
".",
"WARN",
"]",
"[",
"level",
"]",
"except",
"IndexError",
":",
"return",
"logging",
".",
"INFO"
] | Set log level.
>>> assert get_loglevel(2) == logging.WARN
>>> assert get_loglevel(10) == logging.INFO | [
"Set",
"log",
"level",
"."
] | train | https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/cli.py#L64-L74 |
ssato/python-anytemplate | anytemplate/cli.py | main | def main(argv=None):
"""
Entrypoint.
"""
if argv is None:
argv = sys.argv
psr = option_parser()
args = psr.parse_args(argv[1:])
if not args.template:
if args.list_engines:
ecs = anytemplate.api.list_engines()
print(", ".join("%s (%s)" % (e.name(), e.... | python | def main(argv=None):
"""
Entrypoint.
"""
if argv is None:
argv = sys.argv
psr = option_parser()
args = psr.parse_args(argv[1:])
if not args.template:
if args.list_engines:
ecs = anytemplate.api.list_engines()
print(", ".join("%s (%s)" % (e.name(), e.... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"psr",
"=",
"option_parser",
"(",
")",
"args",
"=",
"psr",
".",
"parse_args",
"(",
"argv",
"[",
"1",
":",
"]",
")",
"if",
"not"... | Entrypoint. | [
"Entrypoint",
"."
] | train | https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/cli.py#L77-L106 |
globocom/globomap-auth-manager | globomap_auth_manager/redis_client.py | RedisClient.get_cache_token | def get_cache_token(self, token):
""" Get token and data from Redis """
if self.conn is None:
raise CacheException('Redis is not connected')
token_data = self.conn.get(token)
token_data = json.loads(token_data) if token_data else None
return token_data | python | def get_cache_token(self, token):
""" Get token and data from Redis """
if self.conn is None:
raise CacheException('Redis is not connected')
token_data = self.conn.get(token)
token_data = json.loads(token_data) if token_data else None
return token_data | [
"def",
"get_cache_token",
"(",
"self",
",",
"token",
")",
":",
"if",
"self",
".",
"conn",
"is",
"None",
":",
"raise",
"CacheException",
"(",
"'Redis is not connected'",
")",
"token_data",
"=",
"self",
".",
"conn",
".",
"get",
"(",
"token",
")",
"token_data... | Get token and data from Redis | [
"Get",
"token",
"and",
"data",
"from",
"Redis"
] | train | https://github.com/globocom/globomap-auth-manager/blob/a8abd7d8416378dc5452a0b31ad0621fc650cb2d/globomap_auth_manager/redis_client.py#L82-L91 |
globocom/globomap-auth-manager | globomap_auth_manager/redis_client.py | RedisClient.set_cache_token | def set_cache_token(self, token_data):
""" Set Token with data in Redis """
if self.conn is None:
raise CacheException('Redis is not connected')
token = token_data['auth_token']
token_expires = token_data['expires_at']
roles = token_data['roles']
try:
... | python | def set_cache_token(self, token_data):
""" Set Token with data in Redis """
if self.conn is None:
raise CacheException('Redis is not connected')
token = token_data['auth_token']
token_expires = token_data['expires_at']
roles = token_data['roles']
try:
... | [
"def",
"set_cache_token",
"(",
"self",
",",
"token_data",
")",
":",
"if",
"self",
".",
"conn",
"is",
"None",
":",
"raise",
"CacheException",
"(",
"'Redis is not connected'",
")",
"token",
"=",
"token_data",
"[",
"'auth_token'",
"]",
"token_expires",
"=",
"toke... | Set Token with data in Redis | [
"Set",
"Token",
"with",
"data",
"in",
"Redis"
] | train | https://github.com/globocom/globomap-auth-manager/blob/a8abd7d8416378dc5452a0b31ad0621fc650cb2d/globomap_auth_manager/redis_client.py#L93-L117 |
ael-code/pyFsdb | fsdb/config.py | check_config | def check_config(conf):
'''Type and boundary check'''
if 'fmode' in conf and not isinstance(conf['fmode'], string_types):
raise TypeError(TAG + ": `fmode` must be a string")
if 'dmode' in conf and not isinstance(conf['dmode'], string_types):
raise TypeError(TAG + ": `dmode` must be a string... | python | def check_config(conf):
'''Type and boundary check'''
if 'fmode' in conf and not isinstance(conf['fmode'], string_types):
raise TypeError(TAG + ": `fmode` must be a string")
if 'dmode' in conf and not isinstance(conf['dmode'], string_types):
raise TypeError(TAG + ": `dmode` must be a string... | [
"def",
"check_config",
"(",
"conf",
")",
":",
"if",
"'fmode'",
"in",
"conf",
"and",
"not",
"isinstance",
"(",
"conf",
"[",
"'fmode'",
"]",
",",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"TAG",
"+",
"\": `fmode` must be a string\"",
")",
"if",
"'... | Type and boundary check | [
"Type",
"and",
"boundary",
"check"
] | train | https://github.com/ael-code/pyFsdb/blob/de33a0d41373307cb32cdd7ba1991b85ff495ee3/fsdb/config.py#L28-L46 |
ael-code/pyFsdb | fsdb/config.py | from_json_format | def from_json_format(conf):
'''Convert fields of parsed json dictionary to python format'''
if 'fmode' in conf:
conf['fmode'] = int(conf['fmode'], 8)
if 'dmode' in conf:
conf['dmode'] = int(conf['dmode'], 8) | python | def from_json_format(conf):
'''Convert fields of parsed json dictionary to python format'''
if 'fmode' in conf:
conf['fmode'] = int(conf['fmode'], 8)
if 'dmode' in conf:
conf['dmode'] = int(conf['dmode'], 8) | [
"def",
"from_json_format",
"(",
"conf",
")",
":",
"if",
"'fmode'",
"in",
"conf",
":",
"conf",
"[",
"'fmode'",
"]",
"=",
"int",
"(",
"conf",
"[",
"'fmode'",
"]",
",",
"8",
")",
"if",
"'dmode'",
"in",
"conf",
":",
"conf",
"[",
"'dmode'",
"]",
"=",
... | Convert fields of parsed json dictionary to python format | [
"Convert",
"fields",
"of",
"parsed",
"json",
"dictionary",
"to",
"python",
"format"
] | train | https://github.com/ael-code/pyFsdb/blob/de33a0d41373307cb32cdd7ba1991b85ff495ee3/fsdb/config.py#L49-L54 |
ael-code/pyFsdb | fsdb/config.py | to_json_format | def to_json_format(conf):
'''Convert fields of a python dictionary to be dumped in json format'''
if 'fmode' in conf:
conf['fmode'] = oct(conf['fmode'])[-3:]
if 'dmode' in conf:
conf['dmode'] = oct(conf['dmode'])[-3:] | python | def to_json_format(conf):
'''Convert fields of a python dictionary to be dumped in json format'''
if 'fmode' in conf:
conf['fmode'] = oct(conf['fmode'])[-3:]
if 'dmode' in conf:
conf['dmode'] = oct(conf['dmode'])[-3:] | [
"def",
"to_json_format",
"(",
"conf",
")",
":",
"if",
"'fmode'",
"in",
"conf",
":",
"conf",
"[",
"'fmode'",
"]",
"=",
"oct",
"(",
"conf",
"[",
"'fmode'",
"]",
")",
"[",
"-",
"3",
":",
"]",
"if",
"'dmode'",
"in",
"conf",
":",
"conf",
"[",
"'dmode'... | Convert fields of a python dictionary to be dumped in json format | [
"Convert",
"fields",
"of",
"a",
"python",
"dictionary",
"to",
"be",
"dumped",
"in",
"json",
"format"
] | train | https://github.com/ael-code/pyFsdb/blob/de33a0d41373307cb32cdd7ba1991b85ff495ee3/fsdb/config.py#L57-L62 |
ael-code/pyFsdb | fsdb/config.py | normalize_conf | def normalize_conf(conf):
'''Check, convert and adjust user passed config
Given a user configuration it returns a verified configuration with
all parameters converted to the types that are needed at runtime.
'''
conf = conf.copy()
# check for type error
check_config(conf)
# conver... | python | def normalize_conf(conf):
'''Check, convert and adjust user passed config
Given a user configuration it returns a verified configuration with
all parameters converted to the types that are needed at runtime.
'''
conf = conf.copy()
# check for type error
check_config(conf)
# conver... | [
"def",
"normalize_conf",
"(",
"conf",
")",
":",
"conf",
"=",
"conf",
".",
"copy",
"(",
")",
"# check for type error",
"check_config",
"(",
"conf",
")",
"# convert some fileds into python suitable format",
"from_json_format",
"(",
"conf",
")",
"if",
"'dmode'",
"not",... | Check, convert and adjust user passed config
Given a user configuration it returns a verified configuration with
all parameters converted to the types that are needed at runtime. | [
"Check",
"convert",
"and",
"adjust",
"user",
"passed",
"config"
] | train | https://github.com/ael-code/pyFsdb/blob/de33a0d41373307cb32cdd7ba1991b85ff495ee3/fsdb/config.py#L65-L78 |
bretth/woven | woven/webservers.py | _site_users | def _site_users():
"""
Get a list of site_n users
"""
userlist = sudo("cat /etc/passwd | awk '/site/'").split('\n')
siteuserlist = [user.split(':')[0] for user in userlist if 'site_' in user]
return siteuserlist | python | def _site_users():
"""
Get a list of site_n users
"""
userlist = sudo("cat /etc/passwd | awk '/site/'").split('\n')
siteuserlist = [user.split(':')[0] for user in userlist if 'site_' in user]
return siteuserlist | [
"def",
"_site_users",
"(",
")",
":",
"userlist",
"=",
"sudo",
"(",
"\"cat /etc/passwd | awk '/site/'\"",
")",
".",
"split",
"(",
"'\\n'",
")",
"siteuserlist",
"=",
"[",
"user",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
"for",
"user",
"in",
"userlist"... | Get a list of site_n users | [
"Get",
"a",
"list",
"of",
"site_n",
"users"
] | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/webservers.py#L76-L82 |
bretth/woven | woven/webservers.py | _ls_sites | def _ls_sites(path):
"""
List only sites in the domain_sites() to ensure we co-exist with other projects
"""
with cd(path):
sites = run('ls').split('\n')
doms = [d.name for d in domain_sites()]
dom_sites = []
for s in sites:
ds = s.split('-')[0]
d... | python | def _ls_sites(path):
"""
List only sites in the domain_sites() to ensure we co-exist with other projects
"""
with cd(path):
sites = run('ls').split('\n')
doms = [d.name for d in domain_sites()]
dom_sites = []
for s in sites:
ds = s.split('-')[0]
d... | [
"def",
"_ls_sites",
"(",
"path",
")",
":",
"with",
"cd",
"(",
"path",
")",
":",
"sites",
"=",
"run",
"(",
"'ls'",
")",
".",
"split",
"(",
"'\\n'",
")",
"doms",
"=",
"[",
"d",
".",
"name",
"for",
"d",
"in",
"domain_sites",
"(",
")",
"]",
"dom_si... | List only sites in the domain_sites() to ensure we co-exist with other projects | [
"List",
"only",
"sites",
"in",
"the",
"domain_sites",
"()",
"to",
"ensure",
"we",
"co",
"-",
"exist",
"with",
"other",
"projects"
] | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/webservers.py#L84-L97 |
bretth/woven | woven/webservers.py | _sitesettings_files | def _sitesettings_files():
"""
Get a list of sitesettings files
settings.py can be prefixed with a subdomain and underscore so with example.com site:
sitesettings/settings.py would be the example.com settings file and
sitesettings/admin_settings.py would be the admin.example.com settings file
... | python | def _sitesettings_files():
"""
Get a list of sitesettings files
settings.py can be prefixed with a subdomain and underscore so with example.com site:
sitesettings/settings.py would be the example.com settings file and
sitesettings/admin_settings.py would be the admin.example.com settings file
... | [
"def",
"_sitesettings_files",
"(",
")",
":",
"settings_files",
"=",
"[",
"]",
"sitesettings_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"env",
".",
"project_package_name",
",",
"'sitesettings'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"sites... | Get a list of sitesettings files
settings.py can be prefixed with a subdomain and underscore so with example.com site:
sitesettings/settings.py would be the example.com settings file and
sitesettings/admin_settings.py would be the admin.example.com settings file | [
"Get",
"a",
"list",
"of",
"sitesettings",
"files",
"settings",
".",
"py",
"can",
"be",
"prefixed",
"with",
"a",
"subdomain",
"and",
"underscore",
"so",
"with",
"example",
".",
"com",
"site",
":",
"sitesettings",
"/",
"settings",
".",
"py",
"would",
"be",
... | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/webservers.py#L101-L118 |
bretth/woven | woven/webservers.py | _get_django_sites | def _get_django_sites():
"""
Get a list of sites as dictionaries {site_id:'domain.name'}
"""
deployed = version_state('deploy_project')
if not env.sites and 'django.contrib.sites' in env.INSTALLED_APPS and deployed:
with cd('/'.join([deployment_root(),'env',env.project_fullname,'project',en... | python | def _get_django_sites():
"""
Get a list of sites as dictionaries {site_id:'domain.name'}
"""
deployed = version_state('deploy_project')
if not env.sites and 'django.contrib.sites' in env.INSTALLED_APPS and deployed:
with cd('/'.join([deployment_root(),'env',env.project_fullname,'project',en... | [
"def",
"_get_django_sites",
"(",
")",
":",
"deployed",
"=",
"version_state",
"(",
"'deploy_project'",
")",
"if",
"not",
"env",
".",
"sites",
"and",
"'django.contrib.sites'",
"in",
"env",
".",
"INSTALLED_APPS",
"and",
"deployed",
":",
"with",
"cd",
"(",
"'/'",
... | Get a list of sites as dictionaries {site_id:'domain.name'} | [
"Get",
"a",
"list",
"of",
"sites",
"as",
"dictionaries",
"{",
"site_id",
":",
"domain",
".",
"name",
"}"
] | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/webservers.py#L120-L145 |
bretth/woven | woven/webservers.py | domain_sites | def domain_sites():
"""
Get a list of domains
Each domain is an attribute dict with name, site_id and settings
"""
if not hasattr(env,'domains'):
sites = _get_django_sites()
site_ids = sites.keys()
site_ids.sort()
domains = []
for id in site_ids... | python | def domain_sites():
"""
Get a list of domains
Each domain is an attribute dict with name, site_id and settings
"""
if not hasattr(env,'domains'):
sites = _get_django_sites()
site_ids = sites.keys()
site_ids.sort()
domains = []
for id in site_ids... | [
"def",
"domain_sites",
"(",
")",
":",
"if",
"not",
"hasattr",
"(",
"env",
",",
"'domains'",
")",
":",
"sites",
"=",
"_get_django_sites",
"(",
")",
"site_ids",
"=",
"sites",
".",
"keys",
"(",
")",
"site_ids",
".",
"sort",
"(",
")",
"domains",
"=",
"["... | Get a list of domains
Each domain is an attribute dict with name, site_id and settings | [
"Get",
"a",
"list",
"of",
"domains",
"Each",
"domain",
"is",
"an",
"attribute",
"dict",
"with",
"name",
"site_id",
"and",
"settings"
] | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/webservers.py#L147-L181 |
bretth/woven | woven/webservers.py | deploy_webconf | def deploy_webconf():
""" Deploy nginx and other wsgi server site configurations to the host """
deployed = []
log_dir = '/'.join([deployment_root(),'log'])
#TODO - incorrect - check for actual package to confirm installation
if webserver_list():
if env.verbosity:
print env.host,... | python | def deploy_webconf():
""" Deploy nginx and other wsgi server site configurations to the host """
deployed = []
log_dir = '/'.join([deployment_root(),'log'])
#TODO - incorrect - check for actual package to confirm installation
if webserver_list():
if env.verbosity:
print env.host,... | [
"def",
"deploy_webconf",
"(",
")",
":",
"deployed",
"=",
"[",
"]",
"log_dir",
"=",
"'/'",
".",
"join",
"(",
"[",
"deployment_root",
"(",
")",
",",
"'log'",
"]",
")",
"#TODO - incorrect - check for actual package to confirm installation",
"if",
"webserver_list",
"(... | Deploy nginx and other wsgi server site configurations to the host | [
"Deploy",
"nginx",
"and",
"other",
"wsgi",
"server",
"site",
"configurations",
"to",
"the",
"host"
] | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/webservers.py#L184-L208 |
bretth/woven | woven/webservers.py | deploy_wsgi | def deploy_wsgi():
"""
deploy python wsgi file(s)
"""
if 'libapache2-mod-wsgi' in get_packages():
remote_dir = '/'.join([deployment_root(),'env',env.project_fullname,'wsgi'])
wsgi = 'apache2'
elif 'gunicorn' in get_packages():
remote_dir = '/etc/init'
wsgi = 'gunicor... | python | def deploy_wsgi():
"""
deploy python wsgi file(s)
"""
if 'libapache2-mod-wsgi' in get_packages():
remote_dir = '/'.join([deployment_root(),'env',env.project_fullname,'wsgi'])
wsgi = 'apache2'
elif 'gunicorn' in get_packages():
remote_dir = '/etc/init'
wsgi = 'gunicor... | [
"def",
"deploy_wsgi",
"(",
")",
":",
"if",
"'libapache2-mod-wsgi'",
"in",
"get_packages",
"(",
")",
":",
"remote_dir",
"=",
"'/'",
".",
"join",
"(",
"[",
"deployment_root",
"(",
")",
",",
"'env'",
",",
"env",
".",
"project_fullname",
",",
"'wsgi'",
"]",
... | deploy python wsgi file(s) | [
"deploy",
"python",
"wsgi",
"file",
"(",
"s",
")"
] | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/webservers.py#L211-L275 |
bretth/woven | woven/webservers.py | webserver_list | def webserver_list():
"""
list of webserver packages
"""
p = set(get_packages())
w = set(['apache2','gunicorn','uwsgi','nginx'])
installed = p & w
return list(installed) | python | def webserver_list():
"""
list of webserver packages
"""
p = set(get_packages())
w = set(['apache2','gunicorn','uwsgi','nginx'])
installed = p & w
return list(installed) | [
"def",
"webserver_list",
"(",
")",
":",
"p",
"=",
"set",
"(",
"get_packages",
"(",
")",
")",
"w",
"=",
"set",
"(",
"[",
"'apache2'",
",",
"'gunicorn'",
",",
"'uwsgi'",
",",
"'nginx'",
"]",
")",
"installed",
"=",
"p",
"&",
"w",
"return",
"list",
"("... | list of webserver packages | [
"list",
"of",
"webserver",
"packages"
] | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/webservers.py#L277-L284 |
bretth/woven | woven/webservers.py | reload_webservers | def reload_webservers():
"""
Reload apache2 and nginx
"""
if env.verbosity:
print env.host, "RELOADING apache2"
with settings(warn_only=True):
a = sudo("/etc/init.d/apache2 reload")
if env.verbosity:
print '',a
if env.verbosity:
#Reload used t... | python | def reload_webservers():
"""
Reload apache2 and nginx
"""
if env.verbosity:
print env.host, "RELOADING apache2"
with settings(warn_only=True):
a = sudo("/etc/init.d/apache2 reload")
if env.verbosity:
print '',a
if env.verbosity:
#Reload used t... | [
"def",
"reload_webservers",
"(",
")",
":",
"if",
"env",
".",
"verbosity",
":",
"print",
"env",
".",
"host",
",",
"\"RELOADING apache2\"",
"with",
"settings",
"(",
"warn_only",
"=",
"True",
")",
":",
"a",
"=",
"sudo",
"(",
"\"/etc/init.d/apache2 reload\"",
")... | Reload apache2 and nginx | [
"Reload",
"apache2",
"and",
"nginx"
] | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/webservers.py#L286-L308 |
bretth/woven | woven/webservers.py | stop_webserver | def stop_webserver(server):
"""
Stop server
"""
#TODO - distinguish between a warning and a error on apache
if server == 'apache2':
with settings(warn_only=True):
if env.verbosity:
print env.host,"STOPPING apache2"
a = sudo("/etc/init.d/apache2 stop")
... | python | def stop_webserver(server):
"""
Stop server
"""
#TODO - distinguish between a warning and a error on apache
if server == 'apache2':
with settings(warn_only=True):
if env.verbosity:
print env.host,"STOPPING apache2"
a = sudo("/etc/init.d/apache2 stop")
... | [
"def",
"stop_webserver",
"(",
"server",
")",
":",
"#TODO - distinguish between a warning and a error on apache",
"if",
"server",
"==",
"'apache2'",
":",
"with",
"settings",
"(",
"warn_only",
"=",
"True",
")",
":",
"if",
"env",
".",
"verbosity",
":",
"print",
"env"... | Stop server | [
"Stop",
"server"
] | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/webservers.py#L310-L329 |
bretth/woven | woven/webservers.py | start_webserver | def start_webserver(server):
"""
Start server
"""
if server == 'apache2':
with settings(warn_only=True):
if env.verbosity:
print env.host,"STARTING apache2"
#some issues with pty=True getting apache to start on ec2
a = sudo("/etc/init.d/apache2... | python | def start_webserver(server):
"""
Start server
"""
if server == 'apache2':
with settings(warn_only=True):
if env.verbosity:
print env.host,"STARTING apache2"
#some issues with pty=True getting apache to start on ec2
a = sudo("/etc/init.d/apache2... | [
"def",
"start_webserver",
"(",
"server",
")",
":",
"if",
"server",
"==",
"'apache2'",
":",
"with",
"settings",
"(",
"warn_only",
"=",
"True",
")",
":",
"if",
"env",
".",
"verbosity",
":",
"print",
"env",
".",
"host",
",",
"\"STARTING apache2\"",
"#some iss... | Start server | [
"Start",
"server"
] | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/webservers.py#L331-L368 |
StyXman/ayrton | ayrton/parser/pyparser/pytokenizer.py | match_encoding_declaration | def match_encoding_declaration(comment):
"""returns the declared encoding or None
This function is a replacement for :
>>> py_encoding = re.compile(r"coding[:=]\s*([-\w.]+)")
>>> py_encoding.search(comment)
"""
# the coding line must be ascii
try:
comment = comment.decode('ascii')
... | python | def match_encoding_declaration(comment):
"""returns the declared encoding or None
This function is a replacement for :
>>> py_encoding = re.compile(r"coding[:=]\s*([-\w.]+)")
>>> py_encoding.search(comment)
"""
# the coding line must be ascii
try:
comment = comment.decode('ascii')
... | [
"def",
"match_encoding_declaration",
"(",
"comment",
")",
":",
"# the coding line must be ascii",
"try",
":",
"comment",
"=",
"comment",
".",
"decode",
"(",
"'ascii'",
")",
"except",
"UnicodeDecodeError",
":",
"return",
"None",
"index",
"=",
"comment",
".",
"find"... | returns the declared encoding or None
This function is a replacement for :
>>> py_encoding = re.compile(r"coding[:=]\s*([-\w.]+)")
>>> py_encoding.search(comment) | [
"returns",
"the",
"declared",
"encoding",
"or",
"None"
] | train | https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/pyparser/pytokenizer.py#L15-L51 |
StyXman/ayrton | ayrton/parser/pyparser/pytokenizer.py | generate_tokens | def generate_tokens(lines, flags):
"""
This is a rewrite of pypy.module.parser.pytokenize.generate_tokens since
the original function is not RPYTHON (uses yield)
It was also slightly modified to generate Token instances instead
of the original 5-tuples -- it's now a 4-tuple of
* the Token insta... | python | def generate_tokens(lines, flags):
"""
This is a rewrite of pypy.module.parser.pytokenize.generate_tokens since
the original function is not RPYTHON (uses yield)
It was also slightly modified to generate Token instances instead
of the original 5-tuples -- it's now a 4-tuple of
* the Token insta... | [
"def",
"generate_tokens",
"(",
"lines",
",",
"flags",
")",
":",
"token_list",
"=",
"[",
"]",
"lnum",
"=",
"parenlev",
"=",
"continued",
"=",
"0",
"namechars",
"=",
"NAMECHARS",
"numchars",
"=",
"NUMCHARS",
"contstr",
",",
"needcont",
"=",
"''",
",",
"0",... | This is a rewrite of pypy.module.parser.pytokenize.generate_tokens since
the original function is not RPYTHON (uses yield)
It was also slightly modified to generate Token instances instead
of the original 5-tuples -- it's now a 4-tuple of
* the Token instance
* the whole line as a string
* the ... | [
"This",
"is",
"a",
"rewrite",
"of",
"pypy",
".",
"module",
".",
"parser",
".",
"pytokenize",
".",
"generate_tokens",
"since",
"the",
"original",
"function",
"is",
"not",
"RPYTHON",
"(",
"uses",
"yield",
")",
"It",
"was",
"also",
"slightly",
"modified",
"to... | train | https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/pyparser/pytokenizer.py#L68-L303 |
globocom/globomap-auth-manager | globomap_auth_manager/auth.py | Auth.is_url_ok | def is_url_ok(self):
""" Verify Keystone Auth URL """
response = requests.head(settings.KEYSTONE_AUTH_URL)
if response.status_code == 200:
return True
return False | python | def is_url_ok(self):
""" Verify Keystone Auth URL """
response = requests.head(settings.KEYSTONE_AUTH_URL)
if response.status_code == 200:
return True
return False | [
"def",
"is_url_ok",
"(",
"self",
")",
":",
"response",
"=",
"requests",
".",
"head",
"(",
"settings",
".",
"KEYSTONE_AUTH_URL",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"return",
"True",
"return",
"False"
] | Verify Keystone Auth URL | [
"Verify",
"Keystone",
"Auth",
"URL"
] | train | https://github.com/globocom/globomap-auth-manager/blob/a8abd7d8416378dc5452a0b31ad0621fc650cb2d/globomap_auth_manager/auth.py#L38-L44 |
globocom/globomap-auth-manager | globomap_auth_manager/auth.py | Auth.set_token | def set_token(self, value):
""" Set Token """
if value and value.find('Token token=') == 0:
token = value[12:]
else:
token = value
self.token = token | python | def set_token(self, value):
""" Set Token """
if value and value.find('Token token=') == 0:
token = value[12:]
else:
token = value
self.token = token | [
"def",
"set_token",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"and",
"value",
".",
"find",
"(",
"'Token token='",
")",
"==",
"0",
":",
"token",
"=",
"value",
"[",
"12",
":",
"]",
"else",
":",
"token",
"=",
"value",
"self",
".",
"token",
... | Set Token | [
"Set",
"Token"
] | train | https://github.com/globocom/globomap-auth-manager/blob/a8abd7d8416378dc5452a0b31ad0621fc650cb2d/globomap_auth_manager/auth.py#L51-L58 |
globocom/globomap-auth-manager | globomap_auth_manager/auth.py | Auth._set_token_data | def _set_token_data(self):
""" Set token_data by Keystone """
if not self.token:
return
self._set_config_keystone(
settings.KEYSTONE_USERNAME, settings.KEYSTONE_PASSWORD)
token_data = self._keystone_auth.validate_token(self.token)
if not token_data:
... | python | def _set_token_data(self):
""" Set token_data by Keystone """
if not self.token:
return
self._set_config_keystone(
settings.KEYSTONE_USERNAME, settings.KEYSTONE_PASSWORD)
token_data = self._keystone_auth.validate_token(self.token)
if not token_data:
... | [
"def",
"_set_token_data",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"token",
":",
"return",
"self",
".",
"_set_config_keystone",
"(",
"settings",
".",
"KEYSTONE_USERNAME",
",",
"settings",
".",
"KEYSTONE_PASSWORD",
")",
"token_data",
"=",
"self",
".",
... | Set token_data by Keystone | [
"Set",
"token_data",
"by",
"Keystone"
] | train | https://github.com/globocom/globomap-auth-manager/blob/a8abd7d8416378dc5452a0b31ad0621fc650cb2d/globomap_auth_manager/auth.py#L60-L81 |
globocom/globomap-auth-manager | globomap_auth_manager/auth.py | Auth._set_config_keystone | def _set_config_keystone(self, username, password):
""" Set config to Keystone """
self._keystone_auth = KeystoneAuth(
settings.KEYSTONE_AUTH_URL, settings.KEYSTONE_PROJECT_NAME, username, password,
settings.KEYSTONE_USER_DOMAIN_NAME, settings.KEYSTONE_PROJECT_DOMAIN_NAME,
... | python | def _set_config_keystone(self, username, password):
""" Set config to Keystone """
self._keystone_auth = KeystoneAuth(
settings.KEYSTONE_AUTH_URL, settings.KEYSTONE_PROJECT_NAME, username, password,
settings.KEYSTONE_USER_DOMAIN_NAME, settings.KEYSTONE_PROJECT_DOMAIN_NAME,
... | [
"def",
"_set_config_keystone",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"self",
".",
"_keystone_auth",
"=",
"KeystoneAuth",
"(",
"settings",
".",
"KEYSTONE_AUTH_URL",
",",
"settings",
".",
"KEYSTONE_PROJECT_NAME",
",",
"username",
",",
"password",
... | Set config to Keystone | [
"Set",
"config",
"to",
"Keystone"
] | train | https://github.com/globocom/globomap-auth-manager/blob/a8abd7d8416378dc5452a0b31ad0621fc650cb2d/globomap_auth_manager/auth.py#L83-L89 |
globocom/globomap-auth-manager | globomap_auth_manager/auth.py | Auth.get_token_data | def get_token_data(self):
""" Get token and data from keystone """
token_data = self._keystone_auth.conn.auth_ref
token = token_data['auth_token']
self.set_token(token)
if self.cache.is_redis_ok():
try:
self.cache.set_cache_token(token_data)
... | python | def get_token_data(self):
""" Get token and data from keystone """
token_data = self._keystone_auth.conn.auth_ref
token = token_data['auth_token']
self.set_token(token)
if self.cache.is_redis_ok():
try:
self.cache.set_cache_token(token_data)
... | [
"def",
"get_token_data",
"(",
"self",
")",
":",
"token_data",
"=",
"self",
".",
"_keystone_auth",
".",
"conn",
".",
"auth_ref",
"token",
"=",
"token_data",
"[",
"'auth_token'",
"]",
"self",
".",
"set_token",
"(",
"token",
")",
"if",
"self",
".",
"cache",
... | Get token and data from keystone | [
"Get",
"token",
"and",
"data",
"from",
"keystone"
] | train | https://github.com/globocom/globomap-auth-manager/blob/a8abd7d8416378dc5452a0b31ad0621fc650cb2d/globomap_auth_manager/auth.py#L91-L109 |
globocom/globomap-auth-manager | globomap_auth_manager/auth.py | Auth.validate_token | def validate_token(self):
""" Validate Token """
if not self.token:
self.logger.error('Missing Token')
raise InvalidToken('Missing Token')
if self.cache.is_redis_ok():
try:
token_data = self.cache.get_cache_token(self.token)
excep... | python | def validate_token(self):
""" Validate Token """
if not self.token:
self.logger.error('Missing Token')
raise InvalidToken('Missing Token')
if self.cache.is_redis_ok():
try:
token_data = self.cache.get_cache_token(self.token)
excep... | [
"def",
"validate_token",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"token",
":",
"self",
".",
"logger",
".",
"error",
"(",
"'Missing Token'",
")",
"raise",
"InvalidToken",
"(",
"'Missing Token'",
")",
"if",
"self",
".",
"cache",
".",
"is_redis_ok",
... | Validate Token | [
"Validate",
"Token"
] | train | https://github.com/globocom/globomap-auth-manager/blob/a8abd7d8416378dc5452a0b31ad0621fc650cb2d/globomap_auth_manager/auth.py#L111-L130 |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/reader.py | get_cache | def get_cache(taxonomy_id):
"""Return cache for the given taxonomy id.
:param taxonomy_id: identifier of the taxonomy
:type taxonomy_id: str
:return: dictionary object (empty if no taxonomy_id
is found), you must not change anything inside it.
Create a new dictionary and use set_cache ... | python | def get_cache(taxonomy_id):
"""Return cache for the given taxonomy id.
:param taxonomy_id: identifier of the taxonomy
:type taxonomy_id: str
:return: dictionary object (empty if no taxonomy_id
is found), you must not change anything inside it.
Create a new dictionary and use set_cache ... | [
"def",
"get_cache",
"(",
"taxonomy_id",
")",
":",
"if",
"taxonomy_id",
"in",
"_CACHE",
":",
"ctime",
",",
"taxonomy",
"=",
"_CACHE",
"[",
"taxonomy_id",
"]",
"# check it is fresh version",
"onto_name",
",",
"onto_path",
",",
"onto_url",
"=",
"_get_ontology",
"("... | Return cache for the given taxonomy id.
:param taxonomy_id: identifier of the taxonomy
:type taxonomy_id: str
:return: dictionary object (empty if no taxonomy_id
is found), you must not change anything inside it.
Create a new dictionary and use set_cache if you want
to update the c... | [
"Return",
"cache",
"for",
"the",
"given",
"taxonomy",
"id",
"."
] | train | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L58-L91 |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/reader.py | get_regular_expressions | def get_regular_expressions(taxonomy_name, rebuild=False, no_cache=False):
"""Return a list of patterns compiled from the RDF/SKOS ontology.
Uses cache if it exists and if the taxonomy hasn't changed.
"""
# Translate the ontology name into a local path. Check if the name
# relates to an existing on... | python | def get_regular_expressions(taxonomy_name, rebuild=False, no_cache=False):
"""Return a list of patterns compiled from the RDF/SKOS ontology.
Uses cache if it exists and if the taxonomy hasn't changed.
"""
# Translate the ontology name into a local path. Check if the name
# relates to an existing on... | [
"def",
"get_regular_expressions",
"(",
"taxonomy_name",
",",
"rebuild",
"=",
"False",
",",
"no_cache",
"=",
"False",
")",
":",
"# Translate the ontology name into a local path. Check if the name",
"# relates to an existing ontology.",
"onto_name",
",",
"onto_path",
",",
"onto... | Return a list of patterns compiled from the RDF/SKOS ontology.
Uses cache if it exists and if the taxonomy hasn't changed. | [
"Return",
"a",
"list",
"of",
"patterns",
"compiled",
"from",
"the",
"RDF",
"/",
"SKOS",
"ontology",
"."
] | train | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L99-L165 |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/reader.py | _get_remote_ontology | def _get_remote_ontology(onto_url, time_difference=None):
"""Check if the online ontology is more recent than the local ontology.
If yes, try to download and store it in Invenio's cache directory.
Return a boolean describing the success of the operation.
:return: path to the downloaded ontology.
... | python | def _get_remote_ontology(onto_url, time_difference=None):
"""Check if the online ontology is more recent than the local ontology.
If yes, try to download and store it in Invenio's cache directory.
Return a boolean describing the success of the operation.
:return: path to the downloaded ontology.
... | [
"def",
"_get_remote_ontology",
"(",
"onto_url",
",",
"time_difference",
"=",
"None",
")",
":",
"if",
"onto_url",
"is",
"None",
":",
"return",
"False",
"dl_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"current_app",
".",
"config",
"[",
"\"CLASSIFIER_WORKDI... | Check if the online ontology is more recent than the local ontology.
If yes, try to download and store it in Invenio's cache directory.
Return a boolean describing the success of the operation.
:return: path to the downloaded ontology. | [
"Check",
"if",
"the",
"online",
"ontology",
"is",
"more",
"recent",
"than",
"the",
"local",
"ontology",
"."
] | train | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L168-L212 |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/reader.py | _get_ontology | def _get_ontology(ontology):
"""Return the (name, path, url) to the short ontology name.
:param ontology: path to the file or url.
"""
onto_name = onto_path = onto_url = None
# first assume we got the path to the file
if os.path.exists(ontology):
onto_name = os.path.split(os.path.abspa... | python | def _get_ontology(ontology):
"""Return the (name, path, url) to the short ontology name.
:param ontology: path to the file or url.
"""
onto_name = onto_path = onto_url = None
# first assume we got the path to the file
if os.path.exists(ontology):
onto_name = os.path.split(os.path.abspa... | [
"def",
"_get_ontology",
"(",
"ontology",
")",
":",
"onto_name",
"=",
"onto_path",
"=",
"onto_url",
"=",
"None",
"# first assume we got the path to the file",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"ontology",
")",
":",
"onto_name",
"=",
"os",
".",
"path"... | Return the (name, path, url) to the short ontology name.
:param ontology: path to the file or url. | [
"Return",
"the",
"(",
"name",
"path",
"url",
")",
"to",
"the",
"short",
"ontology",
"name",
"."
] | train | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L215-L241 |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/reader.py | _discover_ontology | def _discover_ontology(ontology_path):
"""Look for the file in known places.
:param ontology: path name or url
:type ontology: str
:return: absolute path of a file if found, or None
"""
last_part = os.path.split(os.path.abspath(ontology_path))[1]
possible_patterns = [last_part, last_part.l... | python | def _discover_ontology(ontology_path):
"""Look for the file in known places.
:param ontology: path name or url
:type ontology: str
:return: absolute path of a file if found, or None
"""
last_part = os.path.split(os.path.abspath(ontology_path))[1]
possible_patterns = [last_part, last_part.l... | [
"def",
"_discover_ontology",
"(",
"ontology_path",
")",
":",
"last_part",
"=",
"os",
".",
"path",
".",
"split",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"ontology_path",
")",
")",
"[",
"1",
"]",
"possible_patterns",
"=",
"[",
"last_part",
",",
"last_... | Look for the file in known places.
:param ontology: path name or url
:type ontology: str
:return: absolute path of a file if found, or None | [
"Look",
"for",
"the",
"file",
"in",
"known",
"places",
"."
] | train | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L244-L296 |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/reader.py | _build_cache | def _build_cache(source_file, skip_cache=False):
"""Build the cached data.
Either by parsing the RDF taxonomy file or a vocabulary file.
:param source_file: source file of the taxonomy, RDF file
:param skip_cache: if True, build cache will not be
saved (pickled) - it is saved as <source_file.d... | python | def _build_cache(source_file, skip_cache=False):
"""Build the cached data.
Either by parsing the RDF taxonomy file or a vocabulary file.
:param source_file: source file of the taxonomy, RDF file
:param skip_cache: if True, build cache will not be
saved (pickled) - it is saved as <source_file.d... | [
"def",
"_build_cache",
"(",
"source_file",
",",
"skip_cache",
"=",
"False",
")",
":",
"store",
"=",
"rdflib",
".",
"ConjunctiveGraph",
"(",
")",
"if",
"skip_cache",
":",
"current_app",
".",
"logger",
".",
"info",
"(",
"\"You requested not to save the cache to disk... | Build the cached data.
Either by parsing the RDF taxonomy file or a vocabulary file.
:param source_file: source file of the taxonomy, RDF file
:param skip_cache: if True, build cache will not be
saved (pickled) - it is saved as <source_file.db> | [
"Build",
"the",
"cached",
"data",
"."
] | train | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L546-L690 |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/reader.py | _capitalize_first_letter | def _capitalize_first_letter(word):
"""Return a regex pattern with the first letter.
Accepts both lowercase and uppercase.
"""
if word[0].isalpha():
# These two cases are necessary in order to get a regex pattern
# starting with '[xX]' and not '[Xx]'. This allows to check for
# ... | python | def _capitalize_first_letter(word):
"""Return a regex pattern with the first letter.
Accepts both lowercase and uppercase.
"""
if word[0].isalpha():
# These two cases are necessary in order to get a regex pattern
# starting with '[xX]' and not '[Xx]'. This allows to check for
# ... | [
"def",
"_capitalize_first_letter",
"(",
"word",
")",
":",
"if",
"word",
"[",
"0",
"]",
".",
"isalpha",
"(",
")",
":",
"# These two cases are necessary in order to get a regex pattern",
"# starting with '[xX]' and not '[Xx]'. This allows to check for",
"# colliding regex afterward... | Return a regex pattern with the first letter.
Accepts both lowercase and uppercase. | [
"Return",
"a",
"regex",
"pattern",
"with",
"the",
"first",
"letter",
"."
] | train | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L693-L706 |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/reader.py | _convert_punctuation | def _convert_punctuation(punctuation, conversion_table):
"""Return a regular expression for a punctuation string."""
if punctuation in conversion_table:
return conversion_table[punctuation]
return re.escape(punctuation) | python | def _convert_punctuation(punctuation, conversion_table):
"""Return a regular expression for a punctuation string."""
if punctuation in conversion_table:
return conversion_table[punctuation]
return re.escape(punctuation) | [
"def",
"_convert_punctuation",
"(",
"punctuation",
",",
"conversion_table",
")",
":",
"if",
"punctuation",
"in",
"conversion_table",
":",
"return",
"conversion_table",
"[",
"punctuation",
"]",
"return",
"re",
".",
"escape",
"(",
"punctuation",
")"
] | Return a regular expression for a punctuation string. | [
"Return",
"a",
"regular",
"expression",
"for",
"a",
"punctuation",
"string",
"."
] | train | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L709-L713 |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/reader.py | _convert_word | def _convert_word(word):
"""Return the plural form of the word if it exists.
Otherwise return the word itself.
"""
out = None
# Acronyms.
if word.isupper():
out = word + "s?"
# Proper nouns or word with digits.
elif word.istitle():
out = word + "('?s)?"
elif _contai... | python | def _convert_word(word):
"""Return the plural form of the word if it exists.
Otherwise return the word itself.
"""
out = None
# Acronyms.
if word.isupper():
out = word + "s?"
# Proper nouns or word with digits.
elif word.istitle():
out = word + "('?s)?"
elif _contai... | [
"def",
"_convert_word",
"(",
"word",
")",
":",
"out",
"=",
"None",
"# Acronyms.",
"if",
"word",
".",
"isupper",
"(",
")",
":",
"out",
"=",
"word",
"+",
"\"s?\"",
"# Proper nouns or word with digits.",
"elif",
"word",
".",
"istitle",
"(",
")",
":",
"out",
... | Return the plural form of the word if it exists.
Otherwise return the word itself. | [
"Return",
"the",
"plural",
"form",
"of",
"the",
"word",
"if",
"it",
"exists",
"."
] | train | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L716-L765 |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/reader.py | _get_cache | def _get_cache(cache_file, source_file=None):
"""Get cached taxonomy using the cPickle module.
No check is done at that stage.
:param cache_file: full path to the file holding pickled data
:param source_file: if we discover the cache is obsolete, we
will build a new cache, therefore we need th... | python | def _get_cache(cache_file, source_file=None):
"""Get cached taxonomy using the cPickle module.
No check is done at that stage.
:param cache_file: full path to the file holding pickled data
:param source_file: if we discover the cache is obsolete, we
will build a new cache, therefore we need th... | [
"def",
"_get_cache",
"(",
"cache_file",
",",
"source_file",
"=",
"None",
")",
":",
"timer_start",
"=",
"time",
".",
"clock",
"(",
")",
"filestream",
"=",
"open",
"(",
"cache_file",
",",
"\"rb\"",
")",
"try",
":",
"cached_data",
"=",
"cPickle",
".",
"load... | Get cached taxonomy using the cPickle module.
No check is done at that stage.
:param cache_file: full path to the file holding pickled data
:param source_file: if we discover the cache is obsolete, we
will build a new cache, therefore we need the source path
of the cache
:return: (sing... | [
"Get",
"cached",
"taxonomy",
"using",
"the",
"cPickle",
"module",
"."
] | train | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L768-L832 |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/reader.py | _get_cache_path | def _get_cache_path(source_file):
"""Return the path where the cache should be written/located.
:param onto_name: name of the ontology or the full path
:return: string, abs path to the cache file
"""
local_name = os.path.basename(source_file)
cache_name = local_name + ".db"
cache_dir = os.p... | python | def _get_cache_path(source_file):
"""Return the path where the cache should be written/located.
:param onto_name: name of the ontology or the full path
:return: string, abs path to the cache file
"""
local_name = os.path.basename(source_file)
cache_name = local_name + ".db"
cache_dir = os.p... | [
"def",
"_get_cache_path",
"(",
"source_file",
")",
":",
"local_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"source_file",
")",
"cache_name",
"=",
"local_name",
"+",
"\".db\"",
"cache_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"current_app",
"... | Return the path where the cache should be written/located.
:param onto_name: name of the ontology or the full path
:return: string, abs path to the cache file | [
"Return",
"the",
"path",
"where",
"the",
"cache",
"should",
"be",
"written",
"/",
"located",
"."
] | train | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L835-L848 |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/reader.py | _get_last_modification_date | def _get_last_modification_date(url):
"""Get the last modification date of the ontology."""
request = requests.head(url)
date_string = request.headers["last-modified"]
parsed = time.strptime(date_string, "%a, %d %b %Y %H:%M:%S %Z")
return datetime(*(parsed)[0:6]) | python | def _get_last_modification_date(url):
"""Get the last modification date of the ontology."""
request = requests.head(url)
date_string = request.headers["last-modified"]
parsed = time.strptime(date_string, "%a, %d %b %Y %H:%M:%S %Z")
return datetime(*(parsed)[0:6]) | [
"def",
"_get_last_modification_date",
"(",
"url",
")",
":",
"request",
"=",
"requests",
".",
"head",
"(",
"url",
")",
"date_string",
"=",
"request",
".",
"headers",
"[",
"\"last-modified\"",
"]",
"parsed",
"=",
"time",
".",
"strptime",
"(",
"date_string",
",... | Get the last modification date of the ontology. | [
"Get",
"the",
"last",
"modification",
"date",
"of",
"the",
"ontology",
"."
] | train | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L851-L856 |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/reader.py | _download_ontology | def _download_ontology(url, local_file):
"""Download the ontology and stores it in CLASSIFIER_WORKDIR."""
current_app.logger.debug(
"Copying remote ontology '%s' to file '%s'." % (url, local_file)
)
try:
request = requests.get(url, stream=True)
if request.status_code == 200:
... | python | def _download_ontology(url, local_file):
"""Download the ontology and stores it in CLASSIFIER_WORKDIR."""
current_app.logger.debug(
"Copying remote ontology '%s' to file '%s'." % (url, local_file)
)
try:
request = requests.get(url, stream=True)
if request.status_code == 200:
... | [
"def",
"_download_ontology",
"(",
"url",
",",
"local_file",
")",
":",
"current_app",
".",
"logger",
".",
"debug",
"(",
"\"Copying remote ontology '%s' to file '%s'.\"",
"%",
"(",
"url",
",",
"local_file",
")",
")",
"try",
":",
"request",
"=",
"requests",
".",
... | Download the ontology and stores it in CLASSIFIER_WORKDIR. | [
"Download",
"the",
"ontology",
"and",
"stores",
"it",
"in",
"CLASSIFIER_WORKDIR",
"."
] | train | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L859-L875 |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/reader.py | _get_searchable_regex | def _get_searchable_regex(basic=None, hidden=None):
"""Return the searchable regular expressions for the single keyword."""
# Hidden labels are used to store regular expressions.
basic = basic or []
hidden = hidden or []
hidden_regex_dict = {}
for hidden_label in hidden:
if _is_regex(hi... | python | def _get_searchable_regex(basic=None, hidden=None):
"""Return the searchable regular expressions for the single keyword."""
# Hidden labels are used to store regular expressions.
basic = basic or []
hidden = hidden or []
hidden_regex_dict = {}
for hidden_label in hidden:
if _is_regex(hi... | [
"def",
"_get_searchable_regex",
"(",
"basic",
"=",
"None",
",",
"hidden",
"=",
"None",
")",
":",
"# Hidden labels are used to store regular expressions.",
"basic",
"=",
"basic",
"or",
"[",
"]",
"hidden",
"=",
"hidden",
"or",
"[",
"]",
"hidden_regex_dict",
"=",
"... | Return the searchable regular expressions for the single keyword. | [
"Return",
"the",
"searchable",
"regular",
"expressions",
"for",
"the",
"single",
"keyword",
"."
] | train | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L878-L911 |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/reader.py | _get_regex_pattern | def _get_regex_pattern(label):
"""Return a regular expression of the label.
This takes care of plural and different kinds of separators.
"""
parts = _split_by_punctuation.split(label)
for index, part in enumerate(parts):
if index % 2 == 0:
# Word
if not parts[index]... | python | def _get_regex_pattern(label):
"""Return a regular expression of the label.
This takes care of plural and different kinds of separators.
"""
parts = _split_by_punctuation.split(label)
for index, part in enumerate(parts):
if index % 2 == 0:
# Word
if not parts[index]... | [
"def",
"_get_regex_pattern",
"(",
"label",
")",
":",
"parts",
"=",
"_split_by_punctuation",
".",
"split",
"(",
"label",
")",
"for",
"index",
",",
"part",
"in",
"enumerate",
"(",
"parts",
")",
":",
"if",
"index",
"%",
"2",
"==",
"0",
":",
"# Word",
"if"... | Return a regular expression of the label.
This takes care of plural and different kinds of separators. | [
"Return",
"a",
"regular",
"expression",
"of",
"the",
"label",
"."
] | train | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L914-L941 |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/reader.py | check_taxonomy | def check_taxonomy(taxonomy):
"""Check the consistency of the taxonomy.
Outputs a list of errors and warnings.
"""
current_app.logger.info(
"Building graph with Python RDFLib version %s" %
rdflib.__version__
)
store = rdflib.ConjunctiveGraph()
store.parse(taxonomy)
cur... | python | def check_taxonomy(taxonomy):
"""Check the consistency of the taxonomy.
Outputs a list of errors and warnings.
"""
current_app.logger.info(
"Building graph with Python RDFLib version %s" %
rdflib.__version__
)
store = rdflib.ConjunctiveGraph()
store.parse(taxonomy)
cur... | [
"def",
"check_taxonomy",
"(",
"taxonomy",
")",
":",
"current_app",
".",
"logger",
".",
"info",
"(",
"\"Building graph with Python RDFLib version %s\"",
"%",
"rdflib",
".",
"__version__",
")",
"store",
"=",
"rdflib",
".",
"ConjunctiveGraph",
"(",
")",
"store",
".",... | Check the consistency of the taxonomy.
Outputs a list of errors and warnings. | [
"Check",
"the",
"consistency",
"of",
"the",
"taxonomy",
"."
] | train | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L949-L1159 |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/reader.py | KeywordToken.refreshCompositeOf | def refreshCompositeOf(self, single_keywords, composite_keywords,
store=None, namespace=None):
"""Re-check sub-parts of this keyword.
This should be called after the whole RDF was processed, because
it is using a cache of single keywords and if that
one is inc... | python | def refreshCompositeOf(self, single_keywords, composite_keywords,
store=None, namespace=None):
"""Re-check sub-parts of this keyword.
This should be called after the whole RDF was processed, because
it is using a cache of single keywords and if that
one is inc... | [
"def",
"refreshCompositeOf",
"(",
"self",
",",
"single_keywords",
",",
"composite_keywords",
",",
"store",
"=",
"None",
",",
"namespace",
"=",
"None",
")",
":",
"def",
"_get_ckw_components",
"(",
"new_vals",
",",
"label",
")",
":",
"if",
"label",
"in",
"sing... | Re-check sub-parts of this keyword.
This should be called after the whole RDF was processed, because
it is using a cache of single keywords and if that
one is incomplete, you will not identify all parts. | [
"Re",
"-",
"check",
"sub",
"-",
"parts",
"of",
"this",
"keyword",
"."
] | train | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L428-L468 |
TAPPGuild/sqlalchemy-models | sqlalchemy_models/util.py | create_user | def create_user(username, key, session):
"""
Create a User and UserKey record in the session provided.
Will rollback both records if any issues are encountered.
After rollback, Exception is re-raised.
:param username: The username for the User
:param key: The public key to associate with this U... | python | def create_user(username, key, session):
"""
Create a User and UserKey record in the session provided.
Will rollback both records if any issues are encountered.
After rollback, Exception is re-raised.
:param username: The username for the User
:param key: The public key to associate with this U... | [
"def",
"create_user",
"(",
"username",
",",
"key",
",",
"session",
")",
":",
"try",
":",
"user",
"=",
"um",
".",
"User",
"(",
"username",
"=",
"username",
")",
"session",
".",
"add",
"(",
"user",
")",
"session",
".",
"commit",
"(",
")",
"except",
"... | Create a User and UserKey record in the session provided.
Will rollback both records if any issues are encountered.
After rollback, Exception is re-raised.
:param username: The username for the User
:param key: The public key to associate with this User
:param session: The sqlalchemy session to use... | [
"Create",
"a",
"User",
"and",
"UserKey",
"record",
"in",
"the",
"session",
"provided",
".",
"Will",
"rollback",
"both",
"records",
"if",
"any",
"issues",
"are",
"encountered",
".",
"After",
"rollback",
"Exception",
"is",
"re",
"-",
"raised",
"."
] | train | https://github.com/TAPPGuild/sqlalchemy-models/blob/75988a23bdd98e79af8b8b0711c657c79b2f8eac/sqlalchemy_models/util.py#L14-L44 |
TAPPGuild/sqlalchemy-models | sqlalchemy_models/util.py | build_definitions | def build_definitions(dpath="sqlalchemy_models/_definitions.json"):
"""
Nasty hacky method of ensuring LedgerAmounts are rendered as floats in json schemas, instead of integers.
:param str dpath: The path of the definitions file to create as part of the build process.
"""
command.run(AlsoChildrenWa... | python | def build_definitions(dpath="sqlalchemy_models/_definitions.json"):
"""
Nasty hacky method of ensuring LedgerAmounts are rendered as floats in json schemas, instead of integers.
:param str dpath: The path of the definitions file to create as part of the build process.
"""
command.run(AlsoChildrenWa... | [
"def",
"build_definitions",
"(",
"dpath",
"=",
"\"sqlalchemy_models/_definitions.json\"",
")",
":",
"command",
".",
"run",
"(",
"AlsoChildrenWalker",
",",
"module",
"=",
"todo",
",",
"outdir",
"=",
"\"sqlalchemy_models\"",
",",
"definition_name",
"=",
"\"_definitions.... | Nasty hacky method of ensuring LedgerAmounts are rendered as floats in json schemas, instead of integers.
:param str dpath: The path of the definitions file to create as part of the build process. | [
"Nasty",
"hacky",
"method",
"of",
"ensuring",
"LedgerAmounts",
"are",
"rendered",
"as",
"floats",
"in",
"json",
"schemas",
"instead",
"of",
"integers",
"."
] | train | https://github.com/TAPPGuild/sqlalchemy-models/blob/75988a23bdd98e79af8b8b0711c657c79b2f8eac/sqlalchemy_models/util.py#L47-L70 |
TAPPGuild/sqlalchemy-models | sqlalchemy_models/util.py | multiply_tickers | def multiply_tickers(t1, t2):
"""
Multiply two tickers. Quote currency of t1 must match base currency of t2.
:param Ticker t1: Ticker # 1
:param Ticker t2: Ticker # 2
"""
t1pair = t1.market.split("_")
t2pair = t2.market.split("_")
assert t1pair[1] == t2pair[0]
market = t1pair[0] + "... | python | def multiply_tickers(t1, t2):
"""
Multiply two tickers. Quote currency of t1 must match base currency of t2.
:param Ticker t1: Ticker # 1
:param Ticker t2: Ticker # 2
"""
t1pair = t1.market.split("_")
t2pair = t2.market.split("_")
assert t1pair[1] == t2pair[0]
market = t1pair[0] + "... | [
"def",
"multiply_tickers",
"(",
"t1",
",",
"t2",
")",
":",
"t1pair",
"=",
"t1",
".",
"market",
".",
"split",
"(",
"\"_\"",
")",
"t2pair",
"=",
"t2",
".",
"market",
".",
"split",
"(",
"\"_\"",
")",
"assert",
"t1pair",
"[",
"1",
"]",
"==",
"t2pair",
... | Multiply two tickers. Quote currency of t1 must match base currency of t2.
:param Ticker t1: Ticker # 1
:param Ticker t2: Ticker # 2 | [
"Multiply",
"two",
"tickers",
".",
"Quote",
"currency",
"of",
"t1",
"must",
"match",
"base",
"currency",
"of",
"t2",
"."
] | train | https://github.com/TAPPGuild/sqlalchemy-models/blob/75988a23bdd98e79af8b8b0711c657c79b2f8eac/sqlalchemy_models/util.py#L79-L96 |
thomasleese/mo | mo/cli.py | parse_variables | def parse_variables(args):
"""
Parse variables as passed on the command line.
Returns
-------
dict
Mapping variable name to the value.
"""
if args is None:
return {}
def parse_variable(string):
tokens = string.split('=')
name = tokens[0]
value =... | python | def parse_variables(args):
"""
Parse variables as passed on the command line.
Returns
-------
dict
Mapping variable name to the value.
"""
if args is None:
return {}
def parse_variable(string):
tokens = string.split('=')
name = tokens[0]
value =... | [
"def",
"parse_variables",
"(",
"args",
")",
":",
"if",
"args",
"is",
"None",
":",
"return",
"{",
"}",
"def",
"parse_variable",
"(",
"string",
")",
":",
"tokens",
"=",
"string",
".",
"split",
"(",
"'='",
")",
"name",
"=",
"tokens",
"[",
"0",
"]",
"v... | Parse variables as passed on the command line.
Returns
-------
dict
Mapping variable name to the value. | [
"Parse",
"variables",
"as",
"passed",
"on",
"the",
"command",
"line",
"."
] | train | https://github.com/thomasleese/mo/blob/b757f52b42e51ad19c14724ceb7c5db5d52abaea/mo/cli.py#L16-L38 |
thomasleese/mo | mo/cli.py | main | def main():
"""Run the CLI."""
args = parse_args()
frontend = available_frontends[args.frontend]()
frontend.begin()
try:
for event in run(args):
frontend.output(event)
finally:
frontend.end() | python | def main():
"""Run the CLI."""
args = parse_args()
frontend = available_frontends[args.frontend]()
frontend.begin()
try:
for event in run(args):
frontend.output(event)
finally:
frontend.end() | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"parse_args",
"(",
")",
"frontend",
"=",
"available_frontends",
"[",
"args",
".",
"frontend",
"]",
"(",
")",
"frontend",
".",
"begin",
"(",
")",
"try",
":",
"for",
"event",
"in",
"run",
"(",
"args",
")",
"... | Run the CLI. | [
"Run",
"the",
"CLI",
"."
] | train | https://github.com/thomasleese/mo/blob/b757f52b42e51ad19c14724ceb7c5db5d52abaea/mo/cli.py#L74-L87 |
ael-code/pyFsdb | fsdb/fsdb.py | Fsdb._calc_digest | def _calc_digest(self, origin):
"""calculate digest for the given file or readable/seekable object
Args:
origin -- could be the path of a file or a readable/seekable object ( fileobject, stream, stringIO...)
Returns:
String rapresenting the digest for the given origin
... | python | def _calc_digest(self, origin):
"""calculate digest for the given file or readable/seekable object
Args:
origin -- could be the path of a file or a readable/seekable object ( fileobject, stream, stringIO...)
Returns:
String rapresenting the digest for the given origin
... | [
"def",
"_calc_digest",
"(",
"self",
",",
"origin",
")",
":",
"if",
"hasattr",
"(",
"origin",
",",
"'read'",
")",
"and",
"hasattr",
"(",
"origin",
",",
"'seek'",
")",
":",
"pos",
"=",
"origin",
".",
"tell",
"(",
")",
"digest",
"=",
"hashtools",
".",
... | calculate digest for the given file or readable/seekable object
Args:
origin -- could be the path of a file or a readable/seekable object ( fileobject, stream, stringIO...)
Returns:
String rapresenting the digest for the given origin | [
"calculate",
"digest",
"for",
"the",
"given",
"file",
"or",
"readable",
"/",
"seekable",
"object"
] | train | https://github.com/ael-code/pyFsdb/blob/de33a0d41373307cb32cdd7ba1991b85ff495ee3/fsdb/fsdb.py#L94-L108 |
ael-code/pyFsdb | fsdb/fsdb.py | Fsdb._copy_content | def _copy_content(self, origin, dstPath):
"""copy the content of origin into dstPath
Due to concurrency problem, the content will be first
copied to a temporary file alongside `dstPath` and
then atomically moved to `dstPath`
"""
if hasattr(origin, 'read'):
... | python | def _copy_content(self, origin, dstPath):
"""copy the content of origin into dstPath
Due to concurrency problem, the content will be first
copied to a temporary file alongside `dstPath` and
then atomically moved to `dstPath`
"""
if hasattr(origin, 'read'):
... | [
"def",
"_copy_content",
"(",
"self",
",",
"origin",
",",
"dstPath",
")",
":",
"if",
"hasattr",
"(",
"origin",
",",
"'read'",
")",
":",
"copy_content",
"(",
"origin",
",",
"dstPath",
",",
"self",
".",
"BLOCK_SIZE",
",",
"self",
".",
"_conf",
"[",
"'fmod... | copy the content of origin into dstPath
Due to concurrency problem, the content will be first
copied to a temporary file alongside `dstPath` and
then atomically moved to `dstPath` | [
"copy",
"the",
"content",
"of",
"origin",
"into",
"dstPath"
] | train | https://github.com/ael-code/pyFsdb/blob/de33a0d41373307cb32cdd7ba1991b85ff495ee3/fsdb/fsdb.py#L110-L124 |
ael-code/pyFsdb | fsdb/fsdb.py | Fsdb._makedirs | def _makedirs(self, path):
"""Make folders recursively for the given path and
check read and write permission on the path
Args:
path -- path to the leaf folder
"""
try:
oldmask = os.umask(0)
os.makedirs(path, self._conf['dmode'])
... | python | def _makedirs(self, path):
"""Make folders recursively for the given path and
check read and write permission on the path
Args:
path -- path to the leaf folder
"""
try:
oldmask = os.umask(0)
os.makedirs(path, self._conf['dmode'])
... | [
"def",
"_makedirs",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"oldmask",
"=",
"os",
".",
"umask",
"(",
"0",
")",
"os",
".",
"makedirs",
"(",
"path",
",",
"self",
".",
"_conf",
"[",
"'dmode'",
"]",
")",
"os",
".",
"umask",
"(",
"oldmask",
... | Make folders recursively for the given path and
check read and write permission on the path
Args:
path -- path to the leaf folder | [
"Make",
"folders",
"recursively",
"for",
"the",
"given",
"path",
"and",
"check",
"read",
"and",
"write",
"permission",
"on",
"the",
"path",
"Args",
":",
"path",
"--",
"path",
"to",
"the",
"leaf",
"folder"
] | train | https://github.com/ael-code/pyFsdb/blob/de33a0d41373307cb32cdd7ba1991b85ff495ee3/fsdb/fsdb.py#L134-L154 |
ael-code/pyFsdb | fsdb/fsdb.py | Fsdb.add | def add(self, origin):
"""Add new element to fsdb.
Args:
origin -- could be the path of a file or a readable/seekable object ( fileobject, stream, stringIO...)
Returns:
String rapresenting the digest of the file
"""
digest = self._calc_digest(origin)
... | python | def add(self, origin):
"""Add new element to fsdb.
Args:
origin -- could be the path of a file or a readable/seekable object ( fileobject, stream, stringIO...)
Returns:
String rapresenting the digest of the file
"""
digest = self._calc_digest(origin)
... | [
"def",
"add",
"(",
"self",
",",
"origin",
")",
":",
"digest",
"=",
"self",
".",
"_calc_digest",
"(",
"origin",
")",
"if",
"self",
".",
"exists",
"(",
"digest",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Added File: [{0}] ( Already exists. Skippi... | Add new element to fsdb.
Args:
origin -- could be the path of a file or a readable/seekable object ( fileobject, stream, stringIO...)
Returns:
String rapresenting the digest of the file | [
"Add",
"new",
"element",
"to",
"fsdb",
"."
] | train | https://github.com/ael-code/pyFsdb/blob/de33a0d41373307cb32cdd7ba1991b85ff495ee3/fsdb/fsdb.py#L156-L180 |
ael-code/pyFsdb | fsdb/fsdb.py | Fsdb.remove | def remove(self, digest):
"""Remove an existing file from fsdb.
File with the given digest will be removed from fsdb and
the directory tree will be cleaned (remove empty folders)
Args:
digest -- digest of the file to remove
"""
# remove file
abs... | python | def remove(self, digest):
"""Remove an existing file from fsdb.
File with the given digest will be removed from fsdb and
the directory tree will be cleaned (remove empty folders)
Args:
digest -- digest of the file to remove
"""
# remove file
abs... | [
"def",
"remove",
"(",
"self",
",",
"digest",
")",
":",
"# remove file",
"absPath",
"=",
"self",
".",
"get_file_path",
"(",
"digest",
")",
"os",
".",
"remove",
"(",
"absPath",
")",
"# clean directory tree",
"tmpPath",
"=",
"os",
".",
"path",
".",
"dirname",... | Remove an existing file from fsdb.
File with the given digest will be removed from fsdb and
the directory tree will be cleaned (remove empty folders)
Args:
digest -- digest of the file to remove | [
"Remove",
"an",
"existing",
"file",
"from",
"fsdb",
".",
"File",
"with",
"the",
"given",
"digest",
"will",
"be",
"removed",
"from",
"fsdb",
"and",
"the",
"directory",
"tree",
"will",
"be",
"cleaned",
"(",
"remove",
"empty",
"folders",
")",
"Args",
":",
"... | train | https://github.com/ael-code/pyFsdb/blob/de33a0d41373307cb32cdd7ba1991b85ff495ee3/fsdb/fsdb.py#L182-L203 |
ael-code/pyFsdb | fsdb/fsdb.py | Fsdb.exists | def exists(self, digest):
"""Check file existence in fsdb
Returns:
True if file exists under this instance of fsdb, false otherwise
"""
if not isinstance(digest, string_types):
raise TypeError("digest must be a string")
return os.path.isfile(self.get_fi... | python | def exists(self, digest):
"""Check file existence in fsdb
Returns:
True if file exists under this instance of fsdb, false otherwise
"""
if not isinstance(digest, string_types):
raise TypeError("digest must be a string")
return os.path.isfile(self.get_fi... | [
"def",
"exists",
"(",
"self",
",",
"digest",
")",
":",
"if",
"not",
"isinstance",
"(",
"digest",
",",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"\"digest must be a string\"",
")",
"return",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"... | Check file existence in fsdb
Returns:
True if file exists under this instance of fsdb, false otherwise | [
"Check",
"file",
"existence",
"in",
"fsdb"
] | train | https://github.com/ael-code/pyFsdb/blob/de33a0d41373307cb32cdd7ba1991b85ff495ee3/fsdb/fsdb.py#L205-L213 |
ael-code/pyFsdb | fsdb/fsdb.py | Fsdb.get_file_path | def get_file_path(self, digest):
"""Retrieve the absolute path to the file with the given digest
Args:
digest -- digest of the file
Returns:
String rapresenting the absolute path of the file
"""
relPath = Fsdb.generate_tree_path(digest, self._conf['de... | python | def get_file_path(self, digest):
"""Retrieve the absolute path to the file with the given digest
Args:
digest -- digest of the file
Returns:
String rapresenting the absolute path of the file
"""
relPath = Fsdb.generate_tree_path(digest, self._conf['de... | [
"def",
"get_file_path",
"(",
"self",
",",
"digest",
")",
":",
"relPath",
"=",
"Fsdb",
".",
"generate_tree_path",
"(",
"digest",
",",
"self",
".",
"_conf",
"[",
"'depth'",
"]",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"fsdbRoot",... | Retrieve the absolute path to the file with the given digest
Args:
digest -- digest of the file
Returns:
String rapresenting the absolute path of the file | [
"Retrieve",
"the",
"absolute",
"path",
"to",
"the",
"file",
"with",
"the",
"given",
"digest"
] | train | https://github.com/ael-code/pyFsdb/blob/de33a0d41373307cb32cdd7ba1991b85ff495ee3/fsdb/fsdb.py#L215-L224 |
ael-code/pyFsdb | fsdb/fsdb.py | Fsdb.check | def check(self, digest):
"""Check the integrity of the file with the given digest
Args:
digest -- digest of the file to check
Returns:
True if the file is not corrupted
"""
path = self.get_file_path(digest)
if self._calc_digest(path) != digest... | python | def check(self, digest):
"""Check the integrity of the file with the given digest
Args:
digest -- digest of the file to check
Returns:
True if the file is not corrupted
"""
path = self.get_file_path(digest)
if self._calc_digest(path) != digest... | [
"def",
"check",
"(",
"self",
",",
"digest",
")",
":",
"path",
"=",
"self",
".",
"get_file_path",
"(",
"digest",
")",
"if",
"self",
".",
"_calc_digest",
"(",
"path",
")",
"!=",
"digest",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"found corrupte... | Check the integrity of the file with the given digest
Args:
digest -- digest of the file to check
Returns:
True if the file is not corrupted | [
"Check",
"the",
"integrity",
"of",
"the",
"file",
"with",
"the",
"given",
"digest"
] | train | https://github.com/ael-code/pyFsdb/blob/de33a0d41373307cb32cdd7ba1991b85ff495ee3/fsdb/fsdb.py#L226-L238 |
ael-code/pyFsdb | fsdb/fsdb.py | Fsdb.size | def size(self):
"""Return the total size in bytes of all the files handled by this instance of fsdb.
Fsdb does not use auxiliary data structure, so this function could be expensive.
Look at _iter_over_paths() functions for more details.
"""
tot = 0
for p in self.__iter__... | python | def size(self):
"""Return the total size in bytes of all the files handled by this instance of fsdb.
Fsdb does not use auxiliary data structure, so this function could be expensive.
Look at _iter_over_paths() functions for more details.
"""
tot = 0
for p in self.__iter__... | [
"def",
"size",
"(",
"self",
")",
":",
"tot",
"=",
"0",
"for",
"p",
"in",
"self",
".",
"__iter__",
"(",
"overPath",
"=",
"True",
")",
":",
"tot",
"+=",
"os",
".",
"path",
".",
"getsize",
"(",
"p",
")",
"return",
"tot"
] | Return the total size in bytes of all the files handled by this instance of fsdb.
Fsdb does not use auxiliary data structure, so this function could be expensive.
Look at _iter_over_paths() functions for more details. | [
"Return",
"the",
"total",
"size",
"in",
"bytes",
"of",
"all",
"the",
"files",
"handled",
"by",
"this",
"instance",
"of",
"fsdb",
"."
] | train | https://github.com/ael-code/pyFsdb/blob/de33a0d41373307cb32cdd7ba1991b85ff495ee3/fsdb/fsdb.py#L246-L255 |
ael-code/pyFsdb | fsdb/fsdb.py | Fsdb.generate_tree_path | def generate_tree_path(fileDigest, depth):
"""Generate a relative path from the given fileDigest
relative path has a numbers of directories levels according to @depth
Args:
fileDigest -- digest for which the relative path will be generate
depth -- number of levels t... | python | def generate_tree_path(fileDigest, depth):
"""Generate a relative path from the given fileDigest
relative path has a numbers of directories levels according to @depth
Args:
fileDigest -- digest for which the relative path will be generate
depth -- number of levels t... | [
"def",
"generate_tree_path",
"(",
"fileDigest",
",",
"depth",
")",
":",
"if",
"(",
"depth",
"<",
"0",
")",
":",
"raise",
"Exception",
"(",
"\"depth level can not be negative\"",
")",
"if",
"(",
"os",
".",
"path",
".",
"split",
"(",
"fileDigest",
")",
"[",
... | Generate a relative path from the given fileDigest
relative path has a numbers of directories levels according to @depth
Args:
fileDigest -- digest for which the relative path will be generate
depth -- number of levels to use in relative path generation
Returns:
... | [
"Generate",
"a",
"relative",
"path",
"from",
"the",
"given",
"fileDigest",
"relative",
"path",
"has",
"a",
"numbers",
"of",
"directories",
"levels",
"according",
"to",
"@depth"
] | train | https://github.com/ael-code/pyFsdb/blob/de33a0d41373307cb32cdd7ba1991b85ff495ee3/fsdb/fsdb.py#L305-L332 |
inveniosoftware-contrib/invenio-classifier | requirements.py | parse_set | def parse_set(string):
"""Parse set from comma separated string."""
string = string.strip()
if string:
return set(string.split(","))
else:
return set() | python | def parse_set(string):
"""Parse set from comma separated string."""
string = string.strip()
if string:
return set(string.split(","))
else:
return set() | [
"def",
"parse_set",
"(",
"string",
")",
":",
"string",
"=",
"string",
".",
"strip",
"(",
")",
"if",
"string",
":",
"return",
"set",
"(",
"string",
".",
"split",
"(",
"\",\"",
")",
")",
"else",
":",
"return",
"set",
"(",
")"
] | Parse set from comma separated string. | [
"Parse",
"set",
"from",
"comma",
"separated",
"string",
"."
] | train | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/requirements.py#L40-L46 |
inveniosoftware-contrib/invenio-classifier | requirements.py | minver_error | def minver_error(pkg_name):
"""Report error about missing minimum version constraint and exit."""
print(
'ERROR: specify minimal version of "{}" using '
'">=" or "=="'.format(pkg_name),
file=sys.stderr
)
sys.exit(1) | python | def minver_error(pkg_name):
"""Report error about missing minimum version constraint and exit."""
print(
'ERROR: specify minimal version of "{}" using '
'">=" or "=="'.format(pkg_name),
file=sys.stderr
)
sys.exit(1) | [
"def",
"minver_error",
"(",
"pkg_name",
")",
":",
"print",
"(",
"'ERROR: specify minimal version of \"{}\" using '",
"'\">=\" or \"==\"'",
".",
"format",
"(",
"pkg_name",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | Report error about missing minimum version constraint and exit. | [
"Report",
"error",
"about",
"missing",
"minimum",
"version",
"constraint",
"and",
"exit",
"."
] | train | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/requirements.py#L49-L56 |
inveniosoftware-contrib/invenio-classifier | requirements.py | parse_pip_file | def parse_pip_file(path):
"""Parse pip requirements file."""
# requirement lines sorted by importance
# also collect other pip commands
rdev = dict()
rnormal = []
stuff = []
try:
with open(path) as f:
for line in f:
line = line.strip()
# ... | python | def parse_pip_file(path):
"""Parse pip requirements file."""
# requirement lines sorted by importance
# also collect other pip commands
rdev = dict()
rnormal = []
stuff = []
try:
with open(path) as f:
for line in f:
line = line.strip()
# ... | [
"def",
"parse_pip_file",
"(",
"path",
")",
":",
"# requirement lines sorted by importance",
"# also collect other pip commands",
"rdev",
"=",
"dict",
"(",
")",
"rnormal",
"=",
"[",
"]",
"stuff",
"=",
"[",
"]",
"try",
":",
"with",
"open",
"(",
"path",
")",
"as"... | Parse pip requirements file. | [
"Parse",
"pip",
"requirements",
"file",
"."
] | train | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/requirements.py#L59-L101 |
wjszlachta/ig-rest-client | ig_rest_client/__init__.py | AbstractIgRestSession.get | def get(self, endpoint: str, **kwargs) -> dict:
"""HTTP GET operation to API endpoint."""
return self._request('GET', endpoint, **kwargs) | python | def get(self, endpoint: str, **kwargs) -> dict:
"""HTTP GET operation to API endpoint."""
return self._request('GET', endpoint, **kwargs) | [
"def",
"get",
"(",
"self",
",",
"endpoint",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
"->",
"dict",
":",
"return",
"self",
".",
"_request",
"(",
"'GET'",
",",
"endpoint",
",",
"*",
"*",
"kwargs",
")"
] | HTTP GET operation to API endpoint. | [
"HTTP",
"GET",
"operation",
"to",
"API",
"endpoint",
"."
] | train | https://github.com/wjszlachta/ig-rest-client/blob/2a1fb70bfa2c7b6be5109fd881e0844c1b8f1303/ig_rest_client/__init__.py#L25-L28 |
wjszlachta/ig-rest-client | ig_rest_client/__init__.py | AbstractIgRestSession.post | def post(self, endpoint: str, **kwargs) -> dict:
"""HTTP POST operation to API endpoint."""
return self._request('POST', endpoint, **kwargs) | python | def post(self, endpoint: str, **kwargs) -> dict:
"""HTTP POST operation to API endpoint."""
return self._request('POST', endpoint, **kwargs) | [
"def",
"post",
"(",
"self",
",",
"endpoint",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
"->",
"dict",
":",
"return",
"self",
".",
"_request",
"(",
"'POST'",
",",
"endpoint",
",",
"*",
"*",
"kwargs",
")"
] | HTTP POST operation to API endpoint. | [
"HTTP",
"POST",
"operation",
"to",
"API",
"endpoint",
"."
] | train | https://github.com/wjszlachta/ig-rest-client/blob/2a1fb70bfa2c7b6be5109fd881e0844c1b8f1303/ig_rest_client/__init__.py#L30-L33 |
wjszlachta/ig-rest-client | ig_rest_client/__init__.py | AbstractIgRestSession.put | def put(self, endpoint: str, **kwargs) -> dict:
"""HTTP PUT operation to API endpoint."""
return self._request('PUT', endpoint, **kwargs) | python | def put(self, endpoint: str, **kwargs) -> dict:
"""HTTP PUT operation to API endpoint."""
return self._request('PUT', endpoint, **kwargs) | [
"def",
"put",
"(",
"self",
",",
"endpoint",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
"->",
"dict",
":",
"return",
"self",
".",
"_request",
"(",
"'PUT'",
",",
"endpoint",
",",
"*",
"*",
"kwargs",
")"
] | HTTP PUT operation to API endpoint. | [
"HTTP",
"PUT",
"operation",
"to",
"API",
"endpoint",
"."
] | train | https://github.com/wjszlachta/ig-rest-client/blob/2a1fb70bfa2c7b6be5109fd881e0844c1b8f1303/ig_rest_client/__init__.py#L35-L38 |
wjszlachta/ig-rest-client | ig_rest_client/__init__.py | AbstractIgRestSession.delete | def delete(self, endpoint: str, **kwargs) -> dict:
"""HTTP DELETE operation to API endpoint."""
return self._request('DELETE', endpoint, **kwargs) | python | def delete(self, endpoint: str, **kwargs) -> dict:
"""HTTP DELETE operation to API endpoint."""
return self._request('DELETE', endpoint, **kwargs) | [
"def",
"delete",
"(",
"self",
",",
"endpoint",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
"->",
"dict",
":",
"return",
"self",
".",
"_request",
"(",
"'DELETE'",
",",
"endpoint",
",",
"*",
"*",
"kwargs",
")"
] | HTTP DELETE operation to API endpoint. | [
"HTTP",
"DELETE",
"operation",
"to",
"API",
"endpoint",
"."
] | train | https://github.com/wjszlachta/ig-rest-client/blob/2a1fb70bfa2c7b6be5109fd881e0844c1b8f1303/ig_rest_client/__init__.py#L40-L43 |
jf-parent/brome | brome/core/selector.py | Selector.resolve_selector | def resolve_selector(self):
"""Resolve the selector variable in place
"""
effective_selector_list = []
for current_selector in self._selector_list:
# INLINE SELECTOR
if self.get_type(current_selector) != 'selector_variable':
effective_selector_li... | python | def resolve_selector(self):
"""Resolve the selector variable in place
"""
effective_selector_list = []
for current_selector in self._selector_list:
# INLINE SELECTOR
if self.get_type(current_selector) != 'selector_variable':
effective_selector_li... | [
"def",
"resolve_selector",
"(",
"self",
")",
":",
"effective_selector_list",
"=",
"[",
"]",
"for",
"current_selector",
"in",
"self",
".",
"_selector_list",
":",
"# INLINE SELECTOR",
"if",
"self",
".",
"get_type",
"(",
"current_selector",
")",
"!=",
"'selector_vari... | Resolve the selector variable in place | [
"Resolve",
"the",
"selector",
"variable",
"in",
"place"
] | train | https://github.com/jf-parent/brome/blob/784f45d96b83b703dd2181cb59ca8ea777c2510e/brome/core/selector.py#L105-L174 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.