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: ...
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.tzinf...
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 ...
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_disp...
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") ...
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 va...
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)...
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 - currentRo...
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(",") retu...
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']] = {'ope...
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). ...
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 * sig...
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 = {} ...
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 applie...
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 ...
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): ...
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. I...
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...
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 red...
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[st...
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 Ret...
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, _ = tor...
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...
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 th...
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 = [] ...
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 ...
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_ma...
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 ...
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 upload...
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) Return...
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]...
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 = in...
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 ...
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: ...
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 =...
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...
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 stell...
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 t...
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=cent...
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.add...
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 it...
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": "B...
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. ...
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...
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: va...
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_...
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. ...
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": ...
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 [] r...
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...
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, ...
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}...
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")....
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: param...
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_...
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 o...
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