repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 3
values | summary stringlengths 4 350 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
DsixTools/python-smeftrunner | smeftrunner/io.py | load | def load(stream, fmt='lha'):
"""Load a parameter file in DSixTools SLHA-like format or its JSON or
YAML representation."""
if fmt == 'lha':
return pylha.load(stream)
elif fmt == 'json':
if isinstance(stream, str):
return json.loads(stream)
else:
return jso... | python | def load(stream, fmt='lha'):
"""Load a parameter file in DSixTools SLHA-like format or its JSON or
YAML representation."""
if fmt == 'lha':
return pylha.load(stream)
elif fmt == 'json':
if isinstance(stream, str):
return json.loads(stream)
else:
return jso... | [
"def",
"load",
"(",
"stream",
",",
"fmt",
"=",
"'lha'",
")",
":",
"if",
"fmt",
"==",
"'lha'",
":",
"return",
"pylha",
".",
"load",
"(",
"stream",
")",
"elif",
"fmt",
"==",
"'json'",
":",
"if",
"isinstance",
"(",
"stream",
",",
"str",
")",
":",
"r... | Load a parameter file in DSixTools SLHA-like format or its JSON or
YAML representation. | [
"Load",
"a",
"parameter",
"file",
"in",
"DSixTools",
"SLHA",
"-",
"like",
"format",
"or",
"its",
"JSON",
"or",
"YAML",
"representation",
"."
] | 4c9130e53ad4f7bbb526657a82150ca9d57c4b37 | https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/io.py#L8-L19 | train | Load a parameter file in DSixTools SLHA - like format or its JSON or
YAML representation. |
DsixTools/python-smeftrunner | smeftrunner/io.py | lha2matrix | def lha2matrix(values, shape):
"""Return a matrix given a list of values of the form
[[1, 1, float], [1, 2, float], ...]
referring to the (1,1)-element etc.
`shape` is the shape of the final matrix. All elements not provided
will be assumed to be zero. Also works for higher-rank tensors."""
M = ... | python | def lha2matrix(values, shape):
"""Return a matrix given a list of values of the form
[[1, 1, float], [1, 2, float], ...]
referring to the (1,1)-element etc.
`shape` is the shape of the final matrix. All elements not provided
will be assumed to be zero. Also works for higher-rank tensors."""
M = ... | [
"def",
"lha2matrix",
"(",
"values",
",",
"shape",
")",
":",
"M",
"=",
"np",
".",
"zeros",
"(",
"shape",
")",
"for",
"v",
"in",
"values",
":",
"M",
"[",
"tuple",
"(",
"[",
"int",
"(",
"i",
"-",
"1",
")",
"for",
"i",
"in",
"v",
"[",
":",
"-",... | Return a matrix given a list of values of the form
[[1, 1, float], [1, 2, float], ...]
referring to the (1,1)-element etc.
`shape` is the shape of the final matrix. All elements not provided
will be assumed to be zero. Also works for higher-rank tensors. | [
"Return",
"a",
"matrix",
"given",
"a",
"list",
"of",
"values",
"of",
"the",
"form",
"[[",
"1",
"1",
"float",
"]",
"[",
"1",
"2",
"float",
"]",
"...",
"]",
"referring",
"to",
"the",
"(",
"1",
"1",
")",
"-",
"element",
"etc",
".",
"shape",
"is",
... | 4c9130e53ad4f7bbb526657a82150ca9d57c4b37 | https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/io.py#L21-L30 | train | Return a matrix given a list of values of the form
[[ 1 2 2... ]
referring to the 1 - element etc. |
DsixTools/python-smeftrunner | smeftrunner/io.py | matrix2lha | def matrix2lha(M):
"""Inverse function to lha2matrix: return a LHA-like list given a tensor."""
l = []
ind = np.indices(M.shape).reshape(M.ndim, M.size).T
for i in ind:
l.append([j+1 for j in i] + [M[tuple(i)]])
return l | python | def matrix2lha(M):
"""Inverse function to lha2matrix: return a LHA-like list given a tensor."""
l = []
ind = np.indices(M.shape).reshape(M.ndim, M.size).T
for i in ind:
l.append([j+1 for j in i] + [M[tuple(i)]])
return l | [
"def",
"matrix2lha",
"(",
"M",
")",
":",
"l",
"=",
"[",
"]",
"ind",
"=",
"np",
".",
"indices",
"(",
"M",
".",
"shape",
")",
".",
"reshape",
"(",
"M",
".",
"ndim",
",",
"M",
".",
"size",
")",
".",
"T",
"for",
"i",
"in",
"ind",
":",
"l",
".... | Inverse function to lha2matrix: return a LHA-like list given a tensor. | [
"Inverse",
"function",
"to",
"lha2matrix",
":",
"return",
"a",
"LHA",
"-",
"like",
"list",
"given",
"a",
"tensor",
"."
] | 4c9130e53ad4f7bbb526657a82150ca9d57c4b37 | https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/io.py#L32-L38 | train | Inverse function to lha2matrix : return a LHA - like list given a tensor. |
DsixTools/python-smeftrunner | smeftrunner/io.py | sm_lha2dict | def sm_lha2dict(lha):
"""Convert a dictionary returned by pylha from a DSixTools SM input file
into a dictionary of SM values."""
d = OrderedDict()
v = dict(lha['BLOCK']['GAUGE']['values'])
d['g'] = v[1]
d['gp'] = v[2]
d['gs'] = v[3]
v = dict(lha['BLOCK']['SCALAR']['values'])
d['Lamb... | python | def sm_lha2dict(lha):
"""Convert a dictionary returned by pylha from a DSixTools SM input file
into a dictionary of SM values."""
d = OrderedDict()
v = dict(lha['BLOCK']['GAUGE']['values'])
d['g'] = v[1]
d['gp'] = v[2]
d['gs'] = v[3]
v = dict(lha['BLOCK']['SCALAR']['values'])
d['Lamb... | [
"def",
"sm_lha2dict",
"(",
"lha",
")",
":",
"d",
"=",
"OrderedDict",
"(",
")",
"v",
"=",
"dict",
"(",
"lha",
"[",
"'BLOCK'",
"]",
"[",
"'GAUGE'",
"]",
"[",
"'values'",
"]",
")",
"d",
"[",
"'g'",
"]",
"=",
"v",
"[",
"1",
"]",
"d",
"[",
"'gp'",... | Convert a dictionary returned by pylha from a DSixTools SM input file
into a dictionary of SM values. | [
"Convert",
"a",
"dictionary",
"returned",
"by",
"pylha",
"from",
"a",
"DSixTools",
"SM",
"input",
"file",
"into",
"a",
"dictionary",
"of",
"SM",
"values",
"."
] | 4c9130e53ad4f7bbb526657a82150ca9d57c4b37 | https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/io.py#L40-L70 | train | Convert a dictionary returned by pylha from a DSixTools SM input file
into a dictionary of SM values. |
DsixTools/python-smeftrunner | smeftrunner/io.py | sm_dict2lha | def sm_dict2lha(d):
"""Convert a a dictionary of SM parameters into
a dictionary that pylha can convert into a DSixTools SM output file."""
blocks = OrderedDict([
('GAUGE', {'values': [[1, d['g'].real], [2, d['gp'].real], [3, d['gs'].real]]}),
('SCALAR', {'values': [[1, d['Lambda'].real], [2... | python | def sm_dict2lha(d):
"""Convert a a dictionary of SM parameters into
a dictionary that pylha can convert into a DSixTools SM output file."""
blocks = OrderedDict([
('GAUGE', {'values': [[1, d['g'].real], [2, d['gp'].real], [3, d['gs'].real]]}),
('SCALAR', {'values': [[1, d['Lambda'].real], [2... | [
"def",
"sm_dict2lha",
"(",
"d",
")",
":",
"blocks",
"=",
"OrderedDict",
"(",
"[",
"(",
"'GAUGE'",
",",
"{",
"'values'",
":",
"[",
"[",
"1",
",",
"d",
"[",
"'g'",
"]",
".",
"real",
"]",
",",
"[",
"2",
",",
"d",
"[",
"'gp'",
"]",
".",
"real",
... | Convert a a dictionary of SM parameters into
a dictionary that pylha can convert into a DSixTools SM output file. | [
"Convert",
"a",
"a",
"dictionary",
"of",
"SM",
"parameters",
"into",
"a",
"dictionary",
"that",
"pylha",
"can",
"convert",
"into",
"a",
"DSixTools",
"SM",
"output",
"file",
"."
] | 4c9130e53ad4f7bbb526657a82150ca9d57c4b37 | https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/io.py#L72-L86 | train | Convert a dictionary of SM parameters into
a dictionary that pylha can convert into a DSixTools SM output file. |
DsixTools/python-smeftrunner | smeftrunner/io.py | wc_lha2dict | def wc_lha2dict(lha):
"""Convert a dictionary returned by pylha from a DSixTools WC input file
into a dictionary of Wilson coefficients."""
C = OrderedDict()
# try to read all WCs with 0, 2, or 4 fermions; if not found, set to zero
for k, (block, i) in WC_dict_0f.items():
try:
C[... | python | def wc_lha2dict(lha):
"""Convert a dictionary returned by pylha from a DSixTools WC input file
into a dictionary of Wilson coefficients."""
C = OrderedDict()
# try to read all WCs with 0, 2, or 4 fermions; if not found, set to zero
for k, (block, i) in WC_dict_0f.items():
try:
C[... | [
"def",
"wc_lha2dict",
"(",
"lha",
")",
":",
"C",
"=",
"OrderedDict",
"(",
")",
"# try to read all WCs with 0, 2, or 4 fermions; if not found, set to zero",
"for",
"k",
",",
"(",
"block",
",",
"i",
")",
"in",
"WC_dict_0f",
".",
"items",
"(",
")",
":",
"try",
":... | Convert a dictionary returned by pylha from a DSixTools WC input file
into a dictionary of Wilson coefficients. | [
"Convert",
"a",
"dictionary",
"returned",
"by",
"pylha",
"from",
"a",
"DSixTools",
"WC",
"input",
"file",
"into",
"a",
"dictionary",
"of",
"Wilson",
"coefficients",
"."
] | 4c9130e53ad4f7bbb526657a82150ca9d57c4b37 | https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/io.py#L107-L135 | train | Convert a dictionary returned by pylha from a DSixTools WC input file
into a dictionary of Wilson coefficients. |
DsixTools/python-smeftrunner | smeftrunner/io.py | wc_dict2lha | def wc_dict2lha(wc, skip_redundant=True, skip_zero=True):
"""Convert a a dictionary of Wilson coefficients into
a dictionary that pylha can convert into a DSixTools WC output file."""
d = OrderedDict()
for name, (block, i) in WC_dict_0f.items():
if block not in d:
d[block] = defaultd... | python | def wc_dict2lha(wc, skip_redundant=True, skip_zero=True):
"""Convert a a dictionary of Wilson coefficients into
a dictionary that pylha can convert into a DSixTools WC output file."""
d = OrderedDict()
for name, (block, i) in WC_dict_0f.items():
if block not in d:
d[block] = defaultd... | [
"def",
"wc_dict2lha",
"(",
"wc",
",",
"skip_redundant",
"=",
"True",
",",
"skip_zero",
"=",
"True",
")",
":",
"d",
"=",
"OrderedDict",
"(",
")",
"for",
"name",
",",
"(",
"block",
",",
"i",
")",
"in",
"WC_dict_0f",
".",
"items",
"(",
")",
":",
"if",... | Convert a a dictionary of Wilson coefficients into
a dictionary that pylha can convert into a DSixTools WC output file. | [
"Convert",
"a",
"a",
"dictionary",
"of",
"Wilson",
"coefficients",
"into",
"a",
"dictionary",
"that",
"pylha",
"can",
"convert",
"into",
"a",
"DSixTools",
"WC",
"output",
"file",
"."
] | 4c9130e53ad4f7bbb526657a82150ca9d57c4b37 | https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/io.py#L137-L191 | train | Convert a dictionary of Wilson coefficients into a dictionary of DSixTools WC output file. |
Kortemme-Lab/klab | klab/pymath/cartesian/rmsd.py | compute_rmsd_by_matrix | def compute_rmsd_by_matrix(dataframe_1, dataframe_2, use_assertion = False):
'''Computes the RMSD of two pandas dataframes. The dataframes are expected to be of equal dimensions and use_assertion
can be set to assert that the row indices match. '''
if use_assertion: assert([i for i in dataframe_1.index] ... | python | def compute_rmsd_by_matrix(dataframe_1, dataframe_2, use_assertion = False):
'''Computes the RMSD of two pandas dataframes. The dataframes are expected to be of equal dimensions and use_assertion
can be set to assert that the row indices match. '''
if use_assertion: assert([i for i in dataframe_1.index] ... | [
"def",
"compute_rmsd_by_matrix",
"(",
"dataframe_1",
",",
"dataframe_2",
",",
"use_assertion",
"=",
"False",
")",
":",
"if",
"use_assertion",
":",
"assert",
"(",
"[",
"i",
"for",
"i",
"in",
"dataframe_1",
".",
"index",
"]",
"==",
"[",
"i",
"for",
"i",
"i... | Computes the RMSD of two pandas dataframes. The dataframes are expected to be of equal dimensions and use_assertion
can be set to assert that the row indices match. | [
"Computes",
"the",
"RMSD",
"of",
"two",
"pandas",
"dataframes",
".",
"The",
"dataframes",
"are",
"expected",
"to",
"be",
"of",
"equal",
"dimensions",
"and",
"use_assertion",
"can",
"be",
"set",
"to",
"assert",
"that",
"the",
"row",
"indices",
"match",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/pymath/cartesian/rmsd.py#L3-L8 | train | Computes the RMSD of two pandas dataframes. |
projectshift/shift-boiler | boiler/feature/jinja_extensions.py | jinja_extensions_feature | def jinja_extensions_feature(app):
""" Enables custom templating extensions """
# register jinja filters
app.jinja_env.globals['momentjs'] = MomentJsFilters
app.jinja_env.filters.update(MomentJsFilters().get_filters())
app.jinja_env.filters.update(DateFilters().get_filters())
app.jinja_env.filt... | python | def jinja_extensions_feature(app):
""" Enables custom templating extensions """
# register jinja filters
app.jinja_env.globals['momentjs'] = MomentJsFilters
app.jinja_env.filters.update(MomentJsFilters().get_filters())
app.jinja_env.filters.update(DateFilters().get_filters())
app.jinja_env.filt... | [
"def",
"jinja_extensions_feature",
"(",
"app",
")",
":",
"# register jinja filters",
"app",
".",
"jinja_env",
".",
"globals",
"[",
"'momentjs'",
"]",
"=",
"MomentJsFilters",
"app",
".",
"jinja_env",
".",
"filters",
".",
"update",
"(",
"MomentJsFilters",
"(",
")"... | Enables custom templating extensions | [
"Enables",
"custom",
"templating",
"extensions"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/feature/jinja_extensions.py#L7-L20 | train | Enables custom templating extensions |
uogbuji/versa | tools/py/__init__.py | init_localization | def init_localization():
'''prepare l10n'''
locale.setlocale(locale.LC_ALL, '') # User's preferred locale, according to environment
# Use first two characters of country code, defaulting to 'en' in the absence of a preference
loc = locale.getlocale()
lang = loc[0][0:2] if loc[0] else 'en'
filen... | python | def init_localization():
'''prepare l10n'''
locale.setlocale(locale.LC_ALL, '') # User's preferred locale, according to environment
# Use first two characters of country code, defaulting to 'en' in the absence of a preference
loc = locale.getlocale()
lang = loc[0][0:2] if loc[0] else 'en'
filen... | [
"def",
"init_localization",
"(",
")",
":",
"locale",
".",
"setlocale",
"(",
"locale",
".",
"LC_ALL",
",",
"''",
")",
"# User's preferred locale, according to environment",
"# Use first two characters of country code, defaulting to 'en' in the absence of a preference",
"loc",
"=",... | prepare l10n | [
"prepare",
"l10n"
] | f092ffc7ed363a5b170890955168500f32de0dd5 | https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/__init__.py#L26-L42 | train | Prepare l10n locale |
ethan92429/onshapepy | onshapepy/core/utils.py | log | def log(msg, level=0):
'''
Logs a message to the console, with optional level paramater
Args:
- msg (str): message to send to console
- level (int): log level; 0 for info, 1 for error (default = 0)
'''
red = '\033[91m'
endc = '\033[0m'
# configure the logging module
cf... | python | def log(msg, level=0):
'''
Logs a message to the console, with optional level paramater
Args:
- msg (str): message to send to console
- level (int): log level; 0 for info, 1 for error (default = 0)
'''
red = '\033[91m'
endc = '\033[0m'
# configure the logging module
cf... | [
"def",
"log",
"(",
"msg",
",",
"level",
"=",
"0",
")",
":",
"red",
"=",
"'\\033[91m'",
"endc",
"=",
"'\\033[0m'",
"# configure the logging module",
"cfg",
"=",
"{",
"'version'",
":",
"1",
",",
"'disable_existing_loggers'",
":",
"False",
",",
"'formatters'",
... | Logs a message to the console, with optional level paramater
Args:
- msg (str): message to send to console
- level (int): log level; 0 for info, 1 for error (default = 0) | [
"Logs",
"a",
"message",
"to",
"the",
"console",
"with",
"optional",
"level",
"paramater"
] | 61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df | https://github.com/ethan92429/onshapepy/blob/61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df/onshapepy/core/utils.py#L17-L75 | train | Logs a message to the console with optional level paramater
|
ethan92429/onshapepy | onshapepy/core/utils.py | parse_quantity | def parse_quantity(q):
"""
Parse an OnShape units definition
Args:
q:
Returns:
a string that can be converted to any other unit engine.
>>> from onshapepy.core.utils import parse_quantity
>>> d = {'value': 0.1414213562373095, 'unitToPower': [{'value': 1, 'key': 'METER'}], 'type... | python | def parse_quantity(q):
"""
Parse an OnShape units definition
Args:
q:
Returns:
a string that can be converted to any other unit engine.
>>> from onshapepy.core.utils import parse_quantity
>>> d = {'value': 0.1414213562373095, 'unitToPower': [{'value': 1, 'key': 'METER'}], 'type... | [
"def",
"parse_quantity",
"(",
"q",
")",
":",
"units_s",
"=",
"str",
"(",
"q",
"[",
"'value'",
"]",
")",
"for",
"u",
"in",
"q",
"[",
"'unitToPower'",
"]",
":",
"units_s",
"=",
"units_s",
"+",
"\"*\"",
"+",
"u",
"[",
"'key'",
"]",
".",
"lower",
"("... | Parse an OnShape units definition
Args:
q:
Returns:
a string that can be converted to any other unit engine.
>>> from onshapepy.core.utils import parse_quantity
>>> d = {'value': 0.1414213562373095, 'unitToPower': [{'value': 1, 'key': 'METER'}], 'typeTag': ''}
>>> parse_quantity(d)... | [
"Parse",
"an",
"OnShape",
"units",
"definition",
"Args",
":",
"q",
":"
] | 61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df | https://github.com/ethan92429/onshapepy/blob/61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df/onshapepy/core/utils.py#L77-L101 | train | Parse an OnShape units definition into a string that can be converted to any other unit engine. |
ethan92429/onshapepy | onshapepy/assembly.py | Assembly.insert | def insert(self, part):
""" Insert a part into this assembly.
Args:
- part (onshapepy.part.Part) A Part instance that will be inserted.
Returns:
- requests.Response: Onshape response data
"""
params = {k: str(v) for k,v in part.params.items()}
r... | python | def insert(self, part):
""" Insert a part into this assembly.
Args:
- part (onshapepy.part.Part) A Part instance that will be inserted.
Returns:
- requests.Response: Onshape response data
"""
params = {k: str(v) for k,v in part.params.items()}
r... | [
"def",
"insert",
"(",
"self",
",",
"part",
")",
":",
"params",
"=",
"{",
"k",
":",
"str",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"part",
".",
"params",
".",
"items",
"(",
")",
"}",
"res",
"=",
"c",
".",
"create_assembly_instance",
"(",
"sel... | Insert a part into this assembly.
Args:
- part (onshapepy.part.Part) A Part instance that will be inserted.
Returns:
- requests.Response: Onshape response data | [
"Insert",
"a",
"part",
"into",
"this",
"assembly",
"."
] | 61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df | https://github.com/ethan92429/onshapepy/blob/61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df/onshapepy/assembly.py#L26-L38 | train | Insert a part into this assembly. |
TUNE-Archive/freight_forwarder | freight_forwarder/utils/utils.py | parse_http_scheme | def parse_http_scheme(uri):
"""
match on http scheme if no match is found will assume http
"""
regex = re.compile(
r'^(?:http)s?://',
flags=re.IGNORECASE
)
match = regex.match(uri)
return match.group(0) if match else 'http://' | python | def parse_http_scheme(uri):
"""
match on http scheme if no match is found will assume http
"""
regex = re.compile(
r'^(?:http)s?://',
flags=re.IGNORECASE
)
match = regex.match(uri)
return match.group(0) if match else 'http://' | [
"def",
"parse_http_scheme",
"(",
"uri",
")",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"r'^(?:http)s?://'",
",",
"flags",
"=",
"re",
".",
"IGNORECASE",
")",
"match",
"=",
"regex",
".",
"match",
"(",
"uri",
")",
"return",
"match",
".",
"group",
"(",... | match on http scheme if no match is found will assume http | [
"match",
"on",
"http",
"scheme",
"if",
"no",
"match",
"is",
"found",
"will",
"assume",
"http"
] | 6ea4a49f474ec04abb8bb81b175c774a16b5312f | https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/utils/utils.py#L110-L120 | train | Parse the URI to get the HTTP scheme. |
TUNE-Archive/freight_forwarder | freight_forwarder/utils/utils.py | parse_stream | def parse_stream(response):
"""
take stream from docker-py lib and display it to the user.
this also builds a stream list and returns it.
"""
stream_data = []
stream = stdout
for data in response:
if data:
try:
data = data.decode('utf-8')
exc... | python | def parse_stream(response):
"""
take stream from docker-py lib and display it to the user.
this also builds a stream list and returns it.
"""
stream_data = []
stream = stdout
for data in response:
if data:
try:
data = data.decode('utf-8')
exc... | [
"def",
"parse_stream",
"(",
"response",
")",
":",
"stream_data",
"=",
"[",
"]",
"stream",
"=",
"stdout",
"for",
"data",
"in",
"response",
":",
"if",
"data",
":",
"try",
":",
"data",
"=",
"data",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"AttributeE... | take stream from docker-py lib and display it to the user.
this also builds a stream list and returns it. | [
"take",
"stream",
"from",
"docker",
"-",
"py",
"lib",
"and",
"display",
"it",
"to",
"the",
"user",
"."
] | 6ea4a49f474ec04abb8bb81b175c774a16b5312f | https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/utils/utils.py#L159-L204 | train | Parses the stream from the Docker - py lib and displays it to the user. |
TUNE-Archive/freight_forwarder | freight_forwarder/utils/utils.py | normalize_keys | def normalize_keys(suspect, snake_case=True):
"""
take a dict and turn all of its type string keys into snake_case
"""
if not isinstance(suspect, dict):
raise TypeError('you must pass a dict.')
for key in list(suspect):
if not isinstance(key, six.string_types):
continue
... | python | def normalize_keys(suspect, snake_case=True):
"""
take a dict and turn all of its type string keys into snake_case
"""
if not isinstance(suspect, dict):
raise TypeError('you must pass a dict.')
for key in list(suspect):
if not isinstance(key, six.string_types):
continue
... | [
"def",
"normalize_keys",
"(",
"suspect",
",",
"snake_case",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"suspect",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"'you must pass a dict.'",
")",
"for",
"key",
"in",
"list",
"(",
"suspect",
")",... | take a dict and turn all of its type string keys into snake_case | [
"take",
"a",
"dict",
"and",
"turn",
"all",
"of",
"its",
"type",
"string",
"keys",
"into",
"snake_case"
] | 6ea4a49f474ec04abb8bb81b175c774a16b5312f | https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/utils/utils.py#L227-L256 | train | take a dict and turn all of its type string keys into snake_case
|
TUNE-Archive/freight_forwarder | freight_forwarder/utils/utils.py | normalize_value | def normalize_value(value, snake_case=True):
"""
:param value:
:return value:
"""
if not isinstance(value, six.string_types):
raise TypeError("the value passed to value must be a string")
if snake_case:
s1 = first_cap_re.sub(r'\1_\2', value)
new_value = all_cap_re.sub(r'... | python | def normalize_value(value, snake_case=True):
"""
:param value:
:return value:
"""
if not isinstance(value, six.string_types):
raise TypeError("the value passed to value must be a string")
if snake_case:
s1 = first_cap_re.sub(r'\1_\2', value)
new_value = all_cap_re.sub(r'... | [
"def",
"normalize_value",
"(",
"value",
",",
"snake_case",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"\"the value passed to value must be a string\"",
")",
"if",
"snake_c... | :param value:
:return value: | [
":",
"param",
"value",
":",
":",
"return",
"value",
":"
] | 6ea4a49f474ec04abb8bb81b175c774a16b5312f | https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/utils/utils.py#L259-L273 | train | Normalizes the value of a node - level resource list entry. |
TUNE-Archive/freight_forwarder | freight_forwarder/utils/utils.py | capitalize_keys | def capitalize_keys(suspect):
"""
:param suspect:
:return new dict with capitalized keys:
"""
if not isinstance(suspect, dict):
raise TypeError('you must pass a dict.')
converted = {}
for key in list(suspect):
if not isinstance(key, six.string_types):
continue
... | python | def capitalize_keys(suspect):
"""
:param suspect:
:return new dict with capitalized keys:
"""
if not isinstance(suspect, dict):
raise TypeError('you must pass a dict.')
converted = {}
for key in list(suspect):
if not isinstance(key, six.string_types):
continue
... | [
"def",
"capitalize_keys",
"(",
"suspect",
")",
":",
"if",
"not",
"isinstance",
"(",
"suspect",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"'you must pass a dict.'",
")",
"converted",
"=",
"{",
"}",
"for",
"key",
"in",
"list",
"(",
"suspect",
")",
... | :param suspect:
:return new dict with capitalized keys: | [
":",
"param",
"suspect",
":",
":",
"return",
"new",
"dict",
"with",
"capitalized",
"keys",
":"
] | 6ea4a49f474ec04abb8bb81b175c774a16b5312f | https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/utils/utils.py#L276-L306 | train | Convert all keys in a dict to capitalized ones. |
TUNE-Archive/freight_forwarder | freight_forwarder/utils/utils.py | _display_progress | def _display_progress(data, stream):
"""
expecting the following data scheme:
{
u'status': u'Pushing',
u'progressDetail': {
u'current': 655337,
u'start': 1413994898,
u'tota... | python | def _display_progress(data, stream):
"""
expecting the following data scheme:
{
u'status': u'Pushing',
u'progressDetail': {
u'current': 655337,
u'start': 1413994898,
u'tota... | [
"def",
"_display_progress",
"(",
"data",
",",
"stream",
")",
":",
"if",
"type",
"(",
"data",
")",
"is",
"not",
"dict",
":",
"raise",
"TypeError",
"(",
"\"data should be of type dict. the following was passed: {0}\"",
".",
"format",
"(",
"data",
")",
")",
"stream... | expecting the following data scheme:
{
u'status': u'Pushing',
u'progressDetail': {
u'current': 655337,
u'start': 1413994898,
u'total': 20412416
},
... | [
"expecting",
"the",
"following",
"data",
"scheme",
":",
"{",
"u",
"status",
":",
"u",
"Pushing",
"u",
"progressDetail",
":",
"{",
"u",
"current",
":",
"655337",
"u",
"start",
":",
"1413994898",
"u",
"total",
":",
"20412416",
"}",
"u",
"id",
":",
"u",
... | 6ea4a49f474ec04abb8bb81b175c774a16b5312f | https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/utils/utils.py#L309-L342 | train | Display the current progress of the current object in a single line. |
TUNE-Archive/freight_forwarder | freight_forwarder/utils/utils.py | _display_error | def _display_error(normalized_data, stream):
"""
print error message from docker-py stream and raise Exception.
{
u'message': u"Error getting container 981c3e17bfc6138d1985c0c8f5616e9064e56559e817646ad38211a456d6bcf2 from driver
devicemapper: Error mounting '/dev/mapper/docker-8:3-34393696-9... | python | def _display_error(normalized_data, stream):
"""
print error message from docker-py stream and raise Exception.
{
u'message': u"Error getting container 981c3e17bfc6138d1985c0c8f5616e9064e56559e817646ad38211a456d6bcf2 from driver
devicemapper: Error mounting '/dev/mapper/docker-8:3-34393696-9... | [
"def",
"_display_error",
"(",
"normalized_data",
",",
"stream",
")",
":",
"# TODO: need to revisit this later.",
"error",
"=",
"normalized_data",
"[",
"'error'",
"]",
"if",
"'error_detail'",
"in",
"normalized_data",
":",
"stream",
".",
"write",
"(",
"\"exit code: {0}\... | print error message from docker-py stream and raise Exception.
{
u'message': u"Error getting container 981c3e17bfc6138d1985c0c8f5616e9064e56559e817646ad38211a456d6bcf2 from driver
devicemapper: Error mounting '/dev/mapper/docker-8:3-34393696-981c3e17bfc6138d1985c0c8f5616e9064e56559e817646ad38211a456... | [
"print",
"error",
"message",
"from",
"docker",
"-",
"py",
"stream",
"and",
"raise",
"Exception",
".",
"{",
"u",
"message",
":",
"u",
"Error",
"getting",
"container",
"981c3e17bfc6138d1985c0c8f5616e9064e56559e817646ad38211a456d6bcf2",
"from",
"driver",
"devicemapper",
... | 6ea4a49f474ec04abb8bb81b175c774a16b5312f | https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/utils/utils.py#L345-L364 | train | Display the error message from the Docker stream and raise an exception. |
TUNE-Archive/freight_forwarder | freight_forwarder/utils/utils.py | _display_status | def _display_status(normalized_data, stream):
"""
print status message from docker-py stream.
"""
if 'Pull complete' in normalized_data['status'] or 'Download complete' in normalized_data['status']:
stream.write("\n")
if 'id' in normalized_data:
stream.write("%s - " % normalized_dat... | python | def _display_status(normalized_data, stream):
"""
print status message from docker-py stream.
"""
if 'Pull complete' in normalized_data['status'] or 'Download complete' in normalized_data['status']:
stream.write("\n")
if 'id' in normalized_data:
stream.write("%s - " % normalized_dat... | [
"def",
"_display_status",
"(",
"normalized_data",
",",
"stream",
")",
":",
"if",
"'Pull complete'",
"in",
"normalized_data",
"[",
"'status'",
"]",
"or",
"'Download complete'",
"in",
"normalized_data",
"[",
"'status'",
"]",
":",
"stream",
".",
"write",
"(",
"\"\\... | print status message from docker-py stream. | [
"print",
"status",
"message",
"from",
"docker",
"-",
"py",
"stream",
"."
] | 6ea4a49f474ec04abb8bb81b175c774a16b5312f | https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/utils/utils.py#L367-L377 | train | Display the status of the current page. |
TUNE-Archive/freight_forwarder | freight_forwarder/utils/utils.py | _display_stream | def _display_stream(normalized_data, stream):
"""
print stream message from docker-py stream.
"""
try:
stream.write(normalized_data['stream'])
except UnicodeEncodeError:
stream.write(normalized_data['stream'].encode("utf-8")) | python | def _display_stream(normalized_data, stream):
"""
print stream message from docker-py stream.
"""
try:
stream.write(normalized_data['stream'])
except UnicodeEncodeError:
stream.write(normalized_data['stream'].encode("utf-8")) | [
"def",
"_display_stream",
"(",
"normalized_data",
",",
"stream",
")",
":",
"try",
":",
"stream",
".",
"write",
"(",
"normalized_data",
"[",
"'stream'",
"]",
")",
"except",
"UnicodeEncodeError",
":",
"stream",
".",
"write",
"(",
"normalized_data",
"[",
"'stream... | print stream message from docker-py stream. | [
"print",
"stream",
"message",
"from",
"docker",
"-",
"py",
"stream",
"."
] | 6ea4a49f474ec04abb8bb81b175c774a16b5312f | https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/utils/utils.py#L380-L387 | train | Display stream message from docker - py stream. |
fjwCode/cerium | cerium/service.py | BaseService._execute | def _execute(self, *args: str, **kwargs: Any) -> tuple:
'''Execute command.'''
return self.execute(args=args, options=merge_dict(self.options, kwargs)).communicate() | python | def _execute(self, *args: str, **kwargs: Any) -> tuple:
'''Execute command.'''
return self.execute(args=args, options=merge_dict(self.options, kwargs)).communicate() | [
"def",
"_execute",
"(",
"self",
",",
"*",
"args",
":",
"str",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"tuple",
":",
"return",
"self",
".",
"execute",
"(",
"args",
"=",
"args",
",",
"options",
"=",
"merge_dict",
"(",
"self",
".",
"options",
... | Execute command. | [
"Execute",
"command",
"."
] | f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/service.py#L51-L53 | train | Execute command. |
fjwCode/cerium | cerium/service.py | BaseService.version | def version(self) -> str:
'''Show the version number of Android Debug Bridge.'''
output, _ = self._execute('version')
return output.splitlines()[0].split()[-1] | python | def version(self) -> str:
'''Show the version number of Android Debug Bridge.'''
output, _ = self._execute('version')
return output.splitlines()[0].split()[-1] | [
"def",
"version",
"(",
"self",
")",
"->",
"str",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'version'",
")",
"return",
"output",
".",
"splitlines",
"(",
")",
"[",
"0",
"]",
".",
"split",
"(",
")",
"[",
"-",
"1",
"]"
] | Show the version number of Android Debug Bridge. | [
"Show",
"the",
"version",
"number",
"of",
"Android",
"Debug",
"Bridge",
"."
] | f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/service.py#L68-L71 | train | Show the version number of Android Debug Bridge. |
fjwCode/cerium | cerium/service.py | BaseService.devices_l | def devices_l(self) -> Dict:
'''List connected devices (-l for long output).'''
output, _ = self._execute('devices', '-l')
devices = output.split()[4::6]
models = output.split()[7::6]
return dict(zip(devices, models)) | python | def devices_l(self) -> Dict:
'''List connected devices (-l for long output).'''
output, _ = self._execute('devices', '-l')
devices = output.split()[4::6]
models = output.split()[7::6]
return dict(zip(devices, models)) | [
"def",
"devices_l",
"(",
"self",
")",
"->",
"Dict",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'devices'",
",",
"'-l'",
")",
"devices",
"=",
"output",
".",
"split",
"(",
")",
"[",
"4",
":",
":",
"6",
"]",
"models",
"=",
"output"... | List connected devices (-l for long output). | [
"List",
"connected",
"devices",
"(",
"-",
"l",
"for",
"long",
"output",
")",
"."
] | f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/service.py#L78-L83 | train | List connected devices. |
fjwCode/cerium | cerium/service.py | BaseService.connect | def connect(self, host: str = '192.168.0.3', port: Union[int, str] = 5555) -> None:
'''Connect to a device via TCP/IP directly.'''
self.device_sn = f'{host}:{port}'
if not is_connectable(host, port):
raise ConnectionError(f'Cannot connect to {self.device_sn}.')
self._execute(... | python | def connect(self, host: str = '192.168.0.3', port: Union[int, str] = 5555) -> None:
'''Connect to a device via TCP/IP directly.'''
self.device_sn = f'{host}:{port}'
if not is_connectable(host, port):
raise ConnectionError(f'Cannot connect to {self.device_sn}.')
self._execute(... | [
"def",
"connect",
"(",
"self",
",",
"host",
":",
"str",
"=",
"'192.168.0.3'",
",",
"port",
":",
"Union",
"[",
"int",
",",
"str",
"]",
"=",
"5555",
")",
"->",
"None",
":",
"self",
".",
"device_sn",
"=",
"f'{host}:{port}'",
"if",
"not",
"is_connectable",... | Connect to a device via TCP/IP directly. | [
"Connect",
"to",
"a",
"device",
"via",
"TCP",
"/",
"IP",
"directly",
"."
] | f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/service.py#L85-L90 | train | Connect to a device via TCP or IP directly. |
fjwCode/cerium | cerium/service.py | BaseService.disconnect | def disconnect(self, host: str = '192.168.0.3', port: Union[int, str] = 5555) -> None:
'''Disconnect from given TCP/IP device [default port=5555].'''
self.device_sn = None
self._execute('disconnect', f'{host}:{port}') | python | def disconnect(self, host: str = '192.168.0.3', port: Union[int, str] = 5555) -> None:
'''Disconnect from given TCP/IP device [default port=5555].'''
self.device_sn = None
self._execute('disconnect', f'{host}:{port}') | [
"def",
"disconnect",
"(",
"self",
",",
"host",
":",
"str",
"=",
"'192.168.0.3'",
",",
"port",
":",
"Union",
"[",
"int",
",",
"str",
"]",
"=",
"5555",
")",
"->",
"None",
":",
"self",
".",
"device_sn",
"=",
"None",
"self",
".",
"_execute",
"(",
"'dis... | Disconnect from given TCP/IP device [default port=5555]. | [
"Disconnect",
"from",
"given",
"TCP",
"/",
"IP",
"device",
"[",
"default",
"port",
"=",
"5555",
"]",
"."
] | f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/service.py#L92-L95 | train | Disconnect from given TCP / IP device [ default port = 5555. |
fjwCode/cerium | cerium/service.py | BaseService.get_state | def get_state(self) -> str:
'''offline | bootloader | device'''
output, error = self._execute('get-state')
if error:
raise DeviceConnectionException(error.split(':', 1)[-1].strip())
return output.strip() | python | def get_state(self) -> str:
'''offline | bootloader | device'''
output, error = self._execute('get-state')
if error:
raise DeviceConnectionException(error.split(':', 1)[-1].strip())
return output.strip() | [
"def",
"get_state",
"(",
"self",
")",
"->",
"str",
":",
"output",
",",
"error",
"=",
"self",
".",
"_execute",
"(",
"'get-state'",
")",
"if",
"error",
":",
"raise",
"DeviceConnectionException",
"(",
"error",
".",
"split",
"(",
"':'",
",",
"1",
")",
"[",... | offline | bootloader | device | [
"offline",
"|",
"bootloader",
"|",
"device"
] | f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/service.py#L102-L107 | train | Get the current state of the system. |
Kortemme-Lab/klab | klab/plot/graphs/error_by_error_scatterplot.py | error_by_error_scatterplot | def error_by_error_scatterplot(output_directory, file_prefix, df,
reference_series_index, x_series_index, y_series_index,
x_color, y_color,
x_series_name = None, y_series_name = None,
plot_title = '', x_a... | python | def error_by_error_scatterplot(output_directory, file_prefix, df,
reference_series_index, x_series_index, y_series_index,
x_color, y_color,
x_series_name = None, y_series_name = None,
plot_title = '', x_a... | [
"def",
"error_by_error_scatterplot",
"(",
"output_directory",
",",
"file_prefix",
",",
"df",
",",
"reference_series_index",
",",
"x_series_index",
",",
"y_series_index",
",",
"x_color",
",",
"y_color",
",",
"x_series_name",
"=",
"None",
",",
"y_series_name",
"=",
"N... | Creates a scatterplot of error versus error intended to show which computational method (X or Y) has the least amount of error relative to a reference series.
The difference vectors (reference_series - x_series, reference_series - y_series) are created and these differences (errors)
are plotted against... | [
"Creates",
"a",
"scatterplot",
"of",
"error",
"versus",
"error",
"intended",
"to",
"show",
"which",
"computational",
"method",
"(",
"X",
"or",
"Y",
")",
"has",
"the",
"least",
"amount",
"of",
"error",
"relative",
"to",
"a",
"reference",
"series",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/plot/graphs/error_by_error_scatterplot.py#L35-L309 | train | This function creates a scatterplot of error versus error. |
cozy/python_cozy_management | cozy_management/ssl.py | generate_certificate | def generate_certificate(common_name, size=DEFAULT_KEY_SIZE):
'''
Generate private key and certificate for https
'''
private_key_path = '{}/{}.key'.format(CERTIFICATES_PATH, common_name)
certificate_path = '{}/{}.crt'.format(CERTIFICATES_PATH, common_name)
if not os.path.isfile(certificate_... | python | def generate_certificate(common_name, size=DEFAULT_KEY_SIZE):
'''
Generate private key and certificate for https
'''
private_key_path = '{}/{}.key'.format(CERTIFICATES_PATH, common_name)
certificate_path = '{}/{}.crt'.format(CERTIFICATES_PATH, common_name)
if not os.path.isfile(certificate_... | [
"def",
"generate_certificate",
"(",
"common_name",
",",
"size",
"=",
"DEFAULT_KEY_SIZE",
")",
":",
"private_key_path",
"=",
"'{}/{}.key'",
".",
"format",
"(",
"CERTIFICATES_PATH",
",",
"common_name",
")",
"certificate_path",
"=",
"'{}/{}.crt'",
".",
"format",
"(",
... | Generate private key and certificate for https | [
"Generate",
"private",
"key",
"and",
"certificate",
"for",
"https"
] | 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/ssl.py#L31-L54 | train | Generate private key and certificate for the given common name. |
cozy/python_cozy_management | cozy_management/ssl.py | acme_init | def acme_init():
'''
Init acme key
'''
acme_private_key = ACME_PRIVATE_KEY
acme_intermediate_cert = ACME_INTERMEDIATE_CERT
acme_intermediate_cert_url = ACME_INTERMEDIATE_CERT_URL
if not os.path.isfile(acme_private_key):
print 'Create {}'.format(acme_private_key)
cmd = 'o... | python | def acme_init():
'''
Init acme key
'''
acme_private_key = ACME_PRIVATE_KEY
acme_intermediate_cert = ACME_INTERMEDIATE_CERT
acme_intermediate_cert_url = ACME_INTERMEDIATE_CERT_URL
if not os.path.isfile(acme_private_key):
print 'Create {}'.format(acme_private_key)
cmd = 'o... | [
"def",
"acme_init",
"(",
")",
":",
"acme_private_key",
"=",
"ACME_PRIVATE_KEY",
"acme_intermediate_cert",
"=",
"ACME_INTERMEDIATE_CERT",
"acme_intermediate_cert_url",
"=",
"ACME_INTERMEDIATE_CERT_URL",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"acme_private_key"... | Init acme key | [
"Init",
"acme",
"key"
] | 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/ssl.py#L57-L90 | train | Init acme key
|
cozy/python_cozy_management | cozy_management/ssl.py | acme_sign_certificate | def acme_sign_certificate(common_name, size=DEFAULT_KEY_SIZE):
'''
Sign certificate with acme_tiny for let's encrypt
'''
private_key_path = '{}/{}.key'.format(CERTIFICATES_PATH, common_name)
certificate_path = '{}/{}.crt'.format(CERTIFICATES_PATH, common_name)
certificate_request_path = '{}/... | python | def acme_sign_certificate(common_name, size=DEFAULT_KEY_SIZE):
'''
Sign certificate with acme_tiny for let's encrypt
'''
private_key_path = '{}/{}.key'.format(CERTIFICATES_PATH, common_name)
certificate_path = '{}/{}.crt'.format(CERTIFICATES_PATH, common_name)
certificate_request_path = '{}/... | [
"def",
"acme_sign_certificate",
"(",
"common_name",
",",
"size",
"=",
"DEFAULT_KEY_SIZE",
")",
":",
"private_key_path",
"=",
"'{}/{}.key'",
".",
"format",
"(",
"CERTIFICATES_PATH",
",",
"common_name",
")",
"certificate_path",
"=",
"'{}/{}.crt'",
".",
"format",
"(",
... | Sign certificate with acme_tiny for let's encrypt | [
"Sign",
"certificate",
"with",
"acme_tiny",
"for",
"let",
"s",
"encrypt"
] | 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/ssl.py#L120-L155 | train | Signs a new certificate with acme_tiny for let s encrypt it |
cozy/python_cozy_management | cozy_management/ssl.py | acme_renew_certificates | def acme_renew_certificates():
'''
Renew certificates with acme_tiny for let's encrypt
'''
for csr in glob(os.path.join(CERTIFICATES_PATH, '*.csr')):
common_name = os.path.basename(csr)
common_name = os.path.splitext(common_name)[0]
certificate_path = "{}.crt".format(common... | python | def acme_renew_certificates():
'''
Renew certificates with acme_tiny for let's encrypt
'''
for csr in glob(os.path.join(CERTIFICATES_PATH, '*.csr')):
common_name = os.path.basename(csr)
common_name = os.path.splitext(common_name)[0]
certificate_path = "{}.crt".format(common... | [
"def",
"acme_renew_certificates",
"(",
")",
":",
"for",
"csr",
"in",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"CERTIFICATES_PATH",
",",
"'*.csr'",
")",
")",
":",
"common_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"csr",
")",
"common_... | Renew certificates with acme_tiny for let's encrypt | [
"Renew",
"certificates",
"with",
"acme_tiny",
"for",
"let",
"s",
"encrypt"
] | 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/ssl.py#L160-L192 | train | Renew certificates with acme_tiny for let s encrypt
|
cozy/python_cozy_management | cozy_management/ssl.py | generate_certificate_pure_python | def generate_certificate_pure_python(common_name, size=DEFAULT_KEY_SIZE,
digest=DEFAULT_DIGEST):
'''
Generate private key and certificate for https
'''
private_key = OpenSSL.crypto.PKey()
private_key.generate_key(TYPE_RSA, size)
request = OpenSSL.cryp... | python | def generate_certificate_pure_python(common_name, size=DEFAULT_KEY_SIZE,
digest=DEFAULT_DIGEST):
'''
Generate private key and certificate for https
'''
private_key = OpenSSL.crypto.PKey()
private_key.generate_key(TYPE_RSA, size)
request = OpenSSL.cryp... | [
"def",
"generate_certificate_pure_python",
"(",
"common_name",
",",
"size",
"=",
"DEFAULT_KEY_SIZE",
",",
"digest",
"=",
"DEFAULT_DIGEST",
")",
":",
"private_key",
"=",
"OpenSSL",
".",
"crypto",
".",
"PKey",
"(",
")",
"private_key",
".",
"generate_key",
"(",
"TY... | Generate private key and certificate for https | [
"Generate",
"private",
"key",
"and",
"certificate",
"for",
"https"
] | 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/ssl.py#L195-L243 | train | Generate private key and certificate for the current page of the page. |
cozy/python_cozy_management | cozy_management/ssl.py | get_crt_common_name | def get_crt_common_name(certificate_path=OLD_CERTIFICATE_PATH):
'''
Get CN from certificate
'''
try:
certificate_file = open(certificate_path)
crt = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
certificate_file.read())
... | python | def get_crt_common_name(certificate_path=OLD_CERTIFICATE_PATH):
'''
Get CN from certificate
'''
try:
certificate_file = open(certificate_path)
crt = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
certificate_file.read())
... | [
"def",
"get_crt_common_name",
"(",
"certificate_path",
"=",
"OLD_CERTIFICATE_PATH",
")",
":",
"try",
":",
"certificate_file",
"=",
"open",
"(",
"certificate_path",
")",
"crt",
"=",
"OpenSSL",
".",
"crypto",
".",
"load_certificate",
"(",
"OpenSSL",
".",
"crypto",
... | Get CN from certificate | [
"Get",
"CN",
"from",
"certificate"
] | 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/ssl.py#L246-L256 | train | Get CN from certificate
|
cozy/python_cozy_management | cozy_management/ssl.py | normalize_cert_dir | def normalize_cert_dir():
'''
Put old cerfificate form to new one
'''
current_cn = get_crt_common_name()
if not os.path.isdir(COZY_CONFIG_PATH):
print 'Need to create {}'.format(COZY_CONFIG_PATH)
os.mkdir(COZY_CONFIG_PATH, 0755)
if not os.path.isdir(CERTIFICATES_PATH):
... | python | def normalize_cert_dir():
'''
Put old cerfificate form to new one
'''
current_cn = get_crt_common_name()
if not os.path.isdir(COZY_CONFIG_PATH):
print 'Need to create {}'.format(COZY_CONFIG_PATH)
os.mkdir(COZY_CONFIG_PATH, 0755)
if not os.path.isdir(CERTIFICATES_PATH):
... | [
"def",
"normalize_cert_dir",
"(",
")",
":",
"current_cn",
"=",
"get_crt_common_name",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"COZY_CONFIG_PATH",
")",
":",
"print",
"'Need to create {}'",
".",
"format",
"(",
"COZY_CONFIG_PATH",
")",
"os",
... | Put old cerfificate form to new one | [
"Put",
"old",
"cerfificate",
"form",
"to",
"new",
"one"
] | 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/ssl.py#L259-L294 | train | This function takes care of creating the necessary directories and rename the old one to the new one. |
cozy/python_cozy_management | cozy_management/ssl.py | clean_links | def clean_links():
'''
Clean symlink for nginx
'''
if os.path.isfile(CURRENT_CERTIFICATE_PATH):
print 'Delete symlink {}'.format(CURRENT_CERTIFICATE_PATH)
os.remove(CURRENT_CERTIFICATE_PATH)
if os.path.isfile(CURRENT_PRIVATE_KEY_PATH):
print 'Delete symlink {}'.format(CU... | python | def clean_links():
'''
Clean symlink for nginx
'''
if os.path.isfile(CURRENT_CERTIFICATE_PATH):
print 'Delete symlink {}'.format(CURRENT_CERTIFICATE_PATH)
os.remove(CURRENT_CERTIFICATE_PATH)
if os.path.isfile(CURRENT_PRIVATE_KEY_PATH):
print 'Delete symlink {}'.format(CU... | [
"def",
"clean_links",
"(",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"CURRENT_CERTIFICATE_PATH",
")",
":",
"print",
"'Delete symlink {}'",
".",
"format",
"(",
"CURRENT_CERTIFICATE_PATH",
")",
"os",
".",
"remove",
"(",
"CURRENT_CERTIFICATE_PATH",
")"... | Clean symlink for nginx | [
"Clean",
"symlink",
"for",
"nginx"
] | 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/ssl.py#L297-L307 | train | Clean symlink for nginx
|
assamite/creamas | creamas/core/simulation.py | Simulation.create | def create(self, agent_cls=None, n_agents=10, agent_kwargs={},
env_cls=Environment, env_kwargs={}, callback=None, conns=0,
log_folder=None):
"""A convenience function to create simple simulations.
Method first creates environment, then instantiates agents into it
w... | python | def create(self, agent_cls=None, n_agents=10, agent_kwargs={},
env_cls=Environment, env_kwargs={}, callback=None, conns=0,
log_folder=None):
"""A convenience function to create simple simulations.
Method first creates environment, then instantiates agents into it
w... | [
"def",
"create",
"(",
"self",
",",
"agent_cls",
"=",
"None",
",",
"n_agents",
"=",
"10",
",",
"agent_kwargs",
"=",
"{",
"}",
",",
"env_cls",
"=",
"Environment",
",",
"env_kwargs",
"=",
"{",
"}",
",",
"callback",
"=",
"None",
",",
"conns",
"=",
"0",
... | A convenience function to create simple simulations.
Method first creates environment, then instantiates agents into it
with give arguments, and finally creates simulation for the
environment.
:param agent_cls:
class for agents, or list of classes. If list, then **n_agents*... | [
"A",
"convenience",
"function",
"to",
"create",
"simple",
"simulations",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/simulation.py#L28-L101 | train | A convenience method to create a simple simulation for the environment. |
assamite/creamas | creamas/core/simulation.py | Simulation._init_step | def _init_step(self):
"""Initialize next step of simulation to be run.
"""
self._age += 1
self.env.age = self._age
self._log(logging.INFO, "")
self._log(logging.INFO, "\t***** Step {:0>4} *****". format(self.age))
self._log(logging.INFO, "")
self._agents_t... | python | def _init_step(self):
"""Initialize next step of simulation to be run.
"""
self._age += 1
self.env.age = self._age
self._log(logging.INFO, "")
self._log(logging.INFO, "\t***** Step {:0>4} *****". format(self.age))
self._log(logging.INFO, "")
self._agents_t... | [
"def",
"_init_step",
"(",
"self",
")",
":",
"self",
".",
"_age",
"+=",
"1",
"self",
".",
"env",
".",
"age",
"=",
"self",
".",
"_age",
"self",
".",
"_log",
"(",
"logging",
".",
"INFO",
",",
"\"\"",
")",
"self",
".",
"_log",
"(",
"logging",
".",
... | Initialize next step of simulation to be run. | [
"Initialize",
"next",
"step",
"of",
"simulation",
"to",
"be",
"run",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/simulation.py#L186-L196 | train | Initialize next simulation step. |
assamite/creamas | creamas/core/simulation.py | Simulation._finalize_step | def _finalize_step(self):
"""Finalize simulation step after all agents have acted for the current
step.
"""
t = time.time()
if self._callback is not None:
self._callback(self.age)
t2 = time.time()
self._step_processing_time += t2 - t
self._log(... | python | def _finalize_step(self):
"""Finalize simulation step after all agents have acted for the current
step.
"""
t = time.time()
if self._callback is not None:
self._callback(self.age)
t2 = time.time()
self._step_processing_time += t2 - t
self._log(... | [
"def",
"_finalize_step",
"(",
"self",
")",
":",
"t",
"=",
"time",
".",
"time",
"(",
")",
"if",
"self",
".",
"_callback",
"is",
"not",
"None",
":",
"self",
".",
"_callback",
"(",
"self",
".",
"age",
")",
"t2",
"=",
"time",
".",
"time",
"(",
")",
... | Finalize simulation step after all agents have acted for the current
step. | [
"Finalize",
"simulation",
"step",
"after",
"all",
"agents",
"have",
"acted",
"for",
"the",
"current",
"step",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/simulation.py#L198-L211 | train | Finalize simulation step after all agents have acted for the current iteration. |
assamite/creamas | creamas/core/simulation.py | Simulation.async_steps | def async_steps(self, n):
"""Progress simulation by running all agents *n* times asynchronously.
"""
assert len(self._agents_to_act) == 0
for _ in range(n):
self.async_step() | python | def async_steps(self, n):
"""Progress simulation by running all agents *n* times asynchronously.
"""
assert len(self._agents_to_act) == 0
for _ in range(n):
self.async_step() | [
"def",
"async_steps",
"(",
"self",
",",
"n",
")",
":",
"assert",
"len",
"(",
"self",
".",
"_agents_to_act",
")",
"==",
"0",
"for",
"_",
"in",
"range",
"(",
"n",
")",
":",
"self",
".",
"async_step",
"(",
")"
] | Progress simulation by running all agents *n* times asynchronously. | [
"Progress",
"simulation",
"by",
"running",
"all",
"agents",
"*",
"n",
"*",
"times",
"asynchronously",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/simulation.py#L213-L218 | train | Progress simulation by running all agents * n * times asynchronously. |
assamite/creamas | creamas/core/simulation.py | Simulation.async_step | def async_step(self):
"""Progress simulation by running all agents once asynchronously.
"""
assert len(self._agents_to_act) == 0
self._init_step()
t = time.time()
aiomas.run(until=self.env.trigger_all())
self._agents_to_act = []
self._step_processing_time ... | python | def async_step(self):
"""Progress simulation by running all agents once asynchronously.
"""
assert len(self._agents_to_act) == 0
self._init_step()
t = time.time()
aiomas.run(until=self.env.trigger_all())
self._agents_to_act = []
self._step_processing_time ... | [
"def",
"async_step",
"(",
"self",
")",
":",
"assert",
"len",
"(",
"self",
".",
"_agents_to_act",
")",
"==",
"0",
"self",
".",
"_init_step",
"(",
")",
"t",
"=",
"time",
".",
"time",
"(",
")",
"aiomas",
".",
"run",
"(",
"until",
"=",
"self",
".",
"... | Progress simulation by running all agents once asynchronously. | [
"Progress",
"simulation",
"by",
"running",
"all",
"agents",
"once",
"asynchronously",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/simulation.py#L220-L229 | train | Progress simulation by running all agents once asynchronously. |
assamite/creamas | creamas/core/simulation.py | Simulation.steps | def steps(self, n):
"""Progress simulation with given amount of steps.
Can not be called when some of the agents have not acted for the
current step.
:param int n: amount of steps to run
"""
assert len(self._agents_to_act) == 0
for _ in range(n):
sel... | python | def steps(self, n):
"""Progress simulation with given amount of steps.
Can not be called when some of the agents have not acted for the
current step.
:param int n: amount of steps to run
"""
assert len(self._agents_to_act) == 0
for _ in range(n):
sel... | [
"def",
"steps",
"(",
"self",
",",
"n",
")",
":",
"assert",
"len",
"(",
"self",
".",
"_agents_to_act",
")",
"==",
"0",
"for",
"_",
"in",
"range",
"(",
"n",
")",
":",
"self",
".",
"step",
"(",
")"
] | Progress simulation with given amount of steps.
Can not be called when some of the agents have not acted for the
current step.
:param int n: amount of steps to run | [
"Progress",
"simulation",
"with",
"given",
"amount",
"of",
"steps",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/simulation.py#L231-L241 | train | Progress simulation with given amount of steps. |
assamite/creamas | creamas/core/simulation.py | Simulation.step | def step(self):
"""Progress simulation with a single step.
Can not be called when some of the agents have not acted for the
current step.
"""
assert len(self._agents_to_act) == 0
self.next()
while len(self._agents_to_act) > 0:
self.next() | python | def step(self):
"""Progress simulation with a single step.
Can not be called when some of the agents have not acted for the
current step.
"""
assert len(self._agents_to_act) == 0
self.next()
while len(self._agents_to_act) > 0:
self.next() | [
"def",
"step",
"(",
"self",
")",
":",
"assert",
"len",
"(",
"self",
".",
"_agents_to_act",
")",
"==",
"0",
"self",
".",
"next",
"(",
")",
"while",
"len",
"(",
"self",
".",
"_agents_to_act",
")",
">",
"0",
":",
"self",
".",
"next",
"(",
")"
] | Progress simulation with a single step.
Can not be called when some of the agents have not acted for the
current step. | [
"Progress",
"simulation",
"with",
"a",
"single",
"step",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/simulation.py#L243-L252 | train | This method is called by the simulation with a single step. |
assamite/creamas | creamas/core/simulation.py | Simulation.next | def next(self):
"""Trigger next agent to :py:meth:`~creamas.core.CreativeAgent.act` in
the current step.
"""
# all agents acted, init next step
t = time.time()
if len(self._agents_to_act) == 0:
self._init_step()
addr = self._agents_to_act.pop(0)
... | python | def next(self):
"""Trigger next agent to :py:meth:`~creamas.core.CreativeAgent.act` in
the current step.
"""
# all agents acted, init next step
t = time.time()
if len(self._agents_to_act) == 0:
self._init_step()
addr = self._agents_to_act.pop(0)
... | [
"def",
"next",
"(",
"self",
")",
":",
"# all agents acted, init next step",
"t",
"=",
"time",
".",
"time",
"(",
")",
"if",
"len",
"(",
"self",
".",
"_agents_to_act",
")",
"==",
"0",
":",
"self",
".",
"_init_step",
"(",
")",
"addr",
"=",
"self",
".",
... | Trigger next agent to :py:meth:`~creamas.core.CreativeAgent.act` in
the current step. | [
"Trigger",
"next",
"agent",
"to",
":",
"py",
":",
"meth",
":",
"~creamas",
".",
"core",
".",
"CreativeAgent",
".",
"act",
"in",
"the",
"current",
"step",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/simulation.py#L254-L270 | train | Trigger next agent to : py : meth : ~creamas. core. CreativeAgent. act in
the current step. |
assamite/creamas | creamas/core/simulation.py | Simulation.end | def end(self, folder=None):
"""End the simulation and destroy the current simulation environment.
"""
ret = self.env.destroy(folder=folder)
self._end_time = time.time()
self._log(logging.DEBUG, "Simulation run with {} steps took {:.3f}s to"
" complete, while act... | python | def end(self, folder=None):
"""End the simulation and destroy the current simulation environment.
"""
ret = self.env.destroy(folder=folder)
self._end_time = time.time()
self._log(logging.DEBUG, "Simulation run with {} steps took {:.3f}s to"
" complete, while act... | [
"def",
"end",
"(",
"self",
",",
"folder",
"=",
"None",
")",
":",
"ret",
"=",
"self",
".",
"env",
".",
"destroy",
"(",
"folder",
"=",
"folder",
")",
"self",
".",
"_end_time",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"_log",
"(",
"logging",... | End the simulation and destroy the current simulation environment. | [
"End",
"the",
"simulation",
"and",
"destroy",
"the",
"current",
"simulation",
"environment",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/simulation.py#L282-L291 | train | End the simulation and destroy the current simulation environment. |
Kortemme-Lab/klab | klab/db/mysql.py | DatabaseInterface.transaction_insert_dict_auto_inc | def transaction_insert_dict_auto_inc(self, transaction_cursor, tblname, d, unique_id_fields = [], fields = None, check_existing = False, id_field = 'ID'):
'''A transaction wrapper for inserting dicts into fields with an autoincrementing ID. Insert the record and return the associated ID (long).'''
sql, ... | python | def transaction_insert_dict_auto_inc(self, transaction_cursor, tblname, d, unique_id_fields = [], fields = None, check_existing = False, id_field = 'ID'):
'''A transaction wrapper for inserting dicts into fields with an autoincrementing ID. Insert the record and return the associated ID (long).'''
sql, ... | [
"def",
"transaction_insert_dict_auto_inc",
"(",
"self",
",",
"transaction_cursor",
",",
"tblname",
",",
"d",
",",
"unique_id_fields",
"=",
"[",
"]",
",",
"fields",
"=",
"None",
",",
"check_existing",
"=",
"False",
",",
"id_field",
"=",
"'ID'",
")",
":",
"sql... | A transaction wrapper for inserting dicts into fields with an autoincrementing ID. Insert the record and return the associated ID (long). | [
"A",
"transaction",
"wrapper",
"for",
"inserting",
"dicts",
"into",
"fields",
"with",
"an",
"autoincrementing",
"ID",
".",
"Insert",
"the",
"record",
"and",
"return",
"the",
"associated",
"ID",
"(",
"long",
")",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/db/mysql.py#L155-L164 | train | A transaction wrapper for inserting dicts into fields with an autoincrementing ID. Insert the record and return the associated ID. |
Kortemme-Lab/klab | klab/db/mysql.py | DatabaseInterface.get_unique_record | def get_unique_record(self, sql, parameters = None, quiet = False, locked = False):
'''I use this pattern a lot. Return the single record corresponding to the query.'''
results = self.execute_select(sql, parameters = parameters, quiet = quiet, locked = locked)
assert(len(results) == 1)
r... | python | def get_unique_record(self, sql, parameters = None, quiet = False, locked = False):
'''I use this pattern a lot. Return the single record corresponding to the query.'''
results = self.execute_select(sql, parameters = parameters, quiet = quiet, locked = locked)
assert(len(results) == 1)
r... | [
"def",
"get_unique_record",
"(",
"self",
",",
"sql",
",",
"parameters",
"=",
"None",
",",
"quiet",
"=",
"False",
",",
"locked",
"=",
"False",
")",
":",
"results",
"=",
"self",
".",
"execute_select",
"(",
"sql",
",",
"parameters",
"=",
"parameters",
",",
... | I use this pattern a lot. Return the single record corresponding to the query. | [
"I",
"use",
"this",
"pattern",
"a",
"lot",
".",
"Return",
"the",
"single",
"record",
"corresponding",
"to",
"the",
"query",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/db/mysql.py#L167-L171 | train | I use this pattern a lot. Return the single record corresponding to the query. |
Kortemme-Lab/klab | klab/db/mysql.py | DatabaseInterface.run_transaction | def run_transaction(self, command_list, do_commit=True):
'''This can be used to stage multiple commands and roll back the transaction if an error occurs. This is useful
if you want to remove multiple records in multiple tables for one entity but do not want the deletion to occur
if the e... | python | def run_transaction(self, command_list, do_commit=True):
'''This can be used to stage multiple commands and roll back the transaction if an error occurs. This is useful
if you want to remove multiple records in multiple tables for one entity but do not want the deletion to occur
if the e... | [
"def",
"run_transaction",
"(",
"self",
",",
"command_list",
",",
"do_commit",
"=",
"True",
")",
":",
"pass",
"# I decided against creating this for now.",
"# It may be more useful to create a stored procedure like in e.g. _create_protein_deletion_stored_procedure",
"# in the DDGadmin p... | This can be used to stage multiple commands and roll back the transaction if an error occurs. This is useful
if you want to remove multiple records in multiple tables for one entity but do not want the deletion to occur
if the entity is tied to table not specified in the list of commands. Perfor... | [
"This",
"can",
"be",
"used",
"to",
"stage",
"multiple",
"commands",
"and",
"roll",
"back",
"the",
"transaction",
"if",
"an",
"error",
"occurs",
".",
"This",
"is",
"useful",
"if",
"you",
"want",
"to",
"remove",
"multiple",
"records",
"in",
"multiple",
"tabl... | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/db/mysql.py#L327-L347 | train | This method runs the specified list of commands and returns the ID of the last command executed. |
Kortemme-Lab/klab | klab/db/mysql.py | DatabaseInterface.callproc | def callproc(self, procname, parameters=(), quiet=False, expect_return_value=False):
"""Calls a MySQL stored procedure procname and returns the return values. This uses DictCursor.
To get return values back out of a stored procedure, prefix the parameter with a @ character.
"""
self.... | python | def callproc(self, procname, parameters=(), quiet=False, expect_return_value=False):
"""Calls a MySQL stored procedure procname and returns the return values. This uses DictCursor.
To get return values back out of a stored procedure, prefix the parameter with a @ character.
"""
self.... | [
"def",
"callproc",
"(",
"self",
",",
"procname",
",",
"parameters",
"=",
"(",
")",
",",
"quiet",
"=",
"False",
",",
"expect_return_value",
"=",
"False",
")",
":",
"self",
".",
"procedures_run",
"+=",
"1",
"i",
"=",
"0",
"errcode",
"=",
"0",
"caughte",
... | Calls a MySQL stored procedure procname and returns the return values. This uses DictCursor.
To get return values back out of a stored procedure, prefix the parameter with a @ character. | [
"Calls",
"a",
"MySQL",
"stored",
"procedure",
"procname",
"and",
"returns",
"the",
"return",
"values",
".",
"This",
"uses",
"DictCursor",
".",
"To",
"get",
"return",
"values",
"back",
"out",
"of",
"a",
"stored",
"procedure",
"prefix",
"the",
"parameter",
"wi... | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/db/mysql.py#L462-L514 | train | Calls a MySQL stored procedure procname and returns the return values. This uses DictCursor.
to get the return values back out of a stored procedure. |
Kortemme-Lab/klab | klab/db/mysql.py | DatabaseInterface.t_insert_dict_if_new | def t_insert_dict_if_new(self, tblname, d, PKfields, fields=None):
'''A version of insertDictIfNew for transactions. This does not call commit.'''
SQL, values = self._insert_dict_if_new_inner(tblname, d, PKfields, fields=fields)
if SQL != False:
self.execute_select(SQL, parameters=va... | python | def t_insert_dict_if_new(self, tblname, d, PKfields, fields=None):
'''A version of insertDictIfNew for transactions. This does not call commit.'''
SQL, values = self._insert_dict_if_new_inner(tblname, d, PKfields, fields=fields)
if SQL != False:
self.execute_select(SQL, parameters=va... | [
"def",
"t_insert_dict_if_new",
"(",
"self",
",",
"tblname",
",",
"d",
",",
"PKfields",
",",
"fields",
"=",
"None",
")",
":",
"SQL",
",",
"values",
"=",
"self",
".",
"_insert_dict_if_new_inner",
"(",
"tblname",
",",
"d",
",",
"PKfields",
",",
"fields",
"=... | A version of insertDictIfNew for transactions. This does not call commit. | [
"A",
"version",
"of",
"insertDictIfNew",
"for",
"transactions",
".",
"This",
"does",
"not",
"call",
"commit",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/db/mysql.py#L538-L544 | train | A version of insertDictIfNew for transactions. This does not call commit. |
Kortemme-Lab/klab | klab/db/mysql.py | DatabaseInterface.insertDictIfNew | def insertDictIfNew(self, tblname, d, PKfields, fields=None, locked = True):
'''Simple function for inserting a dictionary whose keys match the fieldnames of tblname. The function returns two values, the
second of which is a dict containing the primary keys of the record. If a record already exists ... | python | def insertDictIfNew(self, tblname, d, PKfields, fields=None, locked = True):
'''Simple function for inserting a dictionary whose keys match the fieldnames of tblname. The function returns two values, the
second of which is a dict containing the primary keys of the record. If a record already exists ... | [
"def",
"insertDictIfNew",
"(",
"self",
",",
"tblname",
",",
"d",
",",
"PKfields",
",",
"fields",
"=",
"None",
",",
"locked",
"=",
"True",
")",
":",
"SQL",
",",
"values",
"=",
"self",
".",
"_insert_dict_if_new_inner",
"(",
"tblname",
",",
"d",
",",
"PKf... | Simple function for inserting a dictionary whose keys match the fieldnames of tblname. The function returns two values, the
second of which is a dict containing the primary keys of the record. If a record already exists then no insertion is performed and
(False, the dictionary of existing primar... | [
"Simple",
"function",
"for",
"inserting",
"a",
"dictionary",
"whose",
"keys",
"match",
"the",
"fieldnames",
"of",
"tblname",
".",
"The",
"function",
"returns",
"two",
"values",
"the",
"second",
"of",
"which",
"is",
"a",
"dict",
"containing",
"the",
"primary",
... | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/db/mysql.py#L547-L598 | train | Simple function for inserting a dictionary whose keys match the fieldnames of tblname. The function returns two values the
first of which is a dict containing the primary keys of the record. The function returns two values the
second of which is a dict containing the primary keys of the record. |
Kortemme-Lab/klab | klab/db/mysql.py | DatabaseInterface.create_insert_dict_string | def create_insert_dict_string(self, tblname, d, PKfields=[], fields=None, check_existing = False):
'''The main function of the insert_dict functions.
This creates and returns the SQL query and parameters used by the other functions but does not insert any data into the database.
Simple fu... | python | def create_insert_dict_string(self, tblname, d, PKfields=[], fields=None, check_existing = False):
'''The main function of the insert_dict functions.
This creates and returns the SQL query and parameters used by the other functions but does not insert any data into the database.
Simple fu... | [
"def",
"create_insert_dict_string",
"(",
"self",
",",
"tblname",
",",
"d",
",",
"PKfields",
"=",
"[",
"]",
",",
"fields",
"=",
"None",
",",
"check_existing",
"=",
"False",
")",
":",
"if",
"type",
"(",
"PKfields",
")",
"==",
"type",
"(",
"\"\"",
")",
... | The main function of the insert_dict functions.
This creates and returns the SQL query and parameters used by the other functions but does not insert any data into the database.
Simple function for inserting a dictionary whose keys match the fieldnames of tblname. The function returns two values,... | [
"The",
"main",
"function",
"of",
"the",
"insert_dict",
"functions",
".",
"This",
"creates",
"and",
"returns",
"the",
"SQL",
"query",
"and",
"parameters",
"used",
"by",
"the",
"other",
"functions",
"but",
"does",
"not",
"insert",
"any",
"data",
"into",
"the",... | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/db/mysql.py#L649-L687 | train | Create a SQL query and parameters used by the insert_dict functions. |
projectshift/shift-boiler | boiler/collections/pagination.py | paginate | def paginate(page, total_items, total_pages, slice_size=5):
"""
Paginate
Does some maths to generate ranged pagination. Returns a dictionary
of page numbers to be used in url builders that allows to go to first
page, previous page, next page, last page and one of the pages in
range around curren... | python | def paginate(page, total_items, total_pages, slice_size=5):
"""
Paginate
Does some maths to generate ranged pagination. Returns a dictionary
of page numbers to be used in url builders that allows to go to first
page, previous page, next page, last page and one of the pages in
range around curren... | [
"def",
"paginate",
"(",
"page",
",",
"total_items",
",",
"total_pages",
",",
"slice_size",
"=",
"5",
")",
":",
"if",
"slice_size",
">",
"total_pages",
":",
"slice_size",
"=",
"total_pages",
"# paginate (can be out of bounds for now)",
"first",
"=",
"1",
"previous"... | Paginate
Does some maths to generate ranged pagination. Returns a dictionary
of page numbers to be used in url builders that allows to go to first
page, previous page, next page, last page and one of the pages in
range around current page with possibility to jump in slices. The
result will look like... | [
"Paginate",
"Does",
"some",
"maths",
"to",
"generate",
"ranged",
"pagination",
".",
"Returns",
"a",
"dictionary",
"of",
"page",
"numbers",
"to",
"be",
"used",
"in",
"url",
"builders",
"that",
"allows",
"to",
"go",
"to",
"first",
"page",
"previous",
"page",
... | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/collections/pagination.py#L4-L108 | train | Paginate a single node of the cluster. |
Kortemme-Lab/klab | klab/bio/pfam.py | Pfam.get_pfam_accession_numbers_from_pdb_id | def get_pfam_accession_numbers_from_pdb_id(self, pdb_id):
'''Note: an alternative is to use the RCSB API e.g. http://www.rcsb.org/pdb/rest/hmmer?structureId=1cdg.'''
pdb_id = pdb_id.lower()
if self.pdb_chain_to_pfam_mapping.get(pdb_id):
return self.pdb_chain_to_pfam_mapping[pdb_id].c... | python | def get_pfam_accession_numbers_from_pdb_id(self, pdb_id):
'''Note: an alternative is to use the RCSB API e.g. http://www.rcsb.org/pdb/rest/hmmer?structureId=1cdg.'''
pdb_id = pdb_id.lower()
if self.pdb_chain_to_pfam_mapping.get(pdb_id):
return self.pdb_chain_to_pfam_mapping[pdb_id].c... | [
"def",
"get_pfam_accession_numbers_from_pdb_id",
"(",
"self",
",",
"pdb_id",
")",
":",
"pdb_id",
"=",
"pdb_id",
".",
"lower",
"(",
")",
"if",
"self",
".",
"pdb_chain_to_pfam_mapping",
".",
"get",
"(",
"pdb_id",
")",
":",
"return",
"self",
".",
"pdb_chain_to_pf... | Note: an alternative is to use the RCSB API e.g. http://www.rcsb.org/pdb/rest/hmmer?structureId=1cdg. | [
"Note",
":",
"an",
"alternative",
"is",
"to",
"use",
"the",
"RCSB",
"API",
"e",
".",
"g",
".",
"http",
":",
"//",
"www",
".",
"rcsb",
".",
"org",
"/",
"pdb",
"/",
"rest",
"/",
"hmmer?structureId",
"=",
"1cdg",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pfam.py#L53-L57 | train | Returns a list of PFAM accession numbers for a given PDB ID. |
Kortemme-Lab/klab | klab/bio/pfam.py | Pfam.get_pfam_accession_numbers_from_pdb_chain | def get_pfam_accession_numbers_from_pdb_chain(self, pdb_id, chain):
'''Note: an alternative is to use the RCSB API e.g. http://www.rcsb.org/pdb/rest/hmmer?structureId=1cdg.'''
return self.pdb_chain_to_pfam_mapping.get(pdb_id.lower(), {}).get(chain) | python | def get_pfam_accession_numbers_from_pdb_chain(self, pdb_id, chain):
'''Note: an alternative is to use the RCSB API e.g. http://www.rcsb.org/pdb/rest/hmmer?structureId=1cdg.'''
return self.pdb_chain_to_pfam_mapping.get(pdb_id.lower(), {}).get(chain) | [
"def",
"get_pfam_accession_numbers_from_pdb_chain",
"(",
"self",
",",
"pdb_id",
",",
"chain",
")",
":",
"return",
"self",
".",
"pdb_chain_to_pfam_mapping",
".",
"get",
"(",
"pdb_id",
".",
"lower",
"(",
")",
",",
"{",
"}",
")",
".",
"get",
"(",
"chain",
")"... | Note: an alternative is to use the RCSB API e.g. http://www.rcsb.org/pdb/rest/hmmer?structureId=1cdg. | [
"Note",
":",
"an",
"alternative",
"is",
"to",
"use",
"the",
"RCSB",
"API",
"e",
".",
"g",
".",
"http",
":",
"//",
"www",
".",
"rcsb",
".",
"org",
"/",
"pdb",
"/",
"rest",
"/",
"hmmer?structureId",
"=",
"1cdg",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pfam.py#L59-L61 | train | Get the PFAM accession numbers for a given PDB ID and chain. |
DsixTools/python-smeftrunner | smeftrunner/definitions.py | flavor_rotation | def flavor_rotation(C_in, Uq, Uu, Ud, Ul, Ue, sm_parameters=True):
"""Gauge-invariant $U(3)^5$ flavor rotation of all Wilson coefficients and
SM parameters."""
C = {}
if sm_parameters:
# shift of theta terms, see 0907.4763
C['Thetas'] = C_in['Thetas'] - 2*argdet(Uq) + argdet(Uu) + argdet... | python | def flavor_rotation(C_in, Uq, Uu, Ud, Ul, Ue, sm_parameters=True):
"""Gauge-invariant $U(3)^5$ flavor rotation of all Wilson coefficients and
SM parameters."""
C = {}
if sm_parameters:
# shift of theta terms, see 0907.4763
C['Thetas'] = C_in['Thetas'] - 2*argdet(Uq) + argdet(Uu) + argdet... | [
"def",
"flavor_rotation",
"(",
"C_in",
",",
"Uq",
",",
"Uu",
",",
"Ud",
",",
"Ul",
",",
"Ue",
",",
"sm_parameters",
"=",
"True",
")",
":",
"C",
"=",
"{",
"}",
"if",
"sm_parameters",
":",
"# shift of theta terms, see 0907.4763",
"C",
"[",
"'Thetas'",
"]",... | Gauge-invariant $U(3)^5$ flavor rotation of all Wilson coefficients and
SM parameters. | [
"Gauge",
"-",
"invariant",
"$U",
"(",
"3",
")",
"^5$",
"flavor",
"rotation",
"of",
"all",
"Wilson",
"coefficients",
"and",
"SM",
"parameters",
"."
] | 4c9130e53ad4f7bbb526657a82150ca9d57c4b37 | https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/definitions.py#L1734-L1802 | train | Flavor rotation of all Wilson coefficients and SM parameters. |
ronhanson/python-tbx | tbx/bytes.py | bytes_to_int | def bytes_to_int(byte_array, big_endian=True, signed=False):
"""
Converts a byte array to an integer.
"""
if six.PY3:
order = 'little'
if big_endian:
order = 'big'
return int.from_bytes(byte_array, byteorder=order, signed=signed)
else:
length = len(byte_ar... | python | def bytes_to_int(byte_array, big_endian=True, signed=False):
"""
Converts a byte array to an integer.
"""
if six.PY3:
order = 'little'
if big_endian:
order = 'big'
return int.from_bytes(byte_array, byteorder=order, signed=signed)
else:
length = len(byte_ar... | [
"def",
"bytes_to_int",
"(",
"byte_array",
",",
"big_endian",
"=",
"True",
",",
"signed",
"=",
"False",
")",
":",
"if",
"six",
".",
"PY3",
":",
"order",
"=",
"'little'",
"if",
"big_endian",
":",
"order",
"=",
"'big'",
"return",
"int",
".",
"from_bytes",
... | Converts a byte array to an integer. | [
"Converts",
"a",
"byte",
"array",
"to",
"an",
"integer",
"."
] | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/bytes.py#L20-L48 | train | Converts a byte array to an integer. |
ronhanson/python-tbx | tbx/bytes.py | bytes_to_uuid_list | def bytes_to_uuid_list(byte_array):
"""
Converts a byte array to a list of uuids. Cuts the byte array by packets of 16 bytes and parse each as uuid.
:param byte_array: a byte array of length n*16
:return: a list of uuid objects
"""
result = []
for i in range(0, len(byte_array)//16):
... | python | def bytes_to_uuid_list(byte_array):
"""
Converts a byte array to a list of uuids. Cuts the byte array by packets of 16 bytes and parse each as uuid.
:param byte_array: a byte array of length n*16
:return: a list of uuid objects
"""
result = []
for i in range(0, len(byte_array)//16):
... | [
"def",
"bytes_to_uuid_list",
"(",
"byte_array",
")",
":",
"result",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"byte_array",
")",
"//",
"16",
")",
":",
"result",
".",
"append",
"(",
"uuid",
".",
"UUID",
"(",
"bytes",
"=",
... | Converts a byte array to a list of uuids. Cuts the byte array by packets of 16 bytes and parse each as uuid.
:param byte_array: a byte array of length n*16
:return: a list of uuid objects | [
"Converts",
"a",
"byte",
"array",
"to",
"a",
"list",
"of",
"uuids",
".",
"Cuts",
"the",
"byte",
"array",
"by",
"packets",
"of",
"16",
"bytes",
"and",
"parse",
"each",
"as",
"uuid",
".",
":",
"param",
"byte_array",
":",
"a",
"byte",
"array",
"of",
"le... | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/bytes.py#L69-L78 | train | Converts a byte array to a list of uuids. |
ronhanson/python-tbx | tbx/bytes.py | batch | def batch(byte_array, funcs):
"""
Converts a batch to a list of values.
:param byte_array: a byte array of length n*item_length + 8
:return: a list of uuid objects
"""
result = []
length = bytes_to_int(byte_array[0:4])
item_size = bytes_to_int(byte_array[4:8])
for i in range(0, lengt... | python | def batch(byte_array, funcs):
"""
Converts a batch to a list of values.
:param byte_array: a byte array of length n*item_length + 8
:return: a list of uuid objects
"""
result = []
length = bytes_to_int(byte_array[0:4])
item_size = bytes_to_int(byte_array[4:8])
for i in range(0, lengt... | [
"def",
"batch",
"(",
"byte_array",
",",
"funcs",
")",
":",
"result",
"=",
"[",
"]",
"length",
"=",
"bytes_to_int",
"(",
"byte_array",
"[",
"0",
":",
"4",
"]",
")",
"item_size",
"=",
"bytes_to_int",
"(",
"byte_array",
"[",
"4",
":",
"8",
"]",
")",
"... | Converts a batch to a list of values.
:param byte_array: a byte array of length n*item_length + 8
:return: a list of uuid objects | [
"Converts",
"a",
"batch",
"to",
"a",
"list",
"of",
"values",
".",
":",
"param",
"byte_array",
":",
"a",
"byte",
"array",
"of",
"length",
"n",
"*",
"item_length",
"+",
"8",
":",
"return",
":",
"a",
"list",
"of",
"uuid",
"objects"
] | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/bytes.py#L81-L94 | train | Converts a batch of bytes to a list of uuid objects. |
ronhanson/python-tbx | tbx/bytes.py | text_to_bytes | def text_to_bytes(text, encoding='UTF-8', size=None):
"""
Encode some text or string to a byte array
:param text: text to encode to bytes
:param encoding: optional encoding of the passed string. default to utf-8.
:param size: optional, if given the text will be padded with 0x00 to the right size
... | python | def text_to_bytes(text, encoding='UTF-8', size=None):
"""
Encode some text or string to a byte array
:param text: text to encode to bytes
:param encoding: optional encoding of the passed string. default to utf-8.
:param size: optional, if given the text will be padded with 0x00 to the right size
... | [
"def",
"text_to_bytes",
"(",
"text",
",",
"encoding",
"=",
"'UTF-8'",
",",
"size",
"=",
"None",
")",
":",
"res",
"=",
"str",
"(",
"text",
")",
".",
"encode",
"(",
"encoding",
")",
"if",
"size",
":",
"res",
"=",
"res",
".",
"rjust",
"(",
"size",
"... | Encode some text or string to a byte array
:param text: text to encode to bytes
:param encoding: optional encoding of the passed string. default to utf-8.
:param size: optional, if given the text will be padded with 0x00 to the right size
:return: a bytes object | [
"Encode",
"some",
"text",
"or",
"string",
"to",
"a",
"byte",
"array",
":",
"param",
"text",
":",
"text",
"to",
"encode",
"to",
"bytes",
":",
"param",
"encoding",
":",
"optional",
"encoding",
"of",
"the",
"passed",
"string",
".",
"default",
"to",
"utf",
... | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/bytes.py#L107-L118 | train | Encode some text or string to a byte array |
ronhanson/python-tbx | tbx/bytes.py | int_to_bytes | def int_to_bytes(val, bit=32, signed=False, big_endian=True):
"""
Converts an int to a byte array (bytes).
:param val: value to encode
:param bit: bit length of the integer to encode
:param signed: encode as unsigned int if false
:param big_endian: encode with big or little endian
:return:
... | python | def int_to_bytes(val, bit=32, signed=False, big_endian=True):
"""
Converts an int to a byte array (bytes).
:param val: value to encode
:param bit: bit length of the integer to encode
:param signed: encode as unsigned int if false
:param big_endian: encode with big or little endian
:return:
... | [
"def",
"int_to_bytes",
"(",
"val",
",",
"bit",
"=",
"32",
",",
"signed",
"=",
"False",
",",
"big_endian",
"=",
"True",
")",
":",
"val",
"=",
"int",
"(",
"val",
")",
"#ensure it is an int",
"if",
"six",
".",
"PY3",
":",
"order",
"=",
"'little'",
"if",... | Converts an int to a byte array (bytes).
:param val: value to encode
:param bit: bit length of the integer to encode
:param signed: encode as unsigned int if false
:param big_endian: encode with big or little endian
:return: | [
"Converts",
"an",
"int",
"to",
"a",
"byte",
"array",
"(",
"bytes",
")",
".",
":",
"param",
"val",
":",
"value",
"to",
"encode",
":",
"param",
"bit",
":",
"bit",
"length",
"of",
"the",
"integer",
"to",
"encode",
":",
"param",
"signed",
":",
"encode",
... | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/bytes.py#L130-L166 | train | Converts an integer to a byte array. |
ronhanson/python-tbx | tbx/bytes.py | ip_to_bytes | def ip_to_bytes(ip_str, big_endian=True):
"""
Converts an IP given as a string to a byte sequence
"""
if big_endian:
code = '>L'
else:
code = '<L'
return bytes(struct.unpack(code, socket.inet_aton(ip_str))[0]) | python | def ip_to_bytes(ip_str, big_endian=True):
"""
Converts an IP given as a string to a byte sequence
"""
if big_endian:
code = '>L'
else:
code = '<L'
return bytes(struct.unpack(code, socket.inet_aton(ip_str))[0]) | [
"def",
"ip_to_bytes",
"(",
"ip_str",
",",
"big_endian",
"=",
"True",
")",
":",
"if",
"big_endian",
":",
"code",
"=",
"'>L'",
"else",
":",
"code",
"=",
"'<L'",
"return",
"bytes",
"(",
"struct",
".",
"unpack",
"(",
"code",
",",
"socket",
".",
"inet_aton"... | Converts an IP given as a string to a byte sequence | [
"Converts",
"an",
"IP",
"given",
"as",
"a",
"string",
"to",
"a",
"byte",
"sequence"
] | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/bytes.py#L169-L177 | train | Converts an IP given as a string to a byte sequence |
ronhanson/python-tbx | tbx/bytes.py | decode_ber | def decode_ber(ber):
"""
Decodes a ber length byte array into an integer
return: (length, bytes_read) - a tuple of values
"""
ber = bytearray(ber)
length = ber[0]
bytes_read = 1
if length > 127:
bytes_read += length & 127 # Strip off the high bit
length = 0
for i ... | python | def decode_ber(ber):
"""
Decodes a ber length byte array into an integer
return: (length, bytes_read) - a tuple of values
"""
ber = bytearray(ber)
length = ber[0]
bytes_read = 1
if length > 127:
bytes_read += length & 127 # Strip off the high bit
length = 0
for i ... | [
"def",
"decode_ber",
"(",
"ber",
")",
":",
"ber",
"=",
"bytearray",
"(",
"ber",
")",
"length",
"=",
"ber",
"[",
"0",
"]",
"bytes_read",
"=",
"1",
"if",
"length",
">",
"127",
":",
"bytes_read",
"+=",
"length",
"&",
"127",
"# Strip off the high bit",
"le... | Decodes a ber length byte array into an integer
return: (length, bytes_read) - a tuple of values | [
"Decodes",
"a",
"ber",
"length",
"byte",
"array",
"into",
"an",
"integer",
"return",
":",
"(",
"length",
"bytes_read",
")",
"-",
"a",
"tuple",
"of",
"values"
] | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/bytes.py#L180-L193 | train | Decodes a ber length byte array into an integer
WorkItem |
ronhanson/python-tbx | tbx/bytes.py | ber_from_socket | def ber_from_socket(s):
"""
Reads a ber length from a socket.
Reads first byte to read the ber length first, then read the actual data.
return: (length, bytes_read, data) - a tuple of values
"""
if isinstance(s, network.SocketClient):
recv = s.receive
else:
recv = s.recv
... | python | def ber_from_socket(s):
"""
Reads a ber length from a socket.
Reads first byte to read the ber length first, then read the actual data.
return: (length, bytes_read, data) - a tuple of values
"""
if isinstance(s, network.SocketClient):
recv = s.receive
else:
recv = s.recv
... | [
"def",
"ber_from_socket",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"network",
".",
"SocketClient",
")",
":",
"recv",
"=",
"s",
".",
"receive",
"else",
":",
"recv",
"=",
"s",
".",
"recv",
"data",
"=",
"recv",
"(",
"1",
")",
"length",
... | Reads a ber length from a socket.
Reads first byte to read the ber length first, then read the actual data.
return: (length, bytes_read, data) - a tuple of values | [
"Reads",
"a",
"ber",
"length",
"from",
"a",
"socket",
".",
"Reads",
"first",
"byte",
"to",
"read",
"the",
"ber",
"length",
"first",
"then",
"read",
"the",
"actual",
"data",
".",
"return",
":",
"(",
"length",
"bytes_read",
"data",
")",
"-",
"a",
"tuple"... | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/bytes.py#L196-L216 | train | Reads a ber length from a socket. |
ronhanson/python-tbx | tbx/bytes.py | encode_ber | def encode_ber(value, ber_length=0):
"""
Encodes an integer to ber length
You can set the ber_length manually.
return: bitearray object
"""
if not ber_length:
if value < 127: # 1 byte case
return bytearray([value])
ber_length = 1
while value >= pow(2, 8*ber_le... | python | def encode_ber(value, ber_length=0):
"""
Encodes an integer to ber length
You can set the ber_length manually.
return: bitearray object
"""
if not ber_length:
if value < 127: # 1 byte case
return bytearray([value])
ber_length = 1
while value >= pow(2, 8*ber_le... | [
"def",
"encode_ber",
"(",
"value",
",",
"ber_length",
"=",
"0",
")",
":",
"if",
"not",
"ber_length",
":",
"if",
"value",
"<",
"127",
":",
"# 1 byte case",
"return",
"bytearray",
"(",
"[",
"value",
"]",
")",
"ber_length",
"=",
"1",
"while",
"value",
">=... | Encodes an integer to ber length
You can set the ber_length manually.
return: bitearray object | [
"Encodes",
"an",
"integer",
"to",
"ber",
"length",
"You",
"can",
"set",
"the",
"ber_length",
"manually",
".",
"return",
":",
"bitearray",
"object"
] | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/bytes.py#L219-L238 | train | Encodes an integer to ber length. |
assamite/creamas | creamas/logging.py | log_before | def log_before(attr, level=logging.DEBUG):
'''Decorator to log attribute's value(s) before function call.
Implementation allows usage only for methods belonging to class. The class
instance needs to have a :attr:`logger` that is derived from
:py:class:`~creamas.logging.ObjectLogger`.
:param int le... | python | def log_before(attr, level=logging.DEBUG):
'''Decorator to log attribute's value(s) before function call.
Implementation allows usage only for methods belonging to class. The class
instance needs to have a :attr:`logger` that is derived from
:py:class:`~creamas.logging.ObjectLogger`.
:param int le... | [
"def",
"log_before",
"(",
"attr",
",",
"level",
"=",
"logging",
".",
"DEBUG",
")",
":",
"def",
"deco",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
"=",
... | Decorator to log attribute's value(s) before function call.
Implementation allows usage only for methods belonging to class. The class
instance needs to have a :attr:`logger` that is derived from
:py:class:`~creamas.logging.ObjectLogger`.
:param int level: logging level
:param str attr: name of th... | [
"Decorator",
"to",
"log",
"attribute",
"s",
"value",
"(",
"s",
")",
"before",
"function",
"call",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/logging.py#L16-L34 | train | Decorator to log attribute s value before function call. |
assamite/creamas | creamas/logging.py | ObjectLogger.get_file | def get_file(self, attr_name):
'''Return absolute path to logging file for obj's attribute.'''
return os.path.abspath(os.path.join(self.folder, "{}.log"
.format(attr_name))) | python | def get_file(self, attr_name):
'''Return absolute path to logging file for obj's attribute.'''
return os.path.abspath(os.path.join(self.folder, "{}.log"
.format(attr_name))) | [
"def",
"get_file",
"(",
"self",
",",
"attr_name",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"folder",
",",
"\"{}.log\"",
".",
"format",
"(",
"attr_name",
")",
")",
")"
] | Return absolute path to logging file for obj's attribute. | [
"Return",
"absolute",
"path",
"to",
"logging",
"file",
"for",
"obj",
"s",
"attribute",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/logging.py#L115-L118 | train | Return absolute path to logging file for obj s attribute. |
assamite/creamas | creamas/logging.py | ObjectLogger.log_attr | def log_attr(self, level, attr_name):
'''Log attribute to file and pass the message to underlying logger.
:param int level: logging level
:param str attr_name: attribute's name to be logged
'''
msg = self.write(attr_name)
self.log(level, msg) | python | def log_attr(self, level, attr_name):
'''Log attribute to file and pass the message to underlying logger.
:param int level: logging level
:param str attr_name: attribute's name to be logged
'''
msg = self.write(attr_name)
self.log(level, msg) | [
"def",
"log_attr",
"(",
"self",
",",
"level",
",",
"attr_name",
")",
":",
"msg",
"=",
"self",
".",
"write",
"(",
"attr_name",
")",
"self",
".",
"log",
"(",
"level",
",",
"msg",
")"
] | Log attribute to file and pass the message to underlying logger.
:param int level: logging level
:param str attr_name: attribute's name to be logged | [
"Log",
"attribute",
"to",
"file",
"and",
"pass",
"the",
"message",
"to",
"underlying",
"logger",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/logging.py#L120-L127 | train | Log attribute to file and pass the message to underlying logger. |
assamite/creamas | creamas/logging.py | ObjectLogger.write | def write(self, attr_name, prefix=None):
'''Write attribute's value to a file.
:param str attr_name:
Attribute's name to be logged
:param str prefix:
Optional. Attribute's name that is prefixed to logging message,
defaults to ``None``.
:returns: mes... | python | def write(self, attr_name, prefix=None):
'''Write attribute's value to a file.
:param str attr_name:
Attribute's name to be logged
:param str prefix:
Optional. Attribute's name that is prefixed to logging message,
defaults to ``None``.
:returns: mes... | [
"def",
"write",
"(",
"self",
",",
"attr_name",
",",
"prefix",
"=",
"None",
")",
":",
"if",
"self",
".",
"_folder",
"is",
"None",
":",
"return",
"separator",
"=",
"\"\\t\"",
"attr",
"=",
"getattr",
"(",
"self",
".",
"obj",
",",
"attr_name",
")",
"if",... | Write attribute's value to a file.
:param str attr_name:
Attribute's name to be logged
:param str prefix:
Optional. Attribute's name that is prefixed to logging message,
defaults to ``None``.
:returns: message written to file
:rtype: str | [
"Write",
"attribute",
"s",
"value",
"to",
"a",
"file",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/logging.py#L133-L163 | train | Writes the value of an attribute to a file. |
adaptive-learning/proso-apps | proso/func.py | is_lambda | def is_lambda(fun):
"""
Check whether the given function is a lambda function.
.. testsetup::
from proso.func import is_lambda
.. testcode::
def not_lambda_fun():
return 1
lambda_fun = lambda: 1
print(
is_lambda(not_lambda_fun),
i... | python | def is_lambda(fun):
"""
Check whether the given function is a lambda function.
.. testsetup::
from proso.func import is_lambda
.. testcode::
def not_lambda_fun():
return 1
lambda_fun = lambda: 1
print(
is_lambda(not_lambda_fun),
i... | [
"def",
"is_lambda",
"(",
"fun",
")",
":",
"return",
"isinstance",
"(",
"fun",
",",
"type",
"(",
"LAMBDA",
")",
")",
"and",
"fun",
".",
"__name__",
"==",
"LAMBDA",
".",
"__name__"
] | Check whether the given function is a lambda function.
.. testsetup::
from proso.func import is_lambda
.. testcode::
def not_lambda_fun():
return 1
lambda_fun = lambda: 1
print(
is_lambda(not_lambda_fun),
is_lambda(lambda_fun)
)
... | [
"Check",
"whether",
"the",
"given",
"function",
"is",
"a",
"lambda",
"function",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso/func.py#L4-L33 | train | Check whether the given function is a lambda function. |
adaptive-learning/proso-apps | proso/func.py | fixed_point | def fixed_point(is_zero, plus, minus, f, x):
"""
Get the least fixed point when it can be computed piecewise.
.. testsetup::
from proso.func import fixed_point
.. doctest::
>>> sorted(fixed_point(
... is_zero=lambda xs: len(xs) == 0,
... plus=lambda xs, ys: xs +... | python | def fixed_point(is_zero, plus, minus, f, x):
"""
Get the least fixed point when it can be computed piecewise.
.. testsetup::
from proso.func import fixed_point
.. doctest::
>>> sorted(fixed_point(
... is_zero=lambda xs: len(xs) == 0,
... plus=lambda xs, ys: xs +... | [
"def",
"fixed_point",
"(",
"is_zero",
",",
"plus",
",",
"minus",
",",
"f",
",",
"x",
")",
":",
"@",
"memo_Y",
"def",
"_fixed_point",
"(",
"fixed_point_fun",
")",
":",
"def",
"__fixed_point",
"(",
"collected",
",",
"new",
")",
":",
"diff",
"=",
"minus",... | Get the least fixed point when it can be computed piecewise.
.. testsetup::
from proso.func import fixed_point
.. doctest::
>>> sorted(fixed_point(
... is_zero=lambda xs: len(xs) == 0,
... plus=lambda xs, ys: xs + ys,
... minus=lambda xs, ys: [x for x in xs i... | [
"Get",
"the",
"least",
"fixed",
"point",
"when",
"it",
"can",
"be",
"computed",
"piecewise",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso/func.py#L44-L83 | train | Returns the least fixed point when it can be computed piecewise. |
adaptive-learning/proso-apps | proso/func.py | memo_Y | def memo_Y(f):
"""
Memoized Y combinator.
.. testsetup::
from proso.func import memo_Y
.. testcode::
@memo_Y
def fib(f):
def inner_fib(n):
if n > 1:
return f(n - 1) + f(n - 2)
else:
return n
... | python | def memo_Y(f):
"""
Memoized Y combinator.
.. testsetup::
from proso.func import memo_Y
.. testcode::
@memo_Y
def fib(f):
def inner_fib(n):
if n > 1:
return f(n - 1) + f(n - 2)
else:
return n
... | [
"def",
"memo_Y",
"(",
"f",
")",
":",
"sub",
"=",
"{",
"}",
"def",
"Yf",
"(",
"*",
"args",
")",
":",
"hashable_args",
"=",
"tuple",
"(",
"[",
"repr",
"(",
"x",
")",
"for",
"x",
"in",
"args",
"]",
")",
"if",
"args",
":",
"if",
"hashable_args",
... | Memoized Y combinator.
.. testsetup::
from proso.func import memo_Y
.. testcode::
@memo_Y
def fib(f):
def inner_fib(n):
if n > 1:
return f(n - 1) + f(n - 2)
else:
return n
return inner_fib... | [
"Memoized",
"Y",
"combinator",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso/func.py#L86-L122 | train | Memoized Y combinator. |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/content.py | install | def install(application, default_content_type, encoding=None):
"""
Install the media type management settings.
:param tornado.web.Application application: the application to
install a :class:`.ContentSettings` object into.
:param str|NoneType default_content_type:
:param str|NoneType encodi... | python | def install(application, default_content_type, encoding=None):
"""
Install the media type management settings.
:param tornado.web.Application application: the application to
install a :class:`.ContentSettings` object into.
:param str|NoneType default_content_type:
:param str|NoneType encodi... | [
"def",
"install",
"(",
"application",
",",
"default_content_type",
",",
"encoding",
"=",
"None",
")",
":",
"try",
":",
"settings",
"=",
"application",
".",
"settings",
"[",
"SETTINGS_KEY",
"]",
"except",
"KeyError",
":",
"settings",
"=",
"application",
".",
... | Install the media type management settings.
:param tornado.web.Application application: the application to
install a :class:`.ContentSettings` object into.
:param str|NoneType default_content_type:
:param str|NoneType encoding:
:returns: the content settings instance
:rtype: sprockets.mixi... | [
"Install",
"the",
"media",
"type",
"management",
"settings",
"."
] | c034e04f674201487a8d6ce9f8ce36f3f5de07d8 | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/content.py#L127-L146 | train | Install the media type management settings into the application s settings dictionary. |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/content.py | get_settings | def get_settings(application, force_instance=False):
"""
Retrieve the media type settings for a application.
:param tornado.web.Application application:
:keyword bool force_instance: if :data:`True` then create the
instance if it does not exist
:return: the content settings instance
:r... | python | def get_settings(application, force_instance=False):
"""
Retrieve the media type settings for a application.
:param tornado.web.Application application:
:keyword bool force_instance: if :data:`True` then create the
instance if it does not exist
:return: the content settings instance
:r... | [
"def",
"get_settings",
"(",
"application",
",",
"force_instance",
"=",
"False",
")",
":",
"try",
":",
"return",
"application",
".",
"settings",
"[",
"SETTINGS_KEY",
"]",
"except",
"KeyError",
":",
"if",
"not",
"force_instance",
":",
"return",
"None",
"return",... | Retrieve the media type settings for a application.
:param tornado.web.Application application:
:keyword bool force_instance: if :data:`True` then create the
instance if it does not exist
:return: the content settings instance
:rtype: sprockets.mixins.mediatype.content.ContentSettings | [
"Retrieve",
"the",
"media",
"type",
"settings",
"for",
"a",
"application",
"."
] | c034e04f674201487a8d6ce9f8ce36f3f5de07d8 | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/content.py#L149-L166 | train | Retrieves the media type settings for an application. |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/content.py | add_binary_content_type | def add_binary_content_type(application, content_type, pack, unpack):
"""
Add handler for a binary content type.
:param tornado.web.Application application: the application to modify
:param str content_type: the content type to add
:param pack: function that packs a dictionary to a byte string.
... | python | def add_binary_content_type(application, content_type, pack, unpack):
"""
Add handler for a binary content type.
:param tornado.web.Application application: the application to modify
:param str content_type: the content type to add
:param pack: function that packs a dictionary to a byte string.
... | [
"def",
"add_binary_content_type",
"(",
"application",
",",
"content_type",
",",
"pack",
",",
"unpack",
")",
":",
"add_transcoder",
"(",
"application",
",",
"handlers",
".",
"BinaryContentHandler",
"(",
"content_type",
",",
"pack",
",",
"unpack",
")",
")"
] | Add handler for a binary content type.
:param tornado.web.Application application: the application to modify
:param str content_type: the content type to add
:param pack: function that packs a dictionary to a byte string.
``pack(dict) -> bytes``
:param unpack: function that takes a byte string ... | [
"Add",
"handler",
"for",
"a",
"binary",
"content",
"type",
"."
] | c034e04f674201487a8d6ce9f8ce36f3f5de07d8 | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/content.py#L169-L182 | train | Add a handler for a binary content type. |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/content.py | add_text_content_type | def add_text_content_type(application, content_type, default_encoding,
dumps, loads):
"""
Add handler for a text content type.
:param tornado.web.Application application: the application to modify
:param str content_type: the content type to add
:param str default_encoding... | python | def add_text_content_type(application, content_type, default_encoding,
dumps, loads):
"""
Add handler for a text content type.
:param tornado.web.Application application: the application to modify
:param str content_type: the content type to add
:param str default_encoding... | [
"def",
"add_text_content_type",
"(",
"application",
",",
"content_type",
",",
"default_encoding",
",",
"dumps",
",",
"loads",
")",
":",
"parsed",
"=",
"headers",
".",
"parse_content_type",
"(",
"content_type",
")",
"parsed",
".",
"parameters",
".",
"pop",
"(",
... | Add handler for a text content type.
:param tornado.web.Application application: the application to modify
:param str content_type: the content type to add
:param str default_encoding: encoding to use when one is unspecified
:param dumps: function that dumps a dictionary to a string.
``dumps(di... | [
"Add",
"handler",
"for",
"a",
"text",
"content",
"type",
"."
] | c034e04f674201487a8d6ce9f8ce36f3f5de07d8 | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/content.py#L185-L207 | train | Add a handler for a text content type. |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/content.py | add_transcoder | def add_transcoder(application, transcoder, content_type=None):
"""
Register a transcoder for a specific content type.
:param tornado.web.Application application: the application to modify
:param transcoder: object that translates between :class:`bytes` and
:class:`object` instances
:param ... | python | def add_transcoder(application, transcoder, content_type=None):
"""
Register a transcoder for a specific content type.
:param tornado.web.Application application: the application to modify
:param transcoder: object that translates between :class:`bytes` and
:class:`object` instances
:param ... | [
"def",
"add_transcoder",
"(",
"application",
",",
"transcoder",
",",
"content_type",
"=",
"None",
")",
":",
"settings",
"=",
"get_settings",
"(",
"application",
",",
"force_instance",
"=",
"True",
")",
"settings",
"[",
"content_type",
"or",
"transcoder",
".",
... | Register a transcoder for a specific content type.
:param tornado.web.Application application: the application to modify
:param transcoder: object that translates between :class:`bytes` and
:class:`object` instances
:param str content_type: the content type to add. If this is
unspecified o... | [
"Register",
"a",
"transcoder",
"for",
"a",
"specific",
"content",
"type",
"."
] | c034e04f674201487a8d6ce9f8ce36f3f5de07d8 | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/content.py#L210-L243 | train | Adds a transcoder to the list of available transcoders for a specific content type. |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/content.py | set_default_content_type | def set_default_content_type(application, content_type, encoding=None):
"""
Store the default content type for an application.
:param tornado.web.Application application: the application to modify
:param str content_type: the content type to default to
:param str|None encoding: encoding to use when... | python | def set_default_content_type(application, content_type, encoding=None):
"""
Store the default content type for an application.
:param tornado.web.Application application: the application to modify
:param str content_type: the content type to default to
:param str|None encoding: encoding to use when... | [
"def",
"set_default_content_type",
"(",
"application",
",",
"content_type",
",",
"encoding",
"=",
"None",
")",
":",
"settings",
"=",
"get_settings",
"(",
"application",
",",
"force_instance",
"=",
"True",
")",
"settings",
".",
"default_content_type",
"=",
"content... | Store the default content type for an application.
:param tornado.web.Application application: the application to modify
:param str content_type: the content type to default to
:param str|None encoding: encoding to use when one is unspecified | [
"Store",
"the",
"default",
"content",
"type",
"for",
"an",
"application",
"."
] | c034e04f674201487a8d6ce9f8ce36f3f5de07d8 | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/content.py#L246-L257 | train | Store the default content type for an application. |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/content.py | ContentMixin.get_response_content_type | def get_response_content_type(self):
"""Figure out what content type will be used in the response."""
if self._best_response_match is None:
settings = get_settings(self.application, force_instance=True)
acceptable = headers.parse_accept(
self.request.headers.get(
... | python | def get_response_content_type(self):
"""Figure out what content type will be used in the response."""
if self._best_response_match is None:
settings = get_settings(self.application, force_instance=True)
acceptable = headers.parse_accept(
self.request.headers.get(
... | [
"def",
"get_response_content_type",
"(",
"self",
")",
":",
"if",
"self",
".",
"_best_response_match",
"is",
"None",
":",
"settings",
"=",
"get_settings",
"(",
"self",
".",
"application",
",",
"force_instance",
"=",
"True",
")",
"acceptable",
"=",
"headers",
".... | Figure out what content type will be used in the response. | [
"Figure",
"out",
"what",
"content",
"type",
"will",
"be",
"used",
"in",
"the",
"response",
"."
] | c034e04f674201487a8d6ce9f8ce36f3f5de07d8 | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/content.py#L287-L307 | train | Figure out what content type will be used in the response. |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/content.py | ContentMixin.get_request_body | def get_request_body(self):
"""
Fetch (and cache) the request body as a dictionary.
:raise web.HTTPError:
- if the content type cannot be matched, then the status code
is set to 415 Unsupported Media Type.
- if decoding the content body fails, then the stat... | python | def get_request_body(self):
"""
Fetch (and cache) the request body as a dictionary.
:raise web.HTTPError:
- if the content type cannot be matched, then the status code
is set to 415 Unsupported Media Type.
- if decoding the content body fails, then the stat... | [
"def",
"get_request_body",
"(",
"self",
")",
":",
"if",
"self",
".",
"_request_body",
"is",
"None",
":",
"settings",
"=",
"get_settings",
"(",
"self",
".",
"application",
",",
"force_instance",
"=",
"True",
")",
"content_type_header",
"=",
"headers",
".",
"p... | Fetch (and cache) the request body as a dictionary.
:raise web.HTTPError:
- if the content type cannot be matched, then the status code
is set to 415 Unsupported Media Type.
- if decoding the content body fails, then the status code is
set to 400 Bad Syntax. | [
"Fetch",
"(",
"and",
"cache",
")",
"the",
"request",
"body",
"as",
"a",
"dictionary",
"."
] | c034e04f674201487a8d6ce9f8ce36f3f5de07d8 | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/content.py#L309-L342 | train | Fetch the request body as a dictionary. |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/content.py | ContentMixin.send_response | def send_response(self, body, set_content_type=True):
"""
Serialize and send ``body`` in the response.
:param dict body: the body to serialize
:param bool set_content_type: should the :http:header:`Content-Type`
header be set? Defaults to :data:`True`
"""
s... | python | def send_response(self, body, set_content_type=True):
"""
Serialize and send ``body`` in the response.
:param dict body: the body to serialize
:param bool set_content_type: should the :http:header:`Content-Type`
header be set? Defaults to :data:`True`
"""
s... | [
"def",
"send_response",
"(",
"self",
",",
"body",
",",
"set_content_type",
"=",
"True",
")",
":",
"settings",
"=",
"get_settings",
"(",
"self",
".",
"application",
",",
"force_instance",
"=",
"True",
")",
"handler",
"=",
"settings",
"[",
"self",
".",
"get_... | Serialize and send ``body`` in the response.
:param dict body: the body to serialize
:param bool set_content_type: should the :http:header:`Content-Type`
header be set? Defaults to :data:`True` | [
"Serialize",
"and",
"send",
"body",
"in",
"the",
"response",
"."
] | c034e04f674201487a8d6ce9f8ce36f3f5de07d8 | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/content.py#L344-L359 | train | Serialize and send the body in the response. |
assamite/creamas | creamas/nx.py | connections_from_graph | def connections_from_graph(env, G, edge_data=False):
"""Create connections for agents in the given environment from the given
NetworkX graph structure.
:param env:
Environment where the agents live. The environment should be derived
from :class:`~creamas.core.environment.Environment`,
... | python | def connections_from_graph(env, G, edge_data=False):
"""Create connections for agents in the given environment from the given
NetworkX graph structure.
:param env:
Environment where the agents live. The environment should be derived
from :class:`~creamas.core.environment.Environment`,
... | [
"def",
"connections_from_graph",
"(",
"env",
",",
"G",
",",
"edge_data",
"=",
"False",
")",
":",
"if",
"not",
"issubclass",
"(",
"G",
".",
"__class__",
",",
"(",
"Graph",
",",
"DiGraph",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Graph structure must be ... | Create connections for agents in the given environment from the given
NetworkX graph structure.
:param env:
Environment where the agents live. The environment should be derived
from :class:`~creamas.core.environment.Environment`,
:class:`~creamas.mp.MultiEnvironment` or
:class:`... | [
"Create",
"connections",
"for",
"agents",
"in",
"the",
"given",
"environment",
"from",
"the",
"given",
"NetworkX",
"graph",
"structure",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/nx.py#L22-L74 | train | Create connections for agents in the given environment from the given NetworkX graph structure. |
assamite/creamas | creamas/nx.py | graph_from_connections | def graph_from_connections(env, directed=False):
"""Create NetworkX graph from agent connections in a given environment.
:param env:
Environment where the agents live. The environment must be derived from
:class:`~creamas.core.environment.Environment`,
:class:`~creamas.mp.MultiEnvironme... | python | def graph_from_connections(env, directed=False):
"""Create NetworkX graph from agent connections in a given environment.
:param env:
Environment where the agents live. The environment must be derived from
:class:`~creamas.core.environment.Environment`,
:class:`~creamas.mp.MultiEnvironme... | [
"def",
"graph_from_connections",
"(",
"env",
",",
"directed",
"=",
"False",
")",
":",
"G",
"=",
"DiGraph",
"(",
")",
"if",
"directed",
"else",
"Graph",
"(",
")",
"conn_list",
"=",
"env",
".",
"get_connections",
"(",
"data",
"=",
"True",
")",
"for",
"ag... | Create NetworkX graph from agent connections in a given environment.
:param env:
Environment where the agents live. The environment must be derived from
:class:`~creamas.core.environment.Environment`,
:class:`~creamas.mp.MultiEnvironment` or
:class:`~creamas.ds.DistributedEnvironmen... | [
"Create",
"NetworkX",
"graph",
"from",
"agent",
"connections",
"in",
"a",
"given",
"environment",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/nx.py#L77-L109 | train | Create a NetworkX graph from agent connections in a given environment. |
assamite/creamas | creamas/nx.py | _addrs2nodes | def _addrs2nodes(addrs, G):
"""Map agent addresses to nodes in the graph.
"""
for i, n in enumerate(G.nodes()):
G.node[n]['addr'] = addrs[i] | python | def _addrs2nodes(addrs, G):
"""Map agent addresses to nodes in the graph.
"""
for i, n in enumerate(G.nodes()):
G.node[n]['addr'] = addrs[i] | [
"def",
"_addrs2nodes",
"(",
"addrs",
",",
"G",
")",
":",
"for",
"i",
",",
"n",
"in",
"enumerate",
"(",
"G",
".",
"nodes",
"(",
")",
")",
":",
"G",
".",
"node",
"[",
"n",
"]",
"[",
"'addr'",
"]",
"=",
"addrs",
"[",
"i",
"]"
] | Map agent addresses to nodes in the graph. | [
"Map",
"agent",
"addresses",
"to",
"nodes",
"in",
"the",
"graph",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/nx.py#L112-L116 | train | Map agent addresses to nodes in the graph. |
assamite/creamas | creamas/nx.py | _edges2conns | def _edges2conns(G, edge_data=False):
"""Create a mapping from graph edges to agent connections to be created.
:param G:
NetworkX's Graph or DiGraph which has :attr:`addr` attribute for each
node.
:param bool edge_data:
If ``True``, stores also edge data to the returned dictionary.... | python | def _edges2conns(G, edge_data=False):
"""Create a mapping from graph edges to agent connections to be created.
:param G:
NetworkX's Graph or DiGraph which has :attr:`addr` attribute for each
node.
:param bool edge_data:
If ``True``, stores also edge data to the returned dictionary.... | [
"def",
"_edges2conns",
"(",
"G",
",",
"edge_data",
"=",
"False",
")",
":",
"cm",
"=",
"{",
"}",
"for",
"n",
"in",
"G",
".",
"nodes",
"(",
"data",
"=",
"True",
")",
":",
"if",
"edge_data",
":",
"cm",
"[",
"n",
"[",
"1",
"]",
"[",
"'addr'",
"]"... | Create a mapping from graph edges to agent connections to be created.
:param G:
NetworkX's Graph or DiGraph which has :attr:`addr` attribute for each
node.
:param bool edge_data:
If ``True``, stores also edge data to the returned dictionary.
:returns:
A dictionary where ke... | [
"Create",
"a",
"mapping",
"from",
"graph",
"edges",
"to",
"agent",
"connections",
"to",
"be",
"created",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/nx.py#L119-L143 | train | Create a mapping from edges to agent connections. |
adaptive-learning/proso-apps | proso_user/views.py | profile | def profile(request, status=200):
"""
Get the user's profile. If the user has no assigned profile, the HTTP 404
is returned. Make a POST request to modify the user's profile.
GET parameters:
html
turn on the HTML version of the API
username:
username of user (onl... | python | def profile(request, status=200):
"""
Get the user's profile. If the user has no assigned profile, the HTTP 404
is returned. Make a POST request to modify the user's profile.
GET parameters:
html
turn on the HTML version of the API
username:
username of user (onl... | [
"def",
"profile",
"(",
"request",
",",
"status",
"=",
"200",
")",
":",
"if",
"request",
".",
"method",
"==",
"'GET'",
":",
"if",
"request",
".",
"GET",
".",
"get",
"(",
"\"username\"",
",",
"False",
")",
":",
"try",
":",
"user_profile",
"=",
"User",
... | Get the user's profile. If the user has no assigned profile, the HTTP 404
is returned. Make a POST request to modify the user's profile.
GET parameters:
html
turn on the HTML version of the API
username:
username of user (only for users with public profile)
stats... | [
"Get",
"the",
"user",
"s",
"profile",
".",
"If",
"the",
"user",
"has",
"no",
"assigned",
"profile",
"the",
"HTTP",
"404",
"is",
"returned",
".",
"Make",
"a",
"POST",
"request",
"to",
"modify",
"the",
"user",
"s",
"profile",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_user/views.py#L22-L89 | train | Returns a list of user s profile. |
adaptive-learning/proso-apps | proso_user/views.py | login | def login(request):
"""
Log in
GET parameters:
html
turn on the HTML version of the API
POST parameters (JSON):
username:
user's name
password:
user's password
"""
if request.method == 'GET':
return render(request, 'user_login... | python | def login(request):
"""
Log in
GET parameters:
html
turn on the HTML version of the API
POST parameters (JSON):
username:
user's name
password:
user's password
"""
if request.method == 'GET':
return render(request, 'user_login... | [
"def",
"login",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"'GET'",
":",
"return",
"render",
"(",
"request",
",",
"'user_login.html'",
",",
"{",
"}",
",",
"help_text",
"=",
"login",
".",
"__doc__",
")",
"elif",
"request",
".",
"met... | Log in
GET parameters:
html
turn on the HTML version of the API
POST parameters (JSON):
username:
user's name
password:
user's password | [
"Log",
"in"
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_user/views.py#L124-L160 | train | Log in the user and return the user s profile. |
adaptive-learning/proso-apps | proso_user/views.py | signup | def signup(request):
"""
Create a new user with the given credentials.
GET parameters:
html
turn on the HTML version of the API
POST parameters (JSON):
username:
user's name
email:
user's e-mail
password:
user's password
... | python | def signup(request):
"""
Create a new user with the given credentials.
GET parameters:
html
turn on the HTML version of the API
POST parameters (JSON):
username:
user's name
email:
user's e-mail
password:
user's password
... | [
"def",
"signup",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"'GET'",
":",
"return",
"render",
"(",
"request",
",",
"'user_signup.html'",
",",
"{",
"}",
",",
"help_text",
"=",
"signup",
".",
"__doc__",
")",
"elif",
"request",
".",
"... | Create a new user with the given credentials.
GET parameters:
html
turn on the HTML version of the API
POST parameters (JSON):
username:
user's name
email:
user's e-mail
password:
user's password
password_check:
... | [
"Create",
"a",
"new",
"user",
"with",
"the",
"given",
"credentials",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_user/views.py#L243-L282 | train | Create a new user with the given credentials. |
adaptive-learning/proso-apps | proso_user/views.py | session | def session(request):
"""
Get the information about the current session or modify the current session.
GET parameters:
html
turn on the HTML version of the API
POST parameters:
locale:
client's locale
time_zone:
client's time zone
display_width:
... | python | def session(request):
"""
Get the information about the current session or modify the current session.
GET parameters:
html
turn on the HTML version of the API
POST parameters:
locale:
client's locale
time_zone:
client's time zone
display_width:
... | [
"def",
"session",
"(",
"request",
")",
":",
"if",
"request",
".",
"user",
".",
"id",
"is",
"None",
":",
"# Google Bot",
"return",
"render_json",
"(",
"request",
",",
"{",
"'error'",
":",
"_",
"(",
"'There is no user available to create a session.'",
")",
",",
... | Get the information about the current session or modify the current session.
GET parameters:
html
turn on the HTML version of the API
POST parameters:
locale:
client's locale
time_zone:
client's time zone
display_width:
width of the client's display
... | [
"Get",
"the",
"information",
"about",
"the",
"current",
"session",
"or",
"modify",
"the",
"current",
"session",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_user/views.py#L288-L338 | train | Returns the current session or modify the current session. |
adaptive-learning/proso-apps | proso_user/views.py | initmobile_view | def initmobile_view(request):
"""
Create lazy user with a password. Used from the Android app.
Also returns csrf token.
GET parameters:
username:
user's name
password:
user's password
"""
if 'username' in request.GET and 'password' in request.GET:
... | python | def initmobile_view(request):
"""
Create lazy user with a password. Used from the Android app.
Also returns csrf token.
GET parameters:
username:
user's name
password:
user's password
"""
if 'username' in request.GET and 'password' in request.GET:
... | [
"def",
"initmobile_view",
"(",
"request",
")",
":",
"if",
"'username'",
"in",
"request",
".",
"GET",
"and",
"'password'",
"in",
"request",
".",
"GET",
":",
"username",
"=",
"request",
".",
"GET",
"[",
"'username'",
"]",
"password",
"=",
"request",
".",
"... | Create lazy user with a password. Used from the Android app.
Also returns csrf token.
GET parameters:
username:
user's name
password:
user's password | [
"Create",
"lazy",
"user",
"with",
"a",
"password",
".",
"Used",
"from",
"the",
"Android",
"app",
".",
"Also",
"returns",
"csrf",
"token",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_user/views.py#L341-L370 | train | Create lazy user with a random password. Used from the Android app. |
truveris/py-mdstat | mdstat/disk.py | parse_device_disk | def parse_device_disk(token):
"""Parse a single disk from the header line.
Each disks has at least a device name and a unique number in its array,
after that could follow a list of special flags:
(W) write-mostly
(S) spare disk
(F) faulty disk
(R) replacement disk
So... | python | def parse_device_disk(token):
"""Parse a single disk from the header line.
Each disks has at least a device name and a unique number in its array,
after that could follow a list of special flags:
(W) write-mostly
(S) spare disk
(F) faulty disk
(R) replacement disk
So... | [
"def",
"parse_device_disk",
"(",
"token",
")",
":",
"name",
",",
"token",
"=",
"token",
".",
"split",
"(",
"\"[\"",
",",
"1",
")",
"number",
",",
"flags",
"=",
"token",
".",
"split",
"(",
"\"]\"",
",",
"1",
")",
"return",
"name",
",",
"{",
"\"numbe... | Parse a single disk from the header line.
Each disks has at least a device name and a unique number in its array,
after that could follow a list of special flags:
(W) write-mostly
(S) spare disk
(F) faulty disk
(R) replacement disk
Some are mutually exclusive (e.g. can't... | [
"Parse",
"a",
"single",
"disk",
"from",
"the",
"header",
"line",
"."
] | 881af99d1168694d2f38e606af377ef6cabe2297 | https://github.com/truveris/py-mdstat/blob/881af99d1168694d2f38e606af377ef6cabe2297/mdstat/disk.py#L6-L27 | train | Parse a single disk from the header line. |
adaptive-learning/proso-apps | proso/list.py | group_by | def group_by(what, by):
"""
Take a list and apply the given function on each its value, then group the
values by the function results.
.. testsetup::
from proso.list import group_by
.. doctest::
>>> group_by([i for i in range(10)], by=lambda x: x % 2 == 0)
{False: [1, 3, ... | python | def group_by(what, by):
"""
Take a list and apply the given function on each its value, then group the
values by the function results.
.. testsetup::
from proso.list import group_by
.. doctest::
>>> group_by([i for i in range(10)], by=lambda x: x % 2 == 0)
{False: [1, 3, ... | [
"def",
"group_by",
"(",
"what",
",",
"by",
")",
":",
"return",
"proso",
".",
"dict",
".",
"group_keys_by_values",
"(",
"{",
"x",
":",
"by",
"(",
"x",
")",
"for",
"x",
"in",
"what",
"}",
")"
] | Take a list and apply the given function on each its value, then group the
values by the function results.
.. testsetup::
from proso.list import group_by
.. doctest::
>>> group_by([i for i in range(10)], by=lambda x: x % 2 == 0)
{False: [1, 3, 5, 7, 9], True: [0, 2, 4, 6, 8]}
... | [
"Take",
"a",
"list",
"and",
"apply",
"the",
"given",
"function",
"on",
"each",
"its",
"value",
"then",
"group",
"the",
"values",
"by",
"the",
"function",
"results",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso/list.py#L25-L46 | train | Takes a list and applies the given function on each value then group the values by the function on each its value |
mardix/Mocha | mocha/cli.py | copy_resource_dir | def copy_resource_dir(src, dest):
"""
To copy package data directory to destination
"""
package_name = "mocha"
dest = (dest + "/" + os.path.basename(src)).rstrip("/")
if pkg_resources.resource_isdir(package_name, src):
if not os.path.isdir(dest):
os.makedirs(dest)
for... | python | def copy_resource_dir(src, dest):
"""
To copy package data directory to destination
"""
package_name = "mocha"
dest = (dest + "/" + os.path.basename(src)).rstrip("/")
if pkg_resources.resource_isdir(package_name, src):
if not os.path.isdir(dest):
os.makedirs(dest)
for... | [
"def",
"copy_resource_dir",
"(",
"src",
",",
"dest",
")",
":",
"package_name",
"=",
"\"mocha\"",
"dest",
"=",
"(",
"dest",
"+",
"\"/\"",
"+",
"os",
".",
"path",
".",
"basename",
"(",
"src",
")",
")",
".",
"rstrip",
"(",
"\"/\"",
")",
"if",
"pkg_resou... | To copy package data directory to destination | [
"To",
"copy",
"package",
"data",
"directory",
"to",
"destination"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/cli.py#L71-L84 | train | Copy a resource directory to a destination |
mardix/Mocha | mocha/cli.py | init | def init():
""" Setup Mocha in the current directory """
mochapyfile = os.path.join(os.path.join(CWD, "brew.py"))
header("Initializing Mocha ...")
if os.path.isfile(mochapyfile):
print("WARNING: It seems like Mocha is already setup!")
print("*" * 80)
else:
print("")
... | python | def init():
""" Setup Mocha in the current directory """
mochapyfile = os.path.join(os.path.join(CWD, "brew.py"))
header("Initializing Mocha ...")
if os.path.isfile(mochapyfile):
print("WARNING: It seems like Mocha is already setup!")
print("*" * 80)
else:
print("")
... | [
"def",
"init",
"(",
")",
":",
"mochapyfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"join",
"(",
"CWD",
",",
"\"brew.py\"",
")",
")",
"header",
"(",
"\"Initializing Mocha ...\"",
")",
"if",
"os",
".",
"path",
".",
"isfile",... | Setup Mocha in the current directory | [
"Setup",
"Mocha",
"in",
"the",
"current",
"directory"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/cli.py#L154-L178 | train | Initialize Mocha in the current directory |
mardix/Mocha | mocha/cli.py | add_view | def add_view(name, no_template):
""" Create a new view and template page """
app_dest = APPLICATION_DIR
viewsrc = "%s/create-view/view.py" % SKELETON_DIR
tplsrc = "%s/create-view/template.jade" % SKELETON_DIR
viewdest_dir = os.path.join(app_dest, "views")
viewdest = os.path.join(viewdest_dir, "... | python | def add_view(name, no_template):
""" Create a new view and template page """
app_dest = APPLICATION_DIR
viewsrc = "%s/create-view/view.py" % SKELETON_DIR
tplsrc = "%s/create-view/template.jade" % SKELETON_DIR
viewdest_dir = os.path.join(app_dest, "views")
viewdest = os.path.join(viewdest_dir, "... | [
"def",
"add_view",
"(",
"name",
",",
"no_template",
")",
":",
"app_dest",
"=",
"APPLICATION_DIR",
"viewsrc",
"=",
"\"%s/create-view/view.py\"",
"%",
"SKELETON_DIR",
"tplsrc",
"=",
"\"%s/create-view/template.jade\"",
"%",
"SKELETON_DIR",
"viewdest_dir",
"=",
"os",
".",... | Create a new view and template page | [
"Create",
"a",
"new",
"view",
"and",
"template",
"page"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/cli.py#L184-L221 | train | Create a new view and template page |
mardix/Mocha | mocha/cli.py | server | def server(port):
""" Serve application in development mode """
header("Serving application in development mode ... ")
print("")
print("- Port: %s" % port)
print("")
cwd_to_sys_path()
application.app.run(debug=True, host='0.0.0.0', port=port) | python | def server(port):
""" Serve application in development mode """
header("Serving application in development mode ... ")
print("")
print("- Port: %s" % port)
print("")
cwd_to_sys_path()
application.app.run(debug=True, host='0.0.0.0', port=port) | [
"def",
"server",
"(",
"port",
")",
":",
"header",
"(",
"\"Serving application in development mode ... \"",
")",
"print",
"(",
"\"\"",
")",
"print",
"(",
"\"- Port: %s\"",
"%",
"port",
")",
"print",
"(",
"\"\"",
")",
"cwd_to_sys_path",
"(",
")",
"application",
... | Serve application in development mode | [
"Serve",
"application",
"in",
"development",
"mode"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/cli.py#L227-L235 | train | Serve application in development mode |
mardix/Mocha | mocha/cli.py | initdb | def initdb():
""" Sync database Create new tables etc... """
print("Syncing up database...")
cwd_to_sys_path()
if db and hasattr(db, "Model"):
db.create_all()
for m in db.Model.__subclasses__():
if hasattr(m, "initialize__"):
print("Sync up model: %s ..." % m... | python | def initdb():
""" Sync database Create new tables etc... """
print("Syncing up database...")
cwd_to_sys_path()
if db and hasattr(db, "Model"):
db.create_all()
for m in db.Model.__subclasses__():
if hasattr(m, "initialize__"):
print("Sync up model: %s ..." % m... | [
"def",
"initdb",
"(",
")",
":",
"print",
"(",
"\"Syncing up database...\"",
")",
"cwd_to_sys_path",
"(",
")",
"if",
"db",
"and",
"hasattr",
"(",
"db",
",",
"\"Model\"",
")",
":",
"db",
".",
"create_all",
"(",
")",
"for",
"m",
"in",
"db",
".",
"Model",
... | Sync database Create new tables etc... | [
"Sync",
"database",
"Create",
"new",
"tables",
"etc",
"..."
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/cli.py#L239-L251 | train | Sync database Create new tables etc... |
mardix/Mocha | mocha/cli.py | _set_flask_alembic | def _set_flask_alembic():
from flask_alembic import Alembic
""" Add the SQLAlchemy object in the global extension """
application.app.extensions["sqlalchemy"] = type('', (), {"db": db})
alembic = Alembic()
alembic.init_app(application.app)
return alembic | python | def _set_flask_alembic():
from flask_alembic import Alembic
""" Add the SQLAlchemy object in the global extension """
application.app.extensions["sqlalchemy"] = type('', (), {"db": db})
alembic = Alembic()
alembic.init_app(application.app)
return alembic | [
"def",
"_set_flask_alembic",
"(",
")",
":",
"from",
"flask_alembic",
"import",
"Alembic",
"application",
".",
"app",
".",
"extensions",
"[",
"\"sqlalchemy\"",
"]",
"=",
"type",
"(",
"''",
",",
"(",
")",
",",
"{",
"\"db\"",
":",
"db",
"}",
")",
"alembic",... | Add the SQLAlchemy object in the global extension | [
"Add",
"the",
"SQLAlchemy",
"object",
"in",
"the",
"global",
"extension"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/cli.py#L254-L261 | train | Set the flask_alembic module to the global extension |
mardix/Mocha | mocha/cli.py | db_migrate | def db_migrate():
"""Migrate DB """
print("Not ready for use")
exit()
cwd_to_sys_path()
alembic = _set_flask_alembic()
with application.app.app_context():
p = db.Model.__subclasses__()
print(p)
# Auto-generate a migration
alembic.revision('making changes')
... | python | def db_migrate():
"""Migrate DB """
print("Not ready for use")
exit()
cwd_to_sys_path()
alembic = _set_flask_alembic()
with application.app.app_context():
p = db.Model.__subclasses__()
print(p)
# Auto-generate a migration
alembic.revision('making changes')
... | [
"def",
"db_migrate",
"(",
")",
":",
"print",
"(",
"\"Not ready for use\"",
")",
"exit",
"(",
")",
"cwd_to_sys_path",
"(",
")",
"alembic",
"=",
"_set_flask_alembic",
"(",
")",
"with",
"application",
".",
"app",
".",
"app_context",
"(",
")",
":",
"p",
"=",
... | Migrate DB | [
"Migrate",
"DB"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/cli.py#L266-L280 | train | Migrate the database |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.