seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def _prod(x):
"""Compute the product of an iterable."""
out = 1
for a in x:
out *= a
return out | bigcode/self-oss-instruct-sc2-concepts |
def isInside(point, leftTop, rightBottom):
"""
return True if point is in the rectangle define by leftTop and rightBottom
"""
if not (leftTop[0] < point[0] < rightBottom[0]):
return False
if not (leftTop[1] < point[1] < rightBottom[1]):
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import random
def tournamentSelection(population,popSize):
"""
Function to select some 'good' parents from the population using tournament selection.
This implementation selection n pairs of parents, where n = population size // 2
Parameters:
population (list) - list of solutions.
po... | bigcode/self-oss-instruct-sc2-concepts |
def get_tags(sync_config):
""" return a list of tags with, there name, and displayName """
tags = []
for tag in sync_config['tags']:
tags.append({'name': tag['name'], 'displayName': tag['displayName']})
return tags | bigcode/self-oss-instruct-sc2-concepts |
def IsOperator(value):
""" Check if the passed value is 'operator' """
if value != None and value == "operator" :
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def _build_snapshot_tree(snapshots):
"""
Builds a tree fro the given snapshot.
Parameters
----------
snapshots : `list` of ``BaseSnapshotType``
The snapshot to build tree from.
Returns
-------
snapshot_tree : `dict` of (``client``, `dict` of (`type`, ``BaseSnapshotType`... | bigcode/self-oss-instruct-sc2-concepts |
def pis_map(diffn_img, index_low_b_val, index_high_b_val):
"""
Produces the physically implausible signal (PIS) map [1].
Parameters
----------
diffn_img
index_low_b_val : int
index into the DWI identifying the image with lower b-value.
Usually 0 referring to the b=0 (non-DW) im... | bigcode/self-oss-instruct-sc2-concepts |
def count_slash_for(s):
"""
Returns the number of times '/' appears in string s
Parameter s: the string to search
Precondition: s is a (possibly empty) string
"""
# Accumulator
count = 0
# Loop variable
for i in range(len(s)):
if s[i] == '/':
count= coun... | bigcode/self-oss-instruct-sc2-concepts |
def get_labels(label_filename):
""" Get the label of a given set
The labels are read from a text file, and a dictionary
is built. The key is the file stem and the value is
the label (either 0 for an attack or 1 for banafide access).
Parameters
----------
label_filename: str
The path to the fi... | bigcode/self-oss-instruct-sc2-concepts |
def composition_to_oxidcomposition(series, **kwargs):
"""
Adds oxidation states to a Composition using pymatgen's guessing routines
Args:
series: a pd.Series with Composition object components
**kwargs: parameters to control Composition.oxi_state_guesses()
Returns:
a pd.Series ... | bigcode/self-oss-instruct-sc2-concepts |
def update_available(data, recent_pick):
"""
Reduce available pokemon set by most recent pick.
Parameter
---------
data: DataFrame with available Pokemons
recent_pick: Picked Pokemon name
"""
df = data.copy()
return df.loc[df["Name_1"] != recent_pick] | bigcode/self-oss-instruct-sc2-concepts |
def _create_style(parameter_list):
"""Formats and translated the provided parameters to an ANSI escape sequence"""
return "\033[%sm" % ";".join(parameter_list) | bigcode/self-oss-instruct-sc2-concepts |
def filter_pheno_nan(x_species, y_pheno, pheno_name, verbose=False):
"""Filter X and Y to have same index and drop NANs
"""
y = y_pheno[pheno_name]
y.dropna(axis=0, how='all', inplace=True)
X = x_species
X = X.reindex(y.index)
return X, y | bigcode/self-oss-instruct-sc2-concepts |
def time_from_utc(utc_offset, time):
""" (number, float) -> float
Return UTC time in time zone utc_offset.
>>> time_from_utc(+0, 12.0)
12.0
>>> time_from_utc(+1, 12.0)
13.0
>>> time_from_utc(-1, 12.0)
11.0
>>> time_from_utc(+6, 6.0)
12.0
>>> time_from_utc(-7, 6.0)
23.0
... | bigcode/self-oss-instruct-sc2-concepts |
def replace_u_to_t(seq):
"""Replaces the U's in a sequence with T's.
Args:
seq (str): A nucleotide sequence.
Returns:
str: The sequence with the U's replaced by T's.
Examples:
>>> replace_u_to_t("ACGU")
'ACGT'
>>> replace_u_to_t(None)
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def get_max_release_version(version_id):
"""
Returns current release version of 3ds Max
:param version_id: int, release ID of the current Max version
:return: 3ds Max release version
:rtype: long
.. code-block:: python
import MaxPlus
from dccutils.max import app
versi... | bigcode/self-oss-instruct-sc2-concepts |
def extract(line):
"""Return a tuple (uin, nick) from 'O11111111 nickname'"""
line = line.replace("\n", "")
uin = line[1:line.find("\t")]
# fix uin
uin2 = ""
for c in uin:
if c.isdigit():
uin2 += c
uin = uin2
nick = line[1+line.find("\t"):]
nick = nick.replace("/", "_")
nick = nick.replace(":", "_... | bigcode/self-oss-instruct-sc2-concepts |
def _ConvertValueNameToChartAndTraceName(value_name):
"""Converts a value_name into the equivalent chart-trace name pair.
Buildbot represents values by the measurement name and an optional trace name,
whereas telemetry represents values with a chart_name.trace_name convention,
where chart_name is optional. Thi... | bigcode/self-oss-instruct-sc2-concepts |
def summy(string_of_ints):
"""This function takes a string of numbers with spaces and returns the sum of the numbers."""
numbers = string_of_ints.split()
answer = 0
for i in numbers:
answer = answer + int(i)
return answer | bigcode/self-oss-instruct-sc2-concepts |
def get_min(current_min, input_score):
"""
compare two input numbers, and return smaller one.
:param current_min: int, the current min score.
:param input_score: int, the score just input.
:return: int, compare two numbers and return smaller one.
"""
if current_min != 0 and current_min < inp... | bigcode/self-oss-instruct-sc2-concepts |
def create_css_rule(selectors: list, properties: dict) -> str:
"""
Return CSS rule properly formated.
Paramters
---------
selectors : list of string
list of the CSS selector to apply all the properties
properties : dict
dictionnary of CSS properties to apply
Returns
---... | bigcode/self-oss-instruct-sc2-concepts |
def adjust_displacement(n_trials, n_accept, max_displacement):
"""Adjusts the maximum value allowed for a displacement move.
This function adjusts the maximum displacement to obtain a suitable acceptance \
of trial moves. That is, when the acceptance is too high, the maximum \
displacement is incre... | bigcode/self-oss-instruct-sc2-concepts |
def wildcard_to_regexp(instring):
"""
Converts a player-supplied string that may have wildcards in it to regular
expressions. This is useful for name matching.
instring: (string) A string that may potentially contain wildcards (* or ?).
"""
regexp_string = ""
# If the string starts with an... | bigcode/self-oss-instruct-sc2-concepts |
def makeHtmlInlineImage(text):
"""Create HTML code for an inline image.
"""
return """<IMG SRC="%s" ALT="%s">""" % (text, text) | bigcode/self-oss-instruct-sc2-concepts |
def rollout(env, sess, policy, framer, max_path_length=100, render=False):
"""
Gather an episode of experiences by running the environment. Continues until env.done is True
or length of episode exceeds max_path_length
"""
t = 0
ob = env.reset()
obs = [ob]
logps = []
rews = []
acs... | bigcode/self-oss-instruct-sc2-concepts |
def lower_case(text: str) -> str:
"""Convert `text` to lower case.
Args:
text (str): The text to convert to lower case.
Returns:
The converted text.
"""
return text.lower() | bigcode/self-oss-instruct-sc2-concepts |
import torch
def reverse(input, dim=0):
"""
Reverses a tensor
Args:
- input: tensor to reverse
- dim: dimension to reverse on
Returns:
- reversed input
"""
reverse_index = input.new(input.size(dim)).long()
torch.arange(1 - input.size(dim), 1, out=reverse_index)
... | bigcode/self-oss-instruct-sc2-concepts |
def get_last_col(worksheet, row_num: int = 1) -> int:
"""Retrives the last nonblank column on Google Sheets
Parameters
----------
worksheet : Google Sheets worksheet
The worksheet being queried
row_num : int, optional
Row that's indicative of the overall data length, by default 1
... | bigcode/self-oss-instruct-sc2-concepts |
def pairwise(iterable):
"""
Iter over an iterable, two items by two items
>>> list(range(10)|pairwise())
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
"""
a = iter(iterable)
return zip(a, a) | bigcode/self-oss-instruct-sc2-concepts |
def bc(val):
""" Convert bool to single letter T or F """
if val is True:
return "T"
return "F" | bigcode/self-oss-instruct-sc2-concepts |
def assign_county(point, counties):
"""Assign a single point to its county."""
try:
match = next(
county['NAME'] for _, county in counties.iterrows()
if point.intersects(county['geometry'])
)
except StopIteration:
match = None
return match | bigcode/self-oss-instruct-sc2-concepts |
import mpmath
def cdf(x, mu=0, sigma=1):
"""
Log-normal distribution cumulative distribution function.
"""
if x <= 0:
return mpmath.mp.zero
lnx = mpmath.log(x)
return mpmath.ncdf(lnx, mu, sigma) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def broadcast_to_tensor(tensor, encoding, ch_axis):
"""
This helper method takes n-dimension tensor and a 1-dimension encoding. And the encoding is broad-casted to
match the n-dimensional tensor
:param tensor: Tensor to use as target for the broadcasting operation
:param encoding: Enc... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def write_yaml_data(filepath, data):
"""Write data to YAML file
Args:
filepath: the path to the YAML file
data: a dictionary to write to the YAML file
"""
with open(filepath, 'w') as stream:
yaml.safe_dump(data, stream, default_flow_style=False, indent=2)
return (... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_space_normalized_segment(segment):
"""Remove leading/trailing as well as multiple spaces from a string.
:param str segment: a segment (sentence)
:return: a string with no leading/trailing spaces and only containing single whitespaces
:rtype: str
"""
return re.sub(r'\s{2,}', ... | bigcode/self-oss-instruct-sc2-concepts |
def decimal_digits(x: float, precision: int) -> int:
"""Forms an integer from the base-10 digits of a floating-point number.
Args:
x: A floating point number, which may be negative.
precision: The number of digits after the decimal point to include.
Returns:
An integer containing a... | bigcode/self-oss-instruct-sc2-concepts |
def describe_class_or_specification(obj):
"""
Simple description of a class or interface/providedBy.
"""
return obj.__name__ if obj is not None else 'None' | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import Sequence
def a_seq_int(request: Any) -> Sequence[int]:
"""Provide random values that are sequences of ints."""
return request.param[1] | bigcode/self-oss-instruct-sc2-concepts |
def _extract_synonym(rest_of_line: str) -> str:
"""
Extracts synonym name from obo line.
:param rest_of_line: string containing line except for "synonym: "
:return:
"""
synonym = rest_of_line.split('"')[1].lower()
return synonym | bigcode/self-oss-instruct-sc2-concepts |
def color_temp_post_response_ok(devid, color_temp):
"""Return color temp change response json."""
return '''
{
"idForPanel": "''' + devid + '''",
"colorTemperature": ''' + str(int(color_temp)) + '''
}''' | bigcode/self-oss-instruct-sc2-concepts |
def ord_word(word):
"""
Convert an alphanumeric string to its ASCII values, used for ES keys.
"""
return ''.join([str(ord(letter)) for letter in word]) | bigcode/self-oss-instruct-sc2-concepts |
def cleanup_libs_list(libs):
"""Cleans up libs list by removing invalid entries"""
cleaned = []
for lib in libs:
lib = lib.strip()
if not lib.endswith('.lib.recipe'):
cleaned.append(lib)
return cleaned | bigcode/self-oss-instruct-sc2-concepts |
def read_num_from_file(file_with_path):
"""
read a number from a file
"""
with open(f"{file_with_path}", "r", encoding='utf-8') as text_file:
return int(text_file.read()) | bigcode/self-oss-instruct-sc2-concepts |
def _FlattenList(l):
"""Flattens lists of lists into plain lists, recursively.
For example, [[4, 5, 6], [7, 8], []] will become [4, 5, 6, 7, 8].
Non-list elements will get wrapped in a list, so 'foo' becomes ['foo'].
None becomes [].
Args:
l: a list, or not.
Returns:
A flattened list.
"""
re... | bigcode/self-oss-instruct-sc2-concepts |
import re
def feat_tokens(for_artist=True):
"""Return a regular expression that matches phrases like "featuring"
that separate a main artist or a song title from secondary artists.
The `for_artist` option determines whether the regex should be
suitable for matching artist fields (the default) or title... | bigcode/self-oss-instruct-sc2-concepts |
def nonzero_indices(arr, max_number=1):
"""get an array of indices that have nonzero value"""
result = []
for i in range(len(arr)):
if arr[i] != 0.0:
result.append((arr[i], i))
result = sorted(result, reverse=True)
n = min(max_number, len(result))
return [result[_][1] for _ i... | bigcode/self-oss-instruct-sc2-concepts |
def test_geojson(distribution):
"""
Test if a DCAT:distribution is GeoJSON.
"""
return (
distribution.get("mediaType") == "application/vnd.geo+json"
or distribution.get("format", "").lower() == "geojson"
) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def clean_source(source: List[str]) -> List[str]:
"""
Cleans the source content of a Synapse notebook cell.
:param source: The source content of the cell.
:returns: The cleaned source content of the cell.
"""
source = list([line.rstrip() for line in source])
source... | bigcode/self-oss-instruct-sc2-concepts |
import warnings
def puppy_vid_inspected_trajectory(grp, step_width, loc_marker, epoch_idx, obs_offset):
"""
.. deprecated:: 1.0
Use :py:class:`PuppyActionVideo` instead
"""
warnings.warn('deprecated, use PuppyActionVideo instead')
loc_x = grp['puppyGPS_x'][obs_offset+step_width*e... | bigcode/self-oss-instruct-sc2-concepts |
from struct import pack
def makePalMeta(color_table_ptr: int, colors_count: int, title_len: int):
"""Generates a metadata record for a palette in a pal file.
Since we don't have a serializer in KS, we use the manual one."""
res = bytearray()
res += b"\0\0\0"
res += pack("<I", color_table_ptr)
res += pack("<I",... | bigcode/self-oss-instruct-sc2-concepts |
def get_module(module_id, module_registry):
"""Obtains a configured ContourFeatures given an algorithm identificator.
Parameters
----------
module_id : str
Module identificator (e.g., bitteli, melodia).
module_registry : dict
Dictionary of module_ids to class instances
Returns
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Any
def flatten(ll: List[List[Any]]) -> List[Any]:
"""
Flatten a list of lists into a single list.
"""
return [a for l in ll for a in l] | bigcode/self-oss-instruct-sc2-concepts |
def _class_required(type_, class_, params):
"""Return true if method requires a `cls` instance."""
if not params or class_ is None:
return False
return type_ == 'classmethod' | bigcode/self-oss-instruct-sc2-concepts |
def _make_version(major, minor, micro, level, serial):
"""Generate version string from tuple (almost entirely from coveragepy)."""
level_dict = {"alpha": "a", "beta": "b", "candidate": "rc", "final": ""}
if level not in level_dict:
raise RuntimeError("Invalid release level")
version = "{0:d}.{1:... | bigcode/self-oss-instruct-sc2-concepts |
def char_to_decimal(text):
"""
Converts a string to its decimal ASCII representation, with spaces between
characters
:param text: Text to convert
:type text: string
:rtype: string
For example:
>>> import putil.misc
>>> putil.misc.char_to_decimal('Hello world!')
'... | bigcode/self-oss-instruct-sc2-concepts |
def _structure_parent_category(_parent_id, _payload):
"""This function structures the portion of the payload for the parent category.
.. versionadded:: 2.5.0
:param _parent_id: The ID of the parent category (if applicable)
:type _parent_id: str, None
:param _payload: The partially constructed payl... | bigcode/self-oss-instruct-sc2-concepts |
def parse_drive_size(line):
"""Parses a drive line in the partition information file.
"""
parts = line.split(":")
if len(parts) != 2 or parts[0] != "drive":
raise ValueError("Drive size line format is 'drive:<size>'")
return parts[1] | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_duplicate_labels(labels, n_items, max_label):
"""
Converts the number of items that exist in the game (not
including the targets) to a count word that is interchangeable
with another count word meaning the same thing. For example, the
label for the value "0" can either be 0 or... | bigcode/self-oss-instruct-sc2-concepts |
def NOT(event, sample_space):
"""Returns subset of events from set of samples that are NOT in the subset event."""
return sample_space - event | bigcode/self-oss-instruct-sc2-concepts |
def _patsplit(pattern, default):
"""Split a string into the optional pattern kind prefix and the actual
pattern."""
if ':' in pattern:
kind, pat = pattern.split(':', 1)
if kind in ('re', 'glob', 'path', 'relglob', 'relpath', 'relre',
'listfile', 'listfile0', 'set'):
... | bigcode/self-oss-instruct-sc2-concepts |
def query_to_json(query, name):
"""This query is useful to fetch a complex join
with some aggregations as a single blob, and later,
just hydrate it without having to iterate over the resultset
.. Example:
SELECT
u.id::varchar,
to_jsonb(array_agg(scopes)) as scopes,
... | bigcode/self-oss-instruct-sc2-concepts |
def are_features_consistent(train_df, test_df, dependent_variables=None):
"""Verifies that features in training and test sets are consistent
Training set and test set should have the same features/columns, except for the dependent variables
train_dr: pd.DataFrame training dataset
test_df: pd.Dat... | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
from typing import List
from typing import Any
def get_downloaded_partitions(path_to_folder: pathlib.Path) -> List[Any]:
"""Retrieves the full paths of the partitions file in a folder.
Parameters
----------
path_to_folder: pathlib.Path
A pathlib.Path indicating the full path to... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def mandatory(val: Any) -> Any:
"""Raises a ValueError if the provided input is None, otherwise returns it"""
if (val is None):
raise ValueError("Missing mandatory configuration value")
return val | bigcode/self-oss-instruct-sc2-concepts |
def _snapshot_v2_to_v1(snapv2_result):
"""Transform a v2 snapshot dict to v1."""
snapshots = snapv2_result.get('snapshots')
if snapshots is None:
snapshots = [snapv2_result['snapshot']]
for snapv1 in snapshots:
# The updated_at property was added in v2
snapv1.pop('updated_at', N... | bigcode/self-oss-instruct-sc2-concepts |
def _table_type(typestr):
"""Return the translation of CRDS fuzzy type name `typestr` into numpy dtype str() prefixes.
If CRDS has no definition for `typestr`, return it unchanged.
"""
int_types = [">i","<i","uint","int"]
float_types = [">f","<f","float","float"]
complex_types = [">c","<c","com... | bigcode/self-oss-instruct-sc2-concepts |
def complex_transmission_reflection(in_m0,in_m1,in_m2):
"""
complex_transmission_reflection(in_m0,in_m1,in_m2)
Calculate the complex transmission and reflection coefficients between
media 0, 1, and 2 given their complex refractive indices.
In the Kramers-Kronig implementation (in which this is most likely us... | bigcode/self-oss-instruct-sc2-concepts |
def is_number(word: str) -> bool:
"""Check if string/words is a number.
Args:
word: Word to check.
Returns:
True, if given word is a number.
"""
try:
float(word)
return True
except ValueError:
return False | bigcode/self-oss-instruct-sc2-concepts |
def rectcenter(rect, cast=float):
"""Returns the center ``[x,y]`` of the given `rect`.
Applies the given `cast` function to each coordinate."""
return [cast((rect[0]+rect[2]-1)/2.0), cast((rect[1]+rect[3]-1)/2.0)] | bigcode/self-oss-instruct-sc2-concepts |
def mod_exp(val, exp, modulus):
"""Computes an exponent in a modulus.
Raises val to power exp in the modulus without overflowing.
Args:
val (int): Value we wish to raise the power of.
exp (int): Exponent.
modulus (int): Modulus where computation is performed.
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def read_pickle(filepath):
"""Read pickle file"""
infile = open(filepath,'rb')
data = pickle.load(infile)
infile.close()
return data | bigcode/self-oss-instruct-sc2-concepts |
def _hasclass(context, *cls):
""" Checks if the context node has all the classes passed as arguments
"""
node_classes = set(context.context_node.attrib.get('class', '').split())
return node_classes.issuperset(cls) | bigcode/self-oss-instruct-sc2-concepts |
def get_rank(raw):
"""Return the rank of the player."""
display_rank = None
prefix = raw.get('prefix')
rank = raw.get('rank')
playerRank = raw.get('playerRank')
if prefix:
return prefix
elif rank:
return rank.replace('_', ' ')
else:
return playerRank.replace('_'... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _get_idx_worst(name, ref, hyp):
"""
Computes the batch indices for which the input metric value is worse than the current metric value.
Parameters
----------
name : str
'mse', 'psnr', 'ssim', 'lpips', or 'fvd'. Metric to consider. For 'mse', 'fvd' and 'lpips', lower is be... | bigcode/self-oss-instruct-sc2-concepts |
def ms_to_time(x):
"""Converts and integer number of miliseconds to a time string."""
secs = x / 1000.0
s = secs % 60
m = int(secs / 60) % 60
h = int(secs / 3600)
rtn = []
if h > 0:
rtn.append("{0:02}".format(h))
if m > 0:
rtn.append("{0:02}".format(m))
rtn.append("... | bigcode/self-oss-instruct-sc2-concepts |
def fixture_vcf_sample_id(sample_id: str) -> str:
"""Return a sample id that exists in the test VCF"""
return sample_id | bigcode/self-oss-instruct-sc2-concepts |
def new_dummy_vertex(vertex: int, key: int, biggest: int) -> int:
"""New dummy vertex ID
Args:
vertex: Vertex ID
key: Edge key
biggest: Biggest vertex ID
Returns:
ID of a new negative dummy vertex if key is greater than one.
Otherwise return the same vertex ID as th... | bigcode/self-oss-instruct-sc2-concepts |
import string
def MakeValidFieldName(header):
"""Turn a header name into a valid bigquery field name.
https://developers.google.com/bigquery/docs/tables
Field names are any combination of uppercase and/or lowercase
letters (A-Z, a-z), digits (0-9) and underscores, but no spaces. The
first character must b... | bigcode/self-oss-instruct-sc2-concepts |
def principal_form(disc):
"""Construct principal form for given discriminant.
Follows Def. 5.4 from `Binary quadratic forms` by Lipa Long, 2019:
https://github.com/Chia-Network/vdf-competition/blob/master/classgroups.pdf
"""
assert disc % 4 == 0 or disc % 4 == 1
k = disc % 2
f = (1, k, (k *... | bigcode/self-oss-instruct-sc2-concepts |
import json
def create_snippet(file_path):
"""
Creates a snippet of the original SQuAD data.
Args:
file_path: path to the original file
Returns: string containing file contents
"""
with open(file_path) as data_file:
data = json.load(data_file)['data']
out = {
... | bigcode/self-oss-instruct-sc2-concepts |
def zoo(total_head, total_legs, animal_legs=[2, 4]):
"""
Find the number of kangaroo and tiger in a zoo.
For example:
zoo(6, 16) -> (4, 2)
zoo(8, 20, [4, 2, 2]) -> (2, 0, 6)
Parameters
----------
total_head: int
Total number of animals
total_legs: int
... | bigcode/self-oss-instruct-sc2-concepts |
def clean_name(string):
"""Clean entity/device name."""
return string.replace("-", " ").replace("_", " ").title() | bigcode/self-oss-instruct-sc2-concepts |
def _get_units_prod(array_in, array_out):
"""Helper method calculate units after a product operation
Parameters
----------
array_in : np.ndarray
Array before product operation
array_out : np.ndarray, float
Array after product operation
Returns
-------
... | bigcode/self-oss-instruct-sc2-concepts |
def UsersInvolvedInIssues(issues):
"""Return a set of all user IDs referenced in the issues' metadata."""
result = set()
for issue in issues:
result.update([issue.reporter_id, issue.owner_id, issue.derived_owner_id])
result.update(issue.cc_ids)
result.update(issue.derived_cc_ids)
result.update(fv.... | bigcode/self-oss-instruct-sc2-concepts |
def user_info(props):
"""Decorator to specify a list of properties requested about the current user"""
def real_decorator(function):
function.pi_api_user_info = props
return function
return real_decorator | bigcode/self-oss-instruct-sc2-concepts |
def pretty_print(x, numchars):
"""Given an object `x`, call `str(x)` and format the returned string so
that it is numchars long, padding with trailing spaces or truncating with
ellipses as necessary
"""
s = str(x)
if len(s) > numchars:
return s[:(numchars - 3)] + '...'
else:
... | bigcode/self-oss-instruct-sc2-concepts |
def choice(*args):
"""
Creates a choice argument type. The user will be able to choose one of given possibilities.
Example:
choice("quickly", "slowly")
:param args: a list of string the user will be able to choose
:return: a dict representing this argument type with the appropriate format t... | bigcode/self-oss-instruct-sc2-concepts |
def de_median_redshift(wavelength, median_z):
"""De-redshifts the same way as above
Parameters:
wavelength (array): wavelength values to convert
median_z (int): redshift to change the wavelength by
Returns:
wavelength_red (array): redshifted wavelength
"""
wavelength_red = wavelength... | bigcode/self-oss-instruct-sc2-concepts |
def cons(a, b):
"""
Construct a pair.
:param a: first element
:param b: second element
:return: a function that takes a function and activates it on the pair
"""
def pair(f):
return f(a, b)
return pair | bigcode/self-oss-instruct-sc2-concepts |
def make_filename(instance, filename):
"""Makes the filename of the users profile image nice."""
return "profile_images/" + str(instance.user.id) + "." + filename.split(".")[-1] | bigcode/self-oss-instruct-sc2-concepts |
def padBits(bits, padding):
"""Pad the input bits with 0's so that it is of length padding"""
return [0] * (padding-len(bits)) + bits | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def endmembers_from_interaction(configuration):
"""For a given configuration with possible interactions, return all the endmembers"""
config = []
for c in configuration:
if isinstance(c, (list, tuple)):
config.append(c)
else:
config.append([c])
... | bigcode/self-oss-instruct-sc2-concepts |
import smtplib
def connect(smtp_server, smtp_port=25):
"""
Connect to the SMTP server to send emails.
:param smtp_server: Hostname or IP Address of the SMTP server
:param smtp_port: Port number of the SMTP server, default is 25.
:returns: server instance without logging in.
:raises: None
... | bigcode/self-oss-instruct-sc2-concepts |
def _CheckReadMeComplete(input_api, output_api):
"""Verifies that any new files have been added to the README file.
Checks that if any source files were added in this CL, that they were
also added to the README file. We do not warn about pre-existing
errors, as that would be annoying.
Args:
input_api:... | bigcode/self-oss-instruct-sc2-concepts |
def _parse_error_msg(err):
"""Parse MPD error message."""
if not err.startswith('mpd error:'):
return err
return err.split(':', 1)[1].strip() | bigcode/self-oss-instruct-sc2-concepts |
def transpose_time_to_spat(x):
"""Swap time and spatial dimensions.
Returns
-------
x: torch.Tensor
tensor in which last and first dimensions are swapped
"""
return x.permute(0, 3, 2, 1) | bigcode/self-oss-instruct-sc2-concepts |
def clamp(number, lower, upper):
"""
Limits the range of a number with a specified boundary
"""
return max(min(number, upper), lower) | bigcode/self-oss-instruct-sc2-concepts |
def check_force_length_constraints(force, tol=0.01, printout=False):
"""Checks whether target length constraints applied to the force diagrams are respected, i.e. are below the tolerance criteria.
Parameters
----------
force: compas_ags.diagrams.ForceDiagram
The force diagram to check deviation... | bigcode/self-oss-instruct-sc2-concepts |
import io
from PIL import Image
def matplotlib_figure_to_image(fig):
"""
Convert a matplotlib figure to an image in RGB format, for instance
to save it on disk
"""
buf = io.BytesIO()
fig.savefig(buf)
buf.seek(0)
return Image.open(buf).convert("RGB") | bigcode/self-oss-instruct-sc2-concepts |
def get_expected_ploidy(gender, chrom):
"""
Determine expected ploidy of call based on sample's gender and chromosome. Unknown genders are processed as diploid.
Args:
gender (string): M,F or U
chrom (string): chromosome, PAR values should be represented as XY
Returns
... | 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.