content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def readMoveBaseGoalsFromFile(poses_file):
"""Read and return MoveBaseGoals for the robot-station and patrol-poses.
If the contents of the file do not obey the syntax rules of
_readPosesFromFile(), or if no patrol-poses were found, an IOError
exception is raised.
"""
patrol_poses, station_pose =... | 5,326,400 |
def get_config(section = None):
"""Load local config file"""
run_config = configparser.ConfigParser()
run_config.read(get_repo_dir() + 'config.ini')
if len(run_config) == 1:
run_config = None
elif section is not None:
run_config = run_config[section]
return run_config | 5,326,401 |
def system_info(x):
""" Get system info. """
return list(os.uname()) | 5,326,402 |
def get_parent(running_list, i, this_type, parent_type):
"""Get the description of an industry group's parent
OSHA industry decriptions are provided in ordered lists;
this function identifies the parent industry group based
on information provided by the groups preceeding it
"""
prior = running... | 5,326,403 |
def rebalance_binary_class(label, mask=None, base_w=1.0):
"""Binary-class rebalancing."""
weight_factor = label.float().sum() / torch.prod(torch.tensor(label.size()).float())
weight_factor = torch.clamp(weight_factor, min=1e-2)
alpha = 1.0
weight = alpha * label*(1-weight_factor)/weight_factor + (1-... | 5,326,404 |
def from_base(num_base: int, dec: int) -> float:
"""Returns value in e.g. ETH (taking e.g. wei as input)."""
return float(num_base / (10 ** dec)) | 5,326,405 |
def make_auth_header(auth_token):
"""Make the authorization headers to communicate with endpoints which implement Auth0 authentication API.
Args:
auth_token (dict): a dict obtained from the Auth0 domain oauth endpoint, containing the signed JWT
(JSON Web Token), its expiry, the scopes grant... | 5,326,406 |
def get_file_in_archive(relative_path, subpath, url, force_extract = False):
"""
Download a zip file, unpack it, and get the local address of a file within this zip (so that you can open it, etc).
:param relative_path: Local name for the extracted folder. (Zip file will be named this with the appropriate ... | 5,326,407 |
async def create_nats_client(servers: List[str]) -> Optional[NatsClient]:
"""
Create a NATS client for any NATS server or NATS cluster configured to accept this installation's NKey.
:param servers: List of one or more NATS servers in the same NATS cluster.
:return: a connected NATS client instance
... | 5,326,408 |
def _drop_additional_columns(
pdf: PandasDataFrame,
column_names: Tuple,
additional_columns: Tuple,
) -> PandasDataFrame:
"""Removes additional columns from pandas DataFrame."""
# ! columns has to be a list
to_drop = list(compress(column_names, additional_columns))
return pdf.drop(columns=to... | 5,326,409 |
def get_cc3d(mask, top=1):
""" 26-connected neighbor
:param mask:
:param top: top K connected components
:return:
"""
msk = connected_components(mask.astype('uint8'))
indices, counts = np.unique(msk, return_counts=True)
indices = indices[1:]
counts = counts[1:]
if len(counts) >= ... | 5,326,410 |
def test_preprocess_consistency_adj_prop():
"""
Test scdrs.pp.preprocess: consistency between sparse+cov+adj_prop and dense+cov+adj_prop
"""
adata, adata_balance, df_cov = load_toy_data_adj_prop()
adata_sparse = adata.copy()
scdrs.pp.preprocess(adata_sparse, cov=df_cov, adj_prop="cell_group")
... | 5,326,411 |
def dscp_class(bits_0_2, bit_3, bit_4):
"""
Takes values of DSCP bits and computes dscp class
Bits 0-2 decide major class
Bit 3-4 decide drop precedence
:param bits_0_2: int: decimal value of bits 0-2
:param bit_3: int: value of bit 3
:param bit_4: int: value of bit 4
:return: DSCP cla... | 5,326,412 |
def load_data(impaths_all, test=False):
"""
Load data with corresponding masks and segmentations
:param impaths_all: Paths of images to be loaded
:param test: Boolean, part of test set?
:return: Numpy array of images, masks and segmentations
"""
# Save all images, masks and segmentations
... | 5,326,413 |
def f_assert_seq0_gte_seq1(value_list):
"""检测列表中的第一个元素是否大于等于第二个元素"""
if not value_list[0] >= value_list[1]:
raise FeatureProcessError('%s f_assert_seq0_gte_seq1 Error' % value_list)
return value_list | 5,326,414 |
def save_touchstone(db, filename):
"""Write a Datablock to a touchstone-format file with name filename.
"""
with open(filename, "w") as fil:
for rad in db_iterator(db, format_touchstone_block):
fil.write("\t".join(rad))
fil.write("\n") | 5,326,415 |
def fetch_regions():
"""Retrieve list of regions from EC2 service."""
ecc = ElasticComputeCloud(SESSION)
deliver_output(ecc.get_regions()) | 5,326,416 |
def download_file(res):
"""
Download file into temporary file
:param res: Response object
:return: downloaded file location
"""
LOGGER.debug("Chunked file download started")
with tempfile.NamedTemporaryFile(delete=False) as file:
for chunk in res.iter_content(chunk_size=config.CHUNK_... | 5,326,417 |
def extract_units(name_andor_units):
"""Extracts the number of academic credit units the course is worth.
Returns NaN if the number of units is variable."""
start = name_andor_units.rindex('(') + 1
end = name_andor_units.index(' ', start)
units = name_andor_units[start:end]
try:
return f... | 5,326,418 |
def decorate_diff_with_color(contents: List[str]) -> str:
"""Inject the ANSI color codes to the diff."""
for i, line in enumerate(contents):
if line.startswith("+++") or line.startswith("---"):
line = f"\033[1;37m{line}\033[0m" # bold white, reset
elif line.startswith("@@"):
... | 5,326,419 |
def _combine_multipliers(first: Dict[Text, float],
second: Dict[Text, float]) -> Dict[Text, float]:
"""Combines operation weight multiplier dicts. Modifies the first dict."""
for name in second:
first[name] = first.get(name, 1.0) * second[name]
return first | 5,326,420 |
def scale_to_one(iterable):
"""
Scale an iterable of numbers proportionally such as the highest number
equals to 1
Example:
>> > scale_to_one([5, 4, 3, 2, 1])
[1, 0.8, 0.6, 0.4, 0.2]
"""
m = max(iterable)
return [v / m for v in iterable] | 5,326,421 |
def test_polymorphic_enumerated_deserialization(valid_enumerated_data):
"""Ensure that a polymorphically deserialized EnumeratedDesignSpace looks sane."""
design_space: EnumeratedDesignSpace = DesignSpace.build(valid_enumerated_data)
assert design_space.name == 'my enumerated design space'
assert design... | 5,326,422 |
def fixed_size_of_type_in_bits(type_ir, ir):
"""Returns the fixed, known size for the given type, in bits, or None.
Arguments:
type_ir: The IR of a type.
ir: A complete IR, used to resolve references to types.
Returns:
size if the size of the type can be determined, otherwise None.
"""
array_mul... | 5,326,423 |
def insecure(path):
"""Find an insecure path, at or above this one"""
return first(search_parent_paths(path), insecure_inode) | 5,326,424 |
def usage():
""" print usage info """
print("usage: mnnconvert [-h]")
print(" [--framework {TF,CAFFE,ONNX,TFLITE,MNN}")
print(" [--modelFile MODELFILE]")
print(" [--prototxt PROTOTXT]")
print(" [--MNNModel MNNMODEL]")
print(" [--fp16 {True,False}]")
print(" [--weightQu... | 5,326,425 |
def n_feature_influence(estimators, n_train, n_test, n_features, percentile):
"""
Estimate influence of the number of features on prediction time.
Parameters
----------
estimators : dict of (name (str), estimator) to benchmark
n_train : nber of training instances (int)
n_test : nber of tes... | 5,326,426 |
def make_author_list(res):
"""Takes a list of author names and returns a cleaned list of author names."""
try:
r = [", ".join([clean_txt(x['family']).capitalize(), clean_txt(x['given']).capitalize()]) for x in res['author']]
except KeyError as e:
print("No 'author' key, using 'Unknown Author'. You should ... | 5,326,427 |
def assert_array_equal(x, y, err_msg='', verbose=True, strides_check=False):
"""Raises an AssertionError if two array_like objects are not equal.
Args:
x(numpy.ndarray or cupy.ndarray): The actual object to check.
y(numpy.ndarray or cupy.ndarray): The desired, expected object.
stride... | 5,326,428 |
def backproject_points_np(p, fx=None, fy=None, cx=None, cy=None, K=None):
"""
p.shape = (nr_points,xyz)
"""
if not K is None:
fx = K[0, 0]
fy = K[1, 1]
cx = K[0, 2]
cy = K[1, 2]
# true_divide
u = ((p[:, 0] / p[:, 2]) * fx) + cx
v = ((p[:, 1] / p[:, 2]) * fy) + cy
return np.stack([v, u]).... | 5,326,429 |
def pytest_collection_modifyitems(items):
"""
A pytest hook to filter out mcg tests
when running on openshift dedicated platform
Args:
items: list of collected tests
"""
# Need to update the condition when MCG will get supported
if (
config.ENV_DATA["platform"].lower() == O... | 5,326,430 |
def configure_dexter_substitutions():
"""Configure substitutions for host platform and return list of dependencies
"""
# Produce dexter path, lldb path, and combine into the %dexter substitution
# for running a test.
dexter_path = os.path.join(config.cross_project_tests_src_root,
... | 5,326,431 |
def hp_up(screen, player):
"""Increase the hp of the player"""
player.add_lifes(1) | 5,326,432 |
def recover(D, gamma=None):
"""Recover low-rank and sparse part, using Alg. 4 of [2].
Note: gamma is lambda in Alg. 4.
Parameters
---------
D : numpy ndarray, shape (N, D)
Input data matrix.
gamma : float, default = None
Weight on sparse component. If 'None', then gamma = 1/s... | 5,326,433 |
def plot_Reff(Reff: dict, dates=None, ax_arg=None, truncate=None, **kwargs):
"""
Given summary statistics of Reff as a dictionary, plot the distribution over time
"""
import matplotlib.pyplot as plt
plt.style.use("seaborn-poster")
from datetime import datetime as dt
if ax_arg is None:
... | 5,326,434 |
def get_stylesheet():
"""Generate an html link to a stylesheet"""
return "{static_url}/code_pygments/css/{theme}.css".format(
static_url=core_config['ASSETS_URL'],
theme=module_config['PYGMENTS_THEME']) | 5,326,435 |
def create_volume(ctxt,
host='test_host',
display_name='test_volume',
display_description='this is a test volume',
status='available',
migration_status=None,
size=1,
availability_zone='fake_az',... | 5,326,436 |
def test_load_none_relationship(author_schema, tag_schema, author_jsonapi):
"""Tests that loading a relationship that is set to None does not load anything."""
author_jsonapi['interests'] = None
author, errors = author_schema(include_schemas=(tag_schema,)).load(author_jsonapi)
assert errors == {}
as... | 5,326,437 |
def _writen(fd, data):
"""Write all the data to a descriptor.
reference: https://github.com/python/cpython/blob/main/Lib/pty.py#L124
"""
while data:
n = os.write(fd, data)
data = data[n:] | 5,326,438 |
def duration_of_treatment_30():
"""
Real Name: b'duration of treatment 30'
Original Eqn: b'10'
Units: b'Day'
Limits: (None, None)
Type: constant
b''
"""
return 10 | 5,326,439 |
def input_pkgidx(g_dim):
"""
Specify the parking spots index by the user
return 1*pk_dim np.array 'pk_g_idx' where pk_dim is the number of spots
"""
#print('Please specify the num of parking spots:')
pk_dim = np.int(input('Please specify the num of parking spots:'))
while pk_dim >= g_dim:
... | 5,326,440 |
def get_total_count(data):
"""
Retrieves the total count from a Salesforce SOQL query.
:param dict data: data from the Salesforce API
:rtype: int
"""
return data['totalSize'] | 5,326,441 |
def update(path):
"""Add copyright stuff to the begining of files.
"""
for filename in path_to_pyfile_list(path):
do_update(filename) | 5,326,442 |
def barrier(packet_send_time):
"""Master send a Start message and then waits for a reply.
Slave waits for Start message, then sends reply, then pauses
for packet_send_time so both master and slave return from
barrier() at the same time."""
if master_device:
uart.write(StartGame().t... | 5,326,443 |
def _check_hex(dummy_option, opt, value):
"""
Checks if a value is given in a decimal integer of hexadecimal reppresentation.
Returns the converted value or rises an exception on error.
"""
try:
if value.lower().startswith("0x"):
return int(value, 16)
else:
re... | 5,326,444 |
async def test_step_user(opp):
"""Test that the user step works."""
conf = {CONF_PLACE_ID: "12345", CONF_SERVICE_ID: "12345"}
with patch(
"openpeerpower.components.recollect_waste.async_setup_entry", return_value=True
), patch(
"aiorecollect.client.Client.async_get_next_pickup_event", r... | 5,326,445 |
def test_simple_scenario_configs():
"""Should execute configs commands as expected."""
with supports.ScenarioRunner("simple/scenario_configs.yaml") as sr:
sr.check_success()
assert sr.shell.execution_history[0].result.status == "SUCCESS" | 5,326,446 |
def get_challenge():
"""returns the ChallengeSetting object, from cache if cache is enabled"""
challenge = cache_mgr.get_cache('challenge')
if not challenge:
challenge, _ = ChallengeSetting.objects.get_or_create(pk=1)
# check the WattDepot URL to ensure it does't end with '/'
if cha... | 5,326,447 |
async def get_user_from_event(event):
""" Get the user from argument or replied message. """
args = event.pattern_match.group(1).split(" ", 1)
extra = None
if event.reply_to_msg_id:
previous_message = await event.get_reply_message()
user_obj = await event.client.get_entity(previous_messa... | 5,326,448 |
def migrate_data(conn: redis.StrictRedis, data: dict) -> list:
"""
Uploads the given data to the given redis database connection
"""
pipe = conn.pipeline()
for key, value in data.items():
command_and_formatter = TYPE_TO_PUT_COMMAND[value["type"]]
command = command_and_formatter[0]
... | 5,326,449 |
def test_len_returns_count_of_labels_in_matcher(matcher: TokenMatcher,) -> None:
"""It returns the sum of unique labels in the matcher."""
assert len(matcher) == 2 | 5,326,450 |
def test_dict_inequality_str():
"""Test equality error for string dict values."""
param1 = uvp.UVParameter(name="p1", value={"v1": 1, "s1": "test"})
param4 = uvp.UVParameter(name="p3", value={"v1": 1, "s1": "foo"})
assert param1 != param4 | 5,326,451 |
def dummy_location(db, create_location):
"""Give you a dummy default location."""
loc = create_location(u'Test')
db.session.flush()
return loc | 5,326,452 |
def get_resources_path() -> Path:
""" Convenience method to return the `resources` directory in this project """
return alpyne._ROOT_PATH.joinpath("resources") | 5,326,453 |
def get_gti_file(eventfile,segment_length):
"""
Creating the individual .gti files for my data segments!
eventfile - path to the event file. Will extract ObsID from this for the NICER files.
segment_length - length of the individual segments for combining power spectra
"""
parent_folder = str(pa... | 5,326,454 |
def is_running_in_container():
# type: () -> bool
""" Determines if we're running in an lxc/docker container. """
out = subprocess.check_output('cat /proc/1/sched', shell=True)
out = out.decode('utf-8').lower()
checks = [
'docker' in out,
'/lxc/' in out,
out.split()[0] not in... | 5,326,455 |
def load_imagenet_val(num=None):
"""
Load a handful of validation images from ImageNet.
Inputs:
- num: Number of images to load (max of 25)
Returns:
- X: numpy array with shape [num, 224, 224, 3]
- y: numpy array of integer image labels, shape [num]
- class_names: dict mapping integer ... | 5,326,456 |
def sk_rot_mx(rot_vec):
"""
use Rodrigues' rotation formula to transform the rotation vector into rotation matrix
:param rot_vec:
:return:
"""
theta = np.linalg.norm(rot_vec)
vector = np.array(rot_vec) * math.sin(theta / 2.0) / theta
a = math.cos(theta / 2.0)
b = -vector[0]
c = -... | 5,326,457 |
def split_line(line, points, tolerance=1e-9):
"""Split line at point or multipoint, within some tolerance
"""
to_split = snap_line(line, points, tolerance)
return list(split(to_split, points)) | 5,326,458 |
def analyze_data() -> bool:
"""
Read file format xml and returns name data
Parameters
----------
Returns
-------
True: bool
Answer - whether the copy was successful
"""
path_to_file = Path.PATH_TO_PROGRAM + Path.DATA_DIRECTORY
files_list = o... | 5,326,459 |
def cross_validation(docs, values, k):
"""
docs: Dict with text lists separate by value
values: Target values texts
k: Steps of cross validation
"""
group_size = {}
confusion_matrix = []
m = {'true':{}, 'false':{}}
for value in values:
group_size[value] = len(do... | 5,326,460 |
def test_rrm_unexpected(dev, apdev):
"""hostapd unexpected rrm"""
check_rrm_support(dev[0])
params = {"ssid": "rrm", "rrm_neighbor_report": "0"}
hapd = hostapd.add_ap(apdev[0]['ifname'], params)
bssid = hapd.own_addr()
dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
addr = dev[0].... | 5,326,461 |
def quote_plus(url, safe='/', encoding=None, errors=None):
"""Wrapper for urllib.parse.quote_plus"""
return uquote_plus(url, safe=safe, encoding=encoding, errors=errors) | 5,326,462 |
def test_combining_mutates():
"""Test combining mutates."""
DATA_INT = {"key_int": 0}
DATA_INT2 = {"key_int_2": 1}
COMBINED_INT = {"key_int": 0, "key_int_2": 1}
command1 = Command("method", "path", DATA_INT)
command2 = Command("method", "path", DATA_INT2)
combined = command1 + command2
... | 5,326,463 |
async def test_login(mock_aioresponse: aioresponses) -> None:
"""Test logging in to the API."""
m = mock_aioresponse
m.clear()
m.post(f"{BASE_URL}/o/token/", status=200, payload=login_data, repeat=False)
m.post(f"{BASE_URL}/o/token/", status=403, payload=login_data, repeat=False)
m.post(f"{BASE_... | 5,326,464 |
def test_measure_get_meas(withings_api: WithingsApi) -> None:
"""Test function."""
responses_add_measure_get_meas()
assert withings_api.measure_get_meas() == MeasureGetMeasResponse(
more=False,
offset=0,
timezone=TIMEZONE0,
updatetime=arrow.get(1409596058).to(TIMEZONE0),
... | 5,326,465 |
def JWST():
"""
This will be the main simulated instrument
"""
def __init__():
pass
def get_MIRI_noise(self):
pass
def get_NIRCam_noise(self):
pass
def get_NIRISS_noise(self):
pass
def get_NIRSpec_noise(self):
pass | 5,326,466 |
def create_network_policy(
spec: Dict[str, Any] = None,
spec_path: str = None,
ns: str = "default",
secrets: Secrets = None,
):
"""
Create a network policy in the given namespace eitehr from the definition
as `spec` or from a file containing the definition at `spec_path`.
"""
api = c... | 5,326,467 |
def averageSeriesWithWildcards(requestContext, seriesList, *position): #XXX
"""
Call averageSeries after inserting wildcards at the given position(s).
Example:
.. code-block:: none
&target=averageSeriesWithWildcards(host.cpu-[0-7].cpu-{user,system}.value, 1)
This would be the equivalent of
``target=... | 5,326,468 |
def errore_ddp_digitale(V):
"""
Calcola l'errore della misura di ddp del multimetro digitale
supponendo che si sia scelta la scala corretta.
La ddp deve essere data in Volt
"""
V=absolute(V)
if V<0.2: return sqrt(V**2*25e-6+1e-8)
if V<2: return sqrt(V**2*25e-6+1e-6)
if V<2... | 5,326,469 |
def water_zone(zone_name, force_water=False):
"""
Trigger watering of a zone by moisture sensor
:param zone_name: The name of the zone as used in the zone section header in the config file (i.e. 'zone_1', 'zone_4')
:type zone_name: str
"""
water = False
msg = ' '
# print('%s: Seconds_be... | 5,326,470 |
def print_sql_amortization_table() -> None:
"""Prints the amortization table from the analysis.db file"""
print(
"----------------------------------------"
"----------------------------------------"
)
print("Amortization Table:")
print()
amortization_data = {
'Period': [... | 5,326,471 |
def run_command(cmd, get_output=False, tee=True, custom_env=None):
"""
Runs a command.
Args:
cmd (str): The command to run.
get_output (bool): If true, run_command will return the stdout output. Default: False.
tee (bool): If true, captures output (if get_output is true) as well as ... | 5,326,472 |
def list_profiles_in(path):
"""list profiles in a given root directory"""
files = os.listdir(path)
profiles = []
for f in files:
full_path = os.path.join(path, f)
if os.path.isdir(full_path) and f.startswith('profile_'):
profiles.append(f.split('_',1)[-1])
return profiles | 5,326,473 |
def lambda_handler(context):
"""
url_list = [
{'name': 'SERVER1', 'url': 'http://site-url-1.com/ping'},
{'name': 'SERVER2', 'url': 'http://site-url-2.com/ping?key=secure-key'}
]
"""
url_list = get_ping_urls()
#print(url_list)
results = ping.fetch_all(url_list)
print (re... | 5,326,474 |
def test_freshness_in_catchup(looper,
txnPoolNodeSet,
sdk_pool_handle,
sdk_wallet_steward,
tconf, ):
"""
Check that InstanceChange with reason "State signatures are not updated for too long"
... | 5,326,475 |
def print_result_and_exit(embargoed_builds, embargoed_pullspecs, embargoed_releases, as_yaml, as_json):
""" Prints embargo detection result and exit
:param embargoed_builds: list of dicts of embargoed builds
:embargoed_pullspecs: list of embargoed image pullspecs
:embargoed_releases: list of pullspecs o... | 5,326,476 |
def extractLine(shape, z = 0):
"""
Extracts a line from a shape line.
"""
x = shape.exteriorpoints()[0][0] - shape.exteriorpoints()[1][0]
y = shape.exteriorpoints()[0][1] - shape.exteriorpoints()[1][1]
return (x, y, z) | 5,326,477 |
def get_fragility_model_04(fmodel, fname):
"""
:param fmodel:
a fragilityModel node
:param fname:
path of the fragility file
:returns:
an :class:`openquake.risklib.scientific.FragilityModel` instance
"""
logging.warn('Please upgrade %s to NRML 0.5', fname)
node05 = co... | 5,326,478 |
def user_weights():
"""Used to display the avg and recommended amounts of calories to the user"""
print(colors.green + 'The average and healthy amount of calories for a person is about 2100 or less calories per '
'day.\n',
colors.reset)
if '124' >= str(user_weight) ... | 5,326,479 |
def substring_in_list(substr_to_find, list_to_search):
"""
Returns a boolean value to indicate whether or not a given substring
is located within the strings of a list.
"""
result = [s for s in list_to_search if substr_to_find in s]
return len(result) > 0 | 5,326,480 |
def downsample_image(image: np.ndarray, scale: int) -> np.ndarray:
"""Downsamples the image by an integer factor to prevent artifacts."""
if scale == 1:
return image
height, width = image.shape[:2]
if height % scale > 0 or width % scale > 0:
raise ValueError(f'Image shape ({height},{width}) must be div... | 5,326,481 |
def getQueryString( bindings, variableName ):
""" Columns a bunch of data about the bindings. Will return properly formatted strings for
updating, inserting, and querying the SQLite table specified in the bindings dictionary. Will also
return the table name and a string that lists the columns (properly formatted... | 5,326,482 |
def multiplicities(pattern):
""" Return a dictionary keyed by the geodesics in the given pattern, with values equal to the number of times the geodesic occurs."""
g = geodesics(pattern)
ans = {}
x = 0
for i in g:
if i == x:
ans[i] += 1
else:
x = i
... | 5,326,483 |
def show_menu():
""" Shows a menu """
print '================== ' + util.HEADER + 'WORKFLOW MENU' + util.ENDC + ' =================='
print '1) Development - Create a git branch off of staging'
print '2) Merge - Merge your development branch to staging (GitHub)'
print '3) Build - Builds project, and... | 5,326,484 |
def imap4_utf7_decode(data):
"""Decode a folder name from IMAP modified UTF-7 encoding to unicode.
Input is bytes (Python 3) or str (Python 2); output is always
unicode. If non-bytes/str input is provided, the input is returned
unchanged.
"""
if not isinstance(data, bytes):
return byte... | 5,326,485 |
def get_characters(character_path, character_dim):
"""Reads list of characters .txt file and returns embedding matrix and mappings from characters to character ids.
Input:
character_path: path to characters.txt
character_dim: integer
Returns:
emb_matrix: Numpy array shape (len(characters... | 5,326,486 |
def create_data_storage(dxres):
"""
Creates a DataStorage record for the given DNAnexus sequencing results.
Args:
dxres: `scgpm_seqresults_dnanexus.dnanexus_utils.du.DxSeqResults()` instance that contains
sequencing results metadata in DNAnexus for the given srun.
Returns:
... | 5,326,487 |
def french_to_english(french_text: str) -> str:
"""This function translates from french to english
Parameters
----------
french_text : str
french text to translate
Returns
-------
str
translated text
"""
language_translator = translator_instance()
response = lan... | 5,326,488 |
def test_section_delete(api):
""" Verify the ``section_delete`` method call """
SECTION_ID = 1234
api._session.request.return_value = {}
section = api.section_delete(SECTION_ID)
exp_call = mock.call(method=POST,
path=AP['delete_section'].format(section_id=SECTION_ID))
... | 5,326,489 |
async def start_select_city(msg: Message, lenta: LentaClient, repo: Repo, state: FSMContext):
"""
Начало процесса выбора магазина
Отображение доступных городов
"""
city_keyboard = await services.store.get_inline_keyboard_for_cities(lenta)
await AddStoreForm.select_city.set()
# Сохраняем ID ... | 5,326,490 |
def prefit_histograms(
rex_dir: str | Path,
samples: Iterable[str],
region: str,
fit_name: str = "tW",
) -> dict[str, TH1]:
"""Retrieve sample prefit histograms for a region.
Parameters
----------
rex_dir : str or pathlib.Path
Path of the TRExFitter result directory
samples ... | 5,326,491 |
def ymstring2mjd( ymstr ):
"""
The `ymstring2mjd` function enables array input.
Documentation see the `_ymstring2mjd` function.
"""
ymstr = np.array(ymstr,ndmin=1)
ymstr_count = np.size(ymstr)
mjd = np.zeros(ymstr_count,dtype=np.float_)
for ix in range(ymstr_count):
try:
... | 5,326,492 |
def average(l):
""" Computes average of 2-D list """
llen = len(l)
def divide(x):
return x / float(llen)
return list(map(divide, map(sum, zip(*l)))) | 5,326,493 |
def slugify3(text, delim=u'-'):
"""Generates an ASCII-only slug."""
result = []
for word in _punct_re.split(text.lower()):
result.extend(unidecode(word).split())
return unicode(delim.join(result)) | 5,326,494 |
def test_construct_graph():
"""Example-based test that graph construction works correctly.
Uses 4hhb PDB file as an example test case.
"""
file_path = Path(__file__).parent / "test_data" / "4hhb.pdb"
G = construct_graph(pdb_path=str(file_path))
assert isinstance(G, nx.Graph)
assert len(G) =... | 5,326,495 |
def create_phase2_edgemerge_table():
"""phase2_edgemerge retrieves the initial phase 2 ud_edges coordinate from the u_edges and d_edges coordinates."""
fname = "phase2_edgemerge"
global u_edges_plus_d_edges_to_ud_edges
c_u = cb.CubieCube()
c_d = cb.CubieCube()
c_ud = cb.CubieCube()
edge_u = ... | 5,326,496 |
def teacher_registeration(request):
"""
Info: Registeration for the teacher.
Request-Body: email_id -> str
password -> str
image -> file
name -> str
date_of_birth -> str
education_qualification -> JSON
Response: message -> s... | 5,326,497 |
def check_response(response):
""" Checks that a response is successful, raising the appropriate Exceptions otherwise. """
status_code = response.status_code
if 100 < status_code < 299:
return True
elif status_code == 401 or status_code == 403:
message = get_response_data(response)
... | 5,326,498 |
def walk_storage_from_command(command: instances.FilesRelatedCommand,
filesystem: Filesystem
) -> Iterator[Tuple[str, str, str]]:
"""Typical iteration by command settings."""
return walk(command.storage_folder, filesystem,
command.branc... | 5,326,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.