seed
stringlengths
1
14k
source
stringclasses
2 values
def get_contactinfo_tuple(member, considerNoPublish=False): """Returns tuple with the member's contact information If considerNoPublish is True a member with noPublishContactInfo_fld == 1 will get empty contact information fields. """ contactinfo = member.contactinfo department = '?' try: department = member.department[0].department.name_fld except: pass if considerNoPublish and member.dead_fld == 0 and member.noPublishContactInfo_fld == 1: return (member.preferredName_fld, member.surName_fld, "", "", "", "", "", "") return (member.preferredName_fld, member.surName_fld, contactinfo.email_fld, contactinfo.streetAddress_fld, contactinfo.postalCode_fld, contactinfo.city_fld, contactinfo.country_fld, department)
bigcode/self-oss-instruct-sc2-concepts
import re def regex_escape(string): """Escape all regular expressions special characters from STRING.""" return re.escape(string)
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def is_valid_isodate(date: str, check_timezone: bool = False) -> bool: """Check if a string is a valid ISO formatted datestring""" dt = None try: dt = datetime.fromisoformat(date) except ValueError: return False if check_timezone: if dt.tzinfo: return True else: return False return True
bigcode/self-oss-instruct-sc2-concepts
def _append_notes_to_markdown(*, markdown: str, notes: str) -> str: """ Append a notes string to a specified markdown string. Parameters ---------- markdown : str Target markdown string. notes : str Target notes string. Returns ------- markdown : str Result markdown string. """ if notes == '': return markdown if markdown != '': markdown += '\n\n' markdown += ( '**[Notes]**' f'\n\n{notes}<hr>' ) return markdown
bigcode/self-oss-instruct-sc2-concepts
def inhg_to_hpa(value: float) -> float: """Convert an inHg value to hPa.""" return value * 33.8639
bigcode/self-oss-instruct-sc2-concepts
import re def determine_file_extension_from_response(response): """ This retrieves the file extension from the response. :param requests.Response response: the response object from the download :return the extension indicating the file compression(e.g. zip, tgz) :rtype str """ content_disposition = response.headers.get('content-disposition') ext = None if content_disposition: file_name = re.findall("filename\\*?=([^;]+)", content_disposition) file_name = file_name[0].strip().strip('"') ext = file_name.split(".")[1] if ext is None: message = f"Could not determine compression type of: {content_disposition}" raise Exception(message) return ext
bigcode/self-oss-instruct-sc2-concepts
import traceback def format_last_exception(prefix=" | "): """Format the last exception for display it in tests. This allows to raise custom exception, without loosing the context of what caused the problem in the first place: >>> def f(): ... raise Exception("Something terrible happened") >>> try: ## doctest: +ELLIPSIS ... f() ... except Exception: ... formated_exception = format_last_exception() ... raise ValueError('Oups, an error occured:\\n%s' ... % formated_exception) Traceback (most recent call last): ... ValueError: Oups, an error occured: | Traceback (most recent call last): ... | Exception: Something terrible happened """ return '\n'.join( str(prefix + line) for line in traceback.format_exc().strip().split('\n'))
bigcode/self-oss-instruct-sc2-concepts
def get_next_connection_index(db, profile_id, folder_path): """Finds next connection index Args: db (object): The db object profile_id (int): The id of the profile folder_path (str): The folder path used for grouping and nesting connections Returns: Next connection index value """ res = db.execute('''SELECT max(`index`) FROM profile_has_db_connection WHERE profile_id=? and folder_path=?''', (profile_id, folder_path)).fetch_one() return res[0] + 1 if res[0] is not None else 1
bigcode/self-oss-instruct-sc2-concepts
import re def splitcamelcase(string): """Transform CamelCase into camel case""" res = "" for ch in string: if re.match('[A-Z]', ch): res += ' ' + ch.lower() else: res += ch return res
bigcode/self-oss-instruct-sc2-concepts
def can_make_target_sum(integers, target): """Return True if a pair of integers that add up to `target` are found. The time complexity of this algorithm is O(N), where N is the number of integers in `integers`.""" complements = set() for i in integers: # O(N) complement = target - i # O(1) if complement in complements: # O(1) return True complements.add(i) # O(1) return False
bigcode/self-oss-instruct-sc2-concepts
import itertools def flatten_list(lst): """concatenate a list of lists""" return list(itertools.chain.from_iterable(lst))
bigcode/self-oss-instruct-sc2-concepts
def calculate_manhattan_dist(idx, value, n): """calculate the manhattan distance of a single tile""" goalRow = value // n #row index at goal goalCol = value % n #col index at goal currentRow = idx // n #current row index currentCol = idx % n #current col index dist = abs(goalRow - currentRow) + abs(goalCol - currentCol) #manhattan return dist
bigcode/self-oss-instruct-sc2-concepts
def parse_slots(content): """Parse the list of slots. Cleans up spaces between items. Parameters ---------- content: :class:`str` A string containing comma separated values. Returns ------- :class:`str`: The slots string. """ slots = content.split(",") return ",".join(s.strip() for s in slots)
bigcode/self-oss-instruct-sc2-concepts
def isfloat(in_str): """Check if a string can be cast to float""" try: float(in_str) return True except ValueError: return False
bigcode/self-oss-instruct-sc2-concepts
def get_primary_axis(hist): """Returns the highest dimension axis, e.g. if 1D histo this will return the y-axis. """ dim = hist.GetDimension() if dim == 1: return hist.GetYaxis() elif dim == 2: return hist.GetZaxis()
bigcode/self-oss-instruct-sc2-concepts
def xtype_from_derivation(derivation): """Returns the script type to be used for this derivation.""" if derivation.startswith("m/84'"): return 'p2wpkh' elif derivation.startswith("m/49'"): return 'p2wpkh-p2sh' else: return 'p2pkh'
bigcode/self-oss-instruct-sc2-concepts
import json def load_entities(path): """ Load the entities and return an dict carrying all relevant info """ try: with open(path) as file: entities = json.loads(file.read()) ents = {} for e in entities['entities']: ents[e['entity']] = {'opening hours':e['opening hours'], 'location':e['location'], 'contact':e['contact'], 'link':e['link'] } return ents except FileNotFoundError: print("Entities file not found.") return {}
bigcode/self-oss-instruct-sc2-concepts
import re def ExtractThroughput(output): """Extract throughput from MNIST output. Args: output: MNIST output Returns: throuput float """ regex = r'INFO:tensorflow:global_step/sec: (\S+)' match = re.findall(regex, str(output)) return sum(float(step) for step in match) / len(match)
bigcode/self-oss-instruct-sc2-concepts
def hex2bytes(hex_str): """ Converts spaced hexadecimal string (output of ``bytes2hex()``) function to an array of bytes. Parameters ---------- hex_str: str String of hexadecimal numbers separated by spaces. Returns ------- bytes Array of bytes (ready to be unpicked). """ # Delete spaces from the string to prepare it for conversion. hex_str = hex_str.replace(" ", "") return bytes.fromhex(hex_str)
bigcode/self-oss-instruct-sc2-concepts
def getfullURL(date): """Returns Congressional Record URL (of PDF record) for a given date.""" base_url = "https://www.gpo.gov/fdsys/pkg/CREC-"+date+"/pdf/CREC-"+date+".pdf" return base_url
bigcode/self-oss-instruct-sc2-concepts
import math def lorentzian(x, amplitude=1.0, center=0.0, sigma=1.0): """Return a 1-dimensional Lorentzian function. lorentzian(x, amplitude, center, sigma) = (amplitude/(1 + ((1.0*x-center)/sigma)**2)) / (pi*sigma) """ return (amplitude / (1 + ((1.0 * x - center) / sigma) ** 2)) / (math.pi * sigma)
bigcode/self-oss-instruct-sc2-concepts
def index_sets(items): """ Create a dictionary of sets from an iterable of `(key, value)` pairs. Each item is stored in a set at `key`. More than one item with same key means items get appended to same list. This means items in indices are unique, but they must be hashable. """ index = {} for key, value in items: try: index[key].add(value) except KeyError: index[key] = set((value,)) return index
bigcode/self-oss-instruct-sc2-concepts
def _getAllSpacesInConstraint(spaceConstraintData): """ Return a combined list of native and dynamic spaces for a constraint. Args: spaceConstraintData (dict): The loaded space constraint data from the space constraint node Returns: A list of dict representing spaces applied to a constraint. See `setupSpaceConstraint` for more detail. """ return spaceConstraintData['spaces'] + spaceConstraintData['dynamicSpaces']
bigcode/self-oss-instruct-sc2-concepts
def log_sum_exp(x): """calculate log(sum(exp(x))) = max(x) + log(sum(exp(x - max(x)))) """ max_score = x.max(-1)[0] return max_score + (x - max_score.unsqueeze(-1)).exp().sum(-1).log()
bigcode/self-oss-instruct-sc2-concepts
def run_command(command, args, cwd): """Runs a command with the given context. Args: command: ManageCommand to run. args: Arguments, with the app and command name stripped. cwd: Current working directory. Returns: 0 if the command succeeded and non-zero otherwise. Raises: ValueError: The command could not be found or was not specified. """ parser = command.create_argument_parser() parsed_args = parser.parse_args(args) return command.execute(parsed_args, cwd)
bigcode/self-oss-instruct-sc2-concepts
def divisible(a, b): """Returns `True` if ``a`` is divisible by ``b`` and `False` otherwise.""" return not a % b
bigcode/self-oss-instruct-sc2-concepts
def BitSet(x, n): """Return whether nth bit of x was set""" return bool(x[0] & (1 << n))
bigcode/self-oss-instruct-sc2-concepts
def get_corresponding_letter(index, sentence): """ Get the letter corresponding to the index in the given sentence :param index: the wanted index. :param sentence: the reference sentence. :return: the corresponding letter if found, 'None' otherwise. """ if index < len(sentence.letters): return sentence.letters[index] else: return None
bigcode/self-oss-instruct-sc2-concepts
import torch def gpu_count(gpus: int) -> int: """ Find the number of GPUs to use. By default, the application attempts to use all GPUs available in the system but users can specify a different number of GPUs if desired. If the system doesn't have any GPUs available, it will default to the CPUs. If the user specifies a specific number of GPUs, it needs to be verified that it is a positive integer and less than or equal to the total number of GPUs available in the system. Parameters ---------- gpus : int An ``int`` of the number of GPUs the user requested via the CLI, defaulting to 0. Returns ------- int Returns an ``int`` of the number of GPUs to use in the system. """ count = torch.cuda.device_count() if not torch.cuda.is_available(): print('No GPUs available. Running on CPUs instead.') return 0 if gpus is None: return count if gpus <= 0: print('No GPUs requested. Running on CPUs instead.') return 0 if gpus <= count: return gpus if gpus > count: print(f'Requested {gpus} GPUs but only found {count}') print(f'Using {count} GPUs instead') return count return 0
bigcode/self-oss-instruct-sc2-concepts
def loc2Dict(loc): """ Convert a loc into a dictionary, for the consideration of maintainability. Parameters ---------- loc: list A location, in format of [lat, lon] or [lat, lon, alt] Return ------ dictionary A dictionary of location """ if (len(loc) == 2): locDict = { 'lat': loc[0], 'lon': loc[1], 'alt': 0 } elif (len(loc) == 3): locDict = { 'lat': loc[0], 'lon': loc[1], 'alt': loc[2] } else: return return locDict
bigcode/self-oss-instruct-sc2-concepts
from typing import List def unique(object: List): """Remove duplicates from a list while preserving the order""" # list(set(object)) does the unique job, but it sets to random order u = [] for item in object: if item not in u: u.append(item) return u
bigcode/self-oss-instruct-sc2-concepts
def _create_board(size=4): """Generating the empty starting game board This board can be of any (nxn) size. 0 = a space with no tile """ return [[0 for j in range(size)] for i in range(size)]
bigcode/self-oss-instruct-sc2-concepts
def apc(x): """Perform average product correct, used for contact prediction. Args: x: np array. Returns: apc np array """ a1 = x.sum(-1, keepdims=True) a2 = x.sum(-2, keepdims=True) a12 = x.sum((-1, -2), keepdims=True) avg = a1 * a2 avg.div_(a12) # in-place to reduce memory normalized = x - avg return normalized
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import Dict def key(product_: Tuple[str, Dict]) -> Tuple[float, float]: """Lemma 1 sorting key for the fixed attention problem. An optimal ranking for the fixed attention problem is sorted by this key function. Parameters ---------- product_: tuple[str, dict] A tuple describing a product, the first element is its name or id, the second element is a dictionary describing its revenue if purchased and its probability of being purchased. Returns ------- tuple: A tuple with the revenue of the product as first element and its probability as the second element. """ return product_[1]["revenue"], product_[1]["probability"]
bigcode/self-oss-instruct-sc2-concepts
def unquote(s): """remove quotation chars on both side. >>> unquote('"abc"') 'abc' >>> unquote("'abc'") 'abc' >>> unquote('abc') 'abc' """ if 2 <= len(s) and s[0] + s[-1] in ['""', "''"]: return s[1:-1] else: return s
bigcode/self-oss-instruct-sc2-concepts
def read_dict(filename, div='='): """Read file into dict. A file containing: foo = bar baz = bog results in a dict { 'foo': 'bar', 'baz': 'bog' } Arguments: filename (str): path to file div (str): deviders between dict keys and values Returns: (dict) generated dictionary """ d = {} with open(filename, 'r') as f: for line in f: key, val = line.split(div) d[key.strip()] = val.strip() return d
bigcode/self-oss-instruct-sc2-concepts
import torch def numerically_stable_exp(tensor, dim=-1): """ Removes largest value and exponentiates, returning both. :param tensor: the input tensor :param dim: which is the dim to find max over :returns: exp(tensor - max), max :rtype: (torch.Tensor, torch.Tensor) """ max_value, _ = torch.max(tensor, dim=dim) return torch.exp(tensor - max_value.unsqueeze(dim)), max_value
bigcode/self-oss-instruct-sc2-concepts
def median_manual(l): """ l: List of integers return median of list l """ n = len(l) l = sorted(l) if n%2 == 1: return l[int((n-1)/2)] return (l[int(n/2)-1] + l[int(n/2)]) / 2
bigcode/self-oss-instruct-sc2-concepts
def sink_for_card(card, pulse): """Return first sink that uses the given card otherwise return None""" sinks = pulse.sink_list() for sink in sinks: if sink.card == card.index: return sink return None
bigcode/self-oss-instruct-sc2-concepts
def prepend(value, text): """ Prepends text if value is not None. """ if value is not None: value = str(value).strip() if value: return "{}{}".format(text, value) return ""
bigcode/self-oss-instruct-sc2-concepts
import random def random_from_alphabet(size, alphabet): """ Takes *size* random elements from provided alphabet :param size: :param alphabet: """ return list(random.choice(alphabet) for _ in range(size))
bigcode/self-oss-instruct-sc2-concepts
def _str_to_list(val): """If val is str, return list with single entry, else return as-is.""" l = [] if val.__class__ == str: l.append(val) return l else: return val
bigcode/self-oss-instruct-sc2-concepts
def integer_squareroot(n: int) -> int: """ Return the largest integer ``x`` such that ``x**2 <= n``. """ x = n y = (x + 1) // 2 while y < x: x = y y = (x + n // x) // 2 return x
bigcode/self-oss-instruct-sc2-concepts
def is_threshold_sequence(degree_sequence): """ Returns True if the sequence is a threshold degree seqeunce. Uses the property that a threshold graph must be constructed by adding either dominating or isolated nodes. Thus, it can be deconstructed iteratively by removing a node of degree zero or a node that connects to the remaining nodes. If this deconstruction failes then the sequence is not a threshold sequence. """ ds=degree_sequence[:] # get a copy so we don't destroy original ds.sort() while ds: if ds[0]==0: # if isolated node ds.pop(0) # remove it continue if ds[-1]!=len(ds)-1: # is the largest degree node dominating? return False # no, not a threshold degree sequence ds.pop() # yes, largest is the dominating node ds=[ d-1 for d in ds ] # remove it and decrement all degrees return True
bigcode/self-oss-instruct-sc2-concepts
def crop_to_image_boundary(image, boxes, image_boundary): """Crop transformed image to original image boundaries (e.g., remove padding). Parameters ---------- image : np.ndarray Numpy integer array of shape (H, W, C). boxes : np.ndarray Numpy array of shape (N, 4), where N is the number of boxes. image_boundary : np.ndarray or None Numpy array of shape (4,). If None, no cropping will be performed. """ if image_boundary is None: return image, boxes height, width = image.shape[:2] xmin, ymin, xmax, ymax = image_boundary.astype("int") xmin = max(xmin, 0) ymin = max(ymin, 0) xmax = min(xmax, width) ymax = min(ymax, height) cropped_image = image[ymin:ymax, xmin:xmax] cropped_boxes = [] for box in boxes: cropped_boxes.append(box - [xmin, ymin, xmin, ymin]) return cropped_image, cropped_boxes
bigcode/self-oss-instruct-sc2-concepts
def following_mention_ids(api, ids): """ This function has the mention_ids and make sure if the account follow them if not ... don't make sense to unfollow them returns the ids list only with the ones that the account follow """ ids = list(set(ids)) following_mention_ids = [] for idt in ids: if api.show_friendship(source_id=idt, target_id=api.me().id)[0].followed_by: following_mention_ids.append(idt) return following_mention_ids
bigcode/self-oss-instruct-sc2-concepts
def Trim(t, p=0.01): """Trims the largest and smallest elements of t. Args: t: sequence of numbers p: fraction of values to trim off each end Returns: sequence of values """ n = int(p * len(t)) t = sorted(t)[n:-n] return t
bigcode/self-oss-instruct-sc2-concepts
def show_volume(client, resource_group_name, name): """Show details of a volume. """ return client.get(resource_group_name, name)
bigcode/self-oss-instruct-sc2-concepts
import torch def get_matrix_kernel(A, eps=1e-10): """ Compute an orthonormal basis of the kernel (x_1, x_2, ...) A x_i = 0 scalar_product(x_i, x_j) = delta_ij :param A: matrix :return: matrix where each row is a basis vector of the kernel of A """ _u, s, v = torch.svd(A) # A = u @ torch.diag(s) @ v.t() kernel = v.t()[s < eps] return kernel
bigcode/self-oss-instruct-sc2-concepts
def get_common_tables(old_conn, new_conn): """ a comparison function which checks for tables with the same name :param old_conn: the connection to the old db new_conn: the connection to the new db :return: A list of table names """ list_table_query = "select name from sqlite_master where type = 'table'" old_conn.row_factory = lambda cursor, row: row[0] new_conn.row_factory = lambda cursor, row: row[0] old_cursor = old_conn.cursor() new_cursor = new_conn.cursor() old_tables = old_cursor.execute(list_table_query).fetchall() new_tables = new_cursor.execute(list_table_query).fetchall() # no need for any fancy optimized algorithms since this is always O(n). list has no repeated items return [value for value in new_tables if value in old_tables]
bigcode/self-oss-instruct-sc2-concepts
def get_iteration_prefix(i, total): """ Return a String prefix for itarative task phases. :param i int current step. :param total int total steps. """ return " [{0}/{1}]".format(i, total)
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def cp_path_to_dir(cp_path, tag): """Convert a checkpoint path to a directory with `tag` inserted. If `cp_path` is already a directory, return it unchanged. """ if not isinstance(cp_path, Path): cp_path = Path(cp_path) if cp_path.is_dir(): return cp_path path_sans_extension = cp_path.parent / cp_path.stem cp_dir = Path(f'{path_sans_extension}-{tag}-cp') return cp_dir
bigcode/self-oss-instruct-sc2-concepts
def join_extract(arr, attr_str, join_str): """Join the ``attr_str`` of the element of the ``arr`` with ``join_str``.""" return join_str.join([str(getattr(item, attr_str)) for item in arr])
bigcode/self-oss-instruct-sc2-concepts
def _CreateImage(media_service, opener, url): """Creates an image and uploads it to the server. Args: media_service: a ZeepServiceProxy instance for AdWords's MediaService. opener: an OpenerDirector instance. url: a str URL used to load image data. Returns: The image that was successfully uploaded. """ # Note: The utf-8 decode is for 2to3 Python 3 compatibility. image_data = opener.open(url).read().decode('utf-8') image = { 'type': 'IMAGE', 'data': image_data, 'xsi_type': 'Image' } return media_service.upload(image)[0]
bigcode/self-oss-instruct-sc2-concepts
def get_ann_energy_demands(city, print_out=False): """ Returns annual energy demands of city in kWh (space heating, electrical, hot water) Parameters ---------- city : object City object of pycity_calc print_out : bool, optional Print out results (default: False) Returns ------- res_tuple : Tuple (of floats) 3d tuple with space heating, electrical and hot water energy demands in kWh (ann_space_heat, ann_el_dem, ann_dhw_dem) """ ann_space_heat = round(city.get_annual_space_heating_demand(), 2) ann_el_dem = round(city.get_annual_el_demand(), 2) ann_dhw_dem = round(city.get_annual_dhw_demand(), 2) if print_out: # pragma: no cover print('Annual net thermal space heating demand in kWh: ') print(ann_space_heat) print() print('Annual electrical demand in kWh: ') print(ann_el_dem) print() print('Annual hot water energy demand in kWh: ') print(ann_dhw_dem) print() print('Percentage of space heat demand on total thermal demand in %:') print((100 * ann_space_heat) / (ann_space_heat + ann_dhw_dem)) print('Percentage of hot water demand on total thermal demand in %:') print((100 * ann_dhw_dem) / (ann_space_heat + ann_dhw_dem)) return (ann_space_heat, ann_el_dem, ann_dhw_dem)
bigcode/self-oss-instruct-sc2-concepts
def complex_abs_sq(data): """ Compute the squared absolute value of a complex tensor """ assert data.size(-1) == 2 return (data ** 2).sum(dim=-1)
bigcode/self-oss-instruct-sc2-concepts
def format_cpf(value): """ This function returns the Brazilian CPF with the normal format. :param value is a string with the number of Brazilian CPF like 12345678911 :return: Return a sting with teh number in the normal format like 123.456.789-11 """ return f'{value[:3]}.{value[3:6]}.{value[6:9]}-{value[9:]}'
bigcode/self-oss-instruct-sc2-concepts
async def mock_async_call(): """ mocks a generic async function """ return True
bigcode/self-oss-instruct-sc2-concepts
def dec_indent(indent, count=1): """ decrease indent, e.g. if indent = " ", and count = 1, return " ", if indent = " ", and count = 2, return "", """ if indent.endswith('\t'): indent = indent[:len(indent) - 1 * count] elif indent.endswith(' '): indent = indent[:len(indent) - 4 * count] return indent
bigcode/self-oss-instruct-sc2-concepts
import yaml from textwrap import dedent def create_cron_resource(name="cron", minute=5, image="cron-image"): """Create a CronTab resource from parameters. Args: name (str): name of the resource minute (int): time set for the minutes in the CRON specifications. image (str): image used for the CRON specifications. Returns: dict[str, object]: the generated CronTab resource. """ return next( yaml.safe_load_all( dedent( f""" --- apiVersion: stable.example.com/v1 kind: CronTab metadata: name: {name} namespace: default spec: cronSpec: "* * * * {minute}" image: {image} """ ) ) )
bigcode/self-oss-instruct-sc2-concepts
def freeze_one_half(basis): """ Split the structure into two parts along the z-axis and then freeze the position of the atoms of the upper part (z>0.5) by setting selective dynamics to False. Args: basis (pyiron_atomistics.structure.atoms.Atoms): Atomistic structure object Returns: pyiron_atomistics.structure.atoms.Atoms: Atomistic structure object with half of the atoms fixed """ basis.add_tag(selective_dynamics=None) _, _, z = basis.scaled_pos_xyz() for selector, ind in zip(z < 0.5, range(len(basis))): if selector: basis.selective_dynamics[ind] = [True, True, True] else: basis.selective_dynamics[ind] = [False, False, False] return basis
bigcode/self-oss-instruct-sc2-concepts
def format_args(args): """Formats the args with escaped " """ comma = "," if args else "" return comma + ",".join(['\\\"' + a + '\\\"' for a in args])
bigcode/self-oss-instruct-sc2-concepts
def rescale(ndarray, min, max): """Rescale values of ndarray linearly so min of ndarray is min, max is max Parameters ---------- ndarray: numpy nd array min: int max: int Returns ------- numpy ndarray """ old_max = ndarray.max() old_min = ndarray.min() old_range = old_max - old_min old_dtype = ndarray.dtype new_range = max - min range_scale = new_range / old_range range_offset = min - old_min ndarray = ndarray.astype(float) ndarray -= old_min # translate to make based on 0 ndarray *= range_scale # scale to make range same size ndarray += min # tranlate back to make old min fall on (new) min return ndarray.astype(old_dtype)
bigcode/self-oss-instruct-sc2-concepts
def parse_so_terms(so_file): """Retrieve all available Sequence Ontology terms from the file. """ so_terms = [] with open(so_file) as in_handle: for line in in_handle: if line.find('name:') == 0: name = line[5:].strip() so_terms.append(name) return so_terms
bigcode/self-oss-instruct-sc2-concepts
def avgTeq(L, a, e=0., albedo=0., emissivity=1., beta=1.): """compute the time-averaged equilibrium temperature as in Mendez+2017. This uses eqn 16 in Méndez A, Rivera-Valentín EG (2017) Astrophys J 837:L1. https://doi.org/10.3847/2041-8213/aa5f13" Parameters ---------- L : float stellar luminosity [L_sol] a : float semi-major axis [au] e : float eccentricity albedo : float planetary albedo emissivity : float broadband thermal emissivity (usually ~ 1) beta : float fraction planet surface that re-radiates absorbed flux Returns ------- Teq : float time-averaged equilibrium temperature """ T0 = 278.5 # Teq of Earth for zero albedo [K] avgTeq = T0*(((1 - albedo)*L)/(beta*emissivity*a**2))**(1/4)*(1 - e**2/16 - (15/1024)*e**4) return avgTeq
bigcode/self-oss-instruct-sc2-concepts
def is_member(user, groups): """ Test if a user belongs to any of the groups provided. This function is meant to be used by the user_passes_test decorator to control access to views. Parameters ---------- user : django.contrib.auth.models.User The user which we are trying to identify that belongs to a certain group. groups : list of str A list of the groups we are checking if the user belongs to. Returns --------- bool True if the user belongs to any of the groups. False otherwise """ return any(map(lambda g: user.groups.filter(name=g).exists(), groups))
bigcode/self-oss-instruct-sc2-concepts
def _UpdateFertileSlotsShape(unused_op): """Shape function for UpdateFertileSlots Op.""" return [[None, 2], [None], [None]]
bigcode/self-oss-instruct-sc2-concepts
def str2bytes(data): """ Converts string to bytes. >>> str2bytes("Pwning") b'Pwning' """ return bytes(data, encoding="utf-8")
bigcode/self-oss-instruct-sc2-concepts
import math def normalize(val, min_val, max_val): """ Normalize the popularity value with log transformation. """ new_val = val - min_val + 1 return math.log(new_val)
bigcode/self-oss-instruct-sc2-concepts
def black_is_not_installed(*args, **kwargs): """Check black is not installed.""" return not args[0] == "black"
bigcode/self-oss-instruct-sc2-concepts
def get_trend(row, window_size, center=True): """ Returns trend component of a time series :param row: pandas series containing the time series to extract seasonality from :param window_size: length of moving window :param center: :return: """ trend = row.rolling(window_size, center=center).mean() return trend
bigcode/self-oss-instruct-sc2-concepts
def _get_prefixes(response): """ return lists of strings that are prefixes from a client.list_objects() response """ prefixes = [] if 'CommonPrefixes' in response: prefix_list = response['CommonPrefixes'] prefixes = [prefix['Prefix'] for prefix in prefix_list] return prefixes
bigcode/self-oss-instruct-sc2-concepts
def interface_to_ip(interface): """ Gets the IPv4 address from a `net_if_addrs` interface record. The record is passed as a `snic` `namedtuple`. This function locates the IPv4 one and returns it. """ for record in interface: if record.family == 2: # AF_INET return record.address return None
bigcode/self-oss-instruct-sc2-concepts
def filter_dict_keys(org_dict, keep_keys): """Helper function to keep only certain keys from config. Pass in a dictionary and list of keys you wish to keep Any keys not in the list will be removed in the returned dictionary""" newDict = dict() # Iterate over all the items in dictionary and filter items which has even keys for (key, value) in org_dict.items(): # Check if key is even then add pair to new dictionary if key in keep_keys: newDict[key] = value return newDict
bigcode/self-oss-instruct-sc2-concepts
from typing import Set import click def get_states_as_set(state_list: str) -> Set: """Helper method to parse the state string. Args: state_list: comma separated string with codes and states Returns: Set with valid state names in upper case """ codes_to_states = { "BF": "BOOT_FAIL", "CA": "CANCELLED", "CD": "COMPLETED", "DL": "DEADLINE", "F": "FAILED", "NF": "NODE_FAIL", "OOM": "OUT_OF_MEMORY", "PD": "PENDING", "PR": "PREEMPTED", "R": "RUNNING", "RQ": "REQUEUED", "RS": "RESIZING", "RV": "REVOKED", "S": "SUSPENDED", "TO": "TIMEOUT", } possible_states = set(codes_to_states.values()) states = { codes_to_states.get(state, state) for state in state_list.upper().split(",") } for state in states: if state not in possible_states: click.secho(f"Unknown state {state}", fg="yellow", err=True) return states.intersection(possible_states)
bigcode/self-oss-instruct-sc2-concepts
def transform_globs_into_regexes(globs): """Turns glob patterns into regular expressions.""" return [glob.replace("*", ".*").replace("?", ".") for glob in globs]
bigcode/self-oss-instruct-sc2-concepts
def adjust_convention(img, convention): """ Inverts (could) the image according to the given convention Args: img (np.ndarray): Image numpy array convention (int): -1 or 1 depending on macros.IMAGE_CONVENTION Returns: np.ndarray: Inverted or non inverted (vertically) image. """ img = img[::-convention] return img
bigcode/self-oss-instruct-sc2-concepts
import textwrap async def snippet_to_embed(file_contents, file_path, start_line, end_line): """Given file contents, file path, start line and end line creates a code block""" split_file_contents = file_contents.splitlines() if start_line is None: start_line, end_line = 1, len(split_file_contents) elif end_line is None: start_line = end_line = int(start_line) else: start_line = int(start_line) end_line = int(end_line) if start_line > end_line: start_line, end_line = end_line, start_line if start_line > len(split_file_contents) or end_line < 1: return "" start_line = max(1, start_line) end_line = min(len(split_file_contents), end_line) required = "\n".join(split_file_contents[start_line - 1:end_line]) required = textwrap.dedent(required).rstrip().replace("`", "`\u200b") language = file_path.split("/")[-1].split(".")[-1] if not language.replace("-", "").replace("+", "").replace("_", "").isalnum(): language = "" if len(required) != 0: return f"```{language}\n{required}```\n" return "``` ```\n"
bigcode/self-oss-instruct-sc2-concepts
def stringify_keys(d): # taken from https://stackoverflow.com/a/51051641 """Convert a dict's keys to strings if they are not.""" keys = list(d.keys()) for key in keys: # check inner dict if isinstance(d[key], dict): value = stringify_keys(d[key]) else: value = d[key] # convert nonstring to string if needed if not isinstance(key, str): try: d[str(key)] = value except Exception: try: d[repr(key)] = value except Exception: raise # delete old key d.pop(key, None) return d
bigcode/self-oss-instruct-sc2-concepts
def make_average(fn, num_samples=100): """Return a function that returns the average_value of FN when called. To implement this function, you will have to use *args syntax, a new Python feature introduced in this project. See the project description. >>> dice = make_test_dice(3, 1, 5, 6) >>> avg_dice = make_average(dice, 100) >>> avg_dice() 3.75 >>> avg_score = make_average(roll_dice, 100) >>> avg_score(2, dice) 6.0 In this last example, two different turn scenarios are averaged. - In the first, the player rolls a 3 then a 1, receiving a score of 1. - In the other, the player rolls a 5 and 6, scoring 11. Thus, the average value is 6.0. """ def avg_fn(*args): i = 0 for x in range (0,num_samples): i += fn(*args) return i/num_samples return avg_fn
bigcode/self-oss-instruct-sc2-concepts
def format_time(total_seconds, hours_fmt=False, precise=False, hours_pad=True): """ Convert total_seconds float into a string of the form "02:33:44". total_seconds amounts greater than a day will still use hours notation. Output is either in minutes "00:00" formatting or hours "00:00:00" formatting. Not possible to only produce seconds or days+, etc. total_seconds: float hours_fmt: True = Force hours output. False = Force minutes output. precise: Use floating point value for seconds. hours_pad: Pad hours field to 2 digits. """ if precise: # .0f is to suppress float output if precise=True. # if precise=True, the .format() calls below will be passed floats # from divmod. # :02.0f = pad to 2 digits, no decimal places. # :06.3f = pad to 2 digits, three decimal places (6 chars total) fmt_str_mins = '{:02.0f}:{:06.3f}' fmt_str_hours = '{:02.0f}:{:02.0f}:{:06.3f}' else: fmt_str_mins = '{:02}:{:02}' if hours_pad: fmt_str_hours = '{:02}:{:02}:{:02}' else: fmt_str_hours = '{}:{:02}:{:02}' total_sec = total_seconds if precise else int(total_seconds) total_mins, secs = divmod(total_sec, 60) ret = '' if hours_fmt: hours, mins = divmod(int(total_mins), 60) ret = fmt_str_hours.format(hours, mins, secs) else: ret = fmt_str_mins.format(total_mins, secs) return ret
bigcode/self-oss-instruct-sc2-concepts
def get_channels_number(*, mode: str) -> int: """ This function return the numbers of channels given a color mode. Parameters ---------- mode: str color mode. Returns ------- out: int number of channels associated with the color mode. """ if mode == "YCbCr": return 3 return len(mode)
bigcode/self-oss-instruct-sc2-concepts
def _merge_ranges(ranges): """ From a list of ranges (i.e.: list of tuples (start_idx, end_idx) Produce a list of non-overlapping ranges, merging those which overlap. :param ranges: list of tuples (start_idx, end_idx) :return: list of tuples (start_idx, end_idx) """ if ranges == []: return [] ranges = sorted(ranges) merged_ranges = [] cur_range = ranges[0] for r in ranges[1:]: if r[0] >= cur_range[0] and r[0] < cur_range[1]: cur_range = (cur_range[0], max(r[1], cur_range[1])) else: merged_ranges.append(cur_range) cur_range = r merged_ranges.append(cur_range) return merged_ranges
bigcode/self-oss-instruct-sc2-concepts
def find_when_entered_basement(text): """Find position in text when santa enters basement first time.""" cur_floor = 0 for position, floor_change in enumerate(text, start=1): cur_floor += 1 if floor_change == '(' else -1 if cur_floor < 0: return position return -1
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import Tuple from typing import Dict from typing import List def adjacency_list(edges: Iterable[Tuple[str, str]]) -> Dict[str, List[str]]: """ Convert a sequence of undirected edge pairs into an adjacency "list". """ adj = {} for e1, e2 in edges: if e1 not in adj: adj[e1] = [] if e2 not in adj: adj[e2] = [] adj[e1].append(e2) adj[e2].append(e1) return adj
bigcode/self-oss-instruct-sc2-concepts
import string import random def randStr(chars = string.ascii_uppercase + string.digits + string.ascii_lowercase, N=42): """Generate a random string of len 42 to spoof a reset token""" return ''.join(random.choice(chars) for _ in range(N))
bigcode/self-oss-instruct-sc2-concepts
def _merge(*parts): """ Utility function to merge various strings together with no breaks """ return ''.join(parts)
bigcode/self-oss-instruct-sc2-concepts
def parse_sensors(configuration): """ Bake the sensors array to a dict where the telldus id is the key for easier parsing later on. """ result = {} for sensor in configuration["my_sensors"]: result[sensor["id"]] = sensor return result
bigcode/self-oss-instruct-sc2-concepts
def get_egress_lossless_buffer_size(host_ans): """ Get egress lossless buffer size of a switch Args: host_ans: Ansible host instance of the device Returns: total switch buffer size in byte (int) """ config_facts = host_ans.config_facts(host=host_ans.hostname, source="running")['ansible_facts'] if "BUFFER_POOL" not in config_facts.keys(): return None buffer_pools = config_facts['BUFFER_POOL'] profile_name = 'egress_lossless_pool' if profile_name not in buffer_pools.keys(): return None egress_lossless_pool = buffer_pools[profile_name] return int(egress_lossless_pool['size'])
bigcode/self-oss-instruct-sc2-concepts
def format_nums(number, decimals): """ rounds to a number of decimals and if possible makes a integer from float :param number: input number :param decimals: decimals to round to :return: integer or float """ if round(float(number), decimals).is_integer(): return int(f"{number:.0f}") return float(f"{number:.{decimals}f}")
bigcode/self-oss-instruct-sc2-concepts
def _totuple(a): """ Converts a numpy array into nested tuples, so that each row of the array is a different tuple. E.g. a = [ [0 1 2 3] [4 5 6 7] ] out = ((0, 1, 2, 3), (4, 5, 6, 7)) """ try: return tuple(_totuple(i) for i in a) except TypeError: return a
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def some_dir(tmp_path) -> Path: """Folder with some data, representing a given state""" base_dir = tmp_path / "original" base_dir.mkdir() (base_dir / "empty").mkdir() (base_dir / "d1").mkdir() (base_dir / "d1" / "f1").write_text("o" * 100) (base_dir / "d1" / "f2").write_text("o" * 100) (base_dir / "d1" / "d1_1" / "d1_2").mkdir(parents=True, exist_ok=True) (base_dir / "d1" / "d1_1" / "f3").touch() (base_dir / "d1" / "d1_1" / "d1_2" / "f4").touch() (base_dir / "d1" / "d1_1" / "d1_1_1").mkdir(parents=True, exist_ok=True) (base_dir / "d1" / "d1_1" / "d1_1_1" / "f6").touch() return base_dir
bigcode/self-oss-instruct-sc2-concepts
def DEFAULT_REPORT_SCRUBBER(raw): """Default report scrubber, removes breakdown and properties.""" try: del raw['breakdown'] del raw['properties'] except KeyError: pass return raw
bigcode/self-oss-instruct-sc2-concepts
def list_of(cls): """ Returns a function that checks that each element in a list is of a specific type. """ return lambda l: isinstance(l, list) and all(isinstance(x, cls) for x in l)
bigcode/self-oss-instruct-sc2-concepts
def _task_info(clazz): """ from a provided class instance extract task metadata. This will error if any of the expected fields of the task are missing. :param clazz: class object you need metadata for :return: a metadata dictionary """ params = [] for e in clazz.parameters: params += [{ "name": e.name, "display_name": e.display_name, "type": e.d_type, "description": e.description, "valid_values": e.valid }] return { "name": clazz.name, "display_name": clazz.display_name, "description": clazz.description, "args": params, "img_url": clazz.img_url, "info_url": clazz.info_url, }
bigcode/self-oss-instruct-sc2-concepts
import hashlib def sha1sum(filename): """return the sha1 hash of a file""" with open(filename, mode='rb') as f: d = hashlib.sha1() while True: buf = f.read(8192) if not buf: break d.update(buf) return d.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def get_tokens_from_node(node, result=None): """Return the list of Tokens in the tree starting at node.""" if result is None: result = [] for dtr in node.dtrs: if dtr.isToken(): result.append(dtr) get_tokens_from_node(dtr, result) return result
bigcode/self-oss-instruct-sc2-concepts
import re def parse_string_to_int_tuples(tuples): """ parse a string to tuples, while the string is: (x, x, x, x), (x, x)... """ tuple_list = re.findall('[(](.*?)[)]', tuples) ret = [] for i in tuple_list: int_shape = [] shape = i.strip().split(',') for j in shape: if j: int_shape.append(int(j)) ret.append(tuple(int_shape)) return ret
bigcode/self-oss-instruct-sc2-concepts
import requests from bs4 import BeautifulSoup def get_url_from_character_page(url_IDMB,THUMBNAIL_CLASS="titlecharacters-image-grid__thumbnail-link"): """ Gets url of image viewer of a serie pictures on IMDB (e.g. https://www.imdb.com/title/tt0108778/mediaviewer/rm3406852864) Given the url of a character of that serie (e.g. 'https://www.imdb.com/title/tt0108778/characters/nm0000098') Parameters: ----------- url_IDMB: url of a character of the serie we're interested in. THUMBNAIL_CLASS: IMDB html class which containes the link to the series images url. Returns: -------- media_viewer_url: url of image viewer of a serie pictures on IMDB """ page_IMDB = requests.get(url_IDMB).text soup = BeautifulSoup(page_IMDB, 'lxml') media_viewer_url=soup.findAll("a", {"class":THUMBNAIL_CLASS})[0]["href"] return media_viewer_url
bigcode/self-oss-instruct-sc2-concepts
def get_orders_list(orders_dict): """Returns orders list from orders dict""" return orders_dict.get('orders')
bigcode/self-oss-instruct-sc2-concepts