content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def calculate_Hubble_flow_velocity_from_cMpc(cMpc, cosmology="Planck15"): """ Calculates the Hubble flow recession velocity from comoving distance Parameters ---------- cMpc : array-like, shape (N, ) The distance in units of comoving megaparsecs. Must be 1D or scalar. cosmology : strin...
823d94faa682f3b5fb123ad00fe2a7d02eedd355
25,167
import itertools def CollapseDictionary(mapping): """ Takes a dictionary mapping prefixes to URIs and removes prefix mappings that begin with _ and there is already a map to their value >>> from rdflib import URIRef >>> a = {'ex': URIRef('http://example.com/')} >>> a['_1'] = a['ex'] ...
9f2befbd52b75b75aa15cadf9e68d5f9eebcae71
25,168
def do_pre_context(PreContextSmToBeReversedList, PreContextSmIdList, dial_db): """Pre-context detecting state machine (backward). --------------------------------------------------------------------------- Micro actions are: pre-context fullfilled_f DropOut --> Begin of 'main' state machine...
d211cf1aac7e103b6d1efe25bfde964578b81950
25,169
from datetime import datetime async def check_user_cooldown(ctx: Context, config: Config, cooldown: dict): """Check if command is on cooldown.""" command = ctx.command.qualified_name last = cooldown[command]["last"] rate = cooldown[command]["rate"] per = cooldown[command]["per"] uses = coold...
649b108def51c9029b17fa6e14eada141d7c5239
25,170
def round_robin(units, sets=None): """ Generates a schedule of "fair" pairings from a list of units """ if len(units) % 2: units.append(None) count = len(units) sets = sets or (count - 1) half = count / 2 schedule = [] for turn in range(sets): pairings = [] ...
f736fe4ce1f0b407f55d4627a7ecc8396943cdd0
25,171
def filter_df(p_df:pd.DataFrame, col_name:str, value, keep:bool=True, period=None): """ Filter a dataframe based on a specific date Parameters : p_df : pandas.DataFrame The original dataframe col_name : str The dataframe column name where the ...
f866ac1df9c436dc65e6a3d1b7eeb02487bba100
25,172
import logging def _VerifyOptions(options): """Verify the passed-in options. Args: options: The parsed options to verify. Returns: Boolean, True if verification passes, False otherwise. """ if options.endpoints_service and not options.openapi_template: logging.error('Please specify openAPI tem...
872feb5ac314ed2ef28ddbfaeff1b5dafc5e9ed8
25,173
def force_delegate(func: _F) -> _F: """ A decorator to allow delegation for the specified method even if cls.delegate = False """ func._force_delegate = True # type: ignore[attr-defined] return func
771159f2baafce044f480ce138596e4a07e89a97
25,174
import binascii def create_signature(key_dict, data): """ <Purpose> Return a signature dictionary of the form: {'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...', 'sig': '...'}. The signing process will use the private key in key_dict['keyval']['private'] and 'data' to generate the signa...
1a1e37838679a6912c8dc3d482a8092b1e75056c
25,175
def parse_line(line): """ Parse a queue trace line into a dict """ line = line.split() result = {} if len(line) < 12: return result result["event"] = line[0] result["time"] = float(line[1]) result["from"] = int(line[2]) result["to"] = int(line[3]) result["type"] = line[4]...
432e6a624626e89d27fe6d3d9ed7c4230d97c0a6
25,176
from typing import Dict def gaussian_linear_combination(distributions_and_weights: Dict): """ Computes the PDF of the weighted average of two Gaussian variables. """ assert isinstance(distributions_and_weights, dict) assert all( isinstance(dist, MultivariateNormal) for dist in distribution...
704a1f22392819075e3d9ba0c243c7364baab827
25,177
def check_pattern_startswith_slash(pattern): """ Check that the pattern does not begin with a forward slash. """ regex_pattern = pattern.regex.pattern if regex_pattern.startswith('/') or regex_pattern.startswith('^/'): warning = Warning( "Your URL pattern {} has a regex beginning...
9015f1f8d17297ace5fcef2e2cf0fe2c6dd6e76c
25,178
def ht(x): """ht(x) Evaluates the heaviside function Args: x: Domain points Returns: ht(x): Heaviside function evaluated over the domain x """ g = np.ones_like(x) for i in range(np.size(x)-1): if x[i] < 0: g[i] = 0 elif x[i] > 0: g[i] =...
b109a72a6fd57e088327cc1fa1d9d70950b1860a
25,180
def xoGkuXokhXpZ(): """Package link to class.""" pkg = Package("pkg") return pkg.circles.simple_class.Foo
500832ece1987a726812350faf72130de65f37a0
25,181
def create_all_pts_within_observation_window(observation_window_hours) -> str: """ create a view of all patients within observation window return the view name """ view_name = f"default.all_pts_{observation_window_hours}_hours" query = f""" CREATE OR REPLACE VIEW {view_name} AS ...
f711ac343815b9adc3b07e833ae8ee31cd07a125
25,182
def get_signature(data, raw_labels): """ Should return a 4 x z* matrix, where z* is the number of classes in the labels matrix. """ labels = raw_labels.reset_index() pca = decomposition.PCA(n_components=2) lle = manifold.LocallyLinearEmbedding(n_components=2) X_pca = pd.DataFr...
eefd7f5e682ad25bb31989d118747691f4cc64f0
25,183
def get_xyz_where(Z, Cond): """ Z and Cond are MxN matrices. Z are data and Cond is a boolean matrix where some condition is satisfied. Return value is x,y,z where x and y are the indices into Z and z are the values of Z at those indices. x,y,z are 1D arrays """ X,Y = np.indices(Z.shape) ...
b1e1b2144e44f292dc6e2c5e917cb7511bdbf288
25,184
def retrieve_seq_length(data): """compute the length of a sequence. 0 are masked. Args: data: input sequence Returns: a `int`, length of the sequence """ with tf.name_scope('GetLength'): used = tf.sign(tf.reduce_max(tf.abs(data), axis=2)) length = tf.reduce_sum(used, axis=1) length = ...
ba6cb7ac9e9cc63311a6194e55b30ffa02fb3bc7
25,185
def get_census_params(variable_ids, county_level=False): """Gets census url params to make an API call. variable_ids: The ids of the variables to request. Automatically includes NAME. county_level: Whether to request at the county level, or the state level.""" keys = variable_ids.copy() key...
b24204c8e9ef82575b54151bdc0ac98de0fb7fc0
25,186
def lookupName(n, names): """Check if name is in list of names Parameters ---------- n : str Name to check names : list List of names to check in Returns ------- bool Flag denoting if name has been found in list (True) or not (False) """ if n in names:...
0fbb97e252f5daf9de52a946c206fa74395b01c6
25,187
def calculate_appointments(new_set, old_set): """ Calculate different appointment types. Used for making useful distinctions in the email message. new_set will be the fresh set of all available appointments at a given interval old_set will the previous appointments variable getting passed in. ...
b54735293ba910e2b310e55e263e2611863d088a
25,188
def transaksi_hari_ini(): """ used in: app_kasir/statistik.html """ return Transaksi.objects.filter( tanggal_transaksi__year=timezone.now().year, tanggal_transaksi__month=timezone.now().month, tanggal_transaksi__day=timezone.now().day ).count()
a04e835be4cc495b09e1d7ae93ed141315168a81
25,190
def extractWindows(signal, window_size=10, return_window_indices=False): """ Reshape a signal into a series of non-overlapping windows. Parameters ---------- signal : numpy array, shape (num_samples,) window_size : int, optional return_window_indices : bool, optional Returns ------- ...
2d9b319325dc1be9a92766c093db12c2e1f24123
25,191
def add(left: int, right: int): """ add up two numbers. """ print(left + right) return 0
75d7bd10cfdfb38211f6faf838b5e200e8593693
25,192
import random def rand_x_digit_num(x): """Return an X digit number, leading_zeroes returns a string, otherwise int.""" return '{0:0{x}d}'.format(random.randint(0, 10**x-1), x=x)
b46864143ca6186ebeede6c687a85d1b585e70db
25,194
def gen_workflow_steps(step_list): """Generates a table of steps for a workflow Assumes step_list is a list of dictionaries with 'task_id' and 'state' """ steps = format_utils.table_factory(field_names=['Steps', 'State']) if step_list: for step in step_list: steps.add_row([step....
d01dc1937dc17e3d8b30390ccd1ea460391a7492
25,195
from typing import Union from typing import Any def sround(x: Union[np.ndarray, float, list, tuple], digits: int=1) -> Any: """ 'smart' round to largest `digits` + 1 Args x (float, list, tuple, ndarray) digits (int [1]) number of digits beyond highest Examples >>> sround(0.02123...
a695546c46d4bbd41b481d7b58d879bcd4d53247
25,197
def element_png_display(element, max_frames): """ Used to render elements to PNG if requested in the display formats. """ if 'png' not in Store.display_formats: return None info = process_object(element) if info: IPython.display.display(IPython.display.HTML(info)) return ...
273d19194c467d5596f99626bbe01e53005bee17
25,198
def rsa_obj(key_n, key_e, key_d=None, key_p=None, key_q=None): """ Wrapper for the RSAObj constructor The main reason for its existance is to compute the prime factors if the private exponent d is being set. In testing, the construct method threw exceptions because it wasn't able t...
1ad6d0b4c6f96170b2452b87ea049f63df350b8f
25,200
from operator import ge import logging def create_surface_and_gap(surf_data, radius_mode=False, prev_medium=None, wvl=550.0, **kwargs): """ create a surface and gap where surf_data is a list that contains: [curvature, thickness, refractive_index, v-number] """ s = surface.Su...
187cad25433db2f64aeb482bc5313c97b31a834e
25,201
def deprecate_build(id): """Mark a build as deprecated. **Authorization** User must be authenticated and have ``deprecate_build`` permissions. **Example request** .. code-block:: http DELETE /builds/1 HTTP/1.1 Accept: */* Accept-Encoding: gzip, deflate Authorization:...
3002a8c46e4aa27a03d8b4fdb16fa94d4a7a8698
25,202
def subtractNums(x, y): """ subtract two numbers and return result """ return y - x
2b16636e74a2d1a15e79e4669699c96adcd3833b
25,204
def getTraceback(error=None): """Get formatted exception""" try: return traceback.format_exc( 10 ) except Exception, err: return str(error)
62da3e5b13860c2ecefa1da202aa63531c4fbc19
25,205
from datetime import datetime def confirm_email(token): """ Verify email confirmation token and activate the user account.""" # Verify token user_manager = current_app.user_manager db_adapter = user_manager.db_adapter is_valid, has_expired, object_id = user_manager.verify_token( token,...
83015e9fc74b88eeb57b1ef39decd37b7adf662d
25,207
def _GetInstanceField(instance, field): """Get the value of a field of an instance. @type instance: string @param instance: Instance name @type field: string @param field: Name of the field @rtype: string """ return _GetInstanceFields(instance, [field])[0]
fdf8eebf1dbd9cb443da21530058c6c7b30d8204
25,209
def infectious_rate_tweets(t, p0=0.001, r0=0.424, phi0=0.125, taum=2., t0=0, tm=24, bounds=None): """ Alternative form of i...
939ddde24301badaf1c43731027d40167b5ab414
25,210
def fetch_user(username): """ This method 'fetch_user' fetches an instances of an user if any """ return User.objects.get(username=username)
9861fc648c40312dea62450bd152d511867fcfe5
25,211
def get_script_name(key_combo, key): """ (e.g. ctrl-shift, a -> CtrlShiftA, a -> A """ if key_combo != 'key': return get_capitalized_key_combo_pattern(key_combo) + key.capitalize() return key.capitalize()
a550c4b3852bf7ee3c30c4cecd497ae48a4d4a9d
25,212
def layer(name, features): """Make a vector_tile.Tile.Layer from GeoJSON features.""" pbl = vector_tile_pb2.tile.layer() pbl.name = name pbl.version = 1 pb_keys = [] pb_vals = [] pb_features = [] for j, f in enumerate( chain.from_iterable(singles(ob) for ob in features)): ...
a08e4dea809a938e1a451d34673f2845dd353a21
25,213
def serialize(formula, threshold=None): """Provides a string representing the formula. :param formula: The target formula :type formula: FNode :param threshold: Specify the threshold :type formula: Integer :returns: A string representing the formula :rtype: string """ return get_e...
872b4d5e135a6b1b9c5964ca353edccd0a6d8a40
25,214
import collections def find_single_network_cost(region, option, costs, global_parameters, country_parameters, core_lut): """ Calculates the annual total cost using capex and opex. Parameters ---------- region : dict The region being assessed and all associated parameters. option :...
9602d13a85ee5d4273d6bb82d28a525f42714890
25,215
def get_headings(bulletin): """"function to get the headings from text file takes a single argument 1.takes single argument list of bulletin files""" with open("../input/cityofla/CityofLA/Job Bulletins/"+bulletins[bulletin]) as f: ##reading text files data=f.read().r...
4b84928f8f4f13692c1236277aba6c6d4eb6c5ba
25,216
def phi_text_page_parse(pageAnalyse_str, phi_main_url): """ params: pageAnalyse_str, str. return: phi_page_dict, dict. It takes the precedent functions and maps their information to a dictionary. """ # phi_page_dict = {} phi_page_dict["phi_text_id_no"] = phi_text_id(pageAnalyse_str,...
e11a8b14726c2a65fb721f7a1f8c2f4148d18fea
25,217
def fdfilt_lagr(tau, Lf, fs): """ Parameters ---------- tau : delay / s Lf : length of the filter / sample fs : sampling rate / Hz Returns ------- h : (Lf) nonzero filter coefficients ni : time index of the first element of h n0 : time index of the center of h ...
3a80d3682eb255b7190cc5cd6ddf44a9abbd58bc
25,218
import tqdm def hit_n_run(A_mat, b_vec, n_samples=200, hr_timeout=ALG_TIMEOUT_MULT): """ Hit and Run Sampler: 1. Sample current point x 2. Generate a random direction r 3. Define gamma_i = ( b - a_i'x ) / ( r'a_i ) 4. Calculate max(gamma < 0) gamma_i and min(gamma > 0) gamma_i ...
e867c66ec97b9bbb91ad373b93fb9772e2d519cb
25,219
def construct_simulation_hydra_paths(base_config_path: str) -> HydraConfigPaths: """ Specifies relative paths to simulation configs to pass to hydra to declutter tutorial. :param base_config_path: Base config path. :return Hydra config path. """ common_dir = "file://" + join(base_config_path, 'c...
3353f910f9de708bbf0e5d46dc64b1d833230043
25,220
def delete_from_limits_by_id(id, connection, cursor): """ Delete row with a certain ID from limits table :param id: ID to delete :param connection: connection instance :param cursor: cursor instance :return: """ check_for_existence = get_limit_by_id(id, cursor) if check_for_existence...
7e035550c2d9d22be1af48434d0e36cd6424ecb7
25,221
def article_search(request): """Пошук статті і використанням вектору пошуку (за полями заголовку і тексту з ваговими коефіцієнтами 1 та 0.4 відповідно. Пошуковий набір проходить стемінг. При пошуку враховується близькість шуканих слів одне до одного""" query = '' results = [] if 'query' in reque...
423fd3cc4be6cdcef8fd4ab47bc7aa70f52e32bf
25,222
def get_campaign_data(api, campaign_id): """Return campaign metadata for the given campaign ID.""" campaign = dict() # Pulls the campaign data as dict from GoPhish. rawCampaign: dict = api.campaigns.get(campaign_id).as_dict() campaign["id"] = rawCampaign["name"] campaign["start_time"] = rawCa...
6dc344079e73245ef280d770df3b07f62543d856
25,223
def create_small_map(sharing_model): """ Create small map and 2 BS :returns: tuple (map, bs_list) """ map = Map(width=150, height=100) bs1 = Basestation('A', Point(50, 50), get_sharing_for_bs(sharing_model, 0)) bs2 = Basestation('B', Point(100, 50), get_sharing_for_bs(sharing_model, 1)) ...
ecc56eb95f7d2d8188d7caa7353f5bc95793f46e
25,224
def save_dataz(file_name, obj, **kwargs): """Save compressed structured data to files. The arguments will be passed to ``numpy.save()``.""" return np.savez(file_name, obj, **kwargs)
2ea4ecff522409d79fbecd779710a27a9026dbe4
25,225
def step(x): """Heaviside step function.""" step = np.ones_like(x, dtype='float') step[x<0] = 0 step[x==0] = 0.5 return step
2e11c87668b04acef33b7c7499ad10373b33ed76
25,226
def createRaviartThomas0VectorSpace(context, grid, segment=None, putDofsOnBoundaries=False, requireEdgeOnSegment=True, requireElementOnSegment=False): """ Create and return a space of lowest order Raviart...
100242b50f9aac6e55e6e02bb02c07f3b85c4195
25,227
def edus_toks2ids(edu_toks_list, word2ids): """ 将训练cbos的论元句子们转换成ids序列, 将训练cdtb论元关系的论元对转成对应的论元对的tuple ids 列表并返回 """ tok_list_ids = [] for line in edu_toks_list: line_ids = get_line_ids(toks=line, word2ids=word2ids) tok_list_ids.append(line_ids) # 数据存储 return tok_list_ids
b3b87bfb0ae90c78cff3b02e04f316d917834e2b
25,228
def pd_log_with_neg(ser: pd.Series) -> pd.Series: """log transform series with negative values by adding constant""" return np.log(ser + ser.min() + 1)
cf67df4173df27c7b97d320f04cd607c0ee8b866
25,229
def filter_X_dilutions(df, concentration): """Select only one dilution ('high', 'low', or some number).""" assert concentration in ['high','low'] or type(concentration) is int df = df.sort_index(level=['CID','Dilution']) df = df.fillna(999) # Pandas doesn't select correctly on NaNs if concentration...
b886c87c1c5b96e6efc951ef197d3a0fb13707c1
25,230
def update_params(base_param: dict, additional: dict): """overwrite base parameter dictionary Parameters ---------- base_param : dict base param dictionary additional : dict additional param dictionary Returns ------- dict updated parameter dictionary """ ...
e73581cb0b8d264343ead56da52c6dc12fe49dd7
25,231
import torch def lanczos_generalized( operator, metric_operator=None, metric_inv_operator=None, num_eigenthings=10, which="LM", max_steps=20, tol=1e-6, num_lanczos_vectors=None, init_vec=None, use_gpu=False, ): """ Use the scipy.sparse.linalg.eigsh hook to the ARPACK la...
2a3c236817524f2656f9b1631801293b1acf5278
25,232
import urllib import json def get_articles_news(name): """ Function that gets the json response to our url request """ get_news_url = 'https://newsapi.org/v2/top-headlines?sources={}&apiKey=988fb23113204cfcb2cf79eb7ad99b76'.format(name) with urllib.request.urlopen(get_news_url) as url: ge...
3394112b15903671ec5522c128e9035a404f2650
25,233
def coordConv(fromP, fromV, fromSys, fromDate, toSys, toDate, obsData=None, refCo=None): """Converts a position from one coordinate system to another. Inputs: - fromP(3) cartesian position (au) - fromV(3) cartesian velocity (au/year); ignored if fromSys is Geocentr...
29ef79ff896806171a9819fc5ad8bf071bd48969
25,235
def sample_recipe(user, **params): """create recipe""" defaults = { 'title': 'paneer tikka', 'time_minute': 10, 'price': 5.00 } defaults.update(**params) return Recipe.objects.create(user=user, **defaults)
50b53622c68e6385c20296206759bc54f24afa3c
25,236
def briconToScaleOffset(brightness, contrast, drange): """Used by the :func:`briconToDisplayRange` and the :func:`applyBricon` functions. Calculates a scale and offset which can be used to transform a display range of the given size so that the given brightness/contrast settings are applied. :...
b75ce49f4e79f7fef34a855f2897cfa6b4bd7cc7
25,237
def HostNameRequestHeader(payload_size): """ Construct a ``MessageHeader`` for a HostNameRequest command. Sends local host name to virtual circuit peer. This name will affect access rights. Sent over TCP. Parameters ---------- payload_size : integer Length of host name string....
2371dba58d974408be28390462b5e7eb943edd88
25,238
def cinema_trip(persons, day, premium_seating, treat): """ The total cost of going to the cinema Parameters: ---------- persons: int number of people who need a ticket day: int day of the week to book (1 = Monday, 7 = Sunday) preimum_seating: bool ...
8a2c4418124251ae16dddee6c1a134e3b883b1b8
25,240
import pathlib def check_path(path: pathlib.Path) -> bool: """Check path.""" return path.exists() and path.is_file()
2279dde6912ae6f6eb51d90ed5e71e0b3892fea9
25,241
def omega2kwave(omega, depth, grav=9.81): """ Solve the linear dispersion relation close to machine precision:: omega**2 = kwave * grav * tanh(kwave*depth) Parameters ---------- omega : float Wave oscillation frequency [rad/s] depth : float Constant water depth. [m] (<0...
c448780d0edc3eb59ea79b4025182501875bb82f
25,242
def is_true(a: Bool) -> bool: """Returns whether the provided bool can be simplified to true. :param a: :return: """ return z3.is_true(a.raw)
e579a9793700132f38526d5cb737f3540d550821
25,243
from typing import Counter def traverse_caves_recursive(cave: str, cave_system: dict, current_path: list[str]): """Recursively traverse through all paths in the cave.""" if cave != "START": # build the current path traversed current_path = current_path[:] current_path.append(cave) ...
e78680ce8e1c3e7675d8fed980c4c706c87c1758
25,244
def count(A,target): """invoke recursive function to return number of times target appears in A.""" def rcount(lo, hi, target): """Use recursion to find maximum value in A[lo:hi+1].""" if lo == hi: return 1 if A[lo] == target else 0 mid = (lo+hi)//2 left = rcount(lo...
79d9be64d332a11993f65f3c0deba8b4de39ebda
25,246
def asset_get_current_log(asset_id): """ """ db = current.db s3db = current.s3db table = s3db.asset_log query = ( table.asset_id == asset_id ) & \ ( table.cancel == False ) & \ ( table.deleted == False ) # Get the log with the maximum time asset_log = db(query)....
38bbdaade290e0f60a2dd7faa628b2c72dd48a8c
25,247
def _filter_to_k_shot(dataset, num_classes, k): """Filters k-shot subset from a dataset.""" # !!! IMPORTANT: the dataset should *not* be shuffled. !!! # Make sure that `shuffle_buffer_size=1` in the call to # `dloader.get_tf_data`. # Indices of included examples in the k-shot balanced dataset. keep_example...
d61f064dbbdc00b68fffc580baf7e658610e44eb
25,248
def _create_tf_example(entry): """ Creates a tf.train.Example to be saved in the TFRecord file. Args: entry: string containing the path to a image and its label. Return: tf_example: tf.train.Example containing the info stored in feature """ image_path, label = _get_i...
c50c2ff02eccc286319db6263841472d7c2b9fe3
25,249
def _gen_parameters_section(names, parameters, allowed_periods=None): """Generate the "parameters" section of the indicator docstring. Parameters ---------- names : Sequence[str] Names of the input parameters, in order. Usually `Ind._parameters`. parameters : Mapping[str, Any] Parameter...
9bc249ca67dcc1c0f7ff8538b8078bfcd5c231a1
25,250
def bins(df): """Segrega os dados de notas de 10 em 10 pontos para construção de gráficos. Parameters ---------- df : type Pandas DataFrame DataFrame de início. Returns ------- type Pandas DataFrame DataFrame final. """ df_bins = pd.DataFrame(df['ALUNO'].rename('Co...
7c4570866fcb5795dc9052222479e23574fbf64b
25,252
from datetime import datetime def insert_video(ID): """ The function gets a valid YouTube ID, checks for its existence in database, if not found calls YouTube API and inserts into the MongoDB database. """ client = MongoClient('localhost:27017') db = client['PreCog'] collection = db['YoutubeRaw'] check...
9c4f453db72739973384ea1890614463855fcca2
25,254
def get_neighbor_v6_by_search(search=None): """Return a list of NeighborV6's by dict.""" try: objects = NeighborV6.objects.filter() search_dict = search if search else dict() object_map = build_query_to_datatable_v3(objects, search_dict) except FieldError as e: raise api_res...
3ed22479c140b7f71cd02d03be6c0fc82b0e81ca
25,255
import functools def validate_customer(fn): """ Validates that credit cards are between 1 and 5 and that each is 16 chars long """ @functools.wraps(fn) def wrapped(*args, **kwargs): # Validate credit card length cc_list = kwargs.get("credit_cards") trimmed_cc = [remove_non...
ecd5b63ed5f1ae8ecf94a27ba3f353f371dabe39
25,256
from typing import Any from typing import Sequence from typing import Mapping def format_field(value: Any) -> str: """ Function that formats a single field for output on a table or CSV output, in order to deal with nested arrays or objects in the JSON outputs of the API. :param value: the value to for...
5eef5c433924807b195c574c568d0e0a0a433eb7
25,257
def count_honeypot_events(): """ Get total number of honeypot events Returns: JSON/Dict number of honeypot events """ date = fix_date( get_value_from_request("date") ) if date: try: return jsonify( { "count_honeypot_eve...
22a0fd932098ec9e846daaa097c01a9f62763cc6
25,258
def k_i_grid(gridsize, boxsize): """k_i_grid(gridsize, boxlen)""" halfgrid = gridsize // 2 boxsize = egp.utils.boxsize_tuple(boxsize) dk = 2 * np.pi / boxsize kmax = gridsize * dk _ = np.newaxis k1, k2, k3 = dk[:, _, _, _] * np.mgrid[0:gridsize, 0:gridsize, 0:halfgrid + 1] k1 -= kmax[0] ...
29ffb72367672b8dd3f2e0a37923af565fb26306
25,259
def is_bool_type(typ): """ Check if the given type is a bool. """ if hasattr(typ, '__supertype__'): typ = typ.__supertype__ return isinstance(typ, type) and issubclass(typ, bool)
3d8dfae184be330c8cbd7c0e7382311fef31ede5
25,260
def gaussians_entropy(covars, ns=nt.NumpyLinalg): """ Calculates entropy of an array Gaussian distributions :param covar: [N*D*D] covariance matrices :return: total entropy """ N = covar.shape[0] D = covar.shape[-1] return 0.5 * N * D * (1 + log(2*ns.pi)) + 0.5 * ns.sum(ns.det(covar))
fe858d891cb4243b0aaf8b73fc7f38e542c5130d
25,261
def genBetaModel(matshape, cen, betaparam): """ Generate beta model with given parameters inputs ====== matshape: tuple or list Shape of the matrix cen: tuple or list Location of the center pixel betaparam: dict Parameters of the beta function { "A": float, ...
cabe4ff2d217bf918af291ad1fe875a66de2ca2a
25,262
def folders_to_create(search_path, dirs, base_path=""): """ Recursively traverse through folder paths looking for the longest existing subpath. Return the dir info of the longest subpath and the directories that need to be created. """ # Allow user to pass in a string, but use a list in the rec...
91750afa8a4756a09b71cc397a5991b106fd8909
25,263
def profile_line(image, src, dst, linewidth=1, order=1, mode='constant', cval=0.0): """Return the intensity profile of an image measured along a scan line. Parameters ---------- image : numeric array, shape (M, N[, C]) The image, either grayscale (2D array) or multichannel ...
29a020f77448c394d96be3fbd0b382b4657d401e
25,264
def set_out(pin, state): """ Set simple digital (high/low) output :param pin: pun number or logical name :param state: state: 1/0 = True/False :return: verdict """ __digital_out_init(pin).value(state) return {'pin': pin, 'state': state}
c76fb07d52fce9e0c66a6b63b5518b6575589807
25,265
import requests def get_session(): """Define a re-usable Session object""" session = requests.Session() session.auth = auth session.verify = False return session
3539e4a7433ffb58aa726c7fef87af080b011f64
25,266
def create_test_action(context, **kw): """Create and return a test action object. Create a action in the DB and return a Action object with appropriate attributes. """ action = get_test_action(context, **kw) action.create() return action
8093d8f9b73ad0871ee422e2ba977f34907a3ae1
25,268
def parse(header_array, is_paper=False): """ Decides which version of the headers to use.""" if not is_paper: version = clean_entry(header_array[2]) if old_eheaders_re.match(version): headers_list = old_eheaders elif new_eheaders_re.match(version): ...
91f692b20300f96fac5d67e40950f7af17552ecb
25,269
import json def lookup_plex_media(hass, content_type, content_id): """Look up Plex media for other integrations using media_player.play_media service payloads.""" content = json.loads(content_id) if isinstance(content, int): content = {"plex_key": content} content_type = DOMAIN plex_...
060b5cded7bbb8d149a7bf2b94d5a5352114d671
25,271
def dsym_test(func): """Decorate the item as a dsym test.""" if isinstance(func, type) and issubclass(func, unittest2.TestCase): raise Exception("@dsym_test can only be used to decorate a test method") @wraps(func) def wrapper(self, *args, **kwargs): try: if lldb.dont_do_dsym...
d31c5bd87311b2582b9668fb25c1d4648663d1b8
25,273
from datetime import datetime def count_meetings(signups=None, left: datetime=None, right: datetime=None) -> int: """ Returns the number of meetings the user has been to, between two date ranges. Left bound is chosen as an arbitrary date guaranteed to be after any 8th periods from the past year, but befor...
8cb5290111db947b3daa01248452cfd36c80ec46
25,274
def fake_surroundings(len_poem, size_surroundings=5): """ Retourne une liste d'indices tirée au sort :param len_poem: nombre de vers dans le poème :param size_surroundings: distance du vers de référence du vers (default 5) :return: liste """ # bornes inférieures lower_bounds_w_neg = np.a...
91bbdefedd3ed2aa4d63db1ef7281129adb20036
25,275
import numpy def interpolate_missing(sparse_list): """Use linear interpolation to estimate values for missing samples.""" dense_list = list(sparse_list) x_vals, y_vals, x_blanks = [], [], [] for x, y in enumerate(sparse_list): if y is not None: x_vals.append(x) y_vals.a...
a2983a08f00b4de2921c93cc14d3518bc8bd393d
25,276
def classifier_uncertainty(classifier: BaseEstimator, X: modALinput, **predict_proba_kwargs) -> np.ndarray: """ Classification uncertainty of the classifier for the provided samples. Args: classifier: The classifier for which the uncertainty is to be measured. X: The samples for which the u...
419da65825fff7de53ab30f4be31f2be0cf4bbbd
25,278
def test_preserve_scalars(): """ test the preserve_scalars decorator """ class Test(): @misc.preserve_scalars def meth(self, arr): return arr + 1 t = Test() assert t.meth(1) == 2 np.testing.assert_equal(t.meth(np.ones(2)), np.full(2, 2))
ae48d49e5dd6781a304f75abd9b43e67faa09ee1
25,280
def from_string(zma_str, one_indexed=True, angstrom=True, degree=True): """ read a z-matrix from a string """ syms, key_mat, name_mat, val_dct = ar.zmatrix.read(zma_str) val_mat = tuple(tuple(val_dct[name] if name is not None else None for name in name_mat_row) ...
cf3817268cab7e79bf924f9d52cb70d01188ea48
25,281
def get_jmp_addr(bb): """ @param bb List of PseudoInstructions of one basic block @return Address of jump instruction in this basic block """ for inst in bb: if inst.inst_type == 'jmp_T': return inst.addr return None
13e69032bc7d6ed5413b5efbb42729e11661eab1
25,283
import sqlite3 def open_db_conn(db_file=r'/home/openwpm/Desktop/crawl-data.sqlite'): """" open connection to sqlite database """ try: conn = sqlite3.connect(db_file) return conn except Exception as e: print(e) return None
28338f3ff3679c83a1e9040aa9b6e4f5026e4606
25,285
def totals_per_time_frame(data_points, time_frame): """For a set of data points from a single CSV file, calculate the average percent restransmissions per time frame Args: data_points (List[List[int,int,float]]): A list of data points. Each data...
9e71ac2fe7deabd36d7df8ae099575b191260c5d
25,286