seed
stringlengths
1
14k
source
stringclasses
2 values
def getCharacterFromGame(gtitle: str) -> str: """Return a query to get characters with lower Ryu Number to a game. The query will retrieve the name and Ryu Number of a character whose Ryu Number is exactly one less than the Ryu Number of the game whose title is passed. This is used primarily for path-finding towards Ryu. The resulting query takes the following form for game_character as C: `(C.name: str, C.ryu_number: int)` """ return (f"SELECT DISTINCT C.name, C.ryu_number " f"FROM appears_in " f"INNER JOIN game_character AS C ON cname=C.name " f"INNER JOIN game AS G ON gtitle=G.title " f"WHERE gtitle LIKE '{gtitle}' AND C.ryu_number=G.ryu_number-1;" )
bigcode/self-oss-instruct-sc2-concepts
def is_if(t): """Whether t is of the form if P then x else y.""" return t.is_comb("IF", 3)
bigcode/self-oss-instruct-sc2-concepts
def get_volume(module, system): """Return Volume or None""" try: try: volume = system.volumes.get(name=module.params['name']) except KeyError: volume = system.volumes.get(name=module.params['volume']) return volume except Exception: return None
bigcode/self-oss-instruct-sc2-concepts
def mean_of_columns(mat): """Returns 1-row matrix representing means of corresponding columns """ return mat.mean(axis=0)
bigcode/self-oss-instruct-sc2-concepts
import logging def collect_data(**kwargs): """ Ideally, a function that defines how data should be collected for training and prediction. In the real world, of course, there are often differences in data sources between training (data warehouse) and prediction (production application database, streaming system) scenarios. In such cases, one option would be to handle training/prediction scenarios as a positional, named, or keyword argument with control logic to determine how to collect the data from the relevant system. A second option would be to create and maintain to distinct functions. I generally prefer a single function with a keyword argument and control logic. Even if training and prediction data are originating from the same data source, you likely need control logic to handle filtering the data correctly in each of those scenarios (e.g., give me all the data for the last two years to train vs. just the data for the last hour to predict). """ ## Control logic assumes prediction is the default scenario if kwargs.get('scenario') == 'training': data = "Retrieve the training data from the historical data source with relevant filter" else: data = "Retrieve the prediction data from the real-time source with relevant filter" logging.info(f"Logging describing the data, such as its size in memory or number of records") return data
bigcode/self-oss-instruct-sc2-concepts
def normalize_response(response): """ Transform response so that 'off' == 'away' """ if response == 'away': return 'off' else: return response
bigcode/self-oss-instruct-sc2-concepts
def sec2ts(time_s): """ Convert time in seconds to timestamp """ return int(time_s * 1e9)
bigcode/self-oss-instruct-sc2-concepts
import re def find_cites(f): """Return keys to cited papers. """ with open(f) as fp: lst = re.findall(r"{{(.+?)}}", fp.read()) refs = [] for l in lst: if "site.data.refs" in l: refs.append(l.split(".")[3]) return sorted(set(refs))
bigcode/self-oss-instruct-sc2-concepts
def mag(*args): """ Magnitude of any number of axes """ n = len(args) return (sum([abs(arg)**2 for arg in args]))**(1/2)
bigcode/self-oss-instruct-sc2-concepts
def probe_id(subscription_id, resource_group_name, load_balancer_name, name): """Generate the id for a probe""" return '/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Network/loadBalancers/{}/probes/{}'.format( subscription_id, resource_group_name, load_balancer_name, name )
bigcode/self-oss-instruct-sc2-concepts
def search_by_sware_hware(nodes: list, option: int) -> dict: """ Search by software/hardware. Return all unique entries in ``nodes`` list at ``option`` index as keys and all hostnameswhich contains the entry in list as value. :param nodes: list of nodes. :param option: Index in the nodes list(check constants at the start of this file). :return: Return dictionary of unique entries as keys and all host names in list as value. """ filter_nodes = {} for item in nodes: if item[option] not in filter_nodes.keys(): filter_nodes[item[option]] = [item["dns"]] else: filter_nodes[item[option]].append(item["dns"]) return filter_nodes
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import List import string def quote_args(args: Iterable[str]) -> List[str]: """Quote the arguments which contain whitespaces""" r = [] for arg in args: if any(map(lambda c: c in string.whitespace, arg)): r.append(f'"{arg}"') else: r.append(arg) return r
bigcode/self-oss-instruct-sc2-concepts
import hashlib def get_file_md5(path): """ Retrieves the md5sum of a file's contents. Args: path: string path of the file to hash. Returns: string md5sum hash. """ hash_md5 = hashlib.md5() with open(path, 'rb') as in_file: hash_md5.update(in_file.read()) return hash_md5.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def finite_diff(expression, variable, increment=1): """ Takes as input a polynomial expression and the variable used to construct it and returns the difference between function's value when the input is incremented to 1 and the original function value. If you want an increment other than one supply it as a third argument. Examples ========= >>> from sympy.abc import x, y, z, k, n >>> from sympy.series.kauers import finite_diff >>> from sympy import Sum >>> finite_diff(x**2, x) 2*x + 1 >>> finite_diff(y**3 + 2*y**2 + 3*y + 4, y) 3*y**2 + 7*y + 6 >>> finite_diff(x**2 + 3*x + 8, x, 2) 4*x + 10 >>> finite_diff(z**3 + 8*z, z, 3) 9*z**2 + 27*z + 51 """ expression = expression.expand() expression2 = expression.subs(variable, variable + increment) expression2 = expression2.expand() return expression2 - expression
bigcode/self-oss-instruct-sc2-concepts
def parse_file(file_path): """Parse file with lines: retailer url Args: file_path: The path to the url file Returns: dict: {'retailer1': 'url1', 'retailer2': 'url2'...} """ file = open(file_path) retailer_dict = {} for line in file: try: words_in_line = len(line.split()) # Malformed line. if (words_in_line != 2 and words_in_line != 0): raise Exception(f'[Malformed URL File]: File - {file_path} | Line - {line}') [retailer, url] = line.split() retailer_dict[retailer] = url except: file.close() file.close() return retailer_dict
bigcode/self-oss-instruct-sc2-concepts
def _sar_range(dicoms): """Find the minimum and maximum SAR values in a list of DICOM headers.""" sars = set([float(d.SAR) for d in dicoms]) return str(min(sars)), str(max(sars))
bigcode/self-oss-instruct-sc2-concepts
def get_from_list(list, name): """ searches through list of objects with a .name attribute or surface_shaders and returns the object if it exists or None if not """ for item in list: if item.name == name: return item return None
bigcode/self-oss-instruct-sc2-concepts
def format_size(nb_bytes): """ Format a size expressed in bytes as a string Parameters ---------- nb_bytes : int the number of bytes Return ------ formated : str the given number of bytes fromated Example ------- >>> format_size(100) '100.0 bytes' >>> format_size(1000) '1.0 kB' >>> format_size(1000000) '1.0 MB' >>> format_size(1000000000) '1.0 GB' >>> format_size(1000000000000) '1.0 TB' >>> format_size(1000000000000000000) '1000000.0 TB' """ for x in ['bytes', 'kB', 'MB', 'GB']: if nb_bytes < 1000.0: return "%3.1f %s" % (nb_bytes, x) nb_bytes /= 1000.0 return "%3.1f %s" % (nb_bytes, 'TB')
bigcode/self-oss-instruct-sc2-concepts
def get_method_color(method): """ Return color given the method name. """ color = {} color['Random'] = 'blue' color['Target'] = 'cyan' color['Minority'] = 'cyan' color['Loss'] = 'yellow' color['BoostIn'] = 'orange' color['LeafInfSP'] = 'brown' color['TREX'] = 'green' color['TreeSim'] = 'mediumseagreen' color['InputSim'] = 'gray' color['LOO'] = 'red' color['SubSample'] = 'rebeccapurple' color['LeafInfluence'] = 'brown' color['LeafRefit'] = 'gray' assert method in color, f'{method} not in color dict' return color[method]
bigcode/self-oss-instruct-sc2-concepts
import gzip import bz2 import lzma def fopen(filename, mode=None): """GZ/BZ2/XZ-aware file opening function.""" # NOTE: Mode is not used but kept for not breaking iterators. if filename.endswith('.gz'): return gzip.open(filename, 'rt') elif filename.endswith('.bz2'): return bz2.open(filename, 'rt') elif filename.endswith(('.xz', '.lzma')): return lzma.open(filename, 'rt') else: # Plain text return open(filename, 'r')
bigcode/self-oss-instruct-sc2-concepts
def to_celsius(fahrenheit): """ Accepts degrees Fahrenheit (fahrenheit argument) Returns degrees Celsius """ celsius = (fahrenheit - 32) * 5/9 return celsius
bigcode/self-oss-instruct-sc2-concepts
def get_build_info(input_file): """Get build information in UCSC notation, if possible.""" build_dict = { "hg38": ["GRCh38"], "hg19": ["GRCh37", "b37"], "mm10": ["GRCm38"], "mm9": ["MGSCv37"], "rn6": ["Rnor_6.0"], } with open(input_file, "r") as tfile: build = tfile.readline().strip() new_build = [ k for k, v in build_dict.items() if k == build or build.startswith(tuple(v)) ] if new_build: return new_build[0] return ""
bigcode/self-oss-instruct-sc2-concepts
def is_even(number: int) -> bool: """ This method will find if the number passed is even or not :param number : a number :return: True if even False otherwise """ if number <= 0: return False return number % 2 == 0
bigcode/self-oss-instruct-sc2-concepts
def _parse_ref_dict(reference_dict, strict=True): """Parse the referenced dict into a tuple (TYPE, ID). The ``strict`` parameter controls if the number of keys in the reference dict is checked strictly or not. """ keys = list(reference_dict.keys()) if strict and len(keys) != 1: raise ValueError( "Reference dicts may only have one property! " f"Offending dict: {reference_dict}" ) if not keys: return None type_ = keys[0] id_ = reference_dict[type_] return (type_, id_)
bigcode/self-oss-instruct-sc2-concepts
def yLP2DP(lpY, lptLT, lPix = 1.0): """Convert logical coordinates into device coordinates lpY - y logical coordinate lptLT - logical coordinates of left top screen corner lPix - zoom value, number of logical points inside one device point (aka pixel) return coordinate in device coordinates """ return (lptLT.y - lpY) / lPix
bigcode/self-oss-instruct-sc2-concepts
def dot_dir_dir(direction1, direction2): """ Evaluates the dot product of a direction with another direction. PARAMETERS ---------- direction{1, 2}: Point RETURN ------ : float """ return sum((dir_coord1*dir_coord2 for dir_coord1, dir_coord2 in zip(direction1.coords, direction2.coords)))
bigcode/self-oss-instruct-sc2-concepts
def lowercase_words(text): """ Method used to transform text to lowercase" Parameters: ----------------- text (string): Text to clean Returns: ----------------- text (string): Text after transforming to lowercase. """ text = text.lower() return text
bigcode/self-oss-instruct-sc2-concepts
def remove_zeros(r, M): """ image processor to remove zero :param r: Source image measure :param M: Cost matrix :return: Processed r and M with zeros removed """ M = M[r > 0] r = r[r > 0] return r, M
bigcode/self-oss-instruct-sc2-concepts
def cycle_slice(sliceable, start, end): """Given a list, return right hand cycle direction slice from start to end. Usage:: >>> array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> cycle_slice(array, 4, 7) # from array[4] to array[7] [4, 5, 6, 7] >>> cycle_slice(array, 8, 2) # from array[8] to array[2] [8, 9, 0, 1, 2] """ if type(sliceable) != list: sliceable = list(sliceable) if end >= start: return sliceable[start:end+1] else: return sliceable[start:] + sliceable[:end+1]
bigcode/self-oss-instruct-sc2-concepts
import importlib def make_checker(checker_cls, tmp_dir, **kwargs): """Returns a checker object. Parameters ----------- checker_cls : str the Checker class absolute path name. tmp_dir : string directory to save temporary files in. kwargs : dict keyword arguments needed to create a Checker object. """ sections = checker_cls.split('.') module_str = '.'.join(sections[:-1]) class_str = sections[-1] module = importlib.import_module(module_str) return getattr(module, class_str)(tmp_dir, **kwargs)
bigcode/self-oss-instruct-sc2-concepts
def index_by_iterable(obj, iterable): """ Index the given object iteratively with values from the given iterable. :param obj: the object to index. :param iterable: The iterable to get keys from. :return: The value resulting after all the indexing. """ item = obj for i in iterable: item = item[i] return item
bigcode/self-oss-instruct-sc2-concepts
def create_8021Q_vea_cmd(lpar_id, slotnum, port_vlan_id, addl_vlan_ids): """ Generate IVM command to create 8021Q virtual ethernet adapter. :param lpar_id: LPAR id :param slotnum: virtual adapter slot number :param port_vlan_id: untagged port vlan id :param addl_vlan_ids: tagged VLAN id list :returns: A HMC command that can create 8021Q veth based on the specification from input. """ vids = [] if not addl_vlan_ids else addl_vlan_ids cmd = ('chhwres -r virtualio --rsubtype eth -o a -s %(slot)s ' '--id %(lparid)s -a ieee_virtual_eth=1,' 'port_vlan_id=%(pvid)s,is_trunk=1,' 'trunk_priority=1,\\\"addl_vlan_ids=%(addlvids)s\\\"' % {'slot': slotnum, 'lparid': lpar_id, 'pvid': port_vlan_id, 'addlvids': ",".join(str(x) for x in vids)}) return cmd
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence from typing import List from typing import Set def expand_ranges(ranges: Sequence[Sequence[int]], inclusive: bool = False) -> List[int]: """Expand sequence of range definitions into sorted and deduplicated list of individual values. A range definition is either a: * one element sequence -> an individual value. * two element sequence -> a range of values (either inclusive or exclusive). >>> expand_ranges([[1], [2], [10, 12]]) [1, 2, 10, 11] >>> expand_ranges([[1], [2], [10, 12]], inclusive=True) [1, 2, 10, 11, 12] >>> expand_ranges([[]]) Traceback (most recent call last): ... ValueError: Expected 1 or 2 element list for range definition. Got f0 element list instead. Resulting list is sorted:: >>> expand_ranges([[100], [1, 4]], inclusive=True) [1, 2, 3, 4, 100] Args: ranges: sequence of range definitions inclusive: are the stop values of the range definition inclusive or exclusive. Returns: Sorted deduplicated list of individual values. Raises: ValueError: if range definition is not a one or two element sequence. """ values: Set[int] = set() for r in ranges: if (r_len := len(r)) == 2: values.update(range(r[0], r[1] + (1 if inclusive else 0))) elif r_len == 1: values.add(r[0]) else: raise ValueError(f"Expected 1 or 2 element list for range definition. Got f{len(r)} element list instead.") return sorted(values)
bigcode/self-oss-instruct-sc2-concepts
def GetJidFromHostLog(host_log_file): """Parse the me2me host log to obtain the JID that the host registered. Args: host_log_file: path to host-log file that should be parsed for a JID. Returns: host_jid: host-JID if found in host-log, else None """ host_jid = None with open(host_log_file, 'r') as log_file: for line in log_file: # The host JID will be recorded in a line saying 'Signaling # connected'. if 'Signaling connected. ' in line: components = line.split(':') host_jid = components[-1].lstrip() break return host_jid
bigcode/self-oss-instruct-sc2-concepts
def compose2(f, e): """Compose 2 functions""" return lambda x: f(e(x))
bigcode/self-oss-instruct-sc2-concepts
def filtered_tooltip(options, filter): """Returns tooltip for the filter icon if the filter matches one of the filter options """ for option in options: if filter == option[1]: return "Showing only %s"%option[0] return ""
bigcode/self-oss-instruct-sc2-concepts
def _valvar(unk, vardict): """Determines if an unknown string is a value or a dict variable. Parameters ---------- unk : float or str The unknown value, either a float or a dictionary key. vardict : dict The dictionary to be searched if unk is not a float. Returns ------- float The desired value for unk. Raises ------ ValueError When unk is not a float and not a key in vardict. """ try: return float(unk) except ValueError: if unk in vardict: return vardict[unk] else: raise KeyError('\'{}\' not found in variable list'.format(unk))
bigcode/self-oss-instruct-sc2-concepts
def rectangle(a, b): """ Return classic logic rect function: ^ ...... | | | |___|____|___ a b """ return lambda x, a=a, b=b: 1. if a <= x <= b else 0.
bigcode/self-oss-instruct-sc2-concepts
def fnCalculate_Bistatic_RangeRate(speed_light,tau_u1,tau_d1,tau_u2,tau_d2,tc): """ Calculate the average range rate. eqn 6.37 in Montenbruck 2000. tc = length of integration interval, i.e. length of CPI Created: 04/04/17 """ range_rate = (speed_light/tc)*(tau_u2+tau_d2-tau_u1-tau_d1); # removed 0.5 factor. 19.04.17 return range_rate
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def get_wall_duration(op_names, all_ops, pid_list=(11, 7, 13, 15, 9)): """ Calculates wall duration for each op in op_names. Params: op_names: list (str), names of ops of interest. pid_list: list (str), names of pid to include. all_ops: output of get_all_ops(). Return: total wall duration, dict['op'] = wall duration. """ # 1. Construct dictionary of op with name matching op_names ops_dic = OrderedDict() for name in op_names: ops = [] for op in all_ops: if op['name'] == name: ops.append(op) ops_dic[name] = ops # 2. get duration for each op op_dict = OrderedDict() total_dur = 0 for op_name in op_names: op_dur = 0 for itm in ops_dic[op_name]: if itm['pid'] in pid_list: op_dur += itm['dur'] op_dict[op_name] = op_dur * 1e-3 # convert from us to ms total_dur += op_dur * 1e-3 # fixing the NCCL key: op_dict['unknown (nccl AllReduceKernel_sum_)'] = op_dict.pop('unknown') # Sorting durations: sorted_dur = sorted(op_dict.items(), key=lambda x: x[1])[::-1] # sorted_dur = sorted(op_dict.items(), key=operator.itemgetter(1)) return OrderedDict(sorted_dur), total_dur
bigcode/self-oss-instruct-sc2-concepts
def read_biosids(bdfiles, verbose=False): """ REad the biosample ID files. :param bdfiles: iterable of Files with biosample IDs :param verbose: more output :return: a dict of the sample_name and biosample ID """ biosids = {} for fl in bdfiles: with open(fl, 'r') as f: for l in f: if l.startswith("Accession"): continue p = l.rstrip('\n').split("\t") biosids[p[1]] = p[0] return biosids
bigcode/self-oss-instruct-sc2-concepts
import importlib def _get_module_attr(module_name, attribute_name): """Import a module and get an attribute from it. Args: module_name (str): The module name. attribute_name (str): The attribute name. Returns: Any: The attribute. Raises: ModuleNotFoundError: The module could not be imported. AttributeError: The attribute could not be found in the module. """ module = importlib.import_module(module_name) attribute = getattr(module, attribute_name) return attribute
bigcode/self-oss-instruct-sc2-concepts
def simple_app(environ, start_response): """Simplest possible WSGI application object""" status = '200 OK' response_headers = [('Content-type','text/plain')] start_response(status, response_headers) return ['Hello world!\n' for i in range(100)]
bigcode/self-oss-instruct-sc2-concepts
def ozone_ppm(results, temperature=22): """ Calculate ppm for given results array with Mol/m3 concentrion :param results: array of results in Mol/m3 :param temperature: gas measurement temperature in celsius :return: array of ppm """ P = 1e5 # pascal V = 1 # m3 R = 8.314472 # JK-1 mol-1 T = 273 + temperature # K @ temperature grC # Calculate ppm n = (P * V) / (R * T) # total amount of particles in 1000l gas: mol/m3 gas ppm = [(result / n) * 1e6 for result in results] return ppm
bigcode/self-oss-instruct-sc2-concepts
def css_class(field): """ Returns widgets class name in lowercase """ return field.field.widget.__class__.__name__.lower()
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_file(filepath): """Return the content of a file in the test_files directory.""" full_path = Path(__file__).parent / 'test_files' / filepath with open(full_path, 'rb') as file: return file.read()
bigcode/self-oss-instruct-sc2-concepts
import ipaddress def calc_prefix(arg, addresses): """Calculates the prefix for the list of addresses. Creates the prefix from arg if one is supplied, otherwise computes the prefix from the addresses. """ # This can throw an exception if they supplied an invalid netmask. if arg: return(ipaddress.ip_network(arg)) # Should be at least one address present or we return nothing. if not addresses: return None v4max = int(ipaddress.IPv4Network('0.0.0.0/0').hostmask) v6max = int(ipaddress.IPv6Network('::/0').hostmask) v6bitsonly = v4max ^ v6max # Prefix should be the same for both the ORed and ANDed values. ival = int(addresses[0]) ored = ival if ival <= v4max: ival |= v6bitsonly anded = ival for address in addresses[1:]: ival = int(address) ored |= ival if ival <= v4max: ival |= v6bitsonly anded &= ival if ored > v4max: all_bits = v6max n_bits = 128 else: all_bits = v4max n_bits = 32 i = 0 low_bits = 2**i - 1 mask = low_bits ^ all_bits while low_bits <= ored: if (anded & mask) == (ored & mask): break i += 1 low_bits = 2**i - 1 mask = low_bits ^ all_bits return ipaddress.ip_network(((anded & mask), (n_bits - i)))
bigcode/self-oss-instruct-sc2-concepts
def color_hex_to_dec_tuple(color): """Converts a color from hexadecimal to decimal tuple, color can be in the following formats: 3-digit RGB, 4-digit ARGB, 6-digit RGB and 8-digit ARGB. """ assert len(color) in [3, 4, 6, 8] if len(color) in [3, 4]: color = "".join([c*2 for c in color]) n = int(color, 16) t = ((n >> 16) & 255, (n >> 8) & 255, n & 255) if len(color) == 8: t = t + ((n >> 24) & 255,) return t
bigcode/self-oss-instruct-sc2-concepts
def msg(m, ctx): """Check if the message is in the same channel, and is by the same author.""" return m.channel == ctx.channel and m.author == ctx.author
bigcode/self-oss-instruct-sc2-concepts
import torch def all_or_none_accuracy(preds, targets, dim=-1): """ Gets the accuracy of the predicted sequence. :param preds: model predictions :param targets: the true targets :param dim: dimension to operate over :returns: scalar value for all-or-none accuracy :rtype: float32 """ preds_max = preds.data.max(dim=dim)[1] # get the index of the max log-probability assert targets.shape == preds_max.shape, \ "target[{}] shape does not match preds[{}]".format(targets.shape, preds_max.shape) targ = targets.data return torch.mean(preds_max.eq(targ).cpu().all(dim=dim).type(torch.float32))
bigcode/self-oss-instruct-sc2-concepts
def get_ee_points(offsets, ee_pos, ee_rot): """ Helper method for computing the end effector points given a position, rotation matrix, and offsets for each of the ee points. Args: offsets: N x 3 array where N is the number of points. ee_pos: 1 x 3 array of the end effector position. ee_rot: 3 x 3 rotation matrix of the end effector. Returns: 3 x N array of end effector points. """ return ee_rot.dot(offsets.T) + ee_pos.T
bigcode/self-oss-instruct-sc2-concepts
import math def get_observation_data(observation, t): """ Get observation data at t. """ vars = ['Foil', 'Fw', 'Fs', 'Fa', 'Fb', 'Fc', 'Fh', 'Fg', 'Wt', 'discharge', 'DO2', 'T', 'O2', 'pressure'] # convert to pH from H+ concentration pH = observation.pH.y[t] pH = -math.log(pH) / math.log(10) if pH != 0 else pH return [[var, eval(f"observation.{var}.y[t]", {'observation': observation, 't': t})] for var in vars] + [['pH', pH]]
bigcode/self-oss-instruct-sc2-concepts
def num_cooperators(population): """Get the number of cooperators in the population""" return population['Coop'].sum()
bigcode/self-oss-instruct-sc2-concepts
def int_or_zero(s): """ >>> int_or_zero('') 0 >>> int_or_zero('10') 10 """ return 0 if not s else int(s)
bigcode/self-oss-instruct-sc2-concepts
def split_company_name_notes(name): """Return two strings, the first representing the company name, and the other representing the (optional) notes.""" name = name.strip() notes = u'' if name.endswith(')'): fpidx = name.find('(') if fpidx != -1: notes = name[fpidx:] name = name[:fpidx].rstrip() return name, notes
bigcode/self-oss-instruct-sc2-concepts
def test_asyncio_request_response(connection, receiver): """ Test request/response messaging pattern with coroutine callbacks """ async def endpoint_handler(message): return message.payload + "-pong" connection.register_async_endpoint(endpoint_handler, "test.asyncio.request") connection.call_async( receiver.create_callback_coroutine(), "test.asyncio.request", "ping" ) assert ["ping-pong"] == receiver.wait_for_messages()
bigcode/self-oss-instruct-sc2-concepts
import random def stat_check(stat1, stat2): """ Checks if stat1 wins over stat2 in competitive stat check. """ roll1 = random.randrange(stat1) roll2 = random.randrange(stat2) return roll1 >= roll2
bigcode/self-oss-instruct-sc2-concepts
def artists_to_mpd_format(artists): """ Format track artists for output to MPD client. :param artists: the artists :type track: array of :class:`mopidy.models.Artist` :rtype: string """ artists = list(artists) artists.sort(key=lambda a: a.name) return ', '.join([a.name for a in artists if a.name])
bigcode/self-oss-instruct-sc2-concepts
def flatten_substitution_choices(subs_choices): """ For a given dict {expr: (expr1, expr2)} returns a list of all possible substitution arising from choosing to subs expr by expr1 or expr2. """ subs_choices = subs_choices.copy() if not subs_choices: return [{}] result = [] expr = next(iter(subs_choices.keys())) choice1, choice2 = subs_choices.pop(expr) remaining_choices_flat = flatten_substitution_choices(subs_choices) for c in remaining_choices_flat: c1 = c.copy() c1[expr] = choice1 result.append(c1) if choice1 != choice2: c2 = c.copy() c2[expr] = choice2 result.append(c2) return result
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def cmp(a: Any, b: Any) -> int: """ Restores the useful `cmp` function previously in Python 2. - Implemented according to [What's New in Python 3.0](https://docs.python.org/3.0/whatsnew/3.0.html#ordering-comparisons). Args: a: An object. b: An object. Returns: An integer of -1, 0, or 1, denoteing whether a > b, a == b, or a < b, respectively. """ return (a > b) - (a < b)
bigcode/self-oss-instruct-sc2-concepts
def forbidden_view(message, request): """Get JSON response for a 403 status code.""" request.response.status = 403 return {'message': str(message), 'status': 403}
bigcode/self-oss-instruct-sc2-concepts
def normal_diffusion(times, diffusion_coefficient, dimensions=2): """Models the relationship between mean squared displacement and time during a normal (Brownian) diffusion process. During normal diffusion the mean squared displacement increases linearly with time according to the Einstein relation. """ return 2 * dimensions * diffusion_coefficient * times
bigcode/self-oss-instruct-sc2-concepts
import re def check_mac(mac_address, capital_letters=True): """ Check mac address is valid. Either format of 52:54:00:AE:E3:41, or 52-54-00-AE-E3-41 """ if capital_letters: regex = r'^([0-9A-F]{2}[:]){5}([0-9A-F]{2})$' else: regex = r'^([0-9a-f]{2}[:]){5}([0-9a-f]{2})$' if (re.fullmatch(regex, mac_address)): return 0 return -1
bigcode/self-oss-instruct-sc2-concepts
def electrolyte_diffusivity_Valoen2005(c_e, T): """ Diffusivity of LiPF6 in EC:DMC as a function of ion concentration, from [1] (eqn 14) References ---------- .. [1] Valøen, Lars Ole, and Jan N. Reimers. "Transport properties of LiPF6-based Li-ion battery electrolytes." Journal of The Electrochemical Society 152.5 (2005): A882-A891. Parameters ---------- c_e : :class:`pybamm.Symbol` Dimensional electrolyte concentration [mol.m-3] T : :class:`pybamm.Symbol` Dimensional temperature [K] Returns ------- :class:`pybamm.Symbol` Dimensional electrolyte diffusivity [m2.s-1] """ # mol/m3 to molar c_e = c_e / 1000 T_g = 229 + 5 * c_e D_0 = -4.43 - 54 / (T - T_g) D_1 = -0.22 # cm2/s to m2/s # note, in the Valoen paper, ln means log10, so its inverse is 10^x return (10 ** (D_0 + D_1 * c_e)) * 1e-4
bigcode/self-oss-instruct-sc2-concepts
def pascal_voc_palette(num_cls=None): """ Generates the PASCAL Visual Object Classes (PASCAL VOC) data-set color palette. Data-Set URL: http://host.robots.ox.ac.uk/pascal/VOC/ . Original source taken from: https://gluon-cv.mxnet.io/_modules/gluoncv/utils/viz/segmentation.html . `num_cls`: the number of colors to generate return: the generated color palette """ # by default generate 256 colors if num_cls is None: num_cls = 256 palette = [0] * (num_cls * 3) for j in range(0, num_cls): lab = j palette[j*3+0] = 0 palette[j*3+1] = 0 palette[j*3+2] = 0 i = 0 while lab > 0: palette[j*3+0] |= (((lab >> 0) & 1) << (7-i)) palette[j*3+1] |= (((lab >> 1) & 1) << (7-i)) palette[j*3+2] |= (((lab >> 2) & 1) << (7-i)) i = i + 1 lab >>= 3 return palette
bigcode/self-oss-instruct-sc2-concepts
def R(units): """Universal molar gas constant, R Parameters ---------- units : str Units for R. Supported units ============= =============================================== ============ Unit Description Value ============= =============================================== ============ J/mol/K Joule per mole per kelvin 8.3144598 kJ/mol/K kiloJoule per mole per kelvin 8.3144598e-3 L kPa/mol/K Liter kilopascal per mole per kelvin 8.3144598 cm3 kPa/mol/K Cubic centimeter kilopascal per mole per kelvin 8.3144598e3 m3 Pa/mol/K Cubic meter pascal per mole per kelvin 8.3144598 cm3 MPa/mol/K Cubic centimeter megapascal per mole per kelvin 8.3144598 m3 bar/mol/K Cubic meters bar per mole per kelvin 8.3144598e-5 L bar/mol/K Liter bar per mole per kelvin 8.3144598e-2 L torr/mol/K Liter torr per mole per kelvin 62.363577 cal/mol/K Calorie per mole per kelvin 1.9872036 kcal/mol/K Kilocalorie per mole per kevin 1.9872036e-3 L atm/mol/K Liter atmosphere per mole per kelvin 0.082057338 cm3 atm/mol/K Cubic centimeter atmosphere per mole per kelvin 82.057338 eV/K Electron volt per molecule per kelvin 8.6173303e-5 Eh/K Hartree per molecule per kelvin 3.1668105e-6 Ha/K Hartree per molecule per kelvin 3.1668105e-6 ============= =============================================== ============ Returns ------- R : float Universal molar gas constant in appropriate units Raises ------ KeyError If units is not supported. """ R_dict = { 'J/mol/K': 8.3144598, 'kJ/mol/K': 8.3144598e-3, 'L kPa/mol/K': 8.3144598, 'cm3 kPa/mol/K': 8.3144598e3, 'm3 Pa/mol/K': 8.3144598, 'cm3 MPa/mol/K': 8.3144598, 'm3 bar/mol/K': 8.3144598e-5, 'L bar/mol/K': 8.3144598e-2, 'L torr/mol/K': 62.363577, 'cal/mol/K': 1.9872036, 'kcal/mol/K': 1.9872036e-3, 'L atm/mol/K': 0.082057338, 'cm3 atm/mol/K': 82.057338, 'eV/K': 8.6173303e-5, 'Eh/K': 3.1668105e-06, 'Ha/K': 3.1668105e-06, } try: return R_dict[units] except KeyError: err_msg = ('Invalid unit for R: {}. Use help(pmutt.constants.R) ' 'for accepted units.'.format(units)) raise KeyError(err_msg)
bigcode/self-oss-instruct-sc2-concepts
import torch def compute_pdist_matrix(batch, p=2.0): """ Computes the matrix of pairwise distances w.r.t. p-norm :param batch: torch.Tensor, input vectors :param p: float, norm parameter, such that ||x||p = (sum_i |x_i|^p)^(1/p) :return: torch.Tensor, matrix A such that A_ij = ||batch[i] - batch[j]||_p (for flattened batch[i] and batch[j]) """ mat = torch.zeros(batch.shape[0], batch.shape[0], device=batch.device) ind = torch.triu_indices(batch.shape[0], batch.shape[0], offset=1, device=batch.device) mat[ind[0], ind[1]] = torch.pdist(batch.view(batch.shape[0], -1), p=p) return mat + mat.transpose(0, 1)
bigcode/self-oss-instruct-sc2-concepts
import socket import struct def get_ip_mreqn_struct(multicast_address, interface_address, interface_name): """ Set up a mreqn struct to define the interface we want to bind to """ # See https://github.com/torvalds/linux/blob/866ba84ea30f94838251f74becf3cfe3c2d5c0f9/include/uapi/linux/in.h#L168 ip_mreqn = socket.inet_aton(multicast_address) ip_mreqn += socket.inet_aton(interface_address) ip_mreqn += struct.pack('@i', socket.if_nametoindex(interface_name)) return ip_mreqn
bigcode/self-oss-instruct-sc2-concepts
def _get_id(mf, url=None): """ get the uid of the mf object Args: mf: python dictionary of some microformats object url: optional URL to use in case no uid or url in mf Return: string containing the id or None """ props = mf['properties'] if 'uid' in props: return props['uid'][0] elif 'url' in props: return props['url'][0] else: return None
bigcode/self-oss-instruct-sc2-concepts
def get_worksheet_names(workbook): """ Gets the names of all the worksheets of the current workbook. :param workbook: Current workbook to manipulate. :return: A list of all the worksheets' names of the current workbook. """ return workbook.sheetnames
bigcode/self-oss-instruct-sc2-concepts
import time def is_task_successful(task, retry=10 , interval=5): """ Method to check the task state. :param task: VMware task. :param retry(int): Number of Retries. :param interval(int): Interval between each retry. :return: bool( """ while retry > 0: task_status = str(task.info.state) if task_status == 'success': return True if task_status== 'running': time.sleep(interval) retry -= 1 print("Task not successful.") return False
bigcode/self-oss-instruct-sc2-concepts
import torch def binary_acc(y_pred, y): """Calculates model accuracy Arguments: y_pred {torch.Tensor} -- Output of model between 0 and 1 y {torch.Tensor} -- labels/target values Returns: [torch.Tensor] -- accuracy """ y_pred_tag = torch.round(y_pred) correct_results_sum = (y_pred_tag == y).float().sum() n = y.nelement() acc = correct_results_sum/n acc = acc * 100 return acc.item()
bigcode/self-oss-instruct-sc2-concepts
def cvode_stats_to_dict(path: str) -> dict: """ Converts a Delphin integrator_cvode_stats file into a dict. :param path: path to folder :return: converted tsv dict """ file_obj = open(path + '/integrator_cvode_stats.tsv', 'r') lines = file_obj.readlines() file_obj.close() tsv_dict = {'time': [], 'steps': [], 'rhs_evaluations': [], 'lin_setups': [], 'number_iterations': [], 'number_conversion_fails': [], 'number_error_fails': [], 'order': [], 'step_size': []} for i in range(1, len(lines)): line = lines[i].split('\t') tsv_dict['time'].append(float(line[0].strip())) tsv_dict['steps'].append(int(line[1].strip())) tsv_dict['rhs_evaluations'].append(int(line[2].strip())) tsv_dict['lin_setups'].append(int(line[3].strip())) tsv_dict['number_iterations'].append(int(line[4].strip())) tsv_dict['number_conversion_fails'].append(int(line[5].strip())) tsv_dict['number_error_fails'].append(int(line[6].strip())) tsv_dict['order'].append(int(line[7].strip())) tsv_dict['step_size'].append(float(line[8].strip())) return tsv_dict
bigcode/self-oss-instruct-sc2-concepts
def _scale_col_to_target(col, target, metric_func): """ Scale a column's values so that in aggregate they match some metric, for example, mean, median, or sum. Parameters ---------- col : pandas.Series target : number metric_func : callable Must accept a Series and return a number. Returns ------- scaled : pandas.Series """ current = metric_func(col) multiplier = target / current return col * multiplier
bigcode/self-oss-instruct-sc2-concepts
def binlogs_to_backup(cursor, last_binlog=None): """ Finds list of binlogs to copy. It will return the binlogs from the last to the current one (excluding it). :param cursor: MySQL cursor :param last_binlog: Name of the last copied binlog. :return: list of binlogs to backup. :rtype: list """ binlogs = [] cursor.execute("SHOW BINARY LOGS") for row in cursor.fetchall(): binlog = row['Log_name'] if not last_binlog or binlog > last_binlog: binlogs.append(binlog) return binlogs[:-1]
bigcode/self-oss-instruct-sc2-concepts
def performanceCalculator(count, avg, std, maxv, countref, avgref, stdref, maxvref): """ =========================================================================== Performance calculator function =========================================================================== Calculate performance based on reference values. If some value is None return None **Args**: * count : actual number of samples -- (int) * avg : actual duration average -- (float) * std : actual duration standar desviation -- (float) * maxv : actual duration max value -- (float) * countref : reference number of samples -- (int) * avgref : reference duration average -- (float) * stdref : reference duration standar desviation -- (float) * maxvref : reference duration max value -- (float) **Returns**: performance value indicator. [0-1] -- (float) """ if avgref == None or stdref == None or maxvref == None: return None # f = 0 # if maxvref == 0: maxvref = 0.1 # if maxvref < 0.2: # f = avg / (maxvref * 10) # if maxvref < 1: # f = avg / (maxvref * 5) # if maxvref < 10: # f = avg / (maxvref * 2) # # f = 0 # if maxvref == 0: maxvref = 0.1 # if maxvref < 0.2: # f = avg / (maxvref * 5) # elif maxvref < 1: # f = avg / (maxvref * 3) # elif maxvref < 10: # f = avg / (maxvref * 1.5) # else: # f = avg / maxvref # f = 1-f if stdref < 0.01: stdref = 0.01 f = (1-((avg - avgref) / (stdref*2)))*0.9 if f > 1: f=1 if f < 0: f=0 return f
bigcode/self-oss-instruct-sc2-concepts
import torch def weighted_mean_rule_func(predictions: torch.Tensor, weights: torch.Tensor, *_) -> torch.Tensor: """ Mean the predictions of different classifier outputs with classifier weights. Args: predictions: outputs of the base models weights: a one-dimensional tensor with a float for each classifier Returns: a prediction tensor """ return torch.mean(predictions * weights.unsqueeze(dim=1), dim=0)
bigcode/self-oss-instruct-sc2-concepts
def set_val_if_dict( dct, key, val ): """ Set the { ... `key`:`val` ... } only if `dct` is a dictionary """ try: dct[ key ] = val return True except (TypeError, KeyError): return False
bigcode/self-oss-instruct-sc2-concepts
import torch from typing import Optional def weighted_average( x: torch.Tensor, weights: Optional[torch.Tensor] = None, dim=None ) -> torch.Tensor: """ Computes the weighted average of a given tensor across a given dim, masking values associated with weight zero, meaning instead of `nan * 0 = nan` you will get `0 * 0 = 0`. Parameters ---------- x Input tensor, of which the average must be computed. weights Weights tensor, of the same shape as `x`. dim The dim along which to average `x` Returns ------- Tensor: The tensor with values averaged along the specified `dim`. """ if weights is not None: weighted_tensor = torch.where(weights != 0, x * weights, torch.zeros_like(x)) sum_weights = torch.clamp( weights.sum(dim=dim) if dim else weights.sum(), min=1.0 ) return ( weighted_tensor.sum(dim=dim) if dim else weighted_tensor.sum() ) / sum_weights else: return x.mean(dim=dim)
bigcode/self-oss-instruct-sc2-concepts
def check_sudoku(sudoku): """ Funktion zur Überprüfung einer Sudoku-Lösung auf Korrektheit. Als Eingabe an die Funktion wird die Sudoku-Lösung in Form einer Liste von Listen übergeben. Die Funktion gibt als Ergebnis einen Wahrheitswert zurück. """ # Prüfe Zeilen # Gehe jede Zeile durch for line in sudoku: occurrences = [0, 0, 0, 0, 0, 0, 0, 0, 0] # Gehe jedes Element in der Zeile durch for number in line: # Erhöhe Zähler für Zahl um 1 occurrences[number - 1] += 1 # Wenn Zahl häufiger als einmal vorkommt # -> Keine gültige Lösung if max(occurrences) > 1: return False # Prüfe Spalten # Gehe jede Spalte durch for column in range(8): occurrences = [0, 0, 0, 0, 0, 0, 0, 0, 0] # Gehe jedes Element in der Spalte durch for line in sudoku: # Hole Zahl aus Position in Sudoku number = line[column] # Erhöhe Zähler für Zahl um 1 occurrences[number - 1] += 1 # Wenn Zahl häufiger als einmal vorkommt # -> Keine gültige Lösung if max(occurrences) > 1: return False # Prüfe 3x3 Blöcke # Bestimme Blocknummer for i in range(3): # Blocknummer in x-Richtung for j in range(3): # Blocknummer in y-Richtung occurrences = [0, 0, 0, 0, 0, 0, 0, 0, 0] # Gehe inneren Block durch for y in range(3): for x in range(3): # Bestimme globale Position pos_x = 3 * i + x pos_y = 3 * j + y # Bestimme Zahl number = sudoku[pos_y][pos_x] # Erhöhe Zähler für Zahl um 1 occurrences[number - 1] += 1 # Wenn Zahl häufiger als einmal vorkommt # -> Keine gültige Lösung if max(occurrences) > 1: return False # Wenn das Programm bis an diese Stelle kommt, wurde keine "return"- # Anweisung ausgeführt. Das bedeutet, die Prüfung ist erfolgreich! return True
bigcode/self-oss-instruct-sc2-concepts
import re def _is_pull_request_base_branch_match(pull_request: dict, base_branch: str) -> bool: """ Determine if the pull request represents a notification for a base branch we should consider. :param pull_request: Pull request section of payload to examine :type: :class:`~dict` :param base_branch: Regular expression to match base branches to accept :type: :class:`~str` :return: Boolean indicating pull request state :rtype: :class:`~bool` """ base = pull_request.get('base') if not base: return False ref = base.get('ref') return ref and re.match(base_branch, ref) is not None
bigcode/self-oss-instruct-sc2-concepts
def get_contigous_borders(indices): """ helper function to derive contiguous borders from a list of indices Parameters ---------- indicies : all indices at which a certain thing occurs Returns ------- list of groups when the indices starts and ends (note: last element is the real last element of the group _not_ n+1) """ r =[ [indices[0]] ] prev = r[0][0] for ix,i in enumerate(indices): # distance bw last occurence and current > 1 # then there is obviously a space if (i - prev) > 1: # add end r[-1].append(indices[ix-1]) # add new start r.append([ indices[ix] ]) prev = i r[-1].append( indices[-1] ) return r
bigcode/self-oss-instruct-sc2-concepts
import math def hsvToRGB(h, s, v): """Convert HSV color space to RGB color space @param h: Hue @param s: Saturation @param v: Value return (r, g, b) """ hi = math.floor(h / 60.0) % 6 f = (h / 60.0) - math.floor(h / 60.0) p = v * (1.0 - s) q = v * (1.0 - (f*s)) t = v * (1.0 - ((1.0 - f) * s)) D = {0: (v, t, p), 1: (q, v, p), 2: (p, v, t), 3: (p, q, v), 4: (t, p, v), 5: (v, p, q)} return D[hi]
bigcode/self-oss-instruct-sc2-concepts
def is_too_similar_for_axes(word1, word2): """ Checks if the words contain each other """ return word1 in word2 or word2 in word1
bigcode/self-oss-instruct-sc2-concepts
def dominance(solution_1, solution_2): """ Function that analyze solutions dominance. Parameters ----------- :param solution_1: Solution :param solution_2: Solution Returns --------- :return int If solution_1 dominates solution_2 -> return 1 :return -1 If solution_2 dominates solution_1 -> return -1 :return 0 If neither solution dominates the other -> return 0 """ dominance_1, dominance_2 = False, False for i, value in enumerate(solution_1.values): if value > solution_2.values[i]: #  Solution 1 at least greater in one value dominance_1 = True elif value < solution_2.values[i]: # Solution 2 at least greater in one value dominance_2 = True # Solution 1 dominates solution 2 if dominance_1 and not dominance_2: return 1 # Solution 2 dominates solution 1 if not dominance_1 and dominance_2: return -1 return 0
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _parse_csv(s: str) -> List[str]: """Return the values of a csv string. >>> _parse_csv("a,b,c") ['a', 'b', 'c'] >>> _parse_csv(" a, b ,c ") ['a', 'b', 'c'] >>> _parse_csv(" a,b,c ") ['a', 'b', 'c'] >>> _parse_csv(" a,") ['a'] >>> _parse_csv("a, ") ['a'] """ return [s.strip() for s in s.split(",") if s.strip() != ""]
bigcode/self-oss-instruct-sc2-concepts
def get_antigen_name(qseqid): """ Get the antigen name from the BLASTN result query ID. The last item delimited by | characters is the antigen name for all antigens (H1, H2, serogroup) @type qseqid: str @param qseqid: BLASTN result query ID @return: antigen name """ if qseqid: return qseqid.split('|')[-1]
bigcode/self-oss-instruct-sc2-concepts
import requests def get_img_content(img_url): """ 函数功能:向服务器请求图片数据 参数: img_url:图片的链接地址 返回:图片的内容,即图片的二进制数据 """ header2 = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36' try: r = requests.get(img_url, headers={'User-Agent': header2}) return r.content except Exception as e: print(e)
bigcode/self-oss-instruct-sc2-concepts
def normalize_matrix(transformer, matrix): """Normalize count matrix to scale down the impact of very frequent tokens :param transformer: A Sklearn TfidfTransformer object :param matrix: An array representing a term document matrix, output of CountVectorizer.fit_transform """ matrix_normalized = transformer.fit_transform(matrix) return matrix_normalized
bigcode/self-oss-instruct-sc2-concepts
import tempfile import zipfile def unpack_zip(zip_ffn): """ Unpacks zip file in temp directory Parameters: =========== zip_ffn: str Full filename to zip file Returns: ======== temp_dir: string Path to temp directory """ #build temp dir temp_dir = tempfile.mkdtemp() #unpack tar zip_fd = zipfile.ZipFile(zip_ffn) zip_fd.extractall(path=temp_dir) zip_fd.close() return temp_dir
bigcode/self-oss-instruct-sc2-concepts
def _colors(strKey): """ Function gives access to the RxCS console colors dictionary. The Function returns a proper console color formating string (ANSI colors) based on the key given to the function. |br| Available keys: 'PURPLE' 'BLUE' 'GREEN' 'YELLOW' 'RED' 'BLACK' 'DARK_MAGENTA' 'AQUA' 'BLUE_BG' 'DARK_BLUE' 'DARK_GREEN' 'GREY30' 'GREY70' 'PROGRESS' -> color for progress signs ('>>>', '>>', '>') 'INFO' -> color for info messages 'BULLET_INFO' -> color for bullet info messages 'BULLET' -> color for bullets ('*') 'WARN' -> color for warning messages 'PARAM' -> color for parameters printing 'OK' -> color for good messages 'ENDC' -> console formatting string which switches of the coloring Args: strKey (string): key of the color Returns: strColor (string): console color formating string """ # Define colors dColors = {} dColors['PURPLE'] = '\033[95m' dColors['BLUE'] = '\033[94m' dColors['GREEN'] = '\033[92m' dColors['YELLOW'] = '\033[93m' dColors['RED'] = '\033[91m' dColors['BLACK'] = '\033[30m' dColors['DARK_MAGENTA'] = '\033[35m' dColors['AQUA'] = '\033[96m' dColors['BLUE_BG'] = '\033[44m' dColors['DARK_BLUE'] = '\033[34m' dColors['DARK_GREEN'] = '\033[32m' dColors['GREY30'] = '\033[30m' dColors['GREY70'] = '\033[97m' # Define colors for communication dColors['PROGRESS'] = dColors['DARK_MAGENTA'] dColors['INFO'] = dColors['DARK_GREEN'] dColors['BULLET_INFO'] = dColors['AQUA'] dColors['BULLET'] = dColors['DARK_MAGENTA'] dColors['WARN'] = dColors['RED'] dColors['PARAM'] = dColors['AQUA'] dColors['OK'] = dColors['DARK_GREEN'] dColors['ENDC'] = '\033[0m' # Return the correct color strColor = dColors[strKey] return strColor
bigcode/self-oss-instruct-sc2-concepts
def get_target_name(item): """Take a query record, split the name field, and return the target name.""" return item.file_location.split('/')[-2].split('_')[-1]
bigcode/self-oss-instruct-sc2-concepts
import re def split_by_punct(segment): """Splits str segment by punctuation, filters our empties and spaces.""" return [s for s in re.split(r'\W+', segment) if s and not s.isspace()]
bigcode/self-oss-instruct-sc2-concepts
import re def filename_safe(name: str, lower: bool = False) -> str: """ Perform the necessary replacements in <name> to make it filename safe. Any char that is not a-z, A-Z, 0-9, '_', ' ', or '-' is replaced with '_'. Convert to lowercase, if lower=True. :param lower: If True, apply str.lower() to result. :param name: name string to be converted :return: string containing the filename-save version of item_name """ # Inspired by Django's slugify function cleaned = re.sub(r'[^\w\s-]', '_', name) return cleaned.lower() if lower else cleaned
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import Optional def _parse_key_value_pair(arg: str) -> Tuple[Optional[str], str]: """ Parameters ---------- arg : str Arg in the format of "Value" or "Key=Value" Returns ------- key : Optional[str] If key is not specified, None will be the key. value : str """ key: Optional[str] value: str if "=" in arg: parts = arg.split("=", 1) key = parts[0].strip() value = parts[1].strip() else: key = None value = arg.strip() return key, value
bigcode/self-oss-instruct-sc2-concepts
def str_to_bool(val: str) -> bool: """Converts a string to a boolean based on its value. :param val: string being converted :return: boolean value expressed in the string :raises: ValueError if the string does not contain a value corresponding to a boolean value """ if isinstance(val, str): if val.capitalize() == str(True): return True elif val.capitalize() == str(False): return False raise ValueError("must be True or False (case-insensitive)")
bigcode/self-oss-instruct-sc2-concepts
import functools def require(required): """ Decorator for checking the required values in state. It checks the required attributes in the passed state and stop when any of those is missing. """ def decorator(function): @functools.wraps(function) def wrapper(*args, **kwargs): for key in required: assert key in args[0], '{} is missing'.format(key) return function(*args, **kwargs) return wrapper return decorator
bigcode/self-oss-instruct-sc2-concepts
def GetNestedAttr(content, nested_attr, default=None): """Get the (nested) attribuite from content. Get the (nested) attribute from the content dict. E.X. content is {key1: {key2: {key3: value3}}, key4: value4} nested_attr = [key1] gets {key2: value2, {key3: value3}} nested_attr = [key1, key2] gets {key3: value3} nested_attr = [key1, key2, key3] gets value3 nested_attr = [key5] gets the default value. Args: content: A dict of (nested) attributes. nested_attr: String list presenting the (nested) attribute to get. default: Default value to return if the attribute doesn't exist. Returns: The corresponding value if the attribute exits; else, default. """ assert isinstance(nested_attr, list), 'nested_attr must be a list.' if content is None: return default assert isinstance(content, dict), 'content must be a dict.' value = content for attr in nested_attr: assert isinstance(attr, str), 'attribute name must be a string.' if not isinstance(value, dict): return default value = value.get(attr, default) return value
bigcode/self-oss-instruct-sc2-concepts
import json def format_json(json_string): """Converts a minified JSON str to a prettified JSON str. Args: json_string (str): A str representing minified JSON. Returns: (str): A str representing prettified JSON. """ parsed = json.loads(json_string) return json.dumps(parsed, indent=4)
bigcode/self-oss-instruct-sc2-concepts
def wrapped_list(list, which): """ Selects an element from a list, wrapping in either direction. """ if which < 0: ix = len(list) + (which % len(list)) else: ix = which % len(list) return list[ix]
bigcode/self-oss-instruct-sc2-concepts