seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def get_all_duplicate(df, column_list):
"""
Get all duplicated rows.
Extract all rows that the return value of 'DataFrame.duplicated' is true.
Raises
------
ValueError
If the input DataFrame is empty.
Parameters
----------
df : DataFrame
Base dataframe (required)
... | bigcode/self-oss-instruct-sc2-concepts |
def isMixedCase (tok):
"""Returns true if the token contains at least one upper-case letter and another character type,
which may be either a lower-case letter or a non-letter. Examples: ProSys, eBay """
# Clojure original:
# (fn [token] ;; ProSys, eBay
# (if-not (empty? token)
... | bigcode/self-oss-instruct-sc2-concepts |
import statistics
def minMaxAvgPerBin(binnedResults, statFunction):
"""
For each bin in the binned results, find the minimum, maximum, and average of the value of the results determined
by statFunction. The constants MMAMin, MMAMax, and MMAAvg are meant for accessing the results tuple data.
:param bin... | bigcode/self-oss-instruct-sc2-concepts |
def is_heavy_atom(atom):
"""Check if an atom is neither a hydrogen or a virtual site."""
return not (atom.resname.startswith("H") or atom.resname.startswith("M")) | bigcode/self-oss-instruct-sc2-concepts |
def split_content(content):
"""
Split the rule into a list of bags.
"""
bags = []
# Return an empty list if there is no content.
if "no other" in content: return bags
# Separate each type of bag.
for bag in content.replace("bags", "").replace("bag", "").split(","):
# Separat... | bigcode/self-oss-instruct-sc2-concepts |
import re
def sanitize_output(output):
"""Redact access tokens from CLI output to prevent error messages revealing them"""
return re.sub(r"\"accessToken\": \"(.*?)(\"|$)", "****", output) | bigcode/self-oss-instruct-sc2-concepts |
def to_upper(text):
"""Convert word to uppercase."""
return text.upper().strip() | bigcode/self-oss-instruct-sc2-concepts |
def shiftLeft(input, p):
"""Take a bitstring 'input' of arbitrary length. Shift it left by 'p'
places. Left means that the 'p' most significant bits are shifted out
and dropped, while 'p' 0s are inserted in the the least significant
bits. Note that, because the bitstring representation is little-endian,... | bigcode/self-oss-instruct-sc2-concepts |
def get_y_values(x: int, slopes: list, coordinates, edge_count: int) -> list:
"""
Calculate the y value of the current x from each edge
:param x: x-coordinate of the current node
:param slopes:a list of slopes of all edges of the polygon
:param coordinates: a list of vertices of the polygon
:par... | bigcode/self-oss-instruct-sc2-concepts |
def create_norm_peptide_column_if_needed(row_meta_df, gcp_normalization_peptide_field, gcp_normalization_peptide_id):
"""If it doesn't already exist, create a new column indicating the norm
peptide for each probe.
Modifies row_meta_df in-place.
Args:
row_meta_df (pandas df):
gcp_normal... | bigcode/self-oss-instruct-sc2-concepts |
def get_peak_indices(uvvis_obj):
"""Finds indices of unique value/extinction objects at 'peak' scope
:param chemdataextractor.model.UvvisSpectrum uvvis_obj : UvvisSpectrum containng peak data
:returns
list value_peak_indices : UvvisPeak indices pointing to objects solely containing uvvis values
... | bigcode/self-oss-instruct-sc2-concepts |
import six
def _process_model_like_filter(model, query, filters):
"""Applies regex expression filtering to a query.
:param model: model to apply filters to
:param query: query to apply filters to
:param filters: dictionary of filters with regex values
:returns: the updated query.
"""
if q... | bigcode/self-oss-instruct-sc2-concepts |
def to_bool(cfg_value):
"""Convert config file booleans to Python booleans."""
if cfg_value in {"0", "false", "False", "no"}:
return False
if cfg_value in {"1", "true", "True", "yes"}:
return True
raise ValueError("Value {} in config file must be boolean in"
" a form... | bigcode/self-oss-instruct-sc2-concepts |
def solve_game(best_actions, game, state):
"""Returns the value of the state (to both players) and the optimal move to
play in this state. Fills in the dictionary 'best_actions' with the best
actions to take in all the states that are descendants of state (including
state).
"""
if game.is_termin... | bigcode/self-oss-instruct-sc2-concepts |
def truth(a):
"""Return True if a is true, False otherwise."""
return True if a else False | bigcode/self-oss-instruct-sc2-concepts |
def invert_permutation(perm):
"""Implement `invert_permutation`."""
return tuple(perm.index(i) for i in range(len(perm))) | bigcode/self-oss-instruct-sc2-concepts |
def manhattan_distance(point_1, point_2):
"""Return Manhattan distance between two points."""
return sum(abs(a - b) for a, b in zip(point_1, point_2)) | bigcode/self-oss-instruct-sc2-concepts |
import json
def save_json(input_dict, output_file):
"""save dictionary to file as json. Returns the output file written.
Parameters
==========
content: the dictionary to save
output_file: the output_file to save to
"""
with open(output_file, "w") as filey:
filey.writel... | bigcode/self-oss-instruct-sc2-concepts |
def dwid_exists(dwid, cursor):
"""See if a dwid exists in the database or not. If yes, return 1,
if not return 0."""
array = (dwid,)
cursor.execute('SELECT * from dwids where dwid=?', array)
if cursor.fetchone():
return 1
else:
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def standardize_name(name: str) -> str:
"""Remove spaces, hyphens, and make lowercase"""
if isinstance(name, str):
return name.replace('-', '').replace(' ', '').lower()
else:
return name | bigcode/self-oss-instruct-sc2-concepts |
def partition(array):
""" partition split array in half """
return [array[len(array)//2:], array[:len(array)//2]] | bigcode/self-oss-instruct-sc2-concepts |
def create_body_dict(name, schema):
""" Create a body description from the name and the schema."""
body_dict = {}
if schema:
body_dict['in'] = 'body'
body_dict['name'] = name
body_dict['schema'] = schema
if 'description' in schema:
body_dict['description'] = schem... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def add_noise(x_data, noise_std_percent):
"""
Adds normal noise to a dataset
@param noise_std_percent tensor with standard deviation of the noise,
as percent of the mean of the magnitude for that dimension
@return x_data_, same as x_data but with noise added to it
"""
assert (... | bigcode/self-oss-instruct-sc2-concepts |
def getDocComment(node):
"""
Returns the first doc comment of the given node.
"""
comments = getattr(node, "comments", None)
if comments:
for comment in comments:
if comment.variant == "doc":
return comment
return None | bigcode/self-oss-instruct-sc2-concepts |
def distance(a, b):
"""Return the distance between two points (rounded as per TSP datafile)"""
return int(abs(a - b) + 0.5) | bigcode/self-oss-instruct-sc2-concepts |
def find_class_in_dict(cls, d, include=None, exclude=None):
"""Get a list of keys that are an instance of a class in a dict"""
names = []
for key, value in d.copy().items():
if not isinstance(value, type):
continue
if issubclass(value, cls):
if include and include not... | bigcode/self-oss-instruct-sc2-concepts |
import codecs
import re
def get_replies(message_file, charset=None):
""" Finds replies within a message and returns a list containing each reply.
Args:
message_file (str): The email's filename.
charset (str): The optional codec to use for opening the file.
Returns:
list: ... | bigcode/self-oss-instruct-sc2-concepts |
def has_repeating_letter(text):
"""Check if a string has a repeating letter with one letter in between"""
# Check every combination of three letters
# and see if the first and third are the same.
# If there is any such combination, return True, False otherwise.
for i in range(len(text) - 2):
... | bigcode/self-oss-instruct-sc2-concepts |
import socket
def canonv4(text):
"""canonicalize an IPv4 address"""
if text is None:
return None
try:
addr = socket.inet_pton(socket.AF_INET, text)
return socket.inet_ntop(socket.AF_INET, addr)
except socket.error:
#print 'canonv4 failed on', text
return None | bigcode/self-oss-instruct-sc2-concepts |
def is_lock(lock):
"""
Tests if the given lock is an instance of a lock class
"""
if lock is None:
# Don't do useless tests
return False
for attr in ('acquire', 'release', '__enter__', '__exit__'):
if not hasattr(lock, attr):
# Missing something
retur... | bigcode/self-oss-instruct-sc2-concepts |
def printable_str(string):
""" Helper function to convert non-printable chars to its ASCII format """
new_str = ''
for char in string:
if ord(char) >= 32 and ord(char) <= 126:
new_str = new_str + char
else:
new_str = new_str + (r'\x%02x' % ord(char))
return new_... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import torch
def ConvNd(
dim: int,
in_channels: int,
out_channels: int,
kernel: int,
stride: int = 1,
dilation: int = 1,
groups: int = 1,
bias: bool = True,
transposed: bool = False,
output_padding: Optional[int] = None,
dtype=None,
):
"""Con... | bigcode/self-oss-instruct-sc2-concepts |
def _get_last_layer_units_and_activation(num_classes):
"""Gets the # units and activation function for the last network layer.
# Arguments
num_classes: int, number of classes.
# Returns
units, activation values.
"""
if num_classes == 2:
activation = 'sigmoid'
units ... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def qexp_t(q):
"""
Applies exponential map to log quaternion
:param q: N x 3
:return: N x 4
"""
n = torch.norm(q, p=2, dim=1, keepdim=True)
n = torch.clamp(n, min=1e-8)
q = q * torch.sin(n)
q = q / n
q = torch.cat((torch.cos(n), q), dim=1)
return q | bigcode/self-oss-instruct-sc2-concepts |
def solve1(a, b, EPS=1e-6):
"""
Returns root of equation a*x + b = 0.
"""
# a*x + b = 0
if abs(a) < EPS:
return ()
else:
return (complex(-b/a),) | bigcode/self-oss-instruct-sc2-concepts |
def get_val(op):
"""Get value of op."""
return op.gate.get_val() | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_data(pickle_file):
""" Load the data from given path.
Args:
pickle_file: pickle file of the requested data
Returns:
A tuple of (features, labels) for the given `pickle_file`
"""
with open(pickle_file, mode='rb') as f:
data = pickle.load(f)
retu... | bigcode/self-oss-instruct-sc2-concepts |
def check_FS_true(output_hdul):
"""
This function checks if the fits file is a Fixed Slit.
Args:
output_hdul: the HDU list of the output header keywords
Returns:
result: boolean, if true, the file is assumed to be Fixed Slit
"""
result = False
if "EXP_TYPE" in output_hdul:
... | bigcode/self-oss-instruct-sc2-concepts |
def get_key_value(line, sep=":", strip_whitespace=True):
"""
Split a string into key and value parts.
The string must have a separator defined as an argument.
By default, the separator is ":".
An example of a valid string is "name: John Doe ".
The result will be: ("name": "John Doe")
[param... | bigcode/self-oss-instruct-sc2-concepts |
def pool_list(transport, request, **kwargs):
"""Gets a list of pools
:param transport: Transport instance to use
:type transport: `transport.base.Transport`
:param request: Request instance ready to be sent.
:type request: `transport.request.Request`
:param kwargs: Optional arguments for this o... | bigcode/self-oss-instruct-sc2-concepts |
def ranks(x, reverse=False):
"""
Returns a tuple containing the rank of each element of the iterable `x`.
The ranks start at `0`. If `reverse` is `False`, the elements of `x` are
ranked in ascending order, and in descending order otherwise.
Equal elements will all be assigned the same (lowest-poss... | bigcode/self-oss-instruct-sc2-concepts |
def to_camel(string: str) -> str:
"""Convert snake_case to camelCase."""
words = []
for num, word in enumerate(string.split("_")):
if num > 0:
word = word.capitalize()
words.append(word)
return "".join(words) | bigcode/self-oss-instruct-sc2-concepts |
def inrange(value: int, down_limit: int, top_limit: int) -> bool:
"""
Check if number is in specified range and return bool.
"""
if value in range(down_limit, top_limit + 1):
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def vowel_count(phrase):
"""Return frequency map of vowels, case-insensitive.
>>> vowel_count('rithm school')
{'i': 1, 'o': 2}
>>> vowel_count('HOW ARE YOU? i am great!')
{'o': 2, 'a': 3, 'e': 2, 'u': 1, 'i': 1}
"""
d = {}
v = set('aeiou')
for c in phrase.l... | bigcode/self-oss-instruct-sc2-concepts |
def HImass2flux(m_hi, D):
"""
Converts HI masses into observed fluxes, depending on the distance
Input
-----
M : float or ndarray
HI mass in solar masses
D : float
Distance in Mpc
Returns
-------
S : Flux in Jy km/s
"""
S = m_hi / 2.36e5 / D**2
return S | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def get_rule_set(args):
"""Read and parse the config file at the location given when the
linter script is run.
Parameters
----------
args : argparse.Namespace
Arguments input when script is called from the console
Returns
-------
dict
Contains structured d... | bigcode/self-oss-instruct-sc2-concepts |
def str_range(start, end):
"""get range with string type"""
return [str(i) for i in range(start, end)] | bigcode/self-oss-instruct-sc2-concepts |
def get_moves(pos, xs, ys, step):
"""
Get the 5 possible moves from a position given a constant speed.
(left, right, forward, back, stay still)
:param pos:
:param xs:
:param ys:
:param step:
:return:
"""
moves = []
for dx, dy in [(-step, 0), (step, 0), (0, -step), (0, step), ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
def apply_weights(values: Sequence[float], weights: Sequence[float]):
"""
Returns values[0] * weights[0] + values[1] * weights[1] + ... + values[n] * weights[n]
"""
return sum([v[0] * v[1] for v in zip(values, weights)]) | bigcode/self-oss-instruct-sc2-concepts |
import math
def move_time(move, eres):
""" Calculates the time it takes to do a move.
Calculates how long it will take to complete a move of the motor. It
is assumed that the motor will decerate to a stop for the end of the
move as opposed to keep moving at velocity.
Everything is in motor units... | bigcode/self-oss-instruct-sc2-concepts |
def splitIndentDeepness(text):
"""
Return tuple (d, t) where d is deepness of indentation and t is text
without the indentation.
"""
pl = len(text)
text = text.lstrip()
return (pl-len(text), text) | bigcode/self-oss-instruct-sc2-concepts |
def mjd2met(mjd):
"""
Converts Modified Julian Day in Mission Elapsed Time (MET, in seconds).
Cf. http://fermi.gsfc.nasa.gov/ssc/data/analysis/documentation/Cicerone/Cicerone_Data/Time_in_ScienceTools.html
to see how the time is handled in the Fermi Science Tools.
Input: time in MJD (fraction of a... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def is_union(etype) -> bool:
""" Determine whether etype is a Union """
return type(etype) == type(Union) | bigcode/self-oss-instruct-sc2-concepts |
def figsize(relwidth=1, aspect=.618, refwidth=6.5):
"""
Return figure dimensions from a relative width (to a reference width) and
aspect ratio (default: 1/golden ratio).
"""
width = relwidth * refwidth
return width, width*aspect | bigcode/self-oss-instruct-sc2-concepts |
def trim_urls(attrs, new=False):
"""Bleach linkify callback to shorten overly-long URLs in the text.
Pretty much straight out of the bleach docs.
https://bleach.readthedocs.io/en/latest/linkify.html#altering-attributes
"""
if not new: # Only looking at newly-created links.
return attrs
... | bigcode/self-oss-instruct-sc2-concepts |
def format_error_code(errorCode: int, descriptions: list) -> str:
"""Emergency error code -> description.
Args:
errorCode: Error code to check.
descriptions: Description table with (code, mask, description) entries.
Returns:
Text error description.
"""
description = 'Unknow... | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_string_id(string_id):
"""Checks if a string is a valid user ID string"""
if re.match('<@![0-9]+>', string_id):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def parse_list(list_string):
"""
Parses IPv6/prefix/route list string (output of wpanctl get for properties WPAN_IP6_ALL_ADDRESSES,
IP6_MULTICAST_ADDRESSES, WPAN_THREAD_ON_MESH_PREFIXES, ...)
Returns an array of strings each containing an IPv6/prefix/route entry.
"""
# List string example (get(W... | bigcode/self-oss-instruct-sc2-concepts |
def n_params(model):
"""Return the number of parameters in a pytorch model.
Args:
model (nn.Module): The model to analyze.
Returns:
int: The number of parameters in the model.
"""
pp = 0
for p in list(model.parameters()):
nn = 1
for s in list(p.size()):
... | bigcode/self-oss-instruct-sc2-concepts |
def as_int(raw):
"""Return an int for the given raw value.
Return None for "falsey", non-zero values.
"""
if raw == 0:
return 0
elif not raw:
return None
else:
return int(raw) | bigcode/self-oss-instruct-sc2-concepts |
import random
def Jitter(values, jitter=0.5):
"""Jitters the values by adding a uniform variate in (-jitter, jitter)."""
return [x + random.uniform(-jitter, jitter) for x in values] | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def alphabetically_sorted_dict(d):
"""
Returns a dictionary with all keys recursively sorted alphabetically
"""
ordered = OrderedDict()
for k, v in sorted(d.items()):
if isinstance(v, dict):
ordered[k] = alphabetically_sorted_dict(v)
else:... | bigcode/self-oss-instruct-sc2-concepts |
def ensure_collection(value, collection_type):
"""Ensures that `value` is a `collection_type` collection.
:param value: A string or a collection
:param collection_type: A collection type, e.g. `set` or `list`
:return: a `collection_type` object containing the value
"""
return collection_type((v... | bigcode/self-oss-instruct-sc2-concepts |
def exclude_ancestor_filediffs(to_filter, all_filediffs=None):
"""Exclude all ancestor FileDiffs from the given list and return the rest.
A :pyclass:`~reviewboard.diffviewer.models.filediff.FileDiff` is considered
an ancestor of another if it occurs in a previous commit and modifies the
same file.
... | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_within_range(num_bytes, max_bytes=None):
"""Return a random int within range.
- If only ``num_bytes`` is set, return ``num_bytes``
- If both ``num_bytes`` and ``max_bytes`` are set, return random int within between
``num_bytes`` and ``max_bytes`` (including).
"""
r... | bigcode/self-oss-instruct-sc2-concepts |
def cleanup(run_dir):
"""
Cleans up the run directory.
"""
# Remove param_plots folder if empty
histo_dir = run_dir.joinpath('histogram_plots')
if histo_dir.is_dir() and not any(histo_dir.iterdir()):
histo_dir.rmdir()
# If run_dir is empty because there aren't enough good pixels, re... | bigcode/self-oss-instruct-sc2-concepts |
import glob
import shutil
def copy_egg_info(dest_dir):
"""Copies the .egg-info directory to the specified location.
Args:
dest_dir: str. The destination directory.
Returns:
0 on success, 1 on failure.
"""
# Remove any trailing slash on the destination directory.
dest_dir = dest_dir.rstrip('/')
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def get_project_config_from_user() -> Dict:
"""
Ask the user for the information for the project config.
Returns: A dictionary with the config for the project, including local_dir, target, remote_dir, and port.
"""
local_dir = input('Path to code_sync on this local machin... | bigcode/self-oss-instruct-sc2-concepts |
def get_wcs_ctype(wcs):
"""
Get celestial coordinate type of WCS instance.
Parameters
----------
wcs : `~astropy.wcs.WCS`
WCS transformation instance.
Returns
-------
ctype : {'galatic', 'icrs'}
String specifying the coordinate type, that can be used with
`~astr... | bigcode/self-oss-instruct-sc2-concepts |
def multiple(first,second):
"""Return multiplication of the 2 arguments.
Examples
--------
>>> multiple(4,5)
20
>>> multiple(2,1)
2
"""
return first * second | bigcode/self-oss-instruct-sc2-concepts |
import operator
def _ext_proc_tpls_to_procs(xps):
"""List processors by each priority.
:param xps: A list of (file_extension, processor_cls)
:return: List of [processor_cls]
"""
return sorted((operator.itemgetter(1)(xp) for xp in xps),
key=operator.methodcaller("priority")) | bigcode/self-oss-instruct-sc2-concepts |
import logging
def WriteToPoolCount(pool_d, rcbc_list,
counts, nSamples, out_prefix, indexes):
"""
Inputs:
pool_d (dict)
rcbarcode (s) => [barcode (str), scaffold (str), strand (str), pos (i)]
rcbc_list (list<str>): We get a list of all the rcbarcodes as they a... | bigcode/self-oss-instruct-sc2-concepts |
def reverse_str(numeral_str):
"""Reverses the order of a string."""
return numeral_str[::-1] | bigcode/self-oss-instruct-sc2-concepts |
def read_cols_query(col_names, table_name, schema_name):
"""
Obtain the query to read the columns from a table
:param col_names: (list of strs) list of cols names to read
:param table_name: (str) table name to read from
:param schema_name: (str) schema name of the table
:return:
A stri... | bigcode/self-oss-instruct-sc2-concepts |
from bs4 import BeautifulSoup
def lyrics_from_letrasmus(html):
"""Extracts lyrics from the html of a webpage of 'letras.mus.br'."""
lyrics = ''
soup = BeautifulSoup(html, 'html.parser')
verses = soup.select('.cnt-letra article p')
for para in verses:
lyrics += para.get_text('\n') + '\n\n... | bigcode/self-oss-instruct-sc2-concepts |
def normalize_key(key: str):
""" Normalize CSV header values """
key = key.lower().replace('_', '').replace('-', '').replace(' ', '')
return {
'startdatetime': 'start_date_time',
'enddatetime': 'end_date_time',
'resultslocation': 'results_location'
}.get(key, key) | bigcode/self-oss-instruct-sc2-concepts |
def reflect(cp, anchor):
"""
Reflect the point `cp` through the anchor.
"""
vec = (cp[0] - anchor[0], cp[1] - anchor[1])
neg = (-vec[0], -vec[1])
return (anchor[0] + neg[0], anchor[1] + neg[1]) | bigcode/self-oss-instruct-sc2-concepts |
import zlib
def zlib_encode(input,errors='strict'):
""" Encodes the object input and returns a tuple (output
object, length consumed).
errors defines the error handling to apply. It defaults to
'strict' handling which is the only currently supported
error handling for this codec.... | bigcode/self-oss-instruct-sc2-concepts |
def getitem(obj, item):
"""Grab the item from the object.
Example usage:
someObj|getitem:key
"""
return obj[item] | bigcode/self-oss-instruct-sc2-concepts |
def _get_list_traj(trajectory):
"""Return a list of (proxy) snapshots from either a list or Trajectory
Parameters
----------
trajectory : :class:`.Trajectory` or :class:`.list`
trajectory or list to convert into a list of snapshots
Returns
-------
:class:`.list`
list of (prox... | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_empty_line(line: str):
"""Check if line is empty. Returns True if line contains only whitespaces"""
return bool(re.match(r"\s*\n", line)) | bigcode/self-oss-instruct-sc2-concepts |
def is_json_string(text: str) -> bool:
"""
Given an input text, is_json_string returns `True` if it is a valid JSON string, or False otherwise.
The definition of a valid JSON string is set out in the JSON specification available at https://json.org/.
Specifically, the section on strings defines them as: "A string ... | bigcode/self-oss-instruct-sc2-concepts |
def matches(value, attr_list):
"""Return whether value matches the attribute described by attr_list
Attributes come from mutagen as lists of strings (except for the "path"
attribute). If the value is surrounded by double quotes, we look for exact
matches; otherwise, we join together the attribute list ... | bigcode/self-oss-instruct-sc2-concepts |
import struct
def retrieve_message(conn, out_format):
"""Retrieve a message from the client.
Parameters
----------
conn : socket.socket
socket for server connection
out_format : str or None
format of the output structure
Returns
-------
Any
received message
... | bigcode/self-oss-instruct-sc2-concepts |
def bits_to_target(bits):
""" Decodes the full target from a compact representation.
See: https://bitcoin.org/en/developer-reference#target-nbits
Args:
bits (int): Compact target (32 bits)
Returns:
target (Bignum): Full 256-bit target
"""
shift = bits >> 24
target = (bits &... | bigcode/self-oss-instruct-sc2-concepts |
def XOR(a, b):
""" Returns a XOR b (the 'Exclusive or' gate)
Args:
a (bool): First input
b (bool): Second input
Returns:
bool: The output of the XOR gate
"""
return ( a - b ).abs() | bigcode/self-oss-instruct-sc2-concepts |
def filter_out_none(dictionary, keys=None):
""" Filter out items whose value is None.
If `keys` specified, only return non-None items with matched key.
"""
ret = {}
if keys is None:
keys = []
for key, value in dictionary.items():
if value is None or key not in keys:
... | bigcode/self-oss-instruct-sc2-concepts |
def read(filename, binary=True):
"""
Open and read a file
:param filename: filename to open and read
:param binary: True if the file should be read as binary
:return: bytes if binary is True, str otherwise
"""
with open(filename, 'rb' if binary else 'r') as f:
return f.read() | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def prime_factors(n: int) -> List[int]:
"""
Returns prime factors of n as a list.
>>> prime_factors(0)
[]
>>> prime_factors(100)
[2, 2, 5, 5]
>>> prime_factors(2560)
[2, 2, 2, 2, 2, 2, 2, 2, 2, 5]
>>> prime_factors(10**-2)
[]
>>> prime_factors(0.02)... | bigcode/self-oss-instruct-sc2-concepts |
def color_float_to_hex(r, g, b):
"""Convert RGB to hex."""
def clamp(x):
x = round(x*255)
return max(0, min(x, 255))
return "#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b)) | bigcode/self-oss-instruct-sc2-concepts |
def propeller_navbar(navbar):
"""
Render a navbar.
**Tag name**::
propeller_navbar
**Parameters**:
navbar
The previously defined navbar instance
**Usage**::
{% propeller_navbar navbar_instance %}
"""
return navbar.as_html() | bigcode/self-oss-instruct-sc2-concepts |
def is_placement_possible(y, x, n, board):
"""
Returns whether or not a number can be placed at a provided coordinate
This function uses the following format: board[y][x] == is_placement_possible(n)?
:param x: the provided x coordinate (the column number from left)
:param y: the provided y coordinate (the row num... | bigcode/self-oss-instruct-sc2-concepts |
def moeda(preco=0, valor='R$'):
"""
-> Faz a conversão do número real para moeda R$.
:param preco: preço a ser convertido.
:param valor: definida como padrão para o Real Brasileiro.
:return: retorna o preço formatado no Real Brasileiro.
"""
return f'{valor}{preco:.2f}'.replace('.', ',') | bigcode/self-oss-instruct-sc2-concepts |
def totalCredits (theDictionary):
"""Calculates the total credits student is taking this semester.
:param dict[str, int] theDictionary: The student's class information
with the class as the key and the number or credits as the value
:return: The total credits
:rtype: int
"""
total = 0 ... | bigcode/self-oss-instruct-sc2-concepts |
def _cap_first(s: str) -> str:
"""Returns string with first character capitalized. Why this isn't in
the Python stdlib is beyond me. The capitalize() function annoyingly
lowercases the rest of the string."""
return s[:1].upper() + s[1:] if s else s | bigcode/self-oss-instruct-sc2-concepts |
def calc_radiated_power_nadir(radiance_integrated,
pixel_resolution_along,
pixel_resolution_cross):
"""
Calculate the power radiated from a ground pixel at Nadir.
Returns
-------
double : Watts per Sterradian.
"""
return radiance_... | bigcode/self-oss-instruct-sc2-concepts |
def init_Npad(ROI, compression = 8):
"""Calculate the Npad for padding
can be adjusted with compression parameter
By default, 8 times smaller than ROI
"""
if (ROI[2]-ROI[0])>(ROI[3]-ROI[1]):
Npad = (ROI[2]-ROI[0])//compression
else:
Npad = (ROI[3]-ROI[... | bigcode/self-oss-instruct-sc2-concepts |
def auto_capitalize(text, state = None):
"""
Auto-capitalizes text. `state` argument means:
- None: Don't capitalize initial word.
- "sentence start": Capitalize initial word.
- "after newline": Don't capitalize initial word, but we're after a newline.
Used for double-newline detection.
... | bigcode/self-oss-instruct-sc2-concepts |
def get_bearer_token(request):
"""Extracts a Bearer authentication token from the request and returns it if present, None
otherwise."""
auth = request.headers.get("Authorization")
if auth is not None:
try:
method, content = auth.split(" ")
if method == "Bearer":
... | bigcode/self-oss-instruct-sc2-concepts |
import csv
def specification_file_read(spec_file_name):
"""
Returns the input from a CSV file as a dictionary.
Args:
- spec_file_name (String): Path to the CSV file.
Returns:
- (Dictionary(String:String)): Returns a list of Dictionaries mapping
the tables row entrys to the co... | 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.