content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def extract_tags(lexicon):
"""Extract the set of all tags that are used in a lexicon.
The input lexicon should be a dict:
- lexicon = {wordform: {annotation: set(possible tags)}}
"""
tags = set()
for annotations in list(lexicon.values()):
tags.update(*list(annotations.values()))
r... | a9d86a5ade41210be35614515eaa9917b432e38a | 631,143 |
import os
import base64
def random_string():
"""return a short suffix that shouldn't collide with any subsequent calls"""
return '.'.join((
str(os.getpid()),
base64.urlsafe_b64encode(os.urandom(3)).decode('US-ASCII'),
)) | 8d66021c70fa41205280ecbc6b84bb05fe313a8d | 631,144 |
import six
def find_in_list(search_key, search_values, search_list):
"""Find items that match multiple search values on a single search key.
:param search_key: a key to search
:param search_values: values that match
:param search_list: list of dictionary objects to search
:return: list that match... | 8294778125d46fee8af63506d21a42fcc7ade57a | 631,146 |
import os
import sys
import shutil
def copyfile_fullpath(file_name, dest_dir):
""" Copy the file to the destination dir in the same directory structure as its original path
Returns True if file copied OK, False if not"""
directory_name = os.path.dirname(file_name)
base_name = os.path.basename(file_na... | 8f6799c57a66d8569b9e8cf81916f42b4d19653d | 631,147 |
def get_index_lm(l, m):
"""
return the index of an array ordered as
[l=0 m=0, l=1 m=-1, l=1 m=0, l=1 m=1, ....]
"""
return (l+1)**2 -1 -l + m | 3b6cbbf6e5aedda39d5786af58d4403df8d33582 | 631,148 |
def has_overflow(grad_norm):
"""
Detect inf and NaN in grad_norm.
"""
if grad_norm == float('inf') or grad_norm != grad_norm:
return True
return False | 81d02f6a7240cb3d6591ad16da315220291ffd75 | 631,149 |
def mac_to_oid(mac):
"""
Converts a MAC address to an OID string
"""
return '.'.join([ str(int(x,16)) for x in mac.split(':') ]) | 823f68a1708a2d4db6184b3aedc003f9f8fe79fe | 631,150 |
def miller_rabin_test(n):
"""Statistically test the primality of a number using the Miller-Rabin
algorithm.
"""
k, m = 0, n - 1
while True:
if m % 2 != 0:
break
else:
k += 1
m /= 2
b = 2**m % n
if (b - n) == -1 or b == 1:
return T... | f701fe157c875d2e95582ac6d607dda6bf6ed32b | 631,151 |
def stuhlinger_velocity(total_efficiency, t_m, specific_mass):
"""Stuhlinger velocity, a characteristic velocity for electric propulsion missions.
The Stuhlinger velocity is a characteristic velocity for electric propulsion missions,
and is used in calculation of optimal specific impulse. It is defined as:... | 7fb20accb5e404a6845794b4c7b41e1de8514694 | 631,153 |
def real_part_of_complex_image(image_complex):
""" Returns a matrix of only the real parts of the elements of the input matrix """
return image_complex.real | 7cc869826ac7a463c48b2e67865ee9df5ceab2e6 | 631,154 |
def is_solution(cnf, assignment):
"""Test whether the given assignment is a solution to the CNF.
assignment is a dictionary from variable names to truth values.
It is not required that all variables in the CNF are assigned.
"""
for clause in cnf:
satisfied = False
for lit in clause... | 74c83fc8c0089261d3afa344ea9ee7e62e850621 | 631,156 |
def type_repr(type_num):
"""Map a type number to its string representation."""
return str(type_num) | e3c92549d4fe4e5c949c3db38b2e8f3093f85dc1 | 631,158 |
import random
def weighted_choice(choices):
"""
Provides a weighted version of random.choice
:param choices: A dictionary of choices, with the choice as the key and weight the value
:type choices: list of tuple of (str, int)
"""
total = sum(weight for choice, weight in choices)
rand = ran... | b95c046fb009414f3b16bb78652169d0c7bdae84 | 631,159 |
def GetOption(*_args, **_kw):
"""Fake GetOption"""
return [] | eb2a223f2828dde224dd6782b674ecb9e6a366af | 631,160 |
def normalize(output_wavefunc):
""" A function to roughly normalize the wave function to 1. """
normal = max(output_wavefunc)
return output_wavefunc * (1/(normal)) | 821039e00641b1221e135f315b184ee12f5f72c5 | 631,161 |
def calculate_crashes_by_location(df):
"""
Calculates total number of crashes that occurred at each unique lat/lng pair and
generates a comma-separated string of the dates that crashes occurred at that location
Inputs:
- a dataframe where each row represents one unique crash incident
Outpu... | 355928578bf87b7c3f381813f162f1023587faa5 | 631,162 |
def toggle_err_callback():
"""JS callback for Error toggle Toggle button
Returns
-------
code : :obj:`str`
"""
code = """
let n_glyphs = ax.length;
//if toggle button active
if (cb_obj.active.includes(0))
{
for(let i=0; i<... | ca077af203397bba0c1feb4082e5815cf8ff2793 | 631,163 |
import re
def rmRT(text):
"""membuang retweet atau RT
:return: clean string from RT
:rtype: string
"""
return re.sub("\s*RT\s*@[^:]*"," ",text) | 7d1c1fa7c5db36995ab8e3213a43acdf0b343207 | 631,164 |
def merge_max_value(old, new):
"""
Merge the max element one by one in two lists.
"""
assert isinstance(old, list) and isinstance(new, list)
if old != []:
assert len(old) == len(new)
for i in range(len(old)):
assert type(old[i]) == type(new[i])
if isinstance(o... | f0fc56b454b2118a3e415872e1087b56b857dbd0 | 631,165 |
def get_role(oneandone_conn, role, full_object=False):
"""
Given a name, validates that the role exists
whether it is a proper ID or a name.
Returns the role if one was found, else None.
"""
for _role in oneandone_conn.list_roles(per_page=1000):
if role in (_role['id'], _role['name']):
... | f2f93230670ee1e514257209ff0d4df65899ac28 | 631,166 |
import requests
def href_from_link_text(url, headers, link_text):
"""
Returns the url for a link with link_text description, if this
function fails, it raises an error with tells the users a link
which creates an issue on the pycalculix repo
"""
response = requests.get(url, headers=headers)
... | 5a6669a6b8249b239af52a40ac9a0181e9589cb2 | 631,167 |
import os
import glob
def get_file_list(path):
"""
Gets the list of files in a given path
"""
os.chdir(os.path.abspath(path))
return glob.glob(f'*.pdf') | cec02f2e392e6ffd644b01ad4fa4b64aff196d42 | 631,168 |
def noblanklines(value): # pylint: disable=g-bad-name
"""Template filter to remove blank lines."""
return '\n'.join([line for line in value.split('\n') if line.strip()]) | a8e6d7d2f8ac37fe98df56700978302c60b8963d | 631,169 |
def series_sum(n):
"""This function returns the nth sum to the 2nd decimal place."""
x = 4
y = 1
if n == 0:
return str("%.2f" % 0)
if n == 1:
return str("%.2f" % 1)
else:
for i in range(n - 1):
y += (float(1) / x)
x += 3
return str("%.2f" % y) | 0d83be0f08c61ba1101d308544dd362b91732c6f | 631,170 |
def validator_count():
"""
NOTE: overriding here for fork choice test where
it is easier to test weights with more validators
"""
return 2048 | 02fd08ee6b01798489803a1a721c8dec83d18e21 | 631,171 |
def get_loopbacks(yaml):
"""Return a list of all loopbacks."""
ret = []
if "loopbacks" in yaml:
for ifname, _iface in yaml["loopbacks"].items():
ret.append(ifname)
return ret | 9651f264f80a0bfee66b012c8998c467eedecb0b | 631,172 |
import os
def list_files_at_path(path):
"""List files at a path
:param path: a file path
:return: list of files with absolute path names
"""
abs_path = os.path.abspath(path)
return [entry.path for entry in os.scandir(abs_path) if entry.is_file()] | ee6709c9b03de2eb7768586df27e05511eecc653 | 631,173 |
def mara_db_alias() -> str:
"""The database alias for mara internal data"""
return 'mara' | a06f1a08508382f10c96ddf97ec024b75f255f8f | 631,174 |
def map_size(level_of_detail):
"""determines the map width and height (in pixels) at a specified level of detail
level_of_detail, from 1 (lowest detail) to 23 (highest detail)
returns map height and width in pixels
"""
return float(256 << level_of_detail) | 3329a1d9b691c4bf6121485c000a613ad0aa3e6c | 631,175 |
import base64
def deleteFile(path):
"""
删除文件
:param path:
:return:
"""
code = """
@ini_set("display_errors","0");
@set_time_limit(0);
@set_magic_quotes_runtime(0);
function df($p){
$m=@dir($p);
while(@$f=$m->read()){
$pf=$p."/".$f;
if((is_dir($pf))&&($f!="... | 3c189a1896e4c7cdc9dee5a962c9184bf6966b5d | 631,176 |
def _is_pixel(ds):
"""checks if dataset has the size of a pixel
Checks to make sure latitude and longitude are dimensionless
Args:
value: xArray dataset
Returns:
Boolean value - true if the ds is a single pixel
"""
return (len(ds.latitude.dims) == 0) and (len(ds.longitude.dims... | 19fee150d2d321741957be41a3a42841a49dcda5 | 631,177 |
import numpy as np
def count_per_label(labels, include_labels=[], exclude_labels=[]):
"""
Compute the number of times each label occurs.
Parameters
----------
labels : numpy 1-D array of integers
labels (e.g., one label per vertex of a mesh)
include_labels : list of integers
l... | d055e63fc77af0c76490e2bf3f897cea5132b363 | 631,179 |
def load_node2vec(node2vec_file):
"""
loads a file that contains the node2vec embeddings for the graph
Arguments:
node2vec_file -- the node2vec file, where eac line is constituted by nodeid node2vec_embedding
returns:
node2vec -- dict containing the node2vec embeddings
"""
node2vec = {}
print('# loading node2... | 0fe58eca52c9a1b6dd5d2200d765076668e85a47 | 631,180 |
def prod_boiler(info):
"""
Boiler plate text for On-Demand Info for products breakdown
:param info: values to insert into the boiler plate
:param info: dict
:return: formatted string
"""
boiler = ('\n==========================================\n'
' {title}\n'
'===... | 848106e7f78dcad5e55b376c319d222c39f17725 | 631,181 |
def bubble_sort(items):
"""
冒泡排序, 还是while循环换为for循环比较习惯
最好 O(n)
最坏 O(n^2)
"""
items_len = len(items)
for i in range(1, items_len):
has_swap = False
for j in range(1, items_len):
if items[j - 1] > items[j]:
has_swap = True
items[j - 1... | fa285e97528647e7923428b1df38c6f93c66b601 | 631,182 |
def keys(dict):
"""Returns a list containing the names of all the enumerable own properties of
the supplied object.
Note that the order of the output array is not guaranteed to be consistent
across different JS platforms"""
return list(dict.keys()) | 95f2feb43054ddcacc185bcd0896d09d20df0c0f | 631,183 |
import re
def get_column_unit(column_name):
"""Return the unit name of an ivium column, i.e what follows the first '/'."""
unit_match = re.search(r"\((.*)\)$", column_name)
if unit_match:
return unit_match.group(1)
elif "amu" in column_name:
return "A" | d173fc751418a7a6639f145fd52ddc52e57835be | 631,185 |
def make_key_mapping(key):
""" Make a mapping for this key."""
# Sort the characters.
chars = list(key)
chars.sort()
sorted_key = "".join(chars)
# Make the mapping.
mapping = []
for i in range(len(key)):
mapping.append(sorted_key.index(key[i]))
# Make the inverse mapping.
... | c94a072a0ac653a9080dddbbe822d5f64820a33c | 631,186 |
def _unpad_img(padded_img, window_size, subdivisions):
"""
Undo what's done in the `_pad_img` function.
Image is an np array of shape (x, y, nb_channels).
"""
aug = int(round(window_size * (1 - 1.0/subdivisions)))
ret = padded_img[
aug:-aug,
aug:-aug,
:
]
# gc.col... | e5f58a2cb7faca8ad77b27ff26a1659138395785 | 631,187 |
def get_pow2(x):
"""Hacky version to get the greatest power of two smaller than x."""
return len(bin(x)) - 3 | d4f5cecbdf012caa4ac84cd7d23d79cdee18fd60 | 631,188 |
import os
def file_size(file: str) -> str:
"""Return file size as a string"""
try:
val = os.stat(file).st_size
return f"{val}"
except PermissionError:
return "-1"
except FileNotFoundError:
return "-1" | 13b75ef68ba9f21cd4e7b44b628f4b0b3756d48c | 631,189 |
from os.path import join, abspath, exists
import os
def apps_from(folder, include_name=True, as_list=False):
"""
Get all names of django-apps in the project in the given directory/module
Assuming you have only "core" app in "app" directory::
INSTALLED_APPS = (
'django.contrib.admin',
... | eb5ea10d673b94a11f8b7ca3b798d948418c31d4 | 631,190 |
def is_perfect_naive(num: int) -> bool:
"""
Calculates if a number is perfect in a naive way. This function iterates
all the way up to the number and checks every element.
With this approach, we would obtain:
- Temporal Complexity => O(n)
- Spacial Complexity => O(n)
"""... | 1e959824c7d6ad30ba926cb09e4bc7bb1b71e1fe | 631,191 |
def merge(tree1, tree2):
"""Merges two Splay trees, tree1 and tree2, using the last element (of highest rank) in tree1 (left string) as the node for merging, into a new Splay tree.
CONSTRAINTS: None.
INPUTS: tree1, tree2.
OUTPUT (the return value of this function) is tree1, with all the elements of both... | 1d1057d94359bb1adefad62f820299210b7622bd | 631,192 |
def _conv_edges(x, y, fx, fy, sx, sy, n_in, n_out, g=1):
"""Number of edges in convolution."""
nx = (x - fx) / sx + 1
ny = (y - fy) / sy + 1
return (fx * fy * nx * ny * n_in * n_out) / g | 9178607c81c65a216360afd488bc87e93223a1a3 | 631,193 |
def return_group1(code_check):
"""
Input : L/G/R 6 character
Return : First digits of barcode
"""
if code_check == 'LLLLLL':
return 0
elif code_check == 'LLGLGG':
return 1
elif code_check == 'LLGGLG':
return 2
elif code_check == 'LLGGGL':
return 3
elif... | 08a8ab972566c330691a3ce2252158f19b1436ff | 631,194 |
def fdtfile2fieldstring(fdtfile):
"""Make a string of field definitions separated by % (percent sign)
reading from a fdtfile or just take the string and bring into shape:
e.g. 1,AA,20,A,NC,NN%1,F4,4,F,NU,DT=E(UNIXTIME)
:param fdtfile: fdtfile or field string
:return: tuple (number of fields... | dc292c7c0f7d5e8c6c14c5b108dfd28bad13a640 | 631,195 |
import json
def retrieve_history(dataset):
"""
Retrieve history_json field from NetCDF dataset, if it exists
Parameters
----------
dataset : netCDF4.Dataset
NetCDF Dataset representing a single granule
Returns
-------
dict
history_json field
"""
if 'history_js... | 4ff170ce4b34f4264df4eeacc0cf8feccf2bbc8b | 631,197 |
def get_traces_as_tokens(traces_df, col_ref="Activity"):
"""
Groups activities executions into traces
as a string of tokens
Ex:
Activity | Timestamp
-----------------------
START | 2019-09-01
A | 2019-09-01
B ... | d31194821fcbf19184b321f8a1fe0d44b5b67c28 | 631,198 |
def str_to_disp(s):
"""Convert a string to a user-friendly, displayable string by replacing
underscores with spaces and trimming outer whitespace.
Args:
s: String to make displayable.
Returns:
New, converted string.
"""
return s.replace("_", " ").strip() | 9e677a960c7eb4c1b94871c6d29e440266e54866 | 631,199 |
import torch
def slice_entity(batch_input, batch_slice):
"""
1.从batch_input做切片,取batch_slice作为索引
2.计算均值作为entity的语义
:param
batch_input: [batch_size, time_step, hidden_dim]
:param
batch_slice: [batch_size, 2]
:return:
batch_input = torch.Tensor([
[[1, 2], [2, 3], [3, 4]],
... | 449af5c1332e8abe9ec177e18c54edcc78c59703 | 631,200 |
def fact_iter(n):
"""Assumes n is an int >= 0
* computes factorial
* number of steps:
* ignore additive constants
* ignore multplicative constants
"""
answer = 1
while n > 1:
answer *= n
n -= 1
return answer | 739ce453af961584e64ced7fb1362e2291f4e425 | 631,201 |
def to_currency(cents: int) -> str:
"""Convert a given number of cent into a string formated dollar format
Parameters
----------
cents : int
Number of cents that needs to be converted
Returns
-------
str
Formated dollar amount
"""
return f"${cents / 100:.2f}" | 086505884da17470c1d003acea23c44d6a1b605c | 631,202 |
import requests
def get_top_stories_ids(limit):
"""
returns a list with the X top stories-ids of hacker news when x equals to the given limit
"""
get_stories_id_url = \
'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty&limitToFirst={}&orderBy="$key"' \
.format(lim... | 8fe6412b3c7ea63021becebbfa18a2c79e11d80a | 631,203 |
def sum_of_self_exponential(numbers):
"""
Sums each digit raised to the power of itself
Ex: sum_of_self_exponential([2, 3, 4]) = 2^2 + 3^3 + 4^4 = 287
"""
return sum(pow(number, number) for number in numbers) | b27b88aa7a86786c9df37f4b851fb1806c6e4ba7 | 631,204 |
import requests
def get_from_gitlab_no_auth_frontend(url):
""" """
return requests.get(url) | 0fedf8ad70374af0ac6398b279ce0c895e324d8c | 631,205 |
def from_jd_to_phase(x, t0, p):
"""
:param x: jd
:param t0: ephemeris
:param p: period
:return: x in phases
"""
_x = [((jd - t0) / p) - int((jd - t0) / p) for jd in x]
return _x | 8cc9aab732917b0cad0e1872cefa6675d9890fed | 631,207 |
def subset_spike_time_by_channel(spike_time_labels, channel_id):
"""Subset spike times by specific channel ID
Args:
spike_time_labels: A numpy array of shape (n_spikes, 2), each row is [time, channel_id]
channel_id: int, channel_id
Return:
a subset of spike_time_labels from a pa... | 5f1b665cca9d30a3194199304797c68036b66499 | 631,208 |
def _drop_decimals(decimal):
"""Decimal.normalize gives 2E+1 for 20..."""
decimal = str(decimal)
if "." in decimal:
decimal = decimal.rstrip("0").rstrip(".")
return decimal | d0eeee811d54cfb5c967b4a6225c0ec50dc37789 | 631,209 |
import typing
def binary_search(list_input: typing.List[int], x: int, lower_bound: int = -1, upper_bound: int = -1):
"""
The list_input must always be sorted.
"""
if lower_bound == -1:
lower_bound = 0
if upper_bound == -1:
upper_bound = len(list_input) - 1
middle = int((lower_b... | eced33b2a081a39fe8f964d63ab0234124df8555 | 631,210 |
from datetime import datetime
def check_date_time(
y: int, mon: int, d: int, h: int = 0, minute: int = 0, sec: int = 0
) -> bool:
"""Checks if the provided date and time is valid."""
try:
datetime(y, mon, d, h, minute, sec)
except ValueError:
return False
return True | 6b268a968e446a849aa873887c6804e5c248ae53 | 631,211 |
import os
from pathlib import Path
import subprocess
def gzip_uncompressed(path):
"""[summary]
nf-core/rnaseq only takes gzipped read. Recursively walk path and
if we find any uncompressed fastqs, compress them before proceeding.
Args:
path ([type]): Path to recursively search for uncompresse... | 3567a844c8e5a92400b883367603000ca9d44839 | 631,212 |
def make_start_message(prefix: str) -> str:
"""A testable function."""
return prefix + ' sleeping!' | 150ff34a6d4176a2e725dd4ee750daa37cce558b | 631,213 |
def square(x):
"""Return the square of `x`.
Parameters
----------
x : int or float
The input number.
Returns
-------
x2 : same type as `x`
The square of the input value.
Examples
--------
>>> square(5)
25
"""
return x ** 2 | 5cd099fc07253bd5b7fcef153288ffb2fcff3d1c | 631,214 |
def get_middle(s: str) -> str:
"""
>>> get_middle("python")
'th'
>>> get_middle("cpython")
't'
"""
lists = list(s)
if len(lists) % 2 == 0:
return lists[len(lists) // 2 - 1] + lists[len(lists) // 2]
return lists[len(lists) // 2] | 6941738ab97f2cb2bb4a9afd765983648e52587d | 631,215 |
def build_cluster_info(config):
"""
Construct our cluster settings. Dumps global settings config to each cluster
settings, however, does not overwrite local cluster settings. Cluster config
takes precedence over global. Use global config for generic info to be
applied by default.
Note:
... | 02dec2a6ec659c0a579fbc77b5a9677fff9a6871 | 631,216 |
import subprocess
def _is_git_repo_dirty():
"""
Return true if there are any untracked, unstaged, or uncommitted files
"""
status = subprocess.check_output(["git", "status", "--porcelain"])
if status:
return True
else:
return False | bd112e16371220599860ddc5f1bd4cea355d422d | 631,217 |
def get_lhc_sequence_filename_and_bv(beam: int, accel: str = 'lhc'):
""" Return the default sequence filename, the sequence name and the bv-flag
for the given beam.
Args:
beam (int): beam to use.
accel (str): accelerator name ('lhc' or 'hllhc').
"""
as_built = '_as-built' if accel.l... | 1e4a9fec3efd4b59db012422175ed0b416c4729b | 631,218 |
def fatorial(a, show=False):
"""
Calcula o fatorial do valor
param: a: valor a ser calculado
param: show: (bool opcional) mostra o calculo
return: resultado no fatorial
"""
f = 1
for i in range(a, 0, -1):
f *= i
if show:
if i == 1:
... | 69f44431996fbc52014169360d2adeb7220bb454 | 631,219 |
def adapt(action: str) -> str:
"""Adapts a given action into an action that SMARTS can understand for a lane
controller. This adapter expects that the action is already a valid lane controller
action.
Args:
action (str): The action to adapt. The action should be one of four applicable
... | c33b1af4d0709aa85fd698b65dda7edf8e539854 | 631,220 |
import os
import subprocess
def command_check(command):
"""Run a command and see if it completes with returncode zero."""
print('[STATUS] checking command "%s"'%command)
try:
with open(os.devnull,'w') as FNULL:
proc = subprocess.Popen(command,
stdout=FNULL,stderr=FNULL,shell=True,executable='/bin/bash')
... | ecf978ec7bee66cba85eefcfc70b589b5a01c0ce | 631,221 |
def key2struct(jsonkey:str):
"""
string key of type my_key --> MyKey
"""
parts = jsonkey.split('_')
ret = ""
for w in parts:
ret += w.capitalize()
return ret | f21721787a30b80578976a8dc74473198d991147 | 631,222 |
import csv
def parse_cpumem_stats(fp, skip_first, skip_last):
"""
Parse CPU and memory statistics.
:param fp: the file path that stores the statistics
:param skip_first: the number of first several lines to skip (system is not yet steady)
:param skip_last: the line number (start from 1) of the fir... | cd096bc0128a3839e8ca46f403f60916a9f76d50 | 631,223 |
def value_of_card(card):
"""Determine the scoring value of a card.
:param card: str - given card.
:return: int - value of a given card. 'J', 'Q', 'K' = 10; 'A' = 1; numerical value otherwise.
"""
return 10 if card in "JQK" else 1 if card == "A" else int(card) | 265e45e1f0c29355db1efb856a666905add0e10d | 631,224 |
def calc_dihedral(v1, v2, v3, v4):
"""Calculate dihedral angle method.
Calculate the dihedral angle between 4 vectors
representing 4 connected points. The angle is in
]-pi, pi].
:param v1, v2, v3, v4: the four points that define the dihedral angle
:type v1, v2, v3, v4: L{Vector}
"""
ab... | d4a8af56fd25df51e443b1bf25c870b1aff6ae9e | 631,225 |
def classify_variant_id_error(ref_bool, tgt_bool, fgl_s, variant_id_error_type_s, variant_id_s):
"""
function to classify (no_errors, previous_error (=False gene loss), vgp_error, filter_out)
:param ref_bool:
:param tgt_bool: boolean, True: no assembly error in tgt (prior) assembly, False: assembly erro... | c2555a12b11e32bace1fb0f14b2b7c0de0487f83 | 631,226 |
import math
def euclideanDistance(point1, point2):
"""Computes the euclidean width between two entires.
Same function as in task 2.
"""
if not len(point1) == len(point2):
print("Wrong dimensions!")
return None
dist = 0
for x in range(len(point1)):
dist += pow((po... | df6992936768a8d1f867839d3e99e114ee2fa4b1 | 631,227 |
def nodes_cut_fully(graph, dest):
"""
Return the nodes divided up fully into separate partitions.
Order is established by BFS.
"""
return [[v["id"]] for v in graph.bfsiter(dest)] | f7d5609ea13327e75fb41c9d03e631c9fd69fb83 | 631,228 |
import sys
def retrive_id_from_link(link):
"""
Parse the link and retrives the id of a show
"""
# Id of a show/movie in imdb is always after '/tt', if it is not there it is a wrong link
if not "/tt" in link:
sys.exit("Invalid link!")
elements = link.split("/")
# elements[2:] beca... | 916186ddc072536553383293a3b87f049f243801 | 631,230 |
def encode_literal_num(n: int, size: int) -> bytes:
"""Send numbers as literal string in decimal
`size`: target length of the byte str
example: 123 -> ["0","0",... , "1","2","3"]
"""
s = str(n)
s = "0" * (size - len(s)) + s
# prevent overflow
assert s[0] == "0"
return s.encode("utf-8... | 09067cfad4b7304893241bf88beb50ceceb57055 | 631,232 |
def subsequenceMatch(uctext, ucterm):
"""
#returns array of the indices in uctext where the letters of ucterm were found.
# EG: subsequenceMatch("nothing", "ni") returns [0, 4]. subsequenceMatch("nothing", "a")
# returns null.
#simple subsequence match
"""
hits = []
texti = -1
termi = 0
... | 7eb0b42065d4aa796f48a61e36ec175ff60c2fb6 | 631,233 |
def centerstring(string,width):
""" Pad a string to a specific width """
return " "*((width-len(string))/2)+string | c0698d5d52f65ec38e666e8c1652b65db1263129 | 631,234 |
def stdscale(ar, ddof=0):
"""Center and scale numpy.ndarray to zero mean, unit variance.
Treats the array like a single flattened array and computes the mean and
standard deviation over all the elements.
Parameters
----------
ar : numpy.ndarray
Arbitrary numpy.ndarray that can be conve... | 083609d6947cb369a730884ca54ce93093bd470a | 631,235 |
import pandas
def desired_columns(table, columns):
"""
return a new table with the desired columns in it
"""
data = {}
for ii, cc in zip(range(len(columns)), columns):
data[ii] = table[cc]
return pandas.DataFrame(data=data) | 4b807035520a64eae83b144747c47ad95793b91d | 631,237 |
def calculate_dc_dT_CTM(temp):
"""
Seabird eq: dc/dT = 0.1 * (1 + 0.006 * [temperature - 20])
"""
dc_dT = 0.1 * (1 + 0.006 * (temp - 20))
return dc_dT | 045f1c69958f3200a813f26cf05fb18eca9384b1 | 631,238 |
def get_default_semantics(n_dim):
"""
Generate default semantics for n_dim dimensions.
Parameters
----------
n_dim : int
Number of dimensions. Indicating the number of variables of the model.
Returns
-------
semantics: dict
Generated model description.
"""
sem... | 14cac3982b146712480cd698478fb94dfb9006e1 | 631,239 |
import threading
def get_threadname():
"""return current thread name."""
cur_thread = threading.current_thread()
return cur_thread.name | 66e9eec83bd07f34c26bd652af0aee8359fe412f | 631,240 |
def josephus_bitwiseVer2(n):
""" J(2^m+l) = 2*l + 1 """
bNStr = str(bin(n))
return int(bNStr[3:]+bNStr[2], 2) | 44b42135d83524d3c3fb9fcbea18e92ff939597a | 631,241 |
import re
import os
def is_safe_path(path):
"""Check if path is safe and allowed.
"""
contains_windows_var = lambda val: re.match(r'%.+%', val)
contains_posix_var = lambda val: re.match(r'\$.+', val)
unsafeness_conditions = [
os.path.isabs(path),
('..%s' % os.path.sep) in path,
... | 6272f63a5737c2913f5888cb17a759e753716bb8 | 631,242 |
from typing import Collection
from typing import Tuple
from typing import List
from typing import Iterable
def _format_sequence(values: Collection) -> Tuple[str, List]:
"""Get SQL parameter marks for a sequence-based query, and ensure value is a sequence"""
if not isinstance(values, Iterable):
values ... | d3f912e0e32ae55004f13a25fff2fabcfa2c7db7 | 631,243 |
import argparse
import textwrap
def parse_args():
"""
Parse command line arguments
:return: parsed arguments object
"""
parser = argparse.ArgumentParser(
description = "Compare the GCAM xml files in olddir with their counterparts in newdir.",
epilog = textwrap.dedent(
""... | 168f56a35456fff6996a0264e1dab9d920bc4c76 | 631,244 |
def slice_to_list(s):
"""
Converts a slice object to a list of indices
"""
step = s.step or 1
start = s.start
stop = s.stop
return [x for x in range(start,stop,step)] | 9091c43dfc91877cf486ea9a45d862b72ad99416 | 631,245 |
def stoi(n):
"""String to integer. Handles negative values."""
return int(str(n).replace("-", "")) * -1 if "-" in n else int(n) | 4af8b859114ff7955017bbd787898f1d53556bc2 | 631,246 |
def load_data(input_data_path):
"""
loading data
"""
with open(input_data_path, encoding="utf-8"):
with open(input_data_path, 'rt', encoding="utf-8") as path_str:
data_file_list = path_str.read().splitlines()
# Get full list of image and labels
file_image = [s... | 164c34b800a29c225d81405cbec7e95b94ec7c4f | 631,247 |
import os
def read_file(path):
"""Returns contents of a given file or None if not readable."""
assert isinstance(path, (list, tuple))
try:
with open(os.path.join(*path), 'r') as f:
return f.read()
except IOError:
return None | c349ddb83f327dea727d01ffb0faf4cdc0132275 | 631,248 |
def tex_escape(text):
"""
:param text: a plain text message
:return: the message escaped to appear correctly in LaTeX
"""
# conv = {
# '&': r'\&',
# '%': r'\%',
# '$': r'\$',
# '#': r'\#',
# '_': r'\_',
# '{': r'\{',
# '}': r'\}',
# '^': r'\^{}... | 61a227f1715e63af4b4a5c2798f95411e3c6a6d6 | 631,249 |
def getPageText(doc, pno, output="text"):
""" Extract a document page's text by page number.
Notes:
Convenience function calling page.getText().
Args:
pno: page number
output: (str) text, html, dict, json, rawdict, xhtml or xml.
Returns:
output from page.TextPage().
... | 31c5b2008cbdaa39d9d2b0ebf234d0ad37c5dab0 | 631,250 |
def default_iid_function(sample):
"""
The default function for turning a Bgen sample into a
two-part :attr:`pysnptools.distreader.DistReader.iid`.
If the Bgen sample contains a single comma, we split on the comma to
create the iid.
Otherwise, the iid will be ('0',sample)
>>> default_iid_fun... | 881e0ab7ebb3702353ae602a23c753a9196100de | 631,251 |
import os
def normalize_path(path):
"""Normalize path. This is needed on windows because windows' paths are
case-insensitive."""
return os.path.normcase(os.path.normpath(path)) | 489a782406abdb0024c7d876d5baeb7f38b5dc93 | 631,252 |
def get_V_fan_rtd_C(q_hs_rtd_C):
"""(11)
Args:
q_hs_rdt_C: 熱源機の定格冷房能力(W)
q_hs_rtd_C: returns: 定格冷房能力運転時の送風機の風量(m3/h)
Returns:
定格冷房能力運転時の送風機の風量(m3/h)
"""
return (1.69 * q_hs_rtd_C * 10 ** (-3) + 14.5) * 60 | abd815e29bafada0363f3e90aea9c7fc6f27b0c3 | 631,253 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.