id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
47,700 | nccgroup/opinel | opinel/services/iam.py | delete_virtual_mfa_device | def delete_virtual_mfa_device(iam_client, mfa_serial):
"""
Delete a vritual MFA device given its serial number
:param iam_client:
:param mfa_serial:
:return:
"""
try:
printInfo('Deleting MFA device %s...' % mfa_serial)
iam_client.delete_virtual_mfa_device(SerialNumber = mfa_... | python | def delete_virtual_mfa_device(iam_client, mfa_serial):
"""
Delete a vritual MFA device given its serial number
:param iam_client:
:param mfa_serial:
:return:
"""
try:
printInfo('Deleting MFA device %s...' % mfa_serial)
iam_client.delete_virtual_mfa_device(SerialNumber = mfa_... | [
"def",
"delete_virtual_mfa_device",
"(",
"iam_client",
",",
"mfa_serial",
")",
":",
"try",
":",
"printInfo",
"(",
"'Deleting MFA device %s...'",
"%",
"mfa_serial",
")",
"iam_client",
".",
"delete_virtual_mfa_device",
"(",
"SerialNumber",
"=",
"mfa_serial",
")",
"excep... | Delete a vritual MFA device given its serial number
:param iam_client:
:param mfa_serial:
:return: | [
"Delete",
"a",
"vritual",
"MFA",
"device",
"given",
"its",
"serial",
"number"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/services/iam.py#L230-L244 |
47,701 | nccgroup/opinel | opinel/services/iam.py | init_group_category_regex | def init_group_category_regex(category_groups, category_regex_args):
"""
Initialize and compile regular expression for category groups
:param category_regex_args: List of string regex
:return: List of compiled regex
"""
category_regex = []
authorized_empt... | python | def init_group_category_regex(category_groups, category_regex_args):
"""
Initialize and compile regular expression for category groups
:param category_regex_args: List of string regex
:return: List of compiled regex
"""
category_regex = []
authorized_empt... | [
"def",
"init_group_category_regex",
"(",
"category_groups",
",",
"category_regex_args",
")",
":",
"category_regex",
"=",
"[",
"]",
"authorized_empty_regex",
"=",
"1",
"if",
"len",
"(",
"category_regex_args",
")",
"and",
"len",
"(",
"category_groups",
")",
"!=",
"l... | Initialize and compile regular expression for category groups
:param category_regex_args: List of string regex
:return: List of compiled regex | [
"Initialize",
"and",
"compile",
"regular",
"expression",
"for",
"category",
"groups"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/services/iam.py#L257-L280 |
47,702 | mixmastamyk/console | console/core.py | _HighColorPaletteBuilder._get_extended_palette_entry | def _get_extended_palette_entry(self, name, index, is_hex=False):
''' Compute extended entry, once on the fly. '''
values = None
is_fbterm = (env.TERM == 'fbterm') # sigh
if 'extended' in self._palette_support: # build entry
if is_hex:
index = str(find_near... | python | def _get_extended_palette_entry(self, name, index, is_hex=False):
''' Compute extended entry, once on the fly. '''
values = None
is_fbterm = (env.TERM == 'fbterm') # sigh
if 'extended' in self._palette_support: # build entry
if is_hex:
index = str(find_near... | [
"def",
"_get_extended_palette_entry",
"(",
"self",
",",
"name",
",",
"index",
",",
"is_hex",
"=",
"False",
")",
":",
"values",
"=",
"None",
"is_fbterm",
"=",
"(",
"env",
".",
"TERM",
"==",
"'fbterm'",
")",
"# sigh",
"if",
"'extended'",
"in",
"self",
".",... | Compute extended entry, once on the fly. | [
"Compute",
"extended",
"entry",
"once",
"on",
"the",
"fly",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/core.py#L180-L208 |
47,703 | mixmastamyk/console | console/core.py | _HighColorPaletteBuilder._get_true_palette_entry | def _get_true_palette_entry(self, name, digits):
''' Compute truecolor entry, once on the fly.
values must become sequence of decimal int strings: ('1', '2', '3')
'''
values = None
type_digits = type(digits)
is_fbterm = (env.TERM == 'fbterm') # sigh
if 'tru... | python | def _get_true_palette_entry(self, name, digits):
''' Compute truecolor entry, once on the fly.
values must become sequence of decimal int strings: ('1', '2', '3')
'''
values = None
type_digits = type(digits)
is_fbterm = (env.TERM == 'fbterm') # sigh
if 'tru... | [
"def",
"_get_true_palette_entry",
"(",
"self",
",",
"name",
",",
"digits",
")",
":",
"values",
"=",
"None",
"type_digits",
"=",
"type",
"(",
"digits",
")",
"is_fbterm",
"=",
"(",
"env",
".",
"TERM",
"==",
"'fbterm'",
")",
"# sigh",
"if",
"'truecolor'",
"... | Compute truecolor entry, once on the fly.
values must become sequence of decimal int strings: ('1', '2', '3') | [
"Compute",
"truecolor",
"entry",
"once",
"on",
"the",
"fly",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/core.py#L210-L259 |
47,704 | mixmastamyk/console | console/core.py | _HighColorPaletteBuilder._index_to_ansi_values | def _index_to_ansi_values(self, index):
''' Converts an palette index to the corresponding ANSI color.
Arguments:
index - an int (from 0-15)
Returns:
index as str in a list for compatibility with values.
'''
if self.__class__.__name__[0]... | python | def _index_to_ansi_values(self, index):
''' Converts an palette index to the corresponding ANSI color.
Arguments:
index - an int (from 0-15)
Returns:
index as str in a list for compatibility with values.
'''
if self.__class__.__name__[0]... | [
"def",
"_index_to_ansi_values",
"(",
"self",
",",
"index",
")",
":",
"if",
"self",
".",
"__class__",
".",
"__name__",
"[",
"0",
"]",
"==",
"'F'",
":",
"# Foreground",
"if",
"index",
"<",
"8",
":",
"index",
"+=",
"ANSI_FG_LO_BASE",
"else",
":",
"index",
... | Converts an palette index to the corresponding ANSI color.
Arguments:
index - an int (from 0-15)
Returns:
index as str in a list for compatibility with values. | [
"Converts",
"an",
"palette",
"index",
"to",
"the",
"corresponding",
"ANSI",
"color",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/core.py#L287-L305 |
47,705 | mixmastamyk/console | console/core.py | _HighColorPaletteBuilder._create_entry | def _create_entry(self, name, values, fbterm=False):
''' Render first values as string and place as first code,
save, and return attr.
'''
if fbterm:
attr = _PaletteEntryFBTerm(self, name.upper(), ';'.join(values))
else:
attr = _PaletteEntry(self, name... | python | def _create_entry(self, name, values, fbterm=False):
''' Render first values as string and place as first code,
save, and return attr.
'''
if fbterm:
attr = _PaletteEntryFBTerm(self, name.upper(), ';'.join(values))
else:
attr = _PaletteEntry(self, name... | [
"def",
"_create_entry",
"(",
"self",
",",
"name",
",",
"values",
",",
"fbterm",
"=",
"False",
")",
":",
"if",
"fbterm",
":",
"attr",
"=",
"_PaletteEntryFBTerm",
"(",
"self",
",",
"name",
".",
"upper",
"(",
")",
",",
"';'",
".",
"join",
"(",
"values",... | Render first values as string and place as first code,
save, and return attr. | [
"Render",
"first",
"values",
"as",
"string",
"and",
"place",
"as",
"first",
"code",
"save",
"and",
"return",
"attr",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/core.py#L307-L316 |
47,706 | mixmastamyk/console | console/core.py | _LineWriter.write | def write(self, data):
''' This could be a bit less clumsy. '''
if data == '\n': # print does this
return self.stream.write(data)
else:
bytes_ = 0
for line in data.splitlines(True):
nl = ''
if line.endswith('\n'): # mv nl to e... | python | def write(self, data):
''' This could be a bit less clumsy. '''
if data == '\n': # print does this
return self.stream.write(data)
else:
bytes_ = 0
for line in data.splitlines(True):
nl = ''
if line.endswith('\n'): # mv nl to e... | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
"==",
"'\\n'",
":",
"# print does this",
"return",
"self",
".",
"stream",
".",
"write",
"(",
"data",
")",
"else",
":",
"bytes_",
"=",
"0",
"for",
"line",
"in",
"data",
".",
"splitlines... | This could be a bit less clumsy. | [
"This",
"could",
"be",
"a",
"bit",
"less",
"clumsy",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/core.py#L334-L348 |
47,707 | mixmastamyk/console | console/core.py | _PaletteEntry.set_output | def set_output(self, outfile):
''' Set's the output file, currently only useful with context-managers.
Note:
This function is experimental and may not last.
'''
if self._orig_stdout: # restore Usted
sys.stdout = self._orig_stdout
self._stream = ... | python | def set_output(self, outfile):
''' Set's the output file, currently only useful with context-managers.
Note:
This function is experimental and may not last.
'''
if self._orig_stdout: # restore Usted
sys.stdout = self._orig_stdout
self._stream = ... | [
"def",
"set_output",
"(",
"self",
",",
"outfile",
")",
":",
"if",
"self",
".",
"_orig_stdout",
":",
"# restore Usted",
"sys",
".",
"stdout",
"=",
"self",
".",
"_orig_stdout",
"self",
".",
"_stream",
"=",
"outfile",
"sys",
".",
"stdout",
"=",
"_LineWriter",... | Set's the output file, currently only useful with context-managers.
Note:
This function is experimental and may not last. | [
"Set",
"s",
"the",
"output",
"file",
"currently",
"only",
"useful",
"with",
"context",
"-",
"managers",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/core.py#L468-L478 |
47,708 | mixmastamyk/console | console/progress.py | ProgressBar._render | def _render(self):
''' Standard rendering of bar graph. '''
cm_chars = self._comp_style(self.icons[_ic] * self._num_complete_chars)
em_chars = self._empt_style(self.icons[_ie] * self._num_empty_chars)
return f'{self._first}{cm_chars}{em_chars}{self._last} {self._lbl}' | python | def _render(self):
''' Standard rendering of bar graph. '''
cm_chars = self._comp_style(self.icons[_ic] * self._num_complete_chars)
em_chars = self._empt_style(self.icons[_ie] * self._num_empty_chars)
return f'{self._first}{cm_chars}{em_chars}{self._last} {self._lbl}' | [
"def",
"_render",
"(",
"self",
")",
":",
"cm_chars",
"=",
"self",
".",
"_comp_style",
"(",
"self",
".",
"icons",
"[",
"_ic",
"]",
"*",
"self",
".",
"_num_complete_chars",
")",
"em_chars",
"=",
"self",
".",
"_empt_style",
"(",
"self",
".",
"icons",
"[",... | Standard rendering of bar graph. | [
"Standard",
"rendering",
"of",
"bar",
"graph",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/progress.py#L298-L302 |
47,709 | mixmastamyk/console | console/progress.py | ProgressBar._render_internal_label | def _render_internal_label(self):
''' Render with a label inside the bar graph. '''
ncc = self._num_complete_chars
bar = self._lbl.center(self.iwidth)
cm_chars = self._comp_style(bar[:ncc])
em_chars = self._empt_style(bar[ncc:])
return f'{self._first}{cm_chars}{em_chars}{... | python | def _render_internal_label(self):
''' Render with a label inside the bar graph. '''
ncc = self._num_complete_chars
bar = self._lbl.center(self.iwidth)
cm_chars = self._comp_style(bar[:ncc])
em_chars = self._empt_style(bar[ncc:])
return f'{self._first}{cm_chars}{em_chars}{... | [
"def",
"_render_internal_label",
"(",
"self",
")",
":",
"ncc",
"=",
"self",
".",
"_num_complete_chars",
"bar",
"=",
"self",
".",
"_lbl",
".",
"center",
"(",
"self",
".",
"iwidth",
")",
"cm_chars",
"=",
"self",
".",
"_comp_style",
"(",
"bar",
"[",
":",
... | Render with a label inside the bar graph. | [
"Render",
"with",
"a",
"label",
"inside",
"the",
"bar",
"graph",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/progress.py#L304-L310 |
47,710 | mixmastamyk/console | console/progress.py | HiDefProgressBar._get_ncc | def _get_ncc(self, width, ratio):
''' Get the number of complete chars.
This one figures the remainder for the partial char as well.
'''
sub_chars = round(width * ratio * self.partial_chars_len)
ncc, self.remainder = divmod(sub_chars, self.partial_chars_len)
return n... | python | def _get_ncc(self, width, ratio):
''' Get the number of complete chars.
This one figures the remainder for the partial char as well.
'''
sub_chars = round(width * ratio * self.partial_chars_len)
ncc, self.remainder = divmod(sub_chars, self.partial_chars_len)
return n... | [
"def",
"_get_ncc",
"(",
"self",
",",
"width",
",",
"ratio",
")",
":",
"sub_chars",
"=",
"round",
"(",
"width",
"*",
"ratio",
"*",
"self",
".",
"partial_chars_len",
")",
"ncc",
",",
"self",
".",
"remainder",
"=",
"divmod",
"(",
"sub_chars",
",",
"self",... | Get the number of complete chars.
This one figures the remainder for the partial char as well. | [
"Get",
"the",
"number",
"of",
"complete",
"chars",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/progress.py#L335-L342 |
47,711 | mixmastamyk/console | console/progress.py | HiDefProgressBar._render | def _render(self):
''' figure partial character '''
p_char = ''
if not self.done and self.remainder:
p_style = self._comp_style
if self.partial_char_extra_style:
if p_style is str:
p_style = self.partial_char_extra_style
... | python | def _render(self):
''' figure partial character '''
p_char = ''
if not self.done and self.remainder:
p_style = self._comp_style
if self.partial_char_extra_style:
if p_style is str:
p_style = self.partial_char_extra_style
... | [
"def",
"_render",
"(",
"self",
")",
":",
"p_char",
"=",
"''",
"if",
"not",
"self",
".",
"done",
"and",
"self",
".",
"remainder",
":",
"p_style",
"=",
"self",
".",
"_comp_style",
"if",
"self",
".",
"partial_char_extra_style",
":",
"if",
"p_style",
"is",
... | figure partial character | [
"figure",
"partial",
"character"
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/progress.py#L344-L360 |
47,712 | nccgroup/opinel | opinel/utils/threads.py | thread_work | def thread_work(targets, function, params = {}, num_threads = 0):
"""
Generic multithreading helper
:param targets:
:param function:
:param params:
:param num_threads:
:return:
"""
q = Queue(maxsize=0)
if not num_threads:
num_threads = len(targets)
for i in range(nu... | python | def thread_work(targets, function, params = {}, num_threads = 0):
"""
Generic multithreading helper
:param targets:
:param function:
:param params:
:param num_threads:
:return:
"""
q = Queue(maxsize=0)
if not num_threads:
num_threads = len(targets)
for i in range(nu... | [
"def",
"thread_work",
"(",
"targets",
",",
"function",
",",
"params",
"=",
"{",
"}",
",",
"num_threads",
"=",
"0",
")",
":",
"q",
"=",
"Queue",
"(",
"maxsize",
"=",
"0",
")",
"if",
"not",
"num_threads",
":",
"num_threads",
"=",
"len",
"(",
"targets",... | Generic multithreading helper
:param targets:
:param function:
:param params:
:param num_threads:
:return: | [
"Generic",
"multithreading",
"helper"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/threads.py#L15-L35 |
47,713 | nccgroup/opinel | opinel/utils/threads.py | threaded_per_region | def threaded_per_region(q, params):
"""
Helper for multithreading on a per-region basis
:param q:
:param params:
:return:
"""
while True:
try:
params['region'] = q.get()
method = params['method']
method(params)
except Exception as e:
... | python | def threaded_per_region(q, params):
"""
Helper for multithreading on a per-region basis
:param q:
:param params:
:return:
"""
while True:
try:
params['region'] = q.get()
method = params['method']
method(params)
except Exception as e:
... | [
"def",
"threaded_per_region",
"(",
"q",
",",
"params",
")",
":",
"while",
"True",
":",
"try",
":",
"params",
"[",
"'region'",
"]",
"=",
"q",
".",
"get",
"(",
")",
"method",
"=",
"params",
"[",
"'method'",
"]",
"method",
"(",
"params",
")",
"except",
... | Helper for multithreading on a per-region basis
:param q:
:param params:
:return: | [
"Helper",
"for",
"multithreading",
"on",
"a",
"per",
"-",
"region",
"basis"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/threads.py#L38-L55 |
47,714 | mixmastamyk/console | console/screen.py | Screen.location | def location(self, x=None, y=None):
''' Temporarily move the cursor, perform work, and return to the
previous location.
::
with screen.location(40, 20):
print('Hello, world!')
'''
stream = self._stream
stream.write(self.save_p... | python | def location(self, x=None, y=None):
''' Temporarily move the cursor, perform work, and return to the
previous location.
::
with screen.location(40, 20):
print('Hello, world!')
'''
stream = self._stream
stream.write(self.save_p... | [
"def",
"location",
"(",
"self",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
")",
":",
"stream",
"=",
"self",
".",
"_stream",
"stream",
".",
"write",
"(",
"self",
".",
"save_pos",
")",
"# cursor position",
"if",
"x",
"is",
"not",
"None",
"and",
"y... | Temporarily move the cursor, perform work, and return to the
previous location.
::
with screen.location(40, 20):
print('Hello, world!') | [
"Temporarily",
"move",
"the",
"cursor",
"perform",
"work",
"and",
"return",
"to",
"the",
"previous",
"location",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/screen.py#L143-L167 |
47,715 | mixmastamyk/console | console/screen.py | Screen.fullscreen | def fullscreen(self):
''' Context Manager that enters full-screen mode and restores normal
mode on exit.
::
with screen.fullscreen():
print('Hello, world!')
'''
stream = self._stream
stream.write(self.alt_screen_enable)
... | python | def fullscreen(self):
''' Context Manager that enters full-screen mode and restores normal
mode on exit.
::
with screen.fullscreen():
print('Hello, world!')
'''
stream = self._stream
stream.write(self.alt_screen_enable)
... | [
"def",
"fullscreen",
"(",
"self",
")",
":",
"stream",
"=",
"self",
".",
"_stream",
"stream",
".",
"write",
"(",
"self",
".",
"alt_screen_enable",
")",
"stream",
".",
"write",
"(",
"str",
"(",
"self",
".",
"save_title",
"(",
"0",
")",
")",
")",
"# 0 =... | Context Manager that enters full-screen mode and restores normal
mode on exit.
::
with screen.fullscreen():
print('Hello, world!') | [
"Context",
"Manager",
"that",
"enters",
"full",
"-",
"screen",
"mode",
"and",
"restores",
"normal",
"mode",
"on",
"exit",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/screen.py#L170-L188 |
47,716 | mixmastamyk/console | console/screen.py | Screen.hidden_cursor | def hidden_cursor(self):
''' Context Manager that hides the cursor and restores it on exit.
::
with screen.hidden_cursor():
print('Clandestine activity…')
'''
stream = self._stream
stream.write(self.hide_cursor)
stream.flush()
... | python | def hidden_cursor(self):
''' Context Manager that hides the cursor and restores it on exit.
::
with screen.hidden_cursor():
print('Clandestine activity…')
'''
stream = self._stream
stream.write(self.hide_cursor)
stream.flush()
... | [
"def",
"hidden_cursor",
"(",
"self",
")",
":",
"stream",
"=",
"self",
".",
"_stream",
"stream",
".",
"write",
"(",
"self",
".",
"hide_cursor",
")",
"stream",
".",
"flush",
"(",
")",
"try",
":",
"yield",
"self",
"finally",
":",
"stream",
".",
"write",
... | Context Manager that hides the cursor and restores it on exit.
::
with screen.hidden_cursor():
print('Clandestine activity…') | [
"Context",
"Manager",
"that",
"hides",
"the",
"cursor",
"and",
"restores",
"it",
"on",
"exit",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/screen.py#L191-L206 |
47,717 | mapleoin/undecorated | undecorated.py | undecorated | def undecorated(o):
"""Remove all decorators from a function, method or class"""
# class decorator
if type(o) is type:
return o
try:
# python2
closure = o.func_closure
except AttributeError:
pass
try:
# python3
closure = o.__closure__
except ... | python | def undecorated(o):
"""Remove all decorators from a function, method or class"""
# class decorator
if type(o) is type:
return o
try:
# python2
closure = o.func_closure
except AttributeError:
pass
try:
# python3
closure = o.__closure__
except ... | [
"def",
"undecorated",
"(",
"o",
")",
":",
"# class decorator",
"if",
"type",
"(",
"o",
")",
"is",
"type",
":",
"return",
"o",
"try",
":",
"# python2",
"closure",
"=",
"o",
".",
"func_closure",
"except",
"AttributeError",
":",
"pass",
"try",
":",
"# pytho... | Remove all decorators from a function, method or class | [
"Remove",
"all",
"decorators",
"from",
"a",
"function",
"method",
"or",
"class"
] | 79843ce8e8466dbbd26a3626b148fea7f2b26ab1 | https://github.com/mapleoin/undecorated/blob/79843ce8e8466dbbd26a3626b148fea7f2b26ab1/undecorated.py#L22-L60 |
47,718 | nccgroup/opinel | opinel/utils/credentials.py | assume_role | def assume_role(role_name, credentials, role_arn, role_session_name, silent = False):
"""
Assume role and save credentials
:param role_name:
:param credentials:
:param role_arn:
:param role_session_name:
:param silent:
:return:
"""
external_id = credentials.pop('ExternalId') if ... | python | def assume_role(role_name, credentials, role_arn, role_session_name, silent = False):
"""
Assume role and save credentials
:param role_name:
:param credentials:
:param role_arn:
:param role_session_name:
:param silent:
:return:
"""
external_id = credentials.pop('ExternalId') if ... | [
"def",
"assume_role",
"(",
"role_name",
",",
"credentials",
",",
"role_arn",
",",
"role_session_name",
",",
"silent",
"=",
"False",
")",
":",
"external_id",
"=",
"credentials",
".",
"pop",
"(",
"'ExternalId'",
")",
"if",
"'ExternalId'",
"in",
"credentials",
"e... | Assume role and save credentials
:param role_name:
:param credentials:
:param role_arn:
:param role_session_name:
:param silent:
:return: | [
"Assume",
"role",
"and",
"save",
"credentials"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L57-L93 |
47,719 | nccgroup/opinel | opinel/utils/credentials.py | generate_password | def generate_password(length=16):
"""
Generate a password using random characters from uppercase, lowercase, digits, and symbols
:param length: Length of the password to be generated
:return: The random password
"""
chars = string.ascii_letters + ... | python | def generate_password(length=16):
"""
Generate a password using random characters from uppercase, lowercase, digits, and symbols
:param length: Length of the password to be generated
:return: The random password
"""
chars = string.ascii_letters + ... | [
"def",
"generate_password",
"(",
"length",
"=",
"16",
")",
":",
"chars",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
"+",
"'!@#$%^&*()_+-=[]{};:,<.>?|'",
"modulus",
"=",
"len",
"(",
"chars",
")",
"pchars",
"=",
"os",
".",
"urandom",
... | Generate a password using random characters from uppercase, lowercase, digits, and symbols
:param length: Length of the password to be generated
:return: The random password | [
"Generate",
"a",
"password",
"using",
"random",
"characters",
"from",
"uppercase",
"lowercase",
"digits",
"and",
"symbols"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L129-L142 |
47,720 | nccgroup/opinel | opinel/utils/credentials.py | init_sts_session | def init_sts_session(profile_name, credentials, duration = 28800, session_name = None, save_creds = True):
"""
Fetch STS credentials
:param profile_name:
:param credentials:
:param duration:
:param session_name:
:param save_creds:
:return:
"""
# Set STS arguments
sts_args = ... | python | def init_sts_session(profile_name, credentials, duration = 28800, session_name = None, save_creds = True):
"""
Fetch STS credentials
:param profile_name:
:param credentials:
:param duration:
:param session_name:
:param save_creds:
:return:
"""
# Set STS arguments
sts_args = ... | [
"def",
"init_sts_session",
"(",
"profile_name",
",",
"credentials",
",",
"duration",
"=",
"28800",
",",
"session_name",
"=",
"None",
",",
"save_creds",
"=",
"True",
")",
":",
"# Set STS arguments",
"sts_args",
"=",
"{",
"'DurationSeconds'",
":",
"duration",
"}",... | Fetch STS credentials
:param profile_name:
:param credentials:
:param duration:
:param session_name:
:param save_creds:
:return: | [
"Fetch",
"STS",
"credentials"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L155-L187 |
47,721 | nccgroup/opinel | opinel/utils/credentials.py | read_creds_from_aws_credentials_file | def read_creds_from_aws_credentials_file(profile_name, credentials_file = aws_credentials_file):
"""
Read credentials from AWS config file
:param profile_name:
:param credentials_file:
:return:
"""
credentials = init_creds()
profile_found = False
try:
# Make sure the ~.aws f... | python | def read_creds_from_aws_credentials_file(profile_name, credentials_file = aws_credentials_file):
"""
Read credentials from AWS config file
:param profile_name:
:param credentials_file:
:return:
"""
credentials = init_creds()
profile_found = False
try:
# Make sure the ~.aws f... | [
"def",
"read_creds_from_aws_credentials_file",
"(",
"profile_name",
",",
"credentials_file",
"=",
"aws_credentials_file",
")",
":",
"credentials",
"=",
"init_creds",
"(",
")",
"profile_found",
"=",
"False",
"try",
":",
"# Make sure the ~.aws folder exists",
"if",
"not",
... | Read credentials from AWS config file
:param profile_name:
:param credentials_file:
:return: | [
"Read",
"credentials",
"from",
"AWS",
"config",
"file"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L190-L227 |
47,722 | nccgroup/opinel | opinel/utils/credentials.py | read_creds_from_csv | def read_creds_from_csv(filename):
"""
Read credentials from a CSV file
:param filename:
:return:
"""
key_id = None
secret = None
mfa_serial = None
secret_next = False
with open(filename, 'rt') as csvfile:
for i, line in enumerate(csvfile):
values = line.spli... | python | def read_creds_from_csv(filename):
"""
Read credentials from a CSV file
:param filename:
:return:
"""
key_id = None
secret = None
mfa_serial = None
secret_next = False
with open(filename, 'rt') as csvfile:
for i, line in enumerate(csvfile):
values = line.spli... | [
"def",
"read_creds_from_csv",
"(",
"filename",
")",
":",
"key_id",
"=",
"None",
"secret",
"=",
"None",
"mfa_serial",
"=",
"None",
"secret_next",
"=",
"False",
"with",
"open",
"(",
"filename",
",",
"'rt'",
")",
"as",
"csvfile",
":",
"for",
"i",
",",
"line... | Read credentials from a CSV file
:param filename:
:return: | [
"Read",
"credentials",
"from",
"a",
"CSV",
"file"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L230-L253 |
47,723 | nccgroup/opinel | opinel/utils/credentials.py | read_creds_from_environment_variables | def read_creds_from_environment_variables():
"""
Read credentials from environment variables
:return:
"""
creds = init_creds()
# Check environment variables
if 'AWS_ACCESS_KEY_ID' in os.environ and 'AWS_SECRET_ACCESS_KEY' in os.environ:
creds['AccessKeyId'] = os.environ['AWS_ACCESS_... | python | def read_creds_from_environment_variables():
"""
Read credentials from environment variables
:return:
"""
creds = init_creds()
# Check environment variables
if 'AWS_ACCESS_KEY_ID' in os.environ and 'AWS_SECRET_ACCESS_KEY' in os.environ:
creds['AccessKeyId'] = os.environ['AWS_ACCESS_... | [
"def",
"read_creds_from_environment_variables",
"(",
")",
":",
"creds",
"=",
"init_creds",
"(",
")",
"# Check environment variables",
"if",
"'AWS_ACCESS_KEY_ID'",
"in",
"os",
".",
"environ",
"and",
"'AWS_SECRET_ACCESS_KEY'",
"in",
"os",
".",
"environ",
":",
"creds",
... | Read credentials from environment variables
:return: | [
"Read",
"credentials",
"from",
"environment",
"variables"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L295-L308 |
47,724 | nccgroup/opinel | opinel/utils/credentials.py | read_profile_from_environment_variables | def read_profile_from_environment_variables():
"""
Read profiles from env
:return:
"""
role_arn = os.environ.get('AWS_ROLE_ARN', None)
external_id = os.environ.get('AWS_EXTERNAL_ID', None)
return role_arn, external_id | python | def read_profile_from_environment_variables():
"""
Read profiles from env
:return:
"""
role_arn = os.environ.get('AWS_ROLE_ARN', None)
external_id = os.environ.get('AWS_EXTERNAL_ID', None)
return role_arn, external_id | [
"def",
"read_profile_from_environment_variables",
"(",
")",
":",
"role_arn",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'AWS_ROLE_ARN'",
",",
"None",
")",
"external_id",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'AWS_EXTERNAL_ID'",
",",
"None",
")",
"re... | Read profiles from env
:return: | [
"Read",
"profiles",
"from",
"env"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L311-L319 |
47,725 | nccgroup/opinel | opinel/utils/credentials.py | read_profile_from_aws_config_file | def read_profile_from_aws_config_file(profile_name, config_file = aws_config_file):
"""
Read profiles from AWS config file
:param profile_name:
:param config_file:
:return:
"""
role_arn = None
source_profile = 'default'
mfa_serial = None
profile_found = False
external_id = N... | python | def read_profile_from_aws_config_file(profile_name, config_file = aws_config_file):
"""
Read profiles from AWS config file
:param profile_name:
:param config_file:
:return:
"""
role_arn = None
source_profile = 'default'
mfa_serial = None
profile_found = False
external_id = N... | [
"def",
"read_profile_from_aws_config_file",
"(",
"profile_name",
",",
"config_file",
"=",
"aws_config_file",
")",
":",
"role_arn",
"=",
"None",
"source_profile",
"=",
"'default'",
"mfa_serial",
"=",
"None",
"profile_found",
"=",
"False",
"external_id",
"=",
"None",
... | Read profiles from AWS config file
:param profile_name:
:param config_file:
:return: | [
"Read",
"profiles",
"from",
"AWS",
"config",
"file"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L322-L358 |
47,726 | nccgroup/opinel | opinel/utils/credentials.py | write_creds_to_aws_credentials_file | def write_creds_to_aws_credentials_file(profile_name, credentials, credentials_file = aws_credentials_file):
"""
Write credentials to AWS config file
:param profile_name:
:param credentials:
:param credentials_file:
:return:
"""
profile_found = False
profile_ever_found = False
s... | python | def write_creds_to_aws_credentials_file(profile_name, credentials, credentials_file = aws_credentials_file):
"""
Write credentials to AWS config file
:param profile_name:
:param credentials:
:param credentials_file:
:return:
"""
profile_found = False
profile_ever_found = False
s... | [
"def",
"write_creds_to_aws_credentials_file",
"(",
"profile_name",
",",
"credentials",
",",
"credentials_file",
"=",
"aws_credentials_file",
")",
":",
"profile_found",
"=",
"False",
"profile_ever_found",
"=",
"False",
"session_token_written",
"=",
"False",
"security_token_w... | Write credentials to AWS config file
:param profile_name:
:param credentials:
:param credentials_file:
:return: | [
"Write",
"credentials",
"to",
"AWS",
"config",
"file"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L373-L437 |
47,727 | nccgroup/opinel | opinel/utils/credentials.py | complete_profile | def complete_profile(f, credentials, session_token_written, mfa_serial_written):
"""
Append session token and mfa serial if needed
:param f:
:param credentials:
:param session_token_written:
:param mfa_serial_written:
:return:
"""
session_token = credentials['SessionToken'] if 'Sess... | python | def complete_profile(f, credentials, session_token_written, mfa_serial_written):
"""
Append session token and mfa serial if needed
:param f:
:param credentials:
:param session_token_written:
:param mfa_serial_written:
:return:
"""
session_token = credentials['SessionToken'] if 'Sess... | [
"def",
"complete_profile",
"(",
"f",
",",
"credentials",
",",
"session_token_written",
",",
"mfa_serial_written",
")",
":",
"session_token",
"=",
"credentials",
"[",
"'SessionToken'",
"]",
"if",
"'SessionToken'",
"in",
"credentials",
"else",
"None",
"mfa_serial",
"=... | Append session token and mfa serial if needed
:param f:
:param credentials:
:param session_token_written:
:param mfa_serial_written:
:return: | [
"Append",
"session",
"token",
"and",
"mfa",
"serial",
"if",
"needed"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L440-L455 |
47,728 | nccgroup/opinel | opinel/services/cloudformation.py | get_stackset_ready_accounts | def get_stackset_ready_accounts(credentials, account_ids, quiet=True):
"""
Verify which AWS accounts have been configured for CloudFormation stack set by attempting to assume the stack set execution role
:param credentials: AWS credentials to use when calling sts:assumerole
:param org_a... | python | def get_stackset_ready_accounts(credentials, account_ids, quiet=True):
"""
Verify which AWS accounts have been configured for CloudFormation stack set by attempting to assume the stack set execution role
:param credentials: AWS credentials to use when calling sts:assumerole
:param org_a... | [
"def",
"get_stackset_ready_accounts",
"(",
"credentials",
",",
"account_ids",
",",
"quiet",
"=",
"True",
")",
":",
"api_client",
"=",
"connect_service",
"(",
"'sts'",
",",
"credentials",
",",
"silent",
"=",
"True",
")",
"configured_account_ids",
"=",
"[",
"]",
... | Verify which AWS accounts have been configured for CloudFormation stack set by attempting to assume the stack set execution role
:param credentials: AWS credentials to use when calling sts:assumerole
:param org_account_ids: List of AWS accounts to check for Stackset configuration
... | [
"Verify",
"which",
"AWS",
"accounts",
"have",
"been",
"configured",
"for",
"CloudFormation",
"stack",
"set",
"by",
"attempting",
"to",
"assume",
"the",
"stack",
"set",
"execution",
"role"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/services/cloudformation.py#L154-L176 |
47,729 | sveetch/django-feedparser | django_feedparser/renderer.py | FeedBasicRenderer.fetch | def fetch(self, url):
"""
Get the feed content using 'requests'
"""
try:
r = requests.get(url, timeout=self.timeout)
except requests.exceptions.Timeout:
if not self.safe:
raise
else:
return None
... | python | def fetch(self, url):
"""
Get the feed content using 'requests'
"""
try:
r = requests.get(url, timeout=self.timeout)
except requests.exceptions.Timeout:
if not self.safe:
raise
else:
return None
... | [
"def",
"fetch",
"(",
"self",
",",
"url",
")",
":",
"try",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"timeout",
"=",
"self",
".",
"timeout",
")",
"except",
"requests",
".",
"exceptions",
".",
"Timeout",
":",
"if",
"not",
"self",
".",
... | Get the feed content using 'requests' | [
"Get",
"the",
"feed",
"content",
"using",
"requests"
] | 78be6a3ea095a90e4b28cad1b8893ddf1febf60e | https://github.com/sveetch/django-feedparser/blob/78be6a3ea095a90e4b28cad1b8893ddf1febf60e/django_feedparser/renderer.py#L39-L55 |
47,730 | sveetch/django-feedparser | django_feedparser/renderer.py | FeedBasicRenderer.parse | def parse(self, content):
"""
Parse the fetched feed content
Feedparser returned dict contain a 'bozo' key which can be '1' if the feed
is malformed.
Return None if the feed is malformed and 'bozo_accept'
is 'False', else return the feed content dict.
... | python | def parse(self, content):
"""
Parse the fetched feed content
Feedparser returned dict contain a 'bozo' key which can be '1' if the feed
is malformed.
Return None if the feed is malformed and 'bozo_accept'
is 'False', else return the feed content dict.
... | [
"def",
"parse",
"(",
"self",
",",
"content",
")",
":",
"if",
"content",
"is",
"None",
":",
"return",
"None",
"feed",
"=",
"feedparser",
".",
"parse",
"(",
"content",
")",
"# When feed is malformed",
"if",
"feed",
"[",
"'bozo'",
"]",
":",
"# keep track of t... | Parse the fetched feed content
Feedparser returned dict contain a 'bozo' key which can be '1' if the feed
is malformed.
Return None if the feed is malformed and 'bozo_accept'
is 'False', else return the feed content dict.
If the feed is malformed but ... | [
"Parse",
"the",
"fetched",
"feed",
"content",
"Feedparser",
"returned",
"dict",
"contain",
"a",
"bozo",
"key",
"which",
"can",
"be",
"1",
"if",
"the",
"feed",
"is",
"malformed",
".",
"Return",
"None",
"if",
"the",
"feed",
"is",
"malformed",
"and",
"bozo_ac... | 78be6a3ea095a90e4b28cad1b8893ddf1febf60e | https://github.com/sveetch/django-feedparser/blob/78be6a3ea095a90e4b28cad1b8893ddf1febf60e/django_feedparser/renderer.py#L57-L91 |
47,731 | sveetch/django-feedparser | django_feedparser/renderer.py | FeedBasicRenderer._hash_url | def _hash_url(self, url):
"""
Hash the URL to an md5sum.
"""
if isinstance(url, six.text_type):
url = url.encode('utf-8')
return hashlib.md5(url).hexdigest() | python | def _hash_url(self, url):
"""
Hash the URL to an md5sum.
"""
if isinstance(url, six.text_type):
url = url.encode('utf-8')
return hashlib.md5(url).hexdigest() | [
"def",
"_hash_url",
"(",
"self",
",",
"url",
")",
":",
"if",
"isinstance",
"(",
"url",
",",
"six",
".",
"text_type",
")",
":",
"url",
"=",
"url",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"hashlib",
".",
"md5",
"(",
"url",
")",
".",
"hexdigest"... | Hash the URL to an md5sum. | [
"Hash",
"the",
"URL",
"to",
"an",
"md5sum",
"."
] | 78be6a3ea095a90e4b28cad1b8893ddf1febf60e | https://github.com/sveetch/django-feedparser/blob/78be6a3ea095a90e4b28cad1b8893ddf1febf60e/django_feedparser/renderer.py#L93-L101 |
47,732 | sveetch/django-feedparser | django_feedparser/renderer.py | FeedBasicRenderer.get | def get(self, url, expiration):
"""
Fetch the feed if no cache exist or if cache is stale
"""
# Hash url to have a shorter key and add it expiration time to avoid clash for
# other url usage with different expiration
cache_key = self.cache_key.format(**{
'id'... | python | def get(self, url, expiration):
"""
Fetch the feed if no cache exist or if cache is stale
"""
# Hash url to have a shorter key and add it expiration time to avoid clash for
# other url usage with different expiration
cache_key = self.cache_key.format(**{
'id'... | [
"def",
"get",
"(",
"self",
",",
"url",
",",
"expiration",
")",
":",
"# Hash url to have a shorter key and add it expiration time to avoid clash for ",
"# other url usage with different expiration",
"cache_key",
"=",
"self",
".",
"cache_key",
".",
"format",
"(",
"*",
"*",
... | Fetch the feed if no cache exist or if cache is stale | [
"Fetch",
"the",
"feed",
"if",
"no",
"cache",
"exist",
"or",
"if",
"cache",
"is",
"stale"
] | 78be6a3ea095a90e4b28cad1b8893ddf1febf60e | https://github.com/sveetch/django-feedparser/blob/78be6a3ea095a90e4b28cad1b8893ddf1febf60e/django_feedparser/renderer.py#L103-L122 |
47,733 | sveetch/django-feedparser | django_feedparser/renderer.py | FeedBasicRenderer.get_context | def get_context(self, url, expiration):
"""
Build template context with formatted feed content
"""
self._feed = self.get(url, expiration)
return {
self.feed_context_name: self.format_feed_content(self._feed),
} | python | def get_context(self, url, expiration):
"""
Build template context with formatted feed content
"""
self._feed = self.get(url, expiration)
return {
self.feed_context_name: self.format_feed_content(self._feed),
} | [
"def",
"get_context",
"(",
"self",
",",
"url",
",",
"expiration",
")",
":",
"self",
".",
"_feed",
"=",
"self",
".",
"get",
"(",
"url",
",",
"expiration",
")",
"return",
"{",
"self",
".",
"feed_context_name",
":",
"self",
".",
"format_feed_content",
"(",
... | Build template context with formatted feed content | [
"Build",
"template",
"context",
"with",
"formatted",
"feed",
"content"
] | 78be6a3ea095a90e4b28cad1b8893ddf1febf60e | https://github.com/sveetch/django-feedparser/blob/78be6a3ea095a90e4b28cad1b8893ddf1febf60e/django_feedparser/renderer.py#L133-L141 |
47,734 | sveetch/django-feedparser | django_feedparser/renderer.py | FeedBasicRenderer.render | def render(self, url, template=None, expiration=0):
"""
Render feed template
"""
template = template or self.default_template
return render_to_string(template, self.get_context(url, expiration)) | python | def render(self, url, template=None, expiration=0):
"""
Render feed template
"""
template = template or self.default_template
return render_to_string(template, self.get_context(url, expiration)) | [
"def",
"render",
"(",
"self",
",",
"url",
",",
"template",
"=",
"None",
",",
"expiration",
"=",
"0",
")",
":",
"template",
"=",
"template",
"or",
"self",
".",
"default_template",
"return",
"render_to_string",
"(",
"template",
",",
"self",
".",
"get_context... | Render feed template | [
"Render",
"feed",
"template"
] | 78be6a3ea095a90e4b28cad1b8893ddf1febf60e | https://github.com/sveetch/django-feedparser/blob/78be6a3ea095a90e4b28cad1b8893ddf1febf60e/django_feedparser/renderer.py#L143-L149 |
47,735 | mixmastamyk/console | console/windows.py | is_ansi_capable | def is_ansi_capable():
''' Check to see whether this version of Windows is recent enough to
support "ANSI VT"" processing.
'''
BUILD_ANSI_AVAIL = 10586 # Win10 TH2
CURRENT_VERS = sys.getwindowsversion()[:3]
if CURRENT_VERS[2] > BUILD_ANSI_AVAIL:
result = True
else:
resu... | python | def is_ansi_capable():
''' Check to see whether this version of Windows is recent enough to
support "ANSI VT"" processing.
'''
BUILD_ANSI_AVAIL = 10586 # Win10 TH2
CURRENT_VERS = sys.getwindowsversion()[:3]
if CURRENT_VERS[2] > BUILD_ANSI_AVAIL:
result = True
else:
resu... | [
"def",
"is_ansi_capable",
"(",
")",
":",
"BUILD_ANSI_AVAIL",
"=",
"10586",
"# Win10 TH2",
"CURRENT_VERS",
"=",
"sys",
".",
"getwindowsversion",
"(",
")",
"[",
":",
"3",
"]",
"if",
"CURRENT_VERS",
"[",
"2",
"]",
">",
"BUILD_ANSI_AVAIL",
":",
"result",
"=",
... | Check to see whether this version of Windows is recent enough to
support "ANSI VT"" processing. | [
"Check",
"to",
"see",
"whether",
"this",
"version",
"of",
"Windows",
"is",
"recent",
"enough",
"to",
"support",
"ANSI",
"VT",
"processing",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/windows.py#L133-L145 |
47,736 | mixmastamyk/console | console/windows.py | get_color | def get_color(name, stream=STD_OUTPUT_HANDLE):
''' Returns current colors of console.
https://docs.microsoft.com/en-us/windows/console/getconsolescreenbufferinfo
Arguments:
name: one of ('background', 'bg', 'foreground', 'fg')
stream: Handle to stdout, stderr, etc.
... | python | def get_color(name, stream=STD_OUTPUT_HANDLE):
''' Returns current colors of console.
https://docs.microsoft.com/en-us/windows/console/getconsolescreenbufferinfo
Arguments:
name: one of ('background', 'bg', 'foreground', 'fg')
stream: Handle to stdout, stderr, etc.
... | [
"def",
"get_color",
"(",
"name",
",",
"stream",
"=",
"STD_OUTPUT_HANDLE",
")",
":",
"stream",
"=",
"kernel32",
".",
"GetStdHandle",
"(",
"stream",
")",
"csbi",
"=",
"CONSOLE_SCREEN_BUFFER_INFO",
"(",
")",
"kernel32",
".",
"GetConsoleScreenBufferInfo",
"(",
"stre... | Returns current colors of console.
https://docs.microsoft.com/en-us/windows/console/getconsolescreenbufferinfo
Arguments:
name: one of ('background', 'bg', 'foreground', 'fg')
stream: Handle to stdout, stderr, etc.
Returns:
int: a color id from the conho... | [
"Returns",
"current",
"colors",
"of",
"console",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/windows.py#L160-L185 |
47,737 | mixmastamyk/console | console/windows.py | get_position | def get_position(stream=STD_OUTPUT_HANDLE):
''' Returns current position of cursor, starts at 1. '''
stream = kernel32.GetStdHandle(stream)
csbi = CONSOLE_SCREEN_BUFFER_INFO()
kernel32.GetConsoleScreenBufferInfo(stream, byref(csbi))
pos = csbi.dwCursorPosition
# zero based, add ones for compati... | python | def get_position(stream=STD_OUTPUT_HANDLE):
''' Returns current position of cursor, starts at 1. '''
stream = kernel32.GetStdHandle(stream)
csbi = CONSOLE_SCREEN_BUFFER_INFO()
kernel32.GetConsoleScreenBufferInfo(stream, byref(csbi))
pos = csbi.dwCursorPosition
# zero based, add ones for compati... | [
"def",
"get_position",
"(",
"stream",
"=",
"STD_OUTPUT_HANDLE",
")",
":",
"stream",
"=",
"kernel32",
".",
"GetStdHandle",
"(",
"stream",
")",
"csbi",
"=",
"CONSOLE_SCREEN_BUFFER_INFO",
"(",
")",
"kernel32",
".",
"GetConsoleScreenBufferInfo",
"(",
"stream",
",",
... | Returns current position of cursor, starts at 1. | [
"Returns",
"current",
"position",
"of",
"cursor",
"starts",
"at",
"1",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/windows.py#L188-L196 |
47,738 | mixmastamyk/console | console/windows.py | set_position | def set_position(x, y, stream=STD_OUTPUT_HANDLE):
''' Sets current position of the cursor. '''
stream = kernel32.GetStdHandle(stream)
value = x + (y << 16)
kernel32.SetConsoleCursorPosition(stream, c_long(value)) | python | def set_position(x, y, stream=STD_OUTPUT_HANDLE):
''' Sets current position of the cursor. '''
stream = kernel32.GetStdHandle(stream)
value = x + (y << 16)
kernel32.SetConsoleCursorPosition(stream, c_long(value)) | [
"def",
"set_position",
"(",
"x",
",",
"y",
",",
"stream",
"=",
"STD_OUTPUT_HANDLE",
")",
":",
"stream",
"=",
"kernel32",
".",
"GetStdHandle",
"(",
"stream",
")",
"value",
"=",
"x",
"+",
"(",
"y",
"<<",
"16",
")",
"kernel32",
".",
"SetConsoleCursorPositio... | Sets current position of the cursor. | [
"Sets",
"current",
"position",
"of",
"the",
"cursor",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/windows.py#L199-L203 |
47,739 | mixmastamyk/console | console/windows.py | get_title | def get_title():
''' Returns console title string.
https://docs.microsoft.com/en-us/windows/console/getconsoletitle
'''
MAX_LEN = 256
buffer_ = create_unicode_buffer(MAX_LEN)
kernel32.GetConsoleTitleW(buffer_, MAX_LEN)
log.debug('%s', buffer_.value)
return buffer_.value | python | def get_title():
''' Returns console title string.
https://docs.microsoft.com/en-us/windows/console/getconsoletitle
'''
MAX_LEN = 256
buffer_ = create_unicode_buffer(MAX_LEN)
kernel32.GetConsoleTitleW(buffer_, MAX_LEN)
log.debug('%s', buffer_.value)
return buffer_.value | [
"def",
"get_title",
"(",
")",
":",
"MAX_LEN",
"=",
"256",
"buffer_",
"=",
"create_unicode_buffer",
"(",
"MAX_LEN",
")",
"kernel32",
".",
"GetConsoleTitleW",
"(",
"buffer_",
",",
"MAX_LEN",
")",
"log",
".",
"debug",
"(",
"'%s'",
",",
"buffer_",
".",
"value"... | Returns console title string.
https://docs.microsoft.com/en-us/windows/console/getconsoletitle | [
"Returns",
"console",
"title",
"string",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/windows.py#L206-L215 |
47,740 | eagleflo/mpyq | mpyq.py | MPQArchive.read_header | def read_header(self):
"""Read the header of a MPQ archive."""
def read_mpq_header(offset=None):
if offset:
self.file.seek(offset)
data = self.file.read(32)
header = MPQFileHeader._make(
struct.unpack(MPQFileHeader.struct_format, data)... | python | def read_header(self):
"""Read the header of a MPQ archive."""
def read_mpq_header(offset=None):
if offset:
self.file.seek(offset)
data = self.file.read(32)
header = MPQFileHeader._make(
struct.unpack(MPQFileHeader.struct_format, data)... | [
"def",
"read_header",
"(",
"self",
")",
":",
"def",
"read_mpq_header",
"(",
"offset",
"=",
"None",
")",
":",
"if",
"offset",
":",
"self",
".",
"file",
".",
"seek",
"(",
"offset",
")",
"data",
"=",
"self",
".",
"file",
".",
"read",
"(",
"32",
")",
... | Read the header of a MPQ archive. | [
"Read",
"the",
"header",
"of",
"a",
"MPQ",
"archive",
"."
] | ec778a454be62d5e63cae9fb16b75832a76cb9aa | https://github.com/eagleflo/mpyq/blob/ec778a454be62d5e63cae9fb16b75832a76cb9aa/mpyq.py#L108-L147 |
47,741 | eagleflo/mpyq | mpyq.py | MPQArchive.read_table | def read_table(self, table_type):
"""Read either the hash or block table of a MPQ archive."""
if table_type == 'hash':
entry_class = MPQHashTableEntry
elif table_type == 'block':
entry_class = MPQBlockTableEntry
else:
raise ValueError("Invalid table t... | python | def read_table(self, table_type):
"""Read either the hash or block table of a MPQ archive."""
if table_type == 'hash':
entry_class = MPQHashTableEntry
elif table_type == 'block':
entry_class = MPQBlockTableEntry
else:
raise ValueError("Invalid table t... | [
"def",
"read_table",
"(",
"self",
",",
"table_type",
")",
":",
"if",
"table_type",
"==",
"'hash'",
":",
"entry_class",
"=",
"MPQHashTableEntry",
"elif",
"table_type",
"==",
"'block'",
":",
"entry_class",
"=",
"MPQBlockTableEntry",
"else",
":",
"raise",
"ValueErr... | Read either the hash or block table of a MPQ archive. | [
"Read",
"either",
"the",
"hash",
"or",
"block",
"table",
"of",
"a",
"MPQ",
"archive",
"."
] | ec778a454be62d5e63cae9fb16b75832a76cb9aa | https://github.com/eagleflo/mpyq/blob/ec778a454be62d5e63cae9fb16b75832a76cb9aa/mpyq.py#L149-L172 |
47,742 | eagleflo/mpyq | mpyq.py | MPQArchive.get_hash_table_entry | def get_hash_table_entry(self, filename):
"""Get the hash table entry corresponding to a given filename."""
hash_a = self._hash(filename, 'HASH_A')
hash_b = self._hash(filename, 'HASH_B')
for entry in self.hash_table:
if (entry.hash_a == hash_a and entry.hash_b == hash_b):
... | python | def get_hash_table_entry(self, filename):
"""Get the hash table entry corresponding to a given filename."""
hash_a = self._hash(filename, 'HASH_A')
hash_b = self._hash(filename, 'HASH_B')
for entry in self.hash_table:
if (entry.hash_a == hash_a and entry.hash_b == hash_b):
... | [
"def",
"get_hash_table_entry",
"(",
"self",
",",
"filename",
")",
":",
"hash_a",
"=",
"self",
".",
"_hash",
"(",
"filename",
",",
"'HASH_A'",
")",
"hash_b",
"=",
"self",
".",
"_hash",
"(",
"filename",
",",
"'HASH_B'",
")",
"for",
"entry",
"in",
"self",
... | Get the hash table entry corresponding to a given filename. | [
"Get",
"the",
"hash",
"table",
"entry",
"corresponding",
"to",
"a",
"given",
"filename",
"."
] | ec778a454be62d5e63cae9fb16b75832a76cb9aa | https://github.com/eagleflo/mpyq/blob/ec778a454be62d5e63cae9fb16b75832a76cb9aa/mpyq.py#L174-L180 |
47,743 | eagleflo/mpyq | mpyq.py | MPQArchive.read_file | def read_file(self, filename, force_decompress=False):
"""Read a file from the MPQ archive."""
def decompress(data):
"""Read the compression type and decompress file data."""
compression_type = ord(data[0:1])
if compression_type == 0:
return data
... | python | def read_file(self, filename, force_decompress=False):
"""Read a file from the MPQ archive."""
def decompress(data):
"""Read the compression type and decompress file data."""
compression_type = ord(data[0:1])
if compression_type == 0:
return data
... | [
"def",
"read_file",
"(",
"self",
",",
"filename",
",",
"force_decompress",
"=",
"False",
")",
":",
"def",
"decompress",
"(",
"data",
")",
":",
"\"\"\"Read the compression type and decompress file data.\"\"\"",
"compression_type",
"=",
"ord",
"(",
"data",
"[",
"0",
... | Read a file from the MPQ archive. | [
"Read",
"a",
"file",
"from",
"the",
"MPQ",
"archive",
"."
] | ec778a454be62d5e63cae9fb16b75832a76cb9aa | https://github.com/eagleflo/mpyq/blob/ec778a454be62d5e63cae9fb16b75832a76cb9aa/mpyq.py#L182-L244 |
47,744 | eagleflo/mpyq | mpyq.py | MPQArchive.extract | def extract(self):
"""Extract all the files inside the MPQ archive in memory."""
if self.files:
return dict((f, self.read_file(f)) for f in self.files)
else:
raise RuntimeError("Can't extract whole archive without listfile.") | python | def extract(self):
"""Extract all the files inside the MPQ archive in memory."""
if self.files:
return dict((f, self.read_file(f)) for f in self.files)
else:
raise RuntimeError("Can't extract whole archive without listfile.") | [
"def",
"extract",
"(",
"self",
")",
":",
"if",
"self",
".",
"files",
":",
"return",
"dict",
"(",
"(",
"f",
",",
"self",
".",
"read_file",
"(",
"f",
")",
")",
"for",
"f",
"in",
"self",
".",
"files",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
... | Extract all the files inside the MPQ archive in memory. | [
"Extract",
"all",
"the",
"files",
"inside",
"the",
"MPQ",
"archive",
"in",
"memory",
"."
] | ec778a454be62d5e63cae9fb16b75832a76cb9aa | https://github.com/eagleflo/mpyq/blob/ec778a454be62d5e63cae9fb16b75832a76cb9aa/mpyq.py#L246-L251 |
47,745 | eagleflo/mpyq | mpyq.py | MPQArchive.extract_to_disk | def extract_to_disk(self):
"""Extract all files and write them to disk."""
archive_name, extension = os.path.splitext(os.path.basename(self.file.name))
if not os.path.isdir(os.path.join(os.getcwd(), archive_name)):
os.mkdir(archive_name)
os.chdir(archive_name)
for fil... | python | def extract_to_disk(self):
"""Extract all files and write them to disk."""
archive_name, extension = os.path.splitext(os.path.basename(self.file.name))
if not os.path.isdir(os.path.join(os.getcwd(), archive_name)):
os.mkdir(archive_name)
os.chdir(archive_name)
for fil... | [
"def",
"extract_to_disk",
"(",
"self",
")",
":",
"archive_name",
",",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"file",
".",
"name",
")",
")",
"if",
"not",
"os",
".",
"path",
".... | Extract all files and write them to disk. | [
"Extract",
"all",
"files",
"and",
"write",
"them",
"to",
"disk",
"."
] | ec778a454be62d5e63cae9fb16b75832a76cb9aa | https://github.com/eagleflo/mpyq/blob/ec778a454be62d5e63cae9fb16b75832a76cb9aa/mpyq.py#L253-L262 |
47,746 | eagleflo/mpyq | mpyq.py | MPQArchive.extract_files | def extract_files(self, *filenames):
"""Extract given files from the archive to disk."""
for filename in filenames:
data = self.read_file(filename)
f = open(filename, 'wb')
f.write(data or b'')
f.close() | python | def extract_files(self, *filenames):
"""Extract given files from the archive to disk."""
for filename in filenames:
data = self.read_file(filename)
f = open(filename, 'wb')
f.write(data or b'')
f.close() | [
"def",
"extract_files",
"(",
"self",
",",
"*",
"filenames",
")",
":",
"for",
"filename",
"in",
"filenames",
":",
"data",
"=",
"self",
".",
"read_file",
"(",
"filename",
")",
"f",
"=",
"open",
"(",
"filename",
",",
"'wb'",
")",
"f",
".",
"write",
"(",... | Extract given files from the archive to disk. | [
"Extract",
"given",
"files",
"from",
"the",
"archive",
"to",
"disk",
"."
] | ec778a454be62d5e63cae9fb16b75832a76cb9aa | https://github.com/eagleflo/mpyq/blob/ec778a454be62d5e63cae9fb16b75832a76cb9aa/mpyq.py#L264-L270 |
47,747 | eagleflo/mpyq | mpyq.py | MPQArchive._hash | def _hash(self, string, hash_type):
"""Hash a string using MPQ's hash function."""
hash_types = {
'TABLE_OFFSET': 0,
'HASH_A': 1,
'HASH_B': 2,
'TABLE': 3
}
seed1 = 0x7FED7FED
seed2 = 0xEEEEEEEE
for ch in string.upper():
... | python | def _hash(self, string, hash_type):
"""Hash a string using MPQ's hash function."""
hash_types = {
'TABLE_OFFSET': 0,
'HASH_A': 1,
'HASH_B': 2,
'TABLE': 3
}
seed1 = 0x7FED7FED
seed2 = 0xEEEEEEEE
for ch in string.upper():
... | [
"def",
"_hash",
"(",
"self",
",",
"string",
",",
"hash_type",
")",
":",
"hash_types",
"=",
"{",
"'TABLE_OFFSET'",
":",
"0",
",",
"'HASH_A'",
":",
"1",
",",
"'HASH_B'",
":",
"2",
",",
"'TABLE'",
":",
"3",
"}",
"seed1",
"=",
"0x7FED7FED",
"seed2",
"=",... | Hash a string using MPQ's hash function. | [
"Hash",
"a",
"string",
"using",
"MPQ",
"s",
"hash",
"function",
"."
] | ec778a454be62d5e63cae9fb16b75832a76cb9aa | https://github.com/eagleflo/mpyq/blob/ec778a454be62d5e63cae9fb16b75832a76cb9aa/mpyq.py#L315-L332 |
47,748 | eagleflo/mpyq | mpyq.py | MPQArchive._decrypt | def _decrypt(self, data, key):
"""Decrypt hash or block table or a sector."""
seed1 = key
seed2 = 0xEEEEEEEE
result = BytesIO()
for i in range(len(data) // 4):
seed2 += self.encryption_table[0x400 + (seed1 & 0xFF)]
seed2 &= 0xFFFFFFFF
value = ... | python | def _decrypt(self, data, key):
"""Decrypt hash or block table or a sector."""
seed1 = key
seed2 = 0xEEEEEEEE
result = BytesIO()
for i in range(len(data) // 4):
seed2 += self.encryption_table[0x400 + (seed1 & 0xFF)]
seed2 &= 0xFFFFFFFF
value = ... | [
"def",
"_decrypt",
"(",
"self",
",",
"data",
",",
"key",
")",
":",
"seed1",
"=",
"key",
"seed2",
"=",
"0xEEEEEEEE",
"result",
"=",
"BytesIO",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"data",
")",
"//",
"4",
")",
":",
"seed2",
"+=",
... | Decrypt hash or block table or a sector. | [
"Decrypt",
"hash",
"or",
"block",
"table",
"or",
"a",
"sector",
"."
] | ec778a454be62d5e63cae9fb16b75832a76cb9aa | https://github.com/eagleflo/mpyq/blob/ec778a454be62d5e63cae9fb16b75832a76cb9aa/mpyq.py#L334-L352 |
47,749 | eagleflo/mpyq | mpyq.py | MPQArchive._prepare_encryption_table | def _prepare_encryption_table():
"""Prepare encryption table for MPQ hash function."""
seed = 0x00100001
crypt_table = {}
for i in range(256):
index = i
for j in range(5):
seed = (seed * 125 + 3) % 0x2AAAAB
temp1 = (seed & 0xFFFF) ... | python | def _prepare_encryption_table():
"""Prepare encryption table for MPQ hash function."""
seed = 0x00100001
crypt_table = {}
for i in range(256):
index = i
for j in range(5):
seed = (seed * 125 + 3) % 0x2AAAAB
temp1 = (seed & 0xFFFF) ... | [
"def",
"_prepare_encryption_table",
"(",
")",
":",
"seed",
"=",
"0x00100001",
"crypt_table",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"256",
")",
":",
"index",
"=",
"i",
"for",
"j",
"in",
"range",
"(",
"5",
")",
":",
"seed",
"=",
"(",
"seed",... | Prepare encryption table for MPQ hash function. | [
"Prepare",
"encryption",
"table",
"for",
"MPQ",
"hash",
"function",
"."
] | ec778a454be62d5e63cae9fb16b75832a76cb9aa | https://github.com/eagleflo/mpyq/blob/ec778a454be62d5e63cae9fb16b75832a76cb9aa/mpyq.py#L354-L372 |
47,750 | jamesturk/scrapelib | scrapelib/cache.py | CachingSession.key_for_request | def key_for_request(self, method, url, **kwargs):
""" Return a cache key from a given set of request parameters.
Default behavior is to return a complete URL for all GET
requests, and None otherwise.
Can be overriden if caching of non-get requests is desired.
"""
... | python | def key_for_request(self, method, url, **kwargs):
""" Return a cache key from a given set of request parameters.
Default behavior is to return a complete URL for all GET
requests, and None otherwise.
Can be overriden if caching of non-get requests is desired.
"""
... | [
"def",
"key_for_request",
"(",
"self",
",",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"method",
"!=",
"'get'",
":",
"return",
"None",
"return",
"requests",
".",
"Request",
"(",
"url",
"=",
"url",
",",
"params",
"=",
"kwargs",
"."... | Return a cache key from a given set of request parameters.
Default behavior is to return a complete URL for all GET
requests, and None otherwise.
Can be overriden if caching of non-get requests is desired. | [
"Return",
"a",
"cache",
"key",
"from",
"a",
"given",
"set",
"of",
"request",
"parameters",
"."
] | dcae9fa86f1fdcc4b4e90dbca12c8063bcb36525 | https://github.com/jamesturk/scrapelib/blob/dcae9fa86f1fdcc4b4e90dbca12c8063bcb36525/scrapelib/cache.py#L22-L33 |
47,751 | jamesturk/scrapelib | scrapelib/cache.py | CachingSession.request | def request(self, method, url, **kwargs):
""" Override, wraps Session.request in caching.
Cache is only used if key_for_request returns a valid key
and should_cache_response was true as well.
"""
# short circuit if cache isn't configured
if not self.cache_storage... | python | def request(self, method, url, **kwargs):
""" Override, wraps Session.request in caching.
Cache is only used if key_for_request returns a valid key
and should_cache_response was true as well.
"""
# short circuit if cache isn't configured
if not self.cache_storage... | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"# short circuit if cache isn't configured",
"if",
"not",
"self",
".",
"cache_storage",
":",
"resp",
"=",
"super",
"(",
"CachingSession",
",",
"self",
")",
".",
"r... | Override, wraps Session.request in caching.
Cache is only used if key_for_request returns a valid key
and should_cache_response was true as well. | [
"Override",
"wraps",
"Session",
".",
"request",
"in",
"caching",
"."
] | dcae9fa86f1fdcc4b4e90dbca12c8063bcb36525 | https://github.com/jamesturk/scrapelib/blob/dcae9fa86f1fdcc4b4e90dbca12c8063bcb36525/scrapelib/cache.py#L43-L72 |
47,752 | justanr/Flask-Transfer | flask_transfer/transfer.py | _make_destination_callable | def _make_destination_callable(dest):
"""Creates a callable out of the destination. If it's already callable,
the destination is returned. Instead, if the object is a string or a
writable object, it's wrapped in a closure to be used later.
"""
if callable(dest):
return dest
elif hasattr(... | python | def _make_destination_callable(dest):
"""Creates a callable out of the destination. If it's already callable,
the destination is returned. Instead, if the object is a string or a
writable object, it's wrapped in a closure to be used later.
"""
if callable(dest):
return dest
elif hasattr(... | [
"def",
"_make_destination_callable",
"(",
"dest",
")",
":",
"if",
"callable",
"(",
"dest",
")",
":",
"return",
"dest",
"elif",
"hasattr",
"(",
"dest",
",",
"'write'",
")",
"or",
"isinstance",
"(",
"dest",
",",
"string_types",
")",
":",
"return",
"_use_file... | Creates a callable out of the destination. If it's already callable,
the destination is returned. Instead, if the object is a string or a
writable object, it's wrapped in a closure to be used later. | [
"Creates",
"a",
"callable",
"out",
"of",
"the",
"destination",
".",
"If",
"it",
"s",
"already",
"callable",
"the",
"destination",
"is",
"returned",
".",
"Instead",
"if",
"the",
"object",
"is",
"a",
"string",
"or",
"a",
"writable",
"object",
"it",
"s",
"w... | 075ba9edb8c8d0ea47619cc763394bbb717c2ead | https://github.com/justanr/Flask-Transfer/blob/075ba9edb8c8d0ea47619cc763394bbb717c2ead/flask_transfer/transfer.py#L15-L25 |
47,753 | justanr/Flask-Transfer | flask_transfer/transfer.py | Transfer._validate | def _validate(self, filehandle, metadata, catch_all_errors=False):
"""Runs all attached validators on the provided filehandle.
In the base implmentation of Transfer, the result of `_validate` isn't
checked. Rather validators are expected to raise UploadError to report
failure.
`... | python | def _validate(self, filehandle, metadata, catch_all_errors=False):
"""Runs all attached validators on the provided filehandle.
In the base implmentation of Transfer, the result of `_validate` isn't
checked. Rather validators are expected to raise UploadError to report
failure.
`... | [
"def",
"_validate",
"(",
"self",
",",
"filehandle",
",",
"metadata",
",",
"catch_all_errors",
"=",
"False",
")",
":",
"errors",
"=",
"[",
"]",
"DEFAULT_ERROR_MSG",
"=",
"'{0!r}({1!r}, {2!r}) returned False'",
"for",
"validator",
"in",
"self",
".",
"_validators",
... | Runs all attached validators on the provided filehandle.
In the base implmentation of Transfer, the result of `_validate` isn't
checked. Rather validators are expected to raise UploadError to report
failure.
`_validate` can optionally catch all UploadErrors that occur or bail out
... | [
"Runs",
"all",
"attached",
"validators",
"on",
"the",
"provided",
"filehandle",
".",
"In",
"the",
"base",
"implmentation",
"of",
"Transfer",
"the",
"result",
"of",
"_validate",
"isn",
"t",
"checked",
".",
"Rather",
"validators",
"are",
"expected",
"to",
"raise... | 075ba9edb8c8d0ea47619cc763394bbb717c2ead | https://github.com/justanr/Flask-Transfer/blob/075ba9edb8c8d0ea47619cc763394bbb717c2ead/flask_transfer/transfer.py#L146-L172 |
47,754 | justanr/Flask-Transfer | flask_transfer/transfer.py | Transfer._preprocess | def _preprocess(self, filehandle, metadata):
"Runs all attached preprocessors on the provided filehandle."
for process in self._preprocessors:
filehandle = process(filehandle, metadata)
return filehandle | python | def _preprocess(self, filehandle, metadata):
"Runs all attached preprocessors on the provided filehandle."
for process in self._preprocessors:
filehandle = process(filehandle, metadata)
return filehandle | [
"def",
"_preprocess",
"(",
"self",
",",
"filehandle",
",",
"metadata",
")",
":",
"for",
"process",
"in",
"self",
".",
"_preprocessors",
":",
"filehandle",
"=",
"process",
"(",
"filehandle",
",",
"metadata",
")",
"return",
"filehandle"
] | Runs all attached preprocessors on the provided filehandle. | [
"Runs",
"all",
"attached",
"preprocessors",
"on",
"the",
"provided",
"filehandle",
"."
] | 075ba9edb8c8d0ea47619cc763394bbb717c2ead | https://github.com/justanr/Flask-Transfer/blob/075ba9edb8c8d0ea47619cc763394bbb717c2ead/flask_transfer/transfer.py#L174-L178 |
47,755 | justanr/Flask-Transfer | flask_transfer/transfer.py | Transfer._postprocess | def _postprocess(self, filehandle, metadata):
"Runs all attached postprocessors on the provided filehandle."
for process in self._postprocessors:
filehandle = process(filehandle, metadata)
return filehandle | python | def _postprocess(self, filehandle, metadata):
"Runs all attached postprocessors on the provided filehandle."
for process in self._postprocessors:
filehandle = process(filehandle, metadata)
return filehandle | [
"def",
"_postprocess",
"(",
"self",
",",
"filehandle",
",",
"metadata",
")",
":",
"for",
"process",
"in",
"self",
".",
"_postprocessors",
":",
"filehandle",
"=",
"process",
"(",
"filehandle",
",",
"metadata",
")",
"return",
"filehandle"
] | Runs all attached postprocessors on the provided filehandle. | [
"Runs",
"all",
"attached",
"postprocessors",
"on",
"the",
"provided",
"filehandle",
"."
] | 075ba9edb8c8d0ea47619cc763394bbb717c2ead | https://github.com/justanr/Flask-Transfer/blob/075ba9edb8c8d0ea47619cc763394bbb717c2ead/flask_transfer/transfer.py#L180-L184 |
47,756 | justanr/Flask-Transfer | flask_transfer/transfer.py | Transfer.save | def save(self, filehandle, destination=None, metadata=None,
validate=True, catch_all_errors=False, *args, **kwargs):
"""Saves the filehandle to the provided destination or the attached
default destination. Allows passing arbitrary positional and keyword
arguments to the saving mecha... | python | def save(self, filehandle, destination=None, metadata=None,
validate=True, catch_all_errors=False, *args, **kwargs):
"""Saves the filehandle to the provided destination or the attached
default destination. Allows passing arbitrary positional and keyword
arguments to the saving mecha... | [
"def",
"save",
"(",
"self",
",",
"filehandle",
",",
"destination",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"validate",
"=",
"True",
",",
"catch_all_errors",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"destination",
"=",
... | Saves the filehandle to the provided destination or the attached
default destination. Allows passing arbitrary positional and keyword
arguments to the saving mechanism
:param filehandle: werkzeug.FileStorage instance
:param dest: String path, callable or writable destination to pass the... | [
"Saves",
"the",
"filehandle",
"to",
"the",
"provided",
"destination",
"or",
"the",
"attached",
"default",
"destination",
".",
"Allows",
"passing",
"arbitrary",
"positional",
"and",
"keyword",
"arguments",
"to",
"the",
"saving",
"mechanism"
] | 075ba9edb8c8d0ea47619cc763394bbb717c2ead | https://github.com/justanr/Flask-Transfer/blob/075ba9edb8c8d0ea47619cc763394bbb717c2ead/flask_transfer/transfer.py#L186-L219 |
47,757 | mixmastamyk/console | console/detection.py | choose_palette | def choose_palette(stream=sys.stdout, basic_palette=None):
''' Make a best effort to automatically determine whether to enable
ANSI sequences, and if so, which color palettes are available.
This is the main function of the module—meant to be used unless
something more specific is needed.
... | python | def choose_palette(stream=sys.stdout, basic_palette=None):
''' Make a best effort to automatically determine whether to enable
ANSI sequences, and if so, which color palettes are available.
This is the main function of the module—meant to be used unless
something more specific is needed.
... | [
"def",
"choose_palette",
"(",
"stream",
"=",
"sys",
".",
"stdout",
",",
"basic_palette",
"=",
"None",
")",
":",
"result",
"=",
"None",
"pal",
"=",
"basic_palette",
"log",
".",
"debug",
"(",
"'console version: %s'",
",",
"__version__",
")",
"log",
".",
"deb... | Make a best effort to automatically determine whether to enable
ANSI sequences, and if so, which color palettes are available.
This is the main function of the module—meant to be used unless
something more specific is needed.
Takes the following factors into account:
- Whether... | [
"Make",
"a",
"best",
"effort",
"to",
"automatically",
"determine",
"whether",
"to",
"enable",
"ANSI",
"sequences",
"and",
"if",
"so",
"which",
"color",
"palettes",
"are",
"available",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L66-L100 |
47,758 | mixmastamyk/console | console/detection.py | detect_palette_support | def detect_palette_support(basic_palette=None):
''' Returns whether we think the terminal supports basic, extended, or
truecolor. None if not able to tell.
Returns:
None or str: 'basic', 'extended', 'truecolor'
'''
result = col_init = win_enabled = None
TERM = env.TERM or '... | python | def detect_palette_support(basic_palette=None):
''' Returns whether we think the terminal supports basic, extended, or
truecolor. None if not able to tell.
Returns:
None or str: 'basic', 'extended', 'truecolor'
'''
result = col_init = win_enabled = None
TERM = env.TERM or '... | [
"def",
"detect_palette_support",
"(",
"basic_palette",
"=",
"None",
")",
":",
"result",
"=",
"col_init",
"=",
"win_enabled",
"=",
"None",
"TERM",
"=",
"env",
".",
"TERM",
"or",
"''",
"if",
"os_name",
"==",
"'nt'",
":",
"from",
".",
"windows",
"import",
"... | Returns whether we think the terminal supports basic, extended, or
truecolor. None if not able to tell.
Returns:
None or str: 'basic', 'extended', 'truecolor' | [
"Returns",
"whether",
"we",
"think",
"the",
"terminal",
"supports",
"basic",
"extended",
"or",
"truecolor",
".",
"None",
"if",
"not",
"able",
"to",
"tell",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L176-L219 |
47,759 | mixmastamyk/console | console/detection.py | _find_basic_palette | def _find_basic_palette(result):
''' Find the platform-dependent 16-color basic palette.
This is used for "downgrading to the nearest color" support.
'''
pal_name = 'default (xterm)'
basic_palette = color_tables.xterm_palette4
if env.SSH_CLIENT: # fall back to xterm over ssh, info often wr... | python | def _find_basic_palette(result):
''' Find the platform-dependent 16-color basic palette.
This is used for "downgrading to the nearest color" support.
'''
pal_name = 'default (xterm)'
basic_palette = color_tables.xterm_palette4
if env.SSH_CLIENT: # fall back to xterm over ssh, info often wr... | [
"def",
"_find_basic_palette",
"(",
"result",
")",
":",
"pal_name",
"=",
"'default (xterm)'",
"basic_palette",
"=",
"color_tables",
".",
"xterm_palette4",
"if",
"env",
".",
"SSH_CLIENT",
":",
"# fall back to xterm over ssh, info often wrong",
"pal_name",
"=",
"'ssh (xterm)... | Find the platform-dependent 16-color basic palette.
This is used for "downgrading to the nearest color" support. | [
"Find",
"the",
"platform",
"-",
"dependent",
"16",
"-",
"color",
"basic",
"palette",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L266-L315 |
47,760 | mixmastamyk/console | console/detection.py | get_available_palettes | def get_available_palettes(chosen_palette):
''' Given a chosen palette, returns tuple of those available,
or None when not found.
Because palette support of a particular level is almost always a
superset of lower levels, this should return all available palettes.
Returns:
... | python | def get_available_palettes(chosen_palette):
''' Given a chosen palette, returns tuple of those available,
or None when not found.
Because palette support of a particular level is almost always a
superset of lower levels, this should return all available palettes.
Returns:
... | [
"def",
"get_available_palettes",
"(",
"chosen_palette",
")",
":",
"result",
"=",
"None",
"try",
":",
"result",
"=",
"ALL_PALETTES",
"[",
":",
"ALL_PALETTES",
".",
"index",
"(",
"chosen_palette",
")",
"+",
"1",
"]",
"except",
"ValueError",
":",
"pass",
"retur... | Given a chosen palette, returns tuple of those available,
or None when not found.
Because palette support of a particular level is almost always a
superset of lower levels, this should return all available palettes.
Returns:
Boolean, None: is tty or None if not found. | [
"Given",
"a",
"chosen",
"palette",
"returns",
"tuple",
"of",
"those",
"available",
"or",
"None",
"when",
"not",
"found",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L318-L333 |
47,761 | mixmastamyk/console | console/detection.py | is_a_tty | def is_a_tty(stream=sys.stdout):
''' Detect terminal or something else, such as output redirection.
Returns:
Boolean, None: is tty or None if not found.
'''
result = stream.isatty() if hasattr(stream, 'isatty') else None
log.debug(result)
return result | python | def is_a_tty(stream=sys.stdout):
''' Detect terminal or something else, such as output redirection.
Returns:
Boolean, None: is tty or None if not found.
'''
result = stream.isatty() if hasattr(stream, 'isatty') else None
log.debug(result)
return result | [
"def",
"is_a_tty",
"(",
"stream",
"=",
"sys",
".",
"stdout",
")",
":",
"result",
"=",
"stream",
".",
"isatty",
"(",
")",
"if",
"hasattr",
"(",
"stream",
",",
"'isatty'",
")",
"else",
"None",
"log",
".",
"debug",
"(",
"result",
")",
"return",
"result"... | Detect terminal or something else, such as output redirection.
Returns:
Boolean, None: is tty or None if not found. | [
"Detect",
"terminal",
"or",
"something",
"else",
"such",
"as",
"output",
"redirection",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L336-L344 |
47,762 | mixmastamyk/console | console/detection.py | load_x11_color_map | def load_x11_color_map(paths=X11_RGB_PATHS):
''' Load and parse X11's rgb.txt.
Loads:
x11_color_map: { name_lower: ('R', 'G', 'B') }
'''
if type(paths) is str:
paths = (paths,)
x11_color_map = color_tables.x11_color_map
for path in paths:
try:
with o... | python | def load_x11_color_map(paths=X11_RGB_PATHS):
''' Load and parse X11's rgb.txt.
Loads:
x11_color_map: { name_lower: ('R', 'G', 'B') }
'''
if type(paths) is str:
paths = (paths,)
x11_color_map = color_tables.x11_color_map
for path in paths:
try:
with o... | [
"def",
"load_x11_color_map",
"(",
"paths",
"=",
"X11_RGB_PATHS",
")",
":",
"if",
"type",
"(",
"paths",
")",
"is",
"str",
":",
"paths",
"=",
"(",
"paths",
",",
")",
"x11_color_map",
"=",
"color_tables",
".",
"x11_color_map",
"for",
"path",
"in",
"paths",
... | Load and parse X11's rgb.txt.
Loads:
x11_color_map: { name_lower: ('R', 'G', 'B') } | [
"Load",
"and",
"parse",
"X11",
"s",
"rgb",
".",
"txt",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L347-L375 |
47,763 | mixmastamyk/console | console/detection.py | parse_vtrgb | def parse_vtrgb(path='/etc/vtrgb'):
''' Parse the color table for the Linux console. '''
palette = ()
table = []
try:
with open(path) as infile:
for i, line in enumerate(infile):
row = tuple(int(val) for val in line.split(','))
table.append(row)
... | python | def parse_vtrgb(path='/etc/vtrgb'):
''' Parse the color table for the Linux console. '''
palette = ()
table = []
try:
with open(path) as infile:
for i, line in enumerate(infile):
row = tuple(int(val) for val in line.split(','))
table.append(row)
... | [
"def",
"parse_vtrgb",
"(",
"path",
"=",
"'/etc/vtrgb'",
")",
":",
"palette",
"=",
"(",
")",
"table",
"=",
"[",
"]",
"try",
":",
"with",
"open",
"(",
"path",
")",
"as",
"infile",
":",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"infile",
")",
... | Parse the color table for the Linux console. | [
"Parse",
"the",
"color",
"table",
"for",
"the",
"Linux",
"console",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L378-L395 |
47,764 | mixmastamyk/console | console/detection.py | _read_until | def _read_until(infile=sys.stdin, maxchars=20, end=RS):
''' Read a terminal response of up to a few characters from stdin. '''
chars = []
read = infile.read
if not isinstance(end, tuple):
end = (end,)
# count down, stopping at 0
while maxchars:
char = read(1)
if char in... | python | def _read_until(infile=sys.stdin, maxchars=20, end=RS):
''' Read a terminal response of up to a few characters from stdin. '''
chars = []
read = infile.read
if not isinstance(end, tuple):
end = (end,)
# count down, stopping at 0
while maxchars:
char = read(1)
if char in... | [
"def",
"_read_until",
"(",
"infile",
"=",
"sys",
".",
"stdin",
",",
"maxchars",
"=",
"20",
",",
"end",
"=",
"RS",
")",
":",
"chars",
"=",
"[",
"]",
"read",
"=",
"infile",
".",
"read",
"if",
"not",
"isinstance",
"(",
"end",
",",
"tuple",
")",
":",... | Read a terminal response of up to a few characters from stdin. | [
"Read",
"a",
"terminal",
"response",
"of",
"up",
"to",
"a",
"few",
"characters",
"from",
"stdin",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L409-L424 |
47,765 | mixmastamyk/console | console/detection.py | get_color | def get_color(name, number=None):
''' Query the default terminal, for colors, etc.
Direct queries supported on xterm, iTerm, perhaps others.
Arguments:
str: name, one of ('foreground', 'fg', 'background', 'bg',
or 'index') # index grabs a palette ind... | python | def get_color(name, number=None):
''' Query the default terminal, for colors, etc.
Direct queries supported on xterm, iTerm, perhaps others.
Arguments:
str: name, one of ('foreground', 'fg', 'background', 'bg',
or 'index') # index grabs a palette ind... | [
"def",
"get_color",
"(",
"name",
",",
"number",
"=",
"None",
")",
":",
"colors",
"=",
"(",
")",
"if",
"is_a_tty",
"(",
")",
"and",
"not",
"env",
".",
"SSH_CLIENT",
":",
"if",
"not",
"'index'",
"in",
"_color_code_map",
":",
"_color_code_map",
"[",
"'ind... | Query the default terminal, for colors, etc.
Direct queries supported on xterm, iTerm, perhaps others.
Arguments:
str: name, one of ('foreground', 'fg', 'background', 'bg',
or 'index') # index grabs a palette index
int: or a "dynamic color n... | [
"Query",
"the",
"default",
"terminal",
"for",
"colors",
"etc",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L452-L525 |
47,766 | mixmastamyk/console | console/detection.py | get_position | def get_position(fallback=CURSOR_POS_FALLBACK):
''' Return the current column number of the terminal cursor.
Used to figure out if we need to print an extra newline.
Returns:
tuple(int): (x, y), (,) - empty, if an error occurred.
TODO: needs non-ansi mode for Windows
N... | python | def get_position(fallback=CURSOR_POS_FALLBACK):
''' Return the current column number of the terminal cursor.
Used to figure out if we need to print an extra newline.
Returns:
tuple(int): (x, y), (,) - empty, if an error occurred.
TODO: needs non-ansi mode for Windows
N... | [
"def",
"get_position",
"(",
"fallback",
"=",
"CURSOR_POS_FALLBACK",
")",
":",
"values",
"=",
"fallback",
"if",
"is_a_tty",
"(",
")",
":",
"import",
"tty",
",",
"termios",
"try",
":",
"with",
"TermStack",
"(",
")",
"as",
"fd",
":",
"tty",
".",
"setcbreak"... | Return the current column number of the terminal cursor.
Used to figure out if we need to print an extra newline.
Returns:
tuple(int): (x, y), (,) - empty, if an error occurred.
TODO: needs non-ansi mode for Windows
Note:
Checks is_a_tty() first, since function... | [
"Return",
"the",
"current",
"column",
"number",
"of",
"the",
"terminal",
"cursor",
".",
"Used",
"to",
"figure",
"out",
"if",
"we",
"need",
"to",
"print",
"an",
"extra",
"newline",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L528-L559 |
47,767 | mixmastamyk/console | console/detection.py | get_theme | def get_theme():
''' Checks system for theme information.
First checks for the environment variable COLORFGBG.
Next, queries terminal, supported on Windows and xterm, perhaps others.
See notes on get_color().
Returns:
str, None: 'dark', 'light', None if no information.
... | python | def get_theme():
''' Checks system for theme information.
First checks for the environment variable COLORFGBG.
Next, queries terminal, supported on Windows and xterm, perhaps others.
See notes on get_color().
Returns:
str, None: 'dark', 'light', None if no information.
... | [
"def",
"get_theme",
"(",
")",
":",
"theme",
"=",
"None",
"log",
".",
"debug",
"(",
"'COLORFGBG: %s'",
",",
"env",
".",
"COLORFGBG",
")",
"if",
"env",
".",
"COLORFGBG",
":",
"FG",
",",
"_",
",",
"BG",
"=",
"env",
".",
"COLORFGBG",
".",
"partition",
... | Checks system for theme information.
First checks for the environment variable COLORFGBG.
Next, queries terminal, supported on Windows and xterm, perhaps others.
See notes on get_color().
Returns:
str, None: 'dark', 'light', None if no information. | [
"Checks",
"system",
"for",
"theme",
"information",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L631-L665 |
47,768 | justanr/Flask-Transfer | examples/allotr/allotr/transfer.py | really_bad_du | def really_bad_du(path):
"Don't actually use this, it's just an example."
return sum([os.path.getsize(fp) for fp in list_files(path)]) | python | def really_bad_du(path):
"Don't actually use this, it's just an example."
return sum([os.path.getsize(fp) for fp in list_files(path)]) | [
"def",
"really_bad_du",
"(",
"path",
")",
":",
"return",
"sum",
"(",
"[",
"os",
".",
"path",
".",
"getsize",
"(",
"fp",
")",
"for",
"fp",
"in",
"list_files",
"(",
"path",
")",
"]",
")"
] | Don't actually use this, it's just an example. | [
"Don",
"t",
"actually",
"use",
"this",
"it",
"s",
"just",
"an",
"example",
"."
] | 075ba9edb8c8d0ea47619cc763394bbb717c2ead | https://github.com/justanr/Flask-Transfer/blob/075ba9edb8c8d0ea47619cc763394bbb717c2ead/examples/allotr/allotr/transfer.py#L18-L20 |
47,769 | justanr/Flask-Transfer | examples/allotr/allotr/transfer.py | check_disk_usage | def check_disk_usage(filehandle, meta):
"""Checks the upload directory to see if the uploaded file would exceed
the total disk allotment. Meant as a quick and dirty example.
"""
# limit it at twenty kilobytes if no default is provided
MAX_DISK_USAGE = current_app.config.get('MAX_DISK_USAGE', 20 * 10... | python | def check_disk_usage(filehandle, meta):
"""Checks the upload directory to see if the uploaded file would exceed
the total disk allotment. Meant as a quick and dirty example.
"""
# limit it at twenty kilobytes if no default is provided
MAX_DISK_USAGE = current_app.config.get('MAX_DISK_USAGE', 20 * 10... | [
"def",
"check_disk_usage",
"(",
"filehandle",
",",
"meta",
")",
":",
"# limit it at twenty kilobytes if no default is provided",
"MAX_DISK_USAGE",
"=",
"current_app",
".",
"config",
".",
"get",
"(",
"'MAX_DISK_USAGE'",
",",
"20",
"*",
"1024",
")",
"CURRENT_USAGE",
"="... | Checks the upload directory to see if the uploaded file would exceed
the total disk allotment. Meant as a quick and dirty example. | [
"Checks",
"the",
"upload",
"directory",
"to",
"see",
"if",
"the",
"uploaded",
"file",
"would",
"exceed",
"the",
"total",
"disk",
"allotment",
".",
"Meant",
"as",
"a",
"quick",
"and",
"dirty",
"example",
"."
] | 075ba9edb8c8d0ea47619cc763394bbb717c2ead | https://github.com/justanr/Flask-Transfer/blob/075ba9edb8c8d0ea47619cc763394bbb717c2ead/examples/allotr/allotr/transfer.py#L24-L37 |
47,770 | mixmastamyk/console | setup.py | get_version | def get_version(filename, version='1.00'):
''' Read version as text to avoid machinations at import time. '''
with open(filename) as infile:
for line in infile:
if line.startswith('__version__'):
try:
version = line.split("'")[1]
except Ind... | python | def get_version(filename, version='1.00'):
''' Read version as text to avoid machinations at import time. '''
with open(filename) as infile:
for line in infile:
if line.startswith('__version__'):
try:
version = line.split("'")[1]
except Ind... | [
"def",
"get_version",
"(",
"filename",
",",
"version",
"=",
"'1.00'",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"infile",
":",
"for",
"line",
"in",
"infile",
":",
"if",
"line",
".",
"startswith",
"(",
"'__version__'",
")",
":",
"try",
":",
... | Read version as text to avoid machinations at import time. | [
"Read",
"version",
"as",
"text",
"to",
"avoid",
"machinations",
"at",
"import",
"time",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/setup.py#L25-L35 |
47,771 | mixmastamyk/console | console/proximity.py | find_nearest_color_index | def find_nearest_color_index(r, g, b, color_table=None, method='euclid'):
''' Given three integers representing R, G, and B,
return the nearest color index.
Arguments:
r: int - of range 0…255
g: int - of range 0…255
b: int - of range 0…255
Retur... | python | def find_nearest_color_index(r, g, b, color_table=None, method='euclid'):
''' Given three integers representing R, G, and B,
return the nearest color index.
Arguments:
r: int - of range 0…255
g: int - of range 0…255
b: int - of range 0…255
Retur... | [
"def",
"find_nearest_color_index",
"(",
"r",
",",
"g",
",",
"b",
",",
"color_table",
"=",
"None",
",",
"method",
"=",
"'euclid'",
")",
":",
"shortest_distance",
"=",
"257",
"*",
"257",
"*",
"3",
"# max eucl. distance from #000000 to #ffffff",
"index",
"=",
"0"... | Given three integers representing R, G, and B,
return the nearest color index.
Arguments:
r: int - of range 0…255
g: int - of range 0…255
b: int - of range 0…255
Returns:
int, None: index, or None on error. | [
"Given",
"three",
"integers",
"representing",
"R",
"G",
"and",
"B",
"return",
"the",
"nearest",
"color",
"index",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/proximity.py#L77-L107 |
47,772 | mixmastamyk/console | console/proximity.py | find_nearest_color_hexstr | def find_nearest_color_hexstr(hexdigits, color_table=None, method='euclid'):
''' Given a three or six-character hex digit string, return the nearest
color index.
Arguments:
hexdigits: a three/6 digit hex string, e.g. 'b0b', '123456'
Returns:
int, None: index, or No... | python | def find_nearest_color_hexstr(hexdigits, color_table=None, method='euclid'):
''' Given a three or six-character hex digit string, return the nearest
color index.
Arguments:
hexdigits: a three/6 digit hex string, e.g. 'b0b', '123456'
Returns:
int, None: index, or No... | [
"def",
"find_nearest_color_hexstr",
"(",
"hexdigits",
",",
"color_table",
"=",
"None",
",",
"method",
"=",
"'euclid'",
")",
":",
"triplet",
"=",
"[",
"]",
"try",
":",
"if",
"len",
"(",
"hexdigits",
")",
"==",
"3",
":",
"for",
"digit",
"in",
"hexdigits",
... | Given a three or six-character hex digit string, return the nearest
color index.
Arguments:
hexdigits: a three/6 digit hex string, e.g. 'b0b', '123456'
Returns:
int, None: index, or None on error. | [
"Given",
"a",
"three",
"or",
"six",
"-",
"character",
"hex",
"digit",
"string",
"return",
"the",
"nearest",
"color",
"index",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/proximity.py#L110-L135 |
47,773 | konstantint/pyliftover | pyliftover/intervaltree.py | IntervalTree.add_interval | def add_interval(self, start, end, data=None):
'''
Inserts an interval to the tree.
Note that when inserting we do not maintain appropriate sorting of the "mid" data structure.
This should be done after all intervals are inserted.
'''
# Ignore intervals of 0 or negative ... | python | def add_interval(self, start, end, data=None):
'''
Inserts an interval to the tree.
Note that when inserting we do not maintain appropriate sorting of the "mid" data structure.
This should be done after all intervals are inserted.
'''
# Ignore intervals of 0 or negative ... | [
"def",
"add_interval",
"(",
"self",
",",
"start",
",",
"end",
",",
"data",
"=",
"None",
")",
":",
"# Ignore intervals of 0 or negative length",
"if",
"(",
"end",
"-",
"start",
")",
"<=",
"0",
":",
"return",
"if",
"self",
".",
"single_interval",
"is",
"None... | Inserts an interval to the tree.
Note that when inserting we do not maintain appropriate sorting of the "mid" data structure.
This should be done after all intervals are inserted. | [
"Inserts",
"an",
"interval",
"to",
"the",
"tree",
".",
"Note",
"that",
"when",
"inserting",
"we",
"do",
"not",
"maintain",
"appropriate",
"sorting",
"of",
"the",
"mid",
"data",
"structure",
".",
"This",
"should",
"be",
"done",
"after",
"all",
"intervals",
... | 5164eed9ae678ad0ddc164df8c2c5767e6a4b39f | https://github.com/konstantint/pyliftover/blob/5164eed9ae678ad0ddc164df8c2c5767e6a4b39f/pyliftover/intervaltree.py#L55-L74 |
47,774 | konstantint/pyliftover | pyliftover/intervaltree.py | IntervalTree._query | def _query(self, x, result):
'''
Same as self.query, but uses a provided list to accumulate results into.
'''
if self.single_interval is None: # Empty
return
elif self.single_interval != 0: # Single interval, just check whether x is in it
if self.single_i... | python | def _query(self, x, result):
'''
Same as self.query, but uses a provided list to accumulate results into.
'''
if self.single_interval is None: # Empty
return
elif self.single_interval != 0: # Single interval, just check whether x is in it
if self.single_i... | [
"def",
"_query",
"(",
"self",
",",
"x",
",",
"result",
")",
":",
"if",
"self",
".",
"single_interval",
"is",
"None",
":",
"# Empty",
"return",
"elif",
"self",
".",
"single_interval",
"!=",
"0",
":",
"# Single interval, just check whether x is in it",
"if",
"se... | Same as self.query, but uses a provided list to accumulate results into. | [
"Same",
"as",
"self",
".",
"query",
"but",
"uses",
"a",
"provided",
"list",
"to",
"accumulate",
"results",
"into",
"."
] | 5164eed9ae678ad0ddc164df8c2c5767e6a4b39f | https://github.com/konstantint/pyliftover/blob/5164eed9ae678ad0ddc164df8c2c5767e6a4b39f/pyliftover/intervaltree.py#L111-L135 |
47,775 | Oneiroe/PySimpleAutomata | PySimpleAutomata/DFA.py | dfa_complementation | def dfa_complementation(dfa: dict) -> dict:
""" Returns a DFA that accepts any word but he ones accepted
by the input DFA.
Let A be a completed DFA, :math:`Ā = (Σ, S, s_0 , ρ, S − F )`
is the DFA that runs A but accepts whatever word A does not.
:param dict dfa: input DFA.
:return: *(dict)* re... | python | def dfa_complementation(dfa: dict) -> dict:
""" Returns a DFA that accepts any word but he ones accepted
by the input DFA.
Let A be a completed DFA, :math:`Ā = (Σ, S, s_0 , ρ, S − F )`
is the DFA that runs A but accepts whatever word A does not.
:param dict dfa: input DFA.
:return: *(dict)* re... | [
"def",
"dfa_complementation",
"(",
"dfa",
":",
"dict",
")",
"->",
"dict",
":",
"dfa_complement",
"=",
"dfa_completion",
"(",
"deepcopy",
"(",
"dfa",
")",
")",
"dfa_complement",
"[",
"'accepting_states'",
"]",
"=",
"dfa_complement",
"[",
"'states'",
"]",
".",
... | Returns a DFA that accepts any word but he ones accepted
by the input DFA.
Let A be a completed DFA, :math:`Ā = (Σ, S, s_0 , ρ, S − F )`
is the DFA that runs A but accepts whatever word A does not.
:param dict dfa: input DFA.
:return: *(dict)* representing the complement of the input DFA. | [
"Returns",
"a",
"DFA",
"that",
"accepts",
"any",
"word",
"but",
"he",
"ones",
"accepted",
"by",
"the",
"input",
"DFA",
"."
] | 0f9f2705fd8ddd5d8118bc31552a640f5d00c359 | https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/DFA.py#L89-L102 |
47,776 | Oneiroe/PySimpleAutomata | PySimpleAutomata/DFA.py | dfa_intersection | def dfa_intersection(dfa_1: dict, dfa_2: dict) -> dict:
""" Returns a DFA accepting the intersection of the DFAs in
input.
Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and
:math:`A_2 = (Σ, S_2 , s_{02} , ρ_2 , F_2 )` be two DFAs.
Then there is a DFA :math:`A_∧` that runs simultaneously both
... | python | def dfa_intersection(dfa_1: dict, dfa_2: dict) -> dict:
""" Returns a DFA accepting the intersection of the DFAs in
input.
Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and
:math:`A_2 = (Σ, S_2 , s_{02} , ρ_2 , F_2 )` be two DFAs.
Then there is a DFA :math:`A_∧` that runs simultaneously both
... | [
"def",
"dfa_intersection",
"(",
"dfa_1",
":",
"dict",
",",
"dfa_2",
":",
"dict",
")",
"->",
"dict",
":",
"intersection",
"=",
"{",
"'alphabet'",
":",
"dfa_1",
"[",
"'alphabet'",
"]",
".",
"intersection",
"(",
"dfa_2",
"[",
"'alphabet'",
"]",
")",
",",
... | Returns a DFA accepting the intersection of the DFAs in
input.
Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and
:math:`A_2 = (Σ, S_2 , s_{02} , ρ_2 , F_2 )` be two DFAs.
Then there is a DFA :math:`A_∧` that runs simultaneously both
:math:`A_1` and :math:`A_2` on the input word and
accepts w... | [
"Returns",
"a",
"DFA",
"accepting",
"the",
"intersection",
"of",
"the",
"DFAs",
"in",
"input",
"."
] | 0f9f2705fd8ddd5d8118bc31552a640f5d00c359 | https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/DFA.py#L105-L157 |
47,777 | Oneiroe/PySimpleAutomata | PySimpleAutomata/DFA.py | dfa_union | def dfa_union(dfa_1: dict, dfa_2: dict) -> dict:
""" Returns a DFA accepting the union of the input DFAs.
Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and
:math:`A_2 = (Σ, S_2 , s_{02} , ρ_2 , F_2 )` be two completed
DFAs.
Then there is a DFA :math:`A_∨` that runs simultaneously both
:math:... | python | def dfa_union(dfa_1: dict, dfa_2: dict) -> dict:
""" Returns a DFA accepting the union of the input DFAs.
Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and
:math:`A_2 = (Σ, S_2 , s_{02} , ρ_2 , F_2 )` be two completed
DFAs.
Then there is a DFA :math:`A_∨` that runs simultaneously both
:math:... | [
"def",
"dfa_union",
"(",
"dfa_1",
":",
"dict",
",",
"dfa_2",
":",
"dict",
")",
"->",
"dict",
":",
"dfa_1",
"=",
"deepcopy",
"(",
"dfa_1",
")",
"dfa_2",
"=",
"deepcopy",
"(",
"dfa_2",
")",
"dfa_1",
"[",
"'alphabet'",
"]",
"=",
"dfa_2",
"[",
"'alphabet... | Returns a DFA accepting the union of the input DFAs.
Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and
:math:`A_2 = (Σ, S_2 , s_{02} , ρ_2 , F_2 )` be two completed
DFAs.
Then there is a DFA :math:`A_∨` that runs simultaneously both
:math:`A_1` and :math:`A_2` on the input word
and accepts w... | [
"Returns",
"a",
"DFA",
"accepting",
"the",
"union",
"of",
"the",
"input",
"DFAs",
"."
] | 0f9f2705fd8ddd5d8118bc31552a640f5d00c359 | https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/DFA.py#L160-L218 |
47,778 | Oneiroe/PySimpleAutomata | PySimpleAutomata/DFA.py | dfa_minimization | def dfa_minimization(dfa: dict) -> dict:
""" Returns the minimization of the DFA in input through a
greatest fix-point method.
Given a completed DFA :math:`A = (Σ, S, s_0 , ρ, F )` there
exists a single minimal DFA :math:`A_m`
which is equivalent to A, i.e. reads the same language
:math:`L(A) =... | python | def dfa_minimization(dfa: dict) -> dict:
""" Returns the minimization of the DFA in input through a
greatest fix-point method.
Given a completed DFA :math:`A = (Σ, S, s_0 , ρ, F )` there
exists a single minimal DFA :math:`A_m`
which is equivalent to A, i.e. reads the same language
:math:`L(A) =... | [
"def",
"dfa_minimization",
"(",
"dfa",
":",
"dict",
")",
"->",
"dict",
":",
"dfa",
"=",
"dfa_completion",
"(",
"deepcopy",
"(",
"dfa",
")",
")",
"################################################################",
"### Greatest-fixpoint",
"z_current",
"=",
"set",
"(",
... | Returns the minimization of the DFA in input through a
greatest fix-point method.
Given a completed DFA :math:`A = (Σ, S, s_0 , ρ, F )` there
exists a single minimal DFA :math:`A_m`
which is equivalent to A, i.e. reads the same language
:math:`L(A) = L(A_m)` and with a minimal number of states.
... | [
"Returns",
"the",
"minimization",
"of",
"the",
"DFA",
"in",
"input",
"through",
"a",
"greatest",
"fix",
"-",
"point",
"method",
"."
] | 0f9f2705fd8ddd5d8118bc31552a640f5d00c359 | https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/DFA.py#L221-L326 |
47,779 | Oneiroe/PySimpleAutomata | PySimpleAutomata/DFA.py | dfa_reachable | def dfa_reachable(dfa: dict) -> dict:
""" Side effects on input! Removes unreachable states from a
DFA and returns the pruned DFA.
It is possible to remove from a DFA A all unreachable states
from the initial state without altering the language.
The reachable DFA :math:`A_R` corresponding to A is d... | python | def dfa_reachable(dfa: dict) -> dict:
""" Side effects on input! Removes unreachable states from a
DFA and returns the pruned DFA.
It is possible to remove from a DFA A all unreachable states
from the initial state without altering the language.
The reachable DFA :math:`A_R` corresponding to A is d... | [
"def",
"dfa_reachable",
"(",
"dfa",
":",
"dict",
")",
"->",
"dict",
":",
"reachable_states",
"=",
"set",
"(",
")",
"# set of reachable states from root",
"boundary",
"=",
"set",
"(",
")",
"reachable_states",
".",
"add",
"(",
"dfa",
"[",
"'initial_state'",
"]",... | Side effects on input! Removes unreachable states from a
DFA and returns the pruned DFA.
It is possible to remove from a DFA A all unreachable states
from the initial state without altering the language.
The reachable DFA :math:`A_R` corresponding to A is defined as:
:math:`A_R = (Σ, S_R , s_0 , ρ... | [
"Side",
"effects",
"on",
"input!",
"Removes",
"unreachable",
"states",
"from",
"a",
"DFA",
"and",
"returns",
"the",
"pruned",
"DFA",
"."
] | 0f9f2705fd8ddd5d8118bc31552a640f5d00c359 | https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/DFA.py#L330-L373 |
47,780 | Oneiroe/PySimpleAutomata | PySimpleAutomata/DFA.py | dfa_co_reachable | def dfa_co_reachable(dfa: dict) -> dict:
""" Side effects on input! Removes from the DFA all states that
do not reach a final state and returns the pruned DFA.
It is possible to remove from a DFA A all states that do not
reach a final state without altering the language.
The co-reachable dfa :math:... | python | def dfa_co_reachable(dfa: dict) -> dict:
""" Side effects on input! Removes from the DFA all states that
do not reach a final state and returns the pruned DFA.
It is possible to remove from a DFA A all states that do not
reach a final state without altering the language.
The co-reachable dfa :math:... | [
"def",
"dfa_co_reachable",
"(",
"dfa",
":",
"dict",
")",
"->",
"dict",
":",
"co_reachable_states",
"=",
"dfa",
"[",
"'accepting_states'",
"]",
".",
"copy",
"(",
")",
"boundary",
"=",
"co_reachable_states",
".",
"copy",
"(",
")",
"# inverse transition function",
... | Side effects on input! Removes from the DFA all states that
do not reach a final state and returns the pruned DFA.
It is possible to remove from a DFA A all states that do not
reach a final state without altering the language.
The co-reachable dfa :math:`A_F` corresponding to A is
defined as:
... | [
"Side",
"effects",
"on",
"input!",
"Removes",
"from",
"the",
"DFA",
"all",
"states",
"that",
"do",
"not",
"reach",
"a",
"final",
"state",
"and",
"returns",
"the",
"pruned",
"DFA",
"."
] | 0f9f2705fd8ddd5d8118bc31552a640f5d00c359 | https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/DFA.py#L377-L433 |
47,781 | Oneiroe/PySimpleAutomata | PySimpleAutomata/DFA.py | dfa_trimming | def dfa_trimming(dfa: dict) -> dict:
""" Side effects on input! Returns the DFA in input trimmed,
so both reachable and co-reachable.
Given a DFA A, the corresponding trimmed DFA contains only
those states that are reachable from the initial state
and that lead to a final state.
The trimmed dfa... | python | def dfa_trimming(dfa: dict) -> dict:
""" Side effects on input! Returns the DFA in input trimmed,
so both reachable and co-reachable.
Given a DFA A, the corresponding trimmed DFA contains only
those states that are reachable from the initial state
and that lead to a final state.
The trimmed dfa... | [
"def",
"dfa_trimming",
"(",
"dfa",
":",
"dict",
")",
"->",
"dict",
":",
"# Reachable DFA",
"dfa",
"=",
"dfa_reachable",
"(",
"dfa",
")",
"# Co-reachable DFA",
"dfa",
"=",
"dfa_co_reachable",
"(",
"dfa",
")",
"# trimmed DFA",
"return",
"dfa"
] | Side effects on input! Returns the DFA in input trimmed,
so both reachable and co-reachable.
Given a DFA A, the corresponding trimmed DFA contains only
those states that are reachable from the initial state
and that lead to a final state.
The trimmed dfa :math:`A_{RF}` corresponding to A is defined... | [
"Side",
"effects",
"on",
"input!",
"Returns",
"the",
"DFA",
"in",
"input",
"trimmed",
"so",
"both",
"reachable",
"and",
"co",
"-",
"reachable",
"."
] | 0f9f2705fd8ddd5d8118bc31552a640f5d00c359 | https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/DFA.py#L437-L463 |
47,782 | konstantint/pyliftover | pyliftover/chainfile.py | LiftOverChainFile._load_chains | def _load_chains(f):
'''
Loads all LiftOverChain objects from a file into an array. Returns the result.
'''
chains = []
while True:
line = f.readline()
if not line:
break
if line.startswith(b'#') or line.startswith(b'\n') or lin... | python | def _load_chains(f):
'''
Loads all LiftOverChain objects from a file into an array. Returns the result.
'''
chains = []
while True:
line = f.readline()
if not line:
break
if line.startswith(b'#') or line.startswith(b'\n') or lin... | [
"def",
"_load_chains",
"(",
"f",
")",
":",
"chains",
"=",
"[",
"]",
"while",
"True",
":",
"line",
"=",
"f",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"break",
"if",
"line",
".",
"startswith",
"(",
"b'#'",
")",
"or",
"line",
".",
"start... | Loads all LiftOverChain objects from a file into an array. Returns the result. | [
"Loads",
"all",
"LiftOverChain",
"objects",
"from",
"a",
"file",
"into",
"an",
"array",
".",
"Returns",
"the",
"result",
"."
] | 5164eed9ae678ad0ddc164df8c2c5767e6a4b39f | https://github.com/konstantint/pyliftover/blob/5164eed9ae678ad0ddc164df8c2c5767e6a4b39f/pyliftover/chainfile.py#L106-L121 |
47,783 | mmcloughlin/luhn | luhn.py | checksum | def checksum(string):
"""
Compute the Luhn checksum for the provided string of digits. Note this
assumes the check digit is in place.
"""
digits = list(map(int, string))
odd_sum = sum(digits[-1::-2])
even_sum = sum([sum(divmod(2 * d, 10)) for d in digits[-2::-2]])
return (odd_sum + even_... | python | def checksum(string):
"""
Compute the Luhn checksum for the provided string of digits. Note this
assumes the check digit is in place.
"""
digits = list(map(int, string))
odd_sum = sum(digits[-1::-2])
even_sum = sum([sum(divmod(2 * d, 10)) for d in digits[-2::-2]])
return (odd_sum + even_... | [
"def",
"checksum",
"(",
"string",
")",
":",
"digits",
"=",
"list",
"(",
"map",
"(",
"int",
",",
"string",
")",
")",
"odd_sum",
"=",
"sum",
"(",
"digits",
"[",
"-",
"1",
":",
":",
"-",
"2",
"]",
")",
"even_sum",
"=",
"sum",
"(",
"[",
"sum",
"(... | Compute the Luhn checksum for the provided string of digits. Note this
assumes the check digit is in place. | [
"Compute",
"the",
"Luhn",
"checksum",
"for",
"the",
"provided",
"string",
"of",
"digits",
".",
"Note",
"this",
"assumes",
"the",
"check",
"digit",
"is",
"in",
"place",
"."
] | d6f3fa71072f99334a4c1d2a3f062fa93982797f | https://github.com/mmcloughlin/luhn/blob/d6f3fa71072f99334a4c1d2a3f062fa93982797f/luhn.py#L3-L11 |
47,784 | sdonk/django-admin-ip-restrictor | admin_ip_restrictor/middleware.py | AdminIPRestrictorMiddleware.is_blocked | def is_blocked(self, ip):
"""Determine if an IP address should be considered blocked."""
blocked = True
if ip in self.allowed_admin_ips:
blocked = False
for allowed_range in self.allowed_admin_ip_ranges:
if ipaddress.ip_address(ip) in ipaddress.ip_network(allowe... | python | def is_blocked(self, ip):
"""Determine if an IP address should be considered blocked."""
blocked = True
if ip in self.allowed_admin_ips:
blocked = False
for allowed_range in self.allowed_admin_ip_ranges:
if ipaddress.ip_address(ip) in ipaddress.ip_network(allowe... | [
"def",
"is_blocked",
"(",
"self",
",",
"ip",
")",
":",
"blocked",
"=",
"True",
"if",
"ip",
"in",
"self",
".",
"allowed_admin_ips",
":",
"blocked",
"=",
"False",
"for",
"allowed_range",
"in",
"self",
".",
"allowed_admin_ip_ranges",
":",
"if",
"ipaddress",
"... | Determine if an IP address should be considered blocked. | [
"Determine",
"if",
"an",
"IP",
"address",
"should",
"be",
"considered",
"blocked",
"."
] | 29c948677e52bc416d44fff0f013d1f4ba2cb782 | https://github.com/sdonk/django-admin-ip-restrictor/blob/29c948677e52bc416d44fff0f013d1f4ba2cb782/admin_ip_restrictor/middleware.py#L60-L71 |
47,785 | entrepreneur-interet-general/mkinx | mkinx/commands.py | serve | def serve(args):
"""Start a server which will watch .md and .rst files for changes.
If a md file changes, the Home Documentation is rebuilt. If a .rst
file changes, the updated sphinx project is rebuilt
Args:
args (ArgumentParser): flags from the CLI
"""
# Sever's parameters
port = ... | python | def serve(args):
"""Start a server which will watch .md and .rst files for changes.
If a md file changes, the Home Documentation is rebuilt. If a .rst
file changes, the updated sphinx project is rebuilt
Args:
args (ArgumentParser): flags from the CLI
"""
# Sever's parameters
port = ... | [
"def",
"serve",
"(",
"args",
")",
":",
"# Sever's parameters",
"port",
"=",
"args",
".",
"serve_port",
"or",
"PORT",
"host",
"=",
"\"0.0.0.0\"",
"# Current working directory",
"dir_path",
"=",
"Path",
"(",
")",
".",
"absolute",
"(",
")",
"web_dir",
"=",
"dir... | Start a server which will watch .md and .rst files for changes.
If a md file changes, the Home Documentation is rebuilt. If a .rst
file changes, the updated sphinx project is rebuilt
Args:
args (ArgumentParser): flags from the CLI | [
"Start",
"a",
"server",
"which",
"will",
"watch",
".",
"md",
"and",
".",
"rst",
"files",
"for",
"changes",
".",
"If",
"a",
"md",
"file",
"changes",
"the",
"Home",
"Documentation",
"is",
"rebuilt",
".",
"If",
"a",
".",
"rst",
"file",
"changes",
"the",
... | 70ccf81d3fad974283829ca4ec069a873341461d | https://github.com/entrepreneur-interet-general/mkinx/blob/70ccf81d3fad974283829ca4ec069a873341461d/mkinx/commands.py#L45-L138 |
47,786 | entrepreneur-interet-general/mkinx | mkinx/include/example_project/classif/models.py | LogisticRegressor.train | def train(self, X_train, Y_train, X_test, Y_test):
"""Train and validate the LR on a train and test dataset
Args:
X_train (np.array): Training data
Y_train (np.array): Training labels
X_test (np.array): Test data
Y_test (np.array): Test labels
"""... | python | def train(self, X_train, Y_train, X_test, Y_test):
"""Train and validate the LR on a train and test dataset
Args:
X_train (np.array): Training data
Y_train (np.array): Training labels
X_test (np.array): Test data
Y_test (np.array): Test labels
"""... | [
"def",
"train",
"(",
"self",
",",
"X_train",
",",
"Y_train",
",",
"X_test",
",",
"Y_test",
")",
":",
"while",
"True",
":",
"print",
"(",
"1",
")",
"time",
".",
"sleep",
"(",
"1",
")",
"if",
"random",
".",
"randint",
"(",
"0",
",",
"9",
")",
">=... | Train and validate the LR on a train and test dataset
Args:
X_train (np.array): Training data
Y_train (np.array): Training labels
X_test (np.array): Test data
Y_test (np.array): Test labels | [
"Train",
"and",
"validate",
"the",
"LR",
"on",
"a",
"train",
"and",
"test",
"dataset"
] | 70ccf81d3fad974283829ca4ec069a873341461d | https://github.com/entrepreneur-interet-general/mkinx/blob/70ccf81d3fad974283829ca4ec069a873341461d/mkinx/include/example_project/classif/models.py#L24-L38 |
47,787 | choldgraf/download | download/download.py | download | def download(url, path, kind='file',
progressbar=True, replace=False, timeout=10., verbose=True):
"""Download a URL.
This will download a file and store it in a '~/data/` folder,
creating directories if need be. It will also work for zip
files, in which case it will unzip all of the files ... | python | def download(url, path, kind='file',
progressbar=True, replace=False, timeout=10., verbose=True):
"""Download a URL.
This will download a file and store it in a '~/data/` folder,
creating directories if need be. It will also work for zip
files, in which case it will unzip all of the files ... | [
"def",
"download",
"(",
"url",
",",
"path",
",",
"kind",
"=",
"'file'",
",",
"progressbar",
"=",
"True",
",",
"replace",
"=",
"False",
",",
"timeout",
"=",
"10.",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"kind",
"not",
"in",
"ALLOWED_KINDS",
":",... | Download a URL.
This will download a file and store it in a '~/data/` folder,
creating directories if need be. It will also work for zip
files, in which case it will unzip all of the files to the
desired location.
Parameters
----------
url : string
The url of the file to download. ... | [
"Download",
"a",
"URL",
"."
] | 26007bb87751ee35791e30e4dfc54dd088bf15e6 | https://github.com/choldgraf/download/blob/26007bb87751ee35791e30e4dfc54dd088bf15e6/download/download.py#L27-L113 |
47,788 | choldgraf/download | download/download.py | _convert_url_to_downloadable | def _convert_url_to_downloadable(url):
"""Convert a url to the proper style depending on its website."""
if 'drive.google.com' in url:
# For future support of google drive
file_id = url.split('d/')[1].split('/')[0]
base_url = 'https://drive.google.com/uc?export=download&id='
out... | python | def _convert_url_to_downloadable(url):
"""Convert a url to the proper style depending on its website."""
if 'drive.google.com' in url:
# For future support of google drive
file_id = url.split('d/')[1].split('/')[0]
base_url = 'https://drive.google.com/uc?export=download&id='
out... | [
"def",
"_convert_url_to_downloadable",
"(",
"url",
")",
":",
"if",
"'drive.google.com'",
"in",
"url",
":",
"# For future support of google drive",
"file_id",
"=",
"url",
".",
"split",
"(",
"'d/'",
")",
"[",
"1",
"]",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
... | Convert a url to the proper style depending on its website. | [
"Convert",
"a",
"url",
"to",
"the",
"proper",
"style",
"depending",
"on",
"its",
"website",
"."
] | 26007bb87751ee35791e30e4dfc54dd088bf15e6 | https://github.com/choldgraf/download/blob/26007bb87751ee35791e30e4dfc54dd088bf15e6/download/download.py#L116-L134 |
47,789 | choldgraf/download | download/download.py | md5sum | def md5sum(fname, block_size=1048576): # 2 ** 20
"""Calculate the md5sum for a file.
Parameters
----------
fname : str
Filename.
block_size : int
Block size to use when reading.
Returns
-------
hash_ : str
The hexadecimal digest of the hash.
"""
md5 = h... | python | def md5sum(fname, block_size=1048576): # 2 ** 20
"""Calculate the md5sum for a file.
Parameters
----------
fname : str
Filename.
block_size : int
Block size to use when reading.
Returns
-------
hash_ : str
The hexadecimal digest of the hash.
"""
md5 = h... | [
"def",
"md5sum",
"(",
"fname",
",",
"block_size",
"=",
"1048576",
")",
":",
"# 2 ** 20",
"md5",
"=",
"hashlib",
".",
"md5",
"(",
")",
"with",
"open",
"(",
"fname",
",",
"'rb'",
")",
"as",
"fid",
":",
"while",
"True",
":",
"data",
"=",
"fid",
".",
... | Calculate the md5sum for a file.
Parameters
----------
fname : str
Filename.
block_size : int
Block size to use when reading.
Returns
-------
hash_ : str
The hexadecimal digest of the hash. | [
"Calculate",
"the",
"md5sum",
"for",
"a",
"file",
"."
] | 26007bb87751ee35791e30e4dfc54dd088bf15e6 | https://github.com/choldgraf/download/blob/26007bb87751ee35791e30e4dfc54dd088bf15e6/download/download.py#L322-L344 |
47,790 | choldgraf/download | download/download.py | _chunk_write | def _chunk_write(chunk, local_file, progress):
"""Write a chunk to file and update the progress bar."""
local_file.write(chunk)
if progress is not None:
progress.update(len(chunk)) | python | def _chunk_write(chunk, local_file, progress):
"""Write a chunk to file and update the progress bar."""
local_file.write(chunk)
if progress is not None:
progress.update(len(chunk)) | [
"def",
"_chunk_write",
"(",
"chunk",
",",
"local_file",
",",
"progress",
")",
":",
"local_file",
".",
"write",
"(",
"chunk",
")",
"if",
"progress",
"is",
"not",
"None",
":",
"progress",
".",
"update",
"(",
"len",
"(",
"chunk",
")",
")"
] | Write a chunk to file and update the progress bar. | [
"Write",
"a",
"chunk",
"to",
"file",
"and",
"update",
"the",
"progress",
"bar",
"."
] | 26007bb87751ee35791e30e4dfc54dd088bf15e6 | https://github.com/choldgraf/download/blob/26007bb87751ee35791e30e4dfc54dd088bf15e6/download/download.py#L347-L351 |
47,791 | choldgraf/download | download/download.py | sizeof_fmt | def sizeof_fmt(num):
"""Turn number of bytes into human-readable str.
Parameters
----------
num : int
The number of bytes.
Returns
-------
size : str
The size in human-readable format.
"""
units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB']
decimals = [0, 0, 1, 2, 2... | python | def sizeof_fmt(num):
"""Turn number of bytes into human-readable str.
Parameters
----------
num : int
The number of bytes.
Returns
-------
size : str
The size in human-readable format.
"""
units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB']
decimals = [0, 0, 1, 2, 2... | [
"def",
"sizeof_fmt",
"(",
"num",
")",
":",
"units",
"=",
"[",
"'bytes'",
",",
"'kB'",
",",
"'MB'",
",",
"'GB'",
",",
"'TB'",
",",
"'PB'",
"]",
"decimals",
"=",
"[",
"0",
",",
"0",
",",
"1",
",",
"2",
",",
"2",
",",
"2",
"]",
"if",
"num",
">... | Turn number of bytes into human-readable str.
Parameters
----------
num : int
The number of bytes.
Returns
-------
size : str
The size in human-readable format. | [
"Turn",
"number",
"of",
"bytes",
"into",
"human",
"-",
"readable",
"str",
"."
] | 26007bb87751ee35791e30e4dfc54dd088bf15e6 | https://github.com/choldgraf/download/blob/26007bb87751ee35791e30e4dfc54dd088bf15e6/download/download.py#L354-L379 |
47,792 | rasky/geventconnpool | src/geventconnpool/pool.py | retry | def retry(f, exc_classes=DEFAULT_EXC_CLASSES, logger=None,
retry_log_level=logging.INFO,
retry_log_message="Connection broken in '{f}' (error: '{e}'); "
"retrying with new connection.",
max_failures=None, interval=0,
max_failure_log_level=logging.ERROR... | python | def retry(f, exc_classes=DEFAULT_EXC_CLASSES, logger=None,
retry_log_level=logging.INFO,
retry_log_message="Connection broken in '{f}' (error: '{e}'); "
"retrying with new connection.",
max_failures=None, interval=0,
max_failure_log_level=logging.ERROR... | [
"def",
"retry",
"(",
"f",
",",
"exc_classes",
"=",
"DEFAULT_EXC_CLASSES",
",",
"logger",
"=",
"None",
",",
"retry_log_level",
"=",
"logging",
".",
"INFO",
",",
"retry_log_message",
"=",
"\"Connection broken in '{f}' (error: '{e}'); \"",
"\"retrying with new connection.\""... | Decorator to automatically reexecute a function if the connection is
broken for any reason. | [
"Decorator",
"to",
"automatically",
"reexecute",
"a",
"function",
"if",
"the",
"connection",
"is",
"broken",
"for",
"any",
"reason",
"."
] | 47c65c64e051cb62061f3ed072991d6b0a83bbf5 | https://github.com/rasky/geventconnpool/blob/47c65c64e051cb62061f3ed072991d6b0a83bbf5/src/geventconnpool/pool.py#L112-L144 |
47,793 | rasky/geventconnpool | src/geventconnpool/pool.py | ConnectionPool.get | def get(self):
"""
Get a connection from the pool, to make and receive traffic.
If the connection fails for any reason (socket.error), it is dropped
and a new one is scheduled. Please use @retry as a way to automatically
retry whatever operation you were performing.
"""
... | python | def get(self):
"""
Get a connection from the pool, to make and receive traffic.
If the connection fails for any reason (socket.error), it is dropped
and a new one is scheduled. Please use @retry as a way to automatically
retry whatever operation you were performing.
"""
... | [
"def",
"get",
"(",
"self",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"c",
"=",
"self",
".",
"conn",
".",
"popleft",
"(",
")",
"yield",
"c",
"except",
"self",
".",
"exc_classes",
":",
"# The current connection has failed, drop i... | Get a connection from the pool, to make and receive traffic.
If the connection fails for any reason (socket.error), it is dropped
and a new one is scheduled. Please use @retry as a way to automatically
retry whatever operation you were performing. | [
"Get",
"a",
"connection",
"from",
"the",
"pool",
"to",
"make",
"and",
"receive",
"traffic",
"."
] | 47c65c64e051cb62061f3ed072991d6b0a83bbf5 | https://github.com/rasky/geventconnpool/blob/47c65c64e051cb62061f3ed072991d6b0a83bbf5/src/geventconnpool/pool.py#L85-L109 |
47,794 | alimanfoo/vcfnp | vcfnp/eff.py | eff_default_transformer | def eff_default_transformer(fills=EFF_DEFAULT_FILLS):
"""
Return a simple transformer function for parsing EFF annotations. N.B.,
ignores all but the first effect.
"""
def _transformer(vals):
if len(vals) == 0:
return fills
else:
# ignore all but first effect... | python | def eff_default_transformer(fills=EFF_DEFAULT_FILLS):
"""
Return a simple transformer function for parsing EFF annotations. N.B.,
ignores all but the first effect.
"""
def _transformer(vals):
if len(vals) == 0:
return fills
else:
# ignore all but first effect... | [
"def",
"eff_default_transformer",
"(",
"fills",
"=",
"EFF_DEFAULT_FILLS",
")",
":",
"def",
"_transformer",
"(",
"vals",
")",
":",
"if",
"len",
"(",
"vals",
")",
"==",
"0",
":",
"return",
"fills",
"else",
":",
"# ignore all but first effect",
"match_eff_main",
... | Return a simple transformer function for parsing EFF annotations. N.B.,
ignores all but the first effect. | [
"Return",
"a",
"simple",
"transformer",
"function",
"for",
"parsing",
"EFF",
"annotations",
".",
"N",
".",
"B",
".",
"ignores",
"all",
"but",
"the",
"first",
"effect",
"."
] | c3f63fb11ada56d4a88076c61c81f99b8ee78b8f | https://github.com/alimanfoo/vcfnp/blob/c3f63fb11ada56d4a88076c61c81f99b8ee78b8f/vcfnp/eff.py#L69-L96 |
47,795 | alimanfoo/vcfnp | vcfnp/eff.py | ann_default_transformer | def ann_default_transformer(fills=ANN_DEFAULT_FILLS):
"""
Return a simple transformer function for parsing ANN annotations. N.B.,
ignores all but the first effect.
"""
def _transformer(vals):
if len(vals) == 0:
return fills
else:
# ignore all but first effect... | python | def ann_default_transformer(fills=ANN_DEFAULT_FILLS):
"""
Return a simple transformer function for parsing ANN annotations. N.B.,
ignores all but the first effect.
"""
def _transformer(vals):
if len(vals) == 0:
return fills
else:
# ignore all but first effect... | [
"def",
"ann_default_transformer",
"(",
"fills",
"=",
"ANN_DEFAULT_FILLS",
")",
":",
"def",
"_transformer",
"(",
"vals",
")",
":",
"if",
"len",
"(",
"vals",
")",
"==",
"0",
":",
"return",
"fills",
"else",
":",
"# ignore all but first effect",
"ann",
"=",
"val... | Return a simple transformer function for parsing ANN annotations. N.B.,
ignores all but the first effect. | [
"Return",
"a",
"simple",
"transformer",
"function",
"for",
"parsing",
"ANN",
"annotations",
".",
"N",
".",
"B",
".",
"ignores",
"all",
"but",
"the",
"first",
"effect",
"."
] | c3f63fb11ada56d4a88076c61c81f99b8ee78b8f | https://github.com/alimanfoo/vcfnp/blob/c3f63fb11ada56d4a88076c61c81f99b8ee78b8f/vcfnp/eff.py#L104-L126 |
47,796 | bintoro/overloading.py | overloading.py | overloaded | def overloaded(func):
"""
Introduces a new overloaded function and registers its first implementation.
"""
fn = unwrap(func)
ensure_function(fn)
def dispatcher(*args, **kwargs):
resolved = None
if dispatcher.__complex_parameters:
cache_key_pos = []
cache... | python | def overloaded(func):
"""
Introduces a new overloaded function and registers its first implementation.
"""
fn = unwrap(func)
ensure_function(fn)
def dispatcher(*args, **kwargs):
resolved = None
if dispatcher.__complex_parameters:
cache_key_pos = []
cache... | [
"def",
"overloaded",
"(",
"func",
")",
":",
"fn",
"=",
"unwrap",
"(",
"func",
")",
"ensure_function",
"(",
"fn",
")",
"def",
"dispatcher",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"resolved",
"=",
"None",
"if",
"dispatcher",
".",
"__compl... | Introduces a new overloaded function and registers its first implementation. | [
"Introduces",
"a",
"new",
"overloaded",
"function",
"and",
"registers",
"its",
"first",
"implementation",
"."
] | d7b044d6f7e38043f0fc20f44f134baec84a5b32 | https://github.com/bintoro/overloading.py/blob/d7b044d6f7e38043f0fc20f44f134baec84a5b32/overloading.py#L69-L151 |
47,797 | bintoro/overloading.py | overloading.py | register | def register(dispatcher, func, *, hook=None):
"""
Registers `func` as an implementation on `dispatcher`.
"""
wrapper = None
if isinstance(func, (classmethod, staticmethod)):
wrapper = type(func)
func = func.__func__
ensure_function(func)
if isinstance(dispatcher, (classmethod... | python | def register(dispatcher, func, *, hook=None):
"""
Registers `func` as an implementation on `dispatcher`.
"""
wrapper = None
if isinstance(func, (classmethod, staticmethod)):
wrapper = type(func)
func = func.__func__
ensure_function(func)
if isinstance(dispatcher, (classmethod... | [
"def",
"register",
"(",
"dispatcher",
",",
"func",
",",
"*",
",",
"hook",
"=",
"None",
")",
":",
"wrapper",
"=",
"None",
"if",
"isinstance",
"(",
"func",
",",
"(",
"classmethod",
",",
"staticmethod",
")",
")",
":",
"wrapper",
"=",
"type",
"(",
"func"... | Registers `func` as an implementation on `dispatcher`. | [
"Registers",
"func",
"as",
"an",
"implementation",
"on",
"dispatcher",
"."
] | d7b044d6f7e38043f0fc20f44f134baec84a5b32 | https://github.com/bintoro/overloading.py/blob/d7b044d6f7e38043f0fc20f44f134baec84a5b32/overloading.py#L179-L246 |
47,798 | bintoro/overloading.py | overloading.py | find | def find(dispatcher, args, kwargs):
"""
Given the arguments contained in `args` and `kwargs`, returns the best match
from the list of implementations registered on `dispatcher`.
"""
matches = []
full_args = args
full_kwargs = kwargs
for func, sig in dispatcher.__functions:
params... | python | def find(dispatcher, args, kwargs):
"""
Given the arguments contained in `args` and `kwargs`, returns the best match
from the list of implementations registered on `dispatcher`.
"""
matches = []
full_args = args
full_kwargs = kwargs
for func, sig in dispatcher.__functions:
params... | [
"def",
"find",
"(",
"dispatcher",
",",
"args",
",",
"kwargs",
")",
":",
"matches",
"=",
"[",
"]",
"full_args",
"=",
"args",
"full_kwargs",
"=",
"kwargs",
"for",
"func",
",",
"sig",
"in",
"dispatcher",
".",
"__functions",
":",
"params",
"=",
"sig",
".",... | Given the arguments contained in `args` and `kwargs`, returns the best match
from the list of implementations registered on `dispatcher`. | [
"Given",
"the",
"arguments",
"contained",
"in",
"args",
"and",
"kwargs",
"returns",
"the",
"best",
"match",
"from",
"the",
"list",
"of",
"implementations",
"registered",
"on",
"dispatcher",
"."
] | d7b044d6f7e38043f0fc20f44f134baec84a5b32 | https://github.com/bintoro/overloading.py/blob/d7b044d6f7e38043f0fc20f44f134baec84a5b32/overloading.py#L257-L319 |
47,799 | bintoro/overloading.py | overloading.py | get_signature | def get_signature(func):
"""
Gathers information about the call signature of `func`.
"""
code = func.__code__
# Names of regular parameters
parameters = tuple(code.co_varnames[:code.co_argcount])
# Flags
has_varargs = bool(code.co_flags & inspect.CO_VARARGS)
has_varkw = bool(code.c... | python | def get_signature(func):
"""
Gathers information about the call signature of `func`.
"""
code = func.__code__
# Names of regular parameters
parameters = tuple(code.co_varnames[:code.co_argcount])
# Flags
has_varargs = bool(code.co_flags & inspect.CO_VARARGS)
has_varkw = bool(code.c... | [
"def",
"get_signature",
"(",
"func",
")",
":",
"code",
"=",
"func",
".",
"__code__",
"# Names of regular parameters",
"parameters",
"=",
"tuple",
"(",
"code",
".",
"co_varnames",
"[",
":",
"code",
".",
"co_argcount",
"]",
")",
"# Flags",
"has_varargs",
"=",
... | Gathers information about the call signature of `func`. | [
"Gathers",
"information",
"about",
"the",
"call",
"signature",
"of",
"func",
"."
] | d7b044d6f7e38043f0fc20f44f134baec84a5b32 | https://github.com/bintoro/overloading.py/blob/d7b044d6f7e38043f0fc20f44f134baec84a5b32/overloading.py#L421-L450 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.