content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def bt_analysis_tcm(bta, temp_min=300, temp_max=400, doping_min=1e19, doping_max=1e22):
"""
Performs analysis for transparent conductive materials
Focuses on T=300-400K and Doping=1E19-1E22
:param bta: Boltztrap analyzer object
:return: dict of conductivity and effective mass
"""
d = {}
... | a80262ddfd4be0aa99da250ca7b0bd9b2e085b6e | 647,926 |
def clipping_dist(delta):
"""
Returns the average distance between residues i and j, based on experimental data.
Parameters
----------
delta : int
The delta between residue indexes i and j.
Returns
-------
float
The average distance.
"""
if delta == 1:
r... | 395354855944724f20986be3800baa2fbd378fd2 | 647,936 |
def _linestring_to_segments(arr):
"""
Translates line strip to segments
:param arr: numpy.array
Array of line strip vertices
:return: numpy.array
Line segments
"""
return [arr[i / 2] for i in range(0, len(arr) * 2)][1:-1] | e0c642bd245a9f42cc55a8f5e53686a939ba6e3c | 647,939 |
import hashlib
def CalcMd5(data):
"""
calculate the md5 of data
Args:
data : the data to calculate
Returns:
return md5 of data, if fail to calculate return None
"""
try:
md5 = hashlib.md5()
md5.update(data)
return md5.hexdigest()
except BaseExcepti... | 7aaac197fcfac0bbfc1773eeb23096f657be7b90 | 647,940 |
def hztous(hz):
"""
Convert frame rate in hz to microseconds between frames
"""
return (1/hz)*10**6 | b66f2e2fad781beda2a2ebdae4c1619862f3b621 | 647,946 |
import yaml
def read_cadence_file(filename):
"""
Parse a cadence file.
Args:
filename (str): Name of cadence file
Returns:
cadence_dict: dictionary containing cadence file contents
"""
with open(filename, 'r') as f:
cadence_dict = yaml.safe_load(f)
... | 38d09e4f7a9dd042b65ff5c46756c02d7b43aff5 | 647,954 |
def get_table_position(screen_layout):
""" return first position of table encountered within screen layout
"""
for _, data in screen_layout.items():
if data.get('table'):
return data['position']
return None | 0fe1f0ef0de3c17e7e0371c428a83a5c407de5a7 | 647,955 |
def same_fringe(tree1, tree2):
""" Detect is the given two trees have the same fringe. A fringe is a list
of leaves sorted from left to right.
"""
def is_leaf(node):
return len(node['children']) == 0
def in_order_traversal(node):
if node == None:
return []
if is... | 5b7f69cae14f7611e558ca7e88a90fa02cc3f893 | 647,958 |
def get_EVR(pkg):
"""
Return 3-tuple EVR (_epoch_, version, release) of the given RPM.
Epoch is always set as an empty string as in case of kernel epoch is not
expected to be set - ever.
The release includes an architecture as well.
"""
return ('', pkg.version, '{}.{}'.format(pkg.release, ... | 084d05ad9a4420ad8ebe888b1cae3033ff7c2a6e | 647,959 |
def get_hi_file_at_long(longitude, sgps_hi_file_list, edge_size=0.5):
"""
Identify the best SGPS file to retrieve data from at the supplied Galactic
longitude. Will try to find a file where the longitude is at least edge_size
away from the edge of the cube, but will fall back to any file with data
c... | 8579f4a5c650d1c73616ae3f2b77120f4fcf4e87 | 647,960 |
def number_of_ad_performance_threads() -> str:
"""The number of threads used to download ad performance"""
return '10' | a00ea3b634dfe33d82566c62da9456c7ee9fd3e6 | 647,962 |
def formatOneTextRow(fields, values = None, fieldDLM="|@|"):
"""
Parameters in:
fields - a list of fields name
values - a dictionary of values with fields name, Default None
fieldDLM - delimeter of values, default "|@|"
Return:
if values is None, return fields with delimeters... | c4a87c87e83f0e8dcc2b88cff9007eed1586cebf | 647,967 |
def sub_domain_to_tld(domain):
"""
Turn the input domain to get Top Level Domain
Args:
domain: any domain value
Returns:
TLD of input domain
"""
domain_list = domain.split('.')[-2:]
return '.'.join(domain_list) | 676f5c91427e46e662cf94b1764911f7a22e396e | 647,968 |
def is_file_readable(file, strict=False):
"""Check if a file exists and is readable.
Parameters
----------
file : :class:`str`
The file to check.
strict : :class:`bool`, optional
Whether to raise the exception (if one occurs).
Returns
-------
:class:`bool`
Wheth... | cdb8b2c41cf7439dbd8a364cf883fe6d3e4cf845 | 647,969 |
def assert_quality_condition(options, sds_file):
"""Assert that the SDSFile quality is in a list given in the options.
Parameters
----------
options : `dict`
The rule's options.
- ``qualities``: List of qualities to accept (`list` of `str`)
sds_file : `SDSFile`
The file bein... | 3b9ba7653e338f27e509af01a36022aa2369e3a4 | 647,970 |
import six
def pretty_unicode(string):
"""
Make sure string is unicode, try to decode with utf8, or unicode escaped string if failed.
"""
if isinstance(string, six.text_type):
return string
try:
return string.decode("utf8")
except UnicodeDecodeError:
return string.decod... | 3857d63817bd99acc2cf5d0e4106055152d66bc1 | 647,974 |
import pkg_resources
def get_required(dist):
"""Return a set with all distributions that are required of dist
This also includes subdependencies and the given distribution.
:param dist: the distribution to query. Can also be the name of the distribution
:type dist: :class:`pkg_resources.Distribution... | aeb18cb99af0bfc498d87b63dbdc131dad5bcafc | 647,975 |
def read_POPI_points(file_name):
"""
Read the Point-validated Pixel-based Breathing Thorax Model (POPI) landmark points file.
The file is an ASCII file with X Y Z coordinates in each line and the first line is a header.
Args:
file_name: full path to the file.
Returns:
(list(tuple)): L... | bcf5f0b447ab0fe5ab0ca7aa93cc129927425730 | 647,978 |
def update_from_dict(obj, update_dict):
"""
A function to update an object instance with values stored in a dictionary.
In some cases preferred over calling filter(pk=pk).update(**dict) because update does not send signals.
:param obj: The object instance to be updated
:param update_dict: A dictiona... | 1f8e96b7de2435edd597409247c69c693420fde0 | 647,979 |
import math
def haversine_bearing(lat1, lon1, lat2, lon2):
"""
Calculate the bearing from 1 point to 1 other
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2])
dlon = lon2 - lon1
... | bf9c4064ab47454e243e773f0b5e0959da7c1628 | 647,981 |
def get_style(line):
""" get plot styles from Line2D object
mostly copied from "Line2D.update_from"
Args:
line (Line2D): source of style
Return:
dict: line styles readily usable for another plot
"""
styles = {
'linestyle': line.get_linestyle(),
'linewidth': line.get_linewidth(),
'color... | 49a239a9934101754b2ef65354e7740369cb7672 | 647,984 |
from typing import Dict
from typing import Any
from typing import Optional
def _process_api_resource(permission_resource: Dict[str, Any], api_operation: str) -> Optional[bool]:
"""Helper method to check if the api action permission is in this API resource
Args:
permission_resource: The dictionary for ... | 43b3cdf7ddb398594651b3b7dce662f851fd5f58 | 647,985 |
def windows_translator(value):
"""Translates a "windows" target to windows selections."""
return {
"@com_github_renatoutsch_rules_system//system:windows_x64": value,
"@com_github_renatoutsch_rules_system//system:windows_x64_msvc": value,
"@com_github_renatoutsch_rules_system//system:wind... | 65d41739f2829249d3012e9da68eb01c1de5741e | 647,988 |
def reshape_to_tf(tensor, dim=3):
"""Reshape the tensor to Tensorflow ordering.
This function assumes that your patch have
the same width for each dimension.
The types of tensors are supported
- Simple 2D patch sample
shape = (n_channels, patch_size, patch_size)
- 2D patch samples corp... | 4ac754cf07e6bdb8cfa38d8f93c93341bbd2c182 | 647,990 |
def numlookup(x, y):
"""
Try to resolve y as a numberic, then try to
look it up a key in dictionary x.
"""
try:
return int(y)
except ValueError:
return x[y] | 98ba8ca401ba4adddde5e01f94e787b2af30d77b | 647,991 |
from typing import Any
import io
def is_file_like(value: Any) -> bool:
"""Check if a value represents a file like object"""
return isinstance(value, io.IOBase) | 291d72b0ef930951872928a769b7126e35576cdd | 647,994 |
import struct
import socket
def address_in_network(ip, net):
"""
Is an address in a network
ip: 192.168.2.2
net:("192.168.2.0/24",)
"""
ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
for cur_net in net:
netaddr, bits = cur_net.split('/')
netmask = struct.unpack('=L',... | b70e5d2a6b5a243d91e7ca7d577d5d63d4aab71f | 647,995 |
from typing import List
def img_tag(movie_id: int, frame: int, box: List[int]):
"""Get a 'standard' image tag as used by the face recognition stack.
"""
# Real example of full file name: 121614:3616:235_183_293_262.jpeg
# Face file names are <tag>.jpeg
return f"{movie_id}:{frame}" + ":{}_{}_{}_{}"... | 54bcc399f73559007e0c8f2470bf03466877cd22 | 647,996 |
def self_embeds(url):
"""Does this url generate a usable embed on it's own when sent on discord?"""
return (
url.startswith("https://www.youtube.com")
or url.startswith("https://youtu.be")
or url.startswith("https://imgur.com")
or url.startswith("https://www.imgur.com")
o... | 02516b8661c9f4bdcc6c86c7477b1b9c97e9feeb | 647,998 |
def get_object_size_on_humans_retina(distance_to_object, object_height, focus_distance):
"""
Calculates an object size on human's retina
based on the object remoteness and its height
============================================================
The original formula is:
object_height / distanc... | e5432049e8dafba44b84163a50739fe3b9f4a413 | 648,000 |
def w_s_update(u, S):
"""Computes the updates for the proxy of the derivative of u for smoothing
Parameters
----------
u : np.array of shape (None,)
Beamlet radiation distribution u
S : np.array of shape (None, None)
Returns
-------
w_next : list of np.array of shape (None,)
... | e844416fbb1cf5f53cc7cdc3183fd49538d60c71 | 648,001 |
def format_pdf_search_term(search_term, encoding='utf-8'):
"""Converts a unicode string into the way it might actually
exist in the bytes of a pdf document. so we can check if the text
made its way into the final pdf.
An example:
the text
'So\nmany\nlines'
becomes the bytes
... | a72097a03eca825b9dbf61a8aeb3721ea5047ae6 | 648,002 |
import re
def split_mutation_string(instring):
"""Split a string with letters and numbers in it -- the number still stays a string though
Examples:
>>> split_mutation_string('A123F')
['A', '123', 'F']
"""
return re.split('(\d+)', instring) | a0916b137cc3e36d81d1346519a025be90618e89 | 648,004 |
def Username(i, delegates, usernames):
"""
Returns delegates dictionary with username of delegate
from usernames.json file.
"""
name = delegates[i]['Name']
if name in usernames:
delegates[i]['Username'] = usernames[name]
else:
delegates[i]['Username'] = ('NEWBIE')
return... | 30de4899f391f0aad680d8699b05e8f29b2ba14c | 648,005 |
def one_dec_places(x, pos):
"""
Adds 1/10th decimal to plot ticks.
"""
return '%.1f' % x | bca037dc98da23694f0af43b05bc90829e65b327 | 648,006 |
def fac(n):
"""Returns the factorial of n"""
if n < 2:
return 1
else:
return n * fac(n - 1) | 765a8147befe8cafd4633cf80369fffb467e7097 | 648,011 |
def remove_blank_spaces(syllables) -> list:
"""Given a list of letters, remove any blank spaces or empty strings.
>>> remove_blank_spaces(['', 'a', ' ', 'b', ' ', 'c', ''])
['a', 'b', 'c']
"""
cleaned = []
for syl in syllables:
if syl == " " or syl == '':
pass
else:
... | 3cf83c5867fd002c09ac5f109744e6fd9c43a6da | 648,013 |
from typing import Tuple
def format_numbers(nums: Tuple) -> str:
"""Format an array of numbers.
Parameters
----------
lst : Tuple
Array with numbers to be formatted
Returns
-------
str
String with number formatted
Example
-------
>>> format_numbers((2, 3, 10,... | 359c6fb72420d35b916965da25c9bbba77c05587 | 648,018 |
import json
def get_countries_metadata(fname="countries-readable.json"):
"""Read a database file containing information about different countries.
Specifically, we are interested in the capital and population of each country, because
we will use this information to disambiguate records, by giving more we... | 21caf95392ad61ac0db7c75c19ab4d12cccd7a53 | 648,020 |
import re
def get_config(input_image, no_data_config):
"""Read config json file for valid pixel value ranges per band and image type.
Args:
input_image (str): Name of the image file - must contain image type e.g. sentinel2, planet_4m.
no_data_config (dict): Config dictionary as found in json ... | 9d7d8e08be1a669a280959155c1f97fc4d688f9e | 648,022 |
def clean_text(txt):
"""Remove unnecessary spaces."""
return ' '.join(txt.strip().split()) | 41d62148588a65f7e480bdde8888679744a8f365 | 648,024 |
from typing import Type
from typing import TypeVar
def is_type_var(annotation: Type) -> bool:
"""Returns True if the annotation is a TypeVar."""
return isinstance(annotation, TypeVar) | 58ed89427a65ea777ca0426a7090325e8dc6e930 | 648,026 |
def remove_prefix(text: str) -> str:
"""
Removes prefix of a text based on : sign.
"""
return text.split(":", maxsplit=1)[1] if ":" in text else text | 0b0e98cab6f7f22fe1481374ef43d3992a052623 | 648,027 |
def is_experiment_related(title):
"""Check if the title is experiment related."""
name = title.split(":")[1].lower()
long_keywords = [
"method",
"material",
"experimental"
# "materials and method",
# "methods and material",
# "experimental framework",
... | e865f52fb3f1683f106e40f2cf08ac74e6385638 | 648,028 |
def is_magic_5gon_ring(elements):
"""
Return True if elements (10-vector) form a "magic" ring
"""
total = sum(elements[0:3])
return sum(elements[2:5]) == total and sum(elements[4:7]) == total \
and sum(elements[6:9]) == total and elements[1] + sum(elements[8:10]) == total | 43672432e2bbd93b8d8e97a3134848c321570934 | 648,030 |
def collapsed(cube, *args, **kwargs):
"""Collapses the cube with given arguments.
The cell methods of the output cube will match the cell methods
from the input cube. Any cell methods generated by the iris
collapsed method will not be retained.
Args:
cube (iris.cube.Cube):
A Cu... | 08ee8afe141a160c890850c399a8242b952e7345 | 648,042 |
def parse_requirements(filename):
""" load requirements from a pip requirements file """
lineiter = (line.strip() for line in open(filename))
return [
line
for line in lineiter
if line and not line.startswith("#") and not line.startswith('git+')
] | 838b05c9bc2238f8c420ba9bd9c834ddff0dd3d4 | 648,043 |
import csv
def load_csv(filename, label_col):
"""
Loads a csv file containin the data, parses it
and returns numpy arrays the containing the training
and testing data along with their labels.
:param filename: the filename
:return: tuple containing train, test data np arrays and labels
"""... | 30b4b6dcbeaa33fee40cdea81a063dbb3354eb16 | 648,044 |
def split_event(line):
"""Splits a line into tokens divided by one or more spaces."""
tokens = list(filter(None, line.split(' '))) # split by whitespace
return (tokens[1], *tokens[-4:]) | bdd10ec191fa4cfe08e1be240c4ec00d9ba59a31 | 648,049 |
def parameter_substitutions_for_sample(
sample, labels, sample_id, relative_path_to_sample
):
"""
:param sample : The sample to do substitution for.
:param labels : The column labels of the sample.
:param sample_id : The merlin sample id for this sample.
:param relative_path_to_sample : The rela... | 6a049ffb4d292508b4fc25f871cc28dccc3a25db | 648,050 |
def natural_bounds(rank, nb_ingredients):
"""
Computes the upper and lower bounds of the proportion of an ingredient depending on its rank and the number of
ingredients in the product given that they are in decreasing proportion order.
Examples:
>>> natural_bounds(2, 4)
(0.0, 50.0)
... | b6f04bb039c38370da21ab6430fc24e92b7831fe | 648,058 |
def _is_float(value):
""" Check whether a value is a float or not.
"""
try:
value = float(value)
return True
except (TypeError, ValueError):
return False | a397182150797f1dda04b6db0803f7ad2e4f4c5e | 648,066 |
from typing import Dict
def merge_freqs(tfs1: Dict[str, int], tfs2: Dict[str, int]) -> Dict[str, int]:
"""
Merges term-frequencies from tfs1 and tfs2 dictionaries.
This is an inplace operation i.e. It updates the largest dictionary in the argument inplace
and returns that as result.
"""
# keep... | 5550d253697dfbaafcae1a3c8b9beb530ab99462 | 648,069 |
import math
def classify_fixxation(eye_x, eye_y, d_time, treshhold):
"""
a function that classifies fixxations based on a threshhold in pixel per second
:param eye_x: an indexable datastructure with the x eye coordinates
:param eye_y: an indexable datastructure with the y eye coor... | 2e2c3cdf6c746eaeb921f7300e5e7c255f9f8f48 | 648,071 |
def extract_end_bits(num_bits, pixel):
"""
Extracts the last num_bits bits of each value of a given pixel.
example for BW pixel:
num_bits = 5
pixel = 214
214 in binary is 11010110.
The last 5 bits of 11010110 are 10110.
^^^^^
The inte... | 470d57ad81431ed59e682e133e561603ff6fe1d8 | 648,072 |
import codecs
import json
def load(path):
"""Loads a single Zeppelin notebook. For now just a wrapper around json.load"""
with codecs.open(path, mode="r", encoding="UTF-8") as fr:
try:
return json.load(fr)
except json.JSONDecodeError:
return {} | b88ee6454dc603d6b324a91f879dc167e433f442 | 648,073 |
from typing import List
def find_positions(arr: List[str],
mask: List[bool]) -> List[int]:
"""Set positions and tokens.
Args:
tokens: List of tokens and untokens.
mask: Mask for tokens.
Returns:
List of positions of tokens.
"""
pos... | d89a8ab51c4437c55c666b3670f9e09a13e478a5 | 648,075 |
def _get_val(v):
"""get val from a function or a value"""
if callable(v):
return v()
return v | 1017cf4e7026cd5fb0da0a90aa63e48aec2c26da | 648,078 |
import json
def search_for_game_id(game_name: str):
"""
Searches all_games_data.json file for occurences of game_name phrase, and saves findings to
found_games_data.json file.
:param game_name: string containing name of the game
:return: list containing found games as well as their id's
"""
... | 670bd8844afb879878c7dd498300ca78f9fc3e3b | 648,084 |
def valid_image_array(image_array):
"""
Returns `True` if and image array is valid.
An image array is valid if it is in grayscale (having 2 dimensions) or in color
(having 3 dimensions)
:param image_array: Image as an array
:type image_array: :class:`~numpy:numpy.ndarray`
:return: Returns `... | f2f0b22f750c4bc0cd42fdb951dd839f0c02eebd | 648,086 |
def run_mgmt_command(capsys):
"""Function fixture that runs a python manage.py with arguments
and returns the stdout and stderr as a tuple.
"""
def f(cmd_class, argv=None):
argv = argv or []
cmd = cmd_class()
cmd.run_from_argv(["manage.py"] + argv)
out, err = capsys.read... | 52d1b2e4bc438bbc5df28224e434d6c4d98784b4 | 648,087 |
def matrix_to_images(data_matrix, mask):
"""
Unmasks rows of a matrix and writes as images
ANTsR function: `matrixToImages`
Arguments
---------
data_matrix : numpy.ndarray
each row corresponds to an image
array should have number of columns equal to non-zero voxels in the mask
... | d07a356fb22bf6f5a87074906c9d7c8053e29002 | 648,088 |
def filter_events(events, version_label=None, request_id=None, env_name=None):
"""
Method filters events by their version_label, request_id, or env_name if supplied,
or any combination if multiple are specified.
:param events: A list of `events` returned by the `DescribeEvents` API
:param version_l... | 8338d7f93b1b36eb1561de7d6dead358aab7acef | 648,090 |
def counter_to_dict(counter):
"""
Converts counter to dictionary, also replaces the numpy value to an int
"""
dic = {}
for key, value in counter.items():
dic[key] = int(value)
return dic | d9df8c98937c1e0c984662fabcb649e7aca3a69f | 648,091 |
def monster_in_cutout(monster, cutout):
"""
Return True if monster is in cutout.
"""
for i_monster, char_monster in enumerate(monster):
if char_monster == "#" and cutout[i_monster] == ".":
return False
else:
return True | e98875e097e174d5b2555fb29f87666096edb3b4 | 648,093 |
def slack_escape(text):
"""
Escapes special characters for Slack API.
https://api.slack.com/docs/message-formatting#how_to_escape_characters
"""
text = text.replace('&', '&')
text = text.replace('<', '<')
text = text.replace('>', '>')
return text | 9d3d6bc86894f69365973394d0037bdd3eb23ece | 648,097 |
from collections import Counter
def _get_majority_class(y):
"""Get the majority class.
Note that if two or more classes have the same occurrences, one of them is returned arbitrarily.
"""
mc = Counter(y).most_common()
return mc[0][0] | c95f31fac5701c95eeef7714f025ba9ce6bd0bc2 | 648,099 |
def parse_sha256sum_file(filename):
"""
Takes a SHA256 checksum file and returns the values as a dict
:param filename: The file with SHA256 checksums
:return Mapping: Check sums from file
"""
with open(filename, 'r') as file:
string = file.read()
string = string.rstrip()
# Parse... | cc7e4a5df45d14ad5411a6d013dd407d06c0f4e6 | 648,103 |
import random
def freq_sample(freq: float, sample: float):
"""
Down or up sample a frequency based on a sample size. Sub unit frequencies are
rounded probabalistically.
:param freq: pre sampled frequency (integer)
:param sample: sample size (float)
:return: new frequency (integer)
"""
... | e7b894a66ec9c5e980055190563e0bab5286594e | 648,106 |
def chopnetOutputNode(chopnet):
"""Returns the chopnode inside the given chopnet that currently has its display flag set"""
for n in chopnet.children():
if n.isAudioFlagSet():
return n | a5b0d05d6b0daab6f700006fe5ef9dcb377ac4cc | 648,107 |
import uuid
def as_uuid(key: str) -> str:
""" Turn the given key into a uuid version 3. """
return str(uuid.uuid3(uuid.NAMESPACE_DNS, key)) | d770b41631fad272923e5f647cbb4cc95a602c77 | 648,110 |
def test_user(user_num):
"""Pre-defined user variables for testing purposes"""
users = {
"1": (5, "", 3, True, True, True, True, True),
"2": (0, "", 3, False, False, False, False, False),
"3": (2, "", 4, True, True, False, False, True),
"4": (1, "", 5, False, False, True, True, F... | b98d0fea48a1bb96a14c46528ee0754dd90f7d0e | 648,113 |
def ensure_tuple_size(tup, dim):
"""Returns a copy of `tup` with `dim` values by either shortened or padded with zeros as necessary."""
tup = tuple(tup) + (0,) * dim
return tup[:dim] | bcabaebbac248bfaee4daad5c6ac1f35fc7572a6 | 648,114 |
from typing import Any
from contextlib import suppress
def safe_get(key, obj, default=None) -> Any:
"""
Safely retrieve key from object
Args:
obj: Any. target object
key: inner object adders token
default: value to return on failure
Returns:
on success: value of request... | 21929399b123f46e7a24289052b1e9a9bbc71fa0 | 648,116 |
import json
def pretty_json(json_str):
"""Generates a pretty-print json from any json."""
return json.dumps(json.loads(json_str), indent=4) | e1d16fcc91c7d212130af115eb0cad2fbd73a99c | 648,117 |
def _sensor(product_id):
"""Find sensor ID from product ID."""
sid = product_id[:2]
if sid == 'LC':
return 'OLI_TIRS'
elif sid == 'LO':
return 'OLI'
elif sid == 'LE':
return 'ETM'
elif sid == 'LT':
return 'TM'
elif sid == 'LM':
return 'MSS' | 164d166e4e1d519ffb9d810df34a1e2e9b8ff06c | 648,120 |
from datetime import datetime
def extract_date_sitename(directory_path,
sitename_location,
datetime_location):
"""Extract datetime and sitename from directory path names.
Parameters
-----------
directory_path : string
A path to the directory... | df2c30d0b9629cd150a5168fbb403442682e190d | 648,123 |
def triple_length(m: int, n: int) -> int:
"""Returns the length of the triangle formed by the Pythagorean triple
(m^2 - n^2, 2mn, m^2 + n^2)."""
return 2 * m * (m + n) | 002bfdb2bf4d5b73bb90394681b0ef5156b6da7e | 648,127 |
def extract_container_id_removal(line):
"""
Extract container id from a Removing line
Removing intermediate container 816abeca3961
"""
parts = line.strip().split(' ')
if len(parts) == 4:
return parts[3]
else:
raise Exception("Unrecognized docker removing line: " + l... | dc73ced5b0ab6169c9b4ed9e615e6c54a05e4de7 | 648,130 |
def get_recommendation(risk_level):
"""
Returns a investment recommendation based on the choice of risk level
"""
recommendation = ""
if risk_level == 'None' or risk_level == 'none':
recommendation = "Investment recommendation: 100% bonds (AGG), 0% equities (SPY)"
elif ris... | 98779343f5a01bc4d91af8079ca403d0413c5951 | 648,132 |
def digit_that_breaks_ordering_index(digits: list) -> int:
"""
Starting from last digit of given number, find the first
digit which breaks the sorted ordering. Let the index of
this found digit be 'i' and the digit be number[i].
:param digits: list of digits
:return: the index of the first digi... | e4b24a94d04efdaa8311da7878e500e80f066d00 | 648,133 |
def specindex(nu1, nu2, f1, alpha):
"""
Calculate some flux given two wavelengths, one flux, and the spectral
index.
"""
return f1*(nu2/nu1)**(alpha) | 0884206d0aedfb9ee92df93f9bbd7d82ab81af0d | 648,135 |
def find_sols(f, arr, sign_check_func = lambda x, y: x*y < 0, verbose = False):
"""
Given an array of section points, checks if function *f* has a solution
in any of the intervals formed by said points.
"""
sols = []
for i in range(len(arr)-1):
if sign_check_func(f(arr[i]), f(arr[i+1])):... | 36ff973789c645d65645ea4a902c2a80f9548b5a | 648,142 |
def motifs_from_proto(motifs, is_one_dimensional=False):
"""
Utility function to transform motif locations back to single dimension
or multi-dimension location.
Parameter
---------
motifs : array_like
The protobuf formatted array.
is_one_dimensional : boolean
A flag to indic... | b848b0262fb2c82da95b5ef9d9095d1bb80ad13b | 648,143 |
def replacePlaceholder(sentence,placeholder,subsitute):
"""
This function replaces in a sentence a placeholder with a specified substitute
Input:
sentence: string representing a sentence
placeholder: string representing a placeholder that occurs in the supplied sentence
subsitute: s... | 85345f9c00a3b1334057de2a32ea390e76a511d4 | 648,146 |
def list_as_comma_string(bits, serial_comma=False):
"""
>>> list_as_comma_string([])
''
>>> list_as_comma_string(['hi'])
'hi'
>>> list_as_comma_string(['hi', 'there'])
'hi and there'
>>> list_as_comma_string(['hi', 'there', 'world'], serial_comma=False)
'hi, there and world'
... | 58ce30d3cf8e2812c057f3f3303e03e5f8a1a11d | 648,147 |
def auto_label(callable_or_expr):
"""
Given a callable or a string, extract a name for labeling axes.
Parameters
----------
callable_or_expr : String | Callable
Returns
-------
label : String
"""
if callable(callable_or_expr):
return getattr(callable_or_expr, "__name__"... | 470df5bcee871c72eecdf14fb337f5bb1ca3ba11 | 648,148 |
def delete_tasks(project, params, items):
""" Delete tasks by ids
"""
project.delete_tasks(items)
return {'processed_items': len(items),
'detail': 'Deleted ' + str(len(items)) + ' tasks'} | cf32be2942586c0db6c7d36d35876f8adefcace3 | 648,156 |
def get_x_indicator_variable_index(i, j, k, l, m, n):
"""
Map the i,j,k,l indices to the sequential indicator variable index
as generated by linear_objective_function_coefficients().
This is basically the (4-dimensional) 'array equation' (as per
row-major arrays in C for example).
Note that for... | 2bfa271663b00709cfc9e0b858b4a5f17395970e | 648,163 |
import re
from pathlib import Path
def import_public_key(app_path, device_name, keystring):
"""Import a public key for hyperglass-agent.
Arguments:
app_path {Path|str} -- hyperglass app path
device_name {str} -- Device name
keystring {str} -- Public key
Raises:
RuntimeErr... | 8786cd3bafb23125930b2fd3a6f7f35d265171c1 | 648,164 |
import random
def make_marker(bits=64):
""" Return a unique string that , for marking boundaries in text """
# i.e. '|-b1dda1c7f14cd89e-|'
# In python2, hex() on big numbers gives i.e. '0x3333333333L'.
# I'll drop the 1st two and last chars with [2:-1].
return '|-'+hex(random.getrandbits(64))[2:-... | 6b1e09aa68ecea9aae504c0356653b1dbb468292 | 648,169 |
def cursor_fetcher(cursor):
""" Fetcher that simply returns the cursor. """
return cursor | 02d5150975387455d4c2b8ab9081315e72884e64 | 648,177 |
def get_openlibrary_key(key):
"""convert /books/OL27320736M into OL27320736M"""
return key.split("/")[-1] | b4b266e8d79d9b5cd4401439835eff1175ae4d7c | 648,184 |
def factors(number):
"""
Find all of the factors of a number and return it as a list.
:type number: integer
:param number: The number to find the factors for.
"""
if not (isinstance(number, int)):
raise TypeError(
"Incorrect number type provided. Only integers are accepted.... | 5a4aa5b2908ce40ebbcd69093c528467ee45f31e | 648,189 |
import socket
def uds_reachable(uds_path, return_sock=False):
""" Check if the unix domain socket at path `uds_path` is reachable.
Parameters
----------
uds_path : str
return_sock: bool, optional (default is False)
Return the socket.
Returns
-------
bool, socket
If th... | 4c79a301dc4dfea5a3741325fe5abfc373d4c5e1 | 648,193 |
def mid_color(c1, c2):
"""Returns medium color between c1 and c2"""
r = int(0.5 * (c1[0] + c2[0]))
g = int(0.5 * (c1[1] + c2[1]))
b = int(0.5 * (c1[2] + c2[2]))
try:
a = int(0.5 * (c1[3] + c2[3]))
return (r, g, b, a)
except IndexError:
return (r, g, b) | c2a0f7161020cfd7538837c22b48dd418d027616 | 648,197 |
from pathlib import Path
def validate_path(file_name):
"""
Validates if the passed-in argument is a valid path
Parameters
----------
file_name: str
Path to be validated
Returns
-------
tuple
Boolean status and dict to identify if the path is a file or directory
""... | 2c2469268161854104206955258b35a54a3a9222 | 648,200 |
def _get_operator(spec, context):
"""
Gets operator from context
"""
try:
return context[spec]
except KeyError:
print(
f"Error: Operator ${spec} is not defined. Make sure you are importing it in the modules section."
)
raise | bea70c4c49b4b5302d6e60a0a35a5547d764e305 | 648,201 |
def read_list(path):
"""
Reads a list containing one file per line.
Returns an index of line number - line content
"""
with open(path, 'r') as fhandle:
fdata = {}
for nline, line in enumerate(fhandle):
if not line.strip():
continue
# Remove ex... | 7d43ece95a4a062b77395a3a215573c771555911 | 648,213 |
import re
def version_cmp(v1, v2):
"""
Compare two version strings and returns:
* `-1`: if `v1` is less than `v2`
* `0`: if `v1` is equal to `v2`
* `1`: if `v1` is greater than `v2`
Raises `ValueError` if versions are not well formated.
"""
vregex = r"(?P<whole>\d+(\.(\d+))*)"
v1... | 46928c36abce879c5c6e1616af668bb2b4dfa5c6 | 648,215 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.