content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def get_remote_ip_from_request(request) -> str: """Retrieve remote ip addr from request. :param request: Django request :type: django.http.HttpRequest :return: Ip address :rtype: str """ if x_forwarded_for := request.META.get('HTTP_X_FORWARDED_FOR'): ip_addr = x_forwarded_for.split(...
cdafe628d1c4cdcd7a980bb80b19d5983cac4932
177,949
def hasgetattr(obj, attr, default=None): """ Combines hasattr/getattr to return a default if hasattr fail.""" if not hasattr(obj, attr): return default return getattr(obj, attr)
5e2dd25469506a71b2ef20293e623ab9dbc1c8cc
453,602
def collapse_codepoints(codepoints): """ Convert a list of code points in a list of ranges. Given a list of code points, extract the ranges with the maximal length from consecutive code points. :param: codepoints: List of code points. :returns: List of ranges (first_cp, last_cp) >>> range...
7bd9a32cd32047cb42657b6ea6f7867af0d51bd1
472,423
def cumsum(t): """Computes the cumulative sum of the numbers in t. t: list of numbers returns: list of numbers """ total = 0 res = [] for x in t: total += x res.append(total) return res
e3c1d6c3191f4813af87d2da091d023ff09beaa2
414,015
import re def find_date_lines_in_description(description): """ output: a list of matches in format date: the date of the match line: the full line line_before: the text matches before the date line_after: the text matches after the date """ description.strip() out...
a042fdc32c1d986ed60dcd98e2e65bd63877a86b
204,530
def data_to_psychomotor(dic): """ Returns a dictionary of psychomotor details of each student {name:{details}} """ final_dic = {} #will return to psychomotor dic_psymo = dic["psychomotor"][0] #the relevant sheet for key, value in dic_psymo.items(): del value["AGE"] final_d...
a544b0ec8c8e3639ed9e5f82c5b0853c3e283a7e
636,605
def album_info_query(album_id: str) -> dict: """ Build Album information query. :param album_id: Album id :return: Query """ return { "operationName": "AlbumGet", "query": """query AlbumGet($id: ID!) { album { get(id: $id) { ... on Album {....
8ba2415726c23c38c546168d20f3cd0aae84fb18
397,955
def github_split_owner_project(url): """ Parses the owner and project name out of a GitHub URL Examples -------- >>> github_split_owner_project("https://github.com/intel/dffml") ('intel', 'dffml') """ return dict( zip( ("owner", "project"), tuple("/".joi...
ea3d788f92c0936babf48000c51eba3ec2c1ac73
72,159
def comp_float(x, y): """Approximate comparison of floats.""" return abs(x - y) <= 1e-5
8f3a520a0c8017aa1181e413f46491dbbec0210e
400,517
def leia_int(msg=''): """-> Função que requisita um número e verifica se ele é inteiro, podendo utilizar-se de uma mensagem para isso. :param msg: valor opcional, mensagem pela qual o programa requisitara inserção de um número. :return: valor fornecido, se realmente for inteiro.""" valor = input(msg) while True: ...
60680c3f6550c3f26d948f443003bddd5658622e
191,590
from xml.sax.saxutils import escape def _make_in_prompt(prompt_template, number=None): """ Given a prompt number, returns an HTML In prompt. """ try: body = prompt_template % number except TypeError: # allow in_prompt to leave out number, e.g. '>>> ' body = escape(prompt_templa...
0d9dd26f7d5aad9ad37e8c6fe22b2592d95bb5b6
472,200
def get_weekday_word(number): """ Using weekday index return its word representation :param number: number of weekday [0..6] :return: word representation """ weekdays = ( 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', '...
d65c10635a4c9bfdf599129a84e37b3fe7c476b4
556,205
def check_len(key, val, val_len=2, ext='primary'): """ Check if the length of the keyword value has a a given length, default value for the length check is 2. Args: key: keyword val: keyword value val_len: length to be checked against ext: string, extension number (default va...
cfe913a5831f27d2793e17e2c5947ec351a4e1a5
245,065
import pprint def pretty(d: dict) -> str: """ Prettify a dictionary """ return pprint.pformat(d, indent=2, width=100, compact=True)
013b337de3b610a5fdc044d5087a4b17f0e5c8b5
542,247
def eval_guess(chosen, guess): """Check if the number guessed by the user is the same as the number chosen by the program. Parameters: chosen (int>=0): Number chosen by the program. guess (int>=0): Number guessed by the user. Returns: (str): Hint to help the user in the next gues...
0e78ea9a06d89962d31cf3987fdb658d30bc79be
611,957
def object_list_check_any_has_attribute(object_list,attr_name): """ check if any object in the list has the attribute. """ unique = False for obj in object_list: if hasattr(obj,attr_name): unique = True break else: pass return unique
cac90dab958b4bfc25493a2dba86b72454230222
24,162
def trim_unknown_energies(casm_query_json,keyword="energy"): """ Given a data dictionary from a casm query sorted by property, removes data with null/None values in the designated key Parameters ---------- casm_query_json : list of dicts A dictionary from a casm query sorted by property. Loa...
a2d08303bd86deca3ee191f690c7177768179f2b
143,073
def prefilter_by_attractor(networks, attractors, partial=True): """ DESCRIPTION: A function to filter boolean networks based on if they hold certain attractors or not. :param networks: [list] boolean networks (dict) to filter based on their attractors. :param attractors: [list] attractors (s...
3fdc1e0051ba2ddcf299f3b8eeb48bae9915b310
184,941
from typing import Optional from typing import Callable def get_custom_attribute(item: dict, attribute_code: str, coerce_as: Optional[Callable] = None): """ Get a custom attribute from an item given its code. For example: >>> get_custom_attribute(..., "my_custom_attribute") "0" >...
89b49a39de6269064bf6f99defedda35346c85b2
103,286
def fromTM35FINToMap(x, y): """ Function for moving from TM35FIN coordinates into the coordinates of the picture """ pic_h = 2480 pic_w = 1748 x_min = -40442 y_min = 6555699 x_max = 837057 y_max = 7800801 y_max -= y_min x_max -= x_min x_return = pic_w * (x - x_min)...
6519634fece8b1acc308f2262dc29f5ba45a00dc
210,238
import hashlib def string_hash(string: str, algo: str = 'sha1') -> str: """Returns the hash of the specified string.""" return getattr(hashlib, algo)(string.encode('utf-8')).hexdigest()
c8a4423a3548e7b8b9d7171ec1e5020e5f3012d6
553,125
def unique_list_order_preserved(seq): """Returns a unique list of items from the sequence while preserving original ordering. The first occurrence of an item is returned in the new sequence: any subsequent occurrences of the same item are ignored. """ seen = set() seen_add = seen.add ret...
e4157ee4cb016f514ba70a879fb18a706b5a7743
365,178
def AddNoGlob(options): """ If the option 'no_glob' is defined, add it to the cmd string. Returns: a string containing the knob """ string = '' if hasattr(options, 'no_glob') and options.no_glob: string = ' --no_glob' return string
e44c34a7d9652886080ae4167d80b631ffa8b9f9
659,426
import math def round_repeats(depth_coefficient, repeats): """ Round number of filters based on depth coefficient. Args: depth_coefficient: Coefficient to scale number of repeats. repeats: Number to repeat mb_conv_block. From tensorflow implementation: https://github.com/tensorflow/t...
bafa99e8a406e068406806703be122573c68b084
46,348
def lerp(pt1, pt2, intervals): """Linear interpolation. Args: pt1: Array of points. When interval is 0, the result is pt1. pt2: Array of points. When interval is 1, the result is pt2. intervals: Array of intervals at which to evaluate the linear interpolation >>> x = np...
c0f390025a6b9b22101889bd9cbfa443b3920ef5
374,738
import statistics def run_stats(this_set): """ Find standard deviation and mean (average) for the data set. """ # Simply calculate Mean & StdDev for this set. # Return TUPLE of FLOATS return statistics.mean(this_set), statistics.stdev(this_set)
35ce499654bf7e8fe43d862b5456b0578a093fc7
13,289
def file_type(infile): """Return file type after stripping gz or bz2.""" name_parts = infile.split('.') if name_parts[-1] == 'gz' or name_parts[-1] == 'bz2': name_parts.pop() return name_parts[-1]
0bc762667bff0f233b176603f7ef8b54d254c6db
503,403
import json def load_model_info(model_path): """Load model info from file. Args: model_path (string): the full path of where the model is located. Raises: ValueError: raise an error if the path is invalid. Returns: dict: the inputs / outputs info dict. """ if model_p...
8f9aba13db8ef6f9808d9b59cdf46c332e5fcada
464,114
from typing import Tuple def pyth_triple(u: int, v: int) -> Tuple[int, int, int]: """ Generates a Pythagorean triple (u^2 - v^2, 2uv, u^2 + v^2). Conditions: 1) u > v >= 1 :param u: natural number :param v: natural number :return: A Pythagorean triple with a odd and b even. """ ...
1732440074a1755176cf67a5a956c057e6a30621
538,792
from typing import Dict from typing import Any from typing import List def get_label_ids_by_category(crop: Dict[str, Any], category: str) -> List[int]: """ Get all label ids from a crop that belong to a certain category Args: crop: Instance of an entry in the crop da...
2bbc4a79dabe2eedee7438107e1b23c6ae869f24
131,721
def merge_dicts(*args): """ Merge multiple dictionaries each with unique key :param args: dictionaries to merge :return: 1 merged dictionary """ result = {k: v for d in args for k, v in d.items()} return result
34768ac3bd0a79fa9d1a4939122262a6fbd186fc
100,727
import math def plating_efficiency_multiplier(z): """ Plating efficiency correction multiplier for number of mutations per culture from [Steward, 1990]. z is the probability that any given mutant cell will generate a colony. :param z: fraction of a culture plated (plating efficiency); 0 < z <= 1 ...
645f05bd1e3947cae8135d343241fbe240bea358
480,548
def set_up_folder_name_1M ( model_file , date_run ): """ Produce log_file, plot_folder based on model_file (file name ending with _sd.pt) If model_file is epoch_1_sd.pt, date_run is 0913: plot_folder 'plot_2d_epoch_1', log file 'log_0913_2d_epoch_1' """ # if model_file == '': model_pure = f'ep{ep_in...
d7dd24789476279ea8d5fe0b32627aa049731ef7
699,081
import string def remove_punctuation(list_of_string, item_to_keep=""): """ Remove punctuation from a list of strings. Parameters ---------- - list_of_string : a dataframe column or variable containing the text stored as a list of string sentences - item_to_keep : a string of punctuation ...
cb9190bc160f8e725479b531afab383c6857ceac
706,141
def get_cv_object(train): """ Return Time Based CV Object. Time based CV scheme: {train month(s) - test month} {1}-{2} {1,2}-{3} {1,2,3}-{4} {1,2,3,4}-{5,6} """ tx_month = train['DayN...
e5ce051d292588d151d1487f70a8cd254479dfd2
592,313
def get_and_remove_or_default(dict, key, default): """ Get an item from a dictionary, then deletes the item from the dictionary. If the item is not found, return a default value. :return: The value corresponding to the key in the dictionary, or the default value if it wasn't found. """ if key in...
402be98aa112010abfffa1e3dcb2ae9686a12a62
71,762
def update_pid(df, suffix): """ Add a customized suffix to the 'patientId' """ df_update = df.copy() df_update["patientId"] = df["patientId"] + suffix return df_update
b5c4e48cddc36cf8f39e63237da9025d93e7f232
399,540
def helper_stationary_value(val): """ Helper for creating a parameter which is stationary (not changing based on t) in a stationary fuzzy set. Returns the static pertubation function Parameters: ----------- val : the stationary value """ return lambda t: val
1228b3a85a6026c18ebaf57b87841372e73566c6
67,306
def _to_skybell_level(level): """Convert the given Safegate Pro light level (0-255) to Skybell (0-100).""" return int((level * 100) / 255)
67f290d5d14372e928a68b2443d3dc7f41cf26cc
395,991
import random def get_random_integer(number): """ This function takes in a number and returns a random integer between 0 and that number """ return random.randint(0, number)
e5456480530f01f013428f9c5827421b7aaa12f0
671,921
def binary_search(value, array, start_idx=None, end_idx=None): """ Выболняет бинарный поиск значения в отсортированном по возрастанию массиве. :param value: Значение, которое необходимо найти. :param array: Массив поиска. :param start_idx: Начальный индекс поиска (для рекурсивного вызова) :para...
efb1396d00d44cc669c1c8d344d3334894181ae7
662,401
import math def wavy(ind, k=10.): """Wavy function defined as: $$ f(x) = 1 - \frac{1}{n} \sum_{i=1}^{n} \cos(kx_i)e^{-\frac{x_i^2}{2}}$$ with a search domain of $-\pi < x_i < \pi, 1 \leq i \leq n$. """ return 1. - sum(( math.cos(k * ind[i]) * math.exp(-(ind[i]*ind[i])/2.) for i in range(len(ind)))...
a25c99dc8cf3f9b066dd2bbc21cc8f2b41a249f2
69,820
def has_count(unit): """ return true if unit has count """ return unit.get('Count', 0) > 0
dff8c841c981f0361498865cae1adc50b1c9f77e
435,663
def getmeta(resource_or_instance): """ Get meta object from a resource or resource instance. :param resource_or_instance: Resource or instance of a resource. :type resource_or_instance: odin.resources.ResourceType | odin.resources.ResourceBase :return: Meta options class :rtype: odin.resources....
a5e676f75bda3f314ceeec52fb1a44a113734c2d
589,462
def getweakrefs(space, w_obj): """Return a list of all weak reference objects that point to 'obj'.""" lifeline = w_obj.getweakref() if lifeline is None: return space.newlist([]) else: result = [] for i in range(len(lifeline.refs_weak)): w_ref = lifeline.refs_weak[i]()...
304bfbc6075a882cf78b82343df30807e9ced7dc
594,132
import time def is_bst(st: time.struct_time) -> bool: """ Calculates whether the given day falls within British Summer Time. .. note:: This function does not consider the time of day, and therefore does not handle the fact that the time changes at 1 AM GMT. :param st: The :class:`time.struct_time` represen...
7428810629c417cb8a55994b3086a7e9515194b7
627,570
def resolve_option_flag(flag, df): """ Method to resolve an option flag, which may be any of: - None or True: use all columns in the dataframe - None: use no columns - list of columns use these columns - function returning a list of columns """ if flag is N...
c6c90d650c4edb762a4c93fb5f85a59969c8c769
248,125
def pretty_box (rows, cols, s): """This puts an ASCII text box around the given string, s. """ top_bot = '+' + '-'*cols + '+\n' return top_bot + '\n'.join(['|'+line+'|' for line in s.split('\n')]) + '\n' + top_bot
aef083621032ec2f5c429974516233a7fa606536
433,493
def get_output_parameters_of_execute(taskFile): """Get the set of output parameters of an execute method within a program""" # get the invocation of the execute method to extract the output parameters invokeExecuteNode = taskFile.find('assign', recursive=True, value=la...
56ba0c1f1941a72174befc69646b4bdb6bc9e009
41,606
import re def pipe_cleaner(spec): """Guess the actual URL from a "pipe:" specification.""" if spec.startswith("pipe:"): spec = spec[5:] words = spec.split(" ") for word in words: if re.match(r"^(https?|gs|ais|s3)", word): return word return spec
3c5237d3f20391c9bc40bfd3dd16f1e7df422b0a
593,187
def year_slice(df, first_year=None, date_col='start_date'): """Return slice of df containing all rows with df[date_col].dt.year >= first_year. Returns df if first_year is None. """ if first_year is None: return df if first_year <= df[date_col].min().year: # No need to slice ...
faccb0424f2d019e859bb7a3cbe2262b7255f3b5
313,723
from typing import Union from typing import Tuple def parse_deformation_potential( deformation_pot_str: str, ) -> Union[str, float, Tuple[float, ...]]: """Parse deformation potential string. Args: deformation_pot_str: The deformation potential string. Can be a path to a deformation.h5...
f801e72f4a9ac26905ba55e4e200110429f7ad13
599,635
from typing import Dict from typing import Any def create_default_metadata() -> Dict[str, Any]: """Creates a dictionary with the default metadata.""" return { 'title': 'Default title', 'base_url': 'https://example.org', 'description': 'Default description', 'language': 'en-US',...
2ee6aeffaafd209cb93e33bd42291ac3c12b10d8
700,714
def strip_suffixes(s, suffixes=()): """ Return the `s` string with any of the string in the `suffixes` set striped. Normalize and strip spacing. """ s = s.split() while s and s[-1].lower() in suffixes: s = s[:-1] s = u' '.join(s) return s
0f23dfebd402579abc9054b75a97be3dbbc2d4f1
327,909
def safelower(s): """ As string.lower(), but return `s` if something goes wrong. """ try: return s.lower() except AttributeError: return s
f9320df8c1a90ab325dc04a10b36d0c8f7aecf34
531,386
def convert_to_rows(response, agg_layers, prefix={}): """ Converts the hierarchical, dictionary type of response from an an Elasticsearch query into a more SQL-like list of rows (tuples). The Elasticsearch response is expected to have a specific format, where a series of bucket aggregations are nes...
0a247d2fb7652e449f18a65e789c9c2ea4ba3dac
307,557
def _pad(block, n=8): """Pads the block to a multiple of n Accepts an arbitrary sized block and pads it to be a multiple of n. Padding is done using the PKCS5 method, i.e., the block is padded with the same byte as the number of bytes to add. Args: block (bytes): The block to pad, may be a...
e26b08ab4b77a2cde7ad882ddca0b16295db35a7
359,346
import torch def _mask_borders( masks: torch.Tensor, clip_border: int ) -> torch.Tensor: """Masking left/right/top/down borders by setting `masks` to False Args: masks (torch.Tensor): mask in shape (..., h, w). torch.bool clip_border (int): number of border pixels to mask. Returns: torch.Tenso...
1c1cd6fde1effd0db591eeee9a7cec152946c8f6
328,744
def double(n): """ Takes a number n and doubles it """ return n * 2
8efeee1aa09c27d679fa8c5cca18d4849ca7e205
444
import csv def load_labels(filepath): """ Loads and reads CSV MM-Fit CSV label file. :param filepath: File path to a MM-Fit CSV label file. :return: List of lists containing label data, (Start Frame, End Frame, Repetition Count, Activity) for each exercise set. """ labels = [] with ope...
067ebedc5db5e61e414fdf142664be20fc22b2a7
558,563
def _strip_double_quotes(string: str) -> str: """Removes encapsulating double quotes, if there are some. Ignores non-encapsulating double quotes (one side only or inside). Args: string: The string to be pruned. Returns: The pruned string without encapsulating double quotes. """ ...
0c09e6e9579ea4bc7137495aeaf16ae9291a58d0
498,549
def sort_srv_results(results): """ Sort a list of SrvRecords by weight and priority. """ results.sort(key=lambda x: (x.priority << 16) | x.weight) return results
4090b0e6a25cfbe6b7ba4b1c3452ded311b23e2f
262,088
def timecode_to_milliseconds(code): """ Takes a time code and converts it into an integer of milliseconds. """ elements = code.replace(",", ".").split(":") assert(len(elements) < 4) milliseconds = 0 if len(elements) >= 1: milliseconds += int(float(elements[-1]) * 1000) if len(el...
6f25c32fd427692c61b1536d0611cffac1832213
201,381
def make_ucsc_chr(interval): """ Converts interval from ENSEMBL chroms to UCSC chroms (appends str to each chrom) """ interval.chrom = "chr" + interval.chrom return interval
d5878670494dc51e29922d43a605634f26cd8e00
37,207
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...
ffc1d910595074ba3340ce3187ef0b1566bd2909
654,776
def addEdges(graph, edges): """ This function adds edges to a given graph together with their weights """ for i in edges: graph.add_edge(i[0],i[1], weight=i[2]) return graph
92af0c4f093126616abeaf1f07a062a4273087d5
515,939
from typing import List from typing import Dict def get_flags(args: List[str]) -> Dict[str, List[str]]: """ Returns a dictionary containing the flags within the passed through command line arguments. # Example ```py # $ py ./src/main.py normal_argument -flag1 Hello, World ...
2eba1fd243824b8e212b45e70c60b30ec225398d
645,356
import re def check_valid_dob(dob): """ Checks if the dob is in a valid format """ x = re.search("[0-9]{4,4}\-[0-9]{1,2}\-[0-9]{1,2}", dob) return True if x is not None else False
0c7b516a98d513938bfa304fc0a65ffbc84a512f
441,627
def dna_strength(seq): """Calculates DNA strength Args: seq (str): sequence of A, C, T, G, N with len > 1 Returns: DNA strength (float): normalized by length Raises: ValueError: if input is None or str shorter than 2 Citation: Khandelwal et al. 2010. 'A...
9462ffc34ef6a644e470e23262afcfd6d279564d
524,530
def init_headers(token): """ Returns a dictionary of headers with authorization token. Args: token: The string representation of an authorization token. Returns: The headers for a request with the api. """ headers = { 'Content-Type': 'application/json', 'Authorizatio...
163a5fc5d5685fcff85a295eca21334fa4dca4a7
485,073
from typing import OrderedDict def optimise_autopkg_recipes(recipe): """If input is an AutoPkg recipe, optimise the yaml output in 3 ways to aid human readability: 1. Adjust the Processor dictionaries such that the Comment and Arguments keys are moved to the end, ensuring the Processor key is firs...
c48611e6b47c9b9061146ddc5190645339b97578
620,187
from typing import Tuple def parse_interval(interval: str) -> Tuple[str, str, str]: """ Split the interval in three elements. They are, start time of the working day, end time of the working day, and the abbreviation of the day. :param interval: A str that depicts the day, start time and end time ...
f2bac53a1b56e1f6371187743170646c08109a27
41,547
def read_file_from_disk(path, encoding='utf-8'): """ Utility function to read and return a file from disk :param path: Path to the file to read :type path: str :param encoding: Encoding of the file :type encoding: str :return: Contents of the file :rtype: str """ with open(path...
53274609b3a63a591f87c92df45d552e4e27dd4a
359,077
def update_min_size(widget, width=None, height=None, size=None): """Utility function to set minimum width/height of a widget.""" size = size or widget.GetMinSize() if width: size.SetWidth( max(width, size.GetWidth())) if height: size.SetHeight(max(height, size.GetHeight())) widget.SetMinSize(size)...
f6efd83e45331c0b21fabff35fb75b48806f1fc1
279,256
def str_rstrip(S, substr): """Strips a suffix from S if it matches the string in `substr'. """ # This is akin to ${VAR%$substr} in Bourne-shell dialect. if len(substr) > 0 and S.endswith(substr): return S[:-len(substr)] else: return S
2c2c85989880d711fdda8093fda1b4b319063d4a
215,913
import re def parse_conf(dir): """ Extract the Autoinstall and md5sum fields from the package.conf file Args: - dir: directory name Returns: (autoinstall value, checksum value), where autoinstall value is "True" or "False" """ md5pat = re.compile('^md5sum=(.*)$') ...
d97343e31cb4eba70186623828a3a4a4516cebe4
144,588
def dms2dd(dms): """ DMS to decimal degrees. Args: dms (list). d must be negative for S and W. Return: float. """ d, m, s = dms return d + m/60. + s/3600.
26ce439d9a4acc8b8d384ccb88e5142581ddcc99
680,238
def upload_project_run(upload_context): """ Function run by CreateProjectCommand to create the project. Runs in a background process. :param upload_context: UploadContext: contains data service setup and project name to create. """ data_service = upload_context.make_data_service() project_na...
f0313f09c0e9c029648c0c87a93e45b418c13d8a
448,628
def generate_train_config(model_spec, train_batch_spec, val_batch_spec, epoch_size, n_epochs=100, lr=0.001): """ Generates a spec fully specifying a run of the experiment Args: model_spec: a model spec train_batch_spec: a batch spec for train val_batch_spec: batch spe...
0e19dab0263eda8505ddb830fd255b2a760d822c
696,554
def pipe_to_underscore(pipelist): """Converts an AFF pipe-seperated list to a CEDSCI underscore-seperated list""" return pipelist.replace("|", "_")
94d29e07d2c01be5afffab71cc26f9e91646bd9b
72,155
import re def split_words(src_string): """ Split a sentence at the word boundaries :param src_string: String :return: list of words in the string """ r = re.findall(r"[\w]+", src_string) return r
beaf4b72ec79ea9d2779d073acf166960013ce2b
154,582
def metadata_filter_as_dict(metadata_config): """Return the metadata filter represented as either None (no filter), or a dictionary with at most two keys: 'additional' and 'excluded', which contain either a list of metadata names, or the string 'all'""" if metadata_config is None: return {} ...
b851fdfc759f89571d1b39cf34d82122ad3a3e40
626,004
def is_sampler(estimator): """Return True if the given estimator is a sampler, False otherwise. Parameters ---------- estimator : object Estimator to test. Returns ------- is_sampler : bool True if estimator is a sampler, otherwise False. """ if estimator._estimator_t...
5a702e92f82a6d7c579112da91a2ce71851e5373
165,519
from typing import Union from typing import Tuple import torch def conv1x1(in_planes: int, out_planes: int, stride: Union[int, Tuple[int, int]] = 1): """ CREDITS: https://github.com/pytorch/vision 1x1 convolution """ return torch.nn.Conv2d( in_channels=in_planes, out_channels=out_p...
ee3505e1fff51dbedc1b16ba3225e8ee3d4cb014
549,072
def reorder_columns(columns): """ Reorder the columns for creating constraint, preserve primary key ordering ``['task_id', 'dag_id', 'execution_date']`` :param columns: columns retrieved from DB related to constraint :return: ordered column """ ordered_columns = [] for column in ['task_...
70532a911eb8444be574ce12d93cd2398b8447e3
332,251
def read_metadatablockpicture( data ): """Extract picture from a METADATA_BLOCK_PICTURE""" off = 8 + int.from_bytes( data[4:8], 'big' ) off += 4 + int.from_bytes( data[off:off+4], 'big' ) + 16 size = int.from_bytes( data[off:off+4], 'big' ) return data[4+off:4+off+size]
99a993e30577af610df02123de1df030032b55c8
259,192
def csnl_to_list(csnl_str): """Converts a comma-separated and new-line separated string into a list, stripping whitespace from both ends of each item. Does not return any zero-length strings. """ s = csnl_str.replace('\n', ',') return [it.strip() for it in s.split(',') if it.strip()]
cb6743761b1b394b3459f987b02f6d0c9f47b19a
268,253
def switch_player(player): """Switch the player from X to O or vice versa and return the player""" players = {"X": "O", "O": "X"} return players[player]
6ca7412a4c1d6adddee38a15c2f3dc7ebed15cf7
117,800
import re def is_uid(string): """Return true if string is a valid DHIS2 Unique Identifier (UID)""" return re.compile('^[A-Za-z][A-Za-z0-9]{10}$').match(string)
9e1c1d8dc2697a8535018b15662a69edfdbc8eaf
70,821
def insertion_sort(arr): """ The function insertion_sort() sorts the given list using insertion sort algorithm. The function returns the list after sorting it. Arguments arr : An unsorted list. """ for x in arr[1:]: for y in arr[arr.index(x)-1::-1]: if x < y: ...
0c2df7b9ad7bd72f5f7ba26c5b1bc3babe6b30f6
634,569
import re def ip_add(string): """ Extract IP address from text. Parameters ---------- string: str Text selected to apply transformation. Examples: --------- ```python sentence="An example of ip address is 125.16.100.1" ip_add(sentence) >>> ['125.16.100...
efaa5882e63fc3f02091cfcc28f94c643e1ae037
461,944
import yaml def parse_metadata(doc,join='\n'): """ Parse the metadata from a document and parse it as a YAML dict and return it. """ doc = doc.strip() if doc.startswith('---\n') and ('...' in doc or '---' in doc[4:]): # found starting yaml block yblock = doc[4:].split('...')[0]...
3cee56b2e6878d1836669c0c1d68b9b932a61cb1
547,710
def get_ec_params(alg): """Return a string representation of a hex encoded ASN1 object X9.62 EC parameter http://docs.oasis-open.org/pkcs11/pkcs11-curr/v2.40/cos01/pkcs11-curr-v2.40-cos01.html Indicates that EC paramaters are byte arrays of a DER encoded ASN1 objects X9.62 parameter. This function wil...
57746eab7368940b41558970531e6db29aa1023d
117,844
def gen_tagset(tags): """Create TagSet value from a dict.""" return [{'Key': key, 'Value': value} for key, value in tags.items()]
0c12c8a901ac52f69098c4fe73da6ecbdf0cabc7
621,273
def fill_slicer(slicer, in_len): """ Return slice object with Nones filled out to match `in_len` Also fixes too large stop / start values according to slice() slicing rules. The returned slicer can have a None as `slicer.stop` if `slicer.step` is negative and the input `slicer.stop` is None. This ...
ed2bcad1246f8f5e238878bf2fc46edfa871a445
359,280
def _max_full_form_prefix_length(full_form, lemma, min_rule_length): """Return the maximum possible length of the prefix (part of the full form preceding the suffix).""" full_form_prefix = len(full_form) - min_rule_length return min(len(lemma), full_form_prefix)
b9ee8c850f41c69019bfed6e827d83fe90e416e5
560,482
import requests import json def get_entry(url): """Call query URL and check returned entry Parameters ---------- url : str POWER query URL Returns ------- dict entry returned by query Raises ------ RuntimeError when API returned error """ r = ...
2ce788e1a71dbfe3d576b79812228d3d788a44f6
497,834
def normalize_rect(rect): """ Make rectangle a rotated tall rectangle, which means y-size > x-size and the angle indicates the "tilt": rotation of the longer axis from vertical :param rect: OpenCV's rectangle object :return: OpenCV's rectangle object normalized as described rect[0] is the coordi...
4796f4e14b16c3e78098fa74df868f18a684e229
82,826
def ccalc_viridis(x, rgbmax): """viridis colour map""" r = [0.26700401, 0.26851048, 0.26994384, 0.27130489, 0.27259384, 0.27380934, 0.27495242, 0.27602238, 0.2770184, 0.27794143, 0.27879067, 0.2795655, 0.28026658, 0.28089358, 0.28144581, 0.28192358, 0.28232739, 0.28265633, 0.28291049, 0.28309095, 0.28319704, 0.283228...
88a1a135c3f398d33bc8f5b3a56520ea8461c373
122,412
import base64 def base64_from_hex(hexstr): """ Returns the base64 string for the hex string specified :param hexstr: The hex string to convert to base64 :return: The base64 value for the specified hes string """ return base64.b64encode(bytes(bytearray.fromhex(hexstr))).decode("utf8")
5d457d08ed47356073bd2238699b65a3c3037df3
642,348