seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def get_end_index_of_a_paragraph_from_string(text, start=0):
"""
:param text: a string
:param start: the index of the start position
:return: the index of the new line character or the last character
"""
return min(len(text) - 1, text.find('\n', start)) | bigcode/self-oss-instruct-sc2-concepts |
def assign_labels_colors(labels, colors):
"""
Takes a list of labels and colors and assigns a unique label to each color. Returns a color_list of length(labels).
The colors will loop around if the number of unique labels are more than the number of unique colors
:param labels:
:param colors:
:re... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from pathlib import Path
def path_resolver(f: Union[str, Path], *, touch: bool = True) -> Path:
"""Resolve a path.
Parameters
----------
f : Union[str, Path]
File whose path needs to be resolved.
touch : bool
Create file is not already existent. Default: T... | bigcode/self-oss-instruct-sc2-concepts |
def format_timestamp(time_stamp):
"""Create a consistent datetime string representation based on ISO 8601 format.
YYYY-MM-DDTHH:MM:SS.mmmmmm for unaware datetime objects.
YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM for aware datetime objects
:param time_stamp: value to convert
:type time_stamp: datet... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def get_sha1_hash(password):
"""For a given password string, utf-8 encode it and hash it with SHA1."""
encoded = password.encode('utf8')
hashed = hashlib.sha1(encoded).hexdigest()
return hashed | bigcode/self-oss-instruct-sc2-concepts |
import json
def read_lane_stats( lane_file ):
"""
Read RUN001_Lxxx.stats.json file created in bbi-sciatac-demux pipeline run.
These files are in the demux_out/fastqs_barcode directory. The run is always
RUN001 and the Lxxx denotes the results for each lane; that is, L001, ...
"""
lane_stats = json.load( l... | bigcode/self-oss-instruct-sc2-concepts |
def mysql_old_passwd(password, uppercase=True): # prior to version '4.1'
"""
Reference(s):
http://www.sfr-fresh.com/unix/privat/tpop3d-1.5.5.tar.gz:a/tpop3d-1.5.5/password.c
http://voidnetwork.org/5ynL0rd/darkc0de/python_script/darkMySQLi.html
>>> mysql_old_passwd(password='testpass', uppe... | bigcode/self-oss-instruct-sc2-concepts |
def key(name):
"""Extracts the filename key."""
dot = name.rfind(".")
if -1 != dot:
return name[0:dot]
return "" | bigcode/self-oss-instruct-sc2-concepts |
def test_names_list(test_suite):
"""Build a list containing all the test names of a test suite."""
test_names = []
for test in test_suite.test_cases():
test_names.append(test.description)
return test_names | bigcode/self-oss-instruct-sc2-concepts |
def model_device(model):
"""Determine the device the model is allocated on."""
# Source: https://discuss.pytorch.org/t/how-to-check-if-model-is-on-cuda/180
if next(model.parameters()).is_cuda:
return 'cuda'
return 'cpu' | bigcode/self-oss-instruct-sc2-concepts |
import math
def binomial_coefficient(n: int, k: int) -> int:
"""Calculate Binomial coefficient"""
n_fac = math.factorial(n)
k_fac = math.factorial(k)
n_minus_k_fac = math.factorial(n - k)
return round(n_fac/(k_fac*n_minus_k_fac)) | bigcode/self-oss-instruct-sc2-concepts |
import string
import random
def randstr(nchars=10):
"""Creates a random string identifier with the given number of chars"""
chars = string.ascii_letters + string.digits
ret = ''.join([random.choice(chars) for i in range(nchars)])
return ret | bigcode/self-oss-instruct-sc2-concepts |
def _format_function(func_name):
"""Provide better context for a "function" of the caller.
"""
if func_name is None:
return ""
elif func_name == "<module>":
return " (top level stmt)"
else:
return " in " + func_name | bigcode/self-oss-instruct-sc2-concepts |
def reformat_tract_code(tract: str, state_code: str, county_code: str) -> str:
"""Helper function to return GEOIDs compatible with those in deep-dive data files.
Parameters
----------
tract : A string
An unformatted tract code, e.g. '53.38'
state_code : A string
The FIPS code for th... | bigcode/self-oss-instruct-sc2-concepts |
def _safe_mesos_dns_taskname(task_name):
"""Converts a potentially slash-delimited task name to one that works for '.mesos' task names
Mesos DNS task names handle folders like this: /path/to/myservice => myservice-to-path"""
elems = task_name.strip("/").split("/")
elems.reverse()
return "-".join(ele... | bigcode/self-oss-instruct-sc2-concepts |
def get_list_of_subsets(subset_task):
"""
Get the subsets to process for this analysis
Parameters:
-----------
subset_task: string
string which specifies which subsets to use
Results:
--------
list of subset tasks
"""
# prefix for data and images
if subset_task =... | bigcode/self-oss-instruct-sc2-concepts |
def mean_of_number_list(numbers, delim="_"):
"""Report arithmetic mean of a string of integers that are separated by a
common delimiter. Used here to get mean of IES lengths reported in MILRAA
output GFF attribute.
Parameters
----------
numbers : str
List of numbers separated by a commo... | bigcode/self-oss-instruct-sc2-concepts |
def loadLowFreqLabels(labelFilePath):
"""
Return dictionary of channel labels.
:param labelFilePath: path to the data. The path should end with the folder containing all data for a specific house.
:type labelFilePath: str
:rparam: keys=channels_x - appliance name
:rtype: dict
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def rmpHomozygousWithTheta(theta, pu):
"""
Notation from Baldings and Nichols (1994)
taken from Buckleton FSI Gen (23) 2016; 91-100
https://doi.org/10.1016/j.fsigen.2016.03.004
"""
# 2theta + (1-theta)*pu
numerator1 = (theta+theta) + (1-theta)*pu
# 3theta + (1-theta)*pu == theta + numerator1
numerator... | bigcode/self-oss-instruct-sc2-concepts |
def bytes_to_gb(number: float) -> float:
"""
Convert bytes to gigabytes.
Parameters
----------
number : float
A ``float`` in bytes.
Returns
-------
float
Returns a ``float`` of the number in gigabytes.
"""
return round(number * 1e-9, 3) | bigcode/self-oss-instruct-sc2-concepts |
import re
def default_output_mixer_channel(discovery_props, output_channel=0):
"""Return an instrument's default output mixer channel based on the specified
`devicetype` and `options` discovery properties and the hardware output
channel.
This utility function is used by the ziPython examples and retu... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def root_sum_of_squares(x, dim=0):
"""
Compute the root sum-of-squares (RSS) transform along a given dimension of
a complex-valued tensor.
"""
assert x.size(-1) == 2
return torch.sqrt((x**2).sum(dim=-1).sum(dim)) | bigcode/self-oss-instruct-sc2-concepts |
def build_links(tld, region_code, states):
"""
This will build start_urls, It needs to be available before the ChipotleSpider creation
:param tld: 3rd level domain name to use for building the links e.g .co.uk
:param region_code: region is an important url param required for the search
:param state... | bigcode/self-oss-instruct-sc2-concepts |
import six
def _reset_cached_subgraph(func):
"""Resets cached subgraph after execution, in case it was affected."""
@six.wraps(func)
def wrapper(self, *args, **kwargs):
result = func(self, *args, **kwargs)
self._subgraph = None
return result
return wrapper | bigcode/self-oss-instruct-sc2-concepts |
def dt_writer(obj):
"""Check to ensure conformance to dt_writer protocol.
:returns: ``True`` if the object implements the required methods
"""
return hasattr(obj, "__dt_type__") and hasattr(obj, "__dt_write__") | bigcode/self-oss-instruct-sc2-concepts |
def _aggregate_at_state(joint_policies, state, player):
"""Returns {action: prob} for `player` in `state` for all joint policies.
Args:
joint_policies: List of joint policies.
state: Openspiel State
player: Current Player
Returns:
{action: prob} for `player` in `state` for all joint policies.
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
import torch
from typing import List
def cross_entropy_loss(batch: Tuple, model: torch.nn.Module) -> Tuple[float, Tuple[torch.Tensor, List]]:
"""
Calculate cross entropy loss for a batch and a model.
Args:
batch: batch of groundtruth data
model: torch model
R... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import platform
def get_py_prefix(venv_path: Path) -> Path:
"""Return the appropriate prefix for the virtual environment's Python.
>>> # If platform.system() is 'Windows'
>>> get_py_prefix(Path.cwd()/'.venv')
Path('.venv/Scripts/python.exe')
>>> # If platform.system() is... | bigcode/self-oss-instruct-sc2-concepts |
import json
def load_json(filename):
"""Returns students as a list of dicts from JSON file."""
with open(filename) as f:
students = json.load(f)
return students | bigcode/self-oss-instruct-sc2-concepts |
import typing
def flatten_list(list_of_lists: typing.List[typing.List[typing.Any]]) -> typing.List[typing.Any]:
"""flatten a 2 level deep nested list into a single list
Parameters
----------
list_of_lists: typing.List[typing.List[typing.Any]]
2 level nested list
Returns
-------
... | bigcode/self-oss-instruct-sc2-concepts |
def sqliteRowsToDicts(sqliteRows):
"""
Unpacks sqlite rows as returned by fetchall
into an array of simple dicts.
:param sqliteRows: array of rows returned from fetchall DB call
:return: array of dicts, keyed by the column names.
"""
return map(lambda r: dict(zip(r.keys(), r)), sqliteRows) | bigcode/self-oss-instruct-sc2-concepts |
def class_name(self):
"""
Return the name of this class without qualification.
eg. If the class name is "x.y.class" return only "class"
"""
return self.__class__.__name__.split('.')[-1] | bigcode/self-oss-instruct-sc2-concepts |
def add_season_steps(df, season_length):
"""
Adds a column to the DataFrame containing the season step depending on the given season_length.
The season step determines the position of each column within a season. It ranges from 0 to season_length - 1.
:param df: pandas DataFrame with a DateTime index a... | bigcode/self-oss-instruct-sc2-concepts |
def _byte_string(s):
"""Cast a string or byte string to an ASCII byte string."""
return s.encode('ASCII') | bigcode/self-oss-instruct-sc2-concepts |
def is_threaded_build(root):
"""
Check whether the tk build in use supports threading.
:param root: the tk widget to be used as reference
:return: ``1`` if threading is supported ``0`` otherwise
"""
return int(root.tk.eval("set tcl_platform(threaded)")) | bigcode/self-oss-instruct-sc2-concepts |
def bezierPoint(a, b, c, d, t):
"""Given the x or y coordinate of Bézier control points a,b,c,d and
the value of the t parameter, return the corresponding
coordinate of the point."""
u = 1.0 - t
return a * u * u * u + b * 3 * u * u * t + c * 3 * t * t * u + d * t * t * t | bigcode/self-oss-instruct-sc2-concepts |
def get_decoding_route_length(molecular_graph):
""" Returns the number of subgraphs in the `molecular_graph`s decoding route,
which is how many subgraphs would be formed in the process of deleting the
last atom/bond in the molecule stepwise until only a single atom is left.
Note that this is simply the ... | bigcode/self-oss-instruct-sc2-concepts |
def get_texture_declaration(texture):
"""Return the GLSL texture declaration."""
declaration = "uniform sampler%dD %s;\n" % (texture["ndim"], texture["name"])
return declaration | bigcode/self-oss-instruct-sc2-concepts |
def bin_coef_efficient(n: int, k: int) -> int:
"""
C(n, k) = C(n, n-k) # fact
therefore, if k > n-k, change k for n-k (for easier calculation)
i.e. C(n, k) = n! / (k! * (n-k)!) = [(n) * (n-1) * ... (n-k+1) / k!]
=> k terms above and k terms below
Time Complexity: O(k)
Space Complexity: O(... | bigcode/self-oss-instruct-sc2-concepts |
def ec2_inst_is_vpc(inst):
""" Is this EC2 instance a VPC instance? """
return (inst.vpc_id is not None) | bigcode/self-oss-instruct-sc2-concepts |
def read_number_of_agents(dpomdp_file):
"""Returns the number of agents in a Dec-POMDP problem
Keyword arguments:
dpomdp_file -- path to problem file in the .dpomdp format
"""
with open(dpomdp_file) as file:
for line in file:
if line.startswith('agents:'):
return int(line.split(':')[1])
raise V... | bigcode/self-oss-instruct-sc2-concepts |
import io
def _has_fileno(stream):
"""Returns whether the stream object seems to have a working fileno()
Tells whether _redirect_stderr is likely to work.
Parameters
----------
stream : IO stream object
Returns
-------
has_fileno : bool
True if stream.fileno() exists and doe... | bigcode/self-oss-instruct-sc2-concepts |
def remap_gender(gender: str) -> str:
"""Map gender to standard notation.
Args:
gender (str): Original gender, eg male, girl, etc
Returns:
str: m, f or other
"""
if not isinstance(gender, str):
return "other"
gender = gender.strip().lower()
if gender in ["man", "ma... | bigcode/self-oss-instruct-sc2-concepts |
def add(key=None, value=None, *, myst, getpass, **kwargs):
"""
Add a new key-value pair. Accepts a optional key and an optional value for the key. If the key or value is not entered, a secure input will be prompted to enter them.
"""
if not myst.mutable:
return 'the myst is in read-only mode, us... | bigcode/self-oss-instruct-sc2-concepts |
import re
def split_pem(data):
"""
Split a string of several PEM payloads to a list of strings.
:param data: String
:return: List of strings
"""
return re.split("\n(?=-----BEGIN )", data) | bigcode/self-oss-instruct-sc2-concepts |
def get_cell(grid, y: int, x: int) -> str:
"""Returns the value of a cell"""
return grid[y - 1][x - 1] | bigcode/self-oss-instruct-sc2-concepts |
def nsyll_word(word, vowels, sep=None):
"""
Count the number of syllables in a *word*, determined by the number
of characters from the *vowels* list found in that word.
If *sep* is defined, it will be used as the delimiter string (for
example, with `sep="."`, the word "a.bc.de" will be treated as t... | bigcode/self-oss-instruct-sc2-concepts |
def deriv(f,c,dx=0.0001):
"""
deriv(f,c,dx) --> float
Returns f'(x), computed as a symmetric difference quotient.
"""
return (f(c+dx)-f(c-dx))/(2*dx) | bigcode/self-oss-instruct-sc2-concepts |
import math
def distance(origin, destination):
"""
Haversince distance from https://gist.github.com/rochacbruno/2883505
Returns distance in kilometers
"""
lat1, lon1 = origin
lat2, lon2 = destination
radius = 6371 # km radius of Earth
dlat = math.radians(lat2-lat1)
dlon = math.rad... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def rgba_to_rgb(image):
"""
Convert an image from RGBA to RGB.
"""
if not isinstance(image, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 4:
raise ValueError(f"Input size must h... | bigcode/self-oss-instruct-sc2-concepts |
def pass_bot(func):
"""This decorator is deprecated, and it does nothing"""
# What this decorator did is now done by default
return func | bigcode/self-oss-instruct-sc2-concepts |
def internal_pressure(P_d, P_h):
"""Return total internal pressure [Pa].
:param float P_d: Design pressure [Pa]
:param float P_h: Pressure head [Pa]
"""
return P_d + P_h | bigcode/self-oss-instruct-sc2-concepts |
import random
def keep_fraction(l, f):
"""Return fraction `f` of list `l`. Shuffles `l`."""
random.shuffle(l)
count = int(f * len(l))
return l[:count] | bigcode/self-oss-instruct-sc2-concepts |
def list_to_space_string(l):
"""Return a space separated string from a list"""
s = " ".join(l)
return s | bigcode/self-oss-instruct-sc2-concepts |
def _ComplexSentenceAsFlatList(complex_sentence, prefix=""):
"""Expand complex_sentence into a flat list of strings
e.g. ['NUMBERED'] ['IDS', 'INES'] ['SOLUTION']
to ['NUMBERED ID SOLUTION', 'NUMBERED INES SOLUTION']
"""
results = []
next_start = complex_sentence[1:].find('[')
if nex... | bigcode/self-oss-instruct-sc2-concepts |
def arg_meta(*arg_flags, **arg_conf):
"""
Return a tuple `(arg_flags, arg_conf)` that contains argument flags & argument config.
`arg_flags`: A tuple contains argument flags
`arg_conf`: A dict containsf argument config
"""
return (arg_flags, arg_conf) | bigcode/self-oss-instruct-sc2-concepts |
def sec2HMS(sec):
"""Convert time in sec to H:M:S string
:param sec: time in seconds
:return: H:M:S string (to nearest 100th second)
"""
H = int(sec//3600)
M = int(sec//60-H*60)
S = sec-3600*H-60*M
return '%d:%2d:%.2f'%(H,M,S) | bigcode/self-oss-instruct-sc2-concepts |
def dot_product(a, b):
""" Return dot product between two vectors a & b. """
a1, a2, a3 = a
b1, b2, b3 = b
return a1 * b1 + a2 * b2 + a3 * b3 | bigcode/self-oss-instruct-sc2-concepts |
def table_exists(cursor, table_name):
"""
Checks if the table table_name exists in the database.
returns true if the table exists in the database, false otherwise.
:param cursor: the cursor to the database's connection
:type cursor: Cursor
:param table_name: the name of the table searching for
... | bigcode/self-oss-instruct-sc2-concepts |
def _parse_commit_response(commit_response_pb):
"""Extract response data from a commit response.
:type commit_response_pb: :class:`.datastore_pb2.CommitResponse`
:param commit_response_pb: The protobuf response from a commit request.
:rtype: tuple
:returns: The pair of the number of index updates ... | bigcode/self-oss-instruct-sc2-concepts |
import six
def FormatDuration(duration):
"""Formats a duration argument to be a string with units.
Args:
duration (int): The duration in seconds.
Returns:
unicode: The formatted duration.
"""
return six.text_type(duration) + 's' | bigcode/self-oss-instruct-sc2-concepts |
def object_is_valid_pipeline(o):
""" Determines if object behaves like a scikit-learn pipeline. """
return (
o is not None
and hasattr(o, "fit")
and hasattr(o, "predict")
and hasattr(o, "steps")
) | bigcode/self-oss-instruct-sc2-concepts |
def expand_address_range(address_range):
"""
Expand an address if bits are marked as optional
Args:
address_range (str): The address to expand
Returns:
list(str): A list of addresses this address has been expanded to
"""
if "X" in address_range:
res = expand_address_ra... | bigcode/self-oss-instruct-sc2-concepts |
def mandelbrotCalcRow(y, w, h, max_iteration = 1000):
""" Calculate one row of the mandelbrot set with size wxh """
y0 = y * (2/float(h)) - 1 # rescale to -1 to 1
image_rows = {}
for x in range(w):
x0 = x * (3.5/float(w)) - 2.5 # rescale to -2.5 to 1
i, z = 0, 0 + 0j
c... | bigcode/self-oss-instruct-sc2-concepts |
def mass_transfer_coefficient_mishra_kumar(wind_speed):
"""
Return the mass transfert coefficient [m/s] only from wind speed
source:(Berry et al., 2012)
Parameters
----------
wind_speed : Wind speed 10 meters above the surface [m/s]
"""
return 0.0025 * (wind_speed**0.78) | bigcode/self-oss-instruct-sc2-concepts |
import time
def mujoco_rgb_from_states(env, sim_states, time_delay=0.008):
"""
Given the states of the simulator, we can visualize the past Mujoco timesteps.
- Simulator states are obtained via env.sim.get_state()
"""
rgb = []
for t in range(len(sim_states)):
env.sim.set_state(sim_... | bigcode/self-oss-instruct-sc2-concepts |
def average(values):
"""Calculates the average value from a list of numbers
Args:
values (list)
Returns:
float: The average value"""
if len(values) == 0:
return None
return sum(values)/len(values) | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def _group_insertions(sortedlist, keys):
"""
Given a list of keys to insert into sortedlist, returns the pair:
[(index, count), ...] pairs for how many items to insert immediately before each index.
ungroup(new_keys): a function that rearranges new keys to match the original keys.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def ge(y):
"""ge(y)(x) = x > y
>>> list(filter(ge(3), [1,2,3,4,5]))
[3, 4, 5]
"""
return lambda x : x >= y | bigcode/self-oss-instruct-sc2-concepts |
import struct
def _read_header(data):
"""
Returns the header portion of the given data
"""
return struct.unpack('<BBBI', data[:7]) | bigcode/self-oss-instruct-sc2-concepts |
def subListInSexp(sexp, xys):
"""Given a list of tuples of the form xys = [(x1, y1), ..., (xn, yn)]
substitute (replace) `x` with `y` in `sexp`
i.e. returns `sexp[y1/x1, ..., yn/xn]`
"""
d = dict(xys)
if type(sexp) != list:
return (d[sexp] if sexp in d else sexp)
else:
retur... | bigcode/self-oss-instruct-sc2-concepts |
def str2float(value: str):
""" Change a string into a floating point number, or a None """
if value == 'None':
return None
return float(value) | bigcode/self-oss-instruct-sc2-concepts |
def split_at(s: str, i: int):
"""Returns a tuple containing the part of the string before the
specified index (non-inclusive) and the part after the index
"""
return (s[:i], s[i:]) | bigcode/self-oss-instruct-sc2-concepts |
def octal_to_string(octal):
"""The octal_to_string function converts a permission in octal format into a
string format."""
result = ""
value_letters = [(4,"r"),(2,"w"),(1,"x")]
for digit in [int(n) for n in str(octal)]:
for value, letter in value_letters:
if digit >= value:
... | bigcode/self-oss-instruct-sc2-concepts |
def item_at_index_or_none(indexable, index):
"""
Returns the item at a certain index, or None if that index doesn't exist
Args:
indexable (list or tuple):
index (int): The index in the list or tuple
Returns:
The item at the given index, or None
"""
try:
return i... | bigcode/self-oss-instruct-sc2-concepts |
def dict_to_string(formula):
"""
Convert a dictionary formula to a string.
Args:
formula (dict): Dictionary formula representation
Returns:
fstr (str): String formula representation
"""
return ''.join(('{0}({1})'.format(key.title(), formula[key]) for key in sorted(formula.keys(... | bigcode/self-oss-instruct-sc2-concepts |
def parse_color(color):
"""Take any css color definition and give back a tuple containing the
r, g, b, a values along with a type which can be: #rgb, #rgba, #rrggbb,
#rrggbbaa, rgb, rgba
"""
r = g = b = a = type = None
if color.startswith('#'):
color = color[1:]
if len(color) == ... | bigcode/self-oss-instruct-sc2-concepts |
def _parse_free_spaces(string):
"""
Parses the free spaces string and returns the free spaces as integer.
Input example (without quotes): "Anzahl freie Parkplätze: 134"
"""
last_space_index = string.rindex(" ")
return int(string[last_space_index+1:]) | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
def flatten_shape(input_shape, axis=1, end_axis=-1):
""" calculate the output shape of this layer using input shape
Args:
@input_shape (list of num): a list of number which represents the input shape
@axis (int): parameter from caffe's Flatten layer
@end_a... | bigcode/self-oss-instruct-sc2-concepts |
def int_def(value, default=0):
"""Parse the value into a int or return the default value.
Parameters
----------
value : `str`
the value to parse
default : `int`, optional
default value to return in case of pasring errors, by default 0
Returns
-------
`int`
the p... | bigcode/self-oss-instruct-sc2-concepts |
def readline( file, skip_blank=False ):
"""Read a line from provided file, skipping any blank or comment lines"""
while 1:
line = file.readline()
if not line: return None
if line[0] != '#' and not ( skip_blank and line.isspace() ):
return line | bigcode/self-oss-instruct-sc2-concepts |
def compute_sum(v, fg):
"""Compute the sum of a variable v already marked to be summed.
Sum over the given variable and update the factor connected
to it. (akin to marginalization)
Note that the variable v must have only one edge to a factor, so that the
sum is forced to be a simple linear order c... | bigcode/self-oss-instruct-sc2-concepts |
def scan_cluster_parsing(inp, cluster_threshold_kruskal, cluster_threshold_beta, cluster_threshold_vip, cluster_threshold_vip_relevant, cluster_orientation, cluster_vip_top_number, cluster_mean_area, cluster_labelsize_cluster, cluster_figsize_cluster):
"""
Initialize cluster analysis.
Initialization functi... | bigcode/self-oss-instruct-sc2-concepts |
from xdg.DesktopEntry import DesktopEntry
def parse_linux_desktop_entry(fpath):
"""Load data from desktop entry with xdg specification."""
try:
entry = DesktopEntry(fpath)
entry_data = {}
entry_data['name'] = entry.getName()
entry_data['icon_path'] = entry.getIcon()
en... | bigcode/self-oss-instruct-sc2-concepts |
import ssl
def build_ssl_context(local_certs_file: str, ca_certs_file: str, key_file: str, ):
"""
:param local_certs_file: The filename of the certificate to present for authentication.
:param ca_certs_file: The filename of the CA certificates as passed to ssl.SSLContext.load_verify_locations
:param k... | bigcode/self-oss-instruct-sc2-concepts |
import textwrap
def to_curvedskip(of, to, angle=60, xoffset=0):
"""
Curved skip connection arrow.
Optionally, set the angle (default=60) for out-going and in-coming arrow,
and an x offset for where the arrow starts and ends.
"""
text = rf"""
\draw [copyconnection]
([xshift=... | bigcode/self-oss-instruct-sc2-concepts |
def extract_video_id_from_yturl(href):
""" Extract a Youtube video id from a given URL
Returns None on error or failure.
"""
video_id = None
try:
start = -1
if href.find('youtube.com/watch') != -1:
start = href.find('v=') + 2
elif href.find('youtu.be/') != -1... | bigcode/self-oss-instruct-sc2-concepts |
def zone_bc_type_english(raw_table, base_index):
""" Convert zone b/c type to English """
value = raw_table[base_index]
if value == 0:
return "NA"
if value == 1:
return "Direct"
if value == 2:
return "3WV"
if value == 3:
return "NA"
if value == 4:
ret... | bigcode/self-oss-instruct-sc2-concepts |
import uuid
import hashlib
def _create_token(user):
"""Create a unique token for a user.
The token is created from the user id and a unique id generated
from UUIDv4. Then both are hashed using MD5 digest algorithm.
"""
_id = f"{user.id}-{str(uuid.uuid4())}"
_hash = hashlib.md5(_id.encode('as... | bigcode/self-oss-instruct-sc2-concepts |
def git_clone(repo, branch=None):
"""
Return the git command to clone a specified repository.
Args:
repo: string representing a git repo.
branch: string representing a branch name.
Returns:
cmd: list containing the command line arguments to clone a git repo.
"""
cmd = [... | bigcode/self-oss-instruct-sc2-concepts |
def _extract_version(version_string, pattern):
""" Extract the version from `version_string` using `pattern`. """
if version_string:
match = pattern.match(version_string.strip())
if match:
return match.group(1)
return "" | bigcode/self-oss-instruct-sc2-concepts |
def prepend_dict_key(orig, prep_text, camel_case=False):
"""
Return a new dictionary for which every key is prepended with prep_text.
"""
if camel_case:
return dict(
(prep_text + str(k).title(), v) for k, v in orig.items()
)
else:
return dict((prep_text + str(k), ... | bigcode/self-oss-instruct-sc2-concepts |
def int_check(input_value, warning_box):
"""Checks if input is a positive integer."""
try:
int_value = int(input_value)
if int_value > 0:
warning_box.config(text="")
return True
else:
warning_box.config(text="Please type a positive integer.")
return False
except ValueError:
warning_box.config(tex... | bigcode/self-oss-instruct-sc2-concepts |
def is_win(matrix):
"""
is game win? return bool
"""
for item_list in matrix:
if 2048 in item_list:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import sqlite3
def get_twinkles_visits(opsim_db_file, fieldID=1427):
"""
Return a sorted list of visits for a given fieldID from an OpSim
db file.
Parameters
----------
obsim_db_file : str
Filename of the OpSim db sqlite file
fieldID : int, optional
ID number of the field ... | bigcode/self-oss-instruct-sc2-concepts |
import string
import random
def random_string(string_length=20, punctuation=True):
"""
Create a random string that is quotable. Usable for basic passwords.
Args:
string_length - (optional) The number of characters to generate
punctuation - (optional) True if the generated characters shoul... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import json
def read_authors(filename):
"""Read the list of authors from .zenodo.json file."""
with Path(filename).open() as file:
info = json.load(file)
authors = []
for author in info['creators']:
name = ' '.join(author['name'].split(',')[::-1]).s... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_center_block_mask(samples: torch.Tensor, mask_size: int, overlap: int):
"""
Mask out the center square region of samples provided as input.
Parameters
----------
samples: torch.Tensor
Batch of samples, e.g. images, which are passed through the network and for which sp... | bigcode/self-oss-instruct-sc2-concepts |
import re
def hex2rgb(hex_code: str) -> tuple:
"""
Convert color given in hex code to RGB in ints. Result is returned inside 3-element tuple.
:param hex_code:
:return: tuple (R, G, B)
"""
pattern = re.compile(r'^#?[a-fA-F0-9]{6}$')
if not re.match(pattern, hex_code):
raise ValueEr... | bigcode/self-oss-instruct-sc2-concepts |
def eh_posicao(pos): # universal -> booleano
"""
Indica se certo argumento e uma posicao ou nao.
:param pos: posicao
:return: True se o argumento for uma posicao, False caso contrario
"""
# uma posicao e um tuplo com dois elementos em que ambos variam de 0 a 2
if type(pos) != tuple or len(p... | 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.