content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def removal_dispatcher(template, in_iterables, removal_iterables): """First iterates through the list of iterables 'removal_iterables'. Stores each output from these iterables for later. Then iterates through the list 'in_iterables', removing any output which is present in the output of 'removal_iterabl...
bb7b5f9d61af262f92c92be077d2101cfafefec1
67,135
import typing from typing import Union from typing import Dict from typing import Any def List( attributes: dict = {}, children: list = [], class_: str = None, color: str = None, dark: bool = None, dense: bool = None, disabled: bool = None, elevation: typing.Union[float, str] = None, ...
1e6899897c1b75229dfbd1641f445d2663b232b2
67,137
from datetime import datetime def dict_more_modules_log_by_filter( shop_id: int, module_ids: list, operator_ids: list, from_date: datetime, end_date: datetime, ): """ 查询多种模块的操作记录 :param shop_id: :param module_ids: :param operator_ids: :param from_date: :param end_date: ...
2c5fa6d263b2073bee0d8f6efcc3bd12d41767ab
67,138
from zenmapCore_Kvasir.ScriptMetadata import get_script_entries def script_metadata(): """ Load nmap script metadata into a dictionary """ try: except ImportError, e: return dict(error="Cannot load zenmap python library: %s" % (e)) scr_mdata = get_script_entries(settings.nmap_scriptdi...
01d6cde1257c991647bba2586a10bd357b5646b5
67,140
def set_new_bounds(new_bounds_file): """ Takes in a RD and BAF file. Returns: upper_bounds, lower_bounds """ upper_bounds = [] lower_bounds = [] #load in file cols=(1,2,5,6) X=np.loadtxt(new_bounds_file, usecols=cols) goodRows = np.logical_and(X[:,2] != -1, X[:,3] != -1) #Create weighted histogram of poi...
b6a0ab83d567f4a7d7af1c845d477425cbb1e416
67,142
import collections def eval_metrics(X, y, mapping, clf, metrics, kfolds=5): """ Compute metrics. """ kf = KFold(n_splits=kfolds, shuffle=True) output = collections.defaultdict(list) y_dist = compute_y_dist(y) for train_index, test_index in kf.split(X): X_train, X_test = X[train_ind...
9ab9dbcdafca3689ebd9052fded5ba6cf3a8fb27
67,143
from datetime import datetime import random def create_processed_items(n_items=10): """Generates fake processed items.""" now = datetime.now() td = timedelta(minutes=3) return [{ 'time_of_quake': convert_to_datetime((now - td * i).isoformat()), 'url': f'https://www.eqx.com/{i + 1:03d}....
74f841992c03032c4006f3bc324fc046fbc60224
67,144
def create_channel_event( project_id: str, location: str, channel_id: str, event_id: str ) -> str: """Creates a channel event. Args: project_id: The GCP project ID. location: The location of the channel. channel_id: The user-defined channel ID. event_id: The user-defined even...
f14104d0eb67994f1c12b8fc109c87fbb37912b5
67,145
def MaslUrl(target_url: str, mask_domain: str, keyword: str) -> str: """ Function mask the url with given domain and keyword """ url = Shortner(target_url) return f"{mask_domain}-{keyword}@{urlparse(url).netloc + urlparse(url).path}"
d2ed005f7bc352e84482c0fee1ab2954caf4438b
67,146
import smtplib import getpass def setup(): """Email Setup""" server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.ehlo() server.login(CZAR_USERNAME, getpass("Enter password for {0}:".format(CZAR_EMAIL))) return server
384a686cbe614ef19530eb4396b830c576b8b96c
67,147
def db_get_streamer_nickname(channel: str) -> str: """Returns channel nickname, if not found it returns the channel's name """ cursor.execute( "SELECT nickname FROM nicknames " "WHERE channel=?", (channel.lower(),) ) data = cursor.fetchall() if not data: nickname ...
85b75c799dce36086e34fd1eecd9c3ffa2961295
67,149
def patch_byte(*args): """patch_byte(ea_t ea, ulong x) -> bool""" return _idaapi.patch_byte(*args)
3cc0a0cee71ee5cc613fb4fc66c4758b22ee97d4
67,150
def delete(id): """ This function deletes an existing review :param id: id of review to delete :return: 200 on successful delete, 404 otherwise """ response = Response.query.filter_by(id=id).one_or_none() if response is not None: db.session.delete(response) db.session.co...
3b3e5a9686ea779125d81e04f66186b8d2f1ade6
67,151
def test_aggregate_gets_records_states(configured_test_manager): """Inside the aggregate, we should be able to get values from the states of the manually passed in records.""" @aggregate(["output"]) def small_aggregate(record, records): total = 0 for r in records: total += r.sta...
81e91e38a1eeb751f31fab5388514832def094d0
67,152
def _transition_up(skip_connection, block_to_upsample, filters_to_keep): """Performs upsampling on block_to_upsample by a factor 2 and concatenates it with skip_connection.""" layer = layers.Conv2DTranspose(filters_to_keep, kernel_size=3, ...
51db327fa0b7f2232de8731102f281af251bbc02
67,153
import itertools def get_words(docs, selections): """ Gets the selected words in the provided documents. :param docs: the document to analyze :param selections: the words selected in the documents :return: a dictionary with the documents and for each a list of the selected words """ i...
2c0396ac8de4eae19113e46c51a7e07ff9d4d85f
67,155
from bs4 import BeautifulSoup import urllib def get_paper_detail_from_paperlist_page(paper_list_url): """ get the all papers' session name, title and abs link from paper list url :param paper_list_url: :return: """ r = Request(paper_list_url, headers={'User-Agent': 'Mozilla/5.0'}) content ...
44e33a2f7e82e88738415d3ca852e84c31d82d89
67,157
def Vec3_nrow(): """Vec3_nrow() -> int""" return _simbody.Vec3_nrow()
713f0a7b9dc26efb2113cf74b63fb06a56f52ea9
67,158
def unquote(text, exceptions=''): """Unquote a text but ignore the exceptions. >>> unquote('foo%23bar') 'foo#bar' >>> unquote('foo%23bar', ['#']) 'foo%23bar' """ if not text: if text is None: raise TypeError('None object cannot be unquoted') else: retu...
f149fb57be05d2768c7be692e5838a71a061f702
67,159
def generate_ns_record_parameters(**kwargs): """Generates parameters for 'NS' records.""" return generate_dns_record_parameters(record_type='NS', validate_record_as='domain-name', **kwargs)
0f67369473042c15c657c3d8d324c2568e5a100f
67,161
from typing import Tuple def distance_nb_moves(pos_1: Tuple[int, int], pos_2: Tuple[int, int]): """ :param pos_1: :param pos_2: :return: The number of moves to move from pos_1 to pos_2 """ # We calculate the number of moves to do in diagonal x_init, y_init = pos_1 x_final, y_final = po...
949ff9994eecfaf4b0285318f9a2373d935b6ab0
67,162
def try_get_uuid(value): """ gets the uuid object of given value. it returns None if value is not a valid uuid string. :param str value: value to get uuid instance from it. :rtype: uuid.UUID """ try: return get_uuid(value) except Exception: return None
0953891bd76c4406c78c3f24f430bcaf832ea01a
67,163
from typing import Optional def luhn(base: str, num_only: Optional[bool] = False, allow_lower_case: Optional[bool] = False) -> int: """Return the Luhn check digit for the given string. Args: base(str): string for which to calculate the check digit num_only(bool): allow only digits in...
5d78e57d42b7406838e89bffde6a2d249b9a80a5
67,164
def useful_person_for_subjects( person_main_topics: list, scopus_topics: list, k_relevant: int = 1) -> bool: """ Get possibility status use person for subject Args: person_main_topics: scopus_topics: topics list in ScopusScienceTopicSearch class format k_relev...
df567a755dc6a5f4df57ed3654f407fb27655cd5
67,165
from typing import Any def text_one_of(x: str) -> Parser: """Parses any of the characters in `x`.""" @parser def g(c: Cursor, a: Any): options = [literal(ch.encode(c.encoding)) for ch in x] return choice(*options)(c, a) return g
9ac4d35df1b35425dc241a370e8cbd3eb4311886
67,167
def collapsed_velocities_from_ring_vortices( points, back_right_vortex_vertices, front_right_vortex_vertices, front_left_vortex_vertices, back_left_vortex_vertices, strengths, ages=None, nu=0.0, ): """This function takes in a group of points, and the attributes of a group of ring...
9af4ffaf1dc26b8a3e1dcc1b8cceb353ba0071ca
67,169
from typing import Match def _get_match(): """Function used to return a Match instance.""" return Match(in_port=80, dl_src='01:02:03:04:05:06', dl_dst='01:02:03:04:05:06', dl_vlan=1, dl_vlan_pcp=1, dl_type=1, nw_tos=1, nw_proto=1, nw_src='192...
c6bd5f3f60c552373b88be918186697a42d4e10d
67,170
def NumIsolatedLoads(): """(read-only) Number of isolated loads""" return lib.Topology_Get_NumIsolatedLoads()
cbcc2fc1735afbbcaf11283a4af7bf21fd2f007e
67,171
import re def get_ver(): """format check""" with open("./fitgrid/__init__.py", "r") as stream: fg_ver = re.search( r".*__version__.*=.*[\"\'](?P<ver_str>\d+\.\d+\.\d+\S*)[\'\"].*", stream.read(), ) if fg_ver is None: msg = """ fitgrid.__init__.py m...
70d6e7c1938751cf260d666c7bfab10fe1356cd0
67,172
def update_event(name): """updates the time for a single event identified by the name passed in via the URL path """ global apiInstance return apiInstance.update_event(name,request.args.get('weekdayTime'),request.args.get('weekendTime'))
3df1e8848f639347aeb1429a9664ad2548ce6815
67,173
def set_user_settings(): """ Gets the user's name and email address so the recommendations could be sent """ if APP_ENV == "development": USER_NAME = input("Please enter your name: ") RECIEVE_ADDRESS = input("Please enter your email address: ") else: USER_NAME = NAME ...
21cdddb9beb2641fb3d0189cd47ce42e66f8f8c7
67,174
import unicodedata import string def normalize(word): """ Remove special characters """ return "".join(c for c in unicodedata.normalize('NFKD', word) if c in string.ascii_letters).lower()
a9e9df9163a1e1869b24f46dd781851e522f8313
67,175
def get_hpa(gasprice, hashpower): """gets the hash power accpeting the gas price over last 200 blocks""" hpa = hashpower.loc[gasprice >= hashpower.index, 'hashp_pct'] if gasprice > hashpower.index.max(): hpa = 100 elif gasprice < hashpower.index.min(): hpa = 0 else: hpa = hpa...
aef3195b11ea411af8871f0925dc115aa52b7d4e
67,176
def format_line_obj(line_obj, ordered_attributes, delimiter): """Formats an object into delimited string If attribute not found, a ':(' will be inserted instead """ return str(delimiter).join((str(line_obj.__dict__.get(attr, ':(')) for attr in ordered_attributes))
be7da1fa6bd080047bdd235d332b72e770dcfa48
67,177
def create_input_dataflow(dataset_type: DatasetType, filename: str, shuffle: bool = False) -> DataFlow: """Create dataflow from a single dataset with a unified output structure: Dict[dataset: str, idx: List[int, int], timestamps: List[float, float], clouds: List[np.ndarray, np.ndarray], transform: np.ndarra...
e5292f98c55fc9c2c499f45d71e693a834ff76a3
67,178
def _write_igas(parameters, verbose): """Write gas zones.""" out = [] if "zones" not in parameters: return out ngtypes = { "initial_gases": 0, "injection_gases": 0, } for key in ngtypes: if key in parameters["zones"]: ngtypes[key] = len(parameters["z...
33416ef778f94c8415ab6935d585a1ae7eb446ca
67,179
import requests from bs4 import BeautifulSoup import re def process_entry(link): """ Retrieve data of single entry. :param link: string for link to entry :return entry_dict: dictionary of data about entry """ entry_dict = {} # Retrieve the article and create a soup ...
ac16920bbb897f23d2116acdff9385df4a96540d
67,180
def status(): """ Retrieve the status of the PRNG :return: True if the PRNG is seeded enough, false otherwise """ return _lib.RAND_status()
f6bf9a0c62d6bd3ea75cece1e14c7f6c13a8e804
67,182
def rcts_cnf_fs( rct_infos, thy_info, run_prefix, save_prefix, hbond_cutoffs=None, nprocs=1): """ set reactant filesystem stuff """ rct_cnf_fs = () for rct_info in rct_infos: mod_thy_info = tinfo.modify_orb_label( thy_info, rct_info) # Build filesys for ini...
f3898e32b2034ffa3391f930172862e93dc7f60e
67,183
import torchvision def resnet50_fasterRCNN(num_classes, pretrained = True): """Faster-RCNN architecture construction, whose backbone is a Resnet50. Keyword arguments: - num_classes: number of classes """ backbone = resnet50_pt(pretrained) backbone.out_channels = 2048 anchor_gener...
fbb238200b497e650bd1ee84862812fecfde9f58
67,184
from typing import Optional import shutil def search_default(tool_name: str) -> Optional[str]: """ 默认搜索 :param tool_name: 要搜索的工具 :return: 搜索成功返回搜索结果,否则None """ result = shutil.which(str.encode("utf-8")) return result
fdd15e55490caeea618c7f4147a987d5ece565c3
67,185
def get_line_number2(value, matrix): """ Function used to get the line number of a value in a array. Parameters ------------- value : 'float' Value of interest. matrix : 'numpy.ndarray' Vector with the value of interest. Returns ------------ Index """ for i, line in enumerate(matrix, 1): ...
ed888704f0a29c903c32d806c1bed0a0f172e68f
67,186
def _b2Vec2Array_frompointer(*args, **kwargs): """_b2Vec2Array_frompointer(b2Vec2 t) -> _b2Vec2Array""" return _Box2D._b2Vec2Array_frompointer(*args, **kwargs)
80a952a6081d2b94a7785f18d39d3b61c2054e67
67,187
def build_fast_index_structures(mapit, csize): """ :param mapit: :param csize: :return: """ # Default: all positions masked (1), all positions not conserved # Set position to 0 (unmask) if the position is conserved consmask = np.ones(csize, dtype=np.bool) for block in mapit: ...
43bc6e99d78e2f38a29aac85f24a32784c813e40
67,188
from typing import Optional def get_category(category: UnitCategoryModel) -> Optional[UnitCollectionModel]: """ Gets the given collection of measurement quantities for the given dimensionality of measurement. """ res = algorithms.find(lambda c: c.unit_type == category, _models) return res
d150490a5da59f9cf31461a8cd7ebc797d9669ac
67,189
def get_username(details, user=None, *args, **kwargs): """Return an username for new user. Return current user username if user was given. """ if user: return {'username': user.username} warn_setting('SOCIAL_AUTH_FORCE_RANDOM_USERNAME', 'get_username') warn_setting('SOCIAL_AUTH_DEFAULT_...
73dd04b83d26f57d39ffffe5fdbda23a0966e9bf
67,190
from typing import Generator def create_circuit(depth: int) -> LearningCircuit: """ Create a circuit which is equivalent to the one introduced in PennyLane's tutorial: https://pennylane.ai/qml/demos/tutorial_variational_classifier.html """ def prepare_state(circuit: LearningCircuit) -> None: ...
28ad2253a48a0328389008cd0d679179f537a857
67,191
import collections def get_families(fonts): """Group fonts into families, separate into hinted and unhinted, select representative.""" family_id_to_fonts = collections.defaultdict(set) families = {} for font in fonts: family_id = noto_font_to_family_id(font) family_id_to_fonts[family_id].add(font) ...
16046b4a7869e194d3a1ac5485e104e687f07d10
67,192
def pyramid(n): """ Write a function that when given a number >= 0, returns an Array of ascending length subarrays. Note: the subarrays should be filled with 1s :param n: :return: """ result = [] if n is None or n == 0: return result for n in range(1, n + 1): re...
0d63f8fdfe5c4263ebe4e6730e67219a353e5a0f
67,193
def _arg1_attr(identifier): """Determine the attribute name for the first argument.""" return TIME_ID if identifier.startswith('t') \ else EVENT_INSTANCE_ID
ff4149a3dde1cdee77b285c52f71de8ffbd7b963
67,194
def double_exp_rv(a=1, b=1, pa=0.5): """ Double exponential distribution, with scale a with probability pa, and -b with probability (1 - pa), possibly time-dependent. Double exponential distribution, with probability distribution - for ``x`` in ``[0, inf)``, ``pdf(x) = pa*exp(-a*x)*a`` ...
47b250948160fb9e10836dff9796b9f2ec7fe0aa
67,195
import math def cross_track_distance(lon1, lat1, lon2, lat2, lon3, lat3, d13): """ Usage ----- Angular cross-track-distance of a point (lon3, lat3) from a great-circle path between (lon1, lat1) and (lon2, lat2) The sign of this distance tells which side of the path the third point is on. Para...
12a8073f0e3619d509caba2687e272b13a7aa190
67,196
def get_application_model(): """ Return active Appliation model. Use settings to override active model. """ try: app_label, model_name = oauth_api_settings.APPLICATION_MODEL.split('.') except ValueError: raise ImproperlyConfigured("APPLICATION_MODEL must be in the form of 'app_label....
310fb9f67fb8ae02f5a15c9bc0f4861e01fd9a53
67,197
def set_advective_derivative(g): """ Set how the stencil for the second derivative will be called. Here g is a string Typically, ad_i u = g(i, u) """ global ad ad = Function(g) return ad
38b501ccd2332f3c54767f8a935f071872d3643d
67,198
from re import M def WrapTbSignal(signal, tb): """Wrap a model signal with a corresponding testbench wrapper.""" if type(signal) is M.BitsSignal: return BitsTestbench(signal, tb) elif type(signal) is M.ListSignal: return ListTestbench(signal, tb) elif type(signal) is M.BundleSignal: ...
effdec5f1aa93a2472e68fe42d6ee6531be0dc2e
67,199
def assert_not_null(attribute, value): # type: (Any, str) -> Any """Asserts that the given object is non-null and returns it. :param attribute: Object to assert on :param value: Field name to display in exception message if null :return: Object if non null :raises: ValueError if object is null ...
ed305a880946a879a501f0d5580f0183bd8d2cfa
67,200
import struct def parse_images(filename): """ Reading images information and converting from bytearray to list of ints with help of python's struct module. """ images = [] imgs_file = open(filename, 'rb') # Get only the size of following data size = struct.unpack(">IIII", imgs_file.rea...
bf17dded918051d52cc807f01aed350d94897077
67,201
from pathlib import Path def read_psw_file(psw_file: Path) -> bytes: """ Attempts to read the password from the given `psw_file`. Raises: `OSError`: If some IO related error occurred during file reading """ if not psw_file.is_file(): raise FileNotFoundError("'{}' does not exist".f...
64b91077ff4e728f1d6ef26b770bf222e3c8f34a
67,202
from typing import Match import re def _convert_all_hexes_to_ints(vbf_string: str) -> str: """ >>> _convert_all_hexes_to_ints('abc 0xff def 0XF') 'abc 255 def 15' """ def hex_match_to_int_str(match: Match) -> str: return str(int(match.group(0), base=16)) return re.sub(r"(?i)0x[0-9-a-...
4b671facb107c8d8ac0d93ad859dcb1b22ddf151
67,203
def create_cwe_text(cwe_string): """Create a text representation of a CWE string along with a verbose translation. For example, "CWE-190->CWE-122" becomes: "CWE-190->CWE-122: Integer Overflow or Wraparound leads to Heap-based Buffer Overflow". """ cwe_defs = load_cwe_definitions() cwe_parts = c...
b310a22f12ee93ee43dda0bf5a89794a92124024
67,205
def projection_error(states, basis): """Calculate the absolute and relative projection errors induced by projecting states to a low dimensional basis, i.e., absolute_error = ||Q - Vr Vr^T Q||_F, relative_error = ||Q - Vr Vr^T Q||_F / ||Q||_F where Q = states and Vr = basis. Note that Vr Vr...
fb99b6a34de928ecb27a889e2926ce6a60feb17e
67,207
import time def create_env(user_token, inherit, timeout=1): """ CreateEnvironmentBlock might fail when we close a login session and then try to re-open one very quickly. Run the method multiple times to work around the async nature of logoffs. """ start = time.time() env = None exc = N...
d6b9bfbcefc8a8a85af4b348618085861885572e
67,208
def with_weight_decay( grads_and_vars: GradsAndVars, weight_decay: float ) -> GradsAndVars: """Add weight decay to gradients as done in pytoch.""" if weight_decay: return [(g + weight_decay * v, v) for g, v in grads_and_vars] return grads_and_vars
e8b173c057b303381d2c2c4377bb2201f6786ad0
67,209
def exponential_mode_response_function(mode, alpha, cutoff, nfilt, filter_order): """Return an exponential filter coefficient for the user-provided *mode*.""" return np.exp(-1.0 * alpha * ((mode - cutoff) / nfilt) ** (2*filter_order))
915e11d3b494454d3fdcf6503342bc1521dcd3dc
67,210
def matmul_cupydense(left, right, scale=1, out=None): """ Perform the operation ``out := scale * (left @ right) + out`` where `left`, `right` and `out` are matrices. `scale` is a complex scalar, defaulting to 1. """ # This may be done more naturally with gemm from cupy.cublas # but...
244a956221054b7fa330100badf8ec5e15e20f8a
67,211
def merge_dicts(x): """A quick function to combine dictionaries. Parameters ---------- x : list or array-like A list of dictionaries to merge. Returns ------- dict The merged dictionary. """ z = x[0].copy() # start with keys and values of x for y in x[1:]: ...
73ce60aa167d6c4dcfce9e80e09c53db1202b86b
67,213
def success_response(data: dict, web): """Успешный ответ""" return web.json_response({'success': True, 'message': '', **data})
000939a3cb832cb0a104788b91db5140c25462b0
67,214
def load_linear_models_from_avro(model_file, feature_file): """ Load linear models from avro files. The models are in photon-ml format. Intercept is moved to the end of the coefficient array. :param model_file: Model avro file, photon-ml format :param feature_file: A file containing all features...
b2d060a16f4353c2e29c091b9bf9836a36194ba8
67,215
import functools def compute_transition_probabilities( states, transit_keys, optim_paras, dense_key_to_dense_covariates ): """Get transition probabilities by dense_key. We calculate transition probabilities for one dense key in this function. Therefore we retrieve probabilities for individuals an...
9b5f0b738228accba9709b94345f2db2d3d68c8b
67,216
def get_bounding_box(pts, img_shape, relax=0.1): """ Computes the bounding box of a set of points with same height and width, based on the size of the larger side :param pts: :param img_shape: :param relax: :return: """ # format is x,y,w,h x, y, w, h = cv2.boundingRect(pts[:, :2]) ...
399ae6c771dd49fe3660971487ad3243b0c57b58
67,218
def tile(image, level, mask, size, margin, mask_level=5): """ Loads a folder of numpy array into a dictionnary. Parameters ---------- image: string or wsi image, image to tile. level: int, level to which apply the analysis. mask_level: int, level to which apply the m...
887ceeb8e5ce9a987d9f674ab80f9d5086b6614b
67,219
def get_entropy(y_predict, y_real): """ Returns entropy of a split y_predict is the split decision, True/Fasle, and y_true can be multi class """ if len(y_predict) != len(y_real): print('They have to be the same length') return None n = len(y_real) s_true, n_true = entropy_of...
d738c498f09fa0c2e1484bdbe6ed44e53ac86bea
67,220
from re import S def factor(f, *gens, **args): """Returns factorization into irreducibles of `f`. """ frac = args.get('frac', False) gens = _analyze_gens(gens) def _factor(f): """Factor a true polynomial expression. """ F = NonStrictPoly(f, *gens, **args) if not F.is_Poly: ...
76058671493744d00453c6ee2ab16b0b30481f12
67,222
def safe_name(arg): """ Make a leaf or container name safe for use in Python. """ #print "safe_name", arg if ENABLE_CAMEL_CASE: l = arg.split('-') if len(l) > 0: arg = "".join([x[0].upper() + x[1:] for x in l if x != '']) l = arg.split('.') if len(l) > 0...
3a4fb99a9a91f978fde938ef3e9de6d03ac652b8
67,223
def mackey_glass(n, a=0.2, b=0.8, c=0.9, d=23, e=10, initial=0.1): """ Mackey-Glass discrete equation. **Args:** * `n` - length of the output data (int) - how many samples will be on output **Kwargs:** Parameters `a`, `b`, `c`, `d`, `e` can be a scalar or a vector. In case o...
c0839027a6150f582492d3cd361018d931f2f4d4
67,224
def get_user_by_id(id: int, db: Session) -> Query: """ get_user_by_id takes the user from database by his id. :param id: id of user to get. :param db: database session. :return: first result of session query or None if the result doesn't contain any row. """ return db.query(models.User).fi...
769b0d3ee38655a4c2a07e36c52b102906f9160e
67,225
def cross_entropy(y_hat, y): """ 交叉熵损失函数 :param y_hat: :param y: :return: """ return -nd.pick(y_hat, y).log()
3fe49e0a3d0e1957fa83df73cbff4e0c78321749
67,226
import socket def lookup_host(ip): """ Attempt to associate IP to DNS name, retain cache """ if ip not in dns: try: result = socket.gethostbyaddr(ip) dns[ip] = result[0] except Exception as e: log.warning( "Failed to determine hostname for '%...
7413e1e9763ec309912b84a1187414036bf54988
67,227
from typing import List def _translate_output_is_valid(translate_outputs: List[str]) -> bool: """ True if there are invalid tokens in out_path, or if no valid outputs were found. """ # At least one output must be non-empty found_valid_output = False bad_tokens = set(C.VOCAB_SYMBOLS) for js...
2616b242f0f50d1b5190bf27f276ca54edf3087b
67,228
def either(*funcs): """Return ``True`` is any of the function evaluate true""" return lambda x: any(f(x) for f in funcs)
32f037748a1fb4cf06e5fdce7c1bad20e8200d61
67,229
def sliding_window_1D(x, windowLen): """ Constructs a 2D array whose rows are the data in a sliding window that advances one time step at a time. Parameters ---------- x : 1D, array-like An ordered collection of objects windowLen : int > 0 The legnth of the sliding window Returns ------- X : 2D array ...
d84882ca7bd68aa215960f120d4826f9e2102441
67,230
import re def findalliter(patter, string): """Function used to return all re.findall objects in string""" m_test = re.findall(r'(\d+)_(.+)', string) m_iter = [m_test] while m_test: m_test = re.findall(r'(\d+)_(.+)', m_test[0][1]) m_iter.append(m_test) return m_iter
eddeb7393a7e883a313b9612a78c0e3d0be0e23f
67,231
def load(cls, *, where=None, create_if_none_callback=None): """ Returns records for a specific class. """ table = db.table(cls.__name__) if where: result = table.search(where(Query())) else: result = table.all() if len(result) > 0: return (cls.fromdict(item) fo...
3cac43813c45e9cac28a2902b7513dfabbd1f608
67,232
def lrelu(alpha=0.01): """Create a leaky rectified linear unit function. This function returns a new function that implements the LReLU with a specified alpha. The returned value can be used as an activation function in network layers. Parameters ---------- alpha: float the slope of the function wh...
d45b9cd88ab3f4d36cdbce3c5880db29793afd7e
67,233
def split(matrix): """ Splits a given matrix into quarters. Input: nxn matrix Output: tuple containing 4 n/2 x n/2 matrices corresponding to a, b, c, d """ row, col = matrix.shape row2, col2 = row//2, col//2 return matrix[:row2, :col2], matrix[:row2, col2:], matrix[row2:, :col2], matrix[row2:, col2:]
6284c4a8ff6747b005971a7a37f0327aa5815a7c
67,235
def my_fitness_functions(l): """ Utility functions of M. Sefrioui and J. Perlaux, "Nash genetic algorithms: examples and applications," Proceedings of the 2000 Congress on Evolutionary Computation. CEC00 (Cat. No.00TH8512), La Jolla, CA, USA, 2000, pp. 509-516 vol.1, doi: 10.1109/CEC.2000.870339. ...
1da2cf3e1298228f77eb7ed4ae4b6ccbb7401d3a
67,238
import re def normalize_tokenize(string): """ Takes a string, normalizes it (makes it lowercase and removes punctuation), and then splits it into a list of words. Note that everything in this function is plain Python without using NLTK (although as noted below, NLTK provides some more sop...
800be8deabbc109f7d9459e5cf2da9fb134557ae
67,239
def solve_tsp_brute_force(g): """ This is the brute-force algorithm to solve the TSP. Args: g: the graph to solve Returns: the list of the optimized walk in the visiting order and the optimal distance """ n = len(g.nodes) all_routes = list(permutations(range(n))) best_di...
b774bba7feb468ef31b0b74b398747a876e35080
67,240
import requests def get(domain_name=None): """Retreives the DNS SOA record for a particular domain. :param domain_name: string, (required) the domain name for which to retrieve the SOA record """ url = 'https://api.cloudns.net/dns/soa-details.json' params = Parameters({'domain-name': dom...
34a0c8a3ab075c9611f63307465d4297dbc26b3b
67,242
from typing import Generator from typing import Tuple from typing import List from typing import Dict def filter_by_point( file_diagnostics: Generator[Tuple[SessionBufferProtocol, List[Diagnostic]], None, None], point: Point ) -> Tuple[Dict[str, List[Diagnostic]], Range]: """XXX: Move this odd function to...
1e119ee37c2a375080eedee0f419c6a6203eead9
67,243
def get_best_fit_plane(pts, weights=None): """ :param pts: :param weights: :return: """ if weights is None: wSum = len(pts) origin = np.sum(pts, 0) origin /= wSum sums = np.zeros((3, 3), np.double) for pt in pts: dp = pt - origin for i in range(3): ...
cfc2fdc48c4a0d201bcb825517cc183cb32593a7
67,244
import warnings from contextlib import suppress import numbers def _score(estimator, X_test, y_test, eras_test, scorer, error_score="raise"): """Compute the score(s) of an estimator on a given test set. Will return a dict of floats if `scorer` is a dict, otherwise a single float is returned. """ i...
c2fd3a2c6f456779d0836930f4edc5a1ae506fdf
67,245
def dagNodeTypes(): """ Return a list of node types presently loaded. """ return DagNode.__subclasses__()
1fdf6741afdbd3a1ca2d3c083260b9b854049a46
67,247
import torch def replace_masked_values(tensor: torch.Tensor, mask: torch.Tensor, replace_with: float) -> torch.Tensor: """ Replaces all masked values in ``tensor`` with ``replace_with``. ``mask`` must be broadcastable to the same shape as ``tensor``. We require that ``tensor.dim() == mask.dim()``, as oth...
04370638cf533c67273df57e597d2506dfd457a5
67,248
from pathlib import Path def show_normalized_pyramid( path: Path = Depends(imagepath_parameter) ): """ Get image normalized pyramid """ original = path.get_original() check_representation_existence(original) return PyramidInfo.from_pyramid(original.normalized_pyramid)
548c45348e14adda04afa9e0e6b37b705f764575
67,250
import warnings def remove_small_structures(calibration, binary): """ Cleans up the image by removing structures smaller than the configured size. :param calibration: :param binary: :return: >>> remove_small_structures(0.1, np.array([[ False, False, False], ... ...
79bc3e0ed25c2198629f0837d1b890c970bce7f4
67,251
def _IsDisallowedPropertiesError(error): """Checks if an error is due to properties that were not in the schema. Args: error: A ValidationError Returns: Whether the error was due to disallowed properties """ prop_validator = 'additionalProperties' prop_message = 'Additional properties are not allo...
2042806486e861cf97d0e2ec168a167610749ebd
67,252
def html_tag_checker(html_file): """ This function open and read the html file then checks for a tag validity :param html_file: :return: """ html_file = open(html_file, 'r') html_document = html_file.read() tags = tag_search(html_document) # calling the tag searcher function tag_a...
b9d1085a3fd08700838ee62929c05b19e60a6851
67,253
def simple_integrate(ts, peak_list, base_ts=None, intname='simple'): """ Integrate each peak naively; without regard to overlap. This is used as the terminal step by most of the other integrators. """ peaks = [] for hints in peak_list: t0, t1 = hints['t0'], hints['t1'] hints['in...
c1ce0259bc75894ce02653b8a6a60252a77c32ca
67,254
def CSourceToInput(source: str) -> str: """Create a bytecode for the given C source string. This is a convenience method for generating test inputs. If this method fails, it is because clang is broken. """ bytecode = CSourceToBytecode(source) return bytecode
1bcfefce22bca1d30fa69955d539fd22dff7c5f2
67,255