content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _GetColumn(data, token):
"""Gets the column that |token| starts at within a line in |data|."""
last_newline = data.rfind('\n', 0, token.lexpos)
if last_newline < 0:
last_newline = 0
column = token.lexpos - last_newline
return column | a325210b0c2ab186a88a6beb083dfe8f579b1f3d | 613,187 |
def try_get_image_tag(image):
"""Tries to get an image tag. If there is no tag, returns an empty string."""
try:
return image.tags[0]
except:
return "" | 4e490a6b17552363c8c8ac52320221c641eed5ca | 613,190 |
def prettify(value, postfix, value_format="%0.2f"):
"""
return prettified string of given value
value may be None
postfix can be used for unit for example
"""
if value is None:
value_str = "--"
else:
value_str = value_format % value
return "%s %s" % (value_str, postfix) | 0e209bd1bfaf90986ed7c2fe221b2b7943f03c37 | 613,191 |
def either_connected_or_not_connected(v, vertices_in_module, graph):
"""
Check whether ``v`` is connected or disconnected to all vertices in the
module.
INPUT:
- ``v`` -- vertex tested
- ``vertices_in_module`` -- list containing vertices in the module
- ``graph`` -- graph to which the ve... | e506914c6d2c6277e66b0458bf601a20be8fcc48 | 613,193 |
def division_algo_coeff(a,b):
"""
Calculates coefficients q and r in a = bq + r according to division algo
Parameters
----------
a : int
denotes a in a = bq + r
b : int
denotes b in a = bq + r
return : two int
return two integers
first one refers to q (quoti... | 5661a5247059bace2d48523478fb154b08c1a238 | 613,197 |
def has_valid_custom_headers(custom_headers: list):
"""
Check if the list of custom header is valid
:param custom_headers: list of CustomHeader to validate
:type custom_headers: list
:return the result
:rtype bool
"""
if custom_headers is None:
return True
for item in custom... | 8ff6bf5908717a723174be56ad89b7308199480f | 613,198 |
def getReviewRating(reviewDiv):
""" The rating for the review is stored as a class on an inner span with two classes applied
The first class identifies it as a "bubble rating", while the second defines the level from 1 to 5
Example: class="ui_bubble_rating bubble_10"
"""
ratingString = (((reviewDi... | 65ffa2570b6fc87d610d6cb632ec5a019d595d26 | 613,201 |
def _get_trial(df, block, trial_number, block_col='BlockNumber',
trial_col='TrialNumber'):
"""Returns specified trial from specified block. Assumes the block and trial
columns are consistent across experiments"""
return df.groupby([block_col, trial_col]).get_group((block, trial_number)) | 33266f117150cd10fe3560fbf77aea09165403e2 | 613,202 |
def _family_name(set_id, name):
"""
Return the FAM object name corresponding to the unique set id and a list of subset
names
"""
return "FAM" + "_" + str(set_id) + "_" + "_".join(name) | 0ee1d1f24f433f46aed6ead5b08f2c5e571df70a | 613,204 |
def boolean(string):
""" Convert strings to booleans for argparse """
string = string.lower()
if string in ['0', 'f', 'false', 'no', 'off']:
return False
elif string in ['1', 't', 'true', 'yes', 'on']:
return True
else:
raise ValueError() | 50dfa5c6974f965156c43117662de2bb539abcf1 | 613,205 |
def is_string(maybe_string):
""" Check if the given item is a String
:param maybe_string: String
:return: Boolean
"""
return isinstance(maybe_string, str) | 1a919328f5acfe67f8debda1fd13773231218154 | 613,206 |
import string
def camelcase(text):
"""Convert some_string or some-string to SomeString."""
text_spaced = text.replace("_", " ").replace("-", " ")
ret = string.capwords(text_spaced).replace(" ", "")
return ret | 35e15e5798c2e50e3c3883d81e2be47be91d63e5 | 613,207 |
def find_fieldset(fieldsets, fieldset_query_id):
"""Find a fieldset by query id"""
for fieldset in fieldsets:
if fieldset.QueryId == fieldset_query_id:
return fieldset
return None | ae05b90a67162239f857bd12085d26e7b465fe1c | 613,208 |
def default_stop_criterion(epoch_id : int, epoch_max : int, train_losses : list,
validation_losses : list, train_accuracies : list,
validation_accuracies : list) -> bool:
"""
Criterion function to decide whether stop the training or not
=================... | 1eecb9e6e2d4bcc3bfae6ab1daa82814552a2d87 | 613,210 |
def get_most_important_features(vectorizer, model, n=5):
"""
This function returns the most important words
starting from the most important to he least important
that the algorithm used to learn
Inputs:
vectorizer >> The Vectorizer object TF-Idf or CountVectorizer
model >> the algo... | 8834e6d35a234044a2c8755cd11f0af6f59ec0cf | 613,213 |
def find_existing_replacements(reporting_conn, old_host):
""" Determine if a request has already been requested
Args:
reporting_conn - A MySQL connect to the reporting server
old_host - The hostname for the host to be replaced
Returns:
If a replacement has been requested, a dict with the follo... | 6499c8272f75e5bbb63ed9ae887d6718779f8a90 | 613,215 |
def get_variable_name_table(model):
"""
Compute the list of all names of the variable in the model.
:param model: the model of which get all the variables names.
:return: a name-False pair.
:rtype: dict
"""
return {var.varName: False for var in model.model.getVars()} | ec4ecf335f4160704668c67c261c32a19a234b76 | 613,217 |
import random
def sample(items, k, replace=False):
"""
Randomly sample k items with equal probability.
"""
if not replace and k > len(items):
raise ValueError("Sample must be no larger than population.")
remaining = items
sample = []
for i in range(k):
n = random.randint(0,... | f93023c9f8400fc0cb2ff058d07e60e54243fc1b | 613,222 |
from pathlib import Path
def make_wiki_path(path: Path, wiki_root_path: Path) -> str:
"""
Convert path to wiki page url.
"""
return str(path.relative_to(wiki_root_path).with_suffix('')) | 9b209128ce4c1ac97ce9a0429d7da049dc496c2f | 613,224 |
def print_time(duration):
"""
Function to print the time elapsed for the most recent step,
given the current time
"""
if duration < 1:
print("That Took {} mS !".format(round(duration*1000, 2)))
elif duration < 60:
print("That Took {} Sec !".format(round(duration, 2)))
elif ... | 858d727e1ab2b4f7a81ff750b8a2cf2b94ae1646 | 613,225 |
def full_path(parsed_url):
"""
Returns the ``parsed_url.path`` with ``"?"`` and the ``parsed_url.query``
if it exists, just the path otherwise.
"""
if parsed_url.query:
return parsed_url.path + "?" + parsed_url.query
else:
return parsed_url.path | 1e2ab69d4d5a53ac76d1d9a29a55775045e79f80 | 613,228 |
def _missing_parameter(params_required, params_actual, parent=''):
"""Recursively search for the first missing parameter."""
for param_name in params_required:
if param_name not in params_actual:
return '{}.{}'.format(parent, param_name)
param_required = params_required.get(param_... | 4aca12ba2b10247bbe80f2d2f649af55b172fae1 | 613,229 |
def DataFrame_to_HtmlString(pandas_data_frame):
"""Converts a pandas.DataFrame to a html table using index=False
inverse of HtmlString_to_DataFrame"""
html=pandas_data_frame.to_html(index=False)
return html | 066a0bf5b96f855ff6a0aa2a0c6ea981137160b1 | 613,230 |
def form_to_grade_assignment(form):
"""Creates a grade dict from an assignment form."""
grade_id = '{student}-{assignment}-{course}'.format(**form)
grade = {'_id': grade_id,
'student': form['student'],
'assignment': form['assignment'],
'course': form['course'],
... | 842fea89af28cd5d0c8bf1efac36985f64a39387 | 613,232 |
import shutil
def nvsmi_available() -> bool:
""" Returns whether or not nvidia-smi is present in this system's PATH. """
return shutil.which('nvidia-smi') is not None | 7c390b2652e38dcb090909ef0c48005bc0430430 | 613,236 |
def calculate_desired_noise_rms(clean_rms, snr):
"""
Given the Root Mean Square (RMS) of a clean sound and a desired signal-to-noise ratio (SNR),
calculate the desired RMS of a noise sound to be mixed in.
Based on https://github.com/Sato-Kunihiko/audio-SNR/blob/8d2c933b6c0afe6f1203251f4877e7a1068a6130/c... | e99f4b253e26397be9377a8ae2617fe31f6ffc4b | 613,239 |
import logging
def file_to_dict(properties_file):
"""
This method will take a properties file (key=value one per line), load
it, and return a dictionary with the contents.
Parameters:
properties_file -- Path to the properties file
Returns:
Dictionary with the contents
"""
retur... | 1442148ae991fe7cce4e28b83d43246e03a432f7 | 613,240 |
def euclid(a, b):
"""Solve x*a + y*b = ggt(a, b) and return (x, y, ggt(a, b))"""
# Non-recursive approach hence suitable for large numbers
x = yy = 0
y = xx = 1
while b:
q = a // b
a, b = b, a % b
x, xx = xx - q * x, x
y, yy = yy - q * y, y
return xx, yy, a | 4998030919fef4db3246e20c2f71055988e342c7 | 613,251 |
async def _get_feed_price(db):
"""Get a steemd-style ratio object representing feed price."""
price = await db.query_one("SELECT usd_per_steem FROM hive_state")
return {"base": "%.3f SBD" % price, "quote": "1.000 STEEM"} | cdf165add5a442f261e52827c6a087ef8912d43a | 613,254 |
def map_embedding_to_QUBO(QUBO, complete_embedding):
"""
For each variable in QUBO, this function maps that variable to a set of physical qubits
found in complete_embedding.
Parameters
----------
QUBO : dict
keys are linear or quadratic terms, and values are the weights associated
... | 2918dd2a2ac8563967f6df400cbcba8368613ecb | 613,260 |
def getVIfromVIC(vicPage):
"""
Retrieves a VI image page name from a VIC page
Returns either a string or False (silently) in case of error.
Arguments:
vicPage: The VIC Page object
"""
try:
text = vicPage.get()
except:
return False
templates = vicPage.templatesWithParams()
... | 8cf4ce7cf6b60f6c29ffa7da97036f207ef6754d | 613,262 |
def _generate_cache_header_key(key_prefix, request):
"""Return a cache key for the header cache."""
# url = hashlib.md5(force_bytes(iri_to_uri(request.build_absolute_uri())))
cache_key = 'cache.cache_header.%s.' % (
key_prefix)
return cache_key | 308d1af2d96783306d8ec50e4380a0e8de5c96d3 | 613,266 |
def epochBessel2JD(Bepoch):
#----------------------------------------------------------------------
"""
Convert a Besselian epoch to a Julian date
:param Bepoch:
Besselian epoch in format nnnn.nn
:type Bepoch:
Floating point number
:Returns:
Julian date
:Reference:
See: :func:`JD2epochBessel`
:... | 985c1d2be8967e74dbc996c41dee9cf35f195e07 | 613,273 |
def lerp(v0, v1, t):
"""
Simple linear interpolation between v0 and v1 with parameter t, 0 ≤ t ≤ 1
"""
return v0 + (v1 - v0) * t | dda9cb7532ad59eab4fa67716e0f940452b0cf88 | 613,274 |
def transition_indexes(np, nalpha, indexes):
"""
Returns the list of the indices in the bigdft convention that correspond
to the couple iorb-ialpha with given spin.
Args:
np (tuple): (norbu,norbd) occupied orbitals: when of length 1 assumed
spin averaged
nalpha (tuple): (norbu... | eab6f81fa69684284e14fe83bf1f0257d55bd150 | 613,275 |
def __write_rnx3_header__(ver=3.03, typ="O"):
"""
Write the first header line of the Rinex file
"""
TAIL = "RINEX VERSION / TYPE"
PAD = ' '
res = "{0:9.2f}{1:11s}{2:1s}{1:19s}{3:1s}{1:19s}{4}\n".format(ver, PAD, typ, 'M', TAIL)
return res | 61bbf3e77bde56c36936d51926c2e596f7a51efa | 613,278 |
def is_any_list_overlap(list_a, list_b):
"""
Is there any overlap between two lists
:param list_a: Any list
:param list_b: Any other list
:return: True if lists have shared elements
"""
return any({*list_a} & {*list_b}) | 1a7b532e0db58e6cee5b1d561ff90c6207812f82 | 613,282 |
def eigvector_uncoupled(par):
""" Returns the flag for the correction factor to the eigenvectors for the linear guess of the unstable periodic orbit.
Parameters
----------
parameters : float (list)
model parameters
Returns
-------
correcx : 1 or 0
flag to set the x-com... | 7d05aeee2a930a8ce712c4d134c82884717d3160 | 613,283 |
def half_int_float_to_str(f):
"""Given the decimal representation of a half-integer or integer, returns
the string fraction representation.
Example:
> half_int_float_to_str(1.5)
'3/2'
"""
if int(f) - f == 0:
return str(int(f))
else:
return str(int(2 * f)) + '/2' | 654c25b0f9ec759c3d8138e98301f87eb69e492c | 613,289 |
def to_complex(a_component: float | None, b_component: float | None) -> complex:
""" Construct a complex number (a_component + (i * b_component)),
where a_component and b_component default to 0 if passed in as None.
"""
a = 0.0
if isinstance(a_component, float):
a = a_component
b = 0.0
... | 475ac4be75140d51fd7581c98954d37b51e43c64 | 613,290 |
from typing import Dict
import json
def read_json(path: str) -> Dict[str, object]:
"""
Reads json from file path
:return: Dict[str, object]
"""
with open(path) as json_file:
return json.load(json_file) | 345083155ef9aa42157a36feebf768d8cb52a00b | 613,292 |
import re
def natural_sorted(iterable, key=None, reverse=False):
"""Return a new naturally sorted list from the items in *iterable*.
The returned list is in natural sort order. The string is ordered
lexicographically (using the Unicode code point number to order individual
characters), except that mu... | 889acc88b9264c9cd0da1c707b739304d1c4c770 | 613,294 |
def apple_url_fix(url):
"""
Fix Apple URL.
:param url: URL to fix
:return: fixed URL
"""
if url.startswith("webcal://"):
url = url.replace('webcal://', 'http://', 1)
return url | e3576984708089e5932a45675ed5af7bc622b3fa | 613,295 |
import re
def is_oa_license(license_url):
"""
This function returns whether we expect a publication under a given license
to be freely available from the publisher.
Licenses are as expressed in CrossRef: see https://api.crossref.org/licenses
"""
if not license_url:
return False
l... | 535e1fe2767689bf19445914b2b7eb99b666ef80 | 613,298 |
def format_bustime(bustime, round="millisecond"):
"""Convert bustime to a human-readable string (-)HH:MM:SS.fff, with the
ending cut off depending on the value of round:
"millisecond": (default) Round to the nearest millisecond.
"second": Round down to the current second.
"minute": Round down to the current min... | 11b2ab68bc64c881c08018257b36ac1ee9aa1209 | 613,299 |
def _get_axis(array, axis_num, i):
"""
Will get index 'i' along axis 'axis_num' of a 2- or 3-dimensional numpy array.
If array has 4+ dimensions or 'axis_num' is larger than number of axes, will return None.
Args:
array (:obj:`np.ndarray`): Array to fetch axis of.
axis_num (int): Axes t... | 737d5f2c304fd637c5580ad3264e0c8d7b140e35 | 613,307 |
import torch
def pt_sample_standard_normal(n, d):
"""
Generate samples from the standard normal. Return a torch tensor.
"""
return torch.randn(n,d) | 0c9ec79e0bc9bb5293f3dcae06a38977b443defb | 613,309 |
def get_field(d, field_list):
"""get the subfield associated to a list of elastic fields
E.g. ['file', 'filename'] to d['file']['filename']
"""
if isinstance(field_list, str):
return d[field_list]
else:
idx = d.copy()
for field in field_list:
idx = idx[field]
... | 554c6950c150765cd06894faf0b530445c56db91 | 613,310 |
def median(data):
"""
Return the median of numeric data, unsing the "mean of middle two" method.
If ``data`` is empty, ``0`` is returned.
Examples
--------
>>> median([1, 3, 5])
3.0
When the number of data points is even, the median is interpolated:
>>> median([1, 3, 5, 7])
4.... | 6d72969d0de922c625bf0784e119dea3a1ad3517 | 613,316 |
def spherical_radius(frame, origin=None):
"""
Transform a frame of cartesian coordinates into the sperical radius.
If origin=None the center of the box is taken as the coordinates origin.
"""
if origin is None:
origin = frame.box.diagonal() / 2
return ((frame - origin)**2).sum(axis=-1)**... | 0aaafe9e5d8e30bd7c51b8b14848ba6dddba477d | 613,317 |
from typing import OrderedDict
def account_list_table_format(result):
"""Format account list as a table."""
table_output = []
for item in result:
table_row = OrderedDict()
table_row['Name'] = item['name']
table_row['Location'] = item['location']
table_row['Resource Group'] ... | 62a34408337b21c7728258e9d27a685ea81f5b69 | 613,320 |
from typing import Dict
def parse_params(fname: str) -> Dict[str, int]:
"""Take a comma separated csv file with no header, return dict with keys from col 1 and values from col 2.
Example file:
fragment_len,5000
kmer,5
hidden_1,128
hidden_2,64
dim_out,5
Parameters
-... | 754317431a0fcb4e3de1623dd94fff30d56a36ea | 613,322 |
def scheduler_info_widget(scheduler_infos):
"""
Generates the HTML output exposing the scheduler infos. This output can be
consumed and exposed by CloudWatch Custom Widget.
Params:
scheduler_infos (dict): the parameters to display in the widget
"""
header = '<table>\n'
footer = ... | 8559f733f27eb8f8fb51b7c4a55334fdc0656590 | 613,323 |
def rotation(xobj, angle, pivot=None):
"""Rotates an xarray object created using rioxarray around a pivot
Parameters
----------
angle: float
angle in degrees to rotate the object
pivot: tuple
coordinates around which to pivot. Use array coordinates, not
the CRS coordinates. ... | 67797d0e71222bdc496444b7c9da76b246a651e6 | 613,325 |
def clean_arguments(args: dict) -> dict:
"""Cleans up a dictionary from keys containing value `None`.
:param args: A dictionary of argument/value pairs generated with ArgumentParser
:return: A dictionary with argument/value pairs without `None` values
:rtype: dict
"""
rv = {}
for (key, val)... | 83c59bd497e0d9fcee8d350efbffc00e16424610 | 613,332 |
def _get_design_matrix(model):
"""Returns the design matrix for an STS model with a regression component.
If there is not a design matrix, None is returned.
Args:
model: A `tfp.sts.StructuralTimeSeries` model instance return by
`build_model_for_gibbs_fitting`.
"""
design_matrices = [
compone... | 46d7d0768ac49113ab92fad27c1e02128dd136e1 | 613,334 |
import torch
def get_missing_feature_mask(rate, n_nodes, n_features, type="uniform"):
"""
Return mask of shape [n_nodes, n_features] indicating whether each feature is present or missing.
If `type`='uniform', then each feature of each node is missing uniformly at random with probability `rate`.
Inste... | bcc79fc27e3094b5222933ba7c64c418f9e1021f | 613,339 |
def calMassTransferCoefficientEq1(Sh, GaDiCoi, CaPaDi):
"""
calculate mass transfer coefficient [m/s]
args:
Sh: Sherwood number
GaDiCoi: gas component diffusivity coefficient [m^2/s]
CaPaDi: catalyst particle diameter [m]
"""
# try/except
try:
# characteristic le... | 3a297a09663d99146b91a959b410a115a96e942b | 613,347 |
def embed_hex(runtime_hex, python_hex=None):
"""
Given a string representing the MicroPython runtime hex, will embed a
string representing a hex encoded Python script into it.
Returns a string representation of the resulting combination.
Will raise a ValueError if the runtime_hex is missing.
... | 66b18a028dbbf7dd89020761bbbc732e15eef5b2 | 613,349 |
from typing import Dict
from typing import Optional
def parse_job_description(job_id: str, jobs: Dict) -> Optional[Dict]:
"""
Extract a job description for ``job_id`` from ``jobs``
:param job_id: an AWS Batch ``jobId``
:param jobs: a response to AWS Batch job descriptions
:return: a job descriptio... | 38fb055b702efe92c38e013cf891c2fb6886f110 | 613,351 |
def maxFlagellumLength(lst=None):
"""
Return the maximum flagellum length from the list of flagella lst.
"""
if lst is None:
return 0
lengths = [len(i) for i in lst]
return max(lengths) | 493fe7446434a65741444e9da2d4551f06a3f5bc | 613,354 |
import struct
def extract_bsm_data(bsm: bytes, verification_dict: dict) -> tuple:
"""Return a tuple containing the data elements of a BSM
:param bsm: the bsm bytes to parse
:type bsm: bytes
:param verification_dict: verification information from verify_spdu()
:type verification_dict: dict
:r... | e99001e953edc1f79dbe7aa055242b483740240b | 613,359 |
def parse_device_disk(token):
"""Parse a single disk from the header line.
Each disks has at least a device name and a unique number in its array,
after that could follow a list of special flags:
(W) write-mostly
(S) spare disk
(F) faulty disk
(R) replacement disk
So... | 7151d261ebaa933cca25c298860a2501ba3995bc | 613,360 |
def device(session):
"""First device in the session fixture."""
return session.devices[0] | 7a3151293c7492271738b3c7661d7bba3a0bb8d9 | 613,363 |
def is_pulsemap_check(table_name: str) -> bool:
"""Check whether `table_name` corresponds to a pulsemap, and not a truth or RETRO table."""
if "retro" in table_name.lower() or "truth" in table_name.lower():
return False
else: # Could have to include the lower case word 'pulse'?
return True | 8a467580c0ad50c357ff50d17a4ebf7e34633c09 | 613,366 |
def sum_exists_set(a, b, target):
"""
>>> sum_exists_set([1, 2], [3, 4], target=6)
True
>>> sum_exists_set([1, 2], [3, 4], target=7)
False
"""
b_remainders = set()
for el in a:
b_remainders.add(target - el)
for el in b:
if el in b_remainders:
return True
... | 76d45dd72d320ffa3c9a94d027d731c6247aa499 | 613,368 |
def twocs_to_int(val, bits):
"""compute the int value of a two compliment int"""
assert len(bin(val)) - 2 <= bits, (val, bits) # check if it fits
if (val & (1 << (bits - 1))) != 0: # if sign bit is set -> 8bit: 128-255
val = val - (1 << bits) # compute negative value
return val | 284a7f52bd01600b27392d26ed1d5319c332ca27 | 613,373 |
def sort_dict_by_value(dic, reverse=False):
""" sort a dict by value
Args:
dic: the dict to be sorted
reverse: reverse order or not
Returns:
sorted dict
"""
return dict(sorted(dic.items(), key=lambda x: x[1], reverse=reverse)) | 0aa5686d25acebe7f9b417089f59386092bb4003 | 613,374 |
import json
def write_attach(root_dir, name, data):
"""Write article attachments to disk.
:param root_dir: path to output directory
:type root_dir: Path()
:param name: output file name
:type name: str
:param data: data to write to disk
:type data: dict or str
"""
target = root_dir... | f59718fc1c23ce01b2002700764425eac582fd08 | 613,377 |
from typing import Union
from typing import Any
from typing import Dict
from typing import List
def lookup_path(path: str, dict_: Union[Any, Dict[str, Any]]) -> Any:
"""
Recursively traverse a potentially nested dictionary
using the '.' separated path.
>>> lookup_path("k0.k1.k2", {"k0": {"k1": {"k2":... | 0f7b13e0195a565698313a8c8ebf21e9b7fa7d9b | 613,380 |
import random
import string
def sanitize_nfill(value):
"""
Built-in sanitizer which replaces the original value with random numbers.
"""
if not value:
return value
return ''.join(random.choice(string.digits) for _ in range(len(value))) | 7e086ae911bbe811dc145c9a03a7b1f26e97557b | 613,382 |
def proc_to_seconds(val, entry):
"""Process a value in minutes to seconds"""
return 60 * int(val) | aacfa600b065e89443ede1b8eafc771ed695c191 | 613,384 |
import re
def extract(script):
"""Return the code chunks from `script`.
Parameters
==========
script : string
Pandoc Markdown-formatted text
Returns
=======
chunks : list of strings
One string per chunk
"""
pattern = re.compile(
r'''^[~`]{3,} # Chunk be... | 768ea1ea2162e3c9682d588d314d160bfa4dd895 | 613,385 |
def rm_cid(dfcol):
""" Remove (cid:X) where X is a number """
return dfcol.str.replace(r'\(cid:[0-9]+\)', '', regex=True) | dc1ca4cc948dbb4670a8022ef46caa156a5969a1 | 613,389 |
from typing import OrderedDict
def deduplicate(seq, keep_last=True, key=lambda x: x):
"""
Deduplicate items in the given sequence and return a list.
:param seq: Sequence to deduplicate
:type Seq: collections.abc.Sequence
:param key: Key function that will be used to determine duplication. It
... | 84a13e86640bdb7b8292fc289db0a9cd60696734 | 613,391 |
def prepare_source_valid_lengths(F, valid_length, query_data, num_heads: int):
"""
Returns an int32 valid length tensor of shape (batch * num_heads, query_length) to be used in
the softmax operation in DotAttentionCell with the length argument.
Due to broadcast_like, dtypes of valid_length and query_dat... | a67d728928272b6fafe7d2ae52d3d6044b5ee129 | 613,392 |
def clip(arr,thresh=3.5):
"""
clip(arr,thresh=3.5)
Simple sigma-clipping algorithm. Returns avg,std of clipped array.
"""
a = arr.copy()
avg,std = a.mean(),a.std()
while 1:
size = a.size
a = a[abs(a-avg)<thresh*std]
avg,std = a.mean(),a.std()
if size==a.size:
break
return avg,std | f7c3f288b210562ec28fddd880d608da96bd3580 | 613,393 |
def central_credible_interval(samples, alpha=0.05):
"""The equal-tailed interval containing a (1-alpha) fraction of the posterior samples.
Parameter samples: The posterior samples (array like)
Parameter alpha: The total size of the tails (Float between 0 and 1)
Returns: Left and right interval bounds... | cb9d9379234d5cb2db8a3015ef66ef7d4a384e90 | 613,395 |
def glue(f, r) :
"""Return (metadata, stream) pair where `r` is the initial portion of
the metadata that has already been read from the stream `f`.
"""
r = r + f.read(60-len(r))
return (r, f) | a9b6b88c48699dde7bf3e1f19bec2834ba6ee4dd | 613,396 |
def inflation_adjusted(r=0.07, i=0.03):
"""
Calculate inflation adjusted returns.
"""
return (1.0 + r) / (1.0 + i) - 1.0 | e97807e4af745554e804c313ae6ab35397139213 | 613,399 |
def _get_section(config, section):
"""Get all options from a section in a config file.
Args:
config: configparser instance.
section (str): Section name.
Returns:
dict: Contents of a section from config file.
"""
dict1 = {}
options = config.options(section)
for optio... | 1558a05b7f23953d858c5b509589991c287e28e9 | 613,402 |
def allPass(predlist):
"""Returns a function that evaluates each predicate in a list given an argument,
and returns True if all pass, otherwise False."""
def evaluate(x):
for pred in predlist:
if not pred(x):
return False
return True
return evaluate | 4b2b13752dcd2ab9ec94aae1704e4d0a0783d6fb | 613,403 |
def xywh_to_xyxy(x: float, y: float, w: float, h: float, image_width: float,
image_height: float) -> tuple:
"""Converts a bounding box from xywh format to xyxy format.
Args:
x (float): The x coordinate of the center of the bounding box.
y (float): The y coordinate of the center... | cfba89ea3310513dc2f6966c7009110a95187a93 | 613,404 |
def _follow_type_to_int(follow_type: str):
"""Convert dpayd-style "follow type" into internal status (int)."""
assert follow_type in ['blog', 'ignore'], "invalid follow_type"
return 1 if follow_type == 'blog' else 2 | 9ef48a14a85f99b64c55c60350788047c0302b1d | 613,405 |
import re
def isBlif(file):
"""Return true if the file has the .blif extension."""
return re.search("\.blif$", file) != None | 9729fb31b11d502d51982488d7ae81af14252e80 | 613,409 |
def residuals(p, y, x):
""" The residual function required by leastsq."""
## The gradient of the line.
m = p[0]
## The intercept with the y axis.
c = p[1]
## The model we're testing - a straight line in this case.
model = m*x + c
## The result to return.
res = y - model
# Re... | 2e8d8a849291c7a1235977f35a27c312bde34fd6 | 613,410 |
def print_topics(model, feature_names, n_top_words, topic_prev):
"""Prints the topic information. Takes the sklearn.decomposition.LatentDiricheltAllocation lda model,
the names of all the features, the number of words to be printined per topic, a list holding the freq
of each topic in the corpus"""
i = 0
message_... | 3228e57cf6972a15c17f4a2efd594dfbf6d34d2b | 613,419 |
def get_sample_name( bamfile ):
"""
Function to get the sample name from the bam file
Input: An AlignmentFile object of the bam file
Return: The sample or False if there is no SM tag in the bam header
"""
header = bamfile.header
sample_name = False
if 'RG' in header:
if type(head... | c8b07142d878503f540b56374871a937b20dee62 | 613,423 |
def string_to_list(string, sep=",", filter_empty=False):
"""Transforma una string con elementos separados por `sep` en una lista."""
return [value.strip() for value in string.split(sep)
if (not filter_empty or value)] | 5b2698533ebc2963a3498f883a29fdb491c151cd | 613,426 |
from typing import Union
from typing import Dict
import json
def _json_loads(s: Union[str, bytes]) -> Dict:
"""Like json.loads(), but handle str or bytes.
This is needed because an HTTP response's read() method returns bytes on
Python 3.5, and json.load doesn't handle bytes.
"""
if isinstance(s, ... | c220f95198088062f8703d46d6d3ae2216c8d70e | 613,427 |
def comma_and_and(*values, period=True):
""" Return a properly formatted string, eg: a, b and c. """
period = '.' if period else ''
len_values = len(values)
if len_values == 0:
return ""
elif len_values == 1:
return f"{values[0]}{period}"
else:
return f"{', '.join(values[... | db2b1aa5856cda458f8bb4eb9d4e9a80b14688e9 | 613,429 |
def get_species_label(entry):
"""Get the species name of an assembly summary entry."""
parts = entry['organism_name'].split(' ')
if len(parts) < 2:
return 'sp.'
return parts[1] | b4e059d2f40e89351b9749bacea95909e8524873 | 613,430 |
def set_control_user(user_id, prefix='', rconn=None):
"""Set the user who has current control of the telescope and resets chart parameters.
Return True on success, False on failure"""
if user_id is None:
return False
if rconn is None:
return False
try:
rconn.set(prefix+'vi... | 29fd2981f00b00f89af6220a26ac20efe5948dca | 613,431 |
def get_map_name(episode_index, map_index):
"""
Returns a map name from an episode and map index.
@param episode_index: the index of the episode. If this is 0, a Doom 2 style MAPxx name is returned.
@param map_index: the index of the map.
@return: a ExMx map name if episode_index is non-zero, a MA... | 593fdc56f11916df3c884ea3447d7d3e814b0352 | 613,433 |
import six
def getnamespace(f):
"""Returns the complete namespace of a function.
Namespace is defined here as the mapping of all non-local variables to values.
This includes the globals and the closure variables. Note that this captures
the entire globals collection of the function, and may contain extra sym... | acbfb54734be168f503cee11dbc474b712f34ec2 | 613,436 |
def ax25_encode_address(callsign: str, ssid: int, is_last: bool, command_bit: bool = False) -> bytearray:
"""
This function encodes the given info into an AX.25 compatible address field and returns the result as a bytearray.
Parameters:
callsign: The callsign is made up of upper-case alpha and numer... | 70991ecc1263202a5d4c4425c42ebe5e701e2823 | 613,438 |
def celsius_to_fahrenheit(deg_C):
"""Convert degrees Celsius to Fahrenheit."""
return (9 / 5) * deg_C + 32 | 13954a1a6a928cc339596e187fb11599561dcd85 | 613,440 |
def full_callsign(callsign):
"""
Returns a fully-formatted callsign (Callsign + SSID).
:param callsign: Callsign Dictionary {'callsign': '', 'ssid': n}
:type callsign: dict
:returns: Callsign[-SSID].
:rtype: str
"""
if callsign['ssid'] > 0:
return '-'.join([callsign['callsign'],... | f989358f1ced8f9a659ab23d08d18206d7e5147e | 613,444 |
def _get_token_weight(token, token_freq_map, a=1e-3):
"""
Computes SIF weight (Arora et al. 2017)
:param token: input word
:param token_freq_map: dict containing word: word freq.
:param a: weight parameter
:return: SIF weight for the word
"""
token_freq = token_freq_map.get(token, 0.0)
... | c04a50ad78ef316b194fe9525ed0da14132a174f | 613,450 |
def create_moves(x, y):
"""Create all valid moves from (x, y)"""
if (x == 0) and (y == 0):
return list([(0, 0)])
moves = []
for i in range(x):
moves.append((i, y))
for i in range(y):
moves.append((x, i))
return list(set(moves)) | 32b2ea6bad862a860bac9bc24ea8ffca7b915d5d | 613,452 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.