seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import random
def cxSimulatedBinary(ind1, ind2, eta):
"""Executes a simulated binary crossover that modify in-place the input
individuals. The simulated binary crossover expects :term:`sequence`
individuals of floating point numbers.
:param ind1: The first individual participating in the crossover.
... | bigcode/self-oss-instruct-sc2-concepts |
def get_lookup_dicts(pred_name):
"""
Create part-of-speech-specific dicts mapping lemmas to sets of indices
:param pred_name: list of pred names, in order
:return: {'v':verb_dict, 'n':noun_dict}
"""
# Initialise lookup dicts
v_lookup = {}
n_lookup = {}
lookup = {'v':v_lookup, 'n':n_l... | bigcode/self-oss-instruct-sc2-concepts |
def process_entry(line: str) -> list:
"""Take a line from day2_input.txt and return important values"""
split_index = line.index(":")
split_range_index = line.index("-")
password = line[split_index + 2:len(line)]
return [split_index, split_range_index, password] | bigcode/self-oss-instruct-sc2-concepts |
def manhattan(t1b: tuple, t2b: tuple) -> int:
"""For parm pair of coordinate tuples, each (x, y). Return the Manhattan distance between them."""
t1x, t1y = t1b
t2x, t2y = t2b
return abs(t1x - t2x) + abs(t1y - t2y) | bigcode/self-oss-instruct-sc2-concepts |
def strip_terminating_semicolon(sql: str) -> str:
"""Removes terminating semicolon on a SQL statement if it exists"""
return sql.strip().rstrip(";").strip() | bigcode/self-oss-instruct-sc2-concepts |
def tracks_max_popularity_of_epoch(df, tracks=str, col_year=str, popularity=str, year_1=int, year_2=int):
"""
Busca las canciones con máxima popularidad para
un rango de años
:param df: nombre del datafreme
:param tracks: columna con el nombre de las canciones
:param col_year: columna con los añ... | bigcode/self-oss-instruct-sc2-concepts |
def add_all_numbers(n):
"""adds all numbers between zero and n, including n"""
return sum([number for number in range(n + 1)]) | bigcode/self-oss-instruct-sc2-concepts |
def create_finances_table_name(csv_name: str):
"""
Getting a readable table name from the finances csv
Example: EUHWC_-_Expense_Claims_(Responses)
expenses
:param csv_name:
:return:
"""
# table replacements
table_name = csv_name.split("_-_")[1]
table_name = table_name.sp... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_edu_text(text_subtree):
"""return the text of the given EDU subtree, with '_!'-delimiters removed."""
assert text_subtree.label() == 'text', "text_subtree: {}".format(text_subtree)
edu_str = ' '.join(word for word in text_subtree.leaves())
return re.sub('_!(.*?)_!', '\g<1>', edu_str) | bigcode/self-oss-instruct-sc2-concepts |
def _get_help_lines(content):
"""
Return the help text split into lines, but replacing the
progname part of the usage line.
"""
lines = content.splitlines()
lines[0] = 'Usage: <progname> ' + ' '.join(lines[0].split()[2:])
return lines | bigcode/self-oss-instruct-sc2-concepts |
def bestName(inRow):
"""
helper function for annotate_best_CDS
given a row with 'Label' and 'Locus tag', choose the best annotation
choose 'Label' if it's present
otherwise choose 'Locus tag'
return a string with the best name
"""
if inRow['Label'] == '':
result = inRow['Locus T... | bigcode/self-oss-instruct-sc2-concepts |
from unittest.mock import patch
def patch_site_configs(values):
"""
Helper to mock site configuration values.
:param values dict.
Use either as `@patch_site_configs(...)` or `with patch_site_configs(...):`.
"""
return patch.dict('openedx.core.djangoapps.site_configuration.helpers.MOCK_SITE_C... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def is_clique(old_graph, vertices):
"""
Tests if vertices induce a clique in the graph
Multigraphs are reduced to normal graphs
Parameters
----------
graph : networkx.Graph or networkx.MultiGraph
graph
vertices : list
vertices which are tested
Retu... | bigcode/self-oss-instruct-sc2-concepts |
def str_to_int(s):
""" Takes a string provided through user input, which may be hexadecimal or an integer, and
converts it to the actual corresponding integer. """
s = s.strip().lower()
if s.startswith("$"):
return int(s[1:], 16)
elif s.startswith("0x"):
return int(s[2:], 16)
... | bigcode/self-oss-instruct-sc2-concepts |
def sensor_param(request):
"""
parametrize a test with sensor parameters
"""
parameters = request.param
print('test parameters')
print('Device list : ' + str(parameters.devices))
print('socket list : ' + str(parameters.sockets))
print('one socket result : ' + str(parameters.one_socket_re... | bigcode/self-oss-instruct-sc2-concepts |
def is_version_compatible(version: dict, expected_version: tuple) -> bool:
"""
Args:
version: Dictionary containing version info.
Should have following fields -> 'major', 'minor', 'patch'
expected_version: Tuple of 3 elements for ('major', 'minor', 'patch')
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def _test_acc_token(client):
""" Tests access token by trying to fetch a records basic demographics """
try:
demo = client.get_demographics()
status = demo.response.get('status')
if '200' == status:
return True
else:
logging.warning('get_d... | bigcode/self-oss-instruct-sc2-concepts |
def nf(stage, fmap_base=8192, fmap_decay=1.7, fmap_max=32, fmap_min: int = 32):
"""Computes the number of feature map given the current stage.
This function is inspired from the following Github repo:
https://github.com/tkarras/progressive_growing_of_gans/blob/master/networks.py
Arguments:
sta... | bigcode/self-oss-instruct-sc2-concepts |
def match(line,keyword):
"""If the first part of line (modulo blanks) matches keyword,
returns the end of that line. Otherwise returns None"""
line=line.lstrip()
length=len(keyword)
if line[:length] == keyword:
return line[length:]
else:
return None | bigcode/self-oss-instruct-sc2-concepts |
def ignore_empty_keys(o: dict):
"""Removes keys with None-type values from the provided dict.
Used for JSON encoding to avoid schema errors due to empty or invalid parameters.
"""
return {k: v for (k, v) in o if v is not None} | bigcode/self-oss-instruct-sc2-concepts |
def remove_comments(sql: str) -> str:
"""Remove comments from SQL script."""
# NOTE Does not strip multi-line comments.
lines = map(str.strip, sql.split("\n"))
return "\n".join(line for line in lines if not line.startswith("--")) | bigcode/self-oss-instruct-sc2-concepts |
def getprofile(space):
"""Return the profiling function set with sys.setprofile.
See the profiler chapter in the library manual."""
w_func = space.getexecutioncontext().getprofile()
if w_func is not None:
return w_func
else:
return space.w_None | bigcode/self-oss-instruct-sc2-concepts |
import math
def time_str(val):
""" Convert perfcounter difference to time string minutes:seconds.milliseconds """
return f"{math.floor(val / 60):02}:{math.floor(val % 60):02}.{math.floor((val % 1) * 100):02}" | bigcode/self-oss-instruct-sc2-concepts |
def is_fullname_suffix(s):
""" Returns Trus if S is a full name suffix """
return s.upper().strip() in ['JUNIOR', 'SENIOR', 'JR', 'JR.', 'SR', 'SR.', 'DR', 'DR.', 'PHD', "PHD.", "SIR", "ESQ", "ESQ.", "I", "II", "III", "IV", "V", "VI", "1ST", "2ND", "3RD", "4TH", "5TH", "6TH"] | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_pkl(file_path):
"""Load serialized model with pickle library.
Parameters
----------
file_path: str Path to the serialized model.
Returns
-------
Trained model object.
"""
with open(file_path, 'rb') as model:
clf = pickle.load(model)
return ... | bigcode/self-oss-instruct-sc2-concepts |
def filtany(entities, **kw):
"""Filter a set of entities based on method return. Use keyword arguments.
Example:
filtany(entities, id='123')
filtany(entities, name='bart')
Multiple filters are 'OR'.
"""
ret = set()
for k,v in kw.items():
for entity in entities:
if getattr(entity, k)() ... | bigcode/self-oss-instruct-sc2-concepts |
def tag_limit_sibling_ordinal(tag, stop_tag_name):
"""
Count previous tags of the same name until it
reaches a tag name of type stop_tag, then stop counting
"""
tag_count = 1
for prev_tag in tag.previous_elements:
if prev_tag.name == tag.name:
tag_count += 1
if prev_t... | bigcode/self-oss-instruct-sc2-concepts |
import re
def original_image_extender(pipeline_index,
finder_image_urls,
extender_image_urls=[],
*args, **kwargs):
"""
Example:
http://media-cache-ec0.pinimg.com/70x/50/9b/bd/509bbd5c6543d473bc2b49befe75f4c6.jpg
http:/... | bigcode/self-oss-instruct-sc2-concepts |
def from_question_name(name: str) -> str:
"""
Generates GIFT text for a question name.
Parameters
----------
name : str
Name of a question.
Returns
-------
out: str
GIFT-ready question name.
"""
return f'::{name}::' | bigcode/self-oss-instruct-sc2-concepts |
import math
def _compute_sphere_overlap(d, r1, r2):
"""
Compute volume overlap fraction between two spheres of radii
``r1`` and ``r2``, with centers separated by a distance ``d``.
Parameters
----------
d : float
Distance between centers.
r1 : float
Radius of the first spher... | bigcode/self-oss-instruct-sc2-concepts |
import sympy
def solve(a, b, c):
""" Determine x valid value(s) for any Quadratic Equation
`ax² + bx + c = 0` where a, b, c are known values.
Returns a tuple of solutions (x1, x2)."""
if a == 0:
if b == 0:
return (None, None)
return (sympy.Rational(-c, b),None)
d = b*... | bigcode/self-oss-instruct-sc2-concepts |
def fragment_retrieval(coll, fields, fragment, case_sensitive = False):
"""Retrieves a list of all documents from the collection where the fragment
appears in any one of the given fields
Parameters
----------
coll: generator
The collection containing the documents
fields: iterable
... | bigcode/self-oss-instruct-sc2-concepts |
def convert_dict_vals_to_str(dictionary):
"""Convert dictionary to format in uppercase, suitable as env vars."""
return {k.upper(): str(v) for k, v in dictionary.items()} | bigcode/self-oss-instruct-sc2-concepts |
def getifname(sock):
"""Return interface name of `sock`"""
return sock.getsockname()[0] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Set
def get_allowed_courses(conflict_graph: Dict[str, Set[str]], already_selected: Set[str], prohibited: Set[str]) -> Set[str]:
"""
Returns the set of courses in course_df that do not conflict with any course names in
already_selected, according to the graph conf... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def aggr_events(events_raw):
"""Aggregates event vector to the list of compact event vectors.
Parameters:
events_raw -- vector of raw events
Returns:
events_aggr -- list of compact event vectors ([onset, offset, event])
"""
events_aggr = []
s = 0
for bi... | bigcode/self-oss-instruct-sc2-concepts |
def filter_profile_sounds(profile, sounds):
"""
Returns relative paths to sounds that are the folder specified by the profile.
:param profile: Str
:param sounds: List of Str
:return: List of Str
"""
if profile:
filter_lambda = lambda sound: sound.startswith(profile + "\\")
else: ... | bigcode/self-oss-instruct-sc2-concepts |
def get_installed_tool_shed_repository( trans, id ):
"""Get a repository on the Galaxy side from the database via id"""
return trans.sa_session.query( trans.model.ToolShedRepository ).get( trans.security.decode_id( id ) ) | bigcode/self-oss-instruct-sc2-concepts |
import json
def _GetErrorExtraInfo(error_extra_info):
"""Serializes the extra info into a json string for logging.
Args:
error_extra_info: {str: json-serializable}, A json serializable dict of
extra info that we want to log with the error. This enables us to write
queries that can understand the ... | bigcode/self-oss-instruct-sc2-concepts |
def end_game(_game):
"""
Will show a end game screen and thank the player.
Args:
_game: Current game state
Returns: Returns false to end game loop
"""
print("Thank you for playing")
return False | bigcode/self-oss-instruct-sc2-concepts |
def parameter_changed(parameter):
"""Check whether parameter is in a pre-validation changed state.
Args:
arcpy.Parameter: Parameter to check.
Returns:
bool: True if changed, False otherwise.
"""
return all((parameter.altered, not parameter.hasBeenValidated)) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Set
from typing import List
from typing import Dict
def deduped_actions(actions: Set[str]) -> List[str]:
"""Return a sorted list of all the unique items in `actions`, ignoring case."""
# First, group all actions by their lowercased values. This lumps "foo" and "FOO" together.
unique: D... | bigcode/self-oss-instruct-sc2-concepts |
def append_to_dataset(dataset, sample):
"""
Append a new sample to a provided dataset. The dataset has to be expanded before we can add value to it.
:param dataset:
:param sample: data to append
:return: Index of the newly added sample.
"""
old_size = dataset.shape[0] # this function always... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def get_data_element_total(
data_element_id: str,
data_values: List[dict],
) -> int:
"""
A DHIS2 data element may be broken down by category options, and
``data_values`` can contain multiple entries for the same data
element. This function returns the total for a given
... | bigcode/self-oss-instruct-sc2-concepts |
def to_megabytes(size_bytes):
"""
Convert size in bytes to megabytes
"""
return size_bytes * 1024 * 1024 | bigcode/self-oss-instruct-sc2-concepts |
def get_email_domain(email):
"""
Return the domain component of an email address. Returns None if the
provided string cannot be parsed as an email address.
>>> get_email_domain('test@example.com')
'example.com'
>>> get_email_domain('test+trailing@example.com')
'example.com'
>>> get_emai... | bigcode/self-oss-instruct-sc2-concepts |
def factR(n):
"""Assumes n an int > 0
Returns n!"""
if n == 1:
return n
else:
return n*factR(n - 1) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
def get_values_by_keys(k: list, default=None)->Callable[[dict], list]:
"""
Filter dictionary by list of keys.
Parameters
----------
k: list
default: any, optional
Set as default value for key not in dict.
Default value is None
"""
return lam... | bigcode/self-oss-instruct-sc2-concepts |
def left_to_right_check(input_line: str, pivot: int):
"""
Check row-wise visibility from left to right.
Return True if number of building from the left-most hint is visible looking to the right,
False otherwise.
input_line - representing board row.
pivot - number on the left-most hint of the in... | bigcode/self-oss-instruct-sc2-concepts |
def find_version_attribute(obj):
"""Depending on the object, modified, created or _date_added is used to store the
object version"""
if "modified" in obj:
return "modified"
elif "created" in obj:
return "created"
elif "_date_added" in obj:
return "_date_added" | bigcode/self-oss-instruct-sc2-concepts |
def returnTrue(layer):
"""Returns True for any object passed to it."""
return True | bigcode/self-oss-instruct-sc2-concepts |
def all_debates(debates):
"""Debate filter returning all debates.
"""
return debates | bigcode/self-oss-instruct-sc2-concepts |
def get_shell_from_file(shellname):
"""
Returns the shell from a .shell file in the shell directory as a string. It
can then be formatted to place ip and port in the file.
"""
filecontents = None
with open('shells/{}.shell'.format(shellname), 'r') as f:
filecontents = f.read()
return... | bigcode/self-oss-instruct-sc2-concepts |
def setKeyPath(parent, keyPath, value):
"""
Allows the setting of arbitrary nested dictionary keys via a single
dot-separated string. For example, setKeyPath(parent, "foo.bar.baz",
"xyzzy") would create any intermediate missing directories (or whatever
class parent is, such as ConfigDict) so that t... | bigcode/self-oss-instruct-sc2-concepts |
def temp_coeff_cold(lower, upper):
"""
Calculates and returns the m and b coefficients for y = m*x + b
for a line intersecting (lower, 0) and (upper, 255).
"""
m = 255/(upper-lower)
b = 255 - m * upper
return m, b | bigcode/self-oss-instruct-sc2-concepts |
import torch
def become_constant_trick(x, lengths):
"""
Input:
x: a tensor of shape (batch, stream, channel)
lengths: a tensor of shape (batch,)
Returns:
A tensor y of shape (batch, stream, channel), such that
y[i, j, k] = x[i, j, k] if j < lengths[i] else x[i, lengths[i],... | bigcode/self-oss-instruct-sc2-concepts |
def df_last_column(df, column_name):
"""Move a dataframe column to the right-most position.
Parameters
----------
df: :class:`pandas.DataFrame`
Dataframe to rearrange
column_name: :obj:`str`
Column to move.
Returns
----------
:class:`pandas.DataFrame`
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def get_colour(label: str) -> Optional[str]:
"""Given the label of the thing to plot, determine the colour."""
if "given investment" in label:
return "orange"
if "all-in day one" in label:
return "blue"
if "cash" in label:
return "red"
if "nomina... | bigcode/self-oss-instruct-sc2-concepts |
def domain(url):
"""
Extracts the domain of an url
>>> domain('https://gitlab.laas.fr/pipo')
'gitlab.laas.fr'
>>> domain('gitlab.laas.fr/pipo')
'gitlab.laas.fr'
"""
if '://' in url or url.startswith('//'):
url = url.split('//')[1]
return url.split('/')[0] | bigcode/self-oss-instruct-sc2-concepts |
import copy
def get_shared_data(component):
"""
Returns the actual list of component data based on how data is
stored in component, either from the `data` attribute or from the
`data['content']` attribute.
Returns:
list: List of component data.
"""
if component:
return (co... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def read_df(t, tfmt, store, path):
"""
Read a matrix present in a `store` at a certain `path` with
the appropriate formatting of the date `t`.
"""
key = Path(path) / t.strftime(tfmt)
df = store[str(key)]
return df | bigcode/self-oss-instruct-sc2-concepts |
import re
def filename_filter(filename: str, repl: str = '') -> str:
"""
将文件名替换成合法的文件名
:param filename: 原文件名
:param repl: 替换字符
:return: 合法文件名
"""
return re.sub('[/:*?"<>|]', repl, filename) | bigcode/self-oss-instruct-sc2-concepts |
def get_frac_moffat(r, alpha, beta):
"""
Calculate the fraction of light within radius r of a Moffat profile.
"""
frac = 1 - alpha**(2*(beta-1))*(alpha**2 + r**2)**(1-beta)
return(frac) | bigcode/self-oss-instruct-sc2-concepts |
def get_text_box(text, margin=0):
"""Return the coordinates of a Matplotlib Text.
`text` is a Matplotlib text obtained with ax.text().
This returns `(x1,y1, x2, y2)` where (x1,y1) is the lower left corner
and (x2, y2) is the upper right corner of the text, in data coordinates.
If a margin m is supp... | bigcode/self-oss-instruct-sc2-concepts |
import random
def create_neg_relations(entities, rels_between_entities, rel_type_count, neg_rel_count):
""" Creates negative relation samples, i.e. pairs of entities that are unrelated according to ground truth """
neg_unrelated = []
# search unrelated entity pairs
for i1, _ in enumerate(entities):
... | bigcode/self-oss-instruct-sc2-concepts |
def confirmation_reader(msg: str) -> bool:
"""Prints a message and asks for user confirmation.
Asks the user with a [Y/n] option for confirmation.
Args:
msg: The message to be printed before the confirmation choice.
Returns:
The users answer in form of a boolean value.
"""
ans... | bigcode/self-oss-instruct-sc2-concepts |
def get_unused_options(cfg_dict, options):
"""
Returns the unused keys in a configuration dictionary. An unused key
is a key that is not seen in *options*.
Parameters
----------
cfg_dict : dict
options : :py:class:`~enrich2.plugins.options.Options`
Returns
-------
`set`
... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_correlation_lengths(semimajor, semiminor):
"""Calculate the Condon correlation length
In order to derive the error bars from Gauss fitting from the
Condon (1997, PASP 109, 116C) formulae, one needs the so called
correlation length. The Condon formulae assumes a circular area
with diam... | bigcode/self-oss-instruct-sc2-concepts |
def split_and_fill(s, fill = 4, delim = ':'):
"""
Takes a string, a fill amount, and a delimiter and outputs an iterable,
where each index is the substring up to or after `delim`, zero-filled to `fill`.
e.g. split_and_fill("de:ad:be:ef") returns "00de", "00ad", "00be", "00ef"
"""
return (a.... | bigcode/self-oss-instruct-sc2-concepts |
import json
def convert_to_json(value):
"""Converts the inputted object to JSON format.
Args:
value (obj): The object to be converted
Returns:
string : The JSON representation of the inputted object
"""
return json.dumps(value) | bigcode/self-oss-instruct-sc2-concepts |
def build_creative_name(order_name, creative_num):
"""
Returns a name for a creative.
Args:
order_name (int): the name of the order in DFP
creative_num (int): the num_creatives distinguising this creative from any
duplicates
Returns:
a string
"""
return 'HB {order_name... | bigcode/self-oss-instruct-sc2-concepts |
def simple_method_io(method, cdt, indataname, outdataname):
"""
Helper function to create inputs and outputs for a simple
Method with one input, one output, and the same CompoundDatatype
for both incoming and outgoing data.
"""
minput = method.create_input(compounddatatype=cdt,
... | bigcode/self-oss-instruct-sc2-concepts |
def format_user(user_id):
"""
Formats a user id so it appears as @user in the slack
"""
return "<@" + user_id + ">" | bigcode/self-oss-instruct-sc2-concepts |
def scala_T(input_T):
"""
Helper function for building Inception layers. Transforms a list of numbers to a dictionary with ascending keys
and 0 appended to the front. Ignores dictionary inputs.
:param input_T: either list or dict
:return: dictionary with ascending keys and 0 appended to front... | bigcode/self-oss-instruct-sc2-concepts |
def is_material_collidable(material):
"""Check whether a material has meta suggesting we need collision meshes"""
collision_filter = material.meta('collisionFilter')
return (not collision_filter) or (len(collision_filter) > 0) | bigcode/self-oss-instruct-sc2-concepts |
def getClass(obj):
"""Return the class or type of object 'obj'.
Returns sensible result for oldstyle and newstyle instances and types."""
if hasattr(obj, '__class__'):
return obj.__class__
else:
return type(obj) | bigcode/self-oss-instruct-sc2-concepts |
import zipfile
import io
def _make_zip_file() -> zipfile.ZipFile:
"""Returns an in-memory zip file."""
data = io.BytesIO()
zf = zipfile.ZipFile(data, 'w')
zf.writestr('a.txt', b'content of a')
zf.writestr('b/c.txt', b'content of c')
zf.writestr('b/d/e.txt', b'content of e')
zf.writestr('b/f.txt', b'cont... | bigcode/self-oss-instruct-sc2-concepts |
def container_name_for(image, application_id):
"""
Get a name for a service container based on image and application ID
Parameters:
image - image that the container is for
application_id - application id that the container is for
Return value:
A string
"""
return image.... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def date_cleanup(date):
"""Transforms date of form YYYYMMDD to datetime object.
Args:
date (Union[str, NoneType]): Date of the form YYYYMMDD to be transformed.
Returns:
``datetime.datetime`` object if given string.
Returns None if None is given.
... | bigcode/self-oss-instruct-sc2-concepts |
def comma_to_dot(comma_number: str) -> float:
"""Transform the decimal separator from comma to dot.
Args:
comma_number: number as a string with comma as a decimal separator
Return:
The dot-separated number corresponding to the given one.
"""
return float(comma_number.replace(',', '.')) | bigcode/self-oss-instruct-sc2-concepts |
def fits_file(name, ra, my_dir):
"""Get the FITS file for a given source.
Parameters
----------
name : string
Source name.
ra : float
Right ascension.
my_dir : string
Working directory.
Returns
-------
string
Name of the FITS file of the field the so... | bigcode/self-oss-instruct-sc2-concepts |
def get_bytes(s):
"""Returns the byte representation of a hex- or byte-string."""
if isinstance(s, bytes):
b = s
elif isinstance(s, str):
b = bytes.fromhex(s)
else:
raise TypeError("s must be either 'bytes' or 'str'!")
return b | bigcode/self-oss-instruct-sc2-concepts |
import torch
def cRM_tanh_recover(O, K=10, C=0.1):
"""CRM tanh recover.
Args:
O (torch.Tensor): predicted compressed crm.
K (torch.Tensor): parameter to control the compression.
C (torch.Tensor): parameter to control the compression.
Returns:
M (torch.Tensor): uncompresse... | bigcode/self-oss-instruct-sc2-concepts |
def _get_item_from_doc(doc, key):
"""
Get an item from the document given a key which might use dot notation.
e.g.
doc = {'deep': {'nested': {'list': ['a', 'b', 'c']}}}
key = 'deep.nested.list.1'
-> 'b'
:param doc dict:
:param key str:
:rtype: value
"""
if '.' in key:
... | bigcode/self-oss-instruct-sc2-concepts |
def cmp_individual_scaled(a, b):
""" Compares two individual fitness scores, used for sorting population
Example:
>>> GPopulation.cmp_individual_scaled(a, b)
:param a: the A individual instance
:param b: the B individual instance
:rtype: 0 if the two individuals fitness score are the same,
... | bigcode/self-oss-instruct-sc2-concepts |
def prot_comp_composite(row):
"""Creates a composite column from the protein and compound IDs"""
composi = row["DeepAffinity Compound ID"] + "," + row["DeepAffinity Protein ID"]
return composi | bigcode/self-oss-instruct-sc2-concepts |
import math
def num2si(x, format='%.15g', si=True, space=' '):
"""
Returns x formatted using an exponent that is a multiple of 3.
Parameters
----------
x : scalar
The number to format.
format : str
Printf-style format specification used to format the mantissa.
si : bool
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Tuple
def process_data(data: str) -> List[Tuple[int, int, int]]:
"""Parse the raw data.
Convert raw triangle data:
1 2 3
4 5 6
Into list of tuples, where each item is a triangle with a, b, c sides
"""
triangles = []
for triangle in ... | bigcode/self-oss-instruct-sc2-concepts |
def check_enemy_ub(time_count):
"""check enemy ub
Args
time_count (int): count up after ub
Returns
is_enemy_ub (boolean): enemy ub existence
"""
if time_count > 9:
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_json(content):
"""Decode the JSON records from the response.
:param content: the content returned by the eBird API.
:type content: http.client.HTTPResponse:
:return: the records decoded from the JSON payload.
:rtype: list
"""
return json.loads(content.decode("utf-8")... | bigcode/self-oss-instruct-sc2-concepts |
def data_is_encrypted(tasks_backup_job):
""" Returns True if the tasks data has been encrypted.
This assumes that the worker stores the encrypted AES key in
tasks_backup_job.encrypted_aes_key_b64
when the tasks are encrypted.
This will return False for any backup ol... | bigcode/self-oss-instruct-sc2-concepts |
def get_first_label(x):
"""Returns the label of the first element.
:param x: Series or DataFrame
"""
return x.index[0] | bigcode/self-oss-instruct-sc2-concepts |
def max_lens(X):
"""
max_lens
Return: a tuple of which each element is the max length of the elements in
the corresponding dimension of the input X.
Example: max_lens([[1,2,3], [4,5]]) --> [2,3]
"""
if not isinstance(X[0], list):
return tuple([len(X)])
elif not isinstance... | bigcode/self-oss-instruct-sc2-concepts |
def linearsearch(A, elem):
"""
Linear Search Algorithm that searches for an element in an array with O(n) time complexity.
inputs: Array A and element e, that has to be searched
output: True/False
"""
for a in A:
if a==elem:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def efficientdet_params(model_name):
""" Map EfficientDet model name to parameter coefficients. """
params_dict = {
'efficientdet-d0': {
'compound_coef': 0,
'backbone': 'efficientnet-b0',
'R_input': 512,
'W_bifpn': 64,
'D_bifpn': 3,
... | bigcode/self-oss-instruct-sc2-concepts |
def subset_data_for_overhang(dataframe, overhang, horizontal=True, filter=True):
"""Subset Tatapov dataframe for given overhang.
**Parameters**
**dataframe**
> Tatapov dataset, for example `tatapov.annealing_data["25C"]["01h"]`
**overhang**
> Overhang class instance (`Overhang`)
**horiz... | bigcode/self-oss-instruct-sc2-concepts |
def maybe_name_or_idx(idx, model):
"""
Give a name or an integer and return the name and integer location of the
column in a design matrix.
"""
if idx is None:
idx = range(model.exog.shape[1])
if isinstance(idx, int):
exog_name = model.exog_names[idx]
exog_idx = idx
#... | bigcode/self-oss-instruct-sc2-concepts |
def is_code_token(text):
"""
True for non-comment, non-whitespace token text.
"""
char0 = text[0]
return char0 != '#' and char0 > ' ' and char0 != '\\' | bigcode/self-oss-instruct-sc2-concepts |
def range_check(df, maximum, minimum):
"""
range_check adds a column to data frame with label if data are out of range.
Arguments:
df: data frame with a column 'raw' of raw data.
maximum: maximum acceptable value - above this value, data are anomalous
minimum: minimum acceptable valu... | bigcode/self-oss-instruct-sc2-concepts |
def PyDict_Keys(space, w_obj):
"""Return a PyListObject containing all the keys from the dictionary,
as in the dictionary method dict.keys()."""
return space.call_method(space.w_dict, "keys", w_obj) | 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.