seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def pivotFlip(string, pivot):
"""Reverses a string past a pivot index."""
flip = list(string[pivot:])
flip.reverse()
return string[:pivot]+''.join(flip) | bigcode/self-oss-instruct-sc2-concepts |
def det(x):
"""
Return the determinant of ``x``.
EXAMPLES::
sage: M = MatrixSpace(QQ,3,3)
sage: A = M([1,2,3,4,5,6,7,8,9])
sage: det(A)
0
"""
return x.det() | bigcode/self-oss-instruct-sc2-concepts |
def fields_sort_key_factory(fields, field_order):
"""Return a function to sort `fields` by the `field_order`."""
raw_field_order = [x[0] for x in fields]
def key(key):
name, field = key
try:
return field_order.index(name)
except ValueError:
return 100000 + ra... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def unique_dashes(n):
"""Build an arbitrarily long list of unique dash styles for lines.
Parameters
----------
n : int
Number of unique dash specs to generate.
Returns
-------
dashes : list of strings or tuples
Valid arguments for the ``dashes`` parameter... | bigcode/self-oss-instruct-sc2-concepts |
import uuid
def generate_id() -> str:
"""
Generate an uuid to be used as id
"""
return str(uuid.uuid4()) | bigcode/self-oss-instruct-sc2-concepts |
def count_user(data_list):
"""
Function count the users.
Args:
data_list: The data list that is doing to be iterable.
Returns:
A list with the count value of each user type.
"""
customer = 0
subscriber = 0
for i in range(len(data_list)):
if data_list[i][5] ... | bigcode/self-oss-instruct-sc2-concepts |
import base64
def encode_access_id(token_str: str, replica: str) -> str:
"""
Encode a given token as an access ID using URL-safe base64 without padding.
Standard base64 pads the result with equal signs (`=`). Those would need to
be URL-encoded when used in the query portion of a URL:
>>> base64.... | bigcode/self-oss-instruct-sc2-concepts |
def expand_suggested_responses(instrument, lookups, *responses):
"""
Maps any {'_suggested_response': pk} values to the SuggestedResponse by that id, as long as it
is present in the ``lookups`` dict.
"""
values = []
for response in responses:
data = response # Assume raw passthrough by... | bigcode/self-oss-instruct-sc2-concepts |
import fsspec
from typing import Optional
from typing import Set
from typing import List
def _get_objects_in_path(
fs: fsspec.AbstractFileSystem,
path: str,
target_type: Optional[str] = None,
extensions: Optional[Set[str]] = None
) -> List[str]:
"""Get all objects of a specific typ... | bigcode/self-oss-instruct-sc2-concepts |
def get_property_by_name(pif, name):
"""Get a property by name"""
return next((x for x in pif.properties if x.name == name), None) | bigcode/self-oss-instruct-sc2-concepts |
def _scale(column, new_range):
"""
Scale list of values to a given range (the original range is assumed to be [min(column), max(column)]).
"""
old_range = (column.min(), column.max())
return (((column - old_range[0]) * (new_range[1] - new_range[0])) / (old_range[1] - old_range[0])) + new_range[0] | bigcode/self-oss-instruct-sc2-concepts |
def dominance(counts):
"""Dominance = 1 - Simpson's index, sum of squares of probs.
Briefly, gives probability that two species sampled are the same."""
freqs = counts/float(counts.sum())
return (freqs*freqs).sum() | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
from functools import reduce
import operator
def prod(iterable: Iterable) -> float:
"""Returns the product of the elements of an iterable."""
return reduce(operator.mul, iterable, 1) | bigcode/self-oss-instruct-sc2-concepts |
def division_euclidienne_dichotomique(a, b):
"""Renvoie le quotient q et le reste r de la division euclidienne de a par b"""
n = 0
while 2 ** n * b <= a:
n += 1
inf = 2 ** (n - 1)
sup = 2 ** n
for i in range(1, n):
mid = (inf + sup) / 2
if mid * b <= a:
inf =... | bigcode/self-oss-instruct-sc2-concepts |
import re
def sanitize_id(string):
"""Remove characters from a string which would be invalid
in XML identifiers
Parameters
----------
string : str
Returns
-------
str
"""
string = re.sub(r"\s", '_', string)
string = re.sub(r"\\|/", '', string)
return string | bigcode/self-oss-instruct-sc2-concepts |
def mini_help(n):
"""
=> Exibe a docstring do comando que recebe
:param n: o comando a ser pesquisado
:return: a ajuda interactiva (help) do parametro
"""
r = len('Acedendo ao manual do comando')+len(n)+6 #este trecho
print('~'*r) #de codigo
print(f' Acedendo ao manual do comando {n}') #pode ser
print... | bigcode/self-oss-instruct-sc2-concepts |
import random
import string
def random_mutate(word, mutations, no_punct, alpha):
"""Randomly mutate the word with 'mutations' frequency.
If no_punct is true, leave punctuation unaltered."""
letters = list(word) # split the current word in a list
num_mutations = round(mutations * len(letters))
... | bigcode/self-oss-instruct-sc2-concepts |
def get_gem_group(sample_def):
""" Get the GEM group from a sample def.
Defaults to 1 if the gem_group is specified as None.
Args:
sample_def (dict): Sample def
Returns:
int: GEM group
"""
gg = sample_def['gem_group'] or 1
return int(gg) | bigcode/self-oss-instruct-sc2-concepts |
def rinse(M, d=1e-14):
"""
This function removes any entries in a list or array that
are closer to zero than d is. It is used in the gauss function
to avoid division by near-zero values. By default d is set
to be equal to 10^-14.
"""
m = len(M)
if type(M[0]) == list:
n = len(M[0... | bigcode/self-oss-instruct-sc2-concepts |
def get_figure_height(width, ratio=0.6):
"""Compute and return figure height with a ratio."""
return width*ratio | bigcode/self-oss-instruct-sc2-concepts |
import re
def process_content(string):
"""
Process the content string data,
if the string is nan (empty), replace it by ''
else check if '#*;' in string, replace it by right symbol,
and if the meaning of '&#*;' is unknow, return the wrong info
Paras:
string: the context
... | bigcode/self-oss-instruct-sc2-concepts |
def _as_float_string(f):
"""Takes a floating point number and returns it as a formatted string"""
return "%.2f" % f if f is not None else 'nil' | bigcode/self-oss-instruct-sc2-concepts |
def extract_keywords(icss):
"""Helper function
Parameters
----------
icss : string
comma-separated string
Returns
-------
kws : list of string
set of keywords
paramdict : dict
dict of {parameterized_keyword: parameter_valu... | bigcode/self-oss-instruct-sc2-concepts |
def _static(job, t):
"""Static priority assignment according to task IDs (smaller is higher priority)"""
if job.task.id is None:
raise ValueError(f"Cannot use task ID {job.task.id} as priority!")
return job.task.id | bigcode/self-oss-instruct-sc2-concepts |
def CreateFeedItemAddOperation(name, price, date, adgroup_id,
ad_customizer_feed):
"""Creates a FeedItemOperation.
The generated FeedItemOperation will create a FeedItem with the specified
values and AdGroupTargeting when sent to FeedItemService.mutate.
Args:
name: the value... | bigcode/self-oss-instruct-sc2-concepts |
def range_limit(u, range=[-5, 5]):
"""
Returns a logical vector that is True where the values of `u` are
outside of `range`.
Parameters
----------
u : xarray.DataArray
The timeseries data to clean.
range : list
Min and max magnitudes beyond which are masked
Returns
--... | bigcode/self-oss-instruct-sc2-concepts |
def read_data(filename="data/input4.data"):
"""
Load the raw datafile
"""
with open(filename) as f:
lines = f.read().splitlines()
return lines | bigcode/self-oss-instruct-sc2-concepts |
def identity(x):
"""
pickable equivalent of lambda x: x
"""
return x | bigcode/self-oss-instruct-sc2-concepts |
def get_posted_files(db):
"""
Extracts a set of image file names for persisted tweets.
The application's expected image file format is ``an-image-name-without-the-path.png``. So,
it does not include the path to the image file in the saved string.
Args:
db: TinyDB instance.
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def calculer_temps_segment(distance, v, deriver_v, limite, pas):
"""
Renvoie le temps et la vitesse après le parcours d'un segment.
distance : flottant, distance à parcourir
v : flottant, vitesse intiale
deriver_v : fonction, renvoie la dérivée de la vitesse
limite : flottant, limit... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
from typing import List
def _purge_tags(tags: Sequence[str]) -> List[str]:
"""
Purge tags. Remove duplicate and sort tags
:param tags: A sequence of tags
:return: purged tags
"""
return sorted(set({key.strip().lower() for key in tags if key})) | bigcode/self-oss-instruct-sc2-concepts |
def select_from_dict(original_dict, allowed_keys):
"""
>>> select_from_dict({"spam": 1, "eggs": 2, "pizza": 3}, allowed_keys=("pizza", "spam"))
{'spam': 1, 'pizza': 3}
>>> select_from_dict({"spam": 1, "eggs": 2, "pizza": 3}, allowed_keys=())
{'spam': 1, 'eggs': 2, 'pizza': 3}
"""
if len(allo... | bigcode/self-oss-instruct-sc2-concepts |
def path_emission(iterable, emission=0):
"""Construct a common emission from an iterable of :class:`Material` objects
Parameters
----------
iterable: list_like
List of :class:`Material` objects
emission: scalar or :class:`~lentil.radiometry.Spectrum`, optional
Emission collected up... | bigcode/self-oss-instruct-sc2-concepts |
def timeout_from_marker(marker):
"""Return None or the value of the timeout."""
timeout = None
if marker is not None:
if len(marker.args) == 1 and len(marker.kwargs) == 0:
timeout = marker.args[0]
elif len(marker.args) == 0 and len(marker.kwargs) == 1 and "timeout" in marker.kwa... | bigcode/self-oss-instruct-sc2-concepts |
def get_color(score: float) -> str:
"""Return a colour reference from a pylint score"""
colors = {
"brightgreen": "#4c1",
"green": "#97CA00",
"yellow": "#dfb317",
"yellowgreen": "#a4a61d",
"orange": "#fe7d37",
"red": "#e05d44",
"bloodred": "#ff0000",
... | bigcode/self-oss-instruct-sc2-concepts |
def get_romb_offset(rom_slot, rom_split, rom_bases, roms_file=False):
"""
Get ROM slot offset in SPI Flash or ROMS.ZX1 file
:param rom_slot: ROM slot index
:param rom_split: Slot number where rom binary data is split in two
:param rom_bases: Offsets for ROM binary data
:param roms_file: If True,... | bigcode/self-oss-instruct-sc2-concepts |
def add(a, b):
"""
A function that adds two integers
:param a: (int) The first integer
:param b: (int) The second integer
:return: (int) The sum of a and b
:raises: AttributeError, if a and b are not integers
"""
if not isinstance(a, int) or not isinstance(b, int):
raise Attribu... | bigcode/self-oss-instruct-sc2-concepts |
def internal_gains (
metabolic_gains,
lighting_gains,
appliances_gains,
cooking_gains,
pumps_and_fans_gains,
losses,
water_heating_gains
):
"""Calculates Internal Gains, Section 5.
:param metabolic_gains: Calculated using table 5. See (66... | bigcode/self-oss-instruct-sc2-concepts |
def cron_trigger_dict(ts_epoch, ts_2_epoch):
"""A cron trigger as a dictionary."""
return {
"year": "2020",
"month": "*/1",
"day": "*/1",
"week": "*/1",
"day_of_week": "*/1",
"hour": "*/1",
"minute": "*/1",
"second": "*/1",
"start_date": ts... | bigcode/self-oss-instruct-sc2-concepts |
def lighten(color, shades=1):
"""
Lightens a given color by a number of shades.
Args:
color(tuple): the RGBA color.
shades(int): the number of shades to add to the color value.
Return:
The lightened color.
"""
r, g, b, a = color
return min(r + shades, 255), min(g + ... | bigcode/self-oss-instruct-sc2-concepts |
def repeated_letter(word: str) -> dict:
"""
Check if a word has repeated letters.
Args:
word (str): Word to check.
Returns:
dict: {
'A':{1,2},
'B':{0,3},
etc.
} # Dictionary of repeated letters and the indices where they are repeated.
"""... | bigcode/self-oss-instruct-sc2-concepts |
def get_graph_no_active_edges(graph):
"""
Get a molecular graph without the active edges
Arguments:
graph (nx.Graph):
Returns:
(nx.Graph):
"""
graph_no_ae = graph.copy()
active_edges = [edge for edge in graph.edges
if graph.edges[edge]['active'] is True... | bigcode/self-oss-instruct-sc2-concepts |
def fraction_justified_and_finalized(validator):
"""Compute the fraction of justified and finalized checkpoints in the main chain.
From the genesis block to the highest justified checkpoint, count the fraction of checkpoints
in each state.
"""
# Get the main chain
checkpoint = validator.highest... | bigcode/self-oss-instruct-sc2-concepts |
def map_headers(wb_obj):
"""
Returns a nested dictionary with the location and name of each
column header
"""
sheets = wb_obj.sheetnames
return_value = {}
ignore_this = ["Main", "Commands", "Settings", "Errors"]
for sheet in sheets:
if sheet not in ignore_this:
row = ... | bigcode/self-oss-instruct-sc2-concepts |
def parse_edges_and_weights(
data: str, start_string: str = "Distance", end_string: str = "# Source",
) -> list:
"""Return a list of edges with weights.
This function will parse through the read-in input data between strings ''start_string'' and ''end_string''
to return the filtered text in-between... | bigcode/self-oss-instruct-sc2-concepts |
def _kappamstar(kappa, m, xi):
"""
Computes maximized cumulant of order m
Parameters
-----
kappa : list
The first two cumulants of the data
xi : int
The :math:`\\xi` for which is computed the p value of :math:`H_0`
m : float
The order of the cumulant
Returns
... | bigcode/self-oss-instruct-sc2-concepts |
def safe_get(dictionary, key):
"""
Safely get value from dictionary
"""
if key in dictionary:
return dictionary[key]
return None | bigcode/self-oss-instruct-sc2-concepts |
def degree_centrality(graph):
"""
Returns a dictionary with the degree centrality of all the nodes in a given graph network.
A node’s degree centrality is the number of links that lead into or out of the node.
"""
nodes = set(graph.nodes)
s = 1.0 / (len(nodes) - 1.0)
centrality = dict((n, d ... | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_symbol(num: int = 1, seed=None) -> list:
"""
Returns a list of random symbols from the following set:
['!', '@', '#', '$', '%', '^', '&, '*' ,'(', ')', '-', '_', '=', '+', '`', '~]
:param num: Number of symbols to return
:type num: int
:param seed: Random seed (Opti... | bigcode/self-oss-instruct-sc2-concepts |
def my_strip(thing):
"""Safely strip `thing`.
"""
try:
return thing.strip()
except:
return thing | bigcode/self-oss-instruct-sc2-concepts |
def quadratic_depth(x, point_1, point_2):
"""
Evaluate a quadratic function for a given value ``x``. The parameters to define the
function are determined through the coordinates of two points (:math: (x_1, z_1)
and :math: (x_2, z_2)).
.. math ::
z(x) = - a x^2 + b
where,
.. math::... | bigcode/self-oss-instruct-sc2-concepts |
from unittest.mock import Mock
def _get_mock(instance):
"""Create a mock and copy instance attributes over mock."""
if isinstance(instance, Mock):
instance.__dict__.update(instance._mock_wraps.__dict__) # pylint: disable=W0212
return instance
mock = Mock(spec=instance, wraps=instance)
... | bigcode/self-oss-instruct-sc2-concepts |
def _recursive_to_list(array):
"""
Takes some iterable that might contain iterables and converts it to a list of lists
[of lists... etc]
Mainly used for converting the strange fbx wrappers for c++ arrays into python lists
:param array: array to be converted
:return: array converted to lists
... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_bmi(weight, height, system='metric'):
"""
Return the Body Mass Index (BIM) for the
given weight, height, and measurement system.
"""
if system == 'metric':
bmi = (weight / (height ** 2))
else:
bmi = 703 * (weight / (height ** 2))
return bmi | bigcode/self-oss-instruct-sc2-concepts |
def save(df, name):
"""
Save a dataframe as a csv and pickle file
:param df: (pd.DataFrame) - dataframe to save
:param name: (str) - output name
:return name: (str) - output name
"""
df.to_csv('{0}.csv'.format(name))
df.to_pickle('{0}.pkl'.format(name))
return name | bigcode/self-oss-instruct-sc2-concepts |
def rivers_with_station(stations):
"""returns the list rivers where the stations are located"""
river_list = set([])
for each_station in stations :
river_list.add(each_station.river)
return list(river_list) | bigcode/self-oss-instruct-sc2-concepts |
def extract_int_from_str(string):
"""
Tries to extract all digits from a string.
Args:
string: a string
Returns:
An integer consisting of all the digits in the string, in order,
or False
"""
try:
return ''.join(filter(lambda x: x.isdigit(), string))
except:... | bigcode/self-oss-instruct-sc2-concepts |
def formed_bond_keys(tra):
""" keys for bonds that are formed in the transformation
"""
_, frm_bnd_keys, _ = tra
return frm_bnd_keys | bigcode/self-oss-instruct-sc2-concepts |
def go_past_duration(interest_area, fixation_sequence):
"""
Given an interest area and fixation sequence, return the go-past time on
that interest area. Go-past time is the sum duration of all fixations from
when the interest area is first entered until when it is first exited to
the right, includin... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def load_yaml(fileuri):
"""Load yaml file into a dict"""
fd = open(fileuri, 'r')
try:
return yaml.safe_load(fd)
except Exception as e:
raise e
finally:
fd.close() | bigcode/self-oss-instruct-sc2-concepts |
def parse_gpu_ids(gpu_str):
"""Parse gpu ids from configuration.
Args:
gpu_str: string with gpu indexes
Return:
a list where each element is the gpu index as int
"""
gpus = []
if gpu_str:
parsed_gpus = gpu_str.split(",")
if len(gpus) != 1 or int(gpus[0]) >= 0... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def send_get_request(query_url, headers):
"""
Sends a get request using the Requests library
It doesn't do anytthing special right now, but it might do some checks in future
:param query_url:
:param headers:
:return:
"""
response = requests.get(query_url, headers=header... | bigcode/self-oss-instruct-sc2-concepts |
def autotype_seq(entry):
"""Return value for autotype sequence
Args: entry - dict
Return: string
"""
return next((i.get('value') for i in entry['fields'] if i.get('name') == 'autotype'), "") | bigcode/self-oss-instruct-sc2-concepts |
def format_repository_listing(repositories):
"""Returns a formatted list of repositories.
Args:
repositories (list): A list of repositories.
Returns:
The formated list as string
"""
out = ""
i = 1
for r in repositories:
out += (f"{i:>4} {r.get('name', '??')}\n"
... | bigcode/self-oss-instruct-sc2-concepts |
def hex_to_ipv6(hex):
"""
Takes a 128 bit hexidecimal string and returns that string formatted for IPv6
:param hex: Any 128 bit hexidecimal passed as string
:return: String formatted in IPv6
"""
return ':'.join(hex[i:i + 4] for i in range(0, len(hex), 4)) | bigcode/self-oss-instruct-sc2-concepts |
def reconstruct_path(current):
"""
Uses the cameFrom members to follow the chain of moves backwards
and then reverses the list to get the path in the correct order.
"""
total_path = [current]
while current.cameFrom != None:
current = current.cameFrom
total_path.append(current)
... | bigcode/self-oss-instruct-sc2-concepts |
import random
def guess_number(start: int, end: int) -> int:
"""Return a number in specified range."""
result = random.choice(range(start, end + 1))
return result | bigcode/self-oss-instruct-sc2-concepts |
import math # only used in this method
from typing import Tuple
def get_euclidean_distance(start_pos: Tuple[int, int], target_pos: Tuple[int, int]) -> float:
"""
Get distance from an xy position towards another location. Expected tuple in the form of (x, y).
This returns a float indicating the straight l... | bigcode/self-oss-instruct-sc2-concepts |
def crossover(x, y):
"""
Last two values of X serie cross over Y serie.
"""
return x[-1] > y[-1] and x[-2] < y[-2] | bigcode/self-oss-instruct-sc2-concepts |
def ConvertToEnum(versioned_expr, messages):
"""Converts a string version of a versioned expr to the enum representation.
Args:
versioned_expr: string, string version of versioned expr to convert.
messages: messages, The set of available messages.
Returns:
A versioned expression enum.
"""
return... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def bound_signature(method):
"""Return the signature of a method when bound."""
sig = inspect.signature(method)
param = list(sig.parameters.values())[1:]
return inspect.Signature(param, return_annotation=sig.return_annotation) | bigcode/self-oss-instruct-sc2-concepts |
def _ip_bridge_cmd(action, params, device):
"""Build commands to add/del ips to bridges/devices."""
cmd = ['ip', 'addr', action]
cmd.extend(params)
cmd.extend(['dev', device])
return cmd | bigcode/self-oss-instruct-sc2-concepts |
def archimedes(q1, q2, q3):
"""
This is the difference between the lhs and the rhs of the
TripleQuadForumula. [MF 124 @ 2:23].
The TQF is satisfied when this is zero.
Given:
TQF: ((q1 + q2 + q3) ** 2) == (2 * (q1 ** 2 + q2 ** 2 + q3 ** 3))
Define:
A(q1, q2, q3) = ((q1 + q2 + ... | bigcode/self-oss-instruct-sc2-concepts |
def basis_function_one(degree, knot_vector, span, knot):
""" Computes the value of a basis function for a single parameter.
Implementation of Algorithm 2.4 from The NURBS Book by Piegl & Tiller.
:param degree: degree, :math:`p`
:type degree: int
:param knot_vector: knot vector
:type knot_vecto... | bigcode/self-oss-instruct-sc2-concepts |
def append_with_phrases(tokens, phrases):
"""Append phrases to the tokens.
Args:
tokens (list of str): A list of tokens.
phrases (list of str): A list of phrases.
Returns:
list of str: A concatinated list of tokens and phrases.
"""
return tokens + phrases | bigcode/self-oss-instruct-sc2-concepts |
import json
def open_json(filename):
"""Opens the json file
Parameters
----------------
filename: string
Full file path for json file
Returns
----------------
jsonf: dictionary
Json file is opened and ready to be used by other functions in this code
Cont... | bigcode/self-oss-instruct-sc2-concepts |
def get_indexed_constraint_body(backend_model, constraint, input_index):
"""
Return all indeces of a specific decision variable used in a constraint.
This is useful to check that all expected loc_techs are in a summation.
Parameters
----------
backend_model : Pyomo ConcreteModel
constraint ... | bigcode/self-oss-instruct-sc2-concepts |
import base64
def Base64WSDecode(s):
"""
Return decoded version of given Base64 string. Ignore whitespace.
Uses URL-safe alphabet: - replaces +, _ replaces /. Will convert s of type
unicode to string type first.
@param s: Base64 string to decode
@type s: string
@return: original string that was encod... | bigcode/self-oss-instruct-sc2-concepts |
def all_prime_factors(p: int) -> list:
"""
Returns a list of distinct
prime factors of the number p
"""
factors = []
loop = 2
while loop <= p:
if p % loop == 0:
p //= loop
factors.append(loop)
else:
loop += 1
return factors | bigcode/self-oss-instruct-sc2-concepts |
import csv
def csv_file_to_nested_dict(filename, primary_key_col):
"""
assumes the first line of the csv is column names. loads each line
into a dict of kvps where key is column name and value is the value
in the cell.
Puts all of these kvp dicts into one top level dict, where the key
is the... | bigcode/self-oss-instruct-sc2-concepts |
def subsample(input_list, sample_size, rnd_generator):
"""Returns a list that is a random subsample of the input list.
Args:
input_list: List of elements of any type
sample_size: Int. How many elements of input_list should be in the output list
rnd_generator: initialized random generato... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def modify_str_int_value(value) -> Union[str, int]:
"""SQL query needs quotes present for string values. Return value if value is integer else return value wrapped
in quotes."""
return value if isinstance(value, int) else f"'{value}'" | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import glob
def list_temp_files(directory):
"""List all temporary files within a directory which are marked with *temp* in their name"""
try:
dir_path = Path(directory)
assert dir_path.exists()
except Exception:
raise Exception(f"Expected absolute path to v... | bigcode/self-oss-instruct-sc2-concepts |
def retry(limit=1):
"""
Retry a failing function `n` times or until it executes successfully. If the function does not complete
successfully by the nth retry, then the exception will be reraised for the executing code to handle.
Example:
::
root@710027b06106:/plsnocrash/examples# cat retr... | bigcode/self-oss-instruct-sc2-concepts |
import re
def fix_text(text):
"""
Method to fix up bad text from feeds
:param text: Text to cleanup
:return: Fixed text
"""
if text is None:
text = ""
text = re.sub(r"[]^\\-]", " ", text)
return text | bigcode/self-oss-instruct-sc2-concepts |
def get_integer_form(elem_list):
"""For an element list like ['e1', 'a1_2', 'a1_1', 'a1_3'],
return the integer 213, i.e., the 'subscripts' of the elements that
follow the identity element."""
return int(''.join(map(lambda x: x.split("_")[1], elem_list[1:]))) | bigcode/self-oss-instruct-sc2-concepts |
def java_type_boxed(typ):
"""Returns the java boxed type."""
boxed_map = {
'boolean': 'Boolean',
'byte': 'Byte',
'char': 'Character',
'float': 'Float',
'int': 'Integer',
'long': 'Long',
'short': 'Short',
'double': 'Double'
}
if typ in boxed_map:
return boxed_... | bigcode/self-oss-instruct-sc2-concepts |
def filter_spatiotemporal(search_results):
"""
Returns a list of dictionaries containing time_start, time_end and extent polygons for granules
:search_results: dictionary object returned by search_granules
:returns: list of dictionaries or empty list of no entries or keys do not exist
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def rescale_contours(cnts, ratio):
"""
Rescales contours based on scalling `ratio`.
Args:
cnts (list of contour objects):
List of `numpy.ndarray` objects representing contours from OpenCV.
ratio (float):
Float value used to rescale all the points in contours list.
... | bigcode/self-oss-instruct-sc2-concepts |
def turn(orientation, direction):
"""Given an orientation on the compass
and a direction ("L" or "R"), return a
a new orientation after turning 90 deg
in the specified direction."""
compass = ['N', 'E', 'S', 'W']
if orientation not in compass:
raise ValueError('orientation must be N, E, ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def filter_star_import(line, marked_star_import_undefined_name):
"""Return line with the star import expanded."""
undefined_name = sorted(set(marked_star_import_undefined_name))
return re.sub(r'\*', ', '.join(undefined_name), line) | bigcode/self-oss-instruct-sc2-concepts |
def pathToString(filepath):
"""
Coerces pathlib Path objects to a string (only python version 3.6+)
any other objects passed to this function will be returned as is.
This WILL NOT work with on Python 3.4, 3.5 since the __fspath__ dunder
method did not exist in those verisions, however psychopy does ... | bigcode/self-oss-instruct-sc2-concepts |
def get_count(line):
"""
Return the count number from the log line
"""
return line.rstrip().split(":")[-1].strip() | bigcode/self-oss-instruct-sc2-concepts |
import hmac
import hashlib
def do_hmac(key, value):
"""Generate HMAC"""
h = hmac.new(key, msg=None, digestmod=hashlib.sha384)
h.update(value.encode("utf-8"))
return h.hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def if_columns(x):
"""
This function suffixes '_columns' to a dataframe (when saving it as a file) if columns are specified and
suffixes '_dataframe' no columns are specified (i.e. when the user wants to do EDA of the entire dataset).
:param x: list of columns
:return: '_columns' suffix if list of c... | bigcode/self-oss-instruct-sc2-concepts |
def historical_imagery_photo_type_to_linz_geospatial_type(photo_type: str) -> str:
"""Find value in dict and return linz_geospatial_type,
else return the original value string.
"""
geospatial_type_conversion_table = {
"B&W": "black and white image",
"B&W IR": "black and white infrared im... | bigcode/self-oss-instruct-sc2-concepts |
def bin(s, m=1):
"""Converts the number s into its binary representation (as a string)"""
return str(m*s) if s<=1 else bin(s>>1, m) + str(m*(s&1)) | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def get_des_vars_and_qois(discipline):
"""Method to get the relevant design variables and quantities of interest for a specific subsystem.
:param discipline: name of the discipline (structures, aerodynamics, propulsion)
:type discipline: basestring
:return: ordered dict... | bigcode/self-oss-instruct-sc2-concepts |
def max_length(tensor):
"""Function that returns the maximum length of any element in a given tensor"""
return max(len(tensor_unit) for tensor_unit in tensor) | bigcode/self-oss-instruct-sc2-concepts |
def parse_production_company(movie):
"""
Convert production companies to a dictionnary for dataframe.
Keeping only 3 production companies.
:param movie: movie dictionnary
:return: well-formated dictionnary with production companies
"""
parsed_production_co = {}
top_k = 3
productio... | 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.