content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def luminance(qcolor): """ Gives the pseudo-equivalent greyscale value of this color """ r,g,b = qcolor.red(), qcolor.green(), qcolor.blue() return int(0.2*r + 0.6*g + 0.2*b)
9e1821da2c0c6e8d76aefe56d6ed659a728737bb
7,213
def read_info(path, layer=None, encoding=None): """Read information about an OGR data source. `crs` and `geometry` will be `None` and `features` will be 0 for a nonspatial layer. Parameters ---------- path : str or pathlib.Path layer : [type], optional Name or index of layer in dat...
7479c63223288c94ed4756350756473866d7b2b3
7,214
import time import requests import json def _macro_cons_opec_month(): """ 欧佩克报告-月度, 数据区间从 20170118-至今 这里返回的具体索引日期的数据为上一个月的数据, 由于某些国家的数据有缺失, 只选择有数据的国家返回 :return: pandas.Series 阿尔及利亚 安哥拉 厄瓜多尔 加蓬 伊朗 伊拉克 科威特 利比亚 尼日利亚 \ 2017-01-18 108.0 172.4 54.5 21.3 37...
5ae77b64b5d66e14027d757ea840385d0fc96033
7,215
def get_activation(preact_dict, param_name, hook_type): """ Hooks used for in sensitivity schedulers (LOBSTE, Neuron-LOBSTER, SERENE). :param preact_dict: Dictionary in which save the parameters information. :param param_name: Name of the layer, used a dictionary key. :param hook_type: Hook type. ...
8d5766178ef972e010b5be3a3826774f051dd3bd
7,217
def createAbsorption(cfgstr): """Construct Absorption object based on provided configuration (using available factories)""" return Absorption(cfgstr)
587b0e12f845171ffd61d5d04c37b4ff98865216
7,218
def get_optimizer_config(): """Gets configuration for optimizer.""" optimizer_config = configdict.ConfigDict() # Learning rate scheduling. One of: ["fixed", "exponential_decay"] optimizer_config.learning_rate_scheduling = "exponential_decay" # Optimization algorithm. One of: ["SGD", "Adam", "RMSprop"]. opt...
1918cd8aa9ff8446dec8cb90ff529de97f05d5aa
7,219
def flat2seq(x: Tensor, num_features: int) -> Tensor: """Reshapes tensor from flat format to sequence format. Flat format: (batch, sequence x features) Sequence format: (batch, sequence, features) Args: x (Tensor): a tensor in the flat format (batch, sequence x features). num_features ...
d8bace4548d82352ebae28dc9be665b862b744d0
7,220
def run_results(results_data, time_column, pathway_column, table_letters, letters, dataframe_T1, dataframe_T2, dataframe_T3, dataframe_T4, original_transitions, simulation_transitions, intervention_codes, target, individuals, save_location, simulation_...
5292328a1f74d2ecb89daae465bace1a95eff538
7,221
from typing import Optional def get_spatial_anchors_account(name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSpatialAnchorsAccountResult: """ Get information about ...
db94c210af0c46cea2e3a95573f339ec65f7e7fe
7,222
import re def format_query(str_sql): """Strips all newlines, excess whitespace, and spaces around commas""" stage1 = str_sql.replace("\n", " ") stage2 = re.sub(r"\s+", " ", stage1).strip() stage3 = re.sub(r"(\s*,\s*)", ",", stage2) return stage3
5adb0f9c3314ba04bbf92c88e3ef17802b2afeb0
7,223
def make_ytick_labels(current_ticks, n, numstring = ""): """ """ new_ticks = [] for item in current_ticks: if int(item) == item: new_ticks.append(f"{int(item)}{numstring}") else: new_ticks.append(f"{item:.1f}{numstring}") return new_ticks
2685126dc72305ccb7b4bf652fe645e9a39affd3
7,224
import re def check_token(token): """ Returns `True` if *token* is a valid XML token, as defined by XML Schema Part 2. """ return (token == '' or re.match( "[^\r\n\t ]?([^\r\n\t ]| [^\r\n\t ])*[^\r\n\t ]?$", token) is not None)
b4e1d313fb64aad4c1c244cb18d3629e13b1c3af
7,225
def generate_random_data(n=10): """Generate random data.""" return rand(10)
872591efc14d28282b24138f80e19c92487bde6d
7,226
def get_phoible_feature_list(var_to_index): """ Function that takes a var_to_index object and return a list of Phoible segment features :param var_to_index: a dictionary mapping variable name to index(column) number in Phoible data :return : """ return list(var_to_index.keys())[11:]
a53995cd927d1cdc66fadb2a8e6af3f5e2effff0
7,228
def split_data(dataset): """Split pandas dataframe to data and labels.""" data_predictors = [ "Steps_taken", "Minutes_sitting", "Minutes_physical_activity", "HR", "BP", ] X = dataset[data_predictors] y = dataset.Health x_train, x_test, y_train, y_test = ...
b15db522ff45dee825d64d7daf6604fb400bc677
7,229
def add_header(response): """ Add headers to both force latest IE rendering engine or Chrome Frame. """ response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1' return response
6e755f47bd12095d80a941338c451e677f80bcc6
7,230
def draw_lane_on_unwarped_frame(frame, left_line, right_line, trsf_mtx_inv): """ Drawing of the unwarped lane lines and lane area to the current frame. Args: left_line: left Line instance right_line: right Line instance trsf_mtx_inv: inverse of the perspective transformation matrix ...
b59b3d99a17ba241aff0a9ac7e6d33497f1db803
7,232
def n_states_of_vec(l, nval): """ Returns the amount of different states a vector of length 'l' can be in, given that each index can be in 'nval' different configurations. """ if type(l) != int or type(nval) != int or l < 1 or nval < 1: raise ValueError("Both arguments must be positive integ...
98770fa5a5e62501bf365a4a5a40a932b2ba2450
7,234
def remove_items_from_dict(a_dict, bad_keys): """ Remove every item from a_dict whose key is in bad_keys. :param a_dict: The dict to have keys removed from. :param bad_keys: The keys to remove from a_dict. :return: A copy of a_dict with the bad_keys items removed. """ new_dict = {} for ...
7c665e372c2099441f8a661f1194a76a21edf01c
7,235
def writeObject(img_array, obj_array, bbox): """Writes depression objects to the original image. Args: img_array (np.array): The output image array. obj_array (np.array): The numpy array containing depression objects. bbox (list): The bounding box of the depression object. Returns:...
141cf9c3f47766a4020d737e743215db04761f54
7,236
def process_model(current_val): """ :param current_val: model generated by sat solver, atom is satisfied if in modal. :return tuple of sets comprising true and false atoms. """ true_atoms, false_atoms = set(), set() for atom in current_val: if current_val[atom]: true_atoms....
9cf90aec097091841c0f0ac820317f373a92e4c1
7,237
import re def filter_strace_output(lines): """ a function to filter QEMU logs returning only the strace entries Parameters ---------- lines : list a list of strings representing the lines from a QEMU log/trace. Returns ------- list a list of strings representing only ...
01b6c048ebdf890e9124c387fc744e56cc6b7f4d
7,238
def export_gmf_xml(key, dest, sitecol, imts, ruptures, rlz, investigation_time): """ :param key: output_type and export_type :param dest: name of the exported file :param sitecol: the full site collection :param imts: the list of intensity measure types :param ruptures: an ord...
139e24feb476ab10c0f1192fd47f80b7bbe29ccb
7,239
import functools def track_state_change(entity_ids, from_state=None, to_state=None): """Decorator factory to track state changes for entity id.""" def track_state_change_decorator(action): """Decorator to track state changes.""" event.track_state_change(HASS, entity_ids, ...
08f6e7f8354f51dfa54d233156585c84d9b811b3
7,240
def phrase(): """Generate and return random phrase.""" return models.PhraseDescription(text=random_phrase.make_random_text())
458529df5d6dbd92b7a6545d92b836763a8411a6
7,241
def classify_tweets(text): """ classify tweets for tweets about car accidents and others :param text: tweet text :return: boolean, true if tweet is about car accident, false for others """ return text.startswith(u'בשעה') and ( (u'הולך רגל' in text or u'הולכת רגל' in text...
b34991a36febf2648cd83f2782ba4a8631e65a1a
7,242
def _build_results(drift_type, raw_metrics): """Generate all results for queried time window or run id of some a datadriftdetector. :param raw_metrics: origin data diff calculation results. :return: a list of result dict. """ results = [] for metric in raw_metrics: ep = _properties(met...
2938257d54d0be0ac012c4ddc39952c6767b8a38
7,243
def no_test_server_credentials(): """ Helper function that returns true when TEST_INTEGRATION_* credentials are undefined or empty. """ client_id = getattr(settings, 'TEST_INTEGRATION_CLIENT_ID', None) username = getattr(settings, 'TEST_INTEGRATION_USERNAME', None) password = getattr(setting...
a98f249e15f9d1c42aacd62a22024af577332275
7,244
from typing import Tuple from typing import Any def skip_spaces(st: ST) -> Tuple[ST, Any]: """ Pula espaços. """ pos, src = st while pos < len(src) and src[pos].isspace(): pos += 1 return (pos, src), None
df0c549c8af18a66a6e2d1704991592516e62ffb
7,245
def mixed_phone_list(): """Return mixed phone number list.""" return _MIXED_PHONE_LIST_
e607eb5778d8f4999fcbeb85ea5a3bb0ca04ee40
7,246
def get_report_summary(report): """ Retrieve the docstring summary content for the given report module. :param report: The report module object :returns: the first line of the docstring for the given report module """ summary = None details = get_report_details(report) if not details: ...
ea350c527cfab62496110ae08eedd9841db10492
7,248
def load_dataset(dataset_identifier, train_portion='75%', test_portion='25%', partial=None): """ :param dataset_identifier: :param train_portion: :return: dataset with (image, label) """ # splits are not always supported # split = ['train[:{0}]'.format(train_portion), 'test[{0}:]'.format(tes...
f836236f56ba8359194c21c20ea6767d296a0ee4
7,249
from typing import List import functools def stop(ids: List[str]): """Stop one or more instances""" return functools.partial(ec2.stop_instances, InstanceIds=ids)
fdf6db088323e5874c01662cf931aa85143ac2aa
7,250
def simple_parse(config_file): """ Do simple parsing and home-brewed type interference. """ config = ConfigObj(config_file, raise_errors=True) config.walk(string_to_python_type) # Now, parse input and output in the Step definition by hand. _step_io_fix(config) return(config)
85a406125a644fb75a5d8986778de6ea9b8af52a
7,252
import pickle def deserialize_columns(headers, frames): """ Construct a list of Columns from a list of headers and frames. """ columns = [] for meta in headers: col_frame_count = meta["frame_count"] col_typ = pickle.loads(meta["type-serialized"]) colobj = col_typ.deser...
176d936a6019669f15049f11df00e14ad62238d7
7,253
def words_with_joiner(joiner): """Pass through words unchanged, but add a separator between them.""" def formatter_function(i, word, _): return word if i == 0 else joiner + word return (NOSEP, formatter_function)
9f24b2e7d202663902da0bfccd8e9b96faebc152
7,255
def magerr2Ivar(flux, magErr): """ Estimate the inverse variance given flux and magnitude error. The reason for this is that we need to correct the magnitude or flux for Galactic extinction. Parameters ---------- flux : scalar or array of float Flux of the obejct. magErr : scal...
37c48c26f1b876ca4d77dc141b1728daaea24944
7,256
def create_policy_work_item_linking(repository_id, branch, blocking, enabled, branch_match_type='exact', organization=None, project=None, detect=None): """Create work item linking policy. """ organiza...
230604606ba47c29386027503f45d30577cb5edf
7,257
import numbers def center_data(X, y, fit_intercept, normalize=False, copy=True, sample_weight=None): """ Centers data to have mean zero along axis 0. This is here because nearly all linear models will want their data to be centered. If sample_weight is not None, then the weighted mean ...
d31b27868a6f1ee21ef4019df9954fc1136d73eb
7,258
import socket async def get_ipv4_internet_reachability(host, port, timeout): """ Host: 8.8.8.8 (google-public-dns-a.google.com) OpenPort: 53/tcp Service: domain (DNS/TCP) """ try: socket.setdefaulttimeout(timeout) socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host,...
ff1d335dec568810431c58b0bc1a72eb10e65372
7,259
def cov_pen(h_j, h_no_j): """ Personal implementation of covariance matrix with penalization. :param h_j: :param h_no_j: :return: """ final_dim = h_j.shape[1] cov_matrix = np.empty((final_dim, final_dim)) for row in range(final_dim): for column in range(final_dim): ...
4a3ef366a072fd84d198597213ea544d88032ac5
7,260
def get_last_timestamp(): """ 获取当天23:59:59的时间戳 :return: """ # 获取明天0点的时间戳 future_timestamp = get_timestamp(-1) # 明天0点的时间戳-1 last_timestamp = future_timestamp - 1 return last_timestamp
7f4c07309f9be1437c1743f691402bae58a7ec34
7,261
def _get_all_subclasses(typ, # type: Type[T] recursive=True, # type: bool _memo=None # type: Set[Type[Any]] ): # type: (...) -> Iterable[Type[T]] """ Returns all subclasses of `typ` Warning this does not support g...
a9a9c1186e195347f937961b928159c605b64ffe
7,263
import logging def conditions_summary(conditions): """ Return a dict of consumer-level observations, say, for display on a smart mirror or tablet. """ keys = ['timestamp', 'dewpoint', 'barometricPressure', 'windDirection', 'windSpeed', 'windGust', 'precipitationLastHour', 'temperature', ...
aa4c95fd892c63bd05abd24188b8931375973bc0
7,264
def InsertOrganisation(cur, con, entity_name: str = "Organisation") -> int: """ Inserts a new Organisation into the database """ # Get information about the video game print(f"Enter new {entity_name}'s details:") row = {} row["Name"] = input(f"Enter the name of the {entity_name}: ") or None row[...
de22b6eeb446efab58a2124f1b26da1e9edb12ed
7,265
def _rgb_to_hsv(rgbs): """Convert Nx3 or Nx4 rgb to hsv""" rgbs, n_dim = _check_color_dim(rgbs) hsvs = list() for rgb in rgbs: rgb = rgb[:3] # don't use alpha here idx = np.argmax(rgb) val = rgb[idx] c = val - np.min(rgb) if c == 0: hue = 0 ...
ee4a2d9867351e61bf9b14de4ef2d05425285879
7,266
def find_correlation(convergence_data, lens_data, plot_correlation=False, plot_radii=False, impact=False, key=None): """Finds the value of the slope for plotting residuals against convergence. Magnitude of slope and error quantify correlation between the two. Inputs: conv -- convergence. mu_diff ...
d507cd256a555b442fff1cd2a00862a5afdf0661
7,267
def ELCE2_null_estimator(p_err, K, rng): """ Compute the ELCE^2_u for one bootstrap realization. Parameters ---------- p_err: numpy-array one-dimensional probability error vector. K: numpy-array evaluated kernel function. rng: type(np.random.RandomState...
5b42e36ade4aba416bb8cbf6790d22fd8e4913b1
7,268
import curses def select_from(stdscr, x, y, value, slist, redraw): """ Allows user to select from a list of valid options :param stdscr: The current screen :param x: The start x position to begin printing :param y: The start y position to begin pritning :param value: The current value chosen ...
208283731317418bbe5ae1d16386584eaebcd626
7,269
def describe(r): """Return a dictionary with various statistics computed on r: mean, variance, skew, kurtosis, entropy, median. """ stats = {} stats['mean'] = r.mean() stats['variance'] = r.var() stats['skew'] = skew(r) stats['kurtosis'] = kurtosis(r) stats['median'] = np.median(...
7ed070110ac327ef69cf1c05eefdda16c21f7f0d
7,270
def value_iteration(env,maxiter): """ Just like policy_iteration, this employs a similar approach. Steps (to iterate over): 1) Find your optimum state_value_function, V(s). 2) Keep iterating until convergence 3) Calculate your optimized policy Outputs: - Your f...
c116d0408d6edfa82763febb030633b815d69812
7,271
def is_excluded(branch_name): """ We may want to explicitly exclude some BRANCHES from the list of BRANCHES to be merged, check if the branch name supplied is excluded if yes then do not perform merging into it. Args: branch_name: The branch to check if to be inc...
d38923a84e7a3f9a40ebd101de5c542156fff7aa
7,272
def schedule_contrib_conv2d_winograd_without_weight_transform(attrs, outs, target): """Schedule definition of conv2d_winograd_without_weight_transform""" with target: return topi.generic.schedule_conv2d_winograd_without_weight_transform(outs)
e186a727ccf69c3292d8807abd003485308754db
7,273
def _phi(r: FloatTensorLike, order: int) -> FloatTensorLike: """Coordinate-wise nonlinearity used to define the order of the interpolation. See https://en.wikipedia.org/wiki/Polyharmonic_spline for the definition. Args: r: input op. order: interpolation order. Returns: `phi_k` e...
80a41c99a4ef8b396d16b02a6217eaa9191105f6
7,275
def linbin(n, nbin=None, nmin=None): """Given a number of points to bin and the number of approximately equal-sized bins to generate, returns [nbin_out,{from,to}]. nbin_out may be smaller than nbin. The nmin argument specifies the minimum number of points per bin, but it is not implemented yet. nbin defaults to th...
2d537131ad8d13e32375b74b9fa3e77088d046dd
7,276
from bs4 import BeautifulSoup def get_soup(url): """Gets the soup of the given URL. :param url: (str) URL the get the soup from. :return: Soup of given URL. """ header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36'}...
69982a75a5c329b0d9e0ca7638c0ffffdc3ac21e
7,277
def msd_id_to_dirs(msd_id): """Given an MSD ID, generate the path prefix. e.g. TRABCD12345678 -> A/B/C/TRABCD12345678""" return op.join(msd_id[2], msd_id[3], msd_id[4], msd_id)
e210ae919de4fc8b037a7e8d7aabb6858b6e07f9
7,278
def get_data_path(sub_path): """Returns path to file in data folder.""" return join(_data_folder_path, sub_path)
847b59cfea7f4d42b65f166230c032e71bb92ecd
7,279
import io def read_avro_bytes(URL, open_with, start_byte, length, header, nrows=None): """Pass a specific file/bytechunk and convert to dataframe with cyavro Both a python dict version of the header, and the original bytes that define it, are required. The bytes are prepended to the data, so that the ...
9542eb13c1247de35f00a1fa370aba721f8657cd
7,280
def get_launches(method="", **query): """Gets launches based on query strings Gets launches based on query strings from the API Parameters ---------- method : str (optional) the method used for the request query : keyword args keyword args based on t...
ca162affdd7aef187985e0d2c75e153ad75db162
7,281
def state(obj): """Gets the UnitOfWork state of a mapped object""" return obj.__ming__.state
1072265fe175ffcd581d14af5d4ee85f2941a5e4
7,282
def save_file_in_path(file_path, content): """Write the content in a file """ try: with open(file_path, 'w', encoding="utf-8") as f: f.write(content) except Exception as err: print(err) return None return file_path
7b1e453a9b2a8c1211e111a6e8db432811d84a7a
7,283
import json from datetime import datetime def export_entity_for_model_and_options(request): """ Export entity list in a list of 'format' type. @note EntityModelClass.export_list() must return a list of results. User of the request is used to check for permissions. """ limit = int_arg(request.G...
5539d3fe66dd3163044acf7073e40e55cc1c3b5c
7,284
import torch def jaccard_loss(true, logits, eps=1e-7): """Computes the Jaccard loss, a.k.a the IoU loss. Note that PyTorch optimizers minimize a loss. In this case, we would like to maximize the jaccard loss so we return the negated jaccard loss. Args: true: a tensor of shape [B, H, W] or ...
ae6c8f94662f48be81abf60c8a8fcd88f7ff7d81
7,286
def _get_distribution_schema(): """ get the schema for distribution type """ return schemas.load(_DISTRIBUTION_KEY)
32af1d9547d978a8a57a799ba74723f21e05c756
7,287
def compute_transforms(rmf_coordinates, mir_coordinates, node=None): """Get transforms between RMF and MIR coordinates.""" transforms = { 'rmf_to_mir': nudged.estimate(rmf_coordinates, mir_coordinates), 'mir_to_rmf': nudged.estimate(mir_coordinates, rmf_coordinates) } if node: m...
3190a94cc406bb1199df3480202df4a3258912f9
7,288
def merge_dicts(*list_of_dicts): """Merge a list of dictionaries and combine common keys into a list of values. args: list_of_dicts: a list of dictionaries. values within the dicts must be lists dict = {key: [values]} """ output = {} for dikt in list_of_dicts: for k, v ...
3d629bb9bc6af2a637a622fea158447b24c00bd0
7,289
def highpass_filter(src, size): """ highpass_filter(src, size) ハイパスフィルター 引数 ---------- src : AfmImg形式の画像 size : 整数 フィルターのサイズ 戻り値 ------- dst : AfmImg形式の画像 フィルターがかかった画像 """ def highpass(dft_img_src, *args): dft_img = dft_img_src.copy() #マ...
7945e3556cdd2eb4fd1e2303cbba00052a4a5900
7,290
import re import socket def parse_target(target): """ 解析目标为ip格式 :param str target: 待解析的目标 :return tuple scan_ip: 解析后的ip和域名 """ scan_ip = '' domain_result = '' main_domain = '' try: url_result = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', target) if ...
292d90eebefb8da5289b20914dfbcd9c294ee5b7
7,291
from typing import Type def isWrappedScalarType(typ: Type) -> bool: """ Given a type, determine if it is a c10::scalar which we will wrap in a lazy Value. Since we literally change the type from scalarT to valueT, information is lost. This function helps build a list of wrapped scalars to save that in...
0d854c734ddf3441dd2524c56d1d84d85fc7ac22
7,292
def assign_topic(data, doc_topic_distr): """ Assigns dominant topic to documents of corpus. :param data: DF of preprocessed and filtered text data :type data: pd.DataFrame :param doc_topic_distr: Array of topic distribution per doc of corpus :type doc_topic_distr: np.array :return: DF incl assi...
d53661831d9ee1431f989b290396be3ebde0582a
7,293
def _enable_scan_single_bytecode(code, name): """ Part of the ``_enable_scan`` that applies the scan behavior on a single given list/set comprehension or generator expression code. """ bc = bytecode.Bytecode.from_code(code) Instr = bytecode.Instr # Updates LOAD_GLOBAL to LOAD_FAST when arg ...
d1bd12f50961869e09d4cbdc121e01abbe34232a
7,294
def composite_rotation(r, p1=qt.QH([1, 0, 0, 0]), p2=qt.QH([1, 0, 0, 0])): """A composite function of next_rotation.""" return next_rotation(next_rotation(r, p1), p2)
335363a18efb36d28c87b0266bd4dcdd27b6b85a
7,295
def extract_vectors_ped_feature(residues, conformations, key=None, peds=None, features=None, indexes=False, index_slices=False): """ This function allows you to extract information of the ped features from the data structure. In particular allows: - all rows or a specific subset of them, containing a certai...
3d0efb833ffd80303e2494d017c12e1d06d10bcc
7,296
def Load_File(filename): """ Loads a data file """ with open(filename) as file: data = file.readlines() return data
f49aa4474d9af0b8a778b9575e282eb579c103ab
7,297
from scipy.ndimage import morphology import numpy def massage_isig_and_dim(isig, im, flag, band, nm, nu, fac=None): """Construct a WISE inverse sigma image and add saturation to flag. unWISE provides nice inverse variance maps. These however have no contribution from Poisson noise from sources, and so u...
b0bf70ddfff3a6b0a48005b9e1069c5c5f670dac
7,298
def uncapitalize(string: str): """De-capitalize first character of string E.g. 'How is Michael doing?' -> 'how is Michael doing?' """ if len(string): return string[0].lower() + string[1:] return ""
1a294f171d16d7a4c41fb0546feca3c03b7ae37a
7,300
def _sc_weights_trad(M, M_c, V, N, N0, custom_donor_pool, best_w_pen, verbose=0): """ Traditional matrix solving. Requires making NxN0 matrices. """ #Potentially could be decomposed to not build NxN0 matrix, but the RidgeSolution works fine for that. sc_weights = np.full((N,N0), 0.) weight_log_inc =...
00b9ae93b52453281693660fa6de685cd784127e
7,302
from typing import Callable from typing import Awaitable def generate_on_message( test_client: "DiscordTestClient", broker_id: int ) -> Callable[[discord.Message], Awaitable[None]]: """ Whenever a message comes in, we want our test client to: 1. Filter the message so we are only getting the ones ...
2de510a3195f60056ad13c8fb1b9c71fe480b5ab
7,304
import unittest def test_suite(): """ Construct a TestSuite instance for all test cases. """ suite = unittest.TestSuite() for dt, format, expectation in TEST_CASES: suite.addTest(create_testcase(dt, format, expectation)) return suite
791e6942d213c53a44f433495e13a76abfc1f936
7,305
def calcScipionScore(modes): """Calculate the score from hybrid electron microscopy normal mode analysis (HEMNMA) [CS14]_ as implemented in the Scipion continuousflex plugin [MH20]_. This score prioritises modes as a function of mode number and collectivity order. .. [CS14] Sorzano COS, de la Rosa-Tr...
e1c786bb90d6a7bc0367338f5e5bd6d10ec35366
7,306
def google_base(request): """ view for Google Base Product feed template; returns XML response """ products = Product.active.all() template = get_template("marketing/google_base.xml") xml = template.render(Context(locals())) return HttpResponse(xml, mimetype="text/xml")
a850e4c16f55486c872d0d581a25802d7de3c56e
7,307
def get_agivenn_df(run_list, run_list_sep, **kwargs): """DF of mean amplitudes conditiontioned on differnet n values.""" n_simulate = kwargs.pop('n_simulate') adfam_t = kwargs.pop('adfam_t', None) adaptive = kwargs.pop('adaptive') n_list = kwargs.pop('n_list', [1, 2, 3]) comb_vals, comb_val_res...
fe8fa42a3bc2e78ec1d5c5a7d47151d56789f5a5
7,308
def friendship_request_list_rejected(request, template_name='friendship/friend/requests_list.html'): """ View rejected friendship requests """ # friendship_requests = Friend.objects.rejected_requests(request.user) friendship_requests = FriendshipRequest.objects.filter(rejected__isnull=True) return rend...
2457de6e01bd4fee96d499a481a3c5a2cd0d1782
7,309
def cycle_ctgo(object_type, related_type, related_ids): """ indirect relationships between Cycles and Objects mapped to CycleTask """ if object_type == "Cycle": join_by_source_id = db.session.query(CycleTask.cycle_id) \ .join(Relationship, CycleTask.id == Relationship.source_id) \ .filter( ...
25de449672ef9ced358a53762156f3cbeaabd432
7,310
def Min(axis=-1, keepdims=False): """Returns a layer that applies min along one tensor axis. Args: axis: Axis along which values are grouped for computing minimum. keepdims: If `True`, keep the resulting size 1 axis as a separate tensor axis; else, remove that axis. """ return Fn('Min', lambda ...
09c83217b48f16782530c1954f3e4f0127c06e69
7,311
def sampling(args): """Reparameterization trick by sampling fr an isotropic unit Gaussian. # Arguments args (tensor): mean and log of variance of Q(z|X) # Returns z (tensor): sampled latent vector """ z_mean, z_log_var = args batch = K.shape(z_mean)[0] dim = K.int_shape(z_me...
06e8ca16f1139e12242ee043aa680d5ce7c43c10
7,312
def get_expression_arg_names(expression, strip_dots=True): """ Parse expression and return set of all argument names. For arguments with attribute-like syntax (e.g. materials), if `strip_dots` is True, only base argument names are returned. """ args = ','.join(aux.args for aux in parse_definitio...
6f96395af45b008e5e8b0336c320813a760add49
7,313
from pathlib import Path def ORDER_CTIME(path: Path) -> int: """パスのソート用関数です。作成日時でソートを行います。 """ return path.stat().st_ctime_ns
435571222b26e0c83904305784d6c8868b5bf497
7,314
def format_location(data, year): """ Format any spatial data. Does nothing yet. Parameters ---------- data : pd.DataFrame Data before location formatting. Returns ------- data : pd.DataFrame Data with location formatting. """ # No spatial data yet so does nothing. ...
11d5d7b88f3143b38dc57248937b5e19e22e44c8
7,315
def create_app(service: Service): """Start a small webserver with the Service.""" app = FastAPI() @app.post("/query") def query(params: Params): """The main query endpoint.""" return service.query(**params.query, n_neighbors=params.n_neighbors) return app
3d2f01960d3def11f45bbbbf653511d6f5362881
7,317
def establecer_dominio(func_dist: Expr) -> dict: """Establece el dominio a partir de una FD. Parameters ---------- func_dist Distribución de probabilidad Returns ------- dict Dominio """ equations = func_dist.atoms(Eq) orders = func_dist.atoms(Rel) - equations ...
8ab1b4bc6518cb8baa300bd9f1d38ffff3dfbcf7
7,318
def random_init(n, max_norm): """Computes a random initial configuration of n 2D-vectors such that they all are inside of a circle of radius max_norm Parameters ---------- n : int Number of vectors max_norm : float or int Radius of the circle or maximum possible distance from the ...
5533e43572c47d8c8cd2d6765bb383382987015b
7,319
from typing import Dict from typing import Tuple def calc_cells(serial: int) -> Dict[Tuple[int, int], int]: """Calculate the power for all cells and store them in a dict to retrieve them faster later """ r = {} for i in range(300): for j in range(300): r.update({(i, j): calc_po...
70684827b5c3ef1ec31d419f3012356a9bde1e6c
7,320
from typing import Union import pathlib from typing import List import glob from pathlib import Path def child_files_recursive(root: Union[str, pathlib.Path], ext: str) -> List[str]: """ Get all files with a specific extension nested under a root directory. Parameters ---------- root : pathlib.Pa...
c16288b417d36d6d414c799c78fd59df976ca400
7,322
def ensure_dict(value): """Convert None to empty dict.""" if value is None: return {} return value
191b1a469e66750171648e715501690b2814b8b2
7,323
import random def mutSet(individual): """Mutation that pops or add an element.""" if random.random() < 0.5: if len(individual) > 0: # We cannot pop from an empty set individual.remove(random.choice(sorted(tuple(individual)))) else: individual.add(random.randrange(param.NBR_ITE...
f9919da7f6612e3f317dbe854eda05a71d106632
7,324
def validate_tweet(tweet: str) -> bool: """It validates a tweet. Args: tweet (str): The text to tweet. Raises: ValueError: Raises if tweet length is more than 280 unicode characters. Returns: bool: True if validation holds. """ str_len = ((tweet).join(tweet)).count(twe...
41c7ef1967cba5bb75ea8bce7ffa9b7d636ef80e
7,325
def train_and_eval(model, model_dir, train_input_fn, eval_input_fn, steps_per_epoch, epochs, eval_steps): """Train and evaluate.""" train_dataset = train_input_fn() eval_dataset = eval_input_fn() callbacks = get_callbacks(model, model_dir) history = model.fit( x=train_dataset, ...
54a30f82ab3da4b60534a2775c2217de057ba93c
7,326
import requests import html def open_website(url): """ Open website and return a class ready to work on """ headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36' ' (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' } page = req...
081ed99692ff9763cb19208fdc7f3e7e08e03e8d
7,327