content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def has_nan(dataframe): """ Return true if dataframe has missing values (e.g. NaN) and counts how many missing value each feature has """ is_nan = dataframe.isnull().values.any() no_nan = dataframe.isnull().sum() # is_infinite = np.all(np.isfinite(dataframe)) return is_nan, no_nan
691c7fb8e3934cdf7543805b38f1f4d287421c55
678,655
def GnuHash(name): """Compute the GNU hash of a given input string.""" h = 5381 for c in name: h = (h * 33 + ord(c)) & 0xffffffff return h
49ed421d6b055047e81c63d1f15e3be7dea60f68
678,656
def dp_fib_ls(n: int): """A dynamic programming version of Fibonacci, linear space""" res = [0, 1] for i in range(2, n+1): res.append(res[i-2] + res[i-1]) return res[n]
36959ccfd56c01b52c8b989d9b10672401f5230d
678,657
def hex_to_rgb(hex_str: str, normalized=False): """ Returns a list of channel values of a hexadecimal string color :param hex_str: color in hexadecimal string format (ex: '#abcdef') :param normalized: if True, color will be float between 0 and 1 :return: list of all channels """ hex_str = he...
5a6ac8fd0a45264984bee7575011b6886e5ddee4
678,661
import math def adam(opfunc, x, config, state=None): """ An implementation of Adam http://arxiv.org/pdf/1412.6980.pdf ARGS: - 'opfunc' : a function that takes a single input (X), the point of a evaluation, and returns f(X) and df/dX - 'x' : the initial point - 'config` : a t...
7171ad2862e4d96b204eae01383a2e296bbe006b
678,662
def _partition(nums, left, right): """Util method for quicksort_ip() to rearrange nums in place.""" # Use right number as pivot. right_num = nums[right] # Rearrange numbers w.r.t. pivot: # - For left <= k <= i: nums[k] <= pivot, # - For i+1 <= k <= j-1: nums[k] > pivot, # - For k = right: ...
29b23ca1f703428b987d5f2843e9a9bf3ebea81f
678,664
def map_colnames(row, name_map): """Return table row with renamed column names according to `name_map`.""" return { name_map.get(k, k): v for k, v in row.items()}
5a4182996632bade50ef8239229047c91f4cff77
678,665
def is_ineq(tm): """check if tm is an ineq term.""" return tm.is_greater() or tm.is_greater_eq() or tm.is_less() or tm.is_less_eq()
759bc062752f288ab83d67f610a6f04136b0ab69
678,670
def show_resource_pool(client, private_cloud, resource_pool, location): """ Returns the details of a resource pool. """ return client.get(location, private_cloud, resource_pool)
fdca38cfc891eebb37b6ec22c78c321c9aa9fe6c
678,671
def limpiar(texto: str) -> str: """El texto que recibe se devuelve limpio, eliminando espacios dobles y los espacios que haya tanto al principio como al final. :param texto: Texto de entrada :type texto: str :return: Texto de entrada limpio (eliminando :rtype: str >>> limpiar("estoy escribi...
f856e4cfca0423fbbee7d4dbfdf2a16da0c4c164
678,672
from typing import Dict from typing import Optional def weighted_average( distribution: Dict[str, float], weights: Dict[str, float], rounding: Optional[int] = None, ) -> float: """ Calculate a weighted average from dictionaries with the same keys, representing the values and the weights. Args...
b6c710fc8039b79637c8d45329eb90cc0d1bb264
678,674
def get_orientation(strategy, **kwargs): """ Determine a PV system's surface tilt and surface azimuth using a named strategy. Parameters ---------- strategy: str The orientation strategy. Allowed strategies include 'flat', 'south_at_latitude_tilt'. **kwargs: Strategy...
f1d27d67175bd2caa3bb95e8d31668ef07a4c8e2
678,678
def stockmax(prices_): """ Given an array of prices in a stock market find the highest profit you can gain. :param : int[] prices :rtype : int """ if len(prices_) < 2: return 0 profit, peak = 0, prices_[-1] for i in range(len(prices_) - 1, -1, -1): if prices_[i] > pea...
81bdaa94e5a8e2a737be85ff5ad32af9909e7bcb
678,679
import json def load_categories(filename): """Load categories from a file containing json data Parameters: filename (string): the name of the file Returns: object:the categories object """ with open(filename, 'r') as f: cat_to_name = json.load(f) return cat_to_name
cab0612bb83f59224cec31c951bee86c496a2dfe
678,684
def t_norm(a, b, norm=min): """ Equivalent to `a.t_norm(b, norm)`. """ return a.t_norm(b, norm)
81fca86cce391f9d8c67d2a0e3b3060c0d495ad4
678,685
import random import string def get_random_string(length=6): """ Return a random string 'length' characters long """ return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(length))
8de81f82ab044a43608385a3fc8d150b6e08e035
678,686
def mag_double_power_law(mag, phi_star, mag_star, alpha, beta): """Evaluate a broken double power law luminosity function as a function of magnitude. :param mag: Magnitude :type mag: float or np.ndarray :param phi_star: Normalization of the broken power law at a value of mag_star :type phi...
60c891ae6ce8c646ebc51eabc748b1b6c187dda0
678,688
def list_dict_to_list_list(players: list[dict]) -> list[list]: """Convert a list of dictionaries to a list of lists.""" new_list: list = [] for player in players: stats: list = [] for stat in player.values(): stats.append(stat) new_list.append(stats) return new_list
94ca274fad7373f2ca2eacc28d78afa1156fac73
678,689
import csv def samples(gnomAD_path: str): """Create dictionary of sample ID and haplogroup. :param gnomAD_path: path to the gnomAD VCF :return: matches_samples dictionary with the haplogroup of every sample """ with open(gnomAD_path + "t21/sample_annotations_gnomad.txt") as csv_file: samp...
039f52f238fe725f3e06edc7962f5496fb4b37a2
678,690
def fix_var_name(var_name): """Clean up and apply standard formatting to variable names.""" name = var_name.strip() for char in '(). /#,': name = name.replace(char, '_') name = name.replace('+', 'pos_') name = name.replace('-', 'neg_') if name.endswith('_'): name = name[:-1] ...
9022f32862b06e58fc4b6c65ca9f5c961c3148fc
678,691
from typing import Sequence def variant_to_pair(variant: str) -> Sequence[str]: """Given a variant, splits it into an OS and ABI pair Parameters ---------- variant : str The variant received as input to the script (e.g. windows-win64) Returns ------- Sequence[str] A 2...
25f66b24095d529e59a6316aae7a72107572552f
678,695
def extract_properties_by_schema(group_objects_list, group_gid_number_attr, group_name_attr): """ Safeguard Authentication Services is designed to support any Active Directory schema configuration. If your Active Directory schema has built-in support for Unix attributes (Windows 2003 R2 schema, SFU sche...
9d3860ad6fa53ddc34275c61d0186937d58b9f41
678,696
def coupling_list2dict(couplinglist): """Convert coupling map list into dictionary. Example list format: [[0, 1], [0, 2], [1, 2]] Example dictionary format: {0: [1, 2], 1: [2]} We do not do any checking of the input. Return coupling map in dict format. """ if not couplinglist: ret...
dffe72a5312bb8047683ac0784a4620913875d7e
678,698
def GetKnoteSummary(kn): """ Summarizes a knote and related information returns: str - summary of knote """ out_string = "" format_string = "{o: <#020x}" out_string += format_string.format(o=kn) return out_string
0933360ec9876154a4dd1433b874678b37307b81
678,699
def scale(v,sc): """Scale a vector. Parameters ---------- v : list A 3D vector. sc : int or float A scaling factor. Returns ------- tuple Returns `v` scaled by `sc`. Examples -------- >>> from .pycgmKinetics import scale >>> v = [1,2,3] >>> ...
8ec979707ba9c4909ca797ec2ea4b0f2164e3776
678,701
def infix_to_postfix(expression): """ Function turns infix expression into postfix expression by iterating over the expression and moving operators after their operands whilst maintaining order of precedence. :param expression: Space delimited parenthetical expression containing of letters and the oper...
09bed208eb1f027ea0fece25a38a8abeeb72996e
678,702
def q_max_ntu(c_min, temp_hot_in, temp_cold_in): """Computes the maximum q value for the NTU method Args: c_min (int, float): minimum C value for NTU calculations. temp_hot_in (int, float): Hot side inlet temeprature. temp_cold_in (int, float): Cold side inlet temeprature. ...
2e4e7fee30ed41ae2f4ad174c79ea7092c2d3df4
678,705
def get_year_version_from_schema(schema_string): """ expects a schema string from xml like: 2015v2.1 """ [year, version] = schema_string.split('v') return({'year':int(year), 'version':version})
4db6a9184eac2a46b24c57a598ba0947bfd1bf32
678,710
def is_empty(value): """ Checks if a value is an empty string or None. """ if value is None or value == '': return True return False
8090e8a936df133bc9b0beff81b81eeee4283a79
678,711
def theme(dark=False, lighten=0.3, lighten_edges=None, lighten_text=None, lighten_grid=None, **kwargs): """ Create plotting parameters for different themes. Parameters ---------- dark : bool Dark or light theme. lighten : float with range [0.0, 1.0] Lighten lines by fr...
79892b846fd3ae47a05aa128feed8a86b707e87c
678,713
def fix_ra_dec(ra, dec): """ Wraps input RA and DEC values into range expected by the extensions. Parameters ------------ RA: array-like, units must be degrees Right Ascension values (astronomical longitude) DEC: array-like, units must be degrees Declination values (astronomical ...
721aef6fe21128857d81185c8ea344edaaf9894c
678,726
def complete_cases(_data): """Return a logical vector indicating values of rows are complete. Args: _data: The dataframe Returns: A logical vector specifying which observations/rows have no missing values across the entire sequence. """ return _data.apply(lambda row: row.no...
3e6e294f11988d04fd1c3d7d46b409badf1f90f9
678,727
def non_writable_folder(fs): """ A filesystem with a /dir directory that is not writable """ fs.create_dir('/dir', perm_bits=000) return fs
1259701e3aa8cce6d0fb7ce5ad471d260e55a3f1
678,730
def compose(*funcs): """ Composes a series of functions, like the Haskell . operator. Args: *funcs: An arbitrary number of functions to be composed. Returns: A function that accepts whatever parameters funcs[-1] does, feeds those to funcs[-1], feeds the result of that into funcs[-2...
9ae2b6f012879f7e8d237e3b6e03b3cc8b17d5b2
678,734
def match_barcode_rule(trello_db, barcode): """Finds a barcode rule matching the given barcode. Returns the rule if it exists, otherwise returns None.""" rules = trello_db.get_all('barcode_rules') for r in rules: if r['barcode'] == barcode: return r return None
00f7b9226fefb738a830da050820dfb219bc55fb
678,735
def JoinDisjointDicts(dict_a, dict_b): """Joins dictionaries with no conflicting keys. Enforces the constraint that the two key sets must be disjoint, and then merges the two dictionaries in a new dictionary that is returned to the caller. @type dict_a: dict @param dict_a: the first dictionary @type dic...
d42600de9646b8eda5f94cce5961754eb72daa2d
678,742
def diff_single(arr, val): """ Return difference between array and scalar. """ return [i - val for i in arr]
c53d774322c03b6d96b632ed692e77e4792505cc
678,743
import time def run_time_calc(func): """ Calculate the run time of a function. """ def wrapper(*args, **kwargs): start = time.time() ans = func(*args, **kwargs) end = time.time() print('\nRun time of function [%s] is %.2f.' % (func.__name__, ...
dc4e6faae61faf627b20f237762d6cd43af4dc33
678,744
from typing import Union from typing import List def build_gcm_identifier( gcm: str, scenario: str, train_period_start: str, train_period_end: str, predict_period_start: str, predict_period_end: str, variables: Union[str, List[str]], **kwargs, ) -> str: """ Build the common ide...
e7f826adab7637bce323a57ecc2e17407db02a8b
678,746
import re def _apply_extractor(extractor, X, ch_names, return_as_df): """Utility function to apply features extractor to ndarray X. Parameters ---------- extractor : Instance of :class:`~sklearn.pipeline.FeatureUnion` or :class:`~sklearn.pipeline.Pipeline`. X : ndarray, shape (n_channels, n_...
60c9bf56beb0639f4e33e91c43b8dbe0ab5269ad
678,750
def get_inputs(depthdata_str_list): """ Given a list of strings composed of 3 floating pt nbrs x, y, z separated by commas, convert them to floats and return them as 3 individual lists. :param depthdata_str_list: list of floating point string pairs, separated by a comma (think .csv file) :return: ...
397937ca85dbd2836582ef37ae193f9929b79ab0
678,755
import importlib def str_to_type(classpath): """ convert class path in str format to a type :param classpath: class path :return: type """ module_name, class_name = classpath.rsplit(".", 1) cls = getattr(importlib.import_module(module_name), class_name) return cls
9be7b756ee89b2dbfc475f35514567a73a34e12b
678,757
def read_file(path: str): """ Read a file from the filesystem. """ with open(path, "r") as file: data = file.read() return data
96920ee426d09f03ea8c11e86276af60d28f4826
678,761
def get_latest_reading(client, name): """Returns the value and timestamp of the latest reading.""" query = client.query(kind=name) query.order = ["-timestamp"] results = list(query.fetch(limit=1)) if not results: return None, None result = results[0] if "value" not in result: ...
5e427d7a79dcbd3ec484401993a8ffd3c2ca31a0
678,762
def string_transformer(s: str) -> str: """ Given a string, return a new string that has transformed based on the input: 1. Change case of every character, ie. lower case to upper case, upper case to lower case. 2. Reverse the order of words from the input. Note: You will have to handle multiple spaces, and ...
509de3ade824f11b5074322c9d9cbd09ace8bdde
678,764
def isSubDict(dict_super, dict_sub): """ Tests if the second dictonary is a subset of the first. :param dict dict_super: :param dict dict_sub: :return bool: """ for key in dict_sub.keys(): if not key in dict_super: return False if not dict_sub[key] == dict_super[key]: return False re...
a0dead33cddf9482c0281479ad632faebd2501da
678,768
import sympy from typing import Iterable def parameter_checker(parameters): """Checks if any items in an iterable are sympy objects.""" for item in parameters: if isinstance(item, sympy.Expr): return True # This checks all the nested items if item is an iterable if isinsta...
51a20985f6b65aae42470b950475ba21474bd702
678,769
import re def title_year(m_file): """ Regex searching returns the title and year from the filename Currently optimized for: "Title (year).extension" """ name = re.compile(r'([\w+\W?]+)\s\(([0-9]{4})\)[\s\w]*[\d\.\d]*[\s\w]*\.\w{2,4}') fsearch = name.search(m_file) if fsearch: tit...
96640d45fa82aba0de31a6063638dfcb129c1394
678,770
def offset_format(utc_offset): """Display + or - in front of UTC offset number""" return str(utc_offset) if utc_offset < 0 else f"+{str(utc_offset)}"
cf23d1d15c8a3ec852d4099724947b8d2658f4f6
678,773
def odd_even(x): """ odd_even tells if a number is odd (return True) or even (return False) Parameters ---------- x: the integer number to test Returns ------- bool : boolean """ if not isinstance(x, int): raise TypeError(f'{x} should be an integer') if int(x) % 2 =...
0475754117d2d5a126c2806b0c9107a1c60afc4e
678,776
def sort(d): """sort dictionary by keys""" if isinstance(d, dict): return {k: d[k] for k in sorted(d)} return d
613317358ab76e149de64a4106614c32374af15e
678,777
import pickle def read_data(path, n_vaues=None): """ Given a path, read the file and return the contents. Arguments: path (string) : File path with .pkl extension n_values (int) : Number of containers expected to be read. """ f = open(path, "rb") d = pickle.load(...
091ede2a909f8b99d94f94a938ffb60a7f802f1d
678,778
from pathlib import Path import json def load_config(path_config, config_type='json'): """ 加载配置文件。 如果不是绝对路径,则必须是在config目录下。 必须是json文件,可以不指定后缀。 :param path_config: Path变量或者是字符串。 :param config_type: 配置文件类型,值为'json'时,返回字典;为'txt'时,返回字符串列表 :return: """ assert config_type in ('json', 'tx...
674c1df2633ec90f55eeac8b113cffce91dd2ad9
678,781
def _apply_linear_trend(data, elevs, trend, direction): """ Detrend or retrend a set of data points using a given trend value. Parameters ---------- data : ndarray Detrended values. elevs : ndarray Elevations corresponding to the data points. trend : float Trend va...
f9cf5e68de2cbda3a1dddc0ee8ca4a5ab7e9820f
678,783
def _score_phrases(phrase_list, word_scores): """Score a phrase by tallying individual word scores""" phrase_scores = {} for phrase in phrase_list: phrase_score = 0 # cumulative score of words for word in phrase: phrase_score += word_scores[word] phrase_scores[" ...
abc85143bde20dc3097f6408712bfc0bc53c50fe
678,784
def read_lines(filename): """Read all lines from a given file.""" with open(filename) as fp: return fp.readlines()
f3005b1e1bc8a98fe543a1e364eec70ad4d85188
678,789
def prepToMatlab(detectorName, quantity): """Create a name of a variable for MATLAB""" return detectorName + "_" + quantity
16fd3d7d0f0b316da8afc7d2c14d24515ed0c2c4
678,794
from pathlib import Path import re def get_files(folder, name, indexes=None): """Get all files with given name in given folder (and in given order) Parameters ---------- folder : str path to files (folder name) name : str file name pattern indexes : list files order ...
0fbeccc458e3f423af4c491d31f88d7764187da9
678,795
import click def bool_option(name, short_name, desc, dflt=False, **kwargs): """Generic provider for boolean options Parameters ---------- name : str name of the option short_name : str short name for the option desc : str short description for the option dflt : boo...
daadefb05964163df6f77bfd42f4d63157d895c7
678,805
def seqStartsWith(seq, startSeq): """ Returns True iff sequence startSeq is the beginning of sequence seq or equal to seq. """ if len(seq) < len(startSeq): return False if len(seq) > len(startSeq): return seq[:len(startSeq)] == startSeq return seq == startSeq
5e9b910c05b3767045a09860f1e1daa203ab99a3
678,809
def calc_center(eye): """ Using for further cropping eyes from images with faces :param eye: :return: x, y, of center of eye """ center_x = (eye[0][0] + eye[3][0]) // 2 center_y = (eye[0][1] + eye[3][1]) // 2 return int(center_x), int(center_y)
dc6fd0eebda480409fee28b7c4f2aded98a2044f
678,813
def xyz_datashape(al, xyz): """Get datashape from axislabels and bounds.""" x, X, y, Y, z, Z = xyz if al == 'zyx': datalayout = (Z - z, Y - y, X - x) elif al == 'zxy': datalayout = (Z - z, X - x, Y - y) elif al == 'yzx': datalayout = (Y - y, Z - z, X - x) elif al == 'yx...
8215b7f5341a7f7e4d70c57c4641abfbf9f0e941
678,814
def has_group(user, group_name): """ Verify the user has a group_name in groups """ groups = user.groups.all().values_list('name', flat=True) return True if group_name in groups else False
094123f614873d049406059d53e7ab5a6e8224d2
678,816
def output_dim(request) -> int: """Output dimension of the random process.""" return request.param
741c55ef387786193b345d3eed1532197aa6de3c
678,819
def num_gt_0(column): """ Helper function to count number of elements > 0 in an array like object Parameters ---------- column : pandas Series Returns ------- int, number of elements > 0 in ``column`` """ return (column > 0).sum()
bde07386c3c0beec1022ca002e80b9373df69aed
678,826
def scope_contains_scope(sdict, node, other_node): """ Returns true iff scope of `node` contains the scope of `other_node`. """ curnode = other_node nodescope = sdict[node] while curnode is not None: curnode = sdict[curnode] if curnode == nodescope: return True retur...
ec4613431715b68988527794fba24ed1860eeeac
678,827
def radio_text(route): """Returns a short representation of a Route Args: route: a Route object Returns: str: a string containing the route summary and duration """ text = " ".join([ "via " + route.summary, f"({max(1, round(route.duration / 60))} minutes)" ]) ...
6dbbdbc1fe49421bdc39f3fe3a982b7e47b1dd82
678,829
def snitch_last_contained(metadata): """Return the frame when snitch was last contained.""" last_contain = 0 for _, movements in metadata['movements'].items(): contain_start = False for movement in movements: if movement[0] == '_contain' and movement[1] == 'Spl_0': ...
139719b3c4cd38aeab01e52078547da7501161cf
678,831
def dict_factory(cursor, row): """Returns a sqlite row factory that returns a dictionary""" d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d
08ef60c6ac4a72a7235d2f8d4a4bc215321b78b6
678,832
import torch def gram_matrix(tensor): """ Calculate the Gram Matrix of a given tensor Gram Matrix: https://en.wikipedia.org/wiki/Gramian_matrix """ # get the batch_size, depth, height, and width of the Tensor _, d, h, w = tensor.size() # reshape so we're multiplying the features...
135201cc65a701cda1fcfbd325537a4c0c538bd6
678,833
def isOnCorner(x, y): """Returns True if the position is in one of the four corners.""" return ((x == 0 and y == 0) or (x == 7 and y == 0) or (x == 0 and y == 7) or (x == 7 and y == 7))
9f3a33a48d560e5f0eac0f90ec8832bc0a064c9a
678,836
def is_paired(cursor, imei_norm): """ Method to check if an IMEI is paired. :param cursor: db cursor :param imei_norm: normalized imei :return: bool """ cursor.execute("""SELECT EXISTS(SELECT 1 FROM pairing_list WHER...
c01fee34f1572a6af31a70e4b31b42215fd10f70
678,838
def get_P_v(X_ex): """外気の水蒸気圧 式(2) Args: X_ex(ndarray): 絶湿[g/kg'] Returns: ndarray: 外気の水蒸気圧 """ return 101325 * (X_ex / (622 + X_ex))
7af2e09e1e8becb1f019c586d31c2dae3426cc8a
678,846
import re def remove_digits(string): """Removes digits from a string""" return re.sub(r"\d+", "", string)
f5674f12d48a5d14ccaac207aa3b051bde7f1d61
678,847
def _trim_css_to_bounds(css, image_shape): """ Make sure a tuple in (top, right, bottom, left) order is within the bounds of the image. :param css: plain tuple representation of the rect in (top, right, bottom, left) order :param image_shape: numpy shape of the image array :return: a trimmed plain ...
6f87952f1d36e7a0473014b59049697d4a35f53f
678,855
import math def log(*args): """ Evaluate a logarithm Args: *args (:obj:`list` of :obj:`float`): value optional proceeded by a base; otherwise the logarithm is calculated in base 10 Returns: :obj:`float` """ value = args[-1] if len(args) > 1: base = args[0]...
0871722ee1b7d80f125de209e06b28b40a4fcae0
678,856
import socket import contextlib def has_dual_stack(sock=None): """Return True if kernel allows creating a socket which is able to listen for both IPv4 and IPv6 connections. If *sock* is provided the check is made against it. """ try: socket.AF_INET6; socket.IPPROTO_IPV6; socket.IPV6_V6ONLY...
0a4d8a2bead681ec2c8a36ba69f5938a9aa72fc4
678,858
from typing import Dict from typing import Any from typing import List from functools import reduce def traverse_dict(obj: Dict[Any, Any], properties: List[str]) -> Any: """ Traverse a dictionary for a given list of properties. This is useful for traversing a deeply nested dictionary. Instead of recu...
94d1fe6a49aebc982db7e0dcadcddf2d51823c90
678,867
def _BuildRestrictionChoices(freq_restrictions, actions, custom_permissions): """Return a list of autocompletion choices for restriction labels. Args: freq_restrictions: list of (action, perm, doc) tuples for restrictions that are frequently used. actions: list of strings for actions that are relev...
08940cd6d78125e2e8d6a58ac97b443f92e5653f
678,874
import hashlib def get_sha_digest(s, strip=True): """Generate digest for s. Convert to byte string. Produce digest. """ if strip: s = s.rstrip() s = s.encode("utf-8") return hashlib.sha256(s).hexdigest()
41a1b8d1088d86d283b12e382da4c3848608fd8c
678,876
import hashlib def hash_(list_): """Generate sha1 hash from the given list.""" return hashlib.sha1(str(tuple(sorted(list_))).encode("utf-8")).hexdigest()
72d3642306070297693fc2ce3b3e9f1927aea54c
678,878
def get_by_name(ast, name): """ Returns an object from the AST by giving its name. """ for token in ast.declarations: if token.name == name: return token return None
caad2b27be6c25e7ed320847f75e265ac965755c
678,886
def _ecdf_y(data, complementary=False): """Give y-values of an ECDF for an unsorted column in a data frame. Parameters ---------- data : Pandas Series Series (or column of a DataFrame) from which to generate ECDF values complementary : bool, default False If True, give the E...
948d6db91d56c0f5edbaced6caa4c7927c9d90a7
678,889
def _calculate_bsize(stat): """ Calculate the actual disk allocation for a file. This works at least on OS X and Linux, but may not work on other systems with 1024-byte blocks (apparently HP-UX?) From pubs.opengroup.org: The unit for the st_blocks member of the stat structure is not defined wit...
cdf67cead1dac149ab255f12f1d8fc3f56120de1
678,890
def vcum(self, key="", **kwargs): """Allows array parameter results to add to existing results. APDL Command: *VCUM Parameters ---------- key Accumulation key: Overwrite results. - Add results to the current value of the results parameter. Notes ----- Allows results f...
1e21ba4abfc5bd321ab3c0ee7845bb3f12d6f38a
678,892
def brightness_to_percentage(byt): """Convert brightness from absolute 0..255 to percentage.""" return round((byt * 100.0) / 255.0)
81cd7be5d4fc7e966567963185223675e0aeb7f0
678,896
def ensure_bool(val): """ Converts query arguments to boolean value. If None is provided, it will be returned. Otherwise, value is lowered and compared to 'true'. If comparison is truthful, True is returned, otherwise False. :param val: Value to convert to boolean. :return: boolean value ...
6d44a44e0010bdbcbf7739dbf319d6685c3dd4b5
678,900
from typing import Tuple def get_word_from_cursor(s: str, pos: int) -> Tuple[str, int, int]: """ Return the word from a string on a given cursor. :param s: String :param pos: Position to check the string :return: Word, position start, position end """ assert 0 <= pos < len(s) pos += 1...
b777bb454a4e3a206f57388c3136ddc6de7af544
678,904
import math def geometric_progression(a, r, n): """Returns a list [a, ar, ar^2, ar^3, ... , ar^(n-1)]""" comp = [] for num in range(n): comp.append(a*math.pow(r, num)) return(comp)
d7be789f516c4fcc138075ef2782ae8232c05add
678,906
def lifetime_high(m): """Compute the lifetime of a high mass star (M > 6.6 Msun) Args: m (array): stellar mass. Returns: array: stellar lifetimes. """ return (1.2 * m**(-1.85) + 0.003) * 1000.
a7990108f50befd2c73ba4099c4005b827dded94
678,907
def replace_subset(lo, hi, arr, new_values, unique_resort=False): """ Replace a subset of a sorted arr with new_values. Can also ensure the resulting outcome is unique and sorted with the unique_resort option. :param lo: :param hi: :param arr: :param new_values: :param unique_resort: ...
7c85fd36b9b08037d798dc79abd3fdce3f2a879f
678,908
def remove_comment(command): """ Return the contents of *command* appearing before #. """ return command.split('#')[0].strip()
20a6246bffb11a07f77b49197c6f0a8b436e05d9
678,916
def getdefaultencoding(space): """Return the current default string encoding used by the Unicode implementation.""" return space.newtext(space.sys.defaultencoding)
7ee385e18b59b1c4fa0070d1d3205d2f53a933ab
678,921
def seconds_to_str(value): """Convert seconds to a simple simple string describing the amount of time.""" if value < 60: return "%s seconds" % round(value, 2) elif value < 3600: return "%s minutes" % round(value / 60, 2) else: return "%s hours and %s minutes" % (round(value / 360...
0416caace4420bd69a245309e2e8f447267655c1
678,923
def get_mask(k: int, c: int) -> int: """Returns the mask value to copy bits inside a single byte. :param k: The start bit index in the byte. :param c: The number of bits to copy. Examples of returned mask: Returns Arguments 00001111 k=0, c=4 011111...
055945afb8ed2c3d1c57f00726f43a38d5fe98ba
678,925
def _hoist_track_info(track): """Mutates track with artist and album info at top level.""" track['album_name'] = track['album']['name'] artist = track['artists'][0] track['artist_name'] = artist['name'] return track
27c1a2729adceea06cb13618120703fc2a1d95d3
678,933
import time def isDSTTime(timestamp): """Helper function for determining whether the local time currently uses daylight saving time.""" local_time = time.localtime(timestamp) return time.daylight > 0 and local_time.tm_isdst > 0
48537d699cf973c05170c7eeced35d72e173a2d0
678,939
def get_endpoints(astute_config): """Returns services endpoints :returns: dict where key is the a name of endpoint value is dict with host, port and authentication information """ master_ip = astute_config['ADMIN_NETWORK']['ipaddress'] # Set default user/password becaus...
8aeb6cc6c83216026a94908e3cd5355e878fbf39
678,941
def single_child(node): """ The single child node or None. """ result = None if node.nodes is not None and len(node.nodes) == 1: result = node.nodes[0] return result
42bf0be4c202677e05fb5d589620233e6a13b645
678,944
def count_paras(paras): """Count the trainable parameters of the model. """ return sum(p.numel() for p in paras if p.requires_grad)
ad4d2748a1c301c63e2b6389efff425cae2664ed
678,951