seed
stringlengths
1
14k
source
stringclasses
2 values
def _WX(s, wx): """Returns TRUE if s contains string wx""" if wx == '': return False # special case for blowing/drifting snow ix = s.find(wx) if wx == 'SN' and ix > 1: if s[ix-2:ix] in ('BL', 'DR'): return False return ix >= 0
bigcode/self-oss-instruct-sc2-concepts
def ndbpprint(model, level=1): """ Pretty prints an `ndb.Model`. """ body = ['<', type(model).__name__, ':'] values = model.to_dict() for key, field in model._properties.iteritems(): value = values.get(key) if value is not None: body.append('\n%s%s: %s' % ( ' '.join([' ' for idx in range...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any from typing import List def wrap(item: Any) -> List[Any]: """Ensures that the input is either a list, or wrapped in a list. Returns [] for None. """ if item is None: return [] if isinstance(item, list): return item return [item]
bigcode/self-oss-instruct-sc2-concepts
def series_sum(n): """Sum of first nth term in series and return float value.""" total_series = 0.00 for x in range(n): total_series += float(1) / (1 + (x * 3)) total_series_decimal = ('{0:.2f}'.format(total_series)) return total_series_decimal
bigcode/self-oss-instruct-sc2-concepts
def test_well_plot(well): """ Tests mpl image of well. """ plot = well.plot(tracks=['MD', 'GR', 'DT'], extents='curves') return plot.get_figure()
bigcode/self-oss-instruct-sc2-concepts
import socket import binascii def fmt_ipv6_addr(v): """Given a 128-bit integer representing an ipv6 address, return a string for that ipv6 address.""" return socket.inet_ntop(socket.AF_INET6, binascii.unhexlify("%032x"%v))
bigcode/self-oss-instruct-sc2-concepts
def args_to_cmds(args): """Convert args dictionary to command line arguments. For example: >>> args_to_cmds({ 'foo': 'bar', 'qux': 'baz' }) '--foo=bar --qux=baz' """ result = '' for key, val in args.items(): result += '--%s=%s ' % (key, val) return result
bigcode/self-oss-instruct-sc2-concepts
def verbatim(f): """Read a line of text from file 'f'.""" line = f.readline() return line
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def test2solution(filename: str, source_path: str) -> Path: """ Build a solution filename from a corresponding test filename. """ tokens = filename.split("/") collection = tokens[-3] dataset = tokens[-2] filename = tokens[-1].replace("test-", "solutions-") # ...
bigcode/self-oss-instruct-sc2-concepts
def resolve_status(code): """ Get a label and status for the status code :param code: The status to resolve :return: A tuple containing the label and new status """ # Default label status_label = 'info' if code == 'success': status_nice = 'Build Succeeded' status_label ...
bigcode/self-oss-instruct-sc2-concepts
import csv def get_desikan(filepath): """Parse the desikan atlas ordering for the 68 cortical regions from the csv file, or indeed any other csv dictionary. Args: filepath (type): full file path. Returns: regions: list of region names in order of the desikan atlas. coords: th...
bigcode/self-oss-instruct-sc2-concepts
def get_dataset(dashboard): """Retrieves the dataset Parameters: ----------- dashboard : plsexplain.dashboard.Dashboard Returns ------- Callable The API handler for the dataset """ def get_dataset_internal(skip, take): skip = int(skip) take = int(take) ...
bigcode/self-oss-instruct-sc2-concepts
import re def is_tag(token): """Determine if a token is a tag of the format like [i-10] or [o-7]""" is_tag_re = re.compile('\[[io]-\d+\]', re.IGNORECASE) return is_tag_re.match(token)
bigcode/self-oss-instruct-sc2-concepts
def SHPowerL(c, l): """ Calculate the power for degree l. c is the CILM array. RETURNS: scalar value for the power """ return (c[:,l,:]**2).sum()
bigcode/self-oss-instruct-sc2-concepts
def strip_numbers(text: str): """Strip numbers from a piece of text""" text = text.replace("0", "").replace("1", "").replace("2", "").replace("3", "").replace("4", "").replace("5", "") text = text.replace("6", "").replace("7", "").replace("8", "").replace("9", "") return text
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 numb...
bigcode/self-oss-instruct-sc2-concepts
import random import time def call_with_retries(function, max_retries=10, exception_types=(Exception), _args=(), _kwargs={}): """ Call `function` with up to `max_retries` retries. A retry is only performed if the exception thrown is in `exception_types`. :p...
bigcode/self-oss-instruct-sc2-concepts
def yper(p): """Calculates the y position for a given amount of peroxide.""" return 100 + (p - 12) * -10
bigcode/self-oss-instruct-sc2-concepts
def in_by_id(element, collection): """Check if element is in collection, by comparing identity rather than equality.""" return any(element is item for item in collection)
bigcode/self-oss-instruct-sc2-concepts
def getRemoteParams(dbElem): """Get parameters to supply to ktremotemgr to connect to the right DB.""" host = dbElem.getDbHost() or 'localhost' return ['-port', str(dbElem.getDbPort()), '-host', host]
bigcode/self-oss-instruct-sc2-concepts
import torch import math def get_rotation_matrix(heading): """Get the rotation matrix for the given heading. Arguments: heading (float): Rotation in radians. Returns: torch.tensor: 2x2 rotation matrix """ return torch.tensor([[math.cos(heading), -math.sin(heading)], ...
bigcode/self-oss-instruct-sc2-concepts
def repr_calling(args, kwargs): """ Reconstruct function calling code. """ li = [] li.extend(repr(a) for a in args) li.extend('%s=%r' % (k, v) for k, v in kwargs.items()) return ', '.join(li)
bigcode/self-oss-instruct-sc2-concepts
def calc_neighbour_positions(_cell_coord: tuple) -> list: """ Calculate neighbouring cell coordinates in all directions (cardinal + diagonal). Returns list of tuples. """ """Creates and returns coordinates of all cells around the current cell""" neighbour: list = [ (_cell_coord[0] - 1, _cell_co...
bigcode/self-oss-instruct-sc2-concepts
def tmpdir_repoparent(tmpdir_factory, scope='function'): """Return temporary directory for repository checkout guaranteed unique.""" fn = tmpdir_factory.mktemp("repo") return fn
bigcode/self-oss-instruct-sc2-concepts
def format_includes(includes: list) -> str: """Format includes into the argument expected by GCC""" return " ".join([f"-I{path}" for path in includes])
bigcode/self-oss-instruct-sc2-concepts
def _get_keystores_object_type(output_type): """ Map config type to custom resource cert type """ return { 'p12': 'pkcs12', 'jks': 'jks', }[output_type]
bigcode/self-oss-instruct-sc2-concepts
def frame_msg(msg: str) -> str: """Frame a message with hashes so that it covers five lines.""" return f"\n###\n#\n# {msg}\n#\n###"
bigcode/self-oss-instruct-sc2-concepts
import webbrowser import asyncio async def get_oauth_verifier(oauth_token): """ Open authorize page in a browser, print the url if it didn't work Arguments --------- oauth_token : str The oauth token received in :func:`get_oauth_token` Returns ------- str The PIN ...
bigcode/self-oss-instruct-sc2-concepts
def get_timestamp(imu_dict): """The timestamp of a message does not necessarily equal the timestamp in the message's header. The header timestamp is more accurate and the timestamp of the message just corresponds to whenever the bag received the message and saved it. Args: imu_dict (dict): ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import Dict def get_calibrated_plot_fonts(fig_size: Tuple[int, int]) -> Dict[str, float]: """ Takes in figure-size (tuple), and returns dictionary containing fontsizes for all other aspects of the plot (calculated and set appropriately, based on the figure-size). T...
bigcode/self-oss-instruct-sc2-concepts
import logging def get_ctx_options(conf): """Gets the appropriate context options for storing test information. These context options are passed as keyword arguments to methods including ndb.Key.get(), ndb.Key.put(), ndb.get_multi(), and ndb.put_multi() to control how various storage methods are used. Arg...
bigcode/self-oss-instruct-sc2-concepts
def is_a_equal_to_b(num1, num2): """Predicate function evaluating whether num1 is equal to num2.""" return num1 == num2
bigcode/self-oss-instruct-sc2-concepts
def stripMetadataFlags(metadataChunk): """Strip binary flags from the start of the metadata chunk. Arguments: metadataChunk {bytes} -- This refers only to the first metadata chunk. If there are additional ones they won't have any flags. Returns: bytes -- Number of metadata chunks, uint8. bytes -- Rest of t...
bigcode/self-oss-instruct-sc2-concepts
import socket def is_port_available(port: int, host="0.0.0.0"): """ Check if a port is available """ assert isinstance(port, int) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = True try: sock.bind((host, port)) except: result = False sock.close()...
bigcode/self-oss-instruct-sc2-concepts
def shift_point_by_markersize(axes, x, y, markersize): """ Shift overlapping points alonmg x axis by half of the markersize. This allows to show better plots with errorbars. """ inv = axes.transData.inverted() points = [(i,j) for i,j in zip(x,y)] pixels = axes.transData.transform(points) ...
bigcode/self-oss-instruct-sc2-concepts
def find_dupes(facts): """Find hosts with duplicate SSH host keys from PuppetDB output""" hosts_by_key = {} for fact in facts: hosts_by_key.setdefault( fact['value'], set(), ).add(fact['certname']) return { k: v for k, v in hosts_by_key.items() ...
bigcode/self-oss-instruct-sc2-concepts
def encode_data(data, tokenizer, punctuation_enc): """ Converts words to (BERT) tokens and puntuation to given encoding. Note that words can be composed of multiple tokens. """ X = [] Y = [] for line in data: word, punc = line.split('\t') punc = punc.strip() tokens = ...
bigcode/self-oss-instruct-sc2-concepts
def num_strings(data: bytes) -> int: """ return the number of strings in the strings file Args: data: strings data from "Strings.txt" file Returns: Number of lines in strings output """ return data.count(b'\n')
bigcode/self-oss-instruct-sc2-concepts
import random def choose_duration(simple=False): """Returns a random duration in durk units Args: simple (bool, optional): Defaults at False. If True, only considers notes of duration 8 or 16 durks. Otherwise, considers durations in list: [1, 2, 3, 4, 6, 8, 12, 16] Returns: int...
bigcode/self-oss-instruct-sc2-concepts
import torch def onehot_coding(target, device, output_dim): """Convert the class labels into one-hot encoded vectors.""" target_onehot = torch.FloatTensor(target.size()[0], output_dim).to(device) target_onehot.data.zero_() target_onehot.scatter_(1, target.view(-1, 1), 1.0) return target_onehot
bigcode/self-oss-instruct-sc2-concepts
import logging def init_basic_root_logger(level=logging.INFO): """ Initialize the root logger with basic configuration. """ logging.basicConfig() logger = logging.getLogger() # get root logger as default logger.setLevel(level) return logger
bigcode/self-oss-instruct-sc2-concepts
def _get_fontsize(size_name): """Return a fontsize based on matplotlib labels.""" font_sizes = { "xx-small": 5.79, "x-small": 6.94, "small": 8.33, "medium": 10.0, "large": 12.0, "x-large": 14.4, "xx-large": 17.28, "larger": 12.0, "smaller":...
bigcode/self-oss-instruct-sc2-concepts
def get_digits(number): """Get digits in number from left to right.""" digits = [] while number > 0: digits.append(number % 10) number = number // 10 return digits[::-1]
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path from typing import Optional from typing import List def ignore_file(path: Path, patterns: Optional[List[str]]) -> bool: """Check if path matches ignore patterns. :param path: path to compar with ignore pattern :param patterns: list of glob patterns specifying which paths to ignor...
bigcode/self-oss-instruct-sc2-concepts
import requests from bs4 import BeautifulSoup def umc_web_scraper(map_id): """Get static copy of HTML from given url and returns it as HTML soup.""" url = f"http://unfortunate-maps.jukejuice.com/show/{map_id}" page = requests.get(url) soup = BeautifulSoup(page.content, "html.parser") return soup
bigcode/self-oss-instruct-sc2-concepts
def blend(alpha, base=(255, 255, 255), color=(0, 0, 0)): """ :param color should be a 3-element iterable, elements in [0,255] :param alpha should be a float in [0,1] :param base should be a 3-element iterable, elements in [0,255] (defaults to white) :return: rgb, example: (255, 255, 255) """ return tuple(int(...
bigcode/self-oss-instruct-sc2-concepts
import time def time_function(f, *args): """ Call a function f with args and return the time (in seconds) that it took to execute. """ tic = time.time() f(*args) toc = time.time() return toc - tic
bigcode/self-oss-instruct-sc2-concepts
def parse_rank_specification(s): """ Parses info about rank specification, used to filter games by player's ranks. Returns None (all ranks allowed), or a set of possible values (None as a possible value in the set means that we should include games without rank info) # returns None, all ranks ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence from pathlib import Path def real_words() -> Sequence[str]: """Loads a list of real words to search.""" with (Path(__file__).parent / 'words.txt').open() as path: return tuple(map(str.strip, path.readlines()))[:5]
bigcode/self-oss-instruct-sc2-concepts
def list_(client, file_=None, name=None, value=None, get_expanded=None, select=False): """Get a list of notes from one or more models. Values will automatically be returned Base64-encoded if they are strings which contain Creo Symbols or other non-ASCII data. Args: client (obj): cr...
bigcode/self-oss-instruct-sc2-concepts
def ordinary_annuity(p: float, i: float, n: float) -> float: """ Calculates the annuity payment given loan principal, interest rate and number of payments :param p: loan principal value :param i: monthly nominal interest rate :param n: number of payments :return: annuity payment """ nume...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _join(iterable: List, and_or: str) -> str: """Join iterables grammatically.""" return ', '.join(iterable[:-2] + [f' {and_or} '.join(iterable[-2:])])
bigcode/self-oss-instruct-sc2-concepts
def downToLocal(poetryList, path): """下载诗词保存到本地txt Args: poetryList (List): 诗词列表 path (String): 保存路径 Returns: None """ for content in poetryList: with open(f'{path}' f'{content[0]}.txt', 'w', encoding='utf-8') as file: file.writelines('\n'.join(content))...
bigcode/self-oss-instruct-sc2-concepts
def Julian_centuries_since_2000(jd): """ Julian centuries from Jan 1, 2000. @param jd : Julian date @type jd : float @return: float """ t = (jd-2451545.)/36525. return t
bigcode/self-oss-instruct-sc2-concepts
def services_type(loader): """ Returns a function which validates that services string contains only a combination of blob, queue, table, and file. Their shorthand representations are b, q, t, and f. """ def impl(string): t_services = loader.get_models('common.models#Services') if set(strin...
bigcode/self-oss-instruct-sc2-concepts
def dump_queue(queue): """ Empties all pending items in a queue and returns them in a list. """ result = [] queue.put("STOP") for i in iter(queue.get, 'STOP'): result.append(i) return result
bigcode/self-oss-instruct-sc2-concepts
def iterable(arg): """ Simple list typecast """ if not isinstance(arg, (list, tuple)): return [arg] else: return arg
bigcode/self-oss-instruct-sc2-concepts
def complement(predicate): """Generates a complementary predicate function for the given predicate function. :param predicate: Predicate function. :returns: Complementary predicate function. """ def _negate(*args, **kwargs): """Negation.""" return not predicate(*args, **kwargs) retu...
bigcode/self-oss-instruct-sc2-concepts
def mytask(data, *args, **kwargs): """Simple task which returns reverse string """ return data[0][::-1]
bigcode/self-oss-instruct-sc2-concepts
def unpack_point_msg(msg, stamped=False): """ Get coordinates from a Point(Stamped) message. """ if stamped: p = msg.point else: p = msg return p.x, p.y, p.z
bigcode/self-oss-instruct-sc2-concepts
import uuid def uuid_from_string(idstr): """Convert an uuid into an array of integers""" if not idstr: return None hexstr = uuid.UUID(idstr).hex return [int(hexstr[i:i+2], 16) for i in range(32) if i % 2 == 0]
bigcode/self-oss-instruct-sc2-concepts
import string import random def random_string_generator(size=6, chars=string.ascii_uppercase + string.digits): """ Generate random string Args: size: length of the string chars: sequence of chars to use Returns: random string of length "size" """ return ''.join(random.choice(c...
bigcode/self-oss-instruct-sc2-concepts
import math def compute_colors(n, cols): """Interpolate a list of colors cols to a list of n colors.""" m = len(cols) lst = [] for i in range(n): j = math.floor (i * (m - 1.0) / (n - 1.0)) k = math.ceil (i * (m - 1.0) / (n - 1.0)) t = (i * (m - 1.0) / (n - 1.0)) - j (r0...
bigcode/self-oss-instruct-sc2-concepts
def issubstring(s1, s2, *args, **kwargs): """Is s1 a substring of s2""" return s2.count(s1) > 0
bigcode/self-oss-instruct-sc2-concepts
def common_characters(w1, w2): """ Parameters: ---------- w1: str w2: str Returns: -------- int: Number of characters common between two strings """ ws1 = set(w1) ws2 = set(w2) return len(ws1.intersection(ws2))
bigcode/self-oss-instruct-sc2-concepts
def topic_filename(topic: str) -> str: """ Returns the filename that should be used for the topic (without extension). """ # Remove commas and replace spaces with '-'. return topic.replace(",", "").replace(" ", "-")
bigcode/self-oss-instruct-sc2-concepts
def get_published_file_entity_type(tk): """ Return the entity type that this toolkit uses for its Publishes. .. note:: This is for backwards compatibility situations only. Code targeting new installations can assume that the published file type in Shotgun is always ``PublishedFi...
bigcode/self-oss-instruct-sc2-concepts
def tokenize(chars): """ Convert a string of characters into a list of tokens. """ return chars.replace('(', ' ( ').replace(')', ' ) ').split()
bigcode/self-oss-instruct-sc2-concepts
import json def set_config(config_name): """ Config parse :param config_name: config file name :type config_name: str :return: parsed config :rtype: dict """ try: return json.load(open(config_name, 'r')) except FileNotFoundError: print('%s %s' % (config_name, 'no...
bigcode/self-oss-instruct-sc2-concepts
def hsv_to_rgb(h, s, v): """Convert HSV values RGB. See https://stackoverflow.com/a/26856771. :param h: Hue component of the color to convert. :param s: Saturation component of the color to convert. :param v: Value component of the color to convert. :rtype: tuple ""...
bigcode/self-oss-instruct-sc2-concepts
def next_byte(server_socket): """ This method reads in one byte. :param server_socket: the socket to read one byte from :return: a byte object of the single byte read in """ return server_socket.recv(1)
bigcode/self-oss-instruct-sc2-concepts
def cleanupQuotes(text): """ Removes quotes if text starts and ends with them Args: text (str): Text to cleanup Returns: Text with quotes removed from start and end (if they existed) or original string (if not) """ if text.startswith('"') and text.endswith('"'): return text[1:-1] else: return text
bigcode/self-oss-instruct-sc2-concepts
def max3(a,b,c): """a,b,c의 최댓값을 구하여 반환""" #아마 함수를 입력할때 추가로 설명같은 란이 들어가는것 같다. maximum=a if b>maximum: maximum=b if c>maximum: maximum=c return maximum
bigcode/self-oss-instruct-sc2-concepts
def truncate_to_fit(text, len): """ Truncate text to specified length. """ return text[:len]
bigcode/self-oss-instruct-sc2-concepts
def add_headers(response): """ This function adds headers to outbound requests to increase the security posture in the browser """ response.headers["Cache-Control"] = "public, max-age=31536000" response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains" response.hea...
bigcode/self-oss-instruct-sc2-concepts
def _abberation_correction(R): """Calculate the abberation correction (delta_tau, in degrees) given the Earth Heliocentric Radius (in AU)""" return -20.4898/(3600*R)
bigcode/self-oss-instruct-sc2-concepts
def get_photo_rel_url(album_name, filename): """ Gets path of source photo relative to photos basedir :param album_name: :param filename: :return: """ return "%s/%s" % (album_name, filename)
bigcode/self-oss-instruct-sc2-concepts
def iconset_from_class(value): """ extracts the iconset from a class definition "fa-flask" -> "fa" :param value: :return: """ if '-' in value: return value.split('-')[0] return ''
bigcode/self-oss-instruct-sc2-concepts
def make_vertical_bar(percentage, width=1): """ Draws a vertical bar made of unicode characters. :param value: A value between 0 and 100 :param width: How many characters wide the bar should be. :returns: Bar as a String """ bar = ' _▁▂▃▄▅▆▇█' percentage //= 10 if percentage < 0: ...
bigcode/self-oss-instruct-sc2-concepts
import torch def images_to_levels(target, num_level_grids): """Convert targets by image to targets by feature level. [target_img0, target_img1] -> [target_level0, target_level1, ...] """ target = torch.stack(target, 0) level_targets = [] start = 0 for n in num_level_grids: end = s...
bigcode/self-oss-instruct-sc2-concepts
def is_shared_library(f): """Check if the given File is a shared library. Args: f: The File to check. Returns: Bool: True if the given file `f` is a shared library, False otherwise. """ return f.extension in ["so", "dylib"] or f.basename.find(".so.") != -1
bigcode/self-oss-instruct-sc2-concepts
def generate_trail(wire_directions): """Given a list of wire directions, generate a set of coordinate pairs for the wire's path""" trail = set() current_location = (0, 0) for direction in wire_directions: heading = direction[0] distance = int(direction[1:]) while distance > 0: ...
bigcode/self-oss-instruct-sc2-concepts
def song_decoder(song): """ Removes 'WUB' from a string to find the true message of the song. :param song: The input consists of a single non-empty string, consisting only of uppercase English letters, the string's length doesn't exceed 200 characters :return: the words of the initial song that Polycarp...
bigcode/self-oss-instruct-sc2-concepts
def str_starts_with_any_in_list(string_a, string_list): """ Check if string_a starts with any string the provided list of strings """ for string_b in string_list: if string_a.startswith(string_b): return True return False
bigcode/self-oss-instruct-sc2-concepts
def check_monotonic(a): """ Parameters ---------- a input array Returns -1 -- for monotonic, non-increasing 0 -- for non-monotonic 1 -- for monotonic, non-decreasing ------- >>> check_monotonic([1,2,3]) 1 >>> check_monotonic([3,2,1]) -1 >>...
bigcode/self-oss-instruct-sc2-concepts
def format_report(count, new_inst, del_inst, svc_info): """ Given a service's new, deleted inst, return a string representation for email """ needed = False body = '' if new_inst is not None and len(new_inst) > 0: needed = True body += '\n\n New Instances: ' for inst in ...
bigcode/self-oss-instruct-sc2-concepts
import math def p_to_q(p): """ Turn error probability into Phred-scaled integer """ return int(round(-10.0 * math.log10(p)))
bigcode/self-oss-instruct-sc2-concepts
def _make_credentials_property(name): """Helper method which generates properties. Used to access and set values on credentials property as if they were native attributes on the current object. Args: name: A string corresponding to the attribute being accessed on the credentials attrib...
bigcode/self-oss-instruct-sc2-concepts
import pytz def to_utc(dt): """This converts a naive datetime object that represents UTC into an aware datetime object. :type dt: datetime.datetime :return: datetime object, or None if `dt` was None. """ if dt is None: return None if dt.tzinfo is None: return dt.replace(tz...
bigcode/self-oss-instruct-sc2-concepts
import torch def qlog_t(q): """ Applies the log map to a quaternion :param q: N x 4 :return: N x 3 """ n = torch.norm(q[:, 1:], p=2, dim=1, keepdim=True) n = torch.clamp(n, min=1e-8) q = q[:, 1:] * torch.acos(torch.clamp(q[:, :1], min=-1.0, max=1.0)) q = q / n return q
bigcode/self-oss-instruct-sc2-concepts
import pathlib def quandl_apikey_set(apikey, filename=None): """Store the Quandl Token in $HOME/.updoon_quandl Parameters: ----------- apikey : str The API Key from the Quandl Website. See https://www.quandl.com/account/api filename : str Absolute path to the text where t...
bigcode/self-oss-instruct-sc2-concepts
import torch def compute_argmax(ten): """Compute argmax for 2D grid for tensors of shape (batch_size, size_y, size_x) Args: ten (torch.[cuda].FloatTensor): (batch_size, size_y, size_x) Returns: indices (torch.[cuda].LongTensor): (batch_size, 2) index order: (y, x) """ batch_size ...
bigcode/self-oss-instruct-sc2-concepts
def get_cbmc_info(n_insert, n_dihed, cutoffs): """Get the CBMC_Info section of the input file Parameters ---------- n_insert : int number of insertion sites to attempt for CBMC n_dihed : int number of dihedral angles to attempt for CBMC cutoffs : list list containing CBM...
bigcode/self-oss-instruct-sc2-concepts
def has_active_balance_differential(spec, state): """ Ensure there is a difference between the total balance of all _active_ validators and _all_ validators. """ active_balance = spec.get_total_active_balance(state) total_balance = spec.get_total_balance(state, set(range(len(state.validators))))...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def to_boolean(envvar: Union[str, bool]) -> bool: """ Coerce the input to a boolean. >>> to_boolean("True") True >>> to_boolean("FALSE") False NOTE: An empty string is interpreted as False: >>> to_boolean("") False Booleans are returned as-is: ...
bigcode/self-oss-instruct-sc2-concepts
import zipfile def _ExtractZipEntries(path): """Returns a list of (path, CRC32) of all files within |path|.""" entries = [] with zipfile.ZipFile(path) as zip_file: for zip_info in zip_file.infolist(): # Skip directories and empty files. if zip_info.CRC: entries.append( (zip_i...
bigcode/self-oss-instruct-sc2-concepts
def get_icon(icon: str) -> str: """ Get icon unicode from dictionary. Parameters: icon (str): icon code from API response. Returns: (str): icon unicode. """ icons = {"01": ":sun:", "02": ":sun_behind_cloud:", "03": ":cloud:", "04": ":cloud:", "09": ":cloud_with_rain:", "10": ":sun_behind_r...
bigcode/self-oss-instruct-sc2-concepts
def get_start_timestamp_mapping(file_path): """Get mapping of video name id to star timestamp.""" mapping = {} with open(file_path) as f_in: for line in f_in.readlines(): if line.strip() == '': continue video_name, time_txt = line.strip().split(',') ...
bigcode/self-oss-instruct-sc2-concepts
import re def add_datepart(df, fieldname): """ Adds date related features to dataframe df inplace df: dataframe fieldname: name of the date field in df """ new_df = df.copy() field = df[fieldname] target_prefix = re.sub('[Dd]atetime$', '', fieldname) date_features = ( ...
bigcode/self-oss-instruct-sc2-concepts
def _apply_signed_threshold(value, min_thr=None, max_thr=None): """ Apply threshold on signed value. usage examples : >>> _apply_signed_threshold(0.678, min_thr=0.5) 0.5 >>> _apply_signed_threshold(-0.678, min_thr=0.5) -0.5 >>> _apply_signed_threshold(0.678, max_thr=2.0) 0.678 >>> _apply_signed_thres...
bigcode/self-oss-instruct-sc2-concepts