seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def Choose(Decision,TrueChoice,FalseChoice):
"""
Ternary IIF operator, returns TrueChoice or FalseChoice based on
Decision.
This function is handy for use inside Curly Brace Expressions (CBE's).
Decision must evaluate to true or false (0 or 1, empty or full, etc).
If TRUE then TrueChoice wi... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def date_from_path(path: str) -> List[str]:
"""
Takes a path like bla/number1/number2 and returns [number1, number2]
"""
parts = [p for p in path.split('/') if p.isnumeric()]
return parts | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
from typing import Any
def targets_to(targets: List[Dict[str, Any]], device):
"""Moves the target dicts to the given device."""
excluded_keys = [
"questionId",
"tokens_positive",
"tokens",
"dataset_name",
"sentence_id",
... | bigcode/self-oss-instruct-sc2-concepts |
def regroupRDDs(rdd, numGroup=10):
""" regroup an rdd using a new key added that is 0-numGtoup-1
:param rdd: input rdd as a (k,v) pairs
:param numGroup: number of groups to concatenate to
:return: a new rdd in the form of (groupNum, list of (k, v) in that group) pairs
"""
rdd = rdd.map(lambda k... | bigcode/self-oss-instruct-sc2-concepts |
def db_to_linear_gain(db_value):
"""
Parameters
----------
db_value : float
Decibel value
Examples
--------
>>> db_to_linear_gain(db_value=-3)
0.5011872336272722
>>> db_to_linear_gain(db_value=10)
10.0
"""
return 10 ** (db_value / 10) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def calculate_diff_occurrence(joltages: List[int]) -> int:
"""Calculate diff occurrences for differences of 1 and 3.
Args:
joltages (List[int]): the joltages of the adapters on hand
Returns:
int: the product of numbers of diff of 1 and diff of 3
"""
lowes... | bigcode/self-oss-instruct-sc2-concepts |
def _reverse_second_list_dimension(layers):
"""Reverses each list within a list of lists, but not the outer list."""
return [layer[::-1] for layer in layers] | bigcode/self-oss-instruct-sc2-concepts |
def std_array(comment, valueType, ndim, **kwargs):
"""Description for standard array column with variable shape (used for smaller arrays)."""
return dict(comment=comment, valueType=valueType, ndim=ndim, dataManagerType='StandardStMan',
dataManagerGroup='StandardStMan', _c_order=True, option=0, m... | bigcode/self-oss-instruct-sc2-concepts |
def split_GL_string(GL_string):
"""splits GL-string into alleles;
if it becomes too complicated, reduce to POS
"""
if "|" in GL_string: # pretyping contains phasing
return [GL_string] # put everything into first field
else:
alleles = GL_string.split("+")
if len(alleles) > 4: ... | bigcode/self-oss-instruct-sc2-concepts |
def get_source_files(source_ID, sofia_dir_path, name_base):
"""Return the full path of the files for a given source generated by
SoFiA. The source ID is equivalent to the ID in the catalog generated
by SoFiA.
This code is minimalistic, and works on a 'standard' output of SoFiA
see the code for the ... | bigcode/self-oss-instruct-sc2-concepts |
def rglen(ar):
"""shortcut for the iterator ``xrange(len(ar))``"""
return range(len(ar)) | bigcode/self-oss-instruct-sc2-concepts |
from operator import mod
def is_arithmetic_persian_leap_year(p_year):
"""Return True if p_year is a leap year on the Persian calendar."""
y = (p_year - 474) if (0 < p_year) else (p_year - 473)
year = mod(y, 2820) + 474
return mod((year + 38) * 31, 128) < 31 | bigcode/self-oss-instruct-sc2-concepts |
import requests
import calendar
import time
def coindeskticker(currency='USD'):
""" get current bitcoin exchange rate from Coindesk """
data = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json').json()
dataprice = data['bpi'][currency]['rate']
datatime = calendar.timegm(time.strptime(dat... | bigcode/self-oss-instruct-sc2-concepts |
def combinations_nb(n):
"""Return number of (i, j) combinations with 0 <= i < j < n"""
return (n * (n-1)) // 2 | bigcode/self-oss-instruct-sc2-concepts |
def read128(f):
"""Read the next few bytes from file f as LEB128/7bit encoding and return an integer."""
result,i = 0,0
while 1:
byte=ord(f.read(1))
result|=(byte&127)<<i
if byte>>7==0: return result
i+=7 | bigcode/self-oss-instruct-sc2-concepts |
def decode_seat_string(seat):
"""
Test data
BFFFBBFRRR: row 70, column 7, seat ID 567.
FFFBBBFRRR: row 14, column 7, seat ID 119.
BBFFBBFRLL: row 102, column 4, seat ID 820.
Seat string is 10 bits binary
B = 1
F = 0
R = 1
L = 0
"""
bin_seat_number = seat.replace('B', '... | bigcode/self-oss-instruct-sc2-concepts |
def time2levels(tstamp):
"""Given a :class:`datetime.datetime` object,
return a list of directory levels (as strings).
For example, given "2013-09-08 13:01:44",
return ['2013', '09', '08', '13', '01']
"""
return [tstamp.strftime(xx) for xx in ('%Y', '%m', '%d', '%H', '%M')] | bigcode/self-oss-instruct-sc2-concepts |
def generate_fiscal_period(context):
""" Generate fiscal period based on the date provided """
reporting_end_date = context.current_parameters['reporting_end_date']
period = 0
if reporting_end_date:
period = (reporting_end_date.month + 3) % 12
period = 12 if period == 0 else period
r... | bigcode/self-oss-instruct-sc2-concepts |
def create_ngrams(corpus_tokens, n):
"""Funktion, die aus den gegebenen Token saemtliche Ngramme der
Laenge n extrahiert und in einer Liste speichert.
Input:
1. corpus_tokens (list): Text als Liste von Tokens
2. n (int): Laenge der Ngramme
Return:
1. ngrams(list): Liste von Ngrammen"... | bigcode/self-oss-instruct-sc2-concepts |
def string_reverse(input_string):
"""Reverses a string.
Parameters
----------
input_string : str
Holds the string to be reversed
Returns
----------
reversed_string : str
The reversed string
"""
reversed_string = input_string[::-1]
re... | bigcode/self-oss-instruct-sc2-concepts |
def extract_bounds(bounds):
"""
Extract coordinate tuples from bound objects.
"""
res = []
for bound in bounds:
coords = []
for vertex in bound.vertices:
coords.append((vertex.x, vertex.y))
res.append(coords)
return res | bigcode/self-oss-instruct-sc2-concepts |
def _GenerateDeviceKVMId(dev_type, dev):
"""Helper function to generate a unique device name used by KVM
QEMU monitor commands use names to identify devices. Since the UUID
is too long for a device ID (36 chars vs. 30), we choose to use
only the part until the third '-' with a disk/nic prefix.
For example if... | bigcode/self-oss-instruct-sc2-concepts |
def f_pitch(p, pitch_ref=69, freq_ref=440.0):
"""Computes the center frequency/ies of a MIDI pitch
Notebook: C3/C3S1_SpecLogFreq-Chromagram.ipynb
Args:
p (float): MIDI pitch value(s)
pitch_ref (float): Reference pitch (default: 69)
freq_ref (float): Frequency of reference pitch (de... | bigcode/self-oss-instruct-sc2-concepts |
def tailcuts_clean(geom, image, picture_thresh=7, boundary_thresh=5,
keep_isolated_pixels=False):
"""Clean an image by selection pixels that pass a two-threshold
tail-cuts procedure. The picture and boundary thresholds are
defined with respect to the pedestal dispersion. All pixels that
... | bigcode/self-oss-instruct-sc2-concepts |
import click
def validate_relay(context, param, value):
"""
Validates presence of relay by name.
"""
relays = context.obj.api.relays()
relay = next((r for r in relays
if r["name"] == value), None)
if relay is None:
error = "Relay \"%s\" does not exist" % value
... | bigcode/self-oss-instruct-sc2-concepts |
def summarize_consensus(consensus):
"""
Return 'high', 'medium' or 'low' as a rough indicator of consensus.
"""
cons = int(100 * consensus)
if cons >= 70:
return "high"
elif cons >= 30:
return "medium"
else:
return "low" | bigcode/self-oss-instruct-sc2-concepts |
def _build_tool_path(d):
"""Build the list of tool_path for the CROSSTOOL file."""
lines = []
for k in d:
lines.append(" tool_path {name: \"%s\" path: \"%s\" }" % (k, d[k]))
return "\n".join(lines) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def squash(x, dim):
""" Non-linear activation, that squashes all vectors to have norm < 1 """
norm_sq = torch.sum(x ** 2, dim, keepdim=True)
norm = torch.sqrt(norm_sq)
return (norm_sq / (1.0 + norm_sq)) * (x / norm) | bigcode/self-oss-instruct-sc2-concepts |
def get_constraint(obj, name):
"""
Get a constraint vith the given name for the given object.
If constraint is not specified for the object returns None.
"""
for c in obj.constraints:
if c.type.name == name:
return c | bigcode/self-oss-instruct-sc2-concepts |
def has_possible_duplicates(results):
"""Returns True if it detects that there are possible duplicate records
in the results i.e. identical full name."""
full_names = set()
for result in results:
if result.full_name in full_names:
return True
full_names.add(result.full_name)
... | bigcode/self-oss-instruct-sc2-concepts |
def padding_size(num: int) -> int:
"""Calculates base64 padding size as per RFC4648."""
# according to https://tools.ietf.org/html/rfc4648#section-4
# only three cases can exist
mapping = {
0: 0, # no padding
2: 2, # two padding characters
3: 1, # one padding character
}
... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
import calendar
def string_fmt_time_to_seconds(string_format_time):
""" utility function to convert a string format time to epoch seconds """
dt = datetime.strptime(string_format_time, "%Y-%m-%d %H:%M:%S")
epoch_seconds = calendar.timegm(dt.utctimetuple())
return epoch_se... | bigcode/self-oss-instruct-sc2-concepts |
def get_input_channels(shape):
"""
Helper for temporary issues with PyTorch shape inference.
Args:
shape (Tuple): Shape tuple.
Returns:
int: Num input channels.
"""
# Have batch rank from placeholder space reconstruction:
if len(shape) == 4:
# Batch rank and channel... | bigcode/self-oss-instruct-sc2-concepts |
def _push(node):
"""
Push load away from the current node if possible.
If a neighboring node which is "closer" to the target can accept more load
push it to the node. If no such node is found push fails meaning a relabel has
to be executed.
"""
success = False
for edge in node.outgoing_... | bigcode/self-oss-instruct-sc2-concepts |
def _intents_from_messages(messages):
"""Return all intents that occur in at least one of the messages."""
# set of distinct intents
distinct_intents = {m.data["intent"] for m in messages if "intent" in m.data}
return distinct_intents | bigcode/self-oss-instruct-sc2-concepts |
import copy
def multiply_variable(self, c, i, in_place = False):
"""
Replace the variables `x_i` by `c*x_i` in the quadratic form
(replacing the original form if the in_place flag is True).
Here `c` must be an element of the base_ring defining the
quadratic form.
INPUT:
`c` -- an el... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def has_tests(module: str):
"""Test if a module has tests.
Module format: homeassistant.components.hue
Test if exists: tests/components/hue
"""
path = Path(module.replace(".", "/").replace("homeassistant", "tests"))
if not path.exists():
return False
if n... | bigcode/self-oss-instruct-sc2-concepts |
def sales_velocity(units_sold_last_12m, number_of_days_in_stock, velocity_days=30):
"""Return the sales velocity of a product for a given number of days.
Args:
units_sold_last_12m (int): Total number of units sold in the past 12 months.
number_of_days_in_stock (int): Total number of days in the... | bigcode/self-oss-instruct-sc2-concepts |
import ast
def applyTypeConversions(settingObj, value):
"""
Coerce value to proper type given a valid setting object.
Useful in converting XML settings with no type info (all string) as well as
in GUI operations.
"""
if settingObj.underlyingType == list and not isinstance(value, list):
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def first_match(regex, string):
"""Given a regex and a string to search, this function simply returns the
first match, if there is one."""
match = re.search(regex, string)
return match.group(0) if match else None | bigcode/self-oss-instruct-sc2-concepts |
def type2str(cls):
"""Convert type to type name."""
return cls.__qualname__ | bigcode/self-oss-instruct-sc2-concepts |
def get_layer_idx_for_vit(name, num_layers):
"""
Assign a parameter with its layer id
Following BEiT: https://github.com/microsoft/unilm/blob/master/beit/optim_factory.py#L33
"""
if name in ["cls_token", "pos_embed"]:
return 0
elif name.startswith("patch_embed"):
return 0
eli... | bigcode/self-oss-instruct-sc2-concepts |
def AptGetServiceName(vm):
"""Returns the name of the mysql service."""
return 'mysql' | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def _add_minmers(minmers: dict) -> dict:
"""
Read through minmer results and create column for top hit.
Args:
minmers (dict): Mash and Sourmash results against RefSeq and GenBank
Returns:
dict: Top hit description for each set of databases
"""
r... | bigcode/self-oss-instruct-sc2-concepts |
def join_overlapping(s, e):
"""Join overlapping intervals.
Transforms a list of possible overlapping intervals into non-overlapping
intervals.
Parameters
----------
s : list
List with start of interval sorted in ascending order
e : list
List with end of interval.
Retur... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def neginf(dtype: torch.dtype) -> float:
"""
Return a representable finite number near -inf for a dtype.
"""
return -1e20 | bigcode/self-oss-instruct-sc2-concepts |
def page_number(request, page_total):
"""Gets the current page number of a media list.
'request' is expected to have one query parameter, 'page',
containing a page number (with the first page being page 1); if it
does not exist, it is taken to be 1. This page number may be
outside the bounds dicta... | bigcode/self-oss-instruct-sc2-concepts |
def non_empty(d):
"""
Check whether the `collection` is none or empty.
"""
return d is not None and len(d) > 0 | bigcode/self-oss-instruct-sc2-concepts |
def vecs_add(v1, v2):
"""Add two vectors 'v1' and 'v2'."""
return v1 + v2 | bigcode/self-oss-instruct-sc2-concepts |
def _add_extension_feed_item(client, customer_id, callout_text, language_code):
"""Creates a new extension feed item for the callout extension.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
callout_text: a str of text for a hotel callout feed ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _EscapePerfResult(s):
"""Escapes |s| for use in a perf result."""
return re.sub(r'[\:|=/#&,]', '_', s) | bigcode/self-oss-instruct-sc2-concepts |
def area_triangle(b, h):
"""
Returns the area of a triangle given its base
and its height
"""
area = b * h / 2
return area | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
import pathlib
def to_path(source: Any) -> pathlib.Path:
"""Converts 'source' to a pathlib.Path.
Args:
source (Any): source to convert to a pathlib.Path.
Raises:
TypeError: if 'source' is a type that is not registered.
Returns:
pathlib.Path: derive... | bigcode/self-oss-instruct-sc2-concepts |
def _ArgbToRgbaTuple(argb):
"""Convert from a single ARGB value to a tuple containing RGBA.
Args:
argb: Signed 32 bit integer containing an ARGB value.
Returns:
RGBA tuple.
"""
unsigned_argb = argb % 0x100000000
return ((unsigned_argb >> 16) & 0xFF,
(unsigned_argb >> 8) & 0xFF,
... | bigcode/self-oss-instruct-sc2-concepts |
def FindOrderNums(orders, wavelengths):
"""
Given a list of xypoint orders and
another list of wavelengths, this
finds the order numbers with the
requested wavelengths
"""
nums = []
for wave in wavelengths:
for i, order in enumerate(orders):
if order.x[0] < wa... | bigcode/self-oss-instruct-sc2-concepts |
def merge_clusters(articles):
"""Merges articles of every cluster into one article object."""
clusters = []
cluster_ids = set([article['cluster_id'] for article in articles])
for id in cluster_ids:
body = []
for article in articles:
if article['cluster_id'] == id:
... | bigcode/self-oss-instruct-sc2-concepts |
def provider2network(p):
""" Convert a MADIS network ID to one that I use, here in IEM land"""
if p in ['KYMN']:
return p
if len(p) == 5 or p in ['KYTC-RWIS', 'NEDOR']:
if p[:2] == 'IA':
return None
return '%s_RWIS' % (p[:2],)
print("Unsure how to convert %s into a ne... | bigcode/self-oss-instruct-sc2-concepts |
def figshare_stem(stem: str = '', production: bool = True) -> str:
"""
Construct Grouper figshare stems
:param stem: string corresponding to the sub-stem.
Options are: 'quota', 'portal'. Default: root stem
:param production: Bool to use production stem.
Otherwise a stage/test is u... | bigcode/self-oss-instruct-sc2-concepts |
def build_client_user_topic(user_id: str):
"""
Builds the topic name where user push notification are received
:param user_id:
:return:
"""
return f"/app/{user_id}/subscribe" | bigcode/self-oss-instruct-sc2-concepts |
def convert(hours: int, minutes: int) -> int:
"""Convert hours and minutes to total seconds."""
total_seconds = (minutes * 60) + (hours * 3600)
return total_seconds | bigcode/self-oss-instruct-sc2-concepts |
def findall_lod(lst, key, val):
"""get list of dicts of all matches of key-value pair in list of dicts"""
return [x for x in lst if x[key] == val] | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def hash_from_url(url: str):
"""Hash url to create a unique ID."""
return hashlib.sha256(url.encode("utf-8")).hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def back2dim(x, xdim=-1):
"""
Transpose ndarray so that the back dimension is moved to a given position.
Parameters
----------
x : ndarray
Input array.
xdim : int, optional
Dimension at which to put the back "x" input array dimension.
(default=-1)
Returns
------... | bigcode/self-oss-instruct-sc2-concepts |
def maximum_element_size_for_length(length):
"""
Returns the maximum element size representable in a given number of bytes.
:arg length: the limit on the length of the encoded representation in bytes
:type length: int
:returns: the maximum element size representable
:rtype: int
"""
return (2**(7*length)... | bigcode/self-oss-instruct-sc2-concepts |
def first(iterable):
"""Returns the first item of 'iterable'
"""
try:
return next(iter(iterable))
except StopIteration:
return None | bigcode/self-oss-instruct-sc2-concepts |
def _translate_slice(exp, length):
""" Given a slice object, return a 3-tuple
(start, count, step)
for use with the hyperslab selection routines
"""
start, stop, step = exp.indices(length)
# Now if step > 0, then start and stop are in [0, length];
# if step < 0, they are in ... | bigcode/self-oss-instruct-sc2-concepts |
def get_measurement_variable(gt_id, shift=None):
"""Returns measurement variable name for the given ground truth id
Args:
gt_id: ground truth data string accepted by get_ground_truth
shift: (optional) Number of days by which ground truth measurements
should be shifted forward
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def readDictionary(input):
"""
Read file to a dictionary data structure:
Input file is a lexicon consisting lines of the word and the most frequent associated tag
"""
dictionary = {}
lines = open(input, "r").readlines()
for line in lines:
wordtag = line.strip().split()
... | bigcode/self-oss-instruct-sc2-concepts |
import random
def randomize_list_of_words(input_words):
"""
Returns the same list of words in a random order.
Input:
-input_words list of strings
Output:
-output_words list of strings
"""
output_words = []
random_order = random.sample(range(len(input_words)), len(input_word... | bigcode/self-oss-instruct-sc2-concepts |
def only_hostname(s):
"""
Given an SSH target, returns only the hostname.
e.g. only_hostname('user@mydomain:port') == 'mydomain'
"""
return s.split('@')[-1].split(':')[0].strip() | bigcode/self-oss-instruct-sc2-concepts |
import collections
def log_string_to_dict_list(log_string):
"""
Take a single string representing the contents of a jewel::Log file,
and return a list of OrderedDicts representing the logging events in the
log file.
"""
record_separator = "{R}"
field_separator = "{F}"
raw_records = log... | bigcode/self-oss-instruct-sc2-concepts |
def limitValue(value, min, max):
"""Limits value to a min or max value
Arguments:
value {int, float} -- value
min {int, float} -- minValue
max {int, float} -- maxValue
Returns:
int, float -- limited value
"""
if value > max:
out = max
elif value < min:
... | bigcode/self-oss-instruct-sc2-concepts |
def int_depth(h_int: list, thickness: float):
"""
Computes depth to the interface for a three layer model.
:param h_int: depth to to first interface
:param thickness: thickness
:return:
d_interface: interface depths
"""
d_interface = h_int
d_interface.append(d_interface[0] + thi... | bigcode/self-oss-instruct-sc2-concepts |
def remove_subdomain(name: str) -> str:
"""Removes the subdomain from a given URL.
Example:
>>> remove_subdomain("www.example.com")
'.example.com'
Arguments:
name: the domain
Returns:
the string with the subdomain removed. The string starts with the dot.
"""
tr... | bigcode/self-oss-instruct-sc2-concepts |
def euclid(a:int, b:int, Verbose=False):
"""Return the Greatest Common Divisor (GCD) of number a and b."""
# The GCD of two relative integers is equal to the GCD of their absolute values.
a, b=abs(a), abs(b)
# The largest of the two numbers is replaced by the remainder of the Euclidean div... | bigcode/self-oss-instruct-sc2-concepts |
def get_crop(params, shape):
"""
Parses crop from params object.
Parameters
----------
params : object
object holding configuration parameters
shape : tuple
shape of image array, i.e. the array to be cropped
Returns
-------
crop : list
crop in each... | bigcode/self-oss-instruct-sc2-concepts |
def btc_to_satoshi(btc):
"""
Converts a value in BTC to satoshi
outputs => <int>
btc: <Decimal> or <Float>
"""
value = btc * 100000000
return int(value) | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
def ichain(obj, *items):
"""
Gets through a chain of items
handling exceptions with None value.
Useful for data restored from a JSON string:
>>> ichain(data, 'result', 'users', 0, 'address', 'street')
"""
def get_item(obj, item):
if obj is None:
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def transform_coords(Ms, coords, wrap_around=False):
"""
Ms - affine transform matrices, (B,2,3), assumes x-y coordinate system in math
coords - (B,dimx,dimy,2)
"""
B, dimx, dimy = coords.size()[0], coords.size()[1], coords.size()[2]
augmented_coords = torch.cat((coords, torch.one... | bigcode/self-oss-instruct-sc2-concepts |
def clamp(val, low, high):
"""Return val, within [low,high]"""
if val < low:
return low
elif val > high:
return high
return val | bigcode/self-oss-instruct-sc2-concepts |
def _bin_to_hex(bitstring):
"""Convert bitstring readouts (memory) to hexadecimal readouts."""
return hex(int(bitstring, 2)) | bigcode/self-oss-instruct-sc2-concepts |
def list_apim_nv(client, resource_group_name, service_name):
"""List all Named Values of an API Management instance. """
return client.named_value.list_by_service(resource_group_name, service_name) | bigcode/self-oss-instruct-sc2-concepts |
import time
def is_bst(st: time.struct_time) -> bool:
"""
Calculates whether the given day falls within British Summer Time.
.. note::
This function does not consider the time of day,
and therefore does not handle the fact that the time changes at 1 AM GMT.
:param st: The :class:`time.struct_time` represen... | bigcode/self-oss-instruct-sc2-concepts |
def convert_masking(sentences):
"""Converts hash masking to internal [MASK] tokens"""
converted_sentences = []
for sent in sentences:
sent = list(sent)
for i, c in enumerate(sent):
if c == "#":
sent[i] = "[MASK]"
converted_sentences.append("".join(sent))
... | bigcode/self-oss-instruct-sc2-concepts |
def calGasVisEq2(eqExpr, T):
"""
gas viscosity equation - Pa.s
args:
eqExpr: equation expression
T: temperature [K]
"""
# try/except
try:
return eval(eqExpr)
except Exception as e:
raise | bigcode/self-oss-instruct-sc2-concepts |
def get_security_group_rules(body_response_sec_group_list, sec_group_name):
"""
Retrieve security group rules list
:param body_response_sec_group_list: Parsed response (python dic). List of sec. groups
:param sec_group_name: Name of Sec. Group to look for
:return: Return the first sec. group with se... | bigcode/self-oss-instruct-sc2-concepts |
def calcRCutIsolate(rh):
""" For isolated star clusters, set rcut to 20 * half-mass radius
Return
----------
rcut: float
escaper distance criterion
"""
return 20*rh | bigcode/self-oss-instruct-sc2-concepts |
def _pre_commit_has_hallmark(pre_commit_file):
"""
Looks at a pre-commit file and determine if it was created by Jig.
:returns: True if Jig created it
"""
with open(pre_commit_file) as fh:
script = fh.read()
if u'from jig' in script or u'jig init' in script:
return True
... | bigcode/self-oss-instruct-sc2-concepts |
def extract(d, keys, exclude=False):
"""
Helper function to extract keys and values from dictionary
Parameters
----------
d : dict
Dictionary from which to extract keys
keys : list of keys
List of keys to exclude or include
exclude : boolean
If true, excludes the... | bigcode/self-oss-instruct-sc2-concepts |
def merge_ranges(ranges, max_gap):
"""
Merge ranges which are closer than max_gap
"""
merged_ranges = []
for range in ranges:
if merged_ranges:
curr_start, curr_end = range
# compare against last interval in merged_ranges
pre_start, pre_end = merged_ra... | bigcode/self-oss-instruct-sc2-concepts |
def freq(T):
"""
Convert array of periods in days to frequencies in Hz.
"""
return 1./T/86400. | bigcode/self-oss-instruct-sc2-concepts |
def _parse_fingerprint_awsconsole(line, host=None):
"""Parse SSH host fingerprint from AWS console output"""
fingerprint = None
if line.startswith('ec2:'):
host = host
fingerprint = line.split(': ', 2)[1]
return host, fingerprint | bigcode/self-oss-instruct-sc2-concepts |
import logging
import socket
def check_port_in_use(host, port):
"""Check if port is already in use.
Arguments
---------
host: str
The current host.
port: int
The host port to be checked.
Returns
-------
bool:
True if port is in use, false otherwise.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def make_sic_div_lookup(sic):
"""Creates lookup between SIC class and division."""
return (
sic.assign(
Division=lambda x: x.Class.str[0:2],
Class=lambda x: x.Class.str.replace(".", ""),
)
.set_index("Class")["Division"]
.to_dict()
) | bigcode/self-oss-instruct-sc2-concepts |
def get_main_domain_name(url_str) -> str:
"""get url domain texts
Args:
url_str (str): url string
Returns:
str: domain name of url
"""
domain_name = url_str.split("/")[2]
main_domain_name = domain_name.split(".")[-2]
return main_domain_name | bigcode/self-oss-instruct-sc2-concepts |
def force_console_input(
query: str,
allowable,
onfail: str = "Input not recognised, please try again.\n",
case_sensitive=False,
):
"""Get an input from the user matching some string in allowable.
Args:
query (str): The query to issue the user with.
allowable (str or container):... | bigcode/self-oss-instruct-sc2-concepts |
def did(tag_class, is_constructed, tag_id):
"""
Calculate decoder_id as <tag id > | tag_class | constructed
:param tag_class:
:param is_constructed:
:param tag_id:
:return:
"""
did = tag_class >> 5
if is_constructed:
did |= 1
return did | (tag_id << 3) | bigcode/self-oss-instruct-sc2-concepts |
def compute_wave_height(crest_height, trough_depth):
"""Computes wave height from given crest height and trough depth."""
assert crest_height > trough_depth
return crest_height - trough_depth | bigcode/self-oss-instruct-sc2-concepts |
import configparser
import logging
def read_config(filename):
"""Reads a config file.
Args:
filename (str): Filename of config file to be read.
Returns:
configparser.ConfigParser: Read config file.
"""
parser = configparser.ConfigParser()
parser.read(filename)
logging.inf... | bigcode/self-oss-instruct-sc2-concepts |
def UsersInvolvedInComponents(component_defs):
"""Return a set of user IDs referenced in the given components."""
result = set()
for cd in component_defs:
result.update(cd.admin_ids)
result.update(cd.cc_ids)
if cd.creator_id:
result.add(cd.creator_id)
if cd.modifier_id:
result.add(cd.m... | bigcode/self-oss-instruct-sc2-concepts |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.