content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_all_recommendations(csv_file): """ This function reads all recommendations for users using the result of the recommendation system stored in a csv file :param csv_file: the csv file where the recommendations are stored :return: the dataframe of recommendations predicted for users """ df_...
fe0578bb77c60deaf833a22fd9a1b9e946183f91
698,327
from bs4 import BeautifulSoup def filter_bank_account_info(html: str) -> dict: """Filter the bank account info in the data of the HTML structure. Keyword arguments: `html: str` - Content in html structure. """ soup = BeautifulSoup(html, 'html.parser') # Get all the labels to use as a key i...
e4558d52895dbb01f57a26d3722597577367ba26
698,328
def is_prime(nb: int) -> bool: """Check if a number is a prime number or not :param nb: the number to check :return: True if prime, False otherwise """ # even numbers are not prime if nb % 2 == 0 and nb > 2: return False # checking all numbers up to the square root of the number ...
4368fd20eadd4d773d5f5af06f8717ef633d48b8
698,329
async def present(hub, ctx, name: str, image: str, **kwargs): """ Ensure a container is present .. code-block:: yaml new container: lxd.containers.present: - name: webserver01 - image: ubuntu1804 """ ret = { "result": False, "name": name, ...
911b27a3318bc273f790041f2c003f6e8f56645d
698,330
from typing import Sequence from typing import Any from functools import reduce from operator import getitem def get_in_dict(d: dict, keys: Sequence[str]) -> Any: """ Retrieve nested key from dictionary >>> d = {'a': {'b': {'c': 3}}} >>> get_in_dict(d, ('a', 'b', 'c')) 3 """ return reduce...
d851c1d9360e90cbecbff401b98b76afb9b7e52f
698,331
import logging def level_from_verbosity(verbosity=3, maxlevel=logging.CRITICAL): """Return the logging level corresponding to the given verbosity.""" return max(1, # 0 disables it, so we use the next lowest. min(maxlevel, maxlevel - verbosity * 10))
45064e04e27fa170257f37faa56de02ea544f811
698,332
def add_tag(row, tag_key, capitalize=False): """ Looks up the correct tag based on the row, and appends it to the list of tags :param row: :param tag_key: the tag key (string of tag) to add :param capitalize: True to initial cap the tag key :return: the updated row """ if not tag_key: ...
f8a84d4eeb82f516a301553528c3f66741879a7a
698,333
def nested_dict_traverse(path, d): """Uses path to traverse a nested dictionary and returns the value at the end of the path. Assumes path is valid, will return KeyError if it is not. Warning: if key is in multiple nest levels, this will only return one of those values.""" val = d for p in path: val...
1f7e4744585ae134ab1f2eface9284756526ed65
698,335
def is_file_download_finish(file_name): """ 判断文件是否下载完 判断文件后缀为xltd即未下载完 :param file_name: :return: """ return not file_name.endswith('.xltd')
b782d358359c03f50efb6d791bd4403a4190aac0
698,336
import itertools def list_flatten(_l): """Flatten a complex nested list of nested lists into a flat list """ return itertools.chain(*[list_flatten(j) if isinstance(j, list) else [j] for j in _l])
05d1e4018accfe850c07504f123d85949a2ced60
698,340
def handle_2_columns(datalist, return_list = False): """This function has the intent of changing: ('A8', '2') => ('A8', '', '2') ('A8', '', '2') => ('A8', '', '2') [('E2', '5')] => [('E2', '', '5')] [('G1', '', '5')] => [('G1', '', '5')] with the purpose of handling 2 column csv part file inputs...
57a9c1dbad9484a3513cebab68069983d3ae9f35
698,343
def format_button(recipient_id, button_text, buttons): """ Ref: https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template """ return { "recipient": {"id": recipient_id}, "message": { "attachment": { "type": "template", ...
a05f6d08b87d0897a65b291c539b3cbd883c0799
698,344
def get_position_key(atom): """ Get atom position as tuple of integers to be used as lookup key. Rounds the coordinates to 4 decimal places before multiplying by 50 to get unique integer-space coordinates, and avoid floating point errors. :param atom: Atom to get key for :type atom: :class:`nan...
b367fd851a0afa903c2d73548849cc8864233f56
698,348
def _str_eval_break(eval, act, ctxt) : """Passes through [break] so that the writer can handle the formatting code.""" return ["[break]"]
2da4059adb4305a3d7e2183c29d89c9539f3c63b
698,349
import math def tuning_score_size(performance_space, peak): """ Computes TS_s, the tuning score based on the size of the performance space compared to the achievable performance. """ return math.sqrt(performance_space.top() / peak)
9e5386932fa164f0d33e65dd41d57d7a22ebe4d6
698,350
def available(func): """A decorator to indicate that a method on the adapter will be exposed to the database wrapper, and will be available at parse and run time. """ func._is_available_ = True return func
a0c886bccb9bbbdacfe23c5659929b8be68c004e
698,352
def spaces_and_caps_to_snake(spaced_str: str) -> str: """Convert caps and spaces to snake.""" underscored = spaced_str.strip().replace(' ', '_') return underscored.lower()
31796e696c2d4efa7821a0cdff09e04b3e7e8232
698,353
from typing import OrderedDict from typing import Type import collections def kwtypes(**kwargs) -> OrderedDict[str, Type]: """ This is a small helper function to convert the keyword arguments to an OrderedDict of types. .. code-block:: python kwtypes(a=int, b=str) """ d = collections.Ord...
8024e6940f84f2eab8d4c44924889624d75ca3bd
698,354
def sort_libraries(libraries): """Sort libraries according to their necessary include order""" for i in range(len(libraries)): for j in range(i, len(libraries)): if libraries[i].depends_on(libraries[j]) or libraries[i].has_addon_for(libraries[j]): tmp = libraries[i] ...
81187aaeb1879d8de4b23d0adae6547739f6a327
698,356
def hamming(g1,g2,cutoff=1): """ Compare two genotypes and determine if they are within cutoff sequence differences of one another. Parameters ---------- g1, g2 : strs two genotypes to compare (must be same length) cutoff : int max allowable sequence differences between them...
24a180c68545fc1cbd0887bf2bee38cbfe6034e0
698,359
def __dtw_backtracking(steps, step_sizes_sigma, subseq, start=None): # pragma: no cover """Backtrack optimal warping path. Uses the saved step sizes from the cost accumulation step to backtrack the index pairs for an optimal warping path. Parameters ---------- steps : np.ndarray [shape=(...
e22a25f7d9e02aeb9413a7f9b39401f7628848e8
698,361
import torch def extract_bboxes(mask): """Compute bounding boxes from masks. mask: [height, width]. Mask pixels are either 1 or 0. Returns: bbox array (y1, x1, y2, x2). """ # Bounding box. horizontal_indicies = torch.where(torch.any(mask, dim=0))[0] vertical_indicies = torch.where(torch.an...
f634b6cfca16cf06da07f194c701920187f4d3e7
698,364
def strip_domain_address(ip_address): """Return the address or address/netmask from a route domain address. When an address is retrieved from the BIG-IP that has a route domain it contains a %<number> in it. We need to strip that out so we are just dealing with an IP address or IP address/mask. E...
adf566580249d00b660e108cabcf99892a44d32b
698,365
from typing import List def athlete_sort(k: int, arr: List[List[int]]) -> List[List[int]]: """ >>> athlete_sort(1, [[10, 2, 5], [7, 1, 0], [9, 9, 9], ... [1, 23, 12], [6, 5, 9]]) [[7, 1, 0], [10, 2, 5], [6, 5, 9], [9, 9, 9], [1, 23, 12]] """ arr.sort(key=lambda x: x[k]) return arr
1655882b7760a705afcbbeba55f5051eaf7d448f
698,368
def list_to_group_count(input_list): """ List to item occurrences count dictionary """ group_count = {} for input_item in input_list: if input_item in group_count: group_count[input_item] = group_count[input_item] + 1 else: group_count[input_item] = 1 ret...
bc6714d2d0b8872e29089eb0d142517c4ef63154
698,373
from typing import Any def affix(orig: Any, ch: str) -> str: """Ensure a given character is prepended to some original value.""" if isinstance(orig, (list, tuple,)): orig = '.'.join(map(str, orig)) return '%s%s' % (ch, str(orig).lstrip(ch))
f5f01b7fa0e82944646dc755cfa0770cec8c72c9
698,376
import yaml def get_project_id(dataset: str) -> str: """Returns the GCP project ID associated with the given dataset.""" with open(f'../stack/Pulumi.{dataset}.yaml', encoding='utf-8') as f: return yaml.safe_load(f)['config']['gcp:project']
d951e8d2a6c96df9aa2dc15499c36f93123f8038
698,377
def score_state(num_answer, ans_one): """Takes in the player's answer, and ans_one (explained in question); checks if the player's choice is correct """ #assert num_answer in [1, 2] if num_answer == 1: if ans_one == True: correct = True else: correct = Fa...
123a0c5f40930fe5a6dc65220c39097a55120c19
698,379
def arg_name2cli_name(arg_name: str) -> str: """ Convert a snake_case argument into a --kabob-case argument. """ return "--" + arg_name.lower().replace("_", "-")
541601ae07b09acdd2d33487517159cd3cbd6125
698,382
def get_users(client): """Return the db containing users metadata. Parameters ---------- client --> pymongo.mongo_client.MongoClient class, MongoDB client Returns ------- metadatafs['fs'] --> pymongo.collection.Collection, reference to collection users """ #get the MongoDb ...
bd2f0b60781e27a23f015f7a7573821a0e2b8ef0
698,387
def read_raw_values(datasize, datastore, test): """read the raw data for a given test""" in_file_name = str(datasize) + '/' + datastore + '_' + test + '.csv' return [int(line.strip()) for line in open(in_file_name)]
1d724b873ee0ccf50d2027df79a2d32472e7942a
698,388
def TrimMu(Stot, oldmu, thresh, norm=True): """ Remove mu measurements below the threshold and adjust mu measurements above the threshold to unity if we seek P(mu > thresh). """ trim = oldmu > thresh if norm: oldmu[:] = 0 oldmu[trim] = 1 else: oldmu = oldmu[trim] St...
2a986599a6116b104b839d8b664f0caff57b1aee
698,389
import collections def mkparts(sequence, indices=None): """ Make some parts from sequence by indices :param sequence: indexable object :param indices: index list :return: [seq_part1, seq_part2, ...] """ indices = indices or [1] result_list = collections.deque() start = 0 seq_le...
710841ca3861a33382b6243579eec07f866eb965
698,391
def log_minor_tick_formatter(y: int, pos: float) -> str: """ Provide reasonable minor tick formatting for a log y axis. Provides ticks on the 2, 3, and 5 for every decade. Args: y: Tick value. pos: Tick position. Returns: Formatted label. """ ret_val = "" # The posi...
a378bd94ceab8698a45403544a728c6c29b402c9
698,392
from typing import Union from pathlib import Path from typing import Any from typing import TextIO def fopen(filepath: Union[str, Path], *args: Any, **kwargs: Any) -> TextIO: """Open file. Args: filepath (Union[str, Path]): filepath Returns: TextIOWrapper: buffer text stream. """ ...
fcf4ccf53c99a390ceaa9b27f86a7e3f4cff3af1
698,394
import signal def signal_number_to_name(signum): """ Given an OS signal number, returns a signal name. If the signal number is unknown, returns ``'UNKNOWN'``. """ # Since these numbers and names are platform specific, we use the # builtin signal module and build a reverse mapping. signal...
cc17db79f6e47b25e9ec5b9c33fb8d7bf7c0ad26
698,397
def labeledFcn(fcn, paramNames): """Wraps a function with its parameter names (in-place). :type fcn: callable Python object :param fcn: function to wrap :type paramNames: list of strings :param paramNames: parameters to attach to the function :rtype: callable Python object :return: the orig...
e8885cf0cf4db4e84069ec4f0164748b0ab52ae3
698,402
import torch def value_td_residuals( rewards: torch.Tensor, values: torch.Tensor, next_values: torch.Tensor, discount: float, ) -> torch.Tensor: """Compute TD residual of state value function. All tensors must be one dimensional. This is valid only for one trajectory. Parameters ----...
723ed0f0ce651cc7da5ad9c7950972d104198888
698,405
async def agather(aiter): """Gather an async iterator into a list""" lst = [] async for elem in aiter: lst.append(elem) return lst
0a7f278d38237a722724572b6705deab429c8e70
698,407
import socket def tcp_socket_open(host, port): """ Returns True if there is an open TCP socket at the given host/port """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(1) try: return sock.connect_ex((host, port)) == 0 except socket.timeout: return...
11519e5d9f2d1de39d8091af011f0458e556021c
698,413
from typing import Optional from typing import List import math import random def sample_from_range(range_max: int, sample_ratio: float, max_samples: int, preselected: Optional[List[int]]) -> List[int]: """ Given a range of numbers in 0..range_...
8be7b5ded3b6f3b54da57027a5d7629a9bf5dc9f
698,415
def occ(s1,s2): """occ (s1, s2) - returns the number of times that s2 occurs in s1""" count = 0 start = 0 while True: search = s1.find(s2,start) if search == -1: break else: count +=1 start = search+1 return count
4f107e5552d794e9e82a8a6b19ec63992034e9f7
698,416
import functools import operator def prod(x): """Equivalent of sum but with multiplication.""" # http://stackoverflow.com/a/595396/1088938 return functools.reduce(operator.mul, x, 1)
31f4defa3401d6dcf05f8ec70c32650f000a1852
698,417
def indent(text, prefix=" "): """ Add a prefix to every line in a string. """ return "\n".join(prefix+line for line in text.splitlines())
e83cc0b14c5b8c304f6e41bf145b06b1de451e8c
698,418
def get_resblock(model, layer_name): """ model is a class resnet e.g. layer_name is "layer1.0.relu2" """ obj_name, b_idx, act_name = layer_name.split(".") b_idx = int(b_idx) block = getattr(model, obj_name)[b_idx] return block
a4ae6c65df336b3dd36b53e9dd348a76b4a47b89
698,419
def FindClientNode(mothership): """Search the mothership for the client node.""" nodes = mothership.Nodes() assert len(nodes) == 2 if nodes[0].IsAppNode(): return nodes[0] else: assert nodes[1].IsAppNode() return nodes[1]
06ac3bcde5571ca425d47885ad5839f2aa32ca0d
698,421
import textwrap def to_flatimage(pathfile, to="(-3,0,0)", width=8, height=8, name="temp"): """ Adds a flat image to the canvas. """ text = rf""" \node[canvas is xy plane at z=0] ({name}) at {to}{{ \includegraphics[width={width}cm,height={height}cm]{{{pathfile}}} }}; """...
61906516d85ba3311506067ad4ec81b32786f1b9
698,422
def _get_primary_status(row): """Get package primary status.""" try: return row.find('div', {'class': 'pack_h3'}).string except AttributeError: return None
1df5b66e9e16e17b8c5f3fc019a587a4320cf6d0
698,424
def calc_n_g(df_schedule, week): """Calculate list of games i.e. Ng Each row has home_id, away_id, home_total_points, away_total_points :param df_schedule: data frame with each matchup :param week: current matchup period id :return: list of games with team ids and scores for home/away """ df_scores = ( ...
1029840d28617d5de60fa499e8e6a9ae40b4ddea
698,425
def is_string(s): """ Portable function to answer whether a variable is a string. Parameters ---------- s : object An object that is potentially a string Returns ------- isstring : bool A boolean decision on whether ``s`` is a string or not """ return isinstance...
ed59a1b3a80f6695c971c49ff3b7936aa048523f
698,426
from typing import Any from typing import Optional def _strat_has_unitary_from_has_unitary(val: Any) -> Optional[bool]: """Attempts to infer a value's unitary-ness via its _has_unitary_ method.""" if hasattr(val, '_has_unitary_'): result = val._has_unitary_() if result is NotImplemented: ...
96965cfec5f5c3c29ea641c95f20a2d4b1f3b859
698,431
def BFS(map_dict, start, end, verbose): """ BFS algorithm to find the shortest path between the start and end points on the map, following the map given by map_dict If an invalid end location is given then it will return the longest possible path and its length. Returns the length of t...
f6770fe8cd5f6c4ebffce2a78992c76cfbb5bd31
698,434
def update_letter_view(puzzle: str, view: str, position: int, guess: str) -> str: """Return the updated view based on whether the guess matches position in puzzle >>> update_letter_view('apple', 'a^^le', 2, 'p') p >>> update_letter_view('banana', 'ba^a^a', 0, 'b') b >>> update_letter_view('bitt...
b7c534acdbc57c04e1f7ee6a83fc94ff2734948a
698,438
def _remove_duplicates(items): """Return `items`, filtering any duplicate items. Disussion: https://stackoverflow.com/a/7961390/4472195 NOTE: this requires Python 3.7+ in order to preserve order Parameters ---------- items : list [description] Returns ------- list ...
b44a16ed815e8cc09598fe2dc8e9871d45d0ae7e
698,441
import re def seqs_dic_count_lc_nts(seqs_dic): """ Count number of lowercase nucleotides in sequences stored in sequence dictionary. >>> seqs_dic = {'seq1': "gtACGTac", 'seq2': 'cgtACacg'} >>> seqs_dic_count_lc_nts(seqs_dic) 10 >>> seqs_dic = {'seq1': "ACGT", 'seq2': 'ACGTAC'} >>> seq...
4542885f22e255fa0f3d14a9d4ef523fdf19f2e8
698,442
def gaussian_kernel(D, sigma): """ Applies Gaussian kernel element-wise. Computes exp(-d / (2 * (sigma ^ 2))) for each element d in D. Parameters ---------- D: torch tensor sigma: scalar Gaussian kernel width. Returns ----...
22885ccb785893522e57861b82612989945cd5cf
698,444
def trigger_event(connection, id, fields=None, error_msg=None): """Trigger an event. Args: connection(object): MicroStrategy connection object returned by `connection.Connection()`. id(str): ID of the event error_msg (string, optional): Custom Error Message for Error Handlin...
418994565cd20cac681575286553d4fa92cf89c9
698,445
def eratosthenes(n): """ This function is titled eratosthenes(n) because it uses the Eratosthenes Sieve to produce a list of prime numbers. It takes in one positive integer arguement, the returns a list of all the primes less than the given number. Args: n (int): User input ...
7c0e0e89c1571dfc7a87883423a217ef36a984af
698,449
def y_aver_bot(yw_mol, ypf_mol): """ Calculates the average mol concentration at bottom of column. Parameters ---------- yw_mol : float The mol concentration of waste, [kmol/kmol] ypf_mol : float The mol concentration of point of feed, [kmol/kmol] Returns ------- ...
21a438551cc7f6c3774999bafa30495dffd99201
698,450
def _convert_to_numpy_obj(numpy_dtype, obj): """Explicitly convert obj based on numpy type except for string type.""" return numpy_dtype(obj) if numpy_dtype is not object else str(obj)
54a7bd1576ec95456d47e2e3957370c0970cb376
698,451
from datetime import datetime def start_of_month(dt, d_years=0, d_months=0): """ Given a date, return a date first day of the month. @param dt: The date to base the return value upon. @param d_years: Specify a delta in years to apply to date. @param d_months: Specify a delta in months to appl...
90976e7df97b8581622df77528540487181cbb8f
698,452
def frames(string): """Takes a comma separate list of frames/frame ranges, and returns a set containing those frames Example: "2,3,4-7,10" => set([2,3,4,5,6,7,10]) """ def decode_frames(string): print('s', string) if '-' in string: a = string.split('-') start, en...
a00a80bba4ab369a9682db6b62dad88911ecc711
698,454
import importlib def class_from_module_path(module_path): """Given the module name and path of a class, tries to retrieve the class. The loaded class can be used to instantiate new objects. """ # load the module, will raise ImportError if module cannot be loaded if "." in module_path: module...
e1b4935efd165c38c6394274c030c52eca5e241d
698,456
def get_ocr_json_url_for_an_image(first_three_digits, second_three_digits, third_three_digits, fourth_three_digits, image_name): """ Get the URL of a JSON file given a barcode ...
44c4d70971f24beee622ff2e11bef0474001aaa3
698,459
def tupleRemoveByIndex(initTuple, indexList): """ Remove the elements of given indices from a tuple. Parameters ---------- initTuple : tuple of any The given tuple from which we will remove elements. indexList : list of ints The indices of elements that we want to remove. R...
17009fc3616afa586467f43b1e7910a17c89ed0d
698,461
def format_one_query(q, read_seq, read_coords, barcode_dict=None): """Formats output. Parameters ---------- q : dict A dictionary of fuzzy searching result. Key is levenshtein distance. Value is list of matched barcodes. read_seq : str A DNA string (full length read). re...
2523ca6e15547a89e466fc4b4c9dad322fe91dbf
698,463
from typing import Tuple def create_categorical_encoder_and_decoder(categorical_variables: list[str]) -> Tuple[dict, dict]: """ Given a list of categorical variables, returns an encoder and decoder. Encoder Key = category. Value = integer encoding. Decoder Key = integer encoding. Value = category. ...
70de5c8a3e1667da2776a3750c1fae1edf9fd8ae
698,466
def _convert_to_int_list(check_codes): """Takes a comma-separated string or list of strings and converts to list of ints. Args: check_codes: comma-separated string or list of strings Returns: list: the check codes as a list of integers Raises: ValueError: if conversion fails ...
965a68466d0aab358043cedb4838ac9d99ce3249
698,469
def get_note_freq(p): """ Return the frequency corresponding to a particular note number Parameters ---------- p: int Note number, in halfsteps. 0 is a concert a """ return 440*2**(p/12)
cec12355f481494fa53fb0ed535ecd82fd038016
698,470
def stringify_parameters(items): """ Convert all items in list to string. """ return [str(item) for item in items]
41a47f611d1514043eeac27de6c8be6c01607649
698,471
def get_current_spec_list(ctx): """ Get the current spec list, either from -p/--project-specs or --specs-to-include-in-project-generation or specs_to_include_in_project_generation in user_settings.options :param ctx: Current context :return: The current spec list """ try: return ctx....
e0e2788b86bf005b6986ab84f507d784ef837cca
698,472
def title_from_name(name): """ Create a title from an attribute name. """ def _(): """ Generator to convert parts of title """ try: int(name) yield 'Item #%s'% name return except ValueError: pass it = iter(n...
44182a7aefc552701517292563717884835230aa
698,474
def fill_empties(abstract): """Fill empty cells in the abstraction The way the row patterns are constructed assumes that empty cells are marked by the letter `C` as well. This function fill those in. The function also removes duplicate occurrances of ``CC`` and replaces these with ``C``. P...
cc27354fd50ac8588c8374e06025a2ceeff691c6
698,475
def pretty_print(state): """ Returns a 3x3 string matrix representing the given state. """ assert len(state) == 9 str_state = [str(i) for i in state] lines = [' '.join(map(str, l)) for l in [state[:3], state[3:6], state[6:]]] return '\n'.join(lines)
67fb7b091e7256d1fa71f2936d3c8989d5a90f0e
698,477
import re def find_images(document): """Returns the list of image filepaths used by the `document`.""" images = [] for line in document: match = re.match(r"\.\. image::\s+(img\/.+)", line) if match: images.append(match[1]) return list(set(images))
2c58b04974f5ec0d1752cb405cfd314de81a841c
698,481
def determine_time_system(header: dict) -> str: """Determine which time system is used in an observation file.""" # Current implementation is quite inconsistent in terms what is put into # header. try: file_type = header['RINEX VERSION / TYPE'][40] except KeyError: file_type = header...
00a7908aa5eaf21eaaa39d97b23304644ebe27b4
698,486
def expand_header(row): """Parse the header information. Args: List[str]: sambamba BED header row Returns: dict: name/index combos for fields """ # figure out where the sambamba output begins sambamba_start = row.index('readCount') sambamba_end = row.index('sampleName') ...
740790e5aa0f5415d3cb0fc22902403b16bef455
698,488
def cap_text(text): """ Capitalize first letter of a string :param text: input string :return: capitalized string """ return text.title()
8403db85d37399db3b4b0693bc9e578ddcf01c3b
698,489
def size_as_recurrence_map(size, sentinel=''): """ :return: dict, size as "recurrence" map. For example: - size = no value, will return: {<sentinel>: None} - size = simple int value of 5, will return: {<sentinel>: 5} - size = timed interval(s), like "2@0 22 * * *:24@0 10 *...
203bc0697cca9b3710f4079de03e759659116883
698,490
import requests import json def get_mactable(auth): """ Function to get list of mac-addresses from Aruba OS switch :param auth: AOSSAuth class object returned by pyarubaoss.auth :return list of mac-addresses :rtype list """ headers = {'cookie': auth.cookie} url_mactable = "http://" + ...
96c064696bf47872e5a1bec5e8770d6470b76bfc
698,493
def es_primo(n: int) -> bool: """Determina si un número es primo. :param n: número a evaluar. :n type: int :return: True si es primo, False en caso contrario. :rtype: bool """ if n == 2 or n == 3: return True if n % 2 == 0 or n < 2: return False for i in range(3, int...
fff4802d6e47c379b6510f13e2ffe9a9d56429d2
698,494
def replace_string(string_value, replace_string, start, end): """ Replaces one string by another :param string_value: str, string to replace :param replace_string: str, string to replace with :param start: int, string index to start replacing from :param end: int, string index to end replacing ...
b79d685a13c427334149789195e5fbbb4a6ad28d
698,495
import hashlib def hash_str(data, hasher=None): """Checksum hash a string.""" hasher = hasher or hashlib.sha1() hasher.update(data) return hasher
5dd433a3cc04037bb439b64b71d3495d03f51ef1
698,496
import functools def synchronize(lock): """ Decorator that invokes the lock acquire call before a function call and releases after """ def sync_func(func): @functools.wraps(func) def wrapper(*args, **kwargs): lock.acquire() res = func(*args, **kwargs) lock.r...
e9ac48d67cf45e1b0cf9b6e776a93f569726b5d4
698,501
def help_invocation_for_command(prefix, command, locale): """ Get the help command invocation for a command. Parameters ---------- prefix: str The command prefix to show. command: senko.Command The command to get the help invocation for. locale: senko.Locale The loca...
abf80554c479e3f766e6a7dc1e7bbcafdbaa6098
698,502
import torch def derivative_sigmoid(x): """Compute the derivative of the sigmoid for a given input. Args: x (torch.Tensor): The input. Returns: (torch.Tensor): The derivative at the input. """ return torch.mul(torch.sigmoid(x), 1. - torch.sigmoid(x))
00da3734436294bc8bb40189bc1298972fbe7f93
698,503
from pathlib import Path async def check_node_modules(): """Check if node_modules exists and has contents. Returns: {bool} -- True if exists and has contents. """ ui_path = Path(__file__).parent / "ui" node_modules = ui_path / "node_modules" exists = node_modules.exists() valid ...
e76703372c46982cf728b26125808e50e2b92907
698,508
def double(number): """ This function returns twice the value of a given number """ return number * 2
65a4bb13ecb45b37f0349f4be2f834f2fd23f813
698,514
def unique_dict_in_list(array): """Returns the unique dictionaries in the input list, preserving the original order. Replaces ``unique_elements_in_list`` because `dict` is not hashable. Parameters ---------- array: `List` [`dict`] List of dictionaries. Returns ------- uniqu...
ef18d64c4a896321d57f984c0ede3e0e897c59f5
698,517
def _clean_str(value, strip_whitespace=True): """ Remove null values and whitespace, return a str This fn is used in two places: in SACTrace.read, to sanitize strings for SACTrace, and in sac_to_obspy_header, to sanitize strings for making a Trace that the user may have manually added. """ ...
41b9f0a1388045b86d019464512a0253eb5d6523
698,523
def has_access(user, users): """A list of users should look as follows: ['!deny', 'user1', 'user2'] This means that user1 and user2 have deny access. If we have something longer such as ['!deny', 'user1', '!allow', 'user2'] then user2 has access but user1 does not have access. If no keywords are fou...
07d3f47cf3725002023d8c9e487e14280dabc2bf
698,528
def isVowel(letter): """ isVowel checks whether a given letter is a vowel. For purposes of this function, treat y as always a vowel, w never as a vowel. letter should be a string containing a single letter return "error" if the value of the parameter is not a single letter string, return True, if the...
5ba6917c80c4679a59580b8f3a05513d0904cd63
698,531
def isCCW(ring): """ Determines if a LinearRing is oriented counter-clockwise or not """ area = 0.0 for i in range(0,len(ring)-1): p1 = ring[i] p2 = ring[i+1] area += (p1[1] * p2[0]) - (p1[0] * p2[1]) if area > 0: return False else: return True
ef7b3ad88a3a5926896ab1c627b65f2e4e4dc47f
698,533
def get_grant_key(grant_statement): """ Create the key from the grant statement. The key will be used as the dictionnary key. :param grant_statement: The grant statement :return: The key """ splitted_statement = grant_statement.split() grant_privilege = splitted_statement[1] if "."...
200b77d0988090628e013463bba5fe395dd76c00
698,534
def invert(d): """Dict of lists -> list of dicts.""" if d: return [dict(zip(d, i)) for i in zip(*d.values())]
1ac60d7c294e159836be3f6c83817ad7de4f7125
698,536
from datetime import datetime def datetime_str_to_datetime(datetime_str): """ This converts the strings generated when matlab datetimes are written to a table to python datetime objects """ if len(datetime_str) == 24: # Check for milliseconds return datetime.strptime(datetime_str, '%d-%b-%Y %H...
84960880bccfb21bdb2dc1a15b0bd09ef358187c
698,540
def mangle(prefix, name): """Make a unique identifier from the prefix and the name. The name is allowed to start with $.""" if name.startswith('$'): return '%sinternal_%s' % (prefix, name[1:]) else: return '%s_%s' % (prefix, name)
6d949e61a87c6667fdfb262376e476aea64bde4b
698,541
def get_string_value(value_format, vo): """Return a string from a value or object dictionary based on the value format.""" if "value" in vo: return vo["value"] elif value_format == "label": # Label or CURIE (when no label) return vo.get("label") or vo["id"] elif value_format == "...
0efaa0850a63076dd0334bc54f2c96e4f352d6ae
698,546
def create_msearch_payload(host, st, mx=1): """ Create an M-SEARCH packet using the given parameters. Returns a bytes object containing a valid M-SEARCH request. :param host: The address (IP + port) that the M-SEARCH will be sent to. This is usually a multicast address. :type host: str :param ...
cb0da629716e992dd35a5b211f26cae3ad949dcb
698,547
def get_values_from_line(line): """Get values of an observation as a list from string, splitted by semicolons. Note 1: Ignore ';' inside \"...\". E.g. consider \"xxx;yyy\" as one value. Note 2: Null string '' for NA values. """ raw_list = line.strip().split(';') i = 0 values = [] whi...
585c6c9484f6ad145f7265613dc189351cc2d556
698,551