content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def GetPlural(count):
"""Returns a plural 's' if count is not 1"""
return 's' if count != 1 else '' | 3ad7c44c27d15e02d5f6a3de2a08341da8778b01 | 53,912 |
def in_docker() -> bool:
"""
Check if the session is running inside a docker
.. code-block:: python
if in_docker():
print("OMG we are stock in a Docker ! Get me out of here !")
else:
print("We are safe")
Returns:
bool: True if inside a docker
"""
... | 24e976fc0d29d482a0fb8cb83a62ea4a4825654e | 53,916 |
import re
def extract_img_and_tag(entry_main, entry_tag):
"""
Extracts features about an article's main image (3) and tags (1) from the API dictionary
and returns them: 4 variables returned.
------
ARGUMENTS:
The API dictionary entries for the main image ('result->field->main') and tags ('resu... | d51c6d77c18ea85d03b0bc460c67abf483e610f3 | 53,924 |
import pytz
async def get_user_timezone(ctx, user):
"""
Returns a pytz.timezone for a user if set, returns None otherwise
"""
query = '''SELECT tz
FROM timezones
WHERE "user" = $1;'''
record = await ctx.bot.pool.fetchrow(query, user.id)
if record is None:
... | dec6f058902ffb097b5dadcc17f6debde45e4c20 | 53,927 |
def shift_series(s):
"""Produces a copy of the provided series shifted by one, starting with 0."""
s0 = s.copy()
s0 = s0.shift(1)
s0.iloc[0] = 0.0
return s0 | 5c8937de05da5087095600721f4ca9230a0e4296 | 53,929 |
import unicodedata
def slugify(value, replace_spaces=False):
"""
Normalizes string, converts to lowercase, removes non-alpha and "foreign"
characters, removes forbidden characters, and converts spaces to underscores.
Used for file and folder names.
"""
replaced = ('/', '\\', ':', '$', '&', '!'... | 73b55e3cb6d6e00d3f43380af91f4190a0743c27 | 53,930 |
def findstr_in_file(file_path, line_str):
"""
Return True if the line is in the file; False otherwise.
(Trailing whitespace is ignored.)
"""
try:
with open(file_path, 'r') as fh:
for line in fh.readlines():
if line_str == line.rstrip():
return ... | 8cd741fd13bd99f1532951c8b887a04e6bdaffa0 | 53,931 |
def get_particle_time_steps(particle_h5_file):
"""Get time steps stored in the HDF5 particle file
Args :
particle_h5_file : HDF5 file generated from particle tracking
Returns :
time_steps : list containing step numbers
Raises :
None
"""
# read ... | 3cdfdb4e4241e29db8f78cad5228641bc3e73488 | 53,938 |
def shape_and_validate(y, log_pred_prob):
"""Validate shapes and types of predictive distribution against data and
return the shape information.
Parameters
----------
y : ndarray of type int or bool, shape (n_samples,)
True labels for each classication data point.
log_pred_prob : ndarra... | ae71d0c60f4bd9dc132080c10b2c3c1ef80f1fa9 | 53,944 |
from typing import Callable
from typing import Any
from typing import Dict
import inspect
def _get_default_args(func: Callable[..., Any]) -> Dict[str, Any]:
"""
Get default arguments of the given function.
"""
return {
k: v.default
for k, v in inspect.signature(func).parameters.items()... | d2ffa3ac2babc1aa21ef8737ac8ed1d11c3af034 | 53,946 |
def schedule_parser(time_list: str) -> tuple:
""" Module translate string-list of the hours/minutes to the tuple of the seconds.
:arg
string like "00:01; 03:51".
';' it`s separate between some delta-time.
':' it`s separate between hours (first) and minute (second).
:return
tuple like (60, 13... | c57199a22ab84892cd321c2a89131478edbd75a7 | 53,947 |
def validate_passphrases(passphrases, validator):
"""Validate passphrases with validator function."""
return [passphrase for passphrase in passphrases
if validator(passphrase)] | c262da8c243c7661ac4e5c5a84eed454d0b77e4f | 53,951 |
def dq(s):
"""Enclose a string argument in double quotes"""
return '"'+ s + '"' | 2f76a375768a4bc4832f35fde837ccbe11493cef | 53,956 |
def tot_power(Power,N,T):
"""
Calculate the area of the power spectrum, i.e, the total power in V^2 of a signal
--------------------------------------------------------------------------------
input:
- Power: COMPLEX, N-dimensional. Power spectrum of the signal
- N: INTEGER. Number of s... | 14153a9263a294f3a2ded859aff4d77df6815258 | 53,959 |
def scrapeSite(soup):
""" Scrapes ICO website URL from ICODrops listing """
return soup \
.find("div", attrs = { "class" : "ico-right-col" }) \
.find("a")["href"] | 33950d306ea9bd66dd5af3aba2d28406de533491 | 53,962 |
def sysadmin_check(user):
"""
Check whether user is a sysadmin and has an active account.
"""
return user.is_active and hasattr(user, 'sysadmin') | 9dc13240c71f01c052eacb233fa2dbabebb16cba | 53,968 |
def hash_code(key, HASH_SIZE):
"""
Return the hash value of given key and the size of hash table
:param key: given key
:type key: str
:param HASH_SIZE: size of hash table
:type HASH_SIZE: int
:return: hash value
:rtype: int
"""
n = len(key)
res = 0
for i in range(n):
... | af890f853c4774551526518dcc0018fe46b1d266 | 53,969 |
import functools
def func_if_not_scalar(func):
"""Makes a function that uses func only on non-scalar values."""
@functools.wraps(func)
def wrapped(array, axis=0):
if array.ndim == 0:
return array
return func(array, axis=axis)
return wrapped | 19802ebb16f7d5e63991b1ff2e6d87b71ca3bfd9 | 53,970 |
def split_transactions(transactions):
"""
Split transactions into 80% to learn and 20% to test
:param transactions: The whole transactions list
:return: The transactions list to be learnt, the transactions list to be tested
"""
i = int(len(transactions) * 0.8)
transactions_to_learn = transac... | 4e1b0a2b82005fa040da5f46fdac831621d1a0ec | 53,972 |
from typing import List
def get_config_indexes(
config_lines: List[str],
search_string: str
) -> List[int]:
"""
Get index for every list entry that matches the provided search string
Arguments:
config_lines (List[str]):
Keepalived config split into lines
search... | d76e93ec93ea6f9605e54726f3564f7577313732 | 53,976 |
import re
import textwrap
def dedent_string(s):
"""
Strip empty lines at the start and end of a string and dedent it.
Empty and whitespace-only lines at the beginning and end of ``s``
are removed. The remaining lines are dedented, i.e. common leading
whitespace is stripped.
"""
s = re.sub... | 1599d2187b27b3cfc28ff371940ba6250965317b | 53,977 |
def format_coord(x, y, X, extent=None):
"""Set the format of the coordinates that are read when hovering
over on a plot.
"""
numrows, numcols = X.shape
if extent is not None:
col = int((x - extent[0]) / (extent[1] - extent[0]) * numcols + 0.5)
row = int((y - extent[3]) / (extent[2] -... | dd28987d5c1d4d8ac69bf790be38129984961347 | 53,980 |
def get_rowIndex(uid):
"""
return row index as integer
"""
return uid.rowIndex | 77c10637b7bcb9736beaccf38148bcdc9f0b61df | 53,984 |
from typing import List
import shlex
def split_line_elements(text: str) -> List[str]:
"""Separates by space and tabulator.
Args:
text (str): Text to break into separate fields.
Returns:
List[str]: List of formatted values.
"""
# parts = re.split(" |\t", text.strip())
parts = ... | b4ac18f7b60faf29f042c4f7ff02fb5d85d8749e | 53,986 |
def func_lineno(func):
"""Get the line number of a function. First looks for
compat_co_firstlineno, then func_code.co_first_lineno.
"""
try:
return func.compat_co_firstlineno
except AttributeError:
try:
return func.func_code.co_firstlineno
except AttributeError:
... | 27e1a1c141aac4563ba085fdfe6184a7c31c3e8b | 53,987 |
def remap(minfm, maxfm, minto, maxto, v):
"""Map value v in 'from' range to 'to' range"""
return (((v-minfm) * (maxto-minto)) / (maxfm-minfm)) + minto | 35b3f840d18efe5393bf80e8c6f7e89dbeabf860 | 53,993 |
def get_frequency_graph_min_max(latencies):
"""Get min and max times of latencies frequency."""
mins = []
maxs = []
for latency in latencies:
mins.append(latency.time_freq_start_sec)
to_add = len(latency.time_freq_sec) * latency.time_freq_step_sec
maxs.append(latency.time_freq_start_sec + to_add)
... | 7326cfe1ab13aa22067becc9d87b7e536508fd4d | 53,998 |
def _parse_istag(istag):
"""Append "latest" tag onto istag if it has no tag."""
if ":" not in istag:
return f"{istag}:latest"
return istag | 3477750a744a556e57462da14858b6b1d27ec571 | 53,999 |
def HTMLColorToRGB(colorString):
"""
Convert #RRGGBB to a [R, G, B] list.
:param: colorString a string in the form: #RRGGBB where RR, GG, BB are hexadecimal.
The elements of the array rgb are unsigned chars (0..255).
:return: The red, green and blue components as a list.
"""
colorString = co... | ffd4009b26c6c87e407887db6f992500493d1faf | 54,003 |
def binaryForm(n, nbDigs=0):
"""Generates the bits of n in binary form.
If the sequence has less than nbDigs digits, it is left-padded with zeros.
"""
digits = []
while n:
digits.append(n & 1)
n >>= 1
return reversed(digits + [0]*(nbDigs - len(digits))) | 78f3fbda7de846a9380d42696a5cead087031d84 | 54,006 |
def map_node_id_to_coordinates(aux_structures, node):
"""
Maps node IDs to lat and lon.
Returns a dictionary of the format: {node_id: (lat, lon)}
"""
nodes, ways, max_speed_dic = aux_structures
return (nodes[node]['lat'], nodes[node]['lon']) | 926e247d48163e245d75fc7787b8a644d4a464fd | 54,008 |
def remove_redun_hits_from_within_pos_hit_list(l):
"""Take a list of hit sequence ID-Evalue tuples and return a modified list
with redundant items removed. (if two items have the same ID, remove the
one with the higher E-value)
"""
# Check that the E-values are floats.
assert isinstance(l[0][1],... | 9f4ef222fac41460d93c88d6758c11e508b01d8f | 54,010 |
from typing import List
import re
def split_authors(authors: str) -> List:
"""
Split author string into authors entity lists.
Take an author line as a string and return a reference to a list of the
different name and affiliation blocks. While this does normalize spacing
and 'and', it is a key fea... | f6c3952f2b8a2a06411d4acfcda97f55adcd1ba9 | 54,012 |
def is_seq(obj):
"""
Returns true if `obj` is a non-string sequence.
"""
try:
len(obj)
except (TypeError, ValueError):
return False
else:
return not isinstance(obj, str) | ad58f0afdcfd49869eb3bcafe4b82dd878d8b945 | 54,013 |
def _get_stackframe_filename(frame):
"""Return the filename component of a traceback frame."""
# Python 3 has a frame.filename variable, but frames in
# Python 2 are just tuples. This code works in both versions.
return frame[0] | 68f6b91f587df88df366691ef558533e49a18988 | 54,016 |
def assign(var_name, value, current_params, current_variables):
"""
Assigns the indicated `value` to a variable with name `var_name`
Args:
var_name (str) : Name of the variable to assign the value to
value (any) : Value to assign to that variable
Returns:
A dictionary with { var... | acc84a5383a63a35b5012c7b15996606f9251b1d | 54,018 |
def normPath(path: str) -> str:
""" Helper function that's mission is to normalize path strings. Accomplishes this by changing path
strings that are passed in to it from Windows style path strings (unescaped backslashes) and windows style
python path strings (escaped backslashes i.e. double backslash) to un... | 1a858b2ed2ab7a2ea2d8e6e7dd33417aea09cae8 | 54,020 |
def split_stack(stack):
"""
Splits the stack into two, before and after the framework
"""
stack_before, stack_after = list(), list()
in_before = True
for frame in stack:
if 'flow/core' in frame[0]:
in_before = False
else:
if in_before:
stac... | 8d4d143f72357ffd6740d6b08412044edc128307 | 54,021 |
import base64
import hashlib
def generate_short_url(original_url: str, timestamp: float):
"""generate_short_url generates an 8 character string used to represent the original url. This 8 character
string will be used to "unshorten" to the original url submitted.
parameter original_url: the url that the user passes... | 4704111df15e9eb0f71204732fc5cf2897904cf1 | 54,022 |
def multiply_matrices(m_1: list, m_2: list) -> list:
"""
Parameters
----------
m_1 : list of lists =>
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
m_2 : list of lists =>
[[10, 11, 12],
[13, 14, 15],
[17, 18, 19]]
Returns
------
transformation : list of lists =>
[[ ... | 4f849eb2c8d9216dcebb7d6a3ae10a4ff61ea80e | 54,028 |
def response_to_dictionary(response):
"""
Converts the response obtained from UniProt mapping tool to a dictionary.
Output: Dictionary with Uniprot IDs as keys and a lists of PDB ids as values (single UniProt IDs may map to different PDB ids).
"""
list = response.decode('utf-8').split(sep="\n") # ou... | efb5c952ab4487a9d2fd5c5759f22272a08e1257 | 54,030 |
def fields_for_mapping(mapping):
"""Summarize the list of fields in a table mapping"""
fields = []
for sf_field, db_field in mapping.get("fields", {}).items():
fields.append({"sf": sf_field, "db": db_field})
for sf_field, lookup in mapping.get("lookups", {}).items():
fields.append({"sf":... | 4a61c8f43a8a88e4c7ba35570eb54383925f0392 | 54,031 |
def get_state(coq):
"""Collect the state variables for coq."""
return coq.root_state, coq.state_id, coq.states[:] | d04c9fac975bacb2c616b2429b871e159256222e | 54,032 |
def check_flags(peek):
"""Check byte sequence for only flag bytes."""
for i in peek:
if i not in [0, 1]:
return False
return True | 6e33e5a91b9f0cea146aa0772d139a9da8baddc9 | 54,034 |
def _all_ones(x):
"""Utility function to check if all (3) elements all equal 1"""
return all(n == 1 for n in x) | e7d82b7d564ab1c9f94fc875c6652c44108a14b8 | 54,036 |
def get_sentid_from_offset(doc_start_char, doc_end_char, offset2sentid):
""" This function gets the sent index given the character offset of an entity in the document
Args:
doc_start_char: starting character offset of the entity in the document
doc_end_char: ending character offse... | 61ba6729574cd73af0a3508a2964ef6576385156 | 54,037 |
def kmers(dna, k):
"""
Given a dna sequence return a hash with all kmers of length k and their frequency.
This method does NOT use the reverse complement, it only checks the strand you supply.
:param dna: the dna sequence
:param k: the length of the kmer
:return: a hash of kmers and abundance
... | 464386ebc14b31f54d676e6eecf6d9b469d8dff6 | 54,039 |
def request_vars(*valid_param_fields):
"""
Decorator maker to assign variables to the params field.
:param valid_param_fields: The variables to move from **kwargs to params.
:return: A decorator that checks for the passed variables and moves them to the params var.
... | 07d7a673a86358f4fb7033bf9f6fd3683b8f00f7 | 54,040 |
def names_from_file(filename):
"""Takes filenames from the content of a file (removes spaces and end-of-lines, no comment allowed)"""
with open(filename) as f:
item_list = [name for name in f.read().split() if name]
return item_list | 3931fed7f6d657f12062f4dcb0213c193ab394f4 | 54,043 |
def unprocess_image(image):
""" Undo preprocess image. """
# Normalize image to [0, 1]
image = (image / 2) + 0.5
image = image * 255.0 #[0,1] to [0,255] range
return image | 68b8bddfa0d33530687e753bc0f2a07c9be4e425 | 54,045 |
import math
def _Scale(quantity, unit, multiplier, prefixes=None, min_scale=None):
"""Returns the formatted quantity and unit into a tuple.
Args:
quantity: A number.
unit: A string
multiplier: An integer, the ratio between prefixes.
prefixes: A sequence of strings.
If empty or None, no sc... | 224d302c5d2f3a9ffc72b34e5d6614eacb33c89f | 54,046 |
def _convert_value(value, conversions, default):
"""Converts a value using a set of value mappings.
Args:
value: The value to convert.
conversions: A dict giving the desired output for each of a set of possible
input values.
default: The value to return if the input value is not one of the ones
... | e673e950889e63081e343bc41921f16de101be61 | 54,056 |
import asyncio
def create_task(coro, *, name=None):
"""create_task that supports Python 3.6."""
if hasattr(asyncio, "create_task"):
task = asyncio.create_task(coro)
if name is not None and hasattr(task, "set_name"):
task.set_name(name)
return task
else:
return a... | ad0757beca469e6df83923918efa76851d98ab81 | 54,057 |
def normalize(X, mean, std):
"""Normalization of array
Args:
X (np.array): Dataset of shape (N, D)
mean (np.array): Mean of shape (D, )
std (float): Standard deviation of shape(D, )
"""
return (X - mean) / std | abeeb7b17a1e8f0079f80992cbf42e330ffe1ce7 | 54,058 |
import requests
def get_video_info(video_id=""):
"""Get the dictionnary of info (fron Tournesol API) for a video from it's ID"""
# Get video info dictionary
print("Call API with video_id: ", video_id)
response = requests.get(f"https://tournesol.app/api/v2/videos/?video_id={video_id}").json()
if ... | 0e7373cb7bdcc7cbc8f2c5885fa183e573541b0b | 54,059 |
def _make_ssa_name(name):
"""Converts a symbol name (string) into an SSA name, by prepending '%'.
Only used for pretty printing the graph.
"""
return "%" + name | 3a46e300d5880f9ea482f1df00e983de38b2d51c | 54,060 |
import re
import json
def get_bam_library_info(bam):
"""Get the library info from a BAM's comment lines.
Args:
bam (pysam.AlignmentFile): BAM file
Returns:
list of dicts
"""
comments = bam.header['CO']
libraries = []
for comment in comments:
m = re.match(r'^library_info... | cb41eeecf6545c3d1961a4275417e85e4a624d2c | 54,062 |
def get_href_id(prop):
"""Helper function to extract key property information from trademe search site (url and ID)."""
output = {}
output["href"] = prop["href"]
output["id"] = prop["id"]
return output | 858ef1b116a08595b03c3b906b3d636d0072a67c | 54,064 |
def minus(a, b):
"""
Returns the assymetrical difference of set 'a' to set 'b' (a minus b).
In plain english:
Remove all the items in 'a' from 'b'. Return 'a'. (Order matters.)
Minus is set_a.difference(set_b). The nomenclature 'difference
is not linguistically descriptive (at least to a ... | e4f92e57fbe12d9aa5167fe1c0f031ede0d6fba9 | 54,065 |
def checkEqual(vec, val):
"""
Checks if all entries are equal to the supplied value.
"""
allEqual = True
for v in vec:
if v != val: return False
return allEqual | c9fcf5489d2cac5ea21181c3833b35dc073a3674 | 54,066 |
def xor_strings(b1, b2):
"""XOR two strings"""
if len(b1) != len(b2):
raise ValueError('Two strings not of equal length')
return bytes([a ^ b for a,b in zip(b1, b2)]) | 969c0a934099a17aa49bbebea0a8a811c8b0b37a | 54,069 |
from collections import defaultdict
def res_contacts(contacts):
"""
Convert atomic contacts into unique residue contacts. The interaction type is removed as well as any third or
fourth atoms that are part of the interaction (e.g. water-bridges). Finally, the order of the residues within an
interaction... | 42b4736675afa0d76ecc14d663ea261a870430b6 | 54,073 |
def pupil_to_int(pupil):
"""Convert pupil parameters to integers. Useful when drawing.
"""
p = pupil
return ((int(p[0][0]), int(p[0][1])), (int(p[1][0]), int(p[1][1])), int(p[2])) | 2b289dc43c7c65c25b1ad901aa31055f62d67a59 | 54,076 |
def check_key(dictionary, key, default_value):
"""
Returns the value assigned to the 'key' in the ini file.
Parameters:
dictionary : [dict]
key : [string|int]
default_value : [string]
Output: Value assigned to the 'key' into the 'dictionary' (or default value if not ... | 058b3e78503f7427ce39d48afde6c9fb80c8d0d7 | 54,078 |
def get_list_duplicates(in_list):
"""Identify duplicates in a list."""
seen = set()
duplicates = set()
for item in in_list:
if item in seen and item != 'N/A':
duplicates.add(item)
seen.add(item)
return list(duplicates) | a9b7fa3f996f0109f266d31f80fd809cef88333a | 54,079 |
import string
import random
def passwordWithRequirements(lenght=12):
"""assumes lenght is an int >=4, representing how long the password should be
returns a string of ASCII characters, representing a suggested password
containing at least 1 uppercase, 1 lowercase, 1 digit, and 1 symbol"""
if not isins... | d0d69050c39ed577acea0680d54eaf8905d801ce | 54,080 |
def decodeObjectQualifiersList(objectQualifiers):
"""Turn an object qualifiers list into a list of conditions.
Object qualifiers are found as part of G-AIRMET messages.
Object qualifiers are stored in a three array list, each element represents
eight bits or 24 bits in total. Most of the elements are ... | 01ab66c594a50389f1993b13e25951eb9ca6eca2 | 54,082 |
import typing
def filesystem_info(path: str) -> typing.Dict[str, typing.Any]:
"""Parse /proc/mounts (which has fstab format) to find out the type of a filesystem."""
# Get the data and split into a list of mounts.
with open("/proc/mounts", "r") as f:
procmounts_raw = f.read()
procmounts = proc... | 3e32d19d2874191a642cd40757a729d6dc3f9743 | 54,086 |
from operator import mod
def is_gregorian_leap_year(g_year):
"""Return True if Gregorian year 'g_year' is leap."""
return (mod(g_year, 4) == 0) and (mod(g_year, 400) not in [100, 200, 300]) | 2a7cc6fcba9eee503d007679695b87ee04e0c85f | 54,087 |
from typing import Optional
def _default_progress_str(progress: int, total: Optional[int], final: bool):
"""
Default progress string
Args:
progress: The progress so far as an integer.
total: The total progress.
final: Whether this is the final call.
Returns:
A formatt... | 0aa2daf0e1750fb534142125af253e036bb65148 | 54,096 |
def concatenate_replacements(text, replacements):
"""Applies a rewrite to some text and returns a span to be replaced.
Args:
text: Text to be rewritten.
replacements: An iterable of (new_text, start of replacement, end)
Returns:
A new replacement.
"""
joined = []
first_start = None
last_end ... | 48046d59273a542e36efb967b30dc4b82b1c104d | 54,098 |
def check_availability(lower_bound: int, upper_bound: int, high_lower_bound: int, map_array: list,
coordinates: tuple, size: int, scale_factor: int):
"""
Function checks if there is enough space on map to generate structure of given size
at given coordinates
Args:
low... | b97d77d3ee1533a435694844cc21772e49bb7481 | 54,105 |
from typing import Optional
from typing import List
from typing import Callable
def generate_fake_wait_while(*, status: str, status_info: Optional[List[str]] = None) -> Callable:
"""Generate a wait_while function that mutates a resource with the specified status info."""
if status_info is None:
status... | 93381a16c68d74161b112bb47a57f2a745678531 | 54,108 |
def Byte(value):
"""Encode a single byte"""
return bytes((value,)) | aedfae62826571fe631f62438205f6204a87a04c | 54,111 |
def create_centroid_ranges(centroids, tol=15):
"""
Create high and low BGR values to allow for slight variations in layout
:param centroids: legend colors identified from get_centroids
:param tol: int, number of pixels any of B, G, R could vary by and still
be considered part of the original centroi... | 56b3922801dfe75837331e868406964d7ac18f43 | 54,112 |
import re
def _parse_log_entry(l):
"""
Returns an re match object with the contents:
First group: timestamp
2: module name
3: logging level
4: message
"""
pattern = re.compile(r'(\d*-\d*-\d* \d*:\d*:\d*,\d*) - ([\w.]+) - (\w*) - (.+)')
return pattern.match(l) | 1693ccf644e530577d126b9af4f1fa891c4659ef | 54,114 |
import re
def check_username(username):
"""
Checks if a username is valid
:param username: username to check
:return: True if the username is valid, false otherwise
"""
return bool(re.fullmatch(r"[a-zA-Z0-9_\.\-]{3,30}", username)) | ccdfa594f7bf51a47c31ff2d7dc92e9823ee8bf4 | 54,118 |
from typing import Dict
from typing import List
def sort_dict_desc(word_dict: Dict) -> List:
"""Sort the dictionary in descending order.
:param word_dict: the dictionary of word.
:return: sorted list of dictionary.
"""
# sort by value
# word_dict.items() to get a list of (key: value) pairs
... | 87ea93145b7d4d7a867845a52ae3ef1c8403075d | 54,121 |
import hashlib
import six
def md5files(lfp):
"""Returns the MD5 of a list of key:path.
The MD5 object is updated with: key1, file1, key2, file2, ..., keyN, fileN,
with the keys sorted alphabetically.
"""
m = hashlib.md5()
sorted_lfp = sorted(lfp, key=lambda ab: ab[0])
for ab in sorted_lfp... | 309d2dbec88089e78683f6d5dabbd5c2f7826b8f | 54,123 |
def _parse_numbered_syllable(unparsed_syllable):
"""Return the syllable and tone of a numbered Pinyin syllable."""
tone_number = unparsed_syllable[-1]
if not tone_number.isdigit():
syllable, tone = unparsed_syllable, '5'
elif tone_number == '0':
syllable, tone = unparsed_syllable[:-1], '... | f9829ba0b14e9cdcd7c78f19a5159a1cbfd99716 | 54,125 |
def is_valid_rtws(rtws):
"""
Given a clock-valuation timedwords with reset-info, determine its validation.
"""
if len(rtws) == 0 or len(rtws) == 1:
return True
current_clock_valuation = rtws[0].time
reset = rtws[0].reset
for rtw in rtws[1:]:
if reset == False and rtw.time... | 726b44af21a083ae64a260e5214204c53416ffe5 | 54,128 |
def _to_bytes(value, encoding='utf-8'):
"""Encodes string to bytes"""
return value.encode(encoding) | d7b0bebe488fb9f42b6f08e1dc41cffb9063eb11 | 54,140 |
def convert_genre(genre: str) -> str:
"""Return the HTML code to include for the genre of a word."""
return f" <i>{genre}.</i>" if genre else "" | 443ba5217c7ff916e462b3d6f6931e8e60c9b78b | 54,147 |
import itertools
def _region_interval_to_dimensions(old_project_data):
"""
From
interval_definitions:
- name: annual
description: ''
filename: annual_intervals.csv
region_definitions:
- name: national
description: ''
filename: uk_nations_shp/regions.shp
... | cab19b4d2c02766ffa313c8c1960388975751c51 | 54,149 |
def resolve_cardinality(class_property_name, class_property_attributes, class_definition):
"""Resolve class property cardinality from yaml definition"""
if class_property_name in class_definition.get('required', []):
min_count = '1'
elif class_property_name in class_definition.get('heritable_require... | fed27e5c326842f5895f98e3f5e9fb5852444b07 | 54,153 |
def get_col(square: tuple) -> list:
"""
Gets all the squares in the column, this square is in.
:param square: A tuple (row, column) coordinate of the square
:return: A list containing all the tuples of squares in the column
"""
col_squares = []
for j in range(0, 9):
col_squares.appe... | 4c77cb3cba7b2bc19cdff2eb9763b0c95e9f948f | 54,162 |
def remove_apostrophes(df, from_columns=None):
"""
Remove apostrophes from columns names and from data in given columns.
Also strips leading and trailing whitespace.
This function operates in-place on DataFrames.
Parameters
----------
df : pandas.DataFrame
from_columns : Collection, o... | 82f41c807afda33f14adca29d8d3e6bb106e7833 | 54,163 |
from typing import List
def define_frontal_chest_direction(robot: str) -> List:
"""Define the robot-specific frontal chest direction in the chest frame."""
if robot != "iCubV2_5":
raise Exception("Frontal chest direction only defined for iCubV2_5.")
# For iCubV2_5, the z axis of the chest frame ... | 5bf61e3f1291780dddf6cf3b9bb07ce1fb4b13c1 | 54,164 |
def test_consumer(test_amqp):
"""Return a consumer created by the test AMQP instance."""
consumer = test_amqp.consumer()
return consumer | cb9d18952e4a1a7719f35c5813ccee9fb74d32ee | 54,168 |
def _compare_address_lists(list_one, list_two):
"""
Counts the number of elements in list one that are not in list two.
:param list_one: list of strings to check for existence in list_two
:param list_two: list of strings to use for existence check of
list_one parts
:return: the count of it... | ac8e910b0ac54c6402ca980b4d238e2c27fe90e5 | 54,172 |
def get_diff(url, client):
"""Uses client to return file diff from a given URL."""
return client.get(url) | e2fce7d01f4eee2e806393c865e54dd5ffe1a339 | 54,174 |
def sparse_dot_product(A, B):
"""
Function used to compute the dotproduct of sparse weighted sets represented
by python dicts.
Runs in O(n), n being the size of the smallest set.
Args:
A (Counter): First weighted set.
B (Counter): Second weighted set.
Returns:
float: D... | 128d221e2e37125364c31d85c8aa5fb5c98d94c3 | 54,175 |
def rect_offset(rect, offset):
""" Offsets (grows) a rectangle in each direction. """
return (rect[0] - offset, rect[1] - offset, rect[2]+2*offset, rect[3]+2*offset) | ce2bb154acf64e153031c11a889f5eeebc8b61db | 54,179 |
def _convert_delimiters_to_regex(*delimiters):
"""Converts a list of strings into a regex
Arguments
------------------
*delimiters : str
The delimiters as that should be converted into a regex
Returns
------------------
regex : str
The converted string
... | 7d2c26b2fe563907040872c0f33452a3b0ccd072 | 54,182 |
def shrink_sides(image, ts=0, bs=0, ls=0, rs=0):
"""Shrinks/crops the image through shrinking each side of the image.
params:
image: A numpy ndarray, which has 2 or 3 dimensions
ts: An integer, which is the amount to shrink the top side
of the image
bs: An integer, which is t... | 6858a75516626affb3d65b9c8aad8bd207cfe495 | 54,186 |
from pathlib import Path
def get_files(source, extensions=['yaml', 'yml', 'json']):
"""Get all files matching extensions.
Args:
extensions (list): List of extensions to match.
Returns:
list: List of all files matching extensions relative to source folder.
"""
all_files = []
f... | 44c172d0211f147ced5c5f0cb249686b89cb3593 | 54,188 |
def get_subj_ids(data):
"""
Get unique subject ids from the supplied panda DataFrame. (expect to find a 'subj_idx' column.)
"""
# get unique subject ids corresponding to a data subset
return data["subj_idx"].unique() | 94e577e6a2bcd7d55669eae1b01fa8f47b9f6ad3 | 54,189 |
def clean_table_query(conn, table):
"""
Query the specified table with SQL to create clean dataset.
:param conn: the Connection object
:param table: the name of table
:return: cleaned rows dataset
"""
cur = conn.cursor()
if table == 'question2':
cur.execute('''SELECT upper(countr... | 063485ec8c43e1e4add883737034c8c1beb27f15 | 54,190 |
def clean_text(df, text):
"""
Cleans text by replacing unwanted characters with blanks
Replaces @ signs with word at
Makes all text lowercase
"""
# pdb.set_trace()
df[text] = df[text].str.replace(r'[^A-Za-z0-9()!?@\s\'\`\*\"\_\n\r\t]', '', regex=True)
df[text] = df[text].str.replace(r'@'... | 4c8f4b8dae76ef47314ef57b62f51f72ceaacf34 | 54,193 |
def get_base_encoding(encoding: str) -> str:
"""
Check which base encoding is needed to create required encoding.
! Adapt if new encoding is added !
:param encoding: required encoding
:return: base encoding
"""
if encoding in ('raw', '012', 'onehot', '101'):
return 'raw'
else:... | 7ba27b9bfc44445d90d2b3efec2943f8bd3dfddc | 54,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.