content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def chroma_correlate(Lstar_P, S): """ Returns the correlate of *chroma* :math:`C`. Parameters ---------- Lstar_P : numeric *Achromatic Lightness* correlate :math:`L_p^\star`. S : numeric Correlate of *saturation* :math:`S`. Returns ------- numeric Correlate ...
cc583c39c0b64e4075d8f4711163d9cd09875f77
682,040
def find_median(quantiles): """Find median from the quantile boundaries. Args: quantiles: A numpy array containing the quantile boundaries. Returns: The median. """ num_quantiles = len(quantiles) # We assume that we have at least one quantile boundary. assert num_quantiles > 0 median_index = ...
7d65a2fc1f1a6ec5836b841fe5c7e280b0e4c056
682,041
from pathlib import Path import string def guess_pdb_type(pdb_file: str) -> str: """Guess PDB file type from file name. Examples -------- >>> _guess_pdb_type('4dkl.pdb') 'pdb' >>> _guess_pdb_type('/tmp/4dkl.cif.gz') 'cif' """ for suffix in reversed(Path(pdb_file).suffixes): ...
a156ac86c02d05b6f6783bf62f8e3ad06c717744
682,042
import re def replace_text(input_str, find_str, replace_str, ignore_case=False, regex=True, quiet=True): """Find and replace text in a string. Return the new text as a string. Arguments: input_str (str) -- the input text to modify find_str (str) -- the text to find in the input text replace_str (str) -- ...
1979e5a52c2135500d42e00b67d207eddbf248c2
682,043
async def _verify_provision_request(request, params): """Verifies a received 'provision' REST command. Args: request (aiohttp.Web.Request): The request from the client. params (dict-like): A dictionary like object containing the REST command request parameters. Returns: (boolean, s...
fb8db3b3cc8aa12232997e71d5c130402cb45525
682,046
def verify_filename(filename: str) -> str: """ Check file name is accurate Args: filename (str): String for file name with extension Raises: ValueError: Provide filename with extensions ValueError: Specify a length > 0 Returns: str: Verified file name """ if le...
fe989269d4861d209efddf1b13e84e24ba3cfb0c
682,048
def _batchwise_fn(x, y, f): """For each value of `x` and `y`, compute `f(x, y)` batch-wise. Args: x (th.Tensor): [B1, B2, ... , BN, X] The first tensor. y (th.Tensor): [B1, B2, ... , BN, Y] The second tensor. f (function): The function to apply. Returns: (th.Tensor): [B1, B...
bd9b291c00d5905281fb1ac14d3fd2f57c0141ca
682,049
def _pairs(items): """Return a list with all the pairs formed by two different elements of a list "items" Note : This function is a useful tool for the building of the MNN graph. Parameters ---------- items : list Returns ------- list list of pairs formed by two dif...
0dad2a9a77bbcb20359c28db2845cb6e46118761
682,050
def dt_minutes(dt): """Format a datetime with precision to minutes.""" return dt.strftime('%Y-%m-%d %H:%M')
8f510b9207e89500458324bee86bc1428e1e12c9
682,054
def baryocentric_coords(pts,pt): """See e.g.: http://en.wikipedia.org/wiki/Barycentric_coordinate_system_%28mathematics%29""" xs,ys=list(zip(*pts)) x,y=pt det=(ys[1]-ys[2])*(xs[0]-xs[2])+(xs[2]-xs[1])*(ys[0]-ys[2]) l1=((ys[1]-ys[2])*(x-xs[2])+(xs[2]-xs[1])*(y-ys[2]))/float(det) l2=((ys...
370bf1a101fb5cae02f4e0703bcf62c29ab4ddd6
682,055
def read_file(filename): """Returns the contents of a file as a string.""" return open(filename).read()
bb6906cbc580e57dc9de917f962362305694e393
682,059
def create_dict_keyed_by_field_from_items(items, keyfield): """ given a field and iterable of items with that field return a dict keyed by that field with item as values """ return {i.get(keyfield): i for i in items if i and keyfield in i}
a7478c5dc04d7e23801eecb5aaf85b7530d6bf79
682,062
def get_item(value: dict, key: str): """Returns a value from a dictionary""" return value.get(key, None)
2b27510c1ece30970b263c5b127d2911e8b117ca
682,063
import re def camelcase(string, uppercase=True): """Converts a string to camelCase. Args: uppercase (bool): Whether or not to capitalize the first character """ if uppercase: return re.sub(r'(?:^|_)(.)', lambda s: s.group(1).upper(), string) else: return string[0].lower() ...
fc480133abcb012124a4557dcc9474eac5bb86cc
682,065
def read_file(file_path): """Loads raw file content in memory. Args: file_path (str): path to the target file. Returns: bytes: Raw file's content until EOF. Raises: OSError: If `file_path` does not exist or is not readable. """ with open(file_path, 'rb') as byte_file: ...
5d3d361c3823eeca561895c9b28ca2b2c379f86c
682,069
def Annotation(factories, index_annotations): """Create and index an annotation. Looks like factories.Annotation() but automatically uses the build() strategy and automatically indexes the annotation into the test Elasticsearch index. """ def _Annotation(**kwargs): annotation = factori...
315dfd1a4180e4686dd69441efc5c97389c85b69
682,077
def check_hermes() -> bool: """ Check if hermes-parser is available on the system.""" try: return True except ImportError: return False
3bf1d0ceed005e5c85fdd03494cef32fa6a31291
682,078
from typing import Optional def _is_in_range(a_list: list, min: Optional[float] = None, max: Optional[float] = None) -> bool: """ Return True if `a_list` ontains values between `min` and `max`, False otherwise """ for el in a_list: if min is not None: ...
af50579279e98459dd4ed759c7fe36efd1caeff7
682,079
def calculateAvgMass(problemFile,windno): """ Calculate the average mass of a winds flow Inputs: - dict problemFile: problem file, containing mass fractions - int windno: wind number, counting from 1 Outputs: - avgMass: average mass of particles in wind (g) """ protonmass = 1.6726219e-24 ...
a4522d98fbe91aa45ebb25f0a64f9ebdb0abbe3e
682,081
def get_reorg_matrix(m, m_size, transition_state_nb): """ Reorder the matrix to only keep the rows with the transition states By storing the new order in an array, we can have a mapping between new pos (idx) and old pos (value) For example reorg_states = [2,3,1,0] means the first new row/col was in posi...
35cf06daa0225e53fbdc21f2fe34a3337c1b1901
682,082
import time def _get_time_diff_to_now(ts): """Calculate time difference from `ts` to now in human readable format""" secs = abs(int(time.time() - ts)) mins, secs = divmod(secs, 60) hours, mins = divmod(mins, 60) time_ago = "" if hours: time_ago += "%dh" % hours if mins: tim...
091f420971f23432c3ebaa1bef93b60ff2953c88
682,083
def _read_file(name, encoding='utf-8'): """ Read the contents of a file. :param name: The name of the file in the current directory. :param encoding: The encoding of the file; defaults to utf-8. :return: The contents of the file. """ with open(name, encoding=encoding) as f: return f...
c0a03bee2d4ef48dd13c72cc3b05f7e10d724e5c
682,084
def binary_array_search(A, target): """ Use Binary Array Search to search for target in ordered list A. If target is found, a non-negative value is returned marking the location in A; if a negative number, x, is found then -x-1 is the location where target would need to be inserted. """ lo =...
a1f4908032910ea6a7c14e9509953450c9a0a44e
682,085
def _convert_float(value): """Convert an "exact" value to a ``float``. Also works recursively if ``value`` is a list. Assumes a value is one of the following: * :data:`None` * an integer * a string in C "%a" hex format for an IEEE-754 double precision number * a string fraction of the for...
7896c97dafd577b6eefec452f5983c8c06c5f831
682,086
def origin2center_of_mass(inertia, center_of_mass, mass): """ convert the moment of the inertia about the world coordinate into that about center of mass coordinate Parameters ---------- moment of inertia about the world coordinate: [xx, yy, zz, xy, yz, xz] center_of_mass: [x, y, z] ...
9d083c767956b0dddf3a7fea10c17c42fe9354d3
682,091
def _versionTuple(versionString): """ Return a version string in 'x.x.x' format as a tuple of integers. Version numbers in this format can be compared using if statements. """ if not isinstance(versionString, str): raise ValueError("version must be a string") if not versionString.count("...
cc64832a8b7c1c46d639a8628ca7afd8701d7135
682,097
import re def SplitBehavior(behavior): """Splits the behavior to compose a message or i18n-content value. Examples: 'Activate last tab' => ['Activate', 'last', 'tab'] 'Close tab' => ['Close', 'tab'] """ return [x for x in re.split('[ ()"-.,]', behavior) if len(x) > 0]
c388e0a2b57e1826176d7032775622abd0ca5f7c
682,099
def reformat(keyword, fields): """ Reformat field name to url format using specific keyword. Example: reformat('comment', ['a','b']) returns ['comment(A)', 'comment(B)'] """ return ['{}({})'.format(keyword, f.upper()) for f in fields]
b277eb2efdb78d49035c319e1ca31c1c7ff3e333
682,101
def diff_msg_formatter( ref, comp, reason=None, diff_args=None, diff_kwargs=None, load_kwargs=None, format_data_kwargs=None, filter_kwargs=None, format_diff_kwargs=None, sort_kwargs=None, concat_kwargs=None, report_kwargs=None, ): # pylint: disable=too-many-arguments ...
8586c9364e1aef2777cf33a91efa4ffd8aa48708
682,102
def corn() -> str: """Return the string corn.""" return "corn"
e8cbbc3804a24006f2eeef72f9a03cb5a737283d
682,103
def celsius_to_rankine(temp: float) -> float: """ Converts temperature in celsius to temperature in rankine Args: temp (float): supplied temperature, in celsius Returns: float: temperature in rankine """ return (9 / 5) * temp + 491.67
aac1daf7b9681c7ece129b2a1f5ca7e7b9388ad9
682,106
def configs_check(difflist): """ Generate a list of files which exist in the bundle image but not the base image '- ' - line unique to lhs '+ ' - line unique to rhs ' ' - line common '? ' - line not present in either returns a list containing the items which are unique in the rhs ...
897c0b9c05e26619f4d10f693173642f2ffabc8a
682,107
def _broadcast_bmm(a, b): """ Batch multiply two matrices and broadcast if necessary. Args: a: torch tensor of shape (P, K) or (M, P, K) b: torch tensor of shape (N, K, K) Returns: a and b broadcast multipled. The output batch dimension is max(N, M). To broadcast transforms a...
152769b8509eb709d7b762cc718543006dbf29f2
682,111
def _CommonChecks(input_api, output_api): """Checks common to both upload and commit.""" results = [] results.extend( input_api.canned_checks.CheckChangedLUCIConfigs(input_api, output_api)) return results
5ffed5770f6f776851ebe08db0c1bbdf66b89694
682,112
import re def _htmlPingbackURI(fileObj): """Given an interable object returning text, search it for a pingback URI based upon the search parameters given by the pingback specification. Namely, it should match the regex: <link rel="pingback" href="([^"]+)" ?/?> (source: http://www.hixie.ch/specs...
342f401cb955af511040be30cb56c80d05dfeeda
682,113
def add_train_args(parser): """Add training-related arguments. Args: * parser: argument parser Returns: * parser: argument parser with training-related arguments inserted """ train_arg = parser.add_argument_group('Train') train_arg.add_argument('--train_prep', ...
de97966105e08c03f0de180f0385e2ccd6a455ea
682,115
def _convert_graph(G): """Convert a graph to the numbered adjacency list structure expected by METIS. """ index = dict(zip(G, list(range(len(G))))) xadj = [0] adjncy = [] for u in G: adjncy.extend(index[v] for v in G[u]) xadj.append(len(adjncy)) return xadj, adjncy
ba3fc856896c5e6ac1a76668cff519871ee7805d
682,117
import struct import socket def d2ip(d): """Decimal to IP""" packed = struct.pack("!L", d) return socket.inet_ntoa(packed)
e54252c85e7403531342e3fc71a0ebf5f6b5fe16
682,118
import zlib def crc32_hex(data): """Return unsigned CRC32 of binary data as hex-encoded string. >>> crc32_hex(b'spam') '43daff3d' """ value = zlib.crc32(data) & 0xffffffff return f'{value:x}'
0535421da8671f7d3d329c0c8e0a4cf51a29d1cf
682,119
import re def fix_punct_spaces(string: str): """ fix_punct_spaces - replace spaces around punctuation with punctuation. For example, "hello , there" -> "hello, there" Parameters ---------- string : str, required, input string to be corrected Returns ------- str, corrected string ...
ba6e532b2ba702e6a4f4d76484f184a406c5a629
682,120
from datetime import datetime def find_time_since(previous_time): """Just finds the time between now and previous_time.""" return datetime.now() - previous_time
6cdeff0005cf58aa5bd0fc174658e8524a40c83c
682,121
def dansCercle(x,y, cx,cy, r): """ Teste l'appartenance à un cercle. Paramètres: (x,y) --> point à tester, (cx,cy) --> centre du cercle, r --> rayon du cercle. Retourne ``Vrai`` si le point est dans le cercle, ``Faux`` sinon. """ return (x-cx)**2 + (y-cy)**2 <= ...
a429bc6a40d0c49bbc331d9cf0f4011137188900
682,129
from typing import Collection def split_identifier(all_modules: Collection[str], fullname: str) -> tuple[str, str]: """ Split an identifier into a `(modulename, qualname)` tuple. For example, `pdoc.render_helpers.split_identifier` would be split into `("pdoc.render_helpers","split_identifier")`. This is n...
aa9e6ace179634167d8820ccf4d48053ce64ca59
682,130
def read_txt(filename='filename.txt'): """Read a text file into a list of line strings.""" f = open(filename, 'r') data = f.readlines() f.close() return data
ee74a55af75cbbf5f5065f97becf663cc7d01344
682,131
import re def _str_time_to_sec(s): """ Converts epanet time format to seconds. Parameters ---------- s : string EPANET time string. Options are 'HH:MM:SS', 'HH:MM', 'HH' Returns ------- Integer value of time in seconds. """ pattern1 = re.compile(r'^(\d+):(\d+):(\d+...
5bb000920ff3295607317f4d8d001a4b7b859549
682,133
def apisecret(request): """Return API key.""" return request.config.getoption("--apisecret")
152694affb473bc1f44678cda3b89d6aa95804ad
682,134
def pretty_hex_str(byte_seq, separator=","): """Converts a squence of bytes to a string of hexadecimal numbers. For instance, with the input tuple ``(255, 0, 10)`` this function will return the string ``"ff,00,0a"``. :param bytes byte_seq: a sequence of bytes to process. It must be compatible ...
2f3f43bffff140320b12dce5d423d7e3f64b88e5
682,136
def score2durations(score): """ Generates a sequence of note durations (in quarterLengths) from a score. Args: score (music21.Score): the input score Returns: list[float]: a list of durations corresponding to each note in the score """ return [n.duration.quarterLength for n in scor...
2b7060bd5101a10ae4816816a8fbdc812c311cf2
682,138
import torch def complex_abs_sq(data: torch.Tensor) -> torch.Tensor: """ Compute the squared absolute value of a complex tensor. Args: data: A complex valued tensor, where the size of the final dimension should be 2. Returns: Squared absolute value of data. """ if...
42a2cc3daec9ee8cc381985622d89f7ca0665a5d
682,143
def has_attribute(object, name): """Check if the given object has an attribute (variable or method) with the given name""" return hasattr(object, name)
44f0cd1cc54fe61b755d94629e623afe234fe99d
682,145
def filtro_ternario(cantidad_autos: int, numero_auto: int) -> int: """ Filtro ternario Parámetros: cantidad_autos (int): La cantidad de carros que recibe el operario en su parqueadero numero_auto (int): El número único del carro a ubicar en alguno de los tres lotes de parqueo. Se ...
5607c83bc7e3e3cc28dd33e72bc86c943884bf3f
682,146
def text_alignment(x: float, y: float): """ Align text labels based on the x- and y-axis coordinate values. This function is used for computing the appropriate alignment of the text label. For example, if the text is on the "right" side of the plot, we want it to be left-aligned. If the text i...
477ab0dffa22de16af3d1811b39fbfc5289c4327
682,147
def _get_snap_name(snapshot): """Return the name of the snapshot that Purity will use.""" return "{0}-cinder.{1}".format(snapshot["volume_name"], snapshot["name"])
d78deb9ee0b8264868ac120f34b9c862784ab5e7
682,154
def is_even(n): """ True if the integer `n` is even. """ return n % 2 == 0
3e23d6b821c1d396e9ca74d3bb9360531687e940
682,155
def original_choice(door): """ Return True if this door was picked originally by the contestant """ return door.guessed_originally is True
5d2c11e32ef4181b653642fb18a995427a3bae9b
682,158
def get_neighbors(x, y): """Returns the eight neighbors of a point upon a grid.""" return [ [x - 1, y - 1], [x, y - 1], [x + 1, y - 1], [x - 1, y ], [x + 1, y ], [x - 1, y + 1], [x, y + 1], [x + 1, y + 1], ]
21ec6d4f4143f717388ff20def80fd53127bc1ed
682,159
def user_to_dict(user): """ Convert an instance of the User model to a dict. :param user: An instance of the User model. :return: A dict representing the user. """ return { 'id': user.id, 'demoId': user.demoId, 'email': user.email, 'username': user.username...
d3e41fc8f377faf35c3a64ce8716fac6e35a611e
682,161
def _suffix(name, suffix=None): """Append suffix (default _).""" suffix = suffix if suffix else '_' return "{}{}".format(name, suffix)
b7b90f14c2f656b31561b9cabd73649464d507cc
682,163
def test_orchestrator_backup_config( self, protocol: int, hostname: str, port: int, directory: str, username: str, password: str, ) -> dict: """Test specified settings for an Orchestrator backup .. list-table:: :header-rows: 1 * - Swagger Section - Method ...
954e6c842af8f1a9f3effe81aad7683b1c35e36e
682,167
def get_value_safe(d=None, key=None): """ Return value of a given dictionary for a key. @return: value for a key, None otherwise """ if d is None or key is None: return None if key not in d: return None return d[key]
02201527fc100ef63f4731663f567fd1b5613867
682,170
def number_keys(a_dictionary): """ counts the number of keys in a dictionary and returns it """ return(len(a_dictionary))
4ab56cdfc12a4330652a4111154456775171874b
682,172
def get_electricity_production(power_utilities): """Return the total electricity production of all PowerUtility objects in MW.""" return sum([i.production for i in power_utilities]) / 1000
38bf68ae714846c0b2eeb6ef144b40a167b88798
682,173
def zcount(list) -> float: """ returns the number of elements in a list :param list: list of elements :return: int representing number of elements in given list """ c = 0 for _ in list: c += 1 return c
e0a80eb05121721783bb1b8f469fb6fcd8589318
682,174
import math def must_tack_to_get_to(self, other, boat, wind): """Checks if tacks will be necessary to get to the other point from self""" bearing = wind.angle_relative_to_wind(other.bearing_from(self)) return math.fabs(bearing) < boat.upwind_angle
e1933449dfbb276de937fde629969d8a0aa18552
682,176
def get_city(df, city_name=None, city_index=None): """ returns an info dict for a city specified by `city name` containing {city_name: "São Paulo", city_ascii: "Sao Paulo", lat: -23.5504, lng: -46.6339, country: "Brazil", iso2: "BR", iso3: "BRA", admin_name: "São Paulo", capital: "adm...
2a18eb4f4dba2714db522acee58ddd2474915fd2
682,178
def traceback(score_mat, state_mat, max_seen, max_list, seq_m, seq_n): """ This function accepts two m+1 by n+1 matrices. It locates the coordinates of the maximum alignment score (given by the score matrix) and traces back (using the state matrix) to return the alignment of the two sequences. Inpu...
399e27d46d9ae772e8d35ad6c642a68a44ffdd8f
682,182
def impute_missing(df): """ This function detects all missing values and imputes them with the Median of the column each missing value belongs to. """ df=df[df.columns].fillna(df[df.columns].median()) return(df)
acf9a18848729bad4d16d7bec32169bf5105f2b7
682,186
import struct def get_chunk(filereader): """Utility function for reading 64 bit chunks.""" data = filereader.read(8) if not data: print("prematurely hit end of file") exit() bit64chunk = struct.unpack('Q', data)[0] return bit64chunk
6d7ea9c1396242ad40c2bdd14cf1408748300f54
682,189
def _allowed_file(filename): """Return True if file extension is allowed, False otherwise.""" extensions = ['csv', 'xls', 'xlsx'] return '.' in filename and filename.rsplit('.', 1)[1].lower() in extensions
d170a8042a93022b1beaebe1955fd9a102d0ff96
682,190
import random def create_random_graph(nodes): """ Creates a random (directed) graph with the given number of nodes """ graph = [] for i in range(0, nodes): graph.append([]) for j in range(0, nodes): rand = random.randint(1, 100) if rand % 2 == 0 and i != j: ...
57401f41d0dbbd871dcefd369c22b82fc453b3f3
682,196
def critical_damping_parameters(theta, order=2): """ Computes values for g and h (and k for g-h-k filter) for a critically damped filter. The idea here is to create a filter that reduces the influence of old data as new data comes in. This allows the filter to track a moving target better. This goe...
eb42e82d619650b107c16da049c3d59043b1be70
682,197
def clo_dynamic(clo, met, standard="ASHRAE"): """ Estimates the dynamic clothing insulation of a moving occupant. The activity as well as the air speed modify the insulation characteristics of the clothing and the adjacent air layer. Consequently the ISO 7730 states that the clothing insulation shall be...
7ac9c7274a3333c389e226c611e127d5ed101468
682,200
def easeInOutCubic(currentTime, start, end, totalTime): """ Args: currentTime (float): is the current time (or position) of the tween. start (float): is the beginning value of the property. end (float): is the change between the beginning and destination value of the propert...
e9cdb21918cea625fff8bd38deb2eb09dfae4b86
682,201
def is_valid_part2(entry): """ Validate the password against the rule (part 2) Position 1 must contain the token and position 2 must not. """ # note that positions are 1 indexed pos1 = entry.param1 - 1 pos2 = entry.param2 - 1 result = (entry.password[pos1] == entry.token) \ and...
3af62a4c76045aaf30ed02ad7f2dcd5abf2fb242
682,202
def prepareFixed(query, ftypes, fixed): """Called by :meth:`.FileTreeManager.update`. Prepares a dictionary which contains all possible values for each fixed variable, and for each file type. :arg query: :class:`.FileTreeQuery` object :arg ftypes: List of file types to be displayed :arg fixe...
7a67b5828d19229954e6e7ddbfa93e743f0c678c
682,209
def manhattan(p1, p2): """Return manhattan distance between 2 points.""" return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
2836b18004733be2fe9a04adfec2e67651ea1f03
682,210
import re def _load_line(fh) -> str: """Loads a line from the file, skipping blank lines. Validates format, and removes whitespace. """ while True: line = fh.readline() line = line.rstrip() line = re.sub(" ", "", line) if line: # Not blank. ...
4792f9acfd6a0bfc7055bfbe78d78c0a211f222f
682,213
def find_all_lowest(l, f): """Find all elements x in l where f(x) is minimal""" if len(l) == 1: return l minvalue = min([f(x) for x in l]) return [x for x in l if f(x) == minvalue]
3e7154dc626086643d37115579fba51c6ae1c09a
682,214
def get_num_attachments(connection): """Get the number of attachments that need to be migrated""" with connection.cursor() as cursor: cursor.execute("SELECT COUNT(*) FROM form_processor_xformattachmentsql") return cursor.fetchone()[0]
3030a564c922bc77c10de9e84a7646731a1e0c6a
682,218
def is_sorted(ls): """Returns true if the list is sorted""" return ls == sorted(ls)
28e3b0f57ef7ae0a2032c71951572eba50e87230
682,221
import math def sin100( x ): """ A sin function that returns values between 0 and 100 and repeats after x == 100. """ return 50 + 50 * math.sin( x * math.pi / 50 )
ceb2d7627ff7d478f5aef40a9fc8027fb48174bd
682,225
def curve_between( coordinates, start_at, end_at, start_of_contour, end_of_contour): """Returns indices of a part of a contour between start and end of a curve. The contour is the cycle between start_of_contour and end_of_contour, and start_at and end_at are on-curve points, and the return value ...
56996fd7ed196ab6b0b7cae966fa34d5f5849b9a
682,227
from typing import Dict def _to_kwargs(params: Dict) -> str: """Stringify the params as an arg list :param params: The params :return: A string representation of the parameters in the for `param=arg`. """ return ", ".join(f"{k}={v}" for k, v in params.items() if k != 'name')
1e9fec386238395ff088d22186727421250f2267
682,230
def X_y_split(data: list): """ Split data in X and y for ML models. """ X = [row[0] for row in data] y = [row[1] for row in data] return X, y
c81aff64f2c44b3663715a23375ab7fdc0818636
682,236
def attr_str(ctrl_name, attr_name): """ join the two strings together to form the attribute name. :param ctrl_name: :param attr_name: :return: """ return '{}.{}'.format(ctrl_name, attr_name)
d4d31919d8f972045e739f3d02ed793e4d368c58
682,242
def percent_change(starting_point, current_point): """ Computes the percentage difference between two points :return: The percentage change between starting_point and current_point """ default_change = 0.00001 try: change = ((float(current_point) - starting_point) / abs(starting_point)) ...
3344139c838f92cf26d798899829f700231efa46
682,243
def internal_header_to_external(internal_header: str) -> str: """ Within our app we access headers in this form HTTP_LMS_TYPE but they are supplied like LMS-TYPE. This converts the internal form to the external form for error reporting purposes. """ assert internal_header.startswith('HTTP_'...
32b0efade8b74d1ef543b2c5f686bf1d3c4080a6
682,244
def get_deps(project_config): """ Get the recipe engine deps of a project from its recipes.cfg file. """ # "[0]" Since parsing makes every field a list return [dep['project_id'][0] for dep in project_config.get('deps', [])]
eb3fa956348cea97f5c819f2c1e860b12a367947
682,247
from typing import Any import base64 import gzip import json def compress(input: Any) -> str: """ Convenience function for compressing something before sending it to Cloud. Converts to string, encodes, compresses, encodes again using b64, and decodes. Args: - input (Any): the dictionary t...
915a4e60fcf1eb62b14a23ebeeb52143493a27b3
682,251
def _parameterval(tsr,sol,coef): """ Creating polynomial surface based on given coefficients and calculating the point at a given TSR and solidity Parameters ---------- tsr : float specified tip-speed ratio sol : float specified solidity coef : array the polynomial s...
7059cfaa833d027f3d9776df1c9687f586d1efff
682,254
def get_callback(request, spider): """Get ``request.callback`` of a :class:`scrapy.Request`""" if request.callback is None: return getattr(spider, 'parse') return request.callback
090332b01311cbcdb45f5bdd51c5351146626f45
682,256
import hashlib import binascii def verify_password(stored_password, provided_password): """Verify a stored password against one provided by user""" pwdhash = hashlib.pbkdf2_hmac( "sha256", provided_password.encode("utf-8"), stored_password["salt"].encode(), 10000, ) ret...
38808c8a713ed1c78df82847c885d4f57d07d4e1
682,259
def get_lat_lon_alt(pandora_filepath): """Returns a dictionary of lat, lon, alt extracted from the pandora file :param pandora_filepath: The pandora file :type pandora_filepath: str :returns: A dict of {"lat":lat, "lon":lon, "alt":alt} :rtype: dict{str:int} """ lat = None lon = None ...
f363978431a03ee09855c8895e7c164e6934b8df
682,263
def is_user_message(message): """Check if the message is a message from the user""" return (message.get('message') and message['message'].get('text') and not message['message'].get("is_echo"))
d3af3638857650b2da4196818e4800d04c969ae2
682,264
def _ToString(rules): """Formats a sequence of Rule objects into a string.""" return '[\n%s\n]' % '\n'.join('%s' % rule for rule in rules)
927c6eb8d8dce8161ec9fb5db52da64837567b58
682,265
import requests def gateway(self, IPFS_path: str, **kwargs): """ Retrieve an object from the IFPS gateway (useful if you do not want to rely on a public gateway, such as ipfs.blockfrost.dev). https://docs.blockfrost.io/#tag/IPFS-Gateway :param IPFS_path: Path to the IPFS object. :type IPFS_path:...
79597b1ea6699febeb93ceb216466aa3a3d358b2
682,266
import json def ipynb2markdown(ipynb): """ Extract Markdown cells from iPython Notebook Args: ipynb (str): iPython notebook JSON file Returns: str: Markdown """ j = json.loads(ipynb) markdown = "" for cell in j["cells"]: if cell["cell_type"] == "ma...
3e9a8a74440bc261653a1093dedd5f28e82831be
682,270
def get_target_shape(shape, size_factor): """ Given an shape tuple and size_factor, return a new shape tuple such that each of its dimensions is a multiple of size_factor :param shape: tuple of integers :param size_factor: integer :return: tuple of integers """ target_shape = [] fo...
83c60a72e19cca5606995c9cdf324017156012ac
682,273
def format_row(row: list) -> list: """Format a row of scraped data into correct type All elements are scraped as strings and should be converted to the proper format to be used. This converts the following types: - Percentages become floats (Ex: '21.5%' --> 0.215) - Numbers become ints (Ex: '2020'...
eb4de7f8760ac706409e5f32de9427cb78fcc3db
682,275
def count_in_progress(state, event): """ Count in-progress actions. Returns current state as each new produced event, so we can see state change over time """ action = event['action'] phase = event['phase'] if phase == 'start': state[action] = state.get(action, 0) + 1 elif ...
2b8badb80e7f6897945770f8271b550b4c1b6218
682,277