content
stringlengths 22
815k
| id
int64 0
4.91M
|
---|---|
def macd_cross_func_pd(data):
"""
神一样的指标:MACD
"""
if (ST.VERBOSE in data.columns):
print('Phase macd_cross_func', QA_util_timestamp_to_str())
MACD = QA.QA_indicator_MACD(data)
MACD_CROSS = pd.DataFrame(columns=[ST.MACD_CROSS,
FLD.MACD_CROSS_JX_BEFORE,
FLD.MACD_CROSS_SX_BEFORE,
FLD.NEGATIVE_LOWER_PRICE,
FLD.NEGATIVE_LOWER_PRICE_BEFORE,
FLD.LOWER_SETTLE_PRICE,
FLD.LOWER_SETTLE_PRICE_BEFORE,
FLD.HIGHER_SETTLE_PRICE,
FLD.HIGHER_SETTLE_PRICE_BEFORE],
index=data.index)
MACD_CROSS = MACD_CROSS.assign(DIF=MACD[FLD.DIF])
MACD_CROSS = MACD_CROSS.assign(DEA=MACD[FLD.DEA])
MACD_CROSS = MACD_CROSS.assign(MACD=MACD[FLD.MACD])
MACD_CROSS = MACD_CROSS.assign(ZERO=0)
# 新版考虑合并指标,将 DELTA 重命名为 MACD_DELTA
MACD_CROSS = MACD_CROSS.assign(MACD_DELTA=MACD[FLD.MACD].diff())
MACD_CROSS[FLD.MACD_CROSS_JX_BEFORE] = CROSS(MACD_CROSS[FLD.DIF],
MACD_CROSS[FLD.DEA])
MACD_CROSS[FLD.MACD_CROSS_SX_BEFORE] = CROSS(MACD_CROSS[FLD.DEA],
MACD_CROSS[FLD.DIF])
MACD_CROSS[ST.MACD_CROSS] = np.where(MACD_CROSS[FLD.MACD_CROSS_JX_BEFORE] == 1, 1,
np.where(MACD_CROSS[FLD.MACD_CROSS_SX_BEFORE] == 1,
-1, 0))
MACD_CROSS[FLD.DEA_CROSS_JX_BEFORE] = Timeline_duration(CROSS(MACD_CROSS[FLD.DEA],
MACD_CROSS[FLD.ZERO]).values)
MACD_CROSS[FLD.DIF_CROSS_JX_BEFORE] = Timeline_duration(CROSS(MACD_CROSS[FLD.DIF],
MACD_CROSS[FLD.ZERO]).values)
MACD_CROSS[FLD.DEA_CROSS_SX_BEFORE] = Timeline_duration(CROSS(MACD_CROSS[FLD.ZERO],
MACD_CROSS[FLD.DEA]).values)
MACD_CROSS[FLD.MACD_CROSS_JX_BEFORE] = Timeline_duration(MACD_CROSS[FLD.MACD_CROSS_JX_BEFORE].values)
MACD_CROSS[FLD.MACD_CROSS_SX_BEFORE] = Timeline_duration(MACD_CROSS[FLD.MACD_CROSS_SX_BEFORE].values)
MACD_CROSS[FLD.DEA_SLOPE] = talib.LINEARREG_SLOPE(MACD[FLD.DEA], timeperiod=14)
MACD_CROSS['MACD_TIDE_MEDIAN'] = int(min(MACD_CROSS[FLD.MACD_CROSS_JX_BEFORE].median(),
MACD_CROSS[FLD.MACD_CROSS_SX_BEFORE].median()))
MACD_CROSS[FLD.DEA_SLOPE_UB] = MACD_CROSS[FLD.DEA_SLOPE].abs().rolling(MACD_CROSS['MACD_TIDE_MEDIAN'].max()).median()
negative_lower_price_state = (MACD_CROSS[FLD.MACD] < 0) & \
(MACD_CROSS[FLD.DEA] < 0) & \
(MACD_CROSS[FLD.MACD] < MACD_CROSS[FLD.DEA])
negative_lower_price_state = (negative_lower_price_state == True) | \
(MACD_CROSS[FLD.MACD] < 0) & \
(((MACD_CROSS[FLD.DEA] < 0) & \
((MACD_CROSS[FLD.DEA_CROSS_SX_BEFORE] > 6) | \
(MACD_CROSS[FLD.MACD_CROSS_SX_BEFORE] > 12))) | \
((MACD_CROSS[FLD.DIF] < 0) & \
(MACD_CROSS[FLD.MACD_CROSS_SX_BEFORE] > 12))) & \
(MACD_CROSS[FLD.MACD] < MACD_CROSS[FLD.DEA]) & \
(abs(MACD_CROSS[FLD.MACD]) > abs(MACD_CROSS[FLD.DEA]))
MACD_CROSS[FLD.NEGATIVE_LOWER_PRICE] = negative_lower_price_state.apply(int)
MACD_CROSS[FLD.NEGATIVE_LOWER_PRICE_BEFORE] = Timeline_duration(MACD_CROSS[FLD.NEGATIVE_LOWER_PRICE].values)
lower_settle_price_state = ~(negative_lower_price_state == True) & \
(MACD_CROSS[FLD.DEA] < 0) & \
(MACD_CROSS[FLD.MACD_DELTA] > 0)
MACD_CROSS[FLD.LOWER_SETTLE_PRICE] = lower_settle_price_state.apply(int)
MACD_CROSS[FLD.LOWER_SETTLE_PRICE_BEFORE] = Timeline_duration(MACD_CROSS[FLD.LOWER_SETTLE_PRICE].values)
higher_settle_price_state = (MACD_CROSS[FLD.DEA] > 0) & \
(MACD_CROSS[FLD.MACD] > MACD_CROSS[FLD.DEA])
MACD_CROSS[FLD.HIGHER_SETTLE_PRICE] = higher_settle_price_state.apply(int)
MACD_CROSS[FLD.HIGHER_SETTLE_PRICE_BEFORE] = Timeline_duration(MACD_CROSS[FLD.HIGHER_SETTLE_PRICE].values)
return MACD_CROSS
| 5,345,300 |
def jsonp_response(data, callback="f", status=200, serializer=None):
"""
Returns an HttpResponse object containing JSON serialized data,
wrapped in a JSONP callback.
The mime-type is set to application/x-javascript, and the charset to UTF-8.
"""
val = json.dumps(data, default=serializer)
ret = "{callback}('{val}');".format(callback=callback, val=val)
return HttpResponse(ret,
status=status,
content_type='application/x-javascript; charset=UTF-8')
| 5,345,301 |
def enhance_bonds(bond_dataframe, structure_dict):
"""Enhance the bonds dataframe by including derived information.
Args:
bond_dataframe: Pandas dataframe read from train.csv or test.csv.
structure_dict: Output of :func:`make_structure_dict`, after running :func:`enhance_structure_dict`.
Returns:
pandas.DataFrame: Same dataframe, modified in-place, with derived information added.
"""
bond_dataframe.sort_values(['molecule_name', 'atom_index_0', 'atom_index_1'], inplace=True)
assert int(bond_dataframe.groupby("molecule_name").count().max()[0]) <= MAX_BOND_COUNT
new_columns = collections.defaultdict(list)
for index, row in bond_dataframe.iterrows():
molecule_name, iatom0, iatom1 = row['molecule_name'], row['atom_index_0'], row['atom_index_1']
if 'predict' not in structure_dict[molecule_name]:
structure_dict[molecule_name]['predict'] = structure_dict[molecule_name]['bond_orders'] * 0
structure_dict[molecule_name]['predict'][iatom0, iatom1] = 1
structure_dict[molecule_name]['predict'][iatom1, iatom0] = 1
long_symbols = [structure_dict[molecule_name]['long_symbols'][x] for x in [iatom0, iatom1]]
# labeled_type
if all([x[0] == 'H' for x in long_symbols]):
lt = row['type']
elif not any([x[0] == 'H' for x in long_symbols]):
raise ValueError("No hydrogen found in {}".format(row))
else:
ls = [x for x in long_symbols if x[0] != 'H'][0]
lt = row["type"] + ls[1:].replace('.0', '')
if lt in classification_corrections:
lt = classification_corrections[lt]
if lt in small_longtypes:
lt = lt.split('_')[0]
new_columns["labeled_type"].append(lt)
# sublabeled type
new_columns["sublabel_type"].append(row['type'] + '-' + '-'.join(sorted(long_symbols)))
# bond order
new_columns["bond_order"].append(structure_dict[molecule_name]['bond_orders'][iatom0, iatom1])
new_columns["predict"].append(1)
for key in new_columns:
bond_dataframe[key] = new_columns[key]
return bond_dataframe
| 5,345,302 |
def _tofloat(value):
"""Convert a parameter to float or float array"""
if isiterable(value):
try:
value = np.asanyarray(value, dtype=np.float)
except (TypeError, ValueError):
# catch arrays with strings or user errors like different
# types of parameters in a parameter set
raise InputParameterError(
"Parameter of {0} could not be converted to "
"float".format(type(value)))
elif isinstance(value, Quantity):
# Quantities are fine as is
pass
elif isinstance(value, np.ndarray):
# A scalar/dimensionless array
value = float(value.item())
elif isinstance(value, (numbers.Number, np.number)):
value = float(value)
elif isinstance(value, bool):
raise InputParameterError(
"Expected parameter to be of numerical type, not boolean")
else:
raise InputParameterError(
"Don't know how to convert parameter of {0} to "
"float".format(type(value)))
return value
| 5,345,303 |
def sp2mgc(sp, order=20, alpha=0.35, gamma=-0.41, miniter=2,
maxiter=30, criteria=0.001, otype=0, verbose=False):
"""
Accepts 1D or 2D one-sided spectrum (complex or real valued).
If 2D, assumes time is axis 0.
Returns mel generalized cepstral coefficients.
Based on r9y9 Julia code
https://github.com/r9y9/MelGeneralizedCepstrums.jl
"""
if len(sp.shape) == 1:
sp = np.concatenate((sp, sp[:, 1:][:, ::-1]), axis=0)
return _sp2mgc(sp, order=order, alpha=alpha, gamma=gamma,
miniter=miniter, maxiter=maxiter, criteria=criteria,
otype=otype, verbose=verbose)
else:
sp = np.concatenate((sp, sp[:, 1:][:, ::-1]), axis=1)
# Slooow, use multiprocessing to speed up a bit
# http://blog.shenwei.me/python-multiprocessing-pool-difference-between-map-apply-map_async-apply_async/
# http://stackoverflow.com/questions/5666576/show-the-progress-of-a-python-multiprocessing-pool-map-call
c = [(i + 1, sp.shape[0], sp[i]) for i in range(sp.shape[0])]
p = Pool()
start = time.time()
if verbose:
print("Starting conversion of %i frames" % sp.shape[0])
print("This may take some time...")
# takes ~360s for 630 frames, 1 process
itr = p.map_async(functools.partial(_sp_convert, order=order, alpha=alpha, gamma=gamma, miniter=miniter, maxiter=maxiter, criteria=criteria, otype=otype, verbose=False), c, callback=_sp_collect_result)
sz = len(c) // itr._chunksize
if (sz * itr._chunksize) != len(c):
sz += 1
last_remaining = None
while True:
remaining = itr._number_left
if verbose:
if remaining != last_remaining:
last_remaining = remaining
print("%i chunks of %i complete" % (sz - remaining, sz))
if itr.ready():
break
time.sleep(.5)
"""
# takes ~455s for 630 frames
itr = p.imap_unordered(functools.partial(_sp_convert, order=order, alpha=alpha, gamma=gamma, miniter=miniter, maxiter=maxiter, criteria=criteria, otype=otype, verbose=False), c)
res = []
# print ~every 5%
mod = int(len(c)) // 20
if mod < 1:
mod = 1
for i, res_i in enumerate(itr, 1):
res.append(res_i)
if i % mod == 0 or i == 1:
print("%i of %i complete" % (i, len(c)))
"""
p.close()
p.join()
stop = time.time()
if verbose:
print("Processed %i frames in %s seconds" % (sp.shape[0], stop - start))
# map_async result comes in chunks
flat = [a_i for a in _sp_convert_results for a_i in a]
final = [o[1] for o in sorted(flat, key=lambda x: x[0])]
for i in range(len(_sp_convert_results)):
_sp_convert_results.pop()
return np.array(final)
| 5,345,304 |
def has_prefix(sub_s):
"""
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid
:return: (bool) If there is any words with prefix stored in sub_s
"""
for key, val in word_dic.items():
if key.startswith(sub_s):
return True
else:
pass
return False
| 5,345,305 |
def _package_data(vec_f_image, vec_f_imageBscan3d, downscale_size, downscale_size_bscan, crop_size, num_octa,
str_angiography, str_structure, str_bscan, vec_str_layer, vec_str_layer_bscan3d, str_bscan_layer,
dict_layer_order, dict_layer_order_bscan3d):
"""
Organizes the angiography, OCT and b-scan images into a list of cubes for a single subject and also returns which
eye it is. Difference from function below: contains logic that deal with cases where there are two eyes
:param vec_f_image: list of absolute paths to individual images from a single subject
:param vec_f_imageBscan3d: list of absolute paths to individual bscan images from a single subject
:param downscale_size: desired final size of the loaded images, e.g. (256, 256)
:param downscale_size_bscan: desired final size of the loaded bscan images, e.g. (256, 256)
:param crop_size: desired number of pixels to exclude from analysis for bscan images, e.g. [50, 60]
:param num_octa: number of OCTA images per patient, e.g. 5
:param str_angiography: identifier for angiography images in the filename
:param str_structure: identifier for structural OCT images in the filename
:param str_bscan: identifier for b-scan OCT images in the filename
:param vec_str_layer: list of strings that contain the relevant layers to be used for training
:param vec_str_layer_bscan3d: list of strings that contain the relevant bscan images to be used for training
:param str_bscan_layer: string that contains the type of b-scan images to be used in filename, e.g. Flow
:param dict_layer_order: dictionary that contains the order in which the different layers will be organized
:param dict_layer_order_bscan3d: dictionary that contains the order in which the bscans cubes will be organized
:return: return a list in the form [packed_images, str_eye]. If both eyes are available, then each variable would
be a list of cubes and strings; if only one eye is available, packed_images would be a cube and str_eye would be
OD/OS; if nothing is available then both are None
"""
# Test if the dataset has data from both eyes
if any("/OD/" in s for s in vec_f_image) & any("/OS/" in s for s in vec_f_image):
vec_f_image_OD = [s for s in vec_f_image if "/OD/" in s]
vec_f_image_OS = [s for s in vec_f_image if "/OS/" in s]
vec_f_imageBscan3d_OD = [s for s in vec_f_imageBscan3d if "/OD/" in s]
vec_f_imageBscan3d_OS = [s for s in vec_f_imageBscan3d if "/OS/" in s]
x_curr_OD = _form_cubes(vec_f_image_OD, vec_f_imageBscan3d_OD, num_octa, downscale_size, downscale_size_bscan, crop_size,
str_angiography, str_structure, str_bscan, vec_str_layer, vec_str_layer_bscan3d,
str_bscan_layer, dict_layer_order, dict_layer_order_bscan3d)
x_curr_OS = _form_cubes(vec_f_image_OS, vec_f_imageBscan3d_OS, num_octa, downscale_size, downscale_size_bscan, crop_size,
str_angiography, str_structure, str_bscan, vec_str_layer, vec_str_layer_bscan3d,
str_bscan_layer, dict_layer_order, dict_layer_order_bscan3d)
# Figure out if any of the single eye data is none
if x_curr_OD is not None and x_curr_OS is not None:
packed_x_curr = [x_curr_OD, x_curr_OS]
str_eye = ['OD', 'OS']
elif x_curr_OD is None and x_curr_OS is not None:
packed_x_curr = x_curr_OS
str_eye = 'OS'
elif x_curr_OD is not None and x_curr_OS is None:
packed_x_curr = x_curr_OD
str_eye = 'OD'
else:
packed_x_curr = None
str_eye = None
else:
x_curr = _form_cubes(vec_f_image, vec_f_imageBscan3d, num_octa, downscale_size, downscale_size_bscan, crop_size,
str_angiography, str_structure, str_bscan, vec_str_layer, vec_str_layer_bscan3d,
str_bscan_layer, dict_layer_order, dict_layer_order_bscan3d)
packed_x_curr = x_curr
if any("_OD_" in s for s in vec_f_image):
str_eye = 'OD'
elif any("_OS_" in s for s in vec_f_image):
str_eye = 'OS'
else:
str_eye = None
return packed_x_curr, str_eye
| 5,345,306 |
def add_to_db(kb_db_name, obj_file_path):
"""
Add knowledge about the target object manipulation to the database.
Args:
kb_db_name(str): The knowledge base database file name.
obj_file_path(str): File path to the .obj file.
"""
# create vpython scene that is used for graphical representation of a scene
# for the user
vpython_scene = vpython.canvas(
title='',
width=800,
height=600,
center=vpython.vector(0, 0, 0),
background=vpython.color.black)
# Draw XYZ axis in the scene
vpython_drawings.draw_xyz_arrows(300.0)
scene = file_parsers.read_obj_file(obj_file_path)
# collision detection for each mesh in the scene
min_distance = 3
for mesh_1 in scene.values():
for mesh_2 in scene.values():
if mesh_1.name != mesh_2.name:
aabb_collision = aabb_col.aabb_intersect(
mesh_1, mesh_2, min_distance=min_distance)
if aabb_collision:
for surface in mesh_1.surfaces:
intersect = aabb_col.aabb_intersect_vertex(
mesh_2, surface.collider, min_distance=min_distance)
if intersect:
surface.collided_objects[mesh_2.name] = True
surface.collision = True
mesh_1.collision = True
mesh_1.collided_objects[mesh_2.name] = True
for side, surfaces in mesh_1.aabb.closest_surfaces.items():
counter = 0
for surface in surfaces:
if surface.collision:
counter += 1
if counter == len(surfaces):
mesh_1.aabb.collided_sides[side] = 2
elif counter > 0 and counter < len(surfaces):
mesh_1.aabb.collided_sides[side] = 1
# print(mesh_1.name, side, mesh_1.aabb.collided_sides[side])
# vpython_drawings.draw_colliders(mesh_list=scene.values())
vpython_drawings.draw_aabb_colliders(mesh_list=scene.values())
# vpython_drawings.draw_mesh(mesh_list=scene.values())
vpython_drawings.draw_aabb(mesh_list=scene.values(), opacity=0.4)
# select target object
picked_vpython_obj = user_inputs.select_object(vpython_scene)
picked_obj = scene[picked_vpython_obj.name[:-5]]
# get manipulation points and vectors
user_inputs.get_point(vpython_scene, picked_obj, picked_vpython_obj, 'push')
user_inputs.get_vector(vpython_scene, picked_obj, picked_vpython_obj,
'push')
user_inputs.get_point(vpython_scene, picked_obj, picked_vpython_obj, 'pull')
user_inputs.get_vector(vpython_scene, picked_obj, picked_vpython_obj,
'pull')
user_inputs.get_point(vpython_scene, picked_obj, picked_vpython_obj,
'spatula')
user_inputs.get_vector(vpython_scene, picked_obj, picked_vpython_obj,
'spatula')
# save the scene to a file and DB
db = sqlitedb.sqlitedb(name=kb_db_name)
db.create_db() # create tables if not exist
file_path_list = obj_file_path.split('/')
file_name_obj = file_path_list[-1]
file_name_list = file_name_obj.split('.')
scene_name = file_name_list[0]
db.save_scene(scene, scene_name, picked_obj)
db.conn.close()
print('Done')
| 5,345,307 |
def server(
settings: TangoGlobalSettings,
workspace: Optional[str],
workspace_dir: Optional[Union[str, os.PathLike]] = None,
):
"""
Run a local webserver that watches a workspace.
"""
from tango.server.workspace_server import WorkspaceServer
from tango.workspaces import LocalWorkspace
workspace_to_watch: Workspace
if workspace_dir is not None:
if workspace is not None:
raise click.ClickException(
"-w/--workspace is mutually exclusive with -d/--workspace-dir"
)
workspace_to_watch = LocalWorkspace(workspace_dir)
elif workspace is not None:
workspace_to_watch = Workspace.from_url(workspace)
elif settings.workspace is not None:
workspace_to_watch = Workspace.from_params(settings.workspace)
else:
raise click.ClickException(
"-w/--workspace or -d/--workspace-dir required unless a default workspace is specified "
"in tango settings file."
)
server = WorkspaceServer.on_free_port(workspace_to_watch)
cli_logger.info(
"Server started at [bold underline]%s[/bold underline]", server.address_for_display()
)
server.serve_forever()
| 5,345,308 |
def apply_padding_by_last(list_of_lists):
""" The same as applying pad_into_lists followed by carry_previous_over_none
but takes a list of lists instead of events
Args:
lists_of_lists: list of lists with possibly different lengths
Returns:
lists of lists padded to the same length by the last element in each list
"""
padded_lists = pad_into_lists(
[enumerate(vals) for vals in list_of_lists],
lambda x: x[0]
)
return [
# remove the index
[e[1] if e is not None else e for e in carry_previous_over_none(padded)]
for padded in padded_lists
]
| 5,345,309 |
def combine_patterns(
*patterns: str, seperator: Expression = None, combine_all=False
) -> str:
"""
Intelligently combine following input patterns.
Parameters
----------
patterns :
The patterns to combine.
seperator :
The seperator to use. If None, the default seperator :data:`WORD_SEPARATOR`
is used.
combine_all :
If True, the start matches any of the input patterns. If False, the start
matches the first pattern only, followed by any combination of all other
patterns including the first pattern.
Returns
-------
str
The combined pattern.
"""
if seperator is None:
seperator = WORD_SEPARATOR
start_group = non_capturing_group(*[str(p) for p in patterns])
pattern = wrap_pattern(
(start_group if combine_all else patterns[0])
+ non_capturing_group(seperator + start_group)
+ "*"
)
return pattern
| 5,345,310 |
def fetch_and_merge_reports(
project_id: str,
pipeline_id: int,
merged_report_output_file: io.TextIOWrapper,
) -> None:
"""
Fetches and merges the JUnit XML reports of each pytest
integration job in pipeline `pipeline_id` of project `project_id`,
and writes the result to `merged_report_output_file`.
"""
jobs = gitlab_api_project_pipeline_jobs(project_id, pipeline_id)
junit_reports = []
integration_job_re = re.compile(r'integration:pytest (\d+)/(\d+)')
for job in jobs:
match = integration_job_re.match(job['name'])
if match is None:
continue
(ci_node_index, ci_node_total) = match.groups()
artifact_path = (
"tests_python/reports/"
+ f"report_{ci_node_index}_{ci_node_total}.xml"
)
junit_report_str = gitlab_api_project_pipeline_job_artifact(
project_id, job['id'], artifact_path
).decode(encoding="utf-8")
print(f"Job {job['id']} ({job['name']}): " + f"Fetched {artifact_path}")
junit_reports.append(ET.ElementTree(ET.fromstring(junit_report_str)))
if len(junit_reports) == 0:
print(
f"Found no jobs in pipeline {pipeline_id} of project "
+ f"{project_id} matching /{integration_job_re.pattern}/"
)
sys.exit(1)
(nb_testcases, merged_junit_report) = merge_junit_reports(junit_reports)
ET.indent(merged_junit_report)
merged_junit_report.write(merged_report_output_file, encoding='unicode')
print(
f"Wrote merged report with {nb_testcases} testcases "
+ f"to {merged_report_output_file.name}"
)
| 5,345,311 |
def _add_unlinked_object(self: JSONClassObject,
field_name: str,
obj: JSONClassObject) -> None:
"""Add an object into unlinked objects pool."""
if not self._unlinked_objects.get(field_name):
self._unlinked_objects[field_name] = []
if obj not in self._unlinked_objects[field_name]:
self._unlinked_objects[field_name].append(obj)
| 5,345,312 |
async def utc_timediff(t1, t2):
"""
Calculate the absolute difference between two UTC time strings
Parameters
----------
t1, t2 : str
"""
time1 = datetime.datetime.strptime(t1, timefmt)
time2 = datetime.datetime.strptime(t2, timefmt)
timedelt = time1 - time2
return abs(timedelt.total_seconds())
| 5,345,313 |
def function():
"""
>>> function()
'decorated function'
"""
return 'function'
| 5,345,314 |
def load_stopwords(file_path):
"""
:param file_path: Stop word file path
:return: Stop word list
"""
stopwords = [line.strip() for line in open(file_path, 'r', encoding='utf-8').readlines()]
return stopwords
| 5,345,315 |
def test_gen_choice_1(item):
"""Select a random value from integer values."""
choices = range(5)
result = gen_choice(choices)
assert result in choices
| 5,345,316 |
def hello():
"""Return a friendly HTTP greeting."""
return 'abc'
| 5,345,317 |
def draw_graph(x, y):
"""Draw graph with x and y coordinates."""
plt.plot(x, y)
plt.xlabel('x-coordinate')
plt.ylabel('y-coordinate')
plt.title('projectile motion of a ball')
| 5,345,318 |
def show_ip_ospf_route(
enode,
_shell='vtysh',
_shell_args={
'matches': None,
'newline': True,
'timeout': None,
'connection': None
}
):
"""
Show ospf detail.
This function runs the following vtysh command:
::
# show ip ospf route
:param dict kwargs: arguments to pass to the send_command of the
vtysh shell.
:param str _shell: shell to be selected
:param dict _shell_args: low-level shell API arguments
:return: A dictionary as returned by
:func:`topology_lib_vtysh.parser.parse_show_ip_ospf_route`
"""
cmd = [
'show ip ospf route'
]
shell = enode.get_shell(_shell)
shell.send_command(
(' '.join(cmd)).format(**locals()), **_shell_args
)
result = shell.get_response(
connection=_shell_args.get('connection', None)
)
return parse_show_ip_ospf_route(result)
| 5,345,319 |
def fc1():
""" Test function 1 """
print("fc1")
| 5,345,320 |
def test_field_serialize_None():
"""If you attempt to serialize None (because you passed data instead of obj)
an error should be raised"""
class MapperBase(Mapper):
__type__ = TestType
score = Integer()
mapper = MapperBase(data={})
with pytest.raises(MapperError):
mapper.serialize()
| 5,345,321 |
def _PutTestResultsLog(platform, test_results_log):
"""Pushes the given test results log to google storage."""
temp_dir = util.MakeTempDir()
log_name = TEST_LOG_FORMAT % platform
log_path = os.path.join(temp_dir, log_name)
with open(log_path, 'wb') as log_file:
json.dump(test_results_log, log_file)
if slave_utils.GSUtilCopyFile(log_path, GS_CHROMEDRIVER_DATA_BUCKET):
raise Exception('Failed to upload test results log to google storage')
| 5,345,322 |
def attrs_classes(
verb,
typ,
ctx,
pre_hook="__json_pre_decode__",
post_hook="__json_post_encode__",
check="__json_check__",
):
"""
Handle an ``@attr.s`` or ``@dataclass`` decorated class.
This rule also implements several hooks to handle complex cases, especially to
manage backwards compatibility. Hooks should be resilient against invalid data,
and should not mutate their inputs.
`__json_pre_decode__` is used by decoders constructed by `RuleSet.json_to_python`.
It will be called before decoding with the JSON object and may adjust them to fit
the expected structure, which must be a `dict` with the necessary fields.
The checker generated by `inspect_json` will also call `__json_pre_decode__` before
inspecting the value generated.
`__json_post_encode__` is used by encoders constructed by `RuleSet.python_to_json`.
It will be called after encoding with the JSON object and may adjust it as
necessary.
`__json_check__` may be used to completely override the `inspect_json` check generated
for this class.
"""
if verb not in _SUPPORTED_VERBS:
return
if is_generic(typ):
typ_args = get_argument_map(typ)
typ = get_origin(typ)
else:
typ_args = None
inner_map = build_attribute_map(verb, typ, ctx, typ_args)
if inner_map is None:
return
if verb == INSP_PY:
return partial(check_isinst, typ=typ)
if verb == JSON2PY:
pre_hook_method = getattr(typ, pre_hook, identity)
return partial(
convert_dict_to_attrs,
pre_hook=pre_hook_method,
inner_map=inner_map,
con=typ,
)
elif verb == PY2JSON:
post_hook = post_hook if hasattr(typ, post_hook) else None
return partial(convert_attrs_to_dict, post_hook=post_hook, inner_map=inner_map)
elif verb == INSP_JSON:
check = getattr(typ, check, None)
if check:
return check
pre_hook_method = getattr(typ, pre_hook, identity)
return partial(check_dict, inner_map=inner_map, pre_hook=pre_hook_method)
elif verb == PATTERN:
return pat.Object.exact(
(pat.String.exact(attr.name), attr.inner or pat.Unkown)
for attr in inner_map
if attr.is_required
)
| 5,345,323 |
def delta(pricer, *, create_graph: bool = False, **kwargs) -> torch.Tensor:
"""Computes and returns the delta of a derivative.
Args:
pricer (callable): Pricing formula of a derivative.
create_graph (bool): If True, graph of the derivative will be
constructed, allowing to compute higher order derivative products.
Default: False.
**kwargs: Other parameters passed to `pricer`.
Returns:
torch.Tensor: The greek of a derivative.
Examples:
>>> pricer = lambda spot, expiry: spot * expiry
>>> spot = torch.tensor([1.0, 2.0, 3.0])
>>> expiry = torch.tensor([2.0, 3.0, 4.0])
>>> delta(pricer, spot=spot, expiry=expiry)
tensor([2., 3., 4.])
"""
if kwargs.get("strike") is None and kwargs.get("spot") is None:
# Since delta does not depend on strike,
# assign an arbitrary value (1.0) to strike if not given.
kwargs["strike"] = torch.tensor(1.0)
spot = _parse_spot(**kwargs).requires_grad_()
kwargs["spot"] = spot
if "moneyness" in kwargs:
# lest moneyness is used to compute price and grad wrt spot cannot be computed
kwargs["moneyness"] = None
if "log_moneyness" in kwargs:
# lest moneyness is used to compute price and grad wrt spot cannot be computed
kwargs["log_moneyness"] = None
price = pricer(**kwargs)
return torch.autograd.grad(
price,
inputs=spot,
grad_outputs=torch.ones_like(price),
create_graph=create_graph,
)[0]
| 5,345,324 |
def formula_search(min_texts, max_texts, min_entries, max_entries):
"""Filter search results"""
result = Cf.query.filter(
Cf.n_entries >= (min_entries or MIN),
Cf.n_entries <= (max_entries or MAX),
Cf.unique_text >= (min_texts or MIN),
Cf.unique_text <= (max_texts or MAX)
).group_by(
Cf.short_ngram_id
).order_by(Cf.verb_text).all()
return formula_search_to_dict(result)
| 5,345,325 |
def versioneer():
"""
Function used to generate a new version string when saving a new Service
bundle. User can also override this function to get a customized version format
"""
date_string = datetime.now().strftime("%Y%m%d")
random_hash = uuid.uuid4().hex[:6].upper()
# Example output: '20191009_D246ED'
return date_string + "_" + random_hash
| 5,345,326 |
def request_url(method, url):
"""Request the specific url and return data"""
try:
r = http.request(method, url)
if r.status == 200:
return r.data.decode('utf-8')
else:
raise Exception("Fail to {} data from {}".format(method, url))
except Exception as e:
logger.error(str(e), exc_info=True)
raise e
| 5,345,327 |
def _ifail(repo, mynode, orig, fcd, fco, fca, toolconf, labels=None):
"""
Rather than attempting to merge files that were modified on both
branches, it marks them as unresolved. The resolve command must be
used to resolve these conflicts."""
# for change/delete conflicts write out the changed version, then fail
if fcd.isabsent():
_underlyingfctxifabsent(fcd).write(fco.data(), fco.flags())
return 1, False
| 5,345,328 |
def __noise_with_pdf(im_arr: np.ndarray, pdf: Callable, **kwargs) -> np.ndarray:
"""Apply noise to given image array using pdf function that generates random values."""
util.check_input(im_arr)
im_arr = im_arr/255.0
noise = pdf(**kwargs, size=im_arr.shape)
out_im = im_arr + noise
out_im = np.clip(out_im, 0.0, 1.0)
return (out_im*255.0).astype(np.uint8)
| 5,345,329 |
def get_git_revision_hash():
"""Returns the git version of this project"""
return subprocess.check_output(
["git", "describe", "--always"], universal_newlines=True
)
| 5,345,330 |
def train_test_split(df, frac):
"""
Create a Train/Test split function for a dataframe and return both
the Training and Testing sets.
Frac refers to the percent of data you would like to set aside
for training.
"""
frac = round(len(df)*frac)
train = df[:frac]
test = df[frac:]
return train, test
| 5,345,331 |
def print_table(d, words, n=20):
"""
Prints table of stable and unstable words in the following format:
<stable words> | <unstable words>
Arguments:
d - distance distribution
words - list of words - indices of d and words must match
n - number of rows in the table
"""
print("-"*20)
print("%15s\t%15s" % ("stable", "unstable"))
indices = np.argsort(d)
for i in range(n):
print("%15s\t%15s"
% (words[indices[i]], words[indices[-i-1]]))
print("-"*20)
| 5,345,332 |
def load_special_config(config_filename, special_type, image_type='extent'):
"""Loads the google earth ("google"), science on a sphere ("sos"), or any other
special type of image config.
"""
cfg = load_config(config_filename)
# Promote the image type's keys
cfg = _merge_keys(cfg, cfg[image_type])
cfg = _prune_keys(cfg, image_type)
# Promote the special key
cfg = _merge_keys(cfg, cfg[special_type])
cfg = _substitute_colortable(cfg)
return cfg
| 5,345,333 |
def test_optimiser_updatemodel():
"""Test that the method for updating an oogeso optimisation models"""
energy_system_data = make_test_data()
# convert profile data to dictionary of dataframes needed internally:
profiles_df = {"forecast": pd.DataFrame(), "nowcast": pd.DataFrame()}
for pr in energy_system_data.profiles:
profiles_df["forecast"][pr.id] = pr.data
profiles_df["nowcast"][pr.id] = pr.data_nowcast
optimisation_model = oogeso.OptimisationModel(data=energy_system_data)
optimisation_model.updateOptimisationModel(timestep=0, profiles=profiles_df, first=True)
optimisation_model.updateOptimisationModel(timestep=1, profiles=profiles_df, first=False)
# Selecting timestep outside data should give error
# 3 timesteps in each optimisation, so with profile of length 4, we can only
# update for timestep 0 and 1 without error
with pytest.raises(KeyError):
optimisation_model.updateOptimisationModel(timestep=2, profiles=profiles_df, first=False)
| 5,345,334 |
def softmax_strategy_cim(attrs, inputs, out_type, target):
"""softmax cim strategy"""
strategy = _op.OpStrategy()
strategy.add_implementation(
wrap_compute_softmax(topi.nn.softmax),
wrap_topi_schedule(topi.cim.schedule_softmax),
name="softmax.cim",
)
return strategy
| 5,345,335 |
def get_statements_by_hash(hash_list, ev_limit=100, best_first=True, tries=2):
"""Get fully formed statements from a list of hashes.
Parameters
----------
hash_list : list[int or str]
A list of statement hashes.
ev_limit : int or None
Limit the amount of evidence returned per Statement. Default is 100.
best_first : bool
If True, the preassembled statements will be sorted by the amount of
evidence they have, and those with the most evidence will be
prioritized. When using `max_stmts`, this means you will get the "best"
statements. If False, statements will be queried in arbitrary order.
tries : int > 0
Set the number of times to try the query. The database often caches
results, so if a query times out the first time, trying again after a
timeout will often succeed fast enough to avoid a timeout. This can
also help gracefully handle an unreliable connection, if you're
willing to wait. Default is 2.
"""
if not isinstance(hash_list, list):
raise ValueError("The `hash_list` input is a list, not %s."
% type(hash_list))
if not hash_list:
return []
if isinstance(hash_list[0], str):
hash_list = [int(h) for h in hash_list]
if not all([isinstance(h, int) for h in hash_list]):
raise ValueError("Hashes must be ints or strings that can be "
"converted into ints.")
resp = submit_statement_request('post', 'from_hashes', ev_limit=ev_limit,
data={'hashes': hash_list},
best_first=best_first, tries=tries)
return stmts_from_json(resp.json()['statements'].values())
| 5,345,336 |
def test_save_load_model():
"""Test saving/loading a fitted model to disk"""
X_train, y_train, X_dev, y_dev, label_list = toxic_test_data()
model = BertClassifier()
model.max_seq_length = 64
model.train_batch_size = 8
model.epochs= 1
model.multilabel = True
model.label_list = label_list
model.fit(X_train, y_train)
accy1 = model.score(X_dev, y_dev)
savefile='./test_model_save.bin'
print("\nSaving model to ", savefile)
model.save(savefile)
# load model from disk
new_model = load_model(savefile)
# predict with new model
accy2 = new_model.score(X_dev, y_dev )
# clean up
print("Cleaning up model file: test_model_save.bin ")
os.remove(savefile)
assert accy1 == accy2
| 5,345,337 |
def _is_in(val_set):
"""Check if a value is included in a set of values"""
def inner(val, val_set):
if val not in val_set:
if isinstance(val_set, xrange):
acceptable = "[%d-%d]" % (val_set[0], val_set[-1])
else:
acceptable = "{%s}" % ", ".join(val_set)
raise ValueError("Acceptable values are: %s" % acceptable)
return partial(inner, val_set=val_set)
| 5,345,338 |
def commit_config(config):
"""
:param config:
:return:
"""
try:
json_response = apply_config(config, False) # Checks for config validation with Write Param set to False
if "message" in json_response: # If config is valid write the config
return json_response
if json_response[0].get("result") == 0:
applied_config = True
else: # return the error message returned
return json_response[0].get("text")
if applied_config:
if BACKUP_CONFIG:
result = backup_config()
if 'message' in result:
return result
else:
apply_config(config, True) # call the applyConfig flag with new config and write flag set to True
else:
apply_config(config, True)
return applied_config
except Exception as excp:
LOGGER.error("An error has occurred. Error is %s", str(excp))
errmsg = CONFIG_APPLY_FAILED
LOGGER.debug("Response -> %s", json.dumps({"message": errmsg}))
return {"message": errmsg}
| 5,345,339 |
def onebyone(transform, loglikelihood, parameter_names, prior, start = 0.5, ftol=0.1, disp=0, nsteps=40000,
parallel=False, find_uncertainties=False, **args):
"""
**Convex optimization based on Brent's method**
A strict assumption of one optimum between the parameter limits is used.
The bounds are narrowed until it is found, i.e. the likelihood function is flat
within the bounds.
* If optimum outside bracket, expands bracket until contained.
* Thus guaranteed to return local optimum.
* Supports parallelization (multiple parameters are treated independently)
* Supports finding ML uncertainties (Delta-Chi^2=1)
Very useful for 1-3d problems.
Otherwise useful, reproducible/deterministic algorithm for finding the minimum in
well-behaved likelihoods, where the parameters are weakly independent,
or to find a good starting point.
Optimizes each parameter in order, assuming they are largely independent.
For 1-dimensional algorithm used, see :func:`jbopt.opt_grid`
:param ftol: difference in values at which the function can be considered flat
:param compute_errors: compute standard deviation of gaussian around optimum
"""
def minfunc(cube):
cube = numpy.array(cube)
if (cube <= 1e-10).any() or (cube >= 1-1e-10).any():
return 1e100
params = transform(cube)
l = loglikelihood(params)
p = prior(params)
if numpy.isinf(p) and p < 0:
print ' prior rejection'
return -1e300
if numpy.isnan(l):
return -1e300
return -l - p
if parallel:
func = opt_grid_parallel
else:
func = opt_grid
n_params = len(parameter_names)
start = start + numpy.zeros(n_params)
ret = func(start, minfunc, [(1e-10, 1-1e-10)] * n_params, ftol=ftol, disp=disp, compute_errors=find_uncertainties)
if find_uncertainties:
c0 = ret[0]
p0 = transform(c0)
stdev = numpy.zeros(n_params)
lower = numpy.zeros(n_params)
upper = numpy.zeros(n_params)
for i, (lo, hi) in enumerate(ret[1]):
c1 = numpy.copy(c0)
c1[i] = lo
c2 = numpy.copy(c0)
c2[i] = hi
p1 = transform(c1)
p2 = transform(c2)
stdev[i] = numpy.abs(p2[i] - p1[i]) / 2
lower[i] = min(p2[i], p1[i])
upper[i] = max(p2[i], p1[i])
return dict(start=ret[0], maximum=p0,
stdev=stdev, upper=upper, lower=lower,
method='opt_grid')
else:
return dict(start=ret, maximum=transform(ret), method='opt_grid')
| 5,345,340 |
def load_ucs_manager_config():
"""
loads the test configuration into the UCS Manger
"""
logs.info_1('Loading UCSPE emulator from {0}'.format(fit_common.fitcfg()['ucsm_config_file']))
try:
handle = ucshandle.UcsHandle(UCSM_IP, UCSM_USER, UCSM_PASS)
if not handle.login():
logs.error('Failed to log into UCS Manger!')
return False
except Exception as e:
logs.info_1("error trying to log into UCS Manger!")
logs.info_1(str(e))
return False
# now try to update the UCSPE config, if this fails we can still continue
try:
path, file = os.path.split(fit_common.fitcfg()['ucsm_config_file'])
import_ucs_backup(handle, file_dir=path, file_name=file)
except Exception as e:
logs.info_1("error trying to configure UCSPE, continuing to test")
logs.info_1(str(e))
# log the error but do not return a failure, we can still run some tests with the default config
if not handle.logout():
logs.error('Failed to log out of UCS Manger during exit!')
return False
return True
| 5,345,341 |
def test_data():
"""Test data object for the main PlantCV module."""
return TestData()
| 5,345,342 |
def file_with_reftrack(request, tmpdir, parent_reftrack):
"""Return a filename to a scene with the reftracks from parent_reftrack fixture."""
fn = tmpdir.join("test1.mb")
f = cmds.file(rename=fn.dirname)
cmds.file(save=True, type='mayaBinary')
def fin():
os.remove(f)
request.addfinalizer(fin)
return f
| 5,345,343 |
def make_cmap(infile):
"""Call correct cmap function depending on file."""
cornames = ["coherence-cog.tif", "phsig.cor.geo.vrt", "topophase.cor.geo.vrt"]
phsnames = ["unwrapped-phase-cog.tif", "filt_topophase.unw.geo.vrt"]
if infile in cornames:
cpt = make_coherence_cmap()
elif infile in phsnames:
cpt = make_wrapped_phase_cmap()
else: # amplitude cmap
cpt = make_amplitude_cmap()
return cpt
| 5,345,344 |
def tail_correction(r, V, r_switch):
"""Apply a tail correction to a potential making it go to zero smoothly.
Parameters
----------
r : np.ndarray, shape=(n_points,), dtype=float
The radius values at which the potential is given.
V : np.ndarray, shape=r.shape, dtype=float
The potential values at each radius value.
r_switch : float, optional, default=pot_r[-1] - 5 * dr
The radius after which a tail correction is applied.
References
----------
.. [1] https://codeblue.umich.edu/hoomd-blue/doc/classhoomd__script_1_1pair_1_1pair.html
"""
r_cut = r[-1]
idx_r_switch, r_switch = find_nearest(r, r_switch)
S_r = np.ones_like(r)
r = r[idx_r_switch:]
S_r[idx_r_switch:] = (
(r_cut ** 2 - r ** 2) ** 2
* (r_cut ** 2 + 2 * r ** 2 - 3 * r_switch ** 2)
/ (r_cut ** 2 - r_switch ** 2) ** 3
)
return V * S_r
| 5,345,345 |
def process_input(input_string):
"""
>>> for i in range (0, 5):
... parent_node = Node(None)
... parent_node.random_tree(4)
... new_node = process_input(parent_node.get_test_string())
... parent_node.compute_meta_value() - new_node.compute_meta_value()
0
0
0
0
0
>>>
:param input_string: The string from the file that represents the license tree.
:return: The tree of Nodes
"""
node = Node.node_factory(input_string)
return node
| 5,345,346 |
def _get_version_info(blade_root_dir, svn_roots):
"""Gets svn root dir info. """
svn_info_map = {}
if os.path.exists("%s/.git" % blade_root_dir):
cmd = "git log -n 1"
dirname = os.path.dirname(blade_root_dir)
version_info = _exec_get_version_info(cmd, None)
if version_info:
svn_info_map[dirname] = version_info
return svn_info_map
for root_dir in svn_roots:
root_dir_realpath = os.path.realpath(root_dir)
svn_working_dir = os.path.dirname(root_dir_realpath)
svn_dir = os.path.basename(root_dir_realpath)
cmd = 'svn info %s' % svn_dir
version_info = _exec_get_version_info(cmd, svn_working_dir)
if not version_info:
cmd = 'git ls-remote --get-url && git branch | grep "*" && git log -n 1'
version_info = _exec_get_version_info(cmd, root_dir_realpath)
if not version_info:
console.warning('Failed to get version control info in %s' % root_dir)
if version_info:
svn_info_map[root_dir] = version_info
return svn_info_map
| 5,345,347 |
def equiv_alpha(x,y):
"""check if two closed terms are equivalent module alpha
conversion. for now, we assume the terms are closed
"""
if x == y:
return True
if il.is_lambda(x) and il.is_lambda(y):
return x.body == il.substitute(y.body,zip(x.variables,y.variables))
return False
pass
| 5,345,348 |
def delete(isamAppliance, file_id, check_mode=False, force=False):
"""
Clearing a common log file
"""
ret_obj = {'warnings': ''}
try:
ret_obj = get(isamAppliance, file_id, start=1, size=1)
delete_required = True # Exception thrown if the file is empty
# Check for Docker
warnings = ret_obj['warnings']
if warnings and 'Docker' in warnings[0]:
return isamAppliance.create_return_object(warnings=ret_obj['warnings'])
except:
delete_required = False
if force is True or delete_required is True:
if check_mode is True:
return isamAppliance.create_return_object(changed=True, warnings=ret_obj['warnings'])
else:
return isamAppliance.invoke_delete(
"Clearing a common log file",
"{0}/{1}".format(uri, file_id), requires_model=requires_model)
return isamAppliance.create_return_object(warnings=ret_obj['warnings'])
| 5,345,349 |
def filter_imgs(df, properties = [], values = []):
"""Filters pandas dataframe according to properties and a range of values
Input:
df - Pandas dataframe
properties - Array of column names to be filtered
values - Array of tuples containing bounds for each filter
Output:
df - Filtered dataframe
"""
for i, val in enumerate(properties):
df = df.loc[(df[val] > values[i][0]) & (df[val] < values[i][1])]
return df
| 5,345,350 |
def conjugate_term(term: tuple) -> tuple:
"""Returns the sorted hermitian conjugate of the term."""
conj_term = [conjugate_field(field) for field in term]
return tuple(sorted(conj_term))
| 5,345,351 |
def create_notify_policy_if_not_exists(project, user, level=NotifyLevel.involved):
"""
Given a project and user, create notification policy for it.
"""
model_cls = apps.get_model("notifications", "NotifyPolicy")
try:
result = model_cls.objects.get_or_create(project=project,
user=user,
defaults={"notify_level": level})
return result[0]
except IntegrityError as e:
raise exc.IntegrityError(_("Notify exists for specified user and project")) from e
| 5,345,352 |
def test_parser_parse():
"""
Abstract
----------
Testing module.parser.parse function
"""
args = Parser.parse()
| 5,345,353 |
def test():
"""
This function show how you can write a simple python function
"""
print("Hey Python!")
| 5,345,354 |
def plot_hp_sensitivities(experiment_folder, variable_name, hp_name, hp_fixed={}, details=False, box_pts=1, show=False):
""" plot hyper-parameter sensitivities """
dpaths = subdir_paths(experiment_folder)
cfg_global = {}
# read in events into dictionary for chosen hyperparameter and variable respecting the constraints
variable = defaultdict(list)
for dpath in dpaths:
# read config file
with open(os.path.join(dpath, 'cfg.json'), 'r') as f:
data = json.load(f)
cfg = dotdict(data)
# impose constraints on hyperparameters
skip=False
for key, value in hp_fixed.items():
if cfg[key] not in value:
skip=True
break
# store all different hp's
for key, value in cfg.items():
if key not in cfg_global.keys():
cfg_global[key] = []
if value not in cfg_global[key]:
cfg_global[key].append(value)
# read in data from files
if not skip:
if False:
# use tf event files
event_name = 'data/' + variable_name
events, steps = read_tf_events(dpath, event_name)
data = np.reshape(events[event_name], [-1])
elif True:
# use csv files
event_name = 'data_' + variable_name
fpath = os.path.join(dpath, event_name + '.csv')
df = pd.read_csv(fpath)
steps = df.iloc[:,0].values
data = df.iloc[:,1].values
elif False:
# use npy files
data = np.load(os.path.join(dpath, variable_name + '.npy'))
# smooth data
data = smooth(data, box_pts)
# append data to dictionary
hp_value = str(cfg[hp_name])
info = {}
if hp_name == 'model_name' and details:
if 'pg' in hp_value:
info['agent_d_hidden_layers'] = cfg.agent_d_hidden_layers
if 'predictor' in hp_value:
info['predictor_d_hidden_layers'] = cfg.predictor_d_hidden_layers
hp_value += str(info)
if hp_value not in variable:
variable[hp_value] = []
variable[hp_value].append(data)
# varied and fixed hp's
cfg_varied, cfg_fixed = {}, {}
for key, value in cfg_global.items():
if key != hp_name:
if len(value) > 1:
cfg_varied[key] = value
else:
cfg_fixed[key] = value
# create x,y,hp arrays
x_values, y_values, hp_values = [], [], []
for key, value in variable.items():
x_values.append(np.tile(steps, len(value)))
y_values.append(np.reshape(value, [-1]))
hp_values.append([key for _ in range(len(y_values[-1]))])
x_values = np.hstack(x_values)
y_values = np.hstack(y_values)
hp_values = [item for sublist in hp_values for item in sublist]
# construct dataframe
df = pd.DataFrame()
df['number_of_steps'] = x_values
df[variable_name] = y_values
df[hp_name] = hp_values
# plot
fname = variable_name + '_versus_' + hp_name + '.png'
title = cfg.env_name
fpath = os.path.join(experiment_folder, fname)
footnote = None
if details:
footnote = 'varied hyperparameters\n' + str(cfg_varied) + '\n\nfixed hyperparameters\n' + str(cfg_fixed).replace('],','],\n')
plot_df(df, 'number_of_steps', variable_name, hp_name, title, fpath, footnote, show)
| 5,345,355 |
def parse_table(soup, start_gen, end_gen):
"""
- Finds the PKMN names in the soup object and puts them into a list.
- Establishes a gen range.
- Gets rid of repeated entries (formes, e.g. Deoxys) using an OrderedSet.
- Joins the list with commas.
- Handles both Nidorans having 'unmappable' characters in their names (u2642 and u2640).
params: soup (BeautifulSoup object), start_gen (int), end_gen (int)
returns: pkmn_string (string)
"""
pokes = []
for cell in soup.find_all("td", attrs={'style': None}):
for name in cell.find_all("a"):
pokes.append(name.string)
start_index = pokes.index(GEN_STARTS_WITH[start_gen])
end_index = pokes.index(GEN_ENDS_WITH[end_gen]) + 1
# Doesn't have to be ordered, just personal preference.
unique_list = OrderedSet(pokes[start_index:end_index])
if start_gen != end_gen:
print(f"{len(unique_list)} Pokémon from gen {start_gen} to {end_gen} were fetched.")
else:
print(f"{len(unique_list)} Pokémon from gen {start_gen} were fetched.")
pkmn_string = ', '.join(unique_list)
for key, value in NIDORAN_CASE.items():
# Handling of Nidoran male/female symbols.
pkmn_string = pkmn_string.replace(key, value)
return pkmn_string
| 5,345,356 |
def get_expert_parallel_src_rank():
"""Calculate the global rank corresponding to a local rank zero
in the expert parallel group."""
global_rank = torch.distributed.get_rank()
local_world_size = get_expert_parallel_world_size()
return (global_rank // local_world_size) * local_world_size
| 5,345,357 |
def plot_network(network, labels, edge_weights=(0.1, 2), layout_seed=None, figsize=(10, 6)):
"""Plot network.
Notes: uses the spring_layout approach for setting the layout.
"""
plt.figure(figsize=figsize)
# Compute the edges weights to visualize in the plot
weights = [network[ii][jj]['weight'] for ii, jj in network.edges()]
widths = scale_list(weights, *edge_weights)
# Get the location information for plotting the graph
pos = nx.spring_layout(network, seed=layout_seed)
# Update the label positions to offset them from on top of nodes
label_pos = {ind : array + [0, 0.04] for ind, array in pos.items()}
nx.draw(network, pos=pos, node_size=75, alpha=0.75, width=widths)
nx.draw_networkx_labels(network, label_pos, labels=labels, font_size=16);
| 5,345,358 |
def _add_extra_kwargs(
kwargs: Dict[str, Any], extra_kwargs: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""
Safely add additional keyword arguments to an existing dictionary
Parameters
----------
kwargs : dict
Keyword argument dictionary
extra_kwargs : dict, default None
Keyword argument dictionary to add
Returns
-------
dict
Keyword dictionary with added keyword arguments
Notes
-----
There is no checking for duplicate keys
"""
if extra_kwargs is None:
return kwargs
else:
kwargs_copy = kwargs.copy()
kwargs_copy.update(extra_kwargs)
return kwargs_copy
| 5,345,359 |
def Hiker(n,xLst,yLst,dist):
"""
Hiker is a function to generate lists of x and y
coordinates of n steps for a random walk of n steps
along with distance between the first and last point
"""
x0=0
y0=0
x=x0
y=y0
xLst[1] = x0
yLst[1] = y0
for i in range (n-1):
rnum = random.random()
if rnum <= 0.19:
y=y+1
x=x
elif rnum <= 0.43:
y=y+1
x=x+1
elif rnum <= 0.60:
y=y
x=x+1
elif rnum <= 0.70:
y = y-1
x= x+1
elif rnum <= 0.72:
y = y-1
x = x
elif rnum <= 0.75:
y = y-1
x = x-1
elif rnum <= 0.85:
y = y
x = x-1
elif rnum <= 1.00:
y = y+1
x = x-1
xLst[i+1] = x
yLst[i+1] = y
dist = math.sqrt ((x-x0)^2 + (y-y0)^2)
return (xLst,yLst,dist)
| 5,345,360 |
def set_read_access_projects():
"""
Assign the list of projects (as strings of project ids) for which the user
has read access to ``flask.g.read_access_projects``.
The user has read access, firstly, to the projects for which they directly
have read permissions, and also to projects with availability type marked
"Open".
Return:
None
Raises:
peregrine.errors.AuthNError:
if unable to retrieve auth mapping from arborist
Side Effects:
assigns result from ``get_open_project_ids`` to
``flask.g.read_access_projects``.
"""
if not hasattr(flask.g, 'read_access_projects'):
flask.g.read_access_projects = get_read_access_projects()
flask.g.read_access_projects.extend(get_open_project_ids())
| 5,345,361 |
def extractdata(csvName='US_SP_Restructured.csv'):
"""
Parameters
----------
:string csvName: Name of csv file. e.g. 'US_SP_Restructured.csv'
"""
df = pd.read_csv(csvName)
df['index'] = df.index
# extract alternative specific variables
cost = pd.melt(df, id_vars=['quest', 'index'],
value_vars=['Car_Cost', 'CarRental_Cost', 'Bus_Cost',
'Plane_Cost', 'Train_Cost', 'TrH_Cost'],
value_name='cost')
tt = pd.melt(df, id_vars=['quest', 'index'],
value_vars=['Car_TT', 'CarRental_TT', 'Bus_TT',
'Plane_TT', 'Train_TT', 'TrH_TT'],
value_name='tt')
relib = pd.melt(df, id_vars=['quest', 'index'],
value_vars=['CarRelib', 'CarRentalRelib', 'BusRelib',
'PlaneRelib', 'TrainRelib', 'TrHRelib'],
value_name='reliability')
# extract generic variables
data_RP = df[[
'quest', 'index',
'DrvLicens', 'PblcTrst', 'Ag1825', 'Ag2545', 'Ag4565', 'Ag65M',
'Male', 'Fulltime', 'PrtTime', 'Unemplyd',
'Edu_Highschl', 'Edu_BSc', 'Edu_MscPhD',
'HH_Veh0', 'HH_Veh1', 'HH_Veh2M',
'HH_Adult1', 'HH_Adult2', 'HH_Adult3M',
'HH_Chld0', 'HH_Chld1', 'HH_Chld2M',
'HH_Inc020K', 'HH_Inc2060K', 'HH_Inc60KM',
'HH_Sngl', 'HH_SnglParent', 'HH_AllAddults',
'HH_Nuclear', 'P_Chld',
'BusCrwd', 'CarMorning', 'CarAfternoon', 'CarEve',
'O_MTL_US_max', 'O_Odr_US_max', 'D_Bstn_max', 'D_NYC_max', 'D_Maine_max',
'Tp_Onewy_max', 'Tp_2way_max',
'Tp_h06_max', 'Tp_h69_max', 'Tp_h915_max', 'Tp_h1519_max',
'Tp_h1924_max', 'Tp_h1524_max',
'Tp_Y2016_max', 'Tp_Y2017_max',
'Tp_Wntr_max', 'Tp_Sprng_max', 'Tp_Sumr_max', 'Tp_Fall_max',
'Tp_CarDrv_max', 'Tp_CarPsngr_max', 'Tp_CarShrRnt_max',
'Tp_Train_max', 'Tp_Bus_max', 'Tp_Plane_max', 'Tp_ModOdr_max',
'Tp_WrkSkl_max', 'Tp_Leisr_max', 'Tp_Shpng_max', 'Tp_ActOdr_max',
'Tp_NHotel1_max', 'Tp_NHotel2_max', 'Tp_NHotel3M_max',
'Tp_FreqMonthlMulti_max', 'Tp_FreqYearMulti_max',
'Tp_FreqYear1_max',
'Envrn_Car', 'Envrn_Train', 'Envrn_Bus', 'Envrn_Plane',
'Safe_Car', 'Safe_Train', 'Safe_Bus', 'Safe_Plane',
'Comf_Car', 'Comf_Train', 'Comf_Bus', 'Comf_Plane',
'Import_Cost', 'Import_TT', 'Import_Relib', 'Import_StartTime',
'Import_Freq', 'Import_Onboard', 'Import_Crwding'
]]
# extract alternatives
data_choice = df[['quest', 'index', 'New_SP_Choice']]
# extract availability
data_avail = df[['quest', 'index',
'AV_Car', 'AV_CarRental', 'AV_Bus', 'AV_Plane',
'AV_Train', 'AV_TrH']]
# extract indicators
data_ind = df[['quest', 'index',
'Envrn_Car', 'Envrn_Train', 'Envrn_Bus', 'Envrn_Plane',
'Safe_Car', 'Safe_Train', 'Safe_Bus', 'Safe_Plane',
'Comf_Car', 'Comf_Train', 'Comf_Bus', 'Comf_Plane']]
data_choice = data_choice.sort_values(['quest', 'index'])
cost = cost.sort_values(['quest', 'index', 'variable'])
tt = tt.sort_values(['quest', 'index', 'variable'])
relib = relib.sort_values(['quest', 'index', 'variable'])
data_RP = data_RP.sort_values(['quest', 'index'])
data_avail = data_avail.sort_values(['quest', 'index'])
data_ind = data_ind.sort_values(['quest', 'index'])
# make a copy and merge alternative specific variables
data_SP = cost
data_SP['tt'] = tt['tt']
data_SP['relib'] = relib['reliability']
data_SP['choice'] = data_SP['variable'].str.split('_', expand=True)[0]
data_SP = data_SP.reset_index(drop=True)
# check if everything is in order
print(data_SP.head(6))
# extract data arrays
dataset_y = data_choice[['New_SP_Choice']]
dataset_x_ng = data_SP[['cost', 'tt', 'relib']]
dataset_x_g = data_RP[[
'DrvLicens', 'PblcTrst',
'Ag1825', 'Ag2545', 'Ag4565', 'Ag65M',
'Male', 'Fulltime', # 'PrtTime', 'Unemplyd',
'Edu_Highschl', 'Edu_BSc', 'Edu_MscPhD',
'HH_Veh0', 'HH_Veh1', 'HH_Veh2M',
# 'HH_Adult1', 'HH_Adult2', 'HH_Adult3M',
'HH_Chld0', 'HH_Chld1', 'HH_Chld2M',
'HH_Inc020K', 'HH_Inc2060K', 'HH_Inc60KM',
# 'HH_Sngl', 'HH_SnglParent', 'HH_AllAddults',
# 'HH_Nuclear', # 'P_Chld',
# 'O_MTL_US_max', 'O_Odr_US_max',
# 'D_Bstn_max', 'D_NYC_max', 'D_Maine_max',
# 'Tp_Onewy_max', 'Tp_2way_max',
# 'Tp_h06_max', 'Tp_h69_max', 'Tp_h915_max',
# 'Tp_h1519_max', 'Tp_h1924_max', 'Tp_h1524_max',
# 'Tp_Y2016_max', 'Tp_Y2017_max',
# 'Tp_Wntr_max', 'Tp_Sprng_max', 'Tp_Sumr_max', 'Tp_Fall_max',
# 'Tp_CarDrv_max', 'Tp_CarPsngr_max', 'Tp_CarShrRnt_max',
# 'Tp_Train_max', 'Tp_Bus_max', 'Tp_Plane_max', 'Tp_ModOdr_max',
# 'Tp_WrkSkl_max', 'Tp_Leisr_max', 'Tp_Shpng_max',
# 'Tp_ActOdr_max',
# 'Tp_NHotel1_max', 'Tp_NHotel2_max', 'Tp_NHotel3M_max',
# 'Tp_FreqMonthlMulti_max', 'Tp_FreqYearMulti_max',
# 'Tp_FreqYear1_max',
]]
dataset_avail = data_avail[['AV_Bus', 'AV_CarRental', 'AV_Car',
'AV_Plane', 'AV_TrH', 'AV_Train']]
dataset_ind = data_ind[['Envrn_Car', 'Envrn_Train', 'Envrn_Bus', 'Envrn_Plane',
'Safe_Car', 'Safe_Train', 'Safe_Bus', 'Safe_Plane',
'Comf_Car', 'Comf_Train', 'Comf_Bus', 'Comf_Plane']]
n = df.shape[0]
y = dataset_y.values.reshape(n,)
x_ng = dataset_x_ng.values.reshape(n, 6, -1)/100.
x_g = dataset_x_g.values
avail = dataset_avail.values
ind = dataset_ind.values
return x_ng, x_g, y, avail, ind
| 5,345,362 |
def fix_sentence_BIO(sentence):
"""Corrects BIO sequence errors in given Sentence by modifying
Token tag attributes.
"""
# Extract tags into format used by old fixbio functions, invoke
# fix_BIO() to do the work, and re-insert tags. Empty "sentences"
# are inored.
if not sentence.tokens:
return
tags = [[t.tag] for t in sentence.tokens]
fix_BIO([tags], [0])
for i, token in enumerate(sentence.tokens):
token.tag = tags[i][0]
# try predicted tags also
try:
tags = [[t.predicted_tag] for t in sentence.tokens]
fix_BIO([tags], [0])
for i, token in enumerate(sentence.tokens):
token.predicted_tag = tags[i][0]
except AttributeError:
# no predicted tags; fine.
pass
| 5,345,363 |
def has_field(entry: EntryType, field: str) -> bool:
"""Check if a given entry has non empty field"""
return has_data(get_field(entry, field))
| 5,345,364 |
def generate_random_fires(fire_schemas, n=100):
"""
Given a list of fire product schemas (account, loan, derivative_cash_flow,
security), generate random data and associated random relations (customer,
issuer, collateral, etc.)
TODO: add config to set number of products, min/max for dates etc.
TODO: add relations
"""
batches = []
start_time = timeit.default_timer()
for fire_schema in fire_schemas:
f = open(fire_schema, "r")
schema = json.load(f)
data_type = fire_schema.split("/")[-1].split(".json")[0]
data = generate_product_fire(schema, data_type, n)
batches.append(data)
end_time = timeit.default_timer() - start_time
logging.warn(
"Generating FIRE batches and writing to files"
" took {} seconds".format(end_time)
)
# logging.warn(batches)
return batches
| 5,345,365 |
def open_file(app_id, file_name, mode):
# type: (int, str, int) -> str
""" Call to open_file.
:param app_id: Application identifier.
:param file_name: File name reference.
:param mode: Open mode.
:return: The real file name.
"""
return _COMPSs.open_file(app_id, file_name, mode)
| 5,345,366 |
def get_light():
"""Get all light readings"""
try:
lux = ltr559.get_lux()
prox = ltr559.get_proximity()
LUX.set(lux)
PROXIMITY.set(prox)
except IOError:
logging.error("Could not get lux and proximity readings. Resetting i2c.")
reset_i2c()
| 5,345,367 |
def _raise_error():
"""Helper function for `Trimmed` that raises an error."""
raise ValueError('Please do not call fdl.build() on a config tree with '
'Trimmed() nodes. These nodes are for visualization only.')
| 5,345,368 |
def is_valid_network(name, ip_network, **kwargs):
"""Valid the format of an Ip network."""
if isinstance(ip_network, list):
return all([
is_valid_network(name, item, **kwargs) for item in ip_network
])
try:
netaddr.IPNetwork(ip_network)
except Exception:
logging.debug('%s invalid network %s', name, ip_network)
return False
return True
| 5,345,369 |
def test_promise_resolved_after():
"""
The first argument to 'then' must be called when a promise is
fulfilled.
"""
c = Counter()
e = Event()
def check(v, c):
assert v == 5
e.set()
c.tick()
p1 = Promise()
p2 = p1.then(lambda v: check(v, c))
p1.do_resolve(5)
e.wait()
assert 1 == c.value()
| 5,345,370 |
def correct_repeat_line():
""" Matches repeat spec above """
return "2|1|2|3|4|5|6|7"
| 5,345,371 |
def load_materials(material_dir):
"""
Load materials from a directory. We assume that the directory contains .blend
files with one material each. The file X.blend has a single NodeTree item named
X; this NodeTree item must have a "Color" input that accepts an RGBA value.
"""
for fn in os.listdir(material_dir):
if not fn.endswith('.blend'):
continue
name = os.path.splitext(fn)[0]
filepath = os.path.join(material_dir, fn, 'NodeTree', name)
bpy.ops.wm.append(filename=filepath)
| 5,345,372 |
async def party_bunker(ctx):
"""
Функция выводит список игроков
На вход: ctx - инфо пользователя
"""
if not users_bunker:
await ctx.send("Игроков нет")
return
content = "Список игроков:\n" + "\n".join(
[f"<@{user}>" for user in users_bunker]
)
await ctx.send(content)
| 5,345,373 |
def get_byte_range_bounds(byte_range_str: str, total_size: int) -> Tuple[int, int]:
"""Return the start and end byte of a byte range string."""
byte_range_str = byte_range_str.replace("bytes=", "")
segments = byte_range_str.split("-")
start_byte = int(segments[0])
# chrome does not send end_byte but safari does
# we need to handle this case and generate an end_byte if not provided
end_byte = min(
int(segments[-1]) if segments[-1] else start_byte + MAX_CHUNK_SIZE,
total_size,
)
return start_byte, end_byte
| 5,345,374 |
def train(cfg):
"""Trains the backbone embedding network."""
utils.set_seeds(cfg.random_seed)
if torch.cuda.is_available():
gpu_idx = utils.get_gpu_by_usage()
os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_idx)
open_set_datasets = ["cars196", "stanfordonlineproducts", "cub200"]
ds = hydra.utils.instantiate(cfg.dataset)
# Remove the "Dataset" suffix from the class name
ds_name = ds.__class__.__name__.lower()[:-7]
arch = hydra.utils.instantiate(cfg.arch)
method = hydra.utils.instantiate(cfg.method, arch=arch)
method_name = method.__class__.__name__
if torch.cuda.is_available():
arch = arch.cuda()
if method_name == "VMFSoftmax":
assert arch.use_vmf, "use_vmf must be true if using VMFSoftmax."
# If using the vMF Softmax, need to run data through net
# to estimate the value of z_kappa_mult
utils.set_z_kappa_mult_vmf(arch, method, ds, cfg.num_workers)
else:
assert not arch.use_vmf, ("use_vmf should be False if not using the vMF "
"method.")
p = utils.get_parameter_list(arch, cfg.mode.temp_learning_rate)
optim = torch.optim.SGD(
p,
lr=cfg.mode.learning_rate,
momentum=cfg.mode.momentum,
weight_decay=cfg.mode.weight_decay,
nesterov=(cfg.mode.nesterov and 0.0 < cfg.mode.momentum < 1.0),
)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
optim, mode="max", factor=0.5, patience=15)
best_epoch = {
"epoch": -1,
"train_loss": float("inf"),
"valid_acc": 0.0,
}
for e in range(cfg.mode.epochs):
# Training loop
arch.train(True)
ds.switch_split("train")
loader = utils.get_data_loader(cfg.sampler.name, ds, cfg.num_workers,
cfg.sampler)
losses = []
for batch in loader:
optim.zero_grad()
examples = batch["examples"]
ids = batch["ids"]
if torch.cuda.is_available():
examples = examples.cuda()
ids = ids.cuda()
# Catch OOM issues with rejection sampling of vMF
try:
# NOTE: This is a hack for stable training of ArcFace.
# For ArcFace, train with m = 0 for first 20 epochs for MNISTs
# and train with m = 0 for first 60 epochs for CIFAR10
# and train with m = 0 for first 100 epochs for CIFAR100
# unless using pretrained ImageNet weights (Cars196, SOP, CUB200)
if method_name == "ArcFace" and ((e < 20 and "mnist" in ds_name) or
(e < 100 and "cifar100" in ds_name) or
(e < 60 and "cifar10" in ds_name)):
# Set margin to zero
ls = method(examples, ids, set_m_zero=True)
else:
ls = method(examples, ids)
ls.backward()
except RuntimeError as exception:
if "out of memory" in str(
exception).lower() and method_name == "VMFSoftmax":
log.info(
"Out of memory rejection sampling from vMF, stopping training")
for p in arch.parameters():
if p.grad is not None:
del p.grad
if torch.cuda.is_available():
torch.cuda.empty_cache()
log.info("Exception: %s", exception)
log.info("Best epoch: %s", best_epoch)
return
optim.step()
losses.append(ls.item())
train_loss = np.mean(losses)
valid_acc = 0.0
if ds_name in open_set_datasets:
valid_acc = evaluate.open_set_val_loop(arch, ds, method, cfg)
else:
valid_acc = evaluate.fixed_set_val_loop(arch, ds, method, cfg)
scheduler.step(valid_acc)
log.info(
("[Epoch %d / %d] => Train Loss: %.4f, Validation Accuracy: %.4f, "
"Temp: %.4f, Z-Kappa-Mult: %.4f"),
e,
cfg.mode.epochs - 1,
train_loss,
valid_acc,
np.exp(arch.temp.item()) if hasattr(arch, "temp") else 1.0,
arch.z_kappa_mult.item()
if isinstance(arch.z_kappa_mult, torch.Tensor) else arch.z_kappa_mult,
)
if valid_acc > best_epoch["valid_acc"]:
previous_epoch = best_epoch["epoch"]
best_epoch["epoch"] = e
best_epoch["train_loss"] = train_loss
best_epoch["valid_acc"] = valid_acc
utils.save_model(e, best_epoch, arch, optim, scheduler, previous_epoch)
if e - best_epoch["epoch"] >= cfg.mode.patience:
log.info("Early stopping epoch: %d\n", e)
break
log.info("Best epoch: %s", best_epoch)
| 5,345,375 |
def privmsg(recipient, s, prefix='', msg=None):
"""Returns a PRIVMSG to recipient with the message msg."""
if conf.supybot.protocols.irc.strictRfc():
assert (areReceivers(recipient)), repr(recipient)
assert s, 's must not be empty.'
if minisix.PY2 and isinstance(s, unicode):
s = s.encode('utf8')
assert isinstance(s, str)
if msg and not prefix:
prefix = msg.prefix
return IrcMsg(prefix=prefix, command='PRIVMSG',
args=(recipient, s), msg=msg)
| 5,345,376 |
def char_decoding(value):
""" Decode from 'UTF-8' string to unicode.
:param value:
:return:
"""
if isinstance(value, bytes):
return value.decode('utf-8')
# return directly if unicode or exc happens.
return value
| 5,345,377 |
def rebin_file(filename, rebin):
"""Rebin the contents of a file, be it a light curve or a spectrum."""
ftype, contents = get_file_type(filename)
do_dyn = False
if 'dyn{0}'.format(ftype) in contents.keys():
do_dyn = True
if ftype == 'lc':
x = contents['time']
y = contents['lc']
ye = np.sqrt(y)
logging.info('Applying a constant rebinning')
x, y, ye = \
const_rebin(x, y, rebin, ye, normalize=False)
contents['time'] = x
contents['lc'] = y
if 'rebin' in list(contents.keys()):
contents['rebin'] *= rebin
else:
contents['rebin'] = rebin
elif ftype in ['pds', 'cpds']:
x = contents['freq']
y = contents[ftype]
ye = contents['e' + ftype]
# if rebin is integer, use constant rebinning. Otherwise, geometrical
if rebin == float(int(rebin)):
logging.info('Applying a constant rebinning')
if do_dyn:
old_dynspec = contents['dyn{0}'.format(ftype)]
old_edynspec = contents['edyn{0}'.format(ftype)]
dynspec = []
edynspec = []
for i_s, spec in enumerate(old_dynspec):
_, sp, spe = \
const_rebin(x, spec, rebin,
old_edynspec[i_s],
normalize=True)
dynspec.append(sp)
edynspec.append(spe)
contents['dyn{0}'.format(ftype)] = np.array(dynspec)
contents['edyn{0}'.format(ftype)] = np.array(edynspec)
x, y, ye = \
const_rebin(x, y, rebin, ye, normalize=True)
contents['freq'] = x
contents[ftype] = y
contents['e' + ftype] = ye
contents['rebin'] *= rebin
else:
logging.info('Applying a geometrical rebinning')
if do_dyn:
old_dynspec = contents['dyn{0}'.format(ftype)]
old_edynspec = contents['edyn{0}'.format(ftype)]
dynspec = []
edynspec = []
for i_s, spec in enumerate(old_dynspec):
retval = geom_bin(x, spec, rebin, old_edynspec[i_s])
dynspec.append(retval.pds)
edynspec.append(retval.epds)
contents['dyn{0}'.format(ftype)] = np.array(dynspec)
contents['edyn{0}'.format(ftype)] = np.array(edynspec)
retval = geom_bin(x, y, rebin, ye)
del contents['freq']
contents['flo'] = retval.flo
contents['fhi'] = retval.fhi
contents[ftype] = retval.pds
contents['e' + ftype] = retval.epds
contents['nbins'] = retval.nbins
contents['rebin'] *= retval.nbins
else:
raise Exception('Format was not recognized:', ftype)
outfile = filename.replace(get_file_extension(filename),
'_rebin%g' % rebin + MP_FILE_EXTENSION)
logging.info('Saving %s to %s' % (ftype, outfile))
save_data(contents, outfile, ftype)
| 5,345,378 |
def throw_tims_error(dll_handle):
"""Raise the last thronw timsdata error as a
:exc:`RuntimeError`
"""
size = dll_handle.tims_get_last_error_string(None, 0)
buff = create_string_buffer(size)
dll_handle.tims_get_last_error_string(buff, size)
raise RuntimeError(buff.value)
| 5,345,379 |
def inv2(x: np.ndarray) -> np.ndarray:
"""矩阵求逆"""
# np.matrix()废弃
return np.matrix(x).I
| 5,345,380 |
def clean_remaining_artifacts(image):
"""
Method still on development. Use at own risk!
Remove remaining artifacts from image
:param image: Path to Image or 3D Matrix representing RGB image
:return: Image
"""
img, *_ = __image__(image)
blur = cv2.GaussianBlur(img, (3, 3), 0)
# convert to hsv and get saturation channel
sat = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV)[:, :, 1]
# threshold saturation channel
thresh = cv2.threshold(sat, 50, 255, cv2.THRESH_BINARY)[1]
# apply morphology close and open to make mask
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 9))
morph = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=1)
mask = cv2.morphologyEx(morph, cv2.MORPH_OPEN, kernel, iterations=1)
# do OTSU threshold to get melanoma image
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
otsu = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
pre_otsu = otsu.copy()
otsu = cv2.dilate(otsu, kernel)
otsu = cv2.erode(otsu, kernel)
inv_otsu = otsu.copy()
inv_otsu[otsu == 255] = 0
inv_otsu[otsu == 0] = 255
inpaint = mask - inv_otsu
img_result = cv2.inpaint(img, inpaint, 100, cv2.INPAINT_TELEA)
return cv2.cvtColor(img_result, cv2.COLOR_BGR2RGB), otsu
| 5,345,381 |
def cpplint_process(cmd, filename):
"""Has to have a special process since it just
prints sutff to stdout willy nilly"""
lint = subprocess.check_output("%s %s" % (cmd, filename), shell=True)
if "Total errors found: 0" not in lint:
logger.info("Error: %s" % lint)
sys.exit(1)
| 5,345,382 |
def write_new_word(word, go):
"""
Clears the comm.log and loads a game on the turtle_gui side.
Doesn't generate gui, just preps it.
"""
hm.clear_log(True)
hm.load_game(word)
print('-'*20)
hm.gogogo()
if go != 'go':
sys.exit()
| 5,345,383 |
def max_simple_dividers(a):
"""
:param a: число от 1 до 1000
:return: самый большой простой делитель числа
"""
return max(simple_dividers(a))
| 5,345,384 |
def to_light_low_sat(img, new_dims, new_scale, interp_order=1 ):
"""
Turn an image into lightness
Args:
im : (H x W x K) ndarray
new_dims : (height, width) tuple of new dimensions.
new_scale : (min, max) tuple of new scale.
interp_order : interpolation order, default is linear.
Returns:
a lightness version of the original image
"""
img = skimage.img_as_float( img )
img = np.clip(img, 0.2, 0.8)
img = resize_image( img, new_dims, interp_order )
img = skimage.color.rgb2lab(img)[:,:,0]
img = rescale_image( img, new_scale, current_scale=[0,100])
return np.expand_dims(img,2)
| 5,345,385 |
def test_question_load0():
"""Empty iterator.
"""
tupl = ()
quest = exam.Question()
quest.load_sequentially(iter(tupl))
assert quest.text == ""
assert quest.subject == ""
assert quest.image == Path()
assert quest.level == 0
assert quest.answers == ()
| 5,345,386 |
def get_slug_blacklist(lang=None, variant=None):
"""
Returns a list of KA slugs to skip when creating the channel.
Combines the "global" slug blacklist that applies for all channels, and
additional customization for specific languages or curriculum variants.
"""
SLUG_BLACKLIST = GLOBAL_SLUG_BLACKLIST
if variant and (lang, variant) in SLUG_BLACKLIST_PER_LANG:
SLUG_BLACKLIST.extend(SLUG_BLACKLIST_PER_LANG[(lang, variant)])
elif lang in SLUG_BLACKLIST_PER_LANG:
SLUG_BLACKLIST.extend(SLUG_BLACKLIST_PER_LANG[lang])
else:
LOGGER.warning('No slugs for lang=' + lang + ' variant=' + str(variant))
return SLUG_BLACKLIST
| 5,345,387 |
def get_level_rise(station):
"""For a MonitoringStation object (station), returns a the rate of water level rise, specifically
the average value over the last 2 days"""
#Fetch data (if no data available, return None)
times, values = fetch_measure_levels(station.measure_id, timedelta(days=2))
#Only continue if data available, otherwise return None
if times and values and (None in times or None in values) == False:
#Get polynomial approximation of
poly, d0 = polyfit(times, values, p=4)
#Find derivative polynomial
level_der = np.polyder(poly)
#Obtain list of gradients over last 2 days using the derivative polynomial
grads = []
for t in times:
grads.append(level_der(date.date2num(t) - d0))
#Return average of gradient values
return np.average(grads)
else:
return None
| 5,345,388 |
def get_mask_indices(path):
"""Helper function to get raster mask for NYC
Returns:
list: returns list of tuples (row, column) that represent area of interest
"""
raster = tiff_to_array(path)
indices = []
it = np.nditer(raster, flags=['multi_index'])
while not it.finished:
if it[0] == 1:
r, c = it.multi_index
indices.append((r, c))
it.iternext()
return indices
| 5,345,389 |
def about(isin:str):
"""
Get company description.
Parameters
----------
isin : str
Desired company ISIN. ISIN must be of type EQUITY or BOND, see instrument_information() -> instrumentTypeKey
Returns
-------
TYPE
Dict with description.
"""
params = {'isin': isin}
return _data_request('about_the_company', params)
| 5,345,390 |
def test_set_cookie_with_cookiejar() -> None:
"""
Send a request including a cookie, using a `CookieJar` instance.
"""
url = "http://example.org/echo_cookies"
cookies = CookieJar()
cookie = Cookie(
version=0,
name="example-name",
value="example-value",
port=None,
port_specified=False,
domain="",
domain_specified=False,
domain_initial_dot=False,
path="/",
path_specified=True,
secure=False,
expires=None,
discard=True,
comment=None,
comment_url=None,
rest={"HttpOnly": ""},
rfc2109=False,
)
cookies.set_cookie(cookie)
client = httpx.Client(transport=httpx.MockTransport(get_and_set_cookies))
response = client.get(url, cookies=cookies)
assert response.status_code == 200
assert response.json() == {"cookies": "example-name=example-value"}
| 5,345,391 |
def aesEncrypt(message):
"""
Encrypts a message with a fresh key using AES-GCM.
Returns: (key, ciphertext)
"""
key = get_random_bytes(symmetricKeySizeBytes)
cipher = AES.new(key, AES.MODE_GCM)
ctext, tag = cipher.encrypt_and_digest(message)
# Concatenate (nonce, tag, ctext) and return with key
return key, (cipher.nonce + tag + ctext)
| 5,345,392 |
def pyro_nameserver(host=None,
port=None,
auto_clean=0,
auto_start=False):
"""Runs a Pyro name server.
The name server must be running in order to use distributed cameras with POCS. The name server
should be started before starting camera servers or POCS.
Args:
host (str, optional): hostname/IP address to bind the name server to. If `None` is given
(default), will look for the `pyro.nameserver.ip` config entry, otherwise will default
to localhost.
port (int, optional): port number to bind the nameserver to. If `None` is given (default),
will look for the `pyro.nameserver.port` config entry, otherwise will default to `0`,
which auto-selects a port.
auto_clean (int, optional): interval, in seconds, for automatic deregistration of objects
from the name server if they cannot be connected. If not given no autocleaning will
be done.
auto_start (bool, optional): If nameserver should be started, which will case the function
to block. Default is False, which will return the nameserver daemon and it is the users
responsibility to start the `requestLoop`.
Returns:
multiprocess.Process: The process responsible for running the nameserver. Note that if the
nameserver was started via `autostart=True`, the function will block until terminated,
but still return the completed process.
"""
logger.info(f"Pyro nameserver start request: host={host}, port={port}, auto_clean={auto_clean}"
f", auto_start={auto_start}.")
host = host or get_config('pyro.nameserver.host')
port = int(port or get_config('pyro.nameserver.port', default=0))
with suppress(error.PyroNameServerNotFound, Pyro5.errors.NamingError):
logger.info(f'Checking for existing nameserver on {host}:{port}')
nameserver = get_running_nameserver(host=host, port=port)
logger.info(f"Pyro nameserver={nameserver} already running.")
return nameserver
Pyro5.config.NS_AUTOCLEAN = float(auto_clean)
# Function to be called inside a separate process to run our nameserver.
def start_server():
try:
start_ns_loop(host=host, port=port, enableBroadcast=True)
except KeyboardInterrupt: # noqa
logger.info(f'Pyro nameserver requested shutdown by user.')
except Exception as e: # noqa
logger.warning(
f'Problem starting Pyro nameserver, is another nameserver already running?')
logger.error(f'Error: {e!r}')
finally:
logger.info(f'Pyro nameserver shutting down.')
# Set up nameserver process.
logger.debug(f'Setting up Pyro nameserver process.')
server_process = Process(target=start_server)
if auto_start:
logger.info("Auto-starting new pyro nameserver")
server_process.start()
logger.success(
"Pyro nameserver started, will block until finished...(Ctrl-c/Cmd-c to exit)")
server_process.join()
return server_process
| 5,345,393 |
def _get_library_path() -> str:
"""Find library path for compiled IK fast libraries.
Look for sub-package 'linux_so', or '.reach/third_party/ikfast/linux-so'
Only supports Linux "so" file.
Returns:
Library path.
"""
if _is_running_on_google3:
return "./"
current_folder = os.path.dirname(os.path.abspath(__file__))
ur5e_so = os.path.join(current_folder, "linux_so", "libur5e_ikfast61.so")
if os.path.exists(ur5e_so):
return os.path.join(current_folder, "linux_so")
reach_path = _find_reach_path(current_folder)
sys.path.append(reach_path)
return os.path.join(reach_path, "third_party/ikfast/linux-so")
| 5,345,394 |
def view_img(
stat_map_img,
bg_img="MNI152",
cut_coords=None,
colorbar=True,
title=None,
threshold=1e-6,
annotate=True,
draw_cross=True,
black_bg="auto",
cmap=cm.cold_hot,
symmetric_cmap=True,
dim="auto",
vmax=None,
vmin=None,
resampling_interpolation="continuous",
opacity=1,
**kwargs
):
"""
Interactive html viewer of a statistical map, with optional background
Parameters
----------
stat_map_img : Niimg-like object
See http://nilearn.github.io/manipulating_images/input_output.html
The statistical map image. Can be either a 3D volume or a 4D volume
with exactly one time point.
bg_img : Niimg-like object (default='MNI152')
See http://nilearn.github.io/manipulating_images/input_output.html
The background image that the stat map will be plotted on top of.
If nothing is specified, the MNI152 template will be used.
To turn off background image, just pass "bg_img=False".
cut_coords : None, or a tuple of floats (default None)
The MNI coordinates of the point where the cut is performed
as a 3-tuple: (x, y, z). If None is given, the cuts are calculated
automaticaly.
colorbar : boolean, optional (default True)
If True, display a colorbar on top of the plots.
title : string or None (default=None)
The title displayed on the figure (or None: no title).
threshold : string, number or None (default=1e-6)
If None is given, the image is not thresholded.
If a string of the form "90%" is given, use the 90-th percentile of
the absolute value in the image.
If a number is given, it is used to threshold the image:
values below the threshold (in absolute value) are plotted
as transparent. If auto is given, the threshold is determined
automatically.
annotate : boolean (default=True)
If annotate is True, current cuts are added to the viewer.
draw_cross : boolean (default=True)
If draw_cross is True, a cross is drawn on the plot to
indicate the cuts.
black_bg : boolean (default='auto')
If True, the background of the image is set to be black.
Otherwise, a white background is used.
If set to auto, an educated guess is made to find if the background
is white or black.
cmap : matplotlib colormap, optional
The colormap for specified image.
symmetric_cmap : bool, optional (default=True)
True: make colormap symmetric (ranging from -vmax to vmax).
False: the colormap will go from the minimum of the volume to vmax.
Set it to False if you are plotting a positive volume, e.g. an atlas
or an anatomical image.
dim : float, 'auto' (default='auto')
Dimming factor applied to background image. By default, automatic
heuristics are applied based upon the background image intensity.
Accepted float values, where a typical scan is between -2 and 2
(-2 = increase constrast; 2 = decrease contrast), but larger values
can be used for a more pronounced effect. 0 means no dimming.
vmax : float, or None (default=None)
max value for mapping colors.
If vmax is None and symmetric_cmap is True, vmax is the max
absolute value of the volume.
If vmax is None and symmetric_cmap is False, vmax is the max
value of the volume.
vmin : float, or None (default=None)
min value for mapping colors.
If `symmetric_cmap` is `True`, `vmin` is always equal to `-vmax` and
cannot be chosen.
If `symmetric_cmap` is `False`, `vmin` defaults to the min of the
image, or 0 when a threshold is used.
resampling_interpolation : string, optional (default continuous)
The interpolation method for resampling.
Can be 'continuous', 'linear', or 'nearest'.
See nilearn.image.resample_img
opacity : float in [0,1] (default 1)
The level of opacity of the overlay (0: transparent, 1: opaque)
Returns
-------
html_view : the html viewer object.
It can be saved as an html page `html_view.save_as_html('test.html')`,
or opened in a browser `html_view.open_in_browser()`.
If the output is not requested and the current environment is a Jupyter
notebook, the viewer will be inserted in the notebook.
See Also
--------
nilearn.plotting.plot_stat_map:
static plot of brain volume, on a single or multiple planes.
nilearn.plotting.view_connectome:
interactive 3d view of a connectome.
nilearn.plotting.view_markers:
interactive plot of colored markers.
nilearn.plotting.view_surf, nilearn.plotting.view_img_on_surf:
interactive view of statistical maps or surface atlases on the cortical
surface.
"""
# Load template
resource_path = Path(__file__).resolve().parent.joinpath("data", "html")
file_template = resource_path.joinpath("stat_map_template.html")
tpl = tempita.Template.from_filename(str(file_template), encoding="utf-8")
# Initialize namespace for substitution
namespace = {}
namespace["title"] = title or "Slice viewer"
js_dir = os.path.join(os.path.dirname(__file__), "data", "js")
with open(os.path.join(js_dir, "jquery.min.js")) as f:
namespace["jquery_js"] = f.read()
# Initialize the template substitution tool
bsprite = viewer_substitute(
cut_coords=cut_coords,
colorbar=colorbar,
title=title,
threshold=threshold,
annotate=annotate,
draw_cross=draw_cross,
black_bg=black_bg,
cmap=cmap,
symmetric_cmap=symmetric_cmap,
dim=dim,
vmax=vmax,
vmin=vmin,
resampling_interpolation=resampling_interpolation,
opacity=opacity,
base64=True,
value=False,
)
# build sprites and meta-data
bsprite.fit(stat_map_img, bg_img=bg_img)
# Populate template
return bsprite.transform(
tpl,
javascript="javascript",
html="html",
library="library",
namespace=namespace,
)
| 5,345,395 |
async def test_fire_event_sensor(hass):
"""Test fire event."""
await async_setup_component(
hass,
"rfxtrx",
{
"rfxtrx": {
"device": "/dev/serial/by-id/usb"
+ "-RFXCOM_RFXtrx433_A1Y0NJGR-if00-port0",
"dummy": True,
"automatic_add": True,
"devices": {"0a520802060100ff0e0269": {rfxtrx.ATTR_FIRE_EVENT: True}},
}
},
)
await hass.async_block_till_done()
calls = []
@callback
def record_event(event):
"""Add recorded event to set."""
calls.append(event)
hass.bus.async_listen("signal_received", record_event)
await _signal_event(hass, "0a520802060101ff0f0269")
assert len(calls) == 5
assert any(
call.data
== {"entity_id": "sensor.wt260_wt260h_wt440h_wt450_wt450h_06_01_temperature"}
for call in calls
)
| 5,345,396 |
def getType(o):
"""There could be only return o.__class__.__name__"""
if isinstance(o, LispObj):
return o.type
return o.__class__.__name__
| 5,345,397 |
def cli(ctx, opt_input, opt_output):
"""Convert VFRAME JSON to CVAT XML"""
# ------------------------------------------------
# imports
from os.path import join
from vframe.utils import file_utils
from vframe.settings import app_cfg
from vframe.models.pipe_item import PipeContextHeader
# ------------------------------------------------
# start
log = app_cfg.LOG
items = file_utils.load_json(opt_input)
for item in items:
pipe_header = PipeContextHeader.from_dict(item)
log.debug(pipe_header._frames_data)
| 5,345,398 |
def cr2_to_pgm(
cr2_fname,
pgm_fname=None,
overwrite=True, *args,
**kwargs): # pragma: no cover
""" Convert CR2 file to PGM
Converts a raw Canon CR2 file to a netpbm PGM file via `dcraw`. Assumes
`dcraw` is installed on the system
Note:
This is a blocking call
Arguments:
cr2_fname {str} -- Name of CR2 file to convert
**kwargs {dict} -- Additional keywords to pass to script
Keyword Arguments:
pgm_fname {str} -- Name of PGM file to output, if None (default) then
use same name as CR2 (default: {None})
dcraw {str} -- Path to installed `dcraw` (default: {'dcraw'})
overwrite {bool} -- A bool indicating if existing PGM should be overwritten
(default: {True})
Returns:
str -- Filename of PGM that was created
"""
dcraw = shutil.which('dcraw')
if dcraw is None:
raise error.InvalidCommand('dcraw not found')
if pgm_fname is None:
pgm_fname = cr2_fname.replace('.cr2', '.pgm')
if os.path.exists(pgm_fname) and not overwrite:
logger.warning(f"PGM file exists, returning existing file: {pgm_fname}")
else:
try:
# Build the command for this file
command = '{} -t 0 -D -4 {}'.format(dcraw, cr2_fname)
cmd_list = command.split()
logger.debug("PGM Conversion command: \n {}".format(cmd_list))
# Run the command
if subprocess.check_call(cmd_list) == 0:
logger.debug("PGM Conversion command successful")
except subprocess.CalledProcessError as err:
raise error.InvalidSystemCommand(msg="File: {} \n err: {}".format(cr2_fname, err))
return pgm_fname
| 5,345,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.