seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def ok(ret_code: int) -> bool:
"""Convert a posix exit code to a boolean."""
return ret_code == 0 | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def _glob(filenames, pattern: str, invert: bool = False):
"""Applies a glob pattern to a string list of file names.
Args:
filenames: The list of file names.
pattern: The glob pattern to apply.
invert: If True, returns file names which evaluate to False.
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def flatten_list(lofl):
"""
Flatten a list of lists.
"""
new_list = []
for item in lofl:
if type(item) == list:
rl = flatten_list(item)
new_list.extend(rl)
else:
new_list.append(item)
return new_list | bigcode/self-oss-instruct-sc2-concepts |
def calc_intensity(locations):
""" Calculate intensity per location"""
max_duration = float(max(locations.values()))
result = {}
for key, value in locations.items():
result[key] = value/max_duration
return result | bigcode/self-oss-instruct-sc2-concepts |
import math
def split_dataset(inputs, targets, train_perc=0.7, val_perc=0.1, test_perc=0.2):
"""
Splits dataset into training, validation and test set
Output:
train-, validation- and test inputs : (percentage * n)x2 dimension FloatTensor
train-, validation- and test targets : (percentage * n... | bigcode/self-oss-instruct-sc2-concepts |
def assign_weights(context):
"""
Assign weights to securities that we want to order.
"""
long_weight = 0.5 / len(context.longs)
short_weight = -0.5 / len(context.shorts)
return long_weight, short_weight | bigcode/self-oss-instruct-sc2-concepts |
def fake_role(**kwargs):
"""Fixture to return a dictionary representing a role with default values set."""
kwargs.setdefault("id", 9)
kwargs.setdefault("name", "fake role")
kwargs.setdefault("colour", 7)
kwargs.setdefault("permissions", 0)
kwargs.setdefault("position", 55)
return kwargs | bigcode/self-oss-instruct-sc2-concepts |
def declare_variables(variables, macro):
"""
This is the hook for the functions
- variables: the dictionary that contains the variables
- macro: a decorator function, to declare a macro.
"""
variables['baz'] = "John Doe"
# Note - will need to switch the /master in the docs repo
# to match the... | bigcode/self-oss-instruct-sc2-concepts |
def degFormatter(deg):
"""Formats degrees as X˚
Args:
deg: float
Returns:
string
"""
return "${:d}^\circ$".format(int(deg)) | bigcode/self-oss-instruct-sc2-concepts |
def get_grams(sentence, n):
"""
Returns phrases i.e. windowed sub
strings with range (1-N) window
Keyword arguments:
sentence -- utterance (str)
n -- max_ngram (int)
"""
all_grams = []
for l in range(1, n + 1):
grams = [" ".join(sentence[i:i + l]) for i in range(len(sentence... | bigcode/self-oss-instruct-sc2-concepts |
def save_epoch(epoch, filename):
"""Save an epoch to a given filename
:param epoch:
The epoch that should be saved.
:type epoch: Epoch
:param filename:
The filename where to save the epoch
:type filename: str
"""
return epoch.save(filename) | bigcode/self-oss-instruct-sc2-concepts |
def dateToInt(date, strfmt='%Y%m%d'):
""" Converts a datetime date into int
Parameters:
-----------
date : datetime
date in datetime format
strfmt : string
format in which the int date will be generated
Example:
dateToInt(dt.date(2015,10,23),'%Y')
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def shout(text):
"""Return text in uppercase."""
return text.upper() | bigcode/self-oss-instruct-sc2-concepts |
def _window_has_intervening_extrema(window, contour, mode):
"""
Steps 8/9. If there exists a sequence of equal maxima or minima, check if the sequence
contains an intervening opposite extrema, i.e. if a sequence of two equal maxima contains
a minima between them.
>>> maxima_group = [
... (2, [2, {1}]),
... (4... | bigcode/self-oss-instruct-sc2-concepts |
def get_refdes_parts(anno_record):
""" Given an annotation record with a reference designator, return the corresponding subsite, node and sensor.
"""
subsite = None
node = None
sensor = None
refdes = anno_record.get('referenceDesignator')
if '-' not in refdes:
subsite = refdes
el... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def _serialize_comment(prefix: str, comment: Optional[str]) -> str: # pylint: disable=unsubscriptable-object
"""Serialize a comment, with an optional prefix."""
return "%s%s" % (prefix, comment) if comment else "" | bigcode/self-oss-instruct-sc2-concepts |
def safe_filename(name):
"""Utility function to make a source short-name safe as a
filename."""
name = name.replace("/", "-")
return name | bigcode/self-oss-instruct-sc2-concepts |
def rectangle_dot_count(vertices):
""" Count rectangle dot count include edge """
assert len(vertices) == 2
width = abs(vertices[0][0] - vertices[1][0])
height = abs(vertices[0][1] - vertices[1][1])
dot_count = (width + 1) * (height + 1)
return dot_count | bigcode/self-oss-instruct-sc2-concepts |
def GiB(val):
"""Calculate Gibibit in bits, used to set workspace for TensorRT engine builder."""
return val * 1 << 30 | bigcode/self-oss-instruct-sc2-concepts |
def gete2wlandw2el_fromdf(df, missingval='*'):
"""Get dict inputs for the EM algorithm from a pandas dataframe.
Parameters
----------
df: pandas.DataFrame
dataframe, indexed by the question, and where column names
represent the various workers. Entries are the labels assigned
by... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import re
import logging
def Prompt(message: str, validator: str = '.*') -> Optional[str]:
"""Prompt the user for input.
Args:
message: the prompt message displayed to the user
validator: a regular expression to validate any responses
Returns:
a response string if succe... | bigcode/self-oss-instruct-sc2-concepts |
def get_shorturl(ctx, slug):
"""Get the target of a shorturl by its slug."""
query = 'SELECT `target` FROM `shorturls_public` WHERE `slug` = %s'
ctx.execute(query, (slug))
candidate = ctx.fetchone()
return candidate['target'] if candidate else None | bigcode/self-oss-instruct-sc2-concepts |
def is_float(value):
"""Check if value is a float."""
return isinstance(value, float) | bigcode/self-oss-instruct-sc2-concepts |
def player_last_awarded_submission(profile):
"""Returns the last awarded submission date for the profile."""
entry = profile.scoreboardentry_set.order_by("-last_awarded_submission")
if entry:
return entry[0].last_awarded_submission
else:
return None | bigcode/self-oss-instruct-sc2-concepts |
def denormalize_colors(rgb_norm, mean_rgb=(0.485, 0.456, 0.406), std_rgb=(0.229, 0.224, 0.225)):
"""
Denormalize colors
Args:
rgb_norm: Image in RGB format, normalized by normalize_colors()
Numpy array of shape (h, w, 3)
mean_rgb, std_rgb: Mean and standard deviation for RGB cha... | bigcode/self-oss-instruct-sc2-concepts |
def isdict(mixed):
"""
Check if the given argument is a dict.
:param mixed:
:return: bool
"""
return isinstance(mixed, dict) | bigcode/self-oss-instruct-sc2-concepts |
def swagger_type_to_pydantic_type(t, models=[]):
"""Given a swagger type or format or ref definition, return its corresponding python type"""
# Take a swagger type and return the corresponding python type
if t in models:
return t
mapping = {
# swagger type: pydantic type (https://pydant... | bigcode/self-oss-instruct-sc2-concepts |
def getTol(**kwargs):
"""
Returns the tolerances based on kwargs.
There are two ways of specifying tolerance:
1. pass in "tol" which will set atol = rtol = tol
2. individually set atol and rtol.
If any values are unspecified, the default value will be used.
"""
DEFAULT_TOL = 1e-12
if... | bigcode/self-oss-instruct-sc2-concepts |
def get_seat_id(row, column):
"""Get seat id from row and column."""
return row * 8 + column | bigcode/self-oss-instruct-sc2-concepts |
def get_function_name(func):
""" Return the name of a function """
return func.__name__ | bigcode/self-oss-instruct-sc2-concepts |
def Name(uri):
"""Get just the name of the object the uri refers to."""
# Since the path is assumed valid, we can just take the last piece.
return uri.split('/')[-1] | bigcode/self-oss-instruct-sc2-concepts |
def write(fn, data):
"""
Write string to a file.
"""
f = open(fn, "w")
f.write(data)
f.close()
return True | bigcode/self-oss-instruct-sc2-concepts |
def rm_www_prefix(text):
"""
Remove www prefix
"""
prefix = "www."
if text.startswith(prefix):
return text[len(prefix) :]
return text | bigcode/self-oss-instruct-sc2-concepts |
def is_string(value, arg_name, logger=None):
"""
Verifies whether a parameter is correctly defined as string.
:param value: value of the parameter
:param arg_name: str, parameter name
:param logger: logger instance
:return: boolean, True if value is a string, False otherwis... | bigcode/self-oss-instruct-sc2-concepts |
def is_complex(object):
"""Check if the given object is a complex number"""
return isinstance(object, complex) | bigcode/self-oss-instruct-sc2-concepts |
import copy
def strip_registered_meta_comments(messy_dict_or_list, in_place=False):
"""Removes Prereg Challenge comments from a given `registered_meta` dict.
Nothing publicly exposed needs these comments:
```
{
"registered_meta": {
"q20": {
"comments": [ ... ], <~~... | bigcode/self-oss-instruct-sc2-concepts |
def int_to_hex(num):
"""Convert an int to a hexadecimal string"""
num = int(num)
vals = { 10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f'}
if num < 0:
sign = '-'
num = -num
else:
sign = ''
if num < 10:
return sign + str(num)
if num < 16:
return si... | bigcode/self-oss-instruct-sc2-concepts |
import string
import random
def random_string(n=5, uppercase=True):
"""Generates a random string of a given length, containing only uppercase letters and digits."""
letters = string.ascii_uppercase if uppercase else string.ascii_lowercase
return ''.join(random.choice(letters + string.digits) for _ in range(n)) | bigcode/self-oss-instruct-sc2-concepts |
def construct_return_statement(prediction, dog_detection, human_detection):
"""Construct a str return statement from predicted breed and results of dog/human detector."""
if dog_detection:
return 'This is a {}.'.format(prediction)
elif human_detection:
return 'This human looks like a {}.'.fo... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
import json
def jsonify(obj: Any) -> str:
"""Convert a Python object to JSON."""
return json.dumps(obj, sort_keys=True, indent=4) | bigcode/self-oss-instruct-sc2-concepts |
def RunLengthDecode(data):
"""
RunLength decoder (Adobe version) implementation based on PDF Reference
version 1.4 section 3.3.4:
The RunLengthDecode filter decodes data that has been encoded in a
simple byte-oriented format based on run length. The encoded data
is a sequence of runs... | bigcode/self-oss-instruct-sc2-concepts |
def poisson(t, y, den):
"""Poisson's equation for radially symmetric density den(r) = |u(r)|^2."""
y1, y2 = y
y1d = y2
y2d = -den(t) / t
return [y1d, y2d] | bigcode/self-oss-instruct-sc2-concepts |
def code_block(lines, language=''):
"""
Mark the code segment for syntax highlighting.
"""
return ['```' + language] + lines + ['```'] | bigcode/self-oss-instruct-sc2-concepts |
def normalize(s):
"""
Normalize strings to space joined chars.
Args:
s: a list of strings.
Returns:
A list of normalized strings.
"""
if not s:
return s
normalized = []
for ss in s:
tokens = [c for c in list(ss) if len(c.strip()) != 0]
normalized... | bigcode/self-oss-instruct-sc2-concepts |
def find_flat_segment(polygon):
"""
Find beginning and end indexes of a horizontal section in the polygon.
This section can be made of several consecutive segments.
If the polygon contains several flat sections, this function only identify the first one.
The polygon is a list of 2D coordinates (x, y... | bigcode/self-oss-instruct-sc2-concepts |
def test_classifier(classifier, inputs, labels):
"""Compute mean subset accuracy for a classifier.
Args:
classifier: A scikit-learn classifier.
inputs: a Kx464 array of linearised input images.
labels: a K-vector of integer labels.
Returns:
A scalar mean accuracy score.
"""
return classifier... | bigcode/self-oss-instruct-sc2-concepts |
import re
def name_check(name):
"""
NAME: name_check
----------
DESCRIPTION: Replaces and corrects users' park name query with a unique identifier in order
to save them searching for the exact name of the national park. Works for the top 20 national
parks in terms of number of visits.
----... | bigcode/self-oss-instruct-sc2-concepts |
def _get_outside_corners(corners, board):
"""
Return the four corners of the board as a whole, as (up_left, up_right, down_right, down_left).
"""
xdim = board.n_cols
ydim = board.n_rows
if corners.shape[1] * corners.shape[0] != xdim * ydim:
raise Exception("Invalid number of corners! %d... | bigcode/self-oss-instruct-sc2-concepts |
def c_to_f(temperature):
"""
Converts a temperature in Celsius to Fahrenheit.
"""
return temperature * 9 / 5 + 32 | bigcode/self-oss-instruct-sc2-concepts |
def get_intersection(u, v, node_presence):
"""
Get the intersection between the presence of u and v.
:param u: First Node
:param v: Second Node
:param node_presence: Node presence
:return: Interection
"""
intersec = []
for ut0, ut1 in zip(node_presence[u][::2], node_presence[u][1::2... | bigcode/self-oss-instruct-sc2-concepts |
def scale(df, samples, scale_value=100):
"""Return copy of dataframe with a set of columns normalized
Parameters
----------
df : pandas dataframe
The data frame to be normalized
samples : list of str
Column identifiers to use for indexing the data frame
scale_value : Optional[fl... | bigcode/self-oss-instruct-sc2-concepts |
def _check_array_range(istart, iend, npts):
"""
Takes two indices, checks that they are in the correct order, ie. start
is smaller than end, checks that start>=0 and end<=npts, and checks
that start!=end.
"""
istart = int(istart if istart<iend else iend)
iend = int(istart if istart>iend ... | bigcode/self-oss-instruct-sc2-concepts |
def GetObjcopyCmd(target):
"""Return a suitable objcopy command."""
if target == 'mips32':
return 'mipsel-nacl-objcopy'
return 'arm-nacl-objcopy' | bigcode/self-oss-instruct-sc2-concepts |
def c_to_f(c_temp):
"""
Converts from Celsius to Farenheint
"""
try:
return (float(c_temp) * 9.0 / 5.0) + 32.0
except ValueError:
return None | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_no_export_output(vm_host):
"""
Get no export routes on the VM
Args:
vm_host: VM host object
"""
out = vm_host.eos_command(commands=['show ip bgp community no-export'])["stdout"]
return re.findall(r'\d+\.\d+.\d+.\d+\/\d+\s+\d+\.\d+.\d+.\d+.*', out[0]) | bigcode/self-oss-instruct-sc2-concepts |
def iterable(item):
"""
Predicate function to determine whether a object is an iterable or not.
>>> iterable([1, 2, 3])
True
>>> iterable(1)
False
"""
try:
iter(item)
return True
except TypeError:
return False | bigcode/self-oss-instruct-sc2-concepts |
def get_geofence_collection_arn(region, account_id, collection_name):
""" Helper to convert Geofence Collection name to ARN, since this information is not available directly from the
Geofencing API. """
return f"arn:aws:geo:{region}:{account_id}:geofence-collection/{collection_name}" | bigcode/self-oss-instruct-sc2-concepts |
def tofloat(v):
"""Check and convert a string to a real number"""
try:
return float(v) if v != '.' else v
except ValueError:
raise ValueError('Could not convert %s to float' % v) | bigcode/self-oss-instruct-sc2-concepts |
def _pow(a, b):
"""C-like power, a**b
"""
return a**b | bigcode/self-oss-instruct-sc2-concepts |
import urllib.request
def get_htmls(urls, timeout):
"""get htmls from urls array.
args:
urls([str]): urls string array.
timeout(int): seconds
return:
[url, html]
url: str
html: str
"""
ret = []
for url in urls:
try:
with urllib.reques... | bigcode/self-oss-instruct-sc2-concepts |
def has_proper_name(user=None):
"""Whether user has enough data with which to form a proper name.
:param user: Django user object
:returns: True, False, or None (if unknown)
:rtype: bool | None
.. note::
User must be authenticated or function will return None.
"""
ret = None
... | bigcode/self-oss-instruct-sc2-concepts |
def tap(x, label=None):
"""Prints x and then returns it."""
if label:
print('%s: %s' % (label, x))
else:
print(x)
return x | bigcode/self-oss-instruct-sc2-concepts |
import re
def ParseHostPort(address):
"""Parses the provided address string as host:port and
returns a tuple of (str host, int port).
"""
host_port_re = re.match(r"([a-zA-Z0-9-\.]+):([0-9]{1,5})$", address)
if not host_port_re:
raise TypeError("bad host:port: %s" % address)
host = host_port_re.group(1... | bigcode/self-oss-instruct-sc2-concepts |
def compute_murphree_stage_efficiency(mu, alpha, L, V):
"""
Return the sectional murphree efficiency, E_mv.
Parameters
----------
mu: float
Viscosity [mPa*s]
alpha: float
Relative volatility.
L: float
Liquid flow rate by mol.
V: float
Vapor flow r... | bigcode/self-oss-instruct-sc2-concepts |
def fuselage(Sts,qm,Ltb):
""" Compute weifht estimate of human-powered aircraft fuselage
Assumptions:
All of this is from AIAA 89-2048, units are in kg. These weight estimates
are from the MIT Daedalus and are valid for very lightweight
carbon fiber composite structures. This may n... | bigcode/self-oss-instruct-sc2-concepts |
from decimal import Decimal
def euler_totient(num, factors):
"""
Given a number n and all its distinct prime factors, compute φ(n).
The insight is that for every distinct prime factor p of a number n, the portion of numbers coprime to A "decays" by exactly (1/p).
"""
totient = Decimal(num)
fo... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def get_bit_index(number: int) -> List[int]:
"""Get bit indices from number.
Args:
number: A number (greater than 0).
Returns:
List of bit indices.
Examples:
number: 4 (`100` in 2 ary number), Returns: [3]
number: 6 (`110` in 2 ary number), Re... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def process_image(ID, filename, method):
"""
POST request the user to process the image
Args:
ID (str): user name
filename (str): filename that should exist in database
method (str): processing method
Returns:
r6.json() (str): Confirmation that image w... | bigcode/self-oss-instruct-sc2-concepts |
def quantized_rotation(img, factor):
"""
Rotate an image counterclockwise by an integer factor times 90 degrees.
"""
if factor % 4 == 0:
pass
elif factor % 4 == 1:
img = img.transpose(-2, -1).flip(-1)
elif factor % 4 == 2:
img = img.flip(-2).flip(-1)
elif factor % 4 =... | bigcode/self-oss-instruct-sc2-concepts |
def byte2str(e):
"""Return str representation of byte object"""
return e.decode("utf-8") | bigcode/self-oss-instruct-sc2-concepts |
import torch
def generate_all_anchors(anchors, H, W):
"""
Generate dense anchors given grid defined by (H,W)
Arguments:
anchors -- tensor of shape (num_anchors, 2), pre-defined anchors (pw, ph) on each cell
H -- int, grid height
W -- int, grid width
Returns:
all_anchors -- tensor of ... | bigcode/self-oss-instruct-sc2-concepts |
def store_listings(db, listings):
"""
Store listings in database.
Listings already contained in the database are ignored.
Returns the number of listings that were stored.
"""
cursor = db.cursor()
tuples = [(x, y['street'], y['number'], y['suburb'], y['rent'],
y['area']) for x... | bigcode/self-oss-instruct-sc2-concepts |
def valid_command(val, valid=[]):
"""Validate given command among accepted set."""
#pylint: disable=dangerous-default-value
assert val in valid, 'invalid command: %s' % val
return val | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def _get_callable(obj, of_class = None):
""" Get callable for an object and its full name.
Supports:
* functions
* classes (jumps to __init__())
* methods
* @classmethod
* @property
:param obj: function|class
:type obj: Callable
:param of_class: Class that thi... | bigcode/self-oss-instruct-sc2-concepts |
def substr(word, pos, length):
"""Return the substr of word of given length starting/ending at pos; or None."""
W = len(word)
if pos >= 0 and pos+length <= W:
return word[pos:pos+length]
elif pos < 0 and abs(pos)+length-1 <= W:
return word[W+pos+1-length:W+pos+1]
else:
return... | bigcode/self-oss-instruct-sc2-concepts |
def spacing(space, IPA):
"""
Assign space based on its location
Parameters
----------
IPA : bool
A flag used to determine the type of alphabet
space : str
The type of space chosen by user
Returns
-------
list
a list of spaces for prefixes, suffixes, and word... | bigcode/self-oss-instruct-sc2-concepts |
def insert_roi(conn, cur, exp_id, series, offset, size):
"""Inserts an ROI into the database.
Args:
conn (:obj:`sqlite3.Connection): Connection object.
cur (:obj:`sqlite3.Cursor): Cursor object.
exp_id (int): ID of the experiment.
series (int): Series within the experiment. ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def normalize_name(name, separator="_"):
"""Normalizes a name by replacing all non-alphanumeric characters with underscores."""
return re.sub("[^A-Za-z0-9_]+", separator, name) | bigcode/self-oss-instruct-sc2-concepts |
def compose1(h, g):
"""Return a function f, such that f(x) = h(g(x))."""
def f(x):
return h(g(x))
return f | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def fixture_checksum_file(fixtures_dir: Path) -> Path:
"""Return the path to file to test checksum"""
return fixtures_dir / "26a90105b99c05381328317f913e9509e373b64f.txt" | bigcode/self-oss-instruct-sc2-concepts |
def create_query_string(graph_name: str, keyword: str):
"""
This methods generates the query string for the keyword-search in put.
:param graph_name: graph to be queried, default is "default graph",
like "<http://localhost:3030/60d5c79a7d2c38ee678e87a8/60d5c79d7d2c38ee678e87a9>"
:param keyword:... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import re
def extract_with_pattern(text: str, pattern: str) -> Optional[str]:
"""
Return the first found result of a given pattern in the string or None if not found
E.g: ('Test _t Test _t', '_t') -> '_t'
Args:
text: string to find the match
pattern: patter... | bigcode/self-oss-instruct-sc2-concepts |
import six
def _annotator_error_msg(ex):
"""
Formats a human readable error message.
:param ex:
:return:
"""
if isinstance(ex, six.string_types):
return ex
return '\n' + ex.__class__.__name__ + ': ' + str(ex) + '\n\n' | bigcode/self-oss-instruct-sc2-concepts |
def FirstValidDatum(data, default=None):
"""Gets the first valid datum or default.
Args:
data (list[event_data.EventDatum]): list of event data.
default (object): returned in case no no valid datum was found.
Returns:
event_data.EventDatum|object: first valid datum or default value.
"""
for datu... | bigcode/self-oss-instruct-sc2-concepts |
def _getoffsets(lineno, lineindex, data):
"""Return the (start, end) byte offsets for a given 1-based line number."""
offset = 0
if 1 <= lineno < len(lineindex):
offset = lineindex.select(lineno - 1)
else:
raise IndexError
nextoffset = lineindex.select(lineno)
# there is at least one newline, but there may be... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
from typing import Any
from typing import Optional
from typing import Type
def has_types_sequence(item: Sequence[Any]) -> Optional[tuple[Type[Any], ...]]:
"""Returns types contained in 'item'.
Args:
item (Sequence[Any]): item to examine.
Returns:
Optional[... | bigcode/self-oss-instruct-sc2-concepts |
def get_okta_group_name(prefix, account_id, role_name):
"""
Return an Okta group name specific to an account.
The format of the group name is '<prefix>_<account_id>_role'.
"""
group_name = prefix + "_" + account_id + "_" + role_name
print(f"get_okta_group_name() result is {group_name}")
retu... | bigcode/self-oss-instruct-sc2-concepts |
def is_ufshost_error(conn, cloud_type):
"""
Returns true if ufshost setting is not resolvable externally
:type conn: boto.connection.AWSAuthConnection
:param conn: a connection object which we get host from
:type cloud_type: string
:param cloud_type: usually 'aws' or 'euca'
"""
ufshost... | bigcode/self-oss-instruct-sc2-concepts |
def get_separator(handle):
""" get the column separator (assumes same on all lines)
"""
current = handle.tell()
line = handle.readline()
handle.seek(current)
if line.count('\t') > line.count(' '):
return '\t'
else:
return ' ' | bigcode/self-oss-instruct-sc2-concepts |
def cycle_checker(head):
"""Check if the Singly Linked List is cyclic.
Returns boolean value based on the result
"""
marker_1 = head
marker_2 = head
flag = False
while marker_2 != None and marker_2.next_node != None:
marker_1 = marker_1.next_node
marker_2 = marker_2.next_no... | bigcode/self-oss-instruct-sc2-concepts |
import time
def write_generator_lines(conctimes, concaz, concel, concva, concve, az_flags, el_flags):
"""
Produces a list of lines in the format necessary to upload to the ACU to complete a
generated scan. Params are the outputs of generate.
Params:
conctimes (list): List of times starting a... | bigcode/self-oss-instruct-sc2-concepts |
def is_valid_walk(walk):
"""
You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early
to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens
with a Walk Generating App on their phones -- e... | bigcode/self-oss-instruct-sc2-concepts |
def get_department_average_salary_service(department):
"""
Returns department average salary from db
:param department: department
:return: department average salary
"""
average_salary = 0
if department.employees:
for employee in department.employees:
average_salary += em... | bigcode/self-oss-instruct-sc2-concepts |
def get_filter_string(filter_dict):
"""
return a string like _F0_B50 for a dict like {'F': 0, 'B': 50}
"""
return "".join(
"_{}{}".format(k, filter_dict[k]) for k in sorted(filter_dict.keys())
) | bigcode/self-oss-instruct-sc2-concepts |
def get_aic(lnL, Nf):
"""
Provides the Akaike Information Criterion (Akaike, 1973), i.e. AIC.
Parameters
----------
lnL : float
Minus the log-likelihood.
Nf : int
Number of free parameters.
Returns
-------
AIC : float
AIC indicator.
"""
AIC = 2 * (... | bigcode/self-oss-instruct-sc2-concepts |
def mk_level(ptype):
"""Convert a Pylint warning "type" to a Sarif level"""
ldict = {'error': 'error',
'warning': 'warning',
'refactor': 'note',
'convention': 'note',
'usage': 'note'}
return ldict.get(ptype, 'note') | bigcode/self-oss-instruct-sc2-concepts |
def request_json_data(scraper, uri):
"""
A simple helper to return a dict when given the url of a json endpoint
"""
r = scraper.session.get(uri)
if r.status_code != 200:
raise ValueError("Failed to get url '{}' with status code {}.".format(uri, r.status_code))
return r.json() | bigcode/self-oss-instruct-sc2-concepts |
def unzip(ls, nout):
"""Unzip a list of lists into ``nout`` outputs."""
out = list(zip(*ls))
if not out:
out = [()] * nout
return out | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def has_output_type(cell, output_type: Union[set, str]):
"""
Select cells that have a given output_type
:param cell: Cell object to select
:param output_type: Output Type(MIME type) to select: text/plain, text/html, image/png, ...
:type output_type: str
:return: a boo... | bigcode/self-oss-instruct-sc2-concepts |
def ns(v):
"""Return empty str if bool false"""
return str(v) if bool(v) else '' | 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.