content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def bbox_iou(bbox_a, bbox_b=None): """Calculate the Intersection of Unions (IoUs) between bounding boxes. Args: bbox_a (array): An array whose shape is :math:`(N, 4)`. :math:`N` is the number of bounding boxes. The dtype should be :obj:`numpy.float32`. bbox_b (array): An...
0da876bd6b5438e058ad0dff9a5bf0ccd64aaa3c
3,595,916
def riskparity(covariances, assets_risk_budget = None, columns = None, index = None, data = None, tol = None, method = 'pyrb'): """ Designed to take the output from the ewmcovar calculation or a simple covariances matrix. Calculates risk parity weights given covariances and target budgets. If data is pr...
1705321d74594b4326d9711737138616546220cd
3,595,917
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: """Set up the esphome component.""" hass.data.setdefault(DATA_COMPENSATION, {}) if entry.unique_id == CONF_MQTT_PREFIX: _LOGGER.warning("Skipping %s.", CONF_MQTT_PREFIX) return False datapoints = entry.op...
160533fd32427883101078100382189926dbdbf5
3,595,919
import re def regexp(expr, item): """Perform a regular expression search. Parameters ---------- expr : regex Regular expression to search for. item : str Item on which to perform regex search. Returns ------- bool True if result of search is not None, else Fal...
b853411c4a49148497858fe69df675acabf715d8
3,595,920
def column_names_from_cursor(cur): """returns column names as a list when provided cx_Oracle Cursor""" column_names = [] for column_info in cur.description: column_names.append(column_info[0]) return column_names
f5b1606bec5d32a67438c15c7d655079d189e512
3,595,921
import math def convert_size(size_bytes): """ Convert byte number to string Args: size_bytes: Returns: """ if size_bytes == 0: return "0B" size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") i = int(math.floor(math.log(size_bytes, 1024))) p = math.po...
eb16cff5f09d945ef26f94aefccbd9693a508fe9
3,595,922
from typing import Callable import functools def compose(*function: Callable) -> Callable: """Compose functions. I.e:: ``lambda x: f(g(x))`` can be written: ``compose(f, g)`` Args: *function (Callable): Any number of functions to compose together. ...
8c3b04ffeb03303a49c006fa347e150f94700d40
3,595,923
def categorical_distribution(df_master=None): """Distribution of categorical variables :param df_master: DataFrame, only contains categorical features :return: df_cat_report: DataFrame """ cat_cols = df_master.coulumns.tolist() df_cat_report = pd.DataFrame(cat_cols, columns=["COLUMN_NAME"]) ...
9c2a0c42d2ba3c0485543ee86d6527820a599da7
3,595,924
def calls(): """Fixture to record calls.""" return []
5044c9aa34415ff7bb97a243c2f0b5cdc33960b0
3,595,925
def reformat_cmd(text): """ reformat the text to be stripped of noise """ # remove az if there text = text.replace('az', '') # disregard defaulting symbols if text and SELECT_SYMBOL['scope'] == text[0:2]: text = text.replace(SELECT_SYMBOL['scope'], "") if get_scope(): text = get...
88f7531ca0dbecea6a51ab845e3eaa55a5156643
3,595,927
def checkLines(conf, repository, branch, user, group, commitmsg): """ returns whether conf allows a commit, paired with an explanatory message""" for line in conf.splitlines(): line = line.strip() # With Windows clients, empty lines were not recognized. # This might b...
682d57e97db547fa2496931130dc850573c6c269
3,595,928
import ctypes def uiNewNonWrappingMultilineEntry(): """ Creates a new non wrapping multiline entry. :return: uiMultilineEntry """ # Set return type clibui.uiNewNonWrappingMultilineEntry.restype = ctypes.POINTER( uiMultilineEntry) return clibui.uiNewNonWrappingMultilineEntry()
d68e48f8083ab75552810f4952b9ae39494f724e
3,595,929
def oxford_join(words): """Concatenate words with commas and a final 'and' between.""" assert len(words) > 0 if len(words) == 1: return words[0] if len(words) == 2: return words[0] + ' and ' + words[1] return ' '.join(map(lambda x: x + ',', words[0:-1])) + ' and ' + words[-1]
e880d3c42d93f521b5c80591ead907318976c271
3,595,930
def echo(value: str): """Test Celery task to echo a string. Args: value (str): string to return. Returns: str, the input argument string. """ return value
cc96b1f80147950cd0a084f45d379e5be0156c36
3,595,931
def select_from(query_message, options): """ Have the user select from an Array of Strings. Args: query_message - A query message to display to the user when selecting options - The options to select from """ questions = [ inquirer.List('s', message=query...
a34d1cd0845ec65078ec94c27c0d29a69df5791d
3,595,932
from typing import Iterable def plot_polar( df_angles: TfsDataFrame, da_col: str = ALOST2, jobname: str = "", df_da: TfsDataFrame = None, **kwargs, ) -> plt.Figure: """Create Polar Plot for DA analysis data. Keyword arguments are all optional. Args: df_angles (TfsDataFrame): ...
460a473a608d4468d2ae2891a4d004d3b5a612b3
3,595,933
from datetime import datetime import math def to_datetime(dates): """ Description: Convert dates to pd.to_datetime while also figuring out date_type unit ------------------------------------------- Input: dates = list or tuple of dates --------------------------------------...
a90bb1f74bd7cd03de0f9001aafa0cb7ff4ba6c9
3,595,934
def list_relocated(ctx): """list all relocated records / search relocated records by pattern""" return list_addresses(ctx, TYPE_RELOCATED)
99b780c4f51ce43d21ebb8a4fb87cb936842746a
3,595,935
def _is_modified(cache_dir: str, file_path: str) -> bool: """ Perform a cache map read and check if a file in the cache has been modified :param cache_dir: the cache directory :param file_path: the file to check :return: true if the file's modified time is later than the cache time; false otherwise...
b58b38057fade84b3b99ffc7d89904befa9f186c
3,595,937
import struct def wordswap(data): """ Swap byte order in each DWORD """ fmt = '%dL' % ((len(data)+3)/4) pad = len(data) % 4 if pad: pad = 4-pad data += b'\x00' * pad return struct.pack('<'+fmt, *struct.unpack('>'+fmt, data))
559883d3929f3f521dd8878a2582681651e8d122
3,595,938
import math def make_raster_scan_grid(center_ra_hours, center_dec_degs, num_ra_columns, num_dec_rows, ra_spacing_arcsec, dec_spacing_arcsec, equal_sky_angle=True): """ Create a grid of ra/dec coordinates following a "raster-scan" pattern; e.g.: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1...
b73647c33b0119aa13324b724f4dc765848fc71e
3,595,939
import six def printable_text(text): """Returns text encoded in a way suitable for print or `tf.logging`.""" # These functions want `str` for both Python2 and Python3, but in one case # it's a Unicode string and in the other it's a byte string. if six.PY3: if isinstance(text, str): return text ...
fe1df374191f732c981dc40d2d16ff2ede64222d
3,595,940
def get_high_d_function_caller_from_low_d_func(domain_dim, low_d_func, low_d_domain_bounds, low_d_opt_val, low_d_opt_pt, **kwargs): """ Gets a low dimensional function caller from a high dimensional one. """ group_dim = len(low_d_domain_bounds) high_d_func, num_groups = get_high_d_function_from_low_d(domain...
ca493c821ac0f591aa75e1b3aa521423aaa62103
3,595,941
from typing import Optional from typing import Dict from typing import Tuple from typing import Set from textwrap import dedent def get_entity_to_targets( *, client: Neo4jClient, minimum_evidence_count: Optional[int] = 1, minimum_belief: Optional[float] = 0.0, ) -> Dict[Tuple[str, str], Set[str]]: ...
b1c7c131f8bc80dafd81549574c1440749720f72
3,595,943
import time def match_to_tycho(objs, matchrad=1., radec=False): """Match objects to Tycho healpixel files. Parameters ---------- objs : :class:`~numpy.ndarray` Must contain at least "RA" and "DEC". matchrad : :class:`float`, optional, defaults to 1 arcsec The radius at which to ma...
8a245f6c6d2830c12b7ca7c60c8b36720cc5b047
3,595,944
def data_context_service_interface_pointuuid_available_capacity_bandwidth_profile_committed_information_rate_get(uuid): # noqa: E501 """data_context_service_interface_pointuuid_available_capacity_bandwidth_profile_committed_information_rate_get returns tapi.common.CapacityValue # noqa: E501 :param uuid: ...
cddf8054392bdfdeb65539801fab00542026d581
3,595,947
def distance(x1, y1, x2, y2): """ Distance between two points (x1, y1), (x2, y2). """ return pow((pow(x1 - x2, 2) + pow(y1 - y2, 2)), 0.5)
2bd9c1c8be018481998cff594f08c98d29be04de
3,595,948
import numpy def from_numpy(array, regulararray=False, highlevel=True, behavior=None): """ Args: array (np.ndarray): The NumPy array to convert into an Awkward Array. This array can be a np.ma.MaskedArray. regulararray (bool): If True and the array is multidimensional, ...
68765797bb9d45053061ca4404771f6242f8255e
3,595,949
def general_cm_wilson(a, b, digits_of_precision, z_score): """ Computes generalized confusion matrix wilson bounds Used for rates of the form: a / (a + b) This is necessary because the denominators for rates such as True Positive Rate need to be out of total positive results """ n = a + b ...
9fc8b88db13bbddfcfc350ce5cd2b101ac45e030
3,595,950
def get_binary_property(value, mode=MODE_UNICODE): """Get `BINARY` property.""" obj = unidata.ascii_binary if mode != MODE_UNICODE else unidata.unicode_binary if value.startswith('^'): negated = value[1:] value = '^' + unidata.unicode_alias['binary'].get(negated, negated) else: ...
e4bb745c55d3b3e3756ff003de0ac4410d0e95a1
3,595,951
def combine_english_defs(senses, separator=u', '): """Combines the English definitions in senses. Args: senses: An array with dict elements with English info. Returns: A string of English definitions separated by the separator. """ # Each sense contains a list of English definitions....
c4dd5b732e198dc4381ebfd5b133c226a3094be7
3,595,952
def add_or_get_merge_anchor_index(lane, pos): """ Add a merge anchor at pos if needed, return the index of the merge anchor """ if not hasattr(lane, "merge_anchors"): lane.merge_anchors = [] for ind, e in enumerate(lane.merge_anchors): if (e[1] is None and pos == lane.start) or e[1] ...
ee52833b37d84ca765f8e5c56ec9e8f52691451a
3,595,953
def _compute_ap(recall, precision): """ Compute the average precision, given the recall and precision curves. Code originally from https://github.com/rbgirshick/py-faster-rcnn. Args recall: The recall curve (list). precision: The precision curve (list). Returns The average p...
2cbf5de304fc5ba7a1a0b6ed11b5f67b5c715062
3,595,954
def __top_words(corpus, n=None): """For the next function""" vec = CountVectorizer().fit(corpus) bag_of_words = vec.transform(corpus) sum_words = bag_of_words.sum(axis=0) words_freq = [(word, sum_words[0, idx]) for word, idx in vec.vocabulary_.items()] words_freq =sorted(words_freq, key = lambd...
f2b2b63b3679b1ed24322fe6a730adf7365150ee
3,595,955
def generate_farmed_coin( block_index: int, puzzle_hash: bytes32, amount: int, ) -> Coin: """ Generate a (fake) coin which can be used as a starting point for a chain of coin tests. """ return Coin(int_as_bytes32(block_index), puzzle_hash, uint64(amount))
3f60bf63d5b3d8716d9a44808314bf6d2a060157
3,595,957
def create_query(age: tuple = (None, None), gender: str = None, image: str = None, diagnosis: str= None, tool: str = None) -> str: """ Parameters ---------- age : gender : image : diagnosis : tool : Returns ---...
fe99b9973984b6f16ac59202cdf195a56d7d54b0
3,595,958
def create_BRN_weight_matrix(N, w, g, epsilon, gamma): """create a random realization of a weight matrix for an E/I network of N neurons with fixed weights. """ return create_BRN_weight_matrix_fixed_indegree(N, w, g, int(epsilon * N), gamma)
4e7dff14610d47e2831de241f8ef3eeac8bae7ef
3,595,960
def recover_ns(phrase, analysis, position): """ Retrieves the nominal structure of the sentence :param list phrase: sentence :param Sentence analysis: the instance of class sentence :param position: the position of the nominal structure :return: the class sentence and sentence """ #init ...
b2b5f8c5e38ee842b5dc9e00d4ad0344c9a657cb
3,595,961
def is_hovering(rect, mouse_pos): """Checks if a mouse is hovering over a rect""" if ( rect.left <= mouse_pos[0] <= rect.right and rect.top <= mouse_pos[1] <= rect.bottom ): return True return False
e17f4b8ee6e0b5f174473aa88388ff81ab67ea66
3,595,963
def genetic_alg(problem, pop_size=200, mutation_prob=0.1, max_attempts=np.inf, max_iters=np.inf, curve=False, random_state=None): """Use a standard genetic algorithm to find the optimum for a given optimization problem. Parameters ---------- problem: optimization object Obje...
cb77c9f949c21f11ad508185a2a08cafff1572f3
3,595,964
def set_subscription(request, token, subscribe): """ A view that disables or re-enables notifications for a user who may not be authenticated This view is meant to be the target of an unsubscribe link. The request must be a GET, and the `token` parameter must decrypt to a valid username. The subscr...
fdc5c0e6e33ba26d949c1b61b6e0725b6f5f0009
3,595,966
from mriqc.interfaces import PlotMosaic from mriqc.reports import individual_html from mriqc.interfaces.viz import PlotContours from mriqc.viz.utils import plot_bg_dist def individual_reports(settings, name='ReportsWorkflow'): """ Encapsulates nodes writing plots .. workflow:: from mriqc.workflo...
8c31f5c3ae37514f55a6a0852d8fa81c89462028
3,595,967
import math def compass_bearing(pointA, pointB): """ Calculates the bearing between two points. The formulae used is the following: θ = atan2(sin(Δlong).cos(lat2), cos(lat1).sin(lat2) − sin(lat1).cos(lat2).cos(Δlong)) :Parameters: - `pointA: The tuple representing the...
4ef715ab9519e306a12c42ab87f0a624d7e0589c
3,595,968
from enum import Enum def make_parser_cls(message_size): """ A Factory to generate a Parser handling Message of message_size. """ class Parser(object): """ Parses bytes to rebuild messages from byte stream. And generates frames from messages. Us...
a1431705ed7e3a0566e6958d3a589d59109056e2
3,595,969
def unauthorized(): """ Method to try if logged :return: message if non authorized """ return jsonify({'info' : 'Log-in required for this request.'})
d8c5df48c4781b4077c5cb42faf7c973a731334b
3,595,970
from typing import List from typing import Callable from typing import Any def multifit(bins: Bins, items: List[any], valueof: Callable[[Any], float] = lambda x: x, iterations = 10): """ Partition the numbers using the MultiFit algorithm. :param iterations: how many iterationss to run in the binary searc...
c034abe2b52d43a4f991267a8dbbe1fc2ccc8a6e
3,595,971
def dashboard(): """ The "home screen" is a preview of current events... """ # Yes, a one-line function is a good function. return tpl('dashboard')(appt = coming_appointments(), task = pending_tasks())
5f4fbd1305644ee7df3b699f447c5c2a3efa4796
3,595,972
from typing import Dict def update(id_: str, type_: str, object_: Dict[str, str], session: scoped_session, api_name: str, path: str=None) -> str: """Update an object properties based on the given object [PUT]. :param id_: if of ob...
32d31da1e0794b0de9869d5c8f36c6b5d88ce485
3,595,973
def gc(f,stride=35,MDL=3500): """Runs graphcuts""" locs=find_locs(f,stride) unary=init(locs,f,MDL) blank=np.zeros((f.shape[0],0),dtype=np.double) neigh=blank weight=blank seg=np.arange(f.shape[0],dtype=np.double) for i in xrange(5): mdl=np.ones(unary.shape[1])*MDL #Run Gr...
4e19ce2a3d4b58d581ae92b1e635127dddc0c576
3,595,974
def knapsack_dp(items, capacity): """Return the maximum value that can be stored in the knapsack.""" rows = len(items) + 1 cols = capacity + 1 dp_table = [[0 for j in range(cols)] for i in range(rows)] for i in range(rows): for j in range(cols): if i is 0 or j is 0: ...
6beae17041d1922725ccc2641d86594ede7f8bf6
3,595,975
def fk_matchtype(matchtype): """ Gets the full name for a foreign key match type abbreviation. :param matchtype: The match type abbreviation. :returns: Match type full name """ return _FK_MATCHTYPE[matchtype]
692918933a5b6966fbc232ef01e5abbad8d829ea
3,595,977
def optimize(s, probability, loBound, hiBound): """ Optimiere auf die max. mögliche Entnahme bei einer vorgegebenen Fehlerquote Returns: widthdrawal: max. mögliche prozentuale Entnahme """ n_ret_months = s.simulation['n_ret_years'] * 12 accuracy = 0.005 # Genauigkeit der Optimierung ...
1ad98336a531a8fd149f9351cb6f450c836d67a0
3,595,979
def _cell_list(unit_type, num_units, num_layers, num_residual_layers, forget_bias, dropout, mode, num_gpus, base_gpu=0, verbose=True): """Create a list of RNN cells.""" # Multi-GPU cell_list = [] for i in range(num_layers): if verbose: utils.print_out(" cell %d" % i, ...
44e880eac95e13077abd4c30095c38cbbb41f940
3,595,980
def get_y_extent(v): """Automatically determines appropriate y extents of a track. """ v_min, v_max = np.min(v), np.max(v) y_min = max([y for y in Y_EXTENTS if y <= v_min]) y_max = min([y for y in Y_EXTENTS if y >= v_max]) return y_min, y_max
e19d681363b5c543ba59b41c39c419633326bd46
3,595,981
import time import pickle def sign(key, data, lifetime=None): """Produces a signature for the given data. If 'lifetime' is specified, the signature expires in 'lifetime' seconds; otherwise it never expires.""" expiry = lifetime and int(time.time() + lifetime) or 0 bytes = pickle.dumps((data, expiry))...
fa5cb62d4b6893e2862c902eb7c0d072b4568e21
3,595,982
import functools def wraps_set_expire(func): """ 装饰器, 设置key默认过期时间 """ @functools.wraps(func) def wrapper_func(self, keyname, *args, **kwargs): ret_func = func(self, keyname, *args, **kwargs) # 设置key的过期时间 if ret_func is not None: self.set_expire(keyname) ...
4b2f06cce1c598097514963a5280029d515f63f1
3,595,984
def timestamp_julian_transform(value, date_only=False): """Transform Julian timestamp to ISO 8601 date format. Julian timestamps are the number of days that has passed since noon Universal Time on January 1, 4713 BCE. :param int value: Julian timestamp in days :param bool date_only: if we should f...
ff1f2739e6407d155b25c351b28bbf6c17dd9ade
3,595,985
def set_track_name(track_num: int) -> str: """Generate a track name based on the track number Args: track_num (int): The current track number Returns: str: The name of the track """ if track_num < 10: track_name = f"track_0{track_num}{config.FILE_EXT}" else: tra...
2f6b19e29d6d34d63d3013166add22bd4051e26b
3,595,986
import requests import io def facial_fetch(imgurl): """Using the facial recognizer get the location of all the faces on the image. Args: imgurl : image the recognizer is done on. Return: location of found faces ..note: - In light of the fact that were using a free service, it ...
61e340d4a70783b0bb9407b088f6b91e3bb5dda4
3,595,988
def graph_mean_in_tissues(title, column_names, summary, online=False): """ Compute plotly graph with mean value in tissue masks Parameters ---------- title : string Title of the graph. column_names : array of strings Name of the columns in the summary DataFrame. summary : Da...
cf443656f1ceb92ffe93d3bd94bb23c6f0087659
3,595,989
def view(request, acronym): """ View IETF Group details **Templates:** * ``groups/view.html`` **Template Variables:** * group """ group = get_object_or_404(Group, acronym=acronym) add_legacy_fields(group) return render_to_response('groups/view.html', { 'group': gr...
e68109c24abf2a970046afbfbf448853ce6b2d2c
3,595,990
def view() -> pn.Column: """Wraps all tests in a Column that can be included in the Gallery or served independently Returns: pn.Column -- An Column containing all the tests """ return pn.Column(pnx.Markdown(__doc__), test_code(),)
102e9eebad9fccd31ab2c766ef44d9a883fcd604
3,595,991
def copy_dict(other_dict): """ Returns a copy of the dictionary, separate from the original. This separation is only at the top-level keys. If you delete a key in the original, it will not change the copy. >>> d1 = dict(a=1, b=2) >>> d2 = dict(**d1) >>> del d1['a'] >>> 'a' in d1 False >>> 'a' in d2 True ...
a8d25212b2bf0524a5f434fd590c1ac3ec8b8810
3,595,992
def get_filled_buffer(): """ Return simple preinitialized buffer """ observation_space = gym.spaces.Box(low=0, high=255, shape=(2, 2, 1), dtype=int) action_space = gym.spaces.Discrete(4) buffer = DequeMultiEnvBufferBackend(20, num_envs=2, observation_space=observation_space, action_space=action_space) ...
006424a3f695eea920b1052d33487beefafe77a2
3,595,993
def api_municipality_info(): """ route для получения полигонов для отрисовки слоя плотности населения Москвы :return: json с полигонами и необходимой информацией """ return get_municipality_info()
c5b5a985d757ea81c52f047e9deae68475b0219b
3,595,994
def name_numbers(left: Entity, right: Entity) -> float: """Find if names contain numbers, score if the numbers are different.""" lv, rv = type_pair(left, right, registry.name) return has_disjoint(_extract_numbers(lv), _extract_numbers(rv))
d1f02c77a5b7eef7d1c3c457e7a6f42ab4d82fd0
3,595,995
def _get_plane_vectors(ez): """Get two orthogonal vectors orthogonal to ez (ez will be modified).""" assert ez.shape == (3,) ez_len = np.sqrt(np.sum(ez * ez)) if ez_len == 0: raise RuntimeError('Zero length normal. Cannot proceed.') if np.abs(ez_len - np.abs(ez[2])) < 1e-5: # ez already in ...
e983b05e20baae14e24eb323abdbf8fdb4de0322
3,595,997
def render_signal(signal_params): """ Produce a TikZ string defining the given waveform line with parameters as used by WaveDrom. """ return r""" \signallabel{%s} %% A scope to ensure correct styling and limit the effect of clipping \begin{scope}[line cap=rect, line join=round] ...
aa89edd992dcfd423787122e150ee06c8653255e
3,595,998
def drop_duplicate_geometries(gdf, keep='first'): """Drop duplicate geometries from a dataframe """ # convert to wkb so drop_duplicates will work # discussed in https://github.com/geopandas/geopandas/issues/521 mask = gdf.geometry.apply(lambda geom: pygeos.to_wkb(geom)) # use dropped duplicates ...
dedeedf0e6ad0e1aaf5bfba072913b78b5353120
3,596,000
def apply(gate, qubits, state): """Apply a gate to the specified qubits of a state Parameters ---------- gate : ndarray[complex] qubits : sequence of int The qubits on which to act. Qubit 0 is the least significant qubit. state : ndarray[complex] Returns ------- new_state :...
b5c0ad0ec0caec39c8a64e8c95b3f424fd2ff6b2
3,596,001
def box_tuple(c, typ, val): """ Convert native array or structure *val* to a tuple object. """ tuple_val = c.pyapi.tuple_new(typ.count) for i, dtype in enumerate(typ): item = c.builder.extract_value(val, i) obj = c.box(dtype, item) c.pyapi.tuple_setitem(tuple_val, i, obj) ...
45e277406d904060afb1e5d22469fcf104a12b32
3,596,002
def split_dataframe(df, holdout_fraction=0.1): """Splits a DataFrame into training and test sets. Args: df: a dataframe. holdout_fraction: fraction of dataframe rows to use in the test set. Returns: train: dataframe for training test: dataframe for testing """ test = df.sampl...
3936978c860bbc0868a70c38d98ca17f0b167ecb
3,596,003
def web_mercator_y(latitudes): """Find y values in Mercator Web projection related to latitudes""" longitudes = np.zeros(len(latitudes), dtype=np.float) gl = cartopy.crs.Mercator.GOOGLE pc = cartopy.crs.PlateCarree() _, y, _ = gl.transform_points(pc, longitudes, latitudes).T return y
50c232185475b8dc0fc6da611ae038667a6af52b
3,596,005
def uncertainty_largest(network, loader, logits=0, temperature=1): """ Compute uncertainty as the negative largest logit """ outputs = featurize_loader(network, loader, classify=True, logits=logits, ...
f95ef6285720177ff03ce82bd623805feca00ac7
3,596,006
from typing import List from typing import Union def build_whatis_component( whatis: Whatis, is_admin: bool = False, include_buttons: bool = True ) -> List[Union[blocks.DividerBlock, blocks.SectionBlock, blocks.ActionsBlock]]: """ Build the component that will actually hold the whatis including actions re...
f037e894f5c658390d9486f572493ab39d76a729
3,596,007
def assign_segment_scores(test_data, clf): """ Returns a data frame with the segments of *test_data* as indices and the ratio of preictal guesses as a 'Preictal' column :param test_data: A DataFrame with the unlabeled test data. :param clf: The classifier to use for predicting scores. :return: ...
1e5eaf4123dde0e2fb39bd7f7ebc8ad806f8d233
3,596,008
def lsim2(system, U=None, T=None, X0=None, **kwargs): """ Simulate output of a continuous-time linear system, by using the ODE solver `scipy.integrate.odeint`. Parameters ---------- system : an instance of the LTI class or a tuple describing the system. The following gives the number of...
85b062fc8ff4fae93887a7b88e3890581560eb43
3,596,009
def get_default_params(table, columns, where): """ Returns the default columns and where parameters for the table if specified in DEFAULT_PARAMS and if 'columns' and/or 'where' are None. :param str table: The name of the table. :type columns: list or dict :param columns:...
fe1e62c7ba152154813be4e50df8b0d06a57b50b
3,596,010
def superhelper(x, name=""): """Prints help about, and then returns that variable.""" INSPECTOR.pinfo(x, oname=name, detail_level=1) return x
5cef6c2a99e7cdad7d658a5819e82446d85a0bfe
3,596,011
def trans_from_matrix(matrix): """Convert a vtk matrix to a numpy.ndarray.""" t = np.zeros((4, 4)) for i in range(4): for j in range(4): t[i, j] = matrix.GetElement(i, j) return t
ad582ff7e1f5fd6da0d2623d00bf9dae804442fe
3,596,012
import torch from typing import Callable from typing import Optional def relative_entropy_control_cost( sde: torch.nn.Module, log_p: Callable, param_batch_size: Optional[int] = 32, dt: Optional[float] = 0.05, device: Optional[torch.device] = None, ): """ Objective f...
7493130d5e07f69942a0905e305fb8a0602f6d00
3,596,013
def compute_giou(box1, box2): """Calculates the generalized intersection of union between box1 and box2. Args: box1: a `Tensor` whose shape is [..., 4] and represents the coordinates of boxes in x_center, y_center, width, height. box2: a `Tensor` whose shape is [..., 4] and represents the coordinates...
1b4f65aede67297c4b850a990fa25aa51d21f263
3,596,014
def extract_contour_pts_pgm(filename): """Extract points from largest contour in PGM image. This function is used to extract ordered points along the largest detected contour in the provided PGM image and format them for use by OpenCV image tracking. In particular, this function is used to extract the ...
d102aa0542ef1fe31f41eca8f0e3b83711755567
3,596,015
def reduceScale(structure,scale,dim,prec=1E-2): """ Attempt to reduce the structure from a supercell inputs -------- structure (Structure): Pymatgen structure object to reduce scale (int or list (3x1)): How much to scale the periodic lattice vectors by. ...
ab2814adf536dd4512e7316010515c3f6800e3f0
3,596,016
def planet_double_arg_mercury(x, y, e, R): """ Planet double argument mercury :param x: mean center in degree :param y: true argument in degree :param e: eccentricity :param R: radius of the epicycle :return: """ s = utils.s_m_0(x, e) rh = utils.rho_0(x, s, e) p = utils.pla...
aed98d2f8a2d8854ddadbd048c68280c1bed5d0f
3,596,017
def apply_operator(operator, a, b): """Sa se construiasca o functie apply_operator(operator, a, b). Functia va aplica peste a si b regula specificata de dictionarul global. Sa se implementeze astfel incat, in cazul adaugarii unui operator nou, sa nu fie necesara modificarea functiei. """ func =...
79908ce2e3f7a24d34a3d229292ba2de77dc155b
3,596,018
def correct_family_size(cluster, key, number_reads, GCF_dict): """ calculate the total sum of counts and number of family members of a BiG-SCAPE GCF family ---------- cluster string, the name of the cluster key string, the name of the key number_reads int, the number of r...
5184cde71aa2709bb11c58b333040ff2c57132d3
3,596,019
def etree_fromstring(string): """This is a safer implementation of the default fromstring that disable: * network interaction. * entity resolution. This can lead to information leakage and memory hogging. see https://github.com/PyCQA/bandit/issues/435 """ parser = etree.XMLParser(resolve_en...
68db7d32883a6108b2383a8bd9efa3d1d64ee2e9
3,596,021
def num_procs(): """Count active MPI processes.""" return MPI.COMM_WORLD.Get_size()
f9013328110a5d5724369903a3f3cab1463f0eff
3,596,022
def reroot(root, source_path): """Reroot to a new path, maintaining a input proto index. Similar to root.get_descendant_or_error(source_path): however, this method retains the ability to get a map to the original index. Args: root: the original root. source_path: the path to the new root. ...
400d9701d7c85ed9f151eca2f283cca2515101c2
3,596,023
import torch def make_non_pad_mask(lengths): """Function to make tensor mask containing indices of the non-padded part e.g.: lengths = [5, 3, 2] mask = [[1, 1, 1, 1 ,1], [1, 1, 1, 0, 0], [1, 1, 0, 0, 0]] :param list lengths: list of lengths (B) :return: ...
ace8ec28960cf4810257868fcb134e593d45cb20
3,596,026
def filter_all_persons(queryset, name, all_persons): """Filter only trainees when all_persons==False.""" if all_persons: return queryset else: return queryset.filter( task__role__name='learner', task__event__tags__name='TTT').distinct()
f64e4fcdf770e8003319ca1c19b089fa090d4984
3,596,027
def norm_sphere(values=50): """ Generate unit vectors on a sphere. Note the unit vectors cover the sphere with equal probablility around the sphere. For more information see: https://stackoverflow.com/questions/33976911/generate-a- random-sample-of-points-distributed-on-the-surface-of-a...
d2f2e882a60b2f1155bd9f8e365b33d1f7bc4e67
3,596,028
def compute_line_seeds(binary,bottom,top,colseps,scale, threshold=0.2, # use larger scale so broken/blackletter fonts with their large capitals # are not cut into two lines or joined at ascenders/decsenders: vscale=2.0, ...
b5e1228efc314e840bba8c9260a7215488b509d5
3,596,029
def TimestampFromTicks(ticks): """Construct an object holding a timestamp from the given ticks value.""" return Timestamp(*gmtime(ticks)[:6])
29776d2f5da8ca69654cc31ce33a8b03d41ebb5b
3,596,030
import shlex def make_commit_msg(pairs, no_verify): """Return a commit message to explain what was replaced by the provided arguments. """ script = ["./scripts/maint/rename_c_identifier.py"] for id1, id2 in pairs: qid1 = shlex.quote(id1) qid2 = shlex.quote(id2) script.ap...
4757c9200dc25d97bdf8a3de0954d0e373adc07c
3,596,031
import numpy def _bootstrap_cost(observed_labels, forecast_probabilities, cost_function, num_replicates): """Uses bootstrapping to estimate cost. E = number of examples :param observed_labels: length-E numpy array of true classes (integers in 0...1). :param forecast_proba...
473613c7b16876d8b4467e68a119309f35793f90
3,596,032
def check_for_event(device_int, device_ip): """ Author - Jonathan Steward Function - checks for an existing event and if one exists if its an old event or not Inputs - Global - timeout_minuets - defined at the top to identify how many minuets old an event need...
ba40a2111a2d1c86cc8bd9f08d59415ada2641fb
3,596,033
def make_env(env_name, shape=(200, 300, 1), repeat=4, clip_rewards=False, no_ops=0, fire_first=False): """ Create the env with different wrapper for state preprocessing :param env_name: Gym env id :param shape: desired output shape :param repeat: number of stack frame :param clip_rewards: clip r...
4405a17ea1ca563521dbd3bd9751412cb4662a19
3,596,034
def is_circular(spec): """Return `True` if trivial winning set non-empty. @type spec: `tulip.spec.form.GRSpec` @rtype: `bool` """ aut = _grspec_to_automaton(spec) triv, t = gr1.trivial_winning_set(aut) return triv != t.bdd.false
d03063f4b9bdce1d6c9619c09ed71eac3ba4c5e1
3,596,035