content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def normalize_search_terms(search_terms: str)->str:
"""
Normalize the search terms so that searching for "A b c" is the same as searching for
"a b C", "B C A", etc.
Args:
search_terms (str): Space-delimited list of search terms.
Returns:
(str): Space-delimited search terms, lowerca... | be9afce684c3139d0ee132b37bf5dcec7269a3b2 | 678,391 |
from typing import Set
def candidates_to_bits(candidates: Set[int]) -> int:
"""
Convert a candidates set into its bits representation
The bits are in big endian order
>>> bin(candidates_to_bits({1, 2, 3, 6, 7}))
'0b1100111'
>>> bin(candidates_to_bits({6, 9}))
'0b100100000'
"""
bi... | 0f69cb3515975687d1c83fabf690936667a6cf06 | 678,393 |
def get_compute_op_list(job_content):
"""
Get compute op info list from job content info
:param job_content: tbe compilation content info
:return: compute op info list
"""
op_list = job_content["op_list"]
op_compute_list = []
for op in op_list:
if op["type"] != "Data":
... | dc4cf0a9fbc8ff104aeaba812db533bf574bbc84 | 678,395 |
def remove_namespace(tag, name, ns_dict):
"""Used to remove namespaces from tags to create keys in dictionary for quick key lookup.
Attr:
tag(str): Full tag value. Should include namespace by default.
name(str): The namespace key. Usually the ticker of the company.
ns_di... | 0c85db8481007df4b1e0744a315ab7ec4d110a0d | 678,397 |
from typing import List
def flip_v(matrix: List[List]) -> List[List]:
"""Flip a matrix (list of list) vertically
"""
return matrix[::-1] | e52561c8d8aeec737d585c28d5a6f34324da8d78 | 678,404 |
from typing import Union
def int_conversion(string: str) -> Union[int, str]:
"""
Check and convert string that can be represented as an integer
:param string: Input string
:return: Result of conversion
"""
try:
value = int(string)
except ValueError:
value = string
ret... | a223fcb6194907876156ee4e028cb37b048051c2 | 678,406 |
def str_to_bool(string, truelist=None):
"""Returns a boolean according to a string. True if the string
belongs to 'truelist', false otherwise.
By default, truelist has "True" only.
"""
if truelist is None:
truelist = ["True"]
return string in truelist | bd43763fc211e555b977953ef574d64a2d82eee1 | 678,409 |
def level_to_criticality(level: int) -> str:
"""Translate level integer to Criticality string."""
if level >= 4:
return "Very Malicious"
elif level >= 3:
return "Malicious"
elif level >= 2:
return "Suspicious"
elif level >= 1:
return "Informational"
return "Unknow... | c1933f4a1f38e87b5a54643d49b402c0185fe010 | 678,410 |
def get_title_to_id_dict(titles):
"""Creates a dict mapping each title with an id.
:param titles: list of titles
:type titles: list
:return: dict mapping a title to an id.
:rtype: dict
"""
title_to_id = {title: i for i, title in enumerate(titles)}
return title_to_id | fac39a472da59a24a7db80a73ce33e4b1022d409 | 678,412 |
def timestep(dtime, time, end_time):
"""
calculates the timestep for a given time
Returns the timestep if the calculation isnt overstepping the endtime
if it would overstep it returns the resttime to calculte to the endtime.
:param dtime: timestep
:param time: current time in simulation
:p... | 516ba4df05fa8f472c3f45471b63c01806aa76b2 | 678,413 |
def compose_tbl_filename(
key_names, key_indices=None,
prefix='tbl', suffix='txt',
var_separator='.', idx_separator='-'):
"""compose a file name based on key names
Parameters
----------
key_names : list of str
A list of key names
key_indices : list of str
A l... | e4774d4ebc14f8014e12b2973de178ea364b6f9b | 678,415 |
import random
def _random_value(x = None, min=0, max=10):
"""
(not very eye pleasing ;)
returns a random int between min and max
"""
return random.randint(min,max) | 315300dd21d56885d47448e5b6660a72cffb0bc4 | 678,416 |
import re
def _is_bed_row(bed_row):
"""Checks the format of a row of a bedfile.
The logic is to check the first three fields that should be
chromosome start end."""
if len(bed_row) < 3:
return False
return (
(re.match(r"^chr.+$", bed_row[0]) is not None)
and (re.match(r"^[0... | 187a52230d1b71542c4adc3cd5355a3063cb4844 | 678,417 |
import collections
def group_train_data(training_data):
"""
Group training pairs by first phrase
:param training_data: list of (seq1, seq2) pairs
:return: list of (seq1, [seq*]) pairs
"""
groups = collections.defaultdict(list)
for p1, p2 in training_data:
l = groups[tuple(p1)]
... | f916d4f4eaee8ec8a30a9fc9290fbcac68d4c9c5 | 678,421 |
def gcd(a, b):
"""Calculate Greatest Common Divisor (GCD)."""
return b if a == 0 else gcd(b % a, a) | 366a547c680aa5a36ac42b945acd906607b5efc0 | 678,422 |
def _samples_calls(variant_collection, dataset_id, samples):
"""Count all allele calls for a dataset in variants collection
Accepts:
variant_collection(pymongo.database.Database.Collection)
dataset_id(str): id of dataset to be updated
samples(list): list of dataset samples
Returns:
... | edda3c29aa1b844bf2ddcd2df0fb459f22f739d7 | 678,423 |
import zlib
def decode_gzip(content):
"""Return gzip-decoded string.
Arguments:
- `content`: bytestring to gzip-decode.
"""
return zlib.decompress(content, 16 + zlib.MAX_WBITS) | ddded4185b85774d75af7dba93def4efba669f41 | 678,424 |
from functools import reduce
import operator
def prod(iterable):
"""Take product of iterable like."""
return reduce(operator.mul, iterable, 1) | b0534333e870723e88eec01dd7e765185381b6a7 | 678,425 |
def external(cls):
"""
Decorator.
This class or package is meant to be used *only* by code outside this project.
"""
return cls | d56422d291a3468368fdbdd35cf57d65aa695621 | 678,429 |
def get_tag(body):
"""Get the annotation tag from the body."""
if not isinstance(body, list):
body = [body]
try:
return [b['value'] for b in body if b['purpose'] == 'tagging'][0]
except IndexError:
return None | ce71747e108fe806b68be10732b56aaffadffeac | 678,435 |
def check_is_faang(item):
"""
Function checks that record belongs to FAANG project
:param item: item to check
:return: True if item has FAANG project label and False otherwise
"""
if 'characteristics' in item and 'project' in item['characteristics']:
for project in item['characteristics'... | 24b6a3a827974aa57e69b2afee26ebb91644e748 | 678,444 |
def preprocess_prediction_data(data, tokenizer):
"""
It process the prediction data as the format used as training.
Args:
data (obj:`List[str]`): The prediction data whose each element is a tokenized text.
tokenizer(obj: paddlenlp.data.JiebaTokenizer): It use jieba to cut the chinese strin... | b9fa5fcd65e0e17d0fbeccc68773f1a0678a7cfe | 678,445 |
def ListFeatures(font):
"""List features for specified font. Table assumed structured like GPS/GSUB.
Args:
font: a TTFont.
Returns:
List of 3-tuples of ('GPOS', tag, name) of the features in the font.
"""
results = []
for tbl in ["GPOS", "GSUB"]:
if tbl in font.keys():
results += [
... | 0fb2a1ac5b367d7d711cab7b303d2ba1fd487514 | 678,446 |
def split_string_content(content):
"""
Split the string content and returns as a list.
"""
file_contents = content.split("\n")
if file_contents[-1] == '':
file_contents = file_contents[:-1]
return file_contents | 85706b70a33f81c6546a24c8e2bb1766de7779c2 | 678,455 |
def is_widget(view):
"""
Returns `True` if @view is a widget.
"""
return view.settings().get('is_widget') | db949bb860cd2c29f295ca049c11163192c8e2a8 | 678,457 |
def geom_cooling(temp, alpha = 0.95):
"""
Geometric temperature decreasing procedure allows for temperature variations
after every iteration (k).
It returns a value of temperature such that
T(k+1)=alpha*(T)
Parameters
----------
temp: float
Current temperature.
... | 451deeef629707a9d8a66eb8be1ae88aa9231314 | 678,459 |
import time
def apipoll(endpoint, *args, **kwargs):
"""Poll an api endpoint until there is a result that is not None
poll_wait and max_poll can be specified in kwargs to set the polling
interval and max wait time in seconds.
"""
result = endpoint(*args, **kwargs)
if result is not None:
... | 20ba59ac9d3df192f7fe92e5692fe0bc80f66ac1 | 678,461 |
def multiply(a, b):
"""
>>> multiply(3, 5)
15
>>> multiply(-4, 5)
-20
>>> multiply(-4, -2)
8
"""
iterator = 0
value = 0
if iterator < a:
while iterator < a:
value += b
iterator += 1
else:
while iterator > a:
value -= b
... | 3adf7ff18b8559bb8e1a04d79801f307c264f6bb | 678,465 |
import re
def human2bytes(s):
"""
>>> human2bytes('1M')
1048576
>>> human2bytes('1G')
1073741824
"""
symbols = ('Byte', 'KiB', 'MiB', 'GiB', 'T', 'P', 'E', 'Z', 'Y')
num = re.findall(r"[0-9\.]+", s)
assert (len(num) == 1)
num = num[0]
num = float(num)
for i, n in enumer... | 8ed56b6ea327cdc12b58c662268e54719e568f1d | 678,466 |
def print14list(pair14, shift, molecule):
"""Generate pair 14 list line
Parameters
----------
pair14 : Angle Object
Angle Object
shift : int
Shift produced by structural dummy atoms
molecule : molecule object
Molecule object
Returns
-------
pair14 : str
... | 94b92d8b9acdc5d8efe25bd90fa53ca293e1fd88 | 678,467 |
import struct
def readu8(file):
""" Reads an unsigned byte from the file."""
data = file.read(1)
return struct.unpack("B", data)[0] | 1d8de9d2e056c43c2fe93c40892cf9bd285a83ff | 678,468 |
def is_float(istring):
"""Convert a string to a float.
Parameters
----------
istring : str
String to convert to a float.
Returns
-------
float
Converted float when successful, ``0`` when when failed.
"""
try:
return float(istring.strip())
except Exceptio... | 0d0af19566e724f7433d8879a8445d8023c1b622 | 678,473 |
from typing import List
def prime_factors(n: int) -> List[int]:
"""Return an ascending list of the (greather-than-one) prime factors of n.
>>> prime_factors(1)
[]
>>> prime_factors(2)
[2]
>>> prime_factors(4)
[2, 2]
>>> prime_factors(60)
[2, 2, 3, 5]
"""
factors = []
d = 2
while d * d <=... | 605e1d05d6f47ab46ac48290de3d0dbeca0f948e | 678,474 |
def _proposed_scaling_both(current, desired):
"""
identify a x and y scaling to make the current size into the desired size
Arguments
---------
current : tuple
float tuple of current size of svg object
desired : tuple
float tuple of desired size of svg object
Returns
--... | 1db39b32a951a0944104d6011c6f399d926d50fa | 678,477 |
def prometheus_worker_job_count(prometheus, testconfig):
"""
Given a type of a worker job (ReportJob or NotifyJob), returns the value of that metric
"""
def _prometheus_worker_job_count(job_type):
metric_response_codes = prometheus.get_metric(
f"apisonator_worker_job_count{{namespace... | 22b41e5d3b97e97edacf120e50d50ee77e741d44 | 678,478 |
def truncate_descriptions(requested_user_rooms):
"""
Cut descriptions if too long
"""
for i in range(0, len(requested_user_rooms)):
if len(requested_user_rooms[i]['description']) >= 85:
requested_user_rooms[i]['description'] = requested_user_rooms[i]['description'][0:85] + "..."
... | 002f0d9cf5d9a9bd67e08c56b4301fe9c67f5140 | 678,479 |
def calculate_expected_wins(win_rate, num_games):
"""Calculate current expected wins"""
expected_wins = win_rate * float(num_games)
result = int(round(expected_wins, 0))
return result | 5f979a861a0fae1e0fe654c9cc4c9ccf6583b35e | 678,484 |
def get_virtualenv_dir(version):
"""Get virtualenv directory for given version."""
return "version-{}".format(version) | 1b292b48f9c5ce72304019ecb83a1befe25eaf77 | 678,490 |
def convert_timestamp(timestamp: str) -> int:
"""
Converts a timestamp (MM:SS) to milliseconds.
"""
timestamp_list = timestamp.split(":")
minutes = timestamp_list[0]
seconds = timestamp_list[1]
minutes_in_ms = int(minutes) * 60 * 1000
seconds_in_ms = int(seconds) * 1000
total_ms = m... | 7133709d3d5ff76661889bef48301bd0912047d4 | 678,491 |
def chk_keys(keys, src_list):
"""Check the keys are included in the src_list
:param keys: the keys need to check
:param src_list: the source list
"""
for key in keys:
if key not in src_list:
return False
return True | 48706a1f39c06cf79b107ca67eb0a5c5e202fe08 | 678,492 |
def field(fields, **kwargs):
"""Helper for inserting more fields into a metrics fields dictionary.
Args:
fields: Dictionary of metrics fields.
kwargs: Each argument is a key/value pair to insert into dict.
Returns:
Copy of original dictionary with kwargs set as fields.
"""
f = fields.copy()
f.... | c197c458eabebc51138e15182d1485580e33b016 | 678,494 |
def get_name(model, index: int):
"""Get the input name corresponding to the input index"""
return model.inputs[index] | 6620098f8fb99b18a37aed4ca4f8a28f038c8c79 | 678,497 |
def chunkString(string, length):
"""This function returns a generator, using a generator comprehension.
The generator returns the string sliced, from 0 + a multiple of the length of the chunks,
to the length of the chunks + a multiple of the length of the chunks.
Args:
string (String): ... | 819be7b7e234338ffc36450602e2b53bda2034a9 | 678,500 |
def post_process_headways(avg_headway, number_of_trips_per_hour, trip_per_hr_threshold=.5,
reset_headway_if_low_trip_count=180):
"""Used to adjust headways if there are low trips per hour observed in the GTFS dataset.
If the number of trips per hour is below the trip frequency interval... | df7f8de77e1e0828b00f3f0c556ccfce40e5206a | 678,501 |
def sop_classes(uids):
"""Simple decorator that adds or extends ``sop_classes`` attribute
with provided list of UIDs.
"""
def augment(service):
if not hasattr(service, 'sop_classes'):
service.sop_classes = []
service.sop_classes.extend(uids)
return service
return ... | adfb06e19930cf82965b3beb024edb8dada05fd9 | 678,505 |
import re
def parse_show_ip_ecmp(raw_result):
"""
Parse the 'show ip ecmp' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show ip ecmp in a \
dictionary of the form:
::
{
'global_status': True,
... | 3ae0d2ae6bae626691d1c58062a55c3f83013798 | 678,508 |
import sympy
def DfjDxi(DN,f):
"""
This method defines a gradient. Returns a matrix D such that D(i,j) = D(fj)/D(xi)
This is the standard in fluid dynamics, that is:
D(f1)/D(x1) D(f2)/D(x1) D(f3)/D(x1)
D(f1)/D(x2) D(f2)/D(x2) D(f3)/D(x2)
D(f1)/D(x3) D(f2)/D(x3) D(f3)/D(x3)
Ke... | fe99dc5d4e3b7377853f0d93a6c137e44e6f5a6b | 678,509 |
def manhattan_distance(p1, p2):
"""
Precondition: p1 and p2 are same length
:param p1: point 1 tuple coordinate
:param p2: point 2 tuple coordinate
:return: manhattan distance between two points p1 and p2
"""
distance = 0
for dim in range(len(p1)):
distance += abs(p1[dim] - p2[di... | 8edc13b373fa14ea168481923cf4d243c3783b9c | 678,511 |
def tags_with_text(xml, tags=None):
"""Return a list of tags that contain text retrieved recursively from an
XML tree
"""
if tags is None:
tags = []
for element in xml:
if element.text is not None:
tags.append(element)
elif len(element) > 0:
tags_with_... | a922034e1d04b98e0fbcebbae812a1e88109607d | 678,512 |
def generate_text_notebook() -> str:
"""Generate `notebook.md` content."""
content = (
"""\
---
file_format: mystnb
kernelspec:
name: python3
---
# Text-based Notebook
```{code-cell}
print("Hello, World!")
```
""".rstrip()
+ "\n"
)
return content | 2cf2a5277840bfd6df5cfffb87b5692d2f95830c | 678,513 |
def build_vector(image, binary=True):
"""
图像转一维特征向量
:param image: pillow Image object with mode 1 or mode L
:param binary: 黑白图是否生成为0,1向量
:return: list of int
"""
vector = []
for pixel in image.getdata():
if binary:
vector.append(1 if pixel == 255 else 0)
else:... | fffb83574dbe438cadf3b29a4600f36ad70471bb | 678,516 |
def combine_docs(docs):
"""
Combine documents from a list of documents.
Only combines if the element is a string.
Parameters
----------
`docs` : `list`. Documents to combine
Returns
-------
`string` : Combined string of documents
"""
combined_docs = ""
for doc in docs:
... | 4aaa59d8be3f605237b70425562433c0e6b117e4 | 678,524 |
from datetime import datetime
def restore_timestamp(formatted_timestamp):
"""Return a timestamp from a formatted string."""
return datetime.strptime(formatted_timestamp,
"%Y-%m-%d %H:%M:%S").strftime('%Y%m%d%H%M%S') | 62e863f02ec2d93b19d4f3aa934ea8512957c5f4 | 678,528 |
def div(n, d):
"""Divide, with a useful interpretation of division by zero."""
try:
return n/d
except ZeroDivisionError:
if n:
return n*float('inf')
return float('nan') | e5828b600bf6632a2b86cf8c12ab3fcc054be768 | 678,530 |
def wrap(ag, compound='atoms'):
"""
Shift the contents of a given AtomGroup back into the unit cell. ::
+-----------+ +-----------+
| | | |
| 3 | 6 | 6 3 |
| ! | ! | ! ! |
| 1-2-|-5-8 -> |... | 42f46f73e9bf0317cc00d79e257726cff5ecdaf9 | 678,533 |
def parse_scripts(scp_path, value_processor=lambda x: x, num_tokens=2):
"""
Parse kaldi's script(.scp) file
If num_tokens >= 2, function will check token number
"""
scp_dict = dict()
line = 0
with open(scp_path, "r") as f:
for raw_line in f:
scp_tokens = raw_line.strip().... | db22596c8639c2e7d81d3fe749fc235a6281d0c3 | 678,534 |
import json
def read_json(fjson):
"""
Args:
fjson (str) - file name of json to read
Returns:
dictionary stored in fjson
"""
with open(fjson) as f:
return json.load(f) | d391c7d1aa7e2a74e1af16018e61bc63b68d2a88 | 678,539 |
def map_pathogen_id_to_name(pathogen_id):
"""
"""
mapping = {
"p00": "Acinetobacter baumannii",
"p01": "Baceroides fragilis",
"p02": "Burkholderia cepacia",
"p03": "Candida albicans",
"p04": "Candida giabrata",
"p05": "Candida parapsilosis",
"p06": "Ca... | 2ef24ff2876320ce6a7f7da72376c412199eb7ba | 678,544 |
def get_unique_covered_percentage(fuzzer_row_covered_regions,
fuzzer_col_covered_regions):
"""Returns the number of regions covered by the fuzzer of the column
but not by the fuzzer of the row."""
unique_region_count = 0
for region in fuzzer_col_covered_regions:
... | 83b4b69ced91c3a1d279fe6b2fe1b43ce3131b61 | 678,545 |
def check_mid_low(device_name):
"""Check if a device domain contains mid or low"""
domain, *_ = device_name.split("/")
if "mid" in domain or "low" in domain:
return True
return False | de1271bab37057aed4850538ab7b4d46baba411a | 678,546 |
def getSonarData(sensor, angle):
"""
Transmits the sonar angle and returns the sonar intensities
Args:
sensor (Ping360): Sensor class
angle (int): Gradian Angle
Returns:
list: Intensities from 0 - 255
"""
sensor.transmitAngle(angle)
data = bytearray(getattr(sensor, '_... | d007a192a5fe2cd2af9616638e15010b8e820477 | 678,551 |
def _validate_params_epaipm(etl_params):
"""Validate the etl parameters for EPA IPM.
Args:
etl_params (iterable): dictionary of inputs
Returns:
iterable: validated dictionary of inputs
"""
epaipm_dict = {}
# pull out the etl_params from the dictionary passed into this function
... | 6a1737503ecaad0607de9e165d1bf9392dc9a445 | 678,555 |
import random
def generate_emoji(num_emojis: int) -> str:
""" Generates a psuedo-random list of emojis with pasta sprinkled in """
emojis = ["🙄", "😙", "😐", "🤤", "😤", "😲", "😬", "😭", "🥵", "🥺", "🤠", "🤫", "😳", "😢"]
output: str = ""
for _ in range(num_emojis):
output += random.choice(... | 593d00e6c072f266f1c219fab42c31d88bf0f4b3 | 678,561 |
def try_attribute(node, attribute_name, default=None):
"""Tries to get an attribute from the supplied node. Returns the default
value if the attribute is unavailable."""
if node.hasAttribute(attribute_name):
return node.getAttribute(attribute_name)
return default | 4edc2e42be001d200e53b820a6c14de55af46d87 | 678,562 |
import re
def parse_size(size):
"""Parse a size, kinda like 10MB, and return an amount of bytes."""
size_re = re.compile(r'^(\d+)([GMK]?B)$')
match = size_re.match(size.upper())
if not match:
raise ValueError("Invalid size %r" % size)
amount, unit = match.groups()
amount = int(amount)
... | ada427b4c7f803bd0c90e134f0c2e87af4ac834c | 678,567 |
def convert_email(value: str) -> str:
"""Convert email domain from student to employee or vice versa"""
user, domain = value.split('@')
if domain.startswith('st.'):
return f"{user}@{domain[3:]}"
else:
return f"{user}@st.{domain}" | b927a521f379698bcc57c125c39de63a5552d9a6 | 678,568 |
def intersection(r1, r2):
"""Calculates the intersection rectangle of two regions.
Args:
r1, r2 (dict): A dictionary containing {x1, y1, x2, y2} arguments.
Returns:
dict or None: A dictionary in the same fashion of just the
intersection or None if the regions do not int... | 5c435866d36f4dfffa13c443a04ede9beab6e932 | 678,572 |
def get_label_name_from_dict(labels_dict_list):
"""
Parses the labels dict and returns just the names of the labels.
Args:
labels_dict_list (list): list of dictionaries
Returns:
str: name of each label separated by commas.
"""
label_names = [a_dict["name"] for a_dict in labels... | 3b9f429438ba26f997660bc0731bc6a79a053657 | 678,576 |
def _FormatToken(token):
"""Converts a Pythonic token name into a Java-friendly constant name."""
assert str(token).startswith('Token.'), 'Expected token, found ' + token
return str(token)[len('Token.'):].replace('.', '_').upper() | 96f8e2a418daa9ea44b2933b35ace88f6d0cc92b | 678,577 |
def is_fun_upd(t):
"""Whether t is fun_upd applied to three parameters, that
is, whether t is of the form f (a := b).
"""
return t.is_comb('fun_upd', 3) | 04d1eeaaff7a92f2438a51ebdb55ce1e52bdc011 | 678,580 |
def select_field(features, field):
"""Select a field from the features
Arguments:
features {InputFeatures} -- List of features : Instances
of InputFeatures with attribute choice_features being a list
of dicts.
field {str} -- Field to consider.
Returns:
[list] -- List ... | 13912cf5bf9d2920799c30376be5d4b368d6aad9 | 678,583 |
import re
def purify_app_references(txt: str) -> str:
"""
Remove references to `/app`.
"""
txt = re.sub("/app/", "", txt, flags=re.MULTILINE)
return txt | 3461d9fa4e6e86918919b3b635fa3aa0c8205344 | 678,584 |
def paths_from_issues(issues):
"""Extract paths from list of BindConfigIssuesModel."""
return [issue.path for issue in issues] | a1a105058f5682fd6c680ab44701d83161157a4b | 678,586 |
def get_hosts_descriptions(hosts_scans):
"""
Get the hosts descriptions
Args:
hosts_scans (list[dict]): hosts scans information.
Returns:
List[dict]: images descriptions.
"""
return [
{
"Hostname": scan.get("hostname"),
"OS Distribution": scan.ge... | 2801797123bfb724d918b95fcd88cd5d41204431 | 678,587 |
def draw_rectangle(image=None, coordinates=None,
size=None, color=None):
"""
Generate a rectangle on a given image canvas at the given coordinates
:param image: Pillow/PIL Image Canvas
:param coordinates: coordinate pair that will be the center of the rectangle
:param size: tuple with the x... | ff492e256594ef562d58a8d9fdce0c1b6b10e99b | 678,591 |
def _get_real_chan_name(chan):
""" Get the real channel name
Channels with a light group will have the light group
appended to the name
"""
ch_name = chan.channel_name
lgt_grp = chan.light_group.strip()
if lgt_grp != '' and lgt_grp not in ch_name:
ch_name = '%s_%s' % (ch_name, lgt_gr... | a6e58188599bb17757fb93c5e04d8fc127bca84a | 678,598 |
def getOutputsNames(net):
"""Get the output names from the output layer
Arguments:
net {network} -- Yolo network
Returns:
list -- List of names
"""
layersNames = net.getLayerNames()
return [layersNames[i[0] - 1] for i in net.getUnconnectedOutLayers()] | 502c95c0ad37edcce2da454e42aae4d07ec8dc7b | 678,601 |
from typing import List
def ds_make(n: int) -> List[int]:
"""
Make n subsets containing the numbers 0 to n - 1.
"""
# The value of element i is the parent of that set
# If parent is itself then it's the root
return [i for i in range(n)] | ea1b0266751cedb85a8fe8ea8be1ce5bc45a68b9 | 678,602 |
import torch
def batched_concat_per_row(A, B):
"""Concat every row in A with every row in B where
the first dimension of A and B is the batch dimension"""
b, m1, n1 = A.shape
_, m2, n2 = B.shape
res = torch.zeros(b, m1, m2, n1 + n2)
res[:, :, :, :n1] = A[:, :, None, :]
res[:, :, :, n1:] ... | 76da3c7f344c0ceddf74e65fd4aae749731bb0a4 | 678,604 |
def process_dataset(dataset, labeler):
"""Labels all items of the dataset with the specified labeler."""
return {item: labeler.label_object(item, true_description) for item, true_description in dataset.items()} | 9e69704555e5129b5a015160e37db6a87a381dd8 | 678,606 |
def user_info(
first_name,
last_name,
**profile):
"""Function that builds user information."""
profile['firstname'] = first_name
profile['lastname'] = last_name
return profile | c7108061000dab067f3cece044486c906aa67e90 | 678,612 |
def harmonic_mean(frequencies1, frequencies2):
"""Finds the harmonic mean of the absolute differences between two frequency profiles,
expressed as dictionaries.
Assumes every key in frequencies1 is also in frequencies2
>>> harmonic_mean({'a':2, 'b':2, 'c':2}, {'a':1, 'b':1, 'c':1})
1.0
>>> har... | c8701a5df020bd8f4d1655f406a13ffdf92cf362 | 678,613 |
def dnfcode_key(code):
"""Return a rank/dnf code sorting key."""
# rank [rel] '' dsq hd|otl dnf dns
dnfordmap = {
u'rel':8000,
u'':8500,
u'hd':8800,u'otl':8800,
u'dnf':9000,
u'dns':9500,
u'dsq':10000,}
... | fb1be042adb6fd25371c7b382df68f0c7e34d926 | 678,614 |
import itertools
def countCombosSumEqual(sm: int, nums: list) -> int:
"""
Count all possible combos of elements in nums[] such that sum(combo) == sm
Args:
sm (int): the sum to match.
nums (list): list of positive integers.
Returns:
int: resulting count.
If nums[0] == sm,... | 6ab5af1a6b26d6043b677f607a56e989d6d45200 | 678,617 |
import re
def titleize(name):
""" Titleize a course name or instructor, taking into account exceptions such as II. """
name = re.sub(r'I(x|v|i+)', lambda m: 'I' + m.group(1).upper(), name.strip().title())
name = re.sub(r'(\d)(St|Nd|Rd|Th)', lambda m: m.group(1) + m.group(2).lower(), name)
name = re.su... | b4eb58ec092d89d23d1e878a8b0de077ec17c551 | 678,624 |
def get_prediction_results(data, labels, predict_prob, vocab_dict, label_dict):
"""
Get the prediction and the true labels with the words in conll format
@params : data - unpadded test data
@params : labels - unpadded test labels
@params : predict_prob - the predicted probabilities
@params : voc... | b3b1cb1434fcf778252784d5cdd16e277465eff6 | 678,625 |
def get_index_of_user_by_id(id_value, data):
"""Get index of user in list by id"""
for count, item in enumerate(data):
if item['id'] == id_value:
return count
return None | 4bdf8001224aa6b96343e0bce0354fc59d6e962b | 678,626 |
def starts_new_warning(line) -> bool:
"""Return true if the line starts a new warning."""
return "warning:" in line | 10e6871d3ae10ec4d856b3dd4b966a5050cf06f7 | 678,627 |
def find_path(start, end, parents):
"""
Constructs a path between two vertices, given the parents of all vertices.
Parameters
----------
start : int
The first verex in the path
end : int
The last vertex in the path
parents : list[int]
The parent of a vertex in its pa... | f38f4f2fb9631476f20372113066ef94dc3d23e0 | 678,628 |
def get_class_image_ids(self, class_name=None, class_id=None):
""" Retrieves image_ids associated with class_name or class_id """
return self.get_class_info(class_id=class_id, class_name=class_name)['image_ids'] | c354cf627ba3fff7f19f54655c9997a55cfa11dc | 678,631 |
from typing import Union
def _get_vars(symbol: Union[str, int]) -> str:
"""Get the javascript variable declarations associated with a given symbol.
These are adapted from plotly.js -> src/components/drawing/symbol_defs.js
Args:
symbol: The symbol whose variables should be retrieved.
Returns... | 487a93b649ce4c35b3cbea59cc931e8f4c68e0b0 | 678,637 |
import re
def make_consts_consecutive(s):
"""
The given phenotype will have zero or more occurrences of each const c[0],
c[1], etc. But eg it might have c[7], but no c[0]. We need to remap, eg:
7 -> 0
9 -> 1
so that we just have c[0], c[1], etc.
:param s: A given phenotype str... | dad03e955efb8f7e78e9e3bfc13a7a3204689691 | 678,638 |
def normalized_value(xs):
""" normalizes a list of numbers
:param xs: a list of numbers
:return: a normalized list
"""
minval = min(xs)
maxval = max(xs)
minmax = (maxval-minval) * 1.0
return [(x - minval) / minmax for x in xs] | 8036e8041982ebbb5ad21a8f8468797b1ea3e58c | 678,641 |
import yaml
def _yaml_reader(yaml_file):
"""Import the YAML File for the YOLOv5 data as dict."""
with open(yaml_file) as file:
data = yaml.safe_load(file)
return data | fdbb318a5e8176dcf7072643d40fdc433de0b6d4 | 678,642 |
def valid_for_gettext(value):
"""Gettext acts weird when empty string is passes, and passing none would be even weirder"""
return value not in (None, "") | b338d33b13364410cc9b4af5bf5d4a74cab1bef1 | 678,644 |
def convert_indices(direction, x, y):
"""
Converts indices between Python and Fortran indexing, assuming that
Python indexing begins at 0 and Fortran (for x and y) begins at 1.
In Tracmass, the vertical indexing does begin at zero so this script
does nothing to vertical indexing.
Examples:
... | 3984174fa435cc2e8694fff0b516ec7d87d489fe | 678,645 |
def get_or_none(model, **kwargs):
"""
Gets the model you specify or returns none if it doesn't exist.
"""
try:
return model.objects.get(**kwargs)
except model.DoesNotExist:
return None | 590d18d17eb39f8524473f457faebf37f0fb771d | 678,646 |
def armijo(fun, xk, xkp1, p, p_gradf, fun_xk, eta=0.5, nu=0.9):
""" Determine step size using backtracking
f(xk + alpha*p) <= f(xk) + alpha*nu*<p,Df>
Args:
fun : objective function `f`
xk : starting position
xkp1 : where new position `xk + alpha*p` is stored
p : search ... | 0b44b06fe6db1f778dbc22995a2800ebbf6f051a | 678,650 |
def processObjectListWildcards(objectList, suffixList, myId):
"""Replaces all * wildcards with n copies that each have appended one element from the provided suffixList and replaces %id wildcards with myId
ex: objectList = [a, b, c_3, d_*, e_%id], suffixList=['0', '1', '2'], myId=5 => objectList = [a, b, c_3, e... | aaa2a59c36822a94b51d0b08a617b671b8429513 | 678,653 |
def get_remote_file_name(url):
"""Create a file name from the url
Args:
url: file location
Returns:
String representing the filename
"""
array = url.split('/')
name = url
if len(array) > 0:
name = array[-1]
return name | 5591b5ea17344b08d09b85548c83061bcd4e3162 | 678,654 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.