seed
stringlengths
1
14k
source
stringclasses
2 values
import hashlib def key_sha1(*args): """This method creates an SHA-1 from the input parameters, used for caching filename""" return hashlib.sha1("".join(str(args)).encode("utf-8")).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def add_to_dict(d, key, base): """Function to add key to dictionary, either add base or start with base""" if key in d: d[key] += base else: d[key] = base return d
bigcode/self-oss-instruct-sc2-concepts
def make_columns_grammar(columns): """Return a lark rule that looks like // These are my raw columns str_0: "[" + /username/i + "]" | /username/i str_1: "[" + /department/i + "]" | /department/i str_2: "[" + /testid/i + "]" | /testid/i """ items = [] for k in sorted(columns.keys()): ...
bigcode/self-oss-instruct-sc2-concepts
def add_model_params_tree(info_dict): """Adds model parameters to `info_dict` for tree models. Only model-related parameter information will be added in this function. A series of these functions are used in a flow to get all information needed in tree model summary. The flow is `~greykite.algo.com...
bigcode/self-oss-instruct-sc2-concepts
import string def buildGoodSet(goodChars=string.printable, badChar='?'): """Build a translation table that turns all characters not in goodChars to badChar""" allChars = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+...
bigcode/self-oss-instruct-sc2-concepts
def get_newsentry_meta_description(newsentry): """Returns the meta description for the given entry.""" if newsentry.meta_description: return newsentry.meta_description # If there is no seo addon found, take the info from the placeholders text = newsentry.get_description() if len(text) > 16...
bigcode/self-oss-instruct-sc2-concepts
def CleanFCSstring(strFCS): """ If string can be converted to int, then returns clean string with only the int. othervise returns '-1'.""" try: return str(int(strFCS)) except: return "-1"
bigcode/self-oss-instruct-sc2-concepts
from typing import Any import ast def _is_lexical_match(matched: Any) -> bool: """Returns whether the match can be a lexical one. Its not well documented what ast objects return token information and which ones don't, and there are known instances of the token information being wrong in certain cases. Arg...
bigcode/self-oss-instruct-sc2-concepts
def dest_times(t): """Given t1 * t2, return (t1, t2).""" assert t.is_times(), "dest_times" return (t.arg1, t.arg)
bigcode/self-oss-instruct-sc2-concepts
import inspect import warnings def deprecated(func, solution): """ Mark a parser or combiner as deprecated, and give a message of how to fix this. This will emit a warning in the logs when the function is used. When combined with modifications to conftest, this causes deprecations to become fatal...
bigcode/self-oss-instruct-sc2-concepts
import torch def image_distance(x: torch.Tensor, y: torch.Tensor, order=2) -> torch.Tensor: """Returns the distance between two batches of images Args: x (torch.Tensor): First batch of images y (torch.Tensor): Second batch of images order (int, optional): Order of the norm. Defaults t...
bigcode/self-oss-instruct-sc2-concepts
def escape_nmap_filename(filename): """Escape '%' characters so they are not interpreted as strftime format specifiers, which are not supported by Zenmap.""" return filename.replace("%", "%%")
bigcode/self-oss-instruct-sc2-concepts
def shift_and_zero(buf): """Shift 1 -> 0, and zero out 1.""" buf[0, :] = buf[1, :] buf[1, :] = 0.0 return buf
bigcode/self-oss-instruct-sc2-concepts
def to_aws_tags(tags): """ Convert tags from dictionary to a format expected by AWS: [{'Key': key, 'Value': value}] :param tags :return: """ return [{'Key': k, 'Value': v} for k, v in tags.items()]
bigcode/self-oss-instruct-sc2-concepts
def duplicate_count(text): """ Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric dig...
bigcode/self-oss-instruct-sc2-concepts
import time def epoch2iso(timestamp): """Returns the ISO representaton of a UNIX timestamp (epoch). >>> epoch2iso(1620459129) '2021-05-08 09:32:09' """ timestamp = float(timestamp) return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
bigcode/self-oss-instruct-sc2-concepts
def convert_to_xs_and_ys(waypoint, lon_min, lon_max, lat_min, lat_max, w, h): """Convert from a list of positions to their x/y coordinates in the image.""" xs = [] ys = [] for step in waypoint: xs.append((step["lon"] - lon_min) / (lon_max - lon_min) * w) ys.append((lat_max - step["lat"...
bigcode/self-oss-instruct-sc2-concepts
import binascii def b64encode(s, altchars=None): """Encode a byte string using Base64. s is the byte string to encode. Optional altchars must be a byte string of length 2 which specifies an alternative alphabet for the '+' and '/' characters. This allows an application to e.g. generate url or f...
bigcode/self-oss-instruct-sc2-concepts
def ensure_str(s): """ Simple conversion of the value `s` to a `str`, that is, a byte string on Python 2 and a unicode string on Python 3. Input is expected to be a byte-string or unicode string in both Py2 or Py3. """ if not isinstance(s, str): return s.decode('utf-8') return s
bigcode/self-oss-instruct-sc2-concepts
def get_cli_input_year() -> str: """Get CLI input for the year of the car""" car_year = input("Enter the year of the car: ") return car_year
bigcode/self-oss-instruct-sc2-concepts
def argify(argname, argval): """ :param argname: String naming a parameter for a script called from terminal :param argval: Object to assign in string form as the value of the argument :return: String, a parameter assignment for a script called from terminal """ return "--{}={}".format(argname, ...
bigcode/self-oss-instruct-sc2-concepts
def human_size(bytes, units=None): """Returns a human readable string representation of bytes""" if not units: units = [" bytes", "KB", "MB", "GB", "TB", "PB", "EB"] return str(bytes) + units[0] if bytes < 1024 else human_size(bytes >> 10, units[1:])
bigcode/self-oss-instruct-sc2-concepts
def normalizeHomogenious(points): """ Normalize a collection of points in homogeneous coordinates so that last row = 1. """ for row in points: row /= points[-1] return points
bigcode/self-oss-instruct-sc2-concepts
def count_parameters(net, as_int=False): """Returns total number of params in a network""" count = sum(p.numel() for p in net.parameters()) if as_int: return count return f"{count:,}"
bigcode/self-oss-instruct-sc2-concepts
def count_chars(template: str, instructions: dict[str, str], n: int) -> int: """ Counts the characters in the would-be string after `n` steps and returns the highest count (most common) - lowest count (least common). Args: template (str): The polymer template e.g. "NNCB" instructions (d...
bigcode/self-oss-instruct-sc2-concepts
def has_blank_ids(idlist): """ Search the list for empty ID fields and return true/false accordingly. """ return not(all(k for k in idlist))
bigcode/self-oss-instruct-sc2-concepts
import math def applyPan(min_, max_, panFactor, isLog10): """Returns a new range with applied panning. Moves the range according to panFactor. If isLog10 is True, converts to log10 before moving. :param float min_: Min value of the data range to pan. :param float max_: Max value of the data rang...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def find(arr: List[int], key: int) -> int: """Modified version of binary search: one half of the array must be already sorted. Therefore check the sorted half to decide whether to search the left or right half. This takes O(lg n) time and O(1) space. """ lo = 0 hi = len...
bigcode/self-oss-instruct-sc2-concepts
def error_margin_sample(z_star, SE): """ Get the margin of error of a sampling distribution. Parameters ---------- > z_star: the critical score of the confidence level > SE: the standard error of the sample Returns ------- The margin of error, given by z_star/SE. """ return z_star / SE
bigcode/self-oss-instruct-sc2-concepts
from typing import Mapping from typing import Any from typing import Union from typing import Sequence import functools import operator def recursive_getitem(d: Mapping[str, Any], keys: Union[str, Sequence[str]]) -> Any: """Recursively retrieve an item from a nested dict. Credit to: https://stackoverflow.com...
bigcode/self-oss-instruct-sc2-concepts
def group_type(type_string): """ Surround a type with parentheses as needed. """ return ( '(' + type_string + ')' if '|' in type_string else type_string )
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import Tuple def get_input(params: Union[dict, list]) -> Tuple[list, dict]: """ Get positional or keyword arguments from JSON RPC params :param params: Parameters passed through JSON RPC :return: args, kwargs """ # Backwards compatibility for old clients t...
bigcode/self-oss-instruct-sc2-concepts
import re def search_string(data_fetched): """ Function to search the returned email string for the word 'Hi' and return the words after it. Chose to collect 90 expressions after the keyword to ensure variance in the length of ship names and locations are accounted for. It returns the matched stri...
bigcode/self-oss-instruct-sc2-concepts
def _pseudo_voigt_mixing_factor(width_l, width_g): """ Returns the proportion of Lorentzian for the computation of a pseudo-Voigt profile. pseudoVoigt = (1 - eta) Gaussian + eta * Lorentzian Parameters ---------- width_l, width_g : float FWHM for the Gaussian and Lorentzian parts, r...
bigcode/self-oss-instruct-sc2-concepts
import collections import operator def is_batch_good(batch): """ Checks if a batch of tokens is valid. Parameters ---------- batch : list A list of integer tokens """ my_dict = collections.defaultdict(int) for i in batch: my_dict[i] += 1 sorted_x = sorted(my_...
bigcode/self-oss-instruct-sc2-concepts
def odds(nums): """Odds: Given a list of numbers, write a list comprehension that produces a list of only the odd numbers in that list. >>> odds([1, 2, 3, 4, 5]) [1, 3, 5] >>> odds([2, 4, 6]) [] >>> odds([-2, -4, -7]) [-7] """ lst = [a for a in nums if a%2...
bigcode/self-oss-instruct-sc2-concepts
from math import floor def conv_output_dim(input_size, kernel_size, stride=1, padding=0, dilation=1, **kwargs): """Calculate the output dimension of a convolutional layer """ return floor((input_size + 2*padding - dilation*(kernel_size-1) - 1)/stride + 1)
bigcode/self-oss-instruct-sc2-concepts
def do_if(tag, dictionary): """Removes a tag if its condition is False. :param tag: Tag to be evaluated :type tag: BeautifulSoup :param dictionary: Canonical dictionary of parameters :type dictionary: dict :return: Whether or not the tag was deleted :rtype: bool""" if tag.get("tuscon_if...
bigcode/self-oss-instruct-sc2-concepts
import re def find_url(string): """Find if a string contains an URL""" # findall() has been used # with valid conditions for urls in string url = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',string) if len(url) > 0: return True
bigcode/self-oss-instruct-sc2-concepts
def parse_header(line, numeric_vals=True): """ Parse a line of the form: #param=val\tparam=val\tparam=val... Return a dictionary of params: vals """ line = line.strip() if line[0] == '#': line = line[1:] params = {} for pair in line.split('\t'): k, v = pair.spli...
bigcode/self-oss-instruct-sc2-concepts
def split_string(value, arg=None): """ A simple string splitter So you can do that : :: {% if LANGUAGE_CODE in "fr,en-ca,en-gb,zh-hk,it,en,de"|split:',' %} """ return value.split(arg)
bigcode/self-oss-instruct-sc2-concepts
def resample_prices(close_prices, freq='M'): """ Resample close prices for each ticker at specified frequency. Parameters ---------- close_prices : DataFrame Close prices for each ticker and date freq : str What frequency to sample at For valid freq choices, see http...
bigcode/self-oss-instruct-sc2-concepts
def even(x): """ Returns 1 if x is even, 0 otherwise. """ return x % 2 == 0
bigcode/self-oss-instruct-sc2-concepts
def dictUpdate(original,newer): """Combine two dictionaries. If duplicate keys exist, use the newer values to overwrite the older ones.""" for k in newer.keys(): original[k]=newer[k] return original
bigcode/self-oss-instruct-sc2-concepts
def normalize_minmax(ar): """ Return the array ar scaled so that the min value is 0 and the max value is 1. """ x = ar - min(ar) mmax = max(x) if mmax == 0: return x return x/mmax
bigcode/self-oss-instruct-sc2-concepts
def _is_chrome_only_build(revision_to_bot_name): """Figures out if a revision-to-bot-name mapping represents a Chrome build. We assume here that Chrome revisions are always > 100000, whereas WebRTC revisions will not reach that number in the foreseeable future. """ revision = int(revision_to_bot_name.split('...
bigcode/self-oss-instruct-sc2-concepts
def me( context, api_client, api_key, output_file, output_format, verbose, ): """Get information about the currently authenticated Sublime user.""" result = api_client.me() return result
bigcode/self-oss-instruct-sc2-concepts
import re def parse_line(line,pattern,strict=True): """Matches given input line to regex. Line is stripped of leading/trailing whitespace. Args: line (string) : input line to parse pattern (string) : string containing regex strict (bool) : raise exception if mismatch (default: Tr...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any from typing import List def default_value(value: Any, fallback: Any, disallowed: List[Any] = [None]) -> Any: """ Checks whether the provided value is (by default) None or matches any other disallowed value, as provided. If the value is disallowed, the fallback will be returned. ...
bigcode/self-oss-instruct-sc2-concepts
import tempfile import base64 def dummy_image(filetype='gif'): """Generate empty image in temporary file for testing""" # 1x1px Transparent GIF GIF = 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7' tmp_file = tempfile.NamedTemporaryFile(suffix='.%s' % filetype) tmp_file.write(base64.b64...
bigcode/self-oss-instruct-sc2-concepts
def contains_any(string, candidates=[]): """Return True if a string contains any of the given candidate strings.""" for candidate in candidates: if candidate.lower() in string.lower(): return True return False
bigcode/self-oss-instruct-sc2-concepts
def vec_div (v,s): """scalar vector division""" return [ v[0]/s, v[1]/s, v[2]/s ]
bigcode/self-oss-instruct-sc2-concepts
def _alpha(n, threshold=30, scale=2000): """ Calculate a rough guess for the best alpha value for a default scatterplot. This is calculated with the equation .. math:: \\alpha = \\frac{0.99}{1 + \\frac{n}{\\text{scale}}} This is done so that is ranges from nearly 1 for small values of n ...
bigcode/self-oss-instruct-sc2-concepts
import numbers import torch def is_identically_zero(x): """ Check if argument is exactly the number zero. True for the number zero; false for other numbers; false for :class:`~torch.Tensor`s. """ if isinstance(x, numbers.Number): return x == 0 if not torch._C._get_tracing_state(): ...
bigcode/self-oss-instruct-sc2-concepts
import time from datetime import datetime def get_current_chart(charts): """Get the current relevant chart""" current_unix_time = time.mktime(datetime.now().timetuple()) current_chart = charts[-1] for chart in charts: if float(chart.datetimestamp) <= current_unix_time: current_ch...
bigcode/self-oss-instruct-sc2-concepts
import fnmatch def shell_match( namelist, matchlist ): """ Looks for a name in 'namelist' that matches a word in 'matchlist' which can contain shell wildcard characters. """ for n in namelist: for m in matchlist: if fnmatch.fnmatch( n, m ): return 1 return 0
bigcode/self-oss-instruct-sc2-concepts
import random def checkMissPlayer(defender): """ Returns a boolean token: if player missed or not. If defenders AC (Armor Class) is above players hit the token will evaluate to False, and the player will respectively miss. """ global currPlayerHitToken missChance = random.randrange(0, 25) if missChance <...
bigcode/self-oss-instruct-sc2-concepts
def calculate_precision_recall(TP, TN, FP, FN): """ Calculates the Precision and Recall meassure of the supplied reference and test data, as per https://en.wikipedia.org/wiki/Precision_and_recall#Definition_(classification_context) Incase of the denominator being zero for precision/recall, the values are se...
bigcode/self-oss-instruct-sc2-concepts
def heptagonal_n(n): """Returns the nth heptagonal number""" return int(n * (5 * n - 3) / 2)
bigcode/self-oss-instruct-sc2-concepts
def get_minimum_rect_from_contours(contours, padding=2): """ Find the minimum that include all of contour of contours array :param contours: array of contour :param padding: Add padding value for return rect :return: return rect object represent in format of (x_min, x_max, y_...
bigcode/self-oss-instruct-sc2-concepts
import torch def mixup_data(x, y, l): """Returns mixed inputs, pairs of targets, and lambda""" indices = torch.randperm(x.shape[0]).to(x.device) mixed_x = l * x + (1 - l) * x[indices] y_a, y_b = y, y[indices] return mixed_x, y_a, y_b
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def fixture_db_path(db_dir: Path, db_name: str) -> Path: """Return the path to a database""" return db_dir / db_name
bigcode/self-oss-instruct-sc2-concepts
def _merge_small_dims(shape_to_merge, max_dim): """Merge small dimensions. If there are some small dimensions, we collapse them: e.g. [1, 2, 512, 1, 2048, 1, 3, 4] --> [1024, 2048, 12] if max_dim = 1024 [1, 2, 768, 1, 2048] --> [2, 768, 2048] Args: shape_to_merge: Shape to merge small dimensions. ...
bigcode/self-oss-instruct-sc2-concepts
def trimhttp2(url): """ Strip 'http://' or 'https://' prefix to url """ if url[:7] == b'http://': return url[7:] elif url[:8] == b'https://': return url[8:] return url
bigcode/self-oss-instruct-sc2-concepts
def is_affiliate_empty(affiliate_obj): """ Check for an empty Affiliate object to detect for empty Excel rows. :param affiliate_obj: Affiliate :return: Boolean """ if affiliate_obj.affiliate_name is None \ and affiliate_obj.is_accs is False \ and affiliate_obj.is_pcp is F...
bigcode/self-oss-instruct-sc2-concepts
def score_defaults(gold_labels): """ Compute the "all false" baseline (all labels as unrelated) and the max possible score :param gold_labels: list containing the true labels :return: (null_score, best_score) """ unrelated = [g for g in gold_labels if g['Stance'] == 'unrelated'] null_sco...
bigcode/self-oss-instruct-sc2-concepts
from typing import List import requests import string def get_public_suffixes() -> List[str]: """ Retrieves an extensive list of public suffixes used and filters out non ASCII suffixes. In case of any issues connecting to the website this function returns a much less comprehensive builtin list. ""...
bigcode/self-oss-instruct-sc2-concepts
def strip_right_above_below(chars): """Drop leading and trailing blank lines, and drop trailing spaces in each line""" lines_plus = chars.splitlines() lines = list(_.rstrip() for _ in lines_plus) while lines and not lines[0]: lines = lines[1:] while lines and not lines[-1]: lines ...
bigcode/self-oss-instruct-sc2-concepts
import csv def get_max_node_id(nodes_file): """ Examines the 'nodes_file' passed in and finds the value of highest node id. It is assumed the 'nodes_file' a tab delimited file of format: <CLUSTER NAME> <# NODES> <SPACE DELIMITED NODE IDS> <SCORE> :param nodes_file: :type nodes_file:...
bigcode/self-oss-instruct-sc2-concepts
def get_verbose_field_name(instance, field_name): """ Get the verbose_name for a field in a model instance Parameters ---------- instance : Django models.Model An instance of any sub-class of a Django models.Model field_name : str Name of the field to return the verbose field na...
bigcode/self-oss-instruct-sc2-concepts
def _split_channels(num_chan, num_groups): """Split range(num_chan) in num_groups intervals. The first one is larger if num_chan is not a multiple of num_groups""" split = [num_chan // num_groups for _ in range(num_groups)] # add the remaining channels to the first group split[0] += num_chan - sum(split...
bigcode/self-oss-instruct-sc2-concepts
def get_instances_joined(game, player): """ Return the instance ids of instance that player has joined. Args: game: The parent Game database model to query for instances. player: The email address of the player to look for in instances. Returns: An empty list if game is None. Else, returns a list of...
bigcode/self-oss-instruct-sc2-concepts
def is_subset(a, b): """Test whether every element in a is also in b.""" return set(a).issubset(set(b))
bigcode/self-oss-instruct-sc2-concepts
def read_ppm_header(fp, filename): """Read dimensions and headersize from a PPM file.""" headersize = 0 magic_number = fp.readline() if magic_number != "P6\n": raise TypeError("Hey! Not a ppm image file: %s" % filename) headersize += len(magic_number) comment = fp.readline() if comment[0] == "#": ...
bigcode/self-oss-instruct-sc2-concepts
def readFile(nam): """ Read a file and return its content as a string. """ f = open(nam,"r") s = f.read() f.close() return s
bigcode/self-oss-instruct-sc2-concepts
def top_players_stat(fifa_df, stat, no_of_players): """ Returns the top x no players in a stat Parameters ---------- fifa_df The fifa versions players (df) no_of_players The number of players to return (int) stat The stat to sort by (str) Returns ------- ...
bigcode/self-oss-instruct-sc2-concepts
def get_the_node_dict(G, name): """ Helper function that returns the node data of the node with the name supplied """ for node in G.nodes(data=True): if node[0] == name: return node[1]
bigcode/self-oss-instruct-sc2-concepts
def make_kw(bbox, time_range): """Make kw for search. Parameters ---------- bbox: list Geographic bounding box: [min_lon, min_lat, max_lon, max_lat] time_range: list [start_time, end_time] where each are strings that can be interpreted with pandas `Timestamp`. Returns ...
bigcode/self-oss-instruct-sc2-concepts
def slice_text(text, eos_token="<s>", sos_token="</s>"): """Slices text from <s> to </s>, not including these special tokens. """ eos_index = text.find(eos_token) text = text[:eos_index] if eos_index > -1 else text sos_index = text.find(sos_token) text = text[sos_index+len(so...
bigcode/self-oss-instruct-sc2-concepts
def after_userlogin_hook(request, user, client): """Marks Django session modified The purpose of this function is to keep the session used by the oidc-provider fresh. This is achieved by pointing 'OIDC_AFTER_USERLOGIN_HOOK' setting to this.""" request.session.modified = True # Return None to c...
bigcode/self-oss-instruct-sc2-concepts
def dist_rgb(rgb1, rgb2): """ Determine distance between two rgb colors. :arg tuple rgb1: RGB color definition :arg tuple rgb2: RGB color definition :returns: Square of the distance between provided colors :rtype: float This works by treating RGB colors as coordinates in three dimensional ...
bigcode/self-oss-instruct-sc2-concepts
import yaml def load_config(path): """Load yaml collection configuration.""" with open(path, 'r') as stream: return yaml.load(stream, Loader=yaml.SafeLoader)
bigcode/self-oss-instruct-sc2-concepts
def build_param_bul (param): """ Builds a configuration parameter documentation bullet from a parameter tuple. Args: param (tuple): The parameter tuple. Returns: string: The documentation bullet markdown. """ return param[0] + ' (' + param[1] + '): ' + param[2]
bigcode/self-oss-instruct-sc2-concepts
def output_fn(prediction, response_content_type): """ Return model's prediction """ return {'generated_text':prediction}
bigcode/self-oss-instruct-sc2-concepts
def first(sequence, condition=None): """ Returns the first item in a sequence that satisfies specified condition or raises error if no item found. Args: sequence: iterable Sequence of items to go through. condition: callable Condition to test. ...
bigcode/self-oss-instruct-sc2-concepts
def to_signed_byte(num): """ Convert given byte number to signed byte number. :param num: Unsigned byte number in range from 0 to 255. :return: Signed number in range from -128 to 127. """ assert 0 <= num <= 255, 'Value out of range (0 - 255): {0}!'.format(num) if num <= 127: ret =...
bigcode/self-oss-instruct-sc2-concepts
import sqlite3 from typing import Any def transaction(conn: sqlite3.Connection, sql: str, *args: Any) -> sqlite3.Cursor: """Perform a transaction. The transaction needs to be committed or rolled back. Args: conn: database connection sql: formatted string *args: ar...
bigcode/self-oss-instruct-sc2-concepts
def non_none_dict(d): """return a copy of the dictionary without none values.""" return dict([a for a in d.items() if a[1] is not None])
bigcode/self-oss-instruct-sc2-concepts
def java_class_params_to_key(package: str, class_name: str): """Returns the unique key created from a package and class name.""" return f'{package}.{class_name}'
bigcode/self-oss-instruct-sc2-concepts
def create_symbol( client, symbol_file, point, drawing=None, replace_values=None, sheet=None ): """Add a symbol instance to a drawing. Args: client (obj): creopyson Client symbol_file (str): Name of the symbol file. point (dict): Coordinates for t...
bigcode/self-oss-instruct-sc2-concepts
from typing import Set def get_all_subclasses(cls: type) -> Set[type]: """Return all subclasses of a give cls class.""" return set( cls.__subclasses__()).union( [s for c in cls.__subclasses__() for s in get_all_subclasses(c)] )
bigcode/self-oss-instruct-sc2-concepts
def get_containers(client, pod, namespace): """ makes a request against the Kubernetes api and extracts the names of pod's containers :param client the Kubernetes api client :param str pod: the name of the pod :param str namespace: the namespace where to search for the pod :return: the...
bigcode/self-oss-instruct-sc2-concepts
def uniqueify(items): """Return a list of the unique items in the given iterable. Order is NOT preserved. """ return list(set(items))
bigcode/self-oss-instruct-sc2-concepts
import pathlib import hashlib def _md5(file: pathlib.Path) -> str: """Calculates the MD5 hash code of a file for integrity.""" hash_md5 = hashlib.md5() with file.open("rb") as f: # Read and update hash string value in blocks of 4K for chunk in iter(lambda: f.read(4096), b""): h...
bigcode/self-oss-instruct-sc2-concepts
def print_nums_opt(*numbers: int) -> str: """Fill numbers with zeros (optimizible). Args: *numbers: <int> sequence of numbers Returns: zero filled string. Examples: >>> assert print_nums_opt(11, 12, 23) == '11 12 23' """ return ' '.join(str(num).zfill(len(max(str(num)))) for n...
bigcode/self-oss-instruct-sc2-concepts
def unnormalize(z, bounds): """Inverse of normalize""" return z * (bounds[:, 1] - bounds[:, 0]) + bounds[:, 0]
bigcode/self-oss-instruct-sc2-concepts
def parse_nsvca(nsvca): """ Take module name, stream, version, context and architecture in a N:S:V:C:A format and return them as a separate values. """ split = nsvca.split(":") if len(split) != 5: raise ValueError("N:S:V:C:A in unexpected format") split[2] = int(split[2]) return ...
bigcode/self-oss-instruct-sc2-concepts
def pic_flag(compiler=None): """ returns PIC (position independent code) flags, such as -fPIC """ if not compiler or compiler == 'Visual Studio': return "" return '-fPIC'
bigcode/self-oss-instruct-sc2-concepts
import json def read_json(file_path): """Read json file from file_path.""" with open(file_path, encoding="utf-8", errors="surrogateescape") as f: return json.load(f)["data"]
bigcode/self-oss-instruct-sc2-concepts
def ignore_exception(*exception_classes): """ A function decorator to catch exceptions and pass. @ignore_exception(ValueError, ZeroDivisionError) def my_function(): ... Note that this functionality should only be used when you don't care about the return value of the functi...
bigcode/self-oss-instruct-sc2-concepts