content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import ctypes def create_channel(pvname, connect=False, auto_cb=True, callback=None): """ create a Channel for a given pvname creates a channel, returning the Channel ID ``chid`` used by other functions to identify this channel. Parameters ---------- pvname : string the name of the ...
efc02a366873b5a912e951c73aa864b59f999b77
3,629,532
def prep_for_graph(data_frame, series=None, delta_series=None, smoothing=None, outlier_stddev=None): """Prepare a dataframe for graphing by calculating deltas for series that need them, resampling, and removing outliers. """ series = series or [] delta_series = delta_series or [] ...
409fa6b806ce2c6546390e41ae88226b5000a8d8
3,629,535
def vigenere_decryption(text: str, key: str) -> str: """Декодирование шифра Виженера :param text: расшифровываемый текст :type text: str :param key: ключ :type key: str :return: исходный текст :rtype: str """ result = ''.join( [chr((ord(m) - ord(key[i % len(key)]) + 26) % 26...
6ad2277d1060eab48481749023e40e11eb3590ea
3,629,536
def remove_diacritics(string): """Removes diacritics from the given string Parameters ---------- string : str The string from which diacritics should be removed Returns ------- string : str The string with its diacritics removed """ uni = unidecode(string) # r =...
bc6330b32f583b888bfebdeb29993d0a79cae44a
3,629,537
def eval_chip_generalized(theta1, theta2, deltaphi, q, chi1, chi2): """ Generalized definition of the effective precessing spin chip, see arxiv:2011.11948. This definition retains all variations on the precession timescale. Call ---- chip = eval_chip_generalized(theta1,theta2,deltaphi,q,chi1,chi2) ...
bb359afb843d921d216dac69524e43e2ac5807a2
3,629,538
import re def strip_emails(s): """ Remove digits from `s` using RE_EMAILS`. """ RE_EMAILS = re.compile(r"\S*@\S*\s?", re.UNICODE) return RE_EMAILS.sub("", s)
7c9a705023f1d5d821d002815f629bd7ebff8602
3,629,539
def get_hf(sigma_val=0.8228, boxRedshift=0., delta_wrt='mean'): """ Halo mass function model for the MultiDark simulation. """ #hf0 = MassFunction(cosmo_model=cosmo, sigma_8=sigma_val, z=boxRedshift) omega = lambda zz: cosmoMD.Om0*(1+zz)**3. / cosmoMD.efunc(zz)**2 DeltaVir_bn98 = lambda zz : (18.*n.pi**2. + 82.*(...
d90af3c653b62e44c21203ad9c1c48a98abed195
3,629,540
def reverse_one_hot(image): """ Transform a 2D array in one-hot format (depth is num_classes), to a 2D array with only 1 channel, where each pixel value is the classified class key. # Arguments image: The one-hot format image # Returns A 2D array with the same width and...
f4d1f06ad44926ae09a9ecce03dd1e55b4e798f0
3,629,541
def individual_utilities( persons, cdap_indiv_spec, locals_d, trace_hh_id=None, trace_label=None): """ Calculate CDAP utilities for all individuals. Parameters ---------- persons : pandas.DataFrame DataFrame of individual persons data. cdap_indiv_spec : p...
593e4b102755218476651101fa82c47f648e2cf1
3,629,542
def _create_pd_obj(frame, res, RATIO, mode): """Creates a prediction objects file.""" objs = [] # This is only needed for 2D detection or tracking tasks. # Set it to the camera name the prediction is for. if len(res) > 0: for re in res: # import ipdb; ipdb.set_trace() re = re.split(",") obj = metrics_pb...
6effd5af9f4e0da364623eb46a88896dae6ba2a4
3,629,543
import numbers def check_random_state(seed): """Turn `seed` into a `np.random.RandomState` instance. Parameters ---------- seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional If `seed` is None (or `np.random`), the `numpy.random.RandomState` ...
31d9435a277174dc6bc033bc1f37b0b5de02078b
3,629,544
import typing def serialize(message: typing.Union[structure.Call, structure.CallResult, structure.CallError]) -> typing.List: """Serializes an 'OCPPMessage'. Args: - message: 'OCPPMessage', the message to serialize Returns: list, an equivalent to the message, based only on JSON compatibl...
a1cc6f966528fb156f825bd87b9c765b9b8783a0
3,629,546
from typing import Sequence def sequence_plot(units: Sequence[Unit]): """Plot the temperatures of all profiles""" fig, ax = utils.create_sequence_plot(units) ax.set_ylabel(r"temperature $T$") ax.set_title("Mean Profile Temperatures") units = list(units) if len(units) > 0: def gen_seq(...
73b7d5b7a0653deb5108b75398102b2e4ae44e84
3,629,547
def format_data(data): """ :param data: :return: str : this str can print to web page. """ return "<pre>" + change_to_str(data, rowstr="<br/>") + "</pre>"
312cf4a1aaece4cc4921f06ed6b85bdde7ad6955
3,629,548
def DAYS(date1, date2): """Given two strings of dates, calculate the difference in days between the two. Parameters ---------- date1 : string start date in the form of a string: 'YYYY-MM-DD' date2 : string end date in the form of a string: 'YYYY-MM-DD' Returns ------- i...
a7401fe0230f49ec864a0e3549f823e19c9879c0
3,629,549
from typing import List def __get_column_names_from_worksheet(worksheet: Worksheet) -> List[NumberOrString]: """Returns list of column names (headers) from worksheet object (i.e; the values from row #1)""" column_names = [ column.value for column in next(worksheet.iter_rows(min_row=1, max_row=1)) ...
3653091b303a0daa512ca3fc3e2bd4aebe4342f6
3,629,550
def get_fractal_patterns_NtoS_WtoE(fractal_portrait, width, height): """ get all fractal patterns from fractal portrait, from North to South, from West to East """ fractal_patterns = [] for y in range(height): # single fractal pattern f_p = get_fractal_patterns_zero_amounts() for x i...
a19668d5d1f8ae7cb24e79c1e17030cde25c1821
3,629,552
def single_stat_request(player, code, stat): """Actually retrieves the stat and returns the stat info in an embed""" session = Session() message = "" if code == 1: (table, col, message) = stat_dict[stat] columns = [col] res = session.query(*(getattr(table, column) for column in c...
b7eef445b3580eff93768394a0f0632a6174e1a8
3,629,554
from typing import List def random_string_list(num: int = 10) -> List[str]: """ Generate list of random strings >>> type(random_string_list()) <class 'list'> >>> all([True if type(obj) is str else False for obj in random_string_list()]) True >>> len(random_string_list()) 10 >>> le...
f13ee6e837d78b631ece65370c15bc1a69e8c7dc
3,629,556
def get_entity_description(entity): """ Realiza o mapeamento de uma entidade padrão da extracão de entidades (named entity) retornando de forma explícita o equivalente em português para a entidade extraída. param : entity : <str> return : <str> """ ent_map = { 'PERSON': 'pessoa'...
21fe671419ba00436070ec49cc0433fabfb0c597
3,629,557
def duration(utter: Utterance) -> int: """Get the duration of an utterance in milliseconds Args: utter: The utterance we are finding the duration of """ return utter.end_time - utter.start_time
bfa1cc9139134a435b9ab39bc7dad9e504abef2d
3,629,558
import more_itertools as mit def label_sequential_regions(inlist): """Input a list of labeled tuples and return a dictionary of sequentially labeled regions. Args: inlist (list): A list of tuples with the first number representing the index and the second the index label. Returns: dict: ...
f258310bd672be41828405f8cab772358991e1c0
3,629,559
def lines_edit_renderer(widget, data): """Renders text area with list value as lines. """ tag = data.tag area_attrs = textarea_attributes(widget, data) value = fetch_value(widget, data) if value is None: value = u'' else: value = u'\n'.join(value) return tag('textarea', v...
600f1b1c5952bd39b56112208ef61dd08e2887d3
3,629,560
def variantsFromAlignment(refWindow, refSeq, cssSeq, cssQV=None, refCoverage=None): """ Extract the variants implied by a pairwise alignment of cssSeq to refSeq reference. If cssQV, refCoverage are provided, they will be used to decorate the variants with those attributes. ...
a49fd077db6043fbf23dc6a9d88c51143195d928
3,629,561
from datetime import datetime def exception_guard(f): """ Middleware (guard): checks if the current authorized user can created an exception request """ @wraps(f) def decorated_function(*args, **kwargs): if 'eid' not in kwargs.keys(): return F.abort(404) election =...
850c9818516de666082fbfcc19e7bc281c876b30
3,629,563
def return_last(responses): """Return last item of a list.""" return responses[-1]
f4aedfe0b10adcdb859ac1d0f5809ca666abac80
3,629,564
from typing import List from typing import Tuple def autolink_replacements(what: str) -> List[Tuple[str, str, str]]: """ Create a list containing replacement tuples of the form: (``regex``, ``replacement``, ``obj``) for all classes and methods which are imported in ``KEDRO_MODULES`` ``__init__.py`` fi...
4ff706f19b2f3a4ede71f7bd1307f129fce53660
3,629,565
def get_boundary_cell_count(plate_dims, exclude_outer=1): """Get number of wells in outer or inner edges Parameters ---------- plate_dims : array dimensions of plate Returns ------- boundary_cell_count : int number of wells in the edges """ boundary_cell_count =...
8e5056af647f893854bab3de3e6e5038c0d703e1
3,629,567
def _is_false(x): """Evaluates false for bool(False) and str("false")/str("False"). The function is vectorized over numpy arrays or pandas Series. Everything that is NA as defined in `is_na()` evaluates to False. but also works for single values. """ x = np.array(x).astype(object) ret...
200c43dcd60821642cb18a2ac82b1fd592bdaa9e
3,629,568
def compute_border_indices(log2_T, J, i0, i1): """ Computes border indices at all scales which correspond to the original signal boundaries after padding. At the finest resolution, original_signal = padded_signal[..., i0:i1]. This function finds the integers i0, i1 for all temporal subsamplings...
09d29c4de2c808a1947d513580817bda16a6bfe7
3,629,569
def get(data_ids): """ Get a object(s) associated with `data_ids` from the shared object storage. Parameters ---------- data_ids : unidist.core.backends.common.data_id.DataID or list An ID(s) to object(s) to get data from. Returns ------- object A Python object. """...
2f42a45abd56428d1b0087cd9b78460430bed18e
3,629,570
def pass_time(grid, minutes): """Pass number of minutes on grid.""" cur_grid = copy_grid(grid) grid_set = get_grid_for_set(cur_grid) grid_set_to_minute = {grid_set: 0} minute_to_grid_set = {0: grid_set} for minute in range(1, minutes + 1): cur_grid = pass_minute(cur_grid) cur_gri...
6929989d647c46a9c66bb1cee0e545ba621a72cc
3,629,571
def error_rate(predictions, labels): """Return the error rate based on dense predictions and sparse labels.""" return 100.0 - (100.0 * np.sum(np.argmax(predictions, 1) == labels) / predictions.shape[0])
c2e3ce21e799cf0368523fbcb3fab603642e9c7d
3,629,573
import tqdm def run_question_generation(trainer, dset, model, tokenizer, device, num_beams): """ Generate a set of questions from a source text and list of answers (named entities) :param trainer: HuggingFace trainer :param dset: The dataset to generate questions from :param model: Question genera...
aff16d397b908eae0ab8ada273392e59ea444b68
3,629,574
def get_queue_ids(client: Client) -> list: """ Creating a list of all queue ids that are in the system. Args: client: Client for the api. Returns: list of queue ids. """ queues = client.queues_list_request() queues = queues.get('Queues', []) queues_id = [] for q in qu...
e9455f8a30db543c44241c75ab86b4be7db9715e
3,629,575
def get_image_palette(img, nclusters): """ Extract tuple of (Image, Palette) in LAB space """ lab = rgb2lab(np.array(img)) palette = kmeans_get_palette(lab, nclusters) return lab, palette
a6570d08dd2a76bd8dae7ffdcf34ca271c09c7c6
3,629,576
def isbuffer(obj) -> bool: """ Test whether `obj` is an object that supports the buffer API, like a bytes or bytearray object. """ try: with memoryview(obj): return True except TypeError: return False
bede4ffeb154e765c7c2f4dea3bfa77281b313f2
3,629,578
def yes_maybe_condition_true(x: dict) -> bool: """ The yes maybe condition is true if 35% or 2 (or more) out of 3 users 2 (or more) out of 4 users 2 (or more) out of 5 users have classified as 'yes' or 'maybe' """ if x["yes_share"] + x["maybe_share"] > 0.35: return True else...
3009f2fdb6bdec69ab7f7530d47d40e1f493f8ba
3,629,580
def load_texture(filename): """ This fuctions will return the id for the texture""" textureSurface = pygame.image.load(filename) textureData = pygame.image.tostring(textureSurface,"RGBA",1) width = textureSurface.get_width() height = textureSurface.get_height() ID = glGenTextures(1) glBindTe...
223ce31249589ed2db690add01fc0c00449ef211
3,629,581
import string def search(pattern, doc, flags=0): """Scan through string looking for a match to the pattern, returning a match object, or None if no match was found.""" return _compile(pattern, flags).search(string)
d13be664aa3c279fc46c798c757acb80130a4f29
3,629,582
from typing import Concatenate def yolo4_mobilenetv3small_body(inputs, num_anchors, num_classes, alpha=1.0): """Create YOLO_V4 MobileNetV3Small model CNN body in Keras.""" mobilenetv3small = MobileNetV3Small(input_tensor=inputs, weights='imagenet', include_top=False, alpha=alpha) # input: 416 x 416 x 3 ...
586e6f7b88ca785fe93b0cccda41291ccd4dec0f
3,629,583
def get_all_effects(fname): """ Give fname from a direct effect file """ # Step 1: Load results for current file print(fname) indirect_result_df = pd.read_csv(fname) analyze_effect_results( results_df=indirect_result_df, effect="indirect" ) fname = fname.replace("_indirect_"...
e032b963a2ccb98b2d824ddc870fa661f38ad8f6
3,629,585
def cart_key(user_id=DEFAULT_USER_ID): """Sub model for representing an author.""" return ndb.Key('addSong2Cart', user_id)
749ba650ed7ce7301ac1d152efcbd3da24cc6b2b
3,629,586
from contextlib import suppress from datetime import datetime def format_datetime(date_str): """ Convert Twitter's date time format ("Thu Jul 20 19:34:20 +0000 2017") to ISO 8601 International Standard Date and Time format. :param date_str: :return: """ with suppress(TypeError, Val...
fe926659acd095090a37c2cc8fd320d73e30c446
3,629,587
from pathlib import Path from typing import Dict def git_named_refs(git_hash: str, git_dir: Path) -> Dict[str, str]: """ Returns all named tag or reference for the provided hash and the hash. This method does not need nor uses a git client installation. """ refs = dict(hash=git_hash) ref_dir ...
0ad9f07c2885785a39f3918c43b0c795d4a864e7
3,629,588
def check_string(seq): """Checks if seq is a string""" if not isinstance(seq, str): assert False, "Input is not a string." else: pass return None
c56ce486fae2e1335b0b191b1804b19ab121f1c9
3,629,589
from typing import Sized def shift_right(sized: Sized, n: int) -> Sized: """Return a copy of sized with it's elements shifted n places to the left but keeping the same size. sized: A sized object which's elements to shift n: How many places to shift sized's items to the left """ return [None] * n...
39ac29ba835d0ea68971d331b235c17c6f98f56a
3,629,590
import io def backport_makefile( self, mode="r", buffering=None, encoding=None, errors=None, newline=None ): """ Backport of ``socket.makefile`` from Python 3.5. """ if not set(mode) <= {"r", "w", "b"}: raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,)) writing = "w" ...
d19d6ffdd8fcf41e39d021b071bada5bb9c1ea29
3,629,591
from datetime import datetime def epoch_seconds(d: datetime = None) -> int: """ Return the number of seconds for given date. If no date, return current. :param d: timestamp datetime object :return: timestamp in epoch """ if not d: d = datetime.utcnow() return int((d - datetime.utcf...
b9a4671b0904d148248231a1e1eabfa062a5d1d2
3,629,592
import json def parse_json(json_file): """JSON poem parser for 'Gongocorpus'. We read the data and find elements like title, author, year, etc. Then we iterate over the poem text and we look for each stanza, line, word and syllable data. :param json_file: Path for the json file :return: Dict ...
e1944bd5cf18e913c22a8d910aafee608a654e0e
3,629,593
def chou_pseudo_aa_composition(*sequences): """ M.K. Gupta , R. Niyogi & M. Misra (2013) An alignment-free method to find similarity among protein sequences via the general form of Chou’s pseudo amino acid composition, SAR and QSAR in Environmental Research, 24:7, 597-609, DOI: 10.1080/1062936X.20...
95ce5b0ee082a899ea487a910280233fc892430a
3,629,594
def calculate_wire_sweeping_const(h_over_d): """Calculate the wire-sweeping constant for the Upgraded Cheng-Todreas friction factor constant calculation""" ws = {} if h_over_d == 0.0: ws['turbulent'] = 0.0 ws['laminar'] = 0.0 else: ws['turbulent'] = -11.0 * np.log10(h_over_d)...
ae3247de9ff14eb5f14065906f7c6fc0e2a4dc34
3,629,595
import json def create_subscription_definition(subscription_definition_dict): """Create a subscription definition.""" cli_input = json.dumps(subscription_definition_dict) cmd = [ "aws", "greengrass", "create-subscription-definition", "--cli-input-json", cli_input ...
30c51f6f6b905390574b839ec6363716c619c48f
3,629,596
def compile(element, compiler, **_kw): # pylint: disable=function-redefined """ Get length of array defined in a JSONB column """ return "jsonb_typeof(%s)" % compiler.process(element.clauses)
917706c5aa05305c6d2930673d23194665b8c6ed
3,629,597
def guid(fn): """Server mock; grab the object guid from the url""" @wraps(fn) def wrapper(self, request, context, *args, **kwargs): guid = uuid_url_matcher('.+').match(request.path).group(1) return fn(self, request=request, context=context, guid=guid, *args, **kwargs) return wrapper
87dd8b645117e6df5977d72e4f4309a735d00c83
3,629,598
def pil_to_numpy(img: Image.Image) -> np.ndarray: """ Args: img: an Image.Image from `read_img()` Returns: np.ndarray, RGB-style, with shape: [3, H, W], scale: [0, 255], dtype: float32 """ return np.asarray(img.convert('RGB'), dtype='float32').transpose((2, 0, 1))
924b4ad93204b6f2716b316c79b43bc1f83de156
3,629,599
def reference(t, viscosity, density, concentration_init, concentration_init_dev, solutes, permittivity, enable_NS, enable_EC, **namespace): """ This contains the analytical reference for convergence analysis. """ mu = viscosity[0] rho_0 = density[0] ...
388e74271c17029e4477407d0048e931e756f48b
3,629,600
def std_err_mean(data): """ calculates deviation from mean. data: all spikes """ return data.std(0).mean()/np.sqrt(data.shape[0])
53f6aecf543617f5d85ddca88c193c41605ab668
3,629,601
import copy from unittest.mock import patch def mock_history(initial): """ mock the commands that interact with the .history file, to fake history management """ releases = copy.copy(initial) project = 'project' def list_releases(): return releases def _append_to_history(rel...
ae65684fe3c1fda6bbecc73a84bb767aa5d92713
3,629,602
def _EpoOff(opts, node_list, inst_map): """Does the actual power off. @param opts: The command line options selected by the user @param node_list: The list of nodes to operate on (all need to support OOB) @param inst_map: A dict of inst -> nodes mapping @return: The desired exit status """ if not _Insta...
9e23d1979813fadb54b168b2f57a546275b3cf8b
3,629,603
def available_numbers(request): """Uses the Twilio API to generate a list of available phone numbers""" form = AreaCodeForm(request.POST) if form.is_valid(): # We received a valid area code - query the Twilio API area_code = form.cleaned_data['area_code'] available_numbers = search...
b00cabe2a2c276f09d5185b46f20d0640e66a672
3,629,604
def get_julia_version(path): """Return version of the Julia installed in *path*""" return exec_shell_cmd('julia.exe -v', path).splitlines()[0].split(" ")[-1]
8421a6de683b7c364e835c6070c8de9f17a4a3c0
3,629,605
def get_pvc_file(flags, spa, pvc_name): """ Get pvc config """ outfile = os.path.join(os.getenv('TMPDIR', '/tmp'), pvc_name + '.yaml') args = [ 'spa', 'get', '-A', flags.account_arg, '--id', spa['meta']['id'], '-K', 'k8sPvcYaml', '-...
611f3f9878db66b30d4119364c754a3c11af41c6
3,629,606
def video_feed(): """Video streaming route. Put this in the src attribute of an img tag.""" return Response(attendence(), mimetype='multipart/x-mixed-replace; boundary=frame')
0ba1d98a4287406f364900eda2b12faeac491237
3,629,607
def current(ticker): """ Return the current price for a stock """ return rh.get_latest_price(ticker)[0]
abfa290c79267981571ae25ee7bd1827b4182141
3,629,608
from typing import Optional from typing import Tuple def fetch_indicators_command( client, initial_interval, limit, last_run_ctx, fetch_full_feed: bool = False, filter_args: Optional[dict] = None, ) -> Tuple[list, dict]: """ Fetch indicators from TAXII 2 server :param client: Taxii...
e527391a0055c7604d4423e0565cf04b017e8038
3,629,611
def aggregate(loss, weights=None, mode='mean'): """Aggregates an element- or item-wise loss to a scalar loss. Parameters ---------- loss : Theano tensor The loss expression to aggregate. weights : Theano tensor, optional The weights for each element or item, must be broadcastable to...
6d888d1854cfa78e13fcd5eba412e224164386d7
3,629,612
def mirror_ud(image): """Mirrors an image between up and down :param image: An input image to convert :type image: array_like :return: Mirrored image. Same dimensions as input. :rtype: ndarray """ return np.flipud(image)
8a8113fcc4d7335fcaa7bd5a259b19e856408814
3,629,613
import torch def ifftn(input, s=None, dim=-1, norm='backward', real=None): """N-dimensional discrete inverse Fourier transform. Parameters ---------- input : tensor Input signal. If torch <= 1.5, the last dimension must be of length 2 and contain the real and imaginary parts o...
0fa3c678a6747d25634f5a68e78fa3d4597ac587
3,629,614
def list_del(): """ del """ mylist = ['dog', 'lion', 'snake', 'elephant', 'cow', 'donkey', 'goat', 'duck'] del mylist[2] return mylist
716fbb915bc477f4232e66b6b7fcb720bb0520f4
3,629,615
def _get_group_definition(group): """Get an instance of the group definition for the specified item. This definition can be used to clone or download the group. Keyword arguments: group - The arcgis.GIS.Group to get the definition for.""" return _GroupDefinition(dict(group), thumbnail=None, portal_grou...
7a00dc3117ec725bbd9eef2dbafe39e1d39d9de7
3,629,616
def assert_rank(x, rank, data=None, summarize=None, message=None, name=None): """Assert `x` has rank equal to `rank`. Example of adding a dependency to an operation: ```python with tf.control_dependencies([tf.compat.v1.assert_rank(x, 2)]): output = tf.reduce_sum(x) ``` Args: x: Numeric `Tensor`....
447f95b909b21aa5c918bae2eccd327fb3bdb463
3,629,618
def get_lo_hi_from_CI(s, exclude=None): """ Parse the confidence interval from CI. >>> get_lo_hi_from_CI("20-20/40-60") (40, 60) """ a, b = s.split("|") ai, aj = a.split("-") bi, bj = b.split("-") los = [int(ai), int(bi)] his = [int(aj), int(bj)] if exclude and exclude in l...
69c0fb14afd18444465cb7b0f8b23990d044a2b9
3,629,619
import transformers def get_pretrained_model(path='saved_models/checkpoint-1480'): """Gets a BERT classification model from a given pretrained model checkpoint (supplied with a filepath). Args: path (str): a valid filepath that contains the checkpoint of a DistilBert model Returns: transformers.DistilBertFor...
49a6a8603a7dc221f4ec9b85ef24ff2c422d0b51
3,629,620
from typing import Type from typing import Iterable from typing import Optional def get_docstring_summary( cls: Type, *, fallback_to_ancestors: bool = False, ignored_ancestors: Iterable[Type] = (object,) ) -> Optional[str]: """Get the summary line(s) of docstring for a class. If the summary is one more t...
0fbd076962dd08e4b537d00dd39e473a94331a5c
3,629,621
import logging def get_input_evaluation_tensors(reader, data_pattern, batch_size=1024, num_readers=1): """Creates the section of the graph which reads the evaluation data. Args: reader: A class which pars...
6f677a368ab55b8ecc4816f104484444ed8bfa3c
3,629,622
def load_extensions(app): """ To load navitaire extension :param app: :param name: :return: """ if 'stargate' not in app.extensions: raise GeneralError({ "code": "General Error", "description": "{name} not exist".format(name='stargate') }, 'info', http...
6239bc9cafdc1a948634b1b7329cfd6f1bbc1a4f
3,629,623
def blur(img): """ This function will blur the original image --------------------------------------------- :param img: SimpleImage, the original image :return: SimpleImage, the blurred image """ new_img = SimpleImage.blank(img.width, img.height) for x in range(img.width): for y ...
b41784396ff4f4402a7a8604796a32089f328b30
3,629,624
def describe_db_instances( name=None, filters=None, jmespath="DBInstances", region=None, key=None, keyid=None, profile=None, ): """ Return a detailed listing of some, or all, DB Instances visible in the current scope. Arbitrary subelements or subsections of the returned dataset ...
6393a969fd421fe966b593213acf8edc47520665
3,629,626
def get_control_changes(midi, use_drums=True): """Retrieves a list of control change events from a given MIDI song. Arguments: midi (PrettyMIDI): The MIDI song. """ midi_control_changes = [] for num_instrument, midi_instrument in enumerate(midi.instruments): if not midi_instrument.i...
c3c264c11f9ef38aa79c24cd795e35145139beb1
3,629,629
def is_workinprogress(change): """Return True if the patchset is WIP :param dict change: De-serialized dict of a gerrit change :return: True if one of the votes on the review sets it to WIP. """ # This indicates WIP for older Gerrit versions if change['status'] != 'NEW': return True ...
ac2f5ba1ab8d5fd432ef7b13c5b033e0c3710fd4
3,629,630
def get_bot() -> NoneBot: """ 获取全局 NoneBot 对象。可用于在计划任务的回调中获取当前 NoneBot 对象。 返回: NoneBot: 全局 NoneBot 对象 异常: ValueError: 全局 NoneBot 对象尚未初始化 用法: ```python bot = nonebot.get_bot() ``` """ if _bot is None: raise ValueError('NoneBot instance has no...
175c53c0b3bc73d303e1b766df94fcfb074f3de0
3,629,631
def white_noise(sigma, T, seed): """Реализация независимого белого шума длины T, ε ~ N(0, sigma^2)""" np.random.seed(seed) noise = np.random.normal(loc=0, scale=sigma, size=(1, T)) return noise
e6c88bd9f6857ff6aa0cb6f4af916fecb7aa04a7
3,629,633
def register_serializable(cls): """A class decorator registering the class for serialization.""" __types[type2str(cls)] = cls return cls
f6f65288235a291b9cb064b179e454580ecff280
3,629,634
import io from datetime import datetime def generate_realized_trips_from_gtfs(gtfs_path): """Transforms a GTFS feed to realized_trips format (see README for specification). It can either read a feed zip file or a folder. Parameters ---------- gtfs_path : str GTFS feed zip file or fol...
4a5050ebf63d39cb3d800adbc42d98410857e302
3,629,635
def get_stockdata_from_sql(mode,begin,end,name): """ get stock market data from sql,include: [Open,High,Low,Close,Pctchg,Vol, Amount,total_shares,free_float_shares,Vwap] """ try: conn = pymysql.connect(**config) cursor = conn.cursor() if mode == 0: query = "SELECT...
a9456019e51e1049d1bcedb1be45e40304de373f
3,629,636
def full_isomorphism(gra1, gra2): """ full graph isomorphism """ assert gra1 == explicit(gra1) and gra2 == explicit(gra2) nxg1 = _networkx.from_graph(gra1) nxg2 = _networkx.from_graph(gra2) iso_dct = _networkx.isomorphism(nxg1, nxg2) return iso_dct
086b0f85e72beb4b30f405706c0d0896cb65c002
3,629,637
def likelihood_overlap(lk1, lk2): """ Returns overlap area of two likelihood functions. Parameters ---------- lk1 : numpy.ndarray First likelihood function. lk2 : numpy.ndarray Second likelihood function. Returns ------- overlap : float Overlap area. ""...
d5af7b90ad7eac5fe47d7444e284317b573d8780
3,629,638
import resource def get_total_cpu_time_and_memory_usage(): """ Gives the total cpu time of itself and all its children, and the maximum RSS memory usage of itself and its single largest child. """ me = resource.getrusage(resource.RUSAGE_SELF) children = resource.getrusage(resource.RUSAGE_CHILD...
2073440a0ef6e9185b5b4c7613a56c902a722dc3
3,629,639
def require_single_skillet(func): """Commands decorated with this require one skillet to be uniquely specified""" def wrap(command): if not command.sli.options.get("name") and len(command.sli.skillets) > 1: raise InvalidArgumentsException( f"Specify a skillet to run with --n...
98b79706d1b2281a30bfa4a8dc10120a9631f620
3,629,640
def get_ecf_player(database, key): """Return ECFrefDBrecordECFplayer instance for dbrecord[key].""" p = database.get_primary_record(filespec.ECFPLAYER_FILE_DEF, key) pr = ECFrefDBrecordECFplayer() pr.load_record(p) return pr
189ab0219c8a730d7f416aa8419d3ef00352d6f5
3,629,641
import pickle def pickle_load(namefile: str): """Load Python variable, given name of file. :param namefile: A string of file to load. :return output: A loaded variable. """ with open(namefile, 'rb') as load_file: output = pickle.load(load_file) return output
425e53b8daf69bf832abc45a4270cc01f383c50e
3,629,642
import pkg_resources def load_preset_linelist(name): """ Returns one of our preset line lists, loaded into an astropy QTable """ metadata = get_linelist_metadata() if name not in metadata.keys(): raise ValueError("Line name not in available set of line lists. " + "...
ea435e63f30eaab8748fb01a7214050349cd89df
3,629,643
def scale_matrix(matrix): """ nn works best with values between 0.01 and 1 """ return matrix / 255 * 0.99 + 0.01
b4c0d34a21724ee5712caf8dca131b3e1e1d0753
3,629,644
def negate(condition): """ Returns a CPP conditional that is the opposite of the conditional passed in. """ if condition.startswith('!'): return condition[1:] return "!" + condition
5f31ed3ee2f16a53674f830402fdec890af25032
3,629,646
import maya.utils as utils import hdefereval import multiprocessing def __worker(func): """ thread runner Args: func: Returns: """ if env.Maya(): utils.executeDeferred(func) # https://forums.odforce.net/topic/22570-execute-in-main-thread-with-results/ elif env.Houdi...
a6d7635a09fe02975ed802cd4b59d70d2e163090
3,629,647
def _compute_n50_and_n95_np(readlengths): """ Numpy implementation of N50/N95 calculation. """ if isinstance(readlengths, list): readlengths = np.array(readlengths) readlengths[::-1].sort() # = np.sort(readlengths) total_length = np.sum(readlengths) csum = np.cumsum(readlengths) ...
9a3ac1ccdd3a2af10e76524cc6c628b8868d758b
3,629,648
def get_dominant_horizontal_line_colour(ip): """ >>> get_dominant_horizontal_line_colour(np.array([[0,0,0], [1,1,1], [1,0,0], [2,2,2],[0,0,0]])) {1, 2} """ #get unique list of colours per row row_info = ([np.unique(row) for row in ip]) # identify the whole colour lines, we do this if th...
e955b76940f85bf448e959e29f5134b1247d45ab
3,629,649
def _filter_out_disabled(d): """ Helper to remove Nones (actually any false-like type) from the scrubbers. This is needed so we can disable global scrubbers in a per-model basis. """ return {k: v for k, v in d.items() if v}
64a4577d6e5998e647ef82f126c50360388aba9a
3,629,650
def main(): """See fplutil/disttools/push_package.py. Returns: 0 if successful, non-zero otherwise. """ return disttools.push_package.main(disttools.push_package.parse_arguments( project_dir=PROJECT_DIR, config_json=CONFIG_JSON))
9e6ccf0d7654d980361e0ef446a0674344a8d3a5
3,629,651