repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
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
... | 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
... | [
"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: na... | [
"Can",
"set",
"a",
"parameter",
"to",
"a",
"value",
"that",
"is",
"inconsistent",
"with",
"existing",
"values",
"."
] | train | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L84-L119 |
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"
] | train | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L121-L127 |
eng-tools/sfsimodels | sfsimodels/models/soils.py | Soil._add_to_stack | def _add_to_stack(self, item, value):
"""
Add a parameter-value pair to the stack of parameters that have been set.
:param item:
:param value:
:return:
"""
p_value = (item, value)
if p_value not in self.stack:
self.stack.append(p_value) | python | def _add_to_stack(self, item, value):
"""
Add a parameter-value pair to the stack of parameters that have been set.
:param item:
:param value:
:return:
"""
p_value = (item, value)
if p_value not in self.stack:
self.stack.append(p_value) | [
"def",
"_add_to_stack",
"(",
"self",
",",
"item",
",",
"value",
")",
":",
"p_value",
"=",
"(",
"item",
",",
"value",
")",
"if",
"p_value",
"not",
"in",
"self",
".",
"stack",
":",
"self",
".",
"stack",
".",
"append",
"(",
"p_value",
")"
] | Add a parameter-value pair to the stack of parameters that have been set.
:param item:
:param value:
:return: | [
"Add",
"a",
"parameter",
"-",
"value",
"pair",
"to",
"the",
"stack",
"of",
"parameters",
"that",
"have",
"been",
"set",
".",
":",
"param",
"item",
":",
":",
"param",
"value",
":",
":",
"return",
":"
] | train | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L129-L138 |
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:
... | 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:
... | [
"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"
] | train | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L256-L269 |
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
... | 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
... | [
"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"
] | train | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L416-L437 |
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=sel... | 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=sel... | [
"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"
] | train | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L460-L471 |
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] ... | 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] ... | [
"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",
"."
] | train | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L910-L934 |
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",
"."
] | train | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L936-L938 |
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 - ... | 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 - ... | [
"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",
"."
] | train | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L984-L996 |
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 = s... | 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 = s... | [
"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"
] | train | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L1083-L1095 |
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 = []
fo... | 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 = []
fo... | [
"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",
"."
] | train | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L1112-L1123 |
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 = l... | 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 = l... | [
"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",
"."
] | train | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L1125-L1158 |
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 ... | 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 ... | [
"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",
"."
] | train | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L1181-L1190 |
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
... | 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
... | [
"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",
"."
] | train | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L1197-L1214 |
sci-bots/svg-model | docs/generate_modules.py | create_package_file | def create_package_file(root, master_package, subroot, py_files, opts, subs):
"""Build the text of the file and write the file."""
package = os.path.split(root)[-1]
text = format_heading(1, '%s Package' % package)
# add each package's module
for py_file in py_files:
if shall_skip(os.path.joi... | python | def create_package_file(root, master_package, subroot, py_files, opts, subs):
"""Build the text of the file and write the file."""
package = os.path.split(root)[-1]
text = format_heading(1, '%s Package' % package)
# add each package's module
for py_file in py_files:
if shall_skip(os.path.joi... | [
"def",
"create_package_file",
"(",
"root",
",",
"master_package",
",",
"subroot",
",",
"py_files",
",",
"opts",
",",
"subs",
")",
":",
"package",
"=",
"os",
".",
"path",
".",
"split",
"(",
"root",
")",
"[",
"-",
"1",
"]",
"text",
"=",
"format_heading",... | Build the text of the file and write the file. | [
"Build",
"the",
"text",
"of",
"the",
"file",
"and",
"write",
"the",
"file",
"."
] | train | https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/docs/generate_modules.py#L85-L114 |
sci-bots/svg-model | docs/generate_modules.py | create_modules_toc_file | def create_modules_toc_file(master_package, modules, opts, name='modules'):
"""
Create the module's index.
"""
text = format_heading(1, '%s Modules' % opts.header)
text += '.. toctree::\n'
text += ' :maxdepth: %s\n\n' % opts.maxdepth
modules.sort()
prev_module = ''
for module in m... | python | def create_modules_toc_file(master_package, modules, opts, name='modules'):
"""
Create the module's index.
"""
text = format_heading(1, '%s Modules' % opts.header)
text += '.. toctree::\n'
text += ' :maxdepth: %s\n\n' % opts.maxdepth
modules.sort()
prev_module = ''
for module in m... | [
"def",
"create_modules_toc_file",
"(",
"master_package",
",",
"modules",
",",
"opts",
",",
"name",
"=",
"'modules'",
")",
":",
"text",
"=",
"format_heading",
"(",
"1",
",",
"'%s Modules'",
"%",
"opts",
".",
"header",
")",
"text",
"+=",
"'.. toctree::\\n'",
"... | Create the module's index. | [
"Create",
"the",
"module",
"s",
"index",
"."
] | train | https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/docs/generate_modules.py#L116-L133 |
sci-bots/svg-model | docs/generate_modules.py | recurse_tree | def recurse_tree(path, excludes, opts):
"""
Look for every file in the directory tree and create the corresponding
ReST files.
"""
# use absolute path for root, as relative paths like '../../foo' cause
# 'if "/." in root ...' to filter out *all* modules otherwise
path = os.path.abspath(path)... | python | def recurse_tree(path, excludes, opts):
"""
Look for every file in the directory tree and create the corresponding
ReST files.
"""
# use absolute path for root, as relative paths like '../../foo' cause
# 'if "/." in root ...' to filter out *all* modules otherwise
path = os.path.abspath(path)... | [
"def",
"recurse_tree",
"(",
"path",
",",
"excludes",
",",
"opts",
")",
":",
"# use absolute path for root, as relative paths like '../../foo' cause",
"# 'if \"/.\" in root ...' to filter out *all* modules otherwise",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path"... | Look for every file in the directory tree and create the corresponding
ReST files. | [
"Look",
"for",
"every",
"file",
"in",
"the",
"directory",
"tree",
"and",
"create",
"the",
"corresponding",
"ReST",
"files",
"."
] | train | https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/docs/generate_modules.py#L142-L196 |
sci-bots/svg-model | docs/generate_modules.py | normalize_excludes | def normalize_excludes(rootpath, excludes):
"""
Normalize the excluded directory list:
* must be either an absolute path or start with rootpath,
* otherwise it is joined with rootpath
* with trailing slash
"""
sep = os.path.sep
f_excludes = []
for exclude in excludes:
if not ... | python | def normalize_excludes(rootpath, excludes):
"""
Normalize the excluded directory list:
* must be either an absolute path or start with rootpath,
* otherwise it is joined with rootpath
* with trailing slash
"""
sep = os.path.sep
f_excludes = []
for exclude in excludes:
if not ... | [
"def",
"normalize_excludes",
"(",
"rootpath",
",",
"excludes",
")",
":",
"sep",
"=",
"os",
".",
"path",
".",
"sep",
"f_excludes",
"=",
"[",
"]",
"for",
"exclude",
"in",
"excludes",
":",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"exclude",
")... | Normalize the excluded directory list:
* must be either an absolute path or start with rootpath,
* otherwise it is joined with rootpath
* with trailing slash | [
"Normalize",
"the",
"excluded",
"directory",
"list",
":",
"*",
"must",
"be",
"either",
"an",
"absolute",
"path",
"or",
"start",
"with",
"rootpath",
"*",
"otherwise",
"it",
"is",
"joined",
"with",
"rootpath",
"*",
"with",
"trailing",
"slash"
] | train | https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/docs/generate_modules.py#L198-L213 |
sci-bots/svg-model | docs/generate_modules.py | is_excluded | def is_excluded(root, excludes):
"""
Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
"""
sep = os.path.sep
if not root.endswith(sep):
root += sep
... | python | def is_excluded(root, excludes):
"""
Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
"""
sep = os.path.sep
if not root.endswith(sep):
root += sep
... | [
"def",
"is_excluded",
"(",
"root",
",",
"excludes",
")",
":",
"sep",
"=",
"os",
".",
"path",
".",
"sep",
"if",
"not",
"root",
".",
"endswith",
"(",
"sep",
")",
":",
"root",
"+=",
"sep",
"for",
"exclude",
"in",
"excludes",
":",
"if",
"root",
".",
... | Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar". | [
"Check",
"if",
"the",
"directory",
"is",
"in",
"the",
"exclude",
"list",
"."
] | train | https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/docs/generate_modules.py#L215-L228 |
sci-bots/svg-model | docs/generate_modules.py | main | def main():
"""
Parse and check the command line arguments.
"""
parser = optparse.OptionParser(usage="""usage: %prog [options] <package path> [exclude paths, ...]
Note: By default this script will not overwrite already created files.""")
parser.add_option("-n", "--doc-header", action="store", dest=... | python | def main():
"""
Parse and check the command line arguments.
"""
parser = optparse.OptionParser(usage="""usage: %prog [options] <package path> [exclude paths, ...]
Note: By default this script will not overwrite already created files.""")
parser.add_option("-n", "--doc-header", action="store", dest=... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
"usage",
"=",
"\"\"\"usage: %prog [options] <package path> [exclude paths, ...]\n\nNote: By default this script will not overwrite already created files.\"\"\"",
")",
"parser",
".",
"add_option",
"... | Parse and check the command line arguments. | [
"Parse",
"and",
"check",
"the",
"command",
"line",
"arguments",
"."
] | train | https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/docs/generate_modules.py#L230-L257 |
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"
] | train | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L98-L109 |
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"
] | train | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L135-L143 |
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)
... | 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)
... | [
"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",
"."
] | train | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L227-L244 |
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.de... | 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.de... | [
"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"
] | train | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L263-L273 |
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"
] | train | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L275-L280 |
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]
... | 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]
... | [
"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"
] | train | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L291-L308 |
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... | 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... | [
"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 f... | [
"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... | train | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L341-L424 |
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"
] | train | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L444-L451 |
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"
] | train | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L453-L460 |
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_i... | 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_i... | [
"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"
] | train | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L466-L515 |
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... | 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... | [
"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"
] | train | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L524-L543 |
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 cr... | 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 cr... | [
"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"
] | train | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L638-L689 |
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, ... | 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, ... | [
"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"
] | train | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L738-L752 |
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 [... | 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 [... | [
"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"
] | train | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L755-L775 |
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
... | 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
... | [
"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"
] | train | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L785-L799 |
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"
] | train | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L801-L811 |
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 '') )
... | 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 '') )
... | [
"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"
] | train | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/doc.py#L813-L825 |
KelSolaar/Manager | manager/QWidget_component.py | QWidgetComponentFactory | def QWidgetComponentFactory(ui_file=None, *args, **kwargs):
"""
Defines a class factory creating :class:`QWidgetComponent` classes using given ui file.
:param ui_file: Ui file.
:type ui_file: unicode
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Keywords arguments.
:type... | python | def QWidgetComponentFactory(ui_file=None, *args, **kwargs):
"""
Defines a class factory creating :class:`QWidgetComponent` classes using given ui file.
:param ui_file: Ui file.
:type ui_file: unicode
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Keywords arguments.
:type... | [
"def",
"QWidgetComponentFactory",
"(",
"ui_file",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"class",
"QWidgetComponent",
"(",
"foundations",
".",
"ui",
".",
"common",
".",
"QWidget_factory",
"(",
"ui_file",
"=",
"ui_file",
")",
")",... | Defines a class factory creating :class:`QWidgetComponent` classes using given ui file.
:param ui_file: Ui file.
:type ui_file: unicode
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Keywords arguments.
:type \*\*kwargs: \*\*
:return: QWidgetComponent class.
:rtype: QWidg... | [
"Defines",
"a",
"class",
"factory",
"creating",
":",
"class",
":",
"QWidgetComponent",
"classes",
"using",
"given",
"ui",
"file",
"."
] | train | https://github.com/KelSolaar/Manager/blob/39c8153fc021fc8a76e345a6e336ec2644f089d1/manager/QWidget_component.py#L37-L307 |
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)... | 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)... | [
"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.
Note... | [
"Remove",
"volume",
"node",
"if",
"it",
"follows",
"a",
"journal",
"logically",
"in",
"the",
"tree",
"hierarchy",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/restructuring_visitor.py#L48-L87 |
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 i... | 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 i... | [
"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",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/restructuring_visitor.py#L90-L118 |
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:
j... | 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:
j... | [
"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",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/restructuring_visitor.py#L160-L173 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/restructuring_visitor.py | RestructuringVisitor.visit_simple_value_boolean_query | def visit_simple_value_boolean_query(self, node):
"""
Visits only the children of :class:`SimpleValueBooleanQuery` without substituting the actual node type.
Notes:
Defer conversion from :class:`SimpleValueBooleanQuery` to AndOp or OrOp.
This transformation needs to occu... | python | def visit_simple_value_boolean_query(self, node):
"""
Visits only the children of :class:`SimpleValueBooleanQuery` without substituting the actual node type.
Notes:
Defer conversion from :class:`SimpleValueBooleanQuery` to AndOp or OrOp.
This transformation needs to occu... | [
"def",
"visit_simple_value_boolean_query",
"(",
"self",
",",
"node",
")",
":",
"node",
".",
"left",
",",
"node",
".",
"right",
"=",
"node",
".",
"left",
".",
"accept",
"(",
"self",
")",
",",
"node",
".",
"right",
".",
"accept",
"(",
"self",
")",
"ret... | Visits only the children of :class:`SimpleValueBooleanQuery` without substituting the actual node type.
Notes:
Defer conversion from :class:`SimpleValueBooleanQuery` to AndOp or OrOp.
This transformation needs to occur higher in the tree, so that we don't lose the information that this ... | [
"Visits",
"only",
"the",
"children",
"of",
":",
"class",
":",
"SimpleValueBooleanQuery",
"without",
"substituting",
"the",
"actual",
"node",
"type",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/restructuring_visitor.py#L175-L187 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/restructuring_visitor.py | RestructuringVisitor.visit_spires_keyword_query | def visit_spires_keyword_query(self, node):
"""Transform a :class:`SpiresKeywordQuery` into a :class:`KeywordOp`.
Notes:
In case the value being a :class:`SimpleValueBooleanQuery`, the subtree is transformed to chained
:class:`AndOp` queries containing :class:`KeywordOp`, whose ... | python | def visit_spires_keyword_query(self, node):
"""Transform a :class:`SpiresKeywordQuery` into a :class:`KeywordOp`.
Notes:
In case the value being a :class:`SimpleValueBooleanQuery`, the subtree is transformed to chained
:class:`AndOp` queries containing :class:`KeywordOp`, whose ... | [
"def",
"visit_spires_keyword_query",
"(",
"self",
",",
"node",
")",
":",
"keyword",
"=",
"node",
".",
"left",
".",
"accept",
"(",
"self",
")",
"value",
"=",
"node",
".",
"right",
".",
"accept",
"(",
"self",
")",
"if",
"isinstance",
"(",
"value",
",",
... | Transform a :class:`SpiresKeywordQuery` into a :class:`KeywordOp`.
Notes:
In case the value being a :class:`SimpleValueBooleanQuery`, the subtree is transformed to chained
:class:`AndOp` queries containing :class:`KeywordOp`, whose keyword is the keyword of the current node and
... | [
"Transform",
"a",
":",
"class",
":",
"SpiresKeywordQuery",
"into",
"a",
":",
"class",
":",
"KeywordOp",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/restructuring_visitor.py#L206-L221 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/restructuring_visitor.py | RestructuringVisitor.visit_invenio_keyword_query | def visit_invenio_keyword_query(self, node):
"""Transform an :class:`InvenioKeywordQuery` into a :class:`KeywordOp`.
Notes:
In case the value being a :class:`SimpleValueBooleanQuery`, the subtree is transformed to chained
:class:`AndOp` queries containing :class:`KeywordOp`, who... | python | def visit_invenio_keyword_query(self, node):
"""Transform an :class:`InvenioKeywordQuery` into a :class:`KeywordOp`.
Notes:
In case the value being a :class:`SimpleValueBooleanQuery`, the subtree is transformed to chained
:class:`AndOp` queries containing :class:`KeywordOp`, who... | [
"def",
"visit_invenio_keyword_query",
"(",
"self",
",",
"node",
")",
":",
"try",
":",
"keyword",
"=",
"node",
".",
"left",
".",
"accept",
"(",
"self",
")",
"except",
"AttributeError",
":",
"# The keywords whose values aren't an InspireKeyword are simple strings.",
"ke... | Transform an :class:`InvenioKeywordQuery` into a :class:`KeywordOp`.
Notes:
In case the value being a :class:`SimpleValueBooleanQuery`, the subtree is transformed to chained
:class:`AndOp` queries containing :class:`KeywordOp`, whose keyword is the keyword of the current node and
... | [
"Transform",
"an",
":",
"class",
":",
"InvenioKeywordQuery",
"into",
"a",
":",
"class",
":",
"KeywordOp",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/restructuring_visitor.py#L223-L243 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/restructuring_visitor.py | RestructuringVisitor.visit_complex_value | def visit_complex_value(self, node):
"""Convert :class:`ComplexValue` to one of ExactMatch, PartialMatch and Regex Value nodes."""
if node.value.startswith(ComplexValue.EXACT_VALUE_TOKEN):
value = node.value.strip(ComplexValue.EXACT_VALUE_TOKEN)
return ExactMatchValue(value)
... | python | def visit_complex_value(self, node):
"""Convert :class:`ComplexValue` to one of ExactMatch, PartialMatch and Regex Value nodes."""
if node.value.startswith(ComplexValue.EXACT_VALUE_TOKEN):
value = node.value.strip(ComplexValue.EXACT_VALUE_TOKEN)
return ExactMatchValue(value)
... | [
"def",
"visit_complex_value",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"value",
".",
"startswith",
"(",
"ComplexValue",
".",
"EXACT_VALUE_TOKEN",
")",
":",
"value",
"=",
"node",
".",
"value",
".",
"strip",
"(",
"ComplexValue",
".",
"EXACT_VAL... | Convert :class:`ComplexValue` to one of ExactMatch, PartialMatch and Regex Value nodes. | [
"Convert",
":",
"class",
":",
"ComplexValue",
"to",
"one",
"of",
"ExactMatch",
"PartialMatch",
"and",
"Regex",
"Value",
"nodes",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/restructuring_visitor.py#L281-L302 |
jreese/tasky | tasky/tasks/task.py | Task.sleep | async def sleep(self, duration: float=0.0) -> None:
'''Simple wrapper around `asyncio.sleep()`.'''
duration = max(0, duration)
if duration > 0:
Log.debug('sleeping task %s for %.1f seconds', self.name, duration)
await asyncio.sleep(duration) | python | async def sleep(self, duration: float=0.0) -> None:
'''Simple wrapper around `asyncio.sleep()`.'''
duration = max(0, duration)
if duration > 0:
Log.debug('sleeping task %s for %.1f seconds', self.name, duration)
await asyncio.sleep(duration) | [
"async",
"def",
"sleep",
"(",
"self",
",",
"duration",
":",
"float",
"=",
"0.0",
")",
"->",
"None",
":",
"duration",
"=",
"max",
"(",
"0",
",",
"duration",
")",
"if",
"duration",
">",
"0",
":",
"Log",
".",
"debug",
"(",
"'sleeping task %s for %.1f seco... | Simple wrapper around `asyncio.sleep()`. | [
"Simple",
"wrapper",
"around",
"asyncio",
".",
"sleep",
"()",
"."
] | train | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/tasks/task.py#L71-L77 |
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",
"."
] | train | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/tasks/task.py#L84-L92 |
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... | 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",
"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",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L45-L62 |
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... | 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... | [
"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",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L65-L72 |
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 i... | 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 i... | [
"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... | [
"Generate",
"a",
"small",
"number",
"of",
"name",
"variations",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L75-L115 |
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 ... | 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 ... | [
"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",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L139-L151 |
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:
Eith... | 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:
Eith... | [
"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... | [
"Truncate",
"wildcard",
"from",
"date",
"parts",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L226-L251 |
inspirehep/inspire-query-parser | inspire_query_parser/utils/visitor_utils.py | _truncate_date_value_according_on_date_field | def _truncate_date_value_according_on_date_field(field, date_value):
"""Truncates date value (to year only) according to the given date field.
Args:
field (unicode): The field for which the date value will be used to query on.
date_value (str): The date value that is going to be truncated to it... | python | def _truncate_date_value_according_on_date_field(field, date_value):
"""Truncates date value (to year only) according to the given date field.
Args:
field (unicode): The field for which the date value will be used to query on.
date_value (str): The date value that is going to be truncated to it... | [
"def",
"_truncate_date_value_according_on_date_field",
"(",
"field",
",",
"date_value",
")",
":",
"try",
":",
"partial_date",
"=",
"PartialDate",
".",
"parse",
"(",
"date_value",
")",
"except",
"ValueError",
":",
"return",
"None",
"if",
"field",
"in",
"ES_MAPPING_... | Truncates date value (to year only) according to the given date field.
Args:
field (unicode): The field for which the date value will be used to query on.
date_value (str): The date value that is going to be truncated to its year.
Returns:
PartialDate: The possibly truncated date, on s... | [
"Truncates",
"date",
"value",
"(",
"to",
"year",
"only",
")",
"according",
"to",
"the",
"given",
"date",
"field",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L254-L279 |
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.
"""
... | 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.
"""
... | [
"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",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L282-L303 |
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.
... | 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.
... | [
"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.... | [
"Returns",
"the",
"proper",
"ES",
"date",
"math",
"unit",
"according",
"to",
"the",
"resolution",
"of",
"the",
"partial_date",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L306-L331 |
inspirehep/inspire-query-parser | inspire_query_parser/utils/visitor_utils.py | update_date_value_in_operator_value_pairs_for_fieldname | def update_date_value_in_operator_value_pairs_for_fieldname(field, operator_value_pairs):
"""Updates (operator, date value) pairs by normalizing the date value according to the given field.
Args:
field (unicode): The fieldname for which the operator-value pairs are being generated.
operator_val... | python | def update_date_value_in_operator_value_pairs_for_fieldname(field, operator_value_pairs):
"""Updates (operator, date value) pairs by normalizing the date value according to the given field.
Args:
field (unicode): The fieldname for which the operator-value pairs are being generated.
operator_val... | [
"def",
"update_date_value_in_operator_value_pairs_for_fieldname",
"(",
"field",
",",
"operator_value_pairs",
")",
":",
"updated_operator_value_pairs",
"=",
"{",
"}",
"for",
"operator",
",",
"value",
"in",
"operator_value_pairs",
".",
"items",
"(",
")",
":",
"modified_da... | Updates (operator, date value) pairs by normalizing the date value according to the given field.
Args:
field (unicode): The fieldname for which the operator-value pairs are being generated.
operator_value_pairs (dict): ES range operator {'gt', 'gte', 'lt', 'lte'} along with a value.
Add... | [
"Updates",
"(",
"operator",
"date",
"value",
")",
"pairs",
"by",
"normalizing",
"the",
"date",
"value",
"according",
"to",
"the",
"given",
"field",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L334-L363 |
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):... | 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):... | [
"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 ... | [
"Helper",
"for",
"generating",
"a",
"match",
"query",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L367-L402 |
inspirehep/inspire-query-parser | inspire_query_parser/utils/visitor_utils.py | wrap_queries_in_bool_clauses_if_more_than_one | def wrap_queries_in_bool_clauses_if_more_than_one(queries,
use_must_clause,
preserve_bool_semantics_if_one_clause=False):
"""Helper for wrapping a list of queries into a bool.{must, should} clause.
Args:
... | python | def wrap_queries_in_bool_clauses_if_more_than_one(queries,
use_must_clause,
preserve_bool_semantics_if_one_clause=False):
"""Helper for wrapping a list of queries into a bool.{must, should} clause.
Args:
... | [
"def",
"wrap_queries_in_bool_clauses_if_more_than_one",
"(",
"queries",
",",
"use_must_clause",
",",
"preserve_bool_semantics_if_one_clause",
"=",
"False",
")",
":",
"if",
"not",
"queries",
":",
"return",
"{",
"}",
"if",
"len",
"(",
"queries",
")",
"==",
"1",
"and... | Helper for wrapping a list of queries into a bool.{must, should} clause.
Args:
queries (list): List of queries to be wrapped in a bool.{must, should} clause.
use_must_clause (bool): Flag that signifies whether to use 'must' or 'should' clause.
preserve_bool_semantics_if_one_clause (bool): F... | [
"Helper",
"for",
"wrapping",
"a",
"list",
"of",
"queries",
"into",
"a",
"bool",
".",
"{",
"must",
"should",
"}",
"clause",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L422-L448 |
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 neste... | 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 neste... | [
"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"
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L451-L466 |
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",
"."
] | train | https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/subscriptions/management/commands/remove_duplicate_subscriptions.py#L79-L84 |
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 ... | 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 ... | [
"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",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/format_parse_tree.py#L34-L47 |
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 de... | 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 de... | [
"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",
"."
] | train | https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/seed_stage_based_messaging/utils.py#L52-L60 |
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.
No... | 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.
No... | [
"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, a... | [
"Drives",
"the",
"whole",
"logic",
"by",
"parsing",
"restructuring",
"and",
"finally",
"generating",
"an",
"ElasticSearch",
"query",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/parsing_driver.py#L42-L113 |
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)
exce... | 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)
exce... | [
"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",
"."
] | train | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L79-L89 |
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')
... | 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')
... | [
"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",
"."
] | train | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L91-L109 |
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 ta... | 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 ta... | [
"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",
"."
] | train | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L111-L132 |
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",
"."
] | train | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L134-L139 |
jreese/tasky | tasky/loop.py | Tasky.run_forever | def run_forever(self) -> None:
'''Execute the tasky/asyncio event loop until terminated.'''
Log.debug('running event loop until terminated')
asyncio.ensure_future(self.init())
self.loop.run_forever()
self.loop.close() | python | def run_forever(self) -> None:
'''Execute the tasky/asyncio event loop until terminated.'''
Log.debug('running event loop until terminated')
asyncio.ensure_future(self.init())
self.loop.run_forever()
self.loop.close() | [
"def",
"run_forever",
"(",
"self",
")",
"->",
"None",
":",
"Log",
".",
"debug",
"(",
"'running event loop until terminated'",
")",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"init",
"(",
")",
")",
"self",
".",
"loop",
".",
"run_forever",
"(",
")",
... | Execute the tasky/asyncio event loop until terminated. | [
"Execute",
"the",
"tasky",
"/",
"asyncio",
"event",
"loop",
"until",
"terminated",
"."
] | train | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L141-L147 |
jreese/tasky | tasky/loop.py | Tasky.run_until_complete | def run_until_complete(self) -> None:
'''Execute the tasky/asyncio event loop until all tasks finish.'''
Log.debug('running event loop until all tasks completed')
self.terminate_on_finish = True
asyncio.ensure_future(self.init())
self.loop.run_forever()
self.loop.close() | python | def run_until_complete(self) -> None:
'''Execute the tasky/asyncio event loop until all tasks finish.'''
Log.debug('running event loop until all tasks completed')
self.terminate_on_finish = True
asyncio.ensure_future(self.init())
self.loop.run_forever()
self.loop.close() | [
"def",
"run_until_complete",
"(",
"self",
")",
"->",
"None",
":",
"Log",
".",
"debug",
"(",
"'running event loop until all tasks completed'",
")",
"self",
".",
"terminate_on_finish",
"=",
"True",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"init",
"(",
")... | Execute the tasky/asyncio event loop until all tasks finish. | [
"Execute",
"the",
"tasky",
"/",
"asyncio",
"event",
"loop",
"until",
"all",
"tasks",
"finish",
"."
] | train | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L149-L156 |
jreese/tasky | tasky/loop.py | Tasky.run_for_time | def run_for_time(self, duration: float=10.0) -> None:
'''Execute the tasky/asyncio event loop for `duration` seconds.'''
Log.debug('running event loop for %.1f seconds', duration)
try:
asyncio.ensure_future(self.init())
self.loop.run_until_complete(asyncio.sleep(duration... | python | def run_for_time(self, duration: float=10.0) -> None:
'''Execute the tasky/asyncio event loop for `duration` seconds.'''
Log.debug('running event loop for %.1f seconds', duration)
try:
asyncio.ensure_future(self.init())
self.loop.run_until_complete(asyncio.sleep(duration... | [
"def",
"run_for_time",
"(",
"self",
",",
"duration",
":",
"float",
"=",
"10.0",
")",
"->",
"None",
":",
"Log",
".",
"debug",
"(",
"'running event loop for %.1f seconds'",
",",
"duration",
")",
"try",
":",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
... | Execute the tasky/asyncio event loop for `duration` seconds. | [
"Execute",
"the",
"tasky",
"/",
"asyncio",
"event",
"loop",
"for",
"duration",
"seconds",
"."
] | train | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L158-L173 |
jreese/tasky | tasky/loop.py | Tasky.terminate | def terminate(self, *, force: bool=False, timeout: float=30.0,
step: float=1.0) -> None:
'''Stop all scheduled and/or executing tasks, first by asking nicely,
and then by waiting up to `timeout` seconds before forcefully stopping
the asyncio event loop.'''
if isinstanc... | python | def terminate(self, *, force: bool=False, timeout: float=30.0,
step: float=1.0) -> None:
'''Stop all scheduled and/or executing tasks, first by asking nicely,
and then by waiting up to `timeout` seconds before forcefully stopping
the asyncio event loop.'''
if isinstanc... | [
"def",
"terminate",
"(",
"self",
",",
"*",
",",
"force",
":",
"bool",
"=",
"False",
",",
"timeout",
":",
"float",
"=",
"30.0",
",",
"step",
":",
"float",
"=",
"1.0",
")",
"->",
"None",
":",
"if",
"isinstance",
"(",
"self",
".",
"monitor",
",",
"a... | Stop all scheduled and/or executing tasks, first by asking nicely,
and then by waiting up to `timeout` seconds before forcefully stopping
the asyncio event loop. | [
"Stop",
"all",
"scheduled",
"and",
"/",
"or",
"executing",
"tasks",
"first",
"by",
"asking",
"nicely",
"and",
"then",
"by",
"waiting",
"up",
"to",
"timeout",
"seconds",
"before",
"forcefully",
"stopping",
"the",
"asyncio",
"event",
"loop",
"."
] | train | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L175-L208 |
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[... | 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[... | [
"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",
"."
] | train | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L210-L238 |
jreese/tasky | tasky/loop.py | Tasky.monitor_tasks | async def monitor_tasks(self, interval: float=1.0) -> None:
'''Monitor all known tasks for run state. Ensure that enabled tasks
are running, and that disabled tasks are stopped.'''
Log.debug('monitor running')
while True:
try:
await asyncio.sleep(interval)
... | python | async def monitor_tasks(self, interval: float=1.0) -> None:
'''Monitor all known tasks for run state. Ensure that enabled tasks
are running, and that disabled tasks are stopped.'''
Log.debug('monitor running')
while True:
try:
await asyncio.sleep(interval)
... | [
"async",
"def",
"monitor_tasks",
"(",
"self",
",",
"interval",
":",
"float",
"=",
"1.0",
")",
"->",
"None",
":",
"Log",
".",
"debug",
"(",
"'monitor running'",
")",
"while",
"True",
":",
"try",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"interval",
")... | Monitor all known tasks for run state. Ensure that enabled tasks
are running, and that disabled tasks are stopped. | [
"Monitor",
"all",
"known",
"tasks",
"for",
"run",
"state",
".",
"Ensure",
"that",
"enabled",
"tasks",
"are",
"running",
"and",
"that",
"disabled",
"tasks",
"are",
"stopped",
"."
] | train | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L240-L276 |
jreese/tasky | tasky/loop.py | Tasky.exception | def exception(self, loop: asyncio.BaseEventLoop, context: dict) -> None:
'''Log unhandled exceptions from anywhere in the event loop.'''
Log.error('unhandled exception: %s', context['message'])
Log.error('%s', context)
if 'exception' in context:
Log.error(' %s', context['ex... | python | def exception(self, loop: asyncio.BaseEventLoop, context: dict) -> None:
'''Log unhandled exceptions from anywhere in the event loop.'''
Log.error('unhandled exception: %s', context['message'])
Log.error('%s', context)
if 'exception' in context:
Log.error(' %s', context['ex... | [
"def",
"exception",
"(",
"self",
",",
"loop",
":",
"asyncio",
".",
"BaseEventLoop",
",",
"context",
":",
"dict",
")",
"->",
"None",
":",
"Log",
".",
"error",
"(",
"'unhandled exception: %s'",
",",
"context",
"[",
"'message'",
"]",
")",
"Log",
".",
"error... | Log unhandled exceptions from anywhere in the event loop. | [
"Log",
"unhandled",
"exceptions",
"from",
"anywhere",
"in",
"the",
"event",
"loop",
"."
] | train | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L278-L284 |
jreese/tasky | tasky/loop.py | Tasky.sigint | def sigint(self) -> None:
'''Handle the user pressing Ctrl-C by stopping tasks nicely at first,
then forcibly upon further presses.'''
if self.stop_attempts < 1:
Log.info('gracefully stopping tasks')
self.stop_attempts += 1
self.terminate()
elif self... | python | def sigint(self) -> None:
'''Handle the user pressing Ctrl-C by stopping tasks nicely at first,
then forcibly upon further presses.'''
if self.stop_attempts < 1:
Log.info('gracefully stopping tasks')
self.stop_attempts += 1
self.terminate()
elif self... | [
"def",
"sigint",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"stop_attempts",
"<",
"1",
":",
"Log",
".",
"info",
"(",
"'gracefully stopping tasks'",
")",
"self",
".",
"stop_attempts",
"+=",
"1",
"self",
".",
"terminate",
"(",
")",
"elif",
"... | Handle the user pressing Ctrl-C by stopping tasks nicely at first,
then forcibly upon further presses. | [
"Handle",
"the",
"user",
"pressing",
"Ctrl",
"-",
"C",
"by",
"stopping",
"tasks",
"nicely",
"at",
"first",
"then",
"forcibly",
"upon",
"further",
"presses",
"."
] | train | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L286-L302 |
jreese/tasky | tasky/loop.py | Tasky.sigterm | def sigterm(self) -> None:
'''Handle SIGTERM from the system by stopping tasks gracefully.
Repeated signals will be ignored while waiting for tasks to finish.'''
if self.stop_attempts < 1:
Log.info('received SIGTERM, gracefully stopping tasks')
self.stop_attempts += 1
... | python | def sigterm(self) -> None:
'''Handle SIGTERM from the system by stopping tasks gracefully.
Repeated signals will be ignored while waiting for tasks to finish.'''
if self.stop_attempts < 1:
Log.info('received SIGTERM, gracefully stopping tasks')
self.stop_attempts += 1
... | [
"def",
"sigterm",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"stop_attempts",
"<",
"1",
":",
"Log",
".",
"info",
"(",
"'received SIGTERM, gracefully stopping tasks'",
")",
"self",
".",
"stop_attempts",
"+=",
"1",
"self",
".",
"terminate",
"(",
... | Handle SIGTERM from the system by stopping tasks gracefully.
Repeated signals will be ignored while waiting for tasks to finish. | [
"Handle",
"SIGTERM",
"from",
"the",
"system",
"by",
"stopping",
"tasks",
"gracefully",
".",
"Repeated",
"signals",
"will",
"be",
"ignored",
"while",
"waiting",
"for",
"tasks",
"to",
"finish",
"."
] | train | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L304-L314 |
inspirehep/inspire-query-parser | inspire_query_parser/parser.py | CaseInsensitiveKeyword.parse | def parse(cls, parser, text, pos):
"""Checks if terminal token is a keyword after lower-casing it."""
match = cls.regex.match(text)
if match:
# Check if match is is not in the grammar of the specific keyword class.
if match.group(0).lower() not in cls.grammar:
... | python | def parse(cls, parser, text, pos):
"""Checks if terminal token is a keyword after lower-casing it."""
match = cls.regex.match(text)
if match:
# Check if match is is not in the grammar of the specific keyword class.
if match.group(0).lower() not in cls.grammar:
... | [
"def",
"parse",
"(",
"cls",
",",
"parser",
",",
"text",
",",
"pos",
")",
":",
"match",
"=",
"cls",
".",
"regex",
".",
"match",
"(",
"text",
")",
"if",
"match",
":",
"# Check if match is is not in the grammar of the specific keyword class.",
"if",
"match",
".",... | Checks if terminal token is a keyword after lower-casing it. | [
"Checks",
"if",
"terminal",
"token",
"is",
"a",
"keyword",
"after",
"lower",
"-",
"casing",
"it",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/parser.py#L59-L70 |
inspirehep/inspire-query-parser | inspire_query_parser/parser.py | InspireKeyword.parse | def parse(cls, parser, text, pos):
"""Parse InspireKeyword.
If the keyword is `texkey`, enable the parsing texkey expression flag, since its value contains ':' which
normally isn't allowed.
"""
try:
remaining_text, keyword = parser.parse(text, cls.grammar)
... | python | def parse(cls, parser, text, pos):
"""Parse InspireKeyword.
If the keyword is `texkey`, enable the parsing texkey expression flag, since its value contains ':' which
normally isn't allowed.
"""
try:
remaining_text, keyword = parser.parse(text, cls.grammar)
... | [
"def",
"parse",
"(",
"cls",
",",
"parser",
",",
"text",
",",
"pos",
")",
":",
"try",
":",
"remaining_text",
",",
"keyword",
"=",
"parser",
".",
"parse",
"(",
"text",
",",
"cls",
".",
"grammar",
")",
"if",
"keyword",
".",
"lower",
"(",
")",
"==",
... | Parse InspireKeyword.
If the keyword is `texkey`, enable the parsing texkey expression flag, since its value contains ':' which
normally isn't allowed. | [
"Parse",
"InspireKeyword",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/parser.py#L209-L222 |
inspirehep/inspire-query-parser | inspire_query_parser/parser.py | SimpleValueUnit.parse_terminal_token | def parse_terminal_token(cls, parser, text):
"""Parses a terminal token that doesn't contain parentheses nor colon symbol.
Note:
Handles a special case of tokens where a ':' is needed (for `texkey` queries).
If we're parsing text not in parentheses, then some DSL keywords (e.g.... | python | def parse_terminal_token(cls, parser, text):
"""Parses a terminal token that doesn't contain parentheses nor colon symbol.
Note:
Handles a special case of tokens where a ':' is needed (for `texkey` queries).
If we're parsing text not in parentheses, then some DSL keywords (e.g.... | [
"def",
"parse_terminal_token",
"(",
"cls",
",",
"parser",
",",
"text",
")",
":",
"token_regex",
"=",
"cls",
".",
"token_regex",
"if",
"parser",
".",
"_parsing_texkey_expression",
":",
"token_regex",
"=",
"cls",
".",
"texkey_token_regex",
"parser",
".",
"_parsing... | Parses a terminal token that doesn't contain parentheses nor colon symbol.
Note:
Handles a special case of tokens where a ':' is needed (for `texkey` queries).
If we're parsing text not in parentheses, then some DSL keywords (e.g. And, Or, Not, defined above) should
not be ... | [
"Parses",
"a",
"terminal",
"token",
"that",
"doesn",
"t",
"contain",
"parentheses",
"nor",
"colon",
"symbol",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/parser.py#L255-L300 |
inspirehep/inspire-query-parser | inspire_query_parser/parser.py | SimpleValueUnit.parse | def parse(cls, parser, text, pos):
"""Imitates parsing a list grammar.
Specifically, this
grammar = [
SimpleValueUnit.date_specifiers_regex,
SimpleValueUnit.arxiv_token_regex,
SimpleValueUnit.token_regex,
SimpleValueUnit.parenthesized_token_gramma... | python | def parse(cls, parser, text, pos):
"""Imitates parsing a list grammar.
Specifically, this
grammar = [
SimpleValueUnit.date_specifiers_regex,
SimpleValueUnit.arxiv_token_regex,
SimpleValueUnit.token_regex,
SimpleValueUnit.parenthesized_token_gramma... | [
"def",
"parse",
"(",
"cls",
",",
"parser",
",",
"text",
",",
"pos",
")",
":",
"found",
"=",
"False",
"# Attempt to parse date specifier",
"match",
"=",
"cls",
".",
"date_specifiers_regex",
".",
"match",
"(",
"text",
")",
"if",
"match",
":",
"remaining_text",... | Imitates parsing a list grammar.
Specifically, this
grammar = [
SimpleValueUnit.date_specifiers_regex,
SimpleValueUnit.arxiv_token_regex,
SimpleValueUnit.token_regex,
SimpleValueUnit.parenthesized_token_grammar
].
Parses plaintext which m... | [
"Imitates",
"parsing",
"a",
"list",
"grammar",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/parser.py#L303-L358 |
inspirehep/inspire-query-parser | inspire_query_parser/parser.py | SimpleValue.unconsume_and_reconstruct_input | def unconsume_and_reconstruct_input(remaining_text, recognized_tokens, complex_value_idx):
"""Reconstruct input in case of consuming a keyword query or a value query with ComplexValue as value.
Un-consuming at most 3 elements and specifically (Keyword,) Whitespace and ComplexValue, while also
r... | python | def unconsume_and_reconstruct_input(remaining_text, recognized_tokens, complex_value_idx):
"""Reconstruct input in case of consuming a keyword query or a value query with ComplexValue as value.
Un-consuming at most 3 elements and specifically (Keyword,) Whitespace and ComplexValue, while also
r... | [
"def",
"unconsume_and_reconstruct_input",
"(",
"remaining_text",
",",
"recognized_tokens",
",",
"complex_value_idx",
")",
":",
"# Default slicing index: i.e. at most 3 elements will be unconsumed, Keyword, Whitespace and ComplexValue.",
"slicing_start_idx",
"=",
"2",
"# Check whether the... | Reconstruct input in case of consuming a keyword query or a value query with ComplexValue as value.
Un-consuming at most 3 elements and specifically (Keyword,) Whitespace and ComplexValue, while also
reconstructing parser's input text.
Example:
Given this query "author foo t 'bar'"... | [
"Reconstruct",
"input",
"in",
"case",
"of",
"consuming",
"a",
"keyword",
"query",
"or",
"a",
"value",
"query",
"with",
"ComplexValue",
"as",
"value",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/parser.py#L379-L405 |
inspirehep/inspire-query-parser | inspire_query_parser/parser.py | ParenthesizedSimpleValues.parse | def parse(cls, parser, text, pos):
"""Using our own parse to enable the flag below."""
try:
parser._parsing_parenthesized_simple_values_expression = True
remaining_text, recognized_tokens = parser.parse(text, cls.grammar)
return remaining_text, recognized_tokens
... | python | def parse(cls, parser, text, pos):
"""Using our own parse to enable the flag below."""
try:
parser._parsing_parenthesized_simple_values_expression = True
remaining_text, recognized_tokens = parser.parse(text, cls.grammar)
return remaining_text, recognized_tokens
... | [
"def",
"parse",
"(",
"cls",
",",
"parser",
",",
"text",
",",
"pos",
")",
":",
"try",
":",
"parser",
".",
"_parsing_parenthesized_simple_values_expression",
"=",
"True",
"remaining_text",
",",
"recognized_tokens",
"=",
"parser",
".",
"parse",
"(",
"text",
",",
... | Using our own parse to enable the flag below. | [
"Using",
"our",
"own",
"parse",
"to",
"enable",
"the",
"flag",
"below",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/parser.py#L534-L543 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | ElasticSearchVisitor._generate_fieldnames_if_bai_query | def _generate_fieldnames_if_bai_query(self, node_value, bai_field_variation, query_bai_field_if_dots_in_name):
"""Generates new fieldnames in case of BAI query.
Args:
node_value (six.text_type): The node's value (i.e. author name).
bai_field_variation (six.text_type): Which fiel... | python | def _generate_fieldnames_if_bai_query(self, node_value, bai_field_variation, query_bai_field_if_dots_in_name):
"""Generates new fieldnames in case of BAI query.
Args:
node_value (six.text_type): The node's value (i.e. author name).
bai_field_variation (six.text_type): Which fiel... | [
"def",
"_generate_fieldnames_if_bai_query",
"(",
"self",
",",
"node_value",
",",
"bai_field_variation",
",",
"query_bai_field_if_dots_in_name",
")",
":",
"if",
"bai_field_variation",
"not",
"in",
"(",
"FieldVariations",
".",
"search",
",",
"FieldVariations",
".",
"raw",... | Generates new fieldnames in case of BAI query.
Args:
node_value (six.text_type): The node's value (i.e. author name).
bai_field_variation (six.text_type): Which field variation to query ('search' or 'raw').
query_bai_field_if_dots_in_name (bool): Whether to query BAI field (... | [
"Generates",
"new",
"fieldnames",
"in",
"case",
"of",
"BAI",
"query",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L156-L189 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | ElasticSearchVisitor._generate_author_query | def _generate_author_query(self, author_name):
"""Generates a query handling specifically authors.
Notes:
The match query is generic enough to return many results. Then, using the filter clause we truncate these
so that we imitate legacy's behaviour on returning more "exact" res... | python | def _generate_author_query(self, author_name):
"""Generates a query handling specifically authors.
Notes:
The match query is generic enough to return many results. Then, using the filter clause we truncate these
so that we imitate legacy's behaviour on returning more "exact" res... | [
"def",
"_generate_author_query",
"(",
"self",
",",
"author_name",
")",
":",
"name_variations",
"=",
"[",
"name_variation",
".",
"lower",
"(",
")",
"for",
"name_variation",
"in",
"generate_minimal_name_variations",
"(",
"author_name",
")",
"]",
"# When the query contai... | Generates a query handling specifically authors.
Notes:
The match query is generic enough to return many results. Then, using the filter clause we truncate these
so that we imitate legacy's behaviour on returning more "exact" results. E.g. Searching for `Smith, John`
shouldn... | [
"Generates",
"a",
"query",
"handling",
"specifically",
"authors",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L191-L250 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | ElasticSearchVisitor._generate_exact_author_query | def _generate_exact_author_query(self, author_name_or_bai):
"""Generates a term query handling authors and BAIs.
Notes:
If given value is a BAI, search for the provided value in the raw field variation of
`ElasticSearchVisitor.AUTHORS_BAI_FIELD`.
Otherwise, the value... | python | def _generate_exact_author_query(self, author_name_or_bai):
"""Generates a term query handling authors and BAIs.
Notes:
If given value is a BAI, search for the provided value in the raw field variation of
`ElasticSearchVisitor.AUTHORS_BAI_FIELD`.
Otherwise, the value... | [
"def",
"_generate_exact_author_query",
"(",
"self",
",",
"author_name_or_bai",
")",
":",
"if",
"ElasticSearchVisitor",
".",
"BAI_REGEX",
".",
"match",
"(",
"author_name_or_bai",
")",
":",
"bai",
"=",
"author_name_or_bai",
".",
"lower",
"(",
")",
"query",
"=",
"s... | Generates a term query handling authors and BAIs.
Notes:
If given value is a BAI, search for the provided value in the raw field variation of
`ElasticSearchVisitor.AUTHORS_BAI_FIELD`.
Otherwise, the value will be procesed in the same way as the indexed value (i.e. lowercased... | [
"Generates",
"a",
"term",
"query",
"handling",
"authors",
"and",
"BAIs",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L252-L276 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | ElasticSearchVisitor._generate_date_with_wildcard_query | def _generate_date_with_wildcard_query(self, date_value):
"""Helper for generating a date keyword query containing a wildcard.
Returns:
(dict): The date query containing the wildcard or an empty dict in case the date value is malformed.
The policy followed here is quite conservativ... | python | def _generate_date_with_wildcard_query(self, date_value):
"""Helper for generating a date keyword query containing a wildcard.
Returns:
(dict): The date query containing the wildcard or an empty dict in case the date value is malformed.
The policy followed here is quite conservativ... | [
"def",
"_generate_date_with_wildcard_query",
"(",
"self",
",",
"date_value",
")",
":",
"if",
"date_value",
".",
"endswith",
"(",
"ast",
".",
"GenericValue",
".",
"WILDCARD_TOKEN",
")",
":",
"try",
":",
"date_value",
"=",
"_truncate_wildcard_from_date",
"(",
"date_... | Helper for generating a date keyword query containing a wildcard.
Returns:
(dict): The date query containing the wildcard or an empty dict in case the date value is malformed.
The policy followed here is quite conservative on what it accepts as valid input. Look into
:meth:`inspire... | [
"Helper",
"for",
"generating",
"a",
"date",
"keyword",
"query",
"containing",
"a",
"wildcard",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L278-L298 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | ElasticSearchVisitor._generate_queries_for_title_symbols | def _generate_queries_for_title_symbols(title_field, query_value):
"""Generate queries for any symbols in the title against the whitespace tokenized field of titles.
Returns:
(dict): The query or queries for the whitespace tokenized field of titles. If none such tokens exist, then
... | python | def _generate_queries_for_title_symbols(title_field, query_value):
"""Generate queries for any symbols in the title against the whitespace tokenized field of titles.
Returns:
(dict): The query or queries for the whitespace tokenized field of titles. If none such tokens exist, then
... | [
"def",
"_generate_queries_for_title_symbols",
"(",
"title_field",
",",
"query_value",
")",
":",
"values_tokenized_by_whitespace",
"=",
"query_value",
".",
"split",
"(",
")",
"symbol_queries",
"=",
"[",
"]",
"for",
"value",
"in",
"values_tokenized_by_whitespace",
":",
... | Generate queries for any symbols in the title against the whitespace tokenized field of titles.
Returns:
(dict): The query or queries for the whitespace tokenized field of titles. If none such tokens exist, then
returns an empty dict.
Notes:
Splits the value ... | [
"Generate",
"queries",
"for",
"any",
"symbols",
"in",
"the",
"title",
"against",
"the",
"whitespace",
"tokenized",
"field",
"of",
"titles",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L301-L327 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | ElasticSearchVisitor._generate_type_code_query | def _generate_type_code_query(self, value):
"""Generate type-code queries.
Notes:
If the value of the type-code query exists in `TYPECODE_VALUE_TO_FIELD_AND_VALUE_PAIRS_MAPPING, then we
query the specified field, along with the given value according to the mapping.
S... | python | def _generate_type_code_query(self, value):
"""Generate type-code queries.
Notes:
If the value of the type-code query exists in `TYPECODE_VALUE_TO_FIELD_AND_VALUE_PAIRS_MAPPING, then we
query the specified field, along with the given value according to the mapping.
S... | [
"def",
"_generate_type_code_query",
"(",
"self",
",",
"value",
")",
":",
"mapping_for_value",
"=",
"self",
".",
"TYPECODE_VALUE_TO_FIELD_AND_VALUE_PAIRS_MAPPING",
".",
"get",
"(",
"value",
",",
"None",
")",
"if",
"mapping_for_value",
":",
"return",
"generate_match_que... | Generate type-code queries.
Notes:
If the value of the type-code query exists in `TYPECODE_VALUE_TO_FIELD_AND_VALUE_PAIRS_MAPPING, then we
query the specified field, along with the given value according to the mapping.
See: https://github.com/inspirehep/inspire-query-parser/... | [
"Generate",
"type",
"-",
"code",
"queries",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L339-L361 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | ElasticSearchVisitor._generate_range_queries | def _generate_range_queries(self, fieldnames, operator_value_pairs):
"""Generates ElasticSearch range queries.
Args:
fieldnames (list): The fieldnames on which the search is the range query is targeted on,
operator_value_pairs (dict): Contains (range_operator, value) pairs.
... | python | def _generate_range_queries(self, fieldnames, operator_value_pairs):
"""Generates ElasticSearch range queries.
Args:
fieldnames (list): The fieldnames on which the search is the range query is targeted on,
operator_value_pairs (dict): Contains (range_operator, value) pairs.
... | [
"def",
"_generate_range_queries",
"(",
"self",
",",
"fieldnames",
",",
"operator_value_pairs",
")",
":",
"if",
"ElasticSearchVisitor",
".",
"KEYWORD_TO_ES_FIELDNAME",
"[",
"'date'",
"]",
"==",
"fieldnames",
":",
"range_queries",
"=",
"[",
"]",
"for",
"fieldname",
... | Generates ElasticSearch range queries.
Args:
fieldnames (list): The fieldnames on which the search is the range query is targeted on,
operator_value_pairs (dict): Contains (range_operator, value) pairs.
The range_operator should be one of those supported by ElasticSearch... | [
"Generates",
"ElasticSearch",
"range",
"queries",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L411-L458 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | ElasticSearchVisitor._generate_malformed_query | def _generate_malformed_query(data):
"""Generates a query on the ``_all`` field with all the query content.
Args:
data (six.text_type or list): The query in the format of ``six.text_type`` (when used from parsing driver)
or ``list`` when used from withing the ES visitor.
... | python | def _generate_malformed_query(data):
"""Generates a query on the ``_all`` field with all the query content.
Args:
data (six.text_type or list): The query in the format of ``six.text_type`` (when used from parsing driver)
or ``list`` when used from withing the ES visitor.
... | [
"def",
"_generate_malformed_query",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"six",
".",
"text_type",
")",
":",
"# Remove colon character (special character for ES)",
"query_str",
"=",
"data",
".",
"replace",
"(",
"':'",
",",
"' '",
")",
"els... | Generates a query on the ``_all`` field with all the query content.
Args:
data (six.text_type or list): The query in the format of ``six.text_type`` (when used from parsing driver)
or ``list`` when used from withing the ES visitor. | [
"Generates",
"a",
"query",
"on",
"the",
"_all",
"field",
"with",
"all",
"the",
"query",
"content",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L461-L479 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | ElasticSearchVisitor._preprocess_journal_query_value | def _preprocess_journal_query_value(third_journal_field, old_publication_info_values):
"""Transforms the given journal query value (old publication info) to the new one.
Args:
third_journal_field (six.text_type): The final field to be used for populating the old publication info.
... | python | def _preprocess_journal_query_value(third_journal_field, old_publication_info_values):
"""Transforms the given journal query value (old publication info) to the new one.
Args:
third_journal_field (six.text_type): The final field to be used for populating the old publication info.
... | [
"def",
"_preprocess_journal_query_value",
"(",
"third_journal_field",
",",
"old_publication_info_values",
")",
":",
"# Prepare old publication info for :meth:`inspire_schemas.utils.convert_old_publication_info_to_new`.",
"publication_info_keys",
"=",
"[",
"ElasticSearchVisitor",
".",
"JO... | Transforms the given journal query value (old publication info) to the new one.
Args:
third_journal_field (six.text_type): The final field to be used for populating the old publication info.
old_publication_info_values (six.text_type): The old publication info. It must be one of {only t... | [
"Transforms",
"the",
"given",
"journal",
"query",
"value",
"(",
"old",
"publication",
"info",
")",
"to",
"the",
"new",
"one",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L482-L519 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | ElasticSearchVisitor._generate_journal_nested_queries | def _generate_journal_nested_queries(self, value):
"""Generates ElasticSearch nested query(s).
Args:
value (string): Contains the journal_title, journal_volume and artid or start_page separated by a comma.
This value should be of type string.
Notes:
... | python | def _generate_journal_nested_queries(self, value):
"""Generates ElasticSearch nested query(s).
Args:
value (string): Contains the journal_title, journal_volume and artid or start_page separated by a comma.
This value should be of type string.
Notes:
... | [
"def",
"_generate_journal_nested_queries",
"(",
"self",
",",
"value",
")",
":",
"# Abstract away which is the third field, we care only for its existence.",
"third_journal_field",
"=",
"ElasticSearchVisitor",
".",
"JOURNAL_PAGE_START",
"new_publication_info",
"=",
"ElasticSearchVisit... | Generates ElasticSearch nested query(s).
Args:
value (string): Contains the journal_title, journal_volume and artid or start_page separated by a comma.
This value should be of type string.
Notes:
The value contains at least one of the 3 mentioned ite... | [
"Generates",
"ElasticSearch",
"nested",
"query",
"(",
"s",
")",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L521-L575 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | ElasticSearchVisitor.visit_exact_match_value | def visit_exact_match_value(self, node, fieldnames=None):
"""Generates a term query (exact search in ElasticSearch)."""
if not fieldnames:
fieldnames = ['_all']
else:
fieldnames = force_list(fieldnames)
if ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['exact-autho... | python | def visit_exact_match_value(self, node, fieldnames=None):
"""Generates a term query (exact search in ElasticSearch)."""
if not fieldnames:
fieldnames = ['_all']
else:
fieldnames = force_list(fieldnames)
if ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['exact-autho... | [
"def",
"visit_exact_match_value",
"(",
"self",
",",
"node",
",",
"fieldnames",
"=",
"None",
")",
":",
"if",
"not",
"fieldnames",
":",
"fieldnames",
"=",
"[",
"'_all'",
"]",
"else",
":",
"fieldnames",
"=",
"force_list",
"(",
"fieldnames",
")",
"if",
"Elasti... | Generates a term query (exact search in ElasticSearch). | [
"Generates",
"a",
"term",
"query",
"(",
"exact",
"search",
"in",
"ElasticSearch",
")",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L753-L794 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | ElasticSearchVisitor.visit_partial_match_value | def visit_partial_match_value(self, node, fieldnames=None):
"""Generates a query which looks for a substring of the node's value in the given fieldname."""
if ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['date'] == fieldnames:
# Date queries with partial values are transformed into range que... | python | def visit_partial_match_value(self, node, fieldnames=None):
"""Generates a query which looks for a substring of the node's value in the given fieldname."""
if ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['date'] == fieldnames:
# Date queries with partial values are transformed into range que... | [
"def",
"visit_partial_match_value",
"(",
"self",
",",
"node",
",",
"fieldnames",
"=",
"None",
")",
":",
"if",
"ElasticSearchVisitor",
".",
"KEYWORD_TO_ES_FIELDNAME",
"[",
"'date'",
"]",
"==",
"fieldnames",
":",
"# Date queries with partial values are transformed into rang... | Generates a query which looks for a substring of the node's value in the given fieldname. | [
"Generates",
"a",
"query",
"which",
"looks",
"for",
"a",
"substring",
"of",
"the",
"node",
"s",
"value",
"in",
"the",
"given",
"fieldname",
"."
] | train | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L796-L834 |
praekeltfoundation/seed-stage-based-messaging | contentstore/tasks.py | QueueSubscriptionSend.run | def run(self, schedule_id, **kwargs):
"""
Arguments:
schedule_id {int} -- The schedule to send messages for
"""
subscriptions = Subscription.objects.filter(
schedule_id=schedule_id, active=True, completed=False, process_status=0
).values("id")
for ... | python | def run(self, schedule_id, **kwargs):
"""
Arguments:
schedule_id {int} -- The schedule to send messages for
"""
subscriptions = Subscription.objects.filter(
schedule_id=schedule_id, active=True, completed=False, process_status=0
).values("id")
for ... | [
"def",
"run",
"(",
"self",
",",
"schedule_id",
",",
"*",
"*",
"kwargs",
")",
":",
"subscriptions",
"=",
"Subscription",
".",
"objects",
".",
"filter",
"(",
"schedule_id",
"=",
"schedule_id",
",",
"active",
"=",
"True",
",",
"completed",
"=",
"False",
","... | Arguments:
schedule_id {int} -- The schedule to send messages for | [
"Arguments",
":",
"schedule_id",
"{",
"int",
"}",
"--",
"The",
"schedule",
"to",
"send",
"messages",
"for"
] | train | https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/contentstore/tasks.py#L83-L92 |
praekeltfoundation/seed-stage-based-messaging | contentstore/tasks.py | SyncSchedule.run | def run(self, schedule_id, **kwargs):
"""
Synchronises the schedule specified by the ID `schedule_id` to the
scheduler service.
Arguments:
schedule_id {str} -- The ID of the schedule to sync
"""
log = self.get_logger(**kwargs)
try:
schedu... | python | def run(self, schedule_id, **kwargs):
"""
Synchronises the schedule specified by the ID `schedule_id` to the
scheduler service.
Arguments:
schedule_id {str} -- The ID of the schedule to sync
"""
log = self.get_logger(**kwargs)
try:
schedu... | [
"def",
"run",
"(",
"self",
",",
"schedule_id",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
"=",
"self",
".",
"get_logger",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"schedule",
"=",
"Schedule",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"schedule_id... | Synchronises the schedule specified by the ID `schedule_id` to the
scheduler service.
Arguments:
schedule_id {str} -- The ID of the schedule to sync | [
"Synchronises",
"the",
"schedule",
"specified",
"by",
"the",
"ID",
"schedule_id",
"to",
"the",
"scheduler",
"service",
"."
] | train | https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/contentstore/tasks.py#L106-L144 |
praekeltfoundation/seed-stage-based-messaging | contentstore/tasks.py | DeactivateSchedule.run | def run(self, scheduler_schedule_id, **kwargs):
"""
Deactivates the schedule specified by the ID `scheduler_schedule_id` in
the scheduler service.
Arguments:
scheduler_schedule_id {str} -- The ID of the schedule to deactivate
"""
log = self.get_logger(**kwarg... | python | def run(self, scheduler_schedule_id, **kwargs):
"""
Deactivates the schedule specified by the ID `scheduler_schedule_id` in
the scheduler service.
Arguments:
scheduler_schedule_id {str} -- The ID of the schedule to deactivate
"""
log = self.get_logger(**kwarg... | [
"def",
"run",
"(",
"self",
",",
"scheduler_schedule_id",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
"=",
"self",
".",
"get_logger",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"scheduler",
".",
"update_schedule",
"(",
"scheduler_schedule_id",
",",
"{",
"\"... | Deactivates the schedule specified by the ID `scheduler_schedule_id` in
the scheduler service.
Arguments:
scheduler_schedule_id {str} -- The ID of the schedule to deactivate | [
"Deactivates",
"the",
"schedule",
"specified",
"by",
"the",
"ID",
"scheduler_schedule_id",
"in",
"the",
"scheduler",
"service",
"."
] | train | https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/contentstore/tasks.py#L158-L171 |
bitlabstudio/django-multilingual-tags | multilingual_tags/models.py | TagManager.get_for_model | def get_for_model(self, obj):
"""Returns the tags for a specific model/content type."""
qs = Tag.objects.language(get_language())
qs = qs.filter(
tagged_items__content_type=ctype_models.ContentType.objects.get_for_model(obj)) # NOQA
return qs.distinct() | python | def get_for_model(self, obj):
"""Returns the tags for a specific model/content type."""
qs = Tag.objects.language(get_language())
qs = qs.filter(
tagged_items__content_type=ctype_models.ContentType.objects.get_for_model(obj)) # NOQA
return qs.distinct() | [
"def",
"get_for_model",
"(",
"self",
",",
"obj",
")",
":",
"qs",
"=",
"Tag",
".",
"objects",
".",
"language",
"(",
"get_language",
"(",
")",
")",
"qs",
"=",
"qs",
".",
"filter",
"(",
"tagged_items__content_type",
"=",
"ctype_models",
".",
"ContentType",
... | Returns the tags for a specific model/content type. | [
"Returns",
"the",
"tags",
"for",
"a",
"specific",
"model",
"/",
"content",
"type",
"."
] | train | https://github.com/bitlabstudio/django-multilingual-tags/blob/c3040d8c6275b1617b99023ce3388365190cfcbd/multilingual_tags/models.py#L12-L17 |
bitlabstudio/django-multilingual-tags | multilingual_tags/models.py | TagManager.get_for_queryset | def get_for_queryset(self, obj_queryset):
"""Returns all tags for a whole queryset of objects."""
qs = Tag.objects.language(get_language())
if obj_queryset.count() == 0:
return qs.none()
qs = qs.filter(
tagged_items__object_id__in=[
obj.id for obj ... | python | def get_for_queryset(self, obj_queryset):
"""Returns all tags for a whole queryset of objects."""
qs = Tag.objects.language(get_language())
if obj_queryset.count() == 0:
return qs.none()
qs = qs.filter(
tagged_items__object_id__in=[
obj.id for obj ... | [
"def",
"get_for_queryset",
"(",
"self",
",",
"obj_queryset",
")",
":",
"qs",
"=",
"Tag",
".",
"objects",
".",
"language",
"(",
"get_language",
"(",
")",
")",
"if",
"obj_queryset",
".",
"count",
"(",
")",
"==",
"0",
":",
"return",
"qs",
".",
"none",
"... | Returns all tags for a whole queryset of objects. | [
"Returns",
"all",
"tags",
"for",
"a",
"whole",
"queryset",
"of",
"objects",
"."
] | train | https://github.com/bitlabstudio/django-multilingual-tags/blob/c3040d8c6275b1617b99023ce3388365190cfcbd/multilingual_tags/models.py#L27-L36 |
praekeltfoundation/seed-stage-based-messaging | subscriptions/tasks.py | post_send_process | def post_send_process(context):
"""
Task to ensure subscription is bumped or converted
"""
if "error" in context:
return context
[deserialized_subscription] = serializers.deserialize(
"json", context["subscription"]
)
subscription = deserialized_subscription.object
[mess... | python | def post_send_process(context):
"""
Task to ensure subscription is bumped or converted
"""
if "error" in context:
return context
[deserialized_subscription] = serializers.deserialize(
"json", context["subscription"]
)
subscription = deserialized_subscription.object
[mess... | [
"def",
"post_send_process",
"(",
"context",
")",
":",
"if",
"\"error\"",
"in",
"context",
":",
"return",
"context",
"[",
"deserialized_subscription",
"]",
"=",
"serializers",
".",
"deserialize",
"(",
"\"json\"",
",",
"context",
"[",
"\"subscription\"",
"]",
")",... | Task to ensure subscription is bumped or converted | [
"Task",
"to",
"ensure",
"subscription",
"is",
"bumped",
"or",
"converted"
] | train | https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/subscriptions/tasks.py#L337-L387 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.