seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def i_to_the_power(k):
"""
Return the sign (-1 or 1) and minimal integer power (0 or 1) of i to an
integer power.
"""
sign = {0: 1, 1: 1, 2: -1, 3: -1}[k % 4]
imaginary = k % 2
return sign, imaginary | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from bs4 import BeautifulSoup
def extract_flags(ci_attrs: str) -> List[str]:
"""
Get the course flags from the ci_attrs field.
Parameters
----------
ci_attrs:
the field from the Yale API response.
Returns
-------
flag_texts:
Flags (keywords) fo... | bigcode/self-oss-instruct-sc2-concepts |
def version_number_str(major, minor=0, patch=0, prerelease=None, build=None):
"""
Takes the parts of a semantic version number, and returns a nicely
formatted string.
"""
version = str(major) + "." + str(minor) + "." + str(patch)
if prerelease:
if prerelease.startswith("-"):
... | bigcode/self-oss-instruct-sc2-concepts |
def health() -> bool:
"""Shows that the worker is still receiving messages.
"""
return True | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import functools
import operator
def flatten(lst: list) -> List:
"""flatten the list of lists.
:param lst: list of lists
:return: flattened list
"""
return functools.reduce(operator.iconcat, lst, []) | bigcode/self-oss-instruct-sc2-concepts |
def surrounding_tiles(tile_x, tile_y, remove_outside_tiles=False):
"""Return the 8 tiles surrounding the given tile.
Parameters:
tile_x: X coord of tile
tile_y: Y coord of tile
Returns:
List of two tuples (x, y) of surrounding tiles.
The list will exclude the given tile it... | bigcode/self-oss-instruct-sc2-concepts |
def add_xml_data(**property_paths_types):
"""Add properties to a class that access data using :meth:`get_data`.
This provides an alternative usage to directly calling
:meth:`ActivityElement._add_data_properties` below a class definition.
Args:
**property_paths_types: kwargs mapping property_name : tuple(... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
from warnings import warn
def git_rev(repo):
"""
Get the git revision for the repo in the path *repo*.
Returns the commit id of the current head.
Note: this function parses the files in the git repository directory
without using the git application. It may break if the ... | bigcode/self-oss-instruct-sc2-concepts |
def selection_sort(arrayParam):
"""
Sort a list using selection sort algorithm. Run time: O(n**2)
"""
position = 0
array = arrayParam[:]
for k in array:
smallest = None
subPosition = position
smallestIndex = None
# Getting smallest value and index
for i in... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_range_header(range):
"""
Parse a range header as used by the dojo Json Rest store.
:param str range: The content of the range header to be parsed.
eg. `items=0-9`
:returns: A dict with keys start, finish and number or `False` if the
range is invalid.
"""
m... | bigcode/self-oss-instruct-sc2-concepts |
def has_children(element):
"""
Find out whether a xml element contains any children.
The lxml native approach with len is a bit confusing literaly.
Args:
element: lxml.etree.Element
Returns: boolean
"""
return bool(len(element)) | bigcode/self-oss-instruct-sc2-concepts |
def sir_dydt(t, y, beta, gamma, N):
"""
Defines the differential equations for the SIR model system.
Arguments:
t : time
y : vector of state variables:
y = [S, I, R]
beta, gamma, N : model parameters
"""
S, I, R = y
# Output array of form f = (S',... | bigcode/self-oss-instruct-sc2-concepts |
def find_by_attribute(element, name, value):
"""Find children of 'element' where attribute 'name' is equal to 'value'.
"""
return [child for child in element if child.get(name) == value] | bigcode/self-oss-instruct-sc2-concepts |
def domains(client):
"""
Get list of domains owned by current reseller.
"""
return client.domain.all() | bigcode/self-oss-instruct-sc2-concepts |
import math
def percentile(arr, P, is_sorted=False):
"""
NOTE: Returns the first element that is GREATER than the percentile
Inputs:
-------
arr: Array to be sorted
P: Percentile desired [0,1]
Options:
-------
is_sorted: [False] Whether or not the list is already sorte... | bigcode/self-oss-instruct-sc2-concepts |
def cpu_name(proc):
"""Return CPU name"""
items_count = len(proc)
if items_count == 1:
return proc[0]
if items_count >= 3:
return proc[2]
return "Unknown" | bigcode/self-oss-instruct-sc2-concepts |
def generate_absolute_path(home_directory: str, bucket_name: str) -> str:
"""
Generate absolute S3 path in the format that SFTP Transfer accepts.
:param bucket_name: bucket;
:param home_directory: directory in the bucket.
:return: path.
"""
return f'/{bucket_name}/{home_directory}' | bigcode/self-oss-instruct-sc2-concepts |
def check_options(cart_option, baseprice_option):
"""
Checks if the options of a product in the cart matches with the options of the given
product in the base-price file.
:param cart_option: The dict containing options provided with the product in the cart
:type cart_option: dict
:param basepric... | bigcode/self-oss-instruct-sc2-concepts |
def create_scheduler_resources(scheduler, base, goal):
"""Return a dictionary with scheduler resources.
This function will take a dictionary 'base', which contains scheduler resource settings that can be set for the
'resources' key in the 'options' input of a CalcJob, and update it with target scheduler re... | bigcode/self-oss-instruct-sc2-concepts |
def set_mail_from(message):
"""
Returns a string to be used to fill the 'from' field of and email
If no from address is provided in the html form, return 'from_default'
"""
# If a from address is included in html form, return it
if 'mail_from' in message and message['mail_from']:
return ... | bigcode/self-oss-instruct-sc2-concepts |
def _get_name(type_, value):
"""Return the name for the given value of the given type_.
The value `None` returns empty string.
"""
return type_._VALUES_TO_NAMES[value] if value is not None else "None" | bigcode/self-oss-instruct-sc2-concepts |
def calc_euclidean_gcd(left: int, right: int) -> int:
"""Find greatest common divisor using Euclidean Algorithm."""
if right == 0:
return left
return calc_euclidean_gcd(left=right, right=left % right) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def batch_square_vector(vector, M):
"""
Compute x^T M x
"""
vector = vector.unsqueeze(2)
return torch.bmm(torch.bmm(vector.transpose(2, 1), M), vector).squeeze(2) | bigcode/self-oss-instruct-sc2-concepts |
def to_camel_case(snake_case):
"""
Convert snake_case string to camelCase
:param snake_case: snake_case string to convert
:type snake_case: str
:return: camelCase string
:rtype: str
"""
words = snake_case.split('_')
return words[0] + ''.join(x.capitalize() for x in words[1:]) | bigcode/self-oss-instruct-sc2-concepts |
def is_han(c):
"""Return true if the input is a han character, false otherwise"""
return 0x4E00 <= ord(c) <= 0x9FFF | bigcode/self-oss-instruct-sc2-concepts |
def Unzip(iterable):
"""Unzips specified iterable of pairs to pair of two iterables.
This function is an inversion of the standard `zip` function and the following
hold:
* ∀ l, r. l, r == unzip(zip(l, r))
* ∀ p. p == zip(unzip(p))
Examples:
>>> Unzip([("foo", 1), ("bar", 2), ("baz", 3)])
(["f... | bigcode/self-oss-instruct-sc2-concepts |
def dot(origin, p1_end, p2_end):
"""Return dot product of (origin, p1_end) and (origin, p2_end)."""
ux, uy = (p1_end[0] - origin[0], p1_end[1] - origin[1])
vx, vy = (p2_end[0] - origin[0], p2_end[1] - origin[1])
return ux * vx + uy * vy | bigcode/self-oss-instruct-sc2-concepts |
def tfidf2freqdoc(words_tfidf, doc_length=1000):
"""
語のtfidfに応じて頻度が大きくなるような文書を返す.文書は,日本語の語をスペース区切りにしたもの.
Args:
words_tfidf (dict):key:語, value:語のtfidf となる辞書 {word(str):tfidf(float)}
doc_length (int, optional): 文書の長さ. Defaults to 1000.
"""
# tfidfの和が1になるように正規化し,語数に換算する.
tfidf_sum... | bigcode/self-oss-instruct-sc2-concepts |
def fill_with_label(sessions, label, start=None, stop=None, min_gap=.1):
"""fill gaps with a certain label, e.g., absence.
Args:
sessions: list of tuples
label: label str to be added in the gaps
start: starting time
stop: stopping time
min_gap: minimum gap length that ha... | bigcode/self-oss-instruct-sc2-concepts |
def multiple_letter_count(phrase):
"""Return dict of {ltr: frequency} from phrase.
>>> multiple_letter_count('yay')
{'y': 2, 'a': 1}
>>> multiple_letter_count('Yay')
{'Y': 1, 'a': 1, 'y': 1}
"""
return_dict = {}
for letter in phrase:
if return_dict.get(letter):
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def render_json(tree, indent):
"""Converts the tree into a flat json representation.
The json repr will be a list of hashes, each hash having 2 fields:
- package
- dependencies: list of dependencies
:param dict tree: dependency tree
:param int indent: no. of spaces to indent ... | bigcode/self-oss-instruct-sc2-concepts |
def PickHistoryName(args):
"""Returns the results history name to use to look up a history ID.
The history ID corresponds to a history name. If the user provides their
own history name, we use that to look up the history ID; If not, but the user
provides an app-package name, we use the app-package name with ' ... | bigcode/self-oss-instruct-sc2-concepts |
def escape_html(str):
"""Return an HTML-escaped version of STR."""
return str.replace('&', '&').replace('<', '<').replace('>', '>') | bigcode/self-oss-instruct-sc2-concepts |
def _create_rects(rect_list):
"""
Create a vertex buffer for a set of rectangles.
"""
v2f = []
for shape in rect_list:
v2f.extend([-shape.width / 2, -shape.height / 2,
shape.width / 2, -shape.height / 2,
shape.width / 2, shape.height / 2,
... | bigcode/self-oss-instruct-sc2-concepts |
def _get_subclasses(classname):
"""Recursively obtains all subclasses of the given class."""
subclasses = []
for p in classname.__subclasses__():
subclasses.append(p)
subclasses.extend(_get_subclasses(p))
return subclasses | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def generate_item_with_upstream_options(yaml_manifest, options) -> dict:
"""
Generate a VS/VSR item with an upstream option.
Update all the upstreams in VS/VSR
:param yaml_manifest: an absolute path to a file
:param options: dict
:return: dict
"""
with open(yaml_manifest) ... | bigcode/self-oss-instruct-sc2-concepts |
def twice(z):
"""
task 0.5.27
implement one line procedures def twice(z): return 2*z
"""
return 2*z | bigcode/self-oss-instruct-sc2-concepts |
def remove_des(name):
"""
remove 'Class A Common Stock' and 'Common Stock' from listing names
"""
if name.endswith("Class A Common Stock"):
name = name[:-21]
if name.endswith("Common Stock"):
name = name[:-13]
return name | bigcode/self-oss-instruct-sc2-concepts |
def _is_displayed(row, current_quarter, current_offset):
"""
Return true if message is for current quarter and current date
falls within the display range for a given message.
Message will display for 7 days.
"""
display_quarter = row[2]
display_offset = int(row[3])
return current_quart... | bigcode/self-oss-instruct-sc2-concepts |
def snakemake_job_script(tmp_path_factory, tumor_normal_config):
"""
Creates a dummy snakemake jobscript
"""
script_dir = tmp_path_factory.mktemp("snakemake_script")
snakemake_script_file = script_dir / "example_script.sh"
snakemake_script = """#!/bin/sh
# properties = {"type": "single", "rule"... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def getProcFNFromOrigFN(fp):
"""Returns the processed filename (as Path object, which can be treated as string) from origina filename (as string or Path object)"""
return Path(Path(fp).stem + '_processed.h5') | bigcode/self-oss-instruct-sc2-concepts |
def fmtcdb(key, val):
"""Formats a key and value into cdb format."""
key = str(key)
val = str(val)
s = '+%d,%d:%s->%s' % (len(key), len(val), key, val)
return s | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
import io
def read_file(path: pathlib.Path) -> bytes:
"""
Function to read in an image file and return the bytes
:param path: File path
"""
with io.open(path, "rb") as file:
content = file.read()
return content | bigcode/self-oss-instruct-sc2-concepts |
def remove_protected_attrs(item: dict) -> dict:
"""
Remove protected (AWS-only) attributes from a DynamoDB item.
"""
attrs = [attr for attr in item.keys() if attr.startswith('aws:')]
for attr in attrs:
del item[attr]
return item | bigcode/self-oss-instruct-sc2-concepts |
def _get_bib_element(bibitem, element):
"""Return element from bibitem or None."""
lst = [i.strip() for i in bibitem.split("\n")]
for i in lst:
if i.startswith(element):
value = i.split("=", 1)[-1]
value = value.strip()
while value.endswith(','):
v... | bigcode/self-oss-instruct-sc2-concepts |
import zipfile
def unzip_with_python(zip_file, output):
"""Unzips an archive using 'zipfile' python module.
Works everywhere where python works (Windows and Posix).
Args:
zip_file: absolute path to an archive to unzip.
output: existing directory to unzip to.
Returns:
Exit code (0 on success).
... | bigcode/self-oss-instruct-sc2-concepts |
def find_containers(bag, bag_rules):
"""Find the bags that can contain a specified bag."""
allowed = []
for n, item in bag_rules.items():
if bag in item.keys():
allowed.append(n)
return allowed | bigcode/self-oss-instruct-sc2-concepts |
def popravi_st_glasov(seznam_slovarjev):
"""
Popravi vnos ST_GLASOV, da vrne število brez decimalne vejice.
"""
for pivo in seznam_slovarjev:
glasovi = pivo['ST_GLASOV']
glasovi = int(glasovi.replace(',', ''))
pivo['ST_GLASOV'] = glasovi
return seznam_slovarjev | bigcode/self-oss-instruct-sc2-concepts |
def value_to_float(x: str):
"""
Converts strings with abbreviated numbers to floats
>>> value_to_float('1.2k')
1200.0
"""
if type(x) == float or type(x) == int:
return x
x = x.upper()
x = x.replace(',', '')
if 'K' in x:
if len(x) > 1:
return float(x.repla... | bigcode/self-oss-instruct-sc2-concepts |
def decorate_c_array_data (hexdata: str,
var_name: str,
var_type: str,
newline_value: str):
"""
Place @hexdata into a valid C array named @var_name of C type @var_type.
"""
ret = var_type + " " + var_name + "[] = {" + newli... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
from typing import List
def get_shingles(
doc: str,
normalization_func: Callable,
split_method: str,
ngram_size: int,
ngram_stride: int,
) -> List[str]:
"""Extracts the shingles from a document.
Args:
doc (str):
The document to extract the s... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def max_array_sum(arr: List[int]) -> int:
"""
Return the maximum sum of an array subset of non-adjacent items.
:time: O(n)
:space: O(n)
"""
max_sum = [0] * (len(arr) + 2)
for i, num in enumerate(arr, start=2):
max_sum[i] = max(max_sum[i - 2] + num, max_sum[... | bigcode/self-oss-instruct-sc2-concepts |
import math
def wind_speed_2m(ws, z):
"""
Convert wind speed measured at different heights above the soil
surface to wind speed at 2 m above the surface, assuming a short grass
surface.
Based on FAO equation 47 in Allen et al (1998).
:param ws: Measured wind speed [m s-1]
:param z: Heigh... | bigcode/self-oss-instruct-sc2-concepts |
def transform_boolean(value):
"""Transfroms boolean to `1` or `0`.
:param value: Boolean value.
:type value: boolean
:return: number representation of boolean `1` or `0`.
:rtype: str
"""
if value:
return '1'
else:
return '0' | bigcode/self-oss-instruct-sc2-concepts |
import math
def sigmoid(x: float) -> float:
"""
Numerically stable scaled logistic function.
Maps all values ``x`` to [0, 1]. Values between -1000 and 1000 are
mapped reasonably far from 0 and 1, after which the function
converges to bounds.
Parameters
----------
x:
Input.
... | bigcode/self-oss-instruct-sc2-concepts |
import six
def get_string_mapping(kvp):
"""Returns a dictionary mapping strings to strings.
This can take either a string of the form "name=value:name2=value2"
or a dictionary containing all string keys and values.
:param kvp: dictionary or string
:returns: dictionary
"""
if kvp is None... | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
import operator
def get_by_path(root: dict, items: list[str | int]) -> dict:
"""Access a nested object in root by item sequence."""
return reduce(operator.getitem, items, root) | bigcode/self-oss-instruct-sc2-concepts |
def is_number(text):
"""
Checking if the text is a number
:param text: text we want to examine
:type text: str
:return: whether this is a number or not
:rtype: bool
"""
try:
float(text.strip())
except ValueError:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _get_device(device_string):
"""Returns a `torch.device`
Args:
device_string: 'cpu' or 'cuda'
Returns:
`torch.device`
"""
if device_string.lower() == 'cpu':
return torch.device('cpu')
if device_string.lower() == 'cuda':
if torch.cuda.device_count() == ... | bigcode/self-oss-instruct-sc2-concepts |
import math
def euclidean_distance(a, b=None):
"""
Euclidean distance between two n-dimensional points.
"""
if b is None: return euclidean_distance(a, (0,) * len(a))
return math.sqrt(sum((a - b) ** 2 for a, b in zip(a, b)))
#np.linalg.norm(a - b)
#np.sqrt(np.sum((a-b)**2))) | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_condition(*conditions) -> str:
"""
Returns a random condition based on the supplied arguments with
equal probability of all conditions.
Args:
*conditions: A variable number of condition identifiers
Returns:
str: One of the input arguments, chosen at rando... | bigcode/self-oss-instruct-sc2-concepts |
import math
def norm(vec):
"""Return the norm of a 2-dimensional vector."""
return math.sqrt(vec[0] ** 2 + vec[1] ** 2) | bigcode/self-oss-instruct-sc2-concepts |
def between(full, start, end):
"""Returns the substring of the given string that occurs between the start
and end strings."""
try:
if not start:
parse = full
else:
parse = full.split(start, 1)[1]
if end:
result = parse.split(end, 1)[0]
else... | bigcode/self-oss-instruct-sc2-concepts |
def get_mask_paths(metadata):
"""
localization.txt (for masks) has the structure
<path>,<link_to_mask_file>,<link_to_ignore_mask_file>
path/to/image1.jpg,path/to/mask1a.png,path/to/ignore1.png
path/to/image1.jpg,path/to/mask1b.png,
path/to/image2.jpg,path/to/mask2a.png,path/to/ignore2.png
p... | bigcode/self-oss-instruct-sc2-concepts |
import pkg_resources
def get_schema_path(version='1.0.1'):
"""
Location of CPHD schema file.
Returns
-------
str
The path to the CPHD schema.
"""
if version == '1.0.1':
return pkg_resources.resource_filename('sarpy.io.phase_history.cphd_schema', 'CPHD_schema_V1.0.1_2018_0... | bigcode/self-oss-instruct-sc2-concepts |
def _parse_dummy(logfile):
"""Dummy parser for testing"""
return {} | bigcode/self-oss-instruct-sc2-concepts |
import torch
from typing import List
from typing import Dict
from typing import Any
def add_weight_decay(
model: torch.nn.Module, weight_decay: float
) -> List[Dict[str, Any]]:
"""Add weight decay to only the convolutional kernels. Do not add weight decay
to biases and BN. TensorFlow does this automatical... | bigcode/self-oss-instruct-sc2-concepts |
def get_offer_photos_links(html_parser):
"""
This method returns a list of links to photos of the apartment.
:param html_parser: a BeautifulSoup object
:rtype: list(string)
:return: A list of links to photos of the apartment
"""
gallery = html_parser.findAll(class_="gallery-box-thumb-item")... | bigcode/self-oss-instruct-sc2-concepts |
def unescape_double_quote(content: str) -> str:
"""
Replace escaped double quote in content by removing the backslash.
>>> unescape_double_quote(r'UTF\"-8')
'UTF"-8'
>>> unescape_double_quote(r'UTF"-8')
'UTF"-8'
"""
return content.replace(r"\"", '"') | bigcode/self-oss-instruct-sc2-concepts |
def check_url(url):
""" Check if exist a well-formed url"""
if url[:8] == "https://" or url[:7] == "http://":
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def help(title, url=None) -> str:
"""Creat help badge
Args:
title: help text
url: url to open in new tab (optional)
Returns:
HTML formatted help badge
"""
if url is not None:
return f'<a title="{title}" href="{url}" target="_blank"><span class="badge pull-right" sty... | bigcode/self-oss-instruct-sc2-concepts |
def average(values):
"""(list of number) -> number
Return the average of the numbers in values. Some items in values are None,
and they are not counted toward the average.
>>> average([20, 30])
25.0
>>> average([None, 20, 30])
25.0
"""
count = 0 # The number of values seen so far... | bigcode/self-oss-instruct-sc2-concepts |
def get_mask_names_dict(mask_names, tracer_names):
"""
Return a dictionary with the mask names assotiated to the fields to be
correlated
Parameters:
-----------
mask_names (dict): Dictionary of the masks names assotiated to the
fields to be correlated. It has to be given as {1: nam... | bigcode/self-oss-instruct-sc2-concepts |
def clean_text(text):
"""Removing spaces and converting the text into lowercase"""
return text.strip().lower() | bigcode/self-oss-instruct-sc2-concepts |
def filter_gtf_file(gtf_file, source=None, feature=None, copy=True):
"""
filter gtf file based on tthe source of the annotations (HAVANA or ENSEMBL),
and/or the type of feature (transcript, exon, gene)
if source/feature is not None.
It returns a new filtered pandas.DataFrame.
Parameter... | bigcode/self-oss-instruct-sc2-concepts |
def compile_str_from_parsed(parsed):
"""The (quasi-)inverse of string.Formatter.parse.
Args:
parsed: iterator of (literal_text, field_name, format_spec, conversion) tuples,
as yield by string.Formatter.parse
Returns:
A format string that would produce such a parsed input.
>>> ... | bigcode/self-oss-instruct-sc2-concepts |
def getYearsAsList(macroDemand, startYear, endYear):
""" Return a sorted list containing only the years (or "time steps"). """
years = macroDemand.keys()
years.sort()
for i in range(len(years)):
years[i] = int(years[i])
startIndex = years.index(startYear)
endIndex = years.index(endYear)... | bigcode/self-oss-instruct-sc2-concepts |
def open_json(spark, json_path):
"""Opens a json file as a pandas DataFrame.
Parameters
----------
spark
Spark session.
json_path
a HDFS file path and file name ending in .json
Returns
-------
Pandas DataFrame
"""
sdf = spark.read.json(
json_path,
en... | bigcode/self-oss-instruct-sc2-concepts |
def roll_uint8(value):
"""Roll given one-byte value, i.e. increment it such that
the range is preserved.
>>> roll_uint8(-10)
ValueError: Acceptable range: 0 - 255
>>> roll_uint8(-1)
ValueError: Acceptable range: 0 - 255
>>> roll_uint8(0)
1
>>> roll_uint8(10)
11
>>> roll_uint8... | bigcode/self-oss-instruct-sc2-concepts |
def remove_end_from_pathname(filen, end='.image'):
"""
Retrieve the file name excluding an ending extension or terminating string.
Parameters
----------
filen : str
end : str
End to file name to remove. If an extension, include the period, e.g.
".image".
"""
if not filen... | bigcode/self-oss-instruct-sc2-concepts |
def filter_pdna(lognorm_df, pdna_cols, z_low=-3, z_high=None):
"""
Filter the lognorm dataframe based on the z_scored lognorms of pDNA
lognorm_df: dataframe |
pdna_cols: list |
z_low: int or None, lower range of z-scores to filter |
z_high: int or None, upper range of z-scores to filter |
r... | bigcode/self-oss-instruct-sc2-concepts |
def safestr(text):
"""
Safely convert unicode to a string
"""
if text is None:
return
try:
return str(text)
except UnicodeEncodeError:
return str(text.encode('utf-8')) | bigcode/self-oss-instruct-sc2-concepts |
def cmdstr(cmd):
"""Return a string for the |cmd| list w/reasonable quoting."""
quoted = []
for arg in cmd:
if ' ' in arg:
arg = '"%s"' % (arg,)
quoted.append(arg)
return ' '.join(quoted) | bigcode/self-oss-instruct-sc2-concepts |
def _unified_indent(kwargs):
"""
Private helper. If kwargs has an `indent` parameter, that is
made into the the value of both the `initial_indent` and the
`subsequent_indent` parameters in the returned dictionary.
"""
indent = kwargs.get('indent')
if indent is None:
return kwargs
... | bigcode/self-oss-instruct-sc2-concepts |
def dataframe_has_columns_of_these_types(df, types_list):
"""Returns true if the dataset has the given types.
Args:
df: The dataframe to inspect.
types_list: list of types to check for.
Returns:
True if the types are present in the data frame.
"""
return not df.select_dtype... | bigcode/self-oss-instruct-sc2-concepts |
import re
def create_initials(s):
"""
Return the initial letter of each word in s, capitalized and strung together
Example: John Smith -> JS
"""
return "".join(s[0] if s else '' for s in re.split(r"[\W_]+", s)).upper() | bigcode/self-oss-instruct-sc2-concepts |
def remove_falses(tup: tuple) -> tuple:
"""Removes all false occurences from a tuple."""
return tuple([i for i in tup if i]) | bigcode/self-oss-instruct-sc2-concepts |
def get_single_language(kanton):
""" Returns the language given the canton abbreviation for a single canton
"""
if (kanton == "TI"):
return "IT"
elif (kanton in ["FR", "VD", "NE", "JU", "GE", "VS"]):
return "FR"
else:
return "DE" | bigcode/self-oss-instruct-sc2-concepts |
def statustoresult(status):
"""
Convert the status returned from waitpid into a prettier numeric result.
"""
sig = status & 0xFF
if sig:
return -sig
return status >>8 | bigcode/self-oss-instruct-sc2-concepts |
def _convert(value, to_type, default=None):
"""Convert value to to_type, returns default if fails."""
try:
return default if value is None else to_type(value)
except ValueError:
# If value could not be converted
return default | bigcode/self-oss-instruct-sc2-concepts |
def as_number(as_number_val: str) -> int:
"""Convert AS Number to standardized asplain notation as an integer."""
as_number_str = str(as_number_val)
if "." in as_number_str:
big, little = as_number_str.split(".")
return (int(big) << 16) + int(little)
else:
return int(as_number_st... | bigcode/self-oss-instruct-sc2-concepts |
def jsfunc(value):
"""Create a safe javascript function name."""
return value.replace('-', '_') | bigcode/self-oss-instruct-sc2-concepts |
def getRequestType(data):
"""
Returns the HTTP Method type from the given request
"""
return data[0].decode("utf-8") | bigcode/self-oss-instruct-sc2-concepts |
def alias_diff(refcounts_before, refcounts_after):
"""
Given the before and after copies of refcounts works out which aliases
have been added to the after copy.
"""
return set(t for t in refcounts_after
if refcounts_after[t] > refcounts_before.get(t, 0)) | bigcode/self-oss-instruct-sc2-concepts |
def valid_book_definition(name, author, year, pages):
"""Does some simple checks on whether the provided arguments are sufficient to defien a book"""
if len(name) <= 1:
return False
if len(author) <= 1:
return False
try:
int(pages)
int(year)
except ValueError:
... | bigcode/self-oss-instruct-sc2-concepts |
def look_up_data(input_string, logical_zero, logical_one):
"""Looks up the input data to determine if the string is a logical one,
logical zero, or outside the code base.
Parameters
----------
input_string : str
data for analysis
logical_zero : list
list of strings represent... | bigcode/self-oss-instruct-sc2-concepts |
def flatten(target):
"""Flatten a list with nested lists into a single list.
For example::
flatten([1, [2, 3]) # => [1, 2, 3]
"""
return [item for sublist in target for item in sublist] | bigcode/self-oss-instruct-sc2-concepts |
def get_matrix(filename):
"""Return a list of lists containing the content of the input text file.
Note: each line of the text file corresponds to a list. Each item in
the list is from splitting the line of text by the whitespace ' '.
"""
with open(filename, "r") as f:
content = f.readlines... | bigcode/self-oss-instruct-sc2-concepts |
def max_arg_length(arg_list):
"""Returns the max length of the arguments in arg_list."""
return max([len(x) for x in arg_list]) | bigcode/self-oss-instruct-sc2-concepts |
def get_minor_matrix(q, i, j):
"""
Q = [
[1,2,3],
[4,5,6],
[7,8,9],
]
Minor matrix corresponding to 0,0 is
[
[5,6],
[8,9],
]
"""
minor_matrix = []
for row in q[:i] + q[i + 1:]:
temp = []
for item in row[:j] + row[j + 1:]:
... | 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.