content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def rchop(thestring, ending):
"""Removes the given ending from the end of the string"""
if thestring.endswith(ending):
return thestring[:-len(ending)]
return thestring | 904c6066ae835890be6273921b2b3e26c1d559a8 | 619,927 |
def get_median_values(data,ds):
"""extracts median abundance values
:param data: PTCF
:param ds: data set identifier (ds1 or ds1)
:return: median values of given data set
"""
values = data[[x for x in list(data) if x.startswith(ds) & (x!="ds1_cluster") & (x!="ds2_cluster") & (x!="gene")]]
return values.medi... | 546609aa78e9ff2e375a015781b984a87a0f9dfd | 619,932 |
import collections
def group_posts(parsed):
"""Take the raw list of posts and group them by categories."""
grouped = collections.defaultdict(list)
for post in parsed:
grouped[post['category']].append(post)
return grouped | 01c828710f672307d9ff0ae8ee495e687d4bb040 | 619,936 |
import torch
def from_onehot(y):
"""Converts one-hot encoded probabilities to label indices.
Parameters
----------
y: Tensor or Variable
Returns
-------
Tensor or Variable containing the label indices.
"""
_, labels_pred = torch.max(y, 1)
return labels_pred | dca11cc0b75447d64b06925d6fa2c443cb8e0128 | 619,938 |
def retrieve_hidden_word(full_word, found_letter):
"""This function returns a hidden word.
The hidden letters are marked with an asterisk *."""
hidden_word = ""
for letter in full_word:
if letter in found_letter:
hidden_word += letter
else:
hidden_word += "*"
... | 6eb142fe1e04dfd2d53785e21117bc70f773e898 | 619,944 |
import torch
def conv1x1(in_planes, out_planes, stride=1):
"""1x1 convolution"""
return torch.nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) | 2649d1c65e329da472ff79e893b356b0c8f4248f | 619,946 |
import requests
import logging
import json
def get_function_signature_from_4bytes(hex_signature):
"""
Requests the function signature from 4byte-directory based on the hex_signature to get the text_signature
Args:
hex_signature: the signature of the function as hex value
Returns:
signatu... | 7042efda7752bbfceaf3ed074e9635032075b4dd | 619,948 |
def filter_logic_form(lf: list, denylist: list) -> bool:
""" Checks whether logic form contains denylisted terms.
Parameter:
lf (list): logic form
denylist (list): denylisted terms
Returns:
False if logic form contains denylisted term(s).
True otherwise
"""
keep_flags = []
for... | 225fe8da438ada882090d6a6e857b151c367daab | 619,956 |
def calc_stats(total_unique_molecular_bases, total_bases, output_bases, genome_size, coverage):
"""
>>> calc_stats(0, 0, 0, 0, 0) == \
{'genome_size': 0, 'coverage': 0, 'total_bases': 0, 'total_unique_molecular_bases': 0, \
'output_bases': 0, 'unique_molecular_avg_cov': 0.0, 'output_avg_cov': 0.0, 'tota... | 610e062b31812c36050fc4ef179002d88680ce9f | 619,957 |
import requests
def get_live_url(channel):
"""
Finds a live stream url for channel
:param channel: Slug name of channel
:return An url
"""
apiurl = (
"http://ruv.is/sites/all/themes/at_ruv/"
"scripts/ruv-stream.php?format=json"
)
try:
json = requests.get(apiurl ... | 7936532ff62ef941f96cd8703aa2cc22eba3facc | 619,958 |
def sparse_min_size(value=1000):
"""Return minimal sparse problem size for which to warn about converting to dense."""
return value | d4ebe748cebef6695ff1ba3f19b6d3b302cbc977 | 619,964 |
def get_folders(values_dict):
"""Returns a dict of all the folders in the given value_dict."""
return dict(
(item, configs) for (item, configs) in values_dict.iteritems()
if item.endswith('/')
) | f383e21fedb4ee3510d1360a442fb0bfd32a9fd7 | 619,965 |
def wrap_lines(lines, line_length=80,
word_sep=' ', line_sep='\n',
strip_whitespace=True):
"""Wrap the contents of `lines` to be `line_length` characters long.
Parameters
==========
lines : string
Text to wrap
line_length : integer
Maximum number of cha... | 032c994dd946abac003b1a9beecadfe031d0deb2 | 619,966 |
def detect_id_type(sid):
"""Method that tries to infer the type of abstract ID.
Parameters
----------
sid : str
The ID of an abstract on Scopus.
Raises
------
ValueError
If the ID type cannot be inferred.
Notes
-----
... | 5f85199507509c281a560d59d18b6be9eec4a75b | 619,967 |
import re
def _get_index(passed_id=None):
"""
From the url w/ index appended, get the index.
"""
if passed_id:
index_matcher = re.search(r'.*?/?(\d+)$', passed_id)
if index_matcher:
return int(index_matcher.group(1))
# return 0 if no index found
return 0 | 1324e51561802911d1ea66858b618e6a35d65ee8 | 619,968 |
import random
def shuffle_data(x, y, d):
""" Randomly shuffle co-indexed lists, pertaining the alignment of the lists"""
xyd = list(zip(x, y, d))
random.shuffle(xyd)
x, y, d = zip(*xyd)
x, y, d = list(x), list(y), list(d)
return x, y, d | 093fa243fe1e6ae649fccd5946897a531789afc9 | 619,969 |
def mkdown_h(text, level, link=None):
"""
Generates the markdown syntax for a header of a certain level.
"""
if level == 1:
return '\n' + ('<a name="{}"></a>'.format(link) if link else '') + text + '\n' \
+ '='*len(text)
elif level == 2:
return '\n' + ('<a name="{}"><... | b9a0dfc9b2c570b6b0f80975cd1656d8234054ed | 619,976 |
import random
def simInsertions(numIndices, numInsertions):
"""Assumes numIndices and numInsertions are positive ints.
Returns 1 if there is a collision; 0 otherwise"""
choices = range(numIndices) #list of possible indices
used = []
for i in range(numInsertions):
hashVal = random.choice... | bf5bbf911b59f744766d200fd99a5e4f58aa39c7 | 619,978 |
def unrank_from_list(l):
"""
Returns an unrank function from a list.
EXAMPLES::
sage: import sage.combinat.ranker as ranker
sage: l = [1,2,3]
sage: u = ranker.unrank_from_list(l)
sage: u(2)
3
sage: u(0)
1
"""
unrank = lambda j: l[j]
retur... | 4f651a3e1a0ca17547aa8e11d947c5e5829d0fc8 | 619,980 |
def hydraulic_losses_suct_feed(dzeta_enter_feed, dzeta_turn90_feed, n_turn90_feed, dzeta_ventil_feed, n_ventil_feed, g, w_liq_real_enter_feed):
"""
Calculates the hydraulic losses of suction line.
Parameters
----------
dzeta_enter_feed : float
The local resistance of tube enter, [m]
dzet... | 6292100dcc7bd84c77d4b1277b22b3c438e66b67 | 619,988 |
import re
def remove_bad_quotes(text):
"""Returns a string with bad quotes removed"""
result = re.sub("[‘’“”…]", " ", text)
return result | a99b49f1062b2160cbe99808d0272029597d4478 | 619,989 |
def part_encode(part):
"""Encode a part of a JSON pointer.
>>> part_encode("foo")
'foo'
>>> part_encode("~foo")
'~0foo'
>>> part_encode("foo~")
'foo~0'
>>> part_encode("/foo")
'~1foo'
>>> part_encode("foo/")
'foo~1'
>>> part_encode("f/o~o")
'f~1o~0o'
>>> part_enc... | b95be1a1bdf1acc50949d0326462ce38181115c8 | 619,991 |
def getMonth(month):
"""Method to return the month in a number format
Args:
month (string): the month in a string format
Returns:
string: month in the number format
"""
if month == 'Jan':
return '01'
elif month == 'May':
return '05'
elif month == 'Jun':
... | 8ab9cf5f9fc1211de86c2c9280b4c40797a9b86f | 619,992 |
def ingest_dns_record(neo4j_session, name, value, type, update_tag, points_to_record):
"""
Ingest a new DNS record
:param neo4j_session: Neo4j session object
:param name: record name
:param value: record value
:param type: record type
:param update_tag: Update tag to set the node with and c... | d87ed351395b9ca0dd726914fcddd22f92721af9 | 619,996 |
def get_mir_counts(bamfile, gff_file):
"""
Takes a AlignmentFile and a gff file and computes for
each 'miRNA' region of the gff the number of reads that hit it
returns a dict[mir_name] = count
"""
counts = dict()
for line in open(gff_file, 'r'):
if line[0] != '#':
gff_fie... | 626be5f735ea983ed02b668ad9d4149d4bbb0cbd | 619,998 |
import shlex
def shell_variables(data):
"""
Prepare variables to be consumed by shell
Convert dictionary or list/tuple of key=value pairs to list of
key=value pairs where value is quoted with shlex.quote().
"""
# Convert from list/tuple
if isinstance(data, list) or isinstance(data, tuple... | 2bfc6f90683f9fe3344f573c425c32497085c97d | 619,999 |
def startswith_str(text, prefix, start=None, end=None):
"""
Determines if ``text`` starts with the specified prefix.
The prefix can also be a tuple of prefixes to look for. With optional parameter ``start``,
the test will begin at that position. With optional parameter ``end``, the test will
... | 0d8e035c215782a5d09ab2234daf832afd5914ae | 620,000 |
import math
def intRect(rect):
"""Round a rectangle to integer values.
Guarantees that the resulting rectangle is NOT smaller than the original.
Args:
rect: Bounding rectangle, expressed as tuples
``(xMin, yMin, xMax, yMax)``.
Returns:
A rounded bounding rectangle.
"... | 0453b70610b179f1d5652d983b90d1e3ebda9d26 | 620,006 |
def safe_filename(filename):
"""去掉文件名中的非法字符。
:param str filename: 文件名
:return str: 合法文件名
"""
return "".join([c for c in filename if c not in r'\/:*?"<>|']).strip() | a65d81496aaed7a71986492db71bc54813c46d1f | 620,009 |
import math
def make_line ( length ):
"""
Creates a list of bit strings of at least the given length, such
that the bit strings are all unique and consecutive strings
differ on only one bit.
Args:
length (int): Required length of output list.
Returns:
line (list): Lis... | 0de952612c9b7cedb5ef6bdcc402744936e46e4e | 620,011 |
def min_max_vals(vals):
"""
:param vals: an iterable such as list
:return: a tuple in which the first item is the minimum value from the iterable,
and the second item is the maximum value from the iterable
"""
sorted_vals = sorted(vals)
return sorted_vals[0], sorted_vals[-1] | c07e122e7369a946a6c0ad5612270d979be84ef3 | 620,012 |
def neighbors(i, j, m, n):
"""
Returns the neighboring indices for a given index
in a matrix of m x n shape
"""
# Sets default delta indices
# Adjust delta indices for given index on edge of matrix
inbrs = [-1, 0, 1]
if i == 0:
inbrs = [0, 1]
if i == m-1:
inbrs = [-1... | eac8cc665499ef9d65cecabf49a68ea3916e5c65 | 620,016 |
def skip_if(condition):
"""Skips the decorated function if condition is or evaluates to True.
Args:
condition: Either an expression that can be used in "if not condition"
statement, or a callable whose result should be a boolean.
Returns:
The wrapped function
"""
def real_skip_if(fn):
de... | 818bb831724dedf4be703c80e5802c6242556d06 | 620,018 |
import functools
def checkopen(meth):
"""Verify that the file is open before applying a file method. Raises
ValueError if the file is closed.
"""
def wrapper(self, *args, **kw):
if self.handle is None:
raise ValueError("I/O operation on closed file")
return meth(self, *arg... | c2fd766835ad7de969f4f4c51392429d766260b1 | 620,023 |
def distance(a, b):
"""Calculate the distance between two points a and b."""
return ((a[0] - b[0])**2 + (a[1] - b[1])**2)**0.5 | ef4cb52de488c48466432ffc233e570e581d4046 | 620,025 |
import logging
def setup_logger(
log_fp=None,
log_stdout=True,
log_format="%(asctime)s %(levelname)-8s [Workbench] %(message)s"
):
"""
Set up and return a logging instance.
Logs will be printed to standard out by default (with log_stdout=True).
If `log_fp` is provided, logs will also be ap... | 7e2ac5b3cbeae0f4ac49c011606ec31e552b7a36 | 620,032 |
import re
def unir_fragmentos(texto):
"""Une fragmentos de palabras partidas por final de línea.
Parameters
----------
texto : str
Returns
-------
str
Texto con palabras de fin de línea unidas si estaban partidas.
"""
# Asume ord('-') == 45
return re.sub(r'-\n+', '', ... | 2ebdced6f1f09f1090768bccee9bf778f9c32952 | 620,033 |
def center_crop(data, crop_shape, labels=None):
"""
Perform random cropping after optional padding
Args:
data: data array representing 1 image [h, w]
labels: labels array [h, w, 2] (unique values limited to (0, 1)), could be None
crop_shape: target shape after cropping
Returns:
... | 5d66b00994512f0d247dd4cf4d5ea00b74e749e1 | 620,036 |
def create_point_datatype(records):
"""
Creates point datatype to enable fetching GeoJSON from Socrata
:param records: list - List of record dicts
"""
for record in records:
latitude = record["latitude"]
longitude = record["longitude"]
# Socrata rejects point upserts with no ... | 3c762ad4cfbad5ef66cb84a91b5a9dcd0e7bfb4f | 620,037 |
def _pad_jagged_sequence(seq):
"""
Pads a 2D jagged sequence with the default value of the element type to make it rectangular.
The type of each sequence (tuple, list, etc) is maintained.
"""
columns = max(map(len, seq)) # gets length of the longest row
return type(seq)(
(
... | 65285795ccf56edaea61180d42bca861df2d0794 | 620,038 |
def get_league_scoreboards(league, week):
"""
Returns the scoreboards from the specified sleeper league.
:param league: Object league
:param week: Int week to get the scoreboards of
:return: dictionary of the scoreboards;
https://github.com/SwapnikKatkoori/sleeper-api-wrapper#get_scoreboards... | f079573522e9c04400de3bb8802124f47063f9d9 | 620,041 |
def true_param(p):
"""Check if ``p`` is a parameter name, not a limit/error/fix attributes."""
return (
not p.startswith("limit_")
and not p.startswith("error_")
and not p.startswith("fix_")
) | 46d588e1bcbba5f9d031b7734858e3743052ed54 | 620,046 |
def rotate180_augment(is_training=True, **kwargs):
"""Applies rotation by 180 degree."""
del kwargs
if is_training:
return [('rotate180', {})]
return [] | 4973181fed90fbe4639de7f2eae8b2fe3b5f2448 | 620,048 |
def flatten(nested_list):
"""
Called by loanpy.adrc.Adrc.repair_phonotactics and loanpy.adrc.Adrc.adapt.
Flatten a nested list and discard empty strings (to prevent feeding \
empty strings to loanpy.adrc.Adrc.reconstruct, which would throw an Error)
:param nested_list: a nested list
:type nested_li... | 7266d94c991d157b183b7d3ff6a6642a2ef74ddd | 620,050 |
def buildCircuit(circuit_string, parameters, frequencies):
""" transforms a circuit_string, parameters, and frequencies into a string
that can be evaluated
Parameters
----------
circuit_string : str
parameters : list of floats
frequencies : list of floats
Returns
-------
eval_s... | f23e6a180fed8ca7b516eb067854b140a8f28bff | 620,051 |
def fix_location_header(request, response):
"""
Ensures that we always use an absolute URI in any location header in the
response. This is required by RFC 2616, section 14.30.
Code constructing response objects is free to insert relative paths, as
this function converts them to absolute paths.
... | 14d1f1e2c7f1f3405dcc05d4dd0053f6168cffb4 | 620,053 |
def distance_between_sq(x1: float, y1: float, x2: float, y2: float) -> float:
"""
Returns the squared distance between the two points (x1, y1) and (x2, y2)
"""
dx = x2 - x1
dy = y2 - y1
return dx**2 + dy**2 | 07e0022ef4b4b7581070ff649b5059628bb84a07 | 620,054 |
from typing import Any
def round_coordinates(data: Any) -> Any:
"""Recursively round lat,lon floats to 2 digits"""
if isinstance(data, dict):
for key, val in data.items():
if key in ("lat", "lon"):
data[key] = round(val, 2)
else:
data[key] = roun... | 4e1a7e9c5b8aefed33b9410e5fb872e317cebe5e | 620,055 |
def create_dummy_class(klass, dependency, message=""):
"""
When a dependency of a class is not available, create a dummy class which throws ImportError
when used.
Args:
klass (str): name of the class.
dependency (str): name of the dependency.
message: extra message to print
... | d3e9d1d1c9d222be10d14ec4769639360d55e7dc | 620,059 |
import re
def parse_remote_msg(msg):
""" Figure out the different components of the output of the remote script.
Arguments
---------
msg: str
Unicode string that encodes the output.
Returns
-------
error_msg: str
List of error messages, empty list means no errors.
exe... | a472cdcf6b7193730c583f03b931e8805db6d8dc | 620,063 |
def sanitize_releasability(releasability, user_sources):
"""
Remove any releasability that is for sources a user does not have access to
see.
:param releasability: The releasability list for a top-level object.
:type releasability: list
:param user_sources: The sources a user has access to.
... | 0316f7e1dfc883d1db9d5fdc9db251045becc239 | 620,069 |
def _trim_comment(line) -> str:
"""Remove comment from end of line, if any"""
if '#' in line:
icomment = line.index('#')
line = line[:icomment]
return line | 2b6f48969d468638823e92b9cc5dc11c41a79fea | 620,073 |
def cutout_subimage(image2d,
startx=0,
starty=0,
width=100,
height=200):
"""Cutout a subimage ot of a bigger image
:param image2d: the original image
:type image2d: NumPy.Array
:param startx: startx, defaults to 0
:type... | 3e98bda2fc7eae0513a80cf699da60c6a7315e38 | 620,082 |
def calc_sums(variable):
"""
Aggregates the instance dimension of the variable tensor object (see documentation in ../process_raw_data.py)
by summing up the values of the instances.
note: this function is called after the database check -> all values are available and valid.
:param variable: data s... | b88a4352926b23dd27ea598d746619e8c9911ada | 620,083 |
from typing import Dict
from typing import Any
import requests
def get_cluster_status() -> Dict[str, Any]:
"""
Returns the Spark cluster status
:return: Dict[str, Any]
"""
spark_status_url = "http://localhost:8080/json/"
r = requests.get(url=spark_status_url)
return r.json() | 2c3a14f84d940ddc13b7bf5b18b6eb2813a0c388 | 620,084 |
def test(
name: int = 1) -> int:
"""
参数名后跟冒号,冒号后的内容为type hint,表示建议的参数类型,也可以正常赋予默认值,如上所示
括号外的部分用 -> 随后跟随的为返回结果的type hint,表示对结果的建议类型
:param name:
:return:
"""
print(type(name))
print(name)
return name + 2; | c4d67f9d05d3fdde3825b1dc71262a4f235067b0 | 620,087 |
def list_to_str(lst, item_len=1):
"""Format lists as ,(;) separated strings."""
if item_len == 1:
if lst:
return ",".join(str(lst_itm) for lst_itm in lst)
else:
return "None"
else:
joined_items = []
for sub_lst in lst:
joined_items.append("... | 7f92e1eed843e234e25a8a48ce74879e6ef73ca4 | 620,089 |
from functools import reduce
def calculate_adr(bars):
"""
Given a series of bars from the IB client, calculates the ADR
"""
total = reduce(
lambda acc, bar: acc + (bar.high / bar.low),
bars,
0)
return round(100 * ((total / len(bars)) - 1), 1) | 37ed63807dbc80a05a1d8138a199d406b1bd1689 | 620,091 |
def set_io_tile_options(opts,
num_io_tiles,
place_ops_on_io_tiles=None,
io_tile_available_memory_proportion=0.9):
"""Set the number of tiles reserved for I/O per IPU.
Args:
num_io_tiles: Number of tiles to reserve I/O.
place_ops_on_io_... | d7639d8599669efc59db7972e527a8a6f4aab819 | 620,094 |
def rhog(mw, p, tk):
"""
Calculate gas density from molecular weight, pressure, and temperature.
Parameters
----------
mw : float
Molecular weight of gas [g/mol]
p : float
Pressure of the gas [Pa]
tk : float
Temperature of the gas [K]
Returns
-------
rho... | d7bcc93d84ca77e420751e5c8e811cfaa767f538 | 620,097 |
import re
def is_valid_remote_clone_id(remote_clone_job_id):
"""
Validates a remote clone job ID, also known as the remote clone job
"job_name". A valid remote clone job name should look like:
dstrclone-00000001 - It should end with 8 hexadecimal characters in
lower case.
:type remote_clone_j... | 186700e080bc372679d14b7af6ed8e83dcc4f04b | 620,099 |
import json
def read_config(config_path):
"""read config_path and return options as dictionary"""
result = {}
with open(config_path, 'r') as fd:
for line in fd.readlines():
if '=' in line:
key, value = line.split('=', 1)
try:
result[k... | 39c04cf6e16ee2d5b03ca9851bda02ca5cc81d52 | 620,101 |
def remove_outliers(compiled, plot_type, data_type = "raw"):
"""[removes outliers from dataframe]
Args:
compiled ([dataframe]): [raw dataframe containing outliers to be removed]
plot_type ([str]): [string can either be 'hist' for histogram data or 'TDP' for TDP data]
data_type (str, opt... | 496b27d84bb74081d573007e2a598e4ab3eadb09 | 620,105 |
import re
def parse_hpxregion(region):
"""Parse the ``HPX_REG`` header keyword into a list of tokens.
"""
m = re.match(r"([A-Za-z\_]*?)\((.*?)\)", region)
if m is None:
raise ValueError(f"Failed to parse hpx region string: {region!r}")
if not m.group(1):
return re.split(",", m.gr... | 8265aab08a819d538e92abadc20b9f8fd04b4601 | 620,106 |
def doi_identifier(identifiers):
"""Extract DOI from sequence of identifiers."""
doi_identifier = identifiers.get("doi")
return doi_identifier['identifier'] if doi_identifier else None | 42ad222724eef080ecd41689549c2fb84f1c2a88 | 620,109 |
def find_combos(length: int) -> int:
"""
In the data, there are no gaps of two, only gaps of one or three, between
numbers in the sorted list.
The rules are such that the number of combos are the same regardless
of the specific numbers involved--there are the same number of combos
for [0, 1, 2, ... | 8ff8d5c161508c9d55d24ddbcfa2f67f8e95fc5b | 620,115 |
def get_rain_str(risk_of_rain: float) -> str:
"""
Return string in french with risk of rain info
:param risk_of_rain: Risk of rain between 0 and 1
:return: string
"""
if risk_of_rain < 0.33:
return f'Risque de pluie : {int(100*risk_of_rain)}%.'
if risk_of_rain < 0.66:
return ... | 76fb030317eb9db13a52c41aa20652d71d519ece | 620,117 |
def truncate(string, length=20):
"""Truncate a string and add ellipsis, if-needed.
Args:
string (str): String to be truncated
length (int, optional): Lenth of string to truncate
Returns:
str: Truncated string
"""
ellipsis = '..'
# Append ellipsis if-needed
if len(... | 47b2173f9de8ec17328d1cf05edaf383e7b30791 | 620,123 |
def GetReverseDependencyClosure(full_name, deps_map):
"""Gets the closure of the reverse dependencies of a node.
Walks the tree along all the reverse dependency paths to find all the nodes
that transitively depend on the input node.
"""
s = set()
def GetClosure(name):
s.add(name)
node = deps_map[na... | 17f28c06075a495732a8dc59ea1434cd3888f70b | 620,125 |
import json
def decode_transaction(raw):
"""Decode a transaction from bytes to a dict."""
return json.loads(raw.decode('utf8')) | 24376971f21b9410b881de6e85fd3105425f89be | 620,133 |
def compute_response_integral(X, stim_frames):
"""
Compute the integrated/summed response over all stimulus frames
Arguments:
X (array): dF/F of size (trials, time frames, boutons)
stim_frames (array): time frames w/ stimulus
Returns:
Xint (array): summed dF/F during stim frames... | 073e512b8dc8d7a09dbbb813c3717861cf6eb179 | 620,137 |
def derive_state(state_list):
"""
Compute a derived state an object. This will be based off the states of
the objects based in.
:param state_list: List of objects that have a get_state() method.
:returns: State as a string.
"""
# If there are no ports passed in, we assume it is an internal... | 54d08eddee8da85fd5da7f65eed698cef48e868f | 620,142 |
def ensure_nest_alts_are_valid_alts(nest_spec, list_elements, all_ids):
"""
Ensures that the alternative id's in `nest_spec` are all in the universal
choice set for this dataset. Raises a helpful ValueError if they are not.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
... | 0e2c9b39f7941a1f9fff5f342281d87e1d0decfc | 620,143 |
def Gt(a, b):
""" Create an SMT greater-than.
See also the __gt__ overload (> operator) for arithmetic SMT expressions.
>>> x, y = Ints('x y')
>>> Gt(x, y)
x > y
"""
return a > b | 4396206167b83a8524587b8e984b67b3e8881ff3 | 620,145 |
def hamilton_product(q1, q2):
"""
Performs composition of two quaternions by Hamilton product. This is equivalent
of a rotation descried by quaternion_1 (q1), followed by quaternion_2 (q2).
https://en.wikipedia.org/wiki/Quaternion#Hamilton_product
:param q1: 4-item tensor representing unit quaternion.
:pa... | f917cae87fe2bfa100177fda5b1bd56536cfa8bd | 620,146 |
def find_highest_multiple_of_three_ints(int_list):
"""Takes in a list of integers and finds the highest multiple of three of them"""
if type(int_list) != list:
raise TypeError(
"The argument for find_highest_multiple_of_three_ints must be of type list.")
elif len(int_list) == 3:
... | 505d15a76ca96a819cf5a81e836152d88d437475 | 620,149 |
def get_states(weighted_samples):
"""
Get the states from set of weighted particles.
:param weighted_samples: list of weighted particles
:return: list of particle states without weights
"""
return [ws[1] for ws in weighted_samples] | a8e1a639d8cbbac4aede8cc6454da06c10f6e6fd | 620,151 |
import inspect
def get_required_kw_args(fn):
"""
获取函数命名关键参数,且非默认参数
:param fn: function
:return:
"""
args = []
# 获取函数fn的参数, orderd mapping
params = inspect.signature(fn).parameters
for name, param in params.items():
# *或者 *args 后面的参数, 且没有默认值
if param.kind == param.K... | 5e441d336461c67dd624d2bcace3219fa5a49bfc | 620,155 |
def get_portgroup_by_id(task, portgroup_id):
"""Lookup a portgroup by ID on a task object.
:param task: a TaskManager instance
:param portgroup_id: ID of the portgroup.
:returns: A Portgroup object or None.
"""
for portgroup in task.portgroups:
if portgroup.id == portgroup_id:
... | 590c09cdbe7130d675d59465488509f8583a0018 | 620,159 |
def enquote1(text):
"""Quotes input string with single-quote"""
in_str = text.replace("'", r"\'")
return "'%s'" % text | f1b4610b1aa994fc6d79e36130a6209e5ca61437 | 620,162 |
def get_strptime_pattern(s):
"""
:param s: str
:return: get strptime pattern
NOTE: be careful with microseconds. It is not handled properly
"""
if len(s) > 20:
raise Exception("Too big string")
return "%Y%m%d%H%M%S%f"[: int(len(s) - 2)] | 3c376bc9c5f5ad9ff3aad1212701bc25a1261177 | 620,165 |
def compute_field_capacity(clay_val, oc_val, sand_val):
"""
Calculate Field Capacity based on Clay, Organic Matter and sand value
:param clay_val: percentage of clay
:param oc_val: percentage of organic carbon
:param sand_val: percentage of sand
:return: a float value representing FC
"""
... | f24522ee1c9369ee11cf63c81f1da9dfeeff802d | 620,168 |
def _add_missing_parameters(flattened_params_dict):
"""Add the standard etl parameters if they are missing."""
standard_params = ['ferc1_years',
'eia923_years',
'eia860_years',
'epacems_years',
'epacems_states']
for ... | de4eadeeafa09e446acec7fe6c683b43c5c5d5e9 | 620,175 |
def completions_sorting_key(word):
"""key for sorting completions
This does several things:
- Lowercase all completions, so they are sorted alphabetically with
upper and lower case words mingled
- Demote any completions starting with underscores to the end
- Insert any %magic and %%cellmagic... | 1ddebfbdd750cd8e4d21fca6b359bace33280638 | 620,177 |
def noop(x=None, *args, **kwargs):
"""Do nothing"""
return x | 37aae64ab28bb085be8fb2dbd76781e770da4b3f | 620,178 |
def filter_blacklist(genes, blacklist, field='gene_id'):
"""Filters potential hits against given blacklist."""
return genes.loc[~genes[field].isin(blacklist)] | 9af27b7f0e9e74dd0f968392707666c7aedef78a | 620,183 |
from typing import Counter
def gc_content(sequence, as_decimal=True):
"""Returns the GC content for the sequence.
Notes:
This method ignores N when calculating the length of the sequence.
It does not, however ignore other ambiguous bases. It also only
includes the ambiguous base S (G o... | 9e624b726d3f3bdfa851bcd2cc04f7ca11096928 | 620,185 |
from typing import OrderedDict
def optimise_autopkg_recipes(recipe):
"""If input is an AutoPkg recipe, optimise the yaml output in 3 ways to aid
human readability:
1. Adjust the Processor dictionaries such that the Comment and Arguments keys are
moved to the end, ensuring the Processor key is firs... | c48611e6b47c9b9061146ddc5190645339b97578 | 620,187 |
def remove_quotes(string: str) -> str:
"""
Removes quotes from around a string, if they are present.
:param string: The string to remove quotes from.
:return: The string without quotes.
"""
# If starts and ends with double-quotes, remove them
if string.startswith('\"') and string.e... | f954212ac17537fe9fcca9f4f25b189ffb7c2d22 | 620,189 |
def find_range(arr: list[int], val: int) -> list[int]:
"""Binary search to find the range of a given number ‘val’.
The range of val will be the first and last position of val in the arr.
Complexity:
Time: Θ(logn) <=> O(logn) & Ω(logn) (since we must consider duplicates)
Space: O(1)
Ar... | fb353838b7bc2a83caaf3e336da2582d4df3fbe2 | 620,190 |
def _get_csr_submatrix_major_axis(Ap, Aj, Ax, start, stop):
"""Return a submatrix of the input sparse matrix by slicing major axis.
Args:
Ap (cupy.ndarray): indptr array from input sparse matrix
Aj (cupy.ndarray): indices array from input sparse matrix
Ax (cupy.ndarray): data array from... | 55e08d84aa8e0626d169ed621f7ede294e20b12b | 620,191 |
def decode(seqIdx, idxToToken, delim=None, stopAtEnd=True):
"""
Given seqIdx (list of token_ixs), decode to a sentence.
"""
tokens = []
for idx in seqIdx:
tokens.append(idxToToken[idx])
if stopAtEnd and tokens[-1] == '<END>':
break
if delim is None:
return tokens
else:
return delim... | 8d915de1245938ae9c284c97e7177bcd2445e5e3 | 620,193 |
import difflib
def DiffFileContents(expected_path, actual_path):
"""Check file contents for equality and return the diff or None."""
with open(expected_path) as f_expected, open(actual_path) as f_actual:
expected_lines = f_expected.readlines()
actual_lines = f_actual.readlines()
if expected_lines == ac... | fa332cc58d6d2a713700d91bea859a3e1d24a5b8 | 620,194 |
def strip_dav_path(path):
"""Removes the leading "remote.php/webdav" path from the given path.
:param str path: path containing the remote DAV path "remote.php/webdav"
:return: path stripped of the remote DAV path
:rtype: str
"""
if 'remote.php/webdav' in path:
return path.split('remote... | 0f6ea4d0ff3da5236dd361673d18016fd1be65e1 | 620,197 |
def findTrend(trend, trendList):
""" Finds a specific trend tuple within a list of tuples """
# Assuming the lack of duplicates
for tIndex in range(len(trendList)):
if len(trendList[tIndex]) == 2:
if trendList[tIndex][0] == trend:
return tIndex, trendList[tIndex]
retu... | eea1bf32dc5ce04be3610be4d821d342bf474982 | 620,201 |
from typing import Any
def latex_repr(item: Any) -> str:
"""
Return a str if the object, 'item', has a special repr method
for rendering itself in latex. If not, returns str(result).
"""
if hasattr(item, "_repr_latex_"):
return item._repr_latex_().replace("$", "")
elif hasattr(item, "... | 4390900c07dc4e4d7b90e5556a1871f2383891fd | 620,203 |
def _scalar(x):
"""Convert a scalar tensor into a Python value."""
assert x.numel() == 1
return x[0] | f3cac6f72bbbeaa4050642001ad83c86e6c0e9ca | 620,210 |
def look_ahead_line(fd):
"""
Read and return a line from the given file object. Saves the current
position in the file before the reading occurs and then, after the reading,
restores the saved (original) position.
"""
lastpos = fd.tell()
line = fd.readline()
fd.seek(lastpos)
return ... | bce476a9d2a832ed5d6660b16e41343a0cffd5ff | 620,212 |
def GetComplementaryColor(hexStr):
"""Returns complementary RGB color
Example Usage:
>>> GetComplementaryColor('#FFFFFF')
'#000000'
"""
if hexStr[0] == '#':
hexStr = hexStr[1:]
rgb = (hexStr[0:2], hexStr[2:4], hexStr[4:6])
compColor = '#'
for a in rgb:
comp... | 5c42a8ccfc48f57d4f8ba2728b83ad0972dbd644 | 620,214 |
def is_in_grid(index, maximum):
"""Check if index is within grid range."""
return 0 <= index <= maximum | c6b7065b5ec201fc64bc0d190d51606a399f05b7 | 620,217 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.