content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def build_evaluation_from_config_item(configuration_item, compliance_type, annotation=None):
"""Form an evaluation as a dictionary. Usually suited to report on configuration change rules.
Keyword arguments:
configuration_item -- the configurationItem dictionary in the invokingEvent
compliance_type -- either COMPLIANT, NON_COMPLIANT or NOT_APPLICABLE
annotation -- an annotation to be added to the evaluation (default None)
"""
eval_ci = {}
if annotation:
eval_ci['Annotation'] = annotation
eval_ci['ComplianceResourceType'] = configuration_item['resourceType']
eval_ci['ComplianceResourceId'] = configuration_item['resourceId']
eval_ci['ComplianceType'] = compliance_type
eval_ci['OrderingTimestamp'] = configuration_item['configurationItemCaptureTime']
return eval_ci | 05769fc549acdcec7ed611abeff5f0b4f695e57e | 699,335 |
def splitbycharset(txt, charset):
"""Splits a string at the first occurrence of a character in a set.
Args:
txt: Text to split.
chars: Chars to look for (specified as string).
Returns:
(char, before, after) where char is the character from the character
set which has been found as first; before and after are the substrings
before and after it. If none of the characters had been found in the
text, char and after are set to the empty string and before to the
entrire string.
"""
for firstpos, char in enumerate(txt):
if char in charset:
break
else:
return '', txt, ''
return txt[firstpos], txt[:firstpos], txt[firstpos+1:] | c23577eb96c9621909acaa816e8791e95dbf493d | 699,340 |
def process_meta_review(meta_review):
"""
Do something with the meta-review JSON!
This is where you would:
1. Translate meta_review["ty_id"] to your own hotel ID, dropping any unmapped hotels
2. Traverse the JSON structure to find the data you are interested in, documented at
http://api.trustyou.com/hotels/documentation.html
3. Store data in your own database, to run reports, or serve them to a live website
Here, for demonstration purposes, we print a little custom summary sentence.
"""
ty_id = meta_review["ty_id"]
trust_score = meta_review.get("summary", {}).get("score")
badges = meta_review.get("badge_list", [])
def strip_markup(text):
"""
Badge texts contain some formatting hints. Remove them for display on the terminal.
"""
return (text
.replace("<strong class=\"label\">", "")
.replace("</strong>", "")
.replace("<span class=\"hotel-type\">", "")
.replace("</span>", "")
.replace("<strong>", "")
)
badge_texts = list(
strip_markup(badge["text"])
for badge
in badges[1:] # skip the overall badge, which is always in first place
)
sentence = "Hotel {ty_id} has a score of {trust_score}, and got awarded these badges: {badge_texts}".format(
ty_id=ty_id,
trust_score=trust_score,
badge_texts=(", ".join(badge_texts) or "No badges!")
)
print(sentence) | 681ace9b9685f4bfd284ac6e41efde12bafbb1b9 | 699,341 |
def find_natural_number(position: int) -> tuple:
"""Return natural number at specified position and number its a part of."""
num_range = ""
counter = 0
while len(str(num_range)) < position:
counter += 1
num_range += str(counter)
return int(num_range[-1]), counter | 62aff0c400ac007fc67dafd25eb4cacf63262105 | 699,342 |
def camel_case(snake_case: str) -> str:
"""Converts snake case strings to camel case
Args:
snake_case (str): raw snake case string, eg `sample_text`
Returns:
str: camel cased string
"""
cpnts = snake_case.split("_")
return cpnts[0] + "".join(x.title() for x in cpnts[1:]) | b3080a3e3520209581cbd381ffaff24045343115 | 699,343 |
def identify_contentType(url):
"""
Given a URL for a content, it identifies the type of the content
:param url(str): URL
:returns: Type of the content
"""
extensions = ['mp3', 'wav', 'jpeg', 'zip', 'jpg', 'mp4', 'webm', 'ecar', 'wav', 'png']
if ('youtu.be' in url) or ('youtube' in url):
return "youtube"
elif url.endswith('pdf'):
return "pdf"
elif any(url.endswith(x) for x in extensions):
return "ecml"
else:
return "unknown" | 720a9ea9adaab547309f61b6858b0eb19ddebafe | 699,349 |
def stack(x, filters, num_blocks, block_fn, use_bias, stride1=2, name=None):
"""A set of stacked residual blocks.
Arguments:
x: input tensor.
filters: integer, filters of the bottleneck layer in a block.
use_bias: boolean, enables or disables all biases in conv layers.
num_blocks: integer, blocks in the stacked blocks.
block_fn: a function of a block to stack.
stride1: default 2, stride of the first layer in the first block.
name: string, stack label.
Returns:
Output tensor for the stacked blocks.
"""
x = block_fn(x, filters, conv_shortcut=True, stride=stride1, use_bias=use_bias, name=f'{name}_block1')
for i in range(2, num_blocks + 1):
x = block_fn(x, filters, use_bias=use_bias, name=f'{name}_block{i}')
return x | 1ed366778a5abba4e05c070da05e3c87cbd92560 | 699,351 |
def pid_info(output_line):
"""
Take a line of 'ps -o pid,comm' output and return the PID number and name.
The line looks something like:
9108 orterun
or
10183 daos_server
Need both items. Return a tuple (name, pid)
Note: there could be leading spaces on the pid.
"""
info = output_line.lstrip().split()
try:
return info[1], info[0]
except Exception as e:
print("Unable to retrieve PID info from {}".format(output_line))
return "", None | 479c51e562b7bbeb7e812fad4b2cb1f771e2e830 | 699,354 |
from typing import List
from typing import Tuple
def two_columns(pairs: List[Tuple]) -> str:
"""
Join pairs (or more) of strings to a string.
:param pairs: List of tuples of strings
:return: String separated by newlines
"""
return '\n'.join([' '.join(map(str, t)) for t in pairs]) | 810fdab52b4641c32f54c6adc772f8352b8f2ae6 | 699,357 |
def get_record_as_json(cur, tablename, row_id):
"""
Get a single record from the database, by id, as json.
"""
# IMPORTANT NOTE: Only use this function in trusted input. Never on data
# being created by users. The table name is not escaped.
q = """
SELECT row_to_json(new_with_table)
FROM (SELECT {t}.*, '{t}' AS tablename FROM {t}) new_with_table
WHERE id=%s;""".format(
t=tablename,
)
cur.execute(q, (row_id,))
return cur.fetchone()[0] | 00521ae582a013f97b77494944e0f6e04069ed05 | 699,358 |
def segno(x):
"""
Input: x, a number
Return: 1.0 if x>0,
-1.0 if x<0,
0.0 if x==0
"""
if x > 0.0: return 1.0
elif x < 0.0: return -1.0
elif x == 0.0: return 0.0 | 5caccfa037b2972755958f647f009660aefae59d | 699,361 |
def speed_2_pace(speed):
"""Convert speed in km/hr to pace in s/km"""
return 60*60/speed | 25379049e98622ec5888461a9f6455be399d5f5a | 699,364 |
from pathlib import Path
def get_dictionaries(base: Path) -> list[tuple[str, list[Path]]]:
"""Make a list of available dictionaries and the interesting files.
:param base: The Apple Dictionaries root directory.
:return: A list of tuples of name, files for each dictionary.
"""
all_dicts = sorted(
(
(
dic.stem,
[
f
for f in (dic / "Contents" / "Resources").iterdir()
if f.suffix != ".lproj"
],
)
for dic_path in Path(base).iterdir()
if dic_path.is_dir()
for dic in (dic_path / "AssetData").iterdir()
),
key=lambda x: x[0],
)
return [(name, files) for name, files in all_dicts if files] | 98068ecb847aa6975cc8dc7eed59b8948316f191 | 699,366 |
def generate_recipient_from(nhais_cypher):
"""
Generates the recipient cypher. This value can be deduced from the nhais_cypher provided.
The nhais cypher can be 2 to 3 characters is length.
If it is 2 characters in length it will append "01" to generate the recipient cypher
If it is 3 characters in length it will append "1" to generate the recipient cypher
:param nhais_cypher: The nhais cypher provided. Should be 2-3 characters in length
:return: The recipient cypher
"""
recipient = ''
if len(nhais_cypher) == 3:
recipient = nhais_cypher + '1'
elif len(nhais_cypher) == 2:
recipient = nhais_cypher + "01"
return recipient | ac29a09f246fc38b43301cc1b00a4056fc49e203 | 699,367 |
def _convert_color(color):
"""Convert a 24-bit color to 16-bit.
The input `color` is assumed to be a 3-component list [R,G,B], each with
8 bits for color level.
This method will translate that list of colors into a 16-bit number,
with first 5 bits indicating R component,
last 5 bits indicating B component, and remaining
6 bits in the middle indicating G component.
i.e., 16-bit color -> (5 bits, 6 bits, 5 bits) -> (R,G,B).
"""
for i in color:
if i not in range(256):
raise ValueError("Valid color value for R, G, B is 0 - 255.")
red, green, blue = color
return ((blue & 0xF8) << 8) | ((green & 0xFC) << 3) | ((red & 0xF8) >> 3) | 6635e30d574288146c5ff07bf3d0d1661cd33b97 | 699,368 |
def list_get(lst, index, default=None):
"""
A safety mechanism for accessing uncharted indexes of a list. Always remember: safety first!
:param lst: list
:param index: int
:param default: A default value
:return: Value of list at index -or- default value
"""
assert type(lst) == list, "Requires a list type"
return_value = default
try:
return_value = lst[index]
except IndexError:
pass
return return_value | 41ca83d6a9b0ba66858617b48dcb6c43ca5a6a54 | 699,371 |
def iterate_items(collection, *args, **kwargs):
"""
iterates over the items of given object.
:param type collection: collection type to be used to
iterate over given object's items.
:rtype: iterator[tuple[object, object]]
"""
return iter(collection.items(*args, **kwargs)) | 49fde9f9c027ff1fc64a57ee67b06c91033f8755 | 699,372 |
from typing import Tuple
def is_multi_class(output_shape: Tuple[int, ...]) -> bool:
"""Checks if output is multi-class."""
# If single value output
if len(output_shape) == 1:
return False
return True | 66726be66cce6f837b40287b75c547d28d709a74 | 699,374 |
def cradmin_instance_url(context, appname, viewname, *args, **kwargs):
"""
Template tag implementation of :meth:`cradmin_legacy.crinstance.BaseCrAdminInstance.reverse_url`.
Examples:
Reverse the view named ``"edit"`` within the app named ``"pages"``:
.. code-block:: htmldjango
{% load cradmin_legacy_tags %}
<a href='{% cradmin_instance_url appname="pages" viewname="edit" %}'>
Edit
</a>
Reverse a view with keyword arguments:
.. code-block:: htmldjango
{% load cradmin_legacy_tags %}
<a href='{% cradmin_instance_url appname="pages" viewname="list" mode="advanced" orderby="name" %}'>
Show advanced pages listing ordered by name
</a>
"""
request = context['request']
return request.cradmin_instance.reverse_url(
appname=appname, viewname=viewname, args=args, kwargs=kwargs) | 9cea000ff75b68d536796cbcc323fef1b0a7059b | 699,375 |
import torch
def get_discretized_transformation_matrix(matrix, discrete_ratio,
downsample_rate):
"""
Get disretized transformation matrix.
Parameters
----------
matrix : torch.Tensor
Shape -- (B, L, 4, 4) where B is the batch size, L is the max cav
number.
discrete_ratio : float
Discrete ratio.
downsample_rate : float/int
downsample_rate
Returns
-------
matrix : torch.Tensor
Output transformation matrix in 2D with shape (B, L, 2, 3),
including 2D transformation and 2D rotation.
"""
matrix = matrix[:, :, [0, 1], :][:, :, :, [0, 1, 3]]
# normalize the x,y transformation
matrix[:, :, :, -1] = matrix[:, :, :, -1] \
/ (discrete_ratio * downsample_rate)
return matrix.type(dtype=torch.float) | fd6ab95dcbb6fca9cab6b35fd5e20998fc12472b | 699,378 |
import yaml
def represent_ordered_dict(dumper, data):
"""
Serializes ``OrderedDict`` to YAML by its proper order.
Registering this function to ``yaml.SafeDumper`` enables using ``yaml.safe_dump`` with ``OrderedDict``s.
"""
return dumper.represent_mapping(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items()) | f8c83dd3b3ecf94077b7b465334ffa84df7e16a8 | 699,385 |
def get_dot_size(val, verbose=False):
"""
Get the size of the marker based on val
:param val: the value to test
:param verbose: more output
:return: the size of the marker in pixels
"""
markersizes = [6, 9, 12, 15, 18]
# there should be one less maxmakervals than markersizes and then we use markersizes[-1] for anything larger
maxmarkervals = [10, 20, 30, 40]
for i,m in enumerate(maxmarkervals):
if val <= m:
return markersizes[i]
return markersizes[-1] | aa84c98a3cb78822dd02a9062f9f9a325907b310 | 699,387 |
import six
def _tuplify_version(version):
"""
Coerces the version string (if not None), to a version tuple.
Ex. "1.7.0" becomes (1, 7, 0).
"""
if version is None:
return version
if isinstance(version, six.string_types):
version = tuple(int(x) for x in version.split("."))
assert len(version) <= 4, version
assert (1, 3) <= version, version
assert all(isinstance(x, six.integer_types) for x in version), version
return version | 97575c813ce585e7e928b129e67196dcece5db0a | 699,388 |
from typing import Type
from typing import Callable
from typing import Any
def is_type(tipe: Type) -> Callable[[Any], bool]:
"""
:param tipe: A Type
:return: A predicate that checks if an object is an instance of that Type
"""
def predicate(value: Any) -> bool:
"""
:param value: An object
:return: Whether the object is an instance of the exprected Type
"""
return isinstance(value, tipe)
predicate.__name__ = f'_{is_type.__name__}_{tipe}'
return predicate | 2b4be636675216c810f9e14f70fe8a5647552e3f | 699,394 |
def strip_constants(df, indices):
"""Remove columns from DF that are constant input factors.
Parameters
----------
* df : DataFrame, of input parameters used in model run(s).
* indices : list, of constant input factor index positions.
Returns
----------
* copy of `df` modified to exclude constant factors
"""
df = df.copy()
const_col_names = df.iloc[:, indices].columns
df = df.loc[:, ~df.columns.isin(const_col_names)]
return df | 5a68d9beaa39cb2651ccd995af20d25165ccb03e | 699,397 |
def input_details(interpreter, key):
"""Returns input details by specified key."""
return interpreter.get_input_details()[0][key] | b06bd5278fcc5d95da387cb506ac9b9f443d9f27 | 699,401 |
def format_date( date_obj ): # date_obj is a datetime.date object
"""Returns a formatted date string given a date object. If the day is
the first of the month, then the day is dropped, eg:
format_date ( datetime.date(2013, 04, 12)) returns 2013-04-12
format_date ( datetime.date(2013, 4, 1)) returns 2013-04
"""
if date_obj.day == 1:
full_date = date_obj.isoformat()
return full_date[0:7]
else:
return date_obj.isoformat() | bfcddc9cbd4228084a0a4c5e6736be28a90d520e | 699,404 |
from typing import Dict
from typing import Any
def _make_pod_podannotations() -> Dict[str, Any]:
"""Generate pod annotation.
Returns:
Dict[str, Any]: pod annotations.
"""
annot = {
"annotations": {
"k8s.v1.cni.cncf.io/networks": '[\n{\n"name" : "internet-network",'
'\n"interface": "eth1",\n"ips": []\n}\n]'
}
}
return annot | 94ab8b66c5cf63546f15cb8fef6e1fbc4aa3cb49 | 699,406 |
def merge_result(docker_list: dict, result_dict: dict = {}, max_entries_per_docker: int = 5) -> dict:
"""Returns a python dict of the merge result
Args:
:type docker_list: ``dict``
:param docker_list: dictionary representation for the docker image used by integration or script
:type result_dict: ``dict``
:param result_dict: dictionary representation for the docker image and the integration/scripts belongs to it
merge the current result to it
:type max_entries_per_docker: ``int``
:param max_entries_per_docker: max number of integration or script to show per docker image entry
Returns:
:return: dict as {'docker_image':['integration/scripts', 'integration/scripts',...]}
:rtype: dict
"""
result = result_dict or {}
for integration_script, docker_image in docker_list.items():
if integration_script in ['CommonServerUserPowerShell', 'CommonServerUserPython']:
continue
if docker_image in result:
if len(result[docker_image]) < max_entries_per_docker:
result[docker_image].append(integration_script)
else:
result[docker_image] = [integration_script]
return result | 7cfd2708e15eb65c09e32cf0c08a360f780aacb8 | 699,408 |
def _major_minor(version):
"""Given a string of the form ``X.Y.Z``, returns ``X.Y``."""
return ".".join(version.split(".")[:2]) | 8ca52bd0324bb0445ab3c5b9b44124c0f627f635 | 699,412 |
def is_lock_valid(transfer, block_number):
""" True if the lock has not expired. """
return block_number <= transfer.expiration | 186c48c8a81458a9ff25891f5afa380f07dcbede | 699,413 |
def set_overlay(background, overlay, pos=(0,0)):
"""
Function to overlay a transparent image on background.
:param background: input color background image
:param overlay: input transparent image (BGRA)
:param pos: position where the image to be set.
:return: result image
"""
h,w,_ = overlay.shape
rows,cols,_ = background.shape
y,x = pos[0],pos[1]
for i in range(h):
for j in range(w):
if x+i >= rows or y+j >= cols:
continue
alpha = float(overlay[i][j][3]/255.0)
background[x+i][y+j] = alpha*overlay[i][j][:3]+(1-alpha)*background[x+i][y+j]
return background | ae9b8be9193e04ede7649ff9cab2ad4a94c4876a | 699,415 |
def format_line(entries, sep=' | ', pads=None, center=False):
"""
Format data for use in a simple table output to text.
args:
entries: List of data to put in table, left to right.
sep: String to separate data with.
pad: List of numbers, pad each entry as you go with this number.
center: Center the entry, otherwise left aligned.
"""
line = ''
align = '^' if center else ''
if pads:
pads = [align + str(pad) for pad in pads]
else:
pads = [align for ent in entries]
ents = []
for ind, ent in enumerate(entries):
fmt = '{:%s}' % pads[ind]
ents += [fmt.format(str(ent))]
line = sep.join(ents)
return line.rstrip() | c5dfd312f8f13a54943fe18e254a6d8836d4460a | 699,417 |
def int_or_none(x):
"""
A helper to allow filtering by an integer value or None.
"""
if x.lower() in ("null", "none", ""):
return None
return int(x) | f7a99fd637b5f5e2f4519034b36d03128279726c | 699,423 |
import platform
def supports_posix() -> bool:
"""Check if the current machine supports basic posix.
Returns:
bool:
True if the current machine is MacOSX or Linux.
"""
return platform.system().lower() in (
"darwin",
"linux",
) | 527bb8570e0493deec01aadafdf929e7315b27c0 | 699,426 |
import torch
def compute_reconstruction_error(vae, data_loader, **kwargs):
"""
Computes log p(x/z), which is the reconstruction error.
Differs from the marginal log likelihood, but still gives good
insights on the modeling of the data, and is fast to compute.
"""
# Iterate once over the data and computes the reconstruction error
log_lkl = {}
for tensors in data_loader:
loss_kwargs = dict(kl_weight=1)
_, _, losses = vae(tensors, loss_kwargs=loss_kwargs)
for key, value in losses._reconstruction_loss.items():
if key in log_lkl:
log_lkl[key] += torch.sum(value).item()
else:
log_lkl[key] = 0.0
n_samples = len(data_loader.indices)
for key, value in log_lkl.items():
log_lkl[key] = log_lkl[key] / n_samples
log_lkl[key] = -log_lkl[key]
return log_lkl | ee4fa35002e0f43d6482ae7f9ccfc7b7b1282db7 | 699,427 |
def _whbtms(anchor):
"""Return width, height, x bottom, and y bottom for an anchor (window)."""
w = anchor[2] - anchor[0] + 1
h = anchor[3] - anchor[1] + 1
x_btm = anchor[0] + 0.5 * (w - 1)
y_btm = anchor[1] + 1.0 * (h - 1)
return w, h, x_btm, y_btm | 0b4d65ad8a9dca2753ee703ad47764a1cb88f50e | 699,428 |
def _compute_land_only_mask(ds, lsm_min=0.8):
"""Computes a mask for cells that are considered to be over the
land. The lsm fraction is above lsm_min. Here, lsm is the land-sea
mask as a fraction (0 is all water, 1 is all land)."""
da_mask = ds.lsm > lsm_min
da_mask.attrs[
"long_name"
] = f"Land only (land-sea mask > {lsm_min} [{ds.lsm.units}])"
return da_mask | 23b682a216031abac3e90989d130f7b3de9abf7c | 699,432 |
def check_datasets(datasets):
"""Check that datasets is a list of (X,y) pairs or a dictionary of dataset-name:(X,y) pairs."""
try:
datasets_names = [dataset_name for dataset_name, _ in datasets]
are_all_strings = all([isinstance(dataset_name, str) for dataset_name in datasets_names])
are_unique = len(list(datasets_names)) == len(set(datasets_names))
if are_all_strings and are_unique:
return datasets
else:
raise ValueError("The datasets' names should be unique strings.")
except:
raise ValueError("The datasets should be a list of (dataset name:(X,y)) pairs.") | e02771dd7d2df3d9e716141ba2ada92408a2b14e | 699,433 |
import requests
import json
def get_card_updated_data(scryfall_id) -> str:
"""Gets updated data from scryfall
Args:
scryfall_id ([type]): [description]
Returns:
json: result from scryfalls card api
ref: https://scryfall.com/docs/api/cards/id
ex scryfall_id="e9d5aee0-5963-41db-a22b-cfea40a967a3"
"""
r = requests.get(
f"https://api.scryfall.com/cards/{scryfall_id}",
)
if r.status_code == 200:
return json.loads(r.text)
raise Exception("Could not download os save card image") | 2a0f1a9c65cbe7e173543e8a3d4b03fd364e2ae6 | 699,435 |
def get_candidate_file_name(
monotonous: bool,
agg_point: bool,
both: bool = False,
) -> str:
"""Get canonical filename for candidate set sizes."""
if both:
return f"candidate_sizes{'_mono' if monotonous else ''}_k_point"
else:
return f"candidate_sizes{'_mono' if monotonous else ''}_{'_point' if agg_point else '_k'}" | 85b27f7767fd495a46459553b96160691a3dbeda | 699,438 |
def square_of_sum(limit):
""" Returns the square of the sum of all integers in the range 1 up to and
including limit.
"""
return sum([i for i in range(limit + 1)]) ** 2 | 503048c7b175d10dce20ff9d2f9435be4fbe1c35 | 699,439 |
import re
def is_valid_regex(regex):
"""Helper function to determine whether the provided regex is valid.
Args:
regex (str): The user provided regex.
Returns:
bool: Indicates whether the provided regex was valid or not.
"""
try:
re.compile(regex)
return True
except (re.error, TypeError):
return False | 4c544168f2b1894e7cc7c7804342f923287022b5 | 699,441 |
def normalize_medical_kind(shape, properties, fid, zoom):
"""
Many medical practices, such as doctors and dentists, have a speciality,
which is indicated through the `healthcare:speciality` tag. This is a
semi-colon delimited list, so we expand it to an actual list.
"""
kind = properties.get('kind')
if kind in ['clinic', 'doctors', 'dentist']:
tags = properties.get('tags', {})
if tags:
speciality = tags.get('healthcare:speciality')
if speciality:
properties['speciality'] = speciality.split(';')
return (shape, properties, fid) | dbf75799624cbe119c4c3a74c8814d0a979d828e | 699,443 |
def _get_tws(sel_cim_data):
"""Return terrestrial water storage."""
return sel_cim_data.TWS_tavg | 2b8405a245d39466ef2b47463d88518cc3b5bedf | 699,444 |
def merge_arrays(*lsts: list):
"""Merges all arrays into one flat list.
Examples:
>>> lst_abc = ['a','b','c']\n
>>> lst_123 = [1,2,3]\n
>>> lst_names = ['John','Alice','Bob']\n
>>> merge_arrays(lst_abc,lst_123,lst_names)\n
['a', 'b', 'c', 1, 2, 3, 'John', 'Alice', 'Bob']
"""
merged_list = []
[merged_list.extend(e) for e in lsts]
return merged_list | f2dd78a9e2d31347d72e1e904c0f2c6e30b37431 | 699,449 |
def is_within_range(num, lower_bound: int, upper_bound: int) -> bool:
"""
check if a number is within a range bounded by upper and lower bound
:param num: target number needs to be checked against
:param lower_bound: exclusive lower bound
:param upper_bound: exclusive upper bound
:return: True if number is within this range, False otherwise
"""
num = int(num)
if upper_bound < lower_bound:
raise ValueError("bounds are incorrect")
return lower_bound < num < upper_bound | 325f4084a88254ec2f29dd28749b8709de394078 | 699,452 |
from typing import Optional
from typing import Tuple
def _shape_param_to_id_str(shape_param: Optional[Tuple[Optional[int], ...]]) -> str:
"""Convert kernel input shape parameter used in `test_call.py` and `conftest.py`
into a human readable representation which is used in the pytest parameter id."""
if shape_param is None:
return "None"
shape_strs = tuple("indim" if dim is None else str(dim) for dim in shape_param)
if len(shape_strs) == 1:
return f"({shape_strs[0]},)"
return f"({', '.join(shape_strs)})" | ba73efa0693217a32ba42754af36204631c4200d | 699,453 |
def getbox(xcenter, ycenter, size=500):
"""
A function to compute coordinates of a bounding box.
Arguments:
- xcenter: int, x position of the center of the box.
- ycenter: int, y position of the center of the box.
- size: int, size of the side of the box.
Returns:
- box: list of tuple of int, (x, y) coordinates of the sides of the box.
"""
xo = xcenter - int(size / 2)
yo = ycenter - int(size / 2)
xe = xcenter + int(size / 2)
ye = ycenter + int(size / 2)
horizonhaut = [(x, yo) for x in range(xo, xe)]
horizonbas = [(x, ye) for x in range(xo, xe)]
verticalgauche = [(xo, y) for y in range(yo, ye)]
verticaldroite = [(xe, y) for y in range(yo, ye)]
box = horizonbas + horizonhaut + verticaldroite + verticalgauche
return box | 6e8030f113a13775365fcd715be46690849154f3 | 699,460 |
from typing import List
def get_entity_attributes(entity: dict) -> List[str]:
"""Get a list with the attributes of the entity.
Args:
entity(:obj:`dict`): entity.
Returns:
list: containing the attributes.
"""
keys = entity.keys()
not_attributes = ["id", "type"]
attributes = [attr for attr in keys if attr not in not_attributes]
return attributes | a5482a679ff5060d2deb26d7af6f4dc7fe394bf5 | 699,461 |
def fahrenheitToRankie(fahrenheit:float, ndigits = 2)->float:
"""
Convert a given value from Fahrenheit to Rankine and round it to 2 decimal places.
Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit
Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale
"""
return round(float(fahrenheit)+ 459.7, ndigits) | feea06edfbc800fbb4da6a3a128b2a89f07966ed | 699,462 |
def connect(H, G, Gout=None, Hin=None):
"""
Connect outputs Gout of G to inputs Hin of H. The outputs and inputs of
the connected system are arranged as follows:
- remaining outputs of G get lower, the outputs of H the higher indices
- inputs of G get the lower, remaining inputs of H the higher indices
connect(H, G) is equivalent to H * G.
"""
if issubclass(type(H), type(G)):
try:
connection = H.__connect__(G, Gout, Hin)
except AttributeError:
connection = G.__rconnect__(H, Gout, Hin)
else:
try:
connection = G.__rconnect__(H, Gout, Hin)
except AttributeError:
connection = H.__connect__(G, Gout, Hin)
return(connection) | c5a6bbf86ec9da5daf006a5e1dc3de1f8140e45f | 699,463 |
def factorial(x):
"""Return the factorial of a given number."""
if x == 1:
return 1
else:
return factorial(x-1) * x | a1c3adacf122c1bec57bbbfd246f07bf627febcd | 699,465 |
from pathlib import Path
def is_file_suffix(filename, suffixes, check_exist=True):
"""
is_file + check for suffix
:param filename: pathlike object
:param suffixes: tuple of possible suffixes
:param check_exist: whether to check the file's existence
:return: bool
"""
if check_exist and not Path(filename).is_file():
return False
return str(filename).endswith(suffixes) | e1e81eb0c39c991586097882c728535829acf415 | 699,467 |
import shutil
def cmd_exists(cmd):
"""Returns True if a binary exists on
the system path"""
return shutil.which(cmd) is not None | 0d43181532b9b71cb06b6a5d1f207bbb19899129 | 699,468 |
import requests
def get_swapi_resource(url, params=None):
"""This function initiates an HTTP GET request to the SWAPI service in order to return a
representation of a resource. The function defines two parameters, the resource url (str) and
an optional params (dict) query string of key:value pairs may be provided as search terms
(e.g., {'search': 'yoda'}). If a match is obtained from a search, be aware that the JSON object
that is returned will include a list property named 'results' that contains the resource(s)
matched by the search query term(s).
Parameters:
resource (str): a url that specifies the resource.
params (dict): optional dictionary of querystring arguments. This parameter should
have a default value of None.
Returns:
dict: dictionary representation of the decoded JSON.
"""
if params:
response = requests.get(url, params=params).json()
else:
response = requests.get(url).json()
return response | 3a5de57fc498da1e25de4f2b3e61cae8508ad7c7 | 699,469 |
def assertify(text):
"""Wraps text in the (assert )."""
return '(assert ' + text + ')' | da7af0fe5d27759d8cef4589843796bee8e74383 | 699,470 |
def bubble_sort(items):
"""Sort given items by swapping adjacent items that are out of order, and
repeating until all items are in sorted order.
Running time: O(n**2) because it passes through n/2 (on average) elements
n-1 times, which simplifies to n elements n times, n**2
Memory usage: O(1), as only a boolean and two integers are declared
"""
# Take up to n-1 passes
for j in range(len(items) - 1):
# Bool for checking if items were swapped
swapped = False
# Last item after each pass is always sorted and can be ignored
for i in range(len(items) - 1 - j):
# Swap items if the current is greater than the next
if items[i] > items[i + 1]:
items[i], items[i + 1] = items[i + 1], items[i]
swapped = True
# If there were no swaps, list is already sorted
if not swapped:
return items
return items | 88748e0d552f0d08e228049f12268e34aed4907b | 699,473 |
def human_list(_list) -> str:
"""Convert a list of items into 'a, b or c'"""
last_item = _list.pop()
result = ", ".join(_list)
return "%s or %s" % (result, last_item) | 04ee703d1878ac7602ba33aaf1831ccc188ee9e2 | 699,474 |
def ccall_except_check(x):
"""
>>> ccall_except_check(41)
42
>>> ccall_except_check(-2)
-1
>>> ccall_except_check(0)
Traceback (most recent call last):
ValueError
"""
if x == 0:
raise ValueError
return x+1 | f4a877f63a189b39fea477af218438de2e6c2a78 | 699,479 |
def input_prompt(prompt):
"""
Get user input
:param prompt: the prompt to display to the user
"""
return input(prompt) | b780278c37f048d1ea61f36af0947b683c5f9b9c | 699,481 |
def safeintorbignumber(value):
"""safely converts value to integer or 10M"""
try:
return int(value)
except ValueError:
return 10000000 | de665dc11ba27c6846412b706cf833e46dc26758 | 699,482 |
def isNumber(s):
"""
Tests whether an input is a number
Parameters
----------
s : string or a number
Any string or number which needs to be type-checked as a number
Returns
-------
isNum : Bool
Returns True if 's' can be converted to a float
Returns False if converting 's' results in an error
Examples
--------
>>> isNum = isNumber('5')
>>> isNum
True
>>> isNum = isNumber('s')
>>> isNum
False
"""
try:
float(s)
return True
except ValueError:
return False | bd1bae27814ddca22c39d6411df3581e8116c324 | 699,484 |
def read_epi_params(item_basename):
"""Read all the necessary EPI parameters from text files with the given basename.
Args:
item_basename (str): The basename for all the files we need to read.
In particular the following files should exist:
- basename + '.read_out_time.txt' (with the read out time)
- basename + '.phase_enc_dir.txt' (with the phase encode direction, like AP, PA, LR, RL, SI, IS, ...)
Returns:
dict: A dictionary for use in the nipype workflow 'all_peb_pipeline'. It contains the keys:
- read_out_time (the read out time of the scan in seconds)
- enc_dir (the phase encode direction, converted to nipype standards (x, -x, y, -y, ...))
"""
with open(item_basename + '.read_out_times.txt', 'r') as f:
read_out_time = float(f.read())
with open(item_basename + '.phase_enc_dir.txt', 'r') as f:
phase_encoding = f.read()
phase_enc_dirs_translate = {'AP': 'y-', 'PA': 'y',
'LR': 'x-', 'RL': 'x', 'SD': 'x-', 'DS': 'x',
'SI': 'z-', 'IS': 'z', 'HF': 'z-', 'FH': 'z'}
return {'read_out_time': read_out_time,
'enc_dir': phase_enc_dirs_translate[phase_encoding]} | 3af788073607df214c447f2b87606b2d3e1638fd | 699,487 |
def filled_int(val, length):
"""
Takes a value and returns a zero padded representation of the integer component.
:param val: The original value.
:param length: Minimum length of the returned string
:return: Zero-padded integer representation (if possible) of string. Original string used if integer conversion
fails
"""
try:
converted_val = int(val)
except ValueError:
converted_val = val
return str(converted_val).zfill(length) | 55da47570ab03c5964f3af167bb8a4f27656a660 | 699,488 |
import pickle
def _load_batch(fpath, label_key='labels'):
"""Internal utility for parsing CIFAR data.
Arguments:
fpath: path the file to parse.
label_key: key for label data in the retrieve
dictionary.
Returns:
A tuple `(data, labels)`.
"""
with open(fpath, 'rb') as f:
d = pickle.load(f, encoding='bytes')
# decode utf8
d_decoded = {}
for k, v in d.items():
d_decoded[k.decode('utf8')] = v
d = d_decoded
data = d['data']
labels = d[label_key]
data = data.reshape(data.shape[0], 3, 32, 32)
return data, labels | 4311566594ac6f0f6c9573bdb3ccf162205991ae | 699,491 |
def velocity(estimate, actual, times=60):
"""Calculate velocity.
>>> velocity(2, 160, times=60)
0.75
>>> velocity(3, 160, times=60)
1.125
>>> velocity(3, 160, times=80)
1.5
"""
return (estimate*times)/(actual*1.) | ffdb12c7aea05f9fc8aa9e354e8db2320cbf431a | 699,496 |
from pathlib import Path
def _node_does_not_exist(node_path):
"""
Determine whether module already exists for node
:param node_path: full path to node module
:return: bool; True if node does not exist; False if it does exist
"""
try:
# noinspection PyArgumentList
Path(node_path).resolve()
except FileNotFoundError:
return True
else:
return False | 242f9895cb6e7ef4441b6d76b013cbdc88f8de45 | 699,499 |
def indent(s, depth):
# type: (str, int) -> str
"""
Indent a string of text with *depth* additional spaces on each line.
"""
spaces = " "*depth
interline_separator = "\n" + spaces
return spaces + interline_separator.join(s.split("\n")) | 69d509761cc6ab2f861f8b8c7fe7097ce8deff13 | 699,502 |
def prior_transform(u):
"""Flat prior between -10. and 10."""
return 10. * (2. * u - 1.) | 4dd488a76a08361f1c7d833eaef96a7dfdf51ca6 | 699,503 |
def ensure_components(model_tracer_list):
"""If a CO2 flavor is detected for a model, ensure all flavors are present."""
co2_components = {'CO2', 'CO2_OCN', 'CO2_LND', 'CO2_FFF'}
models = set(m for m, t in model_tracer_list)
new_list = []
for model in models:
m_tracers = set(t for m, t in model_tracer_list if m == model)
if m_tracers.intersection({'CO2_LND+CO2_FFF'}):
new_list.extend((model, t) for t in co2_components.union(m_tracers))
else:
new_list.extend([(model, t) for t in m_tracers])
return new_list | 8cb7f4e14f51718c8db75779ea02f6a73917323d | 699,506 |
def subtraction(a, b):
"""subtraction: subtracts b from a, return result c"""
a = float(a)
b = float(b)
c = b - a
return c | 0115222efc08588a12a6fbc1965441b83a7eaff0 | 699,510 |
import time
def sec_to_datetime(timestamp):
""" Convert secondes since epoch to a date and time
"""
return time.strftime("%d/%m/%Y %H:%M:%S %Z", time.localtime(timestamp)) | e1e72e2e9e34259fcf2e2d3fcd6a6598dc77e3ae | 699,511 |
def contains_failure(lines):
"""Check if any line starts with 'FAILED'."""
for line in lines:
if line.startswith('FAILED'):
return True
return False | c3a74373f351a946e7d8f9d9497c8ee9af32282e | 699,512 |
def Jaccard3d(a, b):
"""
This will compute the Jaccard Similarity coefficient for two 3-dimensional volumes
Volumes are expected to be of the same size. We are expecting binary masks -
0's are treated as background and anything else is counted as data
Arguments:
a {Numpy array} -- 3D array with first volume
b {Numpy array} -- 3D array with second volume
Returns:
float
"""
if len(a.shape) != 3 or len(b.shape) != 3:
raise Exception(f"Expecting 3 dimensional inputs, got {a.shape} and {b.shape}")
if a.shape != b.shape:
raise Exception(f"Expecting inputs of the same shape, got {a.shape} and {b.shape}")
ba = (a > 0).astype(int)
bb = (b > 0).astype(int)
n = (ba + bb == 2).sum()
magna = ba.sum()
magnb = bb.sum()
return (n / (magna + magnb - n)) | 0c5e7be04f596736ab0184b2799708350691c240 | 699,516 |
def imputation(matrix, nan_filling):
"""
takes in matrix dataframe and value for filling in NaNs for imputation
Parameters: matrix dataframe, NaN filling value
Returns: imputed matrix dataframe
"""
matrix.fillna(nan_filling, inplace=True)
return matrix | a6981e54f6228e9ebfcbb6ea65e5305f50a327ca | 699,521 |
import pkg_resources
def is_version_greater_equal(version1, version2):
"""Returns True if version1 is greater or equal than version2 else False"""
return (pkg_resources.parse_version(version1) >=
pkg_resources.parse_version(version2)) | 0618f18c22121d954ae156af7bb6eff80236ae29 | 699,524 |
def get_config(config, group):
"""Return the tuple of song_data, log_data and output_data paths.
Arguments:
config -- ConfigParser object used to extract data values
group -- Top-level grouping of config values (AWS or LOCAL)"""
group = group.upper()
return config[group]['SONG_DATA'], config[group]['LOG_DATA'], config[group]['OUTPUT_DATA'] | 62af332b29e0a901c14143bd8b77834229ce0013 | 699,525 |
import asyncio
def run_coro(coro):
"""Runs a co-routing in the default event loop and retuns it result."""
return asyncio.get_event_loop().run_until_complete(coro) | 62f109ef4440ecb2807640ff91b27f07e91d8f9f | 699,530 |
def buildaff(ulx: float, uly: float, pixelres: float) -> tuple:
"""
Build a gdal GeoTransform tuple
Args:
ulx: projected geo-spatial upper-left x reference coord
uly: projected geo-spatial upper-left y reference coord
pixelres: pixel resolution
Returns:
affine tuple
"""
return ulx, pixelres, 0, uly, 0, -pixelres | 43e593050a6b3ebef876f4347d3df787e2a49795 | 699,534 |
def parse_search_result_data(api_response):
"""
Parse the search result data from the given raw json by following the response style of tokopedia
Arg:
- api_response (list): list of products
Returns:
- product_list (list): list of compiled product properties
"""
product_list = []
for resp in api_response:
product_results = resp.get('data').get('ace_search_product_v4').get('data').get('products') # Standard tokopedia response style
for product in product_results:
product_dict = dict(
product_name=product.get('name'),
product_image_link=product.get('imageUrl'),
product_price=product.get('price'),
product_rating=product.get('rating'),
product_average_rating=product.get('ratingAverage'),
product_merchant=product.get('shop').get('name'),
product_target_url=product.get('url') # Going to be used to crawl further into the product page itself, to extract description
)
product_list.append(product_dict)
return product_list | ee1314589e1599f2d4a58523077abc8a7f270f88 | 699,535 |
import re
def parse_show_spanning_tree_mst_config(raw_result):
"""
Parse the 'show spanning-tree mst-config' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show spanning-tree \
mst-config command in a dictionary of the form:
::
{
'mst_config_id': '70:72:cf:d9:2c:f6',
'mst_config_revision': '8'
'no_instances': '2',
'instance_vlan':
{'1': ['1','2'],
'2': ['3','4']}
}
"""
mst_conf_re = (
r'\s*MST\s*config\s*ID\s*:\s*(?P<mst_config_id>[^ ]+)\s*\n'
r'\s*MST\s*config\s*revision\s*:'
r'\s*(?P<mst_config_revision>[0-9]+)\s*\n'
r'\s*MST\s*config\s*digest\s*:\s*(?P<mst_digest>[^ ]+)\s*\n'
r'\s*Number\s*of\s*instances\s*:\s*(?P<no_instances>[0-9]+)\s*\n'
)
instance_re = (
r'(?P<instance>^[0-9]+)\s*(?P<vlan>.+)\s*'
)
error = [
r'No\s*record\s*found\.',
r'\s*Spanning-tree\s*is\s*disabled'
]
instance = {}
result = {}
for error_str in error:
re_result = re.search(error_str, raw_result)
if (re_result):
result['error'] = str(raw_result)
return result
re_result = re.search(mst_conf_re, raw_result)
assert re_result
result = re_result.groupdict()
for line in raw_result.splitlines():
re_result = re.search(instance_re, line)
if re_result:
partial = re_result.groupdict()
instance[partial['instance']] = partial['vlan'].split(',')
result['instance_vlan'] = instance
return result | 2f07e13ff7f79e4c15e0fe5111cbc18fb638dae8 | 699,538 |
def read_sql_file(filename, encoding='utf-8') -> str:
"""Read SQL file, remove comments, and return a list of sql statements as a string"""
with open(filename, encoding=encoding) as f:
file = f.read()
statements = file.split('\n')
return '\n'.join(filter(lambda line: not line.startswith('--'), statements)) | bd29c1080b2fd95d690b4696bf63c92932616964 | 699,540 |
def scenegraphLocationString(dataPacket):
"""
Given a datapacket, return a string representing its location in the
scenegraph. (::UUID:OUTPUT)
"""
return "::"+str(dataPacket.sourceNode.uuid)+":"+dataPacket.sourceOutputName | 027a69984acac4454e27a149ad822864751a0983 | 699,541 |
def get_directive_type(directive):
"""Given a dict containing a directive, return the directive type
Directives have the form {'<directive type>' : <dict of stuff>}
Example: {'#requirement': {...}} --> '#requirement'
"""
keys = list(directive.keys())
if len(keys) != 1:
raise ValueError('Expected directive dict to contain a single key: {}'.format(directive))
return keys[0] | 584c1f22fc120815e79c781fc7ace69940c0f651 | 699,544 |
def u8(x: int) -> bytes:
"""
Encode an 8-bit unsigned integer.
"""
assert 0 <= x < 256
return x.to_bytes(1, byteorder='little') | c23bb4b6ea6bb610da5c3ecd281129e0bcc40bb7 | 699,547 |
def evaluate_poly(poly, x):
"""
Computes the polynomial function for a given value x. Returns that value.
Example:
>>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7x^4 + 9.3x^3 + 5x^2
>>> x = -13
>>> print evaluate_poly(poly, x) # f(-13) = 7(-13)^4 + 9.3(-13)^3 + 5(-13)^2
180339.9
poly: tuple of numbers, length > 0
x: number
returns: float
"""
eval_of_poly = 0.0
for idx, val in enumerate(poly):
eval_of_poly += (val * (x ** idx))
return eval_of_poly | 2705dbdaa937c564454078dc2cbc8dd4a9bd56e8 | 699,551 |
def split(string_to_split, separator):
"""Returns the list of strings divided by the separator."""
return string_to_split.split(separator) | c96d4ed6e3128617925c7d52c19d607cbfe1ece1 | 699,554 |
def _find_biggest_value(list):
"""
Get the intex of the largest value in list of values
:return: -1 if list empty, otherwise index of biggest value
"""
if len(list) < 1:
return -1
max = 0
for idx, val in enumerate(list):
if val > list[max]:
max = idx
return max | e4c4267ac2bfe73ad3bdb11433935805f4859e95 | 699,555 |
def inline(s, fmt):
"""Wrap string with inline escape"""
return "`\u200B{}\u200B`".format(fmt.format(s)) | 3f07a4f55e60c763a10956c9ac52314b6958eca8 | 699,557 |
def _compute_cultural_score_building(building_geometry, historical_elements_gdf, historical_elements_gdf_sindex, score = None):
"""
Compute pragmatic for a single building. It supports the function "pragmatic_meaning"
Parameters
----------
buildings_geometry: Polygon
building_land_use: string
historical_elements_gdf_sindex: Rtree spatial index
score: string
Returns
-------
float
"""
possible_matches_index = list(historical_elements_gdf_sindex.intersection(building_geometry.bounds)) # looking for possible candidates in the external GDF
possible_matches = historical_elements_gdf.iloc[possible_matches_index]
pm = possible_matches[possible_matches.intersects(building_geometry)]
if (score is None):
cs = len(pm) # score only based on number of intersecting elements
elif len(pm) == 0:
cs = 0
else: cs = pm[score].sum() # otherwise sum the scores of the intersecting elements
return cs | 743be39a3c100f53787df8195298c43affac8b4d | 699,561 |
import requests
def get_json_from_url(url):
"""Retrieve JSON from a URL, raising on failure."""
response = requests.get(url)
response.raise_for_status()
return response.json() | c88b36ff6d4911aaa6d4115b5c054fbab2f3051f | 699,568 |
def is_param(arg):
"""Returns whether the passed argument is a list or dictionary of params."""
return isinstance(arg, tuple) and arg[0] == "params" | bedb4745f8fc7095e235be588ad53c28db9fb4d8 | 699,569 |
def evaluate_numeric_condition(target, reveal_response):
"""
Tests whether the reveal_response contains a numeric condition. If so, it will
evaluate the numeric condition and return the results of that comparison.
:param target: the questions value being tested against
:param reveal_response: the numeric condition that will be evaluated against
:return: boolean result of numeric condition evaluation or None if there is no
numeric condition to evaluate.
"""
if target == '': # cannot evaluate if answer is blank
return None
if reveal_response.startswith('>='):
return float(target) >= float(reveal_response[2:])
elif reveal_response.startswith('<='):
return float(target) <= float(reveal_response[2:])
elif reveal_response.startswith('=='):
return float(target) == float(reveal_response[2:])
elif reveal_response.startswith('<'):
return float(target) < float(reveal_response[1:])
elif reveal_response.startswith('>'):
return float(target) > float(reveal_response[1:])
return None | 1eeb170635e5fb0ac5fd379af885a7a0222fb722 | 699,570 |
import hashlib
def checksum(filepath, hcnstrctr=hashlib.md5, enc="utf-8"):
"""Compute the checksum of given file, `filepath`
:raises: OSError, IOError
"""
return hcnstrctr(open(filepath).read().encode(enc)).hexdigest() | a0a6c576ef9f22de106834088f69cbbc2b3c4bd0 | 699,573 |
def increment(x):
"""increments input by one"""
return x+1 | 416451d93765ee148de9b69bd3e1af0e846d6fb5 | 699,575 |
def flatten(list_like, recursive=True):
""" Flattens a list-like datastructure (returning a new list). """
retval = []
for element in list_like:
if isinstance(element, list):
if recursive:
retval += flatten(element, recursive=True)
else:
retval += element
else:
retval.append(element)
return retval | ad343decfa9e8ae949af303fc3f1a52179464009 | 699,579 |
def intents_to_string(intents, queryset=False):
"""
Args:
intents: [{"action": "/application/json/view"}, ...] OR
[models.Intent] (if queryset=True)
Returns:
['<intent.action', ...]
"""
if queryset:
new_intents = [i.action for i in intents]
else:
new_intents = [i['action'] for i in intents]
return str(sorted(new_intents)) | 55e9350d2db63de474f46836e02ae32297e2c170 | 699,581 |
import re
def greek_to_english(string):
"""
Converts all greek letters to the corresponding english letters.
Useful for creating song slugs from greek song titles.
"""
GREEK_MAP = {
'α':'a', 'β':'b', 'γ':'g', 'δ':'d', 'ε':'e', 'ζ':'z', 'η':'h', 'θ':'th',
'ι':'i', 'κ':'k', 'λ':'l', 'μ':'m', 'ν':'n', 'ξ':'ks', 'ο':'o', 'π':'p',
'ρ':'r', 'σ':'s', 'τ':'t', 'υ':'y', 'φ':'f', 'χ':'x', 'ψ':'ps', 'ω':'w',
'ά':'a', 'έ':'e', 'ί':'i', 'ό':'o', 'ύ':'y', 'ή':'h', 'ώ':'w', 'ς':'s',
'ϊ':'i', 'ΰ':'y', 'ϋ':'y', 'ΐ':'i',
'Α':'A', 'Β':'B', 'Γ':'G', 'Δ':'D', 'Ε':'E', 'Ζ':'Z', 'Η':'H', 'Θ':'Th',
'Ι':'I', 'Κ':'K', 'Λ':'L', 'Μ':'M', 'Ν':'N', 'Ξ':'Ks', 'Ο':'O', 'Π':'P',
'Ρ':'R', 'Σ':'S', 'Τ':'T', 'Υ':'Y', 'Φ':'F', 'Χ':'X', 'Ψ':'Ps', 'Ω':'W',
'Ά':'A', 'Έ':'E', 'Ί':'I', 'Ό':'O', 'Ύ':'Y', 'Ή':'H', 'Ώ':'W', 'Ϊ':'I',
'Ϋ':'Y'
}
s = "".join(GREEK_MAP.keys())
result = ''
for piece in re.compile('[%s]|[^%s]+' % (s,s)).findall(string):
if piece in GREEK_MAP:
result += GREEK_MAP[piece]
else:
result += piece
return result.replace('oy', 'ou').replace('OY', 'OU').replace('Oy', 'Ou') | 5c4752b1a1d08b0b37acc3f0e0c884d775eae637 | 699,582 |
def anum(self, num="", type_="", xhot="", yhot="", **kwargs):
"""Specifies the annotation number, type, and hot spot (GUI).
APDL Command: /ANUM
Parameters
----------
num
Annotation number. ANSYS automatically assigns the lowest
available number. You cannot assign a higher number if a lower
number is available; ANSYS will substitute the lowest available
number in place of any user-specified higher number.
type\_
Annotation internal type number. If TYPE = DELE, delete annotation
NUM.
1 - Text
2 - Block text (not available in GUI)
3 - Dimensions
4 - Lines
5 - Rectangles
6 - Circles
7 - Polygons
8 - Arcs
9 - Wedges, pies
11 - Symbols
12 - Arrows
13 - Bitmap
xhot
X hot spot (-1.0 < X < 2.0). Used for menu button item delete.
yhot
Y hot spot (-1.0 < Y < 1.0). Used for menu button item delete.
Notes
-----
This is a command generated by the GUI and will appear in the log file
(Jobname.LOG) if annotation is used. This command is not intended to
be typed in directly in an ANSYS session (although it can be included
in an input file for batch input or for use with the /INPUT command).
Type 13 (bitmap) annotation applies user defined bitmaps defined using
the FILE option of the /TXTRE command.
This command is valid in any processor.
"""
command = f"/ANUM,{num},{type_},{xhot},{yhot}"
return self.run(command, **kwargs) | be3acd32deffcd31a3a83758b64d0d6950bbd791 | 699,583 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.