content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def is_palindrome(n):
"""
Returns true/false if a number (or string) is a palindrome
"""
string = str(n)
reversed_string = str(n)[::-1]
length = len(string)
for position in range(length):
if string[position] != reversed_string[position]:
return False
return Tr... | 06840ed167a0e52fcec818b8f5328f4e6ba8fed6 | 625,902 |
import re
def modify_vars(vars_orig, var_modifiers):
"""Return a copy of `vars_orig` modified according to `var_modifiers`.
Parameters
----------
vars_orig : list of str
A list of variable names.
var_modifiers : list of str or None, optional
A list of variable modifiers. Each vari... | 58f27e60b650a219abad70501e4573ab818b8450 | 625,903 |
def ck_cmd( msg, cmd ):
"""Checks if the first n characters of msg contain cmd. Should not contain the bot prefix when passed in.
msg: String to search in..
cmd: String to search for."""
return cmd in msg[0:len(cmd)] | 0aee1511d073dfab28c090b43443ef693f27fdee | 625,904 |
def line_format(label):
"""
Convert time label to the format of pandas line plot
"""
month = label.month_name()[:3]
if month == 'Jan':
month += f'\n{label.year}'
return month | 9e3b953831bbfcf6c46a2026c96f4666ee8dacc7 | 625,905 |
import os
def fileExists(fname):
""" check if file exists"""
filestatus = os.path.isfile(fname)
return filestatus | 515cd79e202564b41edf299c6f31fe39673724dc | 625,906 |
def check_config_difference(diff, device, change_log):
"""
The function will save the config difference into the change log file
:param diff: the diff between the config files
:param device: dna device
:change_log: file to save the change diff
:return: None
"""
short_description = 'Confi... | a14c256c98a6db7063b56daab03d5ea53b3ba24e | 625,907 |
def get_sizes(G, y, labs):
""" Function to assign sizes to nodes in the graph.
INPUTS
======
G : networkx digraph
y : ADnum
labs : dictionary of graph labels
OUTPUTS
=======
A list of sizes for the graph
"""
sizes = []
for node in G:
label = labs[node]
s... | e12f6366e9dbd05c76d5d4875a298dfce7011183 | 625,908 |
def is_gevent_wait(inferred_func):
"""Note that `wait` is an alias to wait_on_objects set in the __init__.py,
the inferred_func will have the original name instead of the alias name.
"""
return (
inferred_func.name == "wait_on_objects"
and inferred_func.callable()
and inferred_fu... | 64320ed25ac57e6a9301272fa450a9cfcba86e49 | 625,909 |
import json
def format_response(output_format, response):
"""Format the API response to the desired output format"""
if not response.content:
formatted = ''
elif output_format == 'json':
formatted = json.dumps(response.json())
elif output_format == 'pprint':
formatted = json.du... | 8522ea96c27e6ac5eba1416308e5b377c4ecef66 | 625,910 |
from typing import Counter
def cigar_support(line, strand):
"""
Processing the cigar information.
[(cigar, length)], soft clip (4)
"""
cigarinfo = line.cigar
if cigarinfo[-1][0] == 4 and strand == '+':
cigar_c = int(cigarinfo[-1][1])
"""
For R2, if the length of soft c... | da141cf0cf3ce97965483d69f524eb6ccefc4ea5 | 625,912 |
def construct_attack(model, config, dset):
"""
Construct attack for `model`
and configurations `config`
and dataset `dset`
:param model:
:param config:
:param dset:
:return:
"""
return eval(config['attack_name'])(model,
**config['attack_conf... | 9c0c5ba97a6d377a4497d1d4886d315d62c8ddcd | 625,913 |
def websocketize(value):
"""Convert a HTTP(S) URL into a WS(S) URL."""
if not (value.startswith('http://') or value.startswith('https://')):
raise ValueError('cannot websocketize non-HTTP URL')
return 'ws' + value[len('http'):] | c7dd61d6e1bfbc685b4e55ad2f8e11027ece2e4c | 625,914 |
def patternToIndex(pattern):
"""
the index of the pattern in lexicographically ordered k-mers
"""
if len(pattern) == 1:
if pattern == 'A': return 0
elif pattern =='C': return 1
elif pattern =='G': return 2
elif pattern =='T': return 3
lastChar = pattern[-1:]
pref... | c8dc2995ef326ba594e10a11ed06784754cd1260 | 625,915 |
def cal_timeoff(now_time, base_time):
"""
计算两个时间之间的差值,返回值以小时为单位
"""
# 先将 now 按小时对齐
delta = now_time - base_time
return delta.days * 24 + delta.seconds / 3600 | f2f3ac54b77d8797a8da9e38a1f5c6796fb49ca7 | 625,916 |
def gradient_descent_momentum(grads, velocity, var_list, lr, mom):
"""Gradient descent with momentum update.
Args:
grads: List of gradients of the trainable variables.
velocity: List of velocity of the trainable variables.
var_list: List of variables to be optimized.
lr: Learnin... | 6ec886fc3faddeb42d2641ac480b467144899aab | 625,917 |
from typing import List
def find_duplicate_movies(filename: str) -> List[str]:
"""
Finds the duplicate movie titles from the given file.
:param filename: str
:return: list[str]
"""
with open(filename) as f:
movies = f.readlines()
seen = set()
duplicates = []
for movie in m... | 932beedcc84b283c18eaccc813285d9239a340be | 625,918 |
import os
def resp_json(payload_to_format, project_id):
"""Packages a response to send to slack
Function takes in a JSON object, and uses the following format at
the following link:
https://api.slack.com/docs/messages#composing_messages
Returns:
created JSON object, then is sent bac... | ca0b114b648fc2668a7f52f76449b1dcfb96420e | 625,919 |
import torch
def energy(x: torch.Tensor, sps: float = 1.0):
"""Calculate the average energy (per symbol if provided) for each example.
This function assumes that the signal is structured as:
.. math::
Batch x Channel x IQ x Time.
Args:
x (torch.Tensor): Input Tensor (BxCxIQxT)
... | 632009a1f35f470cb94dea4f88acd0036620d641 | 625,920 |
def get_primary_uri_field(fields):
"""Find the first field name containing URI"""
for f in fields:
if "URI" in f.field_name:
return f
return None | 696ea1b15dad3c377585674100a12c128518c4c0 | 625,921 |
def make_iterable(obj):
"""Get a iterable obj."""
if isinstance(obj, (tuple, list)):
return obj
return obj, | a430443fd78d4d481892b2df47461e548f3463d4 | 625,922 |
def sample_key(sample_key_filepath):
"""File-handle in bytes for sample-key fixture"""
with open(sample_key_filepath, "rb") as key_file:
return key_file.read() | 878d36b279b1ccbec49d4b68adfccec148d34995 | 625,924 |
def w020_from_defocus(radius, zi, deltaZ, wavelen=1.0):
"""Return the maximum wavefront error corresponding to defocus amount
`deltaZ`
Parameters
----------
radius : float
The radius of the aperture in units of length (usually mm)
zi : float
Image distance (or the distance of th... | 78cb6b684d5cb725f690bb0eb2f5b57f7ab6cb6e | 625,925 |
def create_export(module, export, filesystem, system):
""" Create new filesystem or update existing one"""
assert not export
changed = False
name = module.params['name']
client_list = module.params['client_list']
if not module.check_mode:
export = system.exports.create(export_path=name... | ba7deeff4e0ce4cf5be00badc4f05d9d7ad8f2cb | 625,926 |
import math
def radcos(v):
"""
RADCOS radians
outputs the cosine of its input, which is taken in radians.
"""
return math.cos(v) | 35ae2842b0e849a01658dc98350909025147ef54 | 625,927 |
import os
def is_absolute_path(desired_file):
"""Whether the path is absolute or not"""
return os.path.basename(desired_file) != desired_file | d2bdd69044005d88b42dae036c8dce63192ba1bc | 625,928 |
import re
def resolve_int_var(init_int_str, int_var_regex='\'?<int>([0-9]+)</int>\'?'):
"""
将需要是 int 类型的变量的 引号去除
用法: 将需要 保持 int 类型的变量 用<int></int>包围
:param init_int_str: 准备进行解析的变量<str>
:param int_var_regex: int型参数 正则表达式<str>
:return: 解析后的变量<str>
"""
re_int_var = re.compile(int_var_reg... | 3273fc024d9ecbf94459602f1aea0e04f96084fc | 625,929 |
def corrected_proj_param(big_H, lil_h, R):
"""
Eq. 4.11
Calculates the corrected projection parameter for a cloud target
Parameters
------------
big_H : int
Satellite's height above the Earth's surface, in km
lil_h : int
Cloud's altitude above the Earth's surface, in km
... | ff447c88449a5c1a92eb9bccc9231ff1f76233c6 | 625,930 |
from typing import Iterable
def prose_list(iterable: Iterable[str], conjunction: str = "or") -> str:
"""
Construct a nice natural language list of items from the *iterable*. The
default *conjunction* is "or".
"""
values = list(iterable)
if len(values) > 2:
return ", ".join([*values[:... | 7d0cbad59bd09f57e460735b7d70d071ab68c952 | 625,931 |
import re
def _is_parsable_table_type_5(table):
"""
Identifies if a table looks like this:
0 1
0 Across Across
1 1 High Barnet...
2 NaN MOHAWK - ...
3 2 Small PO...
4 NaN SPOUSE - ...
Examples:
- https://times-xw... | 4b87ef8eee2f4dfe13bda4c0166a80c1c841abc3 | 625,932 |
def get_captcha_image_element(form):
"""
Return the <img> element in an lxml form that contains the CAPTCHA.
NOTE: This assumes the first image in the form is the CAPTCHA image. If
a form has multiple images, maybe use the etree .sourceline attribute to
figure out which image is closer to the CAPTC... | 95e1edfa21458f1ed6a79d200fabe6cc75b0cc55 | 625,933 |
def get_shrinked_checkpoint_content(content, lines_to_keep)->str:
"""Shrink (reduce size) checkpoint files size"""
i = 0
original_lines = content.splitlines()
newlines = []
for line in reversed(original_lines):
if i < lines_to_keep:
newlines.append(line)
i += 1
... | 37ae3123cbb982ea7024529602451f07650a137b | 625,936 |
def base_install(session):
"""Create basic environment setup for tests and linting."""
session.install("-r", "test_requirements.txt")
session.install("-e", ".")
return session | 7ea362603ce5c062fbea34bd726a3103b92618e4 | 625,937 |
def floor_div(arr, val):
""" Floor division of array by value. """
return [i // val for i in arr] | 270d2eb53a288773a36d9cb90b44ecf8f421a34f | 625,938 |
def check_storage_profile_associated(profile_manager, ref, name):
"""Get name of VMware Storage Policy profile associated with
the specified entities
:param profileManager: A VMware Storage Policy Service manager object
:type profileManager: pbm.profile.ProfileManager
:param ref: A server refer... | 774f73e7293a55d570aaccd04d9eed7281c40048 | 625,939 |
def keep_never_expires(flags):
"""Filter flags to contain only flags that never expire.
>>> keep_never_expires([{'expiry_milestone': -1}, {'expiry_milestone': 2}])
[{'expiry_milestone': -1}]
"""
return [f for f in flags if f['expiry_milestone'] == -1] | 1da445b0b5f085b338e3b62c7c260a46ffcba1e9 | 625,941 |
import os
import imp
def load_module(name, fpath):
"""
Function to return access to the module
:param: name: Module name to be loaded
:param: fpath: Relative path to complexity_parser.py
:return: Module object
"""
return imp.load_source(
name, os.path.join(
os.path.dir... | 68cbe915d42d9902deca9dfb5137569d26c03901 | 625,942 |
import functools
import unittest
def skip_on_not_implemented(only_if=None):
"""Decorator to Ignore NotImplementedError exceptions."""
def decorator(fun):
@functools.wraps(fun)
def wrapper(*args, **kwargs):
try:
return fun(*args, **kwargs)
except NotImple... | 1d4faaeda408e2fb3171c7aa6c90c5a42210d885 | 625,943 |
from typing import Dict
from typing import Any
from typing import Optional
def get_canonical_raw(result: Dict[str, Any]) -> Optional[int]:
"""
An approximation of the raw count of reads.
Args:
result: the entry from the data collection
Returns:
the raw count (as an integer)
"""
... | 348d220d8edbfe1eae7448af4f3d647bf4e53191 | 625,944 |
def rk4_step(u, f, dt, *args):
"""Returns the solution at the next time-step using
the RK4 method. Assumes that f is time independent
Parameters
----------
u : array of floats
solution at the current time-step.
f : function
function to compute the right hand-side of the sys... | dfc8b64cebf2369ffd0020521782be9028900bfa | 625,945 |
def to_string(params):
"""
Combine a parameter dictionary into a single url string
Parameters
----------
params : dictionary
Returns
-------
url string of input dictionary (not encoded)
Examples
--------
>>> CMRparams = {'short_name': 'ATL06', 'version': '002', 'temporal':... | 6906f5013d03afcc77502583136aebd88a14e907 | 625,947 |
import requests
def delete_document(url, document_id):
"""
Wrapper around retrieve function
:param url: the base url of the REST server
:param document_id: document id to be deleted
:returns response.status_code: status code of the request
"""
url += "/documents/" + document_id
respon... | cb5f1e1cd52000dfe2b6c8162cb191b836edd5bd | 625,948 |
def is_pr_comment(event):
"""Determine if a comment applies to a pull request."""
try:
right_type = event.type == 'IssueCommentEvent'
right_payload = 'pull_request' in event.payload['issue'].to_json()
return right_type and right_payload
except (KeyError, IndexError, AttributeError, T... | 6644526d27f4d15c501da8617ad90f82993156fc | 625,949 |
import hashlib
def hash_password(password, salt):
"""
Securely hash a password using a provided salt
:param password:
:param salt:
:return: Hex encoded SHA512 hash of provided password
"""
password = str(password).encode("utf-8")
salt = str(salt).encode("utf-8")
return hashlib.sha5... | 376c28e92d4336ce7c8930289e281d3bb1f10623 | 625,951 |
def minkowski_distance(a: dict, b: dict, p: int):
"""Minkowski distance.
Parameters:
a
b
p: Parameter for the Minkowski distance. When `p=1`, this is equivalent to using the
Manhattan distance. When `p=2`, this is equivalent to using the Euclidean distance.
"""
return... | 72a1a993597355cc1c051cc8dd7156e29cae6cd9 | 625,953 |
def frange(start, end, n):
"""frange(start, end, n): Python's range(), for floats and complexes."""
# If the arguments are already float or complex, this won't hurt.
# If they're int, they will become float.
start *= 1.0
end *= 1.0
step = (end - start) / n
list = []
current = start
for k in range(0, n):
... | 1d1257ab24688a957b7071731299695fbc9ea0df | 625,954 |
import re
def natural_sort_key(string):
"""
Performs natural sort. First sort by alphabet, then by numeral.
Assumes line is comma separated, and has same format as qiime 2 manifest
file. (e.g. sample_name, path, direction)
"""
convert = lambda text: int(text) if text.isdigit() else text.lower... | 9bece3966306a2dde2386a40bbd7cf5b18ae9c25 | 625,955 |
def matchStrengthNoNoise(x, y, n):
"""Compute the match strength for the individual *x* on the string *y*
excluding noise *n*.
"""
return sum(xi == yi for xi, yi, ni in zip(x, y, n) if ni != "#") | 561c8e810249de043cde8b56e638df9db0ff40b8 | 625,956 |
def gap_detector(data, mask, start_pixel, width_gap):
"""
Reproduce a detector gap in reciprocal space data and mask.
:param data: the 3D reciprocal space data
:param mask: the corresponding 3D mask
:param start_pixel: pixel number where the gap starts
:param width_gap: width of the gap in pixe... | 0e480886ea812071726372a9d4a3052cb577c05d | 625,958 |
import torch
def get_bone_vector_from_3d_pose(pose_3d):
"""
:param pose_3d:
:return:
"""
# 17 x 16
convet_mat = torch.Tensor([
[1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 0 1
[0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 1... | d3833d5da0afca42d50bb3526aa08c56c667477f | 625,959 |
def is_reserved_node(node):
""" Return true if the node is reserved. """
reserved_title = node.title and '[Reserved]' in node.title
reserved_text = node.text and '[Reserved]' in node.text
return reserved_title or reserved_text | 57c31957b165d60b3e47b33897b9f4005dcac2b1 | 625,960 |
def third_measurer_I_P(uniqueTuplesDf):
"""
third_measurer_I_P: computes the measure I_P that counts the number of problematic tuples
(tuples participating in a violation of the constraints).
Parameters
----------
uniqueTuplesDf : dataframe
the result of the query that finds all tu... | 0e5f1d4802fdd7b680a77fc227c48d45ca31e2e2 | 625,961 |
import random
def _get_password(passwords_file):
"""
:param passwords_file: Local path of a password file
"""
if passwords_file:
with open(passwords_file, 'r') as f:
data = f.read()
passwords = [p.strip() for p in data.split('\n') if p.strip()]
else:
passwor... | 8d166dfbf8adaf1de5c7b1f9bf66dd6006fac80f | 625,962 |
import struct
def msg_port_unpack(data):
"""out of scope for now, need to read about this later!"""
return {"listen-port": struct.unpack(">H", data)[0]} | 4261ffe2e51b8264e9dcd88ac2a5a67659870607 | 625,963 |
def key_to_option(key):
"""Convert a dictionary key to a valid command line option. This simply
replaces underscores with dashes.
"""
return key.replace('_', '-') | 93a01aa1177ad87eb55fe1623181c0874659568c | 625,964 |
def formatted_username(user):
"""
user: KGS player dict
yes_status: boolean to dicate whether to contain status of user
Given a KGS player dict user, return a string containing user information
"""
rank = ""
if "g" in user["flags"]:
rank = "Guest"
elif "rank" in user:
ra... | 7cdfe4374bf4f95ab5734c90d621dc6baf9177e6 | 625,965 |
from typing import Union
from typing import Any
import json
import logging
def load_json(s: Union[str, bytes]) -> Any:
"""
Like json.loads() but prints the input if parsing fails
"""
try:
return json.loads(s)
except json.decoder.JSONDecodeError:
sep = "----------------"
log... | 2cf71a8c65c5548fc650948e9605d96463209353 | 625,966 |
def nlopt_status(constant):
"""
Convert the enumerated constant returned by the optimization process into a human-readable string.
Input
-----
constant : ``int``
The constant returned by the optimization algorithm as result.
Returns
-------
status : ``str``
A human-read... | 27eee0b0ce8955ba463845c20d07b8289764945a | 625,967 |
def render_no_change(text):
"""Render inline markdown text with no changes
"""
return [text] | 18dd284ad5986de270a6dfc552f1fc105c36e3a2 | 625,968 |
import codecs
import re
def long_description():
"""Pre-process the README so that PyPi can render it properly."""
with codecs.open('README.rst', encoding='utf8') as f:
rst = f.read()
code_block = '(:\n\n)?\.\. code-block::.*'
rst = re.sub(code_block, '::', rst)
return rst | fa36fb33ce199e20e7d57fb7a80b6ee7342fafed | 625,969 |
def alltrue(*args, **kwargs):
"""
Check if all elements of input array are true.
See Also
--------
numpy.all : Equivalent function; see for details.
"""
return all(*args, **kwargs) | 3600455608e169d0ba879d3a67c105e4a2c64488 | 625,970 |
def create_neighborhood_dict(edgelist):
"""
Create a dictionary with nodes as key and a list of neighborhood nodes as the value
@param edgelist -> A list with elements of form `(p, q, w)`
@param neighborhood_dict -> A dictionary with key `p` and value, a set `{p1, p2, p3, ...}`
"""
ndic... | c0eddc3906a4d0aed4988e4e86c6488ebc6ba413 | 625,971 |
def join(separator: str, separated: list) -> str:
"""
>>> join("", ["a", "b", "c", "d"])
'abcd'
>>> join("#", ["a", "b", "c", "d"])
'a#b#c#d'
>>> join("#", "a")
'a'
>>> join(" ", ["You", "are", "amazing!"])
'You are amazing!'
>>> join("#", ["a", "b", "c", 1])
Traceback (most ... | 4762f6ca96ff69211035dbaa31969406b80f262e | 625,972 |
def update(event, context):
"""Noop."""
return event["PhysicalResourceId"], {} | 2d897160c7342ebfdf56fe0a3fd1cbc1b3f33790 | 625,973 |
def _get_opt_attr(obj, attr_path):
"""Returns the value at attr_path on the given object if it is set."""
attr_path = attr_path.split(".")
for a in attr_path:
if not obj or not hasattr(obj, a):
return None
obj = getattr(obj, a)
return obj | db7662f11074e501a2342a038326d633010d1cb6 | 625,974 |
import random
def randomized_primality_test(n, k):
""" Checks if n is a prime number using probabilitic methods.
In particular, this function uses Fermat's primality test.
See http://en.wikipedia.org/wiki/Fermat_primality_test for a description
of the method.
Args:
n: int, number to test... | d7625531dc93e72f9a2c63f843ad9bd08673d50b | 625,976 |
import math
def sqrt(x):
"""Returns square root of x value"""
return math.sqrt(x) | 4252f3d464250cd8f63412473f5707ccdfcec95b | 625,978 |
def _is_a_camel(s):
"""Checks if a string is camelcased
ref: http://stackoverflow.com/a/10182901/386082
"""
return (s != s.lower() and s != s.upper()) | 9bdd72cd82eb46c943ddfa2d1d7b5ad91c684bb4 | 625,979 |
import pickle
def load_synthetic(name, datadir):
"""
Loads data from pickle file with the given name (produced by save_synthetic function)
:param name: name of the pickle file in datadir containing the expression data
:return: np.array of expression with Shape=(nb_samples, nb_genes) and list of gene s... | cabe16e50f4cc72e42ef3f7ac8ee23f98872ff10 | 625,980 |
def jac_or_grad(sgrad, jac, options):
"""
Returns either the simplex gradient or Jacobian depending
on the type of problem (optization or least squares).
sdiff = jac_or_grad(sgrad, jac, options)"""
least_squares = options.least_squares
if least_squares == 1:
sdiff = jac
elif least_square... | 7133a9229400d0b3654df887ef59ce33c9d0c4dc | 625,981 |
import random
def advance(sprites, path, game_state, time_since_start, delta_t, new_missiles):
"""
:param sprites: the sprites object constructed from get_sprite_details
:param path: the (key, index) tuple that describes how to find ourselves in the game_state
Example:
key, index = pat... | fd6c23ba039006d7987a81026adc0422fdc56514 | 625,982 |
import torch
def init_param(mode):
"""
Generates the identity vector for the given transformation set
Input:
:string mode: transformation set
Output:
:Tensor tau: identity vector for mode
"""
if mode == 'rotation':
tau = torch.zeros(1)
elif mode == 'translation' or mode =... | ab228916a512bfc8f02b2202f9bdf77d05fd2260 | 625,983 |
def secDegInterpolate(x1, x2, x3, y1, y2, y3, xfit):
"""second degree interpolation used by findApex"""
x12 = x1-x2
x13 = x1-x3
x23 = x2-x3
xf1 = xfit-x1
xf2 = xfit-x2
xf3 = xfit-x3
yfit = (y1*x23*xf2*xf3-y2*x13*xf1*xf3+y3*x12*xf1*xf2)/(x12*x13*x23)
return yfit | c8c566e57012e9e653de360afd9f03c73035bb41 | 625,984 |
def net_addr(addr):
"""Get network address prefix and length from a given address."""
if addr is None:
return (None, None)
nw_addr, nw_len = addr.split('/')
nw_len = int(nw_len)
return nw_addr, nw_len | 11d4b798338d88a1348ef8efd82fbc3b49b9eb7f | 625,985 |
import os
def check_dns_status(hostname, address):
"""
This function returns true if the hostname resolves to the address
"""
#return not bool(os.system("dig +short " + hostname + " | grep " + address))
return not bool(os.system("getent hosts " + hostname + " | grep " + address)) | 1e9b82cedf345e6825d78f4384aa31a5a4a1bf27 | 625,986 |
def multiply_matrices_complex_numba(A, B):
""" Multiply a complex matrix A with another complex matrix B.
Parameters
----------
A : array
First complex matrix.
b : array
Second complex matrix.
Returns
-------
array
Element-wise A * B (complex).
"""
fo... | e97a2b397fc0d3588a538e4c8bc6e85cd8c2ec81 | 625,987 |
def kw_bigram_score(concept, segment):
"""
Rank the segment using the key word search algorithm
:param segment (list): a list of the tokens in the segment
:param concept (str): the concept
:return: a numeric score of the number of occurences of the concept word normalized by document length
"""
... | 353692bd932eccc46bd6fd6e316f6919ab810d1f | 625,988 |
def even_or_odd(number):
"""Return 'Even' or 'Odd' if number is even or odd."""
if number % 2 == 0:
return "Even"
return "Odd" | bbc2acf702598943f3df7c49ccd6484d00578908 | 625,989 |
def _winpath_to_uri(path):
"""Converts a window absolute path to a file: URL."""
return "///" + path.replace("\\", "/") | 8a35cbc43ee05ea9566910b49ef6c682aad06bb1 | 625,990 |
def get_gq(df):
"""
Calculate GQ
"""
pl_arr = df[['PL_ref', 'PL_het', 'PL_hom']].values
pl_arr.sort(axis=1)
gq = [(row[1] - row[0]) for row in pl_arr]
return gq | 45a2c1666c86a31ffdc7107e890ca1192c76ecbd | 625,991 |
def binary_search(sorted_arr, wanted_num):
""" Szuka elementu w posortwanej tablicy, jeżeli znajdzie to zwraca indeks szukanego elementu. W przypadku nie znalezienia elemetu zwraca -1."""
left = 0
right = len(sorted_arr) - 1
mid = 0
while left <= right:
mid = (right + left) // 2
if ... | fc3abd941bc134effc3ce8bbe741ee3a92ea6386 | 625,992 |
def check_for_period(message):
"""Check that there is no period in the end of the subject line."""
splitted = message.splitlines()
check = not splitted[0].endswith(".")
return check | 2a59f787f92c51a288873d6d1e6bb24b40db3848 | 625,993 |
def public_and_private_rooms():
"""If present in a test, conftest.pytest_generate_tests will parametrize private_rooms fixture
"""
return True | 2155001853b873abeeb05ecfb8d9624ae83b2457 | 625,994 |
def getPrefixForNs(nsDict, ns):
"""Return prefix string for namespace."""
if nsDict.get('_default', None) == ns:
return '_default'
for pre in list(nsDict.keys()):
if nsDict[pre] == ns:
return pre
return None | 16255536399f81b0e918c4f04b2c2b01982ee57f | 625,995 |
import torch
def get_mrr(indices, targets, batch_wise=False):
""" Calculates the MRR score for the given predictions and targets
Args:
indices (Bxk): torch.LongTensor. top-k indices predicted by the model.
targets (B): torch.LongTensor. actual target indices.
batch_wise (Bool)
Ret... | f0cb8c1d5c7b4131daf9d771f18fdac84382fda3 | 625,996 |
def str2bool(val):
"""
Convert the strings "True" and "False" to the booleans True and False.
"""
if val == "True":
return True
elif val == "False":
return False
else:
raise Exception("unknown string for bool '%s'" % val) | 1121ea8080b1cebab098c612f5b48c032080d412 | 625,997 |
import logging
import sys
def set_logging(filename=None, on=True, level=logging.INFO):
"""Turn on or off logging to file or stdout.
Parameters
----------
filename: str, optional
name of the file for logging information
on: bool, optional
turn logging on or off, will close the fil... | 60515cb6a57514acf8737e75ea75028cba2ae0fb | 625,998 |
def interface(request):
""" Type of interface to use """
return request.param | f0e0ad3abc07e7ed72bbe87fa79bd332c82fc65e | 626,000 |
def GetTokensInSubRange(tokens, start, end):
"""Get a subset of tokens within the range [start, end)."""
tokens_in_range = []
for tok in tokens:
tok_range = (tok.lineno, tok.column)
if tok_range >= start and tok_range < end:
tokens_in_range.append(tok)
return tokens_in_range | 3f745d476530c17e9c407a0e4a563897cd0d78ad | 626,001 |
import time
import json
def connectionErrHandler(jsonFormat, errorStr, err):
"""
Error handler various connection errors to bmcs
@param jsonFormat: boolean, used to output in json format with an error code.
@param errorStr: string, used to color the text red or green
@param er... | e0aacfac73c8c86ce294b92b1b38663cfa3c1df1 | 626,002 |
def metadata_filter_as_dict(metadata_config):
"""Return the metadata filter represented as either None (no filter),
or a dictionary with at most two keys: 'additional' and 'excluded',
which contain either a list of metadata names, or the string 'all'"""
if metadata_config is None:
return {}
... | b851fdfc759f89571d1b39cf34d82122ad3a3e40 | 626,004 |
import os
def get_file_name(folder_name='../global_data/', file_name='PreparationScan.stl', exception_file = None):
"""
Get sorted List of filenames: search for all file within folder with specific file name, ignore specific filename
:param folder_name: Folder direcory to search
:param file_name: ... | 63fa24fe9359714dcac42c800e38077217b1f0ce | 626,005 |
def unpad(text):
"""
Unpads the text from the given block size.
:param text | <str>
:return <str>
"""
return text[0:-ord(text[-1])] | 5b992062cb85374a62b839ba53f5c110ff4aeab0 | 626,006 |
def get_parameter_default(parameter, ctx):
"""
Get the value for a specific parameter from the computer_builder or the default value of that option
:param parameter: parameter name
:param ctx: click context of the command
:return: parameter default value, or None
"""
default = None
for... | 01506b86234550e2a8c2b8332e487ef395a194bb | 626,007 |
def get_reverted_disk_rses_id_name_map(disk_rses_id_name_map):
"""Revert k:v to v:k"""
return {v: k for k, v in disk_rses_id_name_map.items()} | 51ea8b84a5d23f365b3e6a182b62ca586dae7009 | 626,008 |
def max_sub_seq(arr):
"""
Problem1
Maximal Uncontinuous Sequence
arr = [1, 2, 3, 4]
res = 6 (2 + 4)
arr = [-1, 1]
res = 1
arr = [-1, -1, -1, ...]
res = 0
length = 10 ^ 6
dp[i] = max(dp[i - 1], dp[i - 2] + arr[i])
dp[i - 1] = max(dp[i - 2], dp[i - 3] + arr[i - 1])
... | 2c341b39de42fdccedc0a15081c675660d1b03ff | 626,009 |
def print_name(name, word_count_threshold=7, break_point_ratio=0.6):
"""Splits name of item in legend into 2 lines
if word count exceeds threshold"""
words = name.split(" ")
word_count = len(words)
if word_count > word_count_threshold:
position = round(word_count*break_point_ratio)
... | 4312c9c5b4c34329ff2ac4d49d27dfae70fee1b1 | 626,010 |
def critical_point_move_to(mobj, critical_point_dir, target_pos):
"""
Move the critical_point(critical_point_dir) to the target
+-----------+
|text C |
X-----------+
Move position X to the target position instead of C (get_center()) position
@param mobj mobject
@para... | b357c3b5ef25a57ea9bf3851785747fd5eff01e2 | 626,011 |
import ipaddress
def netmask_to_prefixlen(netmask: str) -> int:
""" Takes an IP netmask and returns the corresponding prefix length
:param str netmask: IP netmask (e.g. 255.255.0.0)
:return: prefix length
"""
return ipaddress.ip_network('0.0.0.0/{}'.format(netmask)).prefixlen | 890e5f5f480ad22605853a4d8fa40ce76368312d | 626,012 |
def default_eURIFragment():
"""
Gets the default root URI fragment.
:return: the root URI fragment
:rtype: str
"""
return '/' | 7071b4abdb4c10936e867df307e1976a35e004b6 | 626,014 |
def GetBuilderSuccessMap(builder_run, overall_success):
"""Get the pass/fail status of all builders.
A builder is marked as passed if all of its steps ran all of the way to
completion. We determine this by looking at whether all of the steps for
all of the constituent boards ran to completion.
In cases wher... | 66779a5530810dce8562e39f39858eab0d5fedf6 | 626,015 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.