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
RadhikaG/markdown-magic
magic/memeAPI.py
processMeme
def processMeme(imgParams): ''' Wrapper function for genMeme() and findMeme() imgParams may be a string of the following forms: * 'text0 | text1' * 'text0' * ' | text1' Fails gracefully when it can't find or generate a meme by returning an appropriate image url with the failure message on it. ''' template_id = findMeme(imgParams) if template_id is None: print("Couldn't find a suitable match for meme :(") return meme_not_supported # if template_id exists imgParams = imgParams.split('|') if len(imgParams) == 2 or len(imgParams) == 1: text0 = imgParams[0] if len(imgParams) == 2: text1 = imgParams[1] # Bottom text text1 exists elif len(imgParams) == 1: text1 = '' # No bottom text imgURL = genMeme(template_id, text0, text1) if imgURL is None: # Couldn't generate meme print("Couldn't generate meme :(") return couldnt_create_meme else: # Success! # print(imgURL) return imgURL elif len(imgParams) > 2: print("Too many lines of captions! Cannot create meme.") return too_many_lines elif len(imgParams) < 1: # No top text text0 exists print("Too few lines of captions! Cannot create meme.") return too_few_lines
python
def processMeme(imgParams): ''' Wrapper function for genMeme() and findMeme() imgParams may be a string of the following forms: * 'text0 | text1' * 'text0' * ' | text1' Fails gracefully when it can't find or generate a meme by returning an appropriate image url with the failure message on it. ''' template_id = findMeme(imgParams) if template_id is None: print("Couldn't find a suitable match for meme :(") return meme_not_supported # if template_id exists imgParams = imgParams.split('|') if len(imgParams) == 2 or len(imgParams) == 1: text0 = imgParams[0] if len(imgParams) == 2: text1 = imgParams[1] # Bottom text text1 exists elif len(imgParams) == 1: text1 = '' # No bottom text imgURL = genMeme(template_id, text0, text1) if imgURL is None: # Couldn't generate meme print("Couldn't generate meme :(") return couldnt_create_meme else: # Success! # print(imgURL) return imgURL elif len(imgParams) > 2: print("Too many lines of captions! Cannot create meme.") return too_many_lines elif len(imgParams) < 1: # No top text text0 exists print("Too few lines of captions! Cannot create meme.") return too_few_lines
[ "def", "processMeme", "(", "imgParams", ")", ":", "template_id", "=", "findMeme", "(", "imgParams", ")", "if", "template_id", "is", "None", ":", "print", "(", "\"Couldn't find a suitable match for meme :(\"", ")", "return", "meme_not_supported", "# if template_id exists...
Wrapper function for genMeme() and findMeme() imgParams may be a string of the following forms: * 'text0 | text1' * 'text0' * ' | text1' Fails gracefully when it can't find or generate a meme by returning an appropriate image url with the failure message on it.
[ "Wrapper", "function", "for", "genMeme", "()", "and", "findMeme", "()", "imgParams", "may", "be", "a", "string", "of", "the", "following", "forms", ":", "*", "text0", "|", "text1", "*", "text0", "*", "|", "text1" ]
train
https://github.com/RadhikaG/markdown-magic/blob/af99549b033269d861ea13f0541cb4f894057c47/magic/memeAPI.py#L105-L150
gwastro/pycbc-glue
pycbc_glue/ligolw/types.py
string_format_func
def string_format_func(s): """ Function used internally to format string data for output to XML. Escapes back-slashes and quotes, and wraps the resulting string in quotes. """ return u"\"%s\"" % unicode(s).replace(u"\\", u"\\\\").replace(u"\"", u"\\\"")
python
def string_format_func(s): """ Function used internally to format string data for output to XML. Escapes back-slashes and quotes, and wraps the resulting string in quotes. """ return u"\"%s\"" % unicode(s).replace(u"\\", u"\\\\").replace(u"\"", u"\\\"")
[ "def", "string_format_func", "(", "s", ")", ":", "return", "u\"\\\"%s\\\"\"", "%", "unicode", "(", "s", ")", ".", "replace", "(", "u\"\\\\\"", ",", "u\"\\\\\\\\\"", ")", ".", "replace", "(", "u\"\\\"\"", ",", "u\"\\\\\\\"\"", ")" ]
Function used internally to format string data for output to XML. Escapes back-slashes and quotes, and wraps the resulting string in quotes.
[ "Function", "used", "internally", "to", "format", "string", "data", "for", "output", "to", "XML", ".", "Escapes", "back", "-", "slashes", "and", "quotes", "and", "wraps", "the", "resulting", "string", "in", "quotes", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/types.py#L127-L133
gwastro/pycbc-glue
pycbc_glue/ligolw/types.py
mk_complex_format_func
def mk_complex_format_func(fmt): """ Function used internally to generate functions to format complex valued data. """ fmt = fmt + u"+i" + fmt def complex_format_func(z): return fmt % (z.real, z.imag) return complex_format_func
python
def mk_complex_format_func(fmt): """ Function used internally to generate functions to format complex valued data. """ fmt = fmt + u"+i" + fmt def complex_format_func(z): return fmt % (z.real, z.imag) return complex_format_func
[ "def", "mk_complex_format_func", "(", "fmt", ")", ":", "fmt", "=", "fmt", "+", "u\"+i\"", "+", "fmt", "def", "complex_format_func", "(", "z", ")", ":", "return", "fmt", "%", "(", "z", ".", "real", ",", "z", ".", "imag", ")", "return", "complex_format_f...
Function used internally to generate functions to format complex valued data.
[ "Function", "used", "internally", "to", "generate", "functions", "to", "format", "complex", "valued", "data", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/types.py#L144-L152
nickstenning/tagalog
tagalog/__init__.py
fields
def fields(iterable, fields=None): """ Add a set of fields to each item in ``iterable``. The set of fields have a key=value format. '@' are added to the front of each key. """ if not fields: for item in iterable: yield item prepared_fields = _prepare_fields(fields) for item in iterable: yield _process_fields(item, prepared_fields)
python
def fields(iterable, fields=None): """ Add a set of fields to each item in ``iterable``. The set of fields have a key=value format. '@' are added to the front of each key. """ if not fields: for item in iterable: yield item prepared_fields = _prepare_fields(fields) for item in iterable: yield _process_fields(item, prepared_fields)
[ "def", "fields", "(", "iterable", ",", "fields", "=", "None", ")", ":", "if", "not", "fields", ":", "for", "item", "in", "iterable", ":", "yield", "item", "prepared_fields", "=", "_prepare_fields", "(", "fields", ")", "for", "item", "in", "iterable", ":"...
Add a set of fields to each item in ``iterable``. The set of fields have a key=value format. '@' are added to the front of each key.
[ "Add", "a", "set", "of", "fields", "to", "each", "item", "in", "iterable", ".", "The", "set", "of", "fields", "have", "a", "key", "=", "value", "format", "." ]
train
https://github.com/nickstenning/tagalog/blob/c6847a957dc4f96836a5cf13c4eb664fccafaac2/tagalog/__init__.py#L29-L41
nickstenning/tagalog
tagalog/__init__.py
tag
def tag(iterable, tags=None, key='@tags'): """ Add tags to each dict or dict-like object in ``iterable``. Tags are added to each dict with a key set by ``key``. If a key already exists under the key given by ``key``, this function will attempt to ``.extend()``` it, but will fall back to replacing it in the event of error. """ if not tags: for item in iterable: yield item else: for item in iterable: yield _tag(item, tags, key)
python
def tag(iterable, tags=None, key='@tags'): """ Add tags to each dict or dict-like object in ``iterable``. Tags are added to each dict with a key set by ``key``. If a key already exists under the key given by ``key``, this function will attempt to ``.extend()``` it, but will fall back to replacing it in the event of error. """ if not tags: for item in iterable: yield item else: for item in iterable: yield _tag(item, tags, key)
[ "def", "tag", "(", "iterable", ",", "tags", "=", "None", ",", "key", "=", "'@tags'", ")", ":", "if", "not", "tags", ":", "for", "item", "in", "iterable", ":", "yield", "item", "else", ":", "for", "item", "in", "iterable", ":", "yield", "_tag", "(",...
Add tags to each dict or dict-like object in ``iterable``. Tags are added to each dict with a key set by ``key``. If a key already exists under the key given by ``key``, this function will attempt to ``.extend()``` it, but will fall back to replacing it in the event of error.
[ "Add", "tags", "to", "each", "dict", "or", "dict", "-", "like", "object", "in", "iterable", ".", "Tags", "are", "added", "to", "each", "dict", "with", "a", "key", "set", "by", "key", ".", "If", "a", "key", "already", "exists", "under", "the", "key", ...
train
https://github.com/nickstenning/tagalog/blob/c6847a957dc4f96836a5cf13c4eb664fccafaac2/tagalog/__init__.py#L58-L71
ebu/PlugIt
plugit/api.py
PlugItAPI._request
def _request(self, uri, params=None, postParams=None, verb='GET'): """Execute a request on the plugit api""" return getattr(requests, verb.lower())(self.url + uri, params=params, data=postParams, stream=True)
python
def _request(self, uri, params=None, postParams=None, verb='GET'): """Execute a request on the plugit api""" return getattr(requests, verb.lower())(self.url + uri, params=params, data=postParams, stream=True)
[ "def", "_request", "(", "self", ",", "uri", ",", "params", "=", "None", ",", "postParams", "=", "None", ",", "verb", "=", "'GET'", ")", ":", "return", "getattr", "(", "requests", ",", "verb", ".", "lower", "(", ")", ")", "(", "self", ".", "url", ...
Execute a request on the plugit api
[ "Execute", "a", "request", "on", "the", "plugit", "api" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit/api.py#L27-L29
ebu/PlugIt
plugit/api.py
PlugItAPI.get_user
def get_user(self, userPk): """Returns the user specified with the user's Pk or UUID""" r = self._request('user/' + str(userPk)) if r: # Set base properties and copy data inside the user u = User() u.pk = u.id = userPk u.__dict__.update(r.json()) return u return None
python
def get_user(self, userPk): """Returns the user specified with the user's Pk or UUID""" r = self._request('user/' + str(userPk)) if r: # Set base properties and copy data inside the user u = User() u.pk = u.id = userPk u.__dict__.update(r.json()) return u return None
[ "def", "get_user", "(", "self", ",", "userPk", ")", ":", "r", "=", "self", ".", "_request", "(", "'user/'", "+", "str", "(", "userPk", ")", ")", "if", "r", ":", "# Set base properties and copy data inside the user", "u", "=", "User", "(", ")", "u", ".", ...
Returns the user specified with the user's Pk or UUID
[ "Returns", "the", "user", "specified", "with", "the", "user", "s", "Pk", "or", "UUID" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit/api.py#L31-L40
ebu/PlugIt
plugit/api.py
PlugItAPI.get_subscription_labels
def get_subscription_labels(self, userPk): """Returns a list with all the labels the user is subscribed to""" r = self._request('subscriptions/' + str(userPk)) if r: s = r.json() return s return []
python
def get_subscription_labels(self, userPk): """Returns a list with all the labels the user is subscribed to""" r = self._request('subscriptions/' + str(userPk)) if r: s = r.json() return s return []
[ "def", "get_subscription_labels", "(", "self", ",", "userPk", ")", ":", "r", "=", "self", ".", "_request", "(", "'subscriptions/'", "+", "str", "(", "userPk", ")", ")", "if", "r", ":", "s", "=", "r", ".", "json", "(", ")", "return", "s", "return", ...
Returns a list with all the labels the user is subscribed to
[ "Returns", "a", "list", "with", "all", "the", "labels", "the", "user", "is", "subscribed", "to" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit/api.py#L49-L55
ebu/PlugIt
plugit/api.py
PlugItAPI.get_orgas
def get_orgas(self): """Return the list of pk for all orgas""" r = self._request('orgas/') if not r: return None retour = [] for data in r.json()['data']: o = Orga() o.__dict__.update(data) o.pk = o.id retour.append(o) return retour
python
def get_orgas(self): """Return the list of pk for all orgas""" r = self._request('orgas/') if not r: return None retour = [] for data in r.json()['data']: o = Orga() o.__dict__.update(data) o.pk = o.id retour.append(o) return retour
[ "def", "get_orgas", "(", "self", ")", ":", "r", "=", "self", ".", "_request", "(", "'orgas/'", ")", "if", "not", "r", ":", "return", "None", "retour", "=", "[", "]", "for", "data", "in", "r", ".", "json", "(", ")", "[", "'data'", "]", ":", "o",...
Return the list of pk for all orgas
[ "Return", "the", "list", "of", "pk", "for", "all", "orgas" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit/api.py#L57-L73
ebu/PlugIt
plugit/api.py
PlugItAPI.get_orga
def get_orga(self, orgaPk): """Return an organization speficied with orgaPk""" r = self._request('orga/' + str(orgaPk)) if r: # Set base properties and copy data inside the orga o = Orga() o.pk = o.id = orgaPk o.__dict__.update(r.json()) return o return None
python
def get_orga(self, orgaPk): """Return an organization speficied with orgaPk""" r = self._request('orga/' + str(orgaPk)) if r: # Set base properties and copy data inside the orga o = Orga() o.pk = o.id = orgaPk o.__dict__.update(r.json()) return o return None
[ "def", "get_orga", "(", "self", ",", "orgaPk", ")", ":", "r", "=", "self", ".", "_request", "(", "'orga/'", "+", "str", "(", "orgaPk", ")", ")", "if", "r", ":", "# Set base properties and copy data inside the orga", "o", "=", "Orga", "(", ")", "o", ".", ...
Return an organization speficied with orgaPk
[ "Return", "an", "organization", "speficied", "with", "orgaPk" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit/api.py#L75-L84
ebu/PlugIt
plugit/api.py
PlugItAPI.get_project_members
def get_project_members(self): """Return the list of members in the project""" r = self._request('members/') if not r: return None retour = [] for data in r.json()['members']: # Base properties u = User() u.__dict__.update(data) retour.append(u) return retour
python
def get_project_members(self): """Return the list of members in the project""" r = self._request('members/') if not r: return None retour = [] for data in r.json()['members']: # Base properties u = User() u.__dict__.update(data) retour.append(u) return retour
[ "def", "get_project_members", "(", "self", ")", ":", "r", "=", "self", ".", "_request", "(", "'members/'", ")", "if", "not", "r", ":", "return", "None", "retour", "=", "[", "]", "for", "data", "in", "r", ".", "json", "(", ")", "[", "'members'", "]"...
Return the list of members in the project
[ "Return", "the", "list", "of", "members", "in", "the", "project" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit/api.py#L86-L102
ebu/PlugIt
plugit/api.py
PlugItAPI.send_mail
def send_mail(self, sender, subject, recipients, message, response_id=None, html_message=False): """Send an email using EBUio features. If response_id is set, replies will be send back to the PlugIt server.""" params = { 'sender': sender, 'subject': subject, 'dests': recipients, 'message': message, 'html_message': html_message, } if response_id: params['response_id'] = response_id return self._request('mail/', postParams=params, verb='POST')
python
def send_mail(self, sender, subject, recipients, message, response_id=None, html_message=False): """Send an email using EBUio features. If response_id is set, replies will be send back to the PlugIt server.""" params = { 'sender': sender, 'subject': subject, 'dests': recipients, 'message': message, 'html_message': html_message, } if response_id: params['response_id'] = response_id return self._request('mail/', postParams=params, verb='POST')
[ "def", "send_mail", "(", "self", ",", "sender", ",", "subject", ",", "recipients", ",", "message", ",", "response_id", "=", "None", ",", "html_message", "=", "False", ")", ":", "params", "=", "{", "'sender'", ":", "sender", ",", "'subject'", ":", "subjec...
Send an email using EBUio features. If response_id is set, replies will be send back to the PlugIt server.
[ "Send", "an", "email", "using", "EBUio", "features", ".", "If", "response_id", "is", "set", "replies", "will", "be", "send", "back", "to", "the", "PlugIt", "server", "." ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit/api.py#L111-L125
ebu/PlugIt
plugit/api.py
PlugItAPI.forum_create_topic
def forum_create_topic(self, subject, author, message, tags=""): """Create a topic using EBUio features.""" params = {'subject': subject, 'author': author, 'message': message, 'tags': tags} return self._request('ebuio/forum/', postParams=params, verb='POST')
python
def forum_create_topic(self, subject, author, message, tags=""): """Create a topic using EBUio features.""" params = {'subject': subject, 'author': author, 'message': message, 'tags': tags} return self._request('ebuio/forum/', postParams=params, verb='POST')
[ "def", "forum_create_topic", "(", "self", ",", "subject", ",", "author", ",", "message", ",", "tags", "=", "\"\"", ")", ":", "params", "=", "{", "'subject'", ":", "subject", ",", "'author'", ":", "author", ",", "'message'", ":", "message", ",", "'tags'",...
Create a topic using EBUio features.
[ "Create", "a", "topic", "using", "EBUio", "features", "." ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit/api.py#L131-L136
ebu/PlugIt
plugit/api.py
PlugItAPI.forum_topic_get_by_tag_for_user
def forum_topic_get_by_tag_for_user(self, tag=None, author=None): """Get all forum topics with a specific tag""" if not tag: return None if author: r = self._request('ebuio/forum/search/bytag/' + tag + '?u=' + author) else: r = self._request('ebuio/forum/search/bytag/' + tag) if not r: return None retour = [] for data in r.json().get('data', []): retour.append(data) return retour
python
def forum_topic_get_by_tag_for_user(self, tag=None, author=None): """Get all forum topics with a specific tag""" if not tag: return None if author: r = self._request('ebuio/forum/search/bytag/' + tag + '?u=' + author) else: r = self._request('ebuio/forum/search/bytag/' + tag) if not r: return None retour = [] for data in r.json().get('data', []): retour.append(data) return retour
[ "def", "forum_topic_get_by_tag_for_user", "(", "self", ",", "tag", "=", "None", ",", "author", "=", "None", ")", ":", "if", "not", "tag", ":", "return", "None", "if", "author", ":", "r", "=", "self", ".", "_request", "(", "'ebuio/forum/search/bytag/'", "+"...
Get all forum topics with a specific tag
[ "Get", "all", "forum", "topics", "with", "a", "specific", "tag" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit/api.py#L138-L156
hweickert/checksum
checksum/__init__.py
get_for_directory
def get_for_directory( dp, hash_mode="md5", filter_dots=False, filter_func=lambda fp:False ): r""" Returns a hash string for the files below a given directory path. :param dp: Path to a directory. :param hash_mode: Can be either one of 'md5', 'sha1', 'sha256' or 'sha512'. Defines the algorithm used to generate the resulting hash string. Default is 'md5'. :param filter_dots: If True will filter directories or files beginning with a '.' (dot) like '.git'. Default is False. :param filter_func: A function receiving a path as a single paramter. If it returns True the given path will be excluded from the hash calculation. Otherwise it will be included. """ hash_func = _HASH_MODE_DICT.get(hash_mode) root_dps_fns = os.walk( dp, topdown=True ) root_dps_fns = itertools.imap( list, root_dps_fns ) if filter_dots: root_dps_fns = itertools.ifilterfalse( _is_dot_root, root_dps_fns ) root_dps_fns = itertools.imap( _filter_dot_fns, root_dps_fns ) fps_lists = itertools.imap( _gen_fps, root_dps_fns ) fps = itertools.chain( *fps_lists ) fps = itertools.ifilterfalse( filter_func, fps ) file_handles = itertools.imap( _get_file_handle, fps ) file_hash_digests = itertools.imap( _get_file_hash_digest, file_handles, itertools.repeat(hash_func) ) file_hash_digests = sorted( file_hash_digests ) file_hash_digests = map( _get_utf8_encoded, file_hash_digests ) hash_ = _get_merged_hash( file_hash_digests, hash_func ) return hash_.hexdigest()
python
def get_for_directory( dp, hash_mode="md5", filter_dots=False, filter_func=lambda fp:False ): r""" Returns a hash string for the files below a given directory path. :param dp: Path to a directory. :param hash_mode: Can be either one of 'md5', 'sha1', 'sha256' or 'sha512'. Defines the algorithm used to generate the resulting hash string. Default is 'md5'. :param filter_dots: If True will filter directories or files beginning with a '.' (dot) like '.git'. Default is False. :param filter_func: A function receiving a path as a single paramter. If it returns True the given path will be excluded from the hash calculation. Otherwise it will be included. """ hash_func = _HASH_MODE_DICT.get(hash_mode) root_dps_fns = os.walk( dp, topdown=True ) root_dps_fns = itertools.imap( list, root_dps_fns ) if filter_dots: root_dps_fns = itertools.ifilterfalse( _is_dot_root, root_dps_fns ) root_dps_fns = itertools.imap( _filter_dot_fns, root_dps_fns ) fps_lists = itertools.imap( _gen_fps, root_dps_fns ) fps = itertools.chain( *fps_lists ) fps = itertools.ifilterfalse( filter_func, fps ) file_handles = itertools.imap( _get_file_handle, fps ) file_hash_digests = itertools.imap( _get_file_hash_digest, file_handles, itertools.repeat(hash_func) ) file_hash_digests = sorted( file_hash_digests ) file_hash_digests = map( _get_utf8_encoded, file_hash_digests ) hash_ = _get_merged_hash( file_hash_digests, hash_func ) return hash_.hexdigest()
[ "def", "get_for_directory", "(", "dp", ",", "hash_mode", "=", "\"md5\"", ",", "filter_dots", "=", "False", ",", "filter_func", "=", "lambda", "fp", ":", "False", ")", ":", "hash_func", "=", "_HASH_MODE_DICT", ".", "get", "(", "hash_mode", ")", "root_dps_fns"...
r""" Returns a hash string for the files below a given directory path. :param dp: Path to a directory. :param hash_mode: Can be either one of 'md5', 'sha1', 'sha256' or 'sha512'. Defines the algorithm used to generate the resulting hash string. Default is 'md5'. :param filter_dots: If True will filter directories or files beginning with a '.' (dot) like '.git'. Default is False. :param filter_func: A function receiving a path as a single paramter. If it returns True the given path will be excluded from the hash calculation. Otherwise it will be included.
[ "r", "Returns", "a", "hash", "string", "for", "the", "files", "below", "a", "given", "directory", "path", "." ]
train
https://github.com/hweickert/checksum/blob/79e701c76a54ee7739475714ceb7370f9f90eee4/checksum/__init__.py#L35-L71
hweickert/checksum
checksum/__init__.py
get_for_file
def get_for_file( fp, hash_mode="md5" ): r""" Returns a hash string for the given file path. :param fp: Path to the file. :param hash_mode: Can be either one of 'md5', 'sha1', 'sha256' or 'sha512'. Defines the algorithm used to generate the resulting hash string. Default is 'md5'. """ with _get_file_handle(fp) as f: file_hash_digest = get_for_handle(f, hash_mode) return file_hash_digest
python
def get_for_file( fp, hash_mode="md5" ): r""" Returns a hash string for the given file path. :param fp: Path to the file. :param hash_mode: Can be either one of 'md5', 'sha1', 'sha256' or 'sha512'. Defines the algorithm used to generate the resulting hash string. Default is 'md5'. """ with _get_file_handle(fp) as f: file_hash_digest = get_for_handle(f, hash_mode) return file_hash_digest
[ "def", "get_for_file", "(", "fp", ",", "hash_mode", "=", "\"md5\"", ")", ":", "with", "_get_file_handle", "(", "fp", ")", "as", "f", ":", "file_hash_digest", "=", "get_for_handle", "(", "f", ",", "hash_mode", ")", "return", "file_hash_digest" ]
r""" Returns a hash string for the given file path. :param fp: Path to the file. :param hash_mode: Can be either one of 'md5', 'sha1', 'sha256' or 'sha512'. Defines the algorithm used to generate the resulting hash string. Default is 'md5'.
[ "r", "Returns", "a", "hash", "string", "for", "the", "given", "file", "path", "." ]
train
https://github.com/hweickert/checksum/blob/79e701c76a54ee7739475714ceb7370f9f90eee4/checksum/__init__.py#L75-L88
hweickert/checksum
checksum/__init__.py
get_for_handle
def get_for_handle( f, hash_mode="md5" ): r""" Returns a hash string for the given file-like object. :param f: The file object. :param hash_mode: Can be either one of 'md5', 'sha1', 'sha256' or 'sha512'. Defines the algorithm used to generate the resulting hash string. Default is 'md5'. """ hash_func = _HASH_MODE_DICT.get(hash_mode) file_hash_digest = _get_file_hash_digest( f, hash_func ) file_hash_digest = _get_utf8_encoded( file_hash_digest ) return file_hash_digest
python
def get_for_handle( f, hash_mode="md5" ): r""" Returns a hash string for the given file-like object. :param f: The file object. :param hash_mode: Can be either one of 'md5', 'sha1', 'sha256' or 'sha512'. Defines the algorithm used to generate the resulting hash string. Default is 'md5'. """ hash_func = _HASH_MODE_DICT.get(hash_mode) file_hash_digest = _get_file_hash_digest( f, hash_func ) file_hash_digest = _get_utf8_encoded( file_hash_digest ) return file_hash_digest
[ "def", "get_for_handle", "(", "f", ",", "hash_mode", "=", "\"md5\"", ")", ":", "hash_func", "=", "_HASH_MODE_DICT", ".", "get", "(", "hash_mode", ")", "file_hash_digest", "=", "_get_file_hash_digest", "(", "f", ",", "hash_func", ")", "file_hash_digest", "=", "...
r""" Returns a hash string for the given file-like object. :param f: The file object. :param hash_mode: Can be either one of 'md5', 'sha1', 'sha256' or 'sha512'. Defines the algorithm used to generate the resulting hash string. Default is 'md5'.
[ "r", "Returns", "a", "hash", "string", "for", "the", "given", "file", "-", "like", "object", "." ]
train
https://github.com/hweickert/checksum/blob/79e701c76a54ee7739475714ceb7370f9f90eee4/checksum/__init__.py#L92-L105
gwastro/pycbc-glue
pycbc_glue/ligolw/array.py
getArraysByName
def getArraysByName(elem, name): """ Return a list of arrays with name name under elem. """ name = StripArrayName(name) return elem.getElements(lambda e: (e.tagName == ligolw.Array.tagName) and (e.Name == name))
python
def getArraysByName(elem, name): """ Return a list of arrays with name name under elem. """ name = StripArrayName(name) return elem.getElements(lambda e: (e.tagName == ligolw.Array.tagName) and (e.Name == name))
[ "def", "getArraysByName", "(", "elem", ",", "name", ")", ":", "name", "=", "StripArrayName", "(", "name", ")", "return", "elem", ".", "getElements", "(", "lambda", "e", ":", "(", "e", ".", "tagName", "==", "ligolw", ".", "Array", ".", "tagName", ")", ...
Return a list of arrays with name name under elem.
[ "Return", "a", "list", "of", "arrays", "with", "name", "name", "under", "elem", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/array.py#L100-L105
gwastro/pycbc-glue
pycbc_glue/ligolw/array.py
from_array
def from_array(name, array, dim_names = None): """ Construct a LIGO Light Weight XML Array document subtree from a numpy array object. Example: >>> import numpy, sys >>> a = numpy.arange(12, dtype = "double") >>> a.shape = (4, 3) >>> from_array(u"test", a).write(sys.stdout) # doctest: +NORMALIZE_WHITESPACE <Array Type="real_8" Name="test:array"> <Dim>3</Dim> <Dim>4</Dim> <Stream Delimiter=" " Type="Local"> 0 3 6 9 1 4 7 10 2 5 8 11 </Stream> </Array> """ # Type must be set for .__init__(); easier to set Name afterwards # to take advantage of encoding handled by attribute proxy doc = Array(Attributes({u"Type": ligolwtypes.FromNumPyType[str(array.dtype)]})) doc.Name = name for n, dim in enumerate(reversed(array.shape)): child = ligolw.Dim() if dim_names is not None: child.Name = dim_names[n] child.pcdata = unicode(dim) doc.appendChild(child) child = ArrayStream(Attributes({u"Type": ArrayStream.Type.default, u"Delimiter": ArrayStream.Delimiter.default})) doc.appendChild(child) doc.array = array return doc
python
def from_array(name, array, dim_names = None): """ Construct a LIGO Light Weight XML Array document subtree from a numpy array object. Example: >>> import numpy, sys >>> a = numpy.arange(12, dtype = "double") >>> a.shape = (4, 3) >>> from_array(u"test", a).write(sys.stdout) # doctest: +NORMALIZE_WHITESPACE <Array Type="real_8" Name="test:array"> <Dim>3</Dim> <Dim>4</Dim> <Stream Delimiter=" " Type="Local"> 0 3 6 9 1 4 7 10 2 5 8 11 </Stream> </Array> """ # Type must be set for .__init__(); easier to set Name afterwards # to take advantage of encoding handled by attribute proxy doc = Array(Attributes({u"Type": ligolwtypes.FromNumPyType[str(array.dtype)]})) doc.Name = name for n, dim in enumerate(reversed(array.shape)): child = ligolw.Dim() if dim_names is not None: child.Name = dim_names[n] child.pcdata = unicode(dim) doc.appendChild(child) child = ArrayStream(Attributes({u"Type": ArrayStream.Type.default, u"Delimiter": ArrayStream.Delimiter.default})) doc.appendChild(child) doc.array = array return doc
[ "def", "from_array", "(", "name", ",", "array", ",", "dim_names", "=", "None", ")", ":", "# Type must be set for .__init__(); easier to set Name afterwards", "# to take advantage of encoding handled by attribute proxy", "doc", "=", "Array", "(", "Attributes", "(", "{", "u\...
Construct a LIGO Light Weight XML Array document subtree from a numpy array object. Example: >>> import numpy, sys >>> a = numpy.arange(12, dtype = "double") >>> a.shape = (4, 3) >>> from_array(u"test", a).write(sys.stdout) # doctest: +NORMALIZE_WHITESPACE <Array Type="real_8" Name="test:array"> <Dim>3</Dim> <Dim>4</Dim> <Stream Delimiter=" " Type="Local"> 0 3 6 9 1 4 7 10 2 5 8 11 </Stream> </Array>
[ "Construct", "a", "LIGO", "Light", "Weight", "XML", "Array", "document", "subtree", "from", "a", "numpy", "array", "object", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/array.py#L117-L151
gwastro/pycbc-glue
pycbc_glue/ligolw/array.py
get_array
def get_array(xmldoc, name): """ Scan xmldoc for an array named name. Raises ValueError if not exactly 1 such array is found. """ arrays = getArraysByName(xmldoc, name) if len(arrays) != 1: raise ValueError("document must contain exactly one %s array" % StripArrayName(name)) return arrays[0]
python
def get_array(xmldoc, name): """ Scan xmldoc for an array named name. Raises ValueError if not exactly 1 such array is found. """ arrays = getArraysByName(xmldoc, name) if len(arrays) != 1: raise ValueError("document must contain exactly one %s array" % StripArrayName(name)) return arrays[0]
[ "def", "get_array", "(", "xmldoc", ",", "name", ")", ":", "arrays", "=", "getArraysByName", "(", "xmldoc", ",", "name", ")", "if", "len", "(", "arrays", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"document must contain exactly one %s array\"", "%", "...
Scan xmldoc for an array named name. Raises ValueError if not exactly 1 such array is found.
[ "Scan", "xmldoc", "for", "an", "array", "named", "name", ".", "Raises", "ValueError", "if", "not", "exactly", "1", "such", "array", "is", "found", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/array.py#L154-L162
gwastro/pycbc-glue
pycbc_glue/ligolw/array.py
use_in
def use_in(ContentHandler): """ Modify ContentHandler, a sub-class of pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Array and ArrayStream classes defined in this module when parsing XML documents. Example: >>> from pycbc_glue.ligolw import ligolw >>> class MyContentHandler(ligolw.LIGOLWContentHandler): ... pass ... >>> use_in(MyContentHandler) <class 'pycbc_glue.ligolw.array.MyContentHandler'> """ def startStream(self, parent, attrs, __orig_startStream = ContentHandler.startStream): if parent.tagName == ligolw.Array.tagName: return ArrayStream(attrs).config(parent) return __orig_startStream(self, parent, attrs) def startArray(self, parent, attrs): return Array(attrs) ContentHandler.startStream = startStream ContentHandler.startArray = startArray return ContentHandler
python
def use_in(ContentHandler): """ Modify ContentHandler, a sub-class of pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Array and ArrayStream classes defined in this module when parsing XML documents. Example: >>> from pycbc_glue.ligolw import ligolw >>> class MyContentHandler(ligolw.LIGOLWContentHandler): ... pass ... >>> use_in(MyContentHandler) <class 'pycbc_glue.ligolw.array.MyContentHandler'> """ def startStream(self, parent, attrs, __orig_startStream = ContentHandler.startStream): if parent.tagName == ligolw.Array.tagName: return ArrayStream(attrs).config(parent) return __orig_startStream(self, parent, attrs) def startArray(self, parent, attrs): return Array(attrs) ContentHandler.startStream = startStream ContentHandler.startArray = startArray return ContentHandler
[ "def", "use_in", "(", "ContentHandler", ")", ":", "def", "startStream", "(", "self", ",", "parent", ",", "attrs", ",", "__orig_startStream", "=", "ContentHandler", ".", "startStream", ")", ":", "if", "parent", ".", "tagName", "==", "ligolw", ".", "Array", ...
Modify ContentHandler, a sub-class of pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Array and ArrayStream classes defined in this module when parsing XML documents. Example: >>> from pycbc_glue.ligolw import ligolw >>> class MyContentHandler(ligolw.LIGOLWContentHandler): ... pass ... >>> use_in(MyContentHandler) <class 'pycbc_glue.ligolw.array.MyContentHandler'>
[ "Modify", "ContentHandler", "a", "sub", "-", "class", "of", "pycbc_glue", ".", "ligolw", ".", "LIGOLWContentHandler", "to", "cause", "it", "to", "use", "the", "Array", "and", "ArrayStream", "classes", "defined", "in", "this", "module", "when", "parsing", "XML"...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/array.py#L291-L318
gwastro/pycbc-glue
pycbc_glue/ligolw/array.py
Array.get_shape
def get_shape(self): """ Return a tuple of this array's dimensions. This is done by querying the Dim children. Note that once it has been created, it is also possible to examine an Array object's .array attribute directly, and doing that is much faster. """ return tuple(int(c.pcdata) for c in self.getElementsByTagName(ligolw.Dim.tagName))[::-1]
python
def get_shape(self): """ Return a tuple of this array's dimensions. This is done by querying the Dim children. Note that once it has been created, it is also possible to examine an Array object's .array attribute directly, and doing that is much faster. """ return tuple(int(c.pcdata) for c in self.getElementsByTagName(ligolw.Dim.tagName))[::-1]
[ "def", "get_shape", "(", "self", ")", ":", "return", "tuple", "(", "int", "(", "c", ".", "pcdata", ")", "for", "c", "in", "self", ".", "getElementsByTagName", "(", "ligolw", ".", "Dim", ".", "tagName", ")", ")", "[", ":", ":", "-", "1", "]" ]
Return a tuple of this array's dimensions. This is done by querying the Dim children. Note that once it has been created, it is also possible to examine an Array object's .array attribute directly, and doing that is much faster.
[ "Return", "a", "tuple", "of", "this", "array", "s", "dimensions", ".", "This", "is", "done", "by", "querying", "the", "Dim", "children", ".", "Note", "that", "once", "it", "has", "been", "created", "it", "is", "also", "possible", "to", "examine", "an", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/array.py#L252-L259
TracyWebTech/django-conversejs
conversejs/conf.py
get_conversejs_settings
def get_conversejs_settings(): """This helper function returns all the configuration needed by Converse.js frontend (javascript). Configurations specific to django-conversejs should be added above. """ converse_settings = { 'CONVERSEJS_AUTO_LIST_ROOMS': False, 'CONVERSEJS_AUTO_SUBSCRIBE': False, 'CONVERSEJS_BOSH_SERVICE_URL': 'https://bind.opkode.im', 'CONVERSEJS_HIDE_MUC_SERVER': False, 'CONVERSEJS_PREBIND': True, 'CONVERSEJS_SHOW_CONTROLBOX_BY_DEFAULT': False, 'CONVERSEJS_XHR_USER_SEARCH': False, 'CONVERSEJS_DEBUG': settings.DEBUG, 'CONVERSEJS_SHOW_ONLY_ONLINE_USERS': False, 'CONVERSEJS_ALLOW_CONTACT_REQUESTS': True, } for key, value in converse_settings.items(): conf = getattr(settings, key, value) if isinstance(conf, bool): conf = unicode(conf).lower() converse_settings[key] = conf return converse_settings
python
def get_conversejs_settings(): """This helper function returns all the configuration needed by Converse.js frontend (javascript). Configurations specific to django-conversejs should be added above. """ converse_settings = { 'CONVERSEJS_AUTO_LIST_ROOMS': False, 'CONVERSEJS_AUTO_SUBSCRIBE': False, 'CONVERSEJS_BOSH_SERVICE_URL': 'https://bind.opkode.im', 'CONVERSEJS_HIDE_MUC_SERVER': False, 'CONVERSEJS_PREBIND': True, 'CONVERSEJS_SHOW_CONTROLBOX_BY_DEFAULT': False, 'CONVERSEJS_XHR_USER_SEARCH': False, 'CONVERSEJS_DEBUG': settings.DEBUG, 'CONVERSEJS_SHOW_ONLY_ONLINE_USERS': False, 'CONVERSEJS_ALLOW_CONTACT_REQUESTS': True, } for key, value in converse_settings.items(): conf = getattr(settings, key, value) if isinstance(conf, bool): conf = unicode(conf).lower() converse_settings[key] = conf return converse_settings
[ "def", "get_conversejs_settings", "(", ")", ":", "converse_settings", "=", "{", "'CONVERSEJS_AUTO_LIST_ROOMS'", ":", "False", ",", "'CONVERSEJS_AUTO_SUBSCRIBE'", ":", "False", ",", "'CONVERSEJS_BOSH_SERVICE_URL'", ":", "'https://bind.opkode.im'", ",", "'CONVERSEJS_HIDE_MUC_SE...
This helper function returns all the configuration needed by Converse.js frontend (javascript). Configurations specific to django-conversejs should be added above.
[ "This", "helper", "function", "returns", "all", "the", "configuration", "needed", "by", "Converse", ".", "js", "frontend", "(", "javascript", ")", "." ]
train
https://github.com/TracyWebTech/django-conversejs/blob/cd9176f007ef3853ea6321bf93b466644d89305b/conversejs/conf.py#L9-L37
gwastro/pycbc-glue
pycbc_glue/segmentdb/segmentdb_utils.py
get_all_files_in_range
def get_all_files_in_range(dirname, starttime, endtime, pad=64): """Returns all files in dirname and all its subdirectories whose names indicate that they contain segments in the range starttime to endtime""" ret = [] # Maybe the user just wants one file... if os.path.isfile(dirname): if re.match('.*-[0-9]*-[0-9]*\.xml$', dirname): return [dirname] else: return ret first_four_start = starttime / 100000 first_four_end = endtime / 100000 for filename in os.listdir(dirname): if re.match('.*-[0-9]{5}$', filename): dirtime = int(filename[-5:]) if dirtime >= first_four_start and dirtime <= first_four_end: ret += get_all_files_in_range(os.path.join(dirname,filename), starttime, endtime, pad=pad) elif re.match('.*-[0-9]{4}$', filename): dirtime = int(filename[-4:]) if dirtime >= first_four_start and dirtime <= first_four_end: ret += get_all_files_in_range(os.path.join(dirname,filename), starttime, endtime, pad=pad) elif re.match('.*-[0-9]*-[0-9]*\.xml$', filename): file_time = int(filename.split('-')[-2]) if file_time >= (starttime-pad) and file_time <= (endtime+pad): ret.append(os.path.join(dirname,filename)) else: # Keep recursing, we may be looking at directories of # ifos, each of which has directories with times ret += get_all_files_in_range(os.path.join(dirname,filename), starttime, endtime, pad=pad) return ret
python
def get_all_files_in_range(dirname, starttime, endtime, pad=64): """Returns all files in dirname and all its subdirectories whose names indicate that they contain segments in the range starttime to endtime""" ret = [] # Maybe the user just wants one file... if os.path.isfile(dirname): if re.match('.*-[0-9]*-[0-9]*\.xml$', dirname): return [dirname] else: return ret first_four_start = starttime / 100000 first_four_end = endtime / 100000 for filename in os.listdir(dirname): if re.match('.*-[0-9]{5}$', filename): dirtime = int(filename[-5:]) if dirtime >= first_four_start and dirtime <= first_four_end: ret += get_all_files_in_range(os.path.join(dirname,filename), starttime, endtime, pad=pad) elif re.match('.*-[0-9]{4}$', filename): dirtime = int(filename[-4:]) if dirtime >= first_four_start and dirtime <= first_four_end: ret += get_all_files_in_range(os.path.join(dirname,filename), starttime, endtime, pad=pad) elif re.match('.*-[0-9]*-[0-9]*\.xml$', filename): file_time = int(filename.split('-')[-2]) if file_time >= (starttime-pad) and file_time <= (endtime+pad): ret.append(os.path.join(dirname,filename)) else: # Keep recursing, we may be looking at directories of # ifos, each of which has directories with times ret += get_all_files_in_range(os.path.join(dirname,filename), starttime, endtime, pad=pad) return ret
[ "def", "get_all_files_in_range", "(", "dirname", ",", "starttime", ",", "endtime", ",", "pad", "=", "64", ")", ":", "ret", "=", "[", "]", "# Maybe the user just wants one file...", "if", "os", ".", "path", ".", "isfile", "(", "dirname", ")", ":", "if", "re...
Returns all files in dirname and all its subdirectories whose names indicate that they contain segments in the range starttime to endtime
[ "Returns", "all", "files", "in", "dirname", "and", "all", "its", "subdirectories", "whose", "names", "indicate", "that", "they", "contain", "segments", "in", "the", "range", "starttime", "to", "endtime" ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentdb/segmentdb_utils.py#L41-L76
gwastro/pycbc-glue
pycbc_glue/segmentdb/segmentdb_utils.py
setup_database
def setup_database(database_location): """ 1. Determine protocol""" try: # When no protocol is given: if database_location.find('://') == -1: msg = "Error: Please specify protocol in your --segment-url argument in the format PROTOCOL://HOST" msg +="\nFor example: --segment-url https://segdb.ligo.caltech.edu" msg += "\nSupported protocols include: http, https, ldbd, ldbdi" msg += "\nRun with --help for usage" raise ValueError(msg) # When wrong protocol is given: protocol = database_location[:database_location.find('://')].lower() if protocol not in ("http","https","ldbd","ldbdi"): msg = "Error: protocol %s not supported" % protocol msg += "\nPlease specify correct protocol in your --segment-url argument in the format PROTOCOL://HOST" msg += "\nSupported protocols include: http, https, ldbd, ldbdi" msg += "\nRun with --help for usage" raise ValueError(msg) except ValueError, e: print >>sys.stderr, str(e) sys.exit(1) """ 2. Determine host and port""" host_and_port = database_location[(len(protocol)+3):] if host_and_port.find(':') < 0: # if no port number given, set default port respectively: host = host_and_port if protocol == 'http': port = 80 elif protocol == 'https': port = 443 elif protocol == 'ldbd': port = 30015 elif protocol == 'ldbdi': port = 30016 else: host, portString = host_and_port.split(':') port = int(portString) if port == 30020: print >>sys.stderr, "Error: PORT 30020 no longer provide segment database service" sys.exit(1) """ 3. Set up connection to LDBD(W)Server """ client = None identity = "/DC=org/DC=doegrids/OU=Services/CN=ldbd/" if protocol.startswith('http'): if protocol == "https": identity += host else: identity = None try: from pycbc_glue import LDBDWClient client = LDBDWClient.LDBDClient(host,port,protocol,identity) except Exception, e: print >>sys.stderr, "Unable to connect to LDBD Server at %s://%s:%d " % (protocol,host, port) + str(e) sys.exit(1) elif protocol.startswith('ldbd'): if protocol == "ldbd": identity += host from pycbc_glue import gsiserverutils else: identity = None try: from pycbc_glue import LDBDClient client = LDBDClient.LDBDClient(host,port,identity) except Exception, e: print >>sys.stderr, "Unable to connect to LDBD Server at %s://%s:%d" % (protocol,host, port) + str(e) try: if gsiserverutils.checkCredentials(): print >>sys.stderr, "Got the following error : " + str(e) print >>sys.stderr, "Run wiht --help for usage" except UnboundLocalError: pass sys.exit(1) else: raise ValueError( "invalid url for segment database" ) return client
python
def setup_database(database_location): """ 1. Determine protocol""" try: # When no protocol is given: if database_location.find('://') == -1: msg = "Error: Please specify protocol in your --segment-url argument in the format PROTOCOL://HOST" msg +="\nFor example: --segment-url https://segdb.ligo.caltech.edu" msg += "\nSupported protocols include: http, https, ldbd, ldbdi" msg += "\nRun with --help for usage" raise ValueError(msg) # When wrong protocol is given: protocol = database_location[:database_location.find('://')].lower() if protocol not in ("http","https","ldbd","ldbdi"): msg = "Error: protocol %s not supported" % protocol msg += "\nPlease specify correct protocol in your --segment-url argument in the format PROTOCOL://HOST" msg += "\nSupported protocols include: http, https, ldbd, ldbdi" msg += "\nRun with --help for usage" raise ValueError(msg) except ValueError, e: print >>sys.stderr, str(e) sys.exit(1) """ 2. Determine host and port""" host_and_port = database_location[(len(protocol)+3):] if host_and_port.find(':') < 0: # if no port number given, set default port respectively: host = host_and_port if protocol == 'http': port = 80 elif protocol == 'https': port = 443 elif protocol == 'ldbd': port = 30015 elif protocol == 'ldbdi': port = 30016 else: host, portString = host_and_port.split(':') port = int(portString) if port == 30020: print >>sys.stderr, "Error: PORT 30020 no longer provide segment database service" sys.exit(1) """ 3. Set up connection to LDBD(W)Server """ client = None identity = "/DC=org/DC=doegrids/OU=Services/CN=ldbd/" if protocol.startswith('http'): if protocol == "https": identity += host else: identity = None try: from pycbc_glue import LDBDWClient client = LDBDWClient.LDBDClient(host,port,protocol,identity) except Exception, e: print >>sys.stderr, "Unable to connect to LDBD Server at %s://%s:%d " % (protocol,host, port) + str(e) sys.exit(1) elif protocol.startswith('ldbd'): if protocol == "ldbd": identity += host from pycbc_glue import gsiserverutils else: identity = None try: from pycbc_glue import LDBDClient client = LDBDClient.LDBDClient(host,port,identity) except Exception, e: print >>sys.stderr, "Unable to connect to LDBD Server at %s://%s:%d" % (protocol,host, port) + str(e) try: if gsiserverutils.checkCredentials(): print >>sys.stderr, "Got the following error : " + str(e) print >>sys.stderr, "Run wiht --help for usage" except UnboundLocalError: pass sys.exit(1) else: raise ValueError( "invalid url for segment database" ) return client
[ "def", "setup_database", "(", "database_location", ")", ":", "try", ":", "# When no protocol is given:", "if", "database_location", ".", "find", "(", "'://'", ")", "==", "-", "1", ":", "msg", "=", "\"Error: Please specify protocol in your --segment-url argument in the for...
1. Determine protocol
[ "1", ".", "Determine", "protocol" ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentdb/segmentdb_utils.py#L80-L163
gwastro/pycbc-glue
pycbc_glue/segmentdb/segmentdb_utils.py
ensure_segment_table
def ensure_segment_table(connection): """Ensures that the DB represented by connection posses a segment table. If not, creates one and prints a warning to stderr""" count = connection.cursor().execute("SELECT count(*) FROM sqlite_master WHERE name='segment'").fetchone()[0] if count == 0: print >>sys.stderr, "WARNING: None of the loaded files contain a segment table" theClass = lsctables.TableByName['segment'] statement = "CREATE TABLE IF NOT EXISTS segment (" + ", ".join(map(lambda key: "%s %s" % (key, ligolwtypes.ToSQLiteType[theClass.validcolumns[key]]), theClass.validcolumns)) + ")" connection.cursor().execute(statement)
python
def ensure_segment_table(connection): """Ensures that the DB represented by connection posses a segment table. If not, creates one and prints a warning to stderr""" count = connection.cursor().execute("SELECT count(*) FROM sqlite_master WHERE name='segment'").fetchone()[0] if count == 0: print >>sys.stderr, "WARNING: None of the loaded files contain a segment table" theClass = lsctables.TableByName['segment'] statement = "CREATE TABLE IF NOT EXISTS segment (" + ", ".join(map(lambda key: "%s %s" % (key, ligolwtypes.ToSQLiteType[theClass.validcolumns[key]]), theClass.validcolumns)) + ")" connection.cursor().execute(statement)
[ "def", "ensure_segment_table", "(", "connection", ")", ":", "count", "=", "connection", ".", "cursor", "(", ")", ".", "execute", "(", "\"SELECT count(*) FROM sqlite_master WHERE name='segment'\"", ")", ".", "fetchone", "(", ")", "[", "0", "]", "if", "count", "==...
Ensures that the DB represented by connection posses a segment table. If not, creates one and prints a warning to stderr
[ "Ensures", "that", "the", "DB", "represented", "by", "connection", "posses", "a", "segment", "table", ".", "If", "not", "creates", "one", "and", "prints", "a", "warning", "to", "stderr" ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentdb/segmentdb_utils.py#L342-L353
gwastro/pycbc-glue
pycbc_glue/segmentdb/segmentdb_utils.py
build_segment_list
def build_segment_list(engine, gps_start_time, gps_end_time, ifo, segment_name, version = None, start_pad = 0, end_pad = 0): """Optains a list of segments for the given ifo, name and version between the specified times. If a version is given the request is straightforward and is passed on to build_segment_list_one. Otherwise more complex processing is performed (not yet implemented)""" if version is not None: return build_segment_list_one(engine, gps_start_time, gps_end_time, ifo, segment_name, version, start_pad, end_pad) # This needs more sophisticated logic, for the moment just return the latest # available version sql = "SELECT max(version) FROM segment_definer " sql += "WHERE segment_definer.ifos = '%s' " % ifo sql += "AND segment_definer.name = '%s' " % segment_name rows = engine.query(sql) version = len(rows[0]) and rows[0][0] or 1 return build_segment_list_one(engine, gps_start_time, gps_end_time, ifo, segment_name, version, start_pad, end_pad)
python
def build_segment_list(engine, gps_start_time, gps_end_time, ifo, segment_name, version = None, start_pad = 0, end_pad = 0): """Optains a list of segments for the given ifo, name and version between the specified times. If a version is given the request is straightforward and is passed on to build_segment_list_one. Otherwise more complex processing is performed (not yet implemented)""" if version is not None: return build_segment_list_one(engine, gps_start_time, gps_end_time, ifo, segment_name, version, start_pad, end_pad) # This needs more sophisticated logic, for the moment just return the latest # available version sql = "SELECT max(version) FROM segment_definer " sql += "WHERE segment_definer.ifos = '%s' " % ifo sql += "AND segment_definer.name = '%s' " % segment_name rows = engine.query(sql) version = len(rows[0]) and rows[0][0] or 1 return build_segment_list_one(engine, gps_start_time, gps_end_time, ifo, segment_name, version, start_pad, end_pad)
[ "def", "build_segment_list", "(", "engine", ",", "gps_start_time", ",", "gps_end_time", ",", "ifo", ",", "segment_name", ",", "version", "=", "None", ",", "start_pad", "=", "0", ",", "end_pad", "=", "0", ")", ":", "if", "version", "is", "not", "None", ":...
Optains a list of segments for the given ifo, name and version between the specified times. If a version is given the request is straightforward and is passed on to build_segment_list_one. Otherwise more complex processing is performed (not yet implemented)
[ "Optains", "a", "list", "of", "segments", "for", "the", "given", "ifo", "name", "and", "version", "between", "the", "specified", "times", ".", "If", "a", "version", "is", "given", "the", "request", "is", "straightforward", "and", "is", "passed", "on", "to"...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentdb/segmentdb_utils.py#L447-L464
gwastro/pycbc-glue
pycbc_glue/segmentdb/segmentdb_utils.py
build_segment_list_one
def build_segment_list_one(engine, gps_start_time, gps_end_time, ifo, segment_name, version = None, start_pad = 0, end_pad = 0): """Builds a list of segments satisfying the given criteria """ seg_result = segmentlist([]) sum_result = segmentlist([]) # Is there any way to get segment and segement summary in one query? # Maybe some sort of outer join where we keep track of which segment # summaries we've already seen. sql = "SELECT segment_summary.start_time, segment_summary.end_time " sql += "FROM segment_definer, segment_summary " sql += "WHERE segment_summary.segment_def_id = segment_definer.segment_def_id " sql += "AND segment_definer.ifos = '%s' " % ifo if engine.__class__ == query_engine.LdbdQueryEngine: sql += "AND segment_summary.segment_def_cdb = segment_definer.creator_db " sql += "AND segment_definer.name = '%s' " % segment_name sql += "AND segment_definer.version = %s " % version sql += "AND NOT (%s > segment_summary.end_time OR segment_summary.start_time > %s)" % (gps_start_time, gps_end_time) rows = engine.query(sql) for sum_start_time, sum_end_time in rows: sum_start_time = (sum_start_time < gps_start_time) and gps_start_time or sum_start_time sum_end_time = (sum_end_time > gps_end_time) and gps_end_time or sum_end_time sum_result |= segmentlist([segment(sum_start_time, sum_end_time)]) # We can't use queries paramaterized with ? since the ldbd protocol doesn't support it... sql = "SELECT segment.start_time + %d, segment.end_time + %d " % (start_pad, end_pad) sql += "FROM segment, segment_definer " sql += "WHERE segment.segment_def_id = segment_definer.segment_def_id " if engine.__class__ == query_engine.LdbdQueryEngine: sql += "AND segment.segment_def_cdb = segment_definer.creator_db " sql += "AND segment_definer.ifos = '%s' " % ifo sql += "AND segment_definer.name = '%s' " % segment_name sql += "AND segment_definer.version = %s " % version sql += "AND NOT (%s > segment.end_time OR segment.start_time > %s)" % (gps_start_time, gps_end_time) rows = engine.query(sql) for seg_start_time, seg_end_time in rows: seg_start_time = (seg_start_time < gps_start_time) and gps_start_time or seg_start_time seg_end_time = (seg_end_time > gps_end_time) and gps_end_time or seg_end_time seg_result |= segmentlist([segment(seg_start_time, seg_end_time)]) engine.close() return sum_result, seg_result
python
def build_segment_list_one(engine, gps_start_time, gps_end_time, ifo, segment_name, version = None, start_pad = 0, end_pad = 0): """Builds a list of segments satisfying the given criteria """ seg_result = segmentlist([]) sum_result = segmentlist([]) # Is there any way to get segment and segement summary in one query? # Maybe some sort of outer join where we keep track of which segment # summaries we've already seen. sql = "SELECT segment_summary.start_time, segment_summary.end_time " sql += "FROM segment_definer, segment_summary " sql += "WHERE segment_summary.segment_def_id = segment_definer.segment_def_id " sql += "AND segment_definer.ifos = '%s' " % ifo if engine.__class__ == query_engine.LdbdQueryEngine: sql += "AND segment_summary.segment_def_cdb = segment_definer.creator_db " sql += "AND segment_definer.name = '%s' " % segment_name sql += "AND segment_definer.version = %s " % version sql += "AND NOT (%s > segment_summary.end_time OR segment_summary.start_time > %s)" % (gps_start_time, gps_end_time) rows = engine.query(sql) for sum_start_time, sum_end_time in rows: sum_start_time = (sum_start_time < gps_start_time) and gps_start_time or sum_start_time sum_end_time = (sum_end_time > gps_end_time) and gps_end_time or sum_end_time sum_result |= segmentlist([segment(sum_start_time, sum_end_time)]) # We can't use queries paramaterized with ? since the ldbd protocol doesn't support it... sql = "SELECT segment.start_time + %d, segment.end_time + %d " % (start_pad, end_pad) sql += "FROM segment, segment_definer " sql += "WHERE segment.segment_def_id = segment_definer.segment_def_id " if engine.__class__ == query_engine.LdbdQueryEngine: sql += "AND segment.segment_def_cdb = segment_definer.creator_db " sql += "AND segment_definer.ifos = '%s' " % ifo sql += "AND segment_definer.name = '%s' " % segment_name sql += "AND segment_definer.version = %s " % version sql += "AND NOT (%s > segment.end_time OR segment.start_time > %s)" % (gps_start_time, gps_end_time) rows = engine.query(sql) for seg_start_time, seg_end_time in rows: seg_start_time = (seg_start_time < gps_start_time) and gps_start_time or seg_start_time seg_end_time = (seg_end_time > gps_end_time) and gps_end_time or seg_end_time seg_result |= segmentlist([segment(seg_start_time, seg_end_time)]) engine.close() return sum_result, seg_result
[ "def", "build_segment_list_one", "(", "engine", ",", "gps_start_time", ",", "gps_end_time", ",", "ifo", ",", "segment_name", ",", "version", "=", "None", ",", "start_pad", "=", "0", ",", "end_pad", "=", "0", ")", ":", "seg_result", "=", "segmentlist", "(", ...
Builds a list of segments satisfying the given criteria
[ "Builds", "a", "list", "of", "segments", "satisfying", "the", "given", "criteria" ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentdb/segmentdb_utils.py#L467-L515
gwastro/pycbc-glue
pycbc_glue/segmentdb/segmentdb_utils.py
run_query_segments
def run_query_segments(doc, proc_id, engine, gps_start_time, gps_end_time, included_segments_string, excluded_segments_string = None, write_segments = True, start_pad = 0, end_pad = 0): """Runs a segment query. This was originally part of ligolw_query_segments, but now is also used by ligolw_segments_from_cats. The write_segments option is provided so callers can coalesce segments obtained over sever invocations (as segments_from_cats does). """ if write_segments: all_ifos = {} for ifo, segment_name, version in split_segment_ids(included_segments_string.split(',')): all_ifos[ifo] = True new_seg_def_id = add_to_segment_definer(doc, proc_id, ''.join(all_ifos.keys()), 'result', 0) add_to_segment_summary(doc, proc_id, new_seg_def_id, [[gps_start_time, gps_end_time]]) result = segmentlist([]) for ifo, segment_name, version in split_segment_ids(included_segments_string.split(',')): sum_segments, seg_segments = build_segment_list(engine, gps_start_time, gps_end_time, ifo, segment_name, version, start_pad, end_pad) seg_def_id = add_to_segment_definer(doc, proc_id, ifo, segment_name, version) add_to_segment_summary(doc, proc_id, seg_def_id, sum_segments) # and accumulate segments result |= seg_segments # Excluded segments are not required if excluded_segments_string: excluded_segments = segmentlist([]) for ifo, segment_name, version in split_segment_ids(excluded_segments_string.split(',')): sum_segments, seg_segments = build_segment_list(engine, gps_start_time, gps_end_time, ifo, segment_name, version) excluded_segments |= seg_segments result = result - excluded_segments result.coalesce() # Add the segments if write_segments: add_to_segment(doc, proc_id, new_seg_def_id, result) return result
python
def run_query_segments(doc, proc_id, engine, gps_start_time, gps_end_time, included_segments_string, excluded_segments_string = None, write_segments = True, start_pad = 0, end_pad = 0): """Runs a segment query. This was originally part of ligolw_query_segments, but now is also used by ligolw_segments_from_cats. The write_segments option is provided so callers can coalesce segments obtained over sever invocations (as segments_from_cats does). """ if write_segments: all_ifos = {} for ifo, segment_name, version in split_segment_ids(included_segments_string.split(',')): all_ifos[ifo] = True new_seg_def_id = add_to_segment_definer(doc, proc_id, ''.join(all_ifos.keys()), 'result', 0) add_to_segment_summary(doc, proc_id, new_seg_def_id, [[gps_start_time, gps_end_time]]) result = segmentlist([]) for ifo, segment_name, version in split_segment_ids(included_segments_string.split(',')): sum_segments, seg_segments = build_segment_list(engine, gps_start_time, gps_end_time, ifo, segment_name, version, start_pad, end_pad) seg_def_id = add_to_segment_definer(doc, proc_id, ifo, segment_name, version) add_to_segment_summary(doc, proc_id, seg_def_id, sum_segments) # and accumulate segments result |= seg_segments # Excluded segments are not required if excluded_segments_string: excluded_segments = segmentlist([]) for ifo, segment_name, version in split_segment_ids(excluded_segments_string.split(',')): sum_segments, seg_segments = build_segment_list(engine, gps_start_time, gps_end_time, ifo, segment_name, version) excluded_segments |= seg_segments result = result - excluded_segments result.coalesce() # Add the segments if write_segments: add_to_segment(doc, proc_id, new_seg_def_id, result) return result
[ "def", "run_query_segments", "(", "doc", ",", "proc_id", ",", "engine", ",", "gps_start_time", ",", "gps_end_time", ",", "included_segments_string", ",", "excluded_segments_string", "=", "None", ",", "write_segments", "=", "True", ",", "start_pad", "=", "0", ",", ...
Runs a segment query. This was originally part of ligolw_query_segments, but now is also used by ligolw_segments_from_cats. The write_segments option is provided so callers can coalesce segments obtained over sever invocations (as segments_from_cats does).
[ "Runs", "a", "segment", "query", ".", "This", "was", "originally", "part", "of", "ligolw_query_segments", "but", "now", "is", "also", "used", "by", "ligolw_segments_from_cats", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentdb/segmentdb_utils.py#L519-L564
gwastro/pycbc-glue
pycbc_glue/segmentdb/segmentdb_utils.py
split_segment_ids
def split_segment_ids(segment_ids): """Given an array of strings of the form ifo:name and ifo:name:version, returns an array of tuples of the form (ifo, name, version) where version may be None""" def split_segment_id(segment_id): temp = segment_id.split(':') if len(temp) == 2: temp.append(None) elif temp[2] == '*': temp[2] = None else: temp[2] = int(temp[2]) return temp return map(split_segment_id, segment_ids)
python
def split_segment_ids(segment_ids): """Given an array of strings of the form ifo:name and ifo:name:version, returns an array of tuples of the form (ifo, name, version) where version may be None""" def split_segment_id(segment_id): temp = segment_id.split(':') if len(temp) == 2: temp.append(None) elif temp[2] == '*': temp[2] = None else: temp[2] = int(temp[2]) return temp return map(split_segment_id, segment_ids)
[ "def", "split_segment_ids", "(", "segment_ids", ")", ":", "def", "split_segment_id", "(", "segment_id", ")", ":", "temp", "=", "segment_id", ".", "split", "(", "':'", ")", "if", "len", "(", "temp", ")", "==", "2", ":", "temp", ".", "append", "(", "None...
Given an array of strings of the form ifo:name and ifo:name:version, returns an array of tuples of the form (ifo, name, version) where version may be None
[ "Given", "an", "array", "of", "strings", "of", "the", "form", "ifo", ":", "name", "and", "ifo", ":", "name", ":", "version", "returns", "an", "array", "of", "tuples", "of", "the", "form", "(", "ifo", "name", "version", ")", "where", "version", "may", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentdb/segmentdb_utils.py#L568-L584
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/ligolw_add.py
url2path
def url2path(url): """ If url identifies a file on the local host, return the path to the file otherwise raise ValueError. """ scheme, host, path, nul, nul, nul = urlparse(url) if scheme.lower() in ("", "file") and host.lower() in ("", "localhost"): return path raise ValueError(url)
python
def url2path(url): """ If url identifies a file on the local host, return the path to the file otherwise raise ValueError. """ scheme, host, path, nul, nul, nul = urlparse(url) if scheme.lower() in ("", "file") and host.lower() in ("", "localhost"): return path raise ValueError(url)
[ "def", "url2path", "(", "url", ")", ":", "scheme", ",", "host", ",", "path", ",", "nul", ",", "nul", ",", "nul", "=", "urlparse", "(", "url", ")", "if", "scheme", ".", "lower", "(", ")", "in", "(", "\"\"", ",", "\"file\"", ")", "and", "host", "...
If url identifies a file on the local host, return the path to the file otherwise raise ValueError.
[ "If", "url", "identifies", "a", "file", "on", "the", "local", "host", "return", "the", "path", "to", "the", "file", "otherwise", "raise", "ValueError", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/ligolw_add.py#L58-L66
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/ligolw_add.py
remove_input
def remove_input(urls, preserves, verbose = False): """ Attempt to delete all files identified by the URLs in urls except any that are the same as the files in the preserves list. """ for path in map(url2path, urls): if any(os.path.samefile(path, preserve) for preserve in preserves): continue if verbose: print >>sys.stderr, "removing \"%s\" ..." % path try: os.remove(path) except: pass
python
def remove_input(urls, preserves, verbose = False): """ Attempt to delete all files identified by the URLs in urls except any that are the same as the files in the preserves list. """ for path in map(url2path, urls): if any(os.path.samefile(path, preserve) for preserve in preserves): continue if verbose: print >>sys.stderr, "removing \"%s\" ..." % path try: os.remove(path) except: pass
[ "def", "remove_input", "(", "urls", ",", "preserves", ",", "verbose", "=", "False", ")", ":", "for", "path", "in", "map", "(", "url2path", ",", "urls", ")", ":", "if", "any", "(", "os", ".", "path", ".", "samefile", "(", "path", ",", "preserve", ")...
Attempt to delete all files identified by the URLs in urls except any that are the same as the files in the preserves list.
[ "Attempt", "to", "delete", "all", "files", "identified", "by", "the", "URLs", "in", "urls", "except", "any", "that", "are", "the", "same", "as", "the", "files", "in", "the", "preserves", "list", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/ligolw_add.py#L69-L82
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/ligolw_add.py
reassign_ids
def reassign_ids(doc, verbose = False): """ Assign new IDs to all rows in all LSC tables in doc so that there are no collisions when the LIGO_LW elements are merged. """ # Can't simply run reassign_ids() on doc because we need to # construct a fresh old --> new mapping within each LIGO_LW block. for n, elem in enumerate(doc.childNodes): if verbose: print >>sys.stderr, "reassigning row IDs: %.1f%%\r" % (100.0 * (n + 1) / len(doc.childNodes)), if elem.tagName == ligolw.LIGO_LW.tagName: table.reassign_ids(elem) if verbose: print >>sys.stderr, "reassigning row IDs: 100.0%" return doc
python
def reassign_ids(doc, verbose = False): """ Assign new IDs to all rows in all LSC tables in doc so that there are no collisions when the LIGO_LW elements are merged. """ # Can't simply run reassign_ids() on doc because we need to # construct a fresh old --> new mapping within each LIGO_LW block. for n, elem in enumerate(doc.childNodes): if verbose: print >>sys.stderr, "reassigning row IDs: %.1f%%\r" % (100.0 * (n + 1) / len(doc.childNodes)), if elem.tagName == ligolw.LIGO_LW.tagName: table.reassign_ids(elem) if verbose: print >>sys.stderr, "reassigning row IDs: 100.0%" return doc
[ "def", "reassign_ids", "(", "doc", ",", "verbose", "=", "False", ")", ":", "# Can't simply run reassign_ids() on doc because we need to", "# construct a fresh old --> new mapping within each LIGO_LW block.", "for", "n", ",", "elem", "in", "enumerate", "(", "doc", ".", "chil...
Assign new IDs to all rows in all LSC tables in doc so that there are no collisions when the LIGO_LW elements are merged.
[ "Assign", "new", "IDs", "to", "all", "rows", "in", "all", "LSC", "tables", "in", "doc", "so", "that", "there", "are", "no", "collisions", "when", "the", "LIGO_LW", "elements", "are", "merged", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/ligolw_add.py#L94-L108
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/ligolw_add.py
merge_ligolws
def merge_ligolws(elem): """ Merge all LIGO_LW elements that are immediate children of elem by appending their children to the first. """ ligolws = [child for child in elem.childNodes if child.tagName == ligolw.LIGO_LW.tagName] if ligolws: dest = ligolws.pop(0) for src in ligolws: # copy children; LIGO_LW elements have no attributes map(dest.appendChild, src.childNodes) # unlink from parent if src.parentNode is not None: src.parentNode.removeChild(src) return elem
python
def merge_ligolws(elem): """ Merge all LIGO_LW elements that are immediate children of elem by appending their children to the first. """ ligolws = [child for child in elem.childNodes if child.tagName == ligolw.LIGO_LW.tagName] if ligolws: dest = ligolws.pop(0) for src in ligolws: # copy children; LIGO_LW elements have no attributes map(dest.appendChild, src.childNodes) # unlink from parent if src.parentNode is not None: src.parentNode.removeChild(src) return elem
[ "def", "merge_ligolws", "(", "elem", ")", ":", "ligolws", "=", "[", "child", "for", "child", "in", "elem", ".", "childNodes", "if", "child", ".", "tagName", "==", "ligolw", ".", "LIGO_LW", ".", "tagName", "]", "if", "ligolws", ":", "dest", "=", "ligolw...
Merge all LIGO_LW elements that are immediate children of elem by appending their children to the first.
[ "Merge", "all", "LIGO_LW", "elements", "that", "are", "immediate", "children", "of", "elem", "by", "appending", "their", "children", "to", "the", "first", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/ligolw_add.py#L111-L125
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/ligolw_add.py
compare_table_cols
def compare_table_cols(a, b): """ Return False if the two tables a and b have the same columns (ignoring order) according to LIGO LW name conventions, return True otherwise. """ return cmp(sorted((col.Name, col.Type) for col in a.getElementsByTagName(ligolw.Column.tagName)), sorted((col.Name, col.Type) for col in b.getElementsByTagName(ligolw.Column.tagName)))
python
def compare_table_cols(a, b): """ Return False if the two tables a and b have the same columns (ignoring order) according to LIGO LW name conventions, return True otherwise. """ return cmp(sorted((col.Name, col.Type) for col in a.getElementsByTagName(ligolw.Column.tagName)), sorted((col.Name, col.Type) for col in b.getElementsByTagName(ligolw.Column.tagName)))
[ "def", "compare_table_cols", "(", "a", ",", "b", ")", ":", "return", "cmp", "(", "sorted", "(", "(", "col", ".", "Name", ",", "col", ".", "Type", ")", "for", "col", "in", "a", ".", "getElementsByTagName", "(", "ligolw", ".", "Column", ".", "tagName",...
Return False if the two tables a and b have the same columns (ignoring order) according to LIGO LW name conventions, return True otherwise.
[ "Return", "False", "if", "the", "two", "tables", "a", "and", "b", "have", "the", "same", "columns", "(", "ignoring", "order", ")", "according", "to", "LIGO", "LW", "name", "conventions", "return", "True", "otherwise", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/ligolw_add.py#L128-L134
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/ligolw_add.py
merge_compatible_tables
def merge_compatible_tables(elem): """ Below the given element, find all Tables whose structure is described in lsctables, and merge compatible ones of like type. That is, merge all SnglBurstTables that have the same columns into a single table, etc.. """ for name in lsctables.TableByName.keys(): tables = table.getTablesByName(elem, name) if tables: dest = tables.pop(0) for src in tables: if src.Name != dest.Name: # src and dest have different names continue # src and dest have the same names if compare_table_cols(dest, src): # but they have different columns raise ValueError("document contains %s tables with incompatible columns" % dest.Name) # and the have the same columns # copy src rows to dest for row in src: dest.append(row) # unlink src from parent if src.parentNode is not None: src.parentNode.removeChild(src) return elem
python
def merge_compatible_tables(elem): """ Below the given element, find all Tables whose structure is described in lsctables, and merge compatible ones of like type. That is, merge all SnglBurstTables that have the same columns into a single table, etc.. """ for name in lsctables.TableByName.keys(): tables = table.getTablesByName(elem, name) if tables: dest = tables.pop(0) for src in tables: if src.Name != dest.Name: # src and dest have different names continue # src and dest have the same names if compare_table_cols(dest, src): # but they have different columns raise ValueError("document contains %s tables with incompatible columns" % dest.Name) # and the have the same columns # copy src rows to dest for row in src: dest.append(row) # unlink src from parent if src.parentNode is not None: src.parentNode.removeChild(src) return elem
[ "def", "merge_compatible_tables", "(", "elem", ")", ":", "for", "name", "in", "lsctables", ".", "TableByName", ".", "keys", "(", ")", ":", "tables", "=", "table", ".", "getTablesByName", "(", "elem", ",", "name", ")", "if", "tables", ":", "dest", "=", ...
Below the given element, find all Tables whose structure is described in lsctables, and merge compatible ones of like type. That is, merge all SnglBurstTables that have the same columns into a single table, etc..
[ "Below", "the", "given", "element", "find", "all", "Tables", "whose", "structure", "is", "described", "in", "lsctables", "and", "merge", "compatible", "ones", "of", "like", "type", ".", "That", "is", "merge", "all", "SnglBurstTables", "that", "have", "the", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/ligolw_add.py#L137-L163
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/ligolw_add.py
ligolw_add
def ligolw_add(xmldoc, urls, non_lsc_tables_ok = False, verbose = False, contenthandler = DefaultContentHandler): """ An implementation of the LIGO LW add algorithm. urls is a list of URLs (or filenames) to load, xmldoc is the XML document tree to which they should be added. """ # Input for n, url in enumerate(urls): if verbose: print >>sys.stderr, "%d/%d:" % (n + 1, len(urls)), utils.load_url(url, verbose = verbose, xmldoc = xmldoc, contenthandler = contenthandler) # ID reassignment if not non_lsc_tables_ok and lsctables.HasNonLSCTables(xmldoc): raise ValueError("non-LSC tables found. Use --non-lsc-tables-ok to force") reassign_ids(xmldoc, verbose = verbose) # Document merge if verbose: print >>sys.stderr, "merging elements ..." merge_ligolws(xmldoc) merge_compatible_tables(xmldoc) return xmldoc
python
def ligolw_add(xmldoc, urls, non_lsc_tables_ok = False, verbose = False, contenthandler = DefaultContentHandler): """ An implementation of the LIGO LW add algorithm. urls is a list of URLs (or filenames) to load, xmldoc is the XML document tree to which they should be added. """ # Input for n, url in enumerate(urls): if verbose: print >>sys.stderr, "%d/%d:" % (n + 1, len(urls)), utils.load_url(url, verbose = verbose, xmldoc = xmldoc, contenthandler = contenthandler) # ID reassignment if not non_lsc_tables_ok and lsctables.HasNonLSCTables(xmldoc): raise ValueError("non-LSC tables found. Use --non-lsc-tables-ok to force") reassign_ids(xmldoc, verbose = verbose) # Document merge if verbose: print >>sys.stderr, "merging elements ..." merge_ligolws(xmldoc) merge_compatible_tables(xmldoc) return xmldoc
[ "def", "ligolw_add", "(", "xmldoc", ",", "urls", ",", "non_lsc_tables_ok", "=", "False", ",", "verbose", "=", "False", ",", "contenthandler", "=", "DefaultContentHandler", ")", ":", "# Input", "for", "n", ",", "url", "in", "enumerate", "(", "urls", ")", ":...
An implementation of the LIGO LW add algorithm. urls is a list of URLs (or filenames) to load, xmldoc is the XML document tree to which they should be added.
[ "An", "implementation", "of", "the", "LIGO", "LW", "add", "algorithm", ".", "urls", "is", "a", "list", "of", "URLs", "(", "or", "filenames", ")", "to", "load", "xmldoc", "is", "the", "XML", "document", "tree", "to", "which", "they", "should", "be", "ad...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/ligolw_add.py#L184-L207
m110/climb
climb/core.py
Climb.run
def run(self): """Loops and executes commands in interactive mode.""" if self._skip_delims: delims = readline.get_completer_delims() for delim in self._skip_delims: delims = delims.replace(delim, '') readline.set_completer_delims(delims) readline.parse_and_bind("tab: complete") readline.set_completer(self._completer.complete) if self._history_file: # Ensure history file exists if not os.path.isfile(self._history_file): open(self._history_file, 'w').close() readline.read_history_file(self._history_file) self._running = True try: while self._running: try: command = input(self._format_prompt()) if command: result = self.execute(*shlex.split(command)) if result: print(result) except CLIException as exc: print(exc) except (KeyboardInterrupt, EOFError): self._running = False print() except Exception as exc: if self._verbose: traceback.print_exc() else: print(exc) finally: if self._history_file: readline.write_history_file(self._history_file)
python
def run(self): """Loops and executes commands in interactive mode.""" if self._skip_delims: delims = readline.get_completer_delims() for delim in self._skip_delims: delims = delims.replace(delim, '') readline.set_completer_delims(delims) readline.parse_and_bind("tab: complete") readline.set_completer(self._completer.complete) if self._history_file: # Ensure history file exists if not os.path.isfile(self._history_file): open(self._history_file, 'w').close() readline.read_history_file(self._history_file) self._running = True try: while self._running: try: command = input(self._format_prompt()) if command: result = self.execute(*shlex.split(command)) if result: print(result) except CLIException as exc: print(exc) except (KeyboardInterrupt, EOFError): self._running = False print() except Exception as exc: if self._verbose: traceback.print_exc() else: print(exc) finally: if self._history_file: readline.write_history_file(self._history_file)
[ "def", "run", "(", "self", ")", ":", "if", "self", ".", "_skip_delims", ":", "delims", "=", "readline", ".", "get_completer_delims", "(", ")", "for", "delim", "in", "self", ".", "_skip_delims", ":", "delims", "=", "delims", ".", "replace", "(", "delim", ...
Loops and executes commands in interactive mode.
[ "Loops", "and", "executes", "commands", "in", "interactive", "mode", "." ]
train
https://github.com/m110/climb/blob/0a35dfb94df48f85963490fbe0514c2ea80bff34/climb/core.py#L32-L71
m110/climb
climb/core.py
Climb.execute
def execute(self, *args): """Executes single command and returns result.""" command, kwargs = self.parse(*args) return self._commands.execute(command, **kwargs)
python
def execute(self, *args): """Executes single command and returns result.""" command, kwargs = self.parse(*args) return self._commands.execute(command, **kwargs)
[ "def", "execute", "(", "self", ",", "*", "args", ")", ":", "command", ",", "kwargs", "=", "self", ".", "parse", "(", "*", "args", ")", "return", "self", ".", "_commands", ".", "execute", "(", "command", ",", "*", "*", "kwargs", ")" ]
Executes single command and returns result.
[ "Executes", "single", "command", "and", "returns", "result", "." ]
train
https://github.com/m110/climb/blob/0a35dfb94df48f85963490fbe0514c2ea80bff34/climb/core.py#L76-L79
Gjum/agarnet
agarnet/gcommer.py
gcommer_claim
def gcommer_claim(address=None): """ Try to get a token for this server address. `address` has to be ip:port, e.g. `'1.2.3.4:1234'` Returns tuple(address, token) """ if not address: # get token for any world # this is only useful for testing, # because that is exactly what m.agar.io does url = 'http://at.gcommer.com/status' text = urllib.request.urlopen(url).read().decode() j = json.loads(text) for address, num in j['status'].items(): if num > 0: break # address is now one of the listed servers with tokens url = 'http://at.gcommer.com/claim?server=%s' % address text = urllib.request.urlopen(url).read().decode() j = json.loads(text) token = j['token'] return address, token
python
def gcommer_claim(address=None): """ Try to get a token for this server address. `address` has to be ip:port, e.g. `'1.2.3.4:1234'` Returns tuple(address, token) """ if not address: # get token for any world # this is only useful for testing, # because that is exactly what m.agar.io does url = 'http://at.gcommer.com/status' text = urllib.request.urlopen(url).read().decode() j = json.loads(text) for address, num in j['status'].items(): if num > 0: break # address is now one of the listed servers with tokens url = 'http://at.gcommer.com/claim?server=%s' % address text = urllib.request.urlopen(url).read().decode() j = json.loads(text) token = j['token'] return address, token
[ "def", "gcommer_claim", "(", "address", "=", "None", ")", ":", "if", "not", "address", ":", "# get token for any world", "# this is only useful for testing,", "# because that is exactly what m.agar.io does", "url", "=", "'http://at.gcommer.com/status'", "text", "=", "urllib",...
Try to get a token for this server address. `address` has to be ip:port, e.g. `'1.2.3.4:1234'` Returns tuple(address, token)
[ "Try", "to", "get", "a", "token", "for", "this", "server", "address", ".", "address", "has", "to", "be", "ip", ":", "port", "e", ".", "g", ".", "1", ".", "2", ".", "3", ".", "4", ":", "1234", "Returns", "tuple", "(", "address", "token", ")" ]
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/gcommer.py#L9-L29
Gjum/agarnet
agarnet/gcommer.py
gcommer_donate
def gcommer_donate(address, token, *_): """ Donate a token for this server address. `address` and `token` should be the return values from find_server(). """ token = urllib.request.quote(token) url = 'http://at.gcommer.com/donate?server=%s&token=%s' % (address, token) response = urllib.request.urlopen(url).read().decode() return json.loads(response)['msg']
python
def gcommer_donate(address, token, *_): """ Donate a token for this server address. `address` and `token` should be the return values from find_server(). """ token = urllib.request.quote(token) url = 'http://at.gcommer.com/donate?server=%s&token=%s' % (address, token) response = urllib.request.urlopen(url).read().decode() return json.loads(response)['msg']
[ "def", "gcommer_donate", "(", "address", ",", "token", ",", "*", "_", ")", ":", "token", "=", "urllib", ".", "request", ".", "quote", "(", "token", ")", "url", "=", "'http://at.gcommer.com/donate?server=%s&token=%s'", "%", "(", "address", ",", "token", ")", ...
Donate a token for this server address. `address` and `token` should be the return values from find_server().
[ "Donate", "a", "token", "for", "this", "server", "address", ".", "address", "and", "token", "should", "be", "the", "return", "values", "from", "find_server", "()", "." ]
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/gcommer.py#L32-L40
Gjum/agarnet
agarnet/gcommer.py
gcommer_donate_threaded
def gcommer_donate_threaded(interval=5, region='EU-London', mode=None): """ Run a daemon thread that requests and donates a token every `interval` seconds. """ def donate_thread(): while 1: gcommer_donate(*find_server(region, mode)) time.sleep(interval) Thread(target=donate_thread, daemon=True).start()
python
def gcommer_donate_threaded(interval=5, region='EU-London', mode=None): """ Run a daemon thread that requests and donates a token every `interval` seconds. """ def donate_thread(): while 1: gcommer_donate(*find_server(region, mode)) time.sleep(interval) Thread(target=donate_thread, daemon=True).start()
[ "def", "gcommer_donate_threaded", "(", "interval", "=", "5", ",", "region", "=", "'EU-London'", ",", "mode", "=", "None", ")", ":", "def", "donate_thread", "(", ")", ":", "while", "1", ":", "gcommer_donate", "(", "*", "find_server", "(", "region", ",", "...
Run a daemon thread that requests and donates a token every `interval` seconds.
[ "Run", "a", "daemon", "thread", "that", "requests", "and", "donates", "a", "token", "every", "interval", "seconds", "." ]
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/gcommer.py#L43-L53
avara1986/ardy
ardy/core/deploy/deploy.py
Deploy.run
def run(self, src_project=None, path_to_zip_file=None): """Run deploy the lambdas defined in our project. Steps: * Build Artefact * Read file or deploy to S3. It's defined in config["deploy"]["deploy_method"] * Reload conf with deploy changes * check lambda if exist * Create Lambda * Update Lambda :param src_project: str. Name of the folder or path of the project where our code lives :param path_to_zip_file: str. :return: bool """ if path_to_zip_file: code = self.set_artefact_path(path_to_zip_file) elif not self.config["deploy"].get("deploy_file", False): code = self.build_artefact(src_project) else: code = self.set_artefact_path(self.config["deploy"].get("deploy_file")) self.set_artefact(code=code) # Reload conf because each lambda conf need to read again the global conf self.config.reload_conf() self.deploy() return True
python
def run(self, src_project=None, path_to_zip_file=None): """Run deploy the lambdas defined in our project. Steps: * Build Artefact * Read file or deploy to S3. It's defined in config["deploy"]["deploy_method"] * Reload conf with deploy changes * check lambda if exist * Create Lambda * Update Lambda :param src_project: str. Name of the folder or path of the project where our code lives :param path_to_zip_file: str. :return: bool """ if path_to_zip_file: code = self.set_artefact_path(path_to_zip_file) elif not self.config["deploy"].get("deploy_file", False): code = self.build_artefact(src_project) else: code = self.set_artefact_path(self.config["deploy"].get("deploy_file")) self.set_artefact(code=code) # Reload conf because each lambda conf need to read again the global conf self.config.reload_conf() self.deploy() return True
[ "def", "run", "(", "self", ",", "src_project", "=", "None", ",", "path_to_zip_file", "=", "None", ")", ":", "if", "path_to_zip_file", ":", "code", "=", "self", ".", "set_artefact_path", "(", "path_to_zip_file", ")", "elif", "not", "self", ".", "config", "[...
Run deploy the lambdas defined in our project. Steps: * Build Artefact * Read file or deploy to S3. It's defined in config["deploy"]["deploy_method"] * Reload conf with deploy changes * check lambda if exist * Create Lambda * Update Lambda :param src_project: str. Name of the folder or path of the project where our code lives :param path_to_zip_file: str. :return: bool
[ "Run", "deploy", "the", "lambdas", "defined", "in", "our", "project", ".", "Steps", ":", "*", "Build", "Artefact", "*", "Read", "file", "or", "deploy", "to", "S3", ".", "It", "s", "defined", "in", "config", "[", "deploy", "]", "[", "deploy_method", "]"...
train
https://github.com/avara1986/ardy/blob/1942413f12e117b991278cada69f478474b9b94b/ardy/core/deploy/deploy.py#L46-L74
avara1986/ardy
ardy/core/deploy/deploy.py
Deploy.set_artefact_path
def set_artefact_path(self, path_to_zip_file): """ Set the route to the local file to deploy :param path_to_zip_file: :return: """ self.config["deploy"]["deploy_file"] = path_to_zip_file return {'ZipFile': self.build.read(self.config["deploy"]["deploy_file"])}
python
def set_artefact_path(self, path_to_zip_file): """ Set the route to the local file to deploy :param path_to_zip_file: :return: """ self.config["deploy"]["deploy_file"] = path_to_zip_file return {'ZipFile': self.build.read(self.config["deploy"]["deploy_file"])}
[ "def", "set_artefact_path", "(", "self", ",", "path_to_zip_file", ")", ":", "self", ".", "config", "[", "\"deploy\"", "]", "[", "\"deploy_file\"", "]", "=", "path_to_zip_file", "return", "{", "'ZipFile'", ":", "self", ".", "build", ".", "read", "(", "self", ...
Set the route to the local file to deploy :param path_to_zip_file: :return:
[ "Set", "the", "route", "to", "the", "local", "file", "to", "deploy", ":", "param", "path_to_zip_file", ":", ":", "return", ":" ]
train
https://github.com/avara1986/ardy/blob/1942413f12e117b991278cada69f478474b9b94b/ardy/core/deploy/deploy.py#L76-L83
avara1986/ardy
ardy/core/deploy/deploy.py
Deploy.build_artefact
def build_artefact(self, src_project=None): """Run deploy the lambdas defined in our project. Steps: * Build Artefact * Read file or deploy to S3. It's defined in config["deploy"]["deploy_method"] :param src_project: str. Name of the folder or path of the project where our code lives :return: bool """ path_to_zip_file = self.build.run(src_project or self.config.get_projectdir()) self.set_artefact_path(path_to_zip_file) deploy_method = self.config["deploy"]["deploy_method"] if deploy_method == "S3": deploy_bucket = self.config["deploy"]["deploy_bucket"] bucket = self.awss3.Bucket(deploy_bucket) try: self.awss3.meta.client.head_bucket(Bucket=deploy_bucket) except ClientError as e: if e.response['Error']['Code'] == "404" or e.response['Error']['Code'] == "NoSuchBucket": region = self.config.get("aws_credentials", {}).get("region", None) logger.info( "Bucket not exist. Creating new one with name {} in region {}".format(deploy_bucket, region)) bucket_conf = {} if region: bucket_conf = {"CreateBucketConfiguration": {'LocationConstraint': region}} bucket.wait_until_not_exists() bucket.create(**bucket_conf) bucket.wait_until_exists() else: # TODO: handle other errors there pass s3_keyfile = self.config["deploy"]["deploy_file"].split(os.path.sep)[-1] bucket.put_object( Key=s3_keyfile, Body=self.build.read(self.config["deploy"]["deploy_file"]) ) code = {'S3Bucket': deploy_bucket, 'S3Key': s3_keyfile, } elif deploy_method == "FILE": code = {'ZipFile': self.build.read(self.config["deploy"]["deploy_file"])} else: raise Exception("No deploy_method in config") return code
python
def build_artefact(self, src_project=None): """Run deploy the lambdas defined in our project. Steps: * Build Artefact * Read file or deploy to S3. It's defined in config["deploy"]["deploy_method"] :param src_project: str. Name of the folder or path of the project where our code lives :return: bool """ path_to_zip_file = self.build.run(src_project or self.config.get_projectdir()) self.set_artefact_path(path_to_zip_file) deploy_method = self.config["deploy"]["deploy_method"] if deploy_method == "S3": deploy_bucket = self.config["deploy"]["deploy_bucket"] bucket = self.awss3.Bucket(deploy_bucket) try: self.awss3.meta.client.head_bucket(Bucket=deploy_bucket) except ClientError as e: if e.response['Error']['Code'] == "404" or e.response['Error']['Code'] == "NoSuchBucket": region = self.config.get("aws_credentials", {}).get("region", None) logger.info( "Bucket not exist. Creating new one with name {} in region {}".format(deploy_bucket, region)) bucket_conf = {} if region: bucket_conf = {"CreateBucketConfiguration": {'LocationConstraint': region}} bucket.wait_until_not_exists() bucket.create(**bucket_conf) bucket.wait_until_exists() else: # TODO: handle other errors there pass s3_keyfile = self.config["deploy"]["deploy_file"].split(os.path.sep)[-1] bucket.put_object( Key=s3_keyfile, Body=self.build.read(self.config["deploy"]["deploy_file"]) ) code = {'S3Bucket': deploy_bucket, 'S3Key': s3_keyfile, } elif deploy_method == "FILE": code = {'ZipFile': self.build.read(self.config["deploy"]["deploy_file"])} else: raise Exception("No deploy_method in config") return code
[ "def", "build_artefact", "(", "self", ",", "src_project", "=", "None", ")", ":", "path_to_zip_file", "=", "self", ".", "build", ".", "run", "(", "src_project", "or", "self", ".", "config", ".", "get_projectdir", "(", ")", ")", "self", ".", "set_artefact_pa...
Run deploy the lambdas defined in our project. Steps: * Build Artefact * Read file or deploy to S3. It's defined in config["deploy"]["deploy_method"] :param src_project: str. Name of the folder or path of the project where our code lives :return: bool
[ "Run", "deploy", "the", "lambdas", "defined", "in", "our", "project", ".", "Steps", ":", "*", "Build", "Artefact", "*", "Read", "file", "or", "deploy", "to", "S3", ".", "It", "s", "defined", "in", "config", "[", "deploy", "]", "[", "deploy_method", "]"...
train
https://github.com/avara1986/ardy/blob/1942413f12e117b991278cada69f478474b9b94b/ardy/core/deploy/deploy.py#L94-L142
avara1986/ardy
ardy/core/deploy/deploy.py
Deploy.deploy
def deploy(self): """Upload code to AWS Lambda. To use this method, first, must set the zip file with code with `self.set_artefact(code=code)`. Check all lambdas in our config file or the functions passed in command line and exist in our config file. If the function is upload correctly, update/create versions, alias and triggers :return: True """ lambdas_deployed = [] for lambda_funcion in self.config.get_lambdas(): start_deploy = not len(self.lambdas_to_deploy) or \ lambda_funcion["FunctionNameOrigin"] in self.lambdas_to_deploy if start_deploy: lambdas_deployed.append(lambda_funcion["FunctionName"]) conf = lambda_funcion.get_deploy_conf() response = self.remote_get_lambda(**conf) if response: remote_conf = response["Configuration"] # TODO: Diferences sometimes not return all values, check it! logger.info("Diferences:") diffkeys = [k for k in remote_conf if conf.get(k, False) != remote_conf.get(k, True) and k not in ['Code', ]] for k in diffkeys: logger.info((k, ':', conf.get(k, ""), '->', remote_conf.get(k, ""))) logger.info("START to update funcion {}".format(conf["FunctionName"])) self.remote_update_conf_lambada(**conf) result = self.remote_update_code_lambada(**conf) logger.debug("Funcion {} updated {}".format(conf["FunctionName"], result)) else: logger.info("START to create funcion {}".format(lambda_funcion["FunctionName"])) result = self.remote_create_lambada(**conf) logger.debug("Funcion {} created {}".format(conf["FunctionName"], result)) if self.is_client_result_ok(result): # Check and publish version version = "LATEST" if self.config["deploy"].get("use_version", False): logger.info("Publish new version of {} with conf {}".format( lambda_funcion["FunctionName"], json.dumps(conf, indent=4, sort_keys=True) )) result = self.remote_publish_version(**conf) version = result["Version"] logger.info("Published version {}: {}".format( version, json.dumps(result, indent=4, sort_keys=True) )) # Check and publish alias if self.config["deploy"].get("use_alias", False): alias_conf = { "FunctionName": conf["FunctionName"], "Description": conf["Description"], "FunctionVersion": version, } if self.config.get_environment(): alias_conf.update({"Name": self.config.get_environment()}) else: alias_conf.update({"Name": conf["FunctionName"]}) logger.info("Update alias of {} with conf {}".format( lambda_funcion["FunctionName"], json.dumps(alias_conf, indent=4, sort_keys=True) )) result = self.remote_update_alias(**alias_conf) logger.info("Updated alias {}: {}".format(conf["FunctionName"], json.dumps(result, indent=4, sort_keys=True) )) # Check and publish triggers logger.info("Updating Triggers for fuction {}".format(lambda_funcion["FunctionName"])) if lambda_funcion.get("triggers", False): for trigger in lambda_funcion["triggers"].keys(): trigger_object = get_trigger(trigger, lambda_funcion, result["FunctionArn"]) trigger_object.put() if lambdas_deployed: logger.info("Deploy finished. Created/updated lambdas {}".format(", ".join(lambdas_deployed))) else: logger.info("No lambdas found to deploy") # TODO: check errors to return correct value return True
python
def deploy(self): """Upload code to AWS Lambda. To use this method, first, must set the zip file with code with `self.set_artefact(code=code)`. Check all lambdas in our config file or the functions passed in command line and exist in our config file. If the function is upload correctly, update/create versions, alias and triggers :return: True """ lambdas_deployed = [] for lambda_funcion in self.config.get_lambdas(): start_deploy = not len(self.lambdas_to_deploy) or \ lambda_funcion["FunctionNameOrigin"] in self.lambdas_to_deploy if start_deploy: lambdas_deployed.append(lambda_funcion["FunctionName"]) conf = lambda_funcion.get_deploy_conf() response = self.remote_get_lambda(**conf) if response: remote_conf = response["Configuration"] # TODO: Diferences sometimes not return all values, check it! logger.info("Diferences:") diffkeys = [k for k in remote_conf if conf.get(k, False) != remote_conf.get(k, True) and k not in ['Code', ]] for k in diffkeys: logger.info((k, ':', conf.get(k, ""), '->', remote_conf.get(k, ""))) logger.info("START to update funcion {}".format(conf["FunctionName"])) self.remote_update_conf_lambada(**conf) result = self.remote_update_code_lambada(**conf) logger.debug("Funcion {} updated {}".format(conf["FunctionName"], result)) else: logger.info("START to create funcion {}".format(lambda_funcion["FunctionName"])) result = self.remote_create_lambada(**conf) logger.debug("Funcion {} created {}".format(conf["FunctionName"], result)) if self.is_client_result_ok(result): # Check and publish version version = "LATEST" if self.config["deploy"].get("use_version", False): logger.info("Publish new version of {} with conf {}".format( lambda_funcion["FunctionName"], json.dumps(conf, indent=4, sort_keys=True) )) result = self.remote_publish_version(**conf) version = result["Version"] logger.info("Published version {}: {}".format( version, json.dumps(result, indent=4, sort_keys=True) )) # Check and publish alias if self.config["deploy"].get("use_alias", False): alias_conf = { "FunctionName": conf["FunctionName"], "Description": conf["Description"], "FunctionVersion": version, } if self.config.get_environment(): alias_conf.update({"Name": self.config.get_environment()}) else: alias_conf.update({"Name": conf["FunctionName"]}) logger.info("Update alias of {} with conf {}".format( lambda_funcion["FunctionName"], json.dumps(alias_conf, indent=4, sort_keys=True) )) result = self.remote_update_alias(**alias_conf) logger.info("Updated alias {}: {}".format(conf["FunctionName"], json.dumps(result, indent=4, sort_keys=True) )) # Check and publish triggers logger.info("Updating Triggers for fuction {}".format(lambda_funcion["FunctionName"])) if lambda_funcion.get("triggers", False): for trigger in lambda_funcion["triggers"].keys(): trigger_object = get_trigger(trigger, lambda_funcion, result["FunctionArn"]) trigger_object.put() if lambdas_deployed: logger.info("Deploy finished. Created/updated lambdas {}".format(", ".join(lambdas_deployed))) else: logger.info("No lambdas found to deploy") # TODO: check errors to return correct value return True
[ "def", "deploy", "(", "self", ")", ":", "lambdas_deployed", "=", "[", "]", "for", "lambda_funcion", "in", "self", ".", "config", ".", "get_lambdas", "(", ")", ":", "start_deploy", "=", "not", "len", "(", "self", ".", "lambdas_to_deploy", ")", "or", "lamb...
Upload code to AWS Lambda. To use this method, first, must set the zip file with code with `self.set_artefact(code=code)`. Check all lambdas in our config file or the functions passed in command line and exist in our config file. If the function is upload correctly, update/create versions, alias and triggers :return: True
[ "Upload", "code", "to", "AWS", "Lambda", ".", "To", "use", "this", "method", "first", "must", "set", "the", "zip", "file", "with", "code", "with", "self", ".", "set_artefact", "(", "code", "=", "code", ")", ".", "Check", "all", "lambdas", "in", "our", ...
train
https://github.com/avara1986/ardy/blob/1942413f12e117b991278cada69f478474b9b94b/ardy/core/deploy/deploy.py#L144-L231
gwastro/pycbc-glue
pycbc_glue/ldbd.py
Xlator._make_regex
def _make_regex(self): """ Build a re object based on keys in the current dictionary """ return re.compile("|".join(map(re.escape, self.keys())))
python
def _make_regex(self): """ Build a re object based on keys in the current dictionary """ return re.compile("|".join(map(re.escape, self.keys())))
[ "def", "_make_regex", "(", "self", ")", ":", "return", "re", ".", "compile", "(", "\"|\"", ".", "join", "(", "map", "(", "re", ".", "escape", ",", "self", ".", "keys", "(", ")", ")", ")", ")" ]
Build a re object based on keys in the current dictionary
[ "Build", "a", "re", "object", "based", "on", "keys", "in", "the", "current", "dictionary" ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ldbd.py#L80-L84
gwastro/pycbc-glue
pycbc_glue/ldbd.py
UniqueIds.lookup
def lookup(self,istring): """ istring = the ilwd:char string corresponding to a unique id """ try: return self.uqids[istring] except KeyError: curs = self.curs curs.execute('VALUES BLOB(GENERATE_UNIQUE())') self.uqids[istring] = curs.fetchone()[0] return self.uqids[istring]
python
def lookup(self,istring): """ istring = the ilwd:char string corresponding to a unique id """ try: return self.uqids[istring] except KeyError: curs = self.curs curs.execute('VALUES BLOB(GENERATE_UNIQUE())') self.uqids[istring] = curs.fetchone()[0] return self.uqids[istring]
[ "def", "lookup", "(", "self", ",", "istring", ")", ":", "try", ":", "return", "self", ".", "uqids", "[", "istring", "]", "except", "KeyError", ":", "curs", "=", "self", ".", "curs", "curs", ".", "execute", "(", "'VALUES BLOB(GENERATE_UNIQUE())'", ")", "s...
istring = the ilwd:char string corresponding to a unique id
[ "istring", "=", "the", "ilwd", ":", "char", "string", "corresponding", "to", "a", "unique", "id" ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ldbd.py#L143-L153
gwastro/pycbc-glue
pycbc_glue/ldbd.py
LIGOLwParser.__lstring
def __lstring(self,lstr): """ Returns a parsed lstring by stripping out and instances of the escaped delimiter. Sometimes the raw lstring has whitespace and a double quote at the beginning or end. If present, these are removed. """ lstr = self.llsrx.sub('',lstr.encode('ascii')) lstr = self.rlsrx.sub('',lstr) lstr = self.xmltostr.xlat(lstr) lstr = self.dlmrx.sub(',',lstr) return lstr
python
def __lstring(self,lstr): """ Returns a parsed lstring by stripping out and instances of the escaped delimiter. Sometimes the raw lstring has whitespace and a double quote at the beginning or end. If present, these are removed. """ lstr = self.llsrx.sub('',lstr.encode('ascii')) lstr = self.rlsrx.sub('',lstr) lstr = self.xmltostr.xlat(lstr) lstr = self.dlmrx.sub(',',lstr) return lstr
[ "def", "__lstring", "(", "self", ",", "lstr", ")", ":", "lstr", "=", "self", ".", "llsrx", ".", "sub", "(", "''", ",", "lstr", ".", "encode", "(", "'ascii'", ")", ")", "lstr", "=", "self", ".", "rlsrx", ".", "sub", "(", "''", ",", "lstr", ")", ...
Returns a parsed lstring by stripping out and instances of the escaped delimiter. Sometimes the raw lstring has whitespace and a double quote at the beginning or end. If present, these are removed.
[ "Returns", "a", "parsed", "lstring", "by", "stripping", "out", "and", "instances", "of", "the", "escaped", "delimiter", ".", "Sometimes", "the", "raw", "lstring", "has", "whitespace", "and", "a", "double", "quote", "at", "the", "beginning", "or", "end", ".",...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ldbd.py#L192-L203
gwastro/pycbc-glue
pycbc_glue/ldbd.py
LIGOLwParser.__ilwdchar
def __ilwdchar(self,istr): """ If the ilwd:char field contains octal data, it is translated to a binary string and returned. Otherwise a lookup is done in the unique id dictionary and a binary string containing the correct unique id is returned. """ istr_orig = istr istr = self.licrx.sub('',istr.encode('ascii')) istr = self.ricrx.sub('',istr) if self.octrx.match(istr): exec "istr = '"+istr+"'" # if the DB2 module is loaded, the string should be converted # to an instance of the DB2.Binary class. If not, leave it as # a string containing binary data. try: istr = DB2.Binary(istr) except: pass else: try: istr = self.unique.lookup(istr) except AttributeError: if not self.unique: istr = istr_orig else: raise LIGOLwParseError, 'unique id table has not been initialized' return istr
python
def __ilwdchar(self,istr): """ If the ilwd:char field contains octal data, it is translated to a binary string and returned. Otherwise a lookup is done in the unique id dictionary and a binary string containing the correct unique id is returned. """ istr_orig = istr istr = self.licrx.sub('',istr.encode('ascii')) istr = self.ricrx.sub('',istr) if self.octrx.match(istr): exec "istr = '"+istr+"'" # if the DB2 module is loaded, the string should be converted # to an instance of the DB2.Binary class. If not, leave it as # a string containing binary data. try: istr = DB2.Binary(istr) except: pass else: try: istr = self.unique.lookup(istr) except AttributeError: if not self.unique: istr = istr_orig else: raise LIGOLwParseError, 'unique id table has not been initialized' return istr
[ "def", "__ilwdchar", "(", "self", ",", "istr", ")", ":", "istr_orig", "=", "istr", "istr", "=", "self", ".", "licrx", ".", "sub", "(", "''", ",", "istr", ".", "encode", "(", "'ascii'", ")", ")", "istr", "=", "self", ".", "ricrx", ".", "sub", "(",...
If the ilwd:char field contains octal data, it is translated to a binary string and returned. Otherwise a lookup is done in the unique id dictionary and a binary string containing the correct unique id is returned.
[ "If", "the", "ilwd", ":", "char", "field", "contains", "octal", "data", "it", "is", "translated", "to", "a", "binary", "string", "and", "returned", ".", "Otherwise", "a", "lookup", "is", "done", "in", "the", "unique", "id", "dictionary", "and", "a", "bin...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ldbd.py#L205-L232
gwastro/pycbc-glue
pycbc_glue/ldbd.py
LIGOLwParser.parsetuple
def parsetuple(self,xmltuple): """ Parse an XML tuple returned by pyRXP into a dictionary of LIGO metadata elements. The dictionary contains one entry for each table found in the XML tuple. """ # first extract all the table and columns from the tuple from the # children of the ligo lightweight parent tuple table = {} tupleidx = 0 for tag in xmltuple[2]: if tag[0] == 'Table' or tag[0] == 'table': tab = tag[1]['Name'].encode('ascii').lower() try: tab = self.tabrx.match(tab).group(2) except AttributeError: raise LIGOLwParseError, 'unable to parse a valid table name '+tab # initalize the table dictionary for this table table[tab] = { 'pos' : tupleidx, 'column' : {}, 'stream' : (), 'query' : '' } # parse for columns in the tables children # look for the column name and type in the attributes # store the index in which the columns were found as # we need this to decode the stream later for subtag in tag[2]: if subtag[0] == 'Column' or subtag[0] == 'column': col = subtag[1]['Name'].encode('ascii').lower() try: col = self.colrx.match(col).group(3) except AttributeError: raise LIGOLwParseError, 'unable to parse a valid column name '+col try: typ = subtag[1]['Type'].encode('ascii').lower() except KeyError: raise LIGOLwParseError, 'type is missing for column '+col table[tab]['column'][col] = typ table[tab].setdefault('orderedcol',[]).append(col) tupleidx += 1 # now iterate the dictionary of tables we have created looking for streams for tab in table.keys(): for tag in xmltuple[2][table[tab]['pos']][2]: if tag[0] == 'Stream' or tag[0] == 'stream': # store the stream delimiter and create the esacpe regex try: delim = tag[1]['Delimiter'].encode('ascii') except KeyError: raise LIGOLwParseError, 'stream is missing delimiter' if delim != ',': raise LIGOLwParseError, 'unable to handle stream delimiter: '+delim # If the result set is empty tag[2] is an empty array, which causes # the next step to fail. Add an empty string in this case. if len(tag[2]) == 0: tag[2].append("") # strip newlines from the stream and parse it stream = csv.reader([re.sub(r'\n','',tag[2][0])],LIGOLWStream).next() # turn the csv stream into a list of lists slen = len(stream) ntyp = len(table[tab]['column']) mlen, lft = divmod(slen,ntyp) if lft != 0: raise LIGOLwParseError, 'invalid stream length for given columns' lst = [[None] * ntyp for i in range(mlen)] # translate the stream data to the correct data types for i in range(slen): j, k = divmod(i,ntyp) try: thiscol = table[tab]['orderedcol'][k] if len( stream[i] ) == 0: lst[j][k] = None else: lst[j][k] = self.types[table[tab]['column'][thiscol]](stream[i]) except (KeyError, ValueError), errmsg: msg = "stream translation error (%s) " % str(errmsg) msg += "for column %s in table %s: %s -> %s" \ % (tab,thiscol,stream[i],str(table[tab])) raise LIGOLwParseError, msg table[tab]['stream'] = map(tuple,lst) # return the created table to the caller return table
python
def parsetuple(self,xmltuple): """ Parse an XML tuple returned by pyRXP into a dictionary of LIGO metadata elements. The dictionary contains one entry for each table found in the XML tuple. """ # first extract all the table and columns from the tuple from the # children of the ligo lightweight parent tuple table = {} tupleidx = 0 for tag in xmltuple[2]: if tag[0] == 'Table' or tag[0] == 'table': tab = tag[1]['Name'].encode('ascii').lower() try: tab = self.tabrx.match(tab).group(2) except AttributeError: raise LIGOLwParseError, 'unable to parse a valid table name '+tab # initalize the table dictionary for this table table[tab] = { 'pos' : tupleidx, 'column' : {}, 'stream' : (), 'query' : '' } # parse for columns in the tables children # look for the column name and type in the attributes # store the index in which the columns were found as # we need this to decode the stream later for subtag in tag[2]: if subtag[0] == 'Column' or subtag[0] == 'column': col = subtag[1]['Name'].encode('ascii').lower() try: col = self.colrx.match(col).group(3) except AttributeError: raise LIGOLwParseError, 'unable to parse a valid column name '+col try: typ = subtag[1]['Type'].encode('ascii').lower() except KeyError: raise LIGOLwParseError, 'type is missing for column '+col table[tab]['column'][col] = typ table[tab].setdefault('orderedcol',[]).append(col) tupleidx += 1 # now iterate the dictionary of tables we have created looking for streams for tab in table.keys(): for tag in xmltuple[2][table[tab]['pos']][2]: if tag[0] == 'Stream' or tag[0] == 'stream': # store the stream delimiter and create the esacpe regex try: delim = tag[1]['Delimiter'].encode('ascii') except KeyError: raise LIGOLwParseError, 'stream is missing delimiter' if delim != ',': raise LIGOLwParseError, 'unable to handle stream delimiter: '+delim # If the result set is empty tag[2] is an empty array, which causes # the next step to fail. Add an empty string in this case. if len(tag[2]) == 0: tag[2].append("") # strip newlines from the stream and parse it stream = csv.reader([re.sub(r'\n','',tag[2][0])],LIGOLWStream).next() # turn the csv stream into a list of lists slen = len(stream) ntyp = len(table[tab]['column']) mlen, lft = divmod(slen,ntyp) if lft != 0: raise LIGOLwParseError, 'invalid stream length for given columns' lst = [[None] * ntyp for i in range(mlen)] # translate the stream data to the correct data types for i in range(slen): j, k = divmod(i,ntyp) try: thiscol = table[tab]['orderedcol'][k] if len( stream[i] ) == 0: lst[j][k] = None else: lst[j][k] = self.types[table[tab]['column'][thiscol]](stream[i]) except (KeyError, ValueError), errmsg: msg = "stream translation error (%s) " % str(errmsg) msg += "for column %s in table %s: %s -> %s" \ % (tab,thiscol,stream[i],str(table[tab])) raise LIGOLwParseError, msg table[tab]['stream'] = map(tuple,lst) # return the created table to the caller return table
[ "def", "parsetuple", "(", "self", ",", "xmltuple", ")", ":", "# first extract all the table and columns from the tuple from the", "# children of the ligo lightweight parent tuple", "table", "=", "{", "}", "tupleidx", "=", "0", "for", "tag", "in", "xmltuple", "[", "2", "...
Parse an XML tuple returned by pyRXP into a dictionary of LIGO metadata elements. The dictionary contains one entry for each table found in the XML tuple.
[ "Parse", "an", "XML", "tuple", "returned", "by", "pyRXP", "into", "a", "dictionary", "of", "LIGO", "metadata", "elements", ".", "The", "dictionary", "contains", "one", "entry", "for", "each", "table", "found", "in", "the", "XML", "tuple", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ldbd.py#L234-L323
gwastro/pycbc-glue
pycbc_glue/ldbd.py
LIGOMetadata.parse
def parse(self,xml): """ Parses an XML document into a form read for insertion into the database xml = the xml document to be parsed """ if not self.xmlparser: raise LIGOLwParseError, "pyRXP parser not initialized" if not self.lwtparser: raise LIGOLwParseError, "LIGO_LW tuple parser not initialized" xml = "".join([x.strip() for x in xml.split('\n')]) ligolwtup = self.xmlparser(xml) if self.curs: self.lwtparser.unique = UniqueIds(self.curs) self.table = self.lwtparser.parsetuple(ligolwtup)
python
def parse(self,xml): """ Parses an XML document into a form read for insertion into the database xml = the xml document to be parsed """ if not self.xmlparser: raise LIGOLwParseError, "pyRXP parser not initialized" if not self.lwtparser: raise LIGOLwParseError, "LIGO_LW tuple parser not initialized" xml = "".join([x.strip() for x in xml.split('\n')]) ligolwtup = self.xmlparser(xml) if self.curs: self.lwtparser.unique = UniqueIds(self.curs) self.table = self.lwtparser.parsetuple(ligolwtup)
[ "def", "parse", "(", "self", ",", "xml", ")", ":", "if", "not", "self", ".", "xmlparser", ":", "raise", "LIGOLwParseError", ",", "\"pyRXP parser not initialized\"", "if", "not", "self", ".", "lwtparser", ":", "raise", "LIGOLwParseError", ",", "\"LIGO_LW tuple pa...
Parses an XML document into a form read for insertion into the database xml = the xml document to be parsed
[ "Parses", "an", "XML", "document", "into", "a", "form", "read", "for", "insertion", "into", "the", "database" ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ldbd.py#L368-L382
gwastro/pycbc-glue
pycbc_glue/ldbd.py
LIGOMetadata.add_lfn
def add_lfn(self,lfn): """ Add an LFN table to a parsed LIGO_LW XML document. lfn = lfn to be added """ if len(self.table['process']['stream']) > 1: msg = "cannot add lfn to table with more than one process" raise LIGOLwParseError, msg # get the process_id from the process table pid_col = self.table['process']['orderedcol'].index('process_id') pid = self.table['process']['stream'][0][pid_col] try: self.table['lfn']['stream'].append((pid,lfn)) except KeyError: self.table['lfn'] = { 'pos' : 0, 'column' : {'process_id' : 'ilwd:char', 'name' : 'lstring'}, 'stream' : [(pid, lfn)], 'query' : '', 'orderedcol' : ['process_id', 'name' ] }
python
def add_lfn(self,lfn): """ Add an LFN table to a parsed LIGO_LW XML document. lfn = lfn to be added """ if len(self.table['process']['stream']) > 1: msg = "cannot add lfn to table with more than one process" raise LIGOLwParseError, msg # get the process_id from the process table pid_col = self.table['process']['orderedcol'].index('process_id') pid = self.table['process']['stream'][0][pid_col] try: self.table['lfn']['stream'].append((pid,lfn)) except KeyError: self.table['lfn'] = { 'pos' : 0, 'column' : {'process_id' : 'ilwd:char', 'name' : 'lstring'}, 'stream' : [(pid, lfn)], 'query' : '', 'orderedcol' : ['process_id', 'name' ] }
[ "def", "add_lfn", "(", "self", ",", "lfn", ")", ":", "if", "len", "(", "self", ".", "table", "[", "'process'", "]", "[", "'stream'", "]", ")", ">", "1", ":", "msg", "=", "\"cannot add lfn to table with more than one process\"", "raise", "LIGOLwParseError", "...
Add an LFN table to a parsed LIGO_LW XML document. lfn = lfn to be added
[ "Add", "an", "LFN", "table", "to", "a", "parsed", "LIGO_LW", "XML", "document", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ldbd.py#L384-L405
gwastro/pycbc-glue
pycbc_glue/ldbd.py
LIGOMetadata.set_dn
def set_dn(self,dn): """ Use the domain column in the process table to store the DN dn = dn to be added """ try: domain_col = self.table['process']['orderedcol'].index('domain') for row_idx in range(len(self.table['process']['stream'])): row_list = list(self.table['process']['stream'][row_idx]) row_list[domain_col] = dn self.table['process']['stream'][row_idx] = tuple(row_list) except ValueError: self.table['process']['column']['domain'] = 'lstring' self.table['process']['orderedcol'].append('domain') for row_idx in range(len(self.table['process']['stream'])): row_list = list(self.table['process']['stream'][row_idx]) row_list.append(dn) self.table['process']['stream'][row_idx] = tuple(row_list)
python
def set_dn(self,dn): """ Use the domain column in the process table to store the DN dn = dn to be added """ try: domain_col = self.table['process']['orderedcol'].index('domain') for row_idx in range(len(self.table['process']['stream'])): row_list = list(self.table['process']['stream'][row_idx]) row_list[domain_col] = dn self.table['process']['stream'][row_idx] = tuple(row_list) except ValueError: self.table['process']['column']['domain'] = 'lstring' self.table['process']['orderedcol'].append('domain') for row_idx in range(len(self.table['process']['stream'])): row_list = list(self.table['process']['stream'][row_idx]) row_list.append(dn) self.table['process']['stream'][row_idx] = tuple(row_list)
[ "def", "set_dn", "(", "self", ",", "dn", ")", ":", "try", ":", "domain_col", "=", "self", ".", "table", "[", "'process'", "]", "[", "'orderedcol'", "]", ".", "index", "(", "'domain'", ")", "for", "row_idx", "in", "range", "(", "len", "(", "self", "...
Use the domain column in the process table to store the DN dn = dn to be added
[ "Use", "the", "domain", "column", "in", "the", "process", "table", "to", "store", "the", "DN" ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ldbd.py#L407-L425
gwastro/pycbc-glue
pycbc_glue/ldbd.py
LIGOMetadata.insert
def insert(self): """Insert the object into the database""" if not self.curs: raise LIGOLwDBError, "Database connection not initalized" if len(self.table) == 0: raise LIGOLwDBError, 'attempt to insert empty table' for tab in self.table.keys(): # find and add any missing unique ids generate = [] missingcols = [k for k in self.ldb.uniqueids[tab] if k not in self.table[tab]['column']] for m in missingcols: generate.append(',BLOB(GENERATE_UNIQUE())') self.table[tab]['orderedcol'].append(m) # and construct the sql query self.table[tab]['query'] = ' '.join( ['INSERT INTO', tab, '(', ','.join(self.table[tab]['orderedcol']), ') VALUES (', ','.join(['?' for x in self.table[tab]['column']]) , ''.join(generate), ')']) for tabtup in self.ldb.tables: tab = tabtup[0].lower() try: try: self.curs.executemany(self.table[tab]['query'], self.table[tab]['stream']) rowcount = self.curs.rowcount except DB2.Error, e: self.curs.execute('rollback') msg = e[2] msg += self.xml() + '\n' msg += str(self.table[tab]['query']) + '\n' msg += str(self.table[tab]['stream']) + '\n' raise LIGOLwDBError, msg except DB2.Warning, e: self.curs.execute('rollback') raise LIGOLwDBError, e[2] #except Exception, e: # self.curs.execute('rollback') # raise LIGOLwDBError, e[2] except KeyError: pass self.curs.execute('commit') return rowcount
python
def insert(self): """Insert the object into the database""" if not self.curs: raise LIGOLwDBError, "Database connection not initalized" if len(self.table) == 0: raise LIGOLwDBError, 'attempt to insert empty table' for tab in self.table.keys(): # find and add any missing unique ids generate = [] missingcols = [k for k in self.ldb.uniqueids[tab] if k not in self.table[tab]['column']] for m in missingcols: generate.append(',BLOB(GENERATE_UNIQUE())') self.table[tab]['orderedcol'].append(m) # and construct the sql query self.table[tab]['query'] = ' '.join( ['INSERT INTO', tab, '(', ','.join(self.table[tab]['orderedcol']), ') VALUES (', ','.join(['?' for x in self.table[tab]['column']]) , ''.join(generate), ')']) for tabtup in self.ldb.tables: tab = tabtup[0].lower() try: try: self.curs.executemany(self.table[tab]['query'], self.table[tab]['stream']) rowcount = self.curs.rowcount except DB2.Error, e: self.curs.execute('rollback') msg = e[2] msg += self.xml() + '\n' msg += str(self.table[tab]['query']) + '\n' msg += str(self.table[tab]['stream']) + '\n' raise LIGOLwDBError, msg except DB2.Warning, e: self.curs.execute('rollback') raise LIGOLwDBError, e[2] #except Exception, e: # self.curs.execute('rollback') # raise LIGOLwDBError, e[2] except KeyError: pass self.curs.execute('commit') return rowcount
[ "def", "insert", "(", "self", ")", ":", "if", "not", "self", ".", "curs", ":", "raise", "LIGOLwDBError", ",", "\"Database connection not initalized\"", "if", "len", "(", "self", ".", "table", ")", "==", "0", ":", "raise", "LIGOLwDBError", ",", "'attempt to i...
Insert the object into the database
[ "Insert", "the", "object", "into", "the", "database" ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ldbd.py#L427-L469
gwastro/pycbc-glue
pycbc_glue/ldbd.py
LIGOMetadata.select
def select(self,sql): """ Execute an SQL select statement and stuff the results into a dictionary. sql = the (case sensitve) SQL statment to execute """ if not self.curs: raise LIGOLwDBError, "Database connection not initalized" if len(self.table) != 0: raise LIGOLwDBError, 'attempt to fill non-empty table from database' ligolw = '' self.table = {} sqltypes = { -2 : 'ilwd:char_u', 1 : 'lstring', 3 : 'real_8', 4 : 'int_4s', 5 : 'int_2s', 7 : 'real_4', 8 : 'real_8', 12 : 'lstring', 93 : 'lstring', } try: tab = re.compile(r'[Ff][Rr][Oo][Mm]\s+([A-Za-z0-0_]+)([,\s]+|$)').search(sql).group(1) except AttributeError: raise LIGOLwDBError, 'could not find table name in query ' + str(sql) self.table[tab] = { 'pos' : 0, 'column' : {}, 'stream' : (), 'query' : sql } try: self.curs.execute(sql) except DB2.Error, e: raise LIGOLwDBError, e[2] desc = self.curs.description for col,typ,disp,intsz,prec,sca,nul in desc: try: self.table[tab]['column'][col] = sqltypes[typ] except KeyError: raise LIGOLwDBError, 'unknown type returned by database ' + str(typ) self.table[tab].setdefault('orderedcol',[]).append(col) try: self.table[tab]['stream'] = self.curs.fetchall() except DB2.Error, e: raise LIGOLwDBError, e[2] return len(self.table[tab]['stream'])
python
def select(self,sql): """ Execute an SQL select statement and stuff the results into a dictionary. sql = the (case sensitve) SQL statment to execute """ if not self.curs: raise LIGOLwDBError, "Database connection not initalized" if len(self.table) != 0: raise LIGOLwDBError, 'attempt to fill non-empty table from database' ligolw = '' self.table = {} sqltypes = { -2 : 'ilwd:char_u', 1 : 'lstring', 3 : 'real_8', 4 : 'int_4s', 5 : 'int_2s', 7 : 'real_4', 8 : 'real_8', 12 : 'lstring', 93 : 'lstring', } try: tab = re.compile(r'[Ff][Rr][Oo][Mm]\s+([A-Za-z0-0_]+)([,\s]+|$)').search(sql).group(1) except AttributeError: raise LIGOLwDBError, 'could not find table name in query ' + str(sql) self.table[tab] = { 'pos' : 0, 'column' : {}, 'stream' : (), 'query' : sql } try: self.curs.execute(sql) except DB2.Error, e: raise LIGOLwDBError, e[2] desc = self.curs.description for col,typ,disp,intsz,prec,sca,nul in desc: try: self.table[tab]['column'][col] = sqltypes[typ] except KeyError: raise LIGOLwDBError, 'unknown type returned by database ' + str(typ) self.table[tab].setdefault('orderedcol',[]).append(col) try: self.table[tab]['stream'] = self.curs.fetchall() except DB2.Error, e: raise LIGOLwDBError, e[2] return len(self.table[tab]['stream'])
[ "def", "select", "(", "self", ",", "sql", ")", ":", "if", "not", "self", ".", "curs", ":", "raise", "LIGOLwDBError", ",", "\"Database connection not initalized\"", "if", "len", "(", "self", ".", "table", ")", "!=", "0", ":", "raise", "LIGOLwDBError", ",", ...
Execute an SQL select statement and stuff the results into a dictionary. sql = the (case sensitve) SQL statment to execute
[ "Execute", "an", "SQL", "select", "statement", "and", "stuff", "the", "results", "into", "a", "dictionary", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ldbd.py#L472-L523
gwastro/pycbc-glue
pycbc_glue/ldbd.py
LIGOMetadata.xml
def xml(self, ilwdchar_to_hex = True): """Convert a table dictionary to LIGO lightweight XML""" if len(self.table) == 0: raise LIGOLwDBError, 'attempt to convert empty table to xml' ligolw = """\ <?xml version='1.0' encoding='utf-8' ?> <?xml-stylesheet type="text/xsl" href="ligolw.xsl"?> <!DOCTYPE LIGO_LW SYSTEM "http://ldas-sw.ligo.caltech.edu/doc/ligolwAPI/html/ligolw_dtd.txt"> <LIGO_LW> """ for tab in self.table.keys(): try: ligolw += ' <Comment>'+self.strtoxml.xlat(self.table[tab]['query'])+'</Comment>\n' except KeyError: pass ligolw += ' <Table Name="'+tab+':table">\n' for col in self.table[tab]['orderedcol']: ligolw +=' <Column Name="'+tab.lower()+':'+col.lower()+'" Type="'+self.table[tab]['column'][col].lower()+'"/>\n' ligolw += ' <Stream Name="'+tab.lower()+':table" Type="Local" Delimiter=",">\n' stridx = 0 ligolw += ' ' for tup in self.table[tab]['stream']: if stridx != 0: ligolw += ',\n ' colidx = 0 for tupi in tup: if tupi is not None: coltype = self.table[tab]['column'][self.table[tab]['orderedcol'][colidx]] if re.match(r'\Ailwd:char_u\Z',coltype): ligolw += '"' for ch in str(tupi): # NOTE: escape the backslash in the ilwd:char_u octal string ligolw += '\\\\%.3o' % (ord(ch)) ligolw += '"' elif re.match(r'\Ailwd:char\Z',coltype): if ilwdchar_to_hex is True: # encode in DB2-style hex (e.g., "x'deadbeef'") ligolw += '"x\'' for ch in str(tupi): ligolw += "%02x" % ord(ch) ligolw += '\'"' else: ligolw += '"' + str(tupi) + '"' elif re.match(r'\Alstring\Z',coltype): # this santizes the contents of tupi in several ways: # strtoxml.xlat escapes any double-quote and # backslash chars (with a preceding blackslash); and # then replaces <>& chars with their html # code equivalents # NOTE: string_format_func was removed so the enclosing "" # chars need to be added ourselves ligolw += '"'+self.strtoxml.xlat(tupi)+'"' elif re.match(r'\Areal_4\Z',coltype): ligolw += '%13.7e' % tupi elif re.match(r'\Areal_8\Z',coltype): ligolw += '%22.16e' % tupi else: ligolw += str(tupi) else: ligolw += '' if colidx < (len(self.table[tab]['column']) - 1): ligolw += ',' colidx += 1 stridx += 1 ligolw += '\n </Stream>\n' ligolw += ' </Table>\n' ligolw += '</LIGO_LW>' return ligolw
python
def xml(self, ilwdchar_to_hex = True): """Convert a table dictionary to LIGO lightweight XML""" if len(self.table) == 0: raise LIGOLwDBError, 'attempt to convert empty table to xml' ligolw = """\ <?xml version='1.0' encoding='utf-8' ?> <?xml-stylesheet type="text/xsl" href="ligolw.xsl"?> <!DOCTYPE LIGO_LW SYSTEM "http://ldas-sw.ligo.caltech.edu/doc/ligolwAPI/html/ligolw_dtd.txt"> <LIGO_LW> """ for tab in self.table.keys(): try: ligolw += ' <Comment>'+self.strtoxml.xlat(self.table[tab]['query'])+'</Comment>\n' except KeyError: pass ligolw += ' <Table Name="'+tab+':table">\n' for col in self.table[tab]['orderedcol']: ligolw +=' <Column Name="'+tab.lower()+':'+col.lower()+'" Type="'+self.table[tab]['column'][col].lower()+'"/>\n' ligolw += ' <Stream Name="'+tab.lower()+':table" Type="Local" Delimiter=",">\n' stridx = 0 ligolw += ' ' for tup in self.table[tab]['stream']: if stridx != 0: ligolw += ',\n ' colidx = 0 for tupi in tup: if tupi is not None: coltype = self.table[tab]['column'][self.table[tab]['orderedcol'][colidx]] if re.match(r'\Ailwd:char_u\Z',coltype): ligolw += '"' for ch in str(tupi): # NOTE: escape the backslash in the ilwd:char_u octal string ligolw += '\\\\%.3o' % (ord(ch)) ligolw += '"' elif re.match(r'\Ailwd:char\Z',coltype): if ilwdchar_to_hex is True: # encode in DB2-style hex (e.g., "x'deadbeef'") ligolw += '"x\'' for ch in str(tupi): ligolw += "%02x" % ord(ch) ligolw += '\'"' else: ligolw += '"' + str(tupi) + '"' elif re.match(r'\Alstring\Z',coltype): # this santizes the contents of tupi in several ways: # strtoxml.xlat escapes any double-quote and # backslash chars (with a preceding blackslash); and # then replaces <>& chars with their html # code equivalents # NOTE: string_format_func was removed so the enclosing "" # chars need to be added ourselves ligolw += '"'+self.strtoxml.xlat(tupi)+'"' elif re.match(r'\Areal_4\Z',coltype): ligolw += '%13.7e' % tupi elif re.match(r'\Areal_8\Z',coltype): ligolw += '%22.16e' % tupi else: ligolw += str(tupi) else: ligolw += '' if colidx < (len(self.table[tab]['column']) - 1): ligolw += ',' colidx += 1 stridx += 1 ligolw += '\n </Stream>\n' ligolw += ' </Table>\n' ligolw += '</LIGO_LW>' return ligolw
[ "def", "xml", "(", "self", ",", "ilwdchar_to_hex", "=", "True", ")", ":", "if", "len", "(", "self", ".", "table", ")", "==", "0", ":", "raise", "LIGOLwDBError", ",", "'attempt to convert empty table to xml'", "ligolw", "=", "\"\"\"\\\n<?xml version='1.0' encoding=...
Convert a table dictionary to LIGO lightweight XML
[ "Convert", "a", "table", "dictionary", "to", "LIGO", "lightweight", "XML" ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ldbd.py#L525-L594
dstufft/dj-search-url
dj_search_url.py
parse
def parse(url): """Parses a search URL.""" config = {} url = urlparse.urlparse(url) # Remove query strings. path = url.path[1:] path = path.split('?', 2)[0] if url.scheme in SCHEMES: config["ENGINE"] = SCHEMES[url.scheme] if url.scheme in USES_URL: config["URL"] = urlparse.urlunparse(("http",) + url[1:]) if url.scheme in USES_INDEX: if path.endswith("/"): path = path[:-1] split = path.rsplit("/", 1) if len(split) > 1: path = split[:-1] index = split[-1] else: path = "" index = split[0] config.update({ "URL": urlparse.urlunparse(("http",) + url[1:2] + (path,) + url[3:]), "INDEX_NAME": index, }) if url.scheme in USES_PATH: config.update({ "PATH": path, }) return config
python
def parse(url): """Parses a search URL.""" config = {} url = urlparse.urlparse(url) # Remove query strings. path = url.path[1:] path = path.split('?', 2)[0] if url.scheme in SCHEMES: config["ENGINE"] = SCHEMES[url.scheme] if url.scheme in USES_URL: config["URL"] = urlparse.urlunparse(("http",) + url[1:]) if url.scheme in USES_INDEX: if path.endswith("/"): path = path[:-1] split = path.rsplit("/", 1) if len(split) > 1: path = split[:-1] index = split[-1] else: path = "" index = split[0] config.update({ "URL": urlparse.urlunparse(("http",) + url[1:2] + (path,) + url[3:]), "INDEX_NAME": index, }) if url.scheme in USES_PATH: config.update({ "PATH": path, }) return config
[ "def", "parse", "(", "url", ")", ":", "config", "=", "{", "}", "url", "=", "urlparse", ".", "urlparse", "(", "url", ")", "# Remove query strings.", "path", "=", "url", ".", "path", "[", "1", ":", "]", "path", "=", "path", ".", "split", "(", "'?'", ...
Parses a search URL.
[ "Parses", "a", "search", "URL", "." ]
train
https://github.com/dstufft/dj-search-url/blob/3185095eed15ce8e0a83e693d2d2269794a146b3/dj_search_url.py#L45-L85
KenjiTakahashi/td
td/model.py
save
def save(func): """@decorator: Saves data after executing :func:. Also performs modifications set as permanent options. """ def aux(self, *args, **kwargs): out = func(self, *args, **kwargs) path = (hasattr(self, 'path') and self.path or os.path.join(os.getcwd(), '.td')) gpath = (hasattr(self, 'gpath') and self.gpath or os.path.expanduser('~/.tdrc')) if os.path.exists(path): shutil.copy2(path, os.path.join(os.path.dirname(path), '.td~')) open(path, 'w').write( json.dumps({ 'items': self.data, 'refs': self.refs, 'options': self.options }) ) open(gpath, 'w').write(json.dumps(self.globalOptions)) return out return aux
python
def save(func): """@decorator: Saves data after executing :func:. Also performs modifications set as permanent options. """ def aux(self, *args, **kwargs): out = func(self, *args, **kwargs) path = (hasattr(self, 'path') and self.path or os.path.join(os.getcwd(), '.td')) gpath = (hasattr(self, 'gpath') and self.gpath or os.path.expanduser('~/.tdrc')) if os.path.exists(path): shutil.copy2(path, os.path.join(os.path.dirname(path), '.td~')) open(path, 'w').write( json.dumps({ 'items': self.data, 'refs': self.refs, 'options': self.options }) ) open(gpath, 'w').write(json.dumps(self.globalOptions)) return out return aux
[ "def", "save", "(", "func", ")", ":", "def", "aux", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "out", "=", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "path", "=", "(", "hasattr", "(", "self", ...
@decorator: Saves data after executing :func:. Also performs modifications set as permanent options.
[ "@decorator", ":", "Saves", "data", "after", "executing", ":", "func", ":", "." ]
train
https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/model.py#L104-L127
KenjiTakahashi/td
td/model.py
Model.add
def add(self, name, priority=3, comment="", parent=""): """Adds new item to the model. Name argument may contain (ref:) syntax, which will be stripped down as needed. :parent: should have a form "<itemref>.<subitemref...>" (e.g. "1.1"). :name: Name (with refs). :priority: Item's priority. :comment: Comment. :parent: Item's parent ("" for top-level item). """ item = [name, priority, comment, False, []] data = self.data for c in self._split(parent): data = data[int(c) - 1][4] data.append(item)
python
def add(self, name, priority=3, comment="", parent=""): """Adds new item to the model. Name argument may contain (ref:) syntax, which will be stripped down as needed. :parent: should have a form "<itemref>.<subitemref...>" (e.g. "1.1"). :name: Name (with refs). :priority: Item's priority. :comment: Comment. :parent: Item's parent ("" for top-level item). """ item = [name, priority, comment, False, []] data = self.data for c in self._split(parent): data = data[int(c) - 1][4] data.append(item)
[ "def", "add", "(", "self", ",", "name", ",", "priority", "=", "3", ",", "comment", "=", "\"\"", ",", "parent", "=", "\"\"", ")", ":", "item", "=", "[", "name", ",", "priority", ",", "comment", ",", "False", ",", "[", "]", "]", "data", "=", "sel...
Adds new item to the model. Name argument may contain (ref:) syntax, which will be stripped down as needed. :parent: should have a form "<itemref>.<subitemref...>" (e.g. "1.1"). :name: Name (with refs). :priority: Item's priority. :comment: Comment. :parent: Item's parent ("" for top-level item).
[ "Adds", "new", "item", "to", "the", "model", "." ]
train
https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/model.py#L156-L174
KenjiTakahashi/td
td/model.py
Model.edit
def edit( self, index, name=None, priority=None, comment=None, done=None, parent=None ): """Modifies :index: to specified data. Every argument, which is not None, will get changed. If parent is not None, the item will get reparented. Use parent=-1 or parent='' for reparenting to top-level. :index: Index of the item to edit. :name: New name. :priority: New priority. :comment: New comment. :done: Done mark. :parent: New parent. """ if parent == -1: parent = '' parent = self._split(parent) index = self._split(index) item = self.data for j, c in enumerate(index): item = item[int(c) - 1] if j + 1 != len(index): item = item[4] if name is not None: item[0] = name if priority is not None: item[1] = priority if comment is not None: item[2] = comment if done is not None: item[3] = done if parent is not None and parent != index[:-1]: parentitem = self.data for c in parent: parentitem = parentitem[int(c) - 1][4] parentitem.append(item) parent = index[:-1] parentitem = self.data for c in parent: parentitem = parentitem[int(c) - 1][4] parentitem.remove(item)
python
def edit( self, index, name=None, priority=None, comment=None, done=None, parent=None ): """Modifies :index: to specified data. Every argument, which is not None, will get changed. If parent is not None, the item will get reparented. Use parent=-1 or parent='' for reparenting to top-level. :index: Index of the item to edit. :name: New name. :priority: New priority. :comment: New comment. :done: Done mark. :parent: New parent. """ if parent == -1: parent = '' parent = self._split(parent) index = self._split(index) item = self.data for j, c in enumerate(index): item = item[int(c) - 1] if j + 1 != len(index): item = item[4] if name is not None: item[0] = name if priority is not None: item[1] = priority if comment is not None: item[2] = comment if done is not None: item[3] = done if parent is not None and parent != index[:-1]: parentitem = self.data for c in parent: parentitem = parentitem[int(c) - 1][4] parentitem.append(item) parent = index[:-1] parentitem = self.data for c in parent: parentitem = parentitem[int(c) - 1][4] parentitem.remove(item)
[ "def", "edit", "(", "self", ",", "index", ",", "name", "=", "None", ",", "priority", "=", "None", ",", "comment", "=", "None", ",", "done", "=", "None", ",", "parent", "=", "None", ")", ":", "if", "parent", "==", "-", "1", ":", "parent", "=", "...
Modifies :index: to specified data. Every argument, which is not None, will get changed. If parent is not None, the item will get reparented. Use parent=-1 or parent='' for reparenting to top-level. :index: Index of the item to edit. :name: New name. :priority: New priority. :comment: New comment. :done: Done mark. :parent: New parent.
[ "Modifies", ":", "index", ":", "to", "specified", "data", "." ]
train
https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/model.py#L178-L223
KenjiTakahashi/td
td/model.py
Model.remove
def remove(self, index): """Removes specified item from the model. :index: Should have a form "<itemref>.<subitemref...>" (e.g. "1.1"). :index: Item's index. """ data = self.data index = self._split(index) for j, c in enumerate(index): i = int(c) - 1 if j + 1 == len(index): try: del data[i] except IndexError: raise NoItemError('.'.join(index)) else: data = data[i][4]
python
def remove(self, index): """Removes specified item from the model. :index: Should have a form "<itemref>.<subitemref...>" (e.g. "1.1"). :index: Item's index. """ data = self.data index = self._split(index) for j, c in enumerate(index): i = int(c) - 1 if j + 1 == len(index): try: del data[i] except IndexError: raise NoItemError('.'.join(index)) else: data = data[i][4]
[ "def", "remove", "(", "self", ",", "index", ")", ":", "data", "=", "self", ".", "data", "index", "=", "self", ".", "_split", "(", "index", ")", "for", "j", ",", "c", "in", "enumerate", "(", "index", ")", ":", "i", "=", "int", "(", "c", ")", "...
Removes specified item from the model. :index: Should have a form "<itemref>.<subitemref...>" (e.g. "1.1"). :index: Item's index.
[ "Removes", "specified", "item", "from", "the", "model", "." ]
train
https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/model.py#L228-L246
KenjiTakahashi/td
td/model.py
Model.exists
def exists(self, index): """Checks whether :index: exists in the Model. :index: Index to look for. :returns: True if :index: exists in the Model, False otherwise. """ data = self.data try: for c in self._split(index): i = int(c) - 1 data = data[i][4] except Exception: return False return True
python
def exists(self, index): """Checks whether :index: exists in the Model. :index: Index to look for. :returns: True if :index: exists in the Model, False otherwise. """ data = self.data try: for c in self._split(index): i = int(c) - 1 data = data[i][4] except Exception: return False return True
[ "def", "exists", "(", "self", ",", "index", ")", ":", "data", "=", "self", ".", "data", "try", ":", "for", "c", "in", "self", ".", "_split", "(", "index", ")", ":", "i", "=", "int", "(", "c", ")", "-", "1", "data", "=", "data", "[", "i", "]...
Checks whether :index: exists in the Model. :index: Index to look for. :returns: True if :index: exists in the Model, False otherwise.
[ "Checks", "whether", ":", "index", ":", "exists", "in", "the", "Model", "." ]
train
https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/model.py#L249-L263
KenjiTakahashi/td
td/model.py
Model.get
def get(self, index): """Gets data values for specified :index:. :index: Index for which to get data. :returns: A list in form [parent, name, priority, comment, done, children]. """ data = self.data index2 = self._split(index) for c in index2[:-1]: i = int(c) - 1 data = data[i][4] return [index[:-2] or ""] + data[int(index[-1]) - 1]
python
def get(self, index): """Gets data values for specified :index:. :index: Index for which to get data. :returns: A list in form [parent, name, priority, comment, done, children]. """ data = self.data index2 = self._split(index) for c in index2[:-1]: i = int(c) - 1 data = data[i][4] return [index[:-2] or ""] + data[int(index[-1]) - 1]
[ "def", "get", "(", "self", ",", "index", ")", ":", "data", "=", "self", ".", "data", "index2", "=", "self", ".", "_split", "(", "index", ")", "for", "c", "in", "index2", "[", ":", "-", "1", "]", ":", "i", "=", "int", "(", "c", ")", "-", "1"...
Gets data values for specified :index:. :index: Index for which to get data. :returns: A list in form [parent, name, priority, comment, done, children].
[ "Gets", "data", "values", "for", "specified", ":", "index", ":", "." ]
train
https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/model.py#L266-L279
KenjiTakahashi/td
td/model.py
Model._modifyInternal
def _modifyInternal(self, *, sort=None, purge=False, done=None): """Creates a whole new database from existing one, based on given modifiers. :sort: pattern should look like this: ([(<index>, True|False)], {<level_index>: [(<index>, True|False)]}), where True|False indicate whether to reverse or not, <index> are one of Model.indexes and <level_index> indicate a number of level to sort. Of course, the lists above may contain multiple items. :done: patterns looks similar to :sort:, except that it has additional <regexp> values and that True|False means to mark as done|undone. @note: Should not be used directly. It was defined here, because :save: decorator needs undecorated version of Model.modify. :sort: Pattern on which to sort the database. :purge: Whether to purge done items. :done: Pattern on which to mark items as done/undone. :returns: New database, modified according to supplied arguments. """ sortAll, sortLevels = sort is not None and sort or ([], {}) doneAll, doneLevels = done is not None and done or ([], {}) def _mark(v, i): if done is None: return v[:4] def _mark_(index, regexp, du): if du is None: return v[:4] if index is None: for v_ in v[:3]: if regexp is None or re.match(regexp, str(v_)): return v[:3] + [du] return v[:4] if regexp is None or re.match(regexp, str(v[index])): return v[:3] + [du] try: for doneLevel in doneLevels[i]: result = _mark_(*doneLevel) if result is not None: return result except KeyError: pass for doneAll_ in doneAll: result = _mark_(*doneAll_) if result is None: return v[:4] return result def _modify(submodel, i): _new = list() for v in submodel: if purge: if not v[3]: _new.append(_mark(v, i) + [_modify(v[4], i + 1)]) else: _new.append(_mark(v, i) + [_modify(v[4], i + 1)]) levels = sortLevels.get(i) or sortLevels.get(str(i)) for index, reverse in levels or sortAll: _new = sorted(_new, key=lambda e: e[index], reverse=reverse) return _new return _modify(self.data, 1)
python
def _modifyInternal(self, *, sort=None, purge=False, done=None): """Creates a whole new database from existing one, based on given modifiers. :sort: pattern should look like this: ([(<index>, True|False)], {<level_index>: [(<index>, True|False)]}), where True|False indicate whether to reverse or not, <index> are one of Model.indexes and <level_index> indicate a number of level to sort. Of course, the lists above may contain multiple items. :done: patterns looks similar to :sort:, except that it has additional <regexp> values and that True|False means to mark as done|undone. @note: Should not be used directly. It was defined here, because :save: decorator needs undecorated version of Model.modify. :sort: Pattern on which to sort the database. :purge: Whether to purge done items. :done: Pattern on which to mark items as done/undone. :returns: New database, modified according to supplied arguments. """ sortAll, sortLevels = sort is not None and sort or ([], {}) doneAll, doneLevels = done is not None and done or ([], {}) def _mark(v, i): if done is None: return v[:4] def _mark_(index, regexp, du): if du is None: return v[:4] if index is None: for v_ in v[:3]: if regexp is None or re.match(regexp, str(v_)): return v[:3] + [du] return v[:4] if regexp is None or re.match(regexp, str(v[index])): return v[:3] + [du] try: for doneLevel in doneLevels[i]: result = _mark_(*doneLevel) if result is not None: return result except KeyError: pass for doneAll_ in doneAll: result = _mark_(*doneAll_) if result is None: return v[:4] return result def _modify(submodel, i): _new = list() for v in submodel: if purge: if not v[3]: _new.append(_mark(v, i) + [_modify(v[4], i + 1)]) else: _new.append(_mark(v, i) + [_modify(v[4], i + 1)]) levels = sortLevels.get(i) or sortLevels.get(str(i)) for index, reverse in levels or sortAll: _new = sorted(_new, key=lambda e: e[index], reverse=reverse) return _new return _modify(self.data, 1)
[ "def", "_modifyInternal", "(", "self", ",", "*", ",", "sort", "=", "None", ",", "purge", "=", "False", ",", "done", "=", "None", ")", ":", "sortAll", ",", "sortLevels", "=", "sort", "is", "not", "None", "and", "sort", "or", "(", "[", "]", ",", "{...
Creates a whole new database from existing one, based on given modifiers. :sort: pattern should look like this: ([(<index>, True|False)], {<level_index>: [(<index>, True|False)]}), where True|False indicate whether to reverse or not, <index> are one of Model.indexes and <level_index> indicate a number of level to sort. Of course, the lists above may contain multiple items. :done: patterns looks similar to :sort:, except that it has additional <regexp> values and that True|False means to mark as done|undone. @note: Should not be used directly. It was defined here, because :save: decorator needs undecorated version of Model.modify. :sort: Pattern on which to sort the database. :purge: Whether to purge done items. :done: Pattern on which to mark items as done/undone. :returns: New database, modified according to supplied arguments.
[ "Creates", "a", "whole", "new", "database", "from", "existing", "one", "based", "on", "given", "modifiers", "." ]
train
https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/model.py#L281-L346
KenjiTakahashi/td
td/model.py
Model.modify
def modify(self, *, sort=None, purge=False, done=None): """Calls Model._modifyInternal after loading the database.""" return self._modifyInternal(sort=sort, purge=purge, done=done)
python
def modify(self, *, sort=None, purge=False, done=None): """Calls Model._modifyInternal after loading the database.""" return self._modifyInternal(sort=sort, purge=purge, done=done)
[ "def", "modify", "(", "self", ",", "*", ",", "sort", "=", "None", ",", "purge", "=", "False", ",", "done", "=", "None", ")", ":", "return", "self", ".", "_modifyInternal", "(", "sort", "=", "sort", ",", "purge", "=", "purge", ",", "done", "=", "d...
Calls Model._modifyInternal after loading the database.
[ "Calls", "Model", ".", "_modifyInternal", "after", "loading", "the", "database", "." ]
train
https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/model.py#L349-L351
KenjiTakahashi/td
td/model.py
Model.modifyInPlace
def modifyInPlace(self, *, sort=None, purge=False, done=None): """Like Model.modify, but changes existing database instead of returning a new one.""" self.data = self.modify(sort=sort, purge=purge, done=done)
python
def modifyInPlace(self, *, sort=None, purge=False, done=None): """Like Model.modify, but changes existing database instead of returning a new one.""" self.data = self.modify(sort=sort, purge=purge, done=done)
[ "def", "modifyInPlace", "(", "self", ",", "*", ",", "sort", "=", "None", ",", "purge", "=", "False", ",", "done", "=", "None", ")", ":", "self", ".", "data", "=", "self", ".", "modify", "(", "sort", "=", "sort", ",", "purge", "=", "purge", ",", ...
Like Model.modify, but changes existing database instead of returning a new one.
[ "Like", "Model", ".", "modify", "but", "changes", "existing", "database", "instead", "of", "returning", "a", "new", "one", "." ]
train
https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/model.py#L354-L357
KenjiTakahashi/td
td/model.py
Model.setOptions
def setOptions(self, glob=False, **kwargs): """Set option(s). :glob: If True, stores specified options globally. :kwargs: Dictionary of options and values to set. """ if glob: self.globalOptions.update(kwargs) else: self.options.update(kwargs)
python
def setOptions(self, glob=False, **kwargs): """Set option(s). :glob: If True, stores specified options globally. :kwargs: Dictionary of options and values to set. """ if glob: self.globalOptions.update(kwargs) else: self.options.update(kwargs)
[ "def", "setOptions", "(", "self", ",", "glob", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "glob", ":", "self", ".", "globalOptions", ".", "update", "(", "kwargs", ")", "else", ":", "self", ".", "options", ".", "update", "(", "kwargs", "...
Set option(s). :glob: If True, stores specified options globally. :kwargs: Dictionary of options and values to set.
[ "Set", "option", "(", "s", ")", "." ]
train
https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/model.py#L361-L371
fractalego/parvusdb
parvusdb/utils/code_container.py
CodeContainer.add_line
def add_line(self, string): """ Adds a line to the LISP code to execute :param string: The line to add :return: None """ self.code_strings.append(string) code = '' if len(self.code_strings) == 1: code = '(setv result ' + self.code_strings[0] + ')' if len(self.code_strings) > 1: code = '(setv result (and ' + ' '.join(self.code_strings) + '))' self._compiled_ast_and_expr = self.__compile_code(code_string=code)
python
def add_line(self, string): """ Adds a line to the LISP code to execute :param string: The line to add :return: None """ self.code_strings.append(string) code = '' if len(self.code_strings) == 1: code = '(setv result ' + self.code_strings[0] + ')' if len(self.code_strings) > 1: code = '(setv result (and ' + ' '.join(self.code_strings) + '))' self._compiled_ast_and_expr = self.__compile_code(code_string=code)
[ "def", "add_line", "(", "self", ",", "string", ")", ":", "self", ".", "code_strings", ".", "append", "(", "string", ")", "code", "=", "''", "if", "len", "(", "self", ".", "code_strings", ")", "==", "1", ":", "code", "=", "'(setv result '", "+", "self...
Adds a line to the LISP code to execute :param string: The line to add :return: None
[ "Adds", "a", "line", "to", "the", "LISP", "code", "to", "execute" ]
train
https://github.com/fractalego/parvusdb/blob/d5e818d3f3c3decfd4835ef2133aa956b6d87b1d/parvusdb/utils/code_container.py#L18-L31
fractalego/parvusdb
parvusdb/utils/code_container.py
CodeContainer.add_graph_to_namespace
def add_graph_to_namespace(self, graph): """ Adds the variables name to the namespace of the local LISP code :param graph: the graph to add to the namespace :return: None """ for node in graph.vs: attributes = node.attributes() self.namespace[node['name']] = attributes for node in graph.es: attributes = node.attributes() self.namespace[node['name']] = attributes
python
def add_graph_to_namespace(self, graph): """ Adds the variables name to the namespace of the local LISP code :param graph: the graph to add to the namespace :return: None """ for node in graph.vs: attributes = node.attributes() self.namespace[node['name']] = attributes for node in graph.es: attributes = node.attributes() self.namespace[node['name']] = attributes
[ "def", "add_graph_to_namespace", "(", "self", ",", "graph", ")", ":", "for", "node", "in", "graph", ".", "vs", ":", "attributes", "=", "node", ".", "attributes", "(", ")", "self", ".", "namespace", "[", "node", "[", "'name'", "]", "]", "=", "attributes...
Adds the variables name to the namespace of the local LISP code :param graph: the graph to add to the namespace :return: None
[ "Adds", "the", "variables", "name", "to", "the", "namespace", "of", "the", "local", "LISP", "code" ]
train
https://github.com/fractalego/parvusdb/blob/d5e818d3f3c3decfd4835ef2133aa956b6d87b1d/parvusdb/utils/code_container.py#L33-L45
fractalego/parvusdb
parvusdb/utils/code_container.py
CodeContainer.execute
def execute(self, vertices_substitution_dict={}): """ Executes the code :param vertices_substitution_dict: aliases of the variables in the code :return: True/False, depending on the result of the code (default is True) """ if not self.code_strings: return True if vertices_substitution_dict: namespace = self.__substitute_names_in_namespace(self.namespace, vertices_substitution_dict) else: namespace = self.namespace try: self.__execute_code(self._compiled_ast_and_expr, namespace) except: pass return namespace['result']
python
def execute(self, vertices_substitution_dict={}): """ Executes the code :param vertices_substitution_dict: aliases of the variables in the code :return: True/False, depending on the result of the code (default is True) """ if not self.code_strings: return True if vertices_substitution_dict: namespace = self.__substitute_names_in_namespace(self.namespace, vertices_substitution_dict) else: namespace = self.namespace try: self.__execute_code(self._compiled_ast_and_expr, namespace) except: pass return namespace['result']
[ "def", "execute", "(", "self", ",", "vertices_substitution_dict", "=", "{", "}", ")", ":", "if", "not", "self", ".", "code_strings", ":", "return", "True", "if", "vertices_substitution_dict", ":", "namespace", "=", "self", ".", "__substitute_names_in_namespace", ...
Executes the code :param vertices_substitution_dict: aliases of the variables in the code :return: True/False, depending on the result of the code (default is True)
[ "Executes", "the", "code" ]
train
https://github.com/fractalego/parvusdb/blob/d5e818d3f3c3decfd4835ef2133aa956b6d87b1d/parvusdb/utils/code_container.py#L47-L66
fractalego/parvusdb
parvusdb/utils/code_container.py
CodeContainer.substitute_namespace_into_graph
def substitute_namespace_into_graph(self, graph): """ Creates a graph from the local namespace of the code (to be used after the execution of the code) :param graph: The graph to use as a recipient of the namespace :return: the updated graph """ for key, value in self.namespace.items(): try: nodes = graph.vs.select(name=key) for node in nodes: for k, v in value.items(): node[k] = v except: pass try: nodes = graph.es.select(name=key) for node in nodes: for k, v in value.items(): node[k] = v except: pass return graph
python
def substitute_namespace_into_graph(self, graph): """ Creates a graph from the local namespace of the code (to be used after the execution of the code) :param graph: The graph to use as a recipient of the namespace :return: the updated graph """ for key, value in self.namespace.items(): try: nodes = graph.vs.select(name=key) for node in nodes: for k, v in value.items(): node[k] = v except: pass try: nodes = graph.es.select(name=key) for node in nodes: for k, v in value.items(): node[k] = v except: pass return graph
[ "def", "substitute_namespace_into_graph", "(", "self", ",", "graph", ")", ":", "for", "key", ",", "value", "in", "self", ".", "namespace", ".", "items", "(", ")", ":", "try", ":", "nodes", "=", "graph", ".", "vs", ".", "select", "(", "name", "=", "ke...
Creates a graph from the local namespace of the code (to be used after the execution of the code) :param graph: The graph to use as a recipient of the namespace :return: the updated graph
[ "Creates", "a", "graph", "from", "the", "local", "namespace", "of", "the", "code", "(", "to", "be", "used", "after", "the", "execution", "of", "the", "code", ")" ]
train
https://github.com/fractalego/parvusdb/blob/d5e818d3f3c3decfd4835ef2133aa956b6d87b1d/parvusdb/utils/code_container.py#L68-L90
ahmontero/dop
dop/client.py
Client.droplets
def droplets(self): """ This method returns the list of droplets """ json = self.request('/droplets/', method='GET') status = json.get('status') if status == 'OK': droplet_json = json.get('droplets', []) droplets = [Droplet.from_json(droplet) for droplet in droplet_json] return droplets else: message = json.get('message', None) raise DOPException('[%s]: %s' % (status, message))
python
def droplets(self): """ This method returns the list of droplets """ json = self.request('/droplets/', method='GET') status = json.get('status') if status == 'OK': droplet_json = json.get('droplets', []) droplets = [Droplet.from_json(droplet) for droplet in droplet_json] return droplets else: message = json.get('message', None) raise DOPException('[%s]: %s' % (status, message))
[ "def", "droplets", "(", "self", ")", ":", "json", "=", "self", ".", "request", "(", "'/droplets/'", ",", "method", "=", "'GET'", ")", "status", "=", "json", ".", "get", "(", "'status'", ")", "if", "status", "==", "'OK'", ":", "droplet_json", "=", "js...
This method returns the list of droplets
[ "This", "method", "returns", "the", "list", "of", "droplets" ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L45-L57
ahmontero/dop
dop/client.py
Client.reboot_droplet
def reboot_droplet(self, droplet_id): """ This method allows you to reboot a droplet. This is the preferred method to use if a server is not responding. """ if not droplet_id: raise DOPException('droplet_id is required to reboot a droplet!') json = self.request('/droplets/%s/reboot' % droplet_id, method='GET') status = json.get('status') if status == 'OK': return json.get('event_id') else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
def reboot_droplet(self, droplet_id): """ This method allows you to reboot a droplet. This is the preferred method to use if a server is not responding. """ if not droplet_id: raise DOPException('droplet_id is required to reboot a droplet!') json = self.request('/droplets/%s/reboot' % droplet_id, method='GET') status = json.get('status') if status == 'OK': return json.get('event_id') else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
[ "def", "reboot_droplet", "(", "self", ",", "droplet_id", ")", ":", "if", "not", "droplet_id", ":", "raise", "DOPException", "(", "'droplet_id is required to reboot a droplet!'", ")", "json", "=", "self", ".", "request", "(", "'/droplets/%s/reboot'", "%", "droplet_id...
This method allows you to reboot a droplet. This is the preferred method to use if a server is not responding.
[ "This", "method", "allows", "you", "to", "reboot", "a", "droplet", ".", "This", "is", "the", "preferred", "method", "to", "use", "if", "a", "server", "is", "not", "responding", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L169-L182
ahmontero/dop
dop/client.py
Client.power_cycle_droplet
def power_cycle_droplet(self, droplet_id): """ This method allows you to power cycle a droplet. This will turn off the droplet and then turn it back on. """ if not droplet_id: msg = 'droplet_id is required to power cycle a droplet!' raise DOPException(msg) json = self.request('/droplets/%s/power_cycle' % droplet_id, method='GET') status = json.get('status') if status == 'OK': return json.get('event_id') else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
def power_cycle_droplet(self, droplet_id): """ This method allows you to power cycle a droplet. This will turn off the droplet and then turn it back on. """ if not droplet_id: msg = 'droplet_id is required to power cycle a droplet!' raise DOPException(msg) json = self.request('/droplets/%s/power_cycle' % droplet_id, method='GET') status = json.get('status') if status == 'OK': return json.get('event_id') else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
[ "def", "power_cycle_droplet", "(", "self", ",", "droplet_id", ")", ":", "if", "not", "droplet_id", ":", "msg", "=", "'droplet_id is required to power cycle a droplet!'", "raise", "DOPException", "(", "msg", ")", "json", "=", "self", ".", "request", "(", "'/droplet...
This method allows you to power cycle a droplet. This will turn off the droplet and then turn it back on.
[ "This", "method", "allows", "you", "to", "power", "cycle", "a", "droplet", ".", "This", "will", "turn", "off", "the", "droplet", "and", "then", "turn", "it", "back", "on", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L184-L198
ahmontero/dop
dop/client.py
Client.resize_droplet
def resize_droplet(self, droplet_id, size): """ This method allows you to resize a specific droplet to a different size. This will affect the number of processors and memory allocated to the droplet. Required parameters: droplet_id: Integer, this is the id of your droplet that you want to resize size, one of size_id: Numeric, this is the id of the size with which you would like the droplet created size_slug: String, this is the slug of the size with which you would like the droplet created """ if not droplet_id: raise DOPException('droplet_id is required to resize a droplet!') params = {} size_id = size.get('size_id') if size_id: params.update({'size_id': size_id}) else: size_slug = size.get('size_slug') if size_slug: params.update({'size_slug': size_slug}) else: msg = 'size_id or size_slug are required to resize a droplet!' raise DOPException(msg) json = self.request('/droplets/%s/resize' % droplet_id, method='GET', params=params) status = json.get('status') if status == 'OK': return json.get('event_id') else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
def resize_droplet(self, droplet_id, size): """ This method allows you to resize a specific droplet to a different size. This will affect the number of processors and memory allocated to the droplet. Required parameters: droplet_id: Integer, this is the id of your droplet that you want to resize size, one of size_id: Numeric, this is the id of the size with which you would like the droplet created size_slug: String, this is the slug of the size with which you would like the droplet created """ if not droplet_id: raise DOPException('droplet_id is required to resize a droplet!') params = {} size_id = size.get('size_id') if size_id: params.update({'size_id': size_id}) else: size_slug = size.get('size_slug') if size_slug: params.update({'size_slug': size_slug}) else: msg = 'size_id or size_slug are required to resize a droplet!' raise DOPException(msg) json = self.request('/droplets/%s/resize' % droplet_id, method='GET', params=params) status = json.get('status') if status == 'OK': return json.get('event_id') else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
[ "def", "resize_droplet", "(", "self", ",", "droplet_id", ",", "size", ")", ":", "if", "not", "droplet_id", ":", "raise", "DOPException", "(", "'droplet_id is required to resize a droplet!'", ")", "params", "=", "{", "}", "size_id", "=", "size", ".", "get", "("...
This method allows you to resize a specific droplet to a different size. This will affect the number of processors and memory allocated to the droplet. Required parameters: droplet_id: Integer, this is the id of your droplet that you want to resize size, one of size_id: Numeric, this is the id of the size with which you would like the droplet created size_slug: String, this is the slug of the size with which you would like the droplet created
[ "This", "method", "allows", "you", "to", "resize", "a", "specific", "droplet", "to", "a", "different", "size", ".", "This", "will", "affect", "the", "number", "of", "processors", "and", "memory", "allocated", "to", "the", "droplet", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L262-L299
ahmontero/dop
dop/client.py
Client.restore_droplet
def restore_droplet(self, droplet_id, image_id): """ This method allows you to restore a droplet with a previous image or snapshot. This will be a mirror copy of the image or snapshot to your droplet. Be sure you have backed up any necessary information prior to restore. Required parameters: droplet_id: Numeric, this is the id of your droplet that you want to snapshot image_id: Numeric, this is the id of the image you would like to use to restore your droplet with """ if not droplet_id: raise DOPException('droplet_id is required to restore a droplet!') if not image_id: raise DOPException('image_id is required to rebuild a droplet!') params = {'image_id': image_id} json = self.request('/droplets/%s/restore' % droplet_id, method='GET', params=params) status = json.get('status') if status == 'OK': return json.get('event_id') else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
def restore_droplet(self, droplet_id, image_id): """ This method allows you to restore a droplet with a previous image or snapshot. This will be a mirror copy of the image or snapshot to your droplet. Be sure you have backed up any necessary information prior to restore. Required parameters: droplet_id: Numeric, this is the id of your droplet that you want to snapshot image_id: Numeric, this is the id of the image you would like to use to restore your droplet with """ if not droplet_id: raise DOPException('droplet_id is required to restore a droplet!') if not image_id: raise DOPException('image_id is required to rebuild a droplet!') params = {'image_id': image_id} json = self.request('/droplets/%s/restore' % droplet_id, method='GET', params=params) status = json.get('status') if status == 'OK': return json.get('event_id') else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
[ "def", "restore_droplet", "(", "self", ",", "droplet_id", ",", "image_id", ")", ":", "if", "not", "droplet_id", ":", "raise", "DOPException", "(", "'droplet_id is required to restore a droplet!'", ")", "if", "not", "image_id", ":", "raise", "DOPException", "(", "'...
This method allows you to restore a droplet with a previous image or snapshot. This will be a mirror copy of the image or snapshot to your droplet. Be sure you have backed up any necessary information prior to restore. Required parameters: droplet_id: Numeric, this is the id of your droplet that you want to snapshot image_id: Numeric, this is the id of the image you would like to use to restore your droplet with
[ "This", "method", "allows", "you", "to", "restore", "a", "droplet", "with", "a", "previous", "image", "or", "snapshot", ".", "This", "will", "be", "a", "mirror", "copy", "of", "the", "image", "or", "snapshot", "to", "your", "droplet", ".", "Be", "sure", ...
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L330-L357
ahmontero/dop
dop/client.py
Client.rename_droplet
def rename_droplet(self, droplet_id, name): """ This method allows you to reinstall a droplet with a default image. This is useful if you want to start again but retain the same IP address for your droplet. Required parameters: droplet_id: Numeric, this is the id of your droplet that you want to snapshot image_id: Numeric, this is the id of the image you would like to use to rebuild your droplet with """ if not droplet_id: raise DOPException('droplet_id is required to rebuild a droplet!') if not name: raise DOPException('name is required to rebuild a droplet!') params = {'name': name} json = self.request('/droplets/%s/rename' % droplet_id, method='GET', params=params) status = json.get('status') if status == 'OK': return json.get('event_id') else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
def rename_droplet(self, droplet_id, name): """ This method allows you to reinstall a droplet with a default image. This is useful if you want to start again but retain the same IP address for your droplet. Required parameters: droplet_id: Numeric, this is the id of your droplet that you want to snapshot image_id: Numeric, this is the id of the image you would like to use to rebuild your droplet with """ if not droplet_id: raise DOPException('droplet_id is required to rebuild a droplet!') if not name: raise DOPException('name is required to rebuild a droplet!') params = {'name': name} json = self.request('/droplets/%s/rename' % droplet_id, method='GET', params=params) status = json.get('status') if status == 'OK': return json.get('event_id') else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
[ "def", "rename_droplet", "(", "self", ",", "droplet_id", ",", "name", ")", ":", "if", "not", "droplet_id", ":", "raise", "DOPException", "(", "'droplet_id is required to rebuild a droplet!'", ")", "if", "not", "name", ":", "raise", "DOPException", "(", "'name is r...
This method allows you to reinstall a droplet with a default image. This is useful if you want to start again but retain the same IP address for your droplet. Required parameters: droplet_id: Numeric, this is the id of your droplet that you want to snapshot image_id: Numeric, this is the id of the image you would like to use to rebuild your droplet with
[ "This", "method", "allows", "you", "to", "reinstall", "a", "droplet", "with", "a", "default", "image", ".", "This", "is", "useful", "if", "you", "want", "to", "start", "again", "but", "retain", "the", "same", "IP", "address", "for", "your", "droplet", "....
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L390-L417
ahmontero/dop
dop/client.py
Client.destroy_droplet
def destroy_droplet(self, droplet_id, scrub_data=False): """ This method destroys one of your droplets - this is irreversible. Required parameters: droplet_id: Numeric, this is the id of your droplet that you want to destroy Optional parameters scrub_data: Boolean, this will strictly write 0s to your prior partition to ensure that all data is completely erased """ params = {} if scrub_data: params['scrub_data'] = True json = self.request('/droplets/%s/destroy' % droplet_id, method='GET', params=params) status = json.get('status') if status == 'OK': return json.get('event_id') else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
def destroy_droplet(self, droplet_id, scrub_data=False): """ This method destroys one of your droplets - this is irreversible. Required parameters: droplet_id: Numeric, this is the id of your droplet that you want to destroy Optional parameters scrub_data: Boolean, this will strictly write 0s to your prior partition to ensure that all data is completely erased """ params = {} if scrub_data: params['scrub_data'] = True json = self.request('/droplets/%s/destroy' % droplet_id, method='GET', params=params) status = json.get('status') if status == 'OK': return json.get('event_id') else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
[ "def", "destroy_droplet", "(", "self", ",", "droplet_id", ",", "scrub_data", "=", "False", ")", ":", "params", "=", "{", "}", "if", "scrub_data", ":", "params", "[", "'scrub_data'", "]", "=", "True", "json", "=", "self", ".", "request", "(", "'/droplets/...
This method destroys one of your droplets - this is irreversible. Required parameters: droplet_id: Numeric, this is the id of your droplet that you want to destroy Optional parameters scrub_data: Boolean, this will strictly write 0s to your prior partition to ensure that all data is completely erased
[ "This", "method", "destroys", "one", "of", "your", "droplets", "-", "this", "is", "irreversible", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L419-L446
ahmontero/dop
dop/client.py
Client.regions
def regions(self): """ This method will return all the available regions within the DigitalOcean cloud. """ json = self.request('/regions', method='GET') status = json.get('status') if status == 'OK': regions_json = json.get('regions', []) regions = [Region.from_json(region) for region in regions_json] return regions else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
def regions(self): """ This method will return all the available regions within the DigitalOcean cloud. """ json = self.request('/regions', method='GET') status = json.get('status') if status == 'OK': regions_json = json.get('regions', []) regions = [Region.from_json(region) for region in regions_json] return regions else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
[ "def", "regions", "(", "self", ")", ":", "json", "=", "self", ".", "request", "(", "'/regions'", ",", "method", "=", "'GET'", ")", "status", "=", "json", ".", "get", "(", "'status'", ")", "if", "status", "==", "'OK'", ":", "regions_json", "=", "json"...
This method will return all the available regions within the DigitalOcean cloud.
[ "This", "method", "will", "return", "all", "the", "available", "regions", "within", "the", "DigitalOcean", "cloud", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L448-L461
ahmontero/dop
dop/client.py
Client.images
def images(self, filter='global'): """ This method returns all the available images that can be accessed by your client ID. You will have access to all public images by default, and any snapshots or backups that you have created in your own account. Optional parameters filter: String, either "my_images" or "global" """ if filter and filter not in ('my_images', 'global'): raise DOPException('"filter" must be either "my_images" or "global"') params = {} if filter: params['filter'] = filter json = self.request('/images', method='GET', params=params) status = json.get('status') if status == 'OK': images_json = json.get('images', []) images = [Image.from_json(image) for image in images_json] return images else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
def images(self, filter='global'): """ This method returns all the available images that can be accessed by your client ID. You will have access to all public images by default, and any snapshots or backups that you have created in your own account. Optional parameters filter: String, either "my_images" or "global" """ if filter and filter not in ('my_images', 'global'): raise DOPException('"filter" must be either "my_images" or "global"') params = {} if filter: params['filter'] = filter json = self.request('/images', method='GET', params=params) status = json.get('status') if status == 'OK': images_json = json.get('images', []) images = [Image.from_json(image) for image in images_json] return images else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
[ "def", "images", "(", "self", ",", "filter", "=", "'global'", ")", ":", "if", "filter", "and", "filter", "not", "in", "(", "'my_images'", ",", "'global'", ")", ":", "raise", "DOPException", "(", "'\"filter\" must be either \"my_images\" or \"global\"'", ")", "pa...
This method returns all the available images that can be accessed by your client ID. You will have access to all public images by default, and any snapshots or backups that you have created in your own account. Optional parameters filter: String, either "my_images" or "global"
[ "This", "method", "returns", "all", "the", "available", "images", "that", "can", "be", "accessed", "by", "your", "client", "ID", ".", "You", "will", "have", "access", "to", "all", "public", "images", "by", "default", "and", "any", "snapshots", "or", "backu...
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L463-L487
ahmontero/dop
dop/client.py
Client.show_image
def show_image(self, image_id_or_slug): """ This method displays the attributes of an image. Required parameters image_id: Numeric, this is the id of the image you would like to use to rebuild your droplet with """ if not image_id_or_slug: msg = 'image_id_or_slug is required to destroy an image!' raise DOPException(msg) json = self.request('/images/%s' % image_id_or_slug, method='GET') image_json = json.get('image') status = json.get('status') if status == 'OK': image = Image.from_json(image_json) return image else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
def show_image(self, image_id_or_slug): """ This method displays the attributes of an image. Required parameters image_id: Numeric, this is the id of the image you would like to use to rebuild your droplet with """ if not image_id_or_slug: msg = 'image_id_or_slug is required to destroy an image!' raise DOPException(msg) json = self.request('/images/%s' % image_id_or_slug, method='GET') image_json = json.get('image') status = json.get('status') if status == 'OK': image = Image.from_json(image_json) return image else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
[ "def", "show_image", "(", "self", ",", "image_id_or_slug", ")", ":", "if", "not", "image_id_or_slug", ":", "msg", "=", "'image_id_or_slug is required to destroy an image!'", "raise", "DOPException", "(", "msg", ")", "json", "=", "self", ".", "request", "(", "'/ima...
This method displays the attributes of an image. Required parameters image_id: Numeric, this is the id of the image you would like to use to rebuild your droplet with
[ "This", "method", "displays", "the", "attributes", "of", "an", "image", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L489-L511
ahmontero/dop
dop/client.py
Client.destroy_image
def destroy_image(self, image_id_or_slug): """ This method allows you to destroy an image. There is no way to restore a deleted image so be careful and ensure your data is properly backed up. Required parameters image_id: Numeric, this is the id of the image you would like to destroy """ if not image_id_or_slug: msg = 'image_id_or_slug is required to destroy an image!' raise DOPException(msg) json = self.request('/images/%s/destroy' % image_id_or_slug, method='GET') status = json.get('status') return status
python
def destroy_image(self, image_id_or_slug): """ This method allows you to destroy an image. There is no way to restore a deleted image so be careful and ensure your data is properly backed up. Required parameters image_id: Numeric, this is the id of the image you would like to destroy """ if not image_id_or_slug: msg = 'image_id_or_slug is required to destroy an image!' raise DOPException(msg) json = self.request('/images/%s/destroy' % image_id_or_slug, method='GET') status = json.get('status') return status
[ "def", "destroy_image", "(", "self", ",", "image_id_or_slug", ")", ":", "if", "not", "image_id_or_slug", ":", "msg", "=", "'image_id_or_slug is required to destroy an image!'", "raise", "DOPException", "(", "msg", ")", "json", "=", "self", ".", "request", "(", "'/...
This method allows you to destroy an image. There is no way to restore a deleted image so be careful and ensure your data is properly backed up. Required parameters image_id: Numeric, this is the id of the image you would like to destroy
[ "This", "method", "allows", "you", "to", "destroy", "an", "image", ".", "There", "is", "no", "way", "to", "restore", "a", "deleted", "image", "so", "be", "careful", "and", "ensure", "your", "data", "is", "properly", "backed", "up", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L513-L530
ahmontero/dop
dop/client.py
Client.transfer_image
def transfer_image(self, image_id_or_slug, region_id): """ This method allows you to transfer an image to a specified region. Required parameters image_id: Numeric, this is the id of the image you would like to transfer. region_id Numeric, this is the id of the region to which you would like to transfer. """ if not image_id_or_slug: msg = 'image_id_or_slug is required to transfer an image!' raise DOPException(msg) if not region_id: raise DOPException('region_id is required to transfer an image!') params = {'region_id': region_id} json = self.request('/images/%s/transfer' % image_id_or_slug, method='GET', params=params) status = json.get('status') if status == 'OK': return json.get('event_id') else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
def transfer_image(self, image_id_or_slug, region_id): """ This method allows you to transfer an image to a specified region. Required parameters image_id: Numeric, this is the id of the image you would like to transfer. region_id Numeric, this is the id of the region to which you would like to transfer. """ if not image_id_or_slug: msg = 'image_id_or_slug is required to transfer an image!' raise DOPException(msg) if not region_id: raise DOPException('region_id is required to transfer an image!') params = {'region_id': region_id} json = self.request('/images/%s/transfer' % image_id_or_slug, method='GET', params=params) status = json.get('status') if status == 'OK': return json.get('event_id') else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
[ "def", "transfer_image", "(", "self", ",", "image_id_or_slug", ",", "region_id", ")", ":", "if", "not", "image_id_or_slug", ":", "msg", "=", "'image_id_or_slug is required to transfer an image!'", "raise", "DOPException", "(", "msg", ")", "if", "not", "region_id", "...
This method allows you to transfer an image to a specified region. Required parameters image_id: Numeric, this is the id of the image you would like to transfer. region_id Numeric, this is the id of the region to which you would like to transfer.
[ "This", "method", "allows", "you", "to", "transfer", "an", "image", "to", "a", "specified", "region", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L532-L558
ahmontero/dop
dop/client.py
Client.ssh_keys
def ssh_keys(self): """ This method lists all the available public SSH keys in your account that can be added to a droplet. """ params = {} json = self.request('/ssh_keys', method='GET', params=params) status = json.get('status') if status == 'OK': ssh_keys_json = json.get('ssh_keys', []) keys = [SSHKey.from_json(ssh_key) for ssh_key in ssh_keys_json] return keys else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
def ssh_keys(self): """ This method lists all the available public SSH keys in your account that can be added to a droplet. """ params = {} json = self.request('/ssh_keys', method='GET', params=params) status = json.get('status') if status == 'OK': ssh_keys_json = json.get('ssh_keys', []) keys = [SSHKey.from_json(ssh_key) for ssh_key in ssh_keys_json] return keys else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
[ "def", "ssh_keys", "(", "self", ")", ":", "params", "=", "{", "}", "json", "=", "self", ".", "request", "(", "'/ssh_keys'", ",", "method", "=", "'GET'", ",", "params", "=", "params", ")", "status", "=", "json", ".", "get", "(", "'status'", ")", "if...
This method lists all the available public SSH keys in your account that can be added to a droplet.
[ "This", "method", "lists", "all", "the", "available", "public", "SSH", "keys", "in", "your", "account", "that", "can", "be", "added", "to", "a", "droplet", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L560-L574
ahmontero/dop
dop/client.py
Client.add_ssh_key
def add_ssh_key(self, name, ssh_pub_key): """ This method allows you to add a new public SSH key to your account. Required parameters name: String, the name you want to give this SSH key. ssh_pub_key: String, the actual public SSH key. """ params = {'name': name, 'ssh_pub_key': ssh_pub_key} json = self.request('/ssh_keys/new', method='GET', params=params) status = json.get('status') if status == 'OK': ssh_key_json = json.get('ssh_key') ssh_key = SSHKey.from_json(ssh_key_json) return ssh_key else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
def add_ssh_key(self, name, ssh_pub_key): """ This method allows you to add a new public SSH key to your account. Required parameters name: String, the name you want to give this SSH key. ssh_pub_key: String, the actual public SSH key. """ params = {'name': name, 'ssh_pub_key': ssh_pub_key} json = self.request('/ssh_keys/new', method='GET', params=params) status = json.get('status') if status == 'OK': ssh_key_json = json.get('ssh_key') ssh_key = SSHKey.from_json(ssh_key_json) return ssh_key else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
[ "def", "add_ssh_key", "(", "self", ",", "name", ",", "ssh_pub_key", ")", ":", "params", "=", "{", "'name'", ":", "name", ",", "'ssh_pub_key'", ":", "ssh_pub_key", "}", "json", "=", "self", ".", "request", "(", "'/ssh_keys/new'", ",", "method", "=", "'GET...
This method allows you to add a new public SSH key to your account. Required parameters name: String, the name you want to give this SSH key. ssh_pub_key: String, the actual public SSH key.
[ "This", "method", "allows", "you", "to", "add", "a", "new", "public", "SSH", "key", "to", "your", "account", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L576-L597
ahmontero/dop
dop/client.py
Client.show_ssh_key
def show_ssh_key(self, ssh_key_id): """ This method shows a specific public SSH key in your account that can be added to a droplet. """ params = {} json = self.request('/ssh_keys/%s' % ssh_key_id, method='GET', params=params) status = json.get('status') if status == 'OK': ssh_key_json = json.get('ssh_key') ssh_key = SSHKey.from_json(ssh_key_json) return ssh_key else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
def show_ssh_key(self, ssh_key_id): """ This method shows a specific public SSH key in your account that can be added to a droplet. """ params = {} json = self.request('/ssh_keys/%s' % ssh_key_id, method='GET', params=params) status = json.get('status') if status == 'OK': ssh_key_json = json.get('ssh_key') ssh_key = SSHKey.from_json(ssh_key_json) return ssh_key else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
[ "def", "show_ssh_key", "(", "self", ",", "ssh_key_id", ")", ":", "params", "=", "{", "}", "json", "=", "self", ".", "request", "(", "'/ssh_keys/%s'", "%", "ssh_key_id", ",", "method", "=", "'GET'", ",", "params", "=", "params", ")", "status", "=", "jso...
This method shows a specific public SSH key in your account that can be added to a droplet.
[ "This", "method", "shows", "a", "specific", "public", "SSH", "key", "in", "your", "account", "that", "can", "be", "added", "to", "a", "droplet", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L599-L613
ahmontero/dop
dop/client.py
Client.destroy_ssh_key
def destroy_ssh_key(self, ssh_key_id): """ This method will delete the SSH key from your account. """ json = self.request('/ssh_keys/%s/destroy' % ssh_key_id, method='GET') status = json.get('status') return status
python
def destroy_ssh_key(self, ssh_key_id): """ This method will delete the SSH key from your account. """ json = self.request('/ssh_keys/%s/destroy' % ssh_key_id, method='GET') status = json.get('status') return status
[ "def", "destroy_ssh_key", "(", "self", ",", "ssh_key_id", ")", ":", "json", "=", "self", ".", "request", "(", "'/ssh_keys/%s/destroy'", "%", "ssh_key_id", ",", "method", "=", "'GET'", ")", "status", "=", "json", ".", "get", "(", "'status'", ")", "return", ...
This method will delete the SSH key from your account.
[ "This", "method", "will", "delete", "the", "SSH", "key", "from", "your", "account", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L630-L636
ahmontero/dop
dop/client.py
Client.sizes
def sizes(self): """ This method returns all the available sizes that can be used to create a droplet. """ json = self.request('/sizes', method='GET') status = json.get('status') if status == 'OK': sizes_json = json.get('sizes', []) sizes = [Size.from_json(s) for s in sizes_json] return sizes else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
def sizes(self): """ This method returns all the available sizes that can be used to create a droplet. """ json = self.request('/sizes', method='GET') status = json.get('status') if status == 'OK': sizes_json = json.get('sizes', []) sizes = [Size.from_json(s) for s in sizes_json] return sizes else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
[ "def", "sizes", "(", "self", ")", ":", "json", "=", "self", ".", "request", "(", "'/sizes'", ",", "method", "=", "'GET'", ")", "status", "=", "json", ".", "get", "(", "'status'", ")", "if", "status", "==", "'OK'", ":", "sizes_json", "=", "json", "....
This method returns all the available sizes that can be used to create a droplet.
[ "This", "method", "returns", "all", "the", "available", "sizes", "that", "can", "be", "used", "to", "create", "a", "droplet", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L638-L651
ahmontero/dop
dop/client.py
Client.domains
def domains(self): """ This method returns all of your current domains. """ json = self.request('/domains', method='GET') status = json.get('status') if status == 'OK': domains_json = json.get('domains', []) domains = [Domain.from_json(domain) for domain in domains_json] return domains else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
def domains(self): """ This method returns all of your current domains. """ json = self.request('/domains', method='GET') status = json.get('status') if status == 'OK': domains_json = json.get('domains', []) domains = [Domain.from_json(domain) for domain in domains_json] return domains else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
[ "def", "domains", "(", "self", ")", ":", "json", "=", "self", ".", "request", "(", "'/domains'", ",", "method", "=", "'GET'", ")", "status", "=", "json", ".", "get", "(", "'status'", ")", "if", "status", "==", "'OK'", ":", "domains_json", "=", "json"...
This method returns all of your current domains.
[ "This", "method", "returns", "all", "of", "your", "current", "domains", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L653-L665
ahmontero/dop
dop/client.py
Client.create_domain
def create_domain(self, name, ip_address): """ This method creates a new domain name with an A record for the specified [ip_address]. Required parameters name: String, the name you want to give this SSH key. ip_address: String, ip address for the domain's initial a record. """ params = {'name': name, 'ip_address': ip_address} json = self.request('/domains/new', method='GET', params=params) status = json.get('status') if status == 'OK': domain_json = json.get('domain') domain = Domain.from_json(domain_json) return domain else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
def create_domain(self, name, ip_address): """ This method creates a new domain name with an A record for the specified [ip_address]. Required parameters name: String, the name you want to give this SSH key. ip_address: String, ip address for the domain's initial a record. """ params = {'name': name, 'ip_address': ip_address} json = self.request('/domains/new', method='GET', params=params) status = json.get('status') if status == 'OK': domain_json = json.get('domain') domain = Domain.from_json(domain_json) return domain else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
[ "def", "create_domain", "(", "self", ",", "name", ",", "ip_address", ")", ":", "params", "=", "{", "'name'", ":", "name", ",", "'ip_address'", ":", "ip_address", "}", "json", "=", "self", ".", "request", "(", "'/domains/new'", ",", "method", "=", "'GET'"...
This method creates a new domain name with an A record for the specified [ip_address]. Required parameters name: String, the name you want to give this SSH key. ip_address: String, ip address for the domain's initial a record.
[ "This", "method", "creates", "a", "new", "domain", "name", "with", "an", "A", "record", "for", "the", "specified", "[", "ip_address", "]", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L667-L688
ahmontero/dop
dop/client.py
Client.show_domain
def show_domain(self, domain_id): """ This method returns the specified domain. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain to display. """ json = self.request('/domains/%s' % domain_id, method='GET') status = json.get('status') if status == 'OK': domain_json = json.get('domain') domain = Domain.from_json(domain_json) return domain else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
def show_domain(self, domain_id): """ This method returns the specified domain. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain to display. """ json = self.request('/domains/%s' % domain_id, method='GET') status = json.get('status') if status == 'OK': domain_json = json.get('domain') domain = Domain.from_json(domain_json) return domain else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
[ "def", "show_domain", "(", "self", ",", "domain_id", ")", ":", "json", "=", "self", ".", "request", "(", "'/domains/%s'", "%", "domain_id", ",", "method", "=", "'GET'", ")", "status", "=", "json", ".", "get", "(", "'status'", ")", "if", "status", "==",...
This method returns the specified domain. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain to display.
[ "This", "method", "returns", "the", "specified", "domain", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L690-L708
ahmontero/dop
dop/client.py
Client.destroy_domain
def destroy_domain(self, domain_id): """ This method deletes the specified domain. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain to destroy. """ json = self.request('/domains/%s/destroy' % domain_id, method='GET') status = json.get('status') return status
python
def destroy_domain(self, domain_id): """ This method deletes the specified domain. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain to destroy. """ json = self.request('/domains/%s/destroy' % domain_id, method='GET') status = json.get('status') return status
[ "def", "destroy_domain", "(", "self", ",", "domain_id", ")", ":", "json", "=", "self", ".", "request", "(", "'/domains/%s/destroy'", "%", "domain_id", ",", "method", "=", "'GET'", ")", "status", "=", "json", ".", "get", "(", "'status'", ")", "return", "s...
This method deletes the specified domain. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain to destroy.
[ "This", "method", "deletes", "the", "specified", "domain", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L710-L722
ahmontero/dop
dop/client.py
Client.domain_records
def domain_records(self, domain_id): """ This method returns all of your current domain records. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to retrieve records. """ json = self.request('/domains/%s/records' % domain_id, method='GET') status = json.get('status') if status == 'OK': records_json = json.get('records', []) records = [Record.from_json(record) for record in records_json] return records else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
def domain_records(self, domain_id): """ This method returns all of your current domain records. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to retrieve records. """ json = self.request('/domains/%s/records' % domain_id, method='GET') status = json.get('status') if status == 'OK': records_json = json.get('records', []) records = [Record.from_json(record) for record in records_json] return records else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
[ "def", "domain_records", "(", "self", ",", "domain_id", ")", ":", "json", "=", "self", ".", "request", "(", "'/domains/%s/records'", "%", "domain_id", ",", "method", "=", "'GET'", ")", "status", "=", "json", ".", "get", "(", "'status'", ")", "if", "statu...
This method returns all of your current domain records. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to retrieve records.
[ "This", "method", "returns", "all", "of", "your", "current", "domain", "records", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L724-L742
ahmontero/dop
dop/client.py
Client.create_domain_record
def create_domain_record(self, domain_id, record_type, data, name=None, priority=None, port=None, weight=None): """ This method creates a new domain name with an A record for the specified [ip_address]. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to create a record. record_type: String, the type of record you would like to create. 'A', 'CNAME', 'NS', 'TXT', 'MX' or 'SRV' data: String, this is the value of the record Optional parameters name: String, required for 'A', 'CNAME', 'TXT' and 'SRV' records priority: Integer, required for 'SRV' and 'MX' records port: Integer, required for 'SRV' records weight: Integer, required for 'SRV' records """ params = dict(record_type=record_type, data=data) if name: params.update({'name': name}) if priority: params.update({'priority': priority}) if port: params.update({'port': port}) if weight: params.update({'weight': weight}) json = self.request('/domains/%s/records/new' % domain_id, method='GET', params=params) status = json.get('status') if status == 'OK': domain_record_json = json.get('domain_record') domain_record = Record.from_json(domain_record_json) return domain_record else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
def create_domain_record(self, domain_id, record_type, data, name=None, priority=None, port=None, weight=None): """ This method creates a new domain name with an A record for the specified [ip_address]. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to create a record. record_type: String, the type of record you would like to create. 'A', 'CNAME', 'NS', 'TXT', 'MX' or 'SRV' data: String, this is the value of the record Optional parameters name: String, required for 'A', 'CNAME', 'TXT' and 'SRV' records priority: Integer, required for 'SRV' and 'MX' records port: Integer, required for 'SRV' records weight: Integer, required for 'SRV' records """ params = dict(record_type=record_type, data=data) if name: params.update({'name': name}) if priority: params.update({'priority': priority}) if port: params.update({'port': port}) if weight: params.update({'weight': weight}) json = self.request('/domains/%s/records/new' % domain_id, method='GET', params=params) status = json.get('status') if status == 'OK': domain_record_json = json.get('domain_record') domain_record = Record.from_json(domain_record_json) return domain_record else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
[ "def", "create_domain_record", "(", "self", ",", "domain_id", ",", "record_type", ",", "data", ",", "name", "=", "None", ",", "priority", "=", "None", ",", "port", "=", "None", ",", "weight", "=", "None", ")", ":", "params", "=", "dict", "(", "record_t...
This method creates a new domain name with an A record for the specified [ip_address]. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to create a record. record_type: String, the type of record you would like to create. 'A', 'CNAME', 'NS', 'TXT', 'MX' or 'SRV' data: String, this is the value of the record Optional parameters name: String, required for 'A', 'CNAME', 'TXT' and 'SRV' records priority: Integer, required for 'SRV' and 'MX' records port: Integer, required for 'SRV' records weight: Integer, required for 'SRV' records
[ "This", "method", "creates", "a", "new", "domain", "name", "with", "an", "A", "record", "for", "the", "specified", "[", "ip_address", "]", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L744-L795
ahmontero/dop
dop/client.py
Client.show_domain_record
def show_domain_record(self, domain_id, record_id): """ This method returns the specified domain record. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to retrieve a record. record_id: Integer, specifies the record_id to retrieve. """ json = self.request('/domains/%s/records/%s' % (domain_id, record_id), method='GET') status = json.get('status') if status == 'OK': domain_record_json = json.get('record') domain_record = Record.from_json(domain_record_json) return domain_record else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
def show_domain_record(self, domain_id, record_id): """ This method returns the specified domain record. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to retrieve a record. record_id: Integer, specifies the record_id to retrieve. """ json = self.request('/domains/%s/records/%s' % (domain_id, record_id), method='GET') status = json.get('status') if status == 'OK': domain_record_json = json.get('record') domain_record = Record.from_json(domain_record_json) return domain_record else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
[ "def", "show_domain_record", "(", "self", ",", "domain_id", ",", "record_id", ")", ":", "json", "=", "self", ".", "request", "(", "'/domains/%s/records/%s'", "%", "(", "domain_id", ",", "record_id", ")", ",", "method", "=", "'GET'", ")", "status", "=", "js...
This method returns the specified domain record. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to retrieve a record. record_id: Integer, specifies the record_id to retrieve.
[ "This", "method", "returns", "the", "specified", "domain", "record", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L797-L819
ahmontero/dop
dop/client.py
Client.destroy_domain_record
def destroy_domain_record(self, domain_id, record_id): """ This method deletes the specified domain record. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to destroy a record. record_id: Integer, specifies the record_id to destroy. """ json = self.request('/domains/%s/records/%s/destroy' % (domain_id, record_id), method='GET') status = json.get('status') return status
python
def destroy_domain_record(self, domain_id, record_id): """ This method deletes the specified domain record. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to destroy a record. record_id: Integer, specifies the record_id to destroy. """ json = self.request('/domains/%s/records/%s/destroy' % (domain_id, record_id), method='GET') status = json.get('status') return status
[ "def", "destroy_domain_record", "(", "self", ",", "domain_id", ",", "record_id", ")", ":", "json", "=", "self", ".", "request", "(", "'/domains/%s/records/%s/destroy'", "%", "(", "domain_id", ",", "record_id", ")", ",", "method", "=", "'GET'", ")", "status", ...
This method deletes the specified domain record. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to destroy a record. record_id: Integer, specifies the record_id to destroy.
[ "This", "method", "deletes", "the", "specified", "domain", "record", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L877-L893
ahmontero/dop
dop/client.py
Client.events
def events(self, event_id): """ This method is primarily used to report on the progress of an event by providing the percentage of completion. Required parameters event_id: Numeric, this is the id of the event you would like more information about """ json = self.request('/events/%s' % event_id, method='GET') status = json.get('status') if status == 'OK': event_json = json.get('event') event = Event.from_json(event_json) return event else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
python
def events(self, event_id): """ This method is primarily used to report on the progress of an event by providing the percentage of completion. Required parameters event_id: Numeric, this is the id of the event you would like more information about """ json = self.request('/events/%s' % event_id, method='GET') status = json.get('status') if status == 'OK': event_json = json.get('event') event = Event.from_json(event_json) return event else: message = json.get('message') raise DOPException('[%s]: %s' % (status, message))
[ "def", "events", "(", "self", ",", "event_id", ")", ":", "json", "=", "self", ".", "request", "(", "'/events/%s'", "%", "event_id", ",", "method", "=", "'GET'", ")", "status", "=", "json", ".", "get", "(", "'status'", ")", "if", "status", "==", "'OK'...
This method is primarily used to report on the progress of an event by providing the percentage of completion. Required parameters event_id: Numeric, this is the id of the event you would like more information about
[ "This", "method", "is", "primarily", "used", "to", "report", "on", "the", "progress", "of", "an", "event", "by", "providing", "the", "percentage", "of", "completion", "." ]
train
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L895-L914
ebu/PlugIt
examples/simple_service_proxy_mode/server.py
get_ebuio_headers
def get_ebuio_headers(request): """Return a dict with ebuio headers""" retour = {} for (key, value) in request.headers: if key.startswith('X-Plugit-'): key = key[9:] retour[key] = value return retour
python
def get_ebuio_headers(request): """Return a dict with ebuio headers""" retour = {} for (key, value) in request.headers: if key.startswith('X-Plugit-'): key = key[9:] retour[key] = value return retour
[ "def", "get_ebuio_headers", "(", "request", ")", ":", "retour", "=", "{", "}", "for", "(", "key", ",", "value", ")", "in", "request", ".", "headers", ":", "if", "key", ".", "startswith", "(", "'X-Plugit-'", ")", ":", "key", "=", "key", "[", "9", ":...
Return a dict with ebuio headers
[ "Return", "a", "dict", "with", "ebuio", "headers" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/examples/simple_service_proxy_mode/server.py#L10-L21
gwastro/pycbc-glue
pycbc_glue/text_progress_bar.py
getTerminalSize
def getTerminalSize(): """ returns (lines:int, cols:int) """ def ioctl_GWINSZ(fd): # These two imports are only present on POSIX systems, so they must be # guarded by a try block. import fcntl import termios return struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234")) # try stdin, stdout, stderr for fd in (0, 1, 2): try: return ioctl_GWINSZ(fd) except: pass # try os.ctermid() try: fd = os.open(os.ctermid(), os.O_RDONLY) try: return ioctl_GWINSZ(fd) finally: os.close(fd) except: pass # try environment variables try: return tuple(int(os.getenv(var)) for var in ("LINES", "COLUMNS")) except: pass # i give up. return default. return (25, 80)
python
def getTerminalSize(): """ returns (lines:int, cols:int) """ def ioctl_GWINSZ(fd): # These two imports are only present on POSIX systems, so they must be # guarded by a try block. import fcntl import termios return struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234")) # try stdin, stdout, stderr for fd in (0, 1, 2): try: return ioctl_GWINSZ(fd) except: pass # try os.ctermid() try: fd = os.open(os.ctermid(), os.O_RDONLY) try: return ioctl_GWINSZ(fd) finally: os.close(fd) except: pass # try environment variables try: return tuple(int(os.getenv(var)) for var in ("LINES", "COLUMNS")) except: pass # i give up. return default. return (25, 80)
[ "def", "getTerminalSize", "(", ")", ":", "def", "ioctl_GWINSZ", "(", "fd", ")", ":", "# These two imports are only present on POSIX systems, so they must be", "# guarded by a try block.", "import", "fcntl", "import", "termios", "return", "struct", ".", "unpack", "(", "\"h...
returns (lines:int, cols:int)
[ "returns", "(", "lines", ":", "int", "cols", ":", "int", ")" ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/text_progress_bar.py#L30-L62