repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
zweifisch/biro
biro/__init__.py
route
def route(method, pattern, handler=None): """register a routing rule Example: route('GET', '/path/<param>', handler) """ if handler is None: return partial(route, method, pattern) return routes.append(method, pattern, handler)
python
def route(method, pattern, handler=None): """register a routing rule Example: route('GET', '/path/<param>', handler) """ if handler is None: return partial(route, method, pattern) return routes.append(method, pattern, handler)
[ "def", "route", "(", "method", ",", "pattern", ",", "handler", "=", "None", ")", ":", "if", "handler", "is", "None", ":", "return", "partial", "(", "route", ",", "method", ",", "pattern", ")", "return", "routes", ".", "append", "(", "method", ",", "p...
register a routing rule Example: route('GET', '/path/<param>', handler)
[ "register", "a", "routing", "rule" ]
train
https://github.com/zweifisch/biro/blob/0712746de65ff1e25b4f99c669eddd1fb8d1043e/biro/__init__.py#L14-L24
eallik/spinoff
spinoff/actor/util.py
Container.spawn
def spawn(self, owner, *args, **kwargs): """Spawns a new subordinate actor of `owner` and stores it in this container. jobs = Container() ... jobs.spawn(self, Job) jobs.spawn(self, Job, some_param=123) jobs = Container(Job) ... jobs.spawn(self) j...
python
def spawn(self, owner, *args, **kwargs): """Spawns a new subordinate actor of `owner` and stores it in this container. jobs = Container() ... jobs.spawn(self, Job) jobs.spawn(self, Job, some_param=123) jobs = Container(Job) ... jobs.spawn(self) j...
[ "def", "spawn", "(", "self", ",", "owner", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "(", "self", ".", "_spawn", "(", "owner", ",", "self", ".", "factory", ",", "*", "args", ",", "*", "*", "kwargs", ")", "if", "self", ".", ...
Spawns a new subordinate actor of `owner` and stores it in this container. jobs = Container() ... jobs.spawn(self, Job) jobs.spawn(self, Job, some_param=123) jobs = Container(Job) ... jobs.spawn(self) jobs.spawn(self, some_param=123) jobs = Cont...
[ "Spawns", "a", "new", "subordinate", "actor", "of", "owner", "and", "stores", "it", "in", "this", "container", "." ]
train
https://github.com/eallik/spinoff/blob/06b00d6b86c7422c9cb8f9a4b2915906e92b7d52/spinoff/actor/util.py#L22-L44
naphatkrit/easyci
easyci/commands/watch.py
watch
def watch(ctx): """Watch the directory for changes. Automatically run tests. """ vcs = ctx.obj['vcs'] event_handler = TestsEventHandler(vcs) observer = Observer() observer.schedule(event_handler, vcs.path, recursive=True) observer.start() click.echo('Watching directory `{path}`. Use ct...
python
def watch(ctx): """Watch the directory for changes. Automatically run tests. """ vcs = ctx.obj['vcs'] event_handler = TestsEventHandler(vcs) observer = Observer() observer.schedule(event_handler, vcs.path, recursive=True) observer.start() click.echo('Watching directory `{path}`. Use ct...
[ "def", "watch", "(", "ctx", ")", ":", "vcs", "=", "ctx", ".", "obj", "[", "'vcs'", "]", "event_handler", "=", "TestsEventHandler", "(", "vcs", ")", "observer", "=", "Observer", "(", ")", "observer", ".", "schedule", "(", "event_handler", ",", "vcs", "....
Watch the directory for changes. Automatically run tests.
[ "Watch", "the", "directory", "for", "changes", ".", "Automatically", "run", "tests", "." ]
train
https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/commands/watch.py#L12-L24
eugene-eeo/exthread
exthread.py
ExThread.join
def join(self, timeout=None): """ Wait for the thread to finish, may raise an exception (if any is uncaught during execution), and return the value returned by the target function. """ rv = self.thread.join(timeout) if self.err: raise self.err ...
python
def join(self, timeout=None): """ Wait for the thread to finish, may raise an exception (if any is uncaught during execution), and return the value returned by the target function. """ rv = self.thread.join(timeout) if self.err: raise self.err ...
[ "def", "join", "(", "self", ",", "timeout", "=", "None", ")", ":", "rv", "=", "self", ".", "thread", ".", "join", "(", "timeout", ")", "if", "self", ".", "err", ":", "raise", "self", ".", "err", "return", "self", ".", "val" ]
Wait for the thread to finish, may raise an exception (if any is uncaught during execution), and return the value returned by the target function.
[ "Wait", "for", "the", "thread", "to", "finish", "may", "raise", "an", "exception", "(", "if", "any", "is", "uncaught", "during", "execution", ")", "and", "return", "the", "value", "returned", "by", "the", "target", "function", "." ]
train
https://github.com/eugene-eeo/exthread/blob/4ea5ae799b4d860786bbd1d860288838e2e7f2e1/exthread.py#L46-L56
minhhoit/yacms
yacms/conf/context_processors.py
settings
def settings(request=None): """ Add the settings object to the template context. """ from yacms.conf import settings allowed_settings = settings.TEMPLATE_ACCESSIBLE_SETTINGS template_settings = TemplateSettings(settings, allowed_settings) template_settings.update(DEPRECATED) # This is...
python
def settings(request=None): """ Add the settings object to the template context. """ from yacms.conf import settings allowed_settings = settings.TEMPLATE_ACCESSIBLE_SETTINGS template_settings = TemplateSettings(settings, allowed_settings) template_settings.update(DEPRECATED) # This is...
[ "def", "settings", "(", "request", "=", "None", ")", ":", "from", "yacms", ".", "conf", "import", "settings", "allowed_settings", "=", "settings", ".", "TEMPLATE_ACCESSIBLE_SETTINGS", "template_settings", "=", "TemplateSettings", "(", "settings", ",", "allowed_setti...
Add the settings object to the template context.
[ "Add", "the", "settings", "object", "to", "the", "template", "context", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/conf/context_processors.py#L51-L70
alexhayes/django-toolkit
django_toolkit/forms/fields.py
MultiEmailField.validate
def validate(self, value): "Check if value consists only of valid emails." # Use the parent's handling of required fields, etc. super(MultiEmailField, self).validate(value) for email in value: validate_email(email)
python
def validate(self, value): "Check if value consists only of valid emails." # Use the parent's handling of required fields, etc. super(MultiEmailField, self).validate(value) for email in value: validate_email(email)
[ "def", "validate", "(", "self", ",", "value", ")", ":", "# Use the parent's handling of required fields, etc.", "super", "(", "MultiEmailField", ",", "self", ")", ".", "validate", "(", "value", ")", "for", "email", "in", "value", ":", "validate_email", "(", "ema...
Check if value consists only of valid emails.
[ "Check", "if", "value", "consists", "only", "of", "valid", "emails", "." ]
train
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/forms/fields.py#L37-L44
StanfordBioinformatics/scgpm_seqresults_dnanexus
scgpm_seqresults_dnanexus/scripts/batch_download_fastqs.py
log_file_name
def log_file_name(ext=False): """ Function : Creates a logfile name, named after this script and includes the number of seconds since the Epoch. An optional extension can be specified to make the logfile name more meaningful regarding its purpose. Args : ext - The extension to add to the log file...
python
def log_file_name(ext=False): """ Function : Creates a logfile name, named after this script and includes the number of seconds since the Epoch. An optional extension can be specified to make the logfile name more meaningful regarding its purpose. Args : ext - The extension to add to the log file...
[ "def", "log_file_name", "(", "ext", "=", "False", ")", ":", "script_name", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "sys", ".", "argv", "[", "0", "]", ")", ")", "[", "0", "]", "val", "=", "script_name...
Function : Creates a logfile name, named after this script and includes the number of seconds since the Epoch. An optional extension can be specified to make the logfile name more meaningful regarding its purpose. Args : ext - The extension to add to the log file name to indicate its purpose, i.e. ER...
[ "Function", ":", "Creates", "a", "logfile", "name", "named", "after", "this", "script", "and", "includes", "the", "number", "of", "seconds", "since", "the", "Epoch", ".", "An", "optional", "extension", "can", "be", "specified", "to", "make", "the", "logfile"...
train
https://github.com/StanfordBioinformatics/scgpm_seqresults_dnanexus/blob/2bdaae5ec5d38a07fec99e0c5379074a591d77b6/scgpm_seqresults_dnanexus/scripts/batch_download_fastqs.py#L29-L41
jut-io/jut-python-tools
jut/commands/programs.py
list
def list(options): """ list programs that belong to the authenticated user """ configuration = config.get_default() app_url = configuration['app_url'] if options.deployment != None: deployment_name = options.deployment else: deployment_name = configuration['deployment_name'...
python
def list(options): """ list programs that belong to the authenticated user """ configuration = config.get_default() app_url = configuration['app_url'] if options.deployment != None: deployment_name = options.deployment else: deployment_name = configuration['deployment_name'...
[ "def", "list", "(", "options", ")", ":", "configuration", "=", "config", ".", "get_default", "(", ")", "app_url", "=", "configuration", "[", "'app_url'", "]", "if", "options", ".", "deployment", "!=", "None", ":", "deployment_name", "=", "options", ".", "d...
list programs that belong to the authenticated user
[ "list", "programs", "that", "belong", "to", "the", "authenticated", "user" ]
train
https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/commands/programs.py#L22-L82
jut-io/jut-python-tools
jut/commands/programs.py
pull
def pull(options): """ pull all remote programs to a local directory """ configuration = config.get_default() app_url = configuration['app_url'] if options.deployment != None: deployment_name = options.deployment else: deployment_name = configuration['deployment_name'] ...
python
def pull(options): """ pull all remote programs to a local directory """ configuration = config.get_default() app_url = configuration['app_url'] if options.deployment != None: deployment_name = options.deployment else: deployment_name = configuration['deployment_name'] ...
[ "def", "pull", "(", "options", ")", ":", "configuration", "=", "config", ".", "get_default", "(", ")", "app_url", "=", "configuration", "[", "'app_url'", "]", "if", "options", ".", "deployment", "!=", "None", ":", "deployment_name", "=", "options", ".", "d...
pull all remote programs to a local directory
[ "pull", "all", "remote", "programs", "to", "a", "local", "directory" ]
train
https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/commands/programs.py#L89-L199
heikomuller/sco-client
scocli/image.py
ImageGroupHandle.create
def create(url, filename, options, properties): """Create new image group at given SCO-API by uploading local file. Expects an tar-archive containing images in the image group. Allows to update properties of created resource. Parameters ---------- url : string ...
python
def create(url, filename, options, properties): """Create new image group at given SCO-API by uploading local file. Expects an tar-archive containing images in the image group. Allows to update properties of created resource. Parameters ---------- url : string ...
[ "def", "create", "(", "url", ",", "filename", ",", "options", ",", "properties", ")", ":", "# Ensure that the file has valid suffix", "if", "not", "has_tar_suffix", "(", "filename", ")", ":", "raise", "ValueError", "(", "'invalid file suffix: '", "+", "filename", ...
Create new image group at given SCO-API by uploading local file. Expects an tar-archive containing images in the image group. Allows to update properties of created resource. Parameters ---------- url : string Url to POST image group create request filename :...
[ "Create", "new", "image", "group", "at", "given", "SCO", "-", "API", "by", "uploading", "local", "file", ".", "Expects", "an", "tar", "-", "archive", "containing", "images", "in", "the", "image", "group", ".", "Allows", "to", "update", "properties", "of", ...
train
https://github.com/heikomuller/sco-client/blob/c4afab71297f73003379bba4c1679be9dcf7cef8/scocli/image.py#L143-L212
spookey/photon
photon/photon.py
check_m
def check_m(pm): ''' Shared helper function for all :ref:`tools` to check if the passed m-function is indeed :func:`photon.Photon.m` :params pm: Suspected m-function :returns: Now to be proven correct m-function, tears down whole application otherwise. ''' if not an...
python
def check_m(pm): ''' Shared helper function for all :ref:`tools` to check if the passed m-function is indeed :func:`photon.Photon.m` :params pm: Suspected m-function :returns: Now to be proven correct m-function, tears down whole application otherwise. ''' if not an...
[ "def", "check_m", "(", "pm", ")", ":", "if", "not", "any", "(", "[", "callable", "(", "pm", ")", ",", "pm", ".", "__name__", "!=", "Photon", ".", "m", ".", "__name__", ",", "pm", ".", "__doc__", "!=", "Photon", ".", "m", ".", "__doc__", "]", ")...
Shared helper function for all :ref:`tools` to check if the passed m-function is indeed :func:`photon.Photon.m` :params pm: Suspected m-function :returns: Now to be proven correct m-function, tears down whole application otherwise.
[ "Shared", "helper", "function", "for", "all", ":", "ref", ":", "tools", "to", "check", "if", "the", "passed", "m", "-", "function", "is", "indeed", ":", "func", ":", "photon", ".", "Photon", ".", "m" ]
train
https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/photon.py#L6-L28
spookey/photon
photon/photon.py
Photon.m
def m(self, msg, state=False, more=None, cmdd=None, critical=True, verbose=None): ''' Mysterious mega method managing multiple meshed modules magically .. note:: If this function is used, the code contains facepalms: ``m(`` * It is possible to just show a message, \ o...
python
def m(self, msg, state=False, more=None, cmdd=None, critical=True, verbose=None): ''' Mysterious mega method managing multiple meshed modules magically .. note:: If this function is used, the code contains facepalms: ``m(`` * It is possible to just show a message, \ o...
[ "def", "m", "(", "self", ",", "msg", ",", "state", "=", "False", ",", "more", "=", "None", ",", "cmdd", "=", "None", ",", "critical", "=", "True", ",", "verbose", "=", "None", ")", ":", "if", "verbose", "is", "None", ":", "verbose", "=", "self", ...
Mysterious mega method managing multiple meshed modules magically .. note:: If this function is used, the code contains facepalms: ``m(`` * It is possible to just show a message, \ or to run a command with message. * But it is not possible to run a command without a message, \ ...
[ "Mysterious", "mega", "method", "managing", "multiple", "meshed", "modules", "magically" ]
train
https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/photon.py#L91-L167
spookey/photon
photon/photon.py
Photon.s2m
def s2m(self): ''' Imports settings to meta ''' m = '%s settings' % (IDENT) self.meta.load(m, 'import %s' % (m), mdict=self.settings.get)
python
def s2m(self): ''' Imports settings to meta ''' m = '%s settings' % (IDENT) self.meta.load(m, 'import %s' % (m), mdict=self.settings.get)
[ "def", "s2m", "(", "self", ")", ":", "m", "=", "'%s settings'", "%", "(", "IDENT", ")", "self", ".", "meta", ".", "load", "(", "m", ",", "'import %s'", "%", "(", "m", ")", ",", "mdict", "=", "self", ".", "settings", ".", "get", ")" ]
Imports settings to meta
[ "Imports", "settings", "to", "meta" ]
train
https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/photon.py#L170-L176
spookey/photon
photon/photon.py
Photon.mail_handler
def mail_handler(self, punchline=None, add_meta=False, add_settings=True, *args, **kwargs): ''' :param punchline: Adds a punchline before further text :param add_meta: Appends current meta to the mail :param add_settings: ...
python
def mail_handler(self, punchline=None, add_meta=False, add_settings=True, *args, **kwargs): ''' :param punchline: Adds a punchline before further text :param add_meta: Appends current meta to the mail :param add_settings: ...
[ "def", "mail_handler", "(", "self", ",", "punchline", "=", "None", ",", "add_meta", "=", "False", ",", "add_settings", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "m", "=", "Mail", "(", "self", ".", "m", ",", "*", "args", ",...
:param punchline: Adds a punchline before further text :param add_meta: Appends current meta to the mail :param add_settings: Appends current settings to the mail :returns: A new mail handler .. seealso:: :ref:`tools_mail`
[ ":", "param", "punchline", ":", "Adds", "a", "punchline", "before", "further", "text", ":", "param", "add_meta", ":", "Appends", "current", "meta", "to", "the", "mail", ":", "param", "add_settings", ":", "Appends", "current", "settings", "to", "the", "mail",...
train
https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/photon.py#L188-L211
nickmilon/Hellas
Hellas/Pella.py
file_to_base64
def file_to_base64(path_or_obj, max_mb=None): """converts contents of a file to base64 encoding :param str_or_object path_or_obj: fool pathname string for a file or a file like object that supports read :param int max_mb: maximum number in MegaBytes to accept :param float lon2: longitude of second plac...
python
def file_to_base64(path_or_obj, max_mb=None): """converts contents of a file to base64 encoding :param str_or_object path_or_obj: fool pathname string for a file or a file like object that supports read :param int max_mb: maximum number in MegaBytes to accept :param float lon2: longitude of second plac...
[ "def", "file_to_base64", "(", "path_or_obj", ",", "max_mb", "=", "None", ")", ":", "if", "not", "hasattr", "(", "path_or_obj", ",", "'read'", ")", ":", "rt", "=", "read_file", "(", "path_or_obj", ")", "else", ":", "rt", "=", "path_or_obj", ".", "read", ...
converts contents of a file to base64 encoding :param str_or_object path_or_obj: fool pathname string for a file or a file like object that supports read :param int max_mb: maximum number in MegaBytes to accept :param float lon2: longitude of second place (decimal degrees) :raises ErrorFileTooBig: if ...
[ "converts", "contents", "of", "a", "file", "to", "base64", "encoding" ]
train
https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Pella.py#L27-L45
nickmilon/Hellas
Hellas/Pella.py
dict_copy
def dict_copy(a_dict, exclude_keys_lst=[], exclude_values_lst=[]): """a **SALLOW** copy of a dict that excludes items in exclude_keys_lst and exclude_values_lst useful for copying locals() etc.. :param dict a_dict: dictionary to be copied :param list exclude_keys_lst: a list or tuple of keys to exclude...
python
def dict_copy(a_dict, exclude_keys_lst=[], exclude_values_lst=[]): """a **SALLOW** copy of a dict that excludes items in exclude_keys_lst and exclude_values_lst useful for copying locals() etc.. :param dict a_dict: dictionary to be copied :param list exclude_keys_lst: a list or tuple of keys to exclude...
[ "def", "dict_copy", "(", "a_dict", ",", "exclude_keys_lst", "=", "[", "]", ",", "exclude_values_lst", "=", "[", "]", ")", ":", "return", "dict", "(", "[", "copy", "(", "i", ")", "for", "i", "in", "list", "(", "a_dict", ".", "items", "(", ")", ")", ...
a **SALLOW** copy of a dict that excludes items in exclude_keys_lst and exclude_values_lst useful for copying locals() etc.. :param dict a_dict: dictionary to be copied :param list exclude_keys_lst: a list or tuple of keys to exclude :param list exclude_values_lst: a list or tuple of values to exclude ...
[ "a", "**", "SALLOW", "**", "copy", "of", "a", "dict", "that", "excludes", "items", "in", "exclude_keys_lst", "and", "exclude_values_lst", "useful", "for", "copying", "locals", "()", "etc", ".." ]
train
https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Pella.py#L49-L60
nickmilon/Hellas
Hellas/Pella.py
dict_clip
def dict_clip(a_dict, inlude_keys_lst=[]): """returns a new dict with keys not in included in inlude_keys_lst clipped off""" return dict([[i[0], i[1]] for i in list(a_dict.items()) if i[0] in inlude_keys_lst])
python
def dict_clip(a_dict, inlude_keys_lst=[]): """returns a new dict with keys not in included in inlude_keys_lst clipped off""" return dict([[i[0], i[1]] for i in list(a_dict.items()) if i[0] in inlude_keys_lst])
[ "def", "dict_clip", "(", "a_dict", ",", "inlude_keys_lst", "=", "[", "]", ")", ":", "return", "dict", "(", "[", "[", "i", "[", "0", "]", ",", "i", "[", "1", "]", "]", "for", "i", "in", "list", "(", "a_dict", ".", "items", "(", ")", ")", "if",...
returns a new dict with keys not in included in inlude_keys_lst clipped off
[ "returns", "a", "new", "dict", "with", "keys", "not", "in", "included", "in", "inlude_keys_lst", "clipped", "off" ]
train
https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Pella.py#L63-L65
nickmilon/Hellas
Hellas/Pella.py
list_pp
def list_pp(ll, separator='|', header_line=True, autonumber=True): """pretty print list of lists ll""" if autonumber: for cnt, i in enumerate(ll): i.insert(0, cnt if cnt > 0 or not header_line else '#') def lenlst(l): return [len(str(i)) for i in l] lst_len = [lenlst(i) for...
python
def list_pp(ll, separator='|', header_line=True, autonumber=True): """pretty print list of lists ll""" if autonumber: for cnt, i in enumerate(ll): i.insert(0, cnt if cnt > 0 or not header_line else '#') def lenlst(l): return [len(str(i)) for i in l] lst_len = [lenlst(i) for...
[ "def", "list_pp", "(", "ll", ",", "separator", "=", "'|'", ",", "header_line", "=", "True", ",", "autonumber", "=", "True", ")", ":", "if", "autonumber", ":", "for", "cnt", ",", "i", "in", "enumerate", "(", "ll", ")", ":", "i", ".", "insert", "(", ...
pretty print list of lists ll
[ "pretty", "print", "list", "of", "lists", "ll" ]
train
https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Pella.py#L74-L95
nickmilon/Hellas
Hellas/Pella.py
signal_terminate
def signal_terminate(on_terminate): """a common case program termination signal""" for i in [signal.SIGINT, signal.SIGQUIT, signal.SIGUSR1, signal.SIGUSR2, signal.SIGTERM]: signal.signal(i, on_terminate)
python
def signal_terminate(on_terminate): """a common case program termination signal""" for i in [signal.SIGINT, signal.SIGQUIT, signal.SIGUSR1, signal.SIGUSR2, signal.SIGTERM]: signal.signal(i, on_terminate)
[ "def", "signal_terminate", "(", "on_terminate", ")", ":", "for", "i", "in", "[", "signal", ".", "SIGINT", ",", "signal", ".", "SIGQUIT", ",", "signal", ".", "SIGUSR1", ",", "signal", ".", "SIGUSR2", ",", "signal", ".", "SIGTERM", "]", ":", "signal", "....
a common case program termination signal
[ "a", "common", "case", "program", "termination", "signal" ]
train
https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Pella.py#L99-L102
nickmilon/Hellas
Hellas/Pella.py
obj_id_expanded
def obj_id_expanded(obj=None, size=99): """ :param obj (objectj): optional :param size (int): optional size of id(obj) to include defaults to 99 :Returns: id: (str) an id that of the form machine-name|ppid|pid|id(obj) """ return "{}|{}|{}{}".format(os.uname()[1], os.getppid(), os.getpid(), "" i...
python
def obj_id_expanded(obj=None, size=99): """ :param obj (objectj): optional :param size (int): optional size of id(obj) to include defaults to 99 :Returns: id: (str) an id that of the form machine-name|ppid|pid|id(obj) """ return "{}|{}|{}{}".format(os.uname()[1], os.getppid(), os.getpid(), "" i...
[ "def", "obj_id_expanded", "(", "obj", "=", "None", ",", "size", "=", "99", ")", ":", "return", "\"{}|{}|{}{}\"", ".", "format", "(", "os", ".", "uname", "(", ")", "[", "1", "]", ",", "os", ".", "getppid", "(", ")", ",", "os", ".", "getpid", "(", ...
:param obj (objectj): optional :param size (int): optional size of id(obj) to include defaults to 99 :Returns: id: (str) an id that of the form machine-name|ppid|pid|id(obj)
[ ":", "param", "obj", "(", "objectj", ")", ":", "optional", ":", "param", "size", "(", "int", ")", ":", "optional", "size", "of", "id", "(", "obj", ")", "to", "include", "defaults", "to", "99" ]
train
https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Pella.py#L152-L159
polysquare/jobstamps
jobstamps/jobstamp.py
_safe_mkdir
def _safe_mkdir(directory): """Create a directory, ignoring errors if it already exists.""" try: os.makedirs(directory) except OSError as error: if error.errno != errno.EEXIST: raise error
python
def _safe_mkdir(directory): """Create a directory, ignoring errors if it already exists.""" try: os.makedirs(directory) except OSError as error: if error.errno != errno.EEXIST: raise error
[ "def", "_safe_mkdir", "(", "directory", ")", ":", "try", ":", "os", ".", "makedirs", "(", "directory", ")", "except", "OSError", "as", "error", ":", "if", "error", ".", "errno", "!=", "errno", ".", "EEXIST", ":", "raise", "error" ]
Create a directory, ignoring errors if it already exists.
[ "Create", "a", "directory", "ignoring", "errors", "if", "it", "already", "exists", "." ]
train
https://github.com/polysquare/jobstamps/blob/49b4dec93b38c9db55643226a9788c675a53ef25/jobstamps/jobstamp.py#L23-L29
polysquare/jobstamps
jobstamps/jobstamp.py
_stamp
def _stamp(stampfile, func, *args, **kwargs): """Store the repr() of the return value of func in stampfile.""" value = func(*args, **kwargs) with open(stampfile, "wb") as stamp: stamp.truncate() pickle.dump(value, stamp) return value
python
def _stamp(stampfile, func, *args, **kwargs): """Store the repr() of the return value of func in stampfile.""" value = func(*args, **kwargs) with open(stampfile, "wb") as stamp: stamp.truncate() pickle.dump(value, stamp) return value
[ "def", "_stamp", "(", "stampfile", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "value", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "with", "open", "(", "stampfile", ",", "\"wb\"", ")", "as", "stamp", ":", ...
Store the repr() of the return value of func in stampfile.
[ "Store", "the", "repr", "()", "of", "the", "return", "value", "of", "func", "in", "stampfile", "." ]
train
https://github.com/polysquare/jobstamps/blob/49b4dec93b38c9db55643226a9788c675a53ef25/jobstamps/jobstamp.py#L32-L39
polysquare/jobstamps
jobstamps/jobstamp.py
_stamp_and_update_hook
def _stamp_and_update_hook(method, # suppress(too-many-arguments) dependencies, stampfile, func, *args, **kwargs): """Write stamp and call update_stampfile_hook on method.""" r...
python
def _stamp_and_update_hook(method, # suppress(too-many-arguments) dependencies, stampfile, func, *args, **kwargs): """Write stamp and call update_stampfile_hook on method.""" r...
[ "def", "_stamp_and_update_hook", "(", "method", ",", "# suppress(too-many-arguments)", "dependencies", ",", "stampfile", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "_stamp", "(", "stampfile", ",", "func", ",", "*", "args...
Write stamp and call update_stampfile_hook on method.
[ "Write", "stamp", "and", "call", "update_stampfile_hook", "on", "method", "." ]
train
https://github.com/polysquare/jobstamps/blob/49b4dec93b38c9db55643226a9788c675a53ef25/jobstamps/jobstamp.py#L42-L51
polysquare/jobstamps
jobstamps/jobstamp.py
_sha1_for_file
def _sha1_for_file(filename): """Return sha1 for contents of filename.""" with open(filename, "rb") as fileobj: contents = fileobj.read() return hashlib.sha1(contents).hexdigest()
python
def _sha1_for_file(filename): """Return sha1 for contents of filename.""" with open(filename, "rb") as fileobj: contents = fileobj.read() return hashlib.sha1(contents).hexdigest()
[ "def", "_sha1_for_file", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "fileobj", ":", "contents", "=", "fileobj", ".", "read", "(", ")", "return", "hashlib", ".", "sha1", "(", "contents", ")", ".", "hexdigest", ...
Return sha1 for contents of filename.
[ "Return", "sha1", "for", "contents", "of", "filename", "." ]
train
https://github.com/polysquare/jobstamps/blob/49b4dec93b38c9db55643226a9788c675a53ef25/jobstamps/jobstamp.py#L54-L58
polysquare/jobstamps
jobstamps/jobstamp.py
_out_of_date
def _out_of_date(func, *args, **kwargs): """Return out of date file and detail to run job.""" storage_directory = os.path.join(tempfile.gettempdir(), "jobstamps") stamp_input = "".join([func.__name__] + [repr(v) for v in args] + [repr(kwargs[k]) ...
python
def _out_of_date(func, *args, **kwargs): """Return out of date file and detail to run job.""" storage_directory = os.path.join(tempfile.gettempdir(), "jobstamps") stamp_input = "".join([func.__name__] + [repr(v) for v in args] + [repr(kwargs[k]) ...
[ "def", "_out_of_date", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "storage_directory", "=", "os", ".", "path", ".", "join", "(", "tempfile", ".", "gettempdir", "(", ")", ",", "\"jobstamps\"", ")", "stamp_input", "=", "\"\"", ".",...
Return out of date file and detail to run job.
[ "Return", "out", "of", "date", "file", "and", "detail", "to", "run", "job", "." ]
train
https://github.com/polysquare/jobstamps/blob/49b4dec93b38c9db55643226a9788c675a53ef25/jobstamps/jobstamp.py#L145-L189
polysquare/jobstamps
jobstamps/jobstamp.py
HashMethod.check_dependency
def check_dependency(self, dependency_path): """Check if mtime of dependency_path is greater than stored mtime.""" stored_hash = self._stamp_file_hashes.get(dependency_path) # This file was newly added, or we don't have a file # with stored hashes yet. Assume out of date. if not...
python
def check_dependency(self, dependency_path): """Check if mtime of dependency_path is greater than stored mtime.""" stored_hash = self._stamp_file_hashes.get(dependency_path) # This file was newly added, or we don't have a file # with stored hashes yet. Assume out of date. if not...
[ "def", "check_dependency", "(", "self", ",", "dependency_path", ")", ":", "stored_hash", "=", "self", ".", "_stamp_file_hashes", ".", "get", "(", "dependency_path", ")", "# This file was newly added, or we don't have a file", "# with stored hashes yet. Assume out of date.", "...
Check if mtime of dependency_path is greater than stored mtime.
[ "Check", "if", "mtime", "of", "dependency_path", "is", "greater", "than", "stored", "mtime", "." ]
train
https://github.com/polysquare/jobstamps/blob/49b4dec93b38c9db55643226a9788c675a53ef25/jobstamps/jobstamp.py#L96-L105
polysquare/jobstamps
jobstamps/jobstamp.py
HashMethod.update_stampfile_hook
def update_stampfile_hook(self, dependencies): # suppress(no-self-use) """Loop over all dependencies and store hash for each of them.""" hashes = {d: _sha1_for_file(d) for d in dependencies if os.path.exists(d)} with open(self._stamp_file_hashes_path, "wb") as hashes_file: ...
python
def update_stampfile_hook(self, dependencies): # suppress(no-self-use) """Loop over all dependencies and store hash for each of them.""" hashes = {d: _sha1_for_file(d) for d in dependencies if os.path.exists(d)} with open(self._stamp_file_hashes_path, "wb") as hashes_file: ...
[ "def", "update_stampfile_hook", "(", "self", ",", "dependencies", ")", ":", "# suppress(no-self-use)", "hashes", "=", "{", "d", ":", "_sha1_for_file", "(", "d", ")", "for", "d", "in", "dependencies", "if", "os", ".", "path", ".", "exists", "(", "d", ")", ...
Loop over all dependencies and store hash for each of them.
[ "Loop", "over", "all", "dependencies", "and", "store", "hash", "for", "each", "of", "them", "." ]
train
https://github.com/polysquare/jobstamps/blob/49b4dec93b38c9db55643226a9788c675a53ef25/jobstamps/jobstamp.py#L107-L112
markomanninen/abnum
abnum/main.py
Abnum.unicode_value
def unicode_value(self, string): """ String argument must be in unicode format. """ result = 0 # don't accept strings that contain numbers if self.regex_has_numbers.search(string): raise AbnumException(error_msg % string) else: num_str = se...
python
def unicode_value(self, string): """ String argument must be in unicode format. """ result = 0 # don't accept strings that contain numbers if self.regex_has_numbers.search(string): raise AbnumException(error_msg % string) else: num_str = se...
[ "def", "unicode_value", "(", "self", ",", "string", ")", ":", "result", "=", "0", "# don't accept strings that contain numbers", "if", "self", ".", "regex_has_numbers", ".", "search", "(", "string", ")", ":", "raise", "AbnumException", "(", "error_msg", "%", "st...
String argument must be in unicode format.
[ "String", "argument", "must", "be", "in", "unicode", "format", "." ]
train
https://github.com/markomanninen/abnum/blob/9bfc8f06f34d9a51aab038638f87e2bb5f9f4c99/abnum/main.py#L65-L81
ionata/dj-core
dj_core/utils.py
get_app_submodules
def get_app_submodules(submodule_name): """ From wagtail.utils Searches each app module for the specified submodule yields tuples of (app_name, module) """ for name, module in get_app_modules(): if module_has_submodule(module, submodule_name): yield name, import_module('%s.%s' % ...
python
def get_app_submodules(submodule_name): """ From wagtail.utils Searches each app module for the specified submodule yields tuples of (app_name, module) """ for name, module in get_app_modules(): if module_has_submodule(module, submodule_name): yield name, import_module('%s.%s' % ...
[ "def", "get_app_submodules", "(", "submodule_name", ")", ":", "for", "name", ",", "module", "in", "get_app_modules", "(", ")", ":", "if", "module_has_submodule", "(", "module", ",", "submodule_name", ")", ":", "yield", "name", ",", "import_module", "(", "'%s.%...
From wagtail.utils Searches each app module for the specified submodule yields tuples of (app_name, module)
[ "From", "wagtail", ".", "utils", "Searches", "each", "app", "module", "for", "the", "specified", "submodule", "yields", "tuples", "of", "(", "app_name", "module", ")" ]
train
https://github.com/ionata/dj-core/blob/7a3139fc433c17f27e7dc2cee8775db21e0b5c89/dj_core/utils.py#L50-L57
ionata/dj-core
dj_core/utils.py
import_from_string
def import_from_string(value): """Copy of rest_framework.settings.import_from_string""" value = value.replace('-', '_') try: module_path, class_name = value.rsplit('.', 1) module = import_module(module_path) return getattr(module, class_name) except (ImportError, AttributeError) ...
python
def import_from_string(value): """Copy of rest_framework.settings.import_from_string""" value = value.replace('-', '_') try: module_path, class_name = value.rsplit('.', 1) module = import_module(module_path) return getattr(module, class_name) except (ImportError, AttributeError) ...
[ "def", "import_from_string", "(", "value", ")", ":", "value", "=", "value", ".", "replace", "(", "'-'", ",", "'_'", ")", "try", ":", "module_path", ",", "class_name", "=", "value", ".", "rsplit", "(", "'.'", ",", "1", ")", "module", "=", "import_module...
Copy of rest_framework.settings.import_from_string
[ "Copy", "of", "rest_framework", ".", "settings", ".", "import_from_string" ]
train
https://github.com/ionata/dj-core/blob/7a3139fc433c17f27e7dc2cee8775db21e0b5c89/dj_core/utils.py#L70-L79
gebn/nibble
nibble/__main__.py
_parse_args
def _parse_args(args): """ Interpret command line arguments. :param args: `sys.argv` :return: The populated argparse namespace. """ parser = argparse.ArgumentParser(prog='nibble', description='Speed, distance and time ' ...
python
def _parse_args(args): """ Interpret command line arguments. :param args: `sys.argv` :return: The populated argparse namespace. """ parser = argparse.ArgumentParser(prog='nibble', description='Speed, distance and time ' ...
[ "def", "_parse_args", "(", "args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "'nibble'", ",", "description", "=", "'Speed, distance and time '", "'calculations around '", "'quantities of digital '", "'information.'", ")", "parser", ...
Interpret command line arguments. :param args: `sys.argv` :return: The populated argparse namespace.
[ "Interpret", "command", "line", "arguments", "." ]
train
https://github.com/gebn/nibble/blob/e82a2c43509ed38f3d039040591cc630fa676cb0/nibble/__main__.py#L14-L38
gebn/nibble
nibble/__main__.py
main
def main(args): """ Nibble's entry point. :param args: Command-line arguments, with the program in position 0. """ args = _parse_args(args) # sort out logging output and level level = util.log_level_from_vebosity(args.verbosity) root = logging.getLogger() root.setLevel(level) ...
python
def main(args): """ Nibble's entry point. :param args: Command-line arguments, with the program in position 0. """ args = _parse_args(args) # sort out logging output and level level = util.log_level_from_vebosity(args.verbosity) root = logging.getLogger() root.setLevel(level) ...
[ "def", "main", "(", "args", ")", ":", "args", "=", "_parse_args", "(", "args", ")", "# sort out logging output and level", "level", "=", "util", ".", "log_level_from_vebosity", "(", "args", ".", "verbosity", ")", "root", "=", "logging", ".", "getLogger", "(", ...
Nibble's entry point. :param args: Command-line arguments, with the program in position 0.
[ "Nibble", "s", "entry", "point", "." ]
train
https://github.com/gebn/nibble/blob/e82a2c43509ed38f3d039040591cc630fa676cb0/nibble/__main__.py#L41-L68
cirruscluster/cirruscluster
cirruscluster/ext/ansible/runner/action_plugins/normal.py
ActionModule.run
def run(self, conn, tmp, module_name, module_args, inject): ''' transfer & execute a module that is not 'copy' or 'template' ''' # shell and command are the same module if module_name == 'shell': module_name = 'command' module_args += " #USE_SHELL" vv("REMOTE_MO...
python
def run(self, conn, tmp, module_name, module_args, inject): ''' transfer & execute a module that is not 'copy' or 'template' ''' # shell and command are the same module if module_name == 'shell': module_name = 'command' module_args += " #USE_SHELL" vv("REMOTE_MO...
[ "def", "run", "(", "self", ",", "conn", ",", "tmp", ",", "module_name", ",", "module_args", ",", "inject", ")", ":", "# shell and command are the same module", "if", "module_name", "==", "'shell'", ":", "module_name", "=", "'command'", "module_args", "+=", "\" #...
transfer & execute a module that is not 'copy' or 'template'
[ "transfer", "&", "execute", "a", "module", "that", "is", "not", "copy", "or", "template" ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/action_plugins/normal.py#L36-L45
PSU-OIT-ARC/elasticmodels
elasticmodels/management/commands/__init__.py
get_models
def get_models(args): """ Parse a list of ModelName, appname or appname.ModelName list, and return the list of model classes in the IndexRegistry. If the list if falsy, return all the models in the registry. """ if args: models = [] for arg in args: match_found = Fals...
python
def get_models(args): """ Parse a list of ModelName, appname or appname.ModelName list, and return the list of model classes in the IndexRegistry. If the list if falsy, return all the models in the registry. """ if args: models = [] for arg in args: match_found = Fals...
[ "def", "get_models", "(", "args", ")", ":", "if", "args", ":", "models", "=", "[", "]", "for", "arg", "in", "args", ":", "match_found", "=", "False", "for", "model", "in", "registry", ".", "get_models", "(", ")", ":", "if", "model", ".", "_meta", "...
Parse a list of ModelName, appname or appname.ModelName list, and return the list of model classes in the IndexRegistry. If the list if falsy, return all the models in the registry.
[ "Parse", "a", "list", "of", "ModelName", "appname", "or", "appname", ".", "ModelName", "list", "and", "return", "the", "list", "of", "model", "classes", "in", "the", "IndexRegistry", ".", "If", "the", "list", "if", "falsy", "return", "all", "the", "models"...
train
https://github.com/PSU-OIT-ARC/elasticmodels/blob/67870508096f66123ef10b89789bbac06571cc80/elasticmodels/management/commands/__init__.py#L3-L26
RHInception/relent
src/relent/__init__.py
main
def main(): """ Main entry point. """ import jsonschema parser = argparse.ArgumentParser(version=__version__) parser.add_argument( '--verbose', action='store_true', default=False, help='Turn on verbose output.') parser.add_argument( '--header', action='store_true', de...
python
def main(): """ Main entry point. """ import jsonschema parser = argparse.ArgumentParser(version=__version__) parser.add_argument( '--verbose', action='store_true', default=False, help='Turn on verbose output.') parser.add_argument( '--header', action='store_true', de...
[ "def", "main", "(", ")", ":", "import", "jsonschema", "parser", "=", "argparse", ".", "ArgumentParser", "(", "version", "=", "__version__", ")", "parser", ".", "add_argument", "(", "'--verbose'", ",", "action", "=", "'store_true'", ",", "default", "=", "Fals...
Main entry point.
[ "Main", "entry", "point", "." ]
train
https://github.com/RHInception/relent/blob/e8e3eef54f59bf7a8befd84fb2429ef9912d71d5/src/relent/__init__.py#L25-L81
ryanjdillon/pyotelem
pyotelem/plots/plotdives.py
plot_dives
def plot_dives(dv0, dv1, p, dp, t_on, t_off): '''Plots depths and delta depths with dive start stop markers Args ---- dv0: int Index position of dive start in cue array dv1: int Index position of dive stop in cue array p: ndarray Depth values dp: ndarray Delt...
python
def plot_dives(dv0, dv1, p, dp, t_on, t_off): '''Plots depths and delta depths with dive start stop markers Args ---- dv0: int Index position of dive start in cue array dv1: int Index position of dive stop in cue array p: ndarray Depth values dp: ndarray Delt...
[ "def", "plot_dives", "(", "dv0", ",", "dv1", ",", "p", ",", "dp", ",", "t_on", ",", "t_off", ")", ":", "fig", ",", "(", "ax1", ",", "ax2", ")", "=", "plt", ".", "subplots", "(", "2", ",", "1", ",", "sharex", "=", "True", ")", "x0", "=", "t_...
Plots depths and delta depths with dive start stop markers Args ---- dv0: int Index position of dive start in cue array dv1: int Index position of dive stop in cue array p: ndarray Depth values dp: ndarray Delta depths t_on: ndarray Cue array with sta...
[ "Plots", "depths", "and", "delta", "depths", "with", "dive", "start", "stop", "markers" ]
train
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/plots/plotdives.py#L9-L63
ryanjdillon/pyotelem
pyotelem/plots/plotdives.py
plot_dives_pitch
def plot_dives_pitch(depths, dive_mask, des, asc, pitch, pitch_lf): '''Plot dives with phase and associated pitch angle with HF signal Args ---- depths: ndarray Depth values at each sensor sampling dive_mask: ndarray Boolean mask slicing dives from the tag data des: ndarray ...
python
def plot_dives_pitch(depths, dive_mask, des, asc, pitch, pitch_lf): '''Plot dives with phase and associated pitch angle with HF signal Args ---- depths: ndarray Depth values at each sensor sampling dive_mask: ndarray Boolean mask slicing dives from the tag data des: ndarray ...
[ "def", "plot_dives_pitch", "(", "depths", ",", "dive_mask", ",", "des", ",", "asc", ",", "pitch", ",", "pitch_lf", ")", ":", "import", "copy", "import", "numpy", "from", ".", "import", "plotutils", "fig", ",", "(", "ax1", ",", "ax2", ")", "=", "plt", ...
Plot dives with phase and associated pitch angle with HF signal Args ---- depths: ndarray Depth values at each sensor sampling dive_mask: ndarray Boolean mask slicing dives from the tag data des: ndarray boolean mask for slicing descent phases of dives from tag dta asc: ...
[ "Plot", "dives", "with", "phase", "and", "associated", "pitch", "angle", "with", "HF", "signal" ]
train
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/plots/plotdives.py#L66-L117
ryanjdillon/pyotelem
pyotelem/plots/plotdives.py
plot_depth_descent_ascent
def plot_depth_descent_ascent(depths, dive_mask, des, asc): '''Plot depth data for whole deployment, descents, and ascents Args ---- depths: ndarray Depth values at each sensor sampling dive_mask: ndarray Boolean mask slicing dives from the tag data des: ndarray boolean ...
python
def plot_depth_descent_ascent(depths, dive_mask, des, asc): '''Plot depth data for whole deployment, descents, and ascents Args ---- depths: ndarray Depth values at each sensor sampling dive_mask: ndarray Boolean mask slicing dives from the tag data des: ndarray boolean ...
[ "def", "plot_depth_descent_ascent", "(", "depths", ",", "dive_mask", ",", "des", ",", "asc", ")", ":", "import", "numpy", "from", ".", "import", "plotutils", "# Indices where depths are descents or ascents", "des_ind", "=", "numpy", ".", "where", "(", "dive_mask", ...
Plot depth data for whole deployment, descents, and ascents Args ---- depths: ndarray Depth values at each sensor sampling dive_mask: ndarray Boolean mask slicing dives from the tag data des: ndarray boolean mask for slicing descent phases of dives from tag dta asc: ndar...
[ "Plot", "depth", "data", "for", "whole", "deployment", "descents", "and", "ascents" ]
train
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/plots/plotdives.py#L120-L157
ryanjdillon/pyotelem
pyotelem/plots/plotdives.py
plot_triaxial_depths_speed
def plot_triaxial_depths_speed(tag): '''Plot triaxial accelerometer data for whole deployment, descents, and ascents Only x and z axes are ploted since these are associated with stroking Args ---- tag: pandas.DataFrame Tag dataframe with acceleromter, depth, and propeller columns '...
python
def plot_triaxial_depths_speed(tag): '''Plot triaxial accelerometer data for whole deployment, descents, and ascents Only x and z axes are ploted since these are associated with stroking Args ---- tag: pandas.DataFrame Tag dataframe with acceleromter, depth, and propeller columns '...
[ "def", "plot_triaxial_depths_speed", "(", "tag", ")", ":", "import", "numpy", "from", ".", "import", "plotutils", "# TODO return to multiple inputs rather than dataframe", "fig", ",", "axes", "=", "plt", ".", "subplots", "(", "3", ",", "3", ",", "sharex", "=", "...
Plot triaxial accelerometer data for whole deployment, descents, and ascents Only x and z axes are ploted since these are associated with stroking Args ---- tag: pandas.DataFrame Tag dataframe with acceleromter, depth, and propeller columns
[ "Plot", "triaxial", "accelerometer", "data", "for", "whole", "deployment", "descents", "and", "ascents" ]
train
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/plots/plotdives.py#L160-L203
ryanjdillon/pyotelem
pyotelem/plots/plotdives.py
plot_triaxial_descent_ascent
def plot_triaxial_descent_ascent(Ax, Az, des, asc): '''Plot triaxial accelerometer data for whole deployment, descents, and ascents Only x and z axes are ploted since these are associated with stroking Args ---- Ax: ndarray X-axis acclerometer data array Az: ndarray Z-axis ...
python
def plot_triaxial_descent_ascent(Ax, Az, des, asc): '''Plot triaxial accelerometer data for whole deployment, descents, and ascents Only x and z axes are ploted since these are associated with stroking Args ---- Ax: ndarray X-axis acclerometer data array Az: ndarray Z-axis ...
[ "def", "plot_triaxial_descent_ascent", "(", "Ax", ",", "Az", ",", "des", ",", "asc", ")", ":", "import", "numpy", "from", ".", "import", "plotutils", "fig", ",", "(", "(", "ax1", ",", "ax3", ")", ",", "(", "ax2", ",", "ax4", ")", ")", "=", "plt", ...
Plot triaxial accelerometer data for whole deployment, descents, and ascents Only x and z axes are ploted since these are associated with stroking Args ---- Ax: ndarray X-axis acclerometer data array Az: ndarray Z-axis acclerometer data array des: ndarray boolean ma...
[ "Plot", "triaxial", "accelerometer", "data", "for", "whole", "deployment", "descents", "and", "ascents" ]
train
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/plots/plotdives.py#L206-L252
BasementCat/bubbler
bubbler/__init__.py
Event.trigger
def trigger(self, *args, **kwargs): """Trigger this event. Any passed in args/kwargs are passed to the event handlers - if the event handlers cannot accept those arguments then they will cause an exception! """ current = self.name.split('/') while current: name = '/'.join(current) current.po...
python
def trigger(self, *args, **kwargs): """Trigger this event. Any passed in args/kwargs are passed to the event handlers - if the event handlers cannot accept those arguments then they will cause an exception! """ current = self.name.split('/') while current: name = '/'.join(current) current.po...
[ "def", "trigger", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "current", "=", "self", ".", "name", ".", "split", "(", "'/'", ")", "while", "current", ":", "name", "=", "'/'", ".", "join", "(", "current", ")", "current", ".",...
Trigger this event. Any passed in args/kwargs are passed to the event handlers - if the event handlers cannot accept those arguments then they will cause an exception!
[ "Trigger", "this", "event", ".", "Any", "passed", "in", "args", "/", "kwargs", "are", "passed", "to", "the", "event", "handlers", "-", "if", "the", "event", "handlers", "cannot", "accept", "those", "arguments", "then", "they", "will", "cause", "an", "excep...
train
https://github.com/BasementCat/bubbler/blob/ac3c6be8358cd4f448a95545c5b493581fd1854a/bubbler/__init__.py#L57-L82
BasementCat/bubbler
bubbler/__init__.py
Bubbler.getContext
def getContext(self, context_name = 'default'): """Get a context by name, create the default context if it does not exist Params: context_name (string): Context name Raises: KeyError: If the context name does not exist Returns: bubbler.Bubbler: Named context """ if con...
python
def getContext(self, context_name = 'default'): """Get a context by name, create the default context if it does not exist Params: context_name (string): Context name Raises: KeyError: If the context name does not exist Returns: bubbler.Bubbler: Named context """ if con...
[ "def", "getContext", "(", "self", ",", "context_name", "=", "'default'", ")", ":", "if", "context_name", "==", "'default'", "and", "'default'", "not", "in", "self", ".", "contexts", ":", "self", "(", "'default'", ")", "return", "self", ".", "contexts", "["...
Get a context by name, create the default context if it does not exist Params: context_name (string): Context name Raises: KeyError: If the context name does not exist Returns: bubbler.Bubbler: Named context
[ "Get", "a", "context", "by", "name", "create", "the", "default", "context", "if", "it", "does", "not", "exist", "Params", ":", "context_name", "(", "string", ")", ":", "Context", "name", "Raises", ":", "KeyError", ":", "If", "the", "context", "name", "do...
train
https://github.com/BasementCat/bubbler/blob/ac3c6be8358cd4f448a95545c5b493581fd1854a/bubbler/__init__.py#L120-L138
BasementCat/bubbler
bubbler/__init__.py
Bubbler.bind
def bind(self, event_name, callback, first = False): """Bind a callback to an event Params: event_name (string): Name of the event to bind to callback (callable): Callback that will be called when the event is triggered first (boolean): If True, this callback is placed before all the ...
python
def bind(self, event_name, callback, first = False): """Bind a callback to an event Params: event_name (string): Name of the event to bind to callback (callable): Callback that will be called when the event is triggered first (boolean): If True, this callback is placed before all the ...
[ "def", "bind", "(", "self", ",", "event_name", ",", "callback", ",", "first", "=", "False", ")", ":", "if", "event_name", "not", "in", "self", ".", "handlers", ":", "self", ".", "handlers", "[", "event_name", "]", "=", "[", "]", "if", "first", ":", ...
Bind a callback to an event Params: event_name (string): Name of the event to bind to callback (callable): Callback that will be called when the event is triggered first (boolean): If True, this callback is placed before all the other events already registered for this event, otherw...
[ "Bind", "a", "callback", "to", "an", "event", "Params", ":", "event_name", "(", "string", ")", ":", "Name", "of", "the", "event", "to", "bind", "to", "callback", "(", "callable", ")", ":", "Callback", "that", "will", "be", "called", "when", "the", "eve...
train
https://github.com/BasementCat/bubbler/blob/ac3c6be8358cd4f448a95545c5b493581fd1854a/bubbler/__init__.py#L140-L158
BasementCat/bubbler
bubbler/__init__.py
Bubbler.unbind
def unbind(self, callback, event_name = None): """Unbind a callback from an event Params: callback (callable): Callback to unbind event_name (string): If None (default) this callback is removed from every event to which it's bound. If a name is given then it is only removed from tha...
python
def unbind(self, callback, event_name = None): """Unbind a callback from an event Params: callback (callable): Callback to unbind event_name (string): If None (default) this callback is removed from every event to which it's bound. If a name is given then it is only removed from tha...
[ "def", "unbind", "(", "self", ",", "callback", ",", "event_name", "=", "None", ")", ":", "if", "event_name", "is", "None", ":", "for", "name", "in", "self", ".", "handlers", ".", "keys", "(", ")", ":", "self", ".", "unbind", "(", "callback", ",", "...
Unbind a callback from an event Params: callback (callable): Callback to unbind event_name (string): If None (default) this callback is removed from every event to which it's bound. If a name is given then it is only removed from that event, if it is bound to that event.
[ "Unbind", "a", "callback", "from", "an", "event", "Params", ":", "callback", "(", "callable", ")", ":", "Callback", "to", "unbind", "event_name", "(", "string", ")", ":", "If", "None", "(", "default", ")", "this", "callback", "is", "removed", "from", "ev...
train
https://github.com/BasementCat/bubbler/blob/ac3c6be8358cd4f448a95545c5b493581fd1854a/bubbler/__init__.py#L160-L177
BasementCat/bubbler
bubbler/__init__.py
Bubbler.trigger
def trigger(self, event_name, *args, **kwargs): """Trigger an event on this context. Params: event_name (string): Event name to trigger Args and kwargs are passed to each handler - see the bubbler.Event class for more information. Returns: bubbler.Event: Event instance after execu...
python
def trigger(self, event_name, *args, **kwargs): """Trigger an event on this context. Params: event_name (string): Event name to trigger Args and kwargs are passed to each handler - see the bubbler.Event class for more information. Returns: bubbler.Event: Event instance after execu...
[ "def", "trigger", "(", "self", ",", "event_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ev", "=", "Event", "(", "event_name", ",", "self", ")", "ev", ".", "trigger", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "ev" ]
Trigger an event on this context. Params: event_name (string): Event name to trigger Args and kwargs are passed to each handler - see the bubbler.Event class for more information. Returns: bubbler.Event: Event instance after execution of all handlers
[ "Trigger", "an", "event", "on", "this", "context", ".", "Params", ":", "event_name", "(", "string", ")", ":", "Event", "name", "to", "trigger", "Args", "and", "kwargs", "are", "passed", "to", "each", "handler", "-", "see", "the", "bubbler", ".", "Event",...
train
https://github.com/BasementCat/bubbler/blob/ac3c6be8358cd4f448a95545c5b493581fd1854a/bubbler/__init__.py#L179-L195
henrysher/kotocore
kotocore/resources.py
ResourceDetails.result_key_for
def result_key_for(self, op_name): """ Checks for the presence of a ``result_key``, which defines what data should make up an instance. Returns ``None`` if there is no ``result_key``. :param op_name: The operation name to look for the ``result_key`` in. :type op_name: s...
python
def result_key_for(self, op_name): """ Checks for the presence of a ``result_key``, which defines what data should make up an instance. Returns ``None`` if there is no ``result_key``. :param op_name: The operation name to look for the ``result_key`` in. :type op_name: s...
[ "def", "result_key_for", "(", "self", ",", "op_name", ")", ":", "ops", "=", "self", ".", "resource_data", ".", "get", "(", "'operations'", ",", "{", "}", ")", "op", "=", "ops", ".", "get", "(", "op_name", ",", "{", "}", ")", "key", "=", "op", "."...
Checks for the presence of a ``result_key``, which defines what data should make up an instance. Returns ``None`` if there is no ``result_key``. :param op_name: The operation name to look for the ``result_key`` in. :type op_name: string :returns: The expected key to look for d...
[ "Checks", "for", "the", "presence", "of", "a", "result_key", "which", "defines", "what", "data", "should", "make", "up", "an", "instance", "." ]
train
https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/resources.py#L132-L148
henrysher/kotocore
kotocore/resources.py
Resource._update_docstrings
def _update_docstrings(self): """ Runs through the operation methods & updates their docstrings if necessary. If the method has the default placeholder docstring, this will replace it with the docstring from the underlying connection. """ ops = self._details.reso...
python
def _update_docstrings(self): """ Runs through the operation methods & updates their docstrings if necessary. If the method has the default placeholder docstring, this will replace it with the docstring from the underlying connection. """ ops = self._details.reso...
[ "def", "_update_docstrings", "(", "self", ")", ":", "ops", "=", "self", ".", "_details", ".", "resource_data", "[", "'operations'", "]", "for", "method_name", "in", "ops", ".", "keys", "(", ")", ":", "meth", "=", "getattr", "(", "self", ".", "__class__",...
Runs through the operation methods & updates their docstrings if necessary. If the method has the default placeholder docstring, this will replace it with the docstring from the underlying connection.
[ "Runs", "through", "the", "operation", "methods", "&", "updates", "their", "docstrings", "if", "necessary", "." ]
train
https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/resources.py#L238-L271
henrysher/kotocore
kotocore/resources.py
Resource.set_identifiers
def set_identifiers(self, data): """ Sets the identifier(s) within the instance data. The identifier name(s) is/are determined from the ``ResourceDetails`` instance hanging off the class itself. :param data: The value(s) to be set. :param data: dict """ ...
python
def set_identifiers(self, data): """ Sets the identifier(s) within the instance data. The identifier name(s) is/are determined from the ``ResourceDetails`` instance hanging off the class itself. :param data: The value(s) to be set. :param data: dict """ ...
[ "def", "set_identifiers", "(", "self", ",", "data", ")", ":", "for", "id_info", "in", "self", ".", "_details", ".", "identifiers", ":", "var_name", "=", "id_info", "[", "'var_name'", "]", "self", ".", "_data", "[", "var_name", "]", "=", "data", ".", "g...
Sets the identifier(s) within the instance data. The identifier name(s) is/are determined from the ``ResourceDetails`` instance hanging off the class itself. :param data: The value(s) to be set. :param data: dict
[ "Sets", "the", "identifier", "(", "s", ")", "within", "the", "instance", "data", "." ]
train
https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/resources.py#L291-L310
henrysher/kotocore
kotocore/resources.py
Resource.build_relation
def build_relation(self, name, klass=None): """ Constructs a related ``Resource`` or ``Collection``. This allows for construction of classes with information prepopulated from what the current instance has. This enables syntax like:: bucket = Bucket(bucket='some-bucket-name...
python
def build_relation(self, name, klass=None): """ Constructs a related ``Resource`` or ``Collection``. This allows for construction of classes with information prepopulated from what the current instance has. This enables syntax like:: bucket = Bucket(bucket='some-bucket-name...
[ "def", "build_relation", "(", "self", ",", "name", ",", "klass", "=", "None", ")", ":", "try", ":", "rel_data", "=", "self", ".", "_details", ".", "relations", "[", "name", "]", "except", "KeyError", ":", "msg", "=", "\"No such relation named '{0}'.\"", "....
Constructs a related ``Resource`` or ``Collection``. This allows for construction of classes with information prepopulated from what the current instance has. This enables syntax like:: bucket = Bucket(bucket='some-bucket-name') for obj in bucket.objects.each(): ...
[ "Constructs", "a", "related", "Resource", "or", "Collection", "." ]
train
https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/resources.py#L312-L372
henrysher/kotocore
kotocore/resources.py
Resource.post_process_get
def post_process_get(self, result): """ Given an object with identifiers, fetches the data for that object from the service. This alters the data on the object itself & simply passes through what was received. :param result: The response data :type result: dict ...
python
def post_process_get(self, result): """ Given an object with identifiers, fetches the data for that object from the service. This alters the data on the object itself & simply passes through what was received. :param result: The response data :type result: dict ...
[ "def", "post_process_get", "(", "self", ",", "result", ")", ":", "if", "not", "hasattr", "(", "result", ",", "'items'", ")", ":", "# If it's not a dict, give up & just return whatever you get.", "return", "result", "# We need to possibly drill into the response & get out the ...
Given an object with identifiers, fetches the data for that object from the service. This alters the data on the object itself & simply passes through what was received. :param result: The response data :type result: dict :returns: The unmodified response data
[ "Given", "an", "object", "with", "identifiers", "fetches", "the", "data", "for", "that", "object", "from", "the", "service", "." ]
train
https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/resources.py#L489-L519
henrysher/kotocore
kotocore/resources.py
ResourceFactory.construct_for
def construct_for(self, service_name, resource_name, base_class=None): """ Builds a new, specialized ``Resource`` subclass as part of a given service. This will load the ``ResourceJSON``, determine the correct mappings/methods & constructs a brand new class with those methods on...
python
def construct_for(self, service_name, resource_name, base_class=None): """ Builds a new, specialized ``Resource`` subclass as part of a given service. This will load the ``ResourceJSON``, determine the correct mappings/methods & constructs a brand new class with those methods on...
[ "def", "construct_for", "(", "self", ",", "service_name", ",", "resource_name", ",", "base_class", "=", "None", ")", ":", "details", "=", "self", ".", "details_class", "(", "self", ".", "session", ",", "service_name", ",", "resource_name", ",", "loader", "="...
Builds a new, specialized ``Resource`` subclass as part of a given service. This will load the ``ResourceJSON``, determine the correct mappings/methods & constructs a brand new class with those methods on it. :param service_name: The name of the service to construct a resource ...
[ "Builds", "a", "new", "specialized", "Resource", "subclass", "as", "part", "of", "a", "given", "service", "." ]
train
https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/resources.py#L580-L624
awacha/credolib
credolib/io.py
filter_headers
def filter_headers(criterion): """Filter already loaded headers against some criterion. The criterion function must accept a single argument, which is an instance of sastool.classes2.header.Header, or one of its subclasses. The function must return True if the header is to be kept or False if it needs ...
python
def filter_headers(criterion): """Filter already loaded headers against some criterion. The criterion function must accept a single argument, which is an instance of sastool.classes2.header.Header, or one of its subclasses. The function must return True if the header is to be kept or False if it needs ...
[ "def", "filter_headers", "(", "criterion", ")", ":", "ip", "=", "get_ipython", "(", ")", "for", "headerkind", "in", "[", "'processed'", ",", "'raw'", "]", ":", "for", "h", "in", "ip", ".", "user_ns", "[", "'_headers'", "]", "[", "headerkind", "]", "[",...
Filter already loaded headers against some criterion. The criterion function must accept a single argument, which is an instance of sastool.classes2.header.Header, or one of its subclasses. The function must return True if the header is to be kept or False if it needs to be discarded. All manipulations...
[ "Filter", "already", "loaded", "headers", "against", "some", "criterion", "." ]
train
https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/io.py#L13-L27
awacha/credolib
credolib/io.py
load_headers
def load_headers(fsns:List[int]): """Load header files """ ip = get_ipython() ip.user_ns['_headers'] = {} for type_ in ['raw', 'processed']: print("Loading %d headers (%s)" % (len(fsns), type_), flush=True) processed = type_ == 'processed' headers = [] for f in fsns: ...
python
def load_headers(fsns:List[int]): """Load header files """ ip = get_ipython() ip.user_ns['_headers'] = {} for type_ in ['raw', 'processed']: print("Loading %d headers (%s)" % (len(fsns), type_), flush=True) processed = type_ == 'processed' headers = [] for f in fsns: ...
[ "def", "load_headers", "(", "fsns", ":", "List", "[", "int", "]", ")", ":", "ip", "=", "get_ipython", "(", ")", "ip", ".", "user_ns", "[", "'_headers'", "]", "=", "{", "}", "for", "type_", "in", "[", "'raw'", ",", "'processed'", "]", ":", "print", ...
Load header files
[ "Load", "header", "files" ]
train
https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/io.py#L29-L55
hph/mov
mov.py
get_size
def get_size(path): '''Return the size of path in bytes if it exists and can be determined.''' size = os.path.getsize(path) for item in os.walk(path): for file in item[2]: size += os.path.getsize(os.path.join(item[0], file)) return size
python
def get_size(path): '''Return the size of path in bytes if it exists and can be determined.''' size = os.path.getsize(path) for item in os.walk(path): for file in item[2]: size += os.path.getsize(os.path.join(item[0], file)) return size
[ "def", "get_size", "(", "path", ")", ":", "size", "=", "os", ".", "path", ".", "getsize", "(", "path", ")", "for", "item", "in", "os", ".", "walk", "(", "path", ")", ":", "for", "file", "in", "item", "[", "2", "]", ":", "size", "+=", "os", "....
Return the size of path in bytes if it exists and can be determined.
[ "Return", "the", "size", "of", "path", "in", "bytes", "if", "it", "exists", "and", "can", "be", "determined", "." ]
train
https://github.com/hph/mov/blob/36a18d92836e1aff74ca02e16ce09d1c46e111b9/mov.py#L52-L58
hph/mov
mov.py
local_data
def local_data(path): """Return tuples of names, directories, total sizes and files. Each directory represents a single film and the files are the files contained in the directory, such as video, audio and subtitle files.""" dirs = [os.path.join(path, item) for item in os.listdir(path)] names,...
python
def local_data(path): """Return tuples of names, directories, total sizes and files. Each directory represents a single film and the files are the files contained in the directory, such as video, audio and subtitle files.""" dirs = [os.path.join(path, item) for item in os.listdir(path)] names,...
[ "def", "local_data", "(", "path", ")", ":", "dirs", "=", "[", "os", ".", "path", ".", "join", "(", "path", ",", "item", ")", "for", "item", "in", "os", ".", "listdir", "(", "path", ")", "]", "names", ",", "sizes", ",", "files", "=", "zip", "(",...
Return tuples of names, directories, total sizes and files. Each directory represents a single film and the files are the files contained in the directory, such as video, audio and subtitle files.
[ "Return", "tuples", "of", "names", "directories", "total", "sizes", "and", "files", ".", "Each", "directory", "represents", "a", "single", "film", "and", "the", "files", "are", "the", "files", "contained", "in", "the", "directory", "such", "as", "video", "au...
train
https://github.com/hph/mov/blob/36a18d92836e1aff74ca02e16ce09d1c46e111b9/mov.py#L61-L69
hph/mov
mov.py
prefix_size
def prefix_size(size, base=1024): '''Return size in B (bytes), kB, MB, GB or TB.''' if ARGS.prefix == 'None': for i, prefix in enumerate(['', 'ki', 'Mi', 'Gi', 'Ti']): if size < pow(base, i + 1): return '{0} {1}B'.format(round(float(size) / pow(base, i), 1), ...
python
def prefix_size(size, base=1024): '''Return size in B (bytes), kB, MB, GB or TB.''' if ARGS.prefix == 'None': for i, prefix in enumerate(['', 'ki', 'Mi', 'Gi', 'Ti']): if size < pow(base, i + 1): return '{0} {1}B'.format(round(float(size) / pow(base, i), 1), ...
[ "def", "prefix_size", "(", "size", ",", "base", "=", "1024", ")", ":", "if", "ARGS", ".", "prefix", "==", "'None'", ":", "for", "i", ",", "prefix", "in", "enumerate", "(", "[", "''", ",", "'ki'", ",", "'Mi'", ",", "'Gi'", ",", "'Ti'", "]", ")", ...
Return size in B (bytes), kB, MB, GB or TB.
[ "Return", "size", "in", "B", "(", "bytes", ")", "kB", "MB", "GB", "or", "TB", "." ]
train
https://github.com/hph/mov/blob/36a18d92836e1aff74ca02e16ce09d1c46e111b9/mov.py#L72-L85
hph/mov
mov.py
create
def create(): """Create a new database with information about the films in the specified directory or directories.""" if not all(map(os.path.isdir, ARGS.directory)): exit('Error: One or more of the specified directories does not exist.') with sqlite3.connect(ARGS.database) as connection: ...
python
def create(): """Create a new database with information about the films in the specified directory or directories.""" if not all(map(os.path.isdir, ARGS.directory)): exit('Error: One or more of the specified directories does not exist.') with sqlite3.connect(ARGS.database) as connection: ...
[ "def", "create", "(", ")", ":", "if", "not", "all", "(", "map", "(", "os", ".", "path", ".", "isdir", ",", "ARGS", ".", "directory", ")", ")", ":", "exit", "(", "'Error: One or more of the specified directories does not exist.'", ")", "with", "sqlite3", ".",...
Create a new database with information about the films in the specified directory or directories.
[ "Create", "a", "new", "database", "with", "information", "about", "the", "films", "in", "the", "specified", "directory", "or", "directories", "." ]
train
https://github.com/hph/mov/blob/36a18d92836e1aff74ca02e16ce09d1c46e111b9/mov.py#L88-L101
hph/mov
mov.py
destroy
def destroy(): """Destroy a database.""" if not os.path.exists(ARGS.database): exit('Error: The database does not exist; you must create it first.') if ARGS.force: os.remove(ARGS.database) elif raw_input('Destroy {0} [y/n]? '.format(ARGS.database)) in ('y', 'Y'): os.remove(ARGS.d...
python
def destroy(): """Destroy a database.""" if not os.path.exists(ARGS.database): exit('Error: The database does not exist; you must create it first.') if ARGS.force: os.remove(ARGS.database) elif raw_input('Destroy {0} [y/n]? '.format(ARGS.database)) in ('y', 'Y'): os.remove(ARGS.d...
[ "def", "destroy", "(", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "ARGS", ".", "database", ")", ":", "exit", "(", "'Error: The database does not exist; you must create it first.'", ")", "if", "ARGS", ".", "force", ":", "os", ".", "remove",...
Destroy a database.
[ "Destroy", "a", "database", "." ]
train
https://github.com/hph/mov/blob/36a18d92836e1aff74ca02e16ce09d1c46e111b9/mov.py#L111-L118
hph/mov
mov.py
ls
def ls(): """List all items in the database in a predefined format.""" if not os.path.exists(ARGS.database): exit('Error: The database does not exist; you must create it first.') with sqlite3.connect(ARGS.database) as connection: connection.text_factory = str cursor = connection.curs...
python
def ls(): """List all items in the database in a predefined format.""" if not os.path.exists(ARGS.database): exit('Error: The database does not exist; you must create it first.') with sqlite3.connect(ARGS.database) as connection: connection.text_factory = str cursor = connection.curs...
[ "def", "ls", "(", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "ARGS", ".", "database", ")", ":", "exit", "(", "'Error: The database does not exist; you must create it first.'", ")", "with", "sqlite3", ".", "connect", "(", "ARGS", ".", "data...
List all items in the database in a predefined format.
[ "List", "all", "items", "in", "the", "database", "in", "a", "predefined", "format", "." ]
train
https://github.com/hph/mov/blob/36a18d92836e1aff74ca02e16ce09d1c46e111b9/mov.py#L121-L152
hph/mov
mov.py
play
def play(): """Open the matched movie with a media player.""" with sqlite3.connect(ARGS.database) as connection: connection.text_factory = str cursor = connection.cursor() if ARGS.pattern: if not ARGS.strict: ARGS.pattern = '%{0}%'.format(ARGS.pattern) ...
python
def play(): """Open the matched movie with a media player.""" with sqlite3.connect(ARGS.database) as connection: connection.text_factory = str cursor = connection.cursor() if ARGS.pattern: if not ARGS.strict: ARGS.pattern = '%{0}%'.format(ARGS.pattern) ...
[ "def", "play", "(", ")", ":", "with", "sqlite3", ".", "connect", "(", "ARGS", ".", "database", ")", "as", "connection", ":", "connection", ".", "text_factory", "=", "str", "cursor", "=", "connection", ".", "cursor", "(", ")", "if", "ARGS", ".", "patter...
Open the matched movie with a media player.
[ "Open", "the", "matched", "movie", "with", "a", "media", "player", "." ]
train
https://github.com/hph/mov/blob/36a18d92836e1aff74ca02e16ce09d1c46e111b9/mov.py#L155-L172
amaas-fintech/amaas-utils-python
amaasutils/random_utils.py
random_string
def random_string(length, numeric_only=False): """ Generates a random string of length equal to the length parameter """ choices = string.digits if numeric_only else string.ascii_uppercase + string.digits return ''.join(random.choice(choices) for _ in range(length))
python
def random_string(length, numeric_only=False): """ Generates a random string of length equal to the length parameter """ choices = string.digits if numeric_only else string.ascii_uppercase + string.digits return ''.join(random.choice(choices) for _ in range(length))
[ "def", "random_string", "(", "length", ",", "numeric_only", "=", "False", ")", ":", "choices", "=", "string", ".", "digits", "if", "numeric_only", "else", "string", ".", "ascii_uppercase", "+", "string", ".", "digits", "return", "''", ".", "join", "(", "ra...
Generates a random string of length equal to the length parameter
[ "Generates", "a", "random", "string", "of", "length", "equal", "to", "the", "length", "parameter" ]
train
https://github.com/amaas-fintech/amaas-utils-python/blob/5aa64ca65ce0c77b513482d943345d94c9ae58e8/amaasutils/random_utils.py#L10-L15
amaas-fintech/amaas-utils-python
amaasutils/random_utils.py
random_date
def random_date(start_year=2000, end_year=2020): """ Generates a random "sensible" date for use in things like issue dates and maturities """ return date(random.randint(start_year, end_year), random.randint(1, 12), random.randint(1, 28))
python
def random_date(start_year=2000, end_year=2020): """ Generates a random "sensible" date for use in things like issue dates and maturities """ return date(random.randint(start_year, end_year), random.randint(1, 12), random.randint(1, 28))
[ "def", "random_date", "(", "start_year", "=", "2000", ",", "end_year", "=", "2020", ")", ":", "return", "date", "(", "random", ".", "randint", "(", "start_year", ",", "end_year", ")", ",", "random", ".", "randint", "(", "1", ",", "12", ")", ",", "ran...
Generates a random "sensible" date for use in things like issue dates and maturities
[ "Generates", "a", "random", "sensible", "date", "for", "use", "in", "things", "like", "issue", "dates", "and", "maturities" ]
train
https://github.com/amaas-fintech/amaas-utils-python/blob/5aa64ca65ce0c77b513482d943345d94c9ae58e8/amaasutils/random_utils.py#L25-L29
scott-maddox/simpleqw
src/simpleqw/_finite_well.py
_finite_well_energy
def _finite_well_energy(P, n=1, atol=1e-6): ''' Returns the nth bound-state energy for a finite-potential quantum well with the given well-strength parameter, `P`. ''' assert n > 0 and n <= _finite_well_states(P) pi_2 = pi / 2. r = (1 / (P + pi_2)) * (n * pi_2) eta = n * pi_2 - arcsin(r)...
python
def _finite_well_energy(P, n=1, atol=1e-6): ''' Returns the nth bound-state energy for a finite-potential quantum well with the given well-strength parameter, `P`. ''' assert n > 0 and n <= _finite_well_states(P) pi_2 = pi / 2. r = (1 / (P + pi_2)) * (n * pi_2) eta = n * pi_2 - arcsin(r)...
[ "def", "_finite_well_energy", "(", "P", ",", "n", "=", "1", ",", "atol", "=", "1e-6", ")", ":", "assert", "n", ">", "0", "and", "n", "<=", "_finite_well_states", "(", "P", ")", "pi_2", "=", "pi", "/", "2.", "r", "=", "(", "1", "/", "(", "P", ...
Returns the nth bound-state energy for a finite-potential quantum well with the given well-strength parameter, `P`.
[ "Returns", "the", "nth", "bound", "-", "state", "energy", "for", "a", "finite", "-", "potential", "quantum", "well", "with", "the", "given", "well", "-", "strength", "parameter", "P", "." ]
train
https://github.com/scott-maddox/simpleqw/blob/83c1c7ff1f0bac9ddeb6f00fcbb8fafe6ec97f6b/src/simpleqw/_finite_well.py#L46-L79
scott-maddox/simpleqw
src/simpleqw/_finite_well.py
finite_well_energy
def finite_well_energy(a, m, U, n=1): ''' a : float thickness of the well in units of meters m : float effective mass in the well as a fraction of the electron mass U : float the potential in eV n : int the quantum number of the desired state If U <= 0, returns 0...
python
def finite_well_energy(a, m, U, n=1): ''' a : float thickness of the well in units of meters m : float effective mass in the well as a fraction of the electron mass U : float the potential in eV n : int the quantum number of the desired state If U <= 0, returns 0...
[ "def", "finite_well_energy", "(", "a", ",", "m", ",", "U", ",", "n", "=", "1", ")", ":", "if", "U", "<=", "0.", ":", "return", "0", "P", "=", "prefactor", "*", "a", "*", "sqrt", "(", "m", "*", "U", ")", "print", "P", ",", "_finite_well_energy",...
a : float thickness of the well in units of meters m : float effective mass in the well as a fraction of the electron mass U : float the potential in eV n : int the quantum number of the desired state If U <= 0, returns 0. Otherwise, returns the confinement energy in ...
[ "a", ":", "float", "thickness", "of", "the", "well", "in", "units", "of", "meters", "m", ":", "float", "effective", "mass", "in", "the", "well", "as", "a", "fraction", "of", "the", "electron", "mass", "U", ":", "float", "the", "potential", "in", "eV", ...
train
https://github.com/scott-maddox/simpleqw/blob/83c1c7ff1f0bac9ddeb6f00fcbb8fafe6ec97f6b/src/simpleqw/_finite_well.py#L82-L103
Pringley/spyglass
spyglass/scraper.py
Scraper.top
def top(self, n=10, cache=None, prefetch=False): """Find the most popular torrents. Return an array of Torrent objects representing the top n torrents. If the cache option is non-None, override the Scraper's default caching settings. Use the prefetch option to hit each Torrent'...
python
def top(self, n=10, cache=None, prefetch=False): """Find the most popular torrents. Return an array of Torrent objects representing the top n torrents. If the cache option is non-None, override the Scraper's default caching settings. Use the prefetch option to hit each Torrent'...
[ "def", "top", "(", "self", ",", "n", "=", "10", ",", "cache", "=", "None", ",", "prefetch", "=", "False", ")", ":", "use_cache", "=", "self", ".", "_use_cache", "(", "cache", ")", "if", "use_cache", "and", "len", "(", "self", ".", "_top_cache", ")"...
Find the most popular torrents. Return an array of Torrent objects representing the top n torrents. If the cache option is non-None, override the Scraper's default caching settings. Use the prefetch option to hit each Torrent's info page up front (instead of lazy fetching the i...
[ "Find", "the", "most", "popular", "torrents", "." ]
train
https://github.com/Pringley/spyglass/blob/091d74f34837673af936daa9f462ad8216be9916/spyglass/scraper.py#L15-L37
Pringley/spyglass
spyglass/scraper.py
Scraper.torrent_from_url
def torrent_from_url(self, url, cache=True, prefetch=False): """Create a Torrent object from a given URL. If the cache option is set, check to see if we already have a Torrent object representing it. If prefetch is set, automatically query the torrent's info page to fill in the torrent ...
python
def torrent_from_url(self, url, cache=True, prefetch=False): """Create a Torrent object from a given URL. If the cache option is set, check to see if we already have a Torrent object representing it. If prefetch is set, automatically query the torrent's info page to fill in the torrent ...
[ "def", "torrent_from_url", "(", "self", ",", "url", ",", "cache", "=", "True", ",", "prefetch", "=", "False", ")", ":", "if", "self", ".", "_use_cache", "(", "cache", ")", "and", "url", "in", "self", ".", "_torrent_cache", ":", "return", "self", ".", ...
Create a Torrent object from a given URL. If the cache option is set, check to see if we already have a Torrent object representing it. If prefetch is set, automatically query the torrent's info page to fill in the torrent object. (If prefetch is false, then the torrent page will be que...
[ "Create", "a", "Torrent", "object", "from", "a", "given", "URL", "." ]
train
https://github.com/Pringley/spyglass/blob/091d74f34837673af936daa9f462ad8216be9916/spyglass/scraper.py#L61-L75
frejanordsiek/GeminiMotorDrive
GeminiMotorDrive/drivers.py
ASCII_RS232._send_command
def _send_command(self, command, immediate=False, timeout=1.0, check_echo=None): """ Send a single command to the drive after sanitizing it. Takes a single given `command`, sanitizes it (strips out comments, extra whitespace, and newlines), sends the command to the...
python
def _send_command(self, command, immediate=False, timeout=1.0, check_echo=None): """ Send a single command to the drive after sanitizing it. Takes a single given `command`, sanitizes it (strips out comments, extra whitespace, and newlines), sends the command to the...
[ "def", "_send_command", "(", "self", ",", "command", ",", "immediate", "=", "False", ",", "timeout", "=", "1.0", ",", "check_echo", "=", "None", ")", ":", "# Use the default echo checking if None was given.", "if", "check_echo", "is", "None", ":", "check_echo", ...
Send a single command to the drive after sanitizing it. Takes a single given `command`, sanitizes it (strips out comments, extra whitespace, and newlines), sends the command to the drive, and returns the sanitized command. The validity of the command is **NOT** checked. Paramet...
[ "Send", "a", "single", "command", "to", "the", "drive", "after", "sanitizing", "it", "." ]
train
https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/drivers.py#L127-L251
frejanordsiek/GeminiMotorDrive
GeminiMotorDrive/drivers.py
ASCII_RS232._get_response
def _get_response(self, timeout=1.0, eor=('\n', '\n- ')): """ Reads a response from the drive. Reads the response returned by the drive with an optional timeout. All carriage returns and linefeeds are kept. Parameters ---------- timeout : number, optional Op...
python
def _get_response(self, timeout=1.0, eor=('\n', '\n- ')): """ Reads a response from the drive. Reads the response returned by the drive with an optional timeout. All carriage returns and linefeeds are kept. Parameters ---------- timeout : number, optional Op...
[ "def", "_get_response", "(", "self", ",", "timeout", "=", "1.0", ",", "eor", "=", "(", "'\\n'", ",", "'\\n- '", ")", ")", ":", "# If no timeout is given or it is invalid and we are using '\\n'", "# as the eor, use the wrapper to read a line with an infinite", "# timeout. Othe...
Reads a response from the drive. Reads the response returned by the drive with an optional timeout. All carriage returns and linefeeds are kept. Parameters ---------- timeout : number, optional Optional timeout in seconds to use when reading the response...
[ "Reads", "a", "response", "from", "the", "drive", "." ]
train
https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/drivers.py#L253-L338
frejanordsiek/GeminiMotorDrive
GeminiMotorDrive/drivers.py
ASCII_RS232._process_response
def _process_response(self, response): """ Processes a response from the drive. Processes the response returned from the drive. It is broken down into the echoed command (drive echoes it back), any error returned by the drive (leading '*' is stripped), and the different lines of...
python
def _process_response(self, response): """ Processes a response from the drive. Processes the response returned from the drive. It is broken down into the echoed command (drive echoes it back), any error returned by the drive (leading '*' is stripped), and the different lines of...
[ "def", "_process_response", "(", "self", ",", "response", ")", ":", "# Strip the trailing newline and split the response into lines", "# by carriage returns.", "rsp_lines", "=", "response", ".", "rstrip", "(", "'\\r\\n'", ")", ".", "split", "(", "'\\r'", ")", "# If we h...
Processes a response from the drive. Processes the response returned from the drive. It is broken down into the echoed command (drive echoes it back), any error returned by the drive (leading '*' is stripped), and the different lines of the response. Parameters --------...
[ "Processes", "a", "response", "from", "the", "drive", "." ]
train
https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/drivers.py#L340-L391
frejanordsiek/GeminiMotorDrive
GeminiMotorDrive/drivers.py
ASCII_RS232.send_command
def send_command(self, command, immediate=False, timeout=1.0, max_retries=0, eor=('\n', '\n- ')): """ Sends a single command to the drive and returns output. Takes a single given `command`, sanitizes it, sends it to the drive, reads the response, and returns the processed r...
python
def send_command(self, command, immediate=False, timeout=1.0, max_retries=0, eor=('\n', '\n- ')): """ Sends a single command to the drive and returns output. Takes a single given `command`, sanitizes it, sends it to the drive, reads the response, and returns the processed r...
[ "def", "send_command", "(", "self", ",", "command", ",", "immediate", "=", "False", ",", "timeout", "=", "1.0", ",", "max_retries", "=", "0", ",", "eor", "=", "(", "'\\n'", ",", "'\\n- '", ")", ")", ":", "# Execute the command till it either doesn't have an er...
Sends a single command to the drive and returns output. Takes a single given `command`, sanitizes it, sends it to the drive, reads the response, and returns the processed response. The command is first sanitized by removing comments, extra whitespace, and newline characters. If `immedia...
[ "Sends", "a", "single", "command", "to", "the", "drive", "and", "returns", "output", "." ]
train
https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/drivers.py#L420-L527
frejanordsiek/GeminiMotorDrive
GeminiMotorDrive/drivers.py
ASCII_RS232.send_commands
def send_commands(self, commands, timeout=1.0, max_retries=1, eor=('\n', '\n- ')): """ Send a sequence of commands to the drive and collect output. Takes a sequence of many commands and executes them one by one till either all are executed or one runs out of retries ...
python
def send_commands(self, commands, timeout=1.0, max_retries=1, eor=('\n', '\n- ')): """ Send a sequence of commands to the drive and collect output. Takes a sequence of many commands and executes them one by one till either all are executed or one runs out of retries ...
[ "def", "send_commands", "(", "self", ",", "commands", ",", "timeout", "=", "1.0", ",", "max_retries", "=", "1", ",", "eor", "=", "(", "'\\n'", ",", "'\\n- '", ")", ")", ":", "# If eor is not a list, make a list of it replicated enough for", "# every command.", "if...
Send a sequence of commands to the drive and collect output. Takes a sequence of many commands and executes them one by one till either all are executed or one runs out of retries (`max_retries`). Retries are optionally performed if a command's repsonse indicates that there was an error...
[ "Send", "a", "sequence", "of", "commands", "to", "the", "drive", "and", "collect", "output", "." ]
train
https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/drivers.py#L529-L631
tagcubeio/tagcube-cli
tagcube/client/api.py
TagCubeClient.quick_scan
def quick_scan(self, target_url, email_notify=None, scan_profile='full_audit', path_list=('/',)): """ :param target_url: The target url e.g. https://www.tagcube.io/ :param email_notify: The notification email e.g. user@example.com :param scan_profile: The name of the s...
python
def quick_scan(self, target_url, email_notify=None, scan_profile='full_audit', path_list=('/',)): """ :param target_url: The target url e.g. https://www.tagcube.io/ :param email_notify: The notification email e.g. user@example.com :param scan_profile: The name of the s...
[ "def", "quick_scan", "(", "self", ",", "target_url", ",", "email_notify", "=", "None", ",", "scan_profile", "=", "'full_audit'", ",", "path_list", "=", "(", "'/'", ",", ")", ")", ":", "#", "# Scan profile handling", "#", "scan_profile_resource", "=", "self", ...
:param target_url: The target url e.g. https://www.tagcube.io/ :param email_notify: The notification email e.g. user@example.com :param scan_profile: The name of the scan profile :param path_list: The list of paths to use in the crawling bootstrap The basic idea around this method is to...
[ ":", "param", "target_url", ":", "The", "target", "url", "e", ".", "g", ".", "https", ":", "//", "www", ".", "tagcube", ".", "io", "/", ":", "param", "email_notify", ":", "The", "notification", "email", "e", ".", "g", ".", "user@example", ".", "com",...
train
https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube/client/api.py#L97-L180
tagcubeio/tagcube-cli
tagcube/client/api.py
TagCubeClient.low_level_scan
def low_level_scan(self, verification_resource, scan_profile_resource, path_list, notification_resource_list): """ Low level implementation of the scan launch which allows you to start a new scan when you already know the ids for the required resources. :param ver...
python
def low_level_scan(self, verification_resource, scan_profile_resource, path_list, notification_resource_list): """ Low level implementation of the scan launch which allows you to start a new scan when you already know the ids for the required resources. :param ver...
[ "def", "low_level_scan", "(", "self", ",", "verification_resource", ",", "scan_profile_resource", ",", "path_list", ",", "notification_resource_list", ")", ":", "data", "=", "{", "\"verification_href\"", ":", "verification_resource", ".", "href", ",", "\"profile_href\""...
Low level implementation of the scan launch which allows you to start a new scan when you already know the ids for the required resources. :param verification_resource: The verification associated with the domain resource to scan :param scan_profile_resourc...
[ "Low", "level", "implementation", "of", "the", "scan", "launch", "which", "allows", "you", "to", "start", "a", "new", "scan", "when", "you", "already", "know", "the", "ids", "for", "the", "required", "resources", "." ]
train
https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube/client/api.py#L182-L218
tagcubeio/tagcube-cli
tagcube/client/api.py
TagCubeClient.verification_add
def verification_add(self, domain_resource_id, port, is_ssl): """ Sends a POST to /1.0/verifications/ using this post-data: {"domain_href": "/1.0/domains/2", "port":80, "ssl":false} :param domain_resource_id: The domain id to verify :param port: Th...
python
def verification_add(self, domain_resource_id, port, is_ssl): """ Sends a POST to /1.0/verifications/ using this post-data: {"domain_href": "/1.0/domains/2", "port":80, "ssl":false} :param domain_resource_id: The domain id to verify :param port: Th...
[ "def", "verification_add", "(", "self", ",", "domain_resource_id", ",", "port", ",", "is_ssl", ")", ":", "data", "=", "{", "\"domain_href\"", ":", "self", ".", "build_api_path", "(", "'domains'", ",", "domain_resource_id", ")", ",", "\"port\"", ":", "port", ...
Sends a POST to /1.0/verifications/ using this post-data: {"domain_href": "/1.0/domains/2", "port":80, "ssl":false} :param domain_resource_id: The domain id to verify :param port: The TCP port :param is_ssl: Boolean indicating if we should use ssl ...
[ "Sends", "a", "POST", "to", "/", "1", ".", "0", "/", "verifications", "/", "using", "this", "post", "-", "data", ":" ]
train
https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube/client/api.py#L226-L245
tagcubeio/tagcube-cli
tagcube/client/api.py
TagCubeClient.filter_resource
def filter_resource(self, resource_name, field_name, field_value, result_handler=ONE_RESULT): """ :return: The resource (as json), or None """ return self.multi_filter_resource(resource_name, {field_name: field_value}, ...
python
def filter_resource(self, resource_name, field_name, field_value, result_handler=ONE_RESULT): """ :return: The resource (as json), or None """ return self.multi_filter_resource(resource_name, {field_name: field_value}, ...
[ "def", "filter_resource", "(", "self", ",", "resource_name", ",", "field_name", ",", "field_value", ",", "result_handler", "=", "ONE_RESULT", ")", ":", "return", "self", ".", "multi_filter_resource", "(", "resource_name", ",", "{", "field_name", ":", "field_value"...
:return: The resource (as json), or None
[ ":", "return", ":", "The", "resource", "(", "as", "json", ")", "or", "None" ]
train
https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube/client/api.py#L276-L283
tagcubeio/tagcube-cli
tagcube/client/api.py
TagCubeClient.email_notification_add
def email_notification_add(self, notif_email, first_name='None', last_name='None', description=DESCRIPTION): """ Sends a POST to /1.0/notifications/email/ using this post-data: {"email": "andres.riancho@gmail.com", "first_name": "Andres", ...
python
def email_notification_add(self, notif_email, first_name='None', last_name='None', description=DESCRIPTION): """ Sends a POST to /1.0/notifications/email/ using this post-data: {"email": "andres.riancho@gmail.com", "first_name": "Andres", ...
[ "def", "email_notification_add", "(", "self", ",", "notif_email", ",", "first_name", "=", "'None'", ",", "last_name", "=", "'None'", ",", "description", "=", "DESCRIPTION", ")", ":", "data", "=", "{", "\"email\"", ":", "notif_email", ",", "\"first_name\"", ":"...
Sends a POST to /1.0/notifications/email/ using this post-data: {"email": "andres.riancho@gmail.com", "first_name": "Andres", "last_name": "Riancho", "description": "Notification email"} :return: The id of the newly created email notification resource
[ "Sends", "a", "POST", "to", "/", "1", ".", "0", "/", "notifications", "/", "email", "/", "using", "this", "post", "-", "data", ":" ]
train
https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube/client/api.py#L291-L308
tagcubeio/tagcube-cli
tagcube/client/api.py
TagCubeClient.domain_add
def domain_add(self, domain, description=DESCRIPTION): """ Sends a POST to /1.0/domains/ using this post-data: {"domain": "www.fogfu.com", "description":"Added by tagcube-api"} :param domain: The domain name to add as a new resource :return: The newly created r...
python
def domain_add(self, domain, description=DESCRIPTION): """ Sends a POST to /1.0/domains/ using this post-data: {"domain": "www.fogfu.com", "description":"Added by tagcube-api"} :param domain: The domain name to add as a new resource :return: The newly created r...
[ "def", "domain_add", "(", "self", ",", "domain", ",", "description", "=", "DESCRIPTION", ")", ":", "data", "=", "{", "\"domain\"", ":", "domain", ",", "\"description\"", ":", "description", "}", "url", "=", "self", ".", "build_full_url", "(", "self", ".", ...
Sends a POST to /1.0/domains/ using this post-data: {"domain": "www.fogfu.com", "description":"Added by tagcube-api"} :param domain: The domain name to add as a new resource :return: The newly created resource
[ "Sends", "a", "POST", "to", "/", "1", ".", "0", "/", "domains", "/", "using", "this", "post", "-", "data", ":" ]
train
https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube/client/api.py#L347-L360
tagcubeio/tagcube-cli
tagcube/client/api.py
TagCubeClient.get_scan
def get_scan(self, scan_id): """ :param scan_id: The scan ID as a string :return: A resource containing the scan information """ url = self.build_full_url('%s%s' % (self.SCANS, scan_id)) _, json_data = self.send_request(url) return Resource(json_data)
python
def get_scan(self, scan_id): """ :param scan_id: The scan ID as a string :return: A resource containing the scan information """ url = self.build_full_url('%s%s' % (self.SCANS, scan_id)) _, json_data = self.send_request(url) return Resource(json_data)
[ "def", "get_scan", "(", "self", ",", "scan_id", ")", ":", "url", "=", "self", ".", "build_full_url", "(", "'%s%s'", "%", "(", "self", ".", "SCANS", ",", "scan_id", ")", ")", "_", ",", "json_data", "=", "self", ".", "send_request", "(", "url", ")", ...
:param scan_id: The scan ID as a string :return: A resource containing the scan information
[ ":", "param", "scan_id", ":", "The", "scan", "ID", "as", "a", "string", ":", "return", ":", "A", "resource", "containing", "the", "scan", "information" ]
train
https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube/client/api.py#L362-L369
tagcubeio/tagcube-cli
tagcube/client/api.py
TagCubeClient.create_resource
def create_resource(self, url, data): """ Shortcut for creating a new resource :return: The newly created resource as a Resource object """ status_code, json_data = self.send_request(url, data, method='POST') if status_code != 201: msg = 'Expected 201 status ...
python
def create_resource(self, url, data): """ Shortcut for creating a new resource :return: The newly created resource as a Resource object """ status_code, json_data = self.send_request(url, data, method='POST') if status_code != 201: msg = 'Expected 201 status ...
[ "def", "create_resource", "(", "self", ",", "url", ",", "data", ")", ":", "status_code", ",", "json_data", "=", "self", ".", "send_request", "(", "url", ",", "data", ",", "method", "=", "'POST'", ")", "if", "status_code", "!=", "201", ":", "msg", "=", ...
Shortcut for creating a new resource :return: The newly created resource as a Resource object
[ "Shortcut", "for", "creating", "a", "new", "resource", ":", "return", ":", "The", "newly", "created", "resource", "as", "a", "Resource", "object" ]
train
https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube/client/api.py#L371-L388
tagcubeio/tagcube-cli
tagcube/client/api.py
TagCubeClient.handle_api_errors
def handle_api_errors(self, status_code, json_data): """ This method parses all the HTTP responses sent by the REST API and raises exceptions if required. Basically tries to find responses with this format: { 'error': ['The domain foo.com already exists.'] ...
python
def handle_api_errors(self, status_code, json_data): """ This method parses all the HTTP responses sent by the REST API and raises exceptions if required. Basically tries to find responses with this format: { 'error': ['The domain foo.com already exists.'] ...
[ "def", "handle_api_errors", "(", "self", ",", "status_code", ",", "json_data", ")", ":", "error_list", "=", "[", "]", "if", "'error'", "in", "json_data", "and", "len", "(", "json_data", ")", "==", "1", "and", "isinstance", "(", "json_data", ",", "dict", ...
This method parses all the HTTP responses sent by the REST API and raises exceptions if required. Basically tries to find responses with this format: { 'error': ['The domain foo.com already exists.'] } Or this other: { "scans"...
[ "This", "method", "parses", "all", "the", "HTTP", "responses", "sent", "by", "the", "REST", "API", "and", "raises", "exceptions", "if", "required", ".", "Basically", "tries", "to", "find", "responses", "with", "this", "format", ":" ]
train
https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube/client/api.py#L422-L460
xgvargas/smartside
smartside/__init__.py
setAsApplication
def setAsApplication(myappid): """ Tells Windows this is an independent application with an unique icon on task bar. id is an unique string to identify this application, like: 'mycompany.myproduct.subproduct.version' """ if os.name == 'nt': import ctypes ctypes.windll.shell32.SetCu...
python
def setAsApplication(myappid): """ Tells Windows this is an independent application with an unique icon on task bar. id is an unique string to identify this application, like: 'mycompany.myproduct.subproduct.version' """ if os.name == 'nt': import ctypes ctypes.windll.shell32.SetCu...
[ "def", "setAsApplication", "(", "myappid", ")", ":", "if", "os", ".", "name", "==", "'nt'", ":", "import", "ctypes", "ctypes", ".", "windll", ".", "shell32", ".", "SetCurrentProcessExplicitAppUserModelID", "(", "myappid", ")" ]
Tells Windows this is an independent application with an unique icon on task bar. id is an unique string to identify this application, like: 'mycompany.myproduct.subproduct.version'
[ "Tells", "Windows", "this", "is", "an", "independent", "application", "with", "an", "unique", "icon", "on", "task", "bar", "." ]
train
https://github.com/xgvargas/smartside/blob/c63acb7d628b161f438e877eca12d550647de34d/smartside/__init__.py#L11-L20
xgvargas/smartside
smartside/__init__.py
getBestTranslation
def getBestTranslation(basedir, lang=None): """ Find inside basedir the best translation available. lang, if defined, should be a list of prefered languages. It will look for file in the form: - en-US.qm - en_US.qm - en.qm """ if not lang: lang = QtCore.QLocale.system().uiL...
python
def getBestTranslation(basedir, lang=None): """ Find inside basedir the best translation available. lang, if defined, should be a list of prefered languages. It will look for file in the form: - en-US.qm - en_US.qm - en.qm """ if not lang: lang = QtCore.QLocale.system().uiL...
[ "def", "getBestTranslation", "(", "basedir", ",", "lang", "=", "None", ")", ":", "if", "not", "lang", ":", "lang", "=", "QtCore", ".", "QLocale", ".", "system", "(", ")", ".", "uiLanguages", "(", ")", "for", "l", "in", "lang", ":", "l", "=", "l", ...
Find inside basedir the best translation available. lang, if defined, should be a list of prefered languages. It will look for file in the form: - en-US.qm - en_US.qm - en.qm
[ "Find", "inside", "basedir", "the", "best", "translation", "available", "." ]
train
https://github.com/xgvargas/smartside/blob/c63acb7d628b161f438e877eca12d550647de34d/smartside/__init__.py#L23-L56
adamkerz/django-presentation
django_presentation/utils.py
interpretValue
def interpretValue(value,*args,**kwargs): """Interprets a passed value. In this order: - If it's callable, call it with the parameters provided - If it's a tuple/list/dict and we have a single, non-kwarg parameter, look up that parameter within the tuple/list/dict - Else, just return it """ ...
python
def interpretValue(value,*args,**kwargs): """Interprets a passed value. In this order: - If it's callable, call it with the parameters provided - If it's a tuple/list/dict and we have a single, non-kwarg parameter, look up that parameter within the tuple/list/dict - Else, just return it """ ...
[ "def", "interpretValue", "(", "value", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "callable", "(", "value", ")", ":", "return", "value", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "value", ",", "tuple",...
Interprets a passed value. In this order: - If it's callable, call it with the parameters provided - If it's a tuple/list/dict and we have a single, non-kwarg parameter, look up that parameter within the tuple/list/dict - Else, just return it
[ "Interprets", "a", "passed", "value", ".", "In", "this", "order", ":", "-", "If", "it", "s", "callable", "call", "it", "with", "the", "parameters", "provided", "-", "If", "it", "s", "a", "tuple", "/", "list", "/", "dict", "and", "we", "have", "a", ...
train
https://github.com/adamkerz/django-presentation/blob/1e812faa5f682e021fa6580509d8d324cfcc119c/django_presentation/utils.py#L2-L12
adamkerz/django-presentation
django_presentation/utils.py
specialInterpretValue
def specialInterpretValue(value,index,*args,**kwargs): """Interprets a passed value. In this order: - If it's callable, call it with the parameters provided - If it's a tuple/list/dict and index is not None, look up index within the tuple/list/dict - Else, just return it """ if callable(valu...
python
def specialInterpretValue(value,index,*args,**kwargs): """Interprets a passed value. In this order: - If it's callable, call it with the parameters provided - If it's a tuple/list/dict and index is not None, look up index within the tuple/list/dict - Else, just return it """ if callable(valu...
[ "def", "specialInterpretValue", "(", "value", ",", "index", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "callable", "(", "value", ")", ":", "return", "value", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "index", "is", "not"...
Interprets a passed value. In this order: - If it's callable, call it with the parameters provided - If it's a tuple/list/dict and index is not None, look up index within the tuple/list/dict - Else, just return it
[ "Interprets", "a", "passed", "value", ".", "In", "this", "order", ":", "-", "If", "it", "s", "callable", "call", "it", "with", "the", "parameters", "provided", "-", "If", "it", "s", "a", "tuple", "/", "list", "/", "dict", "and", "index", "is", "not",...
train
https://github.com/adamkerz/django-presentation/blob/1e812faa5f682e021fa6580509d8d324cfcc119c/django_presentation/utils.py#L15-L23
davisd50/sparc.cache
sparc/cache/sources/normalize.py
normalizedFieldNameCachableItemMixin.normalize
def normalize(cls, name): """Return string in all lower case with spaces and question marks removed""" name = name.lower() # lower-case for _replace in [' ','-','(',')','?']: name = name.replace(_replace,'') return name
python
def normalize(cls, name): """Return string in all lower case with spaces and question marks removed""" name = name.lower() # lower-case for _replace in [' ','-','(',')','?']: name = name.replace(_replace,'') return name
[ "def", "normalize", "(", "cls", ",", "name", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "# lower-case", "for", "_replace", "in", "[", "' '", ",", "'-'", ",", "'('", ",", "')'", ",", "'?'", "]", ":", "name", "=", "name", ".", "replace"...
Return string in all lower case with spaces and question marks removed
[ "Return", "string", "in", "all", "lower", "case", "with", "spaces", "and", "question", "marks", "removed" ]
train
https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/sources/normalize.py#L67-L72
davisd50/sparc.cache
sparc/cache/sources/normalize.py
normalizedDateTimeResolver.manage
def manage(self, dateTimeString): """Return a Python datetime object based on the dateTimeString This will handle date times in the following formats: YYYY/MM/DD HH:MM:SS 2014/11/05 21:47:28 2014/11/5 21:47:28 11/05/2014 11/5/2014 ...
python
def manage(self, dateTimeString): """Return a Python datetime object based on the dateTimeString This will handle date times in the following formats: YYYY/MM/DD HH:MM:SS 2014/11/05 21:47:28 2014/11/5 21:47:28 11/05/2014 11/5/2014 ...
[ "def", "manage", "(", "self", ",", "dateTimeString", ")", ":", "dateTime", "=", "None", "dateTimeString", "=", "dateTimeString", ".", "replace", "(", "'-'", ",", "'/'", ")", "_date_time_split", "=", "dateTimeString", ".", "split", "(", "' '", ")", "# [0] = d...
Return a Python datetime object based on the dateTimeString This will handle date times in the following formats: YYYY/MM/DD HH:MM:SS 2014/11/05 21:47:28 2014/11/5 21:47:28 11/05/2014 11/5/2014 11/05/2014 16:28:00 11/05...
[ "Return", "a", "Python", "datetime", "object", "based", "on", "the", "dateTimeString", "This", "will", "handle", "date", "times", "in", "the", "following", "formats", ":", "YYYY", "/", "MM", "/", "DD", "HH", ":", "MM", ":", "SS", "2014", "/", "11", "/"...
train
https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/sources/normalize.py#L94-L129
abe-winter/pg13-py
pg13/threevl.py
ThreeVL.nein
def nein(x): "this is 'not' but not is a keyword so it's 'nein'" if not isinstance(x,(bool,ThreeVL)): raise TypeError(type(x)) return not x if isinstance(x,bool) else ThreeVL(dict(t='f',f='t',u='u')[x.value])
python
def nein(x): "this is 'not' but not is a keyword so it's 'nein'" if not isinstance(x,(bool,ThreeVL)): raise TypeError(type(x)) return not x if isinstance(x,bool) else ThreeVL(dict(t='f',f='t',u='u')[x.value])
[ "def", "nein", "(", "x", ")", ":", "if", "not", "isinstance", "(", "x", ",", "(", "bool", ",", "ThreeVL", ")", ")", ":", "raise", "TypeError", "(", "type", "(", "x", ")", ")", "return", "not", "x", "if", "isinstance", "(", "x", ",", "bool", ")"...
this is 'not' but not is a keyword so it's 'nein
[ "this", "is", "not", "but", "not", "is", "a", "keyword", "so", "it", "s", "nein" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/threevl.py#L24-L27
abe-winter/pg13-py
pg13/threevl.py
ThreeVL.compare
def compare(operator,a,b): "this could be replaced by overloading but I want == to return a bool for 'in' use" # todo(awinter): what about nested 3vl like "(a=b)=(c=d)". is that allowed by sql? It will choke here if there's a null involved. f=({'=':lambda a,b:a==b,'!=':lambda a,b:a!=b,'>':lambda a,b:a>b,'<'...
python
def compare(operator,a,b): "this could be replaced by overloading but I want == to return a bool for 'in' use" # todo(awinter): what about nested 3vl like "(a=b)=(c=d)". is that allowed by sql? It will choke here if there's a null involved. f=({'=':lambda a,b:a==b,'!=':lambda a,b:a!=b,'>':lambda a,b:a>b,'<'...
[ "def", "compare", "(", "operator", ",", "a", ",", "b", ")", ":", "# todo(awinter): what about nested 3vl like \"(a=b)=(c=d)\". is that allowed by sql? It will choke here if there's a null involved.", "f", "=", "(", "{", "'='", ":", "lambda", "a", ",", "b", ":", "a", "==...
this could be replaced by overloading but I want == to return a bool for 'in' use
[ "this", "could", "be", "replaced", "by", "overloading", "but", "I", "want", "==", "to", "return", "a", "bool", "for", "in", "use" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/threevl.py#L41-L45
PSU-OIT-ARC/django-cloak
cloak/views.py
login
def login(request, signature): """ Automatically logs in a user based on a signed PK of a user object. The signature should be generated with the `login` management command. The signature will only work for 60 seconds. """ signer = TimestampSigner() try: pk = signer.unsign(signature...
python
def login(request, signature): """ Automatically logs in a user based on a signed PK of a user object. The signature should be generated with the `login` management command. The signature will only work for 60 seconds. """ signer = TimestampSigner() try: pk = signer.unsign(signature...
[ "def", "login", "(", "request", ",", "signature", ")", ":", "signer", "=", "TimestampSigner", "(", ")", "try", ":", "pk", "=", "signer", ".", "unsign", "(", "signature", ",", "max_age", "=", "MAX_AGE_OF_SIGNATURE_IN_SECONDS", ")", "except", "(", "BadSignatur...
Automatically logs in a user based on a signed PK of a user object. The signature should be generated with the `login` management command. The signature will only work for 60 seconds.
[ "Automatically", "logs", "in", "a", "user", "based", "on", "a", "signed", "PK", "of", "a", "user", "object", ".", "The", "signature", "should", "be", "generated", "with", "the", "login", "management", "command", "." ]
train
https://github.com/PSU-OIT-ARC/django-cloak/blob/3f09711837f4fe7b1813692daa064e536135ffa3/cloak/views.py#L12-L30
PSU-OIT-ARC/django-cloak
cloak/views.py
cloak
def cloak(request, pk=None): """ Masquerade as a particular user and redirect based on the REDIRECT_FIELD_NAME parameter, or the LOGIN_REDIRECT_URL. Callers can either pass the pk of the user in the URL itself, or as a POST param. """ pk = request.POST.get('pk', pk) if pk is None: ...
python
def cloak(request, pk=None): """ Masquerade as a particular user and redirect based on the REDIRECT_FIELD_NAME parameter, or the LOGIN_REDIRECT_URL. Callers can either pass the pk of the user in the URL itself, or as a POST param. """ pk = request.POST.get('pk', pk) if pk is None: ...
[ "def", "cloak", "(", "request", ",", "pk", "=", "None", ")", ":", "pk", "=", "request", ".", "POST", ".", "get", "(", "'pk'", ",", "pk", ")", "if", "pk", "is", "None", ":", "return", "HttpResponse", "(", "\"You need to pass a pk POST parameter, or include ...
Masquerade as a particular user and redirect based on the REDIRECT_FIELD_NAME parameter, or the LOGIN_REDIRECT_URL. Callers can either pass the pk of the user in the URL itself, or as a POST param.
[ "Masquerade", "as", "a", "particular", "user", "and", "redirect", "based", "on", "the", "REDIRECT_FIELD_NAME", "parameter", "or", "the", "LOGIN_REDIRECT_URL", "." ]
train
https://github.com/PSU-OIT-ARC/django-cloak/blob/3f09711837f4fe7b1813692daa064e536135ffa3/cloak/views.py#L34-L58
PSU-OIT-ARC/django-cloak
cloak/views.py
uncloak
def uncloak(request): """ Undo a masquerade session and redirect the user back to where they started cloaking from (or where ever the "next" POST parameter points) """ try: del request.session[SESSION_USER_KEY] except KeyError: pass # who cares # figure out where to redirect...
python
def uncloak(request): """ Undo a masquerade session and redirect the user back to where they started cloaking from (or where ever the "next" POST parameter points) """ try: del request.session[SESSION_USER_KEY] except KeyError: pass # who cares # figure out where to redirect...
[ "def", "uncloak", "(", "request", ")", ":", "try", ":", "del", "request", ".", "session", "[", "SESSION_USER_KEY", "]", "except", "KeyError", ":", "pass", "# who cares", "# figure out where to redirect", "next", "=", "request", ".", "POST", ".", "get", "(", ...
Undo a masquerade session and redirect the user back to where they started cloaking from (or where ever the "next" POST parameter points)
[ "Undo", "a", "masquerade", "session", "and", "redirect", "the", "user", "back", "to", "where", "they", "started", "cloaking", "from", "(", "or", "where", "ever", "the", "next", "POST", "parameter", "points", ")" ]
train
https://github.com/PSU-OIT-ARC/django-cloak/blob/3f09711837f4fe7b1813692daa064e536135ffa3/cloak/views.py#L62-L76
tagcubeio/tagcube-cli
tagcube_cli/cli.py
TagCubeCLI.run
def run(self): """ This method handles the user's command line arguments, for example, if the user specified a path file we'll open it and read the contents. Finally it will run the scan using TagCubeClient.scan(...) :return: The exit code for our process """ cli...
python
def run(self): """ This method handles the user's command line arguments, for example, if the user specified a path file we'll open it and read the contents. Finally it will run the scan using TagCubeClient.scan(...) :return: The exit code for our process """ cli...
[ "def", "run", "(", "self", ")", ":", "client", "=", "None", "if", "self", ".", "cmd_args", ".", "subcommand", "in", "self", ".", "API_SUBCOMMAND", ":", "email", ",", "api_key", "=", "TagCubeCLI", ".", "get_credentials", "(", "self", ".", "cmd_args", ")",...
This method handles the user's command line arguments, for example, if the user specified a path file we'll open it and read the contents. Finally it will run the scan using TagCubeClient.scan(...) :return: The exit code for our process
[ "This", "method", "handles", "the", "user", "s", "command", "line", "arguments", "for", "example", "if", "the", "user", "specified", "a", "path", "file", "we", "ll", "open", "it", "and", "read", "the", "contents", ".", "Finally", "it", "will", "run", "th...
train
https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube_cli/cli.py#L50-L81
tagcubeio/tagcube-cli
tagcube_cli/cli.py
TagCubeCLI.parse_args
def parse_args(args=None): """ :return: The result of applying argparse to sys.argv """ # # The main parser # parser = argparse.ArgumentParser(prog='tagcube', description=DESCRIPTION, ...
python
def parse_args(args=None): """ :return: The result of applying argparse to sys.argv """ # # The main parser # parser = argparse.ArgumentParser(prog='tagcube', description=DESCRIPTION, ...
[ "def", "parse_args", "(", "args", "=", "None", ")", ":", "#", "# The main parser", "#", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "'tagcube'", ",", "description", "=", "DESCRIPTION", ",", "epilog", "=", "EPILOG", ")", "#", "# ...
:return: The result of applying argparse to sys.argv
[ ":", "return", ":", "The", "result", "of", "applying", "argparse", "to", "sys", ".", "argv" ]
train
https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube_cli/cli.py#L84-L215
tagcubeio/tagcube-cli
tagcube_cli/cli.py
TagCubeCLI.get_credentials
def get_credentials(cmd_args): """ :return: The email and api_key to use to connect to TagCube. This function will try to get the credentials from: * Command line arguments * Environment variables * Configuration file ...
python
def get_credentials(cmd_args): """ :return: The email and api_key to use to connect to TagCube. This function will try to get the credentials from: * Command line arguments * Environment variables * Configuration file ...
[ "def", "get_credentials", "(", "cmd_args", ")", ":", "# Check the cmd args, return if we have something here", "cmd_credentials", "=", "cmd_args", ".", "email", ",", "cmd_args", ".", "key", "if", "cmd_credentials", "!=", "(", "None", ",", "None", ")", ":", "cli_logg...
:return: The email and api_key to use to connect to TagCube. This function will try to get the credentials from: * Command line arguments * Environment variables * Configuration file It will return the first match, in the ord...
[ ":", "return", ":", "The", "email", "and", "api_key", "to", "use", "to", "connect", "to", "TagCube", ".", "This", "function", "will", "try", "to", "get", "the", "credentials", "from", ":", "*", "Command", "line", "arguments", "*", "Environment", "variables...
train
https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube_cli/cli.py#L259-L287
etcher-be/elib_config
elib_config/_value/_config_value.py
ConfigValue.path
def path(self) -> str: """ :return: path of this config value as a string """ path: str = ELIBConfig.config_sep_str.join(self._raw_path) if ELIBConfig.root_path: prefix = ELIBConfig.config_sep_str.join(ELIBConfig.root_path) path = ELIBConfig.config_sep_str...
python
def path(self) -> str: """ :return: path of this config value as a string """ path: str = ELIBConfig.config_sep_str.join(self._raw_path) if ELIBConfig.root_path: prefix = ELIBConfig.config_sep_str.join(ELIBConfig.root_path) path = ELIBConfig.config_sep_str...
[ "def", "path", "(", "self", ")", "->", "str", ":", "path", ":", "str", "=", "ELIBConfig", ".", "config_sep_str", ".", "join", "(", "self", ".", "_raw_path", ")", "if", "ELIBConfig", ".", "root_path", ":", "prefix", "=", "ELIBConfig", ".", "config_sep_str...
:return: path of this config value as a string
[ ":", "return", ":", "path", "of", "this", "config", "value", "as", "a", "string" ]
train
https://github.com/etcher-be/elib_config/blob/5d8c839e84d70126620ab0186dc1f717e5868bd0/elib_config/_value/_config_value.py#L37-L45
etcher-be/elib_config
elib_config/_value/_config_value.py
ConfigValue.raw_value
def raw_value(self) -> typing.Optional[object]: """ :return: raw value """ raw_value = self._from_environ() if raw_value is None: raw_value = self._from_config_file() if raw_value is None: raw_value = self._from_default() return raw_value
python
def raw_value(self) -> typing.Optional[object]: """ :return: raw value """ raw_value = self._from_environ() if raw_value is None: raw_value = self._from_config_file() if raw_value is None: raw_value = self._from_default() return raw_value
[ "def", "raw_value", "(", "self", ")", "->", "typing", ".", "Optional", "[", "object", "]", ":", "raw_value", "=", "self", ".", "_from_environ", "(", ")", "if", "raw_value", "is", "None", ":", "raw_value", "=", "self", ".", "_from_config_file", "(", ")", ...
:return: raw value
[ ":", "return", ":", "raw", "value" ]
train
https://github.com/etcher-be/elib_config/blob/5d8c839e84d70126620ab0186dc1f717e5868bd0/elib_config/_value/_config_value.py#L85-L94
chrisdrackett/django-support
support/templatetags/form_tags.py
select_template_from_string
def select_template_from_string(arg): """ Select a template from a string, which can include multiple template paths separated by commas. """ if ',' in arg: tpl = loader.select_template( [tn.strip() for tn in arg.split(',')]) else: tpl = loader.get_template(arg) ...
python
def select_template_from_string(arg): """ Select a template from a string, which can include multiple template paths separated by commas. """ if ',' in arg: tpl = loader.select_template( [tn.strip() for tn in arg.split(',')]) else: tpl = loader.get_template(arg) ...
[ "def", "select_template_from_string", "(", "arg", ")", ":", "if", "','", "in", "arg", ":", "tpl", "=", "loader", ".", "select_template", "(", "[", "tn", ".", "strip", "(", ")", "for", "tn", "in", "arg", ".", "split", "(", "','", ")", "]", ")", "els...
Select a template from a string, which can include multiple template paths separated by commas.
[ "Select", "a", "template", "from", "a", "string", "which", "can", "include", "multiple", "template", "paths", "separated", "by", "commas", "." ]
train
https://github.com/chrisdrackett/django-support/blob/a4f29421a31797e0b069637a0afec85328b4f0ca/support/templatetags/form_tags.py#L6-L17
cirruscluster/cirruscluster
cirruscluster/ext/ansible/utils/plugins.py
PluginLoader._get_package_path
def _get_package_path(self): """Gets the path of a Python package""" if not self.package: return [] if not hasattr(self, 'package_path'): m = __import__(self.package) parts = self.package.split('.')[1:] self.package_path = os.path.join(os.path.dirn...
python
def _get_package_path(self): """Gets the path of a Python package""" if not self.package: return [] if not hasattr(self, 'package_path'): m = __import__(self.package) parts = self.package.split('.')[1:] self.package_path = os.path.join(os.path.dirn...
[ "def", "_get_package_path", "(", "self", ")", ":", "if", "not", "self", ".", "package", ":", "return", "[", "]", "if", "not", "hasattr", "(", "self", ",", "'package_path'", ")", ":", "m", "=", "__import__", "(", "self", ".", "package", ")", "parts", ...
Gets the path of a Python package
[ "Gets", "the", "path", "of", "a", "Python", "package" ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/plugins.py#L47-L55
cirruscluster/cirruscluster
cirruscluster/ext/ansible/utils/plugins.py
PluginLoader._get_paths
def _get_paths(self): """Return a list of paths to search for plugins in The list is searched in order.""" ret = [] ret += ['%s/library/' % os.path.dirname(os.path.dirname(__file__))] ret += self._extra_dirs for basedir in _basedirs: fullpath...
python
def _get_paths(self): """Return a list of paths to search for plugins in The list is searched in order.""" ret = [] ret += ['%s/library/' % os.path.dirname(os.path.dirname(__file__))] ret += self._extra_dirs for basedir in _basedirs: fullpath...
[ "def", "_get_paths", "(", "self", ")", ":", "ret", "=", "[", "]", "ret", "+=", "[", "'%s/library/'", "%", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "]", "ret", "+=", "self", ".", "_extra...
Return a list of paths to search for plugins in The list is searched in order.
[ "Return", "a", "list", "of", "paths", "to", "search", "for", "plugins", "in" ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/plugins.py#L57-L71
cirruscluster/cirruscluster
cirruscluster/ext/ansible/utils/plugins.py
PluginLoader.print_paths
def print_paths(self): """Returns a string suitable for printing of the search path""" # Uses a list to get the order right ret = [] for i in self._get_paths(): if i not in ret: ret.append(i) return os.pathsep.join(ret)
python
def print_paths(self): """Returns a string suitable for printing of the search path""" # Uses a list to get the order right ret = [] for i in self._get_paths(): if i not in ret: ret.append(i) return os.pathsep.join(ret)
[ "def", "print_paths", "(", "self", ")", ":", "# Uses a list to get the order right", "ret", "=", "[", "]", "for", "i", "in", "self", ".", "_get_paths", "(", ")", ":", "if", "i", "not", "in", "ret", ":", "ret", ".", "append", "(", "i", ")", "return", ...
Returns a string suitable for printing of the search path
[ "Returns", "a", "string", "suitable", "for", "printing", "of", "the", "search", "path" ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/plugins.py#L78-L85