seed
stringlengths
1
14k
source
stringclasses
2 values
def _BinaryElementwiseShape(op): """Returns same shape as both inputs to op. Args: op: Input operation. Returns: Shape of both inputs to `op`. """ return [op.inputs[0].get_shape().merge_with(op.inputs[1].get_shape())]
bigcode/self-oss-instruct-sc2-concepts
def get_value(data, value): """Retrieve weather value.""" try: if value == "@mps": return round(float(data[value]) * 3.6, 1) return round(float(data[value]), 1) except (ValueError, IndexError, KeyError): return None
bigcode/self-oss-instruct-sc2-concepts
def _intersect(rect1, rect2): """ Return True if the two rectangles rect1 and rect2 intersect. """ x1, y1, w1, h1 = rect1 x2, y2, w2, h2 = rect2 return (x1 + w1 > x2 and x2 + w2 > x1) and (y1 + h1 > y2 and y2 + h2 > y1)
bigcode/self-oss-instruct-sc2-concepts
def load_fb15k_triples(path): """ Loads the raw data from file provided. Args: path: path to the file Returns: triples """ with open(path, 'r') as f: triples = [line.strip('\n').split('\t') for line in f.readlines()] return triples
bigcode/self-oss-instruct-sc2-concepts
def apply_update_rules(state, predecessor_node_lists, truth_tables): """ Update network state according to the update rule. :param state: current network state :param predecessor_node_lists: list of predecessor node lists :param truth_tables: list of dicts (key: tuple of predecessor node st...
bigcode/self-oss-instruct-sc2-concepts
def parse_contour_file(filename): """Parse the given contour filename :param filename: filepath to the contourfile to parse :return: list of tuples holding x, y coordinates of the contour """ coords_lst = [] with open(filename, 'r') as infile: for line in infile: coords = ...
bigcode/self-oss-instruct-sc2-concepts
def subset_by_iqr(df, column, iqr_mult=3): """Remove outliers from a dataframe by column, including optional whiskers, removing rows for which the column value are less than Q1-1.5IQR or greater than Q3+1.5IQR. Args: df (`:obj:pd.DataFrame`): A pandas dataframe to subset column (st...
bigcode/self-oss-instruct-sc2-concepts
import math def get_bounding_box(lat: float, lng: float, radius: float) -> str: """Get bounding box with length of radius * 2 and (lat, lng) as the centre""" offset = radius / 100.0 latMax = lat + offset latMin = lat - offset lngOffset = offset * math.cos(lat * math.pi / 180.0) lngMax = lng +...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def create_output_dir(dir_path: str) -> str: """Creates output directory if it doesn't exits Parameters ----------- dir_path: the output file directory Return ------- dir_path: the output file directory returned for later used """ if not Path(dir_path)...
bigcode/self-oss-instruct-sc2-concepts
def show_sticker_file_id(bot, update, session, chat, user): """Give the file id for a sticker.""" if update.message.reply_to_message is None: return "You need to reply to a sticker to use this command." message = update.message.reply_to_message if message.sticker is None: return "You ne...
bigcode/self-oss-instruct-sc2-concepts
def factorial(number: int) -> int: """ Calculate the factorial of specified number (n!). >>> import math >>> all(factorial(i) == math.factorial(i) for i in range(20)) True >>> factorial(0.1) Traceback (most recent call last): ... ValueError: factorial() only accepts integral val...
bigcode/self-oss-instruct-sc2-concepts
import csv def csv_to_list(csv_file): """ Function to read a csv file and convert the entries on each row to a list. """ csv_list = set() # Open CSV file for reading as provided to the function with open(csv_file, 'r', newline='') as input_file: input_reader = csv.reader(input_file) ...
bigcode/self-oss-instruct-sc2-concepts
def create_function_from_source(function_source, imports=None): """Return a function object from a function source Parameters ---------- function_source : unicode string unicode string defining a function imports : list of strings list of import statements in string form that allow ...
bigcode/self-oss-instruct-sc2-concepts
def simplify_http_accept_header(accept): """Parse an HTTP Accept header (RFC 2616) into a preferred value. The quality factors in the header determine the preference. Possible media-range parameters are allowed, but will be ignored. This function can also be used for the Accept-Charset, Accept-Enco...
bigcode/self-oss-instruct-sc2-concepts
def Int2Digits(i, base): """ The next function converts the number into a list of digits For example: if base=10, then Int2Digits(126, 10) = [1, 2, 6] if base=2, then Int2Digits(126, 2) = [1, 1, 1, 1, 1, 1, 0] (This function is called by the Number2String() function.) """ if (i < base...
bigcode/self-oss-instruct-sc2-concepts
import re def _is_auspex(path): """ Test if a given file path is an Auspex data file """ path = path.rstrip('/') filename = path.split('/')[-1] if re.findall(r".+.auspex", filename): return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def clean_unit_errors(merged_df): """ This function will look in a DataFrame for rows where the height_cat and weight_cat are set to "Unit-Error-High" or "Unit-Error-Low". It will then multiply / divide the height and weight values to convert them. It will also create two new columns: postprocess_heigh...
bigcode/self-oss-instruct-sc2-concepts
def instanceof(obj, classinfo): """Wrap isinstance to only return True/False""" try: return isinstance(obj, classinfo) except TypeError: # pragma: no cover # No coverage since we never call this without a class, # type, or tuple of classes, types, or such typles. return Fals...
bigcode/self-oss-instruct-sc2-concepts
def get_playseq(data, length): """return data read from file as a list of pattern numbers also return highest pattern number """ result = [] highpatt = 0 for bytechar in data[:length]: test = int(bytechar) result.append(test) if test > highpatt: highpatt = te...
bigcode/self-oss-instruct-sc2-concepts
import random def get_random_int(start=1, end=1000000): """Get an random integer between start and end inclusive.""" x = random.random() i = int(x*(end + 1 - start) + start) return i
bigcode/self-oss-instruct-sc2-concepts
import torch def _pad_norm(x, implicit=False): """Add a channel that ensures that prob sum to one if the input has an implicit background class. Else, ensures that prob sum to one.""" if implicit: x = torch.cat((1 - x.sum(dim=1, keepdim=True), x), dim=1) return x
bigcode/self-oss-instruct-sc2-concepts
import torch def all_edges(n): """Return a tensor of all (n choose 2) edges Constructs all possible edges among n items. For example, if ``n`` is 4, the return value will be equal to .. code:: python3 torch.Tensor([[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]) """ return torch.tr...
bigcode/self-oss-instruct-sc2-concepts
def externalarray(file_manager): """ An array of external array references. """ return file_manager.external_array_references
bigcode/self-oss-instruct-sc2-concepts
def matrix_add(list1, list2): """ Accepts two lists-of-lists of numbers and returns one list-of-lists with each of the corresponding numbers in the two given lists-of-lists added together. Example: >>> matrix1 = [[1, -2], [-3, 4]] >>> matrix2 = [[2, -1], [0, -1]] ...
bigcode/self-oss-instruct-sc2-concepts
def eratosthenes(n): """ this fxn is the Sieve of Eratosthenes. this algorithm generates a list of positive integers up to a given input n, then removes all multiples of 2, then 3,then 4, and so on until only the numbers that are divisible by 1 and itself are left in the list. and therefore the lis...
bigcode/self-oss-instruct-sc2-concepts
def _compare(local, remote): """Compare versions.""" if local == remote: return True else: return False
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def is_time_in_range(start: datetime, end: datetime, now: datetime): """Return true if now is in the range [start, end]""" if start <= end: return start <= now <= end return start <= now or now <= end
bigcode/self-oss-instruct-sc2-concepts
def get_interface_connected_adjacent_router_interfaces( device, link_name, num=1 ): """ Get list of connected interfaces from adjacents routers Args: device ('obj'): Device object link_name ('str'): Interface alias in topology num ('int'): Number of interfaces to ret...
bigcode/self-oss-instruct-sc2-concepts
def ainv(x): """Additive inverse""" return -x
bigcode/self-oss-instruct-sc2-concepts
def scale_pixels(X_np_a, max_pixel_intensity): """Scale pixel values to be in [0, 1] to help gradient-descent optimization. Args: X_np_a (:obj:`numpy.ndarray`): Matrix of pixel intensities max_pixel_intensity (int): normalization constant set by user Returns: matrix of scaled inten...
bigcode/self-oss-instruct-sc2-concepts
def get_num_classes(self): """ Retrieves the number of classes in dataset """ return len(self.id_to_class_info)
bigcode/self-oss-instruct-sc2-concepts
import random def getAction(action_list,action_values,minimax_val): """ Returns a random action of the actions with minmax_val """ req_actions = list() min_val_indexs = [i for i in range(len(action_values)) if action_values[i]==minimax_val] for i in range(len(min_val_indexs)): req_act...
bigcode/self-oss-instruct-sc2-concepts
def dump_dict(dump): """Returns dict of common profiles (radial quantities) """ return {'y': dump.y, 'tn': dump.tn, 'xkn': dump.xkn, 'abar': dump.abar, 'zbar': dump.zbar, }
bigcode/self-oss-instruct-sc2-concepts
import math def damping(temp, relhum, freq, pres=101325): """ Calculates the damping factor for sound in dB/m depending on temperature, humidity and sound frequency. Source: http://www.sengpielaudio.com/LuftdaempfungFormel.htm temp: Temperature in degrees celsius relhum: Relative humidity as ...
bigcode/self-oss-instruct-sc2-concepts
def _paths_to_tree(paths): """Build a tree from the given paths. The structure of the tree is described in the docstring for _prune_paths. """ tree = {} for path in paths: t = tree for c in path: if c not in t: t[c] = {} t = t[c] return t...
bigcode/self-oss-instruct-sc2-concepts
def is_main(args): """ returns True if process is being run on the main GPU """ return args.local_rank in [0, -1]
bigcode/self-oss-instruct-sc2-concepts
import re def isHexEncodedString(subject): """ Checks if the provided string is hex encoded >>> isHexEncodedString('DEADBEEF') True >>> isHexEncodedString('test') False """ return re.match(r"\A[0-9a-fA-Fx]+\Z", subject) is not None
bigcode/self-oss-instruct-sc2-concepts
def num_cat_feature_columns(df): """ Takes a pandas Dataframe (part of the black_friday_data_hack project) as input and separates numerical features from categorical features Arguments: data - DataFrame Returns: tuple of numerical features and categorical features ...
bigcode/self-oss-instruct-sc2-concepts
def trans_data_to_axis(ax): """Compute the transform from data to axis coordinate system in axis `ax`""" axis_to_data = ax.transAxes + ax.transData.inverted() data_to_axis = axis_to_data.inverted() return data_to_axis
bigcode/self-oss-instruct-sc2-concepts
def get_docs(d): """ Accepts a dictionary of the form {user: [cleaned word list]} and then returns the a list of lists, where each outer list is the word list for a particular user. This forms our document corpus on which we make LDA predictions. """ docs = [] for user in d: tex...
bigcode/self-oss-instruct-sc2-concepts
def get_Pin_ast(DLP, Pout): """ Calculate Pin_ast for given DLP (or DLP_ast) and Pout """ return DLP + Pout
bigcode/self-oss-instruct-sc2-concepts
def filter_sb_transposon(fusions): """Filters fusions with genes related to transposon sequences.""" mask = fusions['fusion_name'].str.contains('En2|Foxf2') return fusions.loc[~mask]
bigcode/self-oss-instruct-sc2-concepts
def _get_plural_forms(js_translations): """Extracts the parameters for what constitutes a plural. Args: js_translations: GNUTranslations object to be converted. Returns: A tuple of: A formula for what constitutes a plural How many plural forms there are """ ...
bigcode/self-oss-instruct-sc2-concepts
def isWeekend(dt): """Finds if a date lies on a weekend or not. Returns a boolean""" if 0 < dt.weekday() < 6: return False else: return True
bigcode/self-oss-instruct-sc2-concepts
def get_file_content(filename): """Returns the contents of the specified file. :param filename: The full path/name of the file :return: The contents of the file """ file_contents = '' with open(filename) as f: file_contents = f.read() return file_contents
bigcode/self-oss-instruct-sc2-concepts
def factorial(n): """ Return the factorial of a number n. """ f = 1.0 for i in range(0, n): f *= (n - i) return f
bigcode/self-oss-instruct-sc2-concepts
def _http_forbidden(start_response): """Responds with HTTP 403.""" start_response('403 Forbidden', [('Content-Length', '0')]) return []
bigcode/self-oss-instruct-sc2-concepts
def github_site_admin_action(rec): """ author: @mimeframe description: A Github site admin tool/action was used. Example: 'staff.fake_login' "A site admin signed into GitHub Enterprise as another user."" reference: https://help.github.com/enterprise/2.11/ad...
bigcode/self-oss-instruct-sc2-concepts
def de_vec(a, rows, cols): """Column-major de-vectorization. First dimension is batch dim. """ batch = a.size(0) # dim = math.floor(math.sqrt(a.size(1))) a_mat = a.reshape(batch, cols, rows).permute(0, 2, 1) return a_mat
bigcode/self-oss-instruct-sc2-concepts
import hashlib def get_file_md5(fpath, blocksize=2**20): """Get a file's MD5 checksum. Code from stackoverflow.com/a/1131255 Parameters ---------- fpath : string Path to file blocksize : int Read file in chunks of this many bytes Returns ------- md5sum : string ...
bigcode/self-oss-instruct-sc2-concepts
def xsd_datetime_str_from_dt(dt): """Format datetime to a xs:dateTime string. Args: dt : datetime - tz-aware: Used in the formatted string. - tz-naive: Assumed to be in UTC. Returns: str The returned format can be used as the date in xs:dateTime XML elements. It ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Mapping def parse_kv_list(params): """Create a dict from a "key=value" list. Parameters ---------- params : sequence of str or mapping For a sequence, each item should have the form "<key>=<value". If `params` is a mapping, it will be returned as is. Returns ...
bigcode/self-oss-instruct-sc2-concepts
def parse_argstring(magic_func, argstring): """ Parse the string of arguments for the given magic function. """ return magic_func.parser.parse_argstring(argstring)
bigcode/self-oss-instruct-sc2-concepts
def factorizeByBase(n, base, m = None): """ Find a factorization of n with factors from base, if one exists. If the modulus m is given, the base is allowed to contain -1. All other elements must be positive. """ assert n > 0 if m is not None and -1 in base: idx = base.index(-1) ...
bigcode/self-oss-instruct-sc2-concepts
def read_file(path): """Returns document read in by line""" with open(path, 'r') as f_in: # read in text file doc = f_in.readlines() return doc
bigcode/self-oss-instruct-sc2-concepts
import requests def post_as_json(url, payload): """post the payload as JSON data""" return requests.post(url, json=payload)
bigcode/self-oss-instruct-sc2-concepts
def get_other_causes(effect, cause, relations): """ For each effect-cause combination, return a list of the other prima facie causes. Parameters: effect: the variable representing the effect (key of the relations dict). cause: the cause to filter out. relations: the dict containing ...
bigcode/self-oss-instruct-sc2-concepts
import yaml def read_yaml(file_path: str) -> dict: """ Safely reads a yaml-file. Parameters ---------- file_path : str File path to YAML-file. Returns ------- dict Loaded YAML-file. """ with open(file_path, 'r') as stream: try: retu...
bigcode/self-oss-instruct-sc2-concepts
def get_column_names(connection_or_cursor, table): """Return list of column names from given database table.""" cur = connection_or_cursor.execute(f'PRAGMA table_info({table})') return [row[1] for row in cur.fetchall()]
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional import re def parse_timestamp(timestamp: str) -> Optional[int]: """Parse a playback timestamp into a number of seconds. Expects the timestamp to be in HH:MM:SS or MM:SS format. """ match = re.match( r"^(?:(?P<hours>\d+):)?(?P<minutes>\d+):(?P<seconds>\d+)$", timest...
bigcode/self-oss-instruct-sc2-concepts
import ast def get_bool_input(input_parameter): """Returns a boolean corresponding to a string "True/False" input Args: input_parameter (str): String input for a boolean Returns: bool: True/False input """ if input_parameter.lower().capitalize() in ["True","False"]: return ast.literal_eval(input_...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def xlnet_tokens_pre_processor(token_ids: List[int]) -> List[int]: """Add XLNET style special tokens. Args: token_ids: List of token ids without any special tokens. Returns: List of token ids augmented with special tokens. """ XLNET_CLS_ID = 3 XLNET_SE...
bigcode/self-oss-instruct-sc2-concepts
def rolling_variance(old,newValue): """Rolling variance computation according to Welford's algorithm. https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_Online_algorithm Parameters ---------- old : tuple containing the triplet count, mean, M2. Initialize with (0,0,...
bigcode/self-oss-instruct-sc2-concepts
def convert_labels(Lorig, params, toLasStandard=True): """ Convert the labels from the original CLS file to consecutive integer values starting at 0 :param Lorig: numpy array containing original labels :param params: input parameters from params.py :param toLasStandard: determines if labels are conv...
bigcode/self-oss-instruct-sc2-concepts
def max_len(seq_list): """Returns the maximum sequence length within the given list""" lmax=0 for seq in seq_list: lmax=max( lmax, len(seq) ) return lmax
bigcode/self-oss-instruct-sc2-concepts
def account_from_role_arn(role_arn): """ Returns the AWS account ID portion of the given IAM role ARN. """ parts = role_arn.split(':') if len(parts) == 6: return parts[4] return '-'
bigcode/self-oss-instruct-sc2-concepts
def has_issue(item): """Return True if the testcase has an issue.""" return bool(item.issue_id)
bigcode/self-oss-instruct-sc2-concepts
def _i2col(i): """Given an index, return the column string: 0 = 'A' 27 = 'AB' 758 = 'ACE' """ b = (i//26) - 1 if b>=0: return _i2col(b) + chr(65+(i%26)) return chr(65+(i%26))
bigcode/self-oss-instruct-sc2-concepts
import math def rotate_coordinate(x, y, cx, cy, theta): """Return a new point (x', y') as rotating an existing point (x, y) theta radians around the point (cx, cy). """ x_p = ((x - cx) * math.cos(theta) + (y - cy) * math.sin(theta)) + cx y_p = (-(x - cx) * math.sin(theta) + (y - cy) * math.cos(the...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _enumerate_cores(bounds: List[int], ring_bounds: List[int], ring_sizes: List[int], host_bounds: List[int], host_sizes: List[int]) -> List[List[int]]: """Enumerates cores within `bounds` from fatest to slowest varying axes. Args: bounds: Up...
bigcode/self-oss-instruct-sc2-concepts
def convert_to_factors(die): """Converts a sympy factor_list tuple to a list of the factors and returns the list""" sub_list = die[1] # Create a list from the tuple factor_list = [] for i in sub_list: # Iterate through the `sub_list` which contains all the factors for j in range(i[1]): # Nesting...
bigcode/self-oss-instruct-sc2-concepts
def clean_state(state): """ Upper cases the state and fixes a few weird issues. """ new_state = state.upper() if state else None # NF -> NL for Newfoundland and Labrador. if new_state == "NF": new_state = "NL" # PQ -> QC for Quebec. if new_state == "PQ": new_state = "QC" ...
bigcode/self-oss-instruct-sc2-concepts
def ensure_tz_UTC(df): """ Function to ensure that the tzinfo of a data frame is in UTC :param df: a pandas data frame with datetime_index :returns: the dataframe with df.index.tzinfo='UTC' """ # ensure tzinfo is in UTC if (str(df.index.tzinfo)=='None'): #print('The time...
bigcode/self-oss-instruct-sc2-concepts
def get_service_start_name(start): """ Translate a Windows service start number to a friendly service start name. """ return { 0: 'Boot', 1: 'System', 2: 'Automatic', 3: 'Manual', 4: 'Disabled' }.get(start, 'Unknown')
bigcode/self-oss-instruct-sc2-concepts
import re def fix_reserved_name(name): """Returns a tuple of (<name>, <replacement_name>) if name is a reserved word, otherwise returns (<name>, <name>). """ reserved_names = [ ('^key$', '_key_rr'), ('^interval$', '_interval_rr'), ('^load$', '_load_rr'), ('^primary$', '_pri...
bigcode/self-oss-instruct-sc2-concepts
def gray_code_sequence_string(bit_count: int) -> list: """ Will output the n-bit grey sequence as a string of bits >>> gray_code_sequence_string(2) ['00', '01', '11', '10'] >>> gray_code_sequence_string(1) ['0', '1'] """ # The approach is a recursive one # Base case achieved w...
bigcode/self-oss-instruct-sc2-concepts
def pool_url(aws_region, aws_user_pool): """ Create an Amazon cognito issuer URL from a region and pool id Args: aws_region (string): The region the pool was created in. aws_user_pool (string): The Amazon region ID. Returns: string: a URL """ return ( "https://cogni...
bigcode/self-oss-instruct-sc2-concepts
def timedelta_to_integral_seconds(delta): """ Convert a pd.Timedelta to a number of seconds as an int. """ return int(delta.total_seconds())
bigcode/self-oss-instruct-sc2-concepts
def file_number(number, string_length): """Generate number strings with leading zeros so that numerical and string order coincide""" number_to_string = str(number+1) length = len(number_to_string) final_name = '0'*(string_length-length) + number_to_string return final_name
bigcode/self-oss-instruct-sc2-concepts
def get_by_path(obj, path): """ Iteratively get on obj for each key in path. :param (list|dict) obj: The top-level object. :param (tuple[str]|tuple[int]) path: Keys to access parts of obj. :return: (*) Example: >>> figure = {'data': [{'x': [5]}]} >>> path = ('data', 0, 'x') ...
bigcode/self-oss-instruct-sc2-concepts
def find_multiples(integer, limit): """ Finds all integers multiples. :param integer: integer value. :param limit: integer value. :return: a list of its multiples up to another value, limit. """ return [x for x in range(1, limit + 1) if x % integer == 0]
bigcode/self-oss-instruct-sc2-concepts
import math def get_ticks(start, end, target_n_labels=10): """ Tries to put an appropriate number of ticks at nice round coordinates between the genomic positions `start` and `end`. Tries but doesn't guarantee to create `target_n_labels` number of ticks / labels. Returns: a list of tupl...
bigcode/self-oss-instruct-sc2-concepts
def ida_offset(string): """ Converts non-IDA conforming offset representation to a more IDAesk form. :param string: a non IDA conform string :return: IDA conform string """ segment, rest = string.split(':', 2) offset_start = rest.rfind('+') offset = rest[offset_start + 1:-1] operands...
bigcode/self-oss-instruct-sc2-concepts
def format_grid(grid): """ Formats each row to represent list value delimited by spaces :param list grid: input with nested lists to format """ formatted_grid = '' for row in grid: # list comprehension used to explicitly cast items to str # this allows for the grid param to cons...
bigcode/self-oss-instruct-sc2-concepts
import collections def invert_dict(d): """Invert a dictionary. Converts a dictionary (mapping strings to lists of strings) to a dictionary that maps into the other direction. Arguments: d: Dictionary to be inverted Returns: A dictionary n with the property that if "y in d[x]", then "x in n[y]". ...
bigcode/self-oss-instruct-sc2-concepts
def _is_technical(computation: str) -> bool: """ Check if a computation is a technical computation. Parameters ---------- computation: str a computation name. Returns ------- True if it is a technical computation, false otherwise. """ if computation.startswith('_'): ...
bigcode/self-oss-instruct-sc2-concepts
def getPlaylists(sp, username, offset=0): """ Retrieves all the playlists a user has :param sp: A spotipy.Spotify object to be used for the request. :param username: The username of the user who's playlists you want the retrieve. :param offset: Do not worry about this ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def color_mid(value: float) -> Optional[str]: """Determine color for efficiency value where "mid" values are the target. Args: value: percent (0-100) of value to color Returns: The color string for click or None if color should be unchanged """ if valu...
bigcode/self-oss-instruct-sc2-concepts
def _localize(dt, tzinfo): """ :return: A localized datetime :paramd dt: Naive datetime :param tzinfo: A pytz or python time zone object Attempts to localize the datetime using pytz if possible. Falls back to the builtin timezone handling otherwise. """ try: return tzinfo.locali...
bigcode/self-oss-instruct-sc2-concepts
import json def get_all_block_transactions(blocks_file_path): """ Return the number of transactions for blocks in the file in a dictionary """ transaction_counts = {} with open(blocks_file_path) as blocks_file: for line in blocks_file: block = json.loads(line) ...
bigcode/self-oss-instruct-sc2-concepts
def _is_file_valid(name): """Decide if a file is valid.""" return not name.startswith('.')
bigcode/self-oss-instruct-sc2-concepts
import itertools def getdates(yr1=2009, yr2=2016, month1=1, month2=12, day1=1, day2=31): """Returns a list of all possible dates as a set of tuples: E.G. date1 = (2009, 01, 01) or datex = (2011, 12, 06) The form is therefore a [(yyyy, mm, dd), ... (yyyy, mm, dd)] This function is set up to return all possible...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict def _add_annotation(objs: List[Dict], annotation_key: str) -> List[Dict]: """ Adds a boolean annotation (set to True) to a list of rich text objects (https://developers.notion.com/reference/rich-text) """ for obj in objs: if 'annotations' in ...
bigcode/self-oss-instruct-sc2-concepts
def read_and_pre_process_xml(file_name): """ Read XML file with the name specified in the argument and pre process the xml so that it can be parsed. Pre Processing removes line retune characters (i.e. "\n"). Arguments: file_name (str): Name of the XML file. Returns: (str): Pre Pr...
bigcode/self-oss-instruct-sc2-concepts
def _normalize_header_name(name: str) -> str: """ According to rfc https://www.ietf.org/rfc/rfc2616.txt header names are case insensitive, thus they can be normalized to ease usage of Headers class. :param name: :return: """ name = name.lower() if name.startswith("http_"): name =...
bigcode/self-oss-instruct-sc2-concepts
def center_text(text, page_width, char_width): """Helper function for calcuating the start x value for centered text.""" text_width = len(text) * char_width return (page_width - text_width) // 2
bigcode/self-oss-instruct-sc2-concepts
def _stripReverse(s): """Returns the string s, with reverse-video removed.""" return s.replace('\x16', '')
bigcode/self-oss-instruct-sc2-concepts
import logging def GetLogger(name: str) -> logging.Logger: """Return a logger. This is a wrapper around logging.getLogger that is intended to be used by the other modules so that they don't have to import the logging module + this module. Args: name (str); The name for the logger. Returns: logg...
bigcode/self-oss-instruct-sc2-concepts
def secondsToHms(seconds): """Convert seconds to hours, mins, secs seconds - seconds to be converted, >= 0 return hours, mins, secs """ assert seconds >= 0, 'seconds validation failed' hours = int(seconds / 3600) mins = int((seconds - hours * 3600) / 60) secs = seconds - hours * 3600 - mins * 60 return hour...
bigcode/self-oss-instruct-sc2-concepts
def palindromic(s: str) -> bool: """ Checks whether a string is a palindrome. """ size = len(s) for i in range(size // 2): if s[i] != s[size - 1 - i]: return False return True
bigcode/self-oss-instruct-sc2-concepts