content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def pratt(Ea,Ed): """ Created on Tue Oct 12 09:58:15 2021 @author: kondow_a Converted from Vivek Bhadouria (2021). Pratt's Figure of Merit (https://www.mathworks.com/matlabcentral/fileexchange /60473-pratt-s-figure-of-merit), MATLAB Central File Exchange. Retrieved October 1...
c1af52d4384756f5fd1bf409d9f53d2ceae60c91
3,608,500
import requests def get_weather(furl): """ Get the weather of a city given API call. :param furl: URL of the API call. :return: JSON response with weather data. req = requests.get(furl) """ req = requests.get(furl) return req.json()
7aa9c484c368fb61b9b6bf360dffa732e661b037
3,608,501
import nose def import_nose(): """ Import nose only when needed. """ nose_is_good = True minimum_nose_version = (1, 0, 0) try: except ImportError: nose_is_good = False else: if nose.__versioninfo__ < minimum_nose_version: nose_is_good = False if not nose_is...
8828c6911423094c38df79e0e31df4d4f0ffd266
3,608,502
def curry(f, *args, _curry_force_call=False, _curry_allow_uninspectable=False, **kwargs): """Decorator: curry the function f. Essentially, the resulting function automatically chains partial application until the minimum positional arity of ``f`` is satisfied, at which point ``f``is called. Also m...
7f47c0826fba89262e99eeef92c62a5c29885751
3,608,503
import torchvision import torch import argparse def choose_network(model_type, pre_trained_flag): """ 选取特征提取器 使用官方的实现,但是所有网络都去掉全链接层 """ if model_type == 'alexnet': model = torchvision.models.alexnet(pretrained=pre_trained_flag) new_classifier = nn.Sequential(*list(model.classifier....
dcc4247ada208868aefc8e81a0bde5e115e4358f
3,608,504
def checkpoint_list_objects_command(client: Client, limit: int, offset: int, filter_search: str, ip_only: bool, object_type: str) -> CommandResults: """ Retrieve data about objects. Args: client (Client): CheckPoint client. limit (int): The ma...
d776c3dd26656379349f860b830b2ae54e1a821f
3,608,505
import os def mimic_path_relativity(path, other, default_dir): """If 'other' file is relative, make 'path' relative, otherwise make it absolute. """ if os.path.isabs(other): return os.path.join(default_dir, path) if os.path.isabs(path): return os.path.relpath(path, default_dir) ...
5a8243446db11cf13f8fa8f47bac4f05f032c30c
3,608,506
def polyglot_2nd_number(s): """Get second number from the sentence. Parameters ---------- :param s: string Sentence Returns ------- :returns: string second number """ numbers = polyglot_numbers(s) if len(numbers) > 1: return numbers[1] else: ...
e0131b2742e20673d2561cdb7014cb803e157f60
3,608,507
def string_set_intersection(set_a, set_b, ignore_case=True, sep=","): """ Return intersection of two coma-separated sets :type set_a str :type set_b str :type ignore_case bool :type sep str :rtype set """ if set_a is None or set_b is None: return set() if ignore_case: set_a = set_a.lower(...
bd444273c17dc747f6856531c12d0b7280fb5aa3
3,608,508
def Main(a, b, c, d): """ :param a: :param b: :param c: :param d: :return: """ m = 0 if a > b: if c > d: m = 3 else: if b > c: return 8 else: return 10 else: if c > d: ...
d3e12e98bda3109f31e9286b8e95c92bb3e416c0
3,608,509
def ldns_verify_rrsig(*args): """LDNS buffer.""" return _ldns.ldns_verify_rrsig(*args)
20095cd97e5067ec55d53460ff1fd501ac4eba3c
3,608,510
def load_obj(name, folder ): """ To load a .pkl object from a desired folder Parameters ---------- name : string name of the object to be loaded folder: string name of the folder where the object is. Returns ------- returns the .pkl object to b...
5025a82d0f2ecebfe4c36f223bea3b2f0b561fdf
3,608,511
def load_data_from_days_mat(mat_data_path_name,mat_variable_name,get_meta=False): """ mat """ mat_data=sio.loadmat(mat_data_path_name) data=mat_data[mat_variable_name].astype('float32') if get_meta: meta=compute_data_meta(data,axis=(0,1,2)) return data,meta else: return data
0cf19c0c94f185e6e68b93def00576226ec75cbd
3,608,512
def c1Dtochi(c1D, box_size, r_min=None, r_max=None): """ For the cylindrically-averaged 1D correlation function c1D(r), this function returns the 2D susceptibility of the square box system of length L, defined as chi = 2\\pi/L^2 \\int_{r_min}^{r_max} dr c1D(r). NOTE: for displacement-related correlations, this sus...
47849480ae7cb7e060c40e88cf556fd8fca8d641
3,608,513
def traverse_file_structure(current, function, **inner_function_args): """Recursively traverses the given folder and applies the function to every file that it finds. :param current: Source folder :type current: stibnite.file_operations.FolderType :param function: The function that will be applied to f...
93312cb2792a27c1441a3794ca261bc67c22171a
3,608,514
def compute_mt_attention(model, inputs, targets, task=None, device=0): """ """ inputs = place_on_gpu(inputs, device=device) model = model.to(device=device) model.eval() for task_head in model.decoder.task_heads.values(): task_head.region_aware = True model_output = model(inputs, targ...
96769a496f63c6554363fce1fbeff2e111eb742a
3,608,515
import time def my_model_file(): """ 根据我自己训练的NER模型进行提取 Returns: """ time.sleep(2) try: if request.files: file = request.files["file"] msg_dict = extract_data_from_file(file) return jsonify({"code": 200, **msg_dict}) else: return ...
d26efd0c963856026ed181a5811568c9523749e9
3,608,516
def discreteOperatorToPreconditioner(op): """ Create a preconditioner from a discrete boundary operator. *Parameters:* - op (DiscreteBoundaryOperator) A discrete operator, which acts as preconditioner, e.g. an ACA approximate LU decomposition or a sparse inverse. *Returns*...
8dde3df2e5ac076dbd6d4ddbeae18b8b7d50ce3a
3,608,517
from typing import Dict from typing import List def find_input_layers(node_layer_map: Dict) -> List[tf.keras.layers.InputLayer]: """ helper to find the input layers of the model. :param node_layer_ref: dictionary includes node_ref as a key, in_layers and out_layer as value :return: return list of inp...
b4ce3ef67a4ffa952b8775ac66c87e70a7009292
3,608,518
def findDissimilar(index, minibatch1, minibatch2, actions, rewards): """ check which samples should be dissimilar because they lead to different rewards after the same actions :param index: (int) :param minibatch1: (np.ndarray) :param minibatch2: (np.ndarray) :param actions: (np.ndarray) ...
20c5cdcab1f0ebacd38e63e1f29be42ded37baa8
3,608,519
def med_blur(img, ksize=3, flag=False): """ Median filter for input image :param img: input image :param ksize: size of filter :return: image after median filter """ if img.dtype is not np.uint8: img = img.astype(np.uint8) new_img = cv.medianBlur(img, ksize) if flag: ...
19992aed9a4834cb7610894af45f60ff51b4a09b
3,608,520
def plot_source_type_histogram(docs, **kwargs): """ Plot histogram of the number of documents by publication source type. """ default = dict(title='Publication source type', limit=25) return wrapper(docs, compute_source_type_histogram, default, **kwargs)
ae90f7a7140c4b63e34445c0a5623b243ddc8cea
3,608,521
def gyy(lons, lats, heights, tesseroids, dens=None, ratio=2.5): """ Calculate the yy (East-East) component of the gravity gradient tensor due to a tesseroid model. """ return SI2EOTVOS * _optimal_discretize(tesseroids, lons, lats, heights, _gyy, ratio, dens...
20df89dc3b5bead73a68f850f071d723139eff88
3,608,522
def extract_text(dom, name, wrapper=None): """ Function tries to extract text data from the first tag with a given name and wrapps it in a give function / class. """ elements = dom.getElementsByTagName(name) if elements: text = elements[0].lastChild.data else: text = "" r...
19edcf8daad4438fc2096cc19dc7091df46bcdc0
3,608,523
def FMetisShad2(fGHz,r,D,sign=1): """ F Metis shadowing function Parameters ---------- fGHz : np.array(Nf) frequency GHz r : np.array(Nseg,) distance between Tx and Rx D : np.array(Nseg,Nscreen) indirect distance between Tx and Rx (screen effect) sign : np.array(Nse...
be8c9cad7dd69dfbca4fa945edf6cb4a6b38b724
3,608,524
def get_app_settings() -> AppSettings: """ This function returns a cached instance of the AppSettings object. Returns certain settings depending on the set APP_ENV environment variable. Caching is used to prevent re-reading the environment every time the API settings are used in an endpoint. If y...
01057df01cf56914d8f092241e9fbbe0da305714
3,608,525
def AddDefaultLocationToAllocationEndpointRequest(ref, unused_arguments, req): """Python hook to set default global location in allocation endpoint requests.""" del ref project = properties.VALUES.core.project.Get(required=True) # Use global for the location value location = 'global' req.parent = PARENT_TEM...
1b6a3557ac329316022812119cf01378e73ea688
3,608,526
def parse_args(): """Parse arguments""" usage = ('usage: %prog' + ' [--no-personals]' + ' [--protocol=zephyr|zulip]' + ' [--zulip-rc]' + ' [--default-classes]' + ' [--class=class ...]') parser = OptionParser(usage=usage) parser.add_option(...
4159b804cf710f3f7573e1e348cd5fb7e79fcad1
3,608,527
def loading_matfile(file_name, key, key2=''): """ @ param: string: file_name @ param: string: key return: key data in numpy.array form """ if file_name is None: print("Invalid file name!") # res = loadmat(file_name)[key] f = h5py.File(file_name, 'r') res = f.get(key + "/" + k...
e6a902add48c141145627feec3ed15c0f0bab12d
3,608,528
def center_elevation_map(elevation, width, height): """Translate the map horizontally and vertically to put as much ocean as possible at the borders.""" miny = None ymin = None minx = None xmin = None for y in xrange(height): sumy = 0 for x in xrange(width): sumy += ...
143dfdbec7e5e26e8208f57965d53633f14b7494
3,608,529
def multilingual(request): """ Returns context variables containing information about available languages. """ codes = sorted(get_language_code_list()) return {'LANGUAGE_CODES': codes, 'LANGUAGE_CODES_AND_NAMES': [(c, LANG_DICT.get(c, c)) for c in codes], 'DEFAULT_LANGUAGE_C...
a04d9ab287ddf774a701e920778abbcc5e899e62
3,608,530
from typing import Optional def curie_lookup(curie: str) -> Optional[str]: """ Given a CURIE, find its label. This method first does a lookup in predefined maps. If none found, it makes use of CurieLookupService to look for the CURIE in a set of preloaded ontologies. Parameters ---------...
5e6428852619e55d2f5cb025644d72ed5ca7c4eb
3,608,531
import os def get_eessi_envvar(eessi_envvar): """Get an EESSI environment variable from the environment""" eessi_envvar_value = os.getenv(eessi_envvar) if eessi_envvar_value is None: raise EasyBuildError("$%s is not defined!", eessi_envvar) return eessi_envvar_value
e87865813a1ef9a8a07884bafb589d7266250a73
3,608,532
def write_all_output_csv(out_dict, org_list, csv_rbh_output_filename, csv_strict_output_filename, csv_ns_output_filename, DEBUG, debug, good_tax_list): """ Writes formatted final output to CSV. :param out_dict: a dictionary of dictionaries :param org_list: a list of organisms ...
9e15b9ab739693c517f69e8621fa2a53c7c053c9
3,608,533
def youden_onecut(data, pred_col, duration_col, event_col, pt=None): """Cutoff maximize Youden Index. Parameters ---------- data : pandas.DataFrame full survival data. pred_col : str Name of column to reference for dividing groups. duration_col : str Name of column indic...
a96f83c14494cf27afb981f3f5dbd99628c5b412
3,608,534
import itertools def make_multislice_graph(net_list, w): """Makes a multislice representation of a list of separate networks. Creates a single network object representing the specified multislice structure. Every vertex appears once for each network where it is present. Multislice connections occur b...
cdd08acdf6c1faae13685d718d9d7ccff71a1f10
3,608,535
import functools def SupplyImpliedArguments(fn, namespace): """! @brief Supply values from namespace to keyword-only no-default arguments. @param[in] fn A function. @param[in] namespace A dict(str => ..) @return fn wrapped to get arguments from namespace. """ iargs = ImpliedArguments(fn) ...
e9d39458b3b61ea1a7816ac678a9af57ea4940eb
3,608,536
def node_neighbors_average( node, nodes, values, n: int = 50): """ :param node: objective node :param nodes: grid nodes :param values: values calculated in nodes :param n: number of neighbors :return value: averaged value Find the the average value for a node...
1c6724a73df0781b2013d8262c3033254c7687d5
3,608,537
def layout(response: mara_page.response.Response) -> str: """Renders a complete html page for the response""" return '<!DOCTYPE html>\n' + str( _.html(lang='en')[ _.head[ head_elements(response) ], _.body(class_='navigation-collapsed')[ ...
9204be7df1edb002357bfe05ece1eeec792d3ce9
3,608,538
import argparse def get_args(): """ Get arguments of the program :return: arguments parsed """ parser = argparse.ArgumentParser( "Split a video in several images" ) parser.add_argument("--path_video", type=str, help="Path to the input video", default="") parser.add_argu...
59c8e728930e534b95e07d0c03fa9c8932fb31de
3,608,539
def map_enum_fields(field: tp.Any, enum: tp.Enum, **kwargs) -> tp.Any: """Map fields to values. See `vectorbt.utils.mapping.apply_mapping`.""" mapping = to_mapping(enum, reverse=True) return apply_mapping(field, mapping, **kwargs)
5e8592d3cf3584d62e902e0f50b7572d645cc8c0
3,608,540
def _to_xy(df, target): """Converts a Pandas dataframe to the x,y inputs that TensorFlow needs""" return df.loc[:, df.columns != target].values.astype(np.float32),\ df.loc[:, target].values.astype(np.float32)
941516cd0c2c5ba4a8e311b4d5f4851d686b0938
3,608,541
import torch def affine(data: dict, matrix: torch.tensor, visualize: bool = False) -> dict: """ Applies affine transformation to the data :param data dict of elements to be transformed :param matrix: matrix of transformation :param visualize: if true it activates the display tool to debug the ...
dfc2bb71587d29d01ee4fecac9364d61068b04ee
3,608,542
from typing import Optional import types def make_reverb_dataset( server_address: str, batch_size: Optional[int] = None, prefetch_size: Optional[int] = None, table: str = adders.DEFAULT_PRIORITY_TABLE, num_parallel_calls: int = 12, max_in_flight_samples_per_worker: Optional[int] = None, po...
a23b01852148d1f86012d717bd0630fd9b887bab
3,608,543
def unmask(data): """ transform masked array into regular numpy array """ data_out = {} for k in data.keys(): if type(data[k]) is np.ma.core.MaskedArray: data_out[k] = data[k].data else: data_out[k] = data[k] return data_out
3d9a25a56614b03b51138365a568ecb4450e9c2c
3,608,544
def get_locale(): """how to get the locale is defined by you. Match by the Accept Language header:: match = app.config.get('BABEL_SUPPORTED_LOCALES', ['en', 'zh']) default = app.config.get('BABEL_DEFAULT_LOCALES', 'en') return request.accept_languages.best_match(match, default) """...
351a8ca65820d3169de694d44919f610d3faea98
3,608,545
import math def R_2vect(vector_orig, vector_fin): """ Taken from: https://github.com/Wallacoloo/printipi/blob/master/util/rotation_matrix.py Calculate the rotation matrix required to rotate from one vector to another. For the rotation of one vector to another, there are an infinit series of ro...
bbb9edb627ac438bddd87e9e49e5595ba78bce95
3,608,546
def create_numpy_image(dtype_name, nchannels, order='c'): """ Create a numpy image with 'nchannels' channels of major ordering of 'order' :param: nchannels: The number of channels the created image is to have :param: order: major ordering of created image. Default: column major ordering :return:...
c3dc9f92612625fa4eac1b6f4c0a5334e8e0d053
3,608,547
import random def buildModel(): """ Поток заявок поступает в накопитель с допустимой ёмкостью, равной 3 единицам, равномерно каждые 5+/-1 мин. Если заявки после накопителя застают 2-й канал (устройсто) занятым, то они поступают на обработку во второй канал. Время обработки 1-го канала равно 13+/-1 мин, 2-го 9...
9a91844942efb4d1e75547a4c21a474b95d70ccb
3,608,548
def uniform_random_sample(H,persis_info,gen_specs,_): """ Generates ``gen_specs['gen_batch_size']`` points uniformly over the domain defined by ``gen_specs['ub']`` and ``gen_specs['lb']``. :See: ``libensemble/tests/regression_tests/test_6-hump_camel_uniform_sampling.py`` """ ub = gen_sp...
837994b5bb5ae3d833997bff9158e47effa9a3d4
3,608,549
import json def handle_callback(request): """Check the token and save it as a cookie if correct.""" if request.args.get("error"): return request.args["error"] discord = make_session(request, state=request.ctx.session.get("oauth2_state")) try: token = discord.fetch_token( "https://discordapp.com/...
0ef0df0b846507250a707c526fcc773a38dd5464
3,608,550
def get_cache_manager(): """Returns an instance of CacheManager.""" cache_manager = cache.CacheManager() cache_manager.initialize(cache.MemCache()) return cache_manager
8895e03119f4b0f68ef31ddb76813aabb10674fa
3,608,551
def normal_map(tensor, shape): """ Generate a tangent-space normal map. .. image:: images/normals.jpg :width: 1024 :height: 256 :alt: Noisemaker example output (CC0) :param Tensor tensor: :param list[int] shape: :return: Tensor """ height, width, channels = shape ...
edc19b6c300696ed6445793839c5fa763f00458e
3,608,552
import functools from typing import Any def _generate_class_wrapper(obj: RealClass) -> WrappedClass: """Function decorators""" fn: RealFunction = obj.__init__ @functools.wraps(fn) def new_init(*args: Any, **kwargs: Any) -> None: setattr(args[0], RAW_KEY, kwargs) # set the raw data on self ...
f212a07e834ae605d4a258d1ea7bed9a88faa502
3,608,553
import re def get_source(cell): """ Returns the source code of a cell in a way that works for both nbformat and JSON Args: cell (``nbformat.NotebookNode``): notebook cell Returns: ``list`` of ``str``: each line of the cell source stripped of ending line breaks """ sou...
c8d61cd66ed7eb00a38d6e3f9bccf58495de69bf
3,608,554
import datasets from pydantic import BaseModel # noqa: E0611 def load_model(masks: np.ndarray, dataset: datasets.BaseDataset, iou: float, backbone: str, **kwargs) -> BaseModel: """load the model for the training Arguments: masks {np.ndarray} -- the mask used dataset {datas...
2b004922c660602998fe759d8de6f0f8a6123980
3,608,555
def app(): """Test server""" # Instance of Flask server for test suite app = create_app() # Grab FLASK_ENV and format it into a config name, then add that config to our app app.config.from_object("config.TestConfig") return app
43f136cd9744f60ed810d8df320641d11f6de0f0
3,608,556
def parse_ea_from_binary(mode: int, register: int, size: OpSize, is_source: bool, data : bytearray) -> (EAMode, int): """ Takes in the paramaters and returns a newly constructed EAMode and the amount of words of data that it used. If the paramaters were illegal in any way then (None, 0) is returned ...
4306389c81051ab4906dc1b1ae615fa616090e2f
3,608,557
def subplots(nrows=1, ncols=1, width_ratios=None, height_ratios=None, **fig_kw): """Create a figure and a set of subplots. Parameters ---------- nrows, ncols : int, default: 1 Number of rows/columns of the subplot grid. width_ratios : array-like of length *ncols*, optional Defines ...
cad6fab1a9f31529d00bca88edaa1e615153db12
3,608,558
import requests import re def get_dimension_values(dimension_code='YEAR', search_for=''): """ Allows user to inspect, and run a case-insensitive search through the values of a specific dimension. Parameters ---------- dimension_code : str The GHO database unique identifier for each dimen...
0b04c73bec23d682d872ee4d0a24ef5a8700f10f
3,608,559
import torch def sgd_step(self, closure=None): """Performs a single optimization step. Args: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: with torch.enable_grad(): loss = cl...
97bcd84075290281ce30a73d82300f9b03c384c8
3,608,560
def dedup_whoopsies(sortedWhoopsies): """ Take whoopsies sorted first by qid, then magnitude, then return the worst whoopsie by query """ mergedWhoopsies = iter(sortedWhoopsies) whoopsies = [] whoopsie = None lastQid = -1 try: while True: # Read ahead to next...
dfac3eda077e544df39539c4ea10d0a0eb7c6b7e
3,608,561
import string def processPDF(dictionary): """ Process the PDFs that can be found in the dictionary, created by the readPDF function. This includes removing stopwords, punctuations, digits, whitespaces, line breaks, and lemmatizes and stems all the words. Parameters: dictionary: dictionary ...
07faf21ccf53c0ad101cb3d9fb83675f3d391611
3,608,562
def prioritize_nodes(graph, where_conditions): """Assign high priority to nodes mentioned in where conditions.""" priorities = {} for node in graph.keys(): priorities[node] = 1 return priorities
60ef01d7bba9b03925a35e9fae602118207a208a
3,608,563
import random def _place_image(canvas, image): """ Returns the x and y co-ordinate the "image" should be placed at on the "canvas". """ global objects moments = _color_moments(image) if len(objects) == 0: x_val = int((canvas.size[0] - image.size[0]) / 2) y_val = int((canv...
9238255bc57f13a8914674c6b0aa1a3f48f80b7e
3,608,564
def read_file_pdf(): """pdf files --- parameters: - name: input_file in: formData type: file required: true responses: 200: description: Output """ pdfReader = PyPDF2.PdfFileReader(request.files.get("input_file")) text = "" for page in range(pdfReader.numPages): text = text + pdf...
623817577d5fde8042bf3e9648010960782e71bc
3,608,565
def jissue_field_prepare_dummy_s(project, inst): """ This method returns a dummy string, it is a reference to understand how the issues are created and are working in jira, each field has specific attributes, depending on the field type. To get the attributes one easy whay is to check an issue direc...
16ef7c7e94c82d5d752577e270f121b16e903bc3
3,608,566
def no_of_passwords(k=0): """ All are lowercase english alphabet. So for each position we have 26 possibilities. length_of_passwords = 5 each_position_no_of_possibilities = 26 """ n = 26 k = 5 return n**k
01898ae8eda0234858d2be1ff767a13ddb466a31
3,608,567
def get_shape_ids(conn, roi_id, across_groups=True): """Get IDs of shapes associated with an ROI Parameters ---------- conn : ``omero.gateway.BlitzGateway`` object OMERO connection. roi_id : int ID of ``ROI``. across_groups : bool, optional Defines cross-group behavior o...
a657326e6a84f3e80a5c89235daf9da1d52ac3ba
3,608,568
def env_start(): """ returns numpy array """ global maze, current_position start_position = [0,3] #maze[0][3] # start [x,y] current_position = start_position return start_position
a12f2ea46c8ea41923842fd79e9ae91f0441a8ea
3,608,569
import logging async def prover_get_credential(wallet_handle: int, cred_id: str) -> str: """ Gets human readable credential by the given id. :param wallet_handle: wallet handler (created by open_wallet). :param cred_id: Identifier by which requested credential is store...
87f5d47942410b9f2653be26b52c61cd55ef32ad
3,608,570
def rdist(x, y): """Reduced Euclidean distance. Parameters ---------- x: array of shape (embedding_dim,) y: array of shape (embedding_dim,) Returns ------- The squared euclidean distance between x and y """ result = 0.0 for i in range(x.shape[0]): result += (x[i] - ...
3caa871145b8ca68c0cd2bd23a183967b7b5b7cc
3,608,571
import logging import torch def evaluate_dev_set(model, data, criterion, data_loader, device): """ Evaluates the model performance on dev data """ logging.info('Evaluating accuracy on dev set') y_true = list() y_pred = list() total_loss = 0 for batch, targets, lengths, raw_data in dat...
4f61eaf29b42477e7e01aa74cd020053ebff5698
3,608,572
def _handle_time(time_label, time_unit, times): """Handle time label string and units.""" _validate_type(time_label, (None, str, 'callable'), 'time_label') if time_label == 'auto': if times is not None and len(times) > 1: if time_unit == 's': time_label = 'time=%0.3fs' ...
5b894aadd3997aff8b91c1a1e5908d1faa9160de
3,608,573
def argmax_decode(prediction): """ Decode a prediction using the highest probable character at each timestep. Then, simply convert the integer sequence to text Params: prediction (np.array): timestep * num_characters """ int_sequence = [] for timestep in prediction: int_seque...
082baa4a5401353f1237d9a469970d5afc495bd3
3,608,574
def quality_of_life(state, time, config, intervention=None): """Get the world2 quality of life metric derived from a state. Parameters ---------- state: whynot.simulators.world2.State or iterable representing a state. State of the dynamics time: float config: world2.C...
60e09bd475e785dfe788ae203e6c3da5f0d11ff3
3,608,575
def get_face_encoding(image, detected_face): """ Encode face into 128 measurements using a neural net :param image: picture numpy array :param detected_face: face detector object with one detected face :return: measurement (128,) numpy array """ pose_landmarks = face_pose_predictor(image, d...
aa8ebda712dea3dfc20c30ba8912ffad77d5a0aa
3,608,576
def reject_task_create(events, **kw): """Possible argument to attr_handler()""" events = [e for e in events if type(e) is not ThreadTaskCreate] if len(events) == 1: return events[0] else: return events
aa3d6f1b29f72111488018527696a11e25d1d836
3,608,577
def list_products(): """ Returns all of the Products """ app.logger.info("Request for Product list") products = [] category = request.args.get("category") name = request.args.get("name") if category: products = Product.find_by_category(category) elif name: products = Product....
5a257c2dfddb777fcd3b016f80320d4348cbed11
3,608,578
def preprocess_obs(obs, imsize): """ function to preprocess observation from env """ c = obs['images'] # image c = preprocess_image(c) return c
e69915f4b1148f6e9d8d4856285e150eeffdd6e6
3,608,579
def quadratic_approximation(x_list, y_list): """ Аппроксимация квадратичной функцией Parameters ---------- x_list : [float, float, ...] Список координат х. y_list : [float, float, ...] Список координат у. Returns ------- x_koef : [float, float, float] Список...
331a52c06aea40f5600897dbba389b3d5962744c
3,608,580
import os def task_exist(project_name, task_name): """ Checks existence of task. :param project_name: name of project whose task we are going to be looking for :param task_name: name of task that we are looking for :return: boolean """ if '.' in task_name: task_name = os.path.spli...
0e88146f69cfdc99710acc10c0af7ce9517f8430
3,608,581
def rref(m): """Row reduced echelon form of matrix""" n = len(m) M = len(m[0]) if n == M: for row in m: row.append(0) _rref(m,n,M) for row in m: row.pop() elif n != M: _rref(m,n,M) return m
2e75fe50bb9dcfb57fff5a64c741e4f4779996f2
3,608,582
import glob def find_file(path): """ Search file Parameters ---------- path : str Path and pattern to find files. Returns ------- str or list of str List of files. """ file_path = glob.glob(path) if len(file_path) == 0: raise ValueError("!!! No fil...
a5176d5caa5cef6ca2724c79e3f920cfc96aea0c
3,608,583
def set_updated_site(site_id, ttl=2*3600): """ 设置站点更新标记,2 小时 """ key = settings.REDIS_UPDATED_SITE_KEY % site_id return R.set(key, '1', ttl)
955ae942baff8d3346eb633cb3c215a2b7ab4d10
3,608,584
import numpy def compute_ivectors(gmm_stats, ivector_machine): """ Given :py:class:`bob.learn.em.GMMStats` and an T matrix, get the iVectors. """ ivectors = [] for g in gmm_stats: ivectors.append(ivector_machine(g)) return numpy.array(ivectors)
26d25ebd1acfd65571aa91a292c05ec70c35fc58
3,608,585
from typing import OrderedDict def data_preparation_be(country_attributes,reversed_dates=True): """ Creates an sorted dictionary of dates, new cases and tests for the Belgian Covid-19 data Parameters ---------- country_attributes : dict A dictionary containing country attributes rever...
a0a2389c7f1ad81e79e42217b2855bf81f8663a9
3,608,586
from pathlib import Path from datetime import datetime import os def RunPipeline(config, start_population_size): """ Run the daedalus Microsimulation pipeline Parameters ---------- config : ConfigTree Config file to run the pipeline start_population_size: int Size of the starting p...
f837699367a7038b2f568a3ab6c97863d52f761a
3,608,587
import os def get_html_theme_path(): """Return list of HTML theme paths.""" cur_dir = os.path.abspath(os.path.dirname(__file__)) return [cur_dir]
9041e859b786d33257ac3e972c223474261bceca
3,608,588
def invert_hiearchy(hierarchy): """Method to return the inverted hierarchy (1-res_seq) :param :py:obj:`~gemmi.Structure` hierarchy: pdb hierarchy to be inverted :returns: the :py:obj:`~gemmi.Structure` hierarchy corresponding with the inverted sequence (1-res_seq) """ inverted_model = gemmi.Model(...
cde371da9c512cd98dd38c129995ec854d9061d2
3,608,589
def __minimaxav_bruteforce(profile, committeesize): """Brute-force algorithm for computing Minimax AV (MAV)""" opt_committees = [] opt_mavscore = profile.num_cand + 1 for comm in combinations(list(range(profile.num_cand)), committeesize): score = scores.mavscore(profile, comm) if score <...
e97d1bf465bfcc0dbe117a714986173210e173bf
3,608,590
import re def get_potential_dois_from_text(text): """use multiple different regexes to get a list of potential dois, it uses a very generic regex first which only checks for the bare minimum start to the end of line, this result will than be searched for possible endings generating possible dois ...
2a5d8af511fa13bd28c06c1715a1adbd787ee70b
3,608,591
def my_getrss(): """ See http://stackoverflow.com/questions/669438/how-to-get-memory-usage-at-run-time-in-c """ fp = None try: fp = open("/proc/self/stat") parts = fp.read().split() return int(parts[23]) * _sc_page_size / 1024 finally: if fp: fp.close()
8c073b9e06c57bbd2fc3c7aa7829e6f40da61ef2
3,608,592
import scipy def hindered_rotor_d_heat_capacity_d_barr(T, freq, barr): """ Return the first derivative of the heat capacity with respect to the hindered rotor frequency in J/mol*K/cm^-1 at the given set of temperatures `Tlist` in K, evaluated at the frequency `freq` in cm^-1 and a barrier height `...
138149a65c80d04d909cfe480427628adbdbd046
3,608,593
import torch import time def predict(image, checkpoint_path, topk, use_gpu): """ Loads a model from the given checkpoint file and predicts what flower the given image is and the related probability. Parameters: image - A NumPy array representing the desired image checkpoint_path -...
852a802616f35cf3d09f22a2336a781559bfe1c6
3,608,594
import time def get_new_items(ticker: str, channel='@newswire', max_iterations = 60, until = 0): """Gets news items from ceo using ticker Parameters: ticker - stock ticker, for example APHA channel - can be @newswire, @thenewswire max_iterations - max number of reques...
1d9fb1396907fd4936145adb9de18f8a03bd428c
3,608,595
from pathlib import Path def get_file_info(dataset: Dataset, file_path: MetadataPath) -> FileInfo: """ Get information about the file in the dataset or None, if the file is not part of the dataset. """ # Convert the metadata file-path into a system file path path = Path(file...
443fddb515f6ce6f8f439dd89cb7b79887d0012b
3,608,596
def is_json(request): """Indicates if this request is JSON or not. By default a request is considered to include JSON data if the mimetype is ``application/json`` or ``application/*+json``. .. versionadded:: 0.11 """ mt = request.mimetype app.logger.info("Mime Type: %s" %mt); if mt == ...
3d81d11b068f5d2c09693279f15c0ca39c2eeaba
3,608,597
from typing import List from typing import Callable import tqdm import pickle import math def _build_query_ann_index( bucket_filenames: List[str], process_spectrum: Callable, vectorize: Callable, n_probe: int, batch_size: int, n_neighbors: int, n_neighbors_ann: int, precursor_tol_mass: float, ...
644469888045b9c4dd65bb4fec50b2d2f1993e29
3,608,598
import hashlib import json def _hasher(obj): """Computes non-cryptographic hash of an object.""" h = hashlib.md5(json.dumps(obj).encode()) return h.hexdigest()
14262878ac53af8f49f7fef4c028be36e4370725
3,608,599