content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def is_gzipped(filename):
""" Returns True if the target filename looks like a GZIP'd file.
"""
with open(filename, 'rb') as fh:
return fh.read(2) == b'\x1f\x8b' | b1afb5b9cddc91fbc304392171f04f4b018fa929 | 617 |
def get_keys_from_file(csv):
"""Extract the credentials from a csv file."""
lines = tuple(open(csv, 'r'))
creds = lines[1]
access = creds.split(',')[2]
secret = creds.split(',')[3]
return access, secret | eccf56c52dd82656bf85fef618133f86fd9276e6 | 620 |
from typing import Union
def metric_try_to_float(s: str) -> Union[float, str]:
"""
Try to convert input string to float value.
Return float value on success or input value on failure.
"""
v = s
try:
if "%" in v:
v = v[:-1]
return float(v)
except ValueError:
... | 6b0121469d35bc6af04d4808721c3ee06955d02e | 623 |
import shutil
def disk_usage(pathname):
"""Return disk usage statistics for the given path"""
### Return tuple with the attributes total,used,free in bytes.
### usage(total=118013599744, used=63686647808, free=48352747520)
return shutil.disk_usage(pathname) | c7a36e2f3200e26a67c38d50f0a97dd015f7ccfa | 625 |
import numbers
def ensure_r_vector(x):
"""Ensures that the input is rendered as a vector in R.
It is way more complicated to define an array in R than in Python because an array
in R cannot end with an comma.
Examples
--------
>>> ensure_r_vector("string")
"c('string')"
>>> ensure_r_... | 14fdeb6bf73244c69d9a6ef89ba93b33aa4a66d8 | 629 |
def locate_all_occurrence(l, e):
"""
Return indices of all element occurrences in given list
:param l: given list
:type l: list
:param e: element to locate
:return: indices of all occurrences
:rtype: list
"""
return [i for i, x in enumerate(l) if x == e] | 95b662f359bd94baf68ac86450d94298dd6b366d | 636 |
from typing import List
def format_count(
label: str, counts: List[int], color: str, dashed: bool = False
) -> dict:
"""Format a line dataset for chart.js"""
ret = {
"label": label,
"data": counts,
"borderColor": color,
"borderWidth": 2,
"fill": False,
}
if ... | 40f5aee7ad5d66f57737345b7d82e45a97cf6633 | 638 |
def get_valid_segment(text):
""" Returns None or the valid Loki-formatted urn segment for the given input string. """
if text == '':
return None
else:
# Return the converted text value with invalid characters removed.
valid_chars = ['.', '_', '-']
new_text = ''
for c... | 423c1764b590df635b0794bfe52a0a8479d53fbf | 639 |
def positive_dice_parse(dice: str) -> str:
"""
:param dice: Formatted string, where each line is blank or matches
t: [(t, )*t]
t = (0|T|2A|SA|2S|S|A)
(note: T stands for Triumph here)
:return: Formatted string matching above, except tokens are ... | 5b266a4025706bfc8f4deabe67735a32f4b0785d | 642 |
def GetVerificationStepsKeyName(name):
"""Returns a str used to uniquely identify a verification steps."""
return 'VerificationSteps_' + name | e50e9bd7b586d8bbfaf8902ce343d35d752948a4 | 646 |
import codecs
import logging
def read_file(file_path):
"""
Read the contents of a file using utf-8 encoding, or return an empty string
if it does not exist
:param file_path: str: path to the file to read
:return: str: contents of file
"""
try:
with codecs.open(file_path, 'r', encod... | 13a72bc939021e3046243ed9afc7014cb403652a | 647 |
def _list_subclasses(cls):
"""
Recursively lists all subclasses of `cls`.
"""
subclasses = cls.__subclasses__()
for subclass in cls.__subclasses__():
subclasses += _list_subclasses(subclass)
return subclasses | 4cebf48916c64f32fcd5dfff28ecde7a155edb90 | 649 |
def rho_MC(delta, rhoeq=4.39e-38):
"""
returns the characteristic density of an
axion minicluster in [solar masses/km^3]
forming from an overdensity with
overdensity parameter delta.
rhoeq is the matter density at matter
radiation equality in [solar masses/km^3]
"""
return 140 * (1 + del... | f28e382cfcf661199728363b3ebe86f25e92760c | 654 |
def is_ascii(string):
"""Return True is string contains only is us-ascii encoded characters."""
def is_ascii_char(char):
return 0 <= ord(char) <= 127
return all(is_ascii_char(char) for char in string) | cd3aeddcad7610de83af6ec5a67ecbac95f11fd8 | 655 |
def summary(task):
"""Given an ImportTask, produce a short string identifying the
object.
"""
if task.is_album:
return u'{0} - {1}'.format(task.cur_artist, task.cur_album)
else:
return u'{0} - {1}'.format(task.item.artist, task.item.title) | 87387c47e90998c270f6f8f2f63ceacebd4cdc78 | 658 |
from typing import List
def build_graph(order: int, edges: List[List[int]]) -> List[List[int]]:
"""Builds an adjacency list from the edges of an undirected graph."""
adj = [[] for _ in range(order)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
return adj | 86bdd0d4314777ff59078b1c0f639e9439f0ac08 | 660 |
def calculate(cart):
"""Return the total shipping cost for the cart. """
total = 0
for line in cart.get_lines():
total += line.item.shipping_cost * line.quantity
return total | 4b6d9bd94ce3a5748f0d94ab4b23dab993b430e4 | 666 |
def format_perm(model, action):
"""
Format a permission string "app.verb_model" for the model and the
requested action (add, change, delete).
"""
return '{meta.app_label}.{action}_{meta.model_name}'.format(
meta=model._meta, action=action) | 12f532e28f685c2a38a638de63928f07039d44c8 | 668 |
import math
def normal_to_angle(x, y):
"""
Take two normal vectors and return the angle that they give.
:type x: float
:param x: x normal
:type y: float
:param y: y normal
:rtype: float
:return: angle created by the two normals
"""
return math.atan2(y, x) * 180 / math.pi | c6f5b5e2952858cd3592b4e0849806b0ccd5de78 | 670 |
import socket
def is_open_port(port):
"""
Check if port is open
:param port: port number to be checked
:type port: int
:return: is port open
:rtype: bool
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind(("127.0.0.1", port))
except socket.error:
... | df81cc942f39d00bbdb8cb11628666a117c9788f | 672 |
def build_attribute_set(items, attr_name):
"""Build a set off of a particular attribute of a list of
objects. Adds 'None' to the set if one or more of the
objects in items is missing the attribute specified by
attr_name.
"""
attribute_set = set()
for item in items:
attribute_set.add(... | 2cee5922463188a4a8d7db79d6be003e197b577f | 673 |
def get_elk_command(line):
"""Return the 2 character command in the message."""
if len(line) < 4:
return ""
return line[2:4] | 550eda4e04f57ae740bfd294f9ec3b243e17d279 | 674 |
def safe_div(a, b):
"""
Safe division operation. When b is equal to zero, this function returns 0.
Otherwise it returns result of a divided by non-zero b.
:param a: number a
:param b: number b
:return: a divided by b or zero
"""
if b == 0:
return 0
return a / b | 68e5bccbe812315b9a1d27a1fa06d26d5339d6fd | 675 |
def shouldAvoidDirectory(root, dirsToAvoid):
"""
Given a directory (root, of type string) and a set of directory
paths to avoid (dirsToAvoid, of type set of strings), return a boolean value
describing whether the file is in that directory to avoid.
"""
subPaths = root.split('/')
for i, sub... | afc92111f57031eb1e2ba797d80ea4abc2a7ccd0 | 676 |
def get_structure_index(structure_pattern,stream_index):
"""
Translates the stream index into a sequence of structure indices identifying an item in a hierarchy whose structure is specified by the provided structure pattern.
>>> get_structure_index('...',1)
[1]
>>> get_structure_index('.[.].',1)
... | 8f1def101aa2ec63d1ea69382db9641bf0f51380 | 678 |
def errorcode_from_error(e):
"""
Get the error code from a particular error/exception caused by PostgreSQL.
"""
return e.orig.pgcode | 981b447d540e949834c10f4a05fb21769091b104 | 679 |
import re
def clean_filename(string: str) -> str:
"""
清理文件名中的非法字符,防止保存到文件系统时出错
:param string:
:return:
"""
string = string.replace(':', '_').replace('/', '_').replace('\x00', '_')
string = re.sub('[\n\\\*><?\"|\t]', '', string)
return string.strip() | 805023382e30c0d0113715cdf6c7bcbc8b383066 | 686 |
def calc_disordered_regions(limits, seq):
"""
Returns the sequence of disordered regions given a string of
starts and ends of the regions and the sequence.
Example
-------
limits = 1_5;8_10
seq = AHSEDQNAAANTH...
This will return `AHSED_AAA`
"""
seq = seq.replace(' ', '... | 2c9a487a776a742470deb98e6f471b04b23a0ff7 | 692 |
def handle_storage_class(vol):
"""
vol: dict (send from the frontend)
If the fronend sent the special values `{none}` or `{empty}` then the
backend will need to set the corresponding storage_class value that the
python client expects.
"""
if "class" not in vol:
return None
if vo... | a2747b717c6b83bb1128f1d5e9d7696dd8deda19 | 697 |
def get_uniform_comparator(comparator):
""" convert comparator alias to uniform name
"""
if comparator in ["eq", "equals", "==", "is"]:
return "equals"
elif comparator in ["lt", "less_than"]:
return "less_than"
elif comparator in ["le", "less_than_or_equals"]:
return "less_th... | 20c24ba35dea92d916d9dd1006d110db277e0816 | 700 |
def inorder_traversal(root):
"""Function to traverse a binary tree inorder
Args:
root (Node): The root of a binary tree
Returns:
(list): List containing all the values of the tree from an inorder search
"""
res = []
if root:
res = inorder_traversal(root.left)
re... | f6d5141cbe9f39da609bd515133b367975e56688 | 701 |
def make_count(bits, default_count=50):
"""
Return items count from URL bits if last bit is positive integer.
>>> make_count(['Emacs'])
50
>>> make_count(['20'])
20
>>> make_count(['бред', '15'])
15
"""
count = default_count
if len(bits) > 0:
last_bit = bits[len(... | 8e7dc356ba7c0787b4b44ee8bba17568e27d1619 | 703 |
def x_for_half_max_y(xs, ys):
"""Return the x value for which the corresponding y value is half
of the maximum y value. If there is no exact corresponding x value,
one is calculated by linear interpolation from the two
surrounding values.
:param xs: x values
:param ys: y values corresponding to... | b18525664c98dc05d72a29f2904a13372f5696eb | 709 |
def requestor_is_superuser(requestor):
"""Return True if requestor is superuser."""
return getattr(requestor, "is_superuser", False) | 7b201601cf8a1911aff8271ff71b6d4d51f68f1a | 711 |
def removeDuplicates(listToRemoveFrom: list[str]):
"""Given list, returns list without duplicates"""
listToReturn: list[str] = []
for item in listToRemoveFrom:
if item not in listToReturn:
listToReturn.append(item)
return listToReturn | 8265e7c560d552bd9e30c0a1140d6668abd1b4d6 | 712 |
import random
def random_param_shift(vals, sigmas):
"""Add a random (normal) shift to a parameter set, for testing"""
assert len(vals) == len(sigmas)
shifts = [random.gauss(0, sd) for sd in sigmas]
newvals = [(x + y) for x, y in zip(vals, shifts)]
return newvals | 07430572c5051b7142499bcbdbc90de5abfcbd4d | 722 |
from typing import OrderedDict
import six
def BuildPartialUpdate(clear, remove_keys, set_entries, field_mask_prefix,
entry_cls, env_builder):
"""Builds the field mask and patch environment for an environment update.
Follows the environments update semantic which applies operations
in an ... | 320c589cd45dcec9a3ebba4b295075e23ef805ed | 728 |
def bycode(ent, group):
"""
Get the data with the given group code from an entity.
Arguments:
ent: An iterable of (group, data) tuples.
group: Group code that you want to retrieve.
Returns:
The data for the given group code. Can be a list of items if the group
code occu... | c5b92f2bbd1cd5bc383a1102ccf54031222d82c3 | 729 |
import math
def bond_number(r_max, sigma, rho_l, g):
""" calculates the Bond number for the largest droplet according to
Cha, H.; Vahabi, H.; Wu, A.; Chavan, S.; Kim, M.-K.; Sett, S.; Bosch, S. A.; Wang, W.; Kota, A. K.; Miljkovic, N.
Dropwise Condensation on Solid Hydrophilic Surfaces. Science Advances 2... | 2098a762dd7c2e80ff4a570304acf7cfbdbba2e5 | 733 |
async def timeron(websocket, battleID):
"""Start the timer on a Metronome Battle.
"""
return await websocket.send(f'{battleID}|/timer on') | f1601694e2c37d41adcc3983aa535347dc13db71 | 734 |
import base64
def decode(msg):
""" Convert data per pubsub protocol / data format
Args:
msg: The msg from Google Cloud
Returns:
data: The msg data as a string
"""
if 'data' in msg:
data = base64.b64decode(msg['data']).decode('utf-8')
return data | 32e85b3f0c18f3d15ecb0779825941024da75909 | 736 |
from operator import itemgetter
def list_unique(hasDupes):
"""Return the sorted unique values from a list"""
# order preserving
d = dict((x, i) for i, x in enumerate(hasDupes))
return [k for k, _ in sorted(d.items(), key=itemgetter(1))] | 0ba0fcb216400806aca4a11d5397531dc19482f6 | 740 |
def selection_criteria_1(users, label_of_interest):
"""
Formula for Retirement/Selection score:
x = sum_i=1_to_n (r_i) — sum_j=1_to_m (r_j).
Where first summation contains reliability scores of users who have labeled it as the same
as the label of interest, second summation contains reliability scor... | 8255fd3645d5b50c43006d2124d06577e3ac8f2d | 752 |
import re
def book_number_from_path(book_path: str) -> float:
"""
Parses the book number from a directory string.
Novellas will have a floating point value like "1.1" which indicates that it was the first novella
to be published between book 1 and book 2.
:param book_path: path of the currently ... | 087cb0b8cd0c48c003175a05ed0d7bb14ad99ac3 | 753 |
def intervals_split_merge(list_lab_intervals):
"""
对界限列表进行融合
e.g.
如['(2,5]', '(5,7]'], 融合后输出为 '(2,7]'
Parameters:
----------
list_lab_intervals: list, 界限区间字符串列表
Returns:
-------
label_merge: 合并后的区间
"""
list_labels = []
# 遍历每个区间, 取得左值右值字符串组成列表
for lab in list_la... | a9e99ec6fc51efb78a4884206a72f7f4ad129dd4 | 754 |
from typing import List
def set_process_tracking(template: str, channels: List[str]) -> str:
"""This function replaces the template placeholder for the process tracking with the correct process tracking.
Args:
template: The template to be modified.
channels: The list of channels to be used.
... | 0cf720bd56a63939541a06e60492472f92c4e589 | 755 |
def read_dynamo_table(gc, name, read_throughput=None, splits=None):
"""
Reads a Dynamo table as a Glue DynamicFrame.
:param awsglue.context.GlueContext gc: The GlueContext
:param str name: The name of the Dynamo table
:param str read_throughput: Optional read throughput - supports values from "0.1"... | 5f789626cb3fc8004532cc59bdae128b744b111e | 756 |
def check_args(**kwargs):
"""
Check arguments for themis load function
Parameters:
**kwargs : a dictionary of arguments
Possible arguments are: probe, level
The arguments can be: a string or a list of strings
Invalid argument are ignored (e.g. probe = 'g', level=... | 3e25dc43df0a80a9a16bcca0729ee0b170a9fb89 | 763 |
def insert_node_after(new_node, insert_after):
"""Insert new_node into buffer after insert_after."""
next_element = insert_after['next']
next_element['prev'] = new_node
new_node['next'] = insert_after['next']
insert_after['next'] = new_node
new_node['prev'] = insert_after
return new_node | e03fbd7bd44a3d85d36069d494464b9237bdd306 | 765 |
def classname(object, modname):
"""Get a class name and qualify it with a module name if necessary."""
name = object.__name__
if object.__module__ != modname:
name = object.__module__ + '.' + name
return name | af4e05b0adaa9c90bb9946edf1dba67a40e78323 | 766 |
from typing import Union
from pathlib import Path
from typing import Dict
import json
def read_json(json_path: Union[str, Path]) -> Dict:
"""
Read json file from a path.
Args:
json_path: File path to a json file.
Returns:
Python dictionary
"""
with open(json_path, "r") as fp:... | c0b55e5363a134282977ee8a01083490e9908fcf | 780 |
def gce_zones() -> list:
"""Returns the list of GCE zones"""
_bcds = dict.fromkeys(['us-east1', 'europe-west1'], ['b', 'c', 'd'])
_abcfs = dict.fromkeys(['us-central1'], ['a', 'b', 'c', 'f'])
_abcs = dict.fromkeys(
[
'us-east4',
'us-west1',
'europe-west4',
... | 10e684b2f458fe54699eb9886af148b092ec604d | 782 |
def map_parallel(function, xs):
"""Apply a remote function to each element of a list."""
if not isinstance(xs, list):
raise ValueError('The xs argument must be a list.')
if not hasattr(function, 'remote'):
raise ValueError('The function argument must be a remote function.')
# EXERCISE:... | 1fe75868d5ff12a361a6aebd9e4e49bf92c32126 | 785 |
def get_tone(pinyin):
"""Renvoie le ton du pinyin saisi par l'utilisateur.
Args:
pinyin {str}:
l'entrée pinyin par l'utilisateur
Returns:
number/None :
Si pas None, la partie du ton du pinyin (chiffre)
"""
# Prenez le dernier chaine du pinyin
tone = pin... | fc0b02902053b3f2470acf952812573f5125c4cf | 787 |
import requests
def fetch_url(url):
"""Fetches the specified URL.
:param url: The URL to fetch
:type url: string
:returns: The response object
"""
return requests.get(url) | 26198dbc4f7af306e7a09c86b59a7da1a4802241 | 794 |
def get_symbol_size(sym):
"""Get the size of a symbol"""
return sym["st_size"] | b2d39afe39542e7a4e1b4fed60acfc83e6a58677 | 795 |
from pathlib import Path
def get_parent_dir(os_path: str) -> str:
"""
Get the parent directory.
"""
return str(Path(os_path).parents[1]) | 3a6e518119e39bfbdb9381bc570ac772b88b1334 | 796 |
def get_factors(n: int) -> list:
"""Returns the factors of a given integer.
"""
return [i for i in range(1, n+1) if n % i == 0] | c15a0e30e58597daf439facd3900c214831687f2 | 799 |
def getChrLenList(chrLenDict, c):
""" Given a chromosome length dictionary keyed on chromosome names and
a chromosome name (c) this returns a list of all the runtimes for a given
chromosome across all Step names.
"""
l = []
if c not in chrLenDict:
return l
for n in chrLenDict[c]:
... | aedf613484262ac5bd31baf384ade2eb35f3e1eb | 802 |
import unicodedata
def normalize(form, text):
"""Return the normal form form for the Unicode string unistr.
Valid values for form are 'NFC', 'NFKC', 'NFD', and 'NFKD'.
"""
return unicodedata.normalize(form, text) | 6d32604a951bb13ff649fd3e221c2e9b35d4f1a1 | 809 |
def box(type_):
"""Create a non-iterable box type for an object.
Parameters
----------
type_ : type
The type to create a box for.
Returns
-------
box : type
A type to box values of type ``type_``.
"""
class c(object):
__slots__ = 'value',
def __init... | 5b4721ab78ce17f9eeb93abcc59bed046917d296 | 810 |
def path_to_model(path):
"""Return model name from path."""
epoch = str(path).split("phase")[-1]
model = str(path).split("_dir/")[0].split("/")[-1]
return f"{model}_epoch{epoch}" | 78b10c8fb6f9821e6be6564738d40f822e675cb6 | 814 |
def binary_to_string(bin_string: str):
"""
>>> binary_to_string("01100001")
'a'
>>> binary_to_string("a")
Traceback (most recent call last):
...
ValueError: bukan bilangan biner
>>> binary_to_string("")
Traceback (most recent call last):
...
ValueError: tidak ada yang diinput... | f22dd64027ee65acd4d782a6a1ce80520f016770 | 817 |
def tabindex(field, index):
"""Set the tab index on the filtered field."""
field.field.widget.attrs["tabindex"] = index
return field | c42b64b3f94a2a8a35b8b0fa3f14fe6d44b2f755 | 818 |
def hook_name_to_env_name(name, prefix='HOOKS'):
"""
>>> hook_name_to_env_name('foo.bar_baz')
HOOKS_FOO_BAR_BAZ
>>> hook_name_to_env_name('foo.bar_baz', 'PREFIX')
PREFIX_FOO_BAR_BAZ
"""
return '_'.join([prefix, name.upper().replace('.', '_')]) | b0dabce88da8ddf8695303ac4a22379baa4ddffa | 822 |
def readline_skip_comments(f):
"""
Read a new line while skipping comments.
"""
l = f.readline().strip()
while len(l) > 0 and l[0] == '#':
l = f.readline().strip()
return l | c4b36af14cc48b1ed4cd72b06845e131015da6c6 | 823 |
def _verify_weight_parameters(weight_parameters):
"""Verifies that the format of the input `weight_parameters`.
Checks that the input parameters is a 2-tuple of tensors of equal shape.
Args:
weight_parameters: The parameters to check.
Raises:
RuntimeError: If the input is not a 2-tuple of tensors wit... | 9ec018c66d48e830250fd299cd50f370118132cc | 824 |
def _crc16_checksum(bytes):
"""Returns the CRC-16 checksum of bytearray bytes
Ported from Java implementation at: http://introcs.cs.princeton.edu/java/61data/CRC16CCITT.java.html
Initial value changed to 0x0000 to match Stellar configuration.
"""
crc = 0x0000
polynomial = 0x1021
for byte ... | 2b00d11f1b451f3b8a4d2f42180f6f68d2fbb615 | 825 |
def is_bond_member(yaml, ifname):
"""Returns True if this interface is a member of a BondEthernet."""
if not "bondethernets" in yaml:
return False
for _bond, iface in yaml["bondethernets"].items():
if not "interfaces" in iface:
continue
if ifname in iface["interfaces"]:
... | 521186221f2d0135ebcf1edad8c002945a56da26 | 827 |
def extract_paths(actions):
"""
<Purpose>
Given a list of actions, it extracts all the absolute and relative paths
from all the actions.
<Arguments>
actions: A list of actions from a parsed trace
<Returns>
absolute_paths: a list with all absolute paths extracted from the actions
... | 94aaf8fef1a7c6d3efd8b04c980c9e87ee7ab4ff | 833 |
import re
def only_letters(answer):
"""Checks if the string contains alpha-numeric characters
Args:
answer (string):
Returns:
bool:
"""
match = re.match("^[a-z0-9]*$", answer)
return bool(match) | 32c8905294f6794f09bb7ea81ed7dd4b6bab6dc5 | 841 |
def _InUse(resource):
"""All the secret names (local names & remote aliases) in use.
Args:
resource: Revision
Returns:
List of local names and remote aliases.
"""
return ([
source.secretName
for source in resource.template.volumes.secrets.values()
] + [
source.secretKeyRef.name
... | cf13ccf1d0fffcd64ac8b3a40ac19fdb2b1d12c5 | 842 |
import re
def re_identify_image_metadata(filename, image_names_pattern):
"""
Apply a regular expression to the *filename* and return metadata
:param filename:
:param image_names_pattern:
:return: a list with metadata derived from the image filename
"""
match = re.match(image_names_pattern,... | 1730620682f2457537e3f59360d998b251f5067f | 843 |
def mark_task(func):
"""Mark function as a defacto task (for documenting purpose)"""
func._is_task = True
return func | 9f0156fff2a2a6dcb64e79420022b78d1c254490 | 846 |
def make_slack_message_divider() -> dict:
"""Generates a simple divider for a Slack message.
Returns:
The generated divider.
"""
return {'type': 'divider'} | 9d0243c091065056a29d9fa05c62fadde5dcf6f6 | 847 |
def _stringify(item):
"""
Private funtion which wraps all items in quotes to protect from paths
being broken up. It will also unpack lists into strings
:param item: Item to stringify.
:return: string
"""
if isinstance(item, (list, tuple)):
return '"' + '" "'.join(item) + '"'
i... | 7187b33dccce66cb81b53ed8e8c395b74e125633 | 853 |
def _get_tree_filter(attrs, vecvars):
"""
Pull attributes and input/output vector variables out of a tree System.
Parameters
----------
attrs : list of str
Names of attributes (may contain dots).
vecvars : list of str
Names of variables contained in the input or output vectors.
... | fb96025a075cfc3c56011f937d901d1b87be4f03 | 854 |
def replace_string(original, start, end, replacement):
"""Replaces the specified range of |original| with |replacement|"""
return original[0:start] + replacement + original[end:] | c71badb26287d340170cecdbae8d913f4bdc14c6 | 861 |
def dictionarify_recpat_data(recpat_data):
"""
Covert a list of flat dictionaries (single-record dicts) into a dictionary.
If the given data structure is already a dictionary, it is left unchanged.
"""
return {track_id[0]: patterns[0] for track_id, patterns in \
[zip(*item.items()) for ... | d1cdab68ab7445aebe1bbcce2f220c73d6db308f | 862 |
def _module_exists(module_name):
"""
Checks if a module exists.
:param str module_name: module to check existance of
:returns: **True** if module exists and **False** otherwise
"""
try:
__import__(module_name)
return True
except ImportError:
return False | 8f3ed2e97ee6dbb41d6e84e9e5595ec8b6f9b339 | 868 |
def normal_shock_pressure_ratio(M, gamma):
"""Gives the normal shock static pressure ratio as a function of upstream Mach number."""
return 1.0+2.0*gamma/(gamma+1.0)*(M**2.0-1.0) | 30d0a339b17bab2b662fecd5b19073ec6478a1ec | 871 |
def get_ical_file_name(zip_file):
"""Gets the name of the ical file within the zip file."""
ical_file_names = zip_file.namelist()
if len(ical_file_names) != 1:
raise Exception(
"ZIP archive had %i files; expected 1."
% len(ical_file_names)
)
return ical_file_names... | 7013840891844358f0b4a16c7cefd31a602d9eae | 873 |
def decode_field(value):
"""Decodes a field as defined in the 'Field Specification' of the actions
man page: http://www.openvswitch.org/support/dist-docs/ovs-actions.7.txt
"""
parts = value.strip("]\n\r").split("[")
result = {
"field": parts[0],
}
if len(parts) > 1 and parts[1]:
... | 1a1659e69127ddd3c63eb7d4118ceb4e53a28ca0 | 885 |
def _nonempty_line_count(src: str) -> int:
"""Count the number of non-empty lines present in the provided source string."""
return sum(1 for line in src.splitlines() if line.strip()) | ad2ac0723f9b3e1f36b331175dc32a8591c67893 | 886 |
def _dump_multipoint(obj, fmt):
"""
Dump a GeoJSON-like MultiPoint object to WKT.
Input parameters and return value are the MULTIPOINT equivalent to
:func:`_dump_point`.
"""
coords = obj['coordinates']
mp = 'MULTIPOINT (%s)'
points = (' '.join(fmt % c for c in pt) for pt in coords)
... | cdea05b91c251b655e08650807e3f74d3bb5e77b | 889 |
def binary_distance(label1, label2):
"""Simple equality test.
0.0 if the labels are identical, 1.0 if they are different.
>>> from nltk.metrics import binary_distance
>>> binary_distance(1,1)
0.0
>>> binary_distance(1,3)
1.0
"""
return 0.0 if label1 == label2 else 1.0 | 2c4eaebda2d6955a5012cc513857aed66df60194 | 890 |
def apply_function(f, *args, **kwargs):
""" Apply a function or staticmethod/classmethod to the given arguments.
"""
if callable(f):
return f(*args, **kwargs)
elif len(args) and hasattr(f, '__get__'):
# support staticmethod/classmethod
return f.__get__(None, args[0])(*args, **kwa... | 374be0283a234d4121435dbd3fa873640f2b9ad1 | 898 |
def make_file_iterator(filename):
"""Return an iterator over the contents of the given file name."""
# pylint: disable=C0103
with open(filename) as f:
contents = f.read()
return iter(contents.splitlines()) | e7b612465717dafc3155d9df9fd007f7aa9af509 | 902 |
def pad_in(string: str, space: int) -> str:
"""
>>> pad_in('abc', 0)
'abc'
>>> pad_in('abc', 2)
' abc'
"""
return "".join([" "] * space) + string | 325c0751da34982e33e8fae580af6f439a2dcac0 | 908 |
def extend_params(params, more_params):
"""Extends dictionary with new values.
Args:
params: A dictionary
more_params: A dictionary
Returns:
A dictionary which combines keys from both dictionaries.
Raises:
ValueError: if dicts have the same key.
"""
for yak in more_params:
if yak in p... | 626db0ae8d8a249b8c0b1721b7a2e0f1d4c084b8 | 910 |
def get_rdf_lables(obj_list):
"""Get rdf:labels from a given list of objects."""
rdf_labels = []
for obj in obj_list:
rdf_labels.append(obj['rdf:label'])
return rdf_labels | 2bcf6a6e8922e622de602f5956747955ea39eeda | 919 |
def get_request_list(flow_list: list) -> list:
"""
将flow list转换为request list。在mitmproxy中,flow是对request和response的总称,这个功能只获取request。
:param flow_list: flow的列表
:return: request的列表
"""
req_list = []
for flow in flow_list:
request = flow.get("request")
req_list.append(request)
... | a70e0120ef2be88bd0644b82317a2a0748352c6c | 922 |
def _B(slot):
"""Convert slot to Byte boundary"""
return slot*2 | 97f13e9fd99989a83e32f635193a0058656df68b | 925 |
def union(l1, l2):
""" return the union of two lists """
return list(set(l1) | set(l2)) | 573e3b0e475b7b33209c4a477ce9cab53ec849d4 | 931 |
def get_start_end(sequence, skiplist=['-','?']):
"""Return position of first and last character which is not in skiplist.
Skiplist defaults to ['-','?'])."""
length=len(sequence)
if length==0:
return None,None
end=length-1
while end>=0 and (sequence[end] in skiplist):
end-=1
... | b67e0355516f5aa5d7f7fad380d262cf0509bcdb | 934 |
def middle(word):
"""Returns all but the first and last characters of a string."""
return word[1:-1] | 257a159c46633d3c3987437cb3395ea2be7fad70 | 940 |
import re
from pathlib import Path
import json
def load_stdlib_public_names(version: str) -> dict[str, frozenset[str]]:
"""Load stdlib public names data from JSON file"""
if not re.fullmatch(r"\d+\.\d+", version):
raise ValueError(f"{version} is not a valid version")
try:
json_file = Pat... | 02775d96c8a923fc0380fe6976872a7ed2cf953a | 942 |
def calc_dof(model):
"""
Calculate degrees of freedom.
Parameters
----------
model : Model
Model.
Returns
-------
int
DoF.
"""
p = len(model.vars['observed'])
return p * (p + 1) // 2 - len(model.param_vals) | ccff8f5a7624b75141400747ec7444ec55eb492d | 947 |
import functools
def skip_if_disabled(func):
"""Decorator that skips a test if test case is disabled."""
@functools.wraps(func)
def wrapped(*a, **kwargs):
func.__test__ = False
test_obj = a[0]
message = getattr(test_obj, 'disabled_message',
'Test disabled'... | 56d42a1e0418f4edf3d4e8478358495b1353f57a | 956 |
from typing import Any
import itertools
def _compare_keys(target: Any, key: Any) -> bool:
"""
Compare `key` to `target`.
Return True if each value in `key` == corresponding value in `target`.
If any value in `key` is slice(None), it is considered equal
to the corresponding value in `target`.
... | ff5c60fab8ac0cbfe02a816ec78ec4142e32cfbf | 957 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.