content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Iterable from functools import reduce import operator def prod(iterable: Iterable) -> float: """Returns the product of the elements of an iterable.""" return reduce(operator.mul, iterable, 1)
5bb7d725003a3b696d3aef45377e6d682a4be022
660,647
def division_euclidienne_dichotomique(a, b): """Renvoie le quotient q et le reste r de la division euclidienne de a par b""" n = 0 while 2 ** n * b <= a: n += 1 inf = 2 ** (n - 1) sup = 2 ** n for i in range(1, n): mid = (inf + sup) / 2 if mid * b <= a: inf =...
9c7aeb8f8e77363e7853e7223cc648191a9e72a7
660,649
import re def sanitize_id(string): """Remove characters from a string which would be invalid in XML identifiers Parameters ---------- string : str Returns ------- str """ string = re.sub(r"\s", '_', string) string = re.sub(r"\\|/", '', string) return string
33a4ef04298bb7795af55656c190c7dc50620c37
660,651
def mini_help(n): """ => Exibe a docstring do comando que recebe :param n: o comando a ser pesquisado :return: a ajuda interactiva (help) do parametro """ r = len('Acedendo ao manual do comando')+len(n)+6 #este trecho print('~'*r) #de codigo print(f' Acedendo ao manual do comando {n}') #pode ser print...
6d60ed299470f270d2295b2029e4833257edf2d5
660,659
import random import string def random_mutate(word, mutations, no_punct, alpha): """Randomly mutate the word with 'mutations' frequency. If no_punct is true, leave punctuation unaltered.""" letters = list(word) # split the current word in a list num_mutations = round(mutations * len(letters)) ...
9c50d168834b6872500616d70645aebabef315e7
660,662
def get_gem_group(sample_def): """ Get the GEM group from a sample def. Defaults to 1 if the gem_group is specified as None. Args: sample_def (dict): Sample def Returns: int: GEM group """ gg = sample_def['gem_group'] or 1 return int(gg)
6b37c25e52292d98e16e579d5d5688a33620b62f
660,663
def rinse(M, d=1e-14): """ This function removes any entries in a list or array that are closer to zero than d is. It is used in the gauss function to avoid division by near-zero values. By default d is set to be equal to 10^-14. """ m = len(M) if type(M[0]) == list: n = len(M[0...
a62a2a02bc878066cecec212c4499fa00df629ae
660,664
def get_figure_height(width, ratio=0.6): """Compute and return figure height with a ratio.""" return width*ratio
ac5a1c3259007b5dcccb9f40c0c9241b5d8c192d
660,666
import re def process_content(string): """ Process the content string data, if the string is nan (empty), replace it by '' else check if '#*;' in string, replace it by right symbol, and if the meaning of '&#*;' is unknow, return the wrong info Paras: string: the context ...
f97249a7356dc9010d478a83ad9569960afb102f
660,667
def _as_float_string(f): """Takes a floating point number and returns it as a formatted string""" return "%.2f" % f if f is not None else 'nil'
09d53a2d407830a24dd6f4d8b5f1def6d42f22c4
660,669
def extract_keywords(icss): """Helper function Parameters ---------- icss : string comma-separated string Returns ------- kws : list of string set of keywords paramdict : dict dict of {parameterized_keyword: parameter_valu...
215609119de40f34dce3733c0bae3b4b4c20d86b
660,670
def _static(job, t): """Static priority assignment according to task IDs (smaller is higher priority)""" if job.task.id is None: raise ValueError(f"Cannot use task ID {job.task.id} as priority!") return job.task.id
abd287f7ab888761c62c2f0a325491d0338a54a3
660,674
def CreateFeedItemAddOperation(name, price, date, adgroup_id, ad_customizer_feed): """Creates a FeedItemOperation. The generated FeedItemOperation will create a FeedItem with the specified values and AdGroupTargeting when sent to FeedItemService.mutate. Args: name: the value...
0499a55b232c0376e77ef1c6c3428ff2bef0040c
660,678
def range_limit(u, range=[-5, 5]): """ Returns a logical vector that is True where the values of `u` are outside of `range`. Parameters ---------- u : xarray.DataArray The timeseries data to clean. range : list Min and max magnitudes beyond which are masked Returns --...
05face2fb4a10557331b7c6c157e17f688e6f917
660,679
def read_data(filename="data/input4.data"): """ Load the raw datafile """ with open(filename) as f: lines = f.read().splitlines() return lines
0ddf56cf3b82c7f8da51361383d0b518ccc2c0dd
660,680
def identity(x): """ pickable equivalent of lambda x: x """ return x
9b9b3e93f3a51bcd90ae6fd9e7f3bc671d5ddd01
660,684
def get_posted_files(db): """ Extracts a set of image file names for persisted tweets. The application's expected image file format is ``an-image-name-without-the-path.png``. So, it does not include the path to the image file in the saved string. Args: db: TinyDB instance. Returns: ...
e4500a0dcac87df1415a3a4347bb0970b5072710
660,686
def calculer_temps_segment(distance, v, deriver_v, limite, pas): """ Renvoie le temps et la vitesse après le parcours d'un segment. distance : flottant, distance à parcourir v : flottant, vitesse intiale deriver_v : fonction, renvoie la dérivée de la vitesse limite : flottant, limit...
3da1ec025d3240a765d9d07e0eafa7df5a414be1
660,688
from typing import Sequence from typing import List def _purge_tags(tags: Sequence[str]) -> List[str]: """ Purge tags. Remove duplicate and sort tags :param tags: A sequence of tags :return: purged tags """ return sorted(set({key.strip().lower() for key in tags if key}))
27407a0c91b24ef9673d1278094892cad99214ad
660,691
def select_from_dict(original_dict, allowed_keys): """ >>> select_from_dict({"spam": 1, "eggs": 2, "pizza": 3}, allowed_keys=("pizza", "spam")) {'spam': 1, 'pizza': 3} >>> select_from_dict({"spam": 1, "eggs": 2, "pizza": 3}, allowed_keys=()) {'spam': 1, 'eggs': 2, 'pizza': 3} """ if len(allo...
73f49a266150d62631baa09937306657d965e852
660,693
def path_emission(iterable, emission=0): """Construct a common emission from an iterable of :class:`Material` objects Parameters ---------- iterable: list_like List of :class:`Material` objects emission: scalar or :class:`~lentil.radiometry.Spectrum`, optional Emission collected up...
dbaf144b9c20ad407848ee5a8a72a4036999eeb2
660,696
def timeout_from_marker(marker): """Return None or the value of the timeout.""" timeout = None if marker is not None: if len(marker.args) == 1 and len(marker.kwargs) == 0: timeout = marker.args[0] elif len(marker.args) == 0 and len(marker.kwargs) == 1 and "timeout" in marker.kwa...
8d0f56eeba1d5c06bcaa0123923a0ded75da9eba
660,699
def get_color(score: float) -> str: """Return a colour reference from a pylint score""" colors = { "brightgreen": "#4c1", "green": "#97CA00", "yellow": "#dfb317", "yellowgreen": "#a4a61d", "orange": "#fe7d37", "red": "#e05d44", "bloodred": "#ff0000", ...
0344694ea66b1e8c0191b5f7a72fe9fcd83b4912
660,700
def get_romb_offset(rom_slot, rom_split, rom_bases, roms_file=False): """ Get ROM slot offset in SPI Flash or ROMS.ZX1 file :param rom_slot: ROM slot index :param rom_split: Slot number where rom binary data is split in two :param rom_bases: Offsets for ROM binary data :param roms_file: If True,...
73b4014644c636c50af06a16837b2cc15c6aa9af
660,701
def add(a, b): """ A function that adds two integers :param a: (int) The first integer :param b: (int) The second integer :return: (int) The sum of a and b :raises: AttributeError, if a and b are not integers """ if not isinstance(a, int) or not isinstance(b, int): raise Attribu...
4f3725e3d1ace5e31fd80f8d26d6835bfff8d77a
660,702
def internal_gains ( metabolic_gains, lighting_gains, appliances_gains, cooking_gains, pumps_and_fans_gains, losses, water_heating_gains ): """Calculates Internal Gains, Section 5. :param metabolic_gains: Calculated using table 5. See (66...
63d23485b5445b3d3aa24cad94682cf7632f466f
660,707
def cron_trigger_dict(ts_epoch, ts_2_epoch): """A cron trigger as a dictionary.""" return { "year": "2020", "month": "*/1", "day": "*/1", "week": "*/1", "day_of_week": "*/1", "hour": "*/1", "minute": "*/1", "second": "*/1", "start_date": ts...
724654fa9538011e4e288cd080926ab9b21dcfa0
660,709
def lighten(color, shades=1): """ Lightens a given color by a number of shades. Args: color(tuple): the RGBA color. shades(int): the number of shades to add to the color value. Return: The lightened color. """ r, g, b, a = color return min(r + shades, 255), min(g + ...
6ec2d1e51506b2b35eed540bf2d580792d4b0557
660,710
def repeated_letter(word: str) -> dict: """ Check if a word has repeated letters. Args: word (str): Word to check. Returns: dict: { 'A':{1,2}, 'B':{0,3}, etc. } # Dictionary of repeated letters and the indices where they are repeated. """...
9b02784e96a5e2fd84ffd77397e54be4088a26bc
660,711
def get_graph_no_active_edges(graph): """ Get a molecular graph without the active edges Arguments: graph (nx.Graph): Returns: (nx.Graph): """ graph_no_ae = graph.copy() active_edges = [edge for edge in graph.edges if graph.edges[edge]['active'] is True...
03459b65765f4962c651d82902502a1676eca39d
660,714
def fraction_justified_and_finalized(validator): """Compute the fraction of justified and finalized checkpoints in the main chain. From the genesis block to the highest justified checkpoint, count the fraction of checkpoints in each state. """ # Get the main chain checkpoint = validator.highest...
9b228962f83eeb548a35e48b2c67565146572dff
660,715
def map_headers(wb_obj): """ Returns a nested dictionary with the location and name of each column header """ sheets = wb_obj.sheetnames return_value = {} ignore_this = ["Main", "Commands", "Settings", "Errors"] for sheet in sheets: if sheet not in ignore_this: row = ...
474155679ab52aae94cf7ddb7664cd806560223e
660,719
def parse_edges_and_weights( data: str, start_string: str = "Distance", end_string: str = "# Source", ) -> list: """Return a list of edges with weights. This function will parse through the read-in input data between strings ''start_string'' and ''end_string'' to return the filtered text in-between...
e980e5462ac255f8899ca69ee087f575d7b5cdbf
660,721
def _kappamstar(kappa, m, xi): """ Computes maximized cumulant of order m Parameters ----- kappa : list The first two cumulants of the data xi : int The :math:`\\xi` for which is computed the p value of :math:`H_0` m : float The order of the cumulant Returns ...
756d42c3b45f02fd0850cf91ab33bae0e3c21994
660,722
def safe_get(dictionary, key): """ Safely get value from dictionary """ if key in dictionary: return dictionary[key] return None
af618b5a8d0fbcbf540b7b139dcef18203374077
660,723
def degree_centrality(graph): """ Returns a dictionary with the degree centrality of all the nodes in a given graph network. A node’s degree centrality is the number of links that lead into or out of the node. """ nodes = set(graph.nodes) s = 1.0 / (len(nodes) - 1.0) centrality = dict((n, d ...
fced226cd39ea9e186ad927852aaa42cec0525a2
660,725
import random def random_symbol(num: int = 1, seed=None) -> list: """ Returns a list of random symbols from the following set: ['!', '@', '#', '$', '%', '^', '&, '*' ,'(', ')', '-', '_', '=', '+', '`', '~] :param num: Number of symbols to return :type num: int :param seed: Random seed (Opti...
1e6159fb8e15d974d9e97bddaa82e2bcef9e3b5e
660,729
def my_strip(thing): """Safely strip `thing`. """ try: return thing.strip() except: return thing
42e408437234b010fb01f5c7b56b996f68663b4f
660,735
def quadratic_depth(x, point_1, point_2): """ Evaluate a quadratic function for a given value ``x``. The parameters to define the function are determined through the coordinates of two points (:math: (x_1, z_1) and :math: (x_2, z_2)). .. math :: z(x) = - a x^2 + b where, .. math::...
3695b6619d0d3c846be8d6cd41b9dcfa92051fe5
660,737
from unittest.mock import Mock def _get_mock(instance): """Create a mock and copy instance attributes over mock.""" if isinstance(instance, Mock): instance.__dict__.update(instance._mock_wraps.__dict__) # pylint: disable=W0212 return instance mock = Mock(spec=instance, wraps=instance) ...
a8420def2943cf25931234108958546fd4a67857
660,738
def _recursive_to_list(array): """ Takes some iterable that might contain iterables and converts it to a list of lists [of lists... etc] Mainly used for converting the strange fbx wrappers for c++ arrays into python lists :param array: array to be converted :return: array converted to lists ...
f4c6c91855ffc786fd3836d183ae67fc25bcec85
660,743
def calculate_bmi(weight, height, system='metric'): """ Return the Body Mass Index (BIM) for the given weight, height, and measurement system. """ if system == 'metric': bmi = (weight / (height ** 2)) else: bmi = 703 * (weight / (height ** 2)) return bmi
9d7108b1c23eb91e1362ad13e14b71fff1bac527
660,746
def save(df, name): """ Save a dataframe as a csv and pickle file :param df: (pd.DataFrame) - dataframe to save :param name: (str) - output name :return name: (str) - output name """ df.to_csv('{0}.csv'.format(name)) df.to_pickle('{0}.pkl'.format(name)) return name
4efda71dc0f5dcd0208558b7f211636cbf52bb5d
660,748
def rivers_with_station(stations): """returns the list rivers where the stations are located""" river_list = set([]) for each_station in stations : river_list.add(each_station.river) return list(river_list)
84211b528a7e10dd1280c7f08201ab5c687dadfa
660,751
def extract_int_from_str(string): """ Tries to extract all digits from a string. Args: string: a string Returns: An integer consisting of all the digits in the string, in order, or False """ try: return ''.join(filter(lambda x: x.isdigit(), string)) except:...
30e4dbe2eb0eee7e381c0e7dc1fa2c037bef3637
660,755
def formed_bond_keys(tra): """ keys for bonds that are formed in the transformation """ _, frm_bnd_keys, _ = tra return frm_bnd_keys
dbbdd8aaa62af5c6f2b678799e591c7bcf0da258
660,756
def go_past_duration(interest_area, fixation_sequence): """ Given an interest area and fixation sequence, return the go-past time on that interest area. Go-past time is the sum duration of all fixations from when the interest area is first entered until when it is first exited to the right, includin...
3e4ec3ddadb5d2916bd16cffcdd0bb71a4522142
660,759
import yaml def load_yaml(fileuri): """Load yaml file into a dict""" fd = open(fileuri, 'r') try: return yaml.safe_load(fd) except Exception as e: raise e finally: fd.close()
8f749af4b46d3e8255c6a6ca4af5c3797bbb4bed
660,760
def parse_gpu_ids(gpu_str): """Parse gpu ids from configuration. Args: gpu_str: string with gpu indexes Return: a list where each element is the gpu index as int """ gpus = [] if gpu_str: parsed_gpus = gpu_str.split(",") if len(gpus) != 1 or int(gpus[0]) >= 0...
de8c693862ac8d6dc022bf9cb9b12ed10b52d046
660,761
import requests def send_get_request(query_url, headers): """ Sends a get request using the Requests library It doesn't do anytthing special right now, but it might do some checks in future :param query_url: :param headers: :return: """ response = requests.get(query_url, headers=header...
0a1285a7b74f8ef69cf9775cfac781e359a8865f
660,762
def autotype_seq(entry): """Return value for autotype sequence Args: entry - dict Return: string """ return next((i.get('value') for i in entry['fields'] if i.get('name') == 'autotype'), "")
ff2fb811656577ced76ede843def2ef070c8cd43
660,766
def format_repository_listing(repositories): """Returns a formatted list of repositories. Args: repositories (list): A list of repositories. Returns: The formated list as string """ out = "" i = 1 for r in repositories: out += (f"{i:>4} {r.get('name', '??')}\n" ...
f046889948889d5a5aaa7e99bce805f1f10f32a3
660,769
def hex_to_ipv6(hex): """ Takes a 128 bit hexidecimal string and returns that string formatted for IPv6 :param hex: Any 128 bit hexidecimal passed as string :return: String formatted in IPv6 """ return ':'.join(hex[i:i + 4] for i in range(0, len(hex), 4))
0e78ac70169bf7fdaa34f2b8f57f6d0f80579d60
660,772
def reconstruct_path(current): """ Uses the cameFrom members to follow the chain of moves backwards and then reverses the list to get the path in the correct order. """ total_path = [current] while current.cameFrom != None: current = current.cameFrom total_path.append(current) ...
85000ca0d9ed4150afc536ff8ac8a500586df5fb
660,778
import random def guess_number(start: int, end: int) -> int: """Return a number in specified range.""" result = random.choice(range(start, end + 1)) return result
f1545fe7264c3a14484450884b47b256756957b5
660,779
import math # only used in this method from typing import Tuple def get_euclidean_distance(start_pos: Tuple[int, int], target_pos: Tuple[int, int]) -> float: """ Get distance from an xy position towards another location. Expected tuple in the form of (x, y). This returns a float indicating the straight l...
a7a5bf3b68a92703040f096ed95c6bd4f2f76098
660,780
def crossover(x, y): """ Last two values of X serie cross over Y serie. """ return x[-1] > y[-1] and x[-2] < y[-2]
90a2f4244b6e018185507920375cab18639e47f7
660,781
def ConvertToEnum(versioned_expr, messages): """Converts a string version of a versioned expr to the enum representation. Args: versioned_expr: string, string version of versioned expr to convert. messages: messages, The set of available messages. Returns: A versioned expression enum. """ return...
831d5b7b80423a27186b1e204dc517a55a0b9f51
660,782
import inspect def bound_signature(method): """Return the signature of a method when bound.""" sig = inspect.signature(method) param = list(sig.parameters.values())[1:] return inspect.Signature(param, return_annotation=sig.return_annotation)
b0a426041199f713c73f578b1bacc5567af692cd
660,785
def _ip_bridge_cmd(action, params, device): """Build commands to add/del ips to bridges/devices.""" cmd = ['ip', 'addr', action] cmd.extend(params) cmd.extend(['dev', device]) return cmd
f6951b42c734660dcb33c76b0d0e4153f4ee53e7
660,787
def archimedes(q1, q2, q3): """ This is the difference between the lhs and the rhs of the TripleQuadForumula. [MF 124 @ 2:23]. The TQF is satisfied when this is zero. Given: TQF: ((q1 + q2 + q3) ** 2) == (2 * (q1 ** 2 + q2 ** 2 + q3 ** 3)) Define: A(q1, q2, q3) = ((q1 + q2 + ...
9fb282f3448628f46501a9f76936e1beb18dc95f
660,788
def basis_function_one(degree, knot_vector, span, knot): """ Computes the value of a basis function for a single parameter. Implementation of Algorithm 2.4 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector :type knot_vecto...
ea534541df74ab891ce74fc041c9ed950dfe8765
660,789
def append_with_phrases(tokens, phrases): """Append phrases to the tokens. Args: tokens (list of str): A list of tokens. phrases (list of str): A list of phrases. Returns: list of str: A concatinated list of tokens and phrases. """ return tokens + phrases
c411b9d81c44a513a5c26cc52a07802a182ad366
660,793
import json def open_json(filename): """Opens the json file Parameters ---------------- filename: string Full file path for json file Returns ---------------- jsonf: dictionary Json file is opened and ready to be used by other functions in this code Cont...
a9a5af1701d7e3c856753cb6e3c9fb753bccd9f3
660,794
def get_indexed_constraint_body(backend_model, constraint, input_index): """ Return all indeces of a specific decision variable used in a constraint. This is useful to check that all expected loc_techs are in a summation. Parameters ---------- backend_model : Pyomo ConcreteModel constraint ...
fd2603ee06c041f0b06f945c054f63c8cb7671be
660,795
import base64 def Base64WSDecode(s): """ Return decoded version of given Base64 string. Ignore whitespace. Uses URL-safe alphabet: - replaces +, _ replaces /. Will convert s of type unicode to string type first. @param s: Base64 string to decode @type s: string @return: original string that was encod...
d3333b0204bf7d4f54570eef14e5f9aa2fbd6915
660,804
def all_prime_factors(p: int) -> list: """ Returns a list of distinct prime factors of the number p """ factors = [] loop = 2 while loop <= p: if p % loop == 0: p //= loop factors.append(loop) else: loop += 1 return factors
dbd7135f62719fa061e9dbc3ac4035a8ef25c006
660,805
import csv def csv_file_to_nested_dict(filename, primary_key_col): """ assumes the first line of the csv is column names. loads each line into a dict of kvps where key is column name and value is the value in the cell. Puts all of these kvp dicts into one top level dict, where the key is the...
d4f39fc0f27ca1a1995a78d457a5894e8d03dd37
660,806
def subsample(input_list, sample_size, rnd_generator): """Returns a list that is a random subsample of the input list. Args: input_list: List of elements of any type sample_size: Int. How many elements of input_list should be in the output list rnd_generator: initialized random generato...
888f9d79ada3576d4adf08771d10020fcee1f491
660,809
from typing import Union def modify_str_int_value(value) -> Union[str, int]: """SQL query needs quotes present for string values. Return value if value is integer else return value wrapped in quotes.""" return value if isinstance(value, int) else f"'{value}'"
645f222fb510728b74fe5715fad9673a53eecfc7
660,810
from pathlib import Path import glob def list_temp_files(directory): """List all temporary files within a directory which are marked with *temp* in their name""" try: dir_path = Path(directory) assert dir_path.exists() except Exception: raise Exception(f"Expected absolute path to v...
57490451dd0bb2121a59f3e722d108c213b57a4a
660,811
def retry(limit=1): """ Retry a failing function `n` times or until it executes successfully. If the function does not complete successfully by the nth retry, then the exception will be reraised for the executing code to handle. Example: :: root@710027b06106:/plsnocrash/examples# cat retr...
b44803d64ccf60cd656219906c8ac7cfcea019b0
660,812
import re def fix_text(text): """ Method to fix up bad text from feeds :param text: Text to cleanup :return: Fixed text """ if text is None: text = "" text = re.sub(r"[]^\\-]", " ", text) return text
c72a2013e8067fe9ba4ba31fcae0595fc1f11174
660,813
def get_integer_form(elem_list): """For an element list like ['e1', 'a1_2', 'a1_1', 'a1_3'], return the integer 213, i.e., the 'subscripts' of the elements that follow the identity element.""" return int(''.join(map(lambda x: x.split("_")[1], elem_list[1:])))
68bad294b679866ab78df6db09ae49a424cb254c
660,814
def java_type_boxed(typ): """Returns the java boxed type.""" boxed_map = { 'boolean': 'Boolean', 'byte': 'Byte', 'char': 'Character', 'float': 'Float', 'int': 'Integer', 'long': 'Long', 'short': 'Short', 'double': 'Double' } if typ in boxed_map: return boxed_...
23ffb7a1bcfd8440bed98552f01210ad08f4eb71
660,819
def filter_spatiotemporal(search_results): """ Returns a list of dictionaries containing time_start, time_end and extent polygons for granules :search_results: dictionary object returned by search_granules :returns: list of dictionaries or empty list of no entries or keys do not exist """ ...
5b97848c7a2f1edb94c01a9a4759d6ef1e0c1070
660,822
def rescale_contours(cnts, ratio): """ Rescales contours based on scalling `ratio`. Args: cnts (list of contour objects): List of `numpy.ndarray` objects representing contours from OpenCV. ratio (float): Float value used to rescale all the points in contours list. ...
5b9c3a30224f4bd8ac33c6aedecae564f5edcf3c
660,826
def turn(orientation, direction): """Given an orientation on the compass and a direction ("L" or "R"), return a a new orientation after turning 90 deg in the specified direction.""" compass = ['N', 'E', 'S', 'W'] if orientation not in compass: raise ValueError('orientation must be N, E, ...
393d80e317b959a33861c5f0b1745c730eb02745
660,827
import re def filter_star_import(line, marked_star_import_undefined_name): """Return line with the star import expanded.""" undefined_name = sorted(set(marked_star_import_undefined_name)) return re.sub(r'\*', ', '.join(undefined_name), line)
9bf4cbeb79550afd5be0863ca85679579b85cb67
660,828
def pathToString(filepath): """ Coerces pathlib Path objects to a string (only python version 3.6+) any other objects passed to this function will be returned as is. This WILL NOT work with on Python 3.4, 3.5 since the __fspath__ dunder method did not exist in those verisions, however psychopy does ...
4cd41579cfa4369d5fad06521723bf970ff6d502
660,829
def get_count(line): """ Return the count number from the log line """ return line.rstrip().split(":")[-1].strip()
00fd310ece12c70641ec76cf17049cf28dd025ae
660,830
import hmac import hashlib def do_hmac(key, value): """Generate HMAC""" h = hmac.new(key, msg=None, digestmod=hashlib.sha384) h.update(value.encode("utf-8")) return h.hexdigest()
3619f6705fe0f0d38467a778653ddf2dc0079c3a
660,832
def if_columns(x): """ This function suffixes '_columns' to a dataframe (when saving it as a file) if columns are specified and suffixes '_dataframe' no columns are specified (i.e. when the user wants to do EDA of the entire dataset). :param x: list of columns :return: '_columns' suffix if list of c...
3d26f4a7f880fe09078e15fa1c0594c4bc47eec1
660,838
def historical_imagery_photo_type_to_linz_geospatial_type(photo_type: str) -> str: """Find value in dict and return linz_geospatial_type, else return the original value string. """ geospatial_type_conversion_table = { "B&W": "black and white image", "B&W IR": "black and white infrared im...
af244f74254398c52c5bdabf2a8bb5f59dcd5053
660,842
def bin(s, m=1): """Converts the number s into its binary representation (as a string)""" return str(m*s) if s<=1 else bin(s>>1, m) + str(m*(s&1))
deed2c5bf2f50302a53df1f01502524894f8b928
660,844
from typing import OrderedDict def get_des_vars_and_qois(discipline): """Method to get the relevant design variables and quantities of interest for a specific subsystem. :param discipline: name of the discipline (structures, aerodynamics, propulsion) :type discipline: basestring :return: ordered dict...
7c9c8da90ef64e590c317aa422e2f6175520d4a4
660,846
def max_length(tensor): """Function that returns the maximum length of any element in a given tensor""" return max(len(tensor_unit) for tensor_unit in tensor)
4a41aae65f3cb3955b3a00d7b208499ab17b18eb
660,850
def parse_production_company(movie): """ Convert production companies to a dictionnary for dataframe. Keeping only 3 production companies. :param movie: movie dictionnary :return: well-formated dictionnary with production companies """ parsed_production_co = {} top_k = 3 productio...
67ccdf149ba67cebcfba824a6108edf1b2349d1d
660,852
def create_quarterly_schedule_details(api, api_exception, day): """ Creates a ScheduleDetails object for use with a scheduled task for quarterly execution (every 3 months). :param api: The Deep Security API modules. :param api_exception: The Deep Security API exception module. :param day: The day of th...
5f78608cb4289370222065dd21ab387d42cb074c
660,861
def getNumOrRowsForGrid(num_of_cols_for_rgb_grid, rgb_list): """ This is to get a number of rows using a predetermined number of columns. This is to ensure that the images form a grid, so that multiple rgb images can be viewed at once. Args: num_of_cols_for_rgb_grid(integer): The number of co...
c7b0f8b9c3c6df5bccdd852edf780ee8976bea49
660,863
def do_nothing(df, inputs): """ Does absolutely nothing. """ return df
b86cbde1d31d865a1bbaa2fe94432c650aa72e3c
660,869
def bfs_path(ADT,start,end): """Breadth First Search to find the path from start to end""" #create a queue with rule of first-in-first-out queue=[] queue.append(start) #pred keeps track of how we get to the current vertex pred={} while queue: #keep tra...
dd4bd96d879a49872e974d4b0fd619b6fbda264a
660,873
import torch def NLLLoss(inputs, targets, device = 'cpu'): """ Custom Negative Log Likelihood loss that returns loss per example, rather than for the entire batch. Args: inputs : (batch_size, num_classes) *Log probabilities of each class* targets: (batch_size) *Tar...
1d1decf83fa5736b6806d2160f63353617e1b0ca
660,875
def digits(n, base, alphabet=None, pad=0, big_endian=True): """ Returns `n` as a sequence of indexes into an alphabet. Parameters ---------- n : int The number to convert into a sequence of indexes. base : int The desired base of the sequence representation. The base must be ...
ab0c8f560359b903f7853a225c0a7d5256f86c7a
660,877
def version_param(params): """Return the value of the HTTP version parameter, or `None` if no version parameter is supplied. """ for k, v in params.items(): if k.lower() == "version": return v
61348b87007c253dc6533827de4d8f302779f107
660,879
import re def _parse_item(line): """For lines like: - Blah minor returns tuple (True, 3, 'Blah minor') for others - (False, 0, None) """ match = re.search(r'^[ ]*[*-][ ]+', line) if match is not None: ident = len(match.group(0)) return (True, ident, line[ident:]) ret...
55a74babfc8fe2cf42977d50154a57c36ea45fc0
660,881
def get_githost(host: str="github.com") -> str: """Returns the git host for GitHub, GitLab, BitBucket. Parameters: host (str): {("gh", "github", "github.com"), ("gl", "gitlab", "gitlab.com"), ("bb", "bitbucket", "bitbucket.org")}. (defa...
58416910385ad3ee21dcad5e579cf78e94df3b0b
660,884
import yaml def parse_ic(fname): """Parse the Nalu yaml input file for the initial conditions""" with open(fname, "r") as stream: try: dat = yaml.full_load(stream) u0 = float( dat["realms"][0]["initial_conditions"][0]["value"]["velocity"][0] ) ...
8e7b78a5b54f1fedc4ee4d598c8400fe49791b2e
660,888
from typing import Dict def format_location_name(location: Dict): """Returns a string with a combination of venue name, city and state, depending on what information is available""" if not location: return None if "venue" not in location and "city" not in location and "state" not in location...
192542c15c17dde10feb9f8c0b6ec4a1fa65e991
660,889
def mean_of_first_n_matches(df, var, n): """Computes for each player the mean of variable var for the first n matches and returns means as a list""" players = df.groupby('account_id', sort=False) means = players.apply(lambda x: x[var].head(n).mean()).tolist() return means
9c55093338f0c7ff7c08ee5a0c88bea7a99acd78
660,895