seed
stringlengths
1
14k
source
stringclasses
2 values
def filter_active_particles(particles): """Filter active particles from particles dict.""" return {particle_number: particle for particle_number, particle in particles.items() if particle['active']}
bigcode/self-oss-instruct-sc2-concepts
def extract_keys(feature_dict, feature_cls): """Extracts keys from features dict based on feature type. Args: feature_dict: `tfds.features.FeaturesDict` from which extract keys feature_cls: `tfds.features.FeatureConnector` class to search. Returns: List of extracted keys matching the class. """ ...
bigcode/self-oss-instruct-sc2-concepts
import torch def split_last_dimension(x, n): """Reshape x so that the last dimension becomes two dimensions. The first of these two dimensions is n. Args: x: a Tensor with shape [..., m] n: an integer. Returns: a Tensor with shape [..., n, m/n] """ x_shape = x.size() m = x_shap...
bigcode/self-oss-instruct-sc2-concepts
def contains(collection, target): """Determine whether collecitons contains target """ return target in collection
bigcode/self-oss-instruct-sc2-concepts
def _GetDownloadZipFileName(file_name): """Returns the file name for a temporarily compressed downloaded file.""" return '%s_.gztmp' % file_name
bigcode/self-oss-instruct-sc2-concepts
def simple_sanitize(s: str): """ Sanitize SQL string inputs simply by dropping ';' and ''' """ if s is not None: return s.replace(';', '').replace('\'', '') return None
bigcode/self-oss-instruct-sc2-concepts
def _transform_activation(phi, params): """Transform an activation function phi using the given parameters.""" params = params.copy() input_scale = params.pop("input_scale", None) input_shift = params.pop("input_shift", None) output_shift = params.pop("output_shift", None) output_scale = params.pop("outpu...
bigcode/self-oss-instruct-sc2-concepts
def pofiles_to_unique_translations_dicts(pofiles): """Extracts unique translations from a set of PO files. Given multiple pofiles, extracts translations (those messages with non empty msgstrs) into two dictionaries, a dictionary for translations with contexts and other without them. Args: ...
bigcode/self-oss-instruct-sc2-concepts
import inspect def _isFunction(fn): """ Python class is also callable, so we need to deal with such pattern. class A: def b(self): return False a = A() callable(A) # True callable(a) # False callable(a.b) # True inspect.isclass(A) # True inspect.isclass(a) # False inspect.isclass(a.b) # ...
bigcode/self-oss-instruct-sc2-concepts
def is_label_ranker(estimator): """Return ``True`` if the given estimator is a :term:`label ranker`. Parameters ---------- estimator : object The estimator object to test. Returns ------- out : bool ``True`` if ``estimator`` is a label ranker and ``False`` otherwise. ""...
bigcode/self-oss-instruct-sc2-concepts
def get_par_dict(e3d_par): """ return e3d.par as a dict :param e3d_par: path to e3d.par :return: dict """ d = {} with open(e3d_par, "r") as e1: t1 = e1.readlines() for line in t1: k, v = line.strip().split("=") d[k] = v return d
bigcode/self-oss-instruct-sc2-concepts
def convert_string_tf_to_boolean(invalue): """Converts string 'True' or 'False' value to Boolean True or Boolean False. :param invalue: string input true/false value :return: Boolean converted True/False value """ outvalue = False if invalue == 'True': outvalue = True ...
bigcode/self-oss-instruct-sc2-concepts
def lines(string, keepends=False): """ Split a string into a list of strings at newline characters. Unless *keepends* is given and true, the resulting strings do not have newlines included. """ return string.splitlines(keepends)
bigcode/self-oss-instruct-sc2-concepts
def BuildCampaignOperations(batch_job_helper, budget_operations, number_of_campaigns, campaign_names): """Builds the operations needed to create a new Campaign. Note: When the Campaigns are created, they will have a different Id than those generated here as a temporary Id. This is jus...
bigcode/self-oss-instruct-sc2-concepts
import base64 def encode_group_id(group_id): """Encode group_id as returned by the websocket for use with other endpoints.""" return "group." + base64.b64encode(group_id.encode("ascii")).decode("ascii")
bigcode/self-oss-instruct-sc2-concepts
def get_effective_power(unit): """Get effective power of unit.""" return unit['count'] * unit['damage']
bigcode/self-oss-instruct-sc2-concepts
import six from contextlib import suppress def is_valid_aesthetic(value, ae): """ Return True if `value` looks valid. Parameters ---------- value : object Value to check ae : str Aesthetic name Returns ------- out : bool Whether the value is of a valid loo...
bigcode/self-oss-instruct-sc2-concepts
def lag(series, i=1): """ Returns a series shifted backwards by a value. `NaN` values will be filled in the beginning. Same as a call to `series.shift(-i)` Args: series: column to shift backward. i (int): number of positions to shift backward. """ shifted = series.shift(i)...
bigcode/self-oss-instruct-sc2-concepts
from typing import List import json def get_extensions() -> List[str]: """Carica le estensioni dal file extensions.json. Si aspetta di trovare una lista con i nomi delle estensioni da aggiungere al bot. Se non trova il file o ci sono errori ritorna una lista vuota. :returns: la lista coi nomi delle e...
bigcode/self-oss-instruct-sc2-concepts
def aero_force(rho, V, C, A): """ Aerodynamic lift/drag equation Input variables: rho : Fluid density V : Fluid velocity C : Lift/drag coefficient A : Reference area """ F = 0.5 * rho * (V**2) * C * A return F
bigcode/self-oss-instruct-sc2-concepts
def is_anagram(word1, word2): """Checks whether two words are anagrams word1: string or list word2: string or list returns: boolean """ return sorted(word1) == sorted(word2)
bigcode/self-oss-instruct-sc2-concepts
import string def name_make_safe(name, safe_chars = None): """ Given a filename, return the same filename will all characters not in the set [-_.0-9a-zA-Z] replaced with _. :param str name: name to make *safe* :param set safe_chars: (potional) set of characters that are considered safe. Def...
bigcode/self-oss-instruct-sc2-concepts
def get_most_complete_version(versions): """ Return the most complete version. i.e. `versions=['1.4', '1.4.4']` it returns '1.4.4' since it's more complete. """ if not versions: return return max(versions)
bigcode/self-oss-instruct-sc2-concepts
def rename_columns(df, columns_dictionary): """Renames provided columns. """ return df.rename(columns=columns_dictionary)
bigcode/self-oss-instruct-sc2-concepts
def shorten(thelist, maxlen, shorten): """ If thelist has more elements than maxlen, remove elements to make it of size maxlen. The parameter shorten is a string which can be one of left, right, both or middle and specifies where to remove elements. :param thelist: the list to shorten :param max...
bigcode/self-oss-instruct-sc2-concepts
def ByteToHex( byteStr ): """ Convert a byte string to it's hex string representation e.g. for output. """ return ''.join( [ "%02X " % ord( x ) for x in byteStr ] ).strip()
bigcode/self-oss-instruct-sc2-concepts
def update_parameters(parameters, grads, learning_rate = 1.2): """ Updates parameters using the gradient descent update rule given above Arguments: parameters -- python dictionary containing your parameters grads -- python dictionary containing your gradients Returns: parameters ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence import fnmatch def _should_ignore(fd_name: str, patterns: Sequence[str]) -> bool: """Return whether `fd_name` should be ignored according to `patterns`.""" return any(fnmatch.fnmatchcase(fd_name, pattern) for pattern in patterns)
bigcode/self-oss-instruct-sc2-concepts
import torch def unnormalize(img, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]): """ Convert a normalized tensor image to unnormalized form :param img: (B, C, H, W) """ img = img.detach().cpu() img *= torch.tensor(std).view(3, 1, 1) img += torch.tensor(mean).view(3, 1, 1) ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def num_reviews_with_token(profTokenDict): """ Returns a Counter with the number of reviews a given token appears in. """ counter = Counter() for profCounts in profTokenDict.values(): for revCtr in profCounts: counter += Counter(revCtr.keys()) return counter
bigcode/self-oss-instruct-sc2-concepts
def cache_dir(tmp_path_factory): """Return temporary location of DATALAD_REGISTRY_DATASET_CACHE.""" return tmp_path_factory.mktemp("cache_dir")
bigcode/self-oss-instruct-sc2-concepts
def sample_constraint(value): """ The value must be within the range of 1-255. """ return 1 <= value <= 0xFF
bigcode/self-oss-instruct-sc2-concepts
def line(a, t, l): """ Linear interpolation between a and b 0 <= t <= 1 """ return a + t * l
bigcode/self-oss-instruct-sc2-concepts
def combinations(s, K): """ On entry: s sequence of items; K size of the combinations Returns: list of all possible K-combinations without replacement of s. """ N = len(s) assert K<=N, 'Error K must be less or igual than N' S = [[] for i in range(K+1) ] for n in range(1,N+1): ...
bigcode/self-oss-instruct-sc2-concepts
def get_node(data_path): """Return Blender node on a given Blender data path.""" if data_path is None: return None index = data_path.find("[\"") if (index == -1): return None node_name = data_path[(index + 2):] index = node_name.find("\"") if (index == -1): return ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def _safe_path(path: str, extensions: Tuple[str, ...]) -> str: """Returns safe filename based on given extensions. Args: path (str): filepath extensions (tuple[str, ...]): a list of allowed extensions Raises: `ValueError` if path is invalid """ if...
bigcode/self-oss-instruct-sc2-concepts
def grid_to_str(grid): """ Convert grid - our internal representation into an 81-char sudoku string """ return ''.join(str(grid[ndx].pop()) for ndx in range(0, 81))
bigcode/self-oss-instruct-sc2-concepts
def trim(peaks, troughs): """ Trims the peaks and troughs arrays such that they have the same length. Args: peaks (numpy array): list of peak indices or times troughs (numpy array): list of trough indices or times Returns: peaks (numpy array): list of peak indices or times ...
bigcode/self-oss-instruct-sc2-concepts
def is_balanced(node): """Check if a BST is balanced; returns (True/False, height of tree).""" # First we ensure the left subtree is balanced; then ensure the right subtree # is balanced too; and ensure the diff betw heights of left & right subtree <=1 if node is None: return True, 0 balanc...
bigcode/self-oss-instruct-sc2-concepts
from io import StringIO import csv def export_csv(items, fields): """ Generate the data with csv.writer and stream the response. Use StringIO to write to an in-memory buffer rather than generating an intermediate file. """ data = StringIO() w = csv.writer(data) w.writerow(fields) # ...
bigcode/self-oss-instruct-sc2-concepts
def compliment_bools(v1, v2): """Returns true if v1 and v2 are both bools and not equal""" return isinstance(v1, bool) and isinstance(v2, bool) and v1 != v2
bigcode/self-oss-instruct-sc2-concepts
import itertools import random def nbackseq(n, length, words): """Generate n-back balanced sequences :param n: int How many characters (including the current one) to look back to assure no duplicates :param length: int The total length of the sequence to produce :param words: ...
bigcode/self-oss-instruct-sc2-concepts
def main(*, data, decimals): """entrypoint function for this component Usage example: >>> main( ... data = pd.Series( ... { ... "2019-08-01T15:20:12": -25.054, ... "2019-08-01T15:44:12": None, ... "2019-08-03T16:20:15": -0.2514, ... ...
bigcode/self-oss-instruct-sc2-concepts
import math def human_size(size): """Return human readable string for Bytes size """ if size <= 0: return "0M" measure = ['B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'] expo = int(math.log(size, 1024)) mant = float(size/math.pow(1024, expo)) return "{0:.1f}{1:s}".format(mant, measur...
bigcode/self-oss-instruct-sc2-concepts
def sec_2_index(secs, fr=2048, offset=0): """ :param numpy.ndarray secs: time in seconds to be converted :param float fr: dampling frequency :param float offset: offset in seconds :return: time in samples :rtype: numpy.ndarray """ return (secs*fr - offset*fr).astype(int)
bigcode/self-oss-instruct-sc2-concepts
def convert_arg_to_int(cmd_args): """Convert str to int as much as possible :param cmd_args: the sequence of args :return the sequence of args """ args = [] for arg in cmd_args: if isinstance(arg, str): # Int will cause TypeError try: arg = int(arg, 0) ...
bigcode/self-oss-instruct-sc2-concepts
def listHasItems(listOfLists): """ Some of the batched calls return lists of lists. This means that a return value of [ [], [], [], ], say from @ref python.Manager.getRelatedEntities, is hard to easily detect using a boolean cast, as the outer list is not empty. This function checks that some item in the o...
bigcode/self-oss-instruct-sc2-concepts
import re def strip_escape(text: str) -> str: """Remove terminal ascii escape sequences from *text*. Args: text: text to strip escape sequences from Returns: text stripped of escape sequences """ # These are all valid escape sequences... they're probably not # inclusive ...
bigcode/self-oss-instruct-sc2-concepts
import json from typing import OrderedDict def load_ordered(fp, **kwargs): """ Convenience wrapper for json.load() that loads the JSON while preserving the original element ordering/sequence. """ return json.load(fp, object_pairs_hook=OrderedDict, **kwargs)
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from pathlib import Path def _check_data_dirs( data_directory: Union[str, Path] = Path("../data/") ) -> Path: """ Validates data directory exists. If it doesn't exists, it creates it and creates 'raw/' and 'interim/' directories. """ # set directory's values _data_dire...
bigcode/self-oss-instruct-sc2-concepts
import textwrap def wrap(text, width=100): """ Intelligently wrap text. Wrap text without breaking words if possible. Parameters ---------- text : str Text to wrap. width : int, optional Number of characters to wrap to, default 100. """ split_text = text.spli...
bigcode/self-oss-instruct-sc2-concepts
def compute_score_interpretability_method(features_employed_by_explainer, features_employed_black_box): """ Compute the score of the explanation method based on the features employed for the explanation compared to the features truely used by the black box """ score = 0 for feature_employe in featur...
bigcode/self-oss-instruct-sc2-concepts
def convert_string(string, chars=None): """Remove certain characters from a string.""" if chars is None: chars = [',', '.', '-', '/', ':', ' '] for ch in chars: if ch in string: string = string.replace(ch, ' ') return string
bigcode/self-oss-instruct-sc2-concepts
def read_candidates(candidate_path): """Read parent candidates from file. Row number identifies the node and space separated numbers on each row identify the candidate parents. """ C = dict() with open(candidate_path, "r") as f: f = f.readlines() for v, row in enumerate(f): ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def master_name(tf_vars: Dict) -> str: """Construct master name for provided Terraform deployment.""" return f"det-master-{tf_vars.get('cluster_id')}-{tf_vars.get('det_version_key')}"
bigcode/self-oss-instruct-sc2-concepts
import json def load_json(path): """Load JSON file into Python object.""" with open(path, "r") as file_data: data = json.load(file_data) return data
bigcode/self-oss-instruct-sc2-concepts
def tmap(*args, **kwargs): """Like map, but returns a tuple.""" return tuple(map(*args, **kwargs))
bigcode/self-oss-instruct-sc2-concepts
import re def make_clean_input(pattern): """ Enforces that entities or words have parentheses around them and have trailing spaces >>> make_clean_input("@num{3}") '(@(num ) ){3}' >>> make_clean_input("num{3}") '(num ){3}' Entities can sometimes have underscores >>> make_clean_input("@...
bigcode/self-oss-instruct-sc2-concepts
def get_access_headers(app): """ Function to retrieve and format the Authorization Headers that can be passed to various microservices who are expecting that. :param oidc: OIDC object having authorization information :return: A formatted dictionary containing access token as Authorization header...
bigcode/self-oss-instruct-sc2-concepts
def strip_unimportant(source: str) -> str: """ Strips unimportant information like footnotes, alternative names, or weird spaces. """ stripped = "" for char in source: # remove footnotes like RTX 3080[155] if char == "[" or char == "(": break # remove weird sp...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def justify_stringlist(j: List[str], right=False) -> List[str]: """ CONSOLE FUNCTION: justify all str in a list to match the length of the longest str in that list. Determined by len() function, i.e. number of chars, not by true width when printed, so it doesn't work well with JP/CN chars. ...
bigcode/self-oss-instruct-sc2-concepts
def pascal_triangle(rows: int) -> list: """ https://oeis.org/A007318 >>> pascal_triangle(4) [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]] """ res = [[1]] for _ in range(rows): row = res[-1] res.append([1, *map(sum, zip(row, row[1:])), 1]) return res
bigcode/self-oss-instruct-sc2-concepts
def clamp(val: float, minimum: float = 0.0, maximum: float = 1.0) -> float: """ Fix value between min an max""" if val < minimum: return minimum if val > maximum: return maximum return val
bigcode/self-oss-instruct-sc2-concepts
def find_value(sheet, row): """Finds the best available value. Parameters --------- sheet : workbook.sheet An Excel sheet. row : int The row where the value is located. Returns ------- string The cell value that wasn't 'N/E' (not eligible). """ # We f...
bigcode/self-oss-instruct-sc2-concepts
def get_select_indexes(selects, attributes): """ Gets the indexes for all select statements. Args: selects: select values attributes: attributes in the tables Returns: indexes: look up indexes for select values """ if selects[0] != '*': indexes = [] split_se...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def int_to_rgb(x: int) -> Tuple[int, int, int]: """Return a RGB tuple from integer.""" red = (x >> 16) & 0xFF green = (x >> 8) & 0xFF blue = x & 0xFF return red, green, blue
bigcode/self-oss-instruct-sc2-concepts
import base64 def is_base64(s): """Function to check whether a string is base64 encoded or not Parameters ---------- s String to check """ try: return base64.b64encode(base64.b64decode(s)) == s except Exception: return False
bigcode/self-oss-instruct-sc2-concepts
import re def re_match_strings(target, strings): """ Whether or not the string 'target' matches any one string of the strings which can be regular expression string """ return any(name == target or re.match(name, target) for name in strings)
bigcode/self-oss-instruct-sc2-concepts
def uniquify(words): """Remove duplicates from a list. Args: words (list): The list of words Returns: list: An updated word list with duplicates removed. """ return {}.fromkeys(words).keys() if words is not None else words
bigcode/self-oss-instruct-sc2-concepts
import struct def get_hyperheader(file): """ Unpack hypercomplex header parameters to a list. Reads the 28-bytes block header from file and unpacks into a list. Endianness is corrected as needed. Returned list contents: = ======== ================ N Variable Description = ...
bigcode/self-oss-instruct-sc2-concepts
def jenkins_node_names(name, count): """Returns the names for `count` production jenkins node prefixed by `name`.""" return ["%s-%s" % (name, i) for i in range(1, count+1)]
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional import requests def get_latest_flexget_version_number() -> Optional[str]: """ Return latest Flexget version from https://pypi.python.org/pypi/FlexGet/json """ try: data = requests.get('https://pypi.python.org/pypi/FlexGet/json').json() return data.get('info'...
bigcode/self-oss-instruct-sc2-concepts
def Lambda(zhub, IECedition): """ Calculate the IEC length scale. Lambda = 0.7*min(Zhat,zhub) Where: Zhat = 30,60 for IECedition = 2,3, respectively. """ if IECedition <= 2: return 0.7 * min(30, zhub) return 0.7 * min(60, zhub)
bigcode/self-oss-instruct-sc2-concepts
from typing import List def reverse(s: str) -> str: """ Reverse a string. - Time Complexity: O(len(s)) - Space Complexity: O(len(s)) :param s: a string :return: a reversed string """ length = len(s) rlist: List[str] = [''] * length for i in range(length): rlist[length...
bigcode/self-oss-instruct-sc2-concepts
def get_xi(a: float, i: int, delta_x: float) -> float: """ Calculating x_i = a + i * delta_x """ return a + (i * delta_x)
bigcode/self-oss-instruct-sc2-concepts
def legc(leg,col='color'): """Color legend text to match linecolor. :Inputs: 'leg' is a legend object. 'col' sets the field of the leg.get_lines() objects to use to find the color. You may need to refresh the figure to see the changes.""" # 2009-12-14 09:50 IJC: Created tex...
bigcode/self-oss-instruct-sc2-concepts
import re def regquote(s): """Quote regular expressions. :param s: string to be quoted. """ return re.sub(r'([][.^$*+])', r'\\\1', s)
bigcode/self-oss-instruct-sc2-concepts
def _build_dict(words): """Builds a dictionary of words :param list[str] words: words :returns: dictionary of words :rtype: dict """ d = {} for i, word in enumerate(words): try: first, second, third = words[i], words[i + 1], words[i + 2] except IndexError: ...
bigcode/self-oss-instruct-sc2-concepts
import torch def validate_model(model, valid_loader, criterion, device): """Validate the accuracy of the model during training Arguments: model -- The model to validate valid_loader -- Valdation data loader criterion -- Loss function used by the model device -- If it is to tra...
bigcode/self-oss-instruct-sc2-concepts
import inspect def arg_names(receiver): """ Get the expected keyword arguments for a function or class constructor. """ return list(inspect.signature(receiver).parameters.keys())
bigcode/self-oss-instruct-sc2-concepts
def to_language(locale): """Turns a locale name (en_US) into a language name (en-us).""" p = locale.find('_') if p >= 0: return locale[:p].lower() + '-' + locale[p + 1:].lower() else: return locale.lower()
bigcode/self-oss-instruct-sc2-concepts
def process_input(input_name): """ Returns the processed input as well as the max size of the ocean matrix """ with open(input_name) as input: max_size = 0 processed = [] for line in input: points = line.strip().split(' -> ') line_array = [] ...
bigcode/self-oss-instruct-sc2-concepts
def get_spans_in_offsets(spans, start, end): """Return the list of spans (nlplingo.text.text_span.Span) that are within (start, end) offsets :type spans: list[nlplingo.text.text_span.Span] Returns: list[text.text_span.Span] """ ret = [] for span in spans: if start <= span.start_c...
bigcode/self-oss-instruct-sc2-concepts
def run_one_phot_method(allInput): """ Do a photometry/spectroscopy method on one file For example, do aperture photometry on one file This is a slightly awkward workaround because multiprocessing doesn't work on object methods So it's a separate function that takes an object and runs the method ...
bigcode/self-oss-instruct-sc2-concepts
def generate_snake_order(teams, n_rounds): """Create a snake draft order Args: teams (iterable): e.g. ('Team1', 'Team2', 'Team3') n_rounds (int): number of rounds in draft Returns: list Examples: >>>generate_snake_order(teams=['A', 'B', 'C'], n_rounds=4) ['A', ...
bigcode/self-oss-instruct-sc2-concepts
import math import random def prob_round(x): """ Rounds up with probability proportional to decimal places. """ floor = math.floor(x) if random.random() < x - floor: floor += 1 return floor
bigcode/self-oss-instruct-sc2-concepts
def make_users_groups_url(base_url, duke_unique_id): """ Create url for fetching a users groups. :param base_url: base group manager url (eg. 'https://groups.oit.duke.edu/grouper-ws/servicesRest/json/v2_1_500/') :param duke_unique_id: str: unique id (number) of the user we want to build a url for :r...
bigcode/self-oss-instruct-sc2-concepts
def get_stylesheets_for_decorator(decorator: dict, count: int) -> list: """ Gets stylesheets for a decorator. Args: decorator (dict): Decorator config object. count (int): Current page count. Returns: list: List of CSS documents that apply to current usage of decorator. """...
bigcode/self-oss-instruct-sc2-concepts
def count_mismatches_before_variant(reference_prefix, cdna_prefix): """ Computes the number of mismatching nucleotides between two cDNA sequences before a variant locus. Parameters ---------- reference_prefix : str cDNA sequence of a reference transcript before a variant locus cdna...
bigcode/self-oss-instruct-sc2-concepts
def ensure_array(exemplar, item): """Coerces *item* to be an array (linear sequence); if *item* is already an array it is returned unchanged. Otherwise, an array of the same length as exemplar is created which contains *item* at every index. The fresh array is returned. """ try: item[...
bigcode/self-oss-instruct-sc2-concepts
import torch def normalise_quat_in_pose(pose): """Takes a pose and normalises the quaternion portion of it. Args: pose: shape N, 7 Returns: Pose with normalised quat. Shape N, 7 """ pos = pose[:, 0:3] quat = pose[:, 3:7] quat /= torch.norm(quat, dim=-1, p=2).reshape(-1, 1)...
bigcode/self-oss-instruct-sc2-concepts
def get_slurm_directives(user: str, job_name: str = 'BlenderRender', gpu: int = 2, cpu: int = 4, ssd: int = 10, ram: int = 16, days: int = 0, hh:...
bigcode/self-oss-instruct-sc2-concepts
def socket_read_n(sock, n): """ Read exactly n bytes from the socket. Raise RuntimeError if the connection closed before n bytes were read. """ buf = '' while n > 0: data = sock.recv(n) if data == '': raise RuntimeError('unexpected connection close') buf += da...
bigcode/self-oss-instruct-sc2-concepts
def activity_logging_world_check(member): """Returns if an isolated world check is required when generating activity logging code. The check is required when there is no per-world binding code and logging is required only for isolated world. """ extended_attributes = member.extended_attributes ...
bigcode/self-oss-instruct-sc2-concepts
def avg_list(jac_list): """Average a list of jaccard results This is useful for computations like pairwise which need summarization """ if len(jac_list) == 0: return 0 return sum(jac_list)/float(len(jac_list))
bigcode/self-oss-instruct-sc2-concepts
def get_jittering(seed_rng, scale_size, translate_size, rotation_size, img_width): """ This method returns uniform random values for scaling, translation, and rotation in the range given by user. Parameters: ------------- scale_size: float in [0,1] the maximum ratio by w...
bigcode/self-oss-instruct-sc2-concepts
def IsEven( x ): """Tests if x is even""" return ( x % 2 ) == 0
bigcode/self-oss-instruct-sc2-concepts
def _sorted_images(images, start_name): """Retrieve a sorted list of images with most recent first. """ images = [(i.name, i) for i in images if i.name.startswith(start_name)] images.sort(reverse=True) return [(i.id, name) for (name, i) in images]
bigcode/self-oss-instruct-sc2-concepts
def polyXY2(x,y,coeff): """XY quadratic with cross-terms | - | x | x2| ---+---+---+---+ - | a | b | d | y | c | e | g | y2| f | h | i | """ a,b,c,d,e,f,g,h,i = coeff return a + x*(b + x*d) + y*(c + y*f) + x*y*(e + x*g + y*h + x*y*i)
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import fcntl import errno def lock_script() -> bool: """ Locks a file pertaining to this script so that it cannot be run simultaneously. Since the lock is automatically released when this script ends, there is no need for an unlock function for this use case. Returns: ...
bigcode/self-oss-instruct-sc2-concepts