content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import binascii
def enc( msg, k ):
"""
Simple encoding by exoring stuff with a key k
"""
return int( binascii.hexlify( msg.encode() ), 16 ) ^ k | d60a758ab3825d917f84440fce441366453aa073 | 26,648 |
from datetime import datetime
def validate_time_format(time_in):
"""time stamp format checker
validate if the timestamp since is given in the correct format or not.
if not give an warning for the client to change the timestamp format.
Args:
time_in (datetime.datetime): The time stamp in for ... | 9cd10b271875d83b1e30ed6bbec141194e582b50 | 26,649 |
def check_waypoints_correct(waypoints, goal_point):
"""
checks if final waypoint matches with the goal point
has a built in try catch to see if waypoints is empty or not
"""
#waypoints = waypoint_array.tolist()
try:
if waypoints[-1] == tuple(goal_point):
return T... | 3df3e8ed0b3f17e1b37b969524ed85897b231ded | 26,650 |
from typing import List
from typing import Dict
def get_index_of_the_arline_sorted_list(airport_sorted_by_nb_of_flights: List[str]) -> Dict:
"""
Create a dictionnary of the flight arranged in alphabetical order with their index as value to keep the right order
of the airport sorted by number of flight.\n... | 004355204a04d053b165569294c513261074f704 | 26,651 |
import math
def hsv_to_rgb(h,s,v):
""" Convert H,S,V values to RGB values.
Python implementation of hsvToRgb in src/neuroglancer/util/colorspace.ts """
h*=6
hue_index = math.floor(h)
remainder = h - hue_index
val1 = v*(1-s)
val2 = v*(1-(s*remainder))
val3 = v*(1-(s*(1-remainder)))
... | 3795f6bde05f181489be7f7750fdbd1a4886dffd | 26,652 |
def kron_delta(a:float, b:float) -> int:
"""Cannonical Kronecker Delta function.
Returns 1 if inputs are equal returns 0 otherwise.
Args:
(:obj:`float`): First input argument
(:obj:`float`): Second input argument
Returns:
(:obj:`int`) Kronecker delta result {0, 1}
"""
... | 0e7bad79e230740cf35a614dbb21cac90e1cae0c | 26,653 |
def rectangle_area(a,b):
"""Calculate rectangle area"""
return a*b | 60bfd42f38b489ba04c48badbff8fec717ecc53b | 26,655 |
import torch
def cross_entropy(y_hat, y):
"""
Compute the cross entropy as the loss of some nets
Parameters
----------
y_hat : [tensor]
the prediction value
y : [tensor]
the real labels
Returns
-------
[tensor]
the vector of every cross entropy loss. They ... | 622fb9a525c3f99eba0bc3e03a2f4a290f6a36df | 26,656 |
def iscurried(f):
"""Return whether f is a curried function."""
return hasattr(f, "_is_curried_function") | c97efcf3d5df1ce9e4ff90bfdc79b9d0a39e3204 | 26,657 |
def unique_fname(full_path: str) -> str:
"""Get unique file name for given full path to MELD data file. The return format is '[dialog]_[utterance]'.
:param full_path: full path to MELD .mp4 data file
:return: unique id of data file (only unique within dataset directory)
"""
fname = full_path.split(... | 29bffc8a2028ac126709fe17d9e2e1d2914bf769 | 26,658 |
from typing import List
from typing import Dict
import re
def confidence_cm(
region: List[float],
subfam_counts: Dict[str, float],
subfams: List[str],
subfam_rows: List[int],
repeats: int,
node_confidence_bool: bool,
) -> List[float]:
"""
Computes confidence values for competing annota... | ec61f4d9a006f8e4749c282d977ecc05d5025198 | 26,659 |
def calculate_single_list_score(l):
"""
Input -> list of string
Output -> Dictionary {'item': score}
"""
score_dic = {}
i = 0
for rec in l:
score_dic[rec] = len(l) - i
i = i + 1
return score_dic | b77ff4715a41ab59551adec3b8171814878b5c33 | 26,660 |
def partition(f, alist):
"""
Partition is very similar to filter except that it also returns the
elements for which f return false but in a tuple.
>>> partition(lambda x : x > 3, [1,2,3,4,5,6])
([4, 5, 6], [1, 2, 3])
"""
return (filter(f, alist), filter(lambda x: not f(x), alist)) | 928221a285c9e18ae6c9188f2842faf8e94074d6 | 26,661 |
def inferGroup(titlebuffer):
"""infers the function prefix"""
if titlebuffer:
if titlebuffer[0] == "*":
return "*var*"
if titlebuffer[0] in ["-", "_"]: #["*", "-", "_"]
#strip first letter
titlebuffer = titlebuffer[1:]
if titlebuffer.startswith("glfw"):
return "glfw:"
idx = titlebuffer.rfind(":... | 6bf1104f4f8454ec8251565c098cb5a7e7faf792 | 26,663 |
def phase_increment(f_out, phase_bits, f_clk):
"""
Calculate the phase increment required to produce the desired frequency.
:param f_out:
:param phase_bits:
:param f_clk:
:return:
"""
return int(f_out * 2**phase_bits / f_clk) | 0b8a3fe25d006058781f13c2cd7e73af0243ac6b | 26,664 |
def matrixInvert(M):
"""\
Returns the inverse of matrix `M`.
I use Guassian Elimination to calculate the inverse:
(1) 'augment' the matrix (left) by the identity (on the right)
(2) Turn the matrix on the left into the identity by elemetry row ops
(3) The matrix on the right is the inverse (was ... | f3b763fff8c6b7cd96ca49b8d36dc48ef6fa7e2c | 26,666 |
import struct
def read_lc_int(buf):
"""
Takes a buffer and reads an length code string from the start.
Returns a tuple with buffer less the integer and the integer read.
"""
if not buf:
raise ValueError("Empty buffer.")
lcbyte = buf[0]
if lcbyte == 251:
return (buf[1:], N... | fcc1b0fe4cfd8186537700ee124e849473b1fd07 | 26,668 |
def expand_cluster(OW_eddies_box, box, xy, edge, label):
""" Expand the edge dimensions of boundary
If we make it through the column/row, we don't have any more OW masks in this
dimensions and we return True"""
# If moving in x or y direction
if xy == 'x':
n = len(OW_eddies_box[0])
... | 9fb1fe3e93e41621e310a3b58ba21ae22452fe1f | 26,669 |
def prefixM(prefix, s):
"""为字符串添加前缀,对于多行字符串,每行都添加前缀"""
if '\n' not in s:
return prefix+s
ret = ''
lines = s.split('\n')
lineCount = len(lines)
for index in range(lineCount):
ret += prefix
ret += lines[index]
if index != lineCount-1: # 最后一行不要添加换行符
ret... | 135043bb3d3f26afe6393a8b6b005c1e4508b1a4 | 26,670 |
def no_magnitude(arr):
"""Return 0 as magnitude for a given matrix, which is used for baseline
without magnitude ordering
Args:
arr (numpy array): a numpy array
Return:
0
"""
return 0 | 3b610ed5e52ce72485b53c198c144cd2d8c11f52 | 26,671 |
def saddle_points(matrix):
"""
Find saddle points in a matrix
:param matrix list - A list of rows containing values.
:return list - A list containing dictionary(ies) indicating
where the saddle point(s) in the matrix are.
It's called a "saddle point" because it is greater than or
e... | d1cd547f2026f3529bea27003b4172ce13e73c8f | 26,672 |
def Cross(a,b):
"""Cross returns the cross product of 2 vectors of length 3, or a zero vector if the vectors are not both length 3."""
assert len(a) == len(b) == 3, "Cross was given a vector whose length is not 3. a: %s b: %s" % (a, b)
c = [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]]
re... | 1e4af47c6e6a1d9ab9572d0618b5c6b9e27829be | 26,675 |
def provide_dummy_feature_list():
"""Create a list of dictionaries that have similar structure as the featurization output.
Returns:
list -- list of dictionaries
"""
feature_list = [
{
"name": "AZOHEC",
"metal": "Zn",
"coords": [1, 1, 1],
... | a8ba36dbd56326cca3d76c30aa3b69220fdd8051 | 26,679 |
from typing import Iterable
from typing import Dict
def get_substr_frequency(string: str, substrings: Iterable[str]) -> Dict[str, int]:
"""Get dictionary with frequencies (vals) of substrings (keys) in given string."""
return {s: string.count(s) for s in substrings} | 370e0d7fcaef7efa3ca21a80519b9f36934e23a7 | 26,680 |
import torch
def poolfeat(input, prob, avg = True):
""" A function to aggregate superpixel features from pixel features
Args:
input (tensor): input feature tensor.
prob (tensor): one-hot superpixel segmentation.
avg (bool, optional): average or sum the pixel features to get superpixel feat... | 0bcc1dd7b449997491e1e25378ae09eb8f3d0592 | 26,683 |
from datetime import datetime
import json
def gen_rows(csvdata):
""" Generate rows from data """
rkrows = []
headerline = list(csvdata[0].keys())
rkrows.append(headerline)
for rk in csvdata:
rkline = []
for line in rk.values():
if line is None:
rkline.ap... | fc8722fe450da8bbd0523e57e60854ce1874ffbf | 26,684 |
import hashlib
def calculate_identicon(user_id: str) -> str:
"""
Calculate an identicon hash string based on a user name.
:param user_id: the user name
:return: an identicon string
"""
return hashlib.sha256(user_id.encode()).hexdigest() | e22e817da8a38ab289e4c623f8cbcba370317223 | 26,685 |
import sys
import configparser
import os
def load_config(config_file):
""" Returns a ConfigParser for the default config file, or for the file
located at config_file if provided. """
platform = None
if sys.platform.startswith("linux"):
platform = "linux"
else:
platform = "macosx"
... | 8822755dbbd04edd0747f8fb70131031bf3699c7 | 26,686 |
def ldap_role_group_exists_any(handle):
"""
Checks if any ldap role group exists
Args:
handle (ImcHandle)
Returns:
None
Examples:
ldap_role_group_delete_all(handle)
"""
mos = handle.query_classid('AaaLdapRoleGroup')
for mo in mos:
if mo.name and mo.dom... | b223019ee89780198fcdf22ea62691086ee20829 | 26,687 |
def fold_fortran_code(content, width=79):
"""Simplistic fold to n columns, breaking at whitespace.
Fortran line continuation (&) with a six-space following indent
are used where necessary.
"""
lines = content.split(sep="\n")
result = ""
for input_line in lines:
words = input_line.sp... | 17c7288e412fc9567a9bec1b4c1e740145cf27b7 | 26,689 |
import shutil
def command_exists(command: str) -> bool:
"""
Checks whether some external utility is installed and accessible to this script.
Args:
command: The name of the binary/command to look for. It must be a single name; arguments and shell command lines
are not accepted.
Re... | f9160163289f75af6a602641fc357addf0fc18bc | 26,690 |
def assignIfExists(opts, default=None, **kwargs):
"""
Helper for assigning object attributes from API responses.
"""
for opt in opts:
if(opt in kwargs):
return kwargs[opt]
return default | 5ecc18a6bd9548e7a036aa3956718aa80252359f | 26,691 |
import os
def has_terminal():
"""Return True if the script is run in a terminal environment
The environment variables USER and TERM are checked.
USER TERM has_terminal
root anything True
root not defined False
http anything ... | d92dba4f7b36ea3e2b868db08529b21d82c3f9b1 | 26,692 |
def me_follow(type, ids):
"""
Follow artists or users. Max 50 ids
"""
return 'PUT', '/me/following', {'type': type}, {'ids': ids} | d72007e0e06ffe558be893f69b2a8f7c334f5d42 | 26,693 |
from typing import Iterable
from pathlib import Path
def quoted_paths(paths: Iterable[Path]) -> str:
"""Return space separated list of quoted paths.
Args:
paths: iterable of paths.
Returns:
comma separated string of paths.
"""
return " ".join([f'"{p}"' for p in paths]) | f34d94918c89d999dbbfa318c95b84f419c7aa60 | 26,694 |
import os
def loadSuiteFiles(path, start="test_", end=".yaml"):
"""加载用例文件"""
f = []
if os.path.exists(path):
print(path)
if os.path.isfile(path) and os.path.basename(path).startswith(start) and os.path.basename(path).endswith(end):
f.append(path)
return f
e... | 518f6f120a123e1790cd653a56dec44e7a3a96db | 26,695 |
import json
def write_json_to_file(data, outfile):
"""write_json_to_file.
Writes a JSON dump of the passed data to the specified file, or returns to stdout if outfile is None
:param data: Data to dump to JSON
:param outfile: File to write. Uses stdout if None
>>> print(write_json_to_file({'stri... | 5dc465aa082731f9191bc2621598951859579862 | 26,696 |
from typing import Sequence
from typing import Iterator
def chunks(elements: Sequence, size, lazy=False) -> Iterator[Sequence] | list[Sequence]:
"""Create successive n-sized chunks from elements."""
generator_ = (elements[i:i + size] for i in range(0, len(elements), size))
if lazy:
return generat... | 1112ebd4868fe5efb6f444a527ced436e4d59f1b | 26,697 |
def compute_sliced_len(slc, sequence_len):
"""
Compute length of sliced object.
Parameters
----------
slc : slice
Slice object.
sequence_len : int
Length of sequence, to which slice will be applied.
Returns
-------
int
Length of object after applying slice o... | 57b330de7bb7a54d2d6331a72f0a88e005c83d10 | 26,700 |
def _get_json_schema_node_id(fully_qualified_name: str) -> str:
"""Returns the reference id (i.e. HTML fragment id) for a schema."""
return 'json-%s' % (fully_qualified_name,) | eafdacc1e7c4f2feabcd5b486fb264d33332266d | 26,701 |
def kg_derive_facts(idx_subject, idx_object, compute_o_idx=False):
"""
derives fact based on pattern matching inside the knowledge graph
therefore the indices (subject -> [object1, ..., objectn] and object -> [sub1, ..., subn]
are used
@param idx_subject: dictionary which maps each subject of a rela... | f57fa608019cddc01d9363dc464a977dd546c6df | 26,702 |
def create_reverse_complement(input_sequence):
"""
Given an input sequence, returns its reverse complement.
"""
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}
bases = list(input_sequence)
bases = reversed([complement.get(base, base) for base in bases])
bases = ''.join(bases)
retur... | 6d33d449f17bcfec59f762c7d1f1e3b86ea8a975 | 26,704 |
def truncate(string, max_bytes):
"""
Truncates a string to no longer than the specified number of bytes.
>>> truncate('foobar', 8)
'foobar'
>>> truncate('hello', 5)
'hello'
Lob off "partial" words, where practical:
>>> truncate('lorem ipsum dolor sit amet', 21)
'lorem ipsum […]'
... | 67c6fd0c0b4ec709ce0d38ae010aed888ce9d11c | 26,705 |
import os
def stamp_name(workdir, phase, unique):
"""Get a unique name for this particular step.
This is useful for checking whether certain steps have finished (and thus
have been given a completion "stamp").
Args:
workdir: The package-unique work directory.
phase: The phase we're in e.... | af92152ef265f993108497c38b628bbd9ba5336e | 26,706 |
import re
def remove_tags(text):
""" Return the text without any HTML tags in it.
@param text: The text to process
"""
return re.sub('<[^<]+?>', '', text) | 47c9ff7af6466b92b3dd3a4cdc38616231efaa11 | 26,707 |
def rectangle_to_string(rect):
"""
print out rect
"""
top_left = rect.topLeft()
size = rect.size()
return f"QRect({top_left.x()}, {top_left.y()}) ({size.width()}, {size.height()})" | 8fbf5156c0e3b375af0a2cdd39ccc059f0b053b0 | 26,709 |
import os
def save_model_name(opt, path_save):
"""
Creates a path and a name for the current model.
:param opt: Args from the script
:type opt: Dict
:param path_save: Folder we want to save the weights
:type path_save: str
:return: Saving path for the model
:rtype: str
"""
if ... | 0a16e27e39bec1c291d40aa1a9f2095ab2feef5d | 26,711 |
def dig(your_dict, *keys):
"""digs into an dict, if anything along the way is None, then simply return None
"""
end_of_chain = your_dict
key_present = True
for key in keys:
if (isinstance(end_of_chain, dict) and (key in end_of_chain)) or (
isinstance(end_of_chain, (list, tupl... | f6901018c23324f8d92bfea86c22a2ee02eeed27 | 26,712 |
def _merge_str(l):
"""Concatenate consecutive strings in a list of nodes."""
out = []
for node in l:
if (out and isinstance(out[-1], str) and
isinstance(node, str)):
out[-1] += node
else:
out.append(node)
return out | d83de96151ad10576d65866b2f38f38d839ba99f | 26,715 |
def has_gendered_pronouns(doc):
"""
Doc-level spaCy attribute getter, which returns True if
there are any pronouns (tag_ "PRP" or "PRP$") in the Doc
with a "m" or "f" gender.
"""
pronoun_genders = [token._.gender for token in doc if token.tag_ in ["PRP", "PRP$"]]
has_gendered_pronoun = any([... | 2b58db4fb972766502ca94e17140946ddd51467e | 26,717 |
def int_to_char(int_):
"""Return an ascii character in byte string form for a given int"""
return bytes([int_]) | 58ea0118590caa730746540761dc6c4bed42b630 | 26,719 |
def leader_kwargs():
"""Input data (as coming from the view layer)."""
leader = {}
leader["length"] = "00000"
leader["status"] = "n"
leader["type"] = "a"
leader["level"] = "m"
leader["control"] = " "
leader["charset"] = "a"
leader["ind_count"] = "2"
leader["sub_count"] = "2"
... | c58a26f9e2ea52223d46d82b30363051abef3787 | 26,720 |
def notmat(texto,klines=[
'comisi', 'vierne', 'sabado', 'lunes ',
'martes', 'mierco', 'jueves','doming'
]):
"""Return True if line belongs to materia's info, return False otherwise"""
texto=texto.lower()
texto=texto.strip()
if texto[0:6] in klines:
return True
elif ... | 66b1c6c7dfb95f46a0225ecfae659b9625936dad | 26,721 |
from typing import List
from typing import Callable
from typing import Any
def decorate(decorators: List[Callable[..., Any]]) -> Callable[..., Any]:
"""Use this decorator function to apply a list of decorators to a function.
Useful when sharing a common group of decorators among functions.
The original ... | 2f31acdd75067a8943509c98243c855399092109 | 26,722 |
def drop_trailing_zeros_decimal(num):
""" Drops the trailinz zeros from decimal value.
Returns a string
"""
out = str(num)
return out.rstrip('0').rstrip('.') if '.' in out else out | 6ef19f6b0ec01a3d8cb41264e6930864bba1cd2a | 26,723 |
import os
def get_plugin_path(home, plugin_type, plugin_name, editable=False):
"""Return path to plugin.
:param home: Path to honeycomb home
:param plugin_type: Type of plugin (:obj:`honeycomb.defs.SERVICES` pr :obj:`honeycomb.defs.INTEGRATIONS`)
:param plugin_name: Name of plugin
:param editable... | f51418d00a4adc1bb02f7a6d9c6af8dbd6e3cb2a | 26,724 |
from typing import Deque
def json_path(absolute_path: Deque[str]):
"""Flatten a data path to a dot delimited string.
:param absolute_path: The path
:returns: The dot delimited string
"""
path = "$"
for elem in absolute_path:
if isinstance(elem, int):
path += "[" + str(elem... | 7c61f784fa269925e42ac5f1cc3de9e2c55b9718 | 26,725 |
def getbytes(obj):
"""Converts an object to bytes.
- If the object is None an empty byte string is returned.
- If the object is a byte string, it is returned.
- If the object is a str, the value of `str.encode('utf-8')` is returned.
- If the object is a memoryview, the value of `memoryview.tobytes(... | 6f44bcbb31fa9c1b0af812932ada08acf2f3cbfe | 26,726 |
def composite(vol, cmr):
""" Ranks securities in a composite fashion.
Parameters:
- `vol` : :class:`dict` volatility portfolio.
- `cmr` : :class:`dict` momentum portfolio.
.. note::
at this point, the same tickers are present in both portfolios. Their
ranking only is differen... | e6e74c1f53477b8200b777e749cf556dc981c51e | 26,729 |
def _get_single_node(nodes, allow_zero=False):
"""Helper function for when a particular set of nodes returned from `xpath` should have exactly one node.
If null_case is False,
"""
if len(nodes) == 1:
return nodes[0]
elif len(nodes) == 0 and allow_zero:
return None
else:
... | 08efda323d489590d66833a3b4ebe94c400a5205 | 26,730 |
def get_input_mode(mode_description_ls, input_tips=None):
"""
获取输入,并根据 mode_description_ls 返回选择的 mode
:param mode_description_ls: 第一个item为默认模式 [[mode, description], ……]
description 为对应的输入
:param input_tips: 不设定时将根据 mode_description_ls 自动生成
"""
description_mode_dict = {str(description): str(... | e78209bc3119308af9040e854597f1f7c56b601a | 26,731 |
import re
def text_url(text_content):
"""
判断文本中是否存在微博URL
:param text_content: 处理对象文本
:return: 是否含有url(1:有,0:无),url数量
"""
url = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', text_content)
if url:
return 1,len(url)
else:
return 0,0 | 68177c281d1514f952a3636f0c6381d9e11f33dd | 26,733 |
from pathlib import Path
import errno
import os
def args_path_ensure_exists(file_path: str) -> Path:
"""Returns a `Path` object containing the resolved `file_path`.
Raises `FileNotFoundError` if the path does not exist.
"""
path = Path(file_path).resolve()
if not path.exists():
raise File... | 4a50d2a76d6f219836ab2d2c200c4269b144f4ba | 26,734 |
def faConverter(arr):
"""
"""
# print(arr)
results = []
for _s in arr:
converted = []
converted.append('fa')
go_up = True
for _c in _s:
if _c == '-':
go_up = True
continue
if go_up:
converted.appe... | 8995e0be2ed403c3d8552110e36e11fa01cc22fc | 26,736 |
def find_namespace_vars_usages(analysis, namespace_usage):
"""
Returns usages of Vars from namespace_usage.
It's useful when you want to see Vars (from namespace_usage) being used in your namespace.
"""
usages = []
for var_qualified_name, var_usages in analysis.get("vindex_usages", {}).items(... | 8d70b838c18e71e9483d7ccc18c7e70e2ba2a1f6 | 26,737 |
def mf_list(name, y1, y2):
""" list of all yearly files in decade starting in year Y """
return [name+f'{y:04d}-{m:02d}.nc' for y in range(y1,y2) for m in range(1,13)] | 5db4d90a44292380cd339c96894d229e9379a1e3 | 26,739 |
def f_Wint(a, b, c, dh_IS, m_max):
"""
y-intercept of Willans Line
"""
return (c/a)*(m_max*dh_IS - b) | 488c133b973f312359602f41edcb70a487d733d1 | 26,740 |
def get_quote():
"""
Responsible for getting a quote.
Args:
Returns:
str - a quote
"""
return "This is quote from latest master branch! Random quotes coming soon!" | 49236f5b52c08e3bec023c09d52dc13eb07657f9 | 26,741 |
import torch
def linreg(X, w, b):
"""
Return the matrix multiply result of X*w+b
Parameters
----------
X : [tensor]
the variablies of the question
w : [tensor]
the weight of this linear reg
b : [tensor]
the bias of this linear reg
Returns
-------
[tens... | 311cd5636977c608986d536c585e9c50a8a32557 | 26,743 |
def is_annotation_constant(thing):
""" Returns whether the annotator can prove that the argument is constant.
For advanced usage only."""
return True | 99dd8eb2fd168cc70173a4a17e2b6b50d0c16271 | 26,744 |
import os
from pathlib import Path
def get_datafolder_files(datafolder_path, pattern='.wav'):
"""Get all files with specified extension in directory tree
Return: list of file pathes
"""
filelist = []
for root, _, filenames in os.walk(datafolder_path):
for filename in filenames:
if Path(filename).... | 90becba841243117624f6de4fedb32c959ca59e0 | 26,745 |
import json
def load_dexpreopt_configs(configs):
"""Load dexpreopt.config files and map module names to library names."""
module_to_libname = {}
if configs is None:
configs = []
for config in configs:
with open(config, 'r') as f:
contents = json.load(f)
module_to_libname[contents['Name']] ... | b3a8763ee182fa7e9da968404369933e494663b5 | 26,746 |
def reconstruct_standard_path(
data,
next_matrix,
start,
end
):
"""
:param list data: a list of :obj:`decitala.search.Extraction` objects.
"""
path = [start]
if end.onset_range[0] <= start.onset_range[-1]:
return path
while start != end:
start_index = next((index for (index, d) in enumerate(data) if... | 011feb0e8bbd3fef4405675f6f86789d8d7e8a3a | 26,747 |
from typing import Any
from typing import Callable
def cast_field(field_value: Any, column_type: Callable) -> Any:
"""
Returns the casted field value according to the DATATYPE_MAPPING above
:param field_value: value of the field (Any)
:param column_type: class constructor / function that casts the da... | d2aa57bd593f9bc992e3f1d51af62d1077ccda44 | 26,748 |
def hit_location_cmp(hit1, hit2):
"""
Is the location of hit1 before the location of hit2? Used to sort hits.
"""
diff = hit1.location.start() - hit2.location.start()
return 0 != diff and diff or hit1.location.end() - hit2.location.end() | 938c9c5e8d8e00afd24b32eaeaa847300268e61d | 26,749 |
def match(freq1, freq2):
"""
Due to noise considerations, consider frequencies with difference
less than 20Hz as equal.
"""
return abs(freq1 - freq2) < 20 | ef5d023f8ca9c69e1ee2a2f17387ed825183d94c | 26,752 |
def CoolerON():
""" Switches ON the cooling. On some systems the rate
of temperature change is controlled until the
temperature is within 3 deg. of the set value.
Control is returned immediately to the calling
application. """
return None | 1e3e35e687188c98264c9e9c0b4e4d52e2832ba3 | 26,753 |
import pkg_resources
def find_plugins(plug_type):
"""Finds all plugins matching specific entrypoint type.
Arguments:
plug_type (str): plugin entrypoint string to retrieve
Returns:
dict mapping plugin names to plugin entrypoints
"""
return {
entry_point.name: entry_point.l... | f6d6e4debdaec478b14c87582b7e69a9a9bf929b | 26,754 |
from typing import List
def _read_resultset_columns(cursor) -> List[str]:
""" Read names of all columns returned by a cursor
:param cursor: Cursor to read column names from
"""
if cursor.description is None:
return []
else:
return [x[0] for x in cursor.description] | cacefb20b12f327647d1f77bb12216c80388fcd6 | 26,755 |
def apply_function_per_metric(metric_type):
""" Select the proper function the applied in the web service that retrieves the values per pod.
Args:
metric_type (str): The type of the metric
Returns:
str: the name of the function
"""
net_metrics = ["container_network_receive_bytes_to... | 213cd13f5cceee6888227552e26096a1847edb7e | 26,757 |
def max_dict(d):
"""Return dictionary key with the maximum value"""
if d:
return max(d, key=lambda key: d[key])
else:
return None | 446c185a2e986c8a58672d0571f0f100340be7e4 | 26,758 |
def clean_raw_data(df):
"""
Quality Control of the raw dataest.
parameters
-------------
df : data frame
The dataframe of the raw data.
Must have the index of genes & column of time points.
Returns
-------------
df : data frame
A data frame wihout co... | 7ec5438334cb0b195f2fa3a1b586a60f2bcc29fc | 26,759 |
import typing
def hex_to_color(color: str) -> typing.Tuple[int, int, int]:
"""
Helper method for transforming a hex string encoding a color into a tuple of color entries
"""
return int(color[:2], base=16), int(color[2:4], base=16), int(color[4:6], base=16) | 40f0c580822effde33a96027863acafb781e44f9 | 26,760 |
import six
def truncate_rows(rows, length=30, length_id=10):
"""
Truncate every string value in a dictionary up to a certain length.
:param rows: iterable of dictionaries
:param length: int
:param length_id: length for dict keys that end with "Id"
:return:
"""
def trimto(s, l):
... | db0d02e39f4152ea8dc15a68ab968ae8500bc320 | 26,761 |
def find_adjacent(left, line):
"""
find the indices of the next set of adjacent 2048 numbers in the list
Args:
left: start index of the "left" value
line: the list of 2048 numbers
Returns:
left, right: indices of the next adjacent numbers in the list
if there are ... | 0bca5a7683d5a7d7ab7c25ae416e6448044823f8 | 26,762 |
def get_examples(mode='train'):
"""
dataset[0][0] examples
"""
examples = {
'train':
({'sentence1': 'Amrozi accused his brother , whom he called " the witness " , of deliberately distorting his evidence .','sentence2': 'Referring to him as only " the witness " , Amrozi accused his brothe... | 7ed0e97625c833df35aafdf06633cba94289a966 | 26,763 |
import re
def parseStrongs(word_data):
"""
Parses the strong's numbers from word data
:param word_data:
:return:
"""
header = re.findall('^#+\s*Word\s+Data\s*\:?.*', word_data, re.MULTILINE | re.IGNORECASE)
if header:
word_data = word_data.split(header[0])[1]
return re.find... | e09d2339096a3ec26e0732e47526b0ef6b08ed93 | 26,764 |
def max_power_rule(mod, g, tmp):
"""
**Constraint Name**: GenVar_Max_Power_Constraint
**Enforced Over**: GEN_VAR_OPR_TMPS
Power provision plus upward services cannot exceed available power, which
is equal to the available capacity multiplied by the capacity factor.
"""
return (
mod.... | 03cfd061867ce68dcab7068c38eaece69b9906ca | 26,765 |
import itertools
def powerset(iterable):
"""Yield all subsets of given finite iterable.
Based on code from itertools docs.
Arguments:
iterable -- finite iterable
We yield all subsets of the set of all items yielded by iterable.
>>> sorted(list(powerset([1,2,3])))
[(), (1,), (1, 2), (1... | 8bcc95585393e2790a8081337aeb6e9d54173b3d | 26,767 |
import re
def clean_str(s):
""" Clean a string so that it can be used as a Python variable name.
Parameters
----------
s : str
string to clean
Returns
-------
str
string that can be used as a Python variable name
"""
# http://stackoverflow.com/a/3305731
# http... | 26801f0258b61eed5cb2ea7b2da31ccfffad074c | 26,768 |
def marked(obj):
"""Whether an object has been marked by spack_yaml."""
return (hasattr(obj, '_start_mark') and obj._start_mark or
hasattr(obj, '_end_mark') and obj._end_mark) | 07a1b4bb3ae5dcdd6aa39bf44c99596fba217cb0 | 26,770 |
import tempfile
import os
import subprocess
def generate_file(parent_dir, size_mb):
""" Generate a file, write random data to it, and return its filepath. """
fd, filepath = tempfile.mkstemp(dir=parent_dir)
os.close(fd)
print("Generating %u MB file to '%s'..." % (size_mb, filepath))
cmd = ("dd", "if=/dev/fr... | d823d2283b9d786867ae8e34028d3637159846bb | 26,772 |
def get_path(topology, start, end):
""" Takes a dict (topology) representing the geometry of the
connections, an int (start) representing the starting index
and an int (end) representing the ending index and returns
a list corresponding to the shortest path from end --> start
(assuming a ring topolo... | ab37a81d11f52f454725926471103f4c173564b9 | 26,773 |
import fileinput
def get_all_ints(fn):
"""Returns a list of integers from 'fn'.
Arguments:
- fn - a string representing input file name. If None or equal to '-' - read
from STDIN; fn is treated as a single input integer if it is a digit.
"""
if fn is None:
fn = '-'
if ... | fc0fa992258c87220a674275429ac9a04f999a05 | 26,774 |
def check_answers(answers, answer_key):
"""
Check students’ answers against answer key.
Inputs: answers, a tuple of tuples of strs.
answer_key, a tuple of strs.
Returns: tuple of tuples of ints.
"""
def check_section(current, start, end):
"""
Mark answers in a secti... | 3138247b05f6d33d162ac5dc00bb2e1590ff5fe1 | 26,777 |
import csv
def import_callrates(table_in):
"""
Import table of variant callrates
"""
callrates = {}
with open(table_in) as tsvfile:
reader = csv.reader(tsvfile, delimiter='\t')
for vid, callrate in reader:
if vid not in callrates.keys():
callrates[vid]... | 28eab08d976a016503327c8009de42d2823b883e | 26,778 |
from typing import Optional
from typing import List
def parse_match_phase_argument(match_phase: Optional[List[str]] = None) -> List[str]:
"""
Parse match phase argument.
:param match_phase: An optional list of match phase types to use in the experiments.
Currently supported types are 'weak_and' a... | 4d70a4936ebf09e0eb8276bf0477895b726941c2 | 26,780 |
def getMaxMinFreq(msg):
"""
Get the max and min frequencies from a message.
"""
return (msg["mPar"]["fStop"], msg["mPar"]["fStart"]) | 3c28882dce3f2ddd420700997c6f65ed906ec463 | 26,781 |
def parse_creator_string(creator):
"""
Creates a string from the creator information in the SPDX document
:param creators: Array of creationinfo objects
:return: string equivalent
"""
print('Begin Parsing Creator')
creators = []
creator_list = creator.replace(" ", "").split(',')
for ... | 06353584dbc41293980dba3913b56823c9406b28 | 26,782 |
def all_messages():
"""
keep all messages in de
Returns:
all messages in JSON
"""
return \
{
"0": "Nettacker Programm gestartet ...\n\n",
"1": "python nettacker.py [Optionen]",
"2": "Nettacker Hilfe-Menü anzeigen",
"3": "Bitte lesen Si... | 25a1b28fa717b51fa3add316b22425eebf958e8f | 26,783 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.