seed
stringlengths
1
14k
source
stringclasses
2 values
def _get_num_reads(ngs_alignment): """ Returns the number of reads in the template of an NCBI/NGS alignment Args: ngs_alignment (ngs.Alignment): aligned read Returns: int: the number of reads in the template """ if ngs_alignment.hasMate(): return(2) else: retur...
bigcode/self-oss-instruct-sc2-concepts
def group(container, multiple=True): """ Splits a container into a list of lists of equal, adjacent elements. >>> from sympy.utilities.iterables import group >>> group([1, 1, 1, 2, 2, 3]) [[1, 1, 1], [2, 2], [3]] >>> group([1, 1, 1, 2, 2, 3], multiple=False) [(1, 3), (2, 2), (3, 1)] ...
bigcode/self-oss-instruct-sc2-concepts
def Count(Spaces): """ returns tuples *(space, count)* where *count* states how often *space* occurs in *Spaces*. """ dummy = [tuple(sorted(x.items())) for x in Spaces] unique = set(dummy) result = [] for x in unique: result.append((dict(x), dummy.count(x))) return resu...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def rgba_to_html_string(rgba: Tuple[int, int, int, float]) -> str: """Create an HTML code from an RGBA tuple Parameters ---------- rgba : Tuple[int, int, int, float] | Tuple[int, int, int] RGB values and an optional alpha value between 0 and 1. Returns ------...
bigcode/self-oss-instruct-sc2-concepts
def augment_data(train_ds, data_augmentation): """ :param train_ds: raw train_ds :param data_augmentation: data augmentation sequence :return: an augmented training set """ print("Augmenting the train_ds") augmented_train_ds = train_ds.map(lambda x, y: (data_augmentation(x), y)) # augmen...
bigcode/self-oss-instruct-sc2-concepts
import aiohttp async def get_tg_dm_player_json(): """ Helper function for pulling the top 10,000 AoE2 players' info. """ async with aiohttp.ClientSession() as session2: async with session2.get("https://aoe2.net/api/leaderboard?game=aoe2de&leaderboard_id=1&start=1&count=10000") as r: ...
bigcode/self-oss-instruct-sc2-concepts
def copy_of(board): """ Returns a copy of a board """ copy = [] for row_num in range(10): row = [] for col_num in range(10): row.append(board[row_num][col_num]) copy.append(row) return copy
bigcode/self-oss-instruct-sc2-concepts
def average_bmi(df): """ Returns average BMI, rounded to to d.p. """ return round(df.bmi.mean(), 2)
bigcode/self-oss-instruct-sc2-concepts
def get_mesh_cell_array(mesh, array_name): """Retrieve a cell array from the mesh.""" cell_data = mesh.GetCellData() return cell_data.GetArray(array_name)
bigcode/self-oss-instruct-sc2-concepts
import json def get_config_from_json(json_file): """ Get the config from a json file :param json_file: :return: config(dictionary) """ # parse the configurations from the config json file provided with open(json_file, 'r') as config_file: config_dict = json.load(config_file) return config_dict
bigcode/self-oss-instruct-sc2-concepts
def count_orphan_resource_providers(db): """Count all orphan resource providers in the nova_api database.""" sql = '''\ SELECT COUNT(*) FROM nova_api.resource_providers rp JOIN nova.compute_nodes cn ON cn.hypervisor_hostname = rp.name WHERE cn.deleted = 0 AND rp.uuid != cn.uuid ...
bigcode/self-oss-instruct-sc2-concepts
def _date_to_string(d): """Make string of date in Nexus format Args: d (datetime): Date object Returns: String with date """ id = d.day im = d.month iy = d.year if im < 10: st = '0' + str(im) else: st = str(im) st = st + r'/' if id < 10: ...
bigcode/self-oss-instruct-sc2-concepts
def _quoted(arg): """Check if arguments to framework functions are wrapped in quotes. Args: arg (str): The target argument Returns: bool: True if `arg` is quoted """ return arg.startswith("\"") and arg.endswith("\"")
bigcode/self-oss-instruct-sc2-concepts
def cnmr_match_tag(text): """Detect Carbon NMR data from splitted spectral sample text param text:splitted spectral sample text return:string related to Carbon NMR data """ cnmr_data = [] for data_block in text: cnmr_patterns = ["13C NMR", "13C{1H}"] for pattern in cnmr_patterns:...
bigcode/self-oss-instruct-sc2-concepts
def _bool(raw_bool): """ Parse WPS boolean string.""" return raw_bool == "true"
bigcode/self-oss-instruct-sc2-concepts
import re def search_last_letter(input_string): """ Returns the last letter in a string :param input_string: str, string to search for a letter :return: str, last letter in the string """ match = re.findall('[_a-zA-Z]+', input_string) if match: return match[-1][-1]
bigcode/self-oss-instruct-sc2-concepts
def img2rgb(img): """ Convert the image into rgb mode for displaying :param img: input img :return: output img """ img_rgb = (img / 255)[:, :, [2, 1, 0]] return img_rgb
bigcode/self-oss-instruct-sc2-concepts
def get_bbox_from_shapely(shapely_object): """ Accepts shapely box/poly object and returns its bounding box in coco and voc formats """ minx, miny, maxx, maxy = shapely_object.bounds width = maxx - minx height = maxy - miny coco_bbox = [minx, miny, width, height] coco_bbox = [round(point...
bigcode/self-oss-instruct-sc2-concepts
def pb_config(pb2): """Returns an instance of config of *_pb2 package""" return pb2.PrefixConfig()
bigcode/self-oss-instruct-sc2-concepts
def _remove_proper_feature(human_readable: str) -> str: """Removes proper feature from human-readable analysis.""" human_readable = human_readable.replace("+[Proper=False]", "") human_readable = human_readable.replace("+[Proper=True]", "") return human_readable
bigcode/self-oss-instruct-sc2-concepts
def get_data(string: str) -> list[list[int]]: """Take char string of numbers and convert to integer list of lists.""" new_list = list(string.split("\n")) final_list = [] for i in new_list: lst = list(i.split(" ")) ints = [] for j in lst: ints.append(int(j)) fi...
bigcode/self-oss-instruct-sc2-concepts
def flatten_lists(list_of_lists): """ This function flattens a list of lists into a single list. Args: list_of_lists (list): the list to flatten Returns: list: the flattened list """ return [item for sublist in list_of_lists for item in sublist]
bigcode/self-oss-instruct-sc2-concepts
def cable_type(request): """Dualtor cable type.""" return request.param
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Tuple from pathlib import Path def parse_benchfile(f) -> List[Tuple[Path, Path]]: """Parse the given file into benchmark cases. On each line in the file, there should be a path to a map, a colon and a space-separated list of scenarios which should be benchma...
bigcode/self-oss-instruct-sc2-concepts
def is_in_list(list_one, list_two): """Check if any element of list_one is in list_two.""" for element in list_one: if element in list_two: return True return False
bigcode/self-oss-instruct-sc2-concepts
def SortClassAdsByElement(classads, element_name): """ Sort the classads (or any dictionary really) by an attribute @param classads: list of classad objects @param element_name: string of element name """ sorted_ads = sorted(classads, key=lambda ad: int(ad[element_name])) return sorted_...
bigcode/self-oss-instruct-sc2-concepts
def get_process_command(cmd_args): """Get command-line text for task process.""" # Join arguments into command string, escaping any with spaces. cmd = '' for arg_index, arg in enumerate(cmd_args): if arg_index > 0: cmd += ' ' if ' ' in arg: cmd += '"' + arg + '"' else: cmd += arg ...
bigcode/self-oss-instruct-sc2-concepts
def correct_german_spellings(spelling): """Correcting the exceptions in German spellings. Aeseses -> Aseses Eeseses -> Eseses Heseses -> Beses Aeses -> Ases Eeses -> Eses Heses -> Bes Hes -> B Aes -> As Ees -> Es ---------- H♭♭♭ -> B𝄫 H𝄫 -> B♭ H♭ -> B """ ...
bigcode/self-oss-instruct-sc2-concepts
def lambda_handler(event, context): """Lambda function to generate the Map input state for LQP Run Base Parameters ---------- event: dict, required Input event to the Lambda function context: object, required Lambda Context runtime methods and attributes Returns ------ ...
bigcode/self-oss-instruct-sc2-concepts
def text_block(text, margin=0): """ Pad block of text with whitespace to form a regular block, optionally adding a margin. """ # add vertical margin vertical_margin = margin // 2 text = "{}{}{}".format( "\n" * vertical_margin, text, "\n" * vertical_margin ) ...
bigcode/self-oss-instruct-sc2-concepts
import shlex def convert_arg_line_to_args(arg_line): """argparse helper for splitting input from config Allows comment lines in configfiles and allows both argument and value on the same line """ return shlex.split(arg_line, comments=True)
bigcode/self-oss-instruct-sc2-concepts
import torch def load_ckpt(modules_optims, ckpt_file, load_to_cpu=True, verbose=True): """ load state_dict of module & optimizer from file Args: modules_optims: A two-element list which contains module and optimizer ckpt_file: the check point file load_to_cpu: Boolean, whether to t...
bigcode/self-oss-instruct-sc2-concepts
def slice_detections(all_ground_truth_bboxes, slice_mode): """ Find indices of detections of interest and modify the ground truth detections based on slice mode. Params: all_ground_truth_boxes (List of xml.etree.ElementTree.Element): List of all ground truth bounding boxe...
bigcode/self-oss-instruct-sc2-concepts
def get_attr_value(attrs, key): """Read attr value from terncy attributes.""" for att in attrs: if "attr" in att and att["attr"] == key: return att["value"] return None
bigcode/self-oss-instruct-sc2-concepts
def ec2_entities(job_name): """ Returns the name of basic ec2_entities. * Keypair name * Security group for slaves * Security group for master @param job_name: User given name of the Job. @type job_name: string """ keypair_name = "multistack-" + job_name sec_slave = "multistack...
bigcode/self-oss-instruct-sc2-concepts
def contar_caracteres_repetidos(cadena: str) -> int: """ Caracteres Repetidos Parámetros: cadena (str): La cadena que se debe revisar. Retorno: int: La cantidad de caracteres diferentes que aparecen repetidos en la cadena. """ caracteres_cadena = {} diferentes_repetidos = 0 for c...
bigcode/self-oss-instruct-sc2-concepts
import math def resize_bytes(input_bytes: bytes, length: int): """Takes in a byte string and an integer. Outputs the byte string repeated till it is of length integer""" multiplier = math.ceil(length / len(input_bytes)) raw_output = input_bytes * multiplier return raw_output[:length]
bigcode/self-oss-instruct-sc2-concepts
def lmap(v, x, y) -> float: """Linear map of value v with range x to desired range y.""" return y[0] + (v - x[0]) * (y[1] - y[0]) / (x[1] - x[0])
bigcode/self-oss-instruct-sc2-concepts
def get_folder_id(path, c): """Query the folder id of the directory.""" sql = ''' SELECT folder_id FROM folders WHERE path = ? ''' c.execute(sql, (path, )) return c.fetchone()[0]
bigcode/self-oss-instruct-sc2-concepts
def node_restore_all(self, flag=0) : """ Restores a all device from the configuration in ISY args : flag 0 or 1 Flag : 0 = All shall be restored from the configuration files in ISY 1 = Does not regenerate groups/scenes - good for testing ...
bigcode/self-oss-instruct-sc2-concepts
import torch def FloattoRGB(images): """Converts a 0-1 float image with an alpha channel into RGB""" if len(images.size()) < 4: images = torch.unsqueeze(images, 0) return torch.clip(images[:,:3,:,:] * images[:,3,:,:] * 255 + (1-images[:,3,:,:])*255, 0, 255).type(torch.uint8)
bigcode/self-oss-instruct-sc2-concepts
def _uuencode_int6(n): """uuencode a 6-bit element into a char""" if n == 0: return '`' else: return chr(0x20 + n)
bigcode/self-oss-instruct-sc2-concepts
import six def _MergeDicts(a, b): """Shallow merge two dicts. If both dicts have values for a same key and both are lists, it concats them. Args: a: a dict object. This will be updated with merged items. b: a dict object. Returns: a merged dict object. """ for key, value in six.iteritems(b)...
bigcode/self-oss-instruct-sc2-concepts
def _time_hms(datetime_obj): """ Return datetime_obj formatted as mm/dd HH:MM:SS. """ return '{time:%m/%d %H:%M:%S}'.format(time=datetime_obj)
bigcode/self-oss-instruct-sc2-concepts
def _get_set_name(test_data): """Get the set_name from test_data Return the value of 'set_name' key if present in the data If set_name it is not present in data, return the value of the first key. If there's no data, leave set_name as '' """ set_name = '' if 'set_name' in test_data: ...
bigcode/self-oss-instruct-sc2-concepts
def _phi(speciation_initiation_rate, speciation_completion_rate, incipient_species_extinction_rate): """ Returns value of $\varphi$, as given in eq. 6 in Etienne et al. (2014). Parameters ---------- speciation_initiation_rate : float The birth rate, b (the incipient speci...
bigcode/self-oss-instruct-sc2-concepts
def create_cmd(parts): """Join together a command line represented as list""" sane_parts = [] for part in parts: if not isinstance(part, str): # note: python subprocess module raises a TypeError instead # of converting everything to string part = str(part) ...
bigcode/self-oss-instruct-sc2-concepts
def trim_pv(pv): """ Strip anything after +git from the PV """ return "".join(pv.partition("+git")[:2])
bigcode/self-oss-instruct-sc2-concepts
def APs2mAP(aps): """ Take a mean of APs over all classes to compute mAP """ num_classes = 0. sum_ap = 0. for _, v in aps.items(): sum_ap += v num_classes += 1 if num_classes == 0: return 0 return sum_ap/num_classes
bigcode/self-oss-instruct-sc2-concepts
def bounding_box(points): """ The function calculates bounding_box from the coordinates. XY - Min , XY - Max :param points: coordinates list :return: List of bounding box. """ x_coordinates, y_coordinates = zip(*points) return [(min(x_coordinates), min(y_coordinates)), (max(x_coordinates), m...
bigcode/self-oss-instruct-sc2-concepts
def image_data_to_dict(image_data): """ Converts a desktop notification image data array into a dict. """ result = {} result['width'] = image_data[0] result['height'] = image_data[1] result['rowstride'] = image_data[2] result['has_alpha'] = image_data[3] result['bits_per_sample'] = image_data[4] result['chan...
bigcode/self-oss-instruct-sc2-concepts
import re import pathlib def get_library_folders(steam_path, library_index_path): """ Reads the library index file `libraryfolders.vdf` to get a list of all Steam library locations on your system. Because of the lazy way in which the RegEx is written, it only supports up to 100 Steam librarie...
bigcode/self-oss-instruct-sc2-concepts
def filter_str(check_str): """ 过滤无用字符 :param str check_str:待过滤的字符串 :return str temp:过滤后的字符串 """ temp = '' for i in check_str: if i != '\n' and i != '\x00': temp = temp + i return temp
bigcode/self-oss-instruct-sc2-concepts
import torch def cosine_cont(repr_context, relevancy, norm=False): """ cosine siminlarity betwen context and relevancy Args: repr_context - [batch_size, other_len, context_lstm_dim] relevancy - [batch_size, this_len, other_len] Return: size - [batch_size, this_len, context_lstm...
bigcode/self-oss-instruct-sc2-concepts
import requests def obtener_pais(codigo: str) -> str: """Obtiene el nombre del país a partir del código. :param codigo: Código del país. :codigo type: str :return: Nombre del país. :rtype: str """ url = f"https://restcountries.com/v3/alpha/{codigo}" response = requests.get(url) ...
bigcode/self-oss-instruct-sc2-concepts
def merge_proteins(proteins): """ Merge all isozymes that catalyze a given reaction. Automatically removes all isozymes with missing score. Args: proteins (pandas.Series): list of proteins Returns: str: boolean rule """ proteins = set(proteins.dropna()) if not proteins: ...
bigcode/self-oss-instruct-sc2-concepts
def extract_stats_from_uartlog(uartlogpath): """ read a uartlog and get sim perf results """ elapsed_time = -1 sim_speed = -1 cycles = -1 with open(uartlogpath, 'r') as f: readlines = f.readlines() for line in readlines: if "time elapsed:" in line and "simulation speed" in line: ...
bigcode/self-oss-instruct-sc2-concepts
def c(x, y): """Returns 1 if x < y and -1 if x > y.""" return (y - x) // abs(y - x)
bigcode/self-oss-instruct-sc2-concepts
def partition_node(node): """Split a host:port string into (host, int(port)) pair.""" host = node port = 27017 idx = node.rfind(':') if idx != -1: host, port = node[:idx], int(node[idx + 1:]) if host.startswith('['): host = host[1:-1] return host, port
bigcode/self-oss-instruct-sc2-concepts
def indented(contentstring, indent=-1): """ Return indented content. indent >= 0 prefixes content with newline + 2 * indent spaces. indent < 0 returns content unchanged Docstrings: >>> indented("foo bar", -1) 'foo bar' >>> indented("foo bar", 0) '\\nfoo bar' >>> indented("foo ...
bigcode/self-oss-instruct-sc2-concepts
def count_lines(filename): """ Count the number of lines in filename. :param str filename: Path to the filename. :return: The number of lines in the file. :rtype: int """ lines = 0 buf_size = 1024 * 1024 with open(filename, 'rb') as fd: read_f = fd.read # loop optimization...
bigcode/self-oss-instruct-sc2-concepts
def bpm_from_beatspace(btsp): """ Convert a beatspace to a BPM Provided as convenience; the operation is the same as bpm_to_beatspace. :param btsp: beatspace to convert :return: beatspace converted to BPM """ return 60000.0 / btsp
bigcode/self-oss-instruct-sc2-concepts
def is_list(a): """Check if argument is a list""" return isinstance(a, list)
bigcode/self-oss-instruct-sc2-concepts
def conflict_annotation(expt, loc): """ Returns conflict rate of an experiment as a string percentage. Only does this if the experiment is EPaxos, as MPaxos has no conflict rate. """ if expt.is_epaxos(): conflict_rate = '{}%'.format(round(expt.conflict_rate(loc)*100, 1)) return confl...
bigcode/self-oss-instruct-sc2-concepts
def unpack3(var, struct_var, buff): """ Create an unpack call on the ``struct.Struct`` object with the name ``struct_var``. :param var: variable the stores the result of unpack call, ``str`` :param str struct_var: name of the struct variable used to unpack ``buff`` :param buff: buffer that the ...
bigcode/self-oss-instruct-sc2-concepts
import torch def mulaw_encode(x, quantization_channels, scale_to_int=True): """Adapted from torchaudio https://pytorch.org/audio/functional.html mu_law_encoding Args: x (Tensor): Input tensor, float-valued waveforms in (-1, 1) quantization_channels (int): Number of channels scale_to_i...
bigcode/self-oss-instruct-sc2-concepts
import torch def bbox_intersection(bboxes1, bboxes2, aligned=False): """ Compute the intersections among bounding boxes. Args: bboxes1 (:obj:`nn.Tensor[N, 4]`): Bounding boxes to be computed. They are expected to be in ``(x1, y1, x2, y2)`` format. bboxes2 (:obj:`nn.Tensor[M, 4...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def _get_file_contents(file_path: Path) -> str: """ Helper function to get README contents """ with open(file_path, encoding="utf-8") as file: return file.read()
bigcode/self-oss-instruct-sc2-concepts
def _format_name(m_name: str, sep: str = '_') -> str: """Formats name for url Parameters ---------- m_name : str Name of movie sep : str Word seperator to use '-' or '_' typically Returns ------- str movie name formatted for url insertion """ # enfo...
bigcode/self-oss-instruct-sc2-concepts
def get_tricks_taken(active_players): """Determines how many tricks currently have been taken""" tricks_taken = 0 for player in active_players: tricks_taken += player.curr_round_tricks return tricks_taken
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def get_qname(uri: Optional[str], name: str) -> str: """ Returns an expanded QName from URI and local part. If any argument has boolean value `False` or if the name is already an expanded QName, returns the *name* argument. :param uri: namespace URI :param name: local ...
bigcode/self-oss-instruct-sc2-concepts
def arrange_array_size(batch_size: int, array_size: tuple): """ Decide array size given batch size and array size [batch_size, height, width, channel]. :param batch_size: batch size :param array_size: array (img) size :return: final array size """ output = list(array_size) output.insert(...
bigcode/self-oss-instruct-sc2-concepts
def bam_is_processed_by_program(alignments, program='bamtagmultiome'): """Check if bam file has been processed by the supplied program This function checks if there is an entry available in the 'PG' block in header of the bam file where PN matches the program supplied. Args: alignments(pysam.A...
bigcode/self-oss-instruct-sc2-concepts
def convert_define_to_arg(input_define): """ Convert from a #define to a command line arg. Parameters ---------- input_define : str String in the format of "#define variable value". Returns ------- output_str : str String in the format of "-Dvariable=value". """ ...
bigcode/self-oss-instruct-sc2-concepts
def get_subclasses(*args): """Gets the subclasses of the parameters. Parameters ---------- *args : :class:`type` The types to get the subclasses of. Returns ------- :class:`set` The subclasses of ``*args``. """ ret = set() for arg in args: tmp = set(ar...
bigcode/self-oss-instruct-sc2-concepts
def field_to_ysv_column(field: Field) -> list: # type: ignore """Convert a Field instance to ysv column definition.""" return [ {'input': field.field} ]
bigcode/self-oss-instruct-sc2-concepts
def grab_cite_data(template, supported_templates): """Check for supported templates and extract citation data""" template_name = str(template.name).lower().strip().capitalize() if template_name in supported_templates: data = { str(para.name).lower().strip(): str(para.value) ...
bigcode/self-oss-instruct-sc2-concepts
def with_self(method, network, args, kwargs): """Wraps a method with ``with network:``. This makes it easy to add methods to a network that create new Nengo objects. Instead of writing ``with self`` at the top of the method and indenting everything over, you can instead use this decorator. Example...
bigcode/self-oss-instruct-sc2-concepts
def select_bucket_region( custom_bucket, hook_region, cfngin_bucket_region, provider_region ): """Return the appropriate region to use when uploading functions. Select the appropriate region for the bucket where lambdas are uploaded in. Args: custom_bucket (Optional[str]): The custom bucket na...
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import List def basic_complete(text: str, line: str, begidx: int, endidx: int, match_against: Iterable) -> List[str]: """ Basic tab completion function that matches against a list of strings without considering line contents or cursor position. The args required by ...
bigcode/self-oss-instruct-sc2-concepts
def get_subject_name_from_csv(full_subject_name): """This function gets subject name from csv Args: full_subject_name (str): Full subject name with format XXX_YYY_ZZZ Return: subject_name (str): Subject name """ full_subject_name_list = full_subject_name.split("_", 3) subject_n...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def hash_string(string, salt=None): """Get MD5 hash from a string. Parameters ---------- string : str Some string. salt : str, False or None Optional salt added to the string for additional obfuscation. """ if salt is not None: string += salt ret...
bigcode/self-oss-instruct-sc2-concepts
def generate_connection_string(account_name: str, account_key: str, protocol: str = 'https') -> str: """Generates the connection string for Microsoft Azure.""" connection_string = (f'DefaultEndpointsProtocol={protocol};' f'AccountN...
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def parse_metadata(text): """parse yaml metadata on raster layers Parameters ---------- text: str text in yaml format Returns ------- OrderedDict: layer name: raster attribute number """ text = text.rstrip() metadata ...
bigcode/self-oss-instruct-sc2-concepts
import io import zipfile def zip_dict(data, **kwargs): """ Zips a dictionary ``{ str: bytes }``. @param data dictionary @param kwargs see :epkg:`*py:zipfile:ZipFile` @return bytes """ if not isinstance(data, dict): raise TypeError("data must b...
bigcode/self-oss-instruct-sc2-concepts
def invalid_br_vsby(v): """Checks if visibility is inconsistent with BR""" return not 0.6 < v < 6.1
bigcode/self-oss-instruct-sc2-concepts
def _read_code(message): """ Read the verification code from given email message Inputs :param message: <str> verification message sent Outputs :returns: <str> verification code that was sent """ # print("Message Recieved: '%s'" % message) code = message.content.split("...
bigcode/self-oss-instruct-sc2-concepts
def system_address(accounts): """Address pretending to be the system address.""" return accounts[0]
bigcode/self-oss-instruct-sc2-concepts
def add_dummy_multiver(post, pkg_dir, config): """Add a dummy multiver=False value.""" return {'multiver': False}
bigcode/self-oss-instruct-sc2-concepts
def ParsingAddress(raw_location_list): """ A supporting function that parses the raw location info from Yelp Fusion API to make it more readable. Parameters ---------- raw_location_list : pandas.core.series.Series Required. A pd.Series of dictionaries containing address information in the JSO...
bigcode/self-oss-instruct-sc2-concepts
def get_port_numbers(ports): """ Get all port number from response and make comma-separated string :param ports: Port portion from response. :return: Comma-separated port numbers. """ return ', '.join([str(port['number']) for port in ports])
bigcode/self-oss-instruct-sc2-concepts
def square2(value): """ Return the square of a value""" new_value = value ** 2 return new_value
bigcode/self-oss-instruct-sc2-concepts
import pickle def restore_model(path_to_ckpt): """ Loads model from a ckpt file. """ with open(path_to_ckpt, 'rb') as fp: data = pickle.load(fp) return data['model']
bigcode/self-oss-instruct-sc2-concepts
def cast_element_ids_to_s(hash_element_ids, elements): """ Cast a hash of element ids to a string of element ids. :param hash_element_ids: node/relation/way ids :type hash_element_ids: hash :param elements: OSM element to search :type elements: array :returns: a string of node/relation/wa...
bigcode/self-oss-instruct-sc2-concepts
def remove_colons(hexstr): """Removes colons from a string""" return ''.join(hexstr.split(':'))
bigcode/self-oss-instruct-sc2-concepts
import copy def deep_merge_dict(dict_x, dict_y, path=None, local_overwrite=True, merge_only_exist=False, raise_exception=True): """ Recursively merges dict_y into dict_x. Args: dict_x: A dict. dict_y: A dict. path: local_overwrite: Whether to overwrite the ...
bigcode/self-oss-instruct-sc2-concepts
def datahash(*arrays): """Hash the data buffers of some arrays.""" hashstr = '' for arr in arrays: w = arr.flags.writeable arr.flags.writeable = False hashstr += '[{}{}]'.format(hash(bytes(arr)), arr.shape) arr.flags.writeable = w return hash(hashstr)
bigcode/self-oss-instruct-sc2-concepts
def constraint1(x): """ Some constraint to ensure that the probabilities sum to one. """ return x[1:].sum() - 1
bigcode/self-oss-instruct-sc2-concepts
def merge_sorted_lists(list_left, list_right): """ Merge two sorted lists This is a linear operation O(len(list_right) + len(list_right)) :param left_list: list :param right_list: list :return merged list """ # Special case: one or both of lists are empty if len(list_left) == 0: ...
bigcode/self-oss-instruct-sc2-concepts
import re def bcl_scrub_name(name): """Modifies a sample name to be BCL2fastq compatible Parameters ---------- name : str the sample name Returns ------- str the sample name, formatted for bcl2fastq """ return(re.sub('[^0-9a-zA-Z\-\_]+', '_', name))
bigcode/self-oss-instruct-sc2-concepts