seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def gFont(fontname="Times", fontsize=12, fontface='normal'):
""" Returns a font specification to use with the draw text routines
fontname must be a string, fontsize and integer
fontface is also a string normal, bold or italic; for bold and italic,
make fontface "bold italic"
"""
ret... | bigcode/self-oss-instruct-sc2-concepts |
def Get_FigWidth_Inches(FigSizeFormat="default"):
"""
This function gets the figure width in inches for different formats
Args:
FigSizeFormat: the figure size format according to journal for which the figure is intended
values are geomorphology,ESURF, ESPL, EPSL, JGR, big
de... | bigcode/self-oss-instruct-sc2-concepts |
def acrostic(items):
"""
Take the acrostic of a list of words -- the first letter of each word.
"""
return ''.join([item[0] for item in items]) | bigcode/self-oss-instruct-sc2-concepts |
def mean_soft_prediction(y_true, y_score):
"""Compute the mean predicted probability."""
return y_score.mean() | bigcode/self-oss-instruct-sc2-concepts |
def _get_file_name_from_uri(uri):
"""Gets filename from URI
Args:
uri (str): URI
"""
return uri.split("/")[-1] | bigcode/self-oss-instruct-sc2-concepts |
def copy_state_dict(state_dict_1, state_dict_2):
"""Manual copy of state dict.
Why ? Because when copying a state dict to another with load_state_dict, the values of weight are copied only
when keys are the same in both state_dict, even if strict=False.
"""
state1_keys = list(state_dict_1.keys())
... | bigcode/self-oss-instruct-sc2-concepts |
def get_status_code(status,short = False):
"""Converts status code phrase to a simplified code if it isn't already simplified.
Examples: 'Registered' => 'R' or 'Web Drop' => 'DROP'
"""
if short:
status_codes = {'Registered': 'R','Web Registered': 'R','(Add(ed) to Waitlist)': 'WL', 'Web Drop'... | bigcode/self-oss-instruct-sc2-concepts |
def is_repo_image(image):
"""
Checks whether the given image has a name, i.e. is a repository image. This does not imply that it is
assigned to an external repository.
:param image: Image structure from the Docker Remote API.
:type image: dict
:return: ``False`` if the only image name and tag i... | bigcode/self-oss-instruct-sc2-concepts |
def summary_example(field):
"""Returns an example of a value in the summary of the field
"""
distribution_keys = ["categories", "counts", "bins", "tag_cloud", "items"]
for key in distribution_keys:
if key in field["summary"]:
return repr(field["summary"][key][0][0]) | bigcode/self-oss-instruct-sc2-concepts |
def hp_state_english(raw_table, base_index):
""" Convert HP state to English """
value = raw_table[base_index]
if value == 0:
return "Stop"
if value == 1:
return "Heating mode"
if value == 2:
return "Heating mode+comp"
if value == 4:
return "Cooling mode"
if ... | bigcode/self-oss-instruct-sc2-concepts |
def disjoint(L1, L2):
"""returns non-zero if L1 and L2 have no common elements"""
used = dict([(k, None) for k in L1])
for k in L2:
if k in used:
return 0
return 1 | bigcode/self-oss-instruct-sc2-concepts |
def exclude(ex1, ex2):
"""Return the number on the interval [1,3] that is neither ex1 nor ex2
Parameters
----------
ex1 : int
The first number to exclude (1, 2 or 3)
ex2 : int
The second number to exclude (1, 2 or 3)
Returns
-------
int
The number (1, 2 or 3) no... | bigcode/self-oss-instruct-sc2-concepts |
def build_texts_from_keens(keens):
"""
Collects available text from keens in a list and returns it
:param keens: dict of iid: keen_iid
:return: texts: dict of iid: list of strings with text collected from each keen.
The title of the keen is always in the first position of the list
"""
texts ... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_hounsfield_unit_parameterless(mu):
"""
Given linear attenuation coefficients the function calculates the corresponding Hounsfield units.
:param mu: Attenuation coefficient to determine corresponding Hounsfield unit.
:return: Hounsfield unit corresponding to mu
"""
HU = mu * 65536-... | bigcode/self-oss-instruct-sc2-concepts |
def dot(v1, v2):
"""Returns dot product of v1 and v2 """
assert len(v1) == len(v2), 'Vector dimensions should be equal'
return sum(p * q for p, q in zip(v1, v2)) | bigcode/self-oss-instruct-sc2-concepts |
def set_cell(sudoku, y, x, value):
""" Sets the current cell to the input value
"""
sudoku[y][x] = value
return sudoku | bigcode/self-oss-instruct-sc2-concepts |
def ema(s, n):
"""
returns an n period exponential moving average for
the time series s
s is a list ordered from oldest (index 0) to most
recent (index -1)
n is an integer
returns a numeric array of the exponential
moving average
"""
ema = []
j = 1
#get n sma first and... | bigcode/self-oss-instruct-sc2-concepts |
def categorize_transcript_recovery(info):
"""
full --- means that every exon in the tID was covered!
fused --- full, but assembled exon match start > 0, meaning
likely fusion of overlapped transcripts
5missX --- means that the assembled one is missing beginning X exons
3missY --- means... | bigcode/self-oss-instruct-sc2-concepts |
def purge_duplicates(list_in):
"""Remove duplicates from list while preserving order.
Parameters
----------
list_in: Iterable
Returns
-------
list
List of first occurences in order
"""
_list = []
for item in list_in:
if item not in _list:
_list.appen... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def read_yaml_file(filepath):
"""Return contents of a yaml file.
Parameters
----------
filepath : string
The full path to the yaml file.
Returns
-------
list of dictionaries
The contents of the yaml file where each dictionary corresponds
to a line in t... | bigcode/self-oss-instruct-sc2-concepts |
def _surf70(phi1, phi2, phi3, phi4):
"""Compute area of a south fire trapeze
Parameters
----------
phi1 : float
Level-set at south west point
phi2 : float
Level-set at south east point
phi3 : float
Level-set at north east point
phi4 : float
Level-set at north... | bigcode/self-oss-instruct-sc2-concepts |
def hparams_frames_per_second(hparams):
"""Compute frames per second as a function of HParams."""
return hparams.sample_rate / hparams.spec_hop_length | bigcode/self-oss-instruct-sc2-concepts |
import json
def translate_classes(classes, json_file):
"""
Convert torch model outputs to human-readable categories
Parameters
----------
classes : array-like
Numerical class output of the neural network
json_file : str
Path to json file with category/class mapping
Return... | bigcode/self-oss-instruct-sc2-concepts |
def recall_score(true_entities, pred_entities):
"""Compute the recall."""
nb_correct = len(true_entities & pred_entities)
nb_true = len(true_entities)
score = nb_correct / nb_true if nb_true > 0 else 0
return score | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Tuple
from typing import Optional
def has_winner(field: List[List[int]]) -> Tuple[bool, Optional[Tuple[int, int]], Optional[Tuple[int, int]]]:
"""
Checks game for winning (or tie) positions
:param field: playing field matrix
:return: Overall answer & position... | bigcode/self-oss-instruct-sc2-concepts |
def likely_inchi_match(inchi_1, inchi_2, min_agreement=3):
"""Try to match defective inchi to non-defective ones.
Compares inchi parts seperately. Match is found if at least the first 'min_agreement' parts
are a good enough match.
The main 'defects' this method accounts for are missing '-' in the inchi.... | bigcode/self-oss-instruct-sc2-concepts |
def masked_status_eq(masked_status):
""" Returns a function that matches to the masked status. """
return lambda m: m.get_masked_status() == masked_status | bigcode/self-oss-instruct-sc2-concepts |
def translate_matrix(m, v):
"""Translates a matrix by (x, y)."""
(a, b, c, d, e, f) = m
(x, y) = v
return (a, b, c, d, x * a + y * c + e, x * b + y * d + f) | bigcode/self-oss-instruct-sc2-concepts |
def credential_exist(cls,site_name):
"""
method that checks if a credential account exists from the credential list
Args:
site_name: Site_name to search if it exists
Returns:
Boolean: True or false depending if the credential exists
"""
for credential in cls.credentials_list:
if ... | bigcode/self-oss-instruct-sc2-concepts |
import math
def _compute_output_resolution(input_spatial_resolution, kernel_size, stride,
total_padding):
"""Computes output resolution, given input resolution and layer parameters.
Note that this computation is done only over one dimension (eg, x or y).
If any of the inputs is N... | bigcode/self-oss-instruct-sc2-concepts |
import re
def check_password(passw):
"""Checks if password is strong (at least 8 characters, both upper
and lowercase letters, at least one digit) using regex."""
lowre = re.compile(r'[a-z]+')
upre = re.compile(r'[A-Z]+')
digre = re.compile(r'\d+')
if lowre.search(passw) and upre.search(passw) and digre.searc... | bigcode/self-oss-instruct-sc2-concepts |
def tag_data(df, tag, var='auto_tag'):
"""Return data with specified tag."""
return df[df[var].eq(tag)] | bigcode/self-oss-instruct-sc2-concepts |
import torch
def bool_to_strings(bool_data):
"""Convert a vector of [True, False, False, True, ...] to '1001...' ."""
def conversion(entry):
if isinstance(bool_data, torch.Tensor):
entry = entry.item()
return str(int(entry))
mapping = map(conversion, bool_data)
return ''.j... | bigcode/self-oss-instruct-sc2-concepts |
def file_to_list(filename,skip='#'):
"""
Read the filename and append all the lines that do not start
with the skip string, to a list.
Args:
filename (str): name of the file
skip (str): first elements of the skipped lines
"""
lines = []
with open(filename) as f:
for ... | bigcode/self-oss-instruct-sc2-concepts |
def Substarction(matrix_1, matrix_2): # вычитание
"""
Функция, которая вычитает две матрицы
:params matrix_1: матрица, уменьшаемое
:params matrix_2: матрица, вычитаемое
:return matrix_out: матрица, разность
"""
matrix_out = []
for i in range(len(matrix_1)):
if (len(... | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
import json
def json_to_ordered_dict(file):
"""
Reads a timeline.json file output by Tensorflow/libcupti and returns and OrderedDict object
:param file: .json file.
:return: OrderedDict
"""
with open(file, mode='r') as f:
def _as_ordered_dict(val):
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def invert_pose(T01):
"""Invert homogeneous matrix as a rigid transformation
T^-1 = [R^T | -R^T * t]
Parameters
----------
T01: torch.FloatTensor (B44)
Input batch of transformation tensors.
Returns
----------
T10: torch.FloatTensor (B44)
Inverted batc... | bigcode/self-oss-instruct-sc2-concepts |
def data(reader, chunk=100):
"""Creates a pandas DataFrame that is a subset of the entire file
based on chunk
Parameters
----------
reader : pd.DataFrame
A pandas.DataFrame, use grab_files.reader
chunk : int
The number of rows to grab in the first chunk.
Future versions ... | bigcode/self-oss-instruct-sc2-concepts |
def split_path(path):
"""Split a path into a list of path components."""
return path.split('/') | bigcode/self-oss-instruct-sc2-concepts |
def join(seq, separator=","):
"""
Description
----------
Concatenate all values in a sequence into a string separated by the separator value.
Parameters
----------
seq : (list or tuple) - sequence of values to concatenate\n
separator : any, optional - value to separate the values in the... | bigcode/self-oss-instruct-sc2-concepts |
def removeNonAsciiChars(str_in):
"""Remove all non-ascii characters in the string"""
if str_in is None:
return ""
return str_in.encode("ascii", "ignore").decode() | bigcode/self-oss-instruct-sc2-concepts |
def splitStringIntoChunks( string, length=25 ):
"""
Split string into chunks of defined size
"""
if len(string) <= length:
return [ string ]
else:
return [ string[ 0+i : length+i ] \
for i in range( 0, len( string ), length ) ] | bigcode/self-oss-instruct-sc2-concepts |
def setify(diff_list):
"""Take a list of lists and make it a set of tuples."""
s = set()
for diff in diff_list:
s.add(tuple(diff))
return s | bigcode/self-oss-instruct-sc2-concepts |
import codecs
def read_only_relations_into_set(inpath):
"""
Only read the relation of a given relation dataset into a set.
Args:
inpath (str): Path to relation dataset.
Returns:
set: Set of dataset relation types.
"""
relations = set()
with codecs.open(inpath, 'rb', 'utf-8') as infile:
line = infile.r... | bigcode/self-oss-instruct-sc2-concepts |
def get_uuid(connection):
"""Retreive UUID from OVN DB connection JSON."""
return connection["_uuid"][1] | bigcode/self-oss-instruct-sc2-concepts |
def parse_fs_statsfile(statsfile):
"""opens a fs generated stats file and returns
a dict of roi keys with [mean, std, nvox], for
each roi
"""
roidict = {}
for line in open(statsfile):
if line[0] == '#':
continue
tmp = line.split()
roi = tmp[4]
mean = e... | bigcode/self-oss-instruct-sc2-concepts |
def _prod(op1, op2):
"""Product of two operators, allowing for one of them to be None."""
if op1 is None or op2 is None:
return None
else:
return op1 * op2 | bigcode/self-oss-instruct-sc2-concepts |
def _format_83(f):
"""Format a single float into a string of width 8, with ideally 3 decimal
places of precision. If the number is a little too large, we can
gracefully degrade the precision by lopping off some of the decimal
places. If it's much too large, we throw a ValueError"""
if -999.999 < f <... | bigcode/self-oss-instruct-sc2-concepts |
def is_subset(list1, list2):
"""Returns true if list 1 is a subset of list 2
(assumes neither list has any repeats)
"""
for item in list1:
if not item in list2:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def get_args(frame):
"""Gets dictionary of arguments and their values for a function
Frame should be assigned as follows in the function itself: frame = inspect.currentframe()
"""
args, _, _, values = inspect.getargvalues(frame)
return dict((key, value) for key, value in values.ite... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_valid_filename(s: str) -> str:
"""Returns a valid filename given an input. Removes any characters unable to be in a filename"""
s = str(s).strip()
return re.sub(r'(?u)[^-\w.\[\]()\' ]', '', s) | bigcode/self-oss-instruct-sc2-concepts |
def single(value, dice):
"""
Score the dice based on a single value (1-6).
"""
points = 0
for die in dice:
if die == value:
points += value
return points | bigcode/self-oss-instruct-sc2-concepts |
def get_descendant_by_address(tree_node, relative_address):
"""
Get the descendant node with given address relative to the given tree node.
A relative address with respect to a tree node is a list of successive children to traverse to reach the desired
descendant. For example:
[0] is the address o... | bigcode/self-oss-instruct-sc2-concepts |
def getDateTimeByName(entity, name):
"""Returns the DateTime property with the given name.
Args:
entity: Instance of a timeline model.
name: The name of a specific property in the given timeline model.
Returns:
The requested DateTime property, or None if there is no such property set.
"""
if h... | bigcode/self-oss-instruct-sc2-concepts |
def max_divide(a: int, b: int) -> int:
"""
Returns a after dividing it with the greatest possible power of b.
>>> max_divide(729,3)
1
>>> max_divide(7543,2)
7543
>>> max_divide(486,3)
2
"""
while a % b == 0:
a //= b
return a | bigcode/self-oss-instruct-sc2-concepts |
def is_magic(name: str) -> bool:
"""Check magic name."""
name = name.rsplit('.', maxsplit=1)[-1]
return name[:2] == name[-2:] == '__' | bigcode/self-oss-instruct-sc2-concepts |
import re
def trim_xml_html_tags(data_str):
"""
Trim all HTML/XML tags and replace the special "panel" tag with a new line
:param data_str: input data string to trim
:return: Trimmed string
>>> trim_xml_html_tags('')
''
>>> trim_xml_html_tags(u'')
''
>>> trim_xml_html_tags(u'hello... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def _transport_data(t):
"""Return data from "transport = data".
Transport 'file' returns a transfer directory (defaulting to
'$HOME/.CONSTELLATION/REST'.
Transport 'sftp' returns a hostname, directory tuple; the directory
defaults to '.CONSTELLATION/REST'."""
ix = t.... | bigcode/self-oss-instruct-sc2-concepts |
def nextf(f, offset=1):
"""Next token has feature f"""
def feature(s, i):
i += offset
return i < len(s) and f(s, i)
return feature | bigcode/self-oss-instruct-sc2-concepts |
def sint16_to_int(bytes):
"""
Convert a signed 16-bit integer to integer
:param bytes:
:return:
"""
return int.from_bytes(bytes, byteorder='little', signed=True) | bigcode/self-oss-instruct-sc2-concepts |
def is_valid_tour(nodes, num_nodes):
"""Sanity check: tour visits all nodes given.
"""
return sorted(nodes) == [i for i in range(num_nodes)] | bigcode/self-oss-instruct-sc2-concepts |
def sorted_by_key(x, i, reverse=False):
"""For a list of lists/tuples, return list sorted by the ith
component of the list/tuple, E.g.
Sort on first entry of tuple:
> sorted_by_key([(1, 2), (5, 1]), 0)
>>> [(1, 2), (5, 1)]
Sort on second entry of tuple:
> sorted_by_key([(1, 2), (5,... | bigcode/self-oss-instruct-sc2-concepts |
import re
def exact_match_regex(name):
""" Convert string to a regex representing an exact match """
return '^%s$' % re.escape(name or '') | bigcode/self-oss-instruct-sc2-concepts |
def create_attribute_filter(attribute_name: str, values: list) -> dict:
"""
Create a categorical attribute filter to be used in a trace filter sequence.
Args:
attribute_name:
A string denoting the name of the attribute.
values:
A list of values to be filtered.
R... | bigcode/self-oss-instruct-sc2-concepts |
def sort_key(attrs, node):
"""
Sort key for sorting lists of nodes.
"""
acc = 0
for i in range(len(attrs)):
if attrs[i] in node.attrs:
acc += 10**i
return acc | bigcode/self-oss-instruct-sc2-concepts |
def get_test_response(client, method, params):
"""
Test the integration connection state
:param client: instance of client to communicate with server
:param method: Requests method to be used
:param params: Parameters for requests
:return: Test Response Success or Failure
"""
ret_val = '... | bigcode/self-oss-instruct-sc2-concepts |
import re
def escape_string(string):
"""
Escape URL-acceptable regex special-characters.
"""
return re.sub('([.+*?=^!:${}()[\\]|])', r'\\\1', string) | bigcode/self-oss-instruct-sc2-concepts |
import time
def utc_mktime(utc_tuple):
"""Returns number of seconds elapsed since epoch
Note that no timezone are taken into consideration.
utc tuple must be: (year, month, day, hour, minute, second)
"""
if len(utc_tuple) == 6:
utc_tuple += (0, 0, 0)
return time.mktime(utc_tuple) - tim... | bigcode/self-oss-instruct-sc2-concepts |
def instance_group(group_type, instance_type, instance_count, name=None):
"""
Construct instance group
:param group_type: instance group type
:type group_type: ENUM {'Master', 'Core', 'Task'}
:param instance_type
:type instance_type: ENUM {'g.small', 'c.large', 'm.medium', 's.medium', 'c.2xlar... | bigcode/self-oss-instruct-sc2-concepts |
def hasextension(fname):
"""Check if a filename has an extension"""
return fname.find('.')!=-1 | bigcode/self-oss-instruct-sc2-concepts |
def get_file_text(file_path):
"""
Get the text stored in a file in a unique string (without parsing)
:param file_path: str
:return: str
"""
try:
with open(file_path, 'r') as open_file:
lines = open_file.read()
except Exception:
return list()
return lines | bigcode/self-oss-instruct-sc2-concepts |
def _get_task_file_name(task):
"""Returns the file name of the compile task. Eg: ${issue}-${patchset}.json"""
return '%s-%s-%s.json' % (task['lunch_target'], task['issue'],
task['patchset']) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def load_checkpoint(checkpoint_path: str):
"""
Loads a model checkpoint with the model on CPU and in eval mode.
:param checkpoint_path: Path to model checkpoint to load.
:return: Returns a tuple with the model, optimizer, epoch number, iteration number, and auc@0.05 of the loaded model.
... | bigcode/self-oss-instruct-sc2-concepts |
def getPdbOccupancy(a):
""" return pdb atom occupancy"""
try:
return float(a[60:67])
except:
return 0.0 | bigcode/self-oss-instruct-sc2-concepts |
import codecs
def read_voca_file(file_path):
"""
Read vocabulary file
:param file_path: The path of vocabulary file
:return: vocabulary list
"""
vocas = list()
with codecs.open(file_path, "r", "utf-8") as voca_file:
for each_line in voca_file:
vocas.append(each_line.st... | bigcode/self-oss-instruct-sc2-concepts |
def MichaelisMenten(S, E0, k, K):
"""Definition for Michaelis Menten reaction with inputs E0 [mM], k [1/s] and K [mM]"""
return (-k*E0*S[0]/(K+S[0]), ) | bigcode/self-oss-instruct-sc2-concepts |
def memoprop(f):
"""
Memoized property.
When the property is accessed for the first time, the return value
is stored and that value is given on subsequent calls. The memoized
value can be cleared by calling 'del prop', where prop is the name
of the property.
"""
fname = f.__name__
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def _convert_params_to_array(params: dict) -> Union[dict, list]:
"""Convert a dictionary to a list of key-value pairs, unpacking
list values to their own keys. If none of the values are a list,
returns the dictionary untouched.
"""
if not any(isinstance(v, list) for v in p... | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_header(line):
"""true if we are in a header"""
if re.match('^@',line):
f = line.rstrip().split("\t")
if(len(f) > 9):
return False
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def get_docker_job_options(job_options: dict) -> dict:
"""
Returns Docker-specific job options from general job options.
"""
keys = ["volumes", "interactive"]
return {key: job_options[key] for key in keys if key in job_options} | bigcode/self-oss-instruct-sc2-concepts |
def last_occurrence_index(l, val, before_index=None):
"""
Find the last occurrence of some value, before_index will
not be included in the possible return value
:param l:
:param val: value to look for
:param before_index: exclusive ending of the range
:return: zero-based index
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def calc_flux(
energy,
attenuation=1.0,
photon_energy=9,
T_lenses=0.586,
T_apperture=0.75,
T_air=0.39,
):
""" "Calculate the photon flux at MID
Args:
energy (float): pulse energy in micro Joule.
attenuation (float, optional): attenuation factor through absorbers.
... | bigcode/self-oss-instruct-sc2-concepts |
def is_quoted(value):
"""
Return a single or double quote, if a string is wrapped in extra quotes.
Otherwise return an empty string.
"""
ret = ""
if (
isinstance(value, str)
and value[0] == value[-1]
and value.startswith(("'", '"'))
):
ret = value[0]
retur... | bigcode/self-oss-instruct-sc2-concepts |
def progress_bar(completed, total, step=5):
""" Function returning a string progress bar. """
percent = int((completed / total) * 100)
bar = '[='
arrow_reached = False
for t in range(step, 101, step):
if arrow_reached:
bar += ' '
else:
if percent // t != 0:
... | bigcode/self-oss-instruct-sc2-concepts |
def list_workspaces(client):
"""Get a list of workspaces the user can access on the active server.
Args:
client (obj): creopyson Client
Returns:
list: List of workspaces
"""
return client._creoson_post("windchill", "list_workspaces", key_data="workspaces") | bigcode/self-oss-instruct-sc2-concepts |
def add_period_cols(df):
"""
add to given `df` columns with month, day of week
and day of month based on index dates
Parameters
------------------------------------------------
`df`: pd.DataFrame
Returns
-------
pd.Dataframe
"""
df_new = df.copy()
d... | bigcode/self-oss-instruct-sc2-concepts |
def convert_ip(ip_str: str) -> float:
"""Convert innings pitched from the string representation to the float
:param ip_str: String representation of innings pitched
:returns: Float representation of innings pitched
"""
temp = ip_str.split(".")
return int(temp[0]) + int(temp[1]) * (1 / 3) | bigcode/self-oss-instruct-sc2-concepts |
import logging
def get_logger(args):
"""Creates the logger based on the provided arguments"""
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(args.log_level)
return logger | bigcode/self-oss-instruct-sc2-concepts |
def _parse_leaf_node_line(line):
"""
Return the leaf value given the string representation of a leaf node.
"""
return float(line.split('=')[1]) | bigcode/self-oss-instruct-sc2-concepts |
import posixpath
def api_path_join(*paths):
"""
Join API-style paths.
"""
return posixpath.join(*paths).strip('/') | bigcode/self-oss-instruct-sc2-concepts |
def SIR_model(y, t, betta, gamma):
"""
Tradiional SIR model.
:param y:
:param t:
:param betta:
:param gamma:
:return:
"""
S,I,R = y
dS_dt = -betta*S*I
dI_dt = betta*S*I - gamma*I
dR_dt = gamma*I
return ([dS_dt, dI_dt, dR_dt]) | bigcode/self-oss-instruct-sc2-concepts |
def find_span_binsearch(degree, knot_vector, num_ctrlpts, knot, **kwargs):
""" Finds the span of the knot over the input knot vector using binary search.
Implementation of Algorithm A2.1 from The NURBS Book by Piegl & Tiller.
The NURBS Book states that the knot span index always starts from zero, i.e. for... | bigcode/self-oss-instruct-sc2-concepts |
def _autotuple(a):
"""Automatically convert the supplied iterable to a scalar or tuple as appropriate."""
if not hasattr(a, "__iter__"):
return a
if len(a) == 1:
return a[0]
return tuple(a) | bigcode/self-oss-instruct-sc2-concepts |
def _loadfile(filename):
"""Returns a list of lines from `filename`"""
with open(filename, 'r') as fd:
lines = filter(lambda x: x,
map(lambda x: x.strip(), fd.readlines()))
return lines | bigcode/self-oss-instruct-sc2-concepts |
def ternary(condition, first_opernad, second_operand):
"""Same as `first_operand if condition else second_operand`"""
return first_opernad if condition else second_operand | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def git_path(repo_root, tail=None):
"""Returns a Path to the .git directory in repo_root
with tail appended (if present) or None if repo_root is not set.
"""
path = None
if repo_root:
path = pathlib.Path(repo_root) / ".git"
if tail is not None:
path = pat... | bigcode/self-oss-instruct-sc2-concepts |
def read_labels(file_name):
"""
Read list of labels from file like this:
label1
label2
label3
...
"""
labels_tmp = []
try:
with open(file_name, 'r') as f:
labels_tmp = f.readlines()
labels_tmp = [(i.rstrip(), 0) for i in labels_tmp]
... | bigcode/self-oss-instruct-sc2-concepts |
def bare_spectrum(sweep, subsys, which=-1, **kwargs):
"""
Plots energy spectrum of bare system `subsys` for given ParameterSweep `sweep`.
Parameters
----------
sweep: ParameterSweep
subsys: QuantumSystem
which: int or list(int), optional
default: -1, signals to plot all wavefunction... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def accuracy(outputs, labels):
"""
Calculate model accuracy
* :param outputs(torch.tensor): Pytorch weights tensor
* :param labels(list(str)): List of known labels
:return (torch.tensor): Prediction accuracy
"""
_, preds = torch.max(outputs, dim=1)
return torch.te... | bigcode/self-oss-instruct-sc2-concepts |
def attn(card, mode=None, files=None, seconds=None, payload=None, start=None):
"""Configure interrupt detection between a host and Notecard.
Args:
card (Notecard): The current Notecard object.
mode (string): The attn mode to set.
files (array): A collection of notefiles to watch.
... | 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.