content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def histograms(coordinate_sets, r_max, n_bins): """Distance histogram calculation on the CPU using Cython kernels. Calculate histograms from sets of species coordinates by calling the pwd() and pwd2() CPU functions from the Cython dist_knl. Serves as the reference implementation for the pydh and cudh ...
0700c85c3b0cc749cecc7caffe8634a482e0886c
3,603,900
import numpy def cv_image_from_bytes(image): """Convert image bytes to OpenCV image.""" import cv2 # pylint: disable=import-error # pylint: disable=no-member return cv2.imdecode(numpy.asarray(bytearray(image)), cv2.IMREAD_UNCHANGED)
820a25490b6bcce8f39f9c4aeb6520dbba1e5083
3,603,901
def form_url(main_url: str, url: str, data: t.Optional[t.Dict[str, t.Any]] = None) -> str: """ Form and return the URL for the Hypixel API with GET Params. Parameters ---------- main_url: str The Main URL With the root domain. url: str The Route in the Main URL to access the JSO...
9ddcb110bbd79820b11cfe0aa1ac9cd7d5ded1c1
3,603,902
def return_figures(stocks=default_portfolio, index=default_index): """Creates four plotly visualizations Args: None Returns: list (dict): list containing the four plotly visualizations """ def get_stock_history (tiker, invest_period): """ input: ...
1f289abfd46b2ee2811f1081841c282083d810f2
3,603,903
def reduce_repeat_bb(text_list, break_token): """ convert ['<b>Local</b>', '<b>government</b>', '<b>unit</b>'] to ['<b>Local government unit</b>'] PS: maybe style <i>Local</i> is also exist, too. it can be processed like this. :param text_list: :param break_token: :return: """ count = 0 ...
1c9d88ca295ab31831773264c2ede597b707f3f6
3,603,904
def get_spectrogram_data(data:np.array, sr:int, n_mels:int=32, types:str="4d") -> np.array: """ @topic: Convert 1-D audio wave to 2-D spectrogram and build 4-D dataset. @topic: wave: audio wave; sr: sample rate; n_mels: the size of output spectrogram; types: type of data. @return: 4-D spectrogram datase...
017dc78348c03185a194457855a25628e71a4c49
3,603,905
def is_preprocessor_punctuator(c): """Returns true if a preprocessor delimiter""" result = preprocessor_punctuator.match(c) return result is not None
1c9498f9bda541eb6883bf9f042d169031949aaf
3,603,906
def calculate_probability_contour(pdf,axes,pvals,axis=0): """ Calculates the probability level below which the PDF integrates to pval. input: ------ pdf : a conditional PDF from fastKDE axes : a list of axis values returned from fastKDE ...
19abdbb5b30f5dca1f4d6efa49db3c70cace47da
3,603,907
def model_tide_points(ds, points_gdf, extent_buffer=0.05): """ Takes an xarray.Dataset (`ds`), extracts a subset of tide modelling points from a geopandas.GeoDataFrame based on`ds`'s extent, then uses the OTPS tidal model to model tide heights for every point at every time step in `ds`. T...
47aaac8c6fd045bb5af2b09caaf244ffeb57e8dc
3,603,908
def verify() -> str: """Respond to the webhook verification (GET request).""" return request.args.get("challenge", "")
9f1de9d5ab33c6a3d689b818aa75d99108b962f7
3,603,909
def report_old(): """Redirect old bookmarked reports to the new path format.""" try: path = flask.request.args['q'] except: app.logger.info('Unable to decode valid domains from q GET param') return flask.redirect('/error/1') return flask.redirect('/search/{}'.format(path))
5ba17bb479a462d795e47c48c1f7bf9a337e8648
3,603,910
from typing import Union from typing import List from typing import Tuple def suggest_udict_terms( text: Union[str, List[str]], silent: bool = False, spinner: bool = True, ) -> Tuple[List[str], List[str]]: # fmt: on """ suggest userdict terms. >>> filename = "data/hlm-ch1-en.t...
48a7f9fb32b34b1e3cb0b762131d28a336594482
3,603,911
def ferret_result_limits(efid): """ Abstract axis limits for the shapefile_writexyval PyEF """ return ( (1, 1), None, None, None, None, None, )
ba5c3d3a5760b11384b551c08464c16587e58437
3,603,912
def refresh(): """Pull fresh data from Open AQ and replace existing data.""" DB.drop_all() DB.create_all() # TODO Get data from OpenAQ, make Record objects with it, and add to db for n in m_list: db_date = n[0] db_value = n[1] new_rec = Record(datetime=db_date, value=db_value...
5e53e5de6e458c5f78d6764f6d7fc41230c1587f
3,603,913
def get_provider_context(client=None): """Read the manager provider context.""" if client is None: client = get_rest_client() context = client.manager.get_context() return context['context']
d98112cece070abb88a368f224d9ceacb9cdc24a
3,603,914
def has_provider(provider): """Verifies that module has support for requested API provider.""" return provider.lower() in API_ALL
26215c8f664fdc54b2f625b0431723641200a5ce
3,603,915
import os def mkdir(path_name): """ make dirs if not exist Args: path_name: dir path Returns: path """ if not os.path.exists(path_name): os.makedirs(path_name) return path_name
1a67d78870bed50a59e49a290ff57c6d6e58e2d4
3,603,916
def get_chisq_kctl(): """ Obtain chisq from kctl """ output_filen = ofile_for_fitresult read_on = False with open(output_filen, "r") as f: for l in f: if l.find('Results') != -1: read_on = True if read_on and (l.find('Chi**2 (normalized)') != -1): ...
4a2f49686e984e30d497412ba20a446c51707a6a
3,603,917
import re def get_converted_games(): """ Loads converted game movements CSV files and returns list of games to get event descriptions from """ # Try converted directory..maybe user removed csv directory to free up memory potential_game_dirs = [CONFIG.data.movement.converted.dir] names = [] ...
2b1d4301039f13e7e88d0d3e152da689a2785942
3,603,918
def configmap(): """ https://kubernetes.io/docs/tasks/configure-pod-container/configmap/ """ return { 'apiVersion': 'v1', 'kind': 'ConfigMap', 'metadata': { 'name': 'testcfgmap-game-config' }, 'data': { 'game.properties': "enemies=aliens\n...
aadc00e8046be12370202f82adca12b222b0696f
3,603,919
def _bt_model_fn( features, labels, mode, head, feature_columns, tree_hparams, n_batches_per_layer, config, closed_form_grad_and_hess_fn=None, example_id_column_name=None, # TODO(youngheek): replace this later using other options. train_in_memory=False, name='boosted_...
ac1c90b6c45b21e3c0e948213b2a3492a72be2db
3,603,920
def node(auth, node): """Get node by ID or the ``uuid`` key out of a dictionary.""" if isinstance(node, dict): node = node['uuid'] response = API.get(auth, '/v1/nodes/{}'.format(node)) return response.json()
96650abc8c8482c2a6c685a4cb7c7a8af0e9fefe
3,603,921
def identify_contentType(url): """ Given a URL for a content, it identifies the type of the content :param url(str): URL :returns: Type of the content """ extensions = ['mp3', 'wav', 'jpeg', 'zip', 'jpg', 'mp4', 'webm', 'ecar', 'wav', 'png'] if ('youtu.be' in url) or ('youtube' in url): ...
720a9ea9adaab547309f61b6858b0eb19ddebafe
3,603,922
def wrap_annotation(annotation): """Wraps a dict as an instance of the registered Annotation model class. Arguments: - `annotation`: a dictionary-like object containing the model data """ request = get_current_request() cls = request.registry.queryUtility(interfaces.IAnnotationClass) resul...
b49962de4ad4bb06d48cbec02a232f8d1401b38a
3,603,923
def get_L_dash_HB_wall_floor_90_IS(): """主開口方向から時計回りに90°の方向の外気に面した壁と床の熱橋長さ (m) Args: Returns: float: 主開口方向から時計回りに90°の方向の外気に面した壁と床の熱橋長さ (m) """ return get_table_3(62, None)
2675decfd323d679d38452c1c9719f4e0898a3c9
3,603,924
import functools def profile_function(game, function, profiles, num_resamples, *, percentiles=None, processes=None): """Compute a function over profiles Parameters ---------- game : SampleGame The sample game to bootstrap the function value over. function : Game, prof...
20971cd84a0e35f88f2a13ac56e0ebe6266cc0b2
3,603,925
def do_loop_kernel(indx): """ This is where each spectrum is fitted over N iterations of baseline and spectral model estimation and optimization respectively. We return the optimized spectral model parameters and index of the voxel so we can sort the results list in the main process after they ...
71b2b4eb54e00e9ee0e5ba6949cbfda287c5d128
3,603,926
def nice_frequency(frequency): """return a string of the frequency with SI unit and a reasonable number of digits""" if frequency < 1e3: return "%dHz" % frequency elif frequency < 10e3: return "%.3fkHz" % (frequency / 1e3) elif frequency < 100e3: return "%.2fkHz" % (freque...
8fefa58236c57878be9f051e9cbfff85d398f87c
3,603,927
def stack(x, filters, num_blocks, block_fn, use_bias, stride1=2, name=None): """A set of stacked residual blocks. Arguments: x: input tensor. filters: integer, filters of the bottleneck layer in a block. use_bias: boolean, enables or disables all biases in conv layers. num_blocks: integ...
1ed366778a5abba4e05c070da05e3c87cbd92560
3,603,928
import http async def get_user(access_token: str) -> dict: """Coroutine to fetch User data from discord using the users `access_token`""" async with http.session.get( "%s/v6/users/@me" % DISCORD_ENDPOINT, headers={"Authorization": "Bearer %s" % access_token}, ) as response: return ...
71796cb8ce70759de902ed9fad17f64a092b6772
3,603,929
def mel2hz(mel): """Convert a value in Mels to Hertz :param mel: a value in Mels. This can also be a numpy array, conversion proceeds element-wise. :returns: a value in Hertz. If an array was passed in, an identical sized array is returned. """ return 700*(10**(mel/2595.0)-1)
c61d0ce485fe5ca241cfca358a51d1aba4bf4462
3,603,930
def food_finder(board_food, you_id, board_snakes): """ This function should return food Coords in a list = [x,y] this food will be the food that gives the value to the following formula: this works because the value with if no food on board then will return [0,0] and a flase on the boolian Input:...
1d35ecb83b6895ee1093291cde5f2190460fdc99
3,603,931
def row_as_diagonal(a): """ Returns the per row diagonal matrices of the given array. Parameters ---------- a : array_like Array to perform the diagonal matrices computation. Returns ------- ndarray References ---------- :cite:`Castro2014a` Examples ------...
d33be00c44998273bd17ed9b91a54b86d98d29b4
3,603,932
def compute(x, y): """Compute sum of passed in arguments :param x: Integer (operand 1) :param y: Integer (operand 2) :rtype: Integer """ if x > 100 or x < 0 or y > 100 or y < 0: raise ValueError("Passed in value out of bounds") return x + y
beb518f7f9b23f1fa5dc7ac82386a9cbf34a5cd5
3,603,933
def is_weaviate_object_url(url: str) -> bool: """ Checks if the input follows a normal Weaviate 'beacon' like this: 'weaviate://localhost/28f3f61b-b524-45e0-9bbe-2c1550bf73d2' Parameters ---------- input : str The URL to be validated. Returns ------- bool True if 'i...
d9d435e75eec3068aca75db33ee776917fd3bfd2
3,603,934
import requests def response_to_resources(resources_response: requests.Response) -> pd.DataFrame: """ Extracts an API response into an dataframe containing all resources. :param resources_response: a response from the API to the resources request :type resources_response: requests.Response :retur...
2a5b18becd9d1434eebacc9cbd1f563ed08fb655
3,603,935
def config_value(name): """Return callable that returns config value if it exists.""" def get(): try: return config.get('yourls', name) except (NoOptionError, NoSectionError): return None return get
27dedaa666b21636daaf66b0eda59c07d45ba829
3,603,936
from numpy import zeros, sort, array, where def find_ridges(obj, only_min=True, max_guess=600.0, min_guess=1750.0, fast=True): """Finds the ridges of minimal and maximal values within e.g. temperature time series. That is, where the warming changes to a cooling or vice versa. The ridges can then be plot in a...
a8c2128c71b43106a64b5c4d727030e9316e2120
3,603,937
import re def _resolve_operator(statistic: str): """Find the operator corresponding to the statistic.""" statistic = statistic.lower() kwargs = {} # special cases if statistic == 'std': logger.warning( "Changing statistics from specified `std` to `std_dev`, " "sinc...
b83c3bd9daf1c248b00defbc05d9b802db7f1d3a
3,603,938
def crystal_matrix_to_lattice_parameters(crystal_matrix): """ This function takes any strained crystal lattice matrix and return the lattice parameters **Required Inputs crystal_matrix = crystal lattice matrix ([[Vxx,Vxy,Vxz], [Vyx,Vyy,Vyz], ...
b344d54a3177122c13290649777fbd7aa6ed8729
3,603,939
from datetime import datetime def about(): """Renders the about page.""" return render_template( 'about.html', title='About', year=datetime.now().year )
910a8e408caafe5682c4ef869d690fdad381266d
3,603,940
def retrieve_redcap_subjects(url, token, fields, max_time=30): """Read the list of subjects from the REDCap instance using the API""" data = redcap_api_call(url, token, content='record', fields=fields, max_time=max_time) # print("subjects: {}".format(data)) return data
123304e0547c41d522259d8c06f97c75129c29a4
3,603,941
import os from pathlib import Path import csv import statistics def Cubenorm_Filter( cubenorm_tab: os.PathLike, outfile: os.PathLike, pause=False, boxfilter=5, divide=False, chan=None, ) -> tuple: """Returns a two-tuple with the standard deviation of the filtered average and a boolean ...
7d030c8fbc360ae41229c655b9ca35e497a405a3
3,603,942
def host_delete_route(host_id): """delete host""" form = ButtonForm() if form.validate_on_submit(): db.session.delete(Host.query.get(host_id)) db.session.commit() return redirect(url_for('storage.host_list_route')) return render_template('button-delete.html', form=form)
f0e031fef11d0933774a11abffdfa2afdd147f44
3,603,943
import json def predict_img_class(img, device_opt): """Get image class determined by network inference running on GPU.""" # Copy input image data to GPU workspace.FeedBlob("data", img, device_option=device_opt) workspace.RunNet("AlexNet", 1) # Fetch results of AlexNet's last layer output -- prob...
64198940da1c8b8cd69d513e05786f4fa38deca2
3,603,944
def get_subject_id(subject_code: str) -> str: """This function gets the subject ID from the database Args: subject_code (str): Subject code from the subject to get the ID. Returns: subject_id (str): Subject ID from the subject. """ query = "select idMaterias from Materias where Mat...
eab6baa9f9d085f8e83fd03c9059043a0630fbd7
3,603,945
def pid_info(output_line): """ Take a line of 'ps -o pid,comm' output and return the PID number and name. The line looks something like: 9108 orterun or 10183 daos_server Need both items. Return a tuple (name, pid) Note: there could be leading spaces on the pid. """ info =...
479c51e562b7bbeb7e812fad4b2cb1f771e2e830
3,603,946
import os def list_of_ietf_drafts(directory, debug_level): """ Returns the list of files in a directory # status: troubleshooting done :param directory: directory to search for drafts :return: list of found drafts """ only_files = [f for f in os.listdir(directory) if os.path.isfile(os.pat...
79690df2ad61fe9546f05de3490915403753ee74
3,603,947
import json def get_search_subawards_ajax(request): """Provide full search subaward data as JSON to improve render time""" query = get_search_filters_query(request, 'subaward') subawards = Subaward.objects.filter(query).distinct() response = {'data': []} for subaward in subawards: ...
f7c40f91b52333671a2a2e698641cba656e0ae70
3,603,948
def reset_model_using_weights(model_wireframe, weights): """A tool to load flattened weights into model wireframe.""" all_boundaries = { 0: [(0, 16), (16, 160)], 1: [(160, 176), (176, 2480)], 2: [(2480, 2496), (2496, 4800)], 3: [], # GlobalAvgPool has no params 4: [(4800, 4810), (4810...
60771eb220a67c04119f86edb36be741cdbece0d
3,603,949
def memory_function(op, is_regularization, num_alive_inputs, num_alive_outputs, reg_inputs, reg_outputs, batch_size=1): """Calculates memory cost or regularization loss for an op. Args: op: A tf.Operation. is_regularization: Boolean indicating whether to calculate regularization l...
9297c83d62dda928dd9eba619a3f509a80ef75d2
3,603,950
def unshift(array, *items): """Insert the given elements at the beginning of `array` and return the modified list. Args: array (list): List to modify. items (mixed): Items to insert. Returns: list: Modified list. Warning: `array` is modified in place. Example:...
d5177e751c3ce8f95b3c51cfe09e99a50d2561c2
3,603,951
import torch from typing import Optional from typing import List from typing import Union def accuracy( tp: torch.LongTensor, fp: torch.LongTensor, fn: torch.LongTensor, tn: torch.LongTensor, reduction: Optional[str] = None, class_weights: Optional[List[float]] = None, zero_division: Union...
3292ba1cf2c344167958b308d5f69c95594b5991
3,603,952
import torch def test_conv2d_memory_analytical(): """Compute the memory of activation analytically""" # arguments and test data N, H, W, CI, CO, kernel_size, stride, padding, dilation, groups = 256, 28, 28, 256, 256, 3, 1, 1, 1, 1 data_np = np.random.randn(N, CI, H, W).astype('float32') weight_np...
b3485db912c7f4d21aae30f7cf1e65ba05d3c379
3,603,953
import difflib def managed(name, enabled=True, **kwargs): """ Ensure that the named interface is configured properly. name The name of the interface to manage type : eth Type of interface and configuration .. versionchanged:: 3002 enabled Designates the state of...
c06581d27b04993d0a14fff4d2464220a0626027
3,603,954
def update_dimension( response: Response, answer_id: int, request: AnswerRequestSchema, db: Session = Depends(get_database_connection), token: str = Depends(token_bearer) ): """ Update an existing dimension. """ result = VerifyToken(token.credentials).verify() if ...
f378c6f9b97f14c3d51af04e450a967d9aa6ab1e
3,603,955
def load_MACHO_example(): """lightcurve of 2 bands (R, B) from the MACHO survey. The Id of the source is 1.3444.614 Notes ----- The files are gathered from the original FATS project tutorial: https://github.com/isadoranun/tsfeat """ return load_MACHO("lc_1.3444.614")
cd34c640d6909f5b6d49cb033af5054e5871b1a9
3,603,956
def quarter(expr): """ --------------------------------------------------------------------------- Returns calendar quarter of the specified date as an integer, where the January-March quarter is 1. Parameters ---------- expr: object Expression. Returns ------- str_sql SQL expression. """ expr = ...
a9c639ee1fa8a477a03f062473f11efcce769608
3,603,957
def get_index(corners, i, jk): """ Find the index that angle with corners i, jk has inside the corners set. """ if type(jk) != list: jk = list(jk) assert corners.shape[1] == 3 sol = np.where(np.bitwise_or(np.all(corners == [i] + jk, axis=1), np.all(corne...
7fa85c7263a932d076da023adbb5b8117fa00bce
3,603,958
from typing import Container def thread(msglist): """([Message]) : {string:Container} The main threading function. This takes a list of Message objects, and returns a dictionary mapping subjects to Containers. Containers are trees, with the .children attribute containing a list of subtrees, so ca...
d5ee2eceef11c68d6fe1aa3b7ef5bcf2c14a81b8
3,603,959
def remove_flow_overlap(df, aggregate_flow, contributing_flows): """ Quantity of contributing flows is subtracted from aggregate flow and the aggregate flow quantity is updated. Modeled after function of same name in stewicombo.overlaphandler.py :param df: df, FBA format :param aggregate_flow: s...
5e6155010559d084f6f08f6cc9baf3716374e7f6
3,603,960
def getChessTiles(a, lines_x, lines_y): """Split up input grayscale array into 64 tiles stacked in a 3D matrix using the chess linesets""" # Find average square size, round to a whole pixel for determining edge pieces sizes stepx = np.int32(np.round(np.mean(np.diff(lines_x)))) stepy = np.int32(np.round(...
56f3b839df25563d1d2b9204d99025c12f6ad552
3,603,961
def build_model(label, X, model_info, inner_clf, metric_name, metric_func): """build_model :param X: :param y: :param target_type: """ FUNC_MAPPING = { "categorical": build_predictor, "categorical_uniform": build_uniform_predictor, "numerical": build_predictor, "...
f43989e8de6fa08acd84fd82b4f582dbd10f6573
3,603,962
import re def python_cat_to_r_cat(python_df): """ Return the same dataframe with the 3rd level of the multiindex ("Category") updated so that the python-style name (e.g. race[T.3]) is converted to r-style (e.g. race3) """ re_str = re.compile(r"(?P<var_name>.+)\[T\.(?P<cat_name>.+)\]") df = pyt...
c0a248978dca2c169e6a0f3acbe41c9ab53998c0
3,603,963
from typing import List from typing import Tuple def two_columns(pairs: List[Tuple]) -> str: """ Join pairs (or more) of strings to a string. :param pairs: List of tuples of strings :return: String separated by newlines """ return '\n'.join([' '.join(map(str, t)) for t in pairs])
810fdab52b4641c32f54c6adc772f8352b8f2ae6
3,603,964
import functools def preprocess_tvqa(record, config): """ there are 7 frames, each with audio and associated text there is also an initial "frame" that doesn't have any image, but does have metadata where we stick the Q. :param record: :param config: :return: """ k2f = { 'id': ...
3bd516f890cfcf3282d38e030e66340f48c4226e
3,603,965
import os def get_confs_from_local(repo_abs_dir): """ repo_abs_dir: abs dir for the repo return list ontology relative dirs """ ont_files = [] if repo_abs_dir[-1] == os.sep: repo_abs_dir = repo_abs_dir[:-1] num_of_parent_dirs = len(full_path_split(repo_abs_dir)) dolog("...
fe3c30b0658d251ec146dbe12d416ed9a1afb96f
3,603,966
from datetime import datetime import binascii import json def addCredit(): """ add credit request :return: JSON request tous les capteurs de la classe """ nowDt = datetime.datetime.now() now = round(nowDt.timestamp()) dict_req = request.get_json() term_id = dict_req.get('terminal_id', ...
37ddf66205a0554dd2c29b7bdd021f5ff3ebe72c
3,603,967
def get_record_as_json(cur, tablename, row_id): """ Get a single record from the database, by id, as json. """ # IMPORTANT NOTE: Only use this function in trusted input. Never on data # being created by users. The table name is not escaped. q = """ SELECT row_to_json(new_with_table) F...
00521ae582a013f97b77494944e0f6e04069ed05
3,603,968
def stream_handler_set_stream(stream_handler_instance, stream): """ Backport of StreamHandler.setStream() for Python 2 """ if stream is stream_handler_instance.stream: result = None else: result = stream_handler_instance.stream stream_handler_instance.acquire() try: ...
0da047fc1a4e7c17e91d51769ede549551ab9813
3,603,969
def key_press(name, key_index, ctrl=False, shift=False, alt=False, super=False, repeat=True): """ Invisible widget that waits for a given key to be pressed. No widget must be active at the time to prevent triggering hotkeys by editing text fields. Key codes are specified by glfw, e.g. `glfw.KEY_A`, or `glf...
a441f9e1d56c4e81224078b34ee24d4522101b7a
3,603,970
def zip_(self, iterable): """A zip object yielding tuples until an input is exhausted. >>> [1, 2, 3].zip([1, 2, 3]) [(1, 1), (2, 2), (3, 3)] >>> [1, 2, 3].zip([3, 2]) [(1, 3), (2, 2)] """ return list(zip(self, iterable))
b71ea3414a7817959e5b58ad7cd476b7caa3c770
3,603,971
def Pre(*content, **attrs): """ Wrapper for pre tag >>> Pre().render() '<pre></pre>' """ return KWElement('pre', *content, **attrs)
7bc68152449c6180aa69abe4174001156922fcea
3,603,972
def is_main_thread(*args): """ is_main_thread() -> bool Are we running in the main thread? """ return _ida_pro.is_main_thread(*args)
ae8f5dd5f1b6d1681848680b5d0987f0ddf1574d
3,603,973
def _tosg(data): """Draft helper function to convert data we have into SG suitable format TODO: Remove once kernels are implemented here (or, possibly for non-kernel solvers, modify?) """ if __debug__: debug("SG_", "Converting data for shogun into RealFeatures") features = shogun.Feat...
f11f0794e172d6be9b31c0acdd0551488d608f68
3,603,974
def segno(x): """ Input: x, a number Return: 1.0 if x>0, -1.0 if x<0, 0.0 if x==0 """ if x > 0.0: return 1.0 elif x < 0.0: return -1.0 elif x == 0.0: return 0.0
5caccfa037b2972755958f647f009660aefae59d
3,603,975
def pdp_importances(model,X,numx=30,normalize=True): """ Use standard PDP then mean center and take average magnitude as impact. Return an importance dataframe """ pdpxs,pdpys = ice.friedman_partial_dependences(model, X, numx=numx, mean_centered=True) I = pd.DataFrame(data={'Feature': X.columns}...
f2780a03f905cf37b348be27f74424411d017f98
3,603,976
def patch_options(): """Used by the PATCH /options API operation""" LOGGER.debug("PATCH /options invoked patch_options") try: data = connexion.request.get_json() except Exception as err: return connexion.problem( status=400, title="Error parsing the data provided.", ...
548c69f3312f2f871e603d91c976c179711374b7
3,603,977
def recursive_fibonacci(n: int) -> int: """Return the nth number of the fibonacci sequence""" if n <= 1: return n else: return recursive_fibonacci(n - 1) + recursive_fibonacci(n - 2)
c45823648833d80f6d0c2ff815bbea464775e6f1
3,603,978
from typing import Iterable def calculate_row_weights( row: Iterable, param_weights: dict, vars_to_optimize: dict ) -> float: """Used to select random rows of parameter combinations using individual parameter weights. Args: row (Iterable): Series of parameters, with parameter names as index. ...
458cb546fd9fe6193e7cce66b5187ce8ea93369b
3,603,979
import pyWAPOR.Functions.Processing_Functions as PF import os def RetrieveData(Date, args): """ This function retrieves CHIRPS data for a given date from the ftp://chg-ftpout.geog.ucsb.edu server. Keyword arguments: Date -- 'yyyy-mm-dd' args -- A list of parameters defined in the DownloadData...
a079021afde90181e92687d8338e1fc7e1869e35
3,603,980
def swap_xyz_string(xyzs, permutation): """ Permutate the xyz string operation Args: xyzs: e.g. ['x', 'y+1/2', '-z'] permuation: list, e.g., [0, 2, 1] Returns: the new xyz string after transformation """ if permutation == [0,1,2]: return xyzs else: n...
efd0eb400be0dca26b49c3b2d3a04a385a2fc6e4
3,603,981
def _get_input_files(variable, config_user): """Get the input files for a single dataset.""" # Find input files locally. input_files = get_input_filelist( variable=variable, rootpath=config_user['rootpath'], drs=config_user['drs']) # Set up downloading using synda if requested. ...
1365cfd6f6e217a563c9bae807a3f02b1080d1a1
3,603,982
import time import torch import torchvision def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, labels=()): """Performs Non-Maximum Suppression (NMS) on inference results Returns: detections with shape: nx6 (x1, y1, x2, y2, conf, cls) """ nc = ...
c108092bf75d31053e51132d68403a1d1c03ae5e
3,603,983
def distance(seq1, seq2, dist=sqeuclidean): """ Utility function for calculating the distance between two sequences, i.e. between two time-series or their subsequences. :param seq1: First sequence :param seq2: Second sequence :param dist: Distance functor to use for calculating distances between points ...
aaaa90a7e89daeb1371a7ada5087f81fdaeba583
3,603,984
from datetime import datetime def build_history(owner, repo, name=None, since=None, issues=None, url=None, max_issue=None, releases=None, unpublished=False, existing_history=None, skip_issues=None, fLOG=None): """ Returns an history of a module. @param owner ...
b8cd3b6c9c5fd1d24c0a9eaf2a4075357b7b8243
3,603,985
import json def geojson_to_wkt(geojson): # type: (Union[str, dict]) -> str """Converts GeoJSON (serialize or raw) to a WKT string.""" if isinstance(geojson, str): raw_geojson = json.loads(geojson) # type: dict elif isinstance(geojson, dict): raw_geojson = geojson else: rai...
501555f4df460ea8c6f260d640f9cbd4c0fe525b
3,603,986
def affine_softplus(real, lo=0, ref=1): """Maps real numbers to (lo, infinity), where 0 maps to ref.""" if not lo < ref: raise ValueError('`lo` (%g) must be < `ref` (%g)' % (lo, ref)) shift = inv_softplus(tf.cast(1., real.dtype)) scale = (ref - lo) * tf.nn.softplus(real + shift) + lo return ...
53dbb64717beb53088b962744954bf4fa1b0136a
3,603,987
from typing import List from typing import Dict import tqdm def rouge_fn(targets: List[List[str]], predictions: List[str]) -> Dict[str, float]: """Computes ROUGE by taking the max ROUGE-N per reference and N.""" # Following strategy from https://www.aclweb.org/anthology/W04-1013/. # Identify best r...
fb3cc06da2392431ead2c61247ca3745f2456219
3,603,988
def speed_2_pace(speed): """Convert speed in km/hr to pace in s/km""" return 60*60/speed
25379049e98622ec5888461a9f6455be399d5f5a
3,603,989
def vortex(xx, yy, **kwargs): """ analytical function that defines the domain fmsk < 0 : solid fmsk == 0: boundary fmsk > 0 : fluid """ x0 = kwargs["x0"] y0 = kwargs["y0"] d = kwargs["d"] if "vtype" in kwargs: vtype = kwargs["vtype"] else: vtype = "gaussian" ...
810f3837ea588833e683356b44256a5e44b3979d
3,603,990
def computeNumericalGradient(J, theta): """Computes the gradient using "finite differences" and gives us a numerical estimate of the gradient. numgrad = computeNumericalGradient(J, theta) computes the numerical gradient of the function J around theta. Calling y = J(theta) should return the function...
f028612304972dfbf3f3e576c135f8d765724e08
3,603,991
import random def load_label(directory, number=None): """ 导入指定目录的所有图片的标签,不导入图片 :param directory: :return: """ names = list_image_name(directory) random.shuffle(names) if number is not None: names = names[:number] labels = [] for name in names: label = name.split...
a6ee5daf959a86528c1f245115d5c5dbf8b575e9
3,603,992
def quantize_uniform_to_n_bits_(arr, nb_bits): """Reduce each component in an array to a maximum number of bits in-place. This operation sets the ``8-B`` highest frequency (rightmost) bits to zero. For ``B`` bits this is equivalent to changing each component's intensity value ``v`` to ``v' = v & (2**(8...
009b1c3545af37e065072545268feadc3d39397d
3,603,993
def median_frequency(sig, FS): """Compute median frequency along the specified axes. Parameters ---------- sig: ndarray input from which median frequency is computed. FS: int sampling frequency Returns ------- f_max: int 0.50 of max_frequency using cumsum. """ ...
7ef893aaee2b213feaf6f8aa452a4f9ef6236813
3,603,994
def unused(attr): """ This function checks if an attribute is not set (has no value in it). """ if isinstance(attr, (Required, Recommended)) or attr is None: return True else: return False
fdab32aaafb59220d73e7a26827143036dccbab5
3,603,995
import numpy def stat_decumulate(rec): """Converts the stat record from the cumulative (original) to per-block quantities. Returns a copy object containing the decumulated quantities.""" rslt = rec.copy() #print rslt t_elapsed = rslt['T_elapsed'] # Unfortunately numpy does not have a converse function o...
1a7a10ef6836fc79c962036a8b7dfa0c32260380
3,603,996
def contiguous_regions(condition): """Finds contiguous True regions of the boolean array "condition". Returns a 2D array where the first column is the start index of the region and the second column is the end index.""" # Find the indicies of changes in "condition" d = np.diff(condition) idx, =...
fa94d3c5637f6cd8262365e4764d23589fa266dc
3,603,997
import PIL def find() -> None: """Function for rendering image""" path = input("Enter the Path to the photo =") try: Image = PIL.Image.open(path) except FileExistsError: pass print(path, "The given path is not valid") return Image
777107631245497b3416a384dc0a1c30ab25c629
3,603,998
import glob import os def probetimes(mask, wd='.'): """ Parse all files matching PROBE*.loss (or a user-supplied mask for glob.glob()) and return a probe timing dictionary, for ONLY the reference (pid=0) particle. Parameters ---------- mask - file mask compatible with glob.glob() for probe f...
b8dcbb191725ef0f3ea8eabebbbeac1cd8a04545
3,603,999