seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import string
import random
def generate_keyword(chars=None, k_length=None):
"""
Generate keyword for annotators and batches.
Args:
chars (str): type of characters used to generate keyword,
*default:* ``string.ascii_letters+string.digits``
k_length (int): length of the keyword, *default:* ``random.randin... | bigcode/self-oss-instruct-sc2-concepts |
def format_size(size):
""" Format into byes, KB, MB & GB """
power = 2**10
i = 0
power_labels = {0: 'bytes', 1: 'KB', 2: 'MB', 3: 'GB'}
while size > power:
size /= power
i += 1
return f"{round(size, 2)} {power_labels[i]}" | bigcode/self-oss-instruct-sc2-concepts |
def get_user_decision(soup, code_block):
"""Gets user input on a comment it's not able to classify.
Separate multiple languages in a single post with a '/'.
"""
print("Need input.", soup.prettify(), sep="\n")
while True:
language = input("Language (<Enter> for None): ") or "None"
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
import json
def read_dict(file_path: str) -> Dict:
""" Read dictionary from path"""
with open(file_path) as f:
return json.load(f) | bigcode/self-oss-instruct-sc2-concepts |
def patch_save_intermediate_df(mocker):
"""Patch the save_intermediate_df function."""
return mocker.patch("src.make_feedback_tool_data.make_data_for_feedback_tool.save_intermediate_df") | bigcode/self-oss-instruct-sc2-concepts |
def pretty(sbox):
""" Return a pretty printed SBox. """
# List of Columns
p = '\nS-BOX '
for i in range(16):
p += '%02x' % i + ' '
p += '\n'
for i in range(70):
p += '-'
p += '\n'
# Row
for i in range(16):
p += '%02x' % i + ' | '
# Entries
... | bigcode/self-oss-instruct-sc2-concepts |
import mimetypes
def getMimeType(pathToFile):
"""returns mime type
Args:
pathToFile (String): absolute path
Returns:
String: mime type
"""
mime = mimetypes.guess_type(pathToFile, strict=True)
return mime[0] | bigcode/self-oss-instruct-sc2-concepts |
def minimal_generalizations_cons(h,d):
"""returns all minimal generalizations of h that are consistent
with positive example d"""
generalizations=set()
mg=[f for f in h]
for i,f in enumerate(h):
if f!=d[i]:
if f!="0":
mg[i]="?"
else:
mg... | bigcode/self-oss-instruct-sc2-concepts |
def human_file_size(num):
"""Readable file size"""
for unit in ["", "KB", "MB", "GB", "TB", "PB", "EB", "ZB"]:
if abs(num) < 1024.0:
return "%3.1f %s" % (num, unit)
num /= 1024.0
return "%.1f%s" % (num, "YB") | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def partition(iterable, k):
"""
Partition finite iterable into k almost-equal partitions in round-robin manner.
:type iterable: iterable
:param iterable: A finite iterable.
:type k: int
:param k: Number of partitions.
:rtype: list
:returns: List of lists of partition... | bigcode/self-oss-instruct-sc2-concepts |
def set_name_from_dict(string, dictionary, key, leading, trailing):
"""Replaces the string with the value from a specified dictionary key,
prepending and appending the leading/trailing text as applicable"""
return "{}{}{}".format(leading,
dictionary[key],
... | bigcode/self-oss-instruct-sc2-concepts |
def hourly_indicators(df, capacity):
"""
Compute the indicators based on the df profile
>>> df = pd.Series([0.2, 0, 0, 1] , index=pd.date_range('2000',
... freq='h', periods=4))
>>> hourly_indicators(df, 1)
(1.2, 2, 1.2)
"""
# there is no difference by using integration ... | bigcode/self-oss-instruct-sc2-concepts |
def toStringArray(name, a, width = 0):
"""
Returns an array (any sequence of floats, really) as a string.
"""
string = name + ": "
cnt = 0
for i in a:
string += "%4.2f " % i
if width > 0 and (cnt + 1) % width == 0:
string += '\n'
cnt += 1
return string | bigcode/self-oss-instruct-sc2-concepts |
def darpaNodeNet(node_id):
"""Return IP subnet of radio node on DARPA's network."""
return '192.168.{:d}.0'.format(node_id+100) | bigcode/self-oss-instruct-sc2-concepts |
from sympy.stats.stochastic_process_types import StochasticProcess
def sample_stochastic_process(process):
"""
This function is used to sample from stochastic process.
Parameters
==========
process: StochasticProcess
Process used to extract the samples. It must be an instance of
... | bigcode/self-oss-instruct-sc2-concepts |
def make_title(passage_name, process=True, line_end=''):
"""Make a valid page header from a name"""
passage_name = passage_name.lower() if process else passage_name
return f':: {passage_name}{line_end}' | bigcode/self-oss-instruct-sc2-concepts |
def challenge(authentication, realm):
"""Constructs the string to be sent in the WWW-Authenticate header"""
return u"{0} realm=\"{1}\"".format(authentication, realm) | bigcode/self-oss-instruct-sc2-concepts |
def timesteps(paths):
"""Return the total number of timesteps in a list of trajectories"""
return sum(len(path.rewards) for path in paths) | bigcode/self-oss-instruct-sc2-concepts |
def flag_to_list(flagval, flagtype):
"""Convert a string of comma-separated tf flags to a list of values."""
if flagtype == 'int':
return [int(_) for _ in flagval.split(',') if _]
elif flagtype == 'float':
return [float(_) for _ in flagval.split(',') if _]
elif flagtype == 'str':
... | bigcode/self-oss-instruct-sc2-concepts |
def get_open_pull_requests(repo=None, base=None):
"""
retrieve open pull requests from specified repository
:param repo:
:param base:
:return github.PaginatedList.PaginatedList
"""
if not repo:
raise ValueError("you must provide repo")
if not base:
raise ValueError("yo... | bigcode/self-oss-instruct-sc2-concepts |
def is_prolog_functor(json_term):
"""
True if json_term is Prolog JSON representing a Prolog functor (i.e. a term with zero or more arguments). See `swiplserver.prologserver` for documentation on the Prolog JSON format.
"""
return (
isinstance(json_term, dict) and "functor" in json_term and "ar... | bigcode/self-oss-instruct-sc2-concepts |
def get_cmd_param(command, input):
"""return word after command if input starts with command, otherwise return None"""
cl = command.lower()
il = input.lower()
n1 = len(command)
n2 = len(input)
if n1 > n2 or not il.startswith(cl):
return None # it is not command
return input[n1:].lstrip() | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def make_file(dir: Path, f: Path):
"""outputs a file in a dir using the current file features"""
output = dir / (f"{f.stem}_cookies{f.suffix}")
if not output.exists():
output.touch()
return output | bigcode/self-oss-instruct-sc2-concepts |
import linecache
def checkline(filename, lineno, ui):
"""Return line number of first line at or after input
argument such that if the input points to a 'def', the
returned line number is the first
non-blank/non-comment line to follow. If the input
points to a blank or comment line, return 0. At ... | bigcode/self-oss-instruct-sc2-concepts |
def _is_none(arg):
"""Check if argument is None."""
return arg is None | bigcode/self-oss-instruct-sc2-concepts |
import re
def _match_trainid(value):
"""Return the trainID in value, None if no trainID."""
mat = re.search(r"TR(\d{4})", value)
if mat is not None and len(mat.groups()) > 0:
return mat.groups()[0]
return None | bigcode/self-oss-instruct-sc2-concepts |
def argument_parser(input_args):
"""
Returns a list of tokens for a given argument
:param input_args: input string
:return: argument list
"""
arguments = input_args.split(' ')
if len(arguments) > 1:
return arguments[1:]
else:
return arguments | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
from typing import Any
def _add_conditions(hyperparameters: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Returns a list of conditions in a format that is compatible with the json
reader of the ConfigSpace API.
The conditions are used to activate and de... | bigcode/self-oss-instruct-sc2-concepts |
def capitalize_first(x):
"""
This function upper-cases only the first letter, unlike
.capitalize() that leaves the other letters uppercase. It
leaves other letters as they were.
"""
return x[0].capitalize() + x[1:] if len(x) > 0 else x | bigcode/self-oss-instruct-sc2-concepts |
def getFilePath(id):
"""Retrieves file path and name, given file entry ID
Args:
id (str): File entry ID to get details of
Returns:
dict: Object contains file ID, path and name
"""
return {'id': id, 'path': 'test/test.txt', 'name': 'test.txt'} | bigcode/self-oss-instruct-sc2-concepts |
def width(canv):
"""
gets the height of the canvas
:param canv:
:return: integer height of the canvas
"""
return (canv and len(canv[0])) or 0 | bigcode/self-oss-instruct-sc2-concepts |
def kl_div(mean, logvar):
"""Computes KL Divergence between a given normal distribution
and a standard normal distribution
Parameters
----------
mean : torch.tensor
mean of the normal distribution of shape (batch_size x latent_dim)
logvar : torch.tensor
diagonal log variance of... | bigcode/self-oss-instruct-sc2-concepts |
def string_ancilla_mask(location, length):
"""Returns a bit string with a 1 in a certain bit and the 0 elsewhere.
Parameters
----------
location : int
location of the bit which should be set to '1' in the mask
length : int
length of string in the mask
Returns
------... | bigcode/self-oss-instruct-sc2-concepts |
import _struct
def parse_notify_req(pkt):
"""Parse a notification request.
pkt -- raw packet data (str).
Returns: (service, userid, messid, data)
"""
NOTIFY_REQ_LEN = 12 # Minimum packet size for notifications
if len(pkt) < NOTIFY_REQ_LEN:
raise ValueError("Invalid packe... | bigcode/self-oss-instruct-sc2-concepts |
def overlap(x1, x2, y1, y2):
"""
Return True iff [x1:x2] overlaps with [y1:y2]
"""
if not all([isinstance(i, int) for i in [x1, x2, y1, y2]]):
return False
return ((y1 <= x1 <= y2) or
(y1 <= x2 <= y2) or
(x1 <= y1 <= x2) or
(x1 <= y2 <= x2)) | bigcode/self-oss-instruct-sc2-concepts |
def float2transparency(value: float) -> int:
"""
Returns DXF transparency value as integer in the range from ``0`` to ``255``, where ``0`` is 100% transparent
and ``255`` is opaque.
Args:
value: transparency value as float in the range from ``0`` to ``1``, where ``0`` is opaque
a... | bigcode/self-oss-instruct-sc2-concepts |
def is_in_groups(user, group_names):
"""
Returns True if the user is a member of any groups given their names in group_names
"""
return any(user.groups.filter(name=group_name).exists() for group_name in group_names) | bigcode/self-oss-instruct-sc2-concepts |
def illinois_algorithm(f, a, b, y, margin=1e-5):
"""
Bracketed approach of Root-finding with illinois method.
Parameters
----------
f : callable
Continuous function.
a : float
Lower bound to be searched.
b : float
Upper bound to be searched.
y : float
... | bigcode/self-oss-instruct-sc2-concepts |
def get_choice_menu() -> str:
"""
Display the menu and ask for the choice from the user.
Returns
-------
choice: str
The valid choice enter by the user.
"""
valid_choice_list = ['0', '1', '2', '3']
choice = ''
menu = (
'1. Start new game\n'
... | bigcode/self-oss-instruct-sc2-concepts |
import math
def compute_entropy(_list):
"""
计算熵 https://zh.wikipedia.org/zh-hans/%E7%86%B5_(%E4%BF%A1%E6%81%AF%E8%AE%BA)
https://baike.baidu.com/item/熵/19190273
Calculating entropy
:param _list:
:return:
"""
length = float(len(_list))
frequence = {}
if length == 0:
... | bigcode/self-oss-instruct-sc2-concepts |
def MEAN(src_column):
"""
Builtin average aggregator for groupby. Synonym for tc.aggregate.AVG. If
src_column is of array type, and if array's do not match in length a NoneType is
returned in the destination column.
Example: Get the average rating of each user.
>>> sf.groupby("user",
... {'r... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_model_pkl(path):
""" loads a model stored as pickle file (e.g. from sklearn) """
with open(path, 'rb') as f:
return pickle.load(f) | bigcode/self-oss-instruct-sc2-concepts |
import requests
import zipfile
import io
def downloadZipFile(url, directory):
"""
Multimedia Content are stored in cloud in ecar or zip format.
This function downloads a zip file pointed by url location.
The user is expected to have access to the file pointed by url.
The extracted file is availab... | bigcode/self-oss-instruct-sc2-concepts |
def get_discussion_id_map_entry(xblock):
"""
Returns a tuple of (discussion_id, metadata) suitable for inclusion in the results of get_discussion_id_map().
"""
return (
xblock.discussion_id,
{
"location": xblock.location,
"title": xblock.discussion_category.split(... | bigcode/self-oss-instruct-sc2-concepts |
def parse_directions_response(directions_response):
"""Extract basic information relevant to route from the response.
Args:
directions_response: list of directions in the deserialized
Maps API response format
Returns:
if a valid route is found a tuple containing:
a list of the (lat,lon) points ... | bigcode/self-oss-instruct-sc2-concepts |
def to_percentage(number):
"""
Formats a number as a percentage, including the % symbol at the end of the string
"""
return "{:.2%}".format(number) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def diagonal_distance(pa : Tuple[int, int], pb : Tuple[int, int]) -> int:
"""
Gets manhattan distance with diagonals between points pa and pb.
I don't know what this is called, but the fastest route is to take the
diagonal and then do any excess.
"""
(ax, ay) = pa
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_invocation_allowed(command_requested, exact_allowed=[], regex_allowed=[]):
"""
Check if command_requested is an element of exact_allowed or if it
matches a pattern in regex_allowed. If so, then return True.
"""
allowed = False
if command_requested in exact_allowed:
... | bigcode/self-oss-instruct-sc2-concepts |
import click
def conditional_argument(condition, *param_decls, **attrs):
"""
Attaches an argument to the command only when condition is True
"""
def decorator(f):
if condition:
f = click.argument(*param_decls, **attrs)(f)
return f
return decorator | bigcode/self-oss-instruct-sc2-concepts |
def windows_matcher(repository_ctx):
"""Matches Windows."""
if repository_ctx.os.name.lower().find("windows") != -1:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
from typing import List
def pad_line_to_ontonotes(line: Tuple[str, ...], domain: str) -> List[str]:
"""
Pad line to conform to OntoNotes representation.
"""
word_ind, word = line[:2]
pos = "XX"
oie_tags = line[2:]
line_num = "0"
parse = "-"
lemma = "-"
... | bigcode/self-oss-instruct-sc2-concepts |
def buy_signal(df):
"""Function calculates signal to open long position
Args:
df (pandas.DataFrame): pandas.DataFrame
Returns:
string: return "Buy" if condition is met else False
"""
tsi = df["TSI"]
tsi_ma = df["TSI_MA"]
signal = ""
if ((tsi[-2] < 0 and tsi_ma[-1] < 0)... | bigcode/self-oss-instruct-sc2-concepts |
def strahler_stream_order(start_arc_id, start_up_node,
nodes_per_arc, arcs_per_node, stream_orders):
"""Calculate the Strahler stream order
This function recursively computes the Strahler stream order using
the algorithm described by Gleyzer et al. (2004). The sequence of
stre... | bigcode/self-oss-instruct-sc2-concepts |
import math
def _distance(loc1, loc2):
"""
Returns the Euclidean distance between two co-ordinates in
km
"""
R_EARTH = 6378.1
lat1_rad = math.radians(loc1[0])
lat2_rad = math.radians(loc2[0])
lon1_rad = math.radians(loc1[1])
lon2_rad = math.radians(loc2[1])
delta_lat = lat1_ra... | bigcode/self-oss-instruct-sc2-concepts |
def has_c19_tag (tags):
""" Check if the COVID-19 tag is present """
for tag in tags:
if tag.vocabulary == "99" and tag.code.upper() == "COVID-19":
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import json
def load_namelist(namelist_path:str):
"""Given path to `namelist.in` file, load and return as a nested dictionary."""
with open(namelist_path, 'r') as f:
namelist = json.load(f)
return namelist | bigcode/self-oss-instruct-sc2-concepts |
def exclude_targets(*args):
"""Exclude a test from running on a particular target.
Use this decorator when you want your test to be run over a
variety of targets and devices (including cpu and gpu devices),
but want to exclude some particular target or targets. For
example, a test may wish to be r... | bigcode/self-oss-instruct-sc2-concepts |
import click
def demander_mouvement(mvmts_possibles: str):
""" Fonction qui demande au joueur le mouvement qu'il souhaite effectuer
Args:
mvmts_possibles (str): Mouvements que le joueur peut faire
Retourne:
str: Mouvement choisi par le joueur
H : Aller vers le Haut
B : Aller vers le Bas
... | bigcode/self-oss-instruct-sc2-concepts |
def shape_attr_name(name, length=6, keep_layer=False):
"""
Function for to format an array name to a maximum of 10 characters to
conform with ESRI shapefile maximum attribute name length
Parameters
----------
name : string
data array name
length : int
maximum length of strin... | bigcode/self-oss-instruct-sc2-concepts |
def attention_padding_mask(q, k, padding_index=0):
"""Generate mask tensor for padding value
Args:
q (Tensor): (B, T_q)
k (Tensor): (B, T_k)
padding_index (int): padding index. Default: 0
Returns:
(torch.BoolTensor): Mask with shape (B, T_q, T_k). True element stands for re... | bigcode/self-oss-instruct-sc2-concepts |
def lowercase_dict(original):
"""Copies the given dictionary ensuring all keys are lowercase strings. """
copy = {}
for key in original:
copy[key.lower()] = original[key]
return copy | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
import re
def convert_sequence_to_text(
schema_name: str,
schema_desc: str,
sequence: Sequence[str],
) -> str:
"""Converts sequence to text to use as GPT-2 input.
Args:
schema_name: Name of schema to run on.
schema_desc: Description / definition of the ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_error_from_html(html_error, v1=False):
"""This function parses an error message from Khoros displayed in HTML format.
.. versionchanged:: 2.0.0
Added the ``v1`` Boolean argument
:param html_error: The raw HTML returned via the :py:mod:`requests` module
:type html_error: str
... | bigcode/self-oss-instruct-sc2-concepts |
def _break_crt_chain(buffer):
"""Breaks the certificate chain string into a list.
Splits the cert chain with "-----END CERTIFICATE-----".
There are two cases to consider:
1) Certificates ending on "-----END CERTIFICATE-----"
2) Certificates ending on "-----END CERTIFICATE-----\n"
In case (1),... | bigcode/self-oss-instruct-sc2-concepts |
def mkfile(name, meta={}):
"""Return file node."""
return {
'name': name,
'meta': meta,
'type': 'file'
} | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_pickle(file_path = "data.pickle"):
"""
Loads a pickle file created with `create_pickle()`
:param file_path: Path of pickle file
:type file_path: str
:return: Serialized object
:rtype: object
"""
with open(file_path, "rb") as readFile:
data = pickle.load(... | bigcode/self-oss-instruct-sc2-concepts |
def plotFinal(solPlot,aSolPlot,tn,test,tpars,problems,
mlMesh,mlScalarTransport,testOut):
"""
plot out solution and mesh at last step in a couple of formats
"""
if tpars['DG'] == False:
solPlot.hardcopy(testOut+'_sol.eps', eps=1,enhanced=1,color=1)
aSolPlot.hardcopy(testOut... | bigcode/self-oss-instruct-sc2-concepts |
import re
import yaml
def parse_front_matter_and_content(
contents: list[str],
) -> tuple[dict[str, str], list[str]]:
"""
Parse a list of all lines in a file into:
front matter (merged result of existing ones and title + preview image)
all markdown lines in the content apart from the recipe na... | bigcode/self-oss-instruct-sc2-concepts |
def get_mean_and_med_age(d):
"""
Calculate mean and median age of passengers
:param d: data frame
:return: rounded mean amd median
"""
return round(d['Age'].mean(), 2), d['Age'].median() | bigcode/self-oss-instruct-sc2-concepts |
def hzip(x):
"""
Zips the first and second half of `x`.
If `x` has odd length, the last element will be ignored.
>>> list(hzip([1, 2, 3, 4, 5, 6]))
[(1, 4), (2, 5), (3, 6)]
>>> list(hzip([1, 2, 3, 4, 5, 6, 7]))
[(1, 4), (2, 5), (3, 6)]
"""
N = int(len(x) // 2)
return zip(x[:N... | bigcode/self-oss-instruct-sc2-concepts |
def human_readable_number(number: float) -> str:
"""Print a large number in a readable format.
Return a readable format for a number, e.g. 123 milions becomes 123M.
Args:
number: a float to be printed in human readable format.
Returns:
readable_number: a string containing the formatted number.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def write_dot(g):
"""Replacement for pygraph.readwrite.dot.write, which is dog slow.
Note:
This isn't a general replacement. It will work for the graphs that
Rez generates, but there are no guarantees beyond that.
Args:
g (`pygraph.digraph`): Input graph.
Returns:
str:... | bigcode/self-oss-instruct-sc2-concepts |
def simplify(conc_results):
"""Turn concordance output into something slightly more human-readable"""
out = []
for r in conc_results:
if len(r) == 3:
out.append(
[r[1][0], r[1][1]] +
[r[0][i] for i in r[0][-1]]
)
else: # Have context a... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _results_from_main_index(fields, query_regex, time_series_stem=''):
"""_results_from_main_index
Returns dictionary mapping elasticsearch field names from fields
to pairs containing that field's values that match query_regex,
and a boolean indicating if the field is a time series
fie... | bigcode/self-oss-instruct-sc2-concepts |
def getFrameIndex(t, fs):
"""
calculates and returns the frame index of at a given time offset
within a signal
@param t the time offset [s]
@param fs sampling frequency [Hz]
"""
return int(round(float(t) * float(fs))) | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_filename(cd: str) -> str:
"""Returns filename from content disposition header."""
return re.findall(r'filename\*?=[\'"]?(?:UTF-\d[\'"]*)?([^;\r\n"\']*)[\'"]?;?', cd)[0] | bigcode/self-oss-instruct-sc2-concepts |
import re
def natsort(s):
"""
Natural sorting, e.g. test3 comes before test100.
Taken from https://stackoverflow.com/a/16090640/3110740
"""
# if not isinstance(s, (str, bytes)): return s
x = [int(t) if t.isdigit() else t.lower() for t in re.split('([0-9]+)', s)]
return x | bigcode/self-oss-instruct-sc2-concepts |
def size_from_shape(shape):
"""Returns size from the shape sequence
"""
size=1
for d in shape: size*=d
return size | bigcode/self-oss-instruct-sc2-concepts |
def remove_suffix(x, suffix=" "):
"""
Remove a specific suffix from the end of a string.
"""
if x.endswith(suffix):
x = x[: -len(suffix)]
return x | bigcode/self-oss-instruct-sc2-concepts |
def collatzSeq(n, outputSeq = None):
"""
collatzSeq(int, list) -> list
accepts two inputs:
- n (required): the integer against which the conjecture is about to be tested
- outputSeq (optional): only used during ricursion to store the state of the current test
"""
if outputSeq is None:
... | bigcode/self-oss-instruct-sc2-concepts |
def is_boolean(op):
"""
Tests whether an operation requires conversion to boolean.
"""
return op in ['or', 'and', '!'] | bigcode/self-oss-instruct-sc2-concepts |
def notas(*notasalunos, sit=False):
"""
Função para analisar notas de alunos e situações da turma.
:param notasalunos: uma ou mais notas de alunos.
:param sit: (valor opcional). Se True, mostra a situação da turma.
:return: dicionário com várias informações sobre a situação da turma.
"""
con... | bigcode/self-oss-instruct-sc2-concepts |
def dumps(name, namelist):
"""
Writes a namelist to a string.
Parameters
----------
name : str
The name of the namelist
namelist : dict
Members of the namelist
Returns
-------
str
String representation of the namelist
"""
# start with the opening mar... | bigcode/self-oss-instruct-sc2-concepts |
def trimquotes(s):
"""
Remove the single quotes around an expression::
trimquotes("'test'") == "test"
:param s: expression to transform
:type s: string
:rtype: string
"""
if not s: return ''
s = s.rstrip()
if s[0] == "'" and s[-1] == "'": return s[1:-1]
return s | bigcode/self-oss-instruct-sc2-concepts |
def sumall(*args):
"""
Take any number of arguments and return their sum
"""
sumall = 0
sumall = sum(args[0], *args[1:])
return sumall | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import MutableSequence
def ensure_list(value: Any, convert_csv: bool = False, delimiter: str = ',') -> MutableSequence[Any]:
"""Convert an object, response, or (optionally) comma-separated string into a list"""
if not value:
return []
elif isinstance(value, dict)... | bigcode/self-oss-instruct-sc2-concepts |
def _player_n_frame(base_df, n):
"""Create a dataframe of player level results for the nth player in a game frame
This just gets called in player_level_df, doesn't need to be called directly
Properties
----------
base_df: pd.DataFrame
game level dataframe
n: int
the player ... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def warp_homography(sources, homography):
"""Warp features given a homography
Parameters
----------
sources: torch.tensor (1,H,W,2)
Keypoint vector.
homography: torch.Tensor (3,3)
Homography.
Returns
-------
warped_sources: torch.tensor (1,H,W,2)
... | bigcode/self-oss-instruct-sc2-concepts |
def edges_to_line(edges, N):
""" Returns a list of integers corresponding to a relabellign of the edge
tuples by mapping (i,j) --> to N*i + j as per my convention for labelling
of lineP, lineT.
"""
def relabel(edge):
return N*edge[0] +edge[1]
newlist = list(map(relabel, edges))
retu... | bigcode/self-oss-instruct-sc2-concepts |
import re
def search_re(out, l):
""" Search the regular expression 'l' in the output 'out'
and return the start index when successful.
"""
m = re.search(l, out)
if m:
return m.start()
return None | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
import multiprocessing
import re
def parse_num_processors(value: Union[str, int, float]):
"""Convert input value (parse if string) to number of processors.
Args:
value: an int, float or string; string value can be "X" or "MAX-X"
Returns:
An int of the number of pro... | bigcode/self-oss-instruct-sc2-concepts |
def TagValues(d, lstTagValues):
"""
Return TRUE if you have a match within the list of tags (strings)
"""
bool = False
if d['TAG'] in lstTagValues:
bool = True
return bool | bigcode/self-oss-instruct-sc2-concepts |
def shift_TTD_dailyconservation_idx_rule(M):
"""
Index is (window, day, week, tour type).
The index set gets used in the TTD_TTDS_con and TTD_TT_UB constraints.
:param M:
:return: Constraint index rule
"""
return [(i, j, w, t) for i in M.WINDOWS
for j in M.DAYS
for ... | bigcode/self-oss-instruct-sc2-concepts |
def containsExploit(text: str) -> bool:
""" Returns whether or not the given str contains evidence that it is a sqli exploit """
return ('or' in text.lower() or
'and' in text.lower() or
'select' in text.lower() or
'from' in text.lower() or
'where' in text.lower()) | bigcode/self-oss-instruct-sc2-concepts |
def snake_to_camelcase(name: str) -> str:
"""Convert snake-case string to camel-case string."""
return "".join(n.capitalize() for n in name.split("_")) | bigcode/self-oss-instruct-sc2-concepts |
def create_curl_command(authorization, payload, command, url, curl_options, show_api_key,
content_type='application/json'):
"""
cURL command generator
:param authorization: Authorization part e.g Bearer API key
:param payload: Payload data
:param command: GET, PUT, etc
:p... | bigcode/self-oss-instruct-sc2-concepts |
def getFullPath(request):
"""Get full URL path from the request
"""
# When testing, there is no request.META['HTTP_HOST'] in Django test client
host = request.META.get('HTTP_HOST', 'none')
full_path = ('http', ('', 's')[request.is_secure()], \
'://', host, request.path)
return '... | bigcode/self-oss-instruct-sc2-concepts |
def is_point_inside_rect(point: tuple, rect:tuple):
"""Returns whether a point is inside a rectangular region
Args:
point (tuple): The point to be tested
rect (tuple): A rectangular region coordinates (up_left_x,upleft_y,bottom_right_x,bottom_right_y)
Returns:
boolean: If true then ... | bigcode/self-oss-instruct-sc2-concepts |
def is_list(value):
"""
Tests the value to determine whether it is a list.
:param any value:
:return: True of the value is a list (an instance of the list class)
>>> is_list( 'Hello' )
False
>>> is_list( ['Hello'] )
True
"""
return isinstance(value, list) | bigcode/self-oss-instruct-sc2-concepts |
def sents_sync(ck_sents, sj_sents):
"""
check if two sentences are same.
if there're differences, return the list to banish.
:param ck_sents:
:param sj_sents:
:return:
"""
# ck_sents = mk_sents_with_lemma(ck_file, 3)
# sj_sents = mk_sents_with_lemma(sj_file, 2)
# ck_sents = mk_s... | 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.