content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def div_or_none(a,b):
"""Divide a by b. Return result or None on divide by zero."""
if b == 0:
return None
return a/b | 88bf49ac570968e0108356ecad5b6ce9d2f52f4f | 653,358 |
from typing import Optional
def validate_state_of_charge_max(state_of_charge_max: Optional[float]) -> Optional[float]:
"""
Validates the state of charge max of an object.
State of charge max is always optional.
:param state_of_charge_max: The state of charge max of the object.
:return: The valida... | b7d2e4867e18b00595c159ef26233e57482ffa5d | 653,359 |
def read_file(path=None) -> str:
"""
Function for reading the single file
:param path: path to the file
:return: data: data from the file
"""
if not path:
raise NameError('Required path to the file')
with open(path, 'r') as f:
data = f.read()
return data | 097268399ed556de8c61c9cb57aae042d279faa0 | 653,361 |
def timesheetentry_json(timesheetentry) -> dict:
""" Helper function to convert a TimeSheetEntry object into a json dict with nice date and time formatting """
data = {}
data['id'] = timesheetentry.id
data['project'] = timesheetentry.project.id
data['rse'] = timesheetentry.rse.id
data['date'] = ... | 67ff19f5cb1b2ab5f7e373a3f4f81d088a06b14a | 653,364 |
from typing import Mapping
from typing import Sequence
def apply_to_type(input_, input_type, func):
"""Apply a function on a object of `input_type` or mapping, or sequence of objects of `input_type`.
"""
if isinstance(input_, input_type):
return func(input_)
if isinstance(input_, (str, bytes))... | 1dda2aa64546a9a417061b76828dbc1c42deed8e | 653,367 |
def range_overlap(a, b):
"""
>>> range_overlap(("1", 30, 45), ("1", 45, 55))
True
>>> range_overlap(("1", 30, 45), ("1", 57, 68))
False
>>> range_overlap(("1", 30, 45), ("2", 42, 55))
False
"""
a_chr, a_min, a_max = a
b_chr, b_min, b_max = b
# must be on the same chromosome
... | d44da19754faf683d93eea645edba03b1e1c83b9 | 653,369 |
def scale(value, input_low, input_high, output_low, output_high):
"""Scale a value from one range to another"""
scaled_input = ((float(value) - input_low) / (input_high - input_low))
return ((scaled_input) * (output_high - output_low)) + output_low | cc220e52a4060e2f80adc99fdacf6137e2b0a1ee | 653,370 |
def get_group_usage(group, date, db):
"""
Query the database for group usage on a specific date.
:param group: str
:param date: str
:param db: object
:return usage: int
"""
terms = (group, date + '%',)
db.execute('SELECT * FROM `group_stats` WHERE `group` = ? AND `datetime` LIKE ?',... | 0d1b8c8ecba39aa4e733707c74fe9deade458291 | 653,371 |
def iter_algorithm(d, n, p, corpus, pr):
"""
PR(p) = ( (1-d) / n ) + ( d * sum( PR(i) / NumLinks(i) ) )
i
d = dampening number; n = # of possible pages; p = page; i = incoming pages
"""
page_sum = 0
# This for loop will calcula... | b38cdbe6510a81791a7aa2abd0a9943c66610caf | 653,372 |
def has_attribute(ob, attribute):
"""
:func:`hasattr` swallows exceptions. :func:`has_attribute` tests a Python object for the
presence of an attribute.
:param ob:
object to inspect
:param attribute:
``str`` for the name of the attribute.
"""
return getattr(ob, attribute, No... | 5d91f5acf57842d04f2cfd57afe5f7bfe1cc08d5 | 653,374 |
def remove_stop_words(content, stopwords):
"""Removes the stopwords in an article.
:param tokens: The tokens of an article.
:type tokens: []str
:param stopwords: the list of stopwords
:type stopwords: []str
:return: The tokens of an article that are not stopwords.
:rtype: []str
"""
... | 97e7ef8e92853f629d9c6e2e211d423564d865dd | 653,375 |
def defaultparamsfunc(curlag, sensdict, simparams):
"""
Just a pass through function.
"""
return(curlag, sensdict, simparams) | a184c73c317d9b3c589781ca2d3a1a89c9147800 | 653,377 |
def extract_fields(data, exclude=()):
"""Return a tuple of all fields in the DataFrames within *data*."""
features = set()
for station in data:
features = features | set(station['Data'].columns.tolist())
return sorted(list(features - set(exclude))) | d7e32cc9873b70d8ef43c4fc7ff69fb8a7bf8b61 | 653,381 |
def spot_is_free(spot, candles, light):
"""
A spot is NOT free if the horizontal and vertical distance between
that and the light is less than the light strength
"""
for candle in candles:
x_dist = abs(candle[0] - spot[0])
y_dist = abs(candle[1] - spot[1])
if x_dist < light a... | 97d5ca3e3a40d914f4291ff6f7e047aa8bfb7d87 | 653,386 |
def _format_strings(the_string='', prefix='', suffix=''):
"""Small convenience function, allows easier logic in .format() calls"""
if the_string:
return '{0}{1}{2}'.format(prefix, the_string, suffix)
else:
return '' | ef3ac0f8d0972d8d562a763f6255b197951acc26 | 653,387 |
import torch
def extract_logits(out, task_ids, n_classes, device):
"""
Extract logits corresponding to task_ids from out.
Args:
out: Predictions
task_ids: Task ids
n_classes: Number of classes per task
"""
indices = (
(torch.arange(n_classes * out.size(0)) % n_clas... | 551ee2eb2e6319a02c0e905b38c310379cf88a29 | 653,389 |
def task_flake8(output_file):
"""Run flake8 over the code base and benchmarks."""
opts = ''
if output_file:
opts += f'--output-file={output_file}'
return {
'actions': [f"flake8 {opts} scipy benchmarks/benchmarks"],
'doc': 'Lint scipy and benchmarks directory',
} | 7e6dd2a9b49216e3ade2852e86c783f388d97f62 | 653,390 |
def GetMachMsgOOLDescriptorSummary(desc):
""" Returns description for mach_msg_ool_descriptor_t * object
"""
format_string = "{: <#020x} {: <#020x} {: <#010x}"
out_string = format_string.format(desc, desc.address, desc.size)
return out_string | 2c853befaedf0f7f53b0ce258824a61a9d73031c | 653,393 |
def has_duplicates(t):
"""Returns True if any element appears more than once in a sequence.
t: list returns: bool
"""
s = t[:] # make a copy of t to avoid modifying the parameter
s.sort()
for i in range(len(s)-1):
if s[i] == s[i+1]: # check for adjacent eleme... | 2200d4c5c5b22937f60e560937794d7419082f40 | 653,394 |
def _tx_resource_for_name(name):
""" Return the Transifex resource name """
return "taiga-back.{}".format(name) | 9f54f40776c5cbbbb08169114623ef521414a625 | 653,395 |
import re
def remove_svg_dimensions(svg_data):
"""Remove explicit height and width attributes from an svg, if present."""
desired_index = 0
svg_lines = svg_data.split("\n")
for index, line in enumerate(svg_lines):
if "<svg" in line:
desired_index = index
break
line = svg_lines[desired_index]
line = re.... | 7a9c011d8907632825101baa84b7093242d42b1b | 653,397 |
def hex_to_rgb(hex_str):
"""Convert html hex codes to RGB tuple."""
hex_str = hex_str.strip("#")
return tuple(int(hex_str[i : i + 2], 16) for i in (0, 2, 4)) | 45d13aa5290b2a17205dc63899f6d7a9701434bb | 653,398 |
def make_collections_query(value, tag=None):
"""Creates sql and values to query database for collections."""
# init buffers
sqls = []
values = []
# init value
value_like = "%%%s%%" % value.lower()
# search by DBID
if tag == '[ID]':
sqls.append("(id = ?)""")
... | dc3a8697e5cafc9a757d9a35cc28aa0a96f3d7b2 | 653,402 |
def count_from_0(index, collection):
"""Numbering function: consecutive integers starting at 0."""
return index | bc01bc8e46e913c325e4972b3bd71cd4d2543237 | 653,403 |
from pathlib import Path
import configparser
def lit_config(filenames: list[Path]) -> dict:
"""Lecture du fichier de configuration.
Args:
filenames: liste de répertoires où trouver le fichier de configuration.
Returns: dict créé à partir de la section 'paths',
contenant des répertoires e... | 2a76888d262610aca22659b960b13824df5fc16f | 653,405 |
def get_json_carts(response):
"""Get rendered cart's templates from JsonResponse."""
return response.json()['header'], response.json()['table'] | 5d80db9330390dbef74f27cc82d2a84de211b0e5 | 653,407 |
def list_average(score_list):
"""
Utility function to get the average of a list.
Args:
score_list: List containing real numbers that must be averaged
Returns:
Float representing the average of the values in the provided list
"""
if len(score_list) == 0:
return -100
... | cc50f53277850e9837e36b54f3f065e7278f6b25 | 653,410 |
def get_azs(region=''):
"""The intrinsic function Fn::GetAZs returns an array that lists all \
Availability Zones for the specified region.
Because customers have access to different Availability Zones, the
intrinsic function Fn::GetAZs enables template authors to write
templates that adapt to the ... | 44472ea5336a1d389b97b7c24db7c8c70302cd54 | 653,412 |
from typing import Iterator
def ascii_table(dictset: Iterator[dict], limit: int = 5):
"""
Render the dictset as a ASCII table.
NOTE:
This exhausts generators so is only recommended to be used on lists.
Parameters:
dictset: iterable of dictionaries
The dictset to render
... | 7dcfb922f01b5642265ad59a03f5b3e580199e43 | 653,414 |
def item_version(item):
"""
Split the item and version based on sep ':'
"""
sep = ':'
count = item.count(sep)
if count == 0:
return item, None
elif count == 1:
return item.split(sep)
else:
msg = "Found multiple instances of '%s'" % sep
raise ValueError(msg... | 77e595b32aee2ffb28971f5f1f1b0e1cafaf28e8 | 653,416 |
def bits_table_h() -> dict[int, int]:
"""The table of the maximum amount of information (bits) for the version H.
Returns:
dict[int, int]: Dictionary of the form {version: number of bits}
"""
table = {
1: 72, 2: 128, 3: 208, 4: 288, 5: 368, 6: 480, 7: 528, 8: 688, 9: 800,
10: 97... | 30e9f42605d650f1d541e73a815b9b60632442a1 | 653,418 |
import json
def safe_json_load(in_str):
"""
safely load json strings as dictionaries
:param in_str: string with encoded json
:return: dict
>>> safe_json_load('{"bob": 5}')
{'bob': 5}
>>> safe_json_load('{"bob": [1,2,3]}')
{'bob': [1, 2, 3]}
>>> safe_json_load('{"bob": [1,2,3}')
... | 860ec8758a752cafde1b017d24392f922fc36844 | 653,429 |
def pretty_dict(d, indent=0):
"""Pretty the output format of a dictionary.
Parameters
----------
d
dict, the input dictionary instance.
indent
int, indent level, non-negative.
Returns
-------
res
str, the output string
"""
res = ""
for k, v in d.item... | 868c102e70bd477960bf29dc8040eda50b13fffa | 653,436 |
def get_keyword(token):
"""If ``token`` is a keyword, return its lowercase name.
Otherwise return ``None``.
"""
if token.type == 'ident':
return token.lower_value | 2f518754456d98453cfb379a9bae08100b7e7648 | 653,439 |
def clean_full_uri(request):
"""Return the full URI without querystrings"""
return '%s://%s%s' % ('https' if request.is_secure() else 'http',
request.get_host(), request.path) | 6d9b067fd1ce40a4d27619e4b60941cf71afa93a | 653,440 |
def str_to_bool(string_in: str):
"""convert a string to boolean
Args:
string_in (string): Text from config file value
Raises:
ValueError: Cannot convert the string to a bool as it isn't True or False
Returns:
Boolean: True/False value
"""
if string_in.lower() == "true"... | 1074878b8da7a0d10fd128309ec6215746eb8bfb | 653,441 |
def find_twin(device_id, device_list):
"""
Locate the emulated twin of source device with identifier device_id.
Parameters
----------
device_id : str
Identifier of original device for which the twin is located.
device_list : list
List of device dictionaries in project fetched by... | 9bad722712069b86cd1912a7daadd81253f0f578 | 653,442 |
def countTokens(vendorRDD):
""" Count and return the number of tokens
Args:
vendorRDD (RDD of (recordId, tokenizedValue)): Pair tuple of record ID to tokenized output
Returns:
count: count of all tokens
"""
return vendorRDD.map(lambda x: len(x[1])).reduce(lambda a, b: a + b) | 6c8070c799495edbe12123420c4f6703ce13127f | 653,450 |
import ctypes
def create_string_buffer(value, size=None):
"""Create a ctypes string buffer.
Converts any string to a bytes object before calling
ctypes.create_string_buffer().
Args:
value (object): value to pass to ctypes.create_string_buffer()
size (int, optional): sze to pass to ctypes.cre... | edf2534a1fe7f8fc0f6fbf962e48c388268d8ca8 | 653,455 |
from typing import Any
from typing import MutableSequence
def aslist(thing: Any) -> MutableSequence[Any]:
"""Wrap any non-MutableSequence/list in a list."""
if isinstance(thing, MutableSequence):
return thing
return [thing] | 311a7e30567f6cf9632201315ab447b1aa085ff2 | 653,456 |
import multiprocessing
def _run_in_process(target, *args, **kwargs):
"""Runs target in process and returns its exitcode after 10s (None if still alive)."""
process = multiprocessing.Process(target=target, args=args, kwargs=kwargs)
process.daemon = True
try:
process.start()
# Do not nee... | 4ac57947c821a02b8e0ffe55f2f577a7847f248b | 653,458 |
def total_after(integer_number):
"""Returns the total number of grains on the chess board for given number of squares.
See README file for how it is calculated.
The calculation is essentially a Geometric series where a=1, r=2 and the sum of such a series is given by
a(1-r**n)
... | db5a7a15be3c637f4aa8bc2446387750755b85a7 | 653,462 |
from typing import Dict
import math
def logarithmic_utility(
utility_params_by_good_id: Dict[str, float],
quantities_by_good_id: Dict[str, int],
quantity_shift: int = 1,
) -> float:
"""
Compute agent's utility given her utility function params and a good bundle.
:param utility_params_by_good_... | 477e7f098e0721894a2ab0e3647e341a34677141 | 653,463 |
def receive_all(sock, n):
"""
Helper function to fully receive an arbitrary amount of data from a socket.
:param sock: Socket connection
:param n: Number of bytes to receive
:return: Received data
"""
data = b''
while len(data) < n:
packet = sock.recv(n - len(data))
if n... | a510a4878238500c101e9660dba47188bc7d0ba6 | 653,467 |
def get_dict_modes(dict):
"""Finds the keys of the modes of a dictionary
@param dict: A dictionary of the form {"key":#}
"""
highest_count = dict[max(dict)]
modes = []
for key in dict:
if dict[key] == highest_count:
modes.append(key)
return modes | 2952395f9989aa77e008cb351fd99c5de5544788 | 653,470 |
import requests
def fetch_ontologies(enhanced_keywords):
"""
Fetch the connected ontology for each enhanced keyword.
Parameters
----------
enhanced_keywords: list
List of enhanced keywords in string format
Returns
-------
A list of dictionaries. Each one containing the ontolo... | f38580641683b9128febdc8ea180c0f51ceb50b1 | 653,471 |
def entity_key(entity):
"""
Generate a key for the given entity that is unique within the
project.
"""
key = entity.key or entity.string
return ":".join([entity.resource.path, key]) | 7872d209c6eef1054e49d2978d83c988a354b61a | 653,472 |
import re
def split_entries(text, split_expr):
"""Splits text into entries according to split expression"""
return re.split(split_expr, text)[1:] | 224c682f5b9e90fd86fd3d0ba07e33835a92b472 | 653,473 |
def custom_attention_masks(input_ids):
"""Creates attention mask for the given inputs"""
attention_masks = []
# For each sentence...
for sent in input_ids:
# Create the attention mask.
# - If a token ID is 0, then it's padding, set the mask to 0.
# - If a token ID is > 0, t... | ab38c8a0cbd23da4937bdd44785b1d5a3ab08748 | 653,474 |
import binascii
def unhexlify(blob):
"""
Takes a hexlified script and turns it back into a string of Python code.
"""
lines = blob.split('\n')[1:]
output = []
for line in lines:
# Discard the address, length etc. and reverse the hexlification
output.append(binascii.unhexlify(li... | 074edf1359f404e9de14da1cccf3952812ca7cb7 | 653,476 |
def make_geotransform(x_len, y_len, origin):
"""
Build an array of affine transformation coefficients.
Parameters:
x_len (int or float): The length of a pixel along the x axis.
Generally, this will be a positive value.
y_len (int of float): The length of a pixel along the y axi... | 2eb38a36e59130713457ce03dd51281edec0d1c5 | 653,478 |
def splitblocks(lst, limit):
"""Split list lst in blocks of max. limit entries. Return list of blocks."""
res = []
start = 0
while start < len(lst):
res.append(lst[start:start + limit])
start += limit
return res | 3189355235cfada1cd0548e3362b501fccfef0eb | 653,487 |
def get_P_Elc_game_play(P_Elc_game_play_measured):
"""稼働時の消費電力を計算する
Parameters
----------
P_Elc_game_play_measured : float
稼働時の平均消費電力(実測値), W
Returns
----------
P_Elc_game_play : float
稼働時消費電力, W
"""
P_Elc_game_play = P_Elc_game_play_measured
... | e97c14ea73f8071ff15781f404baf734d94accac | 653,488 |
def _is_subrange(rng1, rng2):
"""Return True iff rng1 is wholly inside rng2"""
# Nonpolymers should have an empty range
if rng1 == (None, None) or rng2 == (None, None):
return rng1 == rng2
else:
return rng1[0] >= rng2[0] and rng1[1] <= rng2[1] | 25641fe477d2bf1e2e2e14020a01ccc9e96926b0 | 653,490 |
def role_ids_for_account(dynamo_table, account_number):
"""
Get a list of all role IDs in a given account by querying the Dynamo secondary index 'account'
Args:
account_number (string)
Returns:
list: role ids in given account
"""
role_ids = set()
results = dynamo_table.que... | 73ee88813d7ae6ee5a48f89c7e37fe2cdb8e1093 | 653,497 |
def reconnect(device, **kwargs):
"""Reconnect an unreal device
Parameters
----------
device (UnrealDevice): an unreal device instance
kwargs (dict): keyword arguments
Returns
-------
bool: connection status
"""
result = device.reconnect(**kwargs)
return result | a8623d15053d2525460eb8d4ad90522a7bc5826b | 653,502 |
import torch
def negative_sampling(batch, num_nodes, head_corrupt_prob, device='cpu'):
""" Samples negative examples in a batch of triples. Randomly corrupts either heads or tails."""
bs, ns, _ = batch.size()
# new entities to insert
corruptions = torch.randint(size=(bs * ns,),low=0, high=num_nodes, ... | 568fa8e4859fc356f3a5b7f1fffe8ac07799d224 | 653,503 |
def lie_bracket(element_1, element_2):
"""
Unfolds a Lie bracket. It is assumed that the second element is homogeneous (the bracket grows to the left).
Returns a string encoding the result of unfolding: each addend is represented as a sequence of indeces (which
are separated by '.'), the addends are sep... | 53ab152f92ae058cdacea944e12dd8717b5fa2d0 | 653,508 |
def UsersInvolvedInTemplate(template):
"""Return a set of all user IDs referenced in the template."""
result = set(
template.admin_ids +
[fv.user_id for fv in template.field_values if fv.user_id])
if template.owner_id:
result.add(template.owner_id)
for av in template.approval_values:
result.upda... | 0e40a08fe9d74bccc4a51ca549738e652a2e9097 | 653,510 |
def ibmqx(index):
"""
Creates one of the IBM Quantum Experience coupling maps based on the index provided
Args:
index (integer between 2 and 5): specify which of the QX chips should be returned
Returns:
dict
{
"qubits" : the number of qubits in the coupling map
... | 9a02a4aeb80ba9493ecc2fcee53e16386e95b9d8 | 653,513 |
import collections
def find_duplicate_basenames(paths):
"""Return a dict mapping duplicate basenames to their full paths."""
pathmap = collections.defaultdict(list)
for p in paths:
pathmap[p.name].append(p)
# Remove any entries that only have one item in their associated list
for name in l... | 3770b0c7fcef894552fbbf0e4e2ec9c89b38f96d | 653,514 |
def get_calendar(intent_message, default_calendar):
"""
Get the calendar from an intent.
This returns the default calendar if the intent doesn't have a calendar.
Parameter intent_message: the intent message
Parameter default_calendar: the default calendar
"""
# The user has specified a ca... | 583f939e2cddd83cc4fd5ba3b007c22c8834acfa | 653,515 |
def is_binary(data):
""" Return True if the input series (column of dataframe) is binary """
return len(data.squeeze().unique()) == 2 | 7f895fe03461bc2a1a66f4332f82c13eabe8b4b8 | 653,517 |
def job_id(conf):
# type: (dict) -> str
"""Get job id of a job specification
:param dict conf: job configuration object
:rtype: str
:return: job id
"""
return conf['id'] | 269e802f9b8c21647bde2e597ee6fc21e7c081c8 | 653,518 |
import random
def _generate_placeholder_string(x, default_placeholder="{}"):
"""Generate and return a string that does not appear in `x`."""
placeholder = default_placeholder
rng = random.Random(5)
while placeholder in x:
placeholder = placeholder + str(rng.randint(0, 9))
return placeholder | 143ba87fb28b56af998e54d97a486574f62a3f41 | 653,519 |
import configparser
def configure(config_file='../docs/default_config.ini'):
"""
Reads a configuration (INI format) file that specifies the three working
directories for binary image files, as well as the preferred database
connection.
A configuration file should contain two sections:
1. A ... | 09f58edd29748497e8ee81bc91ae09a9acd7972f | 653,526 |
def approximates(ref_point, point, max_deviation):
"""Helper function to check if two points are the same within the specified deviation."""
x = ref_point[0] - max_deviation <= point[0] <= ref_point[0] + max_deviation
y = ref_point[1] - max_deviation <= point[1] <= ref_point[1] + max_deviation
... | 8e53bf9a3fef2c04323d7000c43bcd09be0c2cce | 653,531 |
def get_distances(clusters):
"""Extract distances as intermediate values between 2 clusters"""
distances = []
for idx, _ in enumerate(clusters[:-1]):
clst_0 = float(clusters[idx])
clst_1 = float(clusters[idx + 1])
distances.append((clst_1 - clst_0) / 2 + clst_0)
return tuple(dist... | 4da9653ae5ed98e9060780f4865ab91ed80f8bee | 653,533 |
def normalize_encoding(encoding):
""" Normalize an encoding name.
Normalization works as follows: all non-alphanumeric
characters except the dot used for Python package names are
collapsed and replaced with a single underscore, e.g. ' -;#'
becomes '_'. Leading and trailing undersc... | 5f3f6d46c2893660b6c390c61bf83af7fe1d4e5a | 653,537 |
def alignment_patterns_table() -> dict[int, list[int]]:
"""A dictionary that contains the positions of the alignment patterns.
Returns:
dict[int, list[int]]: Returns a list of positions.
"""
table = {
2: [18],
3: [22],
4: [26],
5: [30],
6: [34],
7... | 86bf868cfd00b66b1175abe34f7824567e38808a | 653,538 |
def title_case(text: str) -> str:
"""Convert the text to title case.
Args:
text: The text to convert to title case.
Returns:
str: The text converted to title case.
"""
return text.title() | d4e87ecd4fbc003e6370ae2d96cf9a3aef114243 | 653,541 |
def cut_to_specific_word(dataframe, specific_word, part_in_bid):
"""
Takes in a dataframe and a column, and then creates a new dataframe containing only
the rows from the original dataframe that had the search word in that column
:params: a dataframe, a specific_word to look for, and a column name relat... | c8ee42088cb85c053b1a5a8b3877436a50df689d | 653,543 |
import json
def parse_line(line):
"""Parse a JSON string into a Python object."""
try:
line = line.strip()
return json.loads(line)
except json.decoder.JSONDecodeError:
return None | cd2e1e230da656c3adfd8ecede0c1fdb14e00423 | 653,545 |
from pathlib import Path
import logging
def _check_file_existence(file_path: str) -> bool:
"""
Validates the existence of a file
"""
path = Path(file_path)
if not path.exists():
logging.error('Provided file cannot be found.')
return False
return True | d7e147132d824fe62e4bb4f498df79d3c5bd02bb | 653,546 |
def piecewise_linear_continuous(x, x_b, m_1, b_1, m_2):
"""
Eq. 10. 2-Part Piecewise Linear Continuous Function
Used to fit D18O_cc-w fractionation versus drip rate.
Describes two lines that intersect at x_b.
Parameters
----------
x : numpy array
independent variable
x_b : ... | f8dae31e083a75bb8aee3d080604fd7061e78ea9 | 653,548 |
import torch
def prj_vtx_pth(vtx, pose, cam_K):
"""
project 3D vertices to 2-dimensional image plane using pytorch
:param vtx: (N, 3), vertices, tensor
:param pose: (3, 4), tensor
:param cam_K: (3, 3), intrinsic camera parameter, tensor
:return: pts_2D: (N, 2), pixel coordinates, tensor; z: (N... | 5364d328696e19232a06d8c41c0acfbc6f270514 | 653,551 |
def repeat_to_length(string_to_expand, length):
"""Repeats string_to_expand to fill up a string of the provided length.
Args:
string_to_expand: string to repeat
length: length of string to return
Returns: generated string of provided length
"""
return (string_to_expand * (int(leng... | 84b7b20569022ea630020441071cbffa2b016b61 | 653,556 |
def select_rows_by_regex(df, column_name,
regex_str):
"""Returns pandas dataframe rows matching regex in a specific column.
Returns a dataframe with a subset of rows where the value in the column
contains the regex.
Args:
df: A pandas dataframe.
column_name: Name of the column... | c48e6e732864f33b959d3a6c002873b5b9b581eb | 653,557 |
def with_lock(method):
"""
Execute method with lock. Instance should have lock object in lock attribute.
"""
def wrapper(self, *args):
with self.lock:
return method(self, *args)
return wrapper | 1114afa821c9245588328a6757b3ca5e16805a34 | 653,560 |
def sql_file(tmp_path):
""" Construct a file containing a SQL statement """
directory = tmp_path / "sql"
directory.mkdir()
file = directory / "sql.txt"
file.write_text("SELECT\n 1 as foo;")
return file.absolute() | e5adb73bc24519ab7547aa2ca897bcca70e4aaca | 653,561 |
from typing import Optional
import hashlib
def transport_channel_id(transport, is_server: bool, channel_id_type: Optional[str] = None) -> bytes:
"""
Application-layer user authentication protocols are vulnerable to generic
credential forwarding attacks, where an authentication credential sent by
a cli... | 5d87cdea3843651b67a75d5735cd6a58401c38cd | 653,567 |
from pathlib import Path
from typing import List
def _split_pbn(file_path: Path) -> List[List[str]]:
"""
Read in the entire PBN file. Split on lines consisting of '*\n' into a list of strings per board
:param file_path: path to PBN file
:return:
"""
with open(file_path, "r") as pbn_file:
... | 628ec0be07f96e3640dc08527bc6a3de600c0472 | 653,569 |
def is_finite_ordinal(n):
"""
Return True if n is a finite ordinal (non-negative int).
"""
return isinstance(n, int) and n >= 0 | c4a191bf15b550c1fe368d1921d63d821439ff60 | 653,574 |
def _EnableTypoCorrection( flags ):
"""Adds the -fspell-checking flag if the -fno-spell-checking flag is not
present"""
# "Typo correction" (aka spell checking) in clang allows it to produce
# hints (in the form of fix-its) in the case of certain diagnostics. A common
# example is "no type named 'strng' in n... | f632e22c0aa02577fb1936e4c38b04fe1b234a9c | 653,576 |
import six
def _get_column_pairs(columns, require_qualifier=False):
"""Turns a list of column or column families into parsed pairs.
Turns a column family (``fam`` or ``fam:``) into a pair such
as ``['fam', None]`` and turns a column (``fam:col``) into
``['fam', 'col']``.
:type columns: list
... | 44336b76fc82d560a42b2306188a87f93f80ae82 | 653,577 |
def fix2range(vals, minval, maxval):
"""
A helper function that sets the value of the array or number `vals` to
fall within the range `minval` <= `vals` <= `maxval`.
Values of `vals` that are greater than `maxval` are set to
`maxval` (and similar for `minval`).
Parameters
----------
va... | d5df9ec213fdc48f6a30342b71571608a6bd1103 | 653,582 |
def maker_file_path_fromidx(digits=1, levels=1):
"""
Creates a method that returns a file path for the given number of leading digits and levels.
Args:
digits: minimum number of digits to use for the path, any number with less digits will have leading zeros
added.
levels: how to ... | 6d279c9a8b5eb0d3e4919a738114f7b49841743e | 653,590 |
import requests
def query_to_json(query):
"""Query with requests and return response as json
Parameters
----------
query : string
query
Returns
-------
json
response
"""
return requests.get(query).json() | fc3226e33b53b4de7d9e6b1f5dc2cec8afdd27ce | 653,591 |
async def files_for_PR(gh, pull_request):
"""Get files for a pull request."""
# For some unknown reason there isn't any files URL in a pull request
# payload.
files_url = f'{pull_request["url"]}/files'
data = []
async for filedata in gh.getiter(files_url): # pragma: no branch
data.appen... | fb87aaf206538020555c7d3e7872bfceb400b354 | 653,592 |
import math
def create_geographic_chunks(longitude=None, latitude=None, geographic_chunk_size=0.5):
"""Chunk a parameter set defined by latitude, longitude, and a list of acquisitions.
Process the lat/lon/time parameters defined for loading Data Cube Data - these should be
produced by dc.list_acquisition... | dbc23c6e332edbe57c96c786f63d29c3454987bd | 653,593 |
def check(checkRow, checkColumn):
"""checks if this row and column is valid, used when looking at possible piece movement"""
if 0 <= checkRow <= 7 and 0 <= checkColumn <= 7:
return True
return False | 7d87344a245e8f9053d99ff38d78505b3be6caf8 | 653,595 |
def doc_template(object_name: str, body: str)->str:
"""Returns an html page
:param object_name: name of the object
:param body: body of the page
:return: the page
"""
doc = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>""" + object_name + """</title>
<m... | faf7a74f58dd1d2957b29d125b9d24d950c2429a | 653,600 |
import requests
from bs4 import BeautifulSoup
def fetch_swimmer_urls(url):
"""Fetch all of the swimmers and urls from a team url"""
# Download/parse the pages
page = requests.get(url)
soup = BeautifulSoup(page.content, features="html.parser")
# The last table in the page contains all the swimmer... | 73c2dcaf7db5d68dc3774683b08210b1f05add0b | 653,601 |
def _copy_with_ignore(dct, keep, ignore=()):
"""
Copy the entries in the given dict whose keys are in keep.
Parameters
----------
dct : dict
The dictionary to be copied.
keep : set-like
Set of keys for entries we want to keep.
ignore : set or tuple
Don't issue a warn... | b08df5db5506f9b687469686fd71400830b2820b | 653,602 |
def coordinates(width, height):
""" Returns coordinates [x1, y1, x2, y2] for a centered box of width, height
"""
with open('/sys/class/graphics/fb0/virtual_size', 'r') as res:
screenx, screeny = map(int, res.read().strip('\n').split(','))
posx = (screenx/2) - (width/2)
posy = (screeny/2) -... | 8e0b34a300f2a81f303d7592baeb18d4143145be | 653,606 |
def evaluate_ser(entity, outputs):
"""
Get all correct and incorrect queries. Correct means all entities are identified correctly
with exact span
:param entity: list of (start_index, end_index, label) tuples for EACH query
:param outputs: PARSED mallard/duckling responses
:return: Two lists of ... | 142e4b4a85d92625e86cc1ecc664fa265eac8871 | 653,608 |
def target_gene_indices(gene_names,
target_genes):
"""
:param gene_names: list of gene names.
:param target_genes: either int (the top n), 'all', or a collection (subset of gene_names).
:return: the (column) indices of the target genes in the expression_matrix.
"""
if is... | fe53bff4168380d1c3be8b9c48c6a235b7e5abce | 653,609 |
def extract_modified_bs_sequence(sax_sequence):
"""
This functions extracts the modified Behaviour Subsequence (BS) sequence list, which is the original sax word
sequence where every consecutive pairs of sax words are equal are fused into the same sax word.
:param sax_sequence: list of original sax wor... | 3a26278a478789032d35f994902440db3f879c9d | 653,610 |
def build_ols_query(ontology_uri: str) -> str:
"""Build a url to query OLS for a given ontology uri."""
return "https://www.ebi.ac.uk/ols/api/terms?iri={}".format(ontology_uri) | 160611dba7a3a543deec482c16d89da466f0d6cc | 653,611 |
import re
def transform_col_in_line(line, col_transformations):
"""Given a line in a table definition, transform any column names
for which a transformation is defined in `col_transformations`.
"""
col_patterns = [
"^\s*`([a-zA-Z0-9_]+)`.*,$", # fields
"^\s*PRIMARY KEY \(`([a-zA-Z0-9... | 833f48181561868d1b88309f99b52250ef8443ba | 653,616 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.