seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import requests
def get_ipam_roles(url, headers):
"""
Get dictionary of existing IPAM roles
"""
api_url = f"{url}/api/ipam/roles/"
response = requests.request("GET", api_url, headers=headers)
all_roles = response.json()["results"]
roles = []
for role in all_roles:
role_info = d... | bigcode/self-oss-instruct-sc2-concepts |
def node_bounds(*nodes):
"""Get the min and max for the x- and y-coordinates for an iterable of `daft.Node`s."""
xs = list(n.x for n in nodes)
ys = list(n.y for n in nodes)
return (min(xs), max(xs)), (min(ys), max(ys)) | bigcode/self-oss-instruct-sc2-concepts |
def cert_get_serial(cert):
"""
Fetch the serial number from the certificate.
:param cert:
:return: serial number
"""
return cert.serial | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from typing import Union
from typing import List
from typing import Tuple
def normalize_to_list(
value: Optional[Union[str, List[str], Tuple[str, ...]]]
) -> List[str]:
"""
Takes the different formats of options containing multiple values and
returns the value as a list obj... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def _hash_gene(gene, length=6):
"""Get the first letters of the SHA-1 digest of the gene."""
encoded = sum(
v * 4 ** i for i, v in enumerate(gene)
).to_bytes(13, byteorder='big')
digest = hashlib.sha1(encoded).hexdigest()
return digest[0:length] | bigcode/self-oss-instruct-sc2-concepts |
def _tags_to_dict(s):
""" "k1=v1,k2=v2" --> { "k1": "v1", "k2": "v2" } """
return dict(map(lambda kv: kv.split('='), s.split(","))) | bigcode/self-oss-instruct-sc2-concepts |
def formatStyle(a):
"""Format an inline style attribute from a dictionary"""
return ";".join([att+":"+str(val) for att,val in a.iteritems()]) | bigcode/self-oss-instruct-sc2-concepts |
import re
def _get_log_fname(mtz_fname):
"""
convert an mtz filename to the corresponding main log filename
"""
regex = re.compile(r'(.*)_all.mtz$')
hit = regex.search(mtz_fname)
assert hit is not None
assert len(hit.groups()) == 1
return hit.groups()[0] + '_main.log' | bigcode/self-oss-instruct-sc2-concepts |
def create_connectivity_list(shape, element_offset=0):
"""Use the element indices for each shape to create the connectivity list"""
num_points = len(shape.points)
num_parts = len(shape.parts)
elements = []
for i in range(num_parts):
# parts[] returns the point index at the start of each par... | bigcode/self-oss-instruct-sc2-concepts |
def month_difference(from_date, to_date):
"""
gets the number of months between from_date and to_date
could be negative or zero
example usage:
>>> month_difference(datetime(2010,10,1), datetime(2010,11,1))
1
"""
return (to_date.year - from_date.year) * 12 + (to_date.month - from_... | bigcode/self-oss-instruct-sc2-concepts |
def dt_str(dt_object, format_='%Y-%m-%dT%H:%M:%S') -> str:
"""
Converts python datetime object into datetime string
"""
return dt_object.strftime(format_) | bigcode/self-oss-instruct-sc2-concepts |
def generateFilename(photoInfo, photoNum):
"""Creates a file system file name for a photo.
The file name will be in the format date-taken_title.extension. For
example, 20180521203625_My_Flickr_Picture.jpg. The date taken will be a
numeric string which means the pictures on the file system will sort i... | bigcode/self-oss-instruct-sc2-concepts |
def getNestedValue(dictionary, keyString, default=None):
"""
Returns the value from a nested dictionary where '.' is the delimiter
"""
keys = keyString.split('.')
currentValue = dictionary
for key in keys:
if not isinstance(currentValue, dict):
return default
curr... | bigcode/self-oss-instruct-sc2-concepts |
def remove_ticks(ax, x=False, y=False):
"""
Remove ticks from axis.
Parameters:
ax: axes to work on
x: if True, remove xticks. Default False.
y: if True, remove yticks. Default False.
Examples:
removeticks(ax, x=True)
removeticks(ax, x=True, y=True)
"""
if x:
ax... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def normalize_tensor_one_minone(
pp: torch.Tensor,
) -> torch.Tensor:
"""
Receives a tensor and retrieves a normalized version of it between [-1, ..., 1].
We achieve this by normalizing within [0, 2] and subtracting 1 from the result.
"""
pp_norm = pp.float()
pp_max = pp_norm.... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def get_description(description: Optional[str]) -> str:
"""Filter. Get the description of a property or an empty string"""
return description or "" | bigcode/self-oss-instruct-sc2-concepts |
def Hex2Alpha(ch):
"""Convert a hexadecimal digit from 0-9 / a-f to a-p.
Args:
ch: a character in 0-9 / a-f.
Returns:
A character in a-p.
"""
if ch >= '0' and ch <= '9':
return chr(ord(ch) - ord('0') + ord('a'))
else:
return chr(ord(ch) + 10) | bigcode/self-oss-instruct-sc2-concepts |
def _crypt_audio_packet(packet: bytes, key: bytes) -> bytes:
"""Encrypt/decrypt a plaintext/encrypted audios stream payload. Skips encryption/decryption
if packet is less than or equal to 0x140 bytes.
"""
data = bytearray(packet)
if len(data) > 0x140:
for i in range(0x140, len(data)):
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def json_encode(data, *args, **kwargs):
"""Encodes a dictionary into a JSON string
Arguments:
data {dict} -- Dictionary to encoded
Returns:
str -- JSON encoded string
"""
return json.dumps(data, *args, separators=(',', ':'), **kwargs) | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_URL(text: str)-> str:
"""
Removes URL patterns from text.
Args:
`text`: A string, word/sentence
Returns:
Text without url patterns.
"""
url = re.compile('https?://\S+|www\.\S+')
text = url.sub('',text)
return text | bigcode/self-oss-instruct-sc2-concepts |
def split_by_bar(abc_string):
"""
Takes a string of full ABC notation and splits it into lists representing individual bars
"""
result = abc_string.split('|')
return [x for x in result if x != ''] | bigcode/self-oss-instruct-sc2-concepts |
import math
def convert_bytes(size):
"""Make a human readable size."""
label = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB')
try:
i = int(math.floor(math.log(size, 1024)))
except ValueError:
i = 0
p = math.pow(1024, i)
readable_size = round(size/p, 2)
return '{}{}'.... | bigcode/self-oss-instruct-sc2-concepts |
def objtag(accessing_obj, accessed_obj, *args, **kwargs):
"""
Usage:
objtag(tagkey)
objtag(tagkey, category)
Only true if accessed_obj has the specified tag and optional
category.
"""
if hasattr(accessed_obj, "obj"):
accessed_obj = accessed_obj.obj
tagkey = args[0] i... | bigcode/self-oss-instruct-sc2-concepts |
def rec_replace(l, d):
""" Recursively replace list l with values of dictionary d
ARGUMENTS:
l - list or list of lists
d - dictionary where if an element in l matches d['key'], it is replaced by the value
OUTPUT:
l - list with elements updated
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def _map(args):
"""Mapping helper function for mp_list_map."""
lst, fnc, kwargs = args
return fnc(list(lst), **kwargs) | bigcode/self-oss-instruct-sc2-concepts |
def read_file(name):
"""
Reads the content of a text file specified by the user.
"""
file = open(name, 'r', encoding="UTF-8")
return file.read() | bigcode/self-oss-instruct-sc2-concepts |
import math
def is_prime(n):
"""Return True if n is a prime number, else False."""
return n >= 2 and not any(
n % p == 0 for p in range(2, int(math.sqrt(n)) + 1)) | bigcode/self-oss-instruct-sc2-concepts |
def get_block_id(color, id_tag="00"):
"""Get block identifier based on color
Args:
color (string): string representation of color
id_tag (string, optional): prefix for the object. Defaults to "00".
Returns:
string: block identifier as string
"""
return "%s_block_%s"... | bigcode/self-oss-instruct-sc2-concepts |
def findStartOfLine(text,offset,lineLength=None):
"""Searches backwards through the given text from the given offset, until it finds the offset that is the start of the line. With out a set line length, it searches for new line / cariage return characters, with a set line length it simply moves back to sit on a multip... | bigcode/self-oss-instruct-sc2-concepts |
def dodo_existing(tmpdir):
"""
Set up a project with a DODO file
"""
prjdir = tmpdir.join('projdir')
prjdir.ensure(dir=True)
prjdir.join('.project').ensure()
dofile = prjdir.join('DODO')
dofile.write("\n - this is a task\n")
return (prjdir, dofile) | bigcode/self-oss-instruct-sc2-concepts |
def get_theta_bounds(priors):
"""
Returns the state vector parameters bounds.
Parameters
----------
priors : list of instantiated Prior objects
:class:`Prior` vector
Returns
-------
bounds : list
List of (min, max) tuples
"""
return [prior.get_bounds() for prior... | bigcode/self-oss-instruct-sc2-concepts |
def title(snake_case: str):
"""Format snake case string as title."""
return snake_case.replace("_", " ").strip().title() | bigcode/self-oss-instruct-sc2-concepts |
def merge_duplicate(merged_streams_in_island_list):
"""
Merge lists that have at least one common element into one list.
:param merged_streams_in_island_list: list of lists to test and merge
:type merged_streams_in_island_list: list of lists
:return: list of merged lists
:rtype: list o... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
from datetime import datetime
def most_recent_run(outputs_path, fmts=["%Y-%m-%d", "%H-%M-%S"]):
"""Get the most recent Hydra run folder.
Parameters
----------
outputs_path : pathlib.Path or str
The root Hydra outputs directory
fmts : list
Optional list of ... | bigcode/self-oss-instruct-sc2-concepts |
def b_overlap_a(a, b, alab='a', blab='b', verb=False):
"""Check if there is any value in `b` inside the range of the values in `a`.
Only checks if there is overlap, but not how (e.g. do not tell if all values of b inside a, or just from one side).
Examples
--------
a: ' |---| '
b: '|--... | bigcode/self-oss-instruct-sc2-concepts |
def Artifact(file_path, view_url=None, fetch_url=None,
content_type='application/octet-stream'):
"""Build an Artifact dict.
Args:
file_path: A string with the absolute path where the artifact is stored.
view_url: An optional string with a URL where the artifact has been
uploaded to as a ... | bigcode/self-oss-instruct-sc2-concepts |
def careful_update(adict, bdict):
"""
Carefully updates a dictionary with another dictionary, raising a
ValueError if keys are shared.
"""
if not set(adict.keys()).isdisjoint(set(bdict.keys())):
raise ValueError('adict shares keys with bdict')
else:
adict.update(bdict)
... | bigcode/self-oss-instruct-sc2-concepts |
def update_dict_key(dict_value, key_map):
"""将字典中的key进行修改
Args:
dict_value:原始字典
key_map: key映射dict类型
Returns:
返回修改后的字典
举例:
dict_value = {'a':1,'b':2}
key_map = {'a':'c'}
返回值new_val = {'c':1, 'b':2}
"""
new_val = dict_value.copy()
for k, v in ke... | bigcode/self-oss-instruct-sc2-concepts |
def create_lookup_tables(unique_words):
""" Create lookup tables for word_to_id and id_to_word
Args:
unique_words: dictionary of words in training set
Return:
word_to_id: dict with words as keys and corresponding ids as values
id_to_word: dict with ids as keys and corr... | bigcode/self-oss-instruct-sc2-concepts |
import urllib3
def read_pdbid(pdbid):
"""
Read a pdb file from the PDB. Need an internet connection.
Parameters
----------
pdbid: Name of the pdb file. (ex: 1dpx or 1dpx.pdb)
Return
------
The content of the pdb file
"""
# URL of the PDB
url = 'http://files.rcsb.org/downl... | bigcode/self-oss-instruct-sc2-concepts |
def single_structure_property_predicted(body):
"""
Method for make message as dict with data which would be send to rabbitmq
ml single structure property predicted queue
:param body: body of message received from RabbitMQ queue
:type body: dict
:return: single structure property predicted messa... | bigcode/self-oss-instruct-sc2-concepts |
def word_splitter(df):
""" This function takes pandas dataframe as input, split the sentence into a list of separate words and returns a modified dataframe
Example
Input:
Tweets Date
@IamGladstone @CityPowerJhb @HermanMashaba The... 2019-11-29 11... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Awaitable
from typing import Dict
from typing import Any
import aiohttp
import json
async def download_data(url) -> Awaitable[Dict[str, Any]]:
"""The download_data method downloads json data from the `url`.
Args:
url (str): the url that the user wants to download
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def xeval(sexpr):
"""
>>> xeval('')
0
>>> xeval('1234567')
1234567
>>> xeval('+1234567')
1234567
>>> xeval('-1234567')
-1234567
>>> xeval('2+3')
5
>>> xeval('2-3')
-1
>>> xeval('2-23+4')
-17
>>> xeval('2-01+3-1')
3
>>> xeval('1-2-3-4-5')
-13
... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
from typing import Dict
import re
def parse_debian_control(cwd: Path) -> Dict[str, str]:
"""
Extract fields from debian/control
:param cwd: Path to debian source package
:return: Dict object with fields as keys
"""
field_re = re.compile(r"^([\w-]+)\s*:\s*(.+)")
co... | bigcode/self-oss-instruct-sc2-concepts |
def _get_cover_address(metadata):
"""Returns cover address.
Returns
-------
int
cover address
"""
if 'COVER_1' in metadata.footer:
address = int(metadata.footer['COVER_1'])
else:
address = 0
return address | bigcode/self-oss-instruct-sc2-concepts |
def end_ea(obj):
"""
Return end ea for supplied object.
:param obj: Object to retrieve end ea.
:return: end ea.
"""
if not obj:
return None
try:
return obj.endEA
except AttributeError:
return obj.end_ea | bigcode/self-oss-instruct-sc2-concepts |
def chunk(array, num_memory_steps):
"""Chunk an array into size of N steps.
The array of size N x k_1 x ... k_n will be reshaped to be of size
Batch x num_memory_steps x k_1 x ... k_n.
Parameters
----------
array: Array.
Array to reshape.
num_memory_steps: int.
Number of st... | bigcode/self-oss-instruct-sc2-concepts |
def compute_CdS_from_drop_test(
terminal_velocity, rocket_mass, air_density=1.225, gravity=9.80665
):
"""Returns the parachute's CdS calculated through its final speed, air
density in the landing point, the rocket's mass and the force of gravity
in the landing point.
Parameters
----------
t... | bigcode/self-oss-instruct-sc2-concepts |
def cvars(occs):
"""
Return a single representative occurrence for each variable.
"""
names = []
canonicals = []
for occ in occs:
if occ.name in names:
continue
canonicals.append(occ)
return canonicals | bigcode/self-oss-instruct-sc2-concepts |
def convert_to_babylonian_time(seconds):
###############################################################################
"""
Convert time value to seconds to HH:MM:SS
>>> convert_to_babylonian_time(3661)
'01:01:01'
"""
hours = int(seconds / 3600)
seconds %= 3600
minutes = int(seconds / ... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def load_yaml_file(file_name):
"""Load YAML file.
Parameters
----------
file_name: str or pathlib.Path
YAML file name.
Returns
--------
dict_data: dict
YAML contents.
"""
with open(file_name, 'r') as f:
dict_data = yaml.load(f, L... | bigcode/self-oss-instruct-sc2-concepts |
def within(self, index):
"""
Like between() but takes a pandas index object.
:param pandas.Index index: pandas index
:returns self: result of between() with start/end as the ends of the index.
"""
try:
start = index.min().start_time
end = index.max().end_time
except Attribut... | bigcode/self-oss-instruct-sc2-concepts |
def read_transcripts(transcript_file):
"""Return a dict containing transcript data with UCSC ID as key"""
transcripts = dict()
f_in = open(transcript_file)
for line in f_in:
data = line.rstrip('\n').split()
transcript_data = { 'chrom': data[2],
'start': int(da... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def batch_rotate_p4(batch, k, device=None):
"""Rotates by k*90 degrees each sample in a batch.
Args:
batch (Tensor): the batch to rotate, format is (N, C, H, W).
k (list of int): the rotations to perform for each sample k[i]*90 degrees.
device (str): the device to allocate... | bigcode/self-oss-instruct-sc2-concepts |
def lin_sum(x, lr, y):
"""Returns linear sum."""
return x + lr * (y - x) | bigcode/self-oss-instruct-sc2-concepts |
def select_tags(tag_list, key_list):
"""
Return selected tags from a list of many tags given a tag key
"""
select_list = []
# select tags by keys in key_list
for tag in tag_list:
for key in key_list:
if key == tag['Key']:
select_list.append(tag)
# ensure o... | bigcode/self-oss-instruct-sc2-concepts |
def huber(x, y, scaling=0.1):
"""
A helper function for evaluating the smooth L1 (huber) loss
between the rendered silhouettes and colors.
"""
diff_sq = (x - y) ** 2
loss = ((1 + diff_sq / (scaling**2)).clamp(1e-4).sqrt() - 1) * float(scaling)
return loss | bigcode/self-oss-instruct-sc2-concepts |
def fill_zero(df):
"""Fill NaN with zero."""
df = df.fillna(0)
return df | bigcode/self-oss-instruct-sc2-concepts |
def form_template_to_dict(formtemplate):
"""
Initializes a dictionary of form data from the given list-of-dictionaries
form template, as formatted above.
Args:
formtemplate (list of dicts): Tempate for the form to be initialized.
Returns:
formdata (dict): Dictionary of initalized f... | bigcode/self-oss-instruct-sc2-concepts |
def get_channel(driver, team_name, channel_name):
"""
Retrieve a channel given a team and channel name.
Returns the JSON response from the Mattermost API.
"""
response = driver.channels.get_channel_by_name_and_team_name(
team_name, channel_name)
return response | bigcode/self-oss-instruct-sc2-concepts |
def make_ewma_metric(metric, alpha):
""" Format the name of an EWMA metric. """
return f"{metric}-ewma-alpha{alpha}" | bigcode/self-oss-instruct-sc2-concepts |
def reporting_date(submission):
""" Format submission reporting date in MM/YYYY format for monthly submissions and Q#/YYYY for quarterly
Args:
submission: submission whose dates to format
Returns:
Formatted dates in the format specified above
"""
if not (submission.... | bigcode/self-oss-instruct-sc2-concepts |
def matrix_inverse(matrix):
"""Invert a 6-item homogenous transform matrix.
A transform matrix [a, b, c, d, e, f] is part of a 3x3 matrix:
a b 0
c d 0
e f 1
Invert it using the formula for the inverse of a 3x3 matrix from
http://mathworld.wolfram.com/MatrixInverse.html
"""... | bigcode/self-oss-instruct-sc2-concepts |
def build_code(codes_dict):
"""
Builds a code based on a codes dictionary
:param codes_dict: A dictionary with the code and whether it's flagged or not.
:return: The full code
"""
code = 0x00000000
for value in codes_dict.values():
if value[0]:
code += value[1]
retu... | bigcode/self-oss-instruct-sc2-concepts |
def count_ints(cxs):
"""
Given cxs, a list of [(name, set([id1,id2...])), ...], return the number of
possible positive pairwise interactions implied.
"""
def count_pairs(items):
n = len(items)
return int(n*(n-1)/2)
return sum([count_pairs(c[1]) for c in cxs]) | bigcode/self-oss-instruct-sc2-concepts |
def intersection(a, b):
"""
Returns the intersection of sets a and b.
In plain english:
Returns all the items that are in both a and b.
"""
return a.intersection(b) | bigcode/self-oss-instruct-sc2-concepts |
def options_as_dictionary(meta):
"""
Transforms a list of tuples to a dictionary
Args:
meta (list): A list ot option tuples
Retuns:
dict: A dictionary of options key - values
"""
module_config = {}
for seltuple in meta:
module_config.update({seltuple[0]: seltuple[1]})... | bigcode/self-oss-instruct-sc2-concepts |
def del_char_val(inline, char):
"""
Delete all chars matching the given parameter.
Args:
inline(str): Input string.
char(char): A character value which has to be deleted.
"""
return inline.replace(char, '') | bigcode/self-oss-instruct-sc2-concepts |
def get_subregion(row):
"""
Parse subregion and month names from SUBREGION row.
"""
cell_text = [cell.text_content().strip() for cell in row]
return cell_text[0], cell_text[3:] | bigcode/self-oss-instruct-sc2-concepts |
def is_str_or_list_str(s):
"""
Return boolean whether `s` is a string or list of strings.
"""
return isinstance(s, str) or \
(isinstance(s, list) and all(isinstance(x, str) for x in s)) | bigcode/self-oss-instruct-sc2-concepts |
def _namespaceTag(xmlns, tagName):
"""Preface an XML tag name with the provided namespace"""
return ''.join(["{", xmlns, "}", tagName]) | bigcode/self-oss-instruct-sc2-concepts |
def format_card(note: str) -> str:
"""Formats a single org-mode note as an HTML card."""
lines = note.split('\n')
if lines[0].startswith('* '):
card_front = '<br />{}<br />'.format(lines[0][2:])
else:
print('Received an incorrectly formatted note: {}'.format(note))
return ''
... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_files_from_pr(pr_num):
"""Return a list of changed files from a GitHub Pull Request
Arguments:
pr_num {str} -- Pull Request number to get modified files from
Returns:
{list} -- List of modified filenames
"""
files = []
pr_url = f"https://api.github.com... | bigcode/self-oss-instruct-sc2-concepts |
def is_right(gaze):
"""Returns true if the user is looking to the right"""
if gaze.pupils_located:
return gaze.horizontal_ratio() <= 0.5 | bigcode/self-oss-instruct-sc2-concepts |
def str_to_list(string, delim=',', type='float'):
""" Convert a str (that originated from a list) back
to a list of floats."""
if string[0] in ('[', '(') and string[-1] in (']', ')'):
string = string[1:-1]
if type == 'float':
lst = [float(num) for num in string.split(delim)]
elif ty... | bigcode/self-oss-instruct-sc2-concepts |
def argsort(seq, key=None):
""" equivalent of numpy's argsort in basic python
Modified after http://stackoverflow.com/questions/3382352/equivalent-of-numpy-argsort-in-basic-python
>>> a = ['a', 'd', 'c']
>>> argsort(a)
[0, 2, 1]
>>> argsort(a, key=lambda x: {'a':2,'c':1,'d':0}[x])
[1, 2, 0... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def get_dict_value_recursively(dct: Dict, key: str) -> Any:
"""
Nest into the dict given a key like root.container.subcontainer
Args:
dct: Dict to get the value from.
key: Key that can describe several nesting steps at one.
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def Crossing1Files(fileName, ind=None):
"""
Takes a filename of the structure used for the Crossing 1 videos - YYYMMDD_hhmmss-suffix.mkv
Retrieves the datetime of the start of the video
Input:
fileName: Name of the file
ind: Indicator of whether it is the left or right crop of the video... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def is_fitted(model):
"""Checks if model object has any attributes ending with an underscore"""
return 0 < len( [k for k,v in inspect.getmembers(model) if k.endswith('_') and not k.startswith('__')] ) | bigcode/self-oss-instruct-sc2-concepts |
def permission_to_string(perm):
"""
Transforms a Permission instance
into a string representation.
"""
app_label = perm.content_type.app_label
codename = perm.codename
return '%s.%s' % (app_label, codename) | bigcode/self-oss-instruct-sc2-concepts |
def convert_language_code_to_iso639_2(lang_code):
"""
Translate OpenSubtitle language code to its iso-639-2 equivalent.
OpenSubtitles seem to support some extensions to iso-639-2, for instance
"pob" means "brazilian portuguese".
See http://www.opensubtitles.org/addons/export_languages.php.
:p... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _except(txt, pattern):
"""
Show only text that does not match a pattern.
"""
rgx = "^.*({pattern}).*$".format(pattern=pattern)
unmatched = [
line for line in txt.splitlines() if not re.search(rgx, line, re.I)
]
return "\n".join(unmatched) | bigcode/self-oss-instruct-sc2-concepts |
def find_largest_anysize_at_xy(grid, x, y):
"""
Finds the largest sizexsize grid with top-left location (x,y).
"""
maxsize = min(300 - x, 300 - y)
record = grid[(x,y)]
record_tuple = (x, y, 1)
prevsize = record
for size in range(2, maxsize + 1):
cand = prevsize
for i in r... | bigcode/self-oss-instruct-sc2-concepts |
import pytz
def validate_timezone(zone):
"""Return an IETF timezone from the given IETF zone or common abbreviation.
If the length of the zone is 4 or less, it will be upper-cased before being
looked up; otherwise it will be title-cased. This is the expected
case-insensitivity behavior in the majorit... | bigcode/self-oss-instruct-sc2-concepts |
def good(seconds,needed_number_of_copies,x_seconds,y_seconds):
"""
This function is a little tricky
We need to make 2 copies as fast as possible. To do this, we need to use the copier that uses the minimum amount of time.
This minimum copier needs to run once to generate an extra copy
Consequentl... | bigcode/self-oss-instruct-sc2-concepts |
def xy(x:int, y:int) -> int:
"""Converts coordinates [x,y] in [(0-8),(0-8)] to [0-80] array location
"""
return y*9 + x | bigcode/self-oss-instruct-sc2-concepts |
def divide(x, y, use_floor=False):
"""
Divides two number
:param x: dividend
:param y: divisor
:param use_floor: flag to use floor division
:return: division of two numbers
"""
if use_floor:
return x // y
return x / y | bigcode/self-oss-instruct-sc2-concepts |
import json
def _get_as_str(input_value):
"""
Helper method to serialize.
:param input_value:
:type input_value: str or List of str
:return: serialized string
:rtype: str
"""
result = None
if input_value:
if type(input_value) == str:
result = input_value
... | bigcode/self-oss-instruct-sc2-concepts |
def assign_rows_helper(note_fields, table_row):
"""
Builds and returns a String of notes from the fields specified in :param
note_fields and populated with the data for those fields in :param
table_row
:param note_fields: Note fields from profile the user wants included in
the match sent to the... | bigcode/self-oss-instruct-sc2-concepts |
import json
def read_json_file(input_data):
"""Read data source file. File is in json format"""
with open(input_data, "r") as src:
data = json.load(src)
return data | bigcode/self-oss-instruct-sc2-concepts |
def get_weight(item):
"""Get sort weight of a given viewlet"""
_, viewlet = item
try:
return int(viewlet.weight)
except (TypeError, AttributeError):
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def nopat(operating_income, tax_rate):
"""
nopat = Net Operating Profit After Tax
"""
return operating_income * (1-(tax_rate/100)) | bigcode/self-oss-instruct-sc2-concepts |
def encryptxor(key, message):
"""
Takes two strings, key and message, and returns an encrypted ascii string
"""
message_ord = [ord(char) for char in message]
key_ord = [ord(key[index%len(key)]) for index in range(len(message))]
return "".join([chr(key_ord[i] ^ message_ord[i]) for i in range(len(... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def sqrt_PEHE(po: torch.Tensor, hat_te: torch.Tensor) -> torch.Tensor:
"""
Precision in Estimation of Heterogeneous Effect(PyTorch version).
PEHE reflects the ability to capture individual variation in treatment effects.
Args:
po: expected outcome.
hat_te: estimated outcom... | bigcode/self-oss-instruct-sc2-concepts |
def is_unique(digit, cell, grid):
"""
Checks if a given digit is unique across its row, column and subgrid.
Arguments:
digit {number} -- The digit to check for
cell {tuple} -- The (x, y) coordinates of the digit on the grid
grid {number matrix} -- The matrix to check the digit a... | bigcode/self-oss-instruct-sc2-concepts |
def _calc_bin_size(n_bins, t_start, t_stop):
"""
Calculates the stop point from given parameters.
Calculates the size of bins `bin_size` from the three parameters
`n_bins`, `t_start` and `t_stop`.
Parameters
----------
n_bins : int
Number of bins
t_start : pq.Quantity
S... | bigcode/self-oss-instruct-sc2-concepts |
def getShowId(show, conn):
"""
Return the show id given its name. (Database query)
:param show:
:param conn:
:return: id_show (integer)
"""
cur = conn.cursor()
cur.execute("SELECT id_show FROM show WHERE name=?", (show,))
id_show = cur.fetchone()[0]
return id_show | bigcode/self-oss-instruct-sc2-concepts |
def _explode_indexes(df, axis_type, drop_original=False):
"""
Performs an operation similar to explode, but uses the index of the cell as the differentiator.
:param df: the input dataframe of body cells
:param axis_type: either ``"row"`` or ``"column"``, determining which axis to be operating on.
:p... | bigcode/self-oss-instruct-sc2-concepts |
import re
def containChinese(content: str) -> bool:
""" 判断内容是否含有中文字符
Arguments:
content {string} -- 要检测的内容
Returns:
{bool} -- 是否包含中文
"""
zh_pattern = re.compile(
u'([\u4E00-\u9FA5]|[\u9FA6-\u9FEF]|[\u3400-\u4DB5]|[\U00020000-\U0002A6D6]|[\U0002A700-\U0002B734]|[\U0002B740... | 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.