content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import json
def get_credentials(credentials_file):
"""Gets credentials into a dict.
Args:
credentials_file (str): path to the credentials file,
or the Python dictionary containing the contents thereof.
Returns:
credentials (dict): the credentials as a dictionary.
"""
... | 7b9a45ceaf87154f0eb637395e693d418230304d | 581,951 |
def dump_datetime(datetime_obj):
"""convert datetime object to string format"""
if datetime_obj is None:
return None
return datetime_obj.strftime("%Y-%m-%dT%H:%M:%SZ") | 9e61aaf8354fe4c803b33e1d6f2a2d70769410f4 | 581,952 |
from typing import List
def length_of_longest_substring(arr: List[int], k: int) -> int:
"""
This problem follows the Sliding Window pattern and is quite similar to Longest Substring with same Letters after
Replacement. The only difference is that, in the problem, we only have two characters (1s and 0s) in... | fa242a3e28cdd7ce38e898cbe25dc2dd4a3f3776 | 581,954 |
def format_manifest_entry(entry):
"""Convert a manifest_entry instance to its final text representation."""
return entry.target + '=' + entry.source | ab8a0375f2a4424aa68cdc8cd188b41582b34fd5 | 581,957 |
import random
def some_simple_data(length=1000000):
"""Generate random array of integers"""
data = list(range(length))
random.shuffle(data)
return data | c12a22a2e226e80176c428816d9162d0d2cead1b | 581,958 |
def hex_cipher_encryptor(message: str) -> str:
"""Encrypts a given message using a Hex Cipher (converts characters to their hexadecimal equivalents).
Args:
message (str): Message to be encrypted.
Returns:
encrypted_message (str): Encrypted message.
"""
encrypted_message = "".join([... | 88fc70df52f565374c7cc9e93e3cd945518d42c1 | 581,959 |
def get_github_url(failed_sha, passed_sha, repo):
"""
Creates the github diff url for a given failed_sha, passed_sha, and repo
"""
# Generates the 2-dot diff url for each artifact
url = 'https://github.com/{}/compare/{}..{}'.format(repo, failed_sha, passed_sha)
return url | 1373bd24b28880c2b30ee38debaae49c85cdc92c | 581,960 |
from typing import Callable
from typing import Any
from typing import Type
def dictWithFactory(factory: Callable[[Any], Any]) -> Type:
"""
Create a dictionary class with a default factory function.
Contrary to `collections.defaultdict`, the factory takes
the missing key as input parameter.
Parame... | 06ccefef338eeef8fafb734a2a9bbf9184521729 | 581,961 |
def extract_comment(content):
"""Extracts file level comment."""
out = []
for line in content.splitlines(True):
if line.startswith('#'):
out.append(line)
else:
break
return ''.join(out) | 124f823f88f065aa054b01ac4dcdec6896f1fcb5 | 581,965 |
def generate_bands(low, high, increment):
"""Returns a list of bands within low-high based on the increment.
If low is not at an even increment (e.g., 1378), the first band is between
low and the next even increment, e.g., [1378, 1500].
If low is 0, it will be used as is. Otherwise, 1 will be added to... | eb3d68320c713b26f995b8e78cd2e0b7d3fcd8f6 | 581,967 |
def boolize(obj):
""" If obj is a str, returns True if obj is 'True', 'true', or a string
representing a non-zero integer. If obj is not a str, returns a direct
conversion to bool.
"""
if isinstance(obj, str):
if obj.isdigit():
obj = int(obj)
else:
return obj... | 901b285af6fb920269f375d6d0f0b6c7dbd5e110 | 581,971 |
def au_theater(name):
"""
Add a preposition and article to a theater name to make it locative
"""
if not name:
return ''
loc = {
'Théâtre': 'au ',
'Th.': 'au ',
'Académie': "à l'",
'Cirque': 'au ',
'Fêtes': 'aux ',
'Cour': 'à la ',
'Opé... | d2a0d6e35f7e4d558c97a583b1780f1bb3d56c09 | 581,974 |
def call_activation(x, foo=None):
""" return result of an activation function `foo` on the input `x`, return `x` if `foo is None` """
if foo is None:
return x
return foo(x) | 79591561c5d763a271ec4996be2f5c3c7ab51260 | 581,975 |
import functools
import warnings
def deprecated(reason):
"""
This is a decorator which can be used to mark function as deprecated. It
will result in a warning being emitted when the function is used.
:param reason: a reason as a string
:return: decorated function
"""
def deprecated_decora... | 1b1644fbfad94561bce78c47e8fc2f294f99335f | 581,977 |
def AllMentionedVariables(x, dive_in_combines=False):
"""Extracting all variables mentioned in an expression."""
r = []
if isinstance(x, dict) and 'variable' in x:
r.append(x['variable']['var_name'])
if isinstance(x, list):
for v in x:
r.extend(AllMentionedVariables(v, dive_in_combines))
if isin... | 4ffe642f3676fd1323084fe044d203b4265a80ed | 581,982 |
def strip_ids(ids, ids_to_strip):
"""Strip ids_to_strip from the end ids."""
ids = list(ids)
while ids and ids[-1] in ids_to_strip:
ids.pop()
return ids | f6aabe7cc4875889054ee8eb3e5382e3e8647a3f | 581,987 |
def shift_letter(letter, shift):
"""Shift letter by shift number."""
base = ord('a')
num_letters_in_alphabet = 26
return chr(base + (ord(letter) - base + shift) % num_letters_in_alphabet) | dac4ecf8f0d67cdfb020dfb2aa494c24c6aa5207 | 581,988 |
from typing import List
def reformat_span_idxs(span_idx_list: List[List[int]]) -> list:
"""
Reformat span idxs to look like [0, [start_idx, end_idx]]
"""
span_idxs = [x[0] for x in span_idx_list]
start_idx = min(span_idxs)
end_idx = max(span_idxs)
return [0, [start_idx, end_idx]] | 27027754586438877aed4c9d493c020e23a077e9 | 581,989 |
import hashlib
def sha256_checksum(filename, block_size=65536):
"""Computes sha256 for given file"""
sha256 = hashlib.sha256()
with open(filename, 'rb') as f:
for block in iter(lambda: f.read(block_size), b''):
sha256.update(block)
return sha256.hexdigest() | 9bb745672376e917b574095db7680fa0eeacb266 | 581,992 |
def update_toestand(A, x, resistent=[]):
"""
Voor een gegeven verbindingsmatrix A en een binaire toestandsvector x
(0: vatbaar/resitent, 1: geinfecteerd) op tijdstip t, bereken de toestandsvector op
tijdstip t+1. Optioneel kan je een lijst met indices van resistente individuen
geven.
"""
# u... | 20ce9e50f6ebf0ca5d26c9e0ca3c789e81a94dee | 582,003 |
import torch
def to_Boolean(tensor):
"""Transform to Boolean tensor. For PyTorch version >= 1.2, use bool(). Otherwise use byte()"""
version = torch.__version__
version = eval(".".join(version.split(".")[:-1]))
if version >= 1.2:
return tensor.bool()
else:
return tensor.byte() | f39d1897043fa7c69ea33d6e240d4b79330f94a1 | 582,010 |
def webhook_request(
response_id,
session,
intent_id,
text,
title,
subtitle,
image_url,
buttons,
payload,
quick_replies
):
"""Return a sample WebhookRequest dictionary."""
project_id = 'PROJECT_ID'
return {
'responseId': response_id,
'queryResult': {
... | e65c637b45e65ce2b971fa2c1d0074b335f90a83 | 582,013 |
import inspect
def get_class_path(instance):
"""
Converts an instance or `class` to a class path string.
:param instance:
An instance or class.
:return:
The stringified class path.
"""
return '{}.{}'.format(
instance.__module__,
instance.__name__ if inspect.isc... | 54539ac727b09b73cca609973305385fccaeafa0 | 582,016 |
def add_iscsi_auth_group(client, tag, secrets=None):
"""Add authentication group for CHAP authentication.
Args:
tag: Authentication group tag (unique, integer > 0).
secrets: Array of secrets objects (optional).
Returns:
True or False
"""
params = {'tag': tag}
if secret... | aa169099018d9efd5721445635b2fb21d24bf2c1 | 582,019 |
def get_distance_and_orientation (line, cols):
"""return distance and orientation, given a list representing a line from the pairs input file and a ColIndices object """
distance = int(line[cols.pos2]) - int(line[cols.pos1])
# distance will always be > 0 for upper triangle, but in case it is not true.
... | f340645da6b43e990c65064e0c2480d6f1406dcb | 582,020 |
def get_selected_runs(sub, ref):
"""
Returns the positions in ref, which are covered by the subsequence sub.
Returns None if sub is not a subsequence of ref
"""
indices = []
sub_pos = 0
for ref_pos in range(len(ref)):
if sub_pos >= len(sub):
break
if ref[ref_pos] ... | 095cdca83579c6965ea91619e1e9dc47ea78d6f2 | 582,022 |
from typing import Iterable
def tversky(
seq1: Iterable[str], seq2: Iterable[str], *, alpha: float = 1.0, beta: float = 1.0
) -> float:
"""
Measure the similarity between two sequences of strings as sets
using the (symmetric) Tversky index, which is a generalization of
Jaccard (``alpha=0.5, beta=2... | a99363adbaef5bc11a07ea381c1b41dd49ef0b64 | 582,024 |
def SizeReserveUernPremEnd(t):
"""Unearned reserve per policy: End of period"""
return 0 | cf95359100d497ed7c02b72cf8087143e71359ea | 582,027 |
def sift3_distance(s_1, s_2, max_offset=5):
"""Calculate string distance
See http://siderite.blogspot.com/2007/04/super-fast-and-accurate-string-\
distance.html for background. This is a port of sift3Distance from mailcheck.js
rather than the Python code from https://gist.github.com/fjorgemota/3067867
... | f85f983c6cbd9912a75cedf9f6a7555a5de13fc9 | 582,028 |
import re
import warnings
def is_re(s:str,
strict:bool = False) -> bool:
"""checks if `s` is a valid regex.
Parameters
----------
s: str
parameter to check for being a valid regex
strict: bool
if strict mode used, anything except regex compile error will throw exception. el... | 3e2909bdfe03aa8e768176b11d26e8b7322829ce | 582,030 |
import re
def search_re_in_list(out, l):
""" Search the regular expression 'l' in each line of
the given string list 'out' and return the line's index
when successful.
"""
for idx, o in enumerate(out):
m = re.search(l, o)
if m:
return idx
return None | 9d0c8da2c9b37b6421204a71b7f2f65718a33c64 | 582,033 |
def lineno2tokenno(dat,lineno):
"""
This routine takes a line number and returns the token number of the
token corresponding to the first token on that line.
"""
nlines = len(dat.line2token)
if lineno == 0:
tokenno = 0
elif lineno > nlines:
tokenno = len(dat.token)
t... | 7106b1d965cae5a59d9254e21fc6cdc12c88d1bd | 582,034 |
def check_ignore(source):
""" This function checks if a file is on the ignore list """
for f in ["interrogate_module.cpp", "interrogate_wrapper.cpp"]:
if f.lower() in source.lower():
return False
return True | de7066bbf9f3e61fcfb21c630e36a6e2df9e8792 | 582,035 |
def version_string(static_version, commit_hash, build_number):
"""
Format a full version string version.build_number~commit_hash.
:param static_version: manually managed (static) version part, e.g. 0.1.5
:param commit_hash: commit hash (optional)
:param build_number: build number (doesn't have to be... | c02e73a3d1b3f21b96eda632360c1a557f98699b | 582,036 |
def get_common_start_stop_times(neo_objects):
"""
Extracts the `t_start`and the `t_stop` from the input neo objects.
If a single neo object is given, its `t_start` and `t_stop` is returned.
Otherwise, the aligned times are returned: the maximal `t_start` and
minimal `t_stop` across `neo_objects`.
... | d986a9b54b7f067f4f3c25860b22d4cb9443e961 | 582,038 |
def pathinput(hint: str, default_return: str):
"""
A simple path controlling function for easier file path input.
Args:
hint: Hint when inputting.
default_return: When input is nothing (or pressed Enter when inputting), the default result str to be returned.
Returns: The expected file ... | 56fe5c4e8a39db7a11c73af09e64726e7ce56511 | 582,042 |
def percent_delta(old_score, new_score):
"""Calculates the percent change between two scores.
"""
return float(new_score - old_score) / float(old_score) | ceaf4e0eecb436818c12a52c32fb1db7f88ca102 | 582,044 |
def encode_color(color, n_bits):
"""
If color is given as boolean, interpret it as maximally on or totally off.
Otherwise check whether it fits within the number of bits.
"""
if isinstance(color, bool):
return (2 ** n_bits - 1) * color
elif 0 <= color < 2 ** n_bits:
return color
... | eb8c6baed49bb1e5442adcbc4a03ab2556e7c083 | 582,045 |
def test_fail_msg(exp, test_name, miner_name, matched=0):
"""
Formats message string for false test assertion.
- exp:
Expected number of events (to be matched).
- test_name:
Name of running test.
- miner_name:
Name of miner function.
- matched:... | d6941d68ee7363c2483019da72abcec6fa3d1347 | 582,046 |
def _mesh_export_format_from_filename(filename):
"""
Determine a mesh output format based on a file name.
Determine a mesh output format based on a file name. This inspects the file extension.
Parameters
----------
filename: string
A file name, may start with a full path. Examples: 'br... | 7d044abf7a62e78fa9fc29aa4df63eff0c58480a | 582,047 |
def load_vocab_list(vocab_path, add_eos=True):
"""Load the vocab list from path."""
vocab_list = open(vocab_path).read().split()
if vocab_list[0] != 'eos' and add_eos:
vocab_list = ['eos'] + vocab_list
return vocab_list | 0486ea1413c3fb409e393d29ce276fc8e1acd184 | 582,049 |
def get_color_points(surface, color, bounds_rect=None, match_color=True):
"""Get all the points of a given color on the surface within the given
bounds.
If bounds_rect is None the full surface is checked.
If match_color is True, all points matching the color are returned,
otherwise all points n... | c8a0598a556a00fa28c38fb4558d99575f2aeb32 | 582,051 |
def truncate_text(text: str, limit: int = 256) -> str:
"""Truncate a given `text` if the `limit` is reached"""
if limit <= 0:
raise ValueError("limit must be greater than 0")
return text[:limit] + "..." if len(text) > limit else text | 53308f70123669ae7b66f94d225830c41abc2b82 | 582,058 |
import hmac
import hashlib
def generate_secure_signature(secret, expire):
"""Generate secure signature with specified secret and expiration timestamp.
:param secret: Secret Key.
:param expire: Expiration timestamp.
:return: str.
"""
k, m = secret, str(expire).encode('utf-8')
if not isin... | fe9555d7ab0d99b069992e1940b2e8764a4a8ac1 | 582,059 |
def create_optims_default(optim_cls, **optim_params):
"""
Function to create a optimizer dictionary
(in this case only one optimizer)
Parameters
----------
optim_cls :
Class implementing an optimization algorithm
**optim_params :
Additional keyword arguments (passed to the o... | faea2016078bdba2149bb4392f91e896d89901a6 | 582,061 |
def any_of(possibilities, to_add=''):
"""
Construct a regex representing "any of" the given possibilities
:param possibilities: list of strings representing different word possibilities
:param to_add: string to add at the beginning of each possibility (optional)
:return: string corresponding to rege... | fb2d84eb31c3c0cdd7b85094ac272777457b3718 | 582,065 |
def camel_lowercase(camel_string):
""" Convert camel string to lowercase. """
lowercase_string = camel_string[0].lower()
for s in camel_string[1:]:
if s.isupper():
lowercase_string += f'_{s.lower()}'
else:
lowercase_string += s
return lowercase_string | 5cf40ed60d974454a52c82d84b0381fc4d5bb35a | 582,069 |
def is_valid_email(email):
"""
Light validation on email address: require @ and at least one dot.
"""
return "@" in email and "." in email | 95a26ab20cc4c75b6f241f8f4abfc5e902cee6dd | 582,070 |
def get_COMPAS_vars(compas_file, group, variables, mask=None):
"""Return a variable from the COMPAS output data
Parameters
----------
input_file : `hdf5 File`
COMPAS file
group : `str`
Group within COMPAS file
variables : `str` or `list`
List of column names to access in... | 822cd3d248ba591ddc74ea567a109c4541c46b6b | 582,073 |
from typing import List
import re
def strip_list(l: List[str]) -> List[str]:
"""Return a stripped copy of l.
Strip whitespace at the end of all lines, and strip all empty
lines from the end of the array.
"""
r = [] # type: List[str]
for s in l:
# Strip spaces at end of line
... | f4f5b8182e85020a3e8047537ba4ff9530c83f00 | 582,080 |
def dict_to_list(d):
"""Convert a dict whose keys are the ints 0..N-1 into a list of length
N such that l[x] == d[x]. In the process, check that the keys are
indeed such a range.
"""
l = [None]*len(d)
try:
for k, v in d.items():
l[k] = v
except IndexError:
raise... | 3bb878a9478fc60f3c5369e3df817aeabd13e491 | 582,087 |
def from20(digits: list[int], msb: int = 20, lsb: int = 5) -> float:
"""
Convert a sequence of 10 digits, 5 in the msb base and 5 in the lsb base,
into a float value.
>>> from math import isclose
>>> nlat_i = from20([4, 11, 5, 14, 14, 1, 1, 4, 4, 4])
>>> isclose(nlat_i, 91.286785, rel_tol=1E-6)... | d04cfc3ab3a0933d380c6e8b4f975c38f974d04b | 582,090 |
def midpoint(p1, p2, round = "down"):
"""
Get the midpoint between two integers. The round parameter must be
"up" or "down" in case of ties.
"""
if p1 <= p2:
smaller = p1
larger = p2
else:
smaller = p2
larger = p1
difference = larger-smaller
if difference%... | 474f1381aa4af1cb9fb4bd4df6e7bc87a055a811 | 582,091 |
from operator import eq
def in_(x, seq):
"""
Evaluates if x is in seq, avoiding issues such as these:
>>> s = pd.Series([1,2,3])
>>> with pytest.raises(ValueError):
>>> s in [None]
>>> assert not in_(s, [None])
>>> assert in_(s, [None, s])
"""
for s in seq:
if ... | f573725c4810cc3bae953166ca0859a5e30335d4 | 582,107 |
def geterr(obj):
"""
Returns false if there are no errors in a network response,
else a tuple of (code integer, description string)
"""
error = obj.get("error")
if not error:
return False
return (error["code"], error["description"]) | 5a45107f9cc391344b66797d805984dec5cad00a | 582,109 |
def isexact(x):
"""True if all components of x contain exactly one number.
For instance,
>>> isexact(interval(1, 2))
True
>>> isexact(interval([1], [2, 3]))
False
"""
return all(c.inf == c.sup for c in x) | 5c1da92123c7881a5d83bfc43429257aa7eeb696 | 582,112 |
def max_sequence(listeners, price):
"""
Compute the maximum earnings for a sequence of length 'length'.
An instance of the maximum subarray problem.
:param listeners: list of listeners for each break slot
:param price: price per break
:return: maximum profit
"""
best = 0
cur_... | 589cc5a7a64be8736e5d40c216f2d7ff13588418 | 582,113 |
def decode_ip_addr(address_int):
"""decodes a 32-bit int into IP octets (for DCC use)"""
ip_octets = []
if((address_int > 0xffffffff) or (address_int < 0)):
ip_octets = ["0","0","0","0"]
else:
ip_octets.append(str((address_int & 0xff000000) >> 24))
ip_octets.append(str((address_int & 0x00ff0000) >> 16))
ip_... | 74601a63771fc72d718665e7b9a8290e932d46da | 582,114 |
def html5_document(body_elements) -> str:
"""Return complete HTML5 document string."""
style = """
html {
font-family: sans-serif;
}
h2 {
margin-top: 2em;
}
h3 {
margin-bottom: 1px;
}
... | c5dc2b608d489715f1a944911b18110d27f6866b | 582,117 |
def get_block_number(row_index: int, column_index: int, k: int) -> int:
"""Retrieve the block number corresponding to the given row and column indices for a k-by-k block Sudoku puzzle
For example, block 0 in a k=3 Sudoku puzzle contains the indices (0,0), (0,1), (0,2), (1,0) ... (2,2)
:param row_index: ... | 00e2e52181ddc4dad5dc9d2a996f926f4c73e08a | 582,118 |
import copy
def shift_slits(tslits_dict, tilts_dict, waveimg, shift):
"""
Routine to shift slits in a tslits_dict. This routine is used to compensate for flexure.
Args:
tslits_dict (dict):
Dictionary containing slit boundaries and other info
shift (float):
Shift to ... | ef111a24cadc9fc25a0aaf0c8f7ce5daeda5f673 | 582,128 |
def _get_version_content_model_content_type(version):
"""
Returns a content type that describes the content
"""
# Otherwise, use the content type registered by the version
return version.content_type | 81d78a3c107b6925c61eed39060fcb448b181237 | 582,130 |
def eq_14_plume_temperature(
T_0: float,
g: float,
c_p_0_kJ_kg_K: float,
rho_0: float,
Q_dot_c_kW: float,
z: float,
z_0: float,
):
"""Equation 14 in Section 8.3.3 PD 7974-1:2019 calculates mean gas temperature along fire centre-line.
:param T_0: in K, amb... | aeee68292aef5506cad27d6b1c7274fcdad30e22 | 582,132 |
def solution(A):
"""Compute the maximum product of any triplet within a list.
Args:
A (list): A collection of N integers.
Returns:
int: The maximum pruduct that can be derived from A.
Complexity:
Time: O(N * log(N))
Space: O(N)
"""
if len(A) < 3:
r... | 55da6a6e579096acc175a6a50bfbcac30f62da31 | 582,133 |
def divisible_by_2(my_list=[]):
"""Find all multiples of 2 in a list."""
multiples = []
for i in range(len(my_list)):
if my_list[i] % 2 == 0:
multiples.append(True)
else:
multiples.append(False)
return (multiples) | b990fb36852d02cbffdd1919a6fc84178703c5ce | 582,136 |
def _is_curry_func(f):
"""
Checks if f is a toolz or cytoolz function by inspecting the available attributes.
Avoids explicit type checking to accommodate all versions of the curry fn.
"""
return hasattr(f, 'func') and hasattr(f, 'args') and hasattr(f, 'keywords') | 23fc93ade335a69345a14eb9640945bdbb5bcffa | 582,137 |
def _off_faces(faces):
"""
Return a string representing the faces in OFF format.
Parameters
----------
faces: numpy array of integers
A 2D array containing 3 vertex indices per face. Dimension is (m, 3) for m faces.
Returns
-------
string
The OFF format string for the f... | 5488ed221fabe329be876bf5914591a2fd18f2fc | 582,142 |
def trap_exception(e, f, default=None):
""" Call f(), trapping e, default to default (which might be callable) """
try: # pragma: no cover
return f()
except e: # pragma: no cover
if callable(default):
return default(e)
else:
return default | 167a6005288c5daf1eef4cef03946d0012bfd25f | 582,144 |
def _splice_comma_names(namelist):
""" Given a list of names, some of the names can be comma-separated lists.
Return a new list of single names (names in comma-separated lists are
spliced into the list).
"""
newlist = []
for name in namelist:
if ',' in name:
newlist.e... | 9af554a815997902d08c37ed116ba8678b25e7bc | 582,145 |
def bisect_right(data, target, lo, hi):
"""
Given a sorted array, returns the insertion position of target
If the value is already present, the insertion post is to the right of all of them
>>> bisect_right([1,1,2,3,4,5], 1, 0, 6)
2
>>> bisect_right([1,1,2,3,4,5], 0, 0, 6)
0
>>> bisect_r... | e089de79f8a5376490ba94a357d3b6486ea9104d | 582,147 |
def domain_concatenated_no4Gor4C(seq,seqs):
"""prevent G^4 and C^4 under concatenation"""
for altseq in seqs:
catseq = altseq+seq+altseq
if 'GGGG' in catseq:
# print '|GGGG# seq: %s altseq: %s|' % (seq,altseq)
return False
if 'CCCC' in catseq:
# prin... | ca4ab4dde841fbc07072ee55bd9c4b74cdf3011b | 582,150 |
from datetime import datetime
import time
def to_epoch(date_time):
"""
Convert datetime to epoch
:param date_time: datetime
:return: epoch
"""
pattern = '%Y-%m-%d %H:%M:%S'
earliest = datetime(1970, 1, 1, 0, 0, 0, 0)
if date_time is None:
date_time = str(datetime.now()).split... | b6d3e77fcf713980ac70e9920da65d422a6b8422 | 582,152 |
def offset(point, offset):
""" Offsets a point by an amount.
Equivalent to adding vectors.
"""
return tuple(map(sum, zip(point, offset))) | fc13ab3e5463b9128155be11d52119bc09b91248 | 582,156 |
def string_fix(string, encode='utf-8'):
"""
Fix the byte<->string problem in python 3.
This method converts anything is passed to it into a string. If it is
`bytes` also handle the decoding.
Parameters
----------
string: `str` or `bytes`
String to be checked or converted.
encod... | d658166dd3eac04609a28f39d00053304d4f2648 | 582,157 |
def get_module_names(thread):
"""
Returns a sequence of module names from the stack frames of this thread.
"""
def GetModuleName(i):
return thread.GetFrameAtIndex(
i).GetModule().GetFileSpec().GetFilename()
return list(map(GetModuleName, list(range(thread.GetNumFrames())))) | 101470cb441acf445c1d084d13698564d7d858a3 | 582,159 |
def _ConvertFormatToQmark(statement, args):
"""Replaces '%s' with '?'.
The server actually supports '?' for bind parameters, but the
MySQLdb implementation of PEP 249 uses '%s'. Most clients don't
bother checking the paramstyle member and just hardcode '%s' in
their statements. This function converts a for... | f7bf38a29a4daddfaffdbd06088256bda2e8d59e | 582,161 |
def get_str(tuple_obj):
"""
Return str list for tuple obj for logger.
:param tuple_obj: tuple obj
:return: string list
"""
str_list = list()
for item in tuple_obj:
str_list.append(str(item))
return str_list | eb4bcefd4800a5e0d03a39229c1130d33e5be683 | 582,162 |
def range_to_cost_linear(start: int, stop: int) -> float:
"""Return the length of the slice between `start` (inclusive) and `stop` (exclusive)."""
return float(stop - start) | 4d44fd1737c1e66a79f63acbff059850daa7bb55 | 582,163 |
def all_additional_output_names(experiment_proto):
"""Return all additional output names from an Experiment proto.
Args:
experiment_proto: selection_pb2.Experiment describing the experiment.
Returns:
List of strings in sorted order.
"""
names = [ao.name for ao in experiment_proto.additional_output]
... | fdff817f5ec7b0a876b389a8447fc6e5b0e3dae3 | 582,164 |
def decdeg2dms(dd):
""" Convert decimal degrees to deg,min,sec """
is_positive = dd >= 0
dd = abs(dd)
minutes, seconds = divmod(dd * 3600, 60)
degrees, minutes = divmod(minutes, 60)
degrees = degrees if is_positive else -degrees
return (degrees, minutes, seconds) | f369e4f17960238cbb070e6e000dbb24dcba9011 | 582,167 |
def available_plot_channels(plot):
"""
Return the channels+names of the channels that have views.
"""
available_channels = {}
for name,channel in plot.channels.items():
if plot.view_dict.has_key(channel):
available_channels[name]=channel
return available_channels | 603129c2a9ec072013ed6a46779b72b2294171d0 | 582,178 |
def count_matches(list, item):
"""
Return the number of occurrences of the given item in the given
list.
"""
if list == ():
return 0
else:
head, tail = list
if head == item:
return 1 + count_matches(tail, item)
else:
return count_matches(ta... | beaf23ee6d915a32fcb18326ac23fd705e10f94d | 582,181 |
def is_unknown_license(lic_key):
"""
Return True if a license key is for some lesser known or unknown license.
"""
return lic_key.startswith(('unknown', 'other-',)) or 'unknown' in lic_key | cb3a9446d556f85bc828a8dc24a4041ada7256af | 582,183 |
import hashlib
def hashfile(file_path, hasher=hashlib.md5(), blocksize=65536):
"""For verifying checksums of bigger files
From: http://stackoverflow.com/questions/3431825/generating-a-md5-checksum-of-a-file
:param file_path: full path to file to check
:type file_path: string or unicode
:param... | c0cbe3a29f27109bba34b61e1ac3aa265eabfb0e | 582,186 |
import re
def is_uuid4(x):
"""A little helper function - does the passed in string match a uuid4
pattern? Return true if it does match, false otherwise. Used to
replace random stock_id with the year and ID number.
- regex from: https://stackoverflow.com/questions/11384589
Arguments:
- `x`:... | dc65d23350df9ba8a0ecaf20454926c8b5157e9a | 582,187 |
def subsetlatlon(df, lat_range, lon_range):
"""Subsets df to rows where lat and lon fall into lat_range and lon_range
Args:
df: dataframe with columns 'lat' and 'lon'
lat_range: range of latitude values, as xrange
lon_range: range of longitude values, as xrange
Returns:
Subsett... | 6f2fdd6430a8de14e2ad58b87015f0efdb0bf253 | 582,189 |
def is_string_list(lst):
"""Return true if 'lst' is a list of strings, and false otherwise."""
return isinstance(lst, list) and all(isinstance(x, str) for x in lst) | aa59442b475e752b619a74b0b22a17acdebdffa1 | 582,190 |
import math
def calc_distance(pa, pb):
"""
Returns Euclidean distance.
"""
distance = math.sqrt((pa[0] - pb[0])**2.0 + (pa[1] - pb[1])**2.0)
return distance | 95fc8a9e322da8942ab2499a4fcee26be77ce74f | 582,192 |
def curPos(plyr,brdlyt):
"""
Finds current position of player.
:param plyr: Player object
:param brdlyt: Layout of board.
:return: The card at which the player is currently at.
"""
return brdlyt[plyr.position] | 48684623b6629d444bdfa10cd526dfef9659699c | 582,195 |
def str2floats(s):
"""Look for single float or comma-separated floats."""
return tuple(float(f) for f in s.split(',')) | 6ca865d214abe3304355ffcb1d0ea87471ad391f | 582,198 |
def toMicros(funits, unitsPerEM):
"""\
Convert funits into micros.
"""
return funits * 1000 / unitsPerEM | e1bb84f54abd70c39969e74b5bfd363161748219 | 582,202 |
import torch
def sample_diag_gauss(mean, std, generator=None, is_radial=False):
"""Get a sample from a multivariate Gaussian distribution with diagonal
covariance matrix.
Samples are produced using the reparametrization trick.
Note:
If ``is_radial`` is set to ``True``, samples will instead ... | c0f0c7232ba9ef6b6800510642fb603442eef334 | 582,203 |
import fnmatch
def _Matches(path, pattern_list):
"""Returns true if path matches any patten found in pattern_list.
Args:
path: A dot separated path to a package, class, method or variable
pattern_list: A list of wildcard patterns
Returns:
True if path matches any wildcard found in pattern_list.
... | 58ada15fe6218abe0bad33fd71e51622ea6a42fc | 582,204 |
def get_channels_from_values(values, header):
"""Create a dict ('channels') with channel-sorted values.
channels = dict(channel1_name: [channel1_val1, channel1_val2, ...],
channel2_name: [channel2_val1, channel2_val2, ...],
...)
(channels["Time"] is a spe... | ea8f684e1f61208273a5b204c4fe2341436ec680 | 582,205 |
import math
def get_char_distance_distribution(charset):
"""
Calculates the distribution of the distance between characters. VERY slow, to be used with @Memoized
for good performance (if only a predetermined set of charsets is needed)
:param charset: the charset as a string
:return: a (normalized... | 768fe1f5c2df432723e3cfc989f0c612fe4555dd | 582,206 |
from typing import Callable
import inspect
import functools
from typing import Any
def auto_init(old_init: Callable) -> Callable:
"""
auto_init is a decorator for an __init__ which uses setattr() to set values in __init__ based
on the signature of the __init__ function.
Check out this class:
... | 645c5b4ec54a8bfb499d012aa4dd1d0a65e4130f | 582,209 |
def num_applicants(driver):
"""
Grabs number of applicants from either the header of the
applicants-insights div, or within the applicants-table in the same
div element. Returns empty string if data is not available.
"""
# use two selectors since LI has two methods of showing number
# of a... | 5f523db06cc38f0033f6dbd30d8d1a03190c30b3 | 582,211 |
def gen_binding(name, signature):
"""
Generates a binding for a single method with the specified signature
"""
return """
{{-| {name}
-}}
{name} : {signature}
{name} = Native.Decimal.{name}
""".format(name=name, signature=signature) | 487a293953f634c7aaea3b157b5096fbab41a094 | 582,214 |
def split_full_metric(full_metric):
"""Splits a full metric name (split/name or task/split/label/name) into pieces"""
pieces = full_metric.split("/")
if len(pieces) == 2: # Single-task metric
split, name = pieces
return split, name
elif len(pieces) == 4: # Mmtl metric
task, pay... | cf9e4b862d7be8d7da4e5616c281223c82431409 | 582,220 |
def dup_index(s: list) -> dict:
"""Gets a list that might have duplicates and creates a dict with the list
items as keys and their index as values. Only return items that have duplicates.
"""
d = {}
for element in s:
# This could be easily done with a Numpy array
indices = [ind... | 27a055d9d37ff4088029d33adf79483dae9453f1 | 582,223 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.