content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def configure_peak_deconvolution(new_d,min_peak_height,min_sn_ratio,min_peak_duration,max_peak_duration):
"""
"""
idx = [i for i,d in enumerate(new_d['batch']['batchstep']) if 'DeconvolutionModule' in d['@method']][0]
idx2 = [i for i,d in enumerate(new_d['batch']['batchstep'][idx]['parameter']) if ... | cd3bd48634fbf658eb24556b8119c6c582b7522c | 689,804 |
import torch
def bboxes_iou(bboxes_a: torch.Tensor, bboxes_b: torch.Tensor):
"""2つの矩形の IOU を計算する。
Args:
bboxes_a (torch.Tensor): [description]
bboxes_b (torch.Tensor): [description]
Returns:
[type]: [description]
"""
area_a = torch.prod(bboxes_a[:, 2:], 1)
area_b = to... | e7bdd731873f0a2d995278495aa1ce625f33f74a | 689,805 |
def concat_op_support(X, bXs, tXs):
# Type: (XLayer, List[XLayer], List[XLayer]) -> boolean
""" Check whether we can execute the provided Concat operator
on the ultra96 target """
axis = X.attrs['axis']
channels = X.shapes[axis]
return channels >= 1 and channels <= 2560 | 14d34e65b6bdd9e5c6fd9968d951518d4204a642 | 689,806 |
def _default_dcos_error(message=""):
"""
:param message: additional message
:type message: str
:returns: dcos specific error message
:rtype: str
"""
return ("Service likely misconfigured. Please check your proxy or "
"Service URL settings. See dcos config --help. {}").format(
... | 9427334a6833090c685b0f9d689e72e6c602d84d | 689,808 |
def add_articles_from_xml(thread, xml_root):
"""Helper function to create Article objects from XML input and add them to a Thread object."""
added_items = False
for item in xml_root.find('articles').findall('article'):
data = {
'id': int(item.attrib['id']),
'username': item.... | be7e32fdd4831c101842fb8f939d2ce0ea3942f5 | 689,809 |
def load_version(file_path):
"""
Reads in the version file & pulls out the version info.
Requires a ``file_path`` argument, which should be the path to the file.
Example::
>>> import rose
>>> rose.load_version('VERSION')
'1.0.0-final'
>>> rose.load_version(os.path.join... | 328b700f9319cb7605ac2ffa8072771521620947 | 689,810 |
import base64
def decode(payload):
"""
https://en.wikipedia.org/wiki/Base64#URL_applications modified Base64
for URL variants exist, where the + and / characters of standard
Base64 are respectively replaced by - and _
"""
variant = payload.replace('-', '+').replace('_', '/')
return base64.... | f272a3b81544a32a07a1c8aecaa66fa39a51f63e | 689,811 |
def decolonize(val):
"""Remove the colon at the end of the word
This will be used by the unique word of
template class to sanitize attr accesses
"""
return val.strip(":") | 41785bcc38afb812c3ed218e14a3004d0f480ca5 | 689,812 |
def hello():
"""Welcome function to test Flask"""
return "Welcome to the djtango server" | 4a70e80fc5325ab77d59a01a2c603d9ec4754f89 | 689,813 |
import logging
def get_memory_handler():
"""Get MemoryHandler for root logger.
This is used to connect the logging module to log table view in
Main Window.
:rtype: logging.handlers.MemoryHandler
"""
return logging.root.handlers[2] | e44b1dd56b47756190d28ad766018d7c9cab857b | 689,814 |
import subprocess
def test_intents(user_input=""):
"""
Return a string that is the output from subprocess
"""
#out = subprocess.check_output(["C:\\Users\\peter\\Anaconda3\\Scripts\\activate.bat", "NLU", "&&", "C:\\Users\\peter\\Anaconda3\\python.exe", "eval.py", "--eval_train=False", '--checkpoint_dir... | da51f93ff7b4b756342ffa57ff0052cec7219c86 | 689,815 |
def read_trajectory(traj_path):
""" Read xyz trajectory and return coordinates as a list
Args:
- traj_path (str): xyz trajectory path to read
Returns:
- dict: Trajectory dictionary with atoms, coordinates, timestep and xyz keys
"""
with open(traj_path, 'r') as t:
... | 5f79f7c4f2a745e5d9ba7a607694fb939f841b2b | 689,816 |
def BuildInstanceConfigOperationTypeFilter(op_type):
"""Builds the filter for the different instance config operation metadata types."""
if op_type is None:
return ''
base_string = 'metadata.@type:type.googleapis.com/google.spanner.admin.database.v1.'
if op_type == 'INSTANCE_CONFIG_CREATE':
return base... | dbd633c199c78bd529109c258036095a1e681986 | 689,817 |
import re
from datetime import datetime
def datetime_to_yyyymmdd(s: str) -> str:
"""
Convert a datetime string to a string in the yyyymmdd format.
日付がyyyymmddになっていない場合修正。
"""
pat_datetime = re.compile(r"(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})")
m = pat_datetime.match(str(s))
if m:
... | 7be3c8d04fe87d38ab2617b63b72b40e9ba47f67 | 689,818 |
def get_issue_set(data):
"""获取独一的 issue id 集合"""
issue_set = set()
for d in data:
issue_set.add(d[1][0][0])
return issue_set | 025e78431a9d49ea984ec603ccf620b30ac5f942 | 689,819 |
import os
def get_path(file_name='',
save_folder='models',
dataset='pie',
save_root_folder='data/'):
"""
A path generator method for saving model and config data. It create directories if needed.
:param file_name: The actual save file name , e.g. 'model.h5'
:param save_folder: The name of folder conta... | d6f86a93bacf66a0efe49271f8e2a0ec3b8b7d01 | 689,820 |
from datetime import datetime
def _parse_publishing_date(string):
"""
Parses the publishing date string and returns the publishing date
as datetime.
Input example (without quotes): "Wed, 09 Nov 2016 17:11:56 +0100"
"""
return datetime.strptime(string,"%a, %d %b %Y %H:%M:%S +0100") | e0ddc6da2a8acb90cceb4649f0d8491531408fcb | 689,821 |
def multiply(k, v1):
"""Returns the k*v1 where k is multiplied by each element in v1.
Args:
k (float): scale factor.
v1 (iterable): a vector in iterable form.
Returns:
iterable: the resultant vector.
"""
newIterable = [k * i for i in v1]
return tuple(newIterable) if typ... | 6ef0bc8fc0321c803655062c88cc38c23608a068 | 689,822 |
def definition():
"""
View of v_s_mri to be used for providing budgetted
recruitment figures to Y0 & Y1.
"""
sql = """
SELECT acad_year, programme, aos_code, session, school, fee_cat, SUM(student_count) as student_count
FROM (
SELECT v.acad_year,
CASE WHEN session = 0 THEN 'Foundati... | 609f6787dad128f04214e005dbb3e82b5415d16c | 689,823 |
import string
def is_valid_sha1(sha1: str) -> bool:
"""True iff sha1 is a valid 40-character SHA1 hex string."""
if sha1 is None or len(sha1) != 40:
return False
return set(sha1).issubset(string.hexdigits) | bcf0dc6bb568bbbfaaa0b162ee3d400cfe79ce6f | 689,824 |
def nvmf_subsystem_remove_listener(
client,
nqn,
trtype,
traddr,
trsvcid,
adrfam,
tgt_name=None):
"""Remove existing listen address from an NVMe-oF subsystem.
Args:
nqn: Subsystem NQN.
trtype: Transport type ("RDMA").
traddr: Trans... | ab3ec836f330a1e67befdbf4cc31f6bda489baa5 | 689,825 |
def _is_projective(parse):
"""
Is the parse tree projective?
Returns
--------
projective : bool
True if a projective tree.
"""
for m, h in enumerate(parse):
for m2, h2 in enumerate(parse):
if m2 == m:
continue
if m < h:
i... | 10032f43b066c60a2754f0b639f2e572d4b0b547 | 689,826 |
import re
def unescape(value):
"""
copy of unescape from openpyxl.utils.escape, openpyxl version 2.4.x
"""
ESCAPED_REGEX = re.compile("_x([0-9A-Fa-f]{4})_")
def _sub(match):
"""
Callback to unescape chars
"""
return chr(int(match.group(1), 16))
if "_x" in valu... | 74cc80b7f9634be894d54571e11431b2215dc0ac | 689,827 |
import requests
def deepl(english_sentence, target_lang='FR'):
"""Query deepl via their jsonrpc to translate the given
english_sentence to the given target language.
May return an empty string on failure.
"""
response = requests.post(
'https://www.deepl.com/jsonrpc',
json={"jsonrp... | 1c8fd532f91928e09367b13f58d35c03526c4edc | 689,828 |
import torch
def safe_power(x, exponent, *, epsilon=1e-6):
"""
Takes the power of each element in input with exponent and returns a tensor with the result.
This is a safer version of ``torch.pow`` (``out = x ** exponent``), which avoids:
1. NaN/imaginary output when ``x < 0`` and exponent has a frac... | c384c43482fd9cba4957b115555c58f1c6fa50ce | 689,830 |
def fattr(key, value):
"""Decorator for function attributes
>>> @fattr('key', 42)
... def f():
... pass
>>> f.key
42
"""
def wrapper(fn):
setattr(fn, key, value)
return fn
return wrapper | a69d8c929cb53022a8c7b563d3a268d880d32974 | 689,831 |
import pathlib
import os
def export_filepath(filename, output_dir, filetype):
"""
Constructs the file path to be exported, based on user preferences.
Will return None if the file path could not be constructed. Will check if
the target directory exists beforehand and create if necessary.
Arguments... | 0eb9066bcd512af608d55f6285582b374c0fc1ed | 689,832 |
def bitcode(env):
""" Print LLVM bitcode for the given compiled environment """
return env['cgen'].module | c1eac1ceae4aa474f2223f52488c5b2d578a940d | 689,833 |
import pickle
def unpickle_from_disk(filename):
"""Unpickle an object from disk.
Requires a complete filename
Passes Exception if file could not be loaded.
"""
# Warning: only using 'r' or 'w' can result in EOFError when unpickling!
try:
with open(filename, "rb") as pickle_file... | 7b4f1d4d6534c2bdc1c8377198e92441c0c69ef1 | 689,834 |
def method_with_bad_names_on_multiple_lines_1(
myBadlyNamedParam,
):
"""Provide parameters with bad names on multiple lines."""
return myBadlyNamedParam + 5 | d4d759d8d3507b09dbbd64452c4dde4e51917862 | 689,835 |
def slugify(text):
"""Replaces any preceding or trailing whitespace from a given string and replaces all spaces with an underscore"""
return text.strip().replace(' ', '_') | d0884dff55f6a1e5fdb5e114668fccd5918b4cd8 | 689,836 |
def minutes_to_runtime(minutes):
"""Turns an amount of minutes into a runtime as if for a movie or TV show
:param minutes: The amount of minutes to turn into a runtime
"""
# Turn the minutes into hours
hours = minutes // 60
# Return the result
return "{}h {}m".format(hours, minutes - (hour... | a2e03373a2399be180692e643faa60748a5021ec | 689,837 |
def remove_double_quotes_from_teams_alert(alert):
"""Remove double quotes from all the fields"""
for field in alert.__dict__:
if field == "extra_annotations" or field == "extra_labels":
new_inner_map = {}
for inner_field in alert.__getattribute__(field):
original_... | a538d422a3ac35dbb0c901eb29898b8880fc813a | 689,838 |
def parse_alnsummary(rawalnsummary):
"""Parse alnsummary line from exonerate using 'parsable' preset.
Takes an alnsummary line from an alignment that was generated from an ryo
'parsable' preset.
"""
# 'aln_summary: %qi %ql %qab %qae %qS %ti %tl %tab %tae %tS %s %et %ei %pi\n'
data = rawalns... | a383c0494cb761795af072b81dc0f33573a73138 | 689,839 |
import os
import yaml
def gen_var_dict(args):
"""Generate variable dict for epy parsing"""
var_dict = {}
if args.define:
for var_pair in args.define:
var, val = var_pair.split('=', 1)
var_dict[var] = val
if args.setenv:
for var_pair in args.setenv:
... | 120cde878a80659b06de38245d9b04c71410f84a | 689,840 |
import base64
def make_jira_auth(username: str, password: str) -> str:
"""Makes an auth header for Jira in the form 'Basic: <encoded credentials>'.
Parameters:
- username: The Jira email address.
- password: The Jira password.
"""
combo = username + ":" + password
encoded = base64.b64en... | a48524b5e29f57e8ef6d05176dac5bfcad3c223c | 689,841 |
def merge_intervals(intervals):
""" Merge intervals in the form of a list. """
if intervals is None:
return None
intervals.sort(key=lambda i: i[0])
out = [intervals.pop(0)]
for i in intervals:
if out[-1][-1] >= i[0]:
out[-1][-1] = max(out[-1][-1], i[-1])
else:
... | 609c5d463995c64dd331d58136ef41a8d4bf55cc | 689,842 |
import yaml
def represent_unicode(dumper, _unicode): # pylint: disable=unused-argument
"""Function for unicode representation."""
return yaml.ScalarNode(u'tag:yaml.org,2002:str', _unicode) | 26b17fcfcf25304c1ecb82fda4184c1add190b0c | 689,843 |
def _check_file(f, columns):
"""Return shell commands for testing file 'f'."""
# We write information to stdout. It will show up in logs, so that the user
# knows what happened if the test fails.
return """
echo Testing that {file} has at most {columns} columns...
grep -E '^.{{{columns}}}' {path} && err=1
echo
... | 2daad603a054f13e08504a8af17f62fecee49cd9 | 689,844 |
def _get_bzr_status(output):
"""This function exists to enable mocking the `bzr status` output in tests.
"""
return output[0].decode("utf-8").splitlines() | 7a0f7846434c6d13d541283bdf65188ffec5615d | 689,845 |
def find_if(cond, seq):
"""
Return the first x in seq such that cond(x) holds, if there is one.
Otherwise return None.
"""
for x in seq:
if cond(x): return x
return None | 0978689c29bc06fb1783083cec7f5e7f87eeb07e | 689,846 |
def turtle_b_step(this_turtle):
"""Moves forward and spawns two turtles at different angles."""
this_turtle.move(50 * this_turtle.health)
child = this_turtle.copy()
child.rotate_relative(-20)
child.health = child.health * child.decay
child.kind = "C"
this_turtle.rotate_relative(45)
this... | f75136304b4e7d7f4e1c79bf038b1022d644eab4 | 689,847 |
def cytoscapeFormat(predType, val1, val2):
"""
.. versionadded:: 0.3.0
Converts inputs into the triples format used by Cytoscape.
:param predType: The action which relates one or more values.
:type predType: str.
:param val1: The first value.
:type val1: str.
:param val2: The second va... | 2b50a2976294fd2136e1b0de74b5343a66e108eb | 689,848 |
from typing import OrderedDict
def _list_to_dict(items):
""" Convert a list of dicts to a dict with the keys & values aggregated
>>> _list_to_dict([
... OrderedDict([('x', 1), ('y', 10)]),
... OrderedDict([('x', 2), ('y', 20)]),
... OrderedDict([('x', 3), ('y', 30)]),
... ])
O... | 64dc70a62e423e664f800a1e31ef2f5252e95265 | 689,849 |
import math
import time
def timed_method (func) :
"""
This class decorator will decorate all public class methods with a timing
function. That will time the call invocation, and store the respective data
in a private class dict '__timing'. Additionally, it will add the class
method '_timing_las... | 1ae6e1c52d505afcbfb85ccbde153ad64310a350 | 689,850 |
import numpy
def linear_interpolation(u, x, xi):
"""Perform a linear interpolation along the first axis.
Parameters
----------
u : numpy.ndarray
Array to interpolate.
x : numpy.ndarray
Gridline locations.
xi : float
Target location.
Returns
-------
ui : nu... | bb5c159349fff6e600a45a6e9efeafff0d3c2102 | 689,851 |
import fnmatch
import os
def assemble_files_to_install(complete_file_list):
"""
This looks for all of the files which should show up in an installation of ansible
"""
ignore_patterns = tuple()
pkg_data_files = []
for path in complete_file_list:
if path.startswith("lib/ansible"):
... | 6c7387acd25a18fcf4b477d03b7a4642a20efec3 | 689,852 |
def ternary_search(f, left, right, absolute_precision):
"""
Find maximum of unimodal function f() within [left, right]
"""
while True:
if abs(right - left) < absolute_precision:
return (left + right)/2
left_third = left + (right - left)/3
right_third = right - (right... | 1b23f54750c0255a0fbd1c710d989e8e9d4dc50e | 689,853 |
from unittest.mock import patch
def patch_bond_action():
"""Patch Bond API action command."""
return patch("homeassistant.components.bond.Bond.action") | 276599c1a9dc72da40fea1b338f401dc91cbac58 | 689,854 |
def check(product, data):
"""Check if product does not exist in the data"""
if type(data) == dict:
data = data.values()
for d in data:
if product == d:
return False
return True | 6162e986f4e55c6dfaf4b9cf9c1b737aaf311dc7 | 689,856 |
import sys
def check_if_need_to_re_search() -> bool:
"""Gets user input to research if query didn't return wanted results"""
search: bool = False
print('Do you want to search again?(y/N)')
while True:
user_input = sys.stdin.readline()
if user_input == '\n':
break
if... | b1baf4a8f7bf165985fc7e645ee098703c30ea74 | 689,857 |
import numpy as np
def simple_threshold(arr1d, threshold):
"""
simple threshold function, which checks, if the minimum value of the time series falls below a certain threshold
----------
arr1d: numpy.array
1D array representing the time series for one pixel
threshold: int
should be... | 77fb289abfb1c1066d872474933162718d35ec49 | 689,861 |
import zipfile
import os
def _get_all_test_class_names_in_jar(jar):
"""Returns a list of test class names in the jar file. """
test_class_names = []
zip_file = zipfile.ZipFile(jar, 'r')
name_list = zip_file.namelist()
for name in name_list:
basename = os.path.basename(name)
# Exclu... | 1379b745981e579f5542f1f9a166ee6189435f20 | 689,862 |
def _parse_cal_product(cal_product):
"""Split `cal_product` into `cal_stream` and `product_type` parts."""
fields = cal_product.rsplit('.', 1)
if len(fields) != 2:
raise ValueError(f'Calibration product {cal_product} is not in the format '
'<cal_stream>.<product_type>')
... | 69734101e3715939d2032892aebfd762e75849d6 | 689,863 |
def tminmaxstatio_from_sim(sim, VERBOSE=True):
"""Return tmin, tmax and tstatio."""
tmin = sim.output.spatial_means.time_first_saved()
tmax = sim.output.spatial_means.time_last_saved()
Deltat = tmax - tmin
if Deltat > 29:
tstatio = tmin+18
elif Deltat > 10:
tstatio = tmin+5
e... | 79c8ab33a8495dbeead0f034312144c06b2e611b | 689,864 |
def largest(a, b):
"""
This function takes two numbers
to determine which one is larger
"""
if a > b:
larger = a
else:
larger = b
return larger | 9f48283451944a3f6d748b76368019ca1bcbf3db | 689,865 |
def extend_range(min_max, extend_ratio=.2):
"""Symmetrically extend the range given by the `min_max` pair.
The new range will be 1 + `extend_ratio` larger than the original range.
"""
mme = (min_max[1] - min_max[0]) * extend_ratio / 2
return (min_max[0] - mme, min_max[1] + mme) | 16c8ba3b54b885ab546caaf02fc989512d861b12 | 689,866 |
def readme():
"""Include README.rst content in PyPi build information"""
with open('README.md') as file:
return file.read() | 8bc473d52bbe3b292b39f8ca8791c9660ca076d1 | 689,867 |
def build_risk_dataframe(financial_annual_overview):
"""Build risk dataframe
Notes:
Copies financial_annual_overview
Args:
financial_annual_overview (dataframe): An annual overview of financial data
Returns:
risk_dataframe (dataframe): An instance of a a... | bcee282dd9efa0b86c4b278725ac58f975a598eb | 689,868 |
import textwrap
def _build_direct_config(config, interface_map):
"""
Generate the "direct" section of the BIRD daemon configuration.
:type config: akanda.router.models.Configuration
:param config:
:type interface_map: dict
:param interface_map:
:rtype:
"""
tmpl = "protocol direct ... | 53f1e8159408233d3b54d319be0d9aa27d484daf | 689,869 |
from typing import Tuple
import struct
def bytes_to_shortint(byteStream: bytes) -> Tuple[int]:
"""Converts 2 bytes to a short integer"""
# Ignore this in typing, as the 'H' will guarantee ints are returned
return struct.unpack('H', byteStream) | ec5319b8d19c7f3e653349eac31daaf4a30c1c0f | 689,870 |
def extract_question_features(qword, qtext, qtype, qpos, qner, qheadwords, qcomps, qdels):
"""
Utility function used to extract question related feature
"""
features = []
headwords = ''
headwords_pos = ''
headwords_ner = ''
comparisons = ''
comparisons_pos = ''
comp... | 6ec68bf463d0e75ab49dc61a3b642165e6aa3152 | 689,871 |
def make_transparent(img, bg=(255, 255, 255, 255)):
"""Given a PIL image, makes the specified background color transparent."""
img = img.convert("RGBA")
clear = bg[0:3]+(0,)
pixdata = img.load()
width, height = img.size
for y in range(height):
for x in range(width):
if pixda... | 78ee0c3a7e17b131820d710982e17f32b68a0cca | 689,872 |
from pathlib import Path
def phospho_files():
"""Get the phospho file and fasta"""
pin = Path("data", "phospho_rep1.pin")
fasta = Path("data", "human_sp_td.fasta")
return pin, fasta | 9c2cac448c7262a0afbc023df224fe02e36c7f0b | 689,873 |
import struct
def _structure_size(structure):
"""计算structure的字节大小"""
return struct.calcsize('<' + ''.join([i[1] for i in structure])) | c4d8b5bcc9d1f444aafd13d8cebe21b135da0c75 | 689,874 |
import pkg_resources
def get_words(list_name: str):
"""
Reads the given word list from file into a list of capitalized words
"""
resource_package = __name__
resource_path = "/".join(("data", f"{list_name}.txt"))
word_list = pkg_resources.resource_string(resource_package, resource_path)
wor... | 30a31c53aa3fd081be6ee01017f6c6f850765c67 | 689,875 |
def tree_prec_to_adj(prec, root=0):
"""Transforms a tree given as predecessor table into adjacency list form
:param prec: predecessor table representing a tree, prec[u] == v iff u is descendant of v,
except for the root where prec[root] == root
:param root: root vertex of the tree
:ret... | 62065680744c0dcb9086b8898770685533397979 | 689,876 |
import re
def count_occurrences(text, feature):
"""
inputs: feature that is searched for inside text
Count occurrences of a feature in text string by using the regex
findall function to isolate each word, which we compare to the feature
"""
found_occurrences = re.findall(r'\w+', text)
... | 02b52c8c6172c4a62e05bb536b12489f16c445e0 | 689,877 |
from typing import List
def two_list(lst1: List[str], lst2: List[str]) -> str:
"""
Function that return a common element of two lists
:param lst1: first list of strings
:param lst2: second list of strings
"""
for elem in lst1:
if elem in lst2:
return elem
raise Excepti... | ddadc920a71721a0219d1c93533a59f3db31888f | 689,878 |
import os
import re
def getCwdFiles():
"""Get a recursive file listing of the current directory"""
aAllFiles = []
for sRoot, aDirs, aFiles in os.walk('.'):
for sFile in aFiles:
sPath = re.sub(r'^\./', '', sRoot + '/' + sFile)
aAllFiles.append(sPath)
return aAllFiles | b6f834aee26edc84467809ca1958296daf3a58ba | 689,879 |
import os
def distro_exists(distro):
""" Checks if the distro folder exists or not """
return distro in os.listdir('_package') | a278e8001642e6b12c6f53a1148a21ecf23913d8 | 689,880 |
def minutesToHours(minutes):
"""
(number) -> float
convert input minutes to hours;
return hours
>>> minutesToHours(60)
1.0
>>> minutesToHours(90)
1.5
>>>minutesToHours(0)
0.0
"""
hours = minutes / 60
hours = round(hours, 2)
return hours | d2dbcba8f3e78fafb84bd9d23f456c005467bca5 | 689,881 |
import re
import json
import os
def _parseRawData(author=None, constrain=None, src='./chinese-poetry/json/simplified', category="poet.tang"):
"""
code from https://github.com/justdark/pytorch-poetry-gen/blob/master/dataHandler.py
处理json文件,返回诗歌内容
@param: author: 作者名字
@param: constrain: 长度限制
@pa... | cba5977c63ac3f8007ec27f5923b9a45432b0a88 | 689,882 |
def decompress(string, wbits=0, bufsize=0):
"""Decompresses the data in *string*, returning a string containing the
uncompressed data. The *wbits* parameter controls the size of the window
buffer, and is discussed further below.
If *bufsize* is given, it is used as the initial size of the outp... | 8827ba899fb8452afa86ca36fc77461e7364dc17 | 689,883 |
import os
def filename2sortkey(name):
"""Convert a file or dir name to a tuple that can be used to
logically sort them. Sorting first by extension.
"""
# Normalize name
name = os.path.basename(name).lower()
name, e = os.path.splitext(name)
# Split the name in logical parts
try:
... | 48971cde9d9cf059f58d4bcc5db8c267d3dfcc5e | 689,885 |
def _Backward2b_T_Ph(P, h):
"""Backward equation for region 2b, T=f(P,h)
>>> "%.5f" % _Backward2b_T_Ph(5,4000)
'1015.31583'
>>> "%.6f" % _Backward2b_T_Ph(25,3500)
'875.279054'
"""
I=[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 6, 7,... | 1f6fb6aebd0cd0be04a391d1063363e067ea127c | 689,886 |
def url_to_be(url):
"""An expectation for checking the current url.
url is the expected url, which must be an exact match
returns True if the url matches, false otherwise."""
def _predicate(driver):
return url == driver.current_url
return _predicate | df97a46fc3b2b9702969db8b03fd34892b89df62 | 689,887 |
def _get_ordered_keys(rows, column_index):
"""
Get ordered keys from rows, given the key column index.
"""
return [r[column_index] for r in rows] | 109b1d14ece528b7c08394003945c8a80ff9d335 | 689,888 |
from typing import Dict
from typing import Any
def _replace_value(dictionary: Dict[str, Any], value_to_find, value_replace) -> Dict[str, Any]:
"""
Replaces values by searching in the tree.
:param dictionary: dict object
:param value_to_find: The value to find
:param value_replace: The value to rep... | 865fd8bbd50168a619d95767107b437f46bf9660 | 689,889 |
from dataclasses import asdict
def dataclasses_to_dicts(data):
""" Converts a list of dataclass instances to a list of dictionaries
Parameters
----------
data : List[Type[dataclass]]
Returns
--------
list_dict : List[dict]
Examples
--------
>>> @dataclass
>>> class Point... | 2d05a09c8620d3f7f047cc58975a7f41498c32c6 | 689,890 |
def _older_than(number, unit):
"""
Returns a query item matching messages older than a time period.
Args:
number (int): The number of units of time of the period.
unit (str): The unit of time: "day", "month", or "year".
Returns:
The query string.
"""
return f"older_th... | f5389e67f5aa973b57187c395a11eaed79b95bef | 689,891 |
import fnmatch
from pathlib import Path
def generate_lists_of_filepaths_and_filenames(input_file_list: list):
"""For a list of added and modified files, generate the following:
- A list of unique filepaths to cluster folders containing added/modified files
- A set of all added/modified files matching the ... | e712c05b0bc28225db88b66a841ce31c6a1c898f | 689,892 |
def handle(string: str) -> str:
"""
>>> handle('https://github.com/user/repo')
'user/repo'
>>> handle('user/repo')
'user/repo'
>>> handle('')
''
"""
splt = string.split("/")
return "/".join(splt[-2:] if len(splt) >= 2 else splt) | bbd00c63b0a037eda08ce1f4fe3ed97ef8978f35 | 689,894 |
from pathlib import Path
import os
def data_directory() -> Path:
"""
Fixture that returns the test data directory.
Returns
-------
Path
Test data directory
"""
root = Path(__file__).absolute().parent.parent.parent
default = root / 'ci' / 'ibis-testing-data'
datadir = os.e... | db515321dba10f0df96faaf514ffc5bf156691ee | 689,895 |
def proxy_result_as_dict(obj):
"""
Convert SQLAlchemy proxy result object to list of dictionary.
"""
return [{key: value for key, value in row.items()} for row in obj] | 6e7244fa47553d234fba4568d41110d095330704 | 689,897 |
def write_env(env_dict, env_file):
"""
Write config vars to file
:param env_dict: dict of config vars
:param env_file: output file
:return: was the write successful?
"""
content = ["{}={}".format(k, v) for k, v in env_dict.items()]
written = True
try:
with open(env_file, 'w... | 0f752e3966fa5fa9120d74b91643c2b9f9da5704 | 689,899 |
import glob
import os
def search_file(in_dir, keyword):
""" Search a specific file with the keyword.
Arguments:
in_dir: str
Hyspex data input directory.
keyword: str
Searching keyword.
Returns:
file: str
Found filename.
"""
file = glob.g... | 508b133ea400e2c38859fa008f94ba470577b207 | 689,900 |
def get_image(camera):
"""Captures a single image from the camera and returns it in PIL format."""
data = camera.read()
_, im = data
return im | 39897fb0ed6a119eca947dba3528618095b06af1 | 689,901 |
def matrix_to_list(matrix):
"""
From [[21, 12], [3, 4], [9,0]] function
return [21, 12, 3, 4, 9, 0]
"""
lst = []
for i in matrix:
lst.extend(i)
return lst | 55abcb47b2d74c8fc420b82156b18f82d7cd8d4e | 689,902 |
def new(algo, data=b""):
"""Creates a new hashlib object.
:param str algo: Name of the desired algorithm.
:param str data: First parameter.
"""
try:
hash_object = globals()[algo]
return hash_object(data)
except KeyError:
raise ValueError(algo) | 71021915f8589ca97b6b70bfa328e04bc32b31ae | 689,905 |
import os
import json
def load_json(filename, my_dir=None):
"""
load the JSON file
:param filename: filename (with extension)
:param my_dir: path to the file
:return: json_dict
"""
full_path = filename
if my_dir is not None:
full_path = os.path.join(my_dir, filename)
if os.... | 760907339fb1010c4a40390582402958bf8effc7 | 689,906 |
def _hashSymOpList(symops):
"""Return hash value for a sequence of `SymOp` objects.
The symops are sorted so the results is independent of symops order.
Parameters
----------
symops : sequence
The sequence of `SymOp` objects to be hashed
Returns
-------
int
The hash va... | a8c8bc12de9cc1f135bcec38e94b45a79eebfe33 | 689,907 |
from typing import Callable
def inverse_increasing(
func: Callable[[float], float],
target: float,
lower: float,
upper: float,
atol: float = 1e-10,
) -> float:
"""Returns func inverse of target between lower and upper
inverse is accurate to an absolute tolerance of atol, and
must be m... | 13441ae4b8af905996c84b74e14221a19b6d18d1 | 689,908 |
def add_PDF_field_names(equiplist, type="NonEnc"):
"""Takes a list of items and their type and returns a dictionary with the items
as values and the type followed by a sequential number (type0, type1, etc.) as
keys. These are generally used to fill fields in a blank PDF, with keys
corresponding to field... | 4ec5d29e5f8b6c2f66b83628fcb412c2b92dd1f9 | 689,909 |
def sclose(HDR):
"""input: HDR_TYPE HDR
output: [-1, 0]
Closes the according file.
Returns 0 if successfull, -1 otherwise."""
if HDR.FILE.OPEN != 0:
HDR.FILE.FID.close()
HDR.FILE.FID = 0
HDR.FILE.OPEN = 0
return 0
return -1
# End of SCLOSE
###########
# SREAD #
########### | f1ae32a8a37ceda75b06bbf5482225e9f96e7be1 | 689,910 |
import itertools
def _object_pairs(graph1, graph2, weights):
"""Returns a generator with the product of the comparable
objects for the graph similarity process. It determines
objects in common between graphs and objects with weights.
"""
types_in_common = set(graph1.keys()).intersection(graph2.key... | 14c86090f017efa8349140a28258f80349b733b6 | 689,911 |
def read_ncbi_names_dmp(names_dmp):
"""
Load NCBI names file ("names.dmp")
names_dmp: NCBIs names.dmp file
"""
name_dict = {} # Initialise dictionary with TAX_ID:NAME
name_dict_reverse = {} # Initialise dictionary with NAME:TAX_ID
name_file = open(names_dmp, "r")
while 1:
... | 1404ee0795e8526188de88236aef0897e53079b9 | 689,912 |
def heat_exchange_to_condition(s_in, s_out, T=None, phase=None,
H_lim=None, heating=None):
"""
Set the outlet stream condition and return duty required to achieve
said condition.
"""
H_lim_given = H_lim is not None
H_in = s_in.H
if H_lim_given:
if hea... | cf6f538db81ea206ce27c26654d8036a066cf9de | 689,913 |
import yaml
def read_yaml_file(file_path):
"""Parses yaml.
:param file_path: path to yaml file as a string
:returns: deserialized file
"""
with open(file_path, 'r') as stream:
data = yaml.safe_load(stream) or {}
return data | 922525ed3ef450d2e0bb0e99b1294e81a9ef7e6e | 689,914 |
import hashlib
def hash(symbol, hash_type='sha1'):
""" create a hash code from symbol """
code = hashlib.new(hash_type)
code.update(str(symbol).encode('utf-8'))
return code.hexdigest() | fe2f5c6c6b451e0208741be201d640c7d8d371c1 | 689,915 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.