content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def read_query(name: str):
""" Read in a query from a separate SQL file
Retrieves a query from a separate SQL file and stores it as a string for
later execution. Query files are stored in the utils/sql_queries directory
Args:
name: Name of the SQL file to retreive
Returns:
(str): ... | 5b1dc1f9d1aee856cd8b47651aeadf6cd9b5408d | 79,962 |
import torch
def FalseTensor(*size, device='cuda:0'):
"""
Returns a Tensor of type torch.uint8 containing only False values
Parameters
----------
*size : int
the shape of the tensor
device : str
the device to store the tensor to
Returns
-------
Tensor
a ui... | 40ea379020283e87edd74fd0a7821ea763838dc9 | 98,015 |
def quotewrap(item):
"""wrap item in double quotes and return it.
item is a stringlike object"""
return '"' + item + '"' | 91acd54664b9408832b105a01b47165b53fdf4f5 | 59,900 |
def elide_list(line_list, max_num=10):
"""Takes a long list and limits it to a smaller number of elements,
replacing intervening elements with '...'. For example::
elide_list([1,2,3,4,5,6], 4)
gives::
[1, 2, 3, '...', 6]
"""
if len(line_list) > max_num:
return... | b40930de03d3463721e3c6a27d90cb7e0dc7f01f | 138,046 |
def msize(m):
"""
Checks whether the matrix is square and returns its size.
Args:
m (numpy.ndarray): the matrix to measure;
Returns:
An integer with the size.
"""
s = m.shape[0]
if m.shape != (s, s):
raise ValueError("Do not recognize the shape (must be a square matr... | ecd67ade9f5ba1b0297252eb75235f5f9b900e95 | 559,001 |
def dec2bin(num, width=0):
"""
>>> dec2bin(0, 8)
'00000000'
>>> dec2bin(57, 8)
'00111001'
>>> dec2bin(3, 10)
'0000000011'
>>> dec2bin(-23, 8)
'11101001'
>>> dec2bin(23, 8)
'00010111'
>>> dec2bin(256)
'100000000'
"""
if num < 0:
if not width:
... | a63cfca8506d23ee69eeb112d489cf9af0542f79 | 61,928 |
import torch
def collate_train(batch):
"""
Collate function for preparing the training batch for DCL training.
:param batch: The list containing outputs of the __get_item__() function.
Length of the list is equal to the required batch size.
:return: The batch containing images and labels for DCL ... | 18c897fe862a2b75c6aea8e2e239049a1c4929ac | 433,812 |
def occurence_data(pat_df, column):
"""
Return value counts of given dataframe columns
:param pat_df: Dataframe
:param column: Column included in Dataframe
:return: Series of value occurences
"""
return pat_df[column].value_counts() | 7bec7cec90c0f575aa5e2dfd4855106caf03a31a | 90,794 |
def get_rec_names(study_folder):
"""
Get list of keys of recordings.
Read from the 'names.txt' file in study folder.
Parameters
----------
study_folder: str
The study folder.
Returns
----------
rec_names: list
LIst of names.
"""
with open(study_folder / 'na... | ab9c7eddc0ce593ddcea129c2122e753a94432bf | 648,436 |
import six
import operator
def inclusion_unlimited_args_kwargs(one, two='hi', *args, **kwargs):
"""Expected inclusion_unlimited_args_kwargs __doc__"""
# Sort the dictionary by key to guarantee the order for testing.
sorted_kwarg = sorted(six.iteritems(kwargs), key=operator.itemgetter(0))
return {"resu... | 58c903759bc10a3fb215cf5cdbeca9deef72c0d3 | 589,318 |
def md_entry_same(entry_name, s1, s2):
"""Returns (s1 and s2 have the same value for entry_name?, message)."""
s1_val = s1[entry_name]
s2_val = s2[entry_name]
return (s1_val == s2_val, "(" + entry_name + ") " + repr(s1_val) + ", " + repr(s2_val)) | 61d1cae8b70a810e9ff85e66a1667f6cb2431f49 | 321,873 |
def format_score(logpath, log, markup):
"""Turn a log file JSON into a pretty string."""
output = []
output.append('\nLog: ' + logpath)
if log['unrecognized']:
output.append('\nLog is unrecognized: {}'.format(log['unrecognized']))
else:
if log['flagged']:
output.append('\... | c3ac492375b72d05481a3a2dc2986149f79b405e | 664,860 |
def is_categorical(s, column=None):
"""Check if a pandas Series or a column in a DataFrame is categorical.
s (pandas.Series or pandas.DataFrame): Series to check or dataframe with
column to check.
column (str): Column name. If a column name is given it is assumed that
`s` is a `pandas.D... | 21eecc2b6760ffa88194b9cd59c6133ec9c1ba18 | 552,661 |
def create_datafile_url(base_url, identifier, is_filepid):
"""Creates URL of Datafile.
Example
- File ID: https://data.aussda.at/file.xhtml?persistentId=doi:10.11587/CCESLK/5RH5GK
Parameters
----------
base_url : str
Base URL of Dataverse instance
identifier : str
Identifie... | d6deece390b3028f45b27a0f6aa1864688ed97fa | 24,053 |
def project_grad(g):
"""Project gradient onto tangent space of simplex."""
return g - g.sum() / g.size | 41a50bf9d9e8e0efbbe703758385b7da6e2a26ca | 404,552 |
def IsGlobalTargetGrpcProxiesRef(target_grpc_proxy_ref):
"""Returns True if the target gRPC proxy reference is global."""
return target_grpc_proxy_ref.Collection() == 'compute.targetGrpcProxies' | 20ea7d0baf818a2435506a7e0a23f7c1a0921f36 | 653,677 |
def interpretStatus(status, default_status="Idle"):
"""
Transform a integer globus status to
either Wait, Idle, Running, Held, Completed or Removed
"""
if status == 5:
return "Completed"
elif status == 9:
return "Removed"
elif status == 1:
return "Running"
elif st... | 578ace00f98da7f01f42a5ba03cd9a249e08f7ad | 365,198 |
def conv_kwargs_helper(norm: bool, activation: bool):
"""
Helper to force disable normalization and activation in layers
which have those by default
Args:
norm: en-/disable normalization layer
activation: en-/disable activation layer
Returns:
dict: keyword arguments to pass... | 56c578511220a19a614255b83ff1c031814ed5ae | 427,590 |
import math
def rmsd(V, W):
"""
Calculate Root-mean-square deviation from two sets of vectors V and W.
Parameters
----------
V : array
(N,D) matrix, where N is points and D is dimension.
W : array
(N,D) matrix, where N is points and D is dimension.
Returns
-------
... | 36712ed6666c45378ef6959ddcd300a907c121a1 | 364,746 |
def med_min_2darray(a):
"""Takes in a list of lists of integers and returns the minimum value."""
return min(min(inner) for inner in a) | c30a7588a11e2c23829fe73b6d84ffdaee8fb321 | 32,334 |
def _cast_to_int(num, param_name):
"""Casts integer-like objects to int.
Args:
num: the number to be casted.
param_name: the name of the parameter to be displayed in an error
message.
Returns:
num as an int.
Raises:
TypeError: if num is not integer-like.
"""
try:
# ... | 493c9010054c5ff0d80bd7f304de97d3b0e4776c | 293,377 |
def prefix_by_topic(topic_str):
"""
Return a topic-based prefix to produce distinct output files.
`+` in the topic is replaced with `ALL`.
The last element, `#` is left out from the prefix.
See https://digitransit.fi/en/developers/apis/4-realtime-api/vehicle-positions/#the-topic
"""
els = t... | fd1288e664a94277985672f6af38314a805de6be | 506,089 |
def split_by_two_strings(line, str1, str2):
"""Split the input line into three parts separated by two given strings."""
# Start of second part in the input string.
i1 = line.index(str1) + len(str1)
# End of second part in the input string.
i2 = line.index(str2)
# Now we know where the second p... | 4883075e61185b9bfc0490586cb08c66db603a7a | 620,233 |
def get_variant_prices_from_lines(lines):
"""Get's price of each individual item within the lines."""
return [
line.variant.get_price()
for line in lines
for item in range(line.quantity)] | ec6414ec638da574d1665a93c33ccd1b68f58cf9 | 241,681 |
async def client_send(ctx, msg, embed=1):
"""Sends messages to Discord context. Easily makes messages 'embeded' if embed == 1"""
try:
msg = str(msg)
if embed == 1:
m = await ctx.send("```" + msg + "```")
else:
m = await ctx.send(msg)
return m
except:
... | 6429401c692ff3e09fb8cb066706ef0168230c6f | 550,968 |
from typing import List
def split_commits_data(
commits_data: str,
commits_sep: str = '\x1e',
) -> List[str]:
"""
Split data into individual commits using a separator.
:param commits_data: the full data to be split
:param commits_sep: the string which separates individual commits
:return:... | 5b698df35b483628b1f6e5216ebf20174359b5fd | 166,730 |
def create_prop_dictionary(properties_list):
"""
Creates a dictionary of all properties from the properties list
:param properties_list: list of property objects
:return: dictionary of property objects grouped by unique key (name, unit, condition name, condition unit, method and data type)
"""
... | decc20437814386c3499c41c4d6358ea5ab088a7 | 439,438 |
def identity_transformation(data):
"""Default coder is no encoding/decoding"""
return data | effec06dcb5627f35224bebcd68e19ba249a8789 | 161,910 |
from functools import reduce
import operator
def _vector_add(*vecs):
"""For any number of length-n vectors, pairwise add the entries, e.g. for
x = (x_0, ..., x_{n-1}), y = (y_0, ..., y_{n-1}),
xy = (x_0+y_0, x_1+y_1, ..., x_{n-1}+y{n-1})."""
assert(len(set(map(len, vecs))) == 1)
return [reduce(ope... | d5a8c9a6dc42c65e879b721e75c42abd17d97ef0 | 97,163 |
from typing import Tuple
def participant_names(redcap_record: dict) -> Tuple[str, ...]:
"""
Extracts a tuple of names for the participant from the given
*redcap_record*.
"""
if redcap_record['participant_first_name']:
return (redcap_record['participant_first_name'], redcap_record['particip... | d0cd8aa80f585b04828bf52ef1ff76ac5274fd3d | 504,538 |
def get_accounts_aws(self, filter=""):
"""Retrieves AWS account information from Polaris
Args:
filter (str): Search string to filter results
Returns:
dict: Details of AWS accounts in Polaris
Raises:
RequestException: If the query to Polaris returned an error
"""
try:
... | 87ef43ccb7398afced32afb3aaa4a2e81c5d6f88 | 530,679 |
def arg_type_to_string(arg_type) -> str:
"""
Converts the argument type to a string
:param arg_type:
:return:
String representation of the argument type. Multiple return types are
turned into a comma delimited list of type names
"""
union_params = (
getattr(arg_type, '_... | b55506d9a0f9eec2468a05aa839dbd999ce9b42a | 245,040 |
def combine_biases(*masks):
"""Combine attention biases.
Args:
*masks: set of attention bias arguments to combine, some can be None.
Returns:
Combined mask, reduced by summation, returns None if no masks given.
"""
masks = [m for m in masks if m is not None]
if not masks:
return None
assert ... | 994241493b94139f84ec2e944b5a66fbe0b2349b | 262,664 |
from pathlib import Path
def find_source_dir_from_file(filepath: Path):
"""Find the source directory of the Sphinx project."""
conf_file = Path("conf.py")
source_dir = filepath.parent
root = Path("/")
while source_dir != root:
path = source_dir / conf_file
if path.exists():
... | a0f1e3e25c588b11379f5e1e0356efce43e070ac | 243,786 |
import socket
def localhost_has_free_port(port: int) -> bool:
"""Checks if the port is free on localhost.
Args:
port (int): The port which will be checked.
Returns:
bool: True if port is free, else False.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
is_success ... | f64d1570756462bf9cec37d34b1d942d94a23e75 | 377,245 |
import torch
def generate_spatial_noise(size, device, *args, **kwargs):
""" Generates a noise tensor. Currently uses torch.randn. """
# noise = generate_noise([size[0], *size[2:]], *args, **kwargs)
# return noise.expand(size)
return torch.randn(size, device=device) | 5c9116fdc132d59e4a0ccc6c5674042f70533efe | 26,046 |
def get_first_child(node, type):
"""Return the first child of |node| that has type |type|."""
index = node.first_child_matching_class(type)
return node[index] | 090711b92a3a62ad9ee3ed3d2910652c9849d87f | 464,729 |
def add_normalized_column(df, column_name):
"""
Normalize a column and add it to the DataFrame.
Parameters
----------
df: DataFrame
Input DataFrame containing the column to normalize.
column_name: string
Name of the column to normalize.
Returns
-------
out: DataFram... | 0f9d556d12912ee1c659d9ae497f8a6f9b193953 | 459,853 |
def make_reverse_dict(in_dict, warn=True):
""" Build a reverse dictionary from a cluster dictionary
Parameters
----------
in_dict : dict(int:[int,])
A dictionary of clusters. Each cluster is a source index and
the list of other source in the cluster.
Returns
-------
ou... | 7126107779524026f3bf04ec37235413984ea583 | 680,941 |
def stations_highest_rel_level(stations, N):
"""For a list of MonitoringStaton objects (stations), returns a list of the N stations
at which the water level, relative to the typical range, is highest"""
#Filter list as to not include stations without relative water level
new_stations = list(filter(lamb... | 61b9a2282678e13cce238b665009368f4e13043b | 85,945 |
def MeanAveragePrecision(predictions, retrieval_solution, max_predictions=100):
"""Computes mean average precision for retrieval prediction.
Args:
predictions: Dict mapping test image ID to a list of strings corresponding
to index image IDs.
retrieval_solution: Dict mapping test image ID to list of g... | 089baa160e4c01032e759d6479eb48dd34032100 | 539,848 |
def safe_inserter(string, inserter):
"""Helper to insert a subject name into a string if %s is present
Parameters
----------
string : str
String to fill.
inserter : str
The string to put in ``string`` if ``'%s'`` is present.
Returns
-------
string : str
The mod... | 91a86856061b8db8645d87d3313130ffe89a8a96 | 515,088 |
def undulating(number):
""" Returns True if number is undulating """
if number < 100:
return False
number = str(number)
for idx in range(len(number)-2):
if number[idx] != number[idx+2]:
return False
return True | e114bebb260c8c1f895fcd1f9fefb3e14b38f9c6 | 609,332 |
def parse_result_line(line):
"""Take a line consisting of a constituency name and vote count, party id
pairs all separated by commas and return the constituency name and a list of
results as a pair. The results list consists of vote-count party name pairs.
To handle constituencies whose names include a... | 8808f09fad8ba37896826e8ccf7ebe68bf9a516f | 369,850 |
def is_ip_per_task(app):
"""
Return whether the application is using IP-per-task.
:param app: The application to check.
:return: True if using IP per task, False otherwise.
"""
return app.get('ipAddress') is not None | 7de05a7db5eb886bea2687492585b554f898fc41 | 669,691 |
def column(results):
"""
Get a list of values from a single-column ResultProxy.
"""
return [x for x, in results] | 352a604eb9bb863c8bf71c7c96df6c2cbcd226c8 | 53,677 |
def unflatten_dict(d, delimiter = "/"):
"""Creates a hierarchical dictionary by splitting the keys at delimiter."""
new_dict = {}
for path, v in d.items():
current_dict = new_dict
keys = path.split(delimiter)
for key in keys[:-1]:
if key not in current_dict:
current_dict[key] = {}
... | edede31b6fc22a82f70e085b7fcd3a8ace030212 | 464,327 |
def parse_subnets(subnets):
"""
Parse the Subnets dict, checking it is in correct format.
Raises errors if there is a format violation.
Arguments:
subnets : the subnets dict
Returns:
parsed_subnets : parsed Subnet dict
"""
if not isinstance(subnets, dict):
raise Val... | 72d56b25ce269977e2ddad6531eec8ca7e140e34 | 312,375 |
def _get_outside_corners(corners, board):
"""
Return the four corners of the board as a whole, as
(up_left, up_right, down_right, down_left).
"""
xdim = board.n_cols
ydim = board.n_rows
if corners.shape[1] * corners.shape[0] != xdim * ydim:
raise Exception(
"Invalid numb... | 647a5f42192a312c7a661880d1d2750ebf70e154 | 651,335 |
import importlib
def import_object(obj):
"""Import an object from its qualified name."""
if isinstance(obj, str):
package, name = obj.rsplit('.', 1)
return getattr(importlib.import_module(package), name)
return obj | c0e4816c6db6bc2c826ba4d8498e7081daa9be48 | 555,416 |
import re
def snakeCasetoCamelCase(a_string):
"""assumes a_string is a string in snake_case
returns a new string, representing a_string in camelCase"""
pattern = "(\w)(_)(\w)"
new_string = re.sub(pattern, r"\1\3", a_string)
return new_string | 4f8b588cdba4fbc73e997d14c7c0f70e7a2cee57 | 552,992 |
from re import findall
def to_integer(given_input: str):
"""
Finds the number in a given input(should be a string with numbers) using regular expression.
>>> to_integer('abc')
0
>>> to_integer('1')
1
>>> to_integer('abc123')
'123'
>>> to_integer('abc123abc')
'123'
>>> to_i... | a65977833883962cf6327caf3873456b907a6133 | 376,034 |
def _validate_scp_time(the_sicd):
"""
Validate the SCPTime.
Parameters
----------
the_sicd : sarpy.io.complex.sicd_elements.SICD.SICDType
Returns
-------
bool
"""
if the_sicd.SCPCOA is None or the_sicd.SCPCOA.SCPTime is None or \
the_sicd.Grid is None or the_sicd.G... | 6d84c1e204e419042c346b668bd50a7bf3e83406 | 397,577 |
def directory_tree(tmp_path):
"""Create a test directory tree."""
# initialize
p = tmp_path / "directory_tree"
p.mkdir()
p.joinpath("file1").write_text("123")
p.joinpath("dir1").mkdir()
p.joinpath("dir1/file2").write_text("456")
p.joinpath("dir1/file3").write_text("789")
return p | 371dc92f1708bf7de7bd66b19b7a1e1ac4a8e3ff | 323,156 |
def intstrtuple(s):
"""Get (int, string) tuple from int:str strings."""
parts = [p.strip() for p in s.split(":", 1)]
if len(parts) == 2:
return int(parts[0]), parts[1]
else:
return None, parts[0] | eb105081762e5d48584d41c4ace5697fccb8c29e | 602,715 |
def findSmallerInRight(string, start, end):
"""
Counts the number of caracters that are smaller than
string[start] and are at the right of it.
:param string: Input string.
:param start: Integer corresponding to the index of the starting character.
:param end: Integer correspo... | b9cc36373706a305565804831415efe6e0b0d424 | 116,281 |
def dict_is_song(info_dict):
"""Determine if a dictionary returned by youtube_dl is from a song (and not an album for example)."""
if "full album" in info_dict["title"].lower():
return False
if int(info_dict["duration"]) > 7200:
return False
return True | b4792a850be39d4e9dc48c57d28d8e4f50751a75 | 677,740 |
def get_n_last_observations_from_trajectories(trajectories, n, ascending=True):
"""
Get n extremity observations from trajectories
Parameters
----------
trajectories : dataframe
a dataframe with a trajectory_id column that identify trajectory observations. (column trajectory_id and jd have ... | 5c01eefb4d2de6da74a8a7f7967a7ee56ea4a78d | 129,654 |
def get_arg_to_class(class_names):
"""Constructs dictionary from argument to class names.
# Arguments
class_names: List of strings containing the class names.
# Returns
Dictionary mapping integer to class name.
"""
return dict(zip(list(range(len(class_names))), class_names)) | ec992707772716b2707ecb881a700c5726293745 | 510,902 |
def has_encountered_output_source(context):
"""Return True if the current context has already encountered an @output_source directive."""
return 'output_source' in context | 3b78bcb40e8e4aa6b9ea269b0031d03803cae3b9 | 192,455 |
def writeSeg(BCFILE, title, segID, planeNodeIDs):
"""write face segments to BC input file
Args:
BCFILE: file IO object
title (str): header comment line
segID (int): segment ID #
planeNodeIDs (int): 2D array
Returns:
segID (inc +1)
"""
BCFILE.write('*SET_SEGMENT_TITLE... | a82848e3664229ca9d4bcaa78dc8036e731c96a0 | 83,634 |
from typing import List
def get_requires() -> List[str]:
""" Get Requires: Returns a list of required packages. """
return [
'Click',
'cupy',
'tqdm',
'appdirs'
] | 2fa8988e4ce8d2d5fe6cad9d9a995dad899ebb8a | 364,258 |
def github_repository_name(url):
"""
Get the repository name from a Github URL
"""
repo = url.rstrip("/")
if repo.endswith(".git"):
repo = repo[:-4]
_, name = repo.rsplit("/", 1)
return name | 366185873f1a083af8b219359d1c3c30cad7d222 | 336,574 |
def github_paginate(session, url):
"""Combines return from GitHub pagination
:param session: requests client instance
:param url: start url to get the data from.
See https://developer.github.com/v3/#pagination
"""
result = []
while url:
r = session.get(url)
result.extend(r.... | 6c951f0dadc3d6b8c0bae7ada61bbd46e085d544 | 643,200 |
def chunk(arr:list, size:int=1) -> list:
"""
This function takes a list and divides it into sublists of size equal to size.
Args:
arr ( list ) : list to split
size ( int, optional ) : chunk size. Defaults to 1
Return:
list : A new list containing the chunks of the original
... | 0aa82c11fdc63f7e31747c95e678fdcac4571547 | 686,877 |
def split_rows(array:list, l:int=9) -> list:
"""
Transforms a 1D list into a list of lists with every list holding l
elements. Error is raised if array has a length not divisible by l.
"""
if len(array) % l != 0:
raise ValueError("split_rows(): Rows in list have different lengths")
retu... | 3f9934f92f6891f95c868e207831634f62e2eaed | 90,785 |
def fixture_other_case() -> str:
"""Return the case id that differs from base fixture"""
return "angrybird" | 9c31d9b1a4f24d2859829be84cf8f4f526598dfb | 197,614 |
import re
def prune_protected(mailboxes, ns):
""" Remove protected folders from a list of mailboxes
Exchange has several protected folders that are used for non-mail
purposes, but still appear in the list. Therefore, we want to exclude
these folders to prevent reading non-mail items.
Args:
... | 29a709683b40a89c4c1f422860166681dd1f2f7d | 513,757 |
def remove_hetatm(filename_in, file_out, remove_all):
"""Remove HETATM and related lines.
If remove_all is False, remove only element X which happens in many PDB
entries but is not accepted by pointless, refmac, phaser, etc
"""
# we could instead zero occupancy of the atoms and replace X with Y
... | 74278aa9c42334251924856350ce339b62366b44 | 479,141 |
def _urpc_test_func_2(buf):
"""!
@brief u-RPC variable length data test function.
@param buf A byte string buffer
@return The same byte string repeated three times
"""
return buf*3 | f13f7dcf45eaa0706b69eb09c63d29ba2bbd3d60 | 1,596 |
import gzip
def read_consanguineous_samples(path, cutoff=0.05):
"""
Read inbreeding coefficients from a TSV file at the specified path.
Second column is sample id, 6th column is F coefficient. From PLINK:
FID, IID, O(HOM), E(HOM), N(NM), F
Additional columns may be present but will be ignored.
... | be3515e6704966ae927bfaff2594be9191063889 | 6,722 |
def is_reserved_name(name):
"""Tests if name is reserved
Names beginning with 'xml' are reserved for future standardization"""
if name:
return name[:3].lower() == 'xml'
else:
return False | 29ca0ec73b18259126a61aaf335a7d0946b72eb6 | 696,787 |
def prompt(message, values=None):
"""Prompt a message and return the user input.
Set values to None for binary input ('y' or 'n'), to 0 for integer input, or to a list of possible inputs.
"""
if values is None:
message += ' (y/n)'
message += ' > '
while 1:
ans = input(message)
... | 4d6b87b84ed1dfd95722e0055a8df3b1b34f1e84 | 16,212 |
def parse_input(input_file):
"""
Processes the input with song titles.
See above format.
Returns a dict of mapping number -> [title1, title2, ...]
"""
tdb = {}
disc_no = -1
with open(input_file) as fin:
for line in fin:
line = line.strip()
if 'disc ' in l... | 652334d928df97f1456cedcd6250444e60b8207a | 543,389 |
def is_type(indexed_token, tag_type):
"""Tests if the given token was tagged with the given tag type."""
return indexed_token.has_key('tag') and (indexed_token['tag'] == tag_type) | 48a23454459080d9677bfc5f78529407e54864bc | 544,993 |
import re
def get_root_url(the_line):
"""
Get the root URL from the line
:param the_line: the line
:return: either the root URL or None
"""
ret = re.search('https://[^/]*/[^/]*/', the_line)
if ret:
return ret.group(0)
return None | a4a4a283664e8d80088c3ec5e349aae3d3f34dd5 | 607,668 |
import six
def _get_context(estimator=None):
"""Get context name for warning messages."""
if estimator is not None:
if isinstance(estimator, six.string_types):
estimator_name = estimator.lower()
else:
estimator_name = estimator.__class__.__name__.lower()
estima... | 5212bad031a8f953b8f827b8b930da11e60e411c | 506,430 |
def strictly_equal(obj1: object, obj2: object) -> bool:
"""Checks if the objects are equal and are of the same type."""
return obj1 == obj2 and type(obj1) is type(obj2) | 00fcfa2ab3bbbfa40fa03731a553ae9f7224ea57 | 531,135 |
def exception_redirect(new_exception_class, old_exception_class=Exception, logger=None):
"""
Decorator to replace a given exception to another Exception class, with optional exception logging.
>>>
>>> class MyException(Exception):
... pass
>>>
>>> @exception_redirect(MyException)
..... | bef002fc5cf15ebc1517fd1ea9ca78fb2b4be3eb | 568,146 |
def yubikey_get_yubikey_id(yubikey_otp):
"""
Returns the yubikey id based
:param yubikey_otp: Yubikey OTP
:type yubikey_otp: str
:return: Yubikey ID
:rtype: str
"""
yubikey_otp = str(yubikey_otp).strip()
return yubikey_otp[:12] | 32de713e8d4cf3b6a5ca908976b73f7f9eb69561 | 276,686 |
import torch
def load_weights_from_path(model, path):
"""load weights from file
Args:
model (Net): Model instance
path (str): Path to weights file
Returns:
Net: loaded model
"""
model.load_state_dict(torch.load(path))
return model | 7d684d616bd90eea43e73362f31647692cbb0f8e | 202,407 |
def directory_current_user(request):
""" Return the current user directory """
path = request.user.get_home_directory()
try:
if not request.fs.isdir(path):
path = '/'
except Exception:
pass
return path | c73d0d7a50cfb7f7b4942919e79fbf6c7878a269 | 395,468 |
def create_dict_playlists_playlistids(p_list, pid_list):
""" Create a dictionary of playlists and playlist ids """
playlists_and_playlist_ids = {}
for i in range(len(p_list)):
playlists_and_playlist_ids[p_list[i]] = pid_list[i]
return playlists_and_playlist_ids | 173850ed85b3dc774ddea14674e22e701991c807 | 701,685 |
import typing
import types
def is_iterable(obj: typing.Any) -> bool:
"""
>>> is_iterable([])
True
>>> is_iterable(())
True
>>> is_iterable([x for x in range(10)])
True
>>> is_iterable((1, 2, 3))
True
>>> g = (x for x in range(10))
>>> is_iterable(g)
True
>>> is_iter... | fcd260fa3dace6d0de7dcbbd5ad5d9899ed6bb7c | 489,820 |
def color565(red, green=0, blue=0):
"""
Convert red, green and blue values (0-255) into a 16-bit 565 encoding.
"""
try:
red, green, blue = red # see if the first var is a tuple/list
except TypeError:
pass
return (red & 0xf8) << 8 | (green & 0xfc) << 3 | blue >> 3 | 4c1f2c28313c35f839fa189b45fb15abfa715cd1 | 643,010 |
from typing import Mapping
def _flatten_dict(d, prefix=''):
"""
Convert a nested dict: {'a': {'b': 1}} -> {'a--b': 1}
"""
out = {}
for k, v in d.items():
if isinstance(v, Mapping):
out = {**out, **_flatten_dict(v, prefix=prefix + k + '--')}
else:
out[prefix... | fb19771e7aad5b1df832ae95694b2182bcde2725 | 148,057 |
def mass(self):
"""get mass"""
return self._mass | 522c1acb9c154f707ece2a75ad675c7e9b35a338 | 331,169 |
def x_forwarded_ip(request):
"""
Returns the IP Address contained in the 'HTTP_X_FORWARDED_FOR' header, if
present. Otherwise, `None`.
Should handle properly configured proxy servers.
"""
ip_address_list = request.META.get('HTTP_X_FORWARDED_FOR')
if ip_address_list:
ip_address_list ... | 3b346c3fe2404cf637cea66a12f89e41ad87aed6 | 146,110 |
def float2String(input, ndigits=0):
"""
Round and converts the input, if int/float or list of, to a string.
Parameters
----------
input: int/float or list of int/float
ndigits: int
number of decimals to round to
Returns
-------
output: string or list of strings
dep... | 3c2794e1d9b3b4809eb5878895cbc1b246120c94 | 526,323 |
def remove_forbidden_keys(data):
"""Remove forbidden keys from data
Args:
data (list): A list of dictionaries, one per transactions
Returns:
list: A list of dictionariess, one per transaction, with forbidden keys removed
"""
# There are different forbidden keys based on the report... | c0aea19a433e36ab97a827045d576311761a8506 | 220,358 |
def RestoreListType(response, key_triggers=()):
"""Step (recursively) through a response object and restore list types
that were overwritten by SOAPpy. Lists with only one element are converted by
SOAPpy into a dictionary. This handler function restores the proper type.
Args:
response: dict Response data... | 414c7eb4c88838ea6d21977b1f50e16e3db80a13 | 148,418 |
def get_asset_url(release, quiet=False):
"""
get the assets url from the release information
:return: the assets_url
"""
return release["assets_url"] | 38815dce5158c4980e57a4cf7aa7a386e371e57f | 632,206 |
def hour_of_day(datetime_col):
"""Returns the hour from a datetime column."""
return datetime_col.dt.hour | 18b2f6e16ccbcb488f3863968466fda14f669d8b | 706,249 |
def find_service_by_type(cluster, service_type):
"""
Finds and returns service of the given type
@type cluster: ApiCluster
@param cluster: The cluster whose services are checked
@type service_type: str
@param service_type: the service type to look for
@return ApiService or None if not... | fd04adce95c71499e17a143d7c94c0cf1aa603c9 | 28,818 |
def largest_factor(n):
"""Return the largest factor of n*n-1 that is smaller than n.
>>> largest_factor(4) # n*n-1 is 15; factors are 1, 3, 5, 15
3
>>> largest_factor(9) # n*n-1 is 80; factors are 1, 2, 4, 5, 8, 10, ...
8
"""
factor = n - 1
while factor > 0:
if (n*n-1) % factor ... | deaad22f8a5c11a696c8410b8d179b0dc38c8a93 | 636,311 |
def add_required_cargo_fields(toml_3p):
"""Add required fields for a Cargo.toml to be parsed by `cargo tree`."""
toml_3p["package"] = {
"name": "chromium",
"version": "1.0.0",
}
return toml_3p | 1c8d061f8b53fe3cd82c5c2130e13aef07a92670 | 146,192 |
import math
def quat_to_euler(q):
"""returns yaw, pitch, roll
at singularities (north and south pole), assumes roll = 0
"""
# See http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/
eps=1e-14
qw = q.w; qx = q.x; qy = q.z; qz = -q.y
pitch_y = 2*qx*qy + 2... | 94c1c36c20abeb0875f16ff83bc5aaa3dadd5ffd | 159,596 |
def describe(df):
"""Shorthand for df.describe()
Args:
df (`pandas.DataFrame`): The dataframe to describe
Returns:
summary: Series/DataFrame of summary statistics
"""
return df.describe() | 25a637bf7df4ca566ed871f91a3d8860e32eee62 | 411,069 |
def ternary_expr(printer, ast):
"""Prints a ternary expression."""
cond_str = printer.ast_to_string(ast["left"]) # printer.ast_to_string(ast["cond"])
then_expr_str = printer.ast_to_string(ast["middle"]) # printer.ast_to_string(ast["thenExpr"])
else_expr_str = printer.ast_to_string(ast["right"]) # pri... | f88fc65b684bff7ad61e0bc64d17b65bbe7735e5 | 28,675 |
def _combine_paths(path):
"""
Turn path list into edge list.
:param path: List. A list of nodes representing a path.
:returns: List. A list of edge tuples.
"""
edges = []
for i, node in enumerate(path[1:]):
edges.append((path[i], node))
return edges | 7dae202ad637a9360e5a929840989aab34366ece | 268,619 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.