repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
theonion/django-bulbs | bulbs/contributions/filters.py | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/contributions/filters.py#L28-L38 | def apply_published_filter(self, queryset, operation, value):
"""
Add the appropriate Published filter to a given elasticsearch query.
:param queryset: The DJES queryset object to be filtered.
:param operation: The type of filter (before/after).
:param value: The date or datetime value being applied to the filter.
"""
if operation not in ["after", "before"]:
raise ValueError("""Publish filters only use before or after for range filters.""")
return queryset.filter(Published(**{operation: value})) | [
"def",
"apply_published_filter",
"(",
"self",
",",
"queryset",
",",
"operation",
",",
"value",
")",
":",
"if",
"operation",
"not",
"in",
"[",
"\"after\"",
",",
"\"before\"",
"]",
":",
"raise",
"ValueError",
"(",
"\"\"\"Publish filters only use before or after for ra... | Add the appropriate Published filter to a given elasticsearch query.
:param queryset: The DJES queryset object to be filtered.
:param operation: The type of filter (before/after).
:param value: The date or datetime value being applied to the filter. | [
"Add",
"the",
"appropriate",
"Published",
"filter",
"to",
"a",
"given",
"elasticsearch",
"query",
"."
] | python | train |
HazardDede/dictmentor | dictmentor/validator.py | https://github.com/HazardDede/dictmentor/blob/f50ca26ed04f7a924cde6e4d464c4f6ccba4e320/dictmentor/validator.py#L77-L147 | def instance_of(target_type: Optional[type] = None, raise_ex: bool = False,
summary: bool = True, **items: Any) -> ValidationReturn:
"""
Tests if the given key-value pairs (items) are instances of the given ``target_type``.
Per default this function yields whether ``True`` or ``False`` depending on the fact if all
items withstand the validation or not. Per default the validation / evaluation is
short-circuit and will return as soon an item evaluates to ``False``.
When ``raise_ex`` is set to ``True`` the function will raise a meaningful error message
after the first item evaluates to ``False`` (short-circuit).
When ``summary`` is set to ``False`` a dictionary is returned containing the individual
evaluation result of each item (non short-circuit).
Examples:
>>> Validator.instance_of(my_str='str', my_str2='str2', target_type=str)
True
>>> Validator.instance_of(my_str1='str', target_type=int)
False
>>> Validator.instance_of(my_str=None, raise_ex=True, target_type=str)
Traceback (most recent call last):
...
ValueError: 'my_str' (NoneType) is not an instance of type 'str'
>>> Validator.instance_of(my_str='a', my_str2=1, raise_ex=True, target_type=str)
Traceback (most recent call last):
...
ValueError: 'my_str2' (int) is not an instance of type 'str'
>>> (Validator.instance_of(
... my_str='str', my_str2='str2', non_str=5, target_type=str, summary=False
... )
... == {'my_str': True, 'my_str2': True, 'non_str': False})
True
Args:
raise_ex (bool, optional): If set to ``True`` an exception is raised if at least one
item is validated to ``False`` (works short-circuit and will abort the validation when
the first item is evaluated to ``False``).
summary (bool, optional): If set to ``False`` instead of returning just a single
`bool` the validation will return a dictionary containing the individual evaluation
result of each item.
target_type (type): The target type to test the values against.
Returns:
(boolean or dictionary): ``True`` when the value was successfully validated; ``False``
otherwise.
If ``summary`` is set to ``False`` a dictionary containing the individual evaluation
result of each item will be returned.
If ``raise_ex`` is set to True, instead of returning False a meaningful error will be
raised.
"""
if not target_type:
raise ValueError("Argument 'target_type' is None")
return Validator.__test_all(
condition=lambda _, val: isinstance(val, cast(type, target_type)),
formatter=(
lambda name, val:
"'{varname}' ({actual}) is not an instance of type '{ttype}'".format(
varname=name,
actual=type(val).__name__,
ttype=cast(type, target_type).__name__
)
),
raise_ex=raise_ex,
summary=summary,
**items
) | [
"def",
"instance_of",
"(",
"target_type",
":",
"Optional",
"[",
"type",
"]",
"=",
"None",
",",
"raise_ex",
":",
"bool",
"=",
"False",
",",
"summary",
":",
"bool",
"=",
"True",
",",
"*",
"*",
"items",
":",
"Any",
")",
"->",
"ValidationReturn",
":",
"i... | Tests if the given key-value pairs (items) are instances of the given ``target_type``.
Per default this function yields whether ``True`` or ``False`` depending on the fact if all
items withstand the validation or not. Per default the validation / evaluation is
short-circuit and will return as soon an item evaluates to ``False``.
When ``raise_ex`` is set to ``True`` the function will raise a meaningful error message
after the first item evaluates to ``False`` (short-circuit).
When ``summary`` is set to ``False`` a dictionary is returned containing the individual
evaluation result of each item (non short-circuit).
Examples:
>>> Validator.instance_of(my_str='str', my_str2='str2', target_type=str)
True
>>> Validator.instance_of(my_str1='str', target_type=int)
False
>>> Validator.instance_of(my_str=None, raise_ex=True, target_type=str)
Traceback (most recent call last):
...
ValueError: 'my_str' (NoneType) is not an instance of type 'str'
>>> Validator.instance_of(my_str='a', my_str2=1, raise_ex=True, target_type=str)
Traceback (most recent call last):
...
ValueError: 'my_str2' (int) is not an instance of type 'str'
>>> (Validator.instance_of(
... my_str='str', my_str2='str2', non_str=5, target_type=str, summary=False
... )
... == {'my_str': True, 'my_str2': True, 'non_str': False})
True
Args:
raise_ex (bool, optional): If set to ``True`` an exception is raised if at least one
item is validated to ``False`` (works short-circuit and will abort the validation when
the first item is evaluated to ``False``).
summary (bool, optional): If set to ``False`` instead of returning just a single
`bool` the validation will return a dictionary containing the individual evaluation
result of each item.
target_type (type): The target type to test the values against.
Returns:
(boolean or dictionary): ``True`` when the value was successfully validated; ``False``
otherwise.
If ``summary`` is set to ``False`` a dictionary containing the individual evaluation
result of each item will be returned.
If ``raise_ex`` is set to True, instead of returning False a meaningful error will be
raised. | [
"Tests",
"if",
"the",
"given",
"key",
"-",
"value",
"pairs",
"(",
"items",
")",
"are",
"instances",
"of",
"the",
"given",
"target_type",
".",
"Per",
"default",
"this",
"function",
"yields",
"whether",
"True",
"or",
"False",
"depending",
"on",
"the",
"fact"... | python | train |
wdecoster/nanoget | nanoget/utils.py | https://github.com/wdecoster/nanoget/blob/fb7306220e261849b96785fab02dd2f35a0e3b60/nanoget/utils.py#L7-L27 | def reduce_memory_usage(df):
"""reduce memory usage of the dataframe
- convert runIDs to categorical
- downcast ints and floats
"""
usage_pre = df.memory_usage(deep=True).sum()
if "runIDs" in df:
df.loc[:, "runIDs"] = df.loc[:, "runIDs"].astype("category")
df_int = df.select_dtypes(include=['int'])
df_float = df.select_dtypes(include=['float'])
df.loc[:, df_int.columns] = df_int.apply(pd.to_numeric, downcast='unsigned')
df.loc[:, df_float.columns] = df_float.apply(pd.to_numeric, downcast='float')
usage_post = df.memory_usage(deep=True).sum()
logging.info("Reduced DataFrame memory usage from {}Mb to {}Mb".format(
usage_pre / 1024**2, usage_post / 1024**2))
if usage_post > 4e9 and "readIDs" in df:
logging.info("DataFrame of features is too big, dropping read identifiers.")
return df.drop(["readIDs"], axis=1, errors="ignore")
else:
return df | [
"def",
"reduce_memory_usage",
"(",
"df",
")",
":",
"usage_pre",
"=",
"df",
".",
"memory_usage",
"(",
"deep",
"=",
"True",
")",
".",
"sum",
"(",
")",
"if",
"\"runIDs\"",
"in",
"df",
":",
"df",
".",
"loc",
"[",
":",
",",
"\"runIDs\"",
"]",
"=",
"df",... | reduce memory usage of the dataframe
- convert runIDs to categorical
- downcast ints and floats | [
"reduce",
"memory",
"usage",
"of",
"the",
"dataframe"
] | python | train |
Opentrons/opentrons | api/src/opentrons/config/pipette_config.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/config/pipette_config.py#L90-L182 | def load(pipette_model: str, pipette_id: str = None) -> pipette_config:
"""
Load pipette config data
This function loads from a combination of
- the pipetteModelSpecs.json file in the wheel (should never be edited)
- the pipetteNameSpecs.json file in the wheel(should never be edited)
- any config overrides found in
``opentrons.config.CONFIG['pipette_config_overrides_dir']``
This function reads from disk each time, so changes to the overrides
will be picked up in subsequent calls.
:param str pipette_model: The pipette model name (i.e. "p10_single_v1.3")
for which to load configuration
:param pipette_id: An (optional) unique ID for the pipette to locate
config overrides. If the ID is not specified, the system
assumes this is a simulated pipette and does not
save settings. If the ID is specified but no overrides
corresponding to the ID are found, the system creates a
new overrides file for it.
:type pipette_id: str or None
:raises KeyError: if ``pipette_model`` is not in the top-level keys of
pipetteModeLSpecs.json (and therefore not in
:py:attr:`configs`)
:returns pipette_config: The configuration, loaded and checked
"""
# Load the model config and update with the name config
cfg = copy.deepcopy(configs[pipette_model])
cfg.update(copy.deepcopy(name_config()[cfg['name']]))
# Load overrides if we have a pipette id
if pipette_id:
try:
override = load_overrides(pipette_id)
except FileNotFoundError:
save_overrides(pipette_id, {}, pipette_model)
log.info(
"Save defaults for pipette model {} and id {}".format(
pipette_model, pipette_id))
else:
cfg.update(override)
# the ulPerMm functions are structured in pipetteModelSpecs.json as
# a list sorted from oldest to newest. That means the latest functions
# are always the last element and, as of right now, the older ones are
# the first element (for models that only have one function, the first
# and last elements are the same, which is fine). If we add more in the
# future, we’ll have to change this code to select items more
# intelligently
if ff.use_old_aspiration_functions():
log.info("Using old aspiration functions")
ul_per_mm = cfg['ulPerMm'][0]
else:
log.info("Using new aspiration functions")
ul_per_mm = cfg['ulPerMm'][-1]
res = pipette_config(
top=ensure_value(
cfg, 'top', mutable_configs),
bottom=ensure_value(
cfg, 'bottom', mutable_configs),
blow_out=ensure_value(
cfg, 'blowout', mutable_configs),
drop_tip=ensure_value(
cfg, 'dropTip', mutable_configs),
pick_up_current=ensure_value(cfg, 'pickUpCurrent', mutable_configs),
pick_up_distance=ensure_value(cfg, 'pickUpDistance', mutable_configs),
pick_up_increment=ensure_value(
cfg, 'pickUpIncrement', mutable_configs),
pick_up_presses=ensure_value(cfg, 'pickUpPresses', mutable_configs),
pick_up_speed=ensure_value(cfg, 'pickUpSpeed', mutable_configs),
aspirate_flow_rate=ensure_value(
cfg, 'defaultAspirateFlowRate', mutable_configs),
dispense_flow_rate=ensure_value(
cfg, 'defaultDispenseFlowRate', mutable_configs),
channels=ensure_value(cfg, 'channels', mutable_configs),
model_offset=ensure_value(cfg, 'modelOffset', mutable_configs),
plunger_current=ensure_value(cfg, 'plungerCurrent', mutable_configs),
drop_tip_current=ensure_value(cfg, 'dropTipCurrent', mutable_configs),
drop_tip_speed=ensure_value(cfg, 'dropTipSpeed', mutable_configs),
min_volume=ensure_value(cfg, 'minVolume', mutable_configs),
max_volume=ensure_value(cfg, 'maxVolume', mutable_configs),
ul_per_mm=ul_per_mm,
quirks=ensure_value(cfg, 'quirks', mutable_configs),
tip_length=ensure_value(cfg, 'tipLength', mutable_configs),
display_name=ensure_value(cfg, 'displayName', mutable_configs)
)
return res | [
"def",
"load",
"(",
"pipette_model",
":",
"str",
",",
"pipette_id",
":",
"str",
"=",
"None",
")",
"->",
"pipette_config",
":",
"# Load the model config and update with the name config",
"cfg",
"=",
"copy",
".",
"deepcopy",
"(",
"configs",
"[",
"pipette_model",
"]"... | Load pipette config data
This function loads from a combination of
- the pipetteModelSpecs.json file in the wheel (should never be edited)
- the pipetteNameSpecs.json file in the wheel(should never be edited)
- any config overrides found in
``opentrons.config.CONFIG['pipette_config_overrides_dir']``
This function reads from disk each time, so changes to the overrides
will be picked up in subsequent calls.
:param str pipette_model: The pipette model name (i.e. "p10_single_v1.3")
for which to load configuration
:param pipette_id: An (optional) unique ID for the pipette to locate
config overrides. If the ID is not specified, the system
assumes this is a simulated pipette and does not
save settings. If the ID is specified but no overrides
corresponding to the ID are found, the system creates a
new overrides file for it.
:type pipette_id: str or None
:raises KeyError: if ``pipette_model`` is not in the top-level keys of
pipetteModeLSpecs.json (and therefore not in
:py:attr:`configs`)
:returns pipette_config: The configuration, loaded and checked | [
"Load",
"pipette",
"config",
"data"
] | python | train |
fermiPy/fermipy | fermipy/jobs/file_archive.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L627-L630 | def get_handle(self, filepath):
"""Get the `FileHandle` object associated to a particular file """
localpath = self._get_localpath(filepath)
return self._cache[localpath] | [
"def",
"get_handle",
"(",
"self",
",",
"filepath",
")",
":",
"localpath",
"=",
"self",
".",
"_get_localpath",
"(",
"filepath",
")",
"return",
"self",
".",
"_cache",
"[",
"localpath",
"]"
] | Get the `FileHandle` object associated to a particular file | [
"Get",
"the",
"FileHandle",
"object",
"associated",
"to",
"a",
"particular",
"file"
] | python | train |
lreis2415/PyGeoC | pygeoc/utils.py | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L1013-L1023 | def get_config_file():
# type: () -> AnyStr
"""Get model configuration file name from argv"""
parser = argparse.ArgumentParser(description="Read configuration file.")
parser.add_argument('-ini', help="Full path of configuration file")
args = parser.parse_args()
ini_file = args.ini
if not FileClass.is_file_exists(ini_file):
print("Usage: -ini <full path to the configuration file.>")
exit(-1)
return ini_file | [
"def",
"get_config_file",
"(",
")",
":",
"# type: () -> AnyStr",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Read configuration file.\"",
")",
"parser",
".",
"add_argument",
"(",
"'-ini'",
",",
"help",
"=",
"\"Full path of configurati... | Get model configuration file name from argv | [
"Get",
"model",
"configuration",
"file",
"name",
"from",
"argv"
] | python | train |
ga4gh/ga4gh-server | ga4gh/server/datamodel/sequence_annotations.py | https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/datamodel/sequence_annotations.py#L411-L437 | def getFeatures(self, referenceName=None, start=None, end=None,
startIndex=None, maxResults=None,
featureTypes=None, parentId=None,
name=None, geneSymbol=None):
"""
method passed to runSearchRequest to fulfill the request
:param str referenceName: name of reference (ex: "chr1")
:param start: castable to int, start position on reference
:param end: castable to int, end position on reference
:param startIndex: none or castable to int
:param maxResults: none or castable to int
:param featureTypes: array of str
:param parentId: none or featureID of parent
:param name: the name of the feature
:param geneSymbol: the symbol for the gene the features are on
:return: yields a protocol.Feature at a time
"""
with self._db as dataSource:
features = dataSource.searchFeaturesInDb(
startIndex, maxResults,
referenceName=referenceName,
start=start, end=end,
parentId=parentId, featureTypes=featureTypes,
name=name, geneSymbol=geneSymbol)
for feature in features:
gaFeature = self._gaFeatureForFeatureDbRecord(feature)
yield gaFeature | [
"def",
"getFeatures",
"(",
"self",
",",
"referenceName",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"startIndex",
"=",
"None",
",",
"maxResults",
"=",
"None",
",",
"featureTypes",
"=",
"None",
",",
"parentId",
"=",
"None",
",... | method passed to runSearchRequest to fulfill the request
:param str referenceName: name of reference (ex: "chr1")
:param start: castable to int, start position on reference
:param end: castable to int, end position on reference
:param startIndex: none or castable to int
:param maxResults: none or castable to int
:param featureTypes: array of str
:param parentId: none or featureID of parent
:param name: the name of the feature
:param geneSymbol: the symbol for the gene the features are on
:return: yields a protocol.Feature at a time | [
"method",
"passed",
"to",
"runSearchRequest",
"to",
"fulfill",
"the",
"request",
":",
"param",
"str",
"referenceName",
":",
"name",
"of",
"reference",
"(",
"ex",
":",
"chr1",
")",
":",
"param",
"start",
":",
"castable",
"to",
"int",
"start",
"position",
"o... | python | train |
ultrabug/py3status | py3status/modules/google_calendar.py | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/google_calendar.py#L339-L357 | def _delta_time(self, date_time):
"""
Returns in a dict the number of days/hours/minutes and total minutes
until date_time.
"""
now = datetime.datetime.now(tzlocal())
diff = date_time - now
days = int(diff.days)
hours = int(diff.seconds / 3600)
minutes = int((diff.seconds / 60) - (hours * 60)) + 1
total_minutes = int((diff.seconds / 60) + (days * 24 * 60)) + 1
return {
"days": days,
"hours": hours,
"minutes": minutes,
"total_minutes": total_minutes,
} | [
"def",
"_delta_time",
"(",
"self",
",",
"date_time",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
"tzlocal",
"(",
")",
")",
"diff",
"=",
"date_time",
"-",
"now",
"days",
"=",
"int",
"(",
"diff",
".",
"days",
")",
"hours",
"="... | Returns in a dict the number of days/hours/minutes and total minutes
until date_time. | [
"Returns",
"in",
"a",
"dict",
"the",
"number",
"of",
"days",
"/",
"hours",
"/",
"minutes",
"and",
"total",
"minutes",
"until",
"date_time",
"."
] | python | train |
peri-source/peri | peri/opt/addsubtract.py | https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/addsubtract.py#L309-L425 | def remove_bad_particles(st, min_rad='calc', max_rad='calc', min_edge_dist=2.0,
check_rad_cutoff=[3.5, 15], check_outside_im=True,
tries=50, im_change_frac=0.2, **kwargs):
"""
Removes improperly-featured particles from the state, based on a
combination of particle size and the change in error on removal.
Parameters
-----------
st : :class:`peri.states.State`
The state to remove bad particles from.
min_rad : Float, optional
All particles with radius below min_rad are automatically deleted.
Set to 'calc' to make it the median rad - 25* radius std.
Default is 'calc'.
max_rad : Float, optional
All particles with radius above max_rad are automatically deleted.
Set to 'calc' to make it the median rad + 15* radius std.
Default is 'calc'.
min_edge_dist : Float, optional
All particles within min_edge_dist of the (padded) image
edges are automatically deleted. Default is 2.0
check_rad_cutoff : 2-element list of floats, optional
Particles with radii < check_rad_cutoff[0] or > check_rad_cutoff[1]
are checked if they should be deleted. Set to 'calc' to make it the
median rad +- 3.5 * radius std. Default is [3.5, 15].
check_outside_im : Bool, optional
If True, checks if particles located outside the unpadded image
should be deleted. Default is True.
tries : Int, optional
The maximum number of particles with radii < check_rad_cutoff
to try to remove. Checks in increasing order of radius size.
Default is 50.
im_change_frac : Float, , optional
Number between 0 and 1. If removing a particle decreases the
error by less than im_change_frac*the change in the image, then
the particle is deleted. Default is 0.2
Returns
-------
removed: Int
The cumulative number of particles removed.
"""
is_near_im_edge = lambda pos, pad: (((pos + st.pad) < pad) | (pos >
np.array(st.ishape.shape) + st.pad - pad)).any(axis=1)
# returns True if the position is within 'pad' of the _outer_ image edge
removed = 0
attempts = 0
n_tot_part = st.obj_get_positions().shape[0]
q10 = int(0.1 * n_tot_part) # 10% quartile
r_sig = np.sort(st.obj_get_radii())[q10:-q10].std()
r_med = np.median(st.obj_get_radii())
if max_rad == 'calc':
max_rad = r_med + 15*r_sig
if min_rad == 'calc':
min_rad = r_med - 25*r_sig
if check_rad_cutoff == 'calc':
check_rad_cutoff = [r_med - 7.5*r_sig, r_med + 7.5*r_sig]
# 1. Automatic deletion:
rad_wrong_size = np.nonzero(
(st.obj_get_radii() < min_rad) | (st.obj_get_radii() > max_rad))[0]
near_im_edge = np.nonzero(is_near_im_edge(st.obj_get_positions(),
min_edge_dist - st.pad))[0]
delete_inds = np.unique(np.append(rad_wrong_size, near_im_edge)).tolist()
delete_poses = st.obj_get_positions()[delete_inds].tolist()
message = ('-'*27 + 'SUBTRACTING' + '-'*28 +
'\n Z\t Y\t X\t R\t|\t ERR0\t\t ERR1')
with log.noformat():
CLOG.info(message)
for pos in delete_poses:
ind = st.obj_closest_particle(pos)
old_err = st.error
p, r = st.obj_remove_particle(ind)
p = p[0]
r = r[0]
part_msg = '%2.2f\t%3.2f\t%3.2f\t%3.2f\t|\t%4.3f \t%4.3f' % (
tuple(p) + (r,) + (old_err, st.error))
with log.noformat():
CLOG.info(part_msg)
removed += 1
# 2. Conditional deletion:
check_rad_inds = np.nonzero((st.obj_get_radii() < check_rad_cutoff[0]) |
(st.obj_get_radii() > check_rad_cutoff[1]))[0]
if check_outside_im:
check_edge_inds = np.nonzero(
is_near_im_edge(st.obj_get_positions(), st.pad))[0]
check_inds = np.unique(np.append(check_rad_inds, check_edge_inds))
else:
check_inds = check_rad_inds
check_inds = check_inds[np.argsort(st.obj_get_radii()[check_inds])]
tries = np.min([tries, check_inds.size])
check_poses = st.obj_get_positions()[check_inds[:tries]].copy()
for pos in check_poses:
old_err = st.error
ind = st.obj_closest_particle(pos)
killed, p, r = check_remove_particle(
st, ind, im_change_frac=im_change_frac)
if killed:
removed += 1
check_inds[check_inds > ind] -= 1 # cleaning up indices....
delete_poses.append(pos)
part_msg = '%2.2f\t%3.2f\t%3.2f\t%3.2f\t|\t%4.3f \t%4.3f' % (
p + r + (old_err, st.error))
with log.noformat():
CLOG.info(part_msg)
return removed, delete_poses | [
"def",
"remove_bad_particles",
"(",
"st",
",",
"min_rad",
"=",
"'calc'",
",",
"max_rad",
"=",
"'calc'",
",",
"min_edge_dist",
"=",
"2.0",
",",
"check_rad_cutoff",
"=",
"[",
"3.5",
",",
"15",
"]",
",",
"check_outside_im",
"=",
"True",
",",
"tries",
"=",
"... | Removes improperly-featured particles from the state, based on a
combination of particle size and the change in error on removal.
Parameters
-----------
st : :class:`peri.states.State`
The state to remove bad particles from.
min_rad : Float, optional
All particles with radius below min_rad are automatically deleted.
Set to 'calc' to make it the median rad - 25* radius std.
Default is 'calc'.
max_rad : Float, optional
All particles with radius above max_rad are automatically deleted.
Set to 'calc' to make it the median rad + 15* radius std.
Default is 'calc'.
min_edge_dist : Float, optional
All particles within min_edge_dist of the (padded) image
edges are automatically deleted. Default is 2.0
check_rad_cutoff : 2-element list of floats, optional
Particles with radii < check_rad_cutoff[0] or > check_rad_cutoff[1]
are checked if they should be deleted. Set to 'calc' to make it the
median rad +- 3.5 * radius std. Default is [3.5, 15].
check_outside_im : Bool, optional
If True, checks if particles located outside the unpadded image
should be deleted. Default is True.
tries : Int, optional
The maximum number of particles with radii < check_rad_cutoff
to try to remove. Checks in increasing order of radius size.
Default is 50.
im_change_frac : Float, , optional
Number between 0 and 1. If removing a particle decreases the
error by less than im_change_frac*the change in the image, then
the particle is deleted. Default is 0.2
Returns
-------
removed: Int
The cumulative number of particles removed. | [
"Removes",
"improperly",
"-",
"featured",
"particles",
"from",
"the",
"state",
"based",
"on",
"a",
"combination",
"of",
"particle",
"size",
"and",
"the",
"change",
"in",
"error",
"on",
"removal",
"."
] | python | valid |
scikit-tda/kepler-mapper | kmapper/kmapper.py | https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/kmapper.py#L807-L830 | def data_from_cluster_id(self, cluster_id, graph, data):
"""Returns the original data of each cluster member for a given cluster ID
Parameters
----------
cluster_id : String
ID of the cluster.
graph : dict
The resulting dictionary after applying map()
data : Numpy Array
Original dataset. Accepts both 1-D and 2-D array.
Returns
-------
entries:
rows of cluster member data as Numpy array.
"""
if cluster_id in graph["nodes"]:
cluster_members = graph["nodes"][cluster_id]
cluster_members_data = data[cluster_members]
return cluster_members_data
else:
return np.array([]) | [
"def",
"data_from_cluster_id",
"(",
"self",
",",
"cluster_id",
",",
"graph",
",",
"data",
")",
":",
"if",
"cluster_id",
"in",
"graph",
"[",
"\"nodes\"",
"]",
":",
"cluster_members",
"=",
"graph",
"[",
"\"nodes\"",
"]",
"[",
"cluster_id",
"]",
"cluster_member... | Returns the original data of each cluster member for a given cluster ID
Parameters
----------
cluster_id : String
ID of the cluster.
graph : dict
The resulting dictionary after applying map()
data : Numpy Array
Original dataset. Accepts both 1-D and 2-D array.
Returns
-------
entries:
rows of cluster member data as Numpy array. | [
"Returns",
"the",
"original",
"data",
"of",
"each",
"cluster",
"member",
"for",
"a",
"given",
"cluster",
"ID"
] | python | train |
Opentrons/opentrons | api/src/opentrons/protocol_api/contexts.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/contexts.py#L1040-L1052 | def home(self) -> 'InstrumentContext':
""" Home the robot.
:returns: This instance.
"""
def home_dummy(mount): pass
cmds.do_publish(self.broker, cmds.home, home_dummy,
'before', None, None, self._mount.name.lower())
self._hw_manager.hardware.home_z(self._mount)
self._hw_manager.hardware.home_plunger(self._mount)
cmds.do_publish(self.broker, cmds.home, home_dummy,
'after', self, None, self._mount.name.lower())
return self | [
"def",
"home",
"(",
"self",
")",
"->",
"'InstrumentContext'",
":",
"def",
"home_dummy",
"(",
"mount",
")",
":",
"pass",
"cmds",
".",
"do_publish",
"(",
"self",
".",
"broker",
",",
"cmds",
".",
"home",
",",
"home_dummy",
",",
"'before'",
",",
"None",
",... | Home the robot.
:returns: This instance. | [
"Home",
"the",
"robot",
"."
] | python | train |
pnegahdar/inenv | inenv/cli.py | https://github.com/pnegahdar/inenv/blob/8f484e520892bf9eb59f91b4b5c92df9fbd9a4e6/inenv/cli.py#L133-L139 | def init(venv_name):
"""Initializez a virtualenv"""
inenv = InenvManager()
inenv.get_prepped_venv(venv_name, skip_cached=False)
if not os.getenv(INENV_ENV_VAR):
activator_warn(inenv)
click.secho("Your venv is ready. Enjoy!", fg='green') | [
"def",
"init",
"(",
"venv_name",
")",
":",
"inenv",
"=",
"InenvManager",
"(",
")",
"inenv",
".",
"get_prepped_venv",
"(",
"venv_name",
",",
"skip_cached",
"=",
"False",
")",
"if",
"not",
"os",
".",
"getenv",
"(",
"INENV_ENV_VAR",
")",
":",
"activator_warn"... | Initializez a virtualenv | [
"Initializez",
"a",
"virtualenv"
] | python | train |
snare/scruffy | scruffy/state.py | https://github.com/snare/scruffy/blob/0fedc08cfdb6db927ff93c09f25f24ce5a04c541/scruffy/state.py#L69-L74 | def cleanup(self):
"""
Clean up the saved state.
"""
if os.path.exists(self.path):
os.remove(self.path) | [
"def",
"cleanup",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"path",
")",
":",
"os",
".",
"remove",
"(",
"self",
".",
"path",
")"
] | Clean up the saved state. | [
"Clean",
"up",
"the",
"saved",
"state",
"."
] | python | test |
baruwa-enterprise/BaruwaAPI | BaruwaAPI/resource.py | https://github.com/baruwa-enterprise/BaruwaAPI/blob/53335b377ccfd388e42f4f240f181eed72f51180/BaruwaAPI/resource.py#L269-L274 | def create_domain_smarthost(self, domainid, data):
"""Create a domain smarthost"""
return self.api_call(
ENDPOINTS['domainsmarthosts']['new'],
dict(domainid=domainid),
body=data) | [
"def",
"create_domain_smarthost",
"(",
"self",
",",
"domainid",
",",
"data",
")",
":",
"return",
"self",
".",
"api_call",
"(",
"ENDPOINTS",
"[",
"'domainsmarthosts'",
"]",
"[",
"'new'",
"]",
",",
"dict",
"(",
"domainid",
"=",
"domainid",
")",
",",
"body",
... | Create a domain smarthost | [
"Create",
"a",
"domain",
"smarthost"
] | python | train |
albahnsen/CostSensitiveClassification | costcla/sampling/cost_sampling.py | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/sampling/cost_sampling.py#L11-L123 | def cost_sampling(X, y, cost_mat, method='RejectionSampling', oversampling_norm=0.1, max_wc=97.5):
"""Cost-proportionate sampling.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
y : array-like of shape = [n_samples]
Ground truth (correct) labels.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
method : str, optional (default = RejectionSampling)
Method to perform the cost-proportionate sampling,
either 'RejectionSampling' or 'OverSampling'.
oversampling_norm: float, optional (default = 0.1)
normalize value of wc, the smaller the biggest the data.
max_wc: float, optional (default = 97.5)
outlier adjustment for the cost.
References
----------
.. [1] B. Zadrozny, J. Langford, N. Naoki, "Cost-sensitive learning by
cost-proportionate example weighting", in Proceedings of the
Third IEEE International Conference on Data Mining, 435-442, 2003.
.. [2] C. Elkan, "The foundations of Cost-Sensitive Learning",
in Seventeenth International Joint Conference on Artificial Intelligence,
973-978, 2001.
Examples
--------
>>> from sklearn.ensemble import RandomForestClassifier
>>> from sklearn.cross_validation import train_test_split
>>> from costcla.datasets import load_creditscoring1
>>> from costcla.sampling import cost_sampling, undersampling
>>> from costcla.metrics import savings_score
>>> data = load_creditscoring1()
>>> sets = train_test_split(data.data, data.target, data.cost_mat, test_size=0.33, random_state=0)
>>> X_train, X_test, y_train, y_test, cost_mat_train, cost_mat_test = sets
>>> X_cps_o, y_cps_o, cost_mat_cps_o = cost_sampling(X_train, y_train, cost_mat_train, method='OverSampling')
>>> X_cps_r, y_cps_r, cost_mat_cps_r = cost_sampling(X_train, y_train, cost_mat_train, method='RejectionSampling')
>>> X_u, y_u, cost_mat_u = undersampling(X_train, y_train, cost_mat_train)
>>> y_pred_test_rf = RandomForestClassifier(random_state=0).fit(X_train, y_train).predict(X_test)
>>> y_pred_test_rf_cps_o = RandomForestClassifier(random_state=0).fit(X_cps_o, y_cps_o).predict(X_test)
>>> y_pred_test_rf_cps_r = RandomForestClassifier(random_state=0).fit(X_cps_r, y_cps_r).predict(X_test)
>>> y_pred_test_rf_u = RandomForestClassifier(random_state=0).fit(X_u, y_u).predict(X_test)
>>> # Savings using only RandomForest
>>> print(savings_score(y_test, y_pred_test_rf, cost_mat_test))
0.12454256594
>>> # Savings using RandomForest with cost-proportionate over-sampling
>>> print(savings_score(y_test, y_pred_test_rf_cps_o, cost_mat_test))
0.192480226286
>>> # Savings using RandomForest with cost-proportionate rejection-sampling
>>> print(savings_score(y_test, y_pred_test_rf_cps_r, cost_mat_test))
0.465830173459
>>> # Savings using RandomForest with under-sampling
>>> print(savings_score(y_test, y_pred_test_rf_u, cost_mat_test))
0.466630646543
>>> # Size of each training set
>>> print(X_train.shape[0], X_cps_o.shape[0], X_cps_r.shape[0], X_u.shape[0])
75653 109975 8690 10191
>>> # Percentage of positives in each training set
>>> print(y_train.mean(), y_cps_o.mean(), y_cps_r.mean(), y_u.mean())
0.0668182358928 0.358054103205 0.436939010357 0.49602590521
"""
#TODO: Check consistency of input
# The methods are construct only for the misclassification costs, not the full cost matrix.
cost_mis = cost_mat[:, 0]
cost_mis[y == 1] = cost_mat[y == 1, 1]
# wc = cost_mis / cost_mis.max()
wc = np.minimum(cost_mis / np.percentile(cost_mis, max_wc), 1)
n_samples = X.shape[0]
filter_ = list(range(n_samples))
if method == 'RejectionSampling':
# under-sampling by rejection [1]
#TODO: Add random state
rej_rand = np.random.rand(n_samples)
filter_ = rej_rand <= wc
elif method == 'OverSampling':
# over-sampling with normalized wn [2]
wc_n = np.ceil(wc / oversampling_norm).astype(np.int)
new_n = wc_n.sum()
filter_ = np.ones(new_n, dtype=np.int)
e = 0
#TODO replace for
for i in range(n_samples):
filter_[e: e + wc_n[i]] = i
e += wc_n[i]
x_cps = X[filter_]
y_cps = y[filter_]
cost_mat_cps = cost_mat[filter_]
return x_cps, y_cps, cost_mat_cps | [
"def",
"cost_sampling",
"(",
"X",
",",
"y",
",",
"cost_mat",
",",
"method",
"=",
"'RejectionSampling'",
",",
"oversampling_norm",
"=",
"0.1",
",",
"max_wc",
"=",
"97.5",
")",
":",
"#TODO: Check consistency of input",
"# The methods are construct only for the misclassifi... | Cost-proportionate sampling.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
y : array-like of shape = [n_samples]
Ground truth (correct) labels.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix of the classification problem
Where the columns represents the costs of: false positives, false negatives,
true positives and true negatives, for each example.
method : str, optional (default = RejectionSampling)
Method to perform the cost-proportionate sampling,
either 'RejectionSampling' or 'OverSampling'.
oversampling_norm: float, optional (default = 0.1)
normalize value of wc, the smaller the biggest the data.
max_wc: float, optional (default = 97.5)
outlier adjustment for the cost.
References
----------
.. [1] B. Zadrozny, J. Langford, N. Naoki, "Cost-sensitive learning by
cost-proportionate example weighting", in Proceedings of the
Third IEEE International Conference on Data Mining, 435-442, 2003.
.. [2] C. Elkan, "The foundations of Cost-Sensitive Learning",
in Seventeenth International Joint Conference on Artificial Intelligence,
973-978, 2001.
Examples
--------
>>> from sklearn.ensemble import RandomForestClassifier
>>> from sklearn.cross_validation import train_test_split
>>> from costcla.datasets import load_creditscoring1
>>> from costcla.sampling import cost_sampling, undersampling
>>> from costcla.metrics import savings_score
>>> data = load_creditscoring1()
>>> sets = train_test_split(data.data, data.target, data.cost_mat, test_size=0.33, random_state=0)
>>> X_train, X_test, y_train, y_test, cost_mat_train, cost_mat_test = sets
>>> X_cps_o, y_cps_o, cost_mat_cps_o = cost_sampling(X_train, y_train, cost_mat_train, method='OverSampling')
>>> X_cps_r, y_cps_r, cost_mat_cps_r = cost_sampling(X_train, y_train, cost_mat_train, method='RejectionSampling')
>>> X_u, y_u, cost_mat_u = undersampling(X_train, y_train, cost_mat_train)
>>> y_pred_test_rf = RandomForestClassifier(random_state=0).fit(X_train, y_train).predict(X_test)
>>> y_pred_test_rf_cps_o = RandomForestClassifier(random_state=0).fit(X_cps_o, y_cps_o).predict(X_test)
>>> y_pred_test_rf_cps_r = RandomForestClassifier(random_state=0).fit(X_cps_r, y_cps_r).predict(X_test)
>>> y_pred_test_rf_u = RandomForestClassifier(random_state=0).fit(X_u, y_u).predict(X_test)
>>> # Savings using only RandomForest
>>> print(savings_score(y_test, y_pred_test_rf, cost_mat_test))
0.12454256594
>>> # Savings using RandomForest with cost-proportionate over-sampling
>>> print(savings_score(y_test, y_pred_test_rf_cps_o, cost_mat_test))
0.192480226286
>>> # Savings using RandomForest with cost-proportionate rejection-sampling
>>> print(savings_score(y_test, y_pred_test_rf_cps_r, cost_mat_test))
0.465830173459
>>> # Savings using RandomForest with under-sampling
>>> print(savings_score(y_test, y_pred_test_rf_u, cost_mat_test))
0.466630646543
>>> # Size of each training set
>>> print(X_train.shape[0], X_cps_o.shape[0], X_cps_r.shape[0], X_u.shape[0])
75653 109975 8690 10191
>>> # Percentage of positives in each training set
>>> print(y_train.mean(), y_cps_o.mean(), y_cps_r.mean(), y_u.mean())
0.0668182358928 0.358054103205 0.436939010357 0.49602590521 | [
"Cost",
"-",
"proportionate",
"sampling",
"."
] | python | train |
tanghaibao/jcvi | jcvi/graphics/tree.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/graphics/tree.py#L222-L251 | def draw_geoscale(ax, minx=0, maxx=175):
"""
Draw geological epoch on million year ago (mya) scale.
"""
a, b = .1, .6 # Correspond to 200mya and 0mya
def cv(x): return b - (x - b) / (maxx - minx) * (b - a)
ax.plot((a, b), (.5, .5), "k-")
tick = .015
for mya in xrange(maxx - 25, 0, -25):
p = cv(mya)
ax.plot((p, p), (.5, .5 - tick), "k-")
ax.text(p, .5 - 2.5 * tick, str(mya), ha="center", va="center")
ax.text((a + b) / 2, .5 - 5 * tick, "Time before present (million years)",
ha="center", va="center")
# Source:
# http://www.weston.org/schools/ms/biologyweb/evolution/handouts/GSAchron09.jpg
Geo = (("Neogene", 2.6, 23.0, "#fee400"),
("Paleogene", 23.0, 65.5, "#ff9a65"),
("Cretaceous", 65.5, 145.5, "#80ff40"),
("Jurassic", 145.5, 201.6, "#33fff3"))
h = .05
for era, start, end, color in Geo:
start, end = cv(start), cv(end)
end = max(a, end)
p = Rectangle((end, .5 + tick / 2), abs(start - end),
h, lw=1, ec="w", fc=color)
ax.text((start + end) / 2, .5 + (tick + h) / 2, era,
ha="center", va="center", size=9)
ax.add_patch(p) | [
"def",
"draw_geoscale",
"(",
"ax",
",",
"minx",
"=",
"0",
",",
"maxx",
"=",
"175",
")",
":",
"a",
",",
"b",
"=",
".1",
",",
".6",
"# Correspond to 200mya and 0mya",
"def",
"cv",
"(",
"x",
")",
":",
"return",
"b",
"-",
"(",
"x",
"-",
"b",
")",
"... | Draw geological epoch on million year ago (mya) scale. | [
"Draw",
"geological",
"epoch",
"on",
"million",
"year",
"ago",
"(",
"mya",
")",
"scale",
"."
] | python | train |
sethmlarson/virtualbox-python | virtualbox/library.py | https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L20871-L20894 | def read(self, to_read, timeout_ms):
"""Reads data from this file.
in to_read of type int
Number of bytes to read.
in timeout_ms of type int
Timeout (in ms) to wait for the operation to complete.
Pass 0 for an infinite timeout.
return data of type str
Array of data read.
raises :class:`OleErrorNotimpl`
The method is not implemented yet.
"""
if not isinstance(to_read, baseinteger):
raise TypeError("to_read can only be an instance of type baseinteger")
if not isinstance(timeout_ms, baseinteger):
raise TypeError("timeout_ms can only be an instance of type baseinteger")
data = self._call("read",
in_p=[to_read, timeout_ms])
return data | [
"def",
"read",
"(",
"self",
",",
"to_read",
",",
"timeout_ms",
")",
":",
"if",
"not",
"isinstance",
"(",
"to_read",
",",
"baseinteger",
")",
":",
"raise",
"TypeError",
"(",
"\"to_read can only be an instance of type baseinteger\"",
")",
"if",
"not",
"isinstance",
... | Reads data from this file.
in to_read of type int
Number of bytes to read.
in timeout_ms of type int
Timeout (in ms) to wait for the operation to complete.
Pass 0 for an infinite timeout.
return data of type str
Array of data read.
raises :class:`OleErrorNotimpl`
The method is not implemented yet. | [
"Reads",
"data",
"from",
"this",
"file",
"."
] | python | train |
renweizhukov/pytwis | pytwis/pytwis_clt.py | https://github.com/renweizhukov/pytwis/blob/1bc45b038d7e5343824c520f89f644bbd6faab0a/pytwis/pytwis_clt.py#L518-L604 | def get_pytwis(epilog):
"""Connect to the Redis database and return the Pytwis instance.
Parameters
----------
epilog: str
An epilog string which will be displayed by ArgumentParser.
Returns
-------
pytwis: A Pytwis instance.
prompt: str
The prompt string which contains either the hostname and the port or the socket.
Raises
------
ValueError
If we fail to connect to the Redis server.
"""
# Note that we set the conflict handler of ArgumentParser to 'resolve' because we reuse
# the short help option '-h' for the host name.
parser = argparse.ArgumentParser(conflict_handler="resolve",
formatter_class=argparse.RawDescriptionHelpFormatter,
description=\
'Connect to the Redis database of a Twitter clone and '
'then run commands to access and update the database.',
epilog=epilog)
parser.add_argument('-h', '--hostname', nargs='?', default='127.0.0.1',
help='''the Redis server hostname. If the option is not specified,
will be defaulted to 127.0.0.1. If the option is specified but
no value is given after the option, then the help information
is displayed instead.
''')
parser.add_argument('-p', '--port', default=6379,
help='''the Redis server port. If the option is not specified, will
be defaulted to 6379.
''')
parser.add_argument('-s', '--socket', default='',
help='''the Redis server socket (usually /tmp/redis.sock). If it is
given, it will override hostname and port. Make sure that the
unixsocket parameter is defined in your redis.conf file. It’s
commented out by default.
''')
parser.add_argument('-n', '--db', default=0,
help='''the Redis server database. If the option is not specified,
will be defaulted to 0.
''')
parser.add_argument('-a', '--password', default='',
help='''the Redis server password. If the option not specified,
will be defaulted to an empty string.
''')
args = parser.parse_args()
# If no value is given after the option '-h', then the help information is displayed.
if args.hostname is None:
parser.print_help()
return 0
if args.socket:
print('The input Redis server socket is {}'.format(args.socket))
prompt = args.socket
else:
print('The input Redis server hostname is {}.'.format(args.hostname))
print('The input Redis server port is {}.'.format(args.port))
prompt = '{}:{}'.format(args.hostname, args.port)
print('The input Redis server database is {}.'.format(args.db))
if args.password != '':
print('The input Redis server password is "{}".'.format(args.password))
else:
print('The input Redis server password is empty.')
try:
if args.socket:
twis = pytwis.Pytwis(socket=args.socket,
db=args.db,
password=args.password)
else:
twis = pytwis.Pytwis(hostname=args.hostname,
port=args.port,
db=args.db,
password=args.password)
return twis, prompt
except ValueError as excep:
print('Failed to connect to the Redis server: {}'.format(str(excep)),
file=sys.stderr)
return None, None | [
"def",
"get_pytwis",
"(",
"epilog",
")",
":",
"# Note that we set the conflict handler of ArgumentParser to 'resolve' because we reuse",
"# the short help option '-h' for the host name.",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"conflict_handler",
"=",
"\"resolve\"",
... | Connect to the Redis database and return the Pytwis instance.
Parameters
----------
epilog: str
An epilog string which will be displayed by ArgumentParser.
Returns
-------
pytwis: A Pytwis instance.
prompt: str
The prompt string which contains either the hostname and the port or the socket.
Raises
------
ValueError
If we fail to connect to the Redis server. | [
"Connect",
"to",
"the",
"Redis",
"database",
"and",
"return",
"the",
"Pytwis",
"instance",
"."
] | python | train |
census-instrumentation/opencensus-python | contrib/opencensus-ext-dbapi/opencensus/ext/dbapi/trace.py | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-dbapi/opencensus/ext/dbapi/trace.py#L24-L36 | def wrap_conn(conn_func):
"""Wrap the mysql conn object with TraceConnection."""
def call(*args, **kwargs):
try:
conn = conn_func(*args, **kwargs)
cursor_func = getattr(conn, CURSOR_WRAP_METHOD)
wrapped = wrap_cursor(cursor_func)
setattr(conn, cursor_func.__name__, wrapped)
return conn
except Exception: # pragma: NO COVER
logging.warning('Fail to wrap conn, mysql not traced.')
return conn_func(*args, **kwargs)
return call | [
"def",
"wrap_conn",
"(",
"conn_func",
")",
":",
"def",
"call",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"conn",
"=",
"conn_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"cursor_func",
"=",
"getattr",
"(",
"conn",
... | Wrap the mysql conn object with TraceConnection. | [
"Wrap",
"the",
"mysql",
"conn",
"object",
"with",
"TraceConnection",
"."
] | python | train |
wummel/linkchecker | linkcheck/plugins/markdowncheck.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/plugins/markdowncheck.py#L139-L156 | def _extract_url_and_title(self, text, start):
"""Extracts the url from the tail of a link."""
# text[start] equals the opening parenthesis
idx = self._whitespace.match(text, start + 1).end()
if idx == len(text):
return None, None
end_idx = idx
has_anglebrackets = text[idx] == "<"
if has_anglebrackets:
end_idx = self._find_balanced(text, end_idx+1, "<", ">")
end_idx = self._find_balanced(text, end_idx, "(", ")")
match = self._inline_link_title.search(text, idx, end_idx)
if not match:
return None, None
url = text[idx:match.start()]
if has_anglebrackets:
url = self._strip_anglebrackets.sub(r'\1', url)
return url, end_idx | [
"def",
"_extract_url_and_title",
"(",
"self",
",",
"text",
",",
"start",
")",
":",
"# text[start] equals the opening parenthesis",
"idx",
"=",
"self",
".",
"_whitespace",
".",
"match",
"(",
"text",
",",
"start",
"+",
"1",
")",
".",
"end",
"(",
")",
"if",
"... | Extracts the url from the tail of a link. | [
"Extracts",
"the",
"url",
"from",
"the",
"tail",
"of",
"a",
"link",
"."
] | python | train |
linuxsoftware/ls.joyous | ls/joyous/templatetags/joyous_tags.py | https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/templatetags/joyous_tags.py#L143-L148 | def location_gmap(context, location):
"""Display a link to Google maps iff we are using WagtailGMaps"""
gmapq = None
if getattr(MapFieldPanel, "UsingWagtailGMaps", False):
gmapq = location
return {'gmapq': gmapq} | [
"def",
"location_gmap",
"(",
"context",
",",
"location",
")",
":",
"gmapq",
"=",
"None",
"if",
"getattr",
"(",
"MapFieldPanel",
",",
"\"UsingWagtailGMaps\"",
",",
"False",
")",
":",
"gmapq",
"=",
"location",
"return",
"{",
"'gmapq'",
":",
"gmapq",
"}"
] | Display a link to Google maps iff we are using WagtailGMaps | [
"Display",
"a",
"link",
"to",
"Google",
"maps",
"iff",
"we",
"are",
"using",
"WagtailGMaps"
] | python | train |
wiheto/teneto | teneto/networkmeasures/volatility.py | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/networkmeasures/volatility.py#L5-L188 | def volatility(tnet, distance_func_name='default', calc='global', communities=None, event_displacement=None):
r"""
Volatility of temporal networks.
Volatility is the average distance between consecutive time points of graphlets (difference is caclualted either globally or per edge).
Parameters
----------
tnet : array or dict
temporal network input (graphlet or contact). Nettype: 'bu','bd','wu','wd'
D : str
Distance function. Following options available: 'default', 'hamming', 'euclidean'. (Default implies hamming for binary networks, euclidean for weighted).
calc : str
Version of volaitility to caclulate. Possibilities include:
'global' - (default): the average distance of all nodes for each consecutive time point).
'edge' - average distance between consecutive time points for each edge). Takes considerably longer
'node' - (i.e. returns the average per node output when calculating volatility per 'edge').
'time' - returns volatility per time point
'communities' - returns volatility per communitieswork id (see communities). Also is returned per time-point and this may be changed in the future (with additional options)
'event_displacement' - calculates the volatility from a specified point. Returns time-series.
communities : array
Array of indicies for community (eiter (node) or (node,time) dimensions).
event_displacement : int
if calc = event_displacement specify the temporal index where all other time-points are calculated in relation too.
Notes
-----
Volatility calculates the difference between network snapshots.
.. math:: V_t = D(G_t,G_{t+1})
Where D is some distance function (e.g. Hamming distance for binary matrices).
V can be calculated for the entire network (global), but can also be calculated for individual edges, nodes or given a community vector.
Index of communities are returned "as is" with a shape of [max(communities)+1,max(communities)+1]. So if the indexes used are [1,2,3,5], V.shape==(6,6). The returning V[1,2] will correspond indexes 1 and 2. And missing index (e.g. here 0 and 4 will be NANs in rows and columns). If this behaviour is unwanted, call clean_communitiesdexes first. This will probably change.
Examples
--------
Import everything needed.
>>> import teneto
>>> import numpy
>>> np.random.seed(1)
>>> tnet = teneto.TemporalNetwork(nettype='bu')
Here we generate a binary network where edges have a 0.5 change of going "on", and once on a 0.2 change to go "off"
>>> tnet.generatenetwork('rand_binomial', size=(3,10), prob=(0.5,0.2))
Calculate the volatility
>>> tnet.calc_networkmeasure('volatility', distance_func_name='hamming')
0.5555555555555556
If we change the probabilities to instead be certain edges disapeared the time-point after the appeared:
>>> tnet.generatenetwork('rand_binomial', size=(3,10), prob=(0.5,1))
This will make a more volatile network
>>> tnet.calc_networkmeasure('volatility', distance_func_name='hamming')
0.1111111111111111
We can calculate the volatility per time instead
>>> vol_time = tnet.calc_networkmeasure('volatility', calc='time', distance_func_name='hamming')
>>> len(vol_time)
9
>>> vol_time[0]
0.3333333333333333
Or per node:
>>> vol_node = tnet.calc_networkmeasure('volatility', calc='node', distance_func_name='hamming')
>>> vol_node
array([0.07407407, 0.07407407, 0.07407407])
Here we see the volatility for each node was the same.
It is also possible to pass a community vector and the function will return volatility both within and between each community.
So the following has two communities:
>>> vol_com = tnet.calc_networkmeasure('volatility', calc='communities', communities=[0,1,1], distance_func_name='hamming')
>>> vol_com.shape
(2, 2, 9)
>>> vol_com[:,:,0]
array([[nan, 0.5],
[0.5, 0. ]])
And we see that, at time-point 0, there is some volatility between community 0 and 1 but no volatility within community 1. The reason for nan appearing is due to there only being 1 node in community 0.
Output
------
vol : array
"""
# Get input (C or G)
tnet, netinfo = process_input(tnet, ['C', 'G', 'TN'])
distance_func_name = check_distance_funciton_input(
distance_func_name, netinfo)
if not isinstance(distance_func_name, str):
raise ValueError('Distance metric must be a string')
# If not directional, only calc on the uppertriangle
if netinfo['nettype'][1] == 'd':
ind = np.triu_indices(tnet.shape[0], k=-tnet.shape[0])
elif netinfo['nettype'][1] == 'u':
ind = np.triu_indices(tnet.shape[0], k=1)
if calc == 'communities':
# Make sure communities is np array for indexing later on.
communities = np.array(communities)
if len(communities) != netinfo['netshape'][0]:
raise ValueError(
'When processing per network, communities vector must equal the number of nodes')
if communities.min() < 0:
raise ValueError(
'Communitiy assignments must be positive integers')
# Get chosen distance metric fucntion
distance_func = getDistanceFunction(distance_func_name)
if calc == 'global':
vol = np.mean([distance_func(tnet[ind[0], ind[1], t], tnet[ind[0], ind[1], t + 1])
for t in range(0, tnet.shape[-1] - 1)])
elif calc == 'time':
vol = [distance_func(tnet[ind[0], ind[1], t], tnet[ind[0], ind[1], t + 1])
for t in range(0, tnet.shape[-1] - 1)]
elif calc == 'event_displacement':
vol = [distance_func(tnet[ind[0], ind[1], event_displacement],
tnet[ind[0], ind[1], t]) for t in range(0, tnet.shape[-1])]
# This takes quite a bit of time to loop through. When calculating per edge/node.
elif calc == 'edge' or calc == 'node':
vol = np.zeros([tnet.shape[0], tnet.shape[1]])
for i in ind[0]:
for j in ind[1]:
vol[i, j] = np.mean([distance_func(
tnet[i, j, t], tnet[i, j, t + 1]) for t in range(0, tnet.shape[-1] - 1)])
if netinfo['nettype'][1] == 'u':
vol = vol + np.transpose(vol)
if calc == 'node':
vol = np.mean(vol, axis=1)
elif calc == 'communities':
net_id = set(communities)
vol = np.zeros([max(net_id) + 1, max(net_id) +
1, netinfo['netshape'][-1] - 1])
for net1 in net_id:
for net2 in net_id:
if net1 != net2:
vol[net1, net2, :] = [distance_func(tnet[communities == net1][:, communities == net2, t].flatten(),
tnet[communities == net1][:, communities == net2, t + 1].flatten()) for t in range(0, tnet.shape[-1] - 1)]
else:
nettmp = tnet[communities ==
net1][:, communities == net2, :]
triu = np.triu_indices(nettmp.shape[0], k=1)
nettmp = nettmp[triu[0], triu[1], :]
vol[net1, net2, :] = [distance_func(nettmp[:, t].flatten(
), nettmp[:, t + 1].flatten()) for t in range(0, tnet.shape[-1] - 1)]
elif calc == 'withincommunities':
withi = np.array([[ind[0][n], ind[1][n]] for n in range(
0, len(ind[0])) if communities[ind[0][n]] == communities[ind[1][n]]])
vol = [distance_func(tnet[withi[:, 0], withi[:, 1], t], tnet[withi[:, 0],
withi[:, 1], t + 1]) for t in range(0, tnet.shape[-1] - 1)]
elif calc == 'betweencommunities':
beti = np.array([[ind[0][n], ind[1][n]] for n in range(
0, len(ind[0])) if communities[ind[0][n]] != communities[ind[1][n]]])
vol = [distance_func(tnet[beti[:, 0], beti[:, 1], t], tnet[beti[:, 0],
beti[:, 1], t + 1]) for t in range(0, tnet.shape[-1] - 1)]
return vol | [
"def",
"volatility",
"(",
"tnet",
",",
"distance_func_name",
"=",
"'default'",
",",
"calc",
"=",
"'global'",
",",
"communities",
"=",
"None",
",",
"event_displacement",
"=",
"None",
")",
":",
"# Get input (C or G)",
"tnet",
",",
"netinfo",
"=",
"process_input",
... | r"""
Volatility of temporal networks.
Volatility is the average distance between consecutive time points of graphlets (difference is caclualted either globally or per edge).
Parameters
----------
tnet : array or dict
temporal network input (graphlet or contact). Nettype: 'bu','bd','wu','wd'
D : str
Distance function. Following options available: 'default', 'hamming', 'euclidean'. (Default implies hamming for binary networks, euclidean for weighted).
calc : str
Version of volaitility to caclulate. Possibilities include:
'global' - (default): the average distance of all nodes for each consecutive time point).
'edge' - average distance between consecutive time points for each edge). Takes considerably longer
'node' - (i.e. returns the average per node output when calculating volatility per 'edge').
'time' - returns volatility per time point
'communities' - returns volatility per communitieswork id (see communities). Also is returned per time-point and this may be changed in the future (with additional options)
'event_displacement' - calculates the volatility from a specified point. Returns time-series.
communities : array
Array of indicies for community (eiter (node) or (node,time) dimensions).
event_displacement : int
if calc = event_displacement specify the temporal index where all other time-points are calculated in relation too.
Notes
-----
Volatility calculates the difference between network snapshots.
.. math:: V_t = D(G_t,G_{t+1})
Where D is some distance function (e.g. Hamming distance for binary matrices).
V can be calculated for the entire network (global), but can also be calculated for individual edges, nodes or given a community vector.
Index of communities are returned "as is" with a shape of [max(communities)+1,max(communities)+1]. So if the indexes used are [1,2,3,5], V.shape==(6,6). The returning V[1,2] will correspond indexes 1 and 2. And missing index (e.g. here 0 and 4 will be NANs in rows and columns). If this behaviour is unwanted, call clean_communitiesdexes first. This will probably change.
Examples
--------
Import everything needed.
>>> import teneto
>>> import numpy
>>> np.random.seed(1)
>>> tnet = teneto.TemporalNetwork(nettype='bu')
Here we generate a binary network where edges have a 0.5 change of going "on", and once on a 0.2 change to go "off"
>>> tnet.generatenetwork('rand_binomial', size=(3,10), prob=(0.5,0.2))
Calculate the volatility
>>> tnet.calc_networkmeasure('volatility', distance_func_name='hamming')
0.5555555555555556
If we change the probabilities to instead be certain edges disapeared the time-point after the appeared:
>>> tnet.generatenetwork('rand_binomial', size=(3,10), prob=(0.5,1))
This will make a more volatile network
>>> tnet.calc_networkmeasure('volatility', distance_func_name='hamming')
0.1111111111111111
We can calculate the volatility per time instead
>>> vol_time = tnet.calc_networkmeasure('volatility', calc='time', distance_func_name='hamming')
>>> len(vol_time)
9
>>> vol_time[0]
0.3333333333333333
Or per node:
>>> vol_node = tnet.calc_networkmeasure('volatility', calc='node', distance_func_name='hamming')
>>> vol_node
array([0.07407407, 0.07407407, 0.07407407])
Here we see the volatility for each node was the same.
It is also possible to pass a community vector and the function will return volatility both within and between each community.
So the following has two communities:
>>> vol_com = tnet.calc_networkmeasure('volatility', calc='communities', communities=[0,1,1], distance_func_name='hamming')
>>> vol_com.shape
(2, 2, 9)
>>> vol_com[:,:,0]
array([[nan, 0.5],
[0.5, 0. ]])
And we see that, at time-point 0, there is some volatility between community 0 and 1 but no volatility within community 1. The reason for nan appearing is due to there only being 1 node in community 0.
Output
------
vol : array | [
"r",
"Volatility",
"of",
"temporal",
"networks",
"."
] | python | train |
saltstack/salt | salt/modules/lxd.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxd.py#L2204-L2260 | def profile_config_set(name, config_key, config_value,
remote_addr=None,
cert=None, key=None, verify_cert=True):
''' Set a profile config item.
name :
The name of the profile to set the config item to.
config_key :
The items key.
config_value :
Its items value.
remote_addr :
An URL to a remote Server, you also have to give cert and key if
you provide remote_addr and its a TCP Address!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Certificate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
CLI Example:
.. code-block:: bash
$ salt '*' lxd.profile_config_set autostart boot.autostart 0
'''
profile = profile_get(
name,
remote_addr,
cert,
key,
verify_cert,
_raw=True
)
return _set_property_dict_item(
profile, 'config', config_key, config_value
) | [
"def",
"profile_config_set",
"(",
"name",
",",
"config_key",
",",
"config_value",
",",
"remote_addr",
"=",
"None",
",",
"cert",
"=",
"None",
",",
"key",
"=",
"None",
",",
"verify_cert",
"=",
"True",
")",
":",
"profile",
"=",
"profile_get",
"(",
"name",
"... | Set a profile config item.
name :
The name of the profile to set the config item to.
config_key :
The items key.
config_value :
Its items value.
remote_addr :
An URL to a remote Server, you also have to give cert and key if
you provide remote_addr and its a TCP Address!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Certificate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
CLI Example:
.. code-block:: bash
$ salt '*' lxd.profile_config_set autostart boot.autostart 0 | [
"Set",
"a",
"profile",
"config",
"item",
"."
] | python | train |
sirfoga/pyhal | hal/maths/utils.py | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/maths/utils.py#L6-L17 | def get_percentage_relative_to(val, other):
"""Finds percentage between 2 numbers
:param val: number
:param other: number to compare to
:return: percentage of delta between first and second
"""
val = float(val)
other = float(other)
ratio = val / other - 1
return ratio * 100.0 | [
"def",
"get_percentage_relative_to",
"(",
"val",
",",
"other",
")",
":",
"val",
"=",
"float",
"(",
"val",
")",
"other",
"=",
"float",
"(",
"other",
")",
"ratio",
"=",
"val",
"/",
"other",
"-",
"1",
"return",
"ratio",
"*",
"100.0"
] | Finds percentage between 2 numbers
:param val: number
:param other: number to compare to
:return: percentage of delta between first and second | [
"Finds",
"percentage",
"between",
"2",
"numbers"
] | python | train |
edx/edx-submissions | submissions/api.py | https://github.com/edx/edx-submissions/blob/8d531ca25f7c2886dfcb1bb8febe0910e1433ca2/submissions/api.py#L827-L920 | def set_score(submission_uuid, points_earned, points_possible,
annotation_creator=None, annotation_type=None, annotation_reason=None):
"""Set a score for a particular submission.
Sets the score for a particular submission. This score is calculated
externally to the API.
Args:
submission_uuid (str): UUID for the submission (must exist).
points_earned (int): The earned points for this submission.
points_possible (int): The total points possible for this particular student item.
annotation_creator (str): An optional field for recording who gave this particular score
annotation_type (str): An optional field for recording what type of annotation should be created,
e.g. "staff_override".
annotation_reason (str): An optional field for recording why this score was set to its value.
Returns:
None
Raises:
SubmissionInternalError: Thrown if there was an internal error while
attempting to save the score.
SubmissionRequestError: Thrown if the given student item or submission
are not found.
Examples:
>>> set_score("a778b933-9fb3-11e3-9c0f-040ccee02800", 11, 12)
{
'student_item': 2,
'submission': 1,
'points_earned': 11,
'points_possible': 12,
'created_at': datetime.datetime(2014, 2, 7, 20, 6, 42, 331156, tzinfo=<UTC>)
}
"""
try:
submission_model = _get_submission_model(submission_uuid)
except Submission.DoesNotExist:
raise SubmissionNotFoundError(
u"No submission matching uuid {}".format(submission_uuid)
)
except DatabaseError:
error_msg = u"Could not retrieve submission {}.".format(
submission_uuid
)
logger.exception(error_msg)
raise SubmissionRequestError(msg=error_msg)
score = ScoreSerializer(
data={
"student_item": submission_model.student_item.pk,
"submission": submission_model.pk,
"points_earned": points_earned,
"points_possible": points_possible,
}
)
if not score.is_valid():
logger.exception(score.errors)
raise SubmissionInternalError(score.errors)
# When we save the score, a score summary will be created if
# it does not already exist.
# When the database's isolation level is set to repeatable-read,
# it's possible for a score summary to exist for this student item,
# even though we cannot retrieve it.
# In this case, we assume that someone else has already created
# a score summary and ignore the error.
# TODO: once we're using Django 1.8, use transactions to ensure that these
# two models are saved at the same time.
try:
score_model = score.save()
_log_score(score_model)
if annotation_creator is not None:
score_annotation = ScoreAnnotation(
score=score_model,
creator=annotation_creator,
annotation_type=annotation_type,
reason=annotation_reason
)
score_annotation.save()
# Send a signal out to any listeners who are waiting for scoring events.
score_set.send(
sender=None,
points_possible=points_possible,
points_earned=points_earned,
anonymous_user_id=submission_model.student_item.student_id,
course_id=submission_model.student_item.course_id,
item_id=submission_model.student_item.item_id,
created_at=score_model.created_at,
)
except IntegrityError:
pass | [
"def",
"set_score",
"(",
"submission_uuid",
",",
"points_earned",
",",
"points_possible",
",",
"annotation_creator",
"=",
"None",
",",
"annotation_type",
"=",
"None",
",",
"annotation_reason",
"=",
"None",
")",
":",
"try",
":",
"submission_model",
"=",
"_get_submi... | Set a score for a particular submission.
Sets the score for a particular submission. This score is calculated
externally to the API.
Args:
submission_uuid (str): UUID for the submission (must exist).
points_earned (int): The earned points for this submission.
points_possible (int): The total points possible for this particular student item.
annotation_creator (str): An optional field for recording who gave this particular score
annotation_type (str): An optional field for recording what type of annotation should be created,
e.g. "staff_override".
annotation_reason (str): An optional field for recording why this score was set to its value.
Returns:
None
Raises:
SubmissionInternalError: Thrown if there was an internal error while
attempting to save the score.
SubmissionRequestError: Thrown if the given student item or submission
are not found.
Examples:
>>> set_score("a778b933-9fb3-11e3-9c0f-040ccee02800", 11, 12)
{
'student_item': 2,
'submission': 1,
'points_earned': 11,
'points_possible': 12,
'created_at': datetime.datetime(2014, 2, 7, 20, 6, 42, 331156, tzinfo=<UTC>)
} | [
"Set",
"a",
"score",
"for",
"a",
"particular",
"submission",
"."
] | python | train |
alberanid/python-iplib | iplib.py | https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L536-L541 | def set(self, ip, notation=IP_UNKNOWN):
"""Set the IP address/netmask."""
self._ip_dec = int(_convert(ip, notation=IP_DEC, inotation=notation,
_check=True, _isnm=self._isnm))
self._ip = _convert(self._ip_dec, notation=IP_DOT, inotation=IP_DEC,
_check=False, _isnm=self._isnm) | [
"def",
"set",
"(",
"self",
",",
"ip",
",",
"notation",
"=",
"IP_UNKNOWN",
")",
":",
"self",
".",
"_ip_dec",
"=",
"int",
"(",
"_convert",
"(",
"ip",
",",
"notation",
"=",
"IP_DEC",
",",
"inotation",
"=",
"notation",
",",
"_check",
"=",
"True",
",",
... | Set the IP address/netmask. | [
"Set",
"the",
"IP",
"address",
"/",
"netmask",
"."
] | python | valid |
Robpol86/libnl | example_scan_access_points.py | https://github.com/Robpol86/libnl/blob/274e9fdaa39822d06ef70b799ed4a95937a4d923/example_scan_access_points.py#L121-L152 | def callback_dump(msg, results):
"""Here is where SSIDs and their data is decoded from the binary data sent by the kernel.
This function is called once per SSID. Everything in `msg` pertains to just one SSID.
Positional arguments:
msg -- nl_msg class instance containing the data sent by the kernel.
results -- dictionary to populate with parsed data.
"""
bss = dict() # To be filled by nla_parse_nested().
# First we must parse incoming data into manageable chunks and check for errors.
gnlh = genlmsghdr(nlmsg_data(nlmsg_hdr(msg)))
tb = dict((i, None) for i in range(nl80211.NL80211_ATTR_MAX + 1))
nla_parse(tb, nl80211.NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), None)
if not tb[nl80211.NL80211_ATTR_BSS]:
print('WARNING: BSS info missing for an access point.')
return libnl.handlers.NL_SKIP
if nla_parse_nested(bss, nl80211.NL80211_BSS_MAX, tb[nl80211.NL80211_ATTR_BSS], bss_policy):
print('WARNING: Failed to parse nested attributes for an access point!')
return libnl.handlers.NL_SKIP
if not bss[nl80211.NL80211_BSS_BSSID]:
print('WARNING: No BSSID detected for an access point!')
return libnl.handlers.NL_SKIP
if not bss[nl80211.NL80211_BSS_INFORMATION_ELEMENTS]:
print('WARNING: No additional information available for an access point!')
return libnl.handlers.NL_SKIP
# Further parse and then store. Overwrite existing data for BSSID if scan is run multiple times.
bss_parsed = parse_bss(bss)
results[bss_parsed['bssid']] = bss_parsed
return libnl.handlers.NL_SKIP | [
"def",
"callback_dump",
"(",
"msg",
",",
"results",
")",
":",
"bss",
"=",
"dict",
"(",
")",
"# To be filled by nla_parse_nested().",
"# First we must parse incoming data into manageable chunks and check for errors.",
"gnlh",
"=",
"genlmsghdr",
"(",
"nlmsg_data",
"(",
"nlmsg... | Here is where SSIDs and their data is decoded from the binary data sent by the kernel.
This function is called once per SSID. Everything in `msg` pertains to just one SSID.
Positional arguments:
msg -- nl_msg class instance containing the data sent by the kernel.
results -- dictionary to populate with parsed data. | [
"Here",
"is",
"where",
"SSIDs",
"and",
"their",
"data",
"is",
"decoded",
"from",
"the",
"binary",
"data",
"sent",
"by",
"the",
"kernel",
"."
] | python | train |
mouse-reeve/nomina-flora | nominaflora/NominaFlora.py | https://github.com/mouse-reeve/nomina-flora/blob/d99723b95d169dc38021a38c1f9d1f9f2b04c46b/nominaflora/NominaFlora.py#L26-L32 | def get_common(self, filename):
''' Process lists of common name words '''
word_list = []
words = open(filename)
for word in words.readlines():
word_list.append(word.strip())
return word_list | [
"def",
"get_common",
"(",
"self",
",",
"filename",
")",
":",
"word_list",
"=",
"[",
"]",
"words",
"=",
"open",
"(",
"filename",
")",
"for",
"word",
"in",
"words",
".",
"readlines",
"(",
")",
":",
"word_list",
".",
"append",
"(",
"word",
".",
"strip",... | Process lists of common name words | [
"Process",
"lists",
"of",
"common",
"name",
"words"
] | python | train |
openstack/pyghmi | pyghmi/ipmi/console.py | https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/console.py#L459-L531 | def _got_sol_payload(self, payload):
"""SOL payload callback
"""
# TODO(jbjohnso) test cases to throw some likely scenarios at functions
# for example, retry with new data, retry with no new data
# retry with unexpected sequence number
if type(payload) == dict: # we received an error condition
self.activated = False
self._print_error(payload)
return
newseq = payload[0] & 0b1111
ackseq = payload[1] & 0b1111
ackcount = payload[2]
nacked = payload[3] & 0b1000000
breakdetected = payload[3] & 0b10000
# for now, ignore overrun. I assume partial NACK for this reason or
# for no reason would be treated the same, new payload with partial
# data.
remdata = ""
remdatalen = 0
flag = 0
if not self.poweredon:
flag |= 0b1100000
if not self.activated:
flag |= 0b1010000
if newseq != 0: # this packet at least has some data to send to us..
if len(payload) > 4:
remdatalen = len(payload[4:]) # store remote len before dupe
# retry logic, we must ack *this* many even if it is
# a retry packet with new partial data
remdata = bytes(payload[4:])
if newseq == self.remseq: # it is a retry, but could have new data
if remdatalen > self.lastsize:
remdata = bytes(remdata[4 + self.lastsize:])
else: # no new data...
remdata = ""
else: # TODO(jbjohnso) what if remote sequence number is wrong??
self.remseq = newseq
self.lastsize = remdatalen
ackpayload = bytearray((0, self.remseq, remdatalen, flag))
# Why not put pending data into the ack? because it's rare
# and might be hard to decide what to do in the context of
# retry situation
try:
self.send_payload(ackpayload, retry=False)
except exc.IpmiException:
# if the session is broken, then close the SOL session
self.close()
if remdata: # Do not subject callers to empty data
self._print_data(remdata)
if self.myseq != 0 and ackseq == self.myseq: # the bmc has something
# to say about last xmit
self.awaitingack = False
if nacked and not breakdetected: # the BMC was in some way unhappy
newtext = self.lastpayload[4 + ackcount:]
with self.outputlock:
if (self.pendingoutput and
not isinstance(self.pendingoutput[0], dict)):
self.pendingoutput[0] = newtext + self.pendingoutput[0]
else:
self.pendingoutput = [newtext] + self.pendingoutput
# self._sendpendingoutput() checks len(self._sendpendingoutput)
self._sendpendingoutput()
elif ackseq != 0 and self.awaitingack:
# if an ack packet came in, but did not match what we
# expected, retry our payload now.
# the situation that was triggered was a senseless retry
# when data came in while we xmitted. In theory, a BMC
# should handle a retry correctly, but some do not, so
# try to mitigate by avoiding overeager retries
# occasional retry of a packet
# sooner than timeout suggests is evidently a big deal
self.send_payload(payload=self.lastpayload) | [
"def",
"_got_sol_payload",
"(",
"self",
",",
"payload",
")",
":",
"# TODO(jbjohnso) test cases to throw some likely scenarios at functions",
"# for example, retry with new data, retry with no new data",
"# retry with unexpected sequence number",
"if",
"type",
"(",
"payload",
")",
"==... | SOL payload callback | [
"SOL",
"payload",
"callback"
] | python | train |
astropy/photutils | photutils/segmentation/properties.py | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L602-L617 | def sky_bbox_ll(self):
"""
The sky coordinates of the lower-left vertex of the minimal
bounding box of the source segment, returned as a
`~astropy.coordinates.SkyCoord` object.
The bounding box encloses all of the source segment pixels in
their entirety, thus the vertices are at the pixel *corners*.
"""
if self._wcs is not None:
return pixel_to_skycoord(self.xmin.value - 0.5,
self.ymin.value - 0.5,
self._wcs, origin=0)
else:
return None | [
"def",
"sky_bbox_ll",
"(",
"self",
")",
":",
"if",
"self",
".",
"_wcs",
"is",
"not",
"None",
":",
"return",
"pixel_to_skycoord",
"(",
"self",
".",
"xmin",
".",
"value",
"-",
"0.5",
",",
"self",
".",
"ymin",
".",
"value",
"-",
"0.5",
",",
"self",
".... | The sky coordinates of the lower-left vertex of the minimal
bounding box of the source segment, returned as a
`~astropy.coordinates.SkyCoord` object.
The bounding box encloses all of the source segment pixels in
their entirety, thus the vertices are at the pixel *corners*. | [
"The",
"sky",
"coordinates",
"of",
"the",
"lower",
"-",
"left",
"vertex",
"of",
"the",
"minimal",
"bounding",
"box",
"of",
"the",
"source",
"segment",
"returned",
"as",
"a",
"~astropy",
".",
"coordinates",
".",
"SkyCoord",
"object",
"."
] | python | train |
PmagPy/PmagPy | programs/angle.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/angle.py#L11-L79 | def main():
"""
NAME
angle.py
DESCRIPTION
calculates angle between two input directions D1,D2
INPUT (COMMAND LINE ENTRY)
D1_dec D1_inc D1_dec D2_inc
OUTPUT
angle
SYNTAX
angle.py [-h][-i] [command line options] [< filename]
OPTIONS
-h prints help and quits
-i for interactive data entry
-f FILE input filename
-F FILE output filename (required if -F set)
Standard I/O
"""
out = ""
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-F' in sys.argv:
ind = sys.argv.index('-F')
o = sys.argv[ind + 1]
out = open(o, 'w')
if '-i' in sys.argv:
cont = 1
while cont == 1:
dir1, dir2 = [], []
try:
ans = input('Declination 1: [ctrl-D to quit] ')
dir1.append(float(ans))
ans = input('Inclination 1: ')
dir1.append(float(ans))
ans = input('Declination 2: ')
dir2.append(float(ans))
ans = input('Inclination 2: ')
dir2.append(float(ans))
except:
print("\nGood bye\n")
sys.exit()
# send dirs to angle and spit out result
ang = pmag.angle(dir1, dir2)
print('%7.1f ' % (ang))
elif '-f' in sys.argv:
ind = sys.argv.index('-f')
file = sys.argv[ind + 1]
file_input = numpy.loadtxt(file)
else:
# read from standard input
file_input = numpy.loadtxt(sys.stdin.readlines(), dtype=numpy.float)
if len(file_input.shape) > 1: # list of directions
dir1, dir2 = file_input[:, 0:2], file_input[:, 2:]
else:
dir1, dir2 = file_input[0:2], file_input[2:]
angs = pmag.angle(dir1, dir2)
for ang in angs: # read in the data (as string variable), line by line
print('%7.1f' % (ang))
if out != "":
out.write('%7.1f \n' % (ang))
if out:
out.close() | [
"def",
"main",
"(",
")",
":",
"out",
"=",
"\"\"",
"if",
"'-h'",
"in",
"sys",
".",
"argv",
":",
"print",
"(",
"main",
".",
"__doc__",
")",
"sys",
".",
"exit",
"(",
")",
"if",
"'-F'",
"in",
"sys",
".",
"argv",
":",
"ind",
"=",
"sys",
".",
"argv... | NAME
angle.py
DESCRIPTION
calculates angle between two input directions D1,D2
INPUT (COMMAND LINE ENTRY)
D1_dec D1_inc D1_dec D2_inc
OUTPUT
angle
SYNTAX
angle.py [-h][-i] [command line options] [< filename]
OPTIONS
-h prints help and quits
-i for interactive data entry
-f FILE input filename
-F FILE output filename (required if -F set)
Standard I/O | [
"NAME",
"angle",
".",
"py"
] | python | train |
tyarkoni/pliers | pliers/stimuli/video.py | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/stimuli/video.py#L159-L170 | def get_frame(self, index=None, onset=None):
''' Overrides the default behavior by giving access to the onset
argument.
Args:
index (int): Positional index of the desired frame.
onset (float): Onset (in seconds) of the desired frame.
'''
if onset:
index = int(onset * self.fps)
return super(VideoStim, self).get_frame(index) | [
"def",
"get_frame",
"(",
"self",
",",
"index",
"=",
"None",
",",
"onset",
"=",
"None",
")",
":",
"if",
"onset",
":",
"index",
"=",
"int",
"(",
"onset",
"*",
"self",
".",
"fps",
")",
"return",
"super",
"(",
"VideoStim",
",",
"self",
")",
".",
"get... | Overrides the default behavior by giving access to the onset
argument.
Args:
index (int): Positional index of the desired frame.
onset (float): Onset (in seconds) of the desired frame. | [
"Overrides",
"the",
"default",
"behavior",
"by",
"giving",
"access",
"to",
"the",
"onset",
"argument",
"."
] | python | train |
zmiller91/aws-lambda-api-builder | api_builder/zlab.py | https://github.com/zmiller91/aws-lambda-api-builder/blob/86026b5c134faa33eaa1e1268e0206cb074e3285/api_builder/zlab.py#L22-L41 | def get_application_parser(commands):
"""
Builds an argument parser for the application's CLI.
:param commands:
:return: ArgumentParser
"""
parser = argparse.ArgumentParser(
description=configuration.APPLICATION_DESCRIPTION,
usage =configuration.EXECUTABLE_NAME + ' [sub-command] [options]',
add_help=False)
parser.add_argument(
'sub_command',
choices=[name for name in commands],
nargs="?")
parser.add_argument("-h", "--help", action="store_true")
return parser | [
"def",
"get_application_parser",
"(",
"commands",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"configuration",
".",
"APPLICATION_DESCRIPTION",
",",
"usage",
"=",
"configuration",
".",
"EXECUTABLE_NAME",
"+",
"' [sub-command] [o... | Builds an argument parser for the application's CLI.
:param commands:
:return: ArgumentParser | [
"Builds",
"an",
"argument",
"parser",
"for",
"the",
"application",
"s",
"CLI",
"."
] | python | train |
woolfson-group/isambard | isambard/optimisation/evo_optimizers.py | https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/optimisation/evo_optimizers.py#L259-L287 | def update_particle(self, part, chi=0.729843788, c=2.05):
"""Constriction factor update particle method.
Notes
-----
Looks for a list of neighbours attached to a particle and
uses the particle's best position and that of the best
neighbour.
"""
neighbour_pool = [self.population[i] for i in part.neighbours]
best_neighbour = max(neighbour_pool, key=lambda x: x.best.fitness)
ce1 = (c * random.uniform(0, 1) for _ in range(len(part)))
ce2 = (c * random.uniform(0, 1) for _ in range(len(part)))
ce1_p = map(operator.mul, ce1, map(operator.sub, part.best, part))
ce2_g = map(operator.mul, ce2, map(
operator.sub, best_neighbour.best, part))
chi_list = [chi] * len(part)
chi_list2 = [1 - chi] * len(part)
a = map(operator.sub,
map(operator.mul, chi_list, map(operator.add, ce1_p, ce2_g)),
map(operator.mul, chi_list2, part.speed))
part.speed = list(map(operator.add, part.speed, a))
for i, speed in enumerate(part.speed):
if speed < part.smin:
part.speed[i] = part.smin
elif speed > part.smax:
part.speed[i] = part.smax
part[:] = list(map(operator.add, part, part.speed))
return | [
"def",
"update_particle",
"(",
"self",
",",
"part",
",",
"chi",
"=",
"0.729843788",
",",
"c",
"=",
"2.05",
")",
":",
"neighbour_pool",
"=",
"[",
"self",
".",
"population",
"[",
"i",
"]",
"for",
"i",
"in",
"part",
".",
"neighbours",
"]",
"best_neighbour... | Constriction factor update particle method.
Notes
-----
Looks for a list of neighbours attached to a particle and
uses the particle's best position and that of the best
neighbour. | [
"Constriction",
"factor",
"update",
"particle",
"method",
"."
] | python | train |
googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row_filters.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row_filters.py#L399-L423 | def to_pb(self):
"""Converts the row filter to a protobuf.
First converts to a :class:`.data_v2_pb2.ColumnRange` and then uses it
in the ``column_range_filter`` field.
:rtype: :class:`.data_v2_pb2.RowFilter`
:returns: The converted current object.
"""
column_range_kwargs = {"family_name": self.column_family_id}
if self.start_column is not None:
if self.inclusive_start:
key = "start_qualifier_closed"
else:
key = "start_qualifier_open"
column_range_kwargs[key] = _to_bytes(self.start_column)
if self.end_column is not None:
if self.inclusive_end:
key = "end_qualifier_closed"
else:
key = "end_qualifier_open"
column_range_kwargs[key] = _to_bytes(self.end_column)
column_range = data_v2_pb2.ColumnRange(**column_range_kwargs)
return data_v2_pb2.RowFilter(column_range_filter=column_range) | [
"def",
"to_pb",
"(",
"self",
")",
":",
"column_range_kwargs",
"=",
"{",
"\"family_name\"",
":",
"self",
".",
"column_family_id",
"}",
"if",
"self",
".",
"start_column",
"is",
"not",
"None",
":",
"if",
"self",
".",
"inclusive_start",
":",
"key",
"=",
"\"sta... | Converts the row filter to a protobuf.
First converts to a :class:`.data_v2_pb2.ColumnRange` and then uses it
in the ``column_range_filter`` field.
:rtype: :class:`.data_v2_pb2.RowFilter`
:returns: The converted current object. | [
"Converts",
"the",
"row",
"filter",
"to",
"a",
"protobuf",
"."
] | python | train |
trailofbits/manticore | manticore/ethereum/detectors.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/detectors.py#L70-L84 | def add_finding_here(self, state, finding, constraint=True):
"""
Logs a finding in current contract and assembler line.
:param state: current state
:param finding: textual description of the finding
:param constraint: finding is considered reproducible only when constraint is True
"""
address = state.platform.current_vm.address
pc = state.platform.current_vm.pc
if isinstance(pc, Constant):
pc = pc.value
if not isinstance(pc, int):
raise ValueError("PC must be a number")
at_init = state.platform.current_transaction.sort == 'CREATE'
self.add_finding(state, address, pc, finding, at_init, constraint) | [
"def",
"add_finding_here",
"(",
"self",
",",
"state",
",",
"finding",
",",
"constraint",
"=",
"True",
")",
":",
"address",
"=",
"state",
".",
"platform",
".",
"current_vm",
".",
"address",
"pc",
"=",
"state",
".",
"platform",
".",
"current_vm",
".",
"pc"... | Logs a finding in current contract and assembler line.
:param state: current state
:param finding: textual description of the finding
:param constraint: finding is considered reproducible only when constraint is True | [
"Logs",
"a",
"finding",
"in",
"current",
"contract",
"and",
"assembler",
"line",
".",
":",
"param",
"state",
":",
"current",
"state",
":",
"param",
"finding",
":",
"textual",
"description",
"of",
"the",
"finding",
":",
"param",
"constraint",
":",
"finding",
... | python | valid |
TissueMAPS/TmClient | src/python/tmclient/api.py | https://github.com/TissueMAPS/TmClient/blob/6fb40622af19142cb5169a64b8c2965993a25ab1/src/python/tmclient/api.py#L403-L420 | def delete_experiment(self):
'''Deletes the experiment.
See also
--------
:func:`tmserver.api.experiment.delete_experiment`
:class:`tmlib.models.experiment.ExperimentReference`
:class:`tmlib.models.experiment.Experiment`
'''
logger.info('delete experiment "%s"', self.experiment_name)
url = self._build_api_url(
'/experiments/{experiment_id}'.format(
experiment_id=self._experiment_id
)
)
res = self._session.delete(url)
res.raise_for_status()
del self.__experiment_id | [
"def",
"delete_experiment",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'delete experiment \"%s\"'",
",",
"self",
".",
"experiment_name",
")",
"url",
"=",
"self",
".",
"_build_api_url",
"(",
"'/experiments/{experiment_id}'",
".",
"format",
"(",
"experiment... | Deletes the experiment.
See also
--------
:func:`tmserver.api.experiment.delete_experiment`
:class:`tmlib.models.experiment.ExperimentReference`
:class:`tmlib.models.experiment.Experiment` | [
"Deletes",
"the",
"experiment",
"."
] | python | train |
vertexproject/synapse | synapse/lib/syntax.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/syntax.py#L743-L756 | def propjoin(self, prop):
'''
:foo:bar -+> baz:faz
'''
pval = s_ast.RelPropValue(kids=(prop,))
self.ignore(whitespace)
self.nextmust('-+>')
self.ignore(whitespace)
dest = self.absprop()
return s_ast.PropPivot(kids=(pval, dest), isjoin=True) | [
"def",
"propjoin",
"(",
"self",
",",
"prop",
")",
":",
"pval",
"=",
"s_ast",
".",
"RelPropValue",
"(",
"kids",
"=",
"(",
"prop",
",",
")",
")",
"self",
".",
"ignore",
"(",
"whitespace",
")",
"self",
".",
"nextmust",
"(",
"'-+>'",
")",
"self",
".",
... | :foo:bar -+> baz:faz | [
":",
"foo",
":",
"bar",
"-",
"+",
">",
"baz",
":",
"faz"
] | python | train |
Microsoft/ApplicationInsights-Python | applicationinsights/channel/contracts/ExceptionDetails.py | https://github.com/Microsoft/ApplicationInsights-Python/blob/8452ab7126f9bb6964637d4aa1258c2af17563d6/applicationinsights/channel/contracts/ExceptionDetails.py#L122-L131 | def has_full_stack(self, value):
"""The has_full_stack property.
Args:
value (bool). the property value.
"""
if value == self._defaults['hasFullStack'] and 'hasFullStack' in self._values:
del self._values['hasFullStack']
else:
self._values['hasFullStack'] = value | [
"def",
"has_full_stack",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"self",
".",
"_defaults",
"[",
"'hasFullStack'",
"]",
"and",
"'hasFullStack'",
"in",
"self",
".",
"_values",
":",
"del",
"self",
".",
"_values",
"[",
"'hasFullStack'",
"]",
... | The has_full_stack property.
Args:
value (bool). the property value. | [
"The",
"has_full_stack",
"property",
".",
"Args",
":",
"value",
"(",
"bool",
")",
".",
"the",
"property",
"value",
"."
] | python | train |
uw-it-aca/uw-restclients-catalyst | uw_catalyst/gradebook.py | https://github.com/uw-it-aca/uw-restclients-catalyst/blob/17216e1e38d6da05eaed235e9329f62774626d80/uw_catalyst/gradebook.py#L34-L51 | def get_participants_for_section(section, person=None):
"""
Returns a list of gradebook participants for the passed section and person.
"""
section_label = encode_section_label(section.section_label())
url = "/rest/gradebook/v1/section/{}/participants".format(section_label)
headers = {}
if person is not None:
headers["X-UW-Act-as"] = person.uwnetid
data = get_resource(url, headers)
participants = []
for pt in data["participants"]:
participants.append(_participant_from_json(pt))
return participants | [
"def",
"get_participants_for_section",
"(",
"section",
",",
"person",
"=",
"None",
")",
":",
"section_label",
"=",
"encode_section_label",
"(",
"section",
".",
"section_label",
"(",
")",
")",
"url",
"=",
"\"/rest/gradebook/v1/section/{}/participants\"",
".",
"format",... | Returns a list of gradebook participants for the passed section and person. | [
"Returns",
"a",
"list",
"of",
"gradebook",
"participants",
"for",
"the",
"passed",
"section",
"and",
"person",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/osid/objects.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/osid/objects.py#L1587-L1596 | def get_license_metadata(self):
"""Gets the metadata for the license.
return: (osid.Metadata) - metadata for the license
*compliance: mandatory -- This method must be implemented.*
"""
metadata = dict(self._mdata['license'])
metadata.update({'existing_string_values': self._my_map['license']})
return Metadata(**metadata) | [
"def",
"get_license_metadata",
"(",
"self",
")",
":",
"metadata",
"=",
"dict",
"(",
"self",
".",
"_mdata",
"[",
"'license'",
"]",
")",
"metadata",
".",
"update",
"(",
"{",
"'existing_string_values'",
":",
"self",
".",
"_my_map",
"[",
"'license'",
"]",
"}",... | Gets the metadata for the license.
return: (osid.Metadata) - metadata for the license
*compliance: mandatory -- This method must be implemented.* | [
"Gets",
"the",
"metadata",
"for",
"the",
"license",
"."
] | python | train |
XuShaohua/bcloud | bcloud/IconWindow.py | https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/IconWindow.py#L141-L157 | def on_drag_data_get(self, widget, context, data, info, time):
'''拖放开始'''
tree_paths = self.iconview.get_selected_items()
if not tree_paths:
return
filelist = []
for tree_path in tree_paths:
filelist.append({
'path': self.liststore[tree_path][PATH_COL],
'newname': self.liststore[tree_path][NAME_COL],
})
filelist_str = json.dumps(filelist)
if info == TargetInfo.PLAIN_TEXT:
data.set_text(filelist_str, -1)
# 拖拽时无法获取目标路径, 所以不能实现拖拽下载功能
elif info == TargetInfo.URI_LIST:
data.set_uris([]) | [
"def",
"on_drag_data_get",
"(",
"self",
",",
"widget",
",",
"context",
",",
"data",
",",
"info",
",",
"time",
")",
":",
"tree_paths",
"=",
"self",
".",
"iconview",
".",
"get_selected_items",
"(",
")",
"if",
"not",
"tree_paths",
":",
"return",
"filelist",
... | 拖放开始 | [
"拖放开始"
] | python | train |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/common/wrappers/command_wrapper.py | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/common/wrappers/command_wrapper.py#L54-L135 | def execute_command_with_connection(self, context, command, *args):
"""
Note: session & vcenter_data_model & reservation id objects will be injected dynamically to the command
:param command:
:param context: instance of ResourceCommandContext or AutoLoadCommandContext
:type context: cloudshell.shell.core.context.ResourceCommandContext
:param args:
"""
logger = self.context_based_logger_factory.create_logger_for_context(
logger_name='vCenterShell',
context=context)
if not command:
logger.error(COMMAND_CANNOT_BE_NONE)
raise Exception(COMMAND_CANNOT_BE_NONE)
try:
command_name = command.__name__
logger.info(LOG_FORMAT.format(START, command_name))
command_args = []
si = None
session = None
connection_details = None
vcenter_data_model = None
# get connection details
if context:
with CloudShellSessionContext(context) as cloudshell_session:
session = cloudshell_session
vcenter_data_model = self.resource_model_parser.convert_to_vcenter_model(context.resource)
connection_details = ResourceConnectionDetailsRetriever.get_connection_details(session=session,
vcenter_resource_model=vcenter_data_model,
resource_context=context.resource)
if connection_details:
logger.info(INFO_CONNECTING_TO_VCENTER.format(connection_details.host))
logger.debug(
DEBUG_CONNECTION_INFO.format(connection_details.host,
connection_details.username,
connection_details.port))
si = self.get_py_service_connection(connection_details, logger)
if si:
logger.info(CONNECTED_TO_CENTER.format(connection_details.host))
command_args.append(si)
self._try_inject_arg(command=command,
command_args=command_args,
arg_object=session,
arg_name='session')
self._try_inject_arg(command=command,
command_args=command_args,
arg_object=vcenter_data_model,
arg_name='vcenter_data_model')
self._try_inject_arg(command=command,
command_args=command_args,
arg_object=self._get_reservation_id(context),
arg_name='reservation_id')
self._try_inject_arg(command=command,
command_args=command_args,
arg_object=logger,
arg_name='logger')
command_args.extend(args)
logger.info(EXECUTING_COMMAND.format(command_name))
logger.debug(DEBUG_COMMAND_PARAMS.format(COMMA.join([str(x) for x in command_args])))
results = command(*tuple(command_args))
logger.info(FINISHED_EXECUTING_COMMAND.format(command_name))
logger.debug(DEBUG_COMMAND_RESULT.format(str(results)))
return results
except Exception as ex:
logger.exception(COMMAND_ERROR.format(command_name))
logger.exception(str(type(ex)) + ': ' + str(ex))
raise
finally:
logger.info(LOG_FORMAT.format(END, command_name)) | [
"def",
"execute_command_with_connection",
"(",
"self",
",",
"context",
",",
"command",
",",
"*",
"args",
")",
":",
"logger",
"=",
"self",
".",
"context_based_logger_factory",
".",
"create_logger_for_context",
"(",
"logger_name",
"=",
"'vCenterShell'",
",",
"context"... | Note: session & vcenter_data_model & reservation id objects will be injected dynamically to the command
:param command:
:param context: instance of ResourceCommandContext or AutoLoadCommandContext
:type context: cloudshell.shell.core.context.ResourceCommandContext
:param args: | [
"Note",
":",
"session",
"&",
"vcenter_data_model",
"&",
"reservation",
"id",
"objects",
"will",
"be",
"injected",
"dynamically",
"to",
"the",
"command",
":",
"param",
"command",
":",
":",
"param",
"context",
":",
"instance",
"of",
"ResourceCommandContext",
"or",... | python | train |
mlavin/argyle | argyle/postgres.py | https://github.com/mlavin/argyle/blob/92cc6e1dd9b8e7cb41c5098a79d05e14b8243d72/argyle/postgres.py#L74-L85 | def create_db(name, owner=None, encoding=u'UTF-8', template='template1',
**kwargs):
"""Create a Postgres database."""
flags = u''
if encoding:
flags = u'-E %s' % encoding
if owner:
flags = u'%s -O %s' % (flags, owner)
if template and template != 'template1':
flags = u'%s --template=%s' % (flags, template)
sudo('createdb %s %s' % (flags, name), user='postgres', **kwargs) | [
"def",
"create_db",
"(",
"name",
",",
"owner",
"=",
"None",
",",
"encoding",
"=",
"u'UTF-8'",
",",
"template",
"=",
"'template1'",
",",
"*",
"*",
"kwargs",
")",
":",
"flags",
"=",
"u''",
"if",
"encoding",
":",
"flags",
"=",
"u'-E %s'",
"%",
"encoding",... | Create a Postgres database. | [
"Create",
"a",
"Postgres",
"database",
"."
] | python | train |
Ex-Mente/auxi.0 | auxi/modelling/financial/des.py | https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/financial/des.py#L123-L142 | def get_child_account(self, account_name):
"""
Retrieves a child account.
This could be a descendant nested at any level.
:param account_name: The name of the account to retrieve.
:returns: The child account, if found, else None.
"""
if r'/' in account_name:
accs_in_path = account_name.split(r'/', 1)
curr_acc = self[accs_in_path[0]]
if curr_acc is None:
return None
return curr_acc.get_child_account(accs_in_path[1])
pass
else:
return self[account_name] | [
"def",
"get_child_account",
"(",
"self",
",",
"account_name",
")",
":",
"if",
"r'/'",
"in",
"account_name",
":",
"accs_in_path",
"=",
"account_name",
".",
"split",
"(",
"r'/'",
",",
"1",
")",
"curr_acc",
"=",
"self",
"[",
"accs_in_path",
"[",
"0",
"]",
"... | Retrieves a child account.
This could be a descendant nested at any level.
:param account_name: The name of the account to retrieve.
:returns: The child account, if found, else None. | [
"Retrieves",
"a",
"child",
"account",
".",
"This",
"could",
"be",
"a",
"descendant",
"nested",
"at",
"any",
"level",
"."
] | python | valid |
wummel/linkchecker | linkcheck/winutil.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/winutil.py#L19-L33 | def get_shell_folder (name):
"""Get Windows Shell Folder locations from the registry."""
try:
import _winreg as winreg
except ImportError:
import winreg
lm = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)
try:
key = winreg.OpenKey(lm, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
try:
return winreg.QueryValueEx(key, name)[0]
finally:
key.Close()
finally:
lm.Close() | [
"def",
"get_shell_folder",
"(",
"name",
")",
":",
"try",
":",
"import",
"_winreg",
"as",
"winreg",
"except",
"ImportError",
":",
"import",
"winreg",
"lm",
"=",
"winreg",
".",
"ConnectRegistry",
"(",
"None",
",",
"winreg",
".",
"HKEY_CURRENT_USER",
")",
"try"... | Get Windows Shell Folder locations from the registry. | [
"Get",
"Windows",
"Shell",
"Folder",
"locations",
"from",
"the",
"registry",
"."
] | python | train |
HydraChain/hydrachain | hydrachain/native_contracts.py | https://github.com/HydraChain/hydrachain/blob/6c0919b0575dc8aa481f3a8c703e1a7f0575ecc3/hydrachain/native_contracts.py#L79-L84 | def address_to_native_contract_class(self, address):
"returns class._on_msg_unsafe, use x.im_self to get class"
assert isinstance(address, bytes) and len(address) == 20
assert self.is_instance_address(address)
nca = self.native_contract_address_prefix + address[-4:]
return self.native_contracts[nca] | [
"def",
"address_to_native_contract_class",
"(",
"self",
",",
"address",
")",
":",
"assert",
"isinstance",
"(",
"address",
",",
"bytes",
")",
"and",
"len",
"(",
"address",
")",
"==",
"20",
"assert",
"self",
".",
"is_instance_address",
"(",
"address",
")",
"nc... | returns class._on_msg_unsafe, use x.im_self to get class | [
"returns",
"class",
".",
"_on_msg_unsafe",
"use",
"x",
".",
"im_self",
"to",
"get",
"class"
] | python | test |
henrysher/kotocore | kotocore/resources.py | https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/resources.py#L132-L148 | def result_key_for(self, op_name):
"""
Checks for the presence of a ``result_key``, which defines what data
should make up an instance.
Returns ``None`` if there is no ``result_key``.
:param op_name: The operation name to look for the ``result_key`` in.
:type op_name: string
:returns: The expected key to look for data within
:rtype: string or None
"""
ops = self.resource_data.get('operations', {})
op = ops.get(op_name, {})
key = op.get('result_key', None)
return key | [
"def",
"result_key_for",
"(",
"self",
",",
"op_name",
")",
":",
"ops",
"=",
"self",
".",
"resource_data",
".",
"get",
"(",
"'operations'",
",",
"{",
"}",
")",
"op",
"=",
"ops",
".",
"get",
"(",
"op_name",
",",
"{",
"}",
")",
"key",
"=",
"op",
"."... | Checks for the presence of a ``result_key``, which defines what data
should make up an instance.
Returns ``None`` if there is no ``result_key``.
:param op_name: The operation name to look for the ``result_key`` in.
:type op_name: string
:returns: The expected key to look for data within
:rtype: string or None | [
"Checks",
"for",
"the",
"presence",
"of",
"a",
"result_key",
"which",
"defines",
"what",
"data",
"should",
"make",
"up",
"an",
"instance",
"."
] | python | train |
aparrish/pronouncingpy | pronouncing/__init__.py | https://github.com/aparrish/pronouncingpy/blob/09467fa9407d7d87cb0998ee3cb09db4dcc9571a/pronouncing/__init__.py#L135-L155 | def rhyming_part(phones):
"""Get the "rhyming part" of a string with CMUdict phones.
"Rhyming part" here means everything from the vowel in the stressed
syllable nearest the end of the word up to the end of the word.
.. doctest::
>>> import pronouncing
>>> phones = pronouncing.phones_for_word("purple")
>>> pronouncing.rhyming_part(phones[0])
'ER1 P AH0 L'
:param phones: a string containing space-separated CMUdict phones
:returns: a string with just the "rhyming part" of those phones
"""
phones_list = phones.split()
for i in range(len(phones_list) - 1, 0, -1):
if phones_list[i][-1] in '12':
return ' '.join(phones_list[i:])
return phones | [
"def",
"rhyming_part",
"(",
"phones",
")",
":",
"phones_list",
"=",
"phones",
".",
"split",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"phones_list",
")",
"-",
"1",
",",
"0",
",",
"-",
"1",
")",
":",
"if",
"phones_list",
"[",
"i",
"]",... | Get the "rhyming part" of a string with CMUdict phones.
"Rhyming part" here means everything from the vowel in the stressed
syllable nearest the end of the word up to the end of the word.
.. doctest::
>>> import pronouncing
>>> phones = pronouncing.phones_for_word("purple")
>>> pronouncing.rhyming_part(phones[0])
'ER1 P AH0 L'
:param phones: a string containing space-separated CMUdict phones
:returns: a string with just the "rhyming part" of those phones | [
"Get",
"the",
"rhyming",
"part",
"of",
"a",
"string",
"with",
"CMUdict",
"phones",
"."
] | python | train |
hhromic/python-oslom-runner | oslom/runner.py | https://github.com/hhromic/python-oslom-runner/blob/f5991bd5014c65d0a9852641d51cbc344407d6a2/oslom/runner.py#L210-L242 | def run_in_memory(args, edges):
"""Run OSLOM with an in-memory list of edges, return in-memory results."""
# Create an OSLOM runner with a temporary working directory
oslom_runner = OslomRunner(tempfile.mkdtemp())
# Write temporary edges file with re-mapped Ids
logging.info("writing temporary edges file with re-mapped Ids ...")
oslom_runner.store_edges(edges)
# Run OSLOM
logging.info("running OSLOM ...")
log_file = os.path.join(oslom_runner.working_dir, OSLOM_LOG_FILE)
result = oslom_runner.run(args.oslom_exec, args.oslom_args, log_file)
with open(log_file, "r") as reader:
oslom_log = reader.read()
if result["retval"] != 0:
logging.error("error running OSLOM, check the log")
return (None, oslom_log)
logging.info("OSLOM executed in %.3f secs", result["time"])
# Read back clusters found by OSLOM
logging.info("reading OSLOM clusters output file ...")
clusters = oslom_runner.read_clusters(args.min_cluster_size)
logging.info(
"found %d cluster(s) and %d with size >= %d",
clusters["num_found"], len(clusters["clusters"]), args.min_cluster_size)
# Clean-up temporary working directory
oslom_runner.cleanup()
# Finished
logging.info("finished")
return (clusters, oslom_log) | [
"def",
"run_in_memory",
"(",
"args",
",",
"edges",
")",
":",
"# Create an OSLOM runner with a temporary working directory",
"oslom_runner",
"=",
"OslomRunner",
"(",
"tempfile",
".",
"mkdtemp",
"(",
")",
")",
"# Write temporary edges file with re-mapped Ids",
"logging",
".",... | Run OSLOM with an in-memory list of edges, return in-memory results. | [
"Run",
"OSLOM",
"with",
"an",
"in",
"-",
"memory",
"list",
"of",
"edges",
"return",
"in",
"-",
"memory",
"results",
"."
] | python | train |
saltstack/salt | salt/utils/dateutils.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/dateutils.py#L25-L60 | def date_cast(date):
'''
Casts any object into a datetime.datetime object
date
any datetime, time string representation...
'''
if date is None:
return datetime.datetime.now()
elif isinstance(date, datetime.datetime):
return date
# fuzzy date
try:
if isinstance(date, six.string_types):
try:
if HAS_TIMELIB:
# py3: yes, timelib.strtodatetime wants bytes, not str :/
return timelib.strtodatetime(
salt.utils.stringutils.to_bytes(date))
except ValueError:
pass
# not parsed yet, obviously a timestamp?
if date.isdigit():
date = int(date)
else:
date = float(date)
return datetime.datetime.fromtimestamp(date)
except Exception:
if HAS_TIMELIB:
raise ValueError('Unable to parse {0}'.format(date))
raise RuntimeError(
'Unable to parse {0}. Consider installing timelib'.format(date)) | [
"def",
"date_cast",
"(",
"date",
")",
":",
"if",
"date",
"is",
"None",
":",
"return",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"elif",
"isinstance",
"(",
"date",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"date",
"# fuzzy date",
"t... | Casts any object into a datetime.datetime object
date
any datetime, time string representation... | [
"Casts",
"any",
"object",
"into",
"a",
"datetime",
".",
"datetime",
"object"
] | python | train |
michaelpb/omnic | omnic/conversion/resolvergraph.py | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/conversion/resolvergraph.py#L76-L82 | async def download(self, resource_url):
'''
Download given Resource URL by finding path through graph and applying
each step
'''
resolver_path = self.find_path_from_url(resource_url)
await self.apply_resolver_path(resource_url, resolver_path) | [
"async",
"def",
"download",
"(",
"self",
",",
"resource_url",
")",
":",
"resolver_path",
"=",
"self",
".",
"find_path_from_url",
"(",
"resource_url",
")",
"await",
"self",
".",
"apply_resolver_path",
"(",
"resource_url",
",",
"resolver_path",
")"
] | Download given Resource URL by finding path through graph and applying
each step | [
"Download",
"given",
"Resource",
"URL",
"by",
"finding",
"path",
"through",
"graph",
"and",
"applying",
"each",
"step"
] | python | train |
gwastro/pycbc | pycbc/io/record.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1192-L1199 | def virtualfields(self):
"""Returns a tuple listing the names of virtual fields in self.
"""
if self._virtualfields is None:
vfs = tuple()
else:
vfs = tuple(self._virtualfields)
return vfs | [
"def",
"virtualfields",
"(",
"self",
")",
":",
"if",
"self",
".",
"_virtualfields",
"is",
"None",
":",
"vfs",
"=",
"tuple",
"(",
")",
"else",
":",
"vfs",
"=",
"tuple",
"(",
"self",
".",
"_virtualfields",
")",
"return",
"vfs"
] | Returns a tuple listing the names of virtual fields in self. | [
"Returns",
"a",
"tuple",
"listing",
"the",
"names",
"of",
"virtual",
"fields",
"in",
"self",
"."
] | python | train |
boriel/zxbasic | zxbparser.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L780-L784 | def p_bound(p):
""" bound : expr
"""
p[0] = make_bound(make_number(OPTIONS.array_base.value,
lineno=p.lineno(1)), p[1], p.lexer.lineno) | [
"def",
"p_bound",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"make_bound",
"(",
"make_number",
"(",
"OPTIONS",
".",
"array_base",
".",
"value",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
",",
"p",
"[",
"1",
"]",
",",
"p",
"... | bound : expr | [
"bound",
":",
"expr"
] | python | train |
opencobra/memote | memote/support/gpr_helpers.py | https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/support/gpr_helpers.py#L90-L100 | def visit_BoolOp(self, node):
"""Set up recording of elements with this hook."""
if self._is_top and isinstance(node.op, ast.And):
self._is_top = False
self._current = self.left
self.visit(node.values[0])
self._current = self.right
for successor in node.values[1:]:
self.visit(successor)
else:
self.generic_visit(node) | [
"def",
"visit_BoolOp",
"(",
"self",
",",
"node",
")",
":",
"if",
"self",
".",
"_is_top",
"and",
"isinstance",
"(",
"node",
".",
"op",
",",
"ast",
".",
"And",
")",
":",
"self",
".",
"_is_top",
"=",
"False",
"self",
".",
"_current",
"=",
"self",
".",... | Set up recording of elements with this hook. | [
"Set",
"up",
"recording",
"of",
"elements",
"with",
"this",
"hook",
"."
] | python | train |
google/grr | grr/server/grr_response_server/databases/mem_blobs.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mem_blobs.py#L35-L42 | def ReadBlobs(self, blob_ids):
"""Reads given blobs."""
result = {}
for blob_id in blob_ids:
result[blob_id] = self.blobs.get(blob_id, None)
return result | [
"def",
"ReadBlobs",
"(",
"self",
",",
"blob_ids",
")",
":",
"result",
"=",
"{",
"}",
"for",
"blob_id",
"in",
"blob_ids",
":",
"result",
"[",
"blob_id",
"]",
"=",
"self",
".",
"blobs",
".",
"get",
"(",
"blob_id",
",",
"None",
")",
"return",
"result"
] | Reads given blobs. | [
"Reads",
"given",
"blobs",
"."
] | python | train |
poldracklab/niworkflows | niworkflows/utils/misc.py | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/utils/misc.py#L14-L28 | def fix_multi_T1w_source_name(in_files):
"""
Make up a generic source name when there are multiple T1s
>>> fix_multi_T1w_source_name([
... '/path/to/sub-045_ses-test_T1w.nii.gz',
... '/path/to/sub-045_ses-retest_T1w.nii.gz'])
'/path/to/sub-045_T1w.nii.gz'
"""
import os
from nipype.utils.filemanip import filename_to_list
base, in_file = os.path.split(filename_to_list(in_files)[0])
subject_label = in_file.split("_", 1)[0].split("-")[1]
return os.path.join(base, "sub-%s_T1w.nii.gz" % subject_label) | [
"def",
"fix_multi_T1w_source_name",
"(",
"in_files",
")",
":",
"import",
"os",
"from",
"nipype",
".",
"utils",
".",
"filemanip",
"import",
"filename_to_list",
"base",
",",
"in_file",
"=",
"os",
".",
"path",
".",
"split",
"(",
"filename_to_list",
"(",
"in_files... | Make up a generic source name when there are multiple T1s
>>> fix_multi_T1w_source_name([
... '/path/to/sub-045_ses-test_T1w.nii.gz',
... '/path/to/sub-045_ses-retest_T1w.nii.gz'])
'/path/to/sub-045_T1w.nii.gz' | [
"Make",
"up",
"a",
"generic",
"source",
"name",
"when",
"there",
"are",
"multiple",
"T1s"
] | python | train |
maas/python-libmaas | maas/client/viscera/block_devices.py | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/block_devices.py#L141-L144 | async def unmount(self):
"""Unmount this block device."""
self._data = await self._handler.unmount(
system_id=self.node.system_id, id=self.id) | [
"async",
"def",
"unmount",
"(",
"self",
")",
":",
"self",
".",
"_data",
"=",
"await",
"self",
".",
"_handler",
".",
"unmount",
"(",
"system_id",
"=",
"self",
".",
"node",
".",
"system_id",
",",
"id",
"=",
"self",
".",
"id",
")"
] | Unmount this block device. | [
"Unmount",
"this",
"block",
"device",
"."
] | python | train |
underworldcode/stripy | stripy-src/stripy/spherical.py | https://github.com/underworldcode/stripy/blob/d4c3480c3e58c88489ded695eadbe7cd5bf94b48/stripy-src/stripy/spherical.py#L1096-L1148 | def nearest_vertices(self, lon, lat, k=1, max_distance=2.0 ):
"""
Query the cKDtree for the nearest neighbours and Euclidean
distance from x,y points.
Returns 0, 0 if a cKDtree has not been constructed
(switch tree=True if you need this routine)
Parameters
----------
lon : 1D array of longitudinal coordinates in radians
lat : 1D array of latitudinal coordinates in radians
k : number of nearest neighbours to return
(default: 1)
max_distance
: maximum Euclidean distance to search
for neighbours (default: 2.0)
Returns
-------
d : Euclidean distance between each point and their
nearest neighbour(s)
vert : vertices of the nearest neighbour(s)
"""
if self.tree == False or self.tree == None:
return 0, 0
lons = np.array(lon).reshape(-1,1)
lats = np.array(lat).reshape(-1,1)
xyz = np.empty((lons.shape[0],3))
x,y,z = lonlat2xyz(lons, lats)
xyz[:,0] = x[:].reshape(-1)
xyz[:,1] = y[:].reshape(-1)
xyz[:,2] = z[:].reshape(-1)
dxyz, vertices = self._cKDtree.query(xyz, k=k, distance_upper_bound=max_distance)
if k == 1: # force this to be a 2D array
vertices = np.reshape(vertices, (-1, 1))
## Now find the angular separation / great circle distance: dlatlon
vertxyz = self.points[vertices].transpose(0,2,1)
extxyz = np.repeat(xyz, k, axis=1).reshape(vertxyz.shape)
angles = np.arccos((extxyz * vertxyz).sum(axis=1))
return angles, vertices | [
"def",
"nearest_vertices",
"(",
"self",
",",
"lon",
",",
"lat",
",",
"k",
"=",
"1",
",",
"max_distance",
"=",
"2.0",
")",
":",
"if",
"self",
".",
"tree",
"==",
"False",
"or",
"self",
".",
"tree",
"==",
"None",
":",
"return",
"0",
",",
"0",
"lons"... | Query the cKDtree for the nearest neighbours and Euclidean
distance from x,y points.
Returns 0, 0 if a cKDtree has not been constructed
(switch tree=True if you need this routine)
Parameters
----------
lon : 1D array of longitudinal coordinates in radians
lat : 1D array of latitudinal coordinates in radians
k : number of nearest neighbours to return
(default: 1)
max_distance
: maximum Euclidean distance to search
for neighbours (default: 2.0)
Returns
-------
d : Euclidean distance between each point and their
nearest neighbour(s)
vert : vertices of the nearest neighbour(s) | [
"Query",
"the",
"cKDtree",
"for",
"the",
"nearest",
"neighbours",
"and",
"Euclidean",
"distance",
"from",
"x",
"y",
"points",
"."
] | python | train |
vnmabus/dcor | dcor/distances.py | https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/distances.py#L77-L89 | def _cdist(x, y, exponent=1):
"""
Pairwise distance between points in two sets.
As Scipy converts every value to double, this wrapper uses
a less efficient implementation if the original dtype
can not be converted to double.
"""
if _can_be_double(x) and _can_be_double(y):
return _cdist_scipy(x, y, exponent)
else:
return _cdist_naive(x, y, exponent) | [
"def",
"_cdist",
"(",
"x",
",",
"y",
",",
"exponent",
"=",
"1",
")",
":",
"if",
"_can_be_double",
"(",
"x",
")",
"and",
"_can_be_double",
"(",
"y",
")",
":",
"return",
"_cdist_scipy",
"(",
"x",
",",
"y",
",",
"exponent",
")",
"else",
":",
"return",... | Pairwise distance between points in two sets.
As Scipy converts every value to double, this wrapper uses
a less efficient implementation if the original dtype
can not be converted to double. | [
"Pairwise",
"distance",
"between",
"points",
"in",
"two",
"sets",
"."
] | python | train |
apache/incubator-mxnet | python/mxnet/contrib/onnx/mx2onnx/_op_translations.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/mx2onnx/_op_translations.py#L86-L103 | def transform_padding(pad_width):
"""Helper function to convert padding format for pad operator.
"""
num_pad_values = len(pad_width)
onnx_pad_width = [0]*num_pad_values
start_index = 0
# num_pad_values will always be multiple of 2
end_index = int(num_pad_values/2)
for idx in range(0, num_pad_values):
if idx % 2 == 0:
onnx_pad_width[start_index] = pad_width[idx]
start_index += 1
else:
onnx_pad_width[end_index] = pad_width[idx]
end_index += 1
return onnx_pad_width | [
"def",
"transform_padding",
"(",
"pad_width",
")",
":",
"num_pad_values",
"=",
"len",
"(",
"pad_width",
")",
"onnx_pad_width",
"=",
"[",
"0",
"]",
"*",
"num_pad_values",
"start_index",
"=",
"0",
"# num_pad_values will always be multiple of 2",
"end_index",
"=",
"int... | Helper function to convert padding format for pad operator. | [
"Helper",
"function",
"to",
"convert",
"padding",
"format",
"for",
"pad",
"operator",
"."
] | python | train |
KarchinLab/probabilistic2020 | prob2020/python/amino_acid.py | https://github.com/KarchinLab/probabilistic2020/blob/5d70583b0a7c07cfe32e95f3a70e05df412acb84/prob2020/python/amino_acid.py#L209-L233 | def __set_unkown_effect(self, hgvs_string):
"""Sets a flag for unkown effect according to HGVS syntax. The
COSMIC database also uses unconventional questionmarks to denote
missing information.
Args:
hgvs_string (str): hgvs syntax with "p." removed
"""
# Standard use by HGVS of indicating unknown effect.
unknown_effect_list = ['?', '(=)', '='] # unknown effect symbols
if hgvs_string in unknown_effect_list:
self.unknown_effect = True
elif "(" in hgvs_string:
# parethesis in HGVS indicate expected outcomes
self.unknown_effect = True
else:
self.unknown_effect = False
# detect if there are missing information. commonly COSMIC will
# have insertions with p.?_?ins? or deleteions with ?del indicating
# missing information.
if "?" in hgvs_string:
self.is_missing_info = True
else:
self.is_missing_info = False | [
"def",
"__set_unkown_effect",
"(",
"self",
",",
"hgvs_string",
")",
":",
"# Standard use by HGVS of indicating unknown effect.",
"unknown_effect_list",
"=",
"[",
"'?'",
",",
"'(=)'",
",",
"'='",
"]",
"# unknown effect symbols",
"if",
"hgvs_string",
"in",
"unknown_effect_l... | Sets a flag for unkown effect according to HGVS syntax. The
COSMIC database also uses unconventional questionmarks to denote
missing information.
Args:
hgvs_string (str): hgvs syntax with "p." removed | [
"Sets",
"a",
"flag",
"for",
"unkown",
"effect",
"according",
"to",
"HGVS",
"syntax",
".",
"The",
"COSMIC",
"database",
"also",
"uses",
"unconventional",
"questionmarks",
"to",
"denote",
"missing",
"information",
"."
] | python | train |
uber/doubles | doubles/method_double.py | https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/method_double.py#L30-L40 | def add_allowance(self, caller):
"""Adds a new allowance for the method.
:param: tuple caller: A tuple indicating where the method was called
:return: The new ``Allowance``.
:rtype: Allowance
"""
allowance = Allowance(self._target, self._method_name, caller)
self._allowances.insert(0, allowance)
return allowance | [
"def",
"add_allowance",
"(",
"self",
",",
"caller",
")",
":",
"allowance",
"=",
"Allowance",
"(",
"self",
".",
"_target",
",",
"self",
".",
"_method_name",
",",
"caller",
")",
"self",
".",
"_allowances",
".",
"insert",
"(",
"0",
",",
"allowance",
")",
... | Adds a new allowance for the method.
:param: tuple caller: A tuple indicating where the method was called
:return: The new ``Allowance``.
:rtype: Allowance | [
"Adds",
"a",
"new",
"allowance",
"for",
"the",
"method",
"."
] | python | train |
tanghaibao/jcvi | jcvi/assembly/syntenypath.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/syntenypath.py#L452-L516 | def connect(args):
"""
%prog connect assembly.fasta read_mapping.blast
Connect contigs using long reads.
"""
p = OptionParser(connect.__doc__)
p.add_option("--clip", default=2000, type="int",
help="Only consider end of contigs [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
fastafile, blastfile = args
clip = opts.clip
sizes = Sizes(fastafile).mapping
blast = Blast(blastfile)
blasts = []
for b in blast:
seqid = b.subject
size = sizes[seqid]
start, end = b.sstart, b.sstop
cstart, cend = min(size, clip), max(0, size - clip)
if start > cstart and end < cend:
continue
blasts.append(b)
key = lambda x: x.query
blasts.sort(key=key)
g = BiGraph()
for query, bb in groupby(blasts, key=key):
bb = sorted(bb, key=lambda x: x.qstart)
nsubjects = len(set(x.subject for x in bb))
if nsubjects == 1:
continue
print("\n".join(str(x) for x in bb))
for a, b in pairwise(bb):
astart, astop = a.qstart, a.qstop
bstart, bstop = b.qstart, b.qstop
if a.subject == b.subject:
continue
arange = astart, astop
brange = bstart, bstop
ov = range_intersect(arange, brange)
alen = astop - astart + 1
blen = bstop - bstart + 1
if ov:
ostart, ostop = ov
ov = ostop - ostart + 1
print(ov, alen, blen)
if ov and (ov > alen / 2 or ov > blen / 2):
print("Too much overlap ({0})".format(ov))
continue
asub = a.subject
bsub = b.subject
atag = ">" if a.orientation == "+" else "<"
btag = ">" if b.orientation == "+" else "<"
g.add_edge(asub, bsub, atag, btag)
graph_to_agp(g, blastfile, fastafile, verbose=False) | [
"def",
"connect",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"connect",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--clip\"",
",",
"default",
"=",
"2000",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Only consider end of contigs [... | %prog connect assembly.fasta read_mapping.blast
Connect contigs using long reads. | [
"%prog",
"connect",
"assembly",
".",
"fasta",
"read_mapping",
".",
"blast"
] | python | train |
csparpa/pyowm | pyowm/weatherapi25/owm25.py | https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/owm25.py#L460-L508 | def weather_at_places_in_bbox(self, lon_left, lat_bottom, lon_right, lat_top,
zoom=10, cluster=False):
"""
Queries the OWM Weather API for the weather currently observed by
meteostations inside the bounding box of latitude/longitude coords.
:param lat_top: latitude for top margin of bounding box, must be
between -90.0 and 90.0
:type lat_top: int/float
:param lon_left: longitude for left margin of bounding box
must be between -180.0 and 180.0
:type lon_left: int/float
:param lat_bottom: latitude for the bottom margin of bounding box, must
be between -90.0 and 90.0
:type lat_bottom: int/float
:param lon_right: longitude for the right margin of bounding box,
must be between -180.0 and 180.0
:type lon_right: int/float
:param zoom: zoom level (defaults to: 10)
:type zoom: int
:param cluster: use server clustering of points
:type cluster: bool
:returns: a list of *Observation* objects or ``None`` if no weather
data is available
:raises: *ParseResponseException* when OWM Weather API responses' data
cannot be parsed, *APICallException* when OWM Weather API can not be
reached, *ValueError* when coordinates values are out of bounds or
negative values are provided for limit
"""
geo.assert_is_lon(lon_left)
geo.assert_is_lon(lon_right)
geo.assert_is_lat(lat_bottom)
geo.assert_is_lat(lat_top)
assert type(zoom) is int, "'zoom' must be an int"
if zoom <= 0:
raise ValueError("'zoom' must greater than zero")
assert type(cluster) is bool, "'cluster' must be a bool"
params = {'bbox': ','.join([str(lon_left),
str(lat_bottom),
str(lon_right),
str(lat_top),
str(zoom)]),
'cluster': 'yes' if cluster else 'no'}
uri = http_client.HttpClient.to_url(BBOX_CITY_URL,
self._API_key,
self._subscription_type,
self._use_ssl)
_, json_data = self._wapi.cacheable_get_json(uri, params=params)
return self._parsers['observation_list'].parse_JSON(json_data) | [
"def",
"weather_at_places_in_bbox",
"(",
"self",
",",
"lon_left",
",",
"lat_bottom",
",",
"lon_right",
",",
"lat_top",
",",
"zoom",
"=",
"10",
",",
"cluster",
"=",
"False",
")",
":",
"geo",
".",
"assert_is_lon",
"(",
"lon_left",
")",
"geo",
".",
"assert_is... | Queries the OWM Weather API for the weather currently observed by
meteostations inside the bounding box of latitude/longitude coords.
:param lat_top: latitude for top margin of bounding box, must be
between -90.0 and 90.0
:type lat_top: int/float
:param lon_left: longitude for left margin of bounding box
must be between -180.0 and 180.0
:type lon_left: int/float
:param lat_bottom: latitude for the bottom margin of bounding box, must
be between -90.0 and 90.0
:type lat_bottom: int/float
:param lon_right: longitude for the right margin of bounding box,
must be between -180.0 and 180.0
:type lon_right: int/float
:param zoom: zoom level (defaults to: 10)
:type zoom: int
:param cluster: use server clustering of points
:type cluster: bool
:returns: a list of *Observation* objects or ``None`` if no weather
data is available
:raises: *ParseResponseException* when OWM Weather API responses' data
cannot be parsed, *APICallException* when OWM Weather API can not be
reached, *ValueError* when coordinates values are out of bounds or
negative values are provided for limit | [
"Queries",
"the",
"OWM",
"Weather",
"API",
"for",
"the",
"weather",
"currently",
"observed",
"by",
"meteostations",
"inside",
"the",
"bounding",
"box",
"of",
"latitude",
"/",
"longitude",
"coords",
"."
] | python | train |
rwl/godot | godot/base_graph.py | https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/base_graph.py#L623-L627 | def _set_node_lists(self, new):
""" Maintains each edge's list of available nodes.
"""
for edge in self.edges:
edge._nodes = self.nodes | [
"def",
"_set_node_lists",
"(",
"self",
",",
"new",
")",
":",
"for",
"edge",
"in",
"self",
".",
"edges",
":",
"edge",
".",
"_nodes",
"=",
"self",
".",
"nodes"
] | Maintains each edge's list of available nodes. | [
"Maintains",
"each",
"edge",
"s",
"list",
"of",
"available",
"nodes",
"."
] | python | test |
limpyd/redis-limpyd | limpyd/contrib/collection.py | https://github.com/limpyd/redis-limpyd/blob/3c745dde1390a0bd09690b77a089dcc08c6c7e43/limpyd/contrib/collection.py#L397-L424 | def _prepare_sort_by_score(self, values, sort_options):
"""
Create the key to sort on the sorted set references in
self._sort_by_sortedset and adapte sort options
"""
# create the keys
base_tmp_key, tmp_keys = self._zset_to_keys(
key=self._sort_by_sortedset['by'],
values=values,
)
# ask to sort on our new keys
sort_options['by'] = '%s:*' % base_tmp_key
# retrieve original sort parameters
for key in ('desc', 'alpha', 'get', 'store'):
if key in self._sort_by_sortedset:
sort_options[key] = self._sort_by_sortedset[key]
# if we want to get the score with values/values_list
if sort_options.get('get'):
try:
pos = sort_options['get'].index(SORTED_SCORE)
except:
pass
else:
sort_options['get'][pos] = '%s:*' % base_tmp_key
return base_tmp_key, tmp_keys | [
"def",
"_prepare_sort_by_score",
"(",
"self",
",",
"values",
",",
"sort_options",
")",
":",
"# create the keys",
"base_tmp_key",
",",
"tmp_keys",
"=",
"self",
".",
"_zset_to_keys",
"(",
"key",
"=",
"self",
".",
"_sort_by_sortedset",
"[",
"'by'",
"]",
",",
"val... | Create the key to sort on the sorted set references in
self._sort_by_sortedset and adapte sort options | [
"Create",
"the",
"key",
"to",
"sort",
"on",
"the",
"sorted",
"set",
"references",
"in",
"self",
".",
"_sort_by_sortedset",
"and",
"adapte",
"sort",
"options"
] | python | train |
fabioz/PyDev.Debugger | third_party/pep8/autopep8.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/autopep8.py#L3692-L3706 | def fix_multiple_files(filenames, options, output=None):
"""Fix list of files.
Optionally fix files recursively.
"""
filenames = find_files(filenames, options.recursive, options.exclude)
if options.jobs > 1:
import multiprocessing
pool = multiprocessing.Pool(options.jobs)
pool.map(_fix_file,
[(name, options) for name in filenames])
else:
for name in filenames:
_fix_file((name, options, output)) | [
"def",
"fix_multiple_files",
"(",
"filenames",
",",
"options",
",",
"output",
"=",
"None",
")",
":",
"filenames",
"=",
"find_files",
"(",
"filenames",
",",
"options",
".",
"recursive",
",",
"options",
".",
"exclude",
")",
"if",
"options",
".",
"jobs",
">",... | Fix list of files.
Optionally fix files recursively. | [
"Fix",
"list",
"of",
"files",
"."
] | python | train |
JoelBender/bacpypes | py25/bacpypes/udp.py | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/udp.py#L167-L175 | def add_actor(self, actor):
"""Add an actor when a new one is connected."""
if _debug: UDPDirector._debug("add_actor %r", actor)
self.peers[actor.peer] = actor
# tell the ASE there is a new client
if self.serviceElement:
self.sap_request(add_actor=actor) | [
"def",
"add_actor",
"(",
"self",
",",
"actor",
")",
":",
"if",
"_debug",
":",
"UDPDirector",
".",
"_debug",
"(",
"\"add_actor %r\"",
",",
"actor",
")",
"self",
".",
"peers",
"[",
"actor",
".",
"peer",
"]",
"=",
"actor",
"# tell the ASE there is a new client"... | Add an actor when a new one is connected. | [
"Add",
"an",
"actor",
"when",
"a",
"new",
"one",
"is",
"connected",
"."
] | python | train |
Esri/ArcREST | src/arcrest/geometryservice/geometryservice.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/geometryservice/geometryservice.py#L791-L838 | def offset(self,
geometries,
offsetDistance,
offsetUnit,
offsetHow="esriGeometryOffsetRounded",
bevelRatio=10,
simplifyResult=False,
sr=None,
):
"""
The offset operation is performed on a geometry service resource. This
operation constructs geometries that are offset from the given input geometries.
Inputs:
geometries - array of geometries to be offset (structured as JSON geometry
objects returned by the ArcGIS REST API).
sr - spatial reference of the input geometries WKID.
offsetDistance - the distance for constructing an offset based on the
input geometries.
offsetUnit - A unit for offset distance. If a unit is not specified,
the units are derived from sr.
offsetHow - determines how outer corners between segments are handled.
bevelRatio - is multiplied by the offset distance, and the result determines
how far a mitered offset intersection can be located
before it is bevelled.
simplifyResult - if set to true, then self intersecting loops will be
removed from the result offset geometries.
"""
allowedHow = ["esriGeometryOffsetRounded",
"esriGeometryOffsetBevelled",
"esriGeometryOffsetMitered"]
if offsetHow not in allowedHow:
raise AttributeError("Invalid Offset How value")
url = self._url + "/offset"
params = {
"f" : "json",
"sr" : sr,
"geometries": self.__geometryListToGeomTemplate(geometries=geometries),
"offsetDistance": offsetDistance,
"offsetUnit" : offsetUnit,
"offsetHow" : offsetHow,
"bevelRatio" : bevelRatio,
"simplifyResult" : simplifyResult
}
return self._get(url=url, param_dict=params,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port) | [
"def",
"offset",
"(",
"self",
",",
"geometries",
",",
"offsetDistance",
",",
"offsetUnit",
",",
"offsetHow",
"=",
"\"esriGeometryOffsetRounded\"",
",",
"bevelRatio",
"=",
"10",
",",
"simplifyResult",
"=",
"False",
",",
"sr",
"=",
"None",
",",
")",
":",
"allo... | The offset operation is performed on a geometry service resource. This
operation constructs geometries that are offset from the given input geometries.
Inputs:
geometries - array of geometries to be offset (structured as JSON geometry
objects returned by the ArcGIS REST API).
sr - spatial reference of the input geometries WKID.
offsetDistance - the distance for constructing an offset based on the
input geometries.
offsetUnit - A unit for offset distance. If a unit is not specified,
the units are derived from sr.
offsetHow - determines how outer corners between segments are handled.
bevelRatio - is multiplied by the offset distance, and the result determines
how far a mitered offset intersection can be located
before it is bevelled.
simplifyResult - if set to true, then self intersecting loops will be
removed from the result offset geometries. | [
"The",
"offset",
"operation",
"is",
"performed",
"on",
"a",
"geometry",
"service",
"resource",
".",
"This",
"operation",
"constructs",
"geometries",
"that",
"are",
"offset",
"from",
"the",
"given",
"input",
"geometries",
".",
"Inputs",
":",
"geometries",
"-",
... | python | train |
joowani/binarytree | binarytree/__init__.py | https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L1543-L1601 | def postorder(self):
"""Return the nodes in the binary tree using post-order_ traversal.
A post-order_ traversal visits left subtree, right subtree, then root.
.. _post-order: https://en.wikipedia.org/wiki/Tree_traversal
:return: List of nodes.
:rtype: [binarytree.Node]
**Example**:
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1)
>>> root.left = Node(2)
>>> root.right = Node(3)
>>> root.left.left = Node(4)
>>> root.left.right = Node(5)
>>>
>>> print(root)
<BLANKLINE>
__1
/ \\
2 3
/ \\
4 5
<BLANKLINE>
>>> root.postorder
[Node(4), Node(5), Node(2), Node(3), Node(1)]
"""
node_stack = []
result = []
node = self
while True:
while node is not None:
if node.right is not None:
node_stack.append(node.right)
node_stack.append(node)
node = node.left
node = node_stack.pop()
if (node.right is not None and
len(node_stack) > 0 and
node_stack[-1] is node.right):
node_stack.pop()
node_stack.append(node)
node = node.right
else:
result.append(node)
node = None
if len(node_stack) == 0:
break
return result | [
"def",
"postorder",
"(",
"self",
")",
":",
"node_stack",
"=",
"[",
"]",
"result",
"=",
"[",
"]",
"node",
"=",
"self",
"while",
"True",
":",
"while",
"node",
"is",
"not",
"None",
":",
"if",
"node",
".",
"right",
"is",
"not",
"None",
":",
"node_stack... | Return the nodes in the binary tree using post-order_ traversal.
A post-order_ traversal visits left subtree, right subtree, then root.
.. _post-order: https://en.wikipedia.org/wiki/Tree_traversal
:return: List of nodes.
:rtype: [binarytree.Node]
**Example**:
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1)
>>> root.left = Node(2)
>>> root.right = Node(3)
>>> root.left.left = Node(4)
>>> root.left.right = Node(5)
>>>
>>> print(root)
<BLANKLINE>
__1
/ \\
2 3
/ \\
4 5
<BLANKLINE>
>>> root.postorder
[Node(4), Node(5), Node(2), Node(3), Node(1)] | [
"Return",
"the",
"nodes",
"in",
"the",
"binary",
"tree",
"using",
"post",
"-",
"order_",
"traversal",
"."
] | python | train |
maxcountryman/flask-uploads | flask_uploads.py | https://github.com/maxcountryman/flask-uploads/blob/dc24fa0c53d605876e5b4502cadffdf1a4345b1d/flask_uploads.py#L433-L452 | def resolve_conflict(self, target_folder, basename):
"""
If a file with the selected name already exists in the target folder,
this method is called to resolve the conflict. It should return a new
basename for the file.
The default implementation splits the name and extension and adds a
suffix to the name consisting of an underscore and a number, and tries
that until it finds one that doesn't exist.
:param target_folder: The absolute path to the target.
:param basename: The file's original basename.
"""
name, ext = os.path.splitext(basename)
count = 0
while True:
count = count + 1
newname = '%s_%d%s' % (name, count, ext)
if not os.path.exists(os.path.join(target_folder, newname)):
return newname | [
"def",
"resolve_conflict",
"(",
"self",
",",
"target_folder",
",",
"basename",
")",
":",
"name",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"basename",
")",
"count",
"=",
"0",
"while",
"True",
":",
"count",
"=",
"count",
"+",
"1",
"new... | If a file with the selected name already exists in the target folder,
this method is called to resolve the conflict. It should return a new
basename for the file.
The default implementation splits the name and extension and adds a
suffix to the name consisting of an underscore and a number, and tries
that until it finds one that doesn't exist.
:param target_folder: The absolute path to the target.
:param basename: The file's original basename. | [
"If",
"a",
"file",
"with",
"the",
"selected",
"name",
"already",
"exists",
"in",
"the",
"target",
"folder",
"this",
"method",
"is",
"called",
"to",
"resolve",
"the",
"conflict",
".",
"It",
"should",
"return",
"a",
"new",
"basename",
"for",
"the",
"file",
... | python | test |
marl/jams | jams/display.py | https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/display.py#L146-L197 | def display(annotation, meta=True, **kwargs):
'''Visualize a jams annotation through mir_eval
Parameters
----------
annotation : jams.Annotation
The annotation to display
meta : bool
If `True`, include annotation metadata in the figure
kwargs
Additional keyword arguments to mir_eval.display functions
Returns
-------
ax
Axis handles for the new display
Raises
------
NamespaceError
If the annotation cannot be visualized
'''
for namespace, func in six.iteritems(VIZ_MAPPING):
try:
ann = coerce_annotation(annotation, namespace)
axes = func(ann, **kwargs)
# Title should correspond to original namespace, not the coerced version
axes.set_title(annotation.namespace)
if meta:
description = pprint_jobject(annotation.annotation_metadata, indent=2)
anchored_box = AnchoredText(description.strip('\n'),
loc=2,
frameon=True,
bbox_to_anchor=(1.02, 1.0),
bbox_transform=axes.transAxes,
borderpad=0.0)
axes.add_artist(anchored_box)
axes.figure.subplots_adjust(right=0.8)
return axes
except NamespaceError:
pass
raise NamespaceError('Unable to visualize annotation of namespace="{:s}"'
.format(annotation.namespace)) | [
"def",
"display",
"(",
"annotation",
",",
"meta",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"namespace",
",",
"func",
"in",
"six",
".",
"iteritems",
"(",
"VIZ_MAPPING",
")",
":",
"try",
":",
"ann",
"=",
"coerce_annotation",
"(",
"annotatio... | Visualize a jams annotation through mir_eval
Parameters
----------
annotation : jams.Annotation
The annotation to display
meta : bool
If `True`, include annotation metadata in the figure
kwargs
Additional keyword arguments to mir_eval.display functions
Returns
-------
ax
Axis handles for the new display
Raises
------
NamespaceError
If the annotation cannot be visualized | [
"Visualize",
"a",
"jams",
"annotation",
"through",
"mir_eval"
] | python | valid |
ev3dev/ev3dev-lang-python | ev3dev2/motor.py | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L628-L637 | def ramp_up_sp(self):
"""
Writing sets the ramp up setpoint. Reading returns the current value. Units
are in milliseconds and must be positive. When set to a non-zero value, the
motor speed will increase from 0 to 100% of `max_speed` over the span of this
setpoint. The actual ramp time is the ratio of the difference between the
`speed_sp` and the current `speed` and max_speed multiplied by `ramp_up_sp`.
"""
self._ramp_up_sp, value = self.get_attr_int(self._ramp_up_sp, 'ramp_up_sp')
return value | [
"def",
"ramp_up_sp",
"(",
"self",
")",
":",
"self",
".",
"_ramp_up_sp",
",",
"value",
"=",
"self",
".",
"get_attr_int",
"(",
"self",
".",
"_ramp_up_sp",
",",
"'ramp_up_sp'",
")",
"return",
"value"
] | Writing sets the ramp up setpoint. Reading returns the current value. Units
are in milliseconds and must be positive. When set to a non-zero value, the
motor speed will increase from 0 to 100% of `max_speed` over the span of this
setpoint. The actual ramp time is the ratio of the difference between the
`speed_sp` and the current `speed` and max_speed multiplied by `ramp_up_sp`. | [
"Writing",
"sets",
"the",
"ramp",
"up",
"setpoint",
".",
"Reading",
"returns",
"the",
"current",
"value",
".",
"Units",
"are",
"in",
"milliseconds",
"and",
"must",
"be",
"positive",
".",
"When",
"set",
"to",
"a",
"non",
"-",
"zero",
"value",
"the",
"moto... | python | train |
PatrikValkovic/grammpy | grammpy/transforms/UnitRulesRemove/unit_rules_restore.py | https://github.com/PatrikValkovic/grammpy/blob/879ce0ef794ac2823acc19314fcd7a8aba53e50f/grammpy/transforms/UnitRulesRemove/unit_rules_restore.py#L18-L46 | def unit_rules_restore(root):
# type: (Nonterminal) -> Nonterminal
"""
Transform parsed tree for grammar with removed unit rules.
The unit rules will be returned back to the tree.
:param root: Root of the parsed tree.
:return: Modified tree.
"""
items = Traversing.post_order(root)
items = filter(lambda x: isinstance(x, ReducedUnitRule), items)
for rule in items:
parent_nonterm = rule.from_symbols[0] # type: Nonterminal
# restore chain of unit rules
for r in rule.by_rules:
created_rule = r() # type: Rule
parent_nonterm._set_to_rule(created_rule)
created_rule._from_symbols.append(parent_nonterm)
created_nonterm = r.toSymbol() # type: Nonterminal
created_rule._to_symbols.append(created_nonterm)
created_nonterm._set_from_rule(created_rule)
parent_nonterm = created_nonterm
# restore last rule
last_rule = rule.end_rule() # type: Rule
last_rule._from_symbols.append(parent_nonterm)
parent_nonterm._set_to_rule(last_rule)
for ch in rule.to_symbols: # type: Nonterminal
ch._set_from_rule(last_rule)
last_rule._to_symbols.append(ch)
return root | [
"def",
"unit_rules_restore",
"(",
"root",
")",
":",
"# type: (Nonterminal) -> Nonterminal",
"items",
"=",
"Traversing",
".",
"post_order",
"(",
"root",
")",
"items",
"=",
"filter",
"(",
"lambda",
"x",
":",
"isinstance",
"(",
"x",
",",
"ReducedUnitRule",
")",
"... | Transform parsed tree for grammar with removed unit rules.
The unit rules will be returned back to the tree.
:param root: Root of the parsed tree.
:return: Modified tree. | [
"Transform",
"parsed",
"tree",
"for",
"grammar",
"with",
"removed",
"unit",
"rules",
".",
"The",
"unit",
"rules",
"will",
"be",
"returned",
"back",
"to",
"the",
"tree",
".",
":",
"param",
"root",
":",
"Root",
"of",
"the",
"parsed",
"tree",
".",
":",
"r... | python | train |
bcbio/bcbio-nextgen | bcbio/variation/effects.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/effects.py#L360-L386 | def _run_snpeff(snp_in, out_format, data):
"""Run effects prediction with snpEff, skipping if snpEff database not present.
"""
snpeff_db, datadir = get_db(data)
if not snpeff_db:
return None, None
assert os.path.exists(os.path.join(datadir, snpeff_db)), \
"Did not find %s snpEff genome data in %s" % (snpeff_db, datadir)
ext = utils.splitext_plus(snp_in)[1] if out_format == "vcf" else ".tsv"
out_file = "%s-effects%s" % (utils.splitext_plus(snp_in)[0], ext)
stats_file = "%s-stats.html" % utils.splitext_plus(out_file)[0]
csv_file = "%s-stats.csv" % utils.splitext_plus(out_file)[0]
if not utils.file_exists(out_file):
config_args = " ".join(_snpeff_args_from_config(data))
if ext.endswith(".gz"):
bgzip_cmd = "| %s -c" % tools.get_bgzip_cmd(data["config"])
else:
bgzip_cmd = ""
with file_transaction(data, out_file) as tx_out_file:
snpeff_cmd = _get_snpeff_cmd("eff", datadir, data, tx_out_file)
cmd = ("{snpeff_cmd} {config_args} -noLog -i vcf -o {out_format} "
"-csvStats {csv_file} -s {stats_file} {snpeff_db} {snp_in} {bgzip_cmd} > {tx_out_file}")
do.run(cmd.format(**locals()), "snpEff effects", data)
if ext.endswith(".gz"):
out_file = vcfutils.bgzip_and_index(out_file, data["config"])
return out_file, [stats_file, csv_file] | [
"def",
"_run_snpeff",
"(",
"snp_in",
",",
"out_format",
",",
"data",
")",
":",
"snpeff_db",
",",
"datadir",
"=",
"get_db",
"(",
"data",
")",
"if",
"not",
"snpeff_db",
":",
"return",
"None",
",",
"None",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
... | Run effects prediction with snpEff, skipping if snpEff database not present. | [
"Run",
"effects",
"prediction",
"with",
"snpEff",
"skipping",
"if",
"snpEff",
"database",
"not",
"present",
"."
] | python | train |
pantsbuild/pants | src/python/pants/engine/build_files.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/build_files.py#L229-L234 | def _spec_to_globs(address_mapper, specs):
"""Given a Specs object, return a PathGlobs object for the build files that it matches."""
patterns = set()
for spec in specs:
patterns.update(spec.make_glob_patterns(address_mapper))
return PathGlobs(include=patterns, exclude=address_mapper.build_ignore_patterns) | [
"def",
"_spec_to_globs",
"(",
"address_mapper",
",",
"specs",
")",
":",
"patterns",
"=",
"set",
"(",
")",
"for",
"spec",
"in",
"specs",
":",
"patterns",
".",
"update",
"(",
"spec",
".",
"make_glob_patterns",
"(",
"address_mapper",
")",
")",
"return",
"Path... | Given a Specs object, return a PathGlobs object for the build files that it matches. | [
"Given",
"a",
"Specs",
"object",
"return",
"a",
"PathGlobs",
"object",
"for",
"the",
"build",
"files",
"that",
"it",
"matches",
"."
] | python | train |
ktbyers/netmiko | netmiko/scp_handler.py | https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/scp_handler.py#L325-L335 | def enable_scp(self, cmd=None):
"""
Enable SCP on remote device.
Defaults to Cisco IOS command
"""
if cmd is None:
cmd = ["ip scp server enable"]
elif not hasattr(cmd, "__iter__"):
cmd = [cmd]
self.ssh_ctl_chan.send_config_set(cmd) | [
"def",
"enable_scp",
"(",
"self",
",",
"cmd",
"=",
"None",
")",
":",
"if",
"cmd",
"is",
"None",
":",
"cmd",
"=",
"[",
"\"ip scp server enable\"",
"]",
"elif",
"not",
"hasattr",
"(",
"cmd",
",",
"\"__iter__\"",
")",
":",
"cmd",
"=",
"[",
"cmd",
"]",
... | Enable SCP on remote device.
Defaults to Cisco IOS command | [
"Enable",
"SCP",
"on",
"remote",
"device",
"."
] | python | train |
neherlab/treetime | treetime/clock_tree.py | https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/clock_tree.py#L651-L687 | def convert_dates(self):
'''
This function converts the estimated "time_before_present" properties of all nodes
to numerical dates stored in the "numdate" attribute. This date is further converted
into a human readable date string in format %Y-%m-%d assuming the usual calendar.
Returns
-------
None
All manipulations are done in place on the tree
'''
from datetime import datetime, timedelta
now = numeric_date()
for node in self.tree.find_clades():
years_bp = self.date2dist.to_years(node.time_before_present)
if years_bp < 0 and self.real_dates:
if not hasattr(node, "bad_branch") or node.bad_branch is False:
self.logger("ClockTree.convert_dates -- WARNING: The node is later than today, but it is not "
"marked as \"BAD\", which indicates the error in the "
"likelihood optimization.",4 , warn=True)
else:
self.logger("ClockTree.convert_dates -- WARNING: node which is marked as \"BAD\" optimized "
"later than present day",4 , warn=True)
node.numdate = now - years_bp
# set the human-readable date
year = np.floor(node.numdate)
days = max(0,365.25 * (node.numdate - year)-1)
try: # datetime will only operate on dates after 1900
n_date = datetime(year, 1, 1) + timedelta(days=days)
node.date = datetime.strftime(n_date, "%Y-%m-%d")
except:
# this is the approximation not accounting for gap years etc
n_date = datetime(1900, 1, 1) + timedelta(days=days)
node.date = "%04d-%02d-%02d"%(year, n_date.month, n_date.day) | [
"def",
"convert_dates",
"(",
"self",
")",
":",
"from",
"datetime",
"import",
"datetime",
",",
"timedelta",
"now",
"=",
"numeric_date",
"(",
")",
"for",
"node",
"in",
"self",
".",
"tree",
".",
"find_clades",
"(",
")",
":",
"years_bp",
"=",
"self",
".",
... | This function converts the estimated "time_before_present" properties of all nodes
to numerical dates stored in the "numdate" attribute. This date is further converted
into a human readable date string in format %Y-%m-%d assuming the usual calendar.
Returns
-------
None
All manipulations are done in place on the tree | [
"This",
"function",
"converts",
"the",
"estimated",
"time_before_present",
"properties",
"of",
"all",
"nodes",
"to",
"numerical",
"dates",
"stored",
"in",
"the",
"numdate",
"attribute",
".",
"This",
"date",
"is",
"further",
"converted",
"into",
"a",
"human",
"re... | python | test |
utek/pyseaweed | pyseaweed/weed.py | https://github.com/utek/pyseaweed/blob/218049329885425a2b8370157fa44952e64516be/pyseaweed/weed.py#L214-L225 | def version(self):
'''
Returns Weed-FS master version
:rtype: string
'''
url = "http://{master_addr}:{master_port}/dir/status".format(
master_addr=self.master_addr,
master_port=self.master_port)
data = self.conn.get_data(url)
response_data = json.loads(data)
return response_data.get("Version") | [
"def",
"version",
"(",
"self",
")",
":",
"url",
"=",
"\"http://{master_addr}:{master_port}/dir/status\"",
".",
"format",
"(",
"master_addr",
"=",
"self",
".",
"master_addr",
",",
"master_port",
"=",
"self",
".",
"master_port",
")",
"data",
"=",
"self",
".",
"c... | Returns Weed-FS master version
:rtype: string | [
"Returns",
"Weed",
"-",
"FS",
"master",
"version"
] | python | train |
couchbase/couchbase-python-client | couchbase/bucket.py | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L786-L828 | def mutate_in(self, key, *specs, **kwargs):
"""Perform multiple atomic modifications within a document.
:param key: The key of the document to modify
:param specs: A list of specs (See :mod:`.couchbase.subdocument`)
:param bool create_doc:
Whether the document should be create if it doesn't exist
:param bool insert_doc: If the document should be created anew, and the
operations performed *only* if it does not exist.
:param bool upsert_doc: If the document should be created anew if it
does not exist. If it does exist the commands are still executed.
:param kwargs: CAS, etc.
:return: A :class:`~.couchbase.result.SubdocResult` object.
Here's an example of adding a new tag to a "user" document
and incrementing a modification counter::
import couchbase.subdocument as SD
# ....
cb.mutate_in('user',
SD.array_addunique('tags', 'dog'),
SD.counter('updates', 1))
.. note::
The `insert_doc` and `upsert_doc` options are mutually exclusive.
Use `insert_doc` when you wish to create a new document with
extended attributes (xattrs).
.. seealso:: :mod:`.couchbase.subdocument`
"""
# Note we don't verify the validity of the options. lcb does that for
# us.
sdflags = kwargs.pop('_sd_doc_flags', 0)
if kwargs.pop('insert_doc', False):
sdflags |= _P.CMDSUBDOC_F_INSERT_DOC
if kwargs.pop('upsert_doc', False):
sdflags |= _P.CMDSUBDOC_F_UPSERT_DOC
kwargs['_sd_doc_flags'] = sdflags
return super(Bucket, self).mutate_in(key, specs, **kwargs) | [
"def",
"mutate_in",
"(",
"self",
",",
"key",
",",
"*",
"specs",
",",
"*",
"*",
"kwargs",
")",
":",
"# Note we don't verify the validity of the options. lcb does that for",
"# us.",
"sdflags",
"=",
"kwargs",
".",
"pop",
"(",
"'_sd_doc_flags'",
",",
"0",
")",
"if"... | Perform multiple atomic modifications within a document.
:param key: The key of the document to modify
:param specs: A list of specs (See :mod:`.couchbase.subdocument`)
:param bool create_doc:
Whether the document should be create if it doesn't exist
:param bool insert_doc: If the document should be created anew, and the
operations performed *only* if it does not exist.
:param bool upsert_doc: If the document should be created anew if it
does not exist. If it does exist the commands are still executed.
:param kwargs: CAS, etc.
:return: A :class:`~.couchbase.result.SubdocResult` object.
Here's an example of adding a new tag to a "user" document
and incrementing a modification counter::
import couchbase.subdocument as SD
# ....
cb.mutate_in('user',
SD.array_addunique('tags', 'dog'),
SD.counter('updates', 1))
.. note::
The `insert_doc` and `upsert_doc` options are mutually exclusive.
Use `insert_doc` when you wish to create a new document with
extended attributes (xattrs).
.. seealso:: :mod:`.couchbase.subdocument` | [
"Perform",
"multiple",
"atomic",
"modifications",
"within",
"a",
"document",
"."
] | python | train |
sanger-pathogens/circlator | circlator/merge.py | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/merge.py#L451-L473 | def _orientation_ok_to_bridge_contigs(self, start_hit, end_hit):
'''Returns True iff the orientation of the hits means that the query contig of both hits can bridge the reference contigs of the hits'''
assert start_hit.qry_name == end_hit.qry_name
if start_hit.ref_name == end_hit.ref_name:
return False
if (
(self._is_at_ref_end(start_hit) and start_hit.on_same_strand())
or (self._is_at_ref_start(start_hit) and not start_hit.on_same_strand())
):
start_hit_ok = True
else:
start_hit_ok = False
if (
(self._is_at_ref_start(end_hit) and end_hit.on_same_strand())
or (self._is_at_ref_end(end_hit) and not end_hit.on_same_strand())
):
end_hit_ok = True
else:
end_hit_ok = False
return start_hit_ok and end_hit_ok | [
"def",
"_orientation_ok_to_bridge_contigs",
"(",
"self",
",",
"start_hit",
",",
"end_hit",
")",
":",
"assert",
"start_hit",
".",
"qry_name",
"==",
"end_hit",
".",
"qry_name",
"if",
"start_hit",
".",
"ref_name",
"==",
"end_hit",
".",
"ref_name",
":",
"return",
... | Returns True iff the orientation of the hits means that the query contig of both hits can bridge the reference contigs of the hits | [
"Returns",
"True",
"iff",
"the",
"orientation",
"of",
"the",
"hits",
"means",
"that",
"the",
"query",
"contig",
"of",
"both",
"hits",
"can",
"bridge",
"the",
"reference",
"contigs",
"of",
"the",
"hits"
] | python | train |
fhamborg/news-please | newsplease/pipeline/extractor/article_extractor.py | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/article_extractor.py#L43-L66 | def extract(self, item):
"""Runs the HTML-response trough a list of initialized extractors, a cleaner and compares the results.
:param item: NewscrawlerItem to be processed.
:return: An updated NewscrawlerItem including the results of the extraction
"""
article_candidates = []
for extractor in self.extractor_list:
article_candidates.append(extractor.extract(item))
article_candidates = self.cleaner.clean(article_candidates)
article = self.comparer.compare(item, article_candidates)
item['article_title'] = article.title
item['article_description'] = article.description
item['article_text'] = article.text
item['article_image'] = article.topimage
item['article_author'] = article.author
item['article_publish_date'] = article.publish_date
item['article_language'] = article.language
return item | [
"def",
"extract",
"(",
"self",
",",
"item",
")",
":",
"article_candidates",
"=",
"[",
"]",
"for",
"extractor",
"in",
"self",
".",
"extractor_list",
":",
"article_candidates",
".",
"append",
"(",
"extractor",
".",
"extract",
"(",
"item",
")",
")",
"article_... | Runs the HTML-response trough a list of initialized extractors, a cleaner and compares the results.
:param item: NewscrawlerItem to be processed.
:return: An updated NewscrawlerItem including the results of the extraction | [
"Runs",
"the",
"HTML",
"-",
"response",
"trough",
"a",
"list",
"of",
"initialized",
"extractors",
"a",
"cleaner",
"and",
"compares",
"the",
"results",
"."
] | python | train |
linkhub-sdk/popbill.py | popbill/statementService.py | https://github.com/linkhub-sdk/popbill.py/blob/68a0dd7f7a937603318e93be321fde73c50b96cc/popbill/statementService.py#L326-L344 | def getInfo(self, CorpNum, ItemCode, MgtKey):
""" 상태/요약 정보 확인
args
CorpNum : 팝빌회원 사업자번호
ItemCode : 명세서 종류 코드
[121 - 거래명세서], [122 - 청구서], [123 - 견적서],
[124 - 발주서], [125 - 입금표], [126 - 영수증]
MgtKey : 파트너 문서관리번호
return
문서 상태/요약정보 object
raise
PopbillException
"""
if MgtKey == None or MgtKey == "":
raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")
if ItemCode == None or ItemCode == "":
raise PopbillException(-99999999, "명세서 종류 코드가 입력되지 않았습니다.")
return self._httpget('/Statement/' + str(ItemCode) + '/' + MgtKey, CorpNum) | [
"def",
"getInfo",
"(",
"self",
",",
"CorpNum",
",",
"ItemCode",
",",
"MgtKey",
")",
":",
"if",
"MgtKey",
"==",
"None",
"or",
"MgtKey",
"==",
"\"\"",
":",
"raise",
"PopbillException",
"(",
"-",
"99999999",
",",
"\"관리번호가 입력되지 않았습니다.\")\r",
"",
"if",
"ItemCod... | 상태/요약 정보 확인
args
CorpNum : 팝빌회원 사업자번호
ItemCode : 명세서 종류 코드
[121 - 거래명세서], [122 - 청구서], [123 - 견적서],
[124 - 발주서], [125 - 입금표], [126 - 영수증]
MgtKey : 파트너 문서관리번호
return
문서 상태/요약정보 object
raise
PopbillException | [
"상태",
"/",
"요약",
"정보",
"확인",
"args",
"CorpNum",
":",
"팝빌회원",
"사업자번호",
"ItemCode",
":",
"명세서",
"종류",
"코드",
"[",
"121",
"-",
"거래명세서",
"]",
"[",
"122",
"-",
"청구서",
"]",
"[",
"123",
"-",
"견적서",
"]",
"[",
"124",
"-",
"발주서",
"]",
"[",
"125",
"-",
... | python | train |
erocarrera/pefile | pefile.py | https://github.com/erocarrera/pefile/blob/8a78a2e251a3f2336c232bf411133927b479edf2/pefile.py#L5166-L5168 | def set_dword_at_rva(self, rva, dword):
"""Set the double word value at the file offset corresponding to the given RVA."""
return self.set_bytes_at_rva(rva, self.get_data_from_dword(dword)) | [
"def",
"set_dword_at_rva",
"(",
"self",
",",
"rva",
",",
"dword",
")",
":",
"return",
"self",
".",
"set_bytes_at_rva",
"(",
"rva",
",",
"self",
".",
"get_data_from_dword",
"(",
"dword",
")",
")"
] | Set the double word value at the file offset corresponding to the given RVA. | [
"Set",
"the",
"double",
"word",
"value",
"at",
"the",
"file",
"offset",
"corresponding",
"to",
"the",
"given",
"RVA",
"."
] | python | train |
ahawker/ulid | ulid/api.py | https://github.com/ahawker/ulid/blob/f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f/ulid/api.py#L35-L47 | def new() -> ulid.ULID:
"""
Create a new :class:`~ulid.ulid.ULID` instance.
The timestamp is created from :func:`~time.time`.
The randomness is created from :func:`~os.urandom`.
:return: ULID from current timestamp
:rtype: :class:`~ulid.ulid.ULID`
"""
timestamp = int(time.time() * 1000).to_bytes(6, byteorder='big')
randomness = os.urandom(10)
return ulid.ULID(timestamp + randomness) | [
"def",
"new",
"(",
")",
"->",
"ulid",
".",
"ULID",
":",
"timestamp",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
"*",
"1000",
")",
".",
"to_bytes",
"(",
"6",
",",
"byteorder",
"=",
"'big'",
")",
"randomness",
"=",
"os",
".",
"urandom",
"(",
... | Create a new :class:`~ulid.ulid.ULID` instance.
The timestamp is created from :func:`~time.time`.
The randomness is created from :func:`~os.urandom`.
:return: ULID from current timestamp
:rtype: :class:`~ulid.ulid.ULID` | [
"Create",
"a",
"new",
":",
"class",
":",
"~ulid",
".",
"ulid",
".",
"ULID",
"instance",
"."
] | python | train |
django-admin-tools/django-admin-tools | admin_tools/template_loaders.py | https://github.com/django-admin-tools/django-admin-tools/blob/ba6f46f51ebd84fcf84f2f79ec9487f45452d79b/admin_tools/template_loaders.py#L23-L38 | def get_app_template_dir(app_name):
"""Get the template directory for an application
Uses apps interface available in django 1.7+
Returns a full path, or None if the app was not found.
"""
if app_name in _cache:
return _cache[app_name]
template_dir = None
for app in apps.get_app_configs():
if app.label == app_name:
template_dir = join(app.path, 'templates')
break
_cache[app_name] = template_dir
return template_dir | [
"def",
"get_app_template_dir",
"(",
"app_name",
")",
":",
"if",
"app_name",
"in",
"_cache",
":",
"return",
"_cache",
"[",
"app_name",
"]",
"template_dir",
"=",
"None",
"for",
"app",
"in",
"apps",
".",
"get_app_configs",
"(",
")",
":",
"if",
"app",
".",
"... | Get the template directory for an application
Uses apps interface available in django 1.7+
Returns a full path, or None if the app was not found. | [
"Get",
"the",
"template",
"directory",
"for",
"an",
"application"
] | python | train |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_fabric_service.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_fabric_service.py#L841-L855 | def show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_member_trunk_list_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_fabric_trunk_info = ET.Element("show_fabric_trunk_info")
config = show_fabric_trunk_info
output = ET.SubElement(show_fabric_trunk_info, "output")
show_trunk_list = ET.SubElement(output, "show-trunk-list")
trunk_list_groups = ET.SubElement(show_trunk_list, "trunk-list-groups")
trunk_list_member = ET.SubElement(trunk_list_groups, "trunk-list-member")
trunk_list_interface_type = ET.SubElement(trunk_list_member, "trunk-list-interface-type")
trunk_list_interface_type.text = kwargs.pop('trunk_list_interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config) | [
"def",
"show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_member_trunk_list_interface_type",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"show_fabric_trunk_info",
"=",
"ET",
".",
"El... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
PMEAL/OpenPNM | openpnm/algorithms/TransientReactiveTransport.py | https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/algorithms/TransientReactiveTransport.py#L197-L223 | def _t_update_b(self):
r"""
A method to update 'b' array at each time step according to
't_scheme' and the source term value
"""
network = self.project.network
phase = self.project.phases()[self.settings['phase']]
Vi = network['pore.volume']
dt = self.settings['t_step']
s = self.settings['t_scheme']
if (s == 'implicit'):
f1, f2, f3 = 1, 1, 0
elif (s == 'cranknicolson'):
f1, f2, f3 = 0.5, 1, 0
elif (s == 'steady'):
f1, f2, f3 = 1, 0, 1
x_old = self[self.settings['quantity']]
b = (f2*(1-f1)*(-self._A_steady)*x_old +
f2*(Vi/dt)*x_old +
f3*np.zeros(shape=(self.Np, ), dtype=float))
self._update_physics()
for item in self.settings['sources']:
Ps = self.pores(item)
# Update b
b[Ps] = b[Ps] - f2*(1-f1)*(phase[item+'.'+'rate'][Ps])
self._b = b
return b | [
"def",
"_t_update_b",
"(",
"self",
")",
":",
"network",
"=",
"self",
".",
"project",
".",
"network",
"phase",
"=",
"self",
".",
"project",
".",
"phases",
"(",
")",
"[",
"self",
".",
"settings",
"[",
"'phase'",
"]",
"]",
"Vi",
"=",
"network",
"[",
"... | r"""
A method to update 'b' array at each time step according to
't_scheme' and the source term value | [
"r",
"A",
"method",
"to",
"update",
"b",
"array",
"at",
"each",
"time",
"step",
"according",
"to",
"t_scheme",
"and",
"the",
"source",
"term",
"value"
] | python | train |
mjj4791/python-buienradar | buienradar/buienradar_json.py | https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L309-L344 | def __parse_ws_data(jsondata, latitude=52.091579, longitude=5.119734):
"""Parse the buienradar json and rain data."""
log.info("Parse ws data: latitude: %s, longitude: %s", latitude, longitude)
result = {SUCCESS: False, MESSAGE: None, DATA: None}
# select the nearest weather station
loc_data = __select_nearest_ws(jsondata, latitude, longitude)
# process current weather data from selected weatherstation
if not loc_data:
result[MESSAGE] = 'No location selected.'
return result
if not __is_valid(loc_data):
result[MESSAGE] = 'Location data is invalid.'
return result
# add distance to weatherstation
log.debug("Raw location data: %s", loc_data)
result[DISTANCE] = __get_ws_distance(loc_data, latitude, longitude)
result = __parse_loc_data(loc_data, result)
# extract weather forecast
try:
fc_data = jsondata[__FORECAST][__FIVEDAYFORECAST]
except (json.JSONDecodeError, KeyError):
result[MESSAGE] = 'Unable to extract forecast data.'
log.exception(result[MESSAGE])
return result
if fc_data:
# result = __parse_fc_data(fc_data, result)
log.debug("Raw forecast data: %s", fc_data)
# pylint: disable=unsupported-assignment-operation
result[DATA][FORECAST] = __parse_fc_data(fc_data)
return result | [
"def",
"__parse_ws_data",
"(",
"jsondata",
",",
"latitude",
"=",
"52.091579",
",",
"longitude",
"=",
"5.119734",
")",
":",
"log",
".",
"info",
"(",
"\"Parse ws data: latitude: %s, longitude: %s\"",
",",
"latitude",
",",
"longitude",
")",
"result",
"=",
"{",
"SUC... | Parse the buienradar json and rain data. | [
"Parse",
"the",
"buienradar",
"json",
"and",
"rain",
"data",
"."
] | python | train |
tensorflow/probability | tensorflow_probability/python/distributions/joint_distribution_sequential.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/joint_distribution_sequential.py#L492-L523 | def _kl_joint_joint(d0, d1, name=None):
"""Calculate the KL divergence between two `JointDistributionSequential`s.
Args:
d0: instance of a `JointDistributionSequential` object.
d1: instance of a `JointDistributionSequential` object.
name: (optional) Name to use for created operations.
Default value: `"kl_joint_joint"`.
Returns:
kl_joint_joint: `Tensor` The sum of KL divergences between elemental
distributions of two joint distributions.
Raises:
ValueError: when joint distributions have a different number of elemental
distributions.
ValueError: when either joint distribution has a distribution with dynamic
dependency, i.e., when either joint distribution is not a collection of
independent distributions.
"""
if len(d0._dist_fn_wrapped) != len(d1._dist_fn_wrapped): # pylint: disable=protected-access
raise ValueError(
'Can only compute KL divergence between when each has the'
'same number of component distributions.')
if (not all(a is None for a in d0._dist_fn_args) or # pylint: disable=protected-access
not all(a is None for a in d1._dist_fn_args)): # pylint: disable=protected-access
raise ValueError(
'Can only compute KL divergence when all distributions are '
'independent.')
with tf.name_scope(name or 'kl_jointseq_jointseq'):
return sum(kullback_leibler.kl_divergence(d0_(), d1_())
for d0_, d1_ in zip(d0._dist_fn_wrapped, d1._dist_fn_wrapped)) | [
"def",
"_kl_joint_joint",
"(",
"d0",
",",
"d1",
",",
"name",
"=",
"None",
")",
":",
"if",
"len",
"(",
"d0",
".",
"_dist_fn_wrapped",
")",
"!=",
"len",
"(",
"d1",
".",
"_dist_fn_wrapped",
")",
":",
"# pylint: disable=protected-access",
"raise",
"ValueError",
... | Calculate the KL divergence between two `JointDistributionSequential`s.
Args:
d0: instance of a `JointDistributionSequential` object.
d1: instance of a `JointDistributionSequential` object.
name: (optional) Name to use for created operations.
Default value: `"kl_joint_joint"`.
Returns:
kl_joint_joint: `Tensor` The sum of KL divergences between elemental
distributions of two joint distributions.
Raises:
ValueError: when joint distributions have a different number of elemental
distributions.
ValueError: when either joint distribution has a distribution with dynamic
dependency, i.e., when either joint distribution is not a collection of
independent distributions. | [
"Calculate",
"the",
"KL",
"divergence",
"between",
"two",
"JointDistributionSequential",
"s",
"."
] | python | test |
RaRe-Technologies/gensim-simserver | simserver/simserver.py | https://github.com/RaRe-Technologies/gensim-simserver/blob/e7e59e836ef6d9da019a8c6b218ef0bdd998b2da/simserver/simserver.py#L140-L151 | def index_documents(self, fresh_docs, model):
"""
Update fresh index with new documents (potentially replacing old ones with
the same id). `fresh_docs` is a dictionary-like object (=dict, sqlitedict, shelve etc)
that maps document_id->document.
"""
docids = fresh_docs.keys()
vectors = (model.docs2vecs(fresh_docs[docid] for docid in docids))
logger.info("adding %i documents to %s" % (len(docids), self))
self.qindex.add_documents(vectors)
self.qindex.save()
self.update_ids(docids) | [
"def",
"index_documents",
"(",
"self",
",",
"fresh_docs",
",",
"model",
")",
":",
"docids",
"=",
"fresh_docs",
".",
"keys",
"(",
")",
"vectors",
"=",
"(",
"model",
".",
"docs2vecs",
"(",
"fresh_docs",
"[",
"docid",
"]",
"for",
"docid",
"in",
"docids",
... | Update fresh index with new documents (potentially replacing old ones with
the same id). `fresh_docs` is a dictionary-like object (=dict, sqlitedict, shelve etc)
that maps document_id->document. | [
"Update",
"fresh",
"index",
"with",
"new",
"documents",
"(",
"potentially",
"replacing",
"old",
"ones",
"with",
"the",
"same",
"id",
")",
".",
"fresh_docs",
"is",
"a",
"dictionary",
"-",
"like",
"object",
"(",
"=",
"dict",
"sqlitedict",
"shelve",
"etc",
")... | python | train |
marshmallow-code/apispec | src/apispec/core.py | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/core.py#L200-L213 | def security_scheme(self, component_id, component):
"""Add a security scheme which can be referenced.
:param str component_id: component_id to use as reference
:param dict kwargs: security scheme fields
"""
if component_id in self._security_schemes:
raise DuplicateComponentNameError(
'Another security scheme with name "{}" is already registered.'.format(
component_id
)
)
self._security_schemes[component_id] = component
return self | [
"def",
"security_scheme",
"(",
"self",
",",
"component_id",
",",
"component",
")",
":",
"if",
"component_id",
"in",
"self",
".",
"_security_schemes",
":",
"raise",
"DuplicateComponentNameError",
"(",
"'Another security scheme with name \"{}\" is already registered.'",
".",
... | Add a security scheme which can be referenced.
:param str component_id: component_id to use as reference
:param dict kwargs: security scheme fields | [
"Add",
"a",
"security",
"scheme",
"which",
"can",
"be",
"referenced",
"."
] | python | train |
matousc89/padasip | padasip/filters/base_filter.py | https://github.com/matousc89/padasip/blob/c969eadd7fa181a84da0554d737fc13c6450d16f/padasip/filters/base_filter.py#L112-L168 | def explore_learning(self, d, x, mu_start=0, mu_end=1., steps=100,
ntrain=0.5, epochs=1, criteria="MSE", target_w=False):
"""
Test what learning rate is the best.
**Args:**
* `d` : desired value (1 dimensional array)
* `x` : input matrix (2-dimensional array). Rows are samples,
columns are input arrays.
**Kwargs:**
* `mu_start` : starting learning rate (float)
* `mu_end` : final learning rate (float)
* `steps` : how many learning rates should be tested between `mu_start`
and `mu_end`.
* `ntrain` : train to test ratio (float), default value is 0.5
(that means 50% of data is used for training)
* `epochs` : number of training epochs (int), default value is 1.
This number describes how many times the training will be repeated
on dedicated part of data.
* `criteria` : how should be measured the mean error (str),
default value is "MSE".
* `target_w` : target weights (str or 1d array), default value is False.
If False, the mean error is estimated from prediction error.
If an array is provided, the error between weights and `target_w`
is used.
**Returns:**
* `errors` : mean error for tested learning rates (1 dimensional array).
* `mu_range` : range of used learning rates (1d array). Every value
corresponds with one value from `errors`
"""
mu_range = np.linspace(mu_start, mu_end, steps)
errors = np.zeros(len(mu_range))
for i, mu in enumerate(mu_range):
# init
self.init_weights("zeros")
self.mu = mu
# run
y, e, w = self.pretrained_run(d, x, ntrain=ntrain, epochs=epochs)
if type(target_w) != bool:
errors[i] = get_mean_error(w[-1]-target_w, function=criteria)
else:
errors[i] = get_mean_error(e, function=criteria)
return errors, mu_range | [
"def",
"explore_learning",
"(",
"self",
",",
"d",
",",
"x",
",",
"mu_start",
"=",
"0",
",",
"mu_end",
"=",
"1.",
",",
"steps",
"=",
"100",
",",
"ntrain",
"=",
"0.5",
",",
"epochs",
"=",
"1",
",",
"criteria",
"=",
"\"MSE\"",
",",
"target_w",
"=",
... | Test what learning rate is the best.
**Args:**
* `d` : desired value (1 dimensional array)
* `x` : input matrix (2-dimensional array). Rows are samples,
columns are input arrays.
**Kwargs:**
* `mu_start` : starting learning rate (float)
* `mu_end` : final learning rate (float)
* `steps` : how many learning rates should be tested between `mu_start`
and `mu_end`.
* `ntrain` : train to test ratio (float), default value is 0.5
(that means 50% of data is used for training)
* `epochs` : number of training epochs (int), default value is 1.
This number describes how many times the training will be repeated
on dedicated part of data.
* `criteria` : how should be measured the mean error (str),
default value is "MSE".
* `target_w` : target weights (str or 1d array), default value is False.
If False, the mean error is estimated from prediction error.
If an array is provided, the error between weights and `target_w`
is used.
**Returns:**
* `errors` : mean error for tested learning rates (1 dimensional array).
* `mu_range` : range of used learning rates (1d array). Every value
corresponds with one value from `errors` | [
"Test",
"what",
"learning",
"rate",
"is",
"the",
"best",
"."
] | python | train |
Apitax/Apitax | apitax/api/controllers/migrations/users_controller.py | https://github.com/Apitax/Apitax/blob/3883e45f17e01eba4edac9d1bba42f0e7a748682/apitax/api/controllers/migrations/users_controller.py#L152-L164 | def script_catalog(): # noqa: E501
"""Retrieve the script catalog
Retrieve the script catalog # noqa: E501
:rtype: Response
"""
if (not hasAccess()):
return redirectUnauthorized()
driver = LoadedDrivers.getDefaultDriver()
return Response(status=200, body=driver.getScriptsCatalog()) | [
"def",
"script_catalog",
"(",
")",
":",
"# noqa: E501",
"if",
"(",
"not",
"hasAccess",
"(",
")",
")",
":",
"return",
"redirectUnauthorized",
"(",
")",
"driver",
"=",
"LoadedDrivers",
".",
"getDefaultDriver",
"(",
")",
"return",
"Response",
"(",
"status",
"="... | Retrieve the script catalog
Retrieve the script catalog # noqa: E501
:rtype: Response | [
"Retrieve",
"the",
"script",
"catalog"
] | python | train |
google/pybadges | pybadges/precalculate_text.py | https://github.com/google/pybadges/blob/d42c8080adb21b81123ac9540c53127ed2fa1edc/pybadges/precalculate_text.py#L87-L105 | def calculate_character_to_length_mapping(
measurer: text_measurer.TextMeasurer,
characters: Iterable[str]) -> Mapping[str, float]:
"""Return a mapping between each given character and its length.
Args:
measurer: The TextMeasurer used to measure the width of the text in
pixels.
characters: The characters to measure e.g. "ml".
Returns:
A mapping from the given characters to their length in pixels, as
determined by 'measurer' e.g. {'m': 5.2, 'l', 1.2}.
"""
char_to_length = {}
for c in characters:
char_to_length[c] = measurer.text_width(c)
return char_to_length | [
"def",
"calculate_character_to_length_mapping",
"(",
"measurer",
":",
"text_measurer",
".",
"TextMeasurer",
",",
"characters",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"Mapping",
"[",
"str",
",",
"float",
"]",
":",
"char_to_length",
"=",
"{",
"}",
"for",
... | Return a mapping between each given character and its length.
Args:
measurer: The TextMeasurer used to measure the width of the text in
pixels.
characters: The characters to measure e.g. "ml".
Returns:
A mapping from the given characters to their length in pixels, as
determined by 'measurer' e.g. {'m': 5.2, 'l', 1.2}. | [
"Return",
"a",
"mapping",
"between",
"each",
"given",
"character",
"and",
"its",
"length",
"."
] | python | test |
pavoni/pyvera | pyvera/__init__.py | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L730-L739 | def is_switched_on(self, refresh=False):
"""Get dimmer state.
Refresh data from Vera if refresh is True,
otherwise use local cache. Refresh is only needed if you're
not using subscriptions.
"""
if refresh:
self.refresh()
return self.get_brightness(refresh) > 0 | [
"def",
"is_switched_on",
"(",
"self",
",",
"refresh",
"=",
"False",
")",
":",
"if",
"refresh",
":",
"self",
".",
"refresh",
"(",
")",
"return",
"self",
".",
"get_brightness",
"(",
"refresh",
")",
">",
"0"
] | Get dimmer state.
Refresh data from Vera if refresh is True,
otherwise use local cache. Refresh is only needed if you're
not using subscriptions. | [
"Get",
"dimmer",
"state",
"."
] | python | train |
scailer/django-social-publisher | social_publisher/backends/ok.py | https://github.com/scailer/django-social-publisher/blob/7fc0ea28fc9e4ecf0e95617fc2d1f89a90fca087/social_publisher/backends/ok.py#L21-L33 | def get_api_publisher(self, social_user):
"""
and other https://vk.com/dev.php?method=wall.post
"""
def _post(**kwargs):
api = self.get_api(social_user)
from pudb import set_trace; set_trace()
# api.group.getInfo('uids'='your_group_id', 'fields'='members_count')
#response = api.wall.post(**kwargs)
return response
return _post | [
"def",
"get_api_publisher",
"(",
"self",
",",
"social_user",
")",
":",
"def",
"_post",
"(",
"*",
"*",
"kwargs",
")",
":",
"api",
"=",
"self",
".",
"get_api",
"(",
"social_user",
")",
"from",
"pudb",
"import",
"set_trace",
"set_trace",
"(",
")",
"# api.gr... | and other https://vk.com/dev.php?method=wall.post | [
"and",
"other",
"https",
":",
"//",
"vk",
".",
"com",
"/",
"dev",
".",
"php?method",
"=",
"wall",
".",
"post"
] | python | train |
oscarlazoarjona/fast | build/lib/fast/electric_field.py | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/electric_field.py#L374-L393 | def electric_field_amplitude_intensity(s0,Omega=1.0e6):
'''This function returns the value of E0 (the amplitude of the electric field)
at a given saturation parameter s0=I/I0, where I0=2.50399 mW/cm^2 is the
saturation intensity of the D2 line of Rubidium for linearly polarized light.'''
e0=hbar*Omega/(e*a0) #This is the electric field scale.
I0=2.50399 #mW/cm^2
I0=1.66889451102868 #mW/cm^2
I0=I0/1000*(100**2) #W/m^2
r_ciclic=4.226983616875483 #a0
gamma_D2=2*Pi*6.065e6/Omega # The decay frequency of the D2 line.
E0_sat=gamma_D2/r_ciclic/sqrt(2.0)
E0_sat=E0_sat*e0
I0=E0_sat**2/2/c/mu0
#return sqrt(c*mu0*s0*I0/2)/e0
#return sqrt(c*mu0*s0*I0)/e0
return sqrt(2*c*mu0*s0*I0)/e0 | [
"def",
"electric_field_amplitude_intensity",
"(",
"s0",
",",
"Omega",
"=",
"1.0e6",
")",
":",
"e0",
"=",
"hbar",
"*",
"Omega",
"/",
"(",
"e",
"*",
"a0",
")",
"#This is the electric field scale.\r",
"I0",
"=",
"2.50399",
"#mW/cm^2\r",
"I0",
"=",
"1.668894511028... | This function returns the value of E0 (the amplitude of the electric field)
at a given saturation parameter s0=I/I0, where I0=2.50399 mW/cm^2 is the
saturation intensity of the D2 line of Rubidium for linearly polarized light. | [
"This",
"function",
"returns",
"the",
"value",
"of",
"E0",
"(",
"the",
"amplitude",
"of",
"the",
"electric",
"field",
")",
"at",
"a",
"given",
"saturation",
"parameter",
"s0",
"=",
"I",
"/",
"I0",
"where",
"I0",
"=",
"2",
".",
"50399",
"mW",
"/",
"cm... | python | train |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py#L287-L302 | def overlay_gateway_site_tunnel_dst_address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
name_key = ET.SubElement(overlay_gateway, "name")
name_key.text = kwargs.pop('name')
site = ET.SubElement(overlay_gateway, "site")
name_key = ET.SubElement(site, "name")
name_key.text = kwargs.pop('name')
tunnel_dst = ET.SubElement(site, "tunnel-dst")
address = ET.SubElement(tunnel_dst, "address")
address.text = kwargs.pop('address')
callback = kwargs.pop('callback', self._callback)
return callback(config) | [
"def",
"overlay_gateway_site_tunnel_dst_address",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"overlay_gateway",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"overlay-gateway\"",
",",
"xml... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.