repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
Capitains/Nautilus | capitains_nautilus/cts/resolver/base.py | ProtoNautilusCtsResolver.parse | def parse(self, resource=None):
""" Parse a list of directories ans
:param resource: List of folders
"""
if resource is None:
resource = self.__resources__
self.inventory = self.dispatcher.collection
try:
self._parse(resource)
except MyCapytain.errors.UndispatchedTextError as E:
if self.RAISE_ON_UNDISPATCHED is True:
raise UndispatchedTextError(E)
self.inventory = self.dispatcher.collection
return self.inventory | python | def parse(self, resource=None):
""" Parse a list of directories ans
:param resource: List of folders
"""
if resource is None:
resource = self.__resources__
self.inventory = self.dispatcher.collection
try:
self._parse(resource)
except MyCapytain.errors.UndispatchedTextError as E:
if self.RAISE_ON_UNDISPATCHED is True:
raise UndispatchedTextError(E)
self.inventory = self.dispatcher.collection
return self.inventory | [
"def",
"parse",
"(",
"self",
",",
"resource",
"=",
"None",
")",
":",
"if",
"resource",
"is",
"None",
":",
"resource",
"=",
"self",
".",
"__resources__",
"self",
".",
"inventory",
"=",
"self",
".",
"dispatcher",
".",
"collection",
"try",
":",
"self",
".... | Parse a list of directories ans
:param resource: List of folders | [
"Parse",
"a",
"list",
"of",
"directories",
"ans"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/cts/resolver/base.py#L103-L120 | train | 53,800 |
Capitains/Nautilus | capitains_nautilus/cts/resolver/base.py | _SparqlSharedResolver._dispatch | def _dispatch(self, textgroup, directory):
""" Sparql dispatcher do not need to dispatch works, as the link is DB stored through Textgroup
:param textgroup: A Textgroup object
:param directory: The path in which we found the textgroup
:return:
"""
self.dispatcher.dispatch(textgroup, path=directory) | python | def _dispatch(self, textgroup, directory):
""" Sparql dispatcher do not need to dispatch works, as the link is DB stored through Textgroup
:param textgroup: A Textgroup object
:param directory: The path in which we found the textgroup
:return:
"""
self.dispatcher.dispatch(textgroup, path=directory) | [
"def",
"_dispatch",
"(",
"self",
",",
"textgroup",
",",
"directory",
")",
":",
"self",
".",
"dispatcher",
".",
"dispatch",
"(",
"textgroup",
",",
"path",
"=",
"directory",
")"
] | Sparql dispatcher do not need to dispatch works, as the link is DB stored through Textgroup
:param textgroup: A Textgroup object
:param directory: The path in which we found the textgroup
:return: | [
"Sparql",
"dispatcher",
"do",
"not",
"need",
"to",
"dispatch",
"works",
"as",
"the",
"link",
"is",
"DB",
"stored",
"through",
"Textgroup"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/cts/resolver/base.py#L319-L326 | train | 53,801 |
PolyJIT/benchbuild | benchbuild/utils/user_interface.py | ask | def ask(question, default_answer=False, default_answer_str="no"):
"""
Ask for user input.
This asks a yes/no question with a preset default.
You can bypass the user-input and fetch the default answer, if
you set
Args:
question: The question to ask on stdout.
default_answer: The default value to return.
default_answer_str:
The default answer string that we present to the user.
Tests:
>>> os.putenv("TEST", "yes"); ask("Test?", default_answer=True)
True
>>> os.putenv("TEST", "yes"); ask("Test?", default_answer=False)
False
"""
response = default_answer
def should_ignore_tty():
"""
Check, if we want to ignore an opened tty result.
"""
ret_to_bool = {"yes": True, "no": False, "true": True, "false": False}
envs = [os.getenv("CI", default="no"), os.getenv("TEST", default="no")]
vals = [ret_to_bool[val] for val in envs if val in ret_to_bool]
return any(vals)
ignore_stdin_istty = should_ignore_tty()
has_tty = sys.stdin.isatty() and not ignore_stdin_istty
if has_tty:
response = query_yes_no(question, default_answer_str)
else:
LOG.debug("NoTTY: %s -> %s", question, response)
return response | python | def ask(question, default_answer=False, default_answer_str="no"):
"""
Ask for user input.
This asks a yes/no question with a preset default.
You can bypass the user-input and fetch the default answer, if
you set
Args:
question: The question to ask on stdout.
default_answer: The default value to return.
default_answer_str:
The default answer string that we present to the user.
Tests:
>>> os.putenv("TEST", "yes"); ask("Test?", default_answer=True)
True
>>> os.putenv("TEST", "yes"); ask("Test?", default_answer=False)
False
"""
response = default_answer
def should_ignore_tty():
"""
Check, if we want to ignore an opened tty result.
"""
ret_to_bool = {"yes": True, "no": False, "true": True, "false": False}
envs = [os.getenv("CI", default="no"), os.getenv("TEST", default="no")]
vals = [ret_to_bool[val] for val in envs if val in ret_to_bool]
return any(vals)
ignore_stdin_istty = should_ignore_tty()
has_tty = sys.stdin.isatty() and not ignore_stdin_istty
if has_tty:
response = query_yes_no(question, default_answer_str)
else:
LOG.debug("NoTTY: %s -> %s", question, response)
return response | [
"def",
"ask",
"(",
"question",
",",
"default_answer",
"=",
"False",
",",
"default_answer_str",
"=",
"\"no\"",
")",
":",
"response",
"=",
"default_answer",
"def",
"should_ignore_tty",
"(",
")",
":",
"\"\"\"\n Check, if we want to ignore an opened tty result.\n ... | Ask for user input.
This asks a yes/no question with a preset default.
You can bypass the user-input and fetch the default answer, if
you set
Args:
question: The question to ask on stdout.
default_answer: The default value to return.
default_answer_str:
The default answer string that we present to the user.
Tests:
>>> os.putenv("TEST", "yes"); ask("Test?", default_answer=True)
True
>>> os.putenv("TEST", "yes"); ask("Test?", default_answer=False)
False | [
"Ask",
"for",
"user",
"input",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/user_interface.py#L46-L84 | train | 53,802 |
davidhuser/dhis2.py | dhis2/utils.py | load_csv | def load_csv(path, delimiter=','):
"""
Load CSV file from path and yield CSV rows
Usage:
for row in load_csv('/path/to/file'):
print(row)
or
list(load_csv('/path/to/file'))
:param path: file path
:param delimiter: CSV delimiter
:return: a generator where __next__ is a row of the CSV
"""
try:
with open(path, 'rb') as csvfile:
reader = DictReader(csvfile, delimiter=delimiter)
for row in reader:
yield row
except (OSError, IOError):
raise ClientException("File not found: {}".format(path)) | python | def load_csv(path, delimiter=','):
"""
Load CSV file from path and yield CSV rows
Usage:
for row in load_csv('/path/to/file'):
print(row)
or
list(load_csv('/path/to/file'))
:param path: file path
:param delimiter: CSV delimiter
:return: a generator where __next__ is a row of the CSV
"""
try:
with open(path, 'rb') as csvfile:
reader = DictReader(csvfile, delimiter=delimiter)
for row in reader:
yield row
except (OSError, IOError):
raise ClientException("File not found: {}".format(path)) | [
"def",
"load_csv",
"(",
"path",
",",
"delimiter",
"=",
"','",
")",
":",
"try",
":",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"csvfile",
":",
"reader",
"=",
"DictReader",
"(",
"csvfile",
",",
"delimiter",
"=",
"delimiter",
")",
"for",
"row... | Load CSV file from path and yield CSV rows
Usage:
for row in load_csv('/path/to/file'):
print(row)
or
list(load_csv('/path/to/file'))
:param path: file path
:param delimiter: CSV delimiter
:return: a generator where __next__ is a row of the CSV | [
"Load",
"CSV",
"file",
"from",
"path",
"and",
"yield",
"CSV",
"rows"
] | 78cbf1985506db21acdfa0f2e624bc397e455c82 | https://github.com/davidhuser/dhis2.py/blob/78cbf1985506db21acdfa0f2e624bc397e455c82/dhis2/utils.py#L25-L46 | train | 53,803 |
davidhuser/dhis2.py | dhis2/utils.py | partition_payload | def partition_payload(data, key, thresh):
"""
Yield partitions of a payload
e.g. with a threshold of 2:
{ "dataElements": [1, 2, 3] }
-->
{ "dataElements": [1, 2] }
and
{ "dataElements": [3] }
:param data: the payload
:param key: the key of the dict to partition
:param thresh: the maximum value of a chunk
:return: a generator where __next__ is a partition of the payload
"""
data = data[key]
for i in range(0, len(data), thresh):
yield {key: data[i:i + thresh]} | python | def partition_payload(data, key, thresh):
"""
Yield partitions of a payload
e.g. with a threshold of 2:
{ "dataElements": [1, 2, 3] }
-->
{ "dataElements": [1, 2] }
and
{ "dataElements": [3] }
:param data: the payload
:param key: the key of the dict to partition
:param thresh: the maximum value of a chunk
:return: a generator where __next__ is a partition of the payload
"""
data = data[key]
for i in range(0, len(data), thresh):
yield {key: data[i:i + thresh]} | [
"def",
"partition_payload",
"(",
"data",
",",
"key",
",",
"thresh",
")",
":",
"data",
"=",
"data",
"[",
"key",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"data",
")",
",",
"thresh",
")",
":",
"yield",
"{",
"key",
":",
"data",
"[... | Yield partitions of a payload
e.g. with a threshold of 2:
{ "dataElements": [1, 2, 3] }
-->
{ "dataElements": [1, 2] }
and
{ "dataElements": [3] }
:param data: the payload
:param key: the key of the dict to partition
:param thresh: the maximum value of a chunk
:return: a generator where __next__ is a partition of the payload | [
"Yield",
"partitions",
"of",
"a",
"payload"
] | 78cbf1985506db21acdfa0f2e624bc397e455c82 | https://github.com/davidhuser/dhis2.py/blob/78cbf1985506db21acdfa0f2e624bc397e455c82/dhis2/utils.py#L62-L81 | train | 53,804 |
BlueBrain/hpcbench | hpcbench/driver/benchmark.py | BenchmarkCategoryDriver.commands | def commands(self):
"""Get all commands of the benchmark category
:return generator of string
"""
for child in self._children:
with open(osp.join(child, YAML_REPORT_FILE)) as istr:
command = yaml.safe_load(istr)['command']
yield ' '.join(map(six.moves.shlex_quote, command)) | python | def commands(self):
"""Get all commands of the benchmark category
:return generator of string
"""
for child in self._children:
with open(osp.join(child, YAML_REPORT_FILE)) as istr:
command = yaml.safe_load(istr)['command']
yield ' '.join(map(six.moves.shlex_quote, command)) | [
"def",
"commands",
"(",
"self",
")",
":",
"for",
"child",
"in",
"self",
".",
"_children",
":",
"with",
"open",
"(",
"osp",
".",
"join",
"(",
"child",
",",
"YAML_REPORT_FILE",
")",
")",
"as",
"istr",
":",
"command",
"=",
"yaml",
".",
"safe_load",
"(",... | Get all commands of the benchmark category
:return generator of string | [
"Get",
"all",
"commands",
"of",
"the",
"benchmark",
"category"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/benchmark.py#L101-L109 | train | 53,805 |
BlueBrain/hpcbench | hpcbench/driver/benchmark.py | BenchmarkCategoryDriver._module_env | def _module_env(self, execution):
"""Set current process environment according
to execution `environment` and `modules`
"""
env = copy.copy(os.environ)
try:
for mod in execution.get('modules') or []:
Module.load(mod)
os.environ.update(execution.get('environment') or {})
yield
finally:
os.environ = env | python | def _module_env(self, execution):
"""Set current process environment according
to execution `environment` and `modules`
"""
env = copy.copy(os.environ)
try:
for mod in execution.get('modules') or []:
Module.load(mod)
os.environ.update(execution.get('environment') or {})
yield
finally:
os.environ = env | [
"def",
"_module_env",
"(",
"self",
",",
"execution",
")",
":",
"env",
"=",
"copy",
".",
"copy",
"(",
"os",
".",
"environ",
")",
"try",
":",
"for",
"mod",
"in",
"execution",
".",
"get",
"(",
"'modules'",
")",
"or",
"[",
"]",
":",
"Module",
".",
"l... | Set current process environment according
to execution `environment` and `modules` | [
"Set",
"current",
"process",
"environment",
"according",
"to",
"execution",
"environment",
"and",
"modules"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/benchmark.py#L245-L256 | train | 53,806 |
BlueBrain/hpcbench | hpcbench/driver/benchmark.py | BenchmarkCategoryDriver.gather_metrics | def gather_metrics(self, runs):
"""Write a JSON file with the result of every runs
"""
for run_dirs in runs.values():
with open(JSON_METRICS_FILE, 'w') as ostr:
ostr.write('[\n')
for i in range(len(run_dirs)):
with open(osp.join(run_dirs[i], YAML_REPORT_FILE)) as istr:
data = yaml.safe_load(istr)
data.pop('category', None)
data.pop('command', None)
data['id'] = run_dirs[i]
json.dump(data, ostr, indent=2)
if i != len(run_dirs) - 1:
ostr.write(',')
ostr.write('\n')
ostr.write(']\n') | python | def gather_metrics(self, runs):
"""Write a JSON file with the result of every runs
"""
for run_dirs in runs.values():
with open(JSON_METRICS_FILE, 'w') as ostr:
ostr.write('[\n')
for i in range(len(run_dirs)):
with open(osp.join(run_dirs[i], YAML_REPORT_FILE)) as istr:
data = yaml.safe_load(istr)
data.pop('category', None)
data.pop('command', None)
data['id'] = run_dirs[i]
json.dump(data, ostr, indent=2)
if i != len(run_dirs) - 1:
ostr.write(',')
ostr.write('\n')
ostr.write(']\n') | [
"def",
"gather_metrics",
"(",
"self",
",",
"runs",
")",
":",
"for",
"run_dirs",
"in",
"runs",
".",
"values",
"(",
")",
":",
"with",
"open",
"(",
"JSON_METRICS_FILE",
",",
"'w'",
")",
"as",
"ostr",
":",
"ostr",
".",
"write",
"(",
"'[\\n'",
")",
"for",... | Write a JSON file with the result of every runs | [
"Write",
"a",
"JSON",
"file",
"with",
"the",
"result",
"of",
"every",
"runs"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/benchmark.py#L295-L311 | train | 53,807 |
BlueBrain/hpcbench | hpcbench/driver/benchmark.py | MetricsDriver._check_metrics | def _check_metrics(cls, schema, metrics):
"""Ensure that returned metrics are properly exposed
"""
for name, value in metrics.items():
metric = schema.get(name)
if not metric:
message = "Unexpected metric '{}' returned".format(name)
raise Exception(message)
cls._check_metric(schema, metric, name, value) | python | def _check_metrics(cls, schema, metrics):
"""Ensure that returned metrics are properly exposed
"""
for name, value in metrics.items():
metric = schema.get(name)
if not metric:
message = "Unexpected metric '{}' returned".format(name)
raise Exception(message)
cls._check_metric(schema, metric, name, value) | [
"def",
"_check_metrics",
"(",
"cls",
",",
"schema",
",",
"metrics",
")",
":",
"for",
"name",
",",
"value",
"in",
"metrics",
".",
"items",
"(",
")",
":",
"metric",
"=",
"schema",
".",
"get",
"(",
"name",
")",
"if",
"not",
"metric",
":",
"message",
"... | Ensure that returned metrics are properly exposed | [
"Ensure",
"that",
"returned",
"metrics",
"are",
"properly",
"exposed"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/benchmark.py#L400-L408 | train | 53,808 |
eng-tools/sfsimodels | sfsimodels/loader.py | load_frame_building_sample_data | def load_frame_building_sample_data():
"""
Sample data for the BuildingFrame object
:return:
"""
number_of_storeys = 6
interstorey_height = 3.4 # m
masses = 40.0e3 # kg
n_bays = 3
fb = models.BuildingFrame(number_of_storeys, n_bays)
fb.interstorey_heights = interstorey_height * np.ones(number_of_storeys)
fb.floor_length = 18.0 # m
fb.floor_width = 16.0 # m
fb.storey_masses = masses * np.ones(number_of_storeys) # kg
fb.bay_lengths = [6., 6.0, 6.0]
fb.set_beam_prop("depth", [0.5, 0.5, 0.5], repeat="up")
fb.set_beam_prop("width", [0.4, 0.4, 0.4], repeat="up")
fb.set_column_prop("width", [0.5, 0.5, 0.5, 0.5], repeat="up")
fb.set_column_prop("depth", [0.5, 0.5, 0.5, 0.5], repeat="up")
fb.n_seismic_frames = 3
fb.n_gravity_frames = 0
return fb | python | def load_frame_building_sample_data():
"""
Sample data for the BuildingFrame object
:return:
"""
number_of_storeys = 6
interstorey_height = 3.4 # m
masses = 40.0e3 # kg
n_bays = 3
fb = models.BuildingFrame(number_of_storeys, n_bays)
fb.interstorey_heights = interstorey_height * np.ones(number_of_storeys)
fb.floor_length = 18.0 # m
fb.floor_width = 16.0 # m
fb.storey_masses = masses * np.ones(number_of_storeys) # kg
fb.bay_lengths = [6., 6.0, 6.0]
fb.set_beam_prop("depth", [0.5, 0.5, 0.5], repeat="up")
fb.set_beam_prop("width", [0.4, 0.4, 0.4], repeat="up")
fb.set_column_prop("width", [0.5, 0.5, 0.5, 0.5], repeat="up")
fb.set_column_prop("depth", [0.5, 0.5, 0.5, 0.5], repeat="up")
fb.n_seismic_frames = 3
fb.n_gravity_frames = 0
return fb | [
"def",
"load_frame_building_sample_data",
"(",
")",
":",
"number_of_storeys",
"=",
"6",
"interstorey_height",
"=",
"3.4",
"# m",
"masses",
"=",
"40.0e3",
"# kg",
"n_bays",
"=",
"3",
"fb",
"=",
"models",
".",
"BuildingFrame",
"(",
"number_of_storeys",
",",
"n_bay... | Sample data for the BuildingFrame object
:return: | [
"Sample",
"data",
"for",
"the",
"BuildingFrame",
"object"
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/loader.py#L114-L138 | train | 53,809 |
portfoliome/foil | foil/patterns.py | match_subgroup | def match_subgroup(sequence, pattern):
"""Yield the sub-group element dictionary that match a regex pattern."""
for element in sequence:
match = re.match(pattern, element)
if match:
yield match.groupdict() | python | def match_subgroup(sequence, pattern):
"""Yield the sub-group element dictionary that match a regex pattern."""
for element in sequence:
match = re.match(pattern, element)
if match:
yield match.groupdict() | [
"def",
"match_subgroup",
"(",
"sequence",
",",
"pattern",
")",
":",
"for",
"element",
"in",
"sequence",
":",
"match",
"=",
"re",
".",
"match",
"(",
"pattern",
",",
"element",
")",
"if",
"match",
":",
"yield",
"match",
".",
"groupdict",
"(",
")"
] | Yield the sub-group element dictionary that match a regex pattern. | [
"Yield",
"the",
"sub",
"-",
"group",
"element",
"dictionary",
"that",
"match",
"a",
"regex",
"pattern",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/patterns.py#L10-L17 | train | 53,810 |
portfoliome/foil | foil/patterns.py | add_regex_start_end | def add_regex_start_end(pattern_function):
"""Decorator for adding regex pattern start and end characters."""
@wraps(pattern_function)
def func_wrapper(*args, **kwargs):
return r'^{}$'.format(pattern_function(*args, **kwargs))
return func_wrapper | python | def add_regex_start_end(pattern_function):
"""Decorator for adding regex pattern start and end characters."""
@wraps(pattern_function)
def func_wrapper(*args, **kwargs):
return r'^{}$'.format(pattern_function(*args, **kwargs))
return func_wrapper | [
"def",
"add_regex_start_end",
"(",
"pattern_function",
")",
":",
"@",
"wraps",
"(",
"pattern_function",
")",
"def",
"func_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"r'^{}$'",
".",
"format",
"(",
"pattern_function",
"(",
"*",
... | Decorator for adding regex pattern start and end characters. | [
"Decorator",
"for",
"adding",
"regex",
"pattern",
"start",
"and",
"end",
"characters",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/patterns.py#L24-L30 | train | 53,811 |
eng-tools/sfsimodels | sfsimodels/functions.py | convert_stress_to_mass | def convert_stress_to_mass(q, width, length, gravity):
"""
Converts a foundation stress to an equivalent mass.
:param q: applied stress [Pa]
:param width: foundation width [m]
:param length: foundation length [m]
:param gravity: applied gravitational acceleration [m/s2]
:return:
"""
mass = q * width * length / gravity
return mass | python | def convert_stress_to_mass(q, width, length, gravity):
"""
Converts a foundation stress to an equivalent mass.
:param q: applied stress [Pa]
:param width: foundation width [m]
:param length: foundation length [m]
:param gravity: applied gravitational acceleration [m/s2]
:return:
"""
mass = q * width * length / gravity
return mass | [
"def",
"convert_stress_to_mass",
"(",
"q",
",",
"width",
",",
"length",
",",
"gravity",
")",
":",
"mass",
"=",
"q",
"*",
"width",
"*",
"length",
"/",
"gravity",
"return",
"mass"
] | Converts a foundation stress to an equivalent mass.
:param q: applied stress [Pa]
:param width: foundation width [m]
:param length: foundation length [m]
:param gravity: applied gravitational acceleration [m/s2]
:return: | [
"Converts",
"a",
"foundation",
"stress",
"to",
"an",
"equivalent",
"mass",
"."
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/functions.py#L4-L15 | train | 53,812 |
eng-tools/sfsimodels | sfsimodels/functions.py | add_to_obj | def add_to_obj(obj, dictionary, objs=None, exceptions=None, verbose=0):
"""
Cycles through a dictionary and adds the key-value pairs to an object.
:param obj:
:param dictionary:
:param exceptions:
:param verbose:
:return:
"""
if exceptions is None:
exceptions = []
for item in dictionary:
if item in exceptions:
continue
if dictionary[item] is not None:
if verbose:
print("process: ", item, dictionary[item])
key, value = get_key_value(dictionary[item], objs, key=item)
if verbose:
print("assign: ", key, value)
try:
setattr(obj, key, value)
except AttributeError:
raise AttributeError("Can't set {0}={1} on object: {2}".format(key, value, obj)) | python | def add_to_obj(obj, dictionary, objs=None, exceptions=None, verbose=0):
"""
Cycles through a dictionary and adds the key-value pairs to an object.
:param obj:
:param dictionary:
:param exceptions:
:param verbose:
:return:
"""
if exceptions is None:
exceptions = []
for item in dictionary:
if item in exceptions:
continue
if dictionary[item] is not None:
if verbose:
print("process: ", item, dictionary[item])
key, value = get_key_value(dictionary[item], objs, key=item)
if verbose:
print("assign: ", key, value)
try:
setattr(obj, key, value)
except AttributeError:
raise AttributeError("Can't set {0}={1} on object: {2}".format(key, value, obj)) | [
"def",
"add_to_obj",
"(",
"obj",
",",
"dictionary",
",",
"objs",
"=",
"None",
",",
"exceptions",
"=",
"None",
",",
"verbose",
"=",
"0",
")",
":",
"if",
"exceptions",
"is",
"None",
":",
"exceptions",
"=",
"[",
"]",
"for",
"item",
"in",
"dictionary",
"... | Cycles through a dictionary and adds the key-value pairs to an object.
:param obj:
:param dictionary:
:param exceptions:
:param verbose:
:return: | [
"Cycles",
"through",
"a",
"dictionary",
"and",
"adds",
"the",
"key",
"-",
"value",
"pairs",
"to",
"an",
"object",
"."
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/functions.py#L76-L100 | train | 53,813 |
portfoliome/foil | foil/compose.py | create_quantiles | def create_quantiles(items: Sequence, lower_bound, upper_bound):
"""Create quantile start and end boundaries."""
interval = (upper_bound - lower_bound) / len(items)
quantiles = ((g, (x - interval, x)) for g, x in
zip(items, accumulate(repeat(interval, len(items)))))
return quantiles | python | def create_quantiles(items: Sequence, lower_bound, upper_bound):
"""Create quantile start and end boundaries."""
interval = (upper_bound - lower_bound) / len(items)
quantiles = ((g, (x - interval, x)) for g, x in
zip(items, accumulate(repeat(interval, len(items)))))
return quantiles | [
"def",
"create_quantiles",
"(",
"items",
":",
"Sequence",
",",
"lower_bound",
",",
"upper_bound",
")",
":",
"interval",
"=",
"(",
"upper_bound",
"-",
"lower_bound",
")",
"/",
"len",
"(",
"items",
")",
"quantiles",
"=",
"(",
"(",
"g",
",",
"(",
"x",
"-"... | Create quantile start and end boundaries. | [
"Create",
"quantile",
"start",
"and",
"end",
"boundaries",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/compose.py#L5-L13 | train | 53,814 |
portfoliome/foil | foil/compose.py | tupleize | def tupleize(element, ignore_types=(str, bytes)):
"""Cast a single element to a tuple."""
if hasattr(element, '__iter__') and not isinstance(element, ignore_types):
return element
else:
return tuple((element,)) | python | def tupleize(element, ignore_types=(str, bytes)):
"""Cast a single element to a tuple."""
if hasattr(element, '__iter__') and not isinstance(element, ignore_types):
return element
else:
return tuple((element,)) | [
"def",
"tupleize",
"(",
"element",
",",
"ignore_types",
"=",
"(",
"str",
",",
"bytes",
")",
")",
":",
"if",
"hasattr",
"(",
"element",
",",
"'__iter__'",
")",
"and",
"not",
"isinstance",
"(",
"element",
",",
"ignore_types",
")",
":",
"return",
"element",... | Cast a single element to a tuple. | [
"Cast",
"a",
"single",
"element",
"to",
"a",
"tuple",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/compose.py#L16-L21 | train | 53,815 |
portfoliome/foil | foil/compose.py | dictionize | def dictionize(fields: Sequence, records: Sequence) -> Generator:
"""Create dictionaries mapping fields to record data."""
return (dict(zip(fields, rec)) for rec in records) | python | def dictionize(fields: Sequence, records: Sequence) -> Generator:
"""Create dictionaries mapping fields to record data."""
return (dict(zip(fields, rec)) for rec in records) | [
"def",
"dictionize",
"(",
"fields",
":",
"Sequence",
",",
"records",
":",
"Sequence",
")",
"->",
"Generator",
":",
"return",
"(",
"dict",
"(",
"zip",
"(",
"fields",
",",
"rec",
")",
")",
"for",
"rec",
"in",
"records",
")"
] | Create dictionaries mapping fields to record data. | [
"Create",
"dictionaries",
"mapping",
"fields",
"to",
"record",
"data",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/compose.py#L43-L46 | train | 53,816 |
portfoliome/foil | foil/compose.py | flip_iterable_dict | def flip_iterable_dict(d: dict) -> dict:
"""Transform dictionary to unpack values to map to respective key."""
value_keys = disjoint_union((cartesian_product((v, k))
for k, v in d.items()))
return dict(value_keys) | python | def flip_iterable_dict(d: dict) -> dict:
"""Transform dictionary to unpack values to map to respective key."""
value_keys = disjoint_union((cartesian_product((v, k))
for k, v in d.items()))
return dict(value_keys) | [
"def",
"flip_iterable_dict",
"(",
"d",
":",
"dict",
")",
"->",
"dict",
":",
"value_keys",
"=",
"disjoint_union",
"(",
"(",
"cartesian_product",
"(",
"(",
"v",
",",
"k",
")",
")",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
")",
")",
... | Transform dictionary to unpack values to map to respective key. | [
"Transform",
"dictionary",
"to",
"unpack",
"values",
"to",
"map",
"to",
"respective",
"key",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/compose.py#L53-L58 | train | 53,817 |
PolyJIT/benchbuild | benchbuild/extensions/base.py | Extension.call_next | def call_next(self, *args, **kwargs) -> t.List[run.RunInfo]:
"""Call all child extensions with the given arguments.
This calls all child extensions and collects the results for
our own parent. Use this to control the execution of your
nested extensions from your own extension.
Returns:
:obj:`list` of :obj:`RunInfo`: A list of collected
results of our child extensions.
"""
all_results = []
for ext in self.next_extensions:
LOG.debug(" %s ", ext)
results = ext(*args, **kwargs)
LOG.debug(" %s => %s", ext, results)
if results is None:
LOG.warning("No result from: %s", ext)
continue
result_list = []
if isinstance(results, c.Iterable):
result_list.extend(results)
else:
result_list.append(results)
all_results.extend(result_list)
return all_results | python | def call_next(self, *args, **kwargs) -> t.List[run.RunInfo]:
"""Call all child extensions with the given arguments.
This calls all child extensions and collects the results for
our own parent. Use this to control the execution of your
nested extensions from your own extension.
Returns:
:obj:`list` of :obj:`RunInfo`: A list of collected
results of our child extensions.
"""
all_results = []
for ext in self.next_extensions:
LOG.debug(" %s ", ext)
results = ext(*args, **kwargs)
LOG.debug(" %s => %s", ext, results)
if results is None:
LOG.warning("No result from: %s", ext)
continue
result_list = []
if isinstance(results, c.Iterable):
result_list.extend(results)
else:
result_list.append(results)
all_results.extend(result_list)
return all_results | [
"def",
"call_next",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"t",
".",
"List",
"[",
"run",
".",
"RunInfo",
"]",
":",
"all_results",
"=",
"[",
"]",
"for",
"ext",
"in",
"self",
".",
"next_extensions",
":",
"LOG",
".",
"deb... | Call all child extensions with the given arguments.
This calls all child extensions and collects the results for
our own parent. Use this to control the execution of your
nested extensions from your own extension.
Returns:
:obj:`list` of :obj:`RunInfo`: A list of collected
results of our child extensions. | [
"Call",
"all",
"child",
"extensions",
"with",
"the",
"given",
"arguments",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/extensions/base.py#L41-L67 | train | 53,818 |
PolyJIT/benchbuild | benchbuild/extensions/base.py | Extension.print | def print(self, indent=0):
"""Print a structural view of the registered extensions."""
LOG.info("%s:: %s", indent * " ", self.__class__)
for ext in self.next_extensions:
ext.print(indent=indent + 2) | python | def print(self, indent=0):
"""Print a structural view of the registered extensions."""
LOG.info("%s:: %s", indent * " ", self.__class__)
for ext in self.next_extensions:
ext.print(indent=indent + 2) | [
"def",
"print",
"(",
"self",
",",
"indent",
"=",
"0",
")",
":",
"LOG",
".",
"info",
"(",
"\"%s:: %s\"",
",",
"indent",
"*",
"\" \"",
",",
"self",
".",
"__class__",
")",
"for",
"ext",
"in",
"self",
".",
"next_extensions",
":",
"ext",
".",
"print",
"... | Print a structural view of the registered extensions. | [
"Print",
"a",
"structural",
"view",
"of",
"the",
"registered",
"extensions",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/extensions/base.py#L73-L77 | train | 53,819 |
PolyJIT/benchbuild | benchbuild/utils/container.py | cached | def cached(func):
"""Memoize a function result."""
ret = None
def call_or_cache(*args, **kwargs):
nonlocal ret
if ret is None:
ret = func(*args, **kwargs)
return ret
return call_or_cache | python | def cached(func):
"""Memoize a function result."""
ret = None
def call_or_cache(*args, **kwargs):
nonlocal ret
if ret is None:
ret = func(*args, **kwargs)
return ret
return call_or_cache | [
"def",
"cached",
"(",
"func",
")",
":",
"ret",
"=",
"None",
"def",
"call_or_cache",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"nonlocal",
"ret",
"if",
"ret",
"is",
"None",
":",
"ret",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kw... | Memoize a function result. | [
"Memoize",
"a",
"function",
"result",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/container.py#L15-L25 | train | 53,820 |
PolyJIT/benchbuild | benchbuild/utils/container.py | is_valid | def is_valid(container, path):
"""
Checks if a container exists and is unpacked.
Args:
path: The location where the container is expected.
Returns:
True if the container is valid, False if the container needs to
unpacked or if the path does not exist yet.
"""
try:
tmp_hash_path = container.filename + ".hash"
with open(tmp_hash_path, 'r') as tmp_file:
tmp_hash = tmp_file.readline()
except IOError:
LOG.info("No .hash-file in the tmp-directory.")
container_hash_path = local.path(path) / "gentoo.tar.bz2.hash"
if container_hash_path.exists():
with open(container_hash_path, 'r') as hash_file:
container_hash = hash_file.readline()
return container_hash == tmp_hash
return False | python | def is_valid(container, path):
"""
Checks if a container exists and is unpacked.
Args:
path: The location where the container is expected.
Returns:
True if the container is valid, False if the container needs to
unpacked or if the path does not exist yet.
"""
try:
tmp_hash_path = container.filename + ".hash"
with open(tmp_hash_path, 'r') as tmp_file:
tmp_hash = tmp_file.readline()
except IOError:
LOG.info("No .hash-file in the tmp-directory.")
container_hash_path = local.path(path) / "gentoo.tar.bz2.hash"
if container_hash_path.exists():
with open(container_hash_path, 'r') as hash_file:
container_hash = hash_file.readline()
return container_hash == tmp_hash
return False | [
"def",
"is_valid",
"(",
"container",
",",
"path",
")",
":",
"try",
":",
"tmp_hash_path",
"=",
"container",
".",
"filename",
"+",
"\".hash\"",
"with",
"open",
"(",
"tmp_hash_path",
",",
"'r'",
")",
"as",
"tmp_file",
":",
"tmp_hash",
"=",
"tmp_file",
".",
... | Checks if a container exists and is unpacked.
Args:
path: The location where the container is expected.
Returns:
True if the container is valid, False if the container needs to
unpacked or if the path does not exist yet. | [
"Checks",
"if",
"a",
"container",
"exists",
"and",
"is",
"unpacked",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/container.py#L111-L134 | train | 53,821 |
PolyJIT/benchbuild | benchbuild/utils/container.py | unpack | def unpack(container, path):
"""
Unpack a container usable by uchroot.
Method that checks if a directory for the container exists,
checks if erlent support is needed and then unpacks the
container accordingly.
Args:
path: The location where the container is, that needs to be unpacked.
"""
from benchbuild.utils.run import run
from benchbuild.utils.uchroot import no_args
path = local.path(path)
c_filename = local.path(container.filename)
name = c_filename.basename
if not path.exists():
path.mkdir()
with local.cwd(path):
Wget(container.remote, name)
uchroot = no_args()
uchroot = uchroot["-E", "-A", "-C", "-r", "/", "-w",
os.path.abspath("."), "--"]
# Check, if we need erlent support for this archive.
has_erlent = bash[
"-c", "tar --list -f './{0}' | grep --silent '.erlent'".format(
name)]
has_erlent = (has_erlent & TF)
untar = local["/bin/tar"]["xf", "./" + name]
if not has_erlent:
untar = uchroot[untar]
run(untar["--exclude=dev/*"])
if not os.path.samefile(name, container.filename):
rm(name)
else:
LOG.warning("File contents do not match: %s != %s", name,
container.filename)
cp(container.filename + ".hash", path) | python | def unpack(container, path):
"""
Unpack a container usable by uchroot.
Method that checks if a directory for the container exists,
checks if erlent support is needed and then unpacks the
container accordingly.
Args:
path: The location where the container is, that needs to be unpacked.
"""
from benchbuild.utils.run import run
from benchbuild.utils.uchroot import no_args
path = local.path(path)
c_filename = local.path(container.filename)
name = c_filename.basename
if not path.exists():
path.mkdir()
with local.cwd(path):
Wget(container.remote, name)
uchroot = no_args()
uchroot = uchroot["-E", "-A", "-C", "-r", "/", "-w",
os.path.abspath("."), "--"]
# Check, if we need erlent support for this archive.
has_erlent = bash[
"-c", "tar --list -f './{0}' | grep --silent '.erlent'".format(
name)]
has_erlent = (has_erlent & TF)
untar = local["/bin/tar"]["xf", "./" + name]
if not has_erlent:
untar = uchroot[untar]
run(untar["--exclude=dev/*"])
if not os.path.samefile(name, container.filename):
rm(name)
else:
LOG.warning("File contents do not match: %s != %s", name,
container.filename)
cp(container.filename + ".hash", path) | [
"def",
"unpack",
"(",
"container",
",",
"path",
")",
":",
"from",
"benchbuild",
".",
"utils",
".",
"run",
"import",
"run",
"from",
"benchbuild",
".",
"utils",
".",
"uchroot",
"import",
"no_args",
"path",
"=",
"local",
".",
"path",
"(",
"path",
")",
"c_... | Unpack a container usable by uchroot.
Method that checks if a directory for the container exists,
checks if erlent support is needed and then unpacks the
container accordingly.
Args:
path: The location where the container is, that needs to be unpacked. | [
"Unpack",
"a",
"container",
"usable",
"by",
"uchroot",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/container.py#L137-L182 | train | 53,822 |
PolyJIT/benchbuild | benchbuild/utils/container.py | Container.local | def local(self):
"""
Finds the current location of a container.
Also unpacks the project if necessary.
Returns:
target: The path, where the container lies in the end.
"""
assert self.name in CFG["container"]["images"].value
tmp_dir = local.path(str(CFG["tmp_dir"]))
target_dir = tmp_dir / self.name
if not target_dir.exists() or not is_valid(self, target_dir):
unpack(self, target_dir)
return target_dir | python | def local(self):
"""
Finds the current location of a container.
Also unpacks the project if necessary.
Returns:
target: The path, where the container lies in the end.
"""
assert self.name in CFG["container"]["images"].value
tmp_dir = local.path(str(CFG["tmp_dir"]))
target_dir = tmp_dir / self.name
if not target_dir.exists() or not is_valid(self, target_dir):
unpack(self, target_dir)
return target_dir | [
"def",
"local",
"(",
"self",
")",
":",
"assert",
"self",
".",
"name",
"in",
"CFG",
"[",
"\"container\"",
"]",
"[",
"\"images\"",
"]",
".",
"value",
"tmp_dir",
"=",
"local",
".",
"path",
"(",
"str",
"(",
"CFG",
"[",
"\"tmp_dir\"",
"]",
")",
")",
"ta... | Finds the current location of a container.
Also unpacks the project if necessary.
Returns:
target: The path, where the container lies in the end. | [
"Finds",
"the",
"current",
"location",
"of",
"a",
"container",
".",
"Also",
"unpacks",
"the",
"project",
"if",
"necessary",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/container.py#L46-L61 | train | 53,823 |
PolyJIT/benchbuild | benchbuild/utils/container.py | Gentoo.src_file | def src_file(self):
"""
Get the latest src_uri for a stage 3 tarball.
Returns (str):
Latest src_uri from gentoo's distfiles mirror.
"""
try:
src_uri = (curl[Gentoo._LATEST_TXT] | tail["-n", "+3"]
| cut["-f1", "-d "])().strip()
except ProcessExecutionError as proc_ex:
src_uri = "NOT-FOUND"
LOG.error("Could not determine latest stage3 src uri: %s",
str(proc_ex))
return src_uri | python | def src_file(self):
"""
Get the latest src_uri for a stage 3 tarball.
Returns (str):
Latest src_uri from gentoo's distfiles mirror.
"""
try:
src_uri = (curl[Gentoo._LATEST_TXT] | tail["-n", "+3"]
| cut["-f1", "-d "])().strip()
except ProcessExecutionError as proc_ex:
src_uri = "NOT-FOUND"
LOG.error("Could not determine latest stage3 src uri: %s",
str(proc_ex))
return src_uri | [
"def",
"src_file",
"(",
"self",
")",
":",
"try",
":",
"src_uri",
"=",
"(",
"curl",
"[",
"Gentoo",
".",
"_LATEST_TXT",
"]",
"|",
"tail",
"[",
"\"-n\"",
",",
"\"+3\"",
"]",
"|",
"cut",
"[",
"\"-f1\"",
",",
"\"-d \"",
"]",
")",
"(",
")",
".",
"strip... | Get the latest src_uri for a stage 3 tarball.
Returns (str):
Latest src_uri from gentoo's distfiles mirror. | [
"Get",
"the",
"latest",
"src_uri",
"for",
"a",
"stage",
"3",
"tarball",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/container.py#L72-L86 | train | 53,824 |
PolyJIT/benchbuild | benchbuild/utils/container.py | Gentoo.version | def version(self):
"""Return the build date of the gentoo container."""
try:
_version = (curl[Gentoo._LATEST_TXT] | \
awk['NR==2{print}'] | \
cut["-f2", "-d="])().strip()
_version = datetime.utcfromtimestamp(int(_version))\
.strftime("%Y-%m-%d")
except ProcessExecutionError as proc_ex:
_version = "unknown"
LOG.error("Could not determine timestamp: %s",
str(proc_ex))
return _version | python | def version(self):
"""Return the build date of the gentoo container."""
try:
_version = (curl[Gentoo._LATEST_TXT] | \
awk['NR==2{print}'] | \
cut["-f2", "-d="])().strip()
_version = datetime.utcfromtimestamp(int(_version))\
.strftime("%Y-%m-%d")
except ProcessExecutionError as proc_ex:
_version = "unknown"
LOG.error("Could not determine timestamp: %s",
str(proc_ex))
return _version | [
"def",
"version",
"(",
"self",
")",
":",
"try",
":",
"_version",
"=",
"(",
"curl",
"[",
"Gentoo",
".",
"_LATEST_TXT",
"]",
"|",
"awk",
"[",
"'NR==2{print}'",
"]",
"|",
"cut",
"[",
"\"-f2\"",
",",
"\"-d=\"",
"]",
")",
"(",
")",
".",
"strip",
"(",
... | Return the build date of the gentoo container. | [
"Return",
"the",
"build",
"date",
"of",
"the",
"gentoo",
"container",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/container.py#L90-L102 | train | 53,825 |
BlueBrain/hpcbench | hpcbench/cli/bencsv.py | main | def main(argv=None):
"""ben-csv entry point"""
arguments = cli_common(__doc__, argv=argv)
csv_export = CSVExporter(arguments['CAMPAIGN-DIR'], arguments['--output'])
if arguments['--peek']:
csv_export.peek()
else:
fieldsstr = arguments.get('--fields')
fields = fieldsstr.split(',') if fieldsstr else None
csv_export.export(fields)
if argv is not None:
return csv_export | python | def main(argv=None):
"""ben-csv entry point"""
arguments = cli_common(__doc__, argv=argv)
csv_export = CSVExporter(arguments['CAMPAIGN-DIR'], arguments['--output'])
if arguments['--peek']:
csv_export.peek()
else:
fieldsstr = arguments.get('--fields')
fields = fieldsstr.split(',') if fieldsstr else None
csv_export.export(fields)
if argv is not None:
return csv_export | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"arguments",
"=",
"cli_common",
"(",
"__doc__",
",",
"argv",
"=",
"argv",
")",
"csv_export",
"=",
"CSVExporter",
"(",
"arguments",
"[",
"'CAMPAIGN-DIR'",
"]",
",",
"arguments",
"[",
"'--output'",
"]",
")... | ben-csv entry point | [
"ben",
"-",
"csv",
"entry",
"point"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/cli/bencsv.py#L24-L35 | train | 53,826 |
eng-tools/sfsimodels | sfsimodels/models/time.py | time_indices | def time_indices(npts, dt, start, end, index):
"""
Determine the new start and end indices of the time series.
:param npts: Number of points in original time series
:param dt: Time step of original time series
:param start: int or float, optional, New start point
:param end: int or float, optional, New end point
:param index: bool, optional, if False then start and end are considered values in time.
:return: tuple, start index, end index
"""
if index is False: # Convert time values into indices
if end != -1:
e_index = int(end / dt) + 1
else:
e_index = end
s_index = int(start / dt)
else:
s_index = start
e_index = end
if e_index > npts:
raise exceptions.ModelWarning("Cut point is greater than time series length")
return s_index, e_index | python | def time_indices(npts, dt, start, end, index):
"""
Determine the new start and end indices of the time series.
:param npts: Number of points in original time series
:param dt: Time step of original time series
:param start: int or float, optional, New start point
:param end: int or float, optional, New end point
:param index: bool, optional, if False then start and end are considered values in time.
:return: tuple, start index, end index
"""
if index is False: # Convert time values into indices
if end != -1:
e_index = int(end / dt) + 1
else:
e_index = end
s_index = int(start / dt)
else:
s_index = start
e_index = end
if e_index > npts:
raise exceptions.ModelWarning("Cut point is greater than time series length")
return s_index, e_index | [
"def",
"time_indices",
"(",
"npts",
",",
"dt",
",",
"start",
",",
"end",
",",
"index",
")",
":",
"if",
"index",
"is",
"False",
":",
"# Convert time values into indices",
"if",
"end",
"!=",
"-",
"1",
":",
"e_index",
"=",
"int",
"(",
"end",
"/",
"dt",
... | Determine the new start and end indices of the time series.
:param npts: Number of points in original time series
:param dt: Time step of original time series
:param start: int or float, optional, New start point
:param end: int or float, optional, New end point
:param index: bool, optional, if False then start and end are considered values in time.
:return: tuple, start index, end index | [
"Determine",
"the",
"new",
"start",
"and",
"end",
"indices",
"of",
"the",
"time",
"series",
"."
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/time.py#L64-L86 | train | 53,827 |
BlueBrain/hpcbench | hpcbench/toolbox/slurm/job.py | Job.finished | def finished(cls, jobid):
"""Check whether a SLURM job is finished or not"""
output = subprocess.check_output(
[SACCT, '-n', '-X', '-o', "end", '-j', str(jobid)]
)
end = output.strip().decode()
return end not in {'Unknown', ''} | python | def finished(cls, jobid):
"""Check whether a SLURM job is finished or not"""
output = subprocess.check_output(
[SACCT, '-n', '-X', '-o', "end", '-j', str(jobid)]
)
end = output.strip().decode()
return end not in {'Unknown', ''} | [
"def",
"finished",
"(",
"cls",
",",
"jobid",
")",
":",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"SACCT",
",",
"'-n'",
",",
"'-X'",
",",
"'-o'",
",",
"\"end\"",
",",
"'-j'",
",",
"str",
"(",
"jobid",
")",
"]",
")",
"end",
"=",
"... | Check whether a SLURM job is finished or not | [
"Check",
"whether",
"a",
"SLURM",
"job",
"is",
"finished",
"or",
"not"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/slurm/job.py#L53-L59 | train | 53,828 |
PolyJIT/benchbuild | benchbuild/utils/run.py | begin_run_group | def begin_run_group(project):
"""
Begin a run_group in the database.
A run_group groups a set of runs for a given project. This models a series
of runs that form a complete binary runtime test.
Args:
project: The project we begin a new run_group for.
Returns:
``(group, session)`` where group is the created group in the
database and session is the database session this group lives in.
"""
from benchbuild.utils.db import create_run_group
from datetime import datetime
group, session = create_run_group(project)
group.begin = datetime.now()
group.status = 'running'
session.commit()
return group, session | python | def begin_run_group(project):
"""
Begin a run_group in the database.
A run_group groups a set of runs for a given project. This models a series
of runs that form a complete binary runtime test.
Args:
project: The project we begin a new run_group for.
Returns:
``(group, session)`` where group is the created group in the
database and session is the database session this group lives in.
"""
from benchbuild.utils.db import create_run_group
from datetime import datetime
group, session = create_run_group(project)
group.begin = datetime.now()
group.status = 'running'
session.commit()
return group, session | [
"def",
"begin_run_group",
"(",
"project",
")",
":",
"from",
"benchbuild",
".",
"utils",
".",
"db",
"import",
"create_run_group",
"from",
"datetime",
"import",
"datetime",
"group",
",",
"session",
"=",
"create_run_group",
"(",
"project",
")",
"group",
".",
"beg... | Begin a run_group in the database.
A run_group groups a set of runs for a given project. This models a series
of runs that form a complete binary runtime test.
Args:
project: The project we begin a new run_group for.
Returns:
``(group, session)`` where group is the created group in the
database and session is the database session this group lives in. | [
"Begin",
"a",
"run_group",
"in",
"the",
"database",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/run.py#L205-L227 | train | 53,829 |
PolyJIT/benchbuild | benchbuild/utils/run.py | end_run_group | def end_run_group(group, session):
"""
End the run_group successfully.
Args:
group: The run_group we want to complete.
session: The database transaction we will finish.
"""
from datetime import datetime
group.end = datetime.now()
group.status = 'completed'
session.commit() | python | def end_run_group(group, session):
"""
End the run_group successfully.
Args:
group: The run_group we want to complete.
session: The database transaction we will finish.
"""
from datetime import datetime
group.end = datetime.now()
group.status = 'completed'
session.commit() | [
"def",
"end_run_group",
"(",
"group",
",",
"session",
")",
":",
"from",
"datetime",
"import",
"datetime",
"group",
".",
"end",
"=",
"datetime",
".",
"now",
"(",
")",
"group",
".",
"status",
"=",
"'completed'",
"session",
".",
"commit",
"(",
")"
] | End the run_group successfully.
Args:
group: The run_group we want to complete.
session: The database transaction we will finish. | [
"End",
"the",
"run_group",
"successfully",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/run.py#L230-L242 | train | 53,830 |
PolyJIT/benchbuild | benchbuild/utils/run.py | fail_run_group | def fail_run_group(group, session):
"""
End the run_group unsuccessfully.
Args:
group: The run_group we want to complete.
session: The database transaction we will finish.
"""
from datetime import datetime
group.end = datetime.now()
group.status = 'failed'
session.commit() | python | def fail_run_group(group, session):
"""
End the run_group unsuccessfully.
Args:
group: The run_group we want to complete.
session: The database transaction we will finish.
"""
from datetime import datetime
group.end = datetime.now()
group.status = 'failed'
session.commit() | [
"def",
"fail_run_group",
"(",
"group",
",",
"session",
")",
":",
"from",
"datetime",
"import",
"datetime",
"group",
".",
"end",
"=",
"datetime",
".",
"now",
"(",
")",
"group",
".",
"status",
"=",
"'failed'",
"session",
".",
"commit",
"(",
")"
] | End the run_group unsuccessfully.
Args:
group: The run_group we want to complete.
session: The database transaction we will finish. | [
"End",
"the",
"run_group",
"unsuccessfully",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/run.py#L245-L257 | train | 53,831 |
PolyJIT/benchbuild | benchbuild/utils/run.py | exit_code_from_run_infos | def exit_code_from_run_infos(run_infos: t.List[RunInfo]) -> int:
"""Generate a single exit code from a list of RunInfo objects.
Takes a list of RunInfos and returns the exit code that is furthest away
from 0.
Args:
run_infos (t.List[RunInfo]): [description]
Returns:
int: [description]
"""
assert run_infos is not None
if not hasattr(run_infos, "__iter__"):
return run_infos.retcode
rcs = [ri.retcode for ri in run_infos]
max_rc = max(rcs)
min_rc = min(rcs)
if max_rc == 0:
return min_rc
return max_rc | python | def exit_code_from_run_infos(run_infos: t.List[RunInfo]) -> int:
"""Generate a single exit code from a list of RunInfo objects.
Takes a list of RunInfos and returns the exit code that is furthest away
from 0.
Args:
run_infos (t.List[RunInfo]): [description]
Returns:
int: [description]
"""
assert run_infos is not None
if not hasattr(run_infos, "__iter__"):
return run_infos.retcode
rcs = [ri.retcode for ri in run_infos]
max_rc = max(rcs)
min_rc = min(rcs)
if max_rc == 0:
return min_rc
return max_rc | [
"def",
"exit_code_from_run_infos",
"(",
"run_infos",
":",
"t",
".",
"List",
"[",
"RunInfo",
"]",
")",
"->",
"int",
":",
"assert",
"run_infos",
"is",
"not",
"None",
"if",
"not",
"hasattr",
"(",
"run_infos",
",",
"\"__iter__\"",
")",
":",
"return",
"run_info... | Generate a single exit code from a list of RunInfo objects.
Takes a list of RunInfos and returns the exit code that is furthest away
from 0.
Args:
run_infos (t.List[RunInfo]): [description]
Returns:
int: [description] | [
"Generate",
"a",
"single",
"exit",
"code",
"from",
"a",
"list",
"of",
"RunInfo",
"objects",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/run.py#L260-L282 | train | 53,832 |
PolyJIT/benchbuild | benchbuild/utils/run.py | track_execution | def track_execution(cmd, project, experiment, **kwargs):
"""Guard the execution of the given command.
The given command (`cmd`) will be executed inside a database context.
As soon as you leave the context we will commit the transaction.
Any necessary modifications to the database can be identified inside
the context with the RunInfo object.
Args:
cmd: The command we guard.
project: The project we track for.
experiment: The experiment we track for.
Yields:
RunInfo: A context object that carries the necessary
database transaction.
"""
runner = RunInfo(cmd=cmd, project=project, experiment=experiment, **kwargs)
yield runner
runner.commit() | python | def track_execution(cmd, project, experiment, **kwargs):
"""Guard the execution of the given command.
The given command (`cmd`) will be executed inside a database context.
As soon as you leave the context we will commit the transaction.
Any necessary modifications to the database can be identified inside
the context with the RunInfo object.
Args:
cmd: The command we guard.
project: The project we track for.
experiment: The experiment we track for.
Yields:
RunInfo: A context object that carries the necessary
database transaction.
"""
runner = RunInfo(cmd=cmd, project=project, experiment=experiment, **kwargs)
yield runner
runner.commit() | [
"def",
"track_execution",
"(",
"cmd",
",",
"project",
",",
"experiment",
",",
"*",
"*",
"kwargs",
")",
":",
"runner",
"=",
"RunInfo",
"(",
"cmd",
"=",
"cmd",
",",
"project",
"=",
"project",
",",
"experiment",
"=",
"experiment",
",",
"*",
"*",
"kwargs",... | Guard the execution of the given command.
The given command (`cmd`) will be executed inside a database context.
As soon as you leave the context we will commit the transaction.
Any necessary modifications to the database can be identified inside
the context with the RunInfo object.
Args:
cmd: The command we guard.
project: The project we track for.
experiment: The experiment we track for.
Yields:
RunInfo: A context object that carries the necessary
database transaction. | [
"Guard",
"the",
"execution",
"of",
"the",
"given",
"command",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/run.py#L286-L306 | train | 53,833 |
PolyJIT/benchbuild | benchbuild/utils/run.py | with_env_recursive | def with_env_recursive(cmd, **envvars):
"""
Recursively updates the environment of cmd and all its subcommands.
Args:
cmd - A plumbum command-like object
**envvars - The environment variables to update
Returns:
The updated command.
"""
from plumbum.commands.base import BoundCommand, BoundEnvCommand
if isinstance(cmd, BoundCommand):
cmd.cmd = with_env_recursive(cmd.cmd, **envvars)
elif isinstance(cmd, BoundEnvCommand):
cmd.envvars.update(envvars)
cmd.cmd = with_env_recursive(cmd.cmd, **envvars)
return cmd | python | def with_env_recursive(cmd, **envvars):
"""
Recursively updates the environment of cmd and all its subcommands.
Args:
cmd - A plumbum command-like object
**envvars - The environment variables to update
Returns:
The updated command.
"""
from plumbum.commands.base import BoundCommand, BoundEnvCommand
if isinstance(cmd, BoundCommand):
cmd.cmd = with_env_recursive(cmd.cmd, **envvars)
elif isinstance(cmd, BoundEnvCommand):
cmd.envvars.update(envvars)
cmd.cmd = with_env_recursive(cmd.cmd, **envvars)
return cmd | [
"def",
"with_env_recursive",
"(",
"cmd",
",",
"*",
"*",
"envvars",
")",
":",
"from",
"plumbum",
".",
"commands",
".",
"base",
"import",
"BoundCommand",
",",
"BoundEnvCommand",
"if",
"isinstance",
"(",
"cmd",
",",
"BoundCommand",
")",
":",
"cmd",
".",
"cmd"... | Recursively updates the environment of cmd and all its subcommands.
Args:
cmd - A plumbum command-like object
**envvars - The environment variables to update
Returns:
The updated command. | [
"Recursively",
"updates",
"the",
"environment",
"of",
"cmd",
"and",
"all",
"its",
"subcommands",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/run.py#L318-L335 | train | 53,834 |
PolyJIT/benchbuild | benchbuild/utils/run.py | in_builddir | def in_builddir(sub='.'):
"""
Decorate a project phase with a local working directory change.
Args:
sub: An optional subdirectory to change into.
"""
from functools import wraps
def wrap_in_builddir(func):
"""Wrap the function for the new build directory."""
@wraps(func)
def wrap_in_builddir_func(self, *args, **kwargs):
"""The actual function inside the wrapper for the new builddir."""
p = local.path(self.builddir) / sub
if not p.exists():
LOG.error("%s does not exist.", p)
if p == local.cwd:
LOG.debug("CWD already is %s", p)
return func(self, *args, *kwargs)
with local.cwd(p):
return func(self, *args, **kwargs)
return wrap_in_builddir_func
return wrap_in_builddir | python | def in_builddir(sub='.'):
"""
Decorate a project phase with a local working directory change.
Args:
sub: An optional subdirectory to change into.
"""
from functools import wraps
def wrap_in_builddir(func):
"""Wrap the function for the new build directory."""
@wraps(func)
def wrap_in_builddir_func(self, *args, **kwargs):
"""The actual function inside the wrapper for the new builddir."""
p = local.path(self.builddir) / sub
if not p.exists():
LOG.error("%s does not exist.", p)
if p == local.cwd:
LOG.debug("CWD already is %s", p)
return func(self, *args, *kwargs)
with local.cwd(p):
return func(self, *args, **kwargs)
return wrap_in_builddir_func
return wrap_in_builddir | [
"def",
"in_builddir",
"(",
"sub",
"=",
"'.'",
")",
":",
"from",
"functools",
"import",
"wraps",
"def",
"wrap_in_builddir",
"(",
"func",
")",
":",
"\"\"\"Wrap the function for the new build directory.\"\"\"",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrap_in_builddir_f... | Decorate a project phase with a local working directory change.
Args:
sub: An optional subdirectory to change into. | [
"Decorate",
"a",
"project",
"phase",
"with",
"a",
"local",
"working",
"directory",
"change",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/run.py#L338-L365 | train | 53,835 |
PolyJIT/benchbuild | benchbuild/utils/run.py | store_config | def store_config(func):
"""Decorator for storing the configuration in the project's builddir."""
from functools import wraps
@wraps(func)
def wrap_store_config(self, *args, **kwargs):
"""Wrapper that contains the actual storage call for the config."""
CFG.store(local.path(self.builddir) / ".benchbuild.yml")
return func(self, *args, **kwargs)
return wrap_store_config | python | def store_config(func):
"""Decorator for storing the configuration in the project's builddir."""
from functools import wraps
@wraps(func)
def wrap_store_config(self, *args, **kwargs):
"""Wrapper that contains the actual storage call for the config."""
CFG.store(local.path(self.builddir) / ".benchbuild.yml")
return func(self, *args, **kwargs)
return wrap_store_config | [
"def",
"store_config",
"(",
"func",
")",
":",
"from",
"functools",
"import",
"wraps",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrap_store_config",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Wrapper that contains the actual storage ... | Decorator for storing the configuration in the project's builddir. | [
"Decorator",
"for",
"storing",
"the",
"configuration",
"in",
"the",
"project",
"s",
"builddir",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/run.py#L368-L378 | train | 53,836 |
PolyJIT/benchbuild | benchbuild/container.py | clean_directories | def clean_directories(builddir, in_dir=True, out_dir=True):
"""Remove the in and out of the container if confirmed by the user."""
container_in = local.path(builddir) / "container-in"
container_out = local.path(builddir) / "container-out"
if in_dir and container_in.exists():
if ui.ask("Should I delete '{0}'?".format(container_in)):
container_in.delete()
if out_dir and container_out.exists():
if ui.ask("Should I delete '{0}'?".format(container_out)):
container_out.delete() | python | def clean_directories(builddir, in_dir=True, out_dir=True):
"""Remove the in and out of the container if confirmed by the user."""
container_in = local.path(builddir) / "container-in"
container_out = local.path(builddir) / "container-out"
if in_dir and container_in.exists():
if ui.ask("Should I delete '{0}'?".format(container_in)):
container_in.delete()
if out_dir and container_out.exists():
if ui.ask("Should I delete '{0}'?".format(container_out)):
container_out.delete() | [
"def",
"clean_directories",
"(",
"builddir",
",",
"in_dir",
"=",
"True",
",",
"out_dir",
"=",
"True",
")",
":",
"container_in",
"=",
"local",
".",
"path",
"(",
"builddir",
")",
"/",
"\"container-in\"",
"container_out",
"=",
"local",
".",
"path",
"(",
"buil... | Remove the in and out of the container if confirmed by the user. | [
"Remove",
"the",
"in",
"and",
"out",
"of",
"the",
"container",
"if",
"confirmed",
"by",
"the",
"user",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/container.py#L23-L33 | train | 53,837 |
PolyJIT/benchbuild | benchbuild/container.py | setup_directories | def setup_directories(builddir):
"""Create the in and out directories of the container."""
build_dir = local.path(builddir)
in_dir = build_dir / "container-in"
out_dir = build_dir / "container-out"
if not in_dir.exists():
in_dir.mkdir()
if not out_dir.exists():
out_dir.mkdir() | python | def setup_directories(builddir):
"""Create the in and out directories of the container."""
build_dir = local.path(builddir)
in_dir = build_dir / "container-in"
out_dir = build_dir / "container-out"
if not in_dir.exists():
in_dir.mkdir()
if not out_dir.exists():
out_dir.mkdir() | [
"def",
"setup_directories",
"(",
"builddir",
")",
":",
"build_dir",
"=",
"local",
".",
"path",
"(",
"builddir",
")",
"in_dir",
"=",
"build_dir",
"/",
"\"container-in\"",
"out_dir",
"=",
"build_dir",
"/",
"\"container-out\"",
"if",
"not",
"in_dir",
".",
"exists... | Create the in and out directories of the container. | [
"Create",
"the",
"in",
"and",
"out",
"directories",
"of",
"the",
"container",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/container.py#L36-L45 | train | 53,838 |
PolyJIT/benchbuild | benchbuild/container.py | setup_container | def setup_container(builddir, _container):
"""Prepare the container and returns the path where it can be found."""
build_dir = local.path(builddir)
in_dir = build_dir / "container-in"
container_path = local.path(_container)
with local.cwd(builddir):
container_bin = container_path.basename
container_in = in_dir / container_bin
download.Copy(_container, container_in)
uchrt = uchroot.no_args()
with local.cwd("container-in"):
uchrt = uchrt["-E", "-A", "-u", "0", "-g", "0", "-C", "-r", "/",
"-w",
os.path.abspath("."), "--"]
# Check, if we need erlent support for this archive.
has_erlent = bash[
"-c", "tar --list -f './{0}' | grep --silent '.erlent'".format(
container_in)]
has_erlent = (has_erlent & TF)
# Unpack input container to: container-in
if not has_erlent:
cmd = local["/bin/tar"]["xf"]
cmd = uchrt[cmd[container_bin]]
else:
cmd = tar["xf"]
cmd = cmd[container_in]
with local.cwd("container-in"):
cmd("--exclude=dev/*")
rm(container_in)
return in_dir | python | def setup_container(builddir, _container):
"""Prepare the container and returns the path where it can be found."""
build_dir = local.path(builddir)
in_dir = build_dir / "container-in"
container_path = local.path(_container)
with local.cwd(builddir):
container_bin = container_path.basename
container_in = in_dir / container_bin
download.Copy(_container, container_in)
uchrt = uchroot.no_args()
with local.cwd("container-in"):
uchrt = uchrt["-E", "-A", "-u", "0", "-g", "0", "-C", "-r", "/",
"-w",
os.path.abspath("."), "--"]
# Check, if we need erlent support for this archive.
has_erlent = bash[
"-c", "tar --list -f './{0}' | grep --silent '.erlent'".format(
container_in)]
has_erlent = (has_erlent & TF)
# Unpack input container to: container-in
if not has_erlent:
cmd = local["/bin/tar"]["xf"]
cmd = uchrt[cmd[container_bin]]
else:
cmd = tar["xf"]
cmd = cmd[container_in]
with local.cwd("container-in"):
cmd("--exclude=dev/*")
rm(container_in)
return in_dir | [
"def",
"setup_container",
"(",
"builddir",
",",
"_container",
")",
":",
"build_dir",
"=",
"local",
".",
"path",
"(",
"builddir",
")",
"in_dir",
"=",
"build_dir",
"/",
"\"container-in\"",
"container_path",
"=",
"local",
".",
"path",
"(",
"_container",
")",
"w... | Prepare the container and returns the path where it can be found. | [
"Prepare",
"the",
"container",
"and",
"returns",
"the",
"path",
"where",
"it",
"can",
"be",
"found",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/container.py#L48-L81 | train | 53,839 |
PolyJIT/benchbuild | benchbuild/container.py | run_in_container | def run_in_container(command, container_dir):
"""
Run a given command inside a container.
Mounts a directory as a container at the given mountpoint and tries to run
the given command inside the new container.
"""
container_p = local.path(container_dir)
with local.cwd(container_p):
uchrt = uchroot.with_mounts()
uchrt = uchrt["-E", "-A", "-u", "0", "-g", "0", "-C", "-w", "/", "-r",
container_p]
uchrt = uchrt["--"]
cmd_path = container_p / command[0].lstrip('/')
if not cmd_path.exists():
LOG.error("The command does not exist inside the container! %s",
cmd_path)
return
cmd = uchrt[command]
return cmd & FG | python | def run_in_container(command, container_dir):
"""
Run a given command inside a container.
Mounts a directory as a container at the given mountpoint and tries to run
the given command inside the new container.
"""
container_p = local.path(container_dir)
with local.cwd(container_p):
uchrt = uchroot.with_mounts()
uchrt = uchrt["-E", "-A", "-u", "0", "-g", "0", "-C", "-w", "/", "-r",
container_p]
uchrt = uchrt["--"]
cmd_path = container_p / command[0].lstrip('/')
if not cmd_path.exists():
LOG.error("The command does not exist inside the container! %s",
cmd_path)
return
cmd = uchrt[command]
return cmd & FG | [
"def",
"run_in_container",
"(",
"command",
",",
"container_dir",
")",
":",
"container_p",
"=",
"local",
".",
"path",
"(",
"container_dir",
")",
"with",
"local",
".",
"cwd",
"(",
"container_p",
")",
":",
"uchrt",
"=",
"uchroot",
".",
"with_mounts",
"(",
")"... | Run a given command inside a container.
Mounts a directory as a container at the given mountpoint and tries to run
the given command inside the new container. | [
"Run",
"a",
"given",
"command",
"inside",
"a",
"container",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/container.py#L84-L105 | train | 53,840 |
PolyJIT/benchbuild | benchbuild/container.py | pack_container | def pack_container(in_container, out_file):
"""
Pack a container image into a .tar.bz2 archive.
Args:
in_container (str): Path string to the container image.
out_file (str): Output file name.
"""
container_filename = local.path(out_file).basename
out_container = local.cwd / "container-out" / container_filename
out_dir = out_container.dirname
# Pack the results to: container-out
with local.cwd(in_container):
tar("cjf", out_container, ".")
c_hash = download.update_hash(out_container)
if out_dir.exists():
mkdir("-p", out_dir)
mv(out_container, out_file)
mv(out_container + ".hash", out_file + ".hash")
new_container = {"path": out_file, "hash": str(c_hash)}
CFG["container"]["known"] += new_container | python | def pack_container(in_container, out_file):
"""
Pack a container image into a .tar.bz2 archive.
Args:
in_container (str): Path string to the container image.
out_file (str): Output file name.
"""
container_filename = local.path(out_file).basename
out_container = local.cwd / "container-out" / container_filename
out_dir = out_container.dirname
# Pack the results to: container-out
with local.cwd(in_container):
tar("cjf", out_container, ".")
c_hash = download.update_hash(out_container)
if out_dir.exists():
mkdir("-p", out_dir)
mv(out_container, out_file)
mv(out_container + ".hash", out_file + ".hash")
new_container = {"path": out_file, "hash": str(c_hash)}
CFG["container"]["known"] += new_container | [
"def",
"pack_container",
"(",
"in_container",
",",
"out_file",
")",
":",
"container_filename",
"=",
"local",
".",
"path",
"(",
"out_file",
")",
".",
"basename",
"out_container",
"=",
"local",
".",
"cwd",
"/",
"\"container-out\"",
"/",
"container_filename",
"out_... | Pack a container image into a .tar.bz2 archive.
Args:
in_container (str): Path string to the container image.
out_file (str): Output file name. | [
"Pack",
"a",
"container",
"image",
"into",
"a",
".",
"tar",
".",
"bz2",
"archive",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/container.py#L108-L130 | train | 53,841 |
PolyJIT/benchbuild | benchbuild/container.py | setup_bash_in_container | def setup_bash_in_container(builddir, _container, outfile, shell):
"""
Setup a bash environment inside a container.
Creates a new chroot, which the user can use as a bash to run the wanted
projects inside the mounted container, that also gets returned afterwards.
"""
with local.cwd(builddir):
# Switch to bash inside uchroot
print("Entering bash inside User-Chroot. Prepare your image and "
"type 'exit' when you are done. If bash exits with a non-zero"
"exit code, no new container will be stored.")
store_new_container = True
try:
run_in_container(shell, _container)
except ProcessExecutionError:
store_new_container = False
if store_new_container:
print("Packing new container image.")
pack_container(_container, outfile)
config_path = str(CFG["config_file"])
CFG.store(config_path)
print("Storing config in {0}".format(os.path.abspath(config_path))) | python | def setup_bash_in_container(builddir, _container, outfile, shell):
"""
Setup a bash environment inside a container.
Creates a new chroot, which the user can use as a bash to run the wanted
projects inside the mounted container, that also gets returned afterwards.
"""
with local.cwd(builddir):
# Switch to bash inside uchroot
print("Entering bash inside User-Chroot. Prepare your image and "
"type 'exit' when you are done. If bash exits with a non-zero"
"exit code, no new container will be stored.")
store_new_container = True
try:
run_in_container(shell, _container)
except ProcessExecutionError:
store_new_container = False
if store_new_container:
print("Packing new container image.")
pack_container(_container, outfile)
config_path = str(CFG["config_file"])
CFG.store(config_path)
print("Storing config in {0}".format(os.path.abspath(config_path))) | [
"def",
"setup_bash_in_container",
"(",
"builddir",
",",
"_container",
",",
"outfile",
",",
"shell",
")",
":",
"with",
"local",
".",
"cwd",
"(",
"builddir",
")",
":",
"# Switch to bash inside uchroot",
"print",
"(",
"\"Entering bash inside User-Chroot. Prepare your image... | Setup a bash environment inside a container.
Creates a new chroot, which the user can use as a bash to run the wanted
projects inside the mounted container, that also gets returned afterwards. | [
"Setup",
"a",
"bash",
"environment",
"inside",
"a",
"container",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/container.py#L133-L156 | train | 53,842 |
PolyJIT/benchbuild | benchbuild/container.py | set_input_container | def set_input_container(_container, cfg):
"""Save the input for the container in the configurations."""
if not _container:
return False
if _container.exists():
cfg["container"]["input"] = str(_container)
return True
return False | python | def set_input_container(_container, cfg):
"""Save the input for the container in the configurations."""
if not _container:
return False
if _container.exists():
cfg["container"]["input"] = str(_container)
return True
return False | [
"def",
"set_input_container",
"(",
"_container",
",",
"cfg",
")",
":",
"if",
"not",
"_container",
":",
"return",
"False",
"if",
"_container",
".",
"exists",
"(",
")",
":",
"cfg",
"[",
"\"container\"",
"]",
"[",
"\"input\"",
"]",
"=",
"str",
"(",
"_contai... | Save the input for the container in the configurations. | [
"Save",
"the",
"input",
"for",
"the",
"container",
"in",
"the",
"configurations",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/container.py#L167-L174 | train | 53,843 |
PolyJIT/benchbuild | benchbuild/container.py | SetupPolyJITGentooStrategy.run | def run(self, context):
"""Setup a gentoo container suitable for PolyJIT."""
# Don't do something when running non-interactive.
if not sys.stdout.isatty():
return
with local.cwd(context.in_container):
from benchbuild.projects.gentoo import gentoo
gentoo.setup_networking()
gentoo.configure_portage()
sed_in_chroot = uchroot.uchroot()["/bin/sed"]
emerge_in_chroot = uchroot.uchroot()["/usr/bin/emerge"]
has_pkg = uchroot.uchroot()["/usr/bin/qlist", "-I"]
run.run(sed_in_chroot["-i", '/CC=/d', "/etc/portage/make.conf"])
run.run(sed_in_chroot["-i", '/CXX=/d', "/etc/portage/make.conf"])
want_sync = bool(CFG["container"]["strategy"]["polyjit"]["sync"])
want_upgrade = bool(
CFG["container"]["strategy"]["polyjit"]["upgrade"])
packages = \
CFG["container"]["strategy"]["polyjit"]["packages"].value
with local.env(MAKEOPTS="-j{0}".format(int(CFG["jobs"]))):
if want_sync:
LOG.debug("Synchronizing portage.")
run.run(emerge_in_chroot["--sync"])
if want_upgrade:
LOG.debug("Upgrading world.")
run.run(emerge_in_chroot["--autounmask-only=y", "-uUDN",
"--with-bdeps=y", "@world"])
for pkg in packages:
if has_pkg[pkg["name"]] & TF:
continue
env = pkg["env"]
with local.env(**env):
run.run(emerge_in_chroot[pkg["name"]])
gentoo.setup_benchbuild()
print("Packing new container image.")
with local.cwd(context.builddir):
pack_container(context.in_container, context.out_container) | python | def run(self, context):
"""Setup a gentoo container suitable for PolyJIT."""
# Don't do something when running non-interactive.
if not sys.stdout.isatty():
return
with local.cwd(context.in_container):
from benchbuild.projects.gentoo import gentoo
gentoo.setup_networking()
gentoo.configure_portage()
sed_in_chroot = uchroot.uchroot()["/bin/sed"]
emerge_in_chroot = uchroot.uchroot()["/usr/bin/emerge"]
has_pkg = uchroot.uchroot()["/usr/bin/qlist", "-I"]
run.run(sed_in_chroot["-i", '/CC=/d', "/etc/portage/make.conf"])
run.run(sed_in_chroot["-i", '/CXX=/d', "/etc/portage/make.conf"])
want_sync = bool(CFG["container"]["strategy"]["polyjit"]["sync"])
want_upgrade = bool(
CFG["container"]["strategy"]["polyjit"]["upgrade"])
packages = \
CFG["container"]["strategy"]["polyjit"]["packages"].value
with local.env(MAKEOPTS="-j{0}".format(int(CFG["jobs"]))):
if want_sync:
LOG.debug("Synchronizing portage.")
run.run(emerge_in_chroot["--sync"])
if want_upgrade:
LOG.debug("Upgrading world.")
run.run(emerge_in_chroot["--autounmask-only=y", "-uUDN",
"--with-bdeps=y", "@world"])
for pkg in packages:
if has_pkg[pkg["name"]] & TF:
continue
env = pkg["env"]
with local.env(**env):
run.run(emerge_in_chroot[pkg["name"]])
gentoo.setup_benchbuild()
print("Packing new container image.")
with local.cwd(context.builddir):
pack_container(context.in_container, context.out_container) | [
"def",
"run",
"(",
"self",
",",
"context",
")",
":",
"# Don't do something when running non-interactive.",
"if",
"not",
"sys",
".",
"stdout",
".",
"isatty",
"(",
")",
":",
"return",
"with",
"local",
".",
"cwd",
"(",
"context",
".",
"in_container",
")",
":",
... | Setup a gentoo container suitable for PolyJIT. | [
"Setup",
"a",
"gentoo",
"container",
"suitable",
"for",
"PolyJIT",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/container.py#L213-L256 | train | 53,844 |
PolyJIT/benchbuild | benchbuild/container.py | Container.input_file | def input_file(self, _container):
"""Find the input path of a uchroot container."""
p = local.path(_container)
if set_input_container(p, CFG):
return
p = find_hash(CFG["container"]["known"].value, container)
if set_input_container(p, CFG):
return
raise ValueError("The path '{0}' does not exist.".format(p)) | python | def input_file(self, _container):
"""Find the input path of a uchroot container."""
p = local.path(_container)
if set_input_container(p, CFG):
return
p = find_hash(CFG["container"]["known"].value, container)
if set_input_container(p, CFG):
return
raise ValueError("The path '{0}' does not exist.".format(p)) | [
"def",
"input_file",
"(",
"self",
",",
"_container",
")",
":",
"p",
"=",
"local",
".",
"path",
"(",
"_container",
")",
"if",
"set_input_container",
"(",
"p",
",",
"CFG",
")",
":",
"return",
"p",
"=",
"find_hash",
"(",
"CFG",
"[",
"\"container\"",
"]",
... | Find the input path of a uchroot container. | [
"Find",
"the",
"input",
"path",
"of",
"a",
"uchroot",
"container",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/container.py#L265-L275 | train | 53,845 |
PolyJIT/benchbuild | benchbuild/container.py | Container.output_file | def output_file(self, _container):
"""Find and writes the output path of a chroot container."""
p = local.path(_container)
if p.exists():
if not ui.ask("Path '{0}' already exists."
" Overwrite?".format(p)):
sys.exit(0)
CFG["container"]["output"] = str(p) | python | def output_file(self, _container):
"""Find and writes the output path of a chroot container."""
p = local.path(_container)
if p.exists():
if not ui.ask("Path '{0}' already exists."
" Overwrite?".format(p)):
sys.exit(0)
CFG["container"]["output"] = str(p) | [
"def",
"output_file",
"(",
"self",
",",
"_container",
")",
":",
"p",
"=",
"local",
".",
"path",
"(",
"_container",
")",
"if",
"p",
".",
"exists",
"(",
")",
":",
"if",
"not",
"ui",
".",
"ask",
"(",
"\"Path '{0}' already exists.\"",
"\" Overwrite?\"",
".",... | Find and writes the output path of a chroot container. | [
"Find",
"and",
"writes",
"the",
"output",
"path",
"of",
"a",
"chroot",
"container",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/container.py#L278-L285 | train | 53,846 |
eng-tools/sfsimodels | sfsimodels/models/soils.py | discretize_soil_profile | def discretize_soil_profile(sp, incs=None, target=1.0):
"""
Splits the soil profile into slices and stores as dictionary
:param sp: SoilProfile
:param incs: array_like, increments of depth to use for each layer
:param target: target depth increment size
:return: dict
"""
if incs is None:
incs = np.ones(sp.n_layers) * target
dd = {}
dd["thickness"] = []
dd["unit_mass"] = []
dd["shear_vel"] = []
cum_thickness = 0
for i in range(sp.n_layers):
sl = sp.layer(i + 1)
thickness = sp.layer_height(i + 1)
n_slices = max(int(thickness / incs[i]), 1)
slice_thickness = float(thickness) / n_slices
for j in range(n_slices):
cum_thickness += slice_thickness
if cum_thickness >= sp.gwl:
rho = sl.unit_sat_mass
saturation = True
else:
rho = sl.unit_dry_mass
saturation = False
if hasattr(sl, "get_shear_vel_at_v_eff_stress"):
v_eff = sp.vertical_effective_stress(cum_thickness)
vs = sl.get_shear_vel_at_v_eff_stress(v_eff, saturation)
else:
vs = sl.calc_shear_vel(saturation)
dd["shear_vel"].append(vs)
dd["unit_mass"].append(rho)
dd["thickness"].append(slice_thickness)
for item in dd:
dd[item] = np.array(dd[item])
return dd | python | def discretize_soil_profile(sp, incs=None, target=1.0):
"""
Splits the soil profile into slices and stores as dictionary
:param sp: SoilProfile
:param incs: array_like, increments of depth to use for each layer
:param target: target depth increment size
:return: dict
"""
if incs is None:
incs = np.ones(sp.n_layers) * target
dd = {}
dd["thickness"] = []
dd["unit_mass"] = []
dd["shear_vel"] = []
cum_thickness = 0
for i in range(sp.n_layers):
sl = sp.layer(i + 1)
thickness = sp.layer_height(i + 1)
n_slices = max(int(thickness / incs[i]), 1)
slice_thickness = float(thickness) / n_slices
for j in range(n_slices):
cum_thickness += slice_thickness
if cum_thickness >= sp.gwl:
rho = sl.unit_sat_mass
saturation = True
else:
rho = sl.unit_dry_mass
saturation = False
if hasattr(sl, "get_shear_vel_at_v_eff_stress"):
v_eff = sp.vertical_effective_stress(cum_thickness)
vs = sl.get_shear_vel_at_v_eff_stress(v_eff, saturation)
else:
vs = sl.calc_shear_vel(saturation)
dd["shear_vel"].append(vs)
dd["unit_mass"].append(rho)
dd["thickness"].append(slice_thickness)
for item in dd:
dd[item] = np.array(dd[item])
return dd | [
"def",
"discretize_soil_profile",
"(",
"sp",
",",
"incs",
"=",
"None",
",",
"target",
"=",
"1.0",
")",
":",
"if",
"incs",
"is",
"None",
":",
"incs",
"=",
"np",
".",
"ones",
"(",
"sp",
".",
"n_layers",
")",
"*",
"target",
"dd",
"=",
"{",
"}",
"dd"... | Splits the soil profile into slices and stores as dictionary
:param sp: SoilProfile
:param incs: array_like, increments of depth to use for each layer
:param target: target depth increment size
:return: dict | [
"Splits",
"the",
"soil",
"profile",
"into",
"slices",
"and",
"stores",
"as",
"dictionary"
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L1272-L1312 | train | 53,847 |
eng-tools/sfsimodels | sfsimodels/models/soils.py | Soil.override | def override(self, item, value):
"""
Can set a parameter to a value that is inconsistent with existing values.
This method sets the inconsistent value and then reapplies all existing values
that are still consistent, all non-consistent (conflicting) values are removed from the object
and returned as a list
:param item: name of parameter to be set
:param value: value of the parameter to be set
:return: list, conflicting values
"""
if not hasattr(self, item):
raise KeyError("Soil Object does not have property: %s", item)
try:
setattr(self, item, value) # try to set using normal setter method
return []
except ModelError:
pass # if inconsistency, then need to rebuild stack
# create a new temporary stack
temp_stack = list(self.stack)
# remove item from original position in stack
temp_stack[:] = (value for value in temp_stack if value[0] != item)
# add item to the start of the stack
temp_stack.insert(0, (item, value))
# clear object, ready to rebuild
self.reset_all()
# reapply trace, one item at a time, if conflict then don't add the conflict.
conflicts = []
for item, value in temp_stack:
# catch all conflicts
try:
setattr(self, item, value)
except ModelError:
conflicts.append(item)
return conflicts | python | def override(self, item, value):
"""
Can set a parameter to a value that is inconsistent with existing values.
This method sets the inconsistent value and then reapplies all existing values
that are still consistent, all non-consistent (conflicting) values are removed from the object
and returned as a list
:param item: name of parameter to be set
:param value: value of the parameter to be set
:return: list, conflicting values
"""
if not hasattr(self, item):
raise KeyError("Soil Object does not have property: %s", item)
try:
setattr(self, item, value) # try to set using normal setter method
return []
except ModelError:
pass # if inconsistency, then need to rebuild stack
# create a new temporary stack
temp_stack = list(self.stack)
# remove item from original position in stack
temp_stack[:] = (value for value in temp_stack if value[0] != item)
# add item to the start of the stack
temp_stack.insert(0, (item, value))
# clear object, ready to rebuild
self.reset_all()
# reapply trace, one item at a time, if conflict then don't add the conflict.
conflicts = []
for item, value in temp_stack:
# catch all conflicts
try:
setattr(self, item, value)
except ModelError:
conflicts.append(item)
return conflicts | [
"def",
"override",
"(",
"self",
",",
"item",
",",
"value",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"item",
")",
":",
"raise",
"KeyError",
"(",
"\"Soil Object does not have property: %s\"",
",",
"item",
")",
"try",
":",
"setattr",
"(",
"self",
... | Can set a parameter to a value that is inconsistent with existing values.
This method sets the inconsistent value and then reapplies all existing values
that are still consistent, all non-consistent (conflicting) values are removed from the object
and returned as a list
:param item: name of parameter to be set
:param value: value of the parameter to be set
:return: list, conflicting values | [
"Can",
"set",
"a",
"parameter",
"to",
"a",
"value",
"that",
"is",
"inconsistent",
"with",
"existing",
"values",
"."
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L84-L119 | train | 53,848 |
eng-tools/sfsimodels | sfsimodels/models/soils.py | Soil.reset_all | def reset_all(self):
"""
Resets all parameters to None
"""
for item in self.inputs:
setattr(self, "_%s" % item, None)
self.stack = [] | python | def reset_all(self):
"""
Resets all parameters to None
"""
for item in self.inputs:
setattr(self, "_%s" % item, None)
self.stack = [] | [
"def",
"reset_all",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"inputs",
":",
"setattr",
"(",
"self",
",",
"\"_%s\"",
"%",
"item",
",",
"None",
")",
"self",
".",
"stack",
"=",
"[",
"]"
] | Resets all parameters to None | [
"Resets",
"all",
"parameters",
"to",
"None"
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L121-L127 | train | 53,849 |
eng-tools/sfsimodels | sfsimodels/models/soils.py | Soil.get_shear_vel | def get_shear_vel(self, saturated):
"""
Calculate the shear wave velocity
:param saturated: bool, if true then use saturated mass
:return:
"""
try:
if saturated:
return np.sqrt(self.g_mod / self.unit_sat_mass)
else:
return np.sqrt(self.g_mod / self.unit_dry_mass)
except TypeError:
return None | python | def get_shear_vel(self, saturated):
"""
Calculate the shear wave velocity
:param saturated: bool, if true then use saturated mass
:return:
"""
try:
if saturated:
return np.sqrt(self.g_mod / self.unit_sat_mass)
else:
return np.sqrt(self.g_mod / self.unit_dry_mass)
except TypeError:
return None | [
"def",
"get_shear_vel",
"(",
"self",
",",
"saturated",
")",
":",
"try",
":",
"if",
"saturated",
":",
"return",
"np",
".",
"sqrt",
"(",
"self",
".",
"g_mod",
"/",
"self",
".",
"unit_sat_mass",
")",
"else",
":",
"return",
"np",
".",
"sqrt",
"(",
"self"... | Calculate the shear wave velocity
:param saturated: bool, if true then use saturated mass
:return: | [
"Calculate",
"the",
"shear",
"wave",
"velocity"
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L256-L269 | train | 53,850 |
eng-tools/sfsimodels | sfsimodels/models/soils.py | Soil.saturation | def saturation(self, value):
"""Volume of water to volume of voids"""
value = clean_float(value)
if value is None:
return
try:
unit_moisture_weight = self.unit_moist_weight - self.unit_dry_weight
unit_moisture_volume = unit_moisture_weight / self._pw
saturation = unit_moisture_volume / self._calc_unit_void_volume()
if saturation is not None and not ct.isclose(saturation, value, rel_tol=self._tolerance):
raise ModelError("New saturation (%.3f) is inconsistent "
"with calculated value (%.3f)" % (value, saturation))
except TypeError:
pass
old_value = self.saturation
self._saturation = value
try:
self.recompute_all_weights_and_void()
self._add_to_stack("saturation", value)
except ModelError as e:
self._saturation = old_value
raise ModelError(e) | python | def saturation(self, value):
"""Volume of water to volume of voids"""
value = clean_float(value)
if value is None:
return
try:
unit_moisture_weight = self.unit_moist_weight - self.unit_dry_weight
unit_moisture_volume = unit_moisture_weight / self._pw
saturation = unit_moisture_volume / self._calc_unit_void_volume()
if saturation is not None and not ct.isclose(saturation, value, rel_tol=self._tolerance):
raise ModelError("New saturation (%.3f) is inconsistent "
"with calculated value (%.3f)" % (value, saturation))
except TypeError:
pass
old_value = self.saturation
self._saturation = value
try:
self.recompute_all_weights_and_void()
self._add_to_stack("saturation", value)
except ModelError as e:
self._saturation = old_value
raise ModelError(e) | [
"def",
"saturation",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"clean_float",
"(",
"value",
")",
"if",
"value",
"is",
"None",
":",
"return",
"try",
":",
"unit_moisture_weight",
"=",
"self",
".",
"unit_moist_weight",
"-",
"self",
".",
"unit_dry_wei... | Volume of water to volume of voids | [
"Volume",
"of",
"water",
"to",
"volume",
"of",
"voids"
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L416-L437 | train | 53,851 |
eng-tools/sfsimodels | sfsimodels/models/soils.py | Soil.specific_gravity | def specific_gravity(self, value):
""" Set the relative weight of the solid """
value = clean_float(value)
if value is None:
return
specific_gravity = self._calc_specific_gravity()
if specific_gravity is not None and not ct.isclose(specific_gravity, value, rel_tol=self._tolerance):
raise ModelError("specific gravity is inconsistent with set unit_dry_weight and void_ratio")
self._specific_gravity = float(value)
self.stack.append(("specific_gravity", float(value)))
self.recompute_all_weights_and_void() | python | def specific_gravity(self, value):
""" Set the relative weight of the solid """
value = clean_float(value)
if value is None:
return
specific_gravity = self._calc_specific_gravity()
if specific_gravity is not None and not ct.isclose(specific_gravity, value, rel_tol=self._tolerance):
raise ModelError("specific gravity is inconsistent with set unit_dry_weight and void_ratio")
self._specific_gravity = float(value)
self.stack.append(("specific_gravity", float(value)))
self.recompute_all_weights_and_void() | [
"def",
"specific_gravity",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"clean_float",
"(",
"value",
")",
"if",
"value",
"is",
"None",
":",
"return",
"specific_gravity",
"=",
"self",
".",
"_calc_specific_gravity",
"(",
")",
"if",
"specific_gravity",
"i... | Set the relative weight of the solid | [
"Set",
"the",
"relative",
"weight",
"of",
"the",
"solid"
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L460-L471 | train | 53,852 |
eng-tools/sfsimodels | sfsimodels/models/soils.py | SoilProfile.add_layer | def add_layer(self, depth, soil):
"""
Adds a soil to the SoilProfile at a set depth.
Note, the soils are automatically reordered based on depth from surface.
:param depth: depth from surface to top of soil layer
:param soil: Soil object
"""
self._layers[depth] = soil
self._sort_layers()
if self.hydrostatic:
if depth >= self.gwl:
soil.saturation = 1.0
else:
li = self.get_layer_index_by_depth(depth)
layer_height = self.layer_height(li)
if layer_height is None:
soil.saturation = 0.0
elif depth + layer_height <= self.gwl:
soil.saturation = 0.0
else:
sat_height = depth + self.layer_height(li) - self.gwl
soil.saturation = sat_height / self.layer_height(li) | python | def add_layer(self, depth, soil):
"""
Adds a soil to the SoilProfile at a set depth.
Note, the soils are automatically reordered based on depth from surface.
:param depth: depth from surface to top of soil layer
:param soil: Soil object
"""
self._layers[depth] = soil
self._sort_layers()
if self.hydrostatic:
if depth >= self.gwl:
soil.saturation = 1.0
else:
li = self.get_layer_index_by_depth(depth)
layer_height = self.layer_height(li)
if layer_height is None:
soil.saturation = 0.0
elif depth + layer_height <= self.gwl:
soil.saturation = 0.0
else:
sat_height = depth + self.layer_height(li) - self.gwl
soil.saturation = sat_height / self.layer_height(li) | [
"def",
"add_layer",
"(",
"self",
",",
"depth",
",",
"soil",
")",
":",
"self",
".",
"_layers",
"[",
"depth",
"]",
"=",
"soil",
"self",
".",
"_sort_layers",
"(",
")",
"if",
"self",
".",
"hydrostatic",
":",
"if",
"depth",
">=",
"self",
".",
"gwl",
":"... | Adds a soil to the SoilProfile at a set depth.
Note, the soils are automatically reordered based on depth from surface.
:param depth: depth from surface to top of soil layer
:param soil: Soil object | [
"Adds",
"a",
"soil",
"to",
"the",
"SoilProfile",
"at",
"a",
"set",
"depth",
"."
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L910-L934 | train | 53,853 |
eng-tools/sfsimodels | sfsimodels/models/soils.py | SoilProfile._sort_layers | def _sort_layers(self):
"""Sort the layers by depth."""
self._layers = OrderedDict(sorted(self._layers.items(), key=lambda t: t[0])) | python | def _sort_layers(self):
"""Sort the layers by depth."""
self._layers = OrderedDict(sorted(self._layers.items(), key=lambda t: t[0])) | [
"def",
"_sort_layers",
"(",
"self",
")",
":",
"self",
".",
"_layers",
"=",
"OrderedDict",
"(",
"sorted",
"(",
"self",
".",
"_layers",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"t",
":",
"t",
"[",
"0",
"]",
")",
")"
] | Sort the layers by depth. | [
"Sort",
"the",
"layers",
"by",
"depth",
"."
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L936-L938 | train | 53,854 |
eng-tools/sfsimodels | sfsimodels/models/soils.py | SoilProfile.layer_height | def layer_height(self, layer_int):
"""
Get the layer height by layer id number.
:param layer_int:
:return: float, height of the soil layer
"""
if layer_int == self.n_layers:
if self.height is None:
return None
return self.height - self.layer_depth(layer_int)
else:
return self.layer_depth(layer_int + 1) - self.layer_depth(layer_int) | python | def layer_height(self, layer_int):
"""
Get the layer height by layer id number.
:param layer_int:
:return: float, height of the soil layer
"""
if layer_int == self.n_layers:
if self.height is None:
return None
return self.height - self.layer_depth(layer_int)
else:
return self.layer_depth(layer_int + 1) - self.layer_depth(layer_int) | [
"def",
"layer_height",
"(",
"self",
",",
"layer_int",
")",
":",
"if",
"layer_int",
"==",
"self",
".",
"n_layers",
":",
"if",
"self",
".",
"height",
"is",
"None",
":",
"return",
"None",
"return",
"self",
".",
"height",
"-",
"self",
".",
"layer_depth",
"... | Get the layer height by layer id number.
:param layer_int:
:return: float, height of the soil layer | [
"Get",
"the",
"layer",
"height",
"by",
"layer",
"id",
"number",
"."
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L984-L996 | train | 53,855 |
eng-tools/sfsimodels | sfsimodels/models/soils.py | SoilProfile.equivalent_crust_cohesion | def equivalent_crust_cohesion(self):
"""
Calculate the equivalent crust cohesion strength according to Karamitros et al. 2013 sett, pg 8 eq. 14
:return: equivalent cohesion [Pa]
"""
deprecation("Will be moved to a function")
if len(self.layers) > 1:
crust = self.layer(0)
crust_phi_r = np.radians(crust.phi)
equivalent_cohesion = crust.cohesion + crust.k_0 * self.crust_effective_unit_weight * \
self.layer_depth(1) / 2 * np.tan(crust_phi_r)
return equivalent_cohesion | python | def equivalent_crust_cohesion(self):
"""
Calculate the equivalent crust cohesion strength according to Karamitros et al. 2013 sett, pg 8 eq. 14
:return: equivalent cohesion [Pa]
"""
deprecation("Will be moved to a function")
if len(self.layers) > 1:
crust = self.layer(0)
crust_phi_r = np.radians(crust.phi)
equivalent_cohesion = crust.cohesion + crust.k_0 * self.crust_effective_unit_weight * \
self.layer_depth(1) / 2 * np.tan(crust_phi_r)
return equivalent_cohesion | [
"def",
"equivalent_crust_cohesion",
"(",
"self",
")",
":",
"deprecation",
"(",
"\"Will be moved to a function\"",
")",
"if",
"len",
"(",
"self",
".",
"layers",
")",
">",
"1",
":",
"crust",
"=",
"self",
".",
"layer",
"(",
"0",
")",
"crust_phi_r",
"=",
"np",... | Calculate the equivalent crust cohesion strength according to Karamitros et al. 2013 sett, pg 8 eq. 14
:return: equivalent cohesion [Pa] | [
"Calculate",
"the",
"equivalent",
"crust",
"cohesion",
"strength",
"according",
"to",
"Karamitros",
"et",
"al",
".",
"2013",
"sett",
"pg",
"8",
"eq",
".",
"14"
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L1083-L1095 | train | 53,856 |
eng-tools/sfsimodels | sfsimodels/models/soils.py | SoilProfile.get_v_total_stress_at_depth | def get_v_total_stress_at_depth(self, z):
"""
Determine the vertical total stress at depth z, where z can be a number or an array of numbers.
"""
if not hasattr(z, "__len__"):
return self.one_vertical_total_stress(z)
else:
sigma_v_effs = []
for value in z:
sigma_v_effs.append(self.one_vertical_total_stress(value))
return np.array(sigma_v_effs) | python | def get_v_total_stress_at_depth(self, z):
"""
Determine the vertical total stress at depth z, where z can be a number or an array of numbers.
"""
if not hasattr(z, "__len__"):
return self.one_vertical_total_stress(z)
else:
sigma_v_effs = []
for value in z:
sigma_v_effs.append(self.one_vertical_total_stress(value))
return np.array(sigma_v_effs) | [
"def",
"get_v_total_stress_at_depth",
"(",
"self",
",",
"z",
")",
":",
"if",
"not",
"hasattr",
"(",
"z",
",",
"\"__len__\"",
")",
":",
"return",
"self",
".",
"one_vertical_total_stress",
"(",
"z",
")",
"else",
":",
"sigma_v_effs",
"=",
"[",
"]",
"for",
"... | Determine the vertical total stress at depth z, where z can be a number or an array of numbers. | [
"Determine",
"the",
"vertical",
"total",
"stress",
"at",
"depth",
"z",
"where",
"z",
"can",
"be",
"a",
"number",
"or",
"an",
"array",
"of",
"numbers",
"."
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L1112-L1123 | train | 53,857 |
eng-tools/sfsimodels | sfsimodels/models/soils.py | SoilProfile.one_vertical_total_stress | def one_vertical_total_stress(self, z_c):
"""
Determine the vertical total stress at a single depth z_c.
:param z_c: depth from surface
"""
total_stress = 0.0
depths = self.depths
end = 0
for layer_int in range(1, len(depths) + 1):
l_index = layer_int - 1
if z_c > depths[layer_int - 1]:
if l_index < len(depths) - 1 and z_c > depths[l_index + 1]:
height = depths[l_index + 1] - depths[l_index]
bottom_depth = depths[l_index + 1]
else:
end = 1
height = z_c - depths[l_index]
bottom_depth = z_c
if bottom_depth <= self.gwl:
total_stress += height * self.layer(layer_int).unit_dry_weight
else:
if self.layer(layer_int).unit_sat_weight is None:
raise AnalysisError("Saturated unit weight not defined for layer %i." % layer_int)
sat_height = bottom_depth - max(self.gwl, depths[l_index])
dry_height = height - sat_height
total_stress += dry_height * self.layer(layer_int).unit_dry_weight + \
sat_height * self.layer(layer_int).unit_sat_weight
else:
end = 1
if end:
break
return total_stress | python | def one_vertical_total_stress(self, z_c):
"""
Determine the vertical total stress at a single depth z_c.
:param z_c: depth from surface
"""
total_stress = 0.0
depths = self.depths
end = 0
for layer_int in range(1, len(depths) + 1):
l_index = layer_int - 1
if z_c > depths[layer_int - 1]:
if l_index < len(depths) - 1 and z_c > depths[l_index + 1]:
height = depths[l_index + 1] - depths[l_index]
bottom_depth = depths[l_index + 1]
else:
end = 1
height = z_c - depths[l_index]
bottom_depth = z_c
if bottom_depth <= self.gwl:
total_stress += height * self.layer(layer_int).unit_dry_weight
else:
if self.layer(layer_int).unit_sat_weight is None:
raise AnalysisError("Saturated unit weight not defined for layer %i." % layer_int)
sat_height = bottom_depth - max(self.gwl, depths[l_index])
dry_height = height - sat_height
total_stress += dry_height * self.layer(layer_int).unit_dry_weight + \
sat_height * self.layer(layer_int).unit_sat_weight
else:
end = 1
if end:
break
return total_stress | [
"def",
"one_vertical_total_stress",
"(",
"self",
",",
"z_c",
")",
":",
"total_stress",
"=",
"0.0",
"depths",
"=",
"self",
".",
"depths",
"end",
"=",
"0",
"for",
"layer_int",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"depths",
")",
"+",
"1",
")",
":",... | Determine the vertical total stress at a single depth z_c.
:param z_c: depth from surface | [
"Determine",
"the",
"vertical",
"total",
"stress",
"at",
"a",
"single",
"depth",
"z_c",
"."
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L1125-L1158 | train | 53,858 |
eng-tools/sfsimodels | sfsimodels/models/soils.py | SoilProfile.get_v_eff_stress_at_depth | def get_v_eff_stress_at_depth(self, y_c):
"""
Determine the vertical effective stress at a single depth z_c.
:param y_c: float, depth from surface
"""
sigma_v_c = self.get_v_total_stress_at_depth(y_c)
pp = self.get_hydrostatic_pressure_at_depth(y_c)
sigma_veff_c = sigma_v_c - pp
return sigma_veff_c | python | def get_v_eff_stress_at_depth(self, y_c):
"""
Determine the vertical effective stress at a single depth z_c.
:param y_c: float, depth from surface
"""
sigma_v_c = self.get_v_total_stress_at_depth(y_c)
pp = self.get_hydrostatic_pressure_at_depth(y_c)
sigma_veff_c = sigma_v_c - pp
return sigma_veff_c | [
"def",
"get_v_eff_stress_at_depth",
"(",
"self",
",",
"y_c",
")",
":",
"sigma_v_c",
"=",
"self",
".",
"get_v_total_stress_at_depth",
"(",
"y_c",
")",
"pp",
"=",
"self",
".",
"get_hydrostatic_pressure_at_depth",
"(",
"y_c",
")",
"sigma_veff_c",
"=",
"sigma_v_c",
... | Determine the vertical effective stress at a single depth z_c.
:param y_c: float, depth from surface | [
"Determine",
"the",
"vertical",
"effective",
"stress",
"at",
"a",
"single",
"depth",
"z_c",
"."
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L1181-L1190 | train | 53,859 |
eng-tools/sfsimodels | sfsimodels/models/soils.py | SoilProfile.shear_vel_at_depth | def shear_vel_at_depth(self, y_c):
"""
Get the shear wave velocity at a depth.
:param y_c: float, depth from surface
:return:
"""
sl = self.get_soil_at_depth(y_c)
if y_c <= self.gwl:
saturation = False
else:
saturation = True
if hasattr(sl, "get_shear_vel_at_v_eff_stress"):
v_eff = self.get_v_eff_stress_at_depth(y_c)
vs = sl.get_shear_vel_at_v_eff_stress(v_eff, saturation)
else:
vs = sl.get_shear_vel(saturation)
return vs | python | def shear_vel_at_depth(self, y_c):
"""
Get the shear wave velocity at a depth.
:param y_c: float, depth from surface
:return:
"""
sl = self.get_soil_at_depth(y_c)
if y_c <= self.gwl:
saturation = False
else:
saturation = True
if hasattr(sl, "get_shear_vel_at_v_eff_stress"):
v_eff = self.get_v_eff_stress_at_depth(y_c)
vs = sl.get_shear_vel_at_v_eff_stress(v_eff, saturation)
else:
vs = sl.get_shear_vel(saturation)
return vs | [
"def",
"shear_vel_at_depth",
"(",
"self",
",",
"y_c",
")",
":",
"sl",
"=",
"self",
".",
"get_soil_at_depth",
"(",
"y_c",
")",
"if",
"y_c",
"<=",
"self",
".",
"gwl",
":",
"saturation",
"=",
"False",
"else",
":",
"saturation",
"=",
"True",
"if",
"hasattr... | Get the shear wave velocity at a depth.
:param y_c: float, depth from surface
:return: | [
"Get",
"the",
"shear",
"wave",
"velocity",
"at",
"a",
"depth",
"."
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L1197-L1214 | train | 53,860 |
Metatab/metatab | metatab/doc.py | MetatabDoc.path | def path(self):
"""Return the path to the file, if the ref is a file"""
if not isinstance(self.ref, str):
return None
u = parse_app_url(self.ref)
if u.inner.proto != 'file':
return None
return u.path | python | def path(self):
"""Return the path to the file, if the ref is a file"""
if not isinstance(self.ref, str):
return None
u = parse_app_url(self.ref)
if u.inner.proto != 'file':
return None
return u.path | [
"def",
"path",
"(",
"self",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"ref",
",",
"str",
")",
":",
"return",
"None",
"u",
"=",
"parse_app_url",
"(",
"self",
".",
"ref",
")",
"if",
"u",
".",
"inner",
".",
"proto",
"!=",
"'file'",
":",... | Return the path to the file, if the ref is a file | [
"Return",
"the",
"path",
"to",
"the",
"file",
"if",
"the",
"ref",
"is",
"a",
"file"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L98-L109 | train | 53,861 |
Metatab/metatab | metatab/doc.py | MetatabDoc.doc_dir | def doc_dir(self):
"""The absolute directory of the document"""
from os.path import abspath
if not self.ref:
return None
u = parse_app_url(self.ref)
return abspath(dirname(u.path)) | python | def doc_dir(self):
"""The absolute directory of the document"""
from os.path import abspath
if not self.ref:
return None
u = parse_app_url(self.ref)
return abspath(dirname(u.path)) | [
"def",
"doc_dir",
"(",
"self",
")",
":",
"from",
"os",
".",
"path",
"import",
"abspath",
"if",
"not",
"self",
".",
"ref",
":",
"return",
"None",
"u",
"=",
"parse_app_url",
"(",
"self",
".",
"ref",
")",
"return",
"abspath",
"(",
"dirname",
"(",
"u",
... | The absolute directory of the document | [
"The",
"absolute",
"directory",
"of",
"the",
"document"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L135-L143 | train | 53,862 |
Metatab/metatab | metatab/doc.py | MetatabDoc.remove_term | def remove_term(self, t):
"""Only removes top-level terms. Child terms can be removed at the parent. """
try:
self.terms.remove(t)
except ValueError:
pass
if t.section and t.parent_term_lc == 'root':
t.section = self.add_section(t.section)
t.section.remove_term(t, remove_from_doc=False)
if t.parent:
try:
t.parent.remove_child(t)
except ValueError:
pass | python | def remove_term(self, t):
"""Only removes top-level terms. Child terms can be removed at the parent. """
try:
self.terms.remove(t)
except ValueError:
pass
if t.section and t.parent_term_lc == 'root':
t.section = self.add_section(t.section)
t.section.remove_term(t, remove_from_doc=False)
if t.parent:
try:
t.parent.remove_child(t)
except ValueError:
pass | [
"def",
"remove_term",
"(",
"self",
",",
"t",
")",
":",
"try",
":",
"self",
".",
"terms",
".",
"remove",
"(",
"t",
")",
"except",
"ValueError",
":",
"pass",
"if",
"t",
".",
"section",
"and",
"t",
".",
"parent_term_lc",
"==",
"'root'",
":",
"t",
".",... | Only removes top-level terms. Child terms can be removed at the parent. | [
"Only",
"removes",
"top",
"-",
"level",
"terms",
".",
"Child",
"terms",
"can",
"be",
"removed",
"at",
"the",
"parent",
"."
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L227-L244 | train | 53,863 |
Metatab/metatab | metatab/doc.py | MetatabDoc.new_section | def new_section(self, name, params=None):
"""Return a new section"""
self.sections[name.lower()] = SectionTerm(None, name, term_args=params, doc=self)
# Set the default arguments
s = self.sections[name.lower()]
if name.lower() in self.decl_sections:
s.args = self.decl_sections[name.lower()]['args']
return s | python | def new_section(self, name, params=None):
"""Return a new section"""
self.sections[name.lower()] = SectionTerm(None, name, term_args=params, doc=self)
# Set the default arguments
s = self.sections[name.lower()]
if name.lower() in self.decl_sections:
s.args = self.decl_sections[name.lower()]['args']
return s | [
"def",
"new_section",
"(",
"self",
",",
"name",
",",
"params",
"=",
"None",
")",
":",
"self",
".",
"sections",
"[",
"name",
".",
"lower",
"(",
")",
"]",
"=",
"SectionTerm",
"(",
"None",
",",
"name",
",",
"term_args",
"=",
"params",
",",
"doc",
"=",... | Return a new section | [
"Return",
"a",
"new",
"section"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L263-L273 | train | 53,864 |
Metatab/metatab | metatab/doc.py | MetatabDoc.get_or_new_section | def get_or_new_section(self, name, params=None):
"""Create a new section or return an existing one of the same name"""
if name not in self.sections:
self.sections[name.lower()] = SectionTerm(None, name, term_args=params, doc=self)
return self.sections[name.lower()] | python | def get_or_new_section(self, name, params=None):
"""Create a new section or return an existing one of the same name"""
if name not in self.sections:
self.sections[name.lower()] = SectionTerm(None, name, term_args=params, doc=self)
return self.sections[name.lower()] | [
"def",
"get_or_new_section",
"(",
"self",
",",
"name",
",",
"params",
"=",
"None",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"sections",
":",
"self",
".",
"sections",
"[",
"name",
".",
"lower",
"(",
")",
"]",
"=",
"SectionTerm",
"(",
"None",
... | Create a new section or return an existing one of the same name | [
"Create",
"a",
"new",
"section",
"or",
"return",
"an",
"existing",
"one",
"of",
"the",
"same",
"name"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L275-L280 | train | 53,865 |
Metatab/metatab | metatab/doc.py | MetatabDoc.sort_sections | def sort_sections(self, order):
"""
Sort sections according to the section names in the order list. All remaining sections
are added to the end in their original order
:param order: Iterable of section names
:return:
"""
order_lc = [e.lower() for e in order]
sections = OrderedDict( (k,self.sections[k]) for k in order_lc if k in self.sections)
sections.update( (k,self.sections[k]) for k in self.sections.keys() if k not in order_lc)
assert len(self.sections) == len(sections)
self.sections = sections | python | def sort_sections(self, order):
"""
Sort sections according to the section names in the order list. All remaining sections
are added to the end in their original order
:param order: Iterable of section names
:return:
"""
order_lc = [e.lower() for e in order]
sections = OrderedDict( (k,self.sections[k]) for k in order_lc if k in self.sections)
sections.update( (k,self.sections[k]) for k in self.sections.keys() if k not in order_lc)
assert len(self.sections) == len(sections)
self.sections = sections | [
"def",
"sort_sections",
"(",
"self",
",",
"order",
")",
":",
"order_lc",
"=",
"[",
"e",
".",
"lower",
"(",
")",
"for",
"e",
"in",
"order",
"]",
"sections",
"=",
"OrderedDict",
"(",
"(",
"k",
",",
"self",
".",
"sections",
"[",
"k",
"]",
")",
"for"... | Sort sections according to the section names in the order list. All remaining sections
are added to the end in their original order
:param order: Iterable of section names
:return: | [
"Sort",
"sections",
"according",
"to",
"the",
"section",
"names",
"in",
"the",
"order",
"list",
".",
"All",
"remaining",
"sections",
"are",
"added",
"to",
"the",
"end",
"in",
"their",
"original",
"order"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L291-L308 | train | 53,866 |
Metatab/metatab | metatab/doc.py | MetatabDoc.find | def find(self, term, value=False, section=None, _expand_derived=True, **kwargs):
"""Return a list of terms, possibly in a particular section. Use joined term notation, such as 'Root.Name' The kwargs arg is used to set term properties, all of which match returned terms, so ``name='foobar'`` will match terms that have a ``name`` property of ``foobar``
:param term: The type of term to find, in fully-qulified notation, or use '*' for wild cards in either the parent or the record parts, such as 'Root.*', '*.Table' or '*.*'
:param value: Select terms with a given value
:param section: The name of the section in which to restrict the search
:param kwargs: See additional properties on which to match terms.
"""
import itertools
if kwargs: # Look for terms with particular property values
terms = self.find(term, value, section)
found_terms = []
for t in terms:
if all(t.get_value(k) == v for k, v in kwargs.items()):
found_terms.append(t)
return found_terms
def in_section(term, section):
if section is None:
return True
if term.section is None:
return False
if isinstance(section, (list, tuple)):
return any(in_section(t, e) for e in section)
else:
return section.lower() == term.section.name.lower()
# Try to replace the term with the list of its derived terms; that is, replace the super-class with all
# of the derived classes, but only do this expansion once.
if _expand_derived:
try:
try:
# Term is a string
term = list(self.derived_terms[term.lower()]) + [term]
except AttributeError: # Term is hopefully a list
terms = []
for t in term:
terms.append(term)
for dt in self.derived_terms[t.lower()]:
terms.append(dt)
except KeyError as e:
pass
# Find any of a list of terms
if isinstance(term, (list, tuple)):
return list(itertools.chain(*[self.find(e, value=value, section=section, _expand_derived=False) for e in term]))
else:
term = term.lower()
found = []
if not '.' in term:
term = 'root.' + term
if term.startswith('root.'):
term_gen = self.terms # Just the root level terms
else:
term_gen = self.all_terms # All terms, root level and children.
for t in term_gen:
if t.join_lc == 'root.root':
continue
assert t.section or t.join_lc == 'root.root' or t.join_lc == 'root.section', t
if (t.term_is(term)
and in_section(t, section)
and (value is False or value == t.value)):
found.append(t)
return found | python | def find(self, term, value=False, section=None, _expand_derived=True, **kwargs):
"""Return a list of terms, possibly in a particular section. Use joined term notation, such as 'Root.Name' The kwargs arg is used to set term properties, all of which match returned terms, so ``name='foobar'`` will match terms that have a ``name`` property of ``foobar``
:param term: The type of term to find, in fully-qulified notation, or use '*' for wild cards in either the parent or the record parts, such as 'Root.*', '*.Table' or '*.*'
:param value: Select terms with a given value
:param section: The name of the section in which to restrict the search
:param kwargs: See additional properties on which to match terms.
"""
import itertools
if kwargs: # Look for terms with particular property values
terms = self.find(term, value, section)
found_terms = []
for t in terms:
if all(t.get_value(k) == v for k, v in kwargs.items()):
found_terms.append(t)
return found_terms
def in_section(term, section):
if section is None:
return True
if term.section is None:
return False
if isinstance(section, (list, tuple)):
return any(in_section(t, e) for e in section)
else:
return section.lower() == term.section.name.lower()
# Try to replace the term with the list of its derived terms; that is, replace the super-class with all
# of the derived classes, but only do this expansion once.
if _expand_derived:
try:
try:
# Term is a string
term = list(self.derived_terms[term.lower()]) + [term]
except AttributeError: # Term is hopefully a list
terms = []
for t in term:
terms.append(term)
for dt in self.derived_terms[t.lower()]:
terms.append(dt)
except KeyError as e:
pass
# Find any of a list of terms
if isinstance(term, (list, tuple)):
return list(itertools.chain(*[self.find(e, value=value, section=section, _expand_derived=False) for e in term]))
else:
term = term.lower()
found = []
if not '.' in term:
term = 'root.' + term
if term.startswith('root.'):
term_gen = self.terms # Just the root level terms
else:
term_gen = self.all_terms # All terms, root level and children.
for t in term_gen:
if t.join_lc == 'root.root':
continue
assert t.section or t.join_lc == 'root.root' or t.join_lc == 'root.section', t
if (t.term_is(term)
and in_section(t, section)
and (value is False or value == t.value)):
found.append(t)
return found | [
"def",
"find",
"(",
"self",
",",
"term",
",",
"value",
"=",
"False",
",",
"section",
"=",
"None",
",",
"_expand_derived",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"itertools",
"if",
"kwargs",
":",
"# Look for terms with particular property v... | Return a list of terms, possibly in a particular section. Use joined term notation, such as 'Root.Name' The kwargs arg is used to set term properties, all of which match returned terms, so ``name='foobar'`` will match terms that have a ``name`` property of ``foobar``
:param term: The type of term to find, in fully-qulified notation, or use '*' for wild cards in either the parent or the record parts, such as 'Root.*', '*.Table' or '*.*'
:param value: Select terms with a given value
:param section: The name of the section in which to restrict the search
:param kwargs: See additional properties on which to match terms. | [
"Return",
"a",
"list",
"of",
"terms",
"possibly",
"in",
"a",
"particular",
"section",
".",
"Use",
"joined",
"term",
"notation",
"such",
"as",
"Root",
".",
"Name",
"The",
"kwargs",
"arg",
"is",
"used",
"to",
"set",
"term",
"properties",
"all",
"of",
"whic... | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L341-L424 | train | 53,867 |
Metatab/metatab | metatab/doc.py | MetatabDoc.get | def get(self, term, default=None):
"""Return the first term, returning the default if no term is found"""
v = self.find_first(term)
if not v:
return default
else:
return v | python | def get(self, term, default=None):
"""Return the first term, returning the default if no term is found"""
v = self.find_first(term)
if not v:
return default
else:
return v | [
"def",
"get",
"(",
"self",
",",
"term",
",",
"default",
"=",
"None",
")",
":",
"v",
"=",
"self",
".",
"find_first",
"(",
"term",
")",
"if",
"not",
"v",
":",
"return",
"default",
"else",
":",
"return",
"v"
] | Return the first term, returning the default if no term is found | [
"Return",
"the",
"first",
"term",
"returning",
"the",
"default",
"if",
"no",
"term",
"is",
"found"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L444-L451 | train | 53,868 |
Metatab/metatab | metatab/doc.py | MetatabDoc.get_value | def get_value(self, term, default=None, section=None):
"""Return the first value, returning the default if no term is found"""
term = self.find_first(term, value=False, section=section)
if term is None:
return default
else:
return term.value | python | def get_value(self, term, default=None, section=None):
"""Return the first value, returning the default if no term is found"""
term = self.find_first(term, value=False, section=section)
if term is None:
return default
else:
return term.value | [
"def",
"get_value",
"(",
"self",
",",
"term",
",",
"default",
"=",
"None",
",",
"section",
"=",
"None",
")",
":",
"term",
"=",
"self",
".",
"find_first",
"(",
"term",
",",
"value",
"=",
"False",
",",
"section",
"=",
"section",
")",
"if",
"term",
"i... | Return the first value, returning the default if no term is found | [
"Return",
"the",
"first",
"value",
"returning",
"the",
"default",
"if",
"no",
"term",
"is",
"found"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L453-L460 | train | 53,869 |
Metatab/metatab | metatab/doc.py | MetatabDoc.load_terms | def load_terms(self, terms):
"""Create a builder from a sequence of terms, usually a TermInterpreter"""
#if self.root and len(self.root.children) > 0:
# raise MetatabError("Can't run after adding terms to document.")
for t in terms:
t.doc = self
if t.term_is('root.root'):
if not self.root:
self.root = t
self.add_section(t)
continue
if t.term_is('root.section'):
self.add_section(t)
elif t.parent_term_lc == 'root':
self.add_term(t)
else:
# These terms aren't added to the doc because they are attached to a
# parent term that is added to the doc.
assert t.parent is not None
try:
dd = terms.declare_dict
self.decl_terms.update(dd['terms'])
self.decl_sections.update(dd['sections'])
self.super_terms.update(terms.super_terms())
kf = lambda e: e[1] # Sort on the value
self.derived_terms ={ k:set( e[0] for e in g)
for k, g in groupby(sorted(self.super_terms.items(), key=kf), kf)}
except AttributeError as e:
pass
try:
self.errors = terms.errors_as_dict()
except AttributeError:
self.errors = {}
return self | python | def load_terms(self, terms):
"""Create a builder from a sequence of terms, usually a TermInterpreter"""
#if self.root and len(self.root.children) > 0:
# raise MetatabError("Can't run after adding terms to document.")
for t in terms:
t.doc = self
if t.term_is('root.root'):
if not self.root:
self.root = t
self.add_section(t)
continue
if t.term_is('root.section'):
self.add_section(t)
elif t.parent_term_lc == 'root':
self.add_term(t)
else:
# These terms aren't added to the doc because they are attached to a
# parent term that is added to the doc.
assert t.parent is not None
try:
dd = terms.declare_dict
self.decl_terms.update(dd['terms'])
self.decl_sections.update(dd['sections'])
self.super_terms.update(terms.super_terms())
kf = lambda e: e[1] # Sort on the value
self.derived_terms ={ k:set( e[0] for e in g)
for k, g in groupby(sorted(self.super_terms.items(), key=kf), kf)}
except AttributeError as e:
pass
try:
self.errors = terms.errors_as_dict()
except AttributeError:
self.errors = {}
return self | [
"def",
"load_terms",
"(",
"self",
",",
"terms",
")",
":",
"#if self.root and len(self.root.children) > 0:",
"# raise MetatabError(\"Can't run after adding terms to document.\")",
"for",
"t",
"in",
"terms",
":",
"t",
".",
"doc",
"=",
"self",
"if",
"t",
".",
"term_is",... | Create a builder from a sequence of terms, usually a TermInterpreter | [
"Create",
"a",
"builder",
"from",
"a",
"sequence",
"of",
"terms",
"usually",
"a",
"TermInterpreter"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L466-L515 | train | 53,870 |
Metatab/metatab | metatab/doc.py | MetatabDoc.cleanse | def cleanse(self):
"""Clean up some terms, like ensuring that the name is a slug"""
from .util import slugify
self.ensure_identifier()
try:
self.update_name()
except MetatabError:
identifier = self['Root'].find_first('Root.Identifier')
name = self['Root'].find_first('Root.Name')
if name and name.value:
name.value = slugify(name.value)
elif name:
name.value = slugify(identifier.value)
else:
self['Root'].get_or_new_term('Root.Name').value = slugify(identifier.value) | python | def cleanse(self):
"""Clean up some terms, like ensuring that the name is a slug"""
from .util import slugify
self.ensure_identifier()
try:
self.update_name()
except MetatabError:
identifier = self['Root'].find_first('Root.Identifier')
name = self['Root'].find_first('Root.Name')
if name and name.value:
name.value = slugify(name.value)
elif name:
name.value = slugify(identifier.value)
else:
self['Root'].get_or_new_term('Root.Name').value = slugify(identifier.value) | [
"def",
"cleanse",
"(",
"self",
")",
":",
"from",
".",
"util",
"import",
"slugify",
"self",
".",
"ensure_identifier",
"(",
")",
"try",
":",
"self",
".",
"update_name",
"(",
")",
"except",
"MetatabError",
":",
"identifier",
"=",
"self",
"[",
"'Root'",
"]",... | Clean up some terms, like ensuring that the name is a slug | [
"Clean",
"up",
"some",
"terms",
"like",
"ensuring",
"that",
"the",
"name",
"is",
"a",
"slug"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L524-L543 | train | 53,871 |
Metatab/metatab | metatab/doc.py | MetatabDoc.update_name | def update_name(self, force=False, create_term=False, report_unchanged=True):
"""Generate the Root.Name term from DatasetName, Version, Origin, TIme and Space"""
updates = []
self.ensure_identifier()
name_term = self.find_first('Root.Name')
if not name_term:
if create_term:
name_term = self['Root'].new_term('Root.Name','')
else:
updates.append("No Root.Name, can't update name")
return updates
orig_name = name_term.value
identifier = self.get_value('Root.Identifier')
datasetname = self.get_value('Root.Dataset')
if datasetname:
name = self._generate_identity_name()
if name != orig_name or force:
name_term.value = name
updates.append("Changed Name")
else:
if report_unchanged:
updates.append("Name did not change")
elif not orig_name:
if not identifier:
updates.append("Failed to find DatasetName term or Identity term. Giving up")
else:
updates.append("Setting the name to the identifier")
name_term.value = identifier
elif orig_name == identifier:
if report_unchanged:
updates.append("Name did not change")
else:
# There is no DatasetName, so we can't gneerate name, and the Root.Name is not empty, so we should
# not set it to the identity.
updates.append("No Root.Dataset, so can't update the name")
return updates | python | def update_name(self, force=False, create_term=False, report_unchanged=True):
"""Generate the Root.Name term from DatasetName, Version, Origin, TIme and Space"""
updates = []
self.ensure_identifier()
name_term = self.find_first('Root.Name')
if not name_term:
if create_term:
name_term = self['Root'].new_term('Root.Name','')
else:
updates.append("No Root.Name, can't update name")
return updates
orig_name = name_term.value
identifier = self.get_value('Root.Identifier')
datasetname = self.get_value('Root.Dataset')
if datasetname:
name = self._generate_identity_name()
if name != orig_name or force:
name_term.value = name
updates.append("Changed Name")
else:
if report_unchanged:
updates.append("Name did not change")
elif not orig_name:
if not identifier:
updates.append("Failed to find DatasetName term or Identity term. Giving up")
else:
updates.append("Setting the name to the identifier")
name_term.value = identifier
elif orig_name == identifier:
if report_unchanged:
updates.append("Name did not change")
else:
# There is no DatasetName, so we can't gneerate name, and the Root.Name is not empty, so we should
# not set it to the identity.
updates.append("No Root.Dataset, so can't update the name")
return updates | [
"def",
"update_name",
"(",
"self",
",",
"force",
"=",
"False",
",",
"create_term",
"=",
"False",
",",
"report_unchanged",
"=",
"True",
")",
":",
"updates",
"=",
"[",
"]",
"self",
".",
"ensure_identifier",
"(",
")",
"name_term",
"=",
"self",
".",
"find_fi... | Generate the Root.Name term from DatasetName, Version, Origin, TIme and Space | [
"Generate",
"the",
"Root",
".",
"Name",
"term",
"from",
"DatasetName",
"Version",
"Origin",
"TIme",
"and",
"Space"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L638-L689 | train | 53,872 |
Metatab/metatab | metatab/doc.py | MetatabDoc.as_dict | def as_dict(self, replace_value_names=True):
"""Iterate, link terms and convert to a dict"""
# This function is a hack, due to confusion between the root of the document, which
# should contain all terms, and the root section, which has only terms that are not
# in another section. So, here we are taking the Root section, and adding all of the other
# terms to it, as if it were also the root of the document tree.
r = RootSectionTerm(doc=self)
for s in self: # Iterate over sections
for t in s: # Iterate over the terms in each section.
r.terms.append(t)
return r.as_dict(replace_value_names) | python | def as_dict(self, replace_value_names=True):
"""Iterate, link terms and convert to a dict"""
# This function is a hack, due to confusion between the root of the document, which
# should contain all terms, and the root section, which has only terms that are not
# in another section. So, here we are taking the Root section, and adding all of the other
# terms to it, as if it were also the root of the document tree.
r = RootSectionTerm(doc=self)
for s in self: # Iterate over sections
for t in s: # Iterate over the terms in each section.
r.terms.append(t)
return r.as_dict(replace_value_names) | [
"def",
"as_dict",
"(",
"self",
",",
"replace_value_names",
"=",
"True",
")",
":",
"# This function is a hack, due to confusion between the root of the document, which",
"# should contain all terms, and the root section, which has only terms that are not",
"# in another section. So, here we a... | Iterate, link terms and convert to a dict | [
"Iterate",
"link",
"terms",
"and",
"convert",
"to",
"a",
"dict"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L738-L752 | train | 53,873 |
Metatab/metatab | metatab/doc.py | MetatabDoc.rows | def rows(self):
"""Iterate over all of the rows"""
for s_name, s in self.sections.items():
# Yield the section header
if s.name != 'Root':
yield [''] # Unecessary, but makes for nice formatting. Should actually be done just before write
yield ['Section', s.value] + s.property_names
# Yield all of the rows for terms in the section
for row in s.rows:
term, value = row
term = term.replace('root.', '').title()
try:
yield [term] + value
except:
yield [term] + [value] | python | def rows(self):
"""Iterate over all of the rows"""
for s_name, s in self.sections.items():
# Yield the section header
if s.name != 'Root':
yield [''] # Unecessary, but makes for nice formatting. Should actually be done just before write
yield ['Section', s.value] + s.property_names
# Yield all of the rows for terms in the section
for row in s.rows:
term, value = row
term = term.replace('root.', '').title()
try:
yield [term] + value
except:
yield [term] + [value] | [
"def",
"rows",
"(",
"self",
")",
":",
"for",
"s_name",
",",
"s",
"in",
"self",
".",
"sections",
".",
"items",
"(",
")",
":",
"# Yield the section header",
"if",
"s",
".",
"name",
"!=",
"'Root'",
":",
"yield",
"[",
"''",
"]",
"# Unecessary, but makes for ... | Iterate over all of the rows | [
"Iterate",
"over",
"all",
"of",
"the",
"rows"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L755-L775 | train | 53,874 |
Metatab/metatab | metatab/doc.py | MetatabDoc.all_terms | def all_terms(self):
"""Iterate over all of the terms. The self.terms property has only root level terms. This iterator
iterates over all terms"""
for s_name, s in self.sections.items():
# Yield the section header
if s.name != 'Root':
yield s
# Yield all of the rows for terms in the section
for rterm in s:
yield rterm
for d in rterm.descendents:
yield d | python | def all_terms(self):
"""Iterate over all of the terms. The self.terms property has only root level terms. This iterator
iterates over all terms"""
for s_name, s in self.sections.items():
# Yield the section header
if s.name != 'Root':
yield s
# Yield all of the rows for terms in the section
for rterm in s:
yield rterm
for d in rterm.descendents:
yield d | [
"def",
"all_terms",
"(",
"self",
")",
":",
"for",
"s_name",
",",
"s",
"in",
"self",
".",
"sections",
".",
"items",
"(",
")",
":",
"# Yield the section header",
"if",
"s",
".",
"name",
"!=",
"'Root'",
":",
"yield",
"s",
"# Yield all of the rows for terms in t... | Iterate over all of the terms. The self.terms property has only root level terms. This iterator
iterates over all terms | [
"Iterate",
"over",
"all",
"of",
"the",
"terms",
".",
"The",
"self",
".",
"terms",
"property",
"has",
"only",
"root",
"level",
"terms",
".",
"This",
"iterator",
"iterates",
"over",
"all",
"terms"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L785-L799 | train | 53,875 |
Metatab/metatab | metatab/doc.py | MetatabDoc.as_csv | def as_csv(self):
"""Return a CSV representation as a string"""
from io import StringIO
s = StringIO()
w = csv.writer(s)
for row in self.rows:
w.writerow(row)
return s.getvalue() | python | def as_csv(self):
"""Return a CSV representation as a string"""
from io import StringIO
s = StringIO()
w = csv.writer(s)
for row in self.rows:
w.writerow(row)
return s.getvalue() | [
"def",
"as_csv",
"(",
"self",
")",
":",
"from",
"io",
"import",
"StringIO",
"s",
"=",
"StringIO",
"(",
")",
"w",
"=",
"csv",
".",
"writer",
"(",
"s",
")",
"for",
"row",
"in",
"self",
".",
"rows",
":",
"w",
".",
"writerow",
"(",
"row",
")",
"ret... | Return a CSV representation as a string | [
"Return",
"a",
"CSV",
"representation",
"as",
"a",
"string"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L801-L811 | train | 53,876 |
Metatab/metatab | metatab/doc.py | MetatabDoc.as_lines | def as_lines(self):
"""Return a Lines representation as a string"""
out_lines = []
for t,v in self.lines:
# Make the output prettier
if t == 'Section':
out_lines.append('')
out_lines.append('{}: {}'.format(t,v if v is not None else '') )
return '\n'.join(out_lines) | python | def as_lines(self):
"""Return a Lines representation as a string"""
out_lines = []
for t,v in self.lines:
# Make the output prettier
if t == 'Section':
out_lines.append('')
out_lines.append('{}: {}'.format(t,v if v is not None else '') )
return '\n'.join(out_lines) | [
"def",
"as_lines",
"(",
"self",
")",
":",
"out_lines",
"=",
"[",
"]",
"for",
"t",
",",
"v",
"in",
"self",
".",
"lines",
":",
"# Make the output prettier",
"if",
"t",
"==",
"'Section'",
":",
"out_lines",
".",
"append",
"(",
"''",
")",
"out_lines",
".",
... | Return a Lines representation as a string | [
"Return",
"a",
"Lines",
"representation",
"as",
"a",
"string"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L813-L825 | train | 53,877 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/restructuring_visitor.py | _restructure_if_volume_follows_journal | def _restructure_if_volume_follows_journal(left, right):
"""Remove volume node if it follows a journal logically in the tree hierarchy.
Args:
left (ast.ASTElement): The journal KeywordOp node.
right (ast.ASTElement): The rest of the tree to be restructured.
Return:
(ast.ASTElement): The restructured tree, with the volume node removed.
Notes:
This happens to support queries like "journal Phys.Rev. and vol d85". Appends the value of KeywordOp with
Keyword 'volume' and discards 'volume' KeywordOp node from the tree.
"""
def _get_volume_keyword_op_and_remaining_subtree(right_subtree):
if isinstance(right_subtree, NotOp) and isinstance(right_subtree.op, KeywordOp) \
and right_subtree.op.left == Keyword('volume'):
return None, None
elif isinstance(right_subtree, AndOp) and isinstance(right_subtree.left, NotOp) \
and isinstance(right_subtree.left.op, KeywordOp) and right_subtree.left.op.left == Keyword('volume'):
return None, right_subtree.right
elif isinstance(right_subtree, KeywordOp) and right_subtree.left == Keyword('volume'):
return right_subtree, None
elif isinstance(right_subtree, AndOp) and right_subtree.left.left == Keyword('volume'):
return right_subtree.left, right_subtree.right
journal_value = left.right.value
volume_and_remaining_subtree = _get_volume_keyword_op_and_remaining_subtree(right)
if not volume_and_remaining_subtree:
return
volume_node, remaining_subtree = volume_and_remaining_subtree
if volume_node:
left.right.value = ','.join([journal_value, volume_node.right.value])
return AndOp(left, remaining_subtree) if remaining_subtree else left | python | def _restructure_if_volume_follows_journal(left, right):
"""Remove volume node if it follows a journal logically in the tree hierarchy.
Args:
left (ast.ASTElement): The journal KeywordOp node.
right (ast.ASTElement): The rest of the tree to be restructured.
Return:
(ast.ASTElement): The restructured tree, with the volume node removed.
Notes:
This happens to support queries like "journal Phys.Rev. and vol d85". Appends the value of KeywordOp with
Keyword 'volume' and discards 'volume' KeywordOp node from the tree.
"""
def _get_volume_keyword_op_and_remaining_subtree(right_subtree):
if isinstance(right_subtree, NotOp) and isinstance(right_subtree.op, KeywordOp) \
and right_subtree.op.left == Keyword('volume'):
return None, None
elif isinstance(right_subtree, AndOp) and isinstance(right_subtree.left, NotOp) \
and isinstance(right_subtree.left.op, KeywordOp) and right_subtree.left.op.left == Keyword('volume'):
return None, right_subtree.right
elif isinstance(right_subtree, KeywordOp) and right_subtree.left == Keyword('volume'):
return right_subtree, None
elif isinstance(right_subtree, AndOp) and right_subtree.left.left == Keyword('volume'):
return right_subtree.left, right_subtree.right
journal_value = left.right.value
volume_and_remaining_subtree = _get_volume_keyword_op_and_remaining_subtree(right)
if not volume_and_remaining_subtree:
return
volume_node, remaining_subtree = volume_and_remaining_subtree
if volume_node:
left.right.value = ','.join([journal_value, volume_node.right.value])
return AndOp(left, remaining_subtree) if remaining_subtree else left | [
"def",
"_restructure_if_volume_follows_journal",
"(",
"left",
",",
"right",
")",
":",
"def",
"_get_volume_keyword_op_and_remaining_subtree",
"(",
"right_subtree",
")",
":",
"if",
"isinstance",
"(",
"right_subtree",
",",
"NotOp",
")",
"and",
"isinstance",
"(",
"right_s... | Remove volume node if it follows a journal logically in the tree hierarchy.
Args:
left (ast.ASTElement): The journal KeywordOp node.
right (ast.ASTElement): The rest of the tree to be restructured.
Return:
(ast.ASTElement): The restructured tree, with the volume node removed.
Notes:
This happens to support queries like "journal Phys.Rev. and vol d85". Appends the value of KeywordOp with
Keyword 'volume' and discards 'volume' KeywordOp node from the tree. | [
"Remove",
"volume",
"node",
"if",
"it",
"follows",
"a",
"journal",
"logically",
"in",
"the",
"tree",
"hierarchy",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/restructuring_visitor.py#L48-L87 | train | 53,878 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/restructuring_visitor.py | _convert_simple_value_boolean_query_to_and_boolean_queries | def _convert_simple_value_boolean_query_to_and_boolean_queries(tree, keyword):
"""Chain SimpleValueBooleanQuery values into chained AndOp queries with the given current Keyword."""
def _create_operator_node(value_node):
"""Creates a KeywordOp or a ValueOp node."""
base_node = value_node.op if isinstance(value_node, NotOp) else value_node
updated_base_node = KeywordOp(keyword, base_node) if keyword else ValueOp(base_node)
return NotOp(updated_base_node) if isinstance(value_node, NotOp) else updated_base_node
def _get_bool_op_type(bool_op):
return AndOp if isinstance(bool_op, And) else OrOp
new_tree_root = _get_bool_op_type(tree.bool_op)(None, None)
current_tree = new_tree_root
previous_tree = tree
while True: # Walk down the tree while building the new AndOp queries subtree.
current_tree.left = _create_operator_node(previous_tree.left)
if not isinstance(previous_tree.right, SimpleValueBooleanQuery):
current_tree.right = _create_operator_node(previous_tree.right)
break
previous_tree = previous_tree.right
current_tree.right = _get_bool_op_type(previous_tree.bool_op)(None, None)
current_tree = current_tree.right
return new_tree_root | python | def _convert_simple_value_boolean_query_to_and_boolean_queries(tree, keyword):
"""Chain SimpleValueBooleanQuery values into chained AndOp queries with the given current Keyword."""
def _create_operator_node(value_node):
"""Creates a KeywordOp or a ValueOp node."""
base_node = value_node.op if isinstance(value_node, NotOp) else value_node
updated_base_node = KeywordOp(keyword, base_node) if keyword else ValueOp(base_node)
return NotOp(updated_base_node) if isinstance(value_node, NotOp) else updated_base_node
def _get_bool_op_type(bool_op):
return AndOp if isinstance(bool_op, And) else OrOp
new_tree_root = _get_bool_op_type(tree.bool_op)(None, None)
current_tree = new_tree_root
previous_tree = tree
while True: # Walk down the tree while building the new AndOp queries subtree.
current_tree.left = _create_operator_node(previous_tree.left)
if not isinstance(previous_tree.right, SimpleValueBooleanQuery):
current_tree.right = _create_operator_node(previous_tree.right)
break
previous_tree = previous_tree.right
current_tree.right = _get_bool_op_type(previous_tree.bool_op)(None, None)
current_tree = current_tree.right
return new_tree_root | [
"def",
"_convert_simple_value_boolean_query_to_and_boolean_queries",
"(",
"tree",
",",
"keyword",
")",
":",
"def",
"_create_operator_node",
"(",
"value_node",
")",
":",
"\"\"\"Creates a KeywordOp or a ValueOp node.\"\"\"",
"base_node",
"=",
"value_node",
".",
"op",
"if",
"i... | Chain SimpleValueBooleanQuery values into chained AndOp queries with the given current Keyword. | [
"Chain",
"SimpleValueBooleanQuery",
"values",
"into",
"chained",
"AndOp",
"queries",
"with",
"the",
"given",
"current",
"Keyword",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/restructuring_visitor.py#L90-L118 | train | 53,879 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/restructuring_visitor.py | RestructuringVisitor.visit_boolean_query | def visit_boolean_query(self, node):
"""Convert BooleanRule into AndOp or OrOp nodes."""
left = node.left.accept(self)
right = node.right.accept(self)
is_journal_keyword_op = isinstance(left, KeywordOp) and left.left == Keyword('journal')
if is_journal_keyword_op:
journal_and_volume_conjunction = _restructure_if_volume_follows_journal(left, right)
if journal_and_volume_conjunction:
return journal_and_volume_conjunction
return AndOp(left, right) if isinstance(node.bool_op, And) else OrOp(left, right) | python | def visit_boolean_query(self, node):
"""Convert BooleanRule into AndOp or OrOp nodes."""
left = node.left.accept(self)
right = node.right.accept(self)
is_journal_keyword_op = isinstance(left, KeywordOp) and left.left == Keyword('journal')
if is_journal_keyword_op:
journal_and_volume_conjunction = _restructure_if_volume_follows_journal(left, right)
if journal_and_volume_conjunction:
return journal_and_volume_conjunction
return AndOp(left, right) if isinstance(node.bool_op, And) else OrOp(left, right) | [
"def",
"visit_boolean_query",
"(",
"self",
",",
"node",
")",
":",
"left",
"=",
"node",
".",
"left",
".",
"accept",
"(",
"self",
")",
"right",
"=",
"node",
".",
"right",
".",
"accept",
"(",
"self",
")",
"is_journal_keyword_op",
"=",
"isinstance",
"(",
"... | Convert BooleanRule into AndOp or OrOp nodes. | [
"Convert",
"BooleanRule",
"into",
"AndOp",
"or",
"OrOp",
"nodes",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/restructuring_visitor.py#L160-L173 | train | 53,880 |
jreese/tasky | tasky/tasks/task.py | Task.stop | async def stop(self, force: bool=False) -> None:
'''Cancel the task if it hasn't yet started, or tell it to
gracefully stop running if it has.'''
Log.debug('stopping task %s', self.name)
self.running = False
if force:
self.task.cancel() | python | async def stop(self, force: bool=False) -> None:
'''Cancel the task if it hasn't yet started, or tell it to
gracefully stop running if it has.'''
Log.debug('stopping task %s', self.name)
self.running = False
if force:
self.task.cancel() | [
"async",
"def",
"stop",
"(",
"self",
",",
"force",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"Log",
".",
"debug",
"(",
"'stopping task %s'",
",",
"self",
".",
"name",
")",
"self",
".",
"running",
"=",
"False",
"if",
"force",
":",
"self",
"... | Cancel the task if it hasn't yet started, or tell it to
gracefully stop running if it has. | [
"Cancel",
"the",
"task",
"if",
"it",
"hasn",
"t",
"yet",
"started",
"or",
"tell",
"it",
"to",
"gracefully",
"stop",
"running",
"if",
"it",
"has",
"."
] | 681f4e5a9a60a0eb838b89f320309cfb45a56242 | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/tasks/task.py#L84-L92 | train | 53,881 |
inspirehep/inspire-query-parser | inspire_query_parser/utils/visitor_utils.py | author_name_contains_fullnames | def author_name_contains_fullnames(author_name):
"""Recognizes whether the name contains full name parts and not initials or only lastname.
Returns:
bool: True if name has only full name parts, e.g. 'Ellis John', False otherwise. So for example, False is
returned for 'Ellis, J.' or 'Ellis'.
"""
def _is_initial(name_part):
return len(name_part) == 1 or u'.' in name_part
parsed_name = ParsedName(author_name)
if len(parsed_name) == 1:
return False
elif any([_is_initial(name_part) for name_part in parsed_name]):
return False
return True | python | def author_name_contains_fullnames(author_name):
"""Recognizes whether the name contains full name parts and not initials or only lastname.
Returns:
bool: True if name has only full name parts, e.g. 'Ellis John', False otherwise. So for example, False is
returned for 'Ellis, J.' or 'Ellis'.
"""
def _is_initial(name_part):
return len(name_part) == 1 or u'.' in name_part
parsed_name = ParsedName(author_name)
if len(parsed_name) == 1:
return False
elif any([_is_initial(name_part) for name_part in parsed_name]):
return False
return True | [
"def",
"author_name_contains_fullnames",
"(",
"author_name",
")",
":",
"def",
"_is_initial",
"(",
"name_part",
")",
":",
"return",
"len",
"(",
"name_part",
")",
"==",
"1",
"or",
"u'.'",
"in",
"name_part",
"parsed_name",
"=",
"ParsedName",
"(",
"author_name",
"... | Recognizes whether the name contains full name parts and not initials or only lastname.
Returns:
bool: True if name has only full name parts, e.g. 'Ellis John', False otherwise. So for example, False is
returned for 'Ellis, J.' or 'Ellis'. | [
"Recognizes",
"whether",
"the",
"name",
"contains",
"full",
"name",
"parts",
"and",
"not",
"initials",
"or",
"only",
"lastname",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L45-L62 | train | 53,882 |
inspirehep/inspire-query-parser | inspire_query_parser/utils/visitor_utils.py | _name_variation_has_only_initials | def _name_variation_has_only_initials(name):
"""Detects whether the name variation consists only from initials."""
def _is_initial(name_variation):
return len(name_variation) == 1 or u'.' in name_variation
parsed_name = ParsedName.loads(name)
return all([_is_initial(name_part) for name_part in parsed_name]) | python | def _name_variation_has_only_initials(name):
"""Detects whether the name variation consists only from initials."""
def _is_initial(name_variation):
return len(name_variation) == 1 or u'.' in name_variation
parsed_name = ParsedName.loads(name)
return all([_is_initial(name_part) for name_part in parsed_name]) | [
"def",
"_name_variation_has_only_initials",
"(",
"name",
")",
":",
"def",
"_is_initial",
"(",
"name_variation",
")",
":",
"return",
"len",
"(",
"name_variation",
")",
"==",
"1",
"or",
"u'.'",
"in",
"name_variation",
"parsed_name",
"=",
"ParsedName",
".",
"loads"... | Detects whether the name variation consists only from initials. | [
"Detects",
"whether",
"the",
"name",
"variation",
"consists",
"only",
"from",
"initials",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L65-L72 | train | 53,883 |
inspirehep/inspire-query-parser | inspire_query_parser/utils/visitor_utils.py | generate_minimal_name_variations | def generate_minimal_name_variations(author_name):
"""Generate a small number of name variations.
Notes:
Unidecodes the name, so that we use its transliterated version, since this is how the field is being indexed.
For names with more than one part, {lastname} x {non lastnames, non lastnames initial} variations.
Additionally, it generates the swapped version of those, for supporting queries like ``Mele Salvatore`` which
``ParsedName`` parses as lastname: Salvatore and firstname: Mele. So in those cases, we need to generate both
``Mele, Salvatore`` and ``Mele, S``.
Wherever, the '-' is replaced by ' ', it's done because it's the way the name variations are being index, thus
we want our minimal name variations to be generated identically. This has to be done after the creation of
ParsedName, otherwise the name is parsed differently. E.g. 'Caro-Estevez' as is, it's a lastname, if we replace
the '-' with ' ', then it's a firstname and lastname.
"""
parsed_name = ParsedName.loads(unidecode(author_name))
if len(parsed_name) > 1:
lastnames = parsed_name.last.replace('-', ' ')
non_lastnames = ' '.join(
parsed_name.first_list + parsed_name.suffix_list
)
# Strip extra whitespace added if any of middle_list and suffix_list are empty.
non_lastnames = non_lastnames.strip().replace('-', ' ')
# Adding into a set first, so as to drop identical name variations.
return list({
name_variation.lower()
for name_variation
in [
lastnames + ' ' + non_lastnames,
lastnames + ' ' + non_lastnames[0],
non_lastnames + ' ' + lastnames,
non_lastnames + ' ' + lastnames[0],
]
if not _name_variation_has_only_initials(name_variation)
})
else:
return [parsed_name.dumps().replace('-', ' ').lower()] | python | def generate_minimal_name_variations(author_name):
"""Generate a small number of name variations.
Notes:
Unidecodes the name, so that we use its transliterated version, since this is how the field is being indexed.
For names with more than one part, {lastname} x {non lastnames, non lastnames initial} variations.
Additionally, it generates the swapped version of those, for supporting queries like ``Mele Salvatore`` which
``ParsedName`` parses as lastname: Salvatore and firstname: Mele. So in those cases, we need to generate both
``Mele, Salvatore`` and ``Mele, S``.
Wherever, the '-' is replaced by ' ', it's done because it's the way the name variations are being index, thus
we want our minimal name variations to be generated identically. This has to be done after the creation of
ParsedName, otherwise the name is parsed differently. E.g. 'Caro-Estevez' as is, it's a lastname, if we replace
the '-' with ' ', then it's a firstname and lastname.
"""
parsed_name = ParsedName.loads(unidecode(author_name))
if len(parsed_name) > 1:
lastnames = parsed_name.last.replace('-', ' ')
non_lastnames = ' '.join(
parsed_name.first_list + parsed_name.suffix_list
)
# Strip extra whitespace added if any of middle_list and suffix_list are empty.
non_lastnames = non_lastnames.strip().replace('-', ' ')
# Adding into a set first, so as to drop identical name variations.
return list({
name_variation.lower()
for name_variation
in [
lastnames + ' ' + non_lastnames,
lastnames + ' ' + non_lastnames[0],
non_lastnames + ' ' + lastnames,
non_lastnames + ' ' + lastnames[0],
]
if not _name_variation_has_only_initials(name_variation)
})
else:
return [parsed_name.dumps().replace('-', ' ').lower()] | [
"def",
"generate_minimal_name_variations",
"(",
"author_name",
")",
":",
"parsed_name",
"=",
"ParsedName",
".",
"loads",
"(",
"unidecode",
"(",
"author_name",
")",
")",
"if",
"len",
"(",
"parsed_name",
")",
">",
"1",
":",
"lastnames",
"=",
"parsed_name",
".",
... | Generate a small number of name variations.
Notes:
Unidecodes the name, so that we use its transliterated version, since this is how the field is being indexed.
For names with more than one part, {lastname} x {non lastnames, non lastnames initial} variations.
Additionally, it generates the swapped version of those, for supporting queries like ``Mele Salvatore`` which
``ParsedName`` parses as lastname: Salvatore and firstname: Mele. So in those cases, we need to generate both
``Mele, Salvatore`` and ``Mele, S``.
Wherever, the '-' is replaced by ' ', it's done because it's the way the name variations are being index, thus
we want our minimal name variations to be generated identically. This has to be done after the creation of
ParsedName, otherwise the name is parsed differently. E.g. 'Caro-Estevez' as is, it's a lastname, if we replace
the '-' with ' ', then it's a firstname and lastname. | [
"Generate",
"a",
"small",
"number",
"of",
"name",
"variations",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L75-L115 | train | 53,884 |
inspirehep/inspire-query-parser | inspire_query_parser/utils/visitor_utils.py | register_date_conversion_handler | def register_date_conversion_handler(date_specifier_patterns):
"""Decorator for registering handlers that convert text dates to dates.
Args:
date_specifier_patterns (str): the date specifier (in regex pattern format) for which the handler is registered
"""
def _decorator(func):
global DATE_SPECIFIERS_CONVERSION_HANDLERS
DATE_SPECIFIERS_CONVERSION_HANDLERS[DATE_SPECIFIERS_REGEXES[date_specifier_patterns]] = func
return func
return _decorator | python | def register_date_conversion_handler(date_specifier_patterns):
"""Decorator for registering handlers that convert text dates to dates.
Args:
date_specifier_patterns (str): the date specifier (in regex pattern format) for which the handler is registered
"""
def _decorator(func):
global DATE_SPECIFIERS_CONVERSION_HANDLERS
DATE_SPECIFIERS_CONVERSION_HANDLERS[DATE_SPECIFIERS_REGEXES[date_specifier_patterns]] = func
return func
return _decorator | [
"def",
"register_date_conversion_handler",
"(",
"date_specifier_patterns",
")",
":",
"def",
"_decorator",
"(",
"func",
")",
":",
"global",
"DATE_SPECIFIERS_CONVERSION_HANDLERS",
"DATE_SPECIFIERS_CONVERSION_HANDLERS",
"[",
"DATE_SPECIFIERS_REGEXES",
"[",
"date_specifier_patterns",... | Decorator for registering handlers that convert text dates to dates.
Args:
date_specifier_patterns (str): the date specifier (in regex pattern format) for which the handler is registered | [
"Decorator",
"for",
"registering",
"handlers",
"that",
"convert",
"text",
"dates",
"to",
"dates",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L139-L151 | train | 53,885 |
inspirehep/inspire-query-parser | inspire_query_parser/utils/visitor_utils.py | _truncate_wildcard_from_date | def _truncate_wildcard_from_date(date_value):
"""Truncate wildcard from date parts.
Returns:
(str) The truncated date.
Raises:
ValueError, on either unsupported date separator (currently only ' ' and '-' are supported), or if there's a
wildcard in the year.
Notes:
Either whole date part is wildcard, in which we ignore it and do a range query on the
remaining parts, or some numbers are wildcards, where again, we ignore this part.
"""
if ' ' in date_value:
date_parts = date_value.split(' ')
elif '-' in date_value:
date_parts = date_value.split('-')
else:
# Either unsupported separators or wildcard in year, e.g. '201*'.
raise ValueError("Erroneous date value: %s.", date_value)
if GenericValue.WILDCARD_TOKEN in date_parts[-1]:
del date_parts[-1]
return '-'.join(date_parts) | python | def _truncate_wildcard_from_date(date_value):
"""Truncate wildcard from date parts.
Returns:
(str) The truncated date.
Raises:
ValueError, on either unsupported date separator (currently only ' ' and '-' are supported), or if there's a
wildcard in the year.
Notes:
Either whole date part is wildcard, in which we ignore it and do a range query on the
remaining parts, or some numbers are wildcards, where again, we ignore this part.
"""
if ' ' in date_value:
date_parts = date_value.split(' ')
elif '-' in date_value:
date_parts = date_value.split('-')
else:
# Either unsupported separators or wildcard in year, e.g. '201*'.
raise ValueError("Erroneous date value: %s.", date_value)
if GenericValue.WILDCARD_TOKEN in date_parts[-1]:
del date_parts[-1]
return '-'.join(date_parts) | [
"def",
"_truncate_wildcard_from_date",
"(",
"date_value",
")",
":",
"if",
"' '",
"in",
"date_value",
":",
"date_parts",
"=",
"date_value",
".",
"split",
"(",
"' '",
")",
"elif",
"'-'",
"in",
"date_value",
":",
"date_parts",
"=",
"date_value",
".",
"split",
"... | Truncate wildcard from date parts.
Returns:
(str) The truncated date.
Raises:
ValueError, on either unsupported date separator (currently only ' ' and '-' are supported), or if there's a
wildcard in the year.
Notes:
Either whole date part is wildcard, in which we ignore it and do a range query on the
remaining parts, or some numbers are wildcards, where again, we ignore this part. | [
"Truncate",
"wildcard",
"from",
"date",
"parts",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L226-L251 | train | 53,886 |
inspirehep/inspire-query-parser | inspire_query_parser/utils/visitor_utils.py | _get_next_date_from_partial_date | def _get_next_date_from_partial_date(partial_date):
"""Calculates the next date from the given partial date.
Args:
partial_date (inspire_utils.date.PartialDate): The partial date whose next date should be calculated.
Returns:
PartialDate: The next date from the given partial date.
"""
relativedelta_arg = 'years'
if partial_date.month:
relativedelta_arg = 'months'
if partial_date.day:
relativedelta_arg = 'days'
next_date = parse(partial_date.dumps()) + relativedelta(**{relativedelta_arg: 1})
return PartialDate.from_parts(
next_date.year,
next_date.month if partial_date.month else None,
next_date.day if partial_date.day else None
) | python | def _get_next_date_from_partial_date(partial_date):
"""Calculates the next date from the given partial date.
Args:
partial_date (inspire_utils.date.PartialDate): The partial date whose next date should be calculated.
Returns:
PartialDate: The next date from the given partial date.
"""
relativedelta_arg = 'years'
if partial_date.month:
relativedelta_arg = 'months'
if partial_date.day:
relativedelta_arg = 'days'
next_date = parse(partial_date.dumps()) + relativedelta(**{relativedelta_arg: 1})
return PartialDate.from_parts(
next_date.year,
next_date.month if partial_date.month else None,
next_date.day if partial_date.day else None
) | [
"def",
"_get_next_date_from_partial_date",
"(",
"partial_date",
")",
":",
"relativedelta_arg",
"=",
"'years'",
"if",
"partial_date",
".",
"month",
":",
"relativedelta_arg",
"=",
"'months'",
"if",
"partial_date",
".",
"day",
":",
"relativedelta_arg",
"=",
"'days'",
"... | Calculates the next date from the given partial date.
Args:
partial_date (inspire_utils.date.PartialDate): The partial date whose next date should be calculated.
Returns:
PartialDate: The next date from the given partial date. | [
"Calculates",
"the",
"next",
"date",
"from",
"the",
"given",
"partial",
"date",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L282-L303 | train | 53,887 |
inspirehep/inspire-query-parser | inspire_query_parser/utils/visitor_utils.py | _get_proper_elastic_search_date_rounding_format | def _get_proper_elastic_search_date_rounding_format(partial_date):
"""Returns the proper ES date math unit according to the "resolution" of the partial_date.
Args:
partial_date (PartialDate): The partial date for which the date math unit is.
Returns:
(str): The ES date math unit format.
Notes:
This is needed for supporting range queries on dates, i.e. rounding them up or down according to
the ES range operator.
For example, without this, a query like 'date > 2010-11', would return documents with date '2010-11-15', due to
the date value of the query being interpreted by ES as '2010-11-01 01:00:00'. By using the suffixes for rounding
up or down, the date value of the query is interpreted as '2010-11-30T23:59:59.999', thus not returning the
document with date '2010-11-15', as the user would expect. See:
https://www.elastic.co/guide/en/elasticsearch/reference/6.1/query-dsl-range-query.html#_date_math_and_rounding
"""
es_date_math_unit = ES_DATE_MATH_ROUNDING_YEAR
if partial_date.month:
es_date_math_unit = ES_DATE_MATH_ROUNDING_MONTH
if partial_date.day:
es_date_math_unit = ES_DATE_MATH_ROUNDING_DAY
return es_date_math_unit | python | def _get_proper_elastic_search_date_rounding_format(partial_date):
"""Returns the proper ES date math unit according to the "resolution" of the partial_date.
Args:
partial_date (PartialDate): The partial date for which the date math unit is.
Returns:
(str): The ES date math unit format.
Notes:
This is needed for supporting range queries on dates, i.e. rounding them up or down according to
the ES range operator.
For example, without this, a query like 'date > 2010-11', would return documents with date '2010-11-15', due to
the date value of the query being interpreted by ES as '2010-11-01 01:00:00'. By using the suffixes for rounding
up or down, the date value of the query is interpreted as '2010-11-30T23:59:59.999', thus not returning the
document with date '2010-11-15', as the user would expect. See:
https://www.elastic.co/guide/en/elasticsearch/reference/6.1/query-dsl-range-query.html#_date_math_and_rounding
"""
es_date_math_unit = ES_DATE_MATH_ROUNDING_YEAR
if partial_date.month:
es_date_math_unit = ES_DATE_MATH_ROUNDING_MONTH
if partial_date.day:
es_date_math_unit = ES_DATE_MATH_ROUNDING_DAY
return es_date_math_unit | [
"def",
"_get_proper_elastic_search_date_rounding_format",
"(",
"partial_date",
")",
":",
"es_date_math_unit",
"=",
"ES_DATE_MATH_ROUNDING_YEAR",
"if",
"partial_date",
".",
"month",
":",
"es_date_math_unit",
"=",
"ES_DATE_MATH_ROUNDING_MONTH",
"if",
"partial_date",
".",
"day",... | Returns the proper ES date math unit according to the "resolution" of the partial_date.
Args:
partial_date (PartialDate): The partial date for which the date math unit is.
Returns:
(str): The ES date math unit format.
Notes:
This is needed for supporting range queries on dates, i.e. rounding them up or down according to
the ES range operator.
For example, without this, a query like 'date > 2010-11', would return documents with date '2010-11-15', due to
the date value of the query being interpreted by ES as '2010-11-01 01:00:00'. By using the suffixes for rounding
up or down, the date value of the query is interpreted as '2010-11-30T23:59:59.999', thus not returning the
document with date '2010-11-15', as the user would expect. See:
https://www.elastic.co/guide/en/elasticsearch/reference/6.1/query-dsl-range-query.html#_date_math_and_rounding | [
"Returns",
"the",
"proper",
"ES",
"date",
"math",
"unit",
"according",
"to",
"the",
"resolution",
"of",
"the",
"partial_date",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L306-L331 | train | 53,888 |
inspirehep/inspire-query-parser | inspire_query_parser/utils/visitor_utils.py | generate_match_query | def generate_match_query(field, value, with_operator_and):
"""Helper for generating a match query.
Args:
field (six.text_type): The ES field to be queried.
value (six.text_type/bool): The value of the query (bool for the case of type-code query ["core: true"]).
with_operator_and (bool): Flag that signifies whether to generate the explicit notation of the query, along
with '"operator": "and"', so that all tokens of the query value are required to match.
Notes:
If value is of instance bool, then the shortened version of the match query is generated, at all times.
"""
parsed_value = None
try:
parsed_value = json.loads(value.lower())
except (ValueError, TypeError, AttributeError):
# Catch all possible exceptions
# we are not interested if they will appear
pass
if isinstance(value, bool):
return {'match': {field: value}}
elif isinstance(parsed_value, bool):
return {'match': {field: value.lower()}}
if with_operator_and:
return {
'match': {
field: {
'query': value,
'operator': 'and'
}
}
}
return {'match': {field: value}} | python | def generate_match_query(field, value, with_operator_and):
"""Helper for generating a match query.
Args:
field (six.text_type): The ES field to be queried.
value (six.text_type/bool): The value of the query (bool for the case of type-code query ["core: true"]).
with_operator_and (bool): Flag that signifies whether to generate the explicit notation of the query, along
with '"operator": "and"', so that all tokens of the query value are required to match.
Notes:
If value is of instance bool, then the shortened version of the match query is generated, at all times.
"""
parsed_value = None
try:
parsed_value = json.loads(value.lower())
except (ValueError, TypeError, AttributeError):
# Catch all possible exceptions
# we are not interested if they will appear
pass
if isinstance(value, bool):
return {'match': {field: value}}
elif isinstance(parsed_value, bool):
return {'match': {field: value.lower()}}
if with_operator_and:
return {
'match': {
field: {
'query': value,
'operator': 'and'
}
}
}
return {'match': {field: value}} | [
"def",
"generate_match_query",
"(",
"field",
",",
"value",
",",
"with_operator_and",
")",
":",
"parsed_value",
"=",
"None",
"try",
":",
"parsed_value",
"=",
"json",
".",
"loads",
"(",
"value",
".",
"lower",
"(",
")",
")",
"except",
"(",
"ValueError",
",",
... | Helper for generating a match query.
Args:
field (six.text_type): The ES field to be queried.
value (six.text_type/bool): The value of the query (bool for the case of type-code query ["core: true"]).
with_operator_and (bool): Flag that signifies whether to generate the explicit notation of the query, along
with '"operator": "and"', so that all tokens of the query value are required to match.
Notes:
If value is of instance bool, then the shortened version of the match query is generated, at all times. | [
"Helper",
"for",
"generating",
"a",
"match",
"query",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L367-L402 | train | 53,889 |
inspirehep/inspire-query-parser | inspire_query_parser/utils/visitor_utils.py | wrap_query_in_nested_if_field_is_nested | def wrap_query_in_nested_if_field_is_nested(query, field, nested_fields):
"""Helper for wrapping a query into a nested if the fields within the query are nested
Args:
query : The query to be wrapped.
field : The field that is being queried.
nested_fields : List of fields which are nested.
Returns:
(dict): The nested query
"""
for element in nested_fields:
match_pattern = r'^{}.'.format(element)
if re.match(match_pattern, field):
return generate_nested_query(element, query)
return query | python | def wrap_query_in_nested_if_field_is_nested(query, field, nested_fields):
"""Helper for wrapping a query into a nested if the fields within the query are nested
Args:
query : The query to be wrapped.
field : The field that is being queried.
nested_fields : List of fields which are nested.
Returns:
(dict): The nested query
"""
for element in nested_fields:
match_pattern = r'^{}.'.format(element)
if re.match(match_pattern, field):
return generate_nested_query(element, query)
return query | [
"def",
"wrap_query_in_nested_if_field_is_nested",
"(",
"query",
",",
"field",
",",
"nested_fields",
")",
":",
"for",
"element",
"in",
"nested_fields",
":",
"match_pattern",
"=",
"r'^{}.'",
".",
"format",
"(",
"element",
")",
"if",
"re",
".",
"match",
"(",
"mat... | Helper for wrapping a query into a nested if the fields within the query are nested
Args:
query : The query to be wrapped.
field : The field that is being queried.
nested_fields : List of fields which are nested.
Returns:
(dict): The nested query | [
"Helper",
"for",
"wrapping",
"a",
"query",
"into",
"a",
"nested",
"if",
"the",
"fields",
"within",
"the",
"query",
"are",
"nested"
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L451-L466 | train | 53,890 |
praekeltfoundation/seed-stage-based-messaging | subscriptions/management/commands/remove_duplicate_subscriptions.py | Command.is_within_limits | def is_within_limits(self, limit, date, dates):
"""
Returns True if the difference between date and any value in dates
is less than or equal to limit.
"""
return any((self.second_diff(date, d) <= limit for d in dates)) | python | def is_within_limits(self, limit, date, dates):
"""
Returns True if the difference between date and any value in dates
is less than or equal to limit.
"""
return any((self.second_diff(date, d) <= limit for d in dates)) | [
"def",
"is_within_limits",
"(",
"self",
",",
"limit",
",",
"date",
",",
"dates",
")",
":",
"return",
"any",
"(",
"(",
"self",
".",
"second_diff",
"(",
"date",
",",
"d",
")",
"<=",
"limit",
"for",
"d",
"in",
"dates",
")",
")"
] | Returns True if the difference between date and any value in dates
is less than or equal to limit. | [
"Returns",
"True",
"if",
"the",
"difference",
"between",
"date",
"and",
"any",
"value",
"in",
"dates",
"is",
"less",
"than",
"or",
"equal",
"to",
"limit",
"."
] | 6f0cacf0727ac2ed19877de214d58009c685b8fa | https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/subscriptions/management/commands/remove_duplicate_subscriptions.py#L79-L84 | train | 53,891 |
inspirehep/inspire-query-parser | inspire_query_parser/utils/format_parse_tree.py | emit_tree_format | def emit_tree_format(tree, verbose=False):
"""Returns a tree representation of a parse tree.
Arguments:
tree: the parse tree whose tree representation is to be generated
verbose (bool): if True prints the parse tree to be formatted
Returns:
str: tree-like representation of the parse tree
"""
if verbose:
print("Converting: " + repr(tree))
ret_str = __recursive_formatter(tree)
return ret_str | python | def emit_tree_format(tree, verbose=False):
"""Returns a tree representation of a parse tree.
Arguments:
tree: the parse tree whose tree representation is to be generated
verbose (bool): if True prints the parse tree to be formatted
Returns:
str: tree-like representation of the parse tree
"""
if verbose:
print("Converting: " + repr(tree))
ret_str = __recursive_formatter(tree)
return ret_str | [
"def",
"emit_tree_format",
"(",
"tree",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"\"Converting: \"",
"+",
"repr",
"(",
"tree",
")",
")",
"ret_str",
"=",
"__recursive_formatter",
"(",
"tree",
")",
"return",
"ret_str"
] | Returns a tree representation of a parse tree.
Arguments:
tree: the parse tree whose tree representation is to be generated
verbose (bool): if True prints the parse tree to be formatted
Returns:
str: tree-like representation of the parse tree | [
"Returns",
"a",
"tree",
"representation",
"of",
"a",
"parse",
"tree",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/format_parse_tree.py#L34-L47 | train | 53,892 |
praekeltfoundation/seed-stage-based-messaging | seed_stage_based_messaging/utils.py | calculate_retry_delay | def calculate_retry_delay(attempt, max_delay=300):
"""Calculates an exponential backoff for retry attempts with a small
amount of jitter."""
delay = int(random.uniform(2, 4) ** attempt)
if delay > max_delay:
# After reaching the max delay, stop using expontential growth
# and keep the delay nearby the max.
delay = int(random.uniform(max_delay - 20, max_delay + 20))
return delay | python | def calculate_retry_delay(attempt, max_delay=300):
"""Calculates an exponential backoff for retry attempts with a small
amount of jitter."""
delay = int(random.uniform(2, 4) ** attempt)
if delay > max_delay:
# After reaching the max delay, stop using expontential growth
# and keep the delay nearby the max.
delay = int(random.uniform(max_delay - 20, max_delay + 20))
return delay | [
"def",
"calculate_retry_delay",
"(",
"attempt",
",",
"max_delay",
"=",
"300",
")",
":",
"delay",
"=",
"int",
"(",
"random",
".",
"uniform",
"(",
"2",
",",
"4",
")",
"**",
"attempt",
")",
"if",
"delay",
">",
"max_delay",
":",
"# After reaching the max delay... | Calculates an exponential backoff for retry attempts with a small
amount of jitter. | [
"Calculates",
"an",
"exponential",
"backoff",
"for",
"retry",
"attempts",
"with",
"a",
"small",
"amount",
"of",
"jitter",
"."
] | 6f0cacf0727ac2ed19877de214d58009c685b8fa | https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/seed_stage_based_messaging/utils.py#L52-L60 | train | 53,893 |
inspirehep/inspire-query-parser | inspire_query_parser/parsing_driver.py | parse_query | def parse_query(query_str):
"""
Drives the whole logic, by parsing, restructuring and finally, generating an ElasticSearch query.
Args:
query_str (six.text_types): the given query to be translated to an ElasticSearch query
Returns:
six.text_types: Return an ElasticSearch query.
Notes:
In case there's an error, an ElasticSearch `multi_match` query is generated with its `query` value, being the
query_str argument.
"""
def _generate_match_all_fields_query():
# Strip colon character (special character for ES)
stripped_query_str = ' '.join(query_str.replace(':', ' ').split())
return {'multi_match': {'query': stripped_query_str, 'fields': ['_all'], 'zero_terms_query': 'all'}}
if not isinstance(query_str, six.text_type):
query_str = six.text_type(query_str.decode('utf-8'))
logger.info('Parsing: "' + query_str + '\".')
parser = StatefulParser()
rst_visitor = RestructuringVisitor()
es_visitor = ElasticSearchVisitor()
try:
unrecognized_text, parse_tree = parser.parse(query_str, Query)
if unrecognized_text: # Usually, should never happen.
msg = 'Parser returned unrecognized text: "' + unrecognized_text + \
'" for query: "' + query_str + '".'
if query_str == unrecognized_text and parse_tree is None:
# Didn't recognize anything.
logger.warn(msg)
return _generate_match_all_fields_query()
else:
msg += 'Continuing with recognized parse tree.'
logger.warn(msg)
except SyntaxError as e:
logger.warn('Parser syntax error (' + six.text_type(e) + ') with query: "' + query_str +
'". Continuing with a match_all with the given query.')
return _generate_match_all_fields_query()
# Try-Catch-all exceptions for visitors, so that search functionality never fails for the user.
try:
restructured_parse_tree = parse_tree.accept(rst_visitor)
logger.debug('Parse tree: \n' + emit_tree_format(restructured_parse_tree))
except Exception as e:
logger.exception(
RestructuringVisitor.__name__ + " crashed" + (": " + six.text_type(e) + ".") if six.text_type(e) else '.'
)
return _generate_match_all_fields_query()
try:
es_query = restructured_parse_tree.accept(es_visitor)
except Exception as e:
logger.exception(
ElasticSearchVisitor.__name__ + " crashed" + (": " + six.text_type(e) + ".") if six.text_type(e) else '.'
)
return _generate_match_all_fields_query()
if not es_query:
# Case where an empty query was generated (i.e. date query with malformed date, e.g. "d < 200").
return _generate_match_all_fields_query()
return es_query | python | def parse_query(query_str):
"""
Drives the whole logic, by parsing, restructuring and finally, generating an ElasticSearch query.
Args:
query_str (six.text_types): the given query to be translated to an ElasticSearch query
Returns:
six.text_types: Return an ElasticSearch query.
Notes:
In case there's an error, an ElasticSearch `multi_match` query is generated with its `query` value, being the
query_str argument.
"""
def _generate_match_all_fields_query():
# Strip colon character (special character for ES)
stripped_query_str = ' '.join(query_str.replace(':', ' ').split())
return {'multi_match': {'query': stripped_query_str, 'fields': ['_all'], 'zero_terms_query': 'all'}}
if not isinstance(query_str, six.text_type):
query_str = six.text_type(query_str.decode('utf-8'))
logger.info('Parsing: "' + query_str + '\".')
parser = StatefulParser()
rst_visitor = RestructuringVisitor()
es_visitor = ElasticSearchVisitor()
try:
unrecognized_text, parse_tree = parser.parse(query_str, Query)
if unrecognized_text: # Usually, should never happen.
msg = 'Parser returned unrecognized text: "' + unrecognized_text + \
'" for query: "' + query_str + '".'
if query_str == unrecognized_text and parse_tree is None:
# Didn't recognize anything.
logger.warn(msg)
return _generate_match_all_fields_query()
else:
msg += 'Continuing with recognized parse tree.'
logger.warn(msg)
except SyntaxError as e:
logger.warn('Parser syntax error (' + six.text_type(e) + ') with query: "' + query_str +
'". Continuing with a match_all with the given query.')
return _generate_match_all_fields_query()
# Try-Catch-all exceptions for visitors, so that search functionality never fails for the user.
try:
restructured_parse_tree = parse_tree.accept(rst_visitor)
logger.debug('Parse tree: \n' + emit_tree_format(restructured_parse_tree))
except Exception as e:
logger.exception(
RestructuringVisitor.__name__ + " crashed" + (": " + six.text_type(e) + ".") if six.text_type(e) else '.'
)
return _generate_match_all_fields_query()
try:
es_query = restructured_parse_tree.accept(es_visitor)
except Exception as e:
logger.exception(
ElasticSearchVisitor.__name__ + " crashed" + (": " + six.text_type(e) + ".") if six.text_type(e) else '.'
)
return _generate_match_all_fields_query()
if not es_query:
# Case where an empty query was generated (i.e. date query with malformed date, e.g. "d < 200").
return _generate_match_all_fields_query()
return es_query | [
"def",
"parse_query",
"(",
"query_str",
")",
":",
"def",
"_generate_match_all_fields_query",
"(",
")",
":",
"# Strip colon character (special character for ES)",
"stripped_query_str",
"=",
"' '",
".",
"join",
"(",
"query_str",
".",
"replace",
"(",
"':'",
",",
"' '",
... | Drives the whole logic, by parsing, restructuring and finally, generating an ElasticSearch query.
Args:
query_str (six.text_types): the given query to be translated to an ElasticSearch query
Returns:
six.text_types: Return an ElasticSearch query.
Notes:
In case there's an error, an ElasticSearch `multi_match` query is generated with its `query` value, being the
query_str argument. | [
"Drives",
"the",
"whole",
"logic",
"by",
"parsing",
"restructuring",
"and",
"finally",
"generating",
"an",
"ElasticSearch",
"query",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/parsing_driver.py#L42-L113 | train | 53,894 |
jreese/tasky | tasky/loop.py | Tasky.task | def task(self, name_or_class: Any) -> Task:
'''Return a running Task object matching the given name or class.'''
if name_or_class in self.all_tasks:
return self.all_tasks[name_or_class]
try:
return self.all_tasks.get(name_or_class.__class__.__name__, None)
except AttributeError:
return None | python | def task(self, name_or_class: Any) -> Task:
'''Return a running Task object matching the given name or class.'''
if name_or_class in self.all_tasks:
return self.all_tasks[name_or_class]
try:
return self.all_tasks.get(name_or_class.__class__.__name__, None)
except AttributeError:
return None | [
"def",
"task",
"(",
"self",
",",
"name_or_class",
":",
"Any",
")",
"->",
"Task",
":",
"if",
"name_or_class",
"in",
"self",
".",
"all_tasks",
":",
"return",
"self",
".",
"all_tasks",
"[",
"name_or_class",
"]",
"try",
":",
"return",
"self",
".",
"all_tasks... | Return a running Task object matching the given name or class. | [
"Return",
"a",
"running",
"Task",
"object",
"matching",
"the",
"given",
"name",
"or",
"class",
"."
] | 681f4e5a9a60a0eb838b89f320309cfb45a56242 | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L79-L89 | train | 53,895 |
jreese/tasky | tasky/loop.py | Tasky.init | async def init(self) -> None:
'''Initialize configuration and start tasks.'''
self.stats = await self.insert(self.stats)
self.configuration = await self.insert(self.configuration)
if not self.executor:
try:
max_workers = self.config.get('executor_workers')
except Exception:
max_workers = None
self.executor = ThreadPoolExecutor(max_workers=max_workers)
for task in self.initial_tasks:
await self.insert(task)
self.monitor = asyncio.ensure_future(self.monitor_tasks())
self.counters['alive_since'] = time.time() | python | async def init(self) -> None:
'''Initialize configuration and start tasks.'''
self.stats = await self.insert(self.stats)
self.configuration = await self.insert(self.configuration)
if not self.executor:
try:
max_workers = self.config.get('executor_workers')
except Exception:
max_workers = None
self.executor = ThreadPoolExecutor(max_workers=max_workers)
for task in self.initial_tasks:
await self.insert(task)
self.monitor = asyncio.ensure_future(self.monitor_tasks())
self.counters['alive_since'] = time.time() | [
"async",
"def",
"init",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"stats",
"=",
"await",
"self",
".",
"insert",
"(",
"self",
".",
"stats",
")",
"self",
".",
"configuration",
"=",
"await",
"self",
".",
"insert",
"(",
"self",
".",
"configuratio... | Initialize configuration and start tasks. | [
"Initialize",
"configuration",
"and",
"start",
"tasks",
"."
] | 681f4e5a9a60a0eb838b89f320309cfb45a56242 | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L91-L109 | train | 53,896 |
jreese/tasky | tasky/loop.py | Tasky.insert | async def insert(self, task: Task) -> None:
'''Insert the given task class into the Tasky event loop.'''
if not isinstance(task, Task):
task = task()
if task.name not in self.all_tasks:
task.tasky = self
self.all_tasks[task.name] = task
await task.init()
elif task != self.all_tasks[task.name]:
raise Exception('Duplicate task %s' % task.name)
if task.enabled:
task.task = asyncio.ensure_future(self.start_task(task))
self.running_tasks.add(task)
else:
task.task = None
return task | python | async def insert(self, task: Task) -> None:
'''Insert the given task class into the Tasky event loop.'''
if not isinstance(task, Task):
task = task()
if task.name not in self.all_tasks:
task.tasky = self
self.all_tasks[task.name] = task
await task.init()
elif task != self.all_tasks[task.name]:
raise Exception('Duplicate task %s' % task.name)
if task.enabled:
task.task = asyncio.ensure_future(self.start_task(task))
self.running_tasks.add(task)
else:
task.task = None
return task | [
"async",
"def",
"insert",
"(",
"self",
",",
"task",
":",
"Task",
")",
"->",
"None",
":",
"if",
"not",
"isinstance",
"(",
"task",
",",
"Task",
")",
":",
"task",
"=",
"task",
"(",
")",
"if",
"task",
".",
"name",
"not",
"in",
"self",
".",
"all_tasks... | Insert the given task class into the Tasky event loop. | [
"Insert",
"the",
"given",
"task",
"class",
"into",
"the",
"Tasky",
"event",
"loop",
"."
] | 681f4e5a9a60a0eb838b89f320309cfb45a56242 | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L111-L132 | train | 53,897 |
jreese/tasky | tasky/loop.py | Tasky.execute | async def execute(self, fn, *args, **kwargs) -> None:
'''Execute an arbitrary function outside the event loop using
a shared Executor.'''
fn = functools.partial(fn, *args, **kwargs)
return await self.loop.run_in_executor(self.executor, fn) | python | async def execute(self, fn, *args, **kwargs) -> None:
'''Execute an arbitrary function outside the event loop using
a shared Executor.'''
fn = functools.partial(fn, *args, **kwargs)
return await self.loop.run_in_executor(self.executor, fn) | [
"async",
"def",
"execute",
"(",
"self",
",",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"fn",
"=",
"functools",
".",
"partial",
"(",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"await",
"self",
... | Execute an arbitrary function outside the event loop using
a shared Executor. | [
"Execute",
"an",
"arbitrary",
"function",
"outside",
"the",
"event",
"loop",
"using",
"a",
"shared",
"Executor",
"."
] | 681f4e5a9a60a0eb838b89f320309cfb45a56242 | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L134-L139 | train | 53,898 |
jreese/tasky | tasky/loop.py | Tasky.start_task | async def start_task(self, task: Task) -> None:
'''Initialize the task, queue it for execution, add the done callback,
and keep track of it for when tasks need to be stopped.'''
try:
Log.debug('task %s starting', task.name)
before = time.time()
task.counters['last_run'] = before
task.running = True
self.running_tasks.add(task)
await task.run_task()
Log.debug('task %s completed', task.name)
except CancelledError:
Log.debug('task %s cancelled', task.name)
except Exception:
Log.exception('unhandled exception in task %s', task.name)
finally:
self.running_tasks.discard(task)
task.running = False
task.task = None
after = time.time()
total = after - before
task.counters['last_completed'] = after
task.counters['duration'] = total | python | async def start_task(self, task: Task) -> None:
'''Initialize the task, queue it for execution, add the done callback,
and keep track of it for when tasks need to be stopped.'''
try:
Log.debug('task %s starting', task.name)
before = time.time()
task.counters['last_run'] = before
task.running = True
self.running_tasks.add(task)
await task.run_task()
Log.debug('task %s completed', task.name)
except CancelledError:
Log.debug('task %s cancelled', task.name)
except Exception:
Log.exception('unhandled exception in task %s', task.name)
finally:
self.running_tasks.discard(task)
task.running = False
task.task = None
after = time.time()
total = after - before
task.counters['last_completed'] = after
task.counters['duration'] = total | [
"async",
"def",
"start_task",
"(",
"self",
",",
"task",
":",
"Task",
")",
"->",
"None",
":",
"try",
":",
"Log",
".",
"debug",
"(",
"'task %s starting'",
",",
"task",
".",
"name",
")",
"before",
"=",
"time",
".",
"time",
"(",
")",
"task",
".",
"coun... | Initialize the task, queue it for execution, add the done callback,
and keep track of it for when tasks need to be stopped. | [
"Initialize",
"the",
"task",
"queue",
"it",
"for",
"execution",
"add",
"the",
"done",
"callback",
"and",
"keep",
"track",
"of",
"it",
"for",
"when",
"tasks",
"need",
"to",
"be",
"stopped",
"."
] | 681f4e5a9a60a0eb838b89f320309cfb45a56242 | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L210-L238 | train | 53,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.