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
daknuett/py_register_machine2
core/memory.py
ROM.program
def program(self, prog, offset = 0): """ .. _program: Write the content of the iterable ``prog`` starting with the optional offset ``offset`` to the device. Invokes program_word_. """ for addr, word in enumerate(prog): self.program_word(offset + addr, word)
python
def program(self, prog, offset = 0): """ .. _program: Write the content of the iterable ``prog`` starting with the optional offset ``offset`` to the device. Invokes program_word_. """ for addr, word in enumerate(prog): self.program_word(offset + addr, word)
[ "def", "program", "(", "self", ",", "prog", ",", "offset", "=", "0", ")", ":", "for", "addr", ",", "word", "in", "enumerate", "(", "prog", ")", ":", "self", ".", "program_word", "(", "offset", "+", "addr", ",", "word", ")" ]
.. _program: Write the content of the iterable ``prog`` starting with the optional offset ``offset`` to the device. Invokes program_word_.
[ "..", "_program", ":" ]
train
https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/core/memory.py#L51-L61
sandwichcloud/ingredients.db
ingredients_db/database.py
Database._add_process_guards
def _add_process_guards(self, engine): """Add multiprocessing guards. Forces a connection to be reconnected if it is detected as having been shared to a sub-process. """ @sqlalchemy.event.listens_for(engine, "connect") def connect(dbapi_connection, connection_record): ...
python
def _add_process_guards(self, engine): """Add multiprocessing guards. Forces a connection to be reconnected if it is detected as having been shared to a sub-process. """ @sqlalchemy.event.listens_for(engine, "connect") def connect(dbapi_connection, connection_record): ...
[ "def", "_add_process_guards", "(", "self", ",", "engine", ")", ":", "@", "sqlalchemy", ".", "event", ".", "listens_for", "(", "engine", ",", "\"connect\"", ")", "def", "connect", "(", "dbapi_connection", ",", "connection_record", ")", ":", "connection_record", ...
Add multiprocessing guards. Forces a connection to be reconnected if it is detected as having been shared to a sub-process.
[ "Add", "multiprocessing", "guards", "." ]
train
https://github.com/sandwichcloud/ingredients.db/blob/e91602fbece74290e051016439346fd4a3f1524e/ingredients_db/database.py#L53-L76
sandwichcloud/ingredients.db
ingredients_db/database.py
Database.current
def current(self): """ Display the current database revision """ config = self.alembic_config() script = ScriptDirectory.from_config(config) revision = 'base' def display_version(rev, context): for rev in script.get_all_current(rev): ...
python
def current(self): """ Display the current database revision """ config = self.alembic_config() script = ScriptDirectory.from_config(config) revision = 'base' def display_version(rev, context): for rev in script.get_all_current(rev): ...
[ "def", "current", "(", "self", ")", ":", "config", "=", "self", ".", "alembic_config", "(", ")", "script", "=", "ScriptDirectory", ".", "from_config", "(", "config", ")", "revision", "=", "'base'", "def", "display_version", "(", "rev", ",", "context", ")",...
Display the current database revision
[ "Display", "the", "current", "database", "revision" ]
train
https://github.com/sandwichcloud/ingredients.db/blob/e91602fbece74290e051016439346fd4a3f1524e/ingredients_db/database.py#L115-L135
sandwichcloud/ingredients.db
ingredients_db/database.py
Database.revision
def revision(self, message): """ Create a new revision file :param message: """ alembic.command.revision(self.alembic_config(), message=message)
python
def revision(self, message): """ Create a new revision file :param message: """ alembic.command.revision(self.alembic_config(), message=message)
[ "def", "revision", "(", "self", ",", "message", ")", ":", "alembic", ".", "command", ".", "revision", "(", "self", ".", "alembic_config", "(", ")", ",", "message", "=", "message", ")" ]
Create a new revision file :param message:
[ "Create", "a", "new", "revision", "file" ]
train
https://github.com/sandwichcloud/ingredients.db/blob/e91602fbece74290e051016439346fd4a3f1524e/ingredients_db/database.py#L157-L163
clld/cdstarcat
src/cdstarcat/__main__.py
cleanup
def cleanup(args): """ cdstarcat cleanup Deletes objects with no bitstreams from CDSTAR and the catalog. """ with _catalog(args) as cat: n, d, r = len(cat), [], [] for obj in cat: if not obj.bitstreams: if obj.is_special: print('removi...
python
def cleanup(args): """ cdstarcat cleanup Deletes objects with no bitstreams from CDSTAR and the catalog. """ with _catalog(args) as cat: n, d, r = len(cat), [], [] for obj in cat: if not obj.bitstreams: if obj.is_special: print('removi...
[ "def", "cleanup", "(", "args", ")", ":", "with", "_catalog", "(", "args", ")", "as", "cat", ":", "n", ",", "d", ",", "r", "=", "len", "(", "cat", ")", ",", "[", "]", ",", "[", "]", "for", "obj", "in", "cat", ":", "if", "not", "obj", ".", ...
cdstarcat cleanup Deletes objects with no bitstreams from CDSTAR and the catalog.
[ "cdstarcat", "cleanup" ]
train
https://github.com/clld/cdstarcat/blob/41f33f59cdde5e30835d2f3accf2d1fbe5332cab/src/cdstarcat/__main__.py#L23-L44
clld/cdstarcat
src/cdstarcat/__main__.py
stats
def stats(args): """ cdstarcat stats Print summary statistics of bitstreams in the catalog to stdout. """ cat = _catalog(args) print('Summary:') print(' {0:,} objects with {1:,} bitstreams of total size {2}'.format( len(cat), sum(len(obj.bitstreams) for obj in cat), cat.size_h)) ...
python
def stats(args): """ cdstarcat stats Print summary statistics of bitstreams in the catalog to stdout. """ cat = _catalog(args) print('Summary:') print(' {0:,} objects with {1:,} bitstreams of total size {2}'.format( len(cat), sum(len(obj.bitstreams) for obj in cat), cat.size_h)) ...
[ "def", "stats", "(", "args", ")", ":", "cat", "=", "_catalog", "(", "args", ")", "print", "(", "'Summary:'", ")", "print", "(", "' {0:,} objects with {1:,} bitstreams of total size {2}'", ".", "format", "(", "len", "(", "cat", ")", ",", "sum", "(", "len", ...
cdstarcat stats Print summary statistics of bitstreams in the catalog to stdout.
[ "cdstarcat", "stats" ]
train
https://github.com/clld/cdstarcat/blob/41f33f59cdde5e30835d2f3accf2d1fbe5332cab/src/cdstarcat/__main__.py#L48-L71
clld/cdstarcat
src/cdstarcat/__main__.py
add
def add(args): """ cdstarcat add SPEC Add metadata about objects (specified by SPEC) in CDSTAR to the catalog. SPEC: Either a CDSTAR object ID or a query. """ spec = args.args[0] with _catalog(args) as cat: n = len(cat) if OBJID_PATTERN.match(spec): cat.add_objid...
python
def add(args): """ cdstarcat add SPEC Add metadata about objects (specified by SPEC) in CDSTAR to the catalog. SPEC: Either a CDSTAR object ID or a query. """ spec = args.args[0] with _catalog(args) as cat: n = len(cat) if OBJID_PATTERN.match(spec): cat.add_objid...
[ "def", "add", "(", "args", ")", ":", "spec", "=", "args", ".", "args", "[", "0", "]", "with", "_catalog", "(", "args", ")", "as", "cat", ":", "n", "=", "len", "(", "cat", ")", "if", "OBJID_PATTERN", ".", "match", "(", "spec", ")", ":", "cat", ...
cdstarcat add SPEC Add metadata about objects (specified by SPEC) in CDSTAR to the catalog. SPEC: Either a CDSTAR object ID or a query.
[ "cdstarcat", "add", "SPEC" ]
train
https://github.com/clld/cdstarcat/blob/41f33f59cdde5e30835d2f3accf2d1fbe5332cab/src/cdstarcat/__main__.py#L75-L91
clld/cdstarcat
src/cdstarcat/__main__.py
create
def create(args): """ cdstarcat create PATH Create objects in CDSTAR specified by PATH. When PATH is a file, a single object (possibly with multiple bitstreams) is created; When PATH is a directory, an object will be created for each file in the directory (recursing into subdirectories). ""...
python
def create(args): """ cdstarcat create PATH Create objects in CDSTAR specified by PATH. When PATH is a file, a single object (possibly with multiple bitstreams) is created; When PATH is a directory, an object will be created for each file in the directory (recursing into subdirectories). ""...
[ "def", "create", "(", "args", ")", ":", "with", "_catalog", "(", "args", ")", "as", "cat", ":", "for", "fname", ",", "created", ",", "obj", "in", "cat", ".", "create", "(", "args", ".", "args", "[", "0", "]", ",", "{", "}", ")", ":", "args", ...
cdstarcat create PATH Create objects in CDSTAR specified by PATH. When PATH is a file, a single object (possibly with multiple bitstreams) is created; When PATH is a directory, an object will be created for each file in the directory (recursing into subdirectories).
[ "cdstarcat", "create", "PATH" ]
train
https://github.com/clld/cdstarcat/blob/41f33f59cdde5e30835d2f3accf2d1fbe5332cab/src/cdstarcat/__main__.py#L95-L107
clld/cdstarcat
src/cdstarcat/__main__.py
delete
def delete(args): """ cdstarcat delete OID Delete an object specified by OID from CDSTAR. """ with _catalog(args) as cat: n = len(cat) cat.delete(args.args[0]) args.log.info('{0} objects deleted'.format(n - len(cat))) return n - len(cat)
python
def delete(args): """ cdstarcat delete OID Delete an object specified by OID from CDSTAR. """ with _catalog(args) as cat: n = len(cat) cat.delete(args.args[0]) args.log.info('{0} objects deleted'.format(n - len(cat))) return n - len(cat)
[ "def", "delete", "(", "args", ")", ":", "with", "_catalog", "(", "args", ")", "as", "cat", ":", "n", "=", "len", "(", "cat", ")", "cat", ".", "delete", "(", "args", ".", "args", "[", "0", "]", ")", "args", ".", "log", ".", "info", "(", "'{0} ...
cdstarcat delete OID Delete an object specified by OID from CDSTAR.
[ "cdstarcat", "delete", "OID" ]
train
https://github.com/clld/cdstarcat/blob/41f33f59cdde5e30835d2f3accf2d1fbe5332cab/src/cdstarcat/__main__.py#L111-L121
clld/cdstarcat
src/cdstarcat/__main__.py
update
def update(args): """ cdstarcat update OID [KEY=VALUE]+ Update the metadata of an object. """ with _catalog(args) as cat: cat.update_metadata( args.args[0], dict([arg.split('=', 1) for arg in args.args[1:]]))
python
def update(args): """ cdstarcat update OID [KEY=VALUE]+ Update the metadata of an object. """ with _catalog(args) as cat: cat.update_metadata( args.args[0], dict([arg.split('=', 1) for arg in args.args[1:]]))
[ "def", "update", "(", "args", ")", ":", "with", "_catalog", "(", "args", ")", "as", "cat", ":", "cat", ".", "update_metadata", "(", "args", ".", "args", "[", "0", "]", ",", "dict", "(", "[", "arg", ".", "split", "(", "'='", ",", "1", ")", "for"...
cdstarcat update OID [KEY=VALUE]+ Update the metadata of an object.
[ "cdstarcat", "update", "OID", "[", "KEY", "=", "VALUE", "]", "+" ]
train
https://github.com/clld/cdstarcat/blob/41f33f59cdde5e30835d2f3accf2d1fbe5332cab/src/cdstarcat/__main__.py#L125-L133
oubiga/respect
respect/utils.py
sanitize_qualifiers
def sanitize_qualifiers(repos=None, followers=None, language=None): ''' qualifiers = c repos:+42 followers:+1000 language: params = {'q': 'tom repos:>42 followers:>1000'} ''' qualifiers = '' if repos: qualifiers += 'repos:{0} '.format(repos) qualifiers = re.sub(r"([+])([=a-zA-Z0...
python
def sanitize_qualifiers(repos=None, followers=None, language=None): ''' qualifiers = c repos:+42 followers:+1000 language: params = {'q': 'tom repos:>42 followers:>1000'} ''' qualifiers = '' if repos: qualifiers += 'repos:{0} '.format(repos) qualifiers = re.sub(r"([+])([=a-zA-Z0...
[ "def", "sanitize_qualifiers", "(", "repos", "=", "None", ",", "followers", "=", "None", ",", "language", "=", "None", ")", ":", "qualifiers", "=", "''", "if", "repos", ":", "qualifiers", "+=", "'repos:{0} '", ".", "format", "(", "repos", ")", "qualifiers",...
qualifiers = c repos:+42 followers:+1000 language: params = {'q': 'tom repos:>42 followers:>1000'}
[ "qualifiers", "=", "c", "repos", ":", "+", "42", "followers", ":", "+", "1000", "language", ":", "params", "=", "{", "q", ":", "tom", "repos", ":", ">", "42", "followers", ":", ">", "1000", "}" ]
train
https://github.com/oubiga/respect/blob/550554ec4d3139379d03cb8f82a8cd2d80c3ad62/respect/utils.py#L74-L101
coghost/izen
izen/schedule.py
Scheduler.run_continuously
def run_continuously(self, interval=1): """Continuously run, while executing pending jobs at each elapsed time interval. @return cease_continuous_run: threading.Event which can be set to cease continuous run. Please note that it is *intended behavior that run_continuously() ...
python
def run_continuously(self, interval=1): """Continuously run, while executing pending jobs at each elapsed time interval. @return cease_continuous_run: threading.Event which can be set to cease continuous run. Please note that it is *intended behavior that run_continuously() ...
[ "def", "run_continuously", "(", "self", ",", "interval", "=", "1", ")", ":", "cease_continuous_run", "=", "threading", ".", "Event", "(", ")", "class", "ScheduleThread", "(", "threading", ".", "Thread", ")", ":", "@", "classmethod", "def", "run", "(", "cls...
Continuously run, while executing pending jobs at each elapsed time interval. @return cease_continuous_run: threading.Event which can be set to cease continuous run. Please note that it is *intended behavior that run_continuously() does not run missed jobs*. For example, if you...
[ "Continuously", "run", "while", "executing", "pending", "jobs", "at", "each", "elapsed", "time", "interval", "." ]
train
https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/schedule.py#L66-L90
coghost/izen
izen/schedule.py
Job.tag
def tag(self, *tags): """ Tags the job with one or more unique indentifiers. Tags must be hashable. Duplicate tags are discarded. :param tags: A unique list of ``Hashable`` tags. :return: The invoked job instance """ if any([not isinstance(tag, collections.Hasha...
python
def tag(self, *tags): """ Tags the job with one or more unique indentifiers. Tags must be hashable. Duplicate tags are discarded. :param tags: A unique list of ``Hashable`` tags. :return: The invoked job instance """ if any([not isinstance(tag, collections.Hasha...
[ "def", "tag", "(", "self", ",", "*", "tags", ")", ":", "if", "any", "(", "[", "not", "isinstance", "(", "tag", ",", "collections", ".", "Hashable", ")", "for", "tag", "in", "tags", "]", ")", ":", "raise", "TypeError", "(", "'Every tag should be hashabl...
Tags the job with one or more unique indentifiers. Tags must be hashable. Duplicate tags are discarded. :param tags: A unique list of ``Hashable`` tags. :return: The invoked job instance
[ "Tags", "the", "job", "with", "one", "or", "more", "unique", "indentifiers", "." ]
train
https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/schedule.py#L323-L338
coghost/izen
izen/schedule.py
Job.at
def at(self, time_str): """ Schedule the job every day at a specific time. Calling this is only valid for jobs scheduled to run every N day(s). :param time_str: A string in `XX:YY` format. :return: The invoked job instance """ assert self.unit in ('days'...
python
def at(self, time_str): """ Schedule the job every day at a specific time. Calling this is only valid for jobs scheduled to run every N day(s). :param time_str: A string in `XX:YY` format. :return: The invoked job instance """ assert self.unit in ('days'...
[ "def", "at", "(", "self", ",", "time_str", ")", ":", "assert", "self", ".", "unit", "in", "(", "'days'", ",", "'hours'", ")", "or", "self", ".", "start_day", "hour", ",", "minute", "=", "time_str", ".", "split", "(", "':'", ")", "minute", "=", "int...
Schedule the job every day at a specific time. Calling this is only valid for jobs scheduled to run every N day(s). :param time_str: A string in `XX:YY` format. :return: The invoked job instance
[ "Schedule", "the", "job", "every", "day", "at", "a", "specific", "time", "." ]
train
https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/schedule.py#L340-L360
flo-compbio/gopca-server
gpserver/job.py
GSJob.update_status
def update_status(self): """ returns True if status has changed """ # this function should be part of the server if (self.status is not None) and self.status > 0: # status is already final return False old_status = self.status job_dir = self.run_...
python
def update_status(self): """ returns True if status has changed """ # this function should be part of the server if (self.status is not None) and self.status > 0: # status is already final return False old_status = self.status job_dir = self.run_...
[ "def", "update_status", "(", "self", ")", ":", "# this function should be part of the server", "if", "(", "self", ".", "status", "is", "not", "None", ")", "and", "self", ".", "status", ">", "0", ":", "# status is already final", "return", "False", "old_status", ...
returns True if status has changed
[ "returns", "True", "if", "status", "has", "changed" ]
train
https://github.com/flo-compbio/gopca-server/blob/4fe396b12c39c0f156ce3bc4538cade54c9d7ffe/gpserver/job.py#L145-L167
carlosp420/primer-designer
primer_designer/utils.py
is_fasta
def is_fasta(filename): """Check if filename is FASTA based on extension Return: Boolean """ if re.search("\.fa*s[ta]*$", filename, flags=re.I): return True elif re.search("\.fa$", filename, flags=re.I): return True else: return False
python
def is_fasta(filename): """Check if filename is FASTA based on extension Return: Boolean """ if re.search("\.fa*s[ta]*$", filename, flags=re.I): return True elif re.search("\.fa$", filename, flags=re.I): return True else: return False
[ "def", "is_fasta", "(", "filename", ")", ":", "if", "re", ".", "search", "(", "\"\\.fa*s[ta]*$\"", ",", "filename", ",", "flags", "=", "re", ".", "I", ")", ":", "return", "True", "elif", "re", ".", "search", "(", "\"\\.fa$\"", ",", "filename", ",", "...
Check if filename is FASTA based on extension Return: Boolean
[ "Check", "if", "filename", "is", "FASTA", "based", "on", "extension" ]
train
https://github.com/carlosp420/primer-designer/blob/586cb7fecf41fedbffe6563c8b79a3156c6066ae/primer_designer/utils.py#L4-L15
mlaprise/genSpline
genSpline/genSpline.py
gaussianPulse
def gaussianPulse(t, FWHM, t0, P0 = 1.0, m = 1, C = 0): """ Geneate a gaussian/supergaussiance envelope pulse * field_amp: output gaussian pulse envellope (amplitude). * t: vector of times at which to compute u * t0: center of pulse (default = 0) * FWHM: full-width at half-intensity of pulse ...
python
def gaussianPulse(t, FWHM, t0, P0 = 1.0, m = 1, C = 0): """ Geneate a gaussian/supergaussiance envelope pulse * field_amp: output gaussian pulse envellope (amplitude). * t: vector of times at which to compute u * t0: center of pulse (default = 0) * FWHM: full-width at half-intensity of pulse ...
[ "def", "gaussianPulse", "(", "t", ",", "FWHM", ",", "t0", ",", "P0", "=", "1.0", ",", "m", "=", "1", ",", "C", "=", "0", ")", ":", "t_zero", "=", "FWHM", "/", "sqrt", "(", "4.0", "*", "log", "(", "2.0", ")", ")", "amp", "=", "sqrt", "(", ...
Geneate a gaussian/supergaussiance envelope pulse * field_amp: output gaussian pulse envellope (amplitude). * t: vector of times at which to compute u * t0: center of pulse (default = 0) * FWHM: full-width at half-intensity of pulse (default = 1) * P0: peak intensity of the pulse @ t=t0 ...
[ "Geneate", "a", "gaussian", "/", "supergaussiance", "envelope", "pulse" ]
train
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L52-L70
mlaprise/genSpline
genSpline/genSpline.py
IndividualReal.plotGene
def plotGene(self): ''' Plot the gene ''' pl.plot(self.x, self.y, '.') pl.grid(True) pl.show()
python
def plotGene(self): ''' Plot the gene ''' pl.plot(self.x, self.y, '.') pl.grid(True) pl.show()
[ "def", "plotGene", "(", "self", ")", ":", "pl", ".", "plot", "(", "self", ".", "x", ",", "self", ".", "y", ",", "'.'", ")", "pl", ".", "grid", "(", "True", ")", "pl", ".", "show", "(", ")" ]
Plot the gene
[ "Plot", "the", "gene" ]
train
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L100-L106
mlaprise/genSpline
genSpline/genSpline.py
IndividualReal.plotIndividual
def plotIndividual(self): ''' Plot the individual ''' pl.plot(self.x_int, self.y_int) pl.grid(True) pl.show()
python
def plotIndividual(self): ''' Plot the individual ''' pl.plot(self.x_int, self.y_int) pl.grid(True) pl.show()
[ "def", "plotIndividual", "(", "self", ")", ":", "pl", ".", "plot", "(", "self", ".", "x_int", ",", "self", ".", "y_int", ")", "pl", ".", "grid", "(", "True", ")", "pl", ".", "show", "(", ")" ]
Plot the individual
[ "Plot", "the", "individual" ]
train
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L108-L114
mlaprise/genSpline
genSpline/genSpline.py
IndividualReal.plot
def plot(self): ''' Plot the individual and the gene ''' pl.plot(self.x, self.y, '.') pl.plot(self.x_int, self.y_int) pl.grid(True) pl.show()
python
def plot(self): ''' Plot the individual and the gene ''' pl.plot(self.x, self.y, '.') pl.plot(self.x_int, self.y_int) pl.grid(True) pl.show()
[ "def", "plot", "(", "self", ")", ":", "pl", ".", "plot", "(", "self", ".", "x", ",", "self", ".", "y", ",", "'.'", ")", "pl", ".", "plot", "(", "self", ".", "x_int", ",", "self", ".", "y_int", ")", "pl", ".", "grid", "(", "True", ")", "pl",...
Plot the individual and the gene
[ "Plot", "the", "individual", "and", "the", "gene" ]
train
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L116-L123
mlaprise/genSpline
genSpline/genSpline.py
IndividualReal.mutation
def mutation(self, strength = 0.1): ''' Single gene mutation ''' mutStrengthReal = strength mutMaxSizeReal = self.gLength/2 mutSizeReal = int(numpy.random.random_integers(1,mutMaxSizeReal)) mutationPosReal = int(numpy.random.random_integers(0+mutSizeReal-1,self.y.shape[0]-1-mutSizeReal)) mutationSignRea...
python
def mutation(self, strength = 0.1): ''' Single gene mutation ''' mutStrengthReal = strength mutMaxSizeReal = self.gLength/2 mutSizeReal = int(numpy.random.random_integers(1,mutMaxSizeReal)) mutationPosReal = int(numpy.random.random_integers(0+mutSizeReal-1,self.y.shape[0]-1-mutSizeReal)) mutationSignRea...
[ "def", "mutation", "(", "self", ",", "strength", "=", "0.1", ")", ":", "mutStrengthReal", "=", "strength", "mutMaxSizeReal", "=", "self", ".", "gLength", "/", "2", "mutSizeReal", "=", "int", "(", "numpy", ".", "random", ".", "random_integers", "(", "1", ...
Single gene mutation
[ "Single", "gene", "mutation" ]
train
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L125-L143
mlaprise/genSpline
genSpline/genSpline.py
IndividualReal.mutations
def mutations(self, nbr, strength): ''' Multiple gene mutations ''' for i in range(nbr): self.mutation(strength)
python
def mutations(self, nbr, strength): ''' Multiple gene mutations ''' for i in range(nbr): self.mutation(strength)
[ "def", "mutations", "(", "self", ",", "nbr", ",", "strength", ")", ":", "for", "i", "in", "range", "(", "nbr", ")", ":", "self", ".", "mutation", "(", "strength", ")" ]
Multiple gene mutations
[ "Multiple", "gene", "mutations" ]
train
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L145-L150
mlaprise/genSpline
genSpline/genSpline.py
IndividualReal.birth
def birth(self): ''' Create the individual (compute the spline curve) ''' spline = scipy.interpolate.splrep(self.x, self.y) self.y_int = scipy.interpolate.splev(self.x_int,spline)
python
def birth(self): ''' Create the individual (compute the spline curve) ''' spline = scipy.interpolate.splrep(self.x, self.y) self.y_int = scipy.interpolate.splev(self.x_int,spline)
[ "def", "birth", "(", "self", ")", ":", "spline", "=", "scipy", ".", "interpolate", ".", "splrep", "(", "self", ".", "x", ",", "self", ".", "y", ")", "self", ".", "y_int", "=", "scipy", ".", "interpolate", ".", "splev", "(", "self", ".", "x_int", ...
Create the individual (compute the spline curve)
[ "Create", "the", "individual", "(", "compute", "the", "spline", "curve", ")" ]
train
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L153-L158
mlaprise/genSpline
genSpline/genSpline.py
IndividualComp.mutation
def mutation(self,strength = 0.1): ''' Single gene mutation - Complex version ''' # Mutation du gene - real mutStrengthReal = strength mutMaxSizeReal = self.gLength/2 mutSizeReal = int(numpy.random.random_integers(1,mutMaxSizeReal)) mutationPosReal = int(numpy.random.random_integers(0+mutSizeReal-1,self...
python
def mutation(self,strength = 0.1): ''' Single gene mutation - Complex version ''' # Mutation du gene - real mutStrengthReal = strength mutMaxSizeReal = self.gLength/2 mutSizeReal = int(numpy.random.random_integers(1,mutMaxSizeReal)) mutationPosReal = int(numpy.random.random_integers(0+mutSizeReal-1,self...
[ "def", "mutation", "(", "self", ",", "strength", "=", "0.1", ")", ":", "# Mutation du gene - real", "mutStrengthReal", "=", "strength", "mutMaxSizeReal", "=", "self", ".", "gLength", "/", "2", "mutSizeReal", "=", "int", "(", "numpy", ".", "random", ".", "ran...
Single gene mutation - Complex version
[ "Single", "gene", "mutation", "-", "Complex", "version" ]
train
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L253-L288
mlaprise/genSpline
genSpline/genSpline.py
IndividualComp.birth
def birth(self): ''' Create the individual (compute the spline curve) ''' splineReal = scipy.interpolate.splrep(self.x, self.y.real) self.y_int.real = scipy.interpolate.splev(self.x_int,splineReal) splineImag = scipy.interpolate.splrep(self.x, self.y.imag) self.y_int.imag = scipy.interpolate.splev(self.x_...
python
def birth(self): ''' Create the individual (compute the spline curve) ''' splineReal = scipy.interpolate.splrep(self.x, self.y.real) self.y_int.real = scipy.interpolate.splev(self.x_int,splineReal) splineImag = scipy.interpolate.splrep(self.x, self.y.imag) self.y_int.imag = scipy.interpolate.splev(self.x_...
[ "def", "birth", "(", "self", ")", ":", "splineReal", "=", "scipy", ".", "interpolate", ".", "splrep", "(", "self", ".", "x", ",", "self", ".", "y", ".", "real", ")", "self", ".", "y_int", ".", "real", "=", "scipy", ".", "interpolate", ".", "splev",...
Create the individual (compute the spline curve)
[ "Create", "the", "individual", "(", "compute", "the", "spline", "curve", ")" ]
train
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L299-L306
mlaprise/genSpline
genSpline/genSpline.py
Population.rankingEval
def rankingEval(self): ''' Sorting the pop. base on the fitnessEval result ''' fitnessAll = numpy.zeros(self.length) fitnessNorm = numpy.zeros(self.length) for i in range(self.length): self.Ind[i].fitnessEval() fitnessAll[i] = self.Ind[i].fitness maxFitness = fitnessAll.max() for i in range(self...
python
def rankingEval(self): ''' Sorting the pop. base on the fitnessEval result ''' fitnessAll = numpy.zeros(self.length) fitnessNorm = numpy.zeros(self.length) for i in range(self.length): self.Ind[i].fitnessEval() fitnessAll[i] = self.Ind[i].fitness maxFitness = fitnessAll.max() for i in range(self...
[ "def", "rankingEval", "(", "self", ")", ":", "fitnessAll", "=", "numpy", ".", "zeros", "(", "self", ".", "length", ")", "fitnessNorm", "=", "numpy", ".", "zeros", "(", "self", ".", "length", ")", "for", "i", "in", "range", "(", "self", ".", "length",...
Sorting the pop. base on the fitnessEval result
[ "Sorting", "the", "pop", ".", "base", "on", "the", "fitnessEval", "result" ]
train
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L394-L418
mlaprise/genSpline
genSpline/genSpline.py
Population.sortedbyAge
def sortedbyAge(self): ''' Sorting the pop. base of the age ''' ageAll = numpy.zeros(self.length) for i in range(self.length): ageAll[i] = self.Ind[i].age ageSorted = ageAll.argsort() return ageSorted[::-1]
python
def sortedbyAge(self): ''' Sorting the pop. base of the age ''' ageAll = numpy.zeros(self.length) for i in range(self.length): ageAll[i] = self.Ind[i].age ageSorted = ageAll.argsort() return ageSorted[::-1]
[ "def", "sortedbyAge", "(", "self", ")", ":", "ageAll", "=", "numpy", ".", "zeros", "(", "self", ".", "length", ")", "for", "i", "in", "range", "(", "self", ".", "length", ")", ":", "ageAll", "[", "i", "]", "=", "self", ".", "Ind", "[", "i", "]"...
Sorting the pop. base of the age
[ "Sorting", "the", "pop", ".", "base", "of", "the", "age" ]
train
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L420-L428
mlaprise/genSpline
genSpline/genSpline.py
Population.RWSelection
def RWSelection(self, mating_pool_size): ''' Make Selection of the mating pool with the roulette wheel algorithm ''' A = numpy.zeros(self.length) mating_pool = numpy.zeros(mating_pool_size) [F,S,P] = self.rankingEval() P_Sorted = numpy.zeros(self.length) for i in range(self.length): P_Sorted[i] ...
python
def RWSelection(self, mating_pool_size): ''' Make Selection of the mating pool with the roulette wheel algorithm ''' A = numpy.zeros(self.length) mating_pool = numpy.zeros(mating_pool_size) [F,S,P] = self.rankingEval() P_Sorted = numpy.zeros(self.length) for i in range(self.length): P_Sorted[i] ...
[ "def", "RWSelection", "(", "self", ",", "mating_pool_size", ")", ":", "A", "=", "numpy", ".", "zeros", "(", "self", ".", "length", ")", "mating_pool", "=", "numpy", ".", "zeros", "(", "mating_pool_size", ")", "[", "F", ",", "S", ",", "P", "]", "=", ...
Make Selection of the mating pool with the roulette wheel algorithm
[ "Make", "Selection", "of", "the", "mating", "pool", "with", "the", "roulette", "wheel", "algorithm" ]
train
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L430-L457
mlaprise/genSpline
genSpline/genSpline.py
Population.SUSSelection
def SUSSelection(self, mating_pool_size): ''' Make Selection of the mating pool with the stochastic universal sampling algorithm ''' A = numpy.zeros(self.length) mating_pool = numpy.zeros(mating_pool_size) r = numpy.random.random()/float(mating_pool_size) [F,S,P] = self.rankingEval() P_Sorted = num...
python
def SUSSelection(self, mating_pool_size): ''' Make Selection of the mating pool with the stochastic universal sampling algorithm ''' A = numpy.zeros(self.length) mating_pool = numpy.zeros(mating_pool_size) r = numpy.random.random()/float(mating_pool_size) [F,S,P] = self.rankingEval() P_Sorted = num...
[ "def", "SUSSelection", "(", "self", ",", "mating_pool_size", ")", ":", "A", "=", "numpy", ".", "zeros", "(", "self", ".", "length", ")", "mating_pool", "=", "numpy", ".", "zeros", "(", "mating_pool_size", ")", "r", "=", "numpy", ".", "random", ".", "ra...
Make Selection of the mating pool with the stochastic universal sampling algorithm
[ "Make", "Selection", "of", "the", "mating", "pool", "with", "the", "stochastic", "universal", "sampling", "algorithm" ]
train
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L459-L486
evuez/python-rescale
rescale/__init__.py
rescale
def rescale(img, size, mode=None): """ Rescale an image to given size, crop if mode specified * img: a PIL image object * size: a 2-tuple of (width, height); at least one must be specified * mode: CROP_TL keep the top left part, CROP_BR the bottom right part """ assert size[0] or size[1]...
python
def rescale(img, size, mode=None): """ Rescale an image to given size, crop if mode specified * img: a PIL image object * size: a 2-tuple of (width, height); at least one must be specified * mode: CROP_TL keep the top left part, CROP_BR the bottom right part """ assert size[0] or size[1]...
[ "def", "rescale", "(", "img", ",", "size", ",", "mode", "=", "None", ")", ":", "assert", "size", "[", "0", "]", "or", "size", "[", "1", "]", ",", "\"Must provide a width or a height\"", "size", "=", "list", "(", "size", ")", "crop", "=", "size", "[",...
Rescale an image to given size, crop if mode specified * img: a PIL image object * size: a 2-tuple of (width, height); at least one must be specified * mode: CROP_TL keep the top left part, CROP_BR the bottom right part
[ "Rescale", "an", "image", "to", "given", "size", "crop", "if", "mode", "specified", "*", "img", ":", "a", "PIL", "image", "object", "*", "size", ":", "a", "2", "-", "tuple", "of", "(", "width", "height", ")", ";", "at", "least", "one", "must", "be"...
train
https://github.com/evuez/python-rescale/blob/db6396a7542da72792ce6ce187469398f9074419/rescale/__init__.py#L13-L45
edeposit/edeposit.amqp.storage
src/edeposit/amqp/storage/structures/db/db_publication.py
DBPublication.from_comm
def from_comm(cls, pub): ''' Convert communication namedtuple to this class. Args: pub (obj): :class:`.Publication` instance which will be converted. Returns: obj: :class:`DBPublication` instance. ''' filename = None if pub.b64_data: ...
python
def from_comm(cls, pub): ''' Convert communication namedtuple to this class. Args: pub (obj): :class:`.Publication` instance which will be converted. Returns: obj: :class:`DBPublication` instance. ''' filename = None if pub.b64_data: ...
[ "def", "from_comm", "(", "cls", ",", "pub", ")", ":", "filename", "=", "None", "if", "pub", ".", "b64_data", ":", "filename", "=", "cls", ".", "_save_to_unique_filename", "(", "pub", ")", "return", "cls", "(", "title", "=", "pub", ".", "title", ",", ...
Convert communication namedtuple to this class. Args: pub (obj): :class:`.Publication` instance which will be converted. Returns: obj: :class:`DBPublication` instance.
[ "Convert", "communication", "namedtuple", "to", "this", "class", "." ]
train
https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/structures/db/db_publication.py#L94-L123
edeposit/edeposit.amqp.storage
src/edeposit/amqp/storage/structures/db/db_publication.py
DBPublication.to_comm
def to_comm(self, light_request=False): ''' Convert `self` to :class:`.Publication`. Returns: obj: :class:`.Publication` instance. ''' data = None if not light_request: data = read_as_base64(self.file_pointer) return Publication( ...
python
def to_comm(self, light_request=False): ''' Convert `self` to :class:`.Publication`. Returns: obj: :class:`.Publication` instance. ''' data = None if not light_request: data = read_as_base64(self.file_pointer) return Publication( ...
[ "def", "to_comm", "(", "self", ",", "light_request", "=", "False", ")", ":", "data", "=", "None", "if", "not", "light_request", ":", "data", "=", "read_as_base64", "(", "self", ".", "file_pointer", ")", "return", "Publication", "(", "title", "=", "self", ...
Convert `self` to :class:`.Publication`. Returns: obj: :class:`.Publication` instance.
[ "Convert", "self", "to", ":", "class", ":", ".", "Publication", "." ]
train
https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/structures/db/db_publication.py#L155-L183
sysr-q/rcmd.py
rcmd/__init__.py
Rcmd.loop
def loop(self, intro=None): """ TODO as heck. See Python's cmd.Cmd.cmdloop for some (somewhat horrifying) example loops - that's what we're working similarly to. """ self.fire("preloop") if intro is not None: self.intro = intro if self.intro is...
python
def loop(self, intro=None): """ TODO as heck. See Python's cmd.Cmd.cmdloop for some (somewhat horrifying) example loops - that's what we're working similarly to. """ self.fire("preloop") if intro is not None: self.intro = intro if self.intro is...
[ "def", "loop", "(", "self", ",", "intro", "=", "None", ")", ":", "self", ".", "fire", "(", "\"preloop\"", ")", "if", "intro", "is", "not", "None", ":", "self", ".", "intro", "=", "intro", "if", "self", ".", "intro", "is", "not", "None", ":", "sel...
TODO as heck. See Python's cmd.Cmd.cmdloop for some (somewhat horrifying) example loops - that's what we're working similarly to.
[ "TODO", "as", "heck", ".", "See", "Python", "s", "cmd", ".", "Cmd", ".", "cmdloop", "for", "some", "(", "somewhat", "horrifying", ")", "example", "loops", "-", "that", "s", "what", "we", "re", "working", "similarly", "to", "." ]
train
https://github.com/sysr-q/rcmd.py/blob/0ecce1970164805cedb33d02a9dcf9eb6cd14e0c/rcmd/__init__.py#L95-L124
dstufft/storages
storages/utils.py
get_valid_filename
def get_valid_filename(s): """ Returns the given string converted to a string that can be used for a clean filename. Specifically, leading and trailing spaces are removed; other spaces are converted to underscores; and anything that is not a unicode alphanumeric, dash, underscore, or dot, is removed...
python
def get_valid_filename(s): """ Returns the given string converted to a string that can be used for a clean filename. Specifically, leading and trailing spaces are removed; other spaces are converted to underscores; and anything that is not a unicode alphanumeric, dash, underscore, or dot, is removed...
[ "def", "get_valid_filename", "(", "s", ")", ":", "s", "=", "s", ".", "strip", "(", ")", ".", "replace", "(", "\" \"", ",", "\"_\"", ")", "return", "re", ".", "sub", "(", "r\"(?u)[^-\\w.]\"", ",", "\"\"", ",", "s", ")" ]
Returns the given string converted to a string that can be used for a clean filename. Specifically, leading and trailing spaces are removed; other spaces are converted to underscores; and anything that is not a unicode alphanumeric, dash, underscore, or dot, is removed. >>> get_valid_filename("john's po...
[ "Returns", "the", "given", "string", "converted", "to", "a", "string", "that", "can", "be", "used", "for", "a", "clean", "filename", ".", "Specifically", "leading", "and", "trailing", "spaces", "are", "removed", ";", "other", "spaces", "are", "converted", "t...
train
https://github.com/dstufft/storages/blob/0d893afc1db32cd83eaf8e2ad4ed51b37933d5f0/storages/utils.py#L15-L25
dstufft/storages
storages/utils.py
safe_join
def safe_join(base, *paths): """ Joins one or more path components to the base path component intelligently. Returns a normalized, absolute version of the final path. The final path must be located inside of the base path component (otherwise a ValueError is raised). """ base = base pat...
python
def safe_join(base, *paths): """ Joins one or more path components to the base path component intelligently. Returns a normalized, absolute version of the final path. The final path must be located inside of the base path component (otherwise a ValueError is raised). """ base = base pat...
[ "def", "safe_join", "(", "base", ",", "*", "paths", ")", ":", "base", "=", "base", "paths", "=", "[", "p", "for", "p", "in", "paths", "]", "final_path", "=", "abspath", "(", "os", ".", "path", ".", "join", "(", "base", ",", "*", "paths", ")", "...
Joins one or more path components to the base path component intelligently. Returns a normalized, absolute version of the final path. The final path must be located inside of the base path component (otherwise a ValueError is raised).
[ "Joins", "one", "or", "more", "path", "components", "to", "the", "base", "path", "component", "intelligently", ".", "Returns", "a", "normalized", "absolute", "version", "of", "the", "final", "path", "." ]
train
https://github.com/dstufft/storages/blob/0d893afc1db32cd83eaf8e2ad4ed51b37933d5f0/storages/utils.py#L48-L70
dstufft/storages
storages/utils.py
filepath_to_uri
def filepath_to_uri(path): """ Convert an file system path to a URI portion that is suitable for inclusion in a URL. We are assuming input is either UTF-8 or unicode already. This method will encode certain chars that would normally be recognized as special chars for URIs. Note that this meth...
python
def filepath_to_uri(path): """ Convert an file system path to a URI portion that is suitable for inclusion in a URL. We are assuming input is either UTF-8 or unicode already. This method will encode certain chars that would normally be recognized as special chars for URIs. Note that this meth...
[ "def", "filepath_to_uri", "(", "path", ")", ":", "if", "path", "is", "None", ":", "return", "path", "# I know about `os.sep` and `os.altsep` but I want to leave", "# some flexibility for hardcoding separators.", "return", "urllib", ".", "quote", "(", "path", ".", "replace...
Convert an file system path to a URI portion that is suitable for inclusion in a URL. We are assuming input is either UTF-8 or unicode already. This method will encode certain chars that would normally be recognized as special chars for URIs. Note that this method does not encode the ' character,...
[ "Convert", "an", "file", "system", "path", "to", "a", "URI", "portion", "that", "is", "suitable", "for", "inclusion", "in", "a", "URL", "." ]
train
https://github.com/dstufft/storages/blob/0d893afc1db32cd83eaf8e2ad4ed51b37933d5f0/storages/utils.py#L73-L92
hkff/FodtlMon
fodtlmon/dtl/systemd.py
Actor.run
def run(self, once=True): """ Run main monitor and all sub monitors :param : once :return: """ print("\n- Actor %s " % self.name) for m in self.submons: res = m.monitor(once=once) print(" | Submonitor %s : %s" % (self.name, res)) ...
python
def run(self, once=True): """ Run main monitor and all sub monitors :param : once :return: """ print("\n- Actor %s " % self.name) for m in self.submons: res = m.monitor(once=once) print(" | Submonitor %s : %s" % (self.name, res)) ...
[ "def", "run", "(", "self", ",", "once", "=", "True", ")", ":", "print", "(", "\"\\n- Actor %s \"", "%", "self", ".", "name", ")", "for", "m", "in", "self", ".", "submons", ":", "res", "=", "m", ".", "monitor", "(", "once", "=", "once", ")", "prin...
Run main monitor and all sub monitors :param : once :return:
[ "Run", "main", "monitor", "and", "all", "sub", "monitors", ":", "param", ":", "once", ":", "return", ":" ]
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/dtl/systemd.py#L93-L106
hkff/FodtlMon
fodtlmon/dtl/systemd.py
System.add_actors
def add_actors(self, actor): """ Add an actor / actor list to the system's actors :param actor: Actor | list<Actor> :return: self """ if isinstance(actor, list): self.actors.extend(actor) elif isinstance(actor, Actor): self.actors.append(ac...
python
def add_actors(self, actor): """ Add an actor / actor list to the system's actors :param actor: Actor | list<Actor> :return: self """ if isinstance(actor, list): self.actors.extend(actor) elif isinstance(actor, Actor): self.actors.append(ac...
[ "def", "add_actors", "(", "self", ",", "actor", ")", ":", "if", "isinstance", "(", "actor", ",", "list", ")", ":", "self", ".", "actors", ".", "extend", "(", "actor", ")", "elif", "isinstance", "(", "actor", ",", "Actor", ")", ":", "self", ".", "ac...
Add an actor / actor list to the system's actors :param actor: Actor | list<Actor> :return: self
[ "Add", "an", "actor", "/", "actor", "list", "to", "the", "system", "s", "actors", ":", "param", "actor", ":", "Actor", "|", "list<Actor", ">", ":", "return", ":", "self" ]
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/dtl/systemd.py#L137-L147
hkff/FodtlMon
fodtlmon/dtl/systemd.py
System.get_actor
def get_actor(self, name): """ Get an actor by name :param name: str :return: """ return next((x for x in self.actors if x.name == name), None)
python
def get_actor(self, name): """ Get an actor by name :param name: str :return: """ return next((x for x in self.actors if x.name == name), None)
[ "def", "get_actor", "(", "self", ",", "name", ")", ":", "return", "next", "(", "(", "x", "for", "x", "in", "self", ".", "actors", "if", "x", ".", "name", "==", "name", ")", ",", "None", ")" ]
Get an actor by name :param name: str :return:
[ "Get", "an", "actor", "by", "name", ":", "param", "name", ":", "str", ":", "return", ":" ]
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/dtl/systemd.py#L149-L155
hkff/FodtlMon
fodtlmon/dtl/systemd.py
System.generate_monitors
def generate_monitors(self): """ Generate monitors for each actor in the system :return: """ submons = [] for a in self.actors: # Get all remote formula remotes = a.formula.walk(filter_type=At) # Compute formula hash for f i...
python
def generate_monitors(self): """ Generate monitors for each actor in the system :return: """ submons = [] for a in self.actors: # Get all remote formula remotes = a.formula.walk(filter_type=At) # Compute formula hash for f i...
[ "def", "generate_monitors", "(", "self", ")", ":", "submons", "=", "[", "]", "for", "a", "in", "self", ".", "actors", ":", "# Get all remote formula", "remotes", "=", "a", ".", "formula", ".", "walk", "(", "filter_type", "=", "At", ")", "# Compute formula ...
Generate monitors for each actor in the system :return:
[ "Generate", "monitors", "for", "each", "actor", "in", "the", "system", ":", "return", ":" ]
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/dtl/systemd.py#L157-L191
hkff/FodtlMon
fodtlmon/dtl/systemd.py
System.run
def run(self, once=True): """ Run the system :param once :return: """ print(Color("{autored}\n====== System round %s ======{/red}" % self.turn)) print(Color("{autoblue}== Updating actors events...{/blue}")) # Handling OUT messages for a in self.act...
python
def run(self, once=True): """ Run the system :param once :return: """ print(Color("{autored}\n====== System round %s ======{/red}" % self.turn)) print(Color("{autoblue}== Updating actors events...{/blue}")) # Handling OUT messages for a in self.act...
[ "def", "run", "(", "self", ",", "once", "=", "True", ")", ":", "print", "(", "Color", "(", "\"{autored}\\n====== System round %s ======{/red}\"", "%", "self", ".", "turn", ")", ")", "print", "(", "Color", "(", "\"{autoblue}== Updating actors events...{/blue}\"", "...
Run the system :param once :return:
[ "Run", "the", "system", ":", "param", "once", ":", "return", ":" ]
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/dtl/systemd.py#L193-L234
hkff/FodtlMon
fodtlmon/dtl/systemd.py
System.parseJSON
def parseJSON(js): """ { kv_type : "", type : "", actors : <Actors list> [ { actorName : <String>, formula: <String>, events: ["->b", "b->"], tr...
python
def parseJSON(js): """ { kv_type : "", type : "", actors : <Actors list> [ { actorName : <String>, formula: <String>, events: ["->b", "b->"], tr...
[ "def", "parseJSON", "(", "js", ")", ":", "decoded", "=", "json", ".", "JSONDecoder", "(", ")", ".", "decode", "(", "js", ")", "actors", "=", "decoded", ".", "get", "(", "\"actors\"", ")", "if", "actors", "is", "None", ":", "raise", "Exception", "(", ...
{ kv_type : "", type : "", actors : <Actors list> [ { actorName : <String>, formula: <String>, events: ["->b", "b->"], trace: [], speed: 1,...
[ "{", "kv_type", ":", "type", ":", "actors", ":", "<Actors", "list", ">", "[", "{", "actorName", ":", "<String", ">", "formula", ":", "<String", ">", "events", ":", "[", "-", ">", "b", "b", "-", ">", "]", "trace", ":", "[]", "speed", ":", "1", "...
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/dtl/systemd.py#L246-L295
fmd/lazyconf
lazyconf/lazyconf.py
Lazyconf.data_file
def data_file(self): """ Gets the full path to the file in which to save/load configured data. """ path = os.getcwd() + '/' + self.lazy_folder return path + self.data_filename
python
def data_file(self): """ Gets the full path to the file in which to save/load configured data. """ path = os.getcwd() + '/' + self.lazy_folder return path + self.data_filename
[ "def", "data_file", "(", "self", ")", ":", "path", "=", "os", ".", "getcwd", "(", ")", "+", "'/'", "+", "self", ".", "lazy_folder", "return", "path", "+", "self", ".", "data_filename" ]
Gets the full path to the file in which to save/load configured data.
[ "Gets", "the", "full", "path", "to", "the", "file", "in", "which", "to", "save", "/", "load", "configured", "data", "." ]
train
https://github.com/fmd/lazyconf/blob/78e94320c7ff2c08988df04b4e43968f0a7ae06e/lazyconf/lazyconf.py#L19-L22
fmd/lazyconf
lazyconf/lazyconf.py
Lazyconf.schema_file
def schema_file(self): """ Gets the full path to the file in which to load configuration schema. """ path = os.getcwd() + '/' + self.lazy_folder return path + self.schema_filename
python
def schema_file(self): """ Gets the full path to the file in which to load configuration schema. """ path = os.getcwd() + '/' + self.lazy_folder return path + self.schema_filename
[ "def", "schema_file", "(", "self", ")", ":", "path", "=", "os", ".", "getcwd", "(", ")", "+", "'/'", "+", "self", ".", "lazy_folder", "return", "path", "+", "self", ".", "schema_filename" ]
Gets the full path to the file in which to load configuration schema.
[ "Gets", "the", "full", "path", "to", "the", "file", "in", "which", "to", "load", "configuration", "schema", "." ]
train
https://github.com/fmd/lazyconf/blob/78e94320c7ff2c08988df04b4e43968f0a7ae06e/lazyconf/lazyconf.py#L25-L28
fmd/lazyconf
lazyconf/lazyconf.py
Lazyconf.add_ignore
def add_ignore(self): """ Writes a .gitignore file to ignore the generated data file. """ path = self.lazy_folder + self.ignore_filename # If the file exists, return. if os.path.isfile(os.path.realpath(path)): return None sp, sf = os.path.split(self.data_fil...
python
def add_ignore(self): """ Writes a .gitignore file to ignore the generated data file. """ path = self.lazy_folder + self.ignore_filename # If the file exists, return. if os.path.isfile(os.path.realpath(path)): return None sp, sf = os.path.split(self.data_fil...
[ "def", "add_ignore", "(", "self", ")", ":", "path", "=", "self", ".", "lazy_folder", "+", "self", ".", "ignore_filename", "# If the file exists, return.", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "realpath", "(", "path", ")", ...
Writes a .gitignore file to ignore the generated data file.
[ "Writes", "a", ".", "gitignore", "file", "to", "ignore", "the", "generated", "data", "file", "." ]
train
https://github.com/fmd/lazyconf/blob/78e94320c7ff2c08988df04b4e43968f0a7ae06e/lazyconf/lazyconf.py#L35-L54
fmd/lazyconf
lazyconf/lazyconf.py
Lazyconf.choose_schema
def choose_schema(self, out_file): """ Finds all schema templates and prompts to choose one. Copies the file to self.lazy_folder. """ path = os.path.dirname(lazyconf.__file__) + '/schema/' self.prompt.header('Choose a template for your config file: ') i = 0 choices = [] ...
python
def choose_schema(self, out_file): """ Finds all schema templates and prompts to choose one. Copies the file to self.lazy_folder. """ path = os.path.dirname(lazyconf.__file__) + '/schema/' self.prompt.header('Choose a template for your config file: ') i = 0 choices = [] ...
[ "def", "choose_schema", "(", "self", ",", "out_file", ")", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "lazyconf", ".", "__file__", ")", "+", "'/schema/'", "self", ".", "prompt", ".", "header", "(", "'Choose a template for your config file: '", ...
Finds all schema templates and prompts to choose one. Copies the file to self.lazy_folder.
[ "Finds", "all", "schema", "templates", "and", "prompts", "to", "choose", "one", ".", "Copies", "the", "file", "to", "self", ".", "lazy_folder", "." ]
train
https://github.com/fmd/lazyconf/blob/78e94320c7ff2c08988df04b4e43968f0a7ae06e/lazyconf/lazyconf.py#L56-L97
fmd/lazyconf
lazyconf/lazyconf.py
Lazyconf.configure_data
def configure_data(self, data, key_string = ''): """ Goes through all the options in `data`, and prompts new values. This function calls itself recursively if it finds an inner dictionary. Arguments: data -- The dictionary to loop through. key_string -- The dot-...
python
def configure_data(self, data, key_string = ''): """ Goes through all the options in `data`, and prompts new values. This function calls itself recursively if it finds an inner dictionary. Arguments: data -- The dictionary to loop through. key_string -- The dot-...
[ "def", "configure_data", "(", "self", ",", "data", ",", "key_string", "=", "''", ")", ":", "# If there's no keys in this dictionary, we have nothing to do.", "if", "len", "(", "data", ".", "keys", "(", ")", ")", "==", "0", ":", "return", "# Split the key string by...
Goes through all the options in `data`, and prompts new values. This function calls itself recursively if it finds an inner dictionary. Arguments: data -- The dictionary to loop through. key_string -- The dot-notated key of the dictionary being checked through.
[ "Goes", "through", "all", "the", "options", "in", "data", "and", "prompts", "new", "values", ".", "This", "function", "calls", "itself", "recursively", "if", "it", "finds", "an", "inner", "dictionary", "." ]
train
https://github.com/fmd/lazyconf/blob/78e94320c7ff2c08988df04b4e43968f0a7ae06e/lazyconf/lazyconf.py#L99-L158
fmd/lazyconf
lazyconf/lazyconf.py
Lazyconf.configure
def configure(self): """ The main configure function. Uses a schema file and an optional data file, and combines them with user prompts to write a new data file. """ # Make the lazy folder if it doesn't already exist. path = os.getcwd() + '/' + self.lazy_folder if not os.pat...
python
def configure(self): """ The main configure function. Uses a schema file and an optional data file, and combines them with user prompts to write a new data file. """ # Make the lazy folder if it doesn't already exist. path = os.getcwd() + '/' + self.lazy_folder if not os.pat...
[ "def", "configure", "(", "self", ")", ":", "# Make the lazy folder if it doesn't already exist.", "path", "=", "os", ".", "getcwd", "(", ")", "+", "'/'", "+", "self", ".", "lazy_folder", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":",...
The main configure function. Uses a schema file and an optional data file, and combines them with user prompts to write a new data file.
[ "The", "main", "configure", "function", ".", "Uses", "a", "schema", "file", "and", "an", "optional", "data", "file", "and", "combines", "them", "with", "user", "prompts", "to", "write", "a", "new", "data", "file", "." ]
train
https://github.com/fmd/lazyconf/blob/78e94320c7ff2c08988df04b4e43968f0a7ae06e/lazyconf/lazyconf.py#L160-L234
fmd/lazyconf
lazyconf/lazyconf.py
Lazyconf.parse_value
def parse_value(self, inner_dict, label, key, value, default): """ Parses a single value and sets it in an inner dictionary. Arguments: inner_dict -- The dictionary containing the value to set label -- The label to show for the prompt. key -- The key ...
python
def parse_value(self, inner_dict, label, key, value, default): """ Parses a single value and sets it in an inner dictionary. Arguments: inner_dict -- The dictionary containing the value to set label -- The label to show for the prompt. key -- The key ...
[ "def", "parse_value", "(", "self", ",", "inner_dict", ",", "label", ",", "key", ",", "value", ",", "default", ")", ":", "t", "=", "type", "(", "default", ")", "if", "t", "is", "dict", ":", "return", "select", "=", "self", ".", "data", ".", "get_sel...
Parses a single value and sets it in an inner dictionary. Arguments: inner_dict -- The dictionary containing the value to set label -- The label to show for the prompt. key -- The key in the dictionary to set the value for. value -- The value...
[ "Parses", "a", "single", "value", "and", "sets", "it", "in", "an", "inner", "dictionary", "." ]
train
https://github.com/fmd/lazyconf/blob/78e94320c7ff2c08988df04b4e43968f0a7ae06e/lazyconf/lazyconf.py#L236-L271
fmd/lazyconf
lazyconf/lazyconf.py
Lazyconf.set
def set(self, key, value): """ Sets a single value in a preconfigured data file. Arguments: key -- The full dot-notated key to set the value for. value -- The value to set. """ d = self.data.data keys = key.split('.') latest = keys.pop() ...
python
def set(self, key, value): """ Sets a single value in a preconfigured data file. Arguments: key -- The full dot-notated key to set the value for. value -- The value to set. """ d = self.data.data keys = key.split('.') latest = keys.pop() ...
[ "def", "set", "(", "self", ",", "key", ",", "value", ")", ":", "d", "=", "self", ".", "data", ".", "data", "keys", "=", "key", ".", "split", "(", "'.'", ")", "latest", "=", "keys", ".", "pop", "(", ")", "for", "k", "in", "keys", ":", "d", "...
Sets a single value in a preconfigured data file. Arguments: key -- The full dot-notated key to set the value for. value -- The value to set.
[ "Sets", "a", "single", "value", "in", "a", "preconfigured", "data", "file", "." ]
train
https://github.com/fmd/lazyconf/blob/78e94320c7ff2c08988df04b4e43968f0a7ae06e/lazyconf/lazyconf.py#L273-L290
fmd/lazyconf
lazyconf/lazyconf.py
Lazyconf._load
def _load(self, data_file): """ Internal load function. Creates the object and returns it. Arguments: data_file -- The filename to load. """ # Load the data from a file. try: data = Schema().load(data_file) except (Exception, IOError, ValueErr...
python
def _load(self, data_file): """ Internal load function. Creates the object and returns it. Arguments: data_file -- The filename to load. """ # Load the data from a file. try: data = Schema().load(data_file) except (Exception, IOError, ValueErr...
[ "def", "_load", "(", "self", ",", "data_file", ")", ":", "# Load the data from a file.", "try", ":", "data", "=", "Schema", "(", ")", ".", "load", "(", "data_file", ")", "except", "(", "Exception", ",", "IOError", ",", "ValueError", ")", "as", "e", ":", ...
Internal load function. Creates the object and returns it. Arguments: data_file -- The filename to load.
[ "Internal", "load", "function", ".", "Creates", "the", "object", "and", "returns", "it", "." ]
train
https://github.com/fmd/lazyconf/blob/78e94320c7ff2c08988df04b4e43968f0a7ae06e/lazyconf/lazyconf.py#L301-L314
fmd/lazyconf
lazyconf/lazyconf.py
Lazyconf.load
def load(self, data_file = None): """ Loads a data file and sets it to self.data. Arguments: data_file -- The filename to load. """ if not data_file: data_file = '' elif data_file[-1] != '/': data_file += '/' if data_file[-6:] !=...
python
def load(self, data_file = None): """ Loads a data file and sets it to self.data. Arguments: data_file -- The filename to load. """ if not data_file: data_file = '' elif data_file[-1] != '/': data_file += '/' if data_file[-6:] !=...
[ "def", "load", "(", "self", ",", "data_file", "=", "None", ")", ":", "if", "not", "data_file", ":", "data_file", "=", "''", "elif", "data_file", "[", "-", "1", "]", "!=", "'/'", ":", "data_file", "+=", "'/'", "if", "data_file", "[", "-", "6", ":", ...
Loads a data file and sets it to self.data. Arguments: data_file -- The filename to load.
[ "Loads", "a", "data", "file", "and", "sets", "it", "to", "self", ".", "data", "." ]
train
https://github.com/fmd/lazyconf/blob/78e94320c7ff2c08988df04b4e43968f0a7ae06e/lazyconf/lazyconf.py#L317-L335
minhhoit/yacms
yacms/twitter/managers.py
TweetManager.get_for
def get_for(self, query_type, value): """ Create a query and run it for the given arg if it doesn't exist, and return the tweets for the query. """ from yacms.twitter.models import Query lookup = {"type": query_type, "value": value} query, created = Query.objects....
python
def get_for(self, query_type, value): """ Create a query and run it for the given arg if it doesn't exist, and return the tweets for the query. """ from yacms.twitter.models import Query lookup = {"type": query_type, "value": value} query, created = Query.objects....
[ "def", "get_for", "(", "self", ",", "query_type", ",", "value", ")", ":", "from", "yacms", ".", "twitter", ".", "models", "import", "Query", "lookup", "=", "{", "\"type\"", ":", "query_type", ",", "\"value\"", ":", "value", "}", "query", ",", "created", ...
Create a query and run it for the given arg if it doesn't exist, and return the tweets for the query.
[ "Create", "a", "query", "and", "run", "it", "for", "the", "given", "arg", "if", "it", "doesn", "t", "exist", "and", "return", "the", "tweets", "for", "the", "query", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/twitter/managers.py#L12-L25
jmgilman/Neolib
neolib/pyamf/adapters/_sqlalchemy_orm.py
SaMappedClassAlias.getEncodableAttributes
def getEncodableAttributes(self, obj, **kwargs): """ Returns a C{tuple} containing a dict of static and dynamic attributes for C{obj}. """ attrs = pyamf.ClassAlias.getEncodableAttributes(self, obj, **kwargs) if not self.exclude_sa_key: # primary_key_from_inst...
python
def getEncodableAttributes(self, obj, **kwargs): """ Returns a C{tuple} containing a dict of static and dynamic attributes for C{obj}. """ attrs = pyamf.ClassAlias.getEncodableAttributes(self, obj, **kwargs) if not self.exclude_sa_key: # primary_key_from_inst...
[ "def", "getEncodableAttributes", "(", "self", ",", "obj", ",", "*", "*", "kwargs", ")", ":", "attrs", "=", "pyamf", ".", "ClassAlias", ".", "getEncodableAttributes", "(", "self", ",", "obj", ",", "*", "*", "kwargs", ")", "if", "not", "self", ".", "excl...
Returns a C{tuple} containing a dict of static and dynamic attributes for C{obj}.
[ "Returns", "a", "C", "{", "tuple", "}", "containing", "a", "dict", "of", "static", "and", "dynamic", "attributes", "for", "C", "{", "obj", "}", "." ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/adapters/_sqlalchemy_orm.py#L62-L83
inspirehep/plotextractor
plotextractor/converter.py
untar
def untar(original_tarball, output_directory): """Untar given tarball file into directory. Here we decide if our file is actually a tarball, then we untar it and return a list of extracted files. :param: tarball (string): the name of the tar file from arXiv :param: output_directory (string): the d...
python
def untar(original_tarball, output_directory): """Untar given tarball file into directory. Here we decide if our file is actually a tarball, then we untar it and return a list of extracted files. :param: tarball (string): the name of the tar file from arXiv :param: output_directory (string): the d...
[ "def", "untar", "(", "original_tarball", ",", "output_directory", ")", ":", "if", "not", "tarfile", ".", "is_tarfile", "(", "original_tarball", ")", ":", "raise", "InvalidTarball", "tarball", "=", "tarfile", ".", "open", "(", "original_tarball", ")", "# set mtim...
Untar given tarball file into directory. Here we decide if our file is actually a tarball, then we untar it and return a list of extracted files. :param: tarball (string): the name of the tar file from arXiv :param: output_directory (string): the directory to untar in :return: list of absolute fi...
[ "Untar", "given", "tarball", "file", "into", "directory", "." ]
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/converter.py#L45-L79
inspirehep/plotextractor
plotextractor/converter.py
detect_images_and_tex
def detect_images_and_tex( file_list, allowed_image_types=('eps', 'png', 'ps', 'jpg', 'pdf'), timeout=20): """Detect from a list of files which are TeX or images. :param: file_list (list): list of absolute file paths :param: allowed_image_types (list): list of allows image formats ...
python
def detect_images_and_tex( file_list, allowed_image_types=('eps', 'png', 'ps', 'jpg', 'pdf'), timeout=20): """Detect from a list of files which are TeX or images. :param: file_list (list): list of absolute file paths :param: allowed_image_types (list): list of allows image formats ...
[ "def", "detect_images_and_tex", "(", "file_list", ",", "allowed_image_types", "=", "(", "'eps'", ",", "'png'", ",", "'ps'", ",", "'jpg'", ",", "'pdf'", ")", ",", "timeout", "=", "20", ")", ":", "tex_file_extension", "=", "'tex'", "image_list", "=", "[", "]...
Detect from a list of files which are TeX or images. :param: file_list (list): list of absolute file paths :param: allowed_image_types (list): list of allows image formats :param: timeout (int): the timeout value on shell commands. :return: (image_list, tex_file) (([string, string, ...], string)): ...
[ "Detect", "from", "a", "list", "of", "files", "which", "are", "TeX", "or", "images", "." ]
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/converter.py#L82-L126
inspirehep/plotextractor
plotextractor/converter.py
convert_images
def convert_images(image_list, image_format="png", timeout=20): """Convert images from list of images to given format, if needed. Figure out the types of the images that were extracted from the tarball and determine how to convert them into PNG. :param: image_list ([string, string, ...]): the list of ...
python
def convert_images(image_list, image_format="png", timeout=20): """Convert images from list of images to given format, if needed. Figure out the types of the images that were extracted from the tarball and determine how to convert them into PNG. :param: image_list ([string, string, ...]): the list of ...
[ "def", "convert_images", "(", "image_list", ",", "image_format", "=", "\"png\"", ",", "timeout", "=", "20", ")", ":", "png_output_contains", "=", "'PNG image'", "image_mapping", "=", "{", "}", "for", "image_file", "in", "image_list", ":", "if", "os", ".", "p...
Convert images from list of images to given format, if needed. Figure out the types of the images that were extracted from the tarball and determine how to convert them into PNG. :param: image_list ([string, string, ...]): the list of image files extracted from the tarball in step 1 :param: im...
[ "Convert", "images", "from", "list", "of", "images", "to", "given", "format", "if", "needed", "." ]
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/converter.py#L129-L171
inspirehep/plotextractor
plotextractor/converter.py
convert_image
def convert_image(from_file, to_file, image_format): """Convert an image to given format.""" with Image(filename=from_file) as original: with original.convert(image_format) as converted: converted.save(filename=to_file) return to_file
python
def convert_image(from_file, to_file, image_format): """Convert an image to given format.""" with Image(filename=from_file) as original: with original.convert(image_format) as converted: converted.save(filename=to_file) return to_file
[ "def", "convert_image", "(", "from_file", ",", "to_file", ",", "image_format", ")", ":", "with", "Image", "(", "filename", "=", "from_file", ")", "as", "original", ":", "with", "original", ".", "convert", "(", "image_format", ")", "as", "converted", ":", "...
Convert an image to given format.
[ "Convert", "an", "image", "to", "given", "format", "." ]
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/converter.py#L174-L179
inspirehep/plotextractor
plotextractor/converter.py
rotate_image
def rotate_image(filename, line, sdir, image_list): """Rotate a image. Given a filename and a line, figure out what it is that the author wanted to do wrt changing the rotation of the image and convert the file so that this rotation is reflected in its presentation. :param: filename (string): the ...
python
def rotate_image(filename, line, sdir, image_list): """Rotate a image. Given a filename and a line, figure out what it is that the author wanted to do wrt changing the rotation of the image and convert the file so that this rotation is reflected in its presentation. :param: filename (string): the ...
[ "def", "rotate_image", "(", "filename", ",", "line", ",", "sdir", ",", "image_list", ")", ":", "file_loc", "=", "get_image_location", "(", "filename", ",", "sdir", ",", "image_list", ")", "degrees", "=", "re", ".", "findall", "(", "'(angle=[-\\\\d]+|rotate=[-\...
Rotate a image. Given a filename and a line, figure out what it is that the author wanted to do wrt changing the rotation of the image and convert the file so that this rotation is reflected in its presentation. :param: filename (string): the name of the file as specified in the TeX :param: line (...
[ "Rotate", "a", "image", "." ]
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/converter.py#L182-L221
Othernet-Project/ndb-utils
ndb_utils/models.py
OwnershipMixin.get_by_owner
def get_by_owner(cls, owner): """ get all entities owned by specified owner """ return cls.query(cls.owner==cls._get_key(owner))
python
def get_by_owner(cls, owner): """ get all entities owned by specified owner """ return cls.query(cls.owner==cls._get_key(owner))
[ "def", "get_by_owner", "(", "cls", ",", "owner", ")", ":", "return", "cls", ".", "query", "(", "cls", ".", "owner", "==", "cls", ".", "_get_key", "(", "owner", ")", ")" ]
get all entities owned by specified owner
[ "get", "all", "entities", "owned", "by", "specified", "owner" ]
train
https://github.com/Othernet-Project/ndb-utils/blob/7804a5e305a4ed280742e22dad1dd10756cbe695/ndb_utils/models.py#L113-L115
Othernet-Project/ndb-utils
ndb_utils/models.py
ValidatingMixin.clean
def clean(self): """ Cleans the data and throws ValidationError on failure """ errors = {} cleaned = {} for name, validator in self.validate_schema.items(): val = getattr(self, name, None) try: cleaned[name] = validator.to_python(val) ...
python
def clean(self): """ Cleans the data and throws ValidationError on failure """ errors = {} cleaned = {} for name, validator in self.validate_schema.items(): val = getattr(self, name, None) try: cleaned[name] = validator.to_python(val) ...
[ "def", "clean", "(", "self", ")", ":", "errors", "=", "{", "}", "cleaned", "=", "{", "}", "for", "name", ",", "validator", "in", "self", ".", "validate_schema", ".", "items", "(", ")", ":", "val", "=", "getattr", "(", "self", ",", "name", ",", "N...
Cleans the data and throws ValidationError on failure
[ "Cleans", "the", "data", "and", "throws", "ValidationError", "on", "failure" ]
train
https://github.com/Othernet-Project/ndb-utils/blob/7804a5e305a4ed280742e22dad1dd10756cbe695/ndb_utils/models.py#L130-L144
calvinku96/labreporthelper
labreporthelper/bestfit/bestfit.py
BestFit.set_defaults
def set_defaults(self, **defaults): """ Add all keyword arguments to self.args args: **defaults: key and value represents dictionary key and value """ try: defaults_items = defaults.iteritems() except AttributeError: de...
python
def set_defaults(self, **defaults): """ Add all keyword arguments to self.args args: **defaults: key and value represents dictionary key and value """ try: defaults_items = defaults.iteritems() except AttributeError: de...
[ "def", "set_defaults", "(", "self", ",", "*", "*", "defaults", ")", ":", "try", ":", "defaults_items", "=", "defaults", ".", "iteritems", "(", ")", "except", "AttributeError", ":", "defaults_items", "=", "defaults", ".", "items", "(", ")", "for", "key", ...
Add all keyword arguments to self.args args: **defaults: key and value represents dictionary key and value
[ "Add", "all", "keyword", "arguments", "to", "self", ".", "args" ]
train
https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/bestfit/bestfit.py#L25-L39
calvinku96/labreporthelper
labreporthelper/bestfit/bestfit.py
BestFit.set_args
def set_args(self, **kwargs): """ Set more arguments to self.args args: **kwargs: key and value represents dictionary key and value """ try: kwargs_items = kwargs.iteritems() except AttributeError: kwargs_items = kwargs...
python
def set_args(self, **kwargs): """ Set more arguments to self.args args: **kwargs: key and value represents dictionary key and value """ try: kwargs_items = kwargs.iteritems() except AttributeError: kwargs_items = kwargs...
[ "def", "set_args", "(", "self", ",", "*", "*", "kwargs", ")", ":", "try", ":", "kwargs_items", "=", "kwargs", ".", "iteritems", "(", ")", "except", "AttributeError", ":", "kwargs_items", "=", "kwargs", ".", "items", "(", ")", "for", "key", ",", "val", ...
Set more arguments to self.args args: **kwargs: key and value represents dictionary key and value
[ "Set", "more", "arguments", "to", "self", ".", "args" ]
train
https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/bestfit/bestfit.py#L42-L55
calvinku96/labreporthelper
labreporthelper/bestfit/bestfit.py
BestFit.check_important_variables
def check_important_variables(self): """ Check all the variables needed are defined """ if len(self.important_variables - set(self.args.keys())): raise TypeError("Some important variables are not set")
python
def check_important_variables(self): """ Check all the variables needed are defined """ if len(self.important_variables - set(self.args.keys())): raise TypeError("Some important variables are not set")
[ "def", "check_important_variables", "(", "self", ")", ":", "if", "len", "(", "self", ".", "important_variables", "-", "set", "(", "self", ".", "args", ".", "keys", "(", ")", ")", ")", ":", "raise", "TypeError", "(", "\"Some important variables are not set\"", ...
Check all the variables needed are defined
[ "Check", "all", "the", "variables", "needed", "are", "defined" ]
train
https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/bestfit/bestfit.py#L57-L62
calvinku96/labreporthelper
labreporthelper/bestfit/bestfit.py
BestFit.get_bestfit_line
def get_bestfit_line(self, x_min=None, x_max=None, resolution=None): """ Method to get bestfit line using the defined self.bestfit_func method args: x_min: scalar, default=min(x) minimum x value of the line x_max: scalar, default=max(x) ...
python
def get_bestfit_line(self, x_min=None, x_max=None, resolution=None): """ Method to get bestfit line using the defined self.bestfit_func method args: x_min: scalar, default=min(x) minimum x value of the line x_max: scalar, default=max(x) ...
[ "def", "get_bestfit_line", "(", "self", ",", "x_min", "=", "None", ",", "x_max", "=", "None", ",", "resolution", "=", "None", ")", ":", "x", "=", "self", ".", "args", "[", "\"x\"", "]", "if", "x_min", "is", "None", ":", "x_min", "=", "min", "(", ...
Method to get bestfit line using the defined self.bestfit_func method args: x_min: scalar, default=min(x) minimum x value of the line x_max: scalar, default=max(x) maximum x value of the line resolution: int, default=1000 ...
[ "Method", "to", "get", "bestfit", "line", "using", "the", "defined", "self", ".", "bestfit_func", "method" ]
train
https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/bestfit/bestfit.py#L83-L106
calvinku96/labreporthelper
labreporthelper/bestfit/bestfit.py
BestFit.get_rmse
def get_rmse(self, data_x=None, data_y=None): """ Get Root Mean Square Error using self.bestfit_func args: x_min: scalar, default=min(x) minimum x value of the line x_max: scalar, default=max(x) maximum x value of the line ...
python
def get_rmse(self, data_x=None, data_y=None): """ Get Root Mean Square Error using self.bestfit_func args: x_min: scalar, default=min(x) minimum x value of the line x_max: scalar, default=max(x) maximum x value of the line ...
[ "def", "get_rmse", "(", "self", ",", "data_x", "=", "None", ",", "data_y", "=", "None", ")", ":", "if", "data_x", "is", "None", ":", "data_x", "=", "np", ".", "array", "(", "self", ".", "args", "[", "\"x\"", "]", ")", "if", "data_y", "is", "None"...
Get Root Mean Square Error using self.bestfit_func args: x_min: scalar, default=min(x) minimum x value of the line x_max: scalar, default=max(x) maximum x value of the line resolution: int, default=1000 how many steps b...
[ "Get", "Root", "Mean", "Square", "Error", "using", "self", ".", "bestfit_func" ]
train
https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/bestfit/bestfit.py#L108-L128
calvinku96/labreporthelper
labreporthelper/bestfit/bestfit.py
BestFit.get_mae
def get_mae(self, data_x=None, data_y=None): """ Get Mean Absolute Error using self.bestfit_func args: data_x: array_like, default=x x value used to determine rmse, used if only a section of x is to be calculated data_y: array_like...
python
def get_mae(self, data_x=None, data_y=None): """ Get Mean Absolute Error using self.bestfit_func args: data_x: array_like, default=x x value used to determine rmse, used if only a section of x is to be calculated data_y: array_like...
[ "def", "get_mae", "(", "self", ",", "data_x", "=", "None", ",", "data_y", "=", "None", ")", ":", "if", "data_x", "is", "None", ":", "data_x", "=", "np", ".", "array", "(", "self", ".", "args", "[", "\"x\"", "]", ")", "if", "data_y", "is", "None",...
Get Mean Absolute Error using self.bestfit_func args: data_x: array_like, default=x x value used to determine rmse, used if only a section of x is to be calculated data_y: array_like, default=y y value used to determine rmse, used ...
[ "Get", "Mean", "Absolute", "Error", "using", "self", ".", "bestfit_func" ]
train
https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/bestfit/bestfit.py#L130-L150
leonjza/filesmudge
filesmudge/smudge.py
_backup_bytes
def _backup_bytes(target, offset, length): """ Read bytes from one file and write it to a backup file with the .bytes_backup suffix """ click.echo('Backup {l} byes at position {offset} on file {file} to .bytes_backup'.format( l=length, offset=offset, file=target)) with open(targ...
python
def _backup_bytes(target, offset, length): """ Read bytes from one file and write it to a backup file with the .bytes_backup suffix """ click.echo('Backup {l} byes at position {offset} on file {file} to .bytes_backup'.format( l=length, offset=offset, file=target)) with open(targ...
[ "def", "_backup_bytes", "(", "target", ",", "offset", ",", "length", ")", ":", "click", ".", "echo", "(", "'Backup {l} byes at position {offset} on file {file} to .bytes_backup'", ".", "format", "(", "l", "=", "length", ",", "offset", "=", "offset", ",", "file", ...
Read bytes from one file and write it to a backup file with the .bytes_backup suffix
[ "Read", "bytes", "from", "one", "file", "and", "write", "it", "to", "a", "backup", "file", "with", "the", ".", "bytes_backup", "suffix" ]
train
https://github.com/leonjza/filesmudge/blob/ba519aa4df85751458faf68220964d3e2480b9fc/filesmudge/smudge.py#L68-L85
leonjza/filesmudge
filesmudge/smudge.py
_smudge_bytes
def _smudge_bytes(target, offset, magic_bytes): """ Write magic bytes to a file relative from offset """ click.echo('Writing {c} magic byes at position {offset} on file {file}'.format( c=len(magic_bytes), offset=offset, file=target)) with open(target, 'r+b') as f: f.seek...
python
def _smudge_bytes(target, offset, magic_bytes): """ Write magic bytes to a file relative from offset """ click.echo('Writing {c} magic byes at position {offset} on file {file}'.format( c=len(magic_bytes), offset=offset, file=target)) with open(target, 'r+b') as f: f.seek...
[ "def", "_smudge_bytes", "(", "target", ",", "offset", ",", "magic_bytes", ")", ":", "click", ".", "echo", "(", "'Writing {c} magic byes at position {offset} on file {file}'", ".", "format", "(", "c", "=", "len", "(", "magic_bytes", ")", ",", "offset", "=", "offs...
Write magic bytes to a file relative from offset
[ "Write", "magic", "bytes", "to", "a", "file", "relative", "from", "offset" ]
train
https://github.com/leonjza/filesmudge/blob/ba519aa4df85751458faf68220964d3e2480b9fc/filesmudge/smudge.py#L88-L101
leonjza/filesmudge
filesmudge/smudge.py
smudge
def smudge(newtype, target): """ Smudge magic bytes with a known type """ db = smudge_db.get() magic_bytes = db[newtype]['magic'] magic_offset = db[newtype]['offset'] _backup_bytes(target, magic_offset, len(magic_bytes)) _smudge_bytes(target, magic_offset, magic_bytes)
python
def smudge(newtype, target): """ Smudge magic bytes with a known type """ db = smudge_db.get() magic_bytes = db[newtype]['magic'] magic_offset = db[newtype]['offset'] _backup_bytes(target, magic_offset, len(magic_bytes)) _smudge_bytes(target, magic_offset, magic_bytes)
[ "def", "smudge", "(", "newtype", ",", "target", ")", ":", "db", "=", "smudge_db", ".", "get", "(", ")", "magic_bytes", "=", "db", "[", "newtype", "]", "[", "'magic'", "]", "magic_offset", "=", "db", "[", "newtype", "]", "[", "'offset'", "]", "_backup...
Smudge magic bytes with a known type
[ "Smudge", "magic", "bytes", "with", "a", "known", "type" ]
train
https://github.com/leonjza/filesmudge/blob/ba519aa4df85751458faf68220964d3e2480b9fc/filesmudge/smudge.py#L107-L118
leonjza/filesmudge
filesmudge/smudge.py
smudgeraw
def smudgeraw(target, offset, magicbytes): """ Smudge magic bytes with raw bytes """ magicbytes = magicbytes.replace('\\x', '').decode('hex') _backup_bytes(target, offset, len(magicbytes)) _smudge_bytes(target, offset, magicbytes)
python
def smudgeraw(target, offset, magicbytes): """ Smudge magic bytes with raw bytes """ magicbytes = magicbytes.replace('\\x', '').decode('hex') _backup_bytes(target, offset, len(magicbytes)) _smudge_bytes(target, offset, magicbytes)
[ "def", "smudgeraw", "(", "target", ",", "offset", ",", "magicbytes", ")", ":", "magicbytes", "=", "magicbytes", ".", "replace", "(", "'\\\\x'", ",", "''", ")", ".", "decode", "(", "'hex'", ")", "_backup_bytes", "(", "target", ",", "offset", ",", "len", ...
Smudge magic bytes with raw bytes
[ "Smudge", "magic", "bytes", "with", "raw", "bytes" ]
train
https://github.com/leonjza/filesmudge/blob/ba519aa4df85751458faf68220964d3e2480b9fc/filesmudge/smudge.py#L125-L132
leonjza/filesmudge
filesmudge/smudge.py
restore
def restore(source, offset): """ Restore a smudged file from .bytes_backup """ backup_location = os.path.join( os.path.dirname(os.path.abspath(source)), source + '.bytes_backup') click.echo('Reading backup from: {location}'.format(location=backup_location)) if not os.path.isfile(bac...
python
def restore(source, offset): """ Restore a smudged file from .bytes_backup """ backup_location = os.path.join( os.path.dirname(os.path.abspath(source)), source + '.bytes_backup') click.echo('Reading backup from: {location}'.format(location=backup_location)) if not os.path.isfile(bac...
[ "def", "restore", "(", "source", ",", "offset", ")", ":", "backup_location", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "source", ")", ")", ",", "source", "+", "'.bytes_...
Restore a smudged file from .bytes_backup
[ "Restore", "a", "smudged", "file", "from", ".", "bytes_backup" ]
train
https://github.com/leonjza/filesmudge/blob/ba519aa4df85751458faf68220964d3e2480b9fc/filesmudge/smudge.py#L138-L159
leonjza/filesmudge
filesmudge/smudge.py
available
def available(): """ List available types for 'smudge' """ db = smudge_db.get() click.echo('{:<6} {:<6} {:<50}'.format('Type', 'Offset', 'Magic')) for k, v in db.items(): click.echo('{type:<6} {offset:<6} {magic}'.format( type=k, magic=v['magic'].encode('hex'), offset=v...
python
def available(): """ List available types for 'smudge' """ db = smudge_db.get() click.echo('{:<6} {:<6} {:<50}'.format('Type', 'Offset', 'Magic')) for k, v in db.items(): click.echo('{type:<6} {offset:<6} {magic}'.format( type=k, magic=v['magic'].encode('hex'), offset=v...
[ "def", "available", "(", ")", ":", "db", "=", "smudge_db", ".", "get", "(", ")", "click", ".", "echo", "(", "'{:<6} {:<6} {:<50}'", ".", "format", "(", "'Type'", ",", "'Offset'", ",", "'Magic'", ")", ")", "for", "k", ",", "v", "in", "db", ".", "ite...
List available types for 'smudge'
[ "List", "available", "types", "for", "smudge" ]
train
https://github.com/leonjza/filesmudge/blob/ba519aa4df85751458faf68220964d3e2480b9fc/filesmudge/smudge.py#L163-L173
ktdreyer/txproductpages
txproductpages/connection.py
Connection.upcoming_releases
def upcoming_releases(self, product): """ Get upcoming releases for this product. Specifically we search for releases with a GA date greater-than or equal to today's date. :param product: str, eg. "ceph" :returns: deferred that when fired returns a list of Munch (dict-l...
python
def upcoming_releases(self, product): """ Get upcoming releases for this product. Specifically we search for releases with a GA date greater-than or equal to today's date. :param product: str, eg. "ceph" :returns: deferred that when fired returns a list of Munch (dict-l...
[ "def", "upcoming_releases", "(", "self", ",", "product", ")", ":", "url", "=", "'api/v6/releases/'", "url", "=", "url", "+", "'?product__shortname='", "+", "product", "url", "=", "url", "+", "'&ga_date__gte='", "+", "date", ".", "today", "(", ")", ".", "st...
Get upcoming releases for this product. Specifically we search for releases with a GA date greater-than or equal to today's date. :param product: str, eg. "ceph" :returns: deferred that when fired returns a list of Munch (dict-like) objects representing all releases, ...
[ "Get", "upcoming", "releases", "for", "this", "product", "." ]
train
https://github.com/ktdreyer/txproductpages/blob/96c85c498c0eef1d37cddb031db32e8b885fcbd9/txproductpages/connection.py#L26-L43
ktdreyer/txproductpages
txproductpages/connection.py
Connection.newest_release
def newest_release(self, product): """ Get the shortname of the newest upcoming release for a product. :param product: str, eg. "ceph" :returns: deferred that when fired returns the shortname of the newest release. """ releases = yield self.upcoming_rel...
python
def newest_release(self, product): """ Get the shortname of the newest upcoming release for a product. :param product: str, eg. "ceph" :returns: deferred that when fired returns the shortname of the newest release. """ releases = yield self.upcoming_rel...
[ "def", "newest_release", "(", "self", ",", "product", ")", ":", "releases", "=", "yield", "self", ".", "upcoming_releases", "(", "product", ")", "if", "not", "releases", ":", "raise", "ProductPagesException", "(", "'no upcoming releases'", ")", "defer", ".", "...
Get the shortname of the newest upcoming release for a product. :param product: str, eg. "ceph" :returns: deferred that when fired returns the shortname of the newest release.
[ "Get", "the", "shortname", "of", "the", "newest", "upcoming", "release", "for", "a", "product", "." ]
train
https://github.com/ktdreyer/txproductpages/blob/96c85c498c0eef1d37cddb031db32e8b885fcbd9/txproductpages/connection.py#L46-L57
ktdreyer/txproductpages
txproductpages/connection.py
Connection.product_url
def product_url(self, product): """ Return a human-friendly URL for this product. :param product: str, eg. "ceph" :returns: str, URL """ url = 'product/%s' % product return posixpath.join(self.url, url)
python
def product_url(self, product): """ Return a human-friendly URL for this product. :param product: str, eg. "ceph" :returns: str, URL """ url = 'product/%s' % product return posixpath.join(self.url, url)
[ "def", "product_url", "(", "self", ",", "product", ")", ":", "url", "=", "'product/%s'", "%", "product", "return", "posixpath", ".", "join", "(", "self", ".", "url", ",", "url", ")" ]
Return a human-friendly URL for this product. :param product: str, eg. "ceph" :returns: str, URL
[ "Return", "a", "human", "-", "friendly", "URL", "for", "this", "product", "." ]
train
https://github.com/ktdreyer/txproductpages/blob/96c85c498c0eef1d37cddb031db32e8b885fcbd9/txproductpages/connection.py#L59-L67
ktdreyer/txproductpages
txproductpages/connection.py
Connection.release
def release(self, shortname): """ Get a specific release by its shortname. :param shortname: str, eg. "ceph-3-0" :returns: deferred that when fired returns a Release (Munch, dict-like) object representing this release. :raises: ReleaseNotFoundException if this ...
python
def release(self, shortname): """ Get a specific release by its shortname. :param shortname: str, eg. "ceph-3-0" :returns: deferred that when fired returns a Release (Munch, dict-like) object representing this release. :raises: ReleaseNotFoundException if this ...
[ "def", "release", "(", "self", ",", "shortname", ")", ":", "url", "=", "'api/v6/releases/?shortname=%s'", "%", "shortname", "releases", "=", "yield", "self", ".", "_get", "(", "url", ")", "# Note, even if this shortname does not exist, _get() will not errback", "# for t...
Get a specific release by its shortname. :param shortname: str, eg. "ceph-3-0" :returns: deferred that when fired returns a Release (Munch, dict-like) object representing this release. :raises: ReleaseNotFoundException if this release does not exist.
[ "Get", "a", "specific", "release", "by", "its", "shortname", "." ]
train
https://github.com/ktdreyer/txproductpages/blob/96c85c498c0eef1d37cddb031db32e8b885fcbd9/txproductpages/connection.py#L70-L87
ktdreyer/txproductpages
txproductpages/connection.py
Connection.schedule_url
def schedule_url(self, release): """ Return a human-friendly URL for this release. :param release: str, release shortname eg. "ceph-3-0" :returns: str, URL """ product, _ = release.split('-', 1) url = 'product/%s/release/%s/schedule/tasks' % (product, release) ...
python
def schedule_url(self, release): """ Return a human-friendly URL for this release. :param release: str, release shortname eg. "ceph-3-0" :returns: str, URL """ product, _ = release.split('-', 1) url = 'product/%s/release/%s/schedule/tasks' % (product, release) ...
[ "def", "schedule_url", "(", "self", ",", "release", ")", ":", "product", ",", "_", "=", "release", ".", "split", "(", "'-'", ",", "1", ")", "url", "=", "'product/%s/release/%s/schedule/tasks'", "%", "(", "product", ",", "release", ")", "return", "posixpath...
Return a human-friendly URL for this release. :param release: str, release shortname eg. "ceph-3-0" :returns: str, URL
[ "Return", "a", "human", "-", "friendly", "URL", "for", "this", "release", "." ]
train
https://github.com/ktdreyer/txproductpages/blob/96c85c498c0eef1d37cddb031db32e8b885fcbd9/txproductpages/connection.py#L89-L98
ktdreyer/txproductpages
txproductpages/connection.py
Connection._get
def _get(self, url, headers={}): """ Get a JSON API endpoint and return the parsed data. :param url: str, *relative* URL (relative to pp-admin/ api endpoint) :param headers: dict (optional) :returns: deferred that when fired returns the parsed data from JSON or errback...
python
def _get(self, url, headers={}): """ Get a JSON API endpoint and return the parsed data. :param url: str, *relative* URL (relative to pp-admin/ api endpoint) :param headers: dict (optional) :returns: deferred that when fired returns the parsed data from JSON or errback...
[ "def", "_get", "(", "self", ",", "url", ",", "headers", "=", "{", "}", ")", ":", "# print('getting %s' % url)", "headers", "=", "headers", ".", "copy", "(", ")", "headers", "[", "'Accept'", "]", "=", "'application/json'", "url", "=", "posixpath", ".", "j...
Get a JSON API endpoint and return the parsed data. :param url: str, *relative* URL (relative to pp-admin/ api endpoint) :param headers: dict (optional) :returns: deferred that when fired returns the parsed data from JSON or errbacks with ProductPagesException
[ "Get", "a", "JSON", "API", "endpoint", "and", "return", "the", "parsed", "data", "." ]
train
https://github.com/ktdreyer/txproductpages/blob/96c85c498c0eef1d37cddb031db32e8b885fcbd9/txproductpages/connection.py#L101-L126
jmgilman/Neolib
neolib/pyamf/util/__init__.py
get_timestamp
def get_timestamp(d): """ Returns a UTC timestamp for a C{datetime.datetime} object. @type d: C{datetime.datetime} @return: UTC timestamp. @rtype: C{float} @see: Inspiration taken from the U{Intertwingly blog <http://intertwingly.net/blog/2007/09/02/Dealing-With-Dates>}. """ if ...
python
def get_timestamp(d): """ Returns a UTC timestamp for a C{datetime.datetime} object. @type d: C{datetime.datetime} @return: UTC timestamp. @rtype: C{float} @see: Inspiration taken from the U{Intertwingly blog <http://intertwingly.net/blog/2007/09/02/Dealing-With-Dates>}. """ if ...
[ "def", "get_timestamp", "(", "d", ")", ":", "if", "isinstance", "(", "d", ",", "datetime", ".", "date", ")", "and", "not", "isinstance", "(", "d", ",", "datetime", ".", "datetime", ")", ":", "d", "=", "datetime", ".", "datetime", ".", "combine", "(",...
Returns a UTC timestamp for a C{datetime.datetime} object. @type d: C{datetime.datetime} @return: UTC timestamp. @rtype: C{float} @see: Inspiration taken from the U{Intertwingly blog <http://intertwingly.net/blog/2007/09/02/Dealing-With-Dates>}.
[ "Returns", "a", "UTC", "timestamp", "for", "a", "C", "{", "datetime", ".", "datetime", "}", "object", "." ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/__init__.py#L28-L43
jmgilman/Neolib
neolib/pyamf/util/__init__.py
get_datetime
def get_datetime(secs): """ Return a UTC date from a timestamp. @type secs: C{long} @param secs: Seconds since 1970. @return: UTC timestamp. @rtype: C{datetime.datetime} """ if negative_timestamp_broken and secs < 0: return datetime.datetime(1970, 1, 1) + datetime.timedelta(seco...
python
def get_datetime(secs): """ Return a UTC date from a timestamp. @type secs: C{long} @param secs: Seconds since 1970. @return: UTC timestamp. @rtype: C{datetime.datetime} """ if negative_timestamp_broken and secs < 0: return datetime.datetime(1970, 1, 1) + datetime.timedelta(seco...
[ "def", "get_datetime", "(", "secs", ")", ":", "if", "negative_timestamp_broken", "and", "secs", "<", "0", ":", "return", "datetime", ".", "datetime", "(", "1970", ",", "1", ",", "1", ")", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "secs", ...
Return a UTC date from a timestamp. @type secs: C{long} @param secs: Seconds since 1970. @return: UTC timestamp. @rtype: C{datetime.datetime}
[ "Return", "a", "UTC", "date", "from", "a", "timestamp", "." ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/__init__.py#L46-L58
jmgilman/Neolib
neolib/pyamf/util/__init__.py
get_properties
def get_properties(obj): """ Returns a list of properties for L{obj} @since: 0.5 """ if hasattr(obj, 'keys'): return obj.keys() elif hasattr(obj, '__dict__'): return obj.__dict__.keys() return []
python
def get_properties(obj): """ Returns a list of properties for L{obj} @since: 0.5 """ if hasattr(obj, 'keys'): return obj.keys() elif hasattr(obj, '__dict__'): return obj.__dict__.keys() return []
[ "def", "get_properties", "(", "obj", ")", ":", "if", "hasattr", "(", "obj", ",", "'keys'", ")", ":", "return", "obj", ".", "keys", "(", ")", "elif", "hasattr", "(", "obj", ",", "'__dict__'", ")", ":", "return", "obj", ".", "__dict__", ".", "keys", ...
Returns a list of properties for L{obj} @since: 0.5
[ "Returns", "a", "list", "of", "properties", "for", "L", "{", "obj", "}" ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/__init__.py#L61-L72
jmgilman/Neolib
neolib/pyamf/util/__init__.py
set_attrs
def set_attrs(obj, attrs): """ Applies a collection of attributes C{attrs} to object C{obj} in the most generic way possible. @param obj: An instance implementing C{__setattr__}, or C{__setitem__} @param attrs: A collection implementing the C{iteritems} function @type attrs: Usually a dict ...
python
def set_attrs(obj, attrs): """ Applies a collection of attributes C{attrs} to object C{obj} in the most generic way possible. @param obj: An instance implementing C{__setattr__}, or C{__setitem__} @param attrs: A collection implementing the C{iteritems} function @type attrs: Usually a dict ...
[ "def", "set_attrs", "(", "obj", ",", "attrs", ")", ":", "o", "=", "setattr", "if", "hasattr", "(", "obj", ",", "'__setitem__'", ")", ":", "o", "=", "type", "(", "obj", ")", ".", "__setitem__", "[", "o", "(", "obj", ",", "k", ",", "v", ")", "for...
Applies a collection of attributes C{attrs} to object C{obj} in the most generic way possible. @param obj: An instance implementing C{__setattr__}, or C{__setitem__} @param attrs: A collection implementing the C{iteritems} function @type attrs: Usually a dict
[ "Applies", "a", "collection", "of", "attributes", "C", "{", "attrs", "}", "to", "object", "C", "{", "obj", "}", "in", "the", "most", "generic", "way", "possible", "." ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/__init__.py#L75-L89
jmgilman/Neolib
neolib/pyamf/util/__init__.py
get_class_alias
def get_class_alias(klass): """ Tries to find a suitable L{pyamf.ClassAlias} subclass for C{klass}. """ for k, v in pyamf.ALIAS_TYPES.iteritems(): for kl in v: try: if issubclass(klass, kl): return k except TypeError: # ...
python
def get_class_alias(klass): """ Tries to find a suitable L{pyamf.ClassAlias} subclass for C{klass}. """ for k, v in pyamf.ALIAS_TYPES.iteritems(): for kl in v: try: if issubclass(klass, kl): return k except TypeError: # ...
[ "def", "get_class_alias", "(", "klass", ")", ":", "for", "k", ",", "v", "in", "pyamf", ".", "ALIAS_TYPES", ".", "iteritems", "(", ")", ":", "for", "kl", "in", "v", ":", "try", ":", "if", "issubclass", "(", "klass", ",", "kl", ")", ":", "return", ...
Tries to find a suitable L{pyamf.ClassAlias} subclass for C{klass}.
[ "Tries", "to", "find", "a", "suitable", "L", "{", "pyamf", ".", "ClassAlias", "}", "subclass", "for", "C", "{", "klass", "}", "." ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/__init__.py#L92-L105
jmgilman/Neolib
neolib/pyamf/util/__init__.py
is_class_sealed
def is_class_sealed(klass): """ Whether or not the supplied class can accept dynamic properties. @rtype: C{bool} @since: 0.5 """ mro = inspect.getmro(klass) new = False if mro[-1] is object: mro = mro[:-1] new = True for kls in mro: if new and '__dict__' in...
python
def is_class_sealed(klass): """ Whether or not the supplied class can accept dynamic properties. @rtype: C{bool} @since: 0.5 """ mro = inspect.getmro(klass) new = False if mro[-1] is object: mro = mro[:-1] new = True for kls in mro: if new and '__dict__' in...
[ "def", "is_class_sealed", "(", "klass", ")", ":", "mro", "=", "inspect", ".", "getmro", "(", "klass", ")", "new", "=", "False", "if", "mro", "[", "-", "1", "]", "is", "object", ":", "mro", "=", "mro", "[", ":", "-", "1", "]", "new", "=", "True"...
Whether or not the supplied class can accept dynamic properties. @rtype: C{bool} @since: 0.5
[ "Whether", "or", "not", "the", "supplied", "class", "can", "accept", "dynamic", "properties", "." ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/__init__.py#L108-L129
jmgilman/Neolib
neolib/pyamf/util/__init__.py
get_class_meta
def get_class_meta(klass): """ Returns a C{dict} containing meta data based on the supplied class, useful for class aliasing. @rtype: C{dict} @since: 0.5 """ if not isinstance(klass, python.class_types) or klass is object: raise TypeError('klass must be a class object, got %r' % typ...
python
def get_class_meta(klass): """ Returns a C{dict} containing meta data based on the supplied class, useful for class aliasing. @rtype: C{dict} @since: 0.5 """ if not isinstance(klass, python.class_types) or klass is object: raise TypeError('klass must be a class object, got %r' % typ...
[ "def", "get_class_meta", "(", "klass", ")", ":", "if", "not", "isinstance", "(", "klass", ",", "python", ".", "class_types", ")", "or", "klass", "is", "object", ":", "raise", "TypeError", "(", "'klass must be a class object, got %r'", "%", "type", "(", "klass"...
Returns a C{dict} containing meta data based on the supplied class, useful for class aliasing. @rtype: C{dict} @since: 0.5
[ "Returns", "a", "C", "{", "dict", "}", "containing", "meta", "data", "based", "on", "the", "supplied", "class", "useful", "for", "class", "aliasing", "." ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/__init__.py#L132-L175
jmgilman/Neolib
neolib/pyamf/util/__init__.py
get_module
def get_module(mod_name): """ Load and return a module based on C{mod_name}. """ if mod_name is '': raise ImportError('Unable to import empty module') mod = __import__(mod_name) components = mod_name.split('.') for comp in components[1:]: mod = getattr(mod, comp) retur...
python
def get_module(mod_name): """ Load and return a module based on C{mod_name}. """ if mod_name is '': raise ImportError('Unable to import empty module') mod = __import__(mod_name) components = mod_name.split('.') for comp in components[1:]: mod = getattr(mod, comp) retur...
[ "def", "get_module", "(", "mod_name", ")", ":", "if", "mod_name", "is", "''", ":", "raise", "ImportError", "(", "'Unable to import empty module'", ")", "mod", "=", "__import__", "(", "mod_name", ")", "components", "=", "mod_name", ".", "split", "(", "'.'", "...
Load and return a module based on C{mod_name}.
[ "Load", "and", "return", "a", "module", "based", "on", "C", "{", "mod_name", "}", "." ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/__init__.py#L178-L191
nathforge/pydentifier
src/pydentifier/__init__.py
lower_underscore
def lower_underscore(string, prefix='', suffix=''): """ Generate an underscore-separated lower-case identifier, given English text, a prefix, and an optional suffix. Useful for function names and variable names. `prefix` can be set to `''`, though be careful - without a prefix, the function wi...
python
def lower_underscore(string, prefix='', suffix=''): """ Generate an underscore-separated lower-case identifier, given English text, a prefix, and an optional suffix. Useful for function names and variable names. `prefix` can be set to `''`, though be careful - without a prefix, the function wi...
[ "def", "lower_underscore", "(", "string", ",", "prefix", "=", "''", ",", "suffix", "=", "''", ")", ":", "return", "require_valid", "(", "append_underscore_if_keyword", "(", "'_'", ".", "join", "(", "word", ".", "lower", "(", ")", "for", "word", "in", "en...
Generate an underscore-separated lower-case identifier, given English text, a prefix, and an optional suffix. Useful for function names and variable names. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when your string starts with a ...
[ "Generate", "an", "underscore", "-", "separated", "lower", "-", "case", "identifier", "given", "English", "text", "a", "prefix", "and", "an", "optional", "suffix", "." ]
train
https://github.com/nathforge/pydentifier/blob/b8d27076254c65cfd7893c1401e2a198abd6afb4/src/pydentifier/__init__.py#L11-L30
nathforge/pydentifier
src/pydentifier/__init__.py
upper_underscore
def upper_underscore(string, prefix='', suffix=''): """ Generate an underscore-separated upper-case identifier. Useful for constants. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when...
python
def upper_underscore(string, prefix='', suffix=''): """ Generate an underscore-separated upper-case identifier. Useful for constants. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when...
[ "def", "upper_underscore", "(", "string", ",", "prefix", "=", "''", ",", "suffix", "=", "''", ")", ":", "return", "require_valid", "(", "append_underscore_if_keyword", "(", "'_'", ".", "join", "(", "word", ".", "upper", "(", ")", "for", "word", "in", "en...
Generate an underscore-separated upper-case identifier. Useful for constants. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when your string starts with a number. Example: >>>...
[ "Generate", "an", "underscore", "-", "separated", "upper", "-", "case", "identifier", ".", "Useful", "for", "constants", "." ]
train
https://github.com/nathforge/pydentifier/blob/b8d27076254c65cfd7893c1401e2a198abd6afb4/src/pydentifier/__init__.py#L32-L51
nathforge/pydentifier
src/pydentifier/__init__.py
upper_camel
def upper_camel(string, prefix='', suffix=''): """ Generate a camel-case identifier with the first word capitalised. Useful for class names. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifie...
python
def upper_camel(string, prefix='', suffix=''): """ Generate a camel-case identifier with the first word capitalised. Useful for class names. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifie...
[ "def", "upper_camel", "(", "string", ",", "prefix", "=", "''", ",", "suffix", "=", "''", ")", ":", "return", "require_valid", "(", "append_underscore_if_keyword", "(", "''", ".", "join", "(", "upper_case_first_char", "(", "word", ")", "for", "word", "in", ...
Generate a camel-case identifier with the first word capitalised. Useful for class names. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when your string starts with a number. Example:...
[ "Generate", "a", "camel", "-", "case", "identifier", "with", "the", "first", "word", "capitalised", ".", "Useful", "for", "class", "names", "." ]
train
https://github.com/nathforge/pydentifier/blob/b8d27076254c65cfd7893c1401e2a198abd6afb4/src/pydentifier/__init__.py#L53-L72
nathforge/pydentifier
src/pydentifier/__init__.py
lower_camel
def lower_camel(string, prefix='', suffix=''): """ Generate a camel-case identifier. Useful for unit test methods. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when your string starts...
python
def lower_camel(string, prefix='', suffix=''): """ Generate a camel-case identifier. Useful for unit test methods. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when your string starts...
[ "def", "lower_camel", "(", "string", ",", "prefix", "=", "''", ",", "suffix", "=", "''", ")", ":", "return", "require_valid", "(", "append_underscore_if_keyword", "(", "''", ".", "join", "(", "word", ".", "lower", "(", ")", "if", "index", "==", "0", "e...
Generate a camel-case identifier. Useful for unit test methods. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when your string starts with a number. Example: >>> lower_camel("...
[ "Generate", "a", "camel", "-", "case", "identifier", ".", "Useful", "for", "unit", "test", "methods", "." ]
train
https://github.com/nathforge/pydentifier/blob/b8d27076254c65cfd7893c1401e2a198abd6afb4/src/pydentifier/__init__.py#L74-L93
nathforge/pydentifier
src/pydentifier/__init__.py
is_valid
def is_valid(identifier): """ If the identifier is valid for Python, return True, otherwise False. """ return ( isinstance(identifier, six.string_types) and bool(NAME_RE.search(identifier)) and not keyword.iskeyword(identifier) )
python
def is_valid(identifier): """ If the identifier is valid for Python, return True, otherwise False. """ return ( isinstance(identifier, six.string_types) and bool(NAME_RE.search(identifier)) and not keyword.iskeyword(identifier) )
[ "def", "is_valid", "(", "identifier", ")", ":", "return", "(", "isinstance", "(", "identifier", ",", "six", ".", "string_types", ")", "and", "bool", "(", "NAME_RE", ".", "search", "(", "identifier", ")", ")", "and", "not", "keyword", ".", "iskeyword", "(...
If the identifier is valid for Python, return True, otherwise False.
[ "If", "the", "identifier", "is", "valid", "for", "Python", "return", "True", "otherwise", "False", "." ]
train
https://github.com/nathforge/pydentifier/blob/b8d27076254c65cfd7893c1401e2a198abd6afb4/src/pydentifier/__init__.py#L106-L115
20c/xbahn
xbahn/connection/__init__.py
receiver
def receiver(url, **kwargs): """ Return receiver instance from connection url string url <str> connection url eg. 'tcp://0.0.0.0:8080' """ res = url_to_resources(url) fnc = res["receiver"] return fnc(res.get("url"), **kwargs)
python
def receiver(url, **kwargs): """ Return receiver instance from connection url string url <str> connection url eg. 'tcp://0.0.0.0:8080' """ res = url_to_resources(url) fnc = res["receiver"] return fnc(res.get("url"), **kwargs)
[ "def", "receiver", "(", "url", ",", "*", "*", "kwargs", ")", ":", "res", "=", "url_to_resources", "(", "url", ")", "fnc", "=", "res", "[", "\"receiver\"", "]", "return", "fnc", "(", "res", ".", "get", "(", "\"url\"", ")", ",", "*", "*", "kwargs", ...
Return receiver instance from connection url string url <str> connection url eg. 'tcp://0.0.0.0:8080'
[ "Return", "receiver", "instance", "from", "connection", "url", "string" ]
train
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/connection/__init__.py#L289-L297
20c/xbahn
xbahn/connection/__init__.py
sender
def sender(url, **kwargs): """ Return sender instance from connection url string url <str> connection url eg. 'tcp://0.0.0.0:8080' """ res = url_to_resources(url) fnc = res["sender"] return fnc(res.get("url"), **kwargs)
python
def sender(url, **kwargs): """ Return sender instance from connection url string url <str> connection url eg. 'tcp://0.0.0.0:8080' """ res = url_to_resources(url) fnc = res["sender"] return fnc(res.get("url"), **kwargs)
[ "def", "sender", "(", "url", ",", "*", "*", "kwargs", ")", ":", "res", "=", "url_to_resources", "(", "url", ")", "fnc", "=", "res", "[", "\"sender\"", "]", "return", "fnc", "(", "res", ".", "get", "(", "\"url\"", ")", ",", "*", "*", "kwargs", ")"...
Return sender instance from connection url string url <str> connection url eg. 'tcp://0.0.0.0:8080'
[ "Return", "sender", "instance", "from", "connection", "url", "string" ]
train
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/connection/__init__.py#L299-L308
20c/xbahn
xbahn/connection/__init__.py
listen
def listen(url, prefix=None, **kwargs): """ bind and return a connection instance from url arguments: - url (str): xbahn connection url """ return listener(url, prefix=get_prefix(prefix), **kwargs)
python
def listen(url, prefix=None, **kwargs): """ bind and return a connection instance from url arguments: - url (str): xbahn connection url """ return listener(url, prefix=get_prefix(prefix), **kwargs)
[ "def", "listen", "(", "url", ",", "prefix", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "listener", "(", "url", ",", "prefix", "=", "get_prefix", "(", "prefix", ")", ",", "*", "*", "kwargs", ")" ]
bind and return a connection instance from url arguments: - url (str): xbahn connection url
[ "bind", "and", "return", "a", "connection", "instance", "from", "url" ]
train
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/connection/__init__.py#L320-L327
20c/xbahn
xbahn/connection/__init__.py
connect
def connect(url, prefix=None, **kwargs): """ connect and return a connection instance from url arguments: - url (str): xbahn connection url """ return connection(url, prefix=get_prefix(prefix), **kwargs)
python
def connect(url, prefix=None, **kwargs): """ connect and return a connection instance from url arguments: - url (str): xbahn connection url """ return connection(url, prefix=get_prefix(prefix), **kwargs)
[ "def", "connect", "(", "url", ",", "prefix", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "connection", "(", "url", ",", "prefix", "=", "get_prefix", "(", "prefix", ")", ",", "*", "*", "kwargs", ")" ]
connect and return a connection instance from url arguments: - url (str): xbahn connection url
[ "connect", "and", "return", "a", "connection", "instance", "from", "url" ]
train
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/connection/__init__.py#L329-L336
20c/xbahn
xbahn/connection/__init__.py
Connection.make_data
def make_data(self, message): """ make data string from message according to transport_content_type Returns: str: message data """ if not isinstance(message, Message): return message return message.export(self.transport_content_type)
python
def make_data(self, message): """ make data string from message according to transport_content_type Returns: str: message data """ if not isinstance(message, Message): return message return message.export(self.transport_content_type)
[ "def", "make_data", "(", "self", ",", "message", ")", ":", "if", "not", "isinstance", "(", "message", ",", "Message", ")", ":", "return", "message", "return", "message", ".", "export", "(", "self", ".", "transport_content_type", ")" ]
make data string from message according to transport_content_type Returns: str: message data
[ "make", "data", "string", "from", "message", "according", "to", "transport_content_type" ]
train
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/connection/__init__.py#L122-L134
20c/xbahn
xbahn/connection/__init__.py
Connection.make_message
def make_message(self, data): """ Create a Message instance from data, data will be loaded via munge according to the codec specified in the transport_content_type attribute Returns: Message: message object """ data = self.codec.loads(data) ...
python
def make_message(self, data): """ Create a Message instance from data, data will be loaded via munge according to the codec specified in the transport_content_type attribute Returns: Message: message object """ data = self.codec.loads(data) ...
[ "def", "make_message", "(", "self", ",", "data", ")", ":", "data", "=", "self", ".", "codec", ".", "loads", "(", "data", ")", "msg", "=", "Message", "(", "data", ".", "get", "(", "\"data\"", ")", ",", "*", "data", ".", "get", "(", "\"args\"", ","...
Create a Message instance from data, data will be loaded via munge according to the codec specified in the transport_content_type attribute Returns: Message: message object
[ "Create", "a", "Message", "instance", "from", "data", "data", "will", "be", "loaded", "via", "munge", "according", "to", "the", "codec", "specified", "in", "the", "transport_content_type", "attribute" ]
train
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/connection/__init__.py#L136-L156
20c/xbahn
xbahn/connection/__init__.py
Connection.receive
def receive(self, data): """ Create and return a message from data, also triggers the **receive** event Returns: - Message: message object """ self.log_debug("Received: %s" % (data)) message = self.make_message(data) self.trigger("receive", ...
python
def receive(self, data): """ Create and return a message from data, also triggers the **receive** event Returns: - Message: message object """ self.log_debug("Received: %s" % (data)) message = self.make_message(data) self.trigger("receive", ...
[ "def", "receive", "(", "self", ",", "data", ")", ":", "self", ".", "log_debug", "(", "\"Received: %s\"", "%", "(", "data", ")", ")", "message", "=", "self", ".", "make_message", "(", "data", ")", "self", ".", "trigger", "(", "\"receive\"", ",", "data",...
Create and return a message from data, also triggers the **receive** event Returns: - Message: message object
[ "Create", "and", "return", "a", "message", "from", "data", "also", "triggers", "the", "**", "receive", "**", "event" ]
train
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/connection/__init__.py#L203-L215
kshlm/gant
gant/utils/gant_docker.py
check_permissions
def check_permissions(): """ Checks if current user can access docker """ if ( not grp.getgrnam('docker').gr_gid in os.getgroups() and not os.geteuid() == 0 ): exitStr = """ User doesn't have permission to use docker. You can do either of the following, ...
python
def check_permissions(): """ Checks if current user can access docker """ if ( not grp.getgrnam('docker').gr_gid in os.getgroups() and not os.geteuid() == 0 ): exitStr = """ User doesn't have permission to use docker. You can do either of the following, ...
[ "def", "check_permissions", "(", ")", ":", "if", "(", "not", "grp", ".", "getgrnam", "(", "'docker'", ")", ".", "gr_gid", "in", "os", ".", "getgroups", "(", ")", "and", "not", "os", ".", "geteuid", "(", ")", "==", "0", ")", ":", "exitStr", "=", "...
Checks if current user can access docker
[ "Checks", "if", "current", "user", "can", "access", "docker" ]
train
https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/gant_docker.py#L14-L28