content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def translate_fun_Number(x):
"""Converts Number(string) to
__extrafunc_Number(string)
Args:
x (str): JavaScript code to translate.
Returns:
str: Translated JavaScript code.
Examples:
>>> from ee_extra import translate_fun_parseFloat
>>> translate_fun_parseFloat(x =... | e1354411067e583dc948c95b8d0318083e943ba8 | 3,619,023 |
def pad_2d_array(arr, n_column, value=-1):
"""Pad 2D array with columns composed of -1.
Argument:
arr: A 2D array denoting the stimulus set.
n_column: The total number of columns that the array should
have.
value (optional): The value to use to pad the array.
Returns:
... | 61dd20797c9e9c678d2dc425707b79d974bffaac | 3,619,024 |
def yddot_d_z(mu, state, r_15_inv, r_25_inv):
""" Partial of x acceleration with respect to z
Args:
mu (float): three body constant
state (np.array): 6 dimensional state vector of
(x, y, z, dx, dy, dz)
r_15_inv (float): 1 / norm(r_1)^(5) where r_1 is the vector from the
... | 18281dc5dffdef99e38c33e28cc26a0e9d9aa262 | 3,619,026 |
def decypher(text):
"""
Decypher file name into descriptive label for legend
"""
# name shortcuts
help_dict = {"h": "Target/Hunt AI", "p": "Probabilistic AI", "r": "Random AI"}
final = ""
t_split = text.split("-")
final += help_dict[t_split[0]]
# hunt/target AI branch
if t_spli... | bf4db039bcc86d8d874a29dbf301cc91fa461560 | 3,619,027 |
from typing import OrderedDict
def get_chattering_species(atom_followed="C"):
"""
return chattering species
the chatteing reaction infomation is just for reference, will not use it
as long as the paired chattering species is provided, should be fine
better make them in the same order
"""
f... | 334b92ac2db17047c8c934b13961615aafda3621 | 3,619,028 |
def processHostname(hostname):
"""
Check if the received hostname is a bot, based on our list
"""
if regexp_hostname.search(hostname.lower()):
return True
return False | 1b2026098731db9c9fd9a0b493d1fa883beef6c8 | 3,619,029 |
from typing import List
def format_beneficial_tags(
all_sorted_selection: List[MetadataPrioritySet]
) -> List[str]:
"""Formats the operators so that only combinations of tags that
have 'beneficial' results (ie. operators with only rarity 4, 5, 6)
are formatted into the returned list of messages.""... | 2c41d9e719eff7565b0d4e865075bae42d7aeb88 | 3,619,030 |
def guided_wavelength(freq,
line_width,
line_gap,
substrate_thickness,
film_thickness,
dielectric_constant=11.45):
"""A simple calculator to determine the guided wavelength of a planar CPW
transmission ... | dc4e62dc9cd19ed07fb09273f4ddd58078a13712 | 3,619,031 |
from typing import Optional
def get_build_hash(fallback: Optional[str] = None) -> str:
"""Get build hash"""
build_hash = environ.get(ENV_GIT_HASH_KEY, fallback if fallback else "")
if build_hash == "" and fallback:
return fallback
return build_hash | 4888b0a43639c88a43321d0ae61e35bea328348a | 3,619,032 |
from typing import Optional
def segment_mean(data: jnp.ndarray,
segment_ids: jnp.ndarray,
num_segments: Optional[int] = None,
indices_are_sorted: bool = False,
unique_indices: bool = False):
"""Returns mean for each segment.
Args:
data: the ... | de146b43a335915eb8041b1cbab7cce538d9efe6 | 3,619,033 |
import re
def compute_rq_type(oslevel, empty_list):
"""Compute rq_type.
return:
Latest when oslevel is blank or latest (not case sensitive)
Latest when oslevel is a TL (6 digits) and target list is empty
TL when oslevel is xxxx-xx(-00-0000)
SP when oslevel is xxxx-xx-x... | 753e54d4858a8d1248958c15bbd6b1a0cbc9b02e | 3,619,034 |
def custom_repr(repr_text):
"""Function decorator to allow setting a custom repr for a class method.
References:
https://stackoverflow.com/a/32215277
"""
# the decorator itself
def method_decorator(method):
# Wrap the method in our own descriptor.
class CustomReprDescripto... | 95f4a0cd4077571919be5933b6c205df539a61bd | 3,619,035 |
def color_map_cyclic(color_normalized: float) -> (float, float, float):
"""
Maps normalized value to color, cyclic.
Note: For JIT to work, this must be declared at the top level.
@param color_normalized: Normalized color value
@return: R, G, B
"""
hue = (color_normalized + 1 / 6) % 1
x... | 9be1c9b8b4f7e9dccf16fed54525ca8932bd7ee9 | 3,619,037 |
def get_model_names():
"""
Returns all available model names as a list of strings.
"""
model_names = []
for key, value in default_models.items():
model_names.append(key)
return model_names | af9b0a9c43e43b6a692bf6153ea6c2be940398cb | 3,619,039 |
def cli():
"""
Manually check whether names are available on PyPI.
Runs an infinite loop in the command line, where a name can be input
and the avilability status of that name on PyPI is printed.
Notes
-----
Please note that the input name is presently un
"""
while (True): # UI Lo... | b9a7828dfe020f45161e64b481a6865db32bbf82 | 3,619,040 |
def itransduce(xform, rf, init, coll=_Undefined):
"""
itransduce(xform, rf, init, coll) -> reduction result
*itransduce(xform, rf, coll) -> reduction result*
Returns the result of reducing an iterable with a transformation.
Reduces `coll` using a transformed reducing function equal to
``xform(... | 3fc0f34aacbc597e65e5e10f60b64d4699f6f1fe | 3,619,041 |
def lseek_syscall(fd, offset, whence):
"""
http://linux.die.net/man/2/lseek
"""
# check the fd
if fd not in filedescriptortable:
raise SyscallError("lseek_syscall","EBADF","Invalid file descriptor.")
# if we are any of the odd handles(stderr, sockets), we cant seek, so just report we are at 0
if ... | e5f595dd4a6578288a1a6723d51248d4fc9cd988 | 3,619,042 |
from typing import Sequence
from typing import Tuple
def convert_to_embedded(
compressed_messages: Sequence[ndarray],
message_shape: Sequence[int],
tail_capacity: int,
) -> Tuple[ndarray, ndarray]:
"""
Embed a truncated list of byte arrays into equal-size arrays.
Args:
compressed_mess... | 7f93b62909f6629bf1a144ea175ec22166c1bffd | 3,619,043 |
def lambda_handler(event, context):
"""
Manages Let's Encrypt certificates in ACM.
"""
cert = find_latest_cert()
if not cert or get_days_remaining(cert) <= 30:
cert_data = provision_cert()
cert = import_cert(cert_data)
return {
'Certificate': cert.Certificate,
... | 38173baf7f3bf55d60e6c0d9e5d7fff8cecd0278 | 3,619,044 |
def get_full_contentsection_list(course, filter_children=True):
"""Return a list of ContentSections with material and a list of all material for this course."""
level2_items = {} # level2_items gets filled lazily
groups_with_children = set([]) # ContentGroups that h... | 1f131dbfee7c54ba20c59fbbf010d1855d05f361 | 3,619,045 |
def vaecf(users_number: int, items_number: int):
"""
:param users_number:
:param items_number:
:return:
"""
input_layer = tf.keras.layers.Input(shape=(items_number,), name='UserScore')
enc = tf.keras.layers.Dense(512, activation='selu', name='EncLayer1')(input_layer)
lat_space = tf.ke... | ebf00562f55be1df785dfea71d3dfb5150338447 | 3,619,046 |
def mode(series):
"""Computes the mode."""
if series.isnull().all():
return np.nan
return series.mode()[0] | 01deea60914eadae08e90b2b1bc89533bf665843 | 3,619,047 |
def lbeta(x, y, name=None):
"""Returns log(Beta(x, y)).
This is semantically equal to
lgamma(x) + lgamma(y) - lgamma(x + y)
but the method is more accurate for arguments above 8.
The reason for accuracy loss in the naive computation is catastrophic
cancellation between the lgammas. This method avoids t... | 89e311e48f8a5ce89a57daf877c478a0d4dc9a74 | 3,619,048 |
def _xor_guess_key_size(ct, top_results=5, max_key_size=64):
"""Returns a list of the most likely key sizes for a ciphertext
xored with a repeating key.
"""
distances = []
for ksize in range(2, max_key_size+1):
chunks = chunked(ct, ksize)
hammings = [hamming_bin(chunks[i], chunks[i+... | 75957c55fedd0747e27f400001f12464bfe60f3a | 3,619,049 |
def filter_even_devices(nr):
"""
Filter the hosts inventory, using a filter function to
find devices which match what is considered an even number host.
:param nr: An initialised Nornir inventory, used for processing.
:return target_hosts: The targeted nornir hosts after being
processed throug... | b3f1d9aaa670cb12b7d0b11ee976a9ef0305e879 | 3,619,050 |
import re
def convert_input_paths(argo_json):
"""
argo aggregation is not valid json as properties are not enclosed in quotes:
flow/step/[{task-id:flow-step-3119439657},{task-id:flow-step-195521861},{task-id:flow-step-3020891073}]
Parameters
----------
argo_json
Returns
-------
l... | 2a1e5ddd378546343d5532f304145cb2157244b5 | 3,619,051 |
def _constant_i32(value: int):
"""Emits a constant i32 value."""
return d.ConstantOp(
d.IntegerType.get_explicit(32),
ir.IntegerAttr.get(ir.IntegerType.get_signless(32), value)).result | 1461327750d5d22c13cc2034701f5f14e8e4d2b5 | 3,619,052 |
def replace_var(content, variables_mapping):
"""将 url 中带有参数的变量替换为真实的值
:param content: url 地址,如 https://mubu.com/list?code=$code
:param variables_mapping: 要替换的真实的值
:return:
"""
matched = variable_regex_compile.match(content)
if not matched:
return content
var_name_code = matched[1... | a32893f81d1d0d726f2ef5316c91881cd370bf3c | 3,619,053 |
def get_ur(df):
"""
Method of getting user-rating pairs
Parameters
----------
df : pd.DataFrame, rating dataframe
Returns
-------
ur : dict, dictionary stored user-items interactions
"""
ur = defaultdict(set)
for _, row in df.iterrows():
ur[int(row['user'])].add(int(... | 5a7ff213dc813f56660195100962f3536211b9be | 3,619,054 |
def field_popularity(data):
"""
Computes the number of different fields that each paper is about by taking the number of fields in 'fields_of_study'
Input:
- df['fields_of_study']: dataframe (dataset); 'fields_of_study' column [pandas dataframe]
Output:
- Field varie... | 9fdefa880d2bc39c6f18d68cec2a85685a7cb164 | 3,619,055 |
def pubmed_local10k():
"""Hparams for Meena local attention model."""
hparams = sparse_transformer_local()
hparams.max_length = 10240
hparams.batch_size = 10240
hparams.max_target_length = 512
hparams.hidden_size = 256
hparams.embedding_dims = 256
hparams.num_encoder_layers = 4
hparams.num_decoder_lay... | 6a8ca09d46d5932d0740fe4ab3a090aa29909590 | 3,619,056 |
from typing import Mapping
def update_dict(d, u):
"""Return updated dict.
http://stackoverflow.com/a/3233356
:param d: dict
:type d: dict
:param u: updated dict.
:type u: dict
:rtype: dict
"""
for k, v in u.items():
if isinstance(v, Mapping):
r = update_dict(... | 5c855e4d66afee04887fccea2ee8154cd8e40ea5 | 3,619,057 |
import random
from datetime import datetime
def individual_run(individual: Network) -> Network:
"""
An individual run
"""
random.seed(datetime.now())
mario = SuperMario()
player = Joypad(JoypadSpace(mario, MOVEMENT))
while mario.ram[0x0009] < INITIAL_THRESHOLD:
player.press((Butto... | 15d1e4cd6aa2b07674ffb25a03ca43f97bad84c7 | 3,619,058 |
import numpy
import pandas
def parseBamReadcountIndel(row):
"""Parsing indels only"""
# first split ref data
ref_split = row[row['REF']].split(':')
ref_split = ref_split[:1] + [float(x) for x in ref_split[1:]]
# now arrgegate information for alt allels
possib_alt = ['INDEL', 'INDEL1', 'INDEL2'... | a14b3cd5573ca2381b6284e8420a78b9d0763c48 | 3,619,059 |
def loadDataFrame(filename, logger):
""" Loads the file into a pandas dataframe
Args:
filename - Path to file
"""
dataframe = pd.read_excel(io=filename, header=0, na_values=['[]', '', 'NaN'])
logger.info("Finished Loading File: {} ".format(filename.split('\\')[-1]))
return dataframe | 5c994c1f9d4db5a54224ad616c4d28476d241894 | 3,619,060 |
import requests
def get_ui_search_gene_project_donor_counts(url):
"""
if we look at the implementation of this endpoint, there are no filters
http://bit.ly/2hfku5a So, redact the response strip off all projects
not in white list
"""
# if no whitelist_projects, abort
whitelist_projects = _w... | 02aed723e17c86e9ab669f7b563488c6d1651958 | 3,619,061 |
def ocvh_smemo(for_each_device=False):
"""
Makes a function memoizing the result for each argument and device.
This decorator provides automatic memoization of the function result.
Args:
for_each_device (bool): If True, it memoizes the results for each
device. Otherwise, it memo... | 8560f187fdffd83e77cf889084aefe54f9cb4205 | 3,619,062 |
def apply_exif_orientation(image):
"""
Reads an image Exif data for orientation information. Applies the
appropriate rotation with PIL transposition. Use before performing a PIL
.resize() in order to retain correct image rotation. (.resize() discards
Exif tags.)
Accepts a PIL image and returns ... | b5cb3fe31c554fa45d9525c46f3b8f8f3973af3e | 3,619,063 |
def normalize_v4_address(source):
"""
IPv4 アドレスを整形する。
:param source: IPv4 アドレスと思われる文字列
:type source: str
:return: 整形した IPv4 アドレス
:rtype: str
"""
try:
v4 = IPv4Address(source)
except AddressValueError as _:
return None
return str(v4) | bba116ac1fd2abd23b60df98efca1b5e4301ffe9 | 3,619,064 |
def _cursor(host, dictCur = False):
"""Cursor
Returns a cursor for the given host
Args:
host (str): The name of the host
dictCur (bool): If true, cursor will use dicts
Return:
Cursor
"""
# Get a connection to the host
oCon = _connection(host)
# Try to get a cursor on the connection
try:
if dictCur... | fb309ee64f0d95eafca7afe715de6620cb6dea32 | 3,619,066 |
from pathlib import Path
def get_solar_charge_state() -> str:
"""
Gets the current state of the charging system
Returns:
The charge state object as a json string
"""
current_state = Path('current_state.json').read_text()
return current_state | 0621aff9e6ae77b48811b2879f644ff3e4e4ee91 | 3,619,067 |
from datetime import datetime
def get_lambda_execs_in_last_min():
"""
Use CloudWatch to see how many lambdas are currently running (take the
average over the last minute).
Returns:
(int): Average number of currently running lambdas.
"""
utc_zone = timezone(timedelta(hours=0))
now... | 60e2ee45f532c474792f0249cbedb5094478ce4f | 3,619,068 |
def get_fixture_value(request, fixture_name):
"""
Returns the value associated with fixture named `fixture_name`, in provided `request` context.
This is just an easy way to use `getfixturevalue` or `getfuncargvalue` according to whichever is available in
current `pytest` version.
:param request:
... | 11e2b5f67595ecf102f7a8f28cc4aa151a8ebca5 | 3,619,069 |
def ParametricCrossCap(**kwargs):
"""Generate a cross-cap.
ParametricCrossCap generates a cross-cap which is a non-orientable
self-intersecting single-sided surface. This is one possible
image of a projective plane in three-space.
Return
------
surf : pyvista.PolyData
ParametricCr... | ea581de824121908bdb9dac752b64d32b994413e | 3,619,071 |
import random
def random_member_id():
"""
Return a zero-padded string from 00000000 to 99999999 that's not in use by
any Member.
"""
def random_id():
return str("{0:08d}").format(random.randint(0, 99_999_999))
member_id = random_id()
while Member.objects.filter(member_id=member_... | cbf9c54d8b6ac7f96daef138f8439608fcb38761 | 3,619,072 |
def has_role(package_path, role, identity):
"""True if |identity| has |role| in some |package_path|."""
assert impl.is_valid_package_path(package_path), package_path
assert is_valid_role(role), role
if auth.is_admin(identity):
return True
for acl in get_package_acls(package_path, role):
if identity in... | e45a8e5452661bf96452dbb9a4e807158b36f484 | 3,619,073 |
def _add_o_makedup_bam_parser_options(p):
"""Add a bam as output of `pbsv1 markduplicates`"""
return __add_makedup_bam_parser_options(p, str) | 15b9fda402de523e94b043d2d1b6bc8d9c0566da | 3,619,074 |
def image_to_vec(image_rgb: np.ndarray) -> np.ndarray:
"""Construct a RGB color vector from a 2D RGB image.
Args:
image_data (np.ndarray): image data as a ndarray or ndarray-like
image_data.shape = (num_x_pixels, num_y_pixels, num_channels)
Returns:
np.ndarray: one row for each... | 057f91a0f74f4a24623994d1356820208f51a9be | 3,619,075 |
def animate(gens, interval=200):
"""Animate a set of 1d CA generations."""
# we'll need these
num_cols = len(gens[0])
num_rows = len(gens)
# set up figure
fig, ax = plt.subplots(figsize=(num_cols*0.3, num_rows*0.3))
plt.close()
ax.set_xlim([-1, num_cols])
ax.set_xticks(np.a... | 90e3eba1655d4fa4348e9ec0df0170f385e3a95c | 3,619,076 |
def load_user(user_id):
"""Check if user is logged-in on every page load."""
"""Check if user is logged-in on every page load."""
if user_id is not None:
query = 'match (n:User) where ID(n)={userid} return n'
user = db.graph.run(query, parameters={'userid': user_id}).evaluate()
user2... | f65c2caca06eae2cbef23031e76970adbfb3666e | 3,619,077 |
def create_recurrent_merge_branch_model(
vocab_size: int,
embedding_size: int = 96,
num_lstm_layers: int = 1,
lstm_size: int = 670,
shared_embedding: bool = False) -> tf.keras.Model:
"""Constructs a recurrent model with an initial embeding layer.
The output is
the average of the two branches,... | 4b2c3dc9ee1d11229acf54827b3424f25247294b | 3,619,078 |
def _convert_to_initializer(initializer):
"""Returns a TensorFlow initializer.
* Corresponding TensorFlow initializer when the argument is a string (e.g.
"zeros" -> `tf.zeros_initializer`).
* `tf.constant_initializer` when the argument is a `numpy` `array`.
* Identity when the argument is a TensorFlow initia... | 1d9ee4c8dce6c5509f4148290bd64ba77b4bd222 | 3,619,079 |
def parseInpatientClaimData(obj, elem):
"""
Parse InpatientClaim data from xml element.
Parameters:
- obj : the claim data object
- elem : the xml element containing claim data
Return the claim data object
"""
parseData(obj, elem, inpatientClaimDataInstance, InPatientClaimMappi... | 4e95f221c18cfaed9650e3721b505e3c8705d558 | 3,619,080 |
def _unicode(ctx, text):
"""
Returns a numeric code for the first character in a text string
"""
text = conversions.to_string(text, ctx)
if len(text) == 0:
raise ValueError("Text can't be empty")
return ord(text[0]) | e23133c5342acd8e11d6707f39138744443d0823 | 3,619,081 |
def parse_config(config):
"""
Parse config file so that it is in the correct form for the environment class
"""
parsed_config = {}
subnets = config["subnets"]
subnets.insert(0, 1)
parsed_config["subnets"] = subnets
parsed_config["num_services"] = config["num_services"]
parsed_config[... | 08670c9ef50b8f63a94ca1a984988263faf98d35 | 3,619,082 |
def loadFeatures(inpath, maxFeatures=-1, noMix=False, discardDerivs=False):
"""
Given the filepath of an input CSV feature file, this function reads all features from the file and stores them in
a Numpy matrix suitable for use with SciKit classifiers. It returns the feature matrix and the list of labels for... | 56bfe5975e08bd2e26be7cc4d59a9b593897f2b8 | 3,619,083 |
def quote_ident(column: str):
"""
---------------------------------------------------------------------------
Returns the specified string argument in the format that is required in
order to use that string as an identifier in an SQL statement.
Parameters
----------
column: str
Colu... | cdfe1f7e108904ef35c1733b91fea1a51e239570 | 3,619,085 |
def find_opt_end(options):
""" Find the end of an option (;) handling escapes. """
offset = 0
while True:
i = options[offset:].find(";")
if options[offset + i - 1] == "\\":
offset += 2
else:
return offset + i | 5e3404ffb2b776402a598351374f3390500edef3 | 3,619,086 |
def gas_fvf(z, temp, pressure):
"""
Calculate Gas FVF
For range: this is not a correlation, so valid for infinite intervals
"""
temp = temp + 459.67
Bg = 0.0282793 * z * temp / pressure
return(Bg) | 375ac4aeac7f5177aab6e1bb4c2ab604b80778d2 | 3,619,087 |
def index():
"""Return index page.
The index page presents:
- a header with the title of the website and a button that takes
you to the login page. If you are logged in it logs you out.
- a categories menu that displays all available categories.
- a column with the latest items added.
"""
... | c0ac79147fbaef61ce15a0bdf6467da9ac9a024a | 3,619,088 |
def build_auxiliary_edge_connectivity(G):
"""Auxiliary digraph for computing flow based edge connectivity
If the input graph is undirected, we replace each edge (`u`,`v`) with
two reciprocal arcs (`u`, `v`) and (`v`, `u`) and then we set the attribute
'capacity' for each arc to 1. If the input graph is... | 598affab124771953dbf146a26814e89aef01f23 | 3,619,089 |
def resnet18(pretrained=False, **kwargs):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
if pretrained:
# model.load_state_dict(model_zoo.load_url(model_urls['resnet18']... | 7de9843bfb5927394b79d466fc3472cdd12ebd31 | 3,619,090 |
import colorsys
import random
def save_draw_bbox(image, bboxes_,score_,label_, xml_path, iname, classes=classes, show_label=False):
"""
bboxes: [x_min, y_min, x_max, y_max, probability, cls_id] format coordinates.
"""
k = 0
num_classes = len(classes)
image_h, image_w, _ = image.shape
... | 2ee57bdfcf1c9b372b420024e992b10d5dd57f9d | 3,619,091 |
def partition(A, p, r):
"""procedura partition
Parametri:
A (int): lista di numeri interi
p (int): indice di inzio dell'array(o sottoarray)
r(int): indice di fine dell'array(o sottoarray)
Valore di Ritorno:
int: indice del pivot
"""
x = A[r]
... | 0cca35d4f1e010fb606a56272046217c5e231714 | 3,619,092 |
def printSchoolYear(year1):
"""Return a print version of the given school year.
"""
if year1:
return "%d–%d" % (year1 - 1, year1) | 93879512567a2be3e3cf541b747178b422be0590 | 3,619,093 |
def dahua_brightness_to_hass_brightness(bri_str: str) -> int:
"""
Converts a dahua brightness (which is 0 to 100 inclusive) and converts it to what HASS
expects, which is 0 to 255 inclusive
"""
bri = 100
if not bri_str:
bri = int(bri_str)
current = bri / 100
return int(current *... | d1d8d02f896edc4a16fbb1b26c99416b60764fc6 | 3,619,095 |
def connected_to_db():
"""
Queries the database to check if the connection is live
:return: Boolean
"""
try:
session = Session()
session.execute(text('SELECT 1'))
session.close()
return True
except:
return False | 85ec38ff2648829d30f2300061c4e5b67e291f6e | 3,619,096 |
def color_segmentation(segmentation):
"""
Converts a segmentation map to a color image.
Args:
segmentation: a 3-dim numpy array represents a RGB image
Returns:
colored segmentation map
"""
color_map = [
[0, 0, 0],
[255, 0, 0],
[0, 255, 0],
[0, 0,... | 57cb74ce8b1e468690af2bc2adecc69653bad416 | 3,619,098 |
def global_scaling(gt_boxes, points, scale_range):
"""
Args:
gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading]
points: (M, 3 + C),
scale_range: [min, max]
Returns:
"""
if scale_range[1] - scale_range[0] < 1e-3:
return gt_boxes, points
noise_scale = np.random.unifor... | e8bc52c8001a24a4aae9a33bd30d6b217eff18e4 | 3,619,100 |
import inspect
async def parse_annotation(param: inspect.Parameter, default, arg: str, index: int, message: discord.Message):
""" Parse annotations and return the command to use.
index is basically the arg's index in shelx.split(message.content) """
if default is param.empty:
default = None
... | 2ce54a9a70f1eac3ad94b0783e81fd0508ccd731 | 3,619,101 |
from pathlib import Path
def api(path:str):
"""Associate a path with a given method."""
def inner(fn):
fn.path = Path(path)
return fn
return inner | a03d5ea05c5b91e3e18b121fba7771691f508b0c | 3,619,102 |
def wlan_exp_init_time(nodes, time_base=0, output=False, verbose=False, repeat=1):
"""Initialize the time on all of the WLAN Exp nodes.
Attributes:
nodes -- A list of nodes on which to initialize the time.
time_base -- optional time base
output -- optional output to see jitter acro... | dc7681c5649b6d180fca3d9da6b66bb329e2a43c | 3,619,103 |
def GilmoreEick_equation(t, x):
"""Compute one integration step
using the Gilmore--Eick equations.
"""
global T
R = x[0]
R_dot = x[1]
pg = x[2]
pinf = sc_pstat - sc_pac * np.sin(sc_omega * t)
pinf_dot = -sc_pac * sc_omega * np.cos(sc_omega * t)
T_gas = T_gas_0 * pg * R ** 3 /... | 0187050c12dd83d538b4e196eb0e20fa77f645f4 | 3,619,104 |
def findAbsFuncUFromRelaU(CompMean, ru):
"""
:param CompMean:
:param ru:
:return:
"""
result = CompMean * ru
resultString = result.to_eng_string()
intPart = resultString.split('.')[0]
try: # may not have '.'
decimalPart = resultString.split('.')[1]
digiteff = 0
... | 2edb3c08837138f12249705be38ff3b57bf30d5d | 3,619,107 |
import json
def get_all_services(as_json=False, as_json_schema=False):
"""Get all registered services, as objects (default) as JSON, or as JSON schema.
:param bool as_json: If True, return JSON instead of objects. Supersedes as_json_schema.
:param bool as_json_schema: If True, return JSON schema instead ... | d7c47b47ba110748ae3bfec9c455ea82c5d2cf3b | 3,619,108 |
def gen_jets_groomed_precrit(num_events, z_cut, beta, f,
jet_type='quark',
radius=1., acc='LL'):
"""Generates a list of num_events jet_type jets
through angularity based parton showering.
"""
# Setting up for angularities
jet_list = []
f... | b0f3bc11501445c7e1092bf36947d4963ab2bd2f | 3,619,109 |
import torch
def randn(*args, **kwargs):
"""
In ``treetensor``, you can use ``randn`` to create a tree of tensors with numbers
obey standard normal distribution.
Example::
>>> import torch
>>> import treetensor.torch as ttorch
>>> ttorch.randn(2, 3) # the same as torch.randn... | e92e45bc0210f6b00c468629c741eab2d0a7a50a | 3,619,111 |
def parse_host_port(address, default_port=None):
"""
Parse an endpoint address given in the form "host:port".
"""
if isinstance(address, tuple):
return address
if address.startswith('tcp:'):
address = address[4:]
def _fail():
raise ValueError("invalid address %r" % (addr... | 966e53c3c945d7fc728bd4b9a680ae62f4e2b7bf | 3,619,112 |
def synapses2nodepoints(x, layer_scale):
"""Generate nodepoints (point A, point B) from synapses for given neuron(s).
Parameters
----------
x : CatmaidNeuron | CatmaidNeuronList or TreeNeuron | NeuronList
neuron or neuronlist of different formats
layer_scale : int | float
... | 9756830e2b580155ca50d5f67586a6d5552c9a4f | 3,619,113 |
def p52():
""" Smallest integer n s.t n,2*n,...,6*n all have same digits. """
# Returns the digits in the decimal representation of a positive integer n
def digits(n):
ret = []
while n > 0:
ret.append(n % 10)
n = n / 10
ret.sort()
return ret
# C... | e252998ab15a99aa58139005aa9334c9d99005f8 | 3,619,114 |
from typing import Type
def get_microphone_class(system: str) -> Type[RhasspyActor]:
"""Get class type for profile microphone."""
assert system in [
"arecord",
"pyaudio",
"dummy",
"hermes",
"stdin",
"http",
"gstreamer",
], ("Unknown microphone system... | a1b915601ffdfbe0a2f038a380be1a68b66bf85a | 3,619,115 |
def addition(a,b):
""" return sum of a and b """
c = a + b
if abs(c) > Largest:
if c < 0:
return -(Largest)
return Largest
return c | 98a08514dea1dc2c58151917563360946c5fac87 | 3,619,117 |
import requests
def subscribe_in_pubsubhubbub(channel_id: str) -> int:
"""The subscription request to find out when a new video arrives on a
specific channel is made from this function. Basically here the
necessary data for this activity is informed for Pubsubhubbub
Parameters
----------
chan... | 1d65c5c9621d41ea54bf0a68fb3f824a342bb804 | 3,619,119 |
def hsv_complement_color(h, s, v):
""" get the complement of a rgb color
:param h: Hue value (0-360)
:param s: Saturation value (0-255)
:param v: Value value (0-255)
:return: HSV tuple """
# perform 180° hue change
tmp = 180
if h > 180:
tmp = -tmp
return h + tmp, s, v | dd9769b93742349eaca124ee60d65f047c18f2b5 | 3,619,120 |
import requests
def telegram_bot_sendtext(bot_message: str, *, bot_token: str, bot_chatid: str):
"""Send a notification to a telegram channel.
Args:
bot_message (str): Message you want to send.
Returns:
[request]: Returns a request object which is the response to send to the channel.
... | 372d350ad5513a233b148b3f75b8fa5bdd2f2904 | 3,619,122 |
import torch
from typing import Optional
def focal_loss(output: torch.Tensor,
target: torch.Tensor,
reduction: str = "mean",
normalized: bool = False,
gamma=2,
reduced_threshold: Optional[float] = None,
eps: float = 1e-6,
... | d1fcadc9273a6a25a617c40e71e91515352a4bb2 | 3,619,123 |
def preprocess_words_scores(type2freq_1, type2score_1, type2freq_2, type2score_2,
stop_lens, stop_words, handle_missing_scores):
"""
Filters stop words according to a list of words or stop lens on the scores
Parameters
----------
type2freq_1, type2freq_2: dict
Ke... | fe91586acbd9722e24daebcb942971e969f990d2 | 3,619,124 |
from pathlib import Path
def load_mappings_file(fpath: Path) -> list:
"""
Read the mappings file shared by Abu farha (CVPR'18) to read the class
names.
"""
res = []
with open(fpath, 'r') as fin:
for line in fin:
res.append(line.rpartition(' ')[-1].strip())
# convert to ... | 3e450e7ff07516c4149041008cc2cf3b3a1bb364 | 3,619,125 |
def _satisfies_wolfe(val_0,
val_c,
f_lim,
sufficient_decrease_param,
curvature_param):
"""Checks whether the Wolfe or approx Wolfe conditions are satisfied.
The Wolfe conditions are a set of stopping criteria for an inexact line se... | d4afc60f4a6e3d7749935fbbf6d291f4224cc04c | 3,619,126 |
def load_edf(eeg_file):
"""This function uses mne library.
WARNING: The function has strange behaviour, please don't use"""
data = mne.io.read_raw_edf(eeg_file)
sfreq = data.info['sfreq']
signals = data.get_data()
return signals, int(sfreq) | e05a1ed0b013a813c32c43a55bc16bb73dc0f03b | 3,619,127 |
def fit_parabola(x1,x2,x3,y1,y2,y3):
"""Returns the parabola coefficients a,b,c given 3 data points [y(x)=a*x**2+b*x+c]"""
denom = (x1-x2)*(x1-x3)*(x2-x3)
a = (x3*(y2-y1)+x2*(y1-y3)+x1*(y3-y2))/denom
b = (x1**2*(y2-y3)+x3**2*(y1-y2)+x2**2*(y3-y1))/denom
c = (x2**2*(x3*y1-x1*y3)+x2*(x1**2*y3-x3**2*y1... | e077f5a895e353d5b980b15bee603be5c34d3ec4 | 3,619,129 |
def _augment(image, op):
"""Image augmentation"""
if op[0]:
image = np.rot90(image, 1)
if op[1]:
image = np.fliplr(image)
if op[2]:
image = np.flipud(image)
return image | 43a693069629f05f12fd4139a9f2fb1c5de9fe3e | 3,619,131 |
def generate_list(usb_dict: dict) -> list:
"""
wrapper for list conversion
:param usb_dict: usb dictionary
:return: list of usb devices for tui print
"""
devices = []
for usb in usb_dict.values():
devices.append(usb)
return devices | 8d1d106c7b9fd4078b0d78f0370bd9d22ecda368 | 3,619,132 |
def file_test_list(tmpdir_factory, string_test_list):
"""An example of output from
tempest run --list-tests
"""
filename = tmpdir_factory.mktemp('data').join('file_test_list_one').strpath
with open(filename, 'w') as f:
f.write(string_test_list)
return filename | 6ce88df4834d90b1507e9b9171946a5fda1d557a | 3,619,133 |
def read_companies(excel_file: ExcelFile) -> pd.DataFrame:
"""
:param excel_file: (ExcelFile)
:return melted_companies: (DataFrame)
code | (String)
date | (Datetime)
name | (String)
...
"""
# Read excel file.
raw_companies = excel_file.parse(COMPANY, sk... | 8d451f7aeb472a1b9b447a97c9710d6f120b6ff8 | 3,619,134 |
def GXY_B2(
code, error, mag=0.002617993877991494, propagation='random',
NEV=True, **kwargs
):
"""
SPE 90408 Table 4
"""
dpde = np.full((len(error.survey_rad), 3), [0., 0., 1.])
dpde[:, 2] = np.where(
error.survey.inc_rad <= kwargs['header']['XY Static Gyro']['End Inc'],
cos(... | 99cf7c392503e7c9b6276c6caf1fa049c1bd0a64 | 3,619,136 |
def is_lead_worker(rank):
"""
-1 = means serial code so main proc = lead worker = master
0 = first rank is the lead worker (in charge of printing, logging, checkpoiniting etc.)
:return:
"""
am_I_lead_worker = rank == 0 or is_running_serially(rank)
return am_I_lead_worker | 924d847a964d13cbf19e02acc187a89f088de810 | 3,619,137 |
def handler408(request):
""" Custom response handler """
return HttpResponse(content="Custom 408 handler", status=408) | aad27b4d5d81995e1d959e88ea61ade510b03ac6 | 3,619,138 |
def resolve_type_id_to_type_name(type_id, raise_exception=True):
"""
Resolves an EVE Online type_id to type_name. Falls back to ESI if not found in static database.
Returns None if not found.
"""
query = "select typeName from invTypes where typeID = %s" % type_id
type_name = query_static_databa... | 7866ecee769eb677a721b2fa4792ea8af3c41ba0 | 3,619,139 |
import re
def FindTasksByName(searchstr, ignore_case=True):
""" Search the list of tasks by name.
params:
searchstr: str - a regex like string to search for task
ignore_case: bool - If False then exact matching will be enforced
returns:
[] - array of task objec... | cdca2b4ea9122293261c075637880e53f7349379 | 3,619,140 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.