content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def camelcase(key_name): """Convert snake-case to camel-case.""" parts = iter(key_name.split('_')) return next(parts) + ''.join(i.title() for i in parts)
078adb6b7b014bf3b0a7dffb00f1ff321951f275
27,300
def calculate_sigmoid(alpha_value = 1, TDE = 0, sigma=.1): """ SOFTMAX VBDE: f(s, a, \sigma) = \frac{2e^{-|\alpha TDE| / \sigma}}{1-e^{-|\alpha TDE|/\sigma}} :return: """ temp = np.exp(-np.abs(alpha_value *TDE + 1e-16) / sigma) return 2*temp / (1-temp)
d030447197531a850c43d5c86b17aae698c806ff
27,301
def getprop(obj, string): """ Par exemple 'position.x' :param string: :return: """ tab = string.split('.') curr_val = obj for str in tab: curr_val = getattr(curr_val, str) return curr_val
c82f869395129a8b69d1a89cde97ce36fe5affd9
27,302
import argparse def get_options(): """Parses options.""" parser = argparse.ArgumentParser( description="Dynamic inventory for Decapod.") group = parser.add_mutually_exclusive_group(required=True) group.add_argument( "-l", "--list", help="List all inventory.", action="...
c4efc1978dfb735e6e08060400d3752357e924a0
27,303
def extend(vals, inds, shape): """ Makes an array of shape `shape` where indices `inds` have vales `vals` """ z = np.zeros(shape, dtype=vals.dtype) z[inds] = vals return z
fddcf709779ce139f1645e4292690fed6e0378f6
27,304
def check_model(model_name, model, model_type): """ Check the type of input `model` . Args: model_name (str): Name of model. model (Object): Model object. model_type (Class): Class of model. Returns: Object, if the type of `model` is `model_type`, return `model` itself....
b6bd8b25cc2ea91e328ec5e17fd88f3f6e676e67
27,305
import os def load_score_map(input_prefix, day, epsilon=0.000000001, excluded_indices=None, restricted_indices=None): """TODO: The centrality maps were pre-sorted in decreasing order???""" score_file_path = input_prefix + '_%i.csv' % day if not os.path.exists(score_file_path): raise IOError("File ...
7596f68644ce0c4d56becedd26aad450e5590276
27,306
def compute_tnacs( hvib ): """ Computes the time-averaged nonadiabatic couplings for a given hvib. hvib ( list of list of matrices ): The vibronic hamiltonian for all timesteps returns: a matrix of time-averaged nonadiabatic couplings between all electronic states in meV """ nst...
87a30d408a2a9a14fd4987edba66a47b95d4a0fe
27,307
import async_timeout async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up config entry.""" session = aiohttp_client.async_get_clientsession(hass) hass.data.setdefault(DOMAIN, {}) printer = SyncThru( entry.data[CONF_URL], session, connection_mode=ConnectionMo...
4dbecb1a63b228b689461f764c8e679c3a52f545
27,308
def center_binned_stats(*args, **kwargs): """ Same as scipy.stats.binned_statistic, but returns the bin centers (matching length of `statistic`) instead of the binedges. See docs.scipy.org/doc/scipy/reference/generated/scipy.stats.binned_statistic.html """ stat, binedges, binnumber = bi...
adb762d874a19b4af09a49a2ad30b1b33d314be8
27,309
def create_account(): """ Handles the user signing up to create an account Redirects them to the log in page with a message after if successful """ signUpForm = forms.RegisterFormFactory() if signUpForm.validate_on_submit(): netid,name,duke_email,phone_number,affiliation,password=extrac...
321bcf6c779c6aa8857b9c4d054c18c5f611c5ad
27,310
from art.classifiers import BlackBoxClassifier from art.utils import to_categorical import os import json def get_classifier_bb(defences=None): """ Standard BlackBox classifier for unit testing :return: BlackBoxClassifier """ # define blackbox classifier def predict(x): with open(os....
8a2c3d47296450544c3f7ed69b9e4316f85ca591
27,311
import warnings def tracks(track): """ Check if the submitted RGTs are valid Arguments --------- track: ICESat-2 reference ground track (RGT) """ #-- string length of RGTs in granules track_length = 4 #-- total number of ICESat-2 satellite RGTs is 1387 all_tracks = [str(tr + 1...
306b213fc040dbaabf515dfeff7efe45db656549
27,312
def submit_spark_job(project_id, region, cluster_name, job_id_output_path, main_jar_file_uri=None, main_class=None, args=[], spark_job={}, job={}, wait_interval=30): """Submits a Cloud Dataproc job for running Apache Spark applications on YARN. Args: project_id (str): Required. The ID of t...
86494a8af89a93507d40c334a84ee279cc5f7250
27,313
import sys def load_pickle(f): """load pickle file and generate dictionary :param f: absolute filepath to CSC library pickle files :return: dictionary object (Pandas) """ with open(f, 'rb') as infile: pickle_dataframe = pl.load(infile,encoding='latin1') try: pickle_d...
09b28ce3981d41381a632c888e2f331c2733ba84
27,314
def get_filter_ids(id_query): """Parses the `id` filter paramter from the url query. """ if id_query is None: return None filter_ids = id_query.split(',') for filter_id in filter_ids: validate_id(filter_id) return filter_ids
08582368e4487c602160af42dbc6ffcd10c97075
27,315
import random def random_sampling(predictions, number): """ This method will return us the next values that we need to labelise for our training with a random prioritisation Args: predictions : A matrix of probabilities with all the predictions for t...
22a1b13122bdf5c1b95d2b039458d27a62544f6d
27,316
def natsort_key_icase(s: str) -> str: """Split string to numeric and non-numeric fragments.""" return natsort_key(s.lower())
ae8bbbec4a7889c2737fbe10e62c69215398faf7
27,317
def model_fn_builder(bert_config, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_tpu, use_one_hot_embeddings): """Returns `model_fn` closure for TPUEstimator.""" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument ""...
84a66d5e10032c5e6fffbbf0069e2e674f8ca8f8
27,318
def datetime_to_gps_format(t): """ Converts from a datetime to week number and time of week format. NOTE: This does NOT convert between utc and gps time. The result will still be in gps time (so will be off by some number of leap seconds). Parameters ---------- t : np.datetime64, pd.Ti...
66dfdb09534f3b425f50d0710c68819e067c89a4
27,319
def view(jinja_environment: Environment, name: str, *args, **kwargs): """ Returns a Response object with HTML obtained from synchronous rendering. Use this when `enable_async` is set to False when calling `use_templates`. """ return get_response( render_template( jinja_environme...
864c7106db19cc15cb37132c7755652b500f3ef2
27,320
from typing import List import collections def create_preprocess_fn( vocab: List[str], num_oov_buckets: int, client_batch_size: int, client_epochs_per_round: int, max_sequence_length: int, max_elements_per_client: int, max_shuffle_buffer_size: int = 10000) -> tff.Computation: """Creates ...
1a7d114de3d979da4556123b185a00ca810b3f82
27,321
def get_slope_aspect(dem, get_aspect=True): """ Return the instantaneous slope and aspect (if get_aspect) for dem. Both values derived using NumPy's gradient method by methods from: Ritter, Paul. "A vector-based slope and aspect generation algorithm." Photogrammetric Engineering and Remote Sensing...
261ea3dbd114dc706f2b1f388741961bd7eb0360
27,322
def get_element_parts( original_list: list, splitter_character: str, split_index: int ) -> list: """ Split all elements of the passed list on the passed splitter_character. Return the element at the passed index. Parameters ---------- original_list : list List of strings to be spli...
8c663fd64ebb1b2c53a64a17f7d63e842b457652
27,323
from typing import Union import os import csv import requests import json def download(tickers: list, start: Union[str, int] = None, end: Union[str, int] = None, interval: str = "1d") -> dict: """ Download historical data for tickers in the list. Parameters ---------- tickers: list Ticker...
f775f45ab6136773f5c9859531ef96eb73f9e337
27,324
def logsumexp_masked(a, mask): """Returns row-wise masked log sum exp of a. Uses the following trick for numeric stability: log(sum(exp(x))) == log(sum(exp(x - max(x)))) + max(x) Args: a: 2D tensor. mask: 2D tensor. """ mask = tf.cast(mask, a.dtype) a_max = tf.math.reduce_max(a * mask, axis=1, k...
86102b153e7ce912678a6381b38cb3a5168de3c8
27,325
def mutaprop_class(display_name, gui_id=None, gui_major_version=0, gui_minor_version=0): """ Class-level decorator. It is required for classes whose instances should be visible for the Mutaprop UI manager. :param display_name: Class name/description to be accessible by the UI API. ...
4aee47a88ec5f20263decb12eb64340dd0bf296f
27,326
def preprocess2(data: list, max_length: int, test_data: bool): """ 입력을 받아서 딥러닝 모델이 학습 가능한 포맷으로 변경하는 함수입니다. 기본 제공 알고리즘은 char2vec이며, 기본 모델이 MLP이기 때문에, 입력 값의 크기를 모두 고정한 벡터를 리턴합니다. 문자열의 길이가 고정값보다 길면 긴 부분을 제거하고, 짧으면 0으로 채웁니다. :param data: 문자열 리스트 ([문자열1, 문자열2, ...]) :param max_length: 문자열의 최대 길이 ...
61810a385c935796f1d4f6e57c5f602cb0fa6f33
27,327
def create_inference_metadata(object_type, boundary_image, boundary_world): """ Create a metadata of **each** detected object :param object_type: Type of the object | int :param boundary: Boundary of the object in GCS - shape: 2(x, y) x points | np.array :return: JSON object of each detected object ...
b13f1ad4abc22f3eaca2c81c56ab9cb0eae80aa9
27,328
def noauth_filter_factory(global_conf, forged_roles): """Create a NoAuth paste deploy filter :param forged_roles: A space seperated list for roles to forge on requests """ forged_roles = forged_roles.split() def filter(app): return NoAuthFilter(app, forged_roles) return filter
5a18d581616c6b4ae54b5d9c30095dd8734ed2e7
27,329
from typing import Tuple from typing import Dict def parse_line_protocol_stat_key(key: str) -> Tuple[str, Dict[str, str]]: """Parseline protocolish key to stat prefix and key. Examples: SNMP_WORKER;hostname=abc.com,worker=snmp-mti will become: ("SNMP_WORKER", {"hostname": "abc.com", "...
a6806f7dd67fb2a4734caca94bff3d974923f4b2
27,330
def negative_log_partial_likelihood(censor, risk): """Return the negative log-partial likelihood of the prediction y_true contains the survival time risk is the risk output from the neural network censor is the vector of inputs that are censored regularization is the regularization constant (not use...
e42a7cf32fd191efb91806ecf51fd7bf279595c6
27,331
import math def approx_equal(x, y, tol=1e-12, rel=1e-7): """approx_equal(x, y [, tol [, rel]]) => True|False Return True if numbers x and y are approximately equal, to within some margin of error, otherwise return False. Numbers which compare equal will also compare approximately equal. x is app...
45285d62e6fb3da403f3efd15b1f67df92cd345c
27,332
import os def get_deleted_filename(absolute): """ Returns the name of the deleted file referenced by the AUFS whiteout file at the given path or None if the file path does not reference a whiteout file. """ filename = os.path.basename(absolute) if not filename.startswith(AUFS_WHITEOUT): ...
14936fa55bbb1733bf2d481772e9fe96c5291a55
27,333
import json def get_latest_enabled_scripts(): """The ``/scripts/latest/enabled`` endpoint requires authentication. It is used to get latest enabled scripts for all services submitted by all teams including master/organizer where the team id will be Null. The JSON response is: { ...
4430eaf9c7a0d0a82f5977850e46221e8b5998fe
27,334
def hanning(shape, dtype=np.float, device=backend.cpu_device): """Create multi-dimensional hanning window. Args: shape (tuple of ints): Output shape. dtype (Dtype): Output data-type. device (Device): Output device. Returns: array: hanning filter. """ device = backe...
2192b4e75ceb52560865219553d27acd56bf4ef4
27,335
from typing import Union def bitwise_and(x1: Union[ivy.Array, ivy.NativeArray], x2: Union[ivy.Array, ivy.NativeArray]) -> ivy.Array: """ Computes the bitwise AND of the underlying binary representation of each element x1_i of the input array x1 with the respective element x2_i of the input array x2. ...
662a706ba79e5f67958c78752197eff4c2a0a298
27,336
import os def init_database(use_mysql=False, dbname="sbs"): """ initialize database if use_mysql is true, use environment variables to set it up otherwise default to sqlite """ #engine = create_engine('sqlite:///:memory:', echo=False) # "mysql+mysqldb://{user}:{password}@{host}:{port}/{dbn...
9f4ecd5c375333ef717acf6f521001854138b2d2
27,337
def add_without_punctuation(line, punctuation): """Returns the line cleaned of punctuation. Param: line (unicode) Returns: False if there are not any punctuation Corrected line """ cleaned_line = line.translate(str.maketrans('', '', punctuation)) if line != cleaned_line...
20dafde21efad966f8ea1be0da928594e2ee5cc4
27,338
from typing import Callable def there_is_zero( f: Callable[[float], float], head: float, tail: float, subint: int ) -> bool: """ Checks if the function has a zero in [head, tail], looking at subint subintervals """ length = tail - head step = length / subint t = head a = f(head) ...
dd80c55d4be5fed2e3100672ea63862014b0f8cc
27,339
def target_distribution_gen(name, parameter1, parameter2): """ parameter1 is usually a parameter of distribution (not always relevant). parameter2 is usually noise.""" if name=="Fritz-visibility": """ parameter2 is the visibility""" ids = np.zeros((4,4,4)).astype(str) p = np.zeros((4,4,...
475ee931c64f1e0bb0f6a6494aeacb25283adb9f
27,340
def module_code( sexpr, name: str = "<unknown>", filename: str = "<unknown>", lineno: int = 1, doc: str = "", ): """Create a module's code object from given metadata and s-expression. """ module_builder = Builder( ScopeSolver.outermost(), [], SharedState(doc, lineno, filename) ...
b1baf9ab8355fadd15c6763c569399aca62b9994
27,341
def acknowledgements(): """Provides acknowlegements for the JRO instruments and experiments Returns ------- ackn : str String providing acknowledgement text for studies using JRO data """ ackn = ' '.join(["The Jicamarca Radio Observatory is a facility of the", "Ins...
013727319d43baaec57461995af8a683b5f02278
27,342
def list_vmachines(vdc): """ Returns: list: vmachines info """ return vdc.to_dict()["vmachines"]
b3ce74c5b6f7d6d9f109a884f0c050ffae840e70
27,343
def reflection_matrix(v): """ The reflection transformation about a plane with normal vector `v`. """ n = len(v) v = np.array(v)[np.newaxis] return np.eye(n) - 2 * np.dot(v.T, v)
0b56f21e95162720e4856ac2ee995570c0231d4f
27,344
import logging def log_level(level): """ Setup the root logger for the script """ return { 'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'WARNING': logging.WARNING, 'ERROR': logging.ERROR, 'CRITICAL': logging.CRITICAL, }.get(level, logging.INFO)
97af634f195c1ccaef52e3db0e29caaa50554e31
27,345
def is_valid_furl_or_file(furl_or_file): """Validate a FURL or a FURL file. If ``furl_or_file`` looks like a file, we simply make sure its directory exists and that it has a ``.furl`` file extension. We don't try to see if the FURL file exists or to read its contents. This is useful for cases wher...
452617b469006ec5bf4d341af2163dc3b4f69bf7
27,346
import random def stride(input_data, input_labels): """ Takes an input waterfall visibility with labels and strides across frequency, producing (Nchan - 64)/S new waterfalls to be folded. """ spw_hw = 32 # spectral window half width nchans = 1024 fold = nchans / (2 * spw_hw) sample_sp...
f490df82e65356443d6fe8a951a0ad282ca1c2af
27,347
import os def abspaths(paths): """ an wrapper function of os.path.abspath to process mutliple paths. """ return [os.path.abspath(p) for p in paths]
ae3591a11ee152a0ca2eb342644749c669c8d78e
27,348
import DominantSparseEigenAD.Lanczos as lanczos import torch def chiF_sparseAD(model, k): """ Compute chi_F using the DominantSparseSymeig primitive, where the matrix to be diagonalized is "sparse" and represented as a function. """ lanczos.setDominantSparseSymeig(model.H, model.Hadjoint_to_g...
acb820da75218dd37d805867ed246ca9ec2efad2
27,349
def sum_digits(y): """Sum all the digits of y. >>> sum_digits(10) # 1 + 0 = 1 1 >>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12 12 >>> sum_digits(1234567890) 45 >>> a = sum_digits(123) # make sure that you are using return rather than print >>> a 6 """ "*** YOUR CODE HERE ***"...
5300e5bdbb058c4cc8d4a57155b114eab31b1935
27,350
import scipy def leastsq(error_func, x0, *args, **options): """Find the parameters that yield the best fit for the data. `x0` can be a sequence, array, Series, or Params Positional arguments are passed along to `error_func`. Keyword arguments are passed to `scipy.optimize.leastsq` error_func: ...
d949358016ddab5d650ca1bab5c98e4ae124c153
27,351
def atomic_token_partition(value): """Partition given value on a token that appears resolvable(contains no sub tokens). Returns in a tuple: (before_token, token, after_token). Returned token includes token syntax. If no tokens are found, returned tuple contains None in all values. :param value: tex...
1a4b0b952dcaa65c6f04d066685a609f1bd03669
27,352
def add_color_bar(img, space, cv): """ args: img: (ndarray) in [img_rows, img_cols, channels], dtype as unit8 space: (int) pixels of space cv: (int) color value in [0, 255] return: tmp_img: (ndarray) processed img """ assert len(img.shape) == 3, "img should be 3D" ...
a08fc1eac525dd4156add949bc4cf706ee1ea299
27,353
import json def get_cli_body_ssh(command, response, module): """Get response for when transport=cli. This is kind of a hack and mainly needed because these modules were originally written for NX-API. And not every command supports "| json" when using cli/ssh. As such, we assume if | json returns an...
7d65bd1d19a837b5e78d0e1d834f2a00f4815cdb
27,354
def zero_at(pos, size=8): """ Create a size-bit int which only has one '0' bit at specific position. :param int pos: Position of '0' bit. :param int size: Length of value by bit. :rtype: int """ assert 0 <= pos < size return 2**size - 2**(size - pos - 1) - 1
7ebdcc1ac9db4ad934108f67a751b336b4f18011
27,355
def get_authz_token(request, user=None, access_token=None): """Construct AuthzToken instance from session; refresh token if needed.""" if access_token is not None: return _create_authz_token(request, user=user, access_token=access_token) elif is_request_access_token(request): return _create_...
84a7f06085877b51181cadaf29da4dc0611c636b
27,356
import torch def get_bert_model(): """ Load uncased HuggingFace model. """ bert_model = torch.hub.load('huggingface/pytorch-transformers', 'model', 'bert-base-uncased') return bert_model
51b49255fe4b1291d538251c8c199bd570fb1a31
27,357
import bio_utils.bio as bio import tqdm def get_bitseq_estimates( config, isoform_strategy, bitseq_id_field='transcript_id', strings_to_remove=['.cds-only', '.merged']): """ Load the bitseq abundance estimates into a single long data frame. Parameters ---------- config...
93738faf48d82c6989411c3034271da1224490b0
27,358
from pathlib import Path def na_layout(na_layout_path: Path) -> ParadigmLayout: """ Returns the parsed NA layout. """ with na_layout_path.open(encoding="UTF-8") as layout_file: return ParadigmLayout.load(layout_file)
35e8405b5e17ab4da917d48ef89779c7d081791e
27,359
def mean_allcnnc(): """The all convolution layer implementation of torch.mean().""" # TODO implement pre forward hook to adapt to arbitary image size for other data sets than cifar100 return nn.Sequential( nn.AvgPool2d(kernel_size=(6, 6)), flatten() )
f607750c5a05eba77999f54b8ed59f2af2ea1d12
27,360
def load_atomic_data_for_training(in_file, categories, tokenizer, max_input_length, max_output_length): """ Loads an ATOMIC dataset file and :param in_file: CSV ATOMIC file :param categories: ATOMIC category list :param tokenizer: LM tokenizer :return: a list of tuples """ examples = loa...
e47916d61dae92bdbe3cc8ccf8a06299878f1814
27,361
def md5s_loaded(func): """Decorator which automatically calls load_md5s.""" def newfunc(self, *args, **kwargs): if self.md5_map == None: self.load_md5s() return func(self, *args, **kwargs) return newfunc
9eba943b939c484280b6dca79cf79fc04337f0ab
27,362
def is_dap_message(message: str) -> bool: """Checks if a message contains information about some neighbour DAP.""" if "DAP" in message: return True return False
01294888ab5cac7560fb7c58669f14573e0c1acd
27,363
import random def PhotoMetricDistortion( img, brightness_delta=32, contrast_range=(0.5, 1.5), saturation_range=(0.5, 1.5), hue_delta=18): """Apply photometric distortion to image sequentially, every dictprocessation is applied with a probability of 0.5. The position of ...
04b371ec269d1ea52e7689726fe63b158bb53e11
27,364
from typing import Optional import functools def sharded_adafactor( learning_rate_fn: optax.Schedule, weight_decay: Optional[float] = None, layerwise_adaptation: bool = False, decay_method: str = '', decay_adam: float = 0., decay_pow: float = 0., beta1: float = 0., clipping_threshold: ...
1b90507a8fa78e9d13a0f030e7a11cac25aee524
27,365
def make_game(): """Builds and returns an Apprehend game.""" return ascii_art.ascii_art_to_game( GAME_ART, what_lies_beneath=' ', sprites={'P': PlayerSprite, 'b': BallSprite}, update_schedule=['b', 'P'],nb_action=2)
9e6b1ead4ec65083ffe00c5e8708bd174c7eaf79
27,366
import psutil import os import sys def get_system_memory(): """Return the total amount of system memory in bytes. Returns: The total amount of system memory in bytes. """ # Try to accurately figure out the memory limit if we are in a docker # container. Note that this file is not specific...
a9bcde327495cf48a471c42855fc62f39e68fa5b
27,367
from typing import Any from typing import Tuple def process_makefile( data: Any, specification: Any, path: Tuple[str, ...] = (), apply_defaults: bool = True, ) -> Any: """Validates a makefile and applies defaults to missing keys. Note that that default values are deep-copied before being set....
6d4d114b59c22c36414a3c4e0f232dc7782802f1
27,368
def load_fashion(n_data=70000): """Fetches the fashion MNIST dataset and returns its desired subset. Args: n_data (int, optional): The size of the wanted subset. Defaults to 70000. Returns: tuple: The dataset, the labels of elements, the names of categories and the name of the dataset. ...
ed09938ad8c776f11029f6eaecb4f5a01cbf2fed
27,369
from matplotlib.animation import Animation import os import re def matplotlib_scraper_multi(block, block_vars, gallery_conf, **kwargs): """Scrape Matplotlib images, but with both high and low-def... Parameters ---------- block : tuple A tuple containing the (label, content, line_number) of th...
d1684402ba359653dc8d77cd57e189cb9592d9b2
27,370
def add_countdown_ago(date, event, events_dates_per_event): """ Given a date and an even, compute the number of days since the previous occurence of this events within events_dates_per_event """ countdown = [] for special_date in events_dates_per_event[event]: date_count_down = (special_...
3ced21ad6b53007e8777d245dee4fb84f83a3086
27,371
import json import sys def get_groups_from_json(json_definitions): """Return a dict of tango.Group objects matching the JSON definitions. Extracts the definitions of groups of devices and builds up matching tango.Group objects. Some minimal validation is done - if the definition contains nothing the...
8d1f741448764236705a06d72d960f6e3b160c41
27,372
def _get_indexed_role(dep): """Return the function (governor/dependent) and role based on the dependency relation type.""" gram_relation = dep['@type'][0:5] if gram_relation in ["conj", "conj_"]: return (-1, 'conj') (function, role) = _relation_map[gram_relation] return (_iminus_one...
46edb717174f4267414604c362c22134265ceca4
27,373
def aug_op_mul_col(aug_input: Tensor, mul: float) -> Tensor: """ multiply each pixel :param aug_input: the tensor to augment :param mul: the multiplication factor :return: the augmented tensor """ input_tensor = aug_input * mul input_tensor = aug_op_clip(input_tensor, clip=(0, 1)) re...
42e7d1596a7417ca7d981573ffaac9dccff49490
27,374
import math def example3(path: str): """Planetary orbit""" print(f"\n{Col.TITL}{' Example 3 ':-^79}{Col.RES}\n") if not path: path = "qr_data/ex3.txt" file = open(path, "r") ls = file.readlines() # Read input data from `file` m = int(ls[0].replace("\n", "")) data = np.zeros((m...
aebe5d23d3d1080ce6795ba6e292ee4d973360a5
27,375
def drones_byDroneId_patch(droneId): """ Update the information on a specific drone It is handler for PATCH /drones/<droneId> """ return handlers.drones_byDroneId_patchHandler(droneId)
93f66abc182ff4df3b3ad06bb8cdd38d19ab8e01
27,376
def load_drop_columns(df, targets, file): """ Loads a dataframe with only a subset of the columns TODO: we probably need to delete this because this exists: df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields) #https://stackoverflow.com/questions/26063231/read-specific-columns-with-pa...
c9218bbf22ae1429f5f7134e1e53fd85fd9d422e
27,377
def get_categories(categories_file): """ Group categories by image """ # map each category id to its name id_to_category = {} for category in categories_file['categories']: id_to_category[category['id']] = category['name'] image_categories = {} for category in categories_file['annot...
10377ea688c2e33195f137cc9470cadd6eb2b9e7
27,378
from typing import Callable from datetime import datetime def get_profit_forecast(code: str, getter: Callable[[str], pd.DataFrame] = rdb.get_profit_forecast): """ 获取分析师的盈利预期 """ today = datetime.datetime.now().strftime('%Y-%m-%d') return getter(today).loc[code].to_dict()
1e2499eb785e1e4e50b6d82a2c3a4eea7b297a0d
27,379
import functools def checkpoint_wrapper(module: nn.Module, offload_to_cpu: bool = False) -> nn.Module: """ A friendlier wrapper for performing activation checkpointing. Compared to the PyTorch version, this version: - wraps an nn.Module, so that all subsequent calls will use checkpointing - handl...
63d8f20265d2ade29e35ad5ae38b85e5a7f5f8af
27,380
def get_L_star_CS_d_t_i(L_CS_d_t_i, Q_star_trs_prt_d_t_i, region): """(9-2)(9-2)(9-3) Args: L_CS_t_i: 日付dの時刻tにおける暖冷房区画iの1時間当たりの冷房顕熱負荷(MJ/h) Q_star_trs_prt_d_t_i: 日付dの時刻tにおける暖冷房区画iの1時間当たりの熱損失を含む負荷バランス時の非居室への熱移動(MJ/h) region: 地域区分 L_CS_d_t_i: returns: 日付dの時刻tにおける暖冷房区画iの1時間当たりの熱損失を含む負荷バランス...
2d679123b10d4c5206253a9a7a4aadfb14fc77da
27,381
def delete(isamAppliance, name, check_mode=False, force=False): """ Delete an Authentication Mechanism """ ret_obj = search(isamAppliance, name, check_mode=check_mode, force=force) mech_id = ret_obj['data'] if mech_id == {}: logger.info("Authentication Mechanism {0} not found, skipping ...
4deb3c1362010d59abc39868f0b5fef8b4ddaa2f
27,382
def point_to_line_cluster_distance(point, line_cluster): """ Distance between a single point and a cluster of lines """ return val_point_to_line_cluster_distance(point.value, np.array([l.value for l in line_cluster]))
082ba543895e6bf25d013df6d94954de93468754
27,383
import time def str_time_prop(start, end, date_format, prop): """Get a time at a proportion of a range of two formatted times. start and end should be strings specifying times formated in the given format (strftime-style), giving an interval [start, end]. prop specifies how a proportion of the interv...
6ce9a7ec5afd41df43ce029ed7391150f42b8d8a
27,384
def parse_fields(flds): """Parse Data Dictionary XML Fields Arguments: flds -- XML document element for fields """ fields_dict = dict() for elem in flds: elem_tag = str(elem.tag).strip() if elem_tag.lower() != FIELD_TAG.lower(): raise ValueError(elem_tag + " elem...
c3057f2dc3ff525564589024ec75a58bab0a3331
27,385
import json def analyse_json_data(input_file_path): """ :type input_file_path: str :rtype: InputData :raise FileNotFoundError """ data = InputData() try: with open(input_file_path, 'r') as input_file: json_data = json.load(input_file) except FileNotFoundError as e:...
fe4eef01d2fe14f920a1bf64687410ef9d8e13d9
27,386
import math def process_datastore_tweets(project, dataset, pipeline_options): """Creates a pipeline that reads tweets from Cloud Datastore from the last N days. The pipeline finds the top most-used words, the top most-tweeted URLs, ranks word co-occurrences by an 'interestingness' metric (similar to on tf* id...
db60b67d85f2d703e8cf46f5d89d56d8c9cfcbed
27,387
def unpack_uid(uid): """ Convert packed PFile UID to standard DICOM UID. Parameters ---------- uid : str packed PFile UID as a string Returns ------- uid : str unpacked PFile UID as string """ return ''.join([str(i-1) if i < 11 else '.' for pair in [(ord(c) >> 4...
cb131f3df386c40382cf70ddee5125f901de5fa8
27,388
def command(name=None): """A decorator to register a subcommand with the global `Subcommands` instance. """ def decorator(f): _commands.append((name, f)) return f return decorator
89dd62a97ce6af317dbb2d33273fa215d740deab
27,389
def agse_convert(invec, swdata, insys='gse'): """Convert between GSE and aberrated GSE Using common definiton, e.g., Schwartz 1998 (S.J. Schwartz, "Shock and Discontinuity Normals, Mach Numbers, and Related Parameters", In: Analysis Methods for Multi-Spacecraft Data, Eds.: G. Paschmann and P. Daly, ...
3d5d77565187e9242104d8b25260b86458109701
27,390
import numpy as np def parse_geom_text_output(out_lines, input_dict=None): """ Parse output of .geom file :param out_lines: a list of lines from the readline function :param input_dict: not in use at the moment :return parsed_data: key, value of the trajectories of cell, atoms, force etc ...
a01ba11130d91aa2211563322384e772dfe7ad1a
27,391
def evalKnapsackBalanced(individual): """ Variant of the original weight-value knapsack problem with added third object being minimizing weight difference between items. """ weight, value = evalKnapsack(individual) balance = 0.0 for a,b in zip(individual, list(individual)[1:]): balance +...
2037e6b33d4cd8c76496b8fbb866febbf355aaac
27,392
import os def read_links(ls): """Returns list of objects with source and target""" return list(map(lambda el: {"source": el, "target": os.readlink(el)}, ls))
9768106043c706ed37b90de9289325f0574096db
27,393
def complexify_module(lines_in): """ Complexify a module by separating its derived types, functions, and subroutines and passing them through a line complexification function. Parameters ---------- lines_in : list of string List of strings source code for one module to be complexified ...
dfa30e883c2addeb1e3e5ac0c84be4f7d7834277
27,394
from datetime import datetime import pytz def utc_right_now(): """ Returns a datetime object reflecting the time in UTC as of when this function was called. """ return datetime.datetime.now(tz=pytz.utc).replace(tzinfo=None)
870eff5c5f744b8d3e84a21f00adc48bae088221
27,395
def process_img_border(img_array, polygon_pts, border=6): """Process Raw Data into Args: img_array (numpy array): numpy representation of image. polygon_pts (array): corners of the building polygon. Returns: numpy array: . """ heigh...
7ad98cc9e66e34849a534a42e3d78062e1b779c4
27,396
from typing import Dict from typing import Any def async_flow_poll(destination: Text, batch_id: Text) -> Dict[Text, Any]: """Repeatedly checks on the status of the batch, and returns the result after the processing has been completed. Args: destination (Text): This is the destination parsed ...
e0816d6c7bb2f841a5878f55781329844d5b4ce9
27,397
from typing import Optional from typing import Mapping def get_connection(arn: Optional[str] = None, tags: Optional[Mapping[str, str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetConnectionResult: """ Provides details about CodeStar Connection. ...
76494278cfd1ec4adf3ecd90d8f5536f545a814f
27,398
from typing import Counter def generate_samples(n_samples, func, *args, **kwargs): """Call a function a bunch of times and count the results. Args: n_samples: Number of time to call the function. func: The function results are counted from. *args **args: The arguments to pass ...
625c2bf6713420e26704d2c2842504343be09434
27,399