content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _compute_colocation_summary_from_dict(name, colocation_dict, prefix=""):
"""Return a summary of an op's colocation stack.
Args:
name: The op name.
colocation_dict: The op._colocation_dict.
prefix: An optional string prefix used before each line of the multi-
line string returned by this fu... | a8cd7b8fc837d9098f84910f832fbc2ebba45ebd | 655,954 |
import json
def printjson(toprint, exception_conversions={}):
"""print anything in json format. Can override printing for custom
types using a dictionary of types to lambda conversion functions.
Examples:
printjson(data)
printjson(data,{sp.DenseSparseMatrix: lambda x: f"matrix = {x}" })
... | 0fe60c63ff5f1ab84bee8fb8af39513bad90f78a | 655,956 |
def iteritems(obj, **kwargs):
"""Iterate over dict items in Python 2 & 3."""
return (obj.iteritems(**kwargs)
if hasattr(obj, 'iteritems')
else iter(obj.items(**kwargs))) | f35437e0141cd951bd8485e004a9504a823e71ca | 655,958 |
def calculate_handlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string-> int)
returns: integer
"""
return sum(hand.values()) | 877a3faa981624ab869460d96fabcc8e93623bf1 | 655,960 |
def generate_bond_indices(natoms):
"""
natoms: int
The number of atoms
Finds the array of bond indices of the upper triangle of an interatomic distance matrix, in column wise order
( or equivalently, lower triangle of interatomic distance matrix in row wise order):
[[0,1], [0,2], [1,2], [0,3... | 2484a45c653b027de126713d8b7984551b2a1cd1 | 655,961 |
from pathlib import Path
def to_condition(p: Path, ind: int = -1, sep: str = "_") -> list:
"""
converts path into a row for condition dataframe
it assumes that the names of the files have pars separated by "_" or other separator
:param p path to the file
:param ind where in a splited file name to ... | 9b21cf13668256ae3cfbb9d092827705db9d6027 | 655,963 |
from typing import Dict
def _get_labels_dict(label_str: str) -> Dict[str, str]:
"""
Converts CLI input labels string to dictionary format if provided string is valid.
Args:
label_str: A comma-separated string of key-value pairs
Returns:
Dict of key-value label pairs
"""
label... | d3b8024e7692fd281ba03c6f8c03cc69ebcdffa2 | 655,965 |
def make_query_to_get_users_profiles(userIds):
"""Returns a query to retrieve the profile for the indicated list of
user ids
Api info:
parameter name: user_id
values: A comma separated list of user IDs, up to 100 are allowed in a single request.
Notes: You are strongly encouraged to ... | e248b36a7c09381948c9346f4d494754547bb7bd | 655,966 |
import json
def mocked_requests_get(*args, **kwargs):
"""Defines a response suitable for mocking requests responses."""
class MockResponse:
"""Solution cribbed from
https://stackoverflow.com/questions/15753390/how-can-i-mock-requests-and-the-response/28507806#28507806
"""
def _... | 3bb884627a82de6cffee7583f5bd1aa5a5d605b0 | 655,973 |
def getManifestEtag(manifest):
""" returns Etag hash for manifest"""
return manifest["Etag"] | a493779cc739ba38244885ecfe4e92195a7ee467 | 655,975 |
from pathlib import Path
def get_new_files(commit, dir):
"""Return new files in commit that are in dir directory"""
files = []
for file in commit.files:
if Path(dir) in Path(file.filename).parents and file.status == "added":
files.append(file)
return files | 0e8d48fc38f1e07dd1eeca0580c12f0e65057427 | 655,978 |
import math
def _datetime_to_timestamp(dt, period, round_up=False):
""" Convert a datetime object to a timestamp measured in simulation periods.
Args:
dt (datetime): Datetime to be converted to a simulation timestamp.
period (int): Length of one time interval in the simulation. (minutes)
... | 023a7e971db655abb04fa7fb53ceb535553ab076 | 655,979 |
def list_hasnext(xs):
"""Whether the list is empty or not."""
return len(xs) > 0 | 6b244a979ea129efe7d39e554b9986c76653bfe0 | 655,982 |
def rescale(src_scale, dest_scale, x):
"""Map one number scale to another
For example, to convert a score of 4 stars out of 5 into a percentage:
>>> rescale((0, 5), (0, 100), 4)
80.0
Great for mapping different input values into LED pixel brightnesses!
"""
src_start, src_end = src_scale
... | 4ba97ac516e07b5ed8ae7fee80a80ee4b13b7674 | 655,983 |
import six
def downgrader(version):
"""
A decorator for marking a method as a downgrader to an older
version of a given object. Note that downgrader methods are
implicitly class methods. Also note that downgraders take a
single argument--a dictionary of attributes--and must return a
dictiona... | e136829783f2e002ee741fed7acf210d6235c535 | 655,984 |
from typing import Union
from pathlib import Path
def is_notebook(file: Union[Path, str]) -> bool:
"""Determines whether a file is a notebook file or not.
Args:
file: the file, as either a pathlib.Path object or a filename string.
Returns:
True if notebook file, else False.
"""
i... | 7afc70c8151c2fb18497250d67c29fe2fafac3a5 | 655,986 |
def extract_major_version(scala_version):
"""Return major Scala version given a full version, e.g. "2.11.11" -> "2.11" """
return scala_version[:scala_version.find(".", 2)] | 9a3fbee2a3962e28dd29b4ddb6870ecd5ca97d1f | 655,988 |
def sanitize(message: str) -> str:
"""
Removes backticks (code tag) and linebreaks from a message.
"""
return message.replace('`', '').replace('\n', '') | 79c9c951873ce56151bd05a903f91a269c155196 | 655,990 |
def distLinf(x1, y1, x2, y2):
"""Compute the Linfty distance between two points (see TSPLIB documentation)"""
return int(max(abs(x2 - x1), abs(y2 - y1))) | 9a47b59b139445105ad757c5f2d43f5a0c228be2 | 655,991 |
import re
def is_special_character(string, i, pattern):
"""
Returns True if the i-th character in the given string is a special
character, False otherwise. The character is *not* a special character if
it is a dot and it is surrounded by two digits, like in "1.23".
>>> is_special_character(["a", ... | 2ed0e5158e469f305b3f359f9c6e923d8c9ef623 | 655,993 |
def calcArea(vertexes):
"""
:param vertexes:
:return Float: Area of the polygon, Positive value means clockwise direction, negative counter-clockwise.
>>> calcArea([Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0)])
-1.0
>>> calcArea([Point(0, 0), Point(1, 0), Point(1, 1), Point(0, 1)])
... | 813ca2c6e6fa693539307380838fbabdfd881a16 | 655,994 |
def bayesdb_colno_to_variable_names(bdb, population_id, generator_id):
"""Return a dictionary that maps column number to variable name in population."""
cursor = bdb.sql_execute('''
SELECT colno, name FROM bayesdb_variable
WHERE population_id = ?
AND (generator_id IS NULL OR ... | 27d2e1ac9bcebe80ebf83f2d76df7dad8a1fcc8b | 655,998 |
import fnmatch
def _fnmatch_lower(name: str | None, pattern: str) -> bool:
"""Match a lowercase version of the name."""
if name is None:
return False
return fnmatch.fnmatch(name.lower(), pattern) | e04d207de691dd3ee5d35dccf88a8c0ed8e5fc3c | 656,000 |
def denormalize_loc(locations, img_height, img_width):
"""convert locations from normalized co-ordinates in range [0,1] back into pixel co-ordinates
Parameters
----------
locations : numpy.ndarray
with two columns (y, x) (not (x, y), because of how array indexing works)
img_height : int
... | e1bcd35052bcfd14880c38c32a1477ded69a4413 | 656,001 |
def _string_id(*args):
"""Creates an id for a generic entity, by concatenating the given args
with dots.
Parameters
----------
*args: str
The strings to concatenate
Returns
-------
basestring: an identifier to be used.
"""
def is_valid(entry):
return (
... | b6cef4a7291f25ea72b0de76ea927bee9b86f560 | 656,003 |
def only_printable(string):
""" Converts to a string and removes any non-printable characters"""
string = str(string)
return "".join([s for s in string if s.isprintable()]) | 2ee68c5fa77a04a58bb717918833b70e8c6f59bc | 656,004 |
def name_class(classname):
"""Change AMQP class name to Python class name"""
return classname.capitalize() | 676111fcbeb6005f17f09f21af5a817a2487a54c | 656,005 |
def calculateFrameTime(speed, ratio):
"""
Calculates the frame time interval from chopper parameters.
Chopper speed in rpm given, but calculations are in Hz.
The interval is the time between pulses of chopper 5 because chopper 5
has only 2 slits
returns the frame time in s
"""
speed /=... | eca95d90fee99891c7b4922731b9b4722bf5fddf | 656,007 |
def normalize_order_number(order_number: str) -> int:
"""
Normalizes Sierra order number
"""
return int(order_number[2:-1]) | 687afc219fd69cc061a96065fbdd914d0e85ca50 | 656,010 |
def compose_j(n, Nvec):
"""
Eq. 4 in Poly Fits Derivation. Routine to compose the j counter from
the n values. Can also be used as Eq. 10 with the i counter and the nhat
values.
inputs:
n = list of integer values representing the independent variables'
exponents for the... | d9a7f7b92a7c3dadb801c2c86a2497f7b26fafc4 | 656,014 |
from typing import TextIO
def open_read_text(filepath: str) -> TextIO:
"""Open a text file for reading and return a file object."""
return open(filepath, mode="r", encoding="utf-8") | c31f27e74df1e0d8ac342583dd40e89df281172d | 656,017 |
import inspect
def get_default_hook(obj, default_hooks):
"""Finds the default save/load hook to use with the given object.
Follows the Method Resolution Order, i.e., if no hook is registered for
the class of the object itself, also searches classes which the object
inherits from.
Arguments
-... | 1909bc8d3a4706ee9a9518b2159171d7b879f563 | 656,020 |
def resources_to_layout(resources):
"""Given a `list` of resource object [a,b,c], extract the frame and join them like [[a.frame], [b.frame], [c.frame]]"""
res = []
for a in resources:
res.append([a.frame])
return res | 6496ada34999d057633ebaa13ebc21ea53b32978 | 656,034 |
def solution(n: int = 10) -> str:
"""
Returns the last n digits of NUMBER.
>>> solution()
'8739992577'
>>> solution(8)
'39992577'
>>> solution(1)
'7'
>>> solution(-1)
Traceback (most recent call last):
...
ValueError: Invalid input
>>> solution(8.3)
Traceback ... | f7592101aea6598a480be3d3898af1979c48449f | 656,039 |
def _get_file_type(fname):
"""Return the type of a file."""
if fname.endswith('.nii.gz') or fname.endswith('.nii'):
return 'NIfTI-1'
if fname.endswith('.png'):
return 'PNG'
if fname.endswith('.jpg'):
return 'JPEG'
if fname.endswith('.mnc'):
return 'MINC'
if fname.... | f5371eb17e96353bac58632ba8cd212bbf6fa698 | 656,040 |
def locale_to_source_path(path):
"""
Return source resource path for the given locale resource path.
Source files for .po files are actually .pot.
"""
# Comment this for now as js-lingui does not provide .pot files, only .po
# Commenting these lines is enough to make it work
# if path.endswi... | 45a9a5de06754ad8327c836f43645d18764f2cb2 | 656,041 |
from typing import OrderedDict
def _translate_reverse_relationships(opts, reverse_relations):
"""
DRF's `_get_reverse_relationships` uses the `get_accessor_name` method of
`ForeignObjectRel` as the key for the relationship. This function replaces
those keys with the rel's `name` property. This allows ... | 56851cb19ec4410bff5d18f08b088957a04a8ae5 | 656,053 |
def display_title(book):
"""Compute the display title of a book."""
out = book["title"]
if book.get("subtitle"):
out += f": {book['subtitle']}"
if book.get("volume_number") and book.get("fascicle_number"):
out += f" (vol. {book['volume_number']['raw']}; fas. {book['fascicle_number']['ra... | 6dc1eede5283453c94f8bfd414c148971db53c21 | 656,054 |
def int_to_str_v2(n: int) -> str:
"""Convert the given integer into it's string form.
Args:
n: The integer whose string form to be gotten.
Returns:
The string form of the given integer.
"""
if n == 0: return '0'
sign, n = ('-', -n) if n < 0 else ('', n)
s = []
while n... | b88b50601aa55fdbe0da8ce2063a154860a673be | 656,056 |
import inspect
import re
def strip_source_code(method, remove_nested_functions=True):
"""
Strips the source code of a method by everything that's "not important", like comments.
Args:
method (Union[callable,str]): The method to strip the source code for (or the source code directly as string).
... | 5e50c902a6c56b2c46715ebda8a7c2aea8750b1a | 656,057 |
def hadamard_complex(x_re, x_im, y_re, y_im):
"""Hadamard product for complex vectors"""
result_re = x_re * y_re - x_im * y_im
result_im = x_re * y_im + x_im * y_re
return result_re, result_im | 5aa08bf499fd4835d97d6f8fe4bfda7595c719d1 | 656,059 |
def validate_category_or_command_name(name):
"""
Validates the given category name.
Parameters
----------
name : `str`
The name of a category or command.
Returns
-------
name : `str`
The validated name.
Raises
------
TypeError
If `name` ... | 1e58247557f486024d9d929d75e1dd212f2f41b9 | 656,060 |
def query_transform(request, **kwargs):
"""
Merges the existing query params with any new ones passed as kwargs.
Note that we cannot simply use request.GET.update() as that merges lists rather
than replacing the value entirely.
"""
updated_query_params = request.GET.copy()
for key, value ... | 49cef933a9cd01ef93b7a38de5bd7e499edddecf | 656,062 |
def get_all_properties(data, **kws):
"""Get all property definitions from PV data.
Parameters
----------
data : list(dict)
List of dict, each dict element is of the format:
``{'name': PV name (str), 'owner': str, 'properties': PV properties (list[dict]), 'tags': PV tags (list[dict])}``.... | ca65c338681797b5bcb4b411c666d5ec4ea495e4 | 656,067 |
def _find_node_by_name(nodes, name):
"""
Loop through a list of nodes and return the one which has the matching display name
:param nodes: List of nodes
:param name: Target name
:return: Matching node, None otherwise
"""
# Nodes always have unique names, thus there's no need for duplicate ch... | 1ac64ff148e771e416052a16f304ee5e496c4d61 | 656,071 |
def mapfmt(fmt: bytes, size: int) -> bytes:
"""
Changes the type of of a format string from 32-bit to 64-bit.
WARNING: doesn't handle strings.
Example
-------
>>> mapfmt(b'2i 6f')
b'2q 6d'
"""
if size == 4:
return fmt
return fmt.replace(b'i', b'q').replace(b'f', b'd') | 6e872e916700bf185e2342a607908670590e3fb5 | 656,073 |
def get_library_interface_type_name(config):
"""Get the LibraryInterface type name, based on the service_class_prefix config setting."""
service_class_prefix = config["service_class_prefix"]
return f"{service_class_prefix}LibraryInterface" | 8097e9c954570677473ac73997d7ce00aa890268 | 656,074 |
import time
def parse_sfx_now(input_time: str) -> int:
"""Parse Signalfx Now into SignalFx API epoch milliseconds
:raise: ValueError
"""
if input_time == "Now":
return int(time.time()) * 1000
raise ValueError(f"{input_time} is not Now") | bd56c6ad75b9b0823f77d690344f87d89cb2c3b2 | 656,075 |
def readlines(path):
"""Read a file into a list of lines."""
with open(path) as f:
return f.readlines() | 9e9c36fcbdc89fbf796546d26e664cad30494cb0 | 656,077 |
def Vcell_Calc(Enernst, Loss):
"""
Calculate cell voltage.
:param Enernst: Enernst [V}
:type Enernst : float
:param Loss: loss [V]
:type Loss : float
:return: cell voltage [V] as float
"""
try:
result = Enernst - Loss
return result
except TypeError:
pr... | d400459481333d583459c6cefebc1e7446bee66e | 656,081 |
def remove_bots(members):
"""Removes bots from a list of members"""
bots = []
for member in members:
if member.bot:
bots.append(member)
for bot in bots:
members.remove(bot)
return members | 16721756a12ebe8478117eb2ea387e99bc68c9a3 | 656,082 |
def to_flags(value):
"""Return a (flags, ednsflags) tuple which encodes the rcode.
*value*, an ``int``, the rcode.
Raises ``ValueError`` if rcode is < 0 or > 4095.
Returns an ``(int, int)`` tuple.
"""
if value < 0 or value > 4095:
raise ValueError('rcode must be >= 0 and <= 4095')
... | a1fda96e1f5cb40c441c85929b6787f994308ca3 | 656,085 |
import pickle
def read_as_pickle(path: str):
"""Read in pickle file."""
with open(f'{path}.pickle', 'rb') as handle:
return pickle.load(handle) | 70842c647a1fd68ac5b1a89765fe9e31053570bf | 656,092 |
def is_callID_active(callID):
"""Check if reactor.callLater() from callID is active."""
if callID is None:
return False
elif ((callID.called == 0) and (callID.cancelled == 0)):
return True
else:
return False | f54a05fde58db53319bc34cca79629011e2f2ffd | 656,094 |
def build_property_spec(client_factory, type='VirtualMachine',
properties_to_collect=None,
all_properties=False):
"""Builds the Property Spec.
:param client_factory: Factory to get API input specs
:param type: Type of the managed object reference property
... | 8369b03fa22cab90f5bf22dd4cacc824ec352d5a | 656,096 |
def _clean_message(message):
"""
Cleans a message by removing the 0 bytes from the input message.
:param message: The message to be cleaned.
:return: str: The cleaned message.
"""
return message.split('\x00')[0] | 264d40553d8c769916c2882126195ea69f053764 | 656,098 |
import yaml
def get_time_limit(cwl_content: bytes) -> int:
"""Takes a CWL file contents and extracts cwl1.1-dev1 time limit.
Supports only two of three possible ways of writing this. Returns
0 if no value was specified, in which case the default should be
used.
Args:
cwl_content: The con... | 67146dfb38d35f3f077a44deba1e57304692d09a | 656,099 |
import struct
def get_dump_pos(log_file, log_pos, server_id):
"""
https://dev.mysql.com/doc/internals/en/com-binlog-dump.html
1 [12] COM_BINLOG_DUMP
4 binlog-pos
2 flags
4 server-id
string[EOF] binlog-filename
"""
COM_BINLOG_DU... | 032ddefd5f59427f5fd7ade2e0a094a7f1b67a64 | 656,101 |
def _check_no_collapsed_axes(fig):
"""
Check that no axes have collapsed to zero size.
"""
for panel in fig.subfigs:
ok = _check_no_collapsed_axes(panel)
if not ok:
return False
for ax in fig.axes:
if hasattr(ax, 'get_subplotspec'):
gs = ax.get_subplo... | 2ecbc6a3e17f73ab4c09f606c4638ad7748ee59a | 656,103 |
import warnings
def filtfilt(signal, synapse, dt, axis=0, x0=None, copy=True):
"""Zero-phase filtering of ``signal`` using the ``synapse`` filter.
.. note:: Deprecated in Nengo 2.1.0.
Use `.Synapse.filtfilt` method instead.
"""
warnings.warn("Use ``synapse.filtfilt`` instead", Deprecati... | 389184242f68143e1876b8aa8870873ae601162f | 656,105 |
from typing import Dict
from typing import AnyStr
import json
def _decode_json_dict(json_dict: Dict[bytes, AnyStr]) -> dict:
"""
Decode a dict coming from hgetall/hmget, which is encoded with bytes as keys
and bytes or str as values, containing JSON values.
"""
return {k.decode(): json.loads(v) fo... | a0ce492e4cd27829cc1a1508954f7e0d76130338 | 656,110 |
import logging
def get_instance_group_manager_to_delete(key):
"""Returns the URL of the instance group manager to delete.
Args:
key: ndb.Key for a models.InstanceGroupManager entity.
Returns:
The URL of the instance group manager to delete, or None if there isn't one.
"""
instance_group_manager = ... | 6122c4d78cb6ab66200e6ffe7d4d709262dd1e1f | 656,111 |
def _unpack_tensors(reduced, tensor_packer=None):
"""Unpack tensors if they are packed before all-reduce."""
if tensor_packer:
return tensor_packer.unpack(reduced)
return reduced | b9f61b42873002e2b25deb04f1990afade583da4 | 656,112 |
def instance_to_class(instance, parent):
"""
Return the name of the class for an instance of inheritance type parent
"""
return parent + "_" + instance | 11c578ce782a7289aaa4fcb482ceb60699c65632 | 656,115 |
def rayleigh_range(w0, k):
"""
Computes the rayleigh range, which is the distance along the propagation
direction of a beam from the waist to the place where the area of cross
section is doubled.
Args:
w0: waist radius of beam
k: wave number in the direction of propagation of beam
... | b6df563cf0139b65f3ed0067447fc2ea66e0c327 | 656,118 |
from pathlib import Path
def _check_inputs(filepath, order, compact, flatten):
"""
This function checks the input arguments to compute() for validity based
on descriptions below.
Parameters
----------
filepath : Path object
Valid path to file containing nucleotide sequence.
order ... | 71eada00f9ba5cce02758be3694517a6ce929f3c | 656,119 |
import re
def charset_from_headers(headers):
"""Parse charset from headers.
:param httplib2.Response headers: Request headers
:return: Defined encoding, or default to ASCII
"""
match = re.search("charset=([^ ;]+)", headers.get('content-type', ""))
if match:
charset = match.groups()[0... | 50fc897588b94b1b9d9af655244f97a5bb18face | 656,126 |
def parse_reqs(file_path):
"""Parse requirements from file."""
with open(file_path, 'rt') as fobj:
lines = map(str.strip, fobj)
lines = filter(None, lines)
lines = filter(lambda x: not x.startswith("#"), lines)
return tuple(lines) | 5e98df09561d6c89ce5e04dd0207fe288a3c7d8b | 656,129 |
def calculate_position_part2(infile_path: str) -> int:
"""
Read input, determine vertical and horizontal position and return the product of the values
:param infile_path: file path to input file with instructions separated by newlines
:type infile_path: str
:return: product of the vertical and horiz... | 3dfe30a9b4e2971385f610417d2e9cefa34fc1d8 | 656,130 |
def _estimate_geohash_precision(r: int):
"""
Returns hueristic geohash length for the given radius in meters.
:param r: radius in meters
"""
precision = 0
if r > 1000000:
precision = 1
elif r > 250000:
precision = 2
elif r > 50000:
precision = 3
elif r > 1000... | ecc96c5e991fb9792993b58ae77263935be44034 | 656,140 |
def merge_dicts(dict_a, dict_b):
"""Performs a recursive merge of two dicts dict_a and dict_b, wheras dict_b always overwrites the values of dict_a
:param dict_a: the first dictionary. This is the weak dictionary which will always be overwritten by dict_b (dict_a
therefore is a default dicti... | 32e2823a7491f916fcdab8a28b94d5027c1f0306 | 656,141 |
def ensure_list(val):
"""Converts the argument to a list, wrapping in [] if needed"""
return val if isinstance(val, list) else [val] | 10ec23fac23e27defbf5a9325f3c863f8c0b6d50 | 656,142 |
def hideCells(notebook):
"""
Finds the tag 'hide' in each cell and removes it
Returns dict without 'hide' tagged cells
"""
clean = []
for cell in notebook['cells']:
try:
if 'hide' in cell['metadata']['tags']:
pass
else:
clean.appen... | 5920cbc30720bd637d11f14fea363797f328c099 | 656,153 |
from pathlib import Path
def parse_pb_name_data(file_name):
"""Returns data encoded in extraction files, such as datetime or itp id.
>>> parse_pb_name_data("2021-01-01__1__0__filename__etc")
{'extraction_date': '2021-01-01', 'itp_id': 1, 'url_number': 0, 'src_fname': 'filename'}
"""
extraction_... | c7f8be4638b6ddfe47475665ca8a3d9a31055000 | 656,155 |
def _apply_to_sample(func, sample, *args, nest_with_sample=0):
"""Apply to a sample traversing the nesting of the data (tuple/list).
Parameters
----------
func : callable
Function to be applied to every sample data object
sample : sample object or any nesting of those in tuple/list
... | 46fef5b4e32086a1fbcde4d1b63664c9ba9632f4 | 656,157 |
def camelcase(s: str) -> str:
"""Convert snake case to camel case.
Example:
>>> camelcase("camel_case")
'camelCase'
"""
parts = iter(s.split("_"))
return next(parts) + "".join(i.title() for i in parts) | 3ccfa02c2bc7f6e590c3e445c9033e7e15568f1a | 656,165 |
def link_regulator(incoming_links: list) -> list:
"""
Regulates the links coming from Google Search.
Input URL: "/url?q=https://www.example.com/SparqlEndpoint&sa=U&ved=2ahUKEwiU"
Output URL: "https://www.example.com/SparqlEndpoint"
:param incoming_links: List of links to be regulated
:return:... | 9c7c451c65da2f3f0240c26903cdfe2a9ced1913 | 656,169 |
def middleware(get_response):
"""Set up middleware to add X-View-Name header."""
def add_view_name(request):
response = get_response(request)
if getattr(request, 'resolver_match', None):
response['X-View-Name'] = request.resolver_match.view_name
return response
return add... | 66d3f9179f3b35e18c474870806e72643d58a508 | 656,171 |
def enumerated_subsections(request):
"""Parametrized fixture of each subsection along with its index in the parent section."""
return request.param | 8433794d32e3913d8db5706367341f232db0cee4 | 656,173 |
def _MapObjcType(t, other_types):
"""Returns an Objective-C type name for the given IDL type."""
if t.element_type:
assert t.name == 'sequence'
return 'NSArray<%s>*' % _MapObjcType(t.element_type, other_types)
elif t.name in other_types:
return 'Shaka%s*' % t.name
else:
type_map = {
# ID... | 1604d372fa81feaaada09eb4c8551a1412e34afa | 656,175 |
def seq_names(fasta_file):
"""Get sequence names from fasta file."""
names = []
f = open(fasta_file)
fasta = f.read()
f.close()
for a in fasta.split(">"):
names.append(a.split("\n")[0])
return [a for a in names if a != ""] | 3fdc152552534353f75355004f37a3a7f923d488 | 656,176 |
def dict_to_aws_tags(d):
"""
Transforms a python dict {'a': 'b', 'c': 'd'} to the
aws tags format [{'Key': 'a', 'Value': 'b'}, {'Key': 'c', 'Value': 'd'}]
Only needed for boto3 api calls
:param d: dict: the dict to transform
:return: list: the tags in aws format
>>> from pprint import pprin... | 12680d9ccd1cfc04a6ac94910256d52018daa22d | 656,177 |
def legrende_polynomials(max_n, v):
"""
Returns the legendre polynomials
Based on the algorithm here:
http://uk.mathworks.com/help/symbolic/mupad_ref/orthpoly-legendre.html
"""
poly = [1, v] + [0] * (max_n - 1)
for n in range(2, max_n + 1):
poly[n] = (2 * n - 1) / n * v * poly[n - 1]... | b714d84557c68cbd9ad58d8a41526b2b6033cc34 | 656,179 |
def agg_count_distinct(df, group_key, counted_key):
"""Returns a Series that is the result of counting distinct instances of 'counted_key' within each 'group_key'.
The series' index will have one entry per unique 'group_key' value.
Workaround for lack of nunique aggregate function on Dask df.
"""
re... | 9b980bf649ecfc1e240d09aae1eb79798f638a20 | 656,180 |
def get_err_msg(code):
"""
This function formats an error message depending on what error code is
generated by the HTTP request. We wrap the error message in a HTML page
so that it can be displayed by the client.
"""
if code == '404':
str = 'Function Not Implemented'
else:
st... | 7f08705f662a18cbe07fc4df8d2644b90a4e68df | 656,182 |
from typing import Counter
def count_neuron_frequency(neurons):
"""
Calculate neuron frequency for given labels sorted by id number and frequency (ensure the same frequency still keep sort by number )
Counter usage example: https://stackoverflow.com/questions/2161752/how-to-count-the-frequency-of-the-elem... | b0c6601be8036d62581587f0f6b986f93ce6e6b0 | 656,183 |
def csv_format_gaus(gaus):
"""flattens and formats gaussian names and bounds for CSV file"""
# gaus_names = []
# gaus_bounds = []
gaus_flat = []
for g in gaus:
gaus_flat.append(g[0] if g[0] else "-")
this_bounds = [g[5],g[6],g[1],g[2],g[3],g[4]]
gaus_flat += this_bounds
# return gaus_names, gaus_bounds
ret... | 82a853e540853d434fe9a1ba907c6afc1d6495b6 | 656,187 |
import re
def aggregate_alignments(align_tokens):
"""
Parse the alignment file.
Return:
- s2t: a dict mapping source position to target position
- t2s: a dict mapping target position to source position
"""
s2t = {}
t2s = {}
# process alignments
for align_token in align_tok... | 101aff41e0c8a3e311e765a70535ca4fee13535f | 656,188 |
def check_digit(option, num, min, max):
"""
文字列numが整数かチェックし, min-maxの範囲の数値であればTrueを返す
Args:
option: エラーメッセージに表示する文字列を指定. ''の場合はエラーメッセージを表示しない.
num: チェックする文字列
min: 数値の範囲の下限
max: 数値の範囲の上限
Returns:
bool: Trueなら問題なし. Falseなら整数でないか範囲外.
"""
val = False
try:
num_int = int(num)
... | c1a88535e8784bf0b8fd414ed72cce735296ea6c | 656,190 |
def thermal_diffusivity(tc, density, Cp):
"""
calc.thermal_diffusivity
Calculation of thermal diffusivity
Args:
tc: thermal conductivity (float, W/(m K))
density: (float, g/cm^3)
Cp: isobaric heat capacity (float, J/(kg K))
Return:
Thermal diffusivity (float, m^2/s... | 1edbf2489488d77d9028283569e1dc9372acc3d4 | 656,191 |
import gzip
def avg_fastq_quality(fastq_gz: str) -> float:
"""Calculate the mean quality for a set of sequencing reads in gzipped
FASTQ format with a quality offset of 33.
fastq: Path to a gzip-compressed FASTQ formatted set of sequencing reads
"""
total_length = 0
total_quality = 0
# D... | 89e706a7ddfae6fbf46c7deb577058047cc5cc02 | 656,195 |
def text_to_words(the_text):
""" return a list of words with all punctuation removed,
and all in lowercase.
"""
my_substitutions = the_text.maketrans(
# If you find any of these
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&()*+,-./:;<=>?@[]^_`{|}~'\\",
# Replace them by these... | 93a32d74674dc0a01d060fddd408ad93a08b77f7 | 656,196 |
def to_float(value: str) -> float:
"""Convert value to a floating point number"""
return float(value) | b6143a9211cd385bfd4ff6f171e01ce1a584b781 | 656,197 |
def validate_on_batch(
network,
loss_fn,
X,
y_target
):
"""Perform a forward pass on a batch of samples and compute
the loss and the metrics.
"""
# Do the forward pass to predict the primitive_parameters
y_hat = network(X)
loss = loss_fn(y_hat, y_target)
return (
loss... | 9502bd0f04bc4c8504442e6952f514dbe3044e1d | 656,199 |
def unwrap_solt(dc):
"""
Extracts the augmented image from Solt format.
:param dc: Solt datacontainer
:return: Augmented image data
"""
return dc.data | 200498792ee8b4d590fb7701409c76810b22bc5a | 656,207 |
def seen(params):
"""'.seen' & user || Report last time Misty saw a user."""
msg, user, channel, users = params
if msg.startswith('.seen'):
return "core/seen.py"
else:
return None | 2ddcf05ebb0edd83ac45574a9a682635b7914c94 | 656,211 |
from typing import Dict
from typing import Any
def merge_dicts(*args: Dict[Any, Any]) -> Dict[Any, Any]:
"""
Successively merge any number of dictionaries.
>>> merge_dicts({'a': 1}, {'b': 2})
{'a': 1, 'b': 2}
>>> merge_dicts({'a': 1}, {'a': 2}, {'a': 3})
{'a': 3}
Returns:
Dict: ... | 68cf2046f830610a9b386edebc8f16671dfc9293 | 656,213 |
import calendar
def get_month_number(month):
"""
Returns corresponding month number from month name
"""
abbr_to_num = {name: num for num, name in enumerate(calendar.month_abbr) if num}
month_number = abbr_to_num[month.capitalize()[:3]]
return month_number | e541d930c18724a59271fddf5e9251e110589ee7 | 656,215 |
def get_provenance_record(caption: str, ancestors: list):
"""Create a provenance record describing the diagnostic data and plots."""
record = {
'caption':
caption,
'domains': ['reg'],
'authors': [
'kalverla_peter',
'smeets_stef',
'brunner_lukas... | b4eba250f5a581989c80a8de727d7ed3e034bdd6 | 656,217 |
def color_negative_red(val):
"""
Takes a scalar and returns a string with
the css property `'color: red'` for negative
strings, black otherwise.
"""
color = "red" if val < 0 else "black"
return "color: %s" % color | 34f52a7311f7284a1c861c23b0ae31f52d905feb | 656,218 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.