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 |
|---|---|---|---|---|---|---|---|---|---|---|
cdgriffith/Reusables | reusables/log.py | get_file_handler | def get_file_handler(file_path="out.log", level=logging.INFO,
log_format=log_formats.easy_read,
handler=logging.FileHandler,
**handler_kwargs):
"""
Set up a file handler to add to a logger.
:param file_path: file to write the log to, defaults t... | python | def get_file_handler(file_path="out.log", level=logging.INFO,
log_format=log_formats.easy_read,
handler=logging.FileHandler,
**handler_kwargs):
"""
Set up a file handler to add to a logger.
:param file_path: file to write the log to, defaults t... | [
"def",
"get_file_handler",
"(",
"file_path",
"=",
"\"out.log\"",
",",
"level",
"=",
"logging",
".",
"INFO",
",",
"log_format",
"=",
"log_formats",
".",
"easy_read",
",",
"handler",
"=",
"logging",
".",
"FileHandler",
",",
"*",
"*",
"handler_kwargs",
")",
":"... | Set up a file handler to add to a logger.
:param file_path: file to write the log to, defaults to out.log
:param level: logging level to set handler at
:param log_format: formatter to use
:param handler: logging handler to use, defaults to FileHandler
:param handler_kwargs: options to pass to the h... | [
"Set",
"up",
"a",
"file",
"handler",
"to",
"add",
"to",
"a",
"logger",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/log.py#L62-L79 |
cdgriffith/Reusables | reusables/log.py | setup_logger | def setup_logger(module_name=None, level=logging.INFO, stream=sys.stderr,
file_path=None, log_format=log_formats.easy_read,
suppress_warning=True):
"""
Grabs the specified logger and adds wanted handlers to it. Will
default to adding a stream handler.
:param module_nam... | python | def setup_logger(module_name=None, level=logging.INFO, stream=sys.stderr,
file_path=None, log_format=log_formats.easy_read,
suppress_warning=True):
"""
Grabs the specified logger and adds wanted handlers to it. Will
default to adding a stream handler.
:param module_nam... | [
"def",
"setup_logger",
"(",
"module_name",
"=",
"None",
",",
"level",
"=",
"logging",
".",
"INFO",
",",
"stream",
"=",
"sys",
".",
"stderr",
",",
"file_path",
"=",
"None",
",",
"log_format",
"=",
"log_formats",
".",
"easy_read",
",",
"suppress_warning",
"=... | Grabs the specified logger and adds wanted handlers to it. Will
default to adding a stream handler.
:param module_name: logger name to use
:param level: logging level to set logger at
:param stream: stream to log to, or None
:param file_path: file path to log to, or None
:param log_format: form... | [
"Grabs",
"the",
"specified",
"logger",
"and",
"adds",
"wanted",
"handlers",
"to",
"it",
".",
"Will",
"default",
"to",
"adding",
"a",
"stream",
"handler",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/log.py#L82-L108 |
cdgriffith/Reusables | reusables/log.py | add_stream_handler | def add_stream_handler(logger=None, stream=sys.stderr, level=logging.INFO,
log_format=log_formats.easy_read):
"""
Addes a newly created stream handler to the specified logger
:param logger: logging name or object to modify, defaults to root logger
:param stream: which stream to u... | python | def add_stream_handler(logger=None, stream=sys.stderr, level=logging.INFO,
log_format=log_formats.easy_read):
"""
Addes a newly created stream handler to the specified logger
:param logger: logging name or object to modify, defaults to root logger
:param stream: which stream to u... | [
"def",
"add_stream_handler",
"(",
"logger",
"=",
"None",
",",
"stream",
"=",
"sys",
".",
"stderr",
",",
"level",
"=",
"logging",
".",
"INFO",
",",
"log_format",
"=",
"log_formats",
".",
"easy_read",
")",
":",
"if",
"not",
"isinstance",
"(",
"logger",
","... | Addes a newly created stream handler to the specified logger
:param logger: logging name or object to modify, defaults to root logger
:param stream: which stream to use, defaults to sys.stderr
:param level: logging level to set handler at
:param log_format: formatter to use | [
"Addes",
"a",
"newly",
"created",
"stream",
"handler",
"to",
"the",
"specified",
"logger"
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/log.py#L118-L131 |
cdgriffith/Reusables | reusables/log.py | add_file_handler | def add_file_handler(logger=None, file_path="out.log", level=logging.INFO,
log_format=log_formats.easy_read):
"""
Addes a newly created file handler to the specified logger
:param logger: logging name or object to modify, defaults to root logger
:param file_path: path to file to lo... | python | def add_file_handler(logger=None, file_path="out.log", level=logging.INFO,
log_format=log_formats.easy_read):
"""
Addes a newly created file handler to the specified logger
:param logger: logging name or object to modify, defaults to root logger
:param file_path: path to file to lo... | [
"def",
"add_file_handler",
"(",
"logger",
"=",
"None",
",",
"file_path",
"=",
"\"out.log\"",
",",
"level",
"=",
"logging",
".",
"INFO",
",",
"log_format",
"=",
"log_formats",
".",
"easy_read",
")",
":",
"if",
"not",
"isinstance",
"(",
"logger",
",",
"loggi... | Addes a newly created file handler to the specified logger
:param logger: logging name or object to modify, defaults to root logger
:param file_path: path to file to log to
:param level: logging level to set handler at
:param log_format: formatter to use | [
"Addes",
"a",
"newly",
"created",
"file",
"handler",
"to",
"the",
"specified",
"logger"
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/log.py#L134-L147 |
cdgriffith/Reusables | reusables/log.py | add_rotating_file_handler | def add_rotating_file_handler(logger=None, file_path="out.log",
level=logging.INFO,
log_format=log_formats.easy_read,
max_bytes=10*sizes.mb, backup_count=5,
**handler_kwargs):
""" Adds a rotating ... | python | def add_rotating_file_handler(logger=None, file_path="out.log",
level=logging.INFO,
log_format=log_formats.easy_read,
max_bytes=10*sizes.mb, backup_count=5,
**handler_kwargs):
""" Adds a rotating ... | [
"def",
"add_rotating_file_handler",
"(",
"logger",
"=",
"None",
",",
"file_path",
"=",
"\"out.log\"",
",",
"level",
"=",
"logging",
".",
"INFO",
",",
"log_format",
"=",
"log_formats",
".",
"easy_read",
",",
"max_bytes",
"=",
"10",
"*",
"sizes",
".",
"mb",
... | Adds a rotating file handler to the specified logger.
:param logger: logging name or object to modify, defaults to root logger
:param file_path: path to file to log to
:param level: logging level to set handler at
:param log_format: log formatter
:param max_bytes: Max file size in bytes before rota... | [
"Adds",
"a",
"rotating",
"file",
"handler",
"to",
"the",
"specified",
"logger",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/log.py#L150-L172 |
cdgriffith/Reusables | reusables/log.py | add_timed_rotating_file_handler | def add_timed_rotating_file_handler(logger=None, file_path="out.log",
level=logging.INFO,
log_format=log_formats.easy_read,
when='w0', interval=1, backup_count=5,
**handler_kwa... | python | def add_timed_rotating_file_handler(logger=None, file_path="out.log",
level=logging.INFO,
log_format=log_formats.easy_read,
when='w0', interval=1, backup_count=5,
**handler_kwa... | [
"def",
"add_timed_rotating_file_handler",
"(",
"logger",
"=",
"None",
",",
"file_path",
"=",
"\"out.log\"",
",",
"level",
"=",
"logging",
".",
"INFO",
",",
"log_format",
"=",
"log_formats",
".",
"easy_read",
",",
"when",
"=",
"'w0'",
",",
"interval",
"=",
"1... | Adds a timed rotating file handler to the specified logger.
Defaults to weekly rotation, with 5 backups.
:param logger: logging name or object to modify, defaults to root logger
:param file_path: path to file to log to
:param level: logging level to set handler at
:param log_format: log formatter
... | [
"Adds",
"a",
"timed",
"rotating",
"file",
"handler",
"to",
"the",
"specified",
"logger",
".",
"Defaults",
"to",
"weekly",
"rotation",
"with",
"5",
"backups",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/log.py#L175-L200 |
cdgriffith/Reusables | reusables/log.py | remove_stream_handlers | def remove_stream_handlers(logger=None):
"""
Remove only stream handlers from the specified logger
:param logger: logging name or object to modify, defaults to root logger
"""
if not isinstance(logger, logging.Logger):
logger = logging.getLogger(logger)
new_handlers = []
for handle... | python | def remove_stream_handlers(logger=None):
"""
Remove only stream handlers from the specified logger
:param logger: logging name or object to modify, defaults to root logger
"""
if not isinstance(logger, logging.Logger):
logger = logging.getLogger(logger)
new_handlers = []
for handle... | [
"def",
"remove_stream_handlers",
"(",
"logger",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"logger",
",",
"logging",
".",
"Logger",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"logger",
")",
"new_handlers",
"=",
"[",
"]",
"for"... | Remove only stream handlers from the specified logger
:param logger: logging name or object to modify, defaults to root logger | [
"Remove",
"only",
"stream",
"handlers",
"from",
"the",
"specified",
"logger"
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/log.py#L203-L221 |
cdgriffith/Reusables | reusables/log.py | remove_file_handlers | def remove_file_handlers(logger=None):
"""
Remove only file handlers from the specified logger. Will go through
and close each handler for safety.
:param logger: logging name or object to modify, defaults to root logger
"""
if not isinstance(logger, logging.Logger):
logger = logging.get... | python | def remove_file_handlers(logger=None):
"""
Remove only file handlers from the specified logger. Will go through
and close each handler for safety.
:param logger: logging name or object to modify, defaults to root logger
"""
if not isinstance(logger, logging.Logger):
logger = logging.get... | [
"def",
"remove_file_handlers",
"(",
"logger",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"logger",
",",
"logging",
".",
"Logger",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"logger",
")",
"new_handlers",
"=",
"[",
"]",
"for",
... | Remove only file handlers from the specified logger. Will go through
and close each handler for safety.
:param logger: logging name or object to modify, defaults to root logger | [
"Remove",
"only",
"file",
"handlers",
"from",
"the",
"specified",
"logger",
".",
"Will",
"go",
"through",
"and",
"close",
"each",
"handler",
"for",
"safety",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/log.py#L224-L240 |
cdgriffith/Reusables | reusables/log.py | remove_all_handlers | def remove_all_handlers(logger=None):
"""
Safely remove all handlers from the logger
:param logger: logging name or object to modify, defaults to root logger
"""
if not isinstance(logger, logging.Logger):
logger = logging.getLogger(logger)
remove_file_handlers(logger)
logger.handle... | python | def remove_all_handlers(logger=None):
"""
Safely remove all handlers from the logger
:param logger: logging name or object to modify, defaults to root logger
"""
if not isinstance(logger, logging.Logger):
logger = logging.getLogger(logger)
remove_file_handlers(logger)
logger.handle... | [
"def",
"remove_all_handlers",
"(",
"logger",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"logger",
",",
"logging",
".",
"Logger",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"logger",
")",
"remove_file_handlers",
"(",
"logger",
")... | Safely remove all handlers from the logger
:param logger: logging name or object to modify, defaults to root logger | [
"Safely",
"remove",
"all",
"handlers",
"from",
"the",
"logger"
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/log.py#L243-L253 |
cdgriffith/Reusables | reusables/log.py | change_logger_levels | def change_logger_levels(logger=None, level=logging.DEBUG):
"""
Go through the logger and handlers and update their levels to the
one specified.
:param logger: logging name or object to modify, defaults to root logger
:param level: logging level to set at (10=Debug, 20=Info, 30=Warn, 40=Error)
... | python | def change_logger_levels(logger=None, level=logging.DEBUG):
"""
Go through the logger and handlers and update their levels to the
one specified.
:param logger: logging name or object to modify, defaults to root logger
:param level: logging level to set at (10=Debug, 20=Info, 30=Warn, 40=Error)
... | [
"def",
"change_logger_levels",
"(",
"logger",
"=",
"None",
",",
"level",
"=",
"logging",
".",
"DEBUG",
")",
":",
"if",
"not",
"isinstance",
"(",
"logger",
",",
"logging",
".",
"Logger",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"logger",... | Go through the logger and handlers and update their levels to the
one specified.
:param logger: logging name or object to modify, defaults to root logger
:param level: logging level to set at (10=Debug, 20=Info, 30=Warn, 40=Error) | [
"Go",
"through",
"the",
"logger",
"and",
"handlers",
"and",
"update",
"their",
"levels",
"to",
"the",
"one",
"specified",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/log.py#L256-L269 |
cdgriffith/Reusables | reusables/log.py | get_registered_loggers | def get_registered_loggers(hide_children=False, hide_reusables=False):
"""
Find the names of all loggers currently registered
:param hide_children: only return top level logger names
:param hide_reusables: hide the reusables loggers
:return: list of logger names
"""
return [logger for logg... | python | def get_registered_loggers(hide_children=False, hide_reusables=False):
"""
Find the names of all loggers currently registered
:param hide_children: only return top level logger names
:param hide_reusables: hide the reusables loggers
:return: list of logger names
"""
return [logger for logg... | [
"def",
"get_registered_loggers",
"(",
"hide_children",
"=",
"False",
",",
"hide_reusables",
"=",
"False",
")",
":",
"return",
"[",
"logger",
"for",
"logger",
"in",
"logging",
".",
"Logger",
".",
"manager",
".",
"loggerDict",
".",
"keys",
"(",
")",
"if",
"n... | Find the names of all loggers currently registered
:param hide_children: only return top level logger names
:param hide_reusables: hide the reusables loggers
:return: list of logger names | [
"Find",
"the",
"names",
"of",
"all",
"loggers",
"currently",
"registered"
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/log.py#L272-L283 |
cdgriffith/Reusables | reusables/wrappers.py | unique | def unique(max_retries=10, wait=0, alt_return="-no_alt_return-",
exception=Exception, error_text=None):
"""
Wrapper. Makes sure the function's return value has not been returned before
or else it run with the same inputs again.
.. code: python
import reusables
import random
... | python | def unique(max_retries=10, wait=0, alt_return="-no_alt_return-",
exception=Exception, error_text=None):
"""
Wrapper. Makes sure the function's return value has not been returned before
or else it run with the same inputs again.
.. code: python
import reusables
import random
... | [
"def",
"unique",
"(",
"max_retries",
"=",
"10",
",",
"wait",
"=",
"0",
",",
"alt_return",
"=",
"\"-no_alt_return-\"",
",",
"exception",
"=",
"Exception",
",",
"error_text",
"=",
"None",
")",
":",
"def",
"func_wrap",
"(",
"func",
")",
":",
"@",
"wraps",
... | Wrapper. Makes sure the function's return value has not been returned before
or else it run with the same inputs again.
.. code: python
import reusables
import random
@reusables.unique(max_retries=100)
def poor_uuid():
return random.randint(0, 10)
print([p... | [
"Wrapper",
".",
"Makes",
"sure",
"the",
"function",
"s",
"return",
"value",
"has",
"not",
"been",
"returned",
"before",
"or",
"else",
"it",
"run",
"with",
"the",
"same",
"inputs",
"again",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/wrappers.py#L37-L87 |
cdgriffith/Reusables | reusables/wrappers.py | lock_it | def lock_it(lock=g_lock):
"""
Wrapper. Simple wrapper to make sure a function is only run once at a time.
.. code: python
import reusables
import time
def func_one(_):
time.sleep(5)
@reusables.lock_it()
def func_two(_):
time.sleep(5)
... | python | def lock_it(lock=g_lock):
"""
Wrapper. Simple wrapper to make sure a function is only run once at a time.
.. code: python
import reusables
import time
def func_one(_):
time.sleep(5)
@reusables.lock_it()
def func_two(_):
time.sleep(5)
... | [
"def",
"lock_it",
"(",
"lock",
"=",
"g_lock",
")",
":",
"def",
"func_wrapper",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"lock",
":",
"return",
"func",
"(... | Wrapper. Simple wrapper to make sure a function is only run once at a time.
.. code: python
import reusables
import time
def func_one(_):
time.sleep(5)
@reusables.lock_it()
def func_two(_):
time.sleep(5)
@reusables.time_it(message="test_1 ... | [
"Wrapper",
".",
"Simple",
"wrapper",
"to",
"make",
"sure",
"a",
"function",
"is",
"only",
"run",
"once",
"at",
"a",
"time",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/wrappers.py#L90-L129 |
cdgriffith/Reusables | reusables/wrappers.py | time_it | def time_it(log=None, message=None, append=None):
"""
Wrapper. Time the amount of time it takes the execution of the function
and print it.
If log is true, make sure to set the logging level of 'reusables' to INFO
level or lower.
.. code:: python
import time
import reusables
... | python | def time_it(log=None, message=None, append=None):
"""
Wrapper. Time the amount of time it takes the execution of the function
and print it.
If log is true, make sure to set the logging level of 'reusables' to INFO
level or lower.
.. code:: python
import time
import reusables
... | [
"def",
"time_it",
"(",
"log",
"=",
"None",
",",
"message",
"=",
"None",
",",
"append",
"=",
"None",
")",
":",
"def",
"func_wrapper",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs... | Wrapper. Time the amount of time it takes the execution of the function
and print it.
If log is true, make sure to set the logging level of 'reusables' to INFO
level or lower.
.. code:: python
import time
import reusables
reusables.add_stream_handler('reusables')
@re... | [
"Wrapper",
".",
"Time",
"the",
"amount",
"of",
"time",
"it",
"takes",
"the",
"execution",
"of",
"the",
"function",
"and",
"print",
"it",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/wrappers.py#L132-L193 |
cdgriffith/Reusables | reusables/wrappers.py | queue_it | def queue_it(queue=g_queue, **put_args):
"""
Wrapper. Instead of returning the result of the function, add it to a queue.
.. code: python
import reusables
import queue
my_queue = queue.Queue()
@reusables.queue_it(my_queue)
def func(a):
return a
... | python | def queue_it(queue=g_queue, **put_args):
"""
Wrapper. Instead of returning the result of the function, add it to a queue.
.. code: python
import reusables
import queue
my_queue = queue.Queue()
@reusables.queue_it(my_queue)
def func(a):
return a
... | [
"def",
"queue_it",
"(",
"queue",
"=",
"g_queue",
",",
"*",
"*",
"put_args",
")",
":",
"def",
"func_wrapper",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"queue",
".... | Wrapper. Instead of returning the result of the function, add it to a queue.
.. code: python
import reusables
import queue
my_queue = queue.Queue()
@reusables.queue_it(my_queue)
def func(a):
return a
func(10)
print(my_queue.get())
# 1... | [
"Wrapper",
".",
"Instead",
"of",
"returning",
"the",
"result",
"of",
"the",
"function",
"add",
"it",
"to",
"a",
"queue",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/wrappers.py#L196-L224 |
cdgriffith/Reusables | reusables/wrappers.py | log_exception | def log_exception(log="reusables", message=None, exceptions=(Exception, ),
level=logging.ERROR, show_traceback=True):
"""
Wrapper. Log the traceback to any exceptions raised. Possible to raise
custom exception.
.. code :: python
@reusables.log_exception()
def test():
... | python | def log_exception(log="reusables", message=None, exceptions=(Exception, ),
level=logging.ERROR, show_traceback=True):
"""
Wrapper. Log the traceback to any exceptions raised. Possible to raise
custom exception.
.. code :: python
@reusables.log_exception()
def test():
... | [
"def",
"log_exception",
"(",
"log",
"=",
"\"reusables\"",
",",
"message",
"=",
"None",
",",
"exceptions",
"=",
"(",
"Exception",
",",
")",
",",
"level",
"=",
"logging",
".",
"ERROR",
",",
"show_traceback",
"=",
"True",
")",
":",
"def",
"func_wrapper",
"(... | Wrapper. Log the traceback to any exceptions raised. Possible to raise
custom exception.
.. code :: python
@reusables.log_exception()
def test():
raise Exception("Bad")
# 2016-12-26 12:38:01,381 - reusables ERROR Exception in test - Bad
# Traceback (most recent ... | [
"Wrapper",
".",
"Log",
"the",
"traceback",
"to",
"any",
"exceptions",
"raised",
".",
"Possible",
"to",
"raise",
"custom",
"exception",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/wrappers.py#L227-L272 |
cdgriffith/Reusables | reusables/wrappers.py | catch_it | def catch_it(exceptions=(Exception, ), default=None, handler=None):
"""
If the function encounters an exception, catch it, and
return the specified default or sent to a handler function instead.
.. code :: python
def handle_error(exception, func, *args, **kwargs):
print(f"{func.__n... | python | def catch_it(exceptions=(Exception, ), default=None, handler=None):
"""
If the function encounters an exception, catch it, and
return the specified default or sent to a handler function instead.
.. code :: python
def handle_error(exception, func, *args, **kwargs):
print(f"{func.__n... | [
"def",
"catch_it",
"(",
"exceptions",
"=",
"(",
"Exception",
",",
")",
",",
"default",
"=",
"None",
",",
"handler",
"=",
"None",
")",
":",
"def",
"func_wrapper",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"ar... | If the function encounters an exception, catch it, and
return the specified default or sent to a handler function instead.
.. code :: python
def handle_error(exception, func, *args, **kwargs):
print(f"{func.__name__} raised {exception} when called with {args}")
@reusables.catch_it... | [
"If",
"the",
"function",
"encounters",
"an",
"exception",
"catch",
"it",
"and",
"return",
"the",
"specified",
"default",
"or",
"sent",
"to",
"a",
"handler",
"function",
"instead",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/wrappers.py#L275-L304 |
cdgriffith/Reusables | reusables/wrappers.py | retry_it | def retry_it(exceptions=(Exception, ), tries=10, wait=0, handler=None,
raised_exception=ReusablesError, raised_message=None):
"""
Retry a function if an exception is raised, or if output_check returns
False.
Message format options: {func} {args} {kwargs}
:param exceptions: tuple of ex... | python | def retry_it(exceptions=(Exception, ), tries=10, wait=0, handler=None,
raised_exception=ReusablesError, raised_message=None):
"""
Retry a function if an exception is raised, or if output_check returns
False.
Message format options: {func} {args} {kwargs}
:param exceptions: tuple of ex... | [
"def",
"retry_it",
"(",
"exceptions",
"=",
"(",
"Exception",
",",
")",
",",
"tries",
"=",
"10",
",",
"wait",
"=",
"0",
",",
"handler",
"=",
"None",
",",
"raised_exception",
"=",
"ReusablesError",
",",
"raised_message",
"=",
"None",
")",
":",
"def",
"fu... | Retry a function if an exception is raised, or if output_check returns
False.
Message format options: {func} {args} {kwargs}
:param exceptions: tuple of exceptions to catch
:param tries: number of tries to retry the function
:param wait: time to wait between executions in seconds
:param handle... | [
"Retry",
"a",
"function",
"if",
"an",
"exception",
"is",
"raised",
"or",
"if",
"output_check",
"returns",
"False",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/wrappers.py#L307-L351 |
cdgriffith/Reusables | reusables/file_operations.py | extract | def extract(archive_file, path=".", delete_on_success=False,
enable_rar=False):
"""
Automatically detect archive type and extract all files to specified path.
.. code:: python
import os
os.listdir(".")
# ['test_structure.zip']
reusables.extract("test_structure... | python | def extract(archive_file, path=".", delete_on_success=False,
enable_rar=False):
"""
Automatically detect archive type and extract all files to specified path.
.. code:: python
import os
os.listdir(".")
# ['test_structure.zip']
reusables.extract("test_structure... | [
"def",
"extract",
"(",
"archive_file",
",",
"path",
"=",
"\".\"",
",",
"delete_on_success",
"=",
"False",
",",
"enable_rar",
"=",
"False",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"archive_file",
")",
"or",
"not",
"os",
".",
"path"... | Automatically detect archive type and extract all files to specified path.
.. code:: python
import os
os.listdir(".")
# ['test_structure.zip']
reusables.extract("test_structure.zip")
os.listdir(".")
# [ 'test_structure', 'test_structure.zip']
:param archive... | [
"Automatically",
"detect",
"archive",
"type",
"and",
"extract",
"all",
"files",
"to",
"specified",
"path",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L35-L92 |
cdgriffith/Reusables | reusables/file_operations.py | archive | def archive(files_to_archive, name="archive.zip", archive_type=None,
overwrite=False, store=False, depth=None, err_non_exist=True,
allow_zip_64=True, **tarfile_kwargs):
""" Archive a list of files (or files inside a folder), can chose between
- zip
- tar
- gz (tar.gz... | python | def archive(files_to_archive, name="archive.zip", archive_type=None,
overwrite=False, store=False, depth=None, err_non_exist=True,
allow_zip_64=True, **tarfile_kwargs):
""" Archive a list of files (or files inside a folder), can chose between
- zip
- tar
- gz (tar.gz... | [
"def",
"archive",
"(",
"files_to_archive",
",",
"name",
"=",
"\"archive.zip\"",
",",
"archive_type",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"store",
"=",
"False",
",",
"depth",
"=",
"None",
",",
"err_non_exist",
"=",
"True",
",",
"allow_zip_64",
... | Archive a list of files (or files inside a folder), can chose between
- zip
- tar
- gz (tar.gz, tgz)
- bz2 (tar.bz2)
.. code:: python
reusables.archive(['reusables', '.travis.yml'],
name="my_archive.bz2")
# 'C:\\Users\\Me\\Reusables\\m... | [
"Archive",
"a",
"list",
"of",
"files",
"(",
"or",
"files",
"inside",
"a",
"folder",
")",
"can",
"chose",
"between"
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L95-L183 |
cdgriffith/Reusables | reusables/file_operations.py | list_to_csv | def list_to_csv(my_list, csv_file):
"""
Save a matrix (list of lists) to a file as a CSV
.. code:: python
my_list = [["Name", "Location"],
["Chris", "South Pole"],
["Harry", "Depth of Winter"],
["Bob", "Skull"]]
reusables.list_to_cs... | python | def list_to_csv(my_list, csv_file):
"""
Save a matrix (list of lists) to a file as a CSV
.. code:: python
my_list = [["Name", "Location"],
["Chris", "South Pole"],
["Harry", "Depth of Winter"],
["Bob", "Skull"]]
reusables.list_to_cs... | [
"def",
"list_to_csv",
"(",
"my_list",
",",
"csv_file",
")",
":",
"if",
"PY3",
":",
"csv_handler",
"=",
"open",
"(",
"csv_file",
",",
"'w'",
",",
"newline",
"=",
"''",
")",
"else",
":",
"csv_handler",
"=",
"open",
"(",
"csv_file",
",",
"'wb'",
")",
"t... | Save a matrix (list of lists) to a file as a CSV
.. code:: python
my_list = [["Name", "Location"],
["Chris", "South Pole"],
["Harry", "Depth of Winter"],
["Bob", "Skull"]]
reusables.list_to_csv(my_list, "example.csv")
example.csv
... | [
"Save",
"a",
"matrix",
"(",
"list",
"of",
"lists",
")",
"to",
"a",
"file",
"as",
"a",
"CSV"
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L186-L220 |
cdgriffith/Reusables | reusables/file_operations.py | csv_to_list | def csv_to_list(csv_file):
"""
Open and transform a CSV file into a matrix (list of lists).
.. code:: python
reusables.csv_to_list("example.csv")
# [['Name', 'Location'],
# ['Chris', 'South Pole'],
# ['Harry', 'Depth of Winter'],
# ['Bob', 'Skull']]
:param c... | python | def csv_to_list(csv_file):
"""
Open and transform a CSV file into a matrix (list of lists).
.. code:: python
reusables.csv_to_list("example.csv")
# [['Name', 'Location'],
# ['Chris', 'South Pole'],
# ['Harry', 'Depth of Winter'],
# ['Bob', 'Skull']]
:param c... | [
"def",
"csv_to_list",
"(",
"csv_file",
")",
":",
"with",
"open",
"(",
"csv_file",
",",
"'r'",
"if",
"PY3",
"else",
"'rb'",
")",
"as",
"f",
":",
"return",
"list",
"(",
"csv",
".",
"reader",
"(",
"f",
")",
")"
] | Open and transform a CSV file into a matrix (list of lists).
.. code:: python
reusables.csv_to_list("example.csv")
# [['Name', 'Location'],
# ['Chris', 'South Pole'],
# ['Harry', 'Depth of Winter'],
# ['Bob', 'Skull']]
:param csv_file: Path to CSV file as str
:r... | [
"Open",
"and",
"transform",
"a",
"CSV",
"file",
"into",
"a",
"matrix",
"(",
"list",
"of",
"lists",
")",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L223-L239 |
cdgriffith/Reusables | reusables/file_operations.py | load_json | def load_json(json_file, **kwargs):
"""
Open and load data from a JSON file
.. code:: python
reusables.load_json("example.json")
# {u'key_1': u'val_1', u'key_for_dict': {u'sub_dict_key': 8}}
:param json_file: Path to JSON file as string
:param kwargs: Additional arguments for the ... | python | def load_json(json_file, **kwargs):
"""
Open and load data from a JSON file
.. code:: python
reusables.load_json("example.json")
# {u'key_1': u'val_1', u'key_for_dict': {u'sub_dict_key': 8}}
:param json_file: Path to JSON file as string
:param kwargs: Additional arguments for the ... | [
"def",
"load_json",
"(",
"json_file",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"open",
"(",
"json_file",
")",
"as",
"f",
":",
"return",
"json",
".",
"load",
"(",
"f",
",",
"*",
"*",
"kwargs",
")"
] | Open and load data from a JSON file
.. code:: python
reusables.load_json("example.json")
# {u'key_1': u'val_1', u'key_for_dict': {u'sub_dict_key': 8}}
:param json_file: Path to JSON file as string
:param kwargs: Additional arguments for the json.load command
:return: Dictionary | [
"Open",
"and",
"load",
"data",
"from",
"a",
"JSON",
"file"
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L242-L256 |
cdgriffith/Reusables | reusables/file_operations.py | save_json | def save_json(data, json_file, indent=4, **kwargs):
"""
Takes a dictionary and saves it to a file as JSON
.. code:: python
my_dict = {"key_1": "val_1",
"key_for_dict": {"sub_dict_key": 8}}
reusables.save_json(my_dict,"example.json")
example.json
.. code::
... | python | def save_json(data, json_file, indent=4, **kwargs):
"""
Takes a dictionary and saves it to a file as JSON
.. code:: python
my_dict = {"key_1": "val_1",
"key_for_dict": {"sub_dict_key": 8}}
reusables.save_json(my_dict,"example.json")
example.json
.. code::
... | [
"def",
"save_json",
"(",
"data",
",",
"json_file",
",",
"indent",
"=",
"4",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"open",
"(",
"json_file",
",",
"\"w\"",
")",
"as",
"f",
":",
"json",
".",
"dump",
"(",
"data",
",",
"f",
",",
"indent",
"=",
... | Takes a dictionary and saves it to a file as JSON
.. code:: python
my_dict = {"key_1": "val_1",
"key_for_dict": {"sub_dict_key": 8}}
reusables.save_json(my_dict,"example.json")
example.json
.. code::
{
"key_1": "val_1",
"key_for_dict":... | [
"Takes",
"a",
"dictionary",
"and",
"saves",
"it",
"to",
"a",
"file",
"as",
"JSON"
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L259-L287 |
cdgriffith/Reusables | reusables/file_operations.py | config_dict | def config_dict(config_file=None, auto_find=False, verify=True, **cfg_options):
"""
Return configuration options as dictionary. Accepts either a single
config file or a list of files. Auto find will search for all .cfg, .config
and .ini in the execution directory and package root (unsafe but handy).
... | python | def config_dict(config_file=None, auto_find=False, verify=True, **cfg_options):
"""
Return configuration options as dictionary. Accepts either a single
config file or a list of files. Auto find will search for all .cfg, .config
and .ini in the execution directory and package root (unsafe but handy).
... | [
"def",
"config_dict",
"(",
"config_file",
"=",
"None",
",",
"auto_find",
"=",
"False",
",",
"verify",
"=",
"True",
",",
"*",
"*",
"cfg_options",
")",
":",
"if",
"not",
"config_file",
":",
"config_file",
"=",
"[",
"]",
"cfg_parser",
"=",
"ConfigParser",
"... | Return configuration options as dictionary. Accepts either a single
config file or a list of files. Auto find will search for all .cfg, .config
and .ini in the execution directory and package root (unsafe but handy).
.. code:: python
reusables.config_dict(os.path.join("test", "data", "test_config.... | [
"Return",
"configuration",
"options",
"as",
"dictionary",
".",
"Accepts",
"either",
"a",
"single",
"config",
"file",
"or",
"a",
"list",
"of",
"files",
".",
"Auto",
"find",
"will",
"search",
"for",
"all",
".",
"cfg",
".",
"config",
"and",
".",
"ini",
"in"... | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L290-L340 |
cdgriffith/Reusables | reusables/file_operations.py | config_namespace | def config_namespace(config_file=None, auto_find=False,
verify=True, **cfg_options):
"""
Return configuration options as a Namespace.
.. code:: python
reusables.config_namespace(os.path.join("test", "data",
"test_config.ini"))
... | python | def config_namespace(config_file=None, auto_find=False,
verify=True, **cfg_options):
"""
Return configuration options as a Namespace.
.. code:: python
reusables.config_namespace(os.path.join("test", "data",
"test_config.ini"))
... | [
"def",
"config_namespace",
"(",
"config_file",
"=",
"None",
",",
"auto_find",
"=",
"False",
",",
"verify",
"=",
"True",
",",
"*",
"*",
"cfg_options",
")",
":",
"return",
"ConfigNamespace",
"(",
"*",
"*",
"config_dict",
"(",
"config_file",
",",
"auto_find",
... | Return configuration options as a Namespace.
.. code:: python
reusables.config_namespace(os.path.join("test", "data",
"test_config.ini"))
# <Namespace: {'General': {'example': 'A regul...>
:param config_file: path or paths to the files location... | [
"Return",
"configuration",
"options",
"as",
"a",
"Namespace",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L343-L362 |
cdgriffith/Reusables | reusables/file_operations.py | _walk | def _walk(directory, enable_scandir=False, **kwargs):
"""
Internal function to return walk generator either from os or scandir
:param directory: directory to traverse
:param enable_scandir: on python < 3.5 enable external scandir package
:param kwargs: arguments to pass to walk function
:return... | python | def _walk(directory, enable_scandir=False, **kwargs):
"""
Internal function to return walk generator either from os or scandir
:param directory: directory to traverse
:param enable_scandir: on python < 3.5 enable external scandir package
:param kwargs: arguments to pass to walk function
:return... | [
"def",
"_walk",
"(",
"directory",
",",
"enable_scandir",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"walk",
"=",
"os",
".",
"walk",
"if",
"python_version",
"<",
"(",
"3",
",",
"5",
")",
"and",
"enable_scandir",
":",
"import",
"scandir",
"walk",
... | Internal function to return walk generator either from os or scandir
:param directory: directory to traverse
:param enable_scandir: on python < 3.5 enable external scandir package
:param kwargs: arguments to pass to walk function
:return: walk generator | [
"Internal",
"function",
"to",
"return",
"walk",
"generator",
"either",
"from",
"os",
"or",
"scandir"
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L365-L378 |
cdgriffith/Reusables | reusables/file_operations.py | os_tree | def os_tree(directory, enable_scandir=False):
"""
Return a directories contents as a dictionary hierarchy.
.. code:: python
reusables.os_tree(".")
# {'doc': {'build': {'doctrees': {},
# 'html': {'_sources': {}, '_static': {}}},
# 'source': {}},
... | python | def os_tree(directory, enable_scandir=False):
"""
Return a directories contents as a dictionary hierarchy.
.. code:: python
reusables.os_tree(".")
# {'doc': {'build': {'doctrees': {},
# 'html': {'_sources': {}, '_static': {}}},
# 'source': {}},
... | [
"def",
"os_tree",
"(",
"directory",
",",
"enable_scandir",
"=",
"False",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"directory",
")",
":",
"raise",
"OSError",
"(",
"\"Directory does not exist\"",
")",
"if",
"not",
"os",
".",
"path",
".... | Return a directories contents as a dictionary hierarchy.
.. code:: python
reusables.os_tree(".")
# {'doc': {'build': {'doctrees': {},
# 'html': {'_sources': {}, '_static': {}}},
# 'source': {}},
# 'reusables': {'__pycache__': {}},
# 'test... | [
"Return",
"a",
"directories",
"contents",
"as",
"a",
"dictionary",
"hierarchy",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L381-L422 |
cdgriffith/Reusables | reusables/file_operations.py | file_hash | def file_hash(path, hash_type="md5", block_size=65536, hex_digest=True):
"""
Hash a given file with md5, or any other and return the hex digest. You
can run `hashlib.algorithms_available` to see which are available on your
system unless you have an archaic python version, you poor soul).
This funct... | python | def file_hash(path, hash_type="md5", block_size=65536, hex_digest=True):
"""
Hash a given file with md5, or any other and return the hex digest. You
can run `hashlib.algorithms_available` to see which are available on your
system unless you have an archaic python version, you poor soul).
This funct... | [
"def",
"file_hash",
"(",
"path",
",",
"hash_type",
"=",
"\"md5\"",
",",
"block_size",
"=",
"65536",
",",
"hex_digest",
"=",
"True",
")",
":",
"hashed",
"=",
"hashlib",
".",
"new",
"(",
"hash_type",
")",
"with",
"open",
"(",
"path",
",",
"\"rb\"",
")",
... | Hash a given file with md5, or any other and return the hex digest. You
can run `hashlib.algorithms_available` to see which are available on your
system unless you have an archaic python version, you poor soul).
This function is designed to be non memory intensive.
.. code:: python
reusables.... | [
"Hash",
"a",
"given",
"file",
"with",
"md5",
"or",
"any",
"other",
"and",
"return",
"the",
"hex",
"digest",
".",
"You",
"can",
"run",
"hashlib",
".",
"algorithms_available",
"to",
"see",
"which",
"are",
"available",
"on",
"your",
"system",
"unless",
"you",... | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L425-L450 |
cdgriffith/Reusables | reusables/file_operations.py | find_files | def find_files(directory=".", ext=None, name=None,
match_case=False, disable_glob=False, depth=None,
abspath=False, enable_scandir=False):
"""
Walk through a file directory and return an iterator of files
that match requirements. Will autodetect if name has glob as magic
ch... | python | def find_files(directory=".", ext=None, name=None,
match_case=False, disable_glob=False, depth=None,
abspath=False, enable_scandir=False):
"""
Walk through a file directory and return an iterator of files
that match requirements. Will autodetect if name has glob as magic
ch... | [
"def",
"find_files",
"(",
"directory",
"=",
"\".\"",
",",
"ext",
"=",
"None",
",",
"name",
"=",
"None",
",",
"match_case",
"=",
"False",
",",
"disable_glob",
"=",
"False",
",",
"depth",
"=",
"None",
",",
"abspath",
"=",
"False",
",",
"enable_scandir",
... | Walk through a file directory and return an iterator of files
that match requirements. Will autodetect if name has glob as magic
characters.
Note: For the example below, you can use find_files_list to return as a
list, this is simply an easy way to show the output.
.. code:: python
list(r... | [
"Walk",
"through",
"a",
"file",
"directory",
"and",
"return",
"an",
"iterator",
"of",
"files",
"that",
"match",
"requirements",
".",
"Will",
"autodetect",
"if",
"name",
"has",
"glob",
"as",
"magic",
"characters",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L463-L541 |
cdgriffith/Reusables | reusables/file_operations.py | remove_empty_directories | def remove_empty_directories(root_directory, dry_run=False, ignore_errors=True,
enable_scandir=False):
"""
Remove all empty folders from a path. Returns list of empty directories.
:param root_directory: base directory to start at
:param dry_run: just return a list of what w... | python | def remove_empty_directories(root_directory, dry_run=False, ignore_errors=True,
enable_scandir=False):
"""
Remove all empty folders from a path. Returns list of empty directories.
:param root_directory: base directory to start at
:param dry_run: just return a list of what w... | [
"def",
"remove_empty_directories",
"(",
"root_directory",
",",
"dry_run",
"=",
"False",
",",
"ignore_errors",
"=",
"True",
",",
"enable_scandir",
"=",
"False",
")",
":",
"listdir",
"=",
"os",
".",
"listdir",
"if",
"python_version",
"<",
"(",
"3",
",",
"5",
... | Remove all empty folders from a path. Returns list of empty directories.
:param root_directory: base directory to start at
:param dry_run: just return a list of what would be removed
:param ignore_errors: Permissions are a pain, just ignore if you blocked
:param enable_scandir: on python < 3.5 enable e... | [
"Remove",
"all",
"empty",
"folders",
"from",
"a",
"path",
".",
"Returns",
"list",
"of",
"empty",
"directories",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L544-L592 |
cdgriffith/Reusables | reusables/file_operations.py | remove_empty_files | def remove_empty_files(root_directory, dry_run=False, ignore_errors=True,
enable_scandir=False):
"""
Remove all empty files from a path. Returns list of the empty files removed.
:param root_directory: base directory to start at
:param dry_run: just return a list of what would be ... | python | def remove_empty_files(root_directory, dry_run=False, ignore_errors=True,
enable_scandir=False):
"""
Remove all empty files from a path. Returns list of the empty files removed.
:param root_directory: base directory to start at
:param dry_run: just return a list of what would be ... | [
"def",
"remove_empty_files",
"(",
"root_directory",
",",
"dry_run",
"=",
"False",
",",
"ignore_errors",
"=",
"True",
",",
"enable_scandir",
"=",
"False",
")",
":",
"file_list",
"=",
"[",
"]",
"for",
"root",
",",
"directories",
",",
"files",
"in",
"_walk",
... | Remove all empty files from a path. Returns list of the empty files removed.
:param root_directory: base directory to start at
:param dry_run: just return a list of what would be removed
:param ignore_errors: Permissions are a pain, just ignore if you blocked
:param enable_scandir: on python < 3.5 enab... | [
"Remove",
"all",
"empty",
"files",
"from",
"a",
"path",
".",
"Returns",
"list",
"of",
"the",
"empty",
"files",
"removed",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L595-L627 |
cdgriffith/Reusables | reusables/file_operations.py | dup_finder | def dup_finder(file_path, directory=".", enable_scandir=False):
"""
Check a directory for duplicates of the specified file. This is meant
for a single file only, for checking a directory for dups, use
directory_duplicates.
This is designed to be as fast as possible by doing lighter checks
befor... | python | def dup_finder(file_path, directory=".", enable_scandir=False):
"""
Check a directory for duplicates of the specified file. This is meant
for a single file only, for checking a directory for dups, use
directory_duplicates.
This is designed to be as fast as possible by doing lighter checks
befor... | [
"def",
"dup_finder",
"(",
"file_path",
",",
"directory",
"=",
"\".\"",
",",
"enable_scandir",
"=",
"False",
")",
":",
"size",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"file_path",
")",
"if",
"size",
"==",
"0",
":",
"for",
"empty_file",
"in",
"remov... | Check a directory for duplicates of the specified file. This is meant
for a single file only, for checking a directory for dups, use
directory_duplicates.
This is designed to be as fast as possible by doing lighter checks
before progressing to
more extensive ones, in order they are:
1. File si... | [
"Check",
"a",
"directory",
"for",
"duplicates",
"of",
"the",
"specified",
"file",
".",
"This",
"is",
"meant",
"for",
"a",
"single",
"file",
"only",
"for",
"checking",
"a",
"directory",
"for",
"dups",
"use",
"directory_duplicates",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L630-L681 |
cdgriffith/Reusables | reusables/file_operations.py | directory_duplicates | def directory_duplicates(directory, hash_type='md5', **kwargs):
"""
Find all duplicates in a directory. Will return a list, in that list
are lists of duplicate files.
.. code: python
dups = reusables.directory_duplicates('C:\\Users\\Me\\Pictures')
print(len(dups))
# 56
... | python | def directory_duplicates(directory, hash_type='md5', **kwargs):
"""
Find all duplicates in a directory. Will return a list, in that list
are lists of duplicate files.
.. code: python
dups = reusables.directory_duplicates('C:\\Users\\Me\\Pictures')
print(len(dups))
# 56
... | [
"def",
"directory_duplicates",
"(",
"directory",
",",
"hash_type",
"=",
"'md5'",
",",
"*",
"*",
"kwargs",
")",
":",
"size_map",
",",
"hash_map",
"=",
"defaultdict",
"(",
"list",
")",
",",
"defaultdict",
"(",
"list",
")",
"for",
"item",
"in",
"find_files",
... | Find all duplicates in a directory. Will return a list, in that list
are lists of duplicate files.
.. code: python
dups = reusables.directory_duplicates('C:\\Users\\Me\\Pictures')
print(len(dups))
# 56
print(dups)
# [['C:\\Users\\Me\\Pictures\\IMG_20161127.jpg',
... | [
"Find",
"all",
"duplicates",
"in",
"a",
"directory",
".",
"Will",
"return",
"a",
"list",
"in",
"that",
"list",
"are",
"lists",
"of",
"duplicate",
"files",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L684-L715 |
cdgriffith/Reusables | reusables/file_operations.py | join_paths | def join_paths(*paths, **kwargs):
"""
Join multiple paths together and return the absolute path of them. If 'safe'
is specified, this function will 'clean' the path with the 'safe_path'
function. This will clean root decelerations from the path
after the first item.
Would like to do 'safe=False... | python | def join_paths(*paths, **kwargs):
"""
Join multiple paths together and return the absolute path of them. If 'safe'
is specified, this function will 'clean' the path with the 'safe_path'
function. This will clean root decelerations from the path
after the first item.
Would like to do 'safe=False... | [
"def",
"join_paths",
"(",
"*",
"paths",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"paths",
"[",
"0",
"]",
")",
"for",
"next_path",
"in",
"paths",
"[",
"1",
":",
"]",
":",
"path",
"=",
"os",
".",
"... | Join multiple paths together and return the absolute path of them. If 'safe'
is specified, this function will 'clean' the path with the 'safe_path'
function. This will clean root decelerations from the path
after the first item.
Would like to do 'safe=False' instead of '**kwargs' but stupider versions
... | [
"Join",
"multiple",
"paths",
"together",
"and",
"return",
"the",
"absolute",
"path",
"of",
"them",
".",
"If",
"safe",
"is",
"specified",
"this",
"function",
"will",
"clean",
"the",
"path",
"with",
"the",
"safe_path",
"function",
".",
"This",
"will",
"clean",... | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L728-L755 |
cdgriffith/Reusables | reusables/file_operations.py | join_here | def join_here(*paths, **kwargs):
"""
Join any path or paths as a sub directory of the current file's directory.
.. code:: python
reusables.join_here("Makefile")
# 'C:\\Reusables\\Makefile'
:param paths: paths to join together
:param kwargs: 'strict', do not strip os.sep
:param... | python | def join_here(*paths, **kwargs):
"""
Join any path or paths as a sub directory of the current file's directory.
.. code:: python
reusables.join_here("Makefile")
# 'C:\\Reusables\\Makefile'
:param paths: paths to join together
:param kwargs: 'strict', do not strip os.sep
:param... | [
"def",
"join_here",
"(",
"*",
"paths",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"\".\"",
")",
"for",
"next_path",
"in",
"paths",
":",
"next_path",
"=",
"next_path",
".",
"lstrip",
"(",
"\"\\\\\"",
")",
... | Join any path or paths as a sub directory of the current file's directory.
.. code:: python
reusables.join_here("Makefile")
# 'C:\\Reusables\\Makefile'
:param paths: paths to join together
:param kwargs: 'strict', do not strip os.sep
:param kwargs: 'safe', make them into a safe path i... | [
"Join",
"any",
"path",
"or",
"paths",
"as",
"a",
"sub",
"directory",
"of",
"the",
"current",
"file",
"s",
"directory",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L758-L777 |
cdgriffith/Reusables | reusables/file_operations.py | check_filename | def check_filename(filename):
"""
Returns a boolean stating if the filename is safe to use or not. Note that
this does not test for "legal" names accepted, but a more restricted set of:
Letters, numbers, spaces, hyphens, underscores and periods.
:param filename: name of a file as a string
:retu... | python | def check_filename(filename):
"""
Returns a boolean stating if the filename is safe to use or not. Note that
this does not test for "legal" names accepted, but a more restricted set of:
Letters, numbers, spaces, hyphens, underscores and periods.
:param filename: name of a file as a string
:retu... | [
"def",
"check_filename",
"(",
"filename",
")",
":",
"if",
"not",
"isinstance",
"(",
"filename",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"filename must be a string\"",
")",
"if",
"regex",
".",
"path",
".",
"linux",
".",
"filename",
".",
"search",
... | Returns a boolean stating if the filename is safe to use or not. Note that
this does not test for "legal" names accepted, but a more restricted set of:
Letters, numbers, spaces, hyphens, underscores and periods.
:param filename: name of a file as a string
:return: boolean if it is a safe file name | [
"Returns",
"a",
"boolean",
"stating",
"if",
"the",
"filename",
"is",
"safe",
"to",
"use",
"or",
"not",
".",
"Note",
"that",
"this",
"does",
"not",
"test",
"for",
"legal",
"names",
"accepted",
"but",
"a",
"more",
"restricted",
"set",
"of",
":",
"Letters",... | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L780-L793 |
cdgriffith/Reusables | reusables/file_operations.py | safe_filename | def safe_filename(filename, replacement="_"):
"""
Replace unsafe filename characters with underscores. Note that this does not
test for "legal" names accepted, but a more restricted set of:
Letters, numbers, spaces, hyphens, underscores and periods.
:param filename: name of a file as a string
:... | python | def safe_filename(filename, replacement="_"):
"""
Replace unsafe filename characters with underscores. Note that this does not
test for "legal" names accepted, but a more restricted set of:
Letters, numbers, spaces, hyphens, underscores and periods.
:param filename: name of a file as a string
:... | [
"def",
"safe_filename",
"(",
"filename",
",",
"replacement",
"=",
"\"_\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"filename",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"filename must be a string\"",
")",
"if",
"regex",
".",
"path",
".",
"linux",
... | Replace unsafe filename characters with underscores. Note that this does not
test for "legal" names accepted, but a more restricted set of:
Letters, numbers, spaces, hyphens, underscores and periods.
:param filename: name of a file as a string
:param replacement: character to use as a replacement of ba... | [
"Replace",
"unsafe",
"filename",
"characters",
"with",
"underscores",
".",
"Note",
"that",
"this",
"does",
"not",
"test",
"for",
"legal",
"names",
"accepted",
"but",
"a",
"more",
"restricted",
"set",
"of",
":",
"Letters",
"numbers",
"spaces",
"hyphens",
"under... | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L796-L814 |
cdgriffith/Reusables | reusables/file_operations.py | safe_path | def safe_path(path, replacement="_"):
"""
Replace unsafe path characters with underscores. Do NOT use this
with existing paths that cannot be modified, this to to help generate
new, clean paths.
Supports windows and *nix systems.
:param path: path as a string
:param replacement: character ... | python | def safe_path(path, replacement="_"):
"""
Replace unsafe path characters with underscores. Do NOT use this
with existing paths that cannot be modified, this to to help generate
new, clean paths.
Supports windows and *nix systems.
:param path: path as a string
:param replacement: character ... | [
"def",
"safe_path",
"(",
"path",
",",
"replacement",
"=",
"\"_\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"path must be a string\"",
")",
"if",
"os",
".",
"sep",
"not",
"in",
"path",
":",
"r... | Replace unsafe path characters with underscores. Do NOT use this
with existing paths that cannot be modified, this to to help generate
new, clean paths.
Supports windows and *nix systems.
:param path: path as a string
:param replacement: character to use in place of bad characters
:return: a s... | [
"Replace",
"unsafe",
"path",
"characters",
"with",
"underscores",
".",
"Do",
"NOT",
"use",
"this",
"with",
"existing",
"paths",
"that",
"cannot",
"be",
"modified",
"this",
"to",
"to",
"help",
"generate",
"new",
"clean",
"paths",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L817-L853 |
cdgriffith/Reusables | reusables/tasker.py | Tasker.change_task_size | def change_task_size(self, size):
"""Blocking request to change number of running tasks"""
self._pause.value = True
self.log.debug("About to change task size to {0}".format(size))
try:
size = int(size)
except ValueError:
self.log.error("Cannot change task ... | python | def change_task_size(self, size):
"""Blocking request to change number of running tasks"""
self._pause.value = True
self.log.debug("About to change task size to {0}".format(size))
try:
size = int(size)
except ValueError:
self.log.error("Cannot change task ... | [
"def",
"change_task_size",
"(",
"self",
",",
"size",
")",
":",
"self",
".",
"_pause",
".",
"value",
"=",
"True",
"self",
".",
"log",
".",
"debug",
"(",
"\"About to change task size to {0}\"",
".",
"format",
"(",
"size",
")",
")",
"try",
":",
"size",
"=",... | Blocking request to change number of running tasks | [
"Blocking",
"request",
"to",
"change",
"number",
"of",
"running",
"tasks"
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/tasker.py#L128-L163 |
cdgriffith/Reusables | reusables/tasker.py | Tasker.stop | def stop(self):
"""Hard stop the server and sub process"""
self._end.value = True
if self.background_process:
try:
self.background_process.terminate()
except Exception:
pass
for task_id, values in self.current_tasks.items():
... | python | def stop(self):
"""Hard stop the server and sub process"""
self._end.value = True
if self.background_process:
try:
self.background_process.terminate()
except Exception:
pass
for task_id, values in self.current_tasks.items():
... | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"_end",
".",
"value",
"=",
"True",
"if",
"self",
".",
"background_process",
":",
"try",
":",
"self",
".",
"background_process",
".",
"terminate",
"(",
")",
"except",
"Exception",
":",
"pass",
"for",
"t... | Hard stop the server and sub process | [
"Hard",
"stop",
"the",
"server",
"and",
"sub",
"process"
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/tasker.py#L165-L177 |
cdgriffith/Reusables | reusables/tasker.py | Tasker.get_state | def get_state(self):
"""Get general information about the state of the class"""
return {"started": (True if self.background_process and
self.background_process.is_alive() else False),
"paused": self._pause.value,
"stopped": self._end.value,
... | python | def get_state(self):
"""Get general information about the state of the class"""
return {"started": (True if self.background_process and
self.background_process.is_alive() else False),
"paused": self._pause.value,
"stopped": self._end.value,
... | [
"def",
"get_state",
"(",
"self",
")",
":",
"return",
"{",
"\"started\"",
":",
"(",
"True",
"if",
"self",
".",
"background_process",
"and",
"self",
".",
"background_process",
".",
"is_alive",
"(",
")",
"else",
"False",
")",
",",
"\"paused\"",
":",
"self",
... | Get general information about the state of the class | [
"Get",
"general",
"information",
"about",
"the",
"state",
"of",
"the",
"class"
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/tasker.py#L187-L195 |
cdgriffith/Reusables | reusables/tasker.py | Tasker.main_loop | def main_loop(self, stop_at_empty=False):
"""Blocking function that can be run directly, if so would probably
want to specify 'stop_at_empty' to true, or have a separate process
adding items to the queue. """
try:
while True:
self.hook_pre_command()
... | python | def main_loop(self, stop_at_empty=False):
"""Blocking function that can be run directly, if so would probably
want to specify 'stop_at_empty' to true, or have a separate process
adding items to the queue. """
try:
while True:
self.hook_pre_command()
... | [
"def",
"main_loop",
"(",
"self",
",",
"stop_at_empty",
"=",
"False",
")",
":",
"try",
":",
"while",
"True",
":",
"self",
".",
"hook_pre_command",
"(",
")",
"self",
".",
"_check_command_queue",
"(",
")",
"if",
"self",
".",
"run_until",
"and",
"self",
".",... | Blocking function that can be run directly, if so would probably
want to specify 'stop_at_empty' to true, or have a separate process
adding items to the queue. | [
"Blocking",
"function",
"that",
"can",
"be",
"run",
"directly",
"if",
"so",
"would",
"probably",
"want",
"to",
"specify",
"stop_at_empty",
"to",
"true",
"or",
"have",
"a",
"separate",
"process",
"adding",
"items",
"to",
"the",
"queue",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/tasker.py#L232-L269 |
cdgriffith/Reusables | reusables/tasker.py | Tasker.run | def run(self):
"""Start the main loop as a background process. *nix only"""
if win_based:
raise NotImplementedError("Please run main_loop, "
"backgrounding not supported on Windows")
self.background_process = mp.Process(target=self.main_loop)
... | python | def run(self):
"""Start the main loop as a background process. *nix only"""
if win_based:
raise NotImplementedError("Please run main_loop, "
"backgrounding not supported on Windows")
self.background_process = mp.Process(target=self.main_loop)
... | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"win_based",
":",
"raise",
"NotImplementedError",
"(",
"\"Please run main_loop, \"",
"\"backgrounding not supported on Windows\"",
")",
"self",
".",
"background_process",
"=",
"mp",
".",
"Process",
"(",
"target",
"=",
"self... | Start the main loop as a background process. *nix only | [
"Start",
"the",
"main",
"loop",
"as",
"a",
"background",
"process",
".",
"*",
"nix",
"only"
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/tasker.py#L271-L277 |
cdgriffith/Reusables | reusables/cli.py | cmd | def cmd(command, ignore_stderr=False, raise_on_return=False, timeout=None,
encoding="utf-8"):
""" Run a shell command and have it automatically decoded and printed
:param command: Command to run as str
:param ignore_stderr: To not print stderr
:param raise_on_return: Run CompletedProcess.check_... | python | def cmd(command, ignore_stderr=False, raise_on_return=False, timeout=None,
encoding="utf-8"):
""" Run a shell command and have it automatically decoded and printed
:param command: Command to run as str
:param ignore_stderr: To not print stderr
:param raise_on_return: Run CompletedProcess.check_... | [
"def",
"cmd",
"(",
"command",
",",
"ignore_stderr",
"=",
"False",
",",
"raise_on_return",
"=",
"False",
",",
"timeout",
"=",
"None",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"result",
"=",
"run",
"(",
"command",
",",
"timeout",
"=",
"timeout",
",",
... | Run a shell command and have it automatically decoded and printed
:param command: Command to run as str
:param ignore_stderr: To not print stderr
:param raise_on_return: Run CompletedProcess.check_returncode()
:param timeout: timeout to pass to communicate if python 3
:param encoding: How the outpu... | [
"Run",
"a",
"shell",
"command",
"and",
"have",
"it",
"automatically",
"decoded",
"and",
"printed"
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/cli.py#L29-L44 |
cdgriffith/Reusables | reusables/cli.py | pushd | def pushd(directory):
"""Change working directories in style and stay organized!
:param directory: Where do you want to go and remember?
:return: saved directory stack
"""
directory = os.path.expanduser(directory)
_saved_paths.insert(0, os.path.abspath(os.getcwd()))
os.chdir(directory)
... | python | def pushd(directory):
"""Change working directories in style and stay organized!
:param directory: Where do you want to go and remember?
:return: saved directory stack
"""
directory = os.path.expanduser(directory)
_saved_paths.insert(0, os.path.abspath(os.getcwd()))
os.chdir(directory)
... | [
"def",
"pushd",
"(",
"directory",
")",
":",
"directory",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"directory",
")",
"_saved_paths",
".",
"insert",
"(",
"0",
",",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
")"... | Change working directories in style and stay organized!
:param directory: Where do you want to go and remember?
:return: saved directory stack | [
"Change",
"working",
"directories",
"in",
"style",
"and",
"stay",
"organized!"
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/cli.py#L47-L56 |
cdgriffith/Reusables | reusables/cli.py | popd | def popd():
"""Go back to where you once were.
:return: saved directory stack
"""
try:
directory = _saved_paths.pop(0)
except IndexError:
return [os.getcwd()]
os.chdir(directory)
return [directory] + _saved_paths | python | def popd():
"""Go back to where you once were.
:return: saved directory stack
"""
try:
directory = _saved_paths.pop(0)
except IndexError:
return [os.getcwd()]
os.chdir(directory)
return [directory] + _saved_paths | [
"def",
"popd",
"(",
")",
":",
"try",
":",
"directory",
"=",
"_saved_paths",
".",
"pop",
"(",
"0",
")",
"except",
"IndexError",
":",
"return",
"[",
"os",
".",
"getcwd",
"(",
")",
"]",
"os",
".",
"chdir",
"(",
"directory",
")",
"return",
"[",
"direct... | Go back to where you once were.
:return: saved directory stack | [
"Go",
"back",
"to",
"where",
"you",
"once",
"were",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/cli.py#L59-L69 |
cdgriffith/Reusables | reusables/cli.py | ls | def ls(params="", directory=".", printed=True):
"""Know the best python implantation of ls? It's just to subprocess ls...
(uses dir on windows).
:param params: options to pass to ls or dir
:param directory: if not this directory
:param printed: If you're using this, you probably wanted it just prin... | python | def ls(params="", directory=".", printed=True):
"""Know the best python implantation of ls? It's just to subprocess ls...
(uses dir on windows).
:param params: options to pass to ls or dir
:param directory: if not this directory
:param printed: If you're using this, you probably wanted it just prin... | [
"def",
"ls",
"(",
"params",
"=",
"\"\"",
",",
"directory",
"=",
"\".\"",
",",
"printed",
"=",
"True",
")",
":",
"command",
"=",
"\"{0} {1} {2}\"",
".",
"format",
"(",
"\"ls\"",
"if",
"not",
"win_based",
"else",
"\"dir\"",
",",
"params",
",",
"directory",... | Know the best python implantation of ls? It's just to subprocess ls...
(uses dir on windows).
:param params: options to pass to ls or dir
:param directory: if not this directory
:param printed: If you're using this, you probably wanted it just printed
:return: if not printed, you can parse it yours... | [
"Know",
"the",
"best",
"python",
"implantation",
"of",
"ls?",
"It",
"s",
"just",
"to",
"subprocess",
"ls",
"...",
"(",
"uses",
"dir",
"on",
"windows",
")",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/cli.py#L85-L101 |
cdgriffith/Reusables | reusables/cli.py | find | def find(name=None, ext=None, directory=".", match_case=False,
disable_glob=False, depth=None):
""" Designed for the interactive interpreter by making default order
of find_files faster.
:param name: Part of the file name
:param ext: Extensions of the file you are looking for
:param direct... | python | def find(name=None, ext=None, directory=".", match_case=False,
disable_glob=False, depth=None):
""" Designed for the interactive interpreter by making default order
of find_files faster.
:param name: Part of the file name
:param ext: Extensions of the file you are looking for
:param direct... | [
"def",
"find",
"(",
"name",
"=",
"None",
",",
"ext",
"=",
"None",
",",
"directory",
"=",
"\".\"",
",",
"match_case",
"=",
"False",
",",
"disable_glob",
"=",
"False",
",",
"depth",
"=",
"None",
")",
":",
"return",
"find_files_list",
"(",
"directory",
"=... | Designed for the interactive interpreter by making default order
of find_files faster.
:param name: Part of the file name
:param ext: Extensions of the file you are looking for
:param directory: Top location to recursively search for matching files
:param match_case: If name has to be a direct matc... | [
"Designed",
"for",
"the",
"interactive",
"interpreter",
"by",
"making",
"default",
"order",
"of",
"find_files",
"faster",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/cli.py#L104-L119 |
cdgriffith/Reusables | reusables/cli.py | head | def head(file_path, lines=10, encoding="utf-8", printed=True,
errors='strict'):
"""
Read the first N lines of a file, defaults to 10
:param file_path: Path to file to read
:param lines: Number of lines to read in
:param encoding: defaults to utf-8 to decode as, will fail on binary
:par... | python | def head(file_path, lines=10, encoding="utf-8", printed=True,
errors='strict'):
"""
Read the first N lines of a file, defaults to 10
:param file_path: Path to file to read
:param lines: Number of lines to read in
:param encoding: defaults to utf-8 to decode as, will fail on binary
:par... | [
"def",
"head",
"(",
"file_path",
",",
"lines",
"=",
"10",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"printed",
"=",
"True",
",",
"errors",
"=",
"'strict'",
")",
":",
"data",
"=",
"[",
"]",
"with",
"open",
"(",
"file_path",
",",
"\"rb\"",
")",
"as",
"... | Read the first N lines of a file, defaults to 10
:param file_path: Path to file to read
:param lines: Number of lines to read in
:param encoding: defaults to utf-8 to decode as, will fail on binary
:param printed: Automatically print the lines instead of returning it
:param errors: Decoding errors:... | [
"Read",
"the",
"first",
"N",
"lines",
"of",
"a",
"file",
"defaults",
"to",
"10"
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/cli.py#L122-L147 |
cdgriffith/Reusables | reusables/cli.py | tail | def tail(file_path, lines=10, encoding="utf-8",
printed=True, errors='strict'):
"""
A really silly way to get the last N lines, defaults to 10.
:param file_path: Path to file to read
:param lines: Number of lines to read in
:param encoding: defaults to utf-8 to decode as, will fail on bin... | python | def tail(file_path, lines=10, encoding="utf-8",
printed=True, errors='strict'):
"""
A really silly way to get the last N lines, defaults to 10.
:param file_path: Path to file to read
:param lines: Number of lines to read in
:param encoding: defaults to utf-8 to decode as, will fail on bin... | [
"def",
"tail",
"(",
"file_path",
",",
"lines",
"=",
"10",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"printed",
"=",
"True",
",",
"errors",
"=",
"'strict'",
")",
":",
"data",
"=",
"deque",
"(",
")",
"with",
"open",
"(",
"file_path",
",",
"\"rb\"",
")",
... | A really silly way to get the last N lines, defaults to 10.
:param file_path: Path to file to read
:param lines: Number of lines to read in
:param encoding: defaults to utf-8 to decode as, will fail on binary
:param printed: Automatically print the lines instead of returning it
:param errors: Deco... | [
"A",
"really",
"silly",
"way",
"to",
"get",
"the",
"last",
"N",
"lines",
"defaults",
"to",
"10",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/cli.py#L175-L201 |
cdgriffith/Reusables | reusables/cli.py | cp | def cp(src, dst, overwrite=False):
"""
Copy files to a new location.
:param src: list (or string) of paths of files to copy
:param dst: file or folder to copy item(s) to
:param overwrite: IF the file already exists, should I overwrite it?
"""
if not isinstance(src, list):
src = [sr... | python | def cp(src, dst, overwrite=False):
"""
Copy files to a new location.
:param src: list (or string) of paths of files to copy
:param dst: file or folder to copy item(s) to
:param overwrite: IF the file already exists, should I overwrite it?
"""
if not isinstance(src, list):
src = [sr... | [
"def",
"cp",
"(",
"src",
",",
"dst",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"src",
",",
"list",
")",
":",
"src",
"=",
"[",
"src",
"]",
"dst",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"dst",
")",
"dst_fo... | Copy files to a new location.
:param src: list (or string) of paths of files to copy
:param dst: file or folder to copy item(s) to
:param overwrite: IF the file already exists, should I overwrite it? | [
"Copy",
"files",
"to",
"a",
"new",
"location",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/cli.py#L204-L231 |
cdgriffith/Reusables | reusables/string_manipulation.py | cut | def cut(string, characters=2, trailing="normal"):
"""
Split a string into a list of N characters each.
.. code:: python
reusables.cut("abcdefghi")
# ['ab', 'cd', 'ef', 'gh', 'i']
trailing gives you the following options:
* normal: leaves remaining characters in their own last pos... | python | def cut(string, characters=2, trailing="normal"):
"""
Split a string into a list of N characters each.
.. code:: python
reusables.cut("abcdefghi")
# ['ab', 'cd', 'ef', 'gh', 'i']
trailing gives you the following options:
* normal: leaves remaining characters in their own last pos... | [
"def",
"cut",
"(",
"string",
",",
"characters",
"=",
"2",
",",
"trailing",
"=",
"\"normal\"",
")",
":",
"split_str",
"=",
"[",
"string",
"[",
"i",
":",
"i",
"+",
"characters",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"string",
"... | Split a string into a list of N characters each.
.. code:: python
reusables.cut("abcdefghi")
# ['ab', 'cd', 'ef', 'gh', 'i']
trailing gives you the following options:
* normal: leaves remaining characters in their own last position
* remove: return the list without the remainder char... | [
"Split",
"a",
"string",
"into",
"a",
"list",
"of",
"N",
"characters",
"each",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/string_manipulation.py#L24-L69 |
cdgriffith/Reusables | reusables/string_manipulation.py | int_to_roman | def int_to_roman(integer):
"""
Convert an integer into a string of roman numbers.
.. code: python
reusables.int_to_roman(445)
# 'CDXLV'
:param integer:
:return: roman string
"""
if not isinstance(integer, int):
raise ValueError("Input integer must be of type int")... | python | def int_to_roman(integer):
"""
Convert an integer into a string of roman numbers.
.. code: python
reusables.int_to_roman(445)
# 'CDXLV'
:param integer:
:return: roman string
"""
if not isinstance(integer, int):
raise ValueError("Input integer must be of type int")... | [
"def",
"int_to_roman",
"(",
"integer",
")",
":",
"if",
"not",
"isinstance",
"(",
"integer",
",",
"int",
")",
":",
"raise",
"ValueError",
"(",
"\"Input integer must be of type int\"",
")",
"output",
"=",
"[",
"]",
"while",
"integer",
">",
"0",
":",
"for",
"... | Convert an integer into a string of roman numbers.
.. code: python
reusables.int_to_roman(445)
# 'CDXLV'
:param integer:
:return: roman string | [
"Convert",
"an",
"integer",
"into",
"a",
"string",
"of",
"roman",
"numbers",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/string_manipulation.py#L72-L94 |
cdgriffith/Reusables | reusables/string_manipulation.py | roman_to_int | def roman_to_int(roman_string):
"""
Converts a string of roman numbers into an integer.
.. code: python
reusables.roman_to_int("XXXVI")
# 36
:param roman_string: XVI or similar
:return: parsed integer
"""
roman_string = roman_string.upper().strip()
if "IIII" in roman_... | python | def roman_to_int(roman_string):
"""
Converts a string of roman numbers into an integer.
.. code: python
reusables.roman_to_int("XXXVI")
# 36
:param roman_string: XVI or similar
:return: parsed integer
"""
roman_string = roman_string.upper().strip()
if "IIII" in roman_... | [
"def",
"roman_to_int",
"(",
"roman_string",
")",
":",
"roman_string",
"=",
"roman_string",
".",
"upper",
"(",
")",
".",
"strip",
"(",
")",
"if",
"\"IIII\"",
"in",
"roman_string",
":",
"raise",
"ValueError",
"(",
"\"Malformed roman string\"",
")",
"value",
"=",... | Converts a string of roman numbers into an integer.
.. code: python
reusables.roman_to_int("XXXVI")
# 36
:param roman_string: XVI or similar
:return: parsed integer | [
"Converts",
"a",
"string",
"of",
"roman",
"numbers",
"into",
"an",
"integer",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/string_manipulation.py#L97-L135 |
cdgriffith/Reusables | reusables/string_manipulation.py | int_to_words | def int_to_words(number, european=False):
"""
Converts an integer or float to words.
.. code: python
reusables.int_to_number(445)
# 'four hundred forty-five'
reusables.int_to_number(1.45)
# 'one and forty-five hundredths'
:param number: String, integer, or float to co... | python | def int_to_words(number, european=False):
"""
Converts an integer or float to words.
.. code: python
reusables.int_to_number(445)
# 'four hundred forty-five'
reusables.int_to_number(1.45)
# 'one and forty-five hundredths'
:param number: String, integer, or float to co... | [
"def",
"int_to_words",
"(",
"number",
",",
"european",
"=",
"False",
")",
":",
"def",
"ones",
"(",
"n",
")",
":",
"return",
"\"\"",
"if",
"n",
"==",
"0",
"else",
"_numbers",
"[",
"n",
"]",
"def",
"tens",
"(",
"n",
")",
":",
"teen",
"=",
"int",
... | Converts an integer or float to words.
.. code: python
reusables.int_to_number(445)
# 'four hundred forty-five'
reusables.int_to_number(1.45)
# 'one and forty-five hundredths'
:param number: String, integer, or float to convert to words. The decimal
can only be up to ... | [
"Converts",
"an",
"integer",
"or",
"float",
"to",
"words",
"."
] | train | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/string_manipulation.py#L138-L247 |
aicenter/roadmap-processing | roadmaptools/osmfilter.py | filter_osm_file | def filter_osm_file():
""" Downloads (and compiles) osmfilter tool from web and
calls that osmfilter to only filter out only the road elements.
"""
print_info('Filtering OSM file...')
start_time = time.time()
if check_osmfilter():
# params = '--keep="highway=motorway =motorway... | python | def filter_osm_file():
""" Downloads (and compiles) osmfilter tool from web and
calls that osmfilter to only filter out only the road elements.
"""
print_info('Filtering OSM file...')
start_time = time.time()
if check_osmfilter():
# params = '--keep="highway=motorway =motorway... | [
"def",
"filter_osm_file",
"(",
")",
":",
"print_info",
"(",
"'Filtering OSM file...'",
")",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"if",
"check_osmfilter",
"(",
")",
":",
"# params = '--keep=\"highway=motorway =motorway_link =trunk =trunk_link =primary =primary_l... | Downloads (and compiles) osmfilter tool from web and
calls that osmfilter to only filter out only the road elements. | [
"Downloads",
"(",
"and",
"compiles",
")",
"osmfilter",
"tool",
"from",
"web",
"and",
"calls",
"that",
"osmfilter",
"to",
"only",
"filter",
"out",
"only",
"the",
"road",
"elements",
"."
] | train | https://github.com/aicenter/roadmap-processing/blob/d9fb6e0b3bc1f11302a9e2ac62ee6db9484e2018/roadmaptools/osmfilter.py#L10-L37 |
Koed00/django-rq-jobs | django_rq_jobs/models.py | task_list | def task_list():
"""
Scans the modules set in RQ_JOBS_MODULES for RQ jobs decorated with @task
Compiles a readable list for Job model task choices
"""
try:
jobs_module = settings.RQ_JOBS_MODULE
except AttributeError:
raise ImproperlyConfigured(_("You have to define RQ_JOBS_MODULE... | python | def task_list():
"""
Scans the modules set in RQ_JOBS_MODULES for RQ jobs decorated with @task
Compiles a readable list for Job model task choices
"""
try:
jobs_module = settings.RQ_JOBS_MODULE
except AttributeError:
raise ImproperlyConfigured(_("You have to define RQ_JOBS_MODULE... | [
"def",
"task_list",
"(",
")",
":",
"try",
":",
"jobs_module",
"=",
"settings",
".",
"RQ_JOBS_MODULE",
"except",
"AttributeError",
":",
"raise",
"ImproperlyConfigured",
"(",
"_",
"(",
"\"You have to define RQ_JOBS_MODULE in settings.py\"",
")",
")",
"if",
"isinstance",... | Scans the modules set in RQ_JOBS_MODULES for RQ jobs decorated with @task
Compiles a readable list for Job model task choices | [
"Scans",
"the",
"modules",
"set",
"in",
"RQ_JOBS_MODULES",
"for",
"RQ",
"jobs",
"decorated",
"with"
] | train | https://github.com/Koed00/django-rq-jobs/blob/b25ffd15c91858406494ae0c29babf00c268db18/django_rq_jobs/models.py#L33-L65 |
Koed00/django-rq-jobs | django_rq_jobs/models.py | Job.rq_job | def rq_job(self):
"""The last RQ Job this ran on"""
if not self.rq_id or not self.rq_origin:
return
try:
return RQJob.fetch(self.rq_id, connection=get_connection(self.rq_origin))
except NoSuchJobError:
return | python | def rq_job(self):
"""The last RQ Job this ran on"""
if not self.rq_id or not self.rq_origin:
return
try:
return RQJob.fetch(self.rq_id, connection=get_connection(self.rq_origin))
except NoSuchJobError:
return | [
"def",
"rq_job",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"rq_id",
"or",
"not",
"self",
".",
"rq_origin",
":",
"return",
"try",
":",
"return",
"RQJob",
".",
"fetch",
"(",
"self",
".",
"rq_id",
",",
"connection",
"=",
"get_connection",
"(",
"s... | The last RQ Job this ran on | [
"The",
"last",
"RQ",
"Job",
"this",
"ran",
"on"
] | train | https://github.com/Koed00/django-rq-jobs/blob/b25ffd15c91858406494ae0c29babf00c268db18/django_rq_jobs/models.py#L95-L102 |
Koed00/django-rq-jobs | django_rq_jobs/models.py | Job.rq_link | def rq_link(self):
"""Link to Django-RQ status page for this job"""
if self.rq_job:
url = reverse('rq_job_detail',
kwargs={'job_id': self.rq_id, 'queue_index': queue_index_by_name(self.rq_origin)})
return '<a href="{}">{}</a>'.format(url, self.rq_id) | python | def rq_link(self):
"""Link to Django-RQ status page for this job"""
if self.rq_job:
url = reverse('rq_job_detail',
kwargs={'job_id': self.rq_id, 'queue_index': queue_index_by_name(self.rq_origin)})
return '<a href="{}">{}</a>'.format(url, self.rq_id) | [
"def",
"rq_link",
"(",
"self",
")",
":",
"if",
"self",
".",
"rq_job",
":",
"url",
"=",
"reverse",
"(",
"'rq_job_detail'",
",",
"kwargs",
"=",
"{",
"'job_id'",
":",
"self",
".",
"rq_id",
",",
"'queue_index'",
":",
"queue_index_by_name",
"(",
"self",
".",
... | Link to Django-RQ status page for this job | [
"Link",
"to",
"Django",
"-",
"RQ",
"status",
"page",
"for",
"this",
"job"
] | train | https://github.com/Koed00/django-rq-jobs/blob/b25ffd15c91858406494ae0c29babf00c268db18/django_rq_jobs/models.py#L109-L114 |
Koed00/django-rq-jobs | django_rq_jobs/models.py | Job.rq_task | def rq_task(self):
"""
The function to call for this task.
Config errors are caught by tasks_list() already.
"""
task_path = self.task.split('.')
module_name = '.'.join(task_path[:-1])
task_name = task_path[-1]
module = importlib.import_module(module_name... | python | def rq_task(self):
"""
The function to call for this task.
Config errors are caught by tasks_list() already.
"""
task_path = self.task.split('.')
module_name = '.'.join(task_path[:-1])
task_name = task_path[-1]
module = importlib.import_module(module_name... | [
"def",
"rq_task",
"(",
"self",
")",
":",
"task_path",
"=",
"self",
".",
"task",
".",
"split",
"(",
"'.'",
")",
"module_name",
"=",
"'.'",
".",
"join",
"(",
"task_path",
"[",
":",
"-",
"1",
"]",
")",
"task_name",
"=",
"task_path",
"[",
"-",
"1",
"... | The function to call for this task.
Config errors are caught by tasks_list() already. | [
"The",
"function",
"to",
"call",
"for",
"this",
"task",
".",
"Config",
"errors",
"are",
"caught",
"by",
"tasks_list",
"()",
"already",
"."
] | train | https://github.com/Koed00/django-rq-jobs/blob/b25ffd15c91858406494ae0c29babf00c268db18/django_rq_jobs/models.py#L117-L127 |
Koed00/django-rq-jobs | django_rq_jobs/management/commands/rqjobs.py | fix_module | def fix_module(job):
"""
Fix for tasks without a module. Provides backwards compatibility with < 0.1.5
"""
modules = settings.RQ_JOBS_MODULE
if not type(modules) == tuple:
modules = [modules]
for module in modules:
try:
module_match = importlib.import_module(module)
... | python | def fix_module(job):
"""
Fix for tasks without a module. Provides backwards compatibility with < 0.1.5
"""
modules = settings.RQ_JOBS_MODULE
if not type(modules) == tuple:
modules = [modules]
for module in modules:
try:
module_match = importlib.import_module(module)
... | [
"def",
"fix_module",
"(",
"job",
")",
":",
"modules",
"=",
"settings",
".",
"RQ_JOBS_MODULE",
"if",
"not",
"type",
"(",
"modules",
")",
"==",
"tuple",
":",
"modules",
"=",
"[",
"modules",
"]",
"for",
"module",
"in",
"modules",
":",
"try",
":",
"module_... | Fix for tasks without a module. Provides backwards compatibility with < 0.1.5 | [
"Fix",
"for",
"tasks",
"without",
"a",
"module",
".",
"Provides",
"backwards",
"compatibility",
"with",
"<",
"0",
".",
"1",
".",
"5"
] | train | https://github.com/Koed00/django-rq-jobs/blob/b25ffd15c91858406494ae0c29babf00c268db18/django_rq_jobs/management/commands/rqjobs.py#L59-L74 |
Python-Tools/aioorm | aioorm/database.py | drop_model_tables | async def drop_model_tables(models, **drop_table_kwargs):
"""Drop tables for all given models (in the right order)."""
for m in reversed(sort_models_topologically(models)):
await m.drop_table(**drop_table_kwargs) | python | async def drop_model_tables(models, **drop_table_kwargs):
"""Drop tables for all given models (in the right order)."""
for m in reversed(sort_models_topologically(models)):
await m.drop_table(**drop_table_kwargs) | [
"async",
"def",
"drop_model_tables",
"(",
"models",
",",
"*",
"*",
"drop_table_kwargs",
")",
":",
"for",
"m",
"in",
"reversed",
"(",
"sort_models_topologically",
"(",
"models",
")",
")",
":",
"await",
"m",
".",
"drop_table",
"(",
"*",
"*",
"drop_table_kwargs... | Drop tables for all given models (in the right order). | [
"Drop",
"tables",
"for",
"all",
"given",
"models",
"(",
"in",
"the",
"right",
"order",
")",
"."
] | train | https://github.com/Python-Tools/aioorm/blob/f305e253ce748cda91b8bc9ec9c6b56e0e7681f7/aioorm/database.py#L244-L247 |
Python-Tools/aioorm | aioorm/shortcuts.py | model_to_dict | async def model_to_dict(model, recurse=True, backrefs=False, only=None,
exclude=None, seen=None, extra_attrs=None,
fields_from_query=None, max_depth=None):
"""
Convert a model instance (and any related objects) to a dictionary.
:param bool recurse: Whether for... | python | async def model_to_dict(model, recurse=True, backrefs=False, only=None,
exclude=None, seen=None, extra_attrs=None,
fields_from_query=None, max_depth=None):
"""
Convert a model instance (and any related objects) to a dictionary.
:param bool recurse: Whether for... | [
"async",
"def",
"model_to_dict",
"(",
"model",
",",
"recurse",
"=",
"True",
",",
"backrefs",
"=",
"False",
",",
"only",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"seen",
"=",
"None",
",",
"extra_attrs",
"=",
"None",
",",
"fields_from_query",
"=",
... | Convert a model instance (and any related objects) to a dictionary.
:param bool recurse: Whether foreign-keys should be recursed.
:param bool backrefs: Whether lists of related objects should be recursed.
:param only: A list (or set) of field instances indicating which fields
should be included.
... | [
"Convert",
"a",
"model",
"instance",
"(",
"and",
"any",
"related",
"objects",
")",
"to",
"a",
"dictionary",
".",
":",
"param",
"bool",
"recurse",
":",
"Whether",
"foreign",
"-",
"keys",
"should",
"be",
"recursed",
".",
":",
"param",
"bool",
"backrefs",
"... | train | https://github.com/Python-Tools/aioorm/blob/f305e253ce748cda91b8bc9ec9c6b56e0e7681f7/aioorm/shortcuts.py#L6-L101 |
Python-Tools/aioorm | aioorm/utils/csv_utils/csv_loader.py | RowConverter.extract_rows | async def extract_rows(self, file_or_name, **reader_kwargs):
"""
Extract `self.sample_size` rows from the CSV file and analyze their
data-types.
:param str file_or_name: A string filename or a file handle.
:param reader_kwargs: Arbitrary parameters to pass to the CSV reader.
... | python | async def extract_rows(self, file_or_name, **reader_kwargs):
"""
Extract `self.sample_size` rows from the CSV file and analyze their
data-types.
:param str file_or_name: A string filename or a file handle.
:param reader_kwargs: Arbitrary parameters to pass to the CSV reader.
... | [
"async",
"def",
"extract_rows",
"(",
"self",
",",
"file_or_name",
",",
"*",
"*",
"reader_kwargs",
")",
":",
"rows",
"=",
"[",
"]",
"rows_to_read",
"=",
"self",
".",
"sample_size",
"async",
"with",
"self",
".",
"get_reader",
"(",
"file_or_name",
",",
"*",
... | Extract `self.sample_size` rows from the CSV file and analyze their
data-types.
:param str file_or_name: A string filename or a file handle.
:param reader_kwargs: Arbitrary parameters to pass to the CSV reader.
:returns: A 2-tuple containing a list of headers and list of rows
... | [
"Extract",
"self",
".",
"sample_size",
"rows",
"from",
"the",
"CSV",
"file",
"and",
"analyze",
"their",
"data",
"-",
"types",
".",
":",
"param",
"str",
"file_or_name",
":",
"A",
"string",
"filename",
"or",
"a",
"file",
"handle",
".",
":",
"param",
"reade... | train | https://github.com/Python-Tools/aioorm/blob/f305e253ce748cda91b8bc9ec9c6b56e0e7681f7/aioorm/utils/csv_utils/csv_loader.py#L123-L150 |
Python-Tools/aioorm | aioorm/utils/csv_utils/csv_loader.py | RowConverter.get_checks | def get_checks(self):
"""Return a list of functions to use when testing values."""
return [
self.is_date,
self.is_datetime,
self.is_integer,
self.is_float,
self.default] | python | def get_checks(self):
"""Return a list of functions to use when testing values."""
return [
self.is_date,
self.is_datetime,
self.is_integer,
self.is_float,
self.default] | [
"def",
"get_checks",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"is_date",
",",
"self",
".",
"is_datetime",
",",
"self",
".",
"is_integer",
",",
"self",
".",
"is_float",
",",
"self",
".",
"default",
"]"
] | Return a list of functions to use when testing values. | [
"Return",
"a",
"list",
"of",
"functions",
"to",
"use",
"when",
"testing",
"values",
"."
] | train | https://github.com/Python-Tools/aioorm/blob/f305e253ce748cda91b8bc9ec9c6b56e0e7681f7/aioorm/utils/csv_utils/csv_loader.py#L152-L159 |
Python-Tools/aioorm | aioorm/utils/csv_utils/csv_loader.py | RowConverter.analyze | def analyze(self, rows):
"""
Analyze the given rows and try to determine the type of value stored.
:param list rows: A list-of-lists containing one or more rows from a
csv file.
:returns: A list of peewee Field objects for each column in the CSV.
"""
... | python | def analyze(self, rows):
"""
Analyze the given rows and try to determine the type of value stored.
:param list rows: A list-of-lists containing one or more rows from a
csv file.
:returns: A list of peewee Field objects for each column in the CSV.
"""
... | [
"def",
"analyze",
"(",
"self",
",",
"rows",
")",
":",
"transposed",
"=",
"zip",
"(",
"*",
"rows",
")",
"checks",
"=",
"self",
".",
"get_checks",
"(",
")",
"column_types",
"=",
"[",
"]",
"for",
"i",
",",
"column",
"in",
"enumerate",
"(",
"transposed",... | Analyze the given rows and try to determine the type of value stored.
:param list rows: A list-of-lists containing one or more rows from a
csv file.
:returns: A list of peewee Field objects for each column in the CSV. | [
"Analyze",
"the",
"given",
"rows",
"and",
"try",
"to",
"determine",
"the",
"type",
"of",
"value",
"stored",
".",
":",
"param",
"list",
"rows",
":",
"A",
"list",
"-",
"of",
"-",
"lists",
"containing",
"one",
"or",
"more",
"rows",
"from",
"a",
"csv",
"... | train | https://github.com/Python-Tools/aioorm/blob/f305e253ce748cda91b8bc9ec9c6b56e0e7681f7/aioorm/utils/csv_utils/csv_loader.py#L161-L180 |
BetterWorks/django-bleachfields | bleachfields/bleachfield.py | BleachField.clean_text | def clean_text(self, text):
'''Clean text using bleach.'''
if text is None:
return ''
text = re.sub(ILLEGAL_CHARACTERS_RE, '', text)
if '<' in text or '<' in text:
text = clean(text, tags=self.tags, strip=self.strip)
return unescape(text) | python | def clean_text(self, text):
'''Clean text using bleach.'''
if text is None:
return ''
text = re.sub(ILLEGAL_CHARACTERS_RE, '', text)
if '<' in text or '<' in text:
text = clean(text, tags=self.tags, strip=self.strip)
return unescape(text) | [
"def",
"clean_text",
"(",
"self",
",",
"text",
")",
":",
"if",
"text",
"is",
"None",
":",
"return",
"''",
"text",
"=",
"re",
".",
"sub",
"(",
"ILLEGAL_CHARACTERS_RE",
",",
"''",
",",
"text",
")",
"if",
"'<'",
"in",
"text",
"or",
"'<'",
"in",
"tex... | Clean text using bleach. | [
"Clean",
"text",
"using",
"bleach",
"."
] | train | https://github.com/BetterWorks/django-bleachfields/blob/6b49aad6daa8c1357af31a2f7941352561d04cd6/bleachfields/bleachfield.py#L26-L34 |
nwilming/ocupy | ocupy/loader.py | LoadFromDisk.path | def path(self, category = None, image = None, feature = None):
"""
Constructs the path to categories, images and features.
This path function assumes that the following storage scheme is used on
the hard disk to access categories, images and features:
- categories: /impath/categor... | python | def path(self, category = None, image = None, feature = None):
"""
Constructs the path to categories, images and features.
This path function assumes that the following storage scheme is used on
the hard disk to access categories, images and features:
- categories: /impath/categor... | [
"def",
"path",
"(",
"self",
",",
"category",
"=",
"None",
",",
"image",
"=",
"None",
",",
"feature",
"=",
"None",
")",
":",
"filename",
"=",
"None",
"if",
"not",
"category",
"is",
"None",
":",
"filename",
"=",
"join",
"(",
"self",
".",
"impath",
",... | Constructs the path to categories, images and features.
This path function assumes that the following storage scheme is used on
the hard disk to access categories, images and features:
- categories: /impath/category
- images: /impath/category/category_image.png
-... | [
"Constructs",
"the",
"path",
"to",
"categories",
"images",
"and",
"features",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/loader.py#L168-L195 |
nwilming/ocupy | ocupy/loader.py | LoadFromDisk.get_image | def get_image(self, cat, img):
""" Loads an image from disk. """
filename = self.path(cat, img)
data = []
if filename.endswith('mat'):
data = loadmat(filename)['output']
else:
data = imread(filename)
if self.size is not None:
return imr... | python | def get_image(self, cat, img):
""" Loads an image from disk. """
filename = self.path(cat, img)
data = []
if filename.endswith('mat'):
data = loadmat(filename)['output']
else:
data = imread(filename)
if self.size is not None:
return imr... | [
"def",
"get_image",
"(",
"self",
",",
"cat",
",",
"img",
")",
":",
"filename",
"=",
"self",
".",
"path",
"(",
"cat",
",",
"img",
")",
"data",
"=",
"[",
"]",
"if",
"filename",
".",
"endswith",
"(",
"'mat'",
")",
":",
"data",
"=",
"loadmat",
"(",
... | Loads an image from disk. | [
"Loads",
"an",
"image",
"from",
"disk",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/loader.py#L197-L208 |
nwilming/ocupy | ocupy/loader.py | LoadFromDisk.get_feature | def get_feature(self, cat, img, feature):
"""
Load a feature from disk.
"""
filename = self.path(cat, img, feature)
data = loadmat(filename)
name = [k for k in list(data.keys()) if not k.startswith('__')]
if self.size is not None:
return imresize(data[... | python | def get_feature(self, cat, img, feature):
"""
Load a feature from disk.
"""
filename = self.path(cat, img, feature)
data = loadmat(filename)
name = [k for k in list(data.keys()) if not k.startswith('__')]
if self.size is not None:
return imresize(data[... | [
"def",
"get_feature",
"(",
"self",
",",
"cat",
",",
"img",
",",
"feature",
")",
":",
"filename",
"=",
"self",
".",
"path",
"(",
"cat",
",",
"img",
",",
"feature",
")",
"data",
"=",
"loadmat",
"(",
"filename",
")",
"name",
"=",
"[",
"k",
"for",
"k... | Load a feature from disk. | [
"Load",
"a",
"feature",
"from",
"disk",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/loader.py#L210-L219 |
nwilming/ocupy | ocupy/loader.py | SaveToDisk.save_image | def save_image(self, cat, img, data):
"""Saves a new image."""
filename = self.path(cat, img)
mkdir(filename)
if type(data) == np.ndarray:
data = Image.fromarray(data).convert('RGB')
data.save(filename) | python | def save_image(self, cat, img, data):
"""Saves a new image."""
filename = self.path(cat, img)
mkdir(filename)
if type(data) == np.ndarray:
data = Image.fromarray(data).convert('RGB')
data.save(filename) | [
"def",
"save_image",
"(",
"self",
",",
"cat",
",",
"img",
",",
"data",
")",
":",
"filename",
"=",
"self",
".",
"path",
"(",
"cat",
",",
"img",
")",
"mkdir",
"(",
"filename",
")",
"if",
"type",
"(",
"data",
")",
"==",
"np",
".",
"ndarray",
":",
... | Saves a new image. | [
"Saves",
"a",
"new",
"image",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/loader.py#L243-L249 |
nwilming/ocupy | ocupy/loader.py | SaveToDisk.save_feature | def save_feature(self, cat, img, feature, data):
"""Saves a new feature."""
filename = self.path(cat, img, feature)
mkdir(filename)
savemat(filename, {'output':data}) | python | def save_feature(self, cat, img, feature, data):
"""Saves a new feature."""
filename = self.path(cat, img, feature)
mkdir(filename)
savemat(filename, {'output':data}) | [
"def",
"save_feature",
"(",
"self",
",",
"cat",
",",
"img",
",",
"feature",
",",
"data",
")",
":",
"filename",
"=",
"self",
".",
"path",
"(",
"cat",
",",
"img",
",",
"feature",
")",
"mkdir",
"(",
"filename",
")",
"savemat",
"(",
"filename",
",",
"{... | Saves a new feature. | [
"Saves",
"a",
"new",
"feature",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/loader.py#L251-L255 |
nwilming/ocupy | ocupy/datamat_tools.py | factorise_field | def factorise_field(dm, field_name, boundary_char = None, parameter_name=None):
"""This removes a common beginning from the data of the fields, placing
the common element in a parameter and the different endings in the fields.
if parameter_name is None, then it will be <field_name>_common.
So ... | python | def factorise_field(dm, field_name, boundary_char = None, parameter_name=None):
"""This removes a common beginning from the data of the fields, placing
the common element in a parameter and the different endings in the fields.
if parameter_name is None, then it will be <field_name>_common.
So ... | [
"def",
"factorise_field",
"(",
"dm",
",",
"field_name",
",",
"boundary_char",
"=",
"None",
",",
"parameter_name",
"=",
"None",
")",
":",
"old_data",
"=",
"dm",
".",
"field",
"(",
"field_name",
")",
"if",
"isinstance",
"(",
"old_data",
"[",
"0",
"]",
",",... | This removes a common beginning from the data of the fields, placing
the common element in a parameter and the different endings in the fields.
if parameter_name is None, then it will be <field_name>_common.
So far, it's probably only useful for the file_name.
TODO: remove field entirely ... | [
"This",
"removes",
"a",
"common",
"beginning",
"from",
"the",
"data",
"of",
"the",
"fields",
"placing",
"the",
"common",
"element",
"in",
"a",
"parameter",
"and",
"the",
"different",
"endings",
"in",
"the",
"fields",
".",
"if",
"parameter_name",
"is",
"None"... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/datamat_tools.py#L11-L34 |
nwilming/ocupy | ocupy/utils.py | randsample | def randsample(vec, nr_samples, with_replacement = False):
"""
Draws nr_samples random samples from vec.
"""
if not with_replacement:
return np.random.permutation(vec)[0:nr_samples]
else:
return np.asarray(vec)[np.random.randint(0, len(vec), nr_samples)] | python | def randsample(vec, nr_samples, with_replacement = False):
"""
Draws nr_samples random samples from vec.
"""
if not with_replacement:
return np.random.permutation(vec)[0:nr_samples]
else:
return np.asarray(vec)[np.random.randint(0, len(vec), nr_samples)] | [
"def",
"randsample",
"(",
"vec",
",",
"nr_samples",
",",
"with_replacement",
"=",
"False",
")",
":",
"if",
"not",
"with_replacement",
":",
"return",
"np",
".",
"random",
".",
"permutation",
"(",
"vec",
")",
"[",
"0",
":",
"nr_samples",
"]",
"else",
":",
... | Draws nr_samples random samples from vec. | [
"Draws",
"nr_samples",
"random",
"samples",
"from",
"vec",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/utils.py#L63-L70 |
nwilming/ocupy | ocupy/utils.py | calc_resize_factor | def calc_resize_factor(prediction, image_size):
"""
Calculates how much prediction.shape and image_size differ.
"""
resize_factor_x = prediction.shape[1] / float(image_size[1])
resize_factor_y = prediction.shape[0] / float(image_size[0])
if abs(resize_factor_x - resize_factor_y) > 1.0/image_size... | python | def calc_resize_factor(prediction, image_size):
"""
Calculates how much prediction.shape and image_size differ.
"""
resize_factor_x = prediction.shape[1] / float(image_size[1])
resize_factor_y = prediction.shape[0] / float(image_size[0])
if abs(resize_factor_x - resize_factor_y) > 1.0/image_size... | [
"def",
"calc_resize_factor",
"(",
"prediction",
",",
"image_size",
")",
":",
"resize_factor_x",
"=",
"prediction",
".",
"shape",
"[",
"1",
"]",
"/",
"float",
"(",
"image_size",
"[",
"1",
"]",
")",
"resize_factor_y",
"=",
"prediction",
".",
"shape",
"[",
"0... | Calculates how much prediction.shape and image_size differ. | [
"Calculates",
"how",
"much",
"prediction",
".",
"shape",
"and",
"image_size",
"differ",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/utils.py#L78-L88 |
nwilming/ocupy | ocupy/utils.py | dict_2_mat | def dict_2_mat(data, fill = True):
"""
Creates a NumPy array from a dictionary with only integers as keys and
NumPy arrays as values. Dimension 0 of the resulting array is formed from
data.keys(). Missing values in keys can be filled up with np.nan (default)
or ignored.
Parameters
---------... | python | def dict_2_mat(data, fill = True):
"""
Creates a NumPy array from a dictionary with only integers as keys and
NumPy arrays as values. Dimension 0 of the resulting array is formed from
data.keys(). Missing values in keys can be filled up with np.nan (default)
or ignored.
Parameters
---------... | [
"def",
"dict_2_mat",
"(",
"data",
",",
"fill",
"=",
"True",
")",
":",
"if",
"any",
"(",
"[",
"type",
"(",
"k",
")",
"!=",
"int",
"for",
"k",
"in",
"list",
"(",
"data",
".",
"keys",
"(",
")",
")",
"]",
")",
":",
"raise",
"RuntimeError",
"(",
"... | Creates a NumPy array from a dictionary with only integers as keys and
NumPy arrays as values. Dimension 0 of the resulting array is formed from
data.keys(). Missing values in keys can be filled up with np.nan (default)
or ignored.
Parameters
----------
data : dict
a dictionary with int... | [
"Creates",
"a",
"NumPy",
"array",
"from",
"a",
"dictionary",
"with",
"only",
"integers",
"as",
"keys",
"and",
"NumPy",
"arrays",
"as",
"values",
".",
"Dimension",
"0",
"of",
"the",
"resulting",
"array",
"is",
"formed",
"from",
"data",
".",
"keys",
"()",
... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/utils.py#L90-L128 |
nwilming/ocupy | ocupy/utils.py | dict_fun | def dict_fun(data, function):
"""
Apply a function to all values in a dictionary, return a dictionary with
results.
Parameters
----------
data : dict
a dictionary whose values are adequate input to the second argument
of this function.
function : function
a function... | python | def dict_fun(data, function):
"""
Apply a function to all values in a dictionary, return a dictionary with
results.
Parameters
----------
data : dict
a dictionary whose values are adequate input to the second argument
of this function.
function : function
a function... | [
"def",
"dict_fun",
"(",
"data",
",",
"function",
")",
":",
"return",
"dict",
"(",
"(",
"k",
",",
"function",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"data",
".",
"items",
"(",
")",
")",
")"
] | Apply a function to all values in a dictionary, return a dictionary with
results.
Parameters
----------
data : dict
a dictionary whose values are adequate input to the second argument
of this function.
function : function
a function that takes one argument
Returns
... | [
"Apply",
"a",
"function",
"to",
"all",
"values",
"in",
"a",
"dictionary",
"return",
"a",
"dictionary",
"with",
"results",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/utils.py#L130-L148 |
nwilming/ocupy | ocupy/utils.py | snip_string_middle | def snip_string_middle(string, max_len=20, snip_string='...'):
"""
>>> snip_string_middle('this is long', 8)
'th...ong'
>>> snip_string_middle('this is long', 12)
'this is long'
>>> snip_string_middle('this is long', 8, '~')
'thi~long'
"""
#warn('use snip_string() instead', Dep... | python | def snip_string_middle(string, max_len=20, snip_string='...'):
"""
>>> snip_string_middle('this is long', 8)
'th...ong'
>>> snip_string_middle('this is long', 12)
'this is long'
>>> snip_string_middle('this is long', 8, '~')
'thi~long'
"""
#warn('use snip_string() instead', Dep... | [
"def",
"snip_string_middle",
"(",
"string",
",",
"max_len",
"=",
"20",
",",
"snip_string",
"=",
"'...'",
")",
":",
"#warn('use snip_string() instead', DeprecationWarning)",
"if",
"len",
"(",
"string",
")",
"<=",
"max_len",
":",
"new_string",
"=",
"string",
"else",... | >>> snip_string_middle('this is long', 8)
'th...ong'
>>> snip_string_middle('this is long', 12)
'this is long'
>>> snip_string_middle('this is long', 8, '~')
'thi~long' | [
">>>",
"snip_string_middle",
"(",
"this",
"is",
"long",
"8",
")",
"th",
"...",
"ong",
">>>",
"snip_string_middle",
"(",
"this",
"is",
"long",
"12",
")",
"this",
"is",
"long",
">>>",
"snip_string_middle",
"(",
"this",
"is",
"long",
"8",
"~",
")",
"thi~lon... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/utils.py#L150-L171 |
nwilming/ocupy | ocupy/utils.py | snip_string | def snip_string(string, max_len=20, snip_string='...', snip_point=0.5):
"""
Snips a string so that it is no longer than max_len, replacing deleted
characters with the snip_string.
The snip is done at snip_point, which is a fraction between 0 and 1,
indicating relatively where along the string to sni... | python | def snip_string(string, max_len=20, snip_string='...', snip_point=0.5):
"""
Snips a string so that it is no longer than max_len, replacing deleted
characters with the snip_string.
The snip is done at snip_point, which is a fraction between 0 and 1,
indicating relatively where along the string to sni... | [
"def",
"snip_string",
"(",
"string",
",",
"max_len",
"=",
"20",
",",
"snip_string",
"=",
"'...'",
",",
"snip_point",
"=",
"0.5",
")",
":",
"if",
"len",
"(",
"string",
")",
"<=",
"max_len",
":",
"new_string",
"=",
"string",
"else",
":",
"visible_len",
"... | Snips a string so that it is no longer than max_len, replacing deleted
characters with the snip_string.
The snip is done at snip_point, which is a fraction between 0 and 1,
indicating relatively where along the string to snip. snip_point of
0.5 would be the middle.
>>> snip_string('this is long', 8)... | [
"Snips",
"a",
"string",
"so",
"that",
"it",
"is",
"no",
"longer",
"than",
"max_len",
"replacing",
"deleted",
"characters",
"with",
"the",
"snip_string",
".",
"The",
"snip",
"is",
"done",
"at",
"snip_point",
"which",
"is",
"a",
"fraction",
"between",
"0",
"... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/utils.py#L173-L203 |
nwilming/ocupy | ocupy/utils.py | find_common_beginning | def find_common_beginning(string_list, boundary_char = None):
"""Given a list of strings, finds finds the longest string that is common
to the *beginning* of all strings in the list.
boundary_char defines a boundary that must be preserved, so that the
common string removed must end with this char.
... | python | def find_common_beginning(string_list, boundary_char = None):
"""Given a list of strings, finds finds the longest string that is common
to the *beginning* of all strings in the list.
boundary_char defines a boundary that must be preserved, so that the
common string removed must end with this char.
... | [
"def",
"find_common_beginning",
"(",
"string_list",
",",
"boundary_char",
"=",
"None",
")",
":",
"common",
"=",
"''",
"# by definition there is nothing common to 1 item...",
"if",
"len",
"(",
"string_list",
")",
">",
"1",
":",
"shortestLen",
"=",
"min",
"(",
"[",
... | Given a list of strings, finds finds the longest string that is common
to the *beginning* of all strings in the list.
boundary_char defines a boundary that must be preserved, so that the
common string removed must end with this char. | [
"Given",
"a",
"list",
"of",
"strings",
"finds",
"finds",
"the",
"longest",
"string",
"that",
"is",
"common",
"to",
"the",
"*",
"beginning",
"*",
"of",
"all",
"strings",
"in",
"the",
"list",
".",
"boundary_char",
"defines",
"a",
"boundary",
"that",
"must",
... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/utils.py#L205-L233 |
nwilming/ocupy | ocupy/utils.py | factorise_strings | def factorise_strings (string_list, boundary_char=None):
"""Given a list of strings, finds the longest string that is common
to the *beginning* of all strings in the list and
returns a new list whose elements lack this common beginning.
boundary_char defines a boundary that must be preserved, so th... | python | def factorise_strings (string_list, boundary_char=None):
"""Given a list of strings, finds the longest string that is common
to the *beginning* of all strings in the list and
returns a new list whose elements lack this common beginning.
boundary_char defines a boundary that must be preserved, so th... | [
"def",
"factorise_strings",
"(",
"string_list",
",",
"boundary_char",
"=",
"None",
")",
":",
"cmn",
"=",
"find_common_beginning",
"(",
"string_list",
",",
"boundary_char",
")",
"new_list",
"=",
"[",
"el",
"[",
"len",
"(",
"cmn",
")",
":",
"]",
"for",
"el",... | Given a list of strings, finds the longest string that is common
to the *beginning* of all strings in the list and
returns a new list whose elements lack this common beginning.
boundary_char defines a boundary that must be preserved, so that the
common string removed must end with this char.
... | [
"Given",
"a",
"list",
"of",
"strings",
"finds",
"the",
"longest",
"string",
"that",
"is",
"common",
"to",
"the",
"*",
"beginning",
"*",
"of",
"all",
"strings",
"in",
"the",
"list",
"and",
"returns",
"a",
"new",
"list",
"whose",
"elements",
"lack",
"this"... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/utils.py#L235-L277 |
nwilming/ocupy | ocupy/datamat.py | load | def load(path, variable='Datamat'):
"""
Load datamat at path.
Parameters:
path : string
Absolute path of the file to load from.
"""
f = h5py.File(path,'r')
try:
dm = fromhdf5(f[variable])
finally:
f.close()
return dm | python | def load(path, variable='Datamat'):
"""
Load datamat at path.
Parameters:
path : string
Absolute path of the file to load from.
"""
f = h5py.File(path,'r')
try:
dm = fromhdf5(f[variable])
finally:
f.close()
return dm | [
"def",
"load",
"(",
"path",
",",
"variable",
"=",
"'Datamat'",
")",
":",
"f",
"=",
"h5py",
".",
"File",
"(",
"path",
",",
"'r'",
")",
"try",
":",
"dm",
"=",
"fromhdf5",
"(",
"f",
"[",
"variable",
"]",
")",
"finally",
":",
"f",
".",
"close",
"("... | Load datamat at path.
Parameters:
path : string
Absolute path of the file to load from. | [
"Load",
"datamat",
"at",
"path",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/datamat.py#L528-L541 |
nwilming/ocupy | ocupy/datamat.py | VectorFactory | def VectorFactory(fields, parameters, categories = None):
'''
Creates a datamat from a dictionary that contains lists/arrays as values.
Input:
fields: Dictionary
The values will be used as fields of the datamat and the keys
as field names.
parameters: Dictionary
... | python | def VectorFactory(fields, parameters, categories = None):
'''
Creates a datamat from a dictionary that contains lists/arrays as values.
Input:
fields: Dictionary
The values will be used as fields of the datamat and the keys
as field names.
parameters: Dictionary
... | [
"def",
"VectorFactory",
"(",
"fields",
",",
"parameters",
",",
"categories",
"=",
"None",
")",
":",
"fm",
"=",
"Datamat",
"(",
"categories",
"=",
"categories",
")",
"fm",
".",
"_fields",
"=",
"list",
"(",
"fields",
".",
"keys",
"(",
")",
")",
"for",
... | Creates a datamat from a dictionary that contains lists/arrays as values.
Input:
fields: Dictionary
The values will be used as fields of the datamat and the keys
as field names.
parameters: Dictionary
A dictionary whose values are added as parameters. Keys are us... | [
"Creates",
"a",
"datamat",
"from",
"a",
"dictionary",
"that",
"contains",
"lists",
"/",
"arrays",
"as",
"values",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/datamat.py#L560-L584 |
nwilming/ocupy | ocupy/datamat.py | Datamat.filter | def filter(self, index): #@ReservedAssignment
"""
Filters a datamat by different aspects.
This function is a device to filter the datamat by certain logical
conditions. It takes as input a logical array (contains only True
or False for every datapoint) and kicks out all datapoin... | python | def filter(self, index): #@ReservedAssignment
"""
Filters a datamat by different aspects.
This function is a device to filter the datamat by certain logical
conditions. It takes as input a logical array (contains only True
or False for every datapoint) and kicks out all datapoin... | [
"def",
"filter",
"(",
"self",
",",
"index",
")",
":",
"#@ReservedAssignment",
"return",
"Datamat",
"(",
"categories",
"=",
"self",
".",
"_categories",
",",
"datamat",
"=",
"self",
",",
"index",
"=",
"index",
")"
] | Filters a datamat by different aspects.
This function is a device to filter the datamat by certain logical
conditions. It takes as input a logical array (contains only True
or False for every datapoint) and kicks out all datapoints for which
the array says False. The logical array can c... | [
"Filters",
"a",
"datamat",
"by",
"different",
"aspects",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/datamat.py#L140-L163 |
nwilming/ocupy | ocupy/datamat.py | Datamat.copy | def copy(self):
"""
Returns a copy of the datamat.
"""
return self.filter(np.ones(self._num_fix).astype(bool)) | python | def copy(self):
"""
Returns a copy of the datamat.
"""
return self.filter(np.ones(self._num_fix).astype(bool)) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"self",
".",
"filter",
"(",
"np",
".",
"ones",
"(",
"self",
".",
"_num_fix",
")",
".",
"astype",
"(",
"bool",
")",
")"
] | Returns a copy of the datamat. | [
"Returns",
"a",
"copy",
"of",
"the",
"datamat",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/datamat.py#L165-L169 |
nwilming/ocupy | ocupy/datamat.py | Datamat.save | def save(self, path):
"""
Saves Datamat to path.
Parameters:
path : string
Absolute path of the file to save to.
"""
f = h5py.File(path, 'w')
try:
fm_group = f.create_group('Datamat')
for field in self.fieldnames():
... | python | def save(self, path):
"""
Saves Datamat to path.
Parameters:
path : string
Absolute path of the file to save to.
"""
f = h5py.File(path, 'w')
try:
fm_group = f.create_group('Datamat')
for field in self.fieldnames():
... | [
"def",
"save",
"(",
"self",
",",
"path",
")",
":",
"f",
"=",
"h5py",
".",
"File",
"(",
"path",
",",
"'w'",
")",
"try",
":",
"fm_group",
"=",
"f",
".",
"create_group",
"(",
"'Datamat'",
")",
"for",
"field",
"in",
"self",
".",
"fieldnames",
"(",
")... | Saves Datamat to path.
Parameters:
path : string
Absolute path of the file to save to. | [
"Saves",
"Datamat",
"to",
"path",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/datamat.py#L190-L217 |
nwilming/ocupy | ocupy/datamat.py | Datamat.set_param | def set_param(self, key, value):
"""
Set the value of a parameter.
"""
self.__dict__[key] = value
self._parameters[key] = value | python | def set_param(self, key, value):
"""
Set the value of a parameter.
"""
self.__dict__[key] = value
self._parameters[key] = value | [
"def",
"set_param",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"__dict__",
"[",
"key",
"]",
"=",
"value",
"self",
".",
"_parameters",
"[",
"key",
"]",
"=",
"value"
] | Set the value of a parameter. | [
"Set",
"the",
"value",
"of",
"a",
"parameter",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/datamat.py#L234-L239 |
nwilming/ocupy | ocupy/datamat.py | Datamat.by_field | def by_field(self, field):
"""
Returns an iterator that iterates over unique values of field
Parameters:
field : string
Filters the datamat for every unique value in field and yields
the filtered datamat.
Returns:
datamat : Datamat... | python | def by_field(self, field):
"""
Returns an iterator that iterates over unique values of field
Parameters:
field : string
Filters the datamat for every unique value in field and yields
the filtered datamat.
Returns:
datamat : Datamat... | [
"def",
"by_field",
"(",
"self",
",",
"field",
")",
":",
"for",
"value",
"in",
"np",
".",
"unique",
"(",
"self",
".",
"__dict__",
"[",
"field",
"]",
")",
":",
"yield",
"self",
".",
"filter",
"(",
"self",
".",
"__dict__",
"[",
"field",
"]",
"==",
"... | Returns an iterator that iterates over unique values of field
Parameters:
field : string
Filters the datamat for every unique value in field and yields
the filtered datamat.
Returns:
datamat : Datamat that is filtered according to one of the uniqu... | [
"Returns",
"an",
"iterator",
"that",
"iterates",
"over",
"unique",
"values",
"of",
"field"
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/datamat.py#L241-L254 |
nwilming/ocupy | ocupy/datamat.py | Datamat.by_cat | def by_cat(self):
"""
Iterates over categories and returns a filtered datamat.
If a categories object is attached, the images object for the given
category is returned as well (else None is returned).
Returns:
(datamat, categories) : A tuple that contains first the ... | python | def by_cat(self):
"""
Iterates over categories and returns a filtered datamat.
If a categories object is attached, the images object for the given
category is returned as well (else None is returned).
Returns:
(datamat, categories) : A tuple that contains first the ... | [
"def",
"by_cat",
"(",
"self",
")",
":",
"for",
"value",
"in",
"np",
".",
"unique",
"(",
"self",
".",
"category",
")",
":",
"cat_fm",
"=",
"self",
".",
"filter",
"(",
"self",
".",
"category",
"==",
"value",
")",
"if",
"self",
".",
"_categories",
":"... | Iterates over categories and returns a filtered datamat.
If a categories object is attached, the images object for the given
category is returned as well (else None is returned).
Returns:
(datamat, categories) : A tuple that contains first the filtered
datamat (has ... | [
"Iterates",
"over",
"categories",
"and",
"returns",
"a",
"filtered",
"datamat",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/datamat.py#L256-L273 |
nwilming/ocupy | ocupy/datamat.py | Datamat.by_filenumber | def by_filenumber(self):
"""
Iterates over categories and returns a filtered datamat.
If a categories object is attached, the images object for the given
category is returned as well (else None is returned).
Returns:
(datamat, categories) : A tuple that contains fir... | python | def by_filenumber(self):
"""
Iterates over categories and returns a filtered datamat.
If a categories object is attached, the images object for the given
category is returned as well (else None is returned).
Returns:
(datamat, categories) : A tuple that contains fir... | [
"def",
"by_filenumber",
"(",
"self",
")",
":",
"for",
"value",
"in",
"np",
".",
"unique",
"(",
"self",
".",
"filenumber",
")",
":",
"file_fm",
"=",
"self",
".",
"filter",
"(",
"self",
".",
"filenumber",
"==",
"value",
")",
"if",
"self",
".",
"_catego... | Iterates over categories and returns a filtered datamat.
If a categories object is attached, the images object for the given
category is returned as well (else None is returned).
Returns:
(datamat, categories) : A tuple that contains first the filtered
datamat (has ... | [
"Iterates",
"over",
"categories",
"and",
"returns",
"a",
"filtered",
"datamat",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/datamat.py#L275-L292 |
nwilming/ocupy | ocupy/datamat.py | Datamat.add_field | def add_field(self, name, data):
"""
Add a new field to the datamat.
Parameters:
name : string
Name of the new field
data : list
Data for the new field, must be same length as all other fields.
"""
if name in self._fields:
... | python | def add_field(self, name, data):
"""
Add a new field to the datamat.
Parameters:
name : string
Name of the new field
data : list
Data for the new field, must be same length as all other fields.
"""
if name in self._fields:
... | [
"def",
"add_field",
"(",
"self",
",",
"name",
",",
"data",
")",
":",
"if",
"name",
"in",
"self",
".",
"_fields",
":",
"raise",
"ValueError",
"if",
"not",
"len",
"(",
"data",
")",
"==",
"self",
".",
"_num_fix",
":",
"raise",
"ValueError",
"self",
".",... | Add a new field to the datamat.
Parameters:
name : string
Name of the new field
data : list
Data for the new field, must be same length as all other fields. | [
"Add",
"a",
"new",
"field",
"to",
"the",
"datamat",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/datamat.py#L294-L309 |
nwilming/ocupy | ocupy/datamat.py | Datamat.add_field_like | def add_field_like(self, name, like_array):
"""
Add a new field to the Datamat with the dtype of the
like_array and the shape of the like_array except for the first
dimension which will be instead the field-length of this Datamat.
"""
new_shape = list(like_array.shape)
... | python | def add_field_like(self, name, like_array):
"""
Add a new field to the Datamat with the dtype of the
like_array and the shape of the like_array except for the first
dimension which will be instead the field-length of this Datamat.
"""
new_shape = list(like_array.shape)
... | [
"def",
"add_field_like",
"(",
"self",
",",
"name",
",",
"like_array",
")",
":",
"new_shape",
"=",
"list",
"(",
"like_array",
".",
"shape",
")",
"new_shape",
"[",
"0",
"]",
"=",
"len",
"(",
"self",
")",
"new_data",
"=",
"ma",
".",
"empty",
"(",
"new_s... | Add a new field to the Datamat with the dtype of the
like_array and the shape of the like_array except for the first
dimension which will be instead the field-length of this Datamat. | [
"Add",
"a",
"new",
"field",
"to",
"the",
"Datamat",
"with",
"the",
"dtype",
"of",
"the",
"like_array",
"and",
"the",
"shape",
"of",
"the",
"like_array",
"except",
"for",
"the",
"first",
"dimension",
"which",
"will",
"be",
"instead",
"the",
"field",
"-",
... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/datamat.py#L311-L321 |
nwilming/ocupy | ocupy/datamat.py | Datamat.annotate | def annotate (self, src_dm, data_field, key_field, take_first=True):
"""
Adds a new field (data_field) to the Datamat with data from the
corresponding field of another Datamat (src_dm).
This is accomplished through the use of a key_field, which is
used to determine how the data is c... | python | def annotate (self, src_dm, data_field, key_field, take_first=True):
"""
Adds a new field (data_field) to the Datamat with data from the
corresponding field of another Datamat (src_dm).
This is accomplished through the use of a key_field, which is
used to determine how the data is c... | [
"def",
"annotate",
"(",
"self",
",",
"src_dm",
",",
"data_field",
",",
"key_field",
",",
"take_first",
"=",
"True",
")",
":",
"if",
"key_field",
"not",
"in",
"self",
".",
"_fields",
"or",
"key_field",
"not",
"in",
"src_dm",
".",
"_fields",
":",
"raise",
... | Adds a new field (data_field) to the Datamat with data from the
corresponding field of another Datamat (src_dm).
This is accomplished through the use of a key_field, which is
used to determine how the data is copied.
This operation corresponds loosely to an SQL join operation.
The two... | [
"Adds",
"a",
"new",
"field",
"(",
"data_field",
")",
"to",
"the",
"Datamat",
"with",
"data",
"from",
"the",
"corresponding",
"field",
"of",
"another",
"Datamat",
"(",
"src_dm",
")",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/datamat.py#L323-L408 |
nwilming/ocupy | ocupy/datamat.py | Datamat.rm_field | def rm_field(self, name):
"""
Remove a field from the datamat.
Parameters:
name : string
Name of the field to be removed
"""
if not name in self._fields:
raise ValueError
self._fields.remove(name)
del self.__dict__[name] | python | def rm_field(self, name):
"""
Remove a field from the datamat.
Parameters:
name : string
Name of the field to be removed
"""
if not name in self._fields:
raise ValueError
self._fields.remove(name)
del self.__dict__[name] | [
"def",
"rm_field",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"name",
"in",
"self",
".",
"_fields",
":",
"raise",
"ValueError",
"self",
".",
"_fields",
".",
"remove",
"(",
"name",
")",
"del",
"self",
".",
"__dict__",
"[",
"name",
"]"
] | Remove a field from the datamat.
Parameters:
name : string
Name of the field to be removed | [
"Remove",
"a",
"field",
"from",
"the",
"datamat",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/datamat.py#L410-L421 |
nwilming/ocupy | ocupy/datamat.py | Datamat.add_parameter | def add_parameter(self, name, value):
"""
Adds a parameter to the existing Datamat.
Fails if parameter with same name already exists or if name is otherwise
in this objects ___dict__ dictionary.
"""
if name in self._parameters:
raise ValueError("'%s' is alrea... | python | def add_parameter(self, name, value):
"""
Adds a parameter to the existing Datamat.
Fails if parameter with same name already exists or if name is otherwise
in this objects ___dict__ dictionary.
"""
if name in self._parameters:
raise ValueError("'%s' is alrea... | [
"def",
"add_parameter",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"name",
"in",
"self",
".",
"_parameters",
":",
"raise",
"ValueError",
"(",
"\"'%s' is already a parameter\"",
"%",
"(",
"name",
")",
")",
"elif",
"name",
"in",
"self",
".",
"... | Adds a parameter to the existing Datamat.
Fails if parameter with same name already exists or if name is otherwise
in this objects ___dict__ dictionary. | [
"Adds",
"a",
"parameter",
"to",
"the",
"existing",
"Datamat",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/datamat.py#L423-L436 |
nwilming/ocupy | ocupy/datamat.py | Datamat.rm_parameter | def rm_parameter(self, name):
"""
Removes a parameter to the existing Datamat.
Fails if parameter doesn't exist.
"""
if name not in self._parameters:
raise ValueError("no '%s' parameter found" % (name))
del self._parameters[name]
del self.__dict__[na... | python | def rm_parameter(self, name):
"""
Removes a parameter to the existing Datamat.
Fails if parameter doesn't exist.
"""
if name not in self._parameters:
raise ValueError("no '%s' parameter found" % (name))
del self._parameters[name]
del self.__dict__[na... | [
"def",
"rm_parameter",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_parameters",
":",
"raise",
"ValueError",
"(",
"\"no '%s' parameter found\"",
"%",
"(",
"name",
")",
")",
"del",
"self",
".",
"_parameters",
"[",
"name",
... | Removes a parameter to the existing Datamat.
Fails if parameter doesn't exist. | [
"Removes",
"a",
"parameter",
"to",
"the",
"existing",
"Datamat",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/datamat.py#L438-L448 |
nwilming/ocupy | ocupy/datamat.py | Datamat.parameter_to_field | def parameter_to_field(self, name):
"""
Promotes a parameter to a field by creating a new array of same
size as the other existing fields, filling it with the current
value of the parameter, and then removing that parameter.
"""
if name not in self._parameters:
... | python | def parameter_to_field(self, name):
"""
Promotes a parameter to a field by creating a new array of same
size as the other existing fields, filling it with the current
value of the parameter, and then removing that parameter.
"""
if name not in self._parameters:
... | [
"def",
"parameter_to_field",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_parameters",
":",
"raise",
"ValueError",
"(",
"\"no '%s' parameter found\"",
"%",
"(",
"name",
")",
")",
"if",
"self",
".",
"_fields",
".",
"count",
... | Promotes a parameter to a field by creating a new array of same
size as the other existing fields, filling it with the current
value of the parameter, and then removing that parameter. | [
"Promotes",
"a",
"parameter",
"to",
"a",
"field",
"by",
"creating",
"a",
"new",
"array",
"of",
"same",
"size",
"as",
"the",
"other",
"existing",
"fields",
"filling",
"it",
"with",
"the",
"current",
"value",
"of",
"the",
"parameter",
"and",
"then",
"removin... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/datamat.py#L450-L464 |
nwilming/ocupy | ocupy/datamat.py | Datamat.join | def join(self, fm_new, minimal_subset=True):
"""
Adds content of a new Datamat to this Datamat.
If a parameter of the Datamats is not equal or does not exist
in one, it is promoted to a field.
If the two Datamats have different fields then the elements for the
Datamats ... | python | def join(self, fm_new, minimal_subset=True):
"""
Adds content of a new Datamat to this Datamat.
If a parameter of the Datamats is not equal or does not exist
in one, it is promoted to a field.
If the two Datamats have different fields then the elements for the
Datamats ... | [
"def",
"join",
"(",
"self",
",",
"fm_new",
",",
"minimal_subset",
"=",
"True",
")",
":",
"# Check if parameters are equal. If not, promote them to fields.",
"'''\n for (nm, val) in fm_new._parameters.items():\n if self._parameters.has_key(nm):\n if (val != ... | Adds content of a new Datamat to this Datamat.
If a parameter of the Datamats is not equal or does not exist
in one, it is promoted to a field.
If the two Datamats have different fields then the elements for the
Datamats that did not have the field will be NaN, unless
'minimal_... | [
"Adds",
"content",
"of",
"a",
"new",
"Datamat",
"to",
"this",
"Datamat",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/datamat.py#L466-L526 |
nwilming/ocupy | ocupy/simulator.py | makeAngLenHist | def makeAngLenHist(ad, ld, fm = None, collapse=True, fit=spline_base.fit2d):
"""
Histograms and performs a spline fit on the given data,
usually angle and length differences.
Parameters:
ad : array
The data to be histogrammed along the x-axis.
May range from -180 t... | python | def makeAngLenHist(ad, ld, fm = None, collapse=True, fit=spline_base.fit2d):
"""
Histograms and performs a spline fit on the given data,
usually angle and length differences.
Parameters:
ad : array
The data to be histogrammed along the x-axis.
May range from -180 t... | [
"def",
"makeAngLenHist",
"(",
"ad",
",",
"ld",
",",
"fm",
"=",
"None",
",",
"collapse",
"=",
"True",
",",
"fit",
"=",
"spline_base",
".",
"fit2d",
")",
":",
"if",
"fm",
":",
"ad",
",",
"ld",
"=",
"anglendiff",
"(",
"fm",
",",
"roll",
"=",
"2",
... | Histograms and performs a spline fit on the given data,
usually angle and length differences.
Parameters:
ad : array
The data to be histogrammed along the x-axis.
May range from -180 to 180.
ld : array
The data to be histogrammed along the y-axis.
... | [
"Histograms",
"and",
"performs",
"a",
"spline",
"fit",
"on",
"the",
"given",
"data",
"usually",
"angle",
"and",
"length",
"differences",
".",
"Parameters",
":",
"ad",
":",
"array",
"The",
"data",
"to",
"be",
"histogrammed",
"along",
"the",
"x",
"-",
"axis"... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/simulator.py#L329-L372 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.