content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def mcari(b3, b4, b5): """ Modified Chlorophyll Absorption in Reflectance Index \ (Daughtry et al. 2000). .. math:: MCARI = ((b5 - b4) - 0.2 * (b5 - b3)) * (b5 / b4) :param b3: Green. :type b3: numpy.ndarray or float :param b4: Red. :type b4: numpy.ndarray or float :param b5: Red-e...
827157f808afedef492b299f64cac6dda64f95c6
664,505
def get_object_or_none(model_class, name): """ Returns the object or None. """ try: return model_class.objects.get(name=name) except model_class.DoesNotExist: return None
72e6af4f8de00095b4f04427e5316add8c82b362
664,506
def _scale_size(size, scale): """Rescale a size by a ratio. Args: size (tuple[int]): (w, h). scale (float): Scaling factor. Returns: tuple[int]: scaled size. """ w, h = size return int(w * float(scale) + 0.5), int(h * float(scale) + 0.5)
878f7646c1dd0f545a406b758fa45d5bc1a316cf
664,510
def remove_digits(s): """ Returns a string with all digits removed. """ return ''.join(filter(lambda x: not x.isdigit(), s))
42abd1c827f48fe9c22c50aa37944b54781df448
664,513
def _ParseGnArgs(args_path): """Returns a list of normalized "key=value" strings.""" args = {} with open(args_path) as f: for l in f: # Strips #s even if within string literal. Not a problem in practice. parts = l.split('#')[0].split('=') if len(parts) != 2: continue args[parts...
8fa1dc16b4c114a37dbe8e1085938410d40fc302
664,516
import copy def merge_qedges(qedges1: dict, qedges2: dict) -> dict: """Merge qedges: the keys must be the same and the values must be the same. If a key is unique to one edges dict, then the edge will be concatenated to the new edges dictionary. If a particular key exists in both messages but the valu...
0c026e9529f6d66cdec168aa4594df521176a8a4
664,519
def rekey_map(mapping, replacements): """Given an iterable of destination/source pairs in replacements, create a new dict that is the same as the original except for the new key names.""" result = dict(mapping) for dst, src in replacements: value = result[src] result[dst] = value ...
3518f824b31949cc913c4a02ba9537929224765f
664,520
def parseOperator(value): """ Returns a search operator based on the type of the value to match on. :param value: to match in the search. :return: operator to use for the type of value. """ if type(value) == str: return " LIKE " else: return "="
6a82551878b1733db8c08424acf8d8f9a49bcb61
664,523
def unique_list(lst): """Make a list unique, retaining order of initial appearance.""" uniq = [] for item in lst: if item not in uniq: uniq.append(item) return uniq
8710247b83deccbdd6cff7757981bd30b9e874c5
664,526
def get_filenames_add_username(files, username): """ Adds the username to the end of a file name :param files: List of file names :param username: Username to append :return: filename with appended username """ filenames = [] for file in files: filenames.append(file + username...
acf376ab3447f16448b0d6f4cc3e745091d2f84f
664,529
def sortedby(item_list, key_list, reverse=False): """ sorts ``item_list`` using key_list Args: list_ (list): list to sort key_list (list): list to sort by reverse (bool): sort order is descending (largest first) if reverse is True else acscending (smallest first)...
8efca95c32256e3f7b96c9e101f3d7b596bb572f
664,531
def FWHMgeom2FWHMeff(FWHMgeom): """ Convert FWHMgeom to FWHMeff. This conversion was calculated by Bo Xin and Zeljko Ivezic (and will be in an update on the LSE-40 and overview papers). Parameters ---------- FWHMgeom: float The geometric FWHM value, as measured from a typical PSF pr...
882345c03c5e8c2fa789ff796f0f4261c883c8e7
664,533
def selector(selection_string: str, options: "list[str]", default = None) -> str: """ Asks the user for an option within a list of provided options and an optional default and returns their response """ while True: if default: input_string = f"{selection_string} ({', '.join(options)}...
6f712b433762bdf6e198df05ef181700d3b83bfd
664,534
def first(x): """Returns the first time step of all sequences in x.""" return x.dimshuffle((1,0,2))[0]
f31785f01d271fce5bf38f1c18df5cf7e38333a8
664,535
import torch def exact_gaussian_kernel(x1, x2): """Computes exact Gaussian kernel value(s) for tensors x1 and x2.""" x1 = torch.tensor(x1, dtype=torch.float32) x2 = torch.tensor(x2, dtype=torch.float32) x1_squared = torch.sum(x1 ** 2, list(range(1, len(x1.shape)))) x2_squared = torch.sum(x2 ** 2, ...
cb80d07328cdc06c9509df8add93be2a30a9a1df
664,540
def get_depth(node): """ Helper function to get depth of node from root """ depth = 0 while node.parent: node = node.parent depth += 1 return depth
8e2cc2142af1f6a34cdf25d8eae34b2956d0ca1d
664,542
def parametrization_name_func(func_name, kwargs): """ Method name generator for parametrized testcases. >>> import collections >>> parametrization_name_func('test_method', collections.OrderedDict(('foo', 5), ('bar', 10))) 'test_method__foo_5__bar_10' :param func_...
c9b2092a2e7eab80f3ec44733f03df5a2a0d1931
664,544
def union(root1, root2): """Perform a weighted union between root1 and root2. Args: root1 (Root): root of the first cluster in the union root2 (Root): root of the second cluster in the union Returns: NoneType or (Root, Root): If root1 and root2 are same, returns None; e...
c3c7b744fceb8605d280154f7ec7fe83052dddf5
664,547
def dispatch(result): """DB query result parser""" return [row for row in result]
fddf04544a887598f1debf075d5655e57077b1b3
664,550
def is_vcs_link(ireq): """ Returns whether an InstallRequirement is a version control link. """ return ireq.link is not None and not ireq.link.is_artifact
04035e09b9bca224bb2f0d7a3b9ffbe0c0bd2528
664,552
def option7(current_person): """The children of a person can printed using this function. Parameters: current_person: The current Person object. Returns: The current Person object. """ ch_lst = current_person.get_children() if len(ch_lst) == 0: print(f"No children f...
34cf67473233f9c79e7f1040fdf27686dd543e38
664,554
def disp(c, domain=True): """ Create a string formatted list of the curve's x-values if domain is True, otherwise y-values. >>> c = pydvif.span(1, 10) >>> yvalues = pydvif.disp(c, False) :param c: The given curve :type curvelist: Curve :param domain: if True, display the x-values of the c...
8bad553c92cd1ea45e341a6382377eb7137bfe99
664,555
def is_model_class(val) -> bool: """Return whether the parameter is a SQLAlchemy model class.""" return hasattr(val, '__base__') and hasattr(val, '__table__')
2e7cc71a891f1a394d2ba3ff4273bdb5fd4e4995
664,557
def get_range(value): """ Return the range for under or over limit message """ if (value & 4) == 4: return '80 - 130' elif (value & 3) == 3: return '60 - 110' elif (value & 2) == 2: return '50 - 100' elif (value & 1) == 1: return '30 - 80' else : return '...
fc33f45596b88e610b502f2a5d23a8fca5cb6b71
664,559
import re def _escape(line): """ Escape the syntax-breaking characters. """ line = line.replace('[', r'\[').replace(']', r'\]') line = re.sub('\'', '', line) # ' is unescapable afaik return line
8b43b7ddf42af68866eb81fdf91036d28489f897
664,561
def build_message(attr_name, val1, val2, details=""): """ Build error message for is_has_traits_almost_equal and is_val_almost_equal to return. """ type1 = type(val1) type2 = type(val2) msg = "Different {} {}. Types: {} vs {}. Values: \n{} \nvs \n{}" msg = msg.format(attr_name, details, type...
e760602531da9fc56ea1619202bfed7af1251558
664,563
def string_to_number(byte_repr_str): """ Args: byte_repr_str (str): e.g. 100MB, 10Kb; float is not allowed Returns: num (int): bytes """ is_parsing_unit = False num = 0 for ch in byte_repr_str: if ch.isdigit(): assert is_parsing_unit is False n...
4f82ba2acf2af5d7611e5448a5f78c7fe48da9cb
664,564
def read_article(file_name): """ Reads the Text file, and coverts them into sentences. :param file_name: Path of text file (line 12) :return: sentences """ file = open(file_name, 'r', encoding="utf-8") filedata = file.readlines() article = filedata[0].split(". ") sentences = [] ...
863bebfdf07e419abeb7be206e88259cc39014f7
664,565
def subset_sum_squeeze(data, subset={}, sum_dims=None, squeeze=False): """ Take an xarray DataArray and apply indexing, summing and squeezing, to prepare it for analysis. Parameters ---------- data : xarray DataArray A Calliope model data variable, either input or output, which has been...
182c8ddab3642c5fe9bec8520cbc5badb43b8f4e
664,566
def find_root_node(program_tree): """Find root program.""" return [program for program in program_tree if not program_tree[program]][0]
5b7cbc9b317d80edaa6082d7ebce3f7e127be200
664,570
def create_stream_size_map(stream_indices): """ Creates a map from stream name to stream size from the indices table. :param stream_indices: The stream indices table. :return: The map. """ return {pair[0]: len(pair[1]) for pair in stream_indices}
e8ef75da347d6e509bd6f25b3ccf88492d0260f1
664,573
import string import random def generate_key(key_length: int = 16, key_pattern: str = "x#x#"): """ generates a unique activation key with a length and a pattern key_length: length of the key (default 16) key_pattern: set of x's and #'s in a string (default "x#x#") "x": random letter "#": rando...
59364ca45c714d9e1e119561e8ec0b8a08e868f7
664,574
def _is_name_start(css, pos): """Return true if the given character is a name-start code point.""" # https://www.w3.org/TR/css-syntax-3/#name-start-code-point c = css[pos] return ( c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_' or ord(c) > 0x7F)
95fee9bbc2edfe0e61cbd145c1fb3b2a2ff1deef
664,576
import torch def nearest_neighbor_grad( averaged_grad, embedding_matrix, trigger_token_ids, tree, step_size, increase_loss=False, num_candidates=1, ): """ Takes a small step in the direction of the averaged_grad and finds the nearest vector in the embedding matrix using a kd-tr...
6c1c6ab80769a7942fed28c856c3796965a823f4
664,578
def validate_timestamp(val): """ Returns a boolean indication that a field is a valid timestamp - a floating point number representing the time in seconds since the Epoch (so called POSIX time, see https://en.wikipedia.org/wiki/Unix_time). """ return (isinstance(val, float) and val >= 0.0)
d2a47e448c461437f913abd531bcd84df171b6d5
664,579
def TDict(val): """Checks if the given value is a dictionary. """ return isinstance(val, dict)
73675d919a3d6fe192e76768b840495de48a5b25
664,581
from typing import OrderedDict def invert(mapper): """Invert a dict of lists preserving the order.""" inverse = OrderedDict() for k, v in mapper.items(): for i in v: inverse[i] = k return inverse
0cd15a56762b36a774cb91b711f5d893da62de1f
664,585
import socket import struct def inet_aton(addr): """Convert an IP addr in IPv4 dot notation into an int. addr IP address as a string returns integer """ b = socket.inet_aton(addr) return struct.unpack('!I', b)[0]
de8a09f484dae318353198ee4f93d9d8e6b597fe
664,588
def validate_nodes_number(nodes_number: int) -> int: """ Check whether a number of nodes is sufficient to detrend the data. Parameters ---------- nodes_number : int The number of nodes. Returns ------- int The number of nodes. Raises ------ ValueError ...
333b08daba41ef11a18a5ff0dc03af8fc429b99b
664,590
def sum_of_all(list_of_nums: list): """adds all numbers in a list together and returns the sum""" sum_of_nums = 0 for num in list_of_nums: sum_of_nums += num print(sum_of_nums) return sum_of_nums
a91ddda3294eb2d0e90f95d5027397a8bd5ba623
664,591
def link_topics_and_weightings(topic_words, topic_words_weighting): """ Pair every words with their weightings for topics into tuples of (), for each topic. :param topic_words: a 2D array of shape [topics, top_words] :param topic_words_weighting: a 2D array of shape [topics, top_words_weightings] :...
6b751c92fd36c623946819ddcc24c63adbdb082c
664,592
def clean_caption(caption): """Removes unnecessary parts of an Instagram post caption It removes all the hashtags and converts tags in plain text (@marco97pa --> marco97pa) Args: caption: a text Returns: the same caption without hashtags and tags """ clean = "" words = capti...
947cbce981d29a07a1528004dd15f5a574529e3a
664,593
import pickle def load_goal_set(goal_file_path): """ Utility method to load the user goals # Arguments: - goal_file_path: the path to the user goals file """ # Read all goals all_goal_set = pickle.load(open(goal_file_path, 'rb')) # Initialize and create the list of all...
397980aa15a9135be006ed67ccc7613f385862f1
664,596
def rec_mergeSort(array): """ Perform merge sort by recursively splitting array into halves until all the values are separated then do a piece wise comparason to fill the array in order """ # check if array is none if len(array) > 1: # find mid index of list mid = len(array) // 2...
102d924305fe9c801f4b3db15f714c66bfe18bbd
664,597
def is_line_continuation(line): """Determine whether L{line} has a line continuation marker. .properties files can be terminated with a backslash (\\) indicating that the 'value' continues on the next line. Continuation is only valid if there are an odd number of backslashses (an even number woul...
fea5d0063c31a82df1dd29b4ad9eea304689fee6
664,601
def get_skip_initial_samples_min(post_proc_args): """ Function iterates over a list of arguments of the form ["plot_all_individual_cdfs", "visualise_traceworkload", "skipmins_3"] searches for "skipmins_3" and returns 3 in this case. This parameter indicates how many minutes to skip from the ycsb results...
a7fd0007a0ad349a55fd5490fe4baec0c76ab14d
664,602
def duration_to_string(value): """Converts the given timedelta into an appropriate ISO-8601 duration format for JSON. Only handles positive durations correctly. Fractional seconds are rounded. :param value: The timedelta to convert :type value: :class:`datetime.timedelta` :returns: The ISO-8601 dur...
06bc74c30de00ac223c208db06f0b48cd0cb2ad5
664,603
def lookup_prev_stage_start(stage_boundaries, t): """ Returns the previous stage start timestamp from a list/set of stage boundaries and current time. """ return max([0] + [x for x in stage_boundaries if x <= t])
c897431404533ba07e5e160b6688e6531bedf320
664,607
import logging def get_repo_path(ont_obj): """ Extract the repository path for the given object """ repo_path = None if 'repository' in ont_obj: repo_path = ont_obj['repository'] elif 'tracker' in ont_obj: tracker = ont_obj['tracker'] if tracker is not None and 'github' in tracker: repo_...
12c227f862fec91b4483a68328fe882bc778004a
664,608
import torch def sentence_emb(inp_token_embeddings, n=4): """ Adds the last n layers of each token and stacks all the input token representations except the first and last ones. It considers that the first and last tokens are special BERT tokens ([CLS] and [SEP]) and it drops them within the function ...
5d625c8e1f0cf26a921e190da7ff8bd9d111ac31
664,612
import struct def unpack_int(string): """Read an n-byte big-endian integer from a byte string.""" (ret,) = struct.unpack_from('>I', b'\x00' * (4 - len(string)) + string) return ret
d0d3b14e006977f23c21f1953df0b210a79e2ca4
664,613
import struct def timestamp_to_bytes(t): """Convert timestamp to 96 bit representation Bits 0 - 63 are big endian two's complement encoded :attr:`Timestamp.s` and bits 64 - 95 are big endian two's complement encoded :attr:`Timestamp.us`. Args: t (Timestamp): timestamp Returns: b...
1d3c72706ca1216bd611ec323bd624f023de6d6f
664,614
def lookup(stmt, embeddings, dictionary): """ Look up a statement's embedded vector in the embedding matrix :param stmt: statement to be looked up (string) :param embeddings: embedding matrix :param dictionary: [keys=statement, values==statement index] :return: embedded vector """ return...
b7dc20092618dbbffb75941c7ab04efdc7af16c7
664,615
def search_entities(raw_text_string, search): """Searches for known entities in a string. Helper function for construct_entity_conet(). Iterates over a list of entities and looks to see if they are present in a given text string. If they are, then it will append the entity to a list for each te...
13e1a424154c54099bbd40ad8b9615cde5f0d99b
664,616
def int_list_to_string(intli, sep=''): """整数列表转字符串 :param intli: :param sep: :return: >>> int_list_to_string([1,2]) '\\x01\\x02' """ return sep.join([chr(n) for n in intli])
10fe03ab2ddb1a5602e816dac398e6ce57fca082
664,621
def sources_and_sinks( data, enforce_earliest_start=False ): """ Calculates all sources and sinks in a given dataset. :param list data: a list of :obj:`decitala.search.Extraction` objects. :param bool enforce_earliest_start: whether to require that all sources begin at the earliest detected onset. ...
d869db3f0a9b330faa99cf63ddcef8168637fafb
664,626
def underscore_to_camelcase(s): """ Convert lowercase_with_underscore names to CamelCase. """ return ''.join(x.capitalize() or '_' for x in s.split('_'))
8de189007ac25b53037cb17e267ec4b81ee80f8f
664,628
def pixel_wise_boundary_precision_recall(pred, gt): """Evaluate voxel prediction accuracy against a ground truth. Parameters ---------- pred : np.ndarray of int or bool, arbitrary shape The voxel-wise discrete prediction. 1 for boundary, 0 for non-boundary. gt : np.ndarray of int or bool, s...
9a39bbcfbc8ca8e7838ea8713636cbd8a66b5186
664,629
import itertools def flatten(list_, gen=False): """ Flatten a list. """ if gen: return itertools.chain(*list_) else: return list(flatten(list_=list_, gen=True))
b16729ecb0779ce9c3480ea75b8d734c87da65e1
664,633
def JsBoolString(bool_value): """Write boolean value as javascript boolean.""" if bool_value: return "true" else: return "false"
0e2a6d5d005294c8243ab5702374a65a65b100dd
664,636
def split_tracks(midfile): """Break file into different tracks and store them separately :param midfile: MidiFile object :return: meta messages, instrument messages """ meta_messages = [] instrument_messages = [] for i, track in enumerate(midfile.tracks): temp_meta_messages = [] ...
50ec899161797dffaf8bc9a838efe48beabe43ec
664,637
import requests def get_node(name, api_url, headers, validate_certs=True): """Returns a dict containing API results for the node if found. Returns None if not just one node is found """ url = "{}/v3/nodes?name={}".format(api_url, name) node_search = requests.get(url, headers=headers, verify=valid...
d6df2228d3a49cf82f2f38caff3204a738ea5547
664,642
def get_max_operand_size(operands): """ Given the list of named tuples containing the operand value and bit width, determine the largest bit width. :param operands: list of Operand objects :return: largest operand width """ return max(operand.width for operand in operands)
876c991b90f70ca349a18230ec74b4fb431af909
664,645
def _read_file_data(filepath): """Read file data. :param filepath: The file path. :return: The file contents. """ data = open(filepath, 'rb').read() return data
55481b78b9ab3f9340790458cb33955f2896f273
664,647
from typing import Optional from typing import Dict import json def load_result_file(eval_file) -> Optional[Dict]: """Loads the results data from a submitted file. If the file cannot be read, returns None. """ try: with open(eval_file, 'r') as f: result = json.load(f) ...
d8ba0b8bf23763e7a5fe33e2ac8cfd7a0a6d87de
664,648
def NSE(y_pred, y_true): """ Calculate the Nash-Sutcliffe efficiency coefficient. """ return 1 - sum((y_pred - y_true) ** 2) / sum((y_true - y_true.mean()) ** 2)
f4098e3add7228ab999f525724cd1922232ac3b2
664,654
def sort_params(model, params): """Sort parameters to be consistent with the model's parameter order""" return [p for p in model.parameters if p in params]
295e9defae5311b596b53265ddd38fc0b3605c02
664,656
def check_args(args): """See if we got our minimal set of valid arguments.""" ok = True message = "" if not args.output_root : ok = False message += "Didn't get directory for output (--output-root) " return([ok,message])
ce4c45b146a281057201229d461542d942d6291a
664,663
def unflatten1(flat_list, reverse_list): """Rebuilds unflat list from invertible_flatten1 Args: flat_list (list): the flattened list reverse_list (list): the list which undoes flattenting Returns: unflat_list2: original nested list SeeAlso: invertible_flatten1 ...
4f583f0c29db32865403be4a17aabcdecef4e2ce
664,664
import zipfile def zipFileIsGood(filePath): """ Function to test if a ZIP file is good or bad @param filePath the zip file to be tested @return True if the ZIP file is good. False otherwise. """ ret = True try: the_zip_file = zipfile.ZipFile(filePath) badFile ...
5f856cd40f0767b44df362c097aab2b09faf637c
664,665
def qt4_to_mpl_color(color): """ Convert a QColor object into a string that matplotlib understands Note: This ignores opacity :param color: QColor instance *Returns* A hex string describing that color """ hexid = color.name() return str(hexid)
3b885562a7e4c1889c14291dfa047715fdf9a440
664,666
def public(fun, scope=None): """ Functions that allow any client access, including those that haven't logged in should be wrapped in this decorator. :param fun: A REST endpoint. :type fun: callable :param scope: The scope or list of scopes required for this token. :type scope: str or list o...
b3146486c5d335117d9447605b0c9dc0bfdfaeb4
664,673
def check_key(request): """ Check to see if we already have an access_key stored, if we do then we have already gone through OAuth. If not then we haven't and we probably need to. """ try: access_key = request.session.get('oauth_token', None) if not access_key: return...
da8d2a10642ceec36bfd6cdfec63c516c38fa2cb
664,675
def divide_separate_words(X): """ As part of processing, some words obviously need to be separated. :param X: a data matrix: a list wrapping a list of strings, with each sublist being a sentence. :return: >>> divide_separate_words([['ita vero'], ['quid', 'est', 'veritas']]) [['ita', 'vero'], ['q...
69a6887f562629d2b82d3302fa61ce3c7a7dd791
664,677
def resize(image, size, resize_image_pl, resize_shape_pl, resize_op, session): """ Performs resizing of image. :param image: Image to resize. :param size: Size of resized image. :param resize_image_pl: Resize operation input tensor. :param resize_shape_pl: Resize operation shape input t...
943d158ee4ca21fb039e388bb8b36bc5d4434798
664,678
def ilcode(msg: str): """Format to inline markdown code""" return f'`{msg}`'
64205d05c9260a94cc18dd0c1bc08663ad11d6ec
664,680
def opaque_legend(ax, fontsize=None, handler_map=None): """ Calls legend, and sets all the legend colors opacity to 100%. Returns the legend handle. """ leg = ax.legend(fontsize=fontsize, handler_map=handler_map) for lh in leg.legendHandles: fc_arr = lh.get_fc().copy() fc_arr[:, ...
585188d19062a050878208133a06f6e93f8928fd
664,682
def _requirement_to_str_lowercase_name(requirement): """ Formats a packaging.requirements.Requirement with a lowercase name. This is simply a copy of https://github.com/pypa/packaging/blob/16.8/packaging/requirements.py#L109-L124 modified to lowercase the dependency name. Previously, we were i...
83a7d1b825d32456066dfe9b0e79fa08a2ed9444
664,683
import re def to_snake_case(value: str) -> str: """ Convert camel case string to snake case :param value: string :return: string """ first_underscore = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', value) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', first_underscore).lower()
9ca9eb70dfcbce50b99a206442426492f1c99fd1
664,684
def alnum(string, alt='_', trim=False, single=False): """Replace non alpha numeric characters with *alt*. If *trim* is **True** remove preceding and trailing *arg* characters. If *single* is **True**, contain only a single joining *alt* character. """ result = '' multi = not bool(single) prev...
8cff96608f0760e74fcdceae9d1d0d213825a81d
664,687
def is_singleline_comment_start(code, idx=0): """Position in string starts a one-line comment.""" return idx >= 0 and idx+2 <= len(code) and code[idx:idx+2] == '//'
21a4b65ec923c5a87e510614f88bbb93ccff87b3
664,689
def unique(elements): """ Removes duplicate elements from a list of elements. """ return list(set(elements))
831983be502d37c3900f4dad36b47773380fe740
664,694
def get_route_policy( self, ne_id: str, cached: bool, ) -> dict: """Get route policy configurations from Edge Connect appliance .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - routePolicy - GET - GET /route...
5b6c7654602c198570c710492c311eb9de51a024
664,700
def change_categorical_value(df, new_name, old_values, col): """ replace categorical values in `old_values` with `new_name` in given `col` of `df` Parameters ---------- df: pandas.DataFrame new_name: STR old_values: LIST col: STR Returns ------- DataFrame ...
09e856ec0fe0f1206ad611d451a8921ea9eabedd
664,703
def insert(s, c, pos): """ Returns the string s with character c inserted into position pos. c can also be a string. If the position given is 0, c will be placed at the beginning of the string. If the position given is len(s), c will be placed at the end of the string. If pos is anything beyond thes...
6f6cc81401de1bee5a1a1dfa5ddf1155aa94b625
664,708
import torch from typing import Union def first_element(x: torch.Tensor, element: Union[int, float], dim: int = 1) -> torch.Tensor: """ Return indices of first occurence of element in x. If not found, return length of x along dim. Based on https://discuss.pytorch.org/t/first-nonzero-index/24769/9 Ex...
22b508463b3b82684c4d25679d4579b34a0cdbda
664,719
import re def check_legitimate_ver(version): """ This function check if the version is legitimate, only digits and dot. :param version: str :return: boolean """ return re.match("^[0-9.]+$", version)
550e65b8deeb4c49562ace1cbf14b89c2d0818e5
664,723
def insertion_sort(array): """ Insertion Sort Complexity: O(N^2) """ array_len = len(array) for k in range(array_len): temp = array[k] i = k while i > 0 and temp < array[i-1]: array[i] = array[i-1] i -= 1 array[i] = temp return array
09a9e5be73e23f42ee04129f979516e9e556a908
664,724
from typing import Tuple def find_padding_for_stride( image_height: int, image_width: int, max_stride: int ) -> Tuple[int, int]: """Compute padding required to ensure image is divisible by a stride. This function is useful for determining how to pad images such that they will not have issues with div...
b181a75c38037c5efaf063772dd14b7be75ac48d
664,729
def calcBounds(array): """Calculate the bounding rectangle of a 2D points array. Args: array: A sequence of 2D tuples. Returns: A four-item tuple representing the bounding rectangle ``(xMin, yMin, xMax, yMax)``. """ if len(array) == 0: return 0, 0, 0, 0 xs = [x for x, y...
b25f75a793c8cc2667b17c76bc0339a1da11af49
664,731
def set_title(title): """ print title in a square box To enhance the readability of the tests, this function prints in the terminal teh string title in a square box. Args: title (str): the string """ space = " " title = space + title + space h_line = '+' for character in...
7090853f7b3e33095786b61b851c27d63199b57c
664,732
def _get_enz_states(er_mech: str) -> list: """ Given a string with the enzyme mechanism written as a sequence of elementary reactions produces a list with the enzyme state numbers and metabolites that bind/unbind to the respective enzyme states. Args: er_mech: string with elementary reactions t...
0a2be33ce4a48a558b2fd9a0ef66d00742f45d76
664,733
def parse_stage_config(stage_cfg): """Parse config of STPP for three stages. Args: stage_cfg (int | tuple[int]): Config of structured temporal pyramid pooling. Returns: tuple[tuple[int], int]: Config of structured temporal pyramid pooling and total numbe...
b7214f0822439cf069717574920e2653cd962178
664,734
def redis_update_load_data_button(n): """ Let the user load the DRF data once they have chosen an input directory """ if n < 1: return True return False
63727a1e9da4165c0dad9c999be20389b4c374f3
664,738
import pathlib def get_config_directory() -> pathlib.Path: """ Get the path to the config directory based off its location to this file. Up two directories, then into config :return: Path pointing to the config directory """ return pathlib.Path(__file__).absolute().parent.parent.joinpath("config...
e4ab249e42db67117884746514c8e21a8d36a658
664,741
def egcd(a, b): """extended GCD returns: (s, t, gcd) as a*s + b*t == gcd >>> s, t, gcd = egcd(a, b) >>> assert a % gcd == 0 and b % gcd == 0 >>> assert a * s + b * t == gcd """ s0, s1, t0, t1 = 1, 0, 0, 1 while b > 0: q, r = divmod(a, b) a, b = b, r s0, s1, t0, t1...
75f74a6fdfe03d512f88c81fa81a5f1bd4e91206
664,742
def english_to_persian_number(number): """ converts a number from English alphabet to Persian alphabet. It is used because some students use Persian alphabet in their student number and for each student number, we must check both English and Persian alphabet. :param number: int or str Number in...
90dc5963d0c54e4928701a8f04b810c0021713e5
664,745
def _GetPackageName(module_name): """Returns package name for given module name.""" last_dot_idx = module_name.rfind('.') if last_dot_idx > 0: return module_name[:last_dot_idx] return ''
eebbafe9a8e3014eae9279ad982794483e0c5515
664,746
def nldpost(self, label="", key="", fileid="", prefix="", **kwargs): """Gets element component information from nonlinear diagnostic files. APDL Command: NLDPOST Parameters ---------- label Specifies the type of command operation: EFLG - Element flag for nonlinear diagnostics. ...
f5209920bc3e2d5a799df66a0a5ade4be32f79ce
664,747
def recursive_min(nxs): """ Find the maximum in a recursive structure of lists within other lists. Precondition: No lists or sublists are empty. """ smallest = None first_time = True for e in nxs: if type(e) == type([]): val = recursive_min(e) else: ...
5bf37edd7793c9202265c9ab7ad83379eb2b0b26
664,748