seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def encode_data(data):
"""Encode sysex data as a list of bytes. A sysex end byte (0xf7)
is appended.
"""
return list(data) + [0xf7] | bigcode/self-oss-instruct-sc2-concepts |
def splitProjectInfo(value: str):
"""Split a comma-separated list of 3 values (hub,group,project)"""
tokens = value.split(",")
if len(tokens) != 3:
raise RuntimeError(f"Invalid project: {value}")
return tokens | bigcode/self-oss-instruct-sc2-concepts |
import torch
def num_flat_features(x: torch.Tensor) -> int:
"""
Computes the total number of items except the first dimension.
:param x: input tensor
:return: number of item from the second dimension onward
"""
size = x.size()[1:]
num_features = 1
for ff in size:
num_features ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_role_for_profile(role: str) -> str:
"""Returns a 'safe' profile name for a given role.
Args:
role: The role to generate a profile name for.
Returns:
Formatted profile name.
"""
account_id = "000000000000"
role_name = "Unknown-Role-Name"
account_re = r... | bigcode/self-oss-instruct-sc2-concepts |
def datetime_to_str(date_time):
"""
Convert datetime to string. This format is specific to the 42API responses.
Arguments:
date_time: (datetime) the datetime.
Returns:
(str) containing the string equivalent of the datetime object.
"""
return (date_time.strftime("%Y-%m-%dT%H:%M:%S.%fZ")) | bigcode/self-oss-instruct-sc2-concepts |
def verbose_name(obj):
"""Return the object's verbose name."""
try:
return obj._meta.verbose_name
except Exception:
return '' | bigcode/self-oss-instruct-sc2-concepts |
def unique(s, key=None):
"""
Return unique entries in s
:Returns:
A sequence of unique entries of s.
If `key` is given, return entries whose key(s) is unique.
Order is preserved, and first of duplicate entries is picked.
"""
if key is not None:
keys = (key(x) fo... | bigcode/self-oss-instruct-sc2-concepts |
async def index(request):
"""
This is the view handler for the "/" url.
:param request: the request object see http://aiohttp.readthedocs.io/en/stable/web_reference.html#request
:return: context for the template.
"""
# Note: we return a dict not a response because of the @template decorator
... | bigcode/self-oss-instruct-sc2-concepts |
import copy
def CountUnique(inputList):
"""
Count the number of unique entries in the supplied list
"""
lInputList = copy.copy(inputList)
lInputList.sort()
count = 0
if len(lInputList) > 0:
count += 1
for i in range(1, len(lInputList)):
if not lInputList[i] == lInputList[i - 1]:
co... | bigcode/self-oss-instruct-sc2-concepts |
def simulate(job):
"""Run the minimization, equilibration, and production simulations"""
command = (
"gmx_d grompp -f em.mdp -c system.gro -p system.top -o em && "
"gmx_d mdrun -v -deffnm em -ntmpi 1 -ntomp 1 && "
"gmx_d grompp -f eq.mdp -c em.gro -p system.top -o eq && "
"gmx_d... | bigcode/self-oss-instruct-sc2-concepts |
def categories_to_string(categories, queryset=False):
"""
Args:
categories: [{"title": "Business"}, ...] OR
[models.Category] (if queryset=True)
Returns:
['<category.title', ...]
"""
if queryset:
new_categories = [i.title for i in categories]
else:
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def _intermediate_helper(
start_unit: str,
end_unit: str,
quantity: Union[int, float],
imperial: dict,
metric: dict,
) -> Union[int, float]:
"""
Function turns any input quantity into an intermediate value based on dictionary constants. Function
then takes the... | bigcode/self-oss-instruct-sc2-concepts |
import six
def _bytes(*args):
"""
Returns a byte array (bytes in py3, str in py2) of chr(b) for
each b in args
"""
if six.PY2:
return "".join(chr(c) for c in args)
# else: Python 3
return bytes(args) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def hat(v: torch.Tensor):
"""Maps a vector to a 3x3 skew symmetric matrix."""
h = torch.zeros((*v.shape, 3), dtype=v.dtype, device=v.device)
h[..., 0, 1] = -v[..., 2]
h[..., 0, 2] = v[..., 1]
h[..., 1, 2] = -v[..., 0]
h = h - h.transpose(-1, -2)
return h | bigcode/self-oss-instruct-sc2-concepts |
import string
def create_character_list(args):
"""Create the list of allowed characters to generate passwords from"""
possible_chars = []
if args.uppercase_ascii:
possible_chars += string.ascii_uppercase
if args.lowercase_ascii:
possible_chars += string.ascii_lowercase
if args.n... | bigcode/self-oss-instruct-sc2-concepts |
import torch
from typing import Tuple
def _equalize_attributes(actual: torch.Tensor, expected: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Equalizes some attributes of two tensors for value comparison.
If :attr:`actual` and :attr:`expected`
- are not onn the same memory :attr:`~torch.Tensor.de... | bigcode/self-oss-instruct-sc2-concepts |
def rightDiagonalProduct(a, diag):
"""
Calculate the product of a matrix and a diagonal matrix, with broadcast.
Parameters
----------
a : 2D ndarray of float
diag : array of float
The diagonal elements of the diagonal matrix.
Returns
2D ndarray of float
Matrix (a @... | bigcode/self-oss-instruct-sc2-concepts |
def bcon(reg, blocks):
"""
Block list converter.
If blocks is a list of integers, convert to a list of blocks using reg.blocks.
Else, do nothing.
Return list of blocks.
"""
## go
if len(blocks)>0 and type(blocks[0])==int:
blocks = [ reg.blocks[blocks[i]] for i in range(len(blocks)) ]
## return
return blocks | bigcode/self-oss-instruct-sc2-concepts |
def _get_vertex_location_name(location):
"""Get the location name from a location that is expected to point to a vertex."""
mark_name, field_name = location.get_location_name()
if field_name is not None:
raise AssertionError(u"Location unexpectedly pointed to a field: {}".format(location))
return mark_name | bigcode/self-oss-instruct-sc2-concepts |
def _generate_manifest(ctx, srcs):
"""Create a `clang_format_manifest` output file
Args:
ctx (ctx): The rule's or aspect's context object
srcs (list): A list of File objects
Returns:
File: The manifest
"""
manifest = ctx.actions.declare_file(ctx.label.name + ".clang_format.... | bigcode/self-oss-instruct-sc2-concepts |
def to_int16(y1, y2):
"""
Convert two 8 bit bytes to a signed 16 bit integer.
Args:
y1 (int): 8-bit byte
y2 (int): 8-bit byte
Returns:
int: 16-bit integer
"""
x = (y1) | (y2 << 8)
if x >= 32768:
x = -(65536 - x)
return x | bigcode/self-oss-instruct-sc2-concepts |
def any_positive_or_none(*args):
"""Return None if any argument is negative and the list of its argument otherwise"""
for arg in args:
if arg < 0:
return None
return list(args) | bigcode/self-oss-instruct-sc2-concepts |
import glob
def get_bridges(vnic_dir='/sys/devices/virtual/net'):
"""Return a list of bridges on the system."""
b_regex = "%s/*/bridge" % vnic_dir
return [x.replace(vnic_dir, '').split('/')[1] for x in glob.glob(b_regex)] | bigcode/self-oss-instruct-sc2-concepts |
import torch
def input_2_tensor(input_seq, encoding_space):
"""convert regular sequence of values to one hot encoding tensor"""
input_tensor = torch.zeros((len(input_seq), len(encoding_space)), dtype=torch.float)
for e, element in enumerate(input_seq):
element_tensor = torch.zeros(len(encoding_sp... | bigcode/self-oss-instruct-sc2-concepts |
import difflib
def get_similar_words(word_with_typo, words):
"""Returns a list of similar words.
The parameters we chose are based on experimenting with
different values of the cutoff parameter for the difflib function
get_close_matches.
Suppose we have the following words:
['cos', 'cosh', '... | bigcode/self-oss-instruct-sc2-concepts |
def power_function(context, base, exponent):
"""
The math:power function returns the value of a base expression taken to
a specified power.
"""
base = base.evaluate_as_number(context)
exponent = exponent.evaluate_as_number(context)
return base**exponent | bigcode/self-oss-instruct-sc2-concepts |
import re
def multireplace(string, replacements):
"""
Replace multiple matches in a string at once.
:param string: The string to be processed
:param replacements: a dictionary of replacement values {value to find, value to replace}
:return: returns string with all matches replaced.
Credit to b... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def vae_loss(x, recon, mu, logvar, beta):
"""Standard VAE Loss.
Args:
x: input image.
recon: model output as reconstruction of input.
mu: mean of latent.
logvar: logvar of latent distribution.
beta : Hyper-param in loss function.
Returns:
floa... | bigcode/self-oss-instruct-sc2-concepts |
def write_float_11e(val: float) -> str:
"""writes a Nastran formatted 11.4 float"""
v2 = '%11.4E' % val
if v2 in (' 0.0000E+00', '-0.0000E+00'):
v2 = ' 0.0'
return v2 | bigcode/self-oss-instruct-sc2-concepts |
def EgVarshni(E0, VarshniA, VarshniB, tempDet):
"""
This function calculates the bandgap at detector temperature, using the
Varshni equation
Args:
| E0: band gap at room temperature [eV]
| VarshniA: Varshni parameter
| VarshniB: Varshni parameter
| tempDet: detector oper... | bigcode/self-oss-instruct-sc2-concepts |
def get_kw_pos_association(kernel):
"""
Returns a tuple of ``(kw_to_pos, pos_to_kw)`` for the arguments in
*kernel*.
"""
kw_to_pos = {}
pos_to_kw = {}
read_count = 0
write_count = -1
for arg in kernel.args:
if not arg.is_output_only:
kw_to_pos[arg.name] = read_c... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
def _add_one(s: Sequence[int]) -> Sequence[int]:
"""Adds one to each element in the sequence of integer."""
return [i + 1 for i in s] | bigcode/self-oss-instruct-sc2-concepts |
def buffer_shp_corners(gdf_list, bufferwidth = 0):
"""
Finds the lower left and upper right corners of a list of geopandas.GeoDataFrame objects. Optionally define a buffer (in degrees) around the list GeoDataFrames
:param gdf_list:
:param bufferwidth:
:return:
"""
lonmin = 181
lonmax = ... | bigcode/self-oss-instruct-sc2-concepts |
def write_halos(halos_dset, halos_dset_offset, halos, nhalos_to_write,
write_halo_props_cont):
"""
Writes halos into the relevant dataset(s) within a hdf5 file
Parameters
-----------
halos_dset: dictionary, required
Contains the halos dataset(s) within a hdf5 file where eit... | bigcode/self-oss-instruct-sc2-concepts |
def transformPointsToImaris(points, scale = (4.0625, 4.0625, 3), offset = (0,0,0)):
"""Transform pixel coordinates of cell centers to work in Imaris
Arguments:
points (array): point coordinate array
scale (tuple): spatial scale of the image data
offset (tuple): spatial offset of the... | bigcode/self-oss-instruct-sc2-concepts |
import base64
def file_to_base64(filepath):
"""
Returns the content of a file as a Base64 encoded string.
:param filepath: Path to the file.
:type filepath: str
:return: The file content, Base64 encoded.
:rtype: str
"""
with open(filepath, 'rb') as f:
encoded_str = base64.b64e... | bigcode/self-oss-instruct-sc2-concepts |
import shutil
def concatenate_job(job, input_ids):
"""This job just concatenates the input files together and returns them."""
out_path = job.fileStore.getLocalTempFile()
with open(out_path, 'w') as output:
for input_id in input_ids:
input_path = job.fileStore.readGlobalFile(input_id)
... | bigcode/self-oss-instruct-sc2-concepts |
def is_bmp(codepoint):
"""Determine if a codepoint (interger) is in the BMP"""
return codepoint <= 0xffff | bigcode/self-oss-instruct-sc2-concepts |
def str_concat(str1: str, str2: str) -> str:
"""Конкатенация двух строк
Args:
str1 (str): Строка 1
str2 (str): Строка 2
Returns:
str: Новая строка из двух строк
"""
return str1 + ' ' + str2 | bigcode/self-oss-instruct-sc2-concepts |
def _lines_to_list(path):
"""
Reads file from at the specified path and creates a list which contains
lines from the file, without a newline.
"""
with open(path, 'r') as f:
return f.read().splitlines() | bigcode/self-oss-instruct-sc2-concepts |
def convert(value):
"""Convert value in milliseconds to a string."""
milliseconds = value % 1000
value = value // 1000
seconds = value % 60
value = value // 60
minutes = value % 60
value = value // 60
hours = value % 24
value = value // 24
days = value
if days:
result... | bigcode/self-oss-instruct-sc2-concepts |
def get_node_overview(data, requested_nodes):
"""
Creates a dictionary with all node keys as keys, and as value another dictionary which has
all attribute names as keys and the corresponding values as values.
:param data: The data objects corresponding to the nodes
:param requested_nodes: The nodes ... | bigcode/self-oss-instruct-sc2-concepts |
def reset_clickData(n):
"""
Resets the click data when new ticker is inserted
:param n: new ticker inserted
:return: None
"""
if n is None:
pass
else:
return None | bigcode/self-oss-instruct-sc2-concepts |
from pydantic import types
from typing import List
from typing import Type
def get_int_like_types() -> List[Type]:
"""Returns many int-like types from stdlib and Pydantic."""
def _chk(x) -> bool:
try:
return issubclass(x, (int))
except Exception:
return False
can... | bigcode/self-oss-instruct-sc2-concepts |
def is_rule_exists_violation(rule, policies, exact_match=True):
"""Checks if the rule is the same as one of the policies.
Args:
rule (FirweallRule): A FirewallRule.
policies (list): A list of FirewallRule that must have the rule.
exact_match (bool): Whether to match the rule exactly.
Ret... | bigcode/self-oss-instruct-sc2-concepts |
def validate_higlass_file_sources(files_info, expected_genome_assembly):
"""
Args:
files_info(list) : A list of dicts. Each dict contains the
file's uuid and data.
expected_genome_assembly(str, optional, default=None): If provided,
each file should have this ge... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def get_channel_values(digitalOut, func) -> Tuple:
"""Get the result of applying 'func' to all DigitalOut channels."""
return tuple(func(channel_index) for channel_index in range(digitalOut.count())) | bigcode/self-oss-instruct-sc2-concepts |
def _filter_size_out(n_prev, filter_size, stride, padding):
"""Calculates the output size for a filter."""
return ((n_prev + 2 * padding - filter_size) // stride) + 1 | bigcode/self-oss-instruct-sc2-concepts |
def is_anyscale_connect(address: str) -> bool:
"""Returns whether or not the Ray Address points to an Anyscale cluster."""
is_anyscale_connect = address is not None and address.startswith(
"anyscale://")
return is_anyscale_connect | bigcode/self-oss-instruct-sc2-concepts |
def in_sector_bounding_box(polar_point, radius, start_theta, end_theta):
"""Check if a polar coordinate lies within the segment of a circle
:param polar_point: tuple representing the point to check (r,phi)
:param radius: radius of the segement
:param start_theta: start angle of the segement in rad
... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def normalize_string(value):
"""
5.1.1.4 - c.3:
String values shall be rendered using the first eight characters of
their md5 (Message-Digest Algorithm) checksum.
"""
md5 = hashlib.md5(value.encode('utf-8')).hexdigest()
return md5[:8] | bigcode/self-oss-instruct-sc2-concepts |
def get_rotation(row):
"""Generate a rotation matrix from elements in dictionary ``row``.
Examples
---------
>>> sdict = { \
'_pdbx_struct_oper_list.matrix[{}][{}]'.format(i // 3 + 1, i % 3 + 1): i \
for i in range(9) \
}
>>> get_rotation(sdict)
[[0.0, 1.0, 2.0], [3.0, 4.0, ... | bigcode/self-oss-instruct-sc2-concepts |
import re
import json
def fix_tokens_file(file_path):
"""
Replace each
# ::tok sentence
by json parsable version
# ::token json-parseable-sentence
so that
sentence == json.loads(json-parseable-sentence)
"""
token_line = re.compile('^# ::tok (.*)')
# read and modifiy toke... | bigcode/self-oss-instruct-sc2-concepts |
def w(el1, el2):
"""
Returns weight based on residue pair
"""
pair = el1 + el2
return int(pair == 'AU' or
pair == 'UA' or
pair == 'GC' or
pair == 'CG') | bigcode/self-oss-instruct-sc2-concepts |
def scan2colfil(x, y, x0, y0, scale, tipo=0):
"""
Transforma de x/y en proyeccion geoestacionaria a
En base a 5.2.8.2 de PUG3
Parameters
----------
x : float, float arr
coordenada vertical, en radianes
x : float
coordenada vertical del primer punto en radianes
x0 : float
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def create_columns(column_def: Tuple[str, str]) -> str:
"""
Prepare columns for table create as follows:
- types copied from target table
- no indexes or constraints (no serial, no unique, no primary key etc.)
"""
return (','.join(f'{k} {v}' for k, v in column_def)
... | bigcode/self-oss-instruct-sc2-concepts |
def _tile_size(shape, out_shape, ndim):
"""Returns tile_size such that shape*tile_size = out_shape"""
size = [1] * ndim
for idx, (i, j) in enumerate(zip(shape, out_shape)):
if i != j:
size[idx] = j
return tuple(size) | bigcode/self-oss-instruct-sc2-concepts |
def has_already_cover(cover_metadata={}):
"""Check if record has already valid cover in cover_metadata."""
return cover_metadata.get("ISBN") or cover_metadata.get("ISSN") | bigcode/self-oss-instruct-sc2-concepts |
def append_concat_predictions(y_batch, predictions):
"""
Args:
y_batch (torch.Tensor or list):
predictions (list): accumulation list where all the batched predictions are added
Returns:
list: predictions list with the new tensor appended
"""
if isinstance(y_batch, list):
... | bigcode/self-oss-instruct-sc2-concepts |
def remove_comments(s):
"""remove comments (prefaced by #) from a single line"""
r = s.split("#")
return r[0] | bigcode/self-oss-instruct-sc2-concepts |
def compact(objects):
"""
Filter out any falsey objects in a sequence.
"""
return tuple(filter(bool, objects or [])) | bigcode/self-oss-instruct-sc2-concepts |
def trim(text, max_length):
"""Trims text to be at most `max_length`, without splitting apart words."""
if len(text) <= max_length:
return text
text = text[:max_length + 1]
# Trim until the last two characters are the boundary between an
# alphanumeric character, and a non-alphanumeric cha... | bigcode/self-oss-instruct-sc2-concepts |
import time
def parse_date(value, dateformat='%Y-%m-%d'):
"""Parse a string into a date"""
return time.strptime(value.strip(), dateformat) | bigcode/self-oss-instruct-sc2-concepts |
def rayleigh_coefficients(zeta, omega_1, omega_2):
"""
Compute the coefficients for rayleigh damping such, that the modal damping
for the given two eigenfrequencies is zeta.
Parameters
----------
zeta : float
modal damping for modes 1 and 2
omega_1 : float
first eigenfrequen... | bigcode/self-oss-instruct-sc2-concepts |
def get_queue_arn(sqs_client, queue_url: str) -> str:
"""
Returns the given Queue's ARN. Expects the Queue to exist.
:param sqs_client: the boto3 client
:param queue_url: the queue URL
:return: the QueueARN
"""
response = sqs_client.get_queue_attributes(QueueUrl=queue_url, AttributeNames=["... | bigcode/self-oss-instruct-sc2-concepts |
def compute_scaling_dnu(numax, numax_threshold=300, numax_coeff_low=0.267, numax_coeff_high=0.22, numax_exponent_low=0.76, numax_exponent_high=0.797):
"""
Compute the large frequency separation (`dnu`).
This function computes a value of `dnu` from an input `numax` as based on
literature scaling relati... | bigcode/self-oss-instruct-sc2-concepts |
def word_doc_freq_map(doc):
"""emit words
Args:
doc (list[string]): one document
Returns:
zip(string, int): emitted words
"""
words = set(doc)
return zip(words, [1] * len(words)) | bigcode/self-oss-instruct-sc2-concepts |
def paraxial_focus(separation, z0, focal_length):
"""
Calculates the paraxial focus of a lens given its position, separation
between its two surfaces and the required focal length.
"""
focus = z0 + separation/2 + focal_length
return focus | bigcode/self-oss-instruct-sc2-concepts |
def filter_by_length(genes, transcripts, min_length):
""" Given a minimum transcript length, this function
- Iterates over transcripts and keeps the ones with length >= min_length
- Removes genes not represented in the transcript set
"""
filtered_transcripts = {}
filtered_genes = {}
... | bigcode/self-oss-instruct-sc2-concepts |
def find_review_comment(user_gitee, group, repo_name, pull_id):
"""
Find the review comment for PR
"""
review_key = "以下为 openEuler-Advisor 的 review_tool 生成审视要求清单"
data = user_gitee.get_pr_comments_all(group, repo_name, pull_id)
for comment in data[::-1]:
if review_key in comment['body']:... | bigcode/self-oss-instruct-sc2-concepts |
def predict(model, data):
"""
Predicts and prepares the answer for the API-caller
:param model: Loaded object from load_model function
:param data: Data from process function
:return: Response to API-caller
:rtype: dict
"""
# return a dictionary that will be parsed to JSON and sent bac... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_fig_name(title, tag, legends=[]):
"""Get the name of the figure with the title and tag."""
fig_name = "_".join(re.split("/|-|_|,", title) + legends).replace(" ", "")
return f"{fig_name}_generalization_{tag}.pdf" | bigcode/self-oss-instruct-sc2-concepts |
import requests
def is_already_blocked(ip, firewall_ip_and_port):
""" This function checks if {ip} is already blocked in the firewall.
:param ip: IP to check.
:param firewall_ip_and_port: URL of firewall wrapper.
:return: True if IP if already blocked on the firewall, False otherwise.
"""
ret... | bigcode/self-oss-instruct-sc2-concepts |
def getFeatureId(feature):
"""
Return the ID of a feature
params:
feature -> a feature
"""
return feature["id"] | bigcode/self-oss-instruct-sc2-concepts |
def field_name(field):
"""
Produce a clean version of a field's name.
The
:class:`zope.schema.fieldproperty.FieldPropertyStoredThroughField`
class mangles the field name, making it difficult to trace fields
back to their intended attribute name. This undoes that mangling
if possible.
T... | bigcode/self-oss-instruct-sc2-concepts |
def remap(degreeinput,degreemin,degreemax,dmxmin=0,dmxmax=65536):
"""
Convert the degree value to a 16 bit dmx number.
"""
DMXvalue = ((degreeinput - degreemin) * (dmxmax-dmxmin) / (degreemax - degreemin) + dmxmin)
return DMXvalue | bigcode/self-oss-instruct-sc2-concepts |
def get_month_delta(date1, date2):
"""
Return the difference between to dates in months.
It does only work on calendars with 12 months per year, and where the months
are consecutive and non-negative numbers.
"""
return date2.month - date1.month + (date2.year - date1.year) * 12 | bigcode/self-oss-instruct-sc2-concepts |
def notas(*n, sit=False):
"""
-> Função para analisar notas e situações de vários alunos.
:param n: uma ou mais notas dos alunos.
:param sit: valor opcional, para mostrar a situação do aluno.
:return: dicionário com várias informações sobre a situação da turma.
"""
nota = dict()
nota['to... | bigcode/self-oss-instruct-sc2-concepts |
def months_between(date1, date2):
"""
Compare two dates and return the number of months beetween them.
**Parameters**
``date1``
First date for the comparison
``date2``
Second date for the comparison
"""
if date1 > date2:
date1, date2 = date2, date1
m1 = date1.ye... | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_palindrome(usr_ip):
"""
Checks if string is a palindrome
ValueError: if string is invalid
Returns True if palindrome, False otherwise
"""
# remove punctuations & whitespace and change to all lowercase
ip_str = re.sub(r'[\s.;:,\'"!?-]', r'', usr_ip).lower()
if re.se... | bigcode/self-oss-instruct-sc2-concepts |
import math
def perturb_coordinates(old_coords, negative_freq_vecs, molecule_perturb_scale, reversed_direction):
"""
Perturbs a structure along the imaginary mode vibrational frequency vectors
old_coords (np.ndarray): Initial molecule coordinates
negative_freq_vecs (list of np.ndarray): Vibrational f... | bigcode/self-oss-instruct-sc2-concepts |
def _get_deps(meta, section=None):
"""
meta : dict-like
Parsed meta.yaml file.
section : str, list, or None
If None, returns all dependencies. Otherwise can be a string or list of
options [build, host, run, test] to return section-specific dependencies.
"""
def get_name(dep)... | bigcode/self-oss-instruct-sc2-concepts |
def _kwargs_to_props(**kwargs):
"""
Receives `kwargs` and returns them as dict to give easier manipulation
for different methods.
:param kwargs: kwargs
:return: kwargs dict
"""
props = {k: v for k, v in kwargs.items() if v}
return props | bigcode/self-oss-instruct-sc2-concepts |
def chip_converter(chip):
"""Converts a chip name to usable string."""
chip_map = {
"3xc": "TC",
"wildcard": "WC",
"bboost": "BB",
"freehit": "FH"
}
return chip_map[chip] | bigcode/self-oss-instruct-sc2-concepts |
def baseline_calc_hmean ( SSP1, SSP2, BSL_range, TAT):
""" Calculates measured baseline lengths (harmonic mean sound speed).
It needs:
SSP1 ... sound speed at beacon 1 in metres per second
SSP2 ... sound speed at beacon 2 in metres per second
BSL_range ... measured traveltime in milliseconds
TA... | bigcode/self-oss-instruct-sc2-concepts |
def spectral_penalty_d_optimal(svs,
already_abs=False,
already_normalized=False,
eps=1e-7):
"""
D-Optimal Regularizer as described in https://openreview.net/pdf?id=rJNH6sAqY7
"""
svs = list(svs.values())
... | bigcode/self-oss-instruct-sc2-concepts |
def code_h_format(what):
"""
Converts content of code/pictures history to an html form
Minor Tweak: You can change the html tags however you like.
Another Tweak: Can change the length of displayed history (100 currently)
"""
if len(what) == 0:
return ''
res = '<ul>'
# pick t... | bigcode/self-oss-instruct-sc2-concepts |
def parse_values_in_lines(lines):
"""
Parses the lines for 'A = B' lines and returns a dictionary, as well as the
profile name
"""
values = {}
profile_name = None
for line in lines:
line = line.strip()
if len(line) > 2 and line[0] == '[':
profile_name = line[1:-1]... | bigcode/self-oss-instruct-sc2-concepts |
def remove_empty_items(v: list) -> list:
"""Remove Falsy values from list.
Sees dicts with all Falsy values as Falsy.
This is used to allow people to submit list fields which are "empty" but are not really empty like:
`[{}, None, {name:"", email:""}]`
Example:
>>> remove_empty_items([{}, N... | bigcode/self-oss-instruct-sc2-concepts |
def Switch(node):
"""
Root of switch/case branch
Args:
node (Switch): Current position in node-tree
Return:
str : Translation of current node.
Children:
Expression Case+ Otherwise?
Expression:
Test-expression
Case:
Case-block
Otherwise:
Otherwise-block
Examples:
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def trim_id(id, prefix):
"""Remove insignificant characters from the feature ID
If we know the species in a downstream context, in an ID like
"ENSMUSG00000102628", we can infer everything except the "102628".
So we trim the ID to only those significant characters, which yields
a smalle... | bigcode/self-oss-instruct-sc2-concepts |
def command_result_processor_command_uninitialized(command_line_command):
"""
Command result message processor if a command line command is not initialized (should not happen).
Parameters
----------
command_line_command : ``CommandLineCommand``
Respective command.
Returns
-... | bigcode/self-oss-instruct-sc2-concepts |
import colorsys
def generate_colour(num, count, rotate):
"""Create an RGB colour value from an HSV colour wheel.
num - index from the rainbow
count - number of items in the rainbow
rotate - number between 0 and 1 to rotate the rainbow from its
usual red first, violet last.
"""
h = num / count
h = h + rotate
... | bigcode/self-oss-instruct-sc2-concepts |
def match_condition(exc_type):
"""Return a function that matches subclasses of ``exc_type``"""
return lambda _exc_type: issubclass(exc_type, _exc_type) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def create_property(attr: str, default: Any, type_annotation: type) -> property:
"""Return a property descriptor given config attribute."""
def fget(self) -> Any:
if attr in self._env_overrides:
return self._env_overrides[attr]
if attr in self._config:
... | bigcode/self-oss-instruct-sc2-concepts |
def wrapGrowthRatioDiv(value, MoM, YoY):
"""
Wrap the growth ratio into grids
MoM: month on month growth ratio
YoY: year on year growth ratio
"""
return "<div style='width:50%'>"+value+\
"</div><div style='width:50%'><table><tr><td>"+MoM+ \
"</td></tr><tr><td>"+YoY+"</td>... | bigcode/self-oss-instruct-sc2-concepts |
import re
def check_symbols(value):
"""
Checks if an string has symbols
:param value: String to be checked
:type value: String
:returns: True if there are symbols in the string
:rtype: Boolean
Examples:
>>> check_symbols('Lorem ipsum')
True
>>> check_... | bigcode/self-oss-instruct-sc2-concepts |
import re
def snake2camelback(snake_dict: dict):
"""Convert the passed dictionary's keys from snake_case to camelBack case."""
converted_obj = {}
for key in snake_dict.keys():
converted_key = re.sub(r'_([a-z])', lambda x: x.group(1).upper(), key)
converted_obj[converted_key] = snake_dict[k... | bigcode/self-oss-instruct-sc2-concepts |
def get_type(mal, kitsu_attr):
"""
Get the type of the weeb media.
:param mal: The MAL search result.
:param kitsu_attr: The attributes of kitsu search result.
:return: the type of the weeb media
"""
mal_type = mal.get('type')
if mal_type:
return mal_type
show_type = kitsu_a... | bigcode/self-oss-instruct-sc2-concepts |
def get_extension(filename: str, default_extension="py") -> str:
""" Get a file's extension (assumed to be after a period) """
if not filename:
return default_extension
return filename.lower().split(".")[-1] | 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.