content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def url_path_join(*items):
"""
Make it easier to build url path by joining every arguments with a '/'
character.
Args:
items (list): Path elements
"""
return "/".join([item.lstrip("/").rstrip("/") for item in items]) | d864c870f9d52bad1268c843098a9f7e1fa69158 | 3,639,604 |
def f_match (pattern, string, flags = None):
""" Match function
Args:
pattern (string): regexp (pattern|/pattern/flags)
string (string): tested string
flags (int): regexp flage
Return:
boolean
"""
if build_regexp(pattern, flags).search(to_strin... | 31871f35568ca71c86535cfda5d434a57008f981 | 3,639,605 |
def validate_epoch(val_loader, model, criterion, epoch, args):
"""Perform validation on the validation set"""
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
batch_time = AverageMeter()
data_time = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
b... | 084d3c5b200470cd9b3a3d905c83c1046df0b96e | 3,639,606 |
def utf8_german_fix( uglystring ):
"""
If your string contains ugly characters (like ü, ö, ä or ß) in your source file, run this string through here.
This adds the German "Umlaute" to your string, making (ÄÖÜäöü߀) compatible for processing.
\tprint( utf8_german_fix("ü߀") ) == ü߀
"""
... | 7ed12d819b384e3bb5cb019ce7b7afe3d6bb8b86 | 3,639,607 |
def subtends(a1, b1, a2, b2, units='radians'):
""" Calculate the angle subtended by 2 positions on a sphere """
if units.lower() == 'degrees':
a1 = radians(a1)
b1 = radians(b1)
a2 = radians(a2)
b2 = radians(b2)
x1 = cos(a1) * cos(b1)
y1 = sin(a1) * cos(b1)
z1 = sin(... | f9e99119666fba375240111668229d400f1e37e5 | 3,639,608 |
import inspect
def get_args(obj):
"""Get a list of argument names for a callable."""
if inspect.isfunction(obj):
return inspect.getargspec(obj).args
elif inspect.ismethod(obj):
return inspect.getargspec(obj).args[1:]
elif inspect.isclass(obj):
return inspect.getargspec(obj.__in... | e9fb13c155a8d8589a619491d44be1c9194c29bc | 3,639,610 |
def name_value(obj):
"""
Convert (key, value) pairs to HAR format.
"""
return [{"name": k, "value": v} for k, v in obj.items()] | d9a5bef186b259401302f3b489033325e32af1f5 | 3,639,612 |
def get_ids(id_type):
"""Get unique article identifiers from the dataset.
Parameters
----------
id_type : str
Dataframe column name, e.g. 'pubmed_id', 'pmcid', 'doi'.
Returns
-------
list of str
List of unique identifiers in the dataset, e.g. all unique PMCIDs.
"""
... | 6b70d74d79ce7dcdd3654c09f1413ab468514eaa | 3,639,613 |
def get_items_info(request):
"""Get a collection of person objects"""
result = request.dbsession.query(Item).all()
results=[]
for c in result:
results.append({'id':c.id, 'markup':c.markup})
return results | 29265a41ffba7cda211fc86b8c60cae872167b12 | 3,639,614 |
def _test(value, *args, **keywargs):
"""
A function that exists for test purposes.
>>> checks = [
... '3, 6, min=1, max=3, test=list(a, b, c)',
... '3',
... '3, 6',
... '3,',
... 'min=1, test="a b c"',
... 'min=5, test="a, b, c"',
... 'min=1, max=... | c011c9386392c4b8dc8034fee33bfcfdec9845ed | 3,639,615 |
from typing import Union
from typing import Sequence
from typing import Any
from typing import Tuple
def plot_chromaticity_diagram_CIE1976UCS(
cmfs: Union[
MultiSpectralDistributions,
str,
Sequence[Union[MultiSpectralDistributions, str]],
] = "CIE 1931 2 Degree Standard Observer",
... | e9621c2e94dc7a43401905e9a633692a28a1a4d1 | 3,639,616 |
def generateFilter(targetType, left = False):
"""Generate filter function for loaded plugins"""
def filter(plugins):
for pi in plugins:
if left:
if not pi.isThisType(targetType):
plugins.remove(pi)
logger.info("Plugin: {} is filtered out by predefined filter"\
.format(pi.namePlugin()))
... | db97ecd3700bd3c7b56a26cc3d49d4825fb9dc61 | 3,639,617 |
def format_sample_case(s: str) -> str:
"""format_sample_case convert a string s to a good form as a sample case.
A good form means that, it use LR instead of CRLF, it has the trailing newline, and it has no superfluous whitespaces.
"""
if not s.strip():
return ''
lines = s.strip().splitlin... | cd691f2bfc8cc56db85f2a55ff3bf4b5afd5f30e | 3,639,620 |
from typing import Any
import json
def replace_floats_with_decimals(obj: Any, round_digits: int = 9) -> Any:
"""Convert all instances in `obj` of `float` to `Decimal`.
Args:
obj: Input object.
round_digits: Rounding precision of `Decimal` values.
Returns:
Input `obj` with all `fl... | 60529b4542a3b969b6b6fbe67fd6f26b3b7f3c25 | 3,639,621 |
def _calc_range_mixed_data_columns(data, observation, dtypes):
""" Return range for each numeric column, 0 for categorical variables """
_, cols = data.shape
result = np.zeros(cols)
for col in range(cols):
if np.issubdtype(dtypes[col], np.number):
result[col] = max(max(data[:, col])... | c135227d50b5dd7c6fb1a047ed959ef6c22733f4 | 3,639,622 |
def search(request):
"""
Display search form/results for events (using distance-based search).
Template: events/search.html
Context:
form - ``anthill.events.forms.SearchForm``
event_list - events in the near future
searched - True/Fal... | adeb3f509854ab9dcd2a50aa6833d96714d8603b | 3,639,624 |
def logout() -> Response:
"""Logout route. Logs the current user out.
:return: A redirect to the landing page.
"""
name: str = current_user.name
logout_user()
flash(f'User "{name}" logged out.', 'info')
url: str = url_for('root')
output: Response = redirect(url)
return output | 26577da8f5a4bf5feb884c493043877e7c9bd5e7 | 3,639,625 |
def load_room(name):
"""
There is a potential security problem here.
Who gets to set name? Can that expose a variable?
"""
return globals().get(name) | 14034adf76b8fd086b798cd312977930d42b6e07 | 3,639,626 |
def call_ipt_func(ipt_id: str, function_name: str, source, **kwargs):
"""Processes an image/wrapper with an IPT using an function like syntax
:param ipt_id:
:param function_name:
:param source:
:param kwargs:
:return:
"""
cls_ = get_ipt_class(ipt_id)
if cls_ is not None:
item... | 08645a857981088f6fbde79c8a2aa7057c67445f | 3,639,627 |
def is_running(service):
"""
Checks if service is running using sysdmanager library.
:param service: Service to be checked.
:return: Information if service is running or not.
"""
manager = get_manager()
if manager.is_active(service + ".service"):
return 1
return 0 | 55cef1df395c2082fa5e0243704a0804807a0b22 | 3,639,628 |
def smoothen(data, kernel):
"""Convolve data with odd-size kernel, with boundary handling."""
n, = kernel.shape
assert n % 2 == 1
m = (n-1) // 2
# pad input data
k = m//2 + 1
data_padded = np.concatenate([
np.full(m, data[:k].mean()),
data,
np.full(m, data[-k:].mean(... | 06381249118dc54524ad1617f7e0c01a273cf4a8 | 3,639,629 |
def find_node_name(node_id, g):
"""Go through the attributes and find the node with the given name"""
return g.node[node_id]["label"] | a4656659aeef0427a74822991c2594064b1a9411 | 3,639,630 |
from operator import xor
def aes_cbc_decrypt(data, key, iv):
"""
Decrypt with aes in CBC mode
@param {int[]} data cipher
@param {int[]} key 16/24/32-Byte cipher key
@param {int[]} iv 16-Byte IV
@returns {int[]} decrypted data
"""
expanded_key = key_ex... | 37b685f9e497456e75e3a3e83de9b3b4572da328 | 3,639,631 |
from typing import Dict
from typing import Counter
def score_concepts(merged_graph: AMR, counts: tuple, concept_alignments: Dict[str, str]) -> Counter:
"""
Calculate TF-IDF counts for each node(concept) in `merged_graph` according to their aligned words.
Parameters:
merged_graph(AMR): Graph which... | 73739ede67ddbc74a3f7c17740b6f31929215e11 | 3,639,632 |
def timestamp_to_double(sparkdf):
"""
Utility function to cast columns of type 'timestamp' to type 'double.'
"""
for dtype in sparkdf.dtypes:
if dtype[1] == 'timestamp':
sparkdf = sparkdf.withColumn(dtype[0], col(dtype[0]).cast(DoubleType()))
return sparkdf | 5ee647dd5452c3c1f51140db944170698e81d7be | 3,639,633 |
from typing import List
import time
def get_entrez_id_from_organism_full_name_batch(organism_full_names: List[str]) -> List[str]:
"""Retrieves the Entrez numeric ID of the given organisms.
This numeric identifier is neccessary for BLAST and NCBI TAXONOMY
searches.
This function uses Biopython functio... | e0a84006a6646633c4462a1e68dcefe78d3b3bb1 | 3,639,634 |
def gunzip(content):
"""
Decompression is applied if the first to bytes matches with
the gzip magic numbers.
There is once chance in 65536 that a file that is not gzipped will
be ungzipped.
"""
if len(content) == 0:
raise DecompressionError('File contains zero bytes.')
gzip_magic_numbers = [ 0x1f... | 8a74d6ce4d34589bb04a9ba48d32d6e8d6b6e530 | 3,639,635 |
def get_rigid_elements_with_node_ids(model: BDF, node_ids):
"""
Gets the series of rigid elements that use specific nodes
Parameters
----------
node_ids : List[int]
the node ids to check
Returns
-------
rbes : List[int]
the set of self.rigid_elements
"""
try:
... | 58f264bff7a4fe71a5cd57b719762eaf06aa6120 | 3,639,636 |
def genFileBase(f):
""" Given a filename, generate a safe 'base' name for
HTML and PNG filenames """
baseName = w2res.getBaseMulti(f)
baseName = "R"+w2res.removeGDBCharacters(baseName)
return baseName | ce0e5b8e9261eb0410d8a912e1b77cbe5e25bde3 | 3,639,637 |
import base64
def _json_custom_hook(d):
"""Serialize NumPy arrays."""
if isinstance(d, dict) and '__ndarray__' in d:
data = base64.b64decode(d['__ndarray__'])
return np.frombuffer(data, d['dtype']).reshape(d['shape'])
elif isinstance(d, dict) and '__qbytearray__' in d:
return _deco... | f5fb62ad38b8822ae304ea00e537b66b7e3b75ee | 3,639,639 |
def basic_pyxll_function_3(x):
"""docstrings appear as help text in Excel"""
return x | 3709d1bce92456b1456ed90d81002f71b7d9e754 | 3,639,640 |
import torch
def log_mean_exp(x, dim=1):
"""
log(1/k * sum(exp(x))): this normalizes x.
@param x: PyTorch.Tensor
samples from gaussian
@param dim: integer (default: 1)
which dimension to take the mean over
@return: PyTorch.Tensor
mean of x
"""
m =... | 7f6476ba3a7ec7873ddb9f66754728bb77452721 | 3,639,641 |
def get_shot_end_frame(shot_node):
"""
Returns the end frame of the given shot
:param shot_node: str
:return: int
"""
return maya.cmds.getAttr('{}.endFrame'.format(shot_node)) | efb67eb44afc807202ed46b0096627e8794d2bac | 3,639,642 |
def is_integer():
""" Generates a validator to validate if the value
of a property is an integer.
"""
def wrapper(obj, prop):
value = getattr(obj, prop)
if value is None:
return (True, None)
try:
int(value)
except ValueError:
return... | 0f8a5a48c7b9c45666f20f6feede58fa4fc2ff5a | 3,639,643 |
def int_inputs(n):
"""An error handling function to get integer inputs from the user"""
while True:
try:
option = int(input(Fore.LIGHTCYAN_EX + "\n >>> "))
if option not in range(1, n + 1):
i_print_r("Invalid Entry :( Please Try Again.")
contin... | b3554bc13a2c8a43d0279b6e800ed2f6409e755a | 3,639,644 |
def gen_binder_rst(fname, binder_conf):
"""Generate the RST + link for the Binder badge.
Parameters
----------
fname: str
The path to the `.py` file for which a Binder badge will be generated.
binder_conf: dict | None
If a dictionary it must have the following keys:
'url': ... | 65f8cfc04a11d6660c37cce669a85a133083517e | 3,639,645 |
from datetime import datetime
def downgrade():
"""Make refresh token field not nullable."""
bind = op.get_bind()
session = Session(bind=bind)
class CRUDMixin(object):
"""Mixin that adds convenience methods for CRUD (create, read, update, delete) ops."""
@classmethod
def creat... | ce9f1e8665d126b08fde6f0b4652b431b111f34c | 3,639,646 |
def height(grid):
"""Gets the height of the grid (stored in row-major order)."""
return len(grid) | b90bdb029518cfdaaa4bf93dd77b8996e646b322 | 3,639,647 |
import uuid
import json
def test_blank_index_upload_missing_indexd_credentials_unable_to_load_json(
app, client, auth_client, encoded_creds_jwt, user_client
):
"""
test BlankIndex upload call but unable to load json with a ValueError
"""
class MockArboristResponse:
"""
Mock respon... | b91b921893d2d6c672a313d20fe3820b2027fbcd | 3,639,648 |
import urllib
def parameterize(url):
"""Encode input URL as POST parameter.
url: a string which is the URL to be passed to ur1.ca service.
Returns the POST parameter constructed from the URL.
"""
return urllib.urlencode({"longurl": url}) | f665b67d3637074dcf419a1ebfb153dd7f69acb7 | 3,639,649 |
def sum_ints(*args, **kwargs):
""" This function is contrived to illustrate args in a function.
"""
print args
return sum(args) | 4eb1f78d2e26c63b7e9d6086e55e9588d0257534 | 3,639,650 |
def set_have_mods(have_mods: bool) -> None:
"""set_have_mods(have_mods: bool) -> None
(internal)
"""
return None | a8a504e19450887e473fa607fb7a33253d3de4f3 | 3,639,651 |
def user_required(handler):
"""
Decorator for checking if there's a user associated
with the current session.
Will also fail if there's no session present.
"""
def check_login(self, *args, **kwargs):
"""
If handler has no login_url specified invoke a 403 error... | 4bc794d08989729aa0e8cd8100fa66166083917a | 3,639,652 |
def student_editapplication(request):
"""View allowing a student to edit and/or submit their saved application"""
FSJ_user = get_FSJ_user(request.user.username)
award_id = request.GET.get('award_id', '')
try:
award = Award.objects.get(awardid = award_id)
application = Applicati... | ebfda9d2ac12c3d75e4ffe0dd8a7d2a170e6f80c | 3,639,653 |
def get_haps_from_variants(translation_table_path: str, vcf_data: str,
sample_id: str, solver: str = "CBC",
config_path: str = None, phased = False) -> tuple:
"""
Same as get_haps_from_vcf, but bypasses the VCF file so that you can provide formatted vari... | 018e623532de1d414157610a9e63a3657dfdc061 | 3,639,655 |
import torch
def _populate_number_fields(data_dict):
"""Returns a dict with the number fields N_NODE, N_EDGE filled in.
The N_NODE field is filled if the graph contains a non-`None` NODES field;
otherwise, it is set to 0.
The N_EDGE field is filled if the graph contains a non-`None` RECEIVERS field;
otherw... | 999eee8573d3a11d889a361905f65ce5b996a3c0 | 3,639,656 |
def to_frame(nc):
"""
Convert netCDF4 dataset to pandas frames
"""
s_params = ["time", "bmnum", "noise.sky", "tfreq", "scan", "nrang", "intt.sc", "intt.us", "mppul", "scnum"]
v_params = ["v", "w_l", "gflg", "p_l", "slist", "gflg_conv", "gflg_kde", "v_mad", "cluster_tag", "ribiero_gflg"]
_dict_ =... | 5db0e24b113c0b19dba45df66ec8e42dee3e4b1a | 3,639,658 |
def gather_grade_info(fctx, flow_session, answer_visits):
"""
:returns: a :class:`GradeInfo`
"""
all_page_data = (FlowPageData.objects
.filter(
flow_session=flow_session,
ordinal__isnull=False)
.order_by("ordinal"))
points = 0
provisional... | 516beddad0b9d58239e1d3c9ef675d2b078dd141 | 3,639,659 |
import re
def numericalSort(value):
"""
複数ファイルの入力の際、ファイル名を昇順に並べる。
Input
------
value : 読み込みたいファイルへのパス
Output
------
parts : ファイル中の数字
"""
numbers = re.compile(r'(\d+)')
parts = numbers.split(value)
parts[1::2] = map(int, parts[1::2])
return parts | 1fc8c748b37a89fe9ea3fb0283b5ec8012781028 | 3,639,660 |
def add_markings(obj, marking, selectors):
"""
Append a granular marking to the granular_markings collection. The method
makes a best-effort attempt to distinguish between a marking-definition
or language granular marking.
Args:
obj: An SDO or SRO object.
marking: identifier or list... | b7ede77fac6524cba906fd736edb9d43fe41676b | 3,639,661 |
def add_to_list(str_to_add, dns_names):
"""
This will add a string to the dns_names array if it does not exist.
It will then return the index of the string within the Array
"""
if str_to_add not in dns_names:
dns_names.append(str_to_add)
return dns_names.index(str_to_add) | 4720708778fccc7a16dc66ad52ec911a5acb1f94 | 3,639,662 |
def check_icmp_path(sniffer, path, nodes, icmp_type = ipv6.ICMP_ECHO_REQUEST):
"""Verify icmp message is forwarded along the path.
"""
len_path = len(path)
# Verify icmp message is forwarded to the next node of the path.
for i in range(0, len_path):
node_msg = sniffer.get_messages_sent_by(p... | 0080837e5f79435396d9cf6566c60bdf40d736c9 | 3,639,663 |
def ping():
"""Determine if the container is working and healthy. In this sample container, we declare
it healthy if we can load the model successfully."""
health = scoring_service.get_model() is not None # You can insert a health check here
status = 200 if health else 404
return flask.Response(re... | 8e3cde6098db42be1f93ee04ad4092bef1aec36f | 3,639,664 |
def cyber_pose_to_carla_transform(cyber_pose):
"""
Convert a Cyber pose a carla transform.
"""
return carla.Transform(
cyber_point_to_carla_location(cyber_pose.position),
cyber_quaternion_to_carla_rotation(cyber_pose.orientation)) | 3bd700c8a3f31cadedcaea798f611d97b379115d | 3,639,665 |
def _is_predator_testcase(testcase):
"""Return bool and error message for whether this testcase is applicable to
predator or not."""
if build_manager.is_custom_binary():
return False, 'Not applicable to custom binaries.'
if testcase.regression != 'NA':
if not testcase.regression:
return False, 'N... | 4f9975801bf878522b729035a31685bef170f2dd | 3,639,666 |
def _a_ij_Aij_Dij2(A):
"""A term that appears in the ASE of Kendall's tau and Somers' D."""
# See `somersd` References [2] section 4: Modified ASEs to test the null hypothesis...
m, n = A.shape
count = 0
for i in range(m):
for j in range(n):
count += A[i, j]*(_Aij(A, i, j) - _Dij... | 5deb884310984d23b70d3364d75d0795e847dcb3 | 3,639,667 |
import requests
from bs4 import BeautifulSoup
def getWeekHouseMsg():
"""
获取一周的房产信息
:return:
"""
response = requests.get(url=week_host, headers=headers).text
soup = BeautifulSoup(response, 'lxml')
house_raw = soup.select('div[class=xfjj]')
# 二手房均价
second_hand_price = house_raw[0].select('.f36')[0].string
# 二... | 775fc1b2fa26c1f48890206d5a278f842c5aeaac | 3,639,668 |
def _match(x, y):
"""Returns an array of the positions of (first) matches of y in x
This is similar to R's `match` or Matlab's `[Lia, Locb] = ismember`
See https://stackoverflow.com/a/8251757
This assumes that all values in y are in x, but no check is made
Parameters
--------... | e36b5ad1dce2b7ed18039da16aa6de7a741ecb14 | 3,639,669 |
def buildMeanAndCovMatFromRow(row):
"""
Build a covariance matrix from a row
Paramters
---------
row : astropy Table row
Entries: {X, Y, Z, U, V, W, dX, dY, ..., cXY, cXZ, ...}
Return
------
cov_mat : [6,6] numpy array
Diagonal elements are dX^2, dY^2, ...
Off-d... | f680035a39e72c9685cd563fb092109d3beb3add | 3,639,671 |
import inspect
def getNumArgs(obj):
"""Return the number of "normal" arguments a callable object takes."""
sig = inspect.signature(obj)
return sum(1 for p in sig.parameters.values()
if p.kind == inspect.Parameter.POSITIONAL_ONLY or
p.kind == inspect.Parameter.POSITIONAL_OR_KE... | c2e9edef0b2d8c18a0f9e2af90a6a1573705d590 | 3,639,672 |
def min_distance_from_point(vec, p):
"""
Minimial distance between a single point and each point along a vector (in N dimensions)
"""
return np.apply_along_axis(np.linalg.norm, 1, vec - p).min() | 2b21dec14dcb4026d97d6321d4549f49a9520218 | 3,639,673 |
def create_environment(env_config):
"""Creates an simple sequential testing environment."""
if env_config['num_candidates'] < 4:
raise ValueError('num_candidates must be at least 4.')
SimpleSequentialResponse.MAX_DOC_ID = env_config['num_candidates'] - 1
user_model = SimpleSequentialUserModel(
env_co... | eef78ba1f134b492126b51dd13357ea8687df319 | 3,639,674 |
def nb_to_python(nb_path):
"""convert notebook to python script"""
exporter = python.PythonExporter()
output, resources = exporter.from_filename(nb_path)
return output | 4a918102fc9e6c35e3c7db89f33dc5c081a17df1 | 3,639,675 |
def add(data_source: DataSource) -> DataSource:
"""
Add a new data source to AuroraX
Args:
data_source: the data source to add (note: it must be a fully-defined
DataSource object)
Returns:
the newly created data source
Raises:
pyaurorax.exceptions.AuroraXMaxRet... | 4a1d39c9280308b6dda8835663a57ba62aca7f21 | 3,639,676 |
def read_text(file, num=False):
""" Read from txt [file].
If [num], then data is numerical data and will need to convert each
string to an int.
"""
with open(file,'r') as f:
data = f.read().splitlines()
if num:
data = [int(i) for i in data]
return data | f9b61d254b1c2188ae6be3b9260f94f0657bcd3a | 3,639,678 |
def interpolate_rbf(x, y, z, x_val, y_val, z_val):
"""Radial basis function interpolation.
Parameters
----------
x : np.ndarray
x-faces or x-edges of a mesh
y : np.ndarray
y-faces or y-edges of a mesh
z : np.ndarray
z-faces or z-edges of a mesh
x_val : np.ndarray
... | 35f833a620fabbfa786b1d8e829e378b24d202ad | 3,639,679 |
def get_batch(image_files, width, height, mode='RGB'):
"""
Get a single batch of data as an NumPy array
"""
data_batch = np.array(
[get_image(sample_file, width, height, mode) for sample_file in image_files]).astype(np.float32)
# Make sure the images are in 4 dimensions
if len(data_batc... | b94d095712c14bee2d856b1dba7a6e7286f5f16e | 3,639,681 |
def ScriptProvenanceConst_get_decorator_type_name():
"""ScriptProvenanceConst_get_decorator_type_name() -> std::string"""
return _RMF.ScriptProvenanceConst_get_decorator_type_name() | a15d001dea73333e16c21697c95a8c11d6567264 | 3,639,682 |
def parse_annotation(parameter):
"""
Tries to parse an internal annotation referencing ``Client`` or ``InteractionEvent``.
Parameters
----------
parameter : ``Parameter``
The respective parameter's representation.
Returns
-------
choices : `None` or `dict` of (`str` or ... | 076e0cf5dd60eec8624310bac96dccf53d11d441 | 3,639,684 |
def search(request):
"""
Search results
"""
query = request.GET.get('query')
res = MsVerse.objects.filter(raw_text__icontains=query).order_by(
'verse__chapter__book__num',
'verse__chapter__num',
'verse__num',
'hand__manuscript__liste_id')
return default_response... | 4d5fafad400018981de68006540f4d990a1ebcea | 3,639,685 |
from typing import Tuple
from typing import List
def _compare(pair: Tuple[List[int], List[int]]) -> float:
"""Just a wrapper for fingerprints.compare, that unpack its first argument"""
return fingerprints.compare(*pair) | 9b7947898e2cbf5579a7e31dc385b54a0a1bdd62 | 3,639,686 |
import operator
import re
def output_onto(conll_tokens, markstart_dict, markend_dict, file_name):
"""
Outputs analysis results in OntoNotes .coref XML format
:param conll_tokens: List of all processed ParsedToken objects in the document
:param markstart_dict: Dictionary from markable starting token ids to Markab... | f1a917e85735e9581326e60e3add94176e4f84cc | 3,639,687 |
def vertical() -> np.array:
"""Returns the Jones matrix for a horizontal linear polarizer."""
return np.asarray([[0, 0], [0, 1]]) | 692653446e0e7f96bf2970353f7de702b9e502ca | 3,639,688 |
def resource_id(d, i, r):
"""Get resource id from meter reading.
:param d: Report definition
:type: d: Dict
:param i: Item definition
:type i: Dict
:param r: Meter reading
:type r: usage.reading.Reading
"""
return _get_reading_attr(r, 'resource_id') | 73700abbbf34f634435e1f95d52d2730cc3d532b | 3,639,689 |
import logging
def create_provider_router(neutron_client, project_id):
"""Create the provider router.
:param neutron_client: Authenticated neutronclient
:type neutron_client: neutronclient.Client object
:param project_id: Project ID
:type project_id: string
:returns: Router object
:rtype:... | c9eb1de728d141d73c9f7b169df87c01829892f6 | 3,639,690 |
from typing import List
import shlex
def split(string: str) -> List[str]:
"""
Split string (which represents a command) into a list.
This allows us to just copy/paste command prefixes without having to define a full list.
"""
return shlex.split(string) | 360fceeba7d6280e27068f61d2420cfd9fbfbcc2 | 3,639,691 |
def compute_prevalence_percentage(df, groupby_fields):
"""
base: ['topic_id', 'year']
"""
# agg_df = df.groupby(groupby_fields)['topic_weight'].sum().reset_index()
# groupby_fields.append('topic_weight')
# wide_df = agg_df[groupby_fields].copy().pivot(index=groupby_fields[0],columns=groupby_fiel... | 72bc8f04c6cf05d64ddd36b93a73a81136dfedf9 | 3,639,692 |
from datetime import datetime
def get_token_history(address) -> pd.DataFrame:
"""Get info about token historical transactions. [Source: Ethplorer]
Parameters
----------
address: str
Token e.g. 0xf3db5fa2c66b7af3eb0c0b782510816cbe4813b8
Returns
-------
pd.DataFrame:
DataFr... | 941d02b3ef4a4525e376c1b90519391c97e128eb | 3,639,693 |
def top1_accuracy(pred, y):
"""Main evaluation metric."""
return sum(pred.argmax(axis=1) == y) / float(len(y)) | d011b432c7c04331ff09d16ba8151c8c4f056ead | 3,639,694 |
import requests
def dividend_history (symbol):
"""
This function returns the dividend historical data of the seed stock symbol.
Args:
symbol (:obj:`str`, required): 3 digits name of the desired stock.
"""
data = requests.get('https://apipubaws.tcbs.com.vn/tcanalysis/v1/company/{}/dividend-... | 0775deaeaa4a6a574af62821273cbd052625c889 | 3,639,696 |
def reftype_to_pipelines(reftype, cal_ver=None, context=None):
"""Given `exp_type` and `cal_ver` and `context`, locate the appropriate SYSTEM CRDSCFG
reference file and determine the sequence of pipeline .cfgs required to process that
exp_type.
"""
context = _get_missing_context(context)
cal_ve... | a8443ae6e762322681272bb4b348f535aa4b954b | 3,639,697 |
def levy(x: np.ndarray):
"""
The function is usually evaluated on the hypercube xi ∈ [-10, 10], for all i = 1, …, d.
:param x: c(x1, x2, ..., xd)
:return: the y-value (float)
"""
w = 1 + (x - 1) / 4 # same shape as x
term1 = (np.sin(np.pi * w.T[0])) ** 2
term3 = (w.T[-1] - 1) ** 2 * (1... | e24744982def1509548dd269be596bf310ff6eb6 | 3,639,698 |
import warnings
def _select_programme(state, audio_programme=None):
"""Select an audioProgramme to render.
If audio_programme_id is provided, use that to make the selection,
otherwise select the only audioProgramme, or the one with the lowest id.
Parameters:
state (_ItemSelectionState): 'adm... | a7e5cbc9ad2be80b7bfd5f3651b610c83b3f15fe | 3,639,699 |
def puzzles():
"""
Pick one of the TOP95 puzzle strings
"""
return [l for l in TOP95.split("\n") if l] | def2fefe114fe2867f2d465dbe4b55ae74287e09 | 3,639,700 |
from datetime import datetime
def test_declarative_sfc_obs_full(ccrs):
"""Test making a full surface observation plot."""
data = pd.read_csv(get_test_data('SFC_obs.csv', as_file_obj=False),
infer_datetime_format=True, parse_dates=['valid'])
obs = PlotObs()
obs.data = data
o... | 780b4462ba01ddcd20a1e87ef8637ca174293af8 | 3,639,701 |
def standardize_ants_data(ants_data, subject_ID_col):
""" Takes df from ANTs output and stadardizes column names for both left and right hemi
"""
ants_useful_cols = ['Structure Name']
ants_to_std_naming_dict = {}
ants_to_std_naming_dict['Structure Name'] = subject_ID_col #'SubjID'
for roi in ant... | 0f5216fd75244b0b9b60fdcdf05d63bfd02a2ed9 | 3,639,702 |
def make_gridpoints(bbox, resolution=1, return_coords=False):
"""It constructs a grid of points regularly spaced.
Parameters
----------
bbox : str, GeoDataFrame or dict.
Corresponds to the boundary box in which the grid will be formed.
If a str is provided, it should be in '(S,W,N,E)' f... | 8ccc5b257666cb8bd3a87662c6b021b4ed49ccb9 | 3,639,703 |
def removeElement_2(nums, val):
"""
Using one loop and two pointers
Don't preserve order
"""
# Remove the elment from the list
i = 0
j = len(nums) - 1
count = 0
while i < j:
if nums[i] == val:
while j > i and nums[j] == val:
j -= 1
pr... | e1a836514a09fc925a49b144880960b057dfff80 | 3,639,704 |
def decrypt_ballot_shares(
request: DecryptBallotSharesRequest = Body(...),
scheduler: Scheduler = Depends(get_scheduler),
) -> DecryptBallotSharesResponse:
"""
Decrypt this guardian's share of one or more ballots
"""
ballots = [
SubmittedBallot.from_json_object(ballot) for ballot in req... | c10b9961c2f86e9d9cf26d75e276cd65b3dcfdc4 | 3,639,705 |
def returnHumidity(dd):
""" Returns humidity data if it exists in the dictionary"""
rh = []
if 'RH' in dd:
rh = dd['RH']
elif 'RH1' in dd:
rh = dd['RH1']
else:
# Convert the dew point temperature to relative humidity
Pmb = dd['airpres']/10 # hPa to mb
rh = air... | b51d5d23247780683d9d644f59e442b1c77210e8 | 3,639,706 |
def fixture_penn_chime_raw_df_no_beta(penn_chime_setup) -> DataFrame:
"""Runs penn_chime SIR model for no social policies
"""
p, simsir = penn_chime_setup
n_days = simsir.raw_df.day.max() - simsir.raw_df.day.min()
policies = [(simsir.beta, n_days)]
raw = sim_sir(
simsir.susceptible,
... | 8e1d654b4e171e8ab55023bfb55135d5067d7052 | 3,639,707 |
import json
import hashlib
def _verify_manifest_signature(manifest, text, digest):
"""
Verify the manifest digest and signature
"""
format_length = None
format_tail = None
if 'signatures' in manifest:
for sig in manifest['signatures']:
protected_json = _jose_decode_base64(... | d3c5cebcb6f63723d7356be8def0824bb3cd2726 | 3,639,708 |
def ETL_work():
""" ETL page"""
return render_template("ETL_work.html") | 08806ed7154f4820db961b54a5c852bd0c275532 | 3,639,710 |
def advanced_perm_check_function(*rules_sets, restrictions=None):
"""
Check channels and permissions, use -s -sudo or -a -admin to run it.
Args:
*rules_sets: list of rules, 1d or 2d,
restrictions: Restrictions must be always met
Returns:
message object returned by calling given f... | acf6f5494fcc632fec3bb665778a6bed3e58f19d | 3,639,711 |
def worker_id():
"""Return a predefined worker ID.
Returns:
int: The static work id
"""
return 123 | 8c8e9c570a2355a15fd9a4d1d03d0159a33ffba0 | 3,639,712 |
def get_urls(spec):
"""Small convenience method to construct the URLs of the Jupyter server."""
host_url = f"http{'s' if spec['routing']['tls']['enabled'] else ''}://{spec['routing']['host']}"
full_url = urljoin(
host_url,
spec["routing"]["path"].rstrip("/"),
)
return host_url, full_... | 059913ed12b021fce5964d54bf8b9b22132f914f | 3,639,713 |
def resubs(resubpairs,target):
"""takes several regex find replace pairs [(find1, replace1), (find2,replace2), ... ]
and applies them to a target on the order given"""
return resubpair[0].sub(resubpair[1],target)
for resubpair in resubpairs:
target = resub(resubpair,target)
return target | 49b371211de991c323fdec313801aba0ded8ff93 | 3,639,714 |
import functools
import time
def time_profile(func):
"""Time Profiled for optimisation
Notes:
* Do not use this in production
"""
@functools.wraps(func)
def profile(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} : {tim... | a4dde1d66f5987b4be1e9179da1570c252540363 | 3,639,715 |
from typing import Type
import uuid
from datetime import datetime
async def create_guid(data: GuidIn) -> Type[GuidOut]:
"""
Create a record w/o specifying a guid.
Also cleans up expired records & caches the new record.
"""
guid = uuid.uuid4().hex
validated = data.dict()
try:
awai... | 0ff0f95acc6268e5ccd081156cc9355c8db520db | 3,639,716 |
def exp_for(iterable, filename, display = False):
"""
Run an experiment for words in given iterable and save its
results to PATH_RESULTS/filename. If display is set to True, also
print output to screen.
The output is formated as follows:
[word]RESULT_SEP[size]RESULT_SEP[n+x]RESULT_SEP[diff wit... | 11933d4b4c77dcae354b307cb27ab27af3e49311 | 3,639,717 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.