content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import ctypes def sphrec(r, colat, lon): """ Convert from spherical coordinates to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sphrec_c.html :param r: Distance of a point from the origin. :type r: float :param colat: Angle of the point from the positive Z...
d633b26cd6776d13b6d0e66a9366676c8b8ac962
21,400
import json def counter_endpoint( event=None, context=None ): """ API endpoint that returns the total number of UFO sightings. An example request might look like: .. sourcecode:: http GET www.x.com/counter HTTP/1.1 Host: example.com Accept: application/json, text/javascript ...
e492253f36736c112dcafc15d0e5c30cf27d5560
21,401
def search_trie(result, trie): """ trie search """ if result.is_null(): return [] # output ret_vals = [] for token_str in result: ret_vals += trie.find(token_str) if result.has_memory(): ret_vals = [ one_string for one_string in ret_vals if resu...
75ad08db7962b47ea6402e866cf4a7a9861037c9
21,402
def get_nb_entry(path_to_notes: str = None, nb_name: str = None, show_index: bool = True) -> str: """Returns the entry of a notebook. This entry is to be used for the link to the notebook from the table of contents and from the navigators. Depending on the value of the...
ec216cae586d2746af80ca88a428c6b907ad5240
21,403
def get_label_encoder(config): """Gets a label encoder given the label type from the config Args: config (ModelConfig): A model configuration Returns: LabelEncoder: The appropriate LabelEncoder object for the given config """ return LABEL_MAP[config.label_type](config)
8c7d6e9058af81c94cde039030fed12c4a65b8e6
21,404
def get_lesson_comment_by_sender_user_id(): """ { "page": "Long", "size": "Long", "sender_user_id": "Long" } """ domain = request.args.to_dict() return lesson_comment_service.get_lesson_comment_by_sender_user_id(domain)
7a20e44af39e2efc5cb83eedd9dfb74124a2777f
21,405
def _inertia_grouping(stf): """Grouping function for class inertia. """ if hasattr(stf[2], 'inertia_constant'): return True else: return False
a7689324ccabf601bf8beaec4c1826e8df25880b
21,406
def parse_input(raw_input: str) -> nx.DiGraph: """Parses Day 12 puzzle input.""" graph = nx.DiGraph() graph.add_nodes_from([START, END]) for line in raw_input.strip().splitlines(): edge = line.split('-') for candidate in [edge, list(reversed(edge))]: if candidate[0] == END: ...
1c38124fed386829d712041074cc76c891981498
21,407
def zonal_mode_extract(infield, mode_keep, low_pass = False): """ Subfunction to extract or swipe out zonal modes (mode_keep) of (y, x) data. Assumes here that the data is periodic in axis = 1 (in the x-direction) with the end point missing If mode_keep = 0 then this is just the zonal averaged field I...
a73015ac000668d11dd97ef0c8f435181fb0b9f7
21,408
import pickle def clone(): """Clone model PUT /models Parameters: { "model_name": <model_name_to_clone>, "new_model_name": <name_for_new_model> } Returns: - {"model_names": <list_of_model_names_in_session>} """ request_json = request.get_json() name = request...
49aaf81371f197858e4347efdfa04136e3342dc7
21,409
def GetFlagFromDest(dest): """Returns a conventional flag name given a dest name.""" return '--' + dest.replace('_', '-')
021ab8bca05afbb2325d865a299a2af7c3b939c9
21,410
def get_rst_export_elements( file_environment, environment, module_name, module_path_name, skip_data_value=False, skip_attribute_value=False, rst_elements=None ): """Return :term:`reStructuredText` from exported elements within *file_environment*. *environment* is the full :term:`Javascript` enviro...
4b3a055e47b7c859216b26ec50bf21bcec3af076
21,411
def ganache_url(host='127.0.0.1', port='7445'): """Return URL for Ganache test server.""" return f"http://{host}:{port}"
9de6e2c26c0e1235a14c8dd28040fcdfb8a36a7f
21,412
def to_news_detail_list_by_period(uni_id_list: list, start: str, end: str) -> list: """ 根据统一社会信用代码列表,获取企业在给定日期范围的新闻详情列表,使用串行 :param end: :param start: :param uni_id_list: :return: """ detail_list = [] for uni_id in ...
27493cc0f50a443cea69be74cd2bb1c494e1687f
21,413
from typing import List def positions_to_df(positions: List[alp_api.entity.Asset]) -> pd.DataFrame: """Generate a df from alpaca api assests Parameters ---------- positions : List[alp_api.entity.Asset] List of alpaca trade assets Returns ------- pd.DataFrame Processed dat...
5f77f4862f0244ba66e3d99e8a34e2dd8a56d91d
21,414
import requests from bs4 import BeautifulSoup def get_all_pages(date): """For the specific date, get all page URLs.""" r = requests.get(URL, params={"search": date}) soup = BeautifulSoup(r.text, "html.parser") return [ f"https://www.courts.phila.gov/{url}" for url in set([a["href"] fo...
f74e2167498fa8eb95e81c07c49a79b690adfcb2
21,415
from typing import List def boundary_condition( outer_bc_geometry: List[float], inner_bc_geometry: List[float], bc_num: List[int], T_end: float, ): """ Generate BC points for outer and inner boundaries """ x_l, x_r, y_d, y_u = outer_bc_geometry xc_l, xc_r, yc_d, yc_u = inner_bc_geo...
5941e213a7c48e39b79969d70b9a53a52207272f
21,416
def extractInfiniteNovelTranslations(item): """ # Infinite Novel Translations """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None tagmap = [ ('Ascendance of a Bookworm', 'Ascend...
0b31fcb764840242869eb3aa224b5f04d28beff8
21,417
def fill_diagonal(matrix, value, k=0, unpadded_dim=None): """ Returns a matrix identical to `matrix` except that the `k'th` diagonal has been overwritten with the value `value`. Args: matrix: Matrix whose diagonal to fill. value: The value to fill the diagonal with. k: The diagonal to fill. unpa...
d3dddf35b70788d832b6df119de8ba2760bb7fa7
21,418
def loop_filter(data, images, features, matches, pairs): """ if there’s an edge between (i, j) where i and j are sequence numbers far apart, check that there also exists an edge (i plus/minus k, j plus/minus k), where k is a small integer, and that the loop formed by the four nodes pass the multiplying-...
27a15edb5cae636ce6df3f64517cb6089e2a34f4
21,419
from typing import Optional from typing import Callable import functools def container_model(*, model: type, caption: str, icon: Optional[str]) -> Callable: """ ``container_model`` is an object that keeps together many different properties defined by the plugin and allows developers to build user interfac...
e06ad5ab45f75fcc02550497e290fb8c07193645
21,420
def ward_quick(G, feature, verbose = 0): """ Agglomerative function based on a topology-defining graph and a feature matrix. Parameters ---------- G graph instance, topology-defining graph feature: array of shape (G.V,dim_feature): some vectorial information related to th...
a5c4e847bf6c70acfee1b5d5466b5310d40b528d
21,421
def conv3x3(in_planes, out_planes, stride=1, output_padding=0): """3x3 convolution transpose with padding""" return nn.ConvTranspose2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, output_padding=output_padding, ...
00c9b5123eaf408a1c4432b962739ec519851a59
21,422
def unwrap(func): """ Returns the object wrapped by decorators. """ def _is_wrapped(f): return hasattr(f, '__wrapped__') unwrapped_f = func while (_is_wrapped(unwrapped_f)): unwrapped_f = unwrapped_f.__wrapped__ return unwrapped_f
17aa0c8cc91578fd1187784ad0396ed91c5ec9b8
21,423
def get_payload_from_scopes(scopes): """ Get a dict to be used in JWT payload. Just merge this dict with the JWT payload. :type roles list[rest_jwt_permission.scopes.Scope] :return dictionary to be merged with the JWT payload :rtype dict """ return { get_setting("JWT_PAYLOAD_SCO...
d2192d2eef5cf6e5cc28d2125bef94c438075884
21,424
from typing import Dict def missing_keys_4(data: Dict, lprint=print, eprint=print): """ Add keys: _max_eval_all_epoch, _max_seen_train, _max_seen_eval, _finished_experiment """ if "_finished_experiment" not in data: lprint(f"Add keys _finished_experiment ...") max_eval = -1 for k1, v...
ad8d3f7c19dd4eefa0db465dd52b5e8dc8f0bd1e
21,425
def translate(txt): """Takes a plain czech text as an input and returns its phonetic transcription.""" txt = txt.lower() txt = simple_replacement(txt) txt = regex_replacement(txt) txt = chain_replacement(txt) txt = grind(txt) return txt
a7f35b7be14dfed0d9a4e68e2e3113d97f2468cb
21,426
def struct_getfield_longlong(ffitype, addr, offset): """ Return the field of type ``ffitype`` at ``addr+offset``, casted to lltype.LongLong. """ value = _struct_getfield(lltype.SignedLongLong, addr, offset) return value
24ff5e6b35de48bccf810bb9b723852f1ab16fb6
21,427
def subscribe(request): """View to subscribe the logged in user to a channel""" if request.method == "POST": channels = set() users = set() for key in request.POST: if key.startswith("youtube-"): channel_id = key[8:] if models.YoutubeChannel.ob...
6ee833eb6536f7958f74f274a776b31fab7051dc
21,428
import subprocess import sys def RunCommand(cmd, print_cmd=True, error_ok=False, error_message=None, exit_code=False, redirect_stdout=False, redirect_stderr=False, cwd=None, input=None, enter_chroot=False, num_retries=0, log_to_file=None, combine_stdout_stderr=False): ""...
16a033fce354f232159aaad51d4ffa1a5cc94e22
21,429
from typing import OrderedDict import json def eval_accuracies(hypotheses, references, sources=None, filename=None, mode='dev'): """An unofficial evalutation helper. Arguments: hypotheses: A mapping from instance id to predicted sequences. references: A mapping from instance id to ground trut...
ede152bb51fcb53574eec0dfb84b6ca971289d5d
21,430
from datetime import datetime def perform_login(db: Session, user: FidesopsUser) -> ClientDetail: """Performs a login by updating the FidesopsUser instance and creating and returning an associated ClientDetail.""" client: ClientDetail = user.client if not client: logger.info("Creating client ...
013875ba1ca30615690d8d477e1246174bdc6279
21,431
import time import os import shutil import subprocess def check(e, compiler_params, cmd=None, time_error=False, nerror=-1, nground=-1, nsamples=0, precompute_samples=None, print_command=False, log_rho=False, do_copy=True, extra_args='', do_run=True, do_compile=True, get_command=False, skip_save=False, ndims=-1, our_i...
56c80ab7bbdd10e1bb3c16ffba62a940a07fb0eb
21,432
def _bytestring_to_textstring(bytestring: str, number_of_registers: int = 16) -> str: """Convert a bytestring to a text string. Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits). For example 16 consecutive registers can hold 32 characters (32 bytes). Not much of con...
474ac26b8fb3e454ce2747300c42b86df988ecc8
21,433
import numpy def sigma_XH(elem,Teff=4500.,M_H=0.,SNR=100.,dr=None): """ NAME: sigma_XH PURPOSE: return uncertainty in a given element at specified effective temperature, metallicity and signal to noise ratio (functional form taken from Holtzman et al 2015) INPUT: ele...
186974970505b21cb9978c8afcfbee1a9c0bf17c
21,434
from typing import Callable def lazy_load_command(import_path: str) -> Callable: """Create a lazy loader for command""" _, _, name = import_path.rpartition('.') def command(*args, **kwargs): func = import_string(import_path) return func(*args, **kwargs) command.__name__ = name # typ...
273e482412a079e5a59b84422ee409df7b3a7a1c
21,435
def tlam(func, tup): """Split tuple into arguments """ return func(*tup)
0e3a9b93b36795e6c11631f8c8852aba59724f88
21,436
from typing import Counter def sax_df_reformat(sax_data, sax_dict, meter_data, space_btw_saxseq=3): """"Function to format a SAX timeseries original data for SAX heatmap plotting.""" counts_nb = Counter(sax_dict[meter_data]) # Sort the counter dictionnary per value # source: https://stackoverflow.com...
6e241979d673910da2acfd522d1c32a3f1d815a8
21,437
def filter_not_t(func): """ Transformation for Sequence.filter_not :param func: filter_not function :return: transformation """ return Transformation( "filter_not({0})".format(name(func)), partial(filterfalse, func), {ExecutionStrategies.PARALLEL}, )
af548f7cfa60f5b598ad3527d8eaabca09aed4e6
21,438
def get_task_by_id(id): """Return task by its ID""" return TaskJson.json_by_id(id)
c1b1a4137cdab853e7d6c02167b914367120972a
21,439
def priority(floors, elevator): """Priority for a State.""" priority = 3 - elevator for i, floor in enumerate(floors): priority += (3 - i) * len(floor) return priority
b65abac24fb85f50425f2adfd4d98786b41c9a2d
21,440
from typing import Union from typing import List def get_user_groups(user_id: Union[int, str]) -> List[UserSerializer]: """ 获取指定 User 的全部 Groups Args: user_id: 指定 User 的 {login} 或 {id} Returns: Group 列表, 语雀这里将 Group 均视作 User. """ uri = f'/users/{user_id}/groups' method = ...
de02631693c6b31c566f93ee4cdc96bee3db024a
21,441
def user_news_list(): """ 新闻列表 :return: """ user = g.user page = request.args.get("page") try: page = int(page) except Exception as e: current_app.logger.error(e) page = 1 # 查询 news_list = [] current_page = 1 total_page = 1 try: pagin...
adc202bfdbf2c2e2d7d60c949fdad028a56b63c0
21,442
def unificate_link(link): """Process whitespace, make first letter upper.""" link = process_link_whitespace(link) if len(link) < 2: return link.upper() else: return link[0].upper() + link[1:]
4d9a5a4a88141f2a8e6400186c607615470cabde
21,443
def compute_vel_acc( robo, symo, antRj, antPj, forced=False, gravity=True, floating=False ): """Internal function. Computes speeds and accelerations usitn Parameters ========== robo : Robot Instance of robot description container symo : symbolmgr.SymbolManager Instance of symbol...
474729b9329ee21d4bcfffb33916d8d85a21ea62
21,444
def _sample_n_k(n, k): """Sample k distinct elements uniformly from range(n)""" if not 0 <= k <= n: raise ValueError("Sample larger than population or is negative") if 3 * k >= n: return np.random.choice(n, k, replace=False) else: result = np.random.choice(n, 2 * k) sele...
3aad3ed36590655ef079a4d39745d6c59ec499a8
21,445
def _all_usage_keys(descriptors, aside_types): """ Return a set of all usage_ids for the `descriptors` and for as all asides in `aside_types` for those descriptors. """ usage_ids = set() for descriptor in descriptors: usage_ids.add(descriptor.scope_ids.usage_id) for aside_type i...
75652e9468e6a61763b407bf11d644b1d08dd38c
21,446
def svn_client_invoke_get_commit_log2(*args): """svn_client_invoke_get_commit_log2(svn_client_get_commit_log2_t _obj, apr_array_header_t commit_items, void * baton, apr_pool_t pool) -> svn_error_t""" return _client.svn_client_invoke_get_commit_log2(*args)
fe7652c7e1573c3d688ddde40630b9b24e5bb48c
21,447
def round_extent(extent, cellsize): """Increases the extent until all sides lie on a coordinate divisible by cellsize.""" xmin, ymin, xmax, ymax = extent xmin = np.floor(xmin / cellsize) * cellsize ymin = np.floor(ymin / cellsize) * cellsize xmax = np.ceil(xmax / cellsize) * cellsize ymax = ...
384cf262f5dd206b0755623ce6d859e4f82efa86
21,448
def add_numbers(): """Add two numbers server side, ridiculous but well...""" #a = request.args.get('a', 0, type=str)#input from html a = request.args.get('a') print(a) result = chatbot.main(a) print("Result: ", result) #input from html returned=a #return jsonify(returned); retur...
d0e670ea0fc7bff33d5419316f5ebddf12cecea0
21,449
import re def _parse_stack_info(line, re_obj, crash_obj, line_num): """ :param line: line string :param re_obj: re compiled object :param crash_obj: CrashInfo object :return: crash_obj, re_obj, complete:Bool """ if re_obj is None: re_obj = re.compile(_match_stack_item_re()) com...
b360ef9c6d96092f59952fec90fdc41b2463c780
21,450
import math def Orbiter(pos,POS,veloc,MASS,mass): """ Find the new position and velocity of an Orbiter Parameters ---------- pos : list Position vector of the orbiter. POS : list Position vector of the centre object. veloc : list Velocity of the orbiter. MASS :...
8d6c08fc1a7fa1165550e13944c1dbda414e6e62
21,451
def build_heading(win, readonly=False): """Generate heading text for screen """ if not win.parent().albumdata['artist'] or not win.parent().albumdata['titel']: text = 'Opvoeren nieuw {}'.format(TYPETXT[win.parent().albumtype]) else: wintext = win.heading.text() newtext = '' ...
133f4111171ab0bd04bed82455ced9aa9dcc010b
21,452
def GetTraceValue(): """Return a value to be used for the trace header.""" # Token to be used to route service request traces. trace_token = properties.VALUES.core.trace_token.Get() # Username to which service request traces should be sent. trace_email = properties.VALUES.core.trace_email.Get() # Enable/dis...
67c1fc9d0602ca25c02dd088e1abba1ad951022f
21,453
import six import os import errno def get_file_size(file_obj): """获取文件对象的大小 get_file_size(open('/home/ubuntu-14.04.3-desktop-amd64.iso')) :param file_obj: file-like object. """ if (hasattr(file_obj, 'seek') and hasattr(file_obj, 'tell') and (six.PY2 or six.PY3 and file_obj.seekabl...
3fd9a4ae91fb302237739da319a53f0b8db04c49
21,454
from typing import Optional from typing import Union from typing import Tuple def sql( where: str, parameters: Optional[Parameters] = None ) -> Union[str, Tuple[str, Parameters]]: """ Return a SQL query, usable for querying the TransitMaster database. If provided, parameters are returned duplicated, ...
22ca2194f355deaa4fc55b458c1f1a013ab2902e
21,455
def clip(a, a_min, a_max): """Clips the values of an array to a given interval. Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of ``[0, 1]`` is specified, values smaller than 0 become 0, and values larger than 1 become 1. Args: ...
0394b68329c48198ade9a3131c6c26940f09a154
21,456
def hole_eigenvalue_residual( energy: floatarray, particle: "CoreShellParticle" ) -> float: """This function returns the residual of the hole energy level eigenvalue equation. Used with root-finding methods to calculate the lowest energy state. Parameters ---------- energy : float, eV ...
500033e927c29595c67d2e2327ebe1ae6d39cfd0
21,457
def open_raster(filename): """Take a file path as a string and return a gdal datasource object""" # register all of the GDAL drivers gdal.AllRegister() # open the image img = gdal.Open(filename, GA_ReadOnly) if img is None: print 'Could not open %s' % filename sys.exit(1) el...
b1c002be50b59e74a327943af8613b11cddf9b88
21,458
def reduce2latlon_seasonal( mv, season=seasonsyr, region=None, vid=None, exclude_axes=[], seasons=seasonsyr ): """as reduce2lat_seasonal, but both lat and lon axes are retained. Axis names (ids) may be listed in exclude_axes, to exclude them from the averaging process. """ # backwards compatibility with...
7f101ce4ac5d4382d287901607c455b4d922f847
21,459
def GetFreshAccessTokenIfEnabled(account=None, scopes=None, min_expiry_duration='1h', allow_account_impersonation=True): """Returns a fresh access token of the given account or the active account. Same as GetAccessTo...
7716b44802d84aac1952e936166f3414459cbc4b
21,460
def unicode_to_xes(uni): """Convert unicode characters to our ASCII representation of patterns.""" uni = uni.replace(INVISIBLE_CRAP, '') return ''.join(BOXES[c] for c in uni)
4c6eebcf562804340ef683eec84e28002202d833
21,461
def AvailableSteps(): """(read-only) Number of Steps available in cap bank to be switched ON.""" return lib.Capacitors_Get_AvailableSteps()
210f1316beafcdef266858490411bb9f737cb3de
21,462
import re def modify_list(result, guess, answer): """ Print all the key in dict. Arguments: result -- a list of the show pattern word. guess -- the letter of user's guess. answer -- the answer of word Returns: result -- the list of word after modified. """ guess ...
9384ecd09659c55808a859dd613641ccac46c760
21,463
def f(p, snm, sfs): """ p: proportion of all SNP's on the X chromosome [float, 0<p<1] snm: standard neutral model spectrum (optimally scaled) sfs: observed SFS """ # modify sfs fs = modify(p, sfs) # return sum of squared deviations of modified SFS with snm spectrum: return np.sum( ...
b7d3c8ef188a5126fe7b817c78949fb9feec5b62
21,464
def get_N_intransit(tdur, cadence): """Estimates number of in-transit points for transits in a light curve. Parameters ---------- tdur: float Full transit duration cadence: float Cadence/integration time for light curve Returns ------- n_intransit: int Number of...
d126b5590a8997b8695c1a86360421f2bf4b8357
21,465
def extract_keys(keys, dic, drop=True): """ Extract keys from dictionary and return a dictionary with the extracted values. If key is not included in the dictionary, it will also be absent from the output. """ out = {} for k in keys: try: if drop: ou...
15a66fff5207df18d8ece4959e485068f1bd3c9c
21,466
from flask import current_app def jsonresolver_loader(url_map): """Resolve the referred EItems for a Document record.""" def eitems_resolver(document_pid): """Search and return the EItems that reference this Document.""" eitems = [] eitem_search = current_app_ils.eitem_search_cls() ...
9da05e92850cbdbedb8d49cdf2cdf3763d0b1ab6
21,467
import sqlite3 def getStations(options, type): """Query stations by specific type ('GHCND', 'ASOS', 'COOP', 'USAF-WBAN') """ conn = sqlite3.connect(options.database) c = conn.cursor() if type == "ALL": c.execute("select rowid, id, name, lat, lon from stations") else: c.execute(...
59d45a79542e68cd691cf848f3d4fe250389732c
21,468
def test_name(request): """Returns (module_name, function_name[args]) for a given test""" return ( request.module.__name__, request._parent_request._pyfuncitem.name, # pylint: disable=protected-access )
4ef40de8a2c917c0b12cb83db9fd39f6b59777a0
21,469
import textwrap def inputwrap(x, ARG_indented: bool=False, ARG_end_with: str=" "): """Textwrapping for regular 'input' commands. Parameters ---------- x The text to be wrapped. ARG_indented : bool (default is 'False') Whether or not the textwrapped string should be indented. A...
af0ab3b69205965b40d3e03bdcfe3148889f7080
21,470
from .utils import phys_size def SBP_single(ell_fix, redshift, pixel_scale, zeropoint, ax=None, offset=0.0, x_min=1.0, x_max=4.0, alpha=1, physical_unit=False, show_dots=False, show_grid=False, show_banner=True, vertical_line=None, linecolor='firebrick', linestyle='-', linewidth=3, labelsize=25, ticksi...
5aab69adfc38afad84b6f45972ffb7ce05d547ac
21,471
def min_conflicts_value(csp, var, current): """Return the value that will give var the least number of conflicts. If there is a tie, choose at random.""" return argmin_random_tie(csp.domains[var], key=lambda val: csp.nconflicts(var, val, current))
ab338ce8b0abd7a77078193fcac3041155ed3e78
21,472
from app.model import TokenRepository def init(jwt): """Initialize the JWTManager. Parameters: jwt (JWTManager): an instance of the jwt manager. """ @jwt.token_in_blacklist_loader def check_if_token_in_blacklist(decoded_token): """Callback to check if a token is in the bl...
406ff6e8ce6169dff6559b141f5c4453cce68f1e
21,473
from typing import Callable import inspect def get_component_rst_string(module: ModuleType, component: Callable, level: int) -> str: """Get a rst string, to autogenerate documentation for a component (class or function) :param module: the module containing the component :param component: the component (c...
511c718610456b4c5df5df2bc9e0ae5e7ac6823c
21,474
def log_mse_loss(source, separated, max_snr=1e6, bias_ref_signal=None): """Negative log MSE loss, the negated log of SNR denominator.""" err_pow = tf.math.reduce_sum(tf.math.square(source - separated), axis=-1) snrfactor = 10.**(-max_snr / 10.) if bias_ref_signal is None: ref_pow = tf.math.reduc...
46203582f0d0ec2a98248ec000805c9e43f54091
21,475
from typing import Union def crack(password: str) -> Union[str, None]: """ Crack the given password """ # found 96% by caesar return caesar(password)
058779267c400501eecac2d3e43d691e2152ef8d
21,476
def fetchOne(query): """ Returns a dict result from the fetch of one query row """ return sqliteRowToDict(query.fetchone())
5be4753ea541a6e27ece16fb375c8a0664487a71
21,477
def _get_class_rgb(num_classes, predicted_class): """Map from class to RGB value for a specific colormap. Args: num_classes: Integer, the total number of classes. predicted_class: Integer, the predicted class, in [0, num_classes). Returns: Tuple of 3 floats in [0.0, 1.0] representing an RGB color....
914824eef57a829a7d67e74f45f56088d73ea34e
21,478
from datetime import datetime def PUT(request): """Update a project's name.""" request.check_required_parameters(body={'project': {'name': 'name'}}, path={'projectId': 'string'}) project = Project.from_id(request.params_path['projectId']) project.check_exists() project.check_user_access(request...
ab5cc9bea5f5a933293761a852532f2c7c6004ec
21,479
def load_book_details(file_path): """ Read book details from a csv file into a pandas DataFrame. """ books_df = pd.read_csv(file_path, index_col='book_id') return books_df
9240efd9778198e34464fe6f95d312a82fd3894e
21,480
import random import string def random_string_fx() -> str: """ Creates a 16 digit alphanumeric string. For use with logging tests. Returns: 16 digit alphanumeric string. """ result = "".join(random.sample(string.ascii_letters, 16)) return result
835c2dc2716c6ef0ad37f5ae03cfc9dbe2e16725
21,481
from typing import Dict from typing import List import logging def parse_scheduler_nodes( pbscmd: PBSCMD, resource_definitions: Dict[str, PBSProResourceDefinition] ) -> List[Node]: """ Gets the current state of the nodes as the scheduler sees them, including resources, assigned resources, jobs current...
bceec54b302b0b70e77181d3940fd6e41b8922c4
21,482
def GaugeSet(prefix, *, name, index, **kwargs): """ Factory function for Gauge Set. Parameters ---------- prefix : str Gauge base PV (up to 'GCC'/'GPI'). name : str Name to refer to the gauge set. index : str or int Index for gauge (e.g. '02' or 3). prefix_con...
ef856c77e414d8bc4532483e5b65aa3ebb0cc132
21,483
def user_rating(user, object, category=""): """ Usage: {% user_rating user obj [category] as var %} """ return user_rating_value(user, object, category)
09ac3ea8d1efcc3dc70d82bf5266f3e768a35c3b
21,484
import numpy def weighted_mean( x: NumericOrIter, w: NumericOrIter = None, na_rm: bool = False, ) -> NumericType: """Calculate weighted mean""" if is_scalar(x): x = [x] # type: ignore if w is not None and is_scalar(w): w = [w] # type: ignore x = Array(x) if w is not N...
4034d642629696f1be73c62384bf6633ccb6efe1
21,485
import socket def internet(host="8.8.8.8", port=53, timeout=10): """ Check Internet Connections. :param host: the host that check connection to :param port: port that check connection with :param timeout: times that check the connnection :type host:str :type port:int :type timeout:i...
c0ee11cf7aa9699a077e238d993136aeb4efcead
21,486
def parse_date(td): """helper function to parse time""" resYear = float(td.days)/364.0 # get the number of years including the the numbers after the dot resMonth = int((resYear - int(resYear))*364/30) # get the number of months, by multiply the number after the dot by 364 and divide by 30...
bda78b0968b59c13f763e51f5f15340a377eeb35
21,487
import math def hue_angle(a, b): """ Returns the *hue* angle :math:`h` in degrees. Parameters ---------- a : numeric Opponent colour dimension :math:`a`. b : numeric Opponent colour dimension :math:`b`. Returns ------- numeric *Hue* angle :math:`h` in degr...
2f508be9ed0cdcb0e8b193eefb441a6281a464c7
21,488
def perform_similarity_checks(post, name): """ Performs 4 tests to determine similarity between links in the post and the user name :param post: Test of the post :param name: Username to compare against :return: Float ratio of similarity """ max_similarity, similar_links = 0.0, [] # Kee...
78813c3b2223072a4a5b15a5a71837424a648470
21,489
def create_getters(tuples): """Create a series of itemgetters that return tuples :param tuples: a list of tuples :type tuples: collections.Iterable :returns: a generator of item getters :rtype: generator :: >>> gs = list(create_getters([(0, 2), (), (1,)])) >>> d = ['a', 'b', '...
43d6fed8233ee56b91a52c024c533ae72c8e6890
21,490
def report_cots_cv2x_bsm(bsm: dict) -> str: """A function to report the BSM information contained in an SPDU from a COTS C-V2X device :param bsm: a dictionary containing BSM fields from a C-V2X SPDU :type bsm: dict :return: a string representation of the BSM fields :rtype: str """ report =...
df0aa5ae4b50980088fe69cb0b776abbf0b0998d
21,491
import logging def get_level_matrix(matrix, level): """Returns a binary matrix with positions exceeding a threshold. matrix = numpy array object level = floating number The matrix it returns has 1 in the positions where matrix has values above level and 0 elsewhere.""" logging.info("Selectin...
1516f14970471c4f9402fcbf2cfb2a0d017e754e
21,492
def bookmark(repo, subset, x): """``bookmark([name])`` The named bookmark or all bookmarks. If `name` starts with `re:`, the remainder of the name is treated as a regular expression. To match a bookmark that actually starts with `re:`, use the prefix `literal:`. """ # i18n: "bookmark" is a ...
71fd382ad0710e2e54a80b0b739d04c6d5410719
21,493
def indel_protein_processor(df, refgene, proteincdd=None): """Calculate protein features Features not used in the final model are commented out Args: df (pandas.DataFrame) refgene (str): path to refCodingExon.bed.gz proteincdd (str): optional, path to proteinConservedDomains.t...
721b4b19838ac2d6cd21f471d647c34c3586ebb2
21,494
def perdict_raw(model, *args, **kwargs): """ Tries to call model.predict(*args, **kwargs, prediction_type="RawFormulaVal"). If that fail, calls model.predict(*args, **kwargs) """ try: return model.predict(*args, **kwargs, prediction_type="RawFormulaVal") except TypeError: return ...
2ab7790c0cd48cc9b26f6e7888dd61436cb728b4
21,495
def login_required(arg): """ Decorator to check if a user is logged in""" @wraps(arg) def wrap(*args, **kwargs): """Checking if token exists in the request header""" if request.headers.get('Authorization'): auth_token = request.headers.get('Authorization') token = aut...
2d41e2cd41621a0ce6015182badd7a4117c1daf6
21,496
def calc_manual_numbers(n): """ >>> calc_manual_numbers(1) 20151125 >>> calc_manual_numbers(2) 31916031 >>> calc_manual_numbers(3) 18749137 >>> calc_manual_numbers(21) 33511524 """ return (BASE * pow(FACTOR, n - 1, MOD)) % MOD
d0a276da3eb931afcf6b60b1b6172b468e59b95c
21,497
def accuracy(y0, y1): """ compute accuracy for y1 and y2 does not meter if either of them is in vector or integer form :param y0: list of - labels or vector of probabilities :param y1: list of - labels or vector of probabilities :return: accuracy """ if not isinstance(y0[0], (int, float, np....
b0e1077a8443e3d325b3238355c1a578af8823e3
21,498
import random def random_function(*args): """Picks one of its arguments uniformly at random, calls it, and returns the result. Example usage: >>> random_function(lambda: numpy.uniform(-2, -1), lambda: numpy.uniform(1, 2)) """ choice = random.randint(0, len(args) - 1) return args[choi...
3f8d11becc52fde5752671e3045a9c64ddfeec97
21,499