content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def load_empty_config_setup() -> DictConfig: """Return a dictionary containing all the MLOQ setup config values set to None.""" return OmegaConf.load(setup_yml.src)
e862fb753737990a23975659f7c026ca0a2e7132
27,280
from typing import Dict from typing import Tuple def apply_dfg(dfg: Dict[Tuple[str, str], int], start_activities: Dict[str, int], end_activities: Dict[str, int], activities: Dict[str, int], parameters=None, variant=DEFAULT_VARIANT_DFG) -> Tuple[PetriNet, Marking, Marking]: """ Apply the chosen IM algorithm to...
644b871c17bcf983067754588be54aecf20c5c40
27,281
def make_extrap_log_func(func, extrap_x_l=None): """ Generate a version of func that extrapolates to infinitely many gridpoints. Note that extrapolation here is done on the *log* of the function result, so this will fail if any returned values are < 0. It does seem to be better behaved for SFS calc...
1ddac8d607b18cb3f392ac9a06ccfcc2608617d4
27,282
def get_logger(name): """每次调用,都是一个新的 """ return LogCollector(name)
81cb8ad13bbf54ada444cc624b7fc521b2cb8943
27,283
from re import T def ShowString(name, msg): """Return a html page listing a file and a 'back' button""" return """ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> <html> <head> <title>%s</title> </head> <body> <FORM><INPUT TYPE="BUTTON" VALUE="%s" ONCLICK="history.go(-1)"></FORM> ...
4f1c837989c18180991dcfb6ecb93025d8a6c27d
27,284
def game_loop(screen, buttons, items, music, sound, g_settings, particles=None, percentthing=None): """Manage events, return a gamestate change if it happens, and update the screen""" while True: # Check and manage event queue gs_change = gf.check_events(buttons, music, sound, g_settings) ...
0fcd40402859bca8671a2856a9872bcd7fb6008e
27,285
def fake_request(method, url, **kwargs): """Constructs and sends a :class:`Request <Request>`. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Requ...
a2a1cd19fc657d2e0cece37954735d9c66e877c5
27,286
from typing import List from typing import Dict from typing import Any from typing import OrderedDict def assert_step_match( step: Step, expected_step_func: str, expected_step_arguments: List[Dict[str, Any]], step_registry: StepRegistry, ): """Assert that the Step correctly matches in the Registry...
0b156e6f7a1bf39b6fcc7805f0dcb9da30768e58
27,287
from typing import List from typing import Dict import requests def get_grafana_dashboards_url(admin: bool) -> List[Dict]: """ Get a list of dashboard available to the tenant. :admin (bool) A boolean representing admin status. Return a list of dashboards dictionaries. """ urls = [] req =...
0b28b9ef1333c633a001297f9c038fd5496952a8
27,288
def validate_comma_separated_list(argument): """Convert argument to a list.""" if not isinstance(argument, list): argument = [argument] last = argument.pop() items = [i.strip(u' \t\n') for i in last.split(u',') if i.strip(u' \t\n')] argument.extend(items) return argument
bdf68db95d6070be4ffb5a74a646f5c730c726b4
27,289
def get_view(brain): """Setup for view persistence test""" fig = brain._figures[0][0] if mlab.options.backend == 'test': return fig.scene.camera.parallel_scale = 50 assert fig.scene.camera.parallel_scale == 50 view, roll = brain.show_view() return fig.scene.camera.parallel_scale, vie...
72295348921668e309aed5ac7c281dae7dea292a
27,290
def model_description(formula): """Interpret model formula and obtain a model description. This function receives a string with a formula describing a statistical model and returns an object of class ModelTerms that describes the model interpreted from the formula. Parameters ---------- fo...
fad391e86b31108694c3a784101ad8686f8b3292
27,291
def eintragen_kaeufe(kliste, id_zu_objekt, id_zu_profil): """ bekommt eine Liste von dicts mit dem Inhalt von je einer Zeile der registration-Tabelle der alten db. Außerdem ein mapping der produkt_id der alten db zu model-Instanzen der neuen. Trägt entsprechende Käufe ein und gibt dict produkt_id -> mo...
68da4934335fefd64ffbfb9200afa81976037332
27,293
from datetime import datetime def update_status(payload: Something, context: EventContext) -> Something: """ Updates status of payload to PROCESSED and puts previous status in history. :param payload: Something, object :param context: EventContext """ logger.info(context, "updating something ...
7dbcec5930e657dfc3e654c4d1c8c970e9947906
27,294
def get_holdout_set(train, target_column): """This is a sample callable to demonstrate how the Environment's `holdout_dataset` is evaluated. If you do provide a callable, it should expect two inputs: the train_dataset (pandas.DataFrame), and the target_column name (string). You should return two DataFrames:...
ba2ea647c287f11f37bc4557ef389ed288b0bb02
27,295
def field_type(value): """Return the type of the field, using the Ref object""" if isinstance(value, Ref): return "RefValue" else: return "StringValue"
f3165d87ecef0f13214e98856a10851061aea4f6
27,296
import torch def test_read_covars_manual_input(tmp_observe_class, covar_details_mapped_covar_mapped_names_tmp_observe_class, additional_text, monkeypatch): """ test reading of covars from manual input by user. Monkeypatches reliance on functi...
46c62f0350edbecd001040b5c431862377b9afe8
27,297
def remove_overlapping_squares_v2(squares_dict, array_type): """ removes squares with min_x and min_y that are both within 40 pixels of each other :param squares_dict: dict with overlapping squares :param array_type: "Air_100" is the only one currently supported :return: dict of squares and datafram...
5f13cda913ece68c0402e5c5aa003bffed50b0cd
27,298
def depth_to_space(x, scale, use_default=False): """Depth to space function.""" if use_default: out = tf.depth_to_space(x, scale) else: b, h, w, c = list(map(int, x.shape)) out = tf.reshape(x, [b, h, w, scale, scale, -1]) out = tf.transpose(out, [0, 1, 3, 2, 4, 5]) ou...
1c6f8c55fd9f7371ca7e69d91db44b86ffb81d45
27,299
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
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
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
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
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_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
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 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 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
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
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 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 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
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
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
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
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 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
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 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