content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def vectorized_range(start, end): """ Return an array of NxD, iterating from the start to the end""" N = int(np.max(end - start)) + 1 idxes = np.floor(np.arange(N) * (end - start)[:, None] / N + start[:, None]).astype('int') return idxes
cef2304639dbac3c1a1dfbd9ae928f813bd65b05
32,200
import random def stratified(W, M): """Stratified resampling. """ su = (random.rand(M) + np.arange(M)) / M return inverse_cdf(su, W)
4f1ceb6840240178df312fee266fe612abb3193f
32,201
def is_configured(): """Return if Azure account is configured.""" return False
5662656b513330e0a05fa25decc03c04b5f367fa
32,202
def box_strings(*strings: str, width: int = 80) -> str: """Centre-align and visually box some strings. Args: *strings (str): Strings to box. Each string will be printed on its own line. You need to ensure the strings are short enough to fit in the box (width-6) or the results wi...
b47aaf020cf121b54d2b588bdec3067a3b83fd27
32,203
import traceback def exceptions(e): """This exceptions handler manages Flask/Werkzeug exceptions. For Renku exception handlers check ``service/decorators.py`` """ # NOTE: Capture werkzeug exceptions and propagate them to sentry. capture_exception(e) # NOTE: Capture traceback for dumping it ...
574c97b301f54785ae30dbfc3cc5176d5352cb82
32,204
import torch def top_k_top_p_filtering(logits, top_k, top_p, filter_value=-float("Inf")): """ top_k或top_p解码策略,仅保留top_k个或累积概率到达top_p的标记,其他标记设为filter_value,后续在选取标记的过程中会取不到值设为无穷小。 Args: logits: 预测结果,即预测成为词典中每个词的分数 top_k: 只保留概率最高的top_k个标记 top_p: 只保留概率累积达到top_p的标记 filter_value: ...
74cf4a6cf4622ad1c9b124089cd84ddb07bdb7be
32,205
def get_alb(alb_name, aws_auth_cred): """ Find and return loadbalancers of mentioned name Args: alb_name (str): Load balancer name aws_auth (dict): Dict containing AWS credentials Returns: alb (dict): Loadbalancer details """ client = get_elbv2_client(aws_auth_cred) ...
a31ae3067d96008622b43c57ffd1b0de74eceaa0
32,206
def align_left_position(anchor, size, alignment, margin): """Find the position of a rectangle to the left of a given anchor. :param anchor: A :py:class:`~skald.geometry.Rectangle` to anchor the rectangle to. :param size: The :py:class:`~skald.geometry.Size` of the rectangle. :param alignment: T...
2af1c6175960313958cc51d0180ebc4f6ed9dc41
32,207
def quickdraw_to_linestring(qd_image): """Returns a Shapely MultiLineString for the provided quickdraw image. This MultiLineString can be passed to vsketch """ linestrings = [] for i in range(0, len(qd_image["image"])): line = zip(qd_image["image"][i][0], qd_image["image"][i][1]) lin...
39957b9a36a59b33a2fb5abc91f7479c946515a2
32,208
def get_device_details(): """TODO(jordanhuus): add description """ ptpTransport = PtpUsbTransport( PtpUsbTransport.findptps(PtpUsbTransport.USB_CLASS_PTP)) bulk_in, bulk_out, interrupt_in = \ PtpUsbTransport.retrieve_device_endpoints( PtpUsbTransport.findptps(PtpUsbTransport....
ec98583681a5aefa0701a7b3695210f2f78b4845
32,209
import functools def build(image_resizer_config): """Builds callable for image resizing operations. Args: image_resizer_config: image_resizer.proto object containing parameters for an image resizing operation. Returns: image_resizer_fn: Callable for image resizing. This callable always takes ...
75df1c37397e88322113aa8822d60053ae54981d
32,210
from typing import Optional from typing import Tuple def plotly_protein_structure_graph( G: nx.Graph, plot_title: Optional[str] = None, figsize: Tuple[int, int] = (620, 650), node_alpha: float = 0.7, node_size_min: float = 20.0, node_size_multiplier: float = 20.0, label_node_ids: bool = Tr...
4aae1ce763daa06627fe43e31780fa61cd1886a4
32,211
import os def get_configuration_route(model_name: str) -> str: """Gets the prediction configuration file of a model. Args: model_name (str): Name of the model Raises: ModelToLoadNotFoundError: The model to load could not be found or opened. Returns: str: Evaluati...
5e31235705a75bf2cc043978aaf4428c620e6ea9
32,212
def mag_scale_rel_to_hazardlib(mag_scale_rel, use_default=False): """ Returns the magnitude scaling relation in a format readable by openquake.hazardlib """ if isinstance(mag_scale_rel, BaseMSR): return mag_scale_rel elif isinstance(mag_scale_rel, str): if not mag_scale_rel in SC...
7db46083d4c05e3f53b4a5d064c923937bb5fe2a
32,213
import toml def write_config(conf): """ write_config(conf) function dumps app configuration to TOML file $NOTESDIR/config :param conf: Dictionary containing configuration (see_default_config as a sample structure) :return bool: returns True on successful write of ...
292db9faf278cbc8fae19fe5b18eead13e5d61d0
32,214
import regex import tokenize def __get_words(text, by_spaces): """ Helper function which splits the given text string into words. If by_spaces is false, then text like '01-02-2014' will be split into 3 separate words. For backwards compatibility, this is the default for all expression functions. :...
289d7cc58d165355a4e5a25db016dbe2e6aa74ec
32,215
from typing import Any def gera_paragrafo(data: pd.DataFrame) -> pd.DataFrame: """docstring for gera_paragrafo""" data[["div_sup", "par"]] = data.location.str.split(".", n=1, expand=True) data.dropna(inplace=True) j: Any = data.groupby(["author", "text", "file", "div_sup", "par", "genero"]).agg( ...
04285d5df307e87b8adc389cf2f03d9ef9b44276
32,216
def _parse_boolean(xml_boolean): """Converts strings "true" and "false" from XML files to Python bool""" if xml_boolean is not None: assert xml_boolean in ["true", "false"], \ "The boolean string must be \"true\" or \"false\"" return {"true": True, "false": False}[xml_boolean]
6d9d1b617f8935d1684bd24bbea06d00ca2a5b4a
32,217
def to_heterogeneous(G, ntypes, etypes, ntype_field=NTYPE, etype_field=ETYPE, metagraph=None): """Convert a homogeneous graph to a heterogeneous graph and return. The input graph should have only one type of nodes and edges. Each node and edge stores an integer feature as its type ID ...
f1792d78e4b94c5f3d4f72ef6cfcbcb14c7d1158
32,218
def Solution(image): """ input: same size (256*256) rgb image output: the label of the image "l" -> left "m" -> middle "r" -> right "o" -> other(NO target) if no target detected, return "o", which is the initial value """ #initial two point for locatate the ...
11fb49c96cb7cbfdfb522d6794f148cd6354dcf9
32,219
def index_to_tag(v, index_tag): """ :param v: vector :param index_tag: :return: """ idx = np.nonzero(v) tags = [index_tag[i] for i in idx[0]] return ' '.join(tags)
ebf30632bbf8a7b399461b191c33f345f04c4cc2
32,220
import time import torch import sys def train(train_loader, model, criterion, optimizer, epoch, opt): """one epoch training""" model.train() losses = AverageMeter() end = time.time() for idx, (train_x, labels) in enumerate(train_loader): train_x = train_x.cuda() labels = labels.cu...
482b8c864cb565891b8d9a2b288fb1f64de4db16
32,221
def first_phrase_span(utterance, phrases): """Returns the span (start, end+1) of the first phrase from the given list that is found in the utterance. Returns (-1, -1) if no phrase is found. :param utterance: The utterance to search in :param phrases: a list of phrases to be tried (in the given order) ...
f3be7bd976c60467bcf51edfb15d3736e00568a8
32,222
from datetime import datetime def parse_date(value): """Parse a string and return a datetime.date. Raise ValueError if the input is well formatted but not a valid date. Return None if the input isn't well formatted. """ match = date_re.match(value) if match: kw = {k: int(v) for k, v i...
b32cc64bab460e1384492b7cb694b8263431625f
32,223
import scipy def construct_Dfunc(delays, plot=False): """Return interpolation functions fD(t) and fdD(t). fD(t) is the delay between infection and reporting at reporting time t. fdD(t) is its derivative. Parameter: - delays: tuples (time_report, delay_days) - plot: whether to generate a plo...
ee6acbc265d8020815ac2e9cd77fe74a6ff9d5f7
32,224
def deimmunization_rate_80(): """ Real Name: b'deimmunization rate 80' Original Eqn: b'Recovered 80/immunity time 80' Units: b'person/Day' Limits: (None, None) Type: component b'' """ return recovered_80() / immunity_time_80()
9221343889ba05d93671102e72ef70a5efd40a5a
32,225
def connect_to_lightsail(): """ Uses Paramiko to create a connection to Brendan's instance. Relies on authetication information from a JSON file. :return SFTP_Client: """ return open_sftp_from_json(JSON_PRIVATE_DIR / 'lightsail_server_info.json')
fb0f74fe58e5a99ca93737415b931018be4d67d7
32,226
def coleman_operator(c, cp): """ The approximate Coleman operator. Iteration with this operator corresponds to time iteration on the Euler equation. Computes and returns the updated consumption policy c. The array c is replaced with a function cf that implements univariate linear interpolatio...
dee76b425b5a81799fd1677f2b9ca9889f4a813c
32,227
def generate_scanset_metadata( image_set_dictionary, html_base_path, session_id ): """This is passed a set of NII images, their PNG equilvalents, and an html base path, and then it generates the metadata needed """ cur_subj_info = {} """need to think through the data structure a bit more.... but can always adjust l...
4fa326018fc64f9ef2f7974d850256fdfa30f8f6
32,228
def read_error_codes(src_root='src/mongo'): """Define callback, call parse_source_files() with callback, save matches to global codes list.""" seen = {} errors = [] dups = defaultdict(list) skips = [] malformed = [] # type: ignore # define validation callbacks def check_dups(assert_loc...
46f64798fd3e7010a96e054600557464cf99eade
32,229
def filter_check_vlan_number(value): """ Function to check for a good VLAN number in a template :param value: :return: """ error = f'{value} !!!! possible error the VLAN# should be between 1 and 4096!!!!' if not value: # pylint: disable=no-else-return J2_FILTER_LOGGER.info('filter_c...
6c9e060b13f49048f056b72a6def2d1d15241a74
32,230
def _sanitize(element) -> Gst.Element: """ Passthrough function which sure element is not `None` Returns `Gst.Element` or raises Error """ if element is None: raise Exception("Element is none!") else: return element
f07062474dcf2671cb1c3d13a7e80d9ee96b9878
32,231
import pytz def mean(dt_list): """ .. py:function:: mean(dt_list) Returns the mean datetime from an Iterable collection of datetime objects. Collection can be all naive datetime objects or all datatime objects with tz (if non-naive datetimes are provided, result will be cast to UTC). However,...
2d56eeea44d2afbf752672abb6870d7045745a0f
32,232
from typing import Optional from typing import Dict def win_get_nonblocking(name: str, src_weights: Optional[Dict[int, float]] = None, require_mutex: bool = False) -> int: """ Passively get the tensor(s) from neighbors' shared window memory into local shared memory, which cannot be acc...
a641f963ac3434ece7ded8a642c7833fc8a2b30c
32,233
def parse(file, beautifulsoup=None, makeelement=None, **bsargs): """Parse a file into an ElemenTree using the BeautifulSoup parser. You can pass a different BeautifulSoup parser through the `beautifulsoup` keyword, and a diffent Element factory function through the `makeelement` keyword. By default, t...
5ccf2bfc8f1d6ec4f83200b250755ab149fd60dd
32,234
def get_L_dashdash_b1_d(L_dashdash_b1_d_t): """ Args: L_dashdash_b1_d_t: 1時間当たりの浴槽水栓湯はり時における太陽熱補正給湯負荷 (MJ/h) Returns: 1日当たりの浴槽水栓湯はり時における太陽熱補正給湯負荷 (MJ/d) """ return np.sum(L_dashdash_b1_d_t.reshape((365, 24)), axis=1)
aa541c5f82aa94c33c65ac264f2df420020ca443
32,235
def split_df(df, index_range, columns, iloc=False): """Split a data frame by selecting from columns a particular range. Args: df (:class:`pd.DataFrame`): Data frame to split. index_range (tuple): Tuple containing lower and upper limit of the range to split the index by. If `index_ra...
84e77e60a0f9c73ff3147c3648310875e5b58228
32,236
def basemap_to_tiles(basemap, day=yesterday, **kwargs): """Turn a basemap into a TileLayer object. Parameters ---------- basemap : class:`xyzservices.lib.TileProvider` or Dict Basemap description coming from ipyleaflet.basemaps. day: string If relevant for the chosen basemap, you ca...
ccaf3430294216e7015167dad3ef82bee8071192
32,237
import os def ensure_directory_exists(path, expand_user=True, file=False): """ Create a directory if it doesn't exists. Expanding '~' to the user's home directory on POSIX systems. """ if expand_user: path = os.path.expanduser(path) if file: directory = os.path.dirname(path) ...
5e353ad854792e7af57af1a37700e4ffd8e83967
32,238
def sms_count(request): """Return count of SMSs in Inbox""" sms_count = Messaging.objects.filter(hl_status__exact='Inbox').count() sms_count = sms_count if sms_count else "" return HttpResponse(sms_count)
c445b7c5fd54f632fc6f7c3d0deaeca47c1dd382
32,239
from pathlib import Path import yaml def deserializer(file_name: Path) -> Deserializer: """Load and parse the data deserialize declaration""" with open(file_name) as f: return Deserializer(yaml.load(f, Loader=SafeLoader))
5df5de579e359e7d1658dd00cf279baacb844f1f
32,240
import sys def read_annotations(**kws): """Read annotations from either a GAF file or NCBI's gene2go file.""" if 'gaf' not in kws and 'gene2go' not in kws: return gene2gos = None if 'gaf' in kws: gene2gos = read_gaf(kws['gaf'], prt=sys.stdout) if not gene2gos: raise...
ccf01d712e20ad0e0f55e3f7e1e32fdc845e781a
32,241
def p2db(a): """Returns decibel of power ratio""" return 10.0*np.log10(a)
5177d9ca5ca0ec749e64ebf3e704cf496fa365db
32,242
def buildDictionary(message): """ counts the occurrence of every symbol in the message and store it in a python dictionary parameter: message: input message string return: python dictionary, key = symbol, value = occurrence """ _dict = dict() for c in message: if ...
71b196aaccfb47606ac12242585af4ea2554a983
32,243
import pandas as pd import os def boston_housing(path): """Load the Boston Housing data set [@harrison1978hedonic]. It contains 506 examples of housing values in suburbs of Boston, each with 13 continuous attributes and 1 binary attribute. The data contains the following columns: | Feature | Description |...
732eaeab4183fcd70930c28cdaba09da16ee3995
32,244
import tensorflow as tf from tensorflow.keras.callbacks import TensorBoard, ModelCheckpoint import tensorflow.keras.backend as be def model_fit(mb_query: str, features_dict: dict, target_var: str, model_struct_fn, get_model_sample_fn, existing_models: dict, batch_size: int, epochs: int, patience: int, v...
add35320ef1d9f6474f3712f3222d9a5fdbb3185
32,245
def classify_subtrop(storm_type): """ SD purely - yes SD then SS then TS - no SD then TS - no """ if 'SD' in storm_type: if 'SD' in storm_type and True not in np.isin(storm_type,['TD','TS','HU']): return True if 'SS' in storm_type and True not in np.isin(storm_type,['TD',...
abfc8e002e798e5642e2ab4ae38fe0882259d708
32,246
def overridden_settings(settings): """Return a dict of the settings that have been overridden""" settings = Settings(settings) for name, dft_value in iter_default_settings(): value = settings[name] if value != dft_value and value is not None: settings.update(name, value) ...
ec76feb90dbc97012f84f9ebc75b41131dc925fe
32,247
def ScaleImageToSize(ip, width, height): """Scale image to a specific size using Stephans scaler""" smaller = ip.scale( width, height ); return smaller
9e2ee47ab30bfca70417eafbddd84958cd582618
32,248
import types def retrieve_parent(*, schema: types.Schema, schemas: types.Schemas) -> str: """ Get or check the name of the parent. If x-inherits is True, get the name of the parent. If it is a string, check the parent. Raise InheritanceError if x-inherits is not defined or False. Args: ...
4f6fc55af7b998e02b108d1bc5fea61f2afe82f1
32,249
from .translation.vensim.vensim2py import translate_vensim def read_vensim(mdl_file, data_files=None, initialize=True, missing_values="warning", split_views=False, encoding=None, **kwargs): """ Construct a model from Vensim `.mdl` file. Parameters ---------- mdl_fi...
28d062ebb234cf991dcef164d5151e1ab62e08f7
32,250
import typing def get_feature_importance( trained_pipeline: sklearn.pipeline.Pipeline, numeric_features: typing.List[str] ) -> pd.Series: """ Get feature importance measures from a trained model. Args: trained_pipeline (:obj:`sklearn.pipeline.Pipeline`): Fitted model pipeline ...
cd303af5a0b343a18fb42a3cd562998ecec96423
32,251
from typing import Any import json def json_loads(json_text: str) -> Any: """Does the same as json.loads, but with some additional validation.""" try: json_data = json.loads(json_text) validate_all_strings(json_data) return json_data except json.decoder.JSONDecodeError: raise _jwt_error.JwtInval...
d123054612a0a3e29f312e1506181ca3f9bed219
32,252
def weights(layer, expected_layer_name): """ Return the kernels/weights and bias from the VGG model for a given layer. """ W = vgg_layers[0][layer][0][0][2][0][0] b = vgg_layers[0][layer][0][0][2][0][1] layer_name = vgg_layers[0][layer][0][0][0][0] #to check we obtained the correct laye...
5271f932bd9a870bd7857db50632cd51d91b60a9
32,253
import textwrap def alert(title: str, text: str, *, level: str = "warning", ID: str = None): """ Generate the HTML to display a banner that can be permanently hidden This is used to inform player of important changes in updates. Arguments: text: Main text of the banner title: Title o...
90ff85c228dc70318deee196bdd512e5be90a5ad
32,254
def get_stim_data_df(sessions, analyspar, stimpar, stim_data_df=None, comp_sess=[1, 3], datatype="rel_unexp_resp", rel_sess=1, basepar=None, idxpar=None, abs_usi=True, parallel=False): """ get_stim_data_df(sessions, analyspar, stimpar) Returns dataframe with rela...
5a352a66ad06ed70b04db3ca3e26073fb412cccd
32,255
def get_all_elems_from_json(search_json: dict, search_key: str) -> list: """Returns values by key in all nested dicts. Args: search_json: Dictionary in which one needs to find all values by specific key. search_key: Key for search. Returns: List of values stored in nested structure...
6ab45e33962ccb5996b50d13e57626365c4ed78b
32,256
import sys import os import subprocess def FindVisualStudioInstallation(): """ Returns appropriate values for .build_tool and .uses_msbuild fields of TestGypBase for Visual Studio. We use the value specified by GYP_MSVS_VERSION. If not specified, we search for likely deployment paths. """ msvs_version...
b6969a2a87022efa3bd3164c3b53a21efecf6f15
32,257
def prFinalNodeName(q): """In : q (state : string) Out: dot string (string) Return dot string for generating final state (double circle) """ return dot_san_str(q) + '[shape=circle, peripheries=2];'
8a4e5649ebeb0c68f2e1741fefd935c9a5f919bf
32,258
import typing from datetime import datetime def decodeExifDateTime(value: str) -> typing.Optional[datetime.datetime]: """ utility fct to encode/decode """ try: # return path.encode(sys.stdout.encoding, 'ignore').decode(sys.stdout.encoding) d = datetime.datetime.strptime(value, '%Y:%m:%...
a1ce11305e8e486ad643530930368c47f1c073ef
32,259
def parse(file: str) -> Env: """Parse an RLE file and create a user environment Parameters ---------- file: str Path to the RLE file. Returns ------- user_env: `dict` [str, `Any`] User environment returned from ``user_env()``. It has these attributes: ``width`` ...
cf0a884169b22f4781450c78a35b33ef43049d65
32,260
import six def logger_has_handlers(logger): """ Check if given logger has at least 1 handler associated, return a boolean value. Since Python 2 doesn't provide Logger.hasHandlers(), we have to perform the lookup by ourself. """ if six.PY3: return logger.hasHandlers() else: c =...
dc0093dd25a41c997ca92759ccb9fa17ad265bdd
32,261
import json def query_parameters(prefix, arpnum, t_recs, keywords, redis=True): """Query keyword sequence from a header file. Alternative design: replace prefix and arpnum with filepath. """ KEYWORDS = ['T_REC', 'AREA', 'USFLUXL', 'MEANGBL', 'R_VALUE'] if redis: id = f'{prefix}{arpnum:06...
84c0a43d6d045e3255478175697cbb0bfaac5da8
32,262
def get_columns(tablename): """ This function returns simbench csv file column names for a given table name. """ allcolumns = all_columns() if tablename in allcolumns.keys(): if "Profile" in tablename: logger.debug("The returned column list of %s is given for simbench " % tablename + ...
7f333f7ceb4d9ff02519d886a650e5bc5a489270
32,263
def x0_rand(mu3,xb,num_min): """ Randomly initialise the 5 protocol parameters using the specified bounds. Parameters and bounds should be specified in the order {Px,pk1,pk2,mu1,mu2}. Parameters ---------- mu3 : float Intensity of pulse 3 (vacuum). xb : float, array-like Upp...
fcf32cd7367e7b78e48829f72523f50855ba563e
32,264
def render_smiles_list(smiles_list): """ Format and return a SMILES string(s). """ # The string that will be returned to the template result = r'<h3>Solvent SMILES:</h3>' + '\n' result += r'<p>' if len(smiles_list) == 1: result += smiles_list[0] else: result += 'This is a...
f6207bb63452d1037c321874b8ed5248e89dc83e
32,265
def get_config_id(kwargs=None, call=None): """ Returns a config_id for a given linode. .. versionadded:: 2015.8.0 name The name of the Linode for which to get the config_id. Can be used instead of ``linode_id``. linode_id The ID of the Linode for which to get the config_id...
b66eda936157d0c6794289ed90acd681a5d31c02
32,266
def bunq_oauth_reauthorize(): """ Endpoint to reauthorize OAuth with bunq """ cookie = request.cookies.get('session') if cookie is None or cookie != util.get_session_cookie(): return render_template("message.html", msgtype="danger", msg=\ "Invalid request: session cookie not set or not v...
57708acb8e4c726640360bfb1263ede323571c15
32,267
def get_centrality_measures(network, tol): """ Calculates five centrality measures (degree, betweenness, closeness, and eigenvector centrality, and k-shell) for the nodes of the given network. Parameters ---------- network: networkx.Graph() tol: tolerance parameter for calculating eigenvect...
aacbd931f0809f48f3ee0eab2092259810f08205
32,268
from typing import List from typing import Tuple def extract_mealentries(meals: List[Meal]) -> List[Tuple]: """ Extract meal entries records from a sequence of myfitnesspal meals. Args: - meals (List[Meal]): A list with meal objects to extract data from Returns: - List[Tuple]: A list wit...
c7c043cee0b4af1253902080af67919cc9238d75
32,269
import math def get_45point_spiralling_sphere_with_normal_zaxis_dist( num_of_spirals = 4, num_of_vertices = 45): """ A sphere of spiralling points. Each point is equally spaced on the x,y,z axes. The equal spacing is calculated by dividing the straight-line spiral distance by 45. Adapted from Leonsim's co...
59173bdd28b513d0f039215ea7d713cd80d81b4e
32,270
import os def refresh_gui_with_new_image(shared, df_files, df_model, df_landmarks, main_window, landmarks_window): """ Parameters ---------- shared : dictionary contains data shared across windows, definition is in the main function. df_files : pandas DataFrame dataframe containing...
3036e25e6b6284351c83c9ac8907170252396c31
32,271
def pak64(seq, debug=False): """ :param seq: smallish sequence of smallish integers :return seq64: smaller sequence of 64bit integers Pack a sequence of smallish integers into an array of 64 bit ints, using bit pitch and number of big ints appropriate to the length of the sequence and the ra...
96938d9b23e9b8d3a0c219537c8cd3a62d633e20
32,272
import re import json def parse_results(line): """Parses and logs event information from logcat.""" header = re.search(r'cr_PasswordChangeTest: (\[[\w|:| |#]+\])', line).group(1) print(header) credentials_count = re.search(r'Number of stored credentials: (\d+).', line) if not credentials_count: # Event...
24cc928d945d2d4f16f394be68a8bb217c21b342
32,273
def bqwrapper(datai): """ Wraps the kdtree ball query for concurrent tree search. """ return kdtbq(datai, r=bw[0])
203e77e37ddb53b76366b0d376c37b63536da923
32,274
import re def crawl_user_movies(): """ @功能: 补充用户观看过的电影信息 @参数: 无 @返回: 电影信息 """ user_df = pd.read_csv('douban_users.csv') user_df = user_df.iloc[:, [1, 2, 3]] user_movies = list(user_df['movie_id'].unique()) movies = [] # 储存电影 count = 1 # 日志参数 for i in user_movies: ...
882fe56fc2fc5e22b6ad0ce518b7adaabd724cd2
32,275
import logging def filter_by_shape(data: pd.DataFrame, geofence: Polygon) -> pd.DataFrame: """Remove trips outside of geofence. Filter by pickup and dropoff locations""" logging.info('Filtering by bbox') (min_lon, min_lat, max_lon, max_lat) = geofence.bounds data = data[ (data.pickup_longitu...
fa98c85ea286921e9a986820a7a17e03e94181dc
32,276
from ..core import cache as cache def upload_collection(flask_app, filenames, runs, dataset_id, collection_id, descriptions=None, cache=None): """ Create new Predictors from TSV files Args: filenames list of (str): List of paths to TSVs runs list of (int): List of run ids...
d6d16206716dae0e7e945d1cff95317454031e3e
32,277
def get_filtered_metadata_list(metadata_list, strand): """ Given a lis of exon junctions, remove the ones that redundantly cover a junction Parameters ---------- metadata_list: List(Output_metadata), strand: strand of the gene Returns ------- filtered_meetadata_list: List of metadata o...
dab3da34f435d7401dd5e76be2c9c032aea875c1
32,278
import functools import traceback def handle_exceptions(database, params, constraints, start_params, general_options): """Handle exceptions in the criterion function. This decorator catches any exceptions raised inside the criterion function. If the exception is a :class:`KeyboardInterrupt` or a :class:`...
725cfc7d3c338e2a4dbd143fc558307cbb49e1cc
32,279
def vector2angles(gaze_vector: np.ndarray): """ Transforms a gaze vector into the angles yaw and elevation/pitch. :param gaze_vector: 3D unit gaze vector :return: 2D gaze angles """ gaze_angles = np.empty((1, 2), dtype=np.float32) gaze_angles[0, 0] = np.arctan(-gaze_vector[0]/-gaze_vector[2]...
b0db8e1f6cb9865e9563af5385f760699069013e
32,280
def setup_train_test_idx(X, last_train_time_step, last_time_step, aggregated_timestamp_column='time_step'): """ The aggregated_time_step_column needs to be a column with integer values, such as year, month or day """ split_timesteps = {} split_timesteps['train'] = list(range(last_train_time_step + 1)) ...
256fbe66c0b27b651c8190101e5068f7e0542498
32,281
def get_targets_as_list(key_list): """Get everything as list :param key_list: Target key list :type key_list: `list` :return: Values list :rtype: `list` """ session = get_scoped_session() values = [] for key in key_list: values.append(get_all_targets(session, key)) retur...
bcd2ed48d685353a59c4545d1277589fa388b4a0
32,282
import re def load_jmfd(jmfd_path): """Loads j-MFD as Pandas DataFrame. Args: jmfd_path (str): Path of J-MFD. Raises: JMFDFormatError: J-MFD format error. Returns: pandas.DataFrame: Pandas DataFrame of loaded j-MFD with word, existence of stem, foundation ...
675370c9ce0ed37667ec347dc4a0af57ea5b20b3
32,283
import os def binary_to_notelist(data): """data is a numpy array: [timestep, feature]. Timestep 0 is a midi #, timestep 1 is a duration, timestep 2 is midi, etc...""" assert len(data.shape) == 2 # Read the duration symbol table symbol_to_index = read_pickle(os.path.join(TXT_TOKENIZED, 'symbol_to_ind...
535b774d789055ff99a555d5e44873ff373ac429
32,284
def objectId(value): """objectId校验""" if value and not ObjectId.is_valid(value): raise ValueError('This is not valid objectId') return value
2e33950649fe95460e82102c1d6209a9173fa5fd
32,285
def add_lists(list1, list2): """ Add corresponding values of two lists together. The lists should have the same number of elements. Parameters ---------- list1: list the first list to add list2: list the second list to add Return ---------- output: list ...
e4efbc079a981caa4bcbff4452c8845a7e534195
32,286
def get_struc_first_offset(*args): """ get_struc_first_offset(sptr) -> ea_t Get offset of first member. @param sptr (C++: const struc_t *) @return: BADADDR if memqty == 0 """ return _ida_struct.get_struc_first_offset(*args)
f589dec791c3a81664b81573ea52f02d1c9a6b15
32,287
def export_gps_route( trip_id, trip_date, vehicle_id, gtfs_error, offset_seconds, gps_data ): """ Writes the given entry to the "tracked_routes" table. This table is used to cache the results of finding and filtering only the valid routes as represented in the GPS da...
fe1a4f4fb2c89c6634353748d5cdd49d82110e64
32,288
def optimize_solution(solution): """ Eliminate moves which have a full rotation (N % 4 = 0) since full rotations don't have any effects in the cube also if two consecutive moves are made in the same direction this moves are mixed in one move """ i = 0 while i < len(soluti...
4be6bf0e4200dbb629c37a9bdae8338ee32c262b
32,289
from typing import Iterable import resource from typing import Optional def secretsmanager_resource( client: Client, policies: Iterable[Policy] = None, ): """ Create Secrets Manager resource. Parameters: • client: Secrets Manager client object • policies: security policies to apply to all...
ee2d880944065331aba0751bdfba2f82c3d7e2ac
32,290
def lgbm_hyperband_classifier(numeric_features, categoric_features, learning_rate=0.08): """ Simple classification pipeline using hyperband to optimize lightgbm hyper-parameters Parameters ---------- `numeric_features` : The list of numeric features `categoric_features` : The list of categoric ...
7c48373d1f40d7248a9d0f6a37c95281027aa1bd
32,291
def GL(mu, wid, x, m = 0.5): """ Function to generate a 1D Gaussian-Lorentzian peak. The peak is centered at pos, is wid wide (FWHM) and with blending parameter m. Parameters ---------- mu: float Peak center wid: float FWHM of Gaussian peak. FWHM is related to ...
d458eae3ad1ea31dcab021c798e9d7d02fa390ae
32,292
def jp_(var,mask): """Value at j+1/2, no gradient across boundary""" return div0((var*mask + np.roll(var*mask,-1,axis=0)),(mask+np.roll(mask,-1,axis=0)))
cc2aaf2e17bd0cbe3a211b26bc9d976298307f0d
32,293
import re def _solrize_date(date, date_type=''): """ Takes a date string like 2018/01/01 and returns an integer suitable for querying the date field in a solr document. """ solr_date = "*" if date: date = date.strip() start_year, end_year = fulltext_range() if date_typ...
f309f784d79b46ed704ee1e631d7b4bdda7057f6
32,294
def read_file(filename): """ read filename and return its content """ in_fp = open(filename) content = in_fp.read() in_fp.close() return content
c707a412b6099591daec3e70e9e2305fee6511f9
32,295
import argparse def get_arguments(): """Return the values of CLI params""" parser = argparse.ArgumentParser() parser.add_argument("--image_folder", default="images") parser.add_argument("--image_width", default=400, type=int) args = parser.parse_args() return getattr(args, "image_folder"), get...
288bb7a589bae308252a36febcb14b9349371603
32,296
def delete_job(job_id): """Delete my job by Id Upon success, marks job as &#x27;aborted&#x27; if it must be suspended, and returns the deleted job with the appropriate status # noqa: E501 :param job_id: Id of the job that needs to be deleted :type job_id: str :rtype: Job """ job = q.fetch...
e8f02faa2a9336c93725739443b9007242b50b5c
32,297
def service(appctx): """Service with files instance.""" return RecordService(ServiceWithFilesConfig)
4902f8eae2c2c4200543a9c594f2abbc5163ec70
32,298
import json import re def get_sci_edus(filepath): """ load each sciedu """ with open(filepath, 'r') as fb: train = json.loads(fb.read().encode('utf-8'))['root'] EDUs = [] sentenceNo = 1 sentenceID = 1 for edu_dict in train: if edu_dict['id'] == 0: continue ...
0b8fd37dd8884e9e3f38f4bb671dff2df978f5b2
32,299