content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def quasi_diagonalize(link): """sort clustered assets by distance""" link = link.astype(int) sort_idx = pd.Series([link[-1, 0], link[-1, 1]]) num_items = link[-1, 3] # idx of original items while sort_idx.max() >= num_items: sort_idx.index = list(range(0, sort_idx.shape[0] * 2, 2)) # make ...
8f10f62d5f0b3dc7b8687134497dd42f183194b4
20,552
def keyword(variable): """ Verify that the field_name isn't part of know Python keywords :param variable: String :return: Boolean """ for backend in ADAPTERS: if variable.upper() in ADAPTERS[backend]: msg = ( f'Variable "{variable}" is a "{backend.upper()}" ' ...
b1c6322d3ce3c9ee4bda4eff251af44ca3e2c699
20,554
import logging import json def gcp_api_main(request): """Responds to any HTTP request. Args: request (flask.Request): HTTP request object. Returns: The response text or any set of values that can be turned into a Response object using `make_response <http://flask.pocoo.org/...
21ec4b1dba4ad6f5dac518a3907cd15579a0ba00
20,555
def box_area_3d(boxes: Tensor) -> Tensor: """ Computes the area of a set of bounding boxes, which are specified by its (x1, y1, x2, y2, z1, z2) coordinates. Arguments: boxes (Union[Tensor, ndarray]): boxes for which the area will be computed. They are expected to be in (x1, y1, ...
be8b3c4d58d301d2044e7cfe2844516933c1247f
20,556
from sqlalchemy import create_mock_engine import re def mock_engine(dialect_name=None): """Provides a mocking engine based on the current testing.db. This is normally used to test DDL generation flow as emitted by an Engine. It should not be used in other cases, as assert_compile() and assert_sq...
d773a6e2cd0b2060e5dd66d5ec4e758ac7f1f504
20,557
def get_feedback_thread_reply_info_by_reply_to_id(reply_to_id): """Gets the domain object corresponding to the model which is fetched by reply-to-id field. Args: reply_to_id: str. The reply_to_id to search for. Returns: FeedbackThreadReplyInfo or None. The corresponding domain object. ...
e27521030717a1dc15cd9e678dabafba86007f90
20,558
def _cross_correlations(n_states): """Returns list of crosscorrelations Args: n_states: number of local states Returns: list of tuples for crosscorrelations >>> l = _cross_correlations(np.arange(3)) >>> assert l == [(0, 1), (0, 2), (1, 2)] """ l = n_states cross_corr =...
c11c5655ba655a29991421c6627a3eaca4f7681d
20,559
def select_interface(worker): """ It gets a worker interface channel to do something. """ interfaces = worker.interfaces_list() if len(interfaces) == 0: print ' Error. Worker without interface known.' return -1 elif len(interfaces) == 1: return 1 option = raw_input('...
97d90670dd69d57b4e1f85df250a0abc56106fb6
20,560
def get_middle(arr): """ Get middle point ???? """ n_val = np.array(arr.shape) / 2.0 n_int = n_val.astype(np.int0) # print(n_int) if n_val[0] % 2 == 1 and n_val[1] % 2 == 1: return arr[n_int[0], n_int[1]] if n_val[0] % 2 == 0 and n_val[1] % 2 == 0: return np.average(arr[...
9651bcadc991bbf7a0c635a8870356f422d43e7e
20,561
def annotate_segmentation(image, segmentation): """Return annotated segmentation.""" annotation = AnnotatedImage.from_grayscale(image) for i in segmentation.identifiers: region = segmentation.region_by_identifier(i) color = pretty_color() annotation.mask_region(region.border.dilate()...
2fadbe8d2339e37bea0dbfe054199002a3997b20
20,562
def get_champ_data(champ: str, tier: int, rank: int): """ Gives Champ Information by their champname, tier, and rank. """ champ_info = NewChampsDB() try: champ_info.get_data(champ, tier, rank) champs_dict = { "name": f"{champ_info.name}", "released": champ_i...
7d810fc5ced3d187c68533f42c2443ef8bec651b
20,563
def serving_input_receiver_fn(): """This is used to define inputs to serve the model. Returns: A ServingInputReciever object. """ csv_row = tf.placeholder(shape=[None], dtype=tf.string) features, _ = _make_input_parser(with_target=False)(csv_row) return tf.estimator.export.ServingInputReceiver(features...
bcc6f0c4050d40df114ba4e5d895524f736b463a
20,565
import time def offsetTimer(): """ 'Starts' a timer when called, returns a timer function that returns the time in seconds elapsed since the timer was started """ start_time = time.monotonic() def time_func(): return time.monotonic() - start_time return time_func
348105a408ccedd1fcb840b73d5a58dfd59dd8cc
20,566
from typing import Callable import functools def find_resolution(func: Callable = None) -> Callable: """Decorator that gives the decorated function the image resolution.""" @functools.wraps(func) def wrapper(self: MultiTraceChart, *args, **kwargs): if 'width' not in kwargs: kwargs['wi...
70edffcec5ac772bd52cb819db589d26497fda87
20,568
def transform_spikes_to_isi(self, spikes, time_epoch, last_event_is_spike=False): """Convert spike times to data array, which is a suitable format for optimization. Parameters ---------- spikes : numpy array (num_neuron,N), dtype=np.ndarray A sequence of spike times for each neuron on each tri...
cc2b54e80e00b10b8cabf79093509fde1980b804
20,569
def api_github_v2(user_profile, event, payload, branches, default_stream, commit_stream, issue_stream, topic_focus = None): """ processes github payload with version 2 field specification `payload` comes in unmodified from github `default_stream` is set to what `stream` is in v1 above `commit_stream...
bed307903d7ddcce216919d18accb3ecfd94937d
20,570
from typing import Iterable from typing import Optional from typing import Callable from typing import Dict def concatenate( iterable: Iterable[Results], callback: Optional[Callable] = None, modes: Iterable[str] = ("val", "test"), reduction: str = "none", ) -> Results: """Returns a concatenated Re...
6833a50ddc84d44c942c6e85c1ebbdb793bd78a9
20,571
def parse_version(s: str) -> tuple[int, ...]: """poor man's version comparison""" return tuple(int(p) for p in s.split('.'))
445cd029efa3c8d4331e916f9925daddbc277ada
20,572
def replay_train(DQN, train_batch): """ ์—ฌ๊ธฐ์„œ train_batch๋Š” minibatch์—์„œ ๊ฐ€์ ธ์˜จ data๋“ค์ž…๋‹ˆ๋‹ค. x_stack์€ state๋“ค์„ ์Œ“๋Š” ์šฉ๋„๋กœ์ด๊ณ , y_stack์€ deterministic Q-learning ๊ฐ’์„ ์Œ“๊ธฐ ์œ„ํ•œ ์šฉ๋„์ž…๋‹ˆ๋‹ค. ์šฐ์„  ์Œ“๊ธฐ์ „์— ๋น„์–ด์žˆ๋Š” ๋ฐฐ์—ด๋กœ ๋งŒ๋“ค์–ด๋†“๊ธฐ๋กœ ํ•˜์ฃ . """ x_stack = np.empty(0).reshape(0, DQN.input_size) # array(10, 4) y_stack = np.empty(0).reshape(0, DQN.output_size) # arr...
05b85aab223b82637a23853d15cd8e073ecca845
20,573
def make_reverse_macro_edge_name(macro_edge_name): """Autogenerate a reverse macro edge name for the given macro edge name.""" if macro_edge_name.startswith(INBOUND_EDGE_FIELD_PREFIX): raw_edge_name = macro_edge_name[len(INBOUND_EDGE_FIELD_PREFIX) :] prefix = OUTBOUND_EDGE_FIELD_PREFIX elif ...
807efcc26fb21e553241b2de4d2c6633a24548a2
20,574
def unescaped_split(pattern, string, max_split=0, remove_empty_matches=False, use_regex=False): """ Splits the given string by the specified pattern. The return character (\\n) is not a natural split pattern (if you don't specif...
5a5cec1a54b94840e13ddec3ca8796a73e908898
20,575
def citation_distance_matrix(graph): """ :param graph: networkx graph :returns: distance matrix, node labels """ sinks = [key for key, outdegree in graph.out_degree() if outdegree==0] paths = {s: nx.shortest_path_length(graph, target=s) for s in sinks} paths_df = pd.DataFrame(paths)#, index...
b3c41164c2081704b3b36ce0c5b1ca55440a88be
20,576
from typing import IO def read_into_dataframe(file: IO, filename: str = "", nrows: int = 100,max_characters: int = 50) -> pd.DataFrame: """Reads a file into a DataFrame. Infers the file encoding and whether a header column exists Args: file (IO): file buffer. filename (str): filename. Used...
fe95c60870779353f2aa751c20ed331a2e0156bf
20,577
from typing import OrderedDict import torch def Navigatev0_action_to_tensor(act: OrderedDict, task=1): """ Creates the following (batch_size, seq_len, 11) action tensor from Navigatev0 actions: 0. cam left 1. cam right 2. cam up 3. cam down 4. place + jump 5. place 6...
39d481d2e8597902b18695de97f041606f24f035
20,579
def asfarray(a, dtype=mstype.float32): """ Similar to asarray, converts the input to a float tensor. If non-float dtype is defined, this function will return a float32 tensor instead. Args: a (Union[int, float, bool, list, tuple, numpy.ndarray]): Input data, in any form that can be...
4da49b2bcab9686b2757cf1b9066c21876f992e6
20,580
from typing import Optional from typing import Callable import click def _verify_option(value: Optional[str], value_proc: Callable) -> Optional[str]: """Verifies that input value via click.option matches the expected value. This sets ``value`` to ``None`` if it is invalid so the rest of the prompt can fl...
4d0f58827982924a9d027112ffa3aaeef7634fe8
20,581
def batch_jacobian(output, inp, use_pfor=True, parallel_iterations=None): """Computes and stacks jacobians of `output[i,...]` w.r.t. `input[i,...]`. e.g. x = tf.constant([[1, 2], [3, 4]], dtype=tf.float32) y = x * x jacobian = batch_jacobian(y, x) # => [[[2, 0], [0, 4]], [[6, 0], [0, 8]]] ...
dd42fcc9542bba8033a1eb204bf0d3a91b192dbc
20,582
def declare(baseFamily=None, baseDefault=0, derivedFamily=None, derivedDefault=""): """ Declare a pair of components """ # the declaration class base(pyre.component, family=baseFamily): """a component""" b = pyre.properties.int(default=baseDefault) class derived(base, family=der...
30c8d8f7d264a0e908f4305198b07c3d76a3cfac
20,583
from datetime import datetime def parse_iso8601(dtstring: str) -> datetime: """naive parser for ISO8061 datetime strings, Parameters ---------- dtstring the datetime as string in one of two formats: * ``2017-11-20T07:16:29+0000`` * ``2017-11-20T07:16:29Z`` """ return...
415a4f3a9006109e31ea344cf99e885a3fd2738d
20,584
def CalcCurvature(vertices,faces): """ CalcCurvature recives a list of vertices and faces and the normal at each vertex and calculates the second fundamental matrix and the curvature by least squares, by inverting the 3x3 Normal matrix INPUT: vertices -nX3 array of vertices faces -mX3 a...
b0e31073fe8aff61e60d0393098cca390bb95708
20,585
from typing import Optional def query_abstracts( q: Optional[str] = None, n_results: Optional[int] = None, index: str = "agenda-2020-1", fields: list = ["title^2", "abstract", "fullname", "institution"], ): """ Query abstracts from a given Elastic index q: str, query n_results: int, n...
4ed554231c863c3164c5368978da900e3647570d
20,586
import typing import pickle def PretrainedEmbeddingIndicesDictionary() -> typing.Dict[str, int]: """Read and return the embeddings indices dictionary.""" with open(INST2VEC_DICITONARY_PATH, "rb") as f: return pickle.load(f)
d4c0c8f5d7c83d99927342c5cacd8fd80a4f7d56
20,587
def color_negative_red(val): """ Takes a scalar and returns a string with the css property `'color: red'` for negative strings, black otherwise. """ color = 'red' if val < 0 else 'black' return 'color: %s' % color
1806af9c915740612a6a11df723f1439c73bde2f
20,588
def get_student_discipline(person_id: str = None): """ Returns student discipline information for a particular person. :param person_id: The numeric ID of the person you're interested in. :returns: String containing xml or an lxml element. """ return get_anonymous('getStudentDiscipline', perso...
4e96fb4e9d566af7094b16b29540617bbb230f67
20,590
from re import X def dot(p1, p2): """ Dot product :param p1: :param p2: :return: """ return p1[X] * p2[X] + p1[Y] * p2[Y]
13ba17e8757ebf9022f07d21b58a26376520f84a
20,592
def logout(): """View function which handles a logout request.""" tf_clean_session() if current_user.is_authenticated: logout_user() # No body is required - so if a POST and json - return OK if request.method == "POST" and _security._want_json(request): return _security._render_jso...
0343be8ec063b5c215a0a019003cbf137588171a
20,593
def splinter_session_scoped_browser(): """Make it test scoped.""" return False
a7587f6edff821bab3052dca73929201e98dcf56
20,595
from typing import Counter def sample_mask(source, freq_vocab, threshold=1e-3, min_freq=0, seed=None, name=None): """Generates random mask for downsampling high frequency items. Args: source: string `Tensor` of any shape, items to be sampled. freq_vocab: `Counter` with frequencies vocabulary....
30fca98f95ac7a6aa2f3a3576f32abf271a693bb
20,596
def _xList(l): """ """ if l is None: return [] return l
ef09d779c7ebc2beb321d90726f43603c0ac8315
20,597
def IABN2Float(module: nn.Module) -> nn.Module: """If `module` is IABN don't use half precision.""" if isinstance(module, InplaceAbn): module.float() for child in module.children(): IABN2Float(child) return module
587565ad78afd08d3365f637ab5b98b17e977566
20,598
from datetime import datetime def start_of_day(val): """ Return a new datetime.datetime object with values that represent a start of a day. :param val: Date to ... :type val: datetime.datetime | datetime.date :rtype: datetime.datetime """ if type(val) == date: val = datetime.fr...
74e302513edf428f825f9e24567e23b3a5e5d4f5
20,599
def pending_mediated_transfer(app_chain, token_network_identifier, amount, identifier): """ Nice to read shortcut to make a LockedTransfer where the secret is _not_ revealed. While the secret is not revealed all apps will be synchronized, meaning they are all going to receive the LockedTransfer message. ...
82ae40ffa45a759f1aac132c3edc221ebd11ae9e
20,600
def get_comments(post, sort_mode='hot', max_depth=5, max_breadth=5): """ Retrieves comments for a post. :param post: The unique id of a Post from which Comments will be returned. :type post: `str` or :ref:`Post` :param str sort_mode: The order that the Posts will be sorted by. Options are: "top...
333009358f622560135e7e239741613356387d55
20,601
def neighbor_json(json): """Read neighbor game from json""" utils.check( json['type'].split('.', 1)[0] == 'neighbor', 'incorrect type') return _NeighborDeviationGame( gamereader.loadj(json['model']), num_neighbors=json.get('neighbors', json.get('devs', None)))
19891d59970610ad412fd4eb204477c96d1d82fd
20,602
def get_b16_config(): """Returns the ViT-B/16 configuration.""" config = ml_collections.ConfigDict() config.name = 'ViT-B_16' config.half_precision = True config.encoder = ml_collections.ConfigDict() config.encoder.patches = ml_collections.ConfigDict({'size': (16, 16)}) config.encoder.hidden_size = 768 ...
6afdb862bd07c21d569db65fbb1780492ff153f2
20,603
from typing import Container def build_container_hierarchy(dct): """Create a hierarchy of Containers based on the contents of a nested dict. There will always be a single top level scoping Container regardless of the contents of dct. """ top = Container() for key,val in dct.items(): if...
7fb629d7f570e5f77b381766b5c2d909d7c0d6c1
20,604
def occ_frac(stop_rec_range, bin_size_minutes, edge_bins=1): """ Computes fractional occupancy in inbin and outbin. Parameters ---------- stop_rec_range: list consisting of [intime, outtime] bin_size_minutes: bin size in minutes edge_bins: 1=fractional, 2=whole bin Returns ------- ...
d3d93cd92386a98c865c61ad2b595786aa5d4837
20,605
def geomprogr_mesh(N=None, a=0, L=None, Delta0=None, ratio=None): """Compute a sequence of values according to a geometric progression. Different options are possible with the input number of intervals in the sequence N, the length of the first interval Delta0, the total length L and the ratio of the so...
3de67b8ee2d75b69638648316fcfad07dbabde3a
20,606
def list_subclasses(package, base_class): """ Dynamically import all modules in a package and scan for all subclasses of a base class. `package`: the package to import `base_class`: the base class to scan for subclasses return: a dictionary of possible subclasses with class name as key and class typ...
e5570c30c89869b702c1c1015914540403be356f
20,607
def maxima_in_range(r, g_r, r_min, r_max): """Find the maxima in a range of r, g_r values""" idx = np.where(np.logical_and(np.greater_equal(r, r_min), np.greater_equal(r_max, r))) g_r_slice = g_r[idx] g_r_max = g_r_slice[g_r_slice.argmax()] idx_max, _ = find_nearest(g_r, g_r_max) return r[idx_ma...
14a4e3dc65465dd2e515ac09fb74704a366368b4
20,608
def shared_fit_preprocessing(fit_class): """ Shared preprocessing to get X, y, class_order, and row_weights. Used by _materialize method for both python and R fitting. :param fit_class: PythonFit or RFit class :return: X: pd.DataFrame of features to use in fit y: pd.Series of target...
b87831540ba6fc4bc65fe0532e2af0574515c3a3
20,609
import json def webhook(): """ Triggers on each GET and POST request. Handles GET and POST requests using this function. :return: Return status code acknowledge for the GET and POST request """ if request.method == 'POST': data = request.get_json(force=True) log(json.dumps(data)) ...
0c9f39c1159990e6a84dc9ce0091078397a3b65e
20,610
def extract_winner(state: 'TicTacToeState') -> str: """ Return the winner of the game, or announce if the game resulted in a tie. """ winner = 'No one' tictactoe = TicTacToeGame(True) tictactoe.current_state = state if tictactoe.is_winner('O'): winner = 'O' elif tictactoe.is_...
c92cef3bc3214923107871d5f044df16baf63401
20,611
def _prensor_value_fetch(prensor_tree: prensor.Prensor): """Fetch function for PrensorValue. See the document in session_lib.""" # pylint: disable=protected-access type_spec = prensor_tree._type_spec components = type_spec._to_components(prensor_tree) def _construct_prensor_value(component_values): return...
ccea4a94fff5f17c6e650e1ac820ec6da1be023d
20,612
def request_validation_error(error): """Handles Value Errors from bad data""" message = str(error) app.logger.error(message) return { 'status_code': status.HTTP_400_BAD_REQUEST, 'error': 'Bad Request', 'message': message }, status.HTTP_400_BAD_REQUEST
1d5c779286d83d756e1d73201f1274dbec7cf84b
20,614
def all(request): """Handle places list page.""" places = Place.objects.all() context = {'places': places} return render(request, 'rental/list_place.html', context)
d978a4ec22004a1a863e57113639722eaf1f02cf
20,615
def get_key_by_value(dictionary, search_value): """ searchs a value in a dicionary and returns the key of the first occurrence :param dictionary: dictionary to search in :param search_value: value to search for """ for key, value in dictionary.iteritems(): if value == search_value: ...
febad38e70c973de23ce4e1a5702df92860a6c2e
20,616
def _subtract_ten(x): """Subtracts 10 from x using control flow ops. This function is equivalent to "x - 10" but uses a tf.while_loop, in order to test the use of functions that involve control flow ops. Args: x: A tensor of integral type. Returns: A tensor representing x - 10. """ def stop_con...
f2db402e5c98251dc93036be60f02eb88a4d13d9
20,617
def load_fortune_file(f: str) -> list: """ load fortunes from a file and return it as list """ saved = [] try: with open(f, 'r') as datfile: text = datfile.read() for line in text.split('%'): if len(line.strip()) > 0: saved.append(l...
824ddb0bcb34abf597fb317d10fa3eeab99a292e
20,618
def maskStats(wins, last_win, mask, maxLen): """ return a three-element list with the first element being the total proportion of the window that is masked, the second element being a list of masked positions that are relative to the windown start=0 and the window end = window length, and the third bein...
b5d75d2e86f1b21bf35cbc69d360cd1639c5527b
20,619
def dsoftmax(Z): """Given a (m,n) matrix, returns a (m,n,n) jacobian matrix""" m,n=np.shape(Z) softZ=(softmax(Z)) prodtensor=np.einsum("ij,ik->ijk",softZ,softZ) diagtensor=np.einsum('ij,jk->ijk', softZ, np.eye(n, n)) return diagtensor-prodtensor
15296d493608dac1fc9843dd8a7d6eaaf29c4839
20,620
async def vbd_unplug(cluster_id: str, vbd_uuid: str): """Unplug from VBD""" try: session = create_session( _id=cluster_id, get_xen_clusters=Settings.get_xen_clusters() ) vbd: VBD = VBD.get_by_uuid(session=session, uuid=vbd_uuid) if vbd is not None: ret = ...
8b36c55354b35470bceb47ef212aa183be09fad4
20,621
def calculate_age(created, now): """ Pprepare a Docker CLI-like output of image age. After researching `datetime`, `dateutil` and other libraries I decided to do this manually to get as close as possible to Docker CLI output. `created` and `now` are both datetime.datetime objects. """ a...
f2b1a6fc643a78c9a2d3cdd0f497e05c3294eb03
20,622
def Maxout(x, num_unit): """ Maxout as in the paper `Maxout Networks <http://arxiv.org/abs/1302.4389>`_. Args: x (tf.Tensor): a NHWC or NC tensor. Channel has to be known. num_unit (int): a int. Must be divisible by C. Returns: tf.Tensor: of shape NHW(C/num_unit) named ``output...
d10294d7ad180b47c4276e3bb0f43e7ac4a9fa3b
20,623
import re def is_youtube_url(url: str) -> bool: """Checks if a string is a youtube url Args: url (str): youtube url Returns: bool: true of false """ match = re.match(r"^(https?\:\/\/)?(www\.youtube\.com|youtu\.be)\/.+$", url) return bool(match)
97536b8e7267fb5a72c68f242b3f5d6cbd1b9492
20,624
def time_nanosleep(): """ Delay for a number of seconds and nanoseconds""" return NotImplementedError()
9ec91f2ef2656b5a481425dc65dc9f81a07386c2
20,625
import jinja2 def render_series_fragment(site_config): """ Adds "other posts in this series" fragment to series posts. """ series_fragment = open("_includes/posts_in_series.html", "r").read() for post_object in site_config["series_posts"]: print("Generating 'Other posts in this series' fr...
6cf947148af2978e926d51e9007684b9580d2cb0
20,627
def get_class_by_name(name): """Gets a class object by its name, e.g. sklearn.linear_model.LogisticRegression""" if name.startswith('cid.analytics'): # We changed package names in March 2017. This preserves compatibility with old models. name = name.replace('cid.analytics', 'analytics.core') ...
bf52eb8472e63cbb453183b57c5275d592665fc9
20,629
import functools def _single_optimize( direction, criterion, criterion_kwargs, params, algorithm, constraints, algo_options, derivative, derivative_kwargs, criterion_and_derivative, criterion_and_derivative_kwargs, numdiff_options, logging, log_options, erro...
9f349f8e1124da3a2747b3880969a90e76aad52a
20,630
def item_len(item): """return length of the string format of item""" return len(str(item))
7d68629a5c2ae664d267844fc90006a7f23df1ba
20,631
def get_progress_logger(): """Returns the swift progress logger""" return progress_logger
b1c0e8e206e2f051dcb97337dc51d4971fe0aa8b
20,632
def instantiate_me(spec2d_files, spectrograph, **kwargs): """ Instantiate the CoAdd2d subclass appropriate for the provided spectrograph. The class must be subclassed from Reduce. See :class:`Reduce` for the description of the valid keyword arguments. Args: spectrograph (:...
f9961231ead7c3ece5757e5b18dc5620a3492a40
20,634
def quoteattr(s, table=ESCAPE_ATTR_TABLE): """Escape and quote an attribute value. """ for c, r in table: if c in s: s = s.replace(c, r) return '"%s"' % s
7af3e8ed6bfc0c23a957881ca41065d24cb288d5
20,635
def is_numeric(array): """Return False if any value in the array or list is not numeric Note boolean values are taken as numeric""" for i in array: try: float(i) except ValueError: return False else: return True
2ab0bb3e6c35e859e54e435671b5525c6392f66c
20,636
def reductions_right(collection, callback=None, accumulator=None): """This method is like :func:`reductions` except that it iterates over elements of a `collection` from right to left. Args: collection (list|dict): Collection to iterate over. callback (mixed): Callback applied per iteration...
eba2de662a6386d609da8cf3011010ae822c0440
20,637
import math def pelt_settling_time(margin=1, init=0, final=PELT_SCALE, window=PELT_WINDOW, half_life=PELT_HALF_LIFE, scale=PELT_SCALE): """ Compute an approximation of the PELT settling time. :param margin: How close to the final value we want to get, in PELT units. :type margin_pct: float :para...
c8d53d1132bc45278f2c127ed95ce10cfea0498b
20,638
def InstancesOverlap(instanceList,instance): """Returns True if instance contains a vertex that is contained in an instance of the given instanceList.""" for instance2 in instanceList: if InstanceOverlap(instance,instance2): return True return False
634312b7e8d2ce4e36826410fcd1f6c3c06a40ce
20,640
def calc_qm_lea(p_zone_ref, temp_zone, temp_ext, u_wind_site, dict_props_nat_vent): """ Calculation of leakage infiltration and exfiltration air mass flow as a function of zone indoor reference pressure :param p_zone_ref: zone reference pressure (Pa) :param temp_zone: air temperature in ventilation zon...
4d3f4789b3faedf68b9de3b3e6c8f17bcb478a51
20,641
async def ban(bon): """ For .ban command, bans the replied/tagged person """ # Here laying the sanity check chat = await bon.get_chat() admin = chat.admin_rights creator = chat.creator # Well if not (admin or creator): return await bon.edit(NO_ADMIN) user, reason = await get_us...
f79f16c5e2722f576511a528f546a7f87f7e5236
20,642
def read_offset(rt_info): """ ่Žทๅ–ๆ‰€ๆœ‰ๅˆ†ๅŒบ็š„offset :param rt_info: rt็š„่ฏฆ็ป†ไฟกๆฏ :return: offset_msgs ๅ’Œ offset_info """ rt_id = rt_info[RESULT_TABLE_ID] task_config = get_task_base_conf_by_name(f"{HDFS}-table_{rt_id}") if not task_config: return {} try: partition_num = task_confi...
cc890301d4403a7815480ad0b414e16e26283fa7
20,643
def _CalculateElementMaxNCharge(mol,AtomicNum=6): """ ################################################################# **Internal used only** Most negative charge on atom with atomic number equal to n ################################################################# """ Hmol=Chem.AddHs...
f7bd9957c6e958f31cccc2bc20d6651baaf2f5fa
20,644
def check_stability(lambda0, W, mu, tau, dt_max): """Check if the model is stable for given parameter estimates.""" N, _ = W.shape model = NetworkPoisson(N=N, dt_max=dt_max) model.lamb = lambda0 model.W = W model.mu = mu model.tau = tau return model.check_stability(return_value=True)
d417bdba0f236edf5f5c9e17c09e2d2a93bf2b4a
20,646
import re def pid2id(pid): """convert pid to slurm jobid""" with open('/proc/%s/cgroup' % pid) as f: for line in f: m = re.search('.*slurm\/uid_.*\/job_(\d+)\/.*', line) if m: return m.group(1) return None
e7d0ee60d5a8930b8a6f761d5c27451a28b6ec2a
20,647
import copy def multiaxis_scatterplot(xdata, ydata, *, axes_loc, xlabel='', ylabel='', title='', num_cols=1, n...
22d9aa3b0de496c498535b2b4bf663be429b8f48
20,649
import torch def log1p_mse_loss(estimate: torch.Tensor, target: torch.Tensor, reduce: str = 'sum'): """ Computes the log1p-mse loss between `x` and `y` as defined in [1], eq. 4. The `reduction` only affects the speaker dimension; the time dimension is always reduced by a mean operat...
7c67a67dcf6f6d14bb712d5a92b54ea979f7a73c
20,650
def quaternion_inverse(quaternion: np.ndarray) -> np.ndarray: """Return inverse of quaternion.""" return quaternion_conjugate(quaternion) / np.dot(quaternion, quaternion)
b71c5b544199b02a76362bc42db900b157ea80ec
20,651
def _make_indexable(iterable): """Ensure iterable supports indexing or convert to an indexable variant. Convert sparse matrices to csr and other non-indexable iterable to arrays. Let `None` and indexable objects (e.g. pandas dataframes) pass unchanged. Parameters ---------- iterable : {list, d...
29d067826e0a863b06b1fb0295b12d57ecaea00d
20,652
def batchnorm_forward(x, gamma, beta, bn_param): """ Forward pass for batch normalization. During training the sample mean and (uncorrected) sample variance are computed from minibatch statistics and used to normalize the incoming data. During training we also keep an exponentially decaying running ...
b36ea808c5865eb92a81464c3efe14ab9325d01e
20,653
def chunking(): """ transforms dataframe of full texts into a list of chunked texts of 2000 tokens each """ word_list = [] chunk_list = [] text_chunks = [] # comma separating every word in a book for entry in range(len(df)): word_list.append(df.text[entry].split()) # create a chunk of ...
66e1976b3bd9e88420fab370f1eee9053986bd56
20,654
def generate_random_string(): """Create a random string with 8 letters for users.""" letters = ascii_lowercase + digits return ''.join(choice(letters) for i in range(8))
027a9d50e2ff5b80b7344d35e492ace7c65366e8
20,655
def contains_message(response, message): """ Inspired by django's self.assertRaisesMessage Useful for confirming the response contains the provided message, """ if len(response.context['messages']) != 1: return False full_message = str(list(response.context['messages'])[0]) return...
4afcdba84603b8b53095a52e769d0a8e3f7bbb17
20,656
def definition(): """To be used by UI.""" sql = f""" SELECT c.course_id, c.curriculum_id, cs.course_session_id, description + ' year ' +CAST(session as varchar(2)) as description, CASE WHEN conf.course_id IS NULL THEN 0 ELSE 1 END as linked, 0 as changed FROM (...
ac67783943604e0e83bd4ccfc2b704737e427edd
20,657
def exec_psql_cmd(command, host, port, db="template1", tuples_only=True): """ Sets up execution environment and runs the HAWQ queries """ src_cmd = "export PGPORT={0} && source {1}".format(port, hawq_constants.hawq_greenplum_path_file) if tuples_only: cmd = src_cmd + " && psql -d {0} -c \\\\\\\"{1};\\\\\\...
453f0c2ef0dfdf2a5d03b22d4a6fbd03282dd72a
20,658
def carla_cityscapes_image_to_ndarray(image: carla.Image) -> np.ndarray: # pylint: disable=no-member """Returns a `NumPy` array from a `CARLA` semantic segmentation image. Args: image: The `CARLA` semantic segmented image. Returns: A `NumPy` array representation of the image. """ image.convert(carl...
f191d3f9700b281178f395726d649e90dfc57bb7
20,659
import re def since(version): """A decorator that annotates a function to append the version of skutil the function was added. This decorator is an adaptation of PySpark's. Parameters ---------- version : str, float or int The version the specified method was added to skutil. Exam...
e6b29b5e4c67ba4a213b183a0b79a1f16a85d81c
20,660
def get_dMdU(): """Compute dMdU""" dMdC = form_nd_array("dMdC", [3,3,3,3,3]) dMdPsi = form_nd_array("dMdPsi", [3,3,3,3,3]) dMdGamma = form_nd_array("dMdGamma",[3,3,3,3,3,3]) dCdU = form_symb_dCdU() dPsidU = form_symb_dPhidU() dGammadU = form_symb_dGammadU() ...
55d6dedc5311c8a2a30c44569508bd7687400cb5
20,661
def get_group_value_ctx_nb(sc_oc): """Get group value from context. Accepts `vectorbt.portfolio.enums.SegmentContext` and `vectorbt.portfolio.enums.OrderContext`. Best called once from `segment_prep_func_nb`. To set the valuation price, change `last_val_price` of the context in-place. !!! note ...
0646e7a26b36af42ee38196e0ee60e3684da2d16
20,662
import math import torch import scipy def motion_blur_generate_kernel(radius, angle, sigma): """ Args: radius angle (float): Radians clockwise from the (x=1, y=0) vector. This is how ImageMagick's -motion-blur filter accepts angles, as far as I can tell. >>> mb_1_0...
ff4e939d2ffbc91b6ef6af2ca11aceb1d32df594
20,663
def substitute_crypto_to_req(req): """Replace crypto requirements if customized.""" crypto_backend = get_crypto_req() if crypto_backend is None: return req def is_not_crypto(r): CRYPTO_LIBS = PYCRYPTO_DIST, "cryptography" return not any(r.lower().startswith(c) for c in CRYPTO_L...
0e1836120f52981c3ff126038c0c74b9da94aa7f
20,664
def remove_att(doc_id, doc_rev, att_id, **kwargs): """Delete an attachment. http://docs.couchdb.org/en/stable/api/document/attachments.html#delete--db-docid-attname :param str doc_id: The attachment document. :param str doc_rev: The document revision. :param str att_id: The attachment to remove. ...
2b9361468baf4dc2e358b2fa2f4c43403556cd40
20,665