content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def user_1post(users): """ Fixture that returns a test user with 1 post. """ return users['user1']
48226141b6f82e43c434777110507b601b30a9be
581,411
import functools def reduce(iterable, iteratee, init=None): """ Also known as inject, foldl or fold-left, reduce boils down a list of values into a single value. init is the initial state of the reduction, and each successive step of it should be returned by iteratee. The iteratee is passed thr...
c32f0fb9de3479d39e9e55b61c98939ddd495786
581,417
import struct def bin_to_float(binary): """ Converts a single precision float binary representation to a float. """ return struct.unpack('!f', struct.pack('!I', int(binary, 2)))[0]
6b87cda84e687485114dcbab6e743c0c50c0fafa
581,418
def _RunUnitTests(input_api, output_api): """Runs unit tests for checkteamtags.""" repo_root = input_api.change.RepositoryRoot() checkteamtags_dir = input_api.os_path.join(repo_root, 'tools', 'checkteamtags') test_runner = input_api.os_path.join(checkteamtags_dir, 'r...
bd845c9f53a671b541673c497bd168d7a6bb744a
581,420
def normalization(arr): """ normalization: scale arrary or DataFrame to mean zero and range from -1 to 1 Parameters: arr: numpy arrary or pandas DataFrame Return: scaled arrary value """ return (arr - arr.mean(0)) / (arr.max(0) - arr.min(0))
07eb1f3c409c72bf54814968b886b9bbc1017346
581,423
def _tag_matches_pattern(tag, pattern): """Returns true if MARC 'tag' matches a 'pattern'. 'pattern' is plain text, with % as wildcard Both parameters must be 3 characters long strings. For e.g. >> _tag_matches_pattern("909", "909") -> True >> _tag_matches_pattern("909", "9%9") -> True >>...
4edd1c0f2d84bee905b59a6fc9720cb20fdb591b
581,425
import torch def load_model(model_path=''): """ Load saved model from file :param model_path: mlp.pth prepared using mlp.py :return net: loaded model """ print(f'[INFO]: Loading saved model...') net = torch.load(model_path) net = net.to('cuda:0') net.eval() return net
c6c2c4427ae64846b05cb948683a1ddf6ff9bd6a
581,426
import collections def get_sub_combinations(maxop): """Return a dictionary of lists of combinations suitable for recursively building expressions. Each dictionary key is a tuple of (numops, numoperands), where: numops is the number of operators we should build an exp...
776f6fabd892cccaea4e579ce48d3cd77f0d2a63
581,428
def clean_styles(widget, styles) -> dict: """ Ensures safety while passing styles to tkinter objects. Normally tkinter objects raise errors for declaring styles that are not allowed for a given widget. This function takes in the styles dictionary and removes invalid styles for the particular widget retu...
efe325a0cc202ac5deff38547822156b8b40fae0
581,430
def fix_old_requirements_txt(reqs_in): """Add common missing requirements""" result = [reqs_in] reqs_set = set(reqs_in.splitlines()) if 'naucse_render<1.0' in reqs_set: result.append('') result.append('# compatibility requirements') result.append('naucse_render < 1.4') re...
6ca8ad59e7cf20a6c6f63e7d930614329876c9b0
581,438
def word_before_after(a, sep): """ returns word before and after :sep: in string :a: """ word_before, word_after = "", "" if sep in a: word_before = a.split(str(sep))[0].strip().split(" ")[-1] word_after = a.split(str(sep))[1].strip().split(" ")[0] return word_before, word_after
1646c1a971527e69b7eddd06a5a473923fe3bd39
581,441
def isfloat(instr): """ Reports whether a string is floatable """ try: _ = float(instr) return(True) except: return(False)
02da46f641aef79b0860163fd3d63f4f1f0893ae
581,450
def drop_column(column, table=None, *p, **kw): """Drop a column, given the table. API to :meth:`ChangesetColumn.drop`. """ if table is not None: return table.drop_column(column, *p, **kw) return column.drop(*p, **kw)
1f7901521ecf713c8c5388a99c9d68085600a3e4
581,451
def bed_variant_position(interval): """Get variant position from BedTool interval""" return interval.fields[0] + ':' + interval.fields[1]
52707c7a191ef6285288b5ba8f60e8abb51f6931
581,455
def csv_header_row() -> str: """CSV header string""" return ",".join( [ "Date", "Energy (kWh)", "Cost (GBP)", "Is partial?", "Is energy estimated?", "Is cost estimated?", ] )
d1aa5e159dad364a5af9cf7a010d05a52dc5635e
581,456
def g_iter(n): """Return the value of G(n), computed iteratively. >>> g_iter(1) 1 >>> g_iter(2) 2 >>> g_iter(3) 3 >>> g_iter(4) #1*3+ 2*2 + 3*1 10 >>> g_iter(5) #1*3+ 2*2 + 3*1 + 2*3 + 3*2 22 >>> from construct_check import check >>> check(HW_SOURCE_FILE, 'g_iter...
077248bc462a42406c3ad25e51259566af0e99ff
581,459
def get_stats(flatten_tensor): """Get some stats from tensor. Arguments: flatten_tensor {torchTensor} -- torch tensor to get stats Returns: [list torch.Tensor] -- [mu, std, min_v, max_v, med] """ mu, std = flatten_tensor.mean(), flatten_tensor.std() min_v, max_v, med = ...
1880a0c92ec14b1638f54b379c9ab88174acf7ae
581,461
def get_resume_attachment_upload_dir(instance, filename): """ Determine upload dir for resume attachment files. """ return "/".join([str(instance.user.id), "documents", "resumes", f"user_{str(instance.user.id)}_{filename}"])
bfbf56c0eb8e9ba7435e6720ef6b1f0e991bf44b
581,463
def convert_path(path): """ Convert jsonpath format so it's compatible with jsonpatch Parameters ---------- path : str jsonpath format Returns ------- Path in format compatible with jsonpatch Example: input = 'TraderPeriod.[0].TradeCollection.Trade.[0].@BandAvail1'...
84535d168a316a8696374994bbb541d7ac1f096c
581,464
def _count_parenthesis(value): """Count the number of `(` and `)` in the given string.""" return sum([i for i, c in enumerate(value) if c in ["(", ")"]])
409cc96c33ac107c05189669bef04c740ac1e9d7
581,465
def polarEA_npix(nr, base_nphi=4): """Returns the number of pixels in an equal area polar grid. Parameters ---------- nr : int Number of divisions along the r-axis. base_nphi : int, optional Number of pixels around r=0, default=4. Returns ------- npix : int Numb...
b38fc93a2be7aa89d21a0a319c1311b9020126e3
581,466
def is_player_admin(group, player): """ Determines if a player is an admin in a group or not. :param group: Thr group object to check :param player: The player object to check against :return: A boolean value """ admins = group.admins.all() for admin in admins: if player.user.us...
91c886cb99a2a9180e7fcb548fa59b429cbff97d
581,477
def tuple_split(string): """ Split a string into a list of tuple values from utils.tools import tuple_split print tuple_split('') #[] print tuple_split('3') #[3] print tuple_split('3,4') #[(3, 4)] print tuple_split('3,5 6,1 4,2') #[(3, 5), (6, 1), (4, 2)] """ values ...
7f63bfc733c39ccba3c35ee93081fa4507f9d844
581,488
def GetZScrValuesForPoints(pos_and_nIns_l, mean, SD): """ We take position and num insertion values and get ZScrs for each Args: pos_and_nIns_l: list<value_tuple> value_tuple: (list) [X (int) (position), y (int) (num insertions)] mean: float SD: float (standard deviation) ...
839f4f755e8b1f165bb8e668fcd6efc50b3e9466
581,489
from typing import Sequence def find_divisors(value: int, max_divisor: int) -> Sequence[int]: """ Finds the divisors of a number. :param value: the value to compute the divisors for :param max_divisor: the maximum allowed divisor :return: the list of divisors """ divisors = [] for i ...
a9836b0139bf197eac7da98fa43dcc1990bbfbb7
581,492
def check_line(line: str): """ A funtion that checks if a string passed to this function contains key words that need to be processed further Parameters ---------- line : str\n a string that needs to be checked if it contains key words Returns ------- list\n ...
a335f87a313610315ac418365ecc291fad4e7457
581,501
from pathlib import Path def dir_exists(dirName): """check if directory exists, if not create the directory""" path = Path(dirName) if not Path(dirName).is_dir(): Path(dirName).mkdir() return Path(dirName).is_dir()
7ce0ce2ff43051ac43eb3e347d9ed3b6bbb1e1a8
581,504
def getSurroundings(array, idx, window=2): """ Return words +-2 from idx """ surroundings = [] if idx > 1: surroundings.append(array[idx - 2]) else: surroundings.append('---') if idx > 0: surroundings.append(array[idx - 1]) else: surroundings.append('---') if idx < len(array) - 1: surroundings.append...
371f6ce5d4c15251c2001acc49414f84ccd38ab0
581,505
def ddvv(xyz1, xyz2): """Distance squared between two vectors.""" dx=xyz1[0]-xyz2[0] dy=xyz1[1]-xyz2[1] dz=xyz1[2]-xyz2[2] return dx*dx+dy*dy+dz*dz
2e215049edb58a3b15dbd23e30c3131c55672cec
581,508
def _get_aliased_variables( role_name, dimension_variables): """ Returns list of variable DTOs for a virtual/aliased Dimension "Role" Keyword Parameters: role_name -- String, representing name of the OLAP dimension alias (Role) for which variables are to be returned. dimension_variables -- ...
623a1b105e65d4135895aa7ce2ce810db797e0a7
581,509
def create_api_call_headers(_client_id, _auth_token): """ Creates the necessary headers to invoke an API call. @param _client_id: Client ID magic string. @param _auth_token: Authentication token magic string. This is usually stored in the application state/configuration. @return: A map of headers. """ ret = {}...
0a768e25b9552d222197655a0994a9ed4eb9dca1
581,512
import re def check_regex(patterns): """ Check that regular expression patterns provided by compiling them. Return a list of booleans for each of the provided patterns. """ checks = [] for pattern in patterns: try: re.compile(pattern) is_valid = True exc...
9fec1cb4119b1091fb2d4b2814340c64102622fc
581,513
import ipaddress def validate_ip_address(address): """ Validates an IP address """ try: ip = ipaddress.ip_address(address) is_valid = True # print("IP address {} is valid. The object returned is {}".format(address, ip)) except ValueError: is_valid = False # print("I...
2d54fce0e4072007cd1efc1490cfef1fa03ac71b
581,516
def read_summary(file_path): """ Reads a title and purpose summary from a file. :param file_path: The file to read. :return: A string that contains everything before the Prerequisites section. """ with open(file_path) as readme: summary = readme.read().split('## Prerequisites')[0] r...
f57b7f78c587bd45ebf2d197da2fe910c32def2d
581,520
def readLines(filename): """ Read a file and store the lines into a list :param filename: single filename :return: list of lines in the file """ lines = open(filename, encoding='utf-8').read().strip().split('\n') return lines
4034aca28ded19f69ca119f55fefd6873244ceaa
581,522
def _normalize_requirement_name(name: str) -> str: """ Normalizes the string: the name is converted to lowercase and all dots and underscores are replaced by hyphens. :param name: name of package :return: normalized name of package """ normalized_name = name.lower() normalized_name = norma...
a2f750324579dcd4792c1c06f0d0fb80f6a3d9c2
581,523
def get_album_size(connection, owner_id, album_id=0, tagged=True): """Returns the size of an album. Parameters: ----------- :connection: vk_api.VkApi(...) instance, connection object; :owner_id: int, id of the group/user; :album_id: int, id of the album or 0 if it's the album with ...
1d675a7fde1f91c3c4f6fe736d5d5663e290cfa6
581,524
def add_initiators_to_initiator_group( client, tag, initiators=None, netmasks=None): """Add initiators to an existing initiator group. Args: tag: Initiator group tag (unique, integer > 0) initiators: List of initiator hostnames or IP addresses, e.g. ["127.0.0.1",...
e50ec8df36109857fcde38dfa8136edfdc2b5b7c
581,525
import re def tag_contents(obj, tag: str) -> str: """ Get everything between an opening tag and its closing tag. Args: obj (object): beautifulSoup object that begins with an opening tag and ends with the corresponding closing tag. tag (string): the HTML tag we want every...
a3c583bce360330bceea562d18e2ea5a70d6dc3b
581,528
def CreateRequest(methodname, params, ident=''): """Create a valid JSON-RPC request. Args: methodname: The name of the remote method to invoke. params: The parameters to pass to the remote method. This should be a list or tuple and able to be encoded by the default JSON parser. Returns: A va...
98aeace879865a13cffafff391d1ab345af0ae45
581,532
def export_to_csv(df, location, filename): """ Exports a df to a csv file :params: a df and a location in which to save it :return: nothing, saves a csv """ return df.to_csv(location + filename + '.csv')
fe5f665e8e323cbe0f30199da2b4f4a42776609f
581,533
def compute_next_trapstep(momentum, proposal, stepsize, findE, gradE): """ Computes next trapezoidal step. 1. Half step in momentum 2. Step in spatial variable 3. Find new gradient 4. Half step in momentum Args: momentum: shape (ndim,) proposal: MCMCStat...
3ebf390cd9577fce305517afe9be8087c60a6f44
581,535
def read_file(path): """ Open a file and store its content in a list :param path: Absolute path for the file to open :type path: str :return: List of each line of the file :rtype: List """ with open(path, 'r') as opened_file: state_list = [] lines = opened_file.readlines...
d9cd79a4b52e645058e15b5a4acbeffddc1c4fd0
581,537
def pass_abuse_disposition_filter(incident, abuse_disposition_values): """Checks whether the incident's 'Abuse Disposition' value is in the abuse_disposition_values list. Args: incident (dict): The incident to check abuse_disposition_values (list): The list of relevant values from the customer ...
7c402b0ce069691cb06ef34ed9fb0d45d048de6b
581,539
def getDefaultParam(N: int): """Physical parameters of 2D N-Ball Balancer The N-Ball Balancer consists of N bodies: - N balls (subscript from 0 to N-1, with 0 being the ball on the bottom) - lever arm (inside ball with subscript N-1) Physical parameters that multiple bodies have are indexe...
098155f258f51b290d9f7251c7f01fb290f22853
581,543
import re def get_timespan_chunks(string: str): """ Search string for chunks of timespan parameters, like 5d 10h 15m, etc. :param string: The string to search :returns: ``(days: int, hours: int, minutes: int)`` :rtype: tuple """ s = re.search(r'.*?(-?\d+)d.*', string) days = int(s.gr...
bd6cfcb67abc0b504d4a95d0c486db73e17a7add
581,544
def train_and_test(clf, X, y, train, test): """ One iteration of classification """ clf.fit(X[train, :], y[train]) return clf.score(X[test, :], y[test])
6a9ac017c043856f1eb7de8f32ba5072e856dfd5
581,546
from typing import List from pathlib import Path def check(paths: List[str]) -> bool: """Checks that all paths exist. Returns Boolean.""" return all([Path(x).exists() for x in paths])
ffb340099e9bf38d9ed20984a89ea11ca0b3499b
581,549
def get_task_id(template): """ Get task id from template input parameters. Parameters ---------- template : dict Returns ------- str Task id. """ prefix = "vol-task-" suffix = "-name" for var in template["inputs"]["parameters"]: name = var["name"] ...
ad11f20b41abbad4146bb29c2c56902ea0b7d81e
581,550
from typing import Union from typing import List def _setting_to_list(setting: Union[str, List[str]]) -> List[str]: """Converts a configuration setting to a list. The config allows for two ways of specifying some settings, for example samples. A single sample is specified as ``"Samples": "ABC"``, a list ...
41c1484806669f73e8dc318dea54154f39128809
581,551
from typing import List import re def _claims_parser( puzzle_input_filename : str ) -> List[ tuple ]: """ Returns a list of tuples ( id, x_coord, y_coord, width, height ) after parsing the input file. Each line of the input files is formatted as: #<id> @ <x_coord, y_coord: <width>x<height> **Arguments:** :`...
48c38466f146104f96c2b8ed0687287e50b6086b
581,556
import socket def free_port() -> int: """ Determines a free port using sockets. """ free_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) free_socket.bind(('127.0.0.1', 0)) free_socket.listen(5) port: int = free_socket.getsockname()[1] free_socket.close() return port
03e33db6943a2e5ae646576edf1d70fce27e031e
581,559
from typing import Dict def flatten(nested: Dict) -> Dict: """ For a structure of nested dicts (and other values in them), return a flat dictionary, with inner dict keys prefixed with outer ones. :param nested: dictionary to transform :return: flat dictionary """ flat = {} for k, v in...
3565c4b690b39b2017cb0d06ec269955bc58a69c
581,565
def get_exclamation_count(text): """ Obtains the number of exclamation points in the input text Args: text: string containing text to count the exclamation points in. Returns: The number of exclamation points in the input text """ c = text.count("!") return c
4db53be42cf25f2dc08f771e95c16568985a8589
581,571
import math def template_number2image(template, number): """Construct the an image from the template and image number.""" length = template.count("#") # check that the number will fit in the template if (math.pow(10, length) - 1) < number: raise RuntimeError("number too big for template") ...
f2a1fbe502f4850971e167c2696837f7c14d2540
581,575
import textwrap def heredoc(s, inputs_dict): """ Use docstrings to specify a multi-line string literal. Args: s (str): docstring with named placeholders for replacement. inputs_dict (dict): dict with keys corresponding to placeholders in docstring `s` and values to insert. ...
7e3e2207f5c23a40bd661cc04229aef4044f0bb5
581,577
import random def find_clip_info_from_phrase(phrase, word_mapping, use_random_version=True, specified_versions=[]): """ Takes in a phrase and finds times within videos when words are said. Parameter: phrase (string): the input phrase to search for word_mapping (dict): keys are individ...
ef03a5eb7a934a82df9212a6b52131db50e7aa29
581,578
import logging def get_new_imports(firebase): """ The function to get new project imports from firebase which have not been imported Parameters ---------- firebase : pyrebase firebase object initialized firebase app with admin authentication Returns ------- new_imports : dict...
40afc8072d534cde6a2c3ee3c3ef440a94dd74b9
581,582
def bisection_search(input_lines, elemtype1, numel, global_first_elem_idx): """ Returns the 0-indexed first index where the element type changes """ if numel == 1: return global_first_elem_idx half_idx = numel//2 etype = int(input_lines[half_idx - 1].split()[1]) # 0-indexed ...
5e1561e0b675249fb538451940129c06f8c7611e
581,586
def get_encoding_table(letters): """Defines the mapping between plain and cipher text""" if letters: return { '1': 'nine', '2': 'eight', '3': 'seven', '4': 'six', '5': 'zero', '6': 'four', '7': 'three', '8':...
4c2bd38e3d25c4ac9bf9f91e39d0d7ae9a9d6bd3
581,590
def get_coordinate(coordinate, change, limit): """Get next coordinate, within 0 and limit.""" next_coordinate = coordinate + change if next_coordinate < 0: return 0 elif next_coordinate >= limit: return limit - 1 return next_coordinate
1eee6106b31fd36ca2bbbd0111d747413a695f13
581,593
def position_diff(pose1, pose2): """Computes the position difference between two poses pose1: Pose pose2: Pose """ return (pose1.R.transpose() * pose1.t - pose2.R.transpose() * pose2.t).norm()
e3b2ac668bffa0cdc16ec78db49842143d95be0e
581,595
def monthNameToNumber(month_name): """ Takes the name of a month and returns its corresponding number. """ # A dictionary that converts a month name to its # corresponding number. month_name_to_number = \ {"January" : 1, "February" : 2, "March" : 3, "April" : 4, "Ma...
a03a408443f8d8f1e74575c8e79ba3a26c4173e1
581,596
def remove_verbatim_cr_lf_tab_chars(s): """ Return a string replacing by a space any verbatim but escaped line endings and tabs (such as a literal \n or \r \t). """ if not s: return s return s.replace('\\r', ' ').replace('\\n', ' ').replace('\\t', ' ')
b2e601ffe2326ca9a1b37bfafa88fae3683f94b7
581,598
def radius_from_altitude(altitude, body): """Return radius for a given altitude.""" return altitude + body.mean_radius
e91f2513a2fa1eb617aaa1fc777127d2a12893d0
581,602
def true_positives(T, X, margin=5): """Compute true positives without double counting >>> true_positives({1, 10, 20, 23}, {3, 8, 20}) {1, 10, 20} >>> true_positives({1, 10, 20, 23}, {1, 3, 8, 20}) {1, 10, 20} >>> true_positives({1, 10, 20, 23}, {1, 3, 5, 8, 20}) {1, 10, 20} >>> true_posi...
58bf0edb83d8d2f823fc3c6e10e827109f401c3e
581,604
import re def find_line(line: str, pattern: str, i_case: bool, is_regexp=False) -> bool: """ Check if line contains matches for pattern, with case and regexp flags. Returns True if pattern is found in line. """ found = False if i_case: line = line.lower() pattern = pattern.low...
7c1e1f98ec618f37479fe36e48304850ca1741c2
581,609
def new_particles_with_color(original_particles, red_function, green_function, blue_function, attributes_names=None): """ Returns new color particles. These are bound to the 'original_particles' in the sense that they share their attributes, but have additional attributes 'red', 'green', and 'blue'. ...
f5685b3705c4ef15d8d2ec5d56408e73dcaed727
581,611
def _ose(df): """Calculate the Opportunity Share of Entrepreneurs for a given region and year.""" return (df['oppshare'] * df['wgtat1']).sum() / df['wgtat1'].sum()
9e0782936e8fbd64da0c72d1b15f7f3f128849f1
581,614
def get_func_definition(sourcelines): """Given a block of source lines for a method or function, get the lines for the function block. """ # For now return the line after the first. count = 1 for line in sourcelines: if line.rstrip().endswith(':'): break count += 1 ...
941c504ec1a7d8ed4db1d8ce1a4f5e9ebbce7e57
581,615
import re def parse_tf_string(model, tf_str, verbose=False): """ Returns a list of relevant tfs from a string. Will ignore TFs not in the trn file. iModulonDB helper function. Parameters ---------- model : :class:`~pymodulon.core.IcaData` IcaData object tf_str : str St...
78efe4e84bd9cad33a0786071238e02edbd01255
581,619
def fileHasText(file, text): """ Check whether a file contain a certain piece of text. Parameters ---------- file: str Path of the file. text: str Piece of text to be searched for. Returns ------- bool """ with open(file, "r") as ff: for ll in ff: ...
ee0bb28f75639e415713e08f28d4c66710cfe589
581,620
def bubble_sort(nums: list) -> list: """Sort an array using the bubble sort algorithm. Args: nums (list): The unsorted input array. Returns: list: The sorted output array. """ n = len(nums) # iterate thorugh all elements in the array for i in range(n - 1): for j i...
d0ffe1e862e34a1646935b04f1b50a3e7edb72cb
581,622
import string def non_printable_chars_to_hex(source): """ Converts input string into hex for all non printable chars, printable chars remain unchanged. :param source: input string. :return: output string witch exchanged chars. """ output = "" for char in source: if char not in stri...
d78cd179c46b20882c6afd43d8aae45708f1422d
581,624
def get_device_transition(device, transitions): """Get the transition (device_transition) for a device in the Netbox.""" return transitions[device]
3a617b9608b5edaafd7478645ab19e2d9316ecf2
581,626
def flat2d(x): """Flattens all dimensions after the first of the given array Useful for collapsing spatial dimensions in a spatiotemporal stimulus or filter. """ return x.reshape(x.shape[0], -1)
44f49a252fc3e1960654c70026e751b30b61288d
581,631
def getTofMaskAffines(tof, mask): """This function returns the affine from TOF(voxel->world) and mask(world->voxel) images. Parameters ---------- tof: fslImage Time of Flight MRI imported with fslpy tools. mask: fslImage Mask from a structural MRI brain extraction (output from fsl B...
8e6028a555210b41f1560600b2aa79fff78de067
581,634
def reverse_coordinate_order(coords): """ Takes a tuple of (lat, lng) or (lng, lat) coordinates and reverses their order. """ if len(coords) != 2: raise ValueError('coordinates must contain exactly 2 points') return (coords[1], coords[0])
763ba77ac1d1f9a3c80dcb654fe2c060d48ec540
581,638
import html def clean_content(content): """Escapes HTML """ return html.escape(content)
9f5f1595ad78b975fd5da5d48a96d84f5e9eed8c
581,640
def lists_from_txt(name): """ This function extracts the columns in the results file and writes them as lists. :param str name: name of the results file :returns: lists of the actual labels of the dataset, the labels given by the ice-ring classifier, label if there are ...
223127e169c7153eb62d36ff418ad6acb144ce29
581,644
import math def avg_sdev(scores, mean_type="avg"): """Return average and standard deviation for an iterable. Note: the sdev formula is for the sample only (/n); not the one that estimates the population value (/(n-1)). scores: an iterable providing the scores to average mean_type: "trimmed" for tri...
d0f7151d946bde88151383d6e2b4649d0a3163af
581,645
def _is_julian( y, m, d ): """ The `_is_julian` function determines whether the input date is in the range of the Julian date calender or not. Returns a boolean. """ ret = False if y<1582: ret = True if y==1582 and m<10: ret = True if y==1582 and m==10 and...
2c951745ea1d85a510e04c8a8300b16dedb0669e
581,651
def get_required_distance(W, sigma_det, wav): """ Calculate the propagation distance required to satisfy sampling conditions. :param W: approximate feature size [m] :param sigma_det: propagated plane (detector) pixel size [m] :param wav: source wavelength [m] :returns zreq: required d...
41cce0c6ef27a9366ef6a1882ee226e416c43fa9
581,653
def is_leap_year(year: int) -> bool: """Checks if a given year is, was, or will be a leap year. Args: year: An integer representing a common-era year, e.g. 1984 CE. Returns: ``True`` if ``year`` is a leap year, meaning it contains one additional day in February, for a total of 366 ...
acd3b5310c149c80df868185f144c312340bdd7e
581,654
def _unique_participants(thread): """count unique participants and number of comments in a thread""" users = set([thread['user_id']]) n_replies = 1 + len(thread['children']) for reply in thread['children']: r_users, r_replies = _unique_participants(reply) n_replies += r_replies u...
a85ceed4e0517088dbf13f62deb2687733fb90da
581,659
import calendar def mkutime(d): """ Generate a UTC timestamp from the datetime object. :param d: a :py:class:`datetime` object :type d: datetime """ return float(calendar.timegm(d.timetuple())) + float(d.microsecond) / 1e6
bd4d3b70c180cd919fbceb0316b8378c6bab38d1
581,660
def getPhotoUrl(photoSizes): """Get the url of the jpg file with the highest resolution.""" url = '' # The assumption is that the largest image is last for size in photoSizes.find('sizes').findall('size'): url = size.attrib['source'] return url
90889b5631a3c08f68e848028d15d43ab6d395fe
581,661
def FetchEntities(query_obj, limit): """Fetches number of Entities up to limit using query object. Args: query_obj: AppEngine Datastore Query Object. limit: Fetch limit on number of records you want to fetch. Returns: Fetched Entities. """ entities = [] # If Limit is more than 1000 than let's ...
ed86b6818ad07cc844a85dd272d29eea803cb11a
581,662
def calc_total_div(df_no_max, df_max): """ Calculates the total dividends of the all DataFrames. This will be added onto the Monthly investment. Checks if df_max is an integer which then means that there is only one DataFrame (df_no_max) and calculates accordingly Args: df_no_max (DataFrame): T...
778140ccb1dc107ec49e1de456a93ec69a1d3cce
581,663
def _edit_points(points, remap=None, multiplier=None): """Edit the points data. Examples: Replace the indices of each points values: >>> points = [[1, 2, 3], [4, 5, 6]] >>> _edit_points(points, remap={0: 1, 1: 0}) [[2, 1, 3], [5, 4, 6]] Multiply the values of each poi...
59e8755acd50fdc93498c436f494f92901d04e34
581,664
def remove_single_character(tokens_list:list) -> list: """Remove single characters from list of tokens Args: tokens_list (list): list of tokens Returns: list: list of tokens with single characters removed """ return_lst = [] for lst in tokens_list: return_lst.append([s...
963656f5791f4ce366370d804ae1011eb9a71b31
581,665
def vertex_is_dir(vertex, graph, strict=False): """Given a vertex, return whether it represents a directory. :param vertex: The vertex to test. :type vertex: graph_tool.Vertex :param graph: The graph that vertex belongs to. :type graph: common.graph.DblingGraph :param strict: If True, the first...
8bba181e89180297beb1cc15f75efec289e88f58
581,667
def delete_key(dict_, key_): """Try to delete the key_ from the dict_; then return the dict_.""" try: del dict_[key_] except: pass return dict_
2b92741c300ff92896430d84c533674267b018e0
581,668
from datetime import datetime def format_time(cur_time: datetime, is_delta=True): """ # format_time @Description: transform the datetime.datetime into assigned long format --------- @Param: cur_time: a datetime object, with full precision is_delta: a timedelta object, with full precisi...
30b6ff4b09a27f4ac781474f71e85c8f6ee063b1
581,669
import ast def get_variable(assignable): """ Return modified variable name. >>> import ast >>> ref = ast.Subscript( ... value=ast.Subscript( ... value=ast.Name(id='a', ctx=ast.Load()), ... slice=ast.Index(value=ast.Name(id='i', ctx=ast.Load())), ... ctx=ast...
9ec15916956c6a89ed544adbc7f852df05628529
581,673
import json import base64 def _encode_blob_key(prefix, sub_key): """Encode a blob key from prefix (optional) and sub-key. Args: prefix: The prefix of the sub-provider that generated the sub-key, or `None` if this was generated by the unprefixed provider. sub_key: The opaque key from the s...
e3eba24aeae46c137ed1780a6b47b4c3f628dc5d
581,674
def get_number_of_rows(data): """ Returns the number of rows in the data Parameters ---------- data: Pandas dataframe or series Returns ------- number_of_rows """ return data.shape[0]
4e88eb60a273644b0e21ff8401c95b1fc8c5e635
581,675
def jaccard(x, y): """ Compute the jaccard distance of x and y. For sets x and y, this is the ratio of their intersection cardinality to their union cardinality jacc(x,y) = 1 - #(x n y) / #(x u y) This gives a value between 0 (completely equal) and 1 (totally different) """ intersection = [] union = [] for xi...
bfac8376f489f3f31fb8703e66696b48a62e338e
581,682
def contains_ordered(lst, order): """ Checks if `order` sequence exists in `lst` in the defined order. """ prev_idx = -1 try: for item in order: idx = lst.index(item) if idx <= prev_idx: return False prev_idx = idx except ValueError: ...
931ec98e3edd5179c9a42dfeb72dcc5f23764e75
581,683
import re def replace_markdown_pseudo_html_href_tag_with_markdown_links(content: str) -> str: """ Reformat markdown pseudo html href tag to markdown formatted links in the provided content <https://github.com/kevindurston21/YANOM-Note-O-Matic> becomes [github.com/kevindurston21/YANOM-Note-O-Matic...
5abb2b02025210dd0164b88a1e99702f0e2ed154
581,685