seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import csv
def csv_readline_to_list(csv_file):
"""
Read the CSV content by line.
Example:
csv content:
|name|age|
| a |21 |
| b |22 |
| c |23 |
| d |24 |
| e |25 |
ret = csv_readline_to_list("d/demo.csv")
Ret... | bigcode/self-oss-instruct-sc2-concepts |
def append_instr(qobj, exp_index, instruction):
"""Append a QasmQobjInstruction to a QobjExperiment.
Args:
qobj (Qobj): a Qobj object.
exp_index (int): The index of the experiment in the qobj.
instruction (QasmQobjInstruction): instruction to insert.
"""
qobj.experiments[exp_ind... | bigcode/self-oss-instruct-sc2-concepts |
def cols_to_string_with_dubquotes(cols, backslash=False):
"""
Gets a string representation of a list of strings, using double quotes.
Useful for converting list of columns to a string for use in a query.
Backslashes are possible if the query will be passed as a string argument to (for instance) Shuttle... | bigcode/self-oss-instruct-sc2-concepts |
def get_shock_sds_index_tuples(periods, factors):
"""Index tuples for shock_sd.
Args:
periods (list): The periods of the model.
factors (list): The latent factors of the model.
Returns:
ind_tups (list)
"""
ind_tups = []
for period in periods[:-1]:
for factor in... | bigcode/self-oss-instruct-sc2-concepts |
def applymap_numeric_columns(df, func):
"""Map a function elementwise to numeric columns.
All other columns are returned unchanged.
"""
columns = df._get_numeric_data().columns
df[columns] = df[columns].applymap(func)
return df | bigcode/self-oss-instruct-sc2-concepts |
def subs(text, subst):
"""Based on substitution dict, replace letters in text by their subst
First converts to lower case. Every non-letter is left intact"""
text = text.lower()
return ''.join([subst[l] if l in subst else l for l in text]) | bigcode/self-oss-instruct-sc2-concepts |
def transform_pos(word_pos):
"""Map POS tag to first character lemmatize() accepts"""
if word_pos == 'Noun':
return 'n'
elif word_pos == 'Verb':
return 'v'
elif word_pos == 'Adjective':
return 'a'
elif word_pos == '':
return '' | bigcode/self-oss-instruct-sc2-concepts |
def longest_common_prefix(items1, items2):
"""
Return the longest common prefix.
>>> longest_common_prefix("abcde", "abcxy")
'abc'
:rtype:
``type(items1)``
"""
n = 0
for x1, x2 in zip(items1, items2):
if x1 != x2:
break
n += 1
return items1[:n] | bigcode/self-oss-instruct-sc2-concepts |
def to_list(arr):
"""Transform an numpy array into a list with homogeneous element type."""
return arr.astype(type(arr.ravel()[0])).tolist() | bigcode/self-oss-instruct-sc2-concepts |
def fact(n):
"""Factorial. fact(5) = 5! = 5 * 4! = 5 * 4 * 3 * 2 * 1 = 120"""
if n == 1:
return 1
return n * fact(n - 1) | bigcode/self-oss-instruct-sc2-concepts |
def extractFieldValueFromGml(gmlString, labelInit,labelFin):
"""
Returns the value between two labels in a gml.
Eliminates spaces at start and end of the returned value
"""
g=gmlString
s1=labelInit
s2=labelFin
i=g.find(s1)
f=g.find(s2)
g2= g[i:f]
s1=g2.find('>')+1
g3=g2[s... | bigcode/self-oss-instruct-sc2-concepts |
def default_account(web3):
"""Returns the default account which is used to deploy contracts"""
return web3.eth.defaultAccount | bigcode/self-oss-instruct-sc2-concepts |
def index_map(idx_lines):
"""Returns a map from the orbital index to its descriptive quantum
numbers
:param idx_lines: lines defining the index -> orbital key
"""
idx_map = dict()
for line in idx_lines:
row = line.split()
row[0] = int(row[0])
idx_map[row[0]] = tuple(row[1... | bigcode/self-oss-instruct-sc2-concepts |
def truncate(phrase, n):
"""Return truncated-at-n-chars version of phrase.
If the phrase is longer than, or the same size as, n make sure it ends with '...' and is no
longer than n.
>>> truncate("Hello World", 6)
'Hel...'
>>> truncate("Problem solving is the best!... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from typing import List
def trits_from_int(n: int, pad: Optional[int] = 1) -> List[int]:
"""
Returns a trit representation of an integer value.
:param n:
Integer value to convert.
:param pad:
Ensure the result has at least this many trits.
References:... | bigcode/self-oss-instruct-sc2-concepts |
def event_team_object_factory(event_id, team_id):
"""Cook up a fake eventteam json object from given ids."""
eventteam = {
'event_id': event_id,
'team_id': team_id
}
return eventteam | bigcode/self-oss-instruct-sc2-concepts |
def _GetSetOfAllTestArgs(type_rules, shared_rules):
"""Build a set of all possible 'gcloud test run' args.
We need this set to test for invalid arg combinations because gcloud core
adds many args to our args.Namespace that we don't care about and don't want
to validate. We also need this to validate args comin... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
from typing import Optional
from typing import Union
from typing import Type
from typing import Any
def split_list_type(ftype) -> Tuple[Optional[Union[Type[list], Type[set]]], Any]:
"""Checks if the ftype is a List (or Set) type and return the list type and the inner type.
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
import click
def cli_ssh_group_member_id_argument() -> Any:
"""An argument to specify the ssh group member id.
This is effectively the id of a user that is
part of the group.
"""
return click.argument(
"ssh_group_member_id",
type=str,
required=True,
... | bigcode/self-oss-instruct-sc2-concepts |
import math
def total_level(source_levels):
"""
Calculates the total sound pressure level based on multiple source levels
"""
sums = 0.0
for l in source_levels:
if l is None:
continue
if l == 0:
continue
sums += pow(10.0, float(l) / 10.0)
level =... | bigcode/self-oss-instruct-sc2-concepts |
def take_nth(n):
"""Take each nth item from a collection, always start on first (0 idx)."""
def generator(coll):
for i, item in enumerate(coll):
if not i % n:
yield item
return generator | bigcode/self-oss-instruct-sc2-concepts |
import torch
def l2norm(X):
"""L2-normalize columns of X
"""
norm = torch.pow(X, 2).sum(dim=-1, keepdim=True).sqrt()
X = torch.div(X, norm+1e-10)
return X | bigcode/self-oss-instruct-sc2-concepts |
import colorsys
def rgb_to_hsv(r: int, g: int, b: int) -> tuple:
"""Convert an RGB color (from 0 to 255) to HSV equivalent (from 0 to 1)
"""
return colorsys.rgb_to_hsv(r / 255, g / 255, b / 255) | bigcode/self-oss-instruct-sc2-concepts |
def _update_nested_dict(dict_1: dict, dict_2: dict) -> dict:
"""
Update `dict_1` with elements from `dict_2` in a nested manner.
If a value of a key is a dict, it is going to be updated and not replaced by a the whole dict.
Parameters
----------
dict_1 : dict
The dictionary to be update... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def ensure_dmg_extension(filepath: Path) -> Path:
"""
Make sure given file have .dmg extension
"""
if filepath.suffix != '.dmg':
return filepath.with_suffix(f'{filepath.suffix}.dmg')
return filepath | bigcode/self-oss-instruct-sc2-concepts |
def _NodeShape(data):
"""Helper callback to set default node shapes."""
node_type = data.get("type", "statement")
if node_type == "statement":
return "box"
elif node_type == "identifier":
return "ellipse"
elif node_type == "magic":
return "doubleoctagon"
else:
return "" | bigcode/self-oss-instruct-sc2-concepts |
def find_key_value_in_dict(d, key):
"""
Searches a dictionary (with nested lists and dictionaries)
for the first value matching to the provided key.
"""
for k, v in d.iteritems():
if k == key:
return v
elif isinstance(v, dict):
r = find_key_value_in_dict(v, ke... | bigcode/self-oss-instruct-sc2-concepts |
def check_pre(v, g, order):
"""Check if all predecessors have already been placed."""
if order.index(v) > -2:
return False
for v2 in g.predecessors(v):
if order.index(v2) == -2:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def is_illegal_dir(d: Path):
"""Refuse to remove directories for some situations, for safety.
"""
if (d / ".git").exists():
return ".git file found"
if d.absolute() == Path.home().absolute():
return "cannot replace home directory"
if d.absolute == Path("/")... | bigcode/self-oss-instruct-sc2-concepts |
def shift_to_include_gamma(mp_grid):
""" Calculate the shift required to include $\\Gamma$.
in the Monkhorst-Pack grid.
Parameters:
mp_grid (:obj:`list` of :obj:`int`): number of grid points
in each reciprocal space direction.
Returns:
:obj:`list` of :obj:`float`: shift req... | bigcode/self-oss-instruct-sc2-concepts |
def get_support(item, item_set):
"""
Get support of specified item.
Args:
item (frozenset): The specified item.
item_set (list[tuple]): The frequent item set with support.
Returns:
Support of specified item.
"""
for key, value in item_set:
if frozenset(key) == i... | bigcode/self-oss-instruct-sc2-concepts |
def liquidThermalConductivity(T, lTCP):
"""
liquidThermalConductivity(float T, list lTCP)
liquidThermalConductivity (W/m/K) = 10**(A + B*(1-T/C)^(2/7))
Parameters
T, temperature in Kelvin
lTCP, A=lTCP[0], B=lTCP[1], C=lTCP[2]
A, B, and C are regression coefficients
Returns... | bigcode/self-oss-instruct-sc2-concepts |
def load_stop_words(words):
"""Load stopwords list, return a set"""
with open(words, "r") as lines:
set_stop_words = set()
for i in lines:
set_stop_words.add(i.strip())
return set_stop_words | bigcode/self-oss-instruct-sc2-concepts |
def get_param_value_and_result_list_call(exp_run, val_results_list, **kwargs):
"""
Callable functions to be used when traversing experiments.
Returns dictionary with data organised by environment and agent parameters and their available
values in any of the experiments.
:param exp_run: Dictionary w... | bigcode/self-oss-instruct-sc2-concepts |
def fitLine(line_points):
""" Given 2 points (x1,y1,x2,y2), compute the line equation
y = mx + b"""
x1 = line_points[0]
y1 = line_points[1]
x2 = line_points[2]
y2 = line_points[3]
m = (y2 - y1) / (x2 - x1)
b = y1 - m * x1
return (m, b) | bigcode/self-oss-instruct-sc2-concepts |
def map_items_to_parent(items, parents):
"""Groups all items into a list based on thier respective parent
ex: pages have request, runs have pages
"""
item_lists = {}
if len(parents) > 0:
pk = parents.values()[0].pk
for p_id in parents:
item_lists[p_id] = []
for i... | bigcode/self-oss-instruct-sc2-concepts |
def _check_classifer_response_method(estimator, response_method):
"""Return prediction method from the response_method
Parameters
----------
estimator: object
Classifier to check
response_method: {'auto', 'predict_proba', 'decision_function'}
Specifies whether to use :term:`predict... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def base_func(aggregate_function):
"""Deals with the possibility of functools.partial being applied to a given
function. Allows access to the decorated 'return' attribute whether or not
it is also a partial function
Args:
aggregate_function (callable) Either a raw function or a... | bigcode/self-oss-instruct-sc2-concepts |
def to_rgba_array(arr):
"""
Convert 2D integer values to RGBA tuples .
Parameters
----------
arr: array of input values to split into rgba, will be cast to uint32
Returns
-------
array of RGBA tuples: [[[R, G, B, A] ...]] (uint8)
"""
# from: http://stackoverflow.com/questio... | bigcode/self-oss-instruct-sc2-concepts |
def str_fill(i, n):
"""Returns i as a string with at least n digits.
i: int
n: int length
returns: string
"""
return str(i).zfill(n) | bigcode/self-oss-instruct-sc2-concepts |
def is_valid_input(ext):
""" Checks if input file format is compatible with Open Babel """
formats = ["dat", "ent", "fa", "fasta", "gro", "inp", "log", "mcif", "mdl", "mmcif", "mol", "mol2", "pdb", "pdbqt", "png", "sdf", "smi", "smiles", "txt", "xml", "xtc"]
return ext in formats | bigcode/self-oss-instruct-sc2-concepts |
def get_exit_code(matches):
""" Determine exit code """
exit_code = 0
for match in matches:
if match.rule.id[0] == 'W':
exit_code = exit_code | 4
elif match.rule.id[0] == 'E':
exit_code = exit_code | 2
return exit_code | bigcode/self-oss-instruct-sc2-concepts |
def computa_menor_tamanho_lista(lista_de_listas):
"""
Recebe uma lista de listas e retorna o tamanho da menor lista
"""
menor_lista = len(lista_de_listas[0])
for lista in lista_de_listas:
if(len(lista) < menor_lista):
menor_lista = len(lista)
return menor_lista | bigcode/self-oss-instruct-sc2-concepts |
def parseBrowserBase(base_config):
""" Parses the given option value into type and base url
@param base_config: The option value
@type base_config: C{str}
@return: The type and the base url
@rtype: C{tuple}
"""
if base_config:
tokens = base_config.split(None, 1)
... | bigcode/self-oss-instruct-sc2-concepts |
def is_voiced(sound):
"""
Check if a sound is voiced or not.
"""
if sound.obj.phonation == "voiced" or sound.obj.breathiness or sound.obj.voicing:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def get_ratio_served(solution):
"""Returns the ratio of users that have been assigned a video representation.
"""
nserved = 0
for u in solution["users"]:
if "mos" in u:
nserved += 1
return nserved/len(solution["users"]) | bigcode/self-oss-instruct-sc2-concepts |
def is_form_post(environ):
"""Determine whether the request is a POSTed html form"""
content_type = environ.get('CONTENT_TYPE', '').lower()
if ';' in content_type:
content_type = content_type.split(';', 1)[0]
return content_type in ('application/x-www-form-urlencoded',
... | bigcode/self-oss-instruct-sc2-concepts |
def find_cmd0(cmd_stream, cmd) -> int:
"""Returns parameter of the first command in the stream that matches the given command"""
for command in cmd_stream:
if (command & 0xFFFF) == cmd.value:
return (command >> 16) & 0xFFFF
assert False, f"Not in command stream: {cmd}" | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
import re
def parse_header_links(links_header: str) -> Dict[str, Dict[str, str]]:
"""
Parse a "Link" header from an HTTP response into a `dict` of the form::
{"next": {"url": "...", "rel": "next"}, "last": { ... }}
"""
# <https://git.io/JcYZi>
links: Dict[str, Dict... | bigcode/self-oss-instruct-sc2-concepts |
def filter_pattern_group(note_begin_pattern, note_end_pattern, note_metronome_group, note_end_metronome_group):
"""
The pattern group from dataset contains all notes. This filters it to only notes present in the new map
"""
for i,p in enumerate(note_begin_pattern):
if i not in note_metronome_gro... | bigcode/self-oss-instruct-sc2-concepts |
def is_numeric(series, max_unique=16):
"""Flag if series is numeric."""
if len(set(series.values[:3000])) > max_unique:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def substrings_of_length(length, string):
"""
Given a string, return a list of all substrings of that string with a given
length.
For example, substrings_of_len(2, "ABC") returns ["AB", "BC"].
"""
# You could also use a generator here, but I don't want to overcomplicate
# things.
substrings = []
for ... | bigcode/self-oss-instruct-sc2-concepts |
def get_cfg_var(interp, var):
""" Gets the value of a PHP configuration option"""
w_value = interp.config.get_ini_w(var)
if w_value is None:
return interp.space.w_False
return w_value | bigcode/self-oss-instruct-sc2-concepts |
def rank_features(explanation):
""" Given an explanation of type (name, value) provide the ranked list of feature names according to importance
Parameters
----------
explanation : list
Returns
----------
List contained ranked feature names
"""
ordered_tuples = sorted(explanation, ... | bigcode/self-oss-instruct-sc2-concepts |
def _JoinWithOr(strings):
"""Joins strings, for example, into a string like 'A or B' or 'A, B, or C'."""
if not strings:
return ''
elif len(strings) == 1:
return strings[0]
elif len(strings) == 2:
return strings[0] + ' or ' + strings[1]
else:
return ', '.join(strings[:-1]) + ', or ' + strings[... | bigcode/self-oss-instruct-sc2-concepts |
def convert_coco_category(category_id):
"""
Convert continuous coco class id to discontinuous coco category id (0..79 --> 0..90)
"""
match = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 13, 14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 27, 28, 31, 32, 33, 34,
35, 36, 37, ... | bigcode/self-oss-instruct-sc2-concepts |
def stringToInt(message):
"""
Convert input string message into an integer
"""
string_to_binary = message.encode('utf8')
return int.from_bytes(string_to_binary, byteorder='big', signed=False) | bigcode/self-oss-instruct-sc2-concepts |
def Arn(key):
"""Get the Arn attribute of the given template resource"""
return { 'Fn::GetAtt': [key, 'Arn']} | bigcode/self-oss-instruct-sc2-concepts |
from typing import Type
from typing import Set
def _all_subclasses_of(cls: Type) -> Set[Type]:
"""
All subclasses of cls, including non-direct ones (child of child of ...).
"""
direct_subclasses = set(cls.__subclasses__())
return direct_subclasses.union(
s for d in direct_subclasses for s ... | bigcode/self-oss-instruct-sc2-concepts |
def HandleNearestNeighborQuery(locale_finder, lat, lon):
"""Verifies passed arguments and issues a nearest neighbor lookup.
Args:
lat (float): Latitude of interest.
lon (float): Longitude of interest.
Raises:
SyntaxError: If expected parameters are not provided (are None).
Ret... | bigcode/self-oss-instruct-sc2-concepts |
def choose_condition(data, events, condition):
"""Filters out a specific condition from the data.
:param data: data from which to extract conditions from
:type data: numpy array
:param events: event data of shape [trials x 4]
:type events: numpy array
:param condition: Condition to be filtered ... | bigcode/self-oss-instruct-sc2-concepts |
def get_attributes(obj):
"""
Returns all attributes of an object, excluding those that start with
an underscore.
Args:
obj: the object
Returns:
A dictionary of attributes
"""
return {
key: getattr(obj, key) if not key.startswith("_") else None
for key in di... | bigcode/self-oss-instruct-sc2-concepts |
import functools
import operator
def product(xs):
"""
product :: Num a => [a] -> a
The product function computes the product of a finite list of numbers.
"""
return functools.reduce(operator.mul, xs, 1) | bigcode/self-oss-instruct-sc2-concepts |
def in_slots(obj, key, default=False):
"""
Returns true if key exists in obj.__slots__; false if not in.
If obj.__slots__ is absent, return default
"""
return (key in obj.__slots__) if getattr(obj, '__slots__', None) else default | bigcode/self-oss-instruct-sc2-concepts |
def get_color(node, color_map):
"""
Gets a color for a node from the color map
Parameters
--------------
node
Node
color_map
Color map
"""
if node in color_map:
return color_map[node]
return "black" | bigcode/self-oss-instruct-sc2-concepts |
def format_rp_labels(rp_label: str) -> str:
""" Helper function for formatting the RP label.
Args:
rp_label: Reaction plane orientation label to be formatted.
Returns:
Properly formatted RP label.
"""
# Replace "_" with "-"
return rp_label.replace("_", "-").capitalize() | bigcode/self-oss-instruct-sc2-concepts |
def pad_sentence_batch(sentence_batch, pad_int):
"""Pad sentences with <PAD> so that each sentence of a batch has the same length"""
max_sentence = max([len(sentence) for sentence in sentence_batch])
return [sentence + [pad_int] * (max_sentence - len(sentence)) for sentence in sentence_batch] | bigcode/self-oss-instruct-sc2-concepts |
def check_is_video(file_name):
"""
Ensures passed file inputs are of recognized
media format.
"""
formats = ['flv', 'mp4', 'avi', 'mp3', 'flaac']
return any([extension for extension in
formats if file_name.endswith(extension)]) | bigcode/self-oss-instruct-sc2-concepts |
def FOREVER(*_, **__):
"""Will always return False (continue)."""
return False | bigcode/self-oss-instruct-sc2-concepts |
def c(field):
"""Remove " from field"""
return field.replace('"', "") | bigcode/self-oss-instruct-sc2-concepts |
def find(strng, ch):
"""
Find and return the index of ch in strng.
Return -1 if ch does not occur in strng.
"""
ix = 0
while ix < len(strng):
if strng[ix] == ch:
return ix
ix += 1
return -1 | bigcode/self-oss-instruct-sc2-concepts |
def wrap(seq, bases=60):
"""
Print wrapped sequence.
Args:
seq (str): Nucleotide sequence
bases (int): Number of bases to include on each line.
"""
count = 0
ret = ''
for i in seq:
if count >= bases:
ret = ret + '\n'
count = 0
ret = re... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def is_shutdown_time_int(hour: Any, minute: Any) -> bool:
"""Check if shutdown time are numbers.
Args:
hour (Any): hour according to user config
minute (Any): minute according to user config
Returns:
bool: True if both are numbers
"""
return type(h... | bigcode/self-oss-instruct-sc2-concepts |
def transform_fs_access_output(result):
""" Transform to convert SDK output into a form that is more readily
usable by the CLI and tools such as jpterm. """
new_result = {}
useful_keys = ['acl', 'group', 'owner', 'permissions']
for key in useful_keys:
new_result[key] = result[key]
retur... | bigcode/self-oss-instruct-sc2-concepts |
import numbers
def validate_int(x, name, minimum=None, maximum=None) -> int:
"""Validate integer function parameters.
Parameters
----------
x : object
Object to validate as an int.
name : str
Name of the function parameter.
minimum : int, optional
Minimum value x can t... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_columns_matching(dataframe, pattern, regex=False):
"""
Returns the columns containing pattern (or satisfying the regex pattern, if regex=True).
:param dataframe: Dataframe whose columns are being tested
:param pattern: String to test columns for
:param regex: If True, then check... | bigcode/self-oss-instruct-sc2-concepts |
def isinAngleLimits(angle, min_angle, max_angle):
"""Check if an angle value is between min and max angles in degrees"""
if (min_angle <= angle <= max_angle) or (min_angle <= 180 - angle <= max_angle):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def say_hello(name: str) -> str:
"""
Greet someone in English.
:param name:
Name of the person to greet.
:return:
The greeting.
"""
return f"Hello {name}!" | bigcode/self-oss-instruct-sc2-concepts |
def replace(s: str):
"""
Replace blank to "%20".
Parameters
----------
s: str
given string
Returns
-------
out: str
return string
"""
if not s:
return s
num_blank = 0
for i in s:
if i == " ":
num_blank += 1
raw_len = len(s... | bigcode/self-oss-instruct-sc2-concepts |
def is_same_domain(host, pattern):
"""
Return ``True`` if the host is either an exact match or a match
to the wildcard pattern.
Any pattern beginning with a period matches a domain and all of its
subdomains. (e.g. ``.example.com`` matches ``example.com`` and
``foo.example.com``). Anything else ... | bigcode/self-oss-instruct-sc2-concepts |
def is_float(s):
"""
:param s: s is a string
:return: True if string s can be cast to a float
"""
try:
x = float(s)
return True
except:
return False | bigcode/self-oss-instruct-sc2-concepts |
def get_type( type_name ):
"""Return the type of the given node type string (without *? modifier)."""
if type_name[ -1 ] == '*' or type_name[ -1 ] == '?':
return type_name[ : -1 ]
return type_name | bigcode/self-oss-instruct-sc2-concepts |
def char_age(p0=1.0, p1=1e-12):
"""
Accepts a spin period (in s) and spin period derivative (in s/s) and
returns the characteristic age. Units: years.
"""
tau = p0 / (2 * p1)
return tau / (60 * 60 * 24 * 365) | bigcode/self-oss-instruct-sc2-concepts |
def check_dermoscopic(meta):
"""Checking if a image is acquired through dermoscopy by ISIC's API.
Parameter:
meta: The metadata of the image getting through the API
Return:
True if the image is acquired through dermoscopy, False if it isn't
"""
if "image_type" not in meta["meta"]["acquisiti... | bigcode/self-oss-instruct-sc2-concepts |
def tuple_mul(tuple_item, num):
"""Perform element-wise multiplication by a scaler for a tuple or a number."""
if not isinstance(tuple_item, tuple):
return tuple_item * num
List = []
for item in tuple_item:
if item is not None:
List.append(item * num)
else:
... | bigcode/self-oss-instruct-sc2-concepts |
def _clean_job(job):
"""Remove and key/value pairs from job where the key is prefixed by an
underscore.
Args:
job (JobState): The job to clean.
Returns:
JobState with all underscore-prefixed keys removed.
"""
for key in job.keys():
if key.startswith('_'):
job.... | bigcode/self-oss-instruct-sc2-concepts |
def _tensor_to_list_of_channel_tensors(img):
"""Converts a tensor with dimensions of HWC or BHWC to a list of channels."""
if len(img.shape) == 3: # HWC.
img_list = [img[:, :, c] for c in range(img.shape[-1])]
elif len(img.shape) == 4: # BHWC.
img_list = [img[:, :, :, c] for c in range(img.shape[-1])]
... | bigcode/self-oss-instruct-sc2-concepts |
def name_without_commas(name):
"""
Takes a name formatted as "[LastNames], [FirstNames]"
and returns it formatted as "[FirstNames] [LastNames]".
If a name without commas is passed it is returned unchanged.
"""
if name and "," in name:
name_parts = name.split(",")
if len(name_pa... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def methodName() -> str:
"""Returns string containing name of the calling method."""
return inspect.stack()[1][3] | bigcode/self-oss-instruct-sc2-concepts |
def _dirname_map_fn(f):
"""Returns the dir name of a file.
This function is intended to be used as a mapping function for file passed into `Args.add`.
Args:
f: The file.
Returns:
The dirname of the file.
"""
return f.dirname | bigcode/self-oss-instruct-sc2-concepts |
def indent(string, prefix=' '):
"""
Indent every line of this string.
"""
return ''.join('%s%s\n' % (prefix, s) for s in string.split('\n')) | bigcode/self-oss-instruct-sc2-concepts |
import re
def interpret_cv(cv_index, settings):
"""
Read the cv_index'th CV from settings.cvs, identify its type (distance, angle, dihedral, or differance-of-distances)
and the atom indices the define it (one-indexed) and return these.
This function is designed for use in the umbrella_sampling jobtyp... | bigcode/self-oss-instruct-sc2-concepts |
def _parent_dirs(dirs):
"""Returns a set of parent directories for each directory in dirs."""
return set([f.rpartition("/")[0] for f in dirs]) | bigcode/self-oss-instruct-sc2-concepts |
import textwrap
def wrap(s):
"""
Wrap lines of text, retaining existing newlines as
paragraph markers.
>>> print(wrap(lorem_ipsum))
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nos... | bigcode/self-oss-instruct-sc2-concepts |
def is_string(data):
"""Utility method to see if data is a string."""
return isinstance(data, str) | bigcode/self-oss-instruct-sc2-concepts |
def convert_cache_variables(cache_json: list) -> dict:
"""
Convert list of cache variables returned by server to dictonary without unnecessary information.
cache_json is 'cache' object from response to 'cache' request.
"""
return dict((entry['key'], entry['value']) for entry in cache_json) | bigcode/self-oss-instruct-sc2-concepts |
def sort_dict_by_value(d):
""" Returns the keys of dictionary d sorted by their values """
items=list(d.items())
backitems=[[v[1],v[0]] for v in items]
backitems.sort()
return [backitems[i][1] for i in range(0, len(backitems))] | bigcode/self-oss-instruct-sc2-concepts |
def e(d):
"""Encode the given string instance using UTF-8."""
return d.encode('UTF-8') | bigcode/self-oss-instruct-sc2-concepts |
def _pretty_state_identifier(state):
""" returns 'off' for False and 'on' for True """
if state:
return 'on'
else:
return 'off' | bigcode/self-oss-instruct-sc2-concepts |
def task_list_item_list_description(data, singular, plural):
"""
Returns a description for a task list item depending on how many
items are in its contents
"""
if len(data) == 0:
return None
elif len(data) == 1:
return f"1 {singular} added"
else:
return f"{len(data)} ... | 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.