content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def sqrt(x): """Return square root of x""" return x ** (0.5)
fb1b12a98f5c10dc04fce7827c8acd5be814926c
659,829
def _preamble(layout='layered'): """Return preamble and begin/end document.""" if layout == 'layered': layout_lib = 'layered' elif layout == 'spring': layout_lib = 'force' else: raise ValueError( 'Unknown which library contains layout: {s}'.format(s=layout)) docum...
2cb40fe7d48aa713f01ff79c093794156bff0c96
659,830
def isdistinct(seq): """ All values in sequence are distinct >>> isdistinct([1, 2, 3]) True >>> isdistinct([1, 2, 1]) False >>> isdistinct("Hello") False >>> isdistinct("World") True """ if iter(seq) is seq: seen = set() seen_add = seen.add for item ...
cc7b9c41b3942c1e117e7bd8e8c859be935a8efd
659,831
def buffer_polygon(ft): """Applies a buffer to a polygon""" return ft.buffer(-30, 1)
aec0b7903c9810fa55911115cfea0a1853e82320
659,836
def _make_list(obj): """Returns list corresponding to or containing obj, depending on type.""" if isinstance(obj, list): return obj elif isinstance(obj, tuple): return list(obj) else: return [obj]
9ac452733209033f1c6b5d6953680191971eb4d9
659,838
def _str_to_bool(string: str) -> bool: """ XML only allows "false" and "true" (case-sensitive) as valid values for a boolean. This function checks the string and raises a ValueError if the string is neither "true" nor "false". :param string: String representation of a boolean. ("true" or "false") ...
146bba8733768bbadf07c95839eb6db48fc50c12
659,840
def str_to_enum(name): """Create an enum value from a string.""" return name.replace(" ", "_").replace("-", "_").upper()
17b8f2448d59eccc6b0b34d2b8fb15daf00b7a57
659,843
from typing import Sequence import torch from typing import List def accum_grads(grads: Sequence[Sequence[torch.Tensor]]) -> List[torch.Tensor]: """ Compute accumulated gradients Parameters ---------- grads : Sequence[Sequence[torch.Tensor]] List of gradients on all previous tasks Re...
c1e60c1e4622cc2bcbe83996fc78101b2bed6864
659,844
from bs4 import BeautifulSoup import requests def world_covid19_stats(url: str = "https://www.worldometers.info/coronavirus") -> dict: """ Return a dict of current worldwide COVID-19 statistics """ soup = BeautifulSoup(requests.get(url).text, "html.parser") keys = soup.findAll("h1") values = s...
7840425d5c091c1cb967d2b06a957bb8b68493e3
659,847
import string import re def stemmer(word): """Return leading consonants (if any), and 'stem' of word""" consonants = ''.join([c for c in string.ascii_lowercase if c not in 'aeiou']) word = word.lower() match = re.match(f'([{consonants}]+)?([aeiou])(.*)', word) if match: p1 = match.gro...
d31aaef8cf354b57c7cb1a2b6869a5190b9a445f
659,849
def ascending(list: list) -> bool: """ Check if a list is in ascending ordering :rtype: bool :param list: a non empty list to check :return: if the list is in ascending order """ for i in range(len(list) - 1): if list[i] < list[i + 1]: return True return False
1d0b091f9be7a49e15f8163e9d409040d88f93d2
659,854
def _get_dependencies(dependencies): """Method gets dependent modules Args: dependencies (dict): dependent modules Returns: list """ mods = [] for key, val in dependencies.items(): mods.append(val['package']) return mods
7f9083fc198d252ac3643d1b11aee8cba5114cf4
659,856
def add_additonal_datetime_variables(df): """Adding variables derived from datetime: dropoff_month, *_week_of_year, *_day_of_year, *_day_of_month, *_weekday, *_is_weekend, *_hour""" print("adding additonal datetime variables") do_dt = df.dropoff_datetime.dt as_cat = lambda x: x.astype('category')...
474c10eaeeb0e98a94bd29f040861e05f3df38b8
659,860
def get_read_stop_position(read): """ Returns the stop position of the reference to where the read stops aligning :param read: The read :return: stop position of the reference where the read last aligned """ ref_alignment_stop = read.reference_end # only find the position if the reference e...
b9398e6e11ea052e017371dc368cb52f72dfc5b8
659,861
def player_table_variable_add(df, player_id, pos, year, player_name): """Adds specific variables as columns in a dataframe""" df = df.copy() df['player_id'] = player_id df['pos'] = pos df['year'] = year df['player_name'] = player_name return df
66a165fe1de8e1b135d11108a824c86112a6fb55
659,863
def avg(l): """Returns the average of a list of numbers Parameters ---------- l: sequence The list of numbers. Returns ------- float The average. """ return(sum(l) / float(len(l)))
97fc58a6065023fe4c53b9a9e2ab39a9f4b9df6b
659,864
import math def sum_log_scores(s1: float, s2: float) -> float: """Sum log odds in a numerically stable way.""" # this is slightly faster than using max if s1 >= s2: log_sum = s1 + math.log(1 + math.exp(s2 - s1)) else: log_sum = s2 + math.log(1 + math.exp(s1 - s2)) return log_sum
7e41d5e0838a3bf78b0dd7a5c2b01ddcd1216247
659,869
def get_types(field): """ Returns a field's "type" as a list. :param dict field: the field :returns: a field's "type" :rtype: list """ if 'type' not in field: return [] if isinstance(field['type'], str): return [field['type']] return field['type']
f09e0eac4470d6c21832b054f7988588e80dbaa3
659,873
def rescale_time(temporal_network, new_t0, new_tmax): """Rescale the time in this temporal network (inplace). Parameters ========== temporal_network : :mod:`edge_lists` or :mod:`edge_changes` new_t0 : float The new value of t0. new_tmax : float The new value of tmax. Re...
ea78615dc0d72b7b4a261265ef5f9968a593e1e1
659,874
def tokenize_char(sent): """ Tokenize a string by splitting on characters. """ return list(sent.lower())
d54e149f79598472d61eba42b77826942d1bd981
659,876
def unordlist(cs): """unordlist(cs) -> str Takes a list of ascii values and returns the corresponding string. Example: >>> unordlist([104, 101, 108, 108, 111]) 'hello' """ return ''.join(chr(c) for c in cs)
eb4f92a103b62428576a3129fdb95969c95f2cec
659,879
def get_force_datakeeper(self): """ Generate DataKeepers to store by default results from force module Parameters ---------- self: VarLoadFlux object Returns ------- dk_list: list list of DataKeeper """ dk_list = [] return dk_list
8ca0802eb75dd08b8aa70c037f2b3fd904711249
659,880
def is_vararg(param_name): """ Determine if a parameter is named as a (internal) vararg. :param param_name: String with a parameter name :returns: True iff the name has the form of an internal vararg name """ return param_name.startswith('*')
f9fda2b98038740c35b08222ed6c4fb929273b83
659,881
import random def shuffle(liste): """ brief: choose randomly in the given liste Args: tab :a list of values, raise Exception if not Returns: the value selected randomly Raises: ValueError if input tab is not a list """ if not(isinstance(liste, list)): raise ...
1b68a33b42ebb2d838aca1154d57b3f9ad2c3a33
659,882
def populate_cells(worksheet, bc_cells=[]): """ Populate a worksheet with bc_cell object data. """ for item in bc_cells: if item.cellref: worksheet[item.cellref].value = item.value else: worksheet.cell( row=item.row_num, column=item.col_num, value=...
4b5529ebbb63ebb3d0904d218807166af4bbff38
659,883
def get_query_types(query_list): """ This function is used to parse the query_ticket_grouping_types string from the app.config :param query_list: the string to parse into ticketType groupingType pairs for querying Securework ticket endpoint :return: List of json objects. Each json entry is a ticketType...
fdd78b4c655e9018597c65eba9cc361e3f526266
659,884
def lastLetter (s): """Last letter. Params: s (string) Returns: (string) last letter of s """ return s[-1]
2d1f5f9a1ae3fcc35fd7edcc4673d76627ffef95
659,888
from typing import List import itertools import random def get_separators( space_count: int, sep_count: int, padding_count: int, shuffle: bool ) -> List[str]: """Create a list of separators (whitespaces) Arguments: space_count : minimum number of spaces to add between workds (before padding) sep...
17506e4c94d497eb4c5167862ac63df370e4c783
659,891
import time def get_signature(user_agent, query_string, client_ip_address, lang): """ Get cache signature based on `user_agent`, `url_string`, `lang`, and `client_ip_address` """ timestamp = int(time.time()) / 1000 signature = "%s:%s:%s:%s:%s" % \ (user_agent, query_string, client_ip_...
1e4a56f066a60fe29db3a9a522a472fde5a977b3
659,892
def is_typed_tuple(tpl: object, obj_type: type, allow_none: bool = False, allow_empty: bool = True) -> bool: """ Check if a variable is a tuple that contains objects of specific type. :param tpl: The variable/list to check :param obj_type: The type of objects that the tuple should contain (for the chec...
fc6fe687d8334d1ee177f262221560bf9c46dbd7
659,893
def get_chain_offsets(chainlist, chainlength, chainpadding): """Generates chain offsets :param chainlist: Sorted list of chain letters :param chainlength: chain length dictionary :param chainpadding: chain padding dictionary :return: dictionary of chain offsets """ chainoffset = {} for ...
ef4aaa97e3d4d581ecde5100455fe6de0e33fc1f
659,897
import copy def _set_name(dist, name): """Copies a distribution-like object, replacing its name.""" if hasattr(dist, 'copy'): return dist.copy(name=name) # Some distribution-like entities such as JointDistributionPinned don't # inherit from tfd.Distribution and don't define `self.copy`. We'll try to set ...
a802dad26a2b8c54b1a395635d3cf967b8645e7a
659,898
def rayleigh_Z(n, r): """ Compute rayligh Z statistic :param n: sample size :param r: r-value (mean vector length) """ return n * (r**2)
ac72cce053eaac647ef5139257a189c1e7b79279
659,899
from bs4 import BeautifulSoup from typing import List from typing import Dict def get_author_names_from_grobid_xml(raw_xml: BeautifulSoup) -> List[Dict[str, str]]: """ Returns a list of dictionaries, one for each author, containing the first and last names. e.g. { "first": first, ...
d731db1c4109490867bbc20b6a1a59a50b70bbf3
659,900
def insight_dataframe(dataframe, dataframe_name): """Summary of the shape of a dataframe and view of the first 5 rows of the dataframe Parameters: dataframe (DataFrame): The dataframe we want to analyse dataframe_name (str) : Name of the dataframe Returns: str:Returning summary of the da...
412ed73cd3a2442bbb43828d3a05fdd1cd3f3199
659,901
def pr(x): """ Display a value and return it; useful for lambdas. """ print(x) return x
0a89752040852c4f9ba331eab939accde5b94cea
659,902
def default_window(win_id): """return default config for one window""" win = {} win['win_id'] = win_id win['mfact'] = 0.55 win['nmaster'] = 1 win['layout'] = 'horizontal' win['zoomed'] = False win['num_panes'] = 1 win['last_master_pane_id'] = None win['last_non_mas...
37c3a4753a8d2590676937e9355fb405ddc70dd9
659,903
def Euclidean_Distance(x,y,Boundaries = 'S',Dom_Size=1.0): """ Euclidean distance between positions x and y. """ d = len(x) dij = 0 #Loop over number of dimensions for k in range(d): # Compute the absolute distance dist = abs( x[k] - y[k] ) #Extra condition for periodic BCs: if Boundaries == 'P' o...
a91ea771da229d43f4209a9ffc02a0e9b231e97e
659,905
import re def _GetRcData(comment, rc_path, rc_data, pattern=None): """Generates the comment and `source rc_path` lines. Args: comment: The shell comment string that precedes the source line. rc_path: The path of the rc file to source. rc_data: The current comment and source rc lines or None. patt...
7d1c340a042f7449a92fd7295deba9557ca147eb
659,907
def inconsistent_typical_range_stations(stations): """Given list of stations, returns list of stations with inconsistent data""" inconsiststations = [] for i in stations: if i.typical_range_consistent() == False: inconsiststations.append(i) return inconsiststations
30b5a95ba1715e6781554a04d9c502ebc8d69709
659,909
def intersection(u, v): """Return the intersection of _u_ and _v_. >>> intersection((1,2,3), (2,3,4)) [2, 3] """ w = [] for e in u: if e in v: w.append(e) return w
683aa5c8a0ced935cd252b782af163bfd1a4e7d2
659,911
import re def get_title(name): """ Use a regular expression to search for a title. Titles always consist of capital and lowercase letters, and end with a period. """ title_search = re.search(" ([A-Za-z]+)\.", name) if title_search: return title_search.group(1) return ""
b04ac3752d402021c3ffba709a02b8c9bfa41557
659,914
def importName(modulename, name): """ Import a named object from a module in the context of this function. """ try: module = __import__(modulename, globals(), locals(), [name]) except ImportError: return None return getattr(module, name)
3698aedbc39331cccfa849903c6465bde24c3f41
659,917
def module_equals(model1, model2): """Check if 2 pytorch modules have the same weights """ for p1, p2 in zip(model1.parameters(), model2.parameters()): if p1.data.ne(p2.data).sum() > 0: return False return True
cf23a7da62d95b80f6f878dc77f65e14db74dba6
659,918
def diff(data: list[int]) -> list[int]: """Calculate the difference between numeric values in a list.""" previous = data[0] difference = [] for value in data[1:]: difference.append(value - previous) previous = value return difference
008ae124f2306ce27c4bafed14d8e204fcbd6f2e
659,920
def plot_histograms(ax, prng, nb_samples=10000): """Plot 4 histograms and a text annotation.""" params = ((10, 10), (4, 12), (50, 12), (6, 55)) for a, b in params: values = prng.beta(a, b, size=nb_samples) ax.hist(values, histtype="stepfilled", bins=30, alpha=0.8, density=True) # Add a s...
022ae87044b2f84f544736aa4cf7f65a0a0e4c3d
659,922
import json def _extract_multi_block_from_log(log_content, block_name): """ Extract multiple data blocks from a simultaneous REFL1D fit log. The start tag of each block will be [block_name]_START and the end tag of each block will be [block_name]_END. :param str log_content: strin...
5bfaf61474811fda022a0bc2387837a9c2d6080d
659,923
def strip_path_prefix(path, prefix): """ Strip a prefix from a path if it exists and any remaining prefix slashes. Args: path: The path string to strip. prefix: The prefix to remove. Returns: The stripped path. If the prefix is not present, this will be the same as the input. ...
765c3ff2639ad346cc525b080822de79ba710c01
659,925
def developer_token() -> str: """The developer token that is used to access the BingAds API""" return '012345679ABCDEF'
76926fb74e049e37e6fef0e56ff53cb59a5566a4
659,933
def centerCropImage(img, targetSize): """ Returns a center-cropped image. The returned image is a square image with a width and height of `targetSize`. """ # Resize image while keeping its aspect ratio width, height = img.size if height < targetSize: print(str(height) + " height < targetSiz...
4e89f0f0099c968989a203b4b64d6f64f4015ba3
659,935
def get_string_between_nested(base, start, end): """Extracts a substring with a nested start and end from a string. Arguments: - base: string to extract from. - start: string to use as the start of the substring. - end: string to use as the end of the substring. Returns: - The substring if found...
ed36a5a0c6f293aa6fd40a2898c3255cd726f1bf
659,937
def convert_str_color_to_plt_format(txt): """ Converts an rgb string format to a tuple of float (used by matplotlib format) Parameters ---------- txt : str a string representation of an rgb color (used by plotly) Returns ------- A tuple of float used by matplotlib format E...
0fe890867c18ff961ea39151a4eb1a36279323a6
659,938
async def get_ltd_product_urls(session): """Get URLs for LSST the Docs (LTD) products from the LTD Keeper API. Parameters ---------- session : `aiohttp.ClientSession` Your application's aiohttp client session. See http://aiohttp.readthedocs.io/en/stable/client.html. Returns ---...
bad9b327ad4c0f2def43096b3820f2d8a2bfd33e
659,942
def tochar(v): """Check and convert value to a character""" if isinstance(v, str) and len(v) == 1: return v else: raise ValueError('Expected a character, but found %s' % v)
e406db33807ca0f25e5b348924226b58fcf04da3
659,945
def convert_list_to_sql_tuple(filter_list): """ This function takes a list and formats it into a SQL list that can be used to filter on in the WHERE clause. For example, ['a', 'b'] becomes ('a', 'b') and can be applied as: SELECT * FROM table WHERE column IN ('a', 'b'). Note that any pre-formatting on...
0571fbc5e79169acd48c5983bda92e8a084a20a5
659,953
def transform_keyword(keywords): """ Transform each keyword into a query string compatible string """ keywordlist = [] for keyword in keywords: keywordlist.append(keyword.lower().replace(" ", "+")) return keywordlist
64d2e47bfab5575a5174861d8636c127bb20510e
659,956
def average_daily_peak_demand(peak_usage: float, peak_hrs: float = 6.5) -> float: """ Calculate the average daily peak demand in kW :param peak_usage: Usage during peak window in kWh :param peak_hrs: Length of peak window in hours """ return peak_usage / peak_hrs
e3793bfb7c22af9876bdb99ab75ed475f4901b25
659,960
import re def herbarium(image_file): """Map the image file name to a herbarium.""" image_file = str(image_file) if image_file == 'nan': return '' image_file = image_file.upper() parts = re.split(r'[_-]', image_file) return parts[1] if parts[0] == 'TINGSHUANG' else parts[0]
ce496261b5a79ee4e1ec3fc5743530b65cdbbaaf
659,962
def range_addition(n, updates): """ LeetCode 370: Range Addition Assume you have a list `[0] * n` and are given k update operations. Each operation is represented as a triplet `[start_index, end_index, increment]`, which adds increment to each element of subarray A[start_index ... end_index] (start...
906971c1cf768d2893dd2ca093cf9cca58ba23c2
659,966
async def get_message(ctx, message:int): """ Returns a previous message for a given channel and location (relative to context). Parameters: ctx (context): Passthrough for context from command. message (int): Location of message relative to sent command. Returns: Message: The me...
9ceb5499fd8afb9ec25ae010c7645b4bda9f4c17
659,970
def parse_event_data(event): """Parses Event Data for S3 Object""" s3_records = event.get('Records')[0].get('s3') bucket = s3_records.get('bucket').get('name') key = s3_records.get('object').get('key') data = {"Bucket": bucket, "Key": key} return data
26bcce3dbaa3ce64c906d137261b3ef9458f59b6
659,971
def _check_symmetry(matrix): """ Checks whether a matrix M is symmetric, i.e. M = M^T. By @t-kimber. Parameters ---------- matrix : np.array The matrix for which the condition should be checked. Returns ------- bool : True if the condition is met, False otherwise. ...
e12ae8abb821d12fa83950c0fb61c6d89410fe4c
659,975
from typing import Tuple import math def calc_differential_steering_angle_x_y(wheel_space: int, left_displacement: float, right_displacement: float, orientation: float) -> Tuple[float, float, float]: """ Calculate the next orientation, x and y values of a two-wheel ...
1669b5082bf9c6f1f2cbf0fb68c7e142c55b9988
659,976
import itertools def concat(*iterables): """ :param iterables: the iterables to concatenate :return: the concatenated list :rtype: list """ return list(itertools.chain(*iterables))
82feab920d93fbb744e507e1d499358df31e1c33
659,985
import time import calendar def format_time(time_str, format): """ This will take a time from Jira and format it into the specified string. The time will also be converted from UTC to local time. Jira time format is assumed to be, "YYYY-MM-DDTHH:MM:SS.ssss+0000". Where "T" is the literal charact...
4c8126f3348cef9b9311e48f9564529945bd2aaf
659,988
def _get_row_partition_type_tensor_pairs_tail(partition): """Gets a row partition type tensor pair for the tail. If value_rowid is defined, then it is used. Otherwise, row_splits are used. Args: partition: a RowPartition. Returns: A list of (row_partition_type, row_partition_tensor) pairs. """ ...
ef72da5b236c967a388c5da524e417f830aec738
659,991
import math def compute_perfect_tree(total): """ Determine # of ways complete tree would be constructed from 2^k - 1 values. This is a really subtle problem to solve. One hopes for a recursive solution, because it is binary trees, and the surprisingly simple equation results from the fact that it ...
648840b7c1fb562fa98cc9eaabb0775013d0019e
659,992
def get_choices(query): """Get a list of selection choices from a query object.""" return [(str(item.id), item.name) for item in query]
677938799a1b42d13fb73b578370546c92b47a5d
659,996
import math def power_sum( pdb_lst ): """ take a list of powers in dBm, add them in the linear domain and return the sum in log """ sum_lin = 0 for pdb in pdb_lst: sum_lin += 10**(float(pdb)/10)*1e-3 return 10*math.log10(sum_lin/1e-3)
03cc41a7520f78e5608e3dff4e5989f0f704bd7e
660,000
def interval_intersection(interval1, interval2): """Compute the intersection of two open intervals. Intervals are pairs of comparable values, one or both may be None to denote (negative) infinity. Returns the intersection if it is not empty. >>> interval_intersection((1, 3), (2, 4)) (2, 3) ...
56ed1fa4e8f800512f242a1a2bf66cf1f0c2c3ec
660,001
from typing import Union def is_true(val: Union[str, int]) -> bool: """Decide if `val` is true. Arguments: val: Value to check. Returns: True or False. """ value = str(val).strip().upper() if value in ("1", "TRUE", "T", "Y", "YES"): return True return False
0f6fd71222d343ca0cc614e6a71c7ca2907a0f1b
660,002
def humanize_bytes( num: float, suffix: str = "B", si_prefix: bool = False, round_digits: int = 2 ) -> str: """Return a human friendly byte representation. Modified from: https://stackoverflow.com/questions/1094841/1094933#1094933 Args: num: Raw bytes suffix: String to append s...
ccbbf472a8e6bb5f5c065532a96702698e11b55d
660,004
import math def boiling_point(altitude): """ Get the boiling point at a specific altitude https://www.omnicalculator.com/chemistry/boiling-point-altitude :param float altitude: Altitude in feet (ft) :return: The boiling point in degF :rtype: float """ pressure = 29.921 * pow((1 - 0....
08cdb56482571d69acdaf25f10e39f2845590821
660,006
def macroName(o): """ Return the macro name of the given object """ if o.macroName is None: if type(o) is type: return o.__name__ return type(o).__name__ return o.macroName
151fb46017c89c9bca4d2219d19eeaf812d74bfe
660,007
def get_usa_veh_id(acc_id, vehicle_index): """ Returns global vehicle id for USA, year and index of accident. The id is constructed as <Acc_id><Vehicle_index> where Vehicle_index is three digits max. """ veh_id = acc_id * 1000 veh_id += vehicle_index return veh_id
e89875d5f9f48293e3069a7fe468ee9455d24147
660,010
import calendar def to_unix_timestamp(timestamp): """ Convert datetime object to unix timestamp. Input is local time, result is an UTC timestamp. """ if timestamp is not None: return calendar.timegm(timestamp.utctimetuple())
95481b7c9d1a3a63e6a428f28e8a2fd87e49c623
660,015
import platform def is_platform_arm() -> bool: """ Checking if the running platform use ARM architecture. Returns ------- bool True if the running platform uses ARM architecture. """ return platform.machine() in ("arm64", "aarch64") or platform.machine().startswith( "armv"...
5e487a5d8a6e3423f9752c1e7b520afd8a2d5f08
660,016
def get_content(html_soup): """ Extracts text content of the article from content Input : Content in BeautifulSoup format Output : Text content of the article """ html_soup.find('figure').extract() content = html_soup.find('div', attrs = {"class" : "entry-content"}).get_text() return con...
88e02d03616a25b27b53d02a2888cc6d4088cad1
660,017
import yaml def read_radial_build(file_): """ Loads the radial build YAML file as a Python dictionary Parameters ---------- file_ : str The radial build file path Returns ------- radial_build : list A Python dictionary storing the tokamak radial build data """ ...
c3560cf582941bbc9bdec99d5692983cffee98f7
660,018
def strip_module_names(testcase_names): """Examine all given test case names and strip them the minimal names needed to distinguish each. This prevents cases where test cases housed in different files but with the same names cause clashes.""" result = list(testcase_names) for i, testcase in enumerat...
40f63942d27b7d2fe06f4ad96ea2faad6937eab1
660,019
def text_to_lowercase(text): """Set all letters to lowercase""" return text.lower()
69809b8e02ae468067a55cfdf2b56b020e3f9883
660,024
def safe_compare(val1, val2): """ Compares two strings to each other. The time taken is independent of the number of characters that match. :param val1: First string for comparison. :type val1: :class:`str` :param val2: Second string for comparison. :type val2: :class:`str` :returns: ...
a3ed9bff7516add1b062e45d58c508fa0ea7f35e
660,026
def loess_abstract(estimator, threshold, param, length, migration_time, utilization): """ The abstract Loess algorithm. :param estimator: A parameter estimation function. :type estimator: function :param threshold: The CPU utilization threshold. :type threshold: float :param param: The safe...
34908b76d135cd0b087943cea59ec480844bc082
660,028
def construct_backwards_adjacency_list(adjacency_list): """ Create an adjacency list for traversing a graph backwards The resulting adjacency dictionary maps vertices to each vertex with an edge pointing to them """ backwards_adjacency_list = {} for u in adjacency_list: for v in adjacency_list[u...
ecb2c4eefe3e1c7fa67a66f8aa9701d7c443cb12
660,032
import math def law_of_cosines(a, b, angle): """ Return the side of a triangle given its sides a, b and the angle between them (Law of cosines) """ return math.sqrt( a**2 + b**2 - 2*a*b*math.cos(math.radians(angle)) )
743748d8eff369e9cd01367569b38c90fcac1f09
660,035
def normalize_confusion_matrix(confusion_matrix_dict: dict, normalize_index: int = 0) -> dict: """ normalize a confusion matrix; :param confusion_matrix_dict: dict, a confusion matrix, e.g., {('a', 'a'): 1, ('a', 'b'): 2, ('b', 'a'): 3, ('b', 'b'): 4}; :param normalize_index: int, [0, 1], the p...
2241226671139ee816c104de80bc865aca2f12ae
660,040
def is_nested_list(l): """ Check if list is nested :param l: list :return: boolean """ return any(isinstance(i, list) for i in l)
229f244de536edc1f9496851ef1991ebdb343bdf
660,042
def get_db_collections(db): """ db.collection_names() DeprecationWarning: collection_names is deprecated. Use list_collection_names instead. """ # return db.collection_names() return db.list_collection_names()
d27d1c4cae4cab70a039a96cc594fd3302cee775
660,043
import re def check_if_border(feature, operon_borders): """Return start/end coordinate of the SeqFeature if its accession is the first/last in the given tuple. Parameters ---------- feature : SeqFeature Directory with input genbank files. operon_borders : str Directory to store th...
4cb9cdbfd9f72427b783c848a782cb2f70d98a32
660,044
import random def random_color_from_string(str): """ Given a string, return an RGB color string. The same string will always give the same result but otherwise is random. """ rng = random.Random(str) cs = ['#d98668', '#d97400', '#bfab5c', '#aee66e', '#9bf2be', '#1b9ca6', '#0088ff', '#0000a6', ...
19b94272ab9617ac70a7b1b447a57c2d5c1f05c6
660,047
def find_variable(frame, varname): """Find variable named varname in the scope of a frame. Raise a KeyError when the varname cannot be found. """ try: return frame.f_locals[varname] except KeyError: return frame.f_globals[varname]
f97bbcd5d60faf7cecce12d08f53eb144a766bd0
660,049
def xml_output_document(request): """XML document generated by XSLT transform.""" document = request.param return document
de6bb2b3d6b9da15a03727948efac1e5d7ae6005
660,050
def join_ints(ints): """Joins list of intergers into the ordered comma-separated text. """ return ','.join(map(str, sorted(ints)))
1e263fe00c01fd81252df0e824f5300126374cbd
660,051
import re def get_version(galaxy_file): """ Get the version from the collection manifest file (galaxy.yml). In order to avoid the dependency to a yaml package, this is done by parsing the file with a regular expression. """ with open(galaxy_file, 'r') as fp: ftext = fp.read() m = ...
eed57ff44af9139a0ef80cc596e2f5ee2a6027d5
660,055
import re def getIDfromComment(line): """ Get id from comment Returns 1510862771508 from <!-- 1510862771508 --> """ idPattern = re.compile("\d{13,}") return idPattern.findall(line)[0]
501650935c53a4e1019434bff09d29e2cac6c2bb
660,062
def _sample_distribution_over_matrix(rng): """Samples the config for a distribution over a matrix. Args: rng: np.random.RandomState Returns: A distribution over matrix config (containing a tuple with the name and extra args needed to create the distribution). """ # At this point, the choices her...
20c39319f217e62bd33e06f4f556030f133baff7
660,063
from datetime import datetime def get_todays_date_obj(obj): """Get the date of the daily post and return the date in %d-%B-%Y format""" title = obj.title daily_title = title.split(' ') todays_date = '{}-{}-{}'.format(daily_title[4].rstrip(','), daily_title[3], d...
f5163ac7278357b841b1332ffa670fd4bb1101e4
660,064
def _duration_to_nb_windows( duration, analysis_window, round_fn=round, epsilon=0 ): """ Converts a given duration into a positive integer of analysis windows. if `duration / analysis_window` is not an integer, the result will be rounded to the closest bigger integer. If `duration == 0`, returns `0`...
c6e90549a3c7f7ad42f2bf6c11fa537cc94a112a
660,066
def dt64_epoch(dt64): """ Convert a panda or xarray date/time value represented as a datetime64 object (nanoseconds since 1970) to a float, representing an epoch time stamp (seconds since 1970-01-01). :param dt64: panda or xarray datatime64 object :return epts: epoch time as seconds since 1970-01-0...
fcddeb30780187d85c5a99d9cb4d341b9c57c976
660,068
def viss(t, d): """Viscosity of vapour as a function of temperature (deg C) and density (kg / m3).""" V1 = 0.407 * t + 80.4 if t <= 350.0: return 1.0e-7 * (V1 - d * (1858.0 - 5.9 * t) * 1.0e-3) else: return 1.0e-7 * (V1 + d * (0.353 + d * (676.5e-6 + d * 102.1e-9)))
5ad2b5bad9bd679409bdee914cce504c15fe5980
660,072