content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def remove_constant_features(sfm):
"""
Remove features that are constant across all samples
"""
# boolean matrix of whether x == first column (feature)
x_not_equal_to_1st_row = sfm._x != sfm._x[0]
non_const_f_bool_ind = x_not_equal_to_1st_row.sum(axis=0) >= 1
return sfm.ind_x(selected_f_inds... | ae8c6e1d14b7260c8d2491b2f8a00ba352d7375a | 709,647 |
def readByte (file):
""" Read a byte from file. """
return ord (file.read (1)) | 4e82d1b688d7742fd1dd1025cd7ac1ccb13bbca0 | 709,655 |
def sdfGetMolBlock(mol):
"""
sdfGetMolBlock() returns the MOL block of the molecule
"""
return mol["molblock"] | 399874a696f30f492ee878ef661094119bd5f96f | 709,657 |
def noop_chew_func(_data, _arg):
"""
No-op chew function.
"""
return 0 | 82ef82b350c2a01e5ba22f288c003032bf6e63e0 | 709,662 |
from datetime import datetime
def set_clock(child, timestamp=None):
"""Set the device's clock.
:param pexpect.spawn child: The connection in a child application object.
:param datetime timestamp: A datetime tuple (year, month, day, hour, minute, second).
:returns: The updated connection in a child ap... | b6299ab780ffc9e9d27b0715decf095b3d6a6272 | 709,664 |
def uniquify_contacts(contacts):
"""
Return a sequence of contacts with all duplicates removed.
If any duplicate names are found without matching numbers, an exception is raised.
"""
ctd = {}
for ct in contacts:
stored_ct = ctd.setdefault(ct.name, ct)
if stored_ct.dmrid != ct.dm... | f4bf001abcccad1307633e6de6ed6228516ba0b2 | 709,669 |
def determine_if_is_hmmdb(infp):
"""Return True if the given file is an HMM database (generated using
hmmpress from the HMMer3 software package), and return False otherwise.
"""
#if open(infp, 'r').read().startswith('HMMER3/f'):
if open(infp, 'r').readline().startswith('HMMER3/f'):
return Tr... | 33b962e24c76e9e25f2cc76d4e7f78565adf8a3e | 709,671 |
def template_footer(in_template):
"""Extracts footer from the notebook template.
Args:
in_template (str): Input notebook template file path.
Returns:
list: List of lines.
"""
footer = []
template_lines = []
footer_start_index = 0
with open(in_template) as f... | cb872076b82b2012b2e27fcb1be9b8704cd60d27 | 709,672 |
def post_step1(records):
"""Apply whatever extensions we have for GISTEMP step 1, that run
after the main step 1. None at present."""
return records | 98287f6930db6aa025715356084b3bef8c851774 | 709,673 |
import math
def spatial_shift_crop_list(size, images, spatial_shift_pos, boxes=None):
"""
Perform left, center, or right crop of the given list of images.
Args:
size (int): size to crop.
image (list): ilist of images to perform short side scale. Dimension is
`height` x `width` ... | c80d8ab83f072c94887d48c3d1cfe5bb18285dbb | 709,675 |
def _checker(word: dict):
"""checks if the 'word' dictionary is fine
:param word: the node in the list of the text
:type word: dict
:return: if "f", "ref" and "sig" in word, returns true, else, returns false
:rtype: bool
"""
if "f" in word and "ref" in word and "sig" in word:
return... | ee6ec5a7ee393ddcbc97b13f6c09cdd9019fb1a6 | 709,680 |
def to_n_class(digit_lst, data, labels):
"""to make a subset of MNIST dataset, which has particular digits
Parameters
----------
digit_lst : list
for example, [0,1,2] or [1, 5, 8]
data : numpy.array, shape (n_samples, n_features)
labels : numpy.array or list of str
Returns
------... | 79652687ec0670ec00d67681711903ae01f4cc87 | 709,682 |
def max_tb(collection): # pragma: no cover
"""Returns the maximum number of TB recorded in the collection"""
max_TB = 0
for doc in collection.find({}).sort([('total_TB',-1)]).limit(1):
max_TB = doc['total_TB']
return max_TB | bde417de0b38de7a7b5e4e3db8c05e87fa6c55ca | 709,687 |
import time
def datetime_to_timestamp(d):
"""convert a datetime object to seconds since Epoch.
Args:
d: a naive datetime object in default timezone
Return:
int, timestamp in seconds
"""
return int(time.mktime(d.timetuple())) | 356ac090b0827d49e9929a7ef26041b26c6cc690 | 709,688 |
def update_coverage(coverage, path, func, line, status):
"""Add to coverage the coverage status of a single line"""
coverage[path] = coverage.get(path, {})
coverage[path][func] = coverage[path].get(func, {})
coverage[path][func][line] = coverage[path][func].get(line, status)
coverage[path][func][li... | 46e5a1e5c4ebba3a9483f90ada96a0f7f94d8c1d | 709,690 |
def cross_product(v1, v2):
"""Calculate the cross product of 2 vectors as (x1 * y2 - x2 * y1)."""
return v1.x * v2.y - v2.x * v1.y | 871d803ef687bf80facf036549b4b2062f713994 | 709,691 |
import re
def _xfsdump_output(data):
"""
Parse CLI output of the xfsdump utility.
"""
out = {}
summary = []
summary_block = False
for line in [l.strip() for l in data.split("\n") if l.strip()]:
line = re.sub("^xfsdump: ", "", line)
if line.startswith("session id:"):
... | dbc7fbf9dced99b83a7dc5917c473a1dee16d749 | 709,705 |
def parseParams(opt):
"""Parse a set of name=value parameters in the input value.
Return list of (name,value) pairs.
Raise ValueError if a parameter is badly formatted.
"""
params = []
for nameval in opt:
try:
name, val = nameval.split("=")
except ValueError:
... | b932f74c8e5502ebdd7a8749c2de4b30921d518b | 709,708 |
def _get_name(dist):
"""Attempts to get a distribution's short name, excluding the name scope."""
return getattr(dist, 'parameters', {}).get('name', dist.name) | fd57e523c1a84a36f9ed56236e4b8db1e887575c | 709,709 |
def NO_MERGE(writer, segments):
"""This policy does not merge any existing segments.
"""
return segments | 0742365f30d59cb219ac60483b867180bd910ba8 | 709,712 |
from typing import Union
def parse_boolean(val: str) -> Union[str, bool]:
"""Try to parse a string into boolean.
The string is returned as-is if it does not look like a boolean value.
"""
val = val.lower()
if val in ('y', 'yes', 't', 'true', 'on', '1'):
return True
if val in ('n', 'no... | e2cbda5a849e1166e0f2a3953220c93d1f3ba119 | 709,716 |
import re
def safe_htcondor_attribute(attribute: str) -> str:
"""Convert input attribute name into a valid HTCondor attribute name
HTCondor ClassAd attribute names consist only of alphanumeric characters or
underscores. It is not clearly documented, but the alphanumeric characters
are probably restr... | 7a4dda539b2379120e68737d72a80226c45f5602 | 709,720 |
def make_csv(headers, data):
"""
Creates a CSV given a set of headers and a list of database query results
:param headers: A list containg the first row of the CSV
:param data: The list of query results from the Database
:returns: A str containing a csv of the query results
"""
# Create a list where each entr... | 5101d53de8dd09d8ebe743d77d71bff9aeb26334 | 709,721 |
from typing import Tuple
def extract_value_from_config(
config: dict,
keys: Tuple[str, ...],
):
"""
Traverse a config dictionary to get some hyper-parameter's value.
Parameters
----------
config
A config dictionary.
keys
The possible names of a hyper-parameter.... | d545d4c9298c74776ec52fb6b2c8d54d0e653489 | 709,722 |
def vision_matched_template_get_pose(template_match):
"""
Get the pose of a previously detected template match. Use list operations
to get specific entries, otherwise returns value of first entry.
Parameters:
template_match (List[MatchedTemplate3D] or MatchedTemplate3D): The template match(s)
... | b854da7a085934f4f3aba510e76852fb8c0a440a | 709,724 |
def get_vocabulary(query_tree):
"""Extracts the normalized search terms from the leaf nodes of a parsed
query to construct the vocabulary for the text vectorization.
Arguments
---------
query_tree: pythonds.trees.BinaryTree
The binary tree object representing a parsed search query. Each lea... | bd03f4894cd3f9a7964196bfb163335f84a048d7 | 709,728 |
def find_point_in_section_list(point, section_list):
"""Returns the start of the section the given point belongs to.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 3... | 47d5cda15b140ba8505ee658fd46ab090b2fda8a | 709,729 |
def choose(population, sample):
"""
Returns ``population`` choose ``sample``, given
by: n! / k!(n-k)!, where n == ``population`` and
k == ``sample``.
"""
if sample > population:
return 0
s = max(sample, population - sample)
assert s <= population
assert population > -1
i... | 659eac683cae737888df74c0db21aa3ece746b33 | 709,731 |
def eea(m, n):
"""
Compute numbers a, b such that a*m + b*n = gcd(m, n)
using the Extended Euclidean algorithm.
"""
p, q, r, s = 1, 0, 0, 1
while n != 0:
k = m // n
m, n, p, q, r, s = n, m - k*n, q, p - k*q, s, r - k*s
return (p, r) | 56e1c59ac3a51e26d416fe5c65cf6612dbe56b8c | 709,733 |
def maximum_value(tab):
"""
brief: return maximum value of the list
args:
tab: a list of numeric value expects at leas one positive value
return:
the max value of the list
the index of the max value
raises:
ValueError if expected a list as input
ValueError if no positive value found
"""
if not(isinstan... | 1c31daf3a953a9d781bc48378ef53323313dc22a | 709,739 |
import math
def dsh(
incidence1: float, solar_az1: float, incidence2: float, solar_az2: float
):
"""Returns the Shadow-Tip Distance (dsh) as detailed in
Becker et al.(2015).
The input angles are assumed to be in radians.
This is defined as the distance between the tips of the shadows
in the ... | 5aef1c9d7ffeb3e8534568a53cf537d26d97324a | 709,740 |
from typing import Optional
def convert_postgres_array_as_string_to_list(array_as_string: str) -> Optional[list]:
"""
Postgres arrays are stored in CSVs as strings. Elasticsearch is able to handle lists of items, but needs to
be passed a list instead of a string. In the case of an empty array, ret... | cc64fe8e0cc765624f80abc3900985a443f76792 | 709,749 |
import functools
import logging
def disable_log_warning(fun):
"""Temporarily set FTP server's logging level to ERROR."""
@functools.wraps(fun)
def wrapper(self, *args, **kwargs):
logger = logging.getLogger('pyftpdlib')
level = logger.getEffectiveLevel()
logger.setLevel(logging.ERRO... | 6990a2a1a60ea5a24e4d3ac5c5e7fbf443825e48 | 709,752 |
import json
def read_json(file_name):
"""Read json from file."""
with open(file_name) as f:
return json.load(f) | 2eccab7dddb1c1038de737879c465f293a00e5de | 709,758 |
def _decode_end(_fp):
"""Decode the end tag, which has no data in the file, returning 0.
:type _fp: A binary `file object`
:rtype: int
"""
return 0 | 5e8da3585dda0b9c3c7cd428b7e1606e585e15c6 | 709,759 |
def get_camelcase_name_chunks(name):
"""
Given a name, get its parts.
E.g: maxCount -> ["max", "count"]
"""
out = []
out_str = ""
for c in name:
if c.isupper():
if out_str:
out.append(out_str)
out_str = c.lower()
else:
out_s... | 134a8b1d98af35f185b37c999fbf499d18bf76c5 | 709,760 |
import json
def get_node_to_srn_mapping(match_config_filename):
"""
Returns the node-to-srn map from match_conf.json
"""
with open(match_config_filename) as config_file:
config_json = json.loads(config_file.read())
if "node_to_srn_mapping" in config_json:
return config_j... | 37bf2f266f4e5163cc4d6e9290a8eaf17e220cd3 | 709,765 |
def nest_dictionary(flat_dict, separator):
""" Nests a given flat dictionary.
Nested keys are created by splitting given keys around the `separator`.
"""
nested_dict = {}
for key, val in flat_dict.items():
split_key = key.split(separator)
act_dict = nested_dict
final_key = ... | f5b8649d916055fa5911fd1f80a8532e5dbee274 | 709,766 |
def list_a_minus_b(list1, list2):
"""Given two lists, A and B, returns A-B."""
return filter(lambda x: x not in list2, list1) | 8fbac6452077ef7cf73e0625303822a35d0869c3 | 709,767 |
def tempo_para_percorrer_uma_distancia(distancia, velocidade):
""" Recebe uma distância e a velocidade de movimentação, e retorna
as horas que seriam gastas para percorrer em linha reta"""
horas = distancia / velocidade
return round(horas,2) | e7754e87e010988284a6f89497bb1c5582ea0e85 | 709,773 |
def find_last_index(l, x):
"""Returns the last index of element x within the list l"""
for idx in reversed(range(len(l))):
if l[idx] == x:
return idx
raise ValueError("'{}' is not in list".format(x)) | f787b26dd6c06507380bf2e336a58887d1f1f7ea | 709,774 |
def _CheckUploadStatus(status_code):
"""Validates that HTTP status for upload is 2xx."""
return status_code / 100 == 2 | d799797af012e46945cf413ff54d2ee946d364ba | 709,776 |
import random
def pick_op(r, maxr, w, maxw):
"""Choose a read or a write operation"""
if r == maxr or random.random() >= float(w) / maxw:
return "write"
else:
return "read" | a45f53bf12538412b46f78e2c076966c26cf61ac | 709,779 |
def min_index(array, i, j):
"""Pomocna funkce pro razeni vyberem. Vrati index nejmensiho prvku
v poli 'array' mezi 'i' a 'j'-1.
"""
index = i
for k in range(i, j):
if array[k] < array[index]:
index = k
return index | 4c59362fac2e918ba5a0dfe9f6f1670b3e95d68c | 709,782 |
def average_precision(gt, pred):
"""
Computes the average precision.
This function computes the average prescision at k between two lists of
items.
Parameters
----------
gt: set
A set of ground-truth elements (order doesn't matter)
pred: list
A list of predicted elements (order does mat... | ca265471d073b6a0c7543e24ef0ba4f872737997 | 709,784 |
def Flatten(matrix):
"""Flattens a 2d array 'matrix' to an array."""
array = []
for a in matrix:
array += a
return array | 00389b4dd295274d8081331d6ae78f233f0b5b59 | 709,790 |
def escape_name(name):
"""Escape sensor and request names to be valid Python identifiers."""
return name.replace('.', '_').replace('-', '_') | 856b8fe709e216e027f5ab085dcab91604c93c2e | 709,792 |
def multiset_counter(mset):
"""
Return the sum of occurences of elements present in a token ids multiset,
aka. the multiset cardinality.
"""
return sum(mset.values()) | 36885abd5bf666aa6c77a262a647c227e46d2e88 | 709,793 |
def lengthenFEN(fen):
"""Lengthen FEN to 71-character form (ex. '3p2Q' becomes '111p11Q')"""
return fen.replace('8','11111111').replace('7','1111111') \
.replace('6','111111').replace('5','11111') \
.replace('4','1111').replace('3','111').replace('2','11') | f49cdf8ad6919fbaaad1abc83e24b1a33a3ed3f8 | 709,794 |
def get_list_of_encodings() -> list:
"""
Get a list of all implemented encodings.
! Adapt if new encoding is added !
:return: List of all possible encodings
"""
return ['raw', '012', 'onehot', '101'] | 6e0749eb45f85afe4e5c7414e4d23e67335ba2b5 | 709,799 |
def region_to_bin(chr_start_bin, bin_size, chr, start):
"""Translate genomic region to Cooler bin idx.
Parameters:
----------
chr_start_bin : dict
Dictionary translating chromosome id to bin start index
bin_size : int
Size of the bin
chr : str
Chromosome
start : int
... | f17b132048b0ceb4bbf2a87b77327d0d63b3fd64 | 709,800 |
def word_distance(word1, word2):
"""Computes the number of differences between two words.
word1, word2: strings
Returns: integer
"""
assert len(word1) == len(word2)
count = 0
for c1, c2 in zip(word1, word2):
if c1 != c2:
count += 1
return count | b3279744c628f3adc05a28d9ab7cc520744b540c | 709,803 |
def CheckVPythonSpec(input_api, output_api, file_filter=None):
"""Validates any changed .vpython files with vpython verification tool.
Args:
input_api: Bag of input related interfaces.
output_api: Bag of output related interfaces.
file_filter: Custom function that takes a path (relative to client root)... | d6e888b5ce6fec4bbdb35452b3c0572702430c06 | 709,804 |
def convertInt(s):
"""Tells if a string can be converted to int and converts it
Args:
s : str
Returns:
s : str
Standardized token 'INT' if s can be turned to an int, s otherwise
"""
try:
int(s)
return "INT"
except:
return s | a0eae31b69d4efcf8f8595e745316ea8622e24b3 | 709,809 |
import torch
def pairwise_distance(A, B):
"""
Compute distance between points in A and points in B
:param A: (m,n) -m points, each of n dimension. Every row vector is a point, denoted as A(i).
:param B: (k,n) -k points, each of n dimension. Every row vector is a point, denoted as B(j).
:return: ... | 2142b94f91f9e762d1a8b134fdda4789c564455d | 709,810 |
def coerce(from_, to, **to_kwargs):
"""
A preprocessing decorator that coerces inputs of a given type by passing
them to a callable.
Parameters
----------
from : type or tuple or types
Inputs types on which to call ``to``.
to : function
Coercion function to call on inputs.
... | 61ccce8b9ffbec3e76aa9e78face469add28437e | 709,817 |
import configparser
def parse_config_to_dict(cfg_file, section):
""" Reads config file and returns a dict of parameters.
Args:
cfg_file: <String> path to the configuration ini-file
section: <String> section of the configuration file to read
Returns:
cfg: <dict> configuration param... | 021e3594f3130e502934379c0f5c1ecea228017b | 709,820 |
import math
def mag_inc(x, y, z):
"""
Given *x* (north intensity), *y* (east intensity), and *z*
(vertical intensity) all in [nT], return the magnetic inclincation
angle [deg].
"""
h = math.sqrt(x**2 + y**2)
return math.degrees(math.atan2(z, h)) | f4036358625dd9d032936afc373e53bef7c1e6e1 | 709,825 |
def _parse_disambiguate(disambiguatestatsfilename):
"""Parse disambiguation stats from given file.
"""
disambig_stats = [-1, -1, -1]
with open(disambiguatestatsfilename, "r") as in_handle:
header = in_handle.readline().strip().split("\t")
if header == ['sample', 'unique species A pairs',... | bb05ec857181f032ae9c0916b4364b772ff7c412 | 709,826 |
def clean_vigenere(text):
"""Convert text to a form compatible with the preconditions imposed by Vigenere cipher."""
return ''.join(ch for ch in text.upper() if ch.isupper()) | d7c3fc656ede6d07d6e9bac84a051581364c63a0 | 709,827 |
def f_score(r: float, p: float, b: int = 1):
"""
Calculate f-measure from recall and precision.
Args:
r: recall score
p: precision score
b: weight of precision in harmonic mean
Returns:
val: value of f-measure
"""
try:
val = (1 + b ** 2) * (p * r) / (b *... | d12af20e30fd80cb31b2cc119d5ea79ce2507c4b | 709,829 |
def role_generator(role):
"""Closure function returning a role function."""
return lambda *args, **kwargs: role.run(*args, **kwargs) | 35dd1a54cb53a6435633c39608413c2d0b9fe841 | 709,831 |
def identity_show(client, resource_group_name, account_name):
"""
Show the identity for Azure Cognitive Services account.
"""
sa = client.get(resource_group_name, account_name)
return sa.identity if sa.identity else {} | 19018c895f3fdf0b2b79788547bf80a400724336 | 709,835 |
import math
def get_angle(p1, p2):
"""Get the angle between two points."""
return math.atan2(p2[1] - p1[1], p2[0] - p1[0]) | a29ea1ed74a6c071cf314d1c38c6e2f920bd1c3a | 709,836 |
def simulation_test(**kwargs):
"""Decorate a unit test and mark it as a simulation test.
The arguments provided to this decorator will be passed to
:py:meth:`~reviewbot.tools.testing.testcases.BaseToolTestCase
.setup_simulation_test`.
Args:
**kwargs (dict):
Keyword arguments to... | 56aa51374e66bb765bfc3d4da51e3254d06c0b55 | 709,839 |
def region_filter(annos, annotation):
"""filter for Region annotations.
The 'time' parameter can match either 'time' or 'timeEnd' parameters.
"""
result = []
for anno in annos:
time = annotation.get("time")
timeEnd = annotation.get("timeEnd")
for key in ['text', 'tags']:
... | 3ca4c6ba39d44370b3022f5eb17a25e0e1c9f056 | 709,840 |
def social_bonus_count(user, count):
"""Returns True if the number of social bonus the user received equals to count."""
return user.actionmember_set.filter(social_bonus_awarded=True).count() >= count | b2469833f315410df266cd0a9b36933edb1f9ac6 | 709,842 |
def read_labels(labels_path):
"""Reads list of labels from a file"""
with open(labels_path, 'rb') as f:
return [w.strip() for w in f.readlines()] | 3ebc61c76dd1ae83b73aa8b77584661c08a51321 | 709,844 |
def _gcs_uri_rewriter(raw_uri):
"""Rewrite GCS file paths as required by the rewrite_uris method.
The GCS rewriter performs no operations on the raw_path and simply returns
it as the normalized URI. The docker path has the gs:// prefix replaced
with gs/ so that it can be mounted inside a docker image.
Args:... | 6e476860cb175dd2936cc0c080d3be1d09e04b77 | 709,845 |
def remove_apostrophe(text):
"""Remove apostrophes from text"""
return text.replace("'", " ") | c7d918e56646a247564a639462c4f4d26bb27fc4 | 709,846 |
def generate_initials(text):
"""
Extract initials from a string
Args:
text(str): The string to extract initials from
Returns:
str: The initials extracted from the string
"""
if not text:
return None
text = text.strip()
if text:
split_text = text.split(" ... | 709e53392c790585588da25290a80ab2d19309f8 | 709,847 |
def part_allocation_count(build, part, *args, **kwargs):
""" Return the total number of <part> allocated to <build> """
return build.getAllocatedQuantity(part) | 84c94ca4e1b1006e293851189d17f63fc992b420 | 709,848 |
def __parse_sql(sql_rows):
"""
Parse sqlite3 databse output. Modify this function if you have a different
database setup. Helper function for sql_get().
Parameters:
sql_rows (str): output from SQL SELECT query.
Returns:
dict
"""
column_names... | 09c61da81af069709dd020b8643425c4c6964137 | 709,850 |
import json
def load_default_data() -> dict[str, str]:
"""Finds and opens a .json file with streamer data.
Reads from the file and assigns the data to streamer_list.
Args:
None
Returns:
A dict mapping keys (Twitch usernames) to their corresponding URLs.
Each row is repre... | bfeef64922fb4144228e031b9287c06525c4254d | 709,851 |
def get_value_key(generator, name):
"""
Return a key for the given generator and name pair.
If name None, no key is generated.
"""
if name is not None:
return f"{generator}+{name}"
return None | 0ad630299b00a23d029ea15543982125b792ad53 | 709,852 |
def int_to_bigint(value):
"""Convert integers larger than 64 bits to bytearray
Smaller integers are left alone
"""
if value.bit_length() > 63:
return value.to_bytes((value.bit_length() + 9) // 8, 'little', signed=True)
return value | 0f2d64887dc15d1902b8e10b0257a187ed75187f | 709,854 |
def convert_where_clause(clause: dict) -> str:
"""
Convert a dictionary of clauses to a string for use in a query
Parameters
----------
clause : dict
Dictionary of clauses
Returns
-------
str
A string representation of the clauses
"""
out = "{"
for key in c... | 8b135c799df8d16c116e6a5282679ba43a054684 | 709,863 |
def truncate_string(string: str, max_length: int) -> str:
"""
Truncate a string to a specified maximum length.
:param string: String to truncate.
:param max_length: Maximum length of the output string.
:return: Possibly shortened string.
"""
if len(string) <= max_length:
return strin... | c7d159feadacae5a692b1f4d95da47a25dd67c16 | 709,864 |
def clamp(minVal, val, maxVal):
"""Clamp a `val` to be no lower than `minVal`, and no higher than `maxVal`."""
return max(minVal, min(maxVal, val)) | 004b9a393e69ca30f925da4cb18a8f93f12aa4ef | 709,868 |
def notNone(arg,default=None):
""" Returns arg if not None, else returns default. """
return [arg,default][arg is None] | 71e6012db54b605883491efdc389448931f418d0 | 709,872 |
import hashlib
def calculate_hash(filepath, hash_name):
"""Calculate the hash of a file. The available hashes are given by the hashlib module. The available hashes can be listed with hashlib.algorithms_available."""
hash_name = hash_name.lower()
if not hasattr(hashlib, hash_name):
raise Exception... | 975fe0a2a4443ca3abc67ed950fb7200409f2497 | 709,878 |
def deep_copy(obj):
"""Make deep copy of VTK object."""
copy = obj.NewInstance()
copy.DeepCopy(obj)
return copy | c00c4ff44dad5c0c018152f489955f08e633f5ed | 709,880 |
def matrix2list(mat):
"""Create list of lists from blender Matrix type."""
return list(map(list, list(mat))) | 9b4b598eb33e4d709e15fd826f23d06653659318 | 709,890 |
def get_height(img):
"""
Returns the number of rows in the image
"""
return len(img) | 765babc9fbc1468ef5045fa925843934462a3d32 | 709,893 |
def sum_squares(n):
"""
Returns: sum of squares from 1 to n-1
Example: sum_squares(5) is 1+4+9+16 = 30
Parameter n: The number of steps
Precondition: n is an int > 0
"""
# Accumulator
total = 0
for x in range(n):
total = total + x*x
return total | 669a5aa03a9d9a9ffe74e48571250ffa38a7d319 | 709,895 |
def save(self, fname="", ext="", slab="", **kwargs):
"""Saves all current database information.
APDL Command: SAVE
Parameters
----------
fname
File name and directory path (248 characters maximum,
including the characters needed for the directory path).
An unspecified direc... | ddc79dc0f54e32d6cd96e115ad9842c1689c17b1 | 709,900 |
def get_dict_or_generate(dictionary, key, generator):
"""Get value from dict or generate one using a function on the key"""
if key in dictionary:
return dictionary[key]
value = generator(key)
dictionary[key] = value
return value | e31cd2b6661cf45e5345ce57d1e628174e6fd732 | 709,902 |
import random
def get_random_instance() -> random.Random:
"""
Returns the Random instance in the random module level.
"""
return random._inst | ee66055275153ce8c3eae67eade6e32e50fe1d79 | 709,904 |
import cgitb
def FormatException(exc_info):
"""Gets information from exception info tuple.
Args:
exc_info: exception info tuple (type, value, traceback)
Returns:
exception description in a list - wsgi application response format.
"""
return [cgitb.handler(exc_info)] | 733c2170a08f9880f8c191c1c6a52ee1ab455b7f | 709,905 |
def get_smallerI(x, i):
"""Return true if string x is smaller or equal to i. """
if len(x) <= i:
return True
else:
return False | 1588ef998f4914aa943a063546112766060a9cbf | 709,908 |
def unfold(raw_log_line):
"""Take a raw syslog line and unfold all the multiple levels of
newline-escaping that have been inflicted on it by various things.
Things that got python-repr()-ized, have '\n' sequences in them.
Syslog itself looks like it uses #012.
"""
lines = raw_log_line \
... | 9e23bdd82ac15086468a383a1ef98989aceee25e | 709,909 |
from datetime import datetime
def ts(timestamp_string: str):
"""
Convert a DataFrame show output-style timestamp string into a datetime value
which will marshall to a Hive/Spark TimestampType
:param timestamp_string: A timestamp string in "YYYY-MM-DD HH:MM:SS" format
:return: A datetime object
... | 1902e75ab70c7869686e3a374b22fa80a6dfcf1a | 709,911 |
def nl_to_break( text ):
"""
Text may have newlines, which we want to convert to <br />
when formatting for HTML display
"""
text=text.replace("<", "<") # To avoid HTML insertion
text=text.replace("\r", "")
text=text.replace("\n", "<br />")
return text | d2baf1c19fae686ae2c4571416b4cad8be065474 | 709,912 |
import requests
import logging
def get_page_state(url):
"""
Checks page's current state by sending HTTP HEAD request
:param url: Request URL
:return: ("ok", return_code: int) if request successful,
("error", return_code: int) if error response code,
(None, error_message: str)... | f7b7db656968bed5e5e7d332725e4d4707f2b14b | 709,913 |
def unique(list_, key=lambda x: x):
"""efficient function to uniquify a list preserving item order"""
seen = set()
result = []
for item in list_:
seenkey = key(item)
if seenkey in seen:
continue
seen.add(seenkey)
result.append(item)
return result | 57c82081d92db74a7cbad15262333053a2acd3a7 | 709,914 |
import random
def weight(collection):
"""Choose an element from a dict based on its weight and return its key.
Parameters:
- collection (dict): dict of elements with weights as values.
Returns:
string: key of the chosen element.
"""
# 1. Get sum of weights
weight_sum = s... | 383ddadd4a47fb9ac7be0292ecc079fcc59c4481 | 709,917 |
from typing import List
def make_matrix(points: List[float], degree: int) -> List[List[float]]:
"""Return a nested list representation of a matrix consisting of the basis
elements of the polynomial of degree n, evaluated at each of the points.
In other words, each row consists of 1, x, x^2, ..., x^n, whe... | d8fbea3a0f9536cb681b001a852b07ac7b17f6c2 | 709,918 |
def adjust_seconds_fr(samples_per_channel_in_frame,fs,seconds_fr,num_frame):
"""
Get the timestamp for the first sample in this frame.
Parameters
----------
samples_per_channel_in_frame : int
number of sample components per channel.
fs : int or float
sampling frequency.
... | a19775db3ebcdbe66b50c30bc531e2980ca10082 | 709,919 |
def is_success(msg):
"""
Whether message is success
:param msg:
:return:
"""
return msg['status'] == 'success' | 43ecbf3c7ac8d03ce92ab059e7ec902e51505d0a | 709,921 |
def list_strip_comments(list_item: list, comment_denominator: str = '#') -> list:
"""
Strips all items which are comments from a list.
:param list_item: The list object to be stripped of comments.
:param comment_denominator: The character with which comment lines start with.
:return list: A cleaned... | e5dd6e0c34a1d91586e12e5c39a3a5413746f731 | 709,922 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.