seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def get_images(data):
"""
Get all images from facebook JSON response,
or return None if no data present.
"""
try:
return data['data']
except KeyError:
return [] | bigcode/self-oss-instruct-sc2-concepts |
def _get_acf_params(p):
"""Get ACF parameters from the given parameter vector."""
return p[0], p[1], p[2], p[3] * p[2] | bigcode/self-oss-instruct-sc2-concepts |
def pad(str_float_value):
"""
Pad value with zeroes to 8 digits after dot
"""
return "%.8f"%float(str_float_value) | bigcode/self-oss-instruct-sc2-concepts |
def url_path(url):
"""
Construct a path string for a Hyperlink URL.
:type url: hyperlink.URL
:param url: URL.
:rtype: unicode
"""
return (u'/' if url.rooted else u'') + u'/'.join(url.path) | bigcode/self-oss-instruct-sc2-concepts |
def get_node_color_map(selected_events):
"""Generate color map for all organism groups in selected_events.
This is done dynamically for each node-link diagram, because it
minimizes collisions.
:param selected_events: Specified organism_group-organism_group
relationships inside nested dictionary.
... | bigcode/self-oss-instruct-sc2-concepts |
def send_message(service, message):
"""Sends an email message."""
return service.users().messages().send(userId="me", body=message).execute() | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def last_modified(path: pathlib.Path) -> float:
"""Returns the timestamp of the last modification of a file.
Parameters
----------
path
File path.
"""
path = pathlib.Path(path)
return path.stat().st_mtime | bigcode/self-oss-instruct-sc2-concepts |
def scrape_quotes_container(soup):
"""Get the quote container from a quote page.
Args:
soup (bs4.element.Tag): connection to the quote page.
Returns:
bs4.element.Tag
"""
return soup.findAll('div', attrs={'class': 'quotes'}) | bigcode/self-oss-instruct-sc2-concepts |
def get_remote_url(remote_url):
"""
Takes a GitHub remote URL (e.g., `mozilla/fireplace`) and
returns full remote URL (e.g., `git@github.com:mozilla/fireplace.git`).
"""
if ':' not in remote_url:
remote_url = 'git@github.com:' + remote_url
if not remote_url.endswith('.git'):
rem... | bigcode/self-oss-instruct-sc2-concepts |
def _curl_https_get_code(host):
"""
Create a curl command for a given host that outputs HTTP status code.
"""
return (
'/opt/mesosphere/bin/curl '
'-s -o /dev/null -w "%{{http_code}}" '
'https://{host}'
).format(host=host) | bigcode/self-oss-instruct-sc2-concepts |
def is_open_access(record):
"""Returns True if permissions subject(s) is anyone (all)."""
return record.get('permissions', '').startswith('all_') | bigcode/self-oss-instruct-sc2-concepts |
def mean(values):
"""Calculate the mean.
Parameters
----------
values : list
Values to find the mean of
Returns
-------
out : float
The mean
"""
return sum(values)/float(len(values)) if len(values) > 0 else 0.0 | bigcode/self-oss-instruct-sc2-concepts |
def remove_from_string(string, letters):
"""Given a string and a list of individual letters, returns a new string
which is the same as the old one except all occurrences of those letters
have been removed from it."""
for i in string:
for j in letters:
if i == j:
strin... | bigcode/self-oss-instruct-sc2-concepts |
def n_air(lambda0, temperature=15):
"""
Calculate refractive index of air at atmospheric pressure.
This follows the equation on page 4 of Smith, Modern Optical Engineering.
Args:
lambda0: wavelength in vacuum [m]
temperature: degrees celsius
Returns:
index of refraction [--... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def index_points(points, idx):
"""
Input:
points: input points data, [B, N, C]
idx: sample index data, [B, D1, D2, ..., Dn]
Return:
new_points:, indexed points data, [B, D1, D2, ..., Dn, C]
"""
device = points.device
B = points.shape[0]
view_shape = lis... | bigcode/self-oss-instruct-sc2-concepts |
async def ping() -> str:
"""health check"""
return "pong" | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def get_telapsed(last_draw_timestamp):
"""
Takes in a dictionary that shows last-draw timestamp for each card
and uses that to compute
Returns: Time elapsed dictionary that shows seconds elapsed since last time each card was drawn
(Key is the cue and value i... | bigcode/self-oss-instruct-sc2-concepts |
def combined_maintenance(*args):
"""
Takes any number of maintenance functions and returns one function that calls
all of the given ones in the order they are given.
"""
def combined(net, task, result):
nonlocal args
for mf in args:
mf(net, task, result)
return combined | bigcode/self-oss-instruct-sc2-concepts |
def SUM(src_column):
"""
Builtin sum aggregator for groupby.
Example: Get the sum of the rating column for each user. If
src_column is of array type, if array's do not match in length a NoneType is
returned in the destination column.
>>> sf.groupby("user",
... {'rating_sum':tc.aggregate.SUM('... | bigcode/self-oss-instruct-sc2-concepts |
def df_to_joints(df):
""" Return joint names from list of degrees of freedom. List of joint names is sorted alphabetically.
:param df: List of degrees of freedom like ["joint.x",].
:type df: list
:return: Joint names.
:rtype: list
"""
joints = sorted(set((x.split('.')[0] for x in df if ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def permute_list(x: List, permutation_indices: List[int]) -> List:
"""Permute `x` according to the indices in `permutation_indices`"""
return [x[i] for i in permutation_indices] | bigcode/self-oss-instruct-sc2-concepts |
def text_(s, encoding='latin-1', errors='strict'):
""" If ``s`` is an instance of ``bytes``, return
``s.decode(encoding, errors)``, otherwise return ``s``"""
if isinstance(s, bytes):
return s.decode(encoding, errors)
return s | bigcode/self-oss-instruct-sc2-concepts |
def plane_distance(p, plane):
"""Return signed distance to plane of point."""
x, y, z = p
A, B, C, D = plane
return A*x + B*y + C*z + D | bigcode/self-oss-instruct-sc2-concepts |
def read_fai_file(fai_file_name):
"""
Get a dictionary of an FAI file (reference index).
:param fai_file_name: Name of the file to read.
:return: A dictionary keyed on the sequence names with one tuple of the record values per record (all integers).
"""
fai_record_dict = {}
with open(fai... | bigcode/self-oss-instruct-sc2-concepts |
import ast
def check_deletevar(node):
"""
Check if there is a delete statement for a variable. Deletes for
attributes and subscripts don't count.
"""
class Visitor(ast.NodeVisitor):
def __init__(self):
self.found = False
def visit_Delete(self, node): ... | bigcode/self-oss-instruct-sc2-concepts |
def _permissions(annotation):
"""
Return a permissions dict for the given annotation.
Converts our simple internal annotation storage format into the legacy
complex permissions dict format that is still used in some places.
"""
read = annotation.userid
if annotation.shared:
read = ... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def translate_date(str, in_format, out_format):
"""Convert a date to ISO8601 date format without time"""
try:
return datetime.strptime(str.strip(), in_format).date().strftime(out_format)
except Exception:
pass
return '' | bigcode/self-oss-instruct-sc2-concepts |
import colorsys
def increase_saturation(r, g, b):
"""
Increase the saturation from rgb and return the new value as rgb tuple
"""
h, s, v = colorsys.rgb_to_hsv(r, g, b)
s = min(s+0.3, 1.0)
return colorsys.hsv_to_rgb(h, s, v) | bigcode/self-oss-instruct-sc2-concepts |
import contextlib
import socket
def is_port_open(host: str, port: int) -> bool:
"""Determines whether a port on a given host is open."""
with contextlib.closing(
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
) as s:
return s.connect_ex((host, port)) == 0 | bigcode/self-oss-instruct-sc2-concepts |
import six
def get_num_evts_per_merged_dataset(merged_datasets,num_evts_per_dataset):
""" Return number of events per merged dataset
Returns a dict `<merged_dataset>:<num_evts>'; see comments to function
`merge_datasets' for an explanation of <merged_dataset>.
"""
num_evts_per_merged_dataset = {}... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def _sha1_py3(msg):
"""Compute sha1 hash of a message.
:param msg: string to hash
:type msg: str
:return: upper case hexdigest representation of a hash
:type: str
"""
sha1hash = hashlib.sha1()
sha1hash.update(msg.encode('utf-8'))
return sha1hash.hexdigest().upper() | bigcode/self-oss-instruct-sc2-concepts |
import typing
def extract_entity_types(line: dict) -> typing.List[str]:
"""Extracts the entity type(s) for an entity.
Arguments:
line: ``dict`` A line in the Wikidata dump.
Returns:
entity_types: ``list`` A list of entity types for the entity.
Entity types are also QIDs in Wik... | bigcode/self-oss-instruct-sc2-concepts |
def MSEloss(y_actual, y_pred):
"""
Mean squared error: squared of actual target minus predicted target
y_actual = expected output
y_pred = predicted output
"""
return (y_actual - y_pred) ** 2 | bigcode/self-oss-instruct-sc2-concepts |
from contextlib import suppress
def flatten(lst):
"""
Flatten list.
:param lst: A list to be flattened
:type lst: ``list``
:return: Flattened list
:rtype: ``list``
"""
flattened = []
for element in lst:
if isinstance(element, str):
flattened.append(element)
... | bigcode/self-oss-instruct-sc2-concepts |
def _limit(lower, upper):
"""Returns a regular expression quantifier with an upper and lower limit."""
if ((lower < 0) or (upper <= 0) or (upper < lower)):
raise Exception("Illegal argument to _limit")
return u"{%d,%d}" % (lower, upper) | bigcode/self-oss-instruct-sc2-concepts |
def get_file_len(f):
"""Get file length of file"""
i = -1
for i, l in enumerate(f):
pass
return i + 1 | bigcode/self-oss-instruct-sc2-concepts |
import json
def read_json(filename):
""" Read data from JSON file.
Args:
filename (str): Name of JSON file to be read.
Returns:
dict: Data stored in JSON file.
"""
with open(filename, 'r') as in_file:
return json.load(in_file) | bigcode/self-oss-instruct-sc2-concepts |
def _parse_options_from_cmd_args(args):
"""
Parse out build options from the command line.
Args:
args (Argparse obj): The output of 'ArgumentParser.parse_args()'
Returns:
dict of options.
"""
opts = {}
if args.name is not None:
opts['app_name'] = args.name
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def update_buffer(production: Dict[str, Any], buffer: str) -> Dict[str, str]:
"""Returns a pattern to update the given buffer with.
Args:
production: The production dict that specifies the buffer update.
buffer: The name of the buffer to update.
... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def getDir(*args):
"""
Returns a Path from $HOME/rl_results/ and the extra
folders given as args.
"""
dr = Path.home()
adds = ["rl_results", *args]
for s in adds:
dr /= s
return dr | bigcode/self-oss-instruct-sc2-concepts |
def tau_sobol(dim_num):
"""
tau_sobol defines favorable starting seeds for Sobol sequences.
Discussion:
For spatial dimensions 1 through 13, this routine returns
a "favorable" value TAU by which an appropriate starting point
in the Sobol sequence can be determined.
These starting p... | bigcode/self-oss-instruct-sc2-concepts |
def intfs_only(s1code):
"""Given s1code, keep only interfaces (.h); ignore implementations (.f90)."""
return [(l, f, c) for l, f, c in s1code if f.endswith(".h")] | bigcode/self-oss-instruct-sc2-concepts |
def process_img_paths(input):
"""Processes image paths
If one path is entered, return list of length 1 containing location.
If multiple (comma-separated) paths are entered, return list containing
all paths.
Args:
input (str): string containing image path(s)
Returns:
paths (list... | bigcode/self-oss-instruct-sc2-concepts |
def fst(x):
"""
Returns the first item of a collection.
Examples
--------
>>> fst([0, 1, 2])
0
"""
return x[0] | bigcode/self-oss-instruct-sc2-concepts |
import re
def paste_urls_from_details(details):
"""Return list of URLs to objects from details page source."""
return re.findall(
r'<a href="(http://localhost:\d+/html/[^"]+)"',
details,
) | bigcode/self-oss-instruct-sc2-concepts |
def parse_state_setup(setup):
"""Parse state setup to name, and tuples with parameters for step."""
split = [part.split() for part in setup.split('\n')]
name = split[0][-1][0]
if_zero = (
[param[-1][:-1] if param[-1][:-1].isalpha() else int(param[-1][0])
for param in split[2:5]])
if... | bigcode/self-oss-instruct-sc2-concepts |
def secant(f,x0,x1, TOL=0.001, NMAX=100):
"""
Takes a function f, start values [x0,x1], tolerance value(optional) TOL and
max number of iterations(optional) NMAX and returns the root of the equation
using the secant method.
"""
n=1
while n<=NMAX:
x2 = x1 - f(x1)*((x1-x0)/(f(x1)-f(x0)))
if x2-x1 < TOL:
ret... | bigcode/self-oss-instruct-sc2-concepts |
def read_evid_db(dat_content, BN):
"""
Returns a list of dictionaries.
For each dictionary:
Key: var_name
Val: var_state
"""
# remove \n
dat_content= [i[:-1] for i in dat_content]
dat_db= [] # List of dictionaries. Each dictionary is a map of var_name to var_state
var_lst= dat_con... | bigcode/self-oss-instruct-sc2-concepts |
def indent_text(indent, text):
"""Prepend the specified number of spaces to the specified text.
Args:
indent (int): the number of spaces to use as an indentation
text (object): text to indent. lists will be converted into a
newline-separated str with spaces prepended to each line
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def calc_acc(pred_data: List[List[str]], gold_data: List[List[str]]):
"""Calculates the accuracy, precision and recall
Args:
pred_data (List[List[str]]): The output data from the model
gold_data (List[List[str]]): The labeled data to compare with
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def is_prime_number(number):
""" 判断数值是否为素数
:param number:
:return: boolean
"""
if number <= 1:
return False
for i in range(2, number):
if number % i == 0:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def tick_direction(*, x="inout", y="inout"):
"""Adjust the tick direction."""
return {
"xtick.direction": x,
"ytick.direction": y,
} | bigcode/self-oss-instruct-sc2-concepts |
def parse_bnd_pos(alt):
"""
Parses standard VCF BND ALT (e.g. N]1:1000]) into chrom, pos
Parameters
----------
alt : str
VCF-formatted BND ALT
Returns
-------
chrom : str
pos : int
"""
alt = alt.strip('ATCGNRYSWKMBDHV')
# Strip brackets separately, otherwise GL ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_book(url):
"""Check if *url* hints a book.
"""
return url is None or re.match('https?://[^/]*books.google.com', url) is not None | bigcode/self-oss-instruct-sc2-concepts |
import re
def no_yaml_char(s):
"""Check for characters which prevent the yaml syntax highlighter
from being applied. For example [] and ? and '
"""
return bool(re.match(r"^[a-zA-Z0-9()%|#\"/._,+\-=: {}<>]*$", s)) | bigcode/self-oss-instruct-sc2-concepts |
def yaml_diff_config(yaml_diff_sample_path):
"""Return a list containing the key and the sample path for a different yaml config."""
return ["--config", yaml_diff_sample_path] | bigcode/self-oss-instruct-sc2-concepts |
import json
import logging
def dict_to_json(metrics, input_filepath):
""" Outputs metrics dictionary as a JSON file with the same name (and
directory) as the original csv file from the beginning of the pipeline.
:param metrics: Dictionary of metrics
:param input_filepath: The filepath of the inputted... | bigcode/self-oss-instruct-sc2-concepts |
def step(env, action, state):
"""
Implementation of "step" which uses the given action
as an offset of the existing state. This function overloads
the environment step method and should be used when actions-as-offsets
are required for this particular environment.
"""
# if action == (0.0, 0.0... | bigcode/self-oss-instruct-sc2-concepts |
def det_ltri(ltri):
"""Lower triangular determinant"""
det = ltri[0] * ltri[2]
return det | bigcode/self-oss-instruct-sc2-concepts |
def get_crowd_selection(selection_counts, delimiter='|', error=None):
"""
Figure out what the crowd actually selected
:param selection_counts: output from get_crowd_selection_counts()
:type selection_counts: dict
:param delimiter: character to place between tied responses - response1|response2
... | bigcode/self-oss-instruct-sc2-concepts |
def format_symbolic_duration(symbolic_dur):
"""Create a string representation of the symbolic duration encoded
in the dictionary `symbolic_dur`.
Parameters
----------
symbolic_dur : dict
Dictionary with keys 'type' and 'dots'
Returns
-------
str
A string representation ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
from typing import Tuple
def find_upper_and_lower_integral_upper_bound(
get_integral_value: Callable[[float], Tuple[float, float]],
target_value: float,
min_upper_bound: float,
max_upper_bound: float,
) -> Tuple[float, float]:
"""
This function finds approximate low... | bigcode/self-oss-instruct-sc2-concepts |
def select_element(c, i):
"""Given a collection and an integer "i", return the ith element
of this collection
"""
print("Received collection value is %s" % str(c))
return c[i] | bigcode/self-oss-instruct-sc2-concepts |
def get_from_params(request, key):
"""Try to read a value named ``key`` from the GET parameters.
"""
return request.query.get(key) | bigcode/self-oss-instruct-sc2-concepts |
def pixelwise_norm(x, eps: float=1e-8):
"""
Pixelwise feature vector normalization.
:param x: input activations volume
:param eps: small number for numerical stability
:return: y => pixel normalized activations
"""
return x * x.pow(2).mean(dim=1, keepdim=True).add(eps).rsqrt() | bigcode/self-oss-instruct-sc2-concepts |
import typing
def spring_splitter_by_chunks(number_of_chunks: int, string_to_split: str) -> typing.List[str]:
"""
Splits string into a number of chunks specified
:param number_of_chunks: number of chunks
:param string_to_split: string_to_split
:return: list of strings
"""
pieces = string_t... | bigcode/self-oss-instruct-sc2-concepts |
def citation_metrics(publications):
"""
Return the h_index and total number of citations calculated from a list of
publications.
"""
cite_counts = sorted([v['citations'] for v in publications], reverse=True)
for j, k in enumerate(cite_counts):
if j + 1 > k:
return j, sum(cite... | bigcode/self-oss-instruct-sc2-concepts |
def filhos(indice, dependency_filhos):
"""
Devolve os indices dos filhos do nó dado como input (indice)
:param indice: indice de um nó
:param dependency_filhos: lista com sublistas que contêm os indices dos filhos, ex: [[], [0, 4], [], [], [2, 3], [1, 6, 7], [], []]
:return: Lista com os indices filhos do nó dado ... | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def get_file_path(file: str) -> pathlib.Path:
"""
Get path to passed in file.
Example get_file_path(__file__)
"""
return pathlib.Path(file).parent.absolute() | bigcode/self-oss-instruct-sc2-concepts |
def respond_list(**kwargs):
"""Returns a response to `list`."""
bot = kwargs['bot']
message = kwargs['message']
game_ids = [str(g) for g, c, _ in bot.pollers if c == message.channel.id]
msg = "I'm following: " + ', '.join(game_ids)
return msg | bigcode/self-oss-instruct-sc2-concepts |
def build_variant_display_title(chrom, pos, ref, alt, sep='>'):
""" Builds the variant display title. """
return 'chr%s:%s%s%s%s' % (
chrom,
pos,
ref,
sep,
alt
) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def safe_to_device(X, device):
"""Move the tensor or model to the device if it doesn't already live there.
This function will avoid copying if the object already lives in the
correct context. Works on PyTorch tensors and PyTorch models that inherit
from the torch.nn.Module class.
Pa... | bigcode/self-oss-instruct-sc2-concepts |
def quote_literal(s):
"""Quote a literal string constant."""
return "'" + s.replace("\\", "\\\\").replace("'", "\\'") + "'" | bigcode/self-oss-instruct-sc2-concepts |
import requests
def validate_actions(repo):
"""Validate if a repo has workflows/githubci.yml"""
repo_has_actions = requests.get(
"https://raw.githubusercontent.com/adafruit/"
+ repo["name"]
+ "/master/.github/workflows/githubci.yml"
)
return repo_has_actions.ok | bigcode/self-oss-instruct-sc2-concepts |
import torch
def cos_difference_mem(a, b, adjacency_matrix):
"""
The difference of coupled states in an oscillator model.
Vectorized, faster but costs more memory.
:param a: the vector a
:param b: the vector b
:param adjacency_matrix: The adjacency matrix
:return: The vector y with element... | bigcode/self-oss-instruct-sc2-concepts |
def square_frobenius_distance(m1, m2):
"""
Square frobenius distance between two probability matrices/vectors
:param m1:
:param m2:
:return:
"""
c = m1 - m2
c = c * c
return c.sum() | bigcode/self-oss-instruct-sc2-concepts |
import math
def city_cost(city: int) -> float:
"""
Calculate the cost to purchase a specified city.
:param city: The city to be purchased.
:return: The cost to purchase the specified city.
"""
city -= 1
return 50000 * math.pow((city - 1), 3) + 150000 * city + 75000 | bigcode/self-oss-instruct-sc2-concepts |
def is_digit(arg: str):
"""
isdigit() method
"""
return arg.isdigit() | bigcode/self-oss-instruct-sc2-concepts |
def macd(dataframe_name, signal_lag = 9):
"""Creates MACD Signals
Args:
dataframe_name (df): Single security dataframe containing at least a 'macd' column
signal_lag (int): Desired lag time used for macd rolling average
Returns:
A dataframe of:
original data passed to fun... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from functools import reduce
def sum(l:List[int],n:bool)->int:
"""
Sum a list of integer.
:param l: List of integer.
:param n: if present, multiply the result by -1
:return: The sum of the list
"""
o = reduce(lambda prev,act:prev+act,l)
if(n):o*=-1
return o | bigcode/self-oss-instruct-sc2-concepts |
def get_intervals(l):
"""For list of lists, gets the cumulative products of the lengths"""
intervals = len(l) * [0]
# Initalize with 1
intervals[0] = 1
for k in range(1, len(l)):
intervals[k] = (len(l[k]) + 1) * intervals[k - 1]
return intervals | bigcode/self-oss-instruct-sc2-concepts |
def pointwise_dict_multiply(dict1, dict2):
"""
Inputs:
- dict1, dict2: dicts with {key: float}
Returns:
- dict_mult: dict with {key: dict1[key]*dict2[key]} for all keys dict1 and dict2 have in common
"""
common_keys = set(dict1.keys()) & set(dict2.keys())
return {k: dict1[k]*dict... | bigcode/self-oss-instruct-sc2-concepts |
def is_version_newer(version_1, version_2):
"""
Indicates whether one vManage version is newer than another. Compares only the first 2 digits from version
because maintenance (i.e. 3rd digit) differences are not likely to create any incompatibility between REST API JSON
payloads, thus not relevant in th... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from typing import Dict
def cb_str_loss_wrapper(name: str, **params: Optional[Dict]) -> str:
"""CatBoost loss name wrapper, if it has keyword args. # noqa D403
Args:
name: One of CatBoost loss names.
**params: Additional parameters.
Returns:
Wrapped C... | bigcode/self-oss-instruct-sc2-concepts |
def demo_extension_3(**kwargs):
"""test that kwargs style functions are acceptable"""
return "p3" | bigcode/self-oss-instruct-sc2-concepts |
def is_dict_obj(obj):
"""Return True if obj is a dict."""
return isinstance(obj, dict) | bigcode/self-oss-instruct-sc2-concepts |
def get_array_of_field_values_matching(field_names, matchop, collection_obj):
"""Returns an array with all values the given field takes in all documents
matched by the given Matchop in the given collection."""
push_dict = {field_name : "$" + field_name for field_name in field_names}
agg_pipe = [
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def to_valid_key(name):
"""
convert name into a valid key name which contain only alphanumeric and underscores
"""
valid_name = re.sub(r'[^\w\s]', '_', name)
return valid_name | bigcode/self-oss-instruct-sc2-concepts |
import math
def myround(x, base, choice=None):
"""
Round values to the nearest base
:type x: float
:param x: value to round
:type base: int
:param base: nearest number to round to
:type choice: str
:param choice: 'up' to round up, 'down' to round down, or None for nearest
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def fix_sqltype(sqltype):
"""Fix `sqltype` string. Force uppercase string and
change 'FLOAT' -> 'REAL'.
Parameters
----------
sqltype : str
Returns
-------
st : string
"""
st = sqltype.upper()
if st == 'FLOAT':
st = 'REAL'
return st | bigcode/self-oss-instruct-sc2-concepts |
def add_text_generate_args(parser):
"""Text generation arguments."""
group = parser.add_argument_group(title='text generation')
group.add_argument("--temperature", type=float, default=1.0,
help='Sampling temperature.')
group.add_argument("--greedy", action='store_true', default=F... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
from typing import Iterable
def zip_with(func: Callable, *iters) -> Iterable:
"""`zip` all the iters and apply function `func` to each of them
"""
return map(func, zip(*iters)) | bigcode/self-oss-instruct-sc2-concepts |
def decode_variable_integer(bytes_input: bytes):
"""
If the length is fitting in 7 bits it can be encoded in 1 bytes.
If it is larger then 7 bybitstes the last bit of the first byte indicates
that the length of the lenght is encoded in the first byte and the length
is encoded in the following bytes.... | bigcode/self-oss-instruct-sc2-concepts |
def control_char_symbol(c: str) -> str:
"""Returns one of the Unicode Control Picture characters (e.g. '␛') for
the given single-character string with an ord() less than 32.
Raises ValueError for invalid strings.
"""
if len(c) != 1 or ord(c) >= 32:
raise ValueError('Argument must be a singl... | bigcode/self-oss-instruct-sc2-concepts |
def tf(tokens):
""" Compute TF
Args:
tokens (list of str): input list of tokens from tokenize
Returns:
dictionary: a dictionary of tokens to its TF values
"""
d = {}
for token in tokens:
if token in d:
d[token] += 1
else:
d[token] = 1
t... | bigcode/self-oss-instruct-sc2-concepts |
def extract_by_index(a_list, indices):
"""
Creates a list that consists of the elements at the given indices of
the given list.
:param a_list: The list to get elements from.
:param indices: The indices to use to source elements.
:return: The selected list.
"""
retur... | bigcode/self-oss-instruct-sc2-concepts |
def batch_get_similarity_matrix(ref, target):
"""
Get pixel-level similarity matrix.
:param ref: (batchSize, num_ref, feature_dim, H, W)
:param target: (batchSize, feature_dim, H, W)
:return: (batchSize, num_ref*H*W, H*W)
"""
(batchSize, num_ref, feature_dim, H, W) = ref.shape
ref = ref.... | bigcode/self-oss-instruct-sc2-concepts |
def fallbackSeries(requestContext, seriesList, fallback):
"""
Takes a wildcard seriesList, and a second fallback metric.
If the wildcard does not match any series, draws the fallback metric.
Example:
.. code-block:: none
&target=fallbackSeries(server*.requests_per_second, constantLine(0))
... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def get_class_property_names(obj: object):
"""Returns the names of all properties of a class."""
return [
p[0] for p in inspect.getmembers(type(obj), inspect.isdatadescriptor)
if not p[0].startswith("_")
] | bigcode/self-oss-instruct-sc2-concepts |
def get_most_popular_drugs(nonzero_df):
"""
Get the top 3 drugs that are used by patients.
Input
-----
df: pandas.DataFrame
The dataframe containing patients with positive response to treatments
Returns
-------
popular_df: pandas.DataFrame
The dataframe containing t... | 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.