content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def reduce_vector(V, p): """ Reduces a vector over finite field. """ for i, element in enumerate(V): V[i] = element % p return V
ce67f14ff37e8c3bbed2dbcab173cf79be976e42
620,221
from pathlib import Path def get_doxygen_default_conf_path() -> Path: """Get the path to the doxygen configuration file included with Documenteer. Returns ------- defaults_path : `pathlib.Path` Path the the ``doxygen.defaults.conf`` file included with Documenteer as a basis for Sc...
e76149e4ef357a78edc86c85165d39307f64d1cf
620,222
def _line_labels(last, pos='value', sep=1, delta=0.1, max_iters=20): """Calculate y-position of line labels, minimizing label overlap.""" labels = last.copy() for _ in range(max_iters): changed = False for i, row_i in labels.iterrows(): for j, row_j in labels.iterrows(): if j <= i: continue ...
ef7d400c94c0f4280cd986ab082605266ef44aa1
620,225
def strip_suffixes(s, suffixes): """ Helper function to remove suffixes from given string. At most, a single suffix is removed to avoid removing portions of the string that were not originally at its end. :param str s: String to operate on :param iter<str> tokens: Iterable of suffix strings ...
f3b2fec528794fa3941c0b000ed3cc2fd970f394
620,229
def split_by_two_strings(line, str1, str2): """Split the input line into three parts separated by two given strings.""" # Start of second part in the input string. i1 = line.index(str1) + len(str1) # End of second part in the input string. i2 = line.index(str2) # Now we know where the second p...
4883075e61185b9bfc0490586cb08c66db603a7a
620,233
import re import itertools def replace_wcs(hdu, wcs): """Replaces WCS information in the header. Removes the current WCS information in the input `~astropy.io.fits.ImageHDU` and replace it with new one. Parameters ---------- hdu : `~astropy.io.fits.ImageHDU`: The `~astropy.io.fits.Im...
e027dae3d3ba16e75ff4ced9be764f62e0464ccc
620,235
def get_last_build_number(job_info): """Given a job info dict, returns the last build number.""" if job_info['lastCompletedBuild']: return job_info['lastCompletedBuild']['number'] else: return 0
e005c64c732d85a516fae46863f6a2aeac04dd4f
620,236
def _get_comments_request(post, sort_mode, max_depth, max_breadth): """ Used to build the request string used by :func:`get_comments`. :param str post: The unique id of a Post from which Comments will be returned. :param str sort_mode: The order that the Posts will be sorted by. Options are: "...
cc5ef337d7d87e3c994be0b04b5c69dede9b1af5
620,238
def create_word_set() -> set: """ Generate a set of words from a unix based word file """ word_list = [] with open("/usr/share/dict/words", "r") as word_file: for line in word_file: word_list.append(line.strip()) return set(word_list)
95441a7a1b0241ccead0e393c41d80953e6f5be1
620,244
def normalize_x_data(x_data): """ This function will normalize the training and testing images. Parameters ---------- x_data : ndarray The training and/or testing images. Returns ------- numpy.ndarray A normalized training and/or testing image values. """ max_va...
5a63e82f08f436cc0048709460668d7efeb6a9b4
620,245
def renders(col_name): """ Use this decorator to map your custom Model properties to actual Model db properties. As an example:: class MyModel(Model): id = Column(Integer, primary_key=True) name = Column(String(50), unique = True, nullable=False) ...
7128e0dac6d2c0b1519729e708fe7cb1b14c3596
620,247
def get_entity_id_attribute(self, entity, id_attribute_name = "object_id"): """ Retrieves the id attribute (value) from the given entity that may be both an entity object or an entity map represented by a dictionary. In case the given entity is a map the id attribute name value is used to retrieve t...
f02a443080efd319a9f9fe31175b84707493179c
620,248
import shutil def check_dependencies(*executables, raise_error=True): """Check if the given executables are existing in $PATH. :param tuple executables: A tuple of executables to check for their existence in $PATH. Each element of the tuple can be either a string (e. g. `pdfimages`) or a itself a...
e6acf891a0ffa803a472eb7e9eaa9dd21d7377e9
620,249
def get_module_by_name(model, module_name): """ Get a module specified by its module name Parameters ---------- model : pytorch model the pytorch model from which to get its module module_name : str the name of the required module Returns ------- module, module ...
00bb386ae78e4efdadae7b8b699decf95235e965
620,251
import torch def collate_fn(data): """Pad data in a batch. Parameters ---------- data : list((tensor, int), ) data and label in a batch Returns ------- tuple(tensor, tensor) """ max_len = max([i[0].shape[0] for i in data]) labels = torch.tensor([i[1] for i in data], dty...
e8581fb7d4751de9d5f5ee8f63ff864e5efaa58f
620,256
import string def get_number(text): """ Return the number at the start of text, as a string. text -- string starting with a number """ char = 0 number = "" while char < len(text): if text[char] in string.digits + "-": number = number + text[char] char += 1 ...
e94954d3e9de09dea6ffe0ec0ae39691f3385490
620,264
def manhattenPath(position1, position2): """ calculates grid deltas between two positions relative to first position :param position1: :param position2: :return: dx (int), dy (int) """ dx = position2[0] - position1[0] dy = position2[1] - position1[1] return dx, dy
580aea12c1b5643bcf0ba0ee6fb3d697c63fcf3b
620,265
def gather_columns(rule_name, columns, prefix, additions=None): """Build a list of all columns matching a prefix allong with potential additional rules.""" raw_rule_name = rule_name.split(".")[0] if additions is None: additions = [] # Reduce a pair of parens around a type back to itself. pa...
a77f992607197baa04df02c09c336ca110cc0d9c
620,267
def is_list_like(obj): """ Check whether a variable is a sequence other than a string. """ return hasattr(obj, '__iter__') and not isinstance(obj, str)
2759ed613aa1f4ac009623f98061b5660012b64d
620,271
def PHMS2RA (rast, sep=":"): """ Convert a right ascension string to degrees return RA in degrees * rast = RA string as "hh:mm:ss.s" * sep = sympol to use to separate components instead of ":" """ ################################################################ pp = rast.split(se...
9bc1fd4cf1029a43f01c7831fc829842be090530
620,272
def get_item_details(item): """ This function finds packgen details using item :param item: item is a string containing packgen content type :return: it returns dict of details of packgen. """ details = {'Estimated Time of Delivery':'Na','priority':'Na','cost':'Na','item':'Na'} if item == u...
546e095d104a3da1c75f825be030a8a41d60b219
620,273
def verify(df, check, *args, **kwargs): """ Generic verify. Assert that ``check(df, *args, **kwargs)`` is true. Parameters ========== df : DataFrame check : function Should take DataFrame and **kwargs. Returns bool Returns ======= df : DataFrame same as the inpu...
193b24e3678b13e2c737b090585243fc35a5fd86
620,276
import re def changeStrokeOpacity(text, opacity): """ Change all stroke opacities in a given string of text to the provided opacity. Returns the text with modifications made. """ newData = None regularExpression = re.compile(r'stroke-opacity:[0-9]*[.]?[0-9]+[;|"]') matchOb = regularExpres...
f8976bbf3fb4068d2ab1f45edd393f01784ab651
620,277
def find_bound_tuple(a, b, bounds): """If a and b are both included in a bounds tuple, return it. Otherwise return None. """ def inside(num, spanish): return num >= spanish[0] and num <= spanish[1] for span in bounds: if inside(a, span) and inside(b, span): retu...
30c5cf11fb27e61ede3a78ddfe663d167628169a
620,282
import re def fixChromName(name, orgn="medicago"): """ Convert quirky chromosome names encountered in different release files, which are very project specific, into a more general format. For example, in Medicago Convert a seqid like `Mt3.5.1_Chr1` to `chr1` `Mt3.5...
00d9cd69c1df10f88caaff32709eb4ea0a5c5b60
620,287
from pathlib import Path def _getname(infile): """ Get file names only. Examples -------- >>> _getname("drop/path/filename.txt") 'filename.txt' >>> _getname(["drop/path/filename.txt", "other/path/filename2.txt"]) ['filename.txt', 'filename2.txt'] """ if isinstance(infile, (...
2384a747a72ea28f107610bc4aa609096366c433
620,289
from pathlib import Path def guess_zarr_path(path): """Guess whether string path is part of a zarr hierarchy. Parameters ---------- path : str Path to a file or directory. Returns ------- bool Whether path is for zarr. >>> guess_zarr_path('dataset.zarr') True ...
fa19bd7e233d98bde90629fc36a0843e2f0c0ca2
620,290
def find_key(key_list, key): """Find the index of a key in a list of keys. This is a wrapper for the list method `index` that can search any interable (not just lists) and will return None if the key is not found. Parameters ---------- key_list : iterable key : object to be searched ...
c9ca8075e6abd0b4f026e6a3b7e6a6883cc66655
620,294
def get_worksheet_data(worksheet, data_range, expected_header=None): """Read a range of cells from a worksheet into a list of dictionaries treating the first row as a header. :param worksheet: a pygsheets Worksheet object :param data_range: cell range tuple, e.g. ('A', 'D'), ('A1', 'A17') :param ex...
b72b6220a6881a62864f646b7a6adc30f1088bbd
620,297
def remove_copies(data: list) -> list: """Creates a unique list of arrays given a list of arrays containing identical arrays. Param: data (list[list[float or int]]): a list of lists of comparable items Return arrays: the unique list with no repeated arrays """ arrays = [] f...
db9d74ea19d00856675d4c6c15b3e3ebda1c1982
620,300
def pick_bpart(df, bpart): """ Create a sub dataset of particular body part. :param df: dataframe to process :param bpart: body part to extract :return: trimmed dataframe """ if bpart == "all": return df return df[df["body_part"] == bpart].reset_index()
00d3d80f0e8614d0ee14345cd5e881a1738372b3
620,302
def _format_syntax_error_message(exception): """Returns a nicely formatted SyntaxError message that emulates what the Python interpreter outputs, e.g.: > File "raven.py", line 3 > st.write('Hello world!!')) > ^ > SyntaxError: invalid syntax Parameters -----...
af3526180539e1b7a3cdc7c8c89e3d05fee132a9
620,304
def get_facts(device): """ Determines ifd_style fact based on the personality. """ ifd_style = "CLASSIC" if device.facts["personality"] == "SWITCH": ifd_style = "SWITCH" elif device.facts["personality"] == "JDM": ifd_style = None return { "ifd_style": ifd_style, ...
febfcb49835276677744bbb8846679d88b646eae
620,305
def left_part_of(txt, sub_txt, n=1): """ Return the left part before the nth of sub_txt appeared in txt. :param txt: text :param sub_txt: separate text :param n: the nth of sub_txt(default:1) """ parts = txt.split(sub_txt) return sub_txt.join(parts[:n])
af99d668038d62581792612ec189d15104b31cbf
620,309
import random def random_query(allkeys, revealed): """Selects a uniform random range to query.""" (a,ac), (b,bc) = sorted(random.sample(allkeys, 2)) revealed.add(ac) revealed.add(bc) return a, b + 0.01
24ef87b83be87b2f429b6c70aca444de9e358db9
620,315
def str_to_bool(s: str): """Return a boolean for the given string, follows the same semantics systemd does.""" if s.lower() in ('1', 'yes', 'true', 'on'): return True elif s.lower() in ('0', 'no', 'false', 'off'): return False else: raise NotImplementedError(f"Unknown boolean val...
df5ea2e4b6aba3ee979668ea47e7c1b4ddebf324
620,316
def clamp(n, minn, maxn): """ Clamp a value 'n' within the range 'minn' and 'maxn'. :param n: value to be clamped :param minn: lower bound of clamp :param maxn: upper bound of clamp :returns: * **clamped_val** - value within the range of 'minn' and 'm...
6fbec6b92d88920a9959553d213d76367dbe22ae
620,318
import json import dataclasses import pytz from datetime import datetime def put_release(client, bucket, key, release): """ Upload a new release to S3. Arguments: client (botocore.client.S3): client for AWS S3. bucket (str): bucket's name. key (str): object's key. release ...
bc6b6958ccde277919b3118065dc259bbc4ca1be
620,319
from pathlib import Path def rename_file(source: Path, destination_path: Path): """ Helper function that renames file to reflect new path. If a file of the same name already exists in the destination folder, the file name is numbered and incremented until the filename is unique (prevents overwriting f...
50883047f359fc06cb367b663626096defbeef61
620,320
def clean(synonyms): """ Returns the deduped, sorted list of synonyms """ deduped_synonyms = list(set([s.strip() for s in synonyms])) deduped_synonyms.sort() return deduped_synonyms
bea7ffc850e343c0e0a53d7239d434831658e71f
620,321
def get_imag(input, input_type="linear", channels_axis=1): """Returns the imaginary components of the complex-valued input. Arguments --------- input : torch.Tensor Input tensor. input_type : str, (convolution, linear) (default "linear") channels_axis : int. Default 1. ...
168f2a89dd76cd0bfaa41eae1f8b4138832ecffc
620,322
def smooth(scalars, weight): """Smooth scalar array using some weight between [0, 1]. This is the tensorboard implementation For comparison with @ewma, see https://github.com/theRealSuperMario/notebook_collection Parameters ---------- scalars : np.array array of scalars weight : fl...
cb13ab5ea4eca45fd1cad6b86490dbd89b2b5b41
620,324
import string import random def random_string(choose_from=None, length=8): """ Return a random sequence of characters Args: choose_from (Sequence): he set of eligible characters - by default the set is string.ascii_lowercase + string.digits length (int): the length of the sequ...
4f2654eee76cc978e69e0b551ad9c31ca88eebde
620,331
def to_upper(word: str): """ Make the 'word' parameter uppercase :param word: string to be uppercase :return: uppercase string """ return word.upper()
d4c25391dfb40f5be187d4d8df6bab67a168fcb6
620,332
def dnsDomainLevels(host): """ :param str host: is the hostname from the URL. :return: the number (integer) of DNS domain levels (number of dots) in the hostname. :rtype: int """ return host.count('.')
5c466d89039e3efc59d1c8d21661b7ddaf93b46e
620,334
def extract_mentioned_users(text_string, remove_users=True): """ Extracts mentioned_users from a text_string :param text_string: String of text you wish to extract mentioned_users from :param remove_users: Boolean, if True it will remove the mentioned_users from the text_string :return: text_sting...
6e7c4d62ad9e1ddfc16d5ed63ed1caafacc22e4e
620,336
import requests def send_telegram_message(msg): """ Utility to send message to telegram groups """ base_url = "https://api.telegram.org/bot589160362:AAHEeNBIeh3m3RA07lANaDHovy874xNFi1g/sendMessage" chat_id_one = "-294841384" # Signal Testing chat_id_two = "-464227511" # Signal Development msg ...
54ce31860bdf5916924f8219cd13c296dd5e993f
620,337
import re def isPropVar(s): """ Check, whether the string s can be interpreted as a propositional variable. """ return re.fullmatch('[A-Za-z][A-Za-z0-9<>,]*', s)
d48f33005ee36ae631ff75d224b3be996fb9eee4
620,338
def is_bool(x): """Tests if something is a boolean.""" return isinstance(x, bool)
366ce2ac1252278c8aa774e81f2c2b3f30912d74
620,339
import json def parse_config(config_file=None): """ Read a set of JSON formatted configs and store as dictionary :param config_file: location of file with JSON formatted config :return: dictionary with messages/statuses """ config = {} if not config_file: return config buf = o...
4415f1938dc76fab694a72fb3a96e1fa8ff6d1ed
620,347
import torch def flatten_feature_map(feature_map): """ Flatten input tensor from [batch, y, x, f] to [batch, y*x*f] Args: feature_map: tensor with shape [batch, y, x, f] Returns: reshaped_map: tensor with shape [batch, y*x*f] """ map_shape = feature_map.get_shape() if(map_...
99dc93d7e0e21d19e8252c6a1106e208ac4937ec
620,349
def reverseComplement(read): """ Returns the reverse complemnt of read :param read: a string consisting of only 'A', 'T', 'C', 'G's """ complementDict = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'} return ''.join([complementDict[c] for c in read[::-1]])
d77836b5f75a70189303a1118a4c45493a9a2181
620,351
def convert(tree,fileName=None): """ Converts input files to be compatible with merge request #460: - Removes "all" node - Sets default variable names @ In, tree, xml.etree.ElementTree.ElementTree object, the contents of a RAVEN input file @ In, fileName, the name for the raven input file @O...
365610af53977709b217c73cf78983e87d00c376
620,360
def _get_nodes_mac_addresses(task, node): """Get all mac addresses for a node.""" for r in task.resources: if r.node.id == node['id']: return [p.address for p in r.ports]
46571e5f9295b885916197034c5cae1cb4482fa7
620,361
import time def timestamp_2_datetime(timestamp, fmt): """ 将时间戳转换成指定格式的日期字符串 :param timestamp: 原始时间戳 :param fmt: 时间格式 """ return time.strftime(fmt, time.localtime(timestamp))
01a69f4b2c40722fbca95150cfbde33713bcaffd
620,362
def user_directory_path(instance, filename): """ Obtain the upload path, including the filename. File will be uploaded to settings.MEDIA_ROOT/<username>/<filename> if user is authenticated, and to settings.MEDIA_ROOT/anon_usr/<filename> otherwise. instance: An instance of the model where the FileF...
4568d87754808e63e7a2fedfdee8ca0d8907c726
620,363
def client(app): """return an instance of the application's test client""" return app.test_client()
f0922adb71970f197723c434e0c662b5eeed7ddb
620,364
import logging def log_aucs(**aucs): """Log and tabulate AUCs given as nested dictionaries in the format '{model: {label: auc}}'""" def dashes(n): return '-' * n header = "{:<35} {:<20} {:<15}" row = "{:<35} {:<20} {:<15.10f}" width = 85 logging.info(dashes(width)) for auc_name, auc_value...
c53c5ac3f230570a49bef02dab79b79603750f40
620,365
import random import string def random_string(length): """Return a random string of a certain length.""" return "".join( random.SystemRandom().choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(length) )
a2c6e0c1ec2ac8ce79f2f37f5da085099bebe9e5
620,368
def slice_name_to_components( slice_name ): """ Decomposes a slice name into a map of its unique components. This is the inverse of build_slice_name(). Also handles slice_name's which have been converted into a path or URL as a prefix. Takes 1 argument: slice_name - String specifying the s...
d095c2190d2c308e4711512054dab5f03d393fdf
620,369
import ssl import asyncio import aiohttp async def get(session, url): """Wrapper for session.get() that returns None if the HTTP GET call failed. Args: session: url: Returns: 2-tup status_code: int body_str: str """ try: async with session....
57bf1873ab57e32275dcfbf0bea0f184b21fdce1
620,371
import re def text_cleanup(text): """ 1. Replace HTML tags with punctuations 2. Remove digits in given text as they would interfere 3. Remove single characters in given text 4. Reduce multiple spaces in given text to single space :param text: Raw article text :return: preprocessed art...
500831709671c50f2ab047314281acc4722455ed
620,373
def generate_valid_queue_entry(**overrides): """ This functions generate a valid queue entry. If you want to override the value, provide an object with the same property names """ return { "studentName": "Frinze", "studentNumber": "22711649", "unitCode": "CITS3403", "...
44eaecf0c22526800f2163bac5b253cbcb598a1e
620,384
def mkt_cap_format(x): """ Formats number to millions of dollars. Params: x (numeric, like int or float) the number to be formatted Example: mkt_cap_format(3000000) mkt_cap_format(4490000) """ return "${:.1f}M".format(x/1000000)
a18546ce28942625dfe991bd357b124a5f8b035b
620,388
import configparser def read_from_config_file(filepath: str): """ Read from the generated configparser file path, return the settings and the configparser object Parameters ---------- filepath absolute filepath to the configparser object Returns ------- configparser.ConfigPar...
ff595f3dee79c48207021e466892f13270f45fe9
620,389
def check_detection_overlap(gs, dd): """ Evaluates if two detections overlap Paramters --------- gs: list Gold standard detection [start,stop] dd: list Detector detection [start,stop] Returns ------- overlap: bool Whether two events overlap. """ ov...
af59564c268de9cf0d30d98a0fdba6cd0bac1232
620,394
def is_valid(sg, logger, args): """ Validate our args. :param sg: Shotgun API handle. :param logger: Logger instance. :param args: Any additional misc arguments passed through this plugin. :returns: True if plugin is valid, None if not. """ return True
7ff1920acf2ae561ad2005043cdcba0e815ee094
620,401
import requests from bs4 import BeautifulSoup import re def list_files(url, tag=''): """ Function to create a list of the NetCDF data files in the THREDDS catalog created by a request to the M2M system. :param url: URL to user's THREDDS catalog specific to a data request :param tag: regex pattern used...
8dee7e318604ed7208dafcad34e4d617c55bf927
620,403
import random def qubit_shot(i_mean: float, q_mean: float, i_std: float, q_std: float): """Creates a random IQ point using a Gaussian distribution. Args: i_mean: mean of I distribution q_mean: mean of Q distribution i_std: standard deviation of I distribution q_std: standard d...
51065f7b7a4ba4dd45039c96b5de17d19123d182
620,405
def _get_ndims(x): """Returns the number of dimensions of a TensorFlow Tensor or a numpy array like object. Both objects have a different method to get the number of dimensions. Numpy arrays have a .ndim attribute, whereas TensorFlow tensors have a .shape.ndims and a .rank attribute. Args: x: ...
5001b8c89e17ce9511b20bccea5ad357dd52a3ca
620,406
def MergeResultsFromMultipleFiles(results_by_file, info_levels): """Merge multiple results to show occurrences in files and range of values. Args: results_by_file: A dict of check results indexed by file name. info_levels: A list of report levels to merge. E.g., ['warning', 'error'] Returns: A dict ...
cacaea2e5df8f8db89db792ccf9b0be6eeec3760
620,409
def print_adjacent_bases(bases, sequence): """ Print a summary of the bases preceding removed adapter sequences. Print a warning if one of the bases is overrepresented and there are at least 20 preceding bases available. Return whether a warning was printed. """ total = sum(bases.values()) if total == 0: ret...
7a714c8ef1304804a5a1e03e0adba2d3bfed5586
620,410
import itertools def deque_slice(deque, start, end=-1): """ return a sliced part of a deque as a list """ if end == -1: end = len(deque) return list(itertools.islice(deque, start, end))
b986adffec5054e73863b2a0a38b6e13d2e8e103
620,418
import functools def get_n_trainable_parameters(model): """This funtion calculates the number of trainable parameters of the model Arguments: model {nn.Module} -- model Returns: int -- the number of trainable parameters of the model """ cnt = 0 for param in list(...
6bd819a805f53e24b36b6ec8d78ef3a03f32d608
620,419
def is_even(number: int) -> bool: """ Test if a number is a even number. :param number: the number to be checked. :return: True if the number is even, otherwise False. >>> is_even(-1) False >>> is_even(-2) True >>> is_even(0) True >>> is_even(3) False >>> is_even(4) ...
f83f08394b30c04a30a0684d4bc9caee8271789c
620,422
import pkg_resources def introduction(request): """ Return a configuration for contributing examples to the Demo application. Parameters ---------- request : dict Information provided by the demo application. Currently this is a placeholder. Returns ------- response :...
9ebb4a7630dad67c8659726c8332667af1bc4404
620,430
def read_stopwords(path): """ Loads stop words. :param path: path to file containing the smart stop words :return: set containing all stop words """ stopwords = set() with open(path, "r") as file_stopwords: for line in file_stopwords: line = line.rstrip() if l...
b39d797f73c495e698f284a204b7fc57e4bdae47
620,431
def strip_whitespaces(tpl): """ Strip white spaces before and after each item """ return [item.strip() for item in tpl]
f5aad559559d04300293127be36bce7d17f72c5d
620,434
from typing import Mapping from typing import Any def is_nested(dictionary: Mapping[Any, Any]) -> bool: """Returns if passed 'contents' is nested at least one-level. Args: dictionary (dict): dict to be tested. Returns: bool: indicating whether any value in the 'contents' is also a ...
a38159fd0a83192b3f19a1a86ce979e54d251a0d
620,435
def to_sparse_fillna(df, mean): """fills Nan's in sparse df with mean of df, returns dataframe""" df_filled = df.fillna(mean) return df_filled
67454022568dde28023590b16f621415f134bf32
620,436
def textual_list(items, join_word="or", empty="(nothing)"): """Lists items in humanized list form. e.g. >>> textual_list(['foo', 'bar', 'baz']) 'foo', 'bar' or 'baz' """ if not items: return empty items = list(items) last_item = items.pop() items_list = ", ".join("'{}'".for...
584205763bf81f0d900437e305f90a150656cf35
620,439
import hashlib def getsha512(filename): """ This function computes the SHA512 sum of a file :param filename: path+filename of file to compute SHA512 sum for :return: hexidecimal sha512 sum of file. """ sha512_hash = hashlib.sha512() with open(filename,"rb") as f: # Read and update...
7e870e668720d388e1399bd633c4efb33f07c766
620,440
def devilry_multiple_users_verbose_inline(users): """ Returns the provided iterable of user objects HTML formatted. Perfect for formatting lists of users inline, such as when showing examiners or candidates on a group. """ return { 'users': users }
9cec004b7362bd1a513b5d02a154e2af5cbca7ef
620,442
def type_error_message(func_name: str, expected: str, got: str) -> str: """Return an error message for function func_name returning type got, where the correct return type is expected.""" return ('{0} should return a {1}, but returned {2}' + '.').format(func_name, expected, got)
f89a5740632447faab9cc9e0aa2ce2cdba7444f3
620,443
from pathlib import Path import typing def is_non_empty_dir(expected_dir: Path) -> typing.List[str]: """Assert that directory exists, and that it's not empty. Returns: A list of errors found, or empty if successful. """ errs = [] if expected_dir.is_dir(): for child in expected_dir.iterdir(): ...
17afa8221ba05e8c8eec1c1b97de3872119cc15b
620,444
def check_issubset(to_check, original): """ Check that contain of iterable ``to_check`` is among iterable ``original``. :param to_check: Iterable with elements to check. :param original: Iterable with elements to check to. :return: Boolean. """ s = set() # Need th...
de402bd94878f26b3683dfb2b6ef5f78e553acdb
620,448
def get_name_frame_code(GOP_struct, idx_code): """ Return a list of name (frame_i) with all frames that have coding_order = <idx_code> in the given GOP structure <GOP_struct>. """ name_frame_code = [] for f in GOP_struct: if GOP_struct.get(f).get('coding_order') == idx_code: ...
57e8ca3f3683a13ef17cb235c3c7fe934443a4e0
620,451
def sanitize_string(output): """Removes unwanted characters from output string.""" return output.replace("\t", " ")
17795a9db0d4125101511c6c2158b8f7de973492
620,452
def __digit(value): """ Converts hex to digit """ return int(value, 16)
10ef7a78aa936d5e5e3b3715c2c7e75918f8005a
620,453
def _get_filepath_components(filepath): """ Splits filepath to return (path, filename) """ components = filepath.rsplit("/", 1) if len(components) == 1: return (None, components[0]) return (components[0], components[1])
9a5cf6c8667acee8695804f74f91157ee42ea605
620,456
def ship_name(fleet, designated_no): """Return ship's name for specified designated number from the fleet.""" # has dictionary a key? Use syntax: key in dictionary if designated_no in fleet: return fleet[designated_no]
530e00e2613c2c5424eb4abdfb19658e6ee5413f
620,459
def normalize_tag(tag): """ Drops the namespace from a tag and converts to lower case. e.g. '{https://....}TypeName' -> 'TypeName' """ normalized = tag if len(tag) >= 3: if tag[0] == "{": normalized = tag[1:].split("}")[1] return normalized.lower()
18add46f7bc925d3c3b2b2992eba852ef69e3433
620,461
from typing import Counter def anagrams_cntr(str1, str2): """This function takes two strings and compares if they are Anagram using Counter.""" return Counter(str1.lower()) == Counter(str2.lower())
26a9fd6f3a7e745e5e7733e59a3bdb9c473b79d9
620,463
def approx_first_derivative(fun, x, h): """ Function to approximate the first derivative through central differences args: fun (function): function that will be approximated x (float): value where the function will be centered h (float): finite step that will be taken...
4f29916d9c99cfdf64b8df8edd1f845bdba9f8f3
620,465
def strZip(list1, list2, string): """ Return a list of strings of the form x1stringx2 where x1 and x2 are elements of list1 and list2 respectively. """ result = [] for x1, x2 in zip(list1, list2): result.append(str(x1)+string+str(x2)) return result
08c8278a1af12cfb4e46c7cdf31e88f2261a782c
620,467
def palindrome(word): """Return True if the given word is a palindrome.""" return word == word[::-1]
110262fb8ea2421cf01ed539a549ee7f07052f0e
620,472
import aiohttp async def text_callback(resp: aiohttp.ClientResponse) -> str: """Returns the response result as text. Mostly useful for endpoints that returns just text on its output. Some examples:: $ curl ifconfig.me/ip 123.123.123.123 $ curl 'wttr.in/?format=%t' +31°C ...
2cf7e0d88654f62e3ab33ed8a8dde9495fbe453b
620,473
def find_neighbors(graph, node): """Find neighbors of a node in a graph. Attribute: graph (networkx.Graph): A graph instance. node (str): Name of a node. """ return list(graph.neighbors(node))
1935327dd47ca1c27dd4663e07afada04ebe2a0a
620,475
def _get_activity_masks(df): """Split activities into three groups depending if other activities. Tell if activity is first (trip end), intermediate (can be deleted), or last (trip starts). First and last are intended to overlap. Parameters ---------- df : DataFrame DataFrame with bool...
76e9c8b6a93c07a3e93dac99c82615c0f9c60690
620,478
def delta(n_1, n_2) -> int: """Kronicka-delta function, yields 1 if indexing is the same, else zero.""" if n_1 == n_2: return 1 else: return 0
7ef01ef20ba0aff7f360eddb6d64873556116788
620,479