id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
148,148 |
MacHu-GWU/loggerFactory-project
|
MacHu-GWU_loggerFactory-project/loggerFactory/logfilter.py
|
MacHu-GWU_loggerFactory-project.loggerFactory.logfilter.Result
|
class Result(object):
"""
Filter Results Object.
"""
def __init__(self, path,
level, message, time_lower, time_upper, case_sensitive):
self.path = path
self.level = level
self.message = message
self.time_lower = time_lower
self.time_upper = time_upper
self.case_sensitive = case_sensitive
self.lines = list()
def __str__(self):
return self.header + "\n" + "".join(self.lines)
@property
def header(self):
template = ("--- Result of: filepath=%r, level=%r, pattern=%r,"
"time_lower=%r, time_upper=%r, case_sensitive=%r ---")
return template % (self.path,
self.level, self.message,
self.time_lower, self.time_upper,
self.case_sensitive,
)
def dump(self, path):
with open(path, "wb") as f:
f.write(str(self).encode("utf-8"))
|
class Result(object):
'''
Filter Results Object.
'''
def __init__(self, path,
level, message, time_lower, time_upper, case_sensitive):
pass
def __str__(self):
pass
@property
def header(self):
pass
def dump(self, path):
pass
| 6 | 1 | 6 | 0 | 6 | 0 | 1 | 0.13 | 1 | 2 | 0 | 0 | 4 | 7 | 4 | 4 | 31 | 4 | 24 | 16 | 17 | 3 | 17 | 13 | 12 | 1 | 1 | 1 | 4 |
148,149 |
MacHu-GWU/loggerFactory-project
|
MacHu-GWU_loggerFactory-project/loggerFactory/logger.py
|
MacHu-GWU_loggerFactory-project.loggerFactory.logger.BaseLogger
|
class BaseLogger(object):
"""
A base class for logger constructor.
"""
tab = " "
enable_verbose = True
logger = None
Fore = Fore
Back = Back
Style = Style
class MessageTemplate(object):
with_style = "{indent}{style}{msg}" + Style.RESET_ALL
def __init__(self, name=None, rand_name=False, **kwargs):
self.logger = get_logger_by_name(name, rand_name)
self._handler_cache = list()
def _indent(self, msg, indent):
return "%s%s" % (self.tab * indent, msg)
def debug(self, msg, indent=0, **kwargs):
"""invoke ``self.logger.debug``"""
return self.logger.debug(self._indent(msg, indent), **kwargs)
def info(self, msg, indent=0, **kwargs):
"""
invoke ``self.info.debug``
"""
return self.logger.info(self._indent(msg, indent), **kwargs)
def warning(self, msg, indent=0, **kwargs):
"""
invoke ``self.logger.warning``
"""
return self.logger.warning(self._indent(msg, indent), **kwargs)
def error(self, msg, indent=0, **kwargs):
"""
invoke ``self.logger.error``
"""
return self.logger.error(self._indent(msg, indent), **kwargs)
def critical(self, msg, indent=0, **kwargs):
"""
invoke ``self.logger.critical``
"""
return self.logger.critical(self._indent(msg, indent), **kwargs)
def show(self, msg, indent=0, style="", **kwargs):
"""
Print message to console, indent format may apply.
"""
if self.enable_verbose:
new_msg = self.MessageTemplate.with_style.format(
indent=self.tab * indent,
style=style,
msg=msg,
)
print(new_msg, **kwargs)
def show_in_red(self, msg, indent=0, **kwargs):
self.show(msg, indent, Fore.LIGHTRED_EX, **kwargs)
def show_in_blue(self, msg, indent=0, **kwargs):
self.show(msg, indent, Fore.LIGHTBLUE_EX, **kwargs)
def show_in_yellow(self, msg, indent=0, **kwargs):
self.show(msg, indent, Fore.LIGHTYELLOW_EX, **kwargs)
def show_in_green(self, msg, indent=0, **kwargs):
self.show(msg, indent, Fore.GREEN, **kwargs)
def show_in_cyan(self, msg, indent=0, **kwargs):
self.show(msg, indent, Fore.CYAN, **kwargs)
def show_in_meganta(self, msg, indent=0, **kwargs):
self.show(msg, indent, Fore.MAGENTA, **kwargs)
__call__ = show
def remove_all_handler(self):
"""
Unlink the file handler association.
"""
for handler in self.logger.handlers[:]:
self.logger.removeHandler(handler)
self._handler_cache.append(handler)
def recover_all_handler(self):
"""
Relink the file handler association you just removed.
"""
for handler in self._handler_cache:
self.logger.addHandler(handler)
self._handler_cache = list()
|
class BaseLogger(object):
'''
A base class for logger constructor.
'''
class MessageTemplate(object):
def __init__(self, name=None, rand_name=False, **kwargs):
pass
def _indent(self, msg, indent):
pass
def debug(self, msg, indent=0, **kwargs):
'''invoke ``self.logger.debug``'''
pass
def info(self, msg, indent=0, **kwargs):
'''
invoke ``self.info.debug``
'''
pass
def warning(self, msg, indent=0, **kwargs):
'''
invoke ``self.logger.warning``
'''
pass
def error(self, msg, indent=0, **kwargs):
'''
invoke ``self.logger.error``
'''
pass
def critical(self, msg, indent=0, **kwargs):
'''
invoke ``self.logger.critical``
'''
pass
def show(self, msg, indent=0, style="", **kwargs):
'''
Print message to console, indent format may apply.
'''
pass
def show_in_red(self, msg, indent=0, **kwargs):
pass
def show_in_blue(self, msg, indent=0, **kwargs):
pass
def show_in_yellow(self, msg, indent=0, **kwargs):
pass
def show_in_green(self, msg, indent=0, **kwargs):
pass
def show_in_cyan(self, msg, indent=0, **kwargs):
pass
def show_in_meganta(self, msg, indent=0, **kwargs):
pass
def remove_all_handler(self):
'''
Unlink the file handler association.
'''
pass
def recover_all_handler(self):
'''
Relink the file handler association you just removed.
'''
pass
| 18 | 9 | 4 | 0 | 3 | 1 | 1 | 0.47 | 1 | 2 | 1 | 4 | 16 | 1 | 16 | 16 | 97 | 19 | 53 | 30 | 35 | 25 | 49 | 30 | 31 | 2 | 1 | 1 | 19 |
148,150 |
MacHu-GWU/loggerFactory-project
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_loggerFactory-project/loggerFactory/logger.py
|
MacHu-GWU_loggerFactory-project.loggerFactory.logger.BaseLogger.MessageTemplate
|
class MessageTemplate(object):
with_style = "{indent}{style}{msg}" + Style.RESET_ALL
|
class MessageTemplate(object):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
148,151 |
MacHu-GWU/loggerFactory-project
|
MacHu-GWU_loggerFactory-project/loggerFactory/rand_str.py
|
MacHu-GWU_loggerFactory-project.loggerFactory.rand_str.Charset
|
class Charset(object):
ALPHA_LOWER = string.ascii_lowercase
ALPHA_UPPER = string.ascii_uppercase
ALPHA = string.ascii_letters
HEX = "0123456789abcdef"
ALPHA_DIGITS = string.ascii_letters + string.digits
PUNCTUATION = string.punctuation
|
class Charset(object):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 | 0 | 7 | 7 | 6 | 0 | 7 | 7 | 6 | 0 | 1 | 0 | 0 |
148,152 |
MacHu-GWU/loggerFactory-project
|
MacHu-GWU_loggerFactory-project/loggerFactory/logger.py
|
MacHu-GWU_loggerFactory-project.loggerFactory.logger.TimeRotatingLogger
|
class TimeRotatingLogger(BaseLogger):
"""
Definition:
https://docs.python.org/2/library/logging.handlers.html#timedrotatingfilehandler
:param rotate_on_when: could be "h" (hour), "D" (Day).
:param interval: rotate on how many hour/day.
:param backup_count: max number of files.
**中文文档**
根据日志发生的时间, 每隔一定时间就更换一个文件名。
"""
def __init__(
self,
name=None,
rand_name=False,
path=None,
logging_level=logging.DEBUG,
stream_level=logging.INFO,
logging_format=DEFAULT_LOG_FORMAT,
stream_format=DEFAULT_STREAM_FORMAT,
rotate_on_when="D",
interval=1,
backup_count=30,
):
if path is None: # pragma: no cover
raise ValueError("Please specify a log file in ``path``!")
super(TimeRotatingLogger, self).__init__(name, rand_name)
# Set Logging Level
self.logger.setLevel(logging_level)
# Set File Handler
file_handler = TimedRotatingFileHandler(
path,
when=rotate_on_when,
interval=interval,
backupCount=backup_count,
encoding="utf-8",
)
file_handler.setFormatter(logging.Formatter(logging_format))
self.logger.addHandler(file_handler)
# Set Stream Handler
set_stream_handler(self.logger, stream_level, stream_format)
|
class TimeRotatingLogger(BaseLogger):
'''
Definition:
https://docs.python.org/2/library/logging.handlers.html#timedrotatingfilehandler
:param rotate_on_when: could be "h" (hour), "D" (Day).
:param interval: rotate on how many hour/day.
:param backup_count: max number of files.
**中文文档**
根据日志发生的时间, 每隔一定时间就更换一个文件名。
'''
def __init__(
self,
name=None,
rand_name=False,
path=None,
logging_level=logging.DEBUG,
stream_level=logging.INFO,
logging_format=DEFAULT_LOG_FORMAT,
stream_format=DEFAULT_STREAM_FORMAT,
rotate_on_when="D",
interval=1,
backup_count=30,
):
pass
| 2 | 1 | 34 | 4 | 27 | 4 | 2 | 0.46 | 1 | 4 | 0 | 0 | 1 | 0 | 1 | 17 | 49 | 9 | 28 | 15 | 14 | 13 | 10 | 3 | 8 | 2 | 2 | 1 | 2 |
148,153 |
MacHu-GWU/loggerFactory-project
|
MacHu-GWU_loggerFactory-project/loggerFactory/logger.py
|
MacHu-GWU_loggerFactory-project.loggerFactory.logger.StreamOnlyLogger
|
class StreamOnlyLogger(BaseLogger):
"""
This logger only print message to console, and not write log to files.
:param stream_level: level above this will be streamed.
:param stream_format: log information format.
**中文文档**
只将日志打印到控制台, 并不将日志信息写入到文件。
"""
def __init__(
self,
name=None,
rand_name=False,
stream_level=logging.INFO,
stream_format=DEFAULT_STREAM_FORMAT,
):
super(StreamOnlyLogger, self).__init__(name, rand_name)
# Set Logging Level
self.logger.setLevel(logging.DEBUG)
# Set Stream Handler
set_stream_handler(self.logger, stream_level, stream_format)
|
class StreamOnlyLogger(BaseLogger):
'''
This logger only print message to console, and not write log to files.
:param stream_level: level above this will be streamed.
:param stream_format: log information format.
**中文文档**
只将日志打印到控制台, 并不将日志信息写入到文件。
'''
def __init__(
self,
name=None,
rand_name=False,
stream_level=logging.INFO,
stream_format=DEFAULT_STREAM_FORMAT,
):
pass
| 2 | 1 | 14 | 2 | 10 | 2 | 1 | 0.82 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 17 | 26 | 6 | 11 | 8 | 3 | 9 | 5 | 2 | 3 | 1 | 2 | 0 | 1 |
148,154 |
MacHu-GWU/loggerFactory-project
|
MacHu-GWU_loggerFactory-project/loggerFactory/logger.py
|
MacHu-GWU_loggerFactory-project.loggerFactory.logger.FileRotatingLogger
|
class FileRotatingLogger(BaseLogger):
"""
Definition:
https://docs.python.org/2/library/logging.handlers.html#rotatingfilehandler
:param path: the absolute path to the log file
:param max_bytes: max file size.
:param backup_count: max number of files.
**中文文档**
当日志文件的体积大于某个阈值时, 自动重名名, 将日志录入到新的文件中。
"""
def __init__(
self,
name=None,
rand_name=False,
path=None,
logging_level=logging.DEBUG,
stream_level=logging.INFO,
logging_format=DEFAULT_LOG_FORMAT,
stream_format=DEFAULT_STREAM_FORMAT,
max_bytes=1000000000, # 1GB
backup_count=10,
):
if path is None: # pragma: no cover
raise ValueError("Please specify a log file in ``path``!")
super(FileRotatingLogger, self).__init__(name, rand_name)
# Set Logging Level
self.logger.setLevel(logging_level)
# Set File Handler
file_handler = RotatingFileHandler(
path, mode="a",
maxBytes=max_bytes,
backupCount=backup_count,
encoding="utf-8",
)
file_handler.setFormatter(logging.Formatter(logging_format))
self.logger.addHandler(file_handler)
# Set Stream Handler
set_stream_handler(self.logger, stream_level, stream_format)
|
class FileRotatingLogger(BaseLogger):
'''
Definition:
https://docs.python.org/2/library/logging.handlers.html#rotatingfilehandler
:param path: the absolute path to the log file
:param max_bytes: max file size.
:param backup_count: max number of files.
**中文文档**
当日志文件的体积大于某个阈值时, 自动重名名, 将日志录入到新的文件中。
'''
def __init__(
self,
name=None,
rand_name=False,
path=None,
logging_level=logging.DEBUG,
stream_level=logging.INFO,
logging_format=DEFAULT_LOG_FORMAT,
stream_format=DEFAULT_STREAM_FORMAT,
max_bytes=1000000000, # 1GB
backup_count=10,
):
pass
| 2 | 1 | 32 | 4 | 25 | 5 | 2 | 0.54 | 1 | 4 | 0 | 0 | 1 | 0 | 1 | 17 | 47 | 9 | 26 | 14 | 13 | 14 | 10 | 3 | 8 | 2 | 2 | 1 | 2 |
148,155 |
MacHu-GWU/loggerFactory-project
|
MacHu-GWU_loggerFactory-project/loggerFactory/logger.py
|
MacHu-GWU_loggerFactory-project.loggerFactory.logger.SingleFileLogger
|
class SingleFileLogger(BaseLogger):
"""
This logger print message to console and also write log to files.
Only one log file will be used.
:type path: str
:param path: the absolute path to the log file
:type reset: bool
:param reset: if True, the old log content will be removed.
**中文文档**
日志被写入到单个文件中。
"""
def __init__(
self,
name=None,
rand_name=False,
path=None,
logging_level=logging.DEBUG,
stream_level=logging.INFO,
logging_format=DEFAULT_LOG_FORMAT,
stream_format=DEFAULT_STREAM_FORMAT,
reset=False,
):
if path is None: # pragma: no cover
raise ValueError("Please specify a log file in ``path``!")
super(SingleFileLogger, self).__init__(name, rand_name)
# Set Logging Level
self.logger.setLevel(logging_level)
# Set File Handler
if reset:
with open(path, "wb") as f:
pass
file_handler = logging.FileHandler(
path, mode="a", encoding="utf-8",
)
file_handler.setFormatter(logging.Formatter(logging_format))
self.logger.addHandler(file_handler)
# Set Stream Handler
set_stream_handler(self.logger, stream_level, stream_format)
|
class SingleFileLogger(BaseLogger):
'''
This logger print message to console and also write log to files.
Only one log file will be used.
:type path: str
:param path: the absolute path to the log file
:type reset: bool
:param reset: if True, the old log content will be removed.
**中文文档**
日志被写入到单个文件中。
'''
def __init__(
self,
name=None,
rand_name=False,
path=None,
logging_level=logging.DEBUG,
stream_level=logging.INFO,
logging_format=DEFAULT_LOG_FORMAT,
stream_format=DEFAULT_STREAM_FORMAT,
reset=False,
):
pass
| 2 | 1 | 32 | 5 | 24 | 4 | 3 | 0.56 | 1 | 4 | 0 | 0 | 1 | 0 | 1 | 17 | 49 | 11 | 25 | 14 | 13 | 14 | 13 | 3 | 11 | 3 | 2 | 2 | 3 |
148,156 |
MacHu-GWU/macro-project
|
MacHu-GWU_macro-project/macro/bot.py
|
macro.bot.Bot
|
class Bot(object):
"""Mouse and Keyboard robot class.
Abbreviation table:
- m: stands for mouse
- k: stands for keyboard
- dl: stands for delay
- n: how many times you want to tap the key
- i: usually for the ith function key, F1 ~ F12
Almost every method have an option keyword ``dl`` (dl stands for delay), there
is ``dl`` seconds delay applied at begin. By default it is ``None``, means no
delay applied.
Keyboard Key Name Table (Case Insensitive)::
# Main Keyboard Keys
"ctrl": self.k.control_key,
"l_ctrl": self.k.control_l_key,
"r_ctrl": self.k.control_r_key,
"alt": self.k.alt_key,
"l_alt": self.k.alt_l_key,
"r_alt": self.k.alt_r_key,
"shift": self.k.shift_key,
"l_shift": self.k.shift_l_key,
"r_shift": self.k.shift_r_key,
"tab": self.k.tab_key,
"space": self.k.space_key,
"enter": self.k.enter_key,
"back": self.k.backspace_key,
"backspace": self.k.backspace_key,
# Side Keyboard Keys
"home": self.k.home_key,
"end": self.k.end_key,
"page_up": self.k.page_up_key,
"pageup": self.k.page_up_key,
"page_down": self.k.page_down_key,
"page_down": self.k.page_down_key,
"insert": self.k.insert_key,
"ins": self.k.insert_key,
"delete": self.k.delete_key,
"del": self.k.delete_key,
"up": self.k.up_key,
"down": self.k.down_key,
"left": self.k.left_key,
"right": self.k.right_key,
# Function Keys
"f1": F1
"""
def __init__(self):
self.m = PyMouse()
self.k = PyKeyboard()
self.dl = 0
self._key_mapper = {
# Main Keyboard Keys
"ctrl": self.k.control_key,
"l_ctrl": self.k.control_l_key,
"r_ctrl": self.k.control_r_key,
"alt": self.k.alt_key,
"l_alt": self.k.alt_l_key,
"r_alt": self.k.alt_r_key,
"shift": self.k.shift_key,
"l_shift": self.k.shift_l_key,
"r_shift": self.k.shift_r_key,
"tab": self.k.tab_key,
"space": self.k.space_key,
"enter": self.k.enter_key,
"back": self.k.backspace_key,
"backspace": self.k.backspace_key,
# Side Keyboard Keys
"home": self.k.home_key,
"end": self.k.end_key,
"page_up": self.k.page_up_key,
"pageup": self.k.page_up_key,
"page_down": self.k.page_down_key,
"page_down": self.k.page_down_key,
"insert": self.k.insert_key,
"ins": self.k.insert_key,
"delete": self.k.delete_key,
"del": self.k.delete_key,
"up": self.k.up_key,
"down": self.k.down_key,
"left": self.k.left_key,
"right": self.k.right_key,
# f1 - f12 is the function key
}
for i in range(1, 1+12):
self._key_mapper["f%s" % i] = self.k.function_keys[i]
def _parse_key(self, name):
name = str(name)
if name in string.printable:
return name
elif name.lower() in self._key_mapper:
return self._key_mapper[name.lower()]
else:
raise ValueError(
"%r is not a valid key name, use one of %s." % (name, list(self._key_mapper)))
def delay(self, dl=0):
"""Delay for ``dl`` seconds.
"""
if dl is None:
time.sleep(self.dl)
elif dl < 0:
sys.stderr.write(
"delay cannot less than zero, this takes no effects.\n")
else:
time.sleep(dl)
#--- Meta ---
def get_screen_size(self):
"""Return screen's width and height in pixel.
**中文文档**
返回屏幕的像素尺寸。
"""
width, height = self.m.screen_size()
return width, height
def get_position(self):
"""Return the current coordinate of mouse.
**中文文档**
返回鼠标所处的位置坐标。
"""
x_axis, y_axis = self.m.position()
return x_axis, y_axis
#--- Mouse Macro ---
def left_click(self, x, y, n=1, pre_dl=None, post_dl=None):
"""Left click at ``(x, y)`` on screen for ``n`` times.
at begin.
**中文文档**
在屏幕的 ``(x, y)`` 坐标处左键单击 ``n`` 次。
"""
self.delay(pre_dl)
self.m.click(x, y, 1, n)
self.delay(post_dl)
def right_click(self, x, y, n=1, pre_dl=None, post_dl=None):
"""Right click at ``(x, y)`` on screen for ``n`` times.
at begin.
**中文文档**
在屏幕的 ``(x, y)`` 坐标处右键单击 ``n`` 次。
"""
self.delay(pre_dl)
self.m.click(x, y, 2, n)
self.delay(post_dl)
def middle_click(self, x, y, n=1, pre_dl=None, post_dl=None):
"""Middle click at ``(x, y)`` on screen for ``n`` times.
at begin.
**中文文档**
在屏幕的 ``(x, y)`` 坐标处中键单击 ``n`` 次。
"""
self.delay(pre_dl)
self.m.click(x, y, 3, n)
self.delay(post_dl)
def scroll_up(self, n, pre_dl=None, post_dl=None):
"""Scroll up ``n`` times.
**中文文档**
鼠标滚轮向上滚动n次。
"""
self.delay(pre_dl)
self.m.scroll(vertical=n)
self.delay(post_dl)
def scroll_down(self, n, pre_dl=None, post_dl=None):
"""Scroll down ``n`` times.
**中文文档**
鼠标滚轮向下滚动n次。
"""
self.delay(pre_dl)
self.m.scroll(vertical=-n)
self.delay(post_dl)
def scroll_right(self, n, pre_dl=None, post_dl=None):
"""Scroll right ``n`` times.
**中文文档**
鼠标滚轮向右滚动n次(如果可能的话)。
"""
self.delay(pre_dl)
self.m.scroll(horizontal=n)
self.delay(post_dl)
def scroll_left(self, n, pre_dl=None, post_dl=None):
"""Scroll left ``n`` times.
**中文文档**
鼠标滚轮向左滚动n次(如果可能的话)。
"""
self.delay(pre_dl)
self.m.scroll(horizontal=-n)
self.delay(post_dl)
def move_to(self, x, y, pre_dl=None, post_dl=None):
"""Move mouse to (x, y)
**中文文档**
移动鼠标到 (x, y) 的坐标处。
"""
self.delay(pre_dl)
self.m.move(x, y)
self.delay(post_dl)
def drag_and_release(self, start_x, start_y, end_x, end_y, pre_dl=None, post_dl=None):
"""Drag something from (start_x, start_y) to (end_x, endy)
**中文文档**
从start的坐标处鼠标左键单击拖曳到end的坐标处
start, end是tuple. 格式是(x, y)
"""
self.delay(pre_dl)
self.m.press(start_x, start_y, 1)
self.m.drag(end_x, end_y)
self.m.release(end_x, end_y, 1)
self.delay(post_dl)
#--- Keyboard Single Key ---
def tap_key(self, key_name, n=1, interval=0, pre_dl=None, post_dl=None):
"""Tap a key on keyboard for ``n`` times, with ``interval`` seconds of
interval. Key is declared by it's name
Example::
bot.tap_key("a")
bot.tap_key(1)
bot.tap_key("up")
bot.tap_key("space")
bot.tap_key("enter")
bot.tap_key("tab")
**中文文档**
以 ``interval`` 中定义的频率按下某个按键 ``n`` 次。接受按键名作为输入。
"""
key = self._parse_key(key_name)
self.delay(pre_dl)
self.k.tap_key(key, n, interval)
self.delay(post_dl)
def enter(self, n=1, interval=0, pre_dl=None, post_dl=None):
"""Press enter key n times.
**中文文档**
按回车键/换行键 n 次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.enter_key, n, interval)
self.delay(post_dl)
def backspace(self, n=1, interval=0, pre_dl=None, post_dl=None):
"""Press backspace key n times.
**中文文档**
按退格键 n 次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.backspace_key, n, interval)
self.delay(post_dl)
def space(self, n=1, interval=0, pre_dl=None, post_dl=None):
"""Press white space key n times.
**中文文档**
按空格键 n 次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.space_key, n)
self.delay(post_dl)
def fn(self, i, n=1, interval=0, pre_dl=None, post_dl=None):
"""Press Fn key n times.
**中文文档**
按 Fn 功能键 n 次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.function_keys[i], n, interval)
self.delay(post_dl)
def tab(self, n=1, interval=0, pre_dl=None, post_dl=None):
"""Tap ``tab`` key for ``n`` times, with ``interval`` seconds of interval.
**中文文档**
以 ``interval`` 中定义的频率按下某个tab键 ``n`` 次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.tab_key, n, interval)
self.delay(post_dl)
def up(self, n=1, interval=0, pre_dl=None, post_dl=None):
"""Press up key n times.
**中文文档**
按上方向键 n 次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.up_key, n, interval)
self.delay(post_dl)
def down(self, n=1, interval=0, pre_dl=None, post_dl=None):
"""Press down key n times.
**中文文档**
按下方向键 n 次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.down_key, n, interval)
self.delay(post_dl)
def left(self, n=1, interval=0, pre_dl=None, post_dl=None):
"""Press left key n times
**中文文档**
按左方向键 n 次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.left_key, n, interval)
self.delay(post_dl)
def right(self, n=1, interval=0, pre_dl=None, post_dl=None):
"""Press right key n times.
**中文文档**
按右方向键 n 次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.right_key, n, interval)
self.delay(post_dl)
def delete(self, n=1, interval=0, pre_dl=None, post_dl=None):
"""Pres delete key n times.
**中文文档**
按 delete 键n次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.delete_key, n, interval)
self.delay(post_dl)
def insert(self, n=1, interval=0, pre_dl=None, post_dl=None):
"""Pres insert key n times.
**中文文档**
按 insert 键n次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.insert_key, n, interval)
self.delay(post_dl)
def home(self, n=1, interval=0, pre_dl=None, post_dl=None):
"""Pres home key n times.
**中文文档**
按 home 键n次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.home_key, n, interval)
self.delay(post_dl)
def end(self, n=1, interval=0, pre_dl=None, post_dl=None):
"""Press end key n times.
**中文文档**
按 end 键n次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.end_key, n, interval)
self.delay(post_dl)
def page_up(self, n=1, interval=0, pre_dl=None, post_dl=None):
"""Pres page_up key n times.
**中文文档**
按 page_up 键n次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.page_up_key, n, interval)
self.delay(post_dl)
def page_down(self, n=1, interval=0, pre_dl=None, post_dl=None):
"""Pres page_down key n times.
**中文文档**
按 page_down 键n次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.page_down, n, interval)
self.delay(post_dl)
#--- Keyboard Combination ---
def press_and_tap(self, press_key, tap_key, n=1, interval=0, pre_dl=None, post_dl=None):
"""Press combination of two keys, like Ctrl + C, Alt + F4. The second
key could be tapped for multiple time.
Examples::
bot.press_and_tap("ctrl", "c")
bot.press_and_tap("shift", "1")
**中文文档**
按下两个键的组合键。
"""
press_key = self._parse_key(press_key)
tap_key = self._parse_key(tap_key)
self.delay(pre_dl)
self.k.press_key(press_key)
self.k.tap_key(tap_key, n, interval)
self.k.release_key(press_key)
self.delay(post_dl)
def press_two_and_tap(self,
press_key1, press_key2, tap_key, n=1, interval=0, pre_dl=None, post_dl=None):
"""Press combination of three keys, like Ctrl + Shift + C, The tap key
could be tapped for multiple time.
Examples::
bot.press_and_tap("ctrl", "shift", "c")
**中文文档**
按下三个键的组合键。
"""
press_key1 = self._parse_key(press_key1)
press_key2 = self._parse_key(press_key2)
tap_key = self._parse_key(tap_key)
self.delay(pre_dl)
self.k.press_key(press_key1)
self.k.press_key(press_key2)
self.k.tap_key(tap_key, n, interval)
self.k.release_key(press_key1)
self.k.release_key(press_key2)
self.delay(post_dl)
def ctrl_c(self, pre_dl=None, post_dl=None):
"""Press Ctrl + C, usually for copy.
**中文文档**
按下 Ctrl + C 组合键, 通常用于复制。
"""
self.delay(pre_dl)
self.k.press_key(self.k.control_key)
self.k.tap_key("c")
self.k.release_key(self.k.control_key)
self.delay(post_dl)
def ctrl_v(self, pre_dl=None, post_dl=None):
"""Press Ctrl + V, usually for paste.
**中文文档**
按下 Ctrl + V 组合键, 通常用于粘贴。
"""
self.delay(pre_dl)
self.k.press_key(self.k.control_key)
self.k.tap_key("v")
self.k.release_key(self.k.control_key)
self.delay(post_dl)
def ctrl_x(self, pre_dl=None, post_dl=None):
"""Press Ctrl + X, usually for cut.
**中文文档**
按下 Ctrl + X 组合键, 通常用于剪切。
"""
self.delay(pre_dl)
self.k.press_key(self.k.control_key)
self.k.tap_key("x")
self.k.release_key(self.k.control_key)
self.delay(post_dl)
def ctrl_z(self, pre_dl=None, post_dl=None):
"""Press Ctrl + Z, usually for undo.
**中文文档**
按下 Ctrl + Z 组合键, 通常用于撤销上一次动作。
"""
self.delay(pre_dl)
self.k.press_key(self.k.control_key)
self.k.tap_key("z")
self.k.release_key(self.k.control_key)
self.delay(post_dl)
def ctrl_y(self, pre_dl=None, post_dl=None):
"""Press Ctrl + Y, usually for redo.
**中文文档**
按下 Ctrl + Y 组合键, 通常用于重复上一次动作。
"""
self.delay(pre_dl)
self.k.press_key(self.k.control_key)
self.k.tap_key("y")
self.k.release_key(self.k.control_key)
self.delay(post_dl)
def ctrl_a(self, pre_dl=None, post_dl=None):
"""Press Ctrl + A, usually for select all.
**中文文档**
按下 Ctrl + A 组合键, 通常用于选择全部。
"""
self.delay(pre_dl)
self.k.press_key(self.k.control_key)
self.k.tap_key("a")
self.k.release_key(self.k.control_key)
self.delay(post_dl)
def ctrl_f(self, pre_dl=None, post_dl=None):
"""Press Ctrl + F, usually for search.
**中文文档**
按下 Ctrl + F 组合键, 通常用于搜索。
"""
self.delay(pre_dl)
self.k.press_key(self.k.control_key)
self.k.tap_key("f")
self.k.release_key(self.k.control_key)
self.delay(post_dl)
def ctrl_fn(self, i, pre_dl=None, post_dl=None):
"""Press Ctrl + Fn1 ~ 12 once.
**中文文档**
按下 Ctrl + Fn1 ~ 12 组合键。
"""
self.delay(pre_dl)
self.k.press_key(self.k.control_key)
self.k.tap_key(self.k.function_keys[i])
self.k.release_key(self.k.control_key)
self.delay(post_dl)
def alt_fn(self, i, pre_dl=None, post_dl=None):
"""Press Alt + Fn1 ~ 12 once.
**中文文档**
按下 Alt + Fn1 ~ 12 组合键。
"""
self.delay(pre_dl)
self.k.press_key(self.k.alt_key)
self.k.tap_key(self.k.function_keys[i])
self.k.release_key(self.k.alt_key)
self.delay(post_dl)
def shift_fn(self, i, pre_dl=None, post_dl=None):
"""Press Shift + Fn1 ~ 12 once.
**中文文档**
按下 Shift + Fn1 ~ 12 组合键。
"""
self.delay(pre_dl)
self.k.press_key(self.k.shift_key)
self.k.tap_key(self.k.function_keys[i])
self.k.release_key(self.k.shift_key)
self.delay(post_dl)
def alt_tab(self, n=1, pre_dl=None, post_dl=None):
"""Press Alt + Tab once, usually for switching between windows.
Tab can be tapped for n times, default once.
**中文文档**
按下 Alt + Tab 组合键, 其中Tab键按 n 次, 通常用于切换窗口。
"""
self.delay(pre_dl)
self.k.press_key(self.k.alt_key)
self.k.tap_key(self.k.tab_key, n=n, interval=0.1)
self.k.release_key(self.k.alt_key)
self.delay(post_dl)
#--- Other ---
def type_string(self, text, interval=0, pre_dl=None, post_dl=None):
"""Enter strings.
**中文文档**
从键盘输入字符串, interval是字符间输入时间间隔, 单位是秒。
"""
self.delay(pre_dl)
self.k.type_string(text, interval)
self.delay(post_dl)
def copy_text_to_clipboard(self, text):
"""Copy text to clipboard.
**中文文档**
拷贝字符串到剪贴板。
"""
pyperclip.copy(text)
|
class Bot(object):
'''Mouse and Keyboard robot class.
Abbreviation table:
- m: stands for mouse
- k: stands for keyboard
- dl: stands for delay
- n: how many times you want to tap the key
- i: usually for the ith function key, F1 ~ F12
Almost every method have an option keyword ``dl`` (dl stands for delay), there
is ``dl`` seconds delay applied at begin. By default it is ``None``, means no
delay applied.
Keyboard Key Name Table (Case Insensitive)::
# Main Keyboard Keys
"ctrl": self.k.control_key,
"l_ctrl": self.k.control_l_key,
"r_ctrl": self.k.control_r_key,
"alt": self.k.alt_key,
"l_alt": self.k.alt_l_key,
"r_alt": self.k.alt_r_key,
"shift": self.k.shift_key,
"l_shift": self.k.shift_l_key,
"r_shift": self.k.shift_r_key,
"tab": self.k.tab_key,
"space": self.k.space_key,
"enter": self.k.enter_key,
"back": self.k.backspace_key,
"backspace": self.k.backspace_key,
# Side Keyboard Keys
"home": self.k.home_key,
"end": self.k.end_key,
"page_up": self.k.page_up_key,
"pageup": self.k.page_up_key,
"page_down": self.k.page_down_key,
"page_down": self.k.page_down_key,
"insert": self.k.insert_key,
"ins": self.k.insert_key,
"delete": self.k.delete_key,
"del": self.k.delete_key,
"up": self.k.up_key,
"down": self.k.down_key,
"left": self.k.left_key,
"right": self.k.right_key,
# Function Keys
"f1": F1
'''
def __init__(self):
pass
def _parse_key(self, name):
pass
def delay(self, dl=0):
'''Delay for ``dl`` seconds.
'''
pass
def get_screen_size(self):
'''Return screen's width and height in pixel.
**中文文档**
返回屏幕的像素尺寸。
'''
pass
def get_position(self):
'''Return the current coordinate of mouse.
**中文文档**
返回鼠标所处的位置坐标。
'''
pass
def left_click(self, x, y, n=1, pre_dl=None, post_dl=None):
'''Left click at ``(x, y)`` on screen for ``n`` times.
at begin.
**中文文档**
在屏幕的 ``(x, y)`` 坐标处左键单击 ``n`` 次。
'''
pass
def right_click(self, x, y, n=1, pre_dl=None, post_dl=None):
'''Right click at ``(x, y)`` on screen for ``n`` times.
at begin.
**中文文档**
在屏幕的 ``(x, y)`` 坐标处右键单击 ``n`` 次。
'''
pass
def middle_click(self, x, y, n=1, pre_dl=None, post_dl=None):
'''Middle click at ``(x, y)`` on screen for ``n`` times.
at begin.
**中文文档**
在屏幕的 ``(x, y)`` 坐标处中键单击 ``n`` 次。
'''
pass
def scroll_up(self, n, pre_dl=None, post_dl=None):
'''Scroll up ``n`` times.
**中文文档**
鼠标滚轮向上滚动n次。
'''
pass
def scroll_down(self, n, pre_dl=None, post_dl=None):
'''Scroll down ``n`` times.
**中文文档**
鼠标滚轮向下滚动n次。
'''
pass
def scroll_right(self, n, pre_dl=None, post_dl=None):
'''Scroll right ``n`` times.
**中文文档**
鼠标滚轮向右滚动n次(如果可能的话)。
'''
pass
def scroll_left(self, n, pre_dl=None, post_dl=None):
'''Scroll left ``n`` times.
**中文文档**
鼠标滚轮向左滚动n次(如果可能的话)。
'''
pass
def move_to(self, x, y, pre_dl=None, post_dl=None):
'''Move mouse to (x, y)
**中文文档**
移动鼠标到 (x, y) 的坐标处。
'''
pass
def drag_and_release(self, start_x, start_y, end_x, end_y, pre_dl=None, post_dl=None):
'''Drag something from (start_x, start_y) to (end_x, endy)
**中文文档**
从start的坐标处鼠标左键单击拖曳到end的坐标处
start, end是tuple. 格式是(x, y)
'''
pass
def tap_key(self, key_name, n=1, interval=0, pre_dl=None, post_dl=None):
'''Tap a key on keyboard for ``n`` times, with ``interval`` seconds of
interval. Key is declared by it's name
Example::
bot.tap_key("a")
bot.tap_key(1)
bot.tap_key("up")
bot.tap_key("space")
bot.tap_key("enter")
bot.tap_key("tab")
**中文文档**
以 ``interval`` 中定义的频率按下某个按键 ``n`` 次。接受按键名作为输入。
'''
pass
def enter(self, n=1, interval=0, pre_dl=None, post_dl=None):
'''Press enter key n times.
**中文文档**
按回车键/换行键 n 次。
'''
pass
def backspace(self, n=1, interval=0, pre_dl=None, post_dl=None):
'''Press backspace key n times.
**中文文档**
按退格键 n 次。
'''
pass
def space(self, n=1, interval=0, pre_dl=None, post_dl=None):
'''Press white space key n times.
**中文文档**
按空格键 n 次。
'''
pass
def fn(self, i, n=1, interval=0, pre_dl=None, post_dl=None):
'''Press Fn key n times.
**中文文档**
按 Fn 功能键 n 次。
'''
pass
def tab(self, n=1, interval=0, pre_dl=None, post_dl=None):
'''Tap ``tab`` key for ``n`` times, with ``interval`` seconds of interval.
**中文文档**
以 ``interval`` 中定义的频率按下某个tab键 ``n`` 次。
'''
pass
def up(self, n=1, interval=0, pre_dl=None, post_dl=None):
'''Press up key n times.
**中文文档**
按上方向键 n 次。
'''
pass
def down(self, n=1, interval=0, pre_dl=None, post_dl=None):
'''Press down key n times.
**中文文档**
按下方向键 n 次。
'''
pass
def left_click(self, x, y, n=1, pre_dl=None, post_dl=None):
'''Press left key n times
**中文文档**
按左方向键 n 次。
'''
pass
def right_click(self, x, y, n=1, pre_dl=None, post_dl=None):
'''Press right key n times.
**中文文档**
按右方向键 n 次。
'''
pass
def delete(self, n=1, interval=0, pre_dl=None, post_dl=None):
'''Pres delete key n times.
**中文文档**
按 delete 键n次。
'''
pass
def insert(self, n=1, interval=0, pre_dl=None, post_dl=None):
'''Pres insert key n times.
**中文文档**
按 insert 键n次。
'''
pass
def home(self, n=1, interval=0, pre_dl=None, post_dl=None):
'''Pres home key n times.
**中文文档**
按 home 键n次。
'''
pass
def end(self, n=1, interval=0, pre_dl=None, post_dl=None):
'''Press end key n times.
**中文文档**
按 end 键n次。
'''
pass
def page_up(self, n=1, interval=0, pre_dl=None, post_dl=None):
'''Pres page_up key n times.
**中文文档**
按 page_up 键n次。
'''
pass
def page_down(self, n=1, interval=0, pre_dl=None, post_dl=None):
'''Pres page_down key n times.
**中文文档**
按 page_down 键n次。
'''
pass
def press_and_tap(self, press_key, tap_key, n=1, interval=0, pre_dl=None, post_dl=None):
'''Press combination of two keys, like Ctrl + C, Alt + F4. The second
key could be tapped for multiple time.
Examples::
bot.press_and_tap("ctrl", "c")
bot.press_and_tap("shift", "1")
**中文文档**
按下两个键的组合键。
'''
pass
def press_two_and_tap(self,
press_key1, press_key2, tap_key, n=1, interval=0, pre_dl=None, post_dl=None):
'''Press combination of three keys, like Ctrl + Shift + C, The tap key
could be tapped for multiple time.
Examples::
bot.press_and_tap("ctrl", "shift", "c")
**中文文档**
按下三个键的组合键。
'''
pass
def ctrl_c(self, pre_dl=None, post_dl=None):
'''Press Ctrl + C, usually for copy.
**中文文档**
按下 Ctrl + C 组合键, 通常用于复制。
'''
pass
def ctrl_v(self, pre_dl=None, post_dl=None):
'''Press Ctrl + V, usually for paste.
**中文文档**
按下 Ctrl + V 组合键, 通常用于粘贴。
'''
pass
def ctrl_x(self, pre_dl=None, post_dl=None):
'''Press Ctrl + X, usually for cut.
**中文文档**
按下 Ctrl + X 组合键, 通常用于剪切。
'''
pass
def ctrl_z(self, pre_dl=None, post_dl=None):
'''Press Ctrl + Z, usually for undo.
**中文文档**
按下 Ctrl + Z 组合键, 通常用于撤销上一次动作。
'''
pass
def ctrl_y(self, pre_dl=None, post_dl=None):
'''Press Ctrl + Y, usually for redo.
**中文文档**
按下 Ctrl + Y 组合键, 通常用于重复上一次动作。
'''
pass
def ctrl_a(self, pre_dl=None, post_dl=None):
'''Press Ctrl + A, usually for select all.
**中文文档**
按下 Ctrl + A 组合键, 通常用于选择全部。
'''
pass
def ctrl_f(self, pre_dl=None, post_dl=None):
'''Press Ctrl + F, usually for search.
**中文文档**
按下 Ctrl + F 组合键, 通常用于搜索。
'''
pass
def ctrl_fn(self, i, pre_dl=None, post_dl=None):
'''Press Ctrl + Fn1 ~ 12 once.
**中文文档**
按下 Ctrl + Fn1 ~ 12 组合键。
'''
pass
def alt_fn(self, i, pre_dl=None, post_dl=None):
'''Press Alt + Fn1 ~ 12 once.
**中文文档**
按下 Alt + Fn1 ~ 12 组合键。
'''
pass
def shift_fn(self, i, pre_dl=None, post_dl=None):
'''Press Shift + Fn1 ~ 12 once.
**中文文档**
按下 Shift + Fn1 ~ 12 组合键。
'''
pass
def alt_tab(self, n=1, pre_dl=None, post_dl=None):
'''Press Alt + Tab once, usually for switching between windows.
Tab can be tapped for n times, default once.
**中文文档**
按下 Alt + Tab 组合键, 其中Tab键按 n 次, 通常用于切换窗口。
'''
pass
def type_string(self, text, interval=0, pre_dl=None, post_dl=None):
'''Enter strings.
**中文文档**
从键盘输入字符串, interval是字符间输入时间间隔, 单位是秒。
'''
pass
def copy_text_to_clipboard(self, text):
'''Copy text to clipboard.
**中文文档**
拷贝字符串到剪贴板。
'''
pass
| 46 | 44 | 12 | 2 | 6 | 4 | 1 | 0.95 | 1 | 4 | 0 | 0 | 45 | 4 | 45 | 45 | 647 | 150 | 255 | 55 | 208 | 242 | 219 | 54 | 173 | 3 | 1 | 1 | 50 |
148,157 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/vendor/fileutils.py
|
pathlib_mate.vendor.fileutils.DummyFile
|
class DummyFile(file):
# TODO: raise ValueErrors on closed for all methods?
# TODO: enforce read/write
def __init__(self, path, mode='r', buffering=None):
self.name = path
self.mode = mode
self.closed = False
self.errors = None
self.isatty = False
self.encoding = None
self.newlines = None
self.softspace = 0
def close(self):
self.closed = True
def fileno(self):
return -1
def flush(self):
if self.closed:
raise ValueError('I/O operation on a closed file')
return
def next(self):
raise StopIteration()
def read(self, size=0):
if self.closed:
raise ValueError('I/O operation on a closed file')
return ''
def readline(self, size=0):
if self.closed:
raise ValueError('I/O operation on a closed file')
return ''
def readlines(self, size=0):
if self.closed:
raise ValueError('I/O operation on a closed file')
return []
def seek(self):
if self.closed:
raise ValueError('I/O operation on a closed file')
return
def tell(self):
if self.closed:
raise ValueError('I/O operation on a closed file')
return 0
def truncate(self):
if self.closed:
raise ValueError('I/O operation on a closed file')
return
def write(self, string):
if self.closed:
raise ValueError('I/O operation on a closed file')
return
def writelines(self, list_of_strings):
if self.closed:
raise ValueError('I/O operation on a closed file')
return
def __next__(self):
raise StopIteration()
def __enter__(self):
if self.closed:
raise ValueError('I/O operation on a closed file')
return
def __exit__(self, exc_type, exc_val, exc_tb):
return
|
class DummyFile(file):
def __init__(self, path, mode='r', buffering=None):
pass
def close(self):
pass
def fileno(self):
pass
def flush(self):
pass
def next(self):
pass
def read(self, size=0):
pass
def readline(self, size=0):
pass
def readlines(self, size=0):
pass
def seek(self):
pass
def tell(self):
pass
def truncate(self):
pass
def write(self, string):
pass
def writelines(self, list_of_strings):
pass
def __next__(self):
pass
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
| 17 | 0 | 4 | 0 | 4 | 0 | 2 | 0.03 | 1 | 2 | 0 | 0 | 16 | 8 | 16 | 16 | 77 | 15 | 60 | 25 | 43 | 2 | 60 | 25 | 43 | 2 | 1 | 1 | 26 |
148,158 |
MacHu-GWU/pathlib_mate-project
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_pathlib_mate-project/pathlib_mate/vendor/fileutils.py
|
pathlib_mate.vendor.fileutils.FilePerms._FilePermProperty
|
class _FilePermProperty(object):
_perm_chars = 'rwx'
_perm_set = frozenset('rwx')
_perm_val = {'r': 4, 'w': 2, 'x': 1} # for sorting
def __init__(self, attribute, offset):
self.attribute = attribute
self.offset = offset
def __get__(self, fp_obj, type_=None):
if fp_obj is None:
return self
return getattr(fp_obj, self.attribute)
def __set__(self, fp_obj, value):
cur = getattr(fp_obj, self.attribute)
if cur == value:
return
try:
invalid_chars = set(str(value)) - self._perm_set
except TypeError:
raise TypeError('expected string, not %r' % value)
if invalid_chars:
raise ValueError('got invalid chars %r in permission'
' specification %r, expected empty string'
' or one or more of %r'
% (invalid_chars, value, self._perm_chars))
def sort_key(c): return self._perm_val[c]
new_value = ''.join(sorted(set(value),
key=sort_key, reverse=True))
setattr(fp_obj, self.attribute, new_value)
self._update_integer(fp_obj, new_value)
def _update_integer(self, fp_obj, value):
mode = 0
key = 'xwr'
for symbol in value:
bit = 2 ** key.index(symbol)
mode |= (bit << (self.offset * 3))
fp_obj._integer |= mode
|
class _FilePermProperty(object):
def __init__(self, attribute, offset):
pass
def __get__(self, fp_obj, type_=None):
pass
def __set__(self, fp_obj, value):
pass
def sort_key(c):
pass
def _update_integer(self, fp_obj, value):
pass
| 6 | 0 | 8 | 0 | 8 | 0 | 2 | 0.03 | 1 | 4 | 0 | 0 | 4 | 2 | 4 | 4 | 41 | 5 | 36 | 18 | 31 | 1 | 32 | 18 | 27 | 4 | 1 | 1 | 9 |
148,159 |
MacHu-GWU/pathlib_mate-project
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_pathlib_mate-project/pathlib_mate/vendor/six.py
|
pathlib_mate.vendor.six.Iterator
|
class Iterator(object):
def next(self):
return type(self).__next__(self)
|
class Iterator(object):
def next(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 4 | 1 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
148,160 |
MacHu-GWU/pathlib_mate-project
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_pathlib_mate-project/pathlib_mate/vendor/six.py
|
pathlib_mate.vendor.six.X
|
class X(object):
def __len__(self):
return 1 << 31
|
class X(object):
def __len__(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 4 | 1 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
148,161 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/pathlib2.py
|
pathlib_mate.pathlib2.PureWindowsPath
|
class PureWindowsPath(PurePath):
"""PurePath subclass for Windows systems.
On a Windows system, instantiating a PurePath should return this object.
However, you can also instantiate it directly on any system.
"""
_flavour = _windows_flavour
__slots__ = ()
|
class PureWindowsPath(PurePath):
'''PurePath subclass for Windows systems.
On a Windows system, instantiating a PurePath should return this object.
However, you can also instantiate it directly on any system.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.33 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 40 | 8 | 1 | 3 | 3 | 2 | 4 | 3 | 3 | 2 | 0 | 2 | 0 | 0 |
148,162 |
MacHu-GWU/pathlib_mate-project
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_pathlib_mate-project/pathlib_mate/pathlib2.py
|
pathlib_mate.pathlib2._win32_get_unique_path_id.FILETIME
|
class FILETIME(Structure):
_fields_ = [("datetime_lo", DWORD),
("datetime_hi", DWORD),
]
|
class FILETIME(Structure):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 0 | 4 | 2 | 3 | 0 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
148,163 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/pathlib2.py
|
pathlib_mate.pathlib2.PurePosixPath
|
class PurePosixPath(PurePath):
_flavour = _posix_flavour
__slots__ = ()
|
class PurePosixPath(PurePath):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 40 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 2 | 0 | 0 |
148,164 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/pathlib2.py
|
pathlib_mate.pathlib2.PosixPath
|
class PosixPath(Path, PurePosixPath):
"""Path subclass for non-Windows systems.
On a POSIX system, instantiating a Path should return this object.
"""
__slots__ = ()
|
class PosixPath(Path, PurePosixPath):
'''Path subclass for non-Windows systems.
On a POSIX system, instantiating a Path should return this object.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 167 | 6 | 1 | 2 | 2 | 1 | 3 | 2 | 2 | 1 | 0 | 4 | 0 | 0 |
148,165 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/mate_tool_box_zip.py
|
pathlib_mate.mate_tool_box_zip.ToolBoxZip
|
class ToolBoxZip(object):
"""
Provide zip related functions.
"""
def _default_zip_dst(self):
"""
automatically create destination zip file ``Path`` object.
:type self: Path
:rtype: Path
"""
new_basename = "{}-{}-{}.zip".format(
self.basename,
datetime.now().strftime("%Y-%m-%d-%Hh-%Mm-%Ss"),
rand_str(4),
)
return self.change(new_basename=new_basename)
def make_zip_archive(
self,
dst=None,
filters=all_true,
compress=True,
overwrite=False,
makedirs=False,
include_dir=True,
verbose=False,
):
"""
Make a zip archive of a directory or a file.
:type self: Path
:type dst: Optional[Union[Path, str]]
:param dst: output file path. if not given, will be automatically assigned.
:type filters: typing.Callable
:param filters: custom path filter. By default it allows any file.
:type compress: bool
:param compress: compress or not.
:type verbose: bool
:param overwrite: overwrite exists or not.
:type makedirs: bool
:param makedirs: if True, automatically create the parent dir if not
exists
:type include_dir: bool
:param include_dir: if True, then you will see the source dir when you
unzip it. It only apply when zipping a directory
:type verbose: bool
:param verbose: display log or not.
"""
self.assert_exists()
if dst is None:
dst = self._default_zip_dst()
else:
dst = self.change(new_abspath=dst)
if not dst.basename.lower().endswith(".zip"):
raise ValueError("zip archive name has to be endswith '.zip'!")
if dst.exists():
if not overwrite:
raise IOError("'%s' already exists!" % dst)
if compress:
compression = ZIP_DEFLATED
else:
compression = ZIP_STORED
if not dst.parent.exists():
if makedirs: # pragma: no cover
os.makedirs(dst.parent.abspath)
if verbose:
msg = "Making zip archive for '%s' ..." % self
print(msg)
if self.is_dir():
total_size = 0
selected = list()
for p in self.glob("**/*"):
if filters(p):
selected.append(p)
total_size += p.size
if verbose:
msg = "Got {} files, total size is {}, compressing ...".format(
len(selected),
repr_data_size(total_size),
)
print(msg)
with ZipFile(dst.abspath, "w", compression) as f:
if include_dir:
relpath_root = self.parent
else:
relpath_root = self
for p in selected:
relpath = p.relative_to(relpath_root).__str__()
f.write(p.abspath, relpath)
elif self.is_file():
with ZipFile(dst.abspath, "w", compression) as f:
f.write(self.abspath, self.basename)
if verbose:
msg = "Complete! Archive size is {}.".format(dst.size_in_text)
print(msg)
def backup(
self,
dst=None,
ignore=None,
ignore_ext=None,
ignore_pattern=None,
ignore_size_smaller_than=None,
ignore_size_larger_than=None,
case_sensitive=False,
include_dir=True,
verbose=True,
): # pragma: no cover
"""
Create a compressed zip archive backup for a directory.
:type self: Path
:type dst: Optional[Union[Path, str]]
:param dst: the output file path.
:type ignore: Optional[List[str]]
:param ignore: file or directory defined in this list will be ignored.
:type ignore_ext: Optional[List[str]]
:param ignore_ext: file with extensions defined in this list will be ignored.
:type ignore_pattern: Optional[List[str]]
:param ignore_pattern: any file or directory that contains this pattern
will be ignored.
:type ignore_size_smaller_than: int
:param ignore_size_smaller_than: any file size smaller than this
will be ignored.
:type ignore_size_larger_than: int
:param ignore_size_larger_than: any file size larger than this
will be ignored.
:type case_sensitive: bool
:param case_sensitive: if True, the ignore rules are case sensitive
:type include_dir: bool
:param include_dir: if True, then you will see the source dir when you
unzip it. It only apply when zipping a directory
:type verbose: bool
:param verbose: display log or not.
**中文文档**
为一个目录创建一个备份压缩包。可以通过过滤器选择你要备份的文件。
"""
def preprocess_arg(arg): # pragma: no cover
if arg is None:
return []
if isinstance(arg, (tuple, list)):
return list(arg)
else:
return [
arg,
]
ignore = preprocess_arg(ignore)
for i in ignore:
if i.startswith("/") or i.startswith("\\"):
raise ValueError
ignore_ext = preprocess_arg(ignore_ext)
for ext in ignore_ext:
if not ext.startswith("."):
raise ValueError
ignore_pattern = preprocess_arg(ignore_pattern)
if case_sensitive:
pass
else:
ignore = [i.lower() for i in ignore]
ignore_ext = [i.lower() for i in ignore_ext]
ignore_pattern = [i.lower() for i in ignore_pattern]
def filters(p):
relpath = p.relative_to(self).abspath
if not case_sensitive:
relpath = relpath.lower()
# ignore
for i in ignore:
if relpath.startswith(i):
return False
# ignore_ext
if case_sensitive:
ext = p.ext
else:
ext = p.ext.lower()
if ext in ignore_ext:
return False
# ignore_pattern
for pattern in ignore_pattern:
if pattern in relpath:
return False
# ignore_size_smaller_than
if ignore_size_smaller_than:
if p.size < ignore_size_smaller_than:
return False
# ignore_size_larger_than
if ignore_size_larger_than:
if p.size > ignore_size_larger_than:
return False
return True
self.make_zip_archive(
dst=dst,
filters=filters,
compress=True,
overwrite=False,
include_dir=include_dir,
verbose=verbose,
)
|
class ToolBoxZip(object):
'''
Provide zip related functions.
'''
def _default_zip_dst(self):
'''
automatically create destination zip file ``Path`` object.
:type self: Path
:rtype: Path
'''
pass
def make_zip_archive(
self,
dst=None,
filters=all_true,
compress=True,
overwrite=False,
makedirs=False,
include_dir=True,
verbose=False,
):
'''
Make a zip archive of a directory or a file.
:type self: Path
:type dst: Optional[Union[Path, str]]
:param dst: output file path. if not given, will be automatically assigned.
:type filters: typing.Callable
:param filters: custom path filter. By default it allows any file.
:type compress: bool
:param compress: compress or not.
:type verbose: bool
:param overwrite: overwrite exists or not.
:type makedirs: bool
:param makedirs: if True, automatically create the parent dir if not
exists
:type include_dir: bool
:param include_dir: if True, then you will see the source dir when you
unzip it. It only apply when zipping a directory
:type verbose: bool
:param verbose: display log or not.
'''
pass
def backup(
self,
dst=None,
ignore=None,
ignore_ext=None,
ignore_pattern=None,
ignore_size_smaller_than=None,
ignore_size_larger_than=None,
case_sensitive=False,
include_dir=True,
verbose=True,
):
'''
Create a compressed zip archive backup for a directory.
:type self: Path
:type dst: Optional[Union[Path, str]]
:param dst: the output file path.
:type ignore: Optional[List[str]]
:param ignore: file or directory defined in this list will be ignored.
:type ignore_ext: Optional[List[str]]
:param ignore_ext: file with extensions defined in this list will be ignored.
:type ignore_pattern: Optional[List[str]]
:param ignore_pattern: any file or directory that contains this pattern
will be ignored.
:type ignore_size_smaller_than: int
:param ignore_size_smaller_than: any file size smaller than this
will be ignored.
:type ignore_size_larger_than: int
:param ignore_size_larger_than: any file size larger than this
will be ignored.
:type case_sensitive: bool
:param case_sensitive: if True, the ignore rules are case sensitive
:type include_dir: bool
:param include_dir: if True, then you will see the source dir when you
unzip it. It only apply when zipping a directory
:type verbose: bool
:param verbose: display log or not.
**中文文档**
为一个目录创建一个备份压缩包。可以通过过滤器选择你要备份的文件。
'''
pass
def preprocess_arg(arg):
pass
def filters(p):
pass
| 6 | 4 | 56 | 11 | 33 | 13 | 8 | 0.48 | 1 | 5 | 0 | 1 | 3 | 0 | 3 | 3 | 244 | 51 | 132 | 41 | 106 | 64 | 89 | 20 | 83 | 17 | 1 | 3 | 39 |
148,166 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/mate_tool_box.py
|
pathlib_mate.mate_tool_box.ToolBox
|
class ToolBox(ToolBoxZip):
def get_dir_fingerprint(self, hash_meth):
"""
Return md5 fingerprint of a directory. Calculation is based on
iterate recursively through all files, ordered by absolute path,
and stream in md5 for each file.
:type self: Path
:type hash_meth: Callable
:rtype: str
"""
m = hash_meth()
for p in self.sort_by_abspath(self.select_file(recursive=True)):
m.update(str(p).encode("utf-8"))
m.update(p.md5.encode("utf-8"))
return m.hexdigest()
@property
def dir_md5(self):
"""
Return md5 fingerprint of a directory.
See :meth:`ToolBox.get_dir_fingerprint` for details
:type self: Path
:rtype: str
"""
return self.get_dir_fingerprint(hashlib.md5)
@property
def dir_sha256(self):
"""
Return sha256 fingerprint of a directory.
See :meth:`ToolBox.get_dir_fingerprint` for details
:type self: Path
:rtype: str
"""
return self.get_dir_fingerprint(hashlib.sha256)
@property
def dir_sha512(self):
"""
Return sha512 fingerprint of a directory.
See :meth:`ToolBox.get_dir_fingerprint` for details
:type self: Path
:rtype: str
"""
return self.get_dir_fingerprint(hashlib.sha512)
def is_empty(self, strict=True):
"""
If it's a file, check if it is a empty file. (0 bytes content)
If it's a directory, check if there's no file and dir in it.
But if ``strict = False``, then only check if there's no file in it.
:type self: Path
:type strict: bool
:param strict: only useful when it is a directory. if True, only
return True if this dir has no dir and file. if False, return True
if it doesn't have any file.
:rtype: bool
"""
if self.exists():
if self.is_file():
return self.size == 0
elif self.is_dir():
if strict:
return len(list(self.select(recursive=True))) == 0
else: # pragma: no cover
return len(list(self.select_file(recursive=True))) == 0
else: # pragma: no cover
msg = "'%s' is not either file or directory! (maybe simlink)" % self
raise EnvironmentError(msg)
else:
raise EnvironmentError("'%s' not exists!" % self)
def auto_complete_choices(self, case_sensitive=False):
"""
A command line auto complete similar behavior. Find all item with same
prefix of this one.
:type self: Path
:type case_sensitive: bool
:param case_sensitive: toggle if it is case sensitive.
:rtype: List[Path]
:return: list of :class:`pathlib_mate.pathlib2.Path`.
"""
self_basename = self.basename
self_basename_lower = self.basename.lower()
if case_sensitive: # pragma: no cover
def match(basename):
return basename.startswith(self_basename)
else:
def match(basename):
return basename.lower().startswith(self_basename_lower)
choices = list()
if self.is_dir():
choices.append(self)
for p in self.sort_by_abspath(self.select(recursive=False)):
choices.append(p)
else:
p_parent = self.parent
if p_parent.is_dir():
for p in self.sort_by_abspath(p_parent.select(recursive=False)):
if match(p.basename):
choices.append(p)
else: # pragma: no cover
raise ValueError("'%s' directory does not exist!" % p_parent)
return choices
# --- Directory Exclusive Method ---
def print_big_dir(self, top_n=5):
"""
Print ``top_n`` big dir in this dir.
:type self: Path
:type top_n: int
"""
self.assert_is_dir_and_exists()
size_table = sorted(
[(p, p.dirsize) for p in self.select_dir(recursive=False)],
key=lambda x: x[1],
reverse=True,
)
for p, size in size_table[:top_n]:
print("{:<9} {:<9}".format(repr_data_size(size), p.abspath))
def print_big_file(self, top_n=5):
"""
Print ``top_n`` big file in this dir.
:type self: Path
:type top_n: int
"""
self.assert_is_dir_and_exists()
size_table = sorted(
[(p, p.size) for p in self.select_file(recursive=True)],
key=lambda x: x[1],
reverse=True,
)
for p, size in size_table[:top_n]:
print("{:<9} {:<9}".format(repr_data_size(size), p.abspath))
def print_big_dir_and_big_file(self, top_n=5):
"""
Print ``top_n`` big dir and ``top_n`` big file in each dir.
:type self: Path
:type top_n: int
"""
self.assert_is_dir_and_exists()
size_table1 = sorted(
[(p, p.dirsize) for p in self.select_dir(recursive=False)],
key=lambda x: x[1],
reverse=True,
)
for p1, size1 in size_table1[:top_n]:
print("{:<9} {:<9}".format(repr_data_size(size1), p1.abspath))
size_table2 = sorted(
[(p, p.size) for p in p1.select_file(recursive=True)],
key=lambda x: x[1],
reverse=True,
)
for p2, size2 in size_table2[:top_n]:
print(" {:<9} {:<9}".format(repr_data_size(size2), p2.abspath))
def file_stat_for_all(self, filters=all_true): # pragma: no cover
"""
Find out how many files, directories and total size (Include file in
it's sub-folder) it has for each folder and sub-folder.
:type self: Path
:type filters: Callable
:rtype: dict
:returns: stat, a dict like ``{"directory path": {
"file": number of files, "dir": number of directories,
"size": total size in bytes}}``
**中文文档**
返回一个目录中的每个子目录的, 文件, 文件夹, 大小的统计数据。
"""
self.assert_is_dir_and_exists()
from collections import OrderedDict
stat = OrderedDict()
stat[self.abspath] = {"file": 0, "dir": 0, "size": 0}
for p in self.select(filters=filters, recursive=True):
if p.is_file():
size = p.size
while 1:
parent = p.parent
stat[parent.abspath]["file"] += 1
stat[parent.abspath]["size"] += size
if parent.abspath == self.abspath:
break
p = parent
elif p.is_dir():
stat[p.abspath] = {"file": 0, "dir": 0, "size": 0}
while 1:
parent = p.parent
stat[parent.abspath]["dir"] += 1
if parent.abspath == self.abspath:
break
p = parent
return stat
def file_stat(self, filters=all_true):
"""Find out how many files, directorys and total size (Include file in
it's sub-folder).
:type self: Path
:type filters: Callable
:rtype: dict
:returns: stat, a dict like ``{"file": number of files,
"dir": number of directorys, "size": total size in bytes}``
**中文文档**
返回一个目录中的文件, 文件夹, 大小的统计数据。
"""
self.assert_is_dir_and_exists()
stat = {"file": 0, "dir": 0, "size": 0}
for p in self.select(filters=filters, recursive=True):
if p.is_file():
stat["file"] += 1
stat["size"] += p.size
elif p.is_dir():
stat["dir"] += 1
return stat
def mirror_to(self, dst): # pragma: no cover
"""
Create a new folder having exactly same structure with this directory.
However, all files are just empty file with same file name.
:type self: Path
:type dst: str
:param dst: destination directory. The directory can't exists before
you execute this.
**中文文档**
创建一个目录的镜像拷贝, 与拷贝操作不同的是, 文件的副本只是在文件名上
与原件一致, 但是是空文件, 完全没有内容, 文件大小为0。
"""
self.assert_is_dir_and_exists()
src = self.abspath
dst = os.path.abspath(dst)
if os.path.exists(dst): # pragma: no cover
raise Exception("distination already exist!")
for current_folder, _, file_list in os.walk(self.abspath):
current_folder = current_folder.replace(src, dst)
try:
os.mkdir(current_folder)
except: # pragma: no cover
pass
for basename in file_list:
abspath = os.path.join(current_folder, basename)
with open(abspath, "wb") as _:
pass
def execute_pyfile(self, py_exe=None): # pragma: no cover
"""
Execute every ``.py`` file as main script.
:type self: Path
:type py_exe: str
:param py_exe: python command or python executable path.
**中文文档**
将目录下的所有 Python 文件作为主脚本用当前解释器运行。
"""
warnings.warn(
"this feature will be deprecated soon! this is a historical feature",
DeprecationWarning,
)
import subprocess
self.assert_is_dir_and_exists()
if py_exe is None:
if six.PY2:
py_exe = "python2"
elif six.PY3:
py_exe = "python3"
for p in self.select_by_ext(".py"):
subprocess.Popen('%s "%s"' % (py_exe, p.abspath))
def trail_space(self, filters=lambda p: p.ext == ".py"): # pragma: no cover
"""
Trail white space at end of each line for every ``.py`` file.
:type self: Path
:type filters: Callable
**中文文档**
将目录下的所有被选择的文件中行末的空格删除.
"""
self.assert_is_dir_and_exists()
for p in self.select_file(filters):
try:
with open(p.abspath, "rb") as f:
lines = list()
for line in f:
lines.append(line.decode("utf-8").rstrip())
with open(p.abspath, "wb") as f:
f.write("\n".join(lines).encode("utf-8"))
except Exception as e: # pragma: no cover
raise e
def autopep8(self, **kwargs): # pragma: no cover
"""
Auto convert your python code in a directory to pep8 styled code.
:type self: Path
:param kwargs: arguments for ``autopep8.fix_code`` method.
**中文文档**
将目录下的所有 Python 文件用 pep8 风格格式化. 增加其可读性和规范性.
"""
warnings.warn(
"this feature will be deprecated soon! use subprocess + cli instead",
DeprecationWarning,
)
try:
import autopep8
except ImportError as e:
warnings.warn("you have to 'pip install autopep8' to enable this feature!")
raise e
self.assert_is_dir_and_exists()
for p in self.select_by_ext(".py"):
with open(p.abspath, "rb") as f:
code = f.read().decode("utf-8")
formatted_code = autopep8.fix_code(code, **kwargs)
with open(p.abspath, "wb") as f:
f.write(formatted_code.encode("utf-8"))
@contextlib.contextmanager
def temp_cwd(self):
"""
Temporarily set the current working directory and automatically
switch back when it's done.
:type self: Path
:rtype: Path
"""
cwd = os.getcwd()
os.chdir(self.abspath)
try:
yield self
finally:
os.chdir(cwd)
def atomic_write_bytes(self, data, overwrite=False):
"""
An atomic write action for binary data.
Either fully done or nothing happen.
Preventing overwriting existing file with incomplete data.
Reference:
- https://boltons.readthedocs.io/en/latest/fileutils.html#boltons.fileutils.atomic_save
:type self: Path
:type data: bytes
:type overwrite: bool
"""
if overwrite is False: # pragma: no cover
if self.exists():
raise FileExistsError("file already exists!")
with atomic_save(self.abspath, text_mode=False) as f:
f.write(data)
def atomic_write_text(self, data, encoding="utf-8", overwrite=False):
"""
An atomic write action for text. Either fully done or nothing happen.
Preventing overwriting existing file with incomplete data.
Reference:
- https://boltons.readthedocs.io/en/latest/fileutils.html#boltons.fileutils.atomic_save
:type self: Path
:type data: str
:type encoding: str, recommend to use "utf-8"
:type overwrite: bool
:return:
"""
if overwrite is False: # pragma: no cover
if self.exists():
raise FileExistsError("file already exists!")
with atomic_save(self.abspath, text_mode=False) as f:
f.write(data.encode(encoding))
def atomic_open(
self,
mode="r",
buffering=-1,
encoding=None,
errors=None,
newline=None,
overwrite=None,
file_perms=None,
part_file=None,
overwrite_part=None,
):
"""
A context manager that support
:type self: Path
:type mode: str
:param buffering: original argument for ``pathlib.Path.open()``
:param encoding: original argument for ``pathlib.Path.open()``
:param errors: original argument for ``pathlib.Path.open()``
:param newline: original argument for ``pathlib.Path.open()``
:param overwrite: original argument for ``boltons.fileutils.atomic_save()``
:param file_perms: original argument for ``boltons.fileutils.atomic_save()``
:param part_file: original argument for ``boltons.fileutils.atomic_save()``
:param overwrite_part: original argument for ``boltons.fileutils.atomic_save()``
Reference:
- https://boltons.readthedocs.io/en/latest/fileutils.html#boltons.fileutils.atomic_save
"""
if mode in ["r", "rb", "a"]:
return self.open(
mode=mode,
buffering=buffering,
encoding=encoding,
errors=errors,
newline=newline,
)
else:
kwargs = dict(
overwrite=overwrite,
file_perms=file_perms,
part_file=part_file,
overwrite_part=overwrite_part,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
if mode == "w":
return atomic_save(
self.abspath,
text_mode=True,
**kwargs,
)
elif mode == "wb":
return atomic_save(
self.abspath,
text_mode=False,
**kwargs,
)
else: # pragma: no cover
raise ValueError("mode must be one of 'r', 'rb', 'w', 'wb', 'a'!")
|
class ToolBox(ToolBoxZip):
def get_dir_fingerprint(self, hash_meth):
'''
Return md5 fingerprint of a directory. Calculation is based on
iterate recursively through all files, ordered by absolute path,
and stream in md5 for each file.
:type self: Path
:type hash_meth: Callable
:rtype: str
'''
pass
@property
def dir_md5(self):
'''
Return md5 fingerprint of a directory.
See :meth:`ToolBox.get_dir_fingerprint` for details
:type self: Path
:rtype: str
'''
pass
@property
def dir_sha256(self):
'''
Return sha256 fingerprint of a directory.
See :meth:`ToolBox.get_dir_fingerprint` for details
:type self: Path
:rtype: str
'''
pass
@property
def dir_sha512(self):
'''
Return sha512 fingerprint of a directory.
See :meth:`ToolBox.get_dir_fingerprint` for details
:type self: Path
:rtype: str
'''
pass
def is_empty(self, strict=True):
'''
If it's a file, check if it is a empty file. (0 bytes content)
If it's a directory, check if there's no file and dir in it.
But if ``strict = False``, then only check if there's no file in it.
:type self: Path
:type strict: bool
:param strict: only useful when it is a directory. if True, only
return True if this dir has no dir and file. if False, return True
if it doesn't have any file.
:rtype: bool
'''
pass
def auto_complete_choices(self, case_sensitive=False):
'''
A command line auto complete similar behavior. Find all item with same
prefix of this one.
:type self: Path
:type case_sensitive: bool
:param case_sensitive: toggle if it is case sensitive.
:rtype: List[Path]
:return: list of :class:`pathlib_mate.pathlib2.Path`.
'''
pass
def match(basename):
pass
def match(basename):
pass
def print_big_dir(self, top_n=5):
'''
Print ``top_n`` big dir in this dir.
:type self: Path
:type top_n: int
'''
pass
def print_big_file(self, top_n=5):
'''
Print ``top_n`` big file in this dir.
:type self: Path
:type top_n: int
'''
pass
def print_big_dir_and_big_file(self, top_n=5):
'''
Print ``top_n`` big dir and ``top_n`` big file in each dir.
:type self: Path
:type top_n: int
'''
pass
def file_stat_for_all(self, filters=all_true):
'''
Find out how many files, directories and total size (Include file in
it's sub-folder) it has for each folder and sub-folder.
:type self: Path
:type filters: Callable
:rtype: dict
:returns: stat, a dict like ``{"directory path": {
"file": number of files, "dir": number of directories,
"size": total size in bytes}}``
**中文文档**
返回一个目录中的每个子目录的, 文件, 文件夹, 大小的统计数据。
'''
pass
def file_stat_for_all(self, filters=all_true):
'''Find out how many files, directorys and total size (Include file in
it's sub-folder).
:type self: Path
:type filters: Callable
:rtype: dict
:returns: stat, a dict like ``{"file": number of files,
"dir": number of directorys, "size": total size in bytes}``
**中文文档**
返回一个目录中的文件, 文件夹, 大小的统计数据。
'''
pass
def mirror_to(self, dst):
'''
Create a new folder having exactly same structure with this directory.
However, all files are just empty file with same file name.
:type self: Path
:type dst: str
:param dst: destination directory. The directory can't exists before
you execute this.
**中文文档**
创建一个目录的镜像拷贝, 与拷贝操作不同的是, 文件的副本只是在文件名上
与原件一致, 但是是空文件, 完全没有内容, 文件大小为0。
'''
pass
def execute_pyfile(self, py_exe=None):
'''
Execute every ``.py`` file as main script.
:type self: Path
:type py_exe: str
:param py_exe: python command or python executable path.
**中文文档**
将目录下的所有 Python 文件作为主脚本用当前解释器运行。
'''
pass
def trail_space(self, filters=lambda p: p.ext == ".py"):
'''
Trail white space at end of each line for every ``.py`` file.
:type self: Path
:type filters: Callable
**中文文档**
将目录下的所有被选择的文件中行末的空格删除.
'''
pass
def autopep8(self, **kwargs):
'''
Auto convert your python code in a directory to pep8 styled code.
:type self: Path
:param kwargs: arguments for ``autopep8.fix_code`` method.
**中文文档**
将目录下的所有 Python 文件用 pep8 风格格式化. 增加其可读性和规范性.
'''
pass
@contextlib.contextmanager
def temp_cwd(self):
'''
Temporarily set the current working directory and automatically
switch back when it's done.
:type self: Path
:rtype: Path
'''
pass
def atomic_write_bytes(self, data, overwrite=False):
'''
An atomic write action for binary data.
Either fully done or nothing happen.
Preventing overwriting existing file with incomplete data.
Reference:
- https://boltons.readthedocs.io/en/latest/fileutils.html#boltons.fileutils.atomic_save
:type self: Path
:type data: bytes
:type overwrite: bool
'''
pass
def atomic_write_text(self, data, encoding="utf-8", overwrite=False):
'''
An atomic write action for text. Either fully done or nothing happen.
Preventing overwriting existing file with incomplete data.
Reference:
- https://boltons.readthedocs.io/en/latest/fileutils.html#boltons.fileutils.atomic_save
:type self: Path
:type data: str
:type encoding: str, recommend to use "utf-8"
:type overwrite: bool
:return:
'''
pass
def atomic_open(
self,
mode="r",
buffering=-1,
encoding=None,
errors=None,
newline=None,
overwrite=None,
file_perms=None,
part_file=None,
overwrite_part=None,
):
'''
A context manager that support
:type self: Path
:type mode: str
:param buffering: original argument for ``pathlib.Path.open()``
:param encoding: original argument for ``pathlib.Path.open()``
:param errors: original argument for ``pathlib.Path.open()``
:param newline: original argument for ``pathlib.Path.open()``
:param overwrite: original argument for ``boltons.fileutils.atomic_save()``
:param file_perms: original argument for ``boltons.fileutils.atomic_save()``
:param part_file: original argument for ``boltons.fileutils.atomic_save()``
:param overwrite_part: original argument for ``boltons.fileutils.atomic_save()``
Reference:
- https://boltons.readthedocs.io/en/latest/fileutils.html#boltons.fileutils.atomic_save
'''
pass
| 26 | 19 | 23 | 4 | 11 | 8 | 3 | 0.72 | 1 | 10 | 0 | 1 | 19 | 1 | 19 | 22 | 506 | 105 | 242 | 81 | 202 | 174 | 172 | 60 | 147 | 8 | 2 | 4 | 66 |
148,167 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/pathlib2.py
|
pathlib_mate.pathlib2._Accessor
|
class _Accessor:
"""An accessor implements a particular (system-specific or not) way of
accessing paths on the filesystem."""
|
class _Accessor:
'''An accessor implements a particular (system-specific or not) way of
accessing paths on the filesystem.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 4 | 1 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 0 | 0 | 0 | 0 |
148,168 |
MacHu-GWU/pathlib_mate-project
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_pathlib_mate-project/pathlib_mate/pathlib2.py
|
pathlib_mate.pathlib2._win32_get_unique_path_id.BY_HANDLE_FILE_INFORMATION
|
class BY_HANDLE_FILE_INFORMATION(Structure):
_fields_ = [("attributes", DWORD),
("created_at", FILETIME),
("accessed_at", FILETIME),
("written_at", FILETIME),
("volume", DWORD),
("file_hi", DWORD),
("file_lo", DWORD),
("n_links", DWORD),
("index_hi", DWORD),
("index_lo", DWORD),
]
|
class BY_HANDLE_FILE_INFORMATION(Structure):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 12 | 0 | 12 | 2 | 11 | 0 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
148,169 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/mate_mutate_methods.py
|
pathlib_mate.mate_mutate_methods.MutateMethods
|
class MutateMethods(object):
"""
Provide methods to mutate the Path instance.
"""
# --- methods return another Path ---
def drop_parts(self, n=1):
"""
Drop number of parts from the ends. By default, it is equal to
``self.parent``.
Example::
>>> Path("/usr/bin/python").drop_parts(1)
"/user/bin"
>>> Path("/usr/bin/python").drop_parts(2)
"/user"
:type self: Path
:type n: int
:param n: integer, number of parts you wants to drop from ends.
n has to greater equal than 0.
:rtype: Path
:returns: a new Path object.
"""
return self.__class__(*self.parts[:-n])
def append_parts(self, *parts):
"""
Append some parts to the end of this path.
Example::
>>> Path("/usr/bin/python").append_parts("lib")
"/user/bin/python/lib"
>>> Path("/usr/bin/python").append_parts("lib", "core.py")
"/user/bin/python/lib/core.py"
:type self: Path
:rtype: Path
:returns: a new Path object.
"""
return self.__class__(self, *parts)
def change(
self,
new_abspath=None,
new_dirpath=None,
new_dirname=None,
new_basename=None,
new_fname=None,
new_ext=None,
):
"""
Return a new :class:`pathlib_mate.pathlib2.Path` object with updated path.
Example::
>>> Path("/Users/alice/test.py").change(new_fname="test1")
/Users/alice/test1.py
>>> Path("/Users/alice/test.py").change(new_ext=".txt")
/Users/alice/test.txt
>>> Path("/Users/alice/test.py").change(new_dirname="bob")
/Users/bob/test.py
>>> Path("/Users/alice/test.py").change(new_dirpath="/tmp")
/tmp/test.py
:type self: Path
:type new_abspath: Union[str, Path]
:type new_dirpath: str
:type new_dirname: str
:type new_basename: str
:type new_fname: str
:type new_ext: str
:rtype: Path
**中文文档**
高级重命名函数, 允许用于根据路径的各个组成部分进行重命名. 但和 os.rename
方法一样, 需要保证母文件夹存在.
"""
if new_abspath is not None:
p = self.__class__(new_abspath)
return p
if (new_dirpath is None) and (new_dirname is not None):
new_dirpath = os.path.join(self.parent.dirpath, new_dirname)
elif (new_dirpath is not None) and (new_dirname is None):
new_dirpath = new_dirpath
elif (new_dirpath is None) and (new_dirname is None):
new_dirpath = self.dirpath
elif (new_dirpath is not None) and (new_dirname is not None):
raise ValueError("Cannot having both new_dirpath and new_dirname!")
if new_basename is None:
if new_fname is None:
new_fname = self.fname
if new_ext is None:
new_ext = self.ext
new_basename = new_fname + new_ext
else:
if new_fname is not None or new_ext is not None:
raise ValueError(
"Cannot having both new_basename, " "new_fname, new_ext!"
)
return self.__class__(new_dirpath, new_basename)
def is_not_exist_or_allow_overwrite(self, overwrite=False): # pragma: no cover
"""
Test whether a file target is not exists or it exists but allow
overwrite.
:type self: Path
:param overwrite: bool
:rtype: bool
"""
if (not self.exists()) or (overwrite is True):
return True
else:
return False
def moveto(
self,
new_abspath=None,
new_dirpath=None,
new_dirname=None,
new_basename=None,
new_fname=None,
new_ext=None,
overwrite=False,
makedirs=False,
):
"""
Similar to :meth:`~pathlib_mate.mate_mutate_methods.MutateMethods.change`
method. However, it move the original path to new location.
:type self: Path
:type new_abspath: Union[str, Path]
:type new_dirpath: str
:type new_dirname: str
:type new_basename: str
:type new_fname: str
:type new_ext: str
:type overwrite: bool
:type makedirs: bool
:rtype: Path
**中文文档**
高级 文件 / 文件夹 移动函数, 允许用于根据路径的各个组成部分进行重命名, 然后移动.
"""
self.assert_exists()
p = self.change(
new_abspath=new_abspath,
new_dirpath=new_dirpath,
new_dirname=new_dirname,
new_basename=new_basename,
new_fname=new_fname,
new_ext=new_ext,
)
if p.is_not_exist_or_allow_overwrite(overwrite=overwrite):
# 如果两个路径不同, 才进行move
if self.abspath != p.abspath:
if makedirs:
parent = p.parent
if not parent.exists():
os.makedirs(parent.abspath)
self.rename(p)
return p
def copyto(
self,
new_abspath=None,
new_dirpath=None,
new_dirname=None,
new_basename=None,
new_fname=None,
new_ext=None,
overwrite=False,
makedirs=False,
):
"""
Similar to :meth:`~pathlib_mate.mate_mutate_methods.MutateMethods.change`
method. However, it copy the original path to new location.
:type self: Path
:type new_abspath: Union[str, Path]
:type new_dirpath: str
:type new_dirname: str
:type new_basename: str
:type new_fname: str
:type new_ext: str
:type overwrite: bool
:type makedirs: bool
:rtype: Path
**中文文档**
高级 文件 / 文件夹 拷贝函数, 允许用于根据路径的各个组成部分进行重命名, 然后拷贝.
"""
self.assert_exists()
p = self.change(
new_abspath=new_abspath,
new_dirpath=new_dirpath,
new_dirname=new_dirname,
new_basename=new_basename,
new_fname=new_fname,
new_ext=new_ext,
)
if p.is_not_exist_or_allow_overwrite(overwrite=overwrite):
# 如果两个路径不同, 才进行copy
if self.abspath != p.abspath:
try:
shutil.copy(self.abspath, p.abspath)
except IOError as e:
if makedirs:
os.makedirs(p.parent.abspath)
shutil.copy(self.abspath, p.abspath)
else:
raise e
return p
def remove(self):
"""
Remove this file. Won't work if it is a directory.
:type self: Path
"""
self.unlink()
def remove_if_exists(self):
"""
Remove a file or entire directory recursively.
:type self: Path
"""
if self.exists():
if self.is_dir():
shutil.rmtree(self.abspath)
else:
self.remove()
def mkdir_if_not_exists(self):
"""
Make a directory if not exists yet.
:type self: Path
"""
self.mkdir(parents=True, exist_ok=True)
@classmethod
def dir_here(cls, file_var):
"""
Return the directory of the python script that where this method
is called.
Suppose you have a file structure like this::
/Users/myname/test.py
And it is the content of ``test.py``::
from pathlib_mate import Path
dir_here = Path.dir_here(__file__)
print(dir_here) # /Users/myname
:type file_var: str
:param file_var: the __file__ variable
:rtype: Path
"""
return cls(file_var).absolute().parent
|
class MutateMethods(object):
'''
Provide methods to mutate the Path instance.
'''
def drop_parts(self, n=1):
'''
Drop number of parts from the ends. By default, it is equal to
``self.parent``.
Example::
>>> Path("/usr/bin/python").drop_parts(1)
"/user/bin"
>>> Path("/usr/bin/python").drop_parts(2)
"/user"
:type self: Path
:type n: int
:param n: integer, number of parts you wants to drop from ends.
n has to greater equal than 0.
:rtype: Path
:returns: a new Path object.
'''
pass
def append_parts(self, *parts):
'''
Append some parts to the end of this path.
Example::
>>> Path("/usr/bin/python").append_parts("lib")
"/user/bin/python/lib"
>>> Path("/usr/bin/python").append_parts("lib", "core.py")
"/user/bin/python/lib/core.py"
:type self: Path
:rtype: Path
:returns: a new Path object.
'''
pass
def change(
self,
new_abspath=None,
new_dirpath=None,
new_dirname=None,
new_basename=None,
new_fname=None,
new_ext=None,
):
'''
Return a new :class:`pathlib_mate.pathlib2.Path` object with updated path.
Example::
>>> Path("/Users/alice/test.py").change(new_fname="test1")
/Users/alice/test1.py
>>> Path("/Users/alice/test.py").change(new_ext=".txt")
/Users/alice/test.txt
>>> Path("/Users/alice/test.py").change(new_dirname="bob")
/Users/bob/test.py
>>> Path("/Users/alice/test.py").change(new_dirpath="/tmp")
/tmp/test.py
:type self: Path
:type new_abspath: Union[str, Path]
:type new_dirpath: str
:type new_dirname: str
:type new_basename: str
:type new_fname: str
:type new_ext: str
:rtype: Path
**中文文档**
高级重命名函数, 允许用于根据路径的各个组成部分进行重命名. 但和 os.rename
方法一样, 需要保证母文件夹存在.
'''
pass
def is_not_exist_or_allow_overwrite(self, overwrite=False):
'''
Test whether a file target is not exists or it exists but allow
overwrite.
:type self: Path
:param overwrite: bool
:rtype: bool
'''
pass
def moveto(
self,
new_abspath=None,
new_dirpath=None,
new_dirname=None,
new_basename=None,
new_fname=None,
new_ext=None,
overwrite=False,
makedirs=False,
):
'''
Similar to :meth:`~pathlib_mate.mate_mutate_methods.MutateMethods.change`
method. However, it move the original path to new location.
:type self: Path
:type new_abspath: Union[str, Path]
:type new_dirpath: str
:type new_dirname: str
:type new_basename: str
:type new_fname: str
:type new_ext: str
:type overwrite: bool
:type makedirs: bool
:rtype: Path
**中文文档**
高级 文件 / 文件夹 移动函数, 允许用于根据路径的各个组成部分进行重命名, 然后移动.
'''
pass
def copyto(
self,
new_abspath=None,
new_dirpath=None,
new_dirname=None,
new_basename=None,
new_fname=None,
new_ext=None,
overwrite=False,
makedirs=False,
):
'''
Similar to :meth:`~pathlib_mate.mate_mutate_methods.MutateMethods.change`
method. However, it copy the original path to new location.
:type self: Path
:type new_abspath: Union[str, Path]
:type new_dirpath: str
:type new_dirname: str
:type new_basename: str
:type new_fname: str
:type new_ext: str
:type overwrite: bool
:type makedirs: bool
:rtype: Path
**中文文档**
高级 文件 / 文件夹 拷贝函数, 允许用于根据路径的各个组成部分进行重命名, 然后拷贝.
'''
pass
def remove(self):
'''
Remove this file. Won't work if it is a directory.
:type self: Path
'''
pass
def remove_if_exists(self):
'''
Remove a file or entire directory recursively.
:type self: Path
'''
pass
def mkdir_if_not_exists(self):
'''
Make a directory if not exists yet.
:type self: Path
'''
pass
@classmethod
def dir_here(cls, file_var):
'''
Return the directory of the python script that where this method
is called.
Suppose you have a file structure like this::
/Users/myname/test.py
And it is the content of ``test.py``::
from pathlib_mate import Path
dir_here = Path.dir_here(__file__)
print(dir_here) # /Users/myname
:type file_var: str
:param file_var: the __file__ variable
:rtype: Path
'''
pass
| 12 | 11 | 28 | 5 | 11 | 12 | 3 | 1.05 | 1 | 1 | 0 | 1 | 9 | 0 | 10 | 10 | 292 | 59 | 114 | 45 | 74 | 120 | 62 | 15 | 51 | 10 | 1 | 4 | 30 |
148,170 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/pathlib2.py
|
pathlib_mate.pathlib2._PosixFlavour
|
class _PosixFlavour(_Flavour):
sep = '/'
altsep = ''
has_drv = False
pathmod = posixpath
is_supported = (os.name != 'nt')
def splitroot(self, part, sep=sep):
if part and part[0] == sep:
stripped_part = part.lstrip(sep)
# According to POSIX path resolution:
# http://pubs.opengroup.org/onlinepubs/009695399/basedefs/
# xbd_chap04.html#tag_04_11
# "A pathname that begins with two successive slashes may be
# interpreted in an implementation-defined manner, although more
# than two leading slashes shall be treated as a single slash".
if len(part) - len(stripped_part) == 2:
return '', sep * 2, stripped_part
else:
return '', sep, stripped_part
else:
return '', '', part
def casefold(self, s):
return s
def casefold_parts(self, parts):
return parts
def resolve(self, path, strict=False):
sep = self.sep
accessor = path._accessor
seen = {}
def _resolve(path, rest):
if rest.startswith(sep):
path = ''
for name in rest.split(sep):
if not name or name == '.':
# current dir
continue
if name == '..':
# parent dir
path, _, _ = path.rpartition(sep)
continue
newpath = path + sep + name
if newpath in seen:
# Already seen this path
path = seen[newpath]
if path is not None:
# use cached value
continue
# The symlink is not resolved, so we must have a symlink
# loop.
raise RuntimeError("Symlink loop from %r" % newpath)
# Resolve the symbolic link
try:
target = accessor.readlink(newpath)
except OSError as e:
if e.errno != EINVAL and strict:
raise
# Not a symlink, or non-strict mode. We just leave the path
# untouched.
path = newpath
else:
seen[newpath] = None # not resolved symlink
path = _resolve(path, target)
seen[newpath] = path # resolved symlink
return path
# NOTE: according to POSIX, getcwd() cannot contain path components
# which are symlinks.
base = '' if path.is_absolute() else os.getcwd()
return _resolve(base, str(path)) or sep
def is_reserved(self, parts):
return False
def make_uri(self, path):
# We represent the path using the local filesystem encoding,
# for portability to other applications.
bpath = bytes(path)
return 'file://' + urlquote_from_bytes(bpath)
def gethomedir(self, username):
if not username:
try:
return os.environ['HOME']
except KeyError:
import pwd
return pwd.getpwuid(os.getuid()).pw_dir
else:
import pwd
try:
return pwd.getpwnam(username).pw_dir
except KeyError:
raise RuntimeError("Can't determine home directory "
"for %r" % username)
|
class _PosixFlavour(_Flavour):
def splitroot(self, part, sep=sep):
pass
def casefold(self, s):
pass
def casefold_parts(self, parts):
pass
def resolve(self, path, strict=False):
pass
def _resolve(path, rest):
pass
def is_reserved(self, parts):
pass
def make_uri(self, path):
pass
def gethomedir(self, username):
pass
| 9 | 0 | 15 | 1 | 11 | 4 | 3 | 0.3 | 1 | 5 | 0 | 0 | 7 | 0 | 7 | 14 | 100 | 11 | 70 | 27 | 59 | 21 | 66 | 26 | 55 | 9 | 2 | 3 | 22 |
148,171 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/mate_path_filters.py
|
pathlib_mate.mate_path_filters.PathFilters
|
class PathFilters(object):
"""
Provide friendly path filter API.
"""
# --- assert something ---
def assert_is_file_and_exists(self):
"""
Assert it is a directory and exists in file system.
:type self: Path
"""
if not self.is_file():
msg = "'%s' is not a file or doesn't exists!" % self
raise EnvironmentError(msg)
def assert_is_dir_and_exists(self):
"""
Assert it is a directory and exists in file system.
:type self: Path
"""
if not self.is_dir():
msg = "'%s' is not a file or doesn't exists!" % self
raise EnvironmentError(msg)
def assert_exists(self):
"""
Assert it exists.
:type self: Path
"""
if not self.exists():
msg = "'%s' doesn't exists!" % self
raise EnvironmentError(msg)
# --- select ---
def select(self, filters=all_true, recursive=True):
"""Select path by criterion.
:type self: Path
:type filters: Callable
:param filters: a lambda function that take
a :class:`~pathlib_mate.pathlib2.Path` as input,
return boolean as a output.
:type recursive: bool
:param recursive: include files in sub-folder or not.
:rtype: Iterable[Path]
**中文文档**
根据filters中定义的条件选择路径.
"""
self.assert_is_dir_and_exists()
if recursive:
for p in self.glob("**/*"):
if filters(p):
yield p
else:
for p in self.iterdir():
if filters(p):
yield p
def select_file(self, filters=all_true, recursive=True):
"""Select file path by criterion.
:type self: Path
:type filters: Callable
:type recursive: bool
:rtype: Iterable[Path]
**中文文档**
根据 ``filters`` 中定义的条件选择文件.
"""
for p in self.select(filters, recursive):
if p.is_file():
yield p
def select_dir(self, filters=all_true, recursive=True):
"""Select dir path by criterion.
:type self: Path
:type filters: Callable
:type recursive: bool
:rtype: Iterable[Path]
**中文文档**
根据 ``filters`` 中定义的条件选择文件夹.
"""
for p in self.select(filters, recursive):
if p.is_dir():
yield p
@property
def n_file(self):
"""
Count how many files in this directory. Including file in sub folder.
:type self: Path
:rtype: int
"""
self.assert_is_dir_and_exists()
n = 0
for _ in self.select_file(recursive=True):
n += 1
return n
@property
def n_dir(self):
"""
Count how many folders in this directory. Including folder in sub folder.
:type self: Path
:rtype: int
"""
self.assert_is_dir_and_exists()
n = 0
for _ in self.select_dir(recursive=True):
n += 1
return n
@property
def n_subfile(self):
"""
Count how many files in this directory (doesn't include files in
sub folders).
:type self: Path
:rtype: int
"""
self.assert_is_dir_and_exists()
n = 0
for _ in self.select_file(recursive=False):
n += 1
return n
@property
def n_subdir(self):
"""
Count how many folders in this directory (doesn't include folder in
sub folders).
:type self: Path
:rtype: int
"""
self.assert_is_dir_and_exists()
n = 0
for _ in self.select_dir(recursive=False):
n += 1
return n
# --- Select by built-in criterion ---
def select_by_ext(self, ext, recursive=True):
"""
Select file path by extension.
:type self: Path
:type ext: str
:type recursive: bool
:rtype: Iterable[Path]
**中文文档**
选择与预定义的若干个扩展名匹配的文件.
"""
ext = [ext.strip().lower() for ext in ensure_list(ext)]
def filters(p):
return p.suffix.lower() in ext
return self.select_file(filters, recursive)
def select_by_pattern_in_fname(
self,
pattern,
recursive=True,
case_sensitive=False,
):
"""
Select file path by text pattern in file name.
:type self: Path
:type pattern: str
:type recursive: bool
:rtype: Iterable[Path]
**中文文档**
选择文件名中包含指定子字符串的文件.
"""
if case_sensitive:
def filters(p):
return pattern in p.fname
else:
pattern = pattern.lower()
def filters(p):
return pattern in p.fname.lower()
return self.select_file(filters, recursive)
def select_by_pattern_in_abspath(
self,
pattern,
recursive=True,
case_sensitive=False,
):
"""
Select file path by text pattern in absolute path.
:type self: Path
:type pattern: str
:type recursive: bool
:rtype: Iterable[Path]
**中文文档**
选择绝对路径中包含指定子字符串的文件.
"""
if case_sensitive:
def filters(p):
return pattern in p.abspath
else:
pattern = pattern.lower()
def filters(p):
return pattern in p.abspath.lower()
return self.select_file(filters, recursive)
def select_by_size(
self,
min_size=0,
max_size=1 << 40,
recursive=True,
):
"""
Select file path by size.
:type self: Path
:type min_size: int
:type max_size: int
:type recursive: bool
:rtype: Iterable[Path]
**中文文档**
选择所有文件大小在一定范围内的文件.
"""
def filters(p):
return min_size <= p.size <= max_size
return self.select_file(filters, recursive)
def select_by_mtime(
self,
min_time=0,
max_time=ts_2100,
recursive=True,
):
"""
Select file path by modify time.
:type self: Path
:type min_time: Union[int, float]
:param min_time: lower bound timestamp
:type max_time: Union[int, float]
:param max_time: upper bound timestamp
:type recursive: bool
:rtype: Iterable[Path]
**中文文档**
选择所有 :attr:`pathlib_mate.pathlib2.Path.mtime` 在一定范围内的文件.
"""
def filters(p):
return min_time <= p.mtime <= max_time
return self.select_file(filters, recursive)
def select_by_atime(self, min_time=0, max_time=ts_2100, recursive=True):
"""
Select file path by access time.
:type self: Path
:type min_time: Union[int, float]
:param min_time: lower bound timestamp
:type max_time: Union[int, float]
:param max_time: upper bound timestamp
:type recursive: bool
:rtype: Iterable[Path]
**中文文档**
选择所有 :attr:`pathlib_mate.pathlib2.Path.atime` 在一定范围内的文件.
"""
def filters(p):
return min_time <= p.atime <= max_time
return self.select_file(filters, recursive)
def select_by_ctime(
self,
min_time=0,
max_time=ts_2100,
recursive=True,
):
"""
Select file path by create time.
:type self: Path
:type min_time: Union[int, float]
:param min_time: lower bound timestamp
:type max_time: Union[int, float]
:param max_time: upper bound timestamp
:type recursive: bool
:rtype: Iterable[Path]
**中文文档**
选择所有 :attr:`pathlib_mate.pathlib2.Path.ctime` 在一定范围内的文件.
"""
def filters(p):
return min_time <= p.ctime <= max_time
return self.select_file(filters, recursive)
# --- Select Special File Type ---
_image_ext = [
".jpg",
".jpeg",
".png",
".gif",
".tiff",
".bmp",
".ppm",
".pgm",
".pbm",
".pnm",
".svg",
]
def select_image(self, recursive=True):
"""
Select image file.
:type self: Path
:type recursive: bool
:rtype: Iterable[Path]
"""
return self.select_by_ext(self._image_ext, recursive)
_audio_ext = [
".mp3",
".mp4",
".aac",
".m4a",
".wma",
".wav",
".ape",
".tak",
".tta",
".3gp",
".webm",
".ogg",
]
def select_audio(self, recursive=True): # pragma: no cover
"""
Select audio file.
:type self: Path
:type recursive: bool
:rtype: Iterable[Path]
"""
return self.select_by_ext(self._audio_ext, recursive)
_video_ext = [
".avi",
".wmv",
".mkv",
".mp4",
".flv",
".vob",
".mov",
".rm",
".rmvb",
"3gp",
".3g2",
".nsv",
".webm",
".mpg",
".mpeg",
".m4v",
".iso",
]
def select_video(self, recursive=True): # pragma: no cover
"""
Select video file.
:type self: Path
:type recursive: bool
:rtype: Iterable[Path]
"""
return self.select_by_ext(self._video_ext, recursive)
_ms_word_ext = [".doc", ".docx", ".docm", ".dotx", ".dotm", ".docb"]
def select_word(self, recursive=True): # pragma: no cover
"""
Select Microsoft Word file.
:type self: Path
:type recursive: bool
:rtype: Iterable[Path]
"""
return self.select_by_ext(self._ms_word_ext, recursive)
_ms_excel_ext = [".xls", ".xlsx", ".xlsm", ".xltx", ".xltm"]
def select_excel(self, recursive=True): # pragma: no cover
"""
Select Microsoft Excel file.
:type self: Path
:type recursive: bool
:rtype: Iterable[Path]
"""
return self.select_by_ext(self._ms_excel_ext, recursive)
_archive_ext = [".zip", ".rar", ".gz", ".tar.gz", ".tgz", ".7z"]
def select_archive(self, recursive=True): # pragma: no cover
"""
Select compressed archive file.
:type self: Path
:type recursive: bool
:rtype: Iterable[Path]
"""
return self.select_by_ext(self._archive_ext, recursive)
sort_by_abspath = _sort_by("abspath")
"""
Sort list of :class:`Path` by absolute path.
:params p_list: list of :class:`Path`
:params reverse: if False, return in descending order
"""
sort_by_fname = _sort_by("fname")
"""
Sort list of :class:`Path` by file name.
:params p_list: list of :class:`Path`
:params reverse: if False, return in descending order
"""
sort_by_ext = _sort_by("ext")
"""
Sort list of :class:`Path` by extension.
:params p_list: list of :class:`Path`
:params reverse: if False, return in descending order
"""
sort_by_size = _sort_by("size")
"""
Sort list of :class:`Path` by file size.
:params p_list: list of :class:`Path`
:params reverse: if False, return in descending order
"""
sort_by_mtime = _sort_by("mtime")
"""
Sort list of :class:`Path` by modify time.
:params p_list: list of :class:`Path`
:params reverse: if False, return in descending order
"""
sort_by_atime = _sort_by("atime")
"""
Sort list of :class:`Path` by access time.
:params p_list: list of :class:`Path`
:params reverse: if False, return in descending order
"""
sort_by_ctime = _sort_by("ctime")
"""
Sort list of :class:`Path` by create time.
:params p_list: list of :class:`Path`
:params reverse: if False, return in descending order
"""
sort_by_md5 = _sort_by("md5")
"""
Sort list of :class:`Path` by md5.
:params p_list: list of :class:`Path`
:params reverse: if False, return in descending order
"""
@property
def dirsize(self):
"""
Return total file size (include sub folder). Symlink doesn't count.
:type self: Path
:rtype: int
"""
total = 0
for p in self.select_file(recursive=True):
try:
total += p.size
except: # pragma: no cover
print("Unable to get file size of: %s" % p)
return total
|
class PathFilters(object):
'''
Provide friendly path filter API.
'''
def assert_is_file_and_exists(self):
'''
Assert it is a directory and exists in file system.
:type self: Path
'''
pass
def assert_is_dir_and_exists(self):
'''
Assert it is a directory and exists in file system.
:type self: Path
'''
pass
def assert_exists(self):
'''
Assert it exists.
:type self: Path
'''
pass
def select(self, filters=all_true, recursive=True):
'''Select path by criterion.
:type self: Path
:type filters: Callable
:param filters: a lambda function that take
a :class:`~pathlib_mate.pathlib2.Path` as input,
return boolean as a output.
:type recursive: bool
:param recursive: include files in sub-folder or not.
:rtype: Iterable[Path]
**中文文档**
根据filters中定义的条件选择路径.
'''
pass
def select_file(self, filters=all_true, recursive=True):
'''Select file path by criterion.
:type self: Path
:type filters: Callable
:type recursive: bool
:rtype: Iterable[Path]
**中文文档**
根据 ``filters`` 中定义的条件选择文件.
'''
pass
def select_dir(self, filters=all_true, recursive=True):
'''Select dir path by criterion.
:type self: Path
:type filters: Callable
:type recursive: bool
:rtype: Iterable[Path]
**中文文档**
根据 ``filters`` 中定义的条件选择文件夹.
'''
pass
@property
def n_file(self):
'''
Count how many files in this directory. Including file in sub folder.
:type self: Path
:rtype: int
'''
pass
@property
def n_dir(self):
'''
Count how many folders in this directory. Including folder in sub folder.
:type self: Path
:rtype: int
'''
pass
@property
def n_subfile(self):
'''
Count how many files in this directory (doesn't include files in
sub folders).
:type self: Path
:rtype: int
'''
pass
@property
def n_subdir(self):
'''
Count how many folders in this directory (doesn't include folder in
sub folders).
:type self: Path
:rtype: int
'''
pass
def select_by_ext(self, ext, recursive=True):
'''
Select file path by extension.
:type self: Path
:type ext: str
:type recursive: bool
:rtype: Iterable[Path]
**中文文档**
选择与预定义的若干个扩展名匹配的文件.
'''
pass
def filters(p):
pass
def select_by_pattern_in_fname(
self,
pattern,
recursive=True,
case_sensitive=False,
):
'''
Select file path by text pattern in file name.
:type self: Path
:type pattern: str
:type recursive: bool
:rtype: Iterable[Path]
**中文文档**
选择文件名中包含指定子字符串的文件.
'''
pass
def filters(p):
pass
def filters(p):
pass
def select_by_pattern_in_abspath(
self,
pattern,
recursive=True,
case_sensitive=False,
):
'''
Select file path by text pattern in absolute path.
:type self: Path
:type pattern: str
:type recursive: bool
:rtype: Iterable[Path]
**中文文档**
选择绝对路径中包含指定子字符串的文件.
'''
pass
def filters(p):
pass
def filters(p):
pass
def select_by_size(
self,
min_size=0,
max_size=1 << 40,
recursive=True,
):
'''
Select file path by size.
:type self: Path
:type min_size: int
:type max_size: int
:type recursive: bool
:rtype: Iterable[Path]
**中文文档**
选择所有文件大小在一定范围内的文件.
'''
pass
def filters(p):
pass
def select_by_mtime(
self,
min_time=0,
max_time=ts_2100,
recursive=True,
):
'''
Select file path by modify time.
:type self: Path
:type min_time: Union[int, float]
:param min_time: lower bound timestamp
:type max_time: Union[int, float]
:param max_time: upper bound timestamp
:type recursive: bool
:rtype: Iterable[Path]
**中文文档**
选择所有 :attr:`pathlib_mate.pathlib2.Path.mtime` 在一定范围内的文件.
'''
pass
def filters(p):
pass
def select_by_atime(self, min_time=0, max_time=ts_2100, recursive=True):
'''
Select file path by access time.
:type self: Path
:type min_time: Union[int, float]
:param min_time: lower bound timestamp
:type max_time: Union[int, float]
:param max_time: upper bound timestamp
:type recursive: bool
:rtype: Iterable[Path]
**中文文档**
选择所有 :attr:`pathlib_mate.pathlib2.Path.atime` 在一定范围内的文件.
'''
pass
def filters(p):
pass
def select_by_ctime(
self,
min_time=0,
max_time=ts_2100,
recursive=True,
):
'''
Select file path by create time.
:type self: Path
:type min_time: Union[int, float]
:param min_time: lower bound timestamp
:type max_time: Union[int, float]
:param max_time: upper bound timestamp
:type recursive: bool
:rtype: Iterable[Path]
**中文文档**
选择所有 :attr:`pathlib_mate.pathlib2.Path.ctime` 在一定范围内的文件.
'''
pass
def filters(p):
pass
def select_image(self, recursive=True):
'''
Select image file.
:type self: Path
:type recursive: bool
:rtype: Iterable[Path]
'''
pass
def select_audio(self, recursive=True):
'''
Select audio file.
:type self: Path
:type recursive: bool
:rtype: Iterable[Path]
'''
pass
def select_video(self, recursive=True):
'''
Select video file.
:type self: Path
:type recursive: bool
:rtype: Iterable[Path]
'''
pass
def select_word(self, recursive=True):
'''
Select Microsoft Word file.
:type self: Path
:type recursive: bool
:rtype: Iterable[Path]
'''
pass
def select_excel(self, recursive=True):
'''
Select Microsoft Excel file.
:type self: Path
:type recursive: bool
:rtype: Iterable[Path]
'''
pass
def select_archive(self, recursive=True):
'''
Select compressed archive file.
:type self: Path
:type recursive: bool
:rtype: Iterable[Path]
'''
pass
@property
def dirsize(self):
'''
Return total file size (include sub folder). Symlink doesn't count.
:type self: Path
:rtype: int
'''
pass
| 39 | 25 | 13 | 3 | 5 | 6 | 2 | 1.14 | 1 | 0 | 0 | 1 | 24 | 0 | 24 | 24 | 554 | 130 | 201 | 94 | 137 | 229 | 125 | 64 | 91 | 6 | 1 | 3 | 53 |
148,172 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/vendor/fileutils.py
|
pathlib_mate.vendor.fileutils.FilePerms
|
class FilePerms(object):
"""The :class:`FilePerms` type is used to represent standard POSIX
filesystem permissions:
* Read
* Write
* Execute
Across three classes of user:
* Owning (u)ser
* Owner's (g)roup
* Any (o)ther user
This class assists with computing new permissions, as well as
working with numeric octal ``777``-style and ``rwx``-style
permissions. Currently it only considers the bottom 9 permission
bits; it does not support sticky bits or more advanced permission
systems.
Args:
user (str): A string in the 'rwx' format, omitting characters
for which owning user's permissions are not provided.
group (str): A string in the 'rwx' format, omitting characters
for which owning group permissions are not provided.
other (str): A string in the 'rwx' format, omitting characters
for which owning other/world permissions are not provided.
There are many ways to use :class:`FilePerms`:
>>> FilePerms(user='rwx', group='xrw', other='wxr') # note character order
FilePerms(user='rwx', group='rwx', other='rwx')
>>> int(FilePerms('r', 'r', ''))
288
>>> oct(288)[-3:] # XXX Py3k
'440'
See also the :meth:`FilePerms.from_int` and
:meth:`FilePerms.from_path` classmethods for useful alternative
ways to construct :class:`FilePerms` objects.
"""
# TODO: consider more than the lower 9 bits
class _FilePermProperty(object):
_perm_chars = 'rwx'
_perm_set = frozenset('rwx')
_perm_val = {'r': 4, 'w': 2, 'x': 1} # for sorting
def __init__(self, attribute, offset):
self.attribute = attribute
self.offset = offset
def __get__(self, fp_obj, type_=None):
if fp_obj is None:
return self
return getattr(fp_obj, self.attribute)
def __set__(self, fp_obj, value):
cur = getattr(fp_obj, self.attribute)
if cur == value:
return
try:
invalid_chars = set(str(value)) - self._perm_set
except TypeError:
raise TypeError('expected string, not %r' % value)
if invalid_chars:
raise ValueError('got invalid chars %r in permission'
' specification %r, expected empty string'
' or one or more of %r'
% (invalid_chars, value, self._perm_chars))
sort_key = lambda c: self._perm_val[c]
new_value = ''.join(sorted(set(value),
key=sort_key, reverse=True))
setattr(fp_obj, self.attribute, new_value)
self._update_integer(fp_obj, new_value)
def _update_integer(self, fp_obj, value):
mode = 0
key = 'xwr'
for symbol in value:
bit = 2 ** key.index(symbol)
mode |= (bit << (self.offset * 3))
fp_obj._integer |= mode
def __init__(self, user='', group='', other=''):
self._user, self._group, self._other = '', '', ''
self._integer = 0
self.user = user
self.group = group
self.other = other
@classmethod
def from_int(cls, i):
"""Create a :class:`FilePerms` object from an integer.
>>> FilePerms.from_int(0o644) # note the leading zero-oh for octal
FilePerms(user='rw', group='r', other='r')
"""
i &= FULL_PERMS
key = ('', 'x', 'w', 'xw', 'r', 'rx', 'rw', 'rwx')
parts = []
while i:
parts.append(key[i & _SINGLE_FULL_PERM])
i >>= 3
parts.reverse()
return cls(*parts)
@classmethod
def from_path(cls, path):
"""Make a new :class:`FilePerms` object based on the permissions
assigned to the file or directory at *path*.
Args:
path (str): Filesystem path of the target file.
Here's an example that holds true on most systems:
>>> import tempfile
>>> 'r' in FilePerms.from_path(tempfile.gettempdir()).user
True
"""
stat_res = os.stat(path)
return cls.from_int(stat.S_IMODE(stat_res.st_mode))
def __int__(self):
return self._integer
# Sphinx tip: attribute docstrings come after the attribute
user = _FilePermProperty('_user', 2)
"Stores the ``rwx``-formatted *user* permission."
group = _FilePermProperty('_group', 1)
"Stores the ``rwx``-formatted *group* permission."
other = _FilePermProperty('_other', 0)
"Stores the ``rwx``-formatted *other* permission."
def __repr__(self):
cn = self.__class__.__name__
return ('%s(user=%r, group=%r, other=%r)'
% (cn, self.user, self.group, self.other))
|
class FilePerms(object):
'''The :class:`FilePerms` type is used to represent standard POSIX
filesystem permissions:
* Read
* Write
* Execute
Across three classes of user:
* Owning (u)ser
* Owner's (g)roup
* Any (o)ther user
This class assists with computing new permissions, as well as
working with numeric octal ``777``-style and ``rwx``-style
permissions. Currently it only considers the bottom 9 permission
bits; it does not support sticky bits or more advanced permission
systems.
Args:
user (str): A string in the 'rwx' format, omitting characters
for which owning user's permissions are not provided.
group (str): A string in the 'rwx' format, omitting characters
for which owning group permissions are not provided.
other (str): A string in the 'rwx' format, omitting characters
for which owning other/world permissions are not provided.
There are many ways to use :class:`FilePerms`:
>>> FilePerms(user='rwx', group='xrw', other='wxr') # note character order
FilePerms(user='rwx', group='rwx', other='rwx')
>>> int(FilePerms('r', 'r', ''))
288
>>> oct(288)[-3:] # XXX Py3k
'440'
See also the :meth:`FilePerms.from_int` and
:meth:`FilePerms.from_path` classmethods for useful alternative
ways to construct :class:`FilePerms` objects.
'''
class _FilePermProperty(object):
def __init__(self, attribute, offset):
pass
def __get__(self, fp_obj, type_=None):
pass
def __set__(self, fp_obj, value):
pass
def _update_integer(self, fp_obj, value):
pass
def __init__(self, attribute, offset):
pass
@classmethod
def from_int(cls, i):
'''Create a :class:`FilePerms` object from an integer.
>>> FilePerms.from_int(0o644) # note the leading zero-oh for octal
FilePerms(user='rw', group='r', other='r')
'''
pass
@classmethod
def from_path(cls, path):
'''Make a new :class:`FilePerms` object based on the permissions
assigned to the file or directory at *path*.
Args:
path (str): Filesystem path of the target file.
Here's an example that holds true on most systems:
>>> import tempfile
>>> 'r' in FilePerms.from_path(tempfile.gettempdir()).user
True
'''
pass
def __int__(self):
pass
def __repr__(self):
pass
| 13 | 3 | 8 | 1 | 6 | 1 | 2 | 0.77 | 1 | 0 | 0 | 0 | 3 | 4 | 5 | 5 | 139 | 23 | 66 | 35 | 53 | 51 | 59 | 33 | 48 | 4 | 1 | 1 | 15 |
148,173 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/mate_hashes_methods.py
|
pathlib_mate.mate_hashes_methods.HashesMethods
|
class HashesMethods(object):
"""
Provide hash functions.
"""
# --- file check sum ---
def get_partial_md5(self, nbytes):
"""
Return md5 check sum of first n bytes of this file.
:type self: Path
:type nbytes: int
:rtype: str
"""
return md5file(abspath=self.abspath, nbytes=nbytes)
@property
def md5(self):
"""
Return md5 check sum of this file.
:type self: Path
:rtype: str
"""
return md5file(self.abspath)
def get_partial_sha256(self, nbytes):
"""
Return sha256 check sum of first n bytes of this file.
:type self: Path
:type nbytes: int
:rtype: str
"""
return sha256file(abspath=self.abspath, nbytes=nbytes)
@property
def sha256(self):
"""
Return sha256 check sum of this file.
:type self: Path
:rtype: str
"""
return sha256file(self.abspath)
def get_partial_sha512(self, nbytes):
"""
Return sha512 check sum of first n bytes of this file.
:type self: Path
:type nbytes: int
:rtype: str
"""
return sha512file(abspath=self.abspath, nbytes=nbytes)
@property
def sha512(self):
"""
Return md5 check sum of this file.
:type self: Path
:rtype: str
"""
return sha512file(self.abspath)
|
class HashesMethods(object):
'''
Provide hash functions.
'''
def get_partial_md5(self, nbytes):
'''
Return md5 check sum of first n bytes of this file.
:type self: Path
:type nbytes: int
:rtype: str
'''
pass
@property
def md5(self):
'''
Return md5 check sum of this file.
:type self: Path
:rtype: str
'''
pass
def get_partial_sha256(self, nbytes):
'''
Return sha256 check sum of first n bytes of this file.
:type self: Path
:type nbytes: int
:rtype: str
'''
pass
@property
def sha256(self):
'''
Return sha256 check sum of this file.
:type self: Path
:rtype: str
'''
pass
def get_partial_sha512(self, nbytes):
'''
Return sha512 check sum of first n bytes of this file.
:type self: Path
:type nbytes: int
:rtype: str
'''
pass
@property
def sha512(self):
'''
Return md5 check sum of this file.
:type self: Path
:rtype: str
'''
pass
| 10 | 7 | 10 | 2 | 2 | 6 | 1 | 2.31 | 1 | 0 | 0 | 1 | 6 | 1 | 6 | 6 | 72 | 19 | 16 | 11 | 6 | 37 | 13 | 7 | 6 | 1 | 1 | 0 | 6 |
148,174 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/pathlib2.py
|
pathlib_mate.pathlib2._PreciseSelector
|
class _PreciseSelector(_Selector):
def __init__(self, name, child_parts):
self.name = name
_Selector.__init__(self, child_parts)
def _select_from(self, parent_path, is_dir, exists, scandir):
def try_iter():
path = parent_path._make_child_relpath(self.name)
if (is_dir if self.dironly else exists)(path):
for p in self.successor._select_from(
path, is_dir, exists, scandir):
yield p
def except_iter(exc):
return iter([])
for x in _try_except_permissionerror_iter(try_iter, except_iter):
yield x
|
class _PreciseSelector(_Selector):
def __init__(self, name, child_parts):
pass
def _select_from(self, parent_path, is_dir, exists, scandir):
pass
def try_iter():
pass
def except_iter(exc):
pass
| 5 | 0 | 6 | 1 | 6 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 4 | 19 | 4 | 15 | 9 | 10 | 0 | 14 | 9 | 9 | 4 | 1 | 2 | 8 |
148,175 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/tests/app/main.py
|
main.User
|
class User(object):
def __init__(self, id, name):
self.id = id
self.name = name
|
class User(object):
def __init__(self, id, name):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 2 | 1 | 1 | 4 | 0 | 4 | 4 | 2 | 0 | 4 | 4 | 2 | 1 | 1 | 0 | 1 |
148,176 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/pathlib2.py
|
pathlib_mate.pathlib2._RecursiveWildcardSelector
|
class _RecursiveWildcardSelector(_Selector):
def __init__(self, pat, child_parts):
_Selector.__init__(self, child_parts)
def _iterate_directories(self, parent_path, is_dir, scandir):
yield parent_path
def try_iter():
entries = list(scandir(parent_path))
for entry in entries:
entry_is_dir = False
try:
entry_is_dir = entry.is_dir()
except OSError as e:
if not _ignore_error(e):
raise
if entry_is_dir and not entry.is_symlink():
path = parent_path._make_child_relpath(entry.name)
for p in self._iterate_directories(path, is_dir, scandir):
yield p
def except_iter(exc):
return iter([])
for x in _try_except_permissionerror_iter(try_iter, except_iter):
yield x
def _select_from(self, parent_path, is_dir, exists, scandir):
def try_iter():
yielded = set()
try:
successor_select = self.successor._select_from
for starting_point in self._iterate_directories(
parent_path, is_dir, scandir):
for p in successor_select(
starting_point, is_dir, exists, scandir):
if p not in yielded:
yield p
yielded.add(p)
finally:
yielded.clear()
def except_iter(exc):
return iter([])
for x in _try_except_permissionerror_iter(try_iter, except_iter):
yield x
|
class _RecursiveWildcardSelector(_Selector):
def __init__(self, pat, child_parts):
pass
def _iterate_directories(self, parent_path, is_dir, scandir):
pass
def try_iter():
pass
def except_iter(exc):
pass
def _select_from(self, parent_path, is_dir, exists, scandir):
pass
def try_iter():
pass
def except_iter(exc):
pass
| 8 | 0 | 11 | 1 | 10 | 0 | 2 | 0 | 1 | 3 | 0 | 0 | 3 | 0 | 3 | 5 | 48 | 8 | 40 | 20 | 32 | 0 | 37 | 19 | 29 | 6 | 1 | 4 | 17 |
148,177 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/pathlib2.py
|
pathlib_mate.pathlib2._Selector
|
class _Selector:
"""A selector matches a specific glob pattern part against the children
of a given path."""
def __init__(self, child_parts):
self.child_parts = child_parts
if child_parts:
self.successor = _make_selector(child_parts)
self.dironly = True
else:
self.successor = _TerminatingSelector()
self.dironly = False
def select_from(self, parent_path):
"""Iterate over all child paths of `parent_path` matched by this
selector. This can contain parent_path itself."""
path_cls = type(parent_path)
is_dir = path_cls.is_dir
exists = path_cls.exists
scandir = parent_path._accessor.scandir
if not is_dir(parent_path):
return iter([])
return self._select_from(parent_path, is_dir, exists, scandir)
|
class _Selector:
'''A selector matches a specific glob pattern part against the children
of a given path.'''
def __init__(self, child_parts):
pass
def select_from(self, parent_path):
'''Iterate over all child paths of `parent_path` matched by this
selector. This can contain parent_path itself.'''
pass
| 3 | 2 | 9 | 0 | 8 | 1 | 2 | 0.24 | 0 | 2 | 1 | 3 | 2 | 3 | 2 | 2 | 24 | 3 | 17 | 10 | 14 | 4 | 16 | 10 | 13 | 2 | 0 | 1 | 4 |
148,178 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/pathlib2.py
|
pathlib_mate.pathlib2._TerminatingSelector
|
class _TerminatingSelector:
def _select_from(self, parent_path, is_dir, exists, scandir):
yield parent_path
|
class _TerminatingSelector:
def _select_from(self, parent_path, is_dir, exists, scandir):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 4 | 1 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 0 | 0 | 1 |
148,179 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/pathlib2.py
|
pathlib_mate.pathlib2._WildcardSelector
|
class _WildcardSelector(_Selector):
def __init__(self, pat, child_parts):
self.pat = re.compile(fnmatch.translate(pat))
_Selector.__init__(self, child_parts)
def _select_from(self, parent_path, is_dir, exists, scandir):
def try_iter():
cf = parent_path._flavour.casefold
entries = list(scandir(parent_path))
for entry in entries:
if not self.dironly or entry.is_dir():
name = entry.name
casefolded = cf(name)
if self.pat.match(casefolded):
path = parent_path._make_child_relpath(name)
for p in self.successor._select_from(
path, is_dir, exists, scandir):
yield p
def except_iter(exc):
return iter([])
for x in _try_except_permissionerror_iter(try_iter, except_iter):
yield x
|
class _WildcardSelector(_Selector):
def __init__(self, pat, child_parts):
pass
def _select_from(self, parent_path, is_dir, exists, scandir):
pass
def try_iter():
pass
def except_iter(exc):
pass
| 5 | 0 | 9 | 1 | 9 | 0 | 2 | 0 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 4 | 25 | 4 | 21 | 14 | 16 | 0 | 20 | 14 | 15 | 5 | 1 | 4 | 9 |
148,180 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/pathlib2.py
|
pathlib_mate.pathlib2._WindowsFlavour
|
class _WindowsFlavour(_Flavour):
# Reference for Windows paths can be found at
# http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
sep = '\\'
altsep = '/'
has_drv = True
pathmod = ntpath
is_supported = (os.name == 'nt')
drive_letters = set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
ext_namespace_prefix = '\\\\?\\'
reserved_names = (
set(['CON', 'PRN', 'AUX', 'NUL']) |
set(['COM%d' % i for i in range(1, 10)]) |
set(['LPT%d' % i for i in range(1, 10)])
)
# Interesting findings about extended paths:
# - '\\?\c:\a', '//?/c:\a' and '//?/c:/a' are all supported
# but '\\?\c:/a' is not
# - extended paths are always absolute; "relative" extended paths will
# fail.
def splitroot(self, part, sep=sep):
first = part[0:1]
second = part[1:2]
if second == sep and first == sep:
# XXX extended paths should also disable the collapsing of "."
# components (according to MSDN docs).
prefix, part = self._split_extended_path(part)
first = part[0:1]
second = part[1:2]
else:
prefix = ''
third = part[2:3]
if second == sep and first == sep and third != sep:
# is a UNC path:
# vvvvvvvvvvvvvvvvvvvvv root
# \\machine\mountpoint\directory\etc\...
# directory ^^^^^^^^^^^^^^
index = part.find(sep, 2)
if index != -1:
index2 = part.find(sep, index + 1)
# a UNC path can't have two slashes in a row
# (after the initial two)
if index2 != index + 1:
if index2 == -1:
index2 = len(part)
if prefix:
return prefix + part[1:index2], sep, part[index2 + 1:]
else:
return part[:index2], sep, part[index2 + 1:]
drv = root = ''
if second == ':' and first in self.drive_letters:
drv = part[:2]
part = part[2:]
first = third
if first == sep:
root = first
part = part.lstrip(sep)
return prefix + drv, root, part
def casefold(self, s):
return s.lower()
def casefold_parts(self, parts):
return [p.lower() for p in parts]
def resolve(self, path, strict=False):
s = str(path)
if not s:
return os.getcwd()
if _getfinalpathname is not None:
if strict:
return self._ext_to_normal(_getfinalpathname(s))
else:
# End of the path after the first one not found
tail_parts = [] # type: List[str]
def _try_func():
result[0] = self._ext_to_normal(_getfinalpathname(s))
# if there was no exception, set flag to 0
result[1] = 0
def _exc_func(exc):
pass
while True:
result = ['', 1]
_try_except_filenotfounderror(_try_func, _exc_func)
if result[1] == 1: # file not found exception raised
previous_s = s
s, tail = os.path.split(s) # type: str
tail_parts.append(tail)
if previous_s == s:
return path
else:
s = result[0]
return os.path.join(s, *reversed(tail_parts))
# Means fallback on absolute
return None
def _split_extended_path(self, s, ext_prefix=ext_namespace_prefix):
# type: (str, str) -> Tuple[str, str]
prefix = ''
if s.startswith(ext_prefix):
prefix = s[:4]
s = s[4:]
if s.startswith('UNC\\'):
prefix += s[:3]
s = '\\' + s[3:]
return prefix, s
def _ext_to_normal(self, s):
# type: (str) -> str
# Turn back an extended path into a normal DOS-like path
return self._split_extended_path(s)[1]
def is_reserved(self, parts):
# NOTE: the rules for reserved names seem somewhat complicated
# (e.g. r"..\NUL" is reserved but not r"foo\NUL").
# We err on the side of caution and return True for paths which are
# not considered reserved by Windows.
if not parts:
return False
if parts[0].startswith('\\\\'):
# UNC paths are never reserved
return False
return parts[-1].partition('.')[0].upper() in self.reserved_names
def make_uri(self, path):
# Under Windows, file URIs use the UTF-8 encoding.
drive = path.drive
if len(drive) == 2 and drive[1] == ':':
# It's a path on a local drive => 'file:///c:/a/b'
rest = path.as_posix()[2:].lstrip('/')
return 'file:///%s/%s' % (
drive, urlquote_from_bytes(rest.encode('utf-8')))
else:
# It's a path on a network drive => 'file://host/share/a/b'
return 'file:' + urlquote_from_bytes(
path.as_posix().encode('utf-8'))
def gethomedir(self, username):
if 'HOME' in os.environ:
userhome = os.environ['HOME']
elif 'USERPROFILE' in os.environ:
userhome = os.environ['USERPROFILE']
elif 'HOMEPATH' in os.environ:
try:
drv = os.environ['HOMEDRIVE']
except KeyError:
drv = ''
userhome = drv + os.environ['HOMEPATH']
else:
raise RuntimeError("Can't determine home directory")
if username:
# Try to guess user home directory. By default all users
# directories are located in the same place and are named by
# corresponding usernames. If current user home directory points
# to nonstandard place, this guess is likely wrong.
if os.environ['USERNAME'] != username:
drv, root, parts = self.parse_parts((userhome,))
if parts[-1] != os.environ['USERNAME']:
raise RuntimeError("Can't determine home directory "
"for %r" % username)
parts[-1] = username
if drv or root:
userhome = drv + root + self.join(parts[1:])
else:
userhome = self.join(parts)
return userhome
|
class _WindowsFlavour(_Flavour):
def splitroot(self, part, sep=sep):
pass
def casefold(self, s):
pass
def casefold_parts(self, parts):
pass
def resolve(self, path, strict=False):
pass
def _try_func():
pass
def _exc_func(exc):
pass
def _split_extended_path(self, s, ext_prefix=ext_namespace_prefix):
pass
def _ext_to_normal(self, s):
pass
def is_reserved(self, parts):
pass
def make_uri(self, path):
pass
def gethomedir(self, username):
pass
| 12 | 0 | 13 | 0 | 11 | 3 | 3 | 0.29 | 1 | 4 | 0 | 0 | 9 | 0 | 9 | 16 | 176 | 18 | 125 | 38 | 113 | 36 | 109 | 38 | 97 | 9 | 2 | 5 | 38 |
148,181 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/vendor/fileutils.py
|
pathlib_mate.vendor.fileutils.AtomicSaver
|
class AtomicSaver(object):
"""``AtomicSaver`` is a configurable `context manager`_ that provides
a writable :class:`file` which will be moved into place as long as
no exceptions are raised within the context manager's block. These
"part files" are created in the same directory as the destination
path to ensure atomic move operations (i.e., no cross-filesystem
moves occur).
Args:
dest_path (str): The path where the completed file will be
written.
overwrite (bool): Whether to overwrite the destination file if
it exists at completion time. Defaults to ``True``.
file_perms (int): Integer representation of file permissions
for the newly-created file. Defaults are, when the
destination path already exists, to copy the permissions
from the previous file, or if the file did not exist, to
respect the user's configured `umask`_, usually resulting
in octal 0644 or 0664.
text_mode (bool): Whether to open the destination file in text
mode (i.e., ``'w'`` not ``'wb'``). Defaults to ``False`` (``wb``).
part_file (str): Name of the temporary *part_file*. Defaults
to *dest_path* + ``.part``. Note that this argument is
just the filename, and not the full path of the part
file. To guarantee atomic saves, part files are always
created in the same directory as the destination path.
overwrite_part (bool): Whether to overwrite the *part_file*,
should it exist at setup time. Defaults to ``False``,
which results in an :exc:`OSError` being raised on
pre-existing part files. Be careful of setting this to
``True`` in situations when multiple threads or processes
could be writing to the same part file.
rm_part_on_exc (bool): Remove *part_file* on exception cases.
Defaults to ``True``, but ``False`` can be useful for
recovery in some cases. Note that resumption is not
automatic and by default an :exc:`OSError` is raised if
the *part_file* exists.
Practically, the AtomicSaver serves a few purposes:
* Avoiding overwriting an existing, valid file with a partially
written one.
* Providing a reasonable guarantee that a part file only has one
writer at a time.
* Optional recovery of partial data in failure cases.
.. _context manager: https://docs.python.org/2/reference/compound_stmts.html#with
.. _umask: https://en.wikipedia.org/wiki/Umask
"""
_default_file_perms = RW_PERMS
# TODO: option to abort if target file modify date has changed since start?
def __init__(self, dest_path, **kwargs):
self.dest_path = dest_path
self.overwrite = kwargs.pop('overwrite', True)
self.file_perms = kwargs.pop('file_perms', None)
self.overwrite_part = kwargs.pop('overwrite_part', False)
self.part_filename = kwargs.pop('part_file', None)
self.rm_part_on_exc = kwargs.pop('rm_part_on_exc', True)
self.text_mode = kwargs.pop('text_mode', False)
self.buffering = kwargs.pop('buffering', -1)
if kwargs:
raise TypeError('unexpected kwargs: %r' % (kwargs.keys(),))
self.dest_path = os.path.abspath(self.dest_path)
self.dest_dir = os.path.dirname(self.dest_path)
if not self.part_filename:
self.part_path = dest_path + '.part'
else:
self.part_path = os.path.join(self.dest_dir, self.part_filename)
self.mode = 'w+' if self.text_mode else 'w+b'
self.open_flags = _TEXT_OPENFLAGS if self.text_mode else _BIN_OPENFLAGS
self.part_file = None
def _open_part_file(self):
do_chmod = True
file_perms = self.file_perms
if file_perms is None:
try:
# try to copy from file being replaced
stat_res = os.stat(self.dest_path)
file_perms = stat.S_IMODE(stat_res.st_mode)
except (OSError, IOError):
# default if no destination file exists
file_perms = self._default_file_perms
do_chmod = False # respect the umask
fd = os.open(self.part_path, self.open_flags, file_perms)
set_cloexec(fd)
self.part_file = os.fdopen(fd, self.mode, self.buffering)
# if default perms are overridden by the user or previous dest_path
# chmod away the effects of the umask
if do_chmod:
try:
os.chmod(self.part_path, file_perms)
except (OSError, IOError):
self.part_file.close()
raise
return
def setup(self):
"""Called on context manager entry (the :keyword:`with` statement),
the ``setup()`` method creates the temporary file in the same
directory as the destination file.
``setup()`` tests for a writable directory with rename permissions
early, as the part file may not be written to immediately (not
using :func:`os.access` because of the potential issues of
effective vs. real privileges).
If the caller is not using the :class:`AtomicSaver` as a
context manager, this method should be called explicitly
before writing.
"""
if os.path.lexists(self.dest_path):
if not self.overwrite:
raise OSError(errno.EEXIST,
'Overwrite disabled and file already exists',
self.dest_path)
if self.overwrite_part and os.path.lexists(self.part_path):
os.unlink(self.part_path)
self._open_part_file()
return
def __enter__(self):
self.setup()
return self.part_file
def __exit__(self, exc_type, exc_val, exc_tb):
self.part_file.close()
if exc_type:
if self.rm_part_on_exc:
try:
os.unlink(self.part_path)
except Exception:
pass # avoid masking original error
return
try:
atomic_rename(self.part_path, self.dest_path,
overwrite=self.overwrite)
except OSError:
if self.rm_part_on_exc:
try:
os.unlink(self.part_path)
except Exception:
pass # avoid masking original error
raise # could not save destination file
return
|
class AtomicSaver(object):
'''``AtomicSaver`` is a configurable `context manager`_ that provides
a writable :class:`file` which will be moved into place as long as
no exceptions are raised within the context manager's block. These
"part files" are created in the same directory as the destination
path to ensure atomic move operations (i.e., no cross-filesystem
moves occur).
Args:
dest_path (str): The path where the completed file will be
written.
overwrite (bool): Whether to overwrite the destination file if
it exists at completion time. Defaults to ``True``.
file_perms (int): Integer representation of file permissions
for the newly-created file. Defaults are, when the
destination path already exists, to copy the permissions
from the previous file, or if the file did not exist, to
respect the user's configured `umask`_, usually resulting
in octal 0644 or 0664.
text_mode (bool): Whether to open the destination file in text
mode (i.e., ``'w'`` not ``'wb'``). Defaults to ``False`` (``wb``).
part_file (str): Name of the temporary *part_file*. Defaults
to *dest_path* + ``.part``. Note that this argument is
just the filename, and not the full path of the part
file. To guarantee atomic saves, part files are always
created in the same directory as the destination path.
overwrite_part (bool): Whether to overwrite the *part_file*,
should it exist at setup time. Defaults to ``False``,
which results in an :exc:`OSError` being raised on
pre-existing part files. Be careful of setting this to
``True`` in situations when multiple threads or processes
could be writing to the same part file.
rm_part_on_exc (bool): Remove *part_file* on exception cases.
Defaults to ``True``, but ``False`` can be useful for
recovery in some cases. Note that resumption is not
automatic and by default an :exc:`OSError` is raised if
the *part_file* exists.
Practically, the AtomicSaver serves a few purposes:
* Avoiding overwriting an existing, valid file with a partially
written one.
* Providing a reasonable guarantee that a part file only has one
writer at a time.
* Optional recovery of partial data in failure cases.
.. _context manager: https://docs.python.org/2/reference/compound_stmts.html#with
.. _umask: https://en.wikipedia.org/wiki/Umask
'''
def __init__(self, dest_path, **kwargs):
pass
def _open_part_file(self):
pass
def setup(self):
'''Called on context manager entry (the :keyword:`with` statement),
the ``setup()`` method creates the temporary file in the same
directory as the destination file.
``setup()`` tests for a writable directory with rename permissions
early, as the part file may not be written to immediately (not
using :func:`os.access` because of the potential issues of
effective vs. real privileges).
If the caller is not using the :class:`AtomicSaver` as a
context manager, this method should be called explicitly
before writing.
'''
pass
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
| 6 | 2 | 19 | 1 | 15 | 4 | 4 | 0.85 | 1 | 3 | 0 | 0 | 5 | 13 | 5 | 5 | 151 | 16 | 75 | 24 | 69 | 64 | 71 | 24 | 65 | 7 | 1 | 3 | 22 |
148,182 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/pathlib2.py
|
pathlib_mate.pathlib2._PathParents
|
class _PathParents(Sequence):
"""This object provides sequence-like access to the logical ancestors
of a path. Don't try to construct it yourself."""
__slots__ = ('_pathcls', '_drv', '_root', '_parts')
def __init__(self, path):
# We don't store the instance to avoid reference cycles
self._pathcls = type(path)
self._drv = path._drv
self._root = path._root
self._parts = path._parts
def __len__(self):
if self._drv or self._root:
return len(self._parts) - 1
else:
return len(self._parts)
def __getitem__(self, idx):
"""
:rtype: Path
"""
if idx < 0 or idx >= len(self):
raise IndexError(idx)
return self._pathcls._from_parsed_parts(self._drv, self._root,
self._parts[:-idx - 1])
def __repr__(self):
return "<{0}.parents>".format(self._pathcls.__name__)
|
class _PathParents(Sequence):
'''This object provides sequence-like access to the logical ancestors
of a path. Don't try to construct it yourself.'''
def __init__(self, path):
pass
def __len__(self):
pass
def __getitem__(self, idx):
'''
:rtype: Path
'''
pass
def __repr__(self):
pass
| 5 | 2 | 5 | 0 | 4 | 1 | 2 | 0.32 | 1 | 1 | 0 | 0 | 4 | 4 | 4 | 39 | 30 | 5 | 19 | 10 | 14 | 6 | 17 | 10 | 12 | 2 | 6 | 1 | 6 |
148,183 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/mate_attr_accessor.py
|
pathlib_mate.mate_attr_accessor.AttrAccessor
|
class AttrAccessor(object):
"""
Provides additional attribute accessor.
"""
# --- property methods that returns a value ---
@property
def abspath(self):
r"""
Return absolute path as a string.
:type self: Path
:rtype: str
Example: ``C:\User\admin\readme.txt`` for ``C:\User\admin\readme.txt``
"""
return self.absolute().__str__()
@property
def abspath_hexstr(self):
"""
Return absolute path encoded in hex string.
:type self: Path
:rtype: str
"""
return encode_hexstr(self.abspath)
@property
def dirpath(self):
r"""
Parent dir full absolute path.
:type self: Path
:rtype: str
Example: ``C:\User\admin`` for ``C:\User\admin\readme.txt``
"""
return self.parent.abspath
@property
def dirpath_hexstr(self):
"""
Return dir full absolute path encoded in hex string.
:type self: Path
:rtype: str
"""
return encode_hexstr(self.dirpath)
@property
def dirname(self):
r"""
Parent dir name.
:type self: Path
:rtype: str
Example: ``admin`` for ``C:\User\admin\readme.txt``
"""
return self.parent.name
@property
def dirname_hexstr(self):
"""
Parent dir name in hex string.
:type self: Path
:rtype: str
"""
return encode_hexstr(self.dirname)
@property
def basename(self):
r"""
File name with extension, path is not included.
:type self: Path
:rtype: str
Example: ``readme.txt`` for ``C:\User\admin\readme.txt``
"""
return self.name
@property
def basename_hexstr(self):
"""
File name with extension encoded in hex string.
:type self: Path
:rtype: str
"""
return encode_hexstr(self.basename)
@property
def fname(self):
r"""
File name without extension.
:type self: Path
:rtype: str
Example: ``readme`` for ``C:\User\admin\readme.txt``
"""
return self.stem
@property
def fname_hexstr(self):
"""
File name encoded in hex string.
:type self: Path
:rtype: str
"""
return encode_hexstr(self.fname)
@property
def ext(self):
r"""
File extension. If it's a dir, then return empty str.
:type self: Path
:rtype: str
Example: ``.txt`` for ``C:\User\admin\readme.txt``
"""
return self.suffix
@property
def size(self):
"""
File size in bytes.
:type self: Path
:rtype: int
"""
try:
return self._stat.st_size
except: # pragma: no cover
self._stat = self.stat()
return self.size
@property
def size_in_text(self):
"""
File size as human readable string.
:type self: Path
:rtype: str
"""
return repr_data_size(self.size, precision=2)
@property
def mtime(self):
"""
Get most recent modify time in timestamp.
:type self: Path
:rtype: float
"""
try:
return self._stat.st_mtime
except: # pragma: no cover
self._stat = self.stat()
return self.mtime
@property
def atime(self):
"""
Get most recent access time in timestamp.
:type self: Path
:rtype: float
"""
try:
return self._stat.st_atime
except: # pragma: no cover
self._stat = self.stat()
return self.atime
@property
def ctime(self):
"""
Get most recent create time in timestamp.
:type self: Path
:rtype: float
"""
try:
return self._stat.st_ctime
except: # pragma: no cover
self._stat = self.stat()
return self.ctime
@property
def modify_datetime(self):
"""
Get most recent modify time in datetime.
:type self: Path
:rtype: datetime
"""
return datetime.fromtimestamp(self.mtime)
@property
def access_datetime(self):
"""
Get most recent access time in datetime.
:type self: Path
:rtype: datetime
"""
return datetime.fromtimestamp(self.atime)
@property
def create_datetime(self):
"""
Get most recent create time in datetime.
:type self: Path
:rtype: datetime
"""
return datetime.fromtimestamp(self.ctime)
def __contains__(self, item):
if isinstance(item, six.string_types):
return self.abspath in item
else:
return self.abspath in item.abspath
def __iter__(self):
current_self = self.__class__(self)
while 1:
parent = current_self.parent
if parent == current_self:
yield current_self
break
else:
yield current_self
current_self = parent
|
class AttrAccessor(object):
'''
Provides additional attribute accessor.
'''
@property
def abspath(self):
'''
Return absolute path as a string.
:type self: Path
:rtype: str
Example: ``C:\User\admin\readme.txt`` for ``C:\User\admin\readme.txt``
'''
pass
@property
def abspath_hexstr(self):
'''
Return absolute path encoded in hex string.
:type self: Path
:rtype: str
'''
pass
@property
def dirpath(self):
'''
Parent dir full absolute path.
:type self: Path
:rtype: str
Example: ``C:\User\admin`` for ``C:\User\admin\readme.txt``
'''
pass
@property
def dirpath_hexstr(self):
'''
Return dir full absolute path encoded in hex string.
:type self: Path
:rtype: str
'''
pass
@property
def dirname(self):
'''
Parent dir name.
:type self: Path
:rtype: str
Example: ``admin`` for ``C:\User\admin\readme.txt``
'''
pass
@property
def dirname_hexstr(self):
'''
Parent dir name in hex string.
:type self: Path
:rtype: str
'''
pass
@property
def basename(self):
'''
File name with extension, path is not included.
:type self: Path
:rtype: str
Example: ``readme.txt`` for ``C:\User\admin\readme.txt``
'''
pass
@property
def basename_hexstr(self):
'''
File name with extension encoded in hex string.
:type self: Path
:rtype: str
'''
pass
@property
def fname(self):
'''
File name without extension.
:type self: Path
:rtype: str
Example: ``readme`` for ``C:\User\admin\readme.txt``
'''
pass
@property
def fname_hexstr(self):
'''
File name encoded in hex string.
:type self: Path
:rtype: str
'''
pass
@property
def ext(self):
'''
File extension. If it's a dir, then return empty str.
:type self: Path
:rtype: str
Example: ``.txt`` for ``C:\User\admin\readme.txt``
'''
pass
@property
def size(self):
'''
File size in bytes.
:type self: Path
:rtype: int
'''
pass
@property
def size_in_text(self):
'''
File size as human readable string.
:type self: Path
:rtype: str
'''
pass
@property
def mtime(self):
'''
Get most recent modify time in timestamp.
:type self: Path
:rtype: float
'''
pass
@property
def atime(self):
'''
Get most recent access time in timestamp.
:type self: Path
:rtype: float
'''
pass
@property
def ctime(self):
'''
Get most recent create time in timestamp.
:type self: Path
:rtype: float
'''
pass
@property
def modify_datetime(self):
'''
Get most recent modify time in datetime.
:type self: Path
:rtype: datetime
'''
pass
@property
def access_datetime(self):
'''
Get most recent access time in datetime.
:type self: Path
:rtype: datetime
'''
pass
@property
def create_datetime(self):
'''
Get most recent create time in datetime.
:type self: Path
:rtype: datetime
'''
pass
def __contains__(self, item):
pass
def __iter__(self):
pass
| 41 | 20 | 10 | 2 | 3 | 5 | 1 | 1.22 | 1 | 1 | 0 | 1 | 21 | 1 | 21 | 21 | 259 | 65 | 89 | 44 | 48 | 109 | 68 | 25 | 46 | 3 | 1 | 2 | 28 |
148,184 |
MacHu-GWU/pathlib_mate-project
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_pathlib_mate-project/pathlib_mate/vendor/six.py
|
pathlib_mate.vendor.six.with_metaclass.metaclass
|
class metaclass(type):
def __new__(cls, name, this_bases, d):
if sys.version_info[:2] >= (3, 7):
# This version introduced PEP 560 that requires a bit
# of extra care (we mimic what is done by __build_class__).
resolved_bases = types.resolve_bases(bases)
if resolved_bases is not bases:
d['__orig_bases__'] = bases
else:
resolved_bases = bases
return meta(name, resolved_bases, d)
@classmethod
def __prepare__(cls, name, this_bases):
return meta.__prepare__(name, bases)
|
class metaclass(type):
def __new__(cls, name, this_bases, d):
pass
@classmethod
def __prepare__(cls, name, this_bases):
pass
| 4 | 0 | 6 | 0 | 5 | 1 | 2 | 0.17 | 1 | 0 | 0 | 0 | 1 | 0 | 2 | 15 | 16 | 2 | 12 | 5 | 8 | 2 | 10 | 4 | 7 | 3 | 2 | 2 | 4 |
148,185 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/tests/test_mate_path_filters.py
|
test_mate_path_filters.TestPathFilters
|
class TestPathFilters(object):
def test_assert_is_file_and_exists(self):
Path(__file__).assert_is_file_and_exists()
with raises(Exception):
Path(__file__).parent.assert_is_file_and_exists()
with raises(Exception):
Path("THIS-FILE-NOT-EXIST").assert_is_file_and_exists()
def test_assert_is_dir_and_exists(self):
Path(__file__).parent.assert_is_dir_and_exists()
with raises(Exception):
Path(__file__).assert_is_dir_and_exists()
with raises(Exception):
Path("THIS-FILE-NOT-EXIST").assert_is_dir_and_exists()
def test_assert_exists(self):
with raises(Exception):
Path("THIS-FILE-NOT-EXIST").assert_exists()
def test_select(self):
def filters(p):
if p.fname.startswith("f"):
return True
else:
return False
path = Path(__file__).absolute().parent.parent # pathlibm_mate-project
for p in path.select(filters):
assert p.fname.startswith("f")
def test_select_file(self):
path = Path(__file__).absolute().parent.parent # pathlibm_mate-project
for p in path.select_file():
assert p.is_file()
def test_select_dir(self):
path = Path(__file__).absolute().parent.parent # pathlibm_mate-project
for p in path.select_dir():
assert p.is_dir()
def test_select_by_ext(self):
path = Path(__file__).absolute().parent.parent # pathlibm_mate-project
for p in path.select_by_ext(".Bat"):
assert p.ext.lower() == ".bat"
def test_select_by_pattern_in_fname(self):
path = Path(__file__).absolute().parent # pathlibm_mate-project/tests
for p in path.select_by_pattern_in_fname("test", case_sensitive=True):
assert "test" in p.fname
for p in path.select_by_pattern_in_fname("TEST", case_sensitive=False):
assert "test" in p.fname.lower()
def test_select_by_pattern_in_abspath(self):
path = Path(__file__).absolute().parent # pathlibm_mate-project/tests
for p in path.select_by_pattern_in_abspath("test", case_sensitive=True):
assert "test" in p.abspath
for p in path.select_by_pattern_in_abspath("TEST", case_sensitive=False):
assert "test" in p.abspath.lower()
def test_select_by_time(self):
path = Path(__file__).absolute().parent.parent # pathlibm_mate-project
for p in path.select_by_atime(min_time=0):
p.atime >= 0
for p in path.select_by_ctime(min_time=0):
p.ctime >= 0
for p in path.select_by_mtime(min_time=0):
p.mtime >= 0
def test_select_by_size(self):
path = Path(__file__).absolute().parent.parent # pathlibm_mate-project
for p in path.select_by_size(max_size=1000):
assert p.size <= 1000
def test_select_image(self):
path = Path(__file__).absolute().parent.parent # pathlibm_mate-project
for p in path.select_image():
assert p.ext in [".jpg", ".png", ".gif", ".svg"]
def test_sort_by(self):
path = Path(__file__).absolute().parent.parent # pathlibm_mate-project
p_list = Path.sort_by_size(path.select_file())
assert is_increasing([p.size for p in p_list])
p_list = Path.sort_by_size(path.select_file(), reverse=True)
assert is_decreasing([p.size for p in p_list])
def test_dirsize(self):
p = Path(__file__).parent
assert p.parent.dirsize >= 32768
|
class TestPathFilters(object):
def test_assert_is_file_and_exists(self):
pass
def test_assert_is_dir_and_exists(self):
pass
def test_assert_exists(self):
pass
def test_select(self):
pass
def filters(p):
pass
def test_select_file(self):
pass
def test_select_dir(self):
pass
def test_select_by_ext(self):
pass
def test_select_by_pattern_in_fname(self):
pass
def test_select_by_pattern_in_abspath(self):
pass
def test_select_by_time(self):
pass
def test_select_by_size(self):
pass
def test_select_image(self):
pass
def test_sort_by(self):
pass
def test_dirsize(self):
pass
| 16 | 0 | 6 | 1 | 5 | 1 | 2 | 0.14 | 1 | 2 | 1 | 0 | 14 | 0 | 14 | 14 | 99 | 25 | 74 | 37 | 58 | 10 | 73 | 37 | 57 | 4 | 1 | 1 | 29 |
148,186 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/tests/test_mate_tool_box_stateless.py
|
test_mate_tool_box_stateless.TestToolBoxStateless
|
class TestToolBoxStateless(object):
def test_dir_fingerprint(self):
p = Path(Path(__file__).dirpath)
assert p.dir_md5 == p.dir_md5
assert p.dir_sha256 == p.dir_sha256
assert p.dir_sha512 == p.dir_sha512
def test_is_empty(self):
assert Path(__file__).is_empty() is False
assert Path(__file__).parent.is_empty() is False
with raises(Exception):
assert Path("THIS-FILE-NOT-EXISTS.txt").is_empty()
def test_auto_complete_choices(self):
p = Path(__file__).change(new_basename="te")
for p in p.auto_complete_choices():
assert p.basename.lower().startswith("te")
p = Path(__file__).parent
for p1 in p.auto_complete_choices():
assert p1 in p
def test_print_big_file(self):
"""
Not need in travis.
"""
path = Path(__file__).absolute().parent.parent # pathlibm_mate-project
path.print_big_file()
path.print_big_dir()
def test_print_big_dir_and_big_file(self):
"""
Not need in travis.
"""
path = Path(__file__).absolute().parent.parent # pathlibm_mate-project
path.print_big_dir_and_big_file()
def test_dir_stat_attribute(self):
p = Path(__file__).change(new_basename="app")
assert p.n_file >= 4
assert p.n_subfile >= 3
assert p.n_dir == 1
assert p.n_subdir == 1
def test_file_stat(self):
"""
Not need in travis.
"""
p = Path(__file__).parent
stat = p.file_stat()
assert stat["file"] >= 14
assert stat["dir"] >= 2
assert stat["size"] >= 32000
all_stat = p.file_stat_for_all()
assert all_stat[p.abspath] == stat
|
class TestToolBoxStateless(object):
def test_dir_fingerprint(self):
pass
def test_is_empty(self):
pass
def test_auto_complete_choices(self):
pass
def test_print_big_file(self):
'''
Not need in travis.
'''
pass
def test_print_big_dir_and_big_file(self):
'''
Not need in travis.
'''
pass
def test_dir_stat_attribute(self):
pass
def test_file_stat(self):
'''
Not need in travis.
'''
pass
| 8 | 3 | 7 | 0 | 5 | 2 | 1 | 0.28 | 1 | 2 | 1 | 0 | 7 | 0 | 7 | 7 | 56 | 8 | 39 | 17 | 31 | 11 | 39 | 17 | 31 | 3 | 1 | 1 | 9 |
148,187 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/tests/test_mate_tool_box_zip.py
|
test_mate_tool_box_zip.TestToolBoxZip
|
class TestToolBoxZip(object):
def test_auto_zip_archive_dst(self):
p = dir_pathlib_mate._default_zip_dst()
assert p.dirpath == dir_pathlib_mate.dirpath
p = p_this._default_zip_dst()
assert p.dirpath == p_this.dirpath
def test_make_zip_archive(self):
dst = dir_tests.append_parts("pathlib_mate_with_dir.zip").abspath
dir_pathlib_mate.make_zip_archive(dst=dst, verbose=False)
dst = dir_tests.append_parts("pathlib_mate_without_dir.zip").abspath
dir_pathlib_mate.make_zip_archive(dst=dst, include_dir=False, compress=False, verbose=False)
p_this.make_zip_archive(verbose=False)
# error handling
# already exists error
with pytest.raises(OSError):
dir_pathlib_mate.make_zip_archive(dst=dst, verbose=False)
# file extension error
with pytest.raises(ValueError):
dst = dir_tests.append_parts("pathlib_mate_with_dir.tar").abspath
dir_pathlib_mate.make_zip_archive(dst=dst, verbose=False)
def test_backup(self):
dir_app.backup(verbose=False)
p_this.backup(verbose=False)
|
class TestToolBoxZip(object):
def test_auto_zip_archive_dst(self):
pass
def test_make_zip_archive(self):
pass
def test_backup(self):
pass
| 4 | 0 | 9 | 2 | 6 | 1 | 1 | 0.15 | 1 | 2 | 0 | 0 | 3 | 0 | 3 | 3 | 31 | 8 | 20 | 6 | 16 | 3 | 20 | 6 | 16 | 1 | 1 | 1 | 3 |
148,188 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/tests/test_mate_tool_box_stateful.py
|
test_mate_tool_box_stateful.TestToolBoxStateful
|
class TestToolBoxStateful(object):
def test_make_zip_archive(self):
p = Path(__file__).change(new_basename="app")
p.make_zip_archive()
def test_mirror_to(self):
"""
Not need in travis.
"""
p = Path(__file__).change(new_basename="app")
dst = Path(__file__).change(new_basename="mirror")
p.mirror_to(dst.abspath)
def test_backup(self):
"""
Not need in travis.
"""
import random
p = Path(__file__).change(new_basename="app")
dst = Path(__file__).change(
new_basename="app-backup-%s.zip" % random.randint(1, 9999)
)
assert dst.exists() is False
p.backup(dst.abspath, ignore_size_larger_than=1000, case_sensitive=False)
assert dst.exists() is True
def test_autopep8(self):
"""
Not need in travis.
"""
p = Path(__file__).change(new_basename="app")
p.autopep8()
def test_trail_space(self):
"""
Not need in travis.
"""
p = Path(__file__).change(new_basename="app")
p.trail_space()
def test_temp_cwd(self):
p = Path(__file__).parent.parent.parent
assert Path.cwd() != p
with p.temp_cwd():
assert Path.cwd() == p
assert Path.cwd() != p
|
class TestToolBoxStateful(object):
def test_make_zip_archive(self):
pass
def test_mirror_to(self):
'''
Not need in travis.
'''
pass
def test_backup(self):
'''
Not need in travis.
'''
pass
def test_autopep8(self):
'''
Not need in travis.
'''
pass
def test_trail_space(self):
'''
Not need in travis.
'''
pass
def test_temp_cwd(self):
pass
| 7 | 4 | 7 | 0 | 5 | 2 | 1 | 0.41 | 1 | 1 | 1 | 0 | 6 | 0 | 6 | 6 | 48 | 7 | 29 | 16 | 21 | 12 | 27 | 16 | 19 | 1 | 1 | 1 | 6 |
148,189 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/tests/test_mate_mutate_methods.py
|
test_mate_mutate_methods.TestRemoveFileOrDir
|
class TestRemoveFileOrDir(object):
dir_here = Path(__file__).parent
path_to_move_file = Path(dir_here, "to_move_file.txt")
path_to_move_dir = Path(dir_here, "to_move_dir")
path_to_move_dir_file = Path(dir_here, "to_move_dir", "to_move_file.txt")
def setup_method(self, method):
self.path_to_move_file.write_text("test")
self.path_to_move_dir.mkdir_if_not_exists()
self.path_to_move_dir_file.write_text("test")
# def teardown_method(self, method):
def test_remove(self):
self.path_to_move_file.remove()
assert self.path_to_move_file.exists() is False
with pytest.raises(Exception):
self.path_to_move_file.remove()
def test_remove_if_exists(self):
# remove a file
self.path_to_move_file.remove_if_exists()
assert self.path_to_move_file.exists() is False
self.path_to_move_file.remove_if_exists()
# remove a dir
self.path_to_move_dir.remove_if_exists()
assert self.path_to_move_dir.exists() is False
self.path_to_move_dir.remove_if_exists()
def test_dir_here(self):
dir_here = Path.dir_here(__file__)
assert dir_here.basename == "tests"
|
class TestRemoveFileOrDir(object):
def setup_method(self, method):
pass
def test_remove(self):
pass
def test_remove_if_exists(self):
pass
def test_dir_here(self):
pass
| 5 | 0 | 6 | 1 | 5 | 1 | 1 | 0.13 | 1 | 2 | 1 | 0 | 4 | 0 | 4 | 4 | 33 | 6 | 24 | 10 | 19 | 3 | 24 | 10 | 19 | 1 | 1 | 1 | 4 |
148,190 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/tests/test_mate_mutate_methods.py
|
test_mate_mutate_methods.TestMutateMethods
|
class TestMutateMethods(object):
def test_drop_parts(self):
p = Path(__file__)
p1 = p.drop_parts(1)
assert len(p.parts) == len(p1.parts) + 1
p1 = p.drop_parts(2)
assert len(p.parts) == len(p1.parts) + 2
def test_append_parts(self):
p = Path(__file__).parent
p1 = p.append_parts("a")
assert len(p.parts) == len(p1.parts) - 1
p1 = p.append_parts("a", "b")
assert len(p.parts) == len(p1.parts) - 2
def test_change(self):
p = Path(__file__)
p1 = p.change(new_ext=".txt")
assert p1.ext == ".txt"
assert p1.fname == p.fname
assert p1.dirname == p.dirname
assert p1.dirpath == p.dirpath
p1 = p.change(new_fname="hello")
assert p1.ext == p.ext
assert p1.fname == "hello"
assert p1.dirname == p.dirname
assert p1.dirpath == p.dirpath
p1 = p.change(new_basename="hello.txt")
assert p1.ext == ".txt"
assert p1.fname == "hello"
assert p1.dirname == p.dirname
assert p1.dirpath == p.dirpath
p1 = p.change(new_dirname="folder")
assert p1.ext == p.ext
assert p1.fname == p.fname
assert p1.dirname == "folder"
assert p1.dirpath.endswith("folder")
with raises(ValueError):
p.change(new_dirpath="new_dirpath", new_dirname="folder")
with raises(ValueError):
p.change(new_basename="hello.txt", new_fname="hello")
with raises(ValueError):
p.change(new_basename="hello.txt", new_ext="hello")
# because __file__ is OS dependent, so don't test this.
system_name = platform.system()
if system_name == "Windows":
p1 = p.change(new_dirpath="C:\\User")
assert p1.ext == p.ext
assert p1.fname == p.fname
assert p1.dirname == "User"
assert p1.dirpath == "C:\\User"
elif system_name in ["Darwin", "Linux"]:
p1 = p.change(new_dirpath="/Users")
assert p1.ext == p.ext
assert p1.fname == p.fname
assert p1.dirname == "Users"
assert p1.dirpath == "/Users"
def test_moveto(self):
# move file
p_file = Path(__file__).change(new_basename="file_to_move.txt")
p_file_new = p_file.moveto(new_ext=".rst") # change extension
assert p_file.exists() is False
assert p_file_new.exists() is True
p_file = p_file_new.moveto(new_ext=".txt") # move back
# move file into not existing folder
with pytest.raises(EnvironmentError):
p_file.moveto(new_dirname="NOT-EXIST-FOLDER-MOVETO")
# move file into not existsing folder, and create the folder
p_file_new = p_file.moveto(
new_abspath=Path(__file__).parent.append_parts(
"NOT-EXIST-FOLDER-MOVETO", "file_to_move.txt"
),
makedirs=True,
)
p_file = p_file_new.moveto(new_abspath=p_file.abspath)
# move directory
p_dir = Path(__file__).change(new_basename="wow")
n_files = p_dir.n_file
n_dir = p_dir.n_dir
p_dir_new = p_dir.moveto(new_basename="wow1")
assert n_files == p_dir_new.n_file
assert n_dir == p_dir_new.n_dir
p_dir = p_dir_new.moveto(new_basename="wow")
def test_copyto(self):
# copy file
p_file = Path(__file__).change(new_basename="file_to_copy.txt")
p_file_new = p_file.change(new_ext=".rst")
assert p_file_new.exists() is False
p_file_new = p_file.copyto(new_ext=".rst")
assert p_file.exists() is True
assert p_file_new.exists() is True
# copy file into not existing folder
with pytest.raises(Exception):
p_file.copyto(new_dirname="NOT-EXIST-FOLDER-COPYTO")
# copy file into not existing folder, and create the folder
p_file_new = p_file.change(
new_abspath=Path(__file__).parent.append_parts(
"NOT-EXIST-FOLDER-COPYTO", "file_to_copy.txt"
),
)
assert p_file_new.exists() is False
assert p_file_new.parent.exists() is False
p_file_new = p_file.copyto(
new_abspath=Path(__file__).parent.append_parts(
"NOT-EXIST-FOLDER-COPYTO", "file_to_copy.txt"
),
makedirs=True,
)
assert p_file_new.exists() is True
# copy directory
p_dir = Path(__file__).change(new_basename="wow")
n_files = p_dir.n_file
p_dir_new = p_dir.moveto(new_basename="wow1")
assert n_files == p_dir_new.n_file
|
class TestMutateMethods(object):
def test_drop_parts(self):
pass
def test_append_parts(self):
pass
def test_change(self):
pass
def test_moveto(self):
pass
def test_copyto(self):
pass
| 6 | 0 | 26 | 3 | 20 | 2 | 1 | 0.11 | 1 | 3 | 1 | 0 | 5 | 0 | 5 | 5 | 133 | 21 | 103 | 24 | 97 | 11 | 88 | 24 | 82 | 3 | 1 | 1 | 7 |
148,191 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/tests/test_mate_hashes_methods.py
|
test_mate_hashes_methods.TestHashesMethods
|
class TestHashesMethods(object):
def test(self):
p = Path(__file__)
assert (
len(
{
p.md5,
p.get_partial_md5(nbytes=1 << 20),
p.sha256,
p.get_partial_sha256(nbytes=1 << 20),
p.sha512,
p.get_partial_sha512(nbytes=1 << 20),
}
)
== 3
)
|
class TestHashesMethods(object):
def test(self):
pass
| 2 | 0 | 15 | 0 | 15 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 1 | 16 | 0 | 16 | 3 | 14 | 0 | 4 | 3 | 2 | 1 | 1 | 0 | 1 |
148,192 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/tests/test_mate_attr_accessor.py
|
test_mate_attr_accessor.TestAttrAccessor
|
class TestAttrAccessor(object):
def test(self):
HEXSTR_CHARSET = set("0123456789abcdef")
def assert_hexstr(text):
assert len(HEXSTR_CHARSET.union(set(text))) <= 16
p = Path(__file__).absolute()
assert isinstance(p.abspath, six.string_types)
assert isinstance(p.dirpath, six.string_types)
assert p.abspath == __file__
assert p.dirpath == os.path.dirname(__file__)
assert p.dirname == os.path.basename(os.path.dirname(__file__))
assert p.basename == os.path.basename(__file__)
assert p.fname == os.path.splitext(os.path.basename(__file__))[0]
assert p.ext == os.path.splitext(__file__)[1]
assert_hexstr(p.abspath_hexstr)
assert_hexstr(p.dirpath_hexstr)
assert_hexstr(p.dirname_hexstr)
assert_hexstr(p.basename_hexstr)
assert_hexstr(p.fname_hexstr)
assert len(p.md5) == 32
assert len(p.get_partial_md5(1)) == 32
assert p.size >= 1024
ts_2016_1_1 = (datetime(2016, 1, 1) -
datetime(1970, 1, 1)).total_seconds()
assert p.ctime >= ts_2016_1_1
assert p.mtime >= ts_2016_1_1
assert p.atime >= ts_2016_1_1
assert p.modify_datetime >= datetime(2016, 1, 1)
assert p.access_datetime >= datetime(2016, 1, 1)
assert p.create_datetime >= datetime(2016, 1, 1)
assert "KB" in p.size_in_text
assert p.get_partial_md5(
nbytes=10) == "52ee8aa6c482035e08afabda0f0f8dd8"
with raises(ValueError):
p.get_partial_md5(-1)
def test_contains(self):
p = Path(__file__).absolute()
assert p in p.parent
assert p.abspath in p.parent # string also works
assert p.parent not in p
def test_iter(self):
p = Path(__file__).absolute()
for ancestor in p:
assert p in ancestor
|
class TestAttrAccessor(object):
def test(self):
pass
def assert_hexstr(text):
pass
def test_contains(self):
pass
def test_iter(self):
pass
| 5 | 0 | 13 | 2 | 11 | 0 | 1 | 0.02 | 1 | 4 | 1 | 0 | 3 | 0 | 3 | 3 | 52 | 8 | 44 | 11 | 39 | 1 | 42 | 11 | 37 | 2 | 1 | 1 | 5 |
148,193 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/tests/test_helper.py
|
test_helper.Path
|
class Path(object):
def __init__(self, p):
self.p = p
def __str__(self):
return self.p
|
class Path(object):
def __init__(self, p):
pass
def __str__(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 6 | 1 | 5 | 4 | 2 | 0 | 5 | 4 | 2 | 1 | 1 | 0 | 2 |
148,194 |
MacHu-GWU/pathlib_mate-project
|
MacHu-GWU_pathlib_mate-project/pathlib_mate/vendor/six.py
|
pathlib_mate.vendor.six._SixMetaPathImporter
|
class _SixMetaPathImporter(object):
"""
A meta path importer to import six.moves and its submodules.
This class implements a PEP302 finder and loader. It should be compatible
with Python 2.5 and all existing versions of Python3
"""
def __init__(self, six_module_name):
self.name = six_module_name
self.known_modules = {}
def _add_module(self, mod, *fullnames):
for fullname in fullnames:
self.known_modules[self.name + "." + fullname] = mod
def _get_module(self, fullname):
return self.known_modules[self.name + "." + fullname]
def find_module(self, fullname, path=None):
if fullname in self.known_modules:
return self
return None
def find_spec(self, fullname, path, target=None):
if fullname in self.known_modules:
return spec_from_loader(fullname, self)
return None
def __get_module(self, fullname):
try:
return self.known_modules[fullname]
except KeyError:
raise ImportError("This loader does not know module " + fullname)
def load_module(self, fullname):
try:
# in case of a reload
return sys.modules[fullname]
except KeyError:
pass
mod = self.__get_module(fullname)
if isinstance(mod, MovedModule):
mod = mod._resolve()
else:
mod.__loader__ = self
sys.modules[fullname] = mod
return mod
def is_package(self, fullname):
"""
Return true, if the named module is a package.
We need this method to get correct spec objects with
Python 3.4 (see PEP451)
"""
return hasattr(self.__get_module(fullname), "__path__")
def get_code(self, fullname):
"""Return None
Required, if is_package is implemented"""
self.__get_module(fullname) # eventually raises ImportError
return None
get_source = get_code # same as get_code
def create_module(self, spec):
return self.load_module(spec.name)
def exec_module(self, module):
pass
|
class _SixMetaPathImporter(object):
'''
A meta path importer to import six.moves and its submodules.
This class implements a PEP302 finder and loader. It should be compatible
with Python 2.5 and all existing versions of Python3
'''
def __init__(self, six_module_name):
pass
def _add_module(self, mod, *fullnames):
pass
def _get_module(self, fullname):
pass
def find_module(self, fullname, path=None):
pass
def find_spec(self, fullname, path, target=None):
pass
def __get_module(self, fullname):
pass
def load_module(self, fullname):
pass
def is_package(self, fullname):
'''
Return true, if the named module is a package.
We need this method to get correct spec objects with
Python 3.4 (see PEP451)
'''
pass
def get_code(self, fullname):
'''Return None
Required, if is_package is implemented'''
pass
def create_module(self, spec):
pass
def exec_module(self, module):
pass
| 12 | 3 | 5 | 0 | 4 | 1 | 2 | 0.34 | 1 | 3 | 1 | 0 | 11 | 2 | 11 | 11 | 72 | 15 | 44 | 17 | 32 | 15 | 43 | 17 | 31 | 3 | 1 | 1 | 17 |
148,195 |
MacHu-GWU/pyknackhq-project
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_pyknackhq-project/pyknackhq/js.py
|
pyknackhq.js.JSUnittest
|
class JSUnittest(unittest.TestCase):
def test_write_and_read(self):
data = {"a": [1, 2], "b": ["是", "否"]}
safe_dump_js(data, "data.json")
data = load_js("data.json")
self.assertEqual(data["a"][0], 1)
self.assertEqual(data["b"][0], "是")
def test_js2str(self):
data = {"a": [1, 2], "b": ["是", "否"]}
prt_js(data)
def test_compress(self):
data = {"a": list(range(32)),
"b": list(range(32)), }
safe_dump_js(data, "data.gz", compress=True)
prt_js(load_js("data.gz", compress=True))
def tearDown(self):
for path in ["data.json", "data.gz"]:
try:
os.remove(path)
except:
pass
|
class JSUnittest(unittest.TestCase):
def test_write_and_read(self):
pass
def test_js2str(self):
pass
def test_compress(self):
pass
def tearDown(self):
pass
| 5 | 0 | 5 | 0 | 5 | 0 | 2 | 0 | 1 | 2 | 0 | 0 | 4 | 0 | 4 | 76 | 24 | 3 | 21 | 9 | 16 | 0 | 20 | 9 | 15 | 3 | 2 | 2 | 6 |
148,196 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/datatype.py
|
pyknackhq.datatype.DateTimeFromToType
|
class DateTimeFromToType(BaseDataType):
"""From xxx to xxx Type.
:param from_: from datetime or date
:param to_: to datetime or date
:param repeat: a python dict contains repeat information
:param all_day: Default False, True for date only
example repeat param::
{
"FR": true,
"MO": true,
"SA": false,
"SU": false,
"TH": true,
"TU": true,
"WE": true,
"end_count": "",
"end_date": "",
"endson": "never",
"frequency": "weekly",
"interval": "1",
"repeatby": "dom",
"start_date": "11/01/2015"
},
"""
def __init__(self, from_, to_, repeat=None, all_day=False):
from_and_to = list()
from_and_to_data = list()
for value in [from_, to_]:
if isinstance(value, datetime):
if all_day:
from_and_to.append(value.date())
from_and_to_data.append(
{"date": value.strftime("%m/%d/%Y")})
else:
from_and_to.append(value)
from_and_to_data.append({
"date": value.strftime("%m/%d/%Y"),
"hours": value.hour,
"minutes": value.minute,
})
elif isinstance(value, date):
from_and_to.append(value)
from_and_to_data.append(
{"date": value.strftime("%m/%d/%Y")}
)
self.from_ = from_and_to[0]
self.to_ = from_and_to[1]
self._data = from_and_to_data[0]
self._data["to"] = from_and_to_data[1]
if all_day:
self._data["all_day"] = True
if repeat:
self.repeat = repeat
self._data["repeat"] = repeat
|
class DateTimeFromToType(BaseDataType):
'''From xxx to xxx Type.
:param from_: from datetime or date
:param to_: to datetime or date
:param repeat: a python dict contains repeat information
:param all_day: Default False, True for date only
example repeat param::
{
"FR": true,
"MO": true,
"SA": false,
"SU": false,
"TH": true,
"TU": true,
"WE": true,
"end_count": "",
"end_date": "",
"endson": "never",
"frequency": "weekly",
"interval": "1",
"repeatby": "dom",
"start_date": "11/01/2015"
},
'''
def __init__(self, from_, to_, repeat=None, all_day=False):
pass
| 2 | 1 | 33 | 3 | 30 | 0 | 7 | 0.74 | 1 | 3 | 0 | 0 | 1 | 4 | 1 | 2 | 60 | 6 | 31 | 9 | 29 | 23 | 22 | 9 | 20 | 7 | 2 | 3 | 7 |
148,197 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/datatype.py
|
pyknackhq.datatype.DateTimeType
|
class DateTimeType(BaseDataType): # TODO
"""Date time type.
:param value: Python datetime, date type
:param is_date: Default False, True for date only
"""
def __init__(self, value, is_date=False):
if isinstance(value, datetime):
if is_date:
self.value = value.date()
self._data = {"date": self.value.strftime("%m/%d/%Y")}
else:
self.value = value
self._data = {
"date": self.value.strftime("%m/%d/%Y"),
"hours": self.value.hour,
"minutes": self.value.minute,
}
elif isinstance(value, date):
self.value = value
self._data = {"date": self.value.strftime("%m/%d/%Y")}
|
class DateTimeType(BaseDataType):
'''Date time type.
:param value: Python datetime, date type
:param is_date: Default False, True for date only
'''
def __init__(self, value, is_date=False):
pass
| 2 | 1 | 15 | 0 | 15 | 0 | 4 | 0.31 | 1 | 2 | 0 | 0 | 1 | 2 | 1 | 2 | 21 | 1 | 16 | 4 | 14 | 5 | 10 | 4 | 8 | 4 | 2 | 2 | 4 |
148,198 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/datatype.py
|
pyknackhq.datatype.EmailType
|
class EmailType(BaseDataType):
"""Email type.
"""
def __init__(self, email, label=None):
self.email = email
self.label = label
@property
def _data(self):
attrs = ["email", "label"]
d = dict()
for attr in attrs:
value = self.__getattribute__(attr)
if value:
d[attr] = value
return d
|
class EmailType(BaseDataType):
'''Email type.
'''
def __init__(self, email, label=None):
pass
@property
def _data(self):
pass
| 4 | 1 | 6 | 0 | 6 | 0 | 2 | 0.15 | 1 | 1 | 0 | 0 | 2 | 2 | 2 | 3 | 16 | 1 | 13 | 10 | 9 | 2 | 12 | 9 | 9 | 3 | 2 | 2 | 4 |
148,199 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/datatype.py
|
pyknackhq.datatype.LinkType
|
class LinkType(BaseDataType):
"""Link type.
"""
def __init__(self, url, label=None):
self.url = url
self.label = label
@property
def _data(self):
attrs = ["url", "label"]
d = dict()
for attr in attrs:
value = self.__getattribute__(attr)
if value:
d[attr] = value
return d
|
class LinkType(BaseDataType):
'''Link type.
'''
def __init__(self, url, label=None):
pass
@property
def _data(self):
pass
| 4 | 1 | 6 | 0 | 6 | 0 | 2 | 0.15 | 1 | 1 | 0 | 0 | 2 | 2 | 2 | 3 | 16 | 1 | 13 | 10 | 9 | 2 | 12 | 9 | 9 | 3 | 2 | 2 | 4 |
148,200 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/datatype.py
|
pyknackhq.datatype.NameType
|
class NameType(BaseDataType):
"""Name type.
"""
def __init__(self, title=None, first=None, middle=None, last=None):
self.title = title
self.first = first
self.middle = middle
self.last = last
@property
def _data(self):
attrs = ["title", "first", "middle", "last"]
d = dict()
for attr in attrs:
value = self.__getattribute__(attr)
if value:
d[attr] = value
return d
|
class NameType(BaseDataType):
'''Name type.
'''
def __init__(self, title=None, first=None, middle=None, last=None):
pass
@property
def _data(self):
pass
| 4 | 1 | 7 | 0 | 7 | 0 | 2 | 0.13 | 1 | 1 | 0 | 0 | 2 | 4 | 2 | 3 | 18 | 1 | 15 | 12 | 11 | 2 | 14 | 11 | 11 | 3 | 2 | 2 | 4 |
148,201 |
MacHu-GWU/pyknackhq-project
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_pyknackhq-project/pyknackhq/schema.py
|
pyknackhq.schema.ApplicationUnittest
|
class ApplicationUnittest(unittest.TestCase):
def test_from_dict(self):
d = load_js(SCHEMA_JSON_PATH, enable_verbose=False)
application = Application.from_dict(d)
def test_from_json(self):
application = Application.from_json(SCHEMA_JSON_PATH)
def test_to_json(self):
application = Application.from_json(SCHEMA_JSON_PATH)
application.to_json("schema.json")
def test_all(self):
d = load_js(SCHEMA_JSON_PATH, enable_verbose=False)
application = Application.from_dict(d)
print(application.all_object_key)
print(application.all_object_name)
test_object = application.get_object("test_object")
print(test_object.all_field_key)
print(test_object.all_field_name)
short_text_field = test_object.get_field("short text field")
|
class ApplicationUnittest(unittest.TestCase):
def test_from_dict(self):
pass
def test_from_json(self):
pass
def test_to_json(self):
pass
def test_all(self):
pass
| 5 | 0 | 5 | 1 | 4 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 4 | 0 | 4 | 76 | 23 | 5 | 18 | 13 | 13 | 0 | 18 | 13 | 13 | 1 | 2 | 0 | 4 |
148,202 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/datatype.py
|
pyknackhq.datatype.NumberType
|
class NumberType(BaseDataType):
"""Integer or Float Type.
"""
def __init__(self, value):
if not isinstance(value, _number_types):
raise TypeError("'value' has to be int or float")
self.value = value
# construct data
self._data = self.value
|
class NumberType(BaseDataType):
'''Integer or Float Type.
'''
def __init__(self, value):
pass
| 2 | 1 | 8 | 2 | 5 | 1 | 2 | 0.5 | 1 | 1 | 0 | 0 | 1 | 2 | 1 | 2 | 11 | 2 | 6 | 4 | 4 | 3 | 6 | 4 | 4 | 2 | 2 | 1 | 2 |
148,203 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/datatype.py
|
pyknackhq.datatype.ParagraphTextType
|
class ParagraphTextType(BaseDataType):
"""Paragraph text type.
"""
def __init__(self, value):
if not isinstance(value, _str_type):
raise TypeError("'value' has to be str")
self.value = value
# construct data
self._data = self.value
|
class ParagraphTextType(BaseDataType):
'''Paragraph text type.
'''
def __init__(self, value):
pass
| 2 | 1 | 7 | 1 | 5 | 1 | 2 | 0.5 | 1 | 1 | 0 | 0 | 1 | 2 | 1 | 2 | 10 | 1 | 6 | 4 | 4 | 3 | 6 | 4 | 4 | 2 | 2 | 1 | 2 |
148,204 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/datatype.py
|
pyknackhq.datatype.PhoneType
|
class PhoneType(BaseDataType):
"""Phone type.
"""
def __init__(self, full=None, area=None, country=None, number=None):
self.full = full
self.area = area
self.country = country
self.number = number
@property
def _data(self):
attrs = ["full", "area", "country", "number"]
d = dict()
for attr in attrs:
value = self.__getattribute__(attr)
if value:
d[attr] = value
return d
|
class PhoneType(BaseDataType):
'''Phone type.
'''
def __init__(self, full=None, area=None, country=None, number=None):
pass
@property
def _data(self):
pass
| 4 | 1 | 7 | 0 | 7 | 0 | 2 | 0.13 | 1 | 1 | 0 | 0 | 2 | 4 | 2 | 3 | 18 | 1 | 15 | 12 | 11 | 2 | 14 | 11 | 11 | 3 | 2 | 2 | 4 |
148,205 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/datatype.py
|
pyknackhq.datatype.RatingType
|
class RatingType(BaseDataType):
"""Rating type.
"""
def __init__(self, value):
if not isinstance(value, _number_types):
raise TypeError("'value' has to be int or float")
self.value = value
# construct data
self._data = self.value
|
class RatingType(BaseDataType):
'''Rating type.
'''
def __init__(self, value):
pass
| 2 | 1 | 8 | 2 | 5 | 1 | 2 | 0.5 | 1 | 1 | 0 | 0 | 1 | 2 | 1 | 2 | 11 | 2 | 6 | 4 | 4 | 3 | 6 | 4 | 4 | 2 | 2 | 1 | 2 |
148,206 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/datatype.py
|
pyknackhq.datatype.RichTextType
|
class RichTextType(BaseDataType):
"""Rich html text type.
"""
def __init__(self, value):
if not isinstance(value, _str_type):
raise TypeError("'value' has to be str")
self.value = value
# construct data
self._data = self.value
|
class RichTextType(BaseDataType):
'''Rich html text type.
'''
def __init__(self, value):
pass
| 2 | 1 | 7 | 1 | 5 | 1 | 2 | 0.5 | 1 | 1 | 0 | 0 | 1 | 2 | 1 | 2 | 10 | 1 | 6 | 4 | 4 | 3 | 6 | 4 | 4 | 2 | 2 | 1 | 2 |
148,207 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/datatype.py
|
pyknackhq.datatype.ShortTextType
|
class ShortTextType(BaseDataType):
"""Short text type.
"""
def __init__(self, value):
if not isinstance(value, _str_type):
raise TypeError("'value' has to be str")
self.value = value
# construct data
self._data = self.value
|
class ShortTextType(BaseDataType):
'''Short text type.
'''
def __init__(self, value):
pass
| 2 | 1 | 7 | 1 | 5 | 1 | 2 | 0.5 | 1 | 1 | 0 | 0 | 1 | 2 | 1 | 2 | 10 | 1 | 6 | 4 | 4 | 3 | 6 | 4 | 4 | 2 | 2 | 1 | 2 |
148,208 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/datatype.py
|
pyknackhq.datatype.SingleChoiceType
|
class SingleChoiceType(BaseDataType):
"""Single choice type.
"""
def __init__(self, value):
if not isinstance(value, _str_type):
raise TypeError("'value' has to be str")
self.value = value
# construct data
self._data = self.value
|
class SingleChoiceType(BaseDataType):
'''Single choice type.
'''
def __init__(self, value):
pass
| 2 | 1 | 7 | 1 | 5 | 1 | 2 | 0.5 | 1 | 1 | 0 | 0 | 1 | 2 | 1 | 2 | 10 | 1 | 6 | 4 | 4 | 3 | 6 | 4 | 4 | 2 | 2 | 1 | 2 |
148,209 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/datatype.py
|
pyknackhq.datatype.TimerType
|
class TimerType(BaseDataType):
"""Timer type.
:param from_: from datetime
:param to_: to datetime
"""
def __init__(self, from_, to_):
from_and_to_data = list()
for value in [from_, to_]:
from_and_to_data.append({
"date": value.strftime("%m/%d/%Y"),
"hours": value.hour,
"minutes": value.minute,
})
self.from_ = from_
self.to_ = to_
times = [{"from": from_and_to_data[0], "to": from_and_to_data[1]}]
self._data = {"times": times}
|
class TimerType(BaseDataType):
'''Timer type.
:param from_: from datetime
:param to_: to datetime
'''
def __init__(self, from_, to_):
pass
| 2 | 1 | 14 | 2 | 12 | 0 | 2 | 0.31 | 1 | 1 | 0 | 0 | 1 | 3 | 1 | 2 | 20 | 3 | 13 | 8 | 11 | 4 | 9 | 8 | 7 | 2 | 2 | 1 | 2 |
148,210 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/datatype.py
|
pyknackhq.datatype.YesNoType
|
class YesNoType(BaseDataType):
"""Yes or No boolean type.
"""
def __init__(self, value):
if not isinstance(value, bool):
raise TypeError("'value' has to be bool")
self.value = value
# construct data
self._data = self.value
|
class YesNoType(BaseDataType):
'''Yes or No boolean type.
'''
def __init__(self, value):
pass
| 2 | 1 | 8 | 2 | 5 | 1 | 2 | 0.5 | 1 | 2 | 0 | 0 | 1 | 2 | 1 | 2 | 11 | 2 | 6 | 4 | 4 | 3 | 6 | 4 | 4 | 2 | 2 | 1 | 2 |
148,211 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/schema.py
|
pyknackhq.schema.Application
|
class Application(object):
"""Application class that holding object and its fields information.
"""
def __init__(self, **kwargs):
self.data = {"application": kwargs}
for k, v in kwargs.items():
object.__setattr__(self, k, v)
self.o = OrderedDict() # {field_key: Field instance}
self.o_name = OrderedDict() # {field_name: Field instance}
for d in self.objects:
object_ = Object.from_dict(d)
self.o.setdefault(d["key"], object_)
self.o_name.setdefault(d["name"], object_)
def __str__(self):
return "Application('%s')" % self.name
def __repr__(self):
return "Application('%s')" % self.name
@staticmethod
def from_dict(d):
return Application(**d["application"])
@staticmethod
def from_json(abspath):
return Application.from_dict(load_js(abspath, enable_verbose=False))
def to_json(self, abspath):
safe_dump_js(self.data, abspath, enable_verbose=False)
def __iter__(self):
return iter(self.o.values())
@property
def all_object_key(self):
"""Return all available object_key.
"""
return [o.key for o in self.o.values()]
@property
def all_object_name(self):
"""Return all available object_name.
"""
return [o.name for o in self.o.values()]
def get_object_key(self, key, using_name=True):
"""Given a object key or name, return it's object key.
"""
try:
if using_name:
return self.o_name[key].key
else:
return self.o[key].key
except KeyError:
raise ValueError("'%s' are not found!" % key)
def get_object(self, key, using_name=True):
"""Given a object key or name, return the Object instance.
"""
try:
if using_name:
return self.o_name[key]
else:
return self.o[key]
except KeyError:
raise ValueError("'%s' are not found!" % key)
|
class Application(object):
'''Application class that holding object and its fields information.
'''
def __init__(self, **kwargs):
pass
def __str__(self):
pass
def __repr__(self):
pass
@staticmethod
def from_dict(d):
pass
@staticmethod
def from_json(abspath):
pass
def to_json(self, abspath):
pass
def __iter__(self):
pass
@property
def all_object_key(self):
'''Return all available object_key.
'''
pass
@property
def all_object_name(self):
'''Return all available object_name.
'''
pass
def get_object_key(self, key, using_name=True):
'''Given a object key or name, return it's object key.
'''
pass
def get_object_key(self, key, using_name=True):
'''Given a object key or name, return the Object instance.
'''
pass
| 16 | 5 | 5 | 0 | 4 | 1 | 2 | 0.26 | 1 | 4 | 1 | 0 | 9 | 3 | 11 | 11 | 68 | 11 | 47 | 22 | 31 | 12 | 41 | 18 | 29 | 3 | 1 | 2 | 17 |
148,212 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/schema.py
|
pyknackhq.schema.Object
|
class Object(object):
"""Data object class.
Object are used to define an abstract concept of thing. For example, an
employee can be an object having attributes: name, date of birth, phone,
email, etc...
"""
def __init__(self, **kwargs):
for k, v in kwargs.items():
object.__setattr__(self, k, v)
self.f = OrderedDict() # {field_key: Field instance}
self.f_name = OrderedDict() # {field_name: Field instance}
for d in self.fields:
field = Field.from_dict(d)
self.f.setdefault(d["key"], field)
self.f_name.setdefault(d["name"], field)
def __str__(self):
return "Object('%s')" % self.name
def __repr__(self):
return "Object(key='%s', name='%s')" % (self.key, self.name)
@staticmethod
def from_dict(d):
return Object(**d)
@staticmethod
def from_json(abspath):
return Object.from_dict(load_js(abspath, enable_verbose=False))
def __iter__(self):
return iter(self.f.values())
@property
def all_field_key(self):
"""Return all available field_key.
"""
return [f.key for f in self.f.values()]
@property
def all_field_name(self):
"""Return all available field_name.
"""
return [f.name for f in self.f.values()]
def get_field_key(self, key, using_name=True):
"""Given a field key or name, return it's field key.
"""
try:
if using_name:
return self.f_name[key].key
else:
return self.f[key].key
except KeyError:
raise ValueError("'%s' are not found!" % key)
def get_field(self, key, using_name=True):
"""Given a field key or name, return the Field instance.
"""
try:
if using_name:
return self.f_name[key]
else:
return self.f[key]
except KeyError:
raise ValueError("'%s' are not found!" % key)
|
class Object(object):
'''Data object class.
Object are used to define an abstract concept of thing. For example, an
employee can be an object having attributes: name, date of birth, phone,
email, etc...
'''
def __init__(self, **kwargs):
pass
def __str__(self):
pass
def __repr__(self):
pass
@staticmethod
def from_dict(d):
pass
@staticmethod
def from_json(abspath):
pass
def __iter__(self):
pass
@property
def all_field_key(self):
'''Return all available field_key.
'''
pass
@property
def all_field_name(self):
'''Return all available field_name.
'''
pass
def get_field_key(self, key, using_name=True):
'''Given a field key or name, return it's field key.
'''
pass
def get_field_key(self, key, using_name=True):
'''Given a field key or name, return the Field instance.
'''
pass
| 15 | 5 | 5 | 0 | 4 | 1 | 2 | 0.34 | 1 | 4 | 1 | 1 | 8 | 2 | 10 | 10 | 68 | 11 | 44 | 20 | 29 | 15 | 38 | 16 | 27 | 3 | 1 | 2 | 16 |
148,213 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/datatype.py
|
pyknackhq.datatype.MultipleChoiceType
|
class MultipleChoiceType(BaseDataType):
"""Multiple choice type.
"""
def __init__(self, value):
if isinstance(value, list):
for i in value:
if not isinstance(i, _str_type):
raise TypeError("'value' has to be list of str")
else:
raise TypeError("'value' has to be list of str")
self.value = value
# construct data
self._data = self.value
|
class MultipleChoiceType(BaseDataType):
'''Multiple choice type.
'''
def __init__(self, value):
pass
| 2 | 1 | 11 | 1 | 9 | 1 | 4 | 0.3 | 1 | 2 | 0 | 0 | 1 | 2 | 1 | 2 | 14 | 1 | 10 | 5 | 8 | 3 | 9 | 5 | 7 | 4 | 2 | 3 | 4 |
148,214 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/datatype.py
|
pyknackhq.datatype.DataType
|
class DataType(object):
# basic type
ShortTextType = ShortTextType
ParagraphTextType = ParagraphTextType
YesNoType = YesNoType
SingleChoiceType = SingleChoiceType
MultipleChoiceType = MultipleChoiceType
DateTimeType = DateTimeType
DateTimeFromToType = DateTimeFromToType
NumberType = NumberType
# special type
AddressType = AddressType
NameType = NameType
LinkType = LinkType
EmailType = EmailType
PhoneType = PhoneType
RichTextType = RichTextType
TimerType = TimerType
CurrencyType = CurrencyType
RatingType = RatingType
|
class DataType(object):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0.11 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 20 | 0 | 18 | 18 | 17 | 2 | 18 | 18 | 17 | 0 | 1 | 0 | 0 |
148,215 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/schema.py
|
pyknackhq.schema.Field
|
class Field(object):
"""Field of object class.
Fields are used to define specific attributes of an object.
"""
def __init__(self, **kwargs):
for k, v in kwargs.items():
object.__setattr__(self, k, v)
def __str__(self):
return "Field('%s')" % self.name
def __repr__(self):
return ("Field(key='%s', name='%s', type='%s', "
"required=%s, unique=%s)") % (
self.key, self.name, self.type, self.required, self.unique)
@staticmethod
def from_dict(d):
return Field(**d)
@staticmethod
def from_json(abspath):
return Field.from_dict(load_js(abspath, enable_verbose=False))
|
class Field(object):
'''Field of object class.
Fields are used to define specific attributes of an object.
'''
def __init__(self, **kwargs):
pass
def __str__(self):
pass
def __repr__(self):
pass
@staticmethod
def from_dict(d):
pass
@staticmethod
def from_json(abspath):
pass
| 8 | 1 | 3 | 0 | 3 | 0 | 1 | 0.19 | 1 | 0 | 0 | 0 | 3 | 0 | 5 | 5 | 24 | 5 | 16 | 9 | 8 | 3 | 12 | 7 | 6 | 2 | 1 | 1 | 6 |
148,216 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/datatype.py
|
pyknackhq.datatype.BaseDataType
|
class BaseDataType(object):
"""Base type of all knackhq supported data type.
**中文文档**
所有DataType类的基类。其中 `._data` 属性是其可用于直接insert的Json Dict形式。
"""
def __str__(self):
return json.dumps(self._data,
sort_keys=True, indent=4, separators=("," , ": "))
|
class BaseDataType(object):
'''Base type of all knackhq supported data type.
**中文文档**
所有DataType类的基类。其中 `._data` 属性是其可用于直接insert的Json Dict形式。
'''
def __str__(self):
pass
| 2 | 1 | 3 | 0 | 3 | 0 | 1 | 1 | 1 | 0 | 0 | 17 | 1 | 1 | 1 | 1 | 10 | 2 | 4 | 3 | 2 | 4 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
148,217 |
MacHu-GWU/pyknackhq-project
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_pyknackhq-project/pyknackhq/schema.py
|
pyknackhq.schema.ObjectUnittest
|
class ObjectUnittest(unittest.TestCase):
def test_from_dict(self):
d = load_js(SCHEMA_JSON_PATH, enable_verbose=False)
for object_dict in d["application"]["objects"]:
object_ = Object.from_dict(object_dict)
|
class ObjectUnittest(unittest.TestCase):
def test_from_dict(self):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 2 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 73 | 5 | 0 | 5 | 5 | 3 | 0 | 5 | 5 | 3 | 2 | 2 | 1 | 2 |
148,218 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/datatype.py
|
pyknackhq.datatype.CurrencyType
|
class CurrencyType(BaseDataType):
"""Currency type.
"""
def __init__(self, value):
if not isinstance(value, _number_types):
raise TypeError("'value' has to be int or float")
self.value = value
# construct data
self._data = self.value
|
class CurrencyType(BaseDataType):
'''Currency type.
'''
def __init__(self, value):
pass
| 2 | 1 | 8 | 2 | 5 | 1 | 2 | 0.5 | 1 | 1 | 0 | 0 | 1 | 2 | 1 | 2 | 11 | 2 | 6 | 4 | 4 | 3 | 6 | 4 | 4 | 2 | 2 | 1 | 2 |
148,219 |
MacHu-GWU/pyknackhq-project
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_pyknackhq-project/pyknackhq/schema.py
|
pyknackhq.schema.FieldUnittest
|
class FieldUnittest(unittest.TestCase):
def test_from_dict(self):
d = load_js(SCHEMA_JSON_PATH, enable_verbose=False)
for object_dict in d["application"]["objects"]:
for field_dict in object_dict["fields"]:
field = Field.from_dict(field_dict)
|
class FieldUnittest(unittest.TestCase):
def test_from_dict(self):
pass
| 2 | 0 | 5 | 0 | 5 | 0 | 3 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 73 | 6 | 0 | 6 | 6 | 4 | 0 | 6 | 6 | 4 | 3 | 2 | 2 | 3 |
148,220 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/client.py
|
pyknackhq.client.KnackhqClient
|
class KnackhqClient(object):
"""Knackhq API client class.
:param auth: A :class:`KnackAuth` instance.
:param application: An :class:`~pyknackhq.schema.Application` instance.
If it is not given, the client automatically pull it from knack server.
How to construct a knackhq api client::
from pyknackhq import KnackhqClient, KnackhqAuth
auth = KnackhqAuth(application_id="your app id", api_key="your api key")
client = KnackClient(auth=auth)
"""
def __init__(self, auth, application=None):
self.auth = auth
if isinstance(application, Application):
self.application = application
else: # get the schema json, construct Application instance
res = requests.get(
"https://api.knackhq.com/v1/applications/%s" %
self.auth.application_id)
self.application = Application.from_dict(json.loads(res.text))
def __str__(self):
return "KnackhqClient(application='%s')" % self.application
def __repr__(self):
return str(self)
@property
def all_object_key(self):
return self.application.all_object_key
@property
def all_object_name(self):
return self.application.all_object_name
def get_collection(self, key, using_name=True):
"""Get :class:`Collection` instance.
:param key: object_key or object_name
:param using_name: True if getting object by object name
"""
object_ = self.application.get_object(key, using_name=using_name)
collection = Collection.from_dict(object_.__dict__)
for http_cmd in ["get", "post", "put", "delete"]:
collection.__setattr__(http_cmd, self.auth.__getattribute__(http_cmd))
return collection
def export_schema(self, abspath):
"""Export application detailed information to a nicely formatted json
file.
"""
self.application.to_json(abspath)
|
class KnackhqClient(object):
'''Knackhq API client class.
:param auth: A :class:`KnackAuth` instance.
:param application: An :class:`~pyknackhq.schema.Application` instance.
If it is not given, the client automatically pull it from knack server.
How to construct a knackhq api client::
from pyknackhq import KnackhqClient, KnackhqAuth
auth = KnackhqAuth(application_id="your app id", api_key="your api key")
client = KnackClient(auth=auth)
'''
def __init__(self, auth, application=None):
pass
def __str__(self):
pass
def __repr__(self):
pass
@property
def all_object_key(self):
pass
@property
def all_object_name(self):
pass
def get_collection(self, key, using_name=True):
'''Get :class:`Collection` instance.
:param key: object_key or object_name
:param using_name: True if getting object by object name
'''
pass
def export_schema(self, abspath):
'''Export application detailed information to a nicely formatted json
file.
'''
pass
| 10 | 3 | 5 | 0 | 4 | 1 | 1 | 0.61 | 1 | 3 | 2 | 0 | 7 | 2 | 7 | 7 | 55 | 11 | 28 | 16 | 18 | 17 | 23 | 14 | 15 | 2 | 1 | 1 | 9 |
148,221 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/client.py
|
pyknackhq.client.KnackhqAuth
|
class KnackhqAuth(object):
"""Knackhq API authentication class.
:param application_id: str type, Application ID
:param api_key: str type, API Key
To get your Application ID and API Key, read this tutorial:
http://helpdesk.knackhq.com/support/solutions/articles/5000444173-working-with-the-api#key
"""
def __init__(self, application_id, api_key):
self.application_id = application_id
self.api_key = api_key
self.headers = {
"X-Knack-Application-Id": self.application_id,
"X-Knack-REST-API-Key": self.api_key,
"Content-Type": "application/json",
}
@staticmethod
def from_dict(d):
return KnackhqAuth(**d)
@staticmethod
def from_json(abspath):
return KnackhqAuth.from_dict(load_js(abspath, enable_verbose=False))
def get(self, url, params=dict()):
"""Http get method wrapper, to support search.
"""
try:
res = requests.get(url, headers=self.headers, params=params)
return json.loads(res.text)
except Exception as e:
print(e)
return "error"
def post(self, url, data):
"""Http post method wrapper, to support insert.
"""
try:
res = requests.post(
url, headers=self.headers, data=json.dumps(data))
return json.loads(res.text)
except Exception as e:
print(e)
return "error"
def put(self, url, data):
"""Http put method wrapper, to support update.
"""
try:
res = requests.put(
url, headers=self.headers, data=json.dumps(data))
return json.loads(res.text)
except Exception as e:
print(e)
return "error"
def delete(self, url):
"""Http delete method wrapper, to support delete.
"""
try:
res = requests.delete(url, headers=self.headers)
return json.loads(res.text)
except Exception as e:
print(e)
return "error"
|
class KnackhqAuth(object):
'''Knackhq API authentication class.
:param application_id: str type, Application ID
:param api_key: str type, API Key
To get your Application ID and API Key, read this tutorial:
http://helpdesk.knackhq.com/support/solutions/articles/5000444173-working-with-the-api#key
'''
def __init__(self, application_id, api_key):
pass
@staticmethod
def from_dict(d):
pass
@staticmethod
def from_json(abspath):
pass
def get(self, url, params=dict()):
'''Http get method wrapper, to support search.
'''
pass
def post(self, url, data):
'''Http post method wrapper, to support insert.
'''
pass
def put(self, url, data):
'''Http put method wrapper, to support update.
'''
pass
def delete(self, url):
'''Http delete method wrapper, to support delete.
'''
pass
| 10 | 5 | 7 | 0 | 6 | 1 | 2 | 0.31 | 1 | 2 | 0 | 0 | 5 | 3 | 7 | 7 | 67 | 8 | 45 | 21 | 35 | 14 | 37 | 15 | 29 | 2 | 1 | 1 | 11 |
148,222 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/datatype.py
|
pyknackhq.datatype.AddressType
|
class AddressType(BaseDataType):
"""Address type.
"""
def __init__(self, street=None, street2=None,
city=None, state=None, zipcode=None, country=None):
self.street = street
self.street2 = street2
self.city = city
self.state = state
self.zipcode = zipcode
self.country = country
@property
def _data(self):
attrs = ["street", "street2",
"city", "state", "zipcode", "country"]
d = dict()
for attr in attrs:
value = self.__getattribute__(attr)
if value:
d[attr] = value
return d
|
class AddressType(BaseDataType):
'''Address type.
'''
def __init__(self, street=None, street2=None,
city=None, state=None, zipcode=None, country=None):
pass
@property
def _data(self):
pass
| 4 | 1 | 9 | 0 | 9 | 0 | 2 | 0.11 | 1 | 1 | 0 | 0 | 2 | 6 | 2 | 3 | 22 | 1 | 19 | 15 | 14 | 2 | 16 | 13 | 13 | 3 | 2 | 2 | 4 |
148,223 |
MacHu-GWU/pyknackhq-project
|
MacHu-GWU_pyknackhq-project/pyknackhq/client.py
|
pyknackhq.client.Collection
|
class Collection(Object):
"""A collection is the equivalent of an RDBMS table, collection of MongoDB
and object of Knackhq. Most of CRUD method can be executed using this.
- :meth:`~Collection.insert_one`
- :meth:`~Collection.insert`
- :meth:`~Collection.find_one`
- :meth:`~Collection.find`
- :meth:`~Collection.update_one`
- :meth:`~Collection.delete_one`
- :meth:`~Collection.delete_all`
"""
def __str__(self):
return "Collection('%s')" % self.name
def __repr__(self):
return "Collection(key='%s', name='%s')" % (self.key, self.name)
@staticmethod
def from_dict(d):
return Collection(**d)
@property
def get_url(self):
return "https://api.knackhq.com/v1/objects/%s/records" % self.key
@property
def post_url(self):
return "https://api.knackhq.com/v1/objects/%s/records" % self.key
def convert_keys(self, pydict):
"""Convert field_name to field_key.
{"field_name": value} => {"field_key": value}
"""
new_dict = dict()
for key, value in pydict.items():
new_dict[self.get_field_key(key)] = value
return new_dict
def get_html_values(self, pydict, recovery_name=True):
"""Convert naive get response data to human readable field name format.
using html data format.
"""
new_dict = {"id": pydict["id"]}
for field in self:
if field.key in pydict:
if recovery_name:
new_dict[field.name] = pydict[field.key]
else:
new_dict[field.key] = pydict[field.key]
return new_dict
def get_raw_values(self, pydict, recovery_name=True):
"""Convert naive get response data to human readable field name format.
using raw data format.
"""
new_dict = {"id": pydict["id"]}
for field in self:
raw_key = "%s_raw" % field.key
if raw_key in pydict:
if recovery_name:
new_dict[field.name] = pydict[raw_key]
else:
new_dict[field.key] = pydict[raw_key]
return new_dict
def convert_values(self, pydict):
"""Convert knackhq data type instance to json friendly data.
"""
new_dict = dict()
for key, value in pydict.items():
try: # is it's BaseDataType Instance
new_dict[key] = value._data
except AttributeError:
new_dict[key] = value
return new_dict
#-------------------------------------------------------------------------#
# CRUD method #
#-------------------------------------------------------------------------#
def insert_one(self, data, using_name=True):
"""Insert one record.
Ref: http://helpdesk.knackhq.com/support/solutions/articles/5000446111-api-reference-root-access#create
For more information of the raw structure of all data type, read this:
http://helpdesk.knackhq.com/support/solutions/articles/5000446405-field-types
:param data: dict type data
:param using_name: if you are using field_name in data,
please set using_name = True (it's the default), otherwise, False
**中文文档**
插入一条记录
"""
data = self.convert_values(data)
if using_name:
data = self.convert_keys(data)
res = self.post(self.post_url, data)
return res
def insert(self, data, using_name=True):
"""Insert one or many records.
:param data: dict type data or list of dict
:param using_name: if you are using field name in data,
please set using_name = True (it's the default), otherwise, False
**中文文档**
插入多条记录
"""
if isinstance(data, list): # if iterable, insert one by one
for d in data:
self.insert_one(d, using_name=using_name)
else: # not iterable, execute insert_one
self.insert_one(data, using_name=using_name)
def find_one(self, id_, raw=True, recovery_name=True):
"""Find one record.
Ref: http://helpdesk.knackhq.com/support/solutions/articles/5000446111-api-reference-root-access#retrieve
:param id_: record id_
:param using_name: if you are using field name in filter and sort_field,
please set using_name = True (it's the default), otherwise, False
:param raw: Default True, set True if you want the data in raw format.
Otherwise, html format
:param recovery_name: Default True, set True if you want field name
instead of field key
**中文文档**
返回一条记录
"""
url = "https://api.knackhq.com/v1/objects/%s/records/%s" % (
self.key, id_)
res = self.get(url)
if raw:
try:
res = self.get_raw_values(res, recovery_name=recovery_name)
except:
pass
else:
try:
res = self.get_html_values(res, recovery_name=recovery_name)
except:
pass
return res
def find(self, filter=list(),
sort_field=None, sort_order=None,
page=None, rows_per_page=None,
using_name=True, data_only=True, raw=True, recovery_name=True):
"""Execute a find query.
Ref: http://helpdesk.knackhq.com/support/solutions/articles/5000446111-api-reference-root-access#retrieve
:param filter: list of criterions. For more information:
http://helpdesk.knackhq.com/support/solutions/articles/5000447623-api-reference-filters-search
:param sort_field: field_name or field_id, taking field_name by default.
if using field_id, please set using_name = False.
:param sort_order: -1 or 1, 1 means ascending, -1 means descending
:param page and rows_per_page: skip first #page * #rows_per_page,
returns #rows_per_page of records. For more information:
http://helpdesk.knackhq.com/support/solutions/articles/5000444173-working-with-the-api#pagination
:param using_name: if you are using field_name in filter and sort_field,
please set using_name = True (it's the default), otherwise, False
:param data_only: set True you only need the data or the full api
response
:param raw: Default True, set True if you want the data in raw format.
Otherwise, html format
:param recovery_name: Default True, set True if you want field name
instead of field key
**中文文档**
返回多条记录
"""
if using_name:
for criterion in filter:
criterion["field"] = self.get_field_key(criterion["field"])
if sort_field:
sort_field = self.get_field_key(sort_field)
if sort_order is None:
pass
elif sort_order == 1:
sort_order = "asc"
elif sort_order == -1:
sort_order = "desc"
else:
raise ValueError
params = dict()
if len(filter) >= 1:
params["filters"] = json.dumps(filter)
if sort_field:
params["sort_field"] = sort_field
params["sort_order"] = sort_order
if (page is not None) \
and (rows_per_page is not None) \
and isinstance(page, int) \
and isinstance(rows_per_page, int) \
and (page >= 1) \
and (rows_per_page >= 1):
params["page"] = page
params["rows_per_page"] = rows_per_page
res = self.get(self.get_url, params)
# handle data_only and recovery
if data_only:
try:
res = res["records"]
if raw:
res = [self.get_raw_values(data, recovery_name) for data in res]
else:
res = [self.get_html_values(data, recovery_name) for data in res]
except KeyError:
pass
else:
if raw:
try:
res["records"] = [
self.get_raw_values(data, recovery_name) for data in res["records"]]
except KeyError:
pass
else:
try:
res["records"] = [
self.get_html_values(data, recovery_name) for data in res["records"]]
except KeyError:
pass
return res
def update_one(self, id_, data, using_name=True):
"""Update one record. Any fields you don't specify will remain unchanged.
Ref: http://helpdesk.knackhq.com/support/solutions/articles/5000446111-api-reference-root-access#update
:param id_: record id_
:param data: the new data fields and values
:param using_name: if you are using field name in data,
please set using_name = True (it's the default), otherwise, False
**中文文档**
对一条记录进行更新
"""
data = self.convert_values(data)
if using_name:
data = self.convert_keys(data)
url = "https://api.knackhq.com/v1/objects/%s/records/%s" % (
self.key, id_)
res = self.put(url, data)
return res
def delete_one(self, id_):
"""Delete one record.
Ref: http://helpdesk.knackhq.com/support/solutions/articles/5000446111-api-reference-root-access#delete
:param id_: record id_
**中文文档**
删除一条记录
"""
url = "https://api.knackhq.com/v1/objects/%s/records/%s" % (
self.key, id_)
res = self.delete(url)
return res
def delete_all(self):
"""Delete all record in the table/collection of this object.
**中文文档**
删除表中的所有记录
"""
for record in self.find(using_name=False, data_only=True):
res = self.delete_one(record["id"])
|
class Collection(Object):
'''A collection is the equivalent of an RDBMS table, collection of MongoDB
and object of Knackhq. Most of CRUD method can be executed using this.
- :meth:`~Collection.insert_one`
- :meth:`~Collection.insert`
- :meth:`~Collection.find_one`
- :meth:`~Collection.find`
- :meth:`~Collection.update_one`
- :meth:`~Collection.delete_one`
- :meth:`~Collection.delete_all`
'''
def __str__(self):
pass
def __repr__(self):
pass
@staticmethod
def from_dict(d):
pass
@property
def get_url(self):
pass
@property
def post_url(self):
pass
def convert_keys(self, pydict):
'''Convert field_name to field_key.
{"field_name": value} => {"field_key": value}
'''
pass
def get_html_values(self, pydict, recovery_name=True):
'''Convert naive get response data to human readable field name format.
using html data format.
'''
pass
def get_raw_values(self, pydict, recovery_name=True):
'''Convert naive get response data to human readable field name format.
using raw data format.
'''
pass
def convert_values(self, pydict):
'''Convert knackhq data type instance to json friendly data.
'''
pass
def insert_one(self, data, using_name=True):
'''Insert one record.
Ref: http://helpdesk.knackhq.com/support/solutions/articles/5000446111-api-reference-root-access#create
For more information of the raw structure of all data type, read this:
http://helpdesk.knackhq.com/support/solutions/articles/5000446405-field-types
:param data: dict type data
:param using_name: if you are using field_name in data,
please set using_name = True (it's the default), otherwise, False
**中文文档**
插入一条记录
'''
pass
def insert_one(self, data, using_name=True):
'''Insert one or many records.
:param data: dict type data or list of dict
:param using_name: if you are using field name in data,
please set using_name = True (it's the default), otherwise, False
**中文文档**
插入多条记录
'''
pass
def find_one(self, id_, raw=True, recovery_name=True):
'''Find one record.
Ref: http://helpdesk.knackhq.com/support/solutions/articles/5000446111-api-reference-root-access#retrieve
:param id_: record id_
:param using_name: if you are using field name in filter and sort_field,
please set using_name = True (it's the default), otherwise, False
:param raw: Default True, set True if you want the data in raw format.
Otherwise, html format
:param recovery_name: Default True, set True if you want field name
instead of field key
**中文文档**
返回一条记录
'''
pass
def find_one(self, id_, raw=True, recovery_name=True):
'''Execute a find query.
Ref: http://helpdesk.knackhq.com/support/solutions/articles/5000446111-api-reference-root-access#retrieve
:param filter: list of criterions. For more information:
http://helpdesk.knackhq.com/support/solutions/articles/5000447623-api-reference-filters-search
:param sort_field: field_name or field_id, taking field_name by default.
if using field_id, please set using_name = False.
:param sort_order: -1 or 1, 1 means ascending, -1 means descending
:param page and rows_per_page: skip first #page * #rows_per_page,
returns #rows_per_page of records. For more information:
http://helpdesk.knackhq.com/support/solutions/articles/5000444173-working-with-the-api#pagination
:param using_name: if you are using field_name in filter and sort_field,
please set using_name = True (it's the default), otherwise, False
:param data_only: set True you only need the data or the full api
response
:param raw: Default True, set True if you want the data in raw format.
Otherwise, html format
:param recovery_name: Default True, set True if you want field name
instead of field key
**中文文档**
返回多条记录
'''
pass
def update_one(self, id_, data, using_name=True):
'''Update one record. Any fields you don't specify will remain unchanged.
Ref: http://helpdesk.knackhq.com/support/solutions/articles/5000446111-api-reference-root-access#update
:param id_: record id_
:param data: the new data fields and values
:param using_name: if you are using field name in data,
please set using_name = True (it's the default), otherwise, False
**中文文档**
对一条记录进行更新
'''
pass
def delete_one(self, id_):
'''Delete one record.
Ref: http://helpdesk.knackhq.com/support/solutions/articles/5000446111-api-reference-root-access#delete
:param id_: record id_
**中文文档**
删除一条记录
'''
pass
def delete_all(self):
'''Delete all record in the table/collection of this object.
**中文文档**
删除表中的所有记录
'''
pass
| 20 | 12 | 16 | 2 | 9 | 5 | 3 | 0.67 | 1 | 6 | 0 | 0 | 15 | 0 | 16 | 26 | 293 | 55 | 144 | 45 | 121 | 97 | 118 | 39 | 101 | 16 | 2 | 3 | 48 |
148,224 |
MacHu-GWU/pymongo_mate-project
|
MacHu-GWU_pymongo_mate-project/pymongo_mate/query_builder.py
|
pymongo_mate.query_builder.Text
|
class Text(object):
"""Search text by:
- startswith
- endswith
- contain sub string
- full text serach
"""
@staticmethod
def startswith(text, ignore_case=True):
"""
Test if a string-field start with ``text``.
Example::
filters = {"path": Text.startswith(r"C:\\")}
"""
if ignore_case:
compiled = re.compile(
"^%s" % text.replace("\\", "\\\\"), re.IGNORECASE)
else: # pragma: no cover
compiled = re.compile("^%s" % text.replace("\\", "\\\\"))
return {"$regex": compiled}
@staticmethod
def endswith(text, ignore_case=True):
"""
Test if a string-field end with ``text``.
Example::
filters = {"path": Text.endswith(".exe")}
"""
if ignore_case:
compiled = re.compile(
"%s$" % text.replace("\\", "\\\\"), re.IGNORECASE)
else: # pragma: no cover
compiled = re.compile("%s$" % text.replace("\\", "\\\\"))
return {"$regex": compiled}
@staticmethod
def contains(text, ignore_case=True):
"""
Test if a string-field has substring of ``text``.
Example::
filters = {"path": Text.contains("pymongo_mate")}
"""
if ignore_case:
compiled = re.compile(
"%s" % text.replace("\\", "\\\\"), re.IGNORECASE)
else: # pragma: no cover
compiled = re.compile("%s" % text.replace("\\", "\\\\"))
return {"$regex": compiled}
@staticmethod
def fulltext(search, lang=Lang.English, ignore_case=True):
"""Full text search.
Example::
filters = Text.fulltext("python pymongo_mate")
.. note::
This field doesn't need to specify field.
"""
return {
"$text": {
"$search": search,
"$language": lang,
"$caseSensitive": not ignore_case,
"$diacriticSensitive": False,
}
}
|
class Text(object):
'''Search text by:
- startswith
- endswith
- contain sub string
- full text serach
'''
@staticmethod
def startswith(text, ignore_case=True):
'''
Test if a string-field start with ``text``.
Example::
filters = {"path": Text.startswith(r"C:\")}
'''
pass
@staticmethod
def endswith(text, ignore_case=True):
'''
Test if a string-field end with ``text``.
Example::
filters = {"path": Text.endswith(".exe")}
'''
pass
@staticmethod
def contains(text, ignore_case=True):
'''
Test if a string-field has substring of ``text``.
Example::
filters = {"path": Text.contains("pymongo_mate")}
'''
pass
@staticmethod
def fulltext(search, lang=Lang.English, ignore_case=True):
'''Full text search.
Example::
filters = Text.fulltext("python pymongo_mate")
.. note::
This field doesn't need to specify field.
'''
pass
| 9 | 5 | 16 | 3 | 8 | 6 | 2 | 0.86 | 1 | 1 | 1 | 0 | 0 | 0 | 4 | 4 | 79 | 17 | 35 | 12 | 26 | 30 | 18 | 8 | 13 | 2 | 1 | 1 | 7 |
148,225 |
MacHu-GWU/pymongo_mate-project
|
MacHu-GWU_pymongo_mate-project/pymongo_mate/query_builder.py
|
pymongo_mate.query_builder.PipeLine
|
class PipeLine(object):
@staticmethod
def random_sample(filters=None, n=5):
pipeline = list()
if filters is not None:
pipeline.append({"$match": filters})
pipeline.append({"$sample": {"size": n}})
return pipeline
|
class PipeLine(object):
@staticmethod
def random_sample(filters=None, n=5):
pass
| 3 | 0 | 6 | 0 | 6 | 0 | 2 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 1 | 1 | 8 | 0 | 8 | 4 | 5 | 0 | 7 | 3 | 5 | 2 | 1 | 1 | 2 |
148,226 |
MacHu-GWU/pymongo_mate-project
|
MacHu-GWU_pymongo_mate-project/tests/test_query_builder.py
|
test_query_builder.TestPipeLine
|
class TestPipeLine(object):
def test_random_sample(self):
col.remove({})
col.insert([{"_id": i} for i in range(150)])
filters = {"_id": {"$lt": 120}}
pipeline = PipeLine.random_sample(filters, 3)
result = list(col.aggregate(pipeline))
assert len(result) == 3
for doc in result:
assert doc["_id"] < 120
|
class TestPipeLine(object):
def test_random_sample(self):
pass
| 2 | 0 | 9 | 0 | 9 | 0 | 2 | 0 | 1 | 3 | 1 | 0 | 1 | 0 | 1 | 1 | 10 | 0 | 10 | 6 | 8 | 0 | 10 | 6 | 8 | 2 | 1 | 1 | 2 |
148,227 |
MacHu-GWU/pymongo_mate-project
|
MacHu-GWU_pymongo_mate-project/pymongo_mate/query_builder.py
|
pymongo_mate.query_builder.Logic
|
class Logic(object):
@staticmethod
def and_(*filters):
return {"$and": list(filters)}
@staticmethod
def or_(*filters):
return {"$or": list(filters)}
@staticmethod
def nor(*filters):
return {"$nor": list(filters)}
@staticmethod
def not_(expression):
return {"$not": expression}
|
class Logic(object):
@staticmethod
def and_(*filters):
pass
@staticmethod
def or_(*filters):
pass
@staticmethod
def nor(*filters):
pass
@staticmethod
def not_(expression):
pass
| 9 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 4 | 4 | 16 | 3 | 13 | 9 | 4 | 0 | 9 | 5 | 4 | 1 | 1 | 0 | 4 |
148,228 |
MacHu-GWU/pymongo_mate-project
|
MacHu-GWU_pymongo_mate-project/pymongo_mate/query_builder.py
|
pymongo_mate.query_builder.Lang
|
class Lang(object):
"""
Language code Collection.
"""
English = "en"
French = "fr"
German = "de"
Italian = "it"
Portuguese = "pt"
Russian = "ru"
Spanish = "es"
SimplifiedChineses = "zhs"
TraditionalChineses = "zht"
|
class Lang(object):
'''
Language code Collection.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.3 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 13 | 0 | 10 | 10 | 9 | 3 | 10 | 10 | 9 | 0 | 1 | 0 | 0 |
148,229 |
MacHu-GWU/pymongo_mate-project
|
MacHu-GWU_pymongo_mate-project/pymongo_mate/query_builder.py
|
pymongo_mate.query_builder.Geo2DSphere
|
class Geo2DSphere(object):
"""Geosphere query builder.
"""
@staticmethod
def near(lat, lng, max_dist=None, unit_miles=False):
"""Find document near a point.
For example:: find all document with in 25 miles radius from 32.0, -73.0.
"""
filters = {
"$nearSphere": {
"$geometry": {
"type": "Point",
"coordinates": [lng, lat],
}
}
}
if max_dist:
if unit_miles: # pragma: no cover
max_dist = max_dist / 1609.344
filters["$nearSphere"]["$maxDistance"] = max_dist
return filters
|
class Geo2DSphere(object):
'''Geosphere query builder.
'''
@staticmethod
def near(lat, lng, max_dist=None, unit_miles=False):
'''Find document near a point.
For example:: find all document with in 25 miles radius from 32.0, -73.0.
'''
pass
| 3 | 2 | 18 | 1 | 14 | 4 | 3 | 0.38 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 22 | 1 | 16 | 4 | 13 | 6 | 8 | 3 | 6 | 3 | 1 | 2 | 3 |
148,230 |
MacHu-GWU/pymongo_mate-project
|
MacHu-GWU_pymongo_mate-project/pymongo_mate/query_builder.py
|
pymongo_mate.query_builder.Comparison
|
class Comparison(object):
"""``==``, ``!=``, ``>``, ``>=``, ``<``, ``<=``.
"""
@staticmethod
def less_than_equal(value):
"""
``<=``
Example::
filters = {field: Comparison.less_than_equal(10)}
"""
return {"$lte": value}
@staticmethod
def less_than(value):
"""
``<``
Example::
filters = {field: Comparison.less_than(10)}
"""
return {"$lt": value}
@staticmethod
def greater_than_equal(value):
"""
``>=``
Example::
filters = {field: Comparison.greater_than_equal(10)}
"""
return {"$gte": value}
@staticmethod
def greater_than(value):
"""
``>``
Example::
filters = {field: Comparison.greater_than(10)}
"""
return {"$gt": value}
@staticmethod
def equal_to(value):
"""
``==``
Example::
filters = {field: Comparison.equal_to(10)}
"""
return {"$eq": value}
@staticmethod
def not_equal_to(value):
"""
``!=``
Example::
filters = {field: Comparison.not_equal_to(10)}
"""
return {"$ne": value}
|
class Comparison(object):
'''``==``, ``!=``, ``>``, ``>=``, ``<``, ``<=``.
'''
@staticmethod
def less_than_equal(value):
'''
``<=``
Example::
filters = {field: Comparison.less_than_equal(10)}
'''
pass
@staticmethod
def less_than_equal(value):
'''
``<``
Example::
filters = {field: Comparison.less_than(10)}
'''
pass
@staticmethod
def greater_than_equal(value):
'''
``>=``
Example::
filters = {field: Comparison.greater_than_equal(10)}
'''
pass
@staticmethod
def greater_than_equal(value):
'''
``>``
Example::
filters = {field: Comparison.greater_than(10)}
'''
pass
@staticmethod
def equal_to(value):
'''
``==``
Example::
filters = {field: Comparison.equal_to(10)}
'''
pass
@staticmethod
def not_equal_to(value):
'''
``!=``
Example::
filters = {field: Comparison.not_equal_to(10)}
'''
pass
| 13 | 7 | 9 | 2 | 2 | 5 | 1 | 1.68 | 1 | 0 | 0 | 0 | 0 | 0 | 6 | 6 | 68 | 17 | 19 | 13 | 6 | 32 | 13 | 7 | 6 | 1 | 1 | 0 | 6 |
148,231 |
MacHu-GWU/pymongo_mate-project
|
MacHu-GWU_pymongo_mate-project/tests/test_query_builder.py
|
test_query_builder.TestLogic
|
class TestLogic(object):
def test_and(self):
filters = Logic.and_(
{"value": Comparison.greater_than(3)},
{"value": Comparison.less_than(4)},
)
assert col.find(filters).count() == 1
filters = {
"data": Array.element_match(
Logic.and_(
{"v": Comparison.greater_than(1.5)},
{"v": Comparison.less_than(2.5)},
)
)
}
assert col.find(filters).count() == 1
def test_or(self):
filters = Logic.or_(
{"value": Comparison.greater_than(3)},
{"value": Comparison.less_than(2)},
)
assert col.find(filters).count() == 1
def test_nor(self):
filters = Logic.nor(
{"value": Comparison.greater_than(4)},
{"value": Comparison.less_than(3)},
)
assert col.find(filters).count() == 1
def test_not(self):
filters = {"value": Logic.not_(Comparison.equal_to(100))}
assert col.find(filters).count() == 1
|
class TestLogic(object):
def test_and(self):
pass
def test_or(self):
pass
def test_nor(self):
pass
def test_not(self):
pass
| 5 | 0 | 8 | 0 | 8 | 0 | 1 | 0 | 1 | 3 | 3 | 0 | 4 | 0 | 4 | 4 | 35 | 4 | 31 | 9 | 26 | 0 | 15 | 9 | 10 | 1 | 1 | 0 | 4 |
148,232 |
MacHu-GWU/pymongo_mate-project
|
MacHu-GWU_pymongo_mate-project/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py
|
pymongo_mate.pkg.pandas_mate.pkg.rolex.Rolex
|
class Rolex(object):
"""Main class. A time related utility class.
Abbreviations:
- dt -> datetime object
- d -> date object
- ts -> timestamp
- s -> string
- i -> int/item
**中文文档**
本类提供了非常多与时间, 日期相关的函数。其中
"时间包装器"提供了对时间, 日期相关的许多计算操作的函数。能智能的从各种其他
格式的时间中解析出Python datetime.datetime/datetime.date 对象。更多功能请
参考API文档。
"""
DateTemplates = DateTemplates
DatetimeTemplates = DatetimeTemplates
default_date_template = DatetimeTemplates[0]
default_datetime_template = DatetimeTemplates[0]
#--- Parse datetime ---
def str2date(self, datestr):
"""Parse date from string. If no template matches this string,
raise Error. Please go
https://github.com/MacHu-GWU/rolex-project/issues
submit your date string. I 'll update templates asap.
This method is faster than :meth:`dateutil.parser.parse`.
:param datestr: a string represent a date
:type datestr: str
:return: a date object
**中文文档**
从string解析date。首先尝试默认模板, 如果失败了, 则尝试所有的模板。
一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的
字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。
该方法要快过 :meth:`dateutil.parser.parse` 方法。
"""
if datestr is None:
raise ValueError(
"Parser must be a string or character stream, not NoneType")
# try default date template
try:
return datetime.strptime(
datestr, self.default_date_template).date()
except:
pass
# try every datetime templates
for template in DateTemplates:
try:
dt = datetime.strptime(datestr, template)
self.default_date_template = template
return dt.date()
except:
pass
# raise error
raise Exception("Unable to parse date from: %r" % datestr)
def _str2datetime(self, datetimestr):
"""Parse datetime from string. If no template matches this string,
raise Error. Please go
https://github.com/MacHu-GWU/rolex-project/issues
submit your datetime string. I 'll update templates asap.
This method is faster than :meth:`dateutil.parser.parse`.
:param datetimestr: a string represent a datetime
:type datetimestr: str
:return: a datetime object
**中文文档**
从string解析datetime。首先尝试默认模板, 如果失败了, 则尝试所有的模板。
一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的
字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。
该方法要快过 :meth:`dateutil.parser.parse` 方法。
"""
if datetimestr is None:
raise ValueError(
"Parser must be a string or character stream, not NoneType")
# try default datetime template
try:
return datetime.strptime(
datetimestr, self.default_datetime_template)
except:
pass
# try every datetime templates
for template in DatetimeTemplates:
try:
dt = datetime.strptime(datetimestr, template)
self.default_datetime_template = template
return dt
except:
pass
# raise error
dt = parser.parse(datetimestr)
self.str2datetime = parser.parse
return dt
str2datetime = _str2datetime
def parse_date(self, value):
"""A lazy method to parse anything to date.
If input data type is:
- string: parse date from it
- integer: use from ordinal
- datetime: use date part
- date: just return it
"""
if value is None:
raise Exception("Unable to parse date from %r" % value)
elif isinstance(value, string_types):
return self.str2date(value)
elif isinstance(value, int):
return date.fromordinal(value)
elif isinstance(value, datetime):
return value.date()
elif isinstance(value, date):
return value
else:
raise Exception("Unable to parse date from %r" % value)
def parse_datetime(self, value):
"""A lazy method to parse anything to datetime.
If input data type is:
- string: parse datetime from it
- integer: use from ordinal
- date: use date part and set hour, minute, second to zero
- datetime: just return it
"""
if value is None:
raise Exception("Unable to parse datetime from %r" % value)
elif isinstance(value, string_types):
return self.str2datetime(value)
elif isinstance(value, integer_types):
return self.from_utctimestamp(value)
elif isinstance(value, float):
return self.from_utctimestamp(value)
elif isinstance(value, datetime):
return value
elif isinstance(value, date):
return datetime(value.year, value.month, value.day)
else:
raise Exception("Unable to parse datetime from %r" % value)
#--- Method extension toordinary, timestamp ---
def to_ordinal(self, date_object):
"""Calculate number of days from 0000-00-00.
"""
return date_object.toordinal()
def from_ordinal(self, days):
"""Create a date object that number ``days`` of days after 0000-00-00.
"""
return date.fromordinal(days)
def to_utctimestamp(self, dt):
"""Calculate number of seconds from UTC 1970-01-01 00:00:00.
When:
- dt doesn't have tzinfo: assume it's a utc time
- dt has tzinfo: use tzinfo
WARNING, if your datetime object doens't have ``tzinfo``, make sure
it's a UTC time, but **NOT a LOCAL TIME**.
**中文文档**
计算时间戳
若:
- 不带tzinfo: 则默认为是UTC time
- 带tzinfo: 使用tzinfo
"""
if dt.tzinfo is None:
dt = dt.replace(tzinfo=utc)
delta = dt - datetime(1970, 1, 1, tzinfo=utc)
return delta.total_seconds()
def from_utctimestamp(self, timestamp):
"""Create a **UTC datetime** object that number of seconds after
UTC 1970-01-01 00:00:00. If you want local time, use
:meth:`Rolex.from_timestamp`
Because python doesn't support negative timestamp to datetime
so we have to implement my own method.
**中文文档**
返回一个在UTC 1970-01-01 00:00:00 之后 #timestamp 秒后的时间。默认为
UTC时间。即返回的datetime不带tzinfo
"""
if timestamp >= 0:
return datetime.utcfromtimestamp(timestamp)
else:
return datetime(1970, 1, 1) + timedelta(seconds=timestamp)
def to_timestamp(self, dt):
"""Calculate number of seconds from UTC 1970-01-01 00:00:00.
When:
- dt doesn't have tzinfo: assume it's a local time on your computer
- dt has tzinfo: use tzinfo
**中文文档**
计算时间戳
若:
- 不带tzinfo: 则默认为是本机的local time
- 带tzinfo: 使用tzinfo
"""
if PY3:
return dt.timestamp()
else:
raise SystemError("Python2 doesn't support this method!")
def from_timestamp(self, timestamp):
"""Create a **local datetime** object that number of seconds after
UTC 1970-01-01 00:00:00. If you want utc time, use
:meth:`Rolex.from_utctimestamp`
**中文文档**
根据时间戳, 计算时间, 返回的是你的本机local time的时间。
"""
if timestamp >= 0:
return datetime.fromtimestamp(timestamp)
else:
return datetime.fromtimestamp(0) - timedelta(seconds=-timestamp)
#--- Time series ---
def _freq_parser(self, freq):
"""Parse timedelta.
Valid keywords "days", "day", "d", "hours", "hour", "h",
"minutes", "minute", "min", "m", "seconds", "second", "sec", "s",
"weeks", "week", "w",
"""
freq = freq.lower().strip()
valid_keywords = [
"days", "day", "d",
"hours", "hour", "h",
"minutes", "minute", "min", "m",
"seconds", "second", "sec", "s",
"weeks", "week", "w",
]
error_message = "'%s' is invalid, use one of %s" % (
freq, valid_keywords)
try:
# day
for surfix in ["days", "day", "d"]:
if freq.endswith(surfix):
freq = freq.replace(surfix, "")
return timedelta(days=int(freq))
# hour
for surfix in ["hours", "hour", "h"]:
if freq.endswith(surfix):
freq = freq.replace(surfix, "")
return timedelta(hours=int(freq))
# minute
for surfix in ["minutes", "minute", "min", "m"]:
if freq.endswith(surfix):
freq = freq.replace(surfix, "")
return timedelta(minutes=int(freq))
# second
for surfix in ["seconds", "second", "sec", "s"]:
if freq.endswith(surfix):
freq = freq.replace(surfix, "")
return timedelta(seconds=int(freq))
# week
for surfix in ["weeks", "week", "w"]:
if freq.endswith(surfix):
freq = freq.replace(surfix, "")
return timedelta(days=int(freq) * 7)
except:
pass
raise ValueError(error_message)
def time_series(self, start=None, end=None, periods=None,
freq="1day", normalize=False, return_date=False):
"""A pure Python implementation of pandas.date_range().
Given 2 of start, end, periods and freq, generate a series of
datetime object.
:param start: Left bound for generating dates
:type start: str or datetime.datetime (default None)
:param end: Right bound for generating dates
:type end: str or datetime.datetime (default None)
:param periods: Number of date points. If None, must specify start
and end
:type periods: integer (default None)
:param freq: string, default '1day' (calendar daily)
Available mode are day, hour, min, sec
Frequency strings can have multiples. e.g.
'7day', '6hour', '5min', '4sec', '3week`
:type freq: string (default '1day' calendar daily)
:param normalize: Trigger that normalize start/end dates to midnight
:type normalize: boolean (default False)
:return: A list of datetime.datetime object. An evenly sampled time
series.
Usage::
>>> from __future__ import print_function
>>> for dt in rolex.time_series("2014-1-1", "2014-1-7"):
... print(dt)
2014-01-01 00:00:00
2014-01-02 00:00:00
2014-01-03 00:00:00
2014-01-04 00:00:00
2014-01-05 00:00:00
2014-01-06 00:00:00
2014-01-07 00:00:00
**中文文档**
生成等间隔的时间序列。
需要给出, "起始", "结束", "数量" 中的任意两个。以及指定"频率"。以此唯一
确定一个等间隔时间序列。"频率"项所支持的命令字符有"7day", "6hour",
"5min", "4sec", "3week" (可以改变数字).
"""
def normalize_datetime_to_midnight(dt):
"""Normalize a datetime %Y-%m-%d %H:%M:%S to %Y-%m-%d 00:00:00.
"""
return datetime(dt.year, dt.month, dt.day)
def not_normalize(dt):
"""Do not normalize.
"""
return dt
series = list()
# if two of start, end, or periods exist
if (bool(start) + bool(end) + bool(periods)) != 2:
raise ValueError(
"Must specify two of 'start', 'end', or 'periods'.")
if normalize:
converter = normalize_datetime_to_midnight
else:
converter = not_normalize
interval = self._freq_parser(freq)
if (bool(start) & bool(end)): # start and end
start = self.parse_datetime(start)
end = self.parse_datetime(end)
if start > end: # if start time later than end time, raise error
raise ValueError("start time has to be earlier than end time")
start = start - interval
while 1:
start += interval
if start <= end:
series.append(converter(start))
else:
break
elif (bool(start) & bool(periods)): # start and periods
start = self.parse_datetime(start)
start = start - interval
for _ in range(periods):
start += interval
series.append(converter(start))
elif (bool(end) & bool(periods)): # end and periods
end = self.parse_datetime(end)
start = end - interval * periods
for _ in range(periods):
start += interval
series.append(converter(start))
if return_date:
series = [i.date() for i in series]
return series
def weekday_series(self, start, end, weekday, return_date=False):
"""Generate a datetime series with same weekday number.
ISO weekday number: Mon to Sun = 1 to 7
Usage::
>>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25"
>>> rolex.weekday_series(start, end, weekday=2) # All Tuesday
[
datetime(2014, 1, 7, 6, 30, 25),
datetime(2014, 1, 14, 6, 30, 25),
datetime(2014, 1, 21, 6, 30, 25),
datetime(2014, 1, 28, 6, 30, 25),
]
:param weekday: int or list of int
**中文文档**
生成星期数一致的时间序列。
"""
start = self.parse_datetime(start)
end = self.parse_datetime(end)
if isinstance(weekday, integer_types):
weekday = [weekday, ]
series = list()
for i in self.time_series(
start, end, freq="1day", return_date=return_date):
if i.isoweekday() in weekday:
series.append(i)
return series
def isweekend(self, d_or_dt):
"""Check if a datetime is weekend.
"""
return d_or_dt.isoweekday() in [6, 7]
def isweekday(self, d_or_dt):
"""Check if a datetime is weekday.
"""
return d_or_dt.isoweekday() not in [6, 7]
#--- Random Generator ---
def randn(self, size, rnd_generator, *args):
if isinstance(size, integer_types):
if size < 0:
raise ValueError("'size' can't smaller than zero")
return [rnd_generator(*args) for _ in range(size)]
else:
try:
m, n = size[0], size[1]
if ((m < 0) or (n < 0)):
raise ValueError("'size' can't smaller than zero")
return [[rnd_generator(*args) for _ in range(n)] for _ in range(m)]
except:
raise ValueError("'size' has to be int or tuple. "
"e.g. 6 or (2, 3)")
def _rnd_date(self, start, end):
"""Internal random date generator.
"""
return date.fromordinal(
random.randint(start.toordinal(), end.toordinal()))
def rnd_date(self, start=date(1970, 1, 1), end=date.today()):
"""Generate a random date between ``start`` to ``end``.
:param start: Left bound
:type start: string or datetime.date, (default date(1970, 1, 1))
:param end: Right bound
:type end: string or datetime.date, (default date.today())
:return: a datetime.date object
**中文文档**
随机生成一个位于 ``start`` 和 ``end`` 之间的日期。
"""
if isinstance(start, string_types):
start = self.str2date(start)
if isinstance(end, string_types):
end = self.str2date(end)
if start > end:
raise ValueError("start time has to be earlier than end time")
return date.fromordinal(
random.randint(start.toordinal(), end.toordinal()))
def rnd_date_array(self, size, start=date(1970, 1, 1), end=date.today()):
"""Array or Matrix of random date generator.
"""
if isinstance(start, string_types):
start = self.str2date(start)
if isinstance(end, string_types):
end = self.str2date(end)
if start > end:
raise ValueError("start time has to be earlier than end time")
return self.randn(size, self._rnd_date, start, end)
def _rnd_datetime(self, start, end):
"""Internal random datetime generator.
"""
return self.from_utctimestamp(
random.randint(
int(self.to_utctimestamp(start)),
int(self.to_utctimestamp(end)),
)
)
def rnd_datetime(self, start=datetime(1970, 1, 1), end=datetime.now()):
"""Generate a random datetime between ``start`` to ``end``.
:param start: Left bound
:type start: string or datetime.datetime, (default datetime(1970, 1, 1))
:param end: Right bound
:type end: string or datetime.datetime, (default datetime.now())
:return: a datetime.datetime object
**中文文档**
随机生成一个位于 ``start`` 和 ``end`` 之间的时间。
"""
if isinstance(start, string_types):
start = self.str2datetime(start)
if isinstance(end, str):
end = self.str2datetime(end)
if start > end:
raise ValueError("start time has to be earlier than end time")
return self.from_utctimestamp(
random.randint(
int(self.to_utctimestamp(start)),
int(self.to_utctimestamp(end)),
)
)
def rnd_datetime_array(self,
size, start=datetime(1970, 1, 1), end=datetime.now()):
"""Array or Matrix of random datetime generator.
"""
if isinstance(start, string_types):
start = self.str2datetime(start)
if isinstance(end, str):
end = self.str2datetime(end)
if start > end:
raise ValueError("start time has to be earlier than end time")
return self.randn(size, self._rnd_datetime, start, end)
#--- Calculator ---
def add_seconds(self, datetimestr, n):
"""Returns a time that n seconds after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of seconds, value can be negative
**中文文档**
返回给定日期N秒之后的时间。
"""
a_datetime = self.parse_datetime(datetimestr)
return a_datetime + timedelta(seconds=n)
def add_minutes(self, datetimestr, n):
"""Returns a time that n minutes after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of minutes, value can be negative
**中文文档**
返回给定日期N分钟之后的时间。
"""
a_datetime = self.parse_datetime(datetimestr)
return a_datetime + timedelta(seconds=60 * n)
def add_hours(self, datetimestr, n):
"""Returns a time that n hours after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of hours, value can be negative
**中文文档**
返回给定日期N小时之后的时间。
"""
a_datetime = self.parse_datetime(datetimestr)
return a_datetime + timedelta(seconds=3600 * n)
def add_days(self, datetimestr, n, return_date=False):
"""Returns a time that n days after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of days, value can be negative
:param return_date: returns a date object instead of datetime
**中文文档**
返回给定日期N天之后的时间。
"""
a_datetime = self.parse_datetime(datetimestr)
a_datetime += timedelta(days=n)
if return_date:
return a_datetime.date()
else:
return a_datetime
def add_weeks(self, datetimestr, n, return_date=False):
"""Returns a time that n weeks after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of weeks, value can be negative
:param return_date: returns a date object instead of datetime
**中文文档**
返回给定日期N周之后的时间。
"""
a_datetime = self.parse_datetime(datetimestr)
a_datetime += timedelta(days=7 * n)
if return_date:
return a_datetime.date()
else:
return a_datetime
def add_months(self, datetimestr, n, return_date=False):
"""Returns a time that n months after a time.
Notice: for example, the date that one month after 2015-01-31 supposed
to be 2015-02-31. But there's no 31th in Feb, so we fix that value to
2015-02-28.
:param datetimestr: a datetime object or a datetime str
:param n: number of months, value can be negative
:param return_date: returns a date object instead of datetime
**中文文档**
返回给定日期N月之后的时间。
"""
a_datetime = self.parse_datetime(datetimestr)
month_from_ordinary = a_datetime.year * 12 + a_datetime.month
month_from_ordinary += n
year, month = divmod(month_from_ordinary, 12)
# 尝试直接assign year, month, day
try:
a_datetime = datetime(year, month, a_datetime.day,
a_datetime.hour, a_datetime.minute,
a_datetime.second, a_datetime.microsecond)
# 肯定是由于新的月份的日子不够, 那么直接跳到下一个月的第一天, 再回退一天
except ValueError:
a_datetime = datetime(year, month + 1, 1,
a_datetime.hour, a_datetime.minute,
a_datetime.second, a_datetime.microsecond)
a_datetime = self.add_days(a_datetime, -1)
if return_date:
return a_datetime.date()
else:
return a_datetime
def add_years(self, datetimestr, n, return_date=False):
"""Returns a time that n years after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of years, value can be negative
:param return_date: returns a date object instead of datetime
**中文文档**
返回给定日期N年之后的时间。
"""
a_datetime = self.parse_datetime(datetimestr)
try:
a_datetime = datetime(
a_datetime.year + n, a_datetime.month, a_datetime.day,
a_datetime.hour, a_datetime.minute,
a_datetime.second, a_datetime.microsecond)
except:
a_datetime = datetime(
a_datetime.year + n, 2, 28,
a_datetime.hour, a_datetime.minute,
a_datetime.second, a_datetime.microsecond)
if return_date:
return a_datetime.date()
else:
return a_datetime
def round_to(self, dt, hour, minute, second, mode="floor"):
"""Round the given datetime to specified hour, minute and second.
:param mode: 'floor' or 'ceiling'
**中文文档**
将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。
"""
mode = mode.lower()
new_dt = datetime(dt.year, dt.month, dt.day, hour, minute, second)
if mode == "floor":
if new_dt <= dt:
return new_dt
else:
return rolex.add_days(new_dt, -1)
elif mode == "ceiling":
if new_dt >= dt:
return new_dt
else:
return rolex.add_days(new_dt, 1)
else:
raise ValueError("'mode' has to be 'floor' or 'ceiling'!")
@staticmethod
def day_interval(year, month, day, milliseconds=False, return_string=False):
"""Return a start datetime and end datetime of a day.
:param milliseconds: Minimum time resolution.
:param return_string: If you want string instead of datetime, set True
Usage Example::
>>> start, end = rolex.day_interval(2014, 6, 17)
>>> start
datetime(2014, 6, 17, 0, 0, 0)
>>> end
datetime(2014, 6, 17, 23, 59, 59)
"""
if milliseconds:
delta = timedelta(milliseconds=1)
else:
delta = timedelta(seconds=1)
start = datetime(year, month, day)
end = datetime(year, month, day) + timedelta(days=1) - delta
if not return_string:
return start, end
else:
return str(start), str(end)
@staticmethod
def month_interval(year, month, milliseconds=False, return_string=False):
"""Return a start datetime and end datetime of a month.
:param milliseconds: Minimum time resolution.
:param return_string: If you want string instead of datetime, set True
Usage Example::
>>> start, end = rolex.month_interval(2000, 2)
>>> start
datetime(2000, 2, 1, 0, 0, 0)
>>> end
datetime(2000, 2, 29, 23, 59, 59)
"""
if milliseconds:
delta = timedelta(milliseconds=1)
else:
delta = timedelta(seconds=1)
if month == 12:
start = datetime(year, month, 1)
end = datetime(year + 1, 1, 1) - delta
else:
start = datetime(year, month, 1)
end = datetime(year, month + 1, 1) - delta
if not return_string:
return start, end
else:
return str(start), str(end)
@staticmethod
def year_interval(year, milliseconds=False, return_string=False):
"""Return a start datetime and end datetime of a year.
:param milliseconds: Minimum time resolution.
:param return_string: If you want string instead of datetime, set True
Usage Example::
>>> start, end = rolex.year_interval(2007)
>>> start
datetime(2007, 1, 1, 0, 0, 0)
>>> end
datetime(2007, 12, 31, 23, 59, 59)
"""
if milliseconds:
delta = timedelta(milliseconds=1)
else:
delta = timedelta(seconds=1)
start = datetime(year, 1, 1)
end = datetime(year + 1, 1, 1) - delta
if not return_string:
return start, end
else:
return str(start), str(end)
|
class Rolex(object):
'''Main class. A time related utility class.
Abbreviations:
- dt -> datetime object
- d -> date object
- ts -> timestamp
- s -> string
- i -> int/item
**中文文档**
本类提供了非常多与时间, 日期相关的函数。其中
"时间包装器"提供了对时间, 日期相关的许多计算操作的函数。能智能的从各种其他
格式的时间中解析出Python datetime.datetime/datetime.date 对象。更多功能请
参考API文档。
'''
def str2date(self, datestr):
'''Parse date from string. If no template matches this string,
raise Error. Please go
https://github.com/MacHu-GWU/rolex-project/issues
submit your date string. I 'll update templates asap.
This method is faster than :meth:`dateutil.parser.parse`.
:param datestr: a string represent a date
:type datestr: str
:return: a date object
**中文文档**
从string解析date。首先尝试默认模板, 如果失败了, 则尝试所有的模板。
一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的
字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。
该方法要快过 :meth:`dateutil.parser.parse` 方法。
'''
pass
def _str2datetime(self, datetimestr):
'''Parse datetime from string. If no template matches this string,
raise Error. Please go
https://github.com/MacHu-GWU/rolex-project/issues
submit your datetime string. I 'll update templates asap.
This method is faster than :meth:`dateutil.parser.parse`.
:param datetimestr: a string represent a datetime
:type datetimestr: str
:return: a datetime object
**中文文档**
从string解析datetime。首先尝试默认模板, 如果失败了, 则尝试所有的模板。
一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的
字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。
该方法要快过 :meth:`dateutil.parser.parse` 方法。
'''
pass
def parse_date(self, value):
'''A lazy method to parse anything to date.
If input data type is:
- string: parse date from it
- integer: use from ordinal
- datetime: use date part
- date: just return it
'''
pass
def parse_datetime(self, value):
'''A lazy method to parse anything to datetime.
If input data type is:
- string: parse datetime from it
- integer: use from ordinal
- date: use date part and set hour, minute, second to zero
- datetime: just return it
'''
pass
def to_ordinal(self, date_object):
'''Calculate number of days from 0000-00-00.
'''
pass
def from_ordinal(self, days):
'''Create a date object that number ``days`` of days after 0000-00-00.
'''
pass
def to_utctimestamp(self, dt):
'''Calculate number of seconds from UTC 1970-01-01 00:00:00.
When:
- dt doesn't have tzinfo: assume it's a utc time
- dt has tzinfo: use tzinfo
WARNING, if your datetime object doens't have ``tzinfo``, make sure
it's a UTC time, but **NOT a LOCAL TIME**.
**中文文档**
计算时间戳
若:
- 不带tzinfo: 则默认为是UTC time
- 带tzinfo: 使用tzinfo
'''
pass
def from_utctimestamp(self, timestamp):
'''Create a **UTC datetime** object that number of seconds after
UTC 1970-01-01 00:00:00. If you want local time, use
:meth:`Rolex.from_timestamp`
Because python doesn't support negative timestamp to datetime
so we have to implement my own method.
**中文文档**
返回一个在UTC 1970-01-01 00:00:00 之后 #timestamp 秒后的时间。默认为
UTC时间。即返回的datetime不带tzinfo
'''
pass
def to_timestamp(self, dt):
'''Calculate number of seconds from UTC 1970-01-01 00:00:00.
When:
- dt doesn't have tzinfo: assume it's a local time on your computer
- dt has tzinfo: use tzinfo
**中文文档**
计算时间戳
若:
- 不带tzinfo: 则默认为是本机的local time
- 带tzinfo: 使用tzinfo
'''
pass
def from_timestamp(self, timestamp):
'''Create a **local datetime** object that number of seconds after
UTC 1970-01-01 00:00:00. If you want utc time, use
:meth:`Rolex.from_utctimestamp`
**中文文档**
根据时间戳, 计算时间, 返回的是你的本机local time的时间。
'''
pass
def _freq_parser(self, freq):
'''Parse timedelta.
Valid keywords "days", "day", "d", "hours", "hour", "h",
"minutes", "minute", "min", "m", "seconds", "second", "sec", "s",
"weeks", "week", "w",
'''
pass
def time_series(self, start=None, end=None, periods=None,
freq="1day", normalize=False, return_date=False):
'''A pure Python implementation of pandas.date_range().
Given 2 of start, end, periods and freq, generate a series of
datetime object.
:param start: Left bound for generating dates
:type start: str or datetime.datetime (default None)
:param end: Right bound for generating dates
:type end: str or datetime.datetime (default None)
:param periods: Number of date points. If None, must specify start
and end
:type periods: integer (default None)
:param freq: string, default '1day' (calendar daily)
Available mode are day, hour, min, sec
Frequency strings can have multiples. e.g.
'7day', '6hour', '5min', '4sec', '3week`
:type freq: string (default '1day' calendar daily)
:param normalize: Trigger that normalize start/end dates to midnight
:type normalize: boolean (default False)
:return: A list of datetime.datetime object. An evenly sampled time
series.
Usage::
>>> from __future__ import print_function
>>> for dt in rolex.time_series("2014-1-1", "2014-1-7"):
... print(dt)
2014-01-01 00:00:00
2014-01-02 00:00:00
2014-01-03 00:00:00
2014-01-04 00:00:00
2014-01-05 00:00:00
2014-01-06 00:00:00
2014-01-07 00:00:00
**中文文档**
生成等间隔的时间序列。
需要给出, "起始", "结束", "数量" 中的任意两个。以及指定"频率"。以此唯一
确定一个等间隔时间序列。"频率"项所支持的命令字符有"7day", "6hour",
"5min", "4sec", "3week" (可以改变数字).
'''
pass
def normalize_datetime_to_midnight(dt):
'''Normalize a datetime %Y-%m-%d %H:%M:%S to %Y-%m-%d 00:00:00.
'''
pass
def not_normalize(dt):
'''Do not normalize.
'''
pass
def weekday_series(self, start, end, weekday, return_date=False):
'''Generate a datetime series with same weekday number.
ISO weekday number: Mon to Sun = 1 to 7
Usage::
>>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25"
>>> rolex.weekday_series(start, end, weekday=2) # All Tuesday
[
datetime(2014, 1, 7, 6, 30, 25),
datetime(2014, 1, 14, 6, 30, 25),
datetime(2014, 1, 21, 6, 30, 25),
datetime(2014, 1, 28, 6, 30, 25),
]
:param weekday: int or list of int
**中文文档**
生成星期数一致的时间序列。
'''
pass
def isweekend(self, d_or_dt):
'''Check if a datetime is weekend.
'''
pass
def isweekday(self, d_or_dt):
'''Check if a datetime is weekday.
'''
pass
def randn(self, size, rnd_generator, *args):
pass
def _rnd_date(self, start, end):
'''Internal random date generator.
'''
pass
def rnd_date(self, start=date(1970, 1, 1), end=date.today()):
'''Generate a random date between ``start`` to ``end``.
:param start: Left bound
:type start: string or datetime.date, (default date(1970, 1, 1))
:param end: Right bound
:type end: string or datetime.date, (default date.today())
:return: a datetime.date object
**中文文档**
随机生成一个位于 ``start`` 和 ``end`` 之间的日期。
'''
pass
def rnd_date_array(self, size, start=date(1970, 1, 1), end=date.today()):
'''Array or Matrix of random date generator.
'''
pass
def _rnd_datetime(self, start, end):
'''Internal random datetime generator.
'''
pass
def rnd_datetime(self, start=datetime(1970, 1, 1), end=datetime.now()):
'''Generate a random datetime between ``start`` to ``end``.
:param start: Left bound
:type start: string or datetime.datetime, (default datetime(1970, 1, 1))
:param end: Right bound
:type end: string or datetime.datetime, (default datetime.now())
:return: a datetime.datetime object
**中文文档**
随机生成一个位于 ``start`` 和 ``end`` 之间的时间。
'''
pass
def rnd_datetime_array(self,
size, start=datetime(1970, 1, 1), end=datetime.now()):
'''Array or Matrix of random datetime generator.
'''
pass
def add_seconds(self, datetimestr, n):
'''Returns a time that n seconds after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of seconds, value can be negative
**中文文档**
返回给定日期N秒之后的时间。
'''
pass
def add_minutes(self, datetimestr, n):
'''Returns a time that n minutes after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of minutes, value can be negative
**中文文档**
返回给定日期N分钟之后的时间。
'''
pass
def add_hours(self, datetimestr, n):
'''Returns a time that n hours after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of hours, value can be negative
**中文文档**
返回给定日期N小时之后的时间。
'''
pass
def add_days(self, datetimestr, n, return_date=False):
'''Returns a time that n days after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of days, value can be negative
:param return_date: returns a date object instead of datetime
**中文文档**
返回给定日期N天之后的时间。
'''
pass
def add_weeks(self, datetimestr, n, return_date=False):
'''Returns a time that n weeks after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of weeks, value can be negative
:param return_date: returns a date object instead of datetime
**中文文档**
返回给定日期N周之后的时间。
'''
pass
def add_months(self, datetimestr, n, return_date=False):
'''Returns a time that n months after a time.
Notice: for example, the date that one month after 2015-01-31 supposed
to be 2015-02-31. But there's no 31th in Feb, so we fix that value to
2015-02-28.
:param datetimestr: a datetime object or a datetime str
:param n: number of months, value can be negative
:param return_date: returns a date object instead of datetime
**中文文档**
返回给定日期N月之后的时间。
'''
pass
def add_years(self, datetimestr, n, return_date=False):
'''Returns a time that n years after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of years, value can be negative
:param return_date: returns a date object instead of datetime
**中文文档**
返回给定日期N年之后的时间。
'''
pass
def round_to(self, dt, hour, minute, second, mode="floor"):
'''Round the given datetime to specified hour, minute and second.
:param mode: 'floor' or 'ceiling'
**中文文档**
将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。
'''
pass
@staticmethod
def day_interval(year, month, day, milliseconds=False, return_string=False):
'''Return a start datetime and end datetime of a day.
:param milliseconds: Minimum time resolution.
:param return_string: If you want string instead of datetime, set True
Usage Example::
>>> start, end = rolex.day_interval(2014, 6, 17)
>>> start
datetime(2014, 6, 17, 0, 0, 0)
>>> end
datetime(2014, 6, 17, 23, 59, 59)
'''
pass
@staticmethod
def month_interval(year, month, milliseconds=False, return_string=False):
'''Return a start datetime and end datetime of a month.
:param milliseconds: Minimum time resolution.
:param return_string: If you want string instead of datetime, set True
Usage Example::
>>> start, end = rolex.month_interval(2000, 2)
>>> start
datetime(2000, 2, 1, 0, 0, 0)
>>> end
datetime(2000, 2, 29, 23, 59, 59)
'''
pass
@staticmethod
def year_interval(year, milliseconds=False, return_string=False):
'''Return a start datetime and end datetime of a year.
:param milliseconds: Minimum time resolution.
:param return_string: If you want string instead of datetime, set True
Usage Example::
>>> start, end = rolex.year_interval(2007)
>>> start
datetime(2007, 1, 1, 0, 0, 0)
>>> end
datetime(2007, 12, 31, 23, 59, 59)
'''
pass
| 39 | 35 | 22 | 4 | 10 | 8 | 3 | 0.81 | 1 | 12 | 0 | 0 | 30 | 0 | 33 | 33 | 825 | 175 | 361 | 81 | 320 | 293 | 286 | 75 | 250 | 12 | 1 | 3 | 116 |
148,233 |
MacHu-GWU/pymongo_mate-project
|
MacHu-GWU_pymongo_mate-project/pymongo_mate/pkg/pandas_mate/pkg/prettytable/prettytable.py
|
pymongo_mate.pkg.pandas_mate.pkg.prettytable.prettytable.PrettyTable
|
class PrettyTable(object):
def __init__(self, field_names=None, **kwargs):
"""Return a new PrettyTable instance
Arguments:
encoding - Unicode encoding scheme used to decode any encoded input
title - optional table title
field_names - list or tuple of field names
fields - list or tuple of field names to include in displays
start - index of first data row to include in output
end - index of last data row to include in output PLUS ONE (list slice style)
header - print a header showing field names (True or False)
header_style - stylisation to apply to field names in header ("cap", "title", "upper", "lower" or None)
border - print a border around the table (True or False)
hrules - controls printing of horizontal rules after rows. Allowed values: FRAME, HEADER, ALL, NONE
vrules - controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE
int_format - controls formatting of integer data
float_format - controls formatting of floating point data
min_table_width - minimum desired table width, in characters
max_table_width - maximum desired table width, in characters
padding_width - number of spaces on either side of column data (only used if left and right paddings are None)
left_padding_width - number of spaces on left hand side of column data
right_padding_width - number of spaces on right hand side of column data
vertical_char - single character string used to draw vertical lines
horizontal_char - single character string used to draw horizontal lines
junction_char - single character string used to draw line junctions
sortby - name of field to sort rows by
sort_key - sorting key function, applied to data points before sorting
valign - default valign for each row (None, "t", "m" or "b")
reversesort - True or False to sort in descending or ascending order
oldsortslice - Slice rows before sorting in the "old style" """
self.encoding = kwargs.get("encoding", "UTF-8")
# Data
self._field_names = []
self._rows = []
self.align = {}
self.valign = {}
self.max_width = {}
self.min_width = {}
self.int_format = {}
self.float_format = {}
if field_names:
self.field_names = field_names
else:
self._widths = []
# Options
self._options = "title start end fields header border sortby reversesort sort_key attributes format hrules vrules".split()
self._options.extend(
"int_format float_format min_table_width max_table_width padding_width left_padding_width right_padding_width".split())
self._options.extend(
"vertical_char horizontal_char junction_char header_style valign xhtml print_empty oldsortslice".split())
self._options.extend("align valign max_width min_width".split())
for option in self._options:
if option in kwargs:
self._validate_option(option, kwargs[option])
else:
kwargs[option] = None
self._title = kwargs["title"] or None
self._start = kwargs["start"] or 0
self._end = kwargs["end"] or None
self._fields = kwargs["fields"] or None
if kwargs["header"] in (True, False):
self._header = kwargs["header"]
else:
self._header = True
self._header_style = kwargs["header_style"] or None
if kwargs["border"] in (True, False):
self._border = kwargs["border"]
else:
self._border = True
self._hrules = kwargs["hrules"] or FRAME
self._vrules = kwargs["vrules"] or ALL
self._sortby = kwargs["sortby"] or None
if kwargs["reversesort"] in (True, False):
self._reversesort = kwargs["reversesort"]
else:
self._reversesort = False
self._sort_key = kwargs["sort_key"] or (lambda x: x)
# Column specific arguments, use property.setters
self.align = kwargs["align"] or {}
self.valign = kwargs["valign"] or {}
self.max_width = kwargs["max_width"] or {}
self.min_width = kwargs["min_width"] or {}
self.int_format = kwargs["int_format"] or {}
self.float_format = kwargs["float_format"] or {}
self._min_table_width = kwargs["min_table_width"] or None
self._max_table_width = kwargs["max_table_width"] or None
self._padding_width = kwargs["padding_width"] or 1
self._left_padding_width = kwargs["left_padding_width"] or None
self._right_padding_width = kwargs["right_padding_width"] or None
self._vertical_char = kwargs["vertical_char"] or self._unicode("|")
self._horizontal_char = kwargs["horizontal_char"] or self._unicode("-")
self._junction_char = kwargs["junction_char"] or self._unicode("+")
if kwargs["print_empty"] in (True, False):
self._print_empty = kwargs["print_empty"]
else:
self._print_empty = True
if kwargs["oldsortslice"] in (True, False):
self._oldsortslice = kwargs["oldsortslice"]
else:
self._oldsortslice = False
self._format = kwargs["format"] or False
self._xhtml = kwargs["xhtml"] or False
self._attributes = kwargs["attributes"] or {}
def _unicode(self, value):
if not isinstance(value, basestring_):
value = str(value)
if not isinstance(value, unicode_):
value = unicode_(value, self.encoding, "strict")
return value
def _justify(self, text, width, align):
excess = width - _str_block_width(text)
if align == "l":
return text + excess * " "
elif align == "r":
return excess * " " + text
else:
if excess % 2:
# Uneven padding
# Put more space on right if text is of odd length...
if _str_block_width(text) % 2:
return (excess // 2) * " " + text + (excess // 2 + 1) * " "
# and more space on left if text is of even length
else:
return (excess // 2 + 1) * " " + text + (excess // 2) * " "
# Why distribute extra space this way? To match the behaviour of
# the inbuilt str.center() method.
else:
# Equal padding on either side
return (excess // 2) * " " + text + (excess // 2) * " "
def __getattr__(self, name):
if name == "rowcount":
return len(self._rows)
elif name == "colcount":
if self._field_names:
return len(self._field_names)
elif self._rows:
return len(self._rows[0])
else:
return 0
else:
raise AttributeError(name)
def __getitem__(self, index):
new = PrettyTable()
new.field_names = self.field_names
for attr in self._options:
setattr(new, "_" + attr, getattr(self, "_" + attr))
setattr(new, "_align", getattr(self, "_align"))
if isinstance(index, slice):
for row in self._rows[index]:
new.add_row(row)
elif isinstance(index, int):
new.add_row(self._rows[index])
else:
raise Exception(
"Index %s is invalid, must be an integer or slice" % str(index))
return new
if py3k:
def __str__(self):
return self.__unicode__()
else:
def __str__(self):
return self.__unicode__().encode(self.encoding)
def __unicode__(self):
return self.get_string()
##############################
# ATTRIBUTE VALIDATORS #
##############################
# The method _validate_option is all that should be used elsewhere in the code base to validate options.
# It will call the appropriate validation method for that option. The individual validation methods should
# never need to be called directly (although nothing bad will happen if they *are*).
# Validation happens in TWO places.
# Firstly, in the property setters defined in the ATTRIBUTE MANAGMENT section.
# Secondly, in the _get_options method, where keyword arguments are mixed
# with persistent settings
def _validate_option(self, option, val):
if option in ("field_names"):
self._validate_field_names(val)
elif option in ("start", "end", "max_width", "min_width", "min_table_width", "max_table_width", "padding_width",
"left_padding_width", "right_padding_width", "format"):
self._validate_nonnegative_int(option, val)
elif option in ("sortby"):
self._validate_field_name(option, val)
elif option in ("sort_key"):
self._validate_function(option, val)
elif option in ("hrules"):
self._validate_hrules(option, val)
elif option in ("vrules"):
self._validate_vrules(option, val)
elif option in ("fields"):
self._validate_all_field_names(option, val)
elif option in ("header", "border", "reversesort", "xhtml", "print_empty", "oldsortslice"):
self._validate_true_or_false(option, val)
elif option in ("header_style"):
self._validate_header_style(val)
elif option in ("int_format"):
self._validate_int_format(option, val)
elif option in ("float_format"):
self._validate_float_format(option, val)
elif option in ("vertical_char", "horizontal_char", "junction_char"):
self._validate_single_char(option, val)
elif option in ("attributes"):
self._validate_attributes(option, val)
def _validate_field_names(self, val):
# Check for appropriate length
if self._field_names:
try:
assert len(val) == len(self._field_names)
except AssertionError:
raise Exception("Field name list has incorrect number of values, (actual) %d!=%d (expected)" % (
len(val), len(self._field_names)))
if self._rows:
try:
assert len(val) == len(self._rows[0])
except AssertionError:
raise Exception("Field name list has incorrect number of values, (actual) %d!=%d (expected)" % (
len(val), len(self._rows[0])))
# Check for uniqueness
try:
assert len(val) == len(set(val))
except AssertionError:
raise Exception("Field names must be unique!")
def _validate_header_style(self, val):
try:
assert val in ("cap", "title", "upper", "lower", None)
except AssertionError:
raise Exception(
"Invalid header style, use cap, title, upper, lower or None!")
def _validate_align(self, val):
try:
assert val in ["l", "c", "r"]
except AssertionError:
raise Exception("Alignment %s is invalid, use l, c or r!" % val)
def _validate_valign(self, val):
try:
assert val in ["t", "m", "b", None]
except AssertionError:
raise Exception(
"Alignment %s is invalid, use t, m, b or None!" % val)
def _validate_nonnegative_int(self, name, val):
try:
assert int(val) >= 0
except AssertionError:
raise Exception("Invalid value for %s: %s!" %
(name, self._unicode(val)))
def _validate_true_or_false(self, name, val):
try:
assert val in (True, False)
except AssertionError:
raise Exception(
"Invalid value for %s! Must be True or False." % name)
def _validate_int_format(self, name, val):
if val == "":
return
try:
assert type(val) in str_types
assert val.isdigit()
except AssertionError:
raise Exception(
"Invalid value for %s! Must be an integer format string." % name)
def _validate_float_format(self, name, val):
if val == "":
return
try:
val = val.rsplit('f')[0]
assert type(val) in str_types
assert "." in val
bits = val.split(".")
assert len(bits) <= 2
assert bits[0] == "" or bits[0].isdigit()
assert bits[1] == "" or bits[1].isdigit()
except AssertionError:
raise Exception(
"Invalid value for %s! Must be a float format string." % name)
def _validate_function(self, name, val):
try:
assert hasattr(val, "__call__")
except AssertionError:
raise Exception(
"Invalid value for %s! Must be a function." % name)
def _validate_hrules(self, name, val):
try:
assert val in (ALL, FRAME, HEADER, NONE)
except AssertionError:
raise Exception(
"Invalid value for %s! Must be ALL, FRAME, HEADER or NONE." % name)
def _validate_vrules(self, name, val):
try:
assert val in (ALL, FRAME, NONE)
except AssertionError:
raise Exception(
"Invalid value for %s! Must be ALL, FRAME, or NONE." % name)
def _validate_field_name(self, name, val):
try:
assert (val in self._field_names) or (val is None)
except AssertionError:
raise Exception("Invalid field name: %s!" % val)
def _validate_all_field_names(self, name, val):
try:
for x in val:
self._validate_field_name(name, x)
except AssertionError:
raise Exception("fields must be a sequence of field names!")
def _validate_single_char(self, name, val):
try:
assert _str_block_width(val) == 1
except AssertionError:
raise Exception(
"Invalid value for %s! Must be a string of length 1." % name)
def _validate_attributes(self, name, val):
try:
assert isinstance(val, dict)
except AssertionError:
raise Exception(
"attributes must be a dictionary of name/value pairs!")
##############################
# ATTRIBUTE MANAGEMENT #
##############################
@property
def field_names(self):
"""List or tuple of field names"""
return self._field_names
@field_names.setter
def field_names(self, val):
val = [self._unicode(x) for x in val]
self._validate_option("field_names", val)
if self._field_names:
old_names = self._field_names[:]
self._field_names = val
if self._align and old_names:
for old_name, new_name in zip(old_names, val):
self._align[new_name] = self._align[old_name]
for old_name in old_names:
if old_name not in self._align:
self._align.pop(old_name)
else:
self.align = "c"
if self._valign and old_names:
for old_name, new_name in zip(old_names, val):
self._valign[new_name] = self._valign[old_name]
for old_name in old_names:
if old_name not in self._valign:
self._valign.pop(old_name)
else:
self.valign = "t"
@property
def align(self):
"""Controls alignment of fields
Arguments:
align - alignment, one of "l", "c", or "r" """
return self._align
@align.setter
def align(self, val):
if not self._field_names:
self._align = {}
elif val is None or (isinstance(val, dict) and len(val) is 0):
for field in self._field_names:
self._align[field] = "c"
else:
self._validate_align(val)
for field in self._field_names:
self._align[field] = val
@property
def valign(self):
"""Controls vertical alignment of fields
Arguments:
valign - vertical alignment, one of "t", "m", or "b" """
return self._valign
@valign.setter
def valign(self, val):
if not self._field_names:
self._valign = {}
elif val is None or (isinstance(val, dict) and len(val) is 0):
for field in self._field_names:
self._valign[field] = "t"
else:
self._validate_valign(val)
for field in self._field_names:
self._valign[field] = val
@property
def max_width(self):
"""Controls maximum width of fields
Arguments:
max_width - maximum width integer"""
return self._max_width
@max_width.setter
def max_width(self, val):
if val is None or (isinstance(val, dict) and len(val) is 0):
self._max_width = {}
else:
self._validate_option("max_width", val)
for field in self._field_names:
self._max_width[field] = val
@property
def min_width(self):
"""Controls minimum width of fields
Arguments:
min_width - minimum width integer"""
return self._min_width
@min_width.setter
def min_width(self, val):
if val is None or (isinstance(val, dict) and len(val) is 0):
self._min_width = {}
else:
self._validate_option("min_width", val)
for field in self._field_names:
self._min_width[field] = val
@property
def min_table_width(self):
return self._min_table_width
@min_table_width.setter
def min_table_width(self, val):
self._validate_option("min_table_width", val)
self._min_table_width = val
@property
def max_table_width(self):
return self._max_table_width
@max_table_width.setter
def max_table_width(self, val):
self._validate_option("max_table_width", val)
self._max_table_width = val
@property
def fields(self):
"""List or tuple of field names to include in displays"""
return self._fields
@fields.setter
def fields(self, val):
self._validate_option("fields", val)
self._fields = val
@property
def title(self):
"""Optional table title
Arguments:
title - table title"""
return self._title
@title.setter
def title(self, val):
self._title = self._unicode(val)
@property
def start(self):
"""Start index of the range of rows to print
Arguments:
start - index of first data row to include in output"""
return self._start
@start.setter
def start(self, val):
self._validate_option("start", val)
self._start = val
@property
def end(self):
"""End index of the range of rows to print
Arguments:
end - index of last data row to include in output PLUS ONE (list slice style)"""
return self._end
@end.setter
def end(self, val):
self._validate_option("end", val)
self._end = val
@property
def sortby(self):
"""Name of field by which to sort rows
Arguments:
sortby - field name to sort by"""
return self._sortby
@sortby.setter
def sortby(self, val):
self._validate_option("sortby", val)
self._sortby = val
@property
def reversesort(self):
"""Controls direction of sorting (ascending vs descending)
Arguments:
reveresort - set to True to sort by descending order, or False to sort by ascending order"""
return self._reversesort
@reversesort.setter
def reversesort(self, val):
self._validate_option("reversesort", val)
self._reversesort = val
@property
def sort_key(self):
"""Sorting key function, applied to data points before sorting
Arguments:
sort_key - a function which takes one argument and returns something to be sorted"""
return self._sort_key
@sort_key.setter
def sort_key(self, val):
self._validate_option("sort_key", val)
self._sort_key = val
@property
def header(self):
"""Controls printing of table header with field names
Arguments:
header - print a header showing field names (True or False)"""
return self._header
@header.setter
def header(self, val):
self._validate_option("header", val)
self._header = val
@property
def header_style(self):
"""Controls stylisation applied to field names in header
Arguments:
header_style - stylisation to apply to field names in header ("cap", "title", "upper", "lower" or None)"""
return self._header_style
@header_style.setter
def header_style(self, val):
self._validate_header_style(val)
self._header_style = val
@property
def border(self):
"""Controls printing of border around table
Arguments:
border - print a border around the table (True or False)"""
return self._border
@border.setter
def border(self, val):
self._validate_option("border", val)
self._border = val
@property
def hrules(self):
"""Controls printing of horizontal rules after rows
Arguments:
hrules - horizontal rules style. Allowed values: FRAME, ALL, HEADER, NONE"""
return self._hrules
@hrules.setter
def hrules(self, val):
self._validate_option("hrules", val)
self._hrules = val
@property
def vrules(self):
"""Controls printing of vertical rules between columns
Arguments:
vrules - vertical rules style. Allowed values: FRAME, ALL, NONE"""
return self._vrules
@vrules.setter
def vrules(self, val):
self._validate_option("vrules", val)
self._vrules = val
@property
def int_format(self):
"""Controls formatting of integer data
Arguments:
int_format - integer format string"""
return self._int_format
@int_format.setter
def int_format(self, val):
if val is None or (isinstance(val, dict) and len(val) is 0):
self._int_format = {}
else:
self._validate_option("int_format", val)
for field in self._field_names:
self._int_format[field] = val
@property
def float_format(self):
"""Controls formatting of floating point data
Arguments:
float_format - floating point format string"""
return self._float_format
@float_format.setter
def float_format(self, val):
if val is None or (isinstance(val, dict) and len(val) is 0):
self._float_format = {}
else:
self._validate_option("float_format", val)
for field in self._field_names:
self._float_format[field] = val
@property
def padding_width(self):
"""The number of empty spaces between a column's edge and its content
Arguments:
padding_width - number of spaces, must be a positive integer"""
return self._padding_width
@padding_width.setter
def padding_width(self, val):
self._validate_option("padding_width", val)
self._padding_width = val
@property
def left_padding_width(self):
"""The number of empty spaces between a column's left edge and its content
Arguments:
left_padding - number of spaces, must be a positive integer"""
return self._left_padding_width
@left_padding_width.setter
def left_padding_width(self, val):
self._validate_option("left_padding_width", val)
self._left_padding_width = val
@property
def right_padding_width(self):
"""The number of empty spaces between a column's right edge and its content
Arguments:
right_padding - number of spaces, must be a positive integer"""
return self._right_padding_width
@right_padding_width.setter
def right_padding_width(self, val):
self._validate_option("right_padding_width", val)
self._right_padding_width = val
@property
def vertical_char(self):
"""The charcter used when printing table borders to draw vertical lines
Arguments:
vertical_char - single character string used to draw vertical lines"""
return self._vertical_char
@vertical_char.setter
def vertical_char(self, val):
val = self._unicode(val)
self._validate_option("vertical_char", val)
self._vertical_char = val
@property
def horizontal_char(self):
"""The charcter used when printing table borders to draw horizontal lines
Arguments:
horizontal_char - single character string used to draw horizontal lines"""
return self._horizontal_char
@horizontal_char.setter
def horizontal_char(self, val):
val = self._unicode(val)
self._validate_option("horizontal_char", val)
self._horizontal_char = val
@property
def junction_char(self):
"""The charcter used when printing table borders to draw line junctions
Arguments:
junction_char - single character string used to draw line junctions"""
return self._junction_char
@junction_char.setter
def junction_char(self, val):
val = self._unicode(val)
self._validate_option("vertical_char", val)
self._junction_char = val
@property
def format(self):
"""Controls whether or not HTML tables are formatted to match styling options
Arguments:
format - True or False"""
return self._format
@format.setter
def format(self, val):
self._validate_option("format", val)
self._format = val
@property
def print_empty(self):
"""Controls whether or not empty tables produce a header and frame or just an empty string
Arguments:
print_empty - True or False"""
return self._print_empty
@print_empty.setter
def print_empty(self, val):
self._validate_option("print_empty", val)
self._print_empty = val
@property
def attributes(self):
"""A dictionary of HTML attribute name/value pairs to be included in the <table> tag when printing HTML
Arguments:
attributes - dictionary of attributes"""
return self._attributes
@attributes.setter
def attributes(self, val):
self._validate_option("attributes", val)
self._attributes = val
@property
def oldsortslice(self):
""" oldsortslice - Slice rows before sorting in the "old style" """
return self._oldsortslice
@oldsortslice.setter
def oldsortslice(self, val):
self._validate_option("oldsortslice", val)
self._oldsortslice = val
##############################
# OPTION MIXER #
##############################
def _get_options(self, kwargs):
options = {}
for option in self._options:
if option in kwargs:
self._validate_option(option, kwargs[option])
options[option] = kwargs[option]
else:
options[option] = getattr(self, "_" + option)
return options
##############################
# PRESET STYLE LOGIC #
##############################
def set_style(self, style):
if style == DEFAULT:
self._set_default_style()
elif style == MSWORD_FRIENDLY:
self._set_msword_style()
elif style == PLAIN_COLUMNS:
self._set_columns_style()
elif style == RANDOM:
self._set_random_style()
else:
raise Exception("Invalid pre-set style!")
def _set_default_style(self):
self.header = True
self.border = True
self._hrules = FRAME
self._vrules = ALL
self.padding_width = 1
self.left_padding_width = 1
self.right_padding_width = 1
self.vertical_char = "|"
self.horizontal_char = "-"
self.junction_char = "+"
def _set_msword_style(self):
self.header = True
self.border = True
self._hrules = NONE
self.padding_width = 1
self.left_padding_width = 1
self.right_padding_width = 1
self.vertical_char = "|"
def _set_columns_style(self):
self.header = True
self.border = False
self.padding_width = 1
self.left_padding_width = 0
self.right_padding_width = 8
def _set_random_style(self):
# Just for fun!
self.header = random.choice((True, False))
self.border = random.choice((True, False))
self._hrules = random.choice((ALL, FRAME, HEADER, NONE))
self._vrules = random.choice((ALL, FRAME, NONE))
self.left_padding_width = random.randint(0, 5)
self.right_padding_width = random.randint(0, 5)
self.vertical_char = random.choice("~!@#$%^&*()_+|-=\{}[];':\",./;<>?")
self.horizontal_char = random.choice(
"~!@#$%^&*()_+|-=\{}[];':\",./;<>?")
self.junction_char = random.choice("~!@#$%^&*()_+|-=\{}[];':\",./;<>?")
##############################
# DATA INPUT METHODS #
##############################
def add_row(self, row):
"""Add a row to the table
Arguments:
row - row of data, should be a list with as many elements as the table
has fields"""
if self._field_names and len(row) != len(self._field_names):
raise Exception(
"Row has incorrect number of values, (actual) %d!=%d (expected)" % (len(row), len(self._field_names)))
if not self._field_names:
self.field_names = [("Field %d" % (n + 1))
for n in range(0, len(row))]
self._rows.append(list(row))
def del_row(self, row_index):
"""Delete a row to the table
Arguments:
row_index - The index of the row you want to delete. Indexing starts at 0."""
if row_index > len(self._rows) - 1:
raise Exception("Cant delete row at index %d, table only has %d rows!" % (
row_index, len(self._rows)))
del self._rows[row_index]
def add_column(self, fieldname, column, align="c", valign="t"):
"""Add a column to the table.
Arguments:
fieldname - name of the field to contain the new column of data
column - column of data, should be a list with as many elements as the
table has rows
align - desired alignment for this column - "l" for left, "c" for centre and "r" for right
valign - desired vertical alignment for new columns - "t" for top, "m" for middle and "b" for bottom"""
if len(self._rows) in (0, len(column)):
self._validate_align(align)
self._validate_valign(valign)
self._field_names.append(fieldname)
self._align[fieldname] = align
self._valign[fieldname] = valign
for i in range(0, len(column)):
if len(self._rows) < i + 1:
self._rows.append([])
self._rows[i].append(column[i])
else:
raise Exception("Column length %d does not match number of rows %d!" % (
len(column), len(self._rows)))
def clear_rows(self):
"""Delete all rows from the table but keep the current field names"""
self._rows = []
def clear(self):
"""Delete all rows and field names from the table, maintaining nothing but styling options"""
self._rows = []
self._field_names = []
self._widths = []
##############################
# MISC PUBLIC METHODS #
##############################
def copy(self):
return copy.deepcopy(self)
##############################
# MISC PRIVATE METHODS #
##############################
def _format_value(self, field, value):
if isinstance(value, int) and field in self._int_format:
value = self._unicode(("%%%sd" % self._int_format[field]) % value)
elif isinstance(value, float) and field in self._float_format:
value = self._unicode(
("%%%sf" % self._float_format[field]) % value)
return self._unicode(value)
def _compute_table_width(self, options):
table_width = 2 if options["vrules"] in (FRAME, ALL) else 0
per_col_padding = sum(self._get_padding_widths(options))
for index, fieldname in enumerate(self.field_names):
if not options["fields"] or (options["fields"] and fieldname in options["fields"]):
table_width += self._widths[index] + per_col_padding
return table_width
def _compute_widths(self, rows, options):
if options["header"]:
widths = [_get_size(field)[0] for field in self._field_names]
else:
widths = len(self.field_names) * [0]
for row in rows:
for index, value in enumerate(row):
fieldname = self.field_names[index]
if fieldname in self.max_width:
widths[index] = max(widths[index], min(
_get_size(value)[0], self.max_width[fieldname]))
else:
widths[index] = max(widths[index], _get_size(value)[0])
if fieldname in self.min_width:
widths[index] = max(
widths[index], self.min_width[fieldname])
self._widths = widths
# Are we exceeding max_table_width?
if self._max_table_width:
table_width = self._compute_table_width(options)
if table_width > self._max_table_width:
# Shrink widths in proportion
scale = 1.0 * self._max_table_width / table_width
widths = [int(math.floor(w * scale)) for w in widths]
self._widths = widths
# Are we under min_table_width or title width?
if self._min_table_width or options["title"]:
if options["title"]:
title_width = len(options["title"]) + \
sum(self._get_padding_widths(options))
if options["vrules"] in (FRAME, ALL):
title_width += 2
else:
title_width = 0
min_table_width = self.min_table_width or 0
min_width = max(title_width, min_table_width)
table_width = self._compute_table_width(options)
if table_width < min_width:
# Grow widths in proportion
scale = 1.0 * min_width / table_width
widths = [int(math.ceil(w * scale)) for w in widths]
self._widths = widths
def _get_padding_widths(self, options):
if options["left_padding_width"] is not None:
lpad = options["left_padding_width"]
else:
lpad = options["padding_width"]
if options["right_padding_width"] is not None:
rpad = options["right_padding_width"]
else:
rpad = options["padding_width"]
return lpad, rpad
def _get_rows(self, options):
"""Return only those data rows that should be printed, based on slicing and sorting.
Arguments:
options - dictionary of option settings."""
if options["oldsortslice"]:
rows = copy.deepcopy(self._rows[options["start"]:options["end"]])
else:
rows = copy.deepcopy(self._rows)
# Sort
if options["sortby"]:
sortindex = self._field_names.index(options["sortby"])
# Decorate
rows = [[row[sortindex]] + row for row in rows]
# Sort
rows.sort(reverse=options["reversesort"], key=options["sort_key"])
# Undecorate
rows = [row[1:] for row in rows]
# Slice if necessary
if not options["oldsortslice"]:
rows = rows[options["start"]:options["end"]]
return rows
def _format_row(self, row, options):
return [self._format_value(field, value) for (field, value) in zip(self._field_names, row)]
def _format_rows(self, rows, options):
return [self._format_row(row, options) for row in rows]
##############################
# PLAIN TEXT STRING METHODS #
##############################
def get_string(self, **kwargs):
"""Return string representation of table in current state.
Arguments:
title - optional table title
start - index of first data row to include in output
end - index of last data row to include in output PLUS ONE (list slice style)
fields - names of fields (columns) to include
header - print a header showing field names (True or False)
border - print a border around the table (True or False)
hrules - controls printing of horizontal rules after rows. Allowed values: ALL, FRAME, HEADER, NONE
vrules - controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE
int_format - controls formatting of integer data
float_format - controls formatting of floating point data
padding_width - number of spaces on either side of column data (only used if left and right paddings are None)
left_padding_width - number of spaces on left hand side of column data
right_padding_width - number of spaces on right hand side of column data
vertical_char - single character string used to draw vertical lines
horizontal_char - single character string used to draw horizontal lines
junction_char - single character string used to draw line junctions
sortby - name of field to sort rows by
sort_key - sorting key function, applied to data points before sorting
reversesort - True or False to sort in descending or ascending order
print empty - if True, stringify just the header for an empty table, if False return an empty string """
options = self._get_options(kwargs)
lines = []
# Don't think too hard about an empty table
# Is this the desired behaviour? Maybe we should still print the
# header?
if self.rowcount == 0 and (not options["print_empty"] or not options["border"]):
return ""
# Get the rows we need to print, taking into account slicing, sorting,
# etc.
rows = self._get_rows(options)
# Turn all data in all rows into Unicode, formatted as desired
formatted_rows = self._format_rows(rows, options)
# Compute column widths
self._compute_widths(formatted_rows, options)
self._hrule = self._stringify_hrule(options)
# Add title
title = options["title"] or self._title
if title:
lines.append(self._stringify_title(title, options))
# Add header or top of border
if options["header"]:
lines.append(self._stringify_header(options))
elif options["border"] and options["hrules"] in (ALL, FRAME):
lines.append(self._hrule)
# Add rows
for row in formatted_rows:
lines.append(self._stringify_row(row, options))
# Add bottom of border
if options["border"] and options["hrules"] == FRAME:
lines.append(self._hrule)
return self._unicode("\n").join(lines)
def _stringify_hrule(self, options):
if not options["border"]:
return ""
lpad, rpad = self._get_padding_widths(options)
if options['vrules'] in (ALL, FRAME):
bits = [options["junction_char"]]
else:
bits = [options["horizontal_char"]]
# For tables with no data or fieldnames
if not self._field_names:
bits.append(options["junction_char"])
return "".join(bits)
for field, width in zip(self._field_names, self._widths):
if options["fields"] and field not in options["fields"]:
continue
bits.append((width + lpad + rpad) * options["horizontal_char"])
if options['vrules'] == ALL:
bits.append(options["junction_char"])
else:
bits.append(options["horizontal_char"])
if options["vrules"] == FRAME:
bits.pop()
bits.append(options["junction_char"])
return "".join(bits)
def _stringify_title(self, title, options):
lines = []
lpad, rpad = self._get_padding_widths(options)
if options["border"]:
if options["vrules"] == ALL:
options["vrules"] = FRAME
lines.append(self._stringify_hrule(options))
options["vrules"] = ALL
elif options["vrules"] == FRAME:
lines.append(self._stringify_hrule(options))
bits = []
endpoint = options["vertical_char"] if options["vrules"] in (
ALL, FRAME) else " "
bits.append(endpoint)
title = " " * lpad + title + " " * rpad
bits.append(self._justify(title, len(self._hrule) - 2, "c"))
bits.append(endpoint)
lines.append("".join(bits))
return "\n".join(lines)
def _stringify_header(self, options):
bits = []
lpad, rpad = self._get_padding_widths(options)
if options["border"]:
if options["hrules"] in (ALL, FRAME):
bits.append(self._hrule)
bits.append("\n")
if options["vrules"] in (ALL, FRAME):
bits.append(options["vertical_char"])
else:
bits.append(" ")
# For tables with no data or field names
if not self._field_names:
if options["vrules"] in (ALL, FRAME):
bits.append(options["vertical_char"])
else:
bits.append(" ")
for field, width, in zip(self._field_names, self._widths):
if options["fields"] and field not in options["fields"]:
continue
if self._header_style == "cap":
fieldname = field.capitalize()
elif self._header_style == "title":
fieldname = field.title()
elif self._header_style == "upper":
fieldname = field.upper()
elif self._header_style == "lower":
fieldname = field.lower()
else:
fieldname = field
bits.append(" " * lpad + self._justify(fieldname,
width, self._align[field]) + " " * rpad)
if options["border"]:
if options["vrules"] == ALL:
bits.append(options["vertical_char"])
else:
bits.append(" ")
# If vrules is FRAME, then we just appended a space at the end
# of the last field, when we really want a vertical character
if options["border"] and options["vrules"] == FRAME:
bits.pop()
bits.append(options["vertical_char"])
if options["border"] and options["hrules"] != NONE:
bits.append("\n")
bits.append(self._hrule)
return "".join(bits)
def _stringify_row(self, row, options):
for index, field, value, width, in zip(range(0, len(row)), self._field_names, row, self._widths):
# Enforce max widths
lines = value.split("\n")
new_lines = []
for line in lines:
if _str_block_width(line) > width:
line = textwrap.fill(line, width)
new_lines.append(line)
lines = new_lines
value = "\n".join(lines)
row[index] = value
row_height = 0
for c in row:
h = _get_size(c)[1]
if h > row_height:
row_height = h
bits = []
lpad, rpad = self._get_padding_widths(options)
for y in range(0, row_height):
bits.append([])
if options["border"]:
if options["vrules"] in (ALL, FRAME):
bits[y].append(self.vertical_char)
else:
bits[y].append(" ")
for field, value, width, in zip(self._field_names, row, self._widths):
valign = self._valign[field]
lines = value.split("\n")
dHeight = row_height - len(lines)
if dHeight:
if valign == "m":
lines = [""] * int(dHeight / 2) + lines + \
[""] * (dHeight - int(dHeight / 2))
elif valign == "b":
lines = [""] * dHeight + lines
else:
lines = lines + [""] * dHeight
y = 0
for l in lines:
if options["fields"] and field not in options["fields"]:
continue
bits[y].append(" " * lpad + self._justify(l,
width, self._align[field]) + " " * rpad)
if options["border"]:
if options["vrules"] == ALL:
bits[y].append(self.vertical_char)
else:
bits[y].append(" ")
y += 1
# If vrules is FRAME, then we just appended a space at the end
# of the last field, when we really want a vertical character
for y in range(0, row_height):
if options["border"] and options["vrules"] == FRAME:
bits[y].pop()
bits[y].append(options["vertical_char"])
if options["border"] and options["hrules"] == ALL:
bits[row_height - 1].append("\n")
bits[row_height - 1].append(self._hrule)
for y in range(0, row_height):
bits[y] = "".join(bits[y])
return "\n".join(bits)
def paginate(self, page_length=58, **kwargs):
pages = []
kwargs["start"] = kwargs.get("start", 0)
true_end = kwargs.get("end", self.rowcount)
while True:
kwargs["end"] = min(kwargs["start"] + page_length, true_end)
pages.append(self.get_string(**kwargs))
if kwargs["end"] == true_end:
break
kwargs["start"] += page_length
return "\f".join(pages)
##############################
# HTML STRING METHODS #
##############################
def get_html_string(self, **kwargs):
"""Return string representation of HTML formatted version of table in current state.
Arguments:
title - optional table title
start - index of first data row to include in output
end - index of last data row to include in output PLUS ONE (list slice style)
fields - names of fields (columns) to include
header - print a header showing field names (True or False)
border - print a border around the table (True or False)
hrules - controls printing of horizontal rules after rows. Allowed values: ALL, FRAME, HEADER, NONE
vrules - controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE
int_format - controls formatting of integer data
float_format - controls formatting of floating point data
padding_width - number of spaces on either side of column data (only used if left and right paddings are None)
left_padding_width - number of spaces on left hand side of column data
right_padding_width - number of spaces on right hand side of column data
sortby - name of field to sort rows by
sort_key - sorting key function, applied to data points before sorting
attributes - dictionary of name/value pairs to include as HTML attributes in the <table> tag
xhtml - print <br/> tags if True, <br> tags if false"""
options = self._get_options(kwargs)
if options["format"]:
string = self._get_formatted_html_string(options)
else:
string = self._get_simple_html_string(options)
return string
def _get_simple_html_string(self, options):
lines = []
if options["xhtml"]:
linebreak = "<br/>"
else:
linebreak = "<br>"
open_tag = list()
open_tag.append("<table")
if options["attributes"]:
for attr_name in options["attributes"]:
open_tag.append(" %s=\"%s\"" %
(attr_name, options["attributes"][attr_name]))
open_tag.append(">")
lines.append("".join(open_tag))
# Title
title = options["title"] or self._title
if title:
cols = len(options["fields"]) if options["fields"] else len(
self.field_names)
lines.append(" <tr>")
lines.append(" <td colspan=%d>%s</td>" % (cols, title))
lines.append(" </tr>")
# Headers
if options["header"]:
lines.append(" <tr>")
for field in self._field_names:
if options["fields"] and field not in options["fields"]:
continue
lines.append(" <th>%s</th>" %
escape(field).replace("\n", linebreak))
lines.append(" </tr>")
# Data
rows = self._get_rows(options)
formatted_rows = self._format_rows(rows, options)
for row in formatted_rows:
lines.append(" <tr>")
for field, datum in zip(self._field_names, row):
if options["fields"] and field not in options["fields"]:
continue
lines.append(" <td>%s</td>" %
escape(datum).replace("\n", linebreak))
lines.append(" </tr>")
lines.append("</table>")
return self._unicode("\n").join(lines)
def _get_formatted_html_string(self, options):
lines = []
lpad, rpad = self._get_padding_widths(options)
if options["xhtml"]:
linebreak = "<br/>"
else:
linebreak = "<br>"
open_tag = list()
open_tag.append("<table")
if options["border"]:
if options["hrules"] == ALL and options["vrules"] == ALL:
open_tag.append(" frame=\"box\" rules=\"all\"")
elif options["hrules"] == FRAME and options["vrules"] == FRAME:
open_tag.append(" frame=\"box\"")
elif options["hrules"] == FRAME and options["vrules"] == ALL:
open_tag.append(" frame=\"box\" rules=\"cols\"")
elif options["hrules"] == FRAME:
open_tag.append(" frame=\"hsides\"")
elif options["hrules"] == ALL:
open_tag.append(" frame=\"hsides\" rules=\"rows\"")
elif options["vrules"] == FRAME:
open_tag.append(" frame=\"vsides\"")
elif options["vrules"] == ALL:
open_tag.append(" frame=\"vsides\" rules=\"cols\"")
if options["attributes"]:
for attr_name in options["attributes"]:
open_tag.append(" %s=\"%s\"" %
(attr_name, options["attributes"][attr_name]))
open_tag.append(">")
lines.append("".join(open_tag))
# Title
title = options["title"] or self._title
if title:
cols = len(options["fields"]) if options["fields"] else len(
self.field_names)
lines.append(" <tr>")
lines.append(" <td colspan=%d>%s</td>" % (cols, title))
lines.append(" </tr>")
# Headers
if options["header"]:
lines.append(" <tr>")
for field in self._field_names:
if options["fields"] and field not in options["fields"]:
continue
lines.append(
" <th style=\"padding-left: %dem; padding-right: %dem; text-align: center\">%s</th>" % (
lpad, rpad, escape(field).replace("\n", linebreak)))
lines.append(" </tr>")
# Data
rows = self._get_rows(options)
formatted_rows = self._format_rows(rows, options)
aligns = []
valigns = []
for field in self._field_names:
aligns.append({"l": "left", "r": "right", "c": "center"}[
self._align[field]])
valigns.append({"t": "top", "m": "middle", "b": "bottom"}[
self._valign[field]])
for row in formatted_rows:
lines.append(" <tr>")
for field, datum, align, valign in zip(self._field_names, row, aligns, valigns):
if options["fields"] and field not in options["fields"]:
continue
lines.append(
" <td style=\"padding-left: %dem; padding-right: %dem; text-align: %s; vertical-align: %s\">%s</td>" % (
lpad, rpad, align, valign, escape(datum).replace("\n", linebreak)))
lines.append(" </tr>")
lines.append("</table>")
return self._unicode("\n").join(lines)
|
class PrettyTable(object):
def __init__(self, field_names=None, **kwargs):
'''Return a new PrettyTable instance
Arguments:
encoding - Unicode encoding scheme used to decode any encoded input
title - optional table title
field_names - list or tuple of field names
fields - list or tuple of field names to include in displays
start - index of first data row to include in output
end - index of last data row to include in output PLUS ONE (list slice style)
header - print a header showing field names (True or False)
header_style - stylisation to apply to field names in header ("cap", "title", "upper", "lower" or None)
border - print a border around the table (True or False)
hrules - controls printing of horizontal rules after rows. Allowed values: FRAME, HEADER, ALL, NONE
vrules - controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE
int_format - controls formatting of integer data
float_format - controls formatting of floating point data
min_table_width - minimum desired table width, in characters
max_table_width - maximum desired table width, in characters
padding_width - number of spaces on either side of column data (only used if left and right paddings are None)
left_padding_width - number of spaces on left hand side of column data
right_padding_width - number of spaces on right hand side of column data
vertical_char - single character string used to draw vertical lines
horizontal_char - single character string used to draw horizontal lines
junction_char - single character string used to draw line junctions
sortby - name of field to sort rows by
sort_key - sorting key function, applied to data points before sorting
valign - default valign for each row (None, "t", "m" or "b")
reversesort - True or False to sort in descending or ascending order
oldsortslice - Slice rows before sorting in the "old style" '''
pass
def _unicode(self, value):
pass
def _justify(self, text, width, align):
pass
def __getattr__(self, name):
pass
def __getitem__(self, index):
pass
def __str__(self):
pass
def __str__(self):
pass
def __unicode__(self):
pass
def _validate_option(self, option, val):
pass
def _validate_field_names(self, val):
pass
def _validate_header_style(self, val):
pass
def _validate_align(self, val):
pass
def _validate_valign(self, val):
pass
def _validate_nonnegative_int(self, name, val):
pass
def _validate_true_or_false(self, name, val):
pass
def _validate_int_format(self, name, val):
pass
def _validate_float_format(self, name, val):
pass
def _validate_function(self, name, val):
pass
def _validate_hrules(self, name, val):
pass
def _validate_vrules(self, name, val):
pass
def _validate_field_names(self, val):
pass
def _validate_all_field_names(self, name, val):
pass
def _validate_single_char(self, name, val):
pass
def _validate_attributes(self, name, val):
pass
@property
def field_names(self):
'''List or tuple of field names'''
pass
@field_names.setter
def field_names(self):
pass
@property
def align(self):
'''Controls alignment of fields
Arguments:
align - alignment, one of "l", "c", or "r" '''
pass
@align.setter
def align(self):
pass
@property
def valign(self):
'''Controls vertical alignment of fields
Arguments:
valign - vertical alignment, one of "t", "m", or "b" '''
pass
@valign.setter
def valign(self):
pass
@property
def max_width(self):
'''Controls maximum width of fields
Arguments:
max_width - maximum width integer'''
pass
@max_width.setter
def max_width(self):
pass
@property
def min_width(self):
'''Controls minimum width of fields
Arguments:
min_width - minimum width integer'''
pass
@min_width.setter
def min_width(self):
pass
@property
def min_table_width(self):
pass
@min_table_width.setter
def min_table_width(self):
pass
@property
def max_table_width(self):
pass
@max_table_width.setter
def max_table_width(self):
pass
@property
def fields(self):
'''List or tuple of field names to include in displays'''
pass
@fields.setter
def fields(self):
pass
@property
def title(self):
'''Optional table title
Arguments:
title - table title'''
pass
@title.setter
def title(self):
pass
@property
def start(self):
'''Start index of the range of rows to print
Arguments:
start - index of first data row to include in output'''
pass
@start.setter
def start(self):
pass
@property
def end(self):
'''End index of the range of rows to print
Arguments:
end - index of last data row to include in output PLUS ONE (list slice style)'''
pass
@end.setter
def end(self):
pass
@property
def sortby(self):
'''Name of field by which to sort rows
Arguments:
sortby - field name to sort by'''
pass
@sortby.setter
def sortby(self):
pass
@property
def reversesort(self):
'''Controls direction of sorting (ascending vs descending)
Arguments:
reveresort - set to True to sort by descending order, or False to sort by ascending order'''
pass
@reversesort.setter
def reversesort(self):
pass
@property
def sort_key(self):
'''Sorting key function, applied to data points before sorting
Arguments:
sort_key - a function which takes one argument and returns something to be sorted'''
pass
@sort_key.setter
def sort_key(self):
pass
@property
def header(self):
'''Controls printing of table header with field names
Arguments:
header - print a header showing field names (True or False)'''
pass
@header.setter
def header(self):
pass
@property
def header_style(self):
'''Controls stylisation applied to field names in header
Arguments:
header_style - stylisation to apply to field names in header ("cap", "title", "upper", "lower" or None)'''
pass
@header_style.setter
def header_style(self):
pass
@property
def border(self):
'''Controls printing of border around table
Arguments:
border - print a border around the table (True or False)'''
pass
@border.setter
def border(self):
pass
@property
def hrules(self):
'''Controls printing of horizontal rules after rows
Arguments:
hrules - horizontal rules style. Allowed values: FRAME, ALL, HEADER, NONE'''
pass
@hrules.setter
def hrules(self):
pass
@property
def vrules(self):
'''Controls printing of vertical rules between columns
Arguments:
vrules - vertical rules style. Allowed values: FRAME, ALL, NONE'''
pass
@vrules.setter
def vrules(self):
pass
@property
def int_format(self):
'''Controls formatting of integer data
Arguments:
int_format - integer format string'''
pass
@int_format.setter
def int_format(self):
pass
@property
def float_format(self):
'''Controls formatting of floating point data
Arguments:
float_format - floating point format string'''
pass
@float_format.setter
def float_format(self):
pass
@property
def padding_width(self):
'''The number of empty spaces between a column's edge and its content
Arguments:
padding_width - number of spaces, must be a positive integer'''
pass
@padding_width.setter
def padding_width(self):
pass
@property
def left_padding_width(self):
'''The number of empty spaces between a column's left edge and its content
Arguments:
left_padding - number of spaces, must be a positive integer'''
pass
@left_padding_width.setter
def left_padding_width(self):
pass
@property
def right_padding_width(self):
'''The number of empty spaces between a column's right edge and its content
Arguments:
right_padding - number of spaces, must be a positive integer'''
pass
@right_padding_width.setter
def right_padding_width(self):
pass
@property
def vertical_char(self):
'''The charcter used when printing table borders to draw vertical lines
Arguments:
vertical_char - single character string used to draw vertical lines'''
pass
@vertical_char.setter
def vertical_char(self):
pass
@property
def horizontal_char(self):
'''The charcter used when printing table borders to draw horizontal lines
Arguments:
horizontal_char - single character string used to draw horizontal lines'''
pass
@horizontal_char.setter
def horizontal_char(self):
pass
@property
def junction_char(self):
'''The charcter used when printing table borders to draw line junctions
Arguments:
junction_char - single character string used to draw line junctions'''
pass
@junction_char.setter
def junction_char(self):
pass
@property
def format(self):
'''Controls whether or not HTML tables are formatted to match styling options
Arguments:
format - True or False'''
pass
@format.setter
def format(self):
pass
@property
def print_empty(self):
'''Controls whether or not empty tables produce a header and frame or just an empty string
Arguments:
print_empty - True or False'''
pass
@print_empty.setter
def print_empty(self):
pass
@property
def attributes(self):
'''A dictionary of HTML attribute name/value pairs to be included in the <table> tag when printing HTML
Arguments:
attributes - dictionary of attributes'''
pass
@attributes.setter
def attributes(self):
pass
@property
def oldsortslice(self):
''' oldsortslice - Slice rows before sorting in the "old style" '''
pass
@oldsortslice.setter
def oldsortslice(self):
pass
def _get_options(self, kwargs):
pass
def set_style(self, style):
pass
def _set_default_style(self):
pass
def _set_msword_style(self):
pass
def _set_columns_style(self):
pass
def _set_random_style(self):
pass
def add_row(self, row):
'''Add a row to the table
Arguments:
row - row of data, should be a list with as many elements as the table
has fields'''
pass
def del_row(self, row_index):
'''Delete a row to the table
Arguments:
row_index - The index of the row you want to delete. Indexing starts at 0.'''
pass
def add_column(self, fieldname, column, align="c", valign="t"):
'''Add a column to the table.
Arguments:
fieldname - name of the field to contain the new column of data
column - column of data, should be a list with as many elements as the
table has rows
align - desired alignment for this column - "l" for left, "c" for centre and "r" for right
valign - desired vertical alignment for new columns - "t" for top, "m" for middle and "b" for bottom'''
pass
def clear_rows(self):
'''Delete all rows from the table but keep the current field names'''
pass
def clear_rows(self):
'''Delete all rows and field names from the table, maintaining nothing but styling options'''
pass
def copy(self):
pass
def _format_value(self, field, value):
pass
def _compute_table_width(self, options):
pass
def _compute_widths(self, rows, options):
pass
def _get_padding_widths(self, options):
pass
def _get_rows(self, options):
'''Return only those data rows that should be printed, based on slicing and sorting.
Arguments:
options - dictionary of option settings.'''
pass
def _format_row(self, row, options):
pass
def _format_rows(self, rows, options):
pass
def get_string(self, **kwargs):
'''Return string representation of table in current state.
Arguments:
title - optional table title
start - index of first data row to include in output
end - index of last data row to include in output PLUS ONE (list slice style)
fields - names of fields (columns) to include
header - print a header showing field names (True or False)
border - print a border around the table (True or False)
hrules - controls printing of horizontal rules after rows. Allowed values: ALL, FRAME, HEADER, NONE
vrules - controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE
int_format - controls formatting of integer data
float_format - controls formatting of floating point data
padding_width - number of spaces on either side of column data (only used if left and right paddings are None)
left_padding_width - number of spaces on left hand side of column data
right_padding_width - number of spaces on right hand side of column data
vertical_char - single character string used to draw vertical lines
horizontal_char - single character string used to draw horizontal lines
junction_char - single character string used to draw line junctions
sortby - name of field to sort rows by
sort_key - sorting key function, applied to data points before sorting
reversesort - True or False to sort in descending or ascending order
print empty - if True, stringify just the header for an empty table, if False return an empty string '''
pass
def _stringify_hrule(self, options):
pass
def _stringify_title(self, title, options):
pass
def _stringify_header(self, options):
pass
def _stringify_row(self, row, options):
pass
def paginate(self, page_length=58, **kwargs):
pass
def get_html_string(self, **kwargs):
'''Return string representation of HTML formatted version of table in current state.
Arguments:
title - optional table title
start - index of first data row to include in output
end - index of last data row to include in output PLUS ONE (list slice style)
fields - names of fields (columns) to include
header - print a header showing field names (True or False)
border - print a border around the table (True or False)
hrules - controls printing of horizontal rules after rows. Allowed values: ALL, FRAME, HEADER, NONE
vrules - controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE
int_format - controls formatting of integer data
float_format - controls formatting of floating point data
padding_width - number of spaces on either side of column data (only used if left and right paddings are None)
left_padding_width - number of spaces on left hand side of column data
right_padding_width - number of spaces on right hand side of column data
sortby - name of field to sort rows by
sort_key - sorting key function, applied to data points before sorting
attributes - dictionary of name/value pairs to include as HTML attributes in the <table> tag
xhtml - print <br/> tags if True, <br> tags if false'''
pass
def _get_simple_html_string(self, options):
pass
def _get_formatted_html_string(self, options):
pass
| 177 | 38 | 11 | 1 | 8 | 2 | 3 | 0.25 | 1 | 14 | 0 | 0 | 114 | 37 | 114 | 114 | 1,496 | 255 | 993 | 307 | 816 | 251 | 812 | 245 | 697 | 21 | 1 | 4 | 315 |
148,234 |
MacHu-GWU/pymongo_mate-project
|
MacHu-GWU_pymongo_mate-project/pymongo_mate/pkg/pandas_mate/pkg/prettytable/factory.py
|
pymongo_mate.pkg.pandas_mate.pkg.prettytable.factory.TableHandler
|
class TableHandler(HTMLParser):
def __init__(self, **kwargs):
HTMLParser.__init__(self)
self.kwargs = kwargs
self.tables = []
self.last_row = []
self.rows = []
self.max_row_width = 0
self.active = None
self.last_content = ""
self.is_last_row_header = False
self.colspan = 0
def handle_starttag(self, tag, attrs):
self.active = tag
if tag == "th":
self.is_last_row_header = True
for (key, value) in attrs:
if key == "colspan":
self.colspan = int(value)
def handle_endtag(self, tag):
if tag in ["th", "td"]:
stripped_content = self.last_content.strip()
self.last_row.append(stripped_content)
if self.colspan:
for i in range(1, self.colspan):
self.last_row.append("")
self.colspan = 0
if tag == "tr":
self.rows.append(
(self.last_row, self.is_last_row_header))
self.max_row_width = max(self.max_row_width, len(self.last_row))
self.last_row = []
self.is_last_row_header = False
if tag == "table":
table = self.generate_table(self.rows)
self.tables.append(table)
self.rows = []
self.last_content = " "
self.active = None
def handle_data(self, data):
self.last_content += data
def generate_table(self, rows):
"""
Generates from a list of rows a PrettyTable object.
"""
table = PrettyTable(**self.kwargs)
for row in self.rows:
if len(row[0]) < self.max_row_width:
appends = self.max_row_width - len(row[0])
for i in range(1, appends):
row[0].append("-")
if row[1] is True:
self.make_fields_unique(row[0])
table.field_names = row[0]
else:
table.add_row(row[0])
return table
def make_fields_unique(self, fields):
"""
iterates over the row and make each field unique
"""
for i in range(0, len(fields)):
for j in range(i + 1, len(fields)):
if fields[i] == fields[j]:
fields[j] += "'"
|
class TableHandler(HTMLParser):
def __init__(self, **kwargs):
pass
def handle_starttag(self, tag, attrs):
pass
def handle_endtag(self, tag):
pass
def handle_data(self, data):
pass
def generate_table(self, rows):
'''
Generates from a list of rows a PrettyTable object.
'''
pass
def make_fields_unique(self, fields):
'''
iterates over the row and make each field unique
'''
pass
| 7 | 2 | 11 | 0 | 10 | 1 | 4 | 0.1 | 1 | 3 | 1 | 0 | 6 | 9 | 6 | 44 | 72 | 7 | 59 | 26 | 52 | 6 | 57 | 26 | 50 | 6 | 2 | 3 | 21 |
148,235 |
MacHu-GWU/pymongo_mate-project
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_pymongo_mate-project/pymongo_mate/pkg/sixmini.py
|
pymongo_mate.pkg.sixmini.X
|
class X(object):
def __len__(self):
return 1 << 31
|
class X(object):
def __len__(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 4 | 1 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
148,236 |
MacHu-GWU/pymongo_mate-project
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_pymongo_mate-project/pymongo_mate/pkg/pandas_mate/pkg/rolex/template.py
|
pymongo_mate.pkg.pandas_mate.pkg.rolex.template.Unittest
|
class Unittest(unittest.TestCase):
def test_all(self):
for tpl, example in DateTemplatesAndExample:
d1 = datetime.strptime(example, tpl).date()
for tpl, example in DatetimeTemplatesAndExample:
dt1 = datetime.strptime(example, tpl)
|
class Unittest(unittest.TestCase):
def test_all(self):
pass
| 2 | 0 | 6 | 1 | 5 | 0 | 3 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 73 | 7 | 1 | 6 | 5 | 4 | 0 | 6 | 5 | 4 | 3 | 2 | 1 | 3 |
148,237 |
MacHu-GWU/pymongo_mate-project
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_pymongo_mate-project/pymongo_mate/pkg/pandas_mate/pkg/rolex/six.py
|
pymongo_mate.pkg.pandas_mate.pkg.rolex.six.with_metaclass.metaclass
|
class metaclass(meta):
def __new__(cls, name, this_bases, d):
return meta(name, bases, d)
|
class metaclass(meta):
def __new__(cls, name, this_bases, d):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 4 | 1 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
148,238 |
MacHu-GWU/pymongo_mate-project
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_pymongo_mate-project/pymongo_mate/pkg/pandas_mate/pkg/rolex/six.py
|
pymongo_mate.pkg.pandas_mate.pkg.rolex.six.Iterator
|
class Iterator(object):
def next(self):
return type(self).__next__(self)
|
class Iterator(object):
def next(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 4 | 1 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
148,239 |
MacHu-GWU/pymongo_mate-project
|
MacHu-GWU_pymongo_mate-project/pymongo_mate/query_builder.py
|
pymongo_mate.query_builder.Array
|
class Array(object):
"""Array query builder.
"""
@staticmethod
def element_match(filters):
"""
Test if any of items match the criterion.
Example::
data = [
{"_id": 1, "results": [ 82, 85, 88 ]},
{"_id": 2, "results": [ 75, 88, 89 ]},
]
filters = {"results": {"$elemMatch": {"$gte": 80, "$lt": 85 }}}
# equals to
filters = {
"results": Array.element_match({"$gte": 80, })
}
"""
return {"$elemMatch": filters}
@staticmethod
def include_all(items):
"""
Test if an array-like field include all these items.
Example::
{"tag": ["a", "b", "c"]} include all ["a", "c"]
"""
return {"$all": items}
@staticmethod
def include_any(items):
"""
Test if an array-like field include any of these items.
Example::
{"tag": ["a", "b", "c"]} include any of ["c", "d"]
"""
return {"$in": items}
@staticmethod
def exclude_all(items):
"""
Test if an array-like field doesn't include any of these items.
Example::
{"tag": ["a", "b", "c"]} doesn't include any of ["d", "e"]
"""
return {"$nin": items}
@staticmethod
def exclude_any(items):
"""
Test if an array-like field doesn't include at lease one of
these items.
Example::
{"tag": ["a", "b", "c"]} doesn't include "d" from ["c", "d"]
"""
return {"$not": {"$all": items}}
@staticmethod
def item_in(items):
"""
Single item is in item sets.
Example::
{"item_type": "Fruit"}, "Fruit" in ["Fruit", "Meat"]
"""
return {"$in": items}
@staticmethod
def item_not_in(items):
"""
Single item is not in item sets.
Example::
{"item_type": "Seafood"}, "Fruit" not in ["Fruit", "Meat"]
"""
return {"$nin": items}
@staticmethod
def size(n):
"""
Test if size of an array-like field is n.
Example::
filters = {"cart.items": Array.size(3)}
"""
return {"$size": n}
|
class Array(object):
'''Array query builder.
'''
@staticmethod
def element_match(filters):
'''
Test if any of items match the criterion.
Example::
data = [
{"_id": 1, "results": [ 82, 85, 88 ]},
{"_id": 2, "results": [ 75, 88, 89 ]},
]
filters = {"results": {"$elemMatch": {"$gte": 80, "$lt": 85 }}}
# equals to
filters = {
"results": Array.element_match({"$gte": 80, })
}
'''
pass
@staticmethod
def include_all(items):
'''
Test if an array-like field include all these items.
Example::
{"tag": ["a", "b", "c"]} include all ["a", "c"]
'''
pass
@staticmethod
def include_any(items):
'''
Test if an array-like field include any of these items.
Example::
{"tag": ["a", "b", "c"]} include any of ["c", "d"]
'''
pass
@staticmethod
def exclude_all(items):
'''
Test if an array-like field doesn't include any of these items.
Example::
{"tag": ["a", "b", "c"]} doesn't include any of ["d", "e"]
'''
pass
@staticmethod
def exclude_any(items):
'''
Test if an array-like field doesn't include at lease one of
these items.
Example::
{"tag": ["a", "b", "c"]} doesn't include "d" from ["c", "d"]
'''
pass
@staticmethod
def item_in(items):
'''
Single item is in item sets.
Example::
{"item_type": "Fruit"}, "Fruit" in ["Fruit", "Meat"]
'''
pass
@staticmethod
def item_not_in(items):
'''
Single item is not in item sets.
Example::
{"item_type": "Seafood"}, "Fruit" not in ["Fruit", "Meat"]
'''
pass
@staticmethod
def size(n):
'''
Test if size of an array-like field is n.
Example::
filters = {"cart.items": Array.size(3)}
'''
pass
| 17 | 9 | 10 | 2 | 2 | 6 | 1 | 2.04 | 1 | 0 | 0 | 0 | 0 | 0 | 8 | 8 | 101 | 25 | 25 | 17 | 8 | 51 | 17 | 9 | 8 | 1 | 1 | 0 | 8 |
148,240 |
MacHu-GWU/pymongo_mate-project
|
MacHu-GWU_pymongo_mate-project/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py
|
pymongo_mate.pkg.pandas_mate.pkg.rolex.UTC
|
class UTC(tzinfo):
"""UTC
"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
|
class UTC(tzinfo):
'''UTC
'''
def utcoffset(self, dt):
pass
def tzname(self, dt):
pass
def dst(self, dt):
pass
| 4 | 1 | 2 | 0 | 2 | 0 | 1 | 0.29 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 8 | 12 | 3 | 7 | 4 | 3 | 2 | 7 | 4 | 3 | 1 | 1 | 0 | 3 |
148,241 |
MacHu-GWU/pymongo_mate-project
|
MacHu-GWU_pymongo_mate-project/pymongo_mate/query_builder.py
|
pymongo_mate.query_builder.TypeCode
|
class TypeCode(object):
"""MongoDB Bson type code.
"""
Double = 1
String = 2
Object = 3
Array = 4
Binary_Data = 5
Undefined = 6 # Deprecated
ObjectId = 7
Boolean = 8
Date = 9
Null = 10
Regular_Expression = 11
DBPointer = 12 # Deprecated
JavaScript = 13
Symbol = 14 # Deprecated
JavaScript_with_Scope = 15
Integer32 = 16
TimeStamp = 17
Integer64 = 18
Decimal128 = 19
MinKey = -1
MaxKey = 127
Number = "number"
|
class TypeCode(object):
'''MongoDB Bson type code.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.22 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 0 | 23 | 23 | 22 | 5 | 23 | 23 | 22 | 0 | 1 | 0 | 0 |
148,242 |
MacHu-GWU/rolex-project
|
MacHu-GWU_rolex-project/tests/test_util.py
|
test_util.EasternTime
|
class EasternTime(tzinfo):
"""ET, Eastern Time, New York"""
def utcoffset(self, dt):
return timedelta(hours=-5)
def tzname(self, dt):
return "ET"
def dst(self, dt):
return timedelta(hours=-5)
|
class EasternTime(tzinfo):
'''ET, Eastern Time, New York'''
def utcoffset(self, dt):
pass
def tzname(self, dt):
pass
def dst(self, dt):
pass
| 4 | 1 | 2 | 0 | 2 | 0 | 1 | 0.14 | 1 | 1 | 0 | 0 | 3 | 0 | 3 | 8 | 11 | 3 | 7 | 4 | 3 | 1 | 7 | 4 | 3 | 1 | 1 | 0 | 3 |
148,243 |
MacHu-GWU/rolex-project
|
MacHu-GWU_rolex-project/tests/test_parse.py
|
test_parse.TestParser
|
class TestParser(object):
def test_str2date(self):
assert parser.str2date("9/21/2014") == date(2014, 9, 21)
assert parser._default_date_template == "%m/%d/%Y"
def test_str2date_error(self):
with raises(ValueError):
parser.str2date("1234567890")
def test_str2datetime(self):
assert parser.str2datetime(
"2014-07-13 8:12:34 PM") == datetime(2014, 7, 13, 20, 12, 34)
assert parser._default_datetime_template == "%Y-%m-%d %I:%M:%S %p"
assert parser.str2datetime.__name__ == "_str2datetime"
# When rolex failed to parse date time string,
# then start using dateutil.parser.parse
assert isinstance(parser.str2datetime("2000-01-01T00:00:00-5"),
datetime)
assert parser.str2datetime.__name__ == "parse"
# You can use .reset() method to restore default behavior
parser.reset()
assert parser.str2datetime.__name__ == "_str2datetime"
def test_performance(self):
"""Test Result:
- rolex is 4 ~ 5 times faster than dateutil.
- rolex support more data type, can take string, timestamp, date or datetime
Result::
10 item, rolex takes 0.000239 sec, dateutil takes 0.001051 sec.
100 item, rolex takes 0.002138 sec, dateutil takes 0.009662 sec.
1000 item, rolex takes 0.021126 sec, dateutil takes 0.097736 sec.
10000 item, rolex takes 0.214618 sec, dateutil takes 0.977337 sec.
"""
import time
import random
parser.reset()
tested_datetime_template_list = [
"%Y-%m-%d %I:%M:%S %p",
"%Y-%m-%dT%H:%M:%S.%fZ%Z",
"%a, %d %b %Y %H:%M:%S GMT",
]
tpl = random.choice(tested_datetime_template_list)
print("datetime format is: %r" % tpl)
for n in [10 ** n for n in range(2, 3 + 1)]:
data = [datetime.strftime(datetime.now(), tpl)
for _ in range(n)]
st = time.clock()
for datetime_str in data:
parser.str2datetime(datetime_str)
elapse1 = time.clock() - st
st = time.clock()
for datetime_str in data:
parse(datetime_str)
elapse2 = time.clock() - st
print("%s item, rolex takes %.6f sec, "
"dateutil takes %.6f sec, "
"rolex is %.2f times faster than dateutil." % (
n, elapse1, elapse2, elapse2 / elapse1))
def test_parse_date(self):
"""parse anything to date.
"""
assert parser.parse_date("12-1-2000") == date(2000, 12, 1)
with raises(TypeError):
parser.parse_date(None)
assert parser.parse_date(730120) == date(2000, 1, 1)
assert parser.parse_date(datetime(2000, 1, 1)) == date(2000, 1, 1)
assert parser.parse_date(date(2000, 1, 1)) == date(2000, 1, 1)
with raises(ValueError):
parser.parse_date([1, 2, 3])
def test_parse_datetime(self):
"""parse anything to datetime.
"""
assert parser.parse_datetime(
"2000-1-1 8:15:00") == datetime(2000, 1, 1, 8, 15)
with raises(TypeError):
parser.parse_datetime(None)
assert parser.parse_datetime(1) == datetime(1970, 1, 1, 0, 0, 1)
assert parser.parse_datetime(-1.0) == datetime(1969,
12, 31, 23, 59, 59)
assert parser.parse_datetime(
datetime(2000, 1, 1, 8, 30, 0)) == datetime(2000, 1, 1, 8, 30, 0)
assert parser.parse_datetime(date(2000, 1, 1)) == datetime(2000, 1, 1)
with raises(ValueError):
parser.parse_datetime([1, 2, 3])
|
class TestParser(object):
def test_str2date(self):
pass
def test_str2date_error(self):
pass
def test_str2datetime(self):
pass
def test_performance(self):
'''Test Result:
- rolex is 4 ~ 5 times faster than dateutil.
- rolex support more data type, can take string, timestamp, date or datetime
Result::
10 item, rolex takes 0.000239 sec, dateutil takes 0.001051 sec.
100 item, rolex takes 0.002138 sec, dateutil takes 0.009662 sec.
1000 item, rolex takes 0.021126 sec, dateutil takes 0.097736 sec.
10000 item, rolex takes 0.214618 sec, dateutil takes 0.977337 sec.
'''
pass
def test_parse_date(self):
'''parse anything to date.
'''
pass
def test_parse_datetime(self):
'''parse anything to datetime.
'''
pass
| 7 | 3 | 15 | 2 | 11 | 3 | 2 | 0.25 | 1 | 5 | 0 | 0 | 6 | 0 | 6 | 6 | 96 | 15 | 65 | 18 | 56 | 16 | 52 | 17 | 43 | 4 | 1 | 2 | 9 |
148,244 |
MacHu-GWU/rolex-project
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_rolex-project/rolex/pkg/sixmini.py
|
rolex.pkg.sixmini.X
|
class X(object):
def __len__(self):
return 1 << 31
|
class X(object):
def __len__(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 4 | 1 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
148,245 |
MacHu-GWU/rolex-project
|
MacHu-GWU_rolex-project/rolex/parse.py
|
rolex.parse.Parser
|
class Parser(object):
"""
datetime string parser.
"""
_default_date_template = date_template_list[0]
_default_datetime_template = datetime_template_list[0]
# --- Parse datetime ---
def str2date(self, date_str):
"""
Parse date from string.
If there's no template matches your string, Please go
https://github.com/MacHu-GWU/rolex-project/issues
submit your datetime string. I 'll update templates ASAP.
This method is faster than :meth:`dateutil.parser.parse`.
:param date_str: a string represent a date
:type date_str: str
:return: a date object
**中文文档**
从string解析date。首先尝试默认模板, 如果失败了, 则尝试所有的模板。
一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的
字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。
该方法要快过 :meth:`dateutil.parser.parse` 方法。
"""
# try default date template
try:
a_datetime = datetime.strptime(
date_str, self._default_date_template)
return a_datetime.date()
except:
pass
# try every date templates
for template in date_template_list:
try:
a_datetime = datetime.strptime(date_str, template)
self._default_date_template = template
return a_datetime.date()
except:
pass
# raise error
raise ValueError("Unable to parse date from: %r!" % date_str)
def _str2datetime(self, datetime_str):
"""
Parse datetime from string.
If there's no template matches your string, Please go
https://github.com/MacHu-GWU/rolex-project/issues
submit your datetime string. I 'll update templates ASAP.
This method is faster than :meth:`dateutil.parser.parse`.
:param datetime_str: a string represent a datetime
:type datetime_str: str
:return: a datetime object
**中文文档**
从string解析datetime。首先尝试默认模板, 如果失败了, 则尝试所有的模板。
一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的
字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。
该方法要快过 :meth:`dateutil.parser.parse` 方法。
为了防止模板库失败的情况, 程序设定在失败后自动一直启用
:meth:`dateutil.parser.parse` 进行解析。你可以调用 :meth:`Parser.reset()`
方法恢复默认设定。
"""
# try default datetime template
try:
a_datetime = datetime.strptime(
datetime_str, self._default_datetime_template)
return a_datetime
except:
pass
# try every datetime templates
for template in datetime_template_list:
try:
a_datetime = datetime.strptime(datetime_str, template)
self._default_datetime_template = template
return a_datetime
except:
pass
# raise error
a_datetime = parse(datetime_str)
self.str2datetime = parse
return a_datetime
str2datetime = _str2datetime
def reset(self):
"""
Reset :class:`Parser` behavior to default.
"""
self.str2datetime = self._str2datetime
def parse_date(self, value):
"""
A lazy method to parse anything to date.
If input data type is:
- string: parse date from it
- integer: use from ordinal
- datetime: use date part
- date: just return it
"""
if isinstance(value, sixmini.string_types):
return self.str2date(value)
elif value is None:
raise TypeError("Unable to parse date from %r" % value)
elif isinstance(value, sixmini.integer_types):
return date.fromordinal(value)
elif isinstance(value, datetime):
return value.date()
elif isinstance(value, date):
return value
else:
raise ValueError("Unable to parse date from %r" % value)
def parse_datetime(self, value):
"""
A lazy method to parse anything to datetime.
If input data type is:
- string: parse datetime from it
- integer: use from ordinal
- date: use date part and set hour, minute, second to zero
- datetime: just return it
"""
if isinstance(value, sixmini.string_types):
return self.str2datetime(value)
elif value is None:
raise TypeError("Unable to parse datetime from %r" % value)
elif isinstance(value, sixmini.integer_types):
return from_utctimestamp(value)
elif isinstance(value, float):
return from_utctimestamp(value)
elif isinstance(value, datetime):
return value
elif isinstance(value, date):
return datetime(value.year, value.month, value.day)
else:
raise ValueError("Unable to parse datetime from %r" % value)
|
class Parser(object):
'''
datetime string parser.
'''
def str2date(self, date_str):
'''
Parse date from string.
If there's no template matches your string, Please go
https://github.com/MacHu-GWU/rolex-project/issues
submit your datetime string. I 'll update templates ASAP.
This method is faster than :meth:`dateutil.parser.parse`.
:param date_str: a string represent a date
:type date_str: str
:return: a date object
**中文文档**
从string解析date。首先尝试默认模板, 如果失败了, 则尝试所有的模板。
一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的
字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。
该方法要快过 :meth:`dateutil.parser.parse` 方法。
'''
pass
def _str2datetime(self, datetime_str):
'''
Parse datetime from string.
If there's no template matches your string, Please go
https://github.com/MacHu-GWU/rolex-project/issues
submit your datetime string. I 'll update templates ASAP.
This method is faster than :meth:`dateutil.parser.parse`.
:param datetime_str: a string represent a datetime
:type datetime_str: str
:return: a datetime object
**中文文档**
从string解析datetime。首先尝试默认模板, 如果失败了, 则尝试所有的模板。
一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的
字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。
该方法要快过 :meth:`dateutil.parser.parse` 方法。
为了防止模板库失败的情况, 程序设定在失败后自动一直启用
:meth:`dateutil.parser.parse` 进行解析。你可以调用 :meth:`Parser.reset()`
方法恢复默认设定。
'''
pass
def reset(self):
'''
Reset :class:`Parser` behavior to default.
'''
pass
def parse_date(self, value):
'''
A lazy method to parse anything to date.
If input data type is:
- string: parse date from it
- integer: use from ordinal
- datetime: use date part
- date: just return it
'''
pass
def parse_datetime(self, value):
'''
A lazy method to parse anything to datetime.
If input data type is:
- string: parse datetime from it
- integer: use from ordinal
- date: use date part and set hour, minute, second to zero
- datetime: just return it
'''
pass
| 6 | 6 | 28 | 4 | 12 | 12 | 4 | 0.94 | 1 | 5 | 0 | 0 | 5 | 0 | 5 | 5 | 154 | 26 | 66 | 13 | 60 | 62 | 53 | 13 | 47 | 7 | 1 | 2 | 22 |
148,246 |
MacHu-GWU/single_file_module-project
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_single_file_module-project/tests/test_exception_mate.py
|
test_exception_mate.test_ExceptionHavingDefaultMessage.InputError
|
class InputError(em.ExceptionHavingDefaultMessage):
default_message = "array cannot be empty!"
|
class InputError(em.ExceptionHavingDefaultMessage):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 4 | 0 | 0 |
148,247 |
MacHu-GWU/single_file_module-project
|
MacHu-GWU_single_file_module-project/sfm/timer.py
|
sfm.timer.DateTimeTimer
|
class DateTimeTimer(BaseTimer):
"""
Usage::
# usage 1
>>> timer = DateTimeTimer(title="first measure") # start measuring immediately, title is optional
>>> # .. do something
>>> timer.end()
# usage 2
>>> with DateTimeTimer(title="second measure") as timer:
... # do something
>>> timer.end()
# usage 3
>>> timer = DateTimeTimer(start=False) # not start immediately
>>> # do something
>>> timer.start()
>>> # do someting
>>> timer.end()
# usage 4
>>> timer = DateTimeTimer(display=False) # disable auto display information
.. warning::
DateTimeTimer has around 0.003 seconds error in average for each measure.
"""
def _get_current_time(self):
return datetime.utcnow()
def _get_delta_in_sec(self, start, end):
return (end - start).total_seconds()
|
class DateTimeTimer(BaseTimer):
'''
Usage::
# usage 1
>>> timer = DateTimeTimer(title="first measure") # start measuring immediately, title is optional
>>> # .. do something
>>> timer.end()
# usage 2
>>> with DateTimeTimer(title="second measure") as timer:
... # do something
>>> timer.end()
# usage 3
>>> timer = DateTimeTimer(start=False) # not start immediately
>>> # do something
>>> timer.start()
>>> # do someting
>>> timer.end()
# usage 4
>>> timer = DateTimeTimer(display=False) # disable auto display information
.. warning::
DateTimeTimer has around 0.003 seconds error in average for each measure.
'''
def _get_current_time(self):
pass
def _get_delta_in_sec(self, start, end):
pass
| 3 | 1 | 2 | 0 | 2 | 0 | 1 | 4.2 | 1 | 1 | 0 | 0 | 2 | 0 | 2 | 11 | 34 | 8 | 5 | 3 | 2 | 21 | 5 | 3 | 2 | 1 | 2 | 0 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.