content
stringlengths 35
416k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
import os
def conference_title():
"""Get conference title from environ variable"""
return os.environ.get('CONFERENCE_TITLE', None) | adb13a2565f31af8d273690be10d5d39bcb709d4 | 9,844 |
def apply_bounds(grid, lVec):
"""
Assumes periodicity and restricts grid positions to a box in x- and
y-direction.
"""
dx = lVec[1,0]-lVec[0,0]
grid[0][grid[0] >= lVec[1,0]] -= dx
grid[0][grid[0] < lVec[0,0]] += dx
dy = lVec[2,1]-lVec[0,1]
grid[1][grid[1] >= lVec[2,1]] -= dy
grid[1][grid[1] < lVec[0,1]] += dy
return grid | 34411b7cc1062ade4d45c922225a3364a6c84180 | 9,845 |
def _check(edges):
"""Check consistency"""
res = True
for src, dsts in edges.items():
for dst in dsts:
if dst not in edges:
print('Warning: edges[%d] contains %d, which is not in edges[]' % (src, dst))
res = False
return res | e97a72e31fc99fdf35e3302ab7a6216d7cab924d | 9,846 |
def matches_filter(graph, props):
"""
Returns True if a given graph matches all the given props. Returns False
if not.
"""
for prop in props:
if prop != 'all' and not prop in graph['properties']:
return False
return True | 8d53f198b7ad1af759203909a05cd28916512708 | 9,847 |
from typing import List
from typing import Any
from typing import Union
import re
def human_sort_key(key: str) -> List[Any]:
"""
Function that can be used for natural sorting, where "PB2" comes before
"PB10" and after "PA3".
"""
def _convert(text: str) -> Union[int, str]:
return int(text) if text.isdigit() else text
return [_convert(x) for x in re.split(r'(\d+)', key) if x] | 31c163250f5b040b18f3f2374825191ce3f61ff4 | 9,848 |
def get_class(class_string):
""" Returns class object specified by a string.
Arguments:
class_string -- The string representing a class.
Raises:
ValueError if module part of the class is not specified.
"""
module_name, _, class_name = class_string.rpartition('.')
if module_name == '':
raise ValueError('Class name must contain module part.')
return getattr(__import__(module_name, globals(), locals(), [class_name], -1), class_name) | a25573ac9cb6115e0b8ad1d28a286f86628d8235 | 9,849 |
import hashlib
def flip_bloom_filter(string: str, bf_len: int, num_hash_funct: int):
"""
Hash string and return indices of bits that have been flipped correspondingly.
:param string: string: to be hashed and to flip bloom filter
:param bf_len: int: length of bloom filter
:param num_hash_funct: int: number of hash functions
:return: bfset: a set of integers - indices that have been flipped to 1
"""
# config for hashing
h1 = hashlib.sha1
h2 = hashlib.md5
sha_bytes = h1(string.encode('utf-8')).digest()
md5_bytes = h2(string.encode('utf-8')).digest()
int1 = int.from_bytes(sha_bytes, 'big') % bf_len
int2 = int.from_bytes(md5_bytes, 'big') % bf_len
# flip {num_hash_funct} times
bfset = set()
for i in range(num_hash_funct):
gi = (int1 + i * int2) % bf_len
bfset.add(gi)
return bfset | c245637b86cc16b68d069bf2359b1e5c7483a8fc | 9,850 |
def largest_product(product_list):
"""Find the largest product from a given list."""
largest = 1
for products in product_list:
if largest < max(products):
largest = max(products)
return largest | 7f9f2b151afc7d0e35203a5dda665ef100279c65 | 9,852 |
import os
import stat
def is_executable(path):
"""Tests if the specified path corresponds to an executable file. This is,
it is a file and also has the appropriate executable bit set.
:param path: Path to the file to test.
:return: True if the file exists and is executable, False otherwise.
:rtype: bool
"""
if os.path.isfile(path):
f_stat = os.stat(path)
is_exe = f_stat.st_mode & (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
return bool(is_exe)
return False | 0926b6118688892db7446dadafa19c300ff29212 | 9,853 |
def add_api_component(logger, name, event_dict):
"""
Adds the component to the entry if the entry is not from structlog. This only applies to the API since it is
handled by external WSGI servers.
"""
event_dict["component"] = "API"
return event_dict | d510d8eb563ffd3b819abd3ec970790ed9d30083 | 9,854 |
import random
def shuffle_string(s: str) -> str:
"""
Mixes all the letters in the given string
Parameters:
s(str): the string to shuffle
Returns:
str: string with randomly reordered letters
Examples:
>>> shuffle_string('abc')
'cba'
>>> shuffle_string('abc d')
'da bc'
>>> shuffle_string('i like python')
'okny tehiil p'
"""
chars = list(s)
random.shuffle(chars)
return ''.join(chars) | 9c68b276f539d6385e5393cb92fa971fbb6059d4 | 9,855 |
import os
import errno
import functools
import signal
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
"""
This decorator raise an TimeoutError exception if the function
takes more than 'seconds' seconds to terminate
From: https://stackoverflow.com/questions/2281850/
"""
def decorator(func):
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
@functools.wraps(func)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(seconds)
try:
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return wrapper
return decorator | f46280146f0ee309f71100614bbc6d1afd38799d | 9,857 |
def onnx2str(model_onnx, nrows=15):
"""
Displays the beginning of an ONNX graph.
See :ref:`onnxsklearnconsortiumrst`.
"""
lines = str(model_onnx).split('\n')
if len(lines) > nrows:
lines = lines[:nrows] + ['...']
return "\n".join(lines) | 0bca645ab2882cde59788517cc9c8c02d208de2e | 9,858 |
def diff_lists(old, new):
"""Returns sorted lists of added and removed items."""
old = set(old or [])
new = set(new or [])
return sorted(new - old), sorted(old - new) | 1359a2c89c20993445491ff2a986a392eaee2aed | 9,862 |
def get_gw_bytes_encoding():
"""
get gateway encoding method
:return: string
"""
return "utf-8" | 44e23564f5feb086334d7d9c00a8f4283ae5273d | 9,864 |
import os
import errno
def get_cloudinit_instance():
"""Return the current CloudInit instance ID."""
try:
target = os.readlink('/var/lib/cloud/instance')
except OSError as e:
if e.errno != errno.ENOENT:
raise
return
path, instance = os.path.split(target)
return instance | 3eff85599300c0d3a4ae18bc10f7501c3c9c2d25 | 9,866 |
def open_file(filename: str):
"""
>>> open_file("hello.txt")
No such file or directory: hello.txt
>>> import os
>>> if os.path.exists("../LICENSE"):
... f = open_file("../LICENSE")
... _ = f is not None
... _ = f.readline().strip() == "Apache License"
... _ = f.readline().strip() == "Version 2.0, January 2004"
... f.close()
... _ = f.closed
... with open("../LICENSE") as f:
... _ = f.readline().strip() == "Apache License"
... _ = f.readline().strip() == "Version 2.0, January 2004"
"""
try:
f = open(filename)
return f
except FileNotFoundError:
print(f"No such file or directory: {filename}") | fdc9f5746f61573014c4cb7b3631c2ce0ad10d4e | 9,867 |
import torch
def add_gaussian(p, g_std):
"""add gaussian noise
:param p: input tensor
:param g_std: standard deviation of Gaussian
:returns: tensor with added noise
:rtype: tensor
"""
if g_std > 0:
size = p.size()
p += torch.normal(0, g_std, size=size)
return p | 025bfffca50463589619051f58b5d8e95341c0bd | 9,869 |
def chain(_input, funcs):
"""Execute recursive function chain on input and return it.
Side Effects: Mutates input, funcs.
Args:
_input: Input of any data type to be passed into functions.
funcs: Ordered list of funcs to be applied to input.
Returns:
Recusive call if any functions remaining, else the altered input.
"""
return chain(funcs.pop(0)(_input), funcs) if funcs else _input | 3f2d1490044f0eb35656bd7601d1569fb6f8a553 | 9,870 |
def get_resolution_HRF():
"""Returns RIM_ONE_v2 resolution after post-processing."""
return (3504, 3504) | 4d50b1a08a469f5790a7e59207fcde3956c4fa2d | 9,871 |
def overlaps_bool(pred_roi, bbox):
"""
:param rois: regions of interest in format (y1, x1, y2, x2)
:return: Boolean
Example:
[[ 99,325,135,363], [ 54,229,88,264], [ 53,230,94,266], [ 93,321,132,361]]
-> [1, 2, 2, 1]
"""
l_1_y1 = pred_roi[0]
l_1_x1 = pred_roi[1]
r_1_y2 = pred_roi[2]
r_1_x2 = pred_roi[3]
l_2_y1 = bbox[0]
l_2_x1 = bbox[1]
r_2_y2 = bbox[2]
r_2_x2 = bbox[3]
if l_1_x1 > r_2_x2 or l_2_x1 > r_1_x2:
return False
elif l_1_y1 > r_2_y2 or l_2_y1 > r_1_y2:
return False
else:
return True | c186026967b7016aba7ce21cd9d710b51af74d91 | 9,873 |
import re
def underline_to_hump(underline_str):
"""
Transfer underline to hump
Args:
underline_str(string): underline code string
"""
sub = re.sub(r'(_\w)', lambda x: x.group(1)[1].upper(), underline_str)
return sub | dbc59ced8306088f08b6997c305c468370b4631d | 9,874 |
def successor(node):
""" 4.6 Successor: Write an algorithm to find the "next" node
(i.e., in-order successor) of a given node in a binary search tree.
You may assume that each node has a link to its parent.
"""
def get_min(node):
if node.left != None:
return get_min(node.left)
return node
if node.right != None:
return get_min(node.right)
while node.parent != None:
if node.parent.left == node:
return node.parent
node = node.parent
return None | 448342a8adcdf73ba73a5e6b4319cd299d1bc9a8 | 9,875 |
def build_zooma_query(trait_name: str, filters: dict, zooma_host: str) -> str:
"""
Given a trait name, filters and hostname, create a url with which to query Zooma. Return this
url.
:param trait_name: A string containing a trait name from a ClinVar record.
:param filters: A dictionary containing filters used when querying OxO
:param zooma_host: Hostname of a Zooma instance to query.
:return: String of a url which can be requested
"""
url = "{}/spot/zooma/v2/api/services/annotate?propertyValue={}".format(zooma_host, trait_name)
url_filters = [
"required:[{}]".format(filters["required"]),
"ontologies:[{}]".format(filters["ontologies"]),
"preferred:[{}]".format(filters["preferred"])
]
url += "&filter={}".format(",".join(url_filters))
return url | 0fb22b1f44319c2fa8e87d8e720de248dd1a7eba | 9,876 |
import os
import pickle
def pickle_load(cwd,file_Name):
"""
Load pickled data from current working directory.
INPUT: cwd - Current working directory.
file_name - Name of pickled data to be loaded.
OUTPUT: filePickle - Loaded pickle data.
"""
print('\nLoading data...\n')
os.chdir(cwd)
fileObject = open(file_Name,'rb')
filePickle = pickle.load(fileObject)
return filePickle | 63ded4f9511e066d23aa8c99603c3a54f085b5e4 | 9,877 |
from typing import Any
def ret(d: dict, key: str) -> Any:
""" Unwrap nested dictionaries in a recursive way.
Parameters
----------
d: dict
Python dictionary
key: str or Any
Key or chain of keys. See example below to
access nested levels.
Returns
----------
out: Any
Value from the key or value from the
last key from the chains.
Examples
----------
>>> a = {"toto": {"titi":1}, "tutu":2}
>>> ret(a, "tutu")
2
>>> ret(a, "toto")
{"titi":1}
>>> ret(a, "toto:titi")
1
"""
if ":" in key:
# Split at first ":"
level = key.split(":", maxsplit=1)
if isinstance(d[level[0]], dict):
return ret(d[level[0]], level[1])
else:
raise AssertionError("""
Nested level must be dictionaries!
d[{}] is not a dict!
""".format(level[0]))
return d[key] | 86d07ba6dbe2610ceabb0bcee3099b5734c770ae | 9,879 |
def to_minutes(hour, minute):
"""
converts hours to minutes and adds extra minutes in the time...
returns the sum
"""
return (hour * 60) + minute | 05cc1cada49c7a2c84b3fa32cd9fb7bf805be751 | 9,882 |
def is_identity(u):
"""Checks if the unit is equivalent to 1"""
return u.unitSI == 1 and u.unitDimension == (0,0,0,0,0,0,0) | afc9029eeb44739a38869f06f84ba36b2a19da6f | 9,883 |
def m_seq_inx_to_int(seq, args=0):
"""
将列表中单个列表中元素转成int,返回新的列表
:param seq: 列表形成的列表
:param args: 列表的次序
:return: 转换后的列表
example:
:seq [['30', 0], ['5', 1]]
:args 0
:return [[30, 0], [5, 1]]
"""
for i in seq:
i[args] = int(i[args])
return seq | f6ba3c4060edffd704c53752df88b4dcfbdbef68 | 9,884 |
import os
def get_dzi_path(filepath):
"""
Get a path for the DZI relative to a rendered output file.
"""
return "%s/dzi/%s.dzi" % (os.path.dirname(filepath),
os.path.splitext(os.path.basename(filepath))[0]) | f78a88e37130f444e1398c603bfdeda3d30845bd | 9,885 |
import pathlib
def get_tree(tree_type, cfg, section, option):
"""Load a tree from file or parse a string.
If the provided value is the name of an existing file, read the contents and treat it as a
Newick tree specification. Otherwise, assume the provided value is a Newick tree specification.
Trees consisting of only one leaf are considered errors, because they are never useful and can
easily arise when a non-existing file name is parsed as tree, leading to confusing error
messages down the line.
In either case, inspect the tree and make appropriate minor changes so it is suitable for
inclusion in the BEAST XML file.
"""
value = cfg.get(section, option)
assert tree_type in ("starting", "monophyly")
# Read from file if necessary
fname = pathlib.Path(value)
if fname.exists() and fname.is_file():
value = fname.read_text(encoding='utf8').strip()
if value:
if ")" in value:
return value
# A tree with only one node (which is the only Newick string without bracket) is not a
# useful tree specification.
raise ValueError(
"Tree specification {:} is neither an existing file nor does it look "
"like a useful tree.".format(value))
return value | 077ff497e32a9695ae146c381a29361187511bc6 | 9,886 |
def common(first_list, second_list):
"""Receives two lists, returns True if they have any common objects and false otherwise.
Note that this implementation should theoretically work with any container-like object for which
the in operator doesn't have a different meaning."""
# iterate over the elements in the first list
for i in first_list:
# if the current element in the second list, short-circuit and return True
# one common object satisfies "at least one"
if i in second_list:
return True
# fall through to False
return False | da48a3a559bc26a79bc5aa06ca6efa15053e1cd4 | 9,887 |
import logging
def receive(conn):
"""Receive a message
conn has to be the socket which receive the message
A message has to end with the bytestring b'\xDE\xAD\xE1\x1D'
"""
ip, port = conn.getpeername()
logging.info('Receiving a message from '+ip+':'+str(port))
data = b''
while True:
try:
received = conn.recv(16)
if not received:
logging.error("No data received")
break
except:
raise
if b'\xDE\xAD\xE1\x1D' in received:
data += received[:received.find(b'\xDE\xAD\xE1\x1D')]
break
else:
data += received
if data[-4:] == b'\xDE\xAD\xE1\x1D':
data = data[:-4]
break
return data | 0b6f4e9c6fd3a38a33f625fe6b736020a044ca61 | 9,889 |
def calc_linear_crossing(m, left_v, right_v):
"""
Computes the intersection between two line segments, defined by two common
x points, and the values of both segments at both x points
Parameters
----------
m : list or np.array, length 2
The two common x coordinates. m[0] < m[1] is assumed
left_v :list or np.array, length 2
y values of the two segments at m[0]
right_v : list or np.array, length 2
y values of the two segments at m[1]
Returns
-------
(m_int, v_int): a tuple with the corrdinates of the intercept.
if there is no intercept in the interval [m[0],m[1]], (None,None)
"""
# Find slopes of both segments
delta_m = m[1] - m[0]
s0 = (right_v[0] - left_v[0]) / delta_m
s1 = (right_v[1] - left_v[1]) / delta_m
if s1 == s0:
if left_v[0] == left_v[1]:
return (m[0], left_v[0])
else:
return (None, None)
else:
# Find h where intercept happens at m[0] + h
h = (left_v[0] - left_v[1]) / (s1 - s0)
if h >= 0 and h <= (m[1] - m[0]):
return (m[0] + h, left_v[0] + h * s0) | 3f5eeab9fa906b6858e249f97c7e175e427cb2d7 | 9,890 |
def validate_input(input_string):
"""
:param str input_string: A string input to the program for validation
that it will work wiht the diamond_challenge program.
:return: *True* if the string can be used to create a diamond.
*False* if cannot be used.
"""
if not isinstance(input_string, str) or len(input_string) != 1 \
or ord(input_string) < ord('A') or ord(input_string) > ord('Z'):
print("\nInvalid input! Please input a single capital letter (A-Z).\n")
return False
return True | cf18344ddd336d878837bc5654a3ea3b98eec729 | 9,891 |
from sys import version_info
def _open_csv_file(filename):
"""Opens a file for writing to CSV, choosing the correct method for the
current version of Python
"""
if version_info.major < 3:
out_file = open(filename, 'wb')
else:
out_file = open(filename, 'w', newline='')
return out_file | 527b7d216d6ecd2d30ac716e993edee6a95766bc | 9,892 |
def octave_to_frequency(octave: float) -> float:
"""Converts an octave to its corresponding frequency value (in Hz).
By convention, the 0th octave is 125Hz.
Parameters
----------
octave : float
The octave to put on a frequency scale.
Returns
-------
float
The frequency value corresponding to the octave.
"""
return 125 * 2 ** octave | d50fe69e0dd267b5418834ca2999867213b5f306 | 9,893 |
def _complete_choices(msg, choice_range, prompt, all=False, back=True):
"""Return the complete message and choice list."""
choice_list = [str(i) for i in choice_range]
if all:
choice_list += ['a']
msg += '\n- a - All of the above.'
if back:
choice_list += ['b']
msg += '\n- b - Back to the main menu.'
choice_list += ['q']
msg += f'\n- q - Exit the program.\n\n> {prompt}? [{"/".join(choice_list)}]'
return msg, choice_list | 0e5052643cd027d760b08b22bc5f14608845fcb2 | 9,897 |
def is_bitcode_file(path):
"""
Returns True if path contains a LLVM bitcode file, False if not.
"""
with open(path, 'rb') as f:
return f.read(4) == b'BC\xc0\xde' | acfd17eee949f42994b2bc76499ee58c710eb388 | 9,898 |
from typing import List
def get_file_pattern() -> List[str]:
"""
Returns a list with all possible file patterns
"""
return ["*.pb", "*.data", "*.index"] | 8c4f471dea29dfe5c79cf3ea353cb1a335a5cf45 | 9,899 |
import copy
import itertools
def _make_inner_dense(sparse_nested_table, outer_inner_cards, default_value):
"""
Convert n sparse nested table dictionary's implicit default values in the innetables to real entries so that
all possible assignments are present in the inner sub tables.
:param sparse_nested_table: The nested dictionary representing a sparse table.
:type sparse_nested_table: dictionary of dictionaries
:param outer_inner_cards: The lists of the cardinalities for the outer and inner part of the nested table respectively
i.e [[2,2], [3, 4]] if the table dict is {(0,0):{(2,3):0.3},....} where the outer variables has cardinalities [2,2]
and the inner ones [3,4]
"""
sparse_nested_inner_dense_table = copy.deepcopy(sparse_nested_table)
inner_cards = outer_inner_cards[1]
all_inner_table_assignments = itertools.product(*[range(c) for c in inner_cards])
for outer_assign in sparse_nested_inner_dense_table.keys():
for inner_assign in all_inner_table_assignments:
if inner_assign not in sparse_nested_inner_dense_table[outer_assign]:
sparse_nested_inner_dense_table[outer_assign][inner_assign] = default_value
return sparse_nested_inner_dense_table | 372861e9a38016e0426ff29b62eb47fd82ff9631 | 9,900 |
import torch
def extract_tensor_batch(t, batch_size):
""" batch extraction from tensor """
# extracs batch from first dimension (only works for 2D tensors)
idx = torch.randperm(t.nelement())
return t.view(-1)[idx][:batch_size].view(batch_size,1) | 291ee82385dad8ad6a60ced0759900a8fb71e0c5 | 9,901 |
def charPresent(s, chars):
"""charpresent(s, chars) - returns 1 if ANY of the characters present in the string
chars is found in the string s. If none are found, 0 is returned."""
for c in chars:
if str.find(s, c) != -1:
return True
return False | cac51d18788ae4556609f5f289eb8dbb0741fc79 | 9,902 |
def err_ratio(cases):
"""calculate error ratio
Args:
cases: ([case,]) all cases in all parts
Return:
float
"""
return 1 - len(list(filter(lambda x: x['valid'], cases))) / len(cases) | 421905b46c594d99b091e4d6ad094092c4483faa | 9,905 |
def get_param_cols(columns):
""" Get the columns that were provided in the file and return that list so we don't try to query non-existent cols
Args:
columns: The columns in the header of the provided file
Returns:
A dict containing all the FPDS query columns that the provided file has
"""
possible_cols = {'agency_id': 'AGENCY_CODE', 'referenced_idv_agency_iden': 'REF_IDV_AGENCY_ID',
'piid': 'PIID', 'award_modification_amendme': 'MODIFICATION_NUMBER',
'parent_award_id': 'REF_IDV_PIID', 'transaction_number': 'TRANSACTION_NUMBER'}
existing_cols = {}
for key in possible_cols:
if key in columns:
existing_cols[key] = possible_cols[key]
return existing_cols | 8a0030c745d2de5bd2baf93af79efce4dcb4c696 | 9,906 |
import re
def depluralize(word):
"""Return the depluralized version of the word, along with a status flag.
Parameters
----------
word : str
The word which is to be depluralized.
Returns
-------
str
The original word, if it is detected to be non-plural, or the
depluralized version of the word.
str
A status flag represeting the detected pluralization status of the
word, with non_plural (e.g., BRAF), plural_oes (e.g., mosquitoes),
plural_ies (e.g., antibodies), plural_es (e.g., switches),
plural_cap_s (e.g., MAPKs), and plural_s (e.g., receptors).
"""
# If the word doesn't end in s, we assume it's not plural
if not word.endswith('s'):
return word, 'non_plural'
# Another case is words ending in -sis (e.g., apoptosis), these are almost
# exclusively non plural so we return here too
elif word.endswith('sis'):
return word, 'non_plural'
# This is the case when the word ends with an o which is pluralized as oes
# e.g., mosquitoes
elif word.endswith('oes'):
return word[:-2], 'plural_oes'
# This is the case when the word ends with a y which is pluralized as ies,
# e.g., antibodies
elif word.endswith('ies'):
return word[:-3] + 'y', 'plural_ies'
# These are the cases where words form plurals by adding -es so we
# return by stripping it off
elif word.endswith(('xes', 'ses', 'ches', 'shes')):
return word[:-2], 'plural_es'
# If the word is all caps and the last letter is an s, then it's a very
# strong signal that it is pluralized so we have a custom return value
# for that
elif re.match(r'^\p{Lu}+$', word[:-1]):
return word[:-1], 'plural_caps_s'
# Otherwise, we just go with the assumption that the last s is the
# plural marker
else:
return word[:-1], 'plural_s'
# Note: there don't seem to be any compelling examples of -f or -fe -> ves
# so it is not implemented | 9d879a320da566bceb6e5db6cbfe2e7f23f9bb73 | 9,907 |
import ipaddress
def _get_network_address(ip, mask=24):
"""
Return address of the IPv4 network for single IPv4 address with given mask.
"""
ip = ipaddress.ip_address(ip)
return ipaddress.ip_network(
'{}/{}'.format(
ipaddress.ip_address(int(ip) & (2**32 - 1) << (32 - mask)),
mask
)
) | bb706209cc7295ab1d0b4bf88e11d3efba10d526 | 9,909 |
def get_admin_ids(bot, chat_id):
"""
Returns a list of admin IDs for a given chat. Results are cached for 1 hour.
Private chats and groups with all_members_are_administrator flag are handled as empty admin list
"""
chat = bot.getChat(chat_id)
if chat.type == "private" or chat.all_members_are_administrators:
return []
return [admin.user.id for admin in bot.get_chat_administrators(chat_id)] | 6bd89e1d6b7333d97cbc60fd2617a86d1b69fb2f | 9,910 |
import os
def dirname(path):
"""
Returns the directory in which a shapefile exists.
"""
# GitPython can't handle paths starting with "./".
if path.startswith('./'):
path = path[2:]
if os.path.isdir(path):
return path
else:
return os.path.dirname(path) | c4c8dcfb511f27984386ee97f8d1ea414561603a | 9,911 |
import math
def num_tiles_not_in_position(state):
"""
Calculates and returns the number of tiles which are not in their
final positions.
"""
n = len(state)
total = 0
for row in state:
for tile in row:
try:
y = int(math.floor(float(tile)/n - (float(1)/n)))
x = (tile - 1) % n
except ValueError: #blank tile
continue
if row.index(tile) - x != 0 or state.index(row) - y != 0:
total += 1
return total | 102d2eb616f8b459fc31e68788f355440bac97e0 | 9,912 |
import random
def make_babies(parents, size=10000):
"""Create a new population by randomly selecting two parents and
randomly selecting the character from a parent for each position."""
children = []
for i in range(size):
p1, p2 = random.sample(parents, 2)
children.append(''.join([p1[i] if random.randint(0,1) else p2[i] for i in range(len(p1))]))
return children | 74ac5106259eb504ce70a00fccf610137238bbbe | 9,913 |
def plus(cell1, cell2, back_val):
"""Moves forward between two cells.
Requires a third cell, though truly only requires the value of that the
form takes at the cell.
"""
(x1, y1), val1 = cell1
(x2, y2), val2 = cell2
# back_val, val1 + val2, val form an arithmetic progression
val = 2 * (val1 + val2) - back_val
x = x1 + x2
y = y1 + y2
return ((x, y), val) | ecf20c2a46f6ae834e0625f5a54fd30f46af2a7a | 9,914 |
def get_bool_symbols(a_boolean):
"""
:param a_boolean: Any boolean representation
:return: Symbols corresponding the to the
True or False value of some boolean representation
Motivation: this is reused on multiple occasions
"""
if a_boolean:
return "✅"
return "❌" | b95a4fc5ca29e07a89c63c97ba88d256a24a7431 | 9,915 |
def returner(x):
"""
Create a function that takes any arguments and always
returns x.
"""
def func(*args, **kwargs):
return x
return func | 43476f89cae80cd2b61d64771a3dfac5e4297b5a | 9,916 |
from typing import Counter
def get_unique_characters(rows, min_count=2):
"""Given a bunch of text rows, get all unique chars that occur in it."""
def char_iterator():
for row in rows.values:
for char in row:
yield str(char).lower()
return [
c for c, count
in Counter(char_iterator()).items()
if count >= min_count
] | ecba44e44222bb63c2f794e7ee9e87eb3754f695 | 9,917 |
def build_data_type_name(sources, properties, statistic, subtype=None):
"""
Parameters
----------
sources: str or list[str]
type(s) of astrophysical sources to which this applies
properties: str or list[str]
feature(s)/characterisic(s) of those sources/fields to
which the statistic applies
statistic_type: str
mathematical type of the statistic
statistic_subtype: str or None
optional additional specifier. Default is None
Returns
-------
name: str
Type name of the form:
{sources}_{properties}_{statistic_type}[_{statistic_subtype}]
"""
if not isinstance(sources, str):
sources = "".join([sources[0]] + [s.lower().capitalize()
for s in sources[1:]])
if not isinstance(properties, str):
properties = "".join([properties[0]] + [s.lower().capitalize()
for s in properties[1:]])
if subtype:
return f"{sources}_{properties}_{statistic}_{subtype}"
else:
return f"{sources}_{properties}_{statistic}" | 103a7440dfe3b8f6ccce0fdf6cdca86202e27ac5 | 9,918 |
def machineCostPerH(fixed, operating):
"""
fixed = fixed costs
operating = operating costs
"""
return {'Machine cost per H': [fixed + operating]} | d6fd47e14402504dc277375d87a786b7c54cea98 | 9,919 |
import re
def expand_symbols(text):
"""
expand symbols in text
"""
text = re.sub("\;", ",", text)
text = re.sub("\:", ",", text)
text = re.sub("\-", " ", text)
text = re.sub("\&", "and", text)
return text | 9f212718745ef0f2964490b692cab491ad74430c | 9,920 |
def priter(self, **kwargs):
"""Prints solution summary data.
APDL Command: PRITER
Notes
-----
Prints solution summary data (such as time step size, number of
equilibrium iterations, convergence values, etc.) from a static or full
transient analysis. All other analyses print zeros for the data.
"""
command = f"PRITER,"
return self.run(command, **kwargs) | aae2dd4c8103d0244887fc7010ca95814f1b853f | 9,921 |
def is_valid_id(id_: str) -> bool:
"""If it is not nullptr.
Parameters
----------
id_ : str
Notes
-----
Not actually does anything else than id is not 0x00000
Returns
-------
bool
"""
return not id_.endswith("0x0000000000000000") | 6520900966475771e2a0d1fcdfd2b60d3ea2ee9b | 9,922 |
def async_is_zwave_js_migrated(hass):
"""Return True if migration to Z-Wave JS is done."""
zwave_js_config_entries = hass.config_entries.async_entries("zwave_js")
if not zwave_js_config_entries:
return False
migrated = any(
config_entry.data.get("migrated") for config_entry in zwave_js_config_entries
)
return migrated | ca6a5397ec8329557e8be523f4fa416175347c84 | 9,923 |
def get_limit_from_tag(tag_parts):
"""Get the key and value from a notebook limit tag.
Args:
tag_parts: annotation or label notebook tag
Returns (tuple): key (limit name), values
"""
return tag_parts.pop(0), tag_parts.pop(0) | e7d4858b166b2a62ec497952853d95b81a608e85 | 9,924 |
def Percent(numerator, denominator):
"""Convert two integers into a display friendly percentage string.
Percent(5, 10) -> ' 50%'
Percent(5, 5) -> '100%'
Percent(1, 100) -> ' 1%'
Percent(1, 1000) -> ' 0%'
Args:
numerator: Integer.
denominator: Integer.
Returns:
string formatted result.
"""
return '%3d%%' % int(100 * (numerator / float(denominator))) | a0081a387a737b44268fd71ab9746c7edd72221f | 9,925 |
def link_filtered_DLC_predictions(nwb_file,video_dir): # add the DLC files (need code/write code)
""" Function to link filtered DLC predictions to a NWB file"""
return nwb_file | d51980fe2bc7099e13d784eb9fc6e324c547c38d | 9,930 |
import json
def read_data(f_name):
"""
Given an input file name f_name, reads the JSON data inside returns as
Python data object.
"""
f = open(f_name, 'r')
json_data = json.loads(f.read())
f.close()
return json_data | 629ab7e9a8bd7d5b311022af4c9900d5942e7a23 | 9,931 |
def reverse_string_recursive(s):
"""
Returns the reverse of the input string
Time complexity: O(n^2) = O(n) slice * O(n) recursive call stack
Space complexity: O(n)
"""
if len(s) < 2:
return s
# String slicing is O(n) operation
return reverse_string_recursive(s[1:]) + s[0] | a8d22e88b1506c56693aa1a8cd346695e2b160b2 | 9,932 |
def checkIsHours(value):
"""
checkIsHours tries to distinguish if the value describes hours or degrees
:param value: string
:return:
"""
if not isinstance(value, str):
return False
if '*' in value:
return False
elif '+' in value:
return False
elif '-' in value:
return False
else:
return True | 4d28996de6087b802757508313e15543b9dd9272 | 9,933 |
def gnome_sort(a):
"""
Sorts the list 'a' using gnome sort
>>> from pydsa import gnome_sort
>>> a = [5, 6, 1, 9, 3]
>>> gnome_sort(a)
[1, 3, 5, 6, 9]
"""
i = 0
while i < len(a):
if i != 0 and a[i] < a[i-1]:
a[i], a[i-1] = a[i-1], a[i]
i -= 1
else:
i += 1
return a | 05aca54513c6d441836aa7a60147b06b85b4e34d | 9,934 |
def fmod(x, y):
"""Return fmod(x, y), as defined by the platform C library.
:type x: numbers.Real
:type y: numbers.Real
:rtype: float
"""
return 0.0 | cd580ca8efe1e9bd3e5511613ccdcc59ebe55119 | 9,937 |
def get_closest_multiple_of_16(num):
"""
Compute the nearest multiple of 16. Needed because pulse enabled devices require
durations which are multiples of 16 samples.
"""
return int(num) - (int(num) % 16) | 333cbed27abbcb576541d5fb0b44bf85b78c9e78 | 9,939 |
from typing import List
from typing import Tuple
def max_subarray(arr: List[int]) -> Tuple[int, int]:
"""
:time: O(n)
:space: O(n)
"""
max_val = max(x for x in arr)
if max_val < 0:
return max_val, max_val
max_subsequence_sum = sum(x for x in arr if x > 0)
max_subarray_sum = 0
current_sum = 0
for x in arr:
current_sum = max(current_sum + x, 0)
max_subarray_sum = max(max_subarray_sum, current_sum)
return max_subarray_sum, max_subsequence_sum | 056b4c83191f57a36f0fdeb7474b2de2f6e8bb28 | 9,940 |
def split_container(path):
"""Split path container & path
>>> split_container('/bigdata/path/to/file')
['bigdata', 'path/to/file']
"""
path = str(path) # Might be pathlib.Path
if not path:
raise ValueError('empty path')
if path == '/':
return '', ''
if path[0] == '/':
path = path[1:]
if '/' not in path:
return path, '' # container
return path.split('/', maxsplit=1) | 53b0d1164ecc245146e811a97017f66bb1f032a7 | 9,941 |
def parse_sph_header( fh ):
"""Read the file-format header for an sph file
The SPH header-file is exactly 1024 bytes at the head of the file,
there is a simple textual format which AFAIK is always ASCII, but
we allow here for latin1 encoding. The format has a type declaration
for each field and we only pay attention to fields for which we
have some understanding.
returns dictionary describing the format such as::
{
'sample_rate':8000,
'channel_count':1,
'sample_byte_format': '01', # little-endian
'sample_n_bytes':2,
'sample_sig_bits': 16,
'sample_coding': 'pcm',
}
"""
file_format = {
'sample_rate':8000,
'channel_count':1,
'sample_byte_format': '01', # little-endian
'sample_n_bytes':2,
'sample_sig_bits': 16,
'sample_coding': 'pcm',
}
end = b'end_head'
for line in fh.read(1024).splitlines():
if line.startswith(end):
break
line = line.decode('latin-1')
for key in file_format.keys():
if line.startswith(key):
_, format, value = line.split(None, 3)
if format == '-i':
value = int(value, 10)
file_format[key] = value
return file_format | d0055b3dc276facd9acb361dfde167d8c123b662 | 9,942 |
import numpy
def acosine(a,b,weights):
"""Distance between two points based on the pearson correlation coefficient.
By treating each data point as half of a list of ordered pairs it is
possible to caluclate the pearson correlation coefficent for the list.
Since the pearson correlation coefficent for a sample can also be thought
of as the cosine of the angle between the two vectors, the distance is
defined as its arccosine. This function assumes the ordered pairs are
centered around 0. Used over the uncentered pearson distance when linearity
of correlation, and not slope of correlation, is a more appropriate measure
of similarity.
Parameters:
a,b : ndarray
The data points. Expects two rank 1 arrays of the same length.
weights : ndarray
The weights for each dimension. Expects rank 1 array of same
length as a & b.
Returns:
d : float
The inverse cosine pearson distance between the two data points.
See Also:
pearson, upearson
Notes:
This distance is defined mathematically as:
( -- )
( > w[i]a[i]b[i] )
1 ( -- )
d = -- arccos( ----------------------------- )
pi ( -- -- )
( > w[i]a[i]**2 > w[i]b[i]**2 )
( -- -- )
where a[i] & b[i] are the ith elements of a & b respectively and w[i]
is the weight of the ith dimension. Only dimensions for which both
vectors have values are used when computing the sums of squares.
"""
a = ~numpy.isnan(b)*a
b = ~numpy.isnan(a)*b
result = weights*a*b
d1 = weights*a**2
d2 = weights*b**2
return (numpy.arccos(numpy.nansum(result)/numpy.sqrt((numpy.nansum(d1)*numpy.nansum(d2)))))/numpy.pi | 19ffa98cb12c1d4e8026e0763c76062d2c4b19c8 | 9,943 |
def column(matrix, i):
"""
Returning all the values in a specific columns
Parameters:
X: the input matrix
i: the column
Return value: an array with desired column
"""
return [row[i] for row in matrix] | 2a88c40d11e7fe7f28970acd4d995a8428126a4d | 9,944 |
def cubicinout(x):
"""Return the value at x of the 'cubic in out' easing function between 0 and 1."""
if x < 0.5:
return 4 * x**3
else:
return 1/2 * ((2*x - 2)**3 + 2) | 505f0c5b8dc7b9499450474dbb1991eec068b553 | 9,945 |
def remove_duplicates(string: str) -> str:
"""
Remove duplicate characters in a string
:param string:
:return:
"""
without_duplicates = ""
for letter in string:
if letter not in without_duplicates:
without_duplicates += letter
return without_duplicates | 2caafc6b38cf2b920324bd976acb3caf90660c25 | 9,946 |
import argparse
def parse_args():
"""
Parses command line args
Returns:
The argparse namespace
"""
parser = argparse.ArgumentParser(description="Copies packer artifacts from the packer manifest output to terraform input variables.")
parser.add_argument('--enterprise', dest='enterprise', action='store_true', default=False, help='Whether to copy the AMI for the enterprise version of vault')
parser.add_argument('--tfvars-backup-file', dest='tfvar_backup_file', default=None, help="A file at which to back up the current terraform amis variable.")
return parser.parse_args() | 2b0dddb18edc3dfdf527ff31168f428dfb30dd03 | 9,948 |
import glob
import os
def csvLayerNames(layer_path):
"""
Get names of layers stored as csv files.
"""
layer_names = glob.glob(os.path.join(layer_path, "*.csv"))
xx = [os.path.basename(i) for i in layer_names]
return xx | 682bf78f5d0a93f55277acf022d98d8c414a1161 | 9,949 |
import sys
def module_property(func):
"""Decorator to turn module functions into proerties.
Function names must be prefixed with an underscore"""
module = sys.modules[func.__module__]
def base_getattr(name):
raise AttributeError(
f"module '{module.__name__}' has no attribute '{name}'")
old_getattr = getattr(module, '__getattr__', base_getattr)
def new_getattr(name):
if f'_{name}' == func.__name__:
return func()
else:
return old_getattr(name)
module.__getattr__ = new_getattr
return func | 919e83e8c4027b6d541d1348bba2c1c4c3436952 | 9,950 |
import json
def dumps(dict_):
"""
Converts dictionaries to indented JSON for readability.
Args:
dict_ (dict): The dictionary to be JSON encoded.
Returns:
str: JSON encoded dictionary.
"""
string = json.dumps(dict_, indent=4, sort_keys=True)
return string | c2f3eabe0b473def6233476018d8c3a3918beb70 | 9,952 |
def jpeg_linqual(quality):
"""
See int jpeg_quality_scaling(int quality)
in libjpeg-turbo source (file ijg/jcparam.c).
Convert quality rating to percentage scaling factor
used to scale the quantization table.
"""
quality = max(quality, 1)
quality = min(quality, 100)
if quality < 50:
quality = 5000 // quality
else:
quality = 200 - quality * 2
return quality | a35157416fd4d95dddfe6cf8408a99e6247703ba | 9,953 |
def pytest_funcarg__content(request):
"""
The content for the test document as string.
By default, the content is taken from the argument of the ``with_content``
marker. If no such marker exists, the content is build from the id
returned by the ``issue_id`` funcargby prepending a dash before the id.
The issue id ``'10'`` will thus produce the content ``'#10'``. If the
``issue_id`` funcarg returns ``None``, a :exc:`~exceptions.ValueError` is
raised eventually.
Test modules may override this funcarg to add their own content.
"""
content_mark = request.keywords.get('with_content')
if content_mark:
return content_mark.args[0]
else:
issue_id = request.getfuncargvalue('issue_id')
if issue_id:
return '#{0}'.format(issue_id)
raise ValueError('no content provided') | e357042566ce22557ba5c8f83b14f56cb8025dca | 9,954 |
def split_s3_path(s3_path):
"""
Splits the complete s3 path to a bucket name and a key name,
this is useful in cases where and api requires two seperate entries (bucket and key)
Arguments:
s3_path {string} -- An S3 uri path
Returns:
bucket {string} - The bucket name
key {string} - The key name
"""
bucket = s3_path.split("/")[2]
key = '/'.join(s3_path.split("/")[3:])
return bucket, key | 81efc5fc125c62d4dcde577b3424029acb4a536f | 9,955 |
import zipfile
def createZip(zip_name, src):
"""
parameter:- zip file name , folder path
This will create zip file
"""
zipf = zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED)
for file in src:
zipf.write(file)
zipf.close()
print("--------zip file created --------")
return None | 325f8a6b63f4a8c2d46b8d07bfc3b3e938d50836 | 9,957 |
def dash(*txts):
"""Join non-empty txts by a dash."""
return " -- ".join([t for t in txts if t != ""]) | 53566f49991f8d7930a63f7d2d22c125d9d25073 | 9,958 |
import asyncio
import functools
def call_later(delay, fn, *args, **kwargs) -> asyncio.Handle:
"""
Call a function after a delay (in seconds).
"""
loop = asyncio.get_event_loop()
callback = functools.partial(fn, *args, **kwargs)
handle = loop.call_later(delay, callback)
return handle | 86d157ed0f5f8dc7f806af9871a71057dc36222c | 9,959 |
from typing import Tuple
def build_blacklist_status(blacklist_status: str) -> Tuple[str, str, str]:
"""Build the blacklist_status
@type blacklist_status: str
@param blacklist_status: The blacklist status from command line
@returns Tuple[str, str, str]: The builded blacklist status
"""
blacklisted_status = blacklist_status
blacklist_action = ''
blacklist_action_param = ''
if ':' in blacklisted_status:
blacklisted_status, blacklist_action = blacklisted_status.split(':', 1)
blacklist_action = blacklist_action.lower()
if '=' in blacklist_action:
blacklist_action, blacklist_action_param = blacklist_action.split('=')
else:
blacklist_action = 'stop'
return (blacklisted_status, blacklist_action, blacklist_action_param) | 10f0c3a77169a0e9b9136d454e6d17efdd4760f6 | 9,960 |
import spwd
import grp
def isuser(username, domain, password=None):
"""Check if user exists and if he is a member of the group 'domain'."""
try:
spwd.getspnam(username)
return username in grp.getgrnam(domain)[3]
except KeyError:
return False
except PermissionError:
print('No permission to access /etc/shadow')
exit(999)
return False | 70e920c0fe3212c3e2588bc429c745fe134653e7 | 9,961 |
def _check_substituted_domains(patchset, search_regex):
"""Returns True if the patchset contains substituted domains; False otherwise"""
for patchedfile in patchset:
for hunk in patchedfile:
if not search_regex.search(str(hunk)) is None:
return True
return False | e3fdeaa1ede7f041bb6080d4647c8d969b41f73d | 9,962 |
import re
def prepareReposToJson(json_repos):
"""
Convert information about repo to proper format
:param json_repos:
:return: dictionary
"""
columns = ["created_on", "description", "fork_policy", "full_name", "has_issues", "has_wiki", "is_private",
"language", "links", "mainbranch", "name", "owner", "project", "scm", "size", "slug", "type",
"updated_on", "uuid", "website"]
repos = {}
for page in json_repos.keys():
for value in json_repos[page]['values']:
new_value = {col: value[col] for col in columns}
new_value['links'] = value['links']['html']['href']
new_value['project_link'] = value['project']['links']['html']['href']
new_value['project'] = value['project']['key']
new_value['project_name'] = value['project']['name']
new_value['owner_link'] = value['owner']['links']['html']['href']
new_value['owner'] = value['owner']['username']
clone_link = 'https://' + re.findall('^https://\S+@(.*)$', value['links']['clone'][0]['href'])[0]
repos[clone_link] = new_value.copy()
return repos | 40eaa03779b0161f78250a174e19b77041d511e8 | 9,963 |
def delete_segment(seq, start, end):
"""Return the sequence with deleted segment from ``start`` to ``end``."""
return seq[:start] + seq[end:] | 1eba39d373ac2ab28ea1ea414f708a508bdf48d2 | 9,966 |
import math
def triangleSum(n):
"""
Finding the sum of 1+2+...+n
:param n: the last interger to be added
:return: the sum
"""
n = math.floor(n)
if n > 1 :
return n+triangleSum(n-1)
return 1 | 4bffb8d8d758730b161a572fad447e5420c30490 | 9,967 |
import re
def detect_arxiv(txt):
"""
Extract an arXiv ID from text data
"""
regex = r'arXiv:[0-9]{4,4}\.[0-9]{5,5}(v[0-9]+)?'
m = re.search(regex, txt)
if m is not None:
return m.group(0)
else:
return None | a855497b6eb1f027085a301096735e860e76fbe7 | 9,968 |
def cut_sentences(text):
"""
将文本切成句子
:param text: 待切分文本
:return: 句子列表
"""
text = text.translate(str.maketrans('!?!?\r\n', '。。。。 '))
return [sen for sen in text.split('。') if len(sen.strip()) > 1] | 06e8b503c2c6e3ea73901bb19f2b4fba2f443e19 | 9,971 |
def to_literal(typ, always_tuple=False):
"""Convert a typestruct item to a simplified form for ease of use."""
def expand(params):
return (to_literal(x) for x in params)
def union(params):
ret = tuple(sorted(expand(params), key=str))
if len(ret) == 1 and not always_tuple:
ret, = ret # pylint: disable=self-assigning-variable
return ret
tag, params = typ
if tag == 'prim':
return params
elif tag == 'tuple':
vals = tuple(expand(params))
return (tag, *vals)
elif tag == 'map':
k, v = params
return (tag, union(k), union(v))
else:
return (tag, union(params)) | a628676073a09042689f64ab1aa4d12a2a87c463 | 9,973 |
def powmod(a, b, m):
""" Returns the power a**b % m """
# a^(2b) = (a^b)^2
# a^(2b+1) = a * (a^b)^2
if b==0:
return 1
return ((a if b%2==1 else 1) * powmod(a, b//2, m)**2) % m | 33b4cadc1d23423f32e147718e3f08b04bd2fd17 | 9,974 |
import numpy as np
def str_to_array(s):
"""
Simplistic converter of strings from repr to float NumPy arrays.
If the repr representation has ellipsis in it, then this will fail.
Parameters
----------
s : str
The repr version of a NumPy array.
Examples
--------
>>> s = "array([ 0.3, inf, nan])"
>>> a = str_to_array(s)
"""
# Need to make sure eval() knows about inf and nan.
# This also assumes default printoptions for NumPy.
if s.startswith(u'array'):
# Remove array( and )
s = s[6:-1]
if s.startswith(u'['):
a = np.array(eval(s), dtype=float)
else:
# Assume its a regular float. Force 1D so we can index into it.
a = np.atleast_1d(float(s))
return a | 858491f8c7279630951b1244a3ea630d932eb7c6 | 9,975 |
import functools
def generate_decorator(exception):
"""Ddecorator generator"""
def expected_error(test):
@functools.wraps(test)
def inner(*args, **kwargs):
try:
test(*args, **kwargs)
except exception:
assert True
else:
raise AssertionError(exception().__class__.__name__ + ' expected')
return inner
return expected_error | 7089aabfb4ad9ce51b08ec43ada1c27d6fe529f0 | 9,976 |
def _update_dict(d, **kwargs):
"""little helper to modify and return a dict in one line"""
d.update(kwargs)
return d | 0a28c5f82d439ceb65aa3afc39d30a29b589004e | 9,977 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.