content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import List def get_query_ops_and_expr(query: str) -> List[str]: """ Finds all the operators and expressions used inside a query. Returns a list of all operators and expressions Parameters: query (str): A SQL query string. Returns: List[str]: A list a all operators an...
e7b1ec8ff7ec6fd5d48ec2f8b35506e235fd317a
73,102
def configure_null_stonith_resource(stonith_hostnames): """Create null stonith resource for the given hostname. :param stonith_hostnames: The hostnames that the stonith management system refers to the remote node as. :type stonith_hostname: List """ ctxt = { 'st...
30d7605cc49d081d4c9affb13751bff9ce92417a
73,103
def parse_xml(marker, xml): """Parse XML text""" # Genus -> Species -> Strain -> Marker -> Sequence organisms = defaultdict(lambda: defaultdict(lambda: defaultdict(dict))) for match in PATTERNS["xml"].finditer(xml): accession, genus, species, strain, sequence = match.groups() species =...
4ee1f730adf644247ef6696148b13b12d6e4dfdc
73,105
def _format_date(start, end, calendar, busy): """ formats a start date, end date, calendar name, and business state into an object using an object builder. Raises an exception if data prams are invalid. """ return { # 'start' : arrow.get(start).format('YYYY-MM-DD HH:mm:ss'), # ...
6e052f9d1f19ac8f32f5a2ee896fc78bd6c69827
73,106
from typing import Tuple def combine_mask(seq: tf.Tensor) -> Tuple: """对input中的不能见单位进行mask :param seq: 输入序列 :param d_type: 运算精度 :return: mask """ look_ahead_mask = _create_look_ahead_mask(seq) padding_mask = create_padding_mask(seq) return tf.maximum(look_ahead_mask, padding_mask)
464ae3f0f688c7b010f39a51f685dafc0b07d067
73,107
import time def toq(): """ Python implementation of Julia toc() function """ t=time.time() return t-__time_tic_toc
1741be3e7f5137caab885984b14f8fd163e4c4b4
73,108
def load_custom_dict(): """ 加载自定义词典 :return: 一个set形式的词库 """ IOUtil = JClass('com.hankcs.hanlp.corpus.io.IOUtil') path = HanLP.Config.CustomDictionaryPath[0] print('加载自定义词典:%s' % path) dic = IOUtil.loadDictionary([path]) return set(dic.keySet())
4ccc81c917d204bb5078d97a1126c614731e48ad
73,109
def save_vocabulary(file_path, vocab): """ Method to save a vocabulary(or list of tokens) to a binary file in NumPy (.npy format) parameters ----------- :param file_path: str Path to file (if extension is not given, it will be added during saving) :param vocab: list :return: {0, 1} ...
499d2bbbcc1cdc793b9d4c308761d394e9293e1c
73,110
def swap_channel_dimension(tensor): """Swap between channels_first and channels_last. If 'tensor' has 4 elements, it's assumed to be the shape vector. Otherwise, it's assumed that it's the actual tensor. Returns the edited shape vector or tensor. :param tensor: shape vector or tensor to have channel d...
9434c40961a3197b7c93afd99b67b5e1a0658d96
73,111
def nice_Horizons(target, centre, epochs, id_type): """ Mike Alexandersen Convenience function to reformat data returned by Horizons Only require the inputs I actually want to vary. Return in the format I actually want, not an astropy table. """ horizons_table = Horizons(target, centre, epo...
99b880a0df017d008c05b958c72f285a0e222c4a
73,112
def json_required(fn): """ A decorator to check header type is ``application/json`` if you decorate endpoint with this, it will ensure that the request has a valid payload type before access endpoint if header's content type is not ``application/json``, abort the ``invalid_content_type_abort_code`` ...
282b694b58fc88d5100a26a475e093305b1a1ca9
73,113
def delay_stream(delay_item, stream_port): """Delay the stream by one step using the specified initial value.""" i = delay_item s = stream_port expect_stream(s) model = s.get_model() item_data_type = s.get_item_data_type() code = 'return $ delayStream ' code += str(delay_item) code +...
2d3eeed88a1fe81991104fc161125cbe9a94cfea
73,114
import re def process_assignments(config): """Handles interpolation of assignment values. Returns a Config object.""" items = {} to_interpolate = {} re_interpolation = re.compile(r'\{([^}]+)\}') for item in config: if 'name' in item: # This is a section. Nothing to interpolat...
fe6114aab8018ab79c3baf23aa946b122fbfabe3
73,115
from typing import Union from typing import Type import hashlib def make_hash( *args: Union[str, UnstructuredText, CodeableConceptRef, Type[Resource]] ) -> str: """Takes one or more objects and creates a hash for them. The returned hash will always be the same value given the same inputs, even across...
c50b4f5488b01e6bd44f57c2d24e3b25f1540385
73,116
def test_quadratic(): """Check that u(x,t)=x(L-x)(1+t/2) is exactly reproduced.""" def u_exact(x, t): return x*(L-x)*(1 + 0.5*t) def I(x): return u_exact(x, 0) def V(x): return 0.5*u_exact(x, 0) def f(x, t): return 2*(1 + 0.5*t)*c**2 L = 2.5 c = 1.5 C...
7305e6ed048725fe9ac1bfee96d42aea8fb5dcda
73,118
def splunk_setup(splunk): """ Override this fixture in conftest.py, if any setup is required before the test session. splunk fixture can provide the details of the splunk instance in dict format. **Possible setups required**: 1. Enable Saved-searches before running the tests 2. Restart...
88255ac6efd493cc6cb8cf6201ca1f9528534451
73,119
import requests def get_gist(url): """ Get gist contents from gist url. Note the gist url display the raw gist instead of usual gist page. Args: url (str) : url containing the raw gist instead of usual gist page. Returns: (str): output gist str. ""...
853623c31af246dc07e22ac8a7dd0b515a74a080
73,120
import io def plot_to_image_bytes(fig, format='svg', **kwargs): """Return bytes representing the plot image.""" buf = io.BytesIO() FigureCanvasAgg(fig).print_figure(buf, format=format, **kwargs) return buf.getvalue()
356828bc26f0eb8182cdda95b985937893202562
73,121
import random def resolve_subnet(subnet, channel_address, project_id): """ """ # First, determine if the provided subnet is a UUID or an IP address subnet_is_uuid = _is_uuid(subnet) if subnet_is_uuid: # If the subnet is a UUID, we fetch that subnet and make sure it's valid try: ...
fcefb2b3d213b20558831770f28c75e2b8f817c9
73,122
import functools def is_logged(f): """ Check if the user is providing a valid token Parameters ---------- f : function The function that need the user to be logged Returns ------- function The same function but asserting the token is valid Raises ------ U...
926382b156c3b6ed9030250116d1463c6df1019d
73,123
import struct def encode_struct(fmt, value): """Generic method for encoding arbitrary python "struct" values""" return struct.pack(fmt, value)
57285e612f1f2798eceace6de7be0a71fd4520a0
73,124
def generateEventWithProfile(metadata, events, profile_id): """ Generate an XML tree for a live event with a profile. :param events: A list of all inputs to include in the event. :param profileID: Unique profile identifier. :return: Element tree object for an event. """ eventHeader = ET.Elem...
c247a49d575891e54e092fccbb0b072ab00b6bce
73,125
def formatted_results(grub_config_filepath): """ Reformat GRUB menu entries as Ansible facts. """ formatted_results = list() for index, candidate in enumerate(parse_grub_config(grub_config_filepath)): candidate['index'] = index formatted_results.append(candidate) return dict(grub...
7c6a7a61e3382084c726f595d7a6681cdaff10f7
73,126
import re def is_email(addr): """ 判断是否是合法邮箱 :param addr: 邮箱地址 :return: True or False """ re_is_email = re.compile("^[a-z0-9]+([._-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z]+$") if re_is_email.search(addr): return True else: return False
c48d931af7f57420d4b5829da02aa72203275f0f
73,127
def _decoder(vocab_size, num_layers, units, d_model, num_heads, dropout, name="decoder"): """Decoder component.""" inputs = tf.keras.Input(shape=(None,), name="inputs") enc_outputs = tf.keras.Input(shape=(None, d_model), name="encoder_o...
a7e39ba5078f3f8092037daa6b5f2bef29c5ba0d
73,129
def imnormalize_(img, mean, std, to_rgb=True): """Inplace normalize an image with mean and std. Args: img (ndarray): Image to be normalized. mean (ndarray): The mean to be used for normalize. std (ndarray): The std to be used for normalize. to_rgb (bool): Whether to convert to r...
191eb550e414b043b93493b7dc25ac6b5c26f276
73,130
def get_task_result(task_instance_id, username): """ 根据任务ID获取任务执行结果 :param task_instance_id: 任务id :param username: 执行用户 :return: """ url = "/api/c/compapi/job/get_task_result" param = {"task_instance_id": task_instance_id, "username": username} return pass_api(url, param)
4a05dce2b3462b73fcc51e33b016fe319a43c76a
73,131
def pressure_multivariate(obp, vel, phi, vsh, a_0, a_1, a_2, a_3, B, U, vmax, start_idx, end_idx=None): """ Pressure Prediction using multivariate model """ ves = effective_stress_multivariate( vel, phi, vsh, a_0, a_1, a_2, a_3, B, U, vmax, start_idx, end_idx) retur...
e6edee77e6346b771d22d091f4487ccc8b4297a7
73,132
from datetime import datetime def university_phase(date): """ Hardcoded information according to: https://www.jura.uni-hamburg.de/en/service/termine.html the website is not parsed :param timestamp: datetime.timestamp :return: int according to UNIVERSITY_CYCLE """ # we ignore the year, ...
bd5b77f8b0b75b4849bbdf1b1f8317ed6ca81fe0
73,133
def build_rule_directory(rules): """Builds a tree-style rule directory from given rules.""" rule_dir = {} for rule in rules: cur = rule_dir for frag in get_spec_name(rule.package).split("/"): cur = cur.setdefault(frag, {}) cur[rule.name] = rule return rule_dir
7313030123d357d2e3c91fcb048e017e3acc808e
73,134
def gen_html_td(content=None, tagid=None, name=None): """ Generates a table data html td taglet. param content -- The content of the td taglet. param name -- The optional name of the td taglet. param tagid -- The optional tagid of the td taglet. Returns: str -- the html string of the td taglet. """ return gen_...
2db152886f6926aed83096f1ef04030c77520f0c
73,135
def active_face_count(shape): """Number of active faces. Total number of active faces in a structured grid with dimensions, *shape*. Each cell has four faces, and shared faces only count once. An active face is one that has a corresponing active link. >>> from landlab.utils.structured_grid import ...
769d652cfc79f5ea5581d471d8c9417b51fb4f76
73,136
import pathlib import pprint def main(fname, *, donot_filter_html=False, to_files=False): """Produce readable output from a DocTree document collection :param fname: name of DocTree file :param donot_filter_html: leave contents as stored instead of parsed into plain text ...
fc21c659705eb7bb3d9cd331f582e65c73f35ad9
73,137
def has_unsubscribed(email): """Check whether the user has requested to be unsubscribed. Args: email: string. The email address of the user. Returns: bool. True if the user has requested to be unsubscribed. """ model = SubscriptionStateEntity.get_by_key_name(email) return (model is...
3e71ec13e1c2b5957d449d1d225127831e7aef15
73,138
def total_variance_distance(gold_probas, pred_probas, reduction='mean'): """ Calculate the total variance distance between two probability distributions. Args: gold_probas (2d array-like): gold probabilities. Shape of (batch_size, nb_labels) pred_probas (2d array-like): predicti...
035defd353a43770a63f5c5df5f5d066d37210f5
73,140
def get_mock_fyle_empty(): """ get empty mock_fyle :return: mock_fyle """ return get_mock_fyle_from_file('mock_fyle_empty.json')
3586d0d9100e711b34ccd5de0701bdb793aec9ab
73,141
from typing import Optional import pathlib def write_gds( component: Component, gdspath: Optional[PosixPath] = None, gdsdir: PosixPath = tmp, unit: float = 1e-6, precision: float = 1e-9, auto_rename: bool = False, ) -> PosixPath: """Write component to GDS and returs gdspath Args: ...
f545a78f453b62b65662722965b59337ac5b919e
73,142
def _on_missing_reference(app, env, node, contnode): """Handler for missing references. This will attempt to fix references to options and then attempt to apply default intersphinx prefixes (if needed) before resolving a reference using intersphinx. Args: app (sphinx.application.Sphinx): ...
9915caa0ce011b8be4f1bf3b1e4799dc406a9bff
73,143
def generate_id(dashes=True, upper=False): """Return ID with or without dashes as either uppercase or lowercase""" uuid = uuid4() if dashes else uuid4().get_hex() return str(uuid).upper() if upper else str(uuid)
eb6866456dec28ea9662a1bd82d236a28f12434c
73,144
import warnings def parse_epoch(epoch, metadata): """Parse OEM standard epoch using metadata TIME_SYSTEM. Args: epoch (str): OEM epoch string. metadata (MetaDataSection): Metadata corresponding to this epoch. Returns: parsed_epoch (Time): Parsed epoch with assigned time scale. If...
d17f4c6648a20a05f236048b8964a172db3e38b7
73,145
def raw(path_to_file): """ raw: Reads in the IONEX file path_to_file and returns the data. The return value will be a 7-tuple. The first two entires are 1D numpy arrays of the longitude and latitude grid, respectively. The third entry in the tuple is a list of datetimes that define the time gr...
4d90a2b5fa5178aab71baa787b13163282b5d73b
73,146
def build_model(): """Build the mobilenet_v1 model for evaluation. Returns: g: graph with rewrites after insertion of quantization ops and batch norm folding. eval_ops: eval ops for inference. variables_to_restore: List of variables to restore from checkpoint. """ g = tf.Graph() with g.as_def...
817eaca6f144193e17d30e825caaf65bdcb3945f
73,147
def get_filename_fromGEO(): """ Get filename using GEO accession number """ # Create a loop until the user enter a valid GEO accession number # Calls for an infinite loop that keeps executing until an exception occurs while True: print() print("What is the GEO (series) accessio...
7678264abb028056ca98dc92335dd01cadc2007c
73,148
def process_image(image, image_shape): """ Function: Process images: intensity normalization. Inputs: image, image_shape outputs: img_norm in matrix form (normalized images) """ ### params paths = settings.paths matching_info = settings.matching_info analysis_params_general = settings.analysis_params_general...
6b095169843d941e869bbdf4c99061ab9ef1ed46
73,149
from typing import Dict from typing import Any from typing import Tuple def get_gps_point( exif: Dict[str, Any], reference: geo.TopocentricConverter ) -> Tuple[np.ndarray, np.ndarray]: """Return GPS-based representative point. Direction is returned as Z oriented (vertical assumption)""" gps = exif["gps"] ...
f1b0b14ae7d56b7081ac1269506d7a453d89a155
73,150
from typing import List from io import StringIO def download_experiment_comparison(experiment_ids: List[int]): """Render a comparison of several experiments. :param experiment_ids: The identifiers of experiments to compare """ logger.info('working on experiments: %s', experiment_ids) clusters = ...
3ac61ed1f7af3457901422498451be22610debba
73,151
def tuple_code_repr(value: tuple) -> CodeRepresentation: """ Gets the code representation for a tuple. :param value: The tuple. :return: It's code representation. """ return container_code_repr("(", ")", ((el,) for el in val...
4df2bf7451f0b93cd9c4c928d62f12265c7c8ddc
73,152
from typing import Tuple def xavier_normal_gain(shape: Tuple[int, ...]) -> float: """Returns Xavier Glorot gain from `Understanding the difficulty of training deep feedforward neural networks <http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf>`_. Args: shape: shape of the output tensor....
1c9a73cc595c7800b4ec15a207b519fa2a014702
73,153
import requests def http_get(url: str, head_only: bool = False, max_retries: int = 3, retry_interval: float = 5.0, ): """Wrapper of requests.get, with some extra param.""" if head_only: req = _requests_session.head else: req = _requests_session.get error_args = () while max_retries...
abd8b7c0c7be95308538f86ff0750d66a232ede8
73,154
def training_best_model(X_train, y_train, model_name, ncols, build_fn, preprocess_pipeline, params, batch_size=32, epochs=100): """ training_best_model() trains the best model from each subsets and returns an instance of the model. Taking as params things ...
e028ef0d2aa8ac3b104917099ec621d091f50b24
73,155
def exclusions(coord_file, monomers, valence, toplines, atoms, n_atoms, vsites): """ :param coord_file: the original .gro file stored in a list :param monomers: number of monomers :param valence: charge on ions :param atoms: the names of the atoms which should be excluded :param n_atoms: the num...
08210824962062aeacd2a2241b45bb455e406f47
73,156
import torch from typing import Tuple def get_timestamp_embeddings( audio: Tensor, model: torch.nn.Module, hop_size: float = TIMESTAMP_HOP_SIZE, ) -> Tuple[Tensor, Tensor]: """ This function returns embeddings at regular intervals centered at timestamps. Both the embeddings and corresponding t...
fb3c828748e5e9da126c5b1855e99840ad800775
73,157
def iso_stencil(field, model, **kwargs): """ Stencil for the scalar isotropic visco- acoustic variable density self adjoint wave equation: b/v^2 [ P.dt2 + w/Q P.dt ] = (b P.dx).dx + (b P.dy).dy + (b P.dz).dz + s Note derivative shifts are omitted for simplicity above. See implementation no...
205a22ffffb547447b435b41c3a8360551e9d5cc
73,158
def use_content_type(app): """ Applies the middleware :param app: :return: """ @app.middleware("http") async def json_encoding_header(request: Request, call_next): """ Encodes json to UTF-8 :param request: :param call_next: :return: """ ...
e494a299a3a83a577c8983dc9a28d4436a2a5a02
73,159
def create_family_proband(testapp, xml_data, refs, ref_field, family_item, post_extra=None, xml_extra=None): """ Proband-specific object creation protocol. We can expand later on General process (in development): - POST individuals with required fields and attribution (`post_e...
335887a4a58607f88ad3bb530cfeabe31de7a00c
73,160
def FromRFC822(st): """ Create a DT object from an RFC 822/1123 date string """ t = rfc822.parsedate_tz(st) #t is in local time with a tz offset if not t or len(t) != 10: raise SyntaxError("Invalid RFC 822 date: '%s'" % st) year, month, day, hour, min, sec, temp, temp, temp, offset =...
bd3cd2d00ba9f56615c6df724a7bee37abec2af6
73,161
def merge_unique(a: list, b: list) -> set: """ merges all of the unique values of each list into a new set >>> merge_unique([1, 2, 3], [3, 4, 5]) {1, 2, 3, 4, 5} """ ret = set() a.extend(b) for element in a: ret.add(element) return ret
6a969c6beaee46e5618d25c5714cec223ebf1686
73,162
from datetime import datetime def get_specific_img(patient_id, date_time): """ Gets a specific ECG trace for a patient Returns: (JSON): JSON with encoded image data of ECG trace (int): status code """ p_id = int(patient_id) date = datetime.strptime(date_time, "%b %d %Y %H:%M:%S")...
3fefd6f2085d07f770400e26ae688ef238da32d8
73,163
def record_changed(redis_client, session_id, instances, relation_oids=None, expires=None, key=None, get_oid=None): """Add the instances to the changed set for this session.""" # Compose. if expires is None: expires = CHANGED_SET_EXPIRES if key is None: key = CHANGED_KEY if g...
166ad9742870265944a9ac9373ce0ac0e05f5f06
73,164
def format_output(search_obj, output_format, show_headers): """Format search result output. Args: search_obj: API Search object. output_format: The format to use. show_headers: Boolean indicating if header row should be displayed. Returns: Search results in the requested ou...
22525aeeb0b7f0de9f0d87fdc9cf133a7ede3843
73,165
def get_wanted_parameter(season_data, names, index_para): """ Take in a list of players' names, a wanted parameter and return :param season_data: a dictionary of players' statistics :param names: a list of players' names :param index_para: index of the wanted parameter depending on the file :return:...
0d278abd79f28c922dfcacf4984af7efe14a9070
73,166
def read_dataframe( path: str, spark: SparkSession, logger: Logger = None, **kwargs ) -> DataFrame: """ Function to read CSV as a Spark DataFrame Args: path (str): Path of input Data (CSV) spark (SparkSession): Spark Session Object logger (Log4j, optional): Logger O...
3af6f2ac34da608451e1dda824fc9a528ac5873f
73,167
def funding(district_id): """Return funding data points for each district""" conn = psycopg2.connect(host="localhost",database="teacher_strike_db", user="postgres", password="postgres") cur = conn.cursor() funding_data = {} cur.execute("SELECT * FROM district_funding") local = [] state...
06a6a59109ceacdff172aa99c550b8204f6a23e6
73,169
def column_stack(arrays): """Stack 1-D arrays as columns into a 2-D array. Since casadi by default uses 2-d array to represetn a vector (column vector), we need to be very explicit when we're working with 2d or 1d arrays """ if not (_check_1d_arrays(arrays)): raise ValueError("To use colum...
669b9ca97ae5fc1677bb5a1a70dcbd97a014ad35
73,170
import requests def get_FREQ( APIKey='AP8DA23', FromDateTime='2021-01-01 00:01:00', ToDateTime='2021-02-01 23:59:00', ServiceType='csv', endpoint='https://api.bmreports.com/BMRS/FREQ/v1' ): """Rolling System Frequency """ params = { 'APIKey': APIKey, 'FromDateTime...
9e28b80f2b10c998047f10181cd6612a63392111
73,171
def lastend(server_name, p5_connection=None): """ Syntax: Server <name> lastend Description: Returns the absolute time in seconds (Posix time) of the successful end of the last backup operation on the server <name>. This time may be older then the time returned by the lastbegin method, indicating an...
19572ee37174e43c6b87d698bdf41fdf6c342493
73,172
def timestamp(source: ObservableBase) -> ObservableBase: """Records the timestamp for each value in an observable sequence. 1 - res = source.timestamp() # produces objects with attributes "value" and "timestamp", where value is the original value. Returns an observable sequence with timestamp info...
e672ba9c64397b93967e6eba6106f0ed42acc15f
73,173
def cxDummy(ind1, ind2): """Dummy crossover that does nothing. This is used when we have a single gene in the chromosomes, such that crossover would not change the population. """ return ind1, ind2
d5a3667cb714663348d5f8f421c167e134eed612
73,174
def comtypes_get_refcount(ptr): """Helper function for testing: return the COM reference count of a comtypes COM object""" ptr.AddRef() return ptr.Release()
d2e7addf5a4bfa497d46597f194bfaef48b129d7
73,176
from pyspark.sql import DataFrame # noqa def get_spark_dataframe_info(df: Any) -> str: # type: ignore """ Provides information about the spark dataframe Args: obj (Any): The dataframe to provide information for Returns: str: info string about the dataframe """ try: exce...
3289e22ab93e5b298cb8c0774fa232bf542f03ba
73,177
def check_action_permitted(account, subdomain, action): """Returns True if the account is allowed to perform the given action in the given subdomain.""" # Items in the Account.actions list have the form subdomain + ':' + verb, # where '*' can be used a wildcard for the subdomain or the verb. actions...
8d60c59a347277fe3d58e5a4035baf0540cc1d91
73,178
def t_gate_unitary_deterministic(): """T-gate circuits reference unitaries.""" targets = [] # T targets.append(np.diag([1, (1 + 1j) / np.sqrt(2)])) # T.T = S targets.append(np.diag([1, 1j])) # T.X targets.append(np.array([[0, 1], [(1 + 1j) / np.sqrt(2), 0]])) # H.T.T.T.TH = H.Z.H = X...
39be7f26768d83d7a9b164f12337efeeaca6fb67
73,179
def _darknet_l2normalize(inputs, params, attrs, prefix): """Process the l2 normalization operation.""" new_attrs = {} new_attrs['eps'] = attrs.get('eps', 0.0) new_attrs['axis'] = [attrs.get('axis', 1)] return get_relay_op('l2_normalize')(*inputs, **new_attrs)
8664b04a36b5b94baf167d18b3e62e60166321d1
73,180
def convert_cookie_str(_str): """ convert cookie str to dict """ _list = [i.strip() for i in _str.split(';')] cookie_dict = dict() for i in _list: k, v = i.split('=', 1) cookie_dict[k] = v return cookie_dict
de6ada63afb3490e793a62e7de98460c48f3b1c8
73,181
def html2text(element): """extract inner text from html Analog of jQuery's $(element).text() """ if isinstance(element, str): try: element = ElementTree.fromstring(element) except Exception: # failed to parse, just return it unmodified return elem...
3fd979fb73400227ae2508236f93a448b42abaa3
73,183
def _create_section_page(title: str, parent: Page) -> SectionPage: """Abstracting this allows us to test more scenarios than just passing the fixture around. Args: title (str): The page title parent (Page): A page to attach our section page to Returns: SectionPage: Description ...
714debaf1edc602e74dbf3df29b614b398f759eb
73,184
from pathlib import Path def default_formatted_csv_filename(job_id): """ Returns the filename for the formatted CSV associated with job_id Parameters ---------- job_id: str The job_id to generate the filename for Returns ------- filename: pathlib.Path The filename associa...
e6a1a3ba4157412fb808ebef831deb8440ea62e9
73,185
def view_favourites(): """ Function to display user's favourite companies - require user to be logged in - retrieve user in session - find organisations in list of user's favourites """ return render_template('favourites/list_favourites.html', favourites=current_us...
a23103e71c67b86fe935fb4804e97fe74c36748b
73,187
def get_all_dirs_files(folder: str) -> list: """Prende tutti i file nella cartella passatagli Parameters: folder (str): cartella nella quale sono contenuti i file Return: list[str]: tutti i file presenti in quella cartella """ files = listdir(f'{dataset_dir}/{folde...
c23388f6b852f1c1a42d4199659450e5bf78b42c
73,190
def calc_dist_array(norm_df, f_w=[1, 1, 1]): """ 特徴量からデータ間距離を求める。 Parameters ---------- norm_df: pandas.dataframe 標準化された特徴量のデータフレーム f_w: list 各特徴量の重み Returns ------- dist_array: numpy.ndarray 利用者間のデータ間距離2次元配列(上三角行列) """ d_lat = norm_df['desitination_...
45fdf69d871a29e867a163590eb0138d97491d92
73,191
def get_birthday_persons() -> list: """Gets a list of birthday people sorted by day and month""" date_now = dt.datetime(dt.datetime.today().year, dt.datetime.today().month, dt.datetime.today().day) persons = [] bday_sort = User.query.group_by( extract('month', User.b...
5c193251c8cf2527087660da1cabdfadabd57ea4
73,192
from typing import Union from typing import Dict def get_calcjob_builder(label:str, description:str, calc_type:str, computer:Str, structure:StructureData, calculator_settings:Union[dict,Dict], ...
a87ecc885d1c3fc64d73d2339b4dec98674bbd5d
73,193
import re def _gtest_list_tests(gtest_list_tests_output): """Returns a list of strings formatted as TestSuite.TestFixture from the output of running --gtest_list_tests on a GTEST application.""" # Remove log lines. gtest_list_tests_output = ( re.sub("^\[.*\n", "", gtest_list_tests_output, flags=re.MULT...
aae3b83c8380fc72e2c8beda41cb60212f23fe1c
73,195
def DL_ignore(answers): """Return False if any dictionary-learning method was selected. Arguments --------- answers: dict Previous questions answers. Returns ------- bool True if DL verbosity question should be ignored. """ expected = ['ITKrMM', 'wKSVD', 'BPFA'] ...
fda853fc0f959dd5302a90bc9d56f012a1d7da8f
73,196
def get_ova(sandbox, image): """ get_ova :param sandbox: str :param image: str :returns: str """ return f"{sandbox}/output-vmware-iso/{image}.ova"
84ed2db8403c15d9d86330372e867a7e47a752bd
73,198
def check_constraint(write_func, params): """Before writing a file, check that geometry constraints are OK.""" try: write_func(params) return True except geometry.GeometryConstraintError: return False
0af75141bf819653b7cae28d8a306713d2b19fe0
73,199
from typing import List def flatten(lst: List[List[object]]) -> List[object]: """ Flattens a list of lists by one level. :param list lst: A list of lists. """ return [item for sublist in lst for item in sublist]
3d6cd5be545b26666ce4a4695c7325cf1407d36e
73,200
from typing import Optional from typing import Sequence def get_catalog_nodes(query_options: Optional[Sequence[pulumi.InputType['GetCatalogNodesQueryOptionArgs']]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetCatalogNodesResult: """ Use this data source to access i...
5380c534a3cfc34cb778b7967d8d50bfa444d280
73,201
def wait(status, timeout=None, *, poll_rate="DEPRECATED"): """(Blocking) wait for the status object to complete Parameters ---------- status: StatusBase A Status object timeout: Union[Number, None], optional Amount of time in seconds to wait. None disables, such that wait() will ...
3311714c7aee5cbbecf658bfa563826c363752e2
73,202
def get_all_objects_in_scene(): """ Gets all the objects in the scene :return: *list* with object names """ return [obj.name for obj in bpy.data.objects]
777e129356a9434110dd20d2dfe9af51e79a1f87
73,203
from pathlib import Path def get_tle_dir() -> Path: """Return the directory containing TLEs.""" tle_dir = get_data_dir() / "tle" if not tle_dir.exists(): Path.mkdir(tle_dir) return tle_dir
f38a0bbf905edebcb0f7fb1901fccd53637438ab
73,204
import re def find_md_links(md): """Returns dict of links in markdown: 'regular': [foo](some.url) 'footnotes': [foo][3] [3]: some.url """ # https://stackoverflow.com/a/30738268/2755116 INLINE_LINK_RE = re.compile(r'\[([^\]]+)\]\(([^)]+)\)') FOOTNOTE_LINK_TEXT_RE = re.compile(r'\[...
d630d22d571e774312516fc4005444087d23392f
73,205
import struct def _cgo_codegen(name, srcs, c_hdrs=[], deps=[], copts=[], linkopts=[], go_tool=None, toolchain=None): """Generates glue codes for interop between C and Go Args: name: A unique name of the rule srcs: list of Go source files. Each of them must contain `import "C"`. ...
d9f3dc4d3464b0ad1d370ef98ebba38346973369
73,206
import base64 def create_message(sender, to, subject, message_text): """Create a message for an email. Args: sender: Email address of the sender. to: Email address of the receiver. subject: The subject of the email message. message_text: The text of the email message. Returns: An obje...
49f2cda4511110eefe91bf424f7bba85c3a18a99
73,208
def ensure_request(view_func): """ Decorator that ensure request from typeform. """ @wraps(view_func) def _wrapped_view_func(request, *args, **kwargs): logger.info('Typeform request received') if not _ensure_request(request): return HttpResponse('') else: ...
6fa2d4e63e3adc837831e1d427eeef2f28641316
73,209
def timeave(ys): """ Function returns data averaged :param ys: array with two dimensions :return: """ y = [] for i in range(ys.shape[1]): y.append(sum(ys[:,i])/ys.shape[0]) return np.array(y)
7e937187eb94cd189a14a7d34ee6122efbf0948e
73,210
def dup_factor_list(f, K0): """Factor polynomials into irreducibles in `K[x]`. """ j, f = dup_terms_gcd(f, K0) if not K0.has_CharacteristicZero: coeff, factors = dup_gf_factor(f, K0) elif K0.is_Algebraic: coeff, factors = dup_ext_factor(f, K0) else: if not K0.is_Exact: ...
93a306dab1a1ab0eaab2b7a67cc6867452771ba2
73,212
def get_roots(word): """ Returns list of root-words which are titles of dictionary articles containing the given word. If the dictionary doesn't contain the given word the list containing word itself is returned. :param word: russian word :return: list of root-words """ """ :param word:...
951be8ae666c1669e9241e53c2a6e81faf953fbe
73,213
def sex(return_expectations=None): """ Returns M, F or empty string if unknown or other """ return "sex", locals()
4f461d76d96f6c0559d20693b28280436af1a594
73,214
def epoch_time(start_time, end_time): """ Computes the time for each epoch in minutes and seconds. :param start_time: start of the epoch :param end_time: end of the epoch :return: time in minutes and seconds """ elapsed_time = end_time - start_time elapsed_mins = int(elapsed_time / 60) ...
8265cb78c26a96a83a1035c09a7dccb0edf8c4d0
73,215