seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import datetime
import datetime
def get_dates(start_date,end_date):
"""
Creates a list of dates in string format 'Y-M-D'
Yields
------
list
Note
------
To change collection time frame, mend start_date and end_date
"""
# the command argument is a string
# convert the strin... | bigcode/self-oss-instruct-sc2-concepts |
def format_platform(platform):
"""Return formatted uppercase or capitalized platform value"""
if platform == "linux" or platform == "windows":
return platform.capitalize()
else:
return platform.upper() | bigcode/self-oss-instruct-sc2-concepts |
def is_route_login_required(fn):
"""
Determine if a function is decorated to require a logged-in session.
:param fn: The function to check.
:return: True if this function requires a logged-in session, False otherwise.
"""
return hasattr(fn, "route_login_required") and fn.route_login_required | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_changes(changes_file):
"""Obtain changes from a changes file."""
with open(changes_file, "r") as ch_file:
return json.load(ch_file) | bigcode/self-oss-instruct-sc2-concepts |
def clean_tokens(tokens, callback=lambda token: token):
"""
>>> clean_tokens(['Hello', '3', 'P.M.'])
['hello', '3', 'p.m.']
>>> clean_tokens(['Hello', '3', 'P.M.'], lambda token: token.replace('.', ''))
['hello', '3', 'pm']
"""
return [callback(token.lower()) if isinstance(token, str)
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_error_instance_ids_by_class(model, batch_ids, batched_evaluation_data, batched_evaluation_target,
device="cpu"):
"""
Return the instance ids corresponding to errors of the model by class.
Args:
model: The model being evaluated.
batc... | bigcode/self-oss-instruct-sc2-concepts |
import csv
def get_reactions(input_file):
"""
Get all the reactions from the input file
Reads the input file and gets the reactions that the user might
want to add to the universal model.
Input file must be in the same folder as the script.
The file name must be a string including .csv ext... | bigcode/self-oss-instruct-sc2-concepts |
def have_shared_allelic_variation( ref_string, qry_string ):
"""
Because the VCF files have ellele columns with comma-separated values, this function
takes two of them and looks for any single shared allele among them, returning True
if one is found.
"""
refs = ref_string.split(",")
qrys = q... | bigcode/self-oss-instruct-sc2-concepts |
def construct_filter_url(zipcode, page_num=1):
"""
Return a landing url that filters by zipcode. page_num is used to determine the page of the search
results. Redfin search results are up to 18 pages long.
In the current version, the filter is set to 'sold-3yr' and
could be expanded to include 'sol... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
def make_task_name_to_index_map(
lifelong_learning_task_names: List[str]) -> Dict[str, int]:
"""Creates a map going from the task name to the task index.
The tasks might be repeated, so task indexes aren't just a range.
"""
task_name_to_task_ind... | bigcode/self-oss-instruct-sc2-concepts |
async def get_health():
"""
Check health of service.
"""
return {"status": "OK"} | bigcode/self-oss-instruct-sc2-concepts |
def titleType(dataFrame):
"""
Count how many series and movies exists in the dataFrame.
Used for mostWatchedType visualization
Parameters:
dataFrame: string
The name of the dataFrame the user wants to work with.
Returns:
a dataFrame
"""
dataFrameTypeCount = da... | bigcode/self-oss-instruct-sc2-concepts |
def to_bytes(string):
"""Converts a string with a human-readable byte size to a number of
bytes. Takes strings like '7536 kB', in the format of proc."""
num, units = string.split()
num = int(num)
powers = {'kb': 10, 'mb': 20, 'gb': 30}
if units and units.lower() in powers:
num <<= power... | bigcode/self-oss-instruct-sc2-concepts |
def format_as(format_string):
"""format_as(form)(obj) = form % obj
Useful to format many objects with the same format string.
>>> list(map(format_as("0x%x"), [0, 1, 10, 11, 15]))
['0x0', '0x1', '0xa', '0xb', '0xf']
"""
return lambda obj : format_string % obj | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Any
import random
def generate_random_batches(values: List[Any], min_batch_size: int, max_batch_size: int) -> List[List[Any]]:
"""
Generate random batches of elements in values without replacement and return the list of all batches. Batch sizes
can be anything be... | bigcode/self-oss-instruct-sc2-concepts |
def pig_actions_d(state):
"""The legal actions from a state. Usually, ["roll", "hold"].
Exceptions: If double is "double", can only "accept" or "decline".
Can't "hold" if pending is 0.
If double is 1, can "double" (in addition to other moves).
(If double > 1, cannot "double").
"""
# state is... | bigcode/self-oss-instruct-sc2-concepts |
def tail_stream(stream, nlines=10):
"""Returns last N lines from the io object (file or io.string)."""
# Seek to eof, backtrack 1024 or to the beginning, return last
# N lines.
stream.seek(0, 2)
fsize = stream.tell()
stream.seek(max(fsize - 1024, 0), 0)
lines = stream.readlines()
return ... | bigcode/self-oss-instruct-sc2-concepts |
def timedelta2seconds(delta):
"""
Convert a datetime.timedelta() objet to a number of second
(floatting point number).
>>> timedelta2seconds(timedelta(seconds=2, microseconds=40000))
2.04
>>> timedelta2seconds(timedelta(minutes=1, milliseconds=250))
60.25
"""
return delta.microsecon... | bigcode/self-oss-instruct-sc2-concepts |
def get_assumed_creds(sts, arn):
"""Retrieves the AWS assume role credentials.
Args:
sts: boto3 sts object
arn: Arn of the role we want to assume
Returns:
AWS credentials
"""
if arn:
credentials = sts.assume_role(
RoleArn=arn,
RoleSessionName... | bigcode/self-oss-instruct-sc2-concepts |
def get_full_verbs(tokens):
"""Identify, color and count full verbs """
full_verbs = [k for k in tokens if k.full_pos.startswith('VV')]
for t in full_verbs:
t.pos_color.append('Full verbs')
return len(full_verbs) | bigcode/self-oss-instruct-sc2-concepts |
import math
def length_of_degree(lat):
"""Calcualte the length of a degree in meters."""
m1 = 111132.92
m2 = -559.82
m3 = 1.175
m4 = -0.0023
p1 = 111412.84
p2 = -93.5
p3 = 0.118
lat_rad = lat * math.pi / 180
latlen = (
m1 + m2 * math.cos(2 * lat_rad) + m3 * math.cos(4 *... | bigcode/self-oss-instruct-sc2-concepts |
def hexstr(s):
"""Compact inline hexdump"""
return ' '.join(['%02x' % ord(b) for b in s]) | bigcode/self-oss-instruct-sc2-concepts |
def _prefixed_flag_vals(prefixes, flag_vals):
"""Returns a dict of prefixed flag values.
Prefixes are stripped from matching flag names.
The value for the first matching prefix from prefixes is used.
"""
prefixed = {}
for prefix in prefixes:
for full_name in flag_vals:
if f... | bigcode/self-oss-instruct-sc2-concepts |
def navigation_key_expected_key_pair(request):
"""
Fixture to generate pairs of navigation keys with their respective
expected key.
The expected key is the one which is passed to the super `keypress` calls.
"""
return request.param | bigcode/self-oss-instruct-sc2-concepts |
def parabola_through_three_points(p1, p2, p3):
"""
Calculates the parabola a*(x-b)+c through three points. The points should be given as (y, x) tuples.
Returns a tuple (a, b, c)
"""
# formula taken from http://stackoverflow.com/questions/4039039/fastest-way-to-fit-a-parabola-to-set-of-points
# A... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_access_token(username, password, client_id, client_secret):
"""
Get the Netatmo access token
:param username: Netamo username
:param password: Netamo password
:param client_id: Netamo Client ID
:param client_secret: Netamo Client Secret
:return: access token
"""... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Any
def read_keyword_list(keywords: List[Any], list_length: int) -> List[Any]:
"""Reads a number of tokens from a keyword list and returns as separate list"""
newlist = []
#Uses a loop like this to ensure the original list is modified when removing keywords, rath... | bigcode/self-oss-instruct-sc2-concepts |
def split_tag(chunk_tag):
"""
split chunk tag into IOBES prefix and chunk_type
e.g.
B-PER -> (B, PER)
O -> (O, None)
"""
if chunk_tag == 'O':
return ('O', None)
return chunk_tag.split('-', maxsplit=1) | bigcode/self-oss-instruct-sc2-concepts |
def apply_image_filter(image, image_filter=None):
"""
unpacking / pseudo-dispatch function
`image_filter` is a dict() that contains 'params' and 'function'
keys. The optional 'params' value is a parameters dict() and the 'function'
value is the corresponding function to run on `image`.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
import math
def angleBetweenPoints( firstPoint, secondPoint ):
"""
Returns the angle (in degrees) of the straight line between firstPoint and secondPoint,
0 degrees being the second point to the right of first point.
firstPoint, secondPoint: must be NSPoint or GSNode
"""
xDiff = secondPoint.x - firstPoint.x
yD... | bigcode/self-oss-instruct-sc2-concepts |
def find_example3(sequence):
"""
Returns the FIRST STRING in the given sequence,
or None if the sequence contains no strings.
"""
# Returns the item ( sequence[k] ) or None
for k in range(len(sequence)):
if type(sequence[k]) == str:
return sequence[k]
return None | bigcode/self-oss-instruct-sc2-concepts |
def get_num_rows(puzzle: str) -> int:
"""Return the number of rows in puzzle.
puzzle is a game board.
>>> get_num_rows('abcd\nefgh\nijkl\n')
3
"""
return puzzle.count('\n') | bigcode/self-oss-instruct-sc2-concepts |
import torch
def generate_anchors(anchor_shapes, grid_centers):
"""
Generate all anchors.
@Params:
-------
anchor_shapes (tensor):
Tensor of shape [A, 2] giving the shapes of anchor boxes to consider at each
point in the grid. anchor_shapes[a] = (w, h) indicate width and height
... | bigcode/self-oss-instruct-sc2-concepts |
def parse_string(parser, header, arg_name, arg_value):
"""
Parse an argument from the given parser. If the argument is not specified, return the default value
:param parser: the parser to be used for parsing
:param header: name of the header in the configuration file
:param arg_name: name in the con... | bigcode/self-oss-instruct-sc2-concepts |
def msg2typestr(msg):
"""
Introspects the message type from the passed in `msg` and encodes it as a
string in the format required by rosbag2.
Parameters
----------
msg : Message
A ROS 2 message (deserialized) whose type we need to introspect
Returns
-------
A string encoding ... | bigcode/self-oss-instruct-sc2-concepts |
def timedelta2duration(delta):
"""
Convert a datetime.timedelta to ISO 8601 duration format
Parameters
----------
delta : datetime.timedelta
Returns
-------
str
"""
s = "P"
if delta.days:
s += f"{delta.days}D"
if delta.seconds or delta.microseconds:
sec ... | bigcode/self-oss-instruct-sc2-concepts |
def mean(mylist):
"""
Returns the mean value of a list
"""
total = 1.0 * sum(mylist)
length = len(mylist)
if length == 0.0:
raise ArithmeticError(
"Attempting to compute the mean of a zero-length list")
return (total / length) | bigcode/self-oss-instruct-sc2-concepts |
def format_font_name(value):
"""Formats a font name into the display version"""
return value \
.replace('_', ' ') \
.title() | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def get_resource_type(pth: Path) -> str:
"""Get the resource type from the path - useful for finding the right resources."""
typ = Path(pth).parts[1].replace('_backfill', '')
return typ | bigcode/self-oss-instruct-sc2-concepts |
import requests
import zipfile
import io
def get_files(code):
"""
A wrapper function to obtain .csv files from the world bank.
Parameters:
-----------
code: str
The code of the indicator.
Returns:
--------
str
downloaded .csv filename
"""
r = requests.... | bigcode/self-oss-instruct-sc2-concepts |
def parse_col_name(col_name):
""" Standardize column name `col_name`
"""
return col_name.upper().strip() | bigcode/self-oss-instruct-sc2-concepts |
def _update_globals(task_file_to_run, globals_dict):
"""Updates globals dictionary with default data path for provided
task if Inputs/Outputs directories are equal to None.
Args:
task_file_to_run (str): path to the task that will be run.
globals_dict (dict): contains global variables for f... | bigcode/self-oss-instruct-sc2-concepts |
import json
def create_error_response(error):
"""
Create error response from an error exception
Parameters
----------
error : Exception
An error exception
Returns
-------
string
A JSON string of the error response
"""
error_response = json.dumps({
'sta... | bigcode/self-oss-instruct-sc2-concepts |
def _is_json(q):
"""Check if q is JSON.
Parameters
----------
q : str
Query string.
Returns
-------
bool
True if q starts with "{" and ends with "}".
"""
return q.strip().startswith("{") and q.strip().endswith("}") | bigcode/self-oss-instruct-sc2-concepts |
def ComputeR(edge_weights):
""" Computes the value of R (sum of edge weights) given the edge weights of a graph. """
sume = 0
for (i, j) in edge_weights.keys():
sume += edge_weights[(i, j)]
return sume | bigcode/self-oss-instruct-sc2-concepts |
def str_list(input_list):
""" Convert all the elements in a list to str
Args:
input_list: list of any elements
Returns: list of string elements
"""
return ['{}'.format(e) for e in input_list] | bigcode/self-oss-instruct-sc2-concepts |
import torch
from typing import Dict
def standardize(
x: torch.Tensor,
stats: Dict[str, torch.Tensor]) -> torch.Tensor:
"""Standardize a tensor using precalculated global mean and std.
Parameters
----------
x
A tensor to be standardized.
stats
A dict with keys ``me... | bigcode/self-oss-instruct-sc2-concepts |
import re
def filter_re_replace(val, pattern, repl):
"""Perform a regexp replacement on the given string."""
return re.sub(pattern, repl, str(val)) | bigcode/self-oss-instruct-sc2-concepts |
def unpack_transform_msg(msg, stamped=False):
""" Get translation and rotation from a Transform(Stamped) message. """
if stamped:
t = msg.transform.translation
r = msg.transform.rotation
else:
t = msg.translation
r = msg.rotation
return (t.x, t.y, t.z), (r.w, r.x, r.y, r... | bigcode/self-oss-instruct-sc2-concepts |
def make_poem_html(poem, pid):
"""This function makes a section of HTML code for a poem.
Args:
poem: A poem defined as a list (rows) of lists (words in rows).
pid: HTML <p> tag ID attribute for CSS identification.
Returns:
A string containing HTML code for displaying a poem, for ex... | bigcode/self-oss-instruct-sc2-concepts |
def _img_crop(im, x_pos, y_pos, radius, im_shape):
"""
Perform crop of the image.
Crop the region of the image containing the cell of interest.
Parameters
----------
im : numpy.array
Fluorescence microscopy image.
x_pos : int
:math:`x`-coordinate of the center of the cell o... | bigcode/self-oss-instruct-sc2-concepts |
def scrub_response(secret):
"""Helper function that provides a filter function for stripping secrets
from HTTP responses before they are stored by vcrpy
Based on the example implementation found her:
https://vcrpy.readthedocs.io/en/latest/advanced.html#custom-response-filtering
Example:
>... | bigcode/self-oss-instruct-sc2-concepts |
def to_int(n):
"""Converts a string to an integer value. Returns None, if the string cannot be converted."""
try:
return int(n)
except ValueError:
return None | bigcode/self-oss-instruct-sc2-concepts |
import re
def validate_period_format(period_str):
"""validates a period in string format
Args:
period_str (string): period in string format starting with a
number and ending with the letters m, h or d, for minutes, hour and day,
respectively.
Returns:
bool: True if the period is valid, else F... | bigcode/self-oss-instruct-sc2-concepts |
def get_upper_long_from_trace_id(trace_id):
"""Returns the upper 8 bytes of the trace ID as a long value, assuming
little endian order.
:rtype: long
:returns: Upper 8 bytes of trace ID
"""
upper_bytes = trace_id[:16]
upper_long = int(upper_bytes, 16)
return upper_long | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
import operator
def birthday_problem(g, n):
"""returns the probability that n independent choices from a set of g objects are all unique"""
return reduce(operator.mul, [float(g-i)/g for i in range(0, n)]) | bigcode/self-oss-instruct-sc2-concepts |
def remove_private_prefix(attr_name: str, prefix: str) -> str:
"""Return the specified attribute name without the specified prefix."""
return attr_name[len(prefix):] | bigcode/self-oss-instruct-sc2-concepts |
def default_archiver(random, population, archive, args):
"""Do nothing.
This function just returns the existing archive (which is
probably empty) with no changes.
.. Arguments:
random -- the random number generator object
population -- the population of individuals
archive... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def to_ISO8601(dt: datetime) -> str:
"""Convert datetime object to ISO 8601 standard UTC string"""
return dt.strftime("%Y-%m-%dT%H:%M:%SZ") | bigcode/self-oss-instruct-sc2-concepts |
def cmd_subject_hash(cert):
"""Returns hash of certificate subject.
"""
return cert.get_subject().hash() | bigcode/self-oss-instruct-sc2-concepts |
def findResource(resource, request):
"""Traverse resource tree to find who will handle the request."""
while request.postpath and not resource.isLeaf:
#print 'findResource:', resource, request.postpath
pathElement = request.postpath.pop(0)
request.prepath.append(pathElement)
next... | bigcode/self-oss-instruct-sc2-concepts |
def neq(a, b):
"""Checks if antecedent ⇎ consequent (a ⇎ b). `📘`_
- a: antecedent
- b: consequent
Example:
>>> neq(True, False) == True
>>> neq(False, True) == True
>>> neq(True, True) == False
>>> neq(False, False) == False
.. _📘:
https://github.com/python3f/extra-boolean/wiki/neq
... | bigcode/self-oss-instruct-sc2-concepts |
def sort_annotations_by_offset(annotations):
"""
This function expects as input a list of dictionaries with this structure:
{'ann_id': u'T34',
'continuation': False,
'entity_type': u'Registry',
'positions': [{'end': 2465, 'start': 2448}],
'surface': u'reg 38 Padavinus,'},
And sorts... | bigcode/self-oss-instruct-sc2-concepts |
from operator import add
def do_query(issues, config_file=None, logger=None, context=None):
"""
Iterate through issues and count total number of issues
and total number of words.
Returns result of form:
{
"num_issues": num_issues,
"num_words": num_words
}
:pa... | bigcode/self-oss-instruct-sc2-concepts |
import time
def wait_for( func, max_seconds=10, pause=1 ):
""" def wait_for
Wait for up to max_seconds for func to return True
If func returns True within time alloted, return True
Otherwise, return False
func must return a boolean value (others might work, but behavior is undefine... | bigcode/self-oss-instruct-sc2-concepts |
def tcp_opts_tuple_list_to_dict(opts_list: list) -> dict:
"""Convert tuple of TCP options to a dictionary
:param opts_list: list of TCP options tuple
:return: diction of TCP options
"""
opts = {}
if None in opts_list:
opts_list.remove(None)
for opt, value in opts_list:
# here... | bigcode/self-oss-instruct-sc2-concepts |
import copy
def dict_np_to_dict_list(input_dict):
"""
Convert a dict of numpy array to a dict of list
"""
input_dict = copy.copy(input_dict)
if type(input_dict) is dict:
for name in list(input_dict.keys()):
input_dict.update({name: input_dict[name].tolist()})
return inp... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def dict_value_from_path(src_dict: dict, path: List[str], case_sensitive: bool = False):
"""
returns the value of dict field specified via "path" in form of a list of keys. By default the keys are matching
case insensitive way.
Example:
src_dict = {"level1:{"level2":{"lev... | bigcode/self-oss-instruct-sc2-concepts |
from math import floor
def calcL1Ainterval(rate):
"""
Returns the L1Ainterval in BX associated with a given rate in Hz
"""
return floor((1.0 / rate) * (1e9 / 25)) | bigcode/self-oss-instruct-sc2-concepts |
def expectation_description(expect = None, expect_failure = None):
"""Turn expectation of result or error into a string."""
if expect_failure:
return "failure " + str(expect_failure)
else:
return "result " + repr(expect) | bigcode/self-oss-instruct-sc2-concepts |
def get_simulation_priority_value(simulation_result, data_item, target_priority):
"""
Collect a priority metric from the simulation.
:param simulation_result: Metrics on simulation
:param data_item: Metric name
:param target_priority: Priority
:return: List of values from simulation.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def get_keytable_path(opendkim_conf):
"""Returns the path to the KeyTable file from the OpenDKIM config.
"""
param = 'KeyTable'
with open(opendkim_conf, 'r') as f:
for line in f:
if line.startswith(param):
return line.replace(param, '').strip()
msg = "Could not ... | bigcode/self-oss-instruct-sc2-concepts |
import pytz
def get_time_zone(time_zone_str):
"""Get time zone from string. Return None if unable to determine."""
try:
return pytz.timezone(time_zone_str)
except pytz.exceptions.UnknownTimeZoneError:
return None | bigcode/self-oss-instruct-sc2-concepts |
def number_format(number):
"""Formats numbers with thousands separators"""
return u'{:,}'.format(number) | bigcode/self-oss-instruct-sc2-concepts |
def files_exist(files):
"""Check whether all file names in a list are accessible for reading.
"""
for f in files:
with open(f, "r") as fi:
pass
return True | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def get_sha1_file( filename ):
"""
This module generates sha1sum for the given file
Args:
filename (str): Full path to the file
Returns:
sha1sum hash of the file
"""
hash_size = 256
sha1 = hashlib.sha1()
with open( filename, 'rb' ) as f:
while Tru... | bigcode/self-oss-instruct-sc2-concepts |
def check_keys(in_dict):
"""Checks which keys are present within the input dictionary
This function looks within the input dictionary and checks
which keys are contained within it. Then, with these
keys, it generates a list containing these keys and
returns this list as output.
Parameters
... | bigcode/self-oss-instruct-sc2-concepts |
def kmph_to_mps(kmph):
"""
Transform a value from kilometers-per-hour to meters-per-second
"""
return kmph * 0.277778 | bigcode/self-oss-instruct-sc2-concepts |
import json
def reconciliation_period_reformat(lst):
"""
Reformat reconciliation period into From [dd/mm/yyyy] to [dd/mm/yyyy] format
"""
try:
lst = json.loads(lst)
except:
lst = []
period = ""
for f_date, t_date in lst:
period += "From " + f_date + " to " + t_d... | bigcode/self-oss-instruct-sc2-concepts |
def is_ratelimit(tweet):
"""
Returns True if the "tweet" is a rate-limit response.
If False, then it should be an actual tweet.
Works with raw tweet (as str) or de-JSONified tweet (as dict).
"""
if isinstance(tweet, dict):
# The tweet is a Python dictionary
if 'limit' in tweet... | bigcode/self-oss-instruct-sc2-concepts |
def sumsq(values):
"""
Calculates the sum of squares of a list of values.
"""
return sum(map(lambda x: x ** 2, values)) | bigcode/self-oss-instruct-sc2-concepts |
def orbreap(orb):
"""Get the next packet from an orb"""
return orb.reap() | bigcode/self-oss-instruct-sc2-concepts |
def _sort_key(item):
"""
Robust sort key that sorts items with invalid keys last.
This is used to make sorting behave the same across Python 2 and 3.
"""
key = item[0]
return not isinstance(key, int), key | bigcode/self-oss-instruct-sc2-concepts |
def prepare_kwargs(raw, string_parameter='name'):
"""
Utility method to convert raw string/diction input into a dictionary to pass
into a function. Always returns a dictionary.
Args:
raw: string or dictionary, string is assumed to be the name of the activation
activation functi... | bigcode/self-oss-instruct-sc2-concepts |
import ipaddress
def wrap_ipv6(ip_address):
"""Wrap the address in square brackets if it's an IPv6 address."""
if ipaddress.ip_address(ip_address).version == 6:
return '[{}]'.format(ip_address)
return ip_address | bigcode/self-oss-instruct-sc2-concepts |
def iterate_pagerank(corpus, damping_factor):
"""
Return PageRank values for each page by iteratively updating
PageRank values until convergence.
Return a dictionary where keys are page names, and values are
their estimated PageRank value (a value between 0 and 1). All
PageRank values should su... | bigcode/self-oss-instruct-sc2-concepts |
def isolate_rightmost_0_bit(n: int) -> int:
"""
Isolate the rightmost 0-bit.
>>> bin(isolate_rightmost_0_bit(0b10000111))
'0b1000'
"""
return ~n & (n + 1) | bigcode/self-oss-instruct-sc2-concepts |
def is_palindrome(num: int) -> bool:
"""Checks if a number is a palindrome."""
return str(num) == str(num)[::-1] | bigcode/self-oss-instruct-sc2-concepts |
import re
def wiki_escape(s):
"""Detect WikiSyntax (i.e. InterCaps, a.k.a. CamelCase) and escape it."""
ret = []
for word in s.split():
if re.match(r"[A-Z]+[a-z]+[A-Z]", word):
word = "!%s" % word
ret.append(word)
return " ".join(ret) | bigcode/self-oss-instruct-sc2-concepts |
def init_method_normalizer(name: str):
"""Normalizes the name of an initialization method."""
return name.lower().replace('_', '').replace('nodeembeddinginitializer', '') | bigcode/self-oss-instruct-sc2-concepts |
import random
def mutate_value(value):
"""Randomly doubles or halves a value -- applied at "value" level"""
if random.random() < 0.5:
return value * 2
return value / 2 | bigcode/self-oss-instruct-sc2-concepts |
def check_syllable(char):
"""Check whether given character is valid Hangul syllable."""
return 0xAC00 <= ord(char) <= 0xD7A3 | bigcode/self-oss-instruct-sc2-concepts |
import re
def clean_html(raw_html):
"""Remove HTML tags from a text"""
clean_regex = re.compile('<.*?>')
clean_text = re.sub(clean_regex, '', raw_html)
return clean_text
#def process_column(column_name, dataframe, process):
"""Define a method to apply the same process to every row in a
... | bigcode/self-oss-instruct-sc2-concepts |
def _get_last_nonempty_line(loglines, start_line):
"""Check loglines starting at index start_line and return the number of the last line that is not empty"""
last_line = len(loglines) - 1
for i in range(start_line, len(loglines)):
if len(loglines[i].strip()) == 0:
last_line = i - 1
... | bigcode/self-oss-instruct-sc2-concepts |
def reverse(s):
"""
Return reverse of 's'.
"""
r = "".join(reversed(s))
return r | bigcode/self-oss-instruct-sc2-concepts |
def format_range(low, high, width):
"""Format a range from low to high inclusively, with a certain width."""
if low == high:
return "%0*d" % (width, low)
else:
return "%0*d-%0*d" % (width, low, width, high) | bigcode/self-oss-instruct-sc2-concepts |
def file_len(fname):
""" Get length of file """
return sum(1 for line in open(fname)) | bigcode/self-oss-instruct-sc2-concepts |
import math
def estimate_risk(entry_price: float, stop_price: float) -> float:
"""
estimates the risk per share
:param entry_price: float
:param stop_price: float
:return: float
"""
if math.isnan(entry_price) or math.isnan(stop_price):
raise TypeError()
return abs(entry_price... | bigcode/self-oss-instruct-sc2-concepts |
import struct
def get_terminated_strings(num, data):
"""Parse space- or *- separated strings of variable length
Parameters
----------
num : int
Number of substrings to be parsed
data : str
4C binary data file
Returns
-------
str
Truncated 4C binary file
li... | bigcode/self-oss-instruct-sc2-concepts |
def font_bold(mystring):
"""
Formats the string as bold, to be used in printouts.
"""
font_bold = "\033[1m"
font_reset = "\033[0;0m"
return font_bold + mystring + font_reset | 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.