content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def replace_last_command(cmd, replacement):
"""
Replace the last command in cmd with given replacement.
:param cmd: command (string).
:param replacement: replacement (string).
:return: updated command (string).
"""
cmd = cmd.strip('; ')
last_bit = cmd.split(';')[-1]
cmd = cmd.repla... | 714e17869e0c0ac6ce74f44bf212d001809ba6d2 | 573,731 |
def has_child (root,name):
###############################################################################
"""
Check if root element has a *direct* child with given name
>>> xml = '''
... <my_root>
... <a>1</a>
... <b>
... <c>2</c>
... </b>
... </my_root>
... '''
>>... | 78f09958c7ade68e679c89f69cf8ba5978590a94 | 573,733 |
def execute(sql, cursor):
"""Executes a SQL command on the cursor and returns the results."""
cursor.execute(sql)
return cursor.fetchall() | 87d1117cf40012bc01dddb42b51128343b32eea2 | 573,735 |
def deviation_ok(norm, value, epsilon):
"""Check if a value's deviation from given norm stays under boundary"""
deviation = abs(norm-value)/norm
# print(abs(d-epsilon))
return deviation <= epsilon | bd141bd59ee94eb12c7af3247d288c37e4f928fc | 573,739 |
def _opp_cols_to_back(df):
"""
Extracts columns starting with "Opp" and moves them to the end.
:param df: dataframe
:return: dataframe with reordered columns
"""
cols = list(df.columns)
oppcols = {col for col in cols if len(col) >= 3 and col[:3] == 'Opp'}
neworder = [x for x in df.co... | 1e392e9b3965f11261ab6091ec95ca2051b54e51 | 573,744 |
def partition(thelist: list, start_index: int, end_index: int) -> int:
"""
Partitions a list into 2 and returns the pivot index
:param thelist The list to divide into 2 partitions to get the pivot index.
This uses the last element as the pivot of the list
:type thelist list
:param start_index
... | 18a8b28695663c68fd91e4b0bcd61cbc7dc3088e | 573,746 |
import six
def next_or_none(iterator):
"""
Returns the next item from the iterator, or None if there are no more.
"""
try:
return six.advance_iterator(iterator)
except StopIteration:
return None | dfa130c873e8fa49cba458916b2be933d0b734f1 | 573,748 |
def hr_bytes(bytes_, suffix='B', si=False):
""" A method providing a more legible byte format """
bits = 1024.0 if si else 1000.0
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(bytes_) < bits:
return "{:.1f}{}{}".format(bytes_, unit, suffix)
bytes_ /= bits
retu... | 643770211152fb2df3b53e4f024938f5097c779f | 573,749 |
import torch
def get_point_coords_wrt_image(boxes_coords, point_coords):
"""
Convert box-normalized [0, 1] x [0, 1] point cooordinates to image-level coordinates.
Args:
boxes_coords (Tensor): A tensor of shape (R, 4) that contains bounding boxes.
coordinates.
point_coords (Ten... | c7ea056453ad88e942dd2aff5f6a7d6ceedde6ea | 573,750 |
from typing import Union
from typing import List
def count_by(x: Union[int,float], n: int) -> List[Union[int,float]]:
"""
Return a sequence of numbers counting by `x` `n` times.
"""
return [x*it for it in range(1,n+1)] | c0336c0ba5ff0627129fdc5ae51f309f7bf9bf5b | 573,757 |
import shutil
def command_exists(cmd):
""" Does this command even exists? """
path = shutil.which(cmd)
if path is None:
return False
return True | 21361505be6b7d332b9c47217d1db647db033408 | 573,764 |
from typing import Tuple
def get_first_number(expression: str) -> Tuple[float, str]:
"""
Reads the number in the beginning of the expression string.
This number can begin with a sign +-, a number or the decimal point
:param expression: str of the expression
:return: float value of the number in ... | 263b8684a9fb6eb1dce816cf96aa961af711fe3d | 573,765 |
def remove_duplicates_in_items(items: list, id_key: str) -> list:
"""Remove duplicate items based on the given id key,
Args:
items (list): The items list.
id_key (str): The ID key for suplication check.
Returns:
(list) New items without duplications.
"""
i... | 4f204482a9c1625bf4701a08f25add961605ed89 | 573,766 |
def delete_tekton_pipeline_yaml(cursor, yaml_id):
"""tekton_pipeline_yaml情報削除(id指定)
Args:
cursor (mysql.connector.cursor): カーソル
yaml_id (int): yaml ID
Returns:
int: 削除件数
"""
# tekton_pipeline_yaml情報 delete実行
cursor.execute('''
DELETE FROM tekton_pipeline... | 2f73d5b24734ef912617a29ff056213c0d5ebd94 | 573,767 |
def mean(num_lst):
"""
This function calculates the average of a list of numbers
Parameters
-------------
num_lst : list
List of numbers to calculate the average of
Returns
-------------
The average/mean of num_lst
Examples
--------------
>>> mean([1, 2, 3, 4, 5])
... | 64549ed4cb57fc9cb5c7c9477a8c56bf05923758 | 573,769 |
import io
def file_to_png(fp):
"""Convert an image to PNG format with Pillow.
:arg file-like fp: The image file.
:rtype: bytes
"""
import PIL.Image # pylint: disable=import-error
with io.BytesIO() as dest:
PIL.Image.open(fp).save(dest, "PNG", optimize=True)
return dest.getvalue() | 213378ff88bc93c7c399e1e0ff4f2168e680b194 | 573,770 |
async def get_option_market_data(self, input_symbols, expiration_date, strike_price, option_type, info=None):
"""Returns the option market data for the stock option, including the greeks,
open interest, change of profit, and adjusted mark price.
:param input_symbols: The ticker of the stock.
:type inpu... | 19e35842fd434406f9dc31ae22b117958a44236b | 573,772 |
def calc_testname(test):
"""
Build a reasonably human-readable testname from each test.
"""
name = str(test)
if ' ' in name:
name = name.split(' ')[1]
return name | b1d2b05fc4dac6425606f41e0fdce83705967652 | 573,774 |
def _sortkey(filename):
"""
Key for sorting filenames based on angular momentum and parity.
Example filename: 'log_Sc44_GCLSTsdpfsdgix5pn_j0n.txt'
(angular momentum = 0).
"""
tmp = filename.split("_")[-1]
tmp = tmp.split(".")[0]
# parity = tmp[-1]
spin = int(tmp[1:-1])
# return... | 0d0130c52e35080133946017b0db611489d92b2c | 573,776 |
def mean(data):
"""Return the mean of a sequence of numbers."""
return sum(data) / len(data) | 856bfe8806e1552c8fa388fef12b0e94bb86d076 | 573,777 |
import re
def _get_custom_display_values(df, translated_style):
"""Parses pandas.Styler style dictionary into a
{(row, col): display_value} dictionary for cells whose display format
has been customized.
"""
# Create {(row, col): display_value} from translated_style['body']
# translated_style['... | 9a08d6ecd9d79e3c85ef8ae6053366388bcd43cb | 573,779 |
def signature_payload(headers, body = None):
"""Converts a message into a payload to be fed to the signature algorithm.
The Checkout API requires every request and response to be signed.
The first step in the signature process is to convert the request or
response into a payload string. This function ... | 163c2f5c0889f4053b0756da1a138b7c2b98653f | 573,781 |
def Sym(u):
"""Matrix symmetrization."""
return (u + u.transpose()) / 2.0 | b2a79694f6457120ea4b2d75def7d318419dc312 | 573,786 |
from typing import List
from typing import Any
def partition(lst: List[Any], n: int) -> List[List[Any]]:
"""
Splits the list into chunks with size n,
except last chunks that has size <= n
"""
return [lst[i : i + n] for i in range(0, len(lst), n)] | 5511c16d44c91493ce4a4a3575381f4ebbd6fb94 | 573,789 |
def get_forecast_variable(gt_id):
"""Returns forecast variable name for the given ground truth id
Args:
gt_id: ground truth data string ending in "precip" or "tmp2m"
"""
if "tmp2m" in gt_id:
return "tmp2m"
if "precip" in gt_id:
return "prate"
raise ValueError("Unrecognize... | 5ac5ab08cdb7c770c9edc2c34c55c969aab84010 | 573,790 |
def get_request_body(request):
"""Get a request's body (POST data). Works with all Django versions."""
return getattr(request, 'body', getattr(request, 'raw_post_data', '')) | f19a12932cdb9c862bf03160409bfd88e1483c9a | 573,791 |
def FilterStations(MasterStationList,data_files):
"""
Filter the files to download by those stations required
If station of remote file exists in master list, want to download,
else not.
"""
DownloadStationList=[]
for dfile in data_files:
station=dfile.filen.split('.')[0][:-5]... | 704aec2969523faa55f8d69051c9bb66b5b0db59 | 573,797 |
def split_str(s):
""" split s around ',' and removed empty sub-string """
return [sub for sub in s.split(",") if s!= ""] | baa0d611657147fd7dc88cb31934b8e52591e138 | 573,798 |
def has_license(lines):
"""Check if first two lines contain a license header."""
if len(lines) < 2:
return False
return (
"SPDX-FileCopyrightText:" in lines[0] and "SPDX-License-Identifier:" in lines[1]
) | 1b6a694c421bacb41b9a8391febc3b92274e1451 | 573,799 |
def node_name(row, col):
"""Return a unique node name"""
return f"{row:03d},{col:03d}" | c5b22db8c2d9f0af3f6158e46b9d09538bd06d77 | 573,802 |
def translate_severity(sev):
"""
Translates Prisma Cloud Compute alert severity into Demisto's severity score
"""
sev = sev.capitalize()
if sev == 'Critical':
return 4
elif sev == 'High':
return 3
elif sev == 'Important':
return 3
elif sev == 'Medium':
r... | 9f7de7f8cd834ca84370cc9fdf9b27e786d797a9 | 573,803 |
def get_block(output, pos, sep):
""" Returns the current block of output from 'pos' to the next separator in the list of 'sep'.
Also returns the position where there the first separator of the list 'sep' is
"""
sep_pos = []
for separator in sep:
sep_pos.append(output.find(separator, pos)... | fdd605b97cb32e1eafb5c2e6ae16486399c904c8 | 573,810 |
def generate(message: str) -> str:
"""Generate a string with 'Hello message' format.
Args:
message: A string to be added.
Returns:
Generated String.
"""
return 'Hello {}'.format(message) | 1a4190a09457178b18a136a9d7f3e27311dd1d46 | 573,814 |
from typing import Dict
from typing import Any
from typing import List
def subdict(d: Dict[str, Any], keys: List[str]) -> Dict[str, Any]:
"""
Returns a dictionnary with only the keys defined in the keys list
Arguments:
- d: original dictionnary
- keys: list of keys to keep
Returns:
... | 3a691e76bfdd505c016196ee81b978a67778b02a | 573,816 |
import importlib
def import_module(module, package=None):
"""Protected import of a module
"""
try:
ret = importlib.import_module(module, package=package)
except ModuleNotFoundError:
if package is not None:
raise ModuleNotFoundError("Requested module/package '{}/{}' not foun... | bfc215aed80575c5802759fcbce4b2d48b4a6505 | 573,820 |
def read_lines(filename, begin_lineno, end_lineno):
"""Read lines from file."""
lines = []
with open(filename) as f:
for i, line in enumerate(f):
if i >= begin_lineno and i < end_lineno:
lines.append(line.rstrip())
return lines | 43769612ef22f95d2358b349de50fb225345e83f | 573,822 |
def getterm(stream):
"""
This function travels through a given datastream and records all lines
until it finds the start of a new term or the end of a useful section
of the obofile.
"""
block = []
for line in stream:
if line.strip() == "[Term]" or line.strip() == "[Typedef]":
... | e5835502e9d22e73da2e2a98bd007b815884cb17 | 573,823 |
def trim_string_from_front(string, remove_starts_with_string):
""" Remove string provided in the search_string
and returns remainder of the string.
:param string:
:param remove_starts_with_string:
:return: trimmed string
"""
if string.startswith(remove_starts_with_string):
return str... | 3b09d28d4bacdb991c46745af74de66a69213d34 | 573,824 |
def get_photo_id(photo):
""" Given a photo flickrapi object return the flickr photo id. """
return photo['id'] | 8c5e07915785588e3f17774111e7eadc3641eb89 | 573,825 |
def SquaredDifference(a, b):
"""
Squared diff op, i.e. (a-b)**2
"""
return (a - b)**2, | 5466e8ebb54e24f82347c10223ca534b9600232a | 573,826 |
def flatten(dictlist, key):
"""Flattens a list of dicts into just a list of values.
::
>>> d = [{'id': 1, 'name': 'foo'}, {'id': 2, 'name': 'bar'}]
>>> flatten(d, 'id')
[1, 2]
"""
return [d[key] for d in dictlist] | 9231f28de7c88ef5393cc0cacaf8a969b9ec2f42 | 573,829 |
def trunc_name(text: str, max_len: int = 10) -> str:
"""Shortens the name to match the `max_len`
through adding `...`."""
# Check if it meets the criteria
if t_len := len(text) <= max_len:
return text
return text[:max_len-3] + "..." | 0c6a4a158e8ec9f020e931c252cc2ca84737ca65 | 573,831 |
def GetTypeDataName(name, type_name='object'):
"""Returns the data name for name of type type_name.
Args:
name: The data name.
type_name: The data type name.
Returns:
The data name for name of type type_name.
"""
return '{name}::{type_name}'.format(name=name, type_name=type_name) | 7cce971e0e9e3d6c37c636225ee4b2d1a5663252 | 573,833 |
def collect_city_datasets(data_dir):
"""
Collect the city datasets.
If a city does not have *ALL* the datasets, it is discarded.
"""
cities = {
"-".join(city.stem.split("-")[0:-1])
for city in list(data_dir.glob("*"))
if not city.stem.startswith(".")
}
groups = []
... | c4b2db1593e5e8ce02307fe58f1554e86409cbb5 | 573,836 |
def single_value_fetcher(cursor):
""" Return the first value in the first row of the cursor. """
return cursor.fetchall()[0][0] | 0773bbe4107d72bd5366d40ad0698c4625e61e9b | 573,845 |
def replace_none(value, default, lazy=False):
"""Return value if it's not None, otherwise return default value
Parameters
----------
value: object, None
An object that we intend to replace if None
default: object, callable
Either a default returned value or function to be called if ... | 621dfc1a8ea13d082f251758b082906b90caf0e6 | 573,856 |
def calc_lrn(func, in_data, **kwargs):
"""[LocalResponseNormalization](https://docs.chainer.org/en/v4.3.0/reference/generated/chainer.functions.local_response_normalization.html)
Let $c$, $h$ and $w$ be the shape of $x$, so $\|x\| = chw$
First all the values are squared ($chw$ FLOPs).
Then it is integr... | 0940beabf04a1c5563a71340d3d614c70ddf39fc | 573,860 |
def url_to_img_element(url, name, width, height, unit='px'):
"""Convert a given URL to a HTML img element."""
style = None
if width is not None and height is not None:
style = 'width:{width}{unit};height:{height}{unit};'.format(
width=width, height=height, unit=unit)
elif width is no... | 4932eb50bc7219fee6a9226387b2d9081a406b83 | 573,862 |
def get_account_type(account, account_types, def_type='n/a'):
""" Detect the account type of a given account
Args:
account (str): The account name
account_types (dict): The account types with matching account names.
def_type (str): The default account type.
Returns:
(str): ... | cd444c6f4c933d2fde5978ebf511467ec2295ad9 | 573,872 |
def flip(f):
"""Swap Arguments."""
return lambda left, right: f(right, left) | 012f1a42d9f6690556e5622b04f8f6f39dc89007 | 573,873 |
def normalize_image(image):
"""
Normalize image array from 0 ~ 255
to 0.0 ~ 1.0
:param image: origin input image
numpy image array with dtype=float, 0.0 ~ 255.0
:return image: numpy image array with dtype=float, 0.0 ~ 1.0
"""
image = image / 255.0
return image | 90e4ff1f5511821881af70ed050bccd3092e2a79 | 573,875 |
def bit_into_byte(byte, schema, value):
"""
Update bits in a byte to get new value.
args:
- initial byte we are working with.
- data schema(list): [index, bits]
- data's starting bit index.
- number of bits.
- new value for target.
returns:
new byte v... | f43e5e2aef2943b12f818fa96655ccbf557cab55 | 573,880 |
import random
import string
def generate_verification_code() -> str:
"""Generate a random 6-digit code
Returns:
str: a 6-digit code in string format .e.g '654874'
"""
return "".join(random.choices(string.digits + string.digits, k=6)) | 4b6a6891e73c93cd92a5d1fc6098ca6faa5dcd5b | 573,883 |
def expected_number_of_precincts_audited(p):
"""
Return expected number of precincts audited.
p = list of probabilities that each precinct will be audited
"""
return sum(p) | 09048183d94895ed5ad954d26446a721f4c096c0 | 573,891 |
import itertools
def SplitNone(l):
"""Split a list using None elements as separator.
Args:
l: a list which may contain some None elements.
Returns:
A list of non-empty lists, each of which contains a maximal
sequence of non-None elements from the argument list.
"""
groups = itertools.groupby(... | 794eccdb6764b6d607e415ea9eab146e0dc0e947 | 573,893 |
import random
import string
def random_hex(num_chars):
""" Generate random hexadecimal string """
lst = [random.choice("abcdef" + string.digits) for _ in range(num_chars)]
return ''.join(lst) | 21740b77d353b197a22cac93d449a4f2c06fdc7a | 573,897 |
def _check_histories(history1, history2):
"""Check if two histories are the same."""
if history1.replace("\n", "").replace(" ", "") == history2.replace(
"\n", ""
).replace(" ", ""):
return True
else:
return False | 1216e0ab22bdcdb6050f0f95ea398c34cd0c7513 | 573,900 |
def format_title(title):
"""
Format title for reST.
reST requires header text to have an underline at least as long as the text.
"""
underline = "=" * len(title)
return f"{title}\n{underline}" | 8363fa8e0148a183921912f5bf32544018430cb2 | 573,902 |
def _drop_geoms(gdf, geoms, series=False):
"""Drop a subset of geometries from a geopandas dataframe.
Parameters
----------
gdf : geopandas.GeoDataFrame
Dataframe of geometries to search.
geoms : list
Either a list or a list of lists.
series : bool
Search a geoseries. De... | 4a1f7824fb6f518c455f16e313ab203666701440 | 573,908 |
import hashlib
def make_file_hash(stream):
"""Calculate a hash in chunks from a stream.
Must be random-access. Resets to position 0 before and after read.
@param stream: a bytes stream to read
@returns: an MD5 hash
"""
file_hash = hashlib.md5()
stream.seek(0)
while True:
s = st... | 461d0833aa248a447a6888553acd37141fd80a9a | 573,909 |
def url_fix_common_typos(url):
"""Fix common typos in given URL like forgotten colon."""
if url.startswith("http//"):
url = "http://" + url[6:]
elif url.startswith("https//"):
url = "https://" + url[7:]
return url | 295eeaa36741f41d7c3b1f98b7c16079a8fa1331 | 573,910 |
def useFixtures(request):
"""Uses multiple fixtures as specified by name in a list"""
return [
request.getfixturevalue(item)
for item in request.param
] | 0bbcb3c8d4caf926e6000f7079e2345b1897019f | 573,914 |
def update_flag(request):
"""pytest fixture to get the --update flag from command line"""
return request.config.option.update | cef0a9de839744452ce0fd756f769cf7943a562a | 573,916 |
def extract_children(tree):
"""
Extract the immediate child nodes of a tree root
Inputs:
tree: a plan decomposition tree
Outputs:
children: the immediate child nodes of root (with their own subtrees omitted)
"""
return tuple(child if type(child[0])==str else child[0] for child in... | 25e18dc5d5eaa0cefc1d28c11e497e0b71278369 | 573,918 |
def features_labels_extractor(data):
"""
This function takes a Pandas representation of data, and transforms it to Numpy representation, while splitting data
into features and labels arrays
:param data: A Pandas dataframe
:return: A tuple of two elements respectively features and labels arrays
"... | 784b64aaabd56ce1a76aa21bd84705a80e027b6a | 573,919 |
def resize(img, width, height):
"""
Change dimensions of image
:param img: Image to be manipulated
:param width: desired width of image
:param height: desired height of image
:return: PIL image
"""
resized_img = img.resize((width, height))
return resized_img | e182b44f679de3ab0ee32289be6b446ad042af19 | 573,921 |
import torch
def generate_mask_sequence(size, device="cuda:0"):
"""
:param size: seq_len
:param device: cuda or cpu
:return: mask with future timesteps zero-valued. shape 1 x size x size
"""
x = torch.ones((size, size), device=device)
x = torch.tril(x, diagonal=-1)
return x.unsqueeze(0... | a64aa120262733a19f94690f64b8048cbd81617b | 573,923 |
def count_black_pixels(img, left=None, top=None, right=None, bottom=None):
"""
Count black pixels in an image row- and column-wise.
The black pixels in ``img`` are counted row- and column-wise and
the result is returned as a 2-tuple.
``left``, ``top``, ``right`` and ``bottom`` specify the borders ... | 88fe6f09af5fa2a33e1b8c2876ad6bc9e8fab191 | 573,924 |
def _convert_FtoK(T):
""" convert Fahrenheit to Kelvin.
:param T: Temperature (F).
:return: Temperature (K).
"""
return (T - 32.0)*5.0/9.0 + 273.15 | ee3edd6957192289a9cd5fb2b75de4917204f667 | 573,927 |
def validates_required(data, field, errors):
"""Validates if a required field is present.
Args:
data (dict): data to check whether the field is present
field (str): the field name
errors (dict): dict where errors will be put
Returns:
`errors` containing `field` if `field` i... | a531111ad8d2e423c3c274a08b8c071564d2d0b9 | 573,932 |
def misc_command_str(cmds):
"""Builds the uncategorized command string for the discord embed description."""
uncategorized_commands = ""
for cmd in cmds:
uncategorized_commands += f"`{cmd.name}`, \n"
return uncategorized_commands[:-3] | c3f0ce43ba240a60387252902f3d22d3cdaab350 | 573,934 |
def get_file_mime_type(file_name):
""" Returns mime-type of a file based on its file extension.
:param file_name: str -> name of the file
:return: str -> mime-type of the file
"""
mim_type = {
"png": "image/png",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"jfif": "im... | dc5533ed9f1f209990156e57e010b12779aeb507 | 573,940 |
def determine_angle_label(angle: str) -> str:
""" Determine the full angle label and return the corresponding latex.
Args:
angle: Angle to be used in the label.
Returns:
Full angle label.
"""
return_value = r"$\Delta"
# Need to lower because the label in the hist name is upper
... | 4ad88e7c686ff5942f13a844aa3c69f03dda0dc8 | 573,944 |
def sim_to_rgba(similarity, edge_color):
"""Convert similarity to RGBA.
Parameters
----------
similarity : float
Similarity between two answers.
edge_color : tuple
When the graph is plotted, this is the RGB color of the edge
i.e (0, 0, 1).
Returns
-------
tuple ... | 3b609dae4a8bb096333fbed76e9ea3d0ece92952 | 573,948 |
def _CheckListType(settings, allowed_type, name, allow_none=True):
"""Verify that settings in list are of the allowed type or raise TypeError.
Args:
settings: The list of settings to check.
allowed_type: The allowed type of items in 'settings'.
name: Name of the setting, added to the exception.
all... | 83a07cecaefccd543ea1198ac6aadb9153399b15 | 573,949 |
def med_factorial(n):
"""Returns n factorial. Factorial(0) = 1, Factorial(1) = 1."""
return 1 if n < 2 else n * med_factorial(n-1) | e7e8c924b89b8ce6286631fe25cc9e4dbd792cd1 | 573,950 |
def convert_str_to_link(text):
"""
Convert the repo name to link, assistant function for GET requests.
:param: ``text`` String - repository name - to convert
:return: ``Link``
"""
return 'https://github.com/' + text | 91d4d0e3b8ff35e962ff3beb8f5c358cdd691de3 | 573,952 |
def prefetch_category(pets):
"""Prefetch category related to pets in queryset."""
return pets.prefetch_related('category') | fddd6e9cac71154c3ebee7728b159646ef5a2b7e | 573,954 |
def unique_list(X):
"""unique a list with index and count
Example
-------
>>> unique_list([1,2,4,5,3,2,4])
>>> ([1, 2, 3, 4, 5], [0, 1, 4, 2, 3], [1, 2, 1, 2, 1])
"""
idx = sorted(range(len(X)), key=X.__getitem__)
X_uniq = []
X_count = []
idx_uniq = []
for i in idx:
i... | bd30946da7fcb55c853b3fb16714a02ea745f84e | 573,955 |
from datetime import datetime
def find_wait_time(t=None):
"""
Use the current time (minutes) passed the hour to determine the wait time until
the next expected period. This function should only be needed once as each interval
will be 30 minutes after the last lookup.
:param t: Time in minutes cur... | d0107af9aa9d1fc403bb5c3ddd62c631db338bc7 | 573,956 |
def first_or_default(self, default_value):
"""
Blocks until the first element emits from a BlockingObservable.
If no item is emitted when on_completed() is called, the provided default_value is returned instead
Note: This will block even if the underlying Observable is asynchronous.
:param defaul... | 746ae42eb01153e9d37286307d495466ed45bef5 | 573,957 |
def to_var(field):
"""Converts a field name int a variable (snake_case)
Args:
string: a string to be converted to a var
Returns:
a string in lower snake case
"""
return field.replace(' ', '_').lower() | 09833cba0e7c06a4353875ba1beb28530691822e | 573,960 |
def to_list(*args) -> tuple:
"""
Recives a positional args expanded and return it in list format
Args:
args:
Positional args expanded
Returns:
Compacted positional args (tuple)
"""
return args | 290ba5eb5836c0f925370611ed370ffe1ba0cd7f | 573,965 |
from typing import Union
def is_union(tp) -> bool:
""" Return True if a passed type is a typing.Union.
>>> is_union(Union[int, str])
True
>>> is_union(str)
False
>>> is_union(Union)
False
>>> is_union(List[str])
False
"""
return hasattr(tp, "__origin__") and tp.__origin__ ... | c9a23a1924d11b13e0ddeadcdd321fb6b5fa99c1 | 573,970 |
import random
def shuffle_list(py_list, inplace=False):
"""Shuffle a list
If `inplace=True` the input list is modified (faster & less memory), if `inplace=False` a new list is
generated (slower & more memory).
Args:
py_list (list): A list of elements.
inplace (bool): If `True` the inpu... | 7162e7b061ec01c92615991cd15dc928d0ed2ee4 | 573,972 |
import itertools
def get_descendants(node, depth):
"""
Returns a dict of elements {depth: nodes}
of what nodes are at each depth in the subtree whose root is
the given node.
Ex: ```
A - B - D
\- C - E
\- F
\- H
```
return for A: `{1: [B, C], 2: [D, E, F, H]}`
... | b07b61d1f716da8a49ec7e477077108031d133f0 | 573,975 |
def process_row(row, first=False):
"""
Converts a sqlite3.Row object to a string. A boolean is passed to indicate
if the supplied row is the first or only row in a list() of rows.
"""
heading = ''
if first:
heading = ' '.join(row.keys()) + '\n'
content = ' '.join(map(str, row))
r... | e2e50a56a5164e668cf31c859d9b049310cfff17 | 573,978 |
def config_xml(request):
"""Render the XML configuration as XML."""
request.response.content_type = "text/xml"
return {
"launch_url": request.route_url("lti_launches"),
"content_item_url": request.route_url("content_item_selection"),
} | 59f360d132dc5c5833ae4efd72460031f4746cc7 | 573,980 |
def get_multiplier(quality):
""" A multiplier to decide bitrate from the quality string """
if quality == "low":
return 5
elif quality == "medium":
return 6
elif quality == "good":
return 7
elif quality == "high":
return 8
return 6 | 27f94abb4b27b7663ccd6ad24e1793c657b0bd5e | 573,984 |
def render_list(inlist):
"""
Convert a list to a string with newlines.
:param inlist: The input list
:type inlist: list
:return: the list converted to a string
"""
# Return empty string to avoid returning unnecessary newlines
if not inlist:
return ''
return '\n{}\n\n'.forma... | 0d17dae8e7fc746be19e9d5d0034498741c2dc7b | 573,985 |
def all_indices(sequence, sub_sequence, offset=0):
"""
Returns list of all indices at which sub_sequence is found in sequence
"""
indices = []
i = sequence.find(sub_sequence, offset)
while i >= 0:
indices.append(i)
i = sequence.find(sub_sequence, i + 1)
return indices | 269c5632af877e10a771aee3a5d68fa8cf332aa7 | 573,989 |
import base64
def encode_lab_ctrl(infile:str, outfile:str) -> bool:
"""
takes a file and outputs a lab_ctrl file for communication between the mother and children
:param infile: name of the input file to encode
:param outfile: name of the output `lab_ctrl` file
:return: boolean representing whet... | f9aac9ea87b7430ae165a6cd4c0bde9de34d9b3b | 573,990 |
import re
def parse_links(s):
"""
Returns all links found in an input string.
Args:
s (str): input string to search for links in.
"""
return re.findall(r'(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})', str(s)) | 575dfe835579306158a6f4b753a683cd31c737db | 573,991 |
def unsort(arr, idx):
"""unsort a list given idx: a list of each element's 'origin' index pre-sorting
"""
unsorted_arr = arr[:]
for i, origin in enumerate(idx):
unsorted_arr[origin] = arr[i]
return unsorted_arr | bdb8c1d82e60b4eaf64ebf02352d170dde6015a6 | 573,992 |
import json
def course_enrollment_widget_props(context):
"""
Return a json dumps which contains all course_run's properties required by
CourseEnrollment React widget
"""
course_run = context["run"]
return json.dumps(
{
"courseRun": {
"id": course_run.id,
... | 37ed85ab262d91fa2f8788d91e321242f8631135 | 573,995 |
def _mean_list_of_list_of_matrices(lol_matrices):
"""Return mean of each matrix in list of lists of matrices."""
# Sum matrices
mean_matrices = lol_matrices[0]
for list_of_matrices in lol_matrices[1:]:
for i, matrix in enumerate(list_of_matrices):
mean_matrices[i] += matrix
# Di... | d840e0b30178eaaeccd9db5f1369d204cea9a3e7 | 573,998 |
def fix_path(s):
"""
Returns a path with problematic characters replaced by safer ones.
"""
s = s.replace('[','_b_')
s = s.replace(']','_d_')
#s = s.replace('=','_e_')
s = s.replace(':','_i_')
s = s.replace('|','_j_')
s = s.replace('\\','_k_')
#s = s.replace('/','_l_')
s = s.... | 4bcc2a6b965612016a7fb969eb26a8e8a483b9b8 | 574,001 |
def get_gradients(model):
"""Returns a list of average graident per learnable parameter"""
ave_grads = []
for p in model.named_parameters():
if p[1].requires_grad:
if p[1].grad is not None:
ave_grads.append((p[0], p[1].grad.abs().mean()))
else:
... | e54bfe16a539056aeeb941ad96ab3a0d8f4afebd | 574,003 |
import time
def timestamp(t=None):
"""Return a dictionary whose keys give different versions of the timestamp.
The dictionary will contain the following timestamp versions:
'tuple': (year, month, day, hour, min, sec)
'pretty': 'YYYY-MM-DD HH:MM:SS'
'condensed': 'YYYYMMDDHHMMSS'
... | 210f18d06ade499bcb88d7e6b529e414bdcc72cf | 574,004 |
def AddFlagPrefix(name):
"""Add the flag prefix to a name, if not present."""
if name.startswith('--'):
return name
# Does not guarantee a valid flag name.
return '--' + name | b991c79c47804c4d2f6c2ad8d3bf6bd42c272906 | 574,005 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.